Skip to content

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

[GPU] Align GatherMatmul behavior with moe_gemm (#35780)

Egor Duplenskiif81f69219ffb
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul.cpp
index 5cb21b38334..63160d75837 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul.cpp
@@ -7,6 +7,7 @@
#include "gathermatmul_sort_gen.hpp"
#include "gathermatmul_gather_gen.hpp"
#include "gathermatmul_batched_gemm_gen.hpp"
+#include "gathermatmul_scatter_gen.hpp"
// clang-format on
#include "../primitive_ocl_base.hpp"
@@ -18,6 +19,17 @@
#include "gather_matmul_inst.h"
#include "ocl_v2/utils/fused_ops_jitter.hpp"
+#ifdef ENABLE_ONEDNN_FOR_GPU
+# include <algorithm>
+# include <cstdlib>
+# include <memory>
+# include <oneapi/dnnl/dnnl.hpp>
+# include <unordered_map>
+
+# include "intel_gpu/primitives/swiglu.hpp"
+# include "intel_gpu/runtime/lru_cache.hpp"
+#endif
+
namespace ov::intel_gpu::ocl {
namespace {
#ifdef ENABLE_ONEDNN_FOR_GPU
@@ -29,15 +41,50 @@ inline bool is_prefill_stage(const RuntimeParams& params) {
return n_tokens.get_length() > 1;
}
-// Threshold: use batched path only when n_tokens exceeds this value
static constexpr int32_t BATCHED_PREFILL_THRESHOLD = 16;
inline bool use_batched_prefill(const GatherMatmulRuntimeParams* rtp) {
return rtp->n_tokens > BATCHED_PREFILL_THRESHOLD;
}
+
+inline bool has_fused_swiglu(const kernel_impl_params& params) {
+ for (const auto& fd : params.fused_desc) {
+ if (fd.is_type<swiglu>())
+ return true;
+ }
+ return false;
+}
+
+// Local to avoid an ocl_v2 → onednn link dependency.
+inline dnnl::memory::data_type convert_data_type(cldnn::data_types dt) {
+ switch (dt) {
+ case cldnn::data_types::f32:
+ return dnnl::memory::data_type::f32;
+ case cldnn::data_types::f16:
+ return dnnl::memory::data_type::f16;
+ case cldnn::data_types::i8:
+ return dnnl::memory::data_type::s8;
+ case cldnn::data_types::u8:
+ return dnnl::memory::data_type::u8;
+ case cldnn::data_types::i32:
+ return dnnl::memory::data_type::s32;
+ case cldnn::data_types::i4:
+ return dnnl::memory::data_type::s4;
+ case cldnn::data_types::u4:
+ return dnnl::memory::data_type::u4;
+ default:
+ throw std::invalid_argument("[GPU] gather_matmul: unsupported cldnn->onednn type conversion");
+ }
+}
+
+// OCL micro + batched_gemm kernels are u4/i4-only; everything else must take the onednn-grouped path.
+inline bool weights_need_onednn_grouped(const kernel_impl_params& params) {
+ const auto& weights_layout = params.input_layouts[gather_matmul::BGMInputIdx::WEIGHT];
+ const auto dt = weights_layout.data_type;
+ return !(dt == cldnn::data_types::u4 || dt == cldnn::data_types::i4);
+}
#endif
-// Internal buffer indices for the batched prefill pipeline
enum GatherMatmulInternalBufferIdx {
GATHERED_A = 0, // f16, n_tokens * top_k * K
GROUP_EXPERT_IDS = 1, // i32, n_all_experts * top_k
@@ -46,6 +93,10 @@ enum GatherMatmulInternalBufferIdx {
GROUP_SIZES = 4, // i32, n_all_experts * top_k
TOKEN_MAP = 5, // i32, n_tokens * top_k
NUM_GROUPS = 6, // i32, 1
+ // Cumulative per-expert end-offsets consumed by dnnl::memory::desc::grouped().
+ EXPERT_OFFSETS = 7, // i32, n_all_experts
+ // Conditionally allocated: dominates internal memory at typical MoE shapes.
+ PACKED_OUT = 8, // f16, n_tokens * top_k * N
};
class GatherMatmulOCLImpl : public PrimitiveImplOCL {
@@ -54,30 +105,52 @@ public:
#ifdef ENABLE_ONEDNN_FOR_GPU
static constexpr bool prefill = true;
- // Existing per-token stages
+ // Per-token stages
Stage::Ptr regular_micro_single_token = make_stage<GatherMatmulMicroGenerator>(!prefill);
Stage::Ptr regular_micro_multi_tokens = make_stage<GatherMatmulMicroGenerator>(prefill);
- // Batched prefill stages
+ // Batched OCL prefill stages
Stage::Ptr batched_sort = make_stage<GatherMatmulSortGenerator>();
Stage::Ptr batched_gather = make_stage<GatherMatmulGatherGenerator>();
Stage::Ptr batched_gemm = make_stage<GatherMatmulBatchedGemmGenerator>();
+
+ // Onednn-grouped prefill stages (sort packs expert-major; scatter unpacks).
+ Stage::Ptr onednn_sort = make_stage<GatherMatmulOnednnSortGenerator>();
+ Stage::Ptr onednn_scatter = make_stage<GatherMatmulScatterGenerator>();
#endif
- explicit GatherMatmulOCLImpl() : PrimitiveImplOCL(GatherMatmulImpl::get_type_info_static()) {}
+ explicit GatherMatmulOCLImpl() : PrimitiveImplOCL(GatherMatmulImpl::get_type_info_static()) {
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ // GATHER_MATMUL_USE_ONEDNN_PREFILL gates the dnnl-grouped large-prefill path (default off).
+ _use_onednn_grouped = std::getenv("GATHER_MATMUL_USE_ONEDNN_PREFILL") != nullptr;
+#endif
+ }
explicit GatherMatmulOCLImpl(const RuntimeParams& impl_param) : GatherMatmulOCLImpl() {
auto params = impl_param;
GPU_DEBUG_TRACE_DETAIL << "GatherMatmul create stages for dynamic = " << params.is_dynamic() << "\n";
#ifdef ENABLE_ONEDNN_FOR_GPU
- // Per-token stages (generate + small prefill fallback)
+ // Non-u4/i4 weights have no functional OCL path; force onednn-grouped.
+ const bool need_onednn_for_weights = weights_need_onednn_grouped(params);
+ if (need_onednn_for_weights) {
+ _use_onednn_grouped = true;
+ }
+
+ GPU_DEBUG_TRACE_DETAIL << "GatherMatmul :: use_onednn_grouped=" << _use_onednn_grouped << " need_onednn_for_weights=" << need_onednn_for_weights
+ << std::endl;
+
add_stage(regular_micro_multi_tokens, params);
add_stage(regular_micro_single_token, params);
- // Batched prefill stages
+ // Always registered: serve as fallback when onednn declines (e.g. fused swiglu).
add_stage(batched_sort, params);
add_stage(batched_gather, params);
add_stage(batched_gemm, params);
+
+ if (_use_onednn_grouped) {
+ add_stage(onednn_sort, params);
+ add_stage(onednn_scatter, params);
+ }
#endif
}
@@ -113,6 +186,17 @@ public:
descs.emplace_back(std::max(n_tokens * top_k, max_groups), ov::element::i32);
// 6: num_groups — i32, 1
descs.emplace_back(static_cast<size_t>(1), ov::element::i32);
+ // 7: expert_offsets — cumulative exclusive ends per expert.
+ descs.emplace_back(n_all_experts, ov::element::i32);
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ // OR: env-var doesn't survive clone(), but execute() dispatches on dtype directly.
+ if (_use_onednn_grouped || weights_need_onednn_grouped(params)) {
+ // 8: packed dnnl::matmul output [total_tokens, N], unfused N.
+ size_t n_val = weight_shape[1];
+ descs.emplace_back(n_tokens * top_k * n_val, ov::element::f16);
+ }
+#endif
return descs;
}
@@ -143,20 +227,27 @@ public:
const auto& params = *instance.get_impl_params();
bool is_prefill = is_prefill_stage(params);
update_rt_params(instance);
+ auto* rtp = static_cast<GatherMatmulRuntimeParams*>(m_rt_params.get());
+
+ // Non-u4/i4 weights: dnnl is the only correctness-preserving path; route everything here.
+ if (weights_need_onednn_grouped(params) && !has_fused_swiglu(params) && has_stage(onednn_sort) && has_stage(onednn_scatter) &&
+ has_stage(batched_gather)) {
+ GPU_DEBUG_TRACE_DETAIL << "GatherMatmul Execute onednn-grouped (non-u4/i4 weights, n_tokens=" << rtp->n_tokens << ")" << std::endl;
+ return execute_onednn_grouped(events, instance);
+ }
if (is_prefill) {
- auto* rtp = static_cast<GatherMatmulRuntimeParams*>(m_rt_params.get());
+ // Onednn-grouped large-prefill for u4/i4 — fused-swiglu still falls back to OCL batched_gemm.
+ if (_use_onednn_grouped && rtp->n_tokens > BATCHED_PREFILL_THRESHOLD && !has_fused_swiglu(params) && has_stage(onednn_sort) &&
+ has_stage(onednn_scatter) && has_stage(batched_gather)) {
+ GPU_DEBUG_TRACE_DETAIL << "GatherMatmul Execute onednn-grouped prefill (n_tokens=" << rtp->n_tokens << ")" << std::endl;
+ return execute_onednn_grouped(events, instance);
+ }
if (use_batched_prefill(rtp) && has_stage(batched_sort) && has_stage(batched_gather) && has_stage(batched_gemm)) {
GPU_DEBUG_TRACE_DETAIL << "GatherMatmul Execute batched prefill pipeline (n_tokens=" << rtp->n_tokens << ")" << std::endl;
-
- // Stage 1: Sort tokens by expert within each slot
auto sort_event = execute_stage(events, instance, batched_sort);
-
- // Stage 2: Gather activations into contiguous buffer
auto gather_event = execute_stage({sort_event}, instance, batched_gather);
-
- // Stage 3: Batched GEMM with scattered output
return execute_stage({gather_event}, instance, batched_gemm);
} else if (has_stage(regular_micro_multi_tokens)) {
GPU_DEBUG_TRACE_DETAIL << "GatherMatmul Execute prefill micro_multi_tokens stage (n_tokens=" << rtp->n_tokens << ")" << std::endl;
@@ -172,6 +263,201 @@ public:
#endif
return nullptr;
}
+
+private:
+#ifdef ENABLE_ONEDNN_FOR_GPU
+ // One entry per total_tokens; carries the wrappers we need at execute() time.
+ struct OnednnGroupedKernel {
+ dnnl::matmul::primitive_desc pd;
+ dnnl::matmul prim;
+ dnnl::memory::desc scale_md; // valid iff is_quantized
+ dnnl::memory::desc zp_md; // valid iff is_quantized && has_zp
+ dnnl::memory::desc bias_md; // valid iff has_bias
+ bool is_quantized = false;
+ bool has_zp = false;
+ bool has_bias = false;
+ int32_t weight_group_size = -1; // -1 ⇒ per-OC
+ };
+
+ bool _use_onednn_grouped = false;
+ cldnn::LruCache<int, std::shared_ptr<OnednnGroupedKernel>> _grouped_kernels{32};
+
+ OnednnGroupedKernel& get_grouped_kernel(int total_tokens, primitive_inst& instance) {
+ if (_grouped_kernels.has(total_tokens)) {
+ return *_grouped_kernels.get(total_tokens);
+ }
+
+ const auto& impl_params = *instance.get_impl_params();
+ auto desc = impl_params.typed_desc<gather_matmul>();
+ auto& engine = instance.get_network().get_engine();
+ auto& dnnl_engine = engine.get_onednn_engine();
+
+ const auto& input_layout = impl_params.input_layouts[gather_matmul::BGMInputIdx::INPUT];
+ const auto& weights_layout = impl_params.input_layouts[gather_matmul::BGMInputIdx::WEIGHT];
+ const auto& output_layout = impl_params.output_layouts[0];
+ const auto& wshape = weights_layout.get_shape();
+
+ auto a_dt = convert_data_type(input_layout.data_type);
+ auto out_dt = convert_data_type(output_layout.data_type);
+ auto w_dt = convert_data_type(weights_layout.data_type);
+
+ const dnnl::memory::dim num_experts = static_cast<dnnl::memory::dim>(wshape[0]);
+ const dnnl::memory::dim N = static_cast<dnnl::memory::dim>(wshape[1]);
+ const dnnl::memory::dim K = wshape.size() == 4 ? static_cast<dnnl::memory::dim>(wshape[2] * wshape[3]) : static_cast<dnnl::memory::dim>(wshape[2]);
+
+ static const std::vector<cldnn::data_types> quantized_types = {cldnn::data_types::u4,
+ cldnn::data_types::i4,
+ cldnn::data_types::u8,
+ cldnn::data_types::i8};
+ bool is_quantized = std::any_of(quantized_types.begin(), quantized_types.end(), [&](cldnn::data_types t) {
+ return t == weights_layout.data_type;
+ });
+
+ int32_t weight_group_size = -1;
+ if (is_quantized) {
+ const auto& scale_layout = impl_params.input_layouts[gather_matmul::BGMInputIdx::WEIGHT_SCALE];
+ const auto& sshape = scale_layout.get_shape();
+ // Scales: [E, N, G] (rank-3) or [E, N] (rank-2).
+ size_t num_groups = (sshape.size() >= 3) ? sshape[2] : 1;
+ OPENVINO_ASSERT(num_groups > 0 && (static_cast<size_t>(K) % num_groups) == 0,
+ "[GPU] gather_matmul: scale num_groups=",
+ num_groups,
+ " does not divide K=",
+ K);
+ weight_group_size = (num_groups == 1) ? -1 : static_cast<int32_t>(K / num_groups);
+ constexpr int32_t dnnl_decompression_group_alignment = 32;
+ OPENVINO_ASSERT(weight_group_size <= 0 || (weight_group_size % dnnl_decompression_group_alignment) == 0,
+ "[GPU] gather_matmul: weight_group_size must be a multiple of ",
+ dnnl_decompression_group_alignment,
+ ", got ",
+ weight_group_size);
+ }
+
+ dnnl::primitive_attr attr;
+ attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
+
+ if (is_quantized) {
+ const bool has_groups = (weight_group_size > 0);
+ if (has_groups) {
+ // per-expert(0) × per-K-group(1) × per-N-channel(2)
+ attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {weight_group_size, 1}, dnnl::memory::data_type::f16);
+ if (desc->has_zp) {
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {weight_group_size, 1}, w_dt);
+ }
+ } else {
+ // per-expert(0) × per-N-channel(2), no K-grouping
+ attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, dnnl::memory::data_type::f16);
+ if (desc->has_zp) {
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, w_dt);
+ }
+ }
+ }
+
+ // Grouped src/dst: rows grouped by expert along axis-0 (s32 end-offsets).
+ auto src_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, K}, a_dt, 0, num_experts, dnnl::memory::data_type::s32);
+ auto dst_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, N}, out_dt, 0, num_experts, dnnl::memory::data_type::s32);
+ // Logical [E, K, N], physical layout acb ⇒ stored as [E, N, K].
+ auto w_md = dnnl::memory::desc(dnnl::memory::dims{num_experts, K, N}, w_dt, dnnl::memory::format_tag::acb);
+
+ auto gk = std::make_shared<OnednnGroupedKernel>();
+ gk->is_quantized = is_quantized;
+ gk->has_zp = is_quantized && desc->has_zp;
+ gk->has_bias = desc->has_bias;
+ gk->weight_group_size = weight_group_size;
+
+ if (desc->has_bias) {
+ const auto& bias_layout = impl_params.input_layouts[gather_matmul::BGMInputIdx::BIAS];
+ auto b_dt = convert_data_type(bias_layout.data_type);
+ // Logical [E, 1, N] flattens to dnnl {E, N}.
+ gk->bias_md = dnnl::memory::desc(dnnl::memory::dims{num_experts, N}, b_dt, dnnl::memory::format_tag::ab);
+ gk->pd = dnnl::matmul::primitive_desc(dnnl_engine, src_md, w_md, gk->bias_md, dst_md, attr);
+ } else {
+ gk->pd = dnnl::matmul::primitive_desc(dnnl_engine, src_md, w_md, dst_md, attr);
+ }
+
+ if (is_quantized) {
+ const auto& scale_layout = impl_params.input_layouts[gather_matmul::BGMInputIdx::WEIGHT_SCALE];
+ auto s_dt = convert_data_type(scale_layout.data_type);
+ const bool has_groups = (weight_group_size > 0);
+ if (has_groups) {
+ const dnnl::memory::dim num_k_groups = K / weight_group_size;
+ gk->scale_md = dnnl::memory::desc({num_experts, num_k_groups, N}, s_dt, dnnl::memory::format_tag::abc);
+ if (gk->has_zp) {
+ gk->zp_md = dnnl::memory::desc({num_experts, num_k_groups, N}, w_dt, dnnl::memory::format_tag::abc);
+ }
+ } else {
+ gk->scale_md = dnnl::memory::desc({num_experts, N}, s_dt, dnnl::memory::format_tag::ab);
+ if (gk->has_zp) {
+ gk->zp_md = dnnl::memory::desc({num_experts, N}, w_dt, dnnl::memory::format_tag::ab);
+ }
+ }
+ }
+
+ gk->prim = dnnl::matmul(gk->pd);
+
+ _grouped_kernels.add(total_tokens, gk);
+ return *_grouped_kernels.get(total_tokens);
+ }
+
+ // Pipeline: onednn_sort → batched_gather → dnnl::matmul → onednn_scatter (in-order queue serializes).
+ event::ptr execute_onednn_grouped(const std::vector<event::ptr>& events, primitive_inst& instance) {
+ auto* rtp = static_cast<GatherMatmulRuntimeParams*>(m_rt_params.get());
+ const int total_tokens = rtp->n_tokens * rtp->top_k;
+
+ auto sort_event = execute_stage(events, instance, onednn_sort);
+ auto gather_event = execute_stage({sort_event}, instance, batched_gather);
+
+ auto& net = instance.get_network();
+ auto& stream = net.get_stream();
+ auto& dnn_stream = stream.get_onednn_stream();
+
+ auto& gk = get_grouped_kernel(total_tokens, instance);
+ const auto& impl_params = *instance.get_impl_params();
+ auto desc = impl_params.typed_desc<gather_matmul>();
+
+ const auto& intermediates = instance.get_intermediates_memories();
+ OPENVINO_ASSERT(intermediates.size() > PACKED_OUT,
+ "[GPU] gather_matmul: onednn-grouped path requires internal buffer ",
+ PACKED_OUT,
+ " but only ",
+ intermediates.size(),
+ " buffers are allocated");
+
+ auto& gathered_a_mem = *intermediates[GATHERED_A];
+ auto& packed_out_mem = *intermediates[PACKED_OUT];
+ auto& expert_offsets_mem = *intermediates[EXPERT_OFFSETS];
+
+ auto src_dnn = gathered_a_mem.get_onednn_grouped_memory(gk.pd.src_desc(), expert_offsets_mem);
+ auto dst_dnn = packed_out_mem.get_onednn_grouped_memory(gk.pd.dst_desc(), expert_offsets_mem);
+ auto& weights_mem = *instance.input_memory_ptr(gather_matmul::BGMInputIdx::WEIGHT);
+ auto w_dnn = weights_mem.get_onednn_memory(gk.pd.weights_desc());
+
+ std::unordered_map<int, dnnl::memory> args{
+ {DNNL_ARG_SRC, src_dnn},
+ {DNNL_ARG_WEIGHTS, w_dnn},
+ {DNNL_ARG_DST, dst_dnn},
+ };
+
+ if (gk.is_quantized) {
+ auto& scale_mem = *instance.input_memory_ptr(gather_matmul::BGMInputIdx::WEIGHT_SCALE);
+ args.insert({DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale_mem.get_onednn_memory(gk.scale_md)});
+ if (gk.has_zp) {
+ auto& zp_mem = *instance.input_memory_ptr(gather_matmul::BGMInputIdx::WEIGHT_ZP);
+ args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, zp_mem.get_onednn_memory(gk.zp_md)});
+ }
+ }
+
+ if (gk.has_bias) {
+ auto& bias_mem = *instance.input_memory_ptr(gather_matmul::BGMInputIdx::BIAS);
+ // Use the saved bias_md: pd.weights_desc() no-arg form shadows the base bias variant.
+ args.insert({DNNL_ARG_BIAS, bias_mem.get_onednn_memory(gk.bias_md)});
+ }
+
+ gk.prim.execute(dnn_stream, args);
+
+ return execute_stage({gather_event}, instance, onednn_scatter);
+ }
+#endif
};
} // namespace
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_impl.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_impl.hpp
index d90341ddb2f..fbe5548ece9 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_impl.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_impl.hpp
@@ -29,8 +29,6 @@ struct GatherMatmulImpl : public ImplementationManager {
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 = {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.cpp
new file mode 100644
index 00000000000..fb68548753e
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.cpp
@@ -0,0 +1,68 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "gathermatmul_scatter_gen.hpp"
+
+#include "gather_matmul_gen_micro.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+#include "intel_gpu/primitives/gather_matmul.hpp"
+#include "ocl_v2/utils/jitter.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+namespace ov::intel_gpu::ocl {
+
+JitConstants GatherMatmulScatterGenerator::get_jit_constants(const kernel_impl_params& params) const {
+ auto jit = make_base_jit_constants(params);
+
+ const auto& in_offsets_map = params.in_port_to_shape_info_offset;
+ LayoutJitter input_jitter(params.input_layouts[gather_matmul::BGMInputIdx::INPUT], in_offsets_map.at(gather_matmul::BGMInputIdx::INPUT));
+
+ jit.make("N_TOKENS", input_jitter.dim(ChannelName::FEATURE));
+
+ return jit;
+}
+
+Arguments GatherMatmulScatterGenerator::get_arguments_desc(const kernel_impl_params& params) const {
+ Arguments args;
+ if (params.is_dynamic())
+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
+
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 8}); // PACKED_OUT
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 5}); // token_map
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 2}); // group_slot_ids
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 3}); // group_offsets
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 4}); // group_sizes
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 6}); // num_groups
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // n
+
+ return args;
+}
+
+DispatchDataFunc GatherMatmulScatterGenerator::get_dispatch_data_func() const {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ auto* rtp = static_cast<GatherMatmulRuntimeParams*>(rt_params);
+ auto& wgs = kd.params.workGroups;
+ auto& scalars = kd.params.scalars;
+ scalars.clear();
+
+ const auto& weight_shape = params.get_input_layout(gather_matmul::BGMInputIdx::WEIGHT).get_shape();
+ // Unfused N: onednn path declines swiglu-fused nodes (handled by OCL batched_gemm).
+ size_t n_val = weight_shape[1];
+ size_t n_tokens = static_cast<size_t>(rtp->n_tokens);
+ size_t top_k = static_cast<size_t>(rtp->top_k);
+ size_t n_all_experts = weight_shape[0];
+ size_t max_groups = n_all_experts * top_k;
+
+ constexpr size_t COPY_BLOCK = 8;
+ wgs.global = {ceil_div(n_val, COPY_BLOCK), n_tokens, max_groups};
+ wgs.local = {1, 1, 1};
+
+ ScalarDescriptor s_n{ScalarDescriptor::Types::INT32};
+ s_n.v.s32 = static_cast<int32_t>(n_val);
+ scalars.push_back(s_n);
+ }};
+}
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.hpp
new file mode 100644
index 00000000000..8a09dac16c6
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_scatter_gen.hpp
@@ -0,0 +1,22 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "../utils/kernel_generator.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+
+namespace ov::intel_gpu::ocl {
+
+// Onednn-grouped path scatter: PACKED_OUT [total_tokens, N] → per-slot output.
+class GatherMatmulScatterGenerator : public KernelGenerator {
+public:
+ explicit GatherMatmulScatterGenerator() : KernelGenerator("gathermatmul_scatter", "_scatter") {}
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override;
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override;
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
+};
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.cpp
index 6bc42e53e10..bb567a3f6f5 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.cpp
@@ -16,11 +16,10 @@ JitConstants GatherMatmulSortGenerator::get_jit_constants(const kernel_impl_para
const auto& in_offsets_map = params.in_port_to_shape_info_offset;
- // indices layout for INPUT0 in the sort kernel
+ // Sort kernel reads only indices; INPUT0 is the indices layout here.
jit.add(
make_layout_jit_constants("INPUT0", params.input_layouts[gather_matmul::BGMInputIdx::INDICES], in_offsets_map.at(gather_matmul::BGMInputIdx::INDICES)));
- // Activations rank3, indices rank2, weights rank3 (BATCH=n_all_experts).
LayoutJitter input_jitter(params.input_layouts[gather_matmul::BGMInputIdx::INPUT], in_offsets_map.at(gather_matmul::BGMInputIdx::INPUT));
LayoutJitter indices_jitter(params.input_layouts[gather_matmul::BGMInputIdx::INDICES], in_offsets_map.at(gather_matmul::BGMInputIdx::INDICES));
LayoutJitter weight_jitter(params.input_layouts[gather_matmul::BGMInputIdx::WEIGHT], in_offsets_map.at(gather_matmul::BGMInputIdx::WEIGHT));
@@ -37,9 +36,7 @@ Arguments GatherMatmulSortGenerator::get_arguments_desc(const kernel_impl_params
if (params.is_dynamic())
args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});
- // indices input
args.push_back({ArgumentDescriptor::Types::INPUT, gather_matmul::BGMInputIdx::INDICES});
- // Internal buffers: group_expert_ids, group_slot_ids, group_offsets, group_sizes, token_map, num_groups
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1}); // group_expert_ids
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 2}); // group_slot_ids
args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 3}); // group_offsets
@@ -53,10 +50,25 @@ Arguments GatherMatmulSortGenerator::get_arguments_desc(const kernel_impl_params
DispatchDataFunc GatherMatmulSortGenerator::get_dispatch_data_func() const {
return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
auto& wgs = kd.params.workGroups;
- // Single workgroup — all work done sequentially
+ // Single-WG sequential.
wgs.global = {1, 1, 1};
wgs.local = {1, 1, 1};
}};
}
+// --- onednn variant: expert-major order + per-expert cumulative end-offsets ---
+
+JitConstants GatherMatmulOnednnSortGenerator::get_jit_constants(const kernel_impl_params& params) const {
+ auto jit = GatherMatmulSortGenerator::get_jit_constants(params);
+ jit.make("EXPERT_MAJOR_ORDER", 1);
+ jit.make("EMIT_EXPERT_OFFSETS", 1);
+ return jit;
+}
+
+Arguments GatherMatmulOnednnSortGenerator::get_arguments_desc(const kernel_impl_params& params) const {
+ auto args = GatherMatmulSortGenerator::get_arguments_desc(params);
+ args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 7}); // expert_offsets
+ return args;
+}
+
} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.hpp
index ffddcc32b47..bed205e4c76 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_sort_gen.hpp
@@ -18,4 +18,13 @@ public:
[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override;
};
+// Expert-major order + per-expert cumulative end-offsets for dnnl::memory::desc::grouped().
+class GatherMatmulOnednnSortGenerator : public GatherMatmulSortGenerator {
+public:
+ GatherMatmulOnednnSortGenerator() = default;
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override;
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override;
+};
+
} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_scatter.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_scatter.cl
new file mode 100644
index 00000000000..d5c6122f282
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_scatter.cl
@@ -0,0 +1,62 @@
+/*******************************************************************************
+ * Copyright 2026 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.
+ ******************************************************************************/
+
+// Inverse of bgm_gather: out[slot, orig_token, :] = packed[group_offsets[g] + tok, :].
+// No reduction here — Multiply-by-router-weights + ReduceSum stay as separate downstream ops.
+
+#define COPY_BLOCK 8
+
+KERNEL(bgm_scatter)(
+ OPTIONAL_SHAPE_INFO_ARG
+ const global half* packed_ptr,
+ global half* output_ptr,
+ const global int* token_map,
+ const global int* group_slot_ids,
+ const global int* group_offsets,
+ const global int* group_sizes,
+ const global int* num_groups,
+ int n_val
+) {
+ int group_id = get_global_id(2);
+ if (group_id >= num_groups[0])
+ return;
+
+ int n_tokens_in_group = group_sizes[group_id];
+ int token_in_group = get_global_id(1);
+ if (token_in_group >= n_tokens_in_group)
+ return;
+
+ int offset = group_offsets[group_id];
+ int slot = group_slot_ids[group_id];
+ int n_tokens = N_TOKENS;
+
+ int orig_token = token_map[offset + token_in_group];
+
+ const global half* src = packed_ptr + (offset + token_in_group) * n_val;
+ // Output leading dim is top_k (always per-slot), unlike bgm_gather's INPUT clamping.
+ global half* dst = output_ptr + (slot * n_tokens + orig_token) * n_val;
+
+ int n_offset = get_global_id(0) * COPY_BLOCK;
+ if (n_offset + COPY_BLOCK <= n_val) {
+ half8 val = vload8(0, src + n_offset);
+ vstore8(val, 0, dst + n_offset);
+ } else {
+ // Tail
+ for (int i = n_offset; i < n_val && i < n_offset + COPY_BLOCK; i++) {
+ dst[i] = src[i];
+ }
+ }
+}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_sort.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_sort.cl
index 38f52a0e5e9..2e207d06308 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_sort.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gathermatmul_sort.cl
@@ -15,6 +15,10 @@
*/
// Counting sort: groups tokens by expert within each slot. Single-WG, sequential.
+//
+// JIT flags (default 0 for legacy OCL batched-prefill path):
+// EXPERT_MAJOR_ORDER — pack each expert's rows contiguously; required by dnnl grouped src/dst.
+// EMIT_EXPERT_OFFSETS — append expert_offsets[N_ALL_EXPERTS]: cumulative exclusive end per expert.
KERNEL(bgm_sort)(
OPTIONAL_SHAPE_INFO_ARG
@@ -25,6 +29,9 @@ KERNEL(bgm_sort)(
global int* group_sizes,
global int* token_map,
global int* num_groups
+#if EMIT_EXPERT_OFFSETS
+ , global int* expert_offsets
+#endif
) {
int n_tokens = N_TOKENS;
int top_k = TOP_K;
@@ -32,8 +39,7 @@ KERNEL(bgm_sort)(
int max_groups = n_all_experts * top_k;
- // Phase 1 (group_sizes scratch): histogram + compact pass — superseded below; kept
- // for behavioural parity. TODO: drop and run only the clean Pass 1-3.
+ // Phase 1 scratch pass — superseded by Pass 1-3 below; kept for behavioural parity. TODO: drop.
for (int i = 0; i < max_groups; i++) {
group_sizes[i] = 0;
}
@@ -84,6 +90,26 @@ KERNEL(bgm_sort)(
for (int i = 0; i < max_groups; i++) {
group_sizes[i] = -1;
}
+#if EXPERT_MAJOR_ORDER
+ for (int e = 0; e < n_all_experts; e++) {
+ for (int s = 0; s < top_k; s++) {
+ int bin = s * n_all_experts + e;
+ int count = token_map[bin];
+ if (count > 0) {
+ group_expert_ids[g] = e;
+ group_slot_ids[g] = s;
+ group_offsets[g] = offset;
+ group_sizes[bin] = g;
+ offset += count;
+ g++;
+ }
+ }
+ #if EMIT_EXPERT_OFFSETS
+ expert_offsets[e] = offset;
+ #endif
+ }
+#else
+ // Slot-major (legacy OCL batched_gemm dispatch).
for (int s = 0; s < top_k; s++) {
for (int e = 0; e < n_all_experts; e++) {
int bin = s * n_all_experts + e;
@@ -98,6 +124,7 @@ KERNEL(bgm_sort)(
}
}
}
+#endif
total_groups = g;
num_groups[0] = total_groups;
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
index 1a2fdfd10b0..fc8b06fa654 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp
@@ -20,6 +20,7 @@
# include "../primitive_ocl_base.hpp"
# include "../utils/kernel_generator.hpp"
# include "common_utils/jitter.hpp"
+# include "impls/onednn/grouped_matmul_helper.hpp"
# include "intel_gpu/graph/kernel_impl_params.hpp"
# include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"
# include "intel_gpu/runtime/lru_cache.hpp"
@@ -35,6 +36,12 @@ namespace {
using namespace ov::intel_gpu::ocl;
+// Bring shared onednn matmul wrappers into this anonymous namespace so existing call sites
+// that reference `onednn_matmul`, `onednn_linear`, etc. unqualified continue to compile after
+// the definitions moved to impls/onednn/grouped_matmul_helper.hpp.
+using cldnn::onednn::onednn_linear;
+using cldnn::onednn::onednn_matmul;
+
dnnl::memory::data_type convert_data_type(cldnn::data_types dt) {
switch (dt) {
case cldnn::data_types::f32:
@@ -68,308 +75,6 @@ inline dnnl::algorithm moe_activation_to_dnnl_algo(ov::op::internal::MOE::Activa
}
}
-struct onednn_matmul {
- dnnl::matmul m_prim;
- dnnl::memory::desc m_wei_md;
- dnnl::memory::data_type m_w_type;
- dnnl::memory::data_type m_a_type; // activation dtype
- dnnl::memory::dim m_K;
- dnnl::memory::dim m_N;
- dnnl::memory::dim m_M;
- dnnl::memory::dim m_K_groups;
-
- dnnl::primitive_attr attr;
- dnnl::post_ops postops;
-
- onednn_matmul(dnnl::memory::data_type act_dtype,
- dnnl::memory::data_type weight_dtype,
- int batch_size,
- int ic,
- int oc,
- int ic_group_size = -1,
- bool has_zp = true) {
- m_a_type = act_dtype;
- m_w_type = weight_dtype;
- m_K_groups = 0;
- m_K = ic;
- m_N = oc;
- m_M = DNNL_RUNTIME_DIM_VAL;
- if (batch_size > 0) {
- // jit-gemm kernel only support static batch size
- m_M = batch_size;
- }
- if (ic_group_size >= 0) {
- w_scale(ic_group_size);
- if (has_zp)
- w_zp(ic_group_size);
- fpmath_f16();
- }
- }
-
- onednn_matmul& w_scale(int k_group_size) {
- if (k_group_size <= 0) {
- m_K_groups = 1;
- // per-OC, no grouping in K dimension
- attr.set_scales(DNNL_ARG_WEIGHTS, (0 << 0) + (1 << 1), {1}, dnnl::memory::data_type::f16);
- } else {
- OPENVINO_ASSERT((k_group_size % 32) == 0);
- OPENVINO_ASSERT((m_K % k_group_size) == 0);
- m_K_groups = m_K / k_group_size;
- attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) + (1 << 1), {k_group_size, 1}, dnnl::memory::data_type::f16);
- }
- return *this;
- }
-
- onednn_matmul& w_zp(int k_group_size) {
- if (k_group_size <= 0) {
- OPENVINO_ASSERT(m_K_groups == 1);
- attr.set_zero_points(DNNL_ARG_WEIGHTS, (0 << 0) + (1 << 1), {1}, m_w_type);
- } else {
- OPENVINO_ASSERT((m_K % k_group_size) == 0);
- m_K_groups = (m_K / k_group_size);
- attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) + (1 << 1), {k_group_size, 1}, m_w_type);
- }
- return *this;
- }
-
- onednn_matmul& fpmath_f16() {
- attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
- return *this;
- }
- onednn_matmul& post_op_gate_activation(dnnl::algorithm algo) {
- float alpha = 1.0f;
- float beta = 0.0f;
- postops.append_eltwise(algo, alpha, beta);
- return *this;
- }
- onednn_matmul& post_op_bin_mul(bool per_oc = true) {
- dnnl::memory::dim batch_size = m_M;
- if (batch_size == DNNL_RUNTIME_DIM_VAL)
- batch_size = 1024 * 1024; // big enough fake static batch
-
- dnnl::memory::desc bin_mul_md = dnnl::memory::desc(dnnl::memory::dims({batch_size, per_oc ? m_N : 1}), m_a_type, dnnl::memory::format_tag::ab);
- postops.append_binary(dnnl::algorithm::binary_mul, bin_mul_md);
- return *this;
- }
-
- onednn_matmul& post_op_sum(float scale = 1.f, int32_t zero_point = 0) {
- postops.append_sum(scale, zero_point, dnnl::memory::data_type::undef);
- return *this;
- }
-
- void create(dnnl::engine eng) {
- if (postops.len() > 0) {
- attr.set_post_ops(postops);
- }
-
- dnnl::memory::desc src_md = dnnl::memory::desc(dnnl::memory::dims({m_M, m_K}), m_a_type, dnnl::memory::format_tag::ab);
- dnnl::memory::desc dst_md = dnnl::memory::desc(dnnl::memory::dims({m_M, m_N}), m_a_type, dnnl::memory::format_tag::ab);
-
- // use fixed weight-layout to prevent shape-dependent weight-layout changes
- dnnl::memory::desc wei_md = dnnl::memory::desc(dnnl::memory::dims({m_K, m_N}), m_w_type, dnnl::memory::format_tag::ba);
-
- // Create primitive descriptor.
- auto matmul_pd = dnnl::matmul::primitive_desc(eng, src_md, wei_md, dst_md, attr);
-
- // Pre-packed weights stored as int8_t
- m_wei_md = matmul_pd.weights_desc();
-
- // Create the primitive.
- m_prim = dnnl::matmul(matmul_pd);
- }
-
- // this creator is for predefined matmul primitive types
- enum class type {
- none,
- with_bin_mul,
- with_bin_mul_per_row,
- with_bin_mul_per_row_sum,
- with_gate_act,
- with_gate_act_bin_mul,
- with_sigmoid,
- with_bin_mul_sum,
- };
- int bin_post_id = -1;
- bool bin_per_row = false;
- onednn_matmul(dnnl::engine eng,
- dnnl::memory::data_type act_dtype,
- dnnl::memory::data_type weight_dtype,
- int batch,
- int ic,
- int oc,
- int ic_group_size,
- type t,
- bool has_zp = true,
- dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish)
- : onednn_matmul(act_dtype, weight_dtype, batch, ic, oc, ic_group_size, has_zp) {
- if (t == type::with_bin_mul) {
- bin_post_id = 0;
- post_op_bin_mul(true);
- }
- if (t == type::with_bin_mul_sum) {
- bin_post_id = 0;
- post_op_bin_mul(false);
- post_op_sum();
- }
- if (t == type::with_sigmoid) {
- postops.append_eltwise(dnnl::algorithm::eltwise_logistic, 1.0f, 0.0f);
- }
- if (t == type::with_bin_mul_per_row) {
- bin_post_id = 0;
- bin_per_row = true;
- post_op_bin_mul(false);
- }
- if (t == type::with_bin_mul_per_row_sum) {
- bin_post_id = 0;
- bin_per_row = true;
- post_op_bin_mul(false);
- post_op_sum();
- }
- if (t == type::with_gate_act)
- post_op_gate_activation(activation_algo);
- if (t == type::with_gate_act_bin_mul) {
- bin_post_id = 1;
- post_op_gate_activation(activation_algo);
- post_op_bin_mul(true);
- }
-
- create(eng);
- }
-};
-
-// all jit-based/performance-aware function should be a functor/callable because:
-// - it needs to hold reference to kernel (to save build time & resources)
-// - it needs to do other compile time preparation work and hold the relevant
-// runtime-data-struct (to make runtime faster)
-// to optimize compile-time-workload itself, the functor instance itself should be
-// cached with compile-time parameter as the key.
-//
-// because it's a functor, which supposed to have no states, so cache-factory should
-// always return shared_ptr to constant object, so it won't behave differently when being
-// called by different caller, and this also ensure it's multi-threading safe since it
-// won't modify it's content.
-//
-template <typename... TTypes>
-class tuple_hasher {
-private:
- typedef std::tuple<TTypes...> Tuple;
- template <int N>
- size_t hash(Tuple& value) const {
- return 0;
- }
- template <int N, typename THead, typename... TTail>
- size_t hash(Tuple& value) const {
- constexpr int Index = N - sizeof...(TTail) - 1;
- return std::hash<THead>()(std::get<Index>(value)) ^ hash<N, TTail...>(value);
- }
-
-public:
- size_t operator()(Tuple value) const {
- auto hv = hash<sizeof...(TTypes), TTypes...>(value);
- return hv;
- }
-};
-
-// create const object with internal cache with constructor-args as the key
-// this helps reduces construction time overhead, and perfectly suitable
-// for caching functor/callable.
-template <class T, typename... CArgs>
-std::shared_ptr<const T> make_cacheable(dnnl::engine eng, CArgs... cargs) {
- std::shared_ptr<const T> sptr;
- auto key = std::make_tuple(cargs...);
- static std::unordered_map<decltype(key), std::weak_ptr<const T>, tuple_hasher<CArgs...>> cache;
- static std::mutex mutex;
- std::lock_guard<std::mutex> guard(mutex);
- auto it = cache.find(key);
- if (it != cache.end()) {
- auto& wptr = it->second;
- sptr = wptr.lock();
- if (!sptr) {
- sptr = std::make_shared<T>(eng, cargs...);
- wptr = sptr;
- }
- } else {
- sptr = std::make_shared<T>(eng, cargs...);
- cache.emplace(std::make_pair(key, std::weak_ptr<const T>(sptr)));
- }
- return sptr;
-}
-
-struct onednn_linear {
- std::shared_ptr<const onednn_matmul> mm;
- dnnl::memory weight;
- dnnl::memory scale;
- dnnl::memory zp;
- dnnl::matmul m_prim;
- dnnl::memory::dim m_K;
- dnnl::memory::dim m_N;
- dnnl::memory::dim m_batch;
- dnnl::memory::data_type m_a_type;
- int bin_post_id;
-
- static onednn_linear create(dnnl::engine eng,
- dnnl::memory::data_type act_dtype,
- dnnl::memory::data_type weight_dtype,
- int batch,
- int ic,
- int oc,
- int ic_group_size,
- onednn_matmul::type t,
- dnnl::memory weight, // external weight
- dnnl::memory scale,
- dnnl::memory zp,
- dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish) {
- OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("onednn_linear::create()"));
- bool has_zp = static_cast<bool>(zp);
- auto mm = make_cacheable<onednn_matmul>(eng, act_dtype, weight_dtype, batch, ic, oc, ic_group_size, t, has_zp, activation_algo);
- onednn_linear linear;
- linear.mm = mm;
- linear.bin_post_id = mm->bin_post_id;
- linear.m_prim = mm->m_prim;
- linear.m_K = mm->m_K;
- linear.m_N = mm->m_N;
- linear.m_batch = batch;
- linear.m_a_type = mm->m_a_type;
- linear.weight = weight;
-
- if (scale) {
- // https://uxlfoundation.github.io/oneDNN/page_weights_decompression_matmul_cpp.html
- // Quantization Group size for scales. Must be divisible by 32.
- linear.scale = scale;
- if (zp) {
- linear.zp = zp;
- }
- }
- return linear;
- }
-
- void forward(dnnl::stream& stream, int m, dnnl::memory src_mem, dnnl::memory dst_mem, dnnl::memory bin_mem) {
- OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("onednn_linear::forward()"));
- dnnl::memory::dim M = m;
-
- if (!(m_batch == 0 || m_batch == M)) {
- OPENVINO_THROW("onednn_linear::forward(): invalid batch size m_batch=", m_batch, " M=", M);
- }
-
- std::unordered_map<int, dnnl::memory> args;
- args.insert({DNNL_ARG_SRC, src_mem});
- args.insert({DNNL_ARG_WEIGHTS, weight});
- // args.insert({DNNL_ARG_BIAS, bias_mem});
- args.insert({DNNL_ARG_DST, dst_mem});
-
- if (scale) {
- args.insert({DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale});
- }
- if (zp) {
- args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, zp});
- }
- if (bin_mem) {
- args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(bin_post_id) | DNNL_ARG_SRC_1, bin_mem});
- }
- m_prim.execute(stream, args);
- }
-};
-
class MoE3GemmSwigluSoftMaxTopK : public KernelGenerator {
public:
MoE3GemmSwigluSoftMaxTopK() : KernelGenerator("moe_3gemm_swiglu_fuse", "softmax_topk") {}
diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/grouped_matmul_helper.hpp b/src/plugins/intel_gpu/src/graph/impls/onednn/grouped_matmul_helper.hpp
new file mode 100644
index 00000000000..9e4b6de881d
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/grouped_matmul_helper.hpp
@@ -0,0 +1,316 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+// Inline dnnl::matmul wrappers + a construction-cache, shared by primitives that
+// orchestrate their own sort/gather/gemm/scatter pipelines.
+
+#ifdef ENABLE_ONEDNN_FOR_GPU
+
+# include <memory>
+# include <mutex>
+# include <oneapi/dnnl/dnnl.hpp>
+# include <tuple>
+# include <unordered_map>
+
+# include "intel_gpu/runtime/itt.hpp"
+# include "openvino/core/except.hpp"
+
+namespace cldnn {
+namespace onednn {
+
+struct onednn_matmul {
+ dnnl::matmul m_prim;
+ dnnl::memory::desc m_wei_md;
+ dnnl::memory::data_type m_w_type;
+ dnnl::memory::data_type m_a_type; // activation dtype
+ dnnl::memory::dim m_K;
+ dnnl::memory::dim m_N;
+ dnnl::memory::dim m_M;
+ dnnl::memory::dim m_K_groups;
+
+ dnnl::primitive_attr attr;
+ dnnl::post_ops postops;
+
+ onednn_matmul(dnnl::memory::data_type act_dtype,
+ dnnl::memory::data_type weight_dtype,
+ int batch_size,
+ int ic,
+ int oc,
+ int ic_group_size = -1,
+ bool has_zp = true) {
+ m_a_type = act_dtype;
+ m_w_type = weight_dtype;
+ m_K_groups = 0;
+ m_K = ic;
+ m_N = oc;
+ m_M = DNNL_RUNTIME_DIM_VAL;
+ if (batch_size > 0) {
+ // jit-gemm kernel only support static batch size
+ m_M = batch_size;
+ }
+ if (ic_group_size >= 0) {
+ w_scale(ic_group_size);
+ if (has_zp)
+ w_zp(ic_group_size);
+ fpmath_f16();
+ }
+ }
+
+ onednn_matmul& w_scale(int k_group_size) {
+ if (k_group_size <= 0) {
+ m_K_groups = 1;
+ // per-OC, no grouping in K dimension
+ attr.set_scales(DNNL_ARG_WEIGHTS, (0 << 0) + (1 << 1), {1}, dnnl::memory::data_type::f16);
+ } else {
+ OPENVINO_ASSERT((k_group_size % 32) == 0);
+ OPENVINO_ASSERT((m_K % k_group_size) == 0);
+ m_K_groups = m_K / k_group_size;
+ attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) + (1 << 1), {k_group_size, 1}, dnnl::memory::data_type::f16);
+ }
+ return *this;
+ }
+
+ onednn_matmul& w_zp(int k_group_size) {
+ if (k_group_size <= 0) {
+ OPENVINO_ASSERT(m_K_groups == 1);
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (0 << 0) + (1 << 1), {1}, m_w_type);
+ } else {
+ OPENVINO_ASSERT((m_K % k_group_size) == 0);
+ m_K_groups = (m_K / k_group_size);
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) + (1 << 1), {k_group_size, 1}, m_w_type);
+ }
+ return *this;
+ }
+
+ onednn_matmul& fpmath_f16() {
+ attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
+ return *this;
+ }
+ onednn_matmul& post_op_gate_activation(dnnl::algorithm algo) {
+ float alpha = 1.0f;
+ float beta = 0.0f;
+ postops.append_eltwise(algo, alpha, beta);
+ return *this;
+ }
+ onednn_matmul& post_op_bin_mul(bool per_oc = true) {
+ dnnl::memory::dim batch_size = m_M;
+ if (batch_size == DNNL_RUNTIME_DIM_VAL)
+ batch_size = 1024 * 1024; // big enough fake static batch
+
+ dnnl::memory::desc bin_mul_md = dnnl::memory::desc(dnnl::memory::dims({batch_size, per_oc ? m_N : 1}), m_a_type, dnnl::memory::format_tag::ab);
+ postops.append_binary(dnnl::algorithm::binary_mul, bin_mul_md);
+ return *this;
+ }
+
+ onednn_matmul& post_op_sum(float scale = 1.f, int32_t zero_point = 0) {
+ postops.append_sum(scale, zero_point, dnnl::memory::data_type::undef);
+ return *this;
+ }
+
+ void create(dnnl::engine eng) {
+ if (postops.len() > 0) {
+ attr.set_post_ops(postops);
+ }
+
+ dnnl::memory::desc src_md = dnnl::memory::desc(dnnl::memory::dims({m_M, m_K}), m_a_type, dnnl::memory::format_tag::ab);
+ dnnl::memory::desc dst_md = dnnl::memory::desc(dnnl::memory::dims({m_M, m_N}), m_a_type, dnnl::memory::format_tag::ab);
+
+ // use fixed weight-layout to prevent shape-dependent weight-layout changes
+ dnnl::memory::desc wei_md = dnnl::memory::desc(dnnl::memory::dims({m_K, m_N}), m_w_type, dnnl::memory::format_tag::ba);
+
+ // Create primitive descriptor.
+ auto matmul_pd = dnnl::matmul::primitive_desc(eng, src_md, wei_md, dst_md, attr);
+
+ // Pre-packed weights stored as int8_t
+ m_wei_md = matmul_pd.weights_desc();
+
+ // Create the primitive.
+ m_prim = dnnl::matmul(matmul_pd);
+ }
+
+ // this creator is for predefined matmul primitive types
+ enum class type {
+ none,
+ with_bin_mul,
+ with_bin_mul_per_row,
+ with_bin_mul_per_row_sum,
+ with_gate_act,
+ with_gate_act_bin_mul,
+ with_sigmoid,
+ with_bin_mul_sum,
+ };
+ int bin_post_id = -1;
+ bool bin_per_row = false;
+ onednn_matmul(dnnl::engine eng,
+ dnnl::memory::data_type act_dtype,
+ dnnl::memory::data_type weight_dtype,
+ int batch,
+ int ic,
+ int oc,
+ int ic_group_size,
+ type t,
+ bool has_zp = true,
+ dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish)
+ : onednn_matmul(act_dtype, weight_dtype, batch, ic, oc, ic_group_size, has_zp) {
+ if (t == type::with_bin_mul) {
+ bin_post_id = 0;
+ post_op_bin_mul(true);
+ }
+ if (t == type::with_bin_mul_sum) {
+ bin_post_id = 0;
+ post_op_bin_mul(false);
+ post_op_sum();
+ }
+ if (t == type::with_sigmoid) {
+ postops.append_eltwise(dnnl::algorithm::eltwise_logistic, 1.0f, 0.0f);
+ }
+ if (t == type::with_bin_mul_per_row) {
+ bin_post_id = 0;
+ bin_per_row = true;
+ post_op_bin_mul(false);
+ }
+ if (t == type::with_bin_mul_per_row_sum) {
+ bin_post_id = 0;
+ bin_per_row = true;
+ post_op_bin_mul(false);
+ post_op_sum();
+ }
+ if (t == type::with_gate_act)
+ post_op_gate_activation(activation_algo);
+ if (t == type::with_gate_act_bin_mul) {
+ bin_post_id = 1;
+ post_op_gate_activation(activation_algo);
+ post_op_bin_mul(true);
+ }
+
+ create(eng);
+ }
+};
+
+// Stateless functor wrapping a built dnnl primitive; cache returns shared_ptr<const T> for thread safety.
+template <typename... TTypes>
+class tuple_hasher {
+private:
+ typedef std::tuple<TTypes...> Tuple;
+ template <int N>
+ size_t hash(Tuple& value) const {
+ return 0;
+ }
+ template <int N, typename THead, typename... TTail>
+ size_t hash(Tuple& value) const {
+ constexpr int Index = N - sizeof...(TTail) - 1;
+ return std::hash<THead>()(std::get<Index>(value)) ^ hash<N, TTail...>(value);
+ }
+
+public:
+ size_t operator()(Tuple value) const {
+ auto hv = hash<sizeof...(TTypes), TTypes...>(value);
+ return hv;
+ }
+};
+
+// Process-wide cache keyed by constructor args; same-shape callers across TUs reuse one instance.
+template <class T, typename... CArgs>
+std::shared_ptr<const T> make_cacheable(dnnl::engine eng, CArgs... cargs) {
+ std::shared_ptr<const T> sptr;
+ auto key = std::make_tuple(cargs...);
+ static std::unordered_map<decltype(key), std::weak_ptr<const T>, tuple_hasher<CArgs...>> cache;
+ static std::mutex mutex;
+ std::lock_guard<std::mutex> guard(mutex);
+ auto it = cache.find(key);
+ if (it != cache.end()) {
+ auto& wptr = it->second;
+ sptr = wptr.lock();
+ if (!sptr) {
+ sptr = std::make_shared<T>(eng, cargs...);
+ wptr = sptr;
+ }
+ } else {
+ sptr = std::make_shared<T>(eng, cargs...);
+ cache.emplace(std::make_pair(key, std::weak_ptr<const T>(sptr)));
+ }
+ return sptr;
+}
+
+struct onednn_linear {
+ std::shared_ptr<const onednn_matmul> mm;
+ dnnl::memory weight;
+ dnnl::memory scale;
+ dnnl::memory zp;
+ dnnl::matmul m_prim;
+ dnnl::memory::dim m_K;
+ dnnl::memory::dim m_N;
+ dnnl::memory::dim m_batch;
+ dnnl::memory::data_type m_a_type;
+ int bin_post_id;
+
+ static onednn_linear create(dnnl::engine eng,
+ dnnl::memory::data_type act_dtype,
+ dnnl::memory::data_type weight_dtype,
+ int batch,
+ int ic,
+ int oc,
+ int ic_group_size,
+ onednn_matmul::type t,
+ dnnl::memory weight, // external weight
+ dnnl::memory scale,
+ dnnl::memory zp,
+ dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish) {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("onednn_linear::create()"));
+ bool has_zp = static_cast<bool>(zp);
+ auto mm = make_cacheable<onednn_matmul>(eng, act_dtype, weight_dtype, batch, ic, oc, ic_group_size, t, has_zp, activation_algo);
+ onednn_linear linear;
+ linear.mm = mm;
+ linear.bin_post_id = mm->bin_post_id;
+ linear.m_prim = mm->m_prim;
+ linear.m_K = mm->m_K;
+ linear.m_N = mm->m_N;
+ linear.m_batch = batch;
+ linear.m_a_type = mm->m_a_type;
+ linear.weight = weight;
+
+ if (scale) {
+ // https://uxlfoundation.github.io/oneDNN/page_weights_decompression_matmul_cpp.html
+ // Quantization Group size for scales. Must be divisible by 32.
+ linear.scale = scale;
+ if (zp) {
+ linear.zp = zp;
+ }
+ }
+ return linear;
+ }
+
+ void forward(dnnl::stream& stream, int m, dnnl::memory src_mem, dnnl::memory dst_mem, dnnl::memory bin_mem) {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("onednn_linear::forward()"));
+ dnnl::memory::dim M = m;
+
+ if (!(m_batch == 0 || m_batch == M)) {
+ OPENVINO_THROW("onednn_linear::forward(): invalid batch size m_batch=", m_batch, " M=", M);
+ }
+
+ std::unordered_map<int, dnnl::memory> args;
+ args.insert({DNNL_ARG_SRC, src_mem});
+ args.insert({DNNL_ARG_WEIGHTS, weight});
+ // args.insert({DNNL_ARG_BIAS, bias_mem});
+ args.insert({DNNL_ARG_DST, dst_mem});
+
+ if (scale) {
+ args.insert({DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale});
+ }
+ if (zp) {
+ args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, zp});
+ }
+ if (bin_mem) {
+ args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(bin_post_id) | DNNL_ARG_SRC_1, bin_mem});
+ }
+ m_prim.execute(stream, args);
+ }
+};
+
+} // namespace onednn
+} // namespace cldnn
+
+#endif // ENABLE_ONEDNN_FOR_GPU
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
index 48137795595..9f5be16e4e5 100644
--- a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp
@@ -273,13 +273,12 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmCompressedFusion,
// MoEGatherMatmulTest: alias for MoECompressedFusionTest with force_gather_matmul=true.
using MoEGatherMatmulTest = MoECompressedFusionTest;
-// u8 excluded: GatherMatmul prefill micro-kernel for u8 is not selectable yet.
INSTANTIATE_TEST_SUITE_P(smoke_MoEGatherMatmul,
MoEGatherMatmulTest,
::testing::Combine(::testing::ValuesIn(moe_params_smoke),
::testing::Values(MoePatternType::GEMM3),
::testing::ValuesIn(routing_types),
- ::testing::Values(ov::element::u4),
+ ::testing::ValuesIn(weights_precisions),
::testing::Values(ov::element::f16), // decompression_precision
::testing::Values(ov::element::f16), // scale_precision
::testing::Values(ov::test::utils::DecompressionType::full),
@@ -299,7 +298,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmGatherMatmul,
::testing::Combine(::testing::ValuesIn(moe_params_smoke),
::testing::Values(MoePatternType::GEMM2),
::testing::Values(MoERoutingType::SOFTMAX),
- ::testing::Values(ov::element::u4),
+ ::testing::ValuesIn(weights_precisions),
::testing::Values(ov::element::f16), // decompression_precision
::testing::Values(ov::element::f16), // scale_precision
::testing::Values(ov::test::utils::DecompressionType::full),