merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across

conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
gearwave00001 committed 2026-10-24 19:03:26 -05:00
commit 7c3b5ab7d5
285 files changed
+30500 -2898

No files matched your search

+173 -26
View File
@@ -51,8 +51,12 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
* them), outside of which the input reads zero (each sequence is padded on its own). w is
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
* dil (k - 1), on the left (any k). With `stride` > 1 - bf16 only, the encoder's downsample - the
* op is one sequence [0, rows of x], `pad` explicit and any k, and output row m reads
* dil (k - 1), on the left (any k). A `stride` s > 1 comes in two forms. A causal one (a codec
* encoder's downsampling, a reach of at least s) keeps every s-th output row: the left pad is the
* reach less s, and a sequence of L rows (every bound a whole number of strides) gives L / s, y's
* and res's rows the input's over s; `cu_div` reads the bounds in units that many input rows
* apart, as the other encoder ops do. A non-causal one with an explicit `pad` (bf16 only, the
* audio encoder's downsample) is one sequence [0, rows of x] with any k, and output row m reads
* x[m * stride + tap * dil - pad]: PyTorch's zero-padded strided conv, whose output length
* (rows + 2 pad - dil (k - 1) - 1) / stride + 1 the y operand must have exactly. `res`, when
* bound, is added after the bias; then `act` (none, tanh, or clamp to [-1, 1], a vocoder's output
@@ -64,37 +68,47 @@ int ref_conv1d(const RadArgs* a, RadStream) {
if (!y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), pp = p_int(a, "pad", -1);
const int64_t st = p_int(a, "stride", 1), pp = p_int(a, "pad", -1), cd = p_int(a, "cu_div", 1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
/* A stride comes in the causal form (no pad operand, cu_div bounds) or the zero-padded one
* with an explicit `pad` (bf16, one full sequence, PyTorch's formula) - never both. */
const bool padded = pp >= 0 && st > 1;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || pp < 0)) ||
(st <= 1 && pp >= 0))
causal < 0 || causal > 1 || st < 1 || (pp >= 0 && (st <= 1 || causal || cd != 1)) ||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
const int64_t cdv = padded ? 1 : cd;
/* A stride takes each sequence of L rows to L / stride, so every bound is a whole number of
* strides (of cu_div units each); the padded form bounds only its one full sequence. */
for (int64_t e = 0; !padded && e <= n_seq; ++e)
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0) / cdv, r1 = cu_at(cu, n_seq) / cdv;
if (r0 < 0 || r1 <= r0 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE;
/* The strided form: one full sequence, bf16, and y exactly the formula's rows. */
int64_t hi = r1;
if (st > 1) {
/* The padded strided form: one full sequence, bf16, and y exactly the formula's rows. */
int64_t rmin = r0 / st, rmax = r1 / st;
if (padded) {
if (x->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(x, cin)) return RAD_E_SHAPE;
hi = (r1 + 2 * pp - dil * (k - 1) - 1) / st + 1;
if (hi <= 0 || rows_of(y, cout) != hi) return RAD_E_SHAPE;
} else if (rows_of(y, cout) < r1) {
return RAD_E_SHAPE;
rmin = 0;
rmax = (r1 + 2 * pp - dil * (k - 1) - 1) / st + 1;
}
if (res && rows_of(res, cout) < hi) return RAD_E_SHAPE;
const int64_t pad = pp >= 0 ? pp : (causal ? dil * (k - 1) : dil * (k - 1) / 2);
const int64_t lo = st > 1 ? 0 : r0; /* a strided op starts at row 0 of its one sequence */
REF_PAR_FOR((hi - lo) * cout * cin * k)
for (int64_t r = lo; r < hi; ++r) {
const int64_t e = seq_of(cu, n_seq, st > 1 ? r * st : r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
if (rmin >= rmax) return RAD_E_SHAPE;
if (padded ? rows_of(y, cout) != rmax : rows_of(y, cout) < rmax) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < rmax) return RAD_E_SHAPE;
/* Causal: the reach is dil (k - 1) + 1 input rows and the left pad that less the stride, so
* output row o of a sequence reads input rows o stride - pad .. o stride + stride - 1. The
* padded form takes PyTorch's zero padding from the explicit `pad` instead. */
const int64_t pad = padded ? pp : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
REF_PAR_FOR((rmax - rmin) * cout * cin * k)
for (int64_t r = rmin; r < rmax; ++r) {
const int64_t e = seq_of(cu, n_seq, r * st * cdv);
const int64_t s0 = cu_at(cu, e) / cdv, s1 = cu_at(cu, e + 1) / cdv;
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
for (int64_t co = 0; co < cout; ++co) {
float acc = 0.0f;
@@ -273,6 +287,9 @@ int ref_snake_aa(const RadArgs* a, RadStream) {
* `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates
* the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and
* drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream).
* With `top_p` < 1 the kept list is cut first where the cumulative probability of the whole
* candidate set's softmax over temp (summed in index order) passes top_p, as Fish Audio's sampler
* cuts it: a rank whose inclusive cumulative probability exceeds top_p is dropped, rank 0 never.
* The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or
* bf16; seed [n, 2]; frame [n]. */
int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
@@ -284,8 +301,10 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
const float pen = p_f32(a, "penalty", 1.0f);
const double top_p = (double)p_f32(a, "top_p", 1.0f);
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) ||
!(top_p >= 0))
return RAD_E_SHAPE;
const int64_t n = numel(ids) / rep;
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
@@ -336,13 +355,32 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
if (open(j)) idx[(size_t)nc++] = j;
}
if (nc == 0) return RAD_E_SHAPE;
const int64_t kk = std::min(K, nc);
/* The whole candidate set's normaliser, in index order (idx still is), for top_p. */
double z = 0;
if (top_p < 1.0) {
float gm = g[(size_t)idx[0]];
for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[(size_t)idx[(size_t)t]]);
const float m0 = gm / temp;
for (int64_t t = 0; t < nc; ++t)
z += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m0));
}
int64_t kk = std::min(K, nc);
std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc,
[&](int64_t p, int64_t q) {
return g[(size_t)p] > g[(size_t)q] ||
(g[(size_t)p] == g[(size_t)q] && p < q);
});
const float m = g[(size_t)idx[0]] / temp;
if (top_p < 1.0) {
double cum = 0;
int64_t keep = 1;
for (int64_t t = 0; t < kk; ++t) {
cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z;
if (t > 0 && cum > top_p) break;
keep = t + 1;
}
kk = keep;
}
double tot = 0;
std::vector<double> e((size_t)kk);
for (int64_t t = 0; t < kk; ++t) {
@@ -378,24 +416,26 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
const float scale = p_f32(a, "scale", 1.0f);
const int64_t round1 = p_int(a, "round", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, D);
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D);
/* `clamp`: a code above clamp - 1 reads row clamp - 1 (a negative one still reads nothing). */
auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
REF_PAR_FOR(rows * D * K)
for (int64_t r = 0; r < rows; ++r) {
const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0;
const int64_t c0 = cl(ld_int(codes->dtype, codes->data, r * rp)) + off0;
if (c0 < 0 || c0 >= r0) continue;
std::vector<float> acc((size_t)D, 0.0f);
const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D);
if (round1)
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0));
for (int64_t k = 1; k < K; ++k) {
const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
const int64_t ck = cl(ld_int(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc;
if (ck < 0 || ck >= r1) continue;
const int64_t tb = rowoff(t1, ck, D);
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1));
@@ -409,6 +449,62 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ vq_encode */
/* One step of a residual vector quantiser with factorised, L2-normalised codes (DAC's
* VectorQuantize, as Fish Audio's codec encodes): per row of x [rows, n], e = in_w x + in_b
* (in_w [dim, n]); the code is the row of cb [bins, dim] of greatest cosine with e,
* (e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12)), the lower index on a tie; then
* x -= out_w cb[code] + out_b (out_w [n, dim], the raw codebook row), rounded once into x. f32,
* every sum in index order. A chain of these over a codec's codebooks is its residual quantiser,
* each step quantising what the last left. */
int ref_vq_encode(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
return RAD_E_SHAPE;
/* The codebook normalised once, as F.normalize divides. */
std::vector<float> cn((size_t)(bins * dim));
for (int64_t c = 0; c < bins; ++c) {
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) ss += ldt(cb, c * dim + j) * ldt(cb, c * dim + j);
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = ldt(cb, c * dim + j) / nrm;
}
REF_PAR_FOR(rows * (dim * n + bins * dim + n * dim))
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
std::vector<float> e((size_t)dim);
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) {
float acc = 0.0f;
for (int64_t d = 0; d < n; ++d) acc += ldt(iw, j * n + d) * ldt(x, xb + d * xs);
e[(size_t)j] = acc + ldt(ib, j);
ss += e[(size_t)j] * e[(size_t)j];
}
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) e[(size_t)j] /= nrm;
int64_t best = 0;
float bs = -INFINITY;
for (int64_t c = 0; c < bins; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < dim; ++j) s += e[(size_t)j] * cn[(size_t)(c * dim + j)];
if (s > bs) { bs = s; best = c; }
}
st_int(codes->dtype, codes->data, offlin(codes, r), best);
for (int64_t d = 0; d < n; ++d) {
float q = 0.0f;
for (int64_t j = 0; j < dim; ++j) q += ldt(ow, d * dim + j) * ldt(cb, best * dim + j);
stt(x, xb + d * xs, ldt(x, xb + d * xs) - (q + ldt(ob, d)));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ frame_mix_store */
/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale))
* with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row
@@ -454,6 +550,44 @@ int ref_frame_mix_store(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ ras_pick */
/* Fish Audio's repetition-aware sampling, the choice between two draws a lane: the first draw
* ids[rep i] = first[rep i], unless it lies in [lo, hi) and the lane's window (its last `win`
* picks, `hist` [lanes, win], oldest first, -1 empty) holds it, in which case the alternative
* draw alt[rep i] is taken. The pick then enters the window, its oldest entry leaving. `clear` 1
* empties the lane's window first (a piece's first pick). A pick outside [lo, hi) (Fish's end of
* speech) is never redrawn. */
int ref_ras_pick(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3];
const RadTensor* ids = &a->t[4];
const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0);
const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0);
const int64_t n = numel(lane);
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n)
return RAD_E_SHAPE;
for (int64_t i = 0; i < n; ++i) {
const int64_t L = ldi(lane, i);
if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE;
}
for (int64_t i = 0; i < n; ++i) {
const int64_t hb = ldi(lane, i) * W;
if (clear)
for (int64_t w = 0; w < W; ++w) st_int(hist->dtype, hist->data, offlin(hist, hb + w), -1);
const int64_t f = ldi(first, rep * i);
int64_t pick = f;
if (f >= lo && f < hi)
for (int64_t w = 0; w < W; ++w)
if (ldi(hist, hb + w) == f) { pick = ldi(alt, rep * i); break; }
for (int64_t r = 0; r < rep; ++r) st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
for (int64_t w = 0; w + 1 < W; ++w)
st_int(hist->dtype, hist->data, offlin(hist, hb + w), ldi(hist, hb + w + 1));
st_int(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ end_status */
/* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end`
* (the model ended the piece), else the pick. */
@@ -763,6 +897,19 @@ int ref_int_affine(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ sub_i32 */
/* y[i] = x[i] - s[0], int32: a device length less a device offset. */
int ref_sub_i32(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
const int64_t n = numel(y);
if (n <= 0 || numel(x) < n || numel(s) < 1) return RAD_E_SHAPE;
const int64_t s0 = ldi(s, 0);
for (int64_t i = 0; i < n; ++i)
st_int(y->dtype, y->data, offlin(y, i), (int64_t)(int32_t)(ldi(x, i) - s0));
return RAD_OK;
}
/* ------------------------------------------------------------------ cu_repeat */
/* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's
* lengths live on the device (a window's frames, the latents a vocoder decodes per channel group),
+8 -3
View File
@@ -386,8 +386,8 @@ int ref_act_mul(const RadArgs* a, RadStream) {
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
const int act = p_enum(a, "act", kActs, 4, -1);
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" };
const int act = p_enum(a, "act", kActs, 5, -1);
if (act < 0) return RAD_E_INVAL;
REF_PAR_FOR(rows * n)
@@ -396,8 +396,13 @@ int ref_act_mul(const RadArgs* a, RadStream) {
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float g = ldt(A, ab + i * as);
/* quick_gelu is x * sigmoid(1.702 x) with the scaled value rounded to y's dtype
* first, exactly the unfused mul-then-act_mul pair this replaces. */
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
: act == 2 ? act_gelu_tanh(g) : act_sigmoid(g);
: act == 2 ? act_gelu_tanh(g)
: act == 3 ? act_sigmoid(g)
: act_sigmoid(round_dt(Y->dtype,
g * round_dt(RAD_BF16, 1.702f)));
stt(Y, yb + i * ys, round_dt(Y->dtype, v) * ldt(B, bb + i * bs));
}
}
+3 -33
View File
@@ -327,8 +327,8 @@ int ref_s2d3d(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
/* LTX-2's patchifier, both ways, over dense 2-D operands whose shapes give the sizes. A patch of
/* ------------------------------------------------------------------ pix_patch */
/* LTX-2's patchifier over dense 2-D operands whose shapes give the sizes. A patch of
* p x p pixels of C channels is one row of C p p values, channel c's offset (ph, pw) at
* c p p + pw p + ph with `order` wh (LTX-2's: the column offset outer) or c p p + ph p + pw with
* hw.
@@ -358,36 +358,6 @@ int ref_pix_patch(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* patch_pix8: patch rows x [R, w C p p] (R a frame's patch rows times its frames) to RGB bytes
* y [R p, w p C], each byte round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)) with rd
* x's dtype, to_rgba8's rule. */
int ref_patch_pix8(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
X->shape[1] % (C * p * p))
return RAD_E_SHAPE;
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
const int64_t xr = X->stride[0], yr = Y->stride[0];
const uint32_t dt = X->dtype;
uint8_t* yb = (uint8_t*)Y->data;
REF_PAR_FOR(R * p * w * p * C)
for (int64_t y = 0; y < R * p; ++y)
for (int64_t x = 0; x < w * p; ++x)
for (int64_t c = 0; c < C; ++c) {
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
patch_col(c, y % p, x % p, p, wh));
const float cl = std::min(std::max(v, -1.0f), 1.0f);
float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f);
u = std::min(std::max(u, 0.0f), 1.0f);
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ vol_index */
/* A volume's voxel coordinates, the rotary positions of attention over it: geom = (T, H, W), i32
* on the device; y i32 [3, n] component-major (at its own row pitch), voxel m = (t H + i) W + j's
@@ -522,7 +492,7 @@ int ref_tile_crop(const RadArgs* a, RadStream) {
*
* and across time blend_t: frame f of band kt, f < et = min(F of band kt-1, F of band kt,
* (tile_t - stride_t) scale_t), is mix(S_{kt-1}[F_{kt-1} - et + f], S_kt[f], f, et). The byte is
* patch_pix8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8
* to_rgba8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8
* [n (H scale p), (W scale p) C], frames first .. first + n - 1. A tile above, to the left or
* before is never short enough for its own blends to reach the margin read here (a tile not last
* on its axis spans more than `stride`), so these are the reference's values exactly. */
+77
View File
@@ -147,6 +147,83 @@ int ref_moe_scatter(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ router_topk_scatter */
/* The pair as one op, and the reference is the pair: the fused device kernel must be
* byte-identical to these two launches, in order, over the operands the fused op carries. The
* selection runs over the whole router's `n_expert` logits; the sort runs over this rank's slice,
* the fused op's `n_local` standing where `moe_scatter`'s `n_expert` names the slice it owns. */
int ref_router_topk_scatter(const RadArgs* a, RadStream s) {
if (!have(a, 6)) return RAD_E_INVAL;
const int64_t ne = p_int(a, "n_expert", 0);
const int64_t nl = p_int(a, "n_local", ne);
const int64_t k = p_int(a, "top_k", 1);
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_SHAPE;
const RadParam rp[] = { RAD_INT("n_expert", ne), RAD_INT("top_k", k),
RAD_INT("norm", p_int(a, "norm", 0)),
RAD_STR("dtype", p_str(a, "dtype", "bf16")) };
const RadArgs ra{ a->t, 3, rp, 4, nullptr, 0, nullptr, a->rank, a->world_size };
const int rc = ref_router_topk(&ra, s);
if (rc != RAD_OK) return rc;
/* The fused op's operands with `expert_w` removed -- the sort's input is the selection's
* output, named once, and `moe_scatter` takes it in operand slot 0. RadArgs reads a
* contiguous tensor array, so the four descriptors are laid out here, by value. */
const RadTensor t2[] = { a->t[1], a->t[3], a->t[4], a->t[5] };
const RadParam sp[] = { RAD_INT("n_expert", nl), RAD_INT("top_k", k),
RAD_INT("expert_base", p_int(a, "expert_base", 0)),
RAD_STR("protect", p_str(a, "protect", nullptr)) };
const RadArgs sa{ t2, 4, sp, 4, nullptr, 0, nullptr, a->rank, a->world_size };
return ref_moe_scatter(&sa, s);
}
/* ------------------------------------------------------------------ router_gemm_topk_scatter */
/* The router GEMM in front of the pair, and with `gate_b`/`gate` present the shared expert's
* one-column gate over the same input. The reference is the launches it stands in for, and the
* fused kernel must be byte-identical to them: the router's `gemm_nt`, the gate's `gemm_nt` at
* N = 1, then `router_topk_scatter` over the logits. `gate_b` and `gate` come together or not at
* all, and the operand count says which. */
int ref_router_gemm_topk_scatter(const RadArgs* a, RadStream s) {
/* NOT `have`: the required operands are not a prefix -- `gate_b` sits between the router's
* weight and the outputs, and it and `gate` are null slots in the gate-absent form. The nine
* required slots are checked by name; the pair is checked to come together or not at all. */
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
const bool gate_b = a->n_t > 2 && a->t[2].data != nullptr;
const bool gate = a->n_t > 9 && a->t[9].data != nullptr;
if (gate_b != gate) return RAD_E_INVAL;
for (int i : {0, 1, 3, 4, 5, 6, 7, 8})
if (!a->t[i].data) return RAD_E_INVAL;
const int64_t ne = p_int(a, "n_expert", 0);
const int64_t nl = p_int(a, "n_local", ne);
const int64_t k = p_int(a, "top_k", 1);
const int64_t K = p_int(a, "K", 0);
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne || K <= 0) return RAD_E_SHAPE;
const char* dt = p_str(a, "dtype", "bf16");
/* The router: a [M, K] x b [n_expert, K]^T -> logits. gemm_nt takes a, b, y contiguously. */
const RadTensor g3[] = { a->t[0], a->t[1], a->t[3] };
const RadParam gp[] = { RAD_INT("N", ne), RAD_INT("K", K), RAD_STR("dtype", dt) };
const RadArgs ga{ g3, 3, gp, 3, nullptr, 0, nullptr, a->rank, a->world_size };
const int gc = ref_gemm_nt(&ga, s);
if (gc != RAD_OK) return gc;
/* The shared expert's gate: the same arithmetic at N = 1, beside the router, over the same
* `a`. The pair was checked to come together. */
if (gate) {
const RadTensor p3[] = { a->t[0], a->t[2], a->t[9] };
const RadParam pp[] = { RAD_INT("N", 1), RAD_INT("K", K), RAD_STR("dtype", dt) };
const RadArgs pa{ p3, 3, pp, 3, nullptr, 0, nullptr, a->rank, a->world_size };
const int pc = ref_gemm_nt(&pa, s);
if (pc != RAD_OK) return pc;
}
/* The pair over the logits the GEMM just wrote. Every parameter the pair reads is a parameter
* of this op, under the same name -- the fused lists are unions, so `a`'s list passes through. */
const RadTensor t6[] = { a->t[3], a->t[4], a->t[5], a->t[6], a->t[7], a->t[8] };
const RadArgs fa{ t6, 6, a->p, a->n_p, nullptr, 0, nullptr, a->rank, a->world_size };
return ref_router_topk_scatter(&fa, s);
}
/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */
/* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks
* row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per
+15 -2
View File
@@ -151,6 +151,8 @@ int ref_attn_cross (const RadArgs*, RadStream);
int ref_table_add (const RadArgs*, RadStream);
int ref_mix_rows (const RadArgs*, RadStream);
int ref_chan_stats (const RadArgs*, RadStream);
/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */
int ref_sam_attn (const RadArgs*, RadStream);
int ref_kv_store (const RadArgs*, RadStream);
int ref_rope (const RadArgs*, RadStream);
int ref_rope_table (const RadArgs*, RadStream);
@@ -190,7 +192,6 @@ int ref_pixel_norm(const RadArgs*, RadStream);
int ref_d2s3d(const RadArgs*, RadStream);
int ref_s2d3d(const RadArgs*, RadStream);
int ref_pix_patch(const RadArgs*, RadStream);
int ref_patch_pix8(const RadArgs*, RadStream);
int ref_vol_index(const RadArgs*, RadStream);
int ref_attn_na3d(const RadArgs*, RadStream);
int ref_tile_grid(const RadArgs*, RadStream);
@@ -210,8 +211,10 @@ int ref_snake(const RadArgs*, RadStream);
int ref_snake_aa(const RadArgs*, RadStream);
int ref_cfg_topk_sample(const RadArgs*, RadStream);
int ref_rvq_embed(const RadArgs*, RadStream);
int ref_vq_encode(const RadArgs*, RadStream);
int ref_frame_mix_store(const RadArgs*, RadStream);
int ref_end_status(const RadArgs*, RadStream);
int ref_ras_pick(const RadArgs*, RadStream);
int ref_frame_store(const RadArgs*, RadStream);
int ref_resample_nearest(const RadArgs*, RadStream);
int ref_fourier_embed(const RadArgs*, RadStream);
@@ -223,6 +226,7 @@ int ref_interleave2(const RadArgs*, RadStream);
int ref_iota(const RadArgs*, RadStream);
int ref_cu_repeat(const RadArgs*, RadStream);
int ref_int_affine(const RadArgs*, RadStream);
int ref_sub_i32(const RadArgs*, RadStream);
int ref_chan_affine(const RadArgs*, RadStream);
int ref_conv2d_nhwc(const RadArgs*, RadStream);
int ref_im2col_nhwc(const RadArgs*, RadStream);
@@ -245,6 +249,8 @@ int ref_dflash_conv (const RadArgs*, RadStream);
/* ---- mixture of experts */
int ref_router_topk (const RadArgs*, RadStream);
int ref_moe_scatter (const RadArgs*, RadStream);
int ref_router_topk_scatter(const RadArgs*, RadStream);
int ref_router_gemm_topk_scatter(const RadArgs*, RadStream);
int ref_moe_gemm (const RadArgs*, RadStream);
int ref_moe_gemm_q (const RadArgs*, RadStream);
int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream);
@@ -282,6 +288,7 @@ void ref_collective_fini(void*);
/* ---- sampling */
int ref_sample_penalties (const RadArgs*, RadStream);
int ref_sample_dry (const RadArgs*, RadStream);
int ref_sample_ngram_ban (const RadArgs*, RadStream);
int ref_sample_temp (const RadArgs*, RadStream);
int ref_sample_topk (const RadArgs*, RadStream);
int ref_sample_topp (const RadArgs*, RadStream);
@@ -400,6 +407,7 @@ REF_SHAPE_FN(ref_attn_cross);
REF_SHAPE_FN(ref_table_add);
REF_SHAPE_FN(ref_mix_rows);
REF_SHAPE_FN(ref_chan_stats);
REF_SHAPE_FN(ref_sam_attn);
REF_SHAPE_FN(ref_kv_store);
REF_SHAPE_FN(ref_rope);
REF_SHAPE_FN(ref_rope_table);
@@ -436,7 +444,6 @@ REF_SHAPE_FN(ref_pixel_norm);
REF_SHAPE_FN(ref_d2s3d);
REF_SHAPE_FN(ref_s2d3d);
REF_SHAPE_FN(ref_pix_patch);
REF_SHAPE_FN(ref_patch_pix8);
REF_SHAPE_FN(ref_vol_index);
REF_SHAPE_FN(ref_attn_na3d);
REF_SHAPE_FN(ref_tile_grid);
@@ -452,8 +459,10 @@ REF_SHAPE_FN(ref_snake);
REF_SHAPE_FN(ref_snake_aa);
REF_SHAPE_FN(ref_cfg_topk_sample);
REF_SHAPE_FN(ref_rvq_embed);
REF_SHAPE_FN(ref_vq_encode);
REF_SHAPE_FN(ref_frame_mix_store);
REF_SHAPE_FN(ref_end_status);
REF_SHAPE_FN(ref_ras_pick);
REF_SHAPE_FN(ref_frame_store);
REF_SHAPE_FN(ref_resample_nearest);
REF_SHAPE_FN(ref_fourier_embed);
@@ -465,6 +474,7 @@ REF_SHAPE_FN(ref_interleave2);
REF_SHAPE_FN(ref_iota);
REF_SHAPE_FN(ref_cu_repeat);
REF_SHAPE_FN(ref_int_affine);
REF_SHAPE_FN(ref_sub_i32);
REF_SHAPE_FN(ref_chan_affine);
REF_SHAPE_FN(ref_conv2d_nhwc);
REF_SHAPE_FN(ref_im2col_nhwc);
@@ -485,6 +495,8 @@ REF_SHAPE_FN(ref_dflash_conv);
REF_SHAPE_FN(ref_router_topk);
REF_SHAPE_FN(ref_moe_scatter);
REF_SHAPE_FN(ref_router_topk_scatter);
REF_SHAPE_FN(ref_router_gemm_topk_scatter);
REF_SHAPE_FN(ref_moe_gemm);
REF_SHAPE_FN(ref_moe_gemm_q);
REF_SHAPE_FN(ref_moe_gemm_q_mod4);
@@ -508,6 +520,7 @@ REF_SHAPE_FN(ref_all_gather);
REF_SHAPE_FN(ref_sample_penalties);
REF_SHAPE_FN(ref_sample_dry);
REF_SHAPE_FN(ref_sample_ngram_ban);
REF_SHAPE_FN(ref_sample_temp);
REF_SHAPE_FN(ref_sample_topk);
REF_SHAPE_FN(ref_sample_topp);
+114 -9
View File
@@ -357,7 +357,10 @@ static const RadParamSpec pAttnPaged[] = {
/* For libr4d's scratch hook, which sizes its split-KV partial buffer at declare
* (num_seqs * q_len * q_heads * splits rows; gqa is only the head ratio). Ref ignores them;
* they are here because both plugins must agree on the parameter list. */
P_INTO("n_head"), P_INTO("max_seqs")
P_INTO("n_head"), P_INTO("max_seqs"),
/* The e4m3 products a caller accepts (docs/OPS.md). A permission, not a request: ref computes
* the exact form whatever it says. */
P_INTO("prefill_fp8")
};
static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
@@ -383,6 +386,16 @@ static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") };
/* The SAM tower's attention. `q`, `k` and `v` are the three column slices of one fused projection,
* so each is read at its own row pitch. The two rel_pos tables are weights: [2*L-1, head_dim] with
* L the window (or the grid for a global layer), resampled along dim 0 when a geometry needs it.
* `grid_h` x `grid_w` rows a segment, `window` 0 for a whole-segment tile. */
static const RadParamSpec pSamAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("grid_h"), P_INT("grid_w"), P_INT("window"),
P_F64("scale"), P_STR("dtype") };
static const RadOperandSpec oSamAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out"), WGT("rel_pos_h"), WGT("rel_pos_w") };
/* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by
* them; optional because a bf16 cache has none. */
static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"),
@@ -480,6 +493,29 @@ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("t
static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"),
OUT("expert_offset"), OUT("expert_count") };
/* The pair as one op: the union of the two parameter lists, and their operands with the shared
* `expert_ids` named once, as an output. Same schema as libr4d's fused row. */
static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"),
P_INTO("n_local"), P_INT("top_k"),
P_INT("norm"), P_STR("dtype"),
P_INTO("expert_base"),
P_STRO("protect") };
static const RadOperandSpec oRouterTopkScatter[] = { OPD("logits"), OUT("expert_ids"),
OUT("expert_w"), OUT("sorted_tok"),
OUT("expert_offset"),
OUT("expert_count") };
/* The router GEMM in front of the pair, and the gate's one-column GEMM beside it: the union of
* the three operand lists with `logits` named once, as the GEMM's output. */
static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"),
P_INT("n_expert"), P_INTO("n_local"),
P_INT("top_k"), P_INT("norm"),
P_STR("dtype"), P_INTO("expert_base"),
P_STRO("protect") };
static const RadOperandSpec oRouterGemmTopkScatter[] = {
OPD("a"), WGT("b"), WGT_O("gate_b"), OUT("logits"), OUT("expert_ids"), OUT("expert_w"),
OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count"), OUT_O("gate") };
/* `a_order` says which rows the activation has; a routed block's two grouped GEMMs differ. gate_up
* reads the block input, one row per token, so sorted row i gathers `a[sorted_tok[i] / top_k]`.
* down reads gate_up's output, already one row per (token, slot) in scatter order, so row i is row
@@ -679,6 +715,13 @@ static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD
* is a whole DRY sequence breaker and never penalised. Absent, no token is exempt. */
static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD_O("breakers") };
/* The windowed n-gram ban: penalties' operands plus a {n, window} pair a row.
* `whitelist` is optional: a bitmask plane [M, ceil(n_vocab/32)] like sample_mask's, a SET bit
* marking a token exempt from the ban (the reference's whitelist, removed from the banned set
* before the -inf writes). Absent, nothing is exempt. Rows are indexed by the sampled position,
* not by mask_row: every row the op bans reads its own words. */
static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD("ngram"), OPD_O("whitelist") };
static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") };
/* `bitmask` is [rows, ceil(n_vocab/32)] uint32, addressed by the row's mask_row -- which is -1 for
* an unconstrained sequence, so the plane is shared and shorter than M. */
@@ -898,7 +941,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
/* ---- audio generation (ref_audio.cpp) */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
P_INTO("cu_div") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -914,19 +958,28 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"),
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
P_INTO("sup_hi"), P_F64O("penalty") };
P_INTO("sup_hi"), P_F64O("penalty"),
P_F64O("top_p") };
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
P_STR("dtype"), P_INTO("round") };
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
P_STR("dtype") };
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
WGT("out_w"), WGT("out_b"), OUT("codes") };
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
P_INTO("rep"), P_STR("dtype") };
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
OPD("frame"), OPD("status"), INOUT("dst") };
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
P_INTO("rep"), P_INTO("clear") };
static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"),
OUT("ids") };
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
P_INTO("rep"), P_INTO("skip") };
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
@@ -956,6 +1009,8 @@ static const RadOperandSpec oIota[] = { OUT("y") };
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
static const RadParamSpec pSubI32[] = { P_INT("M") };
static const RadOperandSpec oSubI32[] = { OPD("x"), OPD("s"), OUT("y") };
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
/* ================================================================== the schema table */
@@ -1327,6 +1382,14 @@ static const RadOpSchema kSchemas[] = {
{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d),
"3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the "
"kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." },
{ "sam_attn", ARR(pSamAttn), ARR(oSamAttn),
"Unlimited-OCR's SAM tower attention: per cu segment of grid_h*grid_w rows in raster grid order, "
"pad to multiples of `window` with ZERO rows (window_partition, after norm1), cut into window x "
"window tiles and attend each tile to all of its rows; `window` 0 is one tile over the segment. "
"logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w], dotted over the head's whole head_dim, "
"softmax in f32 over the tile's keys (pad keys included), out = sum p*v, written back in segment "
"row order with pad rows dropped. The tables are [2*L-1, head_dim], linearly resampled along "
"dim 0 when a geometry's axes need it (get_rel_pos)." },
{ "kv_store", ARR(pKvStore), ARR(oKvStore),
"Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is "
"INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." },
@@ -1398,6 +1461,16 @@ static const RadOpSchema kSchemas[] = {
"sorts only its own slice, and the slots that went elsewhere simply contribute nothing to this "
"rank's partial -- which the block's end-of-block all-reduce then sums. `expert_base` absent "
"or 0 with n_expert the model's count is the whole-model case." },
{ "router_topk_scatter", ARR(pRouterTopkScatter), ARR(oRouterTopkScatter),
"`router_topk` then `moe_scatter`, in one launch: exactly those two and in that order, over "
"the operands they share. The reference IS the pair -- the fused device kernel claims to be "
"byte-identical to these two launches, and this is what it is measured against. The sort's "
"outputs are sized by `n_local`, this rank's slice; absent it is the router's count." },
{ "router_gemm_topk_scatter", ARR(pRouterGemmTopkScatter), ARR(oRouterGemmTopkScatter),
"`gemm_nt` of `a` against the router `b`, then `router_topk_scatter` over those logits, and "
"with `gate_b`/`gate` present the shared expert's `gemm_nt` at N = 1 over the same `a`. As "
"with the pair, the reference IS the launches: the gate weight and output come together or not "
"at all, and the operand count says which." },
{ "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm),
"y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range contains i. "
"`a_order` picks row(i): \"token\" gathers a[sorted_tok[i] / top_k] from an activation with one "
@@ -1524,6 +1597,15 @@ static const RadOpSchema kSchemas[] = {
"repeats capped at the row's dry_rep_limit. Only lengths at or above allowed_length count, and "
"a token the optional `breakers` plane marks is never penalised. dry_penalty_last_n windows the "
"TAIL of the history; 0 turns the stage off for the row. Columns are ids less vocab_off." },
{ "sample_ngram_ban", ARR(pPenal), ARR(oNgramBan),
"The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor): bans, "
"by setting -infinity, every token that would complete an n-gram the last `window` tokens of "
"the row's history already contain. `ngram` is one i32 {n, window} pair a row; the window "
"bounds the n-gram's START index, as in the reference, window <= 0 searches the whole span and "
"n 0 is off. The optional `whitelist` bitmask (a SET bit, word w bit b covering column 32w + b, "
"the row's own plane row) exempts a token from the ban, as the reference's "
"`banned.difference_update(whitelist)` does; absent, nothing is exempt. Columns are ids less "
"vocab_off." },
{ "sample_temp", ARR(pMVocab), ARR(oTemp),
"logits /= temp, per row. temp <= 0 leaves the row untouched -- greedy decoding is "
"sample_argmax, and a temperature of zero silently meaning something else is how a sampler "
@@ -1746,9 +1828,6 @@ static const RadOpSchema kSchemas[] = {
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch),
"an image [H, W C] to patch rows [H/p, (W/p) C p p], channel c's (ph, pw) at c p p + pw p + ph "
"(order wh) or c p p + ph p + pw (hw)." },
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch),
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule, pix_patch's channel "
"order." },
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex),
"a volume's voxel coordinates (t, i, j), component-major: attention's rotary positions." },
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid),
@@ -1761,7 +1840,7 @@ static const RadOpSchema kSchemas[] = {
{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch),
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h of each tile with the one "
"above and the one to its left, then blend_t of each time band with the one before, each kept to "
"its stride, then patch_pix8's bytes." },
"its stride, then to_rgba8's bytes." },
{ "stft_logmel", ARR(pStftMel), ARR(oStftMel),
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel filterbank, every "
"stored tensor rounded to y's dtype: frames S / hop, columns h n_mel + m." },
@@ -1803,11 +1882,19 @@ static const RadOpSchema kSchemas[] = {
"a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum "
"of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or "
"with `round` 1 one f32 sum in codebook order times scale, rounded once." },
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
"one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest "
"cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded "
"once." },
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
"a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, "
"stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." },
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
{ "ras_pick", ARR(pRasPick), ARR(oRasPick),
"repetition-aware sampling: ids[rep i] = alt[rep i] where first[rep i] is in [lo, hi) and in "
"the lane's window of its last `win` picks (hist [lanes, win], -1 empty, cleared first with "
"`clear` 1), else first[rep i]; the pick then enters the window." },
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = "
"codes[k, rep i] when frame >= skip and status[lane] >= 0." },
@@ -1841,6 +1928,8 @@ static const RadOpSchema kSchemas[] = {
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and "
"bounds derived from a pass's device geometry." },
{ "sub_i32", ARR(pSubI32), ARR(oSubI32),
"y[i] = x[i] - s[0], int32: a device length less a device offset." },
};
/* ================================================================== the kernel table */
@@ -2166,6 +2255,9 @@ SIMPLE("ref_attn_cross", "attn_cross", "attn",
ref_attn_cross),
SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT,
ref_attn_na3d),
SIMPLE("ref_sam_attn", "sam_attn", "attn",
"SAM tower attention: windowed tiles with decomposed relative position", DT_FLOAT,
ref_sam_attn),
ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_kv_store, nullptr),
@@ -2181,6 +2273,12 @@ SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routin
ref_router_topk),
SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
"i32 indices", ref_moe_scatter),
SIMPLE("ref_router_topk_scatter", "router_topk_scatter", "moe",
"the selection and the sort in one op, run as exactly the pair", DT_FLOAT,
ref_router_topk_scatter),
SIMPLE("ref_router_gemm_topk_scatter", "router_gemm_topk_scatter", "moe",
"the router GEMM, the selection and the sort in one op, run as exactly the launches",
DT_FLOAT, ref_router_gemm_topk_scatter),
SIMPLE("ref_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
ref_moe_gemm),
ROW_CB("ref_moe_gemm_q", "moe_gemm_q", "moe",
@@ -2265,6 +2363,8 @@ SIMPLE("ref_sample_logprobs", "sample_logprobs", "sample", "the raw distribution
DT_FLOAT, ref_sample_logprobs),
SIMPLE("ref_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT,
ref_sample_dry),
SIMPLE("ref_sample_ngram_ban", "sample_ngram_ban", "sample",
"windowed no-repeat-ngram ban", DT_FLOAT, ref_sample_ngram_ban),
SIMPLE("ref_sample_typical", "sample_typical", "sample", "locally typical narrowing in place",
DT_FLOAT, ref_sample_typical),
SIMPLE("ref_sample_xtc", "sample_xtc", "sample", "exclude-top-choices narrowing in place",
@@ -2361,7 +2461,6 @@ SIMPLE("ref_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors comp
SIMPLE("ref_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, ref_d2s3d),
SIMPLE("ref_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, ref_s2d3d),
SIMPLE("ref_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, ref_pix_patch),
SIMPLE("ref_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, ref_patch_pix8),
SIMPLE("ref_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, ref_vol_index),
SIMPLE("ref_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, ref_tile_grid),
SIMPLE("ref_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, ref_tile_crop),
@@ -2382,10 +2481,14 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
DT_FLOAT, ref_cfg_topk_sample),
SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
DT_FLOAT, ref_rvq_embed),
SIMPLE("ref_vq_encode", "vq_encode", "elem",
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode),
SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane",
DT_FLOAT, ref_frame_mix_store),
SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
ref_end_status),
SIMPLE("ref_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane",
DT_ANY, ref_ras_pick),
SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
ref_frame_store),
SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
@@ -2406,6 +2509,8 @@ SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_i
SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat),
SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
ref_int_affine),
SIMPLE("ref_sub_i32", "sub_i32", "elem", "a device int32 vector less a device scalar", DT_ANY,
ref_sub_i32),
};
/* ================================================================== plugin exports */
+197
View File
@@ -0,0 +1,197 @@
/* ref_sam_attn.cpp -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative
* position (arch/common/rad_block_sam.h).
*
* The reference is the checkpoint's own deepencoder.py (Attention.forward and
* add_decomposed_rel_pos), whose logits are
*
* scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w]
*
* where Rh = get_rel_pos(rel_pos_h, q_h, k_h) indexes the table at (i_h - j_h + len - 1) and the dot
* runs over the whole head_dim of the head's own q (deepencoder computes r_q of shape
* (B*heads, q_h, q_w, head_dim) and einsums "bhwc,hkc->bhwk"). So the per-pair term folds into
* neither q, k nor v: no plain attention op can carry it, which is why this op exists.
*
* ============================== Windows ==============================
*
* Each cu segment is grid_h * grid_w rows in row-major grid order. With `window` > 0 the segment is
* padded to multiples of `window` with ZERO rows and cut into window x window tiles, exactly as
* window_partition does after norm1: the pad rows are keys AND values of their tile, so their
* logits (which carry the rel terms even though q.k is 0) take part in the softmax, and their v is
* zero. `window` 0 is one tile over the whole segment (the reference's global blocks).
*
* ============================== Table resizing ==============================
*
* get_rel_pos linearly interpolates the table along dim 0 when its length is not
* 2*max(q,k) - 1 (F.interpolate, mode linear, align_corners False). Every geometry the tower
* declares matches exactly, but a non-square global grid has axes of different extents, so the
* resampling is implemented here rather than assumed away.
*
* ============================== Numerics ==============================
*
* f32 throughout: q, k, v and the tables are widened once, every dot and softmax accumulates in
* f32 with the max subtracted, and the output is rounded once to the operand's dtype. Summation
* order is fixed (increasing channel, then key), so two runs agree bit for bit at any thread count.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <algorithm>
#include <cmath>
#include <vector>
using namespace ref;
namespace {
/* A rel_pos table as f32 rows of `hd`, resampled to `want` rows when its own length differs.
* F.interpolate(..., size=want, mode="linear") with align_corners False: output d samples the input
* at (d + 0.5) * rows / want - 0.5, clamped to the ends, linearly between the neighbours. */
static std::vector<float> table_rows(const RadTensor* t, int64_t hd, int64_t want) {
const int64_t rows = hd > 0 ? numel(t) / hd : 0;
std::vector<float> raw((size_t)(rows * hd), 0.0f);
const int64_t st = laststride(t);
for (int64_t r = 0; r < rows; ++r) {
const int64_t base = rowoff(t, r, hd);
for (int64_t c = 0; c < hd; ++c) raw[(size_t)(r * hd + c)] = ldt(t, base + c * st);
}
if (rows == want || rows <= 0 || want <= 0) return raw;
std::vector<float> out((size_t)(want * hd), 0.0f);
const double span = (double)rows / (double)want;
for (int64_t d = 0; d < want; ++d) {
double src = ((double)d + 0.5) * span - 0.5;
if (src < 0.0) src = 0.0;
if (src > (double)(rows - 1)) src = (double)(rows - 1);
const int64_t i0 = (int64_t)src;
const int64_t i1 = i0 + 1 < rows ? i0 + 1 : i0;
const float f = (float)(src - (double)i0);
for (int64_t c = 0; c < hd; ++c) {
const float a = raw[(size_t)(i0 * hd + c)], b = raw[(size_t)(i1 * hd + c)];
out[(size_t)(d * hd + c)] = a + (b - a) * f;
}
}
return out;
}
} /* namespace */
/* See the file header for the semantics. `cu_seqlens` absent is one segment of every row: the
* reference's single-view form. */
int ref_sam_attn(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3];
const RadTensor *o = &a->t[4], *th_tab = &a->t[5], *tw_tab = &a->t[6];
const int64_t hd = p_int(a, "head_dim", 0);
const int64_t nh = p_int(a, "n_head", 0);
const int64_t gh = p_int(a, "grid_h", 0);
const int64_t gw = p_int(a, "grid_w", 0);
const int64_t win = p_int(a, "window", 0);
if (hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_SHAPE;
const int64_t W = nh * hd, R = gh * gw;
if (!q->data || !k->data || !v->data || !o->data || !th_tab->data || !tw_tab->data)
return RAD_E_INVAL;
for (const RadTensor* t : { q, k, v, o })
if (t->rank < 2 || t->shape[t->rank - 1] != W) return RAD_E_SHAPE;
const int64_t M = numel(q) / W;
if (M <= 0) return RAD_E_SHAPE;
if (numel(k) != M * W || numel(v) != M * W || numel(o) < M * W) return RAD_E_SHAPE;
/* Segments: cu[s]..cu[s+1], each exactly one grid. */
int64_t nseq = 1;
if (cu->data) {
if (cu->rank == 0 || numel(cu) < 2) return RAD_E_SHAPE;
nseq = numel(cu) - 1;
if (cu_at(cu, 0) != 0 || cu_at(cu, nseq) != M) return RAD_E_SHAPE;
for (int64_t s = 0; s < nseq; ++s)
if (cu_at(cu, s + 1) - cu_at(cu, s) != R) return RAD_E_SHAPE;
} else if (M != R) {
return RAD_E_SHAPE;
}
const float scale = p_f32(a, "scale", (float)(1.0 / std::sqrt((double)hd)));
/* The tile geometry: window x window, or the whole grid. Table lengths follow the tile axes. */
const int64_t th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
const int64_t keys = th * tw;
if (numel(th_tab) < hd || numel(tw_tab) < hd) return RAD_E_SHAPE;
std::vector<float> Rh = table_rows(th_tab, hd, 2 * th - 1);
std::vector<float> Rw = table_rows(tw_tab, hd, 2 * tw - 1);
/* Every (channel-ordered) dot is written out in one place so the order is explicit: q[c] times
* the row's element c, increasing c. */
auto dot = [hd](const float* x, const float* y) {
float s = 0.0f;
for (int64_t c = 0; c < hd; ++c) s += x[c] * y[c];
return s;
};
/* One thread owns one output row; the work unit is about keys * head_dim per head. */
REF_PAR_FOR(nseq * R * nh * keys * hd)
for (int64_t work = 0; work < nseq * R; ++work) {
const int64_t s = work / R, r = work % R;
const int64_t ih = r / gw, iw = r % gw;
const int64_t ty = win > 0 ? ih / win : 0, tx = win > 0 ? iw / win : 0;
const int64_t lh = ih - ty * th, lw = iw - tx * tw;
const int64_t base = cu->data ? cu_at(cu, s) : 0;
const int64_t out_row = base + r;
/* logits[keys], qt[hd], acc[hd]. */
float* buf = ws_get(keys + 2 * hd);
float* logits = buf;
float* qt = buf + keys;
float* acc = qt + hd;
for (int64_t h = 0; h < nh; ++h) {
const int64_t qbase = rowoff(q, out_row, W) + h * hd;
const int64_t qst = laststride(q);
for (int64_t c = 0; c < hd; ++c) qt[c] = ldt(q, qbase + c * qst);
for (int64_t jh = 0; jh < th; ++jh) {
const float hr = dot(qt, &Rh[(size_t)((lh - jh + th - 1) * hd)]);
for (int64_t jw = 0; jw < tw; ++jw) {
float lgt = hr + dot(qt, &Rw[(size_t)((lw - jw + tw - 1) * hd)]);
const int64_t kh = ty * th + jh, kw = tx * tw + jw;
if (kh < gh && kw < gw) {
const int64_t krow = base + kh * gw + kw;
const int64_t kb = rowoff(k, krow, W) + h * hd;
const int64_t ks = laststride(k);
float s_ = 0.0f;
for (int64_t c = 0; c < hd; ++c) s_ += qt[c] * ldt(k, kb + c * ks);
lgt += scale * s_;
}
logits[jh * tw + jw] = lgt;
}
}
/* Softmax in f32 with the max subtracted, then the weighted sum of v. */
float m = -INFINITY;
for (int64_t j = 0; j < keys; ++j) m = logits[j] > m ? logits[j] : m;
float sum = 0.0f;
for (int64_t j = 0; j < keys; ++j) {
logits[j] = ref_exp(logits[j] - m);
sum += logits[j];
}
for (int64_t c = 0; c < hd; ++c) acc[c] = 0.0f;
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t jh = 0; jh < th; ++jh) {
const int64_t kh = ty * th + jh;
if (kh >= gh) continue; /* pad rows carry v = 0 */
for (int64_t jw = 0; jw < tw; ++jw) {
const int64_t kw = tx * tw + jw;
if (kw >= gw) continue;
const float p = logits[jh * tw + jw] * inv;
if (p == 0.0f) continue;
const int64_t krow = base + kh * gw + kw;
const int64_t vb = rowoff(v, krow, W) + h * hd;
const int64_t vs = laststride(v);
for (int64_t c = 0; c < hd; ++c) acc[c] += p * ldt(v, vb + c * vs);
}
}
const int64_t ob = rowoff(o, out_row, W) + h * hd;
const int64_t os = laststride(o);
for (int64_t c = 0; c < hd; ++c) stt(o, ob + c * os, acc[c]);
}
}
return RAD_OK;
}
+104
View File
@@ -35,6 +35,7 @@
#include <algorithm>
#include <cfloat>
#include <unordered_map>
#include <vector>
using namespace ref;
@@ -235,6 +236,109 @@ int ref_sample_dry(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_ngram_ban */
/* The windowed no-repeat-ngram ban: Unlimited-OCR's `SlidingWindowNoRepeatNgramProcessor`
* (modeling_unlimitedocr.py:353-383), which SGLang ships as
* DeepseekOCRNoRepeatNGramLogitProcessor. With the row's history `s[0, hl)` (oldest first, `hl`
* committed tokens including the one just emitted), `n` and `w` from the `ngram` plane (an i32
* pair a row, {n-gram length, window}):
*
* search_start = max(0, hl - w) (w <= 0: the whole span)
* search_end = hl - n + 1
* prefix = s[hl - n + 1, hl) (empty at n == 1)
* for idx in [search_start, search_end):
* if s[idx, idx + n - 1) == prefix: ban s[idx + n - 1]
*
* A banned token's logit becomes -infinity, exactly as the reference writes it, so the argmax and
* every later stage see the same distribution. The n-gram that spans the window boundary is one
* of the searched ones, as in the reference: the window is applied to the START index, not to the
* n-gram's end.
*
* Ids are global and columns are global less `vocab_off`; a banned token on another rank's shard
* is that rank's to mask. Rows whose n is 0 (the default) are untouched, so a request without the
* ban leaves the logits bit for bit as they were. The scan is O(w * n) a row and compares
* integers, so every implementation (this one, libavx, libr4d) agrees by construction.
*
* The optional `whitelist` bitmask is the reference's whitelist: a token whose column bit is set
* in the row's own plane row is removed from the banned set before the -inf writes
* (`banned.difference_update(self.whitelist)`, modeling_unlimitedocr.py:379), so it is never
* banned. Absent, nothing is exempt -- the default serving form, bit-identical to the ban
* without the operand. */
int ref_sample_ngram_ban(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3];
const RadTensor* wl = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(param_rows(pr, M, &R));
const int64_t hmax = numel(hist) / M;
if (hmax <= 0) return RAD_E_SHAPE;
/* One {n, window} pair a row. At least M pairs, so a plane shared by sparser row sets is not
* read past its end. */
if (numel(ng) < 2 * M) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
const int64_t wwords = (n_vocab + 31) / 32;
if (wl && wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return RAD_E_DTYPE;
if (wl && numel(wl) < M * wwords) return RAD_E_SHAPE;
REF_PAR_FOR(M * hmax)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
const int64_t nb = rowoff(ng, m, 2), ns = laststride(ng);
const int64_t n = ld_int(ng->dtype, ng->data, nb);
const int64_t win_req = ld_int(ng->dtype, ng->data, nb + ns);
if (n <= 0) continue;
/* The whole staged span; the window below keeps its tail. last_n -1 is hist_window's
* "the whole span". */
int64_t ho = 0, hl = 0;
if (!hist_window(sp, -1, hmax, &ho, &hl)) continue;
if (hl < n) continue;
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
const int64_t search_start = hl - win;
const int64_t search_end = hl - n + 1;
if (search_end <= search_start) continue;
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t wb = wl ? rowoff(wl, m, wwords) : 0, ws = wl ? laststride(wl) : 0;
auto tok_at = [&](int64_t i) {
return ld_int(hist->dtype, hist->data, hb + i * hs);
};
/* The reference removes the whitelist from the banned set before it writes; a column
* whose bit is set in the row's whitelist words is therefore never written. */
auto exempt = [&](int64_t col) {
if (!wl) return false;
const uint32_t word = (uint32_t)ld_int(wl->dtype, wl->data, wb + (col / 32) * ws);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
/* n == 1 bans every token in the window: the prefix is empty, as in the reference.
* The prefix is read once, not per search position: it is the same n-1 tokens
* compared at every idx, and the row's history is short (the staged span). */
const int64_t plen = n - 1, p0 = hl - plen;
std::vector<int64_t> pref((size_t)plen);
for (int64_t j = 0; j < plen; ++j) pref[(size_t)j] = tok_at(p0 + j);
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) != pref[(size_t)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) continue;
if (exempt(col)) continue;
stt(lg, lb + col * ls, -INFINITY);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_temp */
/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */
int ref_sample_temp(const RadArgs* a, RadStream) {
+154 -15
View File
@@ -1408,6 +1408,40 @@ int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("chan_stats", operand, out);
}
/* The SAM tower's attention (ref_sam_attn.cpp): a row of `n_head * head_dim`, one raster
* grid_h x grid_w segment a cu entry, and the two rel_pos tables. Their length follows the contract
* in arch/common/rad_block_sam.h: 2*maxdist-1 rows with maxdist the window, or the longer grid axis
* for a global layer (which is the length a resampled table needs; the op resamples along dim 0
* either way). */
int ref_sam_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t nh = gi(p, n_p, "n_head", 0);
const int64_t gh = gi(p, n_p, "grid_h", 0);
const int64_t gw = gi(p, n_p, "grid_w", 0);
const int64_t win = gi(p, n_p, "window", 0);
if (M <= 0 || hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_UNSUPPORTED;
/* A shape hook answers "describe this geometry", so an unbuildable one spells E_UNSUPPORTED
* (the harness convention); the kernels' own launch checks report E_SHAPE for the same
* inputs. */
const int64_t W = nh * hd;
const int64_t S = n_seq_of(p, n_p);
const int64_t maxd = win > 0 ? win : (gh > gw ? gh : gw);
const int64_t tab = 2 * maxd - 1;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, W }); /* q */
o.t(D, { M, W }); /* k */
o.t(D, { M, W }); /* v */
/* [0, ..., M], the batch's shape, not a draw. */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, W }); /* out */
o.t(D, { tab, hd }); /* rel_pos_h */
o.t(D, { tab, hd }); /* rel_pos_w */
return o.finish("sam_attn", operand, out);
}
int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
@@ -1679,8 +1713,55 @@ int ref_moe_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
return o.finish("moe_scatter", operand, out);
}
/* `a_order` decides the activation's row count: one per token, or one per (token, slot) in
* scatter order. */
/* The two shape lists concatenated, with `expert_ids` named ONCE as an output -- it is what the
* selection writes and what the sort reads. The sort's three outputs are sized by THIS RANK'S
* SLICE (`n_local`, absent means the slice is the router), exactly as in libr4d's shape. */
int ref_router_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t ne = gi(p, n_p, "n_expert", 0);
const int64_t k = gi(p, n_p, "top_k", 0);
const int64_t nl = gi(p, n_p, "n_local", ne);
if (M <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, ne }); /* logits */
o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */
o.t(D, { M, k }); /* expert_w */
o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */
o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */
o.t((uint32_t)RAD_I32, { nl }); /* expert_count */
return o.finish("router_topk_scatter", operand, out);
}
/* The router GEMM's list, the pair's list, and -- with the gate present -- the gate's one-column
* list, with `logits` named once as the GEMM's output. `gate_b`/`gate` come together or not: the
* operand count carries it, as in libr4d's shape. */
int ref_router_gemm_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t K = gi(p, n_p, "K", 0);
const int64_t ne = gi(p, n_p, "n_expert", 0);
const int64_t k = gi(p, n_p, "top_k", 0);
const int64_t nl = gi(p, n_p, "n_local", ne);
if (M <= 0 || K <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne)
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, K }); /* a */
o.t(D, { ne, K }); /* b: the router */
o.t(D, { 1, K }); /* gate_b: the shared expert's gate */
o.t(D, { M, ne }); /* logits */
o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */
o.t(D, { M, k }); /* expert_w */
o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */
o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */
o.t((uint32_t)RAD_I32, { nl }); /* expert_count */
o.t(D, { M, 1 }); /* gate */
return o.finish("router_gemm_topk_scatter", operand, out);
}
/* `a_order` decides the activation's row count: one per token, or one per (token, slot) already
* in the scatter's order. A described case that got this wrong would build the operand at the
* extent the WRONG reading wants, and the fault it names would go unseen. */
static inline bool sorted_a_order(const RadParam* p, int n_p) {
const char* s = gs(p, n_p, "a_order");
return s && std::strcmp(s, "sorted") == 0;
@@ -2331,6 +2412,28 @@ int ref_sample_dry_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return penalty_shape(p, n_p, operand, "sample_dry", true, out);
}
/* The n-gram ban reads the same history the two penalty stages do and writes the logits in place,
* and adds one small plane beside them: `ngram`, an i32 {n-gram length, window} pair a row. It is
* a plane of its own rather than fields in `params` because the params row is a fixed 24-word wire
* format shared by every sampler op (and recorded in the kbench fixtures). Drawn in 0..63 so both
* a length inside the 64-token history and the 0 (= off) and whole-window forms occur.
*
* The optional `whitelist` bitmask is sample_mask's plane shape (word w bit b covers column
* 32w + b, a SET bit marking an exempt token), addressed by the sampled row itself; a random draw
* fills it with random bits, so a sweep exercises exemptions as often as plain bans. */
int ref_sample_ngram_ban_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */
sample_params(o, M, REF_SAMPLE_HIST, 0); /* params */
o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1,
(uint32_t)RAD_OPD_F_IDX_HISTORY); /* history */
o.t_idx({ M, 2 }, 64, -1, 0); /* ngram: {n, window} */
o.t((uint32_t)RAD_I32, { M, (nv + 31) / 32 }); /* whitelist, optional */
return o.finish("sample_ngram_ban", operand, out);
}
int ref_sample_temp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
@@ -3153,13 +3256,18 @@ int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
const int64_t st = gi(p, n_p, "stride", 1), pp = gi(p, n_p, "pad", -1);
const int64_t dil = gi(p, n_p, "dil", 1);
const bool padded = pp >= 0 && st > 1; /* the zero-padded strided form (explicit `pad`) */
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) ||
st < 1 || (st > 1 && (causal || pp < 0)) || (st <= 1 && pp >= 0))
st < 1 || (pp >= 0 && (st <= 1 || causal)) ||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st || M % st)) ||
(!padded && gi(p, n_p, "cu_div", 1) != 1))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
if (st > 1 && D != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED;
if (padded && D != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED;
/* A strided convolution is described over one sequence: two would each need a whole number
* of strides. Bounds in coarser units (cu_div) are not drawn; ref_test checks them. */
const int64_t S = st > 1 ? 1 : two_seqs(M);
const int64_t O = st > 1 ? (M + 2 * pp - dil * (k - 1) - 1) / st + 1 : M;
const int64_t O = padded ? (M + 2 * pp - dil * (k - 1) - 1) / st + 1 : M / st;
if (O <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, cin }); /* x */
@@ -3244,6 +3352,22 @@ int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("rvq_embed", operand, out);
}
int ref_vq_encode_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t dim = gi(p, n_p, "dim", 0), bins = gi(p, n_p, "bins", 0);
if (M <= 0 || n <= 0 || dim <= 0 || bins <= 0) return RAD_E_UNSUPPORTED;
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* x, INOUT */
o.t(F, { dim, n }); /* in_w */
o.t(F, { dim }); /* in_b */
o.t(F, { bins, dim }); /* cb */
o.t(F, { n, dim }); /* out_w */
o.t(F, { n }); /* out_b */
o.t_idx({ M }, bins, -1, 0); /* codes, OUT */
return o.finish("vq_encode", operand, out);
}
int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0);
const int64_t st = gi(p, n_p, "stride", 0);
@@ -3271,6 +3395,21 @@ int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("end_status", operand, out);
}
int ref_ras_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), W = gi(p, n_p, "win", 0);
const int64_t hi = gi(p, n_p, "hi", 0);
if (M <= 0 || rep < 1 || W <= 0 || hi <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED;
Opd o;
/* Picks over a small band so the windows repeat them often enough to exercise the redraw. */
const int64_t band = std::min<int64_t>(hi + 2, 12);
o.t_idx({ rep * M }, band, -1, 0); /* first */
o.t_idx({ rep * M }, band, -1, 0); /* alt */
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
o.t_idx({ REF_LANES * W }, band, -1, 0); /* hist, INOUT */
o.t_idx({ rep * M }, band, -1, 0); /* ids, OUT */
return o.finish("ras_pick", operand, out);
}
int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0);
const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1);
@@ -3409,6 +3548,16 @@ int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("int_affine", operand, out);
}
int ref_sub_i32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
if (M <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ M }, 100000, -1, 0); /* x */
o.t_idx({ 1 }, 1000, -1, 0); /* s */
o.t_idx({ M }, 1, -1, 0); /* y */
return o.finish("sub_i32", operand, out);
}
/* ================================================================== LTX-2 (ref_ltx.cpp) */
int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0);
@@ -3567,16 +3716,6 @@ int ref_tile_stitch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
return o.finish("tile_stitch", operand, out);
}
int ref_patch_pix8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0);
const int64_t w = cols_for(M, 1), R = w ? M / w : 0;
if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), { R, w * C * pp * pp }); /* x: patch rows */
o.t((uint32_t)RAD_U8, { R * pp, w * pp * C }); /* y: bytes */
return o.finish("patch_pix8", operand, out);
}
int ref_stft_logmel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), hop = gi(p, n_p, "hop", 0), nfft = gi(p, n_p, "nfft", 0);
const int64_t nm = gi(p, n_p, "n_mel", 0), ch = gi(p, n_p, "ch", 0), F = nfft / 2 + 1;