OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] integration of OneDNN grouped_gemm (#34153)
Eddy Kimbb01920499cc
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.hppindex 62e31d1aea6..772e5847670 100644--- 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@@ -35,37 +35,48 @@ struct moe_mask_gen : public primitive_base<moe_mask_gen> {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)+ const int32_t num_experts_per_token,+ const bool onednn_grouped_gemm_used = false): primitive_base(id, {router_idx}, 5),num_total_experts(num_total_experts),- num_experts_per_token(num_experts_per_token) {}+ num_experts_per_token(num_experts_per_token),+ onednn_grouped_gemm_used(onednn_grouped_gemm_used) {}int32_t num_total_experts = 0;int32_t num_experts_per_token = 0;+ bool onednn_grouped_gemm_used = false;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();+ seed = hash_combine(seed, onednn_grouped_gemm_used);+ return seed;}bool operator==(const primitive& rhs) const override {if (!compare_common_params(rhs))return false;- return true;+ if (auto rhs_casted = dynamic_cast<const moe_mask_gen*>(&rhs)) {+ return num_total_experts == rhs_casted->num_total_experts &&+ num_experts_per_token == rhs_casted->num_experts_per_token &&+ onednn_grouped_gemm_used == rhs_casted->onednn_grouped_gemm_used;+ }+ return false;}void save(BinaryOutputBuffer& ob) const override {primitive_base<moe_mask_gen>::save(ob);ob << num_total_experts;ob << num_experts_per_token;+ ob << onednn_grouped_gemm_used;}void load(BinaryInputBuffer& ib) override {primitive_base<moe_mask_gen>::load(ib);ib >> num_total_experts;ib >> num_experts_per_token;+ ib >> onednn_grouped_gemm_used;}};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.hppindex 97d78807ba2..c54c5b2e120 100644--- 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@@ -33,18 +33,22 @@ struct moe_scatter_reduction : public primitive_base<moe_scatter_reduction> {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)+ const ov::intel_gpu::op::MOECompressed::Config& moe_config,+ const bool onednn_grouped_gemm_used = false): 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) {}+ has_batch_dim(moe_config.has_batch_dim),+ onednn_grouped_gemm_used(onednn_grouped_gemm_used) {}int32_t num_active_experts_per_token = 0;bool has_batch_dim = true;+ bool onednn_grouped_gemm_used = false;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);+ seed = hash_combine(seed, onednn_grouped_gemm_used);return seed;}@@ -54,19 +58,23 @@ struct moe_scatter_reduction : public primitive_base<moe_scatter_reduction> {auto rhs_casted = downcast<const moe_scatter_reduction>(rhs);- return num_active_experts_per_token == rhs_casted.num_active_experts_per_token;+ return num_active_experts_per_token == rhs_casted.num_active_experts_per_token &&+ has_batch_dim == rhs_casted.has_batch_dim &&+ onednn_grouped_gemm_used == rhs_casted.onednn_grouped_gemm_used;}void save(BinaryOutputBuffer& ob) const override {primitive_base<moe_scatter_reduction>::save(ob);ob << num_active_experts_per_token;ob << has_batch_dim;+ ob << onednn_grouped_gemm_used;}void load(BinaryInputBuffer& ib) override {primitive_base<moe_scatter_reduction>::load(ib);ib >> num_active_experts_per_token;ib >> has_batch_dim;+ ib >> onednn_grouped_gemm_used;}};}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.cppdeleted file mode 100644index b0bdc664059..00000000000--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.cpp+++ /dev/null@@ -1,104 +0,0 @@-// Copyright (C) 2018-2026 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.hppdeleted file mode 100644index e205e4e6955..00000000000--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm.hpp+++ /dev/null@@ -1,104 +0,0 @@-// Copyright (C) 2018-2026 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::ocldiff --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.cppdeleted file mode 100644index f492091094f..00000000000--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.cpp+++ /dev/null@@ -1,347 +0,0 @@-// Copyright (C) 2018-2026 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"-#include "gemmstone/kernel_selector.hpp"--// clang-format on-namespace ov::intel_gpu::ocl {--namespace {-void entryObserver(const gemmstone::kcatalog::Entry* entry, double score, gemmstone::EvaluateAuxOutput aux) {- GPU_DEBUG_TRACE_DETAIL << "consider strategy: " << entry->str() << ", score: " << score << "\n";-};-} // anonymous namespace--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);- size_t expert_stride = weight_shape.size() == 4 ? (weight_shape[1] * weight_shape[2] * weight_shape[3]) : (weight_shape[1] * weight_shape[2]);- if (is_u4_i4) {- jit.make("EXPERT_STRIDE", expert_stride / 2);- jit.make("WEIGHT_COMPRESSED_INT4", 1);- } else {- jit.make("EXPERT_STRIDE", expert_stride);- }- 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::GEMMOptions opts_moe;- opts_moe.slmPtr = true;- opts_moe.kParallelLocal = !is_prefill;- 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 */- gemmstone::SelectionObserver observer = entryObserver;- gemm_moe = micro::select_gemm_microkernel(opts_moe, hw_info, sizes, problem_moe, &observer);- } 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{[](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_per_wg_k = static_cast<size_t>(gemm_p.getSetting("sg_per_wg_k"));- auto wg_tile_m = gemm_p.getSetting("wg_tile_m");- auto wg_tile_n = gemm_p.getSetting("wg_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, sg_per_wg_k};- wgs.global = {ceil_div(m, wg_tile_m), ceil_div(n, wg_tile_n), static_cast<size_t>(rtp->num_actually_used_experts)};- wgs.global[0] *= wgs.local[0];- wgs.global[1] *= wgs.local[1];- wgs.global[2] *= wgs.local[2];- 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, 0});- }- return kd;-}-} // namespace ov::intel_gpu::ocl-#endifdiff --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.hppdeleted file mode 100644index 68483157903..00000000000--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_gemm_gen_micro.hpp+++ /dev/null@@ -1,46 +0,0 @@-// Copyright (C) 2018-2026 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::ocldiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_mask_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_mask_gen.cppindex 03db92ce1a8..2968563c5f1 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_mask_gen.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_mask_gen.cpp@@ -22,6 +22,7 @@ protected:auto prim = params.typed_desc<moe_mask_gen>();jit.make("NUM_EXPERTS_PER_TOKEN", prim->num_experts_per_token);+ jit.make("ONEDNN_GROUPED_GEMM_USED", prim->onednn_grouped_gemm_used);return jit;}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_opt.cppindex a769e4599b5..f9ebd404f24 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_opt.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_opt.cpp@@ -50,6 +50,7 @@ protected:jit.make("HIDDEN_SIZE", hidden_size);jit.make("VEC_BLK_SIZE", MoeScatterReductionOpt::block_size);jit.make("BATCHES_PER_THREAD", batches_per_thread);+ jit.make("ONEDNN_GROUPED_GEMM_USED", desc->onednn_grouped_gemm_used);return jit;}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_ref.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_ref.cppindex c3d2de405ae..13cfeb6e9a2 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_ref.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_scatter_reduction_ref.cpp@@ -27,6 +27,7 @@ protected:jit.make("ACTIVE_EXPERTS", desc->num_active_experts_per_token);jit.make("HIDDEN_SIZE", hidden_size);+ jit.make("ONEDNN_GROUPED_GEMM_USED", desc->onednn_grouped_gemm_used);return jit;}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.clindex a349681299e..a89570edc5b 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl@@ -40,11 +40,17 @@ KERNEL(moe_mask_gen)(num_actual_used_experts[0] = experts_id_iter + is_used;}+ #if ONEDNN_GROUPED_GEMM_USED+ experts_info_start_idx[expert_id] = tokens_per_expert_iter + num_tokens_per_curr_expert;+ #endif+if (num_tokens_per_curr_expert == 0) {return;}- experts_info_start_idx[experts_id_iter] = tokens_per_expert_iter;+ #if !ONEDNN_GROUPED_GEMM_USED+ experts_info_start_idx[experts_id_iter] = tokens_per_expert_iter;+ #endifexperts_id[experts_id_iter] = expert_id;tokens_lens_per_expert[experts_id_iter] = num_tokens_per_curr_expert;diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_opt.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_opt.clindex 2db5222dd90..654ee63ad29 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_opt.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_scatter_reduction_opt.cl@@ -63,7 +63,12 @@ KERNEL(moe_scatter_reduction_ref)(continue;INPUT5_TYPE token_len = tokens_len_per_expert[start_offset_index[i]];- INPUT4_TYPE expert_offset = experts_start_offset[start_offset_index[i]];+ #if ONEDNN_GROUPED_GEMM_USED+ INPUT6_TYPE expert_id = experts_ids[start_offset_index[i]];+ INPUT4_TYPE expert_offset = expert_id == 0 ? 0 : experts_start_offset[expert_id - 1];+ #else+ INPUT4_TYPE expert_offset = experts_start_offset[start_offset_index[i]];+ #endif// Hybrid search: use single thread for short sequences to benefit from early exit,// and parallel search for long sequences to utilize memory bandwidth.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.clindex 701e06ab6d7..f3bc33be6df 100644--- 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@@ -29,7 +29,11 @@ KERNEL(moe_scatter_reduction_ref)(break;}}- uint exp_offset_start = experts_start_offset[idx];+ #if ONEDNN_GROUPED_GEMM_USED+ uint exp_offset_start = expert_id == 0 ? 0 : experts_start_offset[expert_id - 1];+ #else+ uint exp_offset_start = experts_start_offset[idx];+ #endifuint input_len = tokens_len_per_expert[idx];uint input_offset = 0;for (uint t = 0; t < input_len; ++t) {diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.cpp b/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.cppnew file mode 100644index 00000000000..31b94ee223f--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.cpp@@ -0,0 +1,203 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_gemm_onednn.hpp"+#include "intel_gpu/runtime/utils.hpp"+#include "primitive_onednn_base.h"++#include <oneapi/dnnl/dnnl.hpp>+#include <oneapi/dnnl/dnnl_ocl.hpp>++#include <algorithm>+#include <memory>++namespace cldnn {+namespace onednn {++struct moe_gemm_onednn : typed_primitive_onednn_impl<moe_gemm> {+ using parent = typed_primitive_onednn_impl<moe_gemm>;+ using parent::parent;++ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::onednn::moe_gemm_onednn)++protected:+ std::unique_ptr<primitive_impl> clone() const override {+ return std::make_unique<moe_gemm_onednn>(*this);+ }++ std::unordered_map<int, dnnl::memory> get_arguments(moe_gemm_inst& instance) const override {+ std::unordered_map<int, dnnl::memory> args;+ auto& engine = instance.get_network().get_engine();+ auto& onednn_engine = engine.get_onednn_engine();+ auto moe_cfg = MoEGemmImplementationManager::get_moe_cfg(*instance.get_impl_params());++ {+ auto& input = instance.input_memory(moe_gemm::MoEGemmInputIdx::INPUT);+ auto& offsets = instance.input_memory(moe_gemm::MoEGemmInputIdx::INPUT_OFFSET_PER_EXPERT);+ OPENVINO_ASSERT(input.get_allocation_type() >= allocation_type::usm_host, "[GPU] oneDNN MOE GEMM implementation supports only USM input memory");+ dnnl::memory input_mem = dnnl::ocl_interop::make_memory(_pd.src_desc(0), onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ {reinterpret_cast<uint8_t*>(input.buffer_ptr()), reinterpret_cast<uint8_t*>(offsets.buffer_ptr())});++ args.insert({DNNL_ARG_SRC, input_mem});+ }++ {+ auto& output = instance.output_memory(0);+ auto& offsets = instance.input_memory(moe_gemm::MoEGemmInputIdx::INPUT_OFFSET_PER_EXPERT);+ OPENVINO_ASSERT(output.get_allocation_type() >= allocation_type::usm_host, "[GPU] oneDNN MOE GEMM implementation supports only USM output memory");+ dnnl::memory output_mem = dnnl::ocl_interop::make_memory(_pd.dst_desc(0), onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ {reinterpret_cast<uint8_t*>(output.buffer_ptr()), reinterpret_cast<uint8_t*>(offsets.buffer_ptr())});++ args.insert({DNNL_ARG_DST, output_mem});+ }++ {+ auto& weights = instance.input_memory(moe_gemm::MoEGemmInputIdx::WEIGHT);+ dnnl::memory weights_mem = dnnl::ocl_interop::make_memory(_pd.weights_desc(0), onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ reinterpret_cast<uint8_t*>(weights.buffer_ptr()));+ args.insert({DNNL_ARG_WEIGHTS, weights_mem});+ }++ if (moe_cfg.is_weight_quantized) {+ auto& wei_scales = instance.input_memory(moe_cfg.weight_scale_idx);+ auto wei_scales_shape = wei_scales.get_layout().get_shape();+ dnnl::memory::dim d0 = wei_scales_shape[0];+ dnnl::memory::dim d1 = wei_scales_shape[1];+ dnnl::memory::dim d2 = wei_scales_shape[2];+ dnnl::memory::dims wei_scales_dims = (moe_cfg.weight_group_size == -1) ? dnnl::memory::dims{d0, d2} : dnnl::memory::dims{d0, d1, d2};+ dnnl::memory::format_tag wei_scales_fmt = (moe_cfg.weight_group_size == -1) ? dnnl::memory::format_tag::ab : dnnl::memory::format_tag::abc;+ dnnl::memory::desc wei_scales_md(+ wei_scales_dims, convert_data_type(wei_scales.get_layout().data_type), wei_scales_fmt);+ dnnl::memory wei_scales_mem = dnnl::ocl_interop::make_memory(wei_scales_md, onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ reinterpret_cast<uint8_t*>(wei_scales.buffer_ptr()));+ args.insert({DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, wei_scales_mem});++ if (!moe_cfg.is_weight_symmetric_quantized) {+ auto& wei_zp = instance.input_memory(moe_cfg.weight_zp_idx);+ dnnl::memory::desc wei_zp_md(+ wei_scales_dims, convert_data_type(wei_zp.get_layout().data_type), wei_scales_fmt);+ dnnl::memory wei_zp_mem = dnnl::ocl_interop::make_memory(wei_zp_md, onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ reinterpret_cast<uint8_t*>(wei_zp.buffer_ptr()));+ args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, wei_zp_mem});+ }+ }++ if (moe_cfg.has_bias) {+ auto& bias = instance.input_memory(moe_gemm::MoEGemmInputIdx::BIAS);+ dnnl::memory bias_mem = dnnl::ocl_interop::make_memory(_pd.weights_desc(1), onednn_engine, dnnl::ocl_interop::memory_kind::usm,+ reinterpret_cast<uint8_t*>(bias.buffer_ptr()));+ args.insert({DNNL_ARG_BIAS, bias_mem});+ }++ return args;+ }++ static std::shared_ptr<dnnl::matmul::primitive_desc>+ get_moe_gemm_primitive_descriptor(const kernel_impl_params& impl_params,+ const dnnl::primitive_attr& attr = dnnl::primitive_attr()) {+ auto& engine = impl_params.prog->get_engine();+ auto prim = impl_params.typed_desc<moe_gemm>();+ auto moe_cfg = MoEGemmImplementationManager::get_moe_cfg(impl_params);++ auto input_layout = impl_params.get_input_layout(moe_gemm::MoEGemmInputIdx::INPUT);+ auto weights_layout = impl_params.get_input_layout(moe_gemm::MoEGemmInputIdx::WEIGHT);+ auto output_layout = impl_params.get_output_layout();++ dnnl::memory::dim total_tokens = prim->has_batch_dim ? input_layout.get_shape()[1] : input_layout.get_shape()[0];+ const auto& experts_weight_shape = weights_layout.get_shape();+ dnnl::memory::dim N = experts_weight_shape[1];+ dnnl::memory::dim K = experts_weight_shape.size() == 4 ? experts_weight_shape[2] * experts_weight_shape[3] : experts_weight_shape[2];+ dnnl::memory::dim num_experts = experts_weight_shape[0];++ dnnl::memory::dims input_dims = {total_tokens, K};+ dnnl::memory::dims weights_dims = {num_experts, K, N};+ dnnl::memory::dims output_dims = {total_tokens, N};++ auto input_md = dnnl::memory::desc::grouped(+ input_dims, convert_data_type(input_layout.data_type), 0, num_experts);+ auto output_md = dnnl::memory::desc::grouped(+ output_dims, convert_data_type(output_layout.data_type), 0, num_experts);+ auto weights_md = dnnl::memory::desc(+ weights_dims, convert_data_type(weights_layout.data_type), dnnl::memory::format_tag::acb);++ if (moe_cfg.has_bias) {+ auto bias_layout = impl_params.get_input_layout(moe_gemm::MoEGemmInputIdx::BIAS);+ auto bias_md = dnnl::memory::desc({num_experts, N}, convert_data_type(bias_layout.data_type), dnnl::memory::format_tag::ab);++ return std::make_shared<dnnl::matmul::primitive_desc>(+ engine.get_onednn_engine(),+ input_md,+ weights_md,+ bias_md,+ output_md,+ attr);+ } else {+ return std::make_shared<dnnl::matmul::primitive_desc>(+ engine.get_onednn_engine(),+ input_md,+ weights_md,+ output_md,+ attr);+ }+ }++public:+ void save(BinaryOutputBuffer& ob) const override {+ parent::save(ob);+ }++ void load(BinaryInputBuffer& ib) override {+ parent::load(ib);+ }++ static std::unique_ptr<primitive_impl> create(const moe_gemm_node& arg, const kernel_impl_params& impl_params) {+ auto& engine = impl_params.prog->get_engine();+ auto& config = impl_params.prog->get_config();+ auto attr = impl_params.attrs_onednn;+ auto prim = impl_params.typed_desc<moe_gemm>();+ auto moe_cfg = MoEGemmImplementationManager::get_moe_cfg(impl_params);++ if (moe_cfg.is_weight_quantized) {+ if (moe_cfg.weight_group_size == -1) {+ attr->set_scales(DNNL_ARG_WEIGHTS,+ (1 << 0) | (1 << 2),+ {},+ convert_data_type(impl_params.get_input_layout(moe_cfg.weight_scale_idx).data_type));+ } else {+ attr->set_scales(DNNL_ARG_WEIGHTS,+ (1 << 0) | (1 << 1) | (1 << 2),+ {moe_cfg.weight_group_size, 1},+ convert_data_type(impl_params.get_input_layout(moe_cfg.weight_scale_idx).data_type));+ }++ if (!moe_cfg.is_weight_symmetric_quantized) {+ if (moe_cfg.weight_group_size == -1) {+ attr->set_zero_points(DNNL_ARG_WEIGHTS,+ (1 << 0) | (1 << 2),+ {},+ convert_data_type(impl_params.get_input_layout(moe_cfg.weight_zp_idx).data_type));+ } else {+ attr->set_zero_points(DNNL_ARG_WEIGHTS,+ (1 << 0) | (1 << 1) | (1 << 2),+ {moe_cfg.weight_group_size, 1},+ convert_data_type(impl_params.get_input_layout(moe_cfg.weight_zp_idx).data_type));+ }+ }+ }++ auto prim_desc = get_moe_gemm_primitive_descriptor(impl_params, *attr);++ return std::make_unique<moe_gemm_onednn>(engine, config, attr, *prim_desc);+ }+};++std::unique_ptr<primitive_impl> MoEGemmImplementationManager::create_impl(const program_node& node, const kernel_impl_params& params) const {+ OPENVINO_ASSERT(node.is_type<moe_gemm>());+ return onednn::moe_gemm_onednn::create(static_cast<const moe_gemm_node&>(node), params);+}++} // namespace onednn+} // namespace cldnn++BIND_BINARY_BUFFER_WITH_TYPE(cldnn::onednn::moe_gemm_onednn)diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.hpp b/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.hppnew file mode 100644index 00000000000..2f5da9116e1--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/moe_gemm_onednn.hpp@@ -0,0 +1,176 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#ifndef ENABLE_ONEDNN_FOR_GPU+ #define ENABLE_ONEDNN_FOR_GPU 1+#endif+#include "moe_gemm_inst.h"+#include "intel_gpu/runtime/utils.hpp"+#include "registry/implementation_manager.hpp"++#include <memory>++namespace cldnn {+namespace onednn {++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;+};++struct MoEGemmImplementationManager : public ImplementationManager {+ OV_GPU_PRIMITIVE_IMPL("onednn::moe_gemm")+ MoEGemmImplementationManager(shape_types shape_type) : ImplementationManager(impl_types::onednn, shape_type) {}+ std::unique_ptr<primitive_impl> create_impl(const program_node& node, const kernel_impl_params& params) const override;++ bool validate_impl(const program_node& node) const override {+ OPENVINO_ASSERT(node.is_type<moe_gemm>());+ const auto& config = node.get_program().get_config();+ const auto& info = node.get_program().get_engine().get_device_info();+ if (!info.supports_immad || info.arch == gpu_arch::unknown || !config.get_use_onednn())+ 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;+ }++ in_out_fmts_t query_formats(const program_node& node) const override {+ OPENVINO_ASSERT(node.is_type<moe_gemm>());+ std::vector<format::type> in_fmts(node.get_dependencies().size(), format::any);+ std::vector<format::type> out_fmts(node.get_outputs_count(), format::any);++ for (size_t idx = 0 ; idx < node.get_dependencies().size() ; idx++) {+ if (node.get_dependency(idx).is_constant())+ continue;++ size_t out_rank = node.get_output_layout().get_rank();+ auto target_format = format::get_default_format(out_rank);++ in_fmts[idx] = target_format;++ if (out_fmts[0] == format::any) {+ out_fmts[0] = target_format;+ }+ }++ return {in_fmts, out_fmts};+ }++ 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];+ // weight scales : [#experts, num_groups, ofm, 1]+ auto scale_group_dim = 1;+ 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 = (num_scale_groups == 1) ? -1 : static_cast<int32_t>(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 onednn+} // namespace cldnndiff --git a/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp b/src/plugins/intel_gpu/src/graph/layout_optimizer.cppindex 21379c98bf7..88a91690bd9 100644--- a/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp+++ b/src/plugins/intel_gpu/src/graph/layout_optimizer.cpp@@ -22,6 +22,7 @@#include "gated_mlp_inst.h"#include "gemm_inst.h"+#include "moe_gemm_inst.h"#include "deconvolution_inst.h"#include "fully_connected_inst.h"#include "gru_seq_inst.h"@@ -1567,6 +1568,7 @@ void layout_optimizer::add_all_onednn_impls_optimization_attribute() {enable_onednn_for<pooling>();enable_onednn_for<reduce>();enable_onednn_for<reorder>();+ enable_onednn_for<moe_gemm>();}bool layout_optimizer::has_all_enabled_onednn_impls_optimization_attribute() {diff --git a/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp b/src/plugins/intel_gpu/src/graph/moe_mask_gen.cppindex a90c3f0e074..687fb19512d 100644--- a/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp+++ b/src/plugins/intel_gpu/src/graph/moe_mask_gen.cpp@@ -90,8 +90,7 @@ std::vector<layout> moe_mask_gen_reshape_inst::calc_output_layouts(moe_mask_gen_// tokens_per_expertoutput_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);+ output_layouts.emplace_back(impl_param.get_input_layout(1));// experts_idauto 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);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.cppindex 4d32e97b22e..747c3a3595d 100644--- a/src/plugins/intel_gpu/src/graph/registry/moe_gemm_impls.cpp+++ b/src/plugins/intel_gpu/src/graph/registry/moe_gemm_impls.cpp@@ -6,8 +6,8 @@#include "intel_gpu/primitives/moe_gemm.hpp"#include "primitive_inst.h"-#if OV_GPU_WITH_OCL- #include "impls/ocl_v2/moe/moe_gemm.hpp"+#if OV_GPU_WITH_ONEDNN+ #include "impls/onednn/moe_gemm_onednn.hpp"#endif@@ -17,8 +17,7 @@ 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)+ OV_GPU_CREATE_INSTANCE_ONEDNN(onednn::MoEGemmImplementationManager, shape_types::static_shape)};return impls;diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cppindex 532d08412b4..6c4b336907b 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp@@ -153,7 +153,8 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::oauto moe_mask_gen_prim = cldnn::moe_mask_gen(moe_mask_gen_name,input_infos[2], // topk indicesstatic_cast<int32_t>(config.num_expert),- static_cast<int32_t>(config.top_k));+ static_cast<int32_t>(config.top_k),+ true);p.add_primitive(*op, moe_mask_gen_prim);auto moe_mask_gen_reshape_prim =cldnn::moe_mask_gen_reshape(moe_mask_gen_reshape_name,@@ -239,7 +240,8 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::oinput_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);+ config,+ true);p.add_primitive(*op, moe_scatter_reduce_prim);}}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cppindex efe0b085258..19e54f58640 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_moe_to_compressed.cpp@@ -375,7 +375,7 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {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.group_size = (scale_shape.size() == 3) ? std::numeric_limits<size_t>::max() : 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;@@ -385,19 +385,27 @@ ConvertMOEToMOECompressed::ConvertMOEToMOECompressed(bool is_pa) {args.push_back(pattern_map.at(topk_indices_gemm2_m));// params for upargs.push_back(pattern_map.at(compressed_weights_m_up));- args.push_back(pattern_map.at(mul_const_m_up));+ auto transposed_index = (config.group_size == std::numeric_limits<size_t>::max()) ?+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1}) :+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 2, 1, 3});+ {+ auto scale = std::make_shared<ov::op::v1::Transpose>(pattern_map.at(mul_const_m_up), transposed_index);+ args.push_back(scale);+ }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);+ auto zp = std::make_shared<ov::op::v1::Transpose>(pattern_map.at(sub_const_m_up), transposed_index);args.push_back(zp);config.has_zp = true;}args.push_back(pattern_map.at(bias_up_gemm2_m));// params for downargs.push_back(pattern_map.at(compressed_weights_m_down));- args.push_back(pattern_map.at(mul_const_m_down));+ {+ auto scale = std::make_shared<ov::op::v1::Transpose>(pattern_map.at(mul_const_m_down), transposed_index);+ args.push_back(scale);+ }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);+ auto zp = std::make_shared<ov::op::v1::Transpose>(pattern_map.at(sub_const_m_down), transposed_index);args.push_back(zp);config.has_zp = true;} else if (config.has_zp) {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.cppindex ec154a3ffdd..d622b86411f 100644--- 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@@ -177,7 +177,8 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {int32_t group_size,bool is_symmetric,std::vector<ov::float16>& weight_scale,- std::vector<ov::float16>& weight_zp) {+ std::vector<ov::float16>& weight_zp_f16,+ std::vector<uint8_t>& 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;@@ -197,11 +198,16 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {OPENVINO_ASSERT(!is_symmetric);const uint8_t q_max = 15;const uint8_t q_min = 0;- float range = (float)amax - (float)amin;+ float famax = (float)amax;+ float famin = (float)amin;+ float range = famax - famin;if (range <= 1e-5f)range = 1e-2f;float inv_scale = (q_max - q_min) / range;- float zp_tmp = (float) (q_min - amin * inv_scale);+ float zp_tmp = (float) (q_min - famin * inv_scale);+ zp_tmp = std::min(std::max(zp_tmp, float(q_min)), float(q_max));+ uint8_t q_zp = static_cast<uint8_t>(std::round(zp_tmp));+ zp_tmp = q_zp; // ensure zp is in valid range after roundingov::float16 zp = zp_tmp;// quantize asym u4for (size_t ki = 0; ki < group_size / num_elements_per_byte; ki++) {@@ -215,7 +221,7 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {}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;+ weight_zp_f16[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;@@ -238,10 +244,35 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {}}}++ if (q_dt == cldnn::data_types::u4) {+ for (size_t b = 0; b < B; b++) {+ for (size_t g = 0; g < num_scale_groups; g++) {+ for (size_t n = 0; n < N; n += 2) {+ size_t idx0 = b * N * num_scale_groups + n * num_scale_groups + g;+ size_t idx1 = b * N * num_scale_groups + (n + 1) * num_scale_groups + g;+ uint8_t zp0 = static_cast<uint8_t>(std::round(float(weight_zp_f16[idx0])));+ uint8_t zp1 = static_cast<uint8_t>(std::round(float(weight_zp_f16[idx1])));+ uint8_t z0z1 = (zp1 << 4) | (zp0 & 0x0F);+ weight_zp[(b * N * num_scale_groups + g * N + n) / 2] = uint8_t(z0z1);+ }+ }+ }+ }+ }++ void transpose_weight_scales(const std::vector<ov::float16>& scales_data, std::vector<ov::float16>& scales_data_transposed, size_t num_total_experts, size_t num_scale_groups, size_t N) {+ for (size_t e = 0; e < num_total_experts; e++) {+ for (size_t n = 0; n < N; n++) {+ for (size_t g = 0; g < num_scale_groups; g++) {+ scales_data_transposed[e * N * num_scale_groups + g * N + n] = scales_data[e * N * num_scale_groups + n * num_scale_groups + g];+ }+ }+ }}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) {+ std::vector<ov::float16>& scales_data, std::vector<ov::float16>& zp_data_f16, std::vector<uint8_t>& 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;@@ -300,24 +331,27 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {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);+ zp_data_f16.resize(p.num_total_experts * p.out_N * num_scale_groups);+ zp_data.resize(p.num_total_experts * p.out_N * num_scale_groups / 2);}- 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);+ 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_f16, 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)} :+ auto scale_shape = num_scale_groups > 1 ? ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(num_scale_groups), ov::Dimension(p.out_N), 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);+ std::vector<ov::float16> scales_data_transposed(scales_data.size());+ transpose_weight_scales(scales_data, scales_data_transposed, p.num_total_experts, num_scale_groups, p.out_N);+ set_values(scale_mem, scales_data_transposed);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)} :+ auto zp_shape = num_scale_groups > 1 ? ov::PartialShape{ov::Dimension(p.num_total_experts), ov::Dimension(num_scale_groups), ov::Dimension(p.out_N), 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_layout = layout{zp_shape, p.weight_dt, 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);@@ -366,7 +400,8 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {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<ov::float16> zp_data_f16;+ std::vector<uint8_t> 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;@@ -374,9 +409,10 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {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);+ create_weight_data_and_topology(p, topo, experts_data_f16, experts_data_q4, scales_data, zp_data_f16, zp_data, is_weight_compressed);auto config = get_test_default_config(engine);config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ config.set_property(ov::intel_gpu::optimize_data(true));network network(engine, topo, config);auto get_input_data = [] (size_t M, size_t K, random_generator& rg) {@@ -407,20 +443,29 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {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_offset_per_expert_data_ref(p.num_actually_used_experts);+ std::vector<int32_t> input_offset_per_expert_data(p.num_total_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);+ input_offset_per_expert_data_ref[e] = static_cast<int32_t>(e * avg_len);+ }+ std::vector<int32_t> tokens_per_expert(p.num_total_experts, 0);+ for (size_t i = 0; i < p.num_actually_used_experts; i++) {+ tokens_per_expert[experts_ids_data[i]] = input_tokens_lens[i];+ }+ input_offset_per_expert_data[0] = tokens_per_expert[0];+ for (size_t e = 1; e < p.num_total_experts; e++) {+ input_offset_per_expert_data[e] = input_offset_per_expert_data[e - 1] + tokens_per_expert[e];}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_shape = ov::PartialShape{ov::Dimension(static_cast<int64_t>(p.num_total_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);@@ -432,18 +477,19 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {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_offset_per_expert_data_ref,input_tokens_lens,static_cast<int32_t>(p.out_N),static_cast<int32_t>(p.hidden_size),scales_data,- zp_data,+ zp_data_f16,p.scale_group_size,is_weight_compressed,p.weight_symmetric_quant,@@ -454,12 +500,12 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {experts_data_f16,output_ref,experts_ids_data,- input_offset_per_expert_data,+ input_offset_per_expert_data_ref,input_tokens_lens,static_cast<int32_t>(p.out_N),static_cast<int32_t>(p.hidden_size),scales_data,- zp_data,+ zp_data_f16,p.scale_group_size,is_weight_compressed,p.weight_symmetric_quant,@@ -469,6 +515,7 @@ struct MoEGemmTest : public ::testing::TestWithParam<T> {for (size_t i = 0; i < M * p.out_N; i++) {auto tolerance = std::max(std::abs(output_ref[i] * 0.01f), 0.1f);+ // std::cout << "[" << i << "] " << output_ref[i] << " : " << output_ptr[i] << std::endl;ASSERT_NEAR(output_ptr[i], output_ref[i], tolerance);}}@@ -536,12 +583,12 @@ INSTANTIATE_TEST_SUITE_P(smoke_moe_gemm,// i4 / symmetric/ group size 32 / prefillmoe_gemm_test_params{PHASE::PREFILL, /*phase*/- static_cast<size_t>(30), /*num_tokens*/+ static_cast<size_t>(32), /*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*/+ static_cast<size_t>(4), /*num_experts_per_token*/+ static_cast<size_t>(32), /*num_actually_used_experts*/+ static_cast<size_t>(2880), /*hidden_size*/+ static_cast<size_t>(2880), /*out_N*/false, /*has_bias*/cldnn::data_types::f16, /*input_dt*/cldnn::data_types::i4, /*weight_dt*/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.cppindex 1e185450ace..4d92fa3d1e6 100644--- 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@@ -1,5 +1,7 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//+#include <iostream>#include <numeric>#include "test_utils.h"@@ -29,6 +31,7 @@ TEST(moe_unit, moe_mask_gen_test) {};int64_t num_tokens = 30;+ int64_t num_total_experts = 32;int64_t num_active_experts_per_token = 2;int32_t num_actually_used_experts = 2;// input shape@@ -38,7 +41,7 @@ TEST(moe_unit, moe_mask_gen_test) {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("moe_mask_gen", input_info("input_topk"), 32, 2, true),moe_mask_gen_reshape("moe_mask_gen_reshape",input_info("moe_mask_gen", 0),input_info("moe_mask_gen", 1),@@ -86,10 +89,10 @@ TEST(moe_unit, moe_mask_gen_test) {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};+ std::vector<float> experts_info_start_idx_ref = {0, 0, 0, 0, 30, 30, 30, 30, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60};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++) {+ for (size_t i = 0; i < static_cast<size_t>(num_total_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};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.cppindex eca87fad219..2068a8ce53a 100644--- 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@@ -1,5 +1,7 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//+#include <iostream>#include <numeric>#include "test_utils.h"@@ -90,7 +92,8 @@ void test_moe_scatter_reduction(bool is_caching_test, size_t k) {input_info("experts_info_offsets"),input_info("tokens_len_per_expert"),input_info("experts_ids"),- moe_config));+ moe_config,+ true));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);@@ -132,9 +135,10 @@ void test_moe_scatter_reduction(bool is_caching_test, size_t k) {}}- 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]);+ std::vector<int32_t> expert_info_start_idx(num_total_experts, 0);+ expert_info_start_idx[0] = static_cast<int32_t>(tokens_per_expert_tmp[0].size());+ for (size_t i = 1; i < num_total_experts; ++i) {+ expert_info_start_idx[i] = static_cast<int32_t>(expert_info_start_idx[i - 1] + tokens_per_expert_tmp[i].size());}// tokens per expert@@ -198,14 +202,10 @@ void test_moe_scatter_reduction(bool is_caching_test, size_t k) {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;+ size_t input_idx = (expert_idx == 0) ? k : (expert_info_start_idx[expert_idx - 1] + k);// copy out the data and multiply the weight then add to token outputstd::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());diff --git a/src/plugins/intel_gpu/thirdparty/CMakeLists.txt b/src/plugins/intel_gpu/thirdparty/CMakeLists.txtindex 2bf709fc206..f5c54d4feb6 100644--- a/src/plugins/intel_gpu/thirdparty/CMakeLists.txt+++ b/src/plugins/intel_gpu/thirdparty/CMakeLists.txt@@ -133,6 +133,7 @@ if(ENABLE_ONEDNN_FOR_GPU)"-DDNNL_LIBRARY_TYPE=STATIC""-DDNNL_EXPERIMENTAL_PROFILING=ON""-DONEDNN_BUILD_GRAPH=OFF"+ "-DDNNL_EXPERIMENTAL_GROUPED_MEMORY=ON"# specifically for Conan, because it overrides CMAKE_PREFIX_PATH and oneDNN's FindOpenCL.cmake is ignored# Conan's FindOpenCL.cmake module does not set OpenCL_INCLUDE_DIRS, so we need to set it manually"-DOpenCL_INCLUDE_DIRS=$<TARGET_PROPERTY:OpenCL::OpenCL,INTERFACE_INCLUDE_DIRECTORIES>"