/* 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 */ constexpr int64_t kRowMax = 8192; /* a row rmsnorm_quant_fp8 keeps in local memory */ /* 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 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(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); const sycl::sub_group sg = it.get_sub_group(); if (sg.get_group_linear_id() == 0) { /* Sub-group 0 takes the squares sixteen at a time, one a lane, and every lane adds them * in index order from the lanes' registers: the same chain of additions as libref's * serial loop, without a local-memory load per addition. */ const int lane = (int)sg.get_local_linear_id(); int64_t i = 0; for (; i + kSub <= cn; i += kSub) { const float v = sq[i + lane]; for (int j = 0; j < kSub; ++j) ss += sycl::select_from_group(sg, v, 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 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()); 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()); 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); if (n <= kRowMax) { /* A row up to kRowMax in local memory: the (narrowed) residual sum and its squares are * formed once from one read of x and the residual, the sum stored once; sub-group 0 adds * the squares in index order through register broadcasts (libref's chain); the groups * read their values from local memory. The same arithmetic as the general form below, * without re-reading what the work-group just stored. */ return submit([&] { q->submit([&](sycl::handler& h) { sycl::local_accessor sv_(sycl::range<1>((size_t)n), h); sycl::local_accessor sq(sycl::range<1>((size_t)n), h); sycl::local_accessor wl(sycl::range<1>((size_t)n), h); h.parallel_for(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 grp = it.get_group(); /* Every load of the work-item first, then the stores: interleaved, each load would * wait for the store before it (the residual may alias x as far as the compiler * knows), a memory round trip an element. */ constexpr int kPer = (int)(kRowMax / kWg); float xv[kPer], rv[kPer], wv[kPer]; /* fully unrolled and predicated (no early exit), so every load is in flight * before the first is used */ #pragma unroll for (int j = 0; j < kPer; ++j) { const int64_t i = t + (int64_t)j * kWg; const bool ok = i < n; const int64_t ii = ok ? i : 0; xv[j] = rad_load_f32(x.base, x.dtype, r * x.pitch + ii); rv[j] = has_res ? rad_load_f32(res.base, res.dtype, r * res.pitch + ii) : 0.0f; wv[j] = rad_load_f32(gw.base, gw.dtype, ii * gw.stride) + wadd; } #pragma unroll for (int j = 0; j < kPer; ++j) { const int64_t i = t + (int64_t)j * kWg; if (i >= n) continue; float v = xv[j]; if (has_res) { const float s0 = v + rv[j]; rad_store_f32(res.base, res.dtype, r * res.pitch + i, s0); v = round_dt(res.dtype, s0); /* what reading it back gives */ } sv_[i] = v; sq[i] = v * v; wl[i] = wv[j]; } sycl::group_barrier(grp); const sycl::sub_group sg = it.get_sub_group(); float ss = 0.0f; if (sg.get_group_linear_id() == 0) { const int lane = (int)sg.get_local_linear_id(); int64_t i = 0; for (; i + kSub <= n; i += kSub) { const float v = sq[i + lane]; for (int j = 0; j < kSub; ++j) ss += sycl::select_from_group(sg, v, j); } for (; i < n; ++i) ss += sq[i]; } ss = sycl::group_broadcast(grp, ss, 0); const float rs = 1.0f / sycl::sqrt(ss / (float)n + eps); auto v = [&](int64_t i) { return rad_bf16_to_f32(rad_f32_to_bf16(sv_[i] * rs * wl[i])); }; 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); } }); }); }); } 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