Skip to content

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

[GPU] Add MoE int3 dpas kernel (#39366)

Nina Wiedemann3950a0b93185
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
index a731165b8e7..3bf47deff3e 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl
@@ -83,7 +83,7 @@ OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, pa_mixed_route_mode, std::strin
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_micro_gemm_prefill, true, "MoE 3GEMM: use micro-kernel GEMM for the prefill path. Requires Xe2+ and 4-bit weights; overridden when grouped GEMM is enabled")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_gpu_mask_gen_prefill, false, "MoE 3GEMM: generate routing masks on GPU instead of CPU for the micro-kernel prefill path")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_use_grouped_gemm_prefill, true, "MoE 3GEMM: use a single OneDNN grouped matmul per GEMM layer for the prefill path. Takes priority over micro-kernel GEMM")
-OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_batched_gemv_threshold, 32, "MoE 3-GEMM: token count (<=) that selects the batched GEMV decode path instead of the prefill path")
+OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_batched_gemv_threshold, 0, "MoE 3-GEMM: token count (<=) that selects the batched GEMV decode path instead of the prefill path. 0 picks the GEMV's own default (32, or a per-device value for u3 weights)")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, moe_disable_fusion, false, "Disable fusion of MoE subgraph to composite MoE operation")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, enable_ternocl_int2, true, "Enable/Disable the TernOCL implementation of FullyConnected with ternary (u2) weights; when disabled the stock kernels are used")
OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, enable_rms_rope_fusion, true, "Enable/Disable the pass which folds per-head Q/K RMSNorm into RoPE")
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.cpp
new file mode 100644
index 00000000000..6900d2ed86e
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.cpp
@@ -0,0 +1,166 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_3gemm_int3_gemv.hpp"
+
+#include <algorithm>
+
+#include "common_utils/jitter.hpp"
+#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"
+#include "moe_3gemm_base.hpp"
+#include "ocl_v2/utils/jitter.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+
+namespace ov::intel_gpu::ocl {
+
+namespace {
+
+// Weight matrices of the routed experts in input order (gate, up, down); the shared expert's follow at SHARED_GATE_WEIGHT
+constexpr size_t INPUTS_PER_MATRIX = 3;
+
+size_t weight_input(size_t matrix, bool shared) {
+ const auto first = shared ? MOE3GemmInputIndex::SHARED_GATE_WEIGHT : MOE3GemmInputIndex::WEIGHT_0;
+ return static_cast<size_t>(first) + matrix * INPUTS_PER_MATRIX;
+}
+
+struct Int3MatrixDesc {
+ size_t k;
+ size_t n;
+ size_t weight_group_size; // 0 if the weights or scales don't suit the kernel
+ bool zp_scalar;
+ ov::element::Type zp_type;
+};
+
+// matrix: 0 gate, 1 up, 2 down
+Int3MatrixDesc get_int3_matrix_desc(const RuntimeParams& params, size_t matrix, bool shared) {
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ const bool down = matrix == 2;
+ const size_t k = down ? config.inter_size : config.hidden_size;
+ const size_t n = down ? config.hidden_size : config.inter_size;
+ const size_t experts = shared ? 1 : config.num_expert;
+ const auto& weight = params.get_input_layout(weight_input(matrix, shared));
+ const auto& scale = params.get_input_layout(weight_input(matrix, shared) + 1);
+ Int3MatrixDesc desc{k, n, 0, false, ov::element::dynamic};
+ if (weight.data_type != ov::element::u3 || scale.data_type != ov::element::f16) {
+ return desc;
+ }
+ const size_t weight_groups = scale.count() / (experts * n);
+ if (weight_groups == 0 || scale.count() != experts * n * weight_groups || k % weight_groups != 0) {
+ return desc;
+ }
+ // The zero point is shared by all the experts, or has the scales' shape
+ if (config.has_zp) {
+ const auto& zp = params.get_input_layout(weight_input(matrix, shared) + 2);
+ desc.zp_scalar = zp.count() == 1;
+ desc.zp_type = zp.data_type;
+ if (!one_of(zp.data_type, {ov::element::u8, ov::element::i8}) || (!desc.zp_scalar && zp.count() != scale.count())) {
+ return desc;
+ }
+ }
+ desc.weight_group_size = k / weight_groups;
+ return desc;
+}
+
+} // namespace
+
+bool MoE3GemmInt3Gemv::has_shared_expert(const RuntimeParams& params) {
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ return config.num_shared_expert > 0 && params.input_layouts.size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT);
+}
+
+bool MoE3GemmInt3Gemv::is_supported(const RuntimeParams& params) {
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ if (params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0)).data_type != ov::element::u3 ||
+ params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES)).data_type != ov::element::f16) {
+ return false;
+ }
+ // A shared expert of another precision runs the other weight types' kernels
+ const bool shared = has_shared_expert(params);
+ if (config.num_shared_expert > 1 || (config.num_shared_expert == 1 && !shared)) {
+ return false;
+ }
+ if (shared && params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT)).data_type != ov::element::f16) {
+ return false;
+ }
+ // The kernel takes one group size and zero point kind per projection: gate and up, and the shared expert's
+ // matrices, must match the routed gate (or down) matrix
+ for (size_t matrix = 0; matrix < 3; ++matrix) {
+ const auto ref = get_int3_matrix_desc(params, matrix == 2 ? 2 : 0, false);
+ const auto proj = matrix == 2 ? Projection::DOWN : Projection::GATE_UP;
+ if (ref.k % (SIMD * 32) != 0 || ref.weight_group_size == 0 || ref.weight_group_size % 32 != 0 || ref.n % (SGN * get_nb(params, proj)) != 0) {
+ return false;
+ }
+ for (bool is_shared : {false, true}) {
+ if (is_shared && !shared) {
+ continue;
+ }
+ const auto desc = get_int3_matrix_desc(params, matrix, is_shared);
+ if (desc.weight_group_size != ref.weight_group_size || desc.zp_scalar != ref.zp_scalar || desc.zp_type != ref.zp_type) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+// One token runs top_k * n / nb subgroups. The column counts (more for down, whose K is short) suit a GPU with 512
+// hardware threads; on larger GPUs they shrink until a single token keeps at least half of the threads busy.
+size_t MoE3GemmInt3Gemv::get_nb(const RuntimeParams& params, Projection proj) {
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ const auto& info = params.get_device_info();
+ const size_t threads = static_cast<size_t>(info.execution_units_count) * std::max<uint32_t>(info.num_threads_per_eu, 1);
+ const size_t n = proj == Projection::DOWN ? config.hidden_size : config.inter_size;
+ size_t nb = proj == Projection::DOWN ? 32 : 8;
+ while (nb > 1 && config.top_k * n / nb < threads / 2) {
+ nb /= 2;
+ }
+ return nb;
+}
+
+// Most tokens per step for which the u3 batched GEMV beats the OneDNN grouped GEMM on a Qwen3.6-35B-A3B MoE layer. The
+// GEMV is bound by the memory bandwidth, the grouped GEMM by the compute: on the shared memory of an integrated GPU the
+// crossover drops with the EU count (6 tokens on LNL 258V with 64 EUs, about 2 on PTL 386H with 96 EUs), while a
+// discrete GPU stays on the GEMV much longer (about 16 tokens on BMG B570).
+size_t MoE3GemmInt3Gemv::get_default_threshold(const RuntimeParams& params) {
+ const auto& info = params.get_device_info();
+ if (info.dev_type == cldnn::device_type::discrete_gpu) {
+ return 16;
+ }
+ return info.execution_units_count <= 64 ? 6 : 2;
+}
+
+JitConstants MoE3GemmInt3Gemv::get_jit_constants(const RuntimeParams& params) const {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ const auto desc = get_int3_matrix_desc(params, m_proj == Projection::DOWN ? 2 : 0, false);
+ jit.make("GEMV_DOWN", m_proj == Projection::DOWN ? 1 : 0);
+ jit.make("K_SIZE", desc.k);
+ jit.make("N_SIZE", desc.n);
+ jit.make("WEI_GROUP_SIZE", desc.weight_group_size);
+ jit.make("HAS_ZP", config.has_zp ? 1 : 0);
+ if (config.has_zp) {
+ jit.make("ZP_SCALAR", desc.zp_scalar ? 1 : 0);
+ jit.make("ZP_TYPE", desc.zp_type == ov::element::i8 ? "char" : "uchar");
+ }
+ jit.make("MAX_TOPK", config.top_k);
+ jit.make("SHARED_EXPERT", has_shared_expert(params) ? 1 : 0);
+ jit.make("SGN", SGN);
+ jit.make("NB", get_nb(params, m_proj));
+ switch (config.activation_type) {
+ case ov::op::internal::MOE::Activation_type::SWIGLU:
+ break;
+ case ov::op::internal::MOE::Activation_type::GEGLU_TANH:
+ jit.make("GATE_ACT_GELU_TANH", 1);
+ break;
+ case ov::op::internal::MOE::Activation_type::GEGLU_ERF:
+ jit.make("GATE_ACT_GELU_ERF", 1);
+ break;
+ default:
+ OPENVINO_THROW("MoE u3 batched GEMV: unsupported gate activation ", static_cast<int>(config.activation_type));
+ }
+ return jit;
+}
+
+} // namespace ov::intel_gpu::ocl
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.hpp
new file mode 100644
index 00000000000..8d4bc53bddc
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_int3_gemv.hpp
@@ -0,0 +1,54 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+
+#include "../utils/kernel_generator.hpp"
+#include "intel_gpu/graph/kernel_impl_params.hpp"
+
+namespace ov::intel_gpu::ocl {
+
+// Batched GEMV decode of u3 experts (moe_3gemm_int3.cl)
+class MoE3GemmInt3Gemv : public KernelGenerator {
+public:
+ enum class Projection { GATE_UP, DOWN };
+
+ // Work-groups of SGN subgroups of SIMD lanes, each subgroup computing get_nb() output columns of one
+ // (token, top-k slot) pair.
+ static constexpr size_t SGN = 8;
+ static constexpr size_t SIMD = 16;
+
+ explicit MoE3GemmInt3Gemv(Projection proj) : KernelGenerator("moe_3gemm_int3", proj == Projection::DOWN ? "gemv_down" : "gemv_gate_up"), m_proj(proj) {}
+
+ // Whether the kernels support this MoE: u3 weights, f16 activations and scales, a u8/i8 zero point that is scalar
+ // or shaped like the scales (or none), K a multiple of 512 and weight groups a multiple of 32 values. A shared
+ // expert needs u3 weights of the same layout.
+ static bool is_supported(const RuntimeParams& params);
+
+ // Output columns per subgroup of a projection, tied to the GPU size
+ static size_t get_nb(const RuntimeParams& params, Projection proj);
+
+ // Most tokens per step that decode through the u3 batched GEMV unless GPU_MOE_BATCHED_GEMV_THRESHOLD is set
+ static size_t get_default_threshold(const RuntimeParams& params);
+
+protected:
+ Projection m_proj;
+
+ // Whether the shared expert is fused into the kernels, as an extra slot per token
+ static bool has_shared_expert(const RuntimeParams& params);
+
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override;
+
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ return {};
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {}};
+ }
+};
+
+} // namespace ov::intel_gpu::ocl
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 a07c75481c9..858a004d4f0 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
@@ -4,6 +4,7 @@
// clang-format off
#include "moe_3gemm_gen_micro.hpp"
+#include "moe_3gemm_int3_gemv.hpp"
#include "moe_otd_runtime.hpp"
#include "moe_3gemm_swiglu_opt.hpp"
#include "openvino/runtime/shared_buffer.hpp"
@@ -77,6 +78,7 @@ inline dnnl::algorithm moe_activation_to_dnnl_algo(ov::op::internal::MOE::Activa
// GEMM implementation of a token-count regime. Fixed at impl creation, see moe_3gemm_swiglu_opt_impl().
enum class MoeGemmImpl : uint8_t {
batched_gemv, // OCL batched GEMV kernels, decode only
+ int3_batched_gemv, // OCL batched GEMV kernels for u3 weights (moe_3gemm_int3.cl), decode only
micro_gemm, // OCL micro-kernel GEMM, prefill only
grouped_gemm, // one OneDNN grouped matmul per GEMM layer
per_expert_onednn, // OneDNN matmul per activated expert, prefill only
@@ -433,35 +435,38 @@ protected:
# define N_BLOCK 4
# define SUBGROUP_NUM 8
+// group_size == SIZE_MAX means per-channel compression: a single group spans the whole K
+static size_t get_group_size(const MOECompressed::Config& config, size_t k) {
+ return config.group_size == std::numeric_limits<size_t>::max() ? k : config.group_size;
+}
+
+// Validate GEMV kernel compatibility: ELEMS_PER_LANE = FAKE_GROUP_SIZE / SUBGROUP_SIZE must be >= 2.
+// Smaller values have no kernel branch and would silently produce wrong results.
+static void check_gemv_group_size(const RuntimeParams& params) {
+ const auto& config = params.typed_desc<moe_3gemm_fused_compressed>()->_config;
+ const auto gate_up_group_size = get_group_size(config, config.hidden_size);
+ const size_t sg = (params.get_device_info().arch >= gpu_arch::xe2) ? 32u : 16u;
+ const size_t fake_gs = std::min(gate_up_group_size, size_t{128});
+ OPENVINO_ASSERT(fake_gs >= 2 * sg,
+ "MoE GEMV kernel does not support group_size=",
+ gate_up_group_size,
+ " on this hardware (SUBGROUP_SIZE=",
+ sg,
+ "). Minimum supported group_size is ",
+ 2 * sg,
+ ". Use a larger quantization group size.");
+}
+
static void add_common_consts(const RuntimeParams& params, JitConstants& jit) {
auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
auto& engine = params.prog->get_engine();
const auto& info = engine.get_device_info();
- auto gate_up_group_size = desc->_config.group_size;
- auto down_group_size = desc->_config.group_size;
- if (desc->_config.group_size == std::numeric_limits<size_t>::max()) {
- gate_up_group_size = desc->_config.hidden_size;
- down_group_size = desc->_config.inter_size;
- }
+ const auto gate_up_group_size = get_group_size(desc->_config, desc->_config.hidden_size);
+ const auto down_group_size = get_group_size(desc->_config, desc->_config.inter_size);
GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt: group_size=" << desc->_config.group_size << ", gate_up_group_size=" << gate_up_group_size
<< ", down_group_size=" << down_group_size << std::endl;
- // Validate GEMV kernel compatibility: ELEMS_PER_LANE = FAKE_GROUP_SIZE / SUBGROUP_SIZE must be >= 2.
- // Smaller values have no kernel branch and would silently produce wrong results.
- {
- const size_t sg = (info.arch >= gpu_arch::xe2) ? 32u : 16u;
- const size_t fake_gs = std::min(gate_up_group_size, size_t{128});
- OPENVINO_ASSERT(fake_gs >= 2 * sg,
- "MoE GEMV kernel does not support group_size=",
- gate_up_group_size,
- " on this hardware (SUBGROUP_SIZE=",
- sg,
- "). Minimum supported group_size is ",
- 2 * sg,
- ". Use a larger quantization group size.");
- }
-
jit.make("MAX_TOPK", desc->_config.top_k);
jit.make("EXPERT_NUM", desc->_config.num_expert);
jit.make("HIDDEN_SIZE", desc->_config.hidden_size);
@@ -508,6 +513,7 @@ protected:
[[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
auto jit = KernelGenerator::get_jit_constants(params);
auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
+ check_gemv_group_size(params);
add_common_consts(params, jit);
jit.make("GATE_UP_ENABLE", 1);
if (desc->_config.activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
@@ -547,6 +553,7 @@ protected:
[[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
auto jit = KernelGenerator::get_jit_constants(params);
auto desc = params.typed_desc<moe_3gemm_fused_compressed>();
+ check_gemv_group_size(params);
add_common_consts(params, jit);
jit.make("DOWN_ENABLE", 1);
if (!_disable_shared_experts && desc->_config.num_shared_expert > 0 &&
@@ -660,10 +667,13 @@ public:
Stage::Ptr grouped_gemm_prefill_gather = make_stage<MoE3GemmSwigluPrefillGather>(/*use_grouped_gemm=*/true);
Stage::Ptr grouped_gemm_prefill_swiglu = make_stage<MoE3GemmSwigluPrefillSwiglu>(/*use_grouped_gemm=*/true);
Stage::Ptr prefill_scatter_reduce_row_lut = make_stage<MoE3GemmSwigluPrefillScatterReduceRowLut>();
- // Single-token decode of weight types without a batched GEMV kernel (u3) goes through grouped GEMM. The CPU mask gen
- // would cost a host sync on topk in every MoE layer (~1 ms/token on Qwen3.6-35B-A3B int3). For one token the max rows
- // per expert (the grouped GEMM dispatch hint) is known to be 1, so the masks can be built on the GPU instead.
+ // Single-token decode of weights without a batched GEMV kernel (u3 outside MoE3GemmInt3Gemv::is_supported) goes through grouped GEMM.
+ // The CPU mask gen would cost a host sync on topk in every MoE layer (~1 ms/token on Qwen3.6-35B-A3B int3). For one token
+ // the max rows per expert (the grouped GEMM dispatch hint) is known to be 1, so the masks can be built on the GPU instead.
Stage::Ptr grouped_gemm_mask_gen = make_stage<MoE3GemmSwigluPrefillMaskGen>(/*use_grouped_gemm=*/true);
+ // u3 decode on the moe_3gemm_int3 batched GEMV
+ Stage::Ptr int3_gemv_gate_up = make_stage<MoE3GemmInt3Gemv>(MoE3GemmInt3Gemv::Projection::GATE_UP);
+ Stage::Ptr int3_gemv_down = make_stage<MoE3GemmInt3Gemv>(MoE3GemmInt3Gemv::Projection::DOWN);
struct dnnl_weights {
dnnl::memory weight;
@@ -1032,10 +1042,12 @@ public:
// Instance-specific flags (not static to avoid race conditions)
// Set by config: build the routing masks on the GPU for prefill, overriding the per-impl heuristic
bool force_gpu_mask_gen_prefill = false;
- // Weight types without a batched GEMV OCL kernel (u3) run decode through OneDNN grouped GEMM instead
+ // Weights without a batched GEMV OCL kernel run decode through OneDNN grouped GEMM instead
MoeGemmImpl decode_impl = MoeGemmImpl::batched_gemv; // token_num <= batched_gemv_threshold
MoeGemmImpl prefill_impl = MoeGemmImpl::per_expert_onednn;
size_t batched_gemv_threshold = 32;
+ // Output columns per subgroup of the u3 batched GEMV, per MoE3GemmInt3Gemv::Projection
+ std::array<size_t, 2> int3_gemv_nbs{};
MoeGemmImpl select_impl(size_t token_num) const {
return token_num <= batched_gemv_threshold ? decode_impl : prefill_impl;
@@ -1074,13 +1086,16 @@ public:
return one_of(weight_dt, {data_types::u4, data_types::i4, data_types::u8, data_types::i8, data_types::f16});
}
- // Weight types without a batched GEMV OCL kernel (u3) decode through OneDNN grouped GEMM instead
- static MoeGemmImpl select_decode_impl(data_types weight_dt) {
+ // Weights without a batched GEMV OCL kernel decode through OneDNN grouped GEMM instead
+ static MoeGemmImpl select_decode_impl(const RuntimeParams& params, data_types weight_dt) {
+ if (MoE3GemmInt3Gemv::is_supported(params)) {
+ return MoeGemmImpl::int3_batched_gemv;
+ }
return is_batched_gemv_supported(weight_dt) ? MoeGemmImpl::batched_gemv : MoeGemmImpl::grouped_gemm;
}
static MoeGemmImpl select_prefill_impl(const ExecutionConfig& config, data_types weight_dt, gpu_arch arch) {
- // No batched GEMV kernel for this weight type: both decode and prefill go through OneDNN grouped GEMM
+ // No GEMV-based prefill for this weight type (u3): prefill goes through OneDNN grouped GEMM
if (!is_batched_gemv_supported(weight_dt) || config.get_moe_use_grouped_gemm_prefill()) {
return MoeGemmImpl::grouped_gemm;
}
@@ -1104,15 +1119,21 @@ public:
force_gpu_mask_gen_prefill = config.get_moe_use_gpu_mask_gen_prefill();
const auto& weight_dt = params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0)).data_type;
- decode_impl = select_decode_impl(weight_dt);
+ decode_impl = select_decode_impl(params, weight_dt);
prefill_impl = select_prefill_impl(config, weight_dt, params.prog->get_engine().get_device_info().arch);
GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt_impl(): prefill_impl=" << static_cast<int>(prefill_impl)
<< ", decode_impl=" << static_cast<int>(decode_impl) << std::endl;
+ if (decode_impl == MoeGemmImpl::int3_batched_gemv) {
+ for (auto proj : {MoE3GemmInt3Gemv::Projection::GATE_UP, MoE3GemmInt3Gemv::Projection::DOWN}) {
+ int3_gemv_nbs[static_cast<size_t>(proj)] = MoE3GemmInt3Gemv::get_nb(params, proj);
+ }
+ }
batched_gemv_threshold = config.get_moe_batched_gemv_threshold();
if (batched_gemv_threshold == 0) {
- batched_gemv_threshold = 1;
+ // The u3 GEMV loses to the grouped GEMM much earlier than the other GEMVs
+ batched_gemv_threshold = decode_impl == MoeGemmImpl::int3_batched_gemv ? MoE3GemmInt3Gemv::get_default_threshold(params) : 32;
}
GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt_impl(): batched_gemv_threshold=" << batched_gemv_threshold << std::endl;
@@ -1136,6 +1157,11 @@ public:
add_stage(mlp_down, params);
add_stage(mlp_reduce, params);
}
+ if (decode_impl == MoeGemmImpl::int3_batched_gemv) {
+ add_stage(int3_gemv_gate_up, params);
+ add_stage(int3_gemv_down, params);
+ add_stage(mlp_reduce, params);
+ }
if (prefill_impl == MoeGemmImpl::micro_gemm) {
add_stage(prefill_mask_gen, params);
add_stage(prefill_gather, params);
@@ -1158,14 +1184,9 @@ public:
void init(const std::shared_ptr<const moe_3gemm_fused_compressed>& cur_moe) {
_hidden_size = static_cast<int>(cur_moe->_config.hidden_size);
_intermediate_size = static_cast<int>(cur_moe->_config.inter_size);
- _gate_up_group_size = static_cast<int>(cur_moe->_config.group_size);
- _down_group_size = static_cast<int>(cur_moe->_config.group_size);
+ _gate_up_group_size = static_cast<int>(get_group_size(cur_moe->_config, cur_moe->_config.hidden_size));
+ _down_group_size = static_cast<int>(get_group_size(cur_moe->_config, cur_moe->_config.inter_size));
_activation_type = cur_moe->_config.activation_type;
-
- if (cur_moe->_config.group_size == std::numeric_limits<size_t>::max()) {
- _gate_up_group_size = static_cast<int>(cur_moe->_config.hidden_size);
- _down_group_size = static_cast<int>(cur_moe->_config.inter_size);
- }
GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt prefill: group_size=" << cur_moe->_config.group_size
<< ", gate_up_group_size=" << _gate_up_group_size << ", down_group_size=" << _down_group_size << std::endl;
}
@@ -1394,6 +1415,10 @@ public:
ob << force_gpu_mask_gen_prefill;
ob << make_data(&prefill_impl, sizeof(prefill_impl));
ob << make_data(&decode_impl, sizeof(decode_impl));
+ for (size_t nb : int3_gemv_nbs) {
+ ob << nb;
+ }
+ ob << batched_gemv_threshold;
}
void load(BinaryInputBuffer& ib) override {
@@ -1403,6 +1428,10 @@ public:
ib >> force_gpu_mask_gen_prefill;
ib >> make_data(&prefill_impl, sizeof(prefill_impl));
ib >> make_data(&decode_impl, sizeof(decode_impl));
+ for (size_t& nb : int3_gemv_nbs) {
+ ib >> nb;
+ }
+ ib >> batched_gemv_threshold;
const kernel_impl_params* impl_params = reinterpret_cast<kernel_impl_params*>(ib.getKernelImplParams());
auto cur_moe = impl_params->typed_desc<moe_3gemm_fused_compressed>();
init(cur_moe);
@@ -1427,6 +1456,7 @@ public:
cur_moe->force_gpu_mask_gen_prefill = force_gpu_mask_gen_prefill;
cur_moe->prefill_impl = prefill_impl;
cur_moe->decode_impl = decode_impl;
+ cur_moe->int3_gemv_nbs = int3_gemv_nbs;
cur_moe->batched_gemv_threshold = batched_gemv_threshold;
cur_moe->_activation_type = _activation_type;
return cur_moe;
@@ -1502,7 +1532,6 @@ public:
void prepare_internal_buffers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch, size_t token_num) {
const auto& intermediates_memories = instance.get_intermediates_memories();
- auto& engine = instance.get_network().get_engine();
// topk_id / topk_weights are read from inputs (computed by MoERouterFused).
scratch.topk_weights = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::TOPK_WEIGHTS));
@@ -1516,24 +1545,31 @@ public:
scratch.gate = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_OUTPUT];
}
// Per-expert masks feed only the per-expert onednn loop, which the other paths fall back to only with offloaded
- // experts. Creating them costs two sub-buffers per expert in every layer (~0.4 ms per layer for 256 experts).
+ // experts. Creating them costs two sub-buffers per expert in every layer (~0.4 ms per layer for 256 experts), so a
+ // single-token step creates them only when it falls back (exec_per_expert_onednn_linear).
const bool needs_expert_masks = select_impl(token_num) == MoeGemmImpl::per_expert_onednn || _weight_provider->is_offloaded();
- if (needs_gather_scratch(token_num) && needs_expert_masks) {
- const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
- int expert_num = static_cast<int>(config.num_expert);
- scratch.expert_masks.resize(expert_num);
- for (int i = 0; i < expert_num; i++) {
- auto mask_layout = cldnn::layout({static_cast<int>(token_num)}, cldnn::data_types::i32, cldnn::format::get_default_format(1));
- scratch.expert_masks[i].batch =
- engine.create_subbuffer(*intermediates_memories[MOE_INTERNAL_BUFFER_EXPERT_MASK_BATCH], mask_layout, i * token_num * sizeof(int32_t));
- scratch.expert_masks[i].topk =
- engine.create_subbuffer(*intermediates_memories[MOE_INTERNAL_BUFFER_EXPERT_MASK_TOPK], mask_layout, i * token_num * sizeof(int32_t));
- }
+ if (token_num > 1 && needs_expert_masks) {
+ prepare_expert_masks(instance, scratch, token_num);
}
prepare_weight_pointers(instance, scratch);
}
+ void prepare_expert_masks(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch, size_t token_num) {
+ const auto& intermediates_memories = instance.get_intermediates_memories();
+ auto& engine = instance.get_network().get_engine();
+ const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
+ int expert_num = static_cast<int>(config.num_expert);
+ scratch.expert_masks.resize(expert_num);
+ for (int i = 0; i < expert_num; i++) {
+ auto mask_layout = cldnn::layout({static_cast<int>(token_num)}, cldnn::data_types::i32, cldnn::format::get_default_format(1));
+ scratch.expert_masks[i].batch =
+ engine.create_subbuffer(*intermediates_memories[MOE_INTERNAL_BUFFER_EXPERT_MASK_BATCH], mask_layout, i * token_num * sizeof(int32_t));
+ scratch.expert_masks[i].topk =
+ engine.create_subbuffer(*intermediates_memories[MOE_INTERNAL_BUFFER_EXPERT_MASK_TOPK], mask_layout, i * token_num * sizeof(int32_t));
+ }
+ }
+
void get_expert_mask_from_gpu(const MOECompressed::Config& config, memory::ptr mem, stream& stream, expert_mask_cpu& expert_mask, size_t actual_token_num) {
// shape: [token_num, topk]
auto layout = mem->get_layout();
@@ -1664,22 +1700,21 @@ public:
typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
scratch_buffers& scratch,
size_t token_num) {
+ auto& cur_net = instance.get_network();
+ auto& stream = cur_net.get_stream();
auto cur_moe = instance.get_typed_desc<moe_3gemm_fused_compressed>();
int max_topk = static_cast<int>(cur_moe->_config.top_k);
- auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
- auto batch_mem_ptr = scratch.topk_id;
auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
auto routing_mem_ptr = scratch.topk_weights;
_hidden_size = static_cast<int>(cur_moe->_config.hidden_size);
_intermediate_size = static_cast<int>(cur_moe->_config.inter_size);
const size_t subgroup_size = instance.get_impl_params()->get_device_info().arch >= gpu_arch::xe2 ? 32 : 16;
- const size_t max_work_group_size = instance.get_impl_params()->get_device_info().max_work_group_size;
- // OTD hook may have remapped expert IDs into scratch._expert_index_buffer
- if (scratch._expert_index_buffer) {
- batch_mem_ptr = scratch._expert_index_buffer;
+ auto batch_mem_ptr = get_batched_gemv_expert_ids(stream, instance, scratch, token_num);
+ if (!batch_mem_ptr) {
+ return exec_batched_gemv_fallback(events, stream, instance, scratch, token_num);
}
// gate
@@ -1701,7 +1736,6 @@ public:
size_t compute_experts = static_cast<size_t>(max_topk);
Stage* stage_gate_up = mlp_gate_up.get();
Stage* stage_down = mlp_down.get();
- Stage* stage_reduce = mlp_reduce.get();
std::vector<memory::ptr> extra_args_gate_up;
std::vector<memory::ptr> extra_args_down;
@@ -1761,26 +1795,150 @@ public:
{token_num * compute_experts, subgroup_size, static_cast<size_t>(_hidden_size / N_BLOCK)},
{1, subgroup_size, SUBGROUP_NUM});
- // Per-token reduction: final[t] = sum(scratch.y[t * REDUCE_COUNT .. (t+1) * REDUCE_COUNT - 1])
- // The local size must divide hidden_size: drivers may reject non-uniform work-groups (-54).
- const size_t hidden_size = static_cast<size_t>(_hidden_size);
- size_t reduce_lws = std::min(max_work_group_size, size_t{1024}) / subgroup_size * subgroup_size;
- while (reduce_lws > 0 && hidden_size % reduce_lws != 0) {
- reduce_lws -= subgroup_size;
- }
- OPENVINO_ASSERT(reduce_lws > 0, "MoE mlp_reduce: hidden_size=", hidden_size, " is not a multiple of SUBGROUP_SIZE=", subgroup_size);
- ret = execute_stage({ret_event},
- instance,
- *stage_reduce,
- {scratch.y},
- {final_hidden_states_mem_ptr},
- {token_num, hidden_size},
- {1, reduce_lws},
- instance.needs_completion_event());
+ ret = exec_batched_gemv_reduce(ret_event, instance, scratch, token_num);
}
return ret;
}
+ // Experts of a batched GEMV path: the topk ids, or their remapped slots once OTD leased them. nullptr if they
+ // cannot all be leased at once.
+ memory::ptr get_batched_gemv_expert_ids(cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch,
+ size_t token_num) {
+ const size_t topk_count = token_num * instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config.top_k;
+ bool needs_fallback = false;
+ on_before_batched_gemv(stream, instance, scratch, topk_count, needs_fallback);
+ if (needs_fallback) {
+ return nullptr;
+ }
+ return scratch._expert_index_buffer ? scratch._expert_index_buffer : scratch.topk_id;
+ }
+
+ // Per-expert onednn loop for a batched GEMV step whose experts cannot all be leased at once, then the shared expert,
+ // which the batched GEMV would have computed
+ cldnn::event::ptr exec_batched_gemv_fallback(const std::vector<cldnn::event::ptr>& events,
+ cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch,
+ size_t token_num) {
+ auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
+ final_hidden_states_mem_ptr->fill(stream, 0u);
+ for (const auto& ev : events) {
+ if (ev) {
+ ev->wait();
+ }
+ }
+ update_rt_params(instance);
+ auto ret_event = exec_per_expert_onednn_linear(events, stream, instance, scratch);
+ if (_has_shared_expert) {
+ // The shared expert's down projection adds to the output: the in-order queue runs it after the experts
+ init_shared_primitives(instance.get_network().get_engine(), scratch.moe_fusion_wei_addr, static_cast<int>(token_num));
+ execute_shared_expert(stream.get_onednn_stream(),
+ static_cast<int>(token_num),
+ instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES)),
+ final_hidden_states_mem_ptr,
+ scratch);
+ }
+ // Include the shared expert and all OneDNN work before returning the completion event
+ on_after_exec_sync(stream);
+ return ret_event;
+ }
+
+ // Per-token reduction of the batched GEMV paths: final[t] = sum(scratch.y[t * REDUCE_COUNT .. (t+1) * REDUCE_COUNT - 1])
+ cldnn::event::ptr exec_batched_gemv_reduce(cldnn::event::ptr dep,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch,
+ size_t token_num) {
+ const auto& info = instance.get_impl_params()->get_device_info();
+ const size_t subgroup_size = info.arch >= gpu_arch::xe2 ? 32 : 16;
+ // The local size must divide hidden_size: drivers may reject non-uniform work-groups (-54).
+ const size_t hidden_size = static_cast<size_t>(_hidden_size);
+ size_t reduce_lws = std::min(static_cast<size_t>(info.max_work_group_size), size_t{1024}) / subgroup_size * subgroup_size;
+ while (reduce_lws > 0 && hidden_size % reduce_lws != 0) {
+ reduce_lws -= subgroup_size;
+ }
+ OPENVINO_ASSERT(reduce_lws > 0, "MoE mlp_reduce: hidden_size=", hidden_size, " is not a multiple of SUBGROUP_SIZE=", subgroup_size);
+ return execute_stage({dep},
+ instance,
+ *mlp_reduce,
+ {scratch.y},
+ {instance.output_memory_ptr(0)},
+ {token_num, hidden_size},
+ {1, reduce_lws},
+ instance.needs_completion_event());
+ }
+
+ // Batched GEMV path of u3 weights (moe_3gemm_int3.cl): gate/up GEMV with the gate activation fused, down GEMV
+ // scaled by the routing weight, then the per-token reduction. The shared expert is one more slot per token.
+ cldnn::event::ptr exec_int3_batched_gemv(const std::vector<cldnn::event::ptr>& events,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch,
+ size_t token_num) {
+ auto& stream = instance.get_network().get_stream();
+ const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
+ _hidden_size = static_cast<int>(config.hidden_size);
+ _intermediate_size = static_cast<int>(config.inter_size);
+
+ auto expert_ids = get_batched_gemv_expert_ids(stream, instance, scratch, token_num);
+ if (!expert_ids) {
+ return exec_batched_gemv_fallback(events, stream, instance, scratch, token_num);
+ }
+ GPU_DEBUG_TRACE_DETAIL << "\nexec_int3_batched_gemv(): token_num=" << token_num << ", max_topk=" << config.top_k
+ << ", has_shared=" << _has_shared_expert << std::endl;
+
+ const auto& wei = scratch.moe_fusion_wei_addr;
+ const size_t pairs = token_num * (config.top_k + (_has_shared_expert ? 1 : 0));
+ using Projection = MoE3GemmInt3Gemv::Projection;
+ constexpr size_t simd = MoE3GemmInt3Gemv::SIMD;
+ constexpr size_t sgn = MoE3GemmInt3Gemv::SGN;
+ const auto gemv = [&](Projection proj, std::vector<memory::ptr> inputs, memory::ptr output, const std::vector<event::ptr>& deps) {
+ const bool down = proj == Projection::DOWN;
+ const size_t n = down ? config.hidden_size : config.inter_size;
+ const size_t blocks = n / (sgn * int3_gemv_nbs[static_cast<size_t>(proj)]);
+ return execute_stage(deps,
+ instance,
+ down ? *int3_gemv_down : *int3_gemv_gate_up,
+ std::move(inputs),
+ {output},
+ {simd, sgn, pairs * blocks},
+ {simd, sgn, 1});
+ };
+
+ const auto add_weights = [&](std::vector<memory::ptr>& inputs, int w, bool shared) {
+ inputs.insert(inputs.end(), {shared ? wei.shared_weight[w] : wei.weight[w], shared ? wei.shared_scale[w] : wei.scale[w]});
+ if (config.has_zp) {
+ inputs.push_back(shared ? wei.shared_zp[w] : wei.zp[w]);
+ }
+ };
+
+ // scratch.up = act(gate(x)) * up(x) for all (token, expert) pairs
+ std::vector<memory::ptr> gate_up_inputs{expert_ids};
+ add_weights(gate_up_inputs, 0, false);
+ add_weights(gate_up_inputs, 1, false);
+ if (_has_shared_expert) {
+ add_weights(gate_up_inputs, 0, true);
+ add_weights(gate_up_inputs, 1, true);
+ gate_up_inputs.insert(gate_up_inputs.end(), {wei.shared_weight[3], scratch.routing_weights}); // shared_gate_out [token_num]
+ }
+ gate_up_inputs.push_back(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES)));
+ auto ret_event = gemv(Projection::GATE_UP, gate_up_inputs, scratch.up, events);
+
+ // scratch.y = down(scratch.up) * routing_weight for all (token, expert) pairs
+ std::vector<memory::ptr> down_inputs{expert_ids};
+ add_weights(down_inputs, 2, false);
+ if (_has_shared_expert) {
+ add_weights(down_inputs, 2, true);
+ }
+ down_inputs.insert(down_inputs.end(), {scratch.up, scratch.topk_weights});
+ if (_has_shared_expert) {
+ down_inputs.push_back(scratch.routing_weights); // shared_gate_in [token_num]
+ }
+ ret_event = gemv(Projection::DOWN, down_inputs, scratch.y, {ret_event});
+
+ return exec_batched_gemv_reduce(ret_event, instance, scratch, token_num);
+ }
+
cldnn::event::ptr exec_prefill_micro_gemm(const std::vector<cldnn::event::ptr>& events,
typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
scratch_buffers& scratch,
@@ -2371,6 +2529,15 @@ public:
auto& engine = instance.get_network().get_engine();
init_dnnl_weights(cur_moe, engine, scratch.moe_fusion_wei_addr);
+ // The OTD fallbacks of single-token steps get here without the gather scratch or the expert masks
+ auto token_num = get_seq_len(hidden_states_layout);
+ const auto& intermediates_memories = instance.get_intermediates_memories();
+ scratch.x = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_UP_INPUT];
+ scratch.gate = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_OUTPUT];
+ if (scratch.expert_masks.empty()) {
+ prepare_expert_masks(instance, scratch, token_num);
+ }
+
auto routing_mem_ptr = scratch.topk_weights;
auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
auto get_best_lws = [](size_t hidden_size) {
@@ -2387,7 +2554,6 @@ public:
// [batch, max_topk]
auto topk_id_mem = scratch.topk_id;
- auto token_num = get_seq_len(hidden_states_layout);
expert_mask_cpu expert_mask;
get_expert_mask_from_gpu(config, topk_id_mem, stream, expert_mask, token_num);
@@ -2786,12 +2952,11 @@ public:
// Batched GEMV: for small token counts (including single token, MTP/speculative decoding),
// use optimized GEMV kernels with batch dimension. Avoids gather/scatter overhead.
const MoeGemmImpl impl = select_impl(token_num);
- bool batched_fallback = false;
if (impl == MoeGemmImpl::batched_gemv) {
- on_before_batched_gemv(stream, instance, scratch, token_num * config.top_k, batched_fallback);
- if (!batched_fallback) {
- return exec_batched_gemv(events, instance, scratch, token_num);
- }
+ return exec_batched_gemv(events, instance, scratch, token_num);
+ }
+ if (impl == MoeGemmImpl::int3_batched_gemv) {
+ return exec_int3_batched_gemv(events, instance, scratch, token_num);
}
auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
@@ -2801,10 +2966,10 @@ public:
// and does not require pre-zeroing — except in OTD mode where the
// fallback to exec_per_expert_onednn_linear (when unique_experts > lru slots)
// also accumulates via index_add.
- if (batched_fallback || (impl != MoeGemmImpl::micro_gemm && should_pre_zero_output())) {
+ if (impl != MoeGemmImpl::micro_gemm && should_pre_zero_output()) {
final_hidden_states_mem_ptr->fill(stream, 0u);
}
- const bool use_gpu_mask_gen = !batched_fallback && should_use_gpu_mask_gen(impl, token_num);
+ const bool use_gpu_mask_gen = should_use_gpu_mask_gen(impl, token_num);
if (!use_gpu_mask_gen) {
// Wait for input events (topk produced upstream by MoERouterFused)
for (const auto& ev : events) {
@@ -2817,9 +2982,7 @@ public:
GPU_DEBUG_TRACE_DETAIL << "\nMoE3GemmFusedCompressed exec(): token_num=" << token_num << ", max_topk=" << static_cast<int>(config.top_k)
<< ", impl=" << static_cast<int>(impl) << std::endl;
update_rt_params(instance);
- if (batched_fallback) {
- ret_env = exec_per_expert_onednn_linear(events, stream, instance, scratch);
- } else if (impl == MoeGemmImpl::micro_gemm) {
+ if (impl == MoeGemmImpl::micro_gemm) {
ret_env = exec_prefill_micro_gemm(events, instance, scratch, use_gpu_mask_gen);
} else if (impl == MoeGemmImpl::grouped_gemm) {
ret_env = use_gpu_mask_gen ? exec_grouped_gemm_gpu_mask_gen(events, stream, instance, scratch)
@@ -2854,10 +3017,6 @@ public:
}
execute_shared_expert(stream.get_onednn_stream(), static_cast<int>(token_num), hidden_states_mem_ptr, final_hidden_states_mem_ptr, scratch);
}
- if (batched_fallback) {
- // Include the shared expert and all OneDNN work before returning the completion event.
- on_after_exec_sync(stream);
- }
return ret_env;
}
};
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.hpp
index 202720e7086..8dafaf1e67c 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.hpp
@@ -41,7 +41,8 @@ struct moe_3gemm_swiglu_opt : public ImplementationManager {
return false;
}
- // Only support weight: u4, i4, u8, i8, u3 (u3 has no batched GEMV kernel and runs decode via OneDNN grouped GEMM)
+ // Only support weight: u4, i4, u8, i8, u3 (u3 prefill runs on OneDNN grouped GEMM, and so does its decode where the
+ // u3 batched GEMV doesn't apply)
static constexpr std::array supported_wei_type = {
ov::element::u4,
ov::element::i4,
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_int3.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_int3.cl
new file mode 100644
index 00000000000..561face8c22
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_int3.cl
@@ -0,0 +1,258 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+#include "moe_gate_activation.cl"
+
+// Batched GEMV decode of the fused MoE for u3 (3-bit unsigned) weights, on f16
+// activations: one work-group per (token, top-k slot) pair and SGN * NB output
+// columns. It reads the expert ids on the GPU and needs no gather or scatter.
+//
+// Weights are the plain [E, N, K] u3 tensor: each output channel is a
+// LSB-first bit stream of K values, so a run of 32 values (a granule) is exactly
+// 3 uints. Lane l owns granule l of every CHUNK-value run of K and loads its 32
+// activations straight from the (cache resident) input, with no SLM staging or
+// barrier, so the weight loads are issued right away.
+//
+// GEMV_DOWN computes the down projection of act(gate) * up, scaled by the routing
+// weight; otherwise each subgroup computes NB gate and NB up columns and stores
+// act(gate) * up.
+//
+// SHARED_EXPERT adds the shared expert as slot MAX_TOPK of every token, as in
+// mlp_gate_up/mlp_down: its weights have the routed experts' layout with E = 1,
+// and its routing weight is sigmoid(x . shared_gate_gate_weight), which the
+// gate/up GEMV writes to shared_gate_out for the down GEMV.
+
+#pragma OPENCL EXTENSION cl_intel_subgroups : enable
+
+#define SIMD 16
+#define K_CHUNK 32 // u3 values per 3-uint granule
+#define GRANULE_UINTS 3
+#define CHUNKS_K (K_SIZE / K_CHUNK)
+#define W_GROUPS_K (K_SIZE / WEI_GROUP_SIZE)
+#define CHUNK (SIMD * K_CHUNK)
+#define NCHUNK (K_SIZE / CHUNK)
+#if (K_SIZE % CHUNK) != 0 || (WEI_GROUP_SIZE % K_CHUNK) != 0 || (N_SIZE % (SGN * NB)) != 0
+# error "moe_3gemm_int3.cl - invalid GEMV configuration"
+#endif
+#if GEMV_DOWN
+# define MATS 1
+#else
+# define MATS 2
+#endif
+#if SHARED_EXPERT
+# define EXPERTS_PER_TOKEN (MAX_TOPK + 1)
+#else
+# define EXPERTS_PER_TOKEN MAX_TOPK
+#endif
+
+// Eight consecutive u3 values (the low 24 bits of f; higher bits are ignored)
+// spread into the eight nibbles of an int: into 12-bit halves at bits 0 and 16,
+// then 6-bit quarters at each byte, then 3-bit values at each nibble. Each step
+// keeps the low part in place and takes the rest from the shifted copy (one bfn);
+// the bits the steps leave over are cleared at the end.
+inline int FUNC(u3_spread8_nib)(uint f) {
+ uint u = bitselect(f << 4, f, 0x00000FFFu);
+ u = bitselect(u << 2, u, 0x003F003Fu);
+ u = bitselect(u << 1, u, 0x07070707u);
+ return as_int(u & 0x77777777u);
+}
+
+// Dot product of one granule with its 32 activations. Values i and i + 4 of each
+// group of eight sit in the low and high half of a nibble pair; or-ing them into
+// the mantissa of 1024.0 and subtracting 1024 gives them exactly as half2.
+inline float FUNC(u3_dot32)(uint3 w, const half* a) {
+ const uint f[4] = {w.s0, (w.s0 >> 24) | (w.s1 << 8), (w.s1 >> 16) | (w.s2 << 16), w.s2 >> 8};
+ const half2 bias = (half2)((half)1024.0f);
+ float acc = 0.0f;
+ unroll_for (uint q = 0; q < 4; ++q) {
+ const uint t = as_uint(FUNC_CALL(u3_spread8_nib)(f[q]));
+ half2 s = (half2)((half)0.0f);
+ unroll_for (uint i = 0; i < 4; ++i) {
+ const half2 v = as_half2(((t >> (4 * i)) & 0x000F000Fu) | 0x64006400u) - bias;
+ s = fma(v, (half2)(a[q * 8 + i], a[q * 8 + i + 4]), s);
+ }
+ acc += (float)s.s0 + (float)s.s1;
+ }
+ return acc;
+}
+
+REQD_SUB_GROUP_SIZE(SIMD)
+__attribute__((reqd_work_group_size(SIMD, SGN, 1)))
+KERNEL(moe_int3_gemv)(
+ const __global int* expert_list, // [tokens, MAX_TOPK]
+ const __global uint* weights0, // [E, N, K] u3: down, or gate
+ const __global half* scale0, // [E, W_GROUPS_K, N]
+#if HAS_ZP
+ const __global ZP_TYPE* zp0, // [E, W_GROUPS_K, N] or [1]
+#endif
+#if !GEMV_DOWN
+ const __global uint* weights1, // up
+ const __global half* scale1,
+#if HAS_ZP
+ const __global ZP_TYPE* zp1,
+#endif
+#endif
+#if SHARED_EXPERT
+ const __global uint* shared_weights0, // [1, N, K] u3: down, or gate
+ const __global half* shared_scale0, // [1, W_GROUPS_K, N]
+#if HAS_ZP
+ const __global ZP_TYPE* shared_zp0, // [1, W_GROUPS_K, N] or [1]
+#endif
+#if !GEMV_DOWN
+ const __global uint* shared_weights1, // up
+ const __global half* shared_scale1,
+#if HAS_ZP
+ const __global ZP_TYPE* shared_zp1,
+#endif
+ const __global half* shared_gate_gate_weight, // [K]
+ __global half* shared_gate_out, // [tokens]
+#endif
+#endif
+ const __global half* x, // gate/up: [tokens, K]; down: [tokens * EXPERTS_PER_TOKEN, K]
+#if GEMV_DOWN
+ const __global half* routing_weights, // [tokens * MAX_TOPK]
+#if SHARED_EXPERT
+ const __global half* shared_gate_in, // [tokens]
+#endif
+#endif
+ __global half* y) // [tokens * EXPERTS_PER_TOKEN, N]
+{
+ const uint lane = get_sub_group_local_id();
+ const uint sg = (uint)get_local_id(1);
+ const uint blocks = N_SIZE / (SGN * NB);
+ const uint pair = (uint)get_group_id(2) / blocks;
+ const uint block = (uint)get_group_id(2) % blocks;
+ const uint n0 = (block * SGN + sg) * NB;
+ const uint token = pair / EXPERTS_PER_TOKEN;
+ const uint slot = pair % EXPERTS_PER_TOKEN;
+#if SHARED_EXPERT
+ const bool is_shared = slot == MAX_TOPK;
+#else
+ const bool is_shared = false;
+#endif
+ uint expert = 0;
+ if (!is_shared)
+ expert = (uint)expert_list[token * MAX_TOPK + slot];
+#if GEMV_DOWN
+ const __global half* xr = x + (size_t)pair * K_SIZE;
+#else
+ const __global half* xr = x + (size_t)token * K_SIZE;
+#endif
+
+ const __global uint* wm[MATS] = {weights0
+#if !GEMV_DOWN
+ , weights1
+#endif
+ };
+ const __global half* sm[MATS] = {scale0
+#if !GEMV_DOWN
+ , scale1
+#endif
+ };
+#if HAS_ZP
+ const __global ZP_TYPE* zm[MATS] = {zp0
+#if !GEMV_DOWN
+ , zp1
+#endif
+ };
+#endif
+#if SHARED_EXPERT
+ if (is_shared) {
+ wm[0] = shared_weights0;
+ sm[0] = shared_scale0;
+#if HAS_ZP
+ zm[0] = shared_zp0;
+#endif
+#if !GEMV_DOWN
+ wm[1] = shared_weights1;
+ sm[1] = shared_scale1;
+#if HAS_ZP
+ zm[1] = shared_zp1;
+#endif
+#endif
+ }
+#if !GEMV_DOWN
+ // One subgroup per token computes the shared expert's routing weight
+ if (is_shared && block == 0 && sg == 0) {
+ float g = 0.0f;
+ for (uint k = lane * 8; k < K_SIZE; k += SIMD * 8) {
+ const half8 xv = vload8(0, xr + k);
+ const half8 wv = vload8(0, shared_gate_gate_weight + k);
+ unroll_for (uint t = 0; t < 8; ++t)
+ g = fma((float)xv[t], (float)wv[t], g);
+ }
+ g = sub_group_reduce_add(g);
+ if (lane == 0)
+ shared_gate_out[token] = (half)(1.0f / (1.0f + exp(-g)));
+ }
+#endif
+#endif
+
+ float acc[MATS][NB];
+ unroll_for (uint m = 0; m < MATS; ++m)
+ unroll_for (uint j = 0; j < NB; ++j)
+ acc[m][j] = 0.0f;
+
+ unroll_for (uint c = 0; c < NCHUNK; ++c) {
+ const uint gi = c * SIMD + lane;
+ const uint wg = gi * K_CHUNK / WEI_GROUP_SIZE;
+ half a[K_CHUNK];
+ unroll_for (uint j = 0; j < K_CHUNK; j += 8) {
+ const half8 v = vload8(0, xr + gi * K_CHUNK + j);
+ unroll_for (uint t = 0; t < 8; ++t)
+ a[j + t] = v[t];
+ }
+#if HAS_ZP
+ // Activation sum of the granule, for the zero point
+ float asum = 0.0f;
+ unroll_for (uint j = 0; j < K_CHUNK; ++j)
+ asum += (float)a[j];
+#endif
+ unroll_for (uint m = 0; m < MATS; ++m) {
+ unroll_for (uint j = 0; j < NB; ++j) {
+ const uint n = n0 + j;
+ const uint3 w = vload3(gi, wm[m] + ((size_t)expert * N_SIZE + n) * CHUNKS_K * GRANULE_UINTS);
+ float d = FUNC_CALL(u3_dot32)(w, a);
+ const size_t sidx = ((size_t)expert * W_GROUPS_K + wg) * N_SIZE + n;
+#if ZP_SCALAR
+ d -= (float)zm[m][0] * asum;
+#elif HAS_ZP
+ d -= (float)zm[m][sidx] * asum;
+#endif
+ acc[m][j] = fma(d, (float)sm[m][sidx], acc[m][j]);
+ }
+ }
+ }
+
+#if GEMV_DOWN
+ float routing_weight;
+#if SHARED_EXPERT
+ if (is_shared)
+ routing_weight = (float)shared_gate_in[token];
+ else
+#endif
+ routing_weight = (float)routing_weights[token * MAX_TOPK + slot];
+#endif
+ unroll_for (uint j = 0; j < NB; ++j) {
+#if GEMV_DOWN
+ const float out = sub_group_reduce_add(acc[0][j]) * routing_weight;
+#else
+ const float gate = sub_group_reduce_add(acc[0][j]);
+ const float out = MOE_GATE_ACT(gate) * sub_group_reduce_add(acc[1][j]);
+#endif
+ if (lane == 0)
+ y[(size_t)pair * N_SIZE + n0 + j] = (half)out;
+ }
+}
+
+#undef SIMD
+#undef K_CHUNK
+#undef GRANULE_UINTS
+#undef CHUNKS_K
+#undef W_GROUPS_K
+#undef CHUNK
+#undef NCHUNK
+#undef MATS
+#undef EXPERTS_PER_TOKEN
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
index cb2b59b488e..d37a45c950a 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_3gemm_swiglu_mlp.cl
@@ -41,28 +41,7 @@
#define EXPERTS_PER_TOKEN MAX_TOPK
#endif
-// Gate activation: SwiGLU (Swish, default), GeGLU-Tanh, or GeGLU-ERF.
-// GATE_ACT_GELU_ERF takes precedence over GATE_ACT_GELU_TANH when both are set.
-#ifdef GATE_ACT_GELU_ERF
-// ERF Gelu: 0.5 * x * (1 + erf(x / sqrt(2))); A&S 7.1.26 fast erf approximation
-inline float moe_mlp_fast_erf(float x) {
- const float p = 0.3275911f;
- const float a1 = 0.254829592f;
- const float a2 = -0.284496736f;
- const float a3 = 1.421413741f;
- const float a4 = -1.453152027f;
- const float a5 = 1.061405429f;
- float z = fabs(x);
- float t = 1.0f / (1.0f + p * z);
- float y = 1.0f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-(z * z));
- return (x >= 0.0f) ? y : -y;
-}
-# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + moe_mlp_fast_erf((x) * 0.7071067811865475f)))
-#elif defined(GATE_ACT_GELU_TANH)
-# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + (tanh(0.79788458347320556640625f * (x) * (1.0f + 0.044715f * (x) * (x))))))
-#else
-# define MOE_GATE_ACT(x) ((x) / (1.0f + exp(-(x))))
-#endif
+#include "moe_gate_activation.cl"
// HAS_ZP: 1 = asymmetric quantization (subtract zero point), 0 = symmetric (no zero point)
#if HAS_ZP
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gate_activation.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gate_activation.cl
new file mode 100644
index 00000000000..0f3f58b9d55
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_gate_activation.cl
@@ -0,0 +1,26 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Gate activation of the MoE expert MLPs, MOE_GATE_ACT(x) on a float: SwiGLU (Swish, default), GeGLU-Tanh,
+// or GeGLU-ERF. GATE_ACT_GELU_ERF takes precedence over GATE_ACT_GELU_TANH when both are set.
+#ifdef GATE_ACT_GELU_ERF
+// ERF Gelu: 0.5 * x * (1 + erf(x / sqrt(2))); A&S 7.1.26 fast erf approximation
+inline float FUNC(moe_mlp_fast_erf)(float x) {
+ const float p = 0.3275911f;
+ const float a1 = 0.254829592f;
+ const float a2 = -0.284496736f;
+ const float a3 = 1.421413741f;
+ const float a4 = -1.453152027f;
+ const float a5 = 1.061405429f;
+ float z = fabs(x);
+ float t = 1.0f / (1.0f + p * z);
+ float y = 1.0f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-(z * z));
+ return (x >= 0.0f) ? y : -y;
+}
+# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + FUNC_CALL(moe_mlp_fast_erf)((x) * 0.7071067811865475f)))
+#elif defined(GATE_ACT_GELU_TANH)
+# define MOE_GATE_ACT(x) (0.5f * (x) * (1.0f + (tanh(0.79788458347320556640625f * (x) * (1.0f + 0.044715f * (x) * (x))))))
+#else
+# define MOE_GATE_ACT(x) ((x) / (1.0f + exp(-(x))))
+#endif
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake
index e738d3dfa5e..0b75822ad1b 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sources.cmake
@@ -38,6 +38,8 @@ set(GPU_OCL_V2_IMPL_SOURCES
${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_base.hpp
${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_gen_micro.cpp
${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_gen_micro.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_int3_gemv.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_int3_gemv.hpp
${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_swiglu_opt.cpp
${CMAKE_CURRENT_LIST_DIR}/moe/moe_3gemm_swiglu_opt.hpp
${CMAKE_CURRENT_LIST_DIR}/moe/moe_gather.cpp
@@ -125,8 +127,10 @@ set(GPU_OCL_V2_KERNEL_SOURCES
${CMAKE_CURRENT_LIST_DIR}/lora_horizontal_fused.cl
${CMAKE_CURRENT_LIST_DIR}/lora_opt.cl
${CMAKE_CURRENT_LIST_DIR}/lora_ref.cl
+ ${CMAKE_CURRENT_LIST_DIR}/moe_3gemm_int3.cl
${CMAKE_CURRENT_LIST_DIR}/moe_3gemm_swiglu_fuse.cl
${CMAKE_CURRENT_LIST_DIR}/moe_3gemm_swiglu_mlp.cl
+ ${CMAKE_CURRENT_LIST_DIR}/moe_gate_activation.cl
${CMAKE_CURRENT_LIST_DIR}/moe_gather_ref.cl
${CMAKE_CURRENT_LIST_DIR}/moe_gemm.cl
${CMAKE_CURRENT_LIST_DIR}/moe_mask_gen.cl
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 94dfdd94bf3..634bc4f2ce6 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
@@ -258,7 +258,9 @@ protected:
abs_threshold = 1e-3;
rel_threshold = 0.025;
const ov::test::MoePatternParams moe_params{{-1, -1, 256}, 4, 8, 512};
- init_input_shapes({{moe_params.data_shape, {{1, 40, 256}}}});
+ // Prefill, then decode steps on the batched GEMV, which falls back to the per-expert loop when the LRU holds
+ // fewer experts than top_k
+ init_input_shapes({{moe_params.data_shape, {{1, 40, 256}, {1, 1, 256}, {1, 4, 256}}}});
function = ov::test::initMoE3GeMMSubgraph(moe_params,
ov::element::f16,
wp,
@@ -314,10 +316,11 @@ TEST_P(MoECompressedOffloadTest, Inference) {
run();
}
+// OFFLOAD_RATIO 50 keeps 4 of the 8 experts resident (= top_k), 75 keeps 2, so every step falls back.
// A scalar zero point is supported for u3 weights only. Per-group u3 zero points are not supported (see skip_tests_config.cpp).
INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload_u3,
MoECompressedOffloadTest,
- ::testing::Combine(::testing::Values(size_t{50}),
+ ::testing::Combine(::testing::Values(size_t{50}, size_t{75}),
::testing::Values(ov::element::u3),
::testing::Values(ov::test::utils::DecompressionType::full,
ov::test::utils::DecompressionType::scalar,
@@ -326,7 +329,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload_u3,
INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload,
MoECompressedOffloadTest,
- ::testing::Combine(::testing::Values(size_t{50}),
+ ::testing::Combine(::testing::Values(size_t{50}, size_t{75}),
::testing::Values(ov::element::u8, ov::element::u4),
::testing::Values(ov::test::utils::DecompressionType::full, ov::test::utils::DecompressionType::empty)),
MoECompressedOffloadTest::getTestCaseName);
@@ -456,7 +459,9 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion,
::testing::Values(true)), // use_weight_decompression
MoECompressedFusionTest::getTestCaseName);
-// u3 has no batched GEMV kernel: decode (<= 32 tokens) and prefill both run OneDNN grouped GEMM.
+// hidden_size 256 is too short for the u3 batched GEMV, so decode falls back to the grouped GEMM there;
+// hidden_size 2048 runs the batched GEMV for decode (up to GPU_MOE_BATCHED_GEMV_THRESHOLD tokens, by default 2 to 16
+// depending on the GPU).
// Scalar zp is the NNCF int3 layout (symmetric u3 with zp = 4 for all experts).
const std::vector<MoeTestShapeParams> moe_params_smoke_u3 = {
{
@@ -466,10 +471,10 @@ const std::vector<MoeTestShapeParams> moe_params_smoke_u3 = {
512 // intermediate_size
},
{
- {{-1, -1, 2048}, {{1, 4, 2048}, {1, 1, 2048}}}, // prefill + decode
- 4, // topk
- 8, // number_of_experts
- 512 // intermediate_size
+ {{-1, -1, 2048}, {{1, 40, 2048}, {1, 1, 2048}, {1, 4, 2048}}}, // prefill + decode
+ 4, // topk
+ 8, // number_of_experts
+ 512 // intermediate_size
},
};
@@ -611,6 +616,28 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmGeluCompressed,
::testing::Values(true)), // use_weight_decompression
MoECompressedFusionTest::getTestCaseName);
+// Gelu gate on u3: applied by the batched GEMV (decode) and by OneDNN (prefill).
+INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmGeluCompressed_u3,
+ MoECompressedFusionTest,
+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke_u3),
+ ::testing::Values(MoePatternType::GEMM3),
+ ::testing::Values(MoERoutingType::SOFTMAX),
+ ::testing::Values(ov::element::u3), // weights_precision
+ ::testing::Values(ov::element::f16), // decompression_precision
+ ::testing::Values(ov::element::f16), // scale_precision
+ ::testing::Values(ov::test::utils::DecompressionType::full),
+ ::testing::Values(ov::test::utils::DecompressionType::full,
+ ov::test::utils::DecompressionType::scalar),
+ ::testing::Values(true), // reshape_on_decompression
+ ::testing::Values(128),
+ ::testing::Values(size_t{0}), // gate_idx unused for GEMM3
+ ::testing::Values(false), // force_gather_matmul
+ ::testing::Values(MoEActivationType::GELU, MoEActivationType::GELU_ERF),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false), // use_layernorm_multiply
+ ::testing::Values(true)), // use_weight_decompression
+ MoECompressedFusionTest::getTestCaseName);
+
// Uncompressed (FP16) experts: dense Tile/MatMul ops run natively
// (would otherwise fail with "MOE ... is not supported").
INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmUncompressed,
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
index 7975dc90e00..69502801a9d 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp
@@ -19,6 +19,7 @@
#include "../../common/random_generator.hpp"
#include "../test_utils/test_utils.h"
+#include "moe_3gemm_fused_inst.h"
#include "moe_3gemm_test_data.h"
#include "common_test_utils/common_utils.hpp"
@@ -1783,3 +1784,208 @@ TEST(moe_3gemm_expert_mask, shape_predictor_overflow_regression) {
total += static_cast<int>(result.batch[e].size());
ASSERT_EQ(total, actual_tokens * top_k);
}
+
+// u3 experts: decode on the moe_3gemm_int3 batched GEMV, prefill on OneDNN grouped GEMM
+struct Moe3GemmU3TestParams {
+ size_t seq_len;
+ size_t hidden_size;
+ size_t inter_size;
+ size_t num_experts;
+ size_t top_k;
+ size_t group_size;
+ size_t batched_gemv_threshold = 32;
+ bool has_zp = true;
+ bool is_caching_test = false;
+ bool has_shared_expert = false;
+};
+
+class moe_3gemm_compressed_gpu_u3 : public ::testing::TestWithParam<Moe3GemmU3TestParams> {};
+
+// LSB-first bit stream: value i occupies bits [3i, 3i + 3)
+static std::vector<uint8_t> pack_u3(const std::vector<uint8_t>& values) {
+ std::vector<uint8_t> packed((values.size() * 3 + 7) / 8, 0);
+ for (size_t i = 0; i < values.size(); ++i) {
+ const size_t bit = 3 * i;
+ const uint32_t v = static_cast<uint32_t>(values[i] & 7u) << (bit % 8);
+ packed[bit / 8] |= static_cast<uint8_t>(v);
+ if (v > 0xFF) {
+ packed[bit / 8 + 1] |= static_cast<uint8_t>(v >> 8);
+ }
+ }
+ return packed;
+}
+
+TEST_P(moe_3gemm_compressed_gpu_u3, moe_accuracy_test_u3) {
+ const auto& param = GetParam();
+ auto& engine = get_test_engine();
+ if (!engine.get_device_info().supports_immad) {
+ GTEST_SKIP() << "No immad support";
+ }
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ Moe3GemmConfig config;
+ config.batch_size = 1;
+ config.seq_len = param.seq_len;
+ config.hidden_size = param.hidden_size;
+ config.inter_size = param.inter_size;
+ config.num_experts = param.num_experts;
+ config.top_k = param.top_k;
+ config.group_size = param.group_size;
+ config.is_u4 = true; // quantizes to [0, 7], the u3 range
+ config.has_shared_expert = param.has_shared_expert;
+ Moe3GemmReference ref(config, rg);
+
+ auto hidden_states = rg.generate_random_1d<ov::float16>(config.seq_len * config.hidden_size, -1.0f, 1.0f, 1000);
+ auto routing_weights = rg.generate_random_1d<ov::float16>(config.seq_len * config.num_experts, 0.0f, 1.0f, 1000);
+
+ const auto hidden = static_cast<int64_t>(config.hidden_size);
+ const auto gs = static_cast<int64_t>(config.group_size);
+ topology topology;
+ std::vector<input_info> moe_inputs{input_info("hidden_states"), input_info("router", 0), input_info("router", 1)};
+ // Gate, up and down of `experts` experts, quantized to u3 and added to the topology. Returns their dequantized
+ // values for the reference.
+ auto add_experts = [&](const std::string& prefix, size_t experts) {
+ const auto E = static_cast<int64_t>(experts);
+ // Weights [E, N, K] as a u3 stream; scales and zero points logically [E, N, G], physically [E, G, N]
+ auto make_weight = [&](const std::vector<uint8_t>& values, int64_t n, int64_t groups) {
+ auto mem = engine.allocate_memory({data_types::u3, format::bfyx, {E, n, gs, groups}});
+ set_values(mem, pack_u3(values));
+ return mem;
+ };
+ auto make_scale = [&](const std::vector<ov::float16>& v, int64_t n, int64_t groups) {
+ auto mem = engine.allocate_memory(layout{ov::PartialShape{E, n, groups, 1}, data_types::f16, format::byfx});
+ set_values(mem, v);
+ return mem;
+ };
+ auto make_zp = [&](const std::vector<uint8_t>& v, int64_t n, int64_t groups) {
+ if (!param.has_zp) {
+ auto one_byte_mem = engine.allocate_memory(cldnn::layout(ov::PartialShape{1}, data_types::u8, format::bfyx), false);
+ return engine.reinterpret_buffer(*one_byte_mem, cldnn::layout(ov::PartialShape{0}, data_types::dynamic, format::bfyx));
+ }
+ auto mem = engine.allocate_memory(layout{ov::PartialShape{E, n, groups, 1}, data_types::u8, format::byfx});
+ set_values(mem, v);
+ return mem;
+ };
+ std::array<std::vector<float>, 3> qdq;
+ for (size_t i = 0; i < 3; ++i) {
+ const bool down = i == 2;
+ const size_t k = down ? config.inter_size : config.hidden_size;
+ const size_t n = down ? config.hidden_size : config.inter_size;
+ const auto groups = static_cast<int64_t>(k / config.group_size);
+ auto values = rg.generate_random_1d<float>(experts * k * n, -1.0f, 1.0f, 1000);
+ for (auto& v : values) {
+ v /= i == 1 ? 11.0f : 7.0f;
+ }
+ auto [q, scale, zp] = ref.quantize(values, experts, k, n, config.group_size);
+ // Without a zero point the weights dequantize as q * scale
+ if (!param.has_zp) {
+ std::fill(zp.begin(), zp.end(), uint8_t{0});
+ }
+ qdq[i] = ref.dequantize(q, scale, zp, experts, k, n, config.group_size);
+ const std::string name = prefix + std::to_string(i);
+ topology.add(data(name + "_weight", make_weight(q, static_cast<int64_t>(n), groups)));
+ topology.add(data(name + "_scale", make_scale(scale, static_cast<int64_t>(n), groups)));
+ topology.add(data(name + "_zp", make_zp(zp, static_cast<int64_t>(n), groups)));
+ moe_inputs.insert(moe_inputs.end(), {input_info(name + "_weight"), input_info(name + "_scale"), input_info(name + "_zp")});
+ }
+ return qdq;
+ };
+ const auto w_qdq = add_experts("w", config.num_experts);
+ std::array<std::vector<float>, 3> s_qdq;
+ std::vector<float> s_gate_scalar;
+ if (param.has_shared_expert) {
+ s_qdq = add_experts("s", 1);
+ auto s_gate_scalar_f16 = rg.generate_random_1d<ov::float16>(config.hidden_size, -0.1f, 0.1f, 1000);
+ s_gate_scalar.assign(s_gate_scalar_f16.begin(), s_gate_scalar_f16.end());
+ auto mem = engine.allocate_memory({data_types::f16, format::bfyx, {1, 1, 1, hidden}});
+ set_values(mem, s_gate_scalar_f16);
+ topology.add(data("s_gate_scalar", mem));
+ moe_inputs.push_back(input_info("s_gate_scalar"));
+ }
+
+ auto hidden_states_mem = engine.allocate_memory(layout{ov::PartialShape{1, static_cast<int64_t>(config.seq_len), hidden}, data_types::f16, format::bfyx});
+ set_values(hidden_states_mem, hidden_states);
+ auto routing_weights_mem = engine.allocate_memory(
+ layout{ov::PartialShape{1, static_cast<int64_t>(config.seq_len), static_cast<int64_t>(config.num_experts)}, data_types::f16, format::bfyx});
+ set_values(routing_weights_mem, routing_weights);
+ get_test_stream().finish();
+
+ topology.add(input_layout("hidden_states", hidden_states_mem->get_layout()));
+ topology.add(input_layout("routing_weights", routing_weights_mem->get_layout()));
+
+ MoERouterFused::Config router_config;
+ router_config.num_expert = config.num_experts;
+ router_config.top_k = config.top_k;
+ topology.add(moe_router_fused("router", {input_info("routing_weights")}, router_config));
+
+ cldnn::MOECompressed::Config moe_config;
+ moe_config.hidden_size = config.hidden_size;
+ moe_config.inter_size = config.inter_size;
+ moe_config.num_expert = config.num_experts;
+ moe_config.top_k = config.top_k;
+ moe_config.group_size = config.group_size;
+ moe_config.out_type = data_types::f16;
+ moe_config.has_zp = param.has_zp;
+ moe_config.num_shared_expert = param.has_shared_expert ? 1 : 0;
+ topology.add(moe_3gemm_fused_compressed("moe", moe_inputs, moe_config));
+
+ auto net_config = get_test_default_config(engine);
+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ net_config.set_property(ov::intel_gpu::moe_batched_gemv_threshold(param.batched_gemv_threshold));
+ auto network = get_network(engine, topology, net_config, get_test_stream_ptr(), param.is_caching_test);
+ network->set_input_data("hidden_states", hidden_states_mem);
+ network->set_input_data("routing_weights", routing_weights_mem);
+ auto outputs = network->execute();
+ auto output_mem = outputs.at("moe").get_memory();
+
+ const auto moe_inst = network->get_primitive("moe");
+ const auto executed_kernels = moe_inst->get_impl()->get_kernels_dump_info(*moe_inst->get_impl_params()).get_entries();
+ // Threshold 0 selects the per-device default, which is at least 2 tokens
+ const size_t threshold = param.batched_gemv_threshold != 0 ? param.batched_gemv_threshold : 2;
+ const bool expect_gemv = param.seq_len <= threshold;
+ for (const char* kernel_name : {"moe_3gemm_int3_gemv_gate_up", "moe_3gemm_int3_gemv_down"}) {
+ ASSERT_EQ(executed_kernels.find(kernel_name) != std::string::npos, expect_gemv) << kernel_name << ", executed kernels: " << executed_kernels;
+ }
+
+ auto ref_output = ref.run_reference_softmax(hidden_states, routing_weights, w_qdq[0], w_qdq[1], w_qdq[2], s_qdq[0], s_qdq[1], s_qdq[2], s_gate_scalar);
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> output_ptr(output_mem, get_test_stream());
+ ASSERT_EQ(output_ptr.size(), ref_output.size());
+ // The batched GEMV and OneDNN compute on f16 activations and stay within ~0.2% of the output range
+ float ref_max = 0.0f;
+ for (const auto& v : ref_output) {
+ ref_max = std::max(ref_max, std::abs(static_cast<float>(v)));
+ }
+ const float tolerance = 0.005f * ref_max + 0.01f;
+ for (size_t i = 0; i < ref_output.size(); ++i) {
+ ASSERT_NEAR(static_cast<float>(output_ptr[i]), static_cast<float>(ref_output[i]), tolerance) << "i = " << i;
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ moe_3gemm_compressed_gpu_u3,
+ ::testing::Values(
+ // decode: batched GEMV, one and several tokens
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 128},
+ Moe3GemmU3TestParams{8, 512, 512, 8, 2, 128},
+ // prefill past the threshold: OneDNN grouped GEMM
+ Moe3GemmU3TestParams{4, 512, 512, 8, 2, 128, 1},
+ Moe3GemmU3TestParams{40, 512, 512, 4, 2, 128},
+ // 64- and 32-value weight groups, and per-channel scales and zero points
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 64},
+ Moe3GemmU3TestParams{4, 512, 512, 8, 2, 32},
+ Moe3GemmU3TestParams{2, 512, 512, 8, 2, 512},
+ // no zero point
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 128, 32, false},
+ Moe3GemmU3TestParams{8, 512, 512, 8, 2, 64, 32, false},
+ // default threshold (per device)
+ Moe3GemmU3TestParams{2, 512, 512, 8, 2, 128, 0},
+ // model cache; the threshold must survive the import
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 128, 32, true, true},
+ Moe3GemmU3TestParams{4, 512, 512, 8, 2, 128, 1, true, true},
+ Moe3GemmU3TestParams{40, 512, 512, 4, 2, 128, 32, true, true},
+ // u3 shared expert: an extra GEMV slot per token (decode), OneDNN (prefill)
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 128, 32, true, false, true},
+ Moe3GemmU3TestParams{8, 512, 512, 8, 2, 128, 32, true, false, true},
+ Moe3GemmU3TestParams{4, 512, 512, 8, 2, 64, 32, false, false, true},
+ Moe3GemmU3TestParams{40, 512, 512, 4, 2, 128, 32, true, false, true},
+ Moe3GemmU3TestParams{1, 512, 512, 8, 2, 128, 32, true, true, true}));