libxe2: Phase 4 step 1 -- a bandwidth-bound decode GEMV and an ordered sum from local memory

The profile of a MiniCPM5-2B decode step on the B65 (232.8 ms) was 79% gemm_nt, reading its
weights at 62 GB/s, and 13% the norms' serial sum of squares.

- xe2_gemm_nt_gemv / xe2_logits_gemm_gemv (priority 10, M <= 16, bf16): a sub-group an output
  column, 16-byte coalesced weight loads, a tree reduction. Not libref's order: rad-kbench passes
  them at the gemm tolerance (fixture 361/361, MiniCPM5 180/180, worst rel_l2 1.6e-4), and
  XE2_EXACT=1 sends every launch to the exact kernel for bisecting.
- The norms form their squares in parallel into local memory and add them in index order: still
  bit-identical to libref.

Decode 4.2 -> 35.5 tok/s. Against a libref-only host build, over 1914 positions of the repo's docs
with every position through the GEMV: KL mean 5.9e-4, p99 3.5e-3, top-1 98.5% -- libavx's own
distance from libref is 5.7e-4 / 3.0e-3 / 98.6%. The exact path scores KL 0, top-1 100%.

docs/SYCL_PROGRESS.md: the profile, the KL bound (D13), and the user's decision to use the bf16
container for Milestone B instead of the fp8 one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
This commit is contained in:
pascallinxweilerandClaude Opus 5.5 committed 2026-10-23 19:48:40 +02:00
1 parent 43d84111c2
commit a869226800
5 files changed
+196 -9

No files matched your search

+33 -2
View File
@@ -217,6 +217,10 @@ Planned use: Milestone A = `minicpm5-2b-bf16.rad` (blocked, item 1); Milestone B
28.5 GB/s H2D / D2H, O_DIRECT fails; registered `posix_memalign` 28.4 / 28.4 GB/s, O_DIRECT ok, 28.5 GB/s H2D / D2H, O_DIRECT fails; registered `posix_memalign` 28.4 / 28.4 GB/s, O_DIRECT ok,
kernel read/write ok (system USM); unregistered 21.0 / 18.2 GB/s. The backend keeps a registry kernel read/write ok (system USM); unregistered 21.0 / 18.2 GB/s. The backend keeps a registry
of those ranges, since the runtime does not know them. of those ranges, since the runtime does not know them.
- D13 (2026-10-23): fast kernels may change libref's reduction order. They are held to rad-kbench's
per-op tolerances (libr4d's standard) and, end to end, to the KL bound measured above against the
libref host build -- no worse than libavx's distance from libref. Every fast row keeps its exact
twin, selectable with `XE2_EXACT=1`.
- D12 (2026-10-23): every libxe2 op is checked twice: rad-kbench (dense operands, fixture and the - D12 (2026-10-23): every libxe2 op is checked twice: rad-kbench (dense operands, fixture and the
real container) and the engine's op oracle on the operands the engine hands it real container) and the engine's op oracle on the operands the engine hands it
(`RADIANCE_OP_ORACLE`), at tolerance ~0 where the kernel reproduces libref's order. Transcendentals (`RADIANCE_OP_ORACLE`), at tolerance ~0 where the kernel reproduces libref's order. Transcendentals
@@ -352,10 +356,37 @@ backend from the prefix with no environment). `tests/oot_plugins.sh` rebuilds li
with icpx when `RAD_OOT_ICPX` is set (the SYCL build's registration sets it) and hides Level Zero with icpx when `RAD_OOT_ICPX` is set (the SYCL build's registration sets it) and hides Level Zero
GPUs from its listing and replay. `ctest -R oot_plugins` in build-sycl: **passed** (370 s). GPUs from its listing and replay. `ctest -R oot_plugins` in build-sycl: **passed** (370 s).
## Phase 4, step 1 (2026-10-23)
Profile (`RADIANCE_SYCL_TIMING=1 --profile-ops`, MiniCPM5 bf16 decode, correctness-first kernels):
232.8 ms/step; `gemm_nt` 79.2% (gate_up, 50 MB of bf16, 810 us a call = 62 GB/s on a ~600 GB/s
card), `rmsnorm_quant_fp8` 13.0% (the serial sum of squares, 360 us a call), `logits_gemm` 3.4%,
the rest under 1.5% each.
- `rmsnorm*`: the squares are formed in parallel into local memory, work-item 0 adds them in index
order -- the same additions, still bit-identical to libref (kbench rel_l2 0).
- `xe2_gemm_nt_gemv`, `xe2_logits_gemm_gemv` (priority 10, `M <= 16`, bf16): a sub-group an output
column, 16-byte coalesced weight loads, a tree reduction. Not libref's order. kbench: fixture
361/361, MiniCPM5 180/180 (worst rel_l2 1.6e-4, tol 8e-3). `XE2_EXACT=1` sends them to the exact
kernels.
- **Decode: 4.2 -> 35.5 tok/s** (128-token greedy completions, speculation off).
- **KL bound (D13)**, `--kld-record` with the libref host build over 12 passages of the repo's docs
(1914 positions), scored with `--max-num-batched-tokens 16` so the GEMV computes every position:
| path | KL mean | median | p99 | p99.9 | max | top-1 | PPL ratio |
|---|---|---|---|---|---|---|---|
| B65, `XE2_EXACT=1` | 0 | 0 | 0 | 0 | 0 | 100% | 1.0000 |
| B65, fast GEMV | 5.9e-4 | 4.1e-4 | 3.5e-3 | 9.4e-3 | 0.045 | 98.54% | 0.9989 |
| host, libavx (reference point) | 5.7e-4 | 4.2e-4 | 3.0e-3 | 6.4e-3 | 0.016 | 98.59% | 1.0004 |
The B65's fast path is as far from libref as the production CPU library is. Greedy against libref:
7/8 prompts identical, the eighth diverging at token 18 on a 0.008-nat near-tie.
## Next steps ## Next steps
1. Milestone B, part 2: `minicpm5-2b-fp8.rad` (**not in the library; asked by webhook**). Its fp8 trunk 1. ~~Milestone B, part 2: `minicpm5-2b-fp8.rad`~~ **Dropped by the user (2026-10-23): "instead of the
uses the ops part 1 added (fp8a8 GEMMs), so it should need no new kernel. fp8 use the one you are already using so the bf16".** Milestone B's MiniCPM5 half is the bf16
container with its DSpark drafter, done above.
2. A 19-22 GiB container: none is in the library as `.rad` (the two Swift-1.5 Qwen3.8-27B int4 2. A 19-22 GiB container: none is in the library as `.rad` (the two Swift-1.5 Qwen3.8-27B int4
checkpoints there are safetensors, not containers). Asking the user which to use / for a container. checkpoints there are safetensors, not containers). Asking the user which to use / for a container.
3. Phase 4 can start now that Milestone A is correct: XMX GEMMs and a split-KV attention, each checked 3. Phase 4 can start now that Milestone A is correct: XMX GEMMs and a split-KV attention, each checked
+122
View File
@@ -0,0 +1,122 @@
/* xe2_gemv.cpp -- Phase 4's first fast kernel: the skinny bf16 GEMM a decode step is made of
* (gemm_nt and logits_gemm at M <= 16), bandwidth-bound by construction.
*
* One 16-lane sub-group an output column: each lane reads 8 bf16 of the weight row at a time (one
* 16-byte load, the sub-group 256 contiguous bytes), multiplies them against the same 8 columns of
* every activation row, and keeps one partial sum a row; the sub-group then reduces the partials and
* lane 0 stores. A weight byte is read once per step whatever M is, so the cost is the weight's
* bytes over the card's bandwidth.
*
* Not libref's order: each lane sums its own strided slice and the slices are reduced as a tree, so
* the result differs from the reference's ascending sum in the last bits. It is checked against
* libref at rad-kbench's gemm tolerance, the standard libr4d's split-K WMMA GEMMs are held to, and
* by the engine oracle at that tolerance. XE2_EXACT=1 sends every launch to the correctness-first
* kernel instead (xe2_gemm.cpp), for bisecting a difference.
*
* Takes: bf16 activation and weight, rows 16-byte aligned with K a multiple of 8 and a unit column
* stride; anything else falls back to the correctness-first kernel, which serves every layout.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cstdlib>
namespace xe2 {
bool exact_only() {
static const bool on = [] {
const char* e = std::getenv("XE2_EXACT");
return e && e[0] == '1';
}();
return on;
}
namespace {
constexpr int kMaxM = 16;
constexpr size_t kWg = 256; /* 16 sub-groups, 16 output columns a work-group */
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];
}
inline float bf(uint16_t h) { return rad_bf16_to_f32(h); }
/* Whether the fast kernel can read this launch's operands; otherwise the exact one runs. */
bool gemv_ok(const RadTensor* A, const RadTensor* B, const RadTensor* Y, int64_t M, int64_t K,
int64_t ars, int64_t brs) {
if (A->dtype != RAD_BF16 || B->dtype != RAD_BF16) return false;
if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false;
if (M < 1 || M > kMaxM || K % 8) return false;
if ((A->rank >= 2 && A->stride[A->rank - 1] != 1) || (B->rank >= 2 && B->stride[B->rank - 1] != 1))
return false;
if (ars % 8 || brs % 8) return false;
return rad_ptr_aligned(A->data, 16) && rad_ptr_aligned(B->data, 16);
}
int gemv(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, int (*exact)(const RadArgs*, RadStream)) {
if (exact_only()) return exact(a, st);
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, K), brs = row_stride(B, K);
if (!gemv_ok(A, B, Y, M, K, ars, brs)) return exact(a, st);
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const uint16_t* ab = (const uint16_t*)A->data;
const uint16_t* bb = (const uint16_t*)B->data;
char* yb = (char*)Y->data;
const uint32_t ydt = Y->dtype;
const int mm = (int)M;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t groups = (size_t)((N + 15) / 16);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t n = (int64_t)it.get_group(0) * 16 + (int64_t)sg.get_group_linear_id();
if (n >= N) return; /* uniform across the sub-group */
const int lane = (int)sg.get_local_linear_id();
float acc[kMaxM];
for (int r = 0; r < kMaxM; ++r) acc[r] = 0.0f;
const uint16_t* wrow = bb + n * brs;
for (int64_t k = (int64_t)lane * 8; k < K; k += 8 * kSub) {
const sycl::vec<uint16_t, 8> w = *(const sycl::vec<uint16_t, 8>*)(wrow + k);
float wf[8];
for (int j = 0; j < 8; ++j) wf[j] = bf(w[j]);
for (int r = 0; r < kMaxM; ++r) {
if (r >= mm) break;
const sycl::vec<uint16_t, 8> x = *(const sycl::vec<uint16_t, 8>*)(ab + r * ars + k);
float s = 0.0f;
for (int j = 0; j < 8; ++j) s += bf(x[j]) * wf[j];
acc[r] += s;
}
}
for (int r = 0; r < kMaxM; ++r) {
if (r >= mm) break;
const float v = sycl::reduce_over_group(sg, acc[r], sycl::plus<float>());
if (lane == 0) rad_store_f32(yb, ydt, r * yrs + n * ycs, v);
}
});
});
}
} // namespace
int gemm_nt_gemv(const RadArgs* a, RadStream s) { return gemv(a, s, "N", "K", gemm_nt); }
int logits_gemm_gemv(const RadArgs* a, RadStream s) {
return gemv(a, s, "n_vocab", "n_embd", logits_gemm);
}
} // namespace xe2
+21 -7
View File
@@ -35,17 +35,31 @@ constexpr size_t kWg = 256; /* work-items a row */
* such code in some of MiniCPM5-2B's 42 layers, enough to flip a greedy near-tie later. */ * 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)); } 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, computed by work-item /* The sum of src(i)^2 over i < n in ascending order, f32, as libref sums it, returned to every
* 0 and returned to every work-item of the group. */ * 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> template <class F>
inline float ordered_sumsq(const sycl::nd_item<1>& it, const F& src, int64_t n) { 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; float ss = 0.0f;
if (it.get_local_id(0) == 0) for (int64_t c0 = 0; c0 < n; c0 += kSqChunk) {
for (int64_t i = 0; i < n; ++i) { const int64_t cn = sycl::min(kSqChunk, n - c0);
const float v = src(i); for (int64_t i = t; i < cn; i += wg) {
ss += v * v; const float v = src(c0 + i);
sq[i] = v * v;
} }
return sycl::group_broadcast(it.get_group(), ss, 0); sycl::group_barrier(grp);
if (t == 0)
for (int64_t i = 0; 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. /* One group's codes and scale, by the sub-group `sg` over values v(k0 + i), i < len.
+5
View File
@@ -45,6 +45,11 @@ int row_topk(const RadArgs* a, RadStream s);
int dflash_select(const RadArgs* a, RadStream s); int dflash_select(const RadArgs* a, RadStream s);
int gemm_nt_q_zp(const RadArgs* a, RadStream s); int gemm_nt_q_zp(const RadArgs* a, RadStream s);
/* Phase 4's fast kernels (xe2_gemv.cpp). XE2_EXACT=1 sends them to the correctness-first ones. */
bool exact_only();
int gemm_nt_gemv(const RadArgs* a, RadStream s);
int logits_gemm_gemv(const RadArgs* a, RadStream s);
int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out); const RadTensor* planes, int n, RadLayout* out);
int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
+15
View File
@@ -14,6 +14,8 @@ namespace {
const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj") }; const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj") };
/* The GEMMs here read float weights only; a quantised dtype key is gemm_nt_q's. */ /* The GEMMs here read float weights only; a quantised dtype key is gemm_nt_q's. */
const RadConstraint cFloatDtype[] = { RAD_CIN("dtype", "bf16 f16 fp16 f32 fp32") }; const RadConstraint cFloatDtype[] = { RAD_CIN("dtype", "bf16 f16 fp16 f32 fp32") };
/* The decode band of the skinny bf16 GEMV (xe2_gemv.cpp). */
const RadConstraint cGemvBf16[] = { RAD_CIN("dtype", "bf16"), RAD_CLE("M", 16) };
/* The block-scaled pairs xe2_gemm_q.cpp serves; the zero-point grids (w2a8, w4*_asym) and mxfp4 are /* The block-scaled pairs xe2_gemm_q.cpp serves; the zero-point grids (w2a8, w4*_asym) and mxfp4 are
* other rows. */ * other rows. */
const RadConstraint cFp8Dtype[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16") }; const RadConstraint cFp8Dtype[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16") };
@@ -77,6 +79,19 @@ const RadKernelInfo kKernels[] = {
.dtypes = "any float or integer pair", .dtypes = "any float or integer pair",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::cast }, .domain = RAD_DOMAIN_DEVICE, .launch = xe2::cast },
{ .name = "xe2_gemm_nt_gemv", .op = "gemm_nt", .family = "gemm",
.computes = "skinny Y = A B^T for decode: a sub-group an output column, 16-byte coalesced "
"weight loads, a tree reduction (not libref's order; checked at the gemm "
"tolerance). XE2_EXACT=1 runs xe2_gemm_nt_ref instead",
.shape = "M <= 16; bf16 rows 16-byte aligned, K a multiple of 8 (else the exact kernel)",
.dtypes = "bf16 A and W, bf16 or f32 Y, f32 accumulate",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .constraints = cGemvBf16, .n_constraints = 2,
.launch = xe2::gemm_nt_gemv },
{ .name = "xe2_logits_gemm_gemv", .op = "logits_gemm", .family = "gemm",
.computes = "logits at decode, as xe2_gemm_nt_gemv", .shape = "M <= 16",
.dtypes = "bf16 x and head, f32 logits",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .constraints = cGemvBf16, .n_constraints = 2,
.launch = xe2::logits_gemm_gemv },
{ .name = "xe2_gemm_nt_ref", .op = "gemm_nt", .family = "gemm", { .name = "xe2_gemm_nt_ref", .op = "gemm_nt", .family = "gemm",
.computes = "Y = A B^T, one work-item an output, f32 over ascending k (libref's order); the " .computes = "Y = A B^T, one work-item an output, f32 over ascending k (libref's order); the "
"correctness-first form, not the fast one", "correctness-first form, not the fast one",