Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port

Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
  expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
  its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
  combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
  mtp_couple_propose.

Also ignores /baseline-models/ (local model copies).

Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-07 22:13:08 +01:00
commit 45f3b510c7
365 files changed
+56942 -6331

No files matched your search

+38 -8
View File
@@ -75,20 +75,24 @@ struct KvDyn {
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
/* attn_paged, and attn_paged_sink with `sinks` (one logit a query head, beside the keys in the
* softmax's denominator and nowhere else): out at operand `oi`. */
/* attn_paged_tree's ninth operand, `spec_parent` (RadBatch::spec_parent, rad_drafter_tree), is
* read here too: a row whose entry is -2 is an ordinary causal row; any other row is a node of its
* sequence's verify block, whose entry is its parent's row within the sequence's rows (-1 for the
* root, the block's first row). Inside the block such a row sees itself and its ancestors only,
* and its window is measured from the block's first position plus its depth -- the position its
* token has if its path is committed -- rather than from its row. */
int ref_attn_paged(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
static int attn_paged_impl(const RadArgs* a, const RadTensor* sinks, int oi, bool shared_anchor_window) {
if (a->n_t < oi + 1) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[oi];
const RadTensor* kdes = t_in(a, 4);
const RadTensor* vdes = t_in(a, 5);
const RadTensor* cus = t_in(a, 6);
const RadTensor* tpar = a->n_t > 8 ? t_in(a, 8) : nullptr;
/* The tree operand sits where attn_paged_sink keeps its output; a sinked call has none. */
const RadTensor* tpar = !sinks && a->n_t > 8 ? t_in(a, 8) : nullptr;
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
if (sinks && !sinks->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
@@ -97,7 +101,8 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim <= 0 || gqa <= 0 || block_size <= 0 ||
(shared_anchor_window && window <= 0)) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
@@ -106,6 +111,7 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
/* gqa and the cache's head count fix the query head count; a rank-3 query that disagrees would
* stride through the wrong rows. */
if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE;
if (sinks && numel(sinks) != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(su);
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
@@ -198,11 +204,16 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
/* Key j's slot in the cache, or -1 when the mask hides it or its block is
* unmapped. */
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
const int64_t mask_pos = shared_anchor_window ? base : pos;
if (causal && j > mask_pos) return -1;
if (tree && j >= base && !((tmask >> (j - base)) & 1)) return -1;
if (window > 0) {
const int64_t d = wpos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
const int64_t d = (shared_anchor_window ? base : wpos) - j;
if (shared_anchor_window) {
if (d >= window) return -1;
} else if (causal ? (d >= window) : (d >= window || d <= -window)) {
return -1;
}
}
const int64_t blk =
ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
@@ -249,6 +260,11 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
return;
}
/* A sink is one more logit in the softmax with no value: the maximum takes it,
* the sum adds it last, and the output stays the keys' weighted values. */
const float sk = sinks ? ldt(sinks, h) : -INFINITY;
if (sinks && sk > mx) mx = sk;
/* Pass two: exponentiate and accumulate in ascending key order. */
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
@@ -262,6 +278,7 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
for (int64_t d = 0; d < head_dim; ++d)
acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vds);
}
if (sinks) sum += ref_exp(sk - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
};
@@ -276,6 +293,19 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
return RAD_OK;
}
int ref_attn_paged(const RadArgs* a, RadStream) { return attn_paged_impl(a, nullptr, 7, false); }
int ref_attn_paged_anchor_window(const RadArgs* a, RadStream) {
if (!a || a->n_t < 8) return RAD_E_INVAL;
if (a->n_t > 8 && t_in(a, 8)) return RAD_E_UNSUPPORTED;
return attn_paged_impl(a, nullptr, 7, true);
}
int ref_attn_paged_sink(const RadArgs* a, RadStream) {
if (a->n_t < 9 || !a->t[7].data) return RAD_E_INVAL;
return attn_paged_impl(a, &a->t[7], 8, false);
}
/* attn_paged with its tree operand present: ref_attn_paged reads it (see there). Refused without
* one, and for a non-causal layer, whose two-sided window has no tree reading here. */
int ref_attn_paged_tree(const RadArgs* a, RadStream s) {
+109 -3
View File
@@ -8,6 +8,7 @@
#include "ref_ops.h"
#include <algorithm>
#include <cmath>
#include <vector>
using namespace ref;
@@ -248,6 +249,73 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* grid_embed_cpe: RADIO's cropped position embedding (CPE). The table resampled as torch's
* F.interpolate(mode="bilinear", align_corners=False) -- without antialias -- onto a square of side
* d = max(grid height, grid width), of which the grid keeps the top-left h x w. Per axis two taps at
* src = (i + 0.5) * side / d - 0.5, clamped at 0, the upper tap clamped into the table, and blended
* along the row first as torch's bilinear kernel does. f32, rounded once before the add. */
static void cpe_taps(int64_t at, int64_t d, int64_t side, int64_t t[2], float w[2]) {
if (d < 1) d = 1;
at = at < 0 ? 0 : (at >= d ? d - 1 : at);
float src = (float)side / (float)d * ((float)at + 0.5f) - 0.5f;
if (src < 0.0f) src = 0.0f;
int64_t i0 = (int64_t)src;
if (i0 > side - 1) i0 = side - 1;
t[0] = i0;
t[1] = i0 < side - 1 ? i0 + 1 : i0;
w[1] = src - (float)i0;
w[0] = 1.0f - w[1];
}
int ref_grid_embed_cpe(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
/* The prefix rows, when n_prefix names some; without it the operand is not read. */
const int64_t npre = p_int(a, "n_prefix", 0);
const RadTensor* pre = npre > 0 && a->n_t > 3 && a->t[3].data ? &a->t[3] : nullptr;
if (npre > 0 && (!pre || numel(pre) < npre * n)) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n * 4)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms);
const int64_t xb0 = rowoff(x, r, n), xs0 = laststride(x);
if (g[0] < 0) {
/* A row ahead of its segment's patches: the learned row its column names. */
const int64_t k = g[1] < 0 ? 0 : (g[1] >= npre ? npre - 1 : g[1]);
for (int64_t i = 0; npre > 0 && i < n; ++i) {
const float pe = round_dt(x->dtype, ldt(pre, rowoff(pre, k, n) + i * laststride(pre)));
stt(x, xb0 + i * xs0, ldt(x, xb0 + i * xs0) + pe);
}
continue;
}
const int64_t d = g[2] > g[3] ? g[2] : g[3];
int64_t th[2], tw[2];
float wh[2], ww[2];
cpe_taps(g[0], d, side, th, wh);
cpe_taps(g[1], d, side, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
auto at = [&](int64_t y, int64_t c, int64_t i) {
return ldt(tab, rowoff(tab, y * side + c, n) + i * ts);
};
for (int64_t i = 0; i < n; ++i) {
const float r0 = ww[0] * at(th[0], tw[0], i) + ww[1] * at(th[0], tw[1], i);
const float r1 = ww[0] * at(th[1], tw[0], i) + ww[1] * at(th[1], tw[1], i);
const float pe = round_dt(x->dtype, wh[0] * r0 + wh[1] * r1);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ add / mul */
/* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which
* broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a
@@ -376,7 +444,8 @@ int ref_silu_mul(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ act_mul */
/* y = act(a) * b, the gated product with its halves in two operands: two column slices of a fused
* gate_up, or a gate whose multiplier is another tensor (Gemma's per-layer-input block multiplies
* gelu(gate(x)) by a per-layer embedding).
* gelu(gate(x)) by a per-layer embedding). With `relu` and the same tensor in both operands it is
* relu(x)^2, Nemotron-H's ungated expert activation.
*
* The activation is rounded to y's dtype before the product, as the unfused pair stores it. */
int ref_act_mul(const RadArgs* a, RadStream) {
@@ -386,8 +455,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", "quick_gelu" };
const int act = p_enum(a, "act", kActs, 5, -1);
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu", "relu" };
const int act = p_enum(a, "act", kActs, 6, -1);
if (act < 0) return RAD_E_INVAL;
REF_PAR_FOR(rows * n)
@@ -401,6 +470,7 @@ int ref_act_mul(const RadArgs* a, RadStream) {
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
: act == 2 ? act_gelu_tanh(g)
: act == 3 ? act_sigmoid(g)
: act == 5 ? (g > 0.0f ? g : 0.0f)
: 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));
@@ -525,6 +595,42 @@ int ref_pool_cols(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ point_fourier */
/* A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)] over x's n values,
* the sines and the cosines each i-major then j, f_j = 2^j for j < freqs (times pi with `pi` 1),
* so y has n (2 freqs + 1) columns. The products are f32 (exact without pi: a power of two), the
* sine and cosine f32 and rounded once to y's dtype, as Hunyuan3D-2's shape VAE embeds a query
* point. */
int ref_point_fourier(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 n = p_int(a, "n", 0), F = p_int(a, "freqs", 0);
const bool pi = p_int(a, "pi", 0) != 0;
if (n <= 0 || F <= 0 || F > 30) return RAD_E_SHAPE;
const int64_t w = n * (2 * F + 1);
const int64_t M = rows_of(X, n);
if (M <= 0 || numel(Y) < M * w) return RAD_E_SHAPE;
float f[30];
for (int64_t j = 0; j < F; ++j)
f[j] = pi ? (float)std::ldexp(3.14159265358979323846, (int)j) : std::ldexp(1.0f, (int)j);
REF_PAR_FOR(M * w)
for (int64_t r = 0; r < M; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, w);
const int64_t xs = laststride(X), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(X, xb + i * xs);
stt(Y, yb + i * ys, v);
for (int64_t j = 0; j < F; ++j) {
const float t = v * f[j];
stt(Y, yb + (n + i * F + j) * ys, std::sin(t));
stt(Y, yb + (n + n * F + i * F + j) * ys, std::cos(t));
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ relu */
/* y = max(x, 0) over [M, n], each operand at its own row pitch. */
int ref_relu(const RadArgs* a, RadStream) {
+85
View File
@@ -68,6 +68,91 @@ int ref_router_sigmoid_topk(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* Group-limited noaux_tc routing (DeepSeek-V3's, Ling-3.0's): the experts fall into `n_group`
* equal groups, a group ranks by the sum of its two highest `p + bias`, and selection runs over
* the experts of the `topk_group` best groups only. Weights as in router_sigmoid_topk. */
int ref_router_sigmoid_group_topk(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &weights = a->t[3];
const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0),
ng = p_int(a, "n_group", 0), kg = p_int(a, "topk_group", 0);
const float scale = p_f32(a, "route_scale", 0);
const bool norm = p_int(a, "norm", 0) != 0;
if (ne < 1 || ne > 512 || k < 1 || ng < 1 || ne % ng || ne / ng < 2 || kg < 1 || kg > ng ||
k > kg * (ne / ng) || !std::isfinite(scale) || scale <= 0 || lg.rank != 2 ||
lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne ||
bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || ids.rank != 2 || weights.rank != 2 ||
ids.shape[0] != lg.shape[0] || weights.shape[0] != lg.shape[0] || ids.shape[1] != k ||
weights.shape[1] != k || !lg.data || !bias.data || !ids.data || !weights.data)
return RAD_E_SHAPE;
const int64_t gsz = ne / ng;
for (int64_t r = 0; r < lg.shape[0]; ++r) {
float scores[512], select[512], chosen[512], gscore[512];
int index[512];
bool keep[512] = {};
for (int64_t e = 0; e < ne; ++e) {
scores[e] = act_sigmoid(ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg)));
select[e] = scores[e] + ldt(&bias, e * laststride(&bias));
}
for (int64_t gi = 0; gi < ng; ++gi) {
float t0 = -INFINITY, t1 = -INFINITY;
for (int64_t e = gi * gsz; e < (gi + 1) * gsz; ++e) {
if (select[e] > t0) { t1 = t0; t0 = select[e]; }
else if (select[e] > t1) t1 = select[e];
}
gscore[gi] = t0 + t1;
}
for (int64_t j = 0; j < kg; ++j) {
int best = -1;
for (int64_t gi = 0; gi < ng; ++gi)
if (gscore[gi] > -INFINITY && (best < 0 || gscore[gi] > gscore[best])) best = (int)gi;
if (best < 0) return RAD_E_SHAPE;
for (int64_t e = best * gsz; e < (best + 1) * gsz; ++e) keep[e] = true;
gscore[best] = -INFINITY;
}
float sum = 0;
for (int64_t j = 0; j < k; ++j) {
int best = -1;
for (int64_t e = 0; e < ne; ++e)
if (keep[e] && select[e] > -INFINITY && (best < 0 || select[e] > select[best]))
best = (int)e;
if (best < 0) return RAD_E_SHAPE;
index[j] = best;
chosen[j] = scores[best];
sum += chosen[j];
select[best] = -INFINITY;
}
for (int64_t j = 0; j < k; ++j) {
st_int(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]);
stt(&weights, rowoff(&weights, r, k) + j * laststride(&weights),
chosen[j] * (norm ? scale / (sum + 1e-20f) : scale));
}
}
return RAD_OK;
}
/* Ling-3.0's clamp: the SiLU is taken first and its value clipped above, the up branch on both
* sides (vLLM's SwigluStepAndMul). swiglu_clamped clips the gate before the SiLU instead. */
int ref_swiglu_step(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const auto &gu = a->t[0], &y = a->t[1];
const int64_t n = p_int(a, "n", 0);
const float limit = p_f32(a, "limit", 0);
if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data ||
!y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n ||
y.shape[1] != n)
return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < y.shape[0]; ++r)
for (int64_t i = 0; i < n; ++i) {
const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu);
const float g = std::min(act_silu(ldt(&gu, b + i * s)), limit);
const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit);
stt(&y, rowoff(&y, r, n) + i * laststride(&y), g * u);
}
return RAD_OK;
}
/* GLM clamps the gate only above, but clamps the up branch on both sides. */
int ref_swiglu_clamped(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
+260
View File
@@ -0,0 +1,260 @@
/* ref_lili.cpp -- LiLiCorr's candidate correlator (NVIDIA's Nemotron-3.5-Bolt drafter; vLLM's
* model_executor/models/lilicorr.py), the four ops a block drafter's query pass ends in:
*
* lili_cand the candidates of every draft position from the target head's top-k, their five
* rank features through LayerNorm, the up projection and SiLU, and the lattice row's
* additive part: the position's own state plus a slot and a rank embedding
* lili_attn attention over each sequence's lattice of steps x k rows, with a learned bias per
* head on the slot distance and on the same slot
* lili_factor [h | a | h * a] a row, a = its sequence's anchor
* lili_walk the factored edge scores and the greedy walk over them
*
* A sequence's lattice is `steps` draft positions of `k` candidates, row s * k + j for position s's
* j-th candidate, the sequences one after another. Everything runs in f32 and rounds once to the
* output's dtype.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <algorithm>
#include <cmath>
#include <vector>
using namespace ref;
/* ------------------------------------------------------------------ lili_cand */
/* stats [M, world * (2 + 2 row_k)] f32: each rank's sample_logprobs row (max, sum of exp(l - max),
* row_k >= k (id, logit) pairs descending), all-gathered row-interleaved; row_k defaults to k (a
* caller widens it so a row is whole 16-byte words for the all-gather). The ranks merge as one row would:
* the maximum and the rescaled sum give the log-normaliser, the pairs the k largest by value, ties
* to the lower id. For candidate j of row m, with lp_j = logit_j - lse:
*
* feat = [lp_j, exp(lp_j), lp_j - lp_0, j / (k - 1), j == 0]
* f = silu(up_w . layernorm(feat; ln_w, ln_b, eps) + up_b) -> feat out, row m*k+j
* base = pas[m] + slot[m % steps] + rank[j] -> base out, row m*k+j
* cand = id_j -> cand [M, k] i32
*/
int ref_lili_cand(const RadArgs* a, RadStream) {
if (a->n_t < 11) return RAD_E_INVAL;
for (int i = 0; i < 11; ++i) if (!a->t[i].data) return RAD_E_INVAL;
const RadTensor *st = &a->t[0], *pas = &a->t[1], *lnw = &a->t[2], *lnb = &a->t[3];
const RadTensor *upw = &a->t[4], *upb = &a->t[5], *slot = &a->t[6], *rank = &a->t[7];
const RadTensor *cand = &a->t[8], *fo = &a->t[9], *bo = &a->t[10];
const int64_t k = p_int(a, "k", 0), world = p_int(a, "world", 1), steps = p_int(a, "steps", 0);
const int64_t n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-5f);
const int64_t rk = p_int(a, "row_k", k);
if (k < 2 || k > 64 || rk < k || world < 1 || steps < 1 || n <= 0) return RAD_E_SHAPE;
const int64_t w = 2 + 2 * rk;
const int64_t M = rows_of(st, world * w);
if (M <= 0 || rows_of(pas, n) < M || numel(cand) < M * k || rows_of(fo, n) < M * k ||
rows_of(bo, n) < M * k)
return RAD_E_SHAPE;
if (numel(lnw) < 5 || numel(lnb) < 5 || numel(upw) < n * 5 || numel(upb) < n ||
rows_of(slot, n) < steps || rows_of(rank, n) < k)
return RAD_E_SHAPE;
if (cand->dtype != RAD_I32) return RAD_E_DTYPE;
REF_PAR_FOR(M * k * n * 8)
for (int64_t m = 0; m < M; ++m) {
const int64_t sb = rowoff(st, m, world * w), ss = laststride(st);
auto S = [&](int64_t r, int64_t i) { return ldt(st, sb + (r * w + i) * ss); };
/* The log-normaliser over every rank's shard. */
float mx = -INFINITY;
for (int64_t r = 0; r < world; ++r) mx = std::max(mx, S(r, 0));
double sum = 0.0;
for (int64_t r = 0; r < world; ++r)
if (S(r, 0) > -INFINITY) sum += (double)S(r, 1) * std::exp((double)S(r, 0) - mx);
const double lse = (double)mx + std::log(sum);
/* The k largest pairs of the world * k, by value, ties to the lower id. */
std::vector<std::pair<float, int64_t>> all;
all.reserve((size_t)(world * k));
for (int64_t r = 0; r < world; ++r)
for (int64_t j = 0; j < k; ++j) {
const int64_t id = (int64_t)S(r, 2 + 2 * j);
if (id >= 0) all.push_back({ S(r, 3 + 2 * j), id });
}
std::sort(all.begin(), all.end(), [](const auto& x, const auto& y) {
return x.first > y.first || (x.first == y.first && x.second < y.second);
});
float lp[64];
int64_t ids[64];
for (int64_t j = 0; j < k; ++j) {
const bool have_j = j < (int64_t)all.size();
ids[j] = have_j ? all[(size_t)j].second : 0;
lp[j] = have_j ? (float)((double)all[(size_t)j].first - lse) : -1e4f;
((int32_t*)cand->data)[rowoff(cand, m, k) + j * laststride(cand)] = (int32_t)ids[j];
}
const int64_t s = m % steps;
for (int64_t j = 0; j < k; ++j) {
const float f[5] = { lp[j], std::exp(lp[j]), lp[j] - lp[0],
(float)j / (float)(k - 1), j == 0 ? 1.0f : 0.0f };
float mean = 0.0f;
for (int i = 0; i < 5; ++i) mean += f[i];
mean /= 5.0f;
float var = 0.0f;
for (int i = 0; i < 5; ++i) var += (f[i] - mean) * (f[i] - mean);
var /= 5.0f;
const float rs = 1.0f / std::sqrt(var + eps);
float y[5];
for (int i = 0; i < 5; ++i) y[i] = (f[i] - mean) * rs * ldt(lnw, i) + ldt(lnb, i);
const int64_t row = m * k + j;
const int64_t fb = rowoff(fo, row, n), fs = laststride(fo);
const int64_t bb = rowoff(bo, row, n), bs = laststride(bo);
for (int64_t c = 0; c < n; ++c) {
float u = ldt(upb, c);
for (int i = 0; i < 5; ++i) u += ldt(upw, c * 5 + i) * y[i];
stt(fo, fb + c * fs, u / (1.0f + std::exp(-u)));
const float b = ldt(pas, rowoff(pas, m, n) + c * laststride(pas)) +
ldt(slot, rowoff(slot, s, n) + c * laststride(slot)) +
ldt(rank, rowoff(rank, j, n) + c * laststride(rank));
stt(bo, bb + c * bs, b);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_attn */
/* qkv [M, 3 * n_head * head_dim] (q | k | v, heads contiguous within each), M = sequences * L with
* L = steps * k. Row i of a lattice sits at slot s_i = i / k. Per sequence and head:
*
* score(i, j) = q_i . k_j * scale + rel[h][s_i - s_j + steps] + (s_i == s_j ? same[h] : 0)
* out_i = softmax_j(score(i, .)) . v
*
* Every row sees every row of its lattice: the bias is a preference, not a mask. */
int ref_lili_attn(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *rel = &a->t[1], *same = &a->t[2], *o = &a->t[3];
const int64_t steps = p_int(a, "steps", 0), k = p_int(a, "k", 0);
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
if (steps < 1 || k < 1 || nh < 1 || hd < 1) return RAD_E_SHAPE;
const int64_t L = steps * k, n = nh * hd;
const int64_t M = rows_of(qkv, 3 * n);
if (M <= 0 || M % L || rows_of(o, n) < M) return RAD_E_SHAPE;
const int64_t rw = rel->rank ? rel->shape[rel->rank - 1] : 0;
if (rw < 2 * steps - 1 || rows_of(rel, rw) < nh || numel(same) < nh) return RAD_E_SHAPE;
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd));
const int64_t qs = laststride(qkv), os = laststride(o);
REF_PAR_FOR(M * nh * L * hd * 2)
for (int64_t u = 0; u < M * nh; ++u) {
const int64_t i = u / nh, h = u % nh;
const int64_t q0 = i / L * L, si = (i - q0) / k;
const int64_t qb = rowoff(qkv, i, 3 * n) + h * hd * qs;
std::vector<float> sc((size_t)L);
float mx = -INFINITY;
for (int64_t j = 0; j < L; ++j) {
const int64_t kb = rowoff(qkv, q0 + j, 3 * n) + (n + h * hd) * qs;
float dot = 0.0f;
for (int64_t d = 0; d < hd; ++d) dot += ldt(qkv, qb + d * qs) * ldt(qkv, kb + d * qs);
const int64_t sj = j / k;
float b = ldt(rel, rowoff(rel, h, rw) + (si - sj + steps) * laststride(rel));
if (si == sj) b += ldt(same, h);
sc[(size_t)j] = dot * scale + b;
mx = std::max(mx, sc[(size_t)j]);
}
float sum = 0.0f;
for (int64_t j = 0; j < L; ++j) { sc[(size_t)j] = std::exp(sc[(size_t)j] - mx); sum += sc[(size_t)j]; }
const int64_t ob = rowoff(o, i, n) + h * hd * os;
for (int64_t d = 0; d < hd; ++d) {
float acc = 0.0f;
for (int64_t j = 0; j < L; ++j)
acc += sc[(size_t)j] * ldt(qkv, rowoff(qkv, q0 + j, 3 * n) + (2 * n + h * hd + d) * qs);
stt(o, ob + d * os, acc / sum);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_factor */
/* y[i] = [h_i | a_s | h_i * a_s] with s = i / L, the factor projection's input. */
int ref_lili_factor(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *h = &a->t[0], *an = &a->t[1], *y = &a->t[2];
const int64_t L = p_int(a, "L", 0), n = p_int(a, "n", 0);
if (L < 1 || n < 1) return RAD_E_SHAPE;
const int64_t M = rows_of(h, n);
if (M <= 0 || M % L || rows_of(an, n) < M / L || rows_of(y, 3 * n) < M) return RAD_E_SHAPE;
REF_PAR_FOR(M * n * 3)
for (int64_t i = 0; i < M; ++i) {
const int64_t hb = rowoff(h, i, n), ab = rowoff(an, i / L, n), yb = rowoff(y, i, 3 * n);
const int64_t hs = laststride(h), as = laststride(an), ys = laststride(y);
for (int64_t c = 0; c < n; ++c) {
const float hv = ldt(h, hb + c * hs), av = ldt(an, ab + c * as);
stt(y, yb + c * ys, hv);
stt(y, yb + (n + c) * ys, av);
stt(y, yb + (2 * n + c) * ys, hv * av);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_walk */
/* edges [M * steps * k, 2n]: each candidate's outgoing | incoming vector, aout [M, n] the anchor's
* outgoing one, cand [M * steps, k] i32. Vectors are normalised as F.normalize (v / max(|v|, eps)).
*
* start[j] = scale * aout . in[0][j]
* pair[s][i][j] = scale * out[s][i] . in[s + 1][j]
* walk p_0 = argmax start, p_s = argmax pair[s - 1][p_{s-1}] (first index on ties)
* tokens[m][s] = cand[m * steps + s][p_s]
*
* `scores` [M, steps, k, k], when present, is vLLM's tensor: row 0 is start for every i. */
int ref_lili_walk(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *ed = &a->t[0], *ao = &a->t[1], *cd = &a->t[2], *tk = &a->t[3];
const RadTensor* sco = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t steps = p_int(a, "steps", 0), k = p_int(a, "k", 0), n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-4f), scale = p_f32(a, "scale", 1.0f);
if (steps < 1 || k < 1 || n < 1) return RAD_E_SHAPE;
const int64_t M = rows_of(ao, n);
if (M <= 0 || rows_of(ed, 2 * n) < M * steps * k || numel(cd) < M * steps * k ||
numel(tk) < M * steps)
return RAD_E_SHAPE;
if (cd->dtype != RAD_I32 || tk->dtype != RAD_I32) return RAD_E_DTYPE;
if (sco && numel(sco) < M * steps * k * k) return RAD_E_SHAPE;
REF_PAR_FOR(M * steps * k * k * n)
for (int64_t m = 0; m < M; ++m) {
auto vec = [&](const RadTensor* t, int64_t row, int64_t pitch, int64_t col0, float* v) {
const int64_t b = rowoff(t, row, pitch) + col0 * laststride(t);
double ss = 0.0;
for (int64_t c = 0; c < n; ++c) { v[c] = ldt(t, b + c * laststride(t)); ss += (double)v[c] * v[c]; }
const float inv = 1.0f / std::max((float)std::sqrt(ss), eps);
for (int64_t c = 0; c < n; ++c) v[c] *= inv;
};
std::vector<float> va((size_t)n), vo((size_t)(steps * k * n)), vi((size_t)(steps * k * n));
vec(ao, m, n, 0, va.data());
for (int64_t r = 0; r < steps * k; ++r) {
vec(ed, m * steps * k + r, 2 * n, 0, &vo[(size_t)(r * n)]);
vec(ed, m * steps * k + r, 2 * n, n, &vi[(size_t)(r * n)]);
}
auto dot = [&](const float* x, const float* y) {
float s = 0.0f;
for (int64_t c = 0; c < n; ++c) s += x[c] * y[c];
return s * scale;
};
std::vector<float> sc((size_t)(steps * k * k));
for (int64_t j = 0; j < k; ++j) {
const float v = dot(va.data(), &vi[(size_t)(j * n)]);
for (int64_t i = 0; i < k; ++i) sc[(size_t)(i * k + j)] = v;
}
for (int64_t s = 1; s < steps; ++s)
for (int64_t i = 0; i < k; ++i)
for (int64_t j = 0; j < k; ++j)
sc[(size_t)((s * k + i) * k + j)] =
dot(&vo[(size_t)(((s - 1) * k + i) * n)], &vi[(size_t)((s * k + j) * n)]);
int64_t prev = 0;
for (int64_t s = 0; s < steps; ++s) {
int64_t best = 0;
for (int64_t j = 1; j < k; ++j)
if (sc[(size_t)((s * k + prev) * k + j)] > sc[(size_t)((s * k + prev) * k + best)]) best = j;
const int64_t id = ld_int(cd->dtype, cd->data, rowoff(cd, m * steps + s, k) + best * laststride(cd));
((int32_t*)tk->data)[rowoff(tk, m, steps) + s * laststride(tk)] = (int32_t)id;
prev = best;
}
if (sco)
for (int64_t e = 0; e < steps * k * k; ++e) stt(sco, m * steps * k * k + e, sc[(size_t)e]);
}
return RAD_OK;
}
+91
View File
@@ -50,6 +50,97 @@ int ref_mla_project(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* Dense causal latent attention over a paged cache whose token row is the normed latent followed
* by the rotated key part (Ling-3.0's MLA). A score is scale * (q . latent + q_rope . rope); the
* value is the latent. Sequences, positions and the causal bound follow attn_paged: sequence s
* owns query rows [cu[s], cu[s+1]), its context after this step is seqused[s], and row i of it
* sits at position seqused[s] - qlen + i and sees keys 0..position. With `gate` the rounded output
* is multiplied by the rounded sigmoid of the head's gate logit and rounded again. */
int ref_mla_attn_paged(const RadArgs* a, RadStream) {
/* q_rope (1) is required when rope_dim is nonzero, gate (6) is optional. */
if (a->n_t < 8 || !t_in(a, 0) || !t_in(a, 2) || !t_in(a, 3) || !t_in(a, 4) || !t_in(a, 5) ||
!t_in(a, 7))
return RAD_E_INVAL;
RadTensor q = a->t[0], qr = a->t[1], o = a->t[7];
const auto &kv = a->t[2], &bt = a->t[3], &su = a->t[4], &cu = a->t[5];
const RadTensor* gate = t_in(a, 6);
const int64_t h = p_int(a, "heads", 0), L = p_int(a, "latent_dim", 0),
R = p_int(a, "rope_dim", 0), bs = p_int(a, "block_size", 0);
const float scale = p_f32(a, "scale", 0);
auto heads_view = [&](RadTensor& t, int64_t width) {
if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) {
t.rank = 3;
t.shape[1] = h;
t.shape[2] = width;
t.stride[2] = t.stride[1];
t.stride[1] *= width;
}
};
heads_view(q, L);
heads_view(qr, R);
heads_view(o, L);
if (h < 1 || L < 1 || L > 2048 || R < 0 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != L || (R && (qr.rank != 3 ||
qr.shape[0] != q.shape[0] || qr.shape[1] != h || qr.shape[2] != R)) || kv.rank != 4 ||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] < L + R || bt.rank != 2 ||
su.rank != 1 || cu.rank != 1 || numel(&cu) != numel(&su) + 1 || o.rank != 3 ||
o.shape[0] != q.shape[0] || o.shape[1] != h || o.shape[2] != L ||
(gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < h)))
return RAD_E_SHAPE;
if (!q.data || (R && !qr.data) || !kv.data || !bt.data || !su.data || !cu.data || !o.data)
return RAD_E_INVAL;
const int64_t n_seq = numel(&su), rows = q.shape[0];
if (cu_at(&cu, 0) != 0 || cu_at(&cu, n_seq) != rows) return RAD_E_SHAPE;
#pragma omp parallel for schedule(dynamic)
for (int64_t job = 0; job < rows * h; ++job) {
const int64_t r = job / h, head = job % h;
const int64_t s = seq_of(&cu, n_seq, r);
const int64_t qlen = cu_at(&cu, s + 1) - cu_at(&cu, s), i = r - cu_at(&cu, s);
const int64_t ctx = ld_int(su.dtype, su.data, s * su.stride[0]);
const int64_t pos = ctx - qlen + i;
const int64_t live = std::min(pos + 1, bt.shape[1] * bs);
auto key_offset = [&](int64_t token) -> int64_t {
const int64_t page =
ld_int(bt.dtype, bt.data, s * bt.stride[0] + (token / bs) * bt.stride[1]);
return page < 0 || page >= kv.shape[0]
? -1
: page * kv.stride[0] + (token % bs) * kv.stride[2];
};
auto score = [&](int64_t base) -> float {
float v = 0;
for (int64_t c = 0; c < L; ++c)
v += ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]) *
ldt(&kv, base + c * kv.stride[3]);
for (int64_t c = 0; c < R; ++c)
v += ldt(&qr, r * qr.stride[0] + head * qr.stride[1] + c * qr.stride[2]) *
ldt(&kv, base + (L + c) * kv.stride[3]);
return v * scale;
};
float max = -INFINITY;
for (int64_t j = 0; j < live; ++j) {
const auto base = key_offset(j);
if (base >= 0) max = std::max(max, score(base));
}
float val[2048] = {}, den = 0;
for (int64_t j = 0; j < live; ++j) {
const auto base = key_offset(j);
if (base < 0) continue;
const float w = std::exp(score(base) - max);
den += w;
for (int64_t c = 0; c < L; ++c) val[c] += w * ldt(&kv, base + c * kv.stride[3]);
}
const float g = gate ? round_dt(RAD_BF16, act_sigmoid(ldt(gate, r * gate->stride[0] +
head * gate->stride[1])))
: 1.0f;
for (int64_t c = 0; c < L; ++c) {
float v = den > 0 ? val[c] / den : 0;
if (gate) v = round_dt(RAD_BF16, v) * g;
stt(&o, r * o.stride[0] + head * o.stride[1] + c * o.stride[2], v);
}
}
return RAD_OK;
}
int ref_mla_attn(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4];
+223 -1
View File
@@ -17,6 +17,8 @@
#include "ref_gemm.h"
#include "ref_ops.h"
#include "ref_planes.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
@@ -707,9 +709,229 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
}
int ref_moe_gemm(const RadArgs* a, RadStream) { return moe_gemm_impl(a, false); }
int ref_moe_gemm_q(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true); }
int ref_moe_gemm_q(const RadArgs* a, RadStream s) {
const char* dt = p_str(a, "dtype", "");
if (dt && std::strcmp(dt, "w4a8") == 0) return ref_moe_gemm_w4a8(a, s);
if (dt && std::strcmp(dt, "w4a4") == 0) return ref_moe_gemm_w4a4(a, s);
return moe_gemm_impl(a, true);
}
int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true, 4); }
/* ------------------------------------------------------------------ moe_gemm_w4a8 */
/* moe_gemm_q dtype w4a8: y[i, :] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^T. The two's-complement
* int4 experts (nibbles, -8..7) carry one bf16 scale per (row, 128 of K); the output is bf16 in
* sorted order. The experts are two tables by parity (the even in `w` / `w_scale`, the odd in
* `w_odd` / `w_odd_scale`, expert e at entry e/2 of class e%2). Two activation arms:
* * int8 a: each 128-block accumulates its raw product sum in i32 (exact), then folds
* (sub * a_scale) * w_scale in f32 in ascending block order -- the exact arithmetic and order
* the libr3d kernel runs, so the two agree bit for bit.
* * E4M3 a: the a and w codes decode exactly to f32 and the 128-block dot is summed in f32, the
* scales folded the same way; the kernel's f16 wave-matrix arm matches this to the f16 store
* ulp.
* A row no expert owns (a dropped slot) is left as the caller set it. */
int ref_moe_gemm_w4a8(const RadArgs* a, RadStream) {
if (!have(a, 9)) return RAD_E_INVAL;
const RadTensor* A = &a->t[0];
const RadTensor* AS = &a->t[1];
const RadTensor* W = &a->t[2];
const RadTensor* WS = &a->t[3];
const RadTensor* ST = &a->t[4];
const RadTensor* OF = &a->t[5];
const RadTensor* WO = &a->t[6];
const RadTensor* WOS = &a->t[7];
const RadTensor* Y = &a->t[8];
const bool e4m3 = (A->dtype == RAD_F8E4M3);
if (A->dtype != RAD_I8 && !e4m3) return RAD_E_DTYPE;
if (AS->dtype != RAD_F32 || W->dtype != RAD_I4 || WS->dtype != RAD_BF16 || Y->dtype != RAD_BF16)
return RAD_E_DTYPE;
if (e4m3 && (WO->dtype != RAD_I4 || WOS->dtype != RAD_BF16)) return RAD_E_DTYPE;
const char* ord = p_str(a, "a_order", "token");
const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0;
if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED;
const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] * 2 : 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE;
const int64_t N = W->rank >= 3 ? W->shape[1] : 0;
const int64_t K = W->rank >= 3 ? W->shape[2] : 0;
const int64_t T = Y->rank >= 2 ? Y->shape[0] : 0;
if (N <= 0 || K <= 0 || T <= 0 || K % 128) return RAD_E_SHAPE;
if (p_int(a, "N", N) != N || p_int(a, "K", K) != K) return RAD_E_SHAPE;
const int64_t n_even = (n_expert + 1) / 2, n_odd = n_expert / 2;
if (W->rank < 3 || W->shape[0] < n_even || W->shape[1] < N || W->shape[2] < K) return RAD_E_SHAPE;
if (WS->rank < 3 || WS->shape[0] < n_even || WS->shape[1] < N || WS->shape[2] < K / 128)
return RAD_E_SHAPE;
if (n_odd > 0) {
if (WO->rank < 3 || WO->shape[0] < n_odd || WO->shape[1] < N || WO->shape[2] < K)
return RAD_E_SHAPE;
if (WOS->rank < 3 || WOS->shape[0] < n_odd || WOS->shape[1] < N || WOS->shape[2] < K / 128)
return RAD_E_SHAPE;
}
const int64_t M = A->rank >= 2 ? A->shape[0] : 0;
const int64_t ar = sorted_a ? T : M;
if (M <= 0 || numel(AS) < ar * (K / 128) || numel(ST) < T || numel(OF) < n_expert + 1)
return RAD_E_SHAPE;
const int64_t a_ld = A->rank >= 2 ? A->stride[0] : K;
const int64_t y_ld = Y->rank >= 2 ? Y->stride[0] : N;
const int64_t w_ld = W->stride[1]; // nibbles per weight row
const int64_t ws_ld = WS->stride[1]; // scales per weight row
const int8_t* ap = (const int8_t*)A->data;
const uint8_t* ap8 = (const uint8_t*)A->data;
const float* asp = (const float*)AS->data;
const int32_t* st = (const int32_t*)ST->data;
const int32_t* of = (const int32_t*)OF->data;
const uint8_t* wp = (const uint8_t*)W->data;
const uint16_t* wsp = (const uint16_t*)WS->data;
const uint8_t* wop = (const uint8_t*)WO->data;
const uint16_t* wosp = (const uint16_t*)WOS->data;
uint16_t* yp = (uint16_t*)Y->data;
for (int64_t i = 0; i < T; ++i) {
const int32_t f = st[i];
const int64_t src = sorted_a ? i : (f >= 0 ? (int64_t)f / top_k : -1);
if (src < 0 || (!sorted_a && (int64_t)f / top_k >= M)) continue; // a dropped slot
int64_t e = 0;
while (e + 1 < n_expert && of[e + 1] <= i) ++e;
if (i < of[e] || i >= of[e + 1]) continue; // no expert owns this row
const int64_t cls = e & 1, e2 = e >> 1;
const uint8_t* wt = cls ? wop : wp;
const uint16_t* wst = cls ? wosp : wsp;
const int64_t wrow0 = (size_t)e2 * (size_t)N * w_ld / 2;
const int64_t wsrow0 = (size_t)e2 * (size_t)N * ws_ld;
for (int64_t n = 0; n < N; ++n) {
const uint8_t* wrow = wt + wrow0 + (size_t)n * w_ld / 2;
const uint16_t* wsrow = wst + wsrow0 + (size_t)n * ws_ld;
const float* asr = asp + src * (K / 128);
float acc = 0.f;
for (int64_t b = 0; b < K / 128; ++b) {
const int64_t k0 = b * 128;
float term;
float wscale;
const uint32_t ws_bits = (uint32_t)wsrow[b] << 16; /* bf16 -> f32: align to high 16 bits */
std::memcpy(&wscale, &ws_bits, 4);
if (e4m3) {
float dot = 0.f;
for (int64_t k = 0; k < 128; ++k)
dot += fp8e4m3_to_f32(ap8[(size_t)src * a_ld + k0 + k]) * w4_code(wrow, k0 + k);
term = dot * asr[b] * wscale;
} else {
int32_t sub = 0;
for (int64_t k = 0; k < 128; ++k)
sub += (int32_t)ap[(size_t)src * a_ld + k0 + k] * (int32_t)w4_code(wrow, k0 + k);
term = (float)sub * asr[b] * wscale;
}
acc += term;
}
yp[i * y_ld + n] = f32_to_bf16(acc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_gemm_w4a4 */
/* moe_gemm_q dtype w4a4: y[i, :] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^T. Both the activation and
* the experts are two's-complement int4 (nibbles, -8..7) packed two per byte; the activation carries
* one f32 scale per (row, 128 of K), each expert one bf16 scale per (row, 128 of K); the output is
* bf16 in sorted order. The experts are two tables by parity (the even in `w` / `w_scale`, the odd in
* `w_odd` / `w_odd_scale`, expert e at entry e/2 of class e%2). Each 128-block accumulates its raw
* product sum in i32 (exact: both codes widen to int8), then folds (sub * a_scale) * w_scale in f32
* in ascending block order -- the exact arithmetic and order the libr3d kernel runs, so the two agree
* bit for bit. A row no expert owns (a dropped slot) is left as the caller set it. */
int ref_moe_gemm_w4a4(const RadArgs* a, RadStream) {
if (!have(a, 9)) return RAD_E_INVAL;
const RadTensor* A = &a->t[0];
const RadTensor* AS = &a->t[1];
const RadTensor* W = &a->t[2];
const RadTensor* WS = &a->t[3];
const RadTensor* ST = &a->t[4];
const RadTensor* OF = &a->t[5];
const RadTensor* WO = &a->t[6];
const RadTensor* WOS = &a->t[7];
const RadTensor* Y = &a->t[8];
if (A->dtype != RAD_I4) return RAD_E_DTYPE;
if (AS->dtype != RAD_F32 || W->dtype != RAD_I4 || WS->dtype != RAD_BF16 || Y->dtype != RAD_BF16)
return RAD_E_DTYPE;
if (WO->dtype != RAD_I4 || WOS->dtype != RAD_BF16) return RAD_E_DTYPE;
const char* ord = p_str(a, "a_order", "token");
const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0;
if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED;
const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] * 2 : 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE;
const int64_t N = W->rank >= 3 ? W->shape[1] : 0;
const int64_t K = W->rank >= 3 ? W->shape[2] : 0;
const int64_t T = Y->rank >= 2 ? Y->shape[0] : 0;
if (N <= 0 || K <= 0 || T <= 0 || K % 128) return RAD_E_SHAPE;
if (p_int(a, "N", N) != N || p_int(a, "K", K) != K) return RAD_E_SHAPE;
const int64_t n_even = (n_expert + 1) / 2, n_odd = n_expert / 2;
if (W->rank < 3 || W->shape[0] < n_even || W->shape[1] < N || W->shape[2] < K) return RAD_E_SHAPE;
if (WS->rank < 3 || WS->shape[0] < n_even || WS->shape[1] < N || WS->shape[2] < K / 128)
return RAD_E_SHAPE;
if (n_odd > 0) {
if (WO->rank < 3 || WO->shape[0] < n_odd || WO->shape[1] < N || WO->shape[2] < K)
return RAD_E_SHAPE;
if (WOS->rank < 3 || WOS->shape[0] < n_odd || WOS->shape[1] < N || WOS->shape[2] < K / 128)
return RAD_E_SHAPE;
}
const int64_t M = A->rank >= 2 ? A->shape[0] : 0;
const int64_t ar = sorted_a ? T : M;
if (M <= 0 || numel(AS) < ar * (K / 128) || numel(ST) < T || numel(OF) < n_expert + 1)
return RAD_E_SHAPE;
const int64_t a_ld = A->rank >= 2 ? A->stride[0] / 2 : K / 2; // BYTES per activation row (K int4 = K/2 bytes)
const int64_t y_ld = Y->rank >= 2 ? Y->stride[0] : N;
const int64_t w_ld = W->stride[1]; // nibbles per weight row
const int64_t ws_ld = WS->stride[1]; // scales per weight row
const uint8_t* ap = (const uint8_t*)A->data;
const float* asp = (const float*)AS->data;
const int32_t* st = (const int32_t*)ST->data;
const int32_t* of = (const int32_t*)OF->data;
const uint8_t* wp = (const uint8_t*)W->data;
const uint16_t* wsp = (const uint16_t*)WS->data;
const uint8_t* wop = (const uint8_t*)WO->data;
const uint16_t* wosp = (const uint16_t*)WOS->data;
uint16_t* yp = (uint16_t*)Y->data;
for (int64_t i = 0; i < T; ++i) {
const int32_t f = st[i];
const int64_t src = sorted_a ? i : (f >= 0 ? (int64_t)f / top_k : -1);
if (src < 0 || (!sorted_a && (int64_t)f / top_k >= M)) continue; // a dropped slot
int64_t e = 0;
while (e + 1 < n_expert && of[e + 1] <= i) ++e;
if (i < of[e] || i >= of[e + 1]) continue; // no expert owns this row
const int64_t cls = e & 1, e2 = e >> 1;
const uint8_t* wt = cls ? wop : wp;
const uint16_t* wst = cls ? wosp : wsp;
const int64_t wrow0 = (size_t)e2 * (size_t)N * w_ld / 2;
const int64_t wsrow0 = (size_t)e2 * (size_t)N * ws_ld;
for (int64_t n = 0; n < N; ++n) {
const uint8_t* wrow = wt + wrow0 + (size_t)n * w_ld / 2;
const uint16_t* wsrow = wst + wsrow0 + (size_t)n * ws_ld;
const float* asr = asp + src * (K / 128);
float acc = 0.f;
for (int64_t b = 0; b < K / 128; ++b) {
const int64_t k0 = b * 128;
float wscale;
const uint32_t ws_bits = (uint32_t)wsrow[b] << 16; /* bf16 -> f32: high 16 bits */
std::memcpy(&wscale, &ws_bits, 4);
int32_t sub = 0;
for (int64_t k = 0; k < 128; ++k)
sub += (int32_t)w4_code(ap + (size_t)src * a_ld, k0 + k)
* (int32_t)w4_code(wrow, k0 + k);
acc += (float)sub * asr[b] * wscale;
}
yp[i * y_ld + n] = f32_to_bf16(acc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_gather */
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)].
*
+36
View File
@@ -65,6 +65,7 @@ int ref_mhc_pre_finish (const RadArgs*, RadStream);
int ref_mhc_post (const RadArgs*, RadStream);
int ref_mhc_contract (const RadArgs*, RadStream);
int ref_kda_update (const RadArgs*, RadStream);
int ref_ssd_update (const RadArgs*, RadStream);
int ref_hc_read (const RadArgs*, RadStream);
int ref_hc_write (const RadArgs*, RadStream);
int ref_hc_project (const RadArgs*, RadStream);
@@ -72,17 +73,25 @@ int ref_mtp_enter (const RadArgs*, RadStream);
int ref_layernorm (const RadArgs*, RadStream);
int ref_grid_embed (const RadArgs*, RadStream);
int ref_grid_embed_aa (const RadArgs*, RadStream);
int ref_grid_embed_cpe (const RadArgs*, RadStream);
int ref_lili_cand (const RadArgs*, RadStream);
int ref_lili_attn (const RadArgs*, RadStream);
int ref_lili_factor (const RadArgs*, RadStream);
int ref_lili_walk (const RadArgs*, RadStream);
int ref_add (const RadArgs*, RadStream);
int ref_mul (const RadArgs*, RadStream);
int ref_silu_mul (const RadArgs*, RadStream);
int ref_swiglu_clamped (const RadArgs*, RadStream);
int ref_router_sigmoid_topk(const RadArgs*, RadStream);
int ref_router_sigmoid_group_topk(const RadArgs*, RadStream);
int ref_swiglu_step (const RadArgs*, RadStream);
int ref_dsa_pool(const RadArgs*, RadStream);
int ref_dsa_query(const RadArgs*, RadStream);
int ref_gemm_nt_f32(const RadArgs*, RadStream);
int ref_mla_project(const RadArgs*, RadStream);
int ref_dsa_score(const RadArgs*, RadStream);
int ref_mla_attn(const RadArgs*, RadStream);
int ref_mla_attn_paged(const RadArgs*, RadStream);
int ref_gelu_mul (const RadArgs*, RadStream);
int ref_act_mul (const RadArgs*, RadStream);
int ref_mul_weight (const RadArgs*, RadStream);
@@ -91,6 +100,7 @@ int ref_seg_mean (const RadArgs*, RadStream);
int ref_seg_softmax_pool (const RadArgs*, RadStream);
int ref_pool_rows (const RadArgs*, RadStream);
int ref_pool_cols (const RadArgs*, RadStream);
int ref_point_fourier (const RadArgs*, RadStream);
int ref_relu (const RadArgs*, RadStream);
int ref_clamp (const RadArgs*, RadStream);
int ref_conv2d (const RadArgs*, RadStream);
@@ -110,6 +120,7 @@ int ref_scatter_rows (const RadArgs*, RadStream);
int ref_ngram_ids (const RadArgs*, RadStream);
int ref_ple_gate (const RadArgs*, RadStream);
int ref_ple_conv (const RadArgs*, RadStream);
int ref_ple_conv_bias (const RadArgs*, RadStream);
int ref_causal_conv1d (const RadArgs*, RadStream);
int ref_cast (const RadArgs*, RadStream);
int ref_softmax (const RadArgs*, RadStream);
@@ -128,11 +139,14 @@ int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
int ref_gated_quant_fp8 (const RadArgs*, RadStream);
int ref_gemm_nt_q_gated (const RadArgs*, RadStream);
int ref_dflash_select (const RadArgs*, RadStream);
int ref_dflash_markov_greedy(const RadArgs*, RadStream);
int ref_dflash_markov_greedy_f32(const RadArgs*, RadStream);
int ref_dflash_tree (const RadArgs*, RadStream);
int ref_gram_accum (const RadArgs*, RadStream);
int ref_rmsnorm_had_quant_i8(const RadArgs*, RadStream);
int ref_gated_had_quant_i8 (const RadArgs*, RadStream);
int ref_dequant (const RadArgs*, RadStream);
int ref_dequant_w4 (const RadArgs*, RadStream);
/* ---- gemm and the vocabulary edges */
int ref_gemm_nt (const RadArgs*, RadStream);
@@ -149,7 +163,9 @@ int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_paged_anchor_window(const RadArgs*, RadStream);
int ref_attn_paged_tree (const RadArgs*, RadStream);
int ref_attn_paged_sink (const RadArgs*, RadStream);
int ref_attn_dense (const RadArgs*, RadStream);
int ref_attn_cross (const RadArgs*, RadStream);
int ref_table_add (const RadArgs*, RadStream);
@@ -271,6 +287,8 @@ 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);
int ref_moe_gemm_w4a8 (const RadArgs*, RadStream);
int ref_moe_gemm_w4a4 (const RadArgs*, RadStream);
/* The layout hooks of moe_gemm_q and moe_gemm_q_mod4: a codebook expert's views of several planes
* in the joined form of abi/rad_planes.h, checked against `dtype` (ref_moe.cpp). */
int ref_moe_cb_layout (const RadParam*, int, int, const RadEncoding*, const int*,
@@ -342,6 +360,7 @@ REF_SHAPE_FN(ref_mhc_pre_finish);
REF_SHAPE_FN(ref_mhc_post);
REF_SHAPE_FN(ref_mhc_contract);
REF_SHAPE_FN(ref_kda_update);
REF_SHAPE_FN(ref_ssd_update);
REF_SHAPE_FN(ref_hc_read);
REF_SHAPE_FN(ref_hc_write);
REF_SHAPE_FN(ref_hc_project);
@@ -349,17 +368,25 @@ REF_SHAPE_FN(ref_mtp_enter);
REF_SHAPE_FN(ref_layernorm);
REF_SHAPE_FN(ref_grid_embed);
REF_SHAPE_FN(ref_grid_embed_aa);
REF_SHAPE_FN(ref_grid_embed_cpe);
REF_SHAPE_FN(ref_lili_cand);
REF_SHAPE_FN(ref_lili_attn);
REF_SHAPE_FN(ref_lili_factor);
REF_SHAPE_FN(ref_lili_walk);
REF_SHAPE_FN(ref_add);
REF_SHAPE_FN(ref_mul);
REF_SHAPE_FN(ref_silu_mul);
REF_SHAPE_FN(ref_swiglu_clamped);
REF_SHAPE_FN(ref_router_sigmoid_topk);
REF_SHAPE_FN(ref_router_sigmoid_group_topk);
REF_SHAPE_FN(ref_swiglu_step);
REF_SHAPE_FN(ref_dsa_pool);
REF_SHAPE_FN(ref_dsa_query);
REF_SHAPE_FN(ref_gemm_nt_f32);
REF_SHAPE_FN(ref_mla_project);
REF_SHAPE_FN(ref_dsa_score);
REF_SHAPE_FN(ref_mla_attn);
REF_SHAPE_FN(ref_mla_attn_paged);
REF_SHAPE_FN(ref_gelu_mul);
REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
@@ -368,6 +395,7 @@ REF_SHAPE_FN(ref_seg_softmax_pool);
REF_SHAPE_FN(ref_seg_mean_bf16_sum);
REF_SHAPE_FN(ref_pool_rows);
REF_SHAPE_FN(ref_pool_cols);
REF_SHAPE_FN(ref_point_fourier);
REF_SHAPE_FN(ref_relu);
REF_SHAPE_FN(ref_clamp);
REF_SHAPE_FN(ref_conv2d);
@@ -387,6 +415,7 @@ REF_SHAPE_FN(ref_scatter_rows);
REF_SHAPE_FN(ref_ngram_ids);
REF_SHAPE_FN(ref_ple_gate);
REF_SHAPE_FN(ref_ple_conv);
REF_SHAPE_FN(ref_ple_conv_bias);
REF_SHAPE_FN(ref_causal_conv1d);
REF_SHAPE_FN(ref_cast);
REF_SHAPE_FN(ref_softmax);
@@ -404,11 +433,14 @@ REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
REF_SHAPE_FN(ref_gated_quant_fp8);
REF_SHAPE_FN(ref_gemm_nt_q_gated);
REF_SHAPE_FN(ref_dflash_select);
REF_SHAPE_FN(ref_dflash_markov_greedy);
REF_SHAPE_FN(ref_dflash_markov_greedy_f32);
REF_SHAPE_FN(ref_dflash_tree);
REF_SHAPE_FN(ref_gram_accum);
REF_SHAPE_FN(ref_rmsnorm_had_quant_i8);
REF_SHAPE_FN(ref_gated_had_quant_i8);
REF_SHAPE_FN(ref_dequant);
REF_SHAPE_FN(ref_dequant_w4);
REF_SHAPE_FN(ref_gemm_nt);
REF_SHAPE_FN(ref_gemm_nt_bias);
@@ -422,7 +454,9 @@ REF_SHAPE_FN(ref_embed_lookup_q);
REF_SHAPE_FN(ref_logits_gemm);
REF_SHAPE_FN(ref_attn_paged);
REF_SHAPE_FN(ref_attn_paged_anchor_window);
REF_SHAPE_FN(ref_attn_paged_tree);
REF_SHAPE_FN(ref_attn_paged_sink);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_attn_cross);
REF_SHAPE_FN(ref_table_add);
@@ -532,6 +566,8 @@ 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);
REF_SHAPE_FN(ref_moe_gemm_w4a8);
REF_SHAPE_FN(ref_moe_gemm_w4a4);
REF_SHAPE_FN(ref_scale_rows);
REF_SHAPE_FN(ref_moe_gather);
REF_SHAPE_FN(ref_row_topk);
+14 -2
View File
@@ -195,11 +195,12 @@ int ref_ple_gate(const RadArgs* a, RadStream) {
struct ConvArgs {
const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y;
bool silu;
const RadTensor* b; /* per-channel bias inside the activation (Mamba-2's conv1d), or null */
};
static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid;
const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y;
const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y, *b = o.b;
if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
@@ -217,6 +218,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
if (N <= 0) return RAD_E_SHAPE;
if (numel(x) < M * n || numel(y) < M * n || numel(w) < n * wid) return RAD_E_SHAPE;
if (resid && numel(resid) < M * n) return RAD_E_SHAPE;
if (b && numel(b) != n) return RAD_E_SHAPE;
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len;
if (cs->data && state_len < hist_len) return RAD_E_SHAPE;
@@ -263,8 +265,9 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
for (int64_t i = 0; i < hist_len; ++i)
hist[i] = (warm && cs->data) ? ldt(cs, base + (off + i) * cs_t) : 0.0f;
const float bias = b ? ldt(b, c * laststride(b)) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = 0.0f;
float acc = bias;
for (int64_t j = 0; j < wid; ++j) {
const int64_t src = t - hist_len + j * dil;
const float v = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
@@ -300,6 +303,15 @@ int ref_ple_conv(const RadArgs* a, RadStream) {
t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 8), true });
}
/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`: Mamba-2's
* conv1d at dilation one. */
int ref_ple_conv_bias(const RadArgs* a, RadStream) {
if (a->n_t < 10 || !t_in(a, 8)) return RAD_E_INVAL;
return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), t_in(a, 4),
t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 9), true,
t_in(a, 8) });
}
/* ple_conv's operands without `resid`, at dilation one and with no activation. */
int ref_causal_conv1d(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
+151
View File
@@ -273,6 +273,66 @@ int ref_dequant(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ dequant_w4
* The packed 4-bit weight back to a plain row-major bf16 [N, K]. The fragment order is
* [t][kb][lh][r][s] with eight nibbles along i, where t = n/16, r = n%16, kb = k/64,
* s = (k%64)/16, and the k inside the step is 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}.
* The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high. */
static const int kKOFF[8] = {0, 8, 1, 9, 2, 10, 3, 11};
static float f16_bits_to_f32(uint16_t h) {
uint32_t sign = (uint32_t)(h >> 15) << 31;
uint32_t exp = (uint32_t)(h >> 10) & 0x1fu;
uint32_t mant = (uint32_t)(h & 0x3ffu);
uint32_t f32;
if (exp == 0) {
if (mant == 0) f32 = sign;
else { while (!(mant & 0x400u)) { mant <<= 1; --exp; } f32 = sign | ((exp + 126u) << 23) | ((mant & 0x3ffu) << 13); }
} else if (exp == 31) {
f32 = sign | 0x7f800000u | (mant << 13);
} else {
f32 = sign | ((exp + 112u) << 23) | (mant << 13);
}
float f; std::memcpy(&f, &f32, 4); return f;
}
int ref_dequant_w4(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *wq = &a->t[0], *ws = &a->t[1], *y = &a->t[2];
const int64_t N = y->shape[0], K = y->shape[1];
const int64_t group = p_int(a, "group", 128);
const int64_t twos = p_int(a, "twos", 1);
if (N <= 0 || K <= 0 || N % 16 || K % 64 || group < 1 || K % group) return RAD_E_SHAPE;
const uint32_t* Wq = (const uint32_t*)wq->data;
const uint32_t* Ws = (const uint32_t*)ws->data;
const int64_t nkb = K / 64, ng = K / group;
const int64_t ys = y->stride[1];
for (int64_t idx = 0; idx < N * K / 8; ++idx) {
const int s = (int)(idx & 3);
const int r = (int)((idx >> 2) & 15);
const int lh = (int)((idx >> 6) & 1);
const int kb = (int)((idx >> 7) % nkb);
const int t = (int)((idx >> 7) / nkb);
const int row_n = t * 16 + r;
const uint32_t w = Wq[idx];
const int kbase = kb * 64 + s * 16 + 4 * lh;
const uint32_t sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r];
const float sc = f16_bits_to_f32((uint16_t)(sz & 0xFFFFu));
const float nz = f16_bits_to_f32((uint16_t)(sz >> 16));
const float zero = -nz - 1024.f;
for (int i = 0; i < 8; i++) {
const int n = (int)((w >> (4 * i)) & 0xF);
const float q = twos ? (float)((n ^ 8) - 8) : (float)n;
const int k = kbase + kKOFF[i];
stt(y, (size_t)row_n * K + k, (q - (twos ? 0.f : zero)) * sc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ quant_act_fp8
*
* The oracle for the block-scaled FP8 family, the activation format the production checkpoints
@@ -824,6 +884,97 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------ dflash_markov_greedy */
/* `logits`, `anchor`, `pred`w, `succ`w -> tile-local winners and `tokens`.
*
* The pinned DSpark reference adds the full-vocabulary bilinear bigram bias to each draft-head
* score, then takes a vocabulary-wide greedy argmax at every position. This is deliberately not
* `dflash_select`: no top-K candidate restriction is applied, and the result at one position is
* the predecessor for the next. Scratch is a 64-token tile decomposition used by the device row;
* the reference writes the same tile winners before selecting the global winner. */
static int ref_markov_greedy(const RadArgs* a, uint32_t logits_dtype) {
if (a->n_t < 7) return RAD_E_INVAL;
const RadTensor *logits = &a->t[0], *anchor = &a->t[1], *pred = &a->t[2];
const RadTensor *succ = &a->t[3], *tile_scores = &a->t[4], *tile_tokens = &a->t[5];
const RadTensor *out = &a->t[6];
if (!logits->data || !anchor->data || !pred->data || !succ->data ||
!tile_scores->data || !tile_tokens->data || !out->data) return RAD_E_INVAL;
if (logits->dtype != logits_dtype || pred->dtype != RAD_BF16 || succ->dtype != RAD_BF16 ||
tile_scores->dtype != RAD_F32 || tile_tokens->dtype != RAD_I32 || out->dtype != RAD_I32)
return RAD_E_DTYPE;
/* The device requires I32 anchors and reports invalid anchor tensors as shape errors. */
if (anchor->dtype != RAD_I32) return RAD_E_SHAPE;
const int64_t steps = p_int(a, "steps", 0);
const int64_t R = p_int(a, "rank", 0);
const int64_t V = p_int(a, "n_vocab", 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
const int64_t M = steps > 0 && V > 0
? band_rows(numel(logits) / (steps * V), p_int(a, "M", 0)) : 0;
if (M <= 0 || steps <= 0 || R <= 0 || V <= 0 || astr <= 0) return RAD_E_SHAPE;
if (numel(logits) < M * steps * V || numel(anchor) < (M - 1) * astr + 1 ||
numel(pred) < V * R || numel(succ) < V * R || numel(out) < M * steps)
return RAD_E_SHAPE;
const int64_t n_tiles = (V + 63) / 64;
if (numel(tile_scores) < M * n_tiles || numel(tile_tokens) < M * n_tiles)
return RAD_E_SHAPE;
const int64_t ls = laststride(logits), ps = laststride(pred), ss = laststride(succ);
const int64_t os = laststride(out), tss = laststride(tile_scores), tis = laststride(tile_tokens);
REF_PAR_FOR(M * steps * V * R)
for (int64_t m = 0; m < M; ++m) {
std::vector<float> previous((size_t)R);
int64_t pid = ld_int(anchor->dtype, anchor->data, offlin(anchor, m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t row = m * steps + l;
const bool pid_ok = pid >= 0 && pid < V;
const int64_t pb = pid_ok ? rowoff(pred, pid, R) : 0;
for (int64_t r = 0; r < R; ++r)
previous[(size_t)r] = pid_ok ? ldt(pred, pb + r * ps) : 0.0f;
float global_best = -INFINITY;
int64_t global_token = 0;
for (int64_t tile = 0; tile < n_tiles; ++tile) {
const int64_t first = tile * 64;
const int64_t end = std::min<int64_t>(first + 64, V);
float best = -INFINITY;
int64_t best_token = first;
const int64_t lb = rowoff(logits, row, V);
for (int64_t token = first; token < end; ++token) {
const float base = ldt(logits, lb + token * ls);
float score = logits_dtype == RAD_F32 ? 0.0f : base;
const int64_t sb = rowoff(succ, token, R);
for (int64_t r = 0; r < R; ++r)
score += previous[(size_t)r] * ldt(succ, sb + r * ss);
if (logits_dtype == RAD_F32) score += base;
if (score > best || (score == best && token < best_token)) {
best = score;
best_token = token;
}
}
stt(tile_scores, rowoff(tile_scores, m, n_tiles) + tile * tss, best);
st_int(tile_tokens->dtype, tile_tokens->data,
rowoff(tile_tokens, m, n_tiles) + tile * tis, best_token);
if (best > global_best || (best == global_best && best_token < global_token)) {
global_best = best;
global_token = best_token;
}
}
st_int(out->dtype, out->data, rowoff(out, m, steps) + l * os, global_token);
pid = global_token;
}
}
return RAD_OK;
}
int ref_dflash_markov_greedy(const RadArgs* a, RadStream) {
return ref_markov_greedy(a, RAD_BF16);
}
int ref_dflash_markov_greedy_f32(const RadArgs* a, RadStream) {
return ref_markov_greedy(a, RAD_F32);
}
/* ------------------------------------------------------------- dflash_tree */
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents`
*
+178 -6
View File
@@ -112,6 +112,10 @@ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"),
static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"),
OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"),
OPD_O("num_accepted"), OUT("y") };
/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`. */
static const RadOperandSpec oPleConvBias[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"),
OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"),
OPD_O("num_accepted"), WGT("b"), OUT("y") };
static const RadParamSpec pCausalConv[] = { P_INT("M"), P_INT("n"), P_INT("width"),
P_STR("dtype") };
static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"),
@@ -146,6 +150,12 @@ static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("he
static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"),
WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"),
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
/* Mamba-2's selective state update: kda_update's rollback contract with a scalar decay per head. */
static const RadParamSpec pSsdUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
P_INT("d_state"), P_INT("groups"), P_STR("mode"), P_STR("dtype"), P_STRO("state_form") };
static const RadOperandSpec oSsdUpdate[] = { OPD("x"), OPD("B"), OPD("C"), OPD("dt"),
WGT("A_log"), WGT("dt_bias"), WGT("D"), INOUT("state"), OPD("state_idx"), OPD("cu"),
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
/* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the
* sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */
static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
@@ -162,14 +172,41 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
/* A learned position table resampled to each row's grid and added in (a vision tower's). */
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
/* grid_embed_cpe adds the rows a segment carries ahead of its patches (n_prefix, `prefix`). */
static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"),
P_INTO("n_prefix") };
static const RadOperandSpec oGridEmbedCpe[] = { INOUT("x"), WGT("table"), OPD("coord"),
WGT_O("prefix") };
/* LiLiCorr's correlator (ref_lili.cpp). */
static const RadParamSpec pLiliCand[] = { P_INT("M"), P_INT("k"), P_INT("world"), P_INT("steps"),
P_INT("n"), P_STR("dtype"), P_F64O("eps"),
P_INTO("row_k") };
static const RadOperandSpec oLiliCand[] = { OPD("stats"), OPD("pas"), WGT("ln_w"), WGT("ln_b"),
WGT("up_w"), WGT("up_b"), WGT("slot"), WGT("rank"),
OUT("cand"), OUT("feat"), OUT("base") };
static const RadParamSpec pLiliAttn[] = { P_INT("M"), P_INT("steps"), P_INT("k"), P_INT("n_head"),
P_INT("head_dim"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oLiliAttn[] = { OPD("qkv"), WGT("rel"), WGT("same"), OUT("out") };
static const RadParamSpec pLiliFactor[] = { P_INT("M"), P_INT("L"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oLiliFactor[] = { OPD("h"), OPD("a"), OUT("y") };
static const RadParamSpec pLiliWalk[] = { P_INT("M"), P_INT("steps"), P_INT("k"), P_INT("n"),
P_STR("dtype"), P_F64O("eps"), P_F64O("scale") };
static const RadOperandSpec oLiliWalk[] = { OPD("edges"), OPD("aout"), OPD("cand"), OUT("tokens"),
OUT_O("scores") };
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") };
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") };
/* `kv_dtype`: the latent cache's dtype when it is not the query's (fp8_e4m3, at descale 1). */
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype"), P_STRO("kv_dtype") };
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") };
static const RadParamSpec pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"),
P_INT("rope_dim"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
static const RadOperandSpec oMlaAttnPaged[] = { OPD("q"), OPD_O("q_rope"), OPD("kv"),
OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), OPD_O("gate"), OUT("out") };
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") };
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
@@ -179,6 +216,8 @@ static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT(
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") };
static const RadParamSpec pRouterSigmoidGroup[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("n_group"), P_INT("topk_group"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
/* `div` divides the rounded sum, rounded again (default 1, the plain sum): a mean of branches
* summed pairwise, as a vocoder averages its residual blocks. */
@@ -197,6 +236,9 @@ static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype")
static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pSegPool[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oSegPool[] = { OPD("score"), OPD("v"), OPD("cu_seqlens"), OUT("y") };
/* `n` is the point's values; y has n (2 freqs + 1) columns. */
static const RadParamSpec pPointFourier[] = { P_INT("M"), P_INT("n"), P_INT("freqs"), P_INTO("pi"),
P_STR("dtype") };
/* `M` is the input row count, a multiple of `k`; y has M / k rows. */
static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"),
P_STR("dtype") };
@@ -289,9 +331,15 @@ static const RadOperandSpec oGemmQGated[] = { OPD("a"), OPD("a_scale"), WGT("b")
static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_STR("dtype") };
static const RadParamSpec pDflashMarkov[] = { P_INT("M"), P_INT("steps"), P_INT("rank"),
P_INT("n_vocab"), P_INTO("anchor_stride"),
P_STR("dtype") };
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
static const RadOperandSpec oDflashMarkov[] = { OPD("logits"), OPD("anchor"), WGT("pred"),
WGT("succ"), OUT("tile_scores"),
OUT("tile_tokens"), OUT("tokens") };
static const RadParamSpec pDflashTree[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_INT("nodes"),
@@ -384,6 +432,13 @@ static const RadOperandSpec oAttnPagedTree[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out"), OPD("spec_parent")
};
/* attn_paged with a learned sink logit a query head (gpt-oss, LiLiCorr's drafter). A name of its
* own, so no attn_paged kernel that does not know the operand can be chosen for it. */
static const RadOperandSpec oAttnPagedSink[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), WGT("sinks"), OUT("out")
};
/* Effective on kv_store, where `block_size` is RAD_REQUIRED: admits every value and refuses only a
* query that omits it. On attn_paged the key is RAD_DERIVED and the constraint is skipped
* (core/plugin/select.cpp). See the file header for the spec §7.2 consequence. */
@@ -596,7 +651,7 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_
static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"),
OPD("sorted_tok"), OPD("expert_offset"),
WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") };
/* The same op over four classes by expert number mod 4: `w`/`w_scale` class 0 at [N, K],
/* The same op over four classes by expert number mod 4: `w`/`w_scale` class 0 at [N, K],
* `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry e / 4 of class e % 4; how four ranks
* share the extra block of a five-block expert (as in libr4d's schema). */
static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"),
@@ -627,6 +682,9 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT
static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"),
P_STR("dtype") };
static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") };
static const RadParamSpec pDequantW4[] = { P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"),
P_INT("twos") };
static const RadOperandSpec oDequantW4[] = { WGT("wq"), WGT("ws"), OUT("y") };
static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") };
@@ -788,7 +846,7 @@ static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT("
* sample_topk. */
static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"),
P_INTO("vocab_off") };
static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD("params"), OUT("stats") };
static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD_O("params"), OUT("stats") };
static const RadOperandSpec oNarrow[] = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
OUT("token") };
@@ -1126,6 +1184,15 @@ static const RadOpSchema kSchemas[] = {
"verify reads state_idx[seq,num_accepted-1] and writes each candidate state_idx[seq,t]; "
"prefill reads/writes column zero, committing only the final state. cu offsets are absolute; "
"has_init=0 starts from zero and a negative initial slot emits zero output. No output norm." },
{ "ssd_update", ARR(pSsdUpdate), ARR(oSsdUpdate),
"Mamba-2 selective state update: dt'=softplus(dt+dt_bias) (identity above 20, no clamp), "
"S*=exp(-exp(A_log)*dt'); S+=dt'*x*B^T; o=S*C+D*x, B and C shared by heads/groups heads. "
"State is f32 [slot,heads,head_dim,d_state]. verify reads state_idx[seq,num_accepted-1] and "
"writes each candidate state_idx[seq,t]; prefill reads/writes column zero, committing only the "
"final state. cu offsets are absolute; has_init=0 starts from zero and a negative initial slot "
"emits zero output. state_form anchor: one committed state (column 0) and a scratch slot "
"(column width/2) of per-token records (decay, dt' x, B) replayed up to num_accepted. No output "
"norm." },
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
"The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, "
"one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); "
@@ -1163,6 +1230,32 @@ static const RadOpSchema kSchemas[] = {
"antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a "
"triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps "
"normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." },
{ "grid_embed_cpe", ARR(pGridEmbedCpe), ARR(oGridEmbedCpe),
"x += the side x side table resampled as torch's F.interpolate(bilinear, align_corners=False) -- "
"no antialias -- onto a square of side max(grid height, grid width), of which the grid keeps the "
"top-left part: RADIO's cropped position embedding (CPE). Per axis two taps at (i + 0.5) * side / "
"d - 0.5, clamped at 0 and into the table, blended along the row first; f32, rounded once before "
"the add. A row whose coordinate row is negative is the k-th of `n_prefix` learned rows ahead of its segment (RADIO's class and register tokens), k its column: it gets `prefix[k]` instead, rounded the same way." },
{ "lili_cand", ARR(pLiliCand), ARR(oLiliCand),
"LiLiCorr's candidates. `stats` [M, world * (2 + 2k)] f32 is each rank's sample_logprobs row, "
"row-interleaved; the ranks merge to the log-normaliser and the k largest pairs by value, ties to "
"the lower id. cand [M, k] i32 = those ids. For candidate j, lp_j = logit_j - lse: feat row m*k+j "
"= silu(up_w . layernorm([lp_j, exp lp_j, lp_j - lp_0, j/(k-1), j == 0]; ln_w, ln_b, eps) + "
"up_b); base row m*k+j = pas[m] + slot[m % steps] + rank[j]. f32, rounded once to the outputs." },
{ "lili_attn", ARR(pLiliAttn), ARR(oLiliAttn),
"Attention over each sequence's lattice of L = steps * k rows (row i at slot i / k): qkv [M, 3 * "
"n_head * head_dim] as q | k | v; score(i, j) = q_i . k_j * scale + rel[h][s_i - s_j + steps] + "
"(s_i == s_j ? same[h] : 0), softmax over the lattice's rows, out [M, n_head * head_dim]. No "
"mask." },
{ "lili_factor", ARR(pLiliFactor), ARR(oLiliFactor),
"y [M, 3n] = [h_i | a_s | h_i * a_s] with s = i / L: each lattice row beside its sequence's anchor "
"and their product, the factor projection's input." },
{ "lili_walk", ARR(pLiliWalk), ARR(oLiliWalk),
"LiLiCorr's walk. edges [M * steps * k, 2n] each candidate's outgoing | incoming vector, aout "
"[M, n] the anchor's; each normalised as v / max(|v|, eps). start[j] = scale * aout . in[0][j], "
"pair[s][i][j] = scale * out[s][i] . in[s+1][j]; greedy p_0 = argmax start, p_s = argmax "
"pair[s-1][p_{s-1}], first index on ties; tokens [M, steps] i32 = cand[m * steps + s][p_s]. "
"`scores` [M, steps, k, k], when passed: row 0 start for every i, row s pair[s - 1]." },
{ "add", ARR(pAdd), ARR(oBinary),
"y = a + b. An operand carrying exactly n elements against a taller output broadcasts along "
"rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last "
@@ -1182,9 +1275,10 @@ static const RadOpSchema kSchemas[] = {
"y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row "
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." },
{ "act_mul", ARR(pActMul), ARR(oBinary),
"y = act(a) * b, `act` \"silu\", \"gelu\" (exact erf), \"gelu_tanh\" or \"sigmoid\". The activation is "
"rounded to y's dtype before the product, which is the unfused pair. `a` and `b` may be column "
"slices of one fused row." },
"y = act(a) * b, `act` \"silu\", \"gelu\" (exact erf), \"gelu_tanh\", \"sigmoid\", \"quick_gelu\" or "
"\"relu\" (relu(x)^2 with one tensor in both operands). The activation is rounded to y's dtype "
"before the product, which is the unfused pair. `a` and `b` may be column slices of one fused "
"row." },
{ "seg_mean_bf16_sum", ARR(pSegMean), ARR(oSegMean),
"BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output." },
{ "seg_mean", ARR(pSegMean), ARR(oSegMean),
@@ -1201,6 +1295,10 @@ static const RadOpSchema kSchemas[] = {
"Column c of row m of y is the mean of x[m]'s columns [c*k, c*k + k), summed in f32 and rounded "
"to y's dtype, then times `mult` (default 1) and rounded again. n, the input width, is a "
"multiple of k." },
{ "point_fourier", ARR(pPointFourier), ARR(oUnary),
"A point's Fourier features: row m of y is [x | sin(x_i f_j) | cos(x_i f_j)] over x's n values, "
"sines then cosines each i-major then j, f_j = 2^j for j < freqs (times pi with `pi` 1); the "
"products f32, the sine and cosine f32 rounded once to y's dtype. y is [M, n (2 freqs + 1)]." },
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0), each operand at its own row pitch." },
{ "clamp", ARR(pMnD), ARR(oClamp),
"y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." },
@@ -1233,6 +1331,10 @@ static const RadOpSchema kSchemas[] = {
"rounding." },
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
{ "mla_attn_paged", ARR(pMlaAttnPaged), ARR(oMlaAttnPaged),
"Dense causal latent attention over a paged cache whose token row is the latent then the rotated "
"key part: score = scale * (q . latent + q_rope . rope), value = the latent; sequences as in "
"attn_paged. With `gate`, out = bf16(bf16(out) * bf16(sigmoid(gate[head])))." },
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." },
{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore),
@@ -1241,6 +1343,8 @@ static const RadOpSchema kSchemas[] = {
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." },
{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool),
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." },
{ "swiglu_step", ARR(pSwigluClamped), ARR(oGateUp),
"min(silu(gate),limit)*clamp(up,-limit,limit); gate is the first half." },
{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp),
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
@@ -1283,6 +1387,10 @@ static const RadOpSchema kSchemas[] = {
"(width-1)*dilation - 1 slots plus one a token. Absent, every token commits: the read is at "
"offset zero and the last (width-1)*dilation inputs land at offset zero, which is the prefill "
"chunk. `resid` absent drops the add and leaves the plain convolution." },
{ "ple_conv_bias", ARR(pPleConv), ARR(oPleConvBias),
"ple_conv with `b`, a per-channel bias added inside the silu: y[t] = resid[t] + silu(b[c] + "
"sum_j w[c][j] * x[t - (width-1-j)*dilation]). At dilation one with no `resid` it is Mamba-2's "
"conv1d. The window, `has_init`, `cache_idx` and `num_accepted` are ple_conv's." },
{ "causal_conv1d", ARR(pCausalConv), ARR(oCausalConv),
"y[t] = sum_j w[c][j] * x[t - (width-1-j)], a DEPTHWISE CAUSAL convolution with no activation "
"and no residual (LFM2's short convolution, whose gates the caller applies). The state, "
@@ -1357,6 +1465,12 @@ static const RadOpSchema kSchemas[] = {
"previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank "
"bigram. Serial in l by construction -- the predecessor is not known until the previous step "
"has been decided." },
{ "dflash_markov_greedy", ARR(pDflashMarkov), ARR(oDflashMarkov),
"The DSpark reference walk: score all vocabulary ids at each position as draft_logit[token] + "
"sum_r pred[previous_token][r] * succ[token][r], select the greatest score (lower id breaks "
"ties), then use that token as the next predecessor." },
{ "dflash_markov_greedy_f32", ARR(pDflashMarkov), ARR(oDflashMarkov),
"Full-vocabulary greedy Markov walk with F32 base logits and BF16 codebooks." },
{ "dflash_tree", ARR(pDflashTree), ARR(oDflashTree),
"dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: node 0 "
"is the anchor, each selected node's children are the valid candidates at the next position "
@@ -1448,11 +1562,20 @@ static const RadOpSchema kSchemas[] = {
"one kernel serves decode, speculative verify and prefill. seqused is the TOTAL key count "
"including this step's query rows. k_descale / v_descale are optional and apply to an fp8 "
"cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." },
{ "attn_paged_anchor_window", ARR(pAttnPaged), ARR(oAttnPaged),
"Paged attention with one shared window anchor at the first query position in each sequence. "
"Every row uses anchor - key < window as its lower-bound predicate; causal attention also masks "
"keys after the anchor. This operation has a distinct name because ordinary attn_paged measures "
"visibility from each query row." },
{ "attn_paged_tree", ARR(pAttnPaged), ARR(oAttnPagedTree),
"attn_paged over a tree verify (rad_drafter_tree): spec_parent[row] is -2 for an ordinary "
"causal row, else the row's parent's index within its sequence's rows (-1 for the block's "
"first row). Inside the block such a row sees itself and its ancestors only, and its window is "
"measured from the block's first position plus its depth." },
{ "attn_paged_sink", ARR(pAttnPaged), ARR(oAttnPagedSink),
"attn_paged with `sinks` [n_head] f32, one logit a query head in the scaled-score domain: it "
"joins the softmax's maximum and denominator, contributes no value, and so only shrinks the "
"keys' weights (out = sum_j p_j v_j with p_j = exp(s_j) / (sum_k exp(s_k) + exp(sink)))." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
"Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is "
"attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < "
@@ -1556,6 +1679,9 @@ static const RadOpSchema kSchemas[] = {
"when rows == n. `act` is \"sigmoid\" or \"none\", and it applies to the SCALAR. With `add` "
"present the form is y = bf16(x * act(s)) + add -- the product NARROWED before the sum, which "
"is what makes the fused form bit-identical to the pair it replaces." },
{ "router_sigmoid_group_topk", ARR(pRouterSigmoidGroup), ARR(oRouterSigmoid),
"Group-limited sigmoid routing: groups rank by the sum of their two best p + bias, selection "
"runs over the topk_group best groups; correction bias selects, original scores weight." },
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
{ "router_topk", ARR(pRouter), ARR(oRouter),
@@ -1611,6 +1737,9 @@ static const RadOpSchema kSchemas[] = {
"(idx, val) form the single-rank top-R produces. `gathered` is [M, world_size * R, 2] pairs, "
"rank r's at [r*R, (r+1)*R); id -1 is a pad and is dropped. Ties break on the LOWER id, which is "
"what makes the merged answer agree with a top-R over the unsharded plane." },
{ "dequant_w4", ARR(pDequantW4), ARR(oDequantW4),
"Packed int4 weight to row-major bf16. Each 32-bit word holds 8 codes; the scale is "
"f16 in the low 16 bits, the zero point -(1024+zero) as f16 in the high 16 bits." },
{ "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax),
"idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first "
"f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower "
@@ -2231,6 +2360,8 @@ SIMPLE("ref_mhc_contract", "mhc_contract", "norm", "mean of manifold residual st
ref_mhc_contract),
SIMPLE("ref_kda_update", "kda_update", "gdn", "bounded per-channel delta recurrence and candidate rollback", DT_FLOAT,
ref_kda_update),
SIMPLE("ref_ssd_update", "ssd_update", "gdn", "Mamba-2 scalar-decay recurrence and candidate rollback", DT_FLOAT,
ref_ssd_update),
ROWL("ref_hc_read", "hc_read", "norm",
"gated residual read: grouped norm, low-rank gate, stream mix",
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined",
@@ -2251,6 +2382,17 @@ SIMPLE("ref_grid_embed", "grid_embed", "elem",
SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem",
"antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT,
ref_grid_embed_aa),
SIMPLE("ref_grid_embed_cpe", "grid_embed_cpe", "elem",
"half-pixel bilinear resample of a position grid onto a square, cropped, added in", DT_FLOAT,
ref_grid_embed_cpe),
SIMPLE("ref_lili_cand", "lili_cand", "draft", "LiLiCorr candidates and their features",
DT_FLOAT, ref_lili_cand),
SIMPLE("ref_lili_attn", "lili_attn", "draft", "LiLiCorr lattice attention with slot biases",
DT_FLOAT, ref_lili_attn),
SIMPLE("ref_lili_factor", "lili_factor", "draft", "LiLiCorr factor input [h | a | h * a]",
DT_FLOAT, ref_lili_factor),
SIMPLE("ref_lili_walk", "lili_walk", "draft", "LiLiCorr edge scores and greedy walk", DT_FLOAT,
ref_lili_walk),
SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add),
SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul),
SIMPLE("ref_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT,
@@ -2263,6 +2405,10 @@ SIMPLE("ref_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_
ref_dsa_query),
SIMPLE("ref_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
ref_gemm_nt_f32),
SIMPLE("ref_mla_attn_paged", "mla_attn_paged", "attn", "dense paged latent attention with a rotary part",
DT_FLOAT, ref_mla_attn_paged),
SIMPLE("ref_swiglu_step", "swiglu_step", "elem", "SwiGLU clipped after the SiLU", DT_FLOAT,
ref_swiglu_step),
SIMPLE("ref_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT,
ref_mla_project),
SIMPLE("ref_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT,
@@ -2289,6 +2435,8 @@ SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows,
DT_FLOAT, ref_pool_rows),
SIMPLE("ref_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
"multiplier", DT_FLOAT, ref_pool_cols),
SIMPLE("ref_point_fourier", "point_fourier", "elem", "a point's sines and cosines at octaves",
DT_FLOAT, ref_point_fourier),
SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu),
SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp),
SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
@@ -2323,6 +2471,9 @@ SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot
DT_FLOAT, ref_ple_gate),
SIMPLE("ref_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add",
DT_FLOAT, ref_ple_conv),
SIMPLE("ref_ple_conv_bias", "ple_conv_bias", "norm",
"ple_conv with a per-channel bias inside the silu (Mamba-2's conv1d)", DT_FLOAT,
ref_ple_conv_bias),
SIMPLE("ref_causal_conv1d", "causal_conv1d", "conv", "depthwise causal conv, no activation",
DT_FLOAT, ref_causal_conv1d),
SIMPLE("ref_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, ref_gather_rows),
@@ -2353,6 +2504,14 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
SIMPLE("ref_dflash_select", "dflash_select", "draft",
"DFlash2's greedy walk over the candidate lattice",
"i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select),
SIMPLE("ref_dflash_markov_greedy", "dflash_markov_greedy", "draft",
"DSpark's full-vocabulary greedy Markov walk",
"bf16 logits and codebooks, f32/i32 tile winners, i32 tokens out",
ref_dflash_markov_greedy),
SIMPLE("ref_dflash_markov_greedy_f32", "dflash_markov_greedy_f32", "draft",
"Full-vocabulary greedy Markov walk with F32 base logits",
"f32 logits, bf16 codebooks, f32/i32 tile winners, i32 tokens out",
ref_dflash_markov_greedy_f32),
SIMPLE("ref_dflash_tree", "dflash_tree", "draft",
"DFlash2's candidate lattice grown best-first into a tree",
"i32 candidates, bf16 codebooks, i32 tokens and parents out", ref_dflash_tree),
@@ -2387,6 +2546,7 @@ SIMPLE("ref_gated_had_quant_i8", "gated_had_quant_i8", "quant",
"gated product, rotation and int8 in one pass", "float in, i8 out, f32 scale",
ref_gated_had_quant_i8),
SIMPLE("ref_dequant", "dequant", "quant", "group-scaled dequantisation", DT_ANY, ref_dequant),
SIMPLE("ref_dequant_w4", "dequant_w4", "quant", "packed int4 weight to row-major bf16", DT_ANY, ref_dequant_w4),
SIMPLE("ref_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate", DT_FLOAT, ref_gemm_nt),
SIMPLE("ref_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT,
@@ -2413,11 +2573,21 @@ ROW("ref_attn_paged", "attn_paged", "attn",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged, nullptr),
ROW("ref_attn_paged_anchor_window", "attn_paged_anchor_window", "attn",
"paged attention with an exact shared anchor-aligned sliding window",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged_anchor_window, nullptr),
ROW("ref_attn_paged_tree", "attn_paged_tree", "attn",
"paged causal / sliding-window attention with a tree verify block (spec_parent)",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; i32 parents",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged_tree, nullptr),
ROW("ref_attn_paged_sink", "attn_paged_sink", "attn",
"paged causal / sliding-window attention with a sink logit a head, any query length",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; f32 sinks",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_attn_paged_sink, nullptr),
SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
ref_attn_dense),
SIMPLE("ref_attn_cross", "attn_cross", "attn",
@@ -2445,6 +2615,8 @@ SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary
SIMPLE("ref_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row",
DT_FLOAT, ref_scale_rows),
SIMPLE("ref_router_sigmoid_group_topk", "router_sigmoid_group_topk", "moe",
"group-limited sigmoid correction-bias routing", DT_FLOAT, ref_router_sigmoid_group_topk),
SIMPLE("ref_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
ref_router_sigmoid_topk),
SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
+4 -4
View File
@@ -674,9 +674,9 @@ int ref_sample_argmax(const RadArgs* a, RadStream) {
* floats (exact below 2^24). Read before any sampling stage, as OpenAI's and llama-server's
* logprobs report. Rows without the flag are not written. Under a split vocabulary ids are global
* (+ `vocab_off`) and the host merges ranks; an unfilled slot is id -1, logit -infinity. The sum is
* in double. */
* in double. Without `params` every row is written (a drafter's candidate logprobs). */
int ref_sample_logprobs(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
if (a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
const int64_t k = p_int(a, "k", 0);
@@ -686,11 +686,11 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) {
const int64_t w = 2 + 2 * k;
if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(param_rows(pr, M, &R));
if (pr->data) RAD_REF_TRY(param_rows(pr, M, &R));
REF_PAR_FOR(M * n_vocab * (k + 2))
for (int64_t m = 0; m < M; ++m) {
if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
if (pr->data && !(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t sb = rowoff(st, m, w), ss = laststride(st);
float mx = -INFINITY;
+283 -3
View File
@@ -358,6 +358,27 @@ int ref_kda_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("kda_update", operand, out);
}
int ref_ssd_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const char* form = gs(p, n_p, "state_form");
if (form && !std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0);
const int64_t P = gi(p, n_p, "head_dim", 0), N = gi(p, n_p, "d_state", 0);
const int64_t G = gi(p, n_p, "groups", 0);
if (M < 1 || H < 1 || P < 1 || N < 1 || G < 1 || H % G) return RAD_E_UNSUPPORTED;
const char* mode = gs(p, n_p, "mode");
const int64_t history = mode && !std::strcmp(mode, "verify") ? M : 1;
Opd o;
o.t(D, {M, H, P}); o.t(D, {M, G, N}); o.t(D, {M, G, N}); o.t(D, {M, H});
o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H});
o.t((uint32_t)RAD_F32, {history + 1, H, P, N});
o.t_idx({1, history}, history + 1, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE);
o.t_idx({2}, M, -1, (uint32_t)RAD_OPD_F_IDX_CU);
o.t_idx({1}, 0, 1, 0); o.t_idx({1}, 0, 1, 0);
o.t(D, {M, H, P});
return o.finish("ssd_update", operand, out);
}
int ref_mhc_pre_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
@@ -488,6 +509,64 @@ int ref_grid_embed_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("grid_embed_aa", operand, out);
}
/* grid_embed's operands plus the prefix rows; coordinates drawn over the table's side. */
int ref_grid_embed_cpe_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), side = gi(p, n_p, "side", 0);
const int64_t npre = gi(p, n_p, "n_prefix", 0);
if (M <= 0 || n <= 0 || side <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x, INOUT */
o.t(D, { side * side, n }); /* table */
o.t_idx({ 4, M }, side, -1, 0);
o.t(D, { npre > 0 ? npre : 1, n }); /* prefix */
return o.finish("grid_embed_cpe", operand, out);
}
/* LiLiCorr's ops. lili_cand declines: its stats rows (sample_logprobs' sorted pairs and positive
* sums) are no draw; avx_check_hand.cpp builds them. The others draw freely. */
int ref_lili_cand_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; }
int ref_lili_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), S = gi(p, n_p, "steps", 0), k = gi(p, n_p, "k", 0);
const int64_t nh = gi(p, n_p, "n_head", 0), hd = gi(p, n_p, "head_dim", 0);
if (M <= 0 || S <= 0 || k <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED;
const int64_t rows = (M + S * k - 1) / (S * k) * (S * k); /* whole lattices */
Opd o;
o.t(D, { rows, 3 * nh * hd }); /* qkv */
o.t((uint32_t)RAD_F32, { nh, 2 * S + 1 }); /* rel */
o.t((uint32_t)RAD_F32, { nh }); /* same */
o.t(D, { rows, nh * hd }); /* out */
return o.finish("lili_attn", operand, out);
}
int ref_lili_factor_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), L = gi(p, n_p, "L", 0), n = gi(p, n_p, "n", 0);
if (M <= 0 || L <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const int64_t rows = (M + L - 1) / L * L;
Opd o;
o.t(D, { rows, n }); /* h */
o.t(D, { rows / L, n }); /* a */
o.t(D, { rows, 3 * n }); /* y */
return o.finish("lili_factor", operand, out);
}
int ref_lili_walk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), S = gi(p, n_p, "steps", 0), k = gi(p, n_p, "k", 0);
const int64_t n = gi(p, n_p, "n", 0);
if (M <= 0 || S <= 0 || k <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M * S * k, 2 * n }); /* edges */
o.t(D, { M, n }); /* aout */
o.t_idx({ M * S, k }, 1000, -1, 0); /* cand: ids, copied */
o.t((uint32_t)RAD_I32, { M, S }); /* tokens */
o.t((uint32_t)RAD_F32, { M, S, k, k }); /* scores */
return o.finish("lili_walk", operand, out);
}
int ref_layernorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
@@ -634,6 +713,16 @@ int ref_pool_cols_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("pool_cols", operand, out);
}
int ref_point_fourier_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), F = gi(p, n_p, "freqs", 0);
if (M <= 0 || n <= 0 || F <= 0 || F > 30) return RAD_E_UNSUPPORTED;
Opd o;
o.t(RAD_F32, { M, n }); /* x */
o.t(D, { M, n * (2 * F + 1) }); /* y */
return o.finish("point_fourier", operand, out);
}
int ref_relu_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
@@ -763,6 +852,24 @@ int ref_router_sigmoid_topk_shape(const RadParam* p, int n_p, int operand, RadOp
o.t(D, { M, k });
return o.finish("router_sigmoid_topk", operand, out);
}
int ref_swiglu_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_silu_mul_shape(p, n_p, operand, out);
}
int ref_router_sigmoid_group_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0),
k = gi(p, n_p, "top_k", 0), ng = gi(p, n_p, "n_group", 0),
kg = gi(p, n_p, "topk_group", 0);
if (M < 1 || ne < 1 || ne > 512 || k < 1 || ng < 1 || ne % ng || ne / ng < 2 || kg < 1 ||
kg > ng || k > kg * (ne / ng))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, ne });
o.t(RAD_F32, { ne });
o.t_idx({ M, k }, ne, -1, 0);
o.t(D, { M, k });
return o.finish("router_sigmoid_group_topk", operand, out);
}
int ref_mla_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0),
l = gi(p, n_p, "latent_dim", 0);
@@ -822,14 +929,39 @@ int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
pages = std::max((int64_t)2, B * M);
if (M < 1 || D < 1 || D > 2048 || H < 1 || B < 1 || bs < 1) return RAD_E_UNSUPPORTED;
const uint32_t dtype = act_dt(p, n_p);
/* The cache is the query's dtype unless `kv_dtype` names another (fp8_e4m3). */
const char* kvs = gs(p, n_p, "kv_dtype");
const uint32_t kv = kvs && dt_parse(kvs) != (uint32_t)RAD_DT_INVALID ? dt_parse(kvs) : dtype;
Opd o;
o.t(dtype, { M, H, D });
o.t(dtype, { pages, 1, bs, D });
o.t(kv, { pages, 1, bs, D });
o.t_idx({ M, B }, pages, -1, 0);
o.t_idx({ M }, 0, B * bs, 0);
o.t(dtype, { M, H, D });
return o.finish("mla_attn", operand, out);
}
/* One sequence whose context is its query (a prefill chunk), as attn_paged describes itself; a
* harness passes `ctx` for a deeper history. */
int ref_mla_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), L = gi(p, n_p, "latent_dim", 0),
R = gi(p, n_p, "rope_dim", 0), H = gi(p, n_p, "heads", 0),
bs = gi(p, n_p, "block_size", 0);
if (M < 1 || L < 1 || L > 2048 || R < 1 || H < 1 || bs < 1) return RAD_E_UNSUPPORTED;
int64_t ctx = gi(p, n_p, "ctx", 0);
if (ctx < M) ctx = M;
const int64_t blocks = (ctx + bs - 1) / bs;
const uint32_t dtype = act_dt(p, n_p);
Opd o;
o.t(dtype, { M, H, L }); /* q */
o.t(dtype, { M, H, R }); /* q_rope */
o.t(dtype, { blocks, 1, bs, L + R }); /* kv */
o.t_idx({ 1, blocks }, blocks, -1, 0); /* block_table */
o.t_idx({ 1 }, 0, ctx, 0); /* seqused */
o.t_idx({ 2 }, M, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens: [0, M], one sequence */
o.skip(); /* gate */
o.t(dtype, { M, H, L }); /* out */
return o.finish("mla_attn_paged", operand, out);
}
int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
@@ -961,6 +1093,27 @@ int ref_ple_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("ple_conv", operand, out);
}
/* ple_conv's description with `b` before `y`. */
int ref_ple_conv_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t wid = gi(p, n_p, "width", 0), dil = gi(p, n_p, "dilation", 1);
if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_UNSUPPORTED;
const int64_t S = 1, hist = (wid - 1) * dil, depth = hist - 1 + M;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { n, wid }); /* w */
o.t(D, { S, n, depth }); /* conv_state, INOUT */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */
o.t(D, { M, n }); /* resid */
o.t_idx({ S }, S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx */
o.t_idx({ S }, 0, 1, 0); /* has_init: warm */
o.t_idx({ S }, 0, M, 0); /* num_accepted: read at M - 1 */
o.t(D, { n }); /* b */
o.t(D, { M, n }); /* y */
return o.finish("ple_conv_bias", operand, out);
}
/* ple_conv's description without `resid` and at dilation one. */
int ref_causal_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
@@ -1186,6 +1339,17 @@ int ref_dequant_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("dequant", operand, out);
}
int ref_dequant_w4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
const int64_t group = gi(p, n_p, "group", 128);
if (N < 1 || K < 1 || N % 16 || K % 64 || group < 1 || K % group) return RAD_E_UNSUPPORTED;
Opd o;
o.t(RAD_I4, { N * K }); /* wq -- packed int4: N*K nibbles = N*K/2 bytes = N*K/8 dwords */
o.t(RAD_F32, { N * K / group }); /* ws -- scale (f16 in a dword, but declared f32) */
o.t(RAD_BF16, { N, K }); /* y */
return o.finish("dequant_w4", operand, out);
}
/* ================================================================== gemm */
int ref_gemm_nt_f32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
@@ -1369,7 +1533,8 @@ int ref_lora_expand_mm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
* The block count and context length are this description's choice; any cache large enough for
* the indices will do. */
int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
static int ref_attn_paged_shape_impl(const RadParam* p, int n_p, int operand, RadOpdDesc* out,
const char* op_name) {
/* `q_len` is the ranged parameter, a query length (one row at decode, thousands in a prefill
* chunk; different kernels, docs/OPS.md). */
const int64_t M = gi(p, n_p, "q_len", 0);
@@ -1408,7 +1573,15 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
* would have to agree with a tool's `M` rather than this description's. */
o.skip(); /* cu_seqlens */
o.t(Q, { S * M, nh, hd }); /* out */
return o.finish("attn_paged", operand, out);
return o.finish(op_name, operand, out);
}
int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_attn_paged_shape_impl(p, n_p, operand, out, "attn_paged");
}
int ref_attn_paged_anchor_window_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_attn_paged_shape_impl(p, n_p, operand, out, "attn_paged_anchor_window");
}
/* attn_paged's operands and its tree's parents, each row an ordinary causal one (-2): a drawn
@@ -1423,6 +1596,24 @@ int ref_attn_paged_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDes
return o.finish("attn_paged_tree", operand, out);
}
/* attn_paged's operands with the sinks before `out`: a learned logit a query head. */
int ref_attn_paged_sink_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int nbase = 8;
if (operand < 7) return ref_attn_paged_shape(p, n_p, operand, out);
if (operand == 8) return ref_attn_paged_shape(p, n_p, nbase - 1, out);
if (operand != 7 || !out) return RAD_E_SHAPE;
const int64_t gqa = gi(p, n_p, "gqa", 1);
const int64_t nh = gi(p, n_p, "n_head", gqa);
if (nh <= 0) return RAD_E_UNSUPPORTED;
std::memset(out, 0, sizeof *out);
out->fill = (uint32_t)RAD_FILL_NORMAL;
out->idx_const = -1;
out->dtype = (uint32_t)RAD_F32;
out->rank = 1;
out->shape[0] = nh;
return RAD_OK;
}
int ref_attn_dense_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);
@@ -1953,6 +2144,10 @@ static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) {
* `w` is described stacked [ne, N, K], since a fixture cannot hold a pointer table; expert_entry()
* reads both forms. */
int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
if (const char* dk = gs(p, n_p, "dtype")) {
if (!std::strcmp(dk, "w4a8")) return ref_moe_gemm_w4a8_shape(p, n_p, operand, out);
if (!std::strcmp(dk, "w4a4")) return ref_moe_gemm_w4a4_shape(p, n_p, operand, out);
}
const int64_t M = gi(p, n_p, "M", 0);
const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0);
const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0);
@@ -2033,6 +2228,61 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes
return o.finish("moe_gemm_q_mod4", operand, out);
}
/* The grouped int4 GEMM: an int8 activation with an f32 scale per (row, 128 of K), two's-
* complement int4 experts (nibbles, -8..7) with an f32 scale per (row, 128 of K); one weight
* table, token-order a only. */
int ref_moe_gemm_w4a8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0);
const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0);
const int64_t ne = gi(p, n_p, "n_expert", 0);
const int64_t k = gi(p, n_p, "top_k", 0);
if (M <= 0 || N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || K0 % 128 || K1 % 128 ||
ne <= 0 || k <= 0)
return RAD_E_UNSUPPORTED;
const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1;
const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2;
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
Opd o;
o.t((uint32_t)RAD_I8, { AR, K }); /* a -- int8 (the E4M3 arm is 8-bit too) */
o.t((uint32_t)RAD_F32, { AR, K / 128 }); /* a_scale */
o.t((uint32_t)RAD_I4, { ne0, N0, K0 }); /* w -- even experts, nibbles */
o.t((uint32_t)RAD_BF16, { ne0, N0, K0 / 128 }); /* w_scale */
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
o.t((uint32_t)RAD_I4, { ne1, N1, K1 }); /* w_odd -- odd experts */
o.t((uint32_t)RAD_BF16, { ne1, N1, K1 / 128 }); /* w_odd_scale */
o.t((uint32_t)RAD_BF16, { M * k, N }); /* y -- in sorted order */
return o.finish("moe_gemm_q", operand, out);
}
/* The same over a two's-complement int4 activation (two nibbles per byte): the w4a8 grid with an
* I4 a, so the activation row is K/2 bytes. */
int ref_moe_gemm_w4a4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0);
const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0);
const int64_t ne = gi(p, n_p, "n_expert", 0);
const int64_t k = gi(p, n_p, "top_k", 0);
if (M <= 0 || N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || K0 % 128 || K1 % 128 ||
ne <= 0 || k <= 0)
return RAD_E_UNSUPPORTED;
const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1;
const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2;
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
Opd o;
o.t((uint32_t)RAD_I4, { AR, K }); /* a -- int4, two nibbles per byte */
o.t((uint32_t)RAD_F32, { AR, K / 128 }); /* a_scale */
o.t((uint32_t)RAD_I4, { ne0, N0, K0 }); /* w -- even experts, nibbles */
o.t((uint32_t)RAD_BF16, { ne0, N0, K0 / 128 }); /* w_scale */
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
o.t((uint32_t)RAD_I4, { ne1, N1, K1 }); /* w_odd -- odd experts */
o.t((uint32_t)RAD_BF16, { ne1, N1, K1 / 128 }); /* w_odd_scale */
o.t((uint32_t)RAD_BF16, { M * k, N }); /* y -- in sorted order */
return o.finish("moe_gemm_q", operand, out);
}
int ref_moe_gather_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 k = gi(p, n_p, "top_k", 0);
@@ -2195,6 +2445,36 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("dflash_select", operand, out);
}
/* The full-vocabulary DSpark Markov walk. Its tile planes hold one exact local max per 64 ids. */
static int ref_markov_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out,
uint32_t logits_dtype, const char* op) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t steps = gi(p, n_p, "steps", 0);
const int64_t R = gi(p, n_p, "rank", 0);
const int64_t nv = gi(p, n_p, "n_vocab", 0);
const int64_t astr = gi(p, n_p, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || R <= 0 || nv <= 0 || astr <= 0)
return RAD_E_UNSUPPORTED;
const int64_t rows = M * steps;
const int64_t tiles = (nv + 63) / 64;
Opd o;
o.t(logits_dtype, { rows, nv }); /* logits */
o.t_idx_dt((uint32_t)RAD_I32, { M * astr }, nv, -1, 0); /* anchor */
o.t((uint32_t)RAD_BF16, { nv, R }); /* pred */
o.t((uint32_t)RAD_BF16, { nv, R }); /* succ */
o.t((uint32_t)RAD_F32, { M, tiles }); /* tile_scores */
o.t_idx_dt((uint32_t)RAD_I32, { M, tiles }, nv, -1, 0); /* tile_tokens */
o.t_idx_dt((uint32_t)RAD_I32, { M, steps }, nv, -1, 0); /* tokens */
return o.finish(op, operand, out);
}
int ref_dflash_markov_greedy_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_markov_shape(p, n_p, operand, out, RAD_BF16, "dflash_markov_greedy");
}
int ref_dflash_markov_greedy_f32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return ref_markov_shape(p, n_p, operand, out, RAD_F32, "dflash_markov_greedy_f32");
}
/* dflash_select's operands, then `nodes` tokens and parents a sequence. */
int ref_dflash_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
+233
View File
@@ -0,0 +1,233 @@
/* ref_ssd.cpp -- the Mamba-2 selective state update (SSD), token by token.
*
* ============================== The algorithm ==============================
*
* Per token, per head h of `heads`, with the state S shaped [head_dim, d_state] and g = h / (heads /
* groups) the head's B/C group:
*
* dt' = softplus(dt[h] + dt_bias[h]) A = -exp(A_log[h])
* S *= e^{dt' A}
* S += dt' . x[h] B[g]^T o[h] = S C[g] + D[h] . x[h]
*
* A Mamba-2 head is a gated delta net head without the delta: one scalar decay per head and token,
* no beta, no l2 norm on B or C, and the skip term D. The gdn ops cannot run it (their rank-1 update
* subtracts S k and their keys are normalised), so it is an op of its own.
*
* dt is not clamped. The checkpoint's `time_step_limit` is (0, inf), which is what mamba_ssm's
* kernels and vLLM pass; transformers' CPU fallback clamps dt at `time_step_min` and is not what
* the model was trained or is served with. softplus keeps torch's and mamba_ssm's threshold: above
* 20 it is the identity.
*
* The output excludes the model's gated norm.
*
* ============================== The layouts ==============================
*
* x, o [T, heads, head_dim] or [T, heads*head_dim]
* B, C [T, groups, d_state] or [T, groups*d_state]
* dt [T, heads] A_log, dt_bias, D [heads], f32
* state [n_slots, heads, head_dim, d_state], f32 state_idx [N, W] cu [N+1]
*
* The rollback contract is kda_update's, in both forms. `per_candidate`: `mode=verify` reads column
* `num_accepted - 1` of the sequence's `state_idx` row and writes the state after token t of the
* window to column t; `mode=prefill` reads column zero and writes only the final state there.
* `has_init` 0 starts from zero, a negative read slot gives zero output and a negative write slot
* is skipped.
*
* `anchor`: column zero is the committed state and column `width/2` a scratch slot of the same
* shape. Per head the scratch holds a replay count and then one record per window token: the
* decay e^{dt' A}, u = dt' x (head_dim) and B (d_state), 1 + head_dim + d_state floats, as many as
* the [head_dim, d_state] block holds, at most 32 (a 64 x 128 head holds 42). `mode=verify` first
* replays the previous window's accepted prefix (`num_accepted` records, at most the stored count)
* onto the committed state, publishes it, then runs the window from it writing each token's record
* and the window length as the new count. The rank-1 update is replayed with the same arithmetic,
* so the committed state is the per-candidate form's bit for bit. `mode=prefill` commits its final
* state and sets the count to zero; a zeroed scratch replays nothing.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <cmath>
#include <cstring>
#include <vector>
using namespace ref;
namespace {
/* Rows of `width` columns per (token, head), whether the tensor is 3-D or flattened to 2-D. */
bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t width) {
return t.data && t.shape[0] == tokens &&
((t.rank == 3 && t.shape[1] == heads && t.shape[2] == width) ||
(t.rank == 2 && t.shape[1] == heads * width));
}
int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) {
return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) +
d * laststride(&t);
}
float softplus(float v) { return v > 20.0f ? v : std::log1p(std::exp(v)); }
/* The anchor scratch's records: per window token 1 + head_dim + d_state floats behind the count. */
int64_t anchor_tokens(int64_t P, int64_t Nst) {
const int64_t fit = (P * Nst - 1) / (1 + P + Nst);
return fit < 32 ? fit : 32;
}
} // namespace
int ref_ssd_update(const RadArgs* a, RadStream) {
if (!a || a->n_t < 13) return RAD_E_INVAL;
for (int i = 0; i < 10; ++i)
if (!rad_arg_in(a, i)) return RAD_E_INVAL;
if (!rad_arg_in(a, 12)) return RAD_E_INVAL;
const int64_t H = p_int(a, "heads", 0), P = p_int(a, "head_dim", 0);
const int64_t Nst = p_int(a, "d_state", 0), G = p_int(a, "groups", 0);
const char* mode = p_str(a, "mode", "");
const bool verify = !std::strcmp(mode, "verify");
if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL;
const char* form = p_str(a, "state_form", "per_candidate");
const bool anchor = !std::strcmp(form, "anchor");
if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
if (H <= 0 || P <= 0 || Nst <= 0 || G <= 0 || H % G) return RAD_E_SHAPE;
const int64_t rec = 1 + P + Nst, deepest = anchor_tokens(P, Nst);
if (anchor && deepest < 1) return RAD_E_SHAPE;
const auto &x = a->t[0], &B = a->t[1], &C = a->t[2], &dt = a->t[3];
const auto &alog = a->t[4], &dtb = a->t[5], &dskip = a->t[6], &state = a->t[7];
const auto &idx = a->t[8], &cu = a->t[9];
const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11);
const auto& out = a->t[12];
if (x.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE;
const int64_t T = x.shape[0], N = cu.shape[0] - 1;
if (T < 1) return RAD_E_SHAPE;
if (!headed(x, T, H, P) || !headed(B, T, G, Nst) || !headed(C, T, G, Nst) ||
!headed(dt, T, H, 1) || !headed(out, T, H, P) || numel(&alog) != H || numel(&dtb) != H ||
numel(&dskip) != H || state.rank != 4 || state.dtype != RAD_F32 || state.shape[1] != H ||
state.shape[2] != P || state.shape[3] != Nst || idx.dtype != RAD_I32 || idx.rank != 2 ||
idx.shape[0] < N || idx.shape[1] < 1 ||
(accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) ||
(init && (init->dtype != RAD_I32 || numel(init) < N)))
return RAD_E_SHAPE;
const int64_t width = idx.shape[1], slots = state.shape[0];
/* Every address is checked before any state is written, so a malformed batch cannot leave a
* partly committed prefix behind an error. */
for (int64_t seq = 0; seq < N; ++seq) {
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
const int64_t na =
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
const int64_t most = anchor ? deepest : width;
if (begin < 0 || end < begin || end > T || na < 1 || na > most ||
(verify && end - begin > most) || (anchor && width < 2))
return RAD_E_SHAPE;
for (int64_t j = 0; j < width; ++j)
if (ld_int(idx.dtype, idx.data, seq * idx.stride[0] + j * idx.stride[1]) >= slots)
return RAD_E_SHAPE;
if (anchor) {
const int64_t read = ld_int(idx.dtype, idx.data, seq * idx.stride[0]);
const int64_t scratch =
ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]);
if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE;
if (verify && read >= 0 &&
(!init || ld_int(init->dtype, init->data, offlin(init, seq))))
for (int64_t h = 0; h < H; ++h) {
const float count =
ldt(&state, scratch * state.stride[0] + h * state.stride[1]);
if (!std::isfinite(count) || count < 0 || count > (float)deepest ||
count != std::floor(count) || (count > 0 && na > count))
return RAD_E_SHAPE;
}
}
}
const int64_t per_group = H / G;
#pragma omp parallel for schedule(static)
for (int64_t sh = 0; sh < N * H; ++sh) {
const int64_t seq = sh / H, head = sh % H, grp = head / per_group;
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
if (begin == end) continue;
const int64_t na =
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
const int64_t read =
ld_int(idx.dtype, idx.data,
seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]);
if (read < 0) {
for (int64_t t = begin; t < end; ++t)
for (int64_t e = 0; e < P; ++e) stt(&out, off(out, t, head, e, P), 0);
continue;
}
const bool initialized = !init || ld_int(init->dtype, init->data, offlin(init, seq)) != 0;
std::vector<float> S((size_t)(P * Nst)), b((size_t)Nst), c((size_t)Nst);
const int64_t sb = read * state.stride[0] + head * state.stride[1];
for (int64_t e = 0; e < P; ++e)
for (int64_t d = 0; d < Nst; ++d)
S[e * Nst + d] =
initialized ? ldt(&state, sb + e * state.stride[2] + d * state.stride[3]) : 0;
const int64_t scratch =
anchor ? ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1])
: 0;
auto factor_at = [&](int64_t i) {
return scratch * state.stride[0] + head * state.stride[1] +
(i / Nst) * state.stride[2] + (i % Nst) * state.stride[3];
};
if (anchor && verify) {
/* The accepted prefix of the previous window, onto the committed state, published. */
const int64_t replay = initialized ? (int64_t)ldt(&state, factor_at(0)) : 0;
for (int64_t t = 0; t < (replay ? na : 0); ++t) {
const int64_t f = 1 + t * rec;
const float decay = ldt(&state, factor_at(f));
for (int64_t d = 0; d < Nst; ++d) b[(size_t)d] = ldt(&state, factor_at(f + 1 + P + d));
for (int64_t e = 0; e < P; ++e) {
const float u = ldt(&state, factor_at(f + 1 + e));
for (int64_t d = 0; d < Nst; ++d) {
float& s = S[e * Nst + d];
s = s * decay + u * b[d];
}
}
}
for (int64_t e = 0; e < P; ++e)
for (int64_t d = 0; d < Nst; ++d)
stt(&state, sb + e * state.stride[2] + d * state.stride[3], S[e * Nst + d]);
}
const float A = -std::exp(ldt(&alog, head * laststride(&alog)));
const float bias = ldt(&dtb, head * laststride(&dtb));
const float skip = ldt(&dskip, head * laststride(&dskip));
for (int64_t t = begin; t < end; ++t) {
const float step = softplus(ldt(&dt, off(dt, t, head, 0, 1)) + bias);
const float decay = std::exp(step * A);
for (int64_t d = 0; d < Nst; ++d) {
b[d] = ldt(&B, off(B, t, grp, d, Nst));
c[d] = ldt(&C, off(C, t, grp, d, Nst));
}
const int64_t f = 1 + (t - begin) * rec;
if (anchor && verify) {
stt(&state, factor_at(f), decay);
for (int64_t d = 0; d < Nst; ++d) stt(&state, factor_at(f + 1 + P + d), b[d]);
}
for (int64_t e = 0; e < P; ++e) {
const float xe = ldt(&x, off(x, t, head, e, P));
const float u = step * xe;
if (anchor && verify) stt(&state, factor_at(f + 1 + e), u);
float result = 0;
for (int64_t d = 0; d < Nst; ++d) {
float& s = S[e * Nst + d];
s = s * decay + u * b[d];
result += s * c[d];
}
stt(&out, off(out, t, head, e, P), result + skip * xe);
}
if ((verify && !anchor) || (!verify && t + 1 == end)) {
const int64_t write =
ld_int(idx.dtype, idx.data,
seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]);
if (write >= 0)
for (int64_t e = 0; e < P; ++e)
for (int64_t d = 0; d < Nst; ++d)
stt(&state,
write * state.stride[0] + head * state.stride[1] +
e * state.stride[2] + d * state.stride[3],
S[e * Nst + d]);
}
}
if (anchor) stt(&state, factor_at(0), verify ? (float)(end - begin) : 0.0f);
}
return RAD_OK;
}