From b2cdcb44209675bbca323d654f5461db31deb689 Mon Sep 17 00:00:00 2001 From: pascallinxweiler Date: Fri, 23 Oct 2026 16:02:58 +0200 Subject: [PATCH] libxe2: rmsnorm, rmsnorm_quant_fp8, quant_act_fp8, gated_quant_fp8 One work-group a row; a quantisation group a sub-group. The arithmetic is libref's step for step, and two things made it so on the card: - Device code is generated at link time (AOT), so the flags that shape it now go to the link as well as the compile: -ffp-contract=off, -ffp-model=precise, and -foffload-fp32-prec-div/-sqrt. Without correctly rounded division a group's scale amax * (1/448) came out one ulp off, and bf16 inputs sit exactly on E4M3 rounding ties often enough that 1780 of 524288 codes moved (a standalone host/device comparison showed it; with the flags, none). - The sum of squares is libref's ascending f32 sum, by one work-item. A tree reduction moved normed values across bf16 ties on MiniCPM5-2B's real weights and failed rmsnorm_quant_fp8 at M=1 (rel 7.7e-3 against its 4e-3 tolerance). rad-kbench against libref: the fixture 228/228 and MiniCPM5-2B's container 140/140, worst rel_l2 1e-7, inside guarded allocations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1 --- libxe2/CMakeLists.txt | 12 +- libxe2/xe2_norm.cpp | 294 ++++++++++++++++++++++++++++++++++++++++++ libxe2/xe2_ops.h | 5 + libxe2/xe2_rows.cpp | 23 ++++ sycl/CMakeLists.txt | 3 +- 5 files changed, 332 insertions(+), 5 deletions(-) create mode 100644 libxe2/xe2_norm.cpp diff --git a/libxe2/CMakeLists.txt b/libxe2/CMakeLists.txt index db3af6dc..42d3a643 100644 --- a/libxe2/CMakeLists.txt +++ b/libxe2/CMakeLists.txt @@ -24,10 +24,14 @@ rad_add_plugin(libxe2 kernels SOURCES ${XE2_SRC}) # -ffp-contract=off is a correctness flag here as in libref: kernels are checked against it, so # `a*b + c` rounds twice on both sides. It follows -ffp-model=precise, which would otherwise set -# contraction back on. -set(_xe2_sycl -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}") -target_compile_options(libxe2 PRIVATE ${_xe2_sycl} -ffp-model=precise -ffp-contract=off -Wno-overriding-option - -fvisibility=hidden) +# contraction back on. -foffload-fp32-prec-div and -sqrt make device division and sqrt correctly +# rounded, as libref's are: a quantiser's scale is amax * (1/top), and a 1/top one ulp off moves +# codes that sit exactly on an E4M3 rounding tie, which bf16 inputs hit often. +# Device code is generated at link time (AOT), so every flag that shapes it goes to the link too; +# on the compile line alone it changes nothing on the card. +set(_xe2_sycl -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}" -ffp-model=precise -ffp-contract=off + -Wno-overriding-option -foffload-fp32-prec-div -foffload-fp32-prec-sqrt) +target_compile_options(libxe2 PRIVATE ${_xe2_sycl} -fvisibility=hidden) get_filename_component(_xe2_icpx_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) get_filename_component(_xe2_oneapi_lib "${_xe2_icpx_bin}/../lib" ABSOLUTE) target_link_options(libxe2 PRIVATE ${_xe2_sycl} "LINKER:-rpath,${_xe2_oneapi_lib}" diff --git a/libxe2/xe2_norm.cpp b/libxe2/xe2_norm.cpp new file mode 100644 index 00000000..34f5f8f3 --- /dev/null +++ b/libxe2/xe2_norm.cpp @@ -0,0 +1,294 @@ +/* xe2_norm.cpp -- the RMS norms and the block-scaled fp8 activation quantisers. + * + * One work-group a row. The sum of squares is libref's: f32, in ascending index order, by one + * work-item and broadcast to the group. A tree reduction rounds differently, and on MiniCPM5-2B's + * real weights that difference moved enough normed values across a bf16 tie, and from there the + * E4M3 codes, to fail rmsnorm_quant_fp8's tolerance at M=1 (rel 7.7e-3 against 4e-3). The serial + * sum is n multiply-adds, small beside the row's loads; a faster ordered form is Phase 4's. + * A quantisation group belongs to one sub-group, whose lanes stride over it for the amax and the + * codes. + * + * The arithmetic is libref's, step for step (ref_elementwise.cpp, ref_quant.cpp): + * rmsnorm y = ((x * s) * (w + wadd)) * mult, s = 1 / sqrt(mean(x^2) + eps) + * quant_act_fp8 per group: scale = amax * (1/448) (1 for an all-zero group), + * code = clamp(x * (1/scale), +-448), stored RNE + * rmsnorm_quant_fp8 the residual sum is stored first and read back (so the norm sees the + * narrowed sum), the normed row is narrowed to bf16, and the codes are + * taken over those bf16 values; an int8 `q` takes amax / 127 instead + * gated_quant_fp8 silu(gate) * up or sigmoid(gate) * up over a packed [M, 2n] gate_up, + * narrowed to bf16, then quantised as above + */ +#include "xe2_common.h" +#include "xe2_ops.h" + +#include + +namespace xe2 { + +namespace { + +constexpr size_t kWg = 256; /* work-items a row */ + +/* sigmoid as libref's act_sigmoid, in f32 (libref computes exp in double and rounds once; the + * device's f32 exp is within an ulp, inside the tolerance). */ +inline float sigmoidf(float x) { return 1.0f / (1.0f + sycl::exp(-x)); } + +/* The sum of src(i)^2 over i < n in ascending order, f32, as libref sums it, computed by work-item + * 0 and returned to every work-item of the group. */ +template +inline float ordered_sumsq(const sycl::nd_item<1>& it, const F& src, int64_t n) { + float ss = 0.0f; + if (it.get_local_id(0) == 0) + for (int64_t i = 0; i < n; ++i) { + const float v = src(i); + ss += v * v; + } + return sycl::group_broadcast(it.get_group(), ss, 0); +} + +/* One group's codes and scale, by the sub-group `sg` over values v(k0 + i), i < len. + * Returns the scale (the same in every lane). */ +template +inline float quant_group(const sycl::sub_group& sg, const V& v, int64_t k0, int64_t len, float top, + char* qbase, uint32_t qdt, int64_t qoff) { + const int lane = (int)sg.get_local_linear_id(); + float amax = 0.0f; + for (int64_t i = lane; i < len; i += kSub) amax = sycl::fmax(amax, sycl::fabs(v(k0 + i))); + amax = sycl::reduce_over_group(sg, amax, sycl::maximum()); + const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f; + const float inv = 1.0f / sc; + for (int64_t i = lane; i < len; i += kSub) { + float c = v(k0 + i) * inv; + if (c > top) c = top; + if (c < -top) c = -top; + rad_store_f32(qbase, qdt, qoff + k0 + i, c); + } + return sc; +} + +/* The scale plane, one value a group, rows of `ngrp`. */ +int scale_view(const RadTensor* s, int64_t rows, int64_t ngrp, Rows* out, const char* what) { + if (rad_tensor_numel(s) < rows * ngrp) return RAD_E_SHAPE; + return rows_view(s, ngrp, out, what); +} + +/* The gain, read as one row of n, or absent. */ +struct Gain { + const char* base = nullptr; + uint32_t dtype = 0; + int64_t stride = 1; +}; +int gain_view(const RadTensor* w, int64_t n, Gain* out, const char* what) { + if (!w) return RAD_OK; + if (rad_tensor_numel(w) < n) return RAD_E_SHAPE; + out->base = (const char*)w->data; + out->dtype = w->dtype; + out->stride = w->rank ? w->stride[w->rank - 1] : 1; + (void)what; + return RAD_OK; +} + +} // namespace + +/* ------------------------------------------------------------------ rmsnorm */ +int rmsnorm(const RadArgs* a, RadStream st) { + if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL; + const RadTensor* w = rad_arg_in(a, 1); + const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0); + if (!w && wadd != 0.0f) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0); + const float eps = (float)rad_args_getf_or(a, "eps", 1e-6); + const float mult = (float)rad_args_getf_or(a, "mult", 1.0); + if (n <= 0) return RAD_E_SHAPE; + Rows x, y; + Gain g; + if (int rc = rows_view(&a->t[0], n, &x, "rmsnorm x"); rc < 0) return rc; + if (int rc = rows_view(&a->t[2], n, &y, "rmsnorm y"); rc < 0) return rc; + if (int rc = gain_view(w, n, &g, "rmsnorm w"); rc < 0) return rc; + const int64_t rows = x.rows; + if (rows <= 0 || y.rows < rows) return RAD_E_SHAPE; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg}, + [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { + const int64_t r = (int64_t)it.get_group(0); + const int t = (int)it.get_local_id(0); + const float ss = ordered_sumsq( + it, [&](int64_t i) { return rad_load_f32(x.base, x.dtype, r * x.pitch + i); }, n); + const float s = 1.0f / sycl::sqrt(ss / (float)n + eps); + for (int64_t i = t; i < n; i += kWg) { + const float gw = g.base ? rad_load_f32(g.base, g.dtype, i * g.stride) + wadd : 1.0f; + const float v = rad_load_f32(x.base, x.dtype, r * x.pitch + i); + rad_store_f32(y.base, y.dtype, r * y.pitch + i, v * s * gw * mult); + } + }); + }); +} + +/* ------------------------------------------------------------------ quant_act_fp8 */ +int quant_act_fp8(const RadArgs* a, RadStream st) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + int64_t g = rad_args_geti_or(a, "group", 0); + if (g <= 0 || g > n) g = n; + const int64_t ngrp = (n + g - 1) / g; + Rows x, qv, sv; + if (int rc = rows_view(&a->t[0], n, &x, "quant_act_fp8 x"); rc < 0) return rc; + const int64_t rows = x.rows; + if (rows <= 0 || rad_tensor_numel(&a->t[1]) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(&a->t[1], n, &qv, "quant_act_fp8 q"); rc < 0) return rc; + if (int rc = scale_view(&a->t[2], rows, ngrp, &sv, "quant_act_fp8 scale"); rc < 0) return rc; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + constexpr int kSubs = (int)(kWg / kSub); + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg}, + [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { + const int64_t r = (int64_t)it.get_group(0); + const sycl::sub_group sg = it.get_sub_group(); + const int sgi = (int)sg.get_group_linear_id(); + auto v = [&](int64_t i) { return rad_load_f32(x.base, x.dtype, r * x.pitch + i); }; + for (int64_t gi = sgi; gi < ngrp; gi += kSubs) { + const int64_t k0 = gi * g, len = sycl::min(g, n - k0); + const float sc = quant_group(sg, v, k0, len, 448.0f, qv.base, qv.dtype, r * qv.pitch); + if (sg.get_local_linear_id() == 0) + rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc); + } + }); + }); +} + +/* ------------------------------------------------------------------ rmsnorm_quant_fp8 */ +int rmsnorm_quant_fp8(const RadArgs* a, RadStream st) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[2], *Q = &a->t[3], *S = &a->t[4]; + const RadTensor* R = rad_arg_in(a, 1); + const RadTensor* O = rad_arg_in(a, 5); + if (!X->data || !W->data || !Q->data || !S->data) return RAD_E_INVAL; + const int64_t n = rad_args_geti_or(a, "n", W->rank ? W->shape[W->rank - 1] : 0); + const float eps = (float)rad_args_getf_or(a, "eps", 1e-6); + const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0); + if (n <= 0) return RAD_E_SHAPE; + int64_t g = rad_args_geti_or(a, "group", 0); + if (g <= 0 || g > n) g = n; + const int64_t ngrp = (n + g - 1) / g; + Rows x, qv, sv, res, ob; + Gain gw; + if (int rc = rows_view(X, n, &x, "rmsnorm_quant_fp8 x"); rc < 0) return rc; + const int64_t rows = x.rows; + if (rows <= 0 || rad_tensor_numel(Q) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(Q, n, &qv, "rmsnorm_quant_fp8 q"); rc < 0) return rc; + if (int rc = scale_view(S, rows, ngrp, &sv, "rmsnorm_quant_fp8 scale"); rc < 0) return rc; + if (int rc = gain_view(W, n, &gw, "rmsnorm_quant_fp8 w"); rc < 0) return rc; + const bool has_res = R != nullptr, has_ob = O != nullptr; + if (has_res) { + if (rad_tensor_numel(R) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(R, n, &res, "rmsnorm_quant_fp8 residual"); rc < 0) return rc; + } + if (has_ob) { + if (rad_tensor_numel(O) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(O, n, &ob, "rmsnorm_quant_fp8 out_bf16"); rc < 0) return rc; + } + const float top = Q->dtype == RAD_I8 ? 127.0f : 448.0f; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + constexpr int kSubs = (int)(kWg / kSub); + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg}, + [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { + const int64_t r = (int64_t)it.get_group(0); + const int t = (int)it.get_local_id(0); + /* The residual sum, stored first; the rest reads it back narrowed. Other work-items + * read these elements below, hence the barrier. */ + if (has_res) { + for (int64_t i = t; i < n; i += kWg) { + const float s = rad_load_f32(x.base, x.dtype, r * x.pitch + i) + + rad_load_f32(res.base, res.dtype, r * res.pitch + i); + rad_store_f32(res.base, res.dtype, r * res.pitch + i, s); + } + sycl::group_barrier(it.get_group()); + } + auto src = [&](int64_t i) { + return has_res ? rad_load_f32(res.base, res.dtype, r * res.pitch + i) + : rad_load_f32(x.base, x.dtype, r * x.pitch + i); + }; + const float ss = ordered_sumsq(it, src, n); + const float rs = 1.0f / sycl::sqrt(ss / (float)n + eps); + /* The normed value narrowed to bf16, as the unfused pair would write it. */ + auto v = [&](int64_t i) { + const float w = rad_load_f32(gw.base, gw.dtype, i * gw.stride) + wadd; + return rad_bf16_to_f32(rad_f32_to_bf16(src(i) * rs * w)); + }; + if (has_ob) + for (int64_t i = t; i < n; i += kWg) + rad_store_f32(ob.base, ob.dtype, r * ob.pitch + i, v(i)); + const sycl::sub_group sg = it.get_sub_group(); + const int sgi = (int)sg.get_group_linear_id(); + for (int64_t gi = sgi; gi < ngrp; gi += kSubs) { + const int64_t k0 = gi * g, len = sycl::min(g, n - k0); + const float sc = quant_group(sg, v, k0, len, top, qv.base, qv.dtype, r * qv.pitch); + if (sg.get_local_linear_id() == 0) + rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc); + } + }); + }); +} + +/* ------------------------------------------------------------------ gated_quant_fp8 */ +int gated_quant_fp8(const RadArgs* a, RadStream st) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *GU = &a->t[0], *Q = &a->t[1], *S = &a->t[2]; + const RadTensor* O = rad_arg_in(a, 3); + const int64_t n = rad_args_geti_or(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const char* act_s = rad_args_gets_or(a, "act", nullptr); + int act = (int)rad_args_geti_or(a, "mode", 0); + if (act_s) act = !std::strcmp(act_s, "silu") ? 0 : !std::strcmp(act_s, "sigmoid") ? 1 : -1; + if (act != 0 && act != 1) return RAD_E_INVAL; + int64_t g = rad_args_geti_or(a, "group", 0); + if (g <= 0 || g > n) g = n; + const int64_t ngrp = (n + g - 1) / g; + Rows gu, qv, sv, ob; + if (int rc = rows_view(GU, 2 * n, &gu, "gated_quant_fp8 gate_up"); rc < 0) return rc; + const int64_t rows = gu.rows; + if (rows <= 0 || rad_tensor_numel(Q) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(Q, n, &qv, "gated_quant_fp8 q"); rc < 0) return rc; + if (int rc = scale_view(S, rows, ngrp, &sv, "gated_quant_fp8 scale"); rc < 0) return rc; + const bool has_ob = O != nullptr; + if (has_ob) { + if (rad_tensor_numel(O) < rows * n) return RAD_E_SHAPE; + if (int rc = rows_view(O, n, &ob, "gated_quant_fp8 out_bf16"); rc < 0) return rc; + } + const float top = Q->dtype == RAD_I8 ? 127.0f : 448.0f; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + constexpr int kSubs = (int)(kWg / kSub); + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * kWg, kWg}, + [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { + const int64_t r = (int64_t)it.get_group(0); + const int t = (int)it.get_local_id(0); + auto v = [&](int64_t i) { + const float gt = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + i); + const float up = rad_load_f32(gu.base, gu.dtype, r * gu.pitch + n + i); + const float sg = sigmoidf(gt); + return rad_bf16_to_f32(rad_f32_to_bf16((act == 0 ? gt * sg : sg) * up)); + }; + if (has_ob) + for (int64_t i = t; i < n; i += kWg) + rad_store_f32(ob.base, ob.dtype, r * ob.pitch + i, v(i)); + const sycl::sub_group sg = it.get_sub_group(); + const int sgi = (int)sg.get_group_linear_id(); + for (int64_t gi = sgi; gi < ngrp; gi += kSubs) { + const int64_t k0 = gi * g, len = sycl::min(g, n - k0); + const float sc = quant_group(sg, v, k0, len, top, qv.base, qv.dtype, r * qv.pitch); + if (sg.get_local_linear_id() == 0) + rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc); + } + }); + }); +} + +} // namespace xe2 diff --git a/libxe2/xe2_ops.h b/libxe2/xe2_ops.h index 7ec41678..12a2f3a7 100644 --- a/libxe2/xe2_ops.h +++ b/libxe2/xe2_ops.h @@ -6,4 +6,9 @@ namespace xe2 { int add(const RadArgs* a, RadStream s); +int rmsnorm(const RadArgs* a, RadStream s); +int rmsnorm_quant_fp8(const RadArgs* a, RadStream s); +int quant_act_fp8(const RadArgs* a, RadStream s); +int gated_quant_fp8(const RadArgs* a, RadStream s); + } // namespace xe2 diff --git a/libxe2/xe2_rows.cpp b/libxe2/xe2_rows.cpp index 1998702f..6fd8f9cd 100644 --- a/libxe2/xe2_rows.cpp +++ b/libxe2/xe2_rows.cpp @@ -20,6 +20,29 @@ const RadKernelInfo kKernels[] = { .dtypes = "any float dtype in and out (bf16, f16, f32, fp8), f32 arithmetic, rounded as libref", .domain = RAD_DOMAIN_DEVICE, .priority = 0, .launch = xe2::add }, + + { .name = "xe2_rmsnorm", .op = "rmsnorm", .family = "norm", + .computes = "RMS norm, one work-group a row, f32 work-group reduction", + .shape = "any n; rows may be padded", + .dtypes = "float x, gain and y (bf16 in the recipes), f32 arithmetic", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::rmsnorm }, + { .name = "xe2_rmsnorm_quant_fp8", .op = "rmsnorm_quant_fp8", .family = "norm", + .computes = "residual add (optional), RMS norm, bf16 narrowing, E4M3 codes and an f32 scale " + "per group; int8 codes at amax/127 for an int8 q", + .shape = "any n and group; one sub-group a quantisation group", + .dtypes = "bf16 in, E4M3 (or i8) codes, f32 scales, optional bf16 out", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::rmsnorm_quant_fp8 }, + { .name = "xe2_quant_act_fp8", .op = "quant_act_fp8", .family = "quant", + .computes = "E4M3 codes and an f32 scale amax/448 per group", + .shape = "any n and group", + .dtypes = "float in, E4M3 codes, f32 scales", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::quant_act_fp8 }, + { .name = "xe2_gated_quant_fp8", .op = "gated_quant_fp8", .family = "quant", + .computes = "silu(gate)*up or sigmoid(gate)*up over packed gate_up, bf16 narrowing, E4M3 " + "codes and an f32 scale per group", + .shape = "any n and group", + .dtypes = "bf16 gate_up, E4M3 (or i8) codes, f32 scales, optional bf16 out", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::gated_quant_fp8 }, }; const RadPluginInfo kInfo = { diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index fde70cef..410d80cb 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -24,7 +24,8 @@ set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31" CACHE STRING "AOT targets for SYCL devi # the kernels themselves. add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -ffp-model=precise) -set(RAD_SYCL_FLAGS -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}") +set(RAD_SYCL_FLAGS -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}" -foffload-fp32-prec-div + -foffload-fp32-prec-sqrt) # The oneAPI runtime libraries sit beside the compiler; record their directory so the engine runs # without setvars.sh in its environment.