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_sample.cpp
T
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

772 lines
36 KiB
C++

/* xe2_sample.cpp -- the sampler ops: libref's arithmetic (ref_sample.cpp), on the card.
*
* Every scalar is per row, read from the `params` operand of RadSampleParams (abi/rad_sample.h).
* Three shapes of kernel, correctness first:
*
* one work-item a row the stages whose arithmetic is a serial walk: penalties, DRY and the
* n-gram ban over the row's history, the narrowing stages (top-p, min-p,
* typical, XTC) and the pick over at most a thousand candidates. These
* are libref's loops, unchanged, so their sums run in libref's order.
* one work-item an element temperature and the grammar mask.
* one work-group a row the full-vocabulary scans (argmax, top-k, logprobs), as reductions
* over a 64-bit key: the value's order-preserving bits above the
* complemented index, so the maximum key is the largest value and, among
* equal values, the lowest index -- libref's tie rule ("ties to the lower
* token id"). -0 is folded to +0 first, since libref compares floats and
* -0 == +0. A NaN logit is never selected (libref's scans would take one
* only by accident of order).
*
* Top-k selects its k candidates in k rounds, each a group reduction over the keys below the
* previous pick: libref's topk_next, k times. A greedy row takes none, so the greedy path costs one
* round trip of the row.
*
* logprobs' normaliser is a double sum, as libref's, here by a group reduction; the f32 it rounds to
* is the reference's but for a double-rounding tie.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_sample.h"
#include <cfloat>
#include <cmath>
#include <cstring>
namespace xe2 {
namespace {
constexpr size_t kRowWg = 1024; /* work-items a row for the full-vocabulary scans */
/* The params operand, checked once (libref's param_rows). */
int param_rows(const RadTensor* t, int64_t M, const RadSampleParams** out) {
if (!t || !t->data) return RAD_E_INVAL;
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return RAD_E_DTYPE;
if (rad_tensor_numel(t) * 4 < M * (int64_t)sizeof(RadSampleParams)) return RAD_E_SHAPE;
*out = (const RadSampleParams*)t->data;
return RAD_OK;
}
/* A logits row: the vocabulary width from the parameter or the last extent; M = numel / width. */
int logits_rows(const RadArgs* a, const RadTensor* lg, int64_t* n_vocab, Rows* out, const char* op) {
*n_vocab = rad_args_geti_or(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (*n_vocab <= 0) return RAD_E_SHAPE;
if (int rc = rows_view(lg, *n_vocab, out, op); rc < 0) return rc;
return out->rows > 0 ? RAD_OK : RAD_E_SHAPE;
}
/* The history plane, [M, hmax] with rows of its own. */
int hist_rows(const RadTensor* h, int64_t M, Rows* out, const char* op) {
const int64_t hmax = rad_tensor_numel(h) / M;
if (hmax <= 0) return RAD_E_SHAPE;
return rows_view(h, hmax, out, op);
}
/* libref's hist_window. */
inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, int64_t* ho_out,
int64_t* hl_out) {
if (last_n == 0) return false;
int64_t hl = sp.hist_len;
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
if (ho > hmax) ho = hmax;
if (hl > hmax - ho) hl = hmax - ho;
if (last_n > 0 && hl > last_n) {
ho += hl - last_n;
hl = last_n;
}
*ho_out = ho;
*hl_out = hl;
return hl > 0;
}
inline float ref_exp(float x) { return (float)sycl::exp((double)x); }
inline float ref_log(float x) { return (float)sycl::log((double)x); }
/* A candidate plane row: cand_idx (integer) and cand_val (float), rows of n_cand. */
struct Cands {
Rows idx, val;
int64_t n_cand = 0;
};
int cand_rows(const RadTensor* ci, const RadTensor* cv, int64_t n_cand, int64_t M, Cands* out,
const char* op) {
out->n_cand = n_cand;
if (rad_tensor_numel(ci) < M * n_cand || rad_tensor_numel(cv) < M * n_cand) return RAD_E_SHAPE;
if (int rc = rows_view(ci, n_cand, &out->idx, op); rc < 0) return rc;
return rows_view(cv, n_cand, &out->val, op);
}
/* One work-item a row over M rows. */
template <class F>
int per_row(sycl::queue* q, int64_t M, F&& body) {
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) body(m);
});
});
}
/* One work-item a row over M rows, a row's candidates first staged in local memory by its whole
* work-group: the serial walks over n_cand (1024, mostly pads behind top_k's 20) were a dependent
* global load a step, ~480 us a call. The body sees the staged ids (int32, -1 a pad) and values;
* what it writes back to the planes it writes itself. */
constexpr int64_t kStageMax = 4096;
template <class F>
int per_row_staged(sycl::queue* q, int64_t M, const Cands& c, F&& body) {
const int64_t n = c.n_cand;
if (n > kStageMax) return refuse("candidate rows of %lld over %lld", (long long)n, (long long)kStageMax);
constexpr size_t wg = 256;
return submit([&] {
q->submit([&](sycl::handler& h) {
sycl::local_accessor<int32_t, 1> sid(sycl::range<1>((size_t)n), h);
sycl::local_accessor<float, 1> sv(sycl::range<1>((size_t)n), h);
sycl::local_accessor<float, 1> se(sycl::range<1>((size_t)n), h);
h.parallel_for(sycl::nd_range<1>{(size_t)M * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int64_t lane = (int64_t)it.get_local_id(0);
float lmx = -INFINITY;
for (int64_t i = lane; i < n; i += (int64_t)wg) {
const int32_t id = (int32_t)ld_index(c.idx.dtype, c.idx.base, m * c.idx.pitch + i);
const float v = rad_load_f32(c.val.base, c.val.dtype, m * c.val.pitch + i);
sid[i] = id;
sv[i] = v;
if (id >= 0 && v > lmx) lmx = v;
}
/* the live maximum (the bodies' own serial scan finds the same value, up to the
* sign of a zero, which no exp(v - mx) below sees), then every live candidate's
* exp(v - mx) a lane each: the double exp is the bodies' cost, ~6 us apiece */
const float mx = sycl::reduce_over_group(it.get_group(), lmx, sycl::maximum<float>());
for (int64_t i = lane; i < n; i += (int64_t)wg)
se[i] = sid[i] >= 0 && mx != -INFINITY ? ref_exp(sv[i] - mx) : 0.0f;
sycl::group_barrier(it.get_group());
if (lane == 0)
body(m, sid.template get_multi_ptr<sycl::access::decorated::no>().get(),
sv.template get_multi_ptr<sycl::access::decorated::no>().get(),
se.template get_multi_ptr<sycl::access::decorated::no>().get());
});
});
});
}
} // namespace
/* ------------------------------------------------------------------ sample_penalties */
int sample_penalties(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg, hist;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_penalties"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_penalties history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_PENALTY)) return;
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.penalty_last_n, hmax, &ho, &hl)) return;
const int64_t hb = m * hist.pitch + ho;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
for (int64_t i = 0; i < hl; ++i) {
const int64_t tok = tok_at(i);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
if (tok_at(j) != tok) continue;
if (j < i) { first = false; break; }
++count;
}
if (!first) continue;
const int64_t off = m * lg.pitch + col;
float v = rad_load_f32(lg.base, lg.dtype, off);
v = v > 0.0f ? v / rep : v * rep;
v -= (float)count * freq;
v -= pres;
rad_store_f32(lg.base, lg.dtype, off, v);
}
});
}
/* ------------------------------------------------------------------ sample_dry */
int sample_dry(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* BRK = rad_arg_in(a, 3);
int64_t n_vocab = 0;
Rows lg, hist, brk;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_dry"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_dry history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
const bool has_brk = BRK != nullptr;
if (has_brk) {
if (rad_tensor_numel(BRK) < M * hmax) return RAD_E_SHAPE;
if (int rc = rows_view(BRK, hmax, &brk, "sample_dry breakers"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) return;
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.dry_penalty_last_n, hmax, &ho, &hl)) return;
if (hl <= allowed) return;
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
if (cap < allowed) return;
const int64_t hb = m * hist.pitch + ho;
const int64_t bb = has_brk ? m * brk.pitch + ho : 0;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
auto exempt = [&](int64_t i) { return has_brk && ld_index(brk.dtype, brk.base, bb + i) != 0; };
/* The repeat length a continuation j + 1 would extend, or -1 when it does not count:
* libref's loop body, so the per-token maximum below is the same map libref builds. */
auto rep_len = [&](int64_t j) -> int64_t {
const int64_t lim = j + 1 < cap ? j + 1 : cap;
int64_t n = 0;
while (n < lim && tok_at(j - n) == tok_at(hl - 1 - n)) ++n;
if (n < allowed || exempt(j + 1)) return -1;
const int64_t next = tok_at(j + 1);
const int64_t col = next - voff;
if (next < 0 || col < 0 || col >= n_vocab) return -1;
return n;
};
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
for (int64_t j = 0; j + 1 < hl; ++j) {
const int64_t n = rep_len(j);
if (n < 0) continue;
const int64_t next = tok_at(j + 1);
/* Each token once, at its first qualifying position, with its longest repeat. */
bool first = true;
int64_t L = n;
for (int64_t j2 = 0; j2 + 1 < hl; ++j2) {
if (j2 == j || tok_at(j2 + 1) != next) continue;
const int64_t n2 = rep_len(j2);
if (n2 < 0) continue;
if (j2 < j) { first = false; break; }
if (n2 > L) L = n2;
}
if (!first) continue;
float pen = sp.dry_multiplier;
if (base != 1.0f) {
const float lim = FLT_MAX / base;
for (int64_t i = 0; i < L - allowed; ++i) {
if (pen > lim) break;
pen *= base;
}
}
const int64_t off = m * lg.pitch + (next - voff);
rad_store_f32(lg.base, lg.dtype, off, rad_load_f32(lg.base, lg.dtype, off) - pen);
}
});
}
/* ------------------------------------------------------------------ sample_ngram_ban */
int sample_ngram_ban(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor* NG = &a->t[3];
const RadTensor* WL = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
int64_t n_vocab = 0;
Rows lg, hist, ng, wl;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_ngram_ban"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
if (int rc = hist_rows(&a->t[2], M, &hist, "sample_ngram_ban history"); rc < 0) return rc;
const int64_t hmax = rad_tensor_numel(&a->t[2]) / M;
if (rad_tensor_numel(NG) < 2 * M) return RAD_E_SHAPE;
if (int rc = rows_view(NG, 2, &ng, "sample_ngram_ban ngram"); rc < 0) return rc;
const int64_t wwords = (n_vocab + 31) / 32;
const bool has_wl = WL != nullptr;
if (has_wl) {
if (WL->dtype != RAD_I32 && WL->dtype != RAD_U32) return RAD_E_DTYPE;
if (rad_tensor_numel(WL) < M * wwords) return RAD_E_SHAPE;
if (int rc = rows_view(WL, wwords, &wl, "sample_ngram_ban whitelist"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row(q, M, [=](int64_t m) {
const RadSampleParams& sp = P[m];
const int64_t n = ld_index(ng.dtype, ng.base, m * ng.pitch);
const int64_t win_req = ld_index(ng.dtype, ng.base, m * ng.pitch + 1);
if (n <= 0) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, -1, hmax, &ho, &hl)) return;
if (hl < n) return;
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
const int64_t search_start = hl - win, search_end = hl - n + 1;
if (search_end <= search_start) return;
const int64_t hb = m * hist.pitch + ho;
auto tok_at = [&](int64_t i) { return ld_index(hist.dtype, hist.base, hb + i); };
auto exempt = [&](int64_t col) {
if (!has_wl) return false;
const uint32_t word = (uint32_t)ld_index(wl.dtype, wl.base, m * wl.pitch + col / 32);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = n - 1, p0 = hl - plen;
for (int64_t idx = search_start; idx < search_end; ++idx) {
bool match = true;
for (int64_t j = 0; j < plen; ++j)
if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; }
if (!match) continue;
const int64_t tok = tok_at(idx + plen);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab || exempt(col)) continue;
rad_store_f32(lg.base, lg.dtype, m * lg.pitch + col, -INFINITY);
}
});
}
/* ------------------------------------------------------------------ sample_temp, sample_mask */
int sample_temp(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_temp"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = M * n_vocab;
const size_t wg = 256, groups = (size_t)((total + 255) / 256);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t m = g / n_vocab, i = g % n_vocab;
const float t = P[m].temp;
if (!(t > 0.0f) || t == 1.0f) return;
const float inv = 1.0f / t;
const int64_t off = m * lg.pitch + i;
rad_store_f32(lg.base, lg.dtype, off, rad_load_f32(lg.base, lg.dtype, off) * inv);
});
});
}
int sample_mask(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
int64_t n_vocab = 0;
Rows lg, bm;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_mask"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
const int64_t words = (n_vocab + 31) / 32;
const int64_t mask_rows = rad_tensor_numel(&a->t[2]) / words;
if (mask_rows <= 0) return RAD_E_SHAPE;
if (int rc = rows_view(&a->t[2], words, &bm, "sample_mask bitmask"); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = M * n_vocab;
const size_t wg = 256, groups = (size_t)((total + 255) / 256);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t m = g / n_vocab, i = g % n_vocab;
const RadSampleParams& sp = P[m];
if (!(sp.flags & RAD_SP_MASK)) return;
const int64_t row = sp.mask_row;
if (row < 0 || row >= mask_rows) return;
const uint32_t word = (uint32_t)ld_index(bm.dtype, bm.base, row * bm.pitch + i / 32);
if (!((word >> (i % 32)) & 1u))
rad_store_f32(lg.base, lg.dtype, m * lg.pitch + i, -INFINITY);
});
});
}
/* ------------------------------------------------------------------ sample_argmax */
int sample_argmax(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* TOK = &a->t[2];
int64_t n_vocab = 0;
Rows lg;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_argmax"); rc < 0) return rc;
const int64_t M = lg.rows;
if (rad_tensor_numel(TOK) < M) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(TOK)) return refuse("sample_argmax: token not contiguous");
char* tb = (char*)TOK->data;
const uint32_t tdt = TOK->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
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);
uint64_t best = 0;
for (int64_t i = (int64_t)it.get_local_id(0); i < n_vocab; i += (int64_t)kRowWg)
best = sycl::max(best, sel_key(rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i), i));
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
if (it.get_local_id(0) == 0) {
/* All NaN: libref takes index 0 (its first element always seeds the scan). */
const int64_t bi = best ? key_index(best) : 0;
if (tdt == RAD_I64) ((int64_t*)tb)[m] = bi;
else ((int32_t*)tb)[m] = (int32_t)bi;
}
});
});
}
/* ------------------------------------------------------------------ sample_topk */
int sample_topk(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[2], *CV = &a->t[3];
const RadTensor* PP = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
int64_t n_vocab = 0;
Rows lg, pp;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_topk"); rc < 0) return rc;
const int64_t M = lg.rows;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
const int64_t n_cand = CI->rank >= 2 ? CI->shape[CI->rank - 1] : rad_tensor_numel(CI) / M;
if (n_cand <= 0) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, "sample_topk"); rc < 0) return rc;
const bool has_pp = PP != nullptr;
if (has_pp) {
if (rad_tensor_numel(PP) < M * 2 * n_cand) return RAD_E_SHAPE;
if (int rc = rows_view(PP, 2 * n_cand, &pp, "sample_topk pairs"); rc < 0) return rc;
}
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
/* Two passes: each chunk of kChunk logits (a work-group, its keys held in registers) takes its
* own top k, and a row's merge takes the top k of the chunks' -- the same keys, since a key's
* rank is a total order (value, then index). One work-group a row walking the whole vocabulary
* k times was 2.3 ms a call at 8 rows (k = 20). */
constexpr int kCw = 256, kEpi = 16;
constexpr int64_t kChunk = (int64_t)kCw * kEpi;
const int64_t nch = (n_vocab + kChunk - 1) / kChunk;
uint64_t* ck = (uint64_t*)workspace(*q, (size_t)(M * nch * n_cand * 2), 10);
if (!ck) return RAD_E_DEVICE;
if (int rc = submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(M * nch) * kCw, kCw}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0) / nch, ch = (int64_t)it.get_group(0) % nch;
const int lane = (int)it.get_local_id(0);
int64_t k = P[m].top_k;
if (k <= 0 || k > n_cand) k = n_cand;
if (P[m].flags & RAD_SP_GREEDY) k = 0;
uint64_t key[kEpi];
#pragma unroll
for (int e = 0; e < kEpi; ++e) {
const int64_t i = ch * kChunk + e * kCw + lane;
key[e] = i < n_vocab ? sel_key(rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i), i) : 0;
}
uint64_t* out = ck + (m * nch + ch) * n_cand;
uint64_t prev = ~(uint64_t)0;
for (int64_t r = 0; r < k; ++r) { /* a chunk's first k keys (0: none left) */
uint64_t best = 0;
if (prev != 0) {
#pragma unroll
for (int e = 0; e < kEpi; ++e)
if (key[e] < prev) best = sycl::max(best, key[e]);
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) out[r] = best;
prev = best;
}
});
});
rc < 0)
return rc;
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kCw, kCw}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int lane = (int)it.get_local_id(0);
int64_t k = P[m].top_k;
if (k <= 0 || k > n_cand) k = n_cand;
if (P[m].flags & RAD_SP_GREEDY) k = 0;
const uint64_t* rk = ck + m * nch * n_cand;
const int64_t nk = nch * k;
/* prev starts above every key, so the first round takes the maximum; `more` is uniform
* across the group, so every work-item reaches the same reductions. Rounds k and on
* only write the pads, a lane each. */
uint64_t prev = ~(uint64_t)0;
bool more = true;
auto emit = [&](int64_t r, uint64_t best) {
const bool ok = best != 0;
const int64_t pi = ok ? key_index(best) : -1;
const float pv = ok ? key_value(best) : -INFINITY;
const int64_t io = m * c.idx.pitch + r;
if (c.idx.dtype == RAD_I64) ((int64_t*)c.idx.base)[io] = pi;
else ((int32_t*)c.idx.base)[io] = (int32_t)pi;
rad_store_f32(c.val.base, c.val.dtype, m * c.val.pitch + r, pv);
if (has_pp) {
uint32_t bits;
std::memcpy(&bits, &pv, 4);
uint32_t* pr = (uint32_t*)pp.base + m * pp.pitch + 2 * r;
pr[0] = ok ? (uint32_t)(pi + voff) : 0xffffffffu;
pr[1] = bits;
}
};
for (int64_t r = 0; r < k; ++r) {
uint64_t best = 0;
if (more) {
for (int64_t i = lane; i < nk; i += (int64_t)kCw) {
const uint64_t key = rk[(i / k) * n_cand + i % k];
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum<uint64_t>());
}
if (lane == 0) emit(r, best);
if (best == 0) more = false;
else prev = best;
}
for (int64_t r = k + lane; r < n_cand; r += (int64_t)kCw) emit(r, 0);
});
});
}
/* ------------------------------------------------------------------ the narrowing stages */
namespace {
enum Narrow { NR_TOPP, NR_MINP, NR_TYPICAL, NR_XTC };
int narrow(const RadArgs* a, RadStream st, Narrow which, const char* op) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[0], *CV = &a->t[1];
const int64_t n_cand = rad_args_geti_or(a, "n_cand", CI->rank >= 2 ? CI->shape[CI->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(CI) / n_cand;
if (M <= 0) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, op); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[2], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row_staged(q, M, c, [=](int64_t m, int32_t* sid, float* sv, const float* se) {
const RadSampleParams& sp = P[m];
if (sp.flags & RAD_SP_GREEDY) return;
const int64_t ib = m * c.idx.pitch, vb = m * c.val.pitch;
auto drop = [&](int64_t i) {
if (c.idx.dtype == RAD_I64) ((int64_t*)c.idx.base)[ib + i] = -1;
else ((int32_t*)c.idx.base)[ib + i] = -1;
rad_store_f32(c.val.base, c.val.dtype, vb + i, -INFINITY);
sid[i] = -1;
sv[i] = -INFINITY;
};
auto live = [&](int64_t i) { return sid[i] >= 0; };
auto val = [&](int64_t i) { return sv[i]; };
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) { const float v = val(i); if (v > mx) mx = v; }
if (mx == -INFINITY) return;
if (which == NR_MINP) {
const float p = sp.min_p;
if (!(p > 0.0f)) return;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float v = val(i);
if (v == mx) continue;
if (se[i] < p) drop(i);
}
return;
}
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) sum += se[i];
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
if (which == NR_TOPP) {
const float p = sp.top_p;
if (!(p < 1.0f) || !(p > 0.0f)) return;
float cum = 0.0f;
bool done = false;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (done) { drop(i); continue; }
cum += se[i] * inv;
if (cum >= p) done = true;
}
return;
}
if (which == NR_TYPICAL) {
const float p = sp.typical_p;
if (!(p < 1.0f) || !(p > 0.0f)) return;
/* libref keeps q[] and d[]; here they are recomputed from the candidates, which give
* the same floats, since the plane is not written until the drops at the end. */
auto qp = [&](int64_t i) { return live(i) ? se[i] * inv : 0.0f; };
float H = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (qi > 0.0f) H -= qi * ref_log(qi);
}
auto dist = [&](float qi) { return sycl::fabs(-ref_log(qi) - H); };
float cut = 0.0f;
bool have_cut = false;
for (int64_t cc = 0; cc < n_cand; ++cc) {
const float qc = qp(cc);
if (!(qc > 0.0f)) continue;
const float dc = dist(qc);
float mass = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (qi > 0.0f && dist(qi) <= dc) mass += qi;
}
if (mass >= p && (!have_cut || dc < cut)) {
cut = dc;
have_cut = true;
}
}
if (!have_cut) return;
/* libref decides from a snapshot of q[]; dropping in order is the same, since a
* decision reads only mx, inv, H, cut and the candidate's own entry, which no other
* candidate's drop changes. */
for (int64_t i = 0; i < n_cand; ++i) {
const float qi = qp(i);
if (live(i) && (!(qi > 0.0f) || dist(qi) > cut)) drop(i);
}
return;
}
/* XTC */
if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) return;
if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability) return;
int64_t last_above = -1, n_above = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (se[i] * inv >= sp.xtc_threshold) {
last_above = i;
++n_above;
}
}
if (n_above < 2) return;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i) || i == last_above) continue;
if (se[i] * inv >= sp.xtc_threshold) drop(i);
}
});
}
} // namespace
int sample_topp(const RadArgs* a, RadStream s) { return narrow(a, s, NR_TOPP, "sample_topp"); }
int sample_minp(const RadArgs* a, RadStream s) { return narrow(a, s, NR_MINP, "sample_minp"); }
int sample_typical(const RadArgs* a, RadStream s) { return narrow(a, s, NR_TYPICAL, "sample_typical"); }
int sample_xtc(const RadArgs* a, RadStream s) { return narrow(a, s, NR_XTC, "sample_xtc"); }
/* ------------------------------------------------------------------ sample_pick */
int sample_pick(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *CI = &a->t[0], *CV = &a->t[1], *TOK = &a->t[3];
const int64_t n_cand = rad_args_geti_or(a, "n_cand", CI->rank >= 2 ? CI->shape[CI->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(CI) / n_cand;
if (M <= 0 || rad_tensor_numel(TOK) < M) return RAD_E_SHAPE;
Cands c;
if (int rc = cand_rows(CI, CV, n_cand, M, &c, "sample_pick"); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[2], M, &P); rc < 0) return rc;
if (!rad_tensor_is_contiguous(TOK)) return refuse("sample_pick: token not contiguous");
char* tb = (char*)TOK->data;
const uint32_t tdt = TOK->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return per_row_staged(q, M, c, [=](int64_t m, const int32_t* sid, const float* sv, const float* se) {
if (P[m].flags & RAD_SP_GREEDY) return;
auto id_at = [&](int64_t i) { return (int64_t)sid[i]; };
auto val = [&](int64_t i) { return sv[i]; };
auto put = [&](int64_t v) {
if (tdt == RAD_I64) ((int64_t*)tb)[m] = v;
else ((int32_t*)tb)[m] = (int32_t)v;
};
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i) {
if (id_at(i) < 0) continue;
const float v = val(i);
if (v > mx) mx = v;
}
if (mx == -INFINITY) { put(-1); return; }
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (id_at(i) >= 0) sum += se[i];
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
const float u = rad_sample_uniform01(P[m].seed ^ RAD_SAMPLE_KEY_PICK, P[m].pos);
float cum = 0.0f;
int64_t chosen = -1, last = -1;
for (int64_t i = 0; i < n_cand; ++i) {
const int64_t id = id_at(i);
if (id < 0) continue;
const float v = val(i);
if (v > -INFINITY) last = id;
cum += se[i] * inv;
if (u < cum) { chosen = id; break; }
}
put(chosen >= 0 ? chosen : last);
});
}
/* ------------------------------------------------------------------ sample_logprobs */
int sample_logprobs(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* ST = &a->t[2];
int64_t n_vocab = 0;
Rows lg, so;
if (int rc = logits_rows(a, &a->t[0], &n_vocab, &lg, "sample_logprobs"); rc < 0) return rc;
const int64_t k = rad_args_geti_or(a, "k", 0);
const int64_t voff = rad_args_geti_or(a, "vocab_off", 0);
if (k <= 0) return RAD_E_SHAPE;
const int64_t M = lg.rows;
const int64_t w = 2 + 2 * k;
if (rad_tensor_numel(ST) < M * w) return RAD_E_SHAPE;
if (int rc = rows_view(ST, w, &so, "sample_logprobs stats"); rc < 0) return rc;
const RadSampleParams* P = nullptr;
if (int rc = param_rows(&a->t[1], M, &P); rc < 0) return rc;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
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);
if (!(P[m].flags & RAD_SP_LOGPROBS)) return; /* uniform across the group */
const int lane = (int)it.get_local_id(0);
const auto grp = it.get_group();
auto ld = [&](int64_t i) { return rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i); };
float mx = -INFINITY;
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) mx = sycl::fmax(mx, ld(i));
mx = sycl::reduce_over_group(grp, mx, sycl::maximum<float>());
double sum = 0.0;
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg)
sum += sycl::exp((double)ld(i) - (double)mx);
sum = sycl::reduce_over_group(grp, sum, sycl::plus<double>());
const int64_t sb = m * so.pitch;
if (lane == 0) {
rad_store_f32(so.base, so.dtype, sb, mx);
rad_store_f32(so.base, so.dtype, sb + 1, (float)sum);
}
uint64_t prev = ~(uint64_t)0;
for (int64_t j = 0; j < k; ++j) {
uint64_t best = 0;
if (prev != 0) {
for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) {
const uint64_t key = sel_key(ld(i), i);
if (key < prev) best = sycl::max(best, key);
}
best = sycl::reduce_over_group(grp, best, sycl::maximum<uint64_t>());
}
if (lane == 0) {
const bool have = best != 0;
rad_store_f32(so.base, so.dtype, sb + 2 + 2 * j,
have ? (float)(key_index(best) + voff) : -1.0f);
rad_store_f32(so.base, so.dtype, sb + 3 + 2 * j,
have ? key_value(best) : -INFINITY);
}
prev = best;
}
});
});
}
} // namespace xe2