This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libxe2/xe2_norm.cpp
T
pascallinxweilerandClaude Opus 5.5 f5614a03bb libxe2: the norm and the fp8 quantisers 3-4x faster at decode, still bit-identical to libref
At one row a work-group, rmsnorm_quant_fp8 took 108 us and gated_quant_fp8 84 us a call (26% and 10%
of a decode step at a 1.8k context). The ordered sum of squares now reads its squares eight at a
time and adds them in the same order; quant_group computes a group's values once into registers and
writes out_bf16 itself; gated_quant_fp8 spreads a row's independent groups over ceil(groups/16)
work-groups. rad-kbench: 208/208 and 206/206 at rel_l2 0.

scripts/sycl/profile_decode.sh isolates decode steps' per-op device time (two profiled runs of the
same request, 1 and 1 + STEPS tokens, differenced). Decode at 1.8k context: 34.8 -> 26.6 ms of
device time a step; the two ops 9.1 -> 3.7 and 3.5 -> 0.9 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:47:13 +02:00

341 lines
17 KiB
C++

/* 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 <cstring>
namespace xe2 {
namespace {
constexpr size_t kWg = 256; /* work-items a row */
/* sigmoid exactly as libref's act_sigmoid: exp in double, rounded once to f32 (ref_exp). An f32
* exp is within an ulp, inside rad-kbench's tolerance, but an ulp in silu now and then moves the
* bf16 narrowing and then an E4M3 code; the engine-level oracle (RADIANCE_OP_ORACLE) caught one
* such code in some of MiniCPM5-2B's 42 layers, enough to flip a greedy near-tie later. */
inline float sigmoidf(float x) { return 1.0f / (1.0f + (float)sycl::exp((double)-x)); }
/* The sum of src(i)^2 over i < n in ascending order, f32, as libref sums it, returned to every
* work-item of the group. The squares are formed in parallel into local memory a chunk at a time
* and work-item 0 adds them in index order: the same additions as a serial loop, bit for bit, but
* reading local memory instead of waiting on one global load after another (that serial walk was
* 13% of a MiniCPM5 decode step, 360 us a call). */
constexpr int64_t kSqChunk = 2048;
template <class F>
inline float ordered_sumsq(const sycl::nd_item<1>& it, const F& src, int64_t n) {
auto grp = it.get_group();
float* sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSqChunk]>(grp);
const int64_t t = (int64_t)it.get_local_id(0), wg = (int64_t)it.get_local_range(0);
float ss = 0.0f;
for (int64_t c0 = 0; c0 < n; c0 += kSqChunk) {
const int64_t cn = sycl::min(kSqChunk, n - c0);
for (int64_t i = t; i < cn; i += wg) {
const float v = src(c0 + i);
sq[i] = v * v;
}
sycl::group_barrier(grp);
if (t == 0) {
/* Eight independent loads a step, then the eight adds in index order: the same sum,
* without waiting on one local-memory load per addition. */
int64_t i = 0;
for (; i + 8 <= cn; i += 8) {
float b[8];
for (int j = 0; j < 8; ++j) b[j] = sq[i + j];
for (int j = 0; j < 8; ++j) ss += b[j];
}
for (; i < cn; ++i) ss += sq[i];
}
sycl::group_barrier(grp);
}
return sycl::group_broadcast(grp, ss, 0);
}
/* One group's codes and scale, by the sub-group `sg` over values v(k0 + i), i < len; with
* `obase`, each value is also stored there (out_bf16). A group of up to kCached * 16 values is
* computed once into registers, so the amax pass and the codes read the same floats without
* evaluating v twice (for gated_quant_fp8 that is a double exp an element); a wider group
* evaluates v in each pass, which gives the same floats. Returns the scale (the same in every
* lane). */
constexpr int kCached = 8;
template <class V>
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, char* obase = nullptr,
uint32_t odt = 0, int64_t ooff = 0) {
const int lane = (int)sg.get_local_linear_id();
auto code = [&](int64_t i, float x, float inv) {
float c = x * inv;
if (c > top) c = top;
if (c < -top) c = -top;
rad_store_f32(qbase, qdt, qoff + k0 + i, c);
if (obase) rad_store_f32(obase, odt, ooff + k0 + i, x);
};
float amax = 0.0f;
if (len <= (int64_t)kCached * kSub) {
float c[kCached];
for (int j = 0; j < kCached; ++j) {
const int64_t i = lane + (int64_t)j * kSub;
c[j] = i < len ? v(k0 + i) : 0.0f;
amax = sycl::fmax(amax, sycl::fabs(c[j]));
}
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
for (int j = 0; j < kCached; ++j) {
const int64_t i = lane + (int64_t)j * kSub;
if (i < len) code(i, c[j], inv);
}
return sc;
}
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<float>());
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) code(i, v(k0 + i), inv);
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));
};
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,
has_ob ? ob.base : nullptr, ob.dtype, r * ob.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;
/* The groups are independent, so a row spreads over ceil(ngrp / 16) work-groups, one group a
* sub-group: at decode (one row of 48 groups) three work-groups share the row, not one. */
constexpr int kSubs = (int)(kWg / kSub);
const int64_t per_row = (ngrp + kSubs - 1) / kSubs;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * per_row) * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t r = (int64_t)it.get_group(0) / per_row;
const sycl::sub_group sg = it.get_sub_group();
const int64_t gi = ((int64_t)it.get_group(0) % per_row) * kSubs + (int64_t)sg.get_group_linear_id();
if (gi >= ngrp) return; /* uniform across the sub-group */
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 sgm = sigmoidf(gt);
return rad_bf16_to_f32(rad_f32_to_bf16((act == 0 ? gt * sgm : sgm) * up));
};
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,
has_ob ? ob.base : nullptr, ob.dtype, r * ob.pitch);
if (sg.get_local_linear_id() == 0) rad_store_f32(sv.base, sv.dtype, r * sv.pitch + gi, sc);
});
});
}
} // namespace xe2