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
claudeandClaude Opus 5.5 8f84939aa2 libxe2: sample_topk in chunks and a merge, the candidate walks staged in local memory, rerank's K split
sample_topk walked the whole vocabulary top_k times with one work-group a row (2.3 ms at
8 rows); each 4096-logit chunk now takes its own top k from registers and a row's merge takes
the top k of those -- the same keys, the order being total. narrow and sample_pick stage a
row's 1024 candidates (mostly pads) in local memory and compute the exps a lane each before
the serial walk; logit_rerank spreads a candidate over up to 16 sub-groups (290 -> 72 us).
Outputs unchanged (kbench; the same draft trajectory). Coupled MTP decode of a seeded code
prompt 90.5 -> 98.3 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 07:31:15 +01:00

294 lines
14 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 <algorithm>
#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. */
/* SP sub-groups a candidate, each a strided share of K, their pairs added in sub-group
* order: one sub-group walking K alone was 320 dependent steps at K = 5120 (290 us a call,
* one work-group on the whole card) */
const int64_t SP = std::max<int64_t>(1, std::min<int64_t>(16, 1024 / (R * kSub)));
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);
sycl::local_accessor<float, 1> part(sycl::range<1>((size_t)(R * SP * 2)), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * (size_t)(R * SP) * kSub, (size_t)(R * SP) * 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 sgi = (int64_t)sg.get_group_linear_id();
const int64_t r = sgi / SP, sp_ = sgi % SP;
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 = sp_ * kSub + lane; k < K; k += kSub * SP) {
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) {
part[(r * SP + sp_) * 2] = hi;
part[(r * SP + sp_) * 2 + 1] = lo;
}
sycl::group_barrier(it.get_group());
if (sp_ == 0 && lane == 0) {
hi = part[r * SP * 2];
lo = part[r * SP * 2 + 1];
for (int64_t u = 1; u < SP; ++u) {
float sv, se;
two_sum(hi, part[(r * SP + u) * 2], sv, se);
hi = sv;
lo = lo + part[(r * SP + u) * 2 + 1] + se;
}
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