diff --git a/libxe2/xe2_ops.h b/libxe2/xe2_ops.h index 9171ea13..7834723d 100644 --- a/libxe2/xe2_ops.h +++ b/libxe2/xe2_ops.h @@ -22,4 +22,18 @@ int logits_gemm(const RadArgs* a, RadStream s); int kv_store(const RadArgs* a, RadStream s); int attn_paged(const RadArgs* a, RadStream s); +int sample_penalties(const RadArgs* a, RadStream s); +int sample_dry(const RadArgs* a, RadStream s); +int sample_ngram_ban(const RadArgs* a, RadStream s); +int sample_temp(const RadArgs* a, RadStream s); +int sample_mask(const RadArgs* a, RadStream s); +int sample_topk(const RadArgs* a, RadStream s); +int sample_topp(const RadArgs* a, RadStream s); +int sample_minp(const RadArgs* a, RadStream s); +int sample_typical(const RadArgs* a, RadStream s); +int sample_xtc(const RadArgs* a, RadStream s); +int sample_pick(const RadArgs* a, RadStream s); +int sample_argmax(const RadArgs* a, RadStream s); +int sample_logprobs(const RadArgs* a, RadStream s); + } // namespace xe2 diff --git a/libxe2/xe2_rows.cpp b/libxe2/xe2_rows.cpp index d12dfb9b..f4b13c27 100644 --- a/libxe2/xe2_rows.cpp +++ b/libxe2/xe2_rows.cpp @@ -96,6 +96,59 @@ const RadKernelInfo kKernels[] = { .shape = "head_dim <= 512, any gqa, causal or not, sliding window, ragged batches", .dtypes = "bf16 query, bf16 or E4M3 cache with per-(seq, head) descales, bf16 out", .domain = RAD_DOMAIN_DEVICE, .launch = xe2::attn_paged }, + + { .name = "xe2_sample_penalties", .op = "sample_penalties", .family = "sample", + .computes = "repetition, frequency and presence penalties over the row's history", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_penalties }, + { .name = "xe2_sample_dry", .op = "sample_dry", .family = "sample", + .computes = "DRY penalty over the row's history", .shape = "one work-item a row; quadratic in the window, as libref", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_dry }, + { .name = "xe2_sample_ngram_ban", .op = "sample_ngram_ban", .family = "sample", + .computes = "windowed no-repeat-ngram ban, optional whitelist", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_ngram_ban }, + { .name = "xe2_sample_temp", .op = "sample_temp", .family = "sample", + .computes = "logits divided by the row's temperature", .shape = "one work-item an element", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_temp }, + { .name = "xe2_sample_mask", .op = "sample_mask", .family = "sample", + .computes = "grammar bitmask: a cleared bit sets -inf", .shape = "one work-item an element", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_mask }, + { .name = "xe2_sample_topk", .op = "sample_topk", .family = "sample", + .computes = "the row's top_k candidates, descending, ties to the lower id", .shape = "one work-group a row, k reduction rounds", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_topk }, + { .name = "xe2_sample_topp", .op = "sample_topp", .family = "sample", + .computes = "top-p over the candidate set", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_topp }, + { .name = "xe2_sample_minp", .op = "sample_minp", .family = "sample", + .computes = "min-p over the candidate set", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_minp }, + { .name = "xe2_sample_typical", .op = "sample_typical", .family = "sample", + .computes = "locally typical sampling over the candidate set", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_typical }, + { .name = "xe2_sample_xtc", .op = "sample_xtc", .family = "sample", + .computes = "exclude top choices, seeded coin", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_xtc }, + { .name = "xe2_sample_pick", .op = "sample_pick", .family = "sample", + .computes = "inverse-CDF draw over the candidates, seeded per row", .shape = "one work-item a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_pick }, + { .name = "xe2_sample_argmax", .op = "sample_argmax", .family = "sample", + .computes = "greedy token, ties to the lower id", .shape = "one work-group a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_argmax }, + { .name = "xe2_sample_logprobs", .op = "sample_logprobs", .family = "sample", + .computes = "max, double normaliser and the top k (id, logit) pairs", .shape = "one work-group a row", + .dtypes = "f32 logits and candidates, RadSampleParams rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::sample_logprobs }, }; const RadPluginInfo kInfo = { diff --git a/libxe2/xe2_sample.cpp b/libxe2/xe2_sample.cpp new file mode 100644 index 00000000..1dd054d8 --- /dev/null +++ b/libxe2/xe2_sample.cpp @@ -0,0 +1,702 @@ +/* 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 +#include +#include + +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); } + +/* The selection key: larger value first, then lower index. 0 is no candidate (NaN). */ +inline uint64_t sel_key(float v, int64_t i) { + if (sycl::isnan(v)) return 0; + if (v == 0.0f) v = 0.0f; + uint32_t b; + std::memcpy(&b, &v, 4); + const uint32_t ord = (b & 0x80000000u) ? ~b : (b | 0x80000000u); + return ((uint64_t)ord << 32) | (uint64_t)(~(uint32_t)i); +} +inline int64_t key_index(uint64_t k) { return (int64_t)(~(uint32_t)k); } +inline float key_value(uint64_t k) { + const uint32_t ord = (uint32_t)(k >> 32); + const uint32_t b = (ord & 0x80000000u) ? (ord & 0x7fffffffu) : ~ord; + float v; + std::memcpy(&v, &b, 4); + return v; +} + +/* 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 +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); + }); + }); +} + +} // 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()); + 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; + 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); + 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; + /* 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. */ + uint64_t prev = ~(uint64_t)0; + bool more = true; + for (int64_t r = 0; r < n_cand; ++r) { + uint64_t best = 0; + if (r < k && more) { + for (int64_t i = lane; i < n_vocab; i += (int64_t)kRowWg) { + const uint64_t key = sel_key(rad_load_f32(lg.base, lg.dtype, m * lg.pitch + i), i); + if (key < prev) best = sycl::max(best, key); + } + best = sycl::reduce_over_group(it.get_group(), best, sycl::maximum()); + } + if (lane == 0) { + 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; + } + } + if (best == 0) more = false; + else prev = best; + } + }); + }); +} + +/* ------------------------------------------------------------------ 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(q, M, [=](int64_t m) { + 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); + }; + auto live = [&](int64_t i) { return ld_index(c.idx.dtype, c.idx.base, ib + i) >= 0; }; + auto val = [&](int64_t i) { return rad_load_f32(c.val.base, c.val.dtype, vb + 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 (ref_exp(v - mx) < p) drop(i); + } + return; + } + float sum = 0.0f; + for (int64_t i = 0; i < n_cand; ++i) + if (live(i)) sum += ref_exp(val(i) - mx); + 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 += ref_exp(val(i) - mx) * 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) ? ref_exp(val(i) - mx) * 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 (ref_exp(val(i) - mx) * 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 (ref_exp(val(i) - mx) * 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(q, M, [=](int64_t m) { + if (P[m].flags & RAD_SP_GREEDY) return; + const int64_t ib = m * c.idx.pitch, vb = m * c.val.pitch; + auto id_at = [&](int64_t i) { return ld_index(c.idx.dtype, c.idx.base, ib + i); }; + auto val = [&](int64_t i) { return rad_load_f32(c.val.base, c.val.dtype, vb + 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 += ref_exp(val(i) - mx); + 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 += ref_exp(v - mx) * 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()); + 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()); + 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()); + } + 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