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_draft.cpp
T
claudeandClaude Opus 5.5 2d1f168ec3 libxe2: row_topk filtered, one work-group a row -- 0.93 ms -> 37 us a round at R = 32 of 248320
The R-th largest of a row's 64 sub-group maxima is a lower bound on its R-th largest key (those
maxima are R distinct elements), so the row's top R are among the keys at or above it -- a few
dozen on real logits. A second read gathers them into local memory, and a survivor's place is the
count of survivors above it: the keys carry the column and are distinct, so that is the order the
serial passes produce. More than 4096 survivors (a row of equal values) takes the passes over the
row. bf16 rows are read 8 values a 16-byte load. XE2_TOPK_CHUNKS=1 keeps the two-stage form.

The two-stage form was 846 + 86 us a round (unitrace, M = 15, N = 248320, R = 32); this one 37 us.
rad-kbench against libref: fixture 21/21, Qwen3.8-27B-DFLASH2-PARO-M2XFP4 (R = 32) 14/14 and
qwen3.8-27b-w4a16-rtn (R = 1) 12/12, all at rel_l2 0; greedy output identical (8/8).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 22:55:01 +01:00

425 lines
24 KiB
C++

/* xe2_draft.cpp -- the speculative drafters' selection ops.
*
* row_topk exact per-row top-R, descending, ties to the lower column (ref_moe.cpp): libref's
* topk_next R times, each a work-group reduction of the selection key
* (xe2_common.h), one work-group a row
* dflash_select the block drafter's greedy walk over its candidate lattice (ref_quant.cpp):
* score[l, c] = unary[l, c] + sum_r pred[pid][r] * hp[l][r] * succ[cand[l, c]][r],
* the best candidate (first strict maximum) becoming the next step's predecessor.
* Serial in l by nature, so one sub-group a sequence, a lane a candidate summing
* over r in libref's order (rank <= 1024; else one work-item a sequence).
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace xe2 {
namespace {
constexpr size_t kRowWg = 1024;
constexpr int64_t kSelMaxR = 1024; /* dflash_select's sub-group form: R floats a row in local memory */
constexpr int64_t kTopChunks = 128; /* row_topk's first stage: work-groups a row */
constexpr size_t kTopWg = 256;
constexpr int64_t kTopMaxR = 64;
constexpr int64_t kTopMaxChunk = 4096; /* keys a chunk in local memory (32 KiB) */
constexpr int64_t kSurvMax = 4096; /* row_topk's filtered form: survivors in local memory */
}
/* ------------------------------------------------------------------ row_topk */
int row_topk(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *IDX = &a->t[1], *VAL = &a->t[2];
const RadTensor* PAIRS = rad_arg_in(a, 3);
const int64_t off = rad_args_geti_or(a, "vocab_off", 0);
const int64_t N = rad_args_geti_or(a, "N", X->rank >= 2 ? X->shape[X->rank - 1] : 0);
const int64_t R = rad_args_geti_or(a, "R", 1);
if (N <= 0 || R <= 0) return RAD_E_SHAPE;
Rows x, iv, vv;
if (int rc = rows_view(X, N, &x, "row_topk x"); rc < 0) return rc;
const int64_t M = x.rows;
if (M <= 0 || rad_tensor_numel(IDX) < M * R || rad_tensor_numel(VAL) < M * R) return RAD_E_SHAPE;
if (PAIRS && (PAIRS->dtype != RAD_F32 || rad_tensor_numel(PAIRS) < M * R * 2)) return RAD_E_SHAPE;
if (PAIRS && !rad_tensor_is_contiguous(PAIRS)) return refuse("row_topk: pairs not contiguous");
if (int rc = rows_view(IDX, R, &iv, "row_topk idx"); rc < 0) return rc;
if (int rc = rows_view(VAL, R, &vv, "row_topk val"); rc < 0) return rc;
float* pairs = PAIRS ? (float*)PAIRS->data : nullptr;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
/* A long row in two stages: each of kTopChunks work-groups takes its chunk's top R by the
* same passes, and one work-group a row then takes the top R of those chunk winners. The keys
* are distinct (they carry the column), so the row's top R are among the winners and both
* stages pick exactly what one pass over the row would. One work-group walking 248320
* columns 32 times was 3.2 ms. */
auto store_out = [=](int64_t m, int64_t r, uint64_t best) {
const bool ok = best != 0;
const int64_t id = ok ? key_index(best) + off : -1;
const float v = ok ? key_value(best) : -INFINITY;
const int64_t io = m * iv.pitch + r;
if (iv.dtype == RAD_I64) ((int64_t*)iv.base)[io] = id;
else ((int32_t*)iv.base)[io] = (int32_t)id;
rad_store_f32(vv.base, vv.dtype, m * vv.pitch + r, v);
if (pairs) {
float* pq = pairs + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(pq, &i32, sizeof i32);
pq[1] = v;
}
};
/* A long row filtered, one work-group a row: the 32nd (R-th) largest of the work-group's 64
* sub-group maxima is a lower bound on the row's R-th largest key (those R maxima are R
* distinct keys at or above it), so the row's top R are among the keys at or above it -- a
* few dozen on real logits. A second read of the row gathers them into local memory, and each
* one's place is the count of survivors above it: the keys are distinct, so that is exactly
* the order the passes below produce. More than kSurvMax survivors (a row of equal values)
* takes those passes over the row instead. The two-stage form was 0.87 ms at M = 15,
* N = 248320, R = 32 (R work-group reductions over every chunk). */
if (N >= 16 * (int64_t)kRowWg && R <= kTopMaxR && N < ((int64_t)1 << 31) && !std::getenv("XE2_TOPK_CHUNKS") &&
!std::getenv("XE2_TOPK_SERIAL")) {
constexpr int kSgs = (int)(kRowWg / kSub);
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<uint64_t, 1> smax(sycl::range<1>((size_t)kSgs + 1), h);
sycl::local_accessor<uint64_t, 1> surv(sycl::range<1>((size_t)kSurvMax), h);
sycl::local_accessor<uint64_t, 1> outk(sycl::range<1>((size_t)kTopMaxR), h);
sycl::local_accessor<uint32_t, 1> cnt(sycl::range<1>(1), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
auto grp = it.get_group();
const sycl::sub_group sg = it.get_sub_group();
const int sgi = (int)sg.get_group_linear_id();
const char* xb = x.base;
const uint32_t xdt = x.dtype;
auto key_at = [&](int64_t i) -> uint64_t {
const int64_t o = m * x.pitch + i;
float v;
if (xdt == RAD_BF16) v = rad_bf16_to_f32(((const uint16_t*)xb)[o]);
else if (xdt == RAD_F32) v = ((const float*)xb)[o];
else v = rad_load_f32(xb, xdt, o);
return sel_key(v, i);
};
/* both reads by value (NaN compares false, -0 equals 0, as the keys treat them),
* 8 bf16 values a 16-byte load where the row allows; keys only for survivors */
const bool v8 = xdt == RAD_BF16 && N % 8 == 0 && x.pitch % 8 == 0 &&
((uintptr_t)xb & 15) == 0; /* uniform */
const uint16_t* xr = (const uint16_t*)xb + m * x.pitch;
float mx = -INFINITY;
if (v8) {
for (int64_t i = (int64_t)lane * 8; i < N; i += (int64_t)kRowWg * 8) {
const sycl::vec<uint16_t, 8> w = *(const sycl::vec<uint16_t, 8>*)(xr + i);
for (int u = 0; u < 8; ++u) mx = sycl::fmax(mx, rad_bf16_to_f32(w[u]));
}
} else {
for (int64_t i = lane; i < N; i += (int64_t)kRowWg) mx = sycl::fmax(mx, key_value(key_at(i)));
}
mx = sycl::reduce_over_group(sg, mx, sycl::maximum<float>());
if (sg.get_local_linear_id() == 0) smax[sgi] = sel_key(mx, 0) & ~(uint64_t)0xffffffffu;
if (lane < kTopMaxR) outk[lane] = 0;
if (lane == 0) { cnt[0] = 0; smax[kSgs] = 0; }
sycl::group_barrier(grp);
/* the bound, by value: the largest v with at least R sub-group maxima >= v (those
* are R distinct elements), or none (every key) with fewer than R non-NaN */
if (lane < kSgs) {
const uint64_t mine = smax[lane];
int above = 0, atleast = 0;
for (int j = 0; j < kSgs; ++j) {
above += smax[j] > mine ? 1 : 0;
atleast += smax[j] >= mine ? 1 : 0;
}
if (mine != 0 && above < (int)R && atleast >= (int)R) smax[kSgs] = mine; /* ties: one value */
}
sycl::group_barrier(grp);
const uint64_t bound = sycl::max(smax[kSgs], (uint64_t)1); /* a value's key, column bits 0 */
sycl::atomic_ref<uint32_t, sycl::memory_order::relaxed, sycl::memory_scope::work_group,
sycl::access::address_space::local_space> nsurv(cnt[0]);
auto offer = [&](float v, int64_t i) {
const uint64_t k = sel_key(v, i);
if (k >= bound) {
const uint32_t slot = nsurv.fetch_add(1u);
if (slot < (uint32_t)kSurvMax) surv[slot] = k;
}
};
const float bv = smax[kSgs] != 0 ? key_value(bound) : -INFINITY;
if (v8) {
for (int64_t i = (int64_t)lane * 8; i < N; i += (int64_t)kRowWg * 8) {
const sycl::vec<uint16_t, 8> w = *(const sycl::vec<uint16_t, 8>*)(xr + i);
for (int u = 0; u < 8; ++u) {
const float v = rad_bf16_to_f32(w[u]);
if (v >= bv) offer(v, i + u);
}
}
} else {
for (int64_t i = lane; i < N; i += (int64_t)kRowWg) {
const uint64_t k = key_at(i);
if (k >= bound) {
const uint32_t slot = nsurv.fetch_add(1u);
if (slot < (uint32_t)kSurvMax) surv[slot] = k;
}
}
}
sycl::group_barrier(grp);
const uint32_t ns = cnt[0];
if (ns <= (uint32_t)kSurvMax) { /* uniform */
for (uint32_t s0 = (uint32_t)lane; s0 < ns; s0 += (uint32_t)kRowWg) {
const uint64_t k = surv[s0];
uint32_t above = 0;
for (uint32_t j = 0; j < ns; ++j) above += surv[j] > k ? 1u : 0u;
if (above < (uint32_t)R) outk[above] = k;
}
sycl::group_barrier(grp);
if (lane < R) store_out(m, lane, outk[lane]);
return;
}
/* too many survivors: the serial passes over the row */
uint64_t prev = ~(uint64_t)0;
bool more = true;
for (int64_t r = 0; r < R; ++r) {
uint64_t best = 0;
if (more) {
for (int64_t i = lane; i < N; i += (int64_t)kRowWg) {
const uint64_t key = key_at(i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(grp, best, sycl::maximum<uint64_t>());
}
if (lane == 0) store_out(m, r, best);
if (best == 0) more = false;
else prev = best;
}
});
});
});
}
const int64_t chunk = (N + kTopChunks - 1) / kTopChunks;
if (N >= 16 * (int64_t)kRowWg && R <= kTopMaxR && chunk <= kTopMaxChunk &&
!std::getenv("XE2_TOPK_SERIAL")) {
uint64_t* win = (uint64_t*)workspace(*q, (size_t)(M * kTopChunks * R * 2), 8);
if (!win) return RAD_E_DEVICE;
int rc = submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<uint64_t, 1> keys(sycl::range<1>((size_t)chunk), h);
h.parallel_for(sycl::nd_range<1>{(size_t)(M * kTopChunks) * kTopWg, kTopWg},
[=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0) / kTopChunks, ch = (int64_t)it.get_group(0) % kTopChunks;
const int lane = (int)it.get_local_id(0);
const int64_t i0 = ch * chunk, n = sycl::min(chunk, N - i0);
for (int64_t i = lane; i < n; i += (int64_t)kTopWg)
keys[i] = sel_key(rad_load_f32(x.base, x.dtype, m * x.pitch + i0 + i), i0 + i);
sycl::group_barrier(it.get_group());
uint64_t prev = ~(uint64_t)0;
for (int64_t r = 0; r < R; ++r) {
uint64_t best = 0;
if (prev != 0) { /* uniform */
for (int64_t i = lane; i < n; i += (int64_t)kTopWg)
if (keys[i] < prev) best = sycl::max(best, keys[i]);
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) win[(m * kTopChunks + ch) * R + r] = best;
prev = best;
}
});
});
});
if (rc < 0) return rc;
const int64_t nw = kTopChunks * R;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
const uint64_t* wk = win + m * nw;
uint64_t prev = ~(uint64_t)0;
bool more = true;
for (int64_t r = 0; r < R; ++r) {
uint64_t best = 0;
if (more) {
for (int64_t i = lane; i < nw; i += (int64_t)kRowWg)
if (wk[i] < prev) best = sycl::max(best, wk[i]);
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool ok = best != 0;
const int64_t id = ok ? key_index(best) + off : -1;
const float v = ok ? key_value(best) : -INFINITY;
const int64_t io = m * iv.pitch + r;
if (iv.dtype == RAD_I64) ((int64_t*)iv.base)[io] = id;
else ((int32_t*)iv.base)[io] = (int32_t)id;
rad_store_f32(vv.base, vv.dtype, m * vv.pitch + r, v);
if (pairs) {
float* pq = pairs + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(pq, &i32, sizeof i32);
pq[1] = v;
}
}
if (best == 0) more = false;
else prev = best;
}
});
});
}
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kRowWg, kRowWg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
uint64_t prev = ~(uint64_t)0;
bool more = true; /* uniform across the group */
for (int64_t r = 0; r < R; ++r) {
uint64_t best = 0;
if (more) {
for (int64_t i = lane; i < N; i += (int64_t)kRowWg) {
const uint64_t key = sel_key(rad_load_f32(x.base, x.dtype, m * x.pitch + i), i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool ok = best != 0;
const int64_t id = ok ? key_index(best) + off : -1;
const float v = ok ? key_value(best) : -INFINITY;
const int64_t io = m * iv.pitch + r;
if (iv.dtype == RAD_I64) ((int64_t*)iv.base)[io] = id;
else ((int32_t*)iv.base)[io] = (int32_t)id;
rad_store_f32(vv.base, vv.dtype, m * vv.pitch + r, v);
if (pairs) {
float* pq = pairs + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(pq, &i32, sizeof i32);
pq[1] = v;
}
}
if (best == 0) more = false;
else prev = best;
}
});
});
}
/* ------------------------------------------------------------------ dflash_select */
int dflash_select(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
const RadTensor *CAND = &a->t[0], *UN = &a->t[1], *ANC = &a->t[3];
const RadTensor *PRED = &a->t[4], *SUCC = &a->t[5], *OUT = &a->t[6];
const RadTensor* HP = rad_arg_in(a, 2);
if (!CAND->data || !UN->data || !ANC->data || !PRED->data || !SUCC->data || !OUT->data)
return RAD_E_INVAL;
const int64_t steps = rad_args_geti_or(a, "steps", 0);
const int64_t K = rad_args_geti_or(a, "top_k", 0);
/* libref's band_rows: the rows `cand` holds, unless that exceeds the band. */
int64_t M = 0;
if (steps > 0 && K > 0) {
const int64_t from = rad_tensor_numel(CAND) / (steps * K), band = rad_args_geti_or(a, "M", 0);
M = from <= 0 ? 0 : (band > 0 && from > band) ? 0 : from;
}
const int64_t R = rad_args_geti_or(a, "rank", PRED->rank >= 2 ? PRED->shape[PRED->rank - 1] : 0);
const int64_t nv = rad_args_geti_or(a, "n_vocab", PRED->rank >= 2 ? PRED->shape[PRED->rank - 2] : 0);
const int64_t astr = rad_args_geti_or(a, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_SHAPE;
if (rad_tensor_numel(UN) < M * steps * K) return RAD_E_SHAPE;
if (rad_tensor_numel(ANC) < (M - 1) * astr + 1 || rad_tensor_numel(OUT) < M * steps) return RAD_E_SHAPE;
if (rad_tensor_numel(PRED) < nv * R || rad_tensor_numel(SUCC) < nv * R) return RAD_E_SHAPE;
if (HP && rad_tensor_numel(HP) < M * steps * R) return RAD_E_SHAPE;
Rows cand, un, pred, succ, out, hp;
if (int rc = rows_view(CAND, K, &cand, "dflash_select cand"); rc < 0) return rc;
if (int rc = rows_view(UN, K, &un, "dflash_select unary"); rc < 0) return rc;
if (int rc = rows_view(PRED, R, &pred, "dflash_select pred"); rc < 0) return rc;
if (int rc = rows_view(SUCC, R, &succ, "dflash_select succ"); rc < 0) return rc;
if (int rc = rows_view(OUT, steps, &out, "dflash_select tokens"); rc < 0) return rc;
const bool has_hp = HP != nullptr;
if (has_hp)
if (int rc = rows_view(HP, R, &hp, "dflash_select hp"); rc < 0) return rc;
const Lin anc = Lin::of(ANC);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
if (R <= kSelMaxR && !std::getenv("XE2_SELECT_SERIAL")) {
/* A sub-group a sequence: (pred * hp)[r] and the 16 candidates' succ rows staged in
* local memory by all lanes, lane c then sums candidate c's score over r in order (the
* same chain as below), and lane 0 takes the first strict maximum over the lanes' scores
* in candidate order. The serial form walks 16 rows of 256 one after another. */
const int64_t RP = R + 1; /* a padded row: lane c reads row c without bank conflicts */
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> axl(sycl::range<1>((size_t)R), h);
sycl::local_accessor<float, 1> rows(sycl::range<1>((size_t)(kSub * RP)), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * kSub, (size_t)kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)sg.get_local_linear_id();
int64_t pid = ld_index(anc.dtype, anc.base, anc.off(m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t r = m * steps + l;
const bool ok = pid >= 0 && pid < nv;
for (int64_t i = lane; i < R; i += kSub)
axl[i] = (ok ? rad_load_f32(pred.base, pred.dtype, pid * pred.pitch + i) : 0.0f) *
(has_hp ? rad_load_f32(hp.base, hp.dtype, r * hp.pitch + i) : 1.0f);
int64_t best_c = 0;
float best_s = -INFINITY;
for (int64_t c0 = 0; c0 < K; c0 += kSub) {
const int64_t c = c0 + lane;
const int64_t tok = c < K ? ld_index(cand.dtype, cand.base, r * cand.pitch + c) : -1;
for (int j = 0; j < kSub; ++j) {
const int64_t tj = sycl::select_from_group(sg, tok, j);
if (tj >= 0 && tj < nv) /* uniform */
for (int64_t i = lane; i < R; i += kSub)
rows[j * RP + i] = rad_load_f32(succ.base, succ.dtype, tj * succ.pitch + i);
}
sycl::group_barrier(sg);
float sc = c < K ? rad_load_f32(un.base, un.dtype, r * un.pitch + c) : -INFINITY;
if (c < K && tok >= 0 && tok < nv)
for (int64_t i = 0; i < R; ++i) sc += axl[i] * rows[lane * RP + i];
for (int j = 0; j < kSub; ++j) {
const float sj = sycl::select_from_group(sg, sc, j);
if (c0 + j < K && sj > best_s) { best_s = sj; best_c = c0 + j; }
}
sycl::group_barrier(sg);
}
pid = ld_index(cand.dtype, cand.base, r * cand.pitch + best_c);
if (lane == 0) {
const int64_t oo = m * out.pitch + l;
if (out.dtype == RAD_I64) ((int64_t*)out.base)[oo] = pid;
else ((int32_t*)out.base)[oo] = (int32_t)pid;
}
}
});
});
});
}
const size_t wg = 16;
const size_t n = (size_t)((M + (int64_t)wg - 1) / (int64_t)wg) * wg;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{n, wg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_global_id(0);
if (m >= M) return;
int64_t pid = ld_index(anc.dtype, anc.base, anc.off(m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t r = m * steps + l;
const bool ok = pid >= 0 && pid < nv;
auto ax = [&](int64_t i) {
return (ok ? rad_load_f32(pred.base, pred.dtype, pid * pred.pitch + i) : 0.0f) *
(has_hp ? rad_load_f32(hp.base, hp.dtype, r * hp.pitch + i) : 1.0f);
};
int64_t best_c = 0;
float best_s = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_index(cand.dtype, cand.base, r * cand.pitch + c);
float sc = rad_load_f32(un.base, un.dtype, r * un.pitch + c);
if (tok >= 0 && tok < nv)
for (int64_t i = 0; i < R; ++i)
sc += ax(i) * rad_load_f32(succ.base, succ.dtype, tok * succ.pitch + i);
if (sc > best_s) { best_s = sc; best_c = c; }
}
pid = ld_index(cand.dtype, cand.base, r * cand.pitch + best_c);
const int64_t oo = m * out.pitch + l;
if (out.dtype == RAD_I64) ((int64_t*)out.base)[oo] = pid;
else ((int32_t*)out.base)[oo] = (int32_t)pid;
}
});
});
}
} // namespace xe2