/* xe2_gemm_q.cpp -- the block-scaled GEMMs: gemm_nt_q over fp8 codes, and gemm_nt_q_gated, the * same product with the gated fp8 quantiser in its epilogue. Correctness first, like xe2_gemm.cpp: * libref's quant_dot (ref_gemm.h) per output, in its order -- * * per weight group g: sub = sum over ascending k in g of a[k] * b[k] (codes decoded to f32) * acc = acc + (sub * sa) * sb * * -- with the scale streams read as libref's make_scales reads them: a rank-2 stream states its own * grid, and a stream with fewer rows than its operand is a block grid (DeepSeek-style 128x128 fp8, * `[ceil(N/128)][ceil(K/128)]`), its block the power of two grid_block finds. The scale grids are * worked out on the host per launch and handed to the kernel as values. * * Served: the byte-coded pairs fp8a8, fp8a8f32 and fp8a16 (E4M3 weights against E4M3 or bf16 * activations). The zero-point grids (w2a8, w4*_asym), mxfp4 and the parts form are not here; their * rows are not declared, so they cannot be selected. * * gemm_nt_q_gated: one work-group a row. Each work-item takes output columns i of the gated half, * forms the gate and up products (columns i and n + i) and libref's epilogue on them -- both rounded * to bf16, the gate (silu or sigmoid, exp in double), the product narrowed to bf16 -- into local * memory; then the E4M3 (or int8) group quantiser over those n values. Byte-identical to gemm_nt_q * followed by gated_quant_fp8, as libref's is. Local memory holds n floats, so n <= 28672 (a * 27B model's gate_up has n = 17408). */ #include "xe2_common.h" #include "xe2_ops.h" #include namespace xe2 { namespace { int64_t row_stride(const RadTensor* t, int64_t cols) { if (!t || t->rank < 2) return cols; int64_t span = 1; for (int i = (int)t->rank - 1; i >= 0; --i) { span *= t->shape[i]; if (span == cols) return (i > 0) ? t->stride[i - 1] : cols; if (span > cols) break; } return t->stride[t->rank - 2]; } /* libref's grid_block. */ int64_t grid_block(int64_t ext, int64_t blocks) { if (ext <= 0) return 1; if (blocks <= 1) return ext; const int64_t lo = (ext + blocks - 1) / blocks; int64_t b = 1; while (b < lo) b <<= 1; return (ext + b - 1) / b == blocks ? b : lo; } /* libref's Scales, by value. */ struct Scales { const char* p = nullptr; uint32_t dt = RAD_F32; int64_t rs = 0, cs = 0, group = 0, rblk = 1; float grp(int64_t row, int64_t g) const { const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; return rad_load_f32(p, dt, i); } float at(int64_t row, int64_t k) const { return grp(row, group > 0 ? k / group : 0); } }; /* libref's make_scales (no mxfp4 here, so never e8m0). */ Scales make_scales(const RadTensor* s, int64_t rows, int64_t K) { Scales q; if (!s || !s->data || rows <= 0 || rad_tensor_numel(s) <= 0) { q.group = K; return q; } q.p = (const char*)s->data; q.dt = s->dtype; int64_t groups = 0; if (s->rank >= 2) { const int64_t srows = s->shape[s->rank - 2]; q.rblk = srows >= rows ? 1 : grid_block(rows, srows); groups = s->shape[s->rank - 1]; q.rs = s->stride[s->rank - 2]; q.cs = s->stride[s->rank - 1]; } else { const int64_t nel = rad_tensor_numel(s); if (nel >= rows) { groups = nel / rows; q.rs = groups; } else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; } q.cs = 1; } q.group = grid_block(K, groups); return q; } struct Mat { const char* p; uint32_t dt; int64_t rs, cs; }; /* libref's quant_dot. */ inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB, int64_t m, int64_t n, int64_t K) { const int64_t g = SB.group > 0 ? SB.group : K; const int64_t ngrp = (K + g - 1) / g; const bool coarse_a = !SA.p || SA.group >= g; const int64_t a0 = m * A.rs, b0 = n * B.rs; float acc = 0.0f; for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K; const float sb = SB.p ? SB.grp(n, gi) : 1.0f; float sub = 0.0f; if (coarse_a) { for (int64_t k = k0; k < k1; ++k) sub += rad_load_f32(A.p, A.dt, a0 + k * A.cs) * rad_load_f32(B.p, B.dt, b0 + k * B.cs); acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb; } else { for (int64_t k = k0; k < k1; ++k) sub += rad_load_f32(A.p, A.dt, a0 + k * A.cs) * SA.at(m, k) * rad_load_f32(B.p, B.dt, b0 + k * B.cs); acc += sub * sb; } } return acc; } bool byte_float(uint32_t dt) { return dt == RAD_F8E4M3 || dt == RAD_F8E5M2 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; } /* The shared front of both ops: operands, extents and the scale grids. */ struct QArgs { Mat A, B; Scales SA, SB; int64_t M = 0, N = 0, K = 0; }; int q_args(const RadArgs* a, const RadTensor* A, const RadTensor* AS, const RadTensor* B, const RadTensor* BS, int64_t M, QArgs* out, const char* op) { const int64_t K = rad_args_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; if (!byte_float(A->dtype) || !byte_float(B->dtype)) return refuse("%s: dtype pair %u x %u is not served (fp8 or bf16 codes only)", op, A->dtype, B->dtype); out->K = K; out->N = N; out->M = M; if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE; out->A = Mat{ (const char*)A->data, A->dtype, row_stride(A, K), A->rank >= 2 ? A->stride[A->rank - 1] : 1 }; out->B = Mat{ (const char*)B->data, B->dtype, row_stride(B, K), B->rank >= 2 ? B->stride[B->rank - 1] : 1 }; out->SA = make_scales(AS, M, K); out->SB = make_scales(BS, N, K); const int64_t gp = rad_args_geti_or(a, "group", 0); if (gp > 0 && out->SB.p && out->SB.group != gp) return RAD_E_SHAPE; return RAD_OK; } } // namespace /* ------------------------------------------------------------------ gemm_nt_q */ int gemm_nt_q(const RadArgs* a, RadStream st) { if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL; if (rad_arg_in(a, 5) || rad_arg_in(a, 6)) return refuse("gemm_nt_q: a_sum / b_ref belong to the zero-point and mxfp4 grids, not served"); if (rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0) return refuse("gemm_nt_q: the parts form is not served"); const RadTensor *Y = &a->t[4], *B = &a->t[2]; const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (N <= 0) return RAD_E_SHAPE; QArgs g; if (int rc = q_args(a, &a->t[0], rad_arg_in(a, 1), B, rad_arg_in(a, 3), rad_tensor_numel(Y) / N, &g, "gemm_nt_q"); rc < 0) return rc; const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; char* yb = (char*)Y->data; const uint32_t ydt = Y->dtype; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const size_t wn = 64; const size_t nn = (size_t)((g.N + (int64_t)wn - 1) / (int64_t)wn) * wn; return submit([&] { syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)g.M, nn}, {1, wn}}, [=](sycl::nd_item<2> it) { const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1); if (n >= g.N) return; rad_store_f32(yb, ydt, m * yrs + n * ycs, quant_dot(g.A, g.B, g.SA, g.SB, m, n, g.K)); }); }); } /* ------------------------------------------------------------------ gemm_nt_q_gated */ namespace { constexpr size_t kGatedWg = 512; constexpr int64_t kGatedMaxN = 2 * 28672; /* n gated values in local memory: 112 KiB of f32 */ } int gemm_nt_q_gated(const RadArgs* a, RadStream st) { if (!a || a->n_t < 6) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[2], *Q = &a->t[4], *S = &a->t[5]; const RadTensor* O = rad_arg_in(a, 6); if (!A->data || !B->data || !Q->data || !S->data) return RAD_E_INVAL; const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (N <= 0 || (N & 1)) return RAD_E_SHAPE; if (N > kGatedMaxN) return refuse("gemm_nt_q_gated: N %lld over %lld", (long long)N, (long long)kGatedMaxN); const int64_t n = N / 2; const char* act_s = rad_args_gets_or(a, "act", nullptr); const int act = !act_s ? -1 : !std::strcmp(act_s, "silu") ? 0 : !std::strcmp(act_s, "sigmoid") ? 1 : -1; if (act != 0 && act != 1) return RAD_E_INVAL; int64_t gq = rad_args_geti_or(a, "group", 0); if (gq <= 0 || gq > n) gq = n; const int64_t ngrp = (n + gq - 1) / gq; const int64_t M = rad_tensor_numel(Q) / n; QArgs g; if (int rc = q_args(a, A, rad_arg_in(a, 1), B, rad_arg_in(a, 3), M, &g, "gemm_nt_q_gated"); rc < 0) return rc; if (rad_tensor_numel(S) < M * ngrp) return RAD_E_SHAPE; Rows qv, sv, ob; if (int rc = rows_view(Q, n, &qv, "gemm_nt_q_gated q"); rc < 0) return rc; if (int rc = rows_view(S, ngrp, &sv, "gemm_nt_q_gated scale"); rc < 0) return rc; const bool has_ob = O != nullptr; if (has_ob) { if (rad_tensor_numel(O) < M * n) return RAD_E_SHAPE; if (int rc = rows_view(O, n, &ob, "gemm_nt_q_gated 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)(kGatedWg / kSub); return submit([&] { q->submit([&](sycl::handler& h) { sycl::local_accessor gv(sycl::range<1>((size_t)n), h); h.parallel_for(sycl::nd_range<1>{(size_t)M * kGatedWg, kGatedWg}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const int64_t m = (int64_t)it.get_group(0); const int t = (int)it.get_local_id(0); for (int64_t i = t; i < n; i += (int64_t)kGatedWg) { const float gt = round_dt(RAD_BF16, quant_dot(g.A, g.B, g.SA, g.SB, m, i, g.K)); const float up = round_dt(RAD_BF16, quant_dot(g.A, g.B, g.SA, g.SB, m, n + i, g.K)); const float sg = 1.0f / (1.0f + (float)sycl::exp((double)-gt)); gv[i] = rad_bf16_to_f32(rad_f32_to_bf16((act == 0 ? gt * sg : sg) * up)); } sycl::group_barrier(it.get_group()); auto v = [&](int64_t i) { return gv[i]; }; if (has_ob) for (int64_t i = t; i < n; i += (int64_t)kGatedWg) rad_store_f32(ob.base, ob.dtype, m * ob.pitch + i, v(i)); const sycl::sub_group sg = it.get_sub_group(); const int sgi = (int)sg.get_group_linear_id(); const int lane = (int)sg.get_local_linear_id(); for (int64_t gi = sgi; gi < ngrp; gi += kSubs) { const int64_t k0 = gi * gq, len = sycl::min(gq, n - k0); 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(qv.base, qv.dtype, m * qv.pitch + k0 + i, c); } if (lane == 0) rad_store_f32(sv.base, sv.dtype, m * sv.pitch + gi, sc); } }); }); }); } /* ------------------------------------------------------------------ silu_mul */ /* y[i] = silu(gate[i]) * up[i] over a packed [M, 2n] gate_up (ref_elementwise.cpp), exp in double. */ int silu_mul(const RadArgs* a, RadStream st) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *GU = &a->t[0], *Y = &a->t[1]; const int64_t n = rad_args_geti_or(a, "n", rad_tensor_numel(Y)); if (n <= 0) return RAD_E_SHAPE; Rows y, gu; if (int rc = rows_view(Y, n, &y, "silu_mul y"); rc < 0) return rc; const int64_t rows = y.rows; if (rows <= 0 || rad_tensor_numel(GU) < rows * 2 * n) return RAD_E_SHAPE; if (int rc = rows_view(GU, 2 * n, &gu, "silu_mul gate_up"); rc < 0) return rc; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const int64_t total = rows * n; const bool bf16_out = y.dtype == RAD_BF16 && !exact_only(); /* bf16 rows, 8-aligned: a work-item eight columns of a row, 16-byte loads and store, the * same per-element arithmetic (the scalar form's int64 divide a value bounded it at ~0.7 ms * a prefill call) */ if (bf16_out && gu.dtype == RAD_BF16 && n % 8 == 0 && gu.pitch % 8 == 0 && y.pitch % 8 == 0 && rad_ptr_aligned(gu.base, 16) && rad_ptr_aligned(y.base, 16) && n / 8 < (int64_t)1 << 30) { using V8 = sycl::vec; const int n8 = (int)(n / 8); const size_t wg8 = 128; return submit([&] { syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)rows, (size_t)((n8 + wg8 - 1) / wg8 * wg8)}, {1, wg8}}, [=](sycl::nd_item<2> it) { const int c8 = (int)it.get_global_id(1); if (c8 >= n8) return; const int64_t r = (int64_t)it.get_global_id(0); const uint16_t* gp = (const uint16_t*)gu.base + r * gu.pitch + (int64_t)c8 * 8; const V8 xg = *(const V8*)gp, xu = *(const V8*)(gp + n); V8 o; #pragma unroll for (int e = 0; e < 8; ++e) { const float x = sycl::bit_cast((uint32_t)xg[e] << 16); const float up = sycl::bit_cast((uint32_t)xu[e] << 16); float v = x * sigmoid_fexp(x) * up; if (near_bf16_tie(v)) v = x * (1.0f / (1.0f + (float)sycl::exp((double)-x))) * up; o[e] = rad_f32_to_bf16(v); } *(V8*)((uint16_t*)y.base + r * y.pitch + (int64_t)c8 * 8) = o; }); }); } const size_t wg = 256, groups = (size_t)((total + 255) / 256); return submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) { const int64_t g = (int64_t)it.get_global_id(0); if (g >= total) return; const int64_t r = g / n, i = g % n; const float x = 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); /* a bf16 result from a float exp, libref's double chain again only near a rounding * tie (near_bf16_tie): the same bf16 */ float v = x * sigmoid_fexp(x) * up; if (!bf16_out || near_bf16_tie(v)) v = x * (1.0f / (1.0f + (float)sycl::exp((double)-x))) * up; rad_store_f32(y.base, y.dtype, r * y.pitch + i, v); }); }); } /* ------------------------------------------------------------------ quant_act_i8 */ /* libref's quant_act_i8: one scale a row, max(amax, 1e-8) / 127; codes x * (1 / scale) stored RNE * and saturated, at the step position i8_step_pos(i) (bits 2 and 3 of the column swapped, the * order libr4d's int8 WMMA reads an A fragment); `asum` (optional) the code sums per `group` * columns, group-major [n/group][Mpad], Mpad = ceil(M/16)*16, rows past M untouched. */ int quant_act_i8(const RadArgs* a, RadStream st) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *Q = &a->t[1], *S = &a->t[2]; const RadTensor* AS = rad_arg_in(a, 3); const int64_t n = rad_args_geti_or(a, "n", 0); if (n <= 0 || n % 16) return RAD_E_SHAPE; if (Q->dtype != RAD_I8) return RAD_E_DTYPE; if (Q->rank && Q->stride[Q->rank - 1] != 1) return RAD_E_STRIDE; Rows x, qv, sv; if (int rc = rows_view(X, n, &x, "quant_act_i8 x"); rc < 0) return rc; const int64_t rows = x.rows; if (rows <= 0 || rad_tensor_numel(Q) < rows * n || rad_tensor_numel(S) < rows) return RAD_E_SHAPE; if (int rc = rows_view(Q, n, &qv, "quant_act_i8 q"); rc < 0) return rc; if (int rc = rows_view(S, 1, &sv, "quant_act_i8 scale"); rc < 0) return rc; const int64_t gsz = AS ? rad_args_geti_or(a, "group", 0) : 0; const int64_t mpad = (rows + 15) / 16 * 16; if (AS && (gsz <= 0 || n % gsz || rad_tensor_numel(AS) < n / gsz * mpad)) return RAD_E_SHAPE; const bool has_as = AS != nullptr; char* asb = AS ? (char*)AS->data : nullptr; const uint32_t asdt = AS ? AS->dtype : 0; if (AS && !rad_tensor_is_contiguous(AS)) return refuse("quant_act_i8: asum not contiguous"); sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const size_t wg = 256; return submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)rows * wg, wg}, [=](sycl::nd_item<1> it) { const int64_t r = (int64_t)it.get_group(0); const int t = (int)it.get_local_id(0); float amax = 0.0f; for (int64_t i = t; i < n; i += (int64_t)wg) amax = sycl::fmax(amax, sycl::fabs(rad_load_f32(x.base, x.dtype, r * x.pitch + i))); amax = sycl::reduce_over_group(it.get_group(), amax, sycl::maximum()); const float scale = sycl::fmax(amax, 1e-8f) / 127.0f; const float inv = 1.0f / scale; int8_t* qr = (int8_t*)qv.base + r * qv.pitch; for (int64_t i = t; i < n; i += (int64_t)wg) { const int64_t pos = (i & ~(int64_t)12) | ((i & 4) << 1) | ((i & 8) >> 1); rad_store_f32(qr, RAD_I8, pos, rad_load_f32(x.base, x.dtype, r * x.pitch + i) * inv); } if (t == 0) rad_store_f32(sv.base, sv.dtype, r * sv.pitch, scale); if (!has_as) return; sycl::group_barrier(it.get_group()); for (int64_t gi = t; gi < n / gsz; gi += (int64_t)wg) { int64_t sum = 0; for (int64_t i = gi * gsz; i < (gi + 1) * gsz; ++i) sum += qr[(i & ~(int64_t)12) | ((i & 4) << 1) | ((i & 8) >> 1)]; rad_store_f32(asb, asdt, gi * mpad + r, (float)sum); } }); }); } } // namespace xe2