Skip to content

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

[GPU] u3 compressed weights support (#37992)

Vladislav Golubev87a0dd74f4e8
diff --git a/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
index a4622449d2c..e8926938e0c 100644
--- a/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/moe_op_fusion.cpp
@@ -32,6 +32,7 @@
#include "ov_ops/gather_matmul.hpp"
#include "ov_ops/gather_matmul_compressed.hpp"
#include "ov_ops/moe_compressed.hpp"
+#include "transformations/utils/utils.hpp"
namespace ov::pass {
@@ -158,6 +159,26 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp() {
const bool is_compressed = is_gate_compressed;
if (is_compressed) {
+ const auto is_zp_supported = [](const ov::Output<ov::Node>& zp, const ov::Output<ov::Node>& weights) {
+ // Scalar zero point is supported only for u3 weights in MoE (OneDNN grouped GEMM common zero point).
+ // Note: other compressed types usually don't have scalar zero points
+ return weights.get_element_type() == ov::element::u3 || ov::shape_size(zp.get_shape()) != 1;
+ };
+ if (!is_zp_supported(pm.at(gate_zp_m), gate_w) || !is_zp_supported(pm.at(up_zp_m), up_w) ||
+ !is_zp_supported(pm.at(down_zp_m), down_w)) {
+ return false;
+ }
+
+ const auto prepare_zero_point = [](const ov::Output<ov::Node>& zp, const ov::Output<ov::Node>& weights) {
+ // Note: OneDNN groupedMM has no u3 zero points: convert them to u8 (as for FullyConnectedCompressed)
+ if (weights.get_element_type() != ov::element::u3 || zp.get_element_type() != ov::element::u3) {
+ return zp;
+ }
+ auto result = ov::op::util::make_try_fold<v0::Convert>(zp, ov::element::u8);
+ ov::copy_runtime_info(zp.get_node_shared_ptr(), result);
+ return result->output(0);
+ };
+
// Build MOECompressed with 12 inputs: hidden, routing, topk,
// gate_w, gate_scale, gate_zp, up_w, up_scale, up_zp, down_w, down_scale, down_zp
ov::OutputVector moe_inputs = {
@@ -166,13 +187,13 @@ Convert3GatherMatmulMoeBlockToMoeOp::Convert3GatherMatmulMoeBlockToMoeOp() {
topk_indices,
gate_w,
pm.at(gate_scale_m),
- pm.at(gate_zp_m),
+ prepare_zero_point(pm.at(gate_zp_m), gate_w),
up_w,
pm.at(up_scale_m),
- pm.at(up_zp_m),
+ prepare_zero_point(pm.at(up_zp_m), up_w),
down_w,
pm.at(down_scale_m),
- pm.at(down_zp_m),
+ prepare_zero_point(pm.at(down_zp_m), down_w),
};
// Populate compressed config from weight shapes
diff --git a/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
index 115a0cbb28f..98baa07b194 100644
--- a/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
+++ b/src/common/transformations/tests/common_optimizations/convert_gather_matmuls_moe_block_to_moe_op.cpp
@@ -10,6 +10,7 @@
#include <openvino/op/clamp.hpp>
#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
+#include <openvino/op/convert.hpp>
#include <openvino/op/gelu.hpp>
#include <openvino/op/matmul.hpp>
#include <openvino/op/minimum.hpp>
@@ -25,9 +26,13 @@
#include <openvino/pass/manager.hpp>
#include <openvino/pass/serialize.hpp>
#include <openvino/pass/visualize_tree.hpp>
+#include <optional>
+#include <string>
+#include <tuple>
#include <vector>
#include "common_test_utils/ov_test_utils.hpp"
+#include "common_test_utils/subgraph_builders/weights_decompression_builders.hpp"
#include "openvino/core/node_vector.hpp"
#include "openvino/op/parameter.hpp"
#include "openvino/op/reshape.hpp"
@@ -35,6 +40,8 @@
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "ov_ops/gather_matmul.hpp"
+#include "ov_ops/gather_matmul_compressed.hpp"
+#include "ov_ops/moe_compressed.hpp"
#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"
#include "transformations/common_optimizations/moe_op_fusion.hpp"
@@ -279,10 +286,42 @@ inline std::shared_ptr<ov::Model> build_3gemm_moe_pattern_model() {
// Post-BGM model builders (3 BGMs + compact routing + ReduceSum + Reshape)
// ============================================================================
+// Compressed expert weights: wei_type weights, f16 scale [E, N, K / group_size] and zp
+struct MoeCompression {
+ static constexpr size_t group_size = 128;
+ ov::element::Type wei_type;
+ ov::test::utils::DecompressionType decompression_subtract_type;
+ ov::element::Type zp_type = ov::element::dynamic;
+};
+
+// Returns {weights} for plain experts, {weights, scale, zp} for compressed ones
+inline ov::OutputVector make_expert_weights(size_t number_of_experts,
+ size_t n,
+ size_t k,
+ const std::optional<MoeCompression>& compression) {
+ using namespace ov;
+ if (!compression) {
+ return {op::v0::Constant::create(element::f32, Shape{number_of_experts, n, k}, {1.0f})};
+ }
+ using ov::test::utils::DecompressionType;
+ const Shape scale_shape{number_of_experts, n, k / MoeCompression::group_size};
+ const auto zp_decompression = compression->decompression_subtract_type;
+ const auto zp =
+ zp_decompression == DecompressionType::empty
+ ? std::make_shared<op::v0::Constant>(element::dynamic, Shape{0})
+ : op::v0::Constant::create(compression->zp_type,
+ zp_decompression == DecompressionType::scalar ? Shape{} : scale_shape,
+ {4});
+ return {op::v0::Constant::create(compression->wei_type, Shape{number_of_experts, n, k}, {1}),
+ op::v0::Constant::create(element::f16, scale_shape, {1.0f}),
+ zp};
+}
+
inline std::shared_ptr<ov::Model> build_3gemm_bgm_model(
ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU,
bool has_batch_dim = true,
- bool restore_output_shape = false) {
+ bool restore_output_shape = false,
+ const std::optional<MoeCompression>& compression = std::nullopt) {
using namespace ov;
const size_t batch = 2;
@@ -318,18 +357,17 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_model(
auto topk_indices = router_topk->output(1); // [batch*seq, topk]
auto chosen_experts = router_topk->output(0); // [batch*seq, topk] (values used as routing weights)
- // Gate weights
- auto gate_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
- // Up weights
- auto up_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
- // Down weights
- auto down_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});
+ auto make_bgm = [&](const Output<Node>& a, size_t n, size_t k) -> std::shared_ptr<Node> {
+ const auto w = make_expert_weights(number_of_experts, n, k, compression);
+ if (!compression) {
+ return std::make_shared<GatherMatmul>(a, w[0], topk_indices);
+ }
+ auto bias = std::make_shared<op::v0::Constant>(element::dynamic, Shape{0});
+ return std::make_shared<ov::op::internal::GatherMatmulCompressed>(a, w[0], topk_indices, bias, w[1], w[2]);
+ };
// 3 BGMs
- auto bgm_gate = std::make_shared<GatherMatmul>(unsqueeze, gate_w, topk_indices);
+ auto bgm_gate = make_bgm(unsqueeze, intermediate_size, hidden_size);
std::shared_ptr<ov::Node> gate_act;
if (activation_type == ov::op::internal::MOE::Activation_type::GEGLU_TANH) {
gate_act = std::make_shared<op::v7::Gelu>(bgm_gate, ov::op::GeluApproximationMode::TANH);
@@ -338,9 +376,9 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_model(
} else {
gate_act = std::make_shared<op::v4::Swish>(bgm_gate);
}
- auto bgm_up = std::make_shared<GatherMatmul>(unsqueeze, up_w, topk_indices);
+ auto bgm_up = make_bgm(unsqueeze, intermediate_size, hidden_size);
auto swiglu = std::make_shared<op::v1::Multiply>(gate_act, bgm_up);
- auto bgm_down = std::make_shared<GatherMatmul>(swiglu, down_w, topk_indices);
+ auto bgm_down = make_bgm(swiglu, hidden_size, intermediate_size);
// Compact routing: chosen_experts → Transpose({1,0}) → Unsqueeze(-1)
auto router_transpose = std::make_shared<op::v1::Transpose>(
@@ -371,7 +409,8 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_model(
inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model(
ov::op::internal::MOE::Activation_type activation_type = ov::op::internal::MOE::Activation_type::SWIGLU,
bool has_batch_dim = true,
- bool restore_output_shape = false) {
+ bool restore_output_shape = false,
+ const std::optional<MoeCompression>& compression = std::nullopt) {
using namespace ov;
const size_t batch = 2;
@@ -404,30 +443,47 @@ inline std::shared_ptr<ov::Model> build_3gemm_bgm_to_moe_reference_model(
auto topk_indices = router_topk->output(1);
auto routing = router_topk->output(0);
- // Weights
- auto gate_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
- auto up_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, intermediate_size, hidden_size}, {1.0f});
- auto down_w =
- op::v0::Constant::create(element::f32, Shape{number_of_experts, hidden_size, intermediate_size}, {1.0f});
-
// MOE op with compact routing
auto hidden_states = input->output(0);
- ov::OutputVector moe_inputs = {hidden_states, routing, topk_indices, gate_w, up_w, down_w};
- ov::op::internal::MOE::Config config;
- config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
- config.activation_type = activation_type;
- auto moe = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);
+ ov::OutputVector moe_inputs = {hidden_states, routing, topk_indices};
+ for (auto [n, k] : {std::pair{intermediate_size, hidden_size},
+ std::pair{intermediate_size, hidden_size},
+ std::pair{hidden_size, intermediate_size}}) {
+ const auto w = make_expert_weights(number_of_experts, n, k, compression);
+ moe_inputs.insert(moe_inputs.end(), w.begin(), w.end());
+ }
+
+ ov::Output<ov::Node> output;
+ if (compression) {
+ using ov::op::internal::MOECompressed;
+ MOECompressed::Config config{
+ {ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, 0.0f, 1.0f, 0, activation_type},
+ hidden_size,
+ intermediate_size,
+ number_of_experts,
+ 0, // num_shared_expert
+ topk,
+ MoeCompression::group_size,
+ has_batch_dim,
+ moe_inputs[5].get_element_type() != element::dynamic, // has_zp
+ element::f16,
+ };
+ auto moe = std::make_shared<MOECompressed>(moe_inputs, config);
+ output = std::make_shared<op::v0::Convert>(moe, input->get_element_type());
+ } else {
+ ov::op::internal::MOE::Config config;
+ config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;
+ config.activation_type = activation_type;
+ output = std::make_shared<ov::op::internal::MOE>(moe_inputs, config);
+ }
- ov::Output<ov::Node> output = moe;
if (!has_batch_dim || restore_output_shape) {
const std::vector<int64_t> output_shape =
restore_output_shape
? std::vector<int64_t>{-1, static_cast<int64_t>(batch), static_cast<int64_t>(hidden_size)}
: std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)};
output = std::make_shared<op::v1::Reshape>(
- moe,
+ output,
op::v0::Constant::create(element::i64, Shape{output_shape.size()}, output_shape),
true);
}
@@ -837,3 +893,105 @@ TEST_F(TransformationTestsF, Convert2GatherMatmulMoeBlockToMoeOp_restores_output
manager.register_pass<ov::pass::Convert2GatherMatmulMoeBlockToMoeOp>();
model_ref = build_2gemm_bgm_to_moe_reference_model(true, true);
}
+
+// Per-group u3 zp is converted to u8
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_compressed_u3_zp_to_u8) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ using ov::test::utils::DecompressionType;
+ model =
+ build_3gemm_bgm_model(AT::SWIGLU, true, false, {{ov::element::u3, DecompressionType::full, ov::element::u3}});
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::SWIGLU,
+ true,
+ false,
+ {{ov::element::u3, DecompressionType::full, ov::element::u8}});
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+}
+
+// Symmetric u3: the absent zp stays absent
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_compressed_u3_no_zp) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ const MoeCompression compression{ov::element::u3, ov::test::utils::DecompressionType::empty};
+ model = build_3gemm_bgm_model(AT::SWIGLU, true, false, compression);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::SWIGLU, true, false, compression);
+}
+
+// Sub-byte zp of other types keeps its precision
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_compressed_u4_zp_unchanged) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ const MoeCompression compression{ov::element::u4, ov::test::utils::DecompressionType::full, ov::element::u4};
+ model = build_3gemm_bgm_model(AT::SWIGLU, true, false, compression);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::SWIGLU, true, false, compression);
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+}
+
+// Tuple parameters: shared weight/ZP precision, ZP shape, and expected fusion result.
+using MoeZeroPointTransformCase = std::tuple<ov::element::Type, ov::test::utils::DecompressionType, bool>;
+
+class Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest : public TransformationTestsF,
+ public testing::WithParamInterface<MoeZeroPointTransformCase> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<MoeZeroPointTransformCase>& info) {
+ const auto& [precision, zp_shape, expect_fusion] = info.param;
+ return precision.get_type_name() +
+ (zp_shape == ov::test::utils::DecompressionType::scalar ? "_scalar_zp" : "_per_group_zp") +
+ (expect_fusion ? "_fused" : "_not_fused");
+ }
+
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ const auto& [precision, zp_shape, expect_fusion] = GetParam();
+ const MoeCompression input_compression{precision, zp_shape, precision};
+
+ model = build_3gemm_bgm_model(ov::op::internal::MOE::Activation_type::SWIGLU, true, false, input_compression);
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ if (expect_fusion) {
+ const auto output_zp_type = precision == ov::element::u3 ? ov::element::u8 : precision;
+ const MoeCompression output_compression{precision, zp_shape, output_zp_type};
+ model_ref = build_3gemm_bgm_to_moe_reference_model(ov::op::internal::MOE::Activation_type::SWIGLU,
+ true,
+ false,
+ output_compression);
+ }
+ }
+};
+
+TEST_P(Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest, ScalarAndPerGroupZp) {}
+
+INSTANTIATE_TEST_SUITE_P(ScalarZpFused,
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest,
+ testing::Combine(testing::Values(ov::element::u3),
+ testing::Values(ov::test::utils::DecompressionType::scalar),
+ testing::Values(true)),
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ ScalarZpNotFused,
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest,
+ testing::Combine(testing::Values(ov::element::u8, ov::element::u4, ov::element::i8, ov::element::i4),
+ testing::Values(ov::test::utils::DecompressionType::scalar),
+ testing::Values(false)),
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(PerGroupZp,
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest,
+ testing::Combine(testing::Values(ov::element::u8, ov::element::i8),
+ testing::Values(ov::test::utils::DecompressionType::full),
+ testing::Values(true)),
+ Convert3GatherMatmulMoeBlockToMoeOpZeroPointTest::getTestCaseName);
+
+TEST_F(TransformationTestsF, Convert3GatherMatmulMoeBlockToMoeOp_compressed_u3_weights_i8_scalar_zp) {
+ using AT = ov::op::internal::MOE::Activation_type;
+ using ov::test::utils::DecompressionType;
+ model =
+ build_3gemm_bgm_model(AT::SWIGLU, true, false, {{ov::element::u3, DecompressionType::scalar, ov::element::i8}});
+ manager.register_pass<ov::pass::Convert3GatherMatmulMoeBlockToMoeOp>();
+ model_ref = build_3gemm_bgm_to_moe_reference_model(AT::SWIGLU,
+ true,
+ false,
+ {{ov::element::u3, DecompressionType::scalar, ov::element::i8}});
+ comparator.enable(FunctionsComparator::CmpValues::CONST_VALUES);
+}
diff --git a/src/core/src/op/moe.cpp b/src/core/src/op/moe.cpp
index 47e5ccafc3c..c70c268b78b 100644
--- a/src/core/src/op/moe.cpp
+++ b/src/core/src/op/moe.cpp
@@ -54,8 +54,9 @@ void MOE::validate_and_infer_types() {
for (size_t i = 4; i < base_inputs_count; i++) {
const auto& ps = get_input_partial_shape(i);
NODE_VALIDATION_CHECK(this, ps.is_static(), "Weights must have static shape.");
- // Note: dynamic element type means empty zero point input
- if (get_input_element_type(i) != ov::element::dynamic) {
+ // Note: dynamic element type means empty zero point input,
+ // a single-element input is a zero point shared by all experts (e.g. u3 weights scalar zp)
+ if (get_input_element_type(i) != ov::element::dynamic && ov::shape_size(ps.to_shape()) != 1) {
NODE_VALIDATION_CHECK(this,
num_experts == get_input_shape(i)[0],
"All weight inputs must have the same first dimension (num_experts).");
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
index 5634fafbaa0..e784d7cc297 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
@@ -251,6 +251,8 @@ kernel_selector::data_type to_data_type(data_types dt) {
switch (dt) {
case cldnn::data_types::u2:
return kernel_selector::data_type::UINT2;
+ case cldnn::data_types::u3:
+ return kernel_selector::data_type::UINT3;
case cldnn::data_types::i4:
return kernel_selector::data_type::INT4;
case cldnn::data_types::u4:
@@ -292,6 +294,8 @@ data_types from_data_type(kernel_selector::data_type dt) {
switch (dt) {
case kernel_selector::data_type::UINT2:
return cldnn::data_types::u2;
+ case kernel_selector::data_type::UINT3:
+ return cldnn::data_types::u3;
case kernel_selector::data_type::INT4:
return cldnn::data_types::i4;
case kernel_selector::data_type::UINT4:
@@ -333,6 +337,8 @@ kernel_selector::weights_type to_weights_type(data_types dt) {
switch (dt) {
case cldnn::data_types::u2:
return kernel_selector::weights_type::UINT2;
+ case cldnn::data_types::u3:
+ return kernel_selector::weights_type::UINT3;
case cldnn::data_types::u4:
return kernel_selector::weights_type::UINT4;
case cldnn::data_types::i4:
@@ -366,6 +372,8 @@ data_types from_weights_type(kernel_selector::weights_type dt) {
switch (dt) {
case kernel_selector::weights_type::UINT2:
return data_types::u2;
+ case kernel_selector::weights_type::UINT3:
+ return data_types::u3;
case kernel_selector::weights_type::INT4:
return data_types::i4;
case kernel_selector::weights_type::UINT4:
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_gen_micro.cpp
index fb06ffe97b3..33827e90439 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gather_matmul_gen_micro.cpp
@@ -418,7 +418,7 @@ KernelData GatherMatmulMicroGenerator::get_kernel_data(const kernel_impl_params&
shim_options.useTileOps = true;
shim_options.decorator = "gm";
- kd.code->jit += generateShim(bgm_gemm, micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(bgm_gemm, micro::HostLanguage::OpenCL_C, shim_options);
if (bgm_gemm.grfMin > 128) {
kd.code->options += " -cl-intel-256-GRF-per-thread";
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_batched_gemm_gen.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_batched_gemm_gen.cpp
index 3737cbceee5..f44edb3d4dd 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_batched_gemm_gen.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/gather_matmul/gathermatmul_batched_gemm_gen.cpp
@@ -274,7 +274,7 @@ KernelData GatherMatmulBatchedGemmGenerator::get_kernel_data(const kernel_impl_p
shim_options.useTileOps = true;
shim_options.decorator = "gm";
- kd.code->jit += generateShim(bgm_gemm, micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(bgm_gemm, micro::HostLanguage::OpenCL_C, shim_options);
if (bgm_gemm.grfMin > 128) {
kd.code->options += " -cl-intel-256-GRF-per-thread";
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
index 13930a11b7c..5ef4d18f4a9 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_gen_micro.cpp
@@ -491,7 +491,7 @@ KernelData MoE3GemmMicroGenerator::get_kernel_data(const kernel_impl_params& par
shim_options.useTileOps = true;
shim_options.decorator = "moe";
- kd.code->jit += generateShim(moe_gemm, micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(moe_gemm, micro::HostLanguage::OpenCL_C, shim_options);
if (moe_gemm.grfMin > 128) {
kd.code->options += " -cl-intel-256-GRF-per-thread";
}
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 ef9efe223d6..4037dfdddec 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
@@ -19,6 +19,7 @@ using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;
#ifdef ENABLE_ONEDNN_FOR_GPU
# include <algorithm>
+# include <array>
# include <chrono>
# include <cstdint>
# include <fstream>
@@ -38,6 +39,7 @@ using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;
# include "../utils/kernel_generator.hpp"
# include "common_utils/jitter.hpp"
# include "impls/onednn/grouped_matmul_helper.hpp"
+# include "impls/onednn/utils.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"
@@ -56,30 +58,10 @@ 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::convert_data_type;
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:
- 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("[clDNN] Unsupported conversion from cldnn to onednn type");
- }
-}
-
inline dnnl::algorithm moe_activation_to_dnnl_algo(ov::op::internal::MOE::Activation_type act) {
switch (act) {
case ov::op::internal::MOE::Activation_type::GEGLU_TANH:
@@ -92,6 +74,14 @@ 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
+ 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
+};
+
class MoE3GemmSwigluGather : public KernelGenerator {
public:
MoE3GemmSwigluGather() : KernelGenerator("moe_3gemm_swiglu_fuse", "gather") {}
@@ -123,9 +113,15 @@ protected:
class MoE3GemmSwigluPrefillMaskGen : public KernelGenerator {
public:
- MoE3GemmSwigluPrefillMaskGen() : KernelGenerator("moe_mask_gen", "prefill_mask_gen") {}
+ // use_grouped_gemm: experts_info_start_idx holds cumulative end-offsets for all experts (OneDNN grouped
+ // memory descriptor), and an extra row_lut output (inverse of tokens_per_expert) is written.
+ explicit MoE3GemmSwigluPrefillMaskGen(bool use_grouped_gemm = false)
+ : KernelGenerator("moe_mask_gen", use_grouped_gemm ? "grouped_mask_gen" : "prefill_mask_gen"),
+ m_use_grouped_gemm(use_grouped_gemm) {}
protected:
+ bool m_use_grouped_gemm;
+
[[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>();
@@ -135,6 +131,11 @@ protected:
jit.make("OUTPUT2_TYPE", "int"); // experts_id
jit.make("OUTPUT3_TYPE", "int"); // tokens_lens_per_expert
jit.make("OUTPUT4_TYPE", "int"); // num_actual_used_experts
+ if (m_use_grouped_gemm) {
+ jit.make("ONEDNN_GROUPED_GEMM_USED", 1);
+ jit.make("ROW_LUT_ENABLE", 1);
+ jit.make("OUTPUT5_TYPE", "int"); // row_lut
+ }
const auto& config = desc->_config;
jit.make("NUM_EXPERTS_PER_TOKEN", config.top_k);
@@ -594,6 +595,23 @@ static int64_t get_bytes_count(int64_t element_count, const cldnn::layout& layou
return static_cast<int64_t>(ov::element::Type(layout.data_type).bitwidth()) * element_count / 8;
}
+// A zero point shared by all the experts is not sliced per expert
+static dnnl::memory convert_zp2dnnl(const memory::ptr& zp, int64_t groups, int64_t oc, int64_t expert_slot) {
+ if (zp->get_layout().count() == 1) {
+ return convert2dnnl(zp, {1}, dnnl::memory::format_tag::a);
+ }
+ return convert2dnnl(zp, {groups, oc}, dnnl::memory::format_tag::ab, expert_slot * get_bytes_count(groups * oc, zp->get_layout()));
+}
+
+// A single zero point shared by all the experts, as a OneDNN host scalar
+static dnnl::memory make_host_scalar_zp(const memory::ptr& zp_mem, cldnn::stream& stream) {
+ const auto dt = zp_mem->get_layout().data_type;
+ OPENVINO_ASSERT(one_of(dt, {data_types::u8, data_types::i8}), "moe_3gemm: unsupported host scalar zero point type ", dt);
+ cldnn::mem_lock<uint8_t, mem_lock_type::read> lock(zp_mem, stream);
+ const auto md = dnnl::memory::desc::host_scalar(convert_data_type(dt));
+ return dt == data_types::u8 ? dnnl::memory(md, lock[0]) : dnnl::memory(md, static_cast<int8_t>(lock[0]));
+}
+
class moe_3gemm_swiglu_opt_impl : public PrimitiveImplOCL {
public:
DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoE3GemmSwigluImpl)
@@ -621,6 +639,10 @@ 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.
+ Stage::Ptr grouped_gemm_mask_gen = make_stage<MoE3GemmSwigluPrefillMaskGen>(/*use_grouped_gemm=*/true);
struct dnnl_weights {
dnnl::memory weight;
@@ -850,22 +872,20 @@ public:
auto& dnnl_weights = _dnnl_weights[expert_no];
auto lru_expert_no = static_cast<int64_t>(_weight_provider->acquire_one(static_cast<uint32_t>(expert_no), stream));
auto& params = instance._weights;
-
-# define CONVERT_DNNL_OTD(name, i) \
- int64_t wei_offset##i = lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, params.name##_w->get_layout()); \
- int64_t scale_offset##i = \
- lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, params.name##_s->get_layout()); \
- int64_t zp_offset##i = \
- lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, params.name##_z->get_layout()); \
- dnnl_weights[i].weight = convert2dnnl(params.name##_w, {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset##i); \
- dnnl_weights[i].scale = convert2dnnl(params.name##_s, \
- {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \
- dnnl::memory::format_tag::ab, \
- scale_offset##i); \
- dnnl_weights[i].zp = convert2dnnl(params.name##_z, \
- {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \
- dnnl::memory::format_tag::ab, \
- zp_offset##i);
+ const bool has_zp = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config.has_zp;
+
+# define CONVERT_DNNL_OTD(name, i) \
+ int64_t wei_offset##i = lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, params.name##_w->get_layout()); \
+ int64_t scale_offset##i = \
+ lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, params.name##_s->get_layout()); \
+ dnnl_weights[i].weight = convert2dnnl(params.name##_w, {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset##i); \
+ dnnl_weights[i].scale = convert2dnnl(params.name##_s, \
+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \
+ dnnl::memory::format_tag::ab, \
+ scale_offset##i); \
+ if (has_zp) { \
+ dnnl_weights[i].zp = convert_zp2dnnl(params.name##_z, dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc, lru_expert_no); \
+ }
CONVERT_DNNL_OTD(gate, 0)
CONVERT_DNNL_OTD(up, 1)
CONVERT_DNNL_OTD(down, 2)
@@ -904,7 +924,7 @@ public:
// If unique experts exceed resident capacity, returns nullopt → caller falls back.
auto lease = _weight_provider->try_acquire_simultaneous(raw_topk_ids, stream);
if (!lease) {
- GPU_DEBUG_TRACE_DETAIL << "exec_prefill_grouped_gemm OTD: unique experts exceed resident_slots=" << resident_slot_count()
+ GPU_DEBUG_TRACE_DETAIL << "exec_grouped_gemm_cpu_mask_gen OTD: unique experts exceed resident_slots=" << resident_slot_count()
<< ", falling back to per-expert onednn loop" << std::endl;
if (auto* perf = moe_otd::get_perf_counters()) {
perf->grouped_fallbacks.fetch_add(1, std::memory_order_relaxed);
@@ -965,8 +985,8 @@ public:
}
bool should_pre_zero_output() {
- // OTD may fallback to exec_prefill_onednn which accumulates via index_add
- return !use_grouped_gemm_prefill || _weight_provider->is_offloaded();
+ // OTD may fallback to exec_per_expert_onednn_linear which accumulates via index_add
+ return prefill_impl != MoeGemmImpl::grouped_gemm || _weight_provider->is_offloaded();
}
bool should_validate_dnnl_weights() {
@@ -989,10 +1009,66 @@ public:
std::shared_ptr<onednn_linear> _shared_gate_gate_proj; // The scalar gate for shared expert
// Instance-specific flags (not static to avoid race conditions)
- bool use_micro_gemm_prefill = false;
- bool use_gpu_mask_gen_prefill = false;
- bool use_grouped_gemm_prefill = false;
- size_t batched_gemv_threshold = 32; // token_num <= threshold uses batched GEMV path
+ // 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
+ MoeGemmImpl decode_impl = MoeGemmImpl::batched_gemv; // token_num <= batched_gemv_threshold
+ MoeGemmImpl prefill_impl = MoeGemmImpl::per_expert_onednn;
+ size_t batched_gemv_threshold = 32;
+
+ MoeGemmImpl select_impl(size_t token_num) const {
+ return token_num <= batched_gemv_threshold ? decode_impl : prefill_impl;
+ }
+
+ // Whether the routing masks are built on the GPU (no host wait on topk) or on the host.
+ bool should_use_gpu_mask_gen(MoeGemmImpl impl, size_t token_num) const {
+ switch (impl) {
+ case MoeGemmImpl::micro_gemm:
+ return force_gpu_mask_gen_prefill;
+ case MoeGemmImpl::grouped_gemm:
+ // OTD computes the expert lease on the host
+ if (_weight_provider->is_offloaded()) {
+ return false;
+ }
+ // GPU mask gen avoids the host sync on topk, but the host never sees the real max rows per expert, which the
+ // grouped GEMM needs as a dispatch hint, so token_num is used instead. That is exact for one token
+ // but oversizes the dispatch for more (25-token prefill: 452 vs 290 ms on Qwen3.6-35B-A3B int3).
+ return force_gpu_mask_gen_prefill || token_num == 1;
+ default:
+ return false;
+ }
+ }
+
+ // Whether the grouped GEMM GPU mask gen stage and its per-expert buffers are needed
+ bool needs_grouped_gpu_mask_gen() const {
+ return decode_impl == MoeGemmImpl::grouped_gemm || (prefill_impl == MoeGemmImpl::grouped_gemm && force_gpu_mask_gen_prefill);
+ }
+
+ // Single-token decode on the batched GEMV path uses none of the gather/scatter scratch buffers
+ bool needs_gather_scratch(size_t token_num) const {
+ return token_num > 1 || decode_impl == MoeGemmImpl::grouped_gemm;
+ }
+
+ static bool is_batched_gemv_supported(data_types weight_dt) {
+ 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) {
+ 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
+ if (!is_batched_gemv_supported(weight_dt) || config.get_moe_use_grouped_gemm_prefill()) {
+ return MoeGemmImpl::grouped_gemm;
+ }
+ // micro_gemm is better than the per-expert onednn loop. Remove the weight limitation once it supports i8/u8.
+ if (config.get_moe_use_micro_gemm_prefill() && arch >= gpu_arch::xe2 && one_of(weight_dt, {data_types::u4, data_types::i4})) {
+ return MoeGemmImpl::micro_gemm;
+ }
+ return MoeGemmImpl::per_expert_onednn;
+ }
moe_3gemm_swiglu_opt_impl() : PrimitiveImplOCL(moe_3gemm_swiglu_opt::get_type_info_static()) {}
moe_3gemm_swiglu_opt_impl(const program_node& node, const RuntimeParams& params) : moe_3gemm_swiglu_opt_impl() {
@@ -1003,34 +1079,15 @@ public:
const auto& config = params.get_program().get_config();
- // micro_gemm is better than gemm, default to use it
- use_micro_gemm_prefill = config.get_moe_use_micro_gemm_prefill();
// gpu mask gen kernel performance is worse than cpu mask gen, default is off
- use_gpu_mask_gen_prefill = config.get_moe_use_gpu_mask_gen_prefill();
+ force_gpu_mask_gen_prefill = config.get_moe_use_gpu_mask_gen_prefill();
- auto& engine = params.prog->get_engine();
- const auto& info = engine.get_device_info();
- if (info.arch < gpu_arch::xe2) {
- use_micro_gemm_prefill = false;
- }
- GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt_impl(): use_micro_gemm_prefill=" << use_micro_gemm_prefill
- << ", arch=" << static_cast<int>(info.arch) << std::endl;
-
- // Remove this limitation once micro_gemm kernels has supported i8/u8 weights.
const auto& weight_dt = params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0)).data_type;
- if (weight_dt != data_types::u4 && weight_dt != data_types::i4 && use_micro_gemm_prefill) {
- use_micro_gemm_prefill = false;
- }
-
- // grouped_gemm path: single OneDNN grouped matmul per GEMM layer (all experts at once).
- // micro_gemm takes priority; grouped_gemm falls back to onednn loop by default.
- use_grouped_gemm_prefill = config.get_moe_use_grouped_gemm_prefill();
- // grouped_gemm supersedes micro_gemm
- if (use_grouped_gemm_prefill) {
- use_micro_gemm_prefill = false;
- }
+ decode_impl = select_decode_impl(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(): use_grouped_gemm_prefill=" << use_grouped_gemm_prefill << std::endl;
+ 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;
batched_gemv_threshold = config.get_moe_batched_gemv_threshold();
if (batched_gemv_threshold == 0) {
@@ -1052,10 +1109,13 @@ public:
// Don't change the order of stages
add_stage(gather, params);
add_stage(scatter, params);
- add_stage(mlp_gate_up, params);
- add_stage(mlp_down, params);
- add_stage(mlp_reduce, params);
- if (use_micro_gemm_prefill) {
+ // The batched GEMV kernels have no code path for this weight type, so they are not built
+ if (decode_impl == MoeGemmImpl::batched_gemv) {
+ add_stage(mlp_gate_up, params);
+ add_stage(mlp_down, params);
+ add_stage(mlp_reduce, params);
+ }
+ if (prefill_impl == MoeGemmImpl::micro_gemm) {
add_stage(prefill_mask_gen, params);
add_stage(prefill_gather, params);
add_stage(micro_gemm_gate, params);
@@ -1064,11 +1124,14 @@ public:
add_stage(micro_gemm_down, params);
add_stage(prefill_scatter_reduce, params);
}
- if (use_grouped_gemm_prefill) {
+ if (prefill_impl == MoeGemmImpl::grouped_gemm) {
add_stage(grouped_gemm_prefill_gather, params);
add_stage(grouped_gemm_prefill_swiglu, params);
add_stage(prefill_scatter_reduce_row_lut, params);
}
+ if (needs_grouped_gpu_mask_gen()) {
+ add_stage(grouped_gemm_mask_gen, params);
+ }
}
void init(const std::shared_ptr<const moe_3gemm_fused_compressed>& cur_moe) {
@@ -1165,6 +1228,10 @@ public:
// zp shape: [ic / ic_group_size, oc], type: u4/i8
// Skip ZP memory allocation for symmetric quantization (has_zp=false) to save memory
if (cur_moe->_config.has_zp) {
+ OPENVINO_ASSERT(moe_fusion_wei_addr.zp[i]->get_layout().count() != 1,
+ "moe_3gemm GEMM ",
+ i,
+ ": a zero point shared by all the experts is supported by the grouped GEMM only");
int64_t zp_offset = j * get_bytes_count(static_cast<int64_t>(dnnl_weights[i].ic) * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size,
moe_fusion_wei_addr.zp[i]->get_layout());
dnnl_weights[i].zp = convert2dnnl(moe_fusion_wei_addr.zp[i],
@@ -1305,18 +1372,18 @@ public:
void save(BinaryOutputBuffer& ob) const override {
PrimitiveImplOCL::save(ob);
- ob << use_micro_gemm_prefill;
- ob << use_gpu_mask_gen_prefill;
- ob << use_grouped_gemm_prefill;
+ ob << force_gpu_mask_gen_prefill;
+ ob << make_data(&prefill_impl, sizeof(prefill_impl));
+ ob << make_data(&decode_impl, sizeof(decode_impl));
}
void load(BinaryInputBuffer& ib) override {
PrimitiveImplOCL::load(ib);
// Read execution-path flags before init() so any future init() logic
// that depends on them sees the deserialized (not default) values.
- ib >> use_micro_gemm_prefill;
- ib >> use_gpu_mask_gen_prefill;
- ib >> use_grouped_gemm_prefill;
+ ib >> force_gpu_mask_gen_prefill;
+ ib >> make_data(&prefill_impl, sizeof(prefill_impl));
+ ib >> make_data(&decode_impl, sizeof(decode_impl));
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);
@@ -1338,9 +1405,9 @@ public:
cur_moe->_gate_up_group_size = _gate_up_group_size;
cur_moe->_down_group_size = _down_group_size;
cur_moe->_weight_provider = _weight_provider; // shared across clones within the same network
- cur_moe->use_micro_gemm_prefill = use_micro_gemm_prefill;
- cur_moe->use_gpu_mask_gen_prefill = use_gpu_mask_gen_prefill;
- cur_moe->use_grouped_gemm_prefill = use_grouped_gemm_prefill;
+ 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->batched_gemv_threshold = batched_gemv_threshold;
cur_moe->_activation_type = _activation_type;
return cur_moe;
@@ -1378,10 +1445,10 @@ public:
internal_buffers.emplace_back(index_layout, false); // 5: expert_mask_batch
internal_buffers.emplace_back(index_layout, false); // 6: expert_mask_topk
- GPU_DEBUG_TRACE_DETAIL << "[DEBUG] get_internal_buffer_descs(): use_micro_gemm_prefill=" << use_micro_gemm_prefill
- << ", use_grouped_gemm_prefill=" << use_grouped_gemm_prefill << std::endl;
+ GPU_DEBUG_TRACE_DETAIL << "[DEBUG] get_internal_buffer_descs(): prefill_impl=" << static_cast<int>(prefill_impl)
+ << ", decode_impl=" << static_cast<int>(decode_impl) << std::endl;
// for micro_gemm: scatter_reduce via moe_scatter_reduction_opt (buffers all of 7-11)
- if (use_micro_gemm_prefill && token_num > 1) {
+ if (prefill_impl == MoeGemmImpl::micro_gemm && token_num > 1) {
layout layout_micro_gemm(ov::Shape{expert_num, token_num}, ov::element::i32, cldnn::format::bfyx);
internal_buffers.emplace_back(layout_micro_gemm, false); // 7: experts_ids for each activated expert
internal_buffers.emplace_back(layout_micro_gemm, false); // 8: token start offset idx (input gather tokens) for each activated expert
@@ -1392,13 +1459,16 @@ public:
internal_buffers.emplace_back(layout_actual_used_expert_num, false); // 11: actual_used_expert_num
}
// for grouped_gemm: scatter_reduce via moe_scatter_reduction_row_lut (13); gather uses 10, OneDNN desc uses 12
- if (use_grouped_gemm_prefill && token_num > 1) {
+ if (prefill_impl == MoeGemmImpl::grouped_gemm && needs_gather_scratch(token_num)) {
// Buffers 7-9 and 11 fed the base scatter_reduce kernel, which the grouped path replaced
- // with the row_lut kernel. The slots stay to keep the shared indices, the storage does not.
+ // with the row_lut kernel. The slots stay to keep the shared indices, the storage does not,
+ // except 7 and 9, which the grouped GPU mask gen writes (one entry per activated expert).
layout layout_unused(ov::Shape{1}, ov::element::i32, cldnn::format::bfyx);
- internal_buffers.emplace_back(layout_unused, false); // 7: activated expert ids (unused here)
+ layout layout_per_expert(ov::Shape{expert_num}, ov::element::i32, cldnn::format::bfyx);
+ const bool grouped_decode = needs_grouped_gpu_mask_gen();
+ internal_buffers.emplace_back(grouped_decode ? layout_per_expert : layout_unused, false); // 7: activated expert ids
internal_buffers.emplace_back(layout_unused, false); // 8: token start offset per activated expert (unused here)
- internal_buffers.emplace_back(layout_unused, false); // 9: token len per activated expert (unused here)
+ internal_buffers.emplace_back(grouped_decode ? layout_per_expert : layout_unused, false); // 9: token len per activated expert
layout layout_token_idx(ov::Shape{token_num * max_topk}, ov::element::i32, cldnn::format::bfyx);
internal_buffers.emplace_back(layout_token_idx, false); // 10: flat token idx per expert (for gather)
internal_buffers.emplace_back(layout_unused, false); // 11: actual_used_expert_num (unused here)
@@ -1422,9 +1492,14 @@ public:
scratch.y = intermediates_memories[MOE_INTERNAL_BUFFER_DOWN_OUTPUT];
// Routing weights scratch buffer (used in prefill paths and reused as shared_gate_vals in batched GEMV)
scratch.routing_weights = intermediates_memories[MOE_INTERNAL_BUFFER_ROUTING_WEIGHTS];
- if (token_num > 1) {
+ if (needs_gather_scratch(token_num)) {
scratch.x = intermediates_memories[MOE_INTERNAL_BUFFER_GATE_UP_INPUT];
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).
+ const bool needs_expert_masks = select_impl(token_num) == MoeGemmImpl::per_expert_onednn || _weight_provider->is_offloaded();
+ if (token_num > 1 && 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);
@@ -1592,7 +1667,7 @@ public:
if (needs_fallback) {
// Cannot fit all experts simultaneously → fall back to per-expert onednn loop
instance.output_memory_ptr(0)->fill(stream, 0u);
- return exec_prefill_onednn(events, stream, instance, scratch);
+ return exec_per_expert_onednn_linear(events, stream, instance, scratch);
}
}
// OTD hook may have remapped expert IDs into scratch._expert_index_buffer
@@ -1733,7 +1808,7 @@ public:
on_before_prefill(stream, instance, scratch, batch_mem_ptr, topk_count, needs_fallback);
if (needs_fallback) {
instance.output_memory_ptr(0)->fill(stream, 0u);
- return exec_prefill_onednn(events, stream, instance, scratch);
+ return exec_per_expert_onednn_linear(events, stream, instance, scratch);
}
}
@@ -2020,9 +2095,21 @@ public:
// Post-ops fused into gate GEMM: eltwise(swish) + binary_mul(up_output)
bool gate_has_post_ops = false;
int gate_bin_po_idx = -1; // index of binary post-op in gate's post_ops chain
+ // DNNL_ARG_HINT_MAX_GROUP_SIZE host scalar, its value is updated in place before each execute
+ dnnl::memory hint_mem;
+ // Execute args of one GEMM. Building them costs several dnnl::memory objects (each one queries the USM
+ // pointer type) per execute, so they are reused while all the buffer addresses they wrap stay the same:
+ // src, dst, grouped offsets, weights, scales, zero points, binary post-op src.
+ struct exec_args {
+ std::array<const void*, 7> key{};
+ std::unordered_map<int, dnnl::memory> args;
+ };
+ std::array<exec_args, 3> args; // gate, up, down
};
using grouped_kernel_lru = LruCache<int, std::shared_ptr<grouped_onednn_kernel>>;
grouped_kernel_lru _grouped_kernels{128};
+ // Gate/up/down zero points shared by all the experts, passed to the grouped GEMM as host scalars (empty otherwise)
+ std::array<dnnl::memory, 3> _grouped_zp_host_scalars;
onednn_kernel& get_kernel(int n_token, int expert_no, typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {
// OTD: all slots have identical shape → cache by n_token only.
// Non-OTD: cache by (n_token, expert_no) since each expert has fixed weight handles.
@@ -2143,6 +2230,19 @@ public:
// Use the model config to determine ZP presence (symmetric vs asymmetric quantization)
bool has_zp = config.has_zp;
+ // All the zero points share one dtype, which may differ from the weight dtype (u3 weights have u8 zp)
+ const auto zp_dt = has_zp ? convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_0))->get_layout().data_type)
+ : dnnl::memory::data_type::undef;
+ // The zero points are constants, so a shared one is read to the host only once
+ if (has_zp) {
+ const std::array<MOE3GemmInputIndex, 3> zp_inputs{MOE3GemmInputIndex::ZP_0, MOE3GemmInputIndex::ZP_1, MOE3GemmInputIndex::ZP_2};
+ for (size_t i = 0; i < zp_inputs.size(); i++) {
+ const auto& zp_mem = instance.input_memory_ptr(static_cast<size_t>(zp_inputs[i]));
+ if (!_grouped_zp_host_scalars[i] && zp_mem->get_layout().count() == 1) {
+ _grouped_zp_host_scalars[i] = make_host_scalar_zp(zp_mem, instance.get_network().get_stream());
+ }
+ }
+ }
int K_gu = _hidden_size; // K for gate / up
int N_gu = _intermediate_size; // N for gate / up
@@ -2151,24 +2251,29 @@ public:
// Helper: create one grouped matmul prim-desc [total_tokens, K]*W[E,K,N]->[total_tokens,N]
// Weights layout in memory is [E, N, K] (stored transposed), expressed as acb over dims {E,K,N}.
- auto make_pd = [&](int K, int N, int group_size, dnnl::memory::data_type w_dt) {
+ auto make_pd = [&](int K, int N, int group_size, dnnl::memory::data_type w_dt, size_t gemm_idx, const dnnl::post_ops& post_ops) {
dnnl::primitive_attr attr;
attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
+ attr.set_post_ops(post_ops);
bool has_k_groups = (group_size < K);
+ const bool zp_host_scalar = static_cast<bool>(_grouped_zp_host_scalars[gemm_idx]);
if (has_k_groups) {
// per-expert(0) x per-K-group(1) x per-N-channel(2)
attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {group_size, 1}, dnnl::memory::data_type::f16);
- if (has_zp) {
- attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {group_size, 1}, w_dt);
+ if (has_zp && !zp_host_scalar) {
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {group_size, 1}, zp_dt);
}
} else {
// per-expert(0) x per-N-channel(2), no K-grouping
attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, dnnl::memory::data_type::f16);
- if (has_zp) {
- attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, w_dt);
+ if (has_zp && !zp_host_scalar) {
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, zp_dt);
}
}
+ if (zp_host_scalar) {
+ attr.set_host_zero_point(DNNL_ARG_WEIGHTS, zp_dt);
+ }
// Grouped src/dst: tokens are grouped by expert along axis-0
auto src_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, K}, a_dt, 0, num_experts, dnnl::memory::data_type::s32);
@@ -2195,22 +2300,6 @@ public:
// This eliminates the separate grouped_gemm_prefill_swiglu OCL kernel.
// Execution order: up GEMM first, then gate GEMM with post-ops consuming up output.
{
- dnnl::primitive_attr gate_attr;
- gate_attr.set_fpmath_mode(dnnl::fpmath_mode::f16, true);
-
- bool has_k_groups = (_gate_up_group_size < K_gu);
- if (has_k_groups) {
- gate_attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {_gate_up_group_size, 1}, dnnl::memory::data_type::f16);
- if (has_zp) {
- gate_attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 1) | (1 << 2), {_gate_up_group_size, 1}, gw_dt);
- }
- } else {
- gate_attr.set_scales(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, dnnl::memory::data_type::f16);
- if (has_zp) {
- gate_attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) | (1 << 2), {}, gw_dt);
- }
- }
-
// Post-ops: eltwise(activation) + binary_mul(up_output as grouped tensor)
dnnl::post_ops gate_po;
auto activation_algo = moe_activation_to_dnnl_algo(_activation_type);
@@ -2218,35 +2307,31 @@ public:
// binary_mul with grouped descriptor matching dst layout
auto bin_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, N_gu}, a_dt, 0, num_experts, dnnl::memory::data_type::s32);
gate_po.append_binary(dnnl::algorithm::binary_mul, bin_md);
- gate_attr.set_post_ops(gate_po);
-
- auto src_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, K_gu}, a_dt, 0, num_experts, dnnl::memory::data_type::s32);
- auto dst_md = dnnl::memory::desc::grouped(dnnl::memory::dims{total_tokens, N_gu}, a_dt, 0, num_experts, dnnl::memory::data_type::s32);
- auto w_md = dnnl::memory::desc(dnnl::memory::dims{num_experts, K_gu, N_gu}, gw_dt, dnnl::memory::format_tag::acb);
- gk->gate_pd = dnnl::matmul::primitive_desc(onednn_engine, src_md, w_md, dst_md, gate_attr);
+ gk->gate_pd = make_pd(K_gu, N_gu, _gate_up_group_size, gw_dt, 0, gate_po);
gk->gate_prim = dnnl::matmul(gk->gate_pd);
gk->gate_has_post_ops = true;
gk->gate_bin_po_idx = 1; // eltwise is index 0, binary is index 1
}
gk->gate_scale_md = make_quant_md(num_experts, K_gu, _gate_up_group_size, N_gu, dnnl::memory::data_type::f16);
if (has_zp) {
- gk->gate_zp_md = make_quant_md(num_experts, K_gu, _gate_up_group_size, N_gu, gw_dt);
+ gk->gate_zp_md = make_quant_md(num_experts, K_gu, _gate_up_group_size, N_gu, zp_dt);
}
- gk->up_pd = make_pd(K_gu, N_gu, _gate_up_group_size, uw_dt);
+ gk->up_pd = make_pd(K_gu, N_gu, _gate_up_group_size, uw_dt, 1, dnnl::post_ops());
gk->up_prim = dnnl::matmul(gk->up_pd);
gk->up_scale_md = gk->gate_scale_md;
if (has_zp) {
gk->up_zp_md = gk->gate_zp_md;
}
- gk->down_pd = make_pd(K_d, N_d, _down_group_size, dw_dt);
+ gk->down_pd = make_pd(K_d, N_d, _down_group_size, dw_dt, 2, dnnl::post_ops());
gk->down_prim = dnnl::matmul(gk->down_pd);
gk->down_scale_md = make_quant_md(num_experts, K_d, _down_group_size, N_d, dnnl::memory::data_type::f16);
if (has_zp) {
- gk->down_zp_md = make_quant_md(num_experts, K_d, _down_group_size, N_d, dw_dt);
+ gk->down_zp_md = make_quant_md(num_experts, K_d, _down_group_size, N_d, zp_dt);
}
+ gk->hint_mem = dnnl::memory(dnnl::memory::desc::host_scalar(dnnl::memory::data_type::s32), int32_t{0});
_grouped_kernels.add(key, gk);
return *_grouped_kernels.get(key);
@@ -2266,10 +2351,10 @@ public:
// scratch.y = MLP(scratch.x, .gate/up/down) * scratch.routing_weights
// scatter(final_hidden, scratch.y, expert_mask.batch)
//
- cldnn::event::ptr exec_prefill_onednn(const std::vector<cldnn::event::ptr>& events,
- cldnn::stream& stream,
- typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
- scratch_buffers& scratch) {
+ cldnn::event::ptr exec_per_expert_onednn_linear(const std::vector<cldnn::event::ptr>& events,
+ cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch) {
auto cur_moe = instance.get_typed_desc<moe_3gemm_fused_compressed>();
const auto& config = cur_moe->_config;
auto& dnn_stream = stream.get_onednn_stream();
@@ -2368,7 +2453,7 @@ public:
}
// Third prefill path: OneDNN grouped GEMM (one matmul call per GEMM layer, all experts together).
- // This avoids the per-expert loop of exec_prefill_onednn while keeping full weight-format
+ // This avoids the per-expert loop of exec_per_expert_onednn_linear while keeping full weight-format
// compatibility (quantized or fp16 weights).
//
// gather_by_expert(hidden_states, topk_id) -> scratch.x [total, hidden]
@@ -2380,21 +2465,18 @@ public:
//
// Note: "total" = token_num * max_topk, sorted by expert assignment.
//
- cldnn::event::ptr exec_prefill_grouped_gemm(const std::vector<cldnn::event::ptr>& events,
- cldnn::stream& stream,
- typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
- scratch_buffers& scratch) {
- OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("moe_3gemm_swiglu_opt_impl::exec_prefill_grouped_gemm"));
+ cldnn::event::ptr exec_grouped_gemm_cpu_mask_gen(const std::vector<cldnn::event::ptr>& events,
+ cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch) {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("moe_3gemm_swiglu_opt_impl::exec_grouped_gemm_cpu_mask_gen"));
auto cur_moe = instance.get_typed_desc<moe_3gemm_fused_compressed>();
const auto& config = cur_moe->_config;
- auto& dnn_stream = stream.get_onednn_stream();
auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
auto token_num = get_seq_len(hidden_states_layout);
- auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
auto batch_mem_ptr = scratch.topk_id;
- auto routing_mem_ptr = scratch.topk_weights;
const auto& intermediates_memories = instance.get_intermediates_memories();
OPENVINO_ASSERT(intermediates_memories.size() > MOE_INTERNAL_BUFFER_ROW_LUT,
@@ -2402,8 +2484,8 @@ public:
MOE_INTERNAL_BUFFER_ROW_LUT,
" (ROW_LUT) but only ",
intermediates_memories.size(),
- " buffers allocated. use_grouped_gemm_prefill=",
- use_grouped_gemm_prefill);
+ " buffers allocated. prefill_impl=",
+ static_cast<int>(prefill_impl));
int num_total_experts = static_cast<int>(config.num_expert);
int max_topk = static_cast<int>(config.top_k);
@@ -2444,7 +2526,7 @@ public:
events)) {
if (_weight_provider->is_offloaded()) {
// OTD: unique experts > capacity → explicit fallback to per-expert loop
- return exec_prefill_onednn(events, stream, instance, scratch);
+ return exec_per_expert_onednn_linear(events, stream, instance, scratch);
}
// Non-OTD path: build mask from original expert IDs
expert_mask_cpu expert_mask;
@@ -2479,7 +2561,7 @@ public:
max_tokens_per_expert = *std::max_element(tokens_lens_per_expert_cpu.begin(), tokens_lens_per_expert_cpu.begin() + num_actually_used_experts);
}
- GPU_DEBUG_TRACE_DETAIL << "\nexec_prefill_grouped_gemm: token_num=" << token_num << ", total_gathered_tokens=" << total_gathered_tokens
+ GPU_DEBUG_TRACE_DETAIL << "\nexec_grouped_gemm_cpu_mask_gen: token_num=" << token_num << ", total_gathered_tokens=" << total_gathered_tokens
<< ", max_tokens_per_expert=" << max_tokens_per_expert << ", num_actually_used_experts=" << num_actually_used_experts
<< std::endl;
@@ -2489,6 +2571,26 @@ public:
intermediates_memories[MOE_INTERNAL_BUFFER_GROUPED_OFFSETS]
->copy_from(stream, grouped_offsets_cpu.data(), 0, 0, grouped_offsets_cpu.size() * sizeof(grouped_offsets_cpu[0]), true);
+ return exec_grouped_gemm_core(ret_event, stream, instance, scratch, max_tokens_per_expert);
+ }
+
+ // Steps 2-6 of the grouped GEMM path. Expects the gather token list, the grouped end-offsets and row_lut
+ // in the internal buffers, written by the CPU (exec_grouped_gemm_cpu_mask_gen) or GPU (exec_grouped_gemm_gpu_mask_gen) mask gen.
+ cldnn::event::ptr exec_grouped_gemm_core(cldnn::event::ptr ret_event,
+ cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch,
+ int max_tokens_per_expert) {
+ const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
+ auto& dnn_stream = stream.get_onednn_stream();
+
+ auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
+ auto token_num = get_seq_len(hidden_states_layout);
+ auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);
+ auto routing_mem_ptr = scratch.topk_weights;
+ const auto& intermediates_memories = instance.get_intermediates_memories();
+ int total_gathered_tokens = static_cast<int>(token_num) * static_cast<int>(config.top_k);
+
// ----------------------------------------------------------------
// Step 2: GPU gather – reorder input tokens sorted by expert
// ----------------------------------------------------------------
@@ -2522,72 +2624,62 @@ public:
// Passed as DNNL_ARG_HINT_MAX_GROUP_SIZE to each grouped matmul execute(),
// allowing the kernel to reduce per-expert workgroup dispatch without
// recompiling the primitive.
- auto hint_md = dnnl::memory::desc::host_scalar(dnnl::memory::data_type::s32);
- dnnl::memory hint_mem(hint_md, static_cast<int32_t>(max_tokens_per_expert));
+ // The value is read on the host at execute(), so updating it in place does not affect GEMMs already submitted.
+ gk.hint_mem.set_host_scalar_value(static_cast<int32_t>(max_tokens_per_expert));
+ const auto& wei = scratch.moe_fusion_wei_addr;
+
+ // One grouped GEMM [total, K] * W[E,K,N] -> [total, N]. The execute args are rebuilt only when a wrapped buffer
+ // address changes, which for decode happens only on the first call.
+ auto exec_gemm = [&](size_t gemm_idx,
+ dnnl::matmul& prim,
+ const dnnl::matmul::primitive_desc& pd,
+ const memory::ptr& src,
+ const memory::ptr& dst,
+ const dnnl::memory::desc& scale_md,
+ const dnnl::memory::desc& zp_md,
+ const memory::ptr& bin_src) {
+ const auto& host_zp = _grouped_zp_host_scalars[gemm_idx];
+ const bool device_zp = gk.has_zp && !host_zp;
+ auto& cache = gk.args[gemm_idx];
+ const std::array<const void*, 7> key{src->buffer_ptr(),
+ dst->buffer_ptr(),
+ row_offsets->buffer_ptr(),
+ wei.weight[gemm_idx]->buffer_ptr(),
+ wei.scale[gemm_idx]->buffer_ptr(),
+ device_zp ? wei.zp[gemm_idx]->buffer_ptr() : nullptr,
+ bin_src ? bin_src->buffer_ptr() : nullptr};
+ if (cache.args.empty() || cache.key != key) {
+ cache.args = {{DNNL_ARG_SRC, src->get_onednn_grouped_memory(pd.src_desc(), *row_offsets)},
+ {DNNL_ARG_WEIGHTS, wei.weight[gemm_idx]->get_onednn_memory(pd.weights_desc())},
+ {DNNL_ARG_DST, dst->get_onednn_grouped_memory(pd.dst_desc(), *row_offsets)},
+ {DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, wei.scale[gemm_idx]->get_onednn_memory(scale_md)},
+ {DNNL_ARG_HINT_MAX_GROUP_SIZE, gk.hint_mem}};
+ if (gk.has_zp) {
+ cache.args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, device_zp ? wei.zp[gemm_idx]->get_onednn_memory(zp_md) : host_zp});
+ }
+ if (bin_src) {
+ // binary post-op input: grouped memory with the same layout as dst
+ cache.args.insert(
+ {DNNL_ARG_ATTR_MULTIPLE_POST_OP(gk.gate_bin_po_idx) | DNNL_ARG_SRC_1, bin_src->get_onednn_grouped_memory(pd.dst_desc(), *row_offsets)});
+ }
+ cache.key = key;
+ }
+ prim.execute(dnn_stream, cache.args);
+ };
- // gate GEMM: [total, hidden] * W_gate[E,hidden,inter] -> [total, inter]
// With post-ops fused: eltwise(swish/gelu) + binary_mul(up_output)
// Execution order: up first (to produce binary input), then gate with fused activation+multiply.
// This eliminates the separate grouped_gemm_prefill_swiglu OCL kernel launch.
// up GEMM: [total, hidden] * W_up[E,hidden,inter] -> [total, inter]
- {
- auto src_mem = scratch.x->get_onednn_grouped_memory(gk.up_pd.src_desc(), *row_offsets);
- auto dst_mem = scratch.up->get_onednn_grouped_memory(gk.up_pd.dst_desc(), *row_offsets);
- auto w_mem = scratch.moe_fusion_wei_addr.weight[1]->get_onednn_memory(gk.up_pd.weights_desc());
- auto scale_mem = scratch.moe_fusion_wei_addr.scale[1]->get_onednn_memory(gk.up_scale_md);
-
- std::unordered_map<int, dnnl::memory> args{{DNNL_ARG_SRC, src_mem},
- {DNNL_ARG_WEIGHTS, w_mem},
- {DNNL_ARG_DST, dst_mem},
- {DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale_mem},
- {DNNL_ARG_HINT_MAX_GROUP_SIZE, hint_mem}};
- if (gk.has_zp) {
- args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, scratch.moe_fusion_wei_addr.zp[1]->get_onednn_memory(gk.up_zp_md)});
- }
- gk.up_prim.execute(dnn_stream, args);
- }
+ exec_gemm(1, gk.up_prim, gk.up_pd, scratch.x, scratch.up, gk.up_scale_md, gk.up_zp_md, nullptr);
// gate GEMM with fused post-ops: gate_output = activation(X * W_gate) * up_output
// Result written to scratch.gate, ready for down GEMM.
- {
- auto src_mem = scratch.x->get_onednn_grouped_memory(gk.gate_pd.src_desc(), *row_offsets);
- auto dst_mem = scratch.gate->get_onednn_grouped_memory(gk.gate_pd.dst_desc(), *row_offsets);
- auto w_mem = scratch.moe_fusion_wei_addr.weight[0]->get_onednn_memory(gk.gate_pd.weights_desc());
- auto scale_mem = scratch.moe_fusion_wei_addr.scale[0]->get_onednn_memory(gk.gate_scale_md);
-
- // up output as binary post-op input (grouped memory with same layout as gate dst)
- auto up_mem = scratch.up->get_onednn_grouped_memory(gk.gate_pd.dst_desc(), *row_offsets);
-
- std::unordered_map<int, dnnl::memory> args{{DNNL_ARG_SRC, src_mem},
- {DNNL_ARG_WEIGHTS, w_mem},
- {DNNL_ARG_DST, dst_mem},
- {DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale_mem},
- {DNNL_ARG_HINT_MAX_GROUP_SIZE, hint_mem},
- {DNNL_ARG_ATTR_MULTIPLE_POST_OP(gk.gate_bin_po_idx) | DNNL_ARG_SRC_1, up_mem}};
- if (gk.has_zp) {
- args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, scratch.moe_fusion_wei_addr.zp[0]->get_onednn_memory(gk.gate_zp_md)});
- }
- gk.gate_prim.execute(dnn_stream, args);
- }
+ exec_gemm(0, gk.gate_prim, gk.gate_pd, scratch.x, scratch.gate, gk.gate_scale_md, gk.gate_zp_md, scratch.up);
// down GEMM: [total, inter] * W_down[E,inter,hidden] -> [total, hidden]
- {
- auto src_mem = scratch.gate->get_onednn_grouped_memory(gk.down_pd.src_desc(), *row_offsets);
- auto dst_mem = scratch.y->get_onednn_grouped_memory(gk.down_pd.dst_desc(), *row_offsets);
- auto w_mem = scratch.moe_fusion_wei_addr.weight[2]->get_onednn_memory(gk.down_pd.weights_desc());
- auto scale_mem = scratch.moe_fusion_wei_addr.scale[2]->get_onednn_memory(gk.down_scale_md);
-
- std::unordered_map<int, dnnl::memory> args{{DNNL_ARG_SRC, src_mem},
- {DNNL_ARG_WEIGHTS, w_mem},
- {DNNL_ARG_DST, dst_mem},
- {DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale_mem},
- {DNNL_ARG_HINT_MAX_GROUP_SIZE, hint_mem}};
- if (gk.has_zp) {
- args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, scratch.moe_fusion_wei_addr.zp[2]->get_onednn_memory(gk.down_zp_md)});
- }
- gk.down_prim.execute(dnn_stream, args);
- }
+ exec_gemm(2, gk.down_prim, gk.down_pd, scratch.gate, scratch.y, gk.down_scale_md, gk.down_zp_md, nullptr);
// Ensure all grouped GEMMs complete before scatter_reduce (OTD sync)
on_after_grouped_gemm(stream);
@@ -2613,6 +2705,45 @@ public:
return ret_event;
}
+ // Grouped GEMM with GPU mask gen, used for single-token decode. The GPU mask gen writes the gather token list,
+ // the grouped end-offsets and row_lut straight into the internal buffers, so unlike the host mask gen of
+ // exec_grouped_gemm_cpu_mask_gen there is no host round-trip.
+ cldnn::event::ptr exec_grouped_gemm_gpu_mask_gen(const std::vector<cldnn::event::ptr>& events,
+ cldnn::stream& stream,
+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,
+ scratch_buffers& scratch) {
+ OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("moe_3gemm_swiglu_opt_impl::exec_grouped_gemm_gpu_mask_gen"));
+
+ const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;
+ auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));
+ auto token_num = get_seq_len(hidden_states_layout);
+ const auto& intermediates_memories = instance.get_intermediates_memories();
+
+ const auto num_total_experts = static_cast<size_t>(config.num_expert);
+ const auto max_wgs = instance.get_impl_params()->get_device_info().max_work_group_size;
+ OPENVINO_ASSERT(num_total_experts <= max_wgs,
+ "GPU mask gen runs one work-item per expert: num_expert=",
+ num_total_experts,
+ " exceeds max work-group size ",
+ max_wgs);
+ auto ret_event = execute_stage(events,
+ instance,
+ *grouped_gemm_mask_gen,
+ {scratch.topk_id},
+ {intermediates_memories[MOE_INTERNAL_BUFFER_TOKEN_IDX_PER_EXPERT],
+ intermediates_memories[MOE_INTERNAL_BUFFER_GROUPED_OFFSETS],
+ intermediates_memories[MOE_INTERNAL_BUFFER_ACTIVATED_EXPERT_IDS],
+ intermediates_memories[MOE_INTERNAL_BUFFER_TOKEN_LEN_PER_ACTIVATED_EXPERT],
+ intermediates_memories[MOE_INTERNAL_BUFFER_ACTUAL_USED_EXPERT_NUM],
+ intermediates_memories[MOE_INTERNAL_BUFFER_ROW_LUT]},
+ {num_total_experts, 1, 1},
+ {num_total_experts, 1, 1},
+ false,
+ {static_cast<int>(token_num)});
+ // The top-k experts of a token are distinct, so an expert gets at most one row per token
+ return exec_grouped_gemm_core(ret_event, stream, instance, scratch, static_cast<int>(token_num));
+ }
+
cldnn::event::ptr execute(const std::vector<cldnn::event::ptr>& events, cldnn::primitive_inst& ins) override {
OV_ITT_SCOPED_TASK(ov::intel_gpu::itt::domains::intel_gpu_plugin, openvino::itt::handle("moe_3gemm_swiglu_opt_impl::execute"));
auto& instance = reinterpret_cast<typed_primitive_inst<moe_3gemm_fused_compressed>&>(ins);
@@ -2647,7 +2778,8 @@ public:
// Batched GEMV: for small token counts (including single token, MTP/speculative decoding),
// use optimized GEMV kernels with batch dimension. Avoids gather/scatter overhead.
- if (token_num <= batched_gemv_threshold) {
+ const MoeGemmImpl impl = select_impl(token_num);
+ if (impl == MoeGemmImpl::batched_gemv) {
return exec_batched_gemv(events, instance, scratch, token_num);
}
@@ -2656,14 +2788,12 @@ public:
// The per-expert onednn loop uses index_add (accumulates into output).
// The grouped_gemm scatter_reduce writes all token positions atomically
// and does not require pre-zeroing — except in OTD mode where the
- // fallback to exec_prefill_onednn (when unique_experts > lru slots)
+ // fallback to exec_per_expert_onednn_linear (when unique_experts > lru slots)
// also accumulates via index_add.
- if (!use_micro_gemm_prefill && should_pre_zero_output()) {
+ if (impl != MoeGemmImpl::micro_gemm && should_pre_zero_output()) {
final_hidden_states_mem_ptr->fill(stream, 0u);
}
- // GPU mask gen is only supported for micro_gemm; both grouped_gemm and onednn loop
- // always use CPU mask gen and therefore always need topk to be ready first.
- const bool use_gpu_mask_gen = use_micro_gemm_prefill && use_gpu_mask_gen_prefill;
+ 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) {
@@ -2674,13 +2804,13 @@ public:
}
GPU_DEBUG_TRACE_DETAIL << "\nMoE3GemmFusedCompressed exec(): token_num=" << token_num << ", max_topk=" << static_cast<int>(config.top_k)
- << ", use_micro_gemm_prefill=" << use_micro_gemm_prefill << ", use_grouped_gemm_prefill=" << use_grouped_gemm_prefill
- << std::endl;
+ << ", impl=" << static_cast<int>(impl) << std::endl;
update_rt_params(instance);
- if (use_micro_gemm_prefill) {
+ if (impl == MoeGemmImpl::micro_gemm) {
ret_env = exec_prefill_micro_gemm(events, instance, scratch, use_gpu_mask_gen);
- } else if (use_grouped_gemm_prefill) {
- ret_env = exec_prefill_grouped_gemm(events, stream, instance, scratch);
+ } else if (impl == MoeGemmImpl::grouped_gemm) {
+ ret_env = use_gpu_mask_gen ? exec_grouped_gemm_gpu_mask_gen(events, stream, instance, scratch)
+ : exec_grouped_gemm_cpu_mask_gen(events, stream, instance, scratch);
// In OTD mode the grouped_gemm path interleaves OCL kernels with OneDNN
// grouped matmul on the same in-order queue. The framework's event-based
// scheduling may proceed to subsequent graph nodes before scatter_reduce
@@ -2688,7 +2818,7 @@ public:
// Flush the queue only in OTD mode to avoid impacting non-OTD perf.
on_after_exec_sync(stream);
} else {
- ret_env = exec_prefill_onednn(events, stream, instance, scratch);
+ ret_env = exec_per_expert_onednn_linear(events, stream, instance, scratch);
}
if (_has_shared_expert) {
@@ -2699,10 +2829,10 @@ public:
// same in-order OCL queue, so submission order guarantees execution order.
// No explicit wait() is needed — the in-order queue serializes all GPU work,
// and any subsequent primitive on the same queue will see the completed output.
- if (use_grouped_gemm_prefill && ret_env) {
+ if (impl == MoeGemmImpl::grouped_gemm && ret_env) {
// ensure grouped GEMM fully completes before executing shared expert, which relies on its output being ready;
// For grouped_gemm path, scatter_reduce (OCL) is preceded by multiple OCL <--> OneDNN
- // transitions inside exec_prefill_grouped_gemm. The implicit ordering between
+ // transitions inside exec_grouped_gemm_cpu_mask_gen. The implicit ordering between
// the OCL queue and OneDNN's stream cannot be relied upon across this many
// back-and-forth submissions, so the shared expert's down_proj sum post-op
// (which reads+writes final_hidden_states) can race with scatter_reduce.
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 e527bdb4855..202720e7086 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,12 +41,13 @@ struct moe_3gemm_swiglu_opt : public ImplementationManager {
return false;
}
- // Only support weight: u4, i4, u8, i8
+ // Only support weight: u4, i4, u8, i8, u3 (u3 has no batched GEMV kernel and runs decode via OneDNN grouped GEMM)
static constexpr std::array supported_wei_type = {
ov::element::u4,
ov::element::i4,
ov::element::u8,
ov::element::i8,
+ ov::element::u3,
};
const auto& wei_layout = node.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0));
if (!one_of(wei_layout.data_type, supported_wei_type)) {
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl
index a89570edc5b..f4ca16df4ba 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe_mask_gen.cl
@@ -12,6 +12,9 @@ KERNEL(moe_mask_gen)(
__global OUTPUT2_TYPE* experts_id,
__global OUTPUT3_TYPE* tokens_lens_per_expert,
__global OUTPUT4_TYPE* num_actual_used_experts
+#if ROW_LUT_ENABLE
+ , __global OUTPUT5_TYPE* row_lut
+#endif
#if SET_TOKEN_LEN
, const int token_len
#endif
@@ -58,6 +61,10 @@ KERNEL(moe_mask_gen)(
for (int t = 0; t < num_tokens; ++t) {
for (int e = 0; e < NUM_EXPERTS_PER_TOKEN; ++e) {
if (topk_idx[token_idx] == expert_id) {
+#if ROW_LUT_ENABLE
+ // inverse mapping: (token, topk) pair -> gathered row
+ row_lut[token_idx] = tokens_per_expert_iter;
+#endif
tokens_per_expert[tokens_per_expert_iter] = t;
tokens_per_expert_iter += 1;
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
index baf657bb037..d2409837bd8 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_micro.cpp
@@ -1143,11 +1143,11 @@ KernelData SDPAMicroGenerator::get_kernel_data(const kernel_impl_params& params)
shim_options.useTileOps = true;
shim_options.decorator = "kq";
- kd.code->jit += generateShim(gemms[kq_id], micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(gemms[kq_id], micro::HostLanguage::OpenCL_C, shim_options);
shim_options.microkernelID++;
shim_options.decorator = "vs";
- kd.code->jit += generateShim(gemms[vs_id], micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(gemms[vs_id], micro::HostLanguage::OpenCL_C, shim_options);
bool need_256_grf = false;
if (gemms[kq_id].grfMin > 128 || gemms[vs_id].grfMin > 128) {
@@ -1161,11 +1161,11 @@ KernelData SDPAMicroGenerator::get_kernel_data(const kernel_impl_params& params)
if (!m_is_prefill && !m_is_gqa_single_token) {
shim_options.microkernelID++;
shim_options.decorator = "kcq";
- kd.code->jit += generateShim(gemms[kcq_id], micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(gemms[kcq_id], micro::HostLanguage::OpenCL_C, shim_options);
shim_options.microkernelID++;
shim_options.decorator = "vcs";
- kd.code->jit += generateShim(gemms[vcs_id], micro::HostLanguage::OpenCL_C, shim_options);
+ kd.code->jit += micro::generate_shim(gemms[vcs_id], micro::HostLanguage::OpenCL_C, shim_options);
if (!need_256_grf && (gemms[kcq_id].grfMin > 128 || gemms[vcs_id].grfMin > 128)) {
kd.code->options += " -cl-intel-256-GRF-per-thread";
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp
index 369c88a2b92..0d4519839c3 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp
@@ -301,6 +301,12 @@ JitConstants make_type_jit_constants(const std::string& name, const ov::element:
type_size = "0.5f";
is_fp = false;
break;
+ case ov::element::u3:
+ // tightly packed, 3 bits per element
+ type = "uchar";
+ type_size = "0.375f";
+ is_fp = false;
+ break;
case ov::element::bf16:
type = "ushort";
max_val = "FLT_MAX";
diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.cpp b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.cpp
index c46c64cb689..acbaea71c56 100644
--- a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.cpp
@@ -69,7 +69,8 @@ protected:
if (prim->compressed_weights) {
const auto weights_dt = instance.get_input_layout(1).data_type;
auto weight_bitwidth = ov::element::Type(weights_dt).bitwidth();
- OPENVINO_ASSERT(weight_bitwidth == 8 || weight_bitwidth == 4, "[GPU] oneDNN supports only 4bit/8bit compressed weights");
+ OPENVINO_ASSERT(weight_bitwidth == 8 || weight_bitwidth == 4 || weight_bitwidth == 3,
+ "[GPU] oneDNN supports only 3bit/4bit/8bit compressed weights");
int idx = prim->bias.is_valid() ? 3 : 2;
if (prim->decompression_scale.is_valid()) {
diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp
index cdd1788a975..cbedc59e971 100644
--- a/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/fully_connected_onednn.hpp
@@ -69,7 +69,7 @@ struct FullyConnectedImplementationManager : public ImplementationManager {
one_of(out_dt, {data_types::f16, data_types::bf16, data_types::f32, data_types::i32, data_types::i8, data_types::u8});
bool compressed_case = fc_prim->compressed_weights &&
one_of(in0_dt, {data_types::f16, data_types::bf16, data_types::f32, data_types::i8, data_types::u8}) &&
- one_of(wei_dt, {data_types::u8, data_types::i8, data_types::u4, data_types::i4}) &&
+ one_of(wei_dt, {data_types::u8, data_types::i8, data_types::u4, data_types::i4, data_types::u3}) &&
one_of(out_dt, {data_types::f16, data_types::bf16, data_types::f32, data_types::u8, data_types::i8});
const bool fp_compressed_case = fc_prim->compressed_weights && one_of(in0_dt, {data_types::f8e4m3, data_types::f4e2m1, data_types::f8e5m2}) &&
one_of(wei_dt, {data_types::f8e4m3, data_types::f4e2m1, data_types::f8e5m2}) && one_of(out_dt, {data_types::f16, data_types::f32});
@@ -81,7 +81,7 @@ struct FullyConnectedImplementationManager : public ImplementationManager {
if (fc_prim->decompression_zero_point.is_valid()) {
const auto decompression_zp_idx = fc_prim->bias.is_valid() ? 4 : 3;
const auto decompression_zp_dt = fc_node.get_input_layout(decompression_zp_idx).data_type;
- const bool is_wei_compressed = one_of(wei_dt, {ov::element::Type_t::i4, ov::element::Type_t::u4, ov::element::Type_t::u8});
+ const bool is_wei_compressed = one_of(wei_dt, {ov::element::Type_t::i4, ov::element::Type_t::u4, ov::element::Type_t::u3, ov::element::Type_t::u8});
const bool is_zp_compressed = one_of(decompression_zp_dt, {ov::element::Type_t::i4, ov::element::Type_t::u4,
ov::element::Type_t::u8, ov::element::Type_t::i8});
if (!is_wei_compressed || !is_zp_compressed) {
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
index bb0e4965311..95a52d0559a 100644
--- 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
@@ -34,13 +34,15 @@ struct onednn_matmul {
dnnl::primitive_attr attr;
dnnl::post_ops postops;
+ // zp_dtype == undef means no weight zero-point
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) {
+ dnnl::memory::data_type zp_dtype = dnnl::memory::data_type::undef,
+ bool common_zp = false) {
m_a_type = act_dtype;
m_w_type = weight_dtype;
m_K_groups = 0;
@@ -53,8 +55,8 @@ struct onednn_matmul {
}
if (ic_group_size >= 0) {
w_scale(ic_group_size);
- if (has_zp) {
- w_zp(ic_group_size);
+ if (zp_dtype != dnnl::memory::data_type::undef) {
+ w_zp(ic_group_size, zp_dtype, common_zp);
}
fpmath_f16();
}
@@ -74,14 +76,19 @@ struct onednn_matmul {
return *this;
}
- onednn_matmul& w_zp(int k_group_size) {
+ onednn_matmul& w_zp(int k_group_size, dnnl::memory::data_type zp_dtype, bool common_zp = false) {
+ if (common_zp) {
+ // One zero point for the whole weights tensor, while the scales stay grouped
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, 0, {}, zp_dtype);
+ return *this;
+ }
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);
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (0 << 0) + (1 << 1), {1}, zp_dtype);
} 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);
+ attr.set_zero_points(DNNL_ARG_WEIGHTS, (1 << 0) + (1 << 1), {k_group_size, 1}, zp_dtype);
}
return *this;
}
@@ -154,9 +161,10 @@ struct onednn_matmul {
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) {
+ dnnl::memory::data_type zp_dtype = dnnl::memory::data_type::undef,
+ dnnl::algorithm activation_algo = dnnl::algorithm::eltwise_swish,
+ bool common_zp = false)
+ : onednn_matmul(act_dtype, weight_dtype, batch, ic, oc, ic_group_size, zp_dtype, common_zp) {
if (t == type::with_bin_mul) {
bin_post_id = 0;
post_op_bin_mul(true);
@@ -263,8 +271,10 @@ struct onednn_linear {
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);
+ // The zp dtype may differ from the weight dtype (u3 weights have u8 zp)
+ const auto zp_dtype = zp ? zp.get_desc().get_data_type() : dnnl::memory::data_type::undef;
+ const bool common_zp = zp && zp.get_desc().get_dims() == dnnl::memory::dims{1};
+ auto mm = make_cacheable<onednn_matmul>(eng, act_dtype, weight_dtype, batch, ic, oc, ic_group_size, t, zp_dtype, activation_algo, common_zp);
onednn_linear linear;
linear.mm = mm;
linear.bin_post_id = mm->bin_post_id;
diff --git a/src/plugins/intel_gpu/src/graph/impls/onednn/utils.cpp b/src/plugins/intel_gpu/src/graph/impls/onednn/utils.cpp
index 73c0a029387..26d1634105c 100644
--- a/src/plugins/intel_gpu/src/graph/impls/onednn/utils.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/onednn/utils.cpp
@@ -164,32 +164,20 @@ dnnl::memory::dims get_strides(dnnl::memory::dims dims) {
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;
- case cldnn::data_types::f4e2m1:
- return dnnl::memory::data_type::f4_e2m1;
- case cldnn::data_types::f8e4m3:
- return dnnl::memory::data_type::f8_e4m3;
- case cldnn::data_types::f8e5m2:
- return dnnl::memory::data_type::f8_e5m2;
- case cldnn::data_types::f8e8m0:
- return dnnl::memory::data_type::e8m0;
- case cldnn::data_types::bf16:
- return dnnl::memory::data_type::bf16;
- default:
- throw std::invalid_argument("[clDNN] Unsupported conversion from cldnn to onednn type");
+ 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;
+ case cldnn::data_types::u3: return dnnl::memory::data_type::u3;
+ case cldnn::data_types::f4e2m1: return dnnl::memory::data_type::f4_e2m1;
+ case cldnn::data_types::f8e4m3: return dnnl::memory::data_type::f8_e4m3;
+ case cldnn::data_types::f8e5m2: return dnnl::memory::data_type::f8_e5m2;
+ case cldnn::data_types::f8e8m0: return dnnl::memory::data_type::e8m0;
+ case cldnn::data_types::bf16: return dnnl::memory::data_type::bf16;
+ default: OPENVINO_THROW("[GPU] Unsupported conversion from cldnn to onednn type");
}
}
@@ -300,24 +288,27 @@ int64_t get_offset(const cldnn::layout& l, dnnl::memory::desc&& desc) {
}
switch (desc.get_data_type()) {
- case dnnl::memory::data_type::s4:
- case dnnl::memory::data_type::u4:
- case dnnl::memory::data_type::f4_e2m1:
- return offset / 2;
- case dnnl::memory::data_type::s8:
- case dnnl::memory::data_type::u8:
- case dnnl::memory::data_type::f8_e4m3:
- case dnnl::memory::data_type::f8_e5m2:
- case dnnl::memory::data_type::e8m0:
- return offset;
- case dnnl::memory::data_type::f16:
- case dnnl::memory::data_type::bf16:
- return (offset * 2);
- case dnnl::memory::data_type::f32:
- case dnnl::memory::data_type::s32:
- return (offset * 4);
- default:
- throw std::runtime_error(std::string("Unsupported offset for dnnl_data_type_t ") + dnnl_dt2str(static_cast<dnnl_data_type_t>(desc.get_data_type())));
+ case dnnl::memory::data_type::u3:
+ OPENVINO_ASSERT(offset % 8 == 0, "[GPU] u3 memory offset must be byte aligned, but got element offset ", offset);
+ return offset * 3 / 8;
+ case dnnl::memory::data_type::s4:
+ case dnnl::memory::data_type::u4:
+ case dnnl::memory::data_type::f4_e2m1:
+ return offset / 2;
+ case dnnl::memory::data_type::s8:
+ case dnnl::memory::data_type::u8:
+ case dnnl::memory::data_type::f8_e4m3:
+ case dnnl::memory::data_type::f8_e5m2:
+ case dnnl::memory::data_type::e8m0:
+ return offset;
+ case dnnl::memory::data_type::f16:
+ case dnnl::memory::data_type::bf16:
+ return (offset * 2);
+ case dnnl::memory::data_type::f32:
+ case dnnl::memory::data_type::s32:
+ return (offset * 4);
+ default:
+ OPENVINO_THROW("[GPU] Unsupported offset for dnnl_data_type_t ", dnnl_dt2str(static_cast<dnnl_data_type_t>(desc.get_data_type())));
}
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/fully_connected_gpu_bfyx_ref.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/fully_connected_gpu_bfyx_ref.cl
index 87c6dca978e..2d1851de2a4 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/fully_connected_gpu_bfyx_ref.cl
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/fully_connected_gpu_bfyx_ref.cl
@@ -5,6 +5,7 @@
#include "include/batch_headers/fetch_data.cl"
#include "include/batch_headers/fetch_weights.cl"
#include "include/batch_headers/int4_utils.cl"
+#include "include/batch_headers/int3_utils.cl"
#include "include/batch_headers/int2_utils.cl"
KERNEL(fc)(
@@ -72,6 +73,10 @@ KERNEL(fc)(
ACCUMULATOR_TYPE filter_compressed = ((ACCUMULATOR_TYPE*)(&filter_unpacked))[filter_idx % 4];
ACCUMULATOR_TYPE filter_val = (filter_compressed - zp) * scale;
dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * filter_val;
+ #elif COMPRESSED_WEIGHTS_UINT3
+ ACCUMULATOR_TYPE filter_compressed = TO_ACCUMULATOR_TYPE(get_uint3_weight(weights, filter_idx));
+ ACCUMULATOR_TYPE filter_val = (filter_compressed - zp) * scale;
+ dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * filter_val;
#else
dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * (ACCUMULATOR_TYPE)(weights[filter_idx]);
#endif
@@ -126,6 +131,10 @@ KERNEL(fc)(
ACCUMULATOR_TYPE filter_compressed = ((ACCUMULATOR_TYPE*)(&filter_unpacked))[filter_idx % 4];
ACCUMULATOR_TYPE filter_val = (filter_compressed - zp) * scale;
dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * filter_val;
+ #elif COMPRESSED_WEIGHTS_UINT3
+ ACCUMULATOR_TYPE filter_compressed = TO_ACCUMULATOR_TYPE(get_uint3_weight(weights, filter_idx));
+ ACCUMULATOR_TYPE filter_val = (filter_compressed - zp) * scale;
+ dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * filter_val;
#else
dotProd += (ACCUMULATOR_TYPE)(input[input0_idx]) * (ACCUMULATOR_TYPE)(weights[filter_idx]);
#endif
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/include/batch_headers/int3_utils.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/include/batch_headers/int3_utils.cl
new file mode 100644
index 00000000000..cdcf91ee87c
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/include/batch_headers/int3_utils.cl
@@ -0,0 +1,15 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// u3 weights are a tightly packed LSB-first bit stream: element i occupies bits [3 * i, 3 * i + 3),
+// so it may span two bytes. The second byte is read only when needed to stay inside the buffer.
+inline uchar get_uint3_weight(const __global uchar* weights, uint idx) {
+ const uint bit_offset = idx * 3;
+ const uint byte_idx = bit_offset / 8;
+ const uint shift = bit_offset % 8;
+ uint packed = weights[byte_idx];
+ if (shift > 5)
+ packed |= (uint)weights[byte_idx + 1] << 8;
+ return (uchar)((packed >> shift) & 0x7);
+}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/common_types.h b/src/plugins/intel_gpu/src/kernel_selector/common_types.h
index 6a0b4a98e22..5e5165daee8 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/common_types.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/common_types.h
@@ -120,6 +120,7 @@ enum class KernelType {
enum class Datatype {
UNSUPPORTED,
UINT2,
+ UINT3,
UINT4,
INT4,
INT8,
@@ -148,6 +149,7 @@ enum class WeightsType {
INT8,
UINT8,
UINT2,
+ UINT3,
UINT4,
INT4,
INT32,
diff --git a/src/plugins/intel_gpu/src/kernel_selector/jitter.cpp b/src/plugins/intel_gpu/src/kernel_selector/jitter.cpp
index da439888ef7..d811dccc85a 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/jitter.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/jitter.cpp
@@ -1673,6 +1673,13 @@ JitConstants MakeTypeJitConstants(Datatype dataType, const std::string& macroNam
type_size = "0.25f";
is_fp = false;
break;
+ case Datatype::UINT3:
+ type = "uchar";
+ to_type = "convert_uchar(v)";
+ to_type_sat = "convert_uchar_sat(v)";
+ type_size = "0.375f";
+ is_fp = false;
+ break;
case Datatype::UINT4:
type = "uchar";
to_type = "convert_uchar(v)";
@@ -1816,6 +1823,8 @@ JitConstants MakeTypeJitConstants(WeightsType weightsType, const std::string& ma
return MakeTypeJitConstants(Datatype::UINT8, macroName);
case WeightsType::UINT2:
return MakeTypeJitConstants(Datatype::UINT2, macroName);
+ case WeightsType::UINT3:
+ return MakeTypeJitConstants(Datatype::UINT3, macroName);
case WeightsType::INT4:
return MakeTypeJitConstants(Datatype::INT4, macroName);
case WeightsType::UINT4:
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.cpp
index f7c7f707443..e4c143e2fd9 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.cpp
@@ -148,6 +148,7 @@ std::string toString(DataLayout l) {
std::string toString(Datatype dType) {
switch (dType) {
case Datatype::UINT2: return "UINT2";
+ case Datatype::UINT3: return "UINT3";
case Datatype::UINT4: return "UINT4";
case Datatype::INT4: return "INT4";
case Datatype::INT8: return "INT8";
@@ -172,6 +173,7 @@ std::string toString(WeightsType wType) {
case WeightsType::F16: return "F16";
case WeightsType::F32: return "F32";
case WeightsType::UINT2: return "UINT2";
+ case WeightsType::UINT3: return "UINT3";
case WeightsType::UINT4: return "UINT4";
case WeightsType::INT4: return "INT4";
case WeightsType::INT8: return "INT8";
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.cpp
index 9830f63ecf5..cdc8d8cb6dc 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.cpp
@@ -50,6 +50,9 @@ void ParamsKey::EnableInputDataType(Datatype dt) {
case Datatype::UINT2:
key.inputType.val.uint2 = 1;
break;
+ case Datatype::UINT3:
+ key.inputType.val.uint3 = 1;
+ break;
case Datatype::INT4:
key.inputType.val.int4 = 1;
break;
@@ -110,6 +113,9 @@ void ParamsKey::EnableOutputDataType(Datatype dt) {
case Datatype::UINT2:
key.outputType.val.uint2 = 1;
break;
+ case Datatype::UINT3:
+ key.outputType.val.uint3 = 1;
+ break;
case Datatype::INT4:
key.outputType.val.int4 = 1;
break;
@@ -185,6 +191,9 @@ void ParamsKey::EnableInputWeightsType(WeightsType wt) {
case WeightsType::UINT2:
key.inputWeightsType.val.uint2 = 1;
break;
+ case WeightsType::UINT3:
+ key.inputWeightsType.val.uint3 = 1;
+ break;
case WeightsType::INT32:
key.inputWeightsType.val.int32 = 1;
break;
@@ -230,6 +239,9 @@ void ParamsKey::EnableOutputWeightsType(WeightsType wt) {
case WeightsType::UINT2:
key.outputWeightsType.val.uint2 = 1;
break;
+ case WeightsType::UINT3:
+ key.outputWeightsType.val.uint3 = 1;
+ break;
case WeightsType::INT32:
key.outputWeightsType.val.int32 = 1;
break;
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.h b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.h
index d382c604366..efba12f11e0 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_params.h
@@ -247,6 +247,7 @@ public:
union DataTypesKey {
struct val_t {
uint32_t uint2 : 1;
+ uint32_t uint3 : 1;
uint32_t int4 : 1;
uint32_t uint4 : 1;
uint32_t int8 : 1;
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_base.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_base.cpp
index dbe1bcac46f..1096b048f10 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_base.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_base.cpp
@@ -31,6 +31,8 @@ JitConstants FullyConnectedKernelBase::GetJitConstants(const fully_connected_par
jit.AddConstants({MakeJitConstant("COMPRESSED_WEIGHTS_INT4", 1)});
} else if (params.weights.GetDType() == WeightsType::UINT2) {
jit.AddConstants({MakeJitConstant("COMPRESSED_WEIGHTS_UINT2", 1)});
+ } else if (params.weights.GetDType() == WeightsType::UINT3) {
+ jit.AddConstants({MakeJitConstant("COMPRESSED_WEIGHTS_UINT3", 1)});
}
const size_t scale_groups_num = params.decompression_scale.Feature().v;
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bfyx_ref.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bfyx_ref.cpp
index 17c78242d5f..efa6128cee5 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bfyx_ref.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/fully_connected_kernel_bfyx_ref.cpp
@@ -30,6 +30,7 @@ ParamsKey FullyConnected_bfyx_Ref::GetSupportedKey() const {
k.EnableInputWeightsType(WeightsType::UINT8);
k.EnableInputWeightsType(WeightsType::INT8);
k.EnableInputWeightsType(WeightsType::UINT2);
+ k.EnableInputWeightsType(WeightsType::UINT3);
k.EnableInputWeightsType(WeightsType::UINT4);
k.EnableInputWeightsType(WeightsType::INT4);
k.EnableAllInputLayout();
diff --git a/src/plugins/intel_gpu/src/kernel_selector/micro_utils.hpp b/src/plugins/intel_gpu/src/kernel_selector/micro_utils.hpp
index 9cc665bce74..813c5b05cb8 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/micro_utils.hpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/micro_utils.hpp
@@ -99,6 +99,26 @@ static inline int alignment_for_ld(int ld) {
return gemmstone::microkernel::alignmentForLD(ld);
}
+// The shim prototypes use oneDNN custom type names for sub-byte / non-native element types (e.g. `const global s4* a`),
+// which oneDNN defines in its own custom_types.h. Only the pointer address reaches the microkernel, so they are
+// defined here as the storage types the plugin kernels pass (and the shim used before these names were introduced).
+inline std::string generate_shim(const Package& package, HostLanguage language, const ShimOptions& options) {
+ static constexpr const char* shim_types = R"(
+#ifndef OV_MICROKERNEL_SHIM_TYPES
+#define OV_MICROKERNEL_SHIM_TYPES
+typedef uchar u4;
+typedef uchar s4;
+typedef uchar u3;
+typedef ushort bf16;
+typedef uchar f8_e5m2;
+typedef uchar f8_e4m3;
+typedef uchar e8m0;
+typedef uchar f4_e2m1;
+#endif
+)";
+ return shim_types + gemmstone::microkernel::generateShim(package, language, options);
+}
+
} // namespace micro
#undef UNUSED
diff --git a/src/plugins/intel_gpu/src/kernel_selector/sources.cmake b/src/plugins/intel_gpu/src/kernel_selector/sources.cmake
index 9740e95f563..798332df508 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/sources.cmake
+++ b/src/plugins/intel_gpu/src/kernel_selector/sources.cmake
@@ -888,6 +888,7 @@ set(GPU_KERNEL_SELECTOR_CL_KERNELS
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/generic_vector_ops.cl
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/imad.cl
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/int2_utils.cl
+ ${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/int3_utils.cl
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/int4_convert.cl
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/int4_utils.cl
${CMAKE_CURRENT_LIST_DIR}/cl_kernels/include/batch_headers/sdpa_utils.cl
diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
index 9603b26540f..12b15b7e1f7 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp
@@ -50,6 +50,12 @@ static bool prepare_moe_otd_params(ProgramBuilder& p,
}
const bool otd_enabled = lru_expert_num > 0;
if (otd_enabled) {
+ // Offloaded experts are streamed from the weights file as stored. A per-group u3 zero point is packed there (3 bits per element)
+ // but is converted to u8 in the graph (oneDNN has no u3 zero point), so its file layout does not match the GPU buffer.
+ // A scalar zero point is shared by all the experts and is not streamed.
+ OPENVINO_ASSERT(!config.has_zp || op->get_input_element_type(static_cast<size_t>(input_idx::weight_0)) != ov::element::u3 ||
+ ov::shape_size(op->get_input_shape(static_cast<size_t>(input_idx::zp_0))) == 1,
+ "OFFLOAD_RATIO is not supported for u3 weights with per-group zero points");
weights_path = std::filesystem::path(p.get_config().get_weights_path());
OPENVINO_ASSERT(!weights_path.empty(),
"ov::weights_path property is not set. OTD requires a valid path to the model .bin file. "
@@ -107,6 +113,11 @@ static bool prepare_moe_otd_params(ProgramBuilder& p,
// Serialized offsets are only needed for OTD path (weight-on-demand loading).
if (otd_enabled) {
for (size_t i = 0; i < const_input_idx_by_offset.size(); i++) {
+ // Offsets are ordered as weights, scales, zero points. Symmetric weights have an empty placeholder instead of the zero points.
+ constexpr size_t first_zp_offset = 6;
+ if (i >= first_zp_offset && !config.has_zp) {
+ continue;
+ }
weight_bin_offsets[i] = get_const_offset(const_input_idx_by_offset[i], i);
}
}
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/compressed_weights_pattern.hpp b/src/plugins/intel_gpu/src/plugin/transformations/compressed_weights_pattern.hpp
index 0ed37eff6bb..3cda16a1c43 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/compressed_weights_pattern.hpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/compressed_weights_pattern.hpp
@@ -17,6 +17,7 @@ using ov::pass::operator|;
};\
\
auto compressed_type = type_matches_any({ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4,\
+ ov::element::u3,\
ov::element::u2, ov::element::f8e4m3, ov::element::f8e5m2,\
ov::element::f4e2m1});\
auto weights_const_m = wrap_type<ov::op::v0::Constant>(compressed_type);\
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.cpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.cpp
index eefb1d31e51..6ebb1728f9d 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.cpp
@@ -122,7 +122,8 @@ ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyCon
// Convert ZP to u8 (or i8 for a scalar i4 ZP)
if (constant->get_element_type() == ov::element::u8) {
result = constant;
- } else if (constant->get_element_type() == ov::element::u4 || constant->get_element_type() == ov::element::u2) {
+ } else if (constant->get_element_type() == ov::element::u4 || constant->get_element_type() == ov::element::u3 ||
+ constant->get_element_type() == ov::element::u2) {
result = std::make_shared<ov::op::v0::Convert>(node, ov::element::u8);
// Only unsigned ZP types can be converted to u8.
} else if (weight_u8 && sub_with_convert && !constant->get_element_type().is_signed()) {
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 5091a2dc79b..60836223d85 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -613,7 +613,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
const auto& defaultPrecisions = ov::pass::low_precision::precision_set::get_int8_support();
const ov::element::TypeVector supported_woq_types =
- {ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4, ov::element::u2};
+ {ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4, ov::element::u3, ov::element::u2};
bool enableInt8;
bool unroll_loop = config.get_enable_loop_unrolling();
auto is_model_quantized = ov::pass::low_precision::LowPrecision::isFunctionQuantized(func);
@@ -697,8 +697,9 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
manager.register_pass<ov::pass::TransposeMatMul>();
- manager.register_pass<ov::pass::MarkDequantization>(std::vector<ov::element::Type>{ov::element::i8, ov::element::u8, ov::element::i4, ov::element::u4, ov::element::u2},
- !device_info.supports_immad);
+ manager.register_pass<ov::pass::MarkDequantization>(
+ std::vector<ov::element::Type>{ov::element::i8, ov::element::u8, ov::element::i4, ov::element::u4, ov::element::u3, ov::element::u2},
+ !device_info.supports_immad);
if (config.get_use_onednn() && m_context->get_engine().get_device_info().arch >= cldnn::gpu_arch::xe3p) {
manager.register_pass<ov::pass::MarkDequantization>(
std::vector<ov::element::Type>{ov::element::f8e4m3, ov::element::f8e5m2, ov::element::f4e2m1, ov::element::f8e8m0},
@@ -715,7 +716,8 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
const std::vector<ov::element::Type> supported_compressed_weights_types{ov::element::u4,
ov::element::i4,
ov::element::i8,
- ov::element::u8};
+ ov::element::u8,
+ ov::element::u3};
manager.register_pass<ov::pass::ConvertGroupedMatMulToGroupedMatMulCompressed>(
supported_compressed_weights_types);
diff --git a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
index 7c9ffaab659..a8babcba76a 100644
--- a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
+++ b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
@@ -142,6 +142,10 @@ const std::vector<std::regex>& disabled_test_patterns() {
std::regex(R"(.*smoke_ConditionGPUTest_static/StaticConditionLayerGPUTest.CompareWithRefs/IS=\(3.6\)_netPRC=i8_ifCond=PARAM_targetDevice=GPU_.*)"),
// Use weight from model not from path hint
std::regex(R"(.*compile_from_weightless_blob.*)"),
+ // u3 Transpose reference implementation is not upstreamed yet (non-transposed u3 weights fold a Transpose)
+ std::regex(R"(.*MatMulCompressedWeights.*weights_precision=u3_.*transpose_weights=0_.*)"),
+ // MoE expert offload does not support per-group u3 zero points: the weights file stores them packed, the graph has them as u8
+ std::regex(R"(.*smoke_MoE3GemmCompressedOffload.*WP=u3_DS=full.*)"),
#if defined(_WIN32)
// by calc abs_threshold with expected value
@@ -187,10 +191,10 @@ const std::vector<std::regex>& disabled_test_patterns() {
patterns.push_back(std::regex(R"(.*smoke_ScaledAttnStatic_GPU/ScaledAttnLayerGPUTest.CompareWithRefs/netPRC=(f16|f32)_.*)"));
patterns.push_back(std::regex(R"(.*smoke_ConvolutionLayerGPUTest_3D_tensor_basic/ConvolutionLayerGPUTest..*)"));
// oneDNN FC: grouped scales with group_size not aligned to 16 are rejected
- patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_corner_cases_basic/.*group_size=4_weights_precision=(u8|u4|i4)_.*)"));
- patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_basic/.*weights_shape=\[16,32\]_group_size=2_weights_precision=(u8|u4|i4)_.*)"));
- // 4-bit constant weights with odd K: no kernel for padding_reorder_for_constant
- patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_basic/.*weights_shape=\[377,335\]_group_size=1111_weights_precision=(u4|i4)_.*)"));
+ patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_corner_cases_basic/.*group_size=4_weights_precision=(u8|u4|i4|u3)_.*)"));
+ patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_basic/.*weights_shape=\[16,32\]_group_size=2_weights_precision=(u8|u4|i4|u3)_.*)"));
+ // 3/4-bit constant weights with odd K: no kernel for padding_reorder_for_constant
+ patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_basic/.*weights_shape=\[377,335\]_group_size=1111_weights_precision=(u4|i4|u3)_.*)"));
// Non-transposed u4 weights + per-token dynamic quantization: no kernel found
patterns.push_back(std::regex(R"(.*smoke_MatMulCompressedWeights_dyn_quan/.*transpose_weights=0_.*_dyn_quan_group_size=9223372036854775807_.*)"));
} else {
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/matmul_weights_decompression.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/matmul_weights_decompression.cpp
index 659ad322736..6d7e841b008 100644
--- a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/matmul_weights_decompression.cpp
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/matmul_weights_decompression.cpp
@@ -269,7 +269,7 @@ TEST_P(MatmulWeightsDecompression, Inference) {
}
const std::vector<ov::element::Type> activations_precisions = {ov::element::f32, ov::element::f16};
-const std::vector<ov::element::Type> weights_precisions = {ov::element::u8, ov::element::u4, ov::element::i4, ov::element::u2};
+const std::vector<ov::element::Type> weights_precisions = {ov::element::u8, ov::element::u4, ov::element::i4, ov::element::u3, ov::element::u2};
const std::vector<bool> transpose_weights = {true, false};
const std::vector<bool> param_weights = {true, false};
const std::vector<ShapeParams> input_shapes_basic = {
@@ -599,4 +599,38 @@ INSTANTIATE_TEST_SUITE_P(smoke_MatMulCompressedWeights_input_4d,
::testing::Values(0),
::testing::Values(1.0f)),
MatmulWeightsDecompression::get_test_case_name);
+
+// Compressed FC (Qwen3-8B q_proj prefill shape) followed by a Transpose, which runs as a separate OCL kernel
+// reading the oneDNN gemm output on the same in-order queue without a host wait. A tail of the output channels can
+// still be in the non-coherent L1 and the Transpose reads stale data.
+// Needs a static shape and a non-oneDNN consumer: a oneDNN consumer or host read-back does not expose it.
+class MatmulWeightsDecompressionWithConsumer : public MatmulWeightsDecompression {
+protected:
+ void SetUp() override {
+ MatmulWeightsDecompression::SetUp();
+ const auto mat_mul = function->get_results()[0]->input_value(0);
+ const auto transpose_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {0, 2, 1});
+ const auto transpose = std::make_shared<ov::op::v1::Transpose>(mat_mul, transpose_order);
+ function = std::make_shared<ov::Model>(ov::OutputVector{transpose}, function->get_parameters(), "MatmulWeightsDecompressionWithConsumer");
+ }
+};
+
+TEST_P(MatmulWeightsDecompressionWithConsumer, Inference) {
+ run();
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_MatMulCompressedWeights_gemm_output_coherency,
+ MatmulWeightsDecompressionWithConsumer,
+ ::testing::Combine(::testing::Values(ShapeParams{{{}, {{1, 15, 4096}}}, {4096, 6144}, 128}),
+ ::testing::ValuesIn({ov::element::u4, ov::element::u3}),
+ ::testing::Values(ov::element::f16),
+ ::testing::Values(ov::element::f16),
+ ::testing::Values(true),
+ ::testing::Values(ov::test::utils::DecompressionType::full),
+ ::testing::Values(true),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(1.0f)),
+ MatmulWeightsDecompression::get_test_case_name);
} // namespace
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 b3d623d210f..94dfdd94bf3 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
@@ -2,8 +2,12 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <algorithm>
+
+#include "common_test_utils/file_utils.hpp"
#include "common_test_utils/node_builders/moe_builders.hpp"
#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/pass/serialize.hpp"
#include "openvino/runtime/intel_gpu/properties.hpp"
#include "shared_test_classes/base/ov_subgraph.hpp"
@@ -230,6 +234,103 @@ TEST_P(MoECompressedFusionTest, Inference) {
run();
}
+using MoECompressedOffloadParams = std::tuple<size_t, ov::element::Type, ov::test::utils::DecompressionType>;
+
+// The experts are streamed from the weights file on demand, so the model has to be read from a file.
+class MoECompressedOffloadTest : public testing::WithParamInterface<MoECompressedOffloadParams>, virtual public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<MoECompressedOffloadParams>& info) {
+ const auto& [offload_ratio, wp, ds] = info.param;
+ std::ostringstream result;
+ result << "OR=" << offload_ratio << "_WP=" << wp << "_DS=" << ds;
+ return result.str();
+ }
+
+protected:
+ void SetUp() override {
+ const auto& [offload_ratio, wp, ds] = GetParam();
+ targetDevice = ov::test::utils::DEVICE_GPU;
+ const auto caps = core->get_property(targetDevice, ov::device::capabilities);
+ if (std::find(caps.begin(), caps.end(), ov::intel_gpu::capability::HW_MATMUL) == caps.end()) {
+ GTEST_SKIP() << "MoE pipeline requires a systolic GPU (HW_MATMUL capability)";
+ }
+ inType = outType = inference_precision = ov::element::f16;
+ 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}}}});
+ function = ov::test::initMoE3GeMMSubgraph(moe_params,
+ ov::element::f16,
+ wp,
+ true,
+ ov::element::f16,
+ ov::element::f16,
+ ov::test::utils::DecompressionType::full,
+ ds,
+ false, // Keep serialized scales/ZPs in their broadcast shapes.
+ 128);
+ functionRefs = function->clone();
+
+ const auto file_prefix = ov::test::utils::generateTestFilePrefix();
+ xml_path = file_prefix + ".xml";
+ bin_path = file_prefix + ".bin";
+ ov::pass::Serialize(xml_path, bin_path).run_on_model(function);
+ function = core->read_model(xml_path);
+ configuration = {ov::hint::inference_precision(ov::element::f16),
+ ov::hint::performance_mode(ov::hint::PerformanceMode::LATENCY),
+ ov::hint::dynamic_quantization_group_size(0),
+ ov::intel_gpu::offload_ratio(offload_ratio),
+ ov::weights_path(bin_path)};
+ }
+
+ void compile_model() override {
+ ov::test::SubgraphBaseTest::compile_model();
+ ov::test::CheckNumberOfNodesWithType(compiledModel, "moe_3gemm_fused_compressed", 1);
+ }
+
+ void generate_inputs(const std::vector<ov::Shape>& target_input_static_shapes) override {
+ inputs.clear();
+ const auto& parameter = function->get_parameters().at(0);
+ // Bound FP16 accumulation error so this test isolates offloaded constant loading.
+ inputs.insert(
+ {parameter, ov::test::utils::create_and_fill_tensor_normal_distribution(ov::element::f16, target_input_static_shapes.at(0), 0.0f, 0.05f, 1234)});
+ }
+
+ void TearDown() override {
+ ov::test::SubgraphBaseTest::TearDown();
+ // The model and the compiled model keep the weights file mapped/open, which blocks its removal on Windows
+ inferRequest = {};
+ compiledModel = {};
+ function.reset();
+ ov::test::utils::removeIRFiles(xml_path, bin_path);
+ }
+
+private:
+ std::string xml_path;
+ std::string bin_path;
+};
+
+TEST_P(MoECompressedOffloadTest, Inference) {
+ run();
+}
+
+// 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::Values(ov::element::u3),
+ ::testing::Values(ov::test::utils::DecompressionType::full,
+ ov::test::utils::DecompressionType::scalar,
+ ov::test::utils::DecompressionType::empty)),
+ MoECompressedOffloadTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload,
+ MoECompressedOffloadTest,
+ ::testing::Combine(::testing::Values(size_t{50}),
+ ::testing::Values(ov::element::u8, ov::element::u4),
+ ::testing::Values(ov::test::utils::DecompressionType::full, ov::test::utils::DecompressionType::empty)),
+ MoECompressedOffloadTest::getTestCaseName);
+
// GatherMatmul and fused MoE kernels support only f16 activations, so the MoE pipeline must be applied
// only if the activations are f16 after ConvertPrecision, regardless of OV_GPU_MOE_DISABLE_FUSION.
// Note: with dynamic inference precision, the model precision is kept.
@@ -355,6 +456,45 @@ 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.
+// Scalar zp is the NNCF int3 layout (symmetric u3 with zp = 4 for all experts).
+const std::vector<MoeTestShapeParams> moe_params_smoke_u3 = {
+ {
+ {{-1, -1, 256}, {{1, 40, 256}, {1, 1, 256}, {1, 3, 256}, {1, 40, 256}}}, // prefill > gemv threshold + decode
+ 4, // topk
+ 8, // number_of_experts
+ 512 // intermediate_size
+ },
+ {
+ {{-1, -1, 2048}, {{1, 4, 2048}, {1, 1, 2048}}}, // prefill + decode
+ 4, // topk
+ 8, // number_of_experts
+ 512 // intermediate_size
+ },
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedFusion_u3,
+ MoECompressedFusionTest,
+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke_u3),
+ ::testing::Values(MoePatternType::GEMM3),
+ ::testing::ValuesIn(routing_types),
+ ::testing::Values(ov::element::u3),
+ ::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,
+ ov::test::utils::DecompressionType::empty),
+ ::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::SWISH),
+ ::testing::Values(false), // use_per_expert_scale
+ ::testing::Values(false), // use_layernorm_multiply
+ ::testing::Values(true)), // use_weight_decompression
+ MoECompressedFusionTest::getTestCaseName);
+
// GPT-OSS 2-GEMM pattern (combined gate/up MatMul + Slice/Clamp/Add/Swish).
// gate_idx=0 matches real gpt-oss IR; gate_idx=1 covers the inverted layout.
INSTANTIATE_TEST_SUITE_P(smoke_MoE2GemmCompressedFusion,
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
index 64eb8144c40..1a0ee594d01 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
@@ -6506,8 +6506,8 @@ INSTANTIATE_TEST_SUITE_P(fully_connected_bf_tiled_dyn_b_accuracy,
// With post-op eltwise
std::make_tuple(16L, 256L, 1024L, true)));
-// Parameterized test fixture for UINT2 fully connected kernel across various matrix dimensions
-class fully_connected_gpu_u2_validation : public ::testing::TestWithParam<std::tuple<int, int, int, int, int, bool>> {
+// Common parameterized fixture for sub-byte (UINT2, UINT3) fully connected kernel tests across various matrix dimensions
+class fully_connected_gpu_sub_byte_validation : public ::testing::TestWithParam<std::tuple<int, int, int, int, int, bool>> {
public:
static std::string GetTestCaseName(const testing::TestParamInfo<std::tuple<int, int, int, int, int, bool>>& obj) {
int batch = std::get<0>(obj.param);
@@ -6525,6 +6525,8 @@ public:
}
};
+class fully_connected_gpu_u2_validation : public fully_connected_gpu_sub_byte_validation {};
+
// Validates UINT2 decompression correctness across multiple sizes using random data vs inline CPU-computed reference
TEST_P(fully_connected_gpu_u2_validation, various_sizes) {
auto& engine = get_test_engine();
@@ -7008,6 +7010,119 @@ TEST(fully_connected_gpu_ternocl_int2_dynamic, non_ternary_zero_point_falls_back
ASSERT_NE(net->get_primitive("fc_prim")->get_impl()->get_kernel_name(), "ternocl_int2");
}
+class fully_connected_gpu_u3_validation : public fully_connected_gpu_sub_byte_validation {};
+
+// Validates UINT3 decompression correctness in the reference kernel. u3 is a tightly packed LSB-first bit stream,
+// so values straddle byte boundaries and rows are not byte-aligned when ifm_num * 3 is not a multiple of 8
+TEST_P(fully_connected_gpu_u3_validation, various_sizes) {
+ auto& engine = get_test_engine();
+
+ const int batch_num = std::get<0>(GetParam());
+ const int ifm_num = std::get<1>(GetParam());
+ const int ofm_num = std::get<2>(GetParam());
+ const int scales_group_size = std::get<3>(GetParam());
+ const int seq_len = std::get<4>(GetParam()); // 1 = 2D path, >1 = 3D (OUTPUT_3D) path
+ const bool use_zp = std::get<5>(GetParam());
+ const bool is_3d = seq_len > 1;
+
+ ASSERT_EQ(ifm_num % scales_group_size, 0) << "ifm_num must be multiple of scales_group_size";
+
+ auto input_shape = is_3d ? ov::PartialShape{batch_num, seq_len, ifm_num} : ov::PartialShape{batch_num, ifm_num};
+ auto input_mem = engine.allocate_memory({input_shape, data_types::f16, format::bfyx});
+ auto weights_mem = engine.allocate_memory({{ofm_num, ifm_num}, data_types::u3, format::bfyx});
+ auto scale_mem = engine.allocate_memory({{ofm_num, ifm_num / scales_group_size}, data_types::f16, format::bfyx});
+ auto zp_mem = use_zp ? engine.allocate_memory({{ofm_num, ifm_num / scales_group_size}, data_types::f16, format::bfyx}) : nullptr;
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ const int input_elems = is_3d ? batch_num * seq_len * ifm_num : batch_num * ifm_num;
+ auto input_data = rg.generate_random_1d<ov::float16>(input_elems, -1.0f, 1.0f);
+ set_values(input_mem, input_data);
+
+ const size_t weights_count = static_cast<size_t>(ofm_num) * ifm_num;
+ auto unpacked_weights = rg.generate_random_1d<uint8_t>(weights_count, 0, 7, 1);
+ std::vector<uint8_t> packed_weights((weights_count * 3 + 7) / 8, 0);
+ for (size_t i = 0; i < weights_count; ++i) {
+ const uint32_t bits = static_cast<uint32_t>(unpacked_weights[i] & 0x7) << ((i * 3) % 8);
+ const size_t byte_idx = i * 3 / 8;
+ packed_weights[byte_idx] |= static_cast<uint8_t>(bits);
+ if (bits > 0xFF)
+ packed_weights[byte_idx + 1] |= static_cast<uint8_t>(bits >> 8);
+ }
+ ASSERT_EQ(weights_mem->size(), packed_weights.size());
+ set_values(weights_mem, packed_weights);
+
+ auto scale_data = rg.generate_random_1d<ov::float16>(ofm_num * ifm_num / scales_group_size, 0.5f, 2.0f);
+ set_values(scale_mem, scale_data);
+
+ std::vector<ov::float16> zp_data;
+ if (use_zp) {
+ zp_data = rg.generate_random_1d<ov::float16>(ofm_num * ifm_num / scales_group_size, 2.5f, 4.5f);
+ set_values(zp_mem, zp_data);
+ }
+
+ auto in_layout = layout{input_shape, data_types::f16, format::bfyx};
+ const int input_size = is_3d ? 3 : 2;
+
+ topology topology(input_layout("input", in_layout), data("weights", weights_mem), data("scale", scale_mem));
+ if (use_zp)
+ topology.add(data("zp", zp_mem));
+ topology.add(fully_connected("fc_prim", input_info("input"), "weights", "", "scale", use_zp ? "zp" : "", data_types::f16, input_size, 2));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ ov::intel_gpu::ImplementationDesc fc_impl_desc = {format::bfyx, "fully_connected_gpu_bfyx_ref", impl_types::ocl};
+ config.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{{"fc_prim", fc_impl_desc}}));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+
+ network::ptr network = get_network(engine, topology, config, get_test_stream_ptr(), false);
+ network->set_input_data("input", input_mem);
+
+ auto outputs = network->execute();
+ ASSERT_EQ(outputs.size(), size_t(1));
+ ASSERT_EQ(outputs.begin()->first, "fc_prim");
+
+ auto output_mem = outputs.begin()->second.get_memory();
+ cldnn::mem_lock<ov::float16> output_ptr(output_mem, get_test_stream());
+
+ const int outer_count = is_3d ? batch_num * seq_len : batch_num;
+ std::vector<float> expected_output(outer_count * ofm_num);
+ for (int n = 0; n < outer_count; ++n) {
+ for (int ofm = 0; ofm < ofm_num; ++ofm) {
+ float acc = 0.0f;
+ for (int ifm = 0; ifm < ifm_num; ++ifm) {
+ int group_id = ifm / scales_group_size;
+ uint8_t weight_u3 = unpacked_weights[ofm * ifm_num + ifm];
+ float scale = static_cast<float>(scale_data[ofm * (ifm_num / scales_group_size) + group_id]);
+ float zp = use_zp ? static_cast<float>(zp_data[ofm * (ifm_num / scales_group_size) + group_id]) : 0.0f;
+ float weight_f16 = (static_cast<float>(weight_u3) - zp) * scale;
+ float inp = static_cast<float>(input_data[n * ifm_num + ifm]);
+ acc += inp * weight_f16;
+ }
+ expected_output[n * ofm_num + ofm] = acc;
+ }
+ }
+
+ ASSERT_EQ(output_ptr.size(), expected_output.size());
+ for (size_t i = 0; i < expected_output.size(); ++i) {
+ ASSERT_NEAR(expected_output[i], static_cast<float>(output_ptr[i]), 2.0f) << "Mismatch at output index " << i;
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ fully_connected_gpu_u3_validation,
+ ::testing::Values(std::make_tuple(1, 8, 4, 8, 1, false), // minimum byte-aligned row
+ std::make_tuple(2, 16, 8, 4, 1, false), // multiple batches, small group size
+ std::make_tuple(4, 64, 32, 32, 1, false), // multiple groups per row
+ std::make_tuple(1, 512, 256, 128, 1, false), // larger dimensions
+ std::make_tuple(2, 12, 7, 4, 1, false), // rows not byte-aligned, odd ofm_num
+ std::make_tuple(2, 60, 63, 4, 1, false), // rows not byte-aligned, many groups
+ std::make_tuple(2, 12, 4, 4, 3, false), // 3D (OUTPUT_3D) path
+ std::make_tuple(2, 16, 8, 4, 1, true), // with zero-point
+ std::make_tuple(1, 60, 33, 12, 1, true), // zero-point, rows not byte-aligned
+ std::make_tuple(2, 12, 5, 4, 3, true) // 3D with zero-point
+ ),
+ fully_connected_gpu_u3_validation::GetTestCaseName);
+
#ifdef ENABLE_ONEDNN_FOR_GPU
namespace {
struct onednn_int4_fc_params {
diff --git a/src/tests/test_utils/common_test_utils/src/subgraph_builders/weights_decompression_builders.cpp b/src/tests/test_utils/common_test_utils/src/subgraph_builders/weights_decompression_builders.cpp
index b07cabbe0aa..7cb35dbf1cf 100644
--- a/src/tests/test_utils/common_test_utils/src/subgraph_builders/weights_decompression_builders.cpp
+++ b/src/tests/test_utils/common_test_utils/src/subgraph_builders/weights_decompression_builders.cpp
@@ -221,11 +221,12 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
const std::optional<bool>& insert_transpose_node,
const size_t seed) {
// Validate that the precision is supported for real quantization
- OPENVINO_ASSERT(weights_precision == ov::element::u2 || weights_precision == ov::element::u4 ||
- weights_precision == ov::element::i4 || weights_precision == ov::element::u8 ||
- weights_precision == ov::element::i8,
- "initMatMulDecompressionSubgraphQuantization only supports u2, u4, i4, u8, i8 precisions. Got: ",
- weights_precision);
+ OPENVINO_ASSERT(
+ weights_precision == ov::element::u2 || weights_precision == ov::element::u3 ||
+ weights_precision == ov::element::u4 || weights_precision == ov::element::i4 ||
+ weights_precision == ov::element::u8 || weights_precision == ov::element::i8,
+ "initMatMulDecompressionSubgraphQuantization only supports u2, u3, u4, i4, u8, i8 precisions. Got: ",
+ weights_precision);
auto transpose_if_necessary = [&](const ov::Shape& shape) {
auto result_shape = shape;
@@ -293,11 +294,13 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
// Calculate quantization parameters
const auto qmin = weights_precision == ov::element::u2 ? 0.0f
+ : weights_precision == ov::element::u3 ? 0.0f
: weights_precision == ov::element::i4 ? -8.0f
: weights_precision == ov::element::u4 ? 0.0f
: weights_precision.is_signed() ? -128.0f
: 0.0f;
const auto qmax = weights_precision == ov::element::u2 ? 3.0f
+ : weights_precision == ov::element::u3 ? 7.0f
: weights_precision == ov::element::i4 ? 7.0f
: weights_precision == ov::element::u4 ? 15.0f
: weights_precision.is_signed() ? 127.0f
@@ -377,7 +380,8 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
};
// Quantize based on weights_precision type
- if (weights_precision == ov::element::u2 || weights_precision == ov::element::u4) {
+ if (weights_precision == ov::element::u2 || weights_precision == ov::element::u3 ||
+ weights_precision == ov::element::u4) {
// For sub-byte unsigned types, use element::iterator
std::vector<uint8_t> quantized_buffer(total_size);
for (size_t i = 0; i < total_size; ++i) {
@@ -388,6 +392,9 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
if (weights_precision == ov::element::u4) {
auto iter = ov::element::iterator<ov::element::u4>(quantized_weights_tensor.data());
std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);
+ } else if (weights_precision == ov::element::u3) {
+ auto iter = ov::element::iterator<ov::element::u3>(quantized_weights_tensor.data());
+ std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);
} else {
auto iter = ov::element::iterator<ov::element::u2>(quantized_weights_tensor.data());
std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);
@@ -443,6 +450,9 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
} else if (weights_precision == ov::element::u2) {
auto iter = ov::element::iterator<ov::element::u2>(shift_tensor.data());
*iter = static_cast<uint8_t>(std::round(avg_zp));
+ } else if (weights_precision == ov::element::u3) {
+ auto iter = ov::element::iterator<ov::element::u3>(shift_tensor.data());
+ *iter = static_cast<uint8_t>(std::round(avg_zp));
} else if (weights_precision == ov::element::i4) {
auto iter = ov::element::iterator<ov::element::i4>(shift_tensor.data());
*iter = static_cast<int8_t>(std::round(avg_zp));
@@ -467,6 +477,13 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(
}
auto iter = ov::element::iterator<ov::element::u2>(shift_tensor.data());
std::copy(zp_buffer.begin(), zp_buffer.end(), iter);
+ } else if (weights_precision == ov::element::u3) {
+ std::vector<uint8_t> zp_buffer(num_groups);
+ for (size_t i = 0; i < num_groups; ++i) {
+ zp_buffer[i] = static_cast<uint8_t>(std::round(zero_points[i]));
+ }
+ auto iter = ov::element::iterator<ov::element::u3>(shift_tensor.data());
+ std::copy(zp_buffer.begin(), zp_buffer.end(), iter);
} else if (weights_precision == ov::element::i4) {
std::vector<int8_t> zp_buffer(num_groups);
for (size_t i = 0; i < num_groups; ++i) {