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_gemm_zp.cpp
T
pascallinxweilerandClaude Opus 5.5 55a350f0c6 libxe2: the DFlash2 path fast -- exact draft head, DPAS verify GEMV, parallel rerank
- gemm_nt_q over the zero-point grids at M <= 16 (the drafter's 2-bit vocabulary head, N=248320):
  a sub-group a column, the group sums exact integers in f32, libref's group terms added in group
  order through lane broadcasts -- bit-identical to the exact kernel on the live head (checked in
  the engine: 0 differing bytes of 3.5 MB, every round). 252 ms -> well under 1 ms a call.
- m2xfp4 at 2 <= M <= 16 (the verify width) on XMX: a lane a column decodes its codes a 64-byte line
  at a time into its sub-group's VNNI slice of local memory (subnormal-bit fp16 pairs times
  (1 + k/4) * 2^(e - e_max + 14)), eight K16 DPAS a step against the permuted fp16 activation,
  K split for narrow N, partials added in order. On the vector ALUs M = 8 cost five times M = 1;
  gate_up at M = 8 1159 -> ~490 us. rad-kbench on the 27B: 50/50, rel_l2 ~8.5e-4 (tol 4e-2).
- logit_rerank: a work-group a row, a sub-group a candidate along K, libref's double sum as a float
  pair (two-product, two-sum, a fixed lane tree), libref's selection; 136 ms -> negligible a call.
- the gated delta net's gate, beta and decay (libref's double exp / log1p) once a (token, head)
  in a prepass instead of once a column block; still bit-identical (10/10 at rel_l2 0).
- profile_decode.sh: KEEP=DIR keeps the per-geometry tables.

27B on the B65, greedy: 12.1 tok/s plain, 13.2 tok/s with the drafter (device time a token
217 -> 76 ms under speculation). The drafter's text now departs from plain decoding at a
near-tie (byte 246 of 256 tokens): the verify forward runs the M = 8 DPAS path and plain decoding
the M = 1 GEMV, whose roundings differ (~1e-3); with the exact kernels the two were identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-24 04:37:16 +02:00

337 lines
16 KiB
C++

/* xe2_gemm_zp.cpp -- gemm_nt_q over the zero-point grids whose activation is quant_act_i8's
* (w2a8, w4a8_asym): the DSpark drafter's 2-bit vocabulary head. Correctness first: libref's
* gemm_zp (ref_gemm.cpp) per output --
*
* per group g of K: is = sum over ascending k of a[k] * code[n][k] (exact integers)
* sub = (float)is - (float)zero[n][g] * a_sum[g][m]
* acc = acc + (sub * a_scale[m]) * scale[n][g]
*
* -- with `a` read back from quant_act_i8's step order into column order, as libref does.
*
* `b_scale` reaches the kernel in libref's joined form (abi/rad_planes.h): a header, an entry per
* plane, then the "scale" and "zero" planes. The layout hook below is libref's
* (ref_layout_gemm_q), so both libraries ask for the same stored bytes and the builder can resolve
* either for a band. The header lives in device memory, so the kernel finds its planes itself: a
* launch must not read device memory from the host.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_planes.h"
#include <cstring>
namespace xe2 {
namespace {
struct ZpGrid {
const char* name;
uint32_t codes;
bool i8_row; /* the activation is quant_act_i8's (served here) */
};
const ZpGrid* zp_grid(const char* dtype) {
static const ZpGrid kGrids[] = {
{ "w2a8", RAD_U2, true }, { "w4a8_asym", RAD_U4, true },
{ "w4a16_asym", RAD_U4, false }, { "w5a16", RAD_U5, false },
{ "w4a8i8_asym", RAD_U4, false }, { "w5a8i8", RAD_U5, false },
};
if (!dtype) return nullptr;
for (const ZpGrid& g : kGrids)
if (std::strcmp(g.name, dtype) == 0) return &g;
return nullptr;
}
bool zero_dt(uint32_t dt) { return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5; }
bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, const char* r1) {
if (!enc || !sel || n != 2) return false;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
}
/* One plane of the joined operand, found on the device. */
struct DPlane {
const char* p = nullptr;
uint32_t dt = 0;
int64_t row_bytes = 0;
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
};
inline bool role_is(const char* role, const char* want) {
for (int i = 0; i < RAD_ENC_STR; ++i) {
if (role[i] != want[i]) return false;
if (!want[i]) return true;
}
return true;
}
inline DPlane find_plane(const char* base, const char* role) {
DPlane v;
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
if (h->magic != RAD_PLANES_MAGIC) return v;
const RadPlanesEntry* e = (const RadPlanesEntry*)(base + sizeof(RadPlanesHeader));
for (int i = 0; i < h->n_planes && i < RAD_ENC_MAX_PLANES; ++i)
if (role_is(e[i].role, role)) {
v.p = base + e[i].offset;
v.dt = e[i].dtype;
v.row_bytes = e[i].row_bytes;
return v;
}
return v;
}
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];
}
} // namespace
/* ------------------------------------------------------------------ the layout hooks */
/* libref's ref_layout_gemm_q, line for line: `b_scale` (operand 3) joined as "scale" and "zero",
* one each per (row, `group` of K), over codes of the grid's width. */
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) {
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE;
const RadEncPlane& c = enc->plane[0];
const RadEncPlane& s = enc->plane[sel[0]];
const RadEncPlane& z = enc->plane[sel[1]];
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes ||
c.block[0] != 1 || c.block[1] != 1)
return RAD_E_DTYPE;
if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group ||
z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group)
return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
RadLayout lay{};
const int st = gemm_zp_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
int gemm_zp_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
int n) {
RadLayout lay{};
const int st = gemm_zp_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
/* ------------------------------------------------------------------ the launch */
int gemm_nt_q_zp(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;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor* AS = rad_arg_in(a, 1);
const RadTensor* BS = rad_arg_in(a, 3);
const RadTensor* ASUM = rad_arg_in(a, 5);
if (rad_arg_in(a, 6)) return refuse("gemm_nt_q (zero-point): b_ref is mxfp4's");
const ZpGrid* zg = zp_grid(rad_args_gets_or(a, "dtype", nullptr));
if (!zg || !zg->i8_row)
return refuse("gemm_nt_q (zero-point): dtype '%s' is not served (w2a8, w4a8_asym are)",
rad_args_gets_or(a, "dtype", ""));
if (rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
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);
const int64_t group = rad_args_geti_or(a, "group", 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;
if (!BS) return RAD_E_INVAL;
if (B->dtype != zg->codes) return RAD_E_DTYPE;
if (group <= 0 || K % group || K % 16) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE;
if (A->dtype != RAD_I8) return RAD_E_DTYPE;
if (A->rank && A->stride[A->rank - 1] != 1) return RAD_E_STRIDE;
const int64_t G = K / group, mpad = (M + 15) / 16 * 16;
if (!AS || rad_tensor_numel(AS) < M) return RAD_E_INVAL;
if (!ASUM || rad_tensor_numel(ASUM) < G * mpad) return RAD_E_INVAL;
const int64_t brow = rad_dtype_bytes(B->dtype, K);
const int cbits = rad_dtype_bits(B->dtype);
const int64_t ars = row_stride(A, K);
const int64_t sa_rs = row_stride(AS, 1);
const int64_t asum_s = ASUM->rank ? ASUM->stride[ASUM->rank - 1] : 1;
const int64_t ys_r = row_stride(Y, N), ys_c = Y->rank ? Y->stride[Y->rank - 1] : 1;
const char *ab = (const char*)A->data, *bb = (const char*)B->data, *bsb = (const char*)BS->data;
const char *sab = (const char*)AS->data, *sumb = (const char*)ASUM->data;
const uint32_t sadt = AS->dtype, sumdt = ASUM->dtype, ydt = Y->dtype;
char* yb = (char*)Y->data;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const size_t wn = 64;
const size_t nn = (size_t)((N + (int64_t)wn - 1) / (int64_t)wn) * wn;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)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 >= N) return;
const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero");
if (!sc.p || !zp.p) return; /* not a joined b_scale: the layout hook guarantees one */
const uint8_t* crow = (const uint8_t*)bb + n * brow;
const int8_t* ar = (const int8_t*)ab + m * ars;
const float sa = rad_load_f32(sab, sadt, m * sa_rs);
float acc = 0.0f;
for (int64_t g = 0; g < G; ++g) {
const float sb = sc.at(n, g);
const int32_t z = (int32_t)zp.at(n, g);
int64_t is = 0;
for (int64_t k = g * group; k < (g + 1) * group; ++k) {
const int64_t pos = (k & ~(int64_t)12) | ((k & 4) << 1) | ((k & 8) >> 1);
is += (int64_t)ar[pos] * (int32_t)rad_load_bits(crow, cbits, k);
}
const float sub = (float)is - (float)z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s);
acc += sub * sa * sb;
}
rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc);
});
});
}
} // namespace xe2
/* ------------------------------------------------------------------ the fast form */
/* The same products and order, spread: a 16-lane sub-group an output column, lane l the groups
* l, l + 16, ... Within a group the sum of a * code is an exact integer (|a| <= 127, code <= 15,
* a group of <= 512: under 2^24), formed in f32 in any order; each group's term
* ((is - zero * a_sum) * a_scale) * scale is libref's; and the terms are added in group order by
* every lane from the lanes' registers (select_from_group), libref's chain. So the result is
* libref's bit for bit, at the cost of a read of the weight rather than one per output row. For
* the DFlash2 drafter's 2-bit head: N = 248320, 252 ms a call in the per-output form. */
namespace xe2 {
namespace {
constexpr int kZpMaxM = 16;
constexpr int kZpMaxPer = 4; /* groups a lane: G <= 64 */
template <int MM>
int zp_gemv(sycl::queue& q, const int8_t* ab, int64_t ars, const char* sab, uint32_t sadt, int64_t sa_rs,
const char* sumb, uint32_t sumdt, int64_t asum_s, int64_t mpad, const uint8_t* bb, int64_t brow,
int cbits, const char* bsb, char* yb, uint32_t ydt, int64_t ys_r, int64_t ys_c, int64_t N,
int64_t K, int64_t group, int mm) {
const int64_t G = K / group;
const size_t groups = (size_t)((N + 15) / 16);
return submit([&] {
syclex::nd_launch(q, sycl::nd_range<1>{groups * 256, 256},
[=](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;
const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero");
if (!sc.p || !zp.p) return;
const int lane = (int)sg.get_local_linear_id();
const uint8_t* crow = bb + n * brow;
float term[MM][kZpMaxPer];
for (int m = 0; m < MM; ++m)
for (int i = 0; i < kZpMaxPer; ++i) term[m][i] = 0.0f;
for (int i = 0; i < kZpMaxPer; ++i) {
const int64_t g = lane + (int64_t)i * kSub;
if (g >= G) break;
float is[MM];
for (int m = 0; m < MM; ++m) is[m] = 0.0f;
for (int64_t k0 = g * group; k0 < (g + 1) * group; k0 += 16) {
float cf[16];
for (int j = 0; j < 16; ++j) cf[j] = (float)rad_load_bits(crow, cbits, k0 + j);
for (int m = 0; m < MM; ++m) {
if (m >= mm) break;
/* the step order: logical column j of the step sits at byte
* (j & ~12) | ((j & 4) << 1) | ((j & 8) >> 1) */
const sycl::vec<int8_t, 16> av = *(const sycl::vec<int8_t, 16>*)(ab + m * ars + k0);
float p = 0.0f;
for (int j = 0; j < 16; ++j) {
const int pos = (j & ~12) | ((j & 4) << 1) | ((j & 8) >> 1);
p += (float)av[pos] * cf[j];
}
is[m] += p;
}
}
const float sb = sc.at(n, g);
const float z = (float)(int32_t)zp.at(n, g);
for (int m = 0; m < MM; ++m) {
if (m >= mm) break;
const float sa = rad_load_f32(sab, sadt, m * sa_rs);
const float sub = is[m] - z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s);
term[m][i] = sub * sa * sb;
}
}
for (int m = 0; m < MM; ++m) {
if (m >= mm) break;
float acc = 0.0f;
for (int i = 0; i < kZpMaxPer; ++i)
for (int l = 0; l < kSub; ++l) {
const int64_t g = (int64_t)i * kSub + l;
if (g < G) acc += sycl::select_from_group(sg, term[m][i], l);
}
if (lane == 0) rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc);
}
});
});
}
} // namespace
int gemm_nt_q_zp_gemv(const RadArgs* a, RadStream st) {
if (exact_only()) return gemm_nt_q_zp(a, st);
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor* AS = rad_arg_in(a, 1);
const RadTensor* BS = rad_arg_in(a, 3);
const RadTensor* ASUM = rad_arg_in(a, 5);
const ZpGrid* zg = zp_grid(rad_args_gets_or(a, "dtype", nullptr));
if (!zg || !zg->i8_row || rad_arg_in(a, 6) || rad_args_geti_or(a, "pb1", 0) > 0 ||
rad_args_geti_or(a, "pb2", 0) > 0)
return gemm_nt_q_zp(a, st);
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);
const int64_t group = rad_args_geti_or(a, "group", 0);
if (K <= 0 || N <= 0 || group <= 0 || group % 16 || group > 512 || K % group) return gemm_nt_q_zp(a, st);
const int64_t M = rad_tensor_numel(Y) / N, G = K / group;
if (M < 1 || M > kZpMaxM || G > kZpMaxPer * kSub || !BS || !AS || !ASUM || A->dtype != RAD_I8 ||
B->dtype != zg->codes || !rad_tensor_is_contiguous(B) || (A->rank && A->stride[A->rank - 1] != 1))
return gemm_nt_q_zp(a, st);
const int64_t ars = row_stride(A, K);
if (ars % 16 || !rad_ptr_aligned(A->data, 16)) return gemm_nt_q_zp(a, st);
const int64_t mpad = (M + 15) / 16 * 16;
if (rad_tensor_numel(AS) < M || rad_tensor_numel(ASUM) < G * mpad || rad_tensor_numel(A) < M * K ||
rad_tensor_numel(B) < N * K)
return RAD_E_SHAPE;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t brow = rad_dtype_bytes(B->dtype, K);
const int cbits = rad_dtype_bits(B->dtype);
const int64_t sa_rs = row_stride(AS, 1);
const int64_t asum_s = ASUM->rank ? ASUM->stride[ASUM->rank - 1] : 1;
const int64_t ys_r = row_stride(Y, N), ys_c = Y->rank ? Y->stride[Y->rank - 1] : 1;
auto go = [&](auto tag) {
constexpr int MM = decltype(tag)::value;
return zp_gemv<MM>(*q, (const int8_t*)A->data, ars, (const char*)AS->data, AS->dtype, sa_rs,
(const char*)ASUM->data, ASUM->dtype, asum_s, mpad, (const uint8_t*)B->data,
brow, cbits, (const char*)BS->data, (char*)Y->data, Y->dtype, ys_r, ys_c, N, K,
group, (int)M);
};
if (M == 1) return go(std::integral_constant<int, 1>{});
if (M <= 8) return go(std::integral_constant<int, 8>{});
return go(std::integral_constant<int, 16>{});
}
} // namespace xe2