Skip to content

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

[GPU] MoE optimization (#32469)

Taylor Yeonbok Lee3010f953325d
diff --git a/src/common/transformations/src/transformations/common_optimizations/matmul_experts_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/matmul_experts_fusion.cpp
index 00166e4b78e..3448526540d 100644
--- a/src/common/transformations/src/transformations/common_optimizations/matmul_experts_fusion.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/matmul_experts_fusion.cpp
@@ -75,6 +75,10 @@ ov::pass::FuseVectorizedMOE2GEMM::FuseVectorizedMOE2GEMM() {
matcher_pass_callback callback = [=](pattern::Matcher& m) {
auto& pm = m.get_pattern_value_map();
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+
auto experts_input_node = pm.at(experts_input).get_node()->input_value(0);
auto routing_weights_node = pm.at(unsqueeze_routing_weights).get_node_shared_ptr();
@@ -156,6 +160,11 @@ ov::pass::FuseVectorizedMOE3GEMM::FuseVectorizedMOE3GEMM() {
matcher_pass_callback callback = [=](pattern::Matcher& m) {
auto& pm = m.get_pattern_value_map();
+
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+
auto experts_input_node = pm.at(experts_input).get_node()->input_value(0);
auto routing_weights_node = pm.at(unsqueeze_routing_weights).get_node_shared_ptr();
auto gate_weight = pm.at(gate_matmul).get_node()->input_value(1).get_node_shared_ptr();
diff --git a/src/core/dev_api/openvino/op/moe.hpp b/src/core/dev_api/openvino/op/moe.hpp
index 5147f15fa8b..9d6770a5fbb 100644
--- a/src/core/dev_api/openvino/op/moe.hpp
+++ b/src/core/dev_api/openvino/op/moe.hpp
@@ -21,6 +21,8 @@ public:
MOE() = default;
+ MOE(const OutputVector& args) : Op(args) {}
+
enum class Expert_type { GEMM2_BIAS_SWIGLU_CLAMP, GEMM3_SWIGLU };
struct Config {
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
new file mode 100644
index 00000000000..5e08e3b52f5
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/op/moe_compressed.hpp
@@ -0,0 +1,72 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/op/op.hpp"
+#include "openvino/op/moe.hpp"
+
+namespace ov::intel_gpu::op {
+
+/// \brief MOECompressed experts that support compressed weights for GEMM3_SWIGLU MOE.
+class MOECompressed : public ov::op::internal::MOE {
+public:
+ OPENVINO_OP("MOECompressed", "gpu_opset", ov::op::internal::MOE);
+
+ MOECompressed() = default;
+
+ struct Config : public MOE::Config {
+ size_t hidden_size = 0;
+ size_t inter_size = 0;
+ size_t num_expert = 0;
+ size_t top_k = 0;
+ size_t group_size = 0;
+ // In CB, intermediate shapes are expanded to {SeqLen, 1, HiddenSize}
+ // In Non-CB, intermediate shapes are expanded to {Batch, SeqLen, HiddenSize}
+ size_t has_batch_dim = 0;
+ bool has_zp = false;
+ ov::element::Type out_type = ov::element::dynamic;
+ Config() = default;
+ Config(const MOE::Config& moe_config) : MOE::Config(moe_config) {}
+ };
+
+ /// \brief Constructs a MOECompressed operation with config only
+ /// \param args The input tensors, in the following order:
+ /// 0: hidden_states - input tensor with hidden representations
+ /// 1: routing_weights - [num_experts, ...] normalized weights for selected experts
+ /// (input to final multiplication)
+ /// 2: router_topk_output_indices - [..., topk] indices of selected top-k experts
+ /// 3: w0_weight - expert weights for first projection,
+ /// shape [num_experts, inter_size, group_num, group_size]
+ /// 4: w0_scale - expert scale for first projection for compressed experts,
+ /// shape [num_experts, inter_size, group_num, 1]
+ /// 5: w0_zp - expert zp for first projection for compressed experts,
+ /// shape [num_experts, inter_size, group_num, 1]
+ /// 6: w1_weight - expert weights for second projection,
+ /// shape [num_experts, inter_size, group_num, group_size]
+ /// 7: w1_scale - expert scale for second projection for compressed experts,
+ /// shape [num_experts, inter_size, group_num, 1]
+ /// 8: w1_zp - expert zp for second projection for compressed experts,
+ /// shape [num_experts, inter_size, group_num, 1]
+ /// 9: w2_weight - expert weights for final projection,
+ /// shape [num_experts, hidden_size, group_num, group_size]
+ /// 10: w2_scale - expert scale for final projection for compressed experts,
+ /// shape [num_experts, hidden_size, group_num, 1]
+ /// 11: w2_zp - expert zp for final projection for compressed experts,
+ /// shape [num_experts, hidden_size, group_num, 1]
+ /// \param config Configuration for the MOE operation
+ MOECompressed(const OutputVector& args, const Config& config);
+
+ const Config& get_config() const;
+ void set_config(const Config& config);
+
+ bool visit_attributes(AttributeVisitor& visitor) override;
+ void validate_and_infer_types() override;
+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
+
+private:
+ Config m_config;
+};
+
+} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/swiglu_with_clamp.hpp b/src/plugins/intel_gpu/include/intel_gpu/op/swiglu_with_clamp.hpp
new file mode 100644
index 00000000000..d09e2412c8c
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/op/swiglu_with_clamp.hpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/op/op.hpp"
+#include "ov_ops/glu.hpp"
+#include "openvino/op/util/sub_graph_base.hpp"
+
+namespace ov::intel_gpu::op {
+
+using GluType = ov::op::internal::GLU::GluType;
+
+/// \brief Operator performing Gated Linear Unit Activation
+/// This operation performs gated linear unit activation that combines swish or gelu activation function
+class SwiGluWithClamp : public ov::op::Op {
+public:
+ OPENVINO_OP("SwiGluWithClamp", "ie_internal_opset");
+
+ SwiGluWithClamp() = default;
+ /// \brief Constructs an SwiGluWithClamp operation.
+ ///
+ /// \param data Input tensor with data
+ /// \param axis The index of an axis in "data" along which to perform the split
+ /// \param glu_stride Size of stride for gate index
+ /// \param glu_type Either of Swish / Gelu / Gelu_Tanh
+ /// \param gate_idx Output index to apply gating activation
+ /// \param clamp_min Clamp output more than min value
+ /// \param clamp_max Clamp output less than max min
+ /// \param swiglu_beta Swiglu beta (default : 1.0f)
+ /// \param up_add_val Value added to up (default : 0.0f)
+ /// \param output_type Output element type
+ SwiGluWithClamp(const ov::Output<Node>& data,
+ int64_t axis,
+ int64_t glu_stride,
+ const GluType glu_type,
+ const size_t gate_idx,
+ const float clamp_min,
+ const float clamp_max,
+ const float swiglu_beta = 1.0f,
+ const float up_add_val = 0.0f,
+ const ov::element::Type output_type = ov::element::dynamic);
+
+ void validate_and_infer_types() override;
+
+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
+
+ int64_t get_axis() const {
+ return m_axis;
+ }
+ int64_t get_glu_stride() const {
+ return m_glu_stride;
+ }
+ GluType get_glu_type() const {
+ return m_glu_type;
+ }
+ size_t get_gate_idx() const {
+ return m_gate_idx;
+ }
+ float get_clamp_min() const {
+ return m_clamp_min;
+ }
+ float get_clamp_max() const {
+ return m_clamp_max;
+ }
+ float get_swiglu_beta() const {
+ return m_swiglu_beta;
+ }
+ float get_up_add_val() const {
+ return m_up_add_val;
+ }
+ void set_axis(int64_t axis) {
+ m_axis = axis;
+ }
+ void set_glu_stride(int64_t stride) {
+ m_glu_stride = stride;
+ }
+ void set_glu_type(GluType glu_type) {
+ m_glu_type = glu_type;
+ }
+ void set_gate_idx(size_t gate_idx) {
+ m_gate_idx = gate_idx;
+ }
+ void set_clamp_min(int64_t min) {
+ m_clamp_min = min;
+ }
+ void set_clamp_max(int64_t max) {
+ m_clamp_max = max;
+ }
+ void set_swiglu_beta(float beta) {
+ m_swiglu_beta = beta;
+ }
+ void set_up_add_val(float val) {
+ m_up_add_val = val;
+ }
+
+private:
+ int64_t m_axis = 0;
+ int64_t m_glu_stride = 0;
+ GluType m_glu_type = GluType::Swish;
+ size_t m_gate_idx = 0;
+ float m_clamp_min = std::numeric_limits<float>::lowest();
+ float m_clamp_max = std::numeric_limits<float>::max();
+ float m_swiglu_beta = 1.0f;
+ float m_up_add_val = 0.0f;
+ ov::element::Type m_output_type{};
+};
+
+std::vector<ov::PartialShape> shape_infer(const ov::intel_gpu::op::SwiGluWithClamp* op,
+ const std::vector<ov::PartialShape>& input_shapes);
+
+} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
index 90363864062..f36e22c7074 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
@@ -312,3 +312,4 @@ REGISTER_FACTORY(internal, PagedAttentionExtension);
REGISTER_FACTORY(internal, LoraSubgraph);
REGISTER_FACTORY(internal, LoraSubgraphFused);
REGISTER_FACTORY(internal, VLSDPA);
+REGISTER_FACTORY(internal, MOECompressed);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gather.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gather.hpp
new file mode 100644
index 00000000000..11fc39a9885
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gather.hpp
@@ -0,0 +1,60 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "primitive.hpp"
+#include "intel_gpu/op/moe_compressed.hpp"
+
+namespace cldnn {
+
+/// @brief
+/// @details
+struct moe_gather : public primitive_base<moe_gather> {
+ CLDNN_DECLARE_PRIMITIVE(moe_gather)
+
+ moe_gather() : primitive_base("", {}) {}
+
+ /// @brief Constructs moe_gather primitive.
+ ///
+ /// @param id This primitive id.
+ /// @param input Input data primitive id.
+ /// @param experts_info_offsets offset of each expert's info from the tokens_per_expert
+ /// @param tokens_per_expert tokens per expert
+ moe_gather(const primitive_id& id,
+ const input_info& data,
+ const input_info& tokens_per_expert,
+ const ov::intel_gpu::op::MOECompressed::Config& moe_config)
+ : primitive_base(id, {data, tokens_per_expert}), num_experts_per_token(static_cast<int32_t>(moe_config.top_k)), has_batch_dim(moe_config.has_batch_dim) {}
+
+ int32_t num_experts_per_token = 0;
+ bool has_batch_dim = true;
+
+ size_t hash() const override {
+ size_t seed = primitive::hash();
+ seed = hash_combine(seed, num_experts_per_token);
+ seed = hash_combine(seed, has_batch_dim);
+ return seed;
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+
+ auto rhs_casted = downcast<const moe_gather>(rhs);
+ return num_experts_per_token == rhs_casted.num_experts_per_token && has_batch_dim == rhs_casted.has_batch_dim;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_gather>::save(ob);
+ ob << num_experts_per_token;
+ ob << has_batch_dim;
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_gather>::load(ib);
+ ib >> num_experts_per_token;
+ ib >> has_batch_dim;
+ }
+};
+}
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gemm.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gemm.hpp
new file mode 100644
index 00000000000..2739b15649b
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_gemm.hpp
@@ -0,0 +1,83 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "primitive.hpp"
+#include "intel_gpu/op/moe_compressed.hpp"
+
+namespace cldnn {
+
+/// @brief gemm for moe_pattern which selectively executes experts.
+/// @details
+/// This primitive implements the GEMM operation for the Mixture of Experts (MoE) pattern,
+/// allowing for efficient execution of a subset of experts based on the input data.
+/// @param input Input data tensor.
+/// @param weight Weights tensor containing expert weights.
+/// @param experts_ids Tensor containing the IDs of the experts that are actually used at each time.
+/// @param inputs_offset_per_expert Tensor containing the offsets information of inputs per expert.
+/// @param input_tokens_lens Tensor containing the lengths of input tokens used by each expert.
+/// @param num_experts_per_token Number of experts per token selected by router.
+struct moe_gemm : public primitive_base<moe_gemm> {
+ CLDNN_DECLARE_PRIMITIVE(moe_gemm)
+
+ enum MoEGemmInputIdx {
+ // required
+ INPUT = 0,
+ WEIGHT = 1,
+ EXPERTS_IDS = 2,
+ INPUT_OFFSET_PER_EXPERT = 3,
+ INPUT_TOKENS_LENS = 4,
+ // optional
+ BIAS = 5,
+ WEIGHT_SCALE = 6,
+ WEIGHT_ZP = 7
+ };
+
+ moe_gemm() : primitive_base("", {}) {}
+
+ /// @brief Constructs moe_gemm primitive.
+ ///
+ moe_gemm(const primitive_id& id,
+ const std::vector<input_info>& inputs,
+ const ov::intel_gpu::op::MOECompressed::Config& moe_config)
+ : primitive_base(id, inputs),
+ num_experts_per_token(static_cast<int32_t>(moe_config.top_k)),
+ has_batch_dim(moe_config.has_batch_dim) {}
+
+ bool has_bias = false;
+ int32_t num_experts_per_token = 0;
+ bool has_batch_dim = true;
+
+ size_t hash() const override {
+ size_t seed = primitive::hash();
+ seed = hash_combine(seed, has_bias);
+ seed = hash_combine(seed, num_experts_per_token);
+ seed = hash_combine(seed, has_batch_dim);
+ return seed;
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+ auto rhs_casted = downcast<const moe_gemm>(rhs);
+ return has_bias == rhs_casted.has_bias &&
+ num_experts_per_token == rhs_casted.num_experts_per_token &&
+ has_batch_dim == rhs_casted.has_batch_dim;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_gemm>::save(ob);
+ ob << has_bias;
+ ob << num_experts_per_token;
+ ob << has_batch_dim;
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_gemm>::load(ib);
+ ib >> has_bias;
+ ib >> num_experts_per_token;
+ ib >> has_batch_dim;
+ }
+};
+}
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_mask_gen.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_mask_gen.hpp
new file mode 100644
index 00000000000..8c5edee7ddf
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_mask_gen.hpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "primitive.hpp"
+
+namespace cldnn {
+
+/// @brief
+/// @details
+struct moe_mask_gen : public primitive_base<moe_mask_gen> {
+ CLDNN_DECLARE_PRIMITIVE(moe_mask_gen)
+
+ enum MoEMaskGenOutputIdx {
+ TOKENS_PER_EXPERT = 0,
+ EXPERTS_INFO_START_IDX = 1,
+ EXPERTS_ID = 2,
+ TOKENS_LENS_PER_EXPERT = 3,
+ NUM_ACTUALLY_USED_EXPERTS = 4
+ };
+
+ moe_mask_gen() : primitive_base("", {}) {}
+
+ /// @brief Constructs moe_mask_gen primitive.
+ ///
+ /// @param id This primitive id.
+ /// @param router_idx output of router (i.e., idx output of topk)
+ /// @param output0 : used tokens per expert
+ /// @param output1 : start offset for each expert' info
+ /// @param output2 : experts' ids actually used
+ /// @param output3 : tokens' length per expert
+ /// @param output4 : number of actually used experts
+
+ moe_mask_gen(const primitive_id& id,
+ const input_info& router_idx,
+ const int32_t num_total_experts,
+ const int32_t num_experts_per_token)
+ : primitive_base(id, {router_idx}, 5),
+ num_total_experts(num_total_experts),
+ num_experts_per_token(num_experts_per_token) {}
+
+ int32_t num_total_experts = 0;
+ int32_t num_experts_per_token = 0;
+
+ size_t hash() const override {
+ size_t seed = primitive::hash();
+ seed = hash_combine(seed, num_total_experts);
+ seed = hash_combine(seed, num_experts_per_token);
+ return primitive::hash();
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+ return true;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_mask_gen>::save(ob);
+ ob << num_total_experts;
+ ob << num_experts_per_token;
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_mask_gen>::load(ib);
+ ib >> num_total_experts;
+ ib >> num_experts_per_token;
+ }
+};
+
+struct moe_mask_gen_reshape : public primitive_base<moe_mask_gen_reshape> {
+ CLDNN_DECLARE_PRIMITIVE(moe_mask_gen_reshape)
+
+ enum MoEMaskGenReshapeOutputIdx {
+ TOKENS_PER_EXPERT = 0,
+ EXPERTS_INFO_START_IDX = 1,
+ EXPERTS_ID = 2,
+ TOKENS_LENS_PER_EXPERT = 3
+ };
+
+ moe_mask_gen_reshape() : primitive_base("", {}) {}
+
+ /// @brief Constructs moe_mask_gen_reshape primitive.
+ ///
+ /// @param id This primitive id.
+ /// @param input0 : output0 of moe_mask_gen
+ /// @param input1 : output1 of moe_mask_gen
+ /// @param input2 : output2 of moe_mask_gen
+ /// @param input3 : output3 of moe_mask_gen
+ /// @param input4 : output4 of moe_mask_gen
+ ///
+ /// @param output0 : output0 of moe_mask_gen reshaped for num of actually used experts
+ /// @param output1 : output1 of moe_mask_gen reshaped for num of actually used experts
+ /// @param output2 : output2 of moe_mask_gen reshaped for num of actually used experts
+ /// @param output3 : output3 of moe_mask_gen reshaped for num of actually used experts
+
+ moe_mask_gen_reshape(const primitive_id& id,
+ const input_info& tokens_per_expert,
+ const input_info& experts_info_start_idx,
+ const input_info& experts_id,
+ const input_info& tokens_lens_per_expert,
+ const input_info& num_actual_used_experts)
+ : primitive_base(id, {tokens_per_expert, experts_info_start_idx, experts_id, tokens_lens_per_expert, num_actual_used_experts}, 4) {}
+
+ size_t hash() const override {
+ return primitive::hash();
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+ return true;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_mask_gen_reshape>::save(ob);
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_mask_gen_reshape>::load(ib);
+ }
+};
+
+}
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_scatter_reduction.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_scatter_reduction.hpp
new file mode 100644
index 00000000000..690730744e7
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_scatter_reduction.hpp
@@ -0,0 +1,73 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "primitive.hpp"
+#include "intel_gpu/op/moe_compressed.hpp"
+
+namespace cldnn {
+
+/// @brief
+/// @details
+struct moe_scatter_reduction : public primitive_base<moe_scatter_reduction> {
+ CLDNN_DECLARE_PRIMITIVE(moe_scatter_reduction)
+
+ moe_scatter_reduction() : primitive_base("", {}) {}
+
+ /// @brief Constructs moe_scatter_reduction primitive.
+ ///
+ /// @param id This primitive id.
+ /// @param input Input data primitive id.
+ /// @param experts_per_token sorted topk expert id per token
+ /// @param expert_weights_per_token sorted topk expert id weight per token
+ /// @param tokens_per_expert tokens per expert
+ /// @param experts_info_offsets offset of each expert's info from the tokens_per_expert
+ /// @param tokens_len_per_expert tokens len_per_expert
+ /// @param experts_ids exert_ids actually used
+ moe_scatter_reduction(const primitive_id& id,
+ const input_info& data,
+ const input_info& experts_per_token,
+ const input_info& expert_weights_per_token,
+ const input_info& tokens_per_expert,
+ const input_info& experts_info_offsets,
+ const input_info& tokens_len_per_expert,
+ const input_info& experts_ids,
+ const ov::intel_gpu::op::MOECompressed::Config& moe_config)
+ : primitive_base(id, {data, experts_per_token, expert_weights_per_token, tokens_per_expert, experts_info_offsets, tokens_len_per_expert, experts_ids}),
+ num_active_experts_per_token(static_cast<int32_t>(moe_config.top_k)),
+ has_batch_dim(moe_config.has_batch_dim) {}
+
+ int32_t num_active_experts_per_token = 0;
+ bool has_batch_dim = true;
+
+ size_t hash() const override {
+ size_t seed = primitive::hash();
+ seed = hash_combine(seed, num_active_experts_per_token);
+ seed = hash_combine(seed, has_batch_dim);
+ return seed;
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ if (!compare_common_params(rhs))
+ return false;
+
+ auto rhs_casted = downcast<const moe_scatter_reduction>(rhs);
+
+ return num_active_experts_per_token == rhs_casted.num_active_experts_per_token;
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<moe_scatter_reduction>::save(ob);
+ ob << num_active_experts_per_token;
+ ob << has_batch_dim;
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<moe_scatter_reduction>::load(ib);
+ ib >> num_active_experts_per_token;
+ ib >> has_batch_dim;
+ }
+};
+}
+
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/swiglu.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/swiglu.hpp
index 1a72e36d471..cd23ccc97a0 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/swiglu.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/swiglu.hpp
@@ -19,34 +19,69 @@ struct swiglu : public primitive_base<swiglu> {
/// @param id This primitive id
/// @param input Input primitive id
/// @param axis The index of an axis in data along which to perform the split
- /// @param split_lengths A list containing the sizes of each output tensor along the split axis
+ /// @param glu_stride A list containing the sizes of each output tensor along the split axis
/// @param output_size Output data size of the primitive
swiglu(const primitive_id& id,
const input_info& input,
const int64_t& axis,
- const int64_t& split_lengths,
+ const int64_t& glu_stride,
const ov::op::internal::GLU::GluType glu_type,
- const size_t split_to_glu_idx,
+ const size_t gate_idx,
+ const float clamp_min,
+ const float clamp_max,
+ const float swish_beta,
+ const float up_add_val,
const tensor output_size)
: primitive_base(id, {input}),
axis(axis),
- split_lengths(split_lengths),
+ glu_stride(glu_stride),
glu_type(glu_type),
- split_to_glu_idx(split_to_glu_idx),
+ gate_idx(gate_idx),
+ clamp_min(clamp_min),
+ clamp_max(clamp_max),
+ swish_beta(swish_beta),
+ up_add_val(up_add_val),
output_size(output_size) {}
+ swiglu(const primitive_id& id,
+ const input_info& input,
+ const int64_t& axis,
+ const int64_t& glu_stride,
+ const ov::op::internal::GLU::GluType glu_type,
+ const size_t gate_idx,
+ const tensor output_size)
+ : swiglu(id,
+ input,
+ axis,
+ glu_stride,
+ glu_type,
+ gate_idx,
+ std::numeric_limits<float>::lowest(),
+ std::numeric_limits<float>::max(),
+ 1.0f,
+ 0.0f,
+ output_size) {}
+
int64_t axis = 0;
- int64_t split_lengths = 0;
+ int64_t glu_stride = 0;
ov::op::internal::GLU::GluType glu_type = ov::op::internal::GLU::GluType::Swish;
- size_t split_to_glu_idx = 0;
+ size_t gate_idx = 0;
+ float clamp_min = std::numeric_limits<float>::lowest();
+ float clamp_max = std::numeric_limits<float>::max();;
+ float swish_beta = 1.0f;
+ float up_add_val = 0.0f;
tensor output_size;
size_t hash() const override {
size_t seed = primitive::hash();
seed = hash_combine(seed, axis);
- seed = hash_combine(seed, split_lengths);
+ seed = hash_combine(seed, glu_stride);
seed = hash_combine(seed, glu_type);
- seed = hash_combine(seed, split_to_glu_idx);
+ seed = hash_combine(seed, gate_idx);
+ seed = hash_combine(seed, clamp_min);
+ seed = hash_combine(seed, clamp_max);
+ seed = hash_combine(seed, swish_beta);
+ seed = hash_combine(seed, up_add_val);
return seed;
}
@@ -55,26 +90,36 @@ struct swiglu : public primitive_base<swiglu> {
return false;
auto rhs_casted = downcast<const swiglu>(rhs);
- return axis == rhs_casted.axis && split_lengths == rhs_casted.split_lengths &&
- glu_type == rhs_casted.glu_type && split_to_glu_idx == rhs_casted.split_to_glu_idx;
+ return axis == rhs_casted.axis && glu_stride == rhs_casted.glu_stride &&
+ glu_type == rhs_casted.glu_type && gate_idx == rhs_casted.gate_idx &&
+ clamp_min == rhs_casted.clamp_min && clamp_max == rhs_casted.clamp_max &&
+ swish_beta == rhs_casted.swish_beta && up_add_val == rhs_casted.up_add_val;
}
void save(BinaryOutputBuffer& ob) const override {
primitive_base<swiglu>::save(ob);
ob << axis;
- ob << split_lengths;
+ ob << glu_stride;
ob << output_size;
ob << make_data(&glu_type, sizeof(glu_type));
- ob << split_to_glu_idx;
+ ob << gate_idx;
+ ob << clamp_min;
+ ob << clamp_max;
+ ob << swish_beta;
+ ob << up_add_val;
}
void load(BinaryInputBuffer& ib) override {
primitive_base<swiglu>::load(ib);
ib >> axis;
- ib >> split_lengths;
+ ib >> glu_stride;
ib >> output_size;
ib >> make_data(&glu_type, sizeof(glu_type));
- ib >> split_to_glu_idx;
+ ib >> gate_idx;
+ ib >> clamp_min;
+ ib >> clamp_max;
+ ib >> swish_beta;
+ ib >> up_add_val;
}
};
} // namespace cldnn
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
index a265f053370..e921d6bef94 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/internal_properties.hpp
@@ -165,6 +165,7 @@ static constexpr Property<size_t, ov::PropertyMutability::RW> disable_post_ops_f
static constexpr Property<bool, ov::PropertyMutability::RW> disable_horizontal_fc_fusion{"GPU_DISABLE_HORIZONTAL_FC_FUSION"};
static constexpr Property<bool, ov::PropertyMutability::RW> disable_fc_swiglu_fusion{"GPU_DISABLE_FC_SWIGLU_FUSION"};
static constexpr Property<bool, ov::PropertyMutability::RW> disable_fake_alignment{"GPU_DISABLE_FAKE_ALIGNMENT"};
+static constexpr Property<bool, ov::PropertyMutability::RW> disable_moe_opt{"GPU_DISABLE_MOE_OPT"};
static constexpr Property<bool, ov::PropertyMutability::RW> disable_runtime_skip_reorder{"GPU_DISABLE_RUNTIME_SKIP_REORDER"};
static constexpr Property<bool, ov::PropertyMutability::RW> asym_dynamic_quantization{"GPU_ASYM_DYNAMIC_QUANTIZATION"};
static constexpr Property<size_t, ov::PropertyMutability::RW> dynamic_quantization_threshold{"GPU_DYNAMIC_QUANTIZATION_THRESHOLD"};
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
index f3c17cb0d28..5301b5d00ba 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
@@ -91,6 +91,7 @@ OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_post_ops_fusions, 0, "Disable fusi
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_horizontal_fc_fusion, false, "Disable pass which merges QKV projections into single MatMul")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_fc_swiglu_fusion, false, "Disable pass which merges FC and SwiGLU ops")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_fake_alignment, false, "Disable fake alignment feature which tries to keep gpu friendly memory alignment for arbitrary tensor shapes")
+OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_moe_opt, false, "Disable mixture of expert optimization")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_memory_reuse, false, "Disable memory reuse for activation tensors")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, disable_runtime_skip_reorder, false, "Disable skip reorder optimization applied in runtime")
OV_CONFIG_DEBUG_OPTION(ov::intel_gpu, load_dump_raw_binary, std::vector<std::string>{}, "List of layers to load raw binary")
diff --git a/src/plugins/intel_gpu/src/graph/fully_connected.cpp b/src/plugins/intel_gpu/src/graph/fully_connected.cpp
index 6282a071977..17bad41044e 100644
--- a/src/plugins/intel_gpu/src/graph/fully_connected.cpp
+++ b/src/plugins/intel_gpu/src/graph/fully_connected.cpp
@@ -200,7 +200,7 @@ std::vector<layout> fully_connected_inst::calc_output_layouts(fully_connected_no
OPENVINO_ASSERT(fused_prims.size() == 1);
OPENVINO_ASSERT(fused_prims[0].typed_desc<swiglu>()->glu_type == ov::op::internal::GLU::GluType::Swish);
swiglu_op.set_axis(fused_prims[0].typed_desc<swiglu>()->axis);
- swiglu_op.set_split_lengths(fused_prims[0].typed_desc<swiglu>()->split_lengths);
+ swiglu_op.set_split_lengths(fused_prims[0].typed_desc<swiglu>()->glu_stride);
swiglu_op.set_glu_type(fused_prims[0].typed_desc<swiglu>()->glu_type);
std::vector<ShapeType> input_shapes = { output_shapes[0] };
output_shapes = shape_infer(&swiglu_op, input_shapes);
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
index b22334c9795..0b7a105c1d7 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
@@ -233,7 +233,8 @@ void prepare_primitive_fusing::fuse_swiglu(program &p) {
continue;
GPU_DEBUG_TRACE_DETAIL << node->id() << " : fuse swiglu to " << fc_node.id() << std::endl;
GPU_DEBUG_TRACE_DETAIL << " - split axis : " << swiglu_prim->axis << std::endl;
- GPU_DEBUG_TRACE_DETAIL << " - split length : " << swiglu_prim->split_lengths << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << " - glu stride : " << swiglu_prim->glu_stride << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << " - gate idx : " << swiglu_prim->gate_idx << std::endl;
p.fuse_nodes(fc_node, *node, &fusing_history);
}
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/cpu/moe_mask_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/cpu/moe_mask_gen.cpp
new file mode 100644
index 00000000000..77b33475c4b
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cpu/moe_mask_gen.cpp
@@ -0,0 +1,194 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "impls/cpu/cpu_impl_helpers.hpp"
+#include "register.hpp"
+#include "moe_mask_gen_inst.h"
+#include "registry/implementation_map.hpp"
+
+namespace cldnn {
+namespace cpu {
+
+struct moe_mask_gen_impl : public typed_primitive_impl<moe_mask_gen> {
+ using parent = typed_primitive_impl<moe_mask_gen>;
+ using parent::parent;
+
+ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::cpu::moe_mask_gen_impl)
+
+ std::unique_ptr<primitive_impl> clone() const override {
+ return std::make_unique<moe_mask_gen_impl>(*this);
+ }
+
+ moe_mask_gen_impl() : parent("moe_mask_gen_cpu_impl") {}
+
+ explicit moe_mask_gen_impl(const moe_mask_gen_node& outer) {
+ set_node_params(outer);
+ }
+
+ void set_node_params(const program_node& arg) override {
+ OPENVINO_ASSERT(arg.is_type<moe_mask_gen>(), "[GPU] Incorrect program_node type");
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ parent::save(ob);
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ parent::load(ib);
+ }
+
+ event::ptr execute_impl(const std::vector<event::ptr>& events, moe_mask_gen_inst& instance) override {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, "moe_mask_gen::execute_impl");
+ auto& stream = instance.get_network().get_stream();
+
+ const bool pass_through_events = (stream.get_queue_type() == QueueTypes::out_of_order) && instance.all_dependencies_cpu_impl();
+
+ if (!pass_through_events) {
+ stream.wait_for_events(events);
+ }
+
+ auto num_tokens = instance.get_input_layout(0).get_shape()[0];
+ auto num_experts_per_token = instance.get_node().as<moe_mask_gen>().get_primitive()->num_experts_per_token;
+ auto num_total_experts = instance.get_node().as<moe_mask_gen>().get_primitive()->num_total_experts;
+
+ auto topk_idx_mem_ptr = instance.dep_memory_ptr(0);
+ auto tokens_per_expert_mem_ptr = instance.output_memory_ptr(0);
+ auto experts_info_start_idx_mem_ptr = instance.output_memory_ptr(1);
+ auto experts_id_mem_ptr = instance.output_memory_ptr(2);
+ auto tokens_lens_per_expert_mem_ptr = instance.output_memory_ptr(3);
+ auto num_actual_used_experts_mem_ptr = instance.output_memory_ptr(4);
+
+ cldnn::mem_lock<int32_t, mem_lock_type::read> topk_idx_lock(topk_idx_mem_ptr, stream);
+ cldnn::mem_lock<int32_t, mem_lock_type::write> num_actual_used_experts_lock(num_actual_used_experts_mem_ptr, stream);
+ cldnn::mem_lock<int32_t, mem_lock_type::write> tokens_per_expert_lock(tokens_per_expert_mem_ptr, stream);
+ cldnn::mem_lock<int32_t, mem_lock_type::write> experts_info_start_idx_lock(experts_info_start_idx_mem_ptr, stream);
+ cldnn::mem_lock<int32_t, mem_lock_type::write> experts_id_lock(experts_id_mem_ptr, stream);
+ cldnn::mem_lock<int32_t, mem_lock_type::write> tokens_lens_per_expert_lock(tokens_lens_per_expert_mem_ptr, stream);
+
+ // make mask for gather
+ std::vector<std::vector<int32_t>> tokens_per_expert(num_total_experts, std::vector<int32_t>());
+ for (size_t token = 0; token < num_tokens; ++token) {
+ for (int j = 0; j < num_experts_per_token; ++j) {
+ const auto expert_id = topk_idx_lock[token * num_experts_per_token + j];
+ tokens_per_expert[expert_id].push_back(static_cast<int32_t>(token));
+ }
+ }
+
+ int tokens_per_expert_iter = 0;
+ int experts_id_iter = 0;
+ int num_actually_used_experts = 0;
+ for (int expert = 0; expert < num_total_experts; expert++) {
+ if (!tokens_per_expert[expert].empty()) {
+ experts_info_start_idx_lock[experts_id_iter] = tokens_per_expert_iter;
+ experts_id_lock[experts_id_iter] = expert;
+ tokens_lens_per_expert_lock[experts_id_iter++] = static_cast<int32_t>(tokens_per_expert[expert].size());
+ num_actually_used_experts++;
+ for (auto t : tokens_per_expert[expert]) {
+ tokens_per_expert_lock[tokens_per_expert_iter++] = t;
+ }
+ }
+ }
+ num_actual_used_experts_lock[0] = num_actually_used_experts;
+
+ if (pass_through_events) {
+ return stream.group_events(events);
+ }
+ return make_output_event(stream, instance.is_output());
+ }
+
+ void init_kernels(const kernels_cache& , const kernel_impl_params&) override {}
+
+ void update(primitive_inst& inst, const kernel_impl_params& impl_param) override {}
+
+public:
+ static std::unique_ptr<primitive_impl> create(const moe_mask_gen_node& arg, const kernel_impl_params& impl_param) {
+ return std::make_unique<moe_mask_gen_impl>();
+ }
+};
+
+struct moe_mask_gen_reshape_impl : public typed_primitive_impl<moe_mask_gen_reshape> {
+ using parent = typed_primitive_impl<moe_mask_gen_reshape>;
+ using parent::parent;
+
+ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::cpu::moe_mask_gen_reshape_impl)
+
+ std::unique_ptr<primitive_impl> clone() const override {
+ return std::make_unique<moe_mask_gen_reshape_impl>(*this);
+ }
+
+ moe_mask_gen_reshape_impl() : parent("moe_mask_gen_reshape_cpu_impl") {}
+
+ explicit moe_mask_gen_reshape_impl(const moe_mask_gen_reshape_node& outer) {
+ set_node_params(outer);
+ }
+
+ void set_node_params(const program_node& arg) override {
+ OPENVINO_ASSERT(arg.is_type<moe_mask_gen_reshape>(), "[GPU] Incorrect program_node type");
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ parent::save(ob);
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ parent::load(ib);
+ }
+
+ event::ptr execute_impl(const std::vector<event::ptr>& events, moe_mask_gen_reshape_inst& instance) override {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, "moe_mask_gen_reshape::execute_impl");
+ auto& stream = instance.get_network().get_stream();
+
+ return stream.group_events(events);
+ }
+
+ void init_kernels(const kernels_cache& , const kernel_impl_params&) override {}
+
+ void update(primitive_inst& inst, const kernel_impl_params& impl_param) override {}
+
+public:
+ static std::unique_ptr<primitive_impl> create(const moe_mask_gen_reshape_node& arg, const kernel_impl_params& impl_param) {
+ return std::make_unique<moe_mask_gen_reshape_impl>();
+ }
+};
+
+namespace detail {
+attach_moe_mask_gen_impl::attach_moe_mask_gen_impl() {
+ auto formats = {
+ format::bfyx,
+ };
+
+ auto types = {
+ data_types::i32,
+ data_types::i64,
+ data_types::f32,
+ };
+
+ implementation_map<moe_mask_gen>::add(impl_types::cpu, shape_types::static_shape, moe_mask_gen_impl::create, types, formats);
+ implementation_map<moe_mask_gen>::add(impl_types::cpu, shape_types::dynamic_shape, moe_mask_gen_impl::create, types, formats);
+}
+
+attach_moe_mask_gen_reshape_impl::attach_moe_mask_gen_reshape_impl() {
+ auto formats = {
+ format::bfyx,
+ };
+
+ auto types = {
+ data_types::i32,
+ data_types::i64,
+ data_types::f32,
+ };
+
+ implementation_map<moe_mask_gen_reshape>::add(impl_types::cpu, shape_types::static_shape, moe_mask_gen_reshape_impl::create, types, formats);
+ implementation_map<moe_mask_gen_reshape>::add(impl_types::cpu, shape_types::dynamic_shape, moe_mask_gen_reshape_impl::create, types, formats);
+}
+
+} // namespace detail
+} // namespace cpu
+} // namespace cldnn
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::cpu::moe_mask_gen_impl)
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::moe_mask_gen)
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::cpu::moe_mask_gen_reshape_impl)
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::moe_mask_gen_reshape)
diff --git a/src/plugins/intel_gpu/src/graph/impls/cpu/register.cpp b/src/plugins/intel_gpu/src/graph/impls/cpu/register.cpp
index 5ecb13a3a10..3889d9e432a 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cpu/register.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cpu/register.cpp
@@ -32,6 +32,8 @@ void register_implementations() {
REGISTER_CPU(select);
REGISTER_CPU(reduce);
REGISTER_CPU(fake_convert);
+ REGISTER_CPU(moe_mask_gen);
+ REGISTER_CPU(moe_mask_gen_reshape);
}
} // namespace cpu
diff --git a/src/plugins/intel_gpu/src/graph/impls/cpu/register.hpp b/src/plugins/intel_gpu/src/graph/impls/cpu/register.hpp
index e9f63807087..131b7e3f86c 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cpu/register.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/cpu/register.hpp
@@ -23,6 +23,7 @@
#include "intel_gpu/primitives/tile.hpp"
#include "intel_gpu/primitives/select.hpp"
#include "intel_gpu/primitives/reduce.hpp"
+#include "intel_gpu/primitives/moe_mask_gen.hpp"
namespace cldnn {
namespace cpu {
@@ -57,6 +58,8 @@ REGISTER_CPU(tile);
REGISTER_CPU(select);
REGISTER_CPU(reduce);
REGISTER_CPU(fake_convert);
+REGISTER_CPU(moe_mask_gen);
+REGISTER_CPU(moe_mask_gen_reshape);
#undef REGISTER_CPU
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
index 2adf2c67d3f..6e70ba0cb12 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
@@ -1039,9 +1039,19 @@ std::shared_ptr<kernel_selector::fuse_params> convert_fuse_params(std::shared_pt
if (p->type() == swiglu::type_id()) {
auto casted = std::dynamic_pointer_cast<SwigluFuseParams>(p);
auto axis = casted->_desc->axis;
- auto split_length = casted->_desc->split_lengths;
- auto split_to_glu_idx = casted->_desc->split_to_glu_idx;
- return std::make_shared<kernel_selector::swiglu_fuse_params>(axis, split_length, split_to_glu_idx);
+ auto glu_stride = casted->_desc->glu_stride;
+ auto gate_idx = casted->_desc->gate_idx;
+ auto clamp_min = casted->_desc->clamp_min;
+ auto clamp_max = casted->_desc->clamp_max;
+ auto swish_beta = casted->_desc->swish_beta;
+ auto up_add_val = casted->_desc->up_add_val;
+ return std::make_shared<kernel_selector::swiglu_fuse_params>(axis,
+ glu_stride,
+ gate_idx,
+ clamp_min,
+ clamp_max,
+ swish_beta,
+ up_add_val);
} else if (p->type() == activation::type_id()) {
auto casted = std::dynamic_pointer_cast<ActivationFuseParams>(p);
auto desc = casted->_desc;
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/swiglu.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/swiglu.cpp
index 61ba0fc7cb9..2c1062deb7d 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/swiglu.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/swiglu.cpp
@@ -38,10 +38,13 @@ struct swiglu_impl : typed_primitive_impl_ocl<swiglu> {
auto rank = impl_param.get_input_layout(0).get_partial_shape().rank();
params.axis = ov::util::normalize(primitive->axis, rank.get_length());
- params.split_length = primitive->split_lengths;
+ params.glu_stride = primitive->glu_stride;
params.glu_type = primitive->glu_type;
- params.split_to_glu_idx = static_cast<int32_t>(primitive->split_to_glu_idx);
-
+ params.gate_idx = static_cast<int32_t>(primitive->gate_idx);
+ params.clamp_min = primitive->clamp_min;
+ params.clamp_max = primitive->clamp_max;
+ params.swish_beta = primitive->swish_beta;
+ params.up_add_val = primitive->up_add_val;
return params;
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.cpp
new file mode 100644
index 00000000000..0cb970ecfcc
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.cpp
@@ -0,0 +1,148 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "moe_gather.hpp"
+
+#include "../common_utils/dispatch_utils.hpp"
+#include "../common_utils/jitter.hpp"
+#include "../primitive_ocl_base.hpp"
+#include "../utils/kernel_generator.hpp"
+#include "intel_gpu/primitives/moe_gather.hpp"
+
+namespace ov::intel_gpu::ocl {
+namespace {
+
+class MoeGatherRefGenerator : public KernelGenerator {
+public:
+ MoeGatherRefGenerator() : KernelGenerator("moe_gather_ref") {}
+
+protected:
+ static size_t GetBlockSize(const RuntimeParams& params) {
+ const auto& input = params.get_input_layout(0);
+ size_t vec_size = 1;
+ switch (input.data_type) {
+ case ov::element::i8:
+ case ov::element::u8:
+ vec_size = 16;
+ break;
+ case ov::element::f16:
+ vec_size = 8;
+ break;
+ case ov::element::f32:
+ case ov::element::i32:
+ vec_size = 4;
+ break;
+ case ov::element::i64:
+ vec_size = 2;
+ break;
+ default:
+ vec_size = 1;
+ break;
+ }
+ return vec_size;
+ }
+
+ static auto calc_thread_count(RuntimeParams& params, const size_t vector_size, const size_t hidden_size) {
+ auto max_wgs = params.get_program().get_engine().get_device_info().max_work_group_size;
+ const uint64_t threads_needed = (hidden_size + vector_size - 1) / vector_size;
+ size_t local_threads_needed = std::min(threads_needed, max_wgs);
+ size_t batches_per_thread = 1;
+ size_t unaligned_elements = 0;
+
+ if (threads_needed <= max_wgs) {
+ batches_per_thread = 1;
+ unaligned_elements = hidden_size % vector_size;
+ } else {
+ batches_per_thread = (threads_needed + max_wgs - 1) / max_wgs;
+ auto new_block_size = batches_per_thread * vector_size;
+ unaligned_elements = hidden_size % new_block_size;
+
+ local_threads_needed = hidden_size / new_block_size;
+ auto partialblock = (hidden_size % new_block_size != 0) ? 1 : 0;
+ local_threads_needed += partialblock;
+ }
+
+ return std::tuple{local_threads_needed, batches_per_thread, unaligned_elements};
+ }
+
+ static size_t get_hidden_size(const RuntimeParams& params) {
+ const auto& input_layout = params.get_input_layout(0);
+ size_t input_rank = input_layout.get_partial_shape().size();
+ return input_layout.get_partial_shape()[input_rank - 1].get_length();
+ }
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ auto in_l = params.input_layouts[0];
+ auto hidden_size = get_hidden_size(params);
+ auto block_size = GetBlockSize(params);
+ auto [local_threads_count, batches_per_thread, unaligned_elements] = calc_thread_count(const_cast<RuntimeParams&>(params), block_size, hidden_size);
+
+ jit.make("HIDDEN_SIZE", hidden_size);
+ jit.make("VEC_BLK_SIZE", block_size);
+ jit.make("BATCHES_PER_THREAD", batches_per_thread);
+ jit.make("UNALIGNED_ELEMENTS", unaligned_elements);
+
+ return jit;
+ }
+
+ Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ Arguments args;
+ if (params.is_dynamic()) {
+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
+ }
+
+ const uint32_t num_of_inputs = 2;
+ for (uint32_t i = 0; i < num_of_inputs; i++) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, i});
+ }
+
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ auto& wgs = kd.params.workGroups;
+ if (!params.is_dynamic()) {
+ auto hidden_size = get_hidden_size(params);
+ auto block_size = GetBlockSize(params);
+ auto [local_threads_count, batches_per_thread, unaligned_elements] =
+ calc_thread_count(const_cast<RuntimeParams&>(params), block_size, hidden_size);
+ auto token_per_expert = extract_channel(ChannelName::BATCH, params.input_layouts[1]);
+
+ wgs.global = {token_per_expert * local_threads_count, 1, 1};
+ wgs.local = {local_threads_count, 1, 1};
+ }
+ }};
+ }
+};
+
+class MoeGatherRefImpl : public PrimitiveImplOCL {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoeGatherRefImpl)
+
+ Stage::Ptr moe_gather = make_stage<MoeGatherRefGenerator>();
+
+ MoeGatherRefImpl() : PrimitiveImplOCL(MoeGatherRef::get_type_info_static()) {}
+ MoeGatherRefImpl(const program_node& node, const RuntimeParams& params) : MoeGatherRefImpl() {
+ add_stage(moe_gather, params);
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<MoeGatherRefImpl>(this);
+ }
+};
+
+} // namespace
+
+std::unique_ptr<primitive_impl> MoeGatherRef::create_impl(const program_node& node, const RuntimeParams& params) const {
+ assert(node.is_type<moe_gather>());
+ return std::make_unique<MoeGatherRefImpl>(node, params);
+}
+
+} // namespace ov::intel_gpu::ocl
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::moe_gather)
+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::MoeGatherRefImpl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.hpp
new file mode 100644
index 00000000000..4f7d4f1c46a
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gather.hpp
@@ -0,0 +1,55 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <utility>
+
+#include "program_node.h"
+#include "registry/implementation_manager.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+
+namespace ov::intel_gpu::ocl {
+
+struct MoeGatherRef : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("ocl::moe_gather::ref")
+ explicit MoeGatherRef(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}
+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;
+ [[nodiscard]] bool validate_impl(const program_node& node) const override {
+ static constexpr std::array supported_fmts = {
+ format::bfyx,
+ };
+
+ static constexpr std::array supported_types = {
+ ov::element::f32,
+ ov::element::f16,
+ ov::element::i32,
+ ov::element::i64,
+ ov::element::i8,
+ ov::element::u8,
+ };
+
+ const auto& in0_layout = node.get_input_layout(0);
+ const auto& out_layout = node.get_output_layout(0);
+ const auto& input_pshapes = in0_layout.get_partial_shape();
+
+ if (input_pshapes.rank() != 3 || input_pshapes[2].is_dynamic()) {
+ return false;
+ }
+
+ if (!one_of(in0_layout.format, supported_fmts) || !one_of(out_layout.format, supported_fmts)) {
+ return false;
+ }
+
+ if (!one_of(in0_layout.data_type, supported_types) || !one_of(out_layout.data_type, supported_types)) {
+ return false;
+ }
+
+ return true;
+ }
+};
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.cpp
new file mode 100644
index 00000000000..68203cf3eb7
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.cpp
@@ -0,0 +1,104 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+// clang-format off
+#include "moe_gemm_gen_micro.hpp"
+// clang-format on
+
+#include "moe_gemm.hpp"
+
+#include "../primitive_ocl_base.hpp"
+#include "../utils/jitter.hpp"
+#include "../utils/kernel_generator.hpp"
+#include "common_utils/dispatch_utils.hpp"
+#include "common_utils/jitter.hpp"
+#include "moe_gemm_base.hpp"
+#include "moe_gemm_inst.h"
+#include "ocl_v2/utils/fused_ops_jitter.hpp"
+
+namespace ov::intel_gpu::ocl {
+namespace {
+#ifdef ENABLE_ONEDNN_FOR_GPU
+inline bool is_prefill_stage(const RuntimeParams& params) {
+ const auto target_seq_len = params.input_layouts[0].get_partial_shape()[0];
+ const auto num_offsets = params.input_layouts[3].get_partial_shape()[0];
+ if (num_offsets.is_dynamic())
+ return false;
+ if (target_seq_len.is_dynamic())
+ return false;
+ return (target_seq_len.get_length() / num_offsets.get_length()) > 1;
+}
+#endif
+
+class MoEGemmImpl : public PrimitiveImplOCL {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoEGemmImpl)
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ static constexpr bool prefill = true;
+
+ Stage::Ptr regular_micro_single_token = make_stage<MoEGemmMicroGenerator>(!prefill);
+ Stage::Ptr regular_micro_multi_tokens = make_stage<MoEGemmMicroGenerator>(prefill);
+#endif
+
+ explicit MoEGemmImpl() : PrimitiveImplOCL(MoEGemm::get_type_info_static()) {}
+ explicit MoEGemmImpl(const RuntimeParams& impl_param) : MoEGemmImpl() {
+ auto params = impl_param;
+ GPU_DEBUG_TRACE_DETAIL << "create stages for dynamic = " << params.is_dynamic() << "\n";
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ add_stage(regular_micro_multi_tokens, params);
+ add_stage(regular_micro_single_token, params);
+#endif
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<MoEGemmImpl>(this);
+ }
+
+ void update_rt_params(const primitive_inst& instance) override {
+ if (m_rt_params == nullptr) {
+ m_rt_params = std::make_unique<MoEGemmRuntimeParams>();
+ }
+ update_stages_flags(instance);
+ auto rtp = static_cast<MoEGemmRuntimeParams*>(m_rt_params.get());
+ rtp->num_actually_used_experts = instance.get_input_layout(moe_gemm::MoEGemmInputIdx::EXPERTS_IDS).get_shape()[0];
+ GPU_DEBUG_TRACE_DETAIL << "moe_gemm :: num_actually_used_experts = " << rtp->num_actually_used_experts << "\n";
+ }
+
+ void update(primitive_inst& inst, const kernel_impl_params& impl_params) override {
+ PrimitiveImplOCL::update(inst, impl_params);
+ inst.update_shape_info_tensor(impl_params);
+ update_rt_params(inst);
+ }
+
+ [[nodiscard]] event::ptr execute(const std::vector<event::ptr>& events, primitive_inst& instance) override {
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ const auto& params = *instance.get_impl_params();
+ bool is_prefill = is_prefill_stage(params);
+ update_rt_params(instance);
+ if (is_prefill) {
+ if (has_stage(regular_micro_multi_tokens)) {
+ GPU_DEBUG_TRACE_DETAIL << "Execute prefill micro_multi_tokens stage" << std::endl;
+ return execute_stage(events, instance, regular_micro_multi_tokens);
+ } else {
+ OPENVINO_THROW("Prefill stage is not available");
+ }
+ } else {
+ return execute_stage(events, instance, regular_micro_single_token);
+ }
+#else
+ OPENVINO_THROW("moe_gemm is only supported on systolic platforms.");
+#endif
+ return nullptr;
+ }
+};
+} // namespace
+
+std::unique_ptr<primitive_impl> MoEGemm::create_impl(const program_node& node, const RuntimeParams& params) const {
+ assert(node.is_type<moe_gemm>());
+ return std::make_unique<MoEGemmImpl>(params);
+}
+} // namespace ov::intel_gpu::ocl
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::moe_gemm)
+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::MoEGemmImpl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.hpp
new file mode 100644
index 00000000000..aa03b7de4bd
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.hpp
@@ -0,0 +1,104 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "program_node.h"
+#include "registry/implementation_manager.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+
+namespace ov::intel_gpu::ocl {
+
+struct MoEGemm : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("ocl::moe_gemm")
+
+ explicit MoEGemm(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;
+
+ [[nodiscard]] bool validate_impl(const program_node& node) const override {
+ const auto& device_info = node.get_program().get_engine().get_device_info();
+ // TODO: only micro kernel is available now for moe_gemm
+ if (!device_info.supports_immad)
+ return false;
+
+ static const std::vector<format> supported_fmts = {
+ format::bfyx,
+ };
+
+ static const std::vector<ov::element::Type_t> supported_activation_types = {
+ ov::element::f16,
+ ov::element::i8,
+ ov::element::u8,
+ };
+
+ static const std::vector<ov::element::Type_t> supported_weight_types = {
+ ov::element::f16,
+ ov::element::u4,
+ ov::element::i4,
+ ov::element::i8,
+ ov::element::u8,
+ };
+
+ static const std::vector<ov::element::Type_t> supported_quant_param_types = {
+ ov::element::f16,
+ ov::element::u4,
+ ov::element::i4,
+ ov::element::i8,
+ ov::element::u8,
+ ov::element::i32,
+ };
+
+ static const std::vector<ov::element::Type_t> supported_mask_types = {
+ ov::element::i32,
+ };
+
+ auto desc = *(node.get_kernel_impl_params()->typed_desc<moe_gemm>());
+ auto layer_id = desc.id;
+
+ size_t input_idx = moe_gemm::MoEGemmInputIdx::INPUT;
+ if (!one_of(node.get_input_layout(input_idx).format, supported_fmts) ||
+ !one_of(node.get_input_layout(input_idx).data_type, supported_activation_types)) {
+ DO_NOT_USE_THIS_KERNEL(layer_id);
+ }
+
+ input_idx = moe_gemm::MoEGemmInputIdx::WEIGHT;
+ if (!one_of(node.get_input_layout(input_idx).format, supported_fmts) || !one_of(node.get_input_layout(input_idx).data_type, supported_weight_types)) {
+ DO_NOT_USE_THIS_KERNEL(layer_id);
+ }
+
+ std::vector<cldnn::data_types> quantized_types = {data_types::u4, data_types::i4, data_types::u8, data_types::i8};
+ bool has_quant_weight = false;
+ if (std::any_of(quantized_types.begin(), quantized_types.end(), [&](const cldnn::data_types& t) -> bool {
+ return t == node.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT).data_type;
+ })) {
+ has_quant_weight = true;
+ }
+
+ input_idx = moe_gemm::MoEGemmInputIdx::BIAS;
+ if (desc.has_bias) {
+ if (!one_of(node.get_input_layout(input_idx).format, supported_fmts) ||
+ !one_of(node.get_input_layout(input_idx).data_type, supported_activation_types)) {
+ DO_NOT_USE_THIS_KERNEL(layer_id);
+ }
+ }
+
+ if (has_quant_weight) {
+ size_t quant_params_idx_start =
+ desc.has_bias ? static_cast<size_t>(moe_gemm::MoEGemmInputIdx::WEIGHT_SCALE) : static_cast<size_t>(moe_gemm::MoEGemmInputIdx::WEIGHT_SCALE - 1);
+ for (size_t i = quant_params_idx_start; i < node.get_input_layouts().size(); i++) {
+ if (!one_of(node.get_input_layout(i).format, supported_fmts) | !one_of(node.get_input_layout(i).data_type, supported_quant_param_types)) {
+ DO_NOT_USE_THIS_KERNEL(layer_id);
+ }
+ }
+ }
+
+ const auto& output_layout = node.get_output_layout(0);
+ if (!one_of(output_layout.format, supported_fmts) || !one_of(output_layout.data_type, supported_activation_types)) {
+ DO_NOT_USE_THIS_KERNEL(layer_id);
+ }
+
+ return true;
+ }
+};
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_base.hpp
new file mode 100644
index 00000000000..58db39911bb
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_base.hpp
@@ -0,0 +1,26 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "../primitive_ocl_base.hpp"
+#include "../utils/kernel_generator.hpp"
+#include "common_utils/jitter.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "moe_gemm_inst.h"
+#include "openvino/core/type.hpp"
+
+namespace ov::intel_gpu::ocl {
+struct MoEGemmRuntimeParams : public ImplRuntimeParams {
+ int32_t num_actually_used_experts = 0;
+};
+
+struct MoEGemmBase : public KernelGenerator {
+ MoEGemmBase(std::string_view name, std::string_view suffix) : KernelGenerator(name, suffix) {}
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override = 0;
+ Arguments get_arguments_desc(const RuntimeParams& params) const override = 0;
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override = 0;
+};
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.cpp
new file mode 100644
index 00000000000..46b64c97aba
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.cpp
@@ -0,0 +1,337 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+// clang-format off
+// Put this file at first to avoid incorrect header files includes order.
+// For example, intel_gpu/runtime/utils.hpp will causes compiling error in hash<dnnl::impl::primitive_hashing::key_t>
+#include "moe_gemm_gen_micro.hpp"
+
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "intel_gpu/primitives/moe_gemm.hpp"
+#include "ocl_v2/utils/jitter.hpp"
+#include "moe_gemm_inst.h"
+#include "../utils/kernel_generator.hpp"
+
+// clang-format on
+namespace ov::intel_gpu::ocl {
+
+static size_t get_subgroup_size(gpu_arch arch) {
+ switch (arch) {
+ case gpu_arch::gen9:
+ case gpu_arch::gen11:
+ case gpu_arch::xe_lp:
+ case gpu_arch::xe_hp:
+ case gpu_arch::xe_hpg:
+ return 8;
+ case gpu_arch::xe_hpc:
+ case gpu_arch::xe2:
+ case gpu_arch::xe3:
+ return 16;
+ default:
+ return 0;
+ }
+}
+
+JitConstants MoEGemmMicroGenerator::get_jit_constants(const kernel_impl_params& params, const micro::Package& moe_gemm, const moe_config& cfg) const {
+ const auto& device_info = params.get_device_info();
+ auto jit = make_base_jit_constants(params);
+ jit.make("SUBGROUP_SIZE", get_subgroup_size(device_info.arch));
+ std::vector<moe_gemm::MoEGemmInputIdx> input_ids = {moe_gemm::MoEGemmInputIdx::INPUT,
+ moe_gemm::MoEGemmInputIdx::WEIGHT,
+ moe_gemm::MoEGemmInputIdx::EXPERTS_IDS,
+ moe_gemm::MoEGemmInputIdx::INPUT_OFFSET_PER_EXPERT,
+ moe_gemm::MoEGemmInputIdx::INPUT_TOKENS_LENS};
+ bool has_bias = cfg.has_bias;
+ bool is_u4_i4 = (params.input_layouts[1].data_type == data_types::u4 || params.input_layouts[1].data_type == data_types::i4);
+ auto weight_idx = moe_gemm::MoEGemmInputIdx::WEIGHT;
+ auto bias_idx = moe_gemm::MoEGemmInputIdx::BIAS;
+ auto scale_idx = cfg.weight_scale_idx;
+ auto zp_idx = cfg.weight_zp_idx;
+ const auto& weight_shape = params.input_layouts[weight_idx].get_shape();
+ if (cfg.is_weight_quantized) {
+ const auto& scale_shape = params.input_layouts[scale_idx].get_shape();
+ const auto& bias_shape = params.input_layouts[bias_idx].get_shape();
+ if (has_bias) {
+ jit.make("BIAS_DT", to_ocl_type(data_types::f16));
+ jit.make("BIAS_STRIDE", bias_shape[1] * bias_shape[2]);
+ }
+ input_ids.push_back((moe_gemm::MoEGemmInputIdx)(static_cast<int32_t>(scale_idx)));
+ if (!cfg.is_weight_symmetric_quantized)
+ input_ids.push_back((moe_gemm::MoEGemmInputIdx)(static_cast<int32_t>(zp_idx)));
+
+ jit.make("WEIGHT_SCALE_DT", to_ocl_type(data_types::f16));
+ if (cfg.weight_group_size > 0)
+ jit.make("NUM_GROUPS", scale_shape[2]);
+ else
+ jit.make("NUM_GROUPS", 1);
+
+ if (is_u4_i4) {
+ size_t stride = weight_shape.size() == 4 ? (weight_shape[1] * weight_shape[2] * weight_shape[3]) / 2 : (weight_shape[1] * weight_shape[2]) / 2;
+ jit.make("EXPERT_STRIDE", stride);
+ jit.make("WEIGHT_COMPRESSED_INT4", 1);
+ } else {
+ jit.make("EXPERT_STRIDE", (weight_shape[1] * weight_shape[2]));
+ }
+ if (!cfg.is_weight_symmetric_quantized)
+ jit.make("WEIGHT_ZP_DT", to_ocl_type(data_types::f16));
+ } else {
+ jit.make("EXPERT_STRIDE", params.input_layouts[1].get_shape()[1] * params.input_layouts[1].get_shape()[2]);
+ }
+
+ const auto& in_offsets_map = params.in_port_to_shape_info_offset;
+ const auto& out_offsets_map = params.out_port_to_shape_info_offset;
+ for (size_t i = 0; i < input_ids.size(); i++) {
+ const size_t tensor_id = input_ids[i];
+ jit.add(make_layout_jit_constants("INPUT" + to_code_string(i), params.input_layouts[tensor_id], in_offsets_map.at(tensor_id)));
+ }
+ jit.add(make_layout_jit_constants("OUTPUT", params.output_layouts[0], out_offsets_map.at(0)));
+ jit.make("INPUT_STRIDE",
+ params.input_layouts[1].get_shape().size() == 4 ? params.input_layouts[1].get_shape()[2] * params.input_layouts[1].get_shape()[3]
+ : params.input_layouts[1].get_shape()[2]);
+ jit.make("OUTPUT_STRIDE", params.input_layouts[1].get_shape()[1]);
+ if (!m_is_prefill)
+ jit.make("IS_GENERATE", 1);
+ if (cfg.has_batch_dim) {
+ jit.make("INPUT_SEQ_LEN", "INPUT0_FEATURE_NUM");
+ } else {
+ jit.make("INPUT_SEQ_LEN", "INPUT0_BATCH_NUM");
+ }
+ auto slm_size = moe_gemm.getSetting("slm_size");
+ if (slm_size > 0)
+ jit.make("USE_SLM", 1);
+ return jit;
+}
+
+static micro::Type convert_type(ov::element::Type t) {
+ switch (t) {
+ case ov::element::f32:
+ return micro::Type::f32;
+ case ov::element::f16:
+ return micro::Type::f16;
+ case ov::element::i8:
+ return micro::Type::s8;
+ case ov::element::u8:
+ return micro::Type::u8;
+ case ov::element::i32:
+ return micro::Type::s32;
+ case ov::element::u4:
+ return micro::Type::u4;
+ case ov::element::i4:
+ return micro::Type::s4;
+ default:
+ break;
+ }
+ OPENVINO_THROW("Unsupported element type: ", t);
+}
+
+std::mutex MoEGemmMicroGenerator::mtx;
+void MoEGemmMicroGenerator::init_microkernels(const kernel_impl_params& params, micro::Package& gemm_moe, bool is_prefill) noexcept {
+ // TODO: Remove once micro API is thread safe
+ std::lock_guard<std::mutex> l(mtx);
+ auto moe_cfg = get_moe_cfg(params);
+ const auto& device_info = params.get_device_info();
+ micro::HWInformation hw_info;
+ hw_info.euCount = device_info.execution_units_count;
+ hw_info.gmdid = device_info.ip_version;
+ hw_info.systolicAvailable = device_info.supports_immad;
+ const auto& weight_shape = params.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT).get_shape();
+ size_t m = weight_shape[1];
+ size_t n = is_prefill ? 32 : 8;
+ size_t k = weight_shape.size() == 4 ? weight_shape[2] * weight_shape[3] : weight_shape[2];
+ GPU_DEBUG_TRACE_DETAIL << "init_microkernels for " << (is_prefill ? "prefill" : "generate") << " : Seq_len:" << n << " Ofm:" << m << " K:" << k << "\n";
+
+ micro::GEMMProblem problem_moe;
+ micro::GEMMProtocol::Options opts_moe;
+ opts_moe.slmPtr = true;
+ enum class MICRO_DIMENSIONALITY { NONE = -1, SCALAR = 0, VECTOR = 1, MATRIX = 2 };
+
+ if (moe_cfg.is_weight_quantized) {
+ problem_moe.Ta = micro::Type::f16;
+ problem_moe.Ta_ext = convert_type(params.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT).data_type);
+ problem_moe.A.setAlignment(micro::alignment_for_ld(k * problem_moe.Ta_ext));
+
+ problem_moe.Ta_scale = convert_type(params.get_input_layout(moe_cfg.weight_scale_idx).data_type); // zp dt
+ problem_moe.A_scale.setAlignment(2);
+ problem_moe.A_scale.layout = micro::MatrixLayout::T;
+ problem_moe.asPtrDims = static_cast<int>(MICRO_DIMENSIONALITY::MATRIX);
+
+ problem_moe.aqGroupM = 1;
+ problem_moe.aqGroupK =
+ (static_cast<int32_t>(moe_cfg.weight_group_size) == -1) ? static_cast<int32_t>(k) : static_cast<int32_t>(moe_cfg.weight_group_size);
+
+ opts_moe.scaleA = true;
+ if (!moe_cfg.is_weight_symmetric_quantized) {
+ const auto& zp_layout = params.get_input_layout(moe_cfg.weight_zp_idx);
+ const auto zp_dt = convert_type(zp_layout.data_type);
+ problem_moe.Tao = zp_dt;
+ problem_moe.AO.setAlignment(zp_dt == gemmstone::Type::u4 ? 1 : static_cast<int32_t>(zp_dt.size()));
+ problem_moe.AO.layout = micro::MatrixLayout::T;
+ problem_moe.aoPtrDims = static_cast<int>(MICRO_DIMENSIONALITY::MATRIX);
+ // Calculate A/B row/column sums in kernel.
+ problem_moe.aOffset = micro::ABOffset::Calc;
+ opts_moe.offsetA = true;
+ }
+ } else {
+ problem_moe.Ta = problem_moe.Ta_ext = convert_type(params.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT).data_type);
+ problem_moe.A.setAlignment(micro::alignment_for_ld(k * problem_moe.Ta));
+ }
+
+ problem_moe.Tb = problem_moe.Tb_ext = micro::Type::f16;
+ problem_moe.Tc = micro::Type::f32;
+ problem_moe.Tc_ext = micro::Type::f32;
+ problem_moe.Ts = problem_moe.Tc;
+ problem_moe.A.layout = micro::MatrixLayout::T;
+ problem_moe.B.layout = micro::MatrixLayout::N;
+ problem_moe.C.layout = micro::MatrixLayout::N;
+ problem_moe.B.setAlignment(micro::alignment_for_ld(k * problem_moe.Tb));
+ problem_moe.C.setAlignment(static_cast<int32_t>(problem_moe.Tc.size()));
+
+ /* Set up problem_moe size information */
+ micro::SizeParams sizes;
+ sizes.n = static_cast<int32_t>(n);
+ sizes.m = static_cast<int32_t>(m);
+ sizes.k = static_cast<int32_t>(k);
+ sizes.batch = static_cast<int32_t>(1);
+
+ GPU_DEBUG_TRACE_DETAIL << "problem_moe:" << problem_moe.toString() << "\n";
+ GPU_DEBUG_TRACE_DETAIL << "sizes to select gemm : m : " << m << " n : " << n << " k : " << k << std::endl;
+ try {
+ /* Ask microkernel provider for microkernel */
+ gemm_moe = micro::select_gemm_microkernel(opts_moe, hw_info, sizes, problem_moe);
+ } catch (const std::runtime_error& ex) {
+ OPENVINO_THROW("Can't create moe micro kernel: ", ex.what());
+ }
+}
+DispatchDataFunc MoEGemmMicroGenerator::get_dispatch_data_func() const {
+ return DispatchDataFunc{[this](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ assert(!params.is_dynamic());
+
+ auto* rtp = static_cast<MoEGemmRuntimeParams*>(rt_params);
+ const auto& desc = params.typed_desc<moe_gemm>();
+ const auto& device_info = params.get_device_info();
+ const auto& gemm_p = kd.micro_kernels[0]->p;
+ auto sg_per_wg_n = static_cast<size_t>(gemm_p.getSetting("sg_per_wg_n"));
+ auto sg_per_wg_m = static_cast<size_t>(gemm_p.getSetting("sg_per_wg_m"));
+ auto sg_tile_m = gemm_p.getSetting("sg_tile_m");
+ auto sg_tile_n = gemm_p.getSetting("sg_tile_n");
+
+ auto& wgs = kd.params.workGroups;
+ auto& scalars = kd.params.scalars;
+ scalars.clear();
+ scalars.reserve(3);
+
+ auto input_layout = params.get_input_layout(moe_gemm::MoEGemmInputIdx::INPUT);
+ auto experts_weight_layout = params.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT);
+ auto output_layout = params.get_output_layout();
+
+ size_t n = desc->has_batch_dim ? input_layout.get_shape()[1] : input_layout.get_shape()[0];
+ 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];
+ wgs.local = {sg_per_wg_m * get_subgroup_size(device_info.arch), sg_per_wg_n, 1};
+ wgs.global = {align_to(ceil_div(m, sg_tile_m), sg_per_wg_m) * get_subgroup_size(device_info.arch),
+ align_to(ceil_div(n, sg_tile_n), sg_per_wg_n),
+ static_cast<size_t>(rtp->num_actually_used_experts)};
+ ScalarDescriptor s_m{ScalarDescriptor::Types::INT32};
+ s_m.v.s32 = static_cast<int32_t>(m);
+ scalars.push_back(s_m);
+ ScalarDescriptor s_k{ScalarDescriptor::Types::INT32};
+ s_k.v.s32 = static_cast<int32_t>(k);
+ scalars.push_back(s_k);
+ }};
+}
+
+std::string MoEGemmMicroGenerator::get_build_options(const kernel_impl_params& params) const {
+ auto base_options = KernelGenerator::get_build_options(params);
+ std::string extra_options = " -Dcl_intel_dot_accumulate";
+ extra_options += " -Dcl_intel_global_float_atomic";
+ extra_options += " -Dcl_intel_subgroup_matrix_multiply_accumulate";
+ extra_options += " -Dcl_intel_subgroup_split_matrix_multiply_accumulate";
+ return base_options + extra_options;
+}
+
+Arguments MoEGemmMicroGenerator::get_arguments_desc(const kernel_impl_params& params) const {
+ Arguments args;
+ if (params.is_dynamic())
+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
+ auto cfg = get_moe_cfg(params);
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::INPUT});
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::WEIGHT});
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::EXPERTS_IDS});
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::INPUT_OFFSET_PER_EXPERT});
+
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::INPUT_TOKENS_LENS});
+
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // m
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // k
+
+ if (cfg.has_bias) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, moe_gemm::MoEGemmInputIdx::BIAS});
+ }
+
+ if (cfg.is_weight_quantized) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(cfg.weight_scale_idx)});
+ if (!cfg.is_weight_symmetric_quantized)
+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(cfg.weight_zp_idx)});
+ }
+
+ return args;
+}
+
+KernelData MoEGemmMicroGenerator::get_kernel_data(const kernel_impl_params& params) const {
+ micro::Package moe_gemm;
+ const auto& device_info = params.get_device_info();
+ try {
+ init_microkernels(params, moe_gemm, m_is_prefill);
+ } catch (const std::runtime_error& ex) {
+ OPENVINO_THROW("MoEGemmMicroGenerator::get_kernel_data() - can't init microkernels: ", ex.what());
+ }
+
+ auto jit = get_jit_constants(params, moe_gemm, get_moe_cfg(params));
+
+ KernelData kd;
+ kd.code = std::make_shared<KernelString>();
+ kd.code->language = kernel_language::OCLC_V2;
+ kd.code->entry_point = get_entry_point(params);
+ kd.code->jit = "";
+ kd.code->undefs = "";
+ kd.code->options = get_build_options(params);
+ kd.code->batch_compilation = false;
+ kd.code->has_microkernels = true;
+ kd.code->str = build_code(get_kernel_name(), jit, kd.code->entry_point);
+
+ kd.params.arguments = get_arguments_desc(params);
+
+ kd.update_dispatch_data_func = get_dispatch_data_func();
+
+ kd.need_args_update = true;
+ kd.need_dispatch_data_update = true;
+
+ /* Generate microkernel shims */
+ micro::ShimOptions shim_options;
+ shim_options.subgroupSize = static_cast<int32_t>(get_subgroup_size(device_info.arch));
+ shim_options.useTileOps = true;
+ shim_options.decorator = "moe";
+
+ kd.code->jit += generateShim(moe_gemm, micro::HostLanguage::OpenCL_C, shim_options);
+ if (moe_gemm.grfMin > 128) {
+ kd.code->options += " -cl-intel-256-GRF-per-thread";
+ }
+
+ kd.micro_kernels.push_back(std::make_shared<micro::MicroKernelPackage>(moe_gemm));
+
+ // Micro kernel is using slm implicitly inside the kernel.
+ // Therefore the slm should be allocated.
+ uint32_t slm_size = kd.micro_kernels[0]->p.getSetting("slm_size");
+ kd.params.local_memory_args.clear();
+ if (slm_size > 0) {
+ kd.params.local_memory_args.push_back(slm_size);
+ kd.params.arguments.push_back({ArgumentDescriptor::Types::LOCAL_MEMORY_SIZE, slm_size});
+ }
+ return kd;
+}
+} // namespace ov::intel_gpu::ocl
+#endif
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.hpp
new file mode 100644
index 00000000000..56597f92279
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.hpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <mutex>
+
+#include "../utils/kernel_generator.hpp"
+#include "common_utils/jitter.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "intel_gpu/primitives/moe_gemm.hpp"
+#include "micro_utils.hpp"
+#include "moe_gemm_base.hpp"
+#include "moe_gemm_gen_opt.hpp"
+#include "moe_gemm_inst.h"
+#include "ocl_v2/utils/jitter.hpp"
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+namespace ov::intel_gpu::ocl {
+#ifdef ENABLE_ONEDNN_FOR_GPU
+# include "micro_utils.hpp"
+
+class MoEGemmMicroGenerator : public MoEGemmOptGeneratorBase {
+public:
+ explicit MoEGemmMicroGenerator(bool prefill) : MoEGemmOptGeneratorBase("moe_gemm", prefill ? "_prefill" : "_generate"), m_is_prefill(prefill) {}
+
+ [[nodiscard]] std::string get_build_options(const kernel_impl_params& params) const override;
+
+ [[nodiscard]] KernelData get_kernel_data(const kernel_impl_params& params) const override;
+
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params) const override {
+ OPENVINO_THROW("Use overloaded version instead");
+ }
+ [[nodiscard]] JitConstants get_jit_constants(const kernel_impl_params& params, const micro::Package& moe_gemm, const moe_config& cfg) const;
+
+ [[nodiscard]] Arguments get_arguments_desc(const kernel_impl_params& params) const override;
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
+
+ static void init_microkernels(const kernel_impl_params& params, micro::Package& gemm_moe, bool is_prefill) noexcept;
+
+ bool m_is_prefill;
+ static std::mutex mtx;
+};
+#endif
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_opt.hpp
new file mode 100644
index 00000000000..1044c13c041
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_opt.hpp
@@ -0,0 +1,67 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "../utils/kernel_generator.hpp"
+#include "common_utils/jitter.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "intel_gpu/primitives/moe_gemm.hpp"
+#include "moe_gemm_base.hpp"
+#include "moe_gemm_inst.h"
+#include "ocl_v2/utils/jitter.hpp"
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+namespace ov::intel_gpu::ocl {
+
+using RuntimeParams = kernel_impl_params;
+
+struct moe_config {
+ bool has_bias = false;
+ bool is_activation_quantized = false;
+ bool is_activation_symmetric_quantized = false;
+ bool is_weight_quantized = false;
+ bool is_weight_symmetric_quantized = false;
+ int32_t weight_group_size = -1;
+ int32_t weight_scale_idx = -1;
+ int32_t weight_zp_idx = -1;
+ bool has_batch_dim = false;
+};
+
+class MoEGemmOptGeneratorBase : public MoEGemmBase {
+public:
+ MoEGemmOptGeneratorBase(std::string_view name, std::string_view stage) : MoEGemmBase(name, stage) {}
+
+ static moe_config get_moe_cfg(const kernel_impl_params& params) {
+ moe_config moe_cfg;
+ auto desc = params.typed_desc<moe_gemm>();
+ std::vector<cldnn::data_types> quantized_types = {data_types::u4, data_types::i4, data_types::u8, data_types::i8};
+ moe_cfg.has_bias = desc->has_bias;
+ if (std::any_of(quantized_types.begin(), quantized_types.end(), [=](const cldnn::data_types& t) -> bool {
+ return t == params.input_layouts[1].data_type;
+ })) {
+ moe_cfg.is_weight_quantized = true;
+ if (desc->has_bias) {
+ moe_cfg.weight_scale_idx = moe_gemm::MoEGemmInputIdx::WEIGHT_SCALE;
+ moe_cfg.weight_zp_idx = moe_gemm::MoEGemmInputIdx::WEIGHT_ZP;
+ } else {
+ moe_cfg.weight_scale_idx = moe_gemm::MoEGemmInputIdx::WEIGHT_SCALE - 1;
+ moe_cfg.weight_zp_idx = moe_gemm::MoEGemmInputIdx::WEIGHT_ZP - 1;
+ }
+ const auto& weight_shape = params.input_layouts[moe_gemm::MoEGemmInputIdx::WEIGHT].get_shape();
+ // experts weight : [#experts, ofm, num_groups, group_size]
+ auto k = (weight_shape.size() == 4) ? weight_shape[2] * weight_shape[3] : weight_shape[2];
+ auto scale_group_dim = params.input_layouts[moe_cfg.weight_scale_idx].get_shape().size() - 2;
+ auto num_scale_groups = (weight_shape.size() == 4) ? params.input_layouts[moe_cfg.weight_scale_idx].get_shape()[scale_group_dim] : 1;
+ moe_cfg.weight_group_size = k / num_scale_groups;
+ if (static_cast<int32_t>(params.input_layouts.size()) > moe_cfg.weight_zp_idx) {
+ moe_cfg.is_weight_symmetric_quantized = false;
+ } else {
+ moe_cfg.is_weight_symmetric_quantized = true;
+ }
+ }
+ moe_cfg.has_batch_dim = desc->has_batch_dim;
+ return moe_cfg;
+ }
+};
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.cpp
new file mode 100644
index 00000000000..105ef397358
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.cpp
@@ -0,0 +1,148 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "moe_scatter_reduction.hpp"
+
+#include "../common_utils/dispatch_utils.hpp"
+#include "../common_utils/jitter.hpp"
+#include "../primitive_ocl_base.hpp"
+#include "../utils/kernel_generator.hpp"
+#include "intel_gpu/primitives/moe_scatter_reduction.hpp"
+
+namespace ov::intel_gpu::ocl {
+namespace {
+
+class MoeScatterReductionRefGenerator : public KernelGenerator {
+public:
+ MoeScatterReductionRefGenerator() : KernelGenerator("moe_scatter_reduction_ref") {}
+
+protected:
+ static size_t GetBlockSize(const RuntimeParams& params) {
+ const auto& input = params.get_input_layout(0);
+ size_t vec_size = 1;
+ switch (input.data_type) {
+ case ov::element::i8:
+ case ov::element::u8:
+ vec_size = 16;
+ break;
+ case ov::element::f16:
+ vec_size = 8;
+ break;
+ case ov::element::f32:
+ case ov::element::i32:
+ vec_size = 4;
+ break;
+ case ov::element::i64:
+ vec_size = 2;
+ break;
+ default:
+ vec_size = 1;
+ break;
+ }
+ return vec_size;
+ }
+
+ static auto calc_thread_count(RuntimeParams& params, const size_t vector_size, const size_t hidden_size) {
+ auto max_wgs = params.get_program().get_engine().get_device_info().max_work_group_size;
+ const uint64_t threads_needed = (hidden_size + vector_size - 1) / vector_size;
+ size_t local_threads_needed = std::min(threads_needed, max_wgs);
+ size_t batches_per_thread = 1;
+ size_t unaligned_elements = 0;
+
+ if (threads_needed <= max_wgs) {
+ batches_per_thread = 1;
+ unaligned_elements = hidden_size % vector_size;
+ } else {
+ batches_per_thread = (threads_needed + max_wgs - 1) / max_wgs;
+ auto new_block_size = batches_per_thread * vector_size;
+ unaligned_elements = hidden_size % new_block_size;
+
+ local_threads_needed = hidden_size / new_block_size;
+ auto partialblock = (hidden_size % new_block_size != 0) ? 1 : 0;
+ local_threads_needed += static_cast<size_t>(partialblock);
+ }
+
+ return std::tuple{local_threads_needed, batches_per_thread, unaligned_elements};
+ }
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ auto in_l = params.input_layouts[0];
+ auto hidden_size = extract_channel(ChannelName::Y, in_l);
+ auto block_size = GetBlockSize(params);
+ auto [local_threads_count, batches_per_thread, unaligned_elements] = calc_thread_count(const_cast<RuntimeParams&>(params), block_size, hidden_size);
+
+ const auto& desc = params.typed_desc<moe_scatter_reduction>();
+
+ jit.make("ACTIVE_EXPERTS", desc->num_active_experts_per_token);
+ jit.make("HIDDEN_SIZE", hidden_size);
+ jit.make("VEC_BLK_SIZE", block_size);
+ jit.make("BATCHES_PER_THREAD", batches_per_thread);
+ jit.make("UNALIGNED_ELEMENTS", unaligned_elements);
+
+ return jit;
+ }
+
+ Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ Arguments args;
+ if (params.is_dynamic()) {
+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
+ }
+
+ uint32_t num_of_inputs = 7;
+
+ for (uint32_t i = 0; i < num_of_inputs; i++) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, i});
+ }
+
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+
+ return args;
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ auto& wgs = kd.params.workGroups;
+
+ if (!params.is_dynamic()) {
+ size_t hidden_size = params.input_layouts[0].get_shape().back();
+ auto block_size = GetBlockSize(params);
+ auto [local_threads_count, batches_per_thread, unaligned_elements] =
+ calc_thread_count(const_cast<RuntimeParams&>(params), block_size, hidden_size);
+
+ auto num_tokens = extract_channel(ChannelName::BATCH, params.input_layouts[1]);
+
+ wgs.global = {num_tokens * local_threads_count, 1, 1};
+ wgs.local = {local_threads_count, 1, 1};
+ }
+ }};
+ }
+};
+
+class MoeScatterReductionRefImpl : public PrimitiveImplOCL {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoeScatterReductionRefImpl)
+
+ Stage::Ptr moe_scatter_reduction = make_stage<MoeScatterReductionRefGenerator>();
+
+ MoeScatterReductionRefImpl() : PrimitiveImplOCL(MoeScatterReductionRef::get_type_info_static()) {}
+ MoeScatterReductionRefImpl(const program_node& node, const RuntimeParams& params) : MoeScatterReductionRefImpl() {
+ add_stage(moe_scatter_reduction, params);
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<MoeScatterReductionRefImpl>(this);
+ }
+};
+
+} // namespace
+
+std::unique_ptr<primitive_impl> MoeScatterReductionRef::create_impl(const program_node& node, const RuntimeParams& params) const {
+ assert(node.is_type<moe_scatter_reduction>());
+ return std::make_unique<MoeScatterReductionRefImpl>(node, params);
+}
+
+} // namespace ov::intel_gpu::ocl
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::moe_scatter_reduction)
+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::ocl::MoeScatterReductionRefImpl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.hpp
new file mode 100644
index 00000000000..64af22a039a
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction.hpp
@@ -0,0 +1,55 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <utility>
+
+#include "program_node.h"
+#include "registry/implementation_manager.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+
+namespace ov::intel_gpu::ocl {
+
+struct MoeScatterReductionRef : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("ocl::moe_scatter_reduction")
+ explicit MoeScatterReductionRef(shape_types shape_type, ValidateFunc vf = nullptr) : ImplementationManager(impl_types::ocl, shape_type, std::move(vf)) {}
+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;
+ [[nodiscard]] bool validate_impl(const program_node& node) const override {
+ static constexpr std::array supported_fmts = {
+ format::bfyx,
+ };
+
+ static constexpr std::array supported_types = {
+ ov::element::f32,
+ ov::element::f16,
+ ov::element::i32,
+ ov::element::i64,
+ ov::element::i8,
+ ov::element::u8,
+ };
+
+ const auto& in0_layout = node.get_input_layout(0);
+ const auto& out_layout = node.get_output_layout(0);
+ const auto& input_pshapes = in0_layout.get_partial_shape();
+
+ if (input_pshapes.rank().get_length() != 3 || input_pshapes[2].is_dynamic()) {
+ return false;
+ }
+
+ if (!one_of(in0_layout.format, supported_fmts) || !one_of(out_layout.format, supported_fmts)) {
+ return false;
+ }
+
+ if (!one_of(in0_layout.data_type, supported_types) || !one_of(out_layout.data_type, supported_types)) {
+ return false;
+ }
+
+ return true;
+ }
+};
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gather_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gather_ref.cl
new file mode 100644
index 00000000000..4e7995cf7cc
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gather_ref.cl
@@ -0,0 +1,45 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+
+#define VLOAD CAT(vload, VEC_BLK_SIZE)
+#define VSTORE CAT(vstore, VEC_BLK_SIZE)
+
+KERNEL(moe_gather_ref)(
+ OPTIONAL_SHAPE_INFO_ARG
+ const __global INPUT0_TYPE* input,
+ const __global INPUT1_TYPE* token_indices,
+ __global OUTPUT_TYPE* output
+)
+{
+ const uint token_group_id = (uint)get_group_id(0);
+ const uint threads_index = (uint)get_local_id(0);
+
+#if UNALIGNED_ELEMENTS > 0
+ if ((threads_index == get_local_size(0) - 1) && (UNALIGNED_ELEMENTS > 0)) {
+ for (uint i = 0; i < UNALIGNED_ELEMENTS; i++) {
+ const INPUT1_TYPE token_index = token_indices[token_group_id] * HIDDEN_SIZE;
+
+ const uint dest_index = token_group_id * HIDDEN_SIZE;
+
+ const uint input_pos = token_index + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD + i;
+ const uint output_pos = dest_index + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD + i;
+ output[output_pos] = input[input_pos];
+ }
+ } else {
+#endif
+ for (uint i = 0; i < BATCHES_PER_THREAD; i++) {
+ const INPUT1_TYPE token_index = token_indices[token_group_id] * HIDDEN_SIZE + i * VEC_BLK_SIZE;
+
+ const uint dest_index = token_group_id * HIDDEN_SIZE + i * VEC_BLK_SIZE;
+
+ const uint input_pos = token_index + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD;
+ const uint output_pos = dest_index + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD;
+ VSTORE(VLOAD(0, &input[input_pos]), 0, &output[output_pos]);
+ }
+#if UNALIGNED_ELEMENTS > 0
+ }
+#endif
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gemm.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gemm.cl
new file mode 100644
index 00000000000..68fce4c329a
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gemm.cl
@@ -0,0 +1,115 @@
+/*******************************************************************************
+* Copyright 2025 Intel Corporation
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+#include "include/batch_headers/generic_vector_ops.cl"
+#include "include/batch_headers/tile_ops.cl"
+#ifdef BIAS_DT
+DECLARE_2D_TILE(bias_tile_type, BIAS_DT, SUBGROUP_SIZE, ugemm_moe_sg_tile_m, 1, 1, 1)
+#endif
+DECLARE_2D_TILE(ugemm_moe_c_type_half, half, SUBGROUP_SIZE, ugemm_moe_c_type_block0, ugemm_moe_c_type_block1, ugemm_moe_c_type_nblock0, ugemm_moe_c_type_nblock1)
+DECLARE_2D_TILE_COPY_REBLOCK(ugemm_moe_c_type, SUBGROUP_SIZE, ugemm_moe_c_type_block0, ugemm_moe_c_type_block1, ugemm_moe_c_type_nblock0, ugemm_moe_c_type_nblock1,
+ ugemm_moe_c_type_half, SUBGROUP_SIZE, ugemm_moe_c_type_block0, ugemm_moe_c_type_block1, ugemm_moe_c_type_nblock0, ugemm_moe_c_type_nblock1)
+
+__attribute__((intel_reqd_sub_group_size(SUBGROUP_SIZE)))
+KERNEL(moe_gemm)(OPTIONAL_SHAPE_INFO_ARG
+ const global INPUT0_TYPE *input_ptr,
+#ifdef WEIGHT_COMPRESSED_INT4
+ const global uchar *weight_ptr,
+#else
+ const global INPUT1_TYPE *weight_ptr,
+#endif
+ global OUTPUT_TYPE *out_ptr,
+ const global INPUT2_TYPE *experts_ids,
+ const global INPUT3_TYPE * input_offset_per_expert,
+ const global INPUT4_TYPE *n_array,
+ int m, int k
+#ifdef BIAS_DT
+ , const global BIAS_DT *bias_ptr
+#endif
+#ifdef WEIGHT_COMPRESSED_INT4
+ , const global WEIGHT_SCALE_DT *weight_scales
+ #ifdef WEIGHT_ZP_DT
+ , const global WEIGHT_ZP_DT *weight_zps
+ #endif
+#endif
+#ifdef USE_SLM
+ , local int* slm
+#endif
+) {
+ uint batch = get_group_id(2);
+ int input_offset = input_offset_per_expert[batch];
+
+ #ifdef IS_GENERATE
+ if (INPUT_SEQ_LEN > 1) {
+ #endif
+ input_ptr += input_offset * INPUT_STRIDE;
+ #ifdef IS_GENERATE
+ }
+ #endif
+ out_ptr += input_offset * OUTPUT_STRIDE;
+ weight_ptr += experts_ids[batch] * EXPERT_STRIDE;
+
+ int ld_input = k;
+#ifdef WEIGHT_COMPRESSED_INT4
+ weight_scales += experts_ids[batch] * m * NUM_GROUPS;
+ #ifdef WEIGHT_ZP_DT
+ weight_zps += experts_ids[batch] * m * NUM_GROUPS;
+ #endif
+#endif
+ int ld_weight = k;
+ int cur_n_tokens = n_array[batch];
+
+ uint sg_i = sub_group_broadcast(get_local_id(0)/SUBGROUP_SIZE, 0);
+ uint sg_j = sub_group_broadcast(get_local_id(1), 0);
+
+ uint wg_i0 = get_group_id(0) * ugemm_moe_wg_tile_m;
+ uint wg_j0 = get_group_id(1) * ugemm_moe_wg_tile_n;
+ uint sg_i0 = wg_i0 + sg_i * ugemm_moe_sg_tile_m;
+ uint sg_j0 = wg_j0 + sg_j * ugemm_moe_sg_tile_n;
+#ifdef WEIGHT_COMPRESSED_INT4
+ uint num_groups = NUM_GROUPS;
+#endif
+ if (wg_j0 >= cur_n_tokens)
+ return; /* early exit if outside batch */
+#ifdef USE_SLM
+ ugemm_moe_c_type c_tile = ugemm_moe(weight_ptr, ld_weight, input_ptr, ld_input, m, cur_n_tokens, k, wg_i0, wg_j0, 0, sg_i, sg_j, slm
+#else
+ ugemm_moe_c_type c_tile = ugemm_moe(weight_ptr, ld_weight, input_ptr, ld_input, m, cur_n_tokens, k, wg_i0, wg_j0, 0, sg_i, sg_j, 0
+#endif
+#ifdef WEIGHT_COMPRESSED_INT4
+ , weight_scales
+#ifdef WEIGHT_ZP_DT
+ , weight_zps
+#endif
+ , num_groups
+#endif
+);
+ ugemm_moe_c_type_half c_tile_half;
+ tile_copy_reblock(c_tile, &c_tile_half);
+
+#ifdef BIAS_DT
+ bias_ptr += (experts_ids[batch] * BIAS_STRIDE);
+ int sglid = get_sub_group_local_id();
+ const int num_cols_per_block = (ugemm_moe_c_type_block0 * ugemm_moe_c_type_block1) / SUBGROUP_SIZE; // 8
+ const int num_rows_per_block = ugemm_moe_c_type_nblock0 * ugemm_moe_c_type_nblock1; // 12
+ for (int br = 0; br < num_rows_per_block; br++) {
+ for (int bc = 0; bc < num_cols_per_block; bc++) {
+ c_tile_half.x[br][bc] += bias_ptr[sg_i0 + br * SUBGROUP_SIZE + sglid];
+ }
+ }
+#endif
+ tile_store(c_tile_half, out_ptr, m, cur_n_tokens, sg_i0, sg_j0);
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_ref.cl
new file mode 100644
index 00000000000..6e0ec365777
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_ref.cl
@@ -0,0 +1,115 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+#include "include/fetch_utils.cl"
+
+#define VLOAD CAT(vload, VEC_BLK_SIZE)
+#define VSTORE CAT(vstore, VEC_BLK_SIZE)
+#define INPUT_VEC_TYPE MAKE_VECTOR_TYPE(INPUT0_TYPE, VEC_BLK_SIZE)
+#define OUTPUT_VEC_TYPE MAKE_VECTOR_TYPE(OUTPUT_TYPE, VEC_BLK_SIZE)
+
+KERNEL(moe_scatter_reduction_ref)(
+ OPTIONAL_SHAPE_INFO_ARG
+ const __global INPUT0_TYPE* input,
+ const __global INPUT1_TYPE* experts_per_token,
+ const __global INPUT2_TYPE* expert_weights,
+ const __global INPUT3_TYPE* tokens_per_expert,
+ const __global INPUT4_TYPE* experts_start_offset,
+ const __global INPUT5_TYPE* tokens_len_per_expert,
+ const __global INPUT6_TYPE* experts_ids,
+ __global OUTPUT_TYPE* output
+)
+{
+ const uint token_group_id = (uint)get_group_id(0);
+ const uint threads_index = (uint)get_local_id(0);
+
+ OUTPUT_VEC_TYPE output_vec[BATCHES_PER_THREAD];
+ // start_offset_idx[i] = n : info for i-th expert in this thread is in the nth slot of the mask
+ __local uint start_offset_index[ACTIVE_EXPERTS];
+ __local uint input_offset;
+
+ if (threads_index < ACTIVE_EXPERTS) {
+ INPUT1_TYPE expert_id = experts_per_token[token_group_id * ACTIVE_EXPERTS + threads_index];
+ for (int i = 0; i < INPUT6_BATCH_NUM; i++) {
+ if (experts_ids[i] == expert_id) {
+ start_offset_index[threads_index] = i;
+ break;
+ }
+ }
+ }
+
+ if (threads_index == 0)
+ input_offset = 0;
+
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+#if UNALIGNED_ELEMENTS > 0
+ OUTPUT_TYPE output_scalar[UNALIGNED_ELEMENTS];
+#endif
+
+ uint dest_index = token_group_id * HIDDEN_SIZE;
+ uint output_pos = dest_index + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD;
+
+ for (uint i = 0; i < BATCHES_PER_THREAD; i++) {
+ output_vec[i] = TO_OUTPUT_TYPE(0);
+ }
+
+#if UNALIGNED_ELEMENTS > 0
+ for (uint i = 0; i < UNALIGNED_ELEMENTS; i++) {
+ output_scalar[i] = TO_OUTPUT_TYPE(0);
+ }
+#endif
+
+ for (uint i = 0; i < ACTIVE_EXPERTS; i++) {
+ INPUT1_TYPE expert_id = experts_per_token[token_group_id * ACTIVE_EXPERTS + i];
+ INPUT2_TYPE expert_weight = expert_weights[token_group_id * ACTIVE_EXPERTS + i];
+ INPUT5_TYPE token_len = tokens_len_per_expert[start_offset_index[i]];
+ INPUT4_TYPE expert_offset = experts_start_offset[start_offset_index[i]];
+
+ for (uint tid = threads_index; tid < token_len; tid += get_local_size(0)) {
+ if (tokens_per_expert[expert_offset + tid] == token_group_id) {
+ input_offset = expert_offset + tid;
+ break;
+ }
+ }
+ barrier(CLK_LOCAL_MEM_FENCE);
+ for (uint j = 0; j < BATCHES_PER_THREAD; j++) {
+ const uint input_pos = input_offset * HIDDEN_SIZE + j * VEC_BLK_SIZE + threads_index * VEC_BLK_SIZE * BATCHES_PER_THREAD;
+
+#if UNALIGNED_ELEMENTS > 0
+ if ((threads_index == get_local_size(0) - 1) && (j == 0)) {
+ uint input_pos_unaligned = input_pos;
+ for (uint k = 0; k < UNALIGNED_ELEMENTS; k++) {
+ output_scalar[k] += input[input_pos_unaligned] * expert_weight;
+ input_pos_unaligned++;
+ }
+ } else {
+#endif
+ INPUT_VEC_TYPE input_data = VLOAD(0, &input[input_pos]);
+ input_data *= expert_weight;
+ output_vec[j] += input_data;
+#if UNALIGNED_ELEMENTS > 0
+ }
+#endif
+ }
+ }
+
+#if UNALIGNED_ELEMENTS > 0
+ if ((threads_index == get_local_size(0) - 1)) {
+ uint output_pos_unaligned = output_pos;
+ for (uint s = 0; s < UNALIGNED_ELEMENTS; s++) {
+ output[output_pos_unaligned] = output_scalar[s];
+ output_pos_unaligned++;
+ }
+ } else {
+#endif
+ for (uint v = 0; v < BATCHES_PER_THREAD; v++) {
+ const uint out_pos = output_pos + v * VEC_BLK_SIZE;
+ VSTORE(output_vec[v], 0, &output[out_pos]);
+ }
+#if UNALIGNED_ELEMENTS > 0
+ }
+#endif
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
index 5fd64ded544..bb46726bcea 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
@@ -244,6 +244,7 @@ struct PrimitiveImplOCL : public cldnn::primitive_impl {
if (kd.need_args_update) {
auto args = get_arguments(instance);
args.scalars = &params.scalars;
+ args.local_memory_args = &params.local_memory_args;
GPU_DEBUG_TRACE_DETAIL << "\nExecute stage = " << stage.kernel->get_id() << '\n';
GPU_DEBUG_TRACE_DETAIL << "Configured kernel arguments:" << params.arguments.size() << '\n';
diff --git a/src/plugins/intel_gpu/src/graph/include/moe_gather_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_gather_inst.h
new file mode 100644
index 00000000000..6cdc6c48959
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/moe_gather_inst.h
@@ -0,0 +1,45 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "intel_gpu/primitives/moe_gather.hpp"
+#include "primitive_inst.h"
+
+#include <memory>
+#include <string>
+
+namespace cldnn {
+
+template <>
+struct typed_program_node<moe_gather> : public typed_program_node_base<moe_gather> {
+ using parent = typed_program_node_base<moe_gather>;
+ typed_program_node(const std::shared_ptr<moe_gather> prim, program& prog) : parent(prim, prog) {
+ support_padding_all(true);
+ }
+
+public:
+ using parent::parent;
+
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {}; }
+ program_node& input() const { return get_dependency(0); }
+};
+
+using moe_gather_node = typed_program_node<moe_gather>;
+
+template <>
+class typed_primitive_inst<moe_gather> : public typed_primitive_inst_base<moe_gather> {
+ using parent = typed_primitive_inst_base<moe_gather>;
+ using parent::parent;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(moe_gather_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(moe_gather_node const& node, kernel_impl_params const& impl_param);
+ static std::string to_string(moe_gather_node const& node);
+
+ typed_primitive_inst(network& network, moe_gather_node const& node);
+};
+
+using moe_gather_inst = typed_primitive_inst<moe_gather>;
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/include/moe_gemm_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_gemm_inst.h
new file mode 100644
index 00000000000..3f687164225
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/moe_gemm_inst.h
@@ -0,0 +1,45 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "intel_gpu/primitives/moe_gemm.hpp"
+#include "primitive_inst.h"
+
+#include <memory>
+#include <string>
+
+namespace cldnn {
+
+template <>
+struct typed_program_node<moe_gemm> : public typed_program_node_base<moe_gemm> {
+ using parent = typed_program_node_base<moe_gemm>;
+ typed_program_node(const std::shared_ptr<moe_gemm> prim, program& prog) : parent(prim, prog) {
+ support_padding_all(true);
+ }
+
+public:
+ using parent::parent;
+
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {}; }
+ program_node& input() const { return get_dependency(0); }
+};
+
+using moe_gemm_node = typed_program_node<moe_gemm>;
+
+template <>
+class typed_primitive_inst<moe_gemm> : public typed_primitive_inst_base<moe_gemm> {
+ using parent = typed_primitive_inst_base<moe_gemm>;
+ using parent::parent;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(moe_gemm_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(moe_gemm_node const& node, kernel_impl_params const& impl_param);
+ static std::string to_string(moe_gemm_node const& node);
+
+ typed_primitive_inst(network& network, moe_gemm_node const& node);
+};
+
+using moe_gemm_inst = typed_primitive_inst<moe_gemm>;
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/include/moe_mask_gen_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_mask_gen_inst.h
new file mode 100644
index 00000000000..c5f3c2cf745
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/moe_mask_gen_inst.h
@@ -0,0 +1,82 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "intel_gpu/primitives/moe_mask_gen.hpp"
+#include "primitive_inst.h"
+
+#include <memory>
+#include <string>
+
+namespace cldnn {
+
+template <>
+struct typed_program_node<moe_mask_gen> : public typed_program_node_base<moe_mask_gen> {
+ using parent = typed_program_node_base<moe_mask_gen>;
+ typed_program_node(const std::shared_ptr<moe_mask_gen> prim, program& prog) : parent(prim, prog) {
+ support_padding_all(true);
+ }
+
+public:
+ using parent::parent;
+
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {}; }
+ program_node& input() const { return get_dependency(0); }
+};
+
+using moe_mask_gen_node = typed_program_node<moe_mask_gen>;
+
+template <>
+class typed_primitive_inst<moe_mask_gen> : public typed_primitive_inst_base<moe_mask_gen> {
+ using parent = typed_primitive_inst_base<moe_mask_gen>;
+ using parent::parent;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(moe_mask_gen_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(moe_mask_gen_node const& node, kernel_impl_params const& impl_param);
+ static std::string to_string(moe_mask_gen_node const& node);
+
+ typed_primitive_inst(network& network, moe_mask_gen_node const& node);
+};
+
+using moe_mask_gen_inst = typed_primitive_inst<moe_mask_gen>;
+
+
+template <>
+struct typed_program_node<moe_mask_gen_reshape> : public typed_program_node_base<moe_mask_gen_reshape> {
+ using parent = typed_program_node_base<moe_mask_gen_reshape>;
+ typed_program_node(const std::shared_ptr<moe_mask_gen_reshape> prim, program& prog) : parent(prim, prog) {
+ can_be_optimized(true);
+ }
+
+public:
+ using parent::parent;
+
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {4}; }
+ program_node& input() const { return get_dependency(0); }
+};
+
+using moe_mask_gen_reshape_node = typed_program_node<moe_mask_gen_reshape>;
+
+template <>
+class typed_primitive_inst<moe_mask_gen_reshape> : public typed_primitive_inst_base<moe_mask_gen_reshape> {
+ using parent = typed_primitive_inst_base<moe_mask_gen_reshape>;
+ using parent::parent;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(moe_mask_gen_reshape_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(moe_mask_gen_reshape_node const& node, kernel_impl_params const& impl_param);
+ static std::string to_string(moe_mask_gen_reshape_node const& node);
+
+ typed_primitive_inst(network& network, moe_mask_gen_reshape_node const& node);
+ void update_output_memory() override;
+private:
+ void on_execute() override;
+};
+
+using moe_mask_gen_reshape_inst = typed_primitive_inst<moe_mask_gen_reshape>;
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/include/moe_scatter_reduction_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_scatter_reduction_inst.h
new file mode 100644
index 00000000000..6cf9f70560c
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/moe_scatter_reduction_inst.h
@@ -0,0 +1,46 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "intel_gpu/primitives/moe_scatter_reduction.hpp"
+#include "primitive_inst.h"
+
+#include <memory>
+#include <string>
+
+namespace cldnn {
+
+template <>
+struct typed_program_node<moe_scatter_reduction> : public typed_program_node_base<moe_scatter_reduction> {
+ using parent = typed_program_node_base<moe_scatter_reduction>;
+ typed_program_node(const std::shared_ptr<moe_scatter_reduction> prim, program& prog) : parent(prim, prog) {
+ support_padding_all(true);
+ }
+
+public:
+ using parent::parent;
+
+ std::vector<size_t> get_shape_infer_dependencies() const override { return {}; }
+ program_node& input() const { return get_dependency(0); }
+};
+
+using moe_scatter_reduction_node = typed_program_node<moe_scatter_reduction>;
+
+template <>
+class typed_primitive_inst<moe_scatter_reduction> : public typed_primitive_inst_base<moe_scatter_reduction> {
+ using parent = typed_primitive_inst_base<moe_scatter_reduction>;
+ using parent::parent;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(moe_scatter_reduction_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(moe_scatter_reduction_node const& node, kernel_impl_params const& impl_param);
+ static std::string to_string(moe_scatter_reduction_node const& node);
+
+ typed_primitive_inst(network& network, moe_scatter_reduction_node const& node);
+};
+
+using moe_scatter_reduction_inst = typed_primitive_inst<moe_scatter_reduction>;
+} // namespace cldnn
+
diff --git a/src/plugins/intel_gpu/src/graph/moe_gather.cpp b/src/plugins/intel_gpu/src/graph/moe_gather.cpp
new file mode 100644
index 00000000000..20f987b8e3f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/moe_gather.cpp
@@ -0,0 +1,61 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_gather_inst.h"
+#include "primitive_type_base.h"
+#include "json_object.h"
+#include "to_string_utils.h"
+#include <string>
+#include <vector>
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_gather)
+
+layout moe_gather_inst::calc_output_layout(moe_gather_node const& node, kernel_impl_params const& impl_param) {
+ auto output_layouts = calc_output_layouts<ov::PartialShape>(node, impl_param);
+ return output_layouts[0];
+}
+
+template <typename ShapeType>
+std::vector<layout> moe_gather_inst::calc_output_layouts(const moe_gather_node& /*node*/, const kernel_impl_params& impl_param) {
+ const auto& desc = impl_param.typed_desc<moe_gather>();
+ const auto num_experts_per_token = desc->num_experts_per_token;
+ const auto& in_layout = impl_param.input_layouts[0];
+ const auto& input_shape = in_layout.get<ShapeType>();
+ const auto& hidden_size = input_shape[input_shape.size() - 1];
+ OPENVINO_ASSERT(hidden_size.is_static(), impl_param.desc->id, " hidden size dimension (shape[1]) must be static");
+
+ if (in_layout.is_dynamic()) {
+ return {layout{ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), ov::Dimension(hidden_size)},
+ in_layout.data_type, in_layout.format}};
+ }
+ const auto num_tokens = input_shape.size() == 2 ? input_shape[0] : desc->has_batch_dim ? input_shape[1] : input_shape[0];
+ if (desc->has_batch_dim) {
+ const auto& out_shape = ov::PartialShape{ov::Dimension(1), ov::Dimension(num_tokens * num_experts_per_token), ov::Dimension(hidden_size)};
+ return {layout{out_shape, in_layout.data_type, in_layout.format}};
+ } else {
+ const auto& out_shape = ov::PartialShape{ov::Dimension(num_tokens * num_experts_per_token), ov::Dimension(1), ov::Dimension(hidden_size)};
+ return {layout{out_shape, in_layout.data_type, in_layout.format}};
+ }
+}
+
+template std::vector<layout> moe_gather_inst::calc_output_layouts<ov::PartialShape>(moe_gather_node const& node, const kernel_impl_params& impl_param);
+
+std::string moe_gather_inst::to_string(moe_gather_node const& node) {
+ auto node_info = node.desc_to_json();
+ auto desc = node.get_primitive();
+
+ std::stringstream primitive_description;
+
+ json_composite moe_gather_info;
+ if (desc->output_data_types[0].has_value())
+ moe_gather_info.add("out dt: ", dt_to_str(*desc->output_data_types[0]));
+ node_info->add("moe_gather info", moe_gather_info);
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+moe_gather_inst::typed_primitive_inst(network& network, moe_gather_node const& node) : parent(network, node) { }
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/moe_gemm.cpp b/src/plugins/intel_gpu/src/graph/moe_gemm.cpp
new file mode 100644
index 00000000000..58666e7a9c2
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/moe_gemm.cpp
@@ -0,0 +1,75 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_gemm_inst.h"
+#include "primitive_type_base.h"
+#include "json_object.h"
+#include "to_string_utils.h"
+#include <string>
+#include <vector>
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_gemm)
+
+layout moe_gemm_inst::calc_output_layout(moe_gemm_node const& node, kernel_impl_params const& impl_param) {
+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[1];
+}
+
+template<typename ShapeType>
+std::vector<layout> moe_gemm_inst::calc_output_layouts(moe_gemm_node const& /*node*/, const kernel_impl_params& impl_param) {
+ const auto& desc = impl_param.typed_desc<moe_gemm>();
+ size_t num_experts_per_token = desc->num_experts_per_token;
+ auto input_layout = impl_param.get_input_layout(0);
+ size_t input_rank = input_layout.get_partial_shape().size();
+ if (input_rank != 3)
+ OPENVINO_THROW("moe_gemm's input rank should be 3");
+ auto experts_layout = impl_param.get_input_layout(1);
+ auto out_n_dim = input_rank - 1;
+ auto output_shape = input_layout.get_partial_shape();
+ for (auto& o : output_shape) {
+ o = ov::Dimension::dynamic();
+ }
+ size_t n = experts_layout.get_shape()[1];
+ output_shape[out_n_dim] = ov::Dimension(n);
+
+ if (!input_layout.is_dynamic()) {
+ size_t seq_len_dim = (desc->has_batch_dim) ? 1 : 0;
+ auto m = input_layout.get_shape()[seq_len_dim];
+ if (m == 1) {
+ // first gemm (up/gate) in the generate phase
+ if (!desc->has_batch_dim) {
+ output_shape = ov::PartialShape{ov::Dimension(num_experts_per_token), ov::Dimension(1), ov::Dimension(n)};
+ } else {
+ output_shape = ov::PartialShape{ov::Dimension(1), ov::Dimension(num_experts_per_token), ov::Dimension(n)};
+ }
+ } else {
+ if (!desc->has_batch_dim) {
+ output_shape = ov::PartialShape{ov::Dimension(m), ov::Dimension(1), ov::Dimension(n)};
+ } else {
+ output_shape = ov::PartialShape{ov::Dimension(1), ov::Dimension(m), ov::Dimension(n)};
+ }
+ }
+ }
+ auto output_layout = layout{output_shape, input_layout.data_type, input_layout.format};
+ return {output_layout};
+}
+
+template std::vector<layout> moe_gemm_inst::calc_output_layouts<ov::PartialShape>(moe_gemm_node const& node, const kernel_impl_params& impl_param);
+
+std::string moe_gemm_inst::to_string(moe_gemm_node const& node) {
+ auto node_info = node.desc_to_json();
+ auto desc = node.get_primitive();
+
+ std::stringstream primitive_description;
+
+ json_composite moe_gemm_info;
+ if (desc->output_data_types[0].has_value())
+ moe_gemm_info.add("out dt: ", dt_to_str(*desc->output_data_types[0]));
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+moe_gemm_inst::typed_primitive_inst(network& network, moe_gemm_node const& node) : parent(network, node) { }
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp b/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp
new file mode 100644
index 00000000000..2e2a1de4b67
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp
@@ -0,0 +1,152 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_mask_gen_inst.h"
+#include "primitive_type_base.h"
+#include "json_object.h"
+#include "to_string_utils.h"
+#include <string>
+#include <vector>
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_mask_gen)
+
+layout moe_mask_gen_inst::calc_output_layout(moe_mask_gen_node const& node, kernel_impl_params const& impl_param) {
+ OPENVINO_THROW("moe_mask_gen has multiple outputs so only supports allow_new_shape_infer = true.");
+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[1];
+}
+
+template<typename ShapeType>
+std::vector<layout> moe_mask_gen_inst::calc_output_layouts(moe_mask_gen_node const& /*node*/, const kernel_impl_params& impl_param) {
+ std::vector<layout> output_layouts;
+ const auto& num_total_experts = impl_param.typed_desc<moe_mask_gen>()->num_total_experts;
+ const auto& num_experts_per_token = impl_param.typed_desc<moe_mask_gen>()->num_experts_per_token;
+
+ if (impl_param.get_input_layout(0).is_dynamic()) {
+ // out0: tokens_per_expert
+ auto tokens_per_expert_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ output_layouts.emplace_back(tokens_per_expert_shape, data_types::i32, format::bfyx);
+ } else {
+ const auto num_tokens = impl_param.get_input_layout(0).get_shape()[0];
+ // out0: tokens_per_expert
+ auto tokens_per_expert_shape = ov::Shape{num_tokens * num_experts_per_token};
+ output_layouts.emplace_back(tokens_per_expert_shape, data_types::i32, format::bfyx);
+ }
+ // out1: experts_info_start_idx
+ auto experts_info_start_idx_shape = ov::Shape{static_cast<size_t>(num_total_experts)};
+ output_layouts.emplace_back(experts_info_start_idx_shape, data_types::i32, format::bfyx);
+ // out2: experts_id
+ auto experts_ids = ov::Shape{static_cast<size_t>(num_total_experts)};
+ output_layouts.emplace_back(experts_ids, data_types::i32, format::bfyx);
+ // out3: tokens_lens_per_expert
+ auto tokens_lens_per_expert = ov::Shape{static_cast<size_t>(num_total_experts)};
+ output_layouts.emplace_back(tokens_lens_per_expert, data_types::i32, format::bfyx);
+ // out4: num_actual_expert
+ auto num_actual_used_experts_shape = ov::Shape{static_cast<size_t>(1)};
+ output_layouts.emplace_back(num_actual_used_experts_shape, data_types::i32, format::bfyx);
+ return output_layouts;
+}
+
+template std::vector<layout> moe_mask_gen_inst::calc_output_layouts<ov::PartialShape>(moe_mask_gen_node const& node, const kernel_impl_params& impl_param);
+
+std::string moe_mask_gen_inst::to_string(moe_mask_gen_node const& node) {
+ auto node_info = node.desc_to_json();
+ auto desc = node.get_primitive();
+ std::stringstream primitive_description;
+
+ json_composite moe_mask_gen_info;
+ for (auto o : desc->output_data_types) {
+ if (o.has_value())
+ moe_mask_gen_info.add("out dt: ", dt_to_str(*o));
+ }
+
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+moe_mask_gen_inst::typed_primitive_inst(network& network, moe_mask_gen_node const& node) : parent(network, node) { }
+
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_mask_gen_reshape)
+layout moe_mask_gen_reshape_inst::calc_output_layout(moe_mask_gen_reshape_node const& node, kernel_impl_params const& impl_param) {
+ OPENVINO_THROW("moe_mask_gen has multiple outputs so only supports allow_new_shape_infer = true.");
+ return calc_output_layouts<ov::PartialShape>(node, impl_param)[1];
+}
+
+template<typename ShapeType>
+std::vector<layout> moe_mask_gen_reshape_inst::calc_output_layouts(moe_mask_gen_reshape_node const& /*node*/, const kernel_impl_params& impl_param) {
+ std::vector<layout> output_layouts;
+ if (!impl_param.memory_deps.count(4)) {
+ auto out_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ output_layouts.emplace_back(out_shape, data_types::i32, format::bfyx);
+ output_layouts.emplace_back(out_shape, data_types::i32, format::bfyx);
+ output_layouts.emplace_back(out_shape, data_types::i32, format::bfyx);
+ output_layouts.emplace_back(out_shape, data_types::i32, format::bfyx);
+ return output_layouts;
+ }
+ auto num_actually_used_experts =
+ read_vector<int32_t>(impl_param.memory_deps.at(moe_mask_gen::MoEMaskGenOutputIdx::NUM_ACTUALLY_USED_EXPERTS), impl_param.get_stream())[0];
+ // tokens_per_expert
+ output_layouts.emplace_back(impl_param.get_input_layout(0));
+ // experts_info_start_idx
+ auto experts_info_start_idx_shape = ov::Shape{static_cast<size_t>(num_actually_used_experts)};
+ output_layouts.emplace_back(experts_info_start_idx_shape, data_types::i32, format::bfyx);
+ // experts_id
+ auto experts_ids_shape = ov::Shape{static_cast<size_t>(num_actually_used_experts)};
+ output_layouts.emplace_back(experts_ids_shape, data_types::i32, format::bfyx);
+ // tokens_lens_per_expert
+ auto tokens_lens_per_expert_shape = ov::Shape{static_cast<size_t>(num_actually_used_experts)};
+ output_layouts.emplace_back(tokens_lens_per_expert_shape, data_types::i32, format::bfyx);
+ return output_layouts;
+}
+
+template std::vector<layout> moe_mask_gen_reshape_inst::calc_output_layouts<ov::PartialShape>
+ (moe_mask_gen_reshape_node const& node, const kernel_impl_params& impl_param);
+
+std::string moe_mask_gen_reshape_inst::to_string(moe_mask_gen_reshape_node const& node) {
+ auto node_info = node.desc_to_json();
+ auto desc = node.get_primitive();
+ std::stringstream primitive_description;
+
+ json_composite moe_mask_gen_reshape_info;
+ for (auto o : desc->output_data_types) {
+ if (o.has_value())
+ moe_mask_gen_reshape_info.add("out dt: ", dt_to_str(*o));
+ }
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+moe_mask_gen_reshape_inst::typed_primitive_inst(network& network, moe_mask_gen_reshape_node const& node) : parent(network, node, false) {
+ update_output_memory();
+}
+
+void moe_mask_gen_reshape_inst::on_execute() {
+ update_output_memory();
+}
+
+void moe_mask_gen_reshape_inst::update_output_memory() {
+ if (!can_be_optimized())
+ return;
+ if (_node != nullptr)
+ build_deps();
+
+ _mem_allocated = false;
+ if (_impl_params->get_input_layout(0).is_dynamic())
+ return;
+ for (size_t i = 0; i < _outputs.size(); ++i) {
+ if (static_cast<bool>(_outputs[i]) && get_node().get_program().get_config().get_enable_memory_pool()) {
+ _network.get_memory_pool().release_memory(_outputs[i].get(), get_node().get_unique_id(), get_node().id(), _network.get_id());
+ }
+ }
+
+ _outputs = {
+ _network.get_engine().reinterpret_buffer(input_memory(0), _impl_params->get_output_layout(0)),
+ _network.get_engine().reinterpret_buffer(input_memory(1), _impl_params->get_output_layout(1)),
+ _network.get_engine().reinterpret_buffer(input_memory(2), _impl_params->get_output_layout(2)),
+ _network.get_engine().reinterpret_buffer(input_memory(3), _impl_params->get_output_layout(3))
+ };
+}
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/moe_scatter_reduction.cpp b/src/plugins/intel_gpu/src/graph/moe_scatter_reduction.cpp
new file mode 100644
index 00000000000..40f0b52f833
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/moe_scatter_reduction.cpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_scatter_reduction_inst.h"
+#include "primitive_type_base.h"
+#include "json_object.h"
+#include "to_string_utils.h"
+#include <string>
+#include <vector>
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(moe_scatter_reduction)
+
+layout moe_scatter_reduction_inst::calc_output_layout(moe_scatter_reduction_node const& node, kernel_impl_params const& impl_param) {
+ auto output_layouts = calc_output_layouts<ov::PartialShape>(node, impl_param);
+ return output_layouts[0];
+}
+
+template<typename ShapeType>
+std::vector<layout> moe_scatter_reduction_inst::calc_output_layouts(moe_scatter_reduction_node const& /*node*/, const kernel_impl_params& impl_param) {
+ const auto& desc = impl_param.typed_desc<moe_scatter_reduction>();
+ const auto num_active_experts_per_token = desc->num_active_experts_per_token;
+
+ const auto& input_shape = impl_param.input_layouts[0].get<ShapeType>();
+ const auto& hidden_size = input_shape[input_shape.size() - 1];
+ OPENVINO_ASSERT(hidden_size.is_static(), impl_param.desc->id, " hidden size dimension (shape[1]) must be static");
+ if (impl_param.input_layouts[0].is_dynamic())
+ return {layout{ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), ov::Dimension(hidden_size)},
+ impl_param.input_layouts[0].data_type, impl_param.input_layouts[0].format}};
+ if (desc->has_batch_dim) {
+ const auto num_tokens = impl_param.input_layouts[0].get_shape()[1] / num_active_experts_per_token;
+ const auto& out_shape = ov::PartialShape{1, ov::Dimension(num_tokens), ov::Dimension(hidden_size)};
+ return {layout{out_shape, impl_param.input_layouts[0].data_type, impl_param.input_layouts[0].format}};
+ } else {
+ const auto num_tokens = impl_param.input_layouts[0].get_shape()[0] / num_active_experts_per_token;
+ const auto& out_shape = ov::PartialShape{ov::Dimension(num_tokens), 1, ov::Dimension(hidden_size)};
+ return {layout{out_shape, impl_param.input_layouts[0].data_type, impl_param.input_layouts[0].format}};
+ }
+}
+
+template std::vector<layout> moe_scatter_reduction_inst::calc_output_layouts<ov::PartialShape>(moe_scatter_reduction_node const& node,
+ const kernel_impl_params& impl_param);
+
+std::string moe_scatter_reduction_inst::to_string(moe_scatter_reduction_node const& node) {
+ auto node_info = node.desc_to_json();
+ auto desc = node.get_primitive();
+
+ std::stringstream primitive_description;
+
+ json_composite moe_scatter_reduction_info;
+ moe_scatter_reduction_info.add("input id", node.input().id());
+ if (desc->output_data_types[0].has_value())
+ moe_scatter_reduction_info.add("out dt: ", dt_to_str(*desc->output_data_types[0]));
+ node_info->add("moe_scatter_reduction_info", moe_scatter_reduction_info);
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+moe_scatter_reduction_inst::typed_primitive_inst(network& network, moe_scatter_reduction_node const& node) : parent(network, node) { }
+} // namespace cldnn
+
diff --git a/src/plugins/intel_gpu/src/graph/registry/moe_gather_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/moe_gather_impls.cpp
new file mode 100644
index 00000000000..096f651a572
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/registry/moe_gather_impls.cpp
@@ -0,0 +1,28 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "registry.hpp"
+#include "intel_gpu/primitives/moe_gather.hpp"
+#include "primitive_inst.h"
+
+#if OV_GPU_WITH_OCL
+ #include "impls/ocl_v2/moe/moe_gather.hpp"
+#endif
+
+namespace ov {
+namespace intel_gpu {
+
+using namespace cldnn;
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_gather>::get_implementations() {
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoeGatherRef, shape_types::static_shape)
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoeGatherRef, shape_types::dynamic_shape)
+ };
+
+ return impls;
+}
+
+} // namespace intel_gpu
+} // namespace ov
diff --git a/src/plugins/intel_gpu/src/graph/registry/moe_gemm_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/moe_gemm_impls.cpp
new file mode 100644
index 00000000000..6acb029e376
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/registry/moe_gemm_impls.cpp
@@ -0,0 +1,27 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "registry.hpp"
+#include "intel_gpu/primitives/moe_gemm.hpp"
+#include "primitive_inst.h"
+
+#if OV_GPU_WITH_OCL
+ #include "impls/ocl_v2/moe/moe_gemm.hpp"
+#endif
+
+
+namespace ov::intel_gpu {
+
+using namespace cldnn;
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_gemm>::get_implementations() {
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoEGemm, shape_types::static_shape)
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoEGemm, shape_types::dynamic_shape)
+ };
+
+ return impls;
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/graph/registry/moe_mask_gen_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/moe_mask_gen_impls.cpp
new file mode 100644
index 00000000000..cdb0037d433
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/registry/moe_mask_gen_impls.cpp
@@ -0,0 +1,31 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "registry.hpp"
+#include "intel_gpu/primitives/moe_mask_gen.hpp"
+#include "primitive_inst.h"
+
+namespace ov::intel_gpu {
+
+using namespace cldnn;
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_mask_gen>::get_implementations() {
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_GET_INSTANCE_CPU(moe_mask_gen, shape_types::static_shape)
+ OV_GPU_GET_INSTANCE_CPU(moe_mask_gen, shape_types::dynamic_shape)
+ };
+
+ return impls;
+}
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_mask_gen_reshape>::get_implementations() {
+ // This primitive only used for shape inference, so no implelementation
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_GET_INSTANCE_CPU(moe_mask_gen_reshape, shape_types::static_shape)
+ OV_GPU_GET_INSTANCE_CPU(moe_mask_gen_reshape, shape_types::dynamic_shape)
+ };
+
+ return impls;
+}
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/graph/registry/moe_scatter_reduction_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/moe_scatter_reduction_impls.cpp
new file mode 100644
index 00000000000..535e9564ed5
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/registry/moe_scatter_reduction_impls.cpp
@@ -0,0 +1,29 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "registry.hpp"
+#include "intel_gpu/primitives/moe_scatter_reduction.hpp"
+#include "primitive_inst.h"
+
+#if OV_GPU_WITH_OCL
+ #include "impls/ocl_v2/moe/moe_scatter_reduction.hpp"
+#endif
+
+namespace ov {
+namespace intel_gpu {
+
+using namespace cldnn;
+
+const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<moe_scatter_reduction>::get_implementations() {
+ static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoeScatterReductionRef, shape_types::dynamic_shape)
+ OV_GPU_CREATE_INSTANCE_OCL(ocl::MoeScatterReductionRef, shape_types::static_shape)
+ };
+
+ return impls;
+}
+
+} // namespace intel_gpu
+} // namespace ov
+
diff --git a/src/plugins/intel_gpu/src/graph/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/registry/registry.hpp
index 341503a2322..910c3a07292 100644
--- a/src/plugins/intel_gpu/src/graph/registry/registry.hpp
+++ b/src/plugins/intel_gpu/src/graph/registry/registry.hpp
@@ -166,6 +166,11 @@ REGISTER_IMPLS(strided_slice);
REGISTER_IMPLS(tile);
REGISTER_IMPLS(col2im);
REGISTER_IMPLS(vl_sdpa);
+REGISTER_IMPLS(moe_mask_gen);
+REGISTER_IMPLS(moe_mask_gen_reshape);
+REGISTER_IMPLS(moe_gemm);
+REGISTER_IMPLS(moe_scatter_reduction);
+REGISTER_IMPLS(moe_gather);
REGISTER_DEFAULT_IMPLS(assign, CPU_S, CPU_D);
REGISTER_DEFAULT_IMPLS(read_value, CPU_S, CPU_D);
diff --git a/src/plugins/intel_gpu/src/graph/swiglu.cpp b/src/plugins/intel_gpu/src/graph/swiglu.cpp
index ffd5333318c..e8670681abc 100644
--- a/src/plugins/intel_gpu/src/graph/swiglu.cpp
+++ b/src/plugins/intel_gpu/src/graph/swiglu.cpp
@@ -3,6 +3,7 @@
//
#include "ov_ops/glu.hpp"
+#include "intel_gpu/op/swiglu_with_clamp.hpp"
#include "glu_shape_inference.hpp"
#include "swiglu_inst.h"
@@ -28,16 +29,23 @@ std::vector<layout> swiglu_inst::calc_output_layouts(swiglu_node const& /*node*/
auto input_layout = impl_param.get_input_layout();
auto output_type = impl_param.desc->output_data_types[0].value_or(input_layout.data_type);
auto output_format = input_layout.format;
-
- ov::op::internal::GLU op;
- op.set_axis(desc->axis);
- op.set_split_lengths(desc->split_lengths);
-
std::vector<ShapeType> input_shapes = {impl_param.get_input_layout(0).get<ShapeType>()};
- std::vector<ShapeType> output_shapes = shape_infer(&op, input_shapes);
-
- return { layout(output_shapes[0], output_type, output_format) };
+ if (desc->clamp_max != std::numeric_limits<float>::max() || desc->clamp_min != std::numeric_limits<float>::lowest()) {
+ std::vector<ov::PartialShape> input_shapes = {impl_param.get_input_layout(0).get_partial_shape()};
+ ov::intel_gpu::op::SwiGluWithClamp op;
+ op.set_glu_stride(desc->glu_stride);
+ op.set_axis(desc->axis);
+ std::vector<ov::PartialShape> output_shapes = shape_infer(&op, input_shapes);
+ return {layout(output_shapes[0], output_type, output_format)};
+ } else {
+ ov::op::internal::GLU op;
+ op.set_axis(desc->axis);
+ op.set_split_lengths(desc->glu_stride);
+
+ std::vector<ShapeType> output_shapes = shape_infer(&op, input_shapes);
+ return {layout(output_shapes[0], output_type, output_format)};
+ }
}
template std::vector<layout> swiglu_inst::calc_output_layouts<ov::PartialShape>(swiglu_node const& node,
@@ -53,7 +61,16 @@ std::string swiglu_inst::to_string(swiglu_node const& node) {
json_composite swiglu_info;
swiglu_info.add("input_id", input.id());
swiglu_info.add("axis", desc->axis);
- swiglu_info.add("split_lengths", desc->split_lengths);
+ swiglu_info.add("glu_stride", desc->glu_stride);
+ swiglu_info.add("gate_idx", desc->gate_idx);
+ swiglu_info.add("swish_beta", desc->swish_beta);
+ swiglu_info.add("up_add_val", desc->up_add_val);
+ if (desc->clamp_max != std::numeric_limits<float>::max()) {
+ swiglu_info.add("clamp_max", desc->clamp_max);
+ }
+ if (desc->clamp_min != std::numeric_limits<float>::lowest()) {
+ swiglu_info.add("clamp_min", desc->clamp_min);
+ }
node_info->add("swiglu_info", swiglu_info);
node_info->dump(primitive_description);
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_opt.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_opt.cl
index 6a019091d06..b61c1927961 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_opt.cl
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_opt.cl
@@ -49,25 +49,37 @@ KERNEL(swiglu_gpu_opt)(
const __global INPUT0_TYPE* input,
__global OUTPUT_TYPE* output)
{
+#if GLU_STRIDE == 2 // alternating
const unsigned int x = (uint)get_global_linear_id();
- const unsigned int y = x + ((x / SPLIT_LENGTH) * SPLIT_LENGTH);
+ const unsigned int y = GLU_STRIDE * x;
+#else // split
+ const unsigned int x = (uint)get_global_linear_id();
+ const unsigned int y = x + ((x / GLU_STRIDE) * GLU_STRIDE);
+#endif
-#if SPLIT_TO_GLU_IDX == 0
+#if GATE_IDX == 0
ACCUMULATOR_TYPE gate = input[y];
- ACCUMULATOR_TYPE value = input[y + SPLIT_LENGTH];
+ #if GLU_STRIDE == 2
+ ACCUMULATOR_TYPE value = input[y + 1];
+ #else
+ ACCUMULATOR_TYPE value = input[y + GLU_STRIDE];
+ #endif
#else
- ACCUMULATOR_TYPE gate = input[y + SPLIT_LENGTH];
+ ACCUMULATOR_TYPE gate = input[y + GLU_STRIDE];
ACCUMULATOR_TYPE value = input[y];
#endif
-
#if GLU_TYPE == 0 // Swish
- gate /= ACCUMULATOR_VAL_ONE + native_exp(-(ACCUMULATOR_VAL_ONE * gate));
+ #if defined(CLAMP_MAX) && defined(CLAMP_MIN)
+ gate = ACCUMULATOR_MIN_FUNC(TO_OUTPUT_TYPE(CLAMP_MAX), gate);
+ value = ACCUMULATOR_MIN_FUNC(ACCUMULATOR_MAX_FUNC(TO_OUTPUT_TYPE(CLAMP_MIN), value), TO_OUTPUT_TYPE(CLAMP_MAX));
+ #endif
+ gate /= (ACCUMULATOR_VAL_ONE + native_exp(-SWISH_BETA * gate));
#elif GLU_TYPE == 1 // Gelu
gate = (GEGLU_HALF * gate * (ACCUMULATOR_VAL_ONE + (FUNC_CALL(fast_erf)(gate * GEGLU_MULT))));
#elif GLU_TYPE == 2 // Gelu_Tanh
gate = (GEGLU_HALF * gate * (ACCUMULATOR_VAL_ONE + (tanh(GEGLU_SQUARE_2_OVER_PI * gate * (ACCUMULATOR_VAL_ONE + GEGLU_MULT * gate * gate)))));
#endif
+ value = (value + UP_ADD_VAL) * gate;
- value *= gate;
output[x] = TO_OUTPUT_TYPE(value);
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_ref.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_ref.cl
index c37645cd019..a8678fc8d4b 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_ref.cl
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/swiglu_gpu_ref.cl
@@ -25,35 +25,57 @@ KERNEL(swiglu_gpu_ref)(
#if OUTPUT_DIMS == 5
const uint output_idx = OUTPUT_GET_INDEX(b, f, z, y, x);
- #if SPLIT_TO_GLU_IDX == 0
+ #if GLU_STRIDE == 2 // alternating
+ #if GATE_IDX == 0
+ const uint gate_idx = OUTPUT_GET_INDEX(b, f, z, y, x) * GLU_STRIDE;
+ const uint input_idx = gate_idx + 1;
+ #else
+ const uint input_idx = OUTPUT_GET_INDEX(b, f, z, y, x) * GLU_STRIDE;
+ const uint gate_idx = input_idx + 1;
+ #endif
+ #else // split
+ #if GATE_IDX == 0
const uint gate_idx = INPUT0_GET_INDEX(b, f, z, y, x);
- const uint input_idx = gate_idx + SPLIT_LENGTH;
- #else
+ const uint input_idx = gate_idx + GLU_STRIDE;
+ #else
const uint input_idx = INPUT0_GET_INDEX(b, f, z, y, x);
- const uint gate_idx = input_idx + SPLIT_LENGTH;
+ const uint gate_idx = input_idx + GLU_STRIDE;
+ #endif
#endif
#else // 2D spatial
const uint output_idx = OUTPUT_GET_INDEX(b, f, y, x);
- #if SPLIT_TO_GLU_IDX == 0
- const uint gate_idx = INPUT0_GET_INDEX(b, f, y, x);
- const uint input_idx = gate_idx + SPLIT_LENGTH;
- #else
- const uint input_idx = INPUT0_GET_INDEX(b, f, y, x);
- const uint gate_idx = input_idx + SPLIT_LENGTH;
+ #if GLU_STRIDE == 2 // alternating
+ #if GATE_IDX == 0
+ const uint gate_idx = (OUTPUT_GET_INDEX(b, f, y, x)) * GLU_STRIDE;
+ const uint input_idx = gate_idx + 1;
+ #else
+ const uint input_idx = (OUTPUT_GET_INDEX(b, f, y, x)) * GLU_STRIDE;
+ const uint gate_idx = input_idx + 1;
+ #endif
+ #else // split
+ #if GATE_IDX == 0
+ const uint gate_idx = INPUT0_GET_INDEX(b, f, y, x);
+ const uint input_idx = gate_idx + GLU_STRIDE;
+ #else
+ const uint input_idx = INPUT0_GET_INDEX(b, f, y, x);
+ const uint gate_idx = input_idx + GLU_STRIDE;
+ #endif
#endif
#endif
-
- ACCUMULATOR_TYPE res = ACCUMULATOR_VAL_ZERO;
-
- res = (ACCUMULATOR_TYPE)input[gate_idx];
+ ACCUMULATOR_TYPE gate = (ACCUMULATOR_TYPE) input[gate_idx];
+ ACCUMULATOR_TYPE up = (ACCUMULATOR_TYPE) input[input_idx];
#if GLU_TYPE == 0 // Swish
- res /= ACCUMULATOR_VAL_ONE + exp(-(ACCUMULATOR_VAL_ONE * res));
+ #if defined(CLAMP_MIN) && defined(CLAMP_MAX)
+ gate = ACCUMULATOR_MIN_FUNC(TO_OUTPUT_TYPE(CLAMP_MAX), gate);
+ up = ACCUMULATOR_MAX_FUNC(TO_OUTPUT_TYPE(CLAMP_MIN), ACCUMULATOR_MIN_FUNC(up, TO_OUTPUT_TYPE(CLAMP_MAX)));
+ #endif
+ gate /= (ACCUMULATOR_VAL_ONE + exp(-SWISH_BETA * gate));
#elif GLU_TYPE == 1 // Gelu
- res = (GEGLU_HALF * res * (ACCUMULATOR_VAL_ONE + (erf(res * GEGLU_MULT))));
+ gate = (GEGLU_HALF * gate * (ACCUMULATOR_VAL_ONE + (erf(gate * GEGLU_MULT))));
#elif GLU_TYPE == 2 // Gelu_Tanh
- res = (GEGLU_HALF * res * (ACCUMULATOR_VAL_ONE + (tanh(GEGLU_SQUARE_2_OVER_PI * res * (ACCUMULATOR_VAL_ONE + GEGLU_MULT * res * res)))));
+ gate = (GEGLU_HALF * gate * (ACCUMULATOR_VAL_ONE + (tanh(GEGLU_SQUARE_2_OVER_PI * gate * (ACCUMULATOR_VAL_ONE + GEGLU_MULT * gate * gate)))));
#endif
- res *= (ACCUMULATOR_TYPE)input[input_idx];
+ ACCUMULATOR_TYPE res = ((ACCUMULATOR_TYPE)up + UP_ADD_VAL) * gate;
output[output_idx] = TO_OUTPUT_TYPE(res);
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bf_tiled.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bf_tiled.cpp
index 8ba62d97e4d..54d28257651 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bf_tiled.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bf_tiled.cpp
@@ -651,8 +651,8 @@ JitConstants FullyConnected_bf_tiled::GetJitConstants(const fully_connected_para
size_t quantize_grp_size = get_dynamic_quantize_group_size(params);
if (is_swiglu_fused(params)) {
- auto split_length = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->split_length;
- auto split_to_glu_idx = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->split_to_glu_idx;
+ auto split_length = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->glu_stride;
+ auto split_to_glu_idx = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->gate_idx;
jit.AddConstant(MakeJitConstant("SWIGLU_LENGTH", split_length));
jit.AddConstant(MakeJitConstant("SWIGLU_SPLIT_TO_GLU_IDX", split_to_glu_idx));
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_gemv.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_gemv.cpp
index ce6a56fdb45..8abc9e03c7f 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_gemv.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_gemv.cpp
@@ -149,9 +149,9 @@ JitConstants FullyConnected_GEMV::GetJitConstants(const fully_connected_params&
// TODO: SWIGLU support
// if (is_swiglu_fused(params)) {
// auto split_length = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->split_length;
- // auto split_to_glu_idx = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->split_to_glu_idx;
+ // auto gate_idx = params.fused_ops[0].GetOpParams<swiglu_fuse_params>()->gate_idx;
// jit.AddConstant(MakeJitConstant("SWIGLU_LENGTH", split_length));
- // jit.AddConstant(MakeJitConstant("SWIGLU_SPLIT_TO_GLU_IDX", split_to_glu_idx));
+ // jit.AddConstant(MakeJitConstant("SWIGLU_SPLIT_TO_GLU_IDX", gate_idx));
// }
if (params.weights.GetLayout() == WeightsLayout::os_iyx_osv16) {
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.cpp
index 4f118ef7d85..aff4c924c6f 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.cpp
@@ -19,7 +19,7 @@ JitConstants SwiGLUKernelBase::GetJitConstants(const swiglu_params& params, cons
JitConstants jit = MakeBaseParamsJitConstants(params);
jit.AddConstants({MakeJitConstant("AXIS", params.axis)});
- jit.AddConstants({MakeJitConstant("SPLIT_LENGTH", params.split_length)});
+ jit.AddConstants({MakeJitConstant("GLU_STRIDE", params.glu_stride)});
jit.AddConstants({MakeJitConstant("GLU_TYPE", params.glu_type)});
jit.AddConstants({MakeJitConstant("LWS0", dispatchData.lws[0])});
jit.AddConstants({MakeJitConstant("LWS1", dispatchData.lws[1])});
@@ -33,10 +33,18 @@ JitConstants SwiGLUKernelBase::GetJitConstants(const swiglu_params& params, cons
jit.AddConstants({MakeJitConstant("GEGLU_MULT", "0.044715" + type_suffix)});
jit.AddConstants({MakeJitConstant("GEGLU_SQUARE_2_OVER_PI", "0.79788458347320556640625" + type_suffix)});
}
- jit.AddConstants({MakeJitConstant("SPLIT_TO_GLU_IDX", params.split_to_glu_idx)});
+ jit.AddConstants({MakeJitConstant("GATE_IDX", params.gate_idx)});
jit.Merge(MakeTypeJitConstants(GetAccumulatorType(params), "ACCUMULATOR"));
jit.Merge(GetTensorFriendlyWorkGroupsJit(params.outputs[0]));
+ if ((params.clamp_min > std::numeric_limits<float>::lowest() || params.clamp_max < std::numeric_limits<float>::max()) &&
+ (params.glu_type == ov::op::internal::GLU::GluType::Swish)) {
+ jit.AddConstants({MakeJitConstant("CLAMP_MAX", static_cast<float>(params.clamp_max))});
+ jit.AddConstants({MakeJitConstant("CLAMP_MIN", static_cast<float>(params.clamp_min))});
+ }
+ jit.AddConstants({MakeJitConstant("SWISH_BETA", static_cast<float>(params.swish_beta))});
+ jit.AddConstants({MakeJitConstant("UP_ADD_VAL", static_cast<float>(params.up_add_val))});
+
return jit;
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.h
index bb5625ba087..a404c52ce59 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/swiglu/swiglu_kernel_base.h
@@ -13,23 +13,43 @@ namespace kernel_selector {
// swiglu_params
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct swiglu_params : public base_params {
- swiglu_params() : base_params(KernelType::SWIGLU), axis(0), split_length(0),
- glu_type(ov::op::internal::GLU::GluType::Swish), split_to_glu_idx(0) {}
+ swiglu_params()
+ : base_params(KernelType::SWIGLU),
+ axis(0),
+ glu_stride(0),
+ glu_type(ov::op::internal::GLU::GluType::Swish),
+ gate_idx(0),
+ clamp_min(std::numeric_limits<float>::lowest()),
+ clamp_max(std::numeric_limits<float>::max()),
+ swish_beta(1.0f),
+ up_add_val(0.0f) {}
int32_t axis;
- int32_t split_length;
+ int32_t glu_stride;
ov::op::internal::GLU::GluType glu_type;
- int32_t split_to_glu_idx;
+ int32_t gate_idx;
+ float clamp_min;
+ float clamp_max;
+ float swish_beta;
+ float up_add_val;
};
struct swiglu_fuse_params : fuse_params {
- explicit swiglu_fuse_params(int32_t axis, size_t split_lengths, size_t split_to_glu_idx)
+ explicit swiglu_fuse_params(int32_t axis, size_t glu_stride, size_t gate_idx, size_t clamp_min, size_t clamp_max, float swish_beta, float up_add_val)
: fuse_params(KernelType::SWIGLU),
- axis(axis),
- split_length(split_lengths),
- split_to_glu_idx(split_to_glu_idx) {}
+ axis(axis),
+ glu_stride(glu_stride),
+ gate_idx(gate_idx),
+ clamp_min(clamp_min),
+ clamp_max(clamp_max),
+ swish_beta(swish_beta),
+ up_add_val(up_add_val) {}
int32_t axis;
- size_t split_length;
- size_t split_to_glu_idx;
+ size_t glu_stride;
+ size_t gate_idx;
+ float clamp_min;
+ float clamp_max;
+ float swish_beta;
+ float up_add_val;
};
class SwiGLUKernelBase : public KernelBaseOpenCL {
diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
new file mode 100644
index 00000000000..5c4cd75c7a4
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
@@ -0,0 +1,161 @@
+// Copyright (C) 2025 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/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>
+
+namespace ov {
+namespace op {
+namespace internal {
+using MOECompressed = ov::intel_gpu::op::MOECompressed;
+} // namespace internal
+} // namespace op
+} // namespace ov
+
+
+namespace ov::intel_gpu {
+using namespace cldnn;
+static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::MOECompressed>& op) {
+ auto inputs = p.GetInputInfo(op);
+ auto& config = op->get_config();
+ std::vector<cldnn::input_info> input_infos;
+ for (const auto& input : inputs) {
+ input_infos.push_back(cldnn::input_info(input));
+ }
+ if (config.expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {
+ // Create GEMM3_SWIGLU specific primitives
+ } else {
+ // Create GEMM2_BIAS_SWIGLU_CLAMP specific primitives
+ // input0 : input {#tokens, hidden_size}
+ // input1 : topk_weight {#tokens, num_experts_per_token}
+ // input2 : topk_idx {#tokens, num_experts_per_token}
+ // input3 : compressed_weights_input_up {#experts, ofm, num_groups, group_size}
+ // input4 : scale_input_up {#experts, ofm, num_groups, 1}
+ // input5 : bias_up {#experts, 1, ofm}
+ // input6 : compressed_weights_input_down {#experts, ofm, num_groups, group_size}
+ // input7 : scale_input_down {#experts, ofm, num_groups, 1}
+ // input8 : bias_down {#experts, 1, ofm}
+ // moe_mask_gen
+ // moe_gather
+ // moe_gemm_up + bias
+ // swiglu_with_clamp
+ // 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_prim = cldnn::moe_mask_gen(moe_mask_gen_name,
+ input_infos[2], // topk indices
+ static_cast<int32_t>(config.num_expert),
+ static_cast<int32_t>(config.top_k));
+ p.add_primitive(*op, moe_mask_gen_prim);
+ auto moe_mask_gen_reshape_prim =
+ cldnn::moe_mask_gen_reshape(moe_mask_gen_reshape_name,
+ input_info(moe_mask_gen_prim, moe_mask_gen::MoEMaskGenOutputIdx::TOKENS_PER_EXPERT),
+ input_info(moe_mask_gen_prim, moe_mask_gen::MoEMaskGenOutputIdx::EXPERTS_INFO_START_IDX),
+ input_info(moe_mask_gen_prim, moe_mask_gen::MoEMaskGenOutputIdx::EXPERTS_ID),
+ input_info(moe_mask_gen_prim, moe_mask_gen::MoEMaskGenOutputIdx::TOKENS_LENS_PER_EXPERT),
+ input_info(moe_mask_gen_prim, moe_mask_gen::MoEMaskGenOutputIdx::NUM_ACTUALLY_USED_EXPERTS));
+ p.add_primitive(*op, moe_mask_gen_reshape_prim);
+ auto moe_gather_prim = cldnn::moe_gather(moe_gather_name,
+ input_infos[0], // input
+ input_info(moe_mask_gen_reshape_name, moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_PER_EXPERT),
+ config);
+ 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_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)
+ };
+ size_t down_idx = 0;
+ if (config.has_zp) {
+ moe_gemm_up_inputs.push_back(input_infos[6]); // bias_up
+ moe_gemm_up_inputs.push_back(input_infos[4]); // scale_input_up
+ moe_gemm_up_inputs.push_back(input_infos[5]); // zp_input_up
+ down_idx = 7;
+ } else {
+ moe_gemm_up_inputs.push_back(input_infos[5]); // bias_up
+ moe_gemm_up_inputs.push_back(input_infos[4]); // scale_input_up
+ down_idx = 6;
+ }
+ auto moe_gemm_up = cldnn::moe_gemm(moe_gemm_up_name, moe_gemm_up_inputs, config);
+ moe_gemm_up.has_bias = true;
+ p.add_primitive(*op, moe_gemm_up);
+
+ // gpt-oss swiglu pattern
+ // config.expert_alpha : clamp_max
+ // config.expert_beta : swish_beta which is slightly different from usual swiglu pattern
+ // - Applied clamp
+ // - Added one for up value
+ // - Gate stride is 1 (not splitting to half and half)
+ // - config.expert_alpha : clamp_max
+ // - config.expert_beta : swish_beta
+ // 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
+ 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
+ cldnn::tensor());
+ p.add_primitive(*op, moe_swiglu_prim);
+ std::vector<cldnn::input_info> moe_gemm_down_inputs = {
+ input_info(moe_swiglu_name),
+ input_infos[down_idx], // compressed_weights_input_down
+ 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),
+ };
+
+ if (config.has_zp) {
+ moe_gemm_down_inputs.push_back(input_infos[down_idx + 3]); // bias_up
+ moe_gemm_down_inputs.push_back(input_infos[down_idx + 1]); // scale_input_up
+ moe_gemm_down_inputs.push_back(input_infos[down_idx + 2]); // zp_input_up
+ } else {
+ moe_gemm_down_inputs.push_back(input_infos[down_idx + 2]); // bias_up
+ moe_gemm_down_inputs.push_back(input_infos[down_idx + 1]); // scale_input_up
+ }
+
+ 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);
+ p.add_primitive(*op, moe_scatter_reduce_prim);
+ }
+}
+
+REGISTER_FACTORY_IMPL(internal, MOECompressed);
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/ops/swiglu_with_clamp.cpp b/src/plugins/intel_gpu/src/plugin/ops/swiglu_with_clamp.cpp
new file mode 100644
index 00000000000..7caf955bac0
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/ops/swiglu_with_clamp.cpp
@@ -0,0 +1,53 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "intel_gpu/op/swiglu_with_clamp.hpp"
+#include "intel_gpu/plugin/program_builder.hpp"
+#include "intel_gpu/plugin/common_utils.hpp"
+#include "intel_gpu/primitives/swiglu.hpp"
+
+namespace ov::op::internal {
+using GLUClamp = ov::intel_gpu::op::SwiGluWithClamp;
+}
+
+namespace ov::intel_gpu {
+
+static void CreateGLUClampOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::GLUClamp>& op) {
+ validate_inputs_count(op, {1});
+ auto inputs = p.GetInputInfo(op);
+ std::string primitive_name = layer_type_name_ID(op);
+
+ if (p.use_new_shape_infer()) {
+ auto prim = cldnn::swiglu(primitive_name,
+ inputs[0],
+ (op->get_axis() < 0 ? op->get_input_partial_shape(0).size() + op->get_axis() : op->get_axis()),
+ op->get_glu_stride(),
+ op->get_glu_type(),
+ op->get_gate_idx(),
+ op->get_clamp_min(),
+ op->get_clamp_max(),
+ op->get_swiglu_beta(),
+ op->get_up_add_val(),
+ cldnn::tensor());
+ prim.output_data_types = get_output_data_types(op);
+ p.add_primitive(*op, prim);
+ } else {
+ auto prim = cldnn::swiglu(primitive_name,
+ inputs[0],
+ (op->get_axis() < 0 ? op->get_input_partial_shape(0).size() + op->get_axis() : op->get_axis()),
+ op->get_glu_stride(),
+ op->get_glu_type(),
+ op->get_gate_idx(),
+ op->get_clamp_min(),
+ op->get_clamp_max(),
+ op->get_swiglu_beta(),
+ op->get_up_add_val(),
+ tensor_from_dims(op->get_output_shape(0)));
+ prim.output_data_types = get_output_data_types(op);
+ p.add_primitive(*op, prim);
+ }
+}
+
+REGISTER_FACTORY_IMPL(internal, GLUClamp);
+
+} // namespace ov::intel_gpu
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
new file mode 100644
index 00000000000..3f772a02f23
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp
@@ -0,0 +1,301 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "convert_moe_to_compressed.hpp"
+
+#include <memory>
+
+#include "intel_gpu/op/moe_compressed.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/moe.hpp"
+#include "openvino/op/topk.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/rt_info/keep_const_precision.hpp"
+#include "transformations/utils/utils.hpp"
+#include "openvino/op/scatter_elements_update.hpp"
+
+namespace ov::intel_gpu {
+ using namespace ov::pass::pattern;
+#define MOE_COMPRESSED_WEIGHT_PATTERN(SUFFIX)\
+ auto compressed_constant_##SUFFIX = [](const ov::Output<ov::Node>& output) {\
+ return (output.get_element_type() == ov::element::u8 || output.get_element_type() == ov::element::i8 ||\
+ output.get_element_type() == ov::element::u4 || output.get_element_type() == ov::element::i4);\
+ };\
+ \
+ auto reshape_squeeze_##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() == 3 && out_ps.size() == 2) || (in_ps.size() == 4 && out_ps.size() == 3));\
+ };\
+ \
+ auto compressed_weights_m_##SUFFIX = wrap_type<ov::op::v0::Constant>(compressed_constant_##SUFFIX);\
+ auto convert_m_##SUFFIX = wrap_type<ov::op::v0::Convert>({compressed_weights_m_##SUFFIX});\
+ \
+ auto sub_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
+ auto sub_convert_const_m_##SUFFIX = wrap_type<ov::op::v0::Convert>({sub_const_m_##SUFFIX});\
+ auto sub_with_convert_m_##SUFFIX = wrap_type<ov::op::v1::Subtract>({convert_m_##SUFFIX, sub_convert_const_m_##SUFFIX});\
+ auto sub_no_convert_m_##SUFFIX = wrap_type<ov::op::v1::Subtract>({convert_m_##SUFFIX, sub_const_m_##SUFFIX});\
+ auto subtract_m_##SUFFIX = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{sub_with_convert_m_##SUFFIX, sub_no_convert_m_##SUFFIX});\
+ \
+ auto mul_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
+ auto mul_with_sub_m_##SUFFIX = wrap_type<ov::op::v1::Multiply>({subtract_m_##SUFFIX, mul_const_m_##SUFFIX});\
+ auto mul_no_sub_m_##SUFFIX = wrap_type<ov::op::v1::Multiply>({convert_m_##SUFFIX, mul_const_m_##SUFFIX});\
+ auto mul_m_##SUFFIX = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{mul_with_sub_m_##SUFFIX, mul_no_sub_m_##SUFFIX});\
+ \
+ auto reshape_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
+ auto reshape_m_##SUFFIX = wrap_type<ov::op::v1::Reshape>({mul_m_##SUFFIX, reshape_const_m_##SUFFIX}, reshape_squeeze_##SUFFIX);\
+ auto convert_reshape_m_##SUFFIX = wrap_type<ov::op::v0::Convert>({reshape_m_##SUFFIX});\
+ \
+ auto mul2_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
+ auto mul2_m_##SUFFIX = wrap_type<ov::op::v1::Multiply>({reshape_m_##SUFFIX, mul2_const_m_##SUFFIX});\
+ \
+ auto transpose_input_##SUFFIX = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{reshape_m_##SUFFIX, mul_m_##SUFFIX});\
+ auto transpose_const_m_##SUFFIX = wrap_type<ov::op::v0::Constant>();\
+ auto transpose_m_##SUFFIX = wrap_type<ov::op::v1::Transpose>({transpose_input_##SUFFIX, transpose_const_m_##SUFFIX});\
+ \
+ auto convert_mul_m_##SUFFIX = wrap_type<ov::op::v0::Convert>({mul_m_##SUFFIX});\
+ auto compressed_weights_input_m_##SUFFIX =\
+ std::make_shared<ov::pass::pattern::op::Or>(ov::OutputVector{reshape_m_##SUFFIX, convert_reshape_m_##SUFFIX, transpose_m_##SUFFIX, \
+ mul_m_##SUFFIX, mul2_m_##SUFFIX, convert_mul_m_##SUFFIX});
+
+
+ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {
+ // gemm3 pattern start
+ auto reshape_ungroup = [](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);
+ };
+ // first proj
+ auto compressed_weights_m_0 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto zp_m_0 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+
+ auto weight_convert_const_m_0 = wrap_type<ov::op::v0::Convert>({compressed_weights_m_0}, type_matches(ov::element::f16));
+ auto zp_convert_const_m_0 = wrap_type<ov::op::v0::Convert>({zp_m_0}, type_matches(ov::element::f16));
+ auto sub_m_0 = wrap_type<ov::op::v1::Subtract>({weight_convert_const_m_0, zp_convert_const_m_0});
+
+ auto scale_m_0 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::f16));
+ auto mul_m_0 = wrap_type<ov::op::v1::Multiply>({sub_m_0, scale_m_0});
+
+ auto reshape_const_m_0 = wrap_type<ov::op::v0::Constant>();
+ auto reshape_m_0 = wrap_type<ov::op::v1::Reshape>({mul_m_0, reshape_const_m_0}, reshape_ungroup);
+
+ auto convert_m_0 = wrap_type<ov::op::v0::Convert>({reshape_m_0}, type_matches(ov::element::f32));
+
+ // second proj
+ auto compressed_weights_m_1 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto zp_m_1 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+
+ auto weight_convert_const_m_1 = wrap_type<ov::op::v0::Convert>({compressed_weights_m_1}, type_matches(ov::element::f16));
+ auto zp_convert_const_m_1 = wrap_type<ov::op::v0::Convert>({zp_m_1}, type_matches(ov::element::f16));
+ auto sub_m_1 = wrap_type<ov::op::v1::Subtract>({weight_convert_const_m_1, zp_convert_const_m_1});
+
+ auto scale_m_1 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::f16));
+ auto mul_m_1 = wrap_type<ov::op::v1::Multiply>({sub_m_1, scale_m_1});
+
+ auto reshape_const_m_1 = wrap_type<ov::op::v0::Constant>();
+ auto reshape_m_1 = wrap_type<ov::op::v1::Reshape>({mul_m_1, reshape_const_m_1}, reshape_ungroup);
+
+ auto convert_m_1 = wrap_type<ov::op::v0::Convert>({reshape_m_1}, type_matches(ov::element::f32));
+
+ // third proj
+ auto compressed_weights_m_2 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+ auto zp_m_2 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::u4));
+
+ auto weight_convert_const_m_2 = wrap_type<ov::op::v0::Convert>({compressed_weights_m_2}, type_matches(ov::element::f16));
+ auto zp_convert_const_m_2 = wrap_type<ov::op::v0::Convert>({zp_m_2}, type_matches(ov::element::f16));
+ auto sub_m_2 = wrap_type<ov::op::v1::Subtract>({weight_convert_const_m_2, zp_convert_const_m_2});
+
+ auto scale_m_2 = wrap_type<ov::op::v0::Constant>(type_matches(ov::element::f16));
+ auto mul_m_2 = wrap_type<ov::op::v1::Multiply>({sub_m_2, scale_m_2});
+
+ auto reshape_const_m_2 = wrap_type<ov::op::v0::Constant>();
+ auto reshape_m_2 = wrap_type<ov::op::v1::Reshape>({mul_m_2, reshape_const_m_2}, reshape_ungroup);
+
+ auto convert_m_2 = wrap_type<ov::op::v0::Convert>({reshape_m_2}, type_matches(ov::element::f32));
+
+ auto hidden_states_m = any_input();
+ auto routing_weights_m = any_input();
+ auto topk_m = any_input();
+
+ auto moe_root_gemm3 = wrap_type<ov::op::internal::MOE>({hidden_states_m, routing_weights_m, topk_m, convert_m_0, convert_m_1, convert_m_2},
+ [](const ov::Output<ov::Node>& output) {
+ auto moe_op = ov::as_type_ptr<ov::op::internal::MOE>(output.get_node_shared_ptr());
+ return moe_op->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ });
+ // gemm3 pattern finished
+ // =========================================================================================
+ // gemm2 pattern start
+ auto topk_input = any_input();
+
+ auto input_gemm2_m = any_input();
+ MOE_COMPRESSED_WEIGHT_PATTERN(up)
+ auto bias_up_gemm2_m = any_input();
+ MOE_COMPRESSED_WEIGHT_PATTERN(down)
+ auto bias_down_gemm2_m = any_input();
+
+
+ auto topk_gemm2_m = wrap_type<ov::op::v11::TopK>({topk_input, any_input()});
+ auto topk_indices_gemm2_m = wrap_type<ov::op::v0::Convert>({topk_gemm2_m});
+
+ auto topk_weight_softmax_m = wrap_type<ov::op::v8::Softmax>({topk_gemm2_m});
+ auto topk_weight_slice_m = wrap_type<ov::op::v8::Slice>({topk_weight_softmax_m, any_input(), any_input(), any_input(), any_input()});
+ auto topk_weight_scatter_elements_update_m = wrap_type<ov::op::v12::ScatterElementsUpdate>({any_input(), any_input(), topk_weight_slice_m, any_input()});
+ auto topk_weight_transpose_m = wrap_type<ov::op::v1::Transpose>({topk_weight_scatter_elements_update_m, any_input()});
+ auto topk_weight_reshape_m = wrap_type<ov::op::v1::Reshape>({topk_weight_transpose_m, any_input()});
+ auto topk_weight_m = wrap_type<ov::op::v0::Unsqueeze>({topk_weight_reshape_m, any_input()});
+
+ auto moe_root_gemm2 =
+ wrap_type<ov::op::internal::MOE>({input_gemm2_m,
+ topk_weight_m,
+ topk_indices_gemm2_m,
+ compressed_weights_input_m_up,
+ bias_up_gemm2_m,
+ compressed_weights_input_m_down,
+ bias_down_gemm2_m},
+ [](const ov::Output<ov::Node>& output) {
+ auto moe_op = ov::as_type_ptr<ov::op::internal::MOE>(output.get_node_shared_ptr());
+ return moe_op->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP;
+ });
+
+ // gemm2 pattern finished
+
+ auto moe_root = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{moe_root_gemm3, moe_root_gemm2});
+
+ 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)) {
+ return false;
+ }
+ if (moe->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {
+ OutputVector args(11);
+ args[0] = pattern_map.at(hidden_states_m);
+ args[1] = pattern_map.at(routing_weights_m);
+ args[2] = pattern_map.at(topk_m);
+ args[3] = pattern_map.at(compressed_weights_m_0);
+ args[4] = pattern_map.at(scale_m_0);
+ args[5] = pattern_map.at(zp_m_0);
+ args[6] = pattern_map.at(compressed_weights_m_1);
+ args[7] = pattern_map.at(scale_m_1);
+ args[8] = pattern_map.at(zp_m_1);
+ args[9] = pattern_map.at(compressed_weights_m_2);
+ args[10] = pattern_map.at(scale_m_2);
+ args[11] = pattern_map.at(zp_m_2);
+ ov::intel_gpu::op::MOECompressed::Config config;
+ auto weight_shape = pattern_map.at(compressed_weights_m_0).get_shape();
+ if (weight_shape.size() != 4) {
+ return false;
+ }
+ auto topk_shape = pattern_map.at(topk_m).get_shape();
+ config.hidden_size = weight_shape[2] * weight_shape[3];
+ config.inter_size = weight_shape[1];
+ config.num_expert = weight_shape[0];
+ config.group_size = weight_shape[3];
+ config.top_k = topk_shape.back();
+ config.out_type = ov::element::dynamic;
+ auto moe_compressed = std::make_shared<ov::intel_gpu::op::MOECompressed>(args, config);
+
+ auto w0 = pattern_map.at(compressed_weights_m_0).get_node_shared_ptr();
+ auto s0 = pattern_map.at(scale_m_0).get_node_shared_ptr();
+ auto z0 = pattern_map.at(zp_m_0).get_node_shared_ptr();
+ auto w1 = pattern_map.at(compressed_weights_m_1).get_node_shared_ptr();
+ auto s1 = pattern_map.at(scale_m_1).get_node_shared_ptr();
+ auto z1 = pattern_map.at(zp_m_1).get_node_shared_ptr();
+ auto w2 = pattern_map.at(compressed_weights_m_2).get_node_shared_ptr();
+ auto s2 = pattern_map.at(scale_m_2).get_node_shared_ptr();
+ auto z2 = pattern_map.at(zp_m_2).get_node_shared_ptr();
+ ov::enable_keep_const_precision(w0);
+ ov::enable_keep_const_precision(s0);
+ ov::enable_keep_const_precision(z0);
+ ov::enable_keep_const_precision(w1);
+ ov::enable_keep_const_precision(s1);
+ ov::enable_keep_const_precision(z1);
+ ov::enable_keep_const_precision(w2);
+ ov::enable_keep_const_precision(s2);
+ ov::enable_keep_const_precision(z2);
+ moe_compressed->set_friendly_name(moe->get_friendly_name());
+ ov::copy_runtime_info(moe, moe_compressed);
+ 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);
+ auto weight_up_node = pattern_map.at(compressed_weights_input_m_up);
+ auto weight_down_node = pattern_map.at(compressed_weights_input_m_down);
+ auto topk_node = pattern_map.at(topk_gemm2_m).get_node_shared_ptr();
+ auto topk_weight_output = topk_node->output(0);
+ auto topk_weight_softmax = pattern_map.at(topk_weight_softmax_m).get_node_shared_ptr();
+
+ auto topk_shape = pattern_map.at(topk_gemm2_m).get_node_shared_ptr()->get_output_partial_shape(1);
+ auto weight_shape = pattern_map.at(compressed_weights_input_m_up).get_shape();
+ auto weight_down_shape = pattern_map.at(compressed_weights_input_m_down).get_shape();
+ auto bias_shape = pattern_map.at(bias_up_gemm2_m).get_node_shared_ptr()->get_shape();
+ auto scale_shape = pattern_map.at(mul_const_m_up).get_shape();
+ // Weight, scale, zp are assumed to be transposed
+ // W : [num_experts, N, K]
+ // scale : [num_experts, N, K / group_size, 1]
+ ov::intel_gpu::op::MOECompressed::Config config(moe->get_config());
+ config.num_expert = weight_shape[0];
+ config.hidden_size = weight_shape[2];
+ if (weight_shape.size() == 4) config.hidden_size *= weight_shape[3];
+ config.inter_size = weight_shape[1];
+ config.group_size = (weight_shape.size() == 3) ? config.hidden_size : scale_shape[3];
+ config.top_k = topk_shape.rbegin()->get_length();
+ config.out_type = ov::element::dynamic;
+ config.has_batch_dim = is_pa ? 0 : 1;
+
+ args.push_back(pattern_map.at(input_gemm2_m));
+ args.push_back(topk_weight_softmax);
+ args.push_back(pattern_map.at(topk_indices_gemm2_m));
+ // params for up
+ args.push_back(pattern_map.at(compressed_weights_m_up));
+ args.push_back(pattern_map.at(mul_const_m_up));
+ if (pattern_map.count(sub_const_m_up)) {
+ auto zp_shape = pattern_map.at(sub_const_m_up).get_node_shared_ptr()->get_shape();
+ auto zp = std::make_shared<ov::op::v0::Convert>(pattern_map.at(sub_const_m_up), element::f16);
+ args.push_back(zp);
+ config.has_zp = true;
+ }
+ args.push_back(pattern_map.at(bias_up_gemm2_m));
+ // params for down
+ args.push_back(pattern_map.at(compressed_weights_m_down));
+ args.push_back(pattern_map.at(mul_const_m_down));
+ if (pattern_map.count(sub_const_m_down)) {
+ auto zp = std::make_shared<ov::op::v0::Convert>(pattern_map.at(sub_const_m_down), element::f16);
+ args.push_back(zp);
+ config.has_zp = true;
+ } else if (config.has_zp) {
+ OPENVINO_THROW("gemm_down has no zp while gemm_up has zp!");
+ }
+ 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);
+ } else {
+ OPENVINO_THROW("Unsupported MOE expert type in ConvertMOEToMOECompressed");
+ }
+
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(moe_root, "ConvertMOEToMOECompressed");
+ this->register_matcher(m, callback);
+}
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.hpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.hpp
new file mode 100644
index 00000000000..3daad37b400
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.hpp
@@ -0,0 +1,17 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+
+namespace ov::intel_gpu {
+
+class ConvertMOEToMOECompressed: public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ConvertMOEToMOECompressed");
+ ConvertMOEToMOECompressed(bool is_pa);
+};
+
+} // namespace ov::intel_gpu
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
new file mode 100644
index 00000000000..021c2525cfd
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/moe_compressed.cpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/op/moe_compressed.hpp"
+
+namespace ov::intel_gpu::op {
+MOECompressed::MOECompressed(const OutputVector& args, const Config& config) : MOE(args), m_config(config) {
+ constructor_validate_and_infer_types();
+}
+
+const MOECompressed::Config& MOECompressed::get_config() const {
+ return m_config;
+}
+
+void MOECompressed::set_config(const Config& config) {
+ m_config = config;
+}
+
+std::shared_ptr<ov::Node> MOECompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ check_new_args_count(this, new_args);
+
+ return std::make_shared<MOECompressed>(new_args, m_config);
+}
+
+void MOECompressed::validate_and_infer_types() {
+ auto output_type = m_config.out_type == ov::element::dynamic ? get_input_element_type(0) : m_config.out_type;
+
+ set_output_type(0, output_type, get_input_partial_shape(0));
+}
+
+bool MOECompressed::visit_attributes(ov::AttributeVisitor& visitor) {
+ visitor.on_attribute("out_type", m_config.out_type);
+ visitor.on_attribute("group_size", m_config.group_size);
+
+ return true;
+}
+
+} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/op/swiglu_with_clamp.cpp b/src/plugins/intel_gpu/src/plugin/transformations/op/swiglu_with_clamp.cpp
new file mode 100644
index 00000000000..224ce395f89
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/op/swiglu_with_clamp.cpp
@@ -0,0 +1,82 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "ov_ops/glu.hpp"
+#include "intel_gpu/op/swiglu_with_clamp.hpp"
+#include "utils.hpp"
+#include "variadic_split_shape_inference.hpp"
+#include "strided_slice_shape_inference.hpp"
+
+namespace ov::intel_gpu::op {
+
+SwiGluWithClamp::SwiGluWithClamp(const ov::Output<Node>& data,
+ int64_t axis,
+ int64_t glu_stride,
+ const GluType glu_type,
+ const size_t gate_idx,
+ float clamp_min,
+ float clamp_max,
+ float swiglu_beta,
+ float up_add_val,
+ const ov::element::Type output_type)
+ : Op({data}),
+ m_axis(axis),
+ m_glu_stride(glu_stride),
+ m_glu_type(glu_type),
+ m_gate_idx(gate_idx),
+ m_clamp_min(clamp_min),
+ m_clamp_max(clamp_max),
+ m_swiglu_beta(swiglu_beta),
+ m_up_add_val(up_add_val),
+ m_output_type(output_type) {
+ validate_and_infer_types();
+}
+
+std::vector<ov::PartialShape> shape_infer(const ov::intel_gpu::op::SwiGluWithClamp* op, const std::vector<ov::PartialShape>& input_shapes) {
+ const auto inputs_count = input_shapes.size();
+ NODE_SHAPE_INFER_CHECK(op, input_shapes, inputs_count == 1);
+
+ int64_t axis = op->get_axis();
+ auto split_length = op->get_glu_stride();
+ if (op->get_glu_stride() == 2) {
+ // alternating
+ split_length = static_cast<int64_t>(input_shapes[0][axis].get_length() / 2);
+ }
+ std::vector<int64_t> split_lengths = {split_length, -1};
+ std::unordered_map<size_t, ov::Tensor> const_data;
+ const_data.emplace(1, ov::Tensor(ov::element::i64, ov::Shape{}, &axis));
+ const_data.emplace(2, ov::Tensor(ov::element::i64, ov::Shape{split_lengths.size()}, split_lengths.data()));
+
+ const ov::Shape split_len_size{split_lengths.size()};
+ const ov::Shape scalar{};
+ std::vector<ov::PartialShape> variadic_split_input_shapes{input_shapes[0], scalar, split_len_size};
+
+ return {std::move(ov::op::variadic_split::shape_infer(op, variadic_split_input_shapes, ov::make_tensor_accessor(const_data))[0])};
+}
+
+void SwiGluWithClamp::validate_and_infer_types() {
+ auto output_type = m_output_type == ov::element::dynamic ? get_input_element_type(0) : m_output_type;
+
+ const auto input_shapes = ov::util::get_node_input_partial_shapes(*this);
+ // glu_shape_inference is using variadic split. Not sure need to create a new
+ // glu_shape_inference with slice
+ const auto output_shapes = shape_infer(this, input_shapes);
+ set_output_type(0, output_type, output_shapes[0]);
+}
+
+
+std::shared_ptr<ov::Node> SwiGluWithClamp::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ check_new_args_count(this, new_args);
+ return std::make_shared<SwiGluWithClamp>(new_args.at(0),
+ m_axis,
+ m_glu_stride,
+ m_glu_type,
+ m_gate_idx,
+ m_clamp_min,
+ m_clamp_max,
+ m_swiglu_beta,
+ m_up_add_val,
+ m_output_type);
+}
+
+} // namespace ov::intel_gpu::op
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.cpp b/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.cpp
new file mode 100644
index 00000000000..b236c37ec1f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.cpp
@@ -0,0 +1,132 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "swiglu_fusion_with_clamp.hpp"
+
+#include "intel_gpu/op/swiglu_with_clamp.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/clamp.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/minimum.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/utils/utils.hpp"
+
+namespace ov {
+namespace intel_gpu {
+ SwiGluFusionWithClamp::SwiGluFusionWithClamp() {
+ using namespace ov::pass::pattern;
+
+ // Detect GLU decomposition pattern
+ auto gate_up_matmul_m = wrap_type<ov::op::v0::MatMul>({any_input(), any_input()});
+ auto gate_up_add_m = wrap_type<ov::op::v1::Add>({gate_up_matmul_m, any_input()});
+
+ // Branch 1: Slice_1 -> Minimum_1 -> Swish
+ auto slice1_start_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice1_end_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice1_axis_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice1_step_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice1_m = wrap_type<ov::op::v8::Slice>({gate_up_add_m, slice1_start_const_m, slice1_end_const_m, slice1_step_const_m, slice1_axis_const_m});
+ auto minimum_m = wrap_type<ov::op::v1::Minimum>({slice1_m, wrap_const()});
+ auto swish_beta_m = wrap_type<ov::op::v0::Constant>();
+ auto swish_m = wrap_type<ov::op::v4::Swish>({minimum_m, swish_beta_m});
+
+ // Branch 2: Slice_2 -> Clamp -> Add_1
+ auto slice2_start_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice2_end_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice2_step_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice2_axis_const_m = wrap_type<ov::op::v0::Constant>();
+ auto slice2_m = wrap_type<ov::op::v8::Slice>({gate_up_add_m, slice2_start_const_m, slice2_end_const_m, slice2_step_const_m, slice2_axis_const_m});
+ auto clamp_m = wrap_type<ov::op::v0::Clamp>({slice2_m});
+ auto added_const_m = wrap_type<ov::op::v0::Constant>();
+ auto add1_m = wrap_type<ov::op::v1::Add>({clamp_m, added_const_m});
+
+ // Join: Multiply_1
+ auto multiply1_m = wrap_type<ov::op::v1::Multiply>({swish_m, add1_m});
+ // Down projection
+ auto down_proj_matmul_m = wrap_type<ov::op::v0::MatMul>({multiply1_m, any_input()});
+
+ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ const auto& pattern_map = m.get_pattern_value_map();
+ auto swish_node_ptr = ov::as_type_ptr<ov::op::v4::Swish>(pattern_map.at(swish_m).get_node_shared_ptr());
+ auto mul_node_ptr = ov::as_type_ptr<ov::op::v1::Multiply>(pattern_map.at(multiply1_m).get_node_shared_ptr());
+ if (!mul_node_ptr || transformation_callback(mul_node_ptr))
+ return false;
+
+ auto clamp_node = ov::as_type_ptr<ov::op::v0::Clamp>(pattern_map.at(clamp_m).get_node_shared_ptr());
+ auto clamp_min_value = clamp_node->get_min();
+ auto clamp_max_value = clamp_node->get_max();
+
+ size_t gate_idx = 0;
+ if (ov::is_type<ov::op::v4::Swish>(mul_node_ptr->get_input_node_shared_ptr(1)))
+ gate_idx = 1;
+
+ auto slice1_node_ptr = ov::as_type_ptr<ov::op::v8::Slice>(pattern_map.at(slice1_m).get_node_shared_ptr());
+ auto slice1_in_ps = slice1_node_ptr->get_input_partial_shape(0);
+ auto last_dim = slice1_in_ps.rank().get_length() - 1;
+
+ auto axis_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(slice1_axis_const_m).get_node_shared_ptr());
+ bool valid_axis_const_values = ov::op::util::has_constant_value<int64_t>(axis_node_ptr, -1)
+ || ov::op::util::has_constant_value<int64_t>(axis_node_ptr, last_dim);
+ // only innermost axis supported
+ if (!valid_axis_const_values)
+ return false;
+ auto axis_dim = axis_node_ptr->cast_vector<int64_t>()[0];
+
+ auto slice1_start_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(slice1_start_const_m).get_node_shared_ptr());
+ auto slice1_end_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(slice1_end_const_m).get_node_shared_ptr());
+ auto slice1_step_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(slice1_step_const_m).get_node_shared_ptr());
+ auto slice_1_start_val = slice1_start_node_ptr->cast_vector<int64_t>()[0];
+ auto slice_1_end_val = slice1_end_node_ptr->cast_vector<int64_t>()[0];
+ auto slice_1_step_val = slice1_step_node_ptr->cast_vector<int64_t>()[0];
+ int64_t glu_stride = slice_1_end_val - slice_1_start_val;
+ if (slice_1_step_val == 2) {
+ // Alternating
+ glu_stride = slice_1_step_val;
+ } else if (slice_1_step_val == 1) {
+ if (glu_stride != slice1_in_ps[axis_dim].get_length() / 2) {
+ // Allow only case that exactly splits in half along the last dimension
+ return false;
+ }
+ } else {
+ return false;
+ }
+ if (pattern_map.find(swish_beta_m) == pattern_map.end())
+ return false;
+ auto swish_beta_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(swish_beta_m).get_node_shared_ptr());
+ auto swish_beta_val = static_cast<float>(swish_beta_node_ptr->cast_vector<double>()[0]);
+ auto add_const_node_ptr = ov::as_type_ptr<ov::op::v0::Constant>(pattern_map.at(added_const_m).get_node_shared_ptr());
+ auto added_const_val = static_cast<float>(add_const_node_ptr->cast_vector<double>()[0]);
+
+ auto data_node = pattern_map.at(gate_up_matmul_m);
+ auto output_type = m.get_match_root()->get_output_element_type(0);
+
+ auto swiglu = std::make_shared<op::SwiGluWithClamp>(data_node,
+ axis_dim,
+ glu_stride,
+ ov::op::internal::GLU::GluType::Swish,
+ gate_idx,
+ clamp_min_value,
+ clamp_max_value,
+ swish_beta_val,
+ added_const_val,
+ output_type);
+ swiglu->set_friendly_name(m.get_match_root()->get_friendly_name());
+ ov::copy_runtime_info(m.get_matched_nodes(), swiglu);
+ ov::replace_node(m.get_match_root(), swiglu);
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(down_proj_matmul_m, "SWIGLU_FUSION_WITH_CLAMP");
+ this->register_matcher(m, callback);
+ }
+
+} // namespace intel_gpu
+} // namespace ov
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.hpp b/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.hpp
new file mode 100644
index 00000000000..f72f79e90da
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/transformations/swiglu_fusion_with_clamp.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/core/visibility.hpp"
+
+namespace ov::intel_gpu {
+
+class SwiGluFusionWithClamp : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("SwiGluFusionWithClamp");
+ SwiGluFusionWithClamp();
+};
+
+} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 6beeaa3a508..b3ddf1f8deb 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -73,6 +73,7 @@
#include "plugin/transformations/clamp_fp16_output.hpp"
#include "plugin/transformations/convert_convolution.hpp"
#include "plugin/transformations/convert_fc_to_compressed.hpp"
+#include "plugin/transformations/convert_moe_to_compressed.hpp"
#include "plugin/transformations/convert_matmul_to_fc.hpp"
#include "plugin/transformations/convert_stridedslices_to_variadicsplit.hpp"
#include "plugin/transformations/decompose_reduce_scalar_output.hpp"
@@ -94,6 +95,7 @@
#include "plugin/transformations/unsqueeze_broadcast_reshape_matmul_fusion.hpp"
#include "plugin/transformations/unsqueeze_broadcast_reshape_sdpa_fusion.hpp"
#include "plugin/transformations/disable_fp16_comp_rms.hpp"
+#include "plugin/transformations/swiglu_fusion_with_clamp.hpp"
#include "transformations/common_optimizations/activations_scaling.hpp"
#include "transformations/common_optimizations/broadcast_elementwise_fusion.hpp"
#include "transformations/common_optimizations/broadcast_transition.hpp"
@@ -108,6 +110,7 @@
#include "transformations/common_optimizations/lstm_cell_fusion.hpp"
#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"
#include "transformations/common_optimizations/mvn_fusion.hpp"
+#include "transformations/common_optimizations/matmul_experts_fusion.hpp"
#include "transformations/common_optimizations/nop_elimination.hpp"
#include "transformations/common_optimizations/rms_fusion.hpp"
#include "transformations/common_optimizations/sdpa_scale_fusion.hpp"
@@ -189,6 +192,7 @@
#include "openvino/op/ceiling.hpp"
#include "openvino/op/clamp.hpp"
#include "openvino/op/matmul.hpp"
+#include "openvino/op/moe.hpp"
#include "openvino/op/reverse_sequence.hpp"
#include "openvino/op/roll.hpp"
#include "openvino/op/shuffle_channels.hpp"
@@ -209,13 +213,14 @@ static bool disable_reduce_decomposition(const std::shared_ptr<const ov::Node> n
}
static bool is_decompression_multiply(const std::shared_ptr<const ov::Node> node, bool supports_immad) {
- std::vector<ov::DiscreteTypeInfo> target_consumers = { ov::opset1::MatMul::get_type_info_static(),
- ov::op::v8::Gather::get_type_info_static(),
- ov::op::v1::Convolution::get_type_info_static(),
- ov::opset1::Convolution::get_type_info_static(),
- ov::op::v1::ConvolutionBackpropData::get_type_info_static(),
- ov::opset1::ConvolutionBackpropData::get_type_info_static(),
- ov::opset1::GroupConvolution::get_type_info_static() };
+ std::vector<ov::DiscreteTypeInfo> target_consumers = {ov::opset1::MatMul::get_type_info_static(),
+ ov::op::internal::MOE::get_type_info_static(),
+ ov::op::v8::Gather::get_type_info_static(),
+ ov::op::v1::Convolution::get_type_info_static(),
+ ov::opset1::Convolution::get_type_info_static(),
+ ov::op::v1::ConvolutionBackpropData::get_type_info_static(),
+ ov::opset1::ConvolutionBackpropData::get_type_info_static(),
+ ov::opset1::GroupConvolution::get_type_info_static()};
std::vector<ov::DiscreteTypeInfo> convolutions = { ov::op::v1::Convolution::get_type_info_static(),
ov::opset1::Convolution::get_type_info_static(),
@@ -393,6 +398,24 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
manager.register_pass<ov::pass::MarkDequantization>(
std::vector<ov::element::Type>{ ov::element::i8, ov::element::u8, ov::element::i4, ov::element::u4 },
!device_info.supports_immad);
+ const bool disable_moe_opt = GPU_DEBUG_VALUE_OR(config.get_disable_moe_opt(), false);
+ if (!disable_moe_opt) {
+ manager.register_pass<ov::pass::FuseVectorizedMOE2GEMM>();
+ pass_config->set_callback<ov::pass::FuseVectorizedMOE2GEMM>([&](const_node_ptr& root) -> bool {
+ // Currently moe op is only supported by >= xe2
+ auto& engine = m_context->get_engine();
+ const auto& info = engine.get_device_info();
+ return (info.arch != cldnn::gpu_arch::xe2) && (info.arch != cldnn::gpu_arch::xe2);
+ });
+ bool is_pa = false;
+ for (const auto& op : func->get_ops()) {
+ if (auto paged_attn_op = ov::as_type_ptr<ov::op::PagedAttentionExtension>(op)) {
+ is_pa = true;
+ break;
+ }
+ }
+ manager.register_pass<ov::intel_gpu::ConvertMOEToMOECompressed>(is_pa);
+ }
manager.register_pass<ov::pass::InitNodeInfo>();
manager.register_pass<EinsumDecomposition>();
@@ -464,7 +487,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
if (is_type<ov::op::v0::Convert>(next_node)) {
next_node = next_node->get_output_target_inputs(0).begin()->get_node();
}
- return !is_type<ov::op::v0::MatMul>(next_node);
+ return !is_type<ov::op::v0::MatMul>(next_node) && !is_type<ov::op::internal::MOE>(next_node);
});
// Disable subtract folding only for the dGPUs to meet the requirements of oneDNN:
@@ -1208,6 +1231,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
pass_config->disable<ov::pass::RoPEShareCosSin>();
manager.register_pass<ov::intel_gpu::IncreasePositionIdsPrecision>();
+ manager.register_pass<ov::intel_gpu::SwiGluFusionWithClamp>();
// This Validate is needed for proper data type propagation after applying IncreasePositionIdsPrecision pass
manager.register_pass<ov::pass::Validate>();
diff --git a/src/plugins/intel_gpu/src/runtime/ocl/ocl_memory.cpp b/src/plugins/intel_gpu/src/runtime/ocl/ocl_memory.cpp
index 636939dca7e..6917cfb726d 100644
--- a/src/plugins/intel_gpu/src/runtime/ocl/ocl_memory.cpp
+++ b/src/plugins/intel_gpu/src/runtime/ocl/ocl_memory.cpp
@@ -548,6 +548,9 @@ void* gpu_usm::lock(const stream& stream, mem_lock_type type) {
void gpu_usm::unlock(const stream& /* stream */) {
std::lock_guard<std::mutex> locker(_mutex);
+ if (_lock_count == 0) {
+ OPENVINO_THROW("Trying to unlock an already unlocked buffer");
+ }
_lock_count--;
if (0 == _lock_count) {
if (get_allocation_type() == allocation_type::usm_device) {
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_gather_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_gather_gpu_test.cpp
new file mode 100644
index 00000000000..7bfa6c93eff
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_gather_gpu_test.cpp
@@ -0,0 +1,142 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+#include <iostream>
+#include <numeric>
+#include "test_utils.h"
+#include "random_generator.hpp"
+
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+#include <intel_gpu/primitives/fully_connected.hpp>
+#include <intel_gpu/primitives/moe_gather.hpp>
+#include "intel_gpu/op/moe_compressed.hpp"
+
+using namespace cldnn;
+using namespace ov::intel_gpu;
+using namespace ::tests;
+
+
+// moe_gather
+template <typename T>
+void test_moe_gather(bool is_caching_test, int k) {
+ auto& engine = get_test_engine();
+ // num_tokens 30
+ // hidden_size 64
+ // num total experts 32
+ // experts_per_token 2
+ // num_actual_used_experts 7
+ // input0 activation [30, 64]
+ // input1 experts_info_offset [7]
+ // input2 tokens_per_expert [30*2*64]
+ size_t num_tokens = 30;
+ size_t num_total_experts = 32;
+ size_t hidden_size = k;
+ int32_t num_experts_per_token = 2;
+
+ ov::intel_gpu::op::MOECompressed::Config moe_config;
+ moe_config.top_k = 2;
+ moe_config.hidden_size = k;
+ moe_config.num_expert = num_total_experts;
+ moe_config.has_batch_dim = false;
+
+ auto input_activation_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension(hidden_size)};
+ auto input_activation_layout = layout{input_activation_shape, data_types::f16, format::bfyx};
+
+ auto tokens_per_expert_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto tokens_per_expert_layout = layout{tokens_per_expert_shape, data_types::i32, format::bfyx};
+
+ topology topology(
+ input_layout("input", input_activation_layout),
+ input_layout("tokens_per_expert", tokens_per_expert_layout),
+ moe_gather("moe_gather", input_info("input"), input_info("tokens_per_expert"), moe_config)
+ );
+ auto input_data_shape = ov::PartialShape{ov::Dimension(num_tokens), ov::Dimension(hidden_size)};
+ auto input_data_layout = layout{input_data_shape, data_types::f16, format::bfyx};
+
+ std::vector<ov::float16> input_data;
+ for (size_t i = 0; i < num_tokens; ++i) {
+ for (size_t h = 0; h < hidden_size; ++h)
+ input_data.push_back(static_cast<ov::float16>(i));
+ }
+ auto input_mem = engine.allocate_memory(input_data_layout);
+ set_values(input_mem, input_data);
+
+ // topk result
+ std::vector<std::vector<int32_t>> experts_per_token = {{0, 5}, {5, 7}, {0, 10}, {11, 20}, {7, 10}, {0, 7}, {20, 31}, {11, 31}, {11, 20}, {7, 10},
+ {0, 5}, {11, 31}, {0, 7}, {0, 20}, {10, 31}, {10, 20}, {7, 31}, {0, 31}, {5, 31}, {7, 31},
+ {7, 20}, {0, 10}, {0, 5}, {5, 11}, {7, 11}, {5, 31}, {7, 31}, {0, 31}, {0, 10}, {11, 20}};
+
+ std::vector<std::vector<int32_t>> tokens_per_expert_tmp(num_total_experts, std::vector<int32_t>{});
+
+ for (size_t i = 0; i < experts_per_token.size(); ++i) {
+ for (size_t j = 0; j < experts_per_token[i].size(); ++j)
+ tokens_per_expert_tmp[experts_per_token[i][j]].push_back(static_cast<int32_t>(i));
+ }
+
+ std::vector<int32_t> tokens_per_expert_data;
+
+ for (size_t i = 0; i < tokens_per_expert_tmp.size(); ++i) {
+ if (tokens_per_expert_tmp[i].empty())
+ continue;
+ for (size_t j = 0; j < tokens_per_expert_tmp[i].size(); ++j) {
+ tokens_per_expert_data.push_back(tokens_per_expert_tmp[i][j]);
+ }
+ }
+ // experts 0, 5, 7, 10, 11, 20, 31 are used
+ // experts[0] offset : 0 {0, 2, 5, 10, 12, 13, 17, 21, 22, 27, 28}
+ // experts[5] offset : 11 {0, 1, 10, 18, 22, 23, 25}
+ // experts[7] offset : 18 {1, 4, 5, 9, 12, 16, 19, 20, 24, 26}
+ // experts[10] offset : 28 {2, 4, 9, 14, 15, 21, 28}
+ // experts[11] offset : 35 {3, 7, 8, 11, 23, 24, 29}
+ // experts[20] offset : 42 {3, 6, 8, 13, 15, 20, 29}
+ // experts[31] offset : 49 {6, 7, 11, 14, 16, 17, 18, 19, 25, 26, 27}
+
+ auto tokens_per_expert_data_shape = ov::PartialShape{ov::Dimension(tokens_per_expert_data.size())};
+ auto tokens_per_expert_data_layout = layout{tokens_per_expert_data_shape, data_types::i32, format::bfyx};
+ auto tokens_per_expert_data_mem = engine.allocate_memory(tokens_per_expert_data_layout);
+ set_values(tokens_per_expert_data_mem, tokens_per_expert_data);
+
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{
+ {"moe_gather", {format::bfyx, "", impl_types::ocl}}}));
+
+ network network(engine, topology, config, is_caching_test);
+ network.set_input_data("input", input_mem);
+ network.set_input_data("tokens_per_expert", tokens_per_expert_data_mem);
+ auto outputs = network.execute();
+ auto output = outputs.begin()->second.get_memory();
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<ov::float16> ref_output;
+ for (size_t i = 0; i < tokens_per_expert_data.size(); ++i) {
+ int32_t token_id = tokens_per_expert_data[i];
+ for (size_t h = 0; h < hidden_size; ++h) {
+ ref_output.push_back(input_data[token_id * hidden_size + h]);
+ }
+ }
+ for (size_t i = 0; i < num_tokens * num_experts_per_token * hidden_size; i++) {
+ ASSERT_EQ(ref_output[i], output_ptr[i]);
+ }
+}
+
+TEST(moe_unit, moe_gather_test_single_batch_aligned) {
+ test_moe_gather<float>(false, 64);
+}
+
+TEST(moe_unit, moe_gather_test_single_batch_noaligned) {
+ test_moe_gather<float>(false, 66);
+}
+
+TEST(moe_unit, moe_gather_test_multi_batch_aligned) {
+ test_moe_gather<float>(false, 5120);
+}
+
+TEST(moe_unit, moe_gather_test_multi_batch_unaligned) {
+ test_moe_gather<float>(false, 5124);
+}
+
+TEST(moe_unit, moe_gather_test_cached) {
+ test_moe_gather<float>(true, 64);
+}
\ No newline at end of file
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_gemm_gpu_test.cpp
new file mode 100644
index 00000000000..fa3af500786
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_gemm_gpu_test.cpp
@@ -0,0 +1,646 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+#include <iostream>
+#include <numeric>
+#include "test_utils.h"
+#include "random_generator.hpp"
+
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+#include <intel_gpu/primitives/moe_gemm.hpp>
+#include <intel_gpu/primitives/fully_connected.hpp>
+#include "intel_gpu/op/moe_compressed.hpp"
+
+using namespace cldnn;
+using namespace ov::intel_gpu;
+using namespace ::tests;
+
+enum class PHASE { PREFILL, UP, DOWN };
+struct moe_gemm_test_params {
+ PHASE phase;
+ size_t num_tokens;
+ size_t num_total_experts;
+ size_t num_experts_per_token;
+ size_t num_actually_used_experts;
+ size_t hidden_size;
+ size_t out_N;
+ bool has_bias;
+ cldnn::data_types input_dt = cldnn::data_types::f16;
+ cldnn::data_types weight_dt = cldnn::data_types::f16;
+ cldnn::data_types scale_dt = cldnn::data_types::f16;
+ int32_t scale_group_size;
+ bool weight_symmetric_quant;
+ bool is_pa;
+};
+
+template <typename T>
+void get_reference(const std::vector<ov::float16>& input,
+ const std::vector<T>& weight,
+ std::vector<ov::float16>& ref_out,
+ const std::vector<int32_t>& experts_ids,
+ const std::vector<int32_t>& input_offset_per_expert,
+ const std::vector<int32_t>& input_tokens_lens,
+ int32_t N,
+ int32_t K,
+ const std::vector<ov::float16>& weight_scale,
+ const std::vector<ov::float16>& weight_zp,
+ int32_t group_size,
+ bool is_weight_compressed,
+ bool is_weight_symmetric_quant,
+ cldnn::data_types weight_dt,
+ const std::vector<ov::float16>& bias) {
+ std::cout << "get_reference" << std::endl;
+ size_t elements_per_byte = (ov::element::Type(weight_dt).bitwidth() == 4) ? 2 : 1;
+ auto ld_w = K / elements_per_byte;
+ auto ld_in = K;
+ auto ld_out = N;
+ auto batch = input_offset_per_expert.size();
+ auto expert_stride = ld_w * N;
+ for (size_t b = 0; b < batch; b++) {
+ int32_t expert_id = experts_ids[b];
+ auto weight_ptr = &weight[expert_id * expert_stride];
+ auto input_ptr = &input[input_offset_per_expert[b] * ld_in];
+ auto ref_out_ptr = &ref_out[input_offset_per_expert[b] * ld_out];
+ auto cur_m = input_tokens_lens[b];
+ for (int j = 0; j < cur_m; j++) {
+ for (int n = 0; n < N; n++) {
+ auto weight_r = weight_ptr + n * ld_w;
+ auto input_r = input_ptr + j * ld_in;
+ float acc = 0.0f;
+ for (int32_t k = 0; k < K; ++k) {
+ acc += static_cast<float>(weight_r[k]) * static_cast<float>(input_r[k]);
+ }
+ ref_out_ptr[j * ld_out + n] = static_cast<ov::float16>(acc);
+ }
+ }
+ }
+}
+template <>
+void get_reference(const std::vector<ov::float16>& input,
+ const std::vector<uint8_t>& weight,
+ std::vector<ov::float16>& ref_out,
+ const std::vector<int32_t>& experts_ids,
+ const std::vector<int32_t>& input_offset_per_expert,
+ const std::vector<int32_t>& input_tokens_lens,
+ int32_t N,
+ int32_t K,
+ const std::vector<ov::float16>& weight_scale,
+ const std::vector<ov::float16>& weight_zp,
+ int32_t group_size,
+ bool is_weight_compressed,
+ bool is_weight_symmetric_quant,
+ cldnn::data_types weight_dt,
+ const std::vector<ov::float16>& bias) {
+ std::cout << "get_reference" << std::endl;
+ size_t elements_per_byte = (ov::element::Type(weight_dt).bitwidth() == 4) ? 2 : 1;
+ auto ld_w = K / elements_per_byte;
+ auto ld_in = K;
+ auto ld_out = N;
+ auto batch = input_offset_per_expert.size();
+ auto expert_stride = ld_w * N;
+ int num_scale_groups = K / group_size;
+ bool has_bias = bias.size() > 0;
+ for (size_t b = 0; b < batch; b++) {
+ int32_t expert_id = experts_ids[b];
+ auto weight_ptr = &weight[expert_id * expert_stride];
+ auto input_ptr = &input[input_offset_per_expert[b] * ld_in];
+ auto ref_out_ptr = &ref_out[input_offset_per_expert[b] * ld_out];
+ auto cur_m = input_tokens_lens[b];
+ for (int j = 0; j < cur_m; j++) {
+ for (int n = 0; n < N; n++) {
+ auto weight_r = weight_ptr + n * ld_w;
+ auto input_r = input_ptr + j * ld_in;
+ float acc = 0.0f;
+ int scale_group = 0;
+ auto bias_val = has_bias ? bias[expert_id * N + n] : ov::float16(0.0f);
+ if (is_weight_compressed) {
+ for (size_t k = 0; k < ld_w; k += (group_size / elements_per_byte)) {
+ for (size_t ki = k; ki < k + (group_size / elements_per_byte); ++ki) {
+ // decompress i4
+ if (weight_dt == cldnn::data_types::i4 && is_weight_symmetric_quant) {
+ int8_t q0 = static_cast<int8_t>(weight_r[ki] & 0x0F);
+ int8_t q1 = static_cast<int8_t>(weight_r[ki] >> 4) & 0x0F;
+ if (q0 > 7)
+ q0 -= 16;
+ if (q1 > 7)
+ q1 -= 16;
+ float scale = float(weight_scale[expert_id * N * num_scale_groups + n * num_scale_groups + scale_group]);
+ ov::float16 fa0 = ov::float16((float)q0 * (float)scale);
+ ov::float16 fa1 = ov::float16((float)q1 * (float)scale);
+ acc += (float)fa0 * input_r[2 * ki];
+ acc += (float)fa1 * input_r[2 * ki + 1];
+ } else if (weight_dt == cldnn::data_types::u4 && !is_weight_symmetric_quant) {
+ uint8_t q0 = (static_cast<uint8_t>(weight_r[ki]) & 0x0F);
+ uint8_t q1 = (static_cast<uint8_t>(weight_r[ki]) >> 4) & 0x0F;
+ float scale = float(weight_scale[expert_id * N * num_scale_groups + n * num_scale_groups + scale_group]);
+ float zp = float(weight_zp[expert_id * N * num_scale_groups + n * num_scale_groups + scale_group]);
+ float fa0 = (float(q0) - zp) * scale;
+ float fa1 = (float(q1) - zp) * scale;
+ acc += fa0 * input_r[2 * ki];
+ acc += fa1 * input_r[2 * ki + 1];
+ } else {
+ OPENVINO_ASSERT("Not implemented dt");
+ }
+ }
+ scale_group++;
+ }
+ } else {
+ for (int32_t k = 0; k < K; ++k) {
+ acc += static_cast<float>(weight_r[k]) * static_cast<float>(input_r[k]);
+ }
+ }
+ ref_out_ptr[j * ld_out + n] = static_cast<ov::float16>(acc + bias_val);
+ }
+ }
+ }
+}
+
+template <typename T>
+struct MoEGemmTest : public ::testing::TestWithParam<T> {
+ public:
+ random_generator rg;
+ cldnn::engine& engine = get_test_engine();
+
+ void SetUp() override {
+ rg.set_seed(GET_SUITE_NAME);
+ }
+
+
+ void quantize_4bit(std::vector<ov::float16>& weight_fp,
+ std::vector<uint8_t>& weight_quantized,
+ cldnn::data_types q_dt,
+ size_t B,
+ size_t N,
+ size_t K,
+ int32_t group_size,
+ bool is_symmetric,
+ std::vector<ov::float16>& weight_scale,
+ std::vector<ov::float16>& weight_zp) {
+ const size_t K_q = K / 2;
+ const size_t num_elements_per_byte = 2;
+ const size_t num_scale_groups = K / group_size;
+
+ for (size_t b = 0; b < B; b++) {
+ for (size_t n = 0; n < N; n++) {
+ size_t group_iter = 0;
+ while (group_iter * group_size < K) {
+ ov::float16 amax = std::numeric_limits<ov::float16>::lowest();
+ ov::float16 amin = std::numeric_limits<ov::float16>::max();
+ for (int32_t ki = 0; ki < group_size; ki++) {
+ ov::float16 v = weight_fp[b * N * K + n * K + group_iter * group_size + ki];
+ amax = std::max(amax, v);
+ amin = std::min(amin, v);
+ }
+ if (q_dt == cldnn::data_types::u4) {
+ OPENVINO_ASSERT(!is_symmetric);
+ const uint8_t q_max = 15;
+ const uint8_t q_min = 0;
+ float range = (float)amax - (float)amin;
+ if (range <= 1e-5f)
+ range = 1e-2f;
+ float inv_scale = (q_max - q_min) / range;
+ float zp_tmp = (float) (q_min - amin * inv_scale);
+ ov::float16 zp = zp_tmp;
+ // quantize asym u4
+ for (size_t ki = 0; ki < group_size / num_elements_per_byte; ki++) {
+ ov::float16 v0 = weight_fp[(b * N * K) + (n * K) + (group_iter * group_size) + num_elements_per_byte * ki];
+ ov::float16 v1 = weight_fp[(b * N * K) + (n * K) + (group_iter * group_size) + num_elements_per_byte * ki + 1];
+ uint8_t q0 = std::min(std::max((uint8_t)(float(v0) * inv_scale + (float)zp), (uint8_t)0), q_max); // u4
+ uint8_t q1 = std::min(std::max((uint8_t)(float(v1) * inv_scale + (float)zp), (uint8_t)0), q_max); // u4
+
+ uint8_t q0q1 = (q1 << 4) | (q0 & 0x0F);
+ weight_quantized[(b * N * K_q) + (n * K_q) + (group_iter * group_size / num_elements_per_byte) + ki] = uint8_t(q0q1);
+ }
+ ov::float16 scale = 1 / inv_scale;
+ weight_scale[b * N + n * num_scale_groups + group_iter ] = scale;
+ weight_zp[b * N + n * num_scale_groups + group_iter] = zp;
+ } else if (q_dt == cldnn::data_types::i4) {
+ OPENVINO_ASSERT(is_symmetric);
+ const int8_t q_max = 7;
+ const int8_t q_min = -8;
+ float abs_max = std::max(std::abs(float(amax)), std::abs(float(amin)));
+ float inv_scale = (float)q_max / abs_max;
+ // quantize sym i4
+ for (size_t ki = 0; ki < group_size / num_elements_per_byte; ki++) {
+ ov::float16 v0 = weight_fp[(b * N * K) + (n * K) + (group_iter * group_size) + num_elements_per_byte * ki];
+ ov::float16 v1 = weight_fp[(b * N * K) + (n * K) + (group_iter * group_size) + num_elements_per_byte * ki + 1];
+ int8_t q0 = std::min(std::max((int8_t)(std::round(float(v0) * inv_scale)), q_min), q_max); // u4
+ int8_t q1 = std::min(std::max((int8_t)(std::round(float(v1) * inv_scale)), q_min), q_max); // u4
+ uint8_t q0q1 = ((uint8_t)q1 << 4) | ((uint8_t)q0 & 0x0F);
+ weight_quantized[b * N * K_q + (n * K_q) + (group_iter * group_size / num_elements_per_byte) + ki] = q0q1;
+ }
+ ov::float16 scale = 1 / inv_scale;
+ weight_scale[b * N * num_scale_groups + n * num_scale_groups + group_iter] = scale;
+ }
+ group_iter++;
+ }
+ }
+ }
+ }
+
+ void create_weight_data_and_topology(T& p, topology& topo, std::vector<ov::float16>& experts_data_f16, std::vector<uint8_t>& experts_data_quant,
+ std::vector<ov::float16>& scales_data, std::vector<ov::float16>& zp_data, bool is_weight_compressed) {
+ ov::intel_gpu::op::MOECompressed::Config moe_config;
+ moe_config.top_k = p.num_experts_per_token;
+ moe_config.num_expert = p.num_total_experts;
+ moe_config.has_batch_dim = !p.is_pa;
+ moe_config.hidden_size = p.hidden_size;
+ moe_config.inter_size = p.out_N;
+ auto num_scale_groups = p.hidden_size / p.scale_group_size;
+ auto input_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), ov::Dimension(p.hidden_size)};
+ auto input_act_layout = layout{input_shape, p.input_dt, format::bfyx};
+
+ auto experts_shape = num_scale_groups > 1
+ ? ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(num_scale_groups), ov::Dimension(p.scale_group_size)}
+ : ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(p.hidden_size)};
+ auto experts_f16_layout = layout{experts_shape, data_types::f16, format::bfyx};
+
+ auto experts_ids_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto experts_ids_layout = layout{experts_ids_shape, data_types::i32, format::bfyx};
+
+ auto input_offset_per_expert_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto input_offset_per_expert_layout = layout{input_offset_per_expert_shape, data_types::i32, format::bfyx};
+
+ auto input_tokens_lens_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto input_tokens_lens_layout = layout{input_tokens_lens_shape, data_types::i32, format::bfyx};
+
+ auto input_prim = input_layout("input", input_act_layout);
+ auto experts_ids_prim = input_layout("experts_ids", experts_ids_layout);
+ auto input_offset_per_expert_prim = input_layout("input_offset_per_expert", input_offset_per_expert_layout);
+ auto input_tokens_lens_prim = input_layout("input_tokens_lens", input_tokens_lens_layout);
+
+ topo.add(input_prim);
+ topo.add(experts_ids_prim);
+ topo.add(input_offset_per_expert_prim);
+ topo.add(input_tokens_lens_prim);
+ // prepare experts weights
+ layout experts_layout;
+ if (is_weight_compressed) {
+ experts_layout = layout{experts_shape, p.weight_dt, format::bfyx};
+ } else {
+ experts_layout = experts_f16_layout;
+ }
+ auto experts_mem = engine.allocate_memory(experts_layout);
+ experts_data_f16.resize(p.num_total_experts * p.out_N * p.hidden_size);
+ auto gen_f16_weight = [&](size_t num_total_experts, size_t expert_out_N, size_t hidden_size) {
+ for (size_t e = 0; e < num_total_experts; ++e) {
+ for (size_t n = 0; n < expert_out_N; ++n) {
+ for (size_t h = 0; h < hidden_size; ++h) {
+ size_t idx = e * expert_out_N * hidden_size + n * hidden_size + h;
+ experts_data_f16[idx] = static_cast<ov::float16>((e + (n % 3) + (h % 5) + 1) / 10.0f);
+ }
+ }
+ }
+ };
+ gen_f16_weight(p.num_total_experts, p.out_N, p.hidden_size);
+
+ if (is_weight_compressed) {
+ experts_data_quant.resize(p.num_total_experts * p.hidden_size * p.out_N / 2);
+ scales_data.resize(p.num_total_experts * p.out_N * num_scale_groups);
+ if (!p.weight_symmetric_quant) {
+ zp_data.resize(p.num_total_experts * p.out_N * num_scale_groups);
+ }
+ quantize_4bit(experts_data_f16, experts_data_quant, p.weight_dt, p.num_total_experts, p.out_N, p.hidden_size, p.scale_group_size, p.weight_symmetric_quant, scales_data, zp_data);
+ set_values(experts_mem, experts_data_quant);
+ auto scale_shape = num_scale_groups > 1 ? ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(num_scale_groups), ov::Dimension(1)} :
+ ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(1)};
+ auto scale_layout = layout{scale_shape, data_types::f16, format::bfyx};
+ auto scale_mem = engine.allocate_memory(scale_layout);
+ set_values(scale_mem, scales_data);
+
+ auto moe_experts_prim = data("moe_experts", experts_mem);
+ auto moe_experts_scale_prim = data("moe_experts_scale", scale_mem);
+ topo.add(moe_experts_prim);
+ topo.add(moe_experts_scale_prim);
+ if (!p.weight_symmetric_quant) {
+ auto zp_shape = num_scale_groups > 1 ? ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(num_scale_groups), ov::Dimension(1)} :
+ ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(p.out_N), ov::Dimension(1)};
+ auto zp_layout = layout{zp_shape, data_types::f16, format::bfyx};
+ auto zp_mem = engine.allocate_memory(zp_layout);
+ set_values(zp_mem, zp_data);
+ auto moe_experts_zp_prim = data("moe_experts_zp", zp_mem);
+ topo.add(moe_experts_zp_prim);
+ std::vector<input_info> inputs = {
+ input_info("input"),
+ input_info("moe_experts"),
+ input_info("experts_ids"),
+ input_info("input_offset_per_expert"),
+ input_info("input_tokens_lens"),
+ input_info("moe_experts_scale"),
+ input_info("moe_experts_zp"),
+ };
+ auto moe_gemm_prim = moe_gemm("moe_gemm", inputs, moe_config);
+ moe_gemm_prim.has_bias = false;
+ topo.add(moe_gemm_prim);
+ } else {
+ std::vector<input_info> inputs = {
+ input_info("input"),
+ input_info("moe_experts"),
+ input_info("experts_ids"),
+ input_info("input_offset_per_expert"),
+ input_info("input_tokens_lens"),
+ input_info("moe_experts_scale"),
+ };
+
+ auto moe_gemm_prim = moe_gemm("moe_gemm", inputs, moe_config);
+ topo.add(moe_gemm_prim);
+ }
+ } else {
+ set_values(experts_mem, experts_data_f16);
+ auto moe_experts_prim = data("moe_experts", experts_mem);
+ topo.add(moe_experts_prim);
+ std::vector<input_info> inputs = {input_info("input"),
+ input_info("moe_experts"),
+ input_info("experts_ids"),
+ input_info("input_offset_per_expert"),
+ input_info("input_tokens_lens")};
+ auto moe_gemm_prim = moe_gemm("moe_gemm", inputs, moe_config);
+ topo.add(moe_gemm_prim);
+ }
+ }
+
+ void execute(T& p) {
+ topology topo;
+ std::vector<ov::float16> experts_data_f16;
+ std::vector<uint8_t> experts_data_q4;
+ std::vector<ov::float16> scales_data;
+ std::vector<ov::float16> zp_data;
+ std::vector<cldnn::data_types> quant_types = {data_types::i4, data_types::u4, data_types::i8, data_types::u8};
+ if (!engine.get_device_info().supports_immad || engine.get_device_info().arch != gpu_arch::xe2)
+ return;
+
+ bool is_weight_compressed = std::any_of(quant_types.begin(), quant_types.end(), [=](const cldnn::data_types& t) -> bool {
+ return t == p.weight_dt;
+ });
+ create_weight_data_and_topology(p, topo, experts_data_f16, experts_data_q4, scales_data, zp_data, is_weight_compressed);
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ network network(engine, topo, config);
+
+ auto get_input_data = [] (size_t M, size_t K, random_generator& rg) {
+ std::vector<ov::float16> input_data(M * K);
+ for (size_t m = 0; m < M; ++m) {
+ for (size_t k = 0; k < K; ++k) {
+ input_data[m * K + k] = static_cast<ov::float16>((k % 20 + 1.0f) / 10);
+ }
+ }
+ return input_data;
+ };
+
+ const auto M = p.phase == PHASE::UP ? p.num_tokens : p.num_tokens * p.num_experts_per_token;
+ auto input_data = get_input_data(M, p.hidden_size, rg);
+ auto input_data_shape = p.is_pa ? ov::PartialShape{ov::Dimension(M), ov::Dimension(1), ov::Dimension(p.hidden_size)}
+ : ov::PartialShape{ov::Dimension(1), ov::Dimension(M), ov::Dimension(p.hidden_size)};
+ auto input_data_layout = layout{input_data_shape, data_types::f16, format::bfyx};
+ auto input_mem = engine.allocate_memory(input_data_layout);
+ set_values(input_mem, input_data);
+
+ std::vector<int32_t> experts_ids_data(p.num_actually_used_experts);
+ const auto step = p.num_total_experts / p.num_actually_used_experts;
+ for (size_t e = 0; e < p.num_actually_used_experts; e++) {
+ experts_ids_data[e] = static_cast<int32_t>(e * step);
+ }
+ auto experts_ids_data_shape = ov::PartialShape{ov::Dimension(static_cast<int64_t>(p.num_actually_used_experts))};
+ auto experts_ids_data_layout = layout{experts_ids_data_shape, data_types::i32, format::bfyx};
+ auto experts_ids_mem = engine.allocate_memory(experts_ids_data_layout);
+ set_values(experts_ids_mem, experts_ids_data);
+
+ std::vector<int32_t> input_offset_per_expert_data(p.num_actually_used_experts);
+ std::vector<int32_t> input_tokens_lens(p.num_actually_used_experts);
+ const auto avg_len = (M / p.num_actually_used_experts);
+ for (size_t e = 0; e < p.num_actually_used_experts; e++) {
+ size_t len = (e == p.num_actually_used_experts -1) ? M - (avg_len * e) : avg_len;
+ input_tokens_lens[e] = static_cast<int32_t>(len);
+ input_offset_per_expert_data[e] = static_cast<int32_t>(e * avg_len);
+ }
+ auto input_tokens_lens_data_shape = ov::PartialShape{ov::Dimension(static_cast<int64_t>(p.num_actually_used_experts))};
+ auto input_tokens_lens_data_layout = layout{input_tokens_lens_data_shape, data_types::i32, format::bfyx};
+ auto input_tokens_lens_mem = engine.allocate_memory(input_tokens_lens_data_layout);
+ set_values(input_tokens_lens_mem, input_tokens_lens);
+
+ auto input_offset_per_expert_data_shape = ov::PartialShape{ov::Dimension(static_cast<int64_t>(p.num_actually_used_experts))};
+ auto input_offset_per_expert_data_layout = layout{input_offset_per_expert_data_shape, data_types::i32, format::bfyx};
+ auto input_offset_per_expert_mem = engine.allocate_memory(input_offset_per_expert_data_layout);
+ set_values(input_offset_per_expert_mem, input_offset_per_expert_data);
+
+ network.set_input_data("input", input_mem);
+ network.set_input_data("experts_ids", experts_ids_mem);
+ network.set_input_data("input_offset_per_expert", input_offset_per_expert_mem);
+ network.set_input_data("input_tokens_lens", input_tokens_lens_mem);
+ auto outputs = network.execute();
+ auto output = outputs.at("moe_gemm").get_memory();
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<ov::float16> output_ref(M * p.out_N, 0.0f);
+ if (is_weight_compressed) {
+ get_reference<uint8_t>(input_data,
+ experts_data_q4,
+ output_ref,
+ experts_ids_data,
+ input_offset_per_expert_data,
+ input_tokens_lens,
+ static_cast<int32_t>(p.out_N),
+ static_cast<int32_t>(p.hidden_size),
+ scales_data,
+ zp_data,
+ p.scale_group_size,
+ is_weight_compressed,
+ p.weight_symmetric_quant,
+ p.weight_dt,
+ {});
+ } else {
+ get_reference<ov::float16>(input_data,
+ experts_data_f16,
+ output_ref,
+ experts_ids_data,
+ input_offset_per_expert_data,
+ input_tokens_lens,
+ static_cast<int32_t>(p.out_N),
+ static_cast<int32_t>(p.hidden_size),
+ scales_data,
+ zp_data,
+ p.scale_group_size,
+ is_weight_compressed,
+ p.weight_symmetric_quant,
+ p.weight_dt,
+ {});
+ }
+
+ for (size_t i = 0; i < M * p.out_N; i++) {
+ auto tolerance = std::max(std::abs(output_ref[i] * 0.01f), 0.1f);
+ ASSERT_NEAR(output_ptr[i], output_ref[i], tolerance);
+ }
+ }
+};
+
+
+
+
+class moe_gemm_test : public MoEGemmTest<moe_gemm_test_params> {};
+TEST_P(moe_gemm_test, basic) {
+ auto p = GetParam();
+ execute(p);
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_moe_gemm,
+ moe_gemm_test,
+ ::testing::ValuesIn(std::vector<moe_gemm_test_params>{// f16 / prefill
+ moe_gemm_test_params{
+ PHASE::PREFILL /*phase*/,
+ static_cast<size_t>(30), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(2), /*num_experts_per_token*/
+ static_cast<size_t>(3), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::f16, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ -1, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // f16 / up
+ moe_gemm_test_params{
+ PHASE::UP /*phase*/,
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::f16, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ -1, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // f16 / down
+ moe_gemm_test_params{
+ PHASE::UP, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::f16, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ -1, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // i4 / symmetric/ group size 32 / prefill
+ moe_gemm_test_params{
+ PHASE::PREFILL, /*phase*/
+ static_cast<size_t>(30), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(2), /*num_experts_per_token*/
+ static_cast<size_t>(3), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::i4, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ 32, /*scale_group_size*/
+ true, /*weight_symmetric_quant*/
+ true, /*is_pa*/
+ },
+ // i4 / symmetric/ group size 32 / up
+ moe_gemm_test_params{
+ PHASE::UP, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::i4, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ 32, /*scale_group_size*/
+ true /*weight_symmetric_quant*/
+ },
+ // i4 / symmetric/ group size 32 / down
+ moe_gemm_test_params{
+ PHASE::DOWN, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(1280), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::i4, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ 32, /*scale_group_size*/
+ true /*weight_symmetric_quant*/
+ },
+ // u4 / asymmetric/ per_token / prefill
+ moe_gemm_test_params{
+ PHASE::PREFILL, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(2880), /*hidden_size*/
+ static_cast<size_t>(5760), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::u4, /*weight_dt*/
+ cldnn::data_types::f16, /*scale_dt*/
+ 2880, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // u4 / asymmetric/ group size 32 / prefill
+ moe_gemm_test_params{
+ PHASE::PREFILL, /*phase*/
+ static_cast<size_t>(50), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(2), /*num_experts_per_token*/
+ static_cast<size_t>(15), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::u4, /*weight_dt*/
+ cldnn::data_types::f32, /*scale_dt*/
+ 32, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // u4 / asymmetric/ group size 32 / up
+ moe_gemm_test_params{
+ PHASE::UP, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::u4, /*weight_dt*/
+ cldnn::data_types::f32, /*scale_dt*/
+ 32, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ },
+ // u4 / asymmetric/ group size 32 / down
+ moe_gemm_test_params{
+ PHASE::DOWN, /*phase*/
+ static_cast<size_t>(1), /*num_tokens*/
+ static_cast<size_t>(32), /*num_total_experts*/
+ static_cast<size_t>(4), /*num_experts_per_token*/
+ static_cast<size_t>(4), /*num_actually_used_experts*/
+ static_cast<size_t>(128), /*hidden_size*/
+ static_cast<size_t>(64), /*out_N*/
+ false, /*has_bias*/
+ cldnn::data_types::f16, /*input_dt*/
+ cldnn::data_types::u4, /*weight_dt*/
+ cldnn::data_types::f32, /*scale_dt*/
+ 32, /*scale_group_size*/
+ false /*weight_symmetric_quant*/
+ }}));
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_mask_gen_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_mask_gen_gpu_test.cpp
new file mode 100644
index 00000000000..36b4a89439d
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_mask_gen_gpu_test.cpp
@@ -0,0 +1,101 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+#include <iostream>
+#include <numeric>
+#include "test_utils.h"
+#include "random_generator.hpp"
+
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+#include <intel_gpu/primitives/moe_mask_gen.hpp>
+
+using namespace cldnn;
+using namespace ov::intel_gpu;
+using namespace ::tests;
+
+TEST(moe_unit, moe_mask_gen_test) {
+ auto& engine = get_test_engine();
+ // num total experts 32
+ // num active experts 2
+ // input activation [30, 64]
+ // topk [30, 2]
+ // output expert_info_offsets [32]
+ // output tokens_indices_per_expert [30*2]
+
+ std::vector<int32_t> topk_idx = {
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4 ,8,
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4 ,8,
+ 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4 ,8,
+ };
+
+ int64_t num_tokens = 30;
+ int64_t num_active_experts_per_token = 2;
+ int32_t num_actually_used_experts = 2;
+ // input shape
+ auto topk_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension(num_active_experts_per_token)};
+ auto topk_layout = layout{topk_shape, data_types::i32, format::bfyx};
+
+ std::vector<int32_t> num_actually_used_experts_ref = {num_actually_used_experts};
+ topology topology(
+ input_layout("input_topk", topk_layout),
+ moe_mask_gen("moe_mask_gen", input_info("input_topk"), 32, 2),
+ moe_mask_gen_reshape("moe_mask_gen_reshape",
+ input_info("moe_mask_gen", 0),
+ input_info("moe_mask_gen", 1),
+ input_info("moe_mask_gen", 2),
+ input_info("moe_mask_gen", 3),
+ input_info("moe_mask_gen", 4)),
+ reorder("num_actual_used_experts",
+ input_info("moe_mask_gen", moe_mask_gen::MoEMaskGenOutputIdx::NUM_ACTUALLY_USED_EXPERTS),
+ format::bfyx,
+ data_types::f32),
+ reorder("tokens_per_experts", input_info("moe_mask_gen_reshape", moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_PER_EXPERT), format::bfyx, data_types::f32),
+ reorder("experts_info_start_idx", input_info("moe_mask_gen_reshape", moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_INFO_START_IDX), format::bfyx, data_types::f32),
+ reorder("experts_ids", input_info("moe_mask_gen_reshape", moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::EXPERTS_ID), format::bfyx, data_types::f32),
+ reorder("tokens_lens_per_expert",
+ input_info("moe_mask_gen_reshape", moe_mask_gen_reshape::MoEMaskGenReshapeOutputIdx::TOKENS_LENS_PER_EXPERT),
+ format::bfyx,
+ data_types::f32));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ auto network = get_network(engine, topology, config, get_test_stream_ptr(), false);
+
+ auto topk_data_shape = ov::PartialShape{ov::Dimension(num_tokens), ov::Dimension(num_active_experts_per_token)};
+ auto topk_data_layout = layout{topk_data_shape, data_types::i32, format::bfyx};
+ auto topk_idx_mem = engine.allocate_memory(topk_data_layout);
+ set_values(topk_idx_mem, topk_idx);
+ network->set_input_data("input_topk", topk_idx_mem);
+
+ auto outputs = network->execute();
+ const auto& output_num_actual_experts = outputs.at("num_actual_used_experts").get_memory();
+
+ cldnn::mem_lock<float, mem_lock_type::read> output_num_actual_experts_ptr(output_num_actual_experts, get_test_stream());
+ ASSERT_EQ(static_cast<int32_t>(output_num_actual_experts_ptr[0]), num_actually_used_experts);
+
+ const auto& output_tokens_per_experts = outputs.at("tokens_per_experts").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_tokens_per_experts_ptr(output_tokens_per_experts, get_test_stream());
+ std::vector<float> tokens_per_expert_ref = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
+ for (size_t i = 0; i < static_cast<size_t>(num_tokens * num_active_experts_per_token); i++) {
+ ASSERT_EQ(output_tokens_per_experts_ptr[i], tokens_per_expert_ref[i]);
+ }
+ std::vector<float> expert_ids_ref = {4, 8};
+ const auto& output_expert_ids = outputs.at("experts_ids").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_expert_ids_ptr(output_expert_ids, get_test_stream());
+ for (size_t i = 0; i < static_cast<size_t>(num_actually_used_experts); i++) {
+ ASSERT_EQ(static_cast<int32_t>(output_expert_ids_ptr[i]), expert_ids_ref[i]);
+ }
+ std::vector<float> experts_info_start_idx_ref = {0, 30};
+ const auto& output_experts_info_start_idx = outputs.at("experts_info_start_idx").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_experts_info_start_idx_ptr(output_experts_info_start_idx, get_test_stream());
+ for (size_t i = 0; i < static_cast<size_t>(num_actually_used_experts); i++) {
+ ASSERT_EQ(static_cast<int32_t>(output_experts_info_start_idx_ptr[i]), experts_info_start_idx_ref[i]);
+ }
+ std::vector<float> tokens_lens_per_expert_ref = {30, 30};
+ const auto& output_tokens_lens_per_expert = outputs.at("tokens_lens_per_expert").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_tokens_lens_per_expert_ptr(output_tokens_lens_per_expert, get_test_stream());
+ for (size_t i = 0; i < static_cast<size_t>(num_actually_used_experts); i++) {
+ ASSERT_EQ(static_cast<int32_t>(output_tokens_lens_per_expert_ptr[i]), tokens_lens_per_expert_ref[i]);
+ }
+}
\ No newline at end of file
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_scatter_reduction_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_scatter_reduction_gpu_test.cpp
new file mode 100644
index 00000000000..36226e187d7
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_scatter_reduction_gpu_test.cpp
@@ -0,0 +1,259 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+#include <iostream>
+#include <numeric>
+#include "test_utils.h"
+#include "random_generator.hpp"
+
+#include <intel_gpu/primitives/data.hpp>
+#include <intel_gpu/primitives/reorder.hpp>
+#include <intel_gpu/primitives/moe_scatter_reduction.hpp>
+#include <intel_gpu/op/moe_compressed.hpp>
+
+using namespace cldnn;
+using namespace ov::intel_gpu;
+using namespace ::tests;
+
+template <typename T, typename TN>
+std::vector<T> flatten (const std::vector<std::vector<TN>>& vec2d) {
+ std::vector<T> res;
+ for (auto row : vec2d) {
+ for (auto col : row) {
+ res.push_back(static_cast<T>(col));
+ }
+ }
+ return res;
+}
+
+template <typename T, typename ShapeType>
+auto create_layout(ShapeType shape) {
+ if constexpr (std::is_same_v<T, float>)
+ return layout{shape, data_types::f32, format::bfyx};
+ else
+ return layout{shape, data_types::f16, format::bfyx};
+}
+
+
+template <typename T>
+void test_moe_scatter_reduction(bool is_caching_test, size_t k) {
+ auto& engine = get_test_engine();
+ // num_tokens 30
+ // hidden_size 64
+ // num total experts 32
+ // num_active_experts_per_token 2
+ // num_actual_used_experts 7
+ // input0 activation [30, 64]
+ // input1 experts_info_offset [7]
+ // input2 tokens_per_expert [30*2*64]
+ size_t num_tokens = 30;
+ size_t num_total_experts = 32;
+ size_t hidden_size = k;
+ size_t num_active_experts_per_token = 2;
+
+ ov::intel_gpu::op::MOECompressed::Config moe_config;
+ moe_config.top_k = num_active_experts_per_token;
+ moe_config.has_batch_dim = false;
+
+ auto input_activation_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), ov::Dimension(hidden_size)};
+ auto input_activation_layout = create_layout<T>(input_activation_shape);
+
+ auto experts_per_token_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension(num_active_experts_per_token)};
+ auto experts_per_token_layout = layout{experts_per_token_shape, data_types::i32, format::bfyx};
+
+ auto expert_weights_per_token_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension(num_active_experts_per_token)};
+ auto expert_weights_per_token_layout = create_layout<T>(expert_weights_per_token_shape);
+
+ auto experts_info_offsets_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto experts_info_offsets_layout = layout{experts_info_offsets_shape, data_types::i32, format::bfyx};
+
+ auto tokens_per_expert_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto tokens_per_expert_layout = layout{tokens_per_expert_shape, data_types::i32, format::bfyx};
+
+ auto tokens_len_per_expert_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto tokens_len_per_expert_layout = layout{tokens_len_per_expert_shape, data_types::i32, format::bfyx};
+
+ auto experts_ids_shape = ov::PartialShape{ov::Dimension::dynamic()};
+ auto experts_ids_layout = layout{experts_ids_shape, data_types::i32, format::bfyx};
+
+ topology topology(input_layout("input", input_activation_layout),
+ input_layout("experts_per_token", experts_per_token_layout),
+ input_layout("expert_weights_per_token", expert_weights_per_token_layout),
+ input_layout("tokens_per_expert", tokens_per_expert_layout),
+ input_layout("experts_info_offsets", experts_info_offsets_layout),
+ input_layout("tokens_len_per_expert", tokens_len_per_expert_layout),
+ input_layout("experts_ids", experts_ids_layout),
+ moe_scatter_reduction("moe_scatter_reduction",
+ input_info("input"),
+ input_info("experts_per_token"),
+ input_info("expert_weights_per_token"),
+ input_info("tokens_per_expert"),
+ input_info("experts_info_offsets"),
+ input_info("tokens_len_per_expert"),
+ input_info("experts_ids"),
+ moe_config));
+ auto input_data_shape = ov::PartialShape{ov::Dimension(num_tokens * num_active_experts_per_token), 1, ov::Dimension(hidden_size)};
+ auto input_data_layout = create_layout<T>(input_data_shape);
+
+ std::vector<T> input_data;
+ for (size_t i = 0; i < num_tokens * num_active_experts_per_token; ++i) {
+ for (size_t h = 0; h < hidden_size; ++h)
+ input_data.push_back(static_cast<T>(i));
+ }
+ auto input_mem = engine.allocate_memory(input_data_layout);
+ set_values(input_mem, input_data);
+
+ // topk result
+ std::vector<std::vector<int32_t>> experts_per_token = {{0, 5}, {5, 7}, {0, 10}, {11, 20}, {7, 10}, {0, 7}, {20, 31}, {11, 31}, {11, 20}, {7, 10},
+ {0, 5}, {11, 31}, {0, 7}, {0, 20}, {10, 31}, {10, 20}, {7, 31}, {0, 31}, {5, 31}, {7, 31},
+ {7, 20}, {0, 10}, {0, 5}, {5, 11}, {7, 11}, {5, 31}, {7, 31}, {0, 31}, {0, 10}, {11, 20}};
+
+ std::vector<std::vector<T>> expert_weights_per_token = {{1.0, .9}, {.8, .7}, {.6, .5}, {.4, .3}, {.2, .1}, {.9, .8}, {.7, .6}, {.5, .4}, {.3, .2}, {.1, .0},
+ {1.0, .9}, {.8, .7}, {.6, .5}, {.4, .3}, {.2, .1}, {.9, .8}, {.7, .6}, {.5, .4}, {.3, .2}, {.1, .0},
+ {1.0, .9}, {.8, .7}, {.6, .5}, {.4, .3}, {.2, .1}, {.9, .8}, {.7, .6}, {.5, .4}, {.3, .2}, {.1, .0}};
+
+ std::vector<std::vector<size_t>> tokens_per_expert_tmp(num_total_experts, std::vector<size_t>{});
+
+ for (size_t i = 0; i < experts_per_token.size(); ++i) {
+ for (size_t j = 0; j < experts_per_token[i].size(); ++j)
+ tokens_per_expert_tmp[experts_per_token[i][j]].push_back(i);
+ }
+
+ std::vector<int32_t> tokens_per_expert_data;
+ std::vector<int32_t> tokens_len_per_expert_data;
+ std::vector<int32_t> experts_ids_data;
+
+ for (size_t i = 0; i < tokens_per_expert_tmp.size(); ++i) {
+ if (tokens_per_expert_tmp[i].empty())
+ continue;
+ experts_ids_data.push_back(static_cast<int32_t>(i));
+ tokens_len_per_expert_data.push_back(static_cast<int32_t>(tokens_per_expert_tmp[i].size()));
+ for (size_t j = 0; j < tokens_per_expert_tmp[i].size(); ++j) {
+ tokens_per_expert_data.push_back(static_cast<int32_t>(tokens_per_expert_tmp[i][j]));
+ }
+ }
+
+ std::vector<int32_t> expert_info_start_idx(tokens_len_per_expert_data.size(), 0);
+ for (size_t i = 1; i < tokens_len_per_expert_data.size(); ++i) {
+ expert_info_start_idx[i] = static_cast<int32_t>(expert_info_start_idx[i - 1] + tokens_len_per_expert_data[i - 1]);
+ }
+
+ // tokens per expert
+ // experts 0, 5, 7, 10, 11, 20, 31 are used
+ // experts[0] offset : 0 {0, 2, 5, 10, 12, 13, 17, 21, 22, 27, 28}
+ // experts[5] offset : 11 {0, 1, 10, 18, 22, 23, 25}
+ // experts[7] offset : 18 {1, 4, 5, 9, 12, 16, 19, 20, 24, 26}
+ // experts[10] offset : 28 {2, 4, 9, 14, 15, 21, 28}
+ // experts[11] offset : 35 {3, 7, 8, 11, 23, 24, 29}
+ // experts[20] offset : 42 {3, 6, 8, 13, 15, 20, 29}
+ // experts[31] offset : 49 {6, 7, 11, 14, 16, 17, 18, 19, 25, 26, 27}
+
+ auto experts_per_token_data_shape = ov::PartialShape{ov::Dimension(num_tokens), ov::Dimension(num_active_experts_per_token)};
+ auto experts_per_token_data_layout = layout{experts_per_token_data_shape, data_types::i32, format::bfyx};
+ auto experts_per_token_data_mem = engine.allocate_memory(experts_per_token_data_layout);
+ set_values(experts_per_token_data_mem, flatten<int32_t>(experts_per_token));
+
+ auto expert_weights_per_token_data_shape = ov::PartialShape{ov::Dimension(num_tokens), ov::Dimension(num_active_experts_per_token)};
+ auto expert_weights_per_token_data_layout = create_layout<T>(expert_weights_per_token_data_shape);
+ auto expert_weights_per_token_data_mem = engine.allocate_memory(expert_weights_per_token_data_layout);
+ set_values(expert_weights_per_token_data_mem, flatten<T>(expert_weights_per_token));
+
+ auto tokens_per_expert_data_shape = ov::PartialShape{ov::Dimension(num_tokens * num_active_experts_per_token)};
+ auto tokens_per_expert_data_layout = layout{tokens_per_expert_data_shape, data_types::i32, format::bfyx};
+ auto tokens_per_expert_data_mem = engine.allocate_memory(tokens_per_expert_data_layout);
+ set_values(tokens_per_expert_data_mem, tokens_per_expert_data);
+
+ auto expert_info_offsets_data_shape = ov::PartialShape{ov::Dimension(expert_info_start_idx.size())};
+ auto expert_info_offsets_data_layout = layout{expert_info_offsets_data_shape, data_types::i32, format::bfyx};
+ auto expert_info_offsets_data_mem = engine.allocate_memory(expert_info_offsets_data_layout);
+ set_values(expert_info_offsets_data_mem, expert_info_start_idx);
+
+ auto tokens_len_per_expert_data_shape = ov::PartialShape{ov::Dimension(tokens_len_per_expert_data.size())};
+ auto tokens_len_per_expert_data_layout = layout{tokens_len_per_expert_data_shape, data_types::i32, format::bfyx};
+ auto tokens_len_per_expert_data_mem = engine.allocate_memory(tokens_len_per_expert_data_layout);
+ set_values(tokens_len_per_expert_data_mem, tokens_len_per_expert_data);
+
+ auto experts_ids_data_shape = ov::PartialShape{ov::Dimension(experts_ids_data.size())};
+ auto experts_ids_data_layout = layout{experts_ids_data_shape, data_types::i32, format::bfyx};
+ auto experts_ids_data_mem = engine.allocate_memory(experts_ids_data_layout);
+ set_values(experts_ids_data_mem, experts_ids_data);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ network network(engine, topology, config, is_caching_test);
+ network.set_input_data("input", input_mem);
+ network.set_input_data("experts_per_token", experts_per_token_data_mem);
+ network.set_input_data("expert_weights_per_token", expert_weights_per_token_data_mem);
+ network.set_input_data("tokens_per_expert", tokens_per_expert_data_mem);
+ network.set_input_data("experts_info_offsets", expert_info_offsets_data_mem);
+ network.set_input_data("tokens_len_per_expert", tokens_len_per_expert_data_mem);
+ network.set_input_data("experts_ids", experts_ids_data_mem);
+ auto outputs = network.execute();
+ auto output = outputs.begin()->second.get_memory();
+ cldnn::mem_lock<T, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<T> ref_output;
+ for (size_t i = 0; i < num_tokens; ++i) {
+ std::vector<T> token_output(hidden_size, 0.0f);
+ for (size_t j = 0; j < num_active_experts_per_token; j++) {
+ size_t expert_idx = experts_per_token[i][j];
+ float expert_weight = expert_weights_per_token[i][j];
+ auto it = std::find(experts_ids_data.begin(), experts_ids_data.end(), expert_idx);
+ size_t start_idx_pos = -1;
+ if (it != experts_ids_data.end())
+ start_idx_pos = std::distance(experts_ids_data.begin(), it);
+
+ for (size_t k = 0; k < tokens_per_expert_tmp[expert_idx].size(); k++) {
+ if (i == tokens_per_expert_tmp[expert_idx][k]) {
+ size_t input_idx = expert_info_start_idx[start_idx_pos] + k;
+ // copy out the data and multiply the weight then add to token output
+ std::vector<T> token_data(hidden_size);
+ std::copy(input_data.begin() + input_idx * hidden_size, input_data.begin() + (input_idx + 1)*hidden_size, token_data.begin());
+ std::transform(token_data.begin(), token_data.end(), token_data.begin(), [&expert_weight](auto& c){return c*expert_weight;});
+ std::transform(token_data.begin(), token_data.end(), token_output.begin(), token_output.begin(), std::plus<T>());
+ break;
+ }
+ }
+ }
+ ref_output.insert(ref_output.end(), token_output.begin(), token_output.end());
+ }
+
+ for (size_t i = 0; i < num_tokens * hidden_size; i++) {
+ EXPECT_NEAR(ref_output[i], output_ptr[i], 1e-1);
+ }
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_one_batch_aligned_f32) {
+ test_moe_scatter_reduction<float>(false, 64);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_one_batch_unaligned_f32) {
+ test_moe_scatter_reduction<float>(false, 66);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_multi_batch_aligned_f32) {
+ test_moe_scatter_reduction<float>(false, 2880);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_multi_batch_unaligned_f32) {
+ test_moe_scatter_reduction<float>(false, 2882);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_one_batch_aligned_f16) {
+ test_moe_scatter_reduction<ov::float16>(false, 64);
+}
+TEST(moe_unit, moe_scatter_reduction_test_one_batch_unaligned_f16) {
+ test_moe_scatter_reduction<ov::float16>(false, 66);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_multi_batch_aligned_f16) {
+ test_moe_scatter_reduction<ov::float16>(false, 2880);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_multi_batch_unaligned_f16) {
+ test_moe_scatter_reduction<ov::float16>(false, 2882);
+}
+
+TEST(moe_unit, moe_scatter_reduction_test_cached) {
+ test_moe_scatter_reduction<float>(true, 64);
+}
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/swiglu_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/swiglu_gpu_test.cpp
index 11bca6e27ba..c9714781587 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/swiglu_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/swiglu_gpu_test.cpp
@@ -16,7 +16,15 @@ using namespace ::tests;
class swiglu_gpu_test : public ::testing::TestWithParam<cldnn::format> {};
template <typename T>
-void swiglu_ref(const memory::ptr input, memory::ptr output, int32_t split_length) {
+void swiglu_ref(const memory::ptr input,
+ memory::ptr output,
+ int32_t swiglu_axis,
+ int32_t gate_idx,
+ int32_t glu_stride,
+ float clamp_min,
+ float clamp_max,
+ float swish_beta = 1.0f,
+ float up_add_val = 0.0f) {
auto input_layout = input->get_layout();
auto output_layout = output->get_layout();
@@ -28,18 +36,37 @@ void swiglu_ref(const memory::ptr input, memory::ptr output, int32_t split_lengt
cldnn::mem_lock<T> src(input, get_test_stream());
cldnn::mem_lock<T> dst(output, get_test_stream());
- T res;
for (uint32_t b = 0; b < batch_size; ++b) {
+ auto b_in = b;
+ if (glu_stride == 2 && swiglu_axis == 0)
+ b_in *= 2;
for (uint32_t f = 0; f < feature_size; ++f) {
+ auto f_in = f;
+ if (glu_stride == 2 && swiglu_axis == 1)
+ f_in *= 2;
for (uint32_t y = 0; y < y_size; ++y) {
+ auto y_in = y;
+ if (glu_stride == 2 && swiglu_axis == 2)
+ y_in *= 2;
for (uint32_t x = 0; x < x_size; ++x) {
- size_t src_offset = input_layout.get_linear_offset({static_cast<int32_t>(b), static_cast<int32_t>(f),
- static_cast<int32_t>(x), static_cast<int32_t>(y), 0, 0});
+ auto x_in = x;
+ if (glu_stride == 2 && swiglu_axis == 3)
+ x_in *= 2;
+ size_t src_offset = input_layout.get_linear_offset({static_cast<int32_t>(b_in), static_cast<int32_t>(f_in),
+ static_cast<int32_t>(x_in), static_cast<int32_t>(y_in), 0, 0});
size_t dst_offset = output_layout.get_linear_offset({static_cast<int32_t>(b), static_cast<int32_t>(f),
static_cast<int32_t>(x), static_cast<int32_t>(y), 0, 0});
- res = src[src_offset];
- res = (res / (static_cast<T>(1) + (std::exp((-(static_cast<T>(1) * res))))));
- res *= src[src_offset + static_cast<size_t>(split_length)];
+ T gate = src[src_offset];
+ T up = (glu_stride == 2) ? src[src_offset + 1] : src[src_offset + static_cast<size_t>(glu_stride)];
+ if (gate_idx == 1) {
+ std::swap(gate, up);
+ }
+ if (clamp_min != clamp_max) {
+ gate = std::min(static_cast<T>(clamp_max), gate);
+ up = std::min(static_cast<T>(clamp_max), std::max(static_cast<T>(clamp_min), up));
+ }
+ gate = (gate / (static_cast<T>(1) + (std::exp((-(static_cast<T>(swish_beta) * gate))))));
+ T res = (up + up_add_val) * gate;
dst[dst_offset] = res;
}
}
@@ -60,7 +87,7 @@ TEST(swiglu_gpu_test, swiglu_test_bfyx_dyn) {
-0.127686f, 0.066650f, -0.394043f, -0.135620f, 0.040985f, -0.011589f
});
- swiglu_ref<float>(input_mem, output_ref, 3);
+ swiglu_ref<float>(input_mem, output_ref, 2, 0, 3, 0., 0.);
topology topology;
topology.add(input_layout("input", input_layout_dynamic));
@@ -90,3 +117,94 @@ TEST(swiglu_gpu_test, swiglu_test_bfyx_dyn) {
EXPECT_NEAR(output_ptr[i], output_ref_ptr[i], 1e-3);
}
}
+
+TEST(swiglu_gpu_test, swiglu_test_bfyx_dyn_clamp) {
+ auto& engine = get_test_engine();
+
+ auto input_layout_dynamic = layout{ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), 6}, data_types::f32, format::bfyx};
+ auto input_mem = engine.allocate_memory({ov::PartialShape{2, 1, 6}, data_types::f32, format::bfyx});
+ auto output_ref = engine.allocate_memory({ov::PartialShape{2, 1, 3}, data_types::f32, format::bfyx});
+
+ auto clamp_min = -0.7;
+ auto clamp_max = 7.0;
+
+ set_values(input_mem, {4.9011f, 2.60f, -1.76636f, 0.16098f, 2.79297f, 3.6377f, -0.127686f, 6.6650f, -3.94043f, -1.35620f, 4.0985f, -1.1589f});
+
+ swiglu_ref<float>(input_mem, output_ref, 2, 0, 3, clamp_min, clamp_max);
+
+ topology topology;
+ topology.add(input_layout("input", input_layout_dynamic));
+ topology.add(swiglu("swiglu", input_info("input"), -1, 3, ov::op::internal::GLU::GluType::Swish, 0, clamp_min, clamp_max, 1.0f, 0.0f, tensor()));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ network network(engine, topology, config);
+
+ network.set_input_data("input", input_mem);
+
+ auto inst = network.get_primitive("swiglu");
+ auto impl = inst->get_impl();
+ ASSERT_TRUE(impl != nullptr);
+ ASSERT_TRUE(impl->is_dynamic());
+
+ auto outputs = network.execute();
+ ASSERT_EQ(outputs.size(), size_t(1));
+ ASSERT_EQ(outputs.begin()->first, "swiglu");
+
+ auto output = outputs.begin()->second.get_memory();
+ cldnn::mem_lock<float> output_ptr(output, get_test_stream());
+ cldnn::mem_lock<float> output_ref_ptr(output_ref, get_test_stream());
+
+ for (unsigned int i = 0; i < output_ref->count(); ++i) {
+ EXPECT_NEAR(output_ptr[i], output_ref_ptr[i], 1e-3);
+ }
+}
+
+TEST(swiglu_gpu_test, swiglu_test_bfyx_dyn_clamp_swish_beta_up_add_val) {
+ auto& engine = get_test_engine();
+ ov::PartialShape input_shape = ov::PartialShape{ov::Dimension::dynamic(), ov::Dimension::dynamic(), 6};
+ auto input_layout_dynamic = layout{input_shape, data_types::f32, format::bfyx};
+ auto input_mem = engine.allocate_memory({ov::PartialShape{2, 1, 6}, data_types::f32, format::bfyx});
+ auto output_ref = engine.allocate_memory({ov::PartialShape{2, 1, 3}, data_types::f32, format::bfyx});
+
+ auto clamp_min = -0.7f;
+ auto clamp_max = 7.0f;
+
+ int32_t gate_idx = 0;
+ int32_t glu_stride = 2;
+ float swish_beta = 1.2f;
+ float up_add_val = 1.0f;
+
+ set_values(input_mem, {4.9011f, 2.60f, -1.76636f, 0.16098f, 2.79297f, 3.6377f, -0.127686f, 6.6650f, -3.94043f, -1.35620f, 4.0985f, -1.1589f});
+
+ swiglu_ref<float>(input_mem, output_ref, 2, gate_idx, glu_stride, clamp_min, clamp_max, swish_beta, up_add_val);
+
+ topology topology;
+ topology.add(input_layout("input", input_layout_dynamic));
+ topology.add(swiglu("swiglu", input_info("input"), -1, glu_stride, ov::op::internal::GLU::GluType::Swish, gate_idx, clamp_min, clamp_max, swish_beta, up_add_val, tensor()));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+
+ network network(engine, topology, config);
+
+ network.set_input_data("input", input_mem);
+
+ auto inst = network.get_primitive("swiglu");
+ auto impl = inst->get_impl();
+ ASSERT_TRUE(impl != nullptr);
+ ASSERT_TRUE(impl->is_dynamic());
+
+ auto outputs = network.execute();
+ ASSERT_EQ(outputs.size(), size_t(1));
+ ASSERT_EQ(outputs.begin()->first, "swiglu");
+
+ auto output = outputs.begin()->second.get_memory();
+ cldnn::mem_lock<float> output_ptr(output, get_test_stream());
+ cldnn::mem_lock<float> output_ref_ptr(output_ref, get_test_stream());
+
+ for (unsigned int i = 0; i < output_ref->count(); ++i) {
+ EXPECT_NEAR(output_ptr[i], output_ref_ptr[i], 1e-3);
+ }
+}
\ No newline at end of file
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/swish_with_clamp_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/swish_with_clamp_fusion_test.cpp
new file mode 100644
index 00000000000..ba4e7abeb01
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/transformations/swish_with_clamp_fusion_test.cpp
@@ -0,0 +1,132 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <string>
+
+#include "plugin/transformations/swiglu_fusion_with_clamp.hpp"
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/op/add.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/split.hpp"
+#include "openvino/op/minimum.hpp"
+#include "openvino/op/clamp.hpp"
+#include "intel_gpu/op/swiglu_with_clamp.hpp"
+#include "openvino/opsets/opset4_decl.hpp"
+#include "openvino/pass/manager.hpp"
+#include "transformations/init_node_info.hpp"
+#include "transformations/utils/utils.hpp"
+using namespace ov;
+using namespace testing;
+using namespace ov::intel_gpu;
+TEST_F(TransformationTestsF, SwishFusionWithClamp) {
+ {
+ auto reshape = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{32, -1, 2880});
+ auto convert1 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 5760});
+ auto gemm_up = std::make_shared<ov::op::v0::MatMul>(reshape, convert1);
+ auto add_const1 = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{32, 1, 5760});
+ auto add_gemm = std::make_shared<ov::op::v1::Add>(gemm_up, add_const1);
+
+ auto start1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {0});
+ auto stop1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2880});
+ auto step = ov::op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto axis = ov::op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto slice1 = std::make_shared<ov::op::v8::Slice>(add_gemm, start1, stop1, step, axis);
+
+ auto start2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2880});
+ auto stop2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {5760});
+ auto slice2 = std::make_shared<ov::op::v8::Slice>(add_gemm, start2, stop2, step, axis);
+
+ auto min_val = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{1, 1, 1});
+ auto min = std::make_shared<ov::op::v1::Minimum>(slice1, min_val);
+ auto beta = ov::op::v0::Constant::create(element::f32, Shape{}, {1.7f});
+ auto swish = std::make_shared<ov::op::v4::Swish>(min, beta);
+
+ auto clamp = std::make_shared<ov::op::v0::Clamp>(slice2, -7.0, 7.0);
+ auto add_const2 = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{1, 1, 1});
+ auto add_clamp = std::make_shared<ov::op::v1::Add>(clamp, add_const2);
+
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(swish, add_clamp);
+
+ auto convert2 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 2880});
+
+ auto gemm_down = std::make_shared<ov::op::v0::MatMul>(multiply, convert2);
+
+ auto result = std::make_shared<ov::op::v0::Result>(gemm_down);
+
+ model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{reshape, convert1, convert2});
+
+ manager.register_pass<SwiGluFusionWithClamp>();
+ }
+ {
+ auto reshape = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{32, -1, 2880});
+ auto convert1 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 5760});
+ auto gemm_up = std::make_shared<ov::op::v0::MatMul>(reshape, convert1);
+ auto swiglu_with_clamp = std::make_shared<
+ ov::intel_gpu::op::SwiGluWithClamp>(gemm_up, 2, 2880, ov::op::internal::GLU::GluType::Swish, 0, -7, 7, 1.7f, 0.0f, ov::element::Type_t::f32);
+ auto result = std::make_shared<ov::op::v0::Result>(swiglu_with_clamp);
+
+ model_ref = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{reshape, convert1});
+ }
+}
+
+TEST_F(TransformationTestsF, SwishFusionWithClampStrided) {
+ {
+ auto reshape = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{32, -1, 2880});
+ auto convert1 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 5760});
+ auto gemm_up = std::make_shared<ov::op::v0::MatMul>(reshape, convert1);
+ auto add_const1 = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{32, 1, 5760});
+ auto add_gemm = std::make_shared<ov::op::v1::Add>(gemm_up, add_const1);
+
+ auto start1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {0});
+ auto stop1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {5760});
+ auto step1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto axis1 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto slice1 = std::make_shared<ov::op::v8::Slice>(add_gemm, start1, stop1, step1, axis1);
+
+ auto start2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto stop2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {5760});
+ auto step2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto axis2 = ov::op::v0::Constant::create(element::i64, Shape{1}, {2});
+ auto slice2 = std::make_shared<ov::op::v8::Slice>(add_gemm, start2, stop2, step2, axis2);
+
+ auto min_val = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{1, 1, 1});
+ auto min = std::make_shared<ov::op::v1::Minimum>(slice1, min_val);
+ auto beta = ov::op::v0::Constant::create(element::f32, Shape{}, {1.7f});
+ auto swish = std::make_shared<ov::op::v4::Swish>(min, beta);
+
+ auto clamp = std::make_shared<ov::op::v0::Clamp>(slice2, -7.0, 7.0);
+ auto add_const2 = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{1, 1, 1});
+ auto add_clamp = std::make_shared<ov::op::v1::Add>(clamp, add_const2);
+
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(swish, add_clamp);
+
+ auto convert2 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 2880});
+
+ auto gemm_down = std::make_shared<ov::op::v0::MatMul>(multiply, convert2);
+
+ auto result = std::make_shared<ov::op::v0::Result>(gemm_down);
+
+ model = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{reshape, convert1, convert2});
+
+ manager.register_pass<SwiGluFusionWithClamp>();
+ }
+ {
+ auto reshape = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{32, -1, 2880});
+ auto convert1 = std::make_shared<ov::op::v0::Parameter>(element::f32, Shape{32, 2880, 5760});
+ auto gemm_up = std::make_shared<ov::op::v0::MatMul>(reshape, convert1);
+ auto swiglu_with_clamp = std::make_shared<
+ ov::intel_gpu::op::SwiGluWithClamp>(gemm_up, 2, 2, ov::op::internal::GLU::GluType::Swish, 0, -7, 7, 1.7f, 0.0f, ov::element::Type_t::f32);
+ auto result = std::make_shared<ov::op::v0::Result>(swiglu_with_clamp);
+
+ model_ref = std::make_shared<ov::Model>(ResultVector{result}, ParameterVector{reshape, convert1});
+ }
+}