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_dflash.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

274 lines
13 KiB
C++

/* xe2_dflash.cpp -- the DFlash2 drafter's own ops: dflash_conv and logit_rerank.
* Correctness first, libref's arithmetic (ref_qsa.cpp, ref_moe.cpp):
*
* dflash_conv: o[t][h] = sum over taps j (in order, the first term not added to zero) of
* (bias[j][h] + delta[t][j][h / group]) * x[t - j][h], a tap skipped when it would reach back past
* the start of t's block of `block_size` rows.
* logit_rerank: R candidate ids a row rescored against the head, each a dot product summed in
* double in k order, then emitted descending by score, ties to the lower id, pads (an id outside
* this shard, or -1) last as id -1 and -inf -- row_topk's order. The head is plain or, in the
* joined row, codes with a scale plane decoded element by element (code * scale).
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_planes.h"
#include <cmath>
#include <cstring>
namespace xe2 {
namespace {
int64_t laststride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
struct HPlane {
const char* p = nullptr;
uint32_t dt = 0;
int64_t row_bytes = 0, br = 0, bc = 0;
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
float cover(int64_t r, int64_t c) const { return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0); }
};
inline bool role_is(const char* r, const char* want) {
for (int i = 0; i < RAD_ENC_STR; ++i) {
if (r[i] != want[i]) return false;
if (!want[i]) return true;
}
return true;
}
inline HPlane hplane(const char* base, const char* role) {
HPlane 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;
v.br = e[i].block[0];
v.bc = e[i].block[1];
return v;
}
return v;
}
int rerank(const RadArgs* a, RadStream st, bool joined) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *IN = &a->t[2], *IDX = &a->t[3], *VAL = &a->t[4];
const RadTensor* PAIRS = (a->n_t > 5 && a->t[5].data) ? &a->t[5] : nullptr;
const int64_t R = rad_args_geti_or(a, "R", 1), K = rad_args_geti_or(a, "n_embd", 0);
const int64_t NV = rad_args_geti_or(a, "n_vocab", 0), voff = rad_args_geti_or(a, "vocab_off", 0);
if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(X) / K;
if (M <= 0 || rad_tensor_numel(IN) < M * R) return RAD_E_SHAPE;
if (rad_tensor_numel(IDX) < M * R || rad_tensor_numel(VAL) < M * R) return RAD_E_SHAPE;
if (!joined && rad_tensor_numel(W) < NV * K) return RAD_E_SHAPE;
if (PAIRS && (PAIRS->dtype != RAD_F32 || rad_tensor_numel(PAIRS) < M * R * 2)) return RAD_E_SHAPE;
Rows x, in, idx, val, w;
if (int rc = rows_view(X, K, &x, "logit_rerank x"); rc < 0) return rc;
if (int rc = rows_view(IN, R, &in, "logit_rerank in"); rc < 0) return rc;
if (int rc = rows_view(IDX, R, &idx, "logit_rerank idx"); rc < 0) return rc;
if (int rc = rows_view(VAL, R, &val, "logit_rerank val"); rc < 0) return rc;
if (!joined)
if (int rc = rows_view(W, K, &w, "logit_rerank head"); rc < 0) return rc;
const char* wb = (const char*)W->data;
float* pairs = PAIRS ? (float*)PAIRS->data : nullptr;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
if (!exact_only() && R <= 32) {
/* The fast form: a work-group a row, sub-group r candidate r, its lanes along K. libref sums
* in double; here each product is split exactly (two-product) and summed as a float pair
* (two-sum), the lanes' pairs combined in a fixed tree: ~48 significant bits, rounded once,
* so the score is libref's unless its exact value sits within ~2^-24 ulp of an f32
* rounding boundary -- a fast kernel, held to the tolerance (and the drafter's acceptance
* changes only through such ties). The selection is libref's, one work-item a row. */
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> scl(sycl::range<1>((size_t)R), h);
sycl::local_accessor<int32_t, 1> idl(sycl::range<1>((size_t)R), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * (size_t)R * kSub, (size_t)R * kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t m = (int64_t)it.get_group(0);
const sycl::sub_group sg = it.get_sub_group();
const int64_t r = (int64_t)sg.get_group_linear_id();
const int lane = (int)sg.get_local_linear_id();
HPlane cp, sp;
if (joined) {
cp = hplane(wb, "codes");
sp = hplane(wb, "scale");
if (!cp.p || !sp.p) return;
}
const int64_t g = ld_index(in.dtype, in.base, m * in.pitch + r);
const int64_t local = g - voff;
const bool pad = g < 0 || local < 0 || local >= NV; /* uniform in the sub-group */
auto two_sum = [](float a, float b, float& s2, float& e) {
s2 = a + b;
const float bb2 = s2 - a;
e = (a - (s2 - bb2)) + (b - bb2);
};
float hi = 0.0f, lo = 0.0f;
if (!pad)
for (int64_t k = lane; k < K; k += kSub) {
const float xv = rad_load_f32(x.base, x.dtype, m * x.pitch + k);
const float wv = joined ? cp.at(local, k) * sp.cover(local, k)
: rad_load_f32(w.base, w.dtype, local * w.pitch + k);
const float pr = xv * wv;
const float pe = sycl::fma(xv, wv, -pr);
float sv, se;
two_sum(hi, pr, sv, se);
hi = sv;
lo += se + pe;
}
for (int off = 8; off > 0; off >>= 1) {
const float h2 = sycl::shift_group_left(sg, hi, off);
const float l2 = sycl::shift_group_left(sg, lo, off);
float sv, se;
two_sum(hi, h2, sv, se);
hi = sv;
lo = lo + l2 + se;
}
if (lane == 0) {
idl[r] = pad ? -1 : (int32_t)g;
scl[r] = pad ? -INFINITY : hi + lo;
}
sycl::group_barrier(it.get_group());
if (it.get_local_id(0) != 0) return;
uint32_t used = 0;
for (int64_t o = 0; o < R; ++o) {
int64_t best = -1;
for (int64_t c = 0; c < R; ++c) {
if (((used >> c) & 1u) || idl[c] < 0) continue;
if (best < 0 || scl[c] > scl[best] || (scl[c] == scl[best] && idl[c] < idl[best])) best = c;
}
const int32_t oid = best >= 0 ? idl[best] : -1;
const float ov = best >= 0 ? scl[best] : -INFINITY;
if (best >= 0) used |= 1u << best;
st_index(idx.dtype, idx.base, m * idx.pitch + o, (int64_t)oid);
rad_store_f32(val.base, val.dtype, m * val.pitch + o, ov);
if (pairs) {
float* pp = pairs + (m * R + o) * 2;
pp[0] = sycl::bit_cast<float>(oid);
pp[1] = ov;
}
}
});
});
});
}
float* ws = workspace(*q, (size_t)(M * R * 3));
if (!ws) return RAD_E_DEVICE;
const size_t wg = 16;
const size_t groups = (size_t)((M + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_global_id(0);
if (m >= M) return;
int32_t* id = (int32_t*)(ws + m * R * 3);
float* sc = ws + m * R * 3 + R;
float* used = sc + R;
HPlane cp, sp;
if (joined) {
cp = hplane(wb, "codes");
sp = hplane(wb, "scale");
if (!cp.p || !sp.p) return; /* the layout hook guarantees a joined head */
}
for (int64_t r = 0; r < R; ++r) {
const int64_t g = ld_index(in.dtype, in.base, m * in.pitch + r);
const int64_t local = g - voff;
used[r] = 0.0f;
if (g < 0 || local < 0 || local >= NV) {
id[r] = -1;
sc[r] = -INFINITY;
continue;
}
double acc = 0.0;
for (int64_t k = 0; k < K; ++k)
acc += (double)rad_load_f32(x.base, x.dtype, m * x.pitch + k) *
(double)(joined ? cp.at(local, k) * sp.cover(local, k)
: rad_load_f32(w.base, w.dtype, local * w.pitch + k));
id[r] = (int32_t)g;
sc[r] = (float)acc;
}
for (int64_t o = 0; o < R; ++o) {
int64_t best = -1;
for (int64_t c = 0; c < R; ++c) {
if (used[c] != 0.0f || id[c] < 0) continue;
if (best < 0 || sc[c] > sc[best] || (sc[c] == sc[best] && id[c] < id[best])) best = c;
}
const int32_t oid = best >= 0 ? id[best] : -1;
const float ov = best >= 0 ? sc[best] : -INFINITY;
if (best >= 0) used[best] = 1.0f;
st_index(idx.dtype, idx.base, m * idx.pitch + o, (int64_t)oid);
rad_store_f32(val.base, val.dtype, m * val.pitch + o, ov);
if (pairs) {
float* p = pairs + (m * R + o) * 2;
p[0] = sycl::bit_cast<float>(oid);
p[1] = ov;
}
}
});
});
}
} // namespace
int dflash_conv(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *DL = &a->t[1], *BS = &a->t[2], *O = &a->t[3];
const int64_t taps = rad_args_geti_or(a, "taps", 0), group = rad_args_geti_or(a, "group_size", 0);
const int64_t NG = rad_args_geti_or(a, "NG", 0), bsz = rad_args_geti_or(a, "block_size", 0);
if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL;
if (X->data == O->data) return RAD_E_INVAL;
if (X->rank != 2 || O->rank != 2) return RAD_E_SHAPE;
const int64_t T = X->shape[0], H = X->shape[1];
if (T <= 0 || O->shape[0] != T || O->shape[1] != H || H != NG * group) return RAD_E_SHAPE;
if (rad_tensor_numel(BS) < taps * H) return RAD_E_SHAPE;
int64_t d_rs = 0, d_ts = 0, d_gs = 0;
if (DL->rank == 3) {
if (DL->shape[0] < T || DL->shape[1] < taps || DL->shape[2] < NG) return RAD_E_SHAPE;
d_rs = DL->stride[0]; d_ts = DL->stride[1]; d_gs = DL->stride[2];
} else if (DL->rank == 2) {
if (DL->shape[0] < T || DL->shape[1] < taps * NG) return RAD_E_SHAPE;
d_rs = DL->stride[0]; d_gs = DL->stride[1]; d_ts = NG * d_gs;
} else {
return RAD_E_SHAPE;
}
Rows bs;
if (int rc = rows_view(BS, H, &bs, "dflash_conv bias"); rc < 0) return rc;
const int64_t bcs = laststride(BS);
const int64_t x_rs = X->stride[0], x_cs = X->stride[1], o_rs = O->stride[0], o_cs = O->stride[1];
const char *xb = (const char*)X->data, *db = (const char*)DL->data;
char* ob = (char*)O->data;
const uint32_t xdt = X->dtype, ddt = DL->dtype, odt = O->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = T * H;
const size_t wg = 256;
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t gi = (int64_t)it.get_global_id(0);
if (gi >= total) return;
const int64_t t = gi / H, h = gi % H, g = h / group;
float acc = 0.0f;
for (int64_t j = 0; j < taps; ++j) {
if (j > 0 && t % bsz < j) continue;
const float c = rad_load_f32(bs.base, bs.dtype, j * bs.pitch + h * bcs) +
rad_load_f32(db, ddt, t * d_rs + j * d_ts + g * d_gs);
const float term = c * rad_load_f32(xb, xdt, (t - j) * x_rs + h * x_cs);
acc = j == 0 ? term : acc + term;
}
rad_store_f32(ob, odt, t * o_rs + h * o_cs, acc);
});
});
}
int logit_rerank(const RadArgs* a, RadStream s) { return rerank(a, s, false); }
int logit_rerank_head(const RadArgs* a, RadStream s) { return rerank(a, s, true); }
} // namespace xe2