Skip to content

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

[GPU] CM u2 weight-compressed FullyConnected (XMX/DPAS) (#38894)

vmadananth7f9cf107a128
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
index 025ba5394b6..94b85aa273a 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_primitive_fusing.cpp
@@ -52,10 +52,15 @@
#include "space_to_depth_inst.h"
#include "strided_slice_inst.h"
#include "swiglu_inst.h"
+#include "registry/registry.hpp"
#ifdef ENABLE_ONEDNN_FOR_GPU
#include <impls/onednn/utils.hpp>
#endif
+#if OV_GPU_WITH_CM
+#include "impls/cm/fully_connected_woq_u2.hpp"
+#endif
+
using namespace cldnn;
void prepare_primitive_fusing::run(program& p) {
@@ -498,6 +503,15 @@ void prepare_primitive_fusing::fuse_bias(program &p) {
} else if (replace_candidate.is_type<fully_connected>()) {
auto& fc = replace_candidate.as<fully_connected>();
auto desc = fc.get_primitive();
+#if OV_GPU_WITH_CM
+ if (fc.get_input_layout(1).data_type == data_types::u2 && ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::accepts_post_op_fusion(fc)) {
+ const auto N = ov::intel_gpu::op::fc_weight_dims(fc.get_input_layout(1).get_partial_shape(), desc->weights_layout).N.get_length();
+ if (!fc.get_fused_primitives().empty() ||
+ !ov::intel_gpu::cm::woq_u2_check_epi_operand(bias_node.get_output_layout(), eltw_node.get_output_layout(), N).empty()) {
+ continue;
+ }
+ }
+#endif
// If the primitive has biases, then we try to combine the values, or do nothing and keep as fused sum.
if (fc.bias_term()) {
@@ -611,13 +625,19 @@ void prepare_primitive_fusing::fuse_simple_primitives(program &p) {
GPU_DEBUG_TRACE_DETAIL << node.id() << " has fused swiglu. Skip fusing more primitives" << std::endl;
return false;
}
- if (lo.has_all_enabled_onednn_impls_optimization_attribute() &&
- lo.get_preferred_impl_type(node, format::any /*dummy*/) == impl_types::onednn) {
+#if OV_GPU_WITH_CM
+ // u2 FCs the CM kernels can run take post-ops in static shapes too: the kernels apply a bias /
+ // fused add / fused SwiGLU themselves. A bias and fused primitives cannot be combined.
+ if (node.get_input_layout(1).data_type == data_types::u2 &&
+ ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::accepts_post_op_fusion(node)) {
+ return !node.bias_term();
+ }
+#endif
+ if (lo.has_all_enabled_onednn_impls_optimization_attribute() && lo.get_preferred_impl_type(node, format::any /*dummy*/) == impl_types::onednn) {
return true;
}
auto in_dt = node.get_input_layout(0).data_type;
return node.is_dynamic() || data_type_traits::is_i8_u8(in_dt);
-
};
auto gemm_supports_fusings = [](gemm_node& node) -> bool {
@@ -962,6 +982,37 @@ void prepare_primitive_fusing::fuse_simple_primitives(program &p) {
if (!should_fuse)
return;
+#if OV_GPU_WITH_CM
+ if (input.is_type<fully_connected>() && input.get_input_layout(1).data_type == data_types::u2 &&
+ ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::accepts_post_op_fusion(input)) {
+ auto& fc = input.as<fully_connected>();
+ const auto act_prim = activation_node.get_primitive();
+ bool can_form_swiglu = !fc.bias_term() && fc.get_fused_primitives().empty() && !activation_node.has_fused_primitives() &&
+ act_prim->activation_function == activation_func::swish && !act_prim->additional_params_input.is_valid() &&
+ act_prim->additional_params.a == 1.0f && activation_node.get_users().size() == 1;
+ if (can_form_swiglu) {
+ auto& user = *activation_node.get_users().front();
+ if (!user.is_type<eltwise>() || user.is_output() || user.has_fused_primitives() || user.get_inputs_count() != 2) {
+ can_form_swiglu = false;
+ } else {
+ const auto eltw_prim = user.as<eltwise>().get_primitive();
+ const auto& deps = user.get_dependencies();
+ const auto& peer = *(deps[0].first == &activation_node ? deps[1].first : deps[0].first);
+ const auto N =
+ ov::intel_gpu::op::fc_weight_dims(fc.get_input_layout(1).get_partial_shape(), fc.get_primitive()->weights_layout).N.get_length();
+ const bool coeffs_ok = std::all_of(eltw_prim->coefficients.begin(), eltw_prim->coefficients.end(), [](float c) {
+ return c == 1.0f;
+ });
+ can_form_swiglu = eltw_prim->mode == eltwise_mode::prod && eltw_prim->stride.empty() && coeffs_ok && &peer != &fc &&
+ ov::intel_gpu::cm::woq_u2_check_epi_operand(peer.get_output_layout(), user.get_output_layout(), N).empty();
+ }
+ }
+ if (!can_form_swiglu) {
+ return;
+ }
+ }
+#endif
+
// Onednn reorder does not support eltwise nor binary post operation
if (lo.has_all_enabled_onednn_impls_optimization_attribute() && input.is_type<reorder>()) {
return;
@@ -1087,6 +1138,13 @@ void prepare_primitive_fusing::fuse_simple_primitives(program &p) {
if (!should_fuse)
return;
+#if OV_GPU_WITH_CM
+ if (input_data.is_type<fully_connected>() && input_data.get_input_layout(1).data_type == data_types::u2 &&
+ ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::accepts_post_op_fusion(input_data)) {
+ return;
+ }
+#endif
+
p.fuse_nodes(input_data, quantize_node, &fusing_history);
};
@@ -1206,6 +1264,32 @@ void prepare_primitive_fusing::fuse_simple_primitives(program &p) {
can_fuse_parents[1] = can_fuse_parents[1] && are_compatible(out_pshape, parent2_pshape);
}
+#if OV_GPU_WITH_CM
+ // A u2 FC eligible for the CM kernels (including any GNK FC) can only fuse post-ops supported by
+ // woq_u2_epilogue and woq_u2_check_epi_operand: a single eltwise::sum, or eltwise::prod completing SwiGLU.
+ for (size_t i = 0; i < parents.size(); i++) {
+ auto& fc = *parents[i].first;
+ if (!can_fuse_parents[i] || !fc.is_type<fully_connected>() || fc.get_input_layout(1).data_type != data_types::u2 ||
+ !fc.get_input_layout(1).is_static() || !ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::accepts_post_op_fusion(fc)) {
+ continue;
+ }
+ const auto& fc_node = fc.as<fully_connected>();
+ const auto& fused = fc_node.get_fused_primitives();
+ const bool coeffs_ok = std::all_of(prim->coefficients.begin(), prim->coefficients.end(), [](float c) {
+ return c == 1.0f;
+ });
+ const bool mode_ok = !fc_node.bias_term() && !node.has_fused_primitives() && coeffs_ok &&
+ ((fused.empty() && prim->mode == eltwise_mode::sum) ||
+ (fused.size() == 1 && fused[0].is_type<activation>() && prim->mode == eltwise_mode::prod));
+ const auto N =
+ ov::intel_gpu::op::fc_weight_dims(fc.get_input_layout(1).get_partial_shape(), fc_node.get_primitive()->weights_layout).N.get_length();
+ const auto& peer = *parents[parents.size() - 1 - i].first;
+ if (!mode_ok || !ov::intel_gpu::cm::woq_u2_check_epi_operand(peer.get_output_layout(), node.get_output_layout(), N).empty()) {
+ can_fuse_parents[i] = false;
+ }
+ }
+#endif
+
// We should have at least one node to fuse
if (!can_fuse_parents[0] && !can_fuse_parents[1])
return;
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
index fc3d6ebcbba..ec0553f52f5 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp
@@ -553,14 +553,15 @@ bool prepare_quantization::optimize_quantize(program &p, quantize_node& quantize
return true;
}
-static void optimize_weights_decompression_parameters(fully_connected_node& fc_node, program& p) {
+std::vector<program_node*> cldnn::reorder_fc_decompression_params_if_needed(fully_connected_node& fc_node, program& p) {
auto fc_prim = fc_node.get_primitive();
+ std::vector<program_node*> new_reorders;
// Grouped scale/zp of non-transposed weights [K, N] are [K / G, N], so they already have the [groups, N] physical layout.
if (!fc_prim->compressed_weights || !fc_prim->weights_transposed)
- return;
+ return new_reorders;
// The reorder below assumes NK / KN weight ranks.
if (fc_prim->weights_layout == ov::intel_gpu::op::FcWeightsLayout::GNK)
- return;
+ return new_reorders;
auto reorder_bfyx = [&](size_t dep_id, cldnn::format format) {
auto& dep = fc_node.get_dependency(dep_id);
@@ -569,6 +570,7 @@ static void optimize_weights_decompression_parameters(fully_connected_node& fc_n
auto reorder_prim = std::make_shared<reorder>(dep.id() + "_reorder_" + fc_node.id(), dep.id(), target_layout);
p.add_intermediate(reorder_prim, fc_node, dep_id, true);
fc_node.get_dependency(dep_id).recalc_output_layout(false);
+ new_reorders.push_back(&fc_node.get_dependency(dep_id));
};
auto need_reorder = [&](size_t dep_id, size_t weight_rank, bool transpose_b_param) {
@@ -604,18 +606,32 @@ static void optimize_weights_decompression_parameters(fully_connected_node& fc_n
if (weight_rank == 3)
format = format::byfx;
+ // Already in the target layout (e.g. reordered earlier): a second reorder would be a no-op.
+ auto reorder_needed = [&](size_t dep_id, bool transpose_b_param) {
+ return need_reorder(dep_id, weight_rank, transpose_b_param) && fc_node.get_input_layout(dep_id).format != format;
+ };
+
auto decompression_scale_idx = !fc_node.bias_term() ? 2 : 3;
// OCL/oneDNN kernel requires decompression scale/zp in layout where scale_ofm dimension is innermost
- if (need_reorder(decompression_scale_idx, weight_rank, fc_prim->transpose_b_scale)) {
+ if (reorder_needed(decompression_scale_idx, fc_prim->transpose_b_scale)) {
reorder_bfyx(decompression_scale_idx, format);
}
if (fc_prim->decompression_zero_point.is_valid()) {
auto decompression_zp_idx = decompression_scale_idx + 1;
- if (need_reorder(decompression_zp_idx, weight_rank, fc_prim->transpose_b_zp)) {
+ if (reorder_needed(decompression_zp_idx, fc_prim->transpose_b_zp)) {
reorder_bfyx(decompression_zp_idx, format);
}
}
+ return new_reorders;
+}
+
+static void optimize_weights_decompression_parameters(fully_connected_node& fc_node, program& p) {
+ // u2: whether scale/zp need a reorder depends on the selected impl (CM takes them as they are); decided in select_preferred_formats.
+ if (defer_u2_decompression_reorder(fc_node))
+ return;
+
+ reorder_fc_decompression_params_if_needed(fc_node, p);
}
// Reorder per-group scales/zp to byfx so physical layout is [E, G, N, 1] (N innermost for SIMD reads).
diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/select_preferred_formats.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/select_preferred_formats.cpp
index 455fece2980..046d66d7c70 100644
--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/select_preferred_formats.cpp
+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/select_preferred_formats.cpp
@@ -16,6 +16,11 @@
#include "intel_gpu/runtime/itt.hpp"
#include "intel_gpu/runtime/debug_configuration.hpp"
#include "to_string_utils.h"
+#include "fully_connected_inst.h"
+#include "registry/registry.hpp"
+#if OV_GPU_WITH_CM
+#include "impls/cm/fully_connected_woq_u2.hpp"
+#endif
#include <iostream>
#include <sstream>
#include <intel_gpu/primitives/fully_connected.hpp>
@@ -180,10 +185,11 @@ void select_preferred_formats::run(program& p) {
auto forcing_map = p.get_config().get_force_implementations();
- for (auto* n : p.get_processing_order()) {
+ // Returns the chosen factory, if any.
+ auto select_formats_for = [&](program_node* n) -> std::shared_ptr<ImplementationManager> {
n->recalc_output_layout();
if (n->is_input() || !n->is_in_data_flow()) {
- continue;
+ return nullptr;
}
auto forced_fmt = format::any;
@@ -230,7 +236,8 @@ void select_preferred_formats::run(program& p) {
GPU_DEBUG_LOG << "WARNING(select_preferred_formats): " << exception.what() << std::endl;
}
print_selected_formats(*n);
- } if (n->is_type<fully_connected>()) {
+ }
+ if (n->is_type<fully_connected>()) {
const auto& fc_prim = n->as<fully_connected>().get_primitive();
size_t decompression_param_idx =
fc_prim->bias.is_valid() ? 3 : 2;
@@ -246,9 +253,41 @@ void select_preferred_formats::run(program& p) {
decompression_param_idx++;
} if (fc_prim->decompression_zero_point.is_valid()) {
if (n->get_preferred_input_fmt(decompression_param_idx) == format::any) {
- n->set_preferred_input_fmt(
- decompression_param_idx,
- n->get_input_layout(decompression_param_idx).format);
+ n->set_preferred_input_fmt(decompression_param_idx, n->get_input_layout(decompression_param_idx).format);
+ }
+ }
+ }
+ return factory;
+ };
+
+ for (auto* n : p.get_processing_order()) {
+ auto factory = select_formats_for(n);
+
+ // u2 scale/zp were left bfyx by prepare_quantization; CM keeps them, other impls get the usual reorder.
+ if (n->is_type<fully_connected>()) {
+ auto& fc_node = n->as<fully_connected>();
+ if (defer_u2_decompression_reorder(fc_node)) {
+ bool cm_selected = false;
+#if OV_GPU_WITH_CM
+ cm_selected = factory && factory->get_type_info() == ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::get_type_info_static();
+#else
+ (void)factory;
+#endif
+ GPU_DEBUG_TRACE_DETAIL << fc_node.id() << " : u2 FC, CM " << (cm_selected ? "selected, scale/zp kept bfyx" : "not selected") << std::endl;
+ if (!cm_selected) {
+ // New reorders precede fc_node in processing order, so the main loop would skip them.
+ for (auto* new_reorder : reorder_fc_decompression_params_if_needed(fc_node, p)) {
+ select_formats_for(new_reorder);
+ }
+ const auto& fc_prim = fc_node.get_primitive();
+ size_t decompression_param_idx = fc_prim->bias.is_valid() ? 3 : 2;
+ if (fc_prim->decompression_scale.is_valid()) {
+ fc_node.set_preferred_input_fmt(decompression_param_idx, fc_node.get_input_layout(decompression_param_idx).format);
+ decompression_param_idx++;
+ }
+ if (fc_prim->decompression_zero_point.is_valid()) {
+ fc_node.set_preferred_input_fmt(decompression_param_idx, fc_node.get_input_layout(decompression_param_idx).format);
+ }
}
}
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.cpp
new file mode 100644
index 00000000000..4022224952f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.cpp
@@ -0,0 +1,229 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "fully_connected_woq_u2.hpp"
+
+#include "common_utils/kernel_generator_base.hpp"
+#include "primitive_cm_base.hpp"
+#include "primitive_inst.h"
+#include "registry/implementation_manager.hpp"
+#include "utils/kernel_generator.hpp"
+
+namespace ov::intel_gpu::cm {
+namespace {
+
+// Tiled kernel work decomposition (must match woq_u2_gemm_dual.cm defaults NCOL=2, MROWS=32,
+// WG_M=WG_N=8): one 8 x 8 work-group computes a 256 x 256 tile, each thread 32 rows x 32 columns.
+constexpr size_t wg_n = 8;
+constexpr size_t wg_m = 8;
+constexpr size_t cols_per_thread = 32;
+constexpr size_t rows_per_thread = 32;
+
+// GEMV kernel (woq_u2_gemm_dual_gemv.cm, built with NCB=1, RBG=1, LS=16, PFG=4): each thread computes
+// 16 columns x 8 rows over all of K, LS threads per work-group, no SLM. Used when M <= gemv_max_m.
+constexpr size_t gemv_cols_per_thread = 16; // 16 * NCB
+constexpr size_t gemv_rows_per_thread = 8; // 8 * RBG
+constexpr size_t gemv_ls = 16; // LS
+constexpr size_t gemv_max_m = 8;
+// Above this many 16-column blocks each GEMV thread takes 2 adjacent blocks (cseq = 2); passed to the kernel
+// as GEMV_MAXT, so the grid below and the kernel's own choice always agree.
+constexpr size_t gemv_maxt = 960;
+
+// M = product of the activation's leading dims (static params only).
+size_t rows_of(const RuntimeParams& params) {
+ const auto& in_shape = params.get_input_layout(0).get_shape();
+ size_t M = 1;
+ for (size_t i = 0; i + 1 < in_shape.size(); i++) {
+ M *= in_shape[i];
+ }
+ return M;
+}
+
+bool has_bias(const RuntimeParams& params) {
+ return params.bias_layout.has_value();
+}
+
+bool is_gnk(const RuntimeParams& params) {
+ return params.typed_desc<fully_connected>()->weights_layout == ov::intel_gpu::op::FcWeightsLayout::GNK;
+}
+
+// {N, K} of the FC from its weights and weights_layout.
+std::pair<size_t, size_t> woq_u2_dims(const RuntimeParams& params) {
+ const auto dims = ov::intel_gpu::op::fc_weight_dims(params.get_input_layout(1).get_partial_shape(), params.typed_desc<fully_connected>()->weights_layout);
+ return {static_cast<size_t>(dims.N.get_length()), static_cast<size_t>(dims.K.get_length())};
+}
+
+// The epilogue (epi_mode and the dependency providing its tensor) of this FC; validate_impl guarantees it
+// is supported (create_impl asserts it).
+WoqU2Epilogue epilogue_of(const RuntimeParams& params) {
+ return woq_u2_epilogue(params.fused_desc, has_bias(params));
+}
+
+// Shared by both kernels: same ABI, JIT constants and scalars; they differ in source, build options and
+// launch grid.
+class WoqU2GeneratorBase : public KernelGenerator {
+public:
+ using KernelGenerator::KernelGenerator;
+
+protected:
+ [[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {
+ auto jit = KernelGenerator::get_jit_constants(params);
+ const auto epi = epilogue_of(params);
+ const bool epi_f16 = epi.dep >= 0 && params.get_input_layout(static_cast<size_t>(epi.dep)).data_type == data_types::f16;
+ jit.add({
+ make_jit_constant("KERNEL_NAME", get_entry_point(params)),
+ // GNK FCs are group-major; NK FCs are N-major unless a test selected the group-major path.
+ make_jit_constant("WLAYOUT",
+ is_gnk(params) ? static_cast<int>(WoqU2WeightLayout::group_major) : static_cast<int>(woq_u2_weight_layout_for_tests())),
+ make_jit_constant("OUT_F16", params.get_output_layout(0).data_type == data_types::f16 ? 1 : 0),
+ make_jit_constant("EPI_F16", epi_f16 ? 1 : 0), // epilogue tensor is half
+ });
+ return jit;
+ }
+
+ [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {
+ // Kernel ABI: (A, Wq, scales, zps, epi, C, M, K, N, epi_mode). epi is the epilogue tensor (FC bias,
+ // fused add operand or SwiGLU multiply operand, see woq_u2_epilogue); without an epilogue
+ // (epi_mode = 0) the kernel never reads it and the output buffer is bound in its place.
+ const bool bias = has_bias(params);
+ Arguments args;
+ args.push_back({ArgumentDescriptor::Types::INPUT, 0}); // A
+ args.push_back({ArgumentDescriptor::Types::INPUT, 1}); // Wq
+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(woq_u2_scale_idx(bias))}); // scales
+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(woq_u2_zp_idx(bias))}); // zero points (u8)
+ const auto epi = epilogue_of(params);
+ if (epi.dep >= 0) {
+ args.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(epi.dep)}); // epi
+ } else {
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0}); // epi (unused, epi_mode = 0)
+ }
+ args.push_back({ArgumentDescriptor::Types::OUTPUT, 0}); // C
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 0}); // M
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 1}); // K
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 2}); // N
+ args.push_back({ArgumentDescriptor::Types::SCALAR, 3}); // epi_mode
+ return args;
+ }
+
+ // Scalars (M, K, N, epi_mode) of either kernel.
+ static void set_scalars(const RuntimeParams& params, KernelData& kd, size_t M) {
+ const auto [N, K] = woq_u2_dims(params);
+ auto& scalars = kd.params.scalars;
+ scalars.resize(4);
+ // epi_mode from the actual bias / fused pattern: 0 none, 1 acc + epi, 2 swish(acc) * epi.
+ const int32_t epi_mode = epilogue_of(params).mode;
+ const size_t vals[4] = {M, K, N, static_cast<size_t>(epi_mode)};
+ for (size_t i = 0; i < 4; i++) {
+ scalars[i].t = ScalarDescriptor::Types::INT32;
+ scalars[i].v.s32 = static_cast<int32_t>(vals[i]);
+ }
+ }
+};
+
+// Tiled DPAS kernel (woq_u2_gemm_dual.cm): M > gemv_max_m.
+class WoqU2TiledGenerator : public WoqU2GeneratorBase {
+public:
+ WoqU2TiledGenerator() : WoqU2GeneratorBase("woq_u2_gemm_dual") {}
+
+protected:
+ [[nodiscard]] std::string get_build_options(const RuntimeParams& params) const override {
+ return KernelGenerator::get_build_options(params) + " -Qxcm_register_file_size=128 ";
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ assert(!params.is_dynamic());
+ const size_t N = woq_u2_dims(params).first;
+ const size_t M = rows_of(params);
+ auto& wgs = kd.params.workGroups;
+ const size_t tiles_n = (N / cols_per_thread + wg_n - 1) / wg_n;
+ const size_t tiles_m = ((M + rows_per_thread - 1) / rows_per_thread + wg_m - 1) / wg_m;
+ wgs.global = {tiles_n * wg_n, std::max<size_t>(tiles_m, 1) * wg_m, 1};
+ wgs.local = {wg_n, wg_m, 1};
+ set_scalars(params, kd, M);
+ }};
+ }
+};
+
+// GEMV kernel (woq_u2_gemm_dual_gemv.cm): M <= gemv_max_m (decode).
+// blocks = ceil(N / 16), cseq = 2 if blocks > gemv_maxt else 1 (column blocks per thread),
+// global = (ceil(blocks / cseq / 16) * 16, ceil(M / 8)), local = (16, 1).
+class WoqU2GemvGenerator : public WoqU2GeneratorBase {
+public:
+ WoqU2GemvGenerator() : WoqU2GeneratorBase("woq_u2_gemm_dual_gemv") {}
+
+protected:
+ [[nodiscard]] std::string get_build_options(const RuntimeParams& params) const override {
+ return KernelGenerator::get_build_options(params) +
+ " -Qxcm_register_file_size=128 -DNCB=1 -DRBG=1 -DLS=16 -DPFG=4 -DGEMV_MAXT=" + std::to_string(gemv_maxt) + " ";
+ }
+
+ [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {
+ return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {
+ assert(!params.is_dynamic());
+ const size_t N = woq_u2_dims(params).first;
+ const size_t M = rows_of(params);
+ auto& wgs = kd.params.workGroups;
+ const size_t blocks = (N + gemv_cols_per_thread - 1) / gemv_cols_per_thread;
+ const size_t cseq = blocks > gemv_maxt ? 2 : 1;
+ const size_t groups_n = ((blocks + cseq - 1) / cseq + gemv_ls - 1) / gemv_ls;
+ const size_t groups_m = (M + gemv_rows_per_thread - 1) / gemv_rows_per_thread;
+ wgs.global = {groups_n * gemv_ls, std::max<size_t>(groups_m, 1), 1};
+ wgs.local = {gemv_ls, 1, 1};
+ set_scalars(params, kd, M);
+ }};
+ }
+};
+
+class WoqU2FCImpl : public PrimitiveImplCM {
+public:
+ DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::cm::WoqU2FCImpl)
+
+ // Stage indices are their registration order: 0 = tiled, 1 = GEMV.
+ Stage::Ptr tiled = make_stage<WoqU2TiledGenerator>();
+ Stage::Ptr gemv = make_stage<WoqU2GemvGenerator>();
+
+ WoqU2FCImpl() : PrimitiveImplOCL(FullyConnectedWoqU2ImplementationManager::get_type_info_static()) {}
+ WoqU2FCImpl(const program_node& node, const RuntimeParams& params) : WoqU2FCImpl() {
+ const auto epi = epilogue_of(params);
+ OPENVINO_ASSERT(epi.ok(), "[GPU] cm::fully_connected::woq_u2 created for ", node.id(), " with an unsupported epilogue: ", epi.error);
+ add_stage(tiled, params);
+ add_stage(gemv, params);
+ }
+
+ // One kernel per execution, chosen by the runtime M (M may be dynamic): GEMV for M <= gemv_max_m.
+ [[nodiscard]] std::vector<size_t> get_stages_execution_order(const cldnn::kernel_impl_params& impl_params) const override {
+ if (impl_params.is_dynamic()) {
+ return _order;
+ }
+ return {rows_of(impl_params) <= gemv_max_m ? size_t(1) : size_t(0)};
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<WoqU2FCImpl>(this);
+ }
+
+protected:
+ // The generic base only exposes the FC's activation input; weights, scales and zero points are the
+ // node's remaining dependencies. Bind all of them in dependency order so INPUT i == dependency i.
+ [[nodiscard]] cldnn::kernel_arguments_data get_arguments(const cldnn::primitive_inst& instance) const override {
+ cldnn::kernel_arguments_data args = PrimitiveImplCM::get_arguments(instance);
+ args.inputs.clear();
+ for (size_t i = 0; i < instance.dependencies().size(); i++) {
+ args.inputs.push_back(instance.dep_memory_ptr(i));
+ }
+ return args;
+ }
+};
+
+} // namespace
+
+std::unique_ptr<primitive_impl> FullyConnectedWoqU2ImplementationManager::create_impl(const program_node& node, const RuntimeParams& params) const {
+ assert(node.is_type<fully_connected>());
+ return std::make_unique<WoqU2FCImpl>(node, params);
+}
+
+} // namespace ov::intel_gpu::cm
+
+BIND_BINARY_BUFFER_WITH_TYPE(ov::intel_gpu::cm::WoqU2FCImpl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.hpp
new file mode 100644
index 00000000000..41032ce4b5b
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2.hpp
@@ -0,0 +1,436 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <sstream>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "activation_inst.h"
+#include "eltwise_inst.h"
+#include "fully_connected_inst.h"
+#include "fully_connected_woq_u2_gnk.hpp"
+#include "intel_gpu/graph/fused_primitive_desc.hpp"
+#include "intel_gpu/op/fc_weights_layout.hpp"
+#include "intel_gpu/runtime/debug_configuration.hpp"
+#include "intel_gpu/runtime/layout.hpp"
+#include "registry/implementation_manager.hpp"
+
+using namespace cldnn; // TODO: Remove once namespaces are aligned
+
+#define CM_FC_LOG_AND_RETURN_FALSE(node, reason) \
+ do { \
+ GPU_DEBUG_TRACE_DETAIL << (node).id() << " : Do not select cm::fully_connected::woq_u2 (" << reason << ")" << std::endl; \
+ return false; \
+ } while (0)
+
+namespace ov::intel_gpu::cm {
+
+// Weight layout woq_u2_gemm_dual.cm is built for (its WLAYOUT). An NK compressed FC provides n_major:
+// weights [N, K/4], scales / zero points [N, K/64]. A GNK FC (weights_layout) provides group_major --
+// weights [K/64, N, 16 B], scales / zero points [K/64, N]. For NK FCs, tests can still select group_major
+// here: the buffers are passed through unchanged, so whoever selects it must fill them in group-major byte
+// order. Read when the kernel is generated (network build).
+enum class WoqU2WeightLayout : int { group_major = 0, n_major = 1 };
+inline WoqU2WeightLayout& woq_u2_weight_layout_for_tests() {
+ static WoqU2WeightLayout layout = WoqU2WeightLayout::n_major;
+ return layout;
+}
+
+// The plugin picks this implementation for GNK weights only. Tests that exercise the NK kernels turn this on.
+inline bool& woq_u2_nk_enabled_for_tests() {
+ static bool enabled = false;
+ return enabled;
+}
+
+// Dependencies of the FC: 0 = input, 1 = weights, [2 = bias], then decompression scale and zero point,
+// then the outer dependencies of fused primitives.
+constexpr size_t woq_u2_bias_idx = 2;
+inline size_t woq_u2_scale_idx(bool has_bias) {
+ return has_bias ? 3 : 2;
+}
+inline size_t woq_u2_zp_idx(bool has_bias) {
+ return woq_u2_scale_idx(has_bias) + 1;
+}
+
+// The epilogue the CM u2 kernels apply (their epi_mode) and the FC dependency that provides its tensor
+// (`epi`), derived from the FC's bias and fused primitives. Supported, and nothing else:
+// no bias, nothing fused -> mode 0: C = acc
+// FC bias -> mode 1: C = acc + bias
+// fused eltwise sum with one outer operand -> mode 1: C = acc + operand
+// fused swish (beta 1) then eltwise prod with an operand -> mode 2: C = swish(acc) * operand (SwiGLU)
+// The operand itself is checked by woq_u2_check_epi_operand (dtype; shape like the output, or one row [N]
+// when the output is one row too).
+struct WoqU2Epilogue {
+ int32_t mode = 0; // kernel epi_mode
+ int32_t dep = -1; // FC dependency index of the epilogue tensor, -1 if none
+ std::string error; // non-empty: unsupported combination (the reason)
+ bool ok() const {
+ return error.empty();
+ }
+};
+
+inline WoqU2Epilogue woq_u2_epilogue(const std::vector<fused_primitive_desc>& fused, bool has_bias) {
+ WoqU2Epilogue e;
+ if (fused.empty()) {
+ if (has_bias) {
+ e.mode = 1;
+ e.dep = static_cast<int32_t>(woq_u2_bias_idx);
+ }
+ return e;
+ }
+ if (has_bias) {
+ e.error = "bias together with fused primitives";
+ return e;
+ }
+ // A fused eltwise of `mode` taking the FC's (fused) result and exactly one outer operand, no strides or
+ // coefficients.
+ auto is_binary = [](const fused_primitive_desc& fd, eltwise_mode mode) {
+ if (!fd.is_type<eltwise>() || !fd.has_outer_dep() || fd.total_num_deps != 2) {
+ return false;
+ }
+ const auto prim = fd.typed_desc<eltwise>();
+ if (prim->mode != mode || !prim->stride.empty()) {
+ return false;
+ }
+ for (auto c : prim->coefficients) {
+ if (c != 1.0f) {
+ return false;
+ }
+ }
+ return true;
+ };
+ if (fused.size() == 1 && is_binary(fused[0], eltwise_mode::sum)) {
+ e.mode = 1;
+ e.dep = fused[0].outer_dep_start_idx;
+ return e;
+ }
+ if (fused.size() == 2 && fused[0].is_type<activation>() && !fused[0].has_outer_dep() && is_binary(fused[1], eltwise_mode::prod)) {
+ const auto act = fused[0].typed_desc<activation>();
+ // The kernel's swish is x / (1 + exp(-x)): beta must be 1 and constant.
+ if (act->activation_function == activation_func::swish && !act->additional_params_input.is_valid() && act->additional_params.a == 1.0f) {
+ e.mode = 2;
+ e.dep = fused[1].outer_dep_start_idx;
+ return e;
+ }
+ }
+ std::ostringstream os;
+ os << "fused primitives not supported:";
+ for (const auto& fd : fused) {
+ os << " " << fd.desc->id;
+ }
+ os << " (supported: one eltwise sum, or swish(beta 1) + eltwise prod)";
+ e.error = os.str();
+ return e;
+}
+
+// True if all dims but the last are static 1: a single row [.., 1, N].
+inline bool woq_u2_is_one_row(const cldnn::layout& l) {
+ const auto& ps = l.get_partial_shape();
+ for (size_t i = 0; i + 1 < ps.size(); i++) {
+ if (!ps[i].is_static() || ps[i].get_length() != 1) {
+ return false;
+ }
+ }
+ return ps.size() >= 1;
+}
+
+// Empty if `epi` can be the kernels' epilogue tensor for output `out` with N columns, else the reason.
+inline std::string woq_u2_check_epi_operand(const cldnn::layout& epi, const cldnn::layout& out, int64_t N) {
+ if (epi.data_type != data_types::f16 && epi.data_type != data_types::f32) {
+ return "epilogue tensor dtype not f16/f32";
+ }
+ if (epi.format != format::bfyx || epi.data_padding) {
+ return "epilogue tensor not plain bfyx / padded";
+ }
+ const auto& ps = epi.get_partial_shape();
+ if (ps.rank().is_dynamic() || ps.size() == 0 || !ps[ps.size() - 1].is_static() || ps[ps.size() - 1].get_length() != N) {
+ return "epilogue tensor last dim != N";
+ }
+ // The kernels read epi[m * N + n]: a one-row operand (bias, per-column post-op) is only that when the
+ // output is one row as well (M == 1); for more rows it would need broadcasting, which they do not do.
+ if (woq_u2_is_one_row(epi)) {
+ if (woq_u2_is_one_row(out)) {
+ return {};
+ }
+ return "one-row (per-column) epilogue tensor with more than one output row (M must be 1)";
+ }
+ // Full tensor: same shape as the output, dimension by dimension (dynamic only where the output is).
+ const auto& os = out.get_partial_shape();
+ if (os.rank().is_dynamic() || os.size() != ps.size()) {
+ return "epilogue tensor rank != output rank";
+ }
+ for (size_t i = 0; i < ps.size(); i++) {
+ if (ps[i].is_static() != os[i].is_static() || (ps[i].is_static() && ps[i].get_length() != os[i].get_length())) {
+ return "epilogue tensor shape != output shape (and not one broadcast row)";
+ }
+ }
+ return {};
+}
+
+// u2 weight-only-quantized fully connected layer on XMX/DPAS: woq_u2_gemm_dual.cm (tiled) for M > 8 and
+// woq_u2_gemm_dual_gemv.cm for M <= 8, both built with WLAYOUT=1 (N-major weights and scales / zero points),
+// or WLAYOUT=0 for a GNK FC (weights [K/64, N, 64], scales / zero points [K/64, N], see woq_u2_accepts_gnk).
+//
+// Selected only for: Xe2 or Xe3 with CM JIT support, >= 96 KB SLM; f16 activations without padding; u2
+// weights [N, K] (weights_transposed); f16 decompression scales [N, K/64] bfyx (group size 64); u8
+// decompression zero points [N, K/64] bfyx (required: the kernels have no scalar / f16 / absent zero-point
+// path); no dynamically quantized activations; f16 or f32 output (OUT_F16); K % 64 == 0 and N % 32 == 0;
+// an epilogue woq_u2_epilogue supports (none, bias, fused add, fused SwiGLU) whose tensor passes
+// woq_u2_check_epi_operand (f16 / f32; shaped like the output -- a bias / per-column operand [N] therefore
+// only with M == 1). M (the product of the leading
+// dims) may be dynamic. Everything else falls back to the other fully_connected implementations (for u2:
+// the OCL reference kernel). prepare_quantization keeps per-group scales / zero points of u2 FCs in bfyx for
+// this kernel, and prepare_primitive_fusing lets u2 FCs that pass validate_base take post-op fusions.
+struct FullyConnectedWoqU2ImplementationManager : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("cm::fully_connected::woq_u2")
+ explicit FullyConnectedWoqU2ImplementationManager(shape_types shape_type, ValidateFunc vf = nullptr)
+ : ImplementationManager(impl_types::cm, shape_type, std::move(vf)) {}
+
+ static constexpr uint64_t required_slm_bytes = woq_u2_required_slm_bytes;
+ static constexpr int64_t group_size = woq_u2_group_size;
+
+ [[nodiscard]] in_out_fmts_t query_formats(const program_node& node) const override {
+ assert(node.is_type<fully_connected>());
+ // Everything plain bfyx: the kernel's N-major layout needs scales / zero points physically [N, K/64].
+ std::vector<format::type> in_fmts(node.get_dependencies().size(), format::bfyx);
+ std::vector<format::type> out_fmts(node.get_outputs_count(), format::bfyx);
+ return {in_fmts, out_fmts};
+ }
+
+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const kernel_impl_params& params) const override;
+
+ [[nodiscard]] bool validate_impl(const program_node& node) const override {
+ return validate_base(node, true);
+ }
+
+ // Runtime shapes: dynamic dims that matched in validate_impl can differ at execution (output [5, N] with a
+ // [1, N] operand), which eltwise broadcasts but the kernels do not; reject so another implementation runs.
+ [[nodiscard]] bool support_shapes(const kernel_impl_params& params) const override {
+ const auto epi = woq_u2_epilogue(params.fused_desc, params.bias_layout.has_value());
+ if (!epi.ok()) {
+ GPU_DEBUG_TRACE_DETAIL << "cm::woq_u2 support_shapes: " << epi.error << std::endl;
+ return false;
+ }
+ if (epi.dep < 0) {
+ return true;
+ }
+ const auto N = ov::intel_gpu::op::fc_weight_dims(params.get_input_layout(1).get_partial_shape(), params.typed_desc<fully_connected>()->weights_layout)
+ .N.get_length();
+ const auto why = woq_u2_check_epi_operand(params.get_input_layout(static_cast<size_t>(epi.dep)), params.get_output_layout(0), N);
+ if (!why.empty()) {
+ GPU_DEBUG_TRACE_DETAIL << "cm::woq_u2 support_shapes: " << why << std::endl;
+ }
+ return why.empty();
+ }
+
+ // Everything but the epilogue: whether this FC could run on the CM kernels if its bias / fused post-ops
+ // are supported. prepare_primitive_fusing uses it to let such FCs take post-op fusions (and for GNK FCs,
+ // which have no fallback implementation, to block unsupported post-op fusions independent of device).
+ static bool accepts_post_op_fusion(const program_node& node) {
+ assert(node.is_type<fully_connected>());
+ if (node.as<fully_connected>().get_primitive()->weights_layout == ov::intel_gpu::op::FcWeightsLayout::GNK) {
+ return validate_node(node, false, false);
+ }
+ return validate_base(node, false);
+ }
+
+ static bool check_device(const program_node& node) {
+ auto& engine = node.get_program().get_engine();
+ const auto& config = node.get_program().get_config();
+ const auto& info = engine.get_device_info();
+
+ if (!check_cm_jit_support(engine, config)) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "CM jit not supported on this device");
+ }
+ if (info.arch != gpu_arch::xe2 && info.arch != gpu_arch::xe3) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "unsupported arch (requires Xe2/Xe3)");
+ }
+ // Deliberately not gated on config.get_use_cm(): that flag is a blanket switch for every CM
+ // kernel (PA/SDPA/LSTM/FC); this impl dispatches on its own whenever all other checks below
+ // pass, without requiring OV_GPU_USE_CM to be set.
+ if (info.max_local_mem_size < required_slm_bytes) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "insufficient SLM: " << info.max_local_mem_size << " < " << required_slm_bytes);
+ }
+ return true;
+ }
+
+ static bool validate_base(const program_node& node, bool check_epilogue) {
+ return check_device(node) && validate_node(node, check_epilogue, true);
+ }
+
+ static bool validate_node(const program_node& node, bool check_epilogue, bool check_dev_info = true) {
+ assert(node.is_type<fully_connected>());
+
+ const auto& fc_node = node.as<fully_connected>();
+ const auto& prim = fc_node.get_primitive();
+ if (!prim->compressed_weights) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weights not compressed");
+ }
+ if (prim->hadamard_block != 0) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "fused Hadamard input transform not supported");
+ }
+ if (!prim->decompression_scale.is_valid()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "no decompression scale");
+ }
+ if (prim->dynamic_quantized_activation) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "dynamic quantized activation not supported");
+ }
+ if (!prim->weights_transposed) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weights not transposed");
+ }
+ const bool gnk = prim->weights_layout == ov::intel_gpu::op::FcWeightsLayout::GNK;
+ if (!gnk && !woq_u2_nk_enabled_for_tests()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "only GNK weights are selected, weights_layout " << ov::intel_gpu::op::to_string(prim->weights_layout));
+ }
+ if (!gnk && prim->weights_rank != 2) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weights_rank != 2: " << prim->weights_rank);
+ }
+ // NK: scale / zp [N, K/64] (transpose_b_scale / zp true); GNK: [K/64, N] (false).
+ if (prim->transpose_b_scale == gnk || prim->transpose_b_zp == gnk) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "scale/zp layout does not match weights_layout " << ov::intel_gpu::op::to_string(prim->weights_layout));
+ }
+
+ const bool has_bias = fc_node.bias_term();
+ const auto in_layouts = node.get_input_layouts();
+ if (in_layouts.size() <= woq_u2_scale_idx(has_bias)) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "missing decompression scale input");
+ }
+ const auto& in = in_layouts[0];
+ const auto& wei = in_layouts[1];
+ const auto& scale = in_layouts[woq_u2_scale_idx(has_bias)];
+ // Use the cached output layout if valid; otherwise compute it, since the const getter throws on an invalid layout.
+ const auto out = node.is_valid_output_layout(0) ? node.get_output_layout(0) : node.calc_output_layout();
+
+ if (in.data_type != data_types::f16) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "activation dtype != f16: " << in.data_type);
+ }
+ if (in.format != format::bfyx || in.data_padding) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "activation not plain bfyx");
+ }
+ if (wei.data_type != data_types::u2) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weights dtype != u2: " << wei.data_type);
+ }
+ if (wei.format != format::bfyx || wei.data_padding || !wei.is_static()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weights not static plain bfyx");
+ }
+ if (out.data_type != data_types::f16 && out.data_type != data_types::f32) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "output dtype not f16/f32: " << out.data_type);
+ }
+ if (out.format != format::bfyx || out.data_padding) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "output not plain bfyx");
+ }
+
+ // Weights [N, K] or GNK [K/64, N, 64] (static even when M is dynamic).
+ const auto wshape = wei.get_shape();
+ if (wshape.size() != (gnk ? 3u : 2u)) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "weight shape rank " << wshape.size() << " does not match weights_layout");
+ }
+ const auto dims = ov::intel_gpu::op::fc_weight_dims(wei.get_partial_shape(), prim->weights_layout);
+ const auto N = dims.N.get_length();
+ const auto K = dims.K.get_length();
+ if (K % group_size != 0) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "K % 64 != 0: K=" << K);
+ }
+ if (N % 32 != 0) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "N % 32 != 0: N=" << N);
+ }
+ const auto KG = K / group_size;
+
+ // Activations: last dim is K.
+ const auto& in_pshape = in.get_partial_shape();
+ if (in_pshape.rank().is_dynamic() || in_pshape[in_pshape.size() - 1].is_dynamic() || in_pshape[in_pshape.size() - 1].get_length() != K) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "activation last dim != K or dynamic");
+ }
+
+ auto is_per_group = [&](const cldnn::layout& l) {
+ if (!l.is_static() || l.format != format::bfyx || l.data_padding) {
+ return false;
+ }
+ const auto s = l.get_shape();
+ size_t total = 1;
+ for (auto d : s) {
+ total *= d;
+ }
+ return s.size() >= 2 && static_cast<int64_t>(s[0]) == (gnk ? KG : N) && static_cast<int64_t>(total) == N * KG;
+ };
+
+ if (scale.data_type != data_types::f16) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "scale dtype != f16: " << scale.data_type);
+ }
+ if (!is_per_group(scale)) {
+ size_t total = 1;
+ for (auto d : scale.get_shape()) {
+ total *= d;
+ }
+ CM_FC_LOG_AND_RETURN_FALSE(
+ node,
+ "scale shape/format mismatch: format=" << scale.format << " total_elems=" << total << " expected(N*K/64)=" << (N * KG) << " N=" << N
+ << " K=" << K << " implied_group_size=" << (total > 0 ? (N * K) / static_cast<int64_t>(total) : -1));
+ }
+
+ // Zero points: a per-group u8 tensor only.
+ if (!prim->decompression_zero_point.is_valid() || in_layouts.size() <= woq_u2_zp_idx(has_bias)) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "no decompression zero point");
+ }
+ const auto& zp = in_layouts[woq_u2_zp_idx(has_bias)];
+ if (zp.data_type != data_types::u8) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "zero point dtype != u8: " << zp.data_type);
+ }
+ if (!is_per_group(zp)) {
+ size_t total = 1;
+ for (auto d : zp.get_shape()) {
+ total *= d;
+ }
+ CM_FC_LOG_AND_RETURN_FALSE(node,
+ "zero point shape/format mismatch: format=" << zp.format << " total_elems=" << total << " expected(N*K/64)=" << (N * KG)
+ << " N=" << N << " K=" << K << " implied_group_size="
+ << (total > 0 ? (N * K) / static_cast<int64_t>(total) : -1));
+ }
+
+ cldnn::device_info gnk_info{};
+ if (check_dev_info) {
+ gnk_info = node.get_program().get_engine().get_device_info();
+ } else {
+ gnk_info.arch = gpu_arch::xe2;
+ gnk_info.max_local_mem_size = required_slm_bytes;
+ }
+ if (gnk && !woq_u2_accepts_gnk(gnk_info,
+ true,
+ wei.data_type,
+ wei.get_partial_shape(),
+ scale.data_type,
+ scale.get_partial_shape(),
+ true,
+ zp.data_type,
+ zp.get_partial_shape())) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "GNK weights / scale / zero point rejected by woq_u2_accepts_gnk");
+ }
+
+ if (!check_epilogue) {
+ return true;
+ }
+
+ // Epilogue: bias / fused post-ops the kernels can apply, and their tensor.
+ const auto epi = woq_u2_epilogue(node.get_fused_primitives(), has_bias);
+ if (!epi.ok()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, epi.error);
+ }
+ if (epi.dep >= 0) {
+ if (static_cast<size_t>(epi.dep) >= in_layouts.size()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, "epilogue tensor dependency missing");
+ }
+ const auto why = woq_u2_check_epi_operand(in_layouts[static_cast<size_t>(epi.dep)], out, N);
+ if (!why.empty()) {
+ CM_FC_LOG_AND_RETURN_FALSE(node, why);
+ }
+ }
+ return true;
+ }
+};
+
+} // namespace ov::intel_gpu::cm
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2_gnk.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2_gnk.hpp
new file mode 100644
index 00000000000..3ec6f8c82a9
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/fully_connected_woq_u2_gnk.hpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+
+#include "intel_gpu/runtime/device_info.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+
+namespace ov::intel_gpu::cm {
+
+constexpr int64_t woq_u2_group_size = 64;
+constexpr uint64_t woq_u2_required_slm_bytes = 3 * (2 * 256 * 32 + 64 * 256); // matches SLM_BYTES in woq_u2_gemm_dual.cm
+
+// Test-only switch: false makes woq_u2_accepts_gnk() always reject, i.e. the plugin behaves as without the GNK path.
+inline bool& woq_u2_gnk_enabled_for_tests() {
+ static bool enabled = true;
+ return enabled;
+}
+
+// True if the CM u2 FC kernels can run an FC with native group-major (GNK) weights [G, N, gs]. The single
+// definition shared by is_decompression_multiply (keeps the chain unfolded), ConvertFullyConnectedToFullyConnectedCompressed
+// (emits the GNK FC) and FullyConnectedWoqU2ImplementationManager::validate_impl.
+// scale / zp: per group, [G, N] or [G, N, 1]. zp_et may still be u2 / u4: the compressed FC widens those to u8.
+inline bool woq_u2_accepts_gnk(const cldnn::device_info& info,
+ bool cm_jit_supported,
+ ov::element::Type w_et,
+ const ov::PartialShape& w,
+ ov::element::Type scale_et,
+ const ov::PartialShape& scale,
+ bool has_zp,
+ ov::element::Type zp_et,
+ const ov::PartialShape& zp) {
+ if (!woq_u2_gnk_enabled_for_tests() || !cm_jit_supported) {
+ return false;
+ }
+ if (info.arch != cldnn::gpu_arch::xe2 && info.arch != cldnn::gpu_arch::xe3) {
+ return false;
+ }
+ if (info.max_local_mem_size < woq_u2_required_slm_bytes) {
+ return false;
+ }
+ if (w_et != ov::element::u2 || !w.is_static() || w.size() != 3) {
+ return false;
+ }
+ const auto G = w[0].get_length();
+ const auto N = w[1].get_length();
+ if (w[2].get_length() != woq_u2_group_size || N % 32 != 0) {
+ return false;
+ }
+ auto per_group = [&](const ov::PartialShape& p) {
+ return p.is_static() && (p.size() == 2 || (p.size() == 3 && p[2].get_length() == 1)) && p[0].get_length() == G && p[1].get_length() == N;
+ };
+ if (scale_et != ov::element::f16 || !per_group(scale)) {
+ return false;
+ }
+ const bool zp_widens_to_u8 = zp_et == ov::element::u8 || zp_et == ov::element::u4 || zp_et == ov::element::u2;
+ return has_zp && zp_widens_to_u8 && per_group(zp);
+}
+
+} // namespace ov::intel_gpu::cm
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/sources.cmake b/src/plugins/intel_gpu/src/graph/impls/cm/sources.cmake
index 51f19e9162a..bd96ce76bbd 100644
--- a/src/plugins/intel_gpu/src/graph/impls/cm/sources.cmake
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/sources.cmake
@@ -3,6 +3,9 @@
#
set(GPU_CM_IMPL_SOURCES
+ ${CMAKE_CURRENT_LIST_DIR}/fully_connected_woq_u2.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/fully_connected_woq_u2.hpp
+ ${CMAKE_CURRENT_LIST_DIR}/fully_connected_woq_u2_gnk.hpp
${CMAKE_CURRENT_LIST_DIR}/include/cm_attention_common.hpp
${CMAKE_CURRENT_LIST_DIR}/include/cm_pa_xe1.hpp
${CMAKE_CURRENT_LIST_DIR}/include/cm_pa_xe2.hpp
@@ -40,6 +43,8 @@ set(GPU_CM_KERNEL_SOURCES
${CMAKE_CURRENT_LIST_DIR}/pa_single_token_finalization.cm
${CMAKE_CURRENT_LIST_DIR}/pa_small_q.cm
${CMAKE_CURRENT_LIST_DIR}/pa_small_q_finalization.cm
+ ${CMAKE_CURRENT_LIST_DIR}/woq_u2_gemm_dual.cm
+ ${CMAKE_CURRENT_LIST_DIR}/woq_u2_gemm_dual_gemv.cm
${CMAKE_CURRENT_LIST_DIR}/xattn_find_block.cm
${CMAKE_CURRENT_LIST_DIR}/xattn_gemm_qk.cm
${CMAKE_CURRENT_LIST_DIR}/xattn_post_proc.cm
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual.cm b/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual.cm
new file mode 100644
index 00000000000..18c6f18b3d0
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual.cm
@@ -0,0 +1,662 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// OpenVINO copy of woq_u2_gemm_cm_dual_v4_final.cpp (u2 weight-only-quantized GEMM on XMX/DPAS, group
+// size 64). The kernel code is unchanged; the entry name is KERNEL_NAME (set by
+// fully_connected_woq_u2.cpp; the original's `woq_matmul` by default). OpenVINO builds it with WLAYOUT=1 (N-major weights [N, K/4],
+// scales / zero points [N, K/64]) and epi_mode=0 (no epilogue). OpenVINO batch-compiles several
+// instances into one program, so (OpenVINO-only additions) the file-scope structs / helpers are
+// defined once (*_ONCE guards) and the kernel's macros are #undef'd at the end of the file. OUT_F16
+// (OpenVINO addition, default 0 = the original's f32 C) stores C as half; nothing before the store changes.
+// EPI_F16 (OpenVINO addition, default 0 = the original's f32 epi) reads epi as half and widens to float
+// right after the load; the epi_mode==1/2 math downstream is unchanged.
+#ifndef KERNEL_NAME
+#define KERNEL_NAME woq_matmul
+#endif
+#ifndef OUT_F16
+#define OUT_F16 0 // OpenVINO addition: 1 = C is half [M, N] (the f32 result rounded to nearest even)
+#endif
+#ifndef EPI_F16
+#define EPI_F16 0 // OpenVINO addition: 1 = epi is half [M, N] instead of float [M, N]
+#endif
+#include <cm/cm.h>
+
+// kernel-gen-build-options: -Qxcm_register_file_size=128 -DNCOL=2 -DMROWS=32 -DWG_M=8 -DWG_N=8 -DKS=32 -DPFD=3
+// kernel-gen-dispatch-global: (N // (16 * NCOL) + WG_N - 1) // WG_N * WG_N, ((M + MROWS - 1) // MROWS + WG_M - 1) // WG_M * WG_M
+// kernel-gen-dispatch-local: WG_N, WG_M
+
+// PTL dual v4 -- FINAL PICK. WLAYOUT 1 bottleneck: DRAM efficiency of the strided N-major rows
+// (probe: with the weights L2-resident, N=3072, WLAYOUT 1 is within 5% of WLAYOUT 0; at N >= 6144 it
+// is 19% behind). Levers: (a) banded group swizzle so both M-blocks of a column block share each
+// weight line from DRAM (only while their A slice fits L2), (b) chunked weight / scale / zp prefetch
+// (8 groups = 2 lines per column, 8 groups ahead). WLAYOUT 0 = v1.
+//
+// PTL dual v3 -- WLAYOUT 1 only. Bottleneck: line locality of the N-major weight / scale / zp
+// streams (v2 ablation: weight gather 0.28 ms, scale/zp 0.13 ms; the same weight bytes as contiguous
+// blocks cost 0.11 ms). v2 fetched each column's 64 B weight line 16 B at a time over 4 groups and
+// its scale line (32 groups) 2 B at a time. Lever: read every line ONCE -- two adjacent 32 B N8 gathers per
+// column every 4 groups (gathers above N8 do not legalize), and 16 groups of scales (U32 N8) / zero points (U32 N4) per gather when KG % 4 == 0 (else
+// v2's per-group gathers); the group's part is picked from registers.
+//
+// PTL dual v2 -- WLAYOUT 1 only (WLAYOUT 0 is v1 unchanged). Bottleneck: cache-line request rate of
+// the N-major gathers. v1's layout-1 fetch has each thread gather ONE 16-bit word from each of 16
+// columns (1280 B apart), so every column's line is requested ~32x (4 threads x 2 slices x 4 groups
+// per line): ~2800 line requests per slice per WG vs ~420 for WLAYOUT 0 (ablation: dropping weight,
+// scale/zp AND prefetch gathers together = WLAYOUT 0 speed; any one alone stays slow). Lever: each
+// thread owns 4 WHOLE columns -- one 4-lane N4 gather of each column's 16-byte group per group, 4-lane
+// scale/zp gathers -- dequantizes 4 columns x 32 k and writes the VNNI Src1 layout with one 16-lane
+// N4 SLM scatter. (Probe probe_vs_layout.cpp: vector gathers return [element][lane].)
+//
+// PTL dual v1 -- bottleneck: DRAM burst at the end of each wave. On PTL (102 GB/s vs 53.9 TFLOP/s)
+// the original's epi-tile prefetch (3 MB per wave in the last 32 slices) saturates the bus and starves
+// the weight stream feeding DPAS (single-layout study: that prefetch alone cost 0.18 ms). Lever: the
+// epi prefetch is spread evenly over the K loop, one row every EPS = 3 slices. Port of the
+// single-layout PTL final (woq_u2_gemm_cm_v6_final); its group remap is NOT ported (it regressed
+// every shape whose A exceeds L2 by up to 1.7x).
+//
+// v15 -- dual weight layout (feature, not a bottleneck lever): the v13/final kernel with the
+// quantization group size fixed by `#define GS 64` and a compile-time weight-layout switch:
+// WLAYOUT 0 (default, the ABI): Wq [KG, N, GS/4] scales [KG, N] zps [KG, N] (group-major)
+// WLAYOUT 1 (N-major, OpenVINO compressed FC):
+// Wq [N, K/4] (= [N, KG, GS/4]) scales [N, KG] zps [N, KG]
+// Both layouts pack 4 u2 per byte, LSB first along K; zps are u8 (0..3) in both. The WLAYOUT 0
+// path is the final kernel's code unchanged. For WLAYOUT 1 the per-(group, column) scale / zero point
+// of 16 columns is strided by KG, so it is a 16-lane gather (issued once per group and reused by the
+// group's second slice), and the weight prefetch touches one line per column.
+// Gate WLAYOUT 1 with `--repack repack_nmajor.py` (transposes the const buffers to N-major); the
+// baseline still runs on the shipped layout, so both layouts are scored against the original.
+//
+// (final) = woq_u2_gemm_cm_v13_epipf.cpp:
+//
+// v13 -- bottleneck: epilogue-tile prefetch cadence. v11/v12 prefetched the epi tile in bursts (2
+// rows per slice / 4 rows per block); at EPI=0 they tie v8, at EPI=2 they lose 0.035 ms. One row per
+// slice over the last EPW=32 slices, into L2 only (the epilogue reads it back from L2 anyway), wins.
+//
+// (v12) bottleneck: v11's generic tail loop (16..21 slices of dynamic code: v11's K-slope is at the
+// DPAS roofline but its intercept grew 0.087 -> 0.131 ms). The unrolled loop now runs to NS-2 (its
+// weight prefetch clamps to the last group), the epilogue-tile prefetch is 4 rows per unrolled block
+// over the last EPW slices, and the generic tail is only the last 2..7 slices.
+//
+// (v11) bottleneck: K-loop issue. v8's loop runs exactly at the DPAS rate but with no issue headroom
+// (v9b: +14 loop instructions -> +4% time). The loop is now lean:
+// * unrolled x6 so the SLM ring slot (period 3) and the slice parity (period 2) are compile-time
+// constants -> every SLM address is an immediate offset, no slot arithmetic;
+// * global offsets are running sums (no per-slice g*N multiplies);
+// * each thread gathers only the 16-bit word of the packed weights it dequantizes (DataSize::U16),
+// replacing a runtime-offset replicate that the compiler lowered to an indirect register move;
+// * the epilogue-tile prefetch lives in a short generic tail loop (the last 16..21 slices).
+//
+// (v10) bottleneck: epilogue message count (v8 ablation: the whole epilogue costs 0.046 ms with the
+// DPAS array idle, and its epi loads are nearly free, so it is the 8192 load/store messages per core
+// per wave). Full row blocks now move 128 B per message (both 16-column blocks of a row at once):
+// half the messages.
+//
+// (v8) bottleneck: the epilogue (v7 ablation: EPI=0 is 0.06 ms faster). Full 8-row blocks now load
+// all their epi rows before any math and run the swish on whole accumulator rows (SIMD32 instead of
+// SIMD16, no per-row branch); only an M-tail block takes the row-by-row path.
+//
+// (v7) bottleneck: the C store (v5b ablation: -0.12 ms without it; stores into an L2-resident region
+// cost nothing, so it is DRAM write traffic). The original's accumulator is C^T, so the epilogue
+// writes every output row as 32 B half-lines through a scatter; a write-pattern probe measured that
+// 1.7x slower than full-line row stores for the same bytes. The DPAS roles are therefore swapped
+// back to the textbook mapping:
+// Src2 (8 rows x K16, row-major) = A : one 256 B SLM block read; A is staged in SLM as
+// [k16 step][row][16 halves].
+// Src1 (VNNI, K16 x 16 lanes) = W : 16 output columns; the dequant writes the VNNI pair
+// layout directly (2 consecutive k per dword).
+// Acc (8 rows x 16 lanes, f32) = C : each accumulator row is 16 consecutive columns of one
+// output row -> full-line 64 B block loads / stores.
+// Everything else is v5b: WG_M x WG_N work-group, KS-wide K slices in a 3-slot SLM ring with a split
+// barrier, weight / epilogue prefetch, exact 16-bit dequant.
+//
+// C[m,n] = epilogue( sum_k A[m,k] * ( (u2_weight[g,n,kk] - zp[g,n]) * scale[g,n] ) ), g = k / 64.
+// Requires N % (16*NCOL) == 0 and K % 64 == 0 (as the original). M is arbitrary (rows >= M read as 0
+// through the buffer bounds check and are never stored); a partial last column work-group keeps its
+// surplus threads in every barrier but skips their weight loads and stores.
+
+#ifndef NCOL
+#define NCOL 2 // 16-wide column blocks per thread
+#endif
+#ifndef MROWS
+#define MROWS 32 // output rows per thread (multiple of 8)
+#endif
+#ifndef WG_M
+#define WG_M 8
+#endif
+#ifndef WG_N
+#define WG_N 8
+#endif
+#ifndef KS
+#define KS 32 // K per SLM slice (16 or 32)
+#endif
+#ifndef PFD
+#define PFD 3 // weight prefetch distance, in quantization groups
+#endif
+#ifndef WLAYOUT
+#define WLAYOUT 0 // 0: group-major [KG, N, GS/4] (ABI), 1: N-major [N, K/4]
+#endif
+#define GS 64 // quantization group size along K (hard-coded)
+#if GS != 64
+#error "GS is fixed at 64: a group is 16 bytes = one 16-bit word per 8 k, 2 KS=32 slices"
+#endif
+#define GB (GS / 4) // packed bytes per (group, column)
+#ifndef L1PF
+#define L1PF 2 // WLAYOUT 1 prefetch: 0 none, 1 per group (PFD ahead), 2 chunked (L1PC / L1PD)
+#endif
+#ifndef REMAPG
+#define REMAPG 2 // WLAYOUT 1: M-blocks per swizzle band
+#endif
+#ifndef REMAP_ABYTES
+#define REMAP_ABYTES (8 << 20) // WLAYOUT 1: swizzle only while the band's A slice fits (half of L2)
+#endif
+#ifndef EPS
+#define EPS 3 // epilogue-tile prefetch stride: one row every EPS slices
+#endif
+#define EPW (MROWS * EPS) // prefetch window (slices before the end); clamped to the whole loop
+
+#define NT (WG_M * WG_N)
+#define RB (MROWS / 8) // 8-row blocks per thread
+#define KW (KS / 16) // DPAS K-steps per slice
+#define SPG (GS / KS) // slices per quantization group
+#define HPT (NCOL * KW * 2) // W half-pieces per column tile per slice
+#define NHW (WG_N * HPT) // W half-pieces per work-group per slice
+#define HPPT ((NHW + NT - 1) / NT) // half-pieces dequantized per thread per slice
+#define WROWS (WG_M * MROWS)
+#define ARPT (WROWS / NT) // A rows staged per thread per slice
+#define A_BYTES (KW * WROWS * 32)
+#define W_BYTES (NHW * 256)
+#define BUF_BYTES (A_BYTES + W_BYTES)
+#define NBUF 3
+#define SLM_BYTES (NBUF * BUF_BYTES)
+#define NACC (RB * NCOL)
+#define ACC(rb, cb) ((rb) * NCOL + (cb))
+// W Src1 operand (column tile ct, 16-column block cb, k-step w): 512 B = half-pieces jh = 0, 1
+// (VNNI rows j = 4*jh .. 4*jh+3, i.e. k = 8*jh .. 8*jh+7).
+#define WPIECE(ct, cb, w) ((((ct) * NCOL + (cb)) * KW) + (w))
+
+#if NHW != NT || KS != 32
+#error "v11's unrolled K loop assumes one weight half-piece per thread and KS == 32"
+#endif
+#if WLAYOUT == 1 && WG_N * NCOL * 16 != 4 * NT
+#error "WLAYOUT 1 dequant assumes 4 columns per thread"
+#endif
+
+#ifndef WOQ_U2_DUAL_HPIECE_RAW_ONCE
+#define WOQ_U2_DUAL_HPIECE_RAW_ONCE
+struct hpiece_raw {
+ vector<ushort, 16> pw; // 16 columns: the 16-bit word (8 x u2) this thread dequantizes
+ vector<ushort, 16> sc; // 16 halves
+ vector<uchar, 16> zp; // 16 uchars
+};
+#endif
+
+#if WLAYOUT == 1
+#ifndef WOQ_U2_DUAL_L1_RAW_ONCE
+#define WOQ_U2_DUAL_L1_RAW_ONCE
+struct l1_raw {
+ vector<uint, 16> w; // [dword e][column i]: e = 0..3 are the group's 16 bytes of column i
+ vector<ushort, 4> sc; // 4 halves
+ vector<uchar, 4> zp; // 4 uchars
+};
+#endif
+#define L1WG 4 // groups per weight line load (64 B per column)
+#ifndef L1PC
+#define L1PC 8 // L1PF == 2: groups per chunked prefetch (multiple of 4)
+#endif
+#ifndef L1PD
+#define L1PD 8 // L1PF == 2: prefetch distance, groups
+#endif
+#define L1SG 16 // groups per scale / zero-point load
+
+// WLAYOUT 1: dequantize slice PAR (bytes 8*PAR .. 8*PAR+7 of the group) of my 4 columns into the
+// VNNI Src1 layout. Slice byte b of column i holds k = 4b..4b+3; its nibble `nib` (bits 4*nib ..
+// 4*nib+3) is exactly one VNNI dword (k pair 2j, 2j+1 of k-step w) with o = w*8 + j = 2b + nib.
+// Element order [i][o] matches the [element][lane] order of the N4 SLM scatter (lane = o).
+// Arithmetic is the original's half(q | 0x6400) - half(zp | 0x6400), times scale: bit-exact.
+#ifndef WOQ_U2_DUAL_STORE_L1_ONCE
+#define WOQ_U2_DUAL_STORE_L1_ONCE
+template <int PAR>
+inline void store_l1(vector<uint, 16> soff, l1_raw &r) {
+ matrix<uchar, 4, 8> b8;
+ vector<uchar, 64> rb = r.w.format<uchar>();
+ #pragma unroll
+ for (int i = 0; i < 4; i++) {
+ b8.row(i).select<4, 1>(0) = rb.select<4, 1>(((PAR * 2) * 4 + i) * 4);
+ b8.row(i).select<4, 1>(4) = rb.select<4, 1>(((PAR * 2 + 1) * 4 + i) * 4);
+ }
+ vector<ushort, 64> by = b8.format<uchar>().replicate<32, 1, 2, 0>(); // (i, o) -> byte o/2
+ vector<ushort, 64> sh;
+ #pragma unroll
+ for (int o = 0; o < 64; o++) sh(o) = 4 * (o % 2);
+ vector<ushort, 64> q0 = ((by >> sh) & (ushort)3) | (ushort)0x6400;
+ vector<ushort, 64> q1 = ((by >> (sh + 2)) & (ushort)3) | (ushort)0x6400;
+ vector<ushort, 4> zb = vector<ushort, 4>(r.zp) | (ushort)0x6400;
+ vector<half, 64> zr = zb.format<half>().replicate<4, 1, 16, 0>();
+ vector<half, 64> sr = r.sc.format<half>().replicate<4, 1, 16, 0>();
+ vector<half, 128> wv;
+ wv.select<64, 2>(0) = (q0.format<half>() - zr) * sr;
+ wv.select<64, 2>(1) = (q1.format<half>() - zr) * sr;
+ cm_store_slm<uint, VectorSize::N4>(soff, wv.format<uint>());
+}
+#endif
+
+#endif
+
+// Dequantize one half-piece: VNNI rows j' = 0..3 of a 16-column Src1 operand, element (j', n, e) =
+// w[k = 2j' + e (within the half)][n], read from bit 2*(2j' + e) of column n's word. Arithmetic is
+// bit-exact with the original's half(short(q - zp)) * scale (see v5).
+#ifndef WOQ_U2_DUAL_STORE_HPIECE_ONCE
+#define WOQ_U2_DUAL_STORE_HPIECE_ONCE
+inline void store_hpiece(unsigned slm_off, vector<ushort, 128> shifts, hpiece_raw &r) {
+ vector<half, 16> sc = r.sc.format<half>();
+ vector<ushort, 16> zb = vector<ushort, 16>(r.zp) | (ushort)0x6400;
+ vector<ushort, 32> wd = r.pw.replicate<16, 1, 2, 0>(); // [n][e]
+ vector<ushort, 128> q = wd.replicate<4>();
+ q = ((q >> shifts) & (ushort)3) | (ushort)0x6400;
+ vector<half, 32> zr = zb.format<half>().replicate<16, 1, 2, 0>();
+ vector<half, 32> sr = sc.replicate<16, 1, 2, 0>();
+ vector<half, 128> wv = (q.format<half>() - zr.replicate<4>()) * sr.replicate<4>();
+ cm_store_slm<uint, 64>(slm_off, wv.format<uint>());
+}
+#endif
+
+
+extern "C" _GENX_MAIN_ void
+KERNEL_NAME(SurfaceIndex A [[type("buffer_t")]], // half [M, K]
+ SurfaceIndex Wq [[type("buffer_t")]], // uchar [KG, N, GS/4] (WLAYOUT 1: [N, K/4])
+ SurfaceIndex scales [[type("buffer_t")]], // half [KG, N] (WLAYOUT 1: [N, KG])
+ SurfaceIndex zps [[type("buffer_t")]], // uchar [KG, N] (WLAYOUT 1: [N, KG])
+ SurfaceIndex epi [[type("buffer_t")]], // float [M, N] (EPI_F16: half [M, N])
+ SurfaceIndex C [[type("buffer_t")]], // float [M, N]
+ int M, int K, int N, int epi_mode) {
+ cm_slm_init(SLM_BYTES);
+
+ const int lx = cm_local_id(0), ly = cm_local_id(1);
+ const int tl = ly * WG_N + lx;
+ int gn = cm_group_id(0), gm = cm_group_id(1);
+#if WLAYOUT == 1
+ // Group swizzle (WLAYOUT 1 only): bands of REMAPG M-blocks walk M first, so the M-blocks sharing a
+ // column block's N-major weights -- whose strided rows are expensive to pull from DRAM -- are
+ // co-resident and each weight line comes from DRAM once per band. Only while the band's A slice
+ // (REMAPG * WROWS * K * 2 bytes) fits in half the L2: measured -7% at K=5120, +5% at K=17920. On
+ // WLAYOUT 0 the same swizzle is worth <= 0.6% and loses on L2-sized A, so it is not used there.
+ if (REMAPG * WROWS * K * 2 <= REMAP_ABYTES) {
+ const int gx = cm_group_count(0), gy = cm_group_count(1);
+ const int lin = gm * gx + gn;
+ const int band = lin / (REMAPG * gx), r = lin % (REMAPG * gx);
+ const int bh = cm_min<int>(REMAPG, gy - band * REMAPG); // M-blocks in this band
+ gn = r / bh;
+ gm = band * REMAPG + r % bh;
+ }
+#endif
+ const int n_wg = gn * (WG_N * NCOL * 16);
+ const int m_wg = gm * WROWS;
+ const int n_base = n_wg + lx * (NCOL * 16);
+ const int m0 = m_wg + ly * MROWS;
+ const int KG = K / GS;
+ const int NS = KG * SPG;
+ const unsigned K2 = (unsigned)(K * 2);
+
+ vector<uint, 16> lane;
+ vector<ushort, 128> shifts; // 2 * (2 j' + e)
+ #pragma unroll
+ for (int i = 0; i < 16; i++) lane(i) = i;
+ #pragma unroll
+ for (int i = 0; i < 128; i++) shifts(i) = 4 * (i / 32) + 2 * (i % 2);
+
+ // A staging: my ARPT rows; SLM layout [k-step w][row][8 dwords].
+ const unsigned a_row0 = (unsigned)(m_wg + tl * ARPT) * K2;
+ const unsigned a_slm = (unsigned)(tl * ARPT * 32);
+ const unsigned a_mine = (unsigned)(ly * MROWS * 32);
+ const unsigned w_self = (unsigned)(lx * NCOL * KW);
+ // My weight half-piece h = tl: (column tile ct, 16-column block cb, k-step w, word jh).
+ const int jh = tl & 1, w_h = (tl >> 1) % KW, cb_h = (tl / (2 * KW)) % NCOL, ct_h = tl / HPT;
+ const int ncol_h = n_wg + ct_h * (NCOL * 16) + cb_h * 16;
+ const bool w_ok = ncol_h < N; // false only past the last column
+ const unsigned w_slm = A_BYTES + (unsigned)tl * 256;
+ // Loop state `gN` advances by GSTEP per group; the weight byte of (group, column, word) is
+ // gN * GB + pw_off in both layouts.
+#if WLAYOUT == 0
+ const unsigned GSTEP = (unsigned)N; // gN = g * N
+ const vector<uint, 16> pw_off = (lane + (unsigned)ncol_h) * (unsigned)GB + (unsigned)(w_h * 4 + jh * 2);
+#else
+ const unsigned GSTEP = 1u; // gN = g
+ // My 4 whole columns c4 .. c4+3 of the WG's 256; N % 32 == 0, so they are all in range or none.
+ const int c4 = n_wg + 4 * tl;
+ const bool w4_ok = c4 < N;
+ const vector<uint, 4> col4 = lane.select<4, 1>(0) + (unsigned)c4;
+ const vector<uint, 4> w_off4 = col4 * (unsigned)(K / 4); // Wq [N, K/4]: 16 B per group
+ const vector<uint, 4> sc_off4 = col4 * (unsigned)(KG * 2); // scales [N, KG] half
+ const vector<uint, 4> zp_off4 = col4 * (unsigned)KG; // zps [N, KG] uchar
+ // SLM scatter offsets (ring-slot relative): lane o = w*8 + j -> VNNI row j of k-step w, columns
+ // n0 .. n0+3 of 16-column block cb of column tile ct.
+ vector<uint, 16> soff;
+ {
+ const int cl = 4 * tl, ct = cl / (NCOL * 16), cb = (cl / 16) % NCOL, n0 = cl % 16;
+ #pragma unroll
+ for (int o = 0; o < 16; o++)
+ soff(o) = (unsigned)(A_BYTES + WPIECE(ct, cb, o / 8) * 512 + ((o % 8) * 16 + n0) * 4);
+ }
+#endif
+
+ matrix<float, NACC, 128> acc = 0.0f;
+#if WLAYOUT == 0
+ hpiece_raw raw;
+#else
+ l1_raw raw;
+ vector<uint, 4 * 4 * L1WG> wline; // [dword e][column i], L1WG groups
+ vector<uint, 4 * L1SG / 2> scl; // [dword][column], 2 groups per dword
+ vector<uint, 4 * L1SG / 4> zpl; // [dword][column], 4 groups per dword
+ const bool l1wide = (KG % 4) == 0; // scale / zp rows dword aligned
+#endif
+ matrix<uint, ARPT, KS / 2> ast;
+
+ // Global loads of one slice: A rows at byte offset `ao` (+ r*K2), weights of group offset gN = g*N
+ // with slice parity `par`.
+ auto fetch = [&](unsigned ao, unsigned gN, int par) {
+ #pragma unroll
+ for (int r = 0; r < ARPT; r++)
+ ast.row(r) = cm_load<uint, KS / 2>(A, ao + (unsigned)r * K2);
+#if WLAYOUT == 0
+ if (w_ok) {
+ raw.pw = cm_load<ushort, VectorSize::N1, DataSize::U16>(Wq, pw_off + (gN * (unsigned)GB + (unsigned)(par * 8)));
+ raw.sc.format<uint>() = cm_load<uint, 8>(scales, (gN + (unsigned)ncol_h) * 2u);
+ raw.zp.format<uint>() = cm_load<uint, 4>(zps, gN + (unsigned)ncol_h);
+ }
+#else
+ // On the group's first slice: every L1WG groups reload my 4 columns' weight lines, every L1SG
+ // groups their scales / zero points; then pick this group's part ([element][lane] order, so a
+ // group is a contiguous run). The second slice dequantizes the other 8 bytes of raw.w.
+ if (w4_ok && par == 0) {
+ const unsigned gw = gN % L1WG, gs = gN % L1SG;
+ if (gw == 0) { // gathers are at most N8 per lane
+ wline.select<32, 1>(0) = cm_load<uint, VectorSize::N8, DataSize::U32>(Wq, w_off4 + gN * (unsigned)GB);
+ wline.select<32, 1>(32) = cm_load<uint, VectorSize::N8, DataSize::U32>(Wq, w_off4 + (gN * (unsigned)GB + 32u));
+ }
+ raw.w = wline.select<16, 1>(gw * 16);
+ if (l1wide) {
+ // 16 groups of scales are N8 dwords and of zero points N4 dwords ([dword e][column] -> group
+ // 2e+h / 4e+b): U16 / U8 vector gathers and gathers above N8 do not legalize.
+ if (gs == 0) {
+ scl = cm_load<uint, VectorSize::N8, DataSize::U32>(scales, sc_off4 + gN * 2u);
+ zpl = cm_load<uint, VectorSize::N4, DataSize::U32>(zps, zp_off4 + gN);
+ }
+ raw.sc = scl.format<ushort>().select<4, 2>((gs / 2) * 8 + (gs % 2));
+ raw.zp = zpl.format<uchar>().select<4, 4>((gs / 4) * 16 + (gs % 4));
+ } else { // KG % 4 != 0: rows not dword aligned
+ raw.sc = cm_load<ushort, VectorSize::N1, DataSize::U16>(scales, sc_off4 + gN * 2u);
+ raw.zp = cm_load<uchar, VectorSize::N1, DataSize::U8>(zps, zp_off4 + gN);
+ }
+ }
+#endif
+ };
+ auto stage = [&](unsigned slot, int par) {
+ #pragma unroll
+ for (int w = 0; w < KW; w++) {
+ matrix<uint, ARPT, 8> t = ast.select<ARPT, 1, 8, 1>(0, w * 8);
+ cm_store_slm<uint, ARPT * 8>(slot + a_slm + w * (WROWS * 32), t.format<uint>());
+ }
+#if WLAYOUT == 0
+ store_hpiece(slot + w_slm, shifts, raw);
+#else
+ if (w4_ok) {
+ if (par == 0) store_l1<0>(soff + slot, raw);
+ else store_l1<1>(soff + slot, raw);
+ }
+#endif
+ };
+ auto prefetch_w = [&](unsigned gNp) { // one group of my column block
+#if WLAYOUT == 0
+ if (w_ok && jh == 0) {
+ const unsigned gn = gNp + (unsigned)ncol_h;
+ cm_prefetch<64, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, gn * (unsigned)GB);
+ cm_prefetch<8, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(scales, gn * 2u);
+ cm_prefetch<4, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(zps, gn);
+ }
+#elif L1PF == 2
+ // Chunked: every L1PC groups, the next L1PC groups of my 4 columns -- L1PC*16 B = 4 adjacent lines
+ // per column for L1PC = 16 -- L1PD groups ahead, so DRAM sees whole runs of each column's row.
+ const unsigned gq = gNp - (unsigned)(PFD - 1) + (unsigned)L1PD; // = current group + L1PD
+ if (w4_ok && gq % L1PC == 0 && gq < (unsigned)KG) {
+ vector<uint, 4 * (L1PC / 4)> po;
+ #pragma unroll
+ for (int l = 0; l < L1PC / 4; l++)
+ po.select<4, 1>(l * 4) = w_off4 + (gq * (unsigned)GB + (unsigned)(l * 64));
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, po);
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(
+ scales, (sc_off4 + gq * 2u) & ~3u);
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(
+ zps, (zp_off4 + gq) & ~3u);
+ }
+#elif L1PF
+ if (w4_ok) { // my 4 columns, one group
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(
+ Wq, w_off4 + gNp * (unsigned)GB);
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(
+ scales, (sc_off4 + gNp * 2u) & ~3u);
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(
+ zps, (zp_off4 + gNp) & ~3u);
+ }
+#endif
+ };
+ auto dpas_slice = [&](unsigned cur) {
+ #pragma unroll
+ for (int w = 0; w < KW; w++) {
+ matrix<uint, RB, 64> am; // Src2: 8 rows x 16 k each
+ matrix<uint, NCOL, 128> bm; // Src1: 16 columns VNNI each
+ #pragma unroll
+ for (int rb = 0; rb < RB; rb++)
+ am.row(rb) = cm_load_slm<uint, 64>(cur + a_mine + rb * 256 + w * (WROWS * 32));
+ #pragma unroll
+ for (int cb = 0; cb < NCOL; cb++) {
+ const unsigned wo = cur + A_BYTES + (w_self + cb * KW + w) * 512;
+ bm.row(cb).select<64, 1>(0) = cm_load_slm<uint, 64>(wo);
+ bm.row(cb).select<64, 1>(64) = cm_load_slm<uint, 64>(wo + 256);
+ }
+ #pragma unroll
+ for (int cb = 0; cb < NCOL; cb++)
+ #pragma unroll
+ for (int rb = 0; rb < RB; rb++)
+ acc.row(ACC(rb, cb)) = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, 8, 8>(
+ acc.row(ACC(rb, cb)), bm.row(cb), am.row(rb));
+ }
+ };
+
+ // Prologue: slices 0 and 1 (group 0) into ring slots 0 and 1.
+ #pragma unroll
+ for (int ps = 0; ps < 2; ps++) {
+ if (ps < NS) {
+ fetch(a_row0 + (unsigned)(ps * KS * 2), 0u, ps);
+ stage(ps * BUF_BYTES, ps);
+ }
+ }
+ cm_slm_fence(CM_GLOBAL_COHERENT_FENCE);
+ cm_barrier();
+ cm_sbarrier(1); // primes the first in-loop wait
+
+ // Loop state for slice s: ao = A offset of slice s+2, gN = (group of slice s+2) * N.
+ unsigned ao = a_row0 + (unsigned)(2 * KS * 2);
+ unsigned gN = GSTEP;
+ const unsigned gN_last = (unsigned)(KG - 1) * GSTEP; // last group's offset
+ const bool epf = epi_mode != 0 && n_base < N;
+ int er = 0; // next epilogue row to prefetch
+ // ao at which the next row is prefetched: slice max(NS - EPW - 2, 0), then every EPS slices.
+ unsigned epf_ao = ao + (unsigned)(cm_max<int>(NS - EPW - 2, 0) * KS * 2);
+
+ // One slice: prefetch (even slices), fetch slice s+2, DPAS on `cur`, then (after the wait that
+ // retires slice s-1's readers) stage slice s+2 into `nxt`, publish, signal.
+ auto slice = [&](unsigned cur, unsigned nxt, int par, bool fill, bool pfw) {
+ if (epf && er < MROWS && ao == epf_ao) { // one epilogue row per EPS slices
+ if (m0 + er < M)
+#if EPI_F16
+ // Transposed prefetch only supports U32/U64 granularity: same bytes, half the word count.
+ cm_prefetch<NCOL * 8, DataSize::U32, CacheHint::Uncached, CacheHint::Cached>(
+ epi, ((unsigned)(m0 + er) * N + n_base) * 2u);
+#else
+ cm_prefetch<NCOL * 16, DataSize::U32, CacheHint::Uncached, CacheHint::Cached>(
+ epi, ((unsigned)(m0 + er) * N + n_base) * 4u);
+#endif
+ er++;
+ epf_ao += EPS * KS * 2;
+ }
+ if (pfw) prefetch_w(cm_min<unsigned>(gN + (unsigned)(PFD - 1) * GSTEP, gN_last));
+ if (fill) fetch(ao, gN, par);
+ dpas_slice(cur);
+ cm_sbarrier(0);
+ if (fill) stage(nxt, par);
+ cm_slm_fence(CM_GLOBAL_COHERENT_FENCE);
+ cm_sbarrier(1);
+ ao += KS * 2;
+ if (par) gN += GSTEP;
+ };
+
+ // Main loop, unrolled x6: ring slot = s % 3 and parity = s % 2 are compile-time constants. Every
+ // main iteration fills (s + 2 < NS); the weight prefetch clamps to the last group near the end.
+ const int nmain = NS >= 8 ? ((NS - 2) / 6) * 6 : 0;
+ int s = 0;
+ for (; s < nmain; s += 6) {
+ slice(0 * BUF_BYTES, 2 * BUF_BYTES, 0, true, true);
+ slice(1 * BUF_BYTES, 0 * BUF_BYTES, 1, true, false);
+ slice(2 * BUF_BYTES, 1 * BUF_BYTES, 0, true, true);
+ slice(0 * BUF_BYTES, 2 * BUF_BYTES, 1, true, false);
+ slice(1 * BUF_BYTES, 0 * BUF_BYTES, 0, true, true);
+ slice(2 * BUF_BYTES, 1 * BUF_BYTES, 1, true, false);
+ }
+ // Generic tail: the last 2..7 slices (all slices when NS < 8).
+ unsigned slot = 0; // nmain % 3 == 0
+ for (; s < NS; s++) {
+ const int par = s & 1;
+ slice(slot * BUF_BYTES, (slot == 0 ? 2 : slot - 1) * BUF_BYTES, par, s + 2 < NS, false);
+ slot = (slot == 2) ? 0 : slot + 1;
+ }
+ cm_sbarrier(0);
+
+ // Epilogue: acc row ACC(rb,cb) element (i*16 + n) = C[m0 + rb*8 + i][n_base + cb*16 + n].
+ if (n_base >= N) return; // surplus column tile
+ #pragma unroll
+ for (int rb = 0; rb < RB; rb++) {
+ const int mb = m0 + rb * 8;
+ if (mb + 8 <= M) {
+ // Whole 8-row block in range. Rows are assembled NCOL*16 floats wide (128 B) so each epi load /
+ // C store moves a whole thread-tile row: the last arithmetic op writes straight into that
+ // row-interleaved layout, so the interleave costs no extra instruction.
+ matrix<float, 8, NCOL * 16> ev, ov;
+ if (epi_mode != 0) {
+#if EPI_F16
+ // Transposed load only supports U32/U64 granularity: load as uint, reinterpret as half.
+ matrix<half, 8, NCOL * 16> eh;
+ #pragma unroll
+ for (int i = 0; i < 8; i++)
+ eh.row(i).format<uint>() = cm_load<uint, NCOL * 8>(epi, ((unsigned)(mb + i) * N + (unsigned)n_base) * 2u);
+ ev = eh; // widen half -> float
+#else
+ #pragma unroll
+ for (int i = 0; i < 8; i++)
+ ev.row(i) = cm_load<float, NCOL * 16>(epi, ((unsigned)(mb + i) * N + (unsigned)n_base) * 4u);
+#endif
+ }
+ #pragma unroll
+ for (int cb = 0; cb < NCOL; cb++) {
+ vector<float, 128> v = acc.row(ACC(rb, cb));
+ if (epi_mode == 1) {
+ ov.select<8, 1, 16, 1>(0, cb * 16) = v + ev.select<8, 1, 16, 1>(0, cb * 16);
+ } else if (epi_mode == 2) {
+ vector<float, 128> e = cm_exp(v * -1.4426950408889634f); // exp(-v) = 2^(-v*log2(e))
+ v = v / (1.0f + e); // swish, alpha = 1.0
+ ov.select<8, 1, 16, 1>(0, cb * 16) = v * ev.select<8, 1, 16, 1>(0, cb * 16);
+ } else {
+ ov.select<8, 1, 16, 1>(0, cb * 16) = v;
+ }
+ }
+#if OUT_F16
+ matrix<half, 8, NCOL * 16> hv = ov; // round to nearest even
+ #pragma unroll
+ for (int i = 0; i < 8; i++)
+ cm_store<uint, NCOL * 8>(C, ((unsigned)(mb + i) * N + (unsigned)n_base) * 2u, hv.row(i).format<uint>());
+#else
+ #pragma unroll
+ for (int i = 0; i < 8; i++)
+ cm_store<float, NCOL * 16>(C, ((unsigned)(mb + i) * N + (unsigned)n_base) * 4u, ov.row(i));
+#endif
+ } else {
+ // M tail: row by row, rows >= M are never touched (as in the original).
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ const int m = mb + i;
+ if (m < M) {
+ #pragma unroll
+ for (int cb = 0; cb < NCOL; cb++) {
+ const unsigned off = ((unsigned)m * N + (unsigned)(n_base + cb * 16)) * 4u;
+ vector<float, 16> v = acc.row(ACC(rb, cb)).select<16, 1>(i * 16);
+#if EPI_F16
+ // Transposed load only supports U32/U64 granularity: load as uint, reinterpret as half.
+ vector<half, 16> eh;
+ if (epi_mode != 0)
+ eh.format<uint>() = cm_load<uint, 8>(epi, off / 2u);
+ vector<float, 16> ef = eh; // widen half -> float
+#endif
+ if (epi_mode == 1) {
+#if EPI_F16
+ v += ef;
+#else
+ v += cm_load<float, 16>(epi, off);
+#endif
+ } else if (epi_mode == 2) {
+ vector<float, 16> e = cm_exp(v * -1.4426950408889634f);
+ v = v / (1.0f + e);
+#if EPI_F16
+ v *= ef;
+#else
+ v *= cm_load<float, 16>(epi, off);
+#endif
+ }
+#if OUT_F16
+ vector<half, 16> h = v; // round to nearest even
+ cm_store<uint, 8>(C, ((unsigned)m * N + (unsigned)(n_base + cb * 16)) * 2u, h.format<uint>());
+#else
+ cm_store<float, 16>(C, off, v);
+#endif
+ }
+ }
+ }
+ }
+ }
+}
+
+// OpenVINO: keep this instance's macros out of the other kernels batched into the same program.
+#undef ACC
+#undef OUT_F16
+#undef EPI_F16
+#undef ARPT
+#undef A_BYTES
+#undef BUF_BYTES
+#undef EPS
+#undef EPW
+#undef GB
+#undef GS
+#undef HPPT
+#undef HPT
+#undef KS
+#undef KW
+#undef L1PC
+#undef L1PD
+#undef L1PF
+#undef L1SG
+#undef L1WG
+#undef MROWS
+#undef NACC
+#undef NBUF
+#undef NCOL
+#undef NHW
+#undef NT
+#undef PFD
+#undef RB
+#undef REMAPG
+#undef REMAP_ABYTES
+#undef SLM_BYTES
+#undef SPG
+#undef WG_M
+#undef WG_N
+#undef WPIECE
+#undef WROWS
+#undef W_BYTES
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual_gemv.cm b/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual_gemv.cm
new file mode 100644
index 00000000000..9d512b30045
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/woq_u2_gemm_dual_gemv.cm
@@ -0,0 +1,463 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// GEMV / small-M companion of woq_u2_gemm_dual.cm (u2 weight-only-quantized GEMM on XMX/DPAS, group
+// size 64): same ABI, same arithmetic, bit-exact with it; use it for M <= 8 (decode). OpenVINO
+// conventions as in woq_u2_gemm_dual.cm: the entry name is KERNEL_NAME (default woq_matmul), OUT_F16
+// stores C as half (the f32 result rounded to nearest even), EPI_F16 reads epi as half and widens to
+// float right after the load, file-scope types are defined once (*_ONCE guards) and the macros are
+// #undef'd at the end. No SLM, no barriers.
+//
+// v2 (decode tuning, cold-L2 measured -- every launch after a 64 MiB L2 flush, as in a real decode
+// step): (a) each thread takes 2 adjacent 16-column blocks when one block per thread would exceed
+// GEMV_MAXT = 960 threads (the dispatch grid follows the same rule): 1x5120x17920 0.44 -> 0.36 ms;
+// (b) with few threads (N/16 <= GEMV_DEEPT = 400) the weight prefetch goes PFG_DEEP = 8 groups ahead
+// with L1PL_DEEP = 2 lines per column (WLAYOUT 1): 1x17920x5120 0.32 -> 0.30 ms; otherwise PFG = 4,
+// L1PL = 1 as in v1.
+//
+// v3 (small decode shapes; cold-L2): (c) for M == 1 on N-major weights with KG % 4 == 0 the loads
+// read every line once -- a column's 64 B weight line (4 groups) by two N8 gathers every 4 groups,
+// double-buffered, and 16 groups of scales / zero points per U32 N8 / N4 gather -- instead of three
+// 16-lane gathers per group (~48 line requests per group per thread -> ~6; the line-request rate
+// bounded the small shapes: a probe that never waits on its loads was no faster). (d) the Src2
+// operand keeps rows >= M at zero and copies only the real rows, and each VNNI dword is built in one
+// 32-bit pass (no half interleave), in the wide path. (e) the wide path is used only
+// for short K (<= 8192) with one column block per thread, with its own deep prefetch (16 groups /
+// 2 lines); every other shape runs v2's per-group path unchanged.
+// Cold-L2 1x5120x7680 0.172 -> 0.145 ms, 1x5120x5120 0.105 -> 0.097 ms; larger shapes as v2.
+//
+// v4: (f) NPU layout -- shallower prefetch (PFN 2 / PFN_DEEP 4 groups), except 2-block shapes (PFG).
+//
+// v6: (g) plain layout -- every M == 1 shape with KG % 4 == 0 takes the line-at-once gather path (v3's
+// wide path), now also 2-block and long-K shapes and KG % 16 != 0 (buffer accesses are
+// bounds-checked, so a 16-group scale / zero-point window may run past a row's end), with per-class
+// prefetch PFB 4 / LPB 2, PFB_DEEP 12 / LPB_DEEP 2, PFB_PAIR 16 / LPB_PAIR 4. Cold-L2: 1x5120x7680
+// 0.145, 1x5120x5120 0.097, 1x5120x17920 0.356 -> 0.332, 1x17920x5120 0.300 -> 0.297 ms. All
+// arguments are buffers (a pointer + 2D-block-load variant measured within ~1% overall).
+//
+// Launch: global = (ceil(ceil(N/16) / cseq / LS) * LS, ceil(M/8)), local = (LS, 1),
+// cseq = 2 if N/16 > GEMV_MAXT else 1.
+#ifndef KERNEL_NAME
+#define KERNEL_NAME woq_matmul
+#endif
+// Not guarded: kernels_db_gen.py #undefs every unguarded macro at the end of the file, so a guard
+// would leave later instances in the same batched program without CAT.
+#define WOQ_U2_GEMV_CAT2(a, b) a##_##b
+#define WOQ_U2_GEMV_CAT(a, b) WOQ_U2_GEMV_CAT2(a, b)
+// The helper is named after KERNEL_NAME so several instances can share one program.
+#define GEMV_BODY_FN WOQ_U2_GEMV_CAT(KERNEL_NAME, gemv_body)
+#ifndef OUT_F16
+#define OUT_F16 0 // 1 = C is half [M, N] (the f32 result rounded to nearest even)
+#endif
+#ifndef EPI_F16
+#define EPI_F16 0 // 1 = epi is half [M, N] instead of float [M, N]
+#endif
+#include <cm/cm.h>
+
+// kernel-gen-build-options: -Qxcm_register_file_size=128 -DNCB=1 -DRBG=1 -DLS=16 -DPFG=4
+// kernel-gen-dispatch-global: (N // (16 * NCB) + LS - 1) // LS * LS, (M + 8 * RBG - 1) // (8 * RBG)
+// kernel-gen-dispatch-local: LS, 1
+
+// PTL dual v7 -- adds WLAYOUT 1 (N-major [N, K/4], scales / zps [N, KG]) to the GEMV path: per
+// group a 16-lane N4 gather of my 16 columns' 16 bytes (register order [dword][column], so k-step s
+// is the contiguous run 16s..16s+15), 16-lane U16 / U8 scale and zero-point gathers, and a one-line
+// per column prefetch every 4 groups (a 64 B line holds 4 groups of one column). WLAYOUT 0 = v6.
+//
+// PTL dual v6 -- bottleneck: v5 spends ~1.1 us per group per thread (4 DPAS + ~150 ALU) -- the A
+// rows were loaded in the iteration that consumes them, exposing their latency every group. Lever:
+// the A rows join the weight double buffer (loaded one group ahead).
+//
+// PTL dual v5 -- GEMV / small-M path (decode, M = 1). Bottleneck of every tiled trial at M = 1: the
+// 256-row tile -- the original runs 1x5120x7680 in 1.158 ms against a 0.115 ms weight-streaming
+// floor (10x), because each work-group still issues the DPAS / SLM work of 256 rows and there are
+// only N/256 work-groups to stream the weights. This path has no SLM and no barriers: each thread
+// owns 16*NCB output columns of RBG 8-row blocks and walks ALL of K in order (so the DPAS
+// accumulation chain is the original's: k-step by k-step from 0, bit-exact), streaming its columns'
+// weights with the next group's loads in flight (double buffer) and a prefetch PFG groups ahead,
+// and dequantizing straight into the VNNI Src1 operand in registers with the original's
+// half(q | 0x6400) - half(zp | 0x6400), times scale.
+//
+// Correct for any M (rows >= M are never loaded or stored); intended for M <= 8 * RBG. Same ABI and
+// group size as the original (GS = 64).
+
+#ifndef NCB
+#define NCB 1 // 16-column blocks per thread
+#endif
+#ifndef RBG
+#define RBG 1 // 8-row blocks per thread
+#endif
+#ifndef LS
+#define LS 16 // threads per work-group
+#endif
+#ifndef PFG
+#define PFG 4 // weight prefetch distance, groups (PFG_DEEP when N/16 <= GEMV_DEEPT)
+#endif
+#ifndef WLAYOUT
+#define WLAYOUT 0 // 0: group-major [KG, N, GS/4] (ABI), 1: N-major [N, K/4]
+#endif
+#ifndef L1PL
+#define L1PL 1 // WLAYOUT 1: weight lines per column per prefetch (L1PL_DEEP when deep)
+#endif
+#ifndef PFG_DEEP
+#define PFG_DEEP 8 // deep prefetch for few threads (N/16 <= GEMV_DEEPT), per-group path
+#endif
+#ifndef PFB
+#define PFB 4 // plain layout, M == 1 gather path: prefetch distance (groups) / lines per column
+#endif
+#ifndef LPB
+#define LPB 2
+#endif
+#ifndef PFB_DEEP
+#define PFB_DEEP 12 // ... few threads (N/16 <= GEMV_DEEPT)
+#endif
+#ifndef LPB_DEEP
+#define LPB_DEEP 2
+#endif
+#ifndef PFB_PAIR
+#define PFB_PAIR 16 // ... 2 column blocks per thread (N/16 > GEMV_MAXT)
+#endif
+#ifndef LPB_PAIR
+#define LPB_PAIR 4
+#endif
+#ifndef PFN
+#define PFN 2 // NPU layout prefetch distance (groups)
+#endif
+#ifndef PFN_DEEP
+#define PFN_DEEP 4 // ... few threads
+#endif
+#ifndef L1PL_DEEP
+#define L1PL_DEEP 2
+#endif
+#ifndef GEMV_DEEPT
+#define GEMV_DEEPT 400 // at most this many column blocks (threads): prefetch PFG_DEEP / L1PL_DEEP
+#endif
+#ifndef GEMV_MAXT
+#define GEMV_MAXT 960 // above this many 16*NCB-column blocks, each thread takes 2 (see the entry)
+#endif
+#define GS 64
+#define GB (GS / 4) // packed bytes per (group, column)
+#define NACC (RBG * NCB)
+
+#if WLAYOUT == 1 && NCB != 1
+#error "WLAYOUT 1 GEMV path is written for NCB == 1"
+#endif
+#ifndef WOQ_U2_GEMV_WGROUP_ONCE
+#define WOQ_U2_GEMV_WGROUP_ONCE
+struct wgroup { // one group of my NCB column blocks
+ vector<uint, 64 * NCB> w; // WLAYOUT 0: [cb][column n][4 dwords]; 1: [dword][column n]
+ vector<uint, 8 * NCB> sc; // [cb][16 halves]
+ vector<uint, 4 * NCB> zp; // [cb][16 uchars]
+ matrix<uint, 8 * RBG, 32> a; // the group's 64 k of my rows (rows >= M stay 0)
+};
+#endif
+
+template <int PF, int LP, int R, bool WIDE>
+inline void GEMV_BODY_FN(SurfaceIndex A, SurfaceIndex Wq, SurfaceIndex scales, SurfaceIndex zps,
+ SurfaceIndex epi, SurfaceIndex C, int M, int K, int N, int epi_mode) {
+ const int t = cm_group_id(0) * LS + cm_local_id(0);
+ // Column blocks per thread: 2 once one block per thread would exceed GEMV_MAXT threads (more than
+ // fit resident; measured cold-L2 at 1x5120x17920: 0.444 -> 0.358 ms), else 1 (fewer threads lose
+ // memory parallelism: 2 blocks at N = 5120 is 1.4x slower). Must match the dispatch grid.
+ const int cseq = (N / (16 * NCB) > GEMV_MAXT) ? 2 : 1;
+ int n0 = t * (16 * NCB) * cseq; // my first column block
+ if (n0 >= N) return; // surplus thread
+ const int m0 = cm_group_id(1) * (8 * RBG);
+ const int KG = K / GS;
+ const unsigned K2 = (unsigned)(K * 2);
+
+ vector<uint, 128> sh; // [k pair j][n] -> 4j
+ #pragma unroll
+ for (int i = 0; i < 128; i++) sh(i) = 4 * (i / 16);
+
+ // cseq adjacent column blocks, one after another (each walks all of K, as before).
+ for (int cs = 0; cs < cseq; cs++, n0 += 16 * NCB) {
+ if (n0 >= N) break;
+ matrix<float, NACC, 128> acc = 0.0f;
+ matrix<uint, RBG * (GS / 16), 64> a2s = 0; // [rb][k-step] Src2: 8 rows x 16 halves
+ wgroup cur, nxt;
+ cur.a = 0;
+ nxt.a = 0;
+
+#if WLAYOUT == 1
+ vector<uint, 16> lane;
+ #pragma unroll
+ for (int i = 0; i < 16; i++) lane(i) = i;
+ const vector<uint, 16> col = lane + (unsigned)n0;
+ const vector<uint, 16> w_off = col * (unsigned)(K / 4); // Wq [N, K/4]
+ const vector<uint, 16> sc_off = col * (unsigned)(KG * 2); // scales [N, KG] half
+ const vector<uint, 16> zp_off = col * (unsigned)KG; // zps [N, KG] uchar
+#endif
+ auto load = [&](wgroup &d, int g) {
+#if WLAYOUT == 0
+ const unsigned gn = (unsigned)g * (unsigned)N + (unsigned)n0;
+ #pragma unroll
+ for (int cb = 0; cb < NCB; cb++) {
+ d.w.select<64, 1>(cb * 64) = cm_load<uint, 64>(Wq, (gn + cb * 16) * (unsigned)GB);
+ d.sc.select<8, 1>(cb * 8) = cm_load<uint, 8>(scales, (gn + cb * 16) * 2u);
+ d.zp.select<4, 1>(cb * 4) = cm_load<uint, 4>(zps, gn + cb * 16);
+ }
+#else
+ d.w = cm_load<uint, VectorSize::N4, DataSize::U32>(Wq, w_off + (unsigned)g * (unsigned)GB);
+ d.sc.format<ushort>() = cm_load<ushort, VectorSize::N1, DataSize::U16>(scales, sc_off + (unsigned)g * 2u);
+ d.zp.format<uchar>() = cm_load<uchar, VectorSize::N1, DataSize::U8>(zps, zp_off + (unsigned)g);
+#endif
+ #pragma unroll
+ for (int r = 0; r < 8 * RBG; r++)
+ if (m0 + r < M)
+ d.a.row(r) = cm_load<uint, 32>(A, (unsigned)(m0 + r) * K2 + (unsigned)g * (GS * 2));
+ };
+ auto prefetch = [&](int g) {
+#if WLAYOUT == 0
+ const unsigned gn = (unsigned)g * (unsigned)N + (unsigned)n0;
+ cm_prefetch<16 * NCB * GB / 4, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, gn * (unsigned)GB);
+ cm_prefetch<8 * NCB, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(scales, gn * 2u);
+ cm_prefetch<4 * NCB, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(zps, gn);
+#else
+ if (g % (4 * LP) == 0) { // LP lines (4 groups each) per column
+ #pragma unroll
+ for (int l = 0; l < LP; l++)
+ if (g + 4 * l < KG) // stay inside the row
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, w_off + ((unsigned)g * (unsigned)GB + (unsigned)(l * 64)));
+ }
+ if (g % 32 == 0) // one scale line = 32 groups
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(scales, (sc_off + (unsigned)g * 2u) & ~3u);
+ if (g % 64 == 0)
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(zps, (zp_off + (unsigned)g) & ~3u);
+#endif
+ };
+
+#if WLAYOUT == 1
+ // Wide N-major path (M == 1, KG % 4 == 0). Per group the per-group path issues three 16-lane
+ // gathers -- 16 B of weights, 2 B of scale, 1 B of zero point per column, each lane a different
+ // line: ~48 line requests per group per thread, and the line-request rate is what bounds the
+ // small shapes (a probe that never waits on the loads is no faster). Here every line is read
+ // once: a column's 64 B weight line (4 groups) by two N8 gathers every 4 groups (double-buffered:
+// the next block's lines are requested when a block starts), its scales and
+ // zero points for 16 groups by one U32 N8 / N4 gather (dword-aligned rows need KG % 4 == 0):
+ // ~6 line requests per group. Same arithmetic, same k order: bit-exact.
+ if (WIDE) { // the entry checked the preconditions
+ vector<uint, 256> wlA, wlB; // [dword e 0..15][column]: 4 groups; ping-pong
+ vector<uint, 128> scl; // [dword e 0..7][column]: 16 groups (halves)
+ vector<uint, 64> zpl; // [dword e 0..3][column]: 16 groups (uchars)
+ vector<uint, 32> ar, arn; // row 0's 64 k of group g / g + 1
+ auto loadw = [&](vector_ref<uint, 256> wl, int g) { // gathers are at most N8 per lane
+ wl.select<128, 1>(0) = cm_load<uint, VectorSize::N8, DataSize::U32>(Wq, w_off + (unsigned)g * (unsigned)GB);
+ wl.select<128, 1>(128) = cm_load<uint, VectorSize::N8, DataSize::U32>(Wq, w_off + ((unsigned)g * (unsigned)GB + 32u));
+ };
+ auto loadsz = [&](int g) {
+ scl = cm_load<uint, VectorSize::N8, DataSize::U32>(scales, sc_off + (unsigned)g * 2u);
+ zpl = cm_load<uint, VectorSize::N4, DataSize::U32>(zps, zp_off + (unsigned)g);
+ };
+ loadw(wlA, 0);
+ loadsz(0);
+ ar = cm_load<uint, 32>(A, 0u);
+ #pragma unroll
+ for (int p = 1; p < PF; p++)
+ if (p < KG) prefetch(p);
+ #pragma unroll
+ for (int l = 0; l < (PF + 3) / 4; l++)
+ if (4 * l < KG)
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, w_off + (unsigned)(l * 64));
+
+ // One 4-group block from `wl`; the next block's lines go into `wn` as soon as this one starts.
+ auto block = [&](vector_ref<uint, 256> wl, vector_ref<uint, 256> wn, int g4) {
+ if (g4 + 4 < KG) loadw(wn, g4 + 4);
+ #pragma unroll
+ for (int u = 0; u < 4; u++) {
+ const int g = g4 + u;
+ if (g + PF < KG) prefetch(g + PF);
+ if (g + 1 < KG) arn = cm_load<uint, 32>(A, (unsigned)(g + 1) * (GS * 2));
+ a2s.select<GS / 16, 1, 8, 1>(0, 0) = ar.format<uint, GS / 16, 8>(); // row 0 of each k-step
+ const int gs = g & 15; // group within the scale / zp load
+ vector<half, 16> scv = scl.format<ushort>().select<16, 2>((gs >> 1) * 32 + (gs & 1)).format<half>();
+ vector<ushort, 16> zb = vector<ushort, 16>(zpl.format<uchar>().select<16, 4>((gs >> 2) * 64 + (gs & 3))) | (ushort)0x6400;
+ vector<half, 256> zr2 = zb.format<half>().replicate<16, 1, 2, 0>().replicate<8>(); // [j][n][e]
+ vector<half, 256> sr2 = scv.replicate<16, 1, 2, 0>().replicate<8>();
+ #pragma unroll
+ for (int s = 0; s < GS / 16; s++) {
+ vector<uint, 16> d = wl.select<16, 1>((u * 4 + s) * 16); // dword u*4 + s of each column
+ vector<uint, 128> x = d.replicate<8>() >> sh;
+ vector<uint, 128> t = (x & 0x0000FFFFu) | ((x << 14) & 0xFFFF0000u);
+ vector<uint, 128> q = (t & 0x00030003u) | 0x64006400u;
+ vector<half, 256> wv = (q.format<half>() - zr2) * sr2;
+ acc.row(0) = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, 8, 8>(
+ acc.row(0), wv.format<uint>(), a2s.row(s));
+ }
+ ar = arn;
+ }
+ if (g4 + 4 < KG && ((g4 + 4) & 15) == 0) loadsz(g4 + 4); // once per 16 groups
+ };
+ int g4 = 0;
+ for (; g4 + 8 <= KG; g4 += 8) { // ping-pong: buffer names stay static
+ block(wlA, wlB, g4);
+ block(wlB, wlA, g4 + 4);
+ }
+ if (g4 < KG) block(wlA, wlB, g4); // KG % 8 == 4
+ } else
+#endif
+ {
+ load(cur, 0);
+ #pragma unroll
+ for (int p = 1; p < PF; p++)
+ if (p < KG) prefetch(p);
+#if WLAYOUT == 1
+ // Lines covering groups 1 .. PF-1 that the in-loop prefetch (multiples of 4*LP / 32 / 64) skips.
+ #pragma unroll
+ for (int l = 0; l < (PF + 3) / 4; l++)
+ if (4 * l < KG)
+ cm_prefetch<VectorSize::N1, DataSize::U32, CacheHint::Cached, CacheHint::Cached>(Wq, w_off + (unsigned)(l * 64));
+#endif
+
+ for (int g = 0; g < KG; g++) {
+ if (g + PF < KG) prefetch(g + PF);
+ if (g + 1 < KG) load(nxt, g + 1);
+
+
+ #pragma unroll
+ for (int cb = 0; cb < NCB; cb++) {
+ vector<half, 16> scv = cur.sc.select<8, 1>(cb * 8).format<half>();
+ vector<ushort, 16> zb = vector<ushort, 16>(cur.zp.select<4, 1>(cb * 4).format<uchar>()) | (ushort)0x6400;
+ vector<half, 128> zr = zb.format<half>().replicate<8>(); // [j][n]
+ vector<half, 128> sr = scv.replicate<8>();
+ #pragma unroll
+ for (int s = 0; s < GS / 16; s++) { // DPAS k-steps of the group
+ // Column n's dword s holds k = 16s .. 16s+15; VNNI dword (j, n) = k pair 16s + 2j, +1, read
+ // from bits 4j (low half) and 4j + 2 (high half).
+#if WLAYOUT == 0
+ vector<uint, 16> d = cur.w.select<16, 4>(cb * 64 + s);
+#else
+ vector<uint, 16> d = cur.w.select<16, 1>(s * 16);
+#endif
+ vector<uint, 128> dr = d.replicate<8>();
+ vector<ushort, 128> q0 = vector<ushort, 128>((dr >> sh) & 3u) | (ushort)0x6400;
+ vector<ushort, 128> q1 = vector<ushort, 128>((dr >> (sh + 2u)) & 3u) | (ushort)0x6400;
+ vector<half, 256> wv;
+ wv.select<128, 2>(0) = (q0.format<half>() - zr) * sr;
+ wv.select<128, 2>(1) = (q1.format<half>() - zr) * sr;
+ vector<uint, 128> b1 = wv.format<uint>();
+ #pragma unroll
+ for (int rb = 0; rb < RBG; rb++) {
+ matrix<uint, 8, 8> a2 = cur.a.select<8, 1, 8, 1>(rb * 8, s * 8); // 8 rows x 16 halves
+ acc.row(rb * NCB + cb) = cm_dpas<CM_PRECISION_HF, CM_PRECISION_HF, 8, 8>(
+ acc.row(rb * NCB + cb), b1, a2.format<uint>());
+ }
+ }
+ }
+ cur = nxt;
+ }
+ }
+
+ // Epilogue: acc row (rb, cb) element (i*16 + n) = C[m0 + rb*8 + i][n0 + cb*16 + n].
+ #pragma unroll
+ for (int rb = 0; rb < RBG; rb++) {
+ #pragma unroll
+ for (int i = 0; i < 8; i++) {
+ const int m = m0 + rb * 8 + i;
+ if (m < M) {
+ #pragma unroll
+ for (int cb = 0; cb < NCB; cb++) {
+ const unsigned off = ((unsigned)m * N + (unsigned)(n0 + cb * 16)) * 4u;
+ vector<float, 16> v = acc.row(rb * NCB + cb).select<16, 1>(i * 16);
+ // Same operations, in the same order, as woq_u2_gemm_dual.cm's row-by-row (M tail) path.
+#if EPI_F16
+ // Transposed load only supports U32/U64 granularity: load as uint, reinterpret as half.
+ vector<half, 16> eh;
+ if (epi_mode != 0)
+ eh.format<uint>() = cm_load<uint, 8>(epi, off / 2u);
+ vector<float, 16> ef = eh; // widen half -> float
+#endif
+ if (epi_mode == 1) {
+#if EPI_F16
+ v += ef;
+#else
+ v += cm_load<float, 16>(epi, off);
+#endif
+ } else if (epi_mode == 2) {
+ vector<float, 16> e = cm_exp(v * -1.4426950408889634f);
+ v = v / (1.0f + e);
+#if EPI_F16
+ v *= ef;
+#else
+ v *= cm_load<float, 16>(epi, off);
+#endif
+ }
+#if OUT_F16
+ vector<half, 16> h = v; // round to nearest even
+ cm_store<uint, 8>(C, off / 2u, h.format<uint>());
+#else
+ cm_store<float, 16>(C, off, v);
+#endif
+ }
+ }
+ }
+ }
+ } // column blocks
+}
+
+
+extern "C" _GENX_MAIN_ void
+KERNEL_NAME(SurfaceIndex A [[type("buffer_t")]], // half [M, K]
+ SurfaceIndex Wq [[type("buffer_t")]], // uchar [KG, N, GS/4] (WLAYOUT 1: [N, K/4])
+ SurfaceIndex scales [[type("buffer_t")]], // half [KG, N] (WLAYOUT 1: [N, KG])
+ SurfaceIndex zps [[type("buffer_t")]], // uchar [KG, N] (WLAYOUT 1: [N, KG])
+ SurfaceIndex epi [[type("buffer_t")]], // float [M, N] (EPI_F16: half [M, N])
+ SurfaceIndex C [[type("buffer_t")]], // float [M, N] (OUT_F16: half [M, N])
+ int M, int K, int N, int epi_mode) {
+ // Compile-time instances (so each keeps its prefetch cadence and prologue unrolled), by shape class:
+ // few threads (N/16 <= GEMV_DEEPT) prefetch deeper; 2-block shapes (N/16 > GEMV_MAXT) and the rest
+ // have their own depths. R = 1 for the line-at-once path (M == 1: 1-row A buffers).
+ const int blocks = N / (16 * NCB);
+ const bool deep = blocks <= GEMV_DEEPT;
+#if WLAYOUT == 1
+ // Plain layout: every M == 1 shape with KG % 4 == 0 takes the line-at-once gather path (buffer
+ // accesses are bounds-checked, so 16-group scale / zero-point windows may run past a row's end).
+ // Prefetch by shape class: few threads PFB_DEEP / LPB_DEEP (cold-L2 1x5120x5120, 1x17920x5120),
+ // 2-block shapes PFB_PAIR / LPB_PAIR (1x5120x17920 -7% vs the per-group path), otherwise PFB / LPB.
+ // M > 1 (or KG % 4 != 0): the per-group path.
+ if (M == 1 && RBG == 1 && ((K / GS) & 3) == 0) {
+ if (deep) GEMV_BODY_FN<PFB_DEEP, LPB_DEEP, 1, true>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ else if (blocks > GEMV_MAXT) GEMV_BODY_FN<PFB_PAIR, LPB_PAIR, 1, true>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ else GEMV_BODY_FN<PFB, LPB, 1, true>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ return;
+ }
+ if (deep)
+ GEMV_BODY_FN<PFG_DEEP, L1PL_DEEP, 8, false>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ else
+ GEMV_BODY_FN<PFG, L1PL, 8, false>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+#else
+ // NPU layout: shallower prefetch, PFN / PFN_DEEP groups ahead (cold-L2: 1x5120x5120 -8%,
+ // 1x17920x5120 -6%, 1x5120x7680 -3% vs 4 / 8) -- except 2-block shapes (N/16 > GEMV_MAXT), which
+ // keep PFG (shallow is +10..+13% at 1x5120x17920).
+ if (deep)
+ GEMV_BODY_FN<PFN_DEEP, 1, 8, false>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ else if (blocks > GEMV_MAXT)
+ GEMV_BODY_FN<PFG, 1, 8, false>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+ else
+ GEMV_BODY_FN<PFN, 1, 8, false>(A, Wq, scales, zps, epi, C, M, K, N, epi_mode);
+#endif
+}
+
+// OpenVINO: keep this instance's macros out of the other kernels batched into the same program.
+#undef OUT_F16
+#undef EPI_F16
+#undef NCB
+#undef GEMV_MAXT
+#undef GEMV_DEEPT
+#undef PFG_DEEP
+#undef PFN
+#undef PFN_DEEP
+#undef PFB
+#undef LPB
+#undef PFB_DEEP
+#undef LPB_DEEP
+#undef PFB_PAIR
+#undef LPB_PAIR
+#undef L1PL_DEEP
+#undef RBG
+#undef LS
+#undef PFG
+#undef L1PL
+#undef GS
+#undef GB
+#undef NACC
+#undef GEMV_BODY_FN
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
index aa5df061b68..98666f7f2fe 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/primitive_ocl_base.hpp
@@ -207,7 +207,9 @@ struct PrimitiveImplOCL : public cldnn::primitive_impl {
void update_stages_flags(const cldnn::primitive_inst& instance) {
const auto current_flags = instance.get_impl_params()->flags.to_ulong();
constexpr size_t mask_args = (1 << cldnn::ExecutionFlags::ARG_UPDATE_REQUIRED) | (1 << cldnn::ExecutionFlags::IMPL_CHANGED);
- constexpr size_t mask_dispatch = (1 << cldnn::ExecutionFlags::SHAPE_CHANGED);
+ // A cached static impl taking over for an unchanged shape (IMPL_CHANGED without SHAPE_CHANGED) has never run its
+ // dispatch data function, so its dispatch data and scalars must be refreshed as well.
+ constexpr size_t mask_dispatch = (1 << cldnn::ExecutionFlags::SHAPE_CHANGED) | (1 << cldnn::ExecutionFlags::IMPL_CHANGED);
for (auto& stage : _stages) {
stage->kd.need_args_update = (current_flags & mask_args) != 0;
stage->kd.need_dispatch_data_update = (current_flags & mask_dispatch) != 0;
diff --git a/src/plugins/intel_gpu/src/graph/include/pass_manager.h b/src/plugins/intel_gpu/src/graph/include/pass_manager.h
index 7b400f922ec..d8a873681da 100644
--- a/src/plugins/intel_gpu/src/graph/include/pass_manager.h
+++ b/src/plugins/intel_gpu/src/graph/include/pass_manager.h
@@ -15,6 +15,7 @@
#include "concatenation_inst.h"
#include "convolution_inst.h"
#include "eltwise_inst.h"
+#include "fully_connected_inst.h"
#include "intel_gpu/graph/program.hpp"
#include "layout_optimizer.h"
#include "lora_inst.h"
@@ -39,6 +40,16 @@ private:
const std::string name;
};
+// Reorders grouped FC decompression scale/zp for OCL/oneDNN; returns the inserted reorder nodes.
+std::vector<program_node*> reorder_fc_decompression_params_if_needed(fully_connected_node& fc_node, program& p);
+
+// u2 FCs whose scale/zp reorder waits for implementation selection (CM keeps them bfyx). A scalar zero point never
+// reaches CM (it needs a per-group tensor), so those, e.g. TernOCL, reorder in prepare_quantization as before.
+inline bool defer_u2_decompression_reorder(const fully_connected_node& fc_node) {
+ const auto& prim = fc_node.get_primitive();
+ return prim->compressed_weights && fc_node.get_input_layout(1).data_type == data_types::u2 && !prim->decompression_zero_point_scalar.has_value();
+}
+
class pass_manager {
public:
explicit pass_manager(program& p);
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index e9833c7301d..78bd1626d64 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -3514,6 +3514,13 @@ bool primitive_inst::is_valid_fusion() const {
return true;
}
+ // GNK FCs have no other implementation to fall back to: if the impl rejects these runtime shapes (e.g. an epilogue
+ // operand that needs broadcasting), run the fused chain as separate primitives.
+ if (get_node().is_type<fully_connected>() && get_node().as<fully_connected>().get_primitive()->weights_layout == ov::intel_gpu::op::FcWeightsLayout::GNK &&
+ (_impl == nullptr || _impl->m_manager == nullptr || !_impl->m_manager->support_shapes(*_impl_params))) {
+ LOG_AND_RETURN_FALSE(_node);
+ }
+
if (get_node().is_type<fully_connected>() || get_node().is_type<gemm>() || get_node().is_type<convolution>()) {
if (_impl_params->input_layouts[0].count() == 0 || _impl_params->input_layouts[1].count() == 0) {
LOG_AND_RETURN_FALSE(_node);
@@ -3630,7 +3637,9 @@ ImplementationsFactory::ImplementationsFactory(const program_node* node)
std::shared_ptr<primitive_impl> ImplementationsFactory::get_primitive_impl_for_params(primitive_inst& inst,
const kernel_impl_params& params,
bool use_async_compilation) {
- auto find_impl = [this](const program_node* node, const kernel_impl_params& params, shape_types shape_type) -> std::unique_ptr<primitive_impl> {
+ // Managers are selected (shape type, support_shapes) with `params`; the impl is created from `create_params` if given.
+ auto find_impl = [this](const program_node* node, const kernel_impl_params& params, shape_types shape_type,
+ const kernel_impl_params* create_params = nullptr) -> std::unique_ptr<primitive_impl> {
OPENVINO_ASSERT(node != nullptr);
for (auto& impl_manager : m_available_impls) {
if ((impl_manager->get_shape_type() & shape_type) != shape_type) {
@@ -3641,7 +3650,7 @@ std::shared_ptr<primitive_impl> ImplementationsFactory::get_primitive_impl_for_p
continue;
}
- auto impl = impl_manager->create(*node, params);
+ auto impl = impl_manager->create(*node, create_params ? *create_params : params);
if (impl) {
return impl;
}
@@ -3731,13 +3740,20 @@ std::shared_ptr<primitive_impl> ImplementationsFactory::get_primitive_impl_for_p
}
// 4. Try to create new shape agnostic impl & cache it
+ // If cached dynamic impls all reject these shapes (e.g. CM for a fused epilogue needing broadcast), the fallback is selected
+ // with the runtime params but created from the node's own params, so it stays shape agnostic for other shapes.
+ // Without any cached dynamic impl, the node may not support dynamic params at all (e.g. a forced conv kernel): keep using the runtime params.
if (!dynamic_impl) {
- dynamic_impl = find_impl(node, params, shape_types::dynamic_shape);
+ const auto node_params = m_dynamic_impls_cache.empty() ? nullptr : node->get_kernel_impl_params();
+ const kernel_impl_params& create_params = node_params ? *node_params : params;
+ dynamic_impl = find_impl(node, params, shape_types::dynamic_shape, node_params.get());
if (dynamic_impl && !inst.can_be_optimized()) {
dynamic_impl->set_node_params(*node);
- auto kernels = kernels_cache.compile(params, dynamic_impl->get_kernels_source());
+ auto kernels = kernels_cache.compile(create_params, dynamic_impl->get_kernels_source());
dynamic_impl->set_kernels(std::move(kernels));
- m_dynamic_impls_cache.push_back(dynamic_impl);
+ if (!node_params || dynamic_impl->is_dynamic()) {
+ m_dynamic_impls_cache.push_back(dynamic_impl);
+ }
}
}
diff --git a/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp
index 60d1777ed41..03513e4a11c 100644
--- a/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp
+++ b/src/plugins/intel_gpu/src/graph/registry/fully_connected_impls.cpp
@@ -18,6 +18,10 @@
# define OV_GPU_CREATE_INSTANCE_TERNOCL(...)
#endif
+#if OV_GPU_WITH_CM
+ #include "impls/cm/fully_connected_woq_u2.hpp"
+#endif
+
namespace ov::intel_gpu {
using namespace cldnn;
@@ -35,6 +39,7 @@ const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<fully
static const std::vector<std::shared_ptr<ImplementationManager>> impls = {
OV_GPU_CREATE_INSTANCE_TERNOCL(cldnn::ocl::TernoclInt2FCImplementationManager, shape_types::dynamic_shape)
OV_GPU_CREATE_INSTANCE_TERNOCL(cldnn::ocl::TernoclInt2FCImplementationManager, shape_types::static_shape)
+ OV_GPU_CREATE_INSTANCE_CM(cm::FullyConnectedWoqU2ImplementationManager, shape_types::any)
OV_GPU_CREATE_INSTANCE_ONEDNN(onednn::FullyConnectedImplementationManager, shape_types::static_shape)
OV_GPU_GET_INSTANCE_OCL(fully_connected, shape_types::static_shape,
[](const program_node& node) {
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 67fcf50d80d..cbc0ddb9b7b 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
@@ -8,8 +8,10 @@
#include <memory>
#include "compressed_weights_pattern.hpp"
+#include "graph/impls/cm/fully_connected_woq_u2_gnk.hpp"
#include "intel_gpu/op/fully_connected.hpp"
#include "intel_gpu/op/fully_connected_compressed.hpp"
+#include "intel_gpu/op/placeholder.hpp"
#include "openvino/core/graph_util.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
@@ -28,7 +30,119 @@
namespace ov::intel_gpu {
using namespace ov::pass::pattern;
-ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyConnectedCompressed() {
+namespace {
+
+// [G, N, gs] u2 -> Transpose{1, 0, 2} -> Reshape [N, G * gs]
+bool is_gnk_u2_pattern(const std::shared_ptr<op::FullyConnected>& fc,
+ const std::shared_ptr<ov::Node>& weights,
+ const std::shared_ptr<ov::Node>& transpose_order,
+ const ov::PartialShape& reshaped) {
+ if (weights->get_element_type() != ov::element::u2 || !fc->get_transpose_b()) {
+ return false;
+ }
+ const auto& w_pshape = weights->get_output_partial_shape(0);
+ if (!w_pshape.is_static() || w_pshape.size() != 3) {
+ return false;
+ }
+ const auto order = ov::as_type_ptr<ov::op::v0::Constant>(transpose_order);
+ const auto w = w_pshape.to_shape();
+ return order && order->cast_vector<int64_t>() == std::vector<int64_t>{1, 0, 2} && reshaped.is_static() && reshaped.size() == 2 &&
+ reshaped[0].get_length() == static_cast<int64_t>(w[1]) && reshaped[1].get_length() == static_cast<int64_t>(w[0] * w[2]);
+}
+
+bool is_one_row_pshape(const ov::PartialShape& ps, int64_t last_dim) {
+ if (ps.rank().is_dynamic() || ps.size() == 0 || !ps[ps.size() - 1].is_static() || ps[ps.size() - 1].get_length() != last_dim) {
+ return false;
+ }
+ for (size_t i = 0; i + 1 < ps.size(); ++i) {
+ if (!ps[i].is_static() || ps[i].get_length() != 1) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Returns nullptr if the CM u2 GNK kernel does not accept this FC. scale / zp may be Constants or runtime nodes; nodes created
+// here (besides Constants) are appended to new_nodes.
+std::shared_ptr<op::FullyConnectedCompressed> try_create_gnk_u2_fc(const std::shared_ptr<op::FullyConnected>& fc,
+ const std::shared_ptr<ov::Node>& weights,
+ const ov::Output<ov::Node>& bias,
+ const std::shared_ptr<ov::Node>& scale,
+ const std::shared_ptr<ov::Node>& zp,
+ const cldnn::device_info& device_info,
+ bool cm_jit_supported,
+ ov::NodeVector& new_nodes) {
+ const auto& w_shape = weights->get_output_shape(0);
+ const auto& a_pshape = fc->get_input_partial_shape(0);
+ const auto out_et = fc->get_output_element_type(0);
+ const auto bias_node = bias.get_node_shared_ptr();
+ const bool a_ok = fc->get_input_element_type(0) == ov::element::f16 && a_pshape.rank().is_static() && a_pshape.size() >= 2 &&
+ a_pshape[a_pshape.size() - 1].is_static() &&
+ a_pshape[a_pshape.size() - 1].get_length() == static_cast<int64_t>(w_shape[0] * w_shape[2]);
+ const bool out_ok = out_et == ov::element::f16 || out_et == ov::element::f32;
+ const bool bias_ok = ov::is_type<op::Placeholder>(bias_node) ||
+ ((bias_node->get_output_element_type(0) == ov::element::f16 || bias_node->get_output_element_type(0) == ov::element::f32) &&
+ is_one_row_pshape(fc->get_output_partial_shape(0), static_cast<int64_t>(w_shape[1])) &&
+ is_one_row_pshape(bias_node->get_output_partial_shape(0), static_cast<int64_t>(w_shape[1])));
+ if (!a_ok || !out_ok || !bias_ok ||
+ !cm::woq_u2_accepts_gnk(device_info,
+ cm_jit_supported,
+ weights->get_element_type(),
+ weights->get_output_partial_shape(0),
+ scale->get_element_type(),
+ scale->get_output_partial_shape(0),
+ true,
+ zp->get_element_type(),
+ zp->get_output_partial_shape(0))) {
+ return nullptr;
+ }
+
+ const ov::Shape gn_shape{w_shape[0], w_shape[1]};
+ auto to_gn = [&](const std::shared_ptr<ov::Node>& node) -> std::shared_ptr<ov::Node> {
+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node)) {
+ auto reshaped = std::make_shared<ov::op::v0::Constant>(*constant, gn_shape);
+ ov::copy_weightless_cache_attr(constant, reshaped);
+ return reshaped;
+ }
+ if (node->get_output_shape(0) == gn_shape) {
+ return node;
+ }
+ auto shape = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{gn_shape.size()}, gn_shape);
+ auto reshaped = std::make_shared<ov::op::v1::Reshape>(node, shape, false);
+ new_nodes.push_back(shape);
+ new_nodes.push_back(reshaped);
+ return reshaped;
+ };
+
+ auto gnk_zp = to_gn(zp);
+ if (gnk_zp->get_element_type() != ov::element::u8) {
+ auto zp_u8 = std::make_shared<ov::op::v0::Convert>(gnk_zp, ov::element::u8);
+ if (auto zp_constant = ov::as_type_ptr<ov::op::v0::Constant>(gnk_zp)) {
+ ov::copy_weightless_cache_attr(zp_constant, zp_u8);
+ }
+ new_nodes.push_back(zp_u8);
+ gnk_zp = zp_u8;
+ }
+ auto gnk_fc = std::make_shared<op::FullyConnectedCompressed>(fc->input_value(0),
+ weights,
+ bias,
+ to_gn(scale),
+ gnk_zp,
+ fc->get_output_type(),
+ true,
+ false,
+ false,
+ op::FcWeightsLayout::GNK);
+ new_nodes.push_back(gnk_fc);
+ return gnk_fc;
+}
+
+} // namespace
+
+ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyConnectedCompressed(const cldnn::device_info& device_info,
+ bool cm_jit_supported)
+ : m_device_info(device_info),
+ m_cm_jit_supported(cm_jit_supported) {
auto data_m = any_input();
auto bias_m = any_input();
@@ -170,6 +284,28 @@ ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyCon
return result;
};
+ // u2 GNK weights can be passed to the CM kernel as is (scale / zp [G, N]) instead of being permuted to NK.
+ if (has_transpose_before_reshape && pattern_map.count(weights_reshape_m) == 0 && with_zero_point &&
+ is_gnk_u2_pattern(fc,
+ weight_ptr,
+ pattern_map.at(transpose_const_m).get_node_shared_ptr(),
+ pattern_map.at(transpose_before_reshape_m).get_node()->get_output_partial_shape(0))) {
+ ov::NodeVector gnk_nodes;
+ if (auto gnk_fc = try_create_gnk_u2_fc(fc,
+ weight_ptr,
+ pattern_map.at(bias_m),
+ scale_output.get_node_shared_ptr(),
+ pattern_map.at(sub_const_m).get_node_shared_ptr(),
+ m_device_info,
+ m_cm_jit_supported,
+ gnk_nodes)) {
+ gnk_fc->set_friendly_name(fc->get_friendly_name());
+ ov::copy_runtime_info(m.get_matched_nodes(), gnk_nodes);
+ ov::replace_node(fc, gnk_fc);
+ return true;
+ }
+ }
+
const ov::Output<Node>& fc_input_a = fc->input(0).get_source_output();
const auto& scale = has_transpose_before_reshape ? scale_output.get_node_shared_ptr() : reshape_input(scale_output.get_node_shared_ptr());
std::shared_ptr<ov::Node> optional_zero_point = nullptr;
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.hpp b/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.hpp
index bb12c74170d..01cfd65fb6b 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.hpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/convert_fc_to_compressed.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include "intel_gpu/runtime/device_info.hpp"
#include "openvino/pass/graph_rewrite.hpp"
namespace ov::intel_gpu {
@@ -11,7 +12,12 @@ namespace ov::intel_gpu {
class ConvertFullyConnectedToFullyConnectedCompressed: public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("ConvertFullyConnectedToFullyConnectedCompressed");
- ConvertFullyConnectedToFullyConnectedCompressed();
+ // device_info / cm_jit_supported feed cm::woq_u2_accepts_gnk for GNK u2 weights.
+ explicit ConvertFullyConnectedToFullyConnectedCompressed(const cldnn::device_info& device_info = {}, bool cm_jit_supported = false);
+
+private:
+ cldnn::device_info m_device_info;
+ bool m_cm_jit_supported;
};
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index a82d1f1e092..39b9ed18841 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -794,6 +794,8 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
if (infer_precision != ov::element::dynamic && !fp_precision_supported(infer_precision)) {
infer_precision = fallback_precision;
}
+ const bool cm_jit_supported = (device_info.arch == cldnn::gpu_arch::xe2 || device_info.arch == cldnn::gpu_arch::xe3) &&
+ check_cm_jit_support(m_context->get_engine(), config);
{
using namespace ov::pass::low_precision;
const auto enableQDQStripping = LowPrecision::isFunctionQuantized(func, std::set<levels>{levels::int16});
@@ -1923,7 +1925,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
if (!device_info.supports_immad) {
manager.register_pass<ov::intel_gpu::ReduceFCDimensions>();
}
- manager.register_pass<ov::intel_gpu::ConvertFullyConnectedToFullyConnectedCompressed>();
+ manager.register_pass<ov::intel_gpu::ConvertFullyConnectedToFullyConnectedCompressed>(device_info, cm_jit_supported);
manager.register_pass<ov::intel_gpu::FoldActivationTranspose>();
const bool disable_horizontal_fc_fusion = GPU_DEBUG_VALUE_OR(config.get_disable_horizontal_fc_fusion(), false);
diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmake
index 1ea68e28bff..a4fd957180e 100644
--- a/src/plugins/intel_gpu/tests/unit/sources.cmake
+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake
@@ -199,6 +199,7 @@ set(GPU_UNIT_TESTS_SRCS
${CMAKE_CURRENT_LIST_DIR}/test_cases/experimental_detectron_topk_rois_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/extract_image_patches_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/eye.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/test_cases/fully_connected_cm_woq_u2_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/fully_connected_gpu_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/fully_connected_weights_layout_test.cpp
${CMAKE_CURRENT_LIST_DIR}/test_cases/gated_delta_net.cpp
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_cm_woq_u2_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_cm_woq_u2_test.cpp
new file mode 100644
index 00000000000..66314d48fbf
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_cm_woq_u2_test.cpp
@@ -0,0 +1,1982 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Conformance tests for the CM u2 weight-only-quantized fully connected implementation
+// (impls/cm/fully_connected_woq_u2.cpp, kernel impls/cm/woq_u2_gemm_dual.cm). The kernel takes u8
+// per-group zero points, so every case uses those (other zero-point kinds are rejected by validate_impl
+// and fall back to the OCL reference); the output is f16 (OUT_F16, what an f16 model uses) or f32.
+//
+// Every conformance case runs in both of the kernel's weight layouts and both output types (f16 / f32):
+// nmajor : weights [N, K/4], scales / zero points [N, K/64] -- what a compressed FC provides;
+// gmajor : weights [K/64, N, 16 B], scales / zero points [K/64, N] -- the kernel's group-major path,
+// selected through woq_u2_weight_layout_for_tests() with the buffers filled group-major.
+// Each case forces the CM implementation, checks that it was actually selected, and compares its output
+// with a host reference that uses the kernel's arithmetic (see host_reference(); for f16 output also its
+// final rounding to fp16), see compare_values() for the pass criteria.
+//
+// smoke_* : small / edge shapes (M tails, partial column tiles, odd group counts, 3D input,
+// dynamic M, two u2 layers in one program)
+// perf_shapes_* : the u2 oneDNN benchdnn matmul cases (bd<n>, numbered as in the benchdnn list), with
+// their exact input rank, shapes, output type and
+// post-op (bd2 / bd5: add f32 [M, N]; bd8 / bd11: add f32 per column; bd4: swish x mul f16
+// [M, N]; bd10: swish x mul f16 per column), in both weight layouts. On M = 512 the
+// reference computes 8 rows per 256-row tile (all N, all K). Not part of the smoke run;
+// select them with --gtest_filter=perf_shapes*fully_connected_cm_woq_u2*
+//
+// Post-ops (Epi): FC bias [N]; a fused eltwise sum with an operand; a fused swish (beta 1) + eltwise prod
+// (SwiGLU). The operand has the output's shape and dtype; a per-column operand / bias ([.., 1, N], epi_row)
+// only with M = 1, where it is that shape (the kernels do not broadcast). A trailing reorder keeps the post-op from being the network output, so
+// prepare_primitive_fusing fuses it into the FC; every post-op case checks it ran inside the CM kernel.
+
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <functional>
+#include <iomanip>
+#include <iostream>
+#include <random>
+#include <sstream>
+#include <string>
+#include <thread>
+
+#include "common_test_utils/graph_comparator.hpp"
+#include "fully_connected_inst.h"
+#include "impls/cm/fully_connected_woq_u2.hpp"
+#include "intel_gpu/graph/program.hpp"
+#include "intel_gpu/op/fully_connected.hpp"
+#include "intel_gpu/op/fully_connected_compressed.hpp"
+#include "intel_gpu/op/placeholder.hpp"
+#include "intel_gpu/plugin/remote_context.hpp"
+#include "intel_gpu/plugin/transformations_pipeline.hpp"
+#include "intel_gpu/primitives/activation.hpp"
+#include "intel_gpu/primitives/data.hpp"
+#include "intel_gpu/primitives/eltwise.hpp"
+#include "intel_gpu/primitives/fully_connected.hpp"
+#include "intel_gpu/primitives/input_layout.hpp"
+#include "intel_gpu/primitives/quantize.hpp"
+#include "intel_gpu/primitives/reorder.hpp"
+#include "intel_gpu/runtime/compilation_context.hpp"
+#include "intel_gpu/runtime/internal_properties.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/pass/manager.hpp"
+#include "pass_manager.h"
+#include "plugin/transformations/convert_fc_to_compressed.hpp"
+#include "plugin/transformations/fuse_hadamard_fc.hpp"
+#include "program_wrapper.h"
+#include "random_generator.hpp"
+#include "reorder_inst.h"
+#include "test_utils.h"
+
+using namespace cldnn;
+using namespace ::tests;
+using ov::intel_gpu::cm::woq_u2_nk_enabled_for_tests;
+using ov::intel_gpu::cm::woq_u2_weight_layout_for_tests;
+using ov::intel_gpu::cm::WoqU2WeightLayout;
+
+namespace {
+
+// Enables the NK test path for the lifetime of the scope while keeping the process-wide default false.
+struct NkEnabledScope {
+ bool saved = woq_u2_nk_enabled_for_tests();
+ NkEnabledScope() {
+ woq_u2_nk_enabled_for_tests() = true;
+ }
+ ~NkEnabledScope() {
+ woq_u2_nk_enabled_for_tests() = saved;
+ }
+};
+
+enum class ZpKind { none, tensor_f16, tensor_u8, scalar };
+
+// Post-op of a case: none; FC bias [N] (M = 1 only); fused add (fc + t); fused SwiGLU (swish(fc) * t). t is
+// an input shaped like the output, or one row (epi_row, M = 1 only).
+enum class Epi { none, bias, add, swiglu };
+
+struct WoqU2Case {
+ int64_t M, K, N;
+ ZpKind zp;
+ int64_t seq = 0; // > 0: 3D input [M/seq, seq, K]
+ bool dynamic = false; // dynamic M; executed at M and at two more sizes
+ bool sample_rows = false; // reference computes a row sample only (all N columns, all of K)
+ Epi epi = Epi::none;
+ bool epi_row = false; // add / SwiGLU operand is one row [.., 1, N] (per column; M = 1 only)
+ int bd = 0; // > 0: number of the benchdnn case it reproduces
+};
+
+std::string zp_name(ZpKind z) {
+ switch (z) {
+ case ZpKind::none:
+ return "nozp";
+ case ZpKind::tensor_f16:
+ return "zpf16";
+ case ZpKind::tensor_u8:
+ return "zpu8";
+ default:
+ return "zpscalar";
+ }
+}
+
+std::string layout_name(WoqU2WeightLayout l) {
+ return l == WoqU2WeightLayout::n_major ? "nmajor" : "gmajor";
+}
+
+// (case, weight layout, output type): every conformance case runs in all four combinations.
+using WoqU2Param = std::tuple<WoqU2Case, WoqU2WeightLayout, data_types>;
+
+std::string case_name(const testing::TestParamInfo<WoqU2Param>& info) {
+ const auto& c = std::get<0>(info.param);
+ std::string name = (c.bd ? "bd" + std::to_string(c.bd) + "_" : std::string()) + "M" + std::to_string(c.M) + "_K" + std::to_string(c.K) + "_N" +
+ std::to_string(c.N) + "_" + zp_name(c.zp);
+ if (c.seq)
+ name += "_seq" + std::to_string(c.seq);
+ if (c.dynamic)
+ name += "_dyn";
+ if (c.epi == Epi::bias)
+ name += "_bias";
+ if (c.epi == Epi::add)
+ name += c.epi_row ? "_addrow" : "_add";
+ if (c.epi == Epi::swiglu)
+ name += c.epi_row ? "_swiglurow" : "_swiglu";
+ return name + "_" + layout_name(std::get<1>(info.param)) + (std::get<2>(info.param) == data_types::f32 ? "_f32out" : "_f16out");
+}
+
+bool cm_woq_u2_supported(engine& e) {
+ const auto& info = e.get_device_info();
+ auto config = get_test_default_config(e);
+ // The FC registry dereferences the legacy OCL impls, which exist only after this call; a test that runs first in its process would crash.
+ program::init_primitives();
+ // The device can run CM while this build has no CM backend (ENABLE_CM_FOR_GPU=OFF).
+ const auto& impls = fully_connected::type_id()->get_all_implementations();
+ const bool cm_registered = std::any_of(impls.begin(), impls.end(), [](const auto& impl) {
+ return impl->get_type_info() == ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::get_type_info_static();
+ });
+ return cm_registered && (info.arch == gpu_arch::xe2 || info.arch == gpu_arch::xe3) && info.max_local_mem_size >= 98304 && check_cm_jit_support(e, config);
+}
+
+// Constant inputs of one u2 FC. Host copies are always N-major: packed weights [N, K/4] (4 per byte, LSB
+// first along K), scales / zero points [N, K/64]. The device buffers hold them in `layout`.
+struct WoqU2Weights {
+ memory::ptr weights, scale, zp;
+ float zp_scalar = 1.5f;
+ int64_t K = 0, N = 0;
+ std::vector<uint8_t> packed;
+ std::vector<ov::float16> scales;
+ std::vector<uint8_t> zp_u8; // empty: no zero point
+};
+
+// Selects the kernel's weight layout for the lifetime of the scope (network build and execution).
+struct WeightLayoutScope {
+ WoqU2WeightLayout saved;
+ explicit WeightLayoutScope(WoqU2WeightLayout l) : saved(woq_u2_weight_layout_for_tests()) {
+ woq_u2_weight_layout_for_tests() = l;
+ }
+ ~WeightLayoutScope() {
+ woq_u2_weight_layout_for_tests() = saved;
+ }
+};
+
+// Fast deterministic 64-bit generator (splitmix64): the perf shapes need ~10^8 random values, which
+// per-element std:: distributions make the dominant cost of the whole suite.
+struct SplitMix64 {
+ uint64_t s;
+ uint64_t next() {
+ uint64_t z = (s += 0x9E3779B97F4A7C15ull);
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
+ return z ^ (z >> 31);
+ }
+};
+
+// Activations uniform on the grid k/1024 in [-1, 1), generated from a 2048-entry fp16 table.
+std::vector<ov::float16> random_activations(size_t count, uint64_t seed) {
+ static const std::vector<ov::float16> table = [] {
+ std::vector<ov::float16> t(2048);
+ for (int i = 0; i < 2048; i++)
+ t[static_cast<size_t>(i)] = ov::float16(static_cast<float>(i - 1024) / 1024.0f);
+ return t;
+ }();
+ std::vector<ov::float16> v(count);
+ SplitMix64 rng{seed};
+ size_t i = 0;
+ while (i < count) {
+ uint64_t bits = rng.next();
+ for (int j = 0; j < 5 && i < count; j++, bits >>= 11) // five 11-bit indices per draw
+ v[i++] = table[static_cast<size_t>(bits & 2047u)];
+ }
+ return v;
+}
+
+WoqU2Weights make_weights(engine& engine,
+ int64_t K,
+ int64_t N,
+ ZpKind zk,
+ tests::random_generator& rg,
+ uint32_t seed,
+ WoqU2WeightLayout layout = WoqU2WeightLayout::n_major) {
+ const int64_t KG = K / 64;
+ WoqU2Weights r;
+ r.K = K;
+ r.N = N;
+ std::mt19937 gen(seed);
+ std::uniform_int_distribution<int> q_dist(0, 3);
+ // Uniformly random bytes are uniformly random u2 values (4 per byte, LSB first along K).
+ std::vector<uint8_t> packed(static_cast<size_t>(N * K / 4));
+ SplitMix64 rng{seed};
+ for (size_t i = 0; i < packed.size(); i += 8) {
+ const uint64_t bits = rng.next();
+ for (size_t j = 0; j < 8 && i + j < packed.size(); j++)
+ packed[i + j] = static_cast<uint8_t>(bits >> (8 * j));
+ }
+
+ auto scales = rg.generate_random_1d<ov::float16>(N * KG, 0.005f, 0.025f, 10000);
+ std::vector<ov::float16> zp_f16;
+ std::vector<uint8_t> zp_u8;
+ if (zk == ZpKind::tensor_f16)
+ zp_f16 = rg.generate_random_1d<ov::float16>(N * KG, 0.0f, 3.0f, 1000); // non-integer zero points
+ if (zk == ZpKind::tensor_u8) {
+ zp_u8.resize(static_cast<size_t>(N * KG));
+ for (auto& v : zp_u8)
+ v = static_cast<uint8_t>(q_dist(gen));
+ }
+
+ OPENVINO_ASSERT(layout == WoqU2WeightLayout::n_major || zk == ZpKind::tensor_u8, "group-major weights need u8 zero points");
+ r.packed = packed;
+ r.scales = scales;
+ r.zp_u8 = zp_u8;
+ if (layout == WoqU2WeightLayout::group_major) {
+ // Same byte count, group-major order: Wq[g][n][16 B], scales / zero points [g][n].
+ std::vector<uint8_t> packed_g(packed.size()), zp_g(zp_u8.size());
+ std::vector<ov::float16> scales_g(scales.size());
+ for (int64_t n = 0; n < N; n++)
+ for (int64_t g = 0; g < KG; g++) {
+ std::copy_n(packed.begin() + n * (K / 4) + g * 16, 16, packed_g.begin() + (g * N + n) * 16);
+ scales_g[static_cast<size_t>(g * N + n)] = scales[static_cast<size_t>(n * KG + g)];
+ zp_g[static_cast<size_t>(g * N + n)] = zp_u8[static_cast<size_t>(n * KG + g)];
+ }
+ packed = packed_g;
+ scales = scales_g;
+ zp_u8 = zp_g;
+ }
+
+ r.weights = engine.allocate_memory({{N, K}, data_types::u2, format::bfyx});
+ r.scale = engine.allocate_memory({{N, KG}, data_types::f16, format::bfyx});
+ set_values(r.weights, packed);
+ set_values(r.scale, scales);
+ if (zk == ZpKind::tensor_f16) {
+ r.zp = engine.allocate_memory({{N, KG}, data_types::f16, format::bfyx});
+ set_values(r.zp, zp_f16);
+ } else if (zk == ZpKind::tensor_u8) {
+ r.zp = engine.allocate_memory({{N, KG}, data_types::u8, format::bfyx});
+ set_values(r.zp, zp_u8);
+ }
+
+ return r;
+}
+
+void add_weights(topology& topo, const std::string& prefix, const WoqU2Weights& w) {
+ topo.add(data(prefix + "weights", w.weights));
+ topo.add(data(prefix + "scale", w.scale));
+ if (w.zp)
+ topo.add(data(prefix + "zp", w.zp));
+}
+
+fully_connected make_fc(const std::string& id,
+ const std::string& input,
+ const std::string& prefix,
+ ZpKind zk,
+ data_types out_dt,
+ size_t input_rank,
+ float zp_scalar,
+ bool with_bias = false) {
+ const bool zp_tensor = zk == ZpKind::tensor_f16 || zk == ZpKind::tensor_u8;
+ auto fc = fully_connected(id,
+ input_info(input),
+ prefix + "weights",
+ with_bias ? prefix + "bias" : "",
+ prefix + "scale",
+ zp_tensor ? prefix + "zp" : "",
+ out_dt,
+ input_rank,
+ 2);
+ if (zk == ZpKind::scalar)
+ fc.decompression_zero_point_scalar = zp_scalar;
+ return fc;
+}
+
+ExecutionConfig woq_config(engine& engine, const std::vector<std::string>& ids) {
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ ov::intel_gpu::ImplForcingMap forcing;
+ for (const auto& id : ids)
+ forcing[id] = ov::intel_gpu::ImplementationDesc{format::bfyx, "", impl_types::cm};
+ config.set_property(ov::intel_gpu::force_implementations(forcing));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+ return config;
+}
+
+// First `count` elements of an f16 / f32 output (dynamic-shape outputs may be over-allocated).
+std::vector<float> read_output(memory::ptr mem, size_t count, bool out_f32) {
+ std::vector<float> out(count);
+ if (out_f32) {
+ cldnn::mem_lock<float, mem_lock_type::read> lk(mem, get_test_stream());
+ OPENVINO_ASSERT(lk.size() >= count, "output smaller than expected");
+ std::copy(lk.begin(), lk.begin() + count, out.begin());
+ } else {
+ cldnn::mem_lock<ov::float16, mem_lock_type::read> lk(mem, get_test_stream());
+ OPENVINO_ASSERT(lk.size() >= count, "output smaller than expected");
+ for (size_t i = 0; i < count; i++)
+ out[i] = static_cast<float>(lk[i]);
+ }
+ return out;
+}
+
+// Host reference for the given rows of A ([*, K] f16, row-major), all N columns, with the CM kernel's
+// arithmetic: each weight is dequantized to fp16 as the kernel does -- one round-to-nearest-even of
+// (q - zp) * scale, where q - zp is a small exact integer -- and the fp16 x fp16 products (exact in f32)
+// are summed in double. The only difference left to the kernel is the order of its f32 summation.
+std::vector<float> host_reference(const std::vector<ov::float16>& a, const std::vector<int64_t>& rows, const WoqU2Weights& w) {
+ const int64_t K = w.K, N = w.N, KG = K / 64, R = static_cast<int64_t>(rows.size());
+ std::vector<float> a32(static_cast<size_t>(R * K));
+ for (int64_t i = 0; i < R; i++)
+ for (int64_t k = 0; k < K; k++)
+ a32[static_cast<size_t>(i * K + k)] = static_cast<float>(a[static_cast<size_t>(rows[static_cast<size_t>(i)] * K + k)]);
+ std::vector<float> out(static_cast<size_t>(R * N));
+ auto columns = [&](int64_t n0, int64_t n1) {
+ std::vector<float> deq(static_cast<size_t>(K));
+ for (int64_t n = n0; n < n1; n++) {
+ for (int64_t k = 0; k < K; k++) {
+ const int q = (w.packed[static_cast<size_t>(n * (K / 4) + k / 4)] >> (2 * (k % 4))) & 3;
+ const size_t gi = static_cast<size_t>(n * KG + k / 64);
+ const int zp = w.zp_u8.empty() ? 0 : w.zp_u8[gi];
+ deq[static_cast<size_t>(k)] = static_cast<float>(ov::float16(static_cast<float>(q - zp) * static_cast<float>(w.scales[gi])));
+ }
+ for (int64_t i = 0; i < R; i++) {
+ const float* ar = a32.data() + i * K;
+ double acc = 0.0;
+ for (int64_t k = 0; k < K; k++)
+ acc += static_cast<double>(ar[k]) * deq[static_cast<size_t>(k)];
+ out[static_cast<size_t>(i * N + n)] = static_cast<float>(acc);
+ }
+ }
+ };
+ const int64_t nt = std::max<int64_t>(1, std::min<int64_t>(static_cast<int64_t>(std::thread::hardware_concurrency()), N / 32));
+ std::vector<std::thread> pool;
+ for (int64_t t = 0; t < nt; t++)
+ pool.emplace_back(columns, N * t / nt, N * (t + 1) / nt);
+ for (auto& th : pool)
+ th.join();
+ return out;
+}
+
+// Pass criterion, CM output vs host reference, the same threshold for both output types:
+// f32 output: |CM - ref| <= max_abs_diff per element. Only the order of the f32 summation differs from
+// the reference (measured <= 1.5e-5 up to K = 17920); 1e-4 is OpenVINO's functional-test
+// f32 threshold.
+// f16 output: the kernel rounds its f32 result to fp16 (nearest even), so the same bound is applied
+// before that rounding: the CM value must be the fp16 rounding of some value within
+// max_abs_diff of ref, i.e. ref must lie within max_abs_diff of the CM value's rounding
+// interval (the reals that round to it). That distance is the smallest f32 error that could
+// have produced the CM value -- the kernel's own f32 result is never visible. A result next to
+// a rounding midpoint may therefore land on either neighbouring fp16 value (the two sides
+// differ only by the summation noise); at most max_midpoint_fraction of the elements may do
+// so (measured <= 0.29 %; a subtle dequant defect measured 9-37 %).
+constexpr float max_abs_diff = 1e-4f;
+constexpr double max_midpoint_fraction = 0.01;
+
+// Distance from x to the interval of reals that round (to nearest) to the fp16 value h; 0 if x is inside.
+float distance_to_fp16_rounding_interval(float x, ov::float16 h) {
+ const uint16_t b = h.to_bits();
+ const float v = static_cast<float>(h);
+ // Neighbouring fp16 values below and above h (sign-magnitude encoding; +-0 neighbours are +-2^-24).
+ auto neighbour = [&](bool up) {
+ const bool neg = (b & 0x8000) != 0;
+ const uint16_t mag = b & 0x7fff;
+ if (mag == 0)
+ return up ? 1.0f / (1 << 24) : -1.0f / (1 << 24);
+ const bool away = up != neg; // moving away from zero
+ return static_cast<float>(ov::float16::from_bits(static_cast<uint16_t>((b & 0x8000) | (away ? mag + 1 : mag - 1))));
+ };
+ const float lo = 0.5f * (v + neighbour(false)), hi = 0.5f * (v + neighbour(true));
+ return x < lo ? lo - x : (x > hi ? x - hi : 0.0f);
+}
+
+// CM output vs the host reference, row-major [rows, N]; `row_ids` names the output row of each compared
+// row. `ref` is always the unrounded reference.
+void compare_values(const std::vector<float>& out,
+ const std::vector<float>& ref,
+ int64_t N,
+ const std::vector<int64_t>* row_ids = nullptr,
+ bool out_f16 = false) {
+ size_t bad = 0, first_bad = 0, differing = 0;
+ float max_err = 0.0f;
+ for (size_t i = 0; i < out.size(); i++) {
+ // NaN makes every comparison in the f16 interval distance false, i.e. a zero error.
+ ASSERT_TRUE(std::isfinite(out[i])) << "Non-finite CM output at index " << i;
+ ASSERT_TRUE(std::isfinite(ref[i])) << "Non-finite reference at index " << i;
+ // f32: distance to ref; f16: distance from ref to the values that round to the CM value.
+ const float err = out_f16 ? distance_to_fp16_rounding_interval(ref[i], ov::float16(out[i])) : std::fabs(out[i] - ref[i]);
+ max_err = std::max(max_err, err);
+ if (out_f16 && out[i] != static_cast<float>(ov::float16(ref[i])))
+ differing++;
+ if (!(err <= max_abs_diff)) {
+ if (bad++ == 0)
+ first_bad = i;
+ }
+ }
+ if (out_f16)
+ std::cout << " [cm vs host ref, f16] min possible f32 error = " << max_err << " (limit " << max_abs_diff << "), " << differing << " / "
+ << out.size() << " at a rounding midpoint (" << 100.0 * static_cast<double>(differing) / static_cast<double>(out.size())
+ << " %, allowed <= " << 100.0 * max_midpoint_fraction << " %)" << "\n";
+ else
+ std::cout << " [cm vs host ref, f32] max|d| = " << max_err << " (limit " << max_abs_diff << ")" << "\n";
+ const int64_t bad_row = row_ids ? (*row_ids)[static_cast<size_t>(first_bad / N)] : static_cast<int64_t>(first_bad / N);
+ ASSERT_EQ(bad, size_t(0)) << bad << " of " << out.size() << " compared outputs are more than " << max_abs_diff
+ << (out_f16 ? " from any value that rounds to them" : " off") << "; first at row " << bad_row << ", col " << first_bad % N
+ << ": got " << out[first_bad] << ", reference " << ref[first_bad];
+ if (out_f16) {
+ ASSERT_LE(static_cast<double>(differing), max_midpoint_fraction * static_cast<double>(out.size()))
+ << differing << " of " << out.size() << " f16 outputs differ from the fp16-rounded reference (more than " << 100.0 * max_midpoint_fraction
+ << " %): too many for rounding-midpoint cases";
+ }
+}
+
+// CM output rows `rows` of an [m, N] output vs the host reference.
+// Host epilogue: kind, operand values (row-major, [m, N] or one row [N] when `row`).
+struct HostEpi {
+ Epi kind = Epi::none;
+ const std::vector<float>* t = nullptr;
+ bool row = false;
+};
+
+// The reference applies the epilogue in double, in the kernel's order: acc + t, or acc / (1 + exp(-acc)) * t.
+void check_rows(memory::ptr out_mem,
+ int64_t m,
+ const std::vector<ov::float16>& a,
+ const std::vector<int64_t>& rows,
+ const WoqU2Weights& w,
+ bool out_f32,
+ const HostEpi& epi = {}) {
+ const int64_t N = w.N, R = static_cast<int64_t>(rows.size());
+ const auto out_all = read_output(out_mem, static_cast<size_t>(m * N), out_f32);
+ std::vector<float> out_rows(static_cast<size_t>(R * N));
+ for (int64_t i = 0; i < R; i++)
+ std::copy_n(out_all.begin() + rows[static_cast<size_t>(i)] * N, N, out_rows.begin() + i * N);
+ auto ref = host_reference(a, rows, w);
+ if (epi.kind != Epi::none) {
+ for (int64_t i = 0; i < R; i++)
+ for (int64_t n = 0; n < N; n++) {
+ const int64_t trow = epi.row ? 0 : rows[static_cast<size_t>(i)];
+ const double t = (*epi.t)[static_cast<size_t>(trow * N + n)];
+ double v = ref[static_cast<size_t>(i * N + n)];
+ v = epi.kind == Epi::swiglu ? v / (1.0 + std::exp(-v)) * t : v + t;
+ ref[static_cast<size_t>(i * N + n)] = static_cast<float>(v);
+ }
+ }
+ compare_values(out_rows, ref, N, &rows, !out_f32);
+}
+
+std::vector<int64_t> all_rows(int64_t M) {
+ std::vector<int64_t> rows(static_cast<size_t>(M));
+ for (int64_t i = 0; i < M; i++)
+ rows[static_cast<size_t>(i)] = i;
+ return rows;
+}
+
+// Rows compared on the large shapes: 8 per 256-row work-group tile, one in each of the tile's 8
+// row-threads (32 rows each) at a different offset inside the thread's 4 x 8-row blocks, plus the last
+// row. All N columns and all of K are always checked.
+std::vector<int64_t> sample_rows(int64_t M) {
+ std::vector<int64_t> rows;
+ for (int64_t base = 0; base < M; base += 256)
+ for (int64_t t = 0; t < 8; t++) {
+ const int64_t r = base + t * 32 + (t * 5) % 32;
+ if (r < M)
+ rows.push_back(r);
+ }
+ if (rows.back() != M - 1)
+ rows.push_back(M - 1);
+ return rows;
+}
+
+class fully_connected_cm_woq_u2 : public ::testing::TestWithParam<WoqU2Param> {};
+
+TEST_P(fully_connected_cm_woq_u2, conformance) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const auto p = std::get<0>(GetParam());
+ const auto wl = std::get<1>(GetParam());
+ const auto out_dt = std::get<2>(GetParam());
+ const bool out_f32 = out_dt == data_types::f32;
+ const WeightLayoutScope layout_scope(wl);
+ const int64_t M = p.M, K = p.K, N = p.N;
+ ASSERT_EQ(K % 64, 0);
+ ASSERT_EQ(N % 32, 0);
+ if (p.seq) {
+ ASSERT_EQ(M % p.seq, 0);
+ }
+
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, p.zp, rg, static_cast<uint32_t>(M * 131 + K * 7 + N), wl);
+
+ const size_t input_rank = p.seq ? 3 : 2;
+ auto make_shape = [&](int64_t m) {
+ return p.seq ? ov::PartialShape{m / p.seq, p.seq, K} : ov::PartialShape{m, K};
+ };
+ auto net_in_shape = p.dynamic ? (p.seq ? ov::PartialShape{-1, p.seq, K} : ov::PartialShape{-1, K}) : make_shape(M);
+
+ // The host reference computes a row sample only on the large shapes (all N columns, all of K).
+ if (p.sample_rows) {
+ ASSERT_FALSE(p.dynamic);
+ }
+ const bool fused_post_op = p.epi == Epi::add || p.epi == Epi::swiglu;
+ auto make_out_shape = [&](int64_t m) {
+ return p.seq ? ov::PartialShape{m / p.seq, p.seq, N} : ov::PartialShape{m, N};
+ };
+ // Shape of the add / SwiGLU operand: the output's, or one row [.., 1, N].
+ auto make_epi_shape = [&](int64_t m) {
+ if (p.epi_row)
+ return p.seq ? ov::PartialShape{1, 1, N} : ov::PartialShape{1, N};
+ return make_out_shape(m);
+ };
+ auto net_epi_shape = p.epi_row ? make_epi_shape(1) : (p.dynamic ? (p.seq ? ov::PartialShape{-1, p.seq, N} : ov::PartialShape{-1, N}) : make_out_shape(M));
+ // Operand / bias values: f16-representable, so the same values serve an f16 and an f32 tensor.
+ auto make_epi_values = [&](size_t count, uint64_t seed) {
+ const auto h = random_activations(count, seed);
+ std::vector<float> v(count);
+ for (size_t i = 0; i < count; i++)
+ v[i] = static_cast<float>(h[i]);
+ return v;
+ };
+ auto upload = [&](const ov::PartialShape& shape, const std::vector<float>& v) {
+ auto mem = engine.allocate_memory({shape, out_dt, format::bfyx});
+ if (out_dt == data_types::f32) {
+ set_values(mem, v);
+ } else {
+ std::vector<ov::float16> h(v.size());
+ for (size_t i = 0; i < v.size(); i++)
+ h[i] = ov::float16(v[i]);
+ set_values(mem, h);
+ }
+ return mem;
+ };
+ std::vector<float> bias_values;
+ if (p.epi == Epi::bias)
+ bias_values = make_epi_values(static_cast<size_t>(N), static_cast<uint64_t>(N * 31 + K));
+
+ auto build = [&](const ov::PartialShape& in_shape) {
+ topology topo(input_layout("input", layout{in_shape, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ if (p.epi == Epi::bias)
+ topo.add(data("bias", upload(ov::PartialShape{1, N}, bias_values)));
+ topo.add(make_fc("fc_prim", "input", "", p.zp, out_dt, input_rank, w.zp_scalar, p.epi == Epi::bias));
+ std::string last = "fc_prim";
+ if (fused_post_op) {
+ topo.add(input_layout("epi", layout{net_epi_shape, out_dt, format::bfyx}));
+ if (p.epi == Epi::swiglu) {
+ // gate_proj-style SwiGLU: swish(fc) * t.
+ topo.add(activation("swish", input_info("fc_prim"), activation_func::swish, {1.0f, 0.0f}));
+ topo.add(eltwise("post", input_info("swish"), input_info("epi"), eltwise_mode::prod));
+ } else {
+ topo.add(eltwise("post", input_info("fc_prim"), input_info("epi"), eltwise_mode::sum));
+ }
+ last = "post";
+ }
+ // Keeps the post-op from being the network output (outputs are not fused); removed later as redundant.
+ topo.add(reorder("out", input_info(last), format::bfyx, out_dt));
+ return topo;
+ };
+ auto net_topology = build(net_in_shape);
+ network::ptr network = get_network(engine, net_topology, woq_config(engine, {"fc_prim"}), get_test_stream_ptr(), false);
+
+ std::vector<int64_t> run_ms = {M};
+ if (p.dynamic) {
+ const int64_t step = p.seq ? p.seq : 1;
+ run_ms.push_back(std::max<int64_t>(step, (M / 3) / step * step));
+ run_ms.push_back(M + 8 * step);
+ }
+
+ for (const int64_t m : run_ms) {
+ SCOPED_TRACE("M = " + std::to_string(m));
+ auto a = random_activations(static_cast<size_t>(m * K), static_cast<uint64_t>(m * 1000003 + K));
+ auto input_mem = engine.allocate_memory({make_shape(m), data_types::f16, format::bfyx});
+ set_values(input_mem, a);
+ network->set_input_data("input", input_mem);
+ std::vector<float> epi_values;
+ if (fused_post_op) {
+ const auto shape = make_epi_shape(m);
+ epi_values = make_epi_values(static_cast<size_t>(ov::shape_size(shape.to_shape())), static_cast<uint64_t>(m * 7919 + N));
+ network->set_input_data("epi", upload(shape, epi_values));
+ }
+ auto outputs = network->execute();
+ ASSERT_EQ(outputs.size(), size_t(1));
+ // The CM FC must have run. Its id depends on graph cleanup (with the trailing reorder removed it
+ // takes the output's id), so look for it among the executed primitives. A post-op must run inside
+ // it (epi_mode 1 / 2), not as a separate kernel.
+ bool cm_ran = false;
+ for (const auto& id : network->get_executed_primitive_ids()) {
+ const auto impl = network->get_primitive(id)->get_impl();
+ cm_ran |= impl && impl->get_kernel_name().find("woq_u2") != std::string::npos;
+ ASSERT_TRUE(id != "swish" && id != "post") << "post-op was not fused into the CM FC (" << id << " ran separately)";
+ }
+ ASSERT_TRUE(cm_ran) << "CM u2 FC implementation was not selected";
+ HostEpi he;
+ he.kind = p.epi;
+ he.row = p.epi == Epi::bias || p.epi_row;
+ he.t = p.epi == Epi::bias ? &bias_values : &epi_values;
+ check_rows(outputs.at("out").get_memory(), m, a, p.sample_rows ? sample_rows(m) : all_rows(m), w, out_f32, he);
+ }
+}
+
+// Performance of the CM implementation on the benchmark shapes of test_woq_cm.py, measured with GPU
+// profiling events (kernel execution time of the FC only), for every weight layout and output type.
+// Not a conformance check and disabled by default; run with
+// --gtest_also_run_disabled_tests --gtest_filter=*fully_connected_cm_woq_u2_perf*
+// Environment: OV_WOQ_U2_PERF_ITERS (CM runs per shape, default 100); OV_WOQ_U2_PERF_SHAPES replaces the
+// built-in shapes with a list of MxKxN, separated by ',' (e.g. "1x5120x7680,128x5120x17920"; K % 64 == 0,
+// N % 32 == 0).
+// Device-resident copy: test buffers default to the lockable allocation type (host USM on a discrete
+// GPU), while a compiled model keeps constants and activations in device memory.
+memory::ptr to_device(engine& engine, const memory::ptr& m) {
+ if (!m)
+ return nullptr;
+ auto d = engine.allocate_memory(m->get_layout(), allocation_type::usm_device, false);
+ d->copy_from(get_test_stream(), *m, true);
+ return d;
+}
+
+TEST(fully_connected_cm_woq_u2_perf, DISABLED_benchmark_shapes) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ auto env_int = [](const char* name, int def) {
+ const char* v = std::getenv(name);
+ return v ? std::max(0, std::atoi(v)) : def;
+ };
+ const int cm_iters = std::max(1, env_int("OV_WOQ_U2_PERF_ITERS", 100));
+
+ // XMX roof: EUs x clock x 256 fp16 flop/clk/EU (Xe2). On Arc B580 this is the 116.7 TFLOP/s measured
+ // with a DPAS-only probe.
+ const auto& info = engine.get_device_info();
+ const double peak_tflops = static_cast<double>(info.execution_units_count) * info.gpu_frequency * 1e-3 * 256.0 * 1e-3;
+
+ struct Shape {
+ int64_t M, K, N;
+ ZpKind zp;
+ };
+ std::vector<Shape> shapes = {{512, 5120, 7680, ZpKind::tensor_u8},
+ {512, 5120, 5120, ZpKind::tensor_u8},
+ {512, 5120, 17920, ZpKind::tensor_u8},
+ {512, 17920, 5120, ZpKind::tensor_u8},
+ {1024, 5120, 7680, ZpKind::tensor_u8},
+ {1024, 5120, 17920, ZpKind::tensor_u8},
+ {2048, 5120, 7680, ZpKind::tensor_u8},
+ {2048, 5120, 17920, ZpKind::tensor_u8},
+ {2048, 17920, 5120, ZpKind::tensor_u8}};
+ if (const char* env = std::getenv("OV_WOQ_U2_PERF_SHAPES")) {
+ shapes.clear();
+ std::stringstream list(env);
+ std::string item;
+ while (std::getline(list, item, ',')) {
+ int64_t m = 0, k = 0, n = 0;
+ char x1 = 0, x2 = 0;
+ std::stringstream one(item);
+ ASSERT_TRUE((one >> m >> x1 >> k >> x2 >> n) && x1 == 'x' && x2 == 'x' && m > 0 && k > 0 && n > 0)
+ << "OV_WOQ_U2_PERF_SHAPES: expected MxKxN, got '" << item << "'";
+ ASSERT_TRUE(k % 64 == 0 && n % 32 == 0) << "OV_WOQ_U2_PERF_SHAPES: " << item << " needs K % 64 == 0 and N % 32 == 0";
+ shapes.push_back({m, k, n, ZpKind::tensor_u8});
+ }
+ ASSERT_FALSE(shapes.empty()) << "OV_WOQ_U2_PERF_SHAPES is empty";
+ }
+
+ // Kernel execution times (ms) of the FC over `iters` runs after `warmup` runs.
+ auto measure = [&](const WoqU2Weights& w,
+ ZpKind zk,
+ data_types out_dt,
+ memory::ptr input_mem,
+ int64_t M,
+ int64_t K,
+ const ExecutionConfig& cfg,
+ int warmup,
+ int iters,
+ std::string& impl_name) {
+ topology topo(input_layout("input", layout{ov::PartialShape{M, K}, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ topo.add(make_fc("fc_prim", "input", "", zk, out_dt, 2, w.zp_scalar));
+ auto config = cfg;
+ config.set_property(ov::enable_profiling(true));
+ network net(engine, topo, config);
+ net.set_input_data("input", input_mem);
+ std::vector<double> ms;
+ for (int i = 0; i < warmup + iters; i++) {
+ auto outputs = net.execute();
+ outputs.at("fc_prim").get_memory(); // waits for completion
+ if (i < warmup)
+ continue;
+ auto ev = net.get_executed_primitives().at("fc_prim");
+ for (const auto& interval : ev->get_profiling_info())
+ if (interval.stage == instrumentation::profiling_stage::executing)
+ ms.push_back(static_cast<double>(interval.value->value().count()) * 1e-6);
+ }
+ impl_name = net.get_primitive("fc_prim")->get_impl()->get_kernel_name();
+ std::sort(ms.begin(), ms.end());
+ return ms;
+ };
+
+ std::cout << "\n XMX roof " << std::fixed << std::setprecision(1) << peak_tflops << " TFLOP/s (" << info.execution_units_count << " EUs x "
+ << info.gpu_frequency << " MHz x 256). CM: " << cm_iters << " runs/shape.\n"
+ << " M K N zp layout out | CM best CM median TFLOP/s %roof\n";
+ tests::random_generator rg(GET_SUITE_NAME);
+ for (const auto& s : shapes) {
+ for (const auto wl : {WoqU2WeightLayout::n_major, WoqU2WeightLayout::group_major}) {
+ for (const auto out_dt : {data_types::f16, data_types::f32}) {
+ const WeightLayoutScope layout_scope(wl);
+ auto w = make_weights(engine, s.K, s.N, s.zp, rg, 5, wl);
+ w.weights = to_device(engine, w.weights);
+ w.scale = to_device(engine, w.scale);
+ w.zp = to_device(engine, w.zp);
+ auto a = random_activations(static_cast<size_t>(s.M * s.K), 17);
+ auto host_input = engine.allocate_memory({ov::PartialShape{s.M, s.K}, data_types::f16, format::bfyx});
+ set_values(host_input, a);
+ auto input_mem = to_device(engine, host_input);
+
+ std::string cm_impl;
+ const auto cm = measure(w, s.zp, out_dt, input_mem, s.M, s.K, woq_config(engine, {"fc_prim"}), 5, cm_iters, cm_impl);
+ ASSERT_FALSE(cm.empty()) << "no profiling data";
+ ASSERT_NE(cm_impl.find("woq_u2"), std::string::npos) << "CM implementation not selected (got " << cm_impl << ")";
+ const double best = cm.front(), median = cm[cm.size() / 2];
+ const double tflops = 2.0 * static_cast<double>(s.M) * s.K * s.N / (best * 1e-3) * 1e-12;
+ std::cout << std::setw(7) << s.M << std::setw(7) << s.K << std::setw(7) << s.N << " " << std::left << std::setw(4) << zp_name(s.zp).substr(2)
+ << std::setw(7) << layout_name(wl) << std::setw(4) << (out_dt == data_types::f16 ? "f16" : "f32") << std::right << " | "
+ << std::setprecision(4) << std::setw(8) << best << std::setw(11) << median << std::setprecision(1) << std::setw(9) << tflops
+ << std::setw(6) << 100.0 * tflops / peak_tflops << "%\n"
+ << std::flush;
+ }
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ fully_connected_cm_woq_u2,
+ ::testing::Combine(::testing::Values(
+ // correctness shapes of test_woq_cm.py (u8 zero points)
+ WoqU2Case{8, 128, 256, ZpKind::tensor_u8},
+ WoqU2Case{5, 128, 256, ZpKind::tensor_u8},
+ WoqU2Case{13, 192, 512, ZpKind::tensor_u8}, // KG = 3 (odd group count)
+ WoqU2Case{16, 256, 256, ZpKind::tensor_u8},
+ WoqU2Case{3, 320, 512, ZpKind::tensor_u8}, // KG = 5
+ WoqU2Case{300, 448, 1024, ZpKind::tensor_u8}, // KG = 7
+ WoqU2Case{517, 5120, 512, ZpKind::tensor_u8},
+ // edge cases: tiny, partial column work-group (N % 256 != 0), 3D input
+ WoqU2Case{1, 64, 32, ZpKind::tensor_u8},
+ WoqU2Case{64, 256, 288, ZpKind::tensor_u8},
+ WoqU2Case{33, 1024, 800, ZpKind::tensor_u8},
+ WoqU2Case{256, 512, 256, ZpKind::tensor_u8},
+ WoqU2Case{24, 384, 512, ZpKind::tensor_u8, 6},
+ // dynamic M (shape-agnostic kernel, re-dispatched per shape)
+ WoqU2Case{96, 512, 512, ZpKind::tensor_u8, 0, true},
+ WoqU2Case{40, 256, 544, ZpKind::tensor_u8, 8, true},
+ // post-ops: tiled kernel (M > 8) and GEMV (M <= 8), operand shaped like the output
+ WoqU2Case{64, 256, 288, ZpKind::tensor_u8, 0, false, false, Epi::add},
+ WoqU2Case{40, 512, 512, ZpKind::tensor_u8, 0, false, false, Epi::swiglu},
+ WoqU2Case{24, 384, 512, ZpKind::tensor_u8, 6, false, false, Epi::add},
+ WoqU2Case{5, 128, 256, ZpKind::tensor_u8, 0, false, false, Epi::add},
+ WoqU2Case{8, 128, 256, ZpKind::tensor_u8, 0, false, false, Epi::swiglu},
+ // per-column operand / bias: M = 1 only
+ WoqU2Case{1, 256, 288, ZpKind::tensor_u8, 0, false, false, Epi::add, true},
+ WoqU2Case{1, 512, 256, ZpKind::tensor_u8, 0, false, false, Epi::swiglu, true},
+ WoqU2Case{1, 64, 32, ZpKind::tensor_u8, 0, false, false, Epi::bias},
+ // post-ops with dynamic M
+ WoqU2Case{96, 512, 512, ZpKind::tensor_u8, 0, true, false, Epi::add},
+ WoqU2Case{40, 256, 544, ZpKind::tensor_u8, 8, true, false, Epi::swiglu}),
+ ::testing::Values(WoqU2WeightLayout::n_major, WoqU2WeightLayout::group_major),
+ ::testing::Values(data_types::f16, data_types::f32)),
+ case_name);
+
+// The u2 oneDNN benchdnn matmul cases: src BxMxK : wei 1xKxN, --wtag=cab (weights [N, K]), scales f16 /
+// zero points u8 per 64 along K, --attr-fpmath=f16. Input rank and shapes as given (BxM flattened by the
+// FC), output type fixed per case; both weight layouts each.
+std::vector<WoqU2Param> benchdnn_u2_cases() {
+ struct BenchCase {
+ WoqU2Case c;
+ data_types out;
+ };
+ const auto u8 = ZpKind::tensor_u8;
+ const std::vector<BenchCase> cases = {
+ // src : wei, post-op (benchdnn mask 6 = full [M, N] tensor, mask 4 = per column)
+ {WoqU2Case{512, 5120, 7680, u8, 1, false, true, Epi::none, false, 1}, data_types::f16}, // 512x1x5120:1x5120x7680
+ {WoqU2Case{512, 5120, 5120, u8, 512, false, true, Epi::add, false, 2}, data_types::f32}, // 1x512x5120:1x5120x5120, add f32:6
+ {WoqU2Case{512, 5120, 17920, u8, 1, false, true, Epi::none, false, 3}, data_types::f16}, // 512x1x5120:1x5120x17920
+ {WoqU2Case{512, 5120, 17920, u8, 512, false, true, Epi::swiglu, false, 4}, data_types::f16}, // 1x512x5120:1x5120x17920, swish+mul f16:6
+ {WoqU2Case{512, 17920, 5120, u8, 512, false, true, Epi::add, false, 5}, data_types::f32}, // 1x512x17920:1x17920x5120, add f32:6
+ {WoqU2Case{1, 5120, 7680, u8, 1, false, false, Epi::none, false, 7}, data_types::f16}, // 1x1x5120:1x5120x7680
+ {WoqU2Case{1, 5120, 5120, u8, 1, false, false, Epi::add, true, 8}, data_types::f32}, // 1x1x5120:1x5120x5120, add f32:4
+ {WoqU2Case{1, 5120, 17920, u8, 1, false, false, Epi::none, false, 9}, data_types::f16}, // 1x1x5120:1x5120x17920
+ {WoqU2Case{1, 5120, 17920, u8, 1, false, false, Epi::swiglu, true, 10}, data_types::f16}, // 1x1x5120:1x5120x17920, swish+mul f16:4
+ {WoqU2Case{1, 17920, 5120, u8, 1, false, false, Epi::add, true, 11}, data_types::f32}, // 1x1x17920:1x17920x5120, add f32:4
+ };
+ std::vector<WoqU2Param> params;
+ for (const auto& bc : cases)
+ for (const auto wl : {WoqU2WeightLayout::n_major, WoqU2WeightLayout::group_major})
+ params.emplace_back(bc.c, wl, bc.out);
+ return params;
+}
+
+INSTANTIATE_TEST_SUITE_P(perf_shapes, fully_connected_cm_woq_u2, ::testing::ValuesIn(benchdnn_u2_cases()), case_name);
+
+// Kernel time of the 10 u2 benchdnn cases, one row each, exactly as benchdnn runs them: input rank, shapes,
+// output type and post-op of benchdnn_u2_cases(), weights N-major (--wtag=cab), the post-op fused into the
+// CM FC; measured with GPU profiling events on the CM FC kernel alone. Reports
+// TFLOP/s against the XMX peak and the effective weight bandwidth (u2 weights + f16 scales + u8 zero points,
+// 0.297 B per K x N element), the meaningful number for M = 1. Disabled by default; run with
+// --gtest_also_run_disabled_tests --gtest_filter=*fully_connected_cm_woq_u2_perf.DISABLED_benchdnn_cases*
+// Environment: OV_WOQ_U2_PERF_ITERS (runs per case, default 100).
+TEST(fully_connected_cm_woq_u2_perf, DISABLED_benchdnn_cases) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+ const char* iters_env = std::getenv("OV_WOQ_U2_PERF_ITERS");
+ const int iters = std::max(1, iters_env ? std::atoi(iters_env) : 100);
+ const int warmup = 5;
+ const auto& info = engine.get_device_info();
+ const double peak_tflops = static_cast<double>(info.execution_units_count) * info.gpu_frequency * 1e-3 * 256.0 * 1e-3;
+
+ auto post_name = [](const WoqU2Case& c) -> std::string {
+ switch (c.epi) {
+ case Epi::bias:
+ return "bias";
+ case Epi::add:
+ return c.epi_row ? "add/col" : "add";
+ case Epi::swiglu:
+ return c.epi_row ? "swiglu/col" : "swiglu";
+ default:
+ return "-";
+ }
+ };
+ std::cout << "\n XMX roof " << std::fixed << std::setprecision(1) << peak_tflops << " TFLOP/s. " << iters << " runs per case." << "\n"
+ << " bd M K N out post-op kernel | CM best CM median TFLOP/s %roof weight GB/s" << "\n";
+ tests::random_generator rg(GET_SUITE_NAME);
+ for (const auto& prm : benchdnn_u2_cases()) {
+ const auto& c = std::get<0>(prm);
+ const auto wl = std::get<1>(prm);
+ const auto out_dt = std::get<2>(prm);
+ if (wl != WoqU2WeightLayout::n_major)
+ continue; // benchdnn's weights are N-major (--wtag=cab)
+ const WeightLayoutScope layout_scope(wl);
+ const bool fused_post_op = c.epi == Epi::add || c.epi == Epi::swiglu;
+
+ auto w = make_weights(engine, c.K, c.N, c.zp, rg, 5, wl);
+ w.weights = to_device(engine, w.weights);
+ w.scale = to_device(engine, w.scale);
+ w.zp = to_device(engine, w.zp);
+ const auto in_shape = c.seq ? ov::PartialShape{c.M / c.seq, c.seq, c.K} : ov::PartialShape{c.M, c.K};
+ const auto out_shape = c.seq ? ov::PartialShape{c.M / c.seq, c.seq, c.N} : ov::PartialShape{c.M, c.N};
+ const auto epi_shape = c.epi_row ? (c.seq ? ov::PartialShape{1, 1, c.N} : ov::PartialShape{1, c.N}) : out_shape;
+ auto device_tensor = [&](const ov::PartialShape& shape, uint64_t seed) {
+ const auto h = random_activations(ov::shape_size(shape.to_shape()), seed);
+ auto host = engine.allocate_memory({shape, out_dt, format::bfyx});
+ if (out_dt == data_types::f32) {
+ std::vector<float> f(h.size());
+ for (size_t i = 0; i < h.size(); i++)
+ f[i] = static_cast<float>(h[i]);
+ set_values(host, f);
+ } else {
+ set_values(host, h);
+ }
+ return to_device(engine, host);
+ };
+
+ const size_t input_rank = c.seq ? 3 : 2;
+ topology topo(input_layout("input", layout{in_shape, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ if (c.epi == Epi::bias)
+ topo.add(data("bias", device_tensor(ov::PartialShape{1, c.N}, 3)));
+ topo.add(make_fc("fc_prim", "input", "", c.zp, out_dt, input_rank, w.zp_scalar, c.epi == Epi::bias));
+ std::string last = "fc_prim";
+ if (fused_post_op) {
+ topo.add(input_layout("epi", layout{epi_shape, out_dt, format::bfyx}));
+ if (c.epi == Epi::swiglu) {
+ topo.add(activation("swish", input_info("fc_prim"), activation_func::swish, {1.0f, 0.0f}));
+ topo.add(eltwise("post", input_info("swish"), input_info("epi"), eltwise_mode::prod));
+ } else {
+ topo.add(eltwise("post", input_info("fc_prim"), input_info("epi"), eltwise_mode::sum));
+ }
+ last = "post";
+ }
+ topo.add(reorder("out", input_info(last), format::bfyx, out_dt));
+
+ auto config = woq_config(engine, {"fc_prim"});
+ config.set_property(ov::enable_profiling(true));
+ network net(engine, topo, config);
+ auto host_in = engine.allocate_memory({in_shape, data_types::f16, format::bfyx});
+ set_values(host_in, random_activations(static_cast<size_t>(c.M * c.K), 17));
+ net.set_input_data("input", to_device(engine, host_in));
+ if (fused_post_op)
+ net.set_input_data("epi", device_tensor(epi_shape, 29));
+
+ std::vector<double> ms;
+ std::string kernel = "-";
+ bool post_op_separate = false;
+ for (int i = 0; i < warmup + iters; i++) {
+ auto outputs = net.execute();
+ outputs.at("out").get_memory(); // waits for completion
+ if (i < warmup)
+ continue;
+ for (const auto& [id, ev] : net.get_executed_primitives()) {
+ post_op_separate |= id == "swish" || id == "post";
+ const auto impl = net.get_primitive(id)->get_impl();
+ if (!impl || impl->get_kernel_name().find("woq_u2") == std::string::npos)
+ continue;
+ kernel = impl->get_kernel_name();
+ for (const auto& interval : ev->get_profiling_info())
+ if (interval.stage == instrumentation::profiling_stage::executing)
+ ms.push_back(static_cast<double>(interval.value->value().count()) * 1e-6);
+ }
+ }
+ ASSERT_FALSE(ms.empty()) << "bd" << c.bd << ": the CM u2 FC did not run";
+ ASSERT_FALSE(post_op_separate) << "bd" << c.bd << ": the post-op was not fused into the CM FC";
+ std::sort(ms.begin(), ms.end());
+ const double best = ms.front(), median = ms[ms.size() / 2];
+ const double tflops = 2.0 * static_cast<double>(c.M) * c.K * c.N / (best * 1e-3) * 1e-12;
+ const double weight_gbs = static_cast<double>(c.K) * c.N * (0.25 + 2.0 / 64 + 1.0 / 64) / (best * 1e-3) * 1e-9;
+ std::cout << " " << std::left << std::setw(4) << ("bd" + std::to_string(c.bd)) << std::right << std::setw(5) << c.M << std::setw(7) << c.K
+ << std::setw(7) << c.N << " " << (out_dt == data_types::f16 ? "f16" : "f32") << " " << std::left << std::setw(11) << post_name(c)
+ << std::setw(6) << (c.M <= 8 ? "gemv" : "tiled") << std::right << " | " << std::setprecision(4) << std::setw(8) << best << std::setw(11)
+ << median << std::setprecision(1) << std::setw(9) << tflops << std::setw(6) << 100.0 * tflops / peak_tflops << "%" << std::setw(13)
+ << weight_gbs << "\n"
+ << std::flush;
+ }
+}
+
+// Scale / zero-point reorder decision for a u2 FC: prepare_quantization defers it, select_preferred_formats
+// keeps bfyx for CM and otherwise reorders only when weights_transposed and transpose_b_scale / zp are set.
+struct U2ReorderResult {
+ bool deferred = false; // no reorder after prepare_quantization
+ bool cm_accepts = false; // CM validate_impl result
+ bool scale_reordered = false;
+ bool zp_reordered = false;
+};
+
+U2ReorderResult run_u2_reorder_passes(engine& engine, int64_t N, int64_t K, bool weights_transposed, bool transpose_b_params) {
+ const int64_t G = K / 64;
+ const auto w_shape = weights_transposed ? ov::PartialShape{N, K} : ov::PartialShape{K, N};
+ const auto p_shape = weights_transposed && transpose_b_params ? ov::PartialShape{N, G} : ov::PartialShape{G, N};
+ topology topo(input_layout("input", layout{ov::PartialShape{16, K}, data_types::f16, format::bfyx}));
+ topo.add(data("weights", engine.allocate_memory({w_shape, data_types::u2, format::bfyx})));
+ topo.add(data("scale", engine.allocate_memory({p_shape, data_types::f16, format::bfyx})));
+ topo.add(data("zp", engine.allocate_memory({p_shape, data_types::u8, format::bfyx})));
+ topo.add(fully_connected("fc",
+ input_info("input"),
+ "weights",
+ "",
+ "scale",
+ "zp",
+ data_types::f16,
+ 2,
+ 2,
+ weights_transposed,
+ transpose_b_params,
+ transpose_b_params));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ auto prog = program::build_program(engine, topo, config, false, true);
+ auto& fc = prog->get_node("fc").as<fully_connected>();
+ fc.get_output_layouts(false);
+
+ U2ReorderResult r;
+ program_wrapper::apply_opt_pass<prepare_quantization>(*prog);
+ r.deferred = !fc.get_dependency(2).is_type<reorder>() && !fc.get_dependency(3).is_type<reorder>();
+ r.cm_accepts = ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::validate_base(fc, true);
+ program_wrapper::apply_opt_pass<select_preferred_formats>(*prog);
+ r.scale_reordered = fc.get_dependency(2).is_type<reorder>();
+ r.zp_reordered = fc.get_dependency(3).is_type<reorder>();
+ return r;
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_reorder, cm_selected_keeps_scale_zp_bfyx) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+ const auto r = run_u2_reorder_passes(engine, 64, 128, true, true);
+ ASSERT_TRUE(r.deferred);
+ ASSERT_TRUE(r.cm_accepts);
+ ASSERT_FALSE(r.scale_reordered);
+ ASSERT_FALSE(r.zp_reordered);
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_reorder, cm_not_selected_reorders_scale_zp) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ // N % 32 != 0: CM rejects it.
+ const auto r = run_u2_reorder_passes(engine, 48, 128, true, true);
+ ASSERT_TRUE(r.deferred);
+ ASSERT_FALSE(r.cm_accepts);
+ ASSERT_TRUE(r.scale_reordered);
+ ASSERT_TRUE(r.zp_reordered);
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_reorder, scale_zp_not_transposed_no_reorder) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ // Scale / zp [G, N]; the second case is square (N == G).
+ for (const auto& [N, K] : std::vector<std::pair<int64_t, int64_t>>{{64, 128}, {32, 32 * 64}}) {
+ SCOPED_TRACE("N=" + std::to_string(N) + " K=" + std::to_string(K));
+ const auto r = run_u2_reorder_passes(engine, N, K, true, false);
+ ASSERT_FALSE(r.cm_accepts);
+ ASSERT_FALSE(r.scale_reordered);
+ ASSERT_FALSE(r.zp_reordered);
+ }
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_reorder, weights_not_transposed_no_reorder) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ // transpose_b_scale / zp left true: only the weights_transposed early return prevents the reorder.
+ const auto r = run_u2_reorder_passes(engine, 64, 128, false, true);
+ ASSERT_FALSE(r.cm_accepts);
+ ASSERT_FALSE(r.scale_reordered);
+ ASSERT_FALSE(r.zp_reordered);
+}
+
+// A scalar zero point never reaches CM (it needs a per-group tensor); TernOCL, which does use one, checks the scale
+// layout in validate_impl, i.e. before select_preferred_formats could reorder it, so it must happen in prepare_quantization.
+TEST(smoke_fully_connected_cm_woq_u2_reorder, scalar_zero_point_reorders_in_prepare_quantization) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ const int64_t N = 64, K = 256, G = K / 64;
+ topology topo(input_layout("input", layout{ov::PartialShape{16, K}, data_types::f16, format::bfyx}));
+ topo.add(data("weights", engine.allocate_memory({ov::PartialShape{N, K}, data_types::u2, format::bfyx})));
+ topo.add(data("scale", engine.allocate_memory({ov::PartialShape{N, G}, data_types::f16, format::bfyx})));
+ auto fc_prim = fully_connected("fc", input_info("input"), "weights", "", "scale", "", data_types::f16, 2, 2, true, true, true);
+ fc_prim.decompression_zero_point_scalar = 1;
+ topo.add(fc_prim);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ auto prog = program::build_program(engine, topo, config, false, true);
+ auto& fc = prog->get_node("fc").as<fully_connected>();
+ fc.get_output_layouts(false);
+
+ EXPECT_FALSE(defer_u2_decompression_reorder(fc));
+ program_wrapper::apply_opt_pass<prepare_quantization>(*prog);
+ EXPECT_TRUE(fc.get_dependency(2).is_type<reorder>());
+}
+
+// Dynamic M and a dynamic operand pass the static epilogue check (both dims are merely "dynamic"), but at run time the
+// operand can have fewer rows than the output: an eltwise broadcast the kernels do not do, they would read past its
+// single row. support_shapes() re-runs the check on the concrete layouts, so this is the rule it relies on.
+TEST(smoke_fully_connected_cm_woq_u2_epi_operand, runtime_row_broadcast_is_rejected) {
+ constexpr int64_t N = 512;
+ auto f16 = [](const ov::PartialShape& s) {
+ return layout{s, data_types::f16, format::bfyx};
+ };
+ using ov::intel_gpu::cm::woq_u2_check_epi_operand;
+
+ // Why a runtime check is needed at all: dynamic against dynamic passes.
+ EXPECT_TRUE(woq_u2_check_epi_operand(f16({-1, N}), f16({-1, N}), N).empty());
+
+ // Same rows: runs on CM.
+ EXPECT_TRUE(woq_u2_check_epi_operand(f16({5, N}), f16({5, N}), N).empty());
+ EXPECT_TRUE(woq_u2_check_epi_operand(f16({2, 4, N}), f16({2, 4, N}), N).empty());
+ // A single output row may take a single-row operand (bias-like).
+ EXPECT_TRUE(woq_u2_check_epi_operand(f16({1, N}), f16({1, N}), N).empty());
+
+ // Fewer operand rows than output rows would be broadcast.
+ EXPECT_FALSE(woq_u2_check_epi_operand(f16({1, N}), f16({5, N}), N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(f16({1, N}), f16({40, N}), N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(f16({3, N}), f16({5, N}), N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(f16({1, 1, N}), f16({2, 4, N}), N).empty());
+ // Wrong width.
+ EXPECT_FALSE(woq_u2_check_epi_operand(f16({5, N / 2}), f16({5, N}), N).empty());
+}
+
+// Reproducer for Issue #1:
+// A dynamic u2 FC runs WoqU2FCImpl from m_dynamic_impls_cache on the first execution of shape M and
+// enqueues an async compilation task into m_static_impls_cache. Once that background task completes,
+// executing the same shape M again has SHAPE_CHANGED=false and IMPL_CHANGED=true. Because
+// WoqU2FCImpl's constructor never invokes update_dispatch_data_func (leaving kd.params.scalars empty)
+// and PrimitiveImplOCL::update_stages_flags clears need_dispatch_data_update when SHAPE_CHANGED=false,
+// the second execution fails in set_arguments with CL_INVALID_ARG_VALUE (-50) on scalar arg 6 (M).
+// Control: if a different shape (M_other) runs in between so SHAPE_CHANGED=true when returning to M,
+// update_stages_flags keeps need_dispatch_data_update=true and the cached static WoqU2FCImpl succeeds.
+void run_dynamic_repeated_shape_repro(int64_t M, int64_t M_interleaved = 0) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const int64_t K = 128, N = 256;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, static_cast<uint32_t>(M * 37 + 11));
+
+ topology topo(input_layout("input", layout{ov::PartialShape{-1, K}, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ topo.add(make_fc("fc_prim", "input", "", ZpKind::tensor_u8, data_types::f16, 2, w.zp_scalar));
+ topo.add(reorder("out", input_info("fc_prim"), format::bfyx, data_types::f16));
+
+ network::ptr net = get_network(engine, topo, woq_config(engine, {"fc_prim"}), get_test_stream_ptr(), false);
+
+ auto exec_and_check = [&](int64_t m) {
+ const auto a = random_activations(static_cast<size_t>(m * K), static_cast<uint64_t>(m * 1009 + K));
+ auto input_mem = engine.allocate_memory({ov::PartialShape{m, K}, data_types::f16, format::bfyx});
+ set_values(input_mem, a);
+ net->set_input_data("input", input_mem);
+ auto outputs = net->execute();
+ check_rows(outputs.at("out").get_memory(), m, a, all_rows(m), w, false);
+ };
+
+ // Iteration 1: runs dynamic impl and enqueues background static compilation for shape [M, K].
+ ASSERT_NO_FATAL_FAILURE(exec_and_check(M));
+
+ // Wait for the background compilation task to populate m_static_impls_cache for [M, K].
+ net->get_program()->get_compilation_context().wait_all();
+
+ if (M_interleaved > 0) {
+ // Intervening shape sets SHAPE_CHANGED=true on the subsequent return to M.
+ ASSERT_NO_FATAL_FAILURE(exec_and_check(M_interleaved));
+ }
+
+ // Re-execute shape [M, K] now that m_static_impls_cache holds the static WoqU2FCImpl.
+ exec_and_check(M);
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_regression, dynamic_repeated_shape_after_async_compile_gemv) {
+ run_dynamic_repeated_shape_repro(1);
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_regression, dynamic_repeated_shape_after_async_compile_tiled) {
+ run_dynamic_repeated_shape_repro(16);
+}
+
+TEST(smoke_fully_connected_cm_woq_u2_regression, dynamic_repeated_shape_control_interleaved_shape) {
+ run_dynamic_repeated_shape_repro(16, 32);
+}
+
+// Reproducer for Issue #2:
+// Dynamic u2 FC with a fused epilogue whose compile-time shapes are both dynamic ([-1, -1, K] and
+// [-1, -1, N]) passes validate_impl and selects CM. When runtime shapes require broadcasting the
+// epilogue operand (e.g. epi=[1, 1, N] with output=[2, 5, N]), support_shapes() returns false so
+// ImplementationsFactory falls back to ImplementationManagerLegacy<fully_connected> (bfyx_ref).
+// Because Step 4 in get_primitive_impl_for_params passes the concrete static runtime params to
+// find_impl(..., shape_types::dynamic_shape), bfyx_ref is compiled with is_shape_agnostic=false
+// (hardcoding S=5 in INPUT0_FEATURE_NUM and OUTPUT_SIZE_Y) and cached in m_dynamic_impls_cache.
+// A subsequent broadcast execution at S=8 reuses that S=5 kernel and corrupts the output.
+TEST(smoke_fully_connected_cm_woq_u2_regression, runtime_epilogue_broadcast_fallback_corrupts_next_shape) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const int64_t K = 128, N = 64;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, 77);
+
+ topology topo(input_layout("input", layout{ov::PartialShape{-1, -1, K}, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ topo.add(make_fc("fc_prim", "input", "", ZpKind::tensor_u8, data_types::f32, 3, w.zp_scalar));
+ topo.add(input_layout("epi", layout{ov::PartialShape{-1, -1, N}, data_types::f32, format::bfyx}));
+ topo.add(eltwise("post", input_info("fc_prim"), input_info("epi"), eltwise_mode::sum));
+ topo.add(reorder("out", input_info("post"), format::bfyx, data_types::f32));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+ network::ptr net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+
+ auto run_step = [&](int64_t B, int64_t S, bool broadcast_epi, float tol) {
+ const int64_t M = B * S;
+ const auto a = random_activations(static_cast<size_t>(M * K), static_cast<uint64_t>(M * 101 + 7));
+ auto in_mem = engine.allocate_memory({ov::PartialShape{B, S, K}, data_types::f16, format::bfyx});
+ set_values(in_mem, a);
+ net->set_input_data("input", in_mem);
+
+ const ov::PartialShape epi_shape = broadcast_epi ? ov::PartialShape{1, 1, N} : ov::PartialShape{B, S, N};
+ const size_t epi_count = static_cast<size_t>(ov::shape_size(epi_shape.to_shape()));
+ std::vector<float> epi_v(epi_count, 0.25f);
+ auto epi_mem = engine.allocate_memory({epi_shape, data_types::f32, format::bfyx});
+ set_values(epi_mem, epi_v);
+ net->set_input_data("epi", epi_mem);
+
+ auto outputs = net->execute();
+ const auto rows = all_rows(M);
+ const auto out = read_output(outputs.at("out").get_memory(), static_cast<size_t>(M * N), true);
+ auto ref = host_reference(a, rows, w);
+ for (float& v : ref)
+ v += 0.25f;
+
+ float max_err = 0.0f;
+ size_t bad = 0, first_bad = 0;
+ for (size_t i = 0; i < out.size(); ++i) {
+ const float err = std::fabs(out[i] - ref[i]);
+ max_err = std::max(max_err, err);
+ if (!(err <= tol)) {
+ if (bad++ == 0)
+ first_bad = i;
+ }
+ }
+ ASSERT_EQ(bad, size_t(0)) << "B=" << B << " S=" << S << " broadcast_epi=" << broadcast_epi << ": " << bad << " / " << out.size()
+ << " elements exceed tol=" << tol << " (max|d|=" << max_err << "); first at row " << first_bad / N << ", col "
+ << first_bad % N << ": got " << out[first_bad] << ", ref " << ref[first_bad];
+ };
+
+ // 1. Non-broadcast [2, 5, 128] + [2, 5, 64]: runs on CM u2 kernel.
+ ASSERT_NO_FATAL_FAILURE(run_step(2, 5, false, 1e-4f));
+ // 2. Broadcast [2, 5, 128] + [1, 1, 64]: support_shapes() rejects CM; falls back to bfyx_ref (1e-2f absorbs f32-vs-f16 dequant).
+ ASSERT_NO_FATAL_FAILURE(run_step(2, 5, true, 1e-2f));
+ // 3. Broadcast [2, 8, 128] + [1, 1, 64]: reuses cached S=5 bfyx_ref kernel on S=8 tensor and corrupts batch 1 (max|d| ~ 0.74).
+ run_step(2, 8, true, 1e-2f);
+}
+
+// A one-row epilogue operand needs broadcasting when M > 1: CM rejects it in support_shapes() and the fallback FC must
+// run (and be rebuilt for each new M) rather than a kernel cached for another shape.
+TEST(smoke_fully_connected_cm_woq_u2_regression, runtime_epilogue_broadcast_2d_falls_back_per_shape) {
+ const NkEnabledScope nk_on;
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const int64_t K = 128, N = 256;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, 55);
+
+ topology topo(input_layout("input", layout{ov::PartialShape{-1, K}, data_types::f16, format::bfyx}));
+ add_weights(topo, "", w);
+ topo.add(make_fc("fc_prim", "input", "", ZpKind::tensor_u8, data_types::f32, 2, w.zp_scalar));
+ topo.add(input_layout("epi", layout{ov::PartialShape{-1, N}, data_types::f32, format::bfyx}));
+ topo.add(eltwise("post", input_info("fc_prim"), input_info("epi"), eltwise_mode::sum));
+ topo.add(reorder("out", input_info("post"), format::bfyx, data_types::f32));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+ network::ptr net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+
+ for (const int64_t M : {5, 7}) {
+ SCOPED_TRACE("M = " + std::to_string(M));
+ const auto a = random_activations(static_cast<size_t>(M * K), static_cast<uint64_t>(M * 333));
+ auto in_mem = engine.allocate_memory({ov::PartialShape{M, K}, data_types::f16, format::bfyx});
+ set_values(in_mem, a);
+ net->set_input_data("input", in_mem);
+
+ std::vector<float> epi_v(static_cast<size_t>(N), 0.5f);
+ auto epi_mem = engine.allocate_memory({ov::PartialShape{1, N}, data_types::f32, format::bfyx});
+ set_values(epi_mem, epi_v);
+ net->set_input_data("epi", epi_mem);
+
+ auto outputs = net->execute();
+ const auto out = read_output(outputs.at("out").get_memory(), static_cast<size_t>(M * N), true);
+ auto ref = host_reference(a, all_rows(M), w);
+ for (float& v : ref)
+ v += 0.5f;
+ size_t bad = 0;
+ for (size_t i = 0; i < out.size(); ++i) {
+ if (!(std::fabs(out[i] - ref[i]) <= 1e-2f))
+ bad++;
+ }
+ ASSERT_EQ(bad, size_t(0)) << bad << " / " << out.size() << " elements exceed tol=1e-2";
+ }
+}
+
+// ---- Native group-major (GNK) weights [G, N, 64] ----
+
+using ov::intel_gpu::cm::woq_u2_accepts_gnk;
+using ov::intel_gpu::cm::woq_u2_gnk_enabled_for_tests;
+using ov::intel_gpu::op::FcWeightsLayout;
+
+TEST(smoke_fully_connected_cm_woq_u2_gnk_check, accepts_only_cm_eligible_gnk) {
+ cldnn::device_info info{};
+ info.arch = gpu_arch::xe2;
+ info.max_local_mem_size = 128 * 1024;
+ const ov::PartialShape w{80, 5120, 64}, gn{80, 5120}, gn1{80, 5120, 1};
+ const auto u2 = ov::element::u2, u8 = ov::element::u8, f16 = ov::element::f16;
+
+ EXPECT_TRUE(woq_u2_accepts_gnk(info, true, u2, w, f16, gn1, true, u2, gn1));
+ EXPECT_TRUE(woq_u2_accepts_gnk(info, true, u2, w, f16, gn, true, u8, gn));
+
+ auto other_arch = info;
+ other_arch.arch = gpu_arch::xe_hpg;
+ EXPECT_FALSE(woq_u2_accepts_gnk(other_arch, true, u2, w, f16, gn, true, u8, gn));
+ auto small_slm = info;
+ small_slm.max_local_mem_size = 64 * 1024;
+ EXPECT_FALSE(woq_u2_accepts_gnk(small_slm, true, u2, w, f16, gn, true, u8, gn));
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, false, u2, w, f16, gn, true, u8, gn));
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, {160, 5120, 32}, f16, {160, 5120}, true, u8, {160, 5120})); // gs != 64
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, {80, 5104, 64}, f16, {80, 5104}, true, u8, {80, 5104})); // N % 32 != 0
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, ov::element::u4, w, f16, gn, true, u8, gn));
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, w, ov::element::f32, gn, true, u8, gn));
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, w, f16, gn, false, ov::element::dynamic, {})); // no zp
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, w, f16, gn, true, f16, gn));
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, w, f16, gn, true, u8, {1})); // scalar zp
+ EXPECT_FALSE(woq_u2_accepts_gnk(info, true, u2, w, f16, {5120, 80}, true, u8, gn));
+}
+
+// MatMulNBits with reordered B, as the ONNX frontend builds it:
+// u2 [G, N, gs] -> Convert -> Subtract(zp [G, N, 1]) -> Multiply(scale [G, N, 1]) -> Transpose{1, 0, 2} -> Reshape [N, K] -> MatMul(transpose_b).
+struct GnkChain {
+ std::string name;
+ int64_t G, N, gs;
+ bool zp = true;
+ bool needs_no_cm = false; // CM-eligible shape: checked only where the device cannot run CM
+};
+
+std::shared_ptr<ov::Model> make_gnk_chain_model(const GnkChain& c) {
+ const int64_t K = c.G * c.gs;
+ auto random_bytes = [](size_t elements, uint64_t seed) {
+ std::vector<uint8_t> v((elements + 3) / 4);
+ SplitMix64 rng{seed};
+ for (auto& b : v)
+ b = static_cast<uint8_t>(rng.next());
+ return v;
+ };
+ const ov::Shape w_shape{static_cast<size_t>(c.G), static_cast<size_t>(c.N), static_cast<size_t>(c.gs)};
+ const ov::Shape gn_shape{static_cast<size_t>(c.G), static_cast<size_t>(c.N), 1};
+
+ auto a = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, K});
+ const auto w_bytes = random_bytes(ov::shape_size(w_shape), 1);
+ auto w = std::make_shared<ov::op::v0::Constant>(ov::element::u2, w_shape, w_bytes.data());
+ std::shared_ptr<ov::Node> deq = std::make_shared<ov::op::v0::Convert>(w, ov::element::f16);
+ if (c.zp) {
+ const auto zp_bytes = random_bytes(ov::shape_size(gn_shape), 2);
+ auto zp = std::make_shared<ov::op::v0::Constant>(ov::element::u2, gn_shape, zp_bytes.data());
+ deq = std::make_shared<ov::op::v1::Subtract>(deq, std::make_shared<ov::op::v0::Convert>(zp, ov::element::f16));
+ }
+ std::vector<ov::float16> scales(ov::shape_size(gn_shape));
+ SplitMix64 rng{3};
+ for (auto& s : scales)
+ s = ov::float16(0.005f + static_cast<float>(rng.next() % 1000) * 2e-5f);
+ auto scale = std::make_shared<ov::op::v0::Constant>(ov::element::f16, gn_shape, scales);
+ auto mul = std::make_shared<ov::op::v1::Multiply>(deq, scale);
+ auto order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{1, 0, 2});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(mul, order);
+ auto target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{c.N, K});
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(transpose, target, false);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(a, reshape, false, true);
+ return std::make_shared<ov::Model>(ov::OutputVector{matmul}, ov::ParameterVector{a});
+}
+
+std::shared_ptr<ov::Model> run_gpu_pipeline(const std::shared_ptr<ov::Model>& model) {
+ auto& engine = get_test_engine();
+ auto context = std::make_shared<ov::intel_gpu::RemoteContextImpl>("GPU", std::vector<cldnn::device::ptr>{engine.get_device()});
+ auto config = get_test_default_config(engine);
+ config.set_user_property(ov::hint::inference_precision(ov::element::f16));
+ config.finalize(context.get(), model.get());
+ ov::intel_gpu::TransformationsPipeline pipeline(config, context);
+ pipeline.apply(model);
+ return model;
+}
+
+// (a) A CM-eligible chain becomes one GNK FullyConnectedCompressed on the raw u2 constant.
+TEST(smoke_fully_connected_cm_woq_u2_gnk_pipeline, eligible_chain_becomes_gnk_fc) {
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const auto model = run_gpu_pipeline(make_gnk_chain_model({"eligible", 80, 5120, 64}));
+ std::vector<std::shared_ptr<ov::intel_gpu::op::FullyConnectedCompressed>> fcs;
+ for (const auto& op : model->get_ops())
+ if (auto fc = ov::as_type_ptr<ov::intel_gpu::op::FullyConnectedCompressed>(op))
+ fcs.push_back(fc);
+ ASSERT_EQ(fcs.size(), size_t(1));
+ const auto& fc = fcs[0];
+ EXPECT_EQ(fc->get_weights_layout(), FcWeightsLayout::GNK);
+ EXPECT_TRUE(fc->get_transpose_b());
+ EXPECT_FALSE(fc->get_transpose_b_scale());
+ EXPECT_FALSE(fc->get_transpose_b_zp());
+ const auto weights = ov::as_type_ptr<ov::op::v0::Constant>(fc->get_input_node_shared_ptr(1));
+ ASSERT_NE(weights, nullptr) << "GNK weights must be the raw constant, without Transpose / Reshape";
+ EXPECT_EQ(weights->get_element_type(), ov::element::u2);
+ EXPECT_EQ(weights->get_shape(), (ov::Shape{80, 5120, 64}));
+ EXPECT_EQ(fc->get_input_element_type(3), ov::element::f16);
+ EXPECT_EQ(fc->get_input_shape(3), (ov::Shape{80, 5120}));
+ EXPECT_EQ(fc->get_input_element_type(4), ov::element::u8);
+ EXPECT_EQ(fc->get_input_shape(4), (ov::Shape{80, 5120}));
+ EXPECT_EQ(fc->get_output_partial_shape(0), (ov::PartialShape{-1, 5120}));
+}
+
+// Disables the GNK path (woq_u2_accepts_gnk always false) for the lifetime of the scope.
+struct GnkDisabledScope {
+ bool saved = woq_u2_gnk_enabled_for_tests();
+ GnkDisabledScope() {
+ woq_u2_gnk_enabled_for_tests() = false;
+ }
+ ~GnkDisabledScope() {
+ woq_u2_gnk_enabled_for_tests() = saved;
+ }
+};
+
+class fully_connected_cm_woq_u2_gnk_fold : public ::testing::TestWithParam<GnkChain> {};
+
+// (b) When the check fails, the pipeline output is exactly the one without the GNK path (master's NK conversion) and
+// contains no GNK FullyConnectedCompressed.
+TEST_P(fully_connected_cm_woq_u2_gnk_fold, matches_pipeline_without_gnk) {
+ const auto c = GetParam();
+ if (c.needs_no_cm && cm_woq_u2_supported(get_test_engine()))
+ GTEST_SKIP() << "the device runs CM; covered by eligible_chain_becomes_gnk_fc";
+
+ const auto with_gnk = run_gpu_pipeline(make_gnk_chain_model(c));
+ std::shared_ptr<ov::Model> without_gnk;
+ {
+ GnkDisabledScope disabled;
+ without_gnk = run_gpu_pipeline(make_gnk_chain_model(c));
+ }
+ const auto res =
+ FunctionsComparator::with_default().enable(FunctionsComparator::ATTRIBUTES).enable(FunctionsComparator::CONST_VALUES).compare(with_gnk, without_gnk);
+ ASSERT_TRUE(res.valid) << res.message;
+ for (const auto& op : with_gnk->get_ops()) {
+ if (const auto fc = ov::as_type_ptr<ov::intel_gpu::op::FullyConnectedCompressed>(op)) {
+ EXPECT_NE(fc->get_weights_layout(), FcWeightsLayout::GNK) << op->get_friendly_name();
+ }
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ fully_connected_cm_woq_u2_gnk_fold,
+ ::testing::Values(GnkChain{"gs32", 160, 5120, 32},
+ GnkChain{"n_not_multiple_of_32", 80, 5104, 64},
+ GnkChain{"no_zp", 80, 5120, 64, false},
+ GnkChain{"no_cm_device", 80, 5120, 64, true, true}),
+ [](const testing::TestParamInfo<GnkChain>& info) {
+ return info.param.name;
+ });
+
+// Group-major device buffers of the host N-major weights: Wq [G, N, 64], scales / zero points [G, N].
+struct GnkBuffers {
+ memory::ptr weights, scale, zp;
+};
+
+GnkBuffers make_gnk_buffers(engine& engine, const WoqU2Weights& w) {
+ const int64_t K = w.K, N = w.N, G = K / 64;
+ std::vector<uint8_t> packed(w.packed.size()), zp(w.zp_u8.size());
+ std::vector<ov::float16> scales(w.scales.size());
+ for (int64_t n = 0; n < N; n++)
+ for (int64_t g = 0; g < G; g++) {
+ std::copy_n(w.packed.begin() + n * (K / 4) + g * 16, 16, packed.begin() + (g * N + n) * 16);
+ scales[static_cast<size_t>(g * N + n)] = w.scales[static_cast<size_t>(n * G + g)];
+ zp[static_cast<size_t>(g * N + n)] = w.zp_u8[static_cast<size_t>(n * G + g)];
+ }
+ GnkBuffers b;
+ b.weights = engine.allocate_memory({ov::PartialShape{G, N, 64}, data_types::u2, format::bfyx});
+ b.scale = engine.allocate_memory({ov::PartialShape{G, N}, data_types::f16, format::bfyx});
+ b.zp = engine.allocate_memory({ov::PartialShape{G, N}, data_types::u8, format::bfyx});
+ set_values(b.weights, packed);
+ set_values(b.scale, scales);
+ set_values(b.zp, zp);
+ return b;
+}
+
+// Runs the u2 FC "fc_prim" that add_fc adds, without forcing an implementation; checks that CM ran and matches the
+// host reference of w. Returns the output values.
+std::vector<float> run_u2_fc(engine& engine,
+ const WoqU2Weights& w,
+ int64_t M,
+ const std::vector<ov::float16>& a,
+ data_types out_dt,
+ const std::function<void(topology&)>& add_fc) {
+ const bool out_f32 = out_dt == data_types::f32;
+ topology topo(input_layout("input", layout{ov::PartialShape{M, w.K}, data_types::f16, format::bfyx}));
+ add_fc(topo);
+ topo.add(reorder("out", input_info("fc_prim"), format::bfyx, out_dt));
+ auto net = get_network(engine, topo, woq_config(engine, {}), get_test_stream_ptr(), false);
+ auto input_mem = engine.allocate_memory({ov::PartialShape{M, w.K}, data_types::f16, format::bfyx});
+ set_values(input_mem, a);
+ net->set_input_data("input", input_mem);
+ auto outputs = net->execute();
+ bool cm_ran = false;
+ for (const auto& id : net->get_executed_primitive_ids()) {
+ const auto impl = net->get_primitive(id)->get_impl();
+ cm_ran |= impl && impl->get_kernel_name().find("woq_u2") != std::string::npos;
+ }
+ EXPECT_TRUE(cm_ran) << "CM u2 FC implementation was not selected";
+ const auto out_mem = outputs.at("out").get_memory();
+ check_rows(out_mem, M, a, all_rows(M), w, out_f32);
+ return read_output(out_mem, static_cast<size_t>(M * w.N), out_f32);
+}
+
+class fully_connected_cm_woq_u2_gnk : public ::testing::TestWithParam<std::tuple<int64_t, data_types>> {};
+
+// (c) A GNK FC selects CM (not forced). Its buffers are group-major while the test layout override stays n-major,
+// so it only matches the reference if the kernel was built with WLAYOUT=0.
+// (d) The same logical weights as an NK FC give the same numbers.
+TEST_P(fully_connected_cm_woq_u2_gnk, selects_cm_and_matches_nk) {
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+ ASSERT_EQ(woq_u2_weight_layout_for_tests(), WoqU2WeightLayout::n_major);
+
+ const int64_t M = std::get<0>(GetParam());
+ const data_types out_dt = std::get<1>(GetParam());
+ const int64_t K = 320, N = 512;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, static_cast<uint32_t>(M * 131 + K));
+ const auto gnk = make_gnk_buffers(engine, w);
+ const auto a = random_activations(static_cast<size_t>(M * K), static_cast<uint64_t>(M * 1000003 + K));
+
+ SCOPED_TRACE("GNK");
+ const auto gnk_out = run_u2_fc(engine, w, M, a, out_dt, [&](topology& topo) {
+ topo.add(data("weights", gnk.weights));
+ topo.add(data("scale", gnk.scale));
+ topo.add(data("zp", gnk.zp));
+ topo.add(fully_connected("fc_prim", input_info("input"), "weights", "", "scale", "zp", out_dt, 2, 3, true, false, false, FcWeightsLayout::GNK));
+ });
+ SCOPED_TRACE("NK");
+ const NkEnabledScope nk_on;
+ const auto nk_out = run_u2_fc(engine, w, M, a, out_dt, [&](topology& topo) {
+ add_weights(topo, "", w);
+ topo.add(make_fc("fc_prim", "input", "", ZpKind::tensor_u8, out_dt, 2, w.zp_scalar));
+ });
+ EXPECT_EQ(gnk_out, nk_out);
+}
+
+// (e) GNK with scale / zp as runtime inputs (Parameters in the model, not constants) selects CM and matches the reference.
+TEST_P(fully_connected_cm_woq_u2_gnk, runtime_scale_zp_selects_cm_and_matches_reference) {
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+ ASSERT_EQ(woq_u2_weight_layout_for_tests(), WoqU2WeightLayout::n_major);
+
+ const int64_t M = std::get<0>(GetParam());
+ const data_types out_dt = std::get<1>(GetParam());
+ const bool out_f32 = out_dt == data_types::f32;
+ const int64_t K = 320, N = 512;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, static_cast<uint32_t>(M * 131 + K));
+ const auto gnk = make_gnk_buffers(engine, w);
+ const auto a = random_activations(static_cast<size_t>(M * K), static_cast<uint64_t>(M * 1000003 + K));
+
+ topology topo(input_layout("input", layout{ov::PartialShape{M, K}, data_types::f16, format::bfyx}),
+ input_layout("scale", gnk.scale->get_layout()),
+ input_layout("zp", gnk.zp->get_layout()));
+ topo.add(data("weights", gnk.weights));
+ topo.add(fully_connected("fc_prim", input_info("input"), "weights", "", "scale", "zp", out_dt, 2, 3, true, false, false, FcWeightsLayout::GNK));
+ topo.add(reorder("out", input_info("fc_prim"), format::bfyx, out_dt));
+ auto net = get_network(engine, topo, woq_config(engine, {}), get_test_stream_ptr(), false);
+ auto input_mem = engine.allocate_memory({ov::PartialShape{M, K}, data_types::f16, format::bfyx});
+ set_values(input_mem, a);
+ net->set_input_data("input", input_mem);
+ net->set_input_data("scale", gnk.scale);
+ net->set_input_data("zp", gnk.zp);
+ auto outputs = net->execute();
+
+ bool cm_ran = false;
+ for (const auto& id : net->get_executed_primitive_ids()) {
+ const auto impl = net->get_primitive(id)->get_impl();
+ cm_ran |= impl && impl->get_kernel_name().find("woq_u2") != std::string::npos;
+ }
+ EXPECT_TRUE(cm_ran) << "CM u2 FC implementation was not selected";
+ check_rows(outputs.at("out").get_memory(), M, a, all_rows(M), w, out_f32);
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke,
+ fully_connected_cm_woq_u2_gnk,
+ ::testing::Combine(::testing::Values(int64_t{5}, int64_t{40}), ::testing::Values(data_types::f16, data_types::f32)),
+ [](const testing::TestParamInfo<std::tuple<int64_t, data_types>>& info) {
+ return "M" + std::to_string(std::get<0>(info.param)) + (std::get<1>(info.param) == data_types::f32 ? "_f32out" : "_f16out");
+ });
+
+// Clears the NK opt-in for the lifetime of the scope, i.e. the plugin's own behavior.
+struct NkDisabledScope {
+ bool saved = woq_u2_nk_enabled_for_tests();
+ NkDisabledScope() {
+ woq_u2_nk_enabled_for_tests() = false;
+ }
+ ~NkDisabledScope() {
+ woq_u2_nk_enabled_for_tests() = saved;
+ }
+};
+
+bool gnk_fc_cm_accepts(engine& engine, int64_t N, int64_t K) {
+ const int64_t G = K / 64;
+ topology topo(input_layout("input", layout{ov::PartialShape{16, K}, data_types::f16, format::bfyx}));
+ topo.add(data("weights", engine.allocate_memory({ov::PartialShape{G, N, 64}, data_types::u2, format::bfyx})));
+ topo.add(data("scale", engine.allocate_memory({ov::PartialShape{G, N}, data_types::f16, format::bfyx})));
+ topo.add(data("zp", engine.allocate_memory({ov::PartialShape{G, N}, data_types::u8, format::bfyx})));
+ topo.add(fully_connected("fc", input_info("input"), "weights", "", "scale", "zp", data_types::f16, 2, 3, true, false, false, FcWeightsLayout::GNK));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ auto prog = program::build_program(engine, topo, config, false, true);
+ auto& fc = prog->get_node("fc").as<fully_connected>();
+ fc.get_output_layouts(false);
+ return ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::validate_base(fc, true);
+}
+
+// CM is picked for GNK weights only: the same FC with NK weights is rejected unless a test opts in to NK, and then
+// takes the same scale / zp reorder as any other non-CM u2 FC.
+TEST(smoke_fully_connected_cm_woq_u2_gnk_only, nk_is_rejected_gnk_is_accepted) {
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ {
+ const NkEnabledScope nk_on;
+ ASSERT_TRUE(run_u2_reorder_passes(engine, 64, 128, true, true).cm_accepts) << "NK must be accepted while the test opt-in is on";
+ }
+
+ const NkDisabledScope nk_off;
+ const auto nk = run_u2_reorder_passes(engine, 64, 128, true, true);
+ EXPECT_FALSE(nk.cm_accepts);
+ EXPECT_TRUE(nk.scale_reordered);
+ EXPECT_TRUE(nk.zp_reordered);
+ EXPECT_TRUE(gnk_fc_cm_accepts(engine, 64, 128));
+}
+
+// Reproducer for Finding 1a:
+// ConvertFullyConnectedToFullyConnectedCompressed must only emit FcWeightsLayout::GNK when the FC itself satisfies
+// the CM u2 kernel's invariants (f16 activations, static K on activations, f16/f32 output, and either no bias or
+// static M == 1 with a 1-row f16/f32 bias). Otherwise it must fall back to the NK path so OCL/oneDNN can execute it.
+TEST(smoke_fully_connected_cm_woq_u2_regression, gnk_conversion_rejects_unsupported_fc_configs) {
+ cldnn::device_info xe2_info{};
+ xe2_info.arch = gpu_arch::xe2;
+ xe2_info.max_local_mem_size = 128 * 1024;
+
+ auto run_convert = [&](ov::element::Type act_et, const ov::PartialShape& act_ps, ov::element::Type out_et, bool with_bias) -> FcWeightsLayout {
+ const size_t G = 2, N = 32, gs = 64;
+ const size_t K = G * gs;
+ auto a = std::make_shared<ov::op::v0::Parameter>(act_et, act_ps);
+ auto w = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{G, N, gs}, {1});
+ auto w_conv = std::make_shared<ov::op::v0::Convert>(w, ov::element::f16);
+ auto zp = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{G, N, 1}, {1});
+ auto zp_conv = std::make_shared<ov::op::v0::Convert>(zp, ov::element::f16);
+ auto sub = std::make_shared<ov::op::v1::Subtract>(w_conv, zp_conv);
+ auto scale = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{G, N, 1}, {0.5f});
+ auto mul = std::make_shared<ov::op::v1::Multiply>(sub, scale);
+ auto order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {1, 0, 2});
+ auto tr = std::make_shared<ov::op::v1::Transpose>(mul, order);
+ auto target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {static_cast<int64_t>(N), static_cast<int64_t>(K)});
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(tr, target, false);
+ std::shared_ptr<ov::Node> bias = with_bias ? std::static_pointer_cast<ov::Node>(ov::op::v0::Constant::create(act_et, ov::Shape{1, N}, {0.1f}))
+ : std::make_shared<ov::intel_gpu::op::Placeholder>();
+ auto fc = std::make_shared<ov::intel_gpu::op::FullyConnected>(a, reshape, bias, out_et, true);
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{fc}, ov::ParameterVector{a});
+
+ ov::pass::Manager pm;
+ pm.register_pass<ov::intel_gpu::ConvertFullyConnectedToFullyConnectedCompressed>(xe2_info, true);
+ pm.run_passes(model);
+
+ for (const auto& op : model->get_ops()) {
+ if (auto fcc = ov::as_type_ptr<ov::intel_gpu::op::FullyConnectedCompressed>(op)) {
+ return fcc->get_weights_layout();
+ }
+ }
+ ADD_FAILURE() << "Expected a FullyConnectedCompressed node";
+ return FcWeightsLayout::NK;
+ };
+
+ // Eligible: f16 activations with static K, no bias (or M == 1 with bias).
+ EXPECT_EQ(run_convert(ov::element::f16, {-1, 128}, ov::element::f16, false), FcWeightsLayout::GNK);
+ EXPECT_EQ(run_convert(ov::element::f16, {1, 128}, ov::element::f16, true), FcWeightsLayout::GNK);
+ EXPECT_EQ(run_convert(ov::element::f16, {1, 1, 128}, ov::element::f32, true), FcWeightsLayout::GNK);
+
+ // Ineligible for CM u2 FC -> must fall back to NK instead of emitting an un-executable GNK FC.
+ EXPECT_EQ(run_convert(ov::element::f32, {-1, 128}, ov::element::f32, false), FcWeightsLayout::NK);
+ EXPECT_EQ(run_convert(ov::element::f16, {-1, -1}, ov::element::f16, false), FcWeightsLayout::NK);
+ EXPECT_EQ(run_convert(ov::element::f16, {16, 128}, ov::element::f16, true), FcWeightsLayout::NK);
+ EXPECT_EQ(run_convert(ov::element::f16, {-1, 128}, ov::element::f16, true), FcWeightsLayout::NK);
+}
+
+// Reproducer for Finding 1b:
+// prepare_primitive_fusing must not fuse a [1, N] bias (when M != 1) or an unsupported activation / eltwise / quantize
+// post-op into a GNK FC: since OCL and oneDNN reject GNK, any fusion rejected by woq_u2_epilogue or
+// woq_u2_check_epi_operand leaves the GNK FC with zero supported implementations.
+TEST(smoke_fully_connected_cm_woq_u2_regression, gnk_prepare_primitive_fusing_guards_unsupported_epilogues) {
+ auto& engine = get_test_engine();
+ const int64_t G = 2, N = 64, gs = 64, K = G * gs;
+
+ auto run_fusing = [&](const ov::PartialShape& in_ps, const std::function<void(topology&)>& add_post) {
+ topology topo(input_layout("input", layout{in_ps, data_types::f16, format::bfyx}));
+ topo.add(data("weights", engine.allocate_memory({ov::PartialShape{G, N, gs}, data_types::u2, format::bfyx})));
+ topo.add(data("scale", engine.allocate_memory({ov::PartialShape{G, N}, data_types::f16, format::bfyx})));
+ topo.add(data("zp", engine.allocate_memory({ov::PartialShape{G, N}, data_types::u8, format::bfyx})));
+ topo.add(fully_connected("fc",
+ input_info("input"),
+ "weights",
+ "",
+ "scale",
+ "zp",
+ data_types::f16,
+ in_ps.size(),
+ 3,
+ true,
+ false,
+ false,
+ FcWeightsLayout::GNK));
+ add_post(topo);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ auto prog = program::build_program(engine, topo, config, false, true);
+ program_wrapper::apply_opt_pass<prepare_quantization>(*prog);
+ program_wrapper::apply_opt_pass<prepare_primitive_fusing>(*prog);
+ for (auto* n : prog->get_processing_order()) {
+ if (n->is_type<fully_connected>()) {
+ n->get_output_layouts(false);
+ const auto& fc_node = n->as<fully_connected>();
+ const auto epi = ov::intel_gpu::cm::woq_u2_epilogue(fc_node.get_fused_primitives(), fc_node.bias_term());
+ EXPECT_TRUE(epi.ok()) << "Unsupported epilogue fused into GNK FC: " << epi.error;
+ if (epi.ok() && epi.dep >= 0) {
+ const auto why =
+ ov::intel_gpu::cm::woq_u2_check_epi_operand(fc_node.get_input_layout(static_cast<size_t>(epi.dep)), fc_node.get_output_layout(0), N);
+ EXPECT_TRUE(why.empty()) << "Invalid epilogue operand fused into GNK FC: " << why;
+ }
+ return std::make_pair(fc_node.bias_term(), fc_node.get_fused_primitives().size());
+ }
+ }
+ ADD_FAILURE() << "fully_connected node not found";
+ return std::make_pair(false, size_t(0));
+ };
+
+ // 1. Constant [1, N] bias: fused only when static M == 1; kept unfused for static M > 1 and dynamic M.
+ {
+ SCOPED_TRACE("M=1 bias");
+ const auto [has_bias, fused_cnt] = run_fusing({1, K}, [&](topology& t) {
+ t.add(data("bias", engine.allocate_memory({ov::PartialShape{1, N}, data_types::f16, format::bfyx})));
+ t.add(eltwise("add_bias", {input_info("fc"), input_info("bias")}, eltwise_mode::sum));
+ t.add(reorder("out", input_info("add_bias"), format::bfyx, data_types::f32));
+ });
+ EXPECT_TRUE(has_bias);
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("M=16 bias");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(data("bias", engine.allocate_memory({ov::PartialShape{1, N}, data_types::f16, format::bfyx})));
+ t.add(eltwise("add_bias", {input_info("fc"), input_info("bias")}, eltwise_mode::sum));
+ t.add(reorder("out", input_info("add_bias"), format::bfyx, data_types::f32));
+ });
+ EXPECT_FALSE(has_bias);
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("dynamic M bias");
+ const auto [has_bias, fused_cnt] = run_fusing({-1, K}, [&](topology& t) {
+ t.add(data("bias", engine.allocate_memory({ov::PartialShape{1, N}, data_types::f16, format::bfyx})));
+ t.add(eltwise("add_bias", {input_info("fc"), input_info("bias")}, eltwise_mode::sum));
+ t.add(reorder("out", input_info("add_bias"), format::bfyx, data_types::f32));
+ });
+ EXPECT_FALSE(has_bias);
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+
+ // 2. Unsupported activations: relu, standalone swish, and swish followed by a 1-row prod when M > 1.
+ {
+ SCOPED_TRACE("relu");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(activation("relu", input_info("fc"), activation_func::relu));
+ t.add(reorder("out", input_info("relu"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("standalone swish");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(activation("swish", input_info("fc"), activation_func::swish, {1.0f, 0.0f}));
+ t.add(reorder("out", input_info("swish"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("swish + 1-row prod at M=16");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(input_layout("gate", layout{ov::PartialShape{1, N}, data_types::f16, format::bfyx}));
+ t.add(activation("swish", input_info("fc"), activation_func::swish, {1.0f, 0.0f}));
+ t.add(eltwise("prod", {input_info("swish"), input_info("gate")}, eltwise_mode::prod));
+ t.add(reorder("out", input_info("prod"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("valid SwiGLU at M=16");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(input_layout("gate", layout{ov::PartialShape{16, N}, data_types::f16, format::bfyx}));
+ t.add(activation("swish", input_info("fc"), activation_func::swish, {1.0f, 0.0f}));
+ t.add(eltwise("prod", {input_info("swish"), input_info("gate")}, eltwise_mode::prod));
+ t.add(reorder("out", input_info("prod"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(2));
+ }
+
+ // 3. Unsupported eltwise modes / chained eltwises: standalone prod, sub, and sum + sum.
+ {
+ SCOPED_TRACE("standalone prod");
+ const auto [has_bias, fused_cnt] = run_fusing({-1, K}, [&](topology& t) {
+ t.add(input_layout("mul_in", layout{ov::PartialShape{-1, N}, data_types::f16, format::bfyx}));
+ t.add(eltwise("mul", {input_info("fc"), input_info("mul_in")}, eltwise_mode::prod));
+ t.add(reorder("out", input_info("mul"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(0));
+ }
+ {
+ SCOPED_TRACE("sum + sum");
+ const auto [has_bias, fused_cnt] = run_fusing({16, K}, [&](topology& t) {
+ t.add(input_layout("s1", layout{ov::PartialShape{16, N}, data_types::f16, format::bfyx}));
+ t.add(input_layout("s2", layout{ov::PartialShape{16, N}, data_types::f16, format::bfyx}));
+ t.add(eltwise("sum1", {input_info("fc"), input_info("s1")}, eltwise_mode::sum));
+ t.add(eltwise("sum2", {input_info("sum1"), input_info("s2")}, eltwise_mode::sum));
+ t.add(reorder("out", input_info("sum2"), format::bfyx, data_types::f32));
+ });
+ EXPECT_EQ(fused_cnt, size_t(1));
+ }
+}
+
+// Reproducer for Finding 2:
+// When a u2 FC does not select CM (e.g. NK weights in production), select_preferred_formats inserts the deferred
+// fbyx reorder on scale/zp after select_formats_for(fc_node). It must update fc_node's preferred_input_fmt for
+// scale/zp to fbyx so reorder_inputs does not insert a reverse fbyx -> bfyx reorder when scale/zp is in data_flow.
+TEST(smoke_fully_connected_cm_woq_u2_regression, deferred_reorder_data_flow_scale_zp_keeps_fbyx_and_matches_ref) {
+ auto& engine = get_test_engine();
+ if (!engine.get_device_info().supports_immad)
+ GTEST_SKIP();
+
+ const NkDisabledScope nk_off;
+ const int64_t M = 4, K = 128, N = 64, G = K / 64;
+ auto input_mem = engine.allocate_memory({ov::PartialShape{M, K}, data_types::f16, format::bfyx});
+ auto weights_mem = engine.allocate_memory({ov::PartialShape{N, K}, data_types::u2, format::bfyx});
+ auto scale_mem = engine.allocate_memory({ov::PartialShape{N, G}, data_types::f16, format::bfyx});
+ auto zp_mem = engine.allocate_memory({ov::PartialShape{N, G}, data_types::u8, format::bfyx});
+
+ set_values(input_mem, std::vector<ov::float16>(M * K, ov::float16(1.0f)));
+ set_values(weights_mem, std::vector<uint8_t>(N * K / 4, 0x55));
+ std::vector<ov::float16> scale_vals(N * G);
+ for (int64_t n = 0; n < N; ++n) {
+ scale_vals[n * G + 0] = ov::float16(1.0f);
+ scale_vals[n * G + 1] = ov::float16(10.0f);
+ }
+ set_values(scale_mem, scale_vals);
+ set_values(zp_mem, std::vector<uint8_t>(N * G, 0));
+
+ topology topo(input_layout("input", input_mem->get_layout()),
+ data("weights", weights_mem),
+ input_layout("scale", scale_mem->get_layout()),
+ input_layout("zp", zp_mem->get_layout()),
+ fully_connected("fc", input_info("input"), "weights", "", "scale", "zp", data_types::f32, 2, 2, true, true, true));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+ network net(engine, topo, config);
+ const auto& fc_node = net.get_program()->get_node("fc");
+ EXPECT_EQ(fc_node.get_preferred_input_fmt(2), format::fbyx);
+ EXPECT_EQ(fc_node.get_preferred_input_fmt(3), format::fbyx);
+ EXPECT_EQ(fc_node.get_input_layout(2).format, format::fbyx);
+ EXPECT_EQ(fc_node.get_input_layout(3).format, format::fbyx);
+
+ net.set_input_data("input", input_mem);
+ net.set_input_data("scale", scale_mem);
+ net.set_input_data("zp", zp_mem);
+ auto outputs = net.execute();
+ auto out_mem = outputs.at("fc").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> out_ptr(out_mem, get_test_stream());
+ for (int64_t i = 0; i < M * N; ++i) {
+ ASSERT_NEAR(out_ptr[i], 704.0f, 1e-1f) << "index " << i << " (row " << i / N << ", col " << i % N << ")";
+ }
+}
+
+// Reproducer for Findings 3 & 5:
+// woq_u2_check_epi_operand must reject transposed planar formats (fbyx, byfx, yxfb), and
+// validate_node must reject FCs with a fused Hadamard input transform (hadamard_block != 0).
+TEST(smoke_fully_connected_cm_woq_u2_regression, epi_format_and_hadamard_guards) {
+ EXPECT_FALSE(woq_u2_nk_enabled_for_tests()) << "NK test opt-in must not be enabled globally at static init";
+ constexpr int64_t N = 64, K = 128, G = K / 64;
+ using ov::intel_gpu::cm::woq_u2_check_epi_operand;
+ const layout out_bfyx{ov::PartialShape{4, N}, data_types::f16, format::bfyx};
+ EXPECT_TRUE(woq_u2_check_epi_operand(out_bfyx, out_bfyx, N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(layout{ov::PartialShape{4, N}, data_types::f16, format::fbyx}, out_bfyx, N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(layout{ov::PartialShape{4, N}, data_types::f16, format::byfx}, out_bfyx, N).empty());
+ EXPECT_FALSE(woq_u2_check_epi_operand(layout{ov::PartialShape{4, N}, data_types::f16, format::yxfb}, out_bfyx, N).empty());
+
+ auto& engine = get_test_engine();
+ topology topo(input_layout("input", layout{ov::PartialShape{16, K}, data_types::f16, format::bfyx}));
+ topo.add(data("weights", engine.allocate_memory({ov::PartialShape{G, N, 64}, data_types::u2, format::bfyx})));
+ topo.add(data("scale", engine.allocate_memory({ov::PartialShape{G, N}, data_types::f16, format::bfyx})));
+ topo.add(data("zp", engine.allocate_memory({ov::PartialShape{G, N}, data_types::u8, format::bfyx})));
+ auto fc_prim = fully_connected("fc", input_info("input"), "weights", "", "scale", "zp", data_types::f16, 2, 3, true, false, false, FcWeightsLayout::GNK);
+ fc_prim.hadamard_block = 1024;
+ topo.add(fc_prim);
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ auto prog = program::build_program(engine, topo, config, false, true);
+ auto& fc = prog->get_node("fc").as<fully_connected>();
+ fc.get_output_layouts(false);
+ EXPECT_FALSE(ov::intel_gpu::cm::FullyConnectedWoqU2ImplementationManager::validate_node(fc, true, false));
+}
+
+// Reproducer for GNK runtime epilogue broadcast unfusing:
+// A dynamic GNK FC with a fused epilogue has no fallback FC implementation when support_shapes() rejects a
+// runtime broadcast operand; primitive_inst::is_valid_fusion() must return false so the node executes via
+// _unfused_subgraph (running the GNK FC on CM and the broadcasting eltwise separately).
+TEST(smoke_fully_connected_cm_woq_u2_regression, gnk_runtime_epilogue_broadcast_unfuses_and_matches_ref) {
+ auto& engine = get_test_engine();
+ if (!cm_woq_u2_supported(engine))
+ GTEST_SKIP() << "CM u2 FC requires Xe2 / Xe3 with CM JIT support and >= 96 KB SLM";
+
+ const NkDisabledScope nk_off;
+ const int64_t K = 128, N = 64;
+ tests::random_generator rg(GET_SUITE_NAME);
+ const auto w = make_weights(engine, K, N, ZpKind::tensor_u8, rg, 91);
+ const auto gnk = make_gnk_buffers(engine, w);
+
+ topology topo(input_layout("input", layout{ov::PartialShape{-1, -1, K}, data_types::f16, format::bfyx}));
+ topo.add(data("weights", gnk.weights));
+ topo.add(data("scale", gnk.scale));
+ topo.add(data("zp", gnk.zp));
+ topo.add(fully_connected("fc_prim", input_info("input"), "weights", "", "scale", "zp", data_types::f32, 3, 3, true, false, false, FcWeightsLayout::GNK));
+ topo.add(input_layout("epi", layout{ov::PartialShape{-1, -1, N}, data_types::f32, format::bfyx}));
+ topo.add(eltwise("post", input_info("fc_prim"), input_info("epi"), eltwise_mode::sum));
+ topo.add(reorder("out", input_info("post"), format::bfyx, data_types::f32));
+
+ auto config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));
+ config.set_property(ov::intel_gpu::optimize_data(true));
+ config.set_user_property(ov::hint::dynamic_quantization_group_size(0));
+ network::ptr net = get_network(engine, topo, config, get_test_stream_ptr(), false);
+
+ auto run_step = [&](int64_t B, int64_t S, bool broadcast_epi) {
+ const int64_t M = B * S;
+ const auto a = random_activations(static_cast<size_t>(M * K), static_cast<uint64_t>(M * 101 + 7));
+ auto in_mem = engine.allocate_memory({ov::PartialShape{B, S, K}, data_types::f16, format::bfyx});
+ set_values(in_mem, a);
+ net->set_input_data("input", in_mem);
+
+ const ov::PartialShape epi_shape = broadcast_epi ? ov::PartialShape{1, 1, N} : ov::PartialShape{B, S, N};
+ std::vector<float> epi_v(static_cast<size_t>(ov::shape_size(epi_shape.to_shape())), 0.25f);
+ auto epi_mem = engine.allocate_memory({epi_shape, data_types::f32, format::bfyx});
+ set_values(epi_mem, epi_v);
+ net->set_input_data("epi", epi_mem);
+
+ auto outputs = net->execute();
+ HostEpi he{Epi::add, &epi_v, broadcast_epi};
+ check_rows(outputs.at("out").get_memory(), M, a, all_rows(M), w, true, he);
+ };
+
+ ASSERT_NO_FATAL_FAILURE(run_step(2, 5, false));
+ ASSERT_NO_FATAL_FAILURE(run_step(2, 5, true));
+ run_step(2, 8, true);
+}
+
+} // namespace
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/convert_fc_to_compressed_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/convert_fc_to_compressed_test.cpp
index 103e34cc3ae..b2b8f7d39fc 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/convert_fc_to_compressed_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/convert_fc_to_compressed_test.cpp
@@ -1225,6 +1225,199 @@ TEST_F(TransformationTestsF, ConvertFCToCompressed24_mxfp4e2m1) {
}
}
+namespace {
+cldnn::device_info cm_u2_capable_device() {
+ cldnn::device_info info{};
+ info.arch = cldnn::gpu_arch::xe2;
+ info.max_local_mem_size = 128 * 1024;
+ return info;
+}
+
+// u2 [G, N, 64] -> Convert -> Subtract(zp) -> Multiply(scale) -> Transpose{1, 0, 2} -> Reshape [N, G * 64] -> FC
+// scale / zero_point default to Constants.
+std::shared_ptr<ov::Node> make_gnk_u2_chain(const ov::Output<ov::Node>& weights,
+ std::shared_ptr<ov::Node> scale = nullptr,
+ std::shared_ptr<ov::Node> zero_point = nullptr) {
+ auto weights_convert = std::make_shared<ov::op::v0::Convert>(weights, ov::element::f16);
+ if (!zero_point) {
+ zero_point = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{2, 32, 1}, {1});
+ }
+ auto zero_point_convert = std::make_shared<ov::op::v0::Convert>(zero_point, ov::element::f16);
+ auto subtract = std::make_shared<ov::op::v1::Subtract>(weights_convert, zero_point_convert);
+ if (!scale) {
+ scale = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{2, 32, 1}, {1});
+ }
+ auto multiply = std::make_shared<ov::op::v1::Multiply>(subtract, scale);
+ auto transpose_order = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{3}, {1, 0, 2});
+ auto transpose = std::make_shared<ov::op::v1::Transpose>(multiply, transpose_order);
+ auto reshape_shape = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{2}, {32, 128});
+ return std::make_shared<ov::op::v1::Reshape>(transpose, reshape_shape, false);
+}
+
+std::shared_ptr<ov::Model> make_gnk_u2_model(const std::shared_ptr<ov::op::v0::Parameter>& input,
+ const std::shared_ptr<ov::Node>& weights,
+ const ov::ParameterVector& parameters,
+ const std::shared_ptr<ov::Node>& scale = nullptr,
+ const std::shared_ptr<ov::Node>& zero_point = nullptr) {
+ auto no_bias = std::make_shared<ov::intel_gpu::op::Placeholder>();
+ auto fc = std::make_shared<ov::intel_gpu::op::FullyConnected>(input, make_gnk_u2_chain(weights, scale, zero_point), no_bias);
+ return std::make_shared<ov::Model>(ov::OutputVector{fc}, parameters);
+}
+
+// Runtime scale [2, 32, 1] / zero point [2, 32, 1] are reshaped to [G, N]; the u2 zero point is widened to u8.
+std::shared_ptr<ov::Node> make_gnk_u2_runtime_params_fc_ref(const ov::Output<ov::Node>& input,
+ const ov::Output<ov::Node>& weights,
+ const ov::Output<ov::Node>& scale,
+ const ov::Output<ov::Node>& zero_point) {
+ auto gn_shape = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{2}, {2, 32});
+ auto gnk_scale = std::make_shared<ov::op::v1::Reshape>(scale, gn_shape, false);
+ auto gnk_zp = std::make_shared<ov::op::v1::Reshape>(zero_point, gn_shape, false);
+ auto zero_point_u8 = std::make_shared<ov::op::v0::Convert>(gnk_zp, ov::element::u8);
+ auto no_bias = std::make_shared<ov::intel_gpu::op::Placeholder>();
+ return std::make_shared<ov::intel_gpu::op::FullyConnectedCompressed>(input,
+ weights,
+ no_bias,
+ gnk_scale,
+ zero_point_u8,
+ ov::element::dynamic,
+ true,
+ false,
+ false,
+ ov::intel_gpu::op::FcWeightsLayout::GNK);
+}
+
+std::shared_ptr<ov::Node> make_gnk_u2_fc_ref(const ov::Output<ov::Node>& input, const ov::Output<ov::Node>& weights) {
+ auto scale = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{2, 32}, {1});
+ auto zero_point = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{2, 32}, {1});
+ auto zero_point_u8 = std::make_shared<ov::op::v0::Convert>(zero_point, ov::element::u8);
+ auto no_bias = std::make_shared<ov::intel_gpu::op::Placeholder>();
+ return std::make_shared<ov::intel_gpu::op::FullyConnectedCompressed>(input,
+ weights,
+ no_bias,
+ scale,
+ zero_point_u8,
+ ov::element::dynamic,
+ true,
+ false,
+ false,
+ ov::intel_gpu::op::FcWeightsLayout::GNK);
+}
+} // namespace
+
+TEST_F(TransformationTestsF, ConvertFCToCompressed25_GnkU2ConstantWeightsOnCmDevice) {
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{2, 32, 64}, {1});
+ model = make_gnk_u2_model(input, weights, ov::ParameterVector{input});
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>(cm_u2_capable_device(), true);
+ }
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = ov::op::v0::Constant::create(ov::element::u2, ov::Shape{2, 32, 64}, {1});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{make_gnk_u2_fc_ref(input, weights)}, ov::ParameterVector{input});
+ }
+}
+
+TEST_F(TransformationTestsF, ConvertFCToCompressed26_GnkU2ParameterWeightsOnCmDevice) {
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ model = make_gnk_u2_model(input, weights, ov::ParameterVector{input, weights});
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>(cm_u2_capable_device(), true);
+ }
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{make_gnk_u2_fc_ref(input, weights)}, ov::ParameterVector{input, weights});
+ }
+}
+
+TEST_F(TransformationTestsF, ConvertFCToCompressed_GnkU2ParameterScaleAndZeroPointOnCmDevice) {
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{2, 32, 1});
+ auto zero_point = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 1});
+ model = make_gnk_u2_model(input, weights, ov::ParameterVector{input, weights, scale, zero_point}, scale, zero_point);
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>(cm_u2_capable_device(), true);
+ }
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{2, 32, 1});
+ auto zero_point = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 1});
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{make_gnk_u2_runtime_params_fc_ref(input, weights, scale, zero_point)},
+ ov::ParameterVector{input, weights, scale, zero_point});
+ }
+}
+
+// A runtime f32 scale reaches the pass behind a Convert to f16 and keeps it.
+TEST_F(TransformationTestsF, ConvertFCToCompressed_GnkU2F32ParameterScaleKeepsConvert) {
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 32, 1});
+ auto zero_point = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 1});
+ auto scale_f16 = std::make_shared<ov::op::v0::Convert>(scale, ov::element::f16);
+ model = make_gnk_u2_model(input, weights, ov::ParameterVector{input, weights, scale, zero_point}, scale_f16, zero_point);
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>(cm_u2_capable_device(), true);
+ }
+ {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 32, 1});
+ auto zero_point = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 1});
+ auto scale_f16 = std::make_shared<ov::op::v0::Convert>(scale, ov::element::f16);
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{make_gnk_u2_runtime_params_fc_ref(input, weights, scale_f16, zero_point)},
+ ov::ParameterVector{input, weights, scale, zero_point});
+ }
+}
+
+TEST(TransformationTests, ConvertFCToCompressed27_GnkU2ParameterWeightsFallBackToNkWithoutCm) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto model = make_gnk_u2_model(input, weights, ov::ParameterVector{input, weights});
+ ov::pass::Manager manager;
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>();
+ manager.run_passes(model);
+
+ size_t compressed_fc_count = 0;
+ for (const auto& node : model->get_ops()) {
+ if (auto fc = ov::as_type_ptr<ov::intel_gpu::op::FullyConnectedCompressed>(node)) {
+ ++compressed_fc_count;
+ EXPECT_EQ(fc->get_weights_layout(), ov::intel_gpu::op::FcWeightsLayout::NK);
+ }
+ }
+ EXPECT_EQ(compressed_fc_count, 1u);
+}
+
+TEST(TransformationTests, ConvertFCToCompressed28_GnkU2FallBackToNkWhenCmRejectsDevice) {
+ auto low_slm_device = cm_u2_capable_device();
+ low_slm_device.max_local_mem_size = 32 * 1024;
+
+ struct Case {
+ cldnn::device_info info;
+ bool cm_jit_supported;
+ };
+ for (const auto& c : {Case{low_slm_device, true}, Case{cm_u2_capable_device(), false}}) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 128});
+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::u2, ov::Shape{2, 32, 64});
+ auto model = make_gnk_u2_model(input, weights, ov::ParameterVector{input, weights});
+ ov::pass::Manager manager;
+ manager.register_pass<ConvertFullyConnectedToFullyConnectedCompressed>(c.info, c.cm_jit_supported);
+ manager.run_passes(model);
+
+ size_t compressed_fc_count = 0;
+ for (const auto& node : model->get_ops()) {
+ if (auto fc = ov::as_type_ptr<ov::intel_gpu::op::FullyConnectedCompressed>(node)) {
+ ++compressed_fc_count;
+ EXPECT_EQ(fc->get_weights_layout(), ov::intel_gpu::op::FcWeightsLayout::NK);
+ }
+ }
+ EXPECT_EQ(compressed_fc_count, 1u);
+ }
+}
+
enum class TransposeBeforeReshapePattern {
ScaleOnly,
ScaleAndZeroPoint,