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

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+162 -1
View File
@@ -75,12 +75,19 @@ struct KvDyn {
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
/* 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];
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;
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
@@ -162,6 +169,27 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t qb = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
/* A tree row: its ancestors inside the block (a bit per row) and its depth. */
const int64_t base = ctx - qlen;
bool tree = false;
uint64_t tmask = 0;
int64_t tdep = 0;
if (tpar) {
const int64_t first = tok - i;
int64_t pj = ld_int(tpar->dtype, tpar->data, offlin(tpar, tok));
if (pj != -2 && i < 64) {
tree = true;
tmask = 1ull << i;
for (int64_t at = i; pj >= 0 && pj < at; ) {
tmask |= 1ull << pj;
++tdep;
at = pj;
pj = ld_int(tpar->dtype, tpar->data, offlin(tpar, first + pj));
}
}
}
const int64_t wpos = tree ? base + tdep : pos;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
@@ -171,8 +199,9 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
* unmapped. */
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
if (tree && j >= base && !((tmask >> (j - base)) & 1)) return -1;
if (window > 0) {
const int64_t d = pos - j;
const int64_t d = wpos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
}
const int64_t blk =
@@ -247,6 +276,14 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* 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) {
if (a->n_t < 9 || !t_in(a, 8)) return RAD_E_INVAL;
if (p_int(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED;
return ref_attn_paged(a, s);
}
/* ------------------------------------------------------------------ attn_dense */
/* For the vision tower: unpaged, unquantised, `cu_seqlens` bounding one image (or attention window)
* per entry so a whole batch is one launch. Causal is a parameter so a dense decoder-only prefill
@@ -565,6 +602,102 @@ int ref_kv_store(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ kv_store_streamed */
/* The store of a streamed group (docs/OPS.md "kv_store_streamed"): `kv_store` into both of the
* group's copies. host[b], the authoritative mirror, is written always; kv_cache[res[b]] only when
* the block is resident. The writer must test residency: at decode the block a step writes is
* usually the one the previous step made resident, so a mirror-only writer would leave the ring's
* copy missing this step's tokens, and the resolve, seeing it resident, would not copy it. The
* caller's order is store, resolve, attention. The planes are the same paged layout at the same
* pitch, so one conversion writes both. `res` is read, never written; an entry outside
* [-1, slots) for a touched block, or a slot past the id space, is refused before any write. */
int ref_kv_store_streamed(const RadArgs* a, RadStream) {
if (!have(a, 6)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
const RadTensor *res = &a->t[4], *host = &a->t[5];
const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0);
const int64_t block_size = p_int(a, "block_size", 0);
const int64_t kv_heads = p_int(a, "n_head_kv", 0);
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE;
if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE;
if (host->dtype != RAD_U8) return RAD_E_DTYPE;
/* E4M3 or bf16: a bf16 group doubles every offset and stores the value itself, as
* kv_store_bf16 does. A packed fp8_v4/k6_v4 group has no streamed row. */
const bool fp8 = kv->dtype == RAD_F8E4M3;
if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED;
if (kv->rank != 4) return RAD_E_SHAPE;
if (kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE;
if (host->rank != 2) return RAD_E_SHAPE;
/* Both planes are dense rows of one block of one layer: a padded mirror row would copy over its
* neighbour, and the two copies must share offsets. */
const int64_t EB = fp8 ? 1 : 2;
const int64_t row = kv_heads * block_size * 2 * head_dim * EB;
const int64_t slots = kv->shape[0], blocks = host->shape[0];
if (host->shape[1] != row || host->stride[0] * rad_dtype_bytes(host->dtype, 1) != row)
return RAD_E_STRIDE;
if (kv->stride[0] * rad_dtype_bytes(kv->dtype, 1) != row) return RAD_E_STRIDE;
if (slots <= 0 || blocks <= 0) return RAD_E_SHAPE;
if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE;
const int64_t M = numel(sm);
if (M <= 0 || numel(k) < M * kv_heads * head_dim || numel(v) < M * kv_heads * head_dim)
return RAD_E_SHAPE;
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
/* kv_store_bf16 stores the value itself; only the E4M3 row divides by the reader's descales. */
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
/* Everything that can refuse is checked before the first write: a half-written mirror would
* make later copies plausible and wrong. */
const int32_t* const R = (int32_t*)res->data;
for (int64_t t = 0; t < M; ++t) {
const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (s < 0) continue; /* padded row, no cache slot */
const int64_t blk = s / block_size;
if (blk >= blocks) return RAD_E_SHAPE;
if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL;
}
/* The mirror seen as the plane it holds, so both copies round the same. */
RadTensor hkv = *host;
hkv.dtype = kv->dtype;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
const KVView hv = kv_view(&hkv, head_dim, block_size, kv_heads);
REF_PAR_FOR(M * kv_heads * head_dim * 2)
for (int64_t t = 0; t < M; ++t) {
const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (s < 0) continue;
const int64_t blk = s / block_size, off = s % block_size;
const int64_t hb = blk * hv.sb + off * hv.so;
/* A non-resident block is written to the mirror alone; the resolve copies it in whole. */
const int64_t cb = R[blk] >= 0 ? R[blk] * kvv.sb + off * kvv.so : -1;
for (int64_t h = 0; h < kv_heads; ++h) {
for (int64_t d = 0; d < head_dim; ++d) {
const float xk = ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks;
const float xv = ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs;
stt(&hkv, hb + h * hv.sh + d * hv.sd, xk);
stt(&hkv, hb + h * hv.sh + (head_dim + d) * hv.sd, xv);
if (cb >= 0) {
stt(kv, cb + h * kvv.sh + d * kvv.sd, xk);
stt(kv, cb + h * kvv.sh + (head_dim + d) * kvv.sd, xv);
}
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rope */
namespace {
@@ -674,6 +807,34 @@ static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t*
} /* namespace */
/* Ministral 3's query multiplier, applied after rotary and rounded to the activation dtype
* before the product. Only the supplied query slice is changed; keys and values stay intact. */
int ref_position_scale(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pos = &a->t[1];
// M in the resolved geometry is a capacity band; issued views carry the active rows.
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
const int64_t n = p_int(a, "n", 0), orig = p_int(a, "original", 0);
const float beta = p_f32(a, "beta", -1);
if (M <= 0 || M > p_int(a, "M", 0) || n <= 0 || orig <= 0 || !std::isfinite(beta) || beta < 0 ||
x->rank != 2 || x->shape[0] < M || x->shape[1] != n || pos->rank != 1 || numel(pos) < M)
return RAD_E_SHAPE;
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
/* Validate all positions before writing: an invalid batch must not leave a partial result. */
for (int64_t r = 0; r < M; ++r)
if (ld_int(pos->dtype, pos->data, offlin(pos, r)) < 0) return RAD_E_INVAL;
REF_PAR_FOR(M * n)
for (int64_t r = 0; r < M; ++r) {
const int64_t p = ld_int(pos->dtype, pos->data, offlin(pos, r));
const float scale = round_dt(x->dtype, 1.0f + beta * std::log(1.0f + (float)(p / orig)));
for (int64_t j = 0; j < n; ++j) {
const int64_t at = rowoff(x, r, n) + j * laststride(x);
stt(x, at, ldt(x, at) * scale);
}
}
return RAD_OK;
}
int ref_rope(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1];
+179 -19
View File
@@ -51,8 +51,14 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
* them), outside of which the input reads zero (each sequence is padded on its own). w is
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
* dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none,
* tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */
* dil (k - 1), on the left (any k). A `stride` s > 1 comes in two forms. The causal one (a reach
* of at least s) keeps every s-th output row: the left pad is the reach less s, and a sequence of
* L rows (every bound a whole number of strides) gives L / s; `cu_div` reads the bounds in units
* that many input rows apart. With an explicit `pad` (bf16 only) it is PyTorch's zero-padded
* strided conv over one sequence of all of x, any k: output row m reads
* x[m * stride + tap * dil - pad], and y has exactly (rows + 2 pad - dil (k - 1) - 1) / stride + 1
* rows. `res`, when bound, is added after the bias; then `act` (none, tanh, or clamp to [-1, 1],
* a vocoder's output clamp). f32 accumulation, one rounding. */
int ref_conv1d(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2];
@@ -60,29 +66,50 @@ int ref_conv1d(const RadArgs* a, RadStream) {
if (!y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), pp = p_int(a, "pad", -1), cd = p_int(a, "cu_div", 1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1)
/* The causal strided form or the padded one, never both. */
const bool padded = pp >= 0 && st > 1;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (pp >= 0 && (st <= 1 || causal || cd != 1)) ||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
const int64_t cdv = padded ? 1 : cd;
/* A stride takes each sequence of L rows to L / stride, so every bound is a whole number of
* strides (of cu_div units each); the padded form bounds only its one full sequence. */
for (int64_t e = 0; !padded && e <= n_seq; ++e)
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0) / cdv, r1 = cu_at(cu, n_seq) / cdv;
if (r0 < 0 || r1 <= r0 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2;
REF_PAR_FOR((r1 - r0) * cout * cin * k)
for (int64_t r = r0; r < r1; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
int64_t rmin = r0 / st, rmax = r1 / st;
if (padded) {
if (x->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(x, cin)) return RAD_E_SHAPE;
rmin = 0;
rmax = (r1 + 2 * pp - dil * (k - 1) - 1) / st + 1;
}
if (rmin >= rmax) return RAD_E_SHAPE;
if (padded ? rows_of(y, cout) != rmax : rows_of(y, cout) < rmax) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < rmax) return RAD_E_SHAPE;
/* Causal: the reach is dil (k - 1) + 1 input rows and the left pad that less the stride, so
* output row o of a sequence reads input rows o stride - pad .. o stride + stride - 1. The
* padded form takes PyTorch's zero padding from the explicit `pad` instead. */
const int64_t pad = padded ? pp : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
REF_PAR_FOR((rmax - rmin) * cout * cin * k)
for (int64_t r = rmin; r < rmax; ++r) {
const int64_t e = seq_of(cu, n_seq, r * st * cdv);
const int64_t s0 = cu_at(cu, e) / cdv, s1 = cu_at(cu, e + 1) / cdv;
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
for (int64_t co = 0; co < cout; ++co) {
float acc = 0.0f;
for (int64_t kk = 0; kk < k; ++kk) {
const int64_t ir = r + kk * dil - pad;
const int64_t ir = r * st + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const int64_t xb = rowoff(x, ir, cin), xs = laststride(x);
for (int64_t ci = 0; ci < cin; ++ci)
@@ -256,6 +283,9 @@ int ref_snake_aa(const RadArgs* a, RadStream) {
* `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates
* the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and
* drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream).
* With `top_p` < 1 the kept list is cut first where the cumulative probability of the whole
* candidate set's softmax over temp (summed in index order) passes top_p, as Fish Audio's sampler
* cuts it: a rank whose inclusive cumulative probability exceeds top_p is dropped, rank 0 never.
* The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or
* bf16; seed [n, 2]; frame [n]. */
int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
@@ -267,8 +297,10 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
const float pen = p_f32(a, "penalty", 1.0f);
const double top_p = (double)p_f32(a, "top_p", 1.0f);
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) ||
!(top_p >= 0))
return RAD_E_SHAPE;
const int64_t n = numel(ids) / rep;
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
@@ -319,13 +351,32 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
if (open(j)) idx[(size_t)nc++] = j;
}
if (nc == 0) return RAD_E_SHAPE;
const int64_t kk = std::min(K, nc);
/* The whole candidate set's normaliser, in index order (idx still is), for top_p. */
double z = 0;
if (top_p < 1.0) {
float gm = g[(size_t)idx[0]];
for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[(size_t)idx[(size_t)t]]);
const float m0 = gm / temp;
for (int64_t t = 0; t < nc; ++t)
z += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m0));
}
int64_t kk = std::min(K, nc);
std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc,
[&](int64_t p, int64_t q) {
return g[(size_t)p] > g[(size_t)q] ||
(g[(size_t)p] == g[(size_t)q] && p < q);
});
const float m = g[(size_t)idx[0]] / temp;
if (top_p < 1.0) {
double cum = 0;
int64_t keep = 1;
for (int64_t t = 0; t < kk; ++t) {
cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z;
if (t > 0 && cum > top_p) break;
keep = t + 1;
}
kk = keep;
}
double tot = 0;
std::vector<double> e((size_t)kk);
for (int64_t t = 0; t < kk; ++t) {
@@ -361,24 +412,26 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
const float scale = p_f32(a, "scale", 1.0f);
const int64_t round1 = p_int(a, "round", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, D);
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D);
/* `clamp`: a code above clamp - 1 reads row clamp - 1 (a negative one still reads nothing). */
auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
REF_PAR_FOR(rows * D * K)
for (int64_t r = 0; r < rows; ++r) {
const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0;
const int64_t c0 = cl(ld_int(codes->dtype, codes->data, r * rp)) + off0;
if (c0 < 0 || c0 >= r0) continue;
std::vector<float> acc((size_t)D, 0.0f);
const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D);
if (round1)
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0));
for (int64_t k = 1; k < K; ++k) {
const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
const int64_t ck = cl(ld_int(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc;
if (ck < 0 || ck >= r1) continue;
const int64_t tb = rowoff(t1, ck, D);
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1));
@@ -392,6 +445,62 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ vq_encode */
/* One step of a residual vector quantiser with factorised, L2-normalised codes (DAC's
* VectorQuantize, as Fish Audio's codec encodes): per row of x [rows, n], e = in_w x + in_b
* (in_w [dim, n]); the code is the row of cb [bins, dim] of greatest cosine with e,
* (e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12)), the lower index on a tie; then
* x -= out_w cb[code] + out_b (out_w [n, dim], the raw codebook row), rounded once into x. f32,
* every sum in index order. A chain of these over a codec's codebooks is its residual quantiser,
* each step quantising what the last left. */
int ref_vq_encode(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
return RAD_E_SHAPE;
/* The codebook normalised once, as F.normalize divides. */
std::vector<float> cn((size_t)(bins * dim));
for (int64_t c = 0; c < bins; ++c) {
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) ss += ldt(cb, c * dim + j) * ldt(cb, c * dim + j);
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = ldt(cb, c * dim + j) / nrm;
}
REF_PAR_FOR(rows * (dim * n + bins * dim + n * dim))
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
std::vector<float> e((size_t)dim);
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) {
float acc = 0.0f;
for (int64_t d = 0; d < n; ++d) acc += ldt(iw, j * n + d) * ldt(x, xb + d * xs);
e[(size_t)j] = acc + ldt(ib, j);
ss += e[(size_t)j] * e[(size_t)j];
}
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) e[(size_t)j] /= nrm;
int64_t best = 0;
float bs = -INFINITY;
for (int64_t c = 0; c < bins; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < dim; ++j) s += e[(size_t)j] * cn[(size_t)(c * dim + j)];
if (s > bs) { bs = s; best = c; }
}
st_int(codes->dtype, codes->data, offlin(codes, r), best);
for (int64_t d = 0; d < n; ++d) {
float q = 0.0f;
for (int64_t j = 0; j < dim; ++j) q += ldt(ow, d * dim + j) * ldt(cb, best * dim + j);
stt(x, xb + d * xs, ldt(x, xb + d * xs) - (q + ldt(ob, d)));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ frame_mix_store */
/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale))
* with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row
@@ -437,6 +546,44 @@ int ref_frame_mix_store(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ ras_pick */
/* Fish Audio's repetition-aware sampling, the choice between two draws a lane: the first draw
* ids[rep i] = first[rep i], unless it lies in [lo, hi) and the lane's window (its last `win`
* picks, `hist` [lanes, win], oldest first, -1 empty) holds it, in which case the alternative
* draw alt[rep i] is taken. The pick then enters the window, its oldest entry leaving. `clear` 1
* empties the lane's window first (a piece's first pick). A pick outside [lo, hi) (Fish's end of
* speech) is never redrawn. */
int ref_ras_pick(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3];
const RadTensor* ids = &a->t[4];
const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0);
const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0);
const int64_t n = numel(lane);
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n)
return RAD_E_SHAPE;
for (int64_t i = 0; i < n; ++i) {
const int64_t L = ldi(lane, i);
if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE;
}
for (int64_t i = 0; i < n; ++i) {
const int64_t hb = ldi(lane, i) * W;
if (clear)
for (int64_t w = 0; w < W; ++w) st_int(hist->dtype, hist->data, offlin(hist, hb + w), -1);
const int64_t f = ldi(first, rep * i);
int64_t pick = f;
if (f >= lo && f < hi)
for (int64_t w = 0; w < W; ++w)
if (ldi(hist, hb + w) == f) { pick = ldi(alt, rep * i); break; }
for (int64_t r = 0; r < rep; ++r) st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
for (int64_t w = 0; w + 1 < W; ++w)
st_int(hist->dtype, hist->data, offlin(hist, hb + w), ldi(hist, hb + w + 1));
st_int(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ end_status */
/* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end`
* (the model ended the piece), else the pick. */
@@ -746,6 +893,19 @@ int ref_int_affine(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ sub_i32 */
/* y[i] = x[i] - s[0], int32: a device length less a device offset. */
int ref_sub_i32(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
const int64_t n = numel(y);
if (n <= 0 || numel(x) < n || numel(s) < 1) return RAD_E_SHAPE;
const int64_t s0 = ldi(s, 0);
for (int64_t i = 0; i < n; ++i)
st_int(y->dtype, y->data, offlin(y, i), (int64_t)(int32_t)(ldi(x, i) - s0));
return RAD_OK;
}
/* ------------------------------------------------------------------ cu_repeat */
/* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's
* lengths live on the device (a window's frames, the latents a vocoder decodes per channel group),
+60
View File
@@ -436,6 +436,39 @@ int ref_seg_mean(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_softmax_pool */
/* y[s, :] = sum over the segment's rows r of softmax(score)[r] * v[r, :]: one row a cu_seqlens
* segment, the weights a softmax over the segment's own scores (f32, the maximum subtracted), the
* sum in f32 and rounded once. A query reading its few candidates with learned scores (clef's
* routing over a question's options). An empty segment writes zeros. */
int ref_seg_softmax_pool(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *Sc = &a->t[0], *V = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
const int64_t n = p_int(a, "n", 0);
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = cu_at(cu, S);
if (total <= 0 || numel(V) < total * n || numel(Sc) < total) return RAD_E_SHAPE;
REF_PAR_FOR((total + S) * n)
for (int64_t s = 0; s < S; ++s) {
const int64_t b0 = cu_at(cu, s);
const int64_t b1 = cu_at(cu, s + 1);
const int64_t yb = rowoff(Y, s, n), ys = laststride(Y), vs = laststride(V);
float m = -INFINITY, z = 0.0f;
for (int64_t r = b0; r < b1; ++r) m = std::max(m, ldt(Sc, rowoff(Sc, r, 1)));
for (int64_t r = b0; r < b1; ++r) z += std::exp(ldt(Sc, rowoff(Sc, r, 1)) - m);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t r = b0; r < b1; ++r)
acc += std::exp(ldt(Sc, rowoff(Sc, r, 1)) - m) / z *
ldt(V, rowoff(V, r, n) + i * vs);
stt(Y, yb + i * ys, b1 > b0 ? acc : 0.0f);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_rows */
/* Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then
* multiplied by `mult` and rounded again, as the unfused pair stores the mean. For vision poolers
@@ -465,6 +498,33 @@ int ref_pool_rows(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_cols */
/* 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 multiplied by `mult` and rounded again: torch's adaptive_avg_pool1d over the
* feature axis. */
int ref_pool_cols(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), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0 || n % k) return RAD_E_SHAPE;
const int64_t M = rows_of(X, n), nw = n / k;
if (M <= 0 || numel(Y) < M * nw) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
REF_PAR_FOR(M * nw * k)
for (int64_t r = 0; r < M; ++r) {
const int64_t yb = rowoff(Y, r, nw), ys = laststride(Y), xs = laststride(X);
for (int64_t c = 0; c < nw; ++c) {
float acc = 0.0f;
for (int64_t j = 0; j < k; ++j) acc += ldt(X, rowoff(X, r, n) + (c * k + j) * xs);
stt(Y, yb + c * ys, acc * inv);
stt(Y, yb + c * ys, ldt(Y, yb + c * ys) * mult);
}
}
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) {
+25 -3
View File
@@ -286,8 +286,8 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c
* acc += (sub * a_scale[m]) * scale
* ZP_I8_GROUP sub = sum(a * (code - zero)) exact
* acc += (sub * a_scale[m][g]) * scale
* ZP_F16 sub = sum over ascending k of a * (code - zero), each product exact in f32
* acc += sub * scale
* ZP_F16 BF16 inputs are first narrowed to F16 (the cast kernel's rounding); sub is
* the sum over ascending k of a * (code - zero), then acc += sub * scale
*
* `a` is already in column order (the caller undoes the step order). `a_sum` is quant_act_i8's,
* group-major [K/group][Mpad], Mpad = ceil(M/16)*16; the grid's zero is removed through it, as
@@ -319,7 +319,29 @@ static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_,
const int64_t acols = parts * K;
if (numel(A) < M * acols) return RAD_E_SHAPE;
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, acols), acs = laststride(A);
int64_t ars = row_stride(A, acols), acs = laststride(A);
/* A BF16 activation (the W4 decode graph's, which the card narrows on load) is narrowed to F16
* first, with the cast kernel's rounding, so the F16 grid sees what the card's GEMM sees. */
std::vector<uint16_t> narrowed;
RadTensor a_f16{};
if (zg.act == ZP_F16 && A->dtype == RAD_BF16) {
narrowed.resize((size_t)(M * acols));
for (int64_t m = 0; m < M; ++m)
for (int64_t k = 0; k < acols; ++k)
narrowed[(size_t)(m * acols + k)] = f32_to_f16(ldt(A, m * ars + k * acs));
a_f16 = *A;
a_f16.data = narrowed.data();
a_f16.dtype = RAD_F16;
a_f16.rank = 2;
a_f16.shape[0] = M;
a_f16.shape[1] = acols;
a_f16.stride[0] = acols;
a_f16.stride[1] = 1;
A = &a_f16;
ars = acols;
acs = 1;
}
const bool i8 = zg.act != ZP_F16;
if (i8 && A->dtype != RAD_I8) return RAD_E_DTYPE;
-13
View File
@@ -69,22 +69,9 @@ struct Scales {
int64_t group; /* K elements per scale */
int64_t rblk; /* operand rows per scale row; 1 unless the grid is block-scaled */
bool e8m0; /* the scale stream is OCP e8m0 exponent bytes, not floats */
/* M2XFP4 (libquant's `m2xfp4`, lq_m2xfp.cpp): `group` is 8, so `g` names a subgroup. The
* E8M0 byte is one per four subgroups and the meta plane's two-bit field refines it, the
* scale of subgroup g being e8m0(scale[g >> 2]) . (1 + k/4) with k the field's value -- the
* quantiser's own decode, which this states where it folds the product. */
const uint8_t* m2_meta = nullptr; /* [rows][K/32] meta bytes, canonical rows */
int64_t m2_mrs = 0; /* bytes between meta rows */
bool m2 = false;
/* The scale of group `g` of `row`. */
inline float grp(int64_t row, int64_t g) const {
if (m2) {
const int64_t gi = g >> 2;
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + gi * cs;
const int k = (m2_meta[row * m2_mrs + gi] >> (2 * (g & 3))) & 3;
return e8m0_to_f32(((const uint8_t*)p)[i]) * (1.0f + 0.25f * (float)k);
}
int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i);
}
+89 -13
View File
@@ -164,14 +164,16 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */
/* The checks both forms share: `s` holds [shift | scale] in each of its n_seq rows, `g` a gate
* row per sequence when `gated`, and every row operand at least `rows` rows. */
* row per sequence when `gated`, and every row operand at least `rows` rows. With `mapped`, the
* sequences address table rows through the column map, so `s` and `g` may hold fewer rows than
* there are sequences; the map's bound is the caller's. */
static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor* s,
const RadTensor* w, const RadTensor* x, int64_t n, int64_t n_seq,
int64_t rows, bool gated) {
int64_t rows, bool gated, bool mapped) {
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || (w && numel(w) < n) ||
numel(s) < n_seq * 2 * n)
(!mapped && numel(s) < n_seq * 2 * n))
return RAD_E_SHAPE;
if (gated && (rows_of(y, n) < rows || numel(g) < n_seq * n)) return RAD_E_SHAPE;
if (gated && (rows_of(y, n) < rows || (!mapped && numel(g) < n_seq * n))) return RAD_E_SHAPE;
return RAD_OK;
}
@@ -230,11 +232,14 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor*
/* A diffusion transformer's adaptive RMS norm with a shift (MiniMax-H3's
* `norm(h) * (1 + scale) + shift`), the gated residual of the branch before it optionally first;
* the norm chain rounds to z's dtype. */
* the norm chain rounds to z's dtype.
*
* The optional trailing `colmap` (slot 7, or 9 for the quantising form), one i32 a sequence, maps a
* sequence to its row of the modulation table, so sequences that share a cell read one row. */
int ref_rms_mod(const RadArgs* a, RadStream) {
if (a->n_t < 7) return RAD_E_INVAL;
const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3);
const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6];
const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6], *cm = t_in(a, 7);
const int64_t n = p_int(a, "n", 0);
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
@@ -246,11 +251,14 @@ int ref_rms_mod(const RadArgs* a, RadStream) {
if (none && t_in(a, 3)) return RAD_E_INVAL;
if (n <= 0 || (gated && (!y || !g))) return RAD_E_SHAPE;
const int64_t rows = rows_of(z, n), n_seq = numel(cu) - 1;
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated));
if (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE;
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated, cm != nullptr));
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> o((size_t)n);
rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data(), wadd, once, layer, none);
int64_t e = seq_of(cu, n_seq, r);
if (cm) e = (int64_t)ldt(cm, e);
rms_mod_row(y, g, s, w, x, r, e, n, eps, gated, z->dtype, o.data(), wadd, once, layer, none);
const int64_t zb = rowoff(z, r, n), zs = laststride(z);
for (int64_t i = 0; i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]);
}
@@ -264,6 +272,7 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) {
if (a->n_t < 9) return RAD_E_INVAL;
const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3);
const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8);
const RadTensor *cm = t_in(a, 9);
const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0);
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
@@ -275,12 +284,15 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) {
if (none && t_in(a, 3)) return RAD_E_INVAL;
if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE;
const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated));
if (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE;
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated, cm != nullptr));
if (numel(sc) < rows * ngrp || (z && rows_of(z, n) < rows)) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> o((size_t)n);
rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none);
int64_t e = seq_of(cu, n_seq, r);
if (cm) e = (int64_t)ldt(cm, e);
rms_mod_row(y, g, s, w, x, r, e, n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none);
const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0;
for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]);
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
@@ -298,7 +310,10 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) {
/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where
* f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value
* diffusers' pipeline hands its transformer: t rounded to bf16 at scale, divided back and rounded
* again, then scaled: scale * bf16(bf16(t * scale) / scale). */
* again, then scaled: scale * bf16(bf16(t * scale) / scale). t is raised to `clamp_min` first.
* With `curve` = G > 0 and a `table` [G, n] f32 operand instead, y[m] is the table at
* clamp01(max(t[m], clamp_min)) (G - 1), between the two rows around it: a curve-form
* checkpoint's embeddings. */
int ref_timestep_embed(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *t = &a->t[0], *y = &a->t[1];
@@ -306,13 +321,36 @@ int ref_timestep_embed(const RadArgs* a, RadStream) {
const float scale = p_f32(a, "scale", 1000.0f);
const double mp = p_f32(a, "max_period", 10000.0f);
const int round = (int)p_int(a, "round", 0);
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
const float clamp = p_f32(a, "clamp_min", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t grid = p_int(a, "curve", 0);
if (!grid && (n & 1)) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE;
if (grid > 0) {
const RadTensor* tab = t_in(a, 2);
if (!tab) return RAD_E_INVAL;
if (tab->dtype != (uint32_t)RAD_F32 || numel(tab) < grid * n) return RAD_E_SHAPE;
for (int64_t m = 0; m < rows; ++m) {
const float tv = std::fmax(ldt(t, offlin(t, m)), clamp);
const float pos = std::fmin(std::fmax(tv, 0.0f), 1.0f) * (float)(grid - 1);
float i0f = std::floor(pos);
if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2);
const float fr = pos - i0f;
const int64_t i0 = (int64_t)i0f;
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
for (int64_t i = 0; i < n; ++i) {
const float a0 = ldt(tab, offlin(tab, i0 * n + i));
const float a1 = ldt(tab, offlin(tab, (i0 + 1) * n + i));
stt(y, yb + i * ys, a0 + fr * (a1 - a0));
}
}
return RAD_OK;
}
const int64_t h = n / 2;
const float coef = (float)(-std::log(mp));
for (int64_t m = 0; m < rows; ++m) {
const float tv = ldt(t, offlin(t, m));
const float tv = std::fmax(ldt(t, offlin(t, m)), clamp);
const float tt = round == 3 ? rbf(scale * rbf(tv)) : round == 2 ? scale * rbf(tv)
: round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv;
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
@@ -532,6 +570,44 @@ int ref_flow_x0_step(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ flow_res_multistep */
/* k-diffusion's res_multistep at eta 0 (DPM-Solver++ 2M) on the clean estimate d = x + sigma v:
* x' = r x + hb1 d + hb2 x0, r = sigma_next / sigma and x0 the last step's estimate, which d then
* replaces; with `order` < 2, Euler, x' = r x + (1 - r) d. sigma, r, hb1, hb2 and order are one
* f32 each, x and x0 f32. */
int ref_flow_res_multistep(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor *v = &a->t[0], *x0 = &a->t[1], *sg = &a->t[2], *rr = &a->t[3];
const RadTensor *hb1 = &a->t[4], *hb2 = &a->t[5], *ord = &a->t[6], *x = &a->t[7];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || rows_of(v, n) < rows || rows_of(x0, n) < rows || numel(sg) < 1 ||
numel(rr) < 1 || numel(hb1) < 1 || numel(hb2) < 1 || numel(ord) < 1)
return RAD_E_SHAPE;
const float sgv = ldt(sg, offlin(sg, 0));
const float r = ldt(rr, offlin(rr, 0));
const float b1 = ldt(hb1, offlin(hb1, 0));
const float b2 = ldt(hb2, offlin(hb2, 0));
const bool two = ldt(ord, offlin(ord, 0)) >= 1.5f;
const float omr = 1.0f - r;
REF_PAR_FOR(rows * n)
for (int64_t k = 0; k < rows; ++k) {
const int64_t vb = rowoff(v, k, n), vs = laststride(v);
const int64_t xb = rowoff(x, k, n), xs = laststride(x);
const int64_t ob = rowoff(x0, k, n), os = laststride(x0);
for (int64_t c = 0; c < n; ++c) {
const float xv = ldt(x, xb + c * xs);
const float d = xv + sgv * ldt(v, vb + c * vs);
const float nx = two ? r * xv + b1 * d + b2 * ldt(x0, ob + c * os)
: r * xv + omr * d;
stt(x, xb + c * xs, nx);
stt(x0, ob + c * os, d);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ kd_input, kd_step */
/* A k-diffusion sampler over a discrete-time (VP-trained) denoiser, run in the variance-exploding
* form x = x0 + sigma eps: the lane holds x in f32, the model reads c_in x with
+292
View File
@@ -0,0 +1,292 @@
/* ref_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and
* the ring slots its device pool holds. The operands, layouts and contract are in docs/OPS.md
* ("kv_resolve"); docs/KV-STREAMING.md §3.4 is the design.
*
* `qsa_select` writes pool page ids into `sel` and `attn_paged` uses each entry as a raw pool
* index. When the group streams, the pool is `slots` blocks deep while the id space is `blocks`, so
* kv_resolve rewrites every selected id as the ring slot holding it, copying a block in from the
* host mirror when it is absent. `sel` is the only place the sparse path names KV storage, so the
* attention is unchanged; `nsel` and `seqused` are token counts and stay as written.
*
* Parameters: `M` (ranged), `blocks` (the id space), `slots` (the declared ring), `sel_pitch`
* (topk + 1) and `block_bytes` (one block of one layer: the mirror's row pitch, the ring's slot
* pitch and every copy's length). Bytes rather than `block_size`, because the op never reads an
* element and is the same code at every cache layout, and because Builder::find_kv_consumer binds
* a group to the first op carrying `block_size`, which must stay the attention. The operands state
* the pitches too, and must agree. `slot_block`'s extent is the ring the call may address; a call
* deeper than the declared `slots` is refused.
*
* The miss list is the row's scratch, not an operand: a device row declares
* `(next_pow2(slots) + slots) * 4` bytes (`miss_block[next_pow2(slots)]`, padded for an in-place
* sort, then `miss_slot[slots]`). This reference sorts locally.
*
* State, which the caller brings up: `res` and `slot_block` filled with -1, `slot_state` and `ctl`
* zeroed. There is no reset op; the maps live as long as the pool. A call entering with a `res`
* entry of -2 or outside [-1, slots), a `slot_block` entry outside [-1, blocks), or a hand outside
* [0, slots) is refused as a state fault. `ctl` is 16 i32s, 8-byte aligned:
*
* [0] epoch of the last call [1] CLOCK hand [2] blocks placed by the last call
* [3] overflow, latched [4..5] u64 misses [6..7] u64 lookups [8..9] u64 calls
* [10] largest union of one call (distinct blocks, hits + misses)
* [11] largest placement of one call
* [12] largest claim count of one call: the depth the miss list must hold, at most
* `M * sel_pitch`; a device kernel sizes its list from those operands, and this says
* whether that was enough
*
* The epoch is a wrapping i32 compared only for equality. `slot_state[s,1]` is a two-bit heat
* counter in [0, 3], kept in the i32.
*
* One call:
*
* 1. epoch = ctl[0] + 1.
* 2. One lookup per distinct block, rows then entries ascending, over [0, nsel[q]). A hit
* (res[b] >= 0) stamps the slot with the epoch and, once a slot a call, bumps its heat
* (clamped at 3), so heat counts calls that wanted the block, not selection width. A miss
* (res[b] == -1) is claimed: res[b] = -2 and b joins the miss list. -2 is already claimed; the
* map is its own set.
* 3. The miss list is sorted by block id, so two implementations place the same blocks in the
* same slots whatever their thread order.
* 4. One victim per miss, in that order. Identity first: slot b when b < slots and the slot is
* free or holds b, and not stamped by this call; the hand does not move. It never evicts, keeps
* a context shorter than the ring at identity, and puts adjacent ids in adjacent slots. Else
* walk from the hand: a free slot is taken before any resident block, a slot stamped this call
* is passed, and once a whole turn finds nothing free the walk is CLOCK with the heat counter
* as its reference: a counter above 0 is halved and passed, a cold slot is the victim. A 3
* survives two passes, so the sweep visits at most 3 * slots slots. The hand ends one past the
* last slot taken. The free scan changes nothing when it finds nothing.
* 5. Re-point both maps as each victim is taken (res[old] = -1, slot_block[s] = b, res[b] = s,
* slot_state[s] = {epoch, min(heat + 1, 3)}): a placement is a use.
* 6. Copy block_bytes from host[b] into slot s, as bytes.
* 7. Rewrite every entry in [0, nsel[q]) as res[b]; the -1 padding past it is kept.
*
* Then ctl[0..2] take the epoch, hand and placement, the counters grow (lookups count entries), and
* the maxima are updated.
*
* Overflow: the ring must hold every distinct block one call selects. At decode that is at most
* `max_seqs * (sel_pitch - 1)`; a prefill launch above `qsa_exact_to` can select a chunk's history,
* which is why the engine reads ctl[10] rather than assuming a bound. A miss the sweep cannot place
* reverts to res[b] = -1, ctl[3] latches, and its entries are rewritten as slot 0: a defined
* address inside the ring, where the block id would be a device address past it. The step's
* numbers are then wrong, so a caller that finds ctl[3] set must discard the step.
*
* The op is stateful (epoch, hand, heat, counters), so two launches must never overlap: its rows
* are not in libr4d's rad_kernel_concurrent list, which orders each behind everything before it.
* It is still recordable: it is a function of device state whose addresses and pitches are fixed
* from bring-up.
*
* This is the serial form of the contract, the oracle two device implementations must agree with
* on which slot every block lands in.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <algorithm>
#include <cstring>
#include <vector>
using namespace ref;
namespace {
/* The heat counter's two writes, the same function in all three implementations: a use bumps by
* one and saturates at 3, a sweep pass halves, and a negative value (never written by a legal call)
* reads as cold rather than letting it survive every pass. */
int32_t heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
int32_t heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; }
/* `ctl`'s size, and the index of its first counter (three u64s from [4]). */
enum { kKvCtlInts = 16, kKvCtlMisses = 4, kKvCtlLookups = 6, kKvCtlCalls = 8 };
static_assert(kKvCtlLookups == kKvCtlMisses + 2 && kKvCtlCalls == kKvCtlMisses + 4,
"the three counters are consecutive u64s from ctl[4]");
/* The byte pitch of a rank-2-or-deeper operand's rows, and whether its trailing extents fill
* exactly `bytes` densely. Both the mirror and the pool are one block a row; a padded row would
* copy a block's bytes over its neighbour's. */
int64_t row_bytes(const RadTensor* t, int64_t* dense) {
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 1; --i) acc *= t->shape[i];
*dense = acc;
return t->stride[0] * rad_dtype_bytes(t->dtype, 1);
}
} /* namespace */
int ref_kv_resolve(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor *sel = &a->t[0], *nsel = &a->t[1], *res = &a->t[2], *sblk = &a->t[3];
const RadTensor *sst = &a->t[4], *ctl = &a->t[5], *host = &a->t[6], *pool = &a->t[7];
const int64_t M = p_int(a, "M", 0), blocks = p_int(a, "blocks", 0);
const int64_t slots_decl = p_int(a, "slots", 0), pitch = p_int(a, "sel_pitch", 0);
const int64_t bbytes = p_int(a, "block_bytes", 0);
/* Zero rows is not a call (docs/OPS.md). */
if (M <= 0) return RAD_E_SHAPE;
if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE;
/* The maps and counts are one format: i32, dense. */
const RadTensor* state[] = { sel, nsel, res, sblk, sst, ctl };
for (const RadTensor* t : state)
if (t->dtype != RAD_I32) return RAD_E_DTYPE;
if (sel->rank != 2 || sst->rank != 2) return RAD_E_SHAPE;
if (sel->shape[0] < M || sel->shape[1] < pitch) return RAD_E_SHAPE;
if (sel->stride[1] != 1 || sel->stride[0] != pitch) return RAD_E_STRIDE;
if (numel(nsel) < M || nsel->stride[0] != 1) return RAD_E_SHAPE;
if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE;
/* The operand states the ring; the parameter is the ceiling it may not pass. */
const int64_t slots = numel(sblk);
if (slots < 1 || slots > slots_decl || sblk->stride[0] != 1) return RAD_E_SHAPE;
if (sst->shape[0] < slots || sst->stride[1] != 1 || sst->stride[0] < 2) return RAD_E_STRIDE;
if (numel(ctl) < kKvCtlInts || ctl->stride[0] != 1) return RAD_E_SHAPE;
if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE;
if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE;
/* The mirror's row and the pool's slot are both `block_bytes`. */
int64_t hdense = 0, pdense = 0;
if (row_bytes(host, &hdense) != bbytes || hdense * rad_dtype_bytes(host->dtype, 1) != bbytes)
return RAD_E_STRIDE;
if (row_bytes(pool, &pdense) != bbytes || pdense * rad_dtype_bytes(pool->dtype, 1) != bbytes)
return RAD_E_STRIDE;
int32_t* const R = (int32_t*)res->data;
int32_t* const SB = (int32_t*)sblk->data;
int32_t* const ST = (int32_t*)sst->data;
int32_t* const C = (int32_t*)ctl->data;
const int64_t stp = sst->stride[0];
/* The counters are read and written as u64 in an i32 block. */
if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE;
/* ---- everything that can refuse, before anything is written; the selection is read once and
* kept for step 7 ---- */
std::vector<int64_t> off, ent;
for (int64_t q = 0; q < M; ++q) {
const int64_t n = ld_int(nsel->dtype, nsel->data, q);
if (n < 0 || n > pitch) return RAD_E_SHAPE;
for (int64_t i = 0; i < n; ++i) {
const int64_t b = ld_int(sel->dtype, sel->data, q * pitch + i);
if (b < 0 || b >= blocks) return RAD_E_INVAL;
off.push_back(q * pitch + i);
ent.push_back(b);
}
}
for (int64_t b = 0; b < blocks; ++b)
if (R[b] < -1 || R[b] >= slots) return RAD_E_INVAL; /* -2 is never left by a call */
for (int64_t s = 0; s < slots; ++s)
if (SB[s] < -1 || SB[s] >= blocks) return RAD_E_INVAL;
if (C[1] < 0 || C[1] >= slots) return RAD_E_INVAL;
/* ---- 1. the epoch ---- */
const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u);
/* ---- 2. hits, and one claim per distinct miss (the map is its own set) ---- */
std::vector<int32_t> miss;
for (size_t e = 0; e < ent.size(); ++e) {
const int32_t b = (int32_t)ent[e];
const int32_t s = R[b];
if (s >= 0) {
/* One bump a slot a call (step 2). */
if (ST[s * stp] != epoch) {
ST[s * stp] = epoch;
ST[s * stp + 1] = heat_up(ST[s * stp + 1]);
}
} else if (s == -1) {
R[b] = -2;
miss.push_back(b);
}
}
const int64_t lookups = (int64_t)ent.size();
/* ---- 3. the canonical miss order ---- */
std::sort(miss.begin(), miss.end());
/* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot
* this call uses ---- */
/* Identity first (step 4), leaving the hand alone. Then free slots, before any resident block
* is evicted; a free scan that finds nothing changes nothing. A free count of zero holds for the
* rest of the call (placements fill slots, evictions re-point them), so a full ring goes
* straight to CLOCK. */
int64_t free_left = 0;
for (int64_t s = 0; s < slots; ++s)
if (SB[s] < 0 && ST[s * stp] != epoch) ++free_left;
int64_t hand = C[1];
int64_t placed = 0;
bool overflow = false;
for (size_t k = 0; k < miss.size(); ++k) {
const int32_t b = miss[k];
int64_t victim = -1;
if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b))
victim = b;
if (victim < 0 && free_left > 0) {
int64_t h = hand;
for (int64_t scanned = 0; scanned < slots; ++scanned) {
const int64_t s = h;
h = h + 1 == slots ? 0 : h + 1;
if (ST[s * stp] == epoch) continue; /* used by this call */
if (SB[s] >= 0) continue; /* holds a block */
victim = s;
hand = h;
break;
}
if (victim < 0) free_left = 0;
}
if (victim < 0) {
for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) {
const int64_t s = hand;
hand = hand + 1 == slots ? 0 : hand + 1;
if (ST[s * stp] == epoch) continue; /* used by this call */
if (SB[s] >= 0 && ST[s * stp + 1] > 0) { /* second chance */
ST[s * stp + 1] = heat_down(ST[s * stp + 1]);
continue;
}
victim = s;
break;
}
}
if (victim < 0) { overflow = true; break; }
/* ---- 5. re-point both maps ---- */
if (SB[victim] < 0 && free_left > 0) --free_left; /* a free slot just filled */
if (SB[victim] >= 0) R[SB[victim]] = -1;
SB[victim] = b;
ST[victim * stp] = epoch;
ST[victim * stp + 1] = heat_up(ST[victim * stp + 1]);
R[b] = (int32_t)victim;
++placed;
}
/* An unplaced miss is not resident: undo the claim so a later call may claim it again. */
for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1;
/* ---- 6. the copies, one block each, in miss order ---- */
const uint8_t* const hb = (const uint8_t*)host->data;
uint8_t* const pb = (uint8_t*)pool->data;
for (int64_t k = 0; k < placed; ++k) {
const int32_t b = miss[(size_t)k];
std::memcpy(pb + (int64_t)R[b] * bbytes, hb + (int64_t)b * bbytes, (size_t)bbytes);
}
/* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */
for (size_t e = 0; e < ent.size(); ++e) {
const int32_t s = R[ent[e]];
/* An unplaced miss's entry names slot 0, inside the ring, not its block id (see the header's
* overflow note); ctl[3] says the table is unusable. */
st_int(sel->dtype, sel->data, off[e], s >= 0 ? s : 0);
}
/* ---- the bookkeeping ---- */
/* The union counts distinct blocks: the slots this call stamped (every hit and placement) plus
* the misses it could not place. */
int64_t used = 0;
for (int64_t s = 0; s < slots; ++s)
if (ST[s * stp] == epoch) ++used;
const int64_t uni = used + (int64_t)miss.size() - placed;
C[0] = epoch;
C[1] = (int32_t)hand;
C[2] = (int32_t)placed;
if (overflow) C[3] = 1;
/* The maxima: the union this call selected and the part of it copied in. */
if (uni > C[10]) C[10] = (int32_t)uni;
if (placed > C[11]) C[11] = (int32_t)placed;
if ((int64_t)miss.size() > C[12]) C[12] = (int32_t)miss.size();
uint64_t* const ctr = (uint64_t*)(C + kKvCtlMisses);
ctr[0] += (uint64_t)placed;
ctr[1] += (uint64_t)lookups;
ctr[2] += 1u;
return RAD_OK;
}
+235
View File
@@ -0,0 +1,235 @@
/* ref_m2xfp4.cpp -- gemm_nt_q at dtype m2xfp4: M2XFP's metadata-augmented MXFP4 (arXiv
* 2601.19213), the scheme libquant's `m2xfp4` quantiser writes.
*
* The weight is three TILED planes over 32-column groups: e2m1 codes, an E8M0 exponent per group
* with the adaptive bias already folded in, and a meta byte per group whose two-bit field k_s
* [2s, 2s+2) refines the exponent of subgroup s, columns [8s, 8s+8). The exact element is
* e2m1 code . 2^(e-127) . (1 + k_s/4).
*
* gemm_nt_q's weight operand takes the codes and the meta, stored as the two planes' canonical
* bytes concatenated -- the codes rows, then the meta rows -- the form the core's selection reader
* hands a kernel that decodes the scheme itself (core/format/encoding.cpp). `b_scale` and `b_ref`
* are the exponent plane as it lies; `b_ref` is accepted as at mxfp4a8 and does not change the
* product.
*
* libref keeps one row an op, so ref_gemm_nt_q's row (ref_registry.cpp) takes its hooks from the
* end of this file: each answers dtype m2xfp4 here and hands every other dtype, unchanged, to the
* hook the row had (ref_gemm.cpp, ref_shapes.cpp, ref_planes.h).
*/
#include <algorithm>
#include <cstring>
#include <vector>
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include "ref_planes.h"
using namespace ref;
namespace {
/* The scheme as libquant writes it: codes [1 x 1], scale and meta [1 x 32]. A rotated weight
* (ParoQuant) carries the same three planes in the basis its "givens" transform names, with the
* rotation's tables beside them; the rotation is the activation's, so the planes are read as they
* are. */
bool m2_enc_planes(const RadEncoding* enc) {
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 &&
mt->block[0] == 1 && mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") && rad_enc_plane(enc, "t.angle") &&
rad_enc_plane(enc, "t.scale");
}
/* Each product is one f32 multiply and each output one f32 accumulation in k order: the exact
* decode's own arithmetic, since the multipliers take the codes off the integer grid an mxfp4
* group sub-sum would use.
*
* Parts (`pb1`, `pb2`), a rotated (ParoQuant) fused projection's pieces, as gemm_ntq_impl's mxfp4
* arm reads them (ref_gemm.cpp): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each meet their own
* copy of the activation, side by side in a row of `a` ([M, parts * K]) and of its scale
* ([M, parts * K / 128]). 0 omits a bound. */
int m2_gemm(const RadArgs* a) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor *as_ = t_in(a, 1), *bs_ = t_in(a, 3);
if (!A->data || !B->data || !Y->data) return RAD_E_INVAL;
if (t_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || B->rank != 1) return RAD_E_DTYPE;
if (!as_ || !bs_ || bs_->dtype != RAD_E8M0 || bs_->rank < 2) return RAD_E_DTYPE;
const int64_t K = p_int(a, "K", 0), N = p_int(a, "N", 0);
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0);
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
if (parts > 1 && (e1 % 16 || e2 % 16 || A->rank < 2 || A->shape[A->rank - 1] != parts * K))
return RAD_E_SHAPE;
const int64_t kb = K / 32, akb = (K + 127) / 128;
if (numel(A) < M * parts * K || numel(B) != N * (K / 2 + kb) || numel(bs_) < N * kb ||
numel(as_) < M * parts * akb)
return RAD_E_SHAPE;
const int64_t ars = row_stride(A, parts * K), acs = laststride(A);
const int64_t srs = row_stride(as_, parts * akb), scs = laststride(as_);
const int64_t brs = row_stride(bs_, kb);
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const uint8_t* meta0 = (const uint8_t*)B->data + N * (K / 2);
REF_PAR_FOR(N)
for (int64_t n = 0; n < N; ++n) {
const uint8_t* codes = (const uint8_t*)B->data + n * (K / 2);
const uint8_t* meta = meta0 + n * kb;
const uint8_t* expe = (const uint8_t*)bs_->data + n * brs;
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
const int64_t ak0 = part * K, sk0 = part * akb; /* this part's copy of `a` */
/* The weight row decoded once, so the meta and exponent reads are not repeated per
* activation row. */
std::vector<float> w((size_t)K);
for (int64_t k = 0; k < K; ++k) {
const uint8_t c = (uint8_t)((codes[k >> 1] >> (4 * (k & 1))) & 0xF);
const float cv = mxfp4_elem_to_f32(c);
const float ev = e8m0_to_f32(expe[k >> 5]);
const float km = 1.0f + 0.25f * (float)((meta[k >> 5] >> (2 * ((k & 31) >> 3))) & 3);
w[(size_t)k] = cv * ev * km;
}
for (int64_t m = 0; m < M; ++m) {
const int64_t ab = m * ars;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += ldt(A, ab + (ak0 + k) * acs) * ldt(as_, m * srs + (sk0 + (k >> 7)) * scs) *
w[(size_t)k];
stt(Y, m * ys_r + n * ys_c, acc);
}
}
return RAD_OK;
}
/* mxfp4a8's operands (ref_shapes.cpp), the weight being the codes and meta concatenated. */
int m2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (rad_param_geti(p, n_p, "group", 0) != 32 || N <= 0 || K <= 0 || K % 32)
return RAD_E_UNSUPPORTED;
std::vector<RadParam> q(p, p + n_p);
for (RadParam& r : q)
if (r.key && std::strcmp(r.key, "dtype") == 0) r.sval = "mxfp4a8";
const int rc = ref_gemm_nt_q_shape(q.data(), n_p, operand, out);
if (rc != RAD_OK || operand != 2) return rc;
out->dtype = (uint32_t)RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->shape[1] = 0;
return RAD_OK;
}
/* The weight operand is codes and meta, concatenated; the scale and reference operands are the
* exponent plane, stored as it is. Any other encoding is refused, a transform other than
* "givens" included. */
int m2_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const long long group = rad_param_geti(p, n_p, "group", 0);
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32) return RAD_E_DTYPE;
if (operand == 2) {
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
if (planes[0].shape[0] != N || planes[0].shape[1] != K ||
planes[1].shape[0] != N || planes[1].shape[1] != K / 32)
return RAD_E_SHAPE;
out->tag = "m2.codes.meta";
out->dtype = RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->align = 0;
out->bytes = out->shape[0];
return RAD_OK;
}
if (operand == 3 || operand == 6) {
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
}
return RAD_E_UNSUPPORTED;
}
int m2_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
RadLayout lay{};
const int st = m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
for (int i = 0; i < n; ++i) {
const int64_t b =
planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
std::memcpy(d, planes[i].data, (size_t)b);
d += b;
}
return RAD_OK;
}
int m2_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes, const RadTensor* planes, int n) {
RadLayout lay{};
const int st = m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
for (int i = 0; i < n; ++i) {
const int64_t b =
planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
std::memcpy(planes[i].data, s, (size_t)b);
s += b;
}
return RAD_OK;
}
} /* namespace */
/* ---- ref_gemm_nt_q's row hooks: m2xfp4 here, every other dtype the row's own. */
static bool is_m2xfp4(const RadParam* p, int n_p) {
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
return dt && std::strcmp(dt, "m2xfp4") == 0;
}
int ref_gemm_nt_q_m2(const RadArgs* a, RadStream s) {
return is_m2xfp4(a->p, a->n_p) ? m2_gemm(a) : ref_gemm_nt_q(a, s);
}
int ref_gemm_nt_q_m2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return is_m2xfp4(p, n_p) ? m2_shape(p, n_p, operand, out)
: ref_gemm_nt_q_shape(p, n_p, operand, out);
}
int ref_layout_gemm_q_m2(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return is_m2xfp4(p, n_p) ? m2_layout(p, n_p, operand, enc, sel, planes, n, out)
: ref_layout_gemm_q(p, n_p, operand, enc, sel, planes, n, out);
}
int ref_relayout_gemm_q_m2(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
return is_m2xfp4(p, n_p)
? m2_relayout(p, n_p, operand, enc, sel, planes, n, dst, dst_bytes)
: ref_relayout_planes<ref_layout_gemm_q>(p, n_p, operand, enc, sel, planes, n, dst,
dst_bytes);
}
int ref_unrelayout_gemm_q_m2(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
return is_m2xfp4(p, n_p)
? m2_unrelayout(p, n_p, operand, enc, sel, src, src_bytes, planes, n)
: ref_unrelayout_planes<ref_layout_gemm_q>(p, n_p, operand, enc, sel, src,
src_bytes, planes, n);
}
+42
View File
@@ -86,8 +86,11 @@ int ref_mla_attn(const RadArgs*, RadStream);
int ref_gelu_mul (const RadArgs*, RadStream);
int ref_act_mul (const RadArgs*, RadStream);
int ref_mul_weight (const RadArgs*, RadStream);
int ref_seg_mean_bf16_sum (const RadArgs*, RadStream);
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_relu (const RadArgs*, RadStream);
int ref_clamp (const RadArgs*, RadStream);
int ref_conv2d (const RadArgs*, RadStream);
@@ -125,6 +128,7 @@ 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_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);
@@ -145,6 +149,7 @@ int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_paged_tree (const RadArgs*, RadStream);
int ref_attn_dense (const RadArgs*, RadStream);
int ref_attn_cross (const RadArgs*, RadStream);
int ref_table_add (const RadArgs*, RadStream);
@@ -153,7 +158,14 @@ int ref_chan_stats (const RadArgs*, RadStream);
/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */
int ref_sam_attn (const RadArgs*, RadStream);
int ref_kv_store (const RadArgs*, RadStream);
/* the store of a streamed group: the host mirror always, the ring slot when the block is resident */
int ref_kv_store_streamed (const RadArgs*, RadStream);
int ref_rope (const RadArgs*, RadStream);
int ref_position_scale (const RadArgs*, RadStream);
int ref_embed_attn (const RadArgs*, RadStream);
int ref_ministral_rope (const RadArgs*, RadStream);
int ref_pixtral_rope (const RadArgs*, RadStream);
int ref_pixtral_merge (const RadArgs*, RadStream);
int ref_rope_table (const RadArgs*, RadStream);
int ref_qk_norm_rope (const RadArgs*, RadStream);
/* image generation (ref_gen.cpp) */
@@ -171,6 +183,7 @@ int ref_kd_step(const RadArgs*, RadStream);
int ref_rms_mod(const RadArgs*, RadStream);
int ref_rms_mod_quant_fp8(const RadArgs*, RadStream);
int ref_flow_x0_step(const RadArgs*, RadStream);
int ref_flow_res_multistep(const RadArgs*, RadStream);
/* ref_video.cpp */
int ref_patch_unfold(const RadArgs*, RadStream);
int ref_vtile_gather(const RadArgs*, RadStream);
@@ -182,6 +195,10 @@ int ref_group_norm(const RadArgs*, RadStream);
int ref_tconv_dw(const RadArgs*, RadStream);
int ref_resize_bilinear(const RadArgs*, RadStream);
int ref_flow_renoise(const RadArgs*, RadStream);
int ref_cond_aug(const RadArgs*, RadStream);
int ref_vtile_plan(const RadArgs*, RadStream);
int ref_vtile_crop(const RadArgs*, RadStream);
int ref_vtile_join(const RadArgs*, RadStream);
/* ref_ltx.cpp */
int ref_rope_split(const RadArgs*, RadStream);
int ref_head_gate(const RadArgs*, RadStream);
@@ -209,8 +226,10 @@ int ref_snake(const RadArgs*, RadStream);
int ref_snake_aa(const RadArgs*, RadStream);
int ref_cfg_topk_sample(const RadArgs*, RadStream);
int ref_rvq_embed(const RadArgs*, RadStream);
int ref_vq_encode(const RadArgs*, RadStream);
int ref_frame_mix_store(const RadArgs*, RadStream);
int ref_end_status(const RadArgs*, RadStream);
int ref_ras_pick(const RadArgs*, RadStream);
int ref_frame_store(const RadArgs*, RadStream);
int ref_resample_nearest(const RadArgs*, RadStream);
int ref_fourier_embed(const RadArgs*, RadStream);
@@ -222,6 +241,7 @@ int ref_interleave2(const RadArgs*, RadStream);
int ref_iota(const RadArgs*, RadStream);
int ref_cu_repeat(const RadArgs*, RadStream);
int ref_int_affine(const RadArgs*, RadStream);
int ref_sub_i32(const RadArgs*, RadStream);
int ref_chan_affine(const RadArgs*, RadStream);
int ref_conv2d_nhwc(const RadArgs*, RadStream);
int ref_im2col_nhwc(const RadArgs*, RadStream);
@@ -239,6 +259,8 @@ int ref_qsa_score (const RadArgs*, RadStream);
int ref_qsa_select (const RadArgs*, RadStream);
int ref_qsa_tail_store (const RadArgs*, RadStream);
int ref_qsa_work (const RadArgs*, RadStream);
/* the residency map between a streamed group's block ids and its ring slots (ref_kvstream.cpp) */
int ref_kv_resolve (const RadArgs*, RadStream);
int ref_dflash_conv (const RadArgs*, RadStream);
/* ---- mixture of experts */
@@ -342,7 +364,10 @@ REF_SHAPE_FN(ref_gelu_mul);
REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
REF_SHAPE_FN(ref_seg_mean);
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_relu);
REF_SHAPE_FN(ref_clamp);
REF_SHAPE_FN(ref_conv2d);
@@ -379,6 +404,7 @@ 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_tree);
REF_SHAPE_FN(ref_gram_accum);
REF_SHAPE_FN(ref_rmsnorm_had_quant_i8);
REF_SHAPE_FN(ref_gated_had_quant_i8);
@@ -396,6 +422,7 @@ 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_tree);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_attn_cross);
REF_SHAPE_FN(ref_table_add);
@@ -403,7 +430,13 @@ REF_SHAPE_FN(ref_mix_rows);
REF_SHAPE_FN(ref_chan_stats);
REF_SHAPE_FN(ref_sam_attn);
REF_SHAPE_FN(ref_kv_store);
REF_SHAPE_FN(ref_kv_store_streamed);
REF_SHAPE_FN(ref_rope);
REF_SHAPE_FN(ref_position_scale);
REF_SHAPE_FN(ref_embed_attn);
REF_SHAPE_FN(ref_ministral_rope);
REF_SHAPE_FN(ref_pixtral_rope);
REF_SHAPE_FN(ref_pixtral_merge);
REF_SHAPE_FN(ref_rope_table);
REF_SHAPE_FN(ref_qk_norm_rope);
REF_SHAPE_FN(ref_ln_mod);
@@ -420,6 +453,7 @@ REF_SHAPE_FN(ref_kd_step);
REF_SHAPE_FN(ref_rms_mod);
REF_SHAPE_FN(ref_rms_mod_quant_fp8);
REF_SHAPE_FN(ref_flow_x0_step);
REF_SHAPE_FN(ref_flow_res_multistep);
REF_SHAPE_FN(ref_patch_unfold);
REF_SHAPE_FN(ref_vtile_gather);
REF_SHAPE_FN(ref_vtile_stitch);
@@ -430,6 +464,10 @@ REF_SHAPE_FN(ref_group_norm);
REF_SHAPE_FN(ref_tconv_dw);
REF_SHAPE_FN(ref_resize_bilinear);
REF_SHAPE_FN(ref_flow_renoise);
REF_SHAPE_FN(ref_cond_aug);
REF_SHAPE_FN(ref_vtile_plan);
REF_SHAPE_FN(ref_vtile_crop);
REF_SHAPE_FN(ref_vtile_join);
REF_SHAPE_FN(ref_rope_split);
REF_SHAPE_FN(ref_head_gate);
REF_SHAPE_FN(ref_ltx_guide);
@@ -452,8 +490,10 @@ REF_SHAPE_FN(ref_snake);
REF_SHAPE_FN(ref_snake_aa);
REF_SHAPE_FN(ref_cfg_topk_sample);
REF_SHAPE_FN(ref_rvq_embed);
REF_SHAPE_FN(ref_vq_encode);
REF_SHAPE_FN(ref_frame_mix_store);
REF_SHAPE_FN(ref_end_status);
REF_SHAPE_FN(ref_ras_pick);
REF_SHAPE_FN(ref_frame_store);
REF_SHAPE_FN(ref_resample_nearest);
REF_SHAPE_FN(ref_fourier_embed);
@@ -465,6 +505,7 @@ REF_SHAPE_FN(ref_interleave2);
REF_SHAPE_FN(ref_iota);
REF_SHAPE_FN(ref_cu_repeat);
REF_SHAPE_FN(ref_int_affine);
REF_SHAPE_FN(ref_sub_i32);
REF_SHAPE_FN(ref_chan_affine);
REF_SHAPE_FN(ref_conv2d_nhwc);
REF_SHAPE_FN(ref_im2col_nhwc);
@@ -481,6 +522,7 @@ REF_SHAPE_FN(ref_qsa_score);
REF_SHAPE_FN(ref_qsa_select);
REF_SHAPE_FN(ref_qsa_tail_store);
REF_SHAPE_FN(ref_qsa_work);
REF_SHAPE_FN(ref_kv_resolve);
REF_SHAPE_FN(ref_dflash_conv);
REF_SHAPE_FN(ref_router_topk);
+234
View File
@@ -0,0 +1,234 @@
/* Nemotron's text/vision rotary, patch merger and materialized BF16 attention.
* Separate ops preserve existing rotary, attention and merger contracts. */
#include "ref_common.h"
#include "ref_ops.h"
#include "rad_yarn.h"
using namespace ref;
int ref_pixtral_rope(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *rc = &a->t[1];
// The issue's row views can be smaller than the resolved M capacity band.
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
const float theta = p_f32(a, "theta", 0);
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D % 4 || H <= 0 || !(theta > 0) ||
!std::isfinite(theta) || x->rank != 2 || x->shape[0] < M || x->shape[1] != 3 * H * D ||
rc->rank != 2 || rc->shape[0] != 2 || rc->shape[1] != M)
return RAD_E_SHAPE;
if (rc->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
for (int64_t r = 0; r < 2; ++r)
for (int64_t p = 0; p < M; ++p)
if (ld_int(rc->dtype, rc->data, r * rc->stride[0] + p * rc->stride[1]) < 0)
return RAD_E_INVAL;
REF_PAR_FOR(M * H * D)
for (int64_t p = 0; p < M; ++p) {
for (int64_t i = 0; i < D / 2; ++i) {
const int64_t axis = i / (D / 4), j = i % (D / 4);
const float pos =
(float)ld_int(rc->dtype, rc->data, axis * rc->stride[0] + p * rc->stride[1]);
const float inv = 1.0f / ref_pow(theta, (float)(4 * j + 2 * axis) / D);
const float angle = pos * inv;
const float c = round_dt(x->dtype, ref_cos(angle)),
s = round_dt(x->dtype, ref_sin(angle));
for (int64_t h = 0; h < 2 * H; ++h) {
const int64_t u = rowoff(x, p, 3 * H * D) + (h * D + i) * laststride(x);
const int64_t v = u + (D / 2) * laststride(x);
const float a0 = ldt(x, u), b0 = ldt(x, v);
/* Transformers narrows cos/sin and each product before adding BF16 tensors. */
stt(x, u, round_dt(x->dtype, a0 * c) - round_dt(x->dtype, b0 * s));
stt(x, v, round_dt(x->dtype, b0 * c) + round_dt(x->dtype, a0 * s));
}
}
}
return RAD_OK;
}
int ref_pixtral_merge(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *rc = &a->t[1], *y = &a->t[2];
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
const int64_t N = p_int(a, "n", 0), K = p_int(a, "merge", 0);
if (M <= 0 || M > p_int(a, "M", 0) || N <= 0 || K <= 0 || K > M || M / K < K || M % (K * K) ||
x->rank != 2 || x->shape[0] != M || x->shape[1] != N || rc->rank != 2 ||
rc->shape[0] != 4 || rc->shape[1] != M || y->rank != 2 || y->shape[0] != M / (K * K) ||
y->shape[1] != N * K * K)
return RAD_E_SHAPE;
if (rc->dtype != RAD_I32 || x->dtype != y->dtype ||
(x->dtype != RAD_BF16 && x->dtype != RAD_F32))
return RAD_E_DTYPE;
const auto coord = [&](int axis, int64_t p) {
return ld_int(rc->dtype, rc->data, axis * rc->stride[0] + p * rc->stride[1]);
};
/* Verify full raster grids before any write, including variable image widths. The grid at
* each image's first patch defines its boundary; no image is merged with the next one. */
for (int64_t p = 0; p < M;) {
const int64_t h = coord(2, p), w = coord(3, p);
if (h <= 0 || w <= 0 || h % K || w % K || h > (M - p) / w) return RAD_E_INVAL;
for (int64_t j = 0; j < h * w; ++j)
if (coord(0, p + j) != j / w || coord(1, p + j) != j % w || coord(2, p + j) != h ||
coord(3, p + j) != w)
return RAD_E_INVAL;
p += h * w;
}
for (int64_t p = 0; p < M;) {
const int64_t h = coord(2, p), w = coord(3, p);
for (int64_t r = 0; r < h / K; ++r)
for (int64_t c = 0; c < w / K; ++c) {
const int64_t dst = p / (K * K) + r * (w / K) + c;
for (int64_t n = 0; n < N; ++n)
for (int64_t dy = 0; dy < K; ++dy)
for (int64_t dx = 0; dx < K; ++dx) {
const int64_t src = p + (r * K + dy) * w + c * K + dx;
const int64_t col = (n * K + dy) * K + dx;
stt(y, rowoff(y, dst, N * K * K) + col * laststride(y),
ldt(x, rowoff(x, src, N) + n * laststride(x)));
}
}
p += h * w;
}
return RAD_OK;
}
int ref_ministral_rope(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pos = &a->t[1];
const int64_t M = x->rank == 2 ? x->shape[0] : 0;
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0),
K = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 0);
const RadYarn yarn = rad_yarn_args(a);
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || D % 2 || H <= 0 || H > 1024 ||
K <= 0 || K > H || H % K || x->shape[1] != (H + 2 * K) * D || pos->rank != 1 ||
numel(pos) != M || !(theta > 0) || !std::isfinite(theta) || !rad_yarn_valid(yarn))
return RAD_E_SHAPE;
if (pos->dtype != RAD_I32 || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) return RAD_E_DTYPE;
for (int64_t p = 0; p < M; ++p)
if (ld_int(pos->dtype, pos->data, offlin(pos, p)) < 0) return RAD_E_INVAL;
float freq[1024];
for (int64_t i = 0; i < D / 2; ++i)
freq[i] = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)D), (int)i);
REF_PAR_FOR(M * (H + K) * D)
for (int64_t p = 0; p < M; ++p) {
const float position = (float)(ld_int(pos->dtype, pos->data, offlin(pos, p)));
for (int64_t i = 0; i < D / 2; ++i) {
const float angle = position * freq[i];
const float c = round_dt(x->dtype, std::cos(angle) * yarn.magnitude);
const float s = round_dt(x->dtype, std::sin(angle) * yarn.magnitude);
for (int64_t h = 0; h < H + K; ++h) {
const int64_t u = rowoff(x, p, (H + 2 * K) * D) + (h * D + i) * laststride(x);
const int64_t v = u + (D / 2) * laststride(x);
const float a0 = ldt(x, u), b0 = ldt(x, v);
stt(x, u, round_dt(x->dtype, a0 * c) - round_dt(x->dtype, b0 * s));
stt(x, v, round_dt(x->dtype, b0 * c) + round_dt(x->dtype, a0 * s));
}
}
}
return RAD_OK;
}
/* The eager BF16 attention expression materializes QK, scaled logits and probabilities.
* Keep it separate from attn_dense's existing fused arithmetic. Only whole, noncausal segments
* are served. Stack storage is bounded by the model's 32768-token limit. */
int ref_embed_attn(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *out = &a->t[4];
const int64_t M = q->rank == 2 ? q->shape[0] : 0;
const int64_t D = p_int(a, "head_dim", 0), G = p_int(a, "gqa", 1);
if (M <= 0 || M > p_int(a, "M", 0) || D <= 0 || D > 2048 || G <= 0 || q->shape[1] <= 0 ||
q->shape[1] % D || k->rank != 2 || v->rank != 2 || out->rank != 2 || cu->rank != 1 ||
numel(cu) < 2 || k->shape[0] != M || v->shape[0] != M || out->shape[0] != M)
return RAD_E_SHAPE;
const int64_t H = q->shape[1] / D, S = numel(cu) - 1;
if (H % G || k->shape[1] != H / G * D || v->shape[1] != H / G * D || out->shape[1] != H * D)
return RAD_E_SHAPE;
if (p_int(a, "causal", 0) != 0) return RAD_E_UNSUPPORTED;
if ((q->dtype != RAD_BF16 && q->dtype != RAD_F32) || k->dtype != q->dtype ||
v->dtype != q->dtype || out->dtype != q->dtype || cu->dtype != RAD_I32)
return RAD_E_DTYPE;
auto boundary = [&](int64_t s) { return ld_int(cu->dtype, cu->data, offlin(cu, s)); };
if (boundary(0) != 0 || boundary(S) != M) return RAD_E_INVAL;
for (int64_t s = 0; s < S; ++s)
if (boundary(s) >= boundary(s + 1) || boundary(s + 1) - boundary(s) > 32768)
return RAD_E_INVAL;
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)D));
if (!std::isfinite(scale) || !(scale > 0)) return RAD_E_INVAL;
REF_PAR_FOR(M * H * D)
for (int64_t sh = 0; sh < S * H; ++sh) {
const int64_t s = sh / H, h = sh % H, kh = h / G;
const int64_t begin = boundary(s), end = boundary(s + 1);
float scores[32768], accum[2048];
for (int64_t i = begin; i < end; ++i) {
const int64_t qb = rowoff(q, i, H * D) + h * D * laststride(q);
float maximum = -INFINITY;
for (int64_t j = begin; j < end; ++j) {
const int64_t kb = rowoff(k, j, H / G * D) + kh * D * laststride(k);
float dot = 0;
for (int64_t d = 0; d < D; ++d)
dot += ldt(q, qb + d * laststride(q)) * ldt(k, kb + d * laststride(k));
const float score = round_dt(q->dtype, round_dt(q->dtype, dot) * scale);
scores[j - begin] = score;
maximum = std::max(maximum, score);
}
float sum = 0;
for (int64_t j = begin; j < end; ++j) {
scores[j - begin] = std::exp(scores[j - begin] - maximum);
sum += scores[j - begin];
}
std::fill_n(accum, D, 0.0f);
for (int64_t j = begin; j < end; ++j) {
const float probability = round_dt(q->dtype, scores[j - begin] / sum);
const int64_t vb = rowoff(v, j, H / G * D) + kh * D * laststride(v);
for (int64_t d = 0; d < D; ++d)
accum[d] += probability * ldt(v, vb + d * laststride(v));
}
const int64_t ob = rowoff(out, i, H * D) + h * D * laststride(out);
for (int64_t d = 0; d < D; ++d)
stt(out, ob + d * laststride(out), accum[d]);
}
}
return RAD_OK;
}
/* Native masked mean: the sum is stored in BF16 before dividing, then stored in BF16 again.
* Keep this separate from seg_mean's one-rounding sentence-embedding contract. */
int ref_seg_mean_bf16_sum(const RadArgs* a, RadStream) {
if (!have(a, 3))
return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *cu = &a->t[1], *y = &a->t[2];
if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16 || cu->dtype != RAD_I32)
return RAD_E_DTYPE;
if (!x->data || !cu->data || !y->data)
return RAD_E_INVAL;
const int64_t M = x->rank == 2 ? x->shape[0] : 0, N = p_int(a, "n", 0);
const int64_t S = cu->rank == 1 && cu->shape[0] > 1 ? cu->shape[0] - 1 : 0;
const auto matrix = [](const RadTensor& t, int64_t rows, int64_t cols) {
constexpr int64_t limit = INT64_MAX / 2;
if (t.rank != 2 || t.shape[0] != rows || t.shape[1] != cols || t.stride[0] <= 0 ||
t.stride[1] <= 0 || cols - 1 > limit / t.stride[1])
return false;
const int64_t columns = (cols - 1) * t.stride[1];
return t.stride[0] > columns && rows - 1 <= (limit - columns) / t.stride[0];
};
if (M <= 0 || M > INT32_MAX || M > p_int(a, "M", 0) || N <= 0 || S <= 0 || S > M ||
cu->stride[0] <= 0 || cu->stride[0] > (INT64_MAX / 4) / S || !matrix(*x, M, N) ||
!matrix(*y, S, N))
return RAD_E_SHAPE;
const auto at = [&](int64_t s) { return ld_int(cu->dtype, cu->data, s * cu->stride[0]); };
if (at(0) != 0 || at(S) != M)
return RAD_E_INVAL;
for (int64_t s = 0; s < S; ++s)
if (at(s) < 0 || at(s + 1) <= at(s) || at(s + 1) > M)
return RAD_E_INVAL;
for (int64_t s = 0; s < S; ++s)
for (int64_t c = 0; c < N; ++c) {
float sum = 0;
for (int64_t r = at(s); r < at(s + 1); ++r)
sum += ldt(x, r * x->stride[0] + c * x->stride[1]);
stt(y, s * y->stride[0] + c * y->stride[1],
round_dt(RAD_BF16, sum) / (float)(at(s + 1) - at(s)));
}
return RAD_OK;
}
+2 -101
View File
@@ -182,70 +182,15 @@ static inline int ref_layout_mtp(const RadParam*, int, int operand, const RadEnc
return layout_scaled(operand, 4, 5, enc, sel, planes, n, out);
}
/* M2XFP4, the `m2xfp4` quantiser's own scheme (libquant): three TILED planes over 32-column
* groups, and gemm_nt_q's weight operand takes the codes and the meta. Their stored form is the
* two planes' canonical bytes concatenated -- the codes' rows, then the meta's -- the form the
* core's selection reader hands a kernel that decodes the scheme itself beside the scale stream
* another operand carries (core/format/encoding.cpp), and the one both libraries' m2 arms read.
* libavx/avx_planes.h states the same rules. */
static inline bool m2_enc_planes(const RadEncoding* enc) {
if (!rad_enc_is(enc, "m2xfp4")) return false;
/* A rotated weight (ParoQuant) carries the same three planes in the basis its "givens"
* transform names, with the rotation's tables beside them; the rotation is the activation's,
* so the planes are read as they are. */
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") &&
rad_enc_plane(enc, "t.angle") && rad_enc_plane(enc, "t.scale");
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the zero-point grid `dtype` names,
* one each per (row, `group` of K), over codes of that grid's width. The codes (operand 2) are one
* plane and stored as they are. A "givens" transform is the activation's (givens_rotate,
* givens_dense_quant), so the planes are read the same way under it. At `m2xfp4` the weight
* operand takes codes and meta concatenated (above); the scale and reference operands are single
* planes, stored as they are. */
* givens_dense_quant), so the planes are read the same way under it. */
static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
if (dt && std::strcmp(dt, "m2xfp4") == 0) {
const long long group = rad_param_geti(p, n_p, "group", 0);
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32)
return RAD_E_DTYPE;
if (operand == 2) {
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
if (planes[0].shape[0] != N || planes[0].shape[1] != K ||
planes[1].shape[0] != N || planes[1].shape[1] != K / 32)
return RAD_E_SHAPE;
out->tag = "m2.codes.meta";
out->dtype = RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->align = 0;
out->bytes = out->shape[0];
return RAD_OK;
}
if (operand == 3 || operand == 6) {
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
}
return RAD_E_UNSUPPORTED;
}
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(dt);
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
@@ -263,50 +208,6 @@ static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
return rad_planes_layout(enc, sel, planes, n, out);
}
/* gemm_nt_q's own relayout: the m2 arm's concatenated form beside the zero-point grids' joined
* one, each as its layout hook laid it out. */
template <RadLayoutFn L>
static int ref_relayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(d, planes[i].data, (size_t)b);
d += b;
}
return RAD_OK;
}
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
template <RadLayoutFn L>
static int ref_unrelayout_gemm_q(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (lay.tag && std::strcmp(lay.tag, "m2.codes.meta") == 0) {
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
for (int i = 0; i < n; ++i) {
const int64_t rb = rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
const int64_t b = planes[i].shape[0] * rb;
std::memcpy(planes[i].data, s, (size_t)b);
s += b;
}
return RAD_OK;
}
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
/* RadRelayoutFn and RadUnrelayoutFn for any of the layout hooks above: the hook decides whether
* the planes are joined, and the copies are rad_planes.h's. */
template <RadLayoutFn L>
+118 -1
View File
@@ -539,11 +539,14 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
ldt(x, xb + k * xst) * (s ? ldt(s, sb + (k / g) * sst) : 1.0f);
}
/* `upper`: only k2 >= k1. libr4d adds whole 64-wide tiles, so it also writes some entries just
* below the diagonal; neither form's entries there are part of the contract. */
const bool upper = p_int(a, "upper", 0) != 0;
const int64_t hst = laststride(h);
REF_PAR_FOR(n * n * rows)
for (int64_t k1 = 0; k1 < n; ++k1) {
const int64_t hb = rowoff(h, k1, n);
for (int64_t k2 = 0; k2 < n; ++k2) {
for (int64_t k2 = upper ? k1 : 0; k2 < n; ++k2) {
double acc = 0.0;
for (int64_t r = 0; r < rows; ++r)
acc += (double)xs[(size_t)r * (size_t)n + (size_t)k1] *
@@ -820,3 +823,117 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
}
return RAD_OK;
}
/* ------------------------------------------------------------- dflash_tree */
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents`
*
* dflash_select's lattice and edge scores, grown into a tree of `nodes` nodes instead of walked
* into one path (rad_drafter_tree). Node 0 is the anchor, at lattice position -1 with log
* probability 0. A node at position l with token t has a child for every valid candidate c at
* position l + 1, scored as dflash_select scores it after t, with log probability its parent's
* plus log_softmax(score / temp)[c] over the valid candidates there. Best-first: each round
* selects the not-yet-selected child of any selected node with the largest log probability (ties
* to the one pushed first: lower parent, then lower c), until `nodes` are selected. Selected node
* j (1-based, in selection order, so a parent always precedes its child) is written as
* tokens[j-1] and parents[j-1], the parent's node index (0 the anchor). A frontier that runs dry
* (every candidate invalid) pads with token 0 under the last node, which the verify rejects.
*
* In f32: score as dflash_select; x = score / temp; m = max x; lse = m + log(sum exp(x - m)) over
* the valid candidates, summed in c order; child = parent + (x - lse). */
int ref_dflash_tree(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
const RadTensor *pred = &a->t[4], *succ = &a->t[5], *out = &a->t[6], *par = &a->t[7];
const RadTensor* hp = t_in(a, 2);
if (!cand->data || !un->data || !anc->data || !pred->data || !succ->data || !out->data ||
!par->data)
return RAD_E_INVAL;
const int64_t steps = p_int(a, "steps", 0);
const int64_t K = p_int(a, "top_k", 0);
const int64_t M = steps > 0 && K > 0
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
const int64_t nv = p_int(a, "n_vocab", pred->rank >= 2 ? pred->shape[pred->rank - 2] : 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
const int64_t N = p_int(a, "nodes", steps);
const float temp = p_f32(a, "temp", 1.0f);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0 ||
!(temp > 0.0f))
return RAD_E_SHAPE;
if (numel(un) < M * steps * K) return RAD_E_SHAPE;
if (numel(anc) < (M - 1) * astr + 1 || numel(out) < M * N || numel(par) < M * N)
return RAD_E_SHAPE;
if (numel(pred) < nv * R || numel(succ) < nv * R) return RAD_E_SHAPE;
if (hp && numel(hp) < M * steps * R) return RAD_E_SHAPE;
const int64_t cs = laststride(cand), us = laststride(un), os = laststride(out);
const int64_t pps = laststride(par);
const int64_t ps = laststride(pred), sxs = laststride(succ);
const int64_t hs = hp ? laststride(hp) : 1;
REF_PAR_FOR(M * N * K * R)
for (int64_t m = 0; m < M; ++m) {
struct Node { int64_t l, tok, parent; float lp; };
struct Kid { float lp; int64_t parent, l, tok; bool taken; };
std::vector<Node> sel; /* selected, node 0 the anchor */
std::vector<Kid> front; /* every child pushed so far, in push order */
std::vector<float> ax((size_t)R), x((size_t)K);
sel.push_back({ -1, ld_int(anc->dtype, anc->data, offlin(anc, m * astr)), -1, 0.0f });
auto expand = [&](int64_t n) {
const Node nd = sel[(size_t)n];
const int64_t l = nd.l + 1;
if (l >= steps) return;
const int64_t r = m * steps + l;
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
const int64_t hb = hp ? rowoff(hp, r, R) : 0;
const bool ok = nd.tok >= 0 && nd.tok < nv;
for (int64_t i = 0; i < R; ++i)
ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, nd.tok, R) + i * ps) : 0.0f) *
(hp ? ldt(hp, hb + i * hs) : 1.0f);
float mx = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_int(cand->dtype, cand->data, cb + c * cs);
float sc = ldt(un, ub + c * us);
const bool valid = tok >= 0 && tok < nv;
if (valid) {
const int64_t sb = rowoff(succ, tok, R);
for (int64_t i = 0; i < R; ++i) sc += ax[(size_t)i] * ldt(succ, sb + i * sxs);
}
x[(size_t)c] = valid ? sc / temp : -INFINITY;
if (x[(size_t)c] > mx) mx = x[(size_t)c];
}
if (mx == -INFINITY) return;
float sum = 0.0f;
for (int64_t c = 0; c < K; ++c)
if (x[(size_t)c] > -INFINITY) sum += std::exp(x[(size_t)c] - mx);
const float lse = mx + std::log(sum);
for (int64_t c = 0; c < K; ++c) {
if (!(x[(size_t)c] > -INFINITY)) continue;
front.push_back({ nd.lp + (x[(size_t)c] - lse), n, l,
ld_int(cand->dtype, cand->data, cb + c * cs), false });
}
};
expand(0);
for (int64_t j = 1; j <= N; ++j) {
int64_t best = -1;
for (size_t f = 0; f < front.size(); ++f)
if (!front[f].taken && (best < 0 || front[f].lp > front[(size_t)best].lp))
best = (int64_t)f;
if (best < 0) {
sel.push_back({ steps, 0, (int64_t)sel.size() - 1, -INFINITY });
} else {
Kid& k = front[(size_t)best];
k.taken = true;
sel.push_back({ k.l, k.tok, k.parent, k.lp });
expand((int64_t)sel.size() - 1);
}
const Node& nd = sel.back();
st_int(out->dtype, out->data, rowoff(out, m, N) + (j - 1) * os, nd.tok);
st_int(par->dtype, par->data, rowoff(par, m, N) + (j - 1) * pps, nd.parent);
}
}
return RAD_OK;
}
+269 -23
View File
@@ -26,6 +26,7 @@
#include "ref_common.h"
#include "ref_ops.h"
#include "ref_planes.h"
#include "rad_abi_layout.h"
/* ================================================================== parameter specs */
#define P_INT(k) { k, RAD_P_INT, RAD_REQUIRED }
@@ -194,6 +195,8 @@ static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_
/* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */
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") };
/* `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") };
@@ -243,6 +246,8 @@ static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_S
/* ---- quantisation and rotation ------------------------------------------------------------ */
static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype") };
/* gram_accum's: `upper` 1 accumulates only k2 >= k1, the half a reader of a symmetric H needs. */
static const RadParamSpec pGram[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INTO("upper") };
/* `asum`, quant_act_i8's optional third output: group-major per-row code sums an asymmetric
* weight grid subtracts to remove the stored zero point. */
static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") };
@@ -287,6 +292,13 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT(
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
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"),
P_F64O("temp"), P_STR("dtype") };
static const RadOperandSpec oDflashTree[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens"), OUT("parents") };
static const RadParamSpec pRmsHadQuant[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_STR("dtype"), P_F64O("wadd") };
@@ -317,10 +329,11 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_
static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"),
OUT("y") };
/* `split_n` is libr4d's (docs/OPS.md): ref never splits K, so it accepts and ignores it. */
/* `split_n` and `w_rb` are libr4d's (docs/OPS.md): ref never splits K and reads the per-row
* scale plane as it is, so it accepts and ignores both. */
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"),
P_INTO("split_n") };
P_INTO("split_n"), P_INTO("w_rb") };
/* The bias form has no parts (`pb1`/`pb2`); only the plain product supports them. */
static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype") };
@@ -366,6 +379,11 @@ static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out")
};
/* attn_paged with the verify block's tree (RadBatch::spec_parent, rad_drafter_tree). */
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")
};
/* 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. */
@@ -403,6 +421,15 @@ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n
P_F64O("k_scale"), P_F64O("v_scale") };
static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping"),
INOUT("kv_cache") };
/* The streamed store: kv_store's parameters, plus the authoritative mirror `host` (always
* written) and the residency map `res` (read, never written). */
static const RadParamSpec pKvStoreStreamed[] = {
P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"),
P_F64O("k_scale"), P_F64O("v_scale")
};
static const RadOperandSpec oKvStoreStreamed[] = { OPD("k"), OPD("v"), OPD("slot_mapping"),
INOUT("kv_cache"), OPD("res"),
INOUT("host") };
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
@@ -414,6 +441,23 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he
P_F64O("llama3_orig") };
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
static const RadParamSpec pPositionScale[] = { P_INT("M"), P_INT("n"), P_INT("original"),
P_F64("beta"), P_STR("dtype") };
static const RadOperandSpec oPositionScale[] = { INOUT("x"), OPD("positions") };
static const RadParamSpec pEmbedAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
P_INT("causal"), P_INTO("max_seqlen"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oEmbedAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") };
static const RadParamSpec pMinistralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_STR("dtype"), P_F64O("yarn_factor"),
P_F64O("yarn_low"), P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oMinistralRope[] = { INOUT("qkv"), OPD("pos") };
static const RadParamSpec pPixtralRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_F64("theta"), P_STR("dtype") };
static const RadOperandSpec oPixtralRope[] = { INOUT("qkv"), OPD("coord") };
static const RadParamSpec pPixtralMerge[] = { P_INT("M"), P_INT("n"), P_INT("merge"), P_STR("dtype") };
static const RadOperandSpec oPixtralMerge[] = { OPD("x"), OPD("coord"), OUT("y") };
/* The cos/sin plane a fused prologue reads instead of theta, at each position's own row of a
* [max_ctx, rot] table. `rot`, `theta` and `scale` are spelled as on `rope`, which must compute the
* same angles. */
@@ -457,6 +501,12 @@ static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
static const RadOperandSpec oQsaWork[] = { OPD("k"), OPD("pos"), OPD("cu"), OPD("state"),
OPD("sidx"), OPD("bt"), OPD_O("rope"), OUT("stage"),
OUT("page"), OUT("bpos"), OUT("nc") };
/* The residency map of a streamed group (ref_kvstream.cpp says why it takes no `block_size`). */
static const RadParamSpec pKvResolve[] = { P_INT("M"), P_INT("blocks"), P_INT("slots"),
P_INT("sel_pitch"), P_INT("block_bytes") };
static const RadOperandSpec oKvResolve[] = { INOUT("sel"), OPD("nsel"), INOUT("res"),
INOUT("slot_block"), INOUT("slot_state"),
INOUT("ctl"), OPD("host"), INOUT("kv_cache") };
/* DFlash2's grouped convolution, libr4d's schema exactly. */
static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"),
@@ -769,19 +819,23 @@ static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P
P_STR("dtype"), P_F64O("wadd"),
P_INTO("norm_once"), P_STRO("norm") };
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
OPD("cu_seqlens"), INOUT("x"), OUT("z") };
OPD("cu_seqlens"), INOUT("x"), OUT("z"),
OPD_O("colmap") };
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
P_INTO("norm_once"), P_STRO("norm") };
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"),
OUT_O("z") };
OUT_O("z"), OPD_O("colmap") };
/* `t`, `sigma` and `sigma_next` are one f32 value each. */
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
INOUT("x") };
static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"),
OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"),
P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y"), WGT_O("table") };
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") };
@@ -842,6 +896,17 @@ static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("o
P_INT("keep"), P_INT("blend"), P_INT("period"),
P_STR("mean"), P_STR("std") };
static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") };
/* The tiled encoder (ref_video.cpp): the plan, the cut and the blend. `geom` is the request's
* (clip, H, W); plan and crop take it in pixels, join in latent units. */
static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
P_INT("ratio") };
static const RadOperandSpec oVtilePlan[] = { OPD("geom"), OUT("y") };
static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
P_INT("ratio"), P_STR("dtype") };
static const RadOperandSpec oVtileCrop[] = { OPD("x"), OPD("geom"), OUT("y") };
static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oVtileJoin[] = { OPD("x"), OPD("geom"), OUT("y") };
/* `y` is [3, >= M], component-major at its own row pitch. */
static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"),
P_INT("period"), P_F64("scale") };
@@ -868,9 +933,12 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
/* ---- the latent upscaler (ref_video.cpp). `geom` is the request's volume, i32 on the device:
* (T, H, W) for conv3d_ndhwc and tconv_dw, (T, h, w, H, W) for resize_bilinear and (F, Hp, Wp)
* for patch_fold, which shares patch_unfold's parameters and operands. */
/* `stride`/`stride_t`/`causal`/`pad`/`reflect`: the video encoder's CausalConv3d forms; the
* defaults are the stride-1 `same` zero padding of everything shipped before them. */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
P_INTO("tpre") };
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
P_INTO("reflect"), P_STRO("tpad"), P_INTO("tpre") };
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
OPD_O("res"), OUT("y") };
/* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */
@@ -885,6 +953,11 @@ static const RadOperandSpec oResize[] = { OPD("x"), OPD("geom"), OUT("y") };
static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"),
P_STR("dtype") };
static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") };
/* `aug` is the condition's kept fraction (VISUAL_COND_TIMESTEP, 0.999), a declared constant
* where `flow_renoise` stages its weight. */
static const RadParamSpec pCondAug[] = { P_INT("M"), P_INT("n"), P_INT("stream"), P_F64("aug"),
P_STR("dtype") };
static const RadOperandSpec oCondAug[] = { OPD("seed"), INOUT("x") };
/* ---- LTX-2 (ref_ltx.cpp) */
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
@@ -935,7 +1008,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
/* ---- audio generation (ref_audio.cpp) */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
P_INTO("cu_div") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -951,19 +1025,28 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"),
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
P_INTO("sup_hi"), P_F64O("penalty") };
P_INTO("sup_hi"), P_F64O("penalty"),
P_F64O("top_p") };
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
P_STR("dtype"), P_INTO("round") };
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
P_STR("dtype") };
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
WGT("out_w"), WGT("out_b"), OUT("codes") };
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
P_INTO("rep"), P_STR("dtype") };
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
OPD("frame"), OPD("status"), INOUT("dst") };
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
P_INTO("rep"), P_INTO("clear") };
static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"),
OUT("ids") };
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
P_INTO("rep"), P_INTO("skip") };
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
@@ -993,6 +1076,8 @@ static const RadOperandSpec oIota[] = { OUT("y") };
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
static const RadParamSpec pSubI32[] = { P_INT("M") };
static const RadOperandSpec oSubI32[] = { OPD("x"), OPD("s"), OUT("y") };
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
/* ================================================================== the schema table */
@@ -1100,12 +1185,22 @@ static const RadOpSchema kSchemas[] = {
"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." },
{ "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),
"y[s] = mean of x's rows [cu[s], cu[s+1]): one row a segment, summed in double and rounded "
"once to y's dtype. An empty segment is a zero row." },
{ "seg_softmax_pool", ARR(pSegPool), ARR(oSegPool),
"y[s] = v's rows [cu[s], cu[s+1]) summed with the softmax of their scores (one a row, f32, the "
"maximum subtracted) as weights, in f32 and rounded once to y's dtype. An empty segment is a "
"zero row." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then "
"times `mult` (default 1) and rounded again. M, the input rows, is a multiple of k." },
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
"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." },
{ "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." },
@@ -1262,6 +1357,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_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 "
"with log probability parent + log_softmax(score / temp) over them, and each round selects the "
"unselected child with the largest (ties to the first pushed). tokens[j-1] and parents[j-1] are "
"the j-th selected node and its parent's index (0 the anchor)." },
{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense),
"ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / "
"rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column "
@@ -1290,7 +1391,7 @@ static const RadOpSchema kSchemas[] = {
/* The calibration op, the only one no forward pass issues: it runs under a calibration flag and
* its output is read at convert time, in another process, through a file. `dtype` is the input's:
* fp8a8 where the tap is a quantiser's output, bf16 without `a_scale` for a plain activation. */
{ "gram_accum", ARR(pQuant), ARR(oGram),
{ "gram_accum", ARR(pGram), ARR(oGram),
"h[k1][k2] += sum over rows m of dequant(a)[m][k1] * dequant(a)[m][k2], in f32. The second "
"moment of a layer's real input over a calibration corpus -- the Hessian a GPTQ packer needs. "
"dequant(a) is a * a_scale for fp8a8 and `a` itself for bf16, which passes no a_scale. "
@@ -1347,6 +1448,11 @@ 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_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_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| < "
@@ -1371,10 +1477,26 @@ static const RadOpSchema kSchemas[] = {
{ "kv_store", ARR(pKvStore), ARR(oKvStore),
"Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is "
"INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." },
{ "kv_store_streamed", ARR(pKvStoreStreamed), ARR(oKvStoreStreamed),
"kv_store for a streamed group: writes the token's k and v into the group's host mirror ALWAYS, "
"at the block's identity row, and into the ring slot only when the residency map says the block "
"is resident. A negative slot is skipped. The mirror is the truth; a block absent from the ring "
"is copied in whole by kv_resolve." },
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable),
"cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: "
"rot values a row, cos for the first half and sin for the second. The angles are `rope`'s "
"exactly. A row no position names is not written; a negative position writes nothing." },
{ "embed_attn", ARR(pEmbedAttn), ARR(oEmbedAttn),
"Whole noncausal segments with QK, scaled scores and probabilities rounded to activation dtype." },
{ "ministral_rope", ARR(pMinistralRope), ARR(oMinistralRope),
"Ministral NeoX rotary with BF16 cos/sin and separately rounded products; V is unchanged." },
{ "pixtral_rope", ARR(pPixtralRope), ARR(oPixtralRope),
"Pixtral axial rotary with interleaved height/width frequencies and BF16 product rounding." },
{ "pixtral_merge", ARR(pPixtralMerge), ARR(oPixtralMerge),
"Pack full raster patch grids into channel-major spatial merge blocks, without mixing images." },
{ "position_scale", ARR(pPositionScale), ARR(oPositionScale),
"Scale query row p by 1 + beta * log(1 + floor(position[p] / original)), rounding the scale "
"to x's dtype before multiplication. Positions are nonnegative i32." },
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
"QSA's compressed key, one vector per `ratio` rows of k: the block's mean accumulated in f32 and "
"rounded to k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at "
@@ -1397,6 +1519,15 @@ static const RadOpSchema kSchemas[] = {
"The blocks completing in this batch: per block its `ratio` raw keys (this step's rows, or the "
"tail's at q % ring) staged contiguously, its block-key page and its first-token position; slots "
"past the count get page -1. nc is each sequence's complete-block count." },
{ "kv_resolve", ARR(pKvResolve), ARR(oKvResolve),
"Makes every block the selections name resident and rewrites them as ring slots: an epoch bump, "
"a hit or a single claim per distinct block, a free slot before any resident one and otherwise "
"one CLOCK (second-chance) victim per miss - never a slot this call uses - the two maps "
"re-pointed, each missed block copied from the host mirror "
"into its slot, then every valid sel entry replaced by the slot holding its block. nsel, and so "
"the attention's length, are unchanged. The ring must hold the call's distinct blocks; a call "
"that cannot place every miss latches ctl[3] and leaves those entries naming blocks, never a "
"fabricated slot." },
{ "dflash_conv", ARR(pDflashConv), ARR(oDflashConv),
"DFlash2's grouped dynamic depthwise convolution: out[t][h] = sum over taps j, j == 0 or "
"t % block_size >= j, of (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]." },
@@ -1637,7 +1768,9 @@ static const RadOpSchema kSchemas[] = {
{ "timestep_embed", ARR(pTimestep), ARR(oTimestep),
"the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)) with "
"t' = scale * t; `round` 1 takes t through bf16 at scale and back first, as diffusers' "
"pipeline hands it to its transformer." },
"pipeline hands it to its transformer. With `curve` > 0 and a `table` [curve, n] f32 operand: "
"y[m] = table sampled at clamp01(max(t[m], clamp_min)) * (curve - 1), lerped between the two "
"rows around that position -- a precomputed adaln time-embedding curve." },
{ "gather_rows2", ARR(pMnD), ARR(oGather2),
"y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]: a sequence assembled from two sources." },
{ "lane_gather", ARR(pLane), ARR(oLaneGather),
@@ -1714,6 +1847,12 @@ static const RadOpSchema kSchemas[] = {
"a sampler step toward a data-ward velocity's clean estimate, in f32: st = 1 - t, "
"d = x + st v, r = sigma_next / sigma, x = r x + (1 - r) d, each product and sum rounded "
"once; t, sigma and sigma_next one value each (MiniMax-H3's scheduler)." },
{ "flow_res_multistep", ARR(pMnD), ARR(oFlowRM),
"a second-order sampler step on the clean estimate: d = x + sigma v, then "
"x = r x + hb1 d + hb2 x0 with r = sigma_next / sigma, x0 the previous step's estimate (read, "
"then d written back for the next). order<2 makes it Euler (x = r x + (1 - r) d), the first "
"step, a schedule restart and the last step; there hb1 + hb2 = 1 - r. sigma, r, hb1, hb2 and "
"order one f32 each; x and x0 f32 (MiniMax-H3's DPM-Solver++2M / res_multistep)." },
{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold),
"patch rows [F Hp Wp, C pt ph pw] (geom = (F, Hp, Wp)) unfolded to voxel rows "
"[(F pt) (Hp ph) (Wp pw), C] and denormalised, f32(f32(x * mul[c]) + add[c]) with `mul` and "
@@ -1729,6 +1868,20 @@ static const RadOpSchema kSchemas[] = {
"with `prev` unless the chunk is first, prev refilled from the chunk's tail (also emitted "
"when it is last), then bytes round(255 clamp(v std + mean, 0, 1)); geom = (frames, H, W, "
"first, last), u8 out." },
{ "vtile_plan", ARR(pVtilePlan), ARR(oVtilePlan),
"the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: split_tiles_axis over "
"the spatial axes in latent units (tile, overlap, pixels per latent ratio), tiles row-major; "
"row t of the i32 [M, 22] y is the tile's first pixel (y0, x0), its pixel extent (th, tw) and "
"level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)) for L = 0..5; M is the tile count." },
{ "vtile_crop", ARR(pVtileCrop), ARR(oVtileCrop),
"one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into vtile_plan's tiles: "
"y [M, 3] the tiles' pixels tile-major, M the tiles' pixel count (sum of th tw)." },
{ "vtile_join", ARR(pVtileJoin), ARR(oVtileJoin),
"the tiled encoder's per-tile moments (vtile_crop's row layout at latent extent) blended into "
"the canvas y [M, n], M = geom's (clip, lat_h, lat_w) lat_h lat_w: a canvas position's tile "
"kept range, blended with the tile above and then the tile to the left, both RAW (never "
"already blended), the products and sums rounding to x's dtype as the reference's bf16 blends "
"do." },
{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3),
"a video decoder's rotary positions over tiles of `period` rows: token (t, i, j) of a tile's "
"T x H x W gets f32(scale) * (2 (c + 0.5) / n - 1) on each axis, in f32 as torch makes it, "
@@ -1747,10 +1900,15 @@ static const RadOpSchema kSchemas[] = {
"max subtracted. With `coarse` and `gate`: out = rd(rd(o) + coarse[h][tile] gate), rd the "
"output's dtype." },
{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d),
"a 3-D convolution over voxel rows [T H W, cin] -> [T H W, cout] (geom = (T, H, W)): "
"PyTorch's Conv3d weight [cout, cin, kt, k, k] and bias, stride 1, `same` zero padding (kt/2 "
"frames, k/2 rows and columns a side; k and kt odd), f32 accumulation, rd(acc + b); with `res`, "
"rd(rd(acc + b) + res), `res` possibly y itself." },
"a 3-D convolution over voxel rows of geom = (T, H, W) -> [rows out, cout]: "
"PyTorch's Conv3d weight [cout, cin, kt, k, k] and bias, f32 accumulation, rd(acc + b). "
"Defaults are stride 1 with `same` zero padding (kt/2 frames, k/2 rows and columns a side; "
"k and kt odd). `stride` (spatial) and `stride_t` > 1 pad then stride (3x3x3 only); `causal` "
"1 pads the time axis front-only with kt - 1 zeros and none behind (so one frame in gives "
"one frame out at any stride, the reference's T==1 tap truncation); `pad` `down` pads none "
"above and left and one below and right; `reflect` 1 mirrors the spatial padding (torch "
"mode `reflect`, a mirror with no repeated edge, so the padded dimension must exceed the "
"pad). With `res`, rd(rd(acc + b) + res), `res` possibly y itself." },
{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm),
"PyTorch's GroupNorm over all M rows: group g is channels [g n/groups, (g+1) n/groups), its "
"biased mean and variance in f64, rstd = 1 / sqrt(var + eps) in f32; v = (x - mean) rstd w + b, "
@@ -1772,6 +1930,11 @@ static const RadOpSchema kSchemas[] = {
{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise),
"a clean latent re-noised to sigma s: x = f32(f32(f32(1 - s) x) + f32(s z)), z element "
"k n + c of the normal stream (seed, `stream`) (abi/rad_philox.h)." },
{ "cond_aug", ARR(pCondAug), ARR(oCondAug),
"a visual condition's rows blended with fresh noise, the reference's condition augmentation: "
"x = f32(f32(a x) + f32(oma z)) with a = `aug` and oma the f32 of the f64 1 - aug, z element "
"k n + c of the normal stream (seed, `stream`); the caller issues one media item's rows so "
"every item restarts the same stream, as the reference does." },
{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit),
"LTX-2's rotary over fractional coordinates: dim/2 pairs over all heads, the first `pad` "
"unrotated, then freq[k] = f32(theta^linspace(0,1,steps)[k] pi/2) with the n_dims coordinates "
@@ -1820,7 +1983,9 @@ static const RadOpSchema kSchemas[] = {
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], "
"y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding "
"dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each "
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1])." },
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). bf16 only "
"with `stride` > 1: one sequence [0, rows of x], an explicit `pad` and any k, output row m "
"reading x[m * stride + tap * dil - pad] — PyTorch's zero-padded strided conv exactly." },
{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d),
"a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` "
"((k - stride) / 2 by default, 0 the causal form): each sequence of x [rows, cin] grows "
@@ -1845,11 +2010,19 @@ static const RadOpSchema kSchemas[] = {
"a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum "
"of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or "
"with `round` 1 one f32 sum in codebook order times scale, rounded once." },
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
"one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest "
"cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded "
"once." },
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
"a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, "
"stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." },
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
{ "ras_pick", ARR(pRasPick), ARR(oRasPick),
"repetition-aware sampling: ids[rep i] = alt[rep i] where first[rep i] is in [lo, hi) and in "
"the lane's window of its last `win` picks (hist [lanes, win], -1 empty, cleared first with "
"`clear` 1), else first[rep i]; the pick then enters the window." },
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = "
"codes[k, rep i] when frame >= skip and status[lane] >= 0." },
@@ -1883,6 +2056,18 @@ static const RadOpSchema kSchemas[] = {
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and "
"bounds derived from a pass's device geometry." },
{ "sub_i32", ARR(pSubI32), ARR(oSubI32),
"y[i] = x[i] - s[0], int32: a device length less a device offset." },
/* Row forms libr4d declares under names of their own, so a model can ask for the form: the same op, the same
* arithmetic and the same schema as the op named in each string. */
{ "rmsnorm_rows", ARR(pRmsnorm), ARR(oRmsnorm),
"rmsnorm, for rows a model declares in thousands (the head norms over head_dim)." },
{ "rope_rows", ARR(pRope), ARR(oRope),
"rope, for a model that wants the per-(token, pair) angles form at prefill row counts." },
{ "gemm_nt_q_short", ARR(pGemmQ), ARR(oGemmQ),
"gemm_nt_q, for the short-prompt split rule's rows." },
{ "gemm_nt_q_gated_wide", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q_gated at any M." },
};
/* ================================================================== the kernel table */
@@ -2003,16 +2188,23 @@ static int ref_check_gemm_q(const char* op, const RadArgs* a) {
}, \
nullptr, lay, ref::ref_relayout_planes<lay>, fn##_shape, ref::ref_unrelayout_planes<lay> }
/* gemm_nt_q: its zero-point grids join scale and zero (ref_planes.h) while its m2xfp4 arm
* concatenates codes and meta, so the row carries the hook's own relayout pair. */
#define ROWL_GQ(nm, opname, fam, what, dts, check, fn, lay) \
/* gemm_nt_q's row: the hooks above with dtype m2xfp4 answered first (ref_m2xfp4.cpp). */
int ref_gemm_nt_q_m2(const RadArgs*, RadStream);
REF_SHAPE_FN(ref_gemm_nt_q_m2);
int ref_layout_gemm_q_m2(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int ref_relayout_gemm_q_m2(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int ref_unrelayout_gemm_q_m2(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
#define ROWL_GQ(nm, opname, fam, what, dts, check, fn, lay, rel, unrel) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, \
[](const RadArgs* a, RadStream s) -> int { \
const int rc = check(opname, a); \
return rc < 0 ? rc : fn(a, s); \
}, \
nullptr, lay, ref::ref_relayout_gemm_q<lay>, fn##_shape, ref::ref_unrelayout_gemm_q<lay> }
nullptr, lay, rel, fn##_shape, unrel }
#define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype"
#define DT_ANY "any dtype rad_types.h names, per operand"
@@ -2086,10 +2278,17 @@ SIMPLE("ref_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows
ref_mix_rows),
SIMPLE("ref_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights",
DT_FLOAT, ref_chan_stats),
SIMPLE("ref_seg_mean_bf16_sum", "seg_mean_bf16_sum", "elem", "BF16 sum/division mean pooling",
"bf16 in and out; f32 sum, BF16 sum and quotient", ref_seg_mean_bf16_sum),
SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT,
ref_seg_mean),
SIMPLE("ref_seg_softmax_pool", "seg_softmax_pool", "elem",
"each cu_seqlens segment's rows summed with the softmax of their scores", DT_FLOAT,
ref_seg_softmax_pool),
SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
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_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",
@@ -2154,6 +2353,9 @@ 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_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),
SIMPLE("ref_givens_rotate", "givens_rotate", "quant",
"channel scale and Givens rotations per part, in the output's dtype",
"float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate),
@@ -2192,7 +2394,8 @@ SIMPLE("ref_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT,
ROWL_GQ("ref_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, m2xfp4, i8 or float B; u2 / u4 / u5 codes with an f16 "
"scale and integer zero per group, joined; f32 accumulate",
ref_check_gemm_q, ref_gemm_nt_q, ref::ref_layout_gemm_q),
ref_check_gemm_q, ref_gemm_nt_q_m2, ref_layout_gemm_q_m2, ref_relayout_gemm_q_m2,
ref_unrelayout_gemm_q_m2),
SIMPLE("ref_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", ref_gemm_nt_q_bias),
SIMPLE("ref_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base rows untouched",
@@ -2210,6 +2413,11 @@ 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_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),
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",
@@ -2223,7 +2431,15 @@ SIMPLE("ref_sam_attn", "sam_attn", "attn",
ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_kv_store, nullptr),
ROW("ref_kv_store_streamed", "kv_store_streamed", "attn",
"scatter k and v into the host mirror always and into the resident ring slot", DT_ANY,
nullptr, 0, nullptr, nullptr, ref_kv_store_streamed, nullptr),
SIMPLE("ref_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, ref_rope),
SIMPLE("ref_embed_attn", "embed_attn", "attn", "BF16 materialized encoder attention", "bf16/f32, i32 cu", ref_embed_attn),
SIMPLE("ref_ministral_rope", "ministral_rope", "attn", "Ministral BF16 rotary", "bf16/f32 inout, i32 positions", ref_ministral_rope),
SIMPLE("ref_pixtral_rope", "pixtral_rope", "attn", "Pixtral interleaved axial rotary", "bf16/f32 inout, i32 coordinates", ref_pixtral_rope),
SIMPLE("ref_pixtral_merge", "pixtral_merge", "vision", "channel-major patch merger packing", "bf16/f32, i32 coordinates", ref_pixtral_merge),
SIMPLE("ref_position_scale", "position_scale", "attn", "Ministral position-dependent query scale", "bf16/f32 inout, i32 positions", ref_position_scale),
SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
DT_FLOAT, ref_qk_norm_rope),
@@ -2265,6 +2481,9 @@ SIMPLE("ref_qsa_tail_store", "qsa_tail_store", "attn",
ref_qsa_tail_store),
SIMPLE("ref_qsa_work", "qsa_work", "attn",
"QSA work list: completing blocks' keys, pages and positions", DT_FLOAT, ref_qsa_work),
SIMPLE("ref_kv_resolve", "kv_resolve", "attn",
"streamed KV residency map: selected block ids become ring slots, misses copied in",
"i32 maps, u8 block planes", ref_kv_resolve),
SIMPLE("ref_dflash_conv", "dflash_conv", "draft",
"DFlash2 grouped dynamic depthwise convolution", DT_FLOAT, ref_dflash_conv),
SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk),
@@ -2382,6 +2601,8 @@ SIMPLE("ref_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
"gated residual, modulated RMS norm, block-scaled E4M3", DT_FLOAT, ref_rms_mod_quant_fp8),
SIMPLE("ref_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate",
DT_FLOAT, ref_flow_x0_step),
SIMPLE("ref_flow_res_multistep", "flow_res_multistep", "elem",
"a second-order sampler step on the clean estimate", DT_FLOAT, ref_flow_res_multistep),
SIMPLE("ref_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows",
DT_FLOAT, ref_patch_unfold),
SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent",
@@ -2389,6 +2610,12 @@ SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out
SIMPLE("ref_vtile_stitch", "vtile_stitch", "elem",
"decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT,
ref_vtile_stitch),
SIMPLE("ref_vtile_plan", "vtile_plan", "elem", "the tiled encoder's per-tile geometry table",
DT_ANY, ref_vtile_plan),
SIMPLE("ref_vtile_crop", "vtile_crop", "elem", "a frame's pixel plane cut into encode tiles",
DT_FLOAT, ref_vtile_crop),
SIMPLE("ref_vtile_join", "vtile_join", "elem",
"per-tile encoder moments blended into the latent canvas", DT_FLOAT, ref_vtile_join),
SIMPLE("ref_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles",
DT_FLOAT, ref_grid_pos3),
SIMPLE("ref_vsa_select", "vsa_select", "attn",
@@ -2410,6 +2637,8 @@ SIMPLE("ref_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r
ref_patch_fold),
SIMPLE("ref_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", DT_FLOAT,
ref_flow_renoise),
SIMPLE("ref_cond_aug", "cond_aug", "elem", "condition rows blended with fresh noise at a fixed aug",
DT_FLOAT, ref_cond_aug),
SIMPLE("ref_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT,
ref_rope_split),
SIMPLE("ref_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT,
@@ -2441,10 +2670,14 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
DT_FLOAT, ref_cfg_topk_sample),
SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
DT_FLOAT, ref_rvq_embed),
SIMPLE("ref_vq_encode", "vq_encode", "elem",
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode),
SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane",
DT_FLOAT, ref_frame_mix_store),
SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
ref_end_status),
SIMPLE("ref_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane",
DT_ANY, ref_ras_pick),
SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
ref_frame_store),
SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
@@ -2465,6 +2698,18 @@ SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_i
SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat),
SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
ref_int_affine),
SIMPLE("ref_sub_i32", "sub_i32", "elem", "a device int32 vector less a device scalar", DT_ANY,
ref_sub_i32),
/* The row-form names (see the schema table): each the base op's reference row. */
SIMPLE("ref_rmsnorm_rows", "rmsnorm_rows", "norm", "rmsnorm under its row-form name", DT_FLOAT,
ref_rmsnorm),
SIMPLE("ref_rope_rows", "rope_rows", "attn", "rope under its row-form name", DT_FLOAT, ref_rope),
ROWL_GQ("ref_gemm_nt_q_short", "gemm_nt_q_short", "gemm", "gemm_nt_q under its row-form name",
"as ref_gemm_nt_q", ref_check_gemm_q, ref_gemm_nt_q_m2, ref_layout_gemm_q_m2,
ref_relayout_gemm_q_m2, ref_unrelayout_gemm_q_m2),
SIMPLE("ref_gemm_nt_q_gated_wide", "gemm_nt_q_gated_wide", "gemm",
"gemm_nt_q_gated under its row-form name", "fp8_e4m3 operands, fp8_e4m3 out, f32 scale",
ref_gemm_nt_q_gated),
};
/* ================================================================== plugin exports */
@@ -2479,6 +2724,7 @@ static const RadPluginInfo kInfo = {
};
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
/* Declares this plugin the reference through the ABI (RadPluginReferenceFn); the engine knows no
* library by name. */
+304 -5
View File
@@ -534,6 +534,52 @@ int ref_act_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return binary_shape(p, n_p, operand, "act_mul", out);
}
int ref_position_scale_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);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), {M, n});
o.t_idx({M}, 32768, -1, 0);
return o.finish("position_scale", operand, out);
}
int ref_embed_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0);
const int64_t G = gi(p, n_p, "gqa", 1), S = n_seq_of(p, n_p);
Opd o;
o.t(act_dt(p, n_p), {M, G * D});
o.t(act_dt(p, n_p), {M, D});
o.t(act_dt(p, n_p), {M, D});
o.t_idx({S + 1}, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU);
o.t(act_dt(p, n_p), {M, G * D});
return o.finish("embed_attn", operand, out);
}
int ref_ministral_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0);
const int64_t H = gi(p, n_p, "n_head", 0), K = gi(p, n_p, "n_head_kv", 0);
Opd o;
o.t(act_dt(p, n_p), {M, (H + 2 * K) * D});
o.t_idx({M}, 32768, -1, 0);
return o.finish("ministral_rope", operand, out);
}
int ref_pixtral_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "head_dim", 0),
H = gi(p, n_p, "n_head", 0);
if (M <= 0 || D <= 0 || D % 4 || H <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), {M, 3 * H * D});
o.t_idx({2, M}, 80, -1, 0);
return o.finish("pixtral_rope", operand, out);
}
int ref_pixtral_merge_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
/* The coordinates describe complete raster grids. Random independent indices cannot make
* a legal fixture: callers provide the grid and its patch data together. */
return RAD_E_UNSUPPORTED;
}
int ref_seg_mean_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);
@@ -546,6 +592,25 @@ int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("seg_mean", operand, out);
}
int ref_seg_softmax_pool_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);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const int64_t S = n_seq_of(p, n_p);
Opd o;
o.t(D, { M }); /* score, one a row of v */
o.t(D, { M, n }); /* v */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { S, n }); /* y */
return o.finish("seg_softmax_pool", operand, out);
}
int ref_seg_mean_bf16_sum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
if (act_dt(p, n_p) != RAD_BF16)
return RAD_E_UNSUPPORTED;
return ref_seg_mean_shape(p, n_p, operand, out);
}
int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0);
@@ -559,6 +624,16 @@ int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("pool_rows", operand, out);
}
int ref_pool_cols_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0), M = gi(p, n_p, "M", 0);
if (M <= 0 || n <= 0 || k <= 0 || n % k) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { M, n / k }); /* y */
return o.finish("pool_cols", 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);
@@ -1336,6 +1411,18 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("attn_paged", operand, out);
}
/* attn_paged's operands and its tree's parents, each row an ordinary causal one (-2): a drawn
* plane would name parents that are not a tree. */
int ref_attn_paged_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
if (operand < 8) return ref_attn_paged_shape(p, n_p, operand, out);
const int64_t M = gi(p, n_p, "q_len", 0);
if (M <= 0) return RAD_E_UNSUPPORTED;
Opd o;
for (int i = 0; i < 8; ++i) o.skip();
o.t_idx({ M }, 0, -2, 0); /* spec_parent */
return o.finish("attn_paged_tree", operand, out);
}
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);
@@ -1470,6 +1557,31 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("kv_store", operand, out);
}
/* The streamed store: kv_store's geometry plus the mirror (one block a row at the ring's pitch)
* and the residency map. The described call touches one block, resident in slot 0: the draw
* cannot express an injective map, and two blocks drawing one slot would race on a ring byte.
* Partly resident maps and mirror-only writes are built by hand in tests/ref_test.cpp and in
* libavx's hand cases. `M <= block_size` keeps every token on its own position of that block. */
int ref_kv_store_streamed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t kvh = gi(p, n_p, "n_head_kv", 0);
const int64_t bs = gi(p, n_p, "block_size", 0);
if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED;
const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_F8E4M3 : kv;
const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1);
Opd o;
o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* k */
o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* v */
o.t_idx({ M }, bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping, one block */
o.t(KV, { 1, kvh, bs, 2 * hd }); /* kv_cache, INOUT */
o.t_idx({ 1 }, 1, -1, 0); /* res -- resident in slot 0 */
o.t((uint32_t)RAD_U8, { 1, row }); /* host, INOUT */
return o.finish("kv_store_streamed", operand, out);
}
int ref_rope_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);
@@ -1659,6 +1771,27 @@ int ref_qsa_work_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("qsa_work", operand, out);
}
/* The residency map and the two byte planes. `sel` is block ids, -1 past `nsel`. A described map
* can only be all-resident (no draw expresses -1), so a tool's cold call exercises the epoch, the
* rewrite and the bookkeeping, never a miss, eviction or copy; those cases are built by hand in
* tests/ref_test.cpp and in libavx's hand cases. */
int ref_kv_resolve_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), blocks = gi(p, n_p, "blocks", 0);
const int64_t slots = gi(p, n_p, "slots", 0), pitch = gi(p, n_p, "sel_pitch", 0);
const int64_t bbytes = gi(p, n_p, "block_bytes", 0);
if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ M, pitch }, blocks, -1, 0); /* sel -- one block id an entry */
o.t_idx({ M }, pitch + 1, -1, 0); /* nsel -- 0 .. sel_pitch */
o.t_idx({ blocks }, slots, -1, 0); /* res -- every block resident, no -2 */
o.t_idx({ slots }, blocks, -1, 0); /* slot_block -- the reverse map */
o.t_idx({ slots, 2 }, 2, 0, 0); /* slot_state -- cold: epoch 0, no reference */
o.t_idx({ 16 }, 2, 0, 0); /* ctl -- cold: epoch 0, hand 0 */
o.t((uint32_t)RAD_U8, { blocks, bbytes }); /* host -- the layer's mirror, a block a row */
o.t((uint32_t)RAD_U8, { slots, bbytes }); /* kv_cache -- the layer's ring, a block a row */
return o.finish("kv_resolve", operand, out);
}
/* `delta` is described as the whole [T, 2 * taps * NG] coefficient projection, of which the op
* reads the first taps * NG columns at the row pitch: the form the architecture issues, and the
* pitch libr4d requires. */
@@ -2062,6 +2195,30 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("dflash_select", operand, out);
}
/* 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);
const int64_t steps = gi(p, n_p, "steps", 0);
const int64_t K = gi(p, n_p, "top_k", 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);
const int64_t N = gi(p, n_p, "nodes", steps);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0)
return RAD_E_UNSUPPORTED;
const int64_t rows = M * steps;
Opd o;
o.t_idx_dt((uint32_t)RAD_I32, { rows, K }, nv, -1, 0); /* cand */
o.t((uint32_t)RAD_F32, { rows, K }); /* unary */
o.t((uint32_t)RAD_BF16, { rows, R }); /* hp */
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_idx_dt((uint32_t)RAD_I32, { M, N }, nv, -1, 0); /* tokens */
o.t_idx_dt((uint32_t)RAD_I32, { M, N }, N + 1, -1, 0); /* parents */
return o.finish("dflash_tree", operand, out);
}
/* ================================================================== gated delta net
*
* The layouts are libref/ref_gdn.cpp's:
@@ -2602,6 +2759,7 @@ int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, n }); /* x, INOUT */
o.t(D, { M, n }); /* z */
o.skip(); /* colmap: the sweep passes none */
return o.finish("rms_mod", operand, out);
}
int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
@@ -2625,6 +2783,7 @@ int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */
o.t((uint32_t)RAD_F32, { M, ng }); /* scale */
o.t(D, { M, n }); /* z */
o.skip(); /* colmap: the sweep passes none */
return o.finish("rms_mod_quant_fp8", operand, out);
}
/* The sampler's three scalars in (0, 1), the state f32. */
@@ -2639,6 +2798,20 @@ int ref_flow_x0_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
o.t(F, { M, n }); /* x, INOUT */
return o.finish("flow_x0_step", operand, out);
}
int ref_flow_res_multistep_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 uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* v */
o.t(F, { M, n }); /* x0, INOUT */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* r */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* hb1 */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* hb2 */
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* order */
o.t(F, { M, n }); /* x, INOUT */
return o.finish("flow_res_multistep", operand, out);
}
int ref_gate_add_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 uint32_t D = act_dt(p, n_p);
@@ -2650,10 +2823,11 @@ int ref_gate_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("gate_add", operand, out);
}
int ref_timestep_embed_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 M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), G = gi(p, n_p, "curve", 0);
Opd o;
o.t_fill((uint32_t)RAD_F32, { M }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t: a sigma in (0, 1) */
o.t(act_dt(p, n_p), { M, n }); /* y */
if (G > 0) o.t((uint32_t)RAD_F32, { G, n }); else o.skip(); /* table */
return o.finish("timestep_embed", operand, out);
}
int ref_gather_rows2_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
@@ -2981,6 +3155,22 @@ static int64_t tile_count(int64_t len, int64_t tile, int64_t overlap) {
return nt;
}
/* The encoder's split (ref_video.cpp split_tiles_axis) over one axis: the tile count and the
* tiles' extent sum along it, a lone tile short of `tile` if the axis is. -1 where the split
* refuses. The drawn encode planes are `axis_len` long, so the shape fns can size the tile
* operands exactly. */
static int64_t axis_split(int64_t len, int64_t tile, int64_t overlap, int64_t* ext) {
if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return -1;
if (tile >= len) {
*ext = len;
return 1;
}
const int64_t nt = tile_count(len, tile, overlap);
/* The extents telescope: sum of the tiles = len + sum of the overlaps = `tile` nt. */
*ext = tile * nt;
return nt;
}
/* A 2 x 2 x 2 grid of patches. */
int ref_patch_unfold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0);
@@ -3133,6 +3323,61 @@ int ref_flow_renoise_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
return o.finish("flow_renoise", operand, out);
}
/* aug in [0, 1); the condition rows f32. */
int ref_cond_aug_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 double aug = rad_param_getf(p, n_p, "aug", -1.0);
if (M <= 0 || n <= 0 || !(aug >= 0.0 && aug < 1.0)) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ 2 }, (int64_t)1 << 30, -1, 0); /* seed: two words */
o.t((uint32_t)RAD_F32, { M, n }); /* x, INOUT */
return o.finish("cond_aug", operand, out);
}
/* ---- the tiled encoder. The drawn frame is 20 latent units a side; with the sweep's tile of
* 16 and overlap of 4 the split lays 2 x 2 full tiles over it, so the crops, the plan's level
* triples and the blends all draw non-trivial. The kernels size by the geom; these only draw a
* plane that one gives them. */
int ref_vtile_plan_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0);
const int64_t ov = gi(p, n_p, "overlap", 0), ratio = gi(p, n_p, "ratio", 0);
int64_t e = 0;
const int64_t nt = axis_split(20, tile, ov, &e);
if (M <= 0 || nt < 0 || ratio <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ 3 }, 0, 20 * ratio, 0); /* geom: (_, H, W) pixels */
o.t((uint32_t)RAD_I32, { M, 22 }); /* y: one row a tile */
return o.finish("vtile_plan", operand, out);
}
int ref_vtile_crop_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0);
const int64_t ov = gi(p, n_p, "overlap", 0), ratio = gi(p, n_p, "ratio", 0);
int64_t e = 0;
const int64_t nt = axis_split(20, tile, ov, &e);
if (M <= 0 || nt < 0 || ratio <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { 20 * ratio * (20 * ratio), 3 }); /* x: the pixel plane */
o.t_idx({ 3 }, 0, 20 * ratio, 0); /* geom: (_, H, W) pixels */
o.t(D, { M, 3 }); /* y: the tiles' pixels */
return o.finish("vtile_crop", operand, out);
}
int ref_vtile_join_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0);
const int64_t ov = gi(p, n_p, "overlap", 0), n = gi(p, n_p, "n", 0);
int64_t e = 0;
const int64_t nt = axis_split(20, tile, ov, &e);
if (M <= 0 || nt < 0 || n <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { e * e, n }); /* x: the tiles' moments */
o.t_idx({ 3 }, 0, 20, 0); /* geom: (_, lat_h, lat_w) */
o.t(D, { M, n }); /* y: the canvas */
return o.finish("vtile_join", operand, out);
}
/* ================================================================== video sparse attention
*
* The tiles come from the values of `segs` and `geom`, which a description draws only as
@@ -3239,19 +3484,32 @@ int ref_attn_vsa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
* REF_LANES lanes, as the image generator's are. */
static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; }
/* `M` is the input rows; with `stride` > 1 (bf16, one sequence, explicit `pad`) the output is
* PyTorch's strided length, `M` being the rows of the one sequence `cu_seqlens` must cover. */
int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0))
const int64_t st = gi(p, n_p, "stride", 1), pp = gi(p, n_p, "pad", -1);
const int64_t dil = gi(p, n_p, "dil", 1);
const bool padded = pp >= 0 && st > 1; /* the zero-padded strided form (explicit `pad`) */
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) ||
st < 1 || (pp >= 0 && (st <= 1 || causal)) ||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st || M % st)) ||
(!padded && gi(p, n_p, "cu_div", 1) != 1))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const int64_t S = two_seqs(M);
if (padded && D != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED;
/* A strided convolution is described over one sequence: two would each need a whole number
* of strides. Bounds in coarser units (cu_div) are not drawn; ref_test checks them. */
const int64_t S = st > 1 ? 1 : two_seqs(M);
const int64_t O = padded ? (M + 2 * pp - dil * (k - 1) - 1) / st + 1 : M / st;
if (O <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, cin }); /* x */
o.t(D, { cout, cin, k }); /* w */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, cout }); /* res */
o.t(D, { M, cout }); /* y */
o.t(D, { O, cout }); /* res */
o.t(D, { O, cout }); /* y */
o.t(D, { cout }); /* b */
return o.finish("conv1d", operand, out);
}
@@ -3329,6 +3587,22 @@ int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
return o.finish("rvq_embed", operand, out);
}
int ref_vq_encode_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t dim = gi(p, n_p, "dim", 0), bins = gi(p, n_p, "bins", 0);
if (M <= 0 || n <= 0 || dim <= 0 || bins <= 0) return RAD_E_UNSUPPORTED;
const uint32_t F = (uint32_t)RAD_F32;
Opd o;
o.t(act_dt(p, n_p), { M, n }); /* x, INOUT */
o.t(F, { dim, n }); /* in_w */
o.t(F, { dim }); /* in_b */
o.t(F, { bins, dim }); /* cb */
o.t(F, { n, dim }); /* out_w */
o.t(F, { n }); /* out_b */
o.t_idx({ M }, bins, -1, 0); /* codes, OUT */
return o.finish("vq_encode", operand, out);
}
int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0);
const int64_t st = gi(p, n_p, "stride", 0);
@@ -3356,6 +3630,21 @@ int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("end_status", operand, out);
}
int ref_ras_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), W = gi(p, n_p, "win", 0);
const int64_t hi = gi(p, n_p, "hi", 0);
if (M <= 0 || rep < 1 || W <= 0 || hi <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED;
Opd o;
/* Picks over a small band so the windows repeat them often enough to exercise the redraw. */
const int64_t band = std::min<int64_t>(hi + 2, 12);
o.t_idx({ rep * M }, band, -1, 0); /* first */
o.t_idx({ rep * M }, band, -1, 0); /* alt */
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
o.t_idx({ REF_LANES * W }, band, -1, 0); /* hist, INOUT */
o.t_idx({ rep * M }, band, -1, 0); /* ids, OUT */
return o.finish("ras_pick", operand, out);
}
int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0);
const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1);
@@ -3494,6 +3783,16 @@ int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("int_affine", operand, out);
}
int ref_sub_i32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
if (M <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ M }, 100000, -1, 0); /* x */
o.t_idx({ 1 }, 1000, -1, 0); /* s */
o.t_idx({ M }, 1, -1, 0); /* y */
return o.finish("sub_i32", operand, out);
}
/* ================================================================== LTX-2 (ref_ltx.cpp) */
int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0);
+279 -18
View File
@@ -63,6 +63,20 @@ bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector<int64_t
return true;
}
/* The encoder's split over one axis (comfy/ldm/minimax/vae.py, `split_tiles`): split_tiles,
* except that an axis no longer than a tile is one tile, short if need be, where the decoder's
* split demands an exact fit. */
bool split_tiles_axis(int64_t len, int64_t tile, int64_t overlap, std::vector<int64_t>* start,
std::vector<int64_t>* ov) {
if (tile >= len) {
start->clear();
ov->clear();
start->push_back(0);
return len > 0 && tile > 0 && overlap >= 0 && overlap < tile;
}
return split_tiles(len, tile, overlap, start, ov);
}
} /* namespace */
/* ------------------------------------------------------------------ patch_unfold */
@@ -346,9 +360,10 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
* `geom` carries the request's volume; an output holds at least the rows the volume writes. */
/* ------------------------------------------------------------------ conv3d_ndhwc */
/* A 3-D convolution, stride 1 with `same` zero padding: kt / 2 frames and k / 2 rows and columns
* on each side (kt and k odd). x [>= T H W, cin], y and `res` [>= T H W, cout], geom = (T, H, W);
* w is PyTorch's Conv3d weight [cout, cin, kt, k, k] and b [cout]:
/* A 3-D convolution over the volume geom = (T, H, W). The defaults are stride 1 with `same` zero
* padding: kt / 2 frames and k / 2 rows and columns on each side (kt and k odd); x
* [>= T H W, cin] and y and `res` [>= rows out, cout]; w is PyTorch's Conv3d weight
* [cout, cin, kt, k, k] and b [cout]:
*
* acc = sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw] x[(t + dt - kt/2, i + kh - k/2,
* j + kw - k/2), ci]
@@ -359,11 +374,33 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
* residual is added, as a residual block's skip(x) + h adds two bf16 tensors. `res` may be y
* itself: each output element reads its own residual before its write, and no other.
*
* The optional `stride` (spatial) and `stride_t` pad first and then stride, `causal` 1 takes the
* temporal padding front-only (kt - 1 zeros, none behind), `pad` `down` pads none above and left
* and one below and right, and `reflect` 1 mirrors the spatial padding instead of zeroing it;
* these CausalConv3d forms need k = kt = 3. Output (t, i, j) then reads
* x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci] over the lengths
*
* ((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
* ((W + pl + pr - k) / stride + 1) (floor divisions)
*
* with ft / bk and pt / pb / pl / pr the front / back and top / bottom / left / right pads. The
* time axis is zero-padded unless `tpad` says otherwise (below); `reflect` mirrors each spatial
* axis once, torch's `reflect` (x[-n] = x[n], x[D + n] = x[D - 2 - n]), so each pad must be below
* the axis it pads.
*
* `tpad` sets the frames' padding (rows and columns stay zero-padded): `zero` (the default),
* `replicate` (the edge frame repeated, kt/2 a side: LTX-2's decoder) or `causal` (the first
* frame repeated kt - 1 times in front, nothing after: LTX-2's encoder). With `causal`, `tpre`
* more copies of the first frame stand in front of those, and y has T + tpre frames (LTX-2's
* temporal downsampler, which prepends its first frame before its convolution). */
* temporal downsampler, which prepends its first frame before its convolution). It folds into
* the same grid math: replicate keeps ft = kt / 2 and clamps the time reads to the volume;
* causal-`tpre` takes ft = kt - 1 + tpre and bk = 0, clamping below. `tpad` `causal` repeats
* where `causal` 1 zeroes, and the two are refused together. */
static int64_t idiv_floor(int64_t a, int64_t b) {
const int64_t q = a / b;
return (a % b && (a < 0) != (b < 0)) ? q - 1 : q;
}
int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
if (a->n_t < 6 || !have(a, 4) || !t_in(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3];
@@ -376,33 +413,52 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 ||
numel(geom) < 3)
return RAD_E_SHAPE;
const int64_t sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
const char* pads = p_str(a, "pad", "same");
const bool down = pads && !std::strcmp(pads, "down");
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
(causal && tpad) /* zero-causal and replicated-causal contradict */ ||
!(!pads || !std::strcmp(pads, "same") || down))
return RAD_E_SHAPE;
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2);
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
const int64_t rows = (T + tpre) * H * W, taps = kt * k * k;
if (rows_of(y, cout) < rows || rows_of(x, cin) < T * H * W ||
(res && rows_of(res, cout) < rows) || numel(w) < cout * cin * taps || numel(b) < cout)
const int64_t ft = causal ? kt - 1 : tpad == 2 ? kt - 1 + tpre : kt / 2;
const int64_t bk = (causal || tpad == 2) ? 0 : kt / 2;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= W)) return RAD_E_SHAPE;
const int64_t T2 = idiv_floor(T + ft + bk - kt, st) + 1;
const int64_t H2 = idiv_floor(H + pt + pb - k, sp) + 1;
const int64_t W2 = idiv_floor(W + pl + pr - k, sp) + 1;
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return RAD_E_SHAPE;
const int64_t rows = T * H * W, orows = T2 * H2 * W2, taps = kt * k * k;
if (rows_of(y, cout) < orows || rows_of(x, cin) < rows ||
(res && rows_of(res, cout) < orows) || numel(w) < cout * cin * taps || numel(b) < cout)
return RAD_E_SHAPE;
const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y);
const int64_t xs = laststride(x), ys = laststride(y);
const int64_t rs = res ? laststride(res) : 0;
const uint32_t dt = y->dtype;
REF_PAR_FOR(rows * cout * cin * taps)
for (int64_t r = 0; r < rows; ++r) {
const int64_t t = r / (H * W), i = (r / W) % H, j = r % W;
REF_PAR_FOR(orows * cout * cin * taps)
for (int64_t r = 0; r < orows; ++r) {
const int64_t t = r / (H2 * W2), i = (r / W2) % H2, j = r % W2;
const int64_t yb = rowoff(y, r, cout), rb = res ? rowoff(res, r, cout) : 0;
for (int64_t o = 0; o < cout; ++o) {
float acc = 0.0f;
for (int64_t dz = 0; dz < kt; ++dz) {
/* The frame tap dz reads: zero pads, the edge frame repeated, or causal (the first
* frame repeated in front, `tpre` more copies of it before those). */
int64_t tz = t + dz - pz;
if (tpad == 1) tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
else if (tpad == 2) tz = std::max<int64_t>(t + dz - (kt - 1) - tpre, 0);
int64_t tz = t * st + dz - ft;
if (tpad) /* replicate and causal-tpre clamp; `zero`/`causal` pad */
tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
if (tz < 0 || tz >= T) continue;
for (int64_t kh = 0; kh < k; ++kh) {
const int64_t iy = i + kh - ps;
int64_t iy = i * sp + kh - pt;
if (reflect) iy = iy < 0 ? -iy : (iy >= H ? 2 * H - 2 - iy : iy);
if (iy < 0 || iy >= H) continue;
for (int64_t kw = 0; kw < k; ++kw) {
const int64_t ix = j + kw - ps;
int64_t ix = j * sp + kw - pl;
if (reflect) ix = ix < 0 ? -ix : (ix >= W ? 2 * W - 2 - ix : ix);
if (ix < 0 || ix >= W) continue;
const int64_t xb = rowoff(x, (tz * H + iy) * W + ix, cin);
const int64_t wb = o * cin * taps + (dz * k + kh) * k + kw;
@@ -614,3 +670,208 @@ int ref_flow_renoise(const RadArgs* a, RadStream) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ cond_aug */
/* A visual condition's rows blended with noise, as ComfyUI's `_cond_video_rows`
* (comfy/ldm/minimax/model.py) does before they become condition rows. Element e = k n + c:
*
* x[k, c] = f32(f32(a x[k, c]) + f32(oma z(e)))
*
* a = `aug` (VISUAL_COND_TIMESTEP, 0.999), oma the f32 of the f64 1 - aug (ComfyUI subtracts in
* double), z(e) = rad_philox_normal_s(seed, stream, e) (abi/rad_philox.h), `seed` the request's
* two u32 words, low first. x is f32 [M, n] at its row pitch. ComfyUI restarts the generator for
* every condition and every forward, so the blend is a fixed function of the request and is
* applied once, per media item. */
int ref_cond_aug(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *seed = &a->t[0], *x = &a->t[1];
const int64_t n = p_int(a, "n", 0), stream = p_int(a, "stream", 0);
const RadParam* ap = p_find(a, "aug");
if (!ap || ap->kind != RAD_P_F64) return RAD_E_SHAPE;
const double aug = ap->dval;
if (n <= 0 || stream < 0 || !(aug >= 0.0 && aug < 1.0) || numel(seed) < 2) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0) return RAD_E_SHAPE;
const float av = (float)aug, omv = (float)(1.0 - aug);
const uint64_t sd = (uint64_t)(uint32_t)ldi(seed, 0) | ((uint64_t)(uint32_t)ldi(seed, 1) << 32);
const int64_t xs = laststride(x);
REF_PAR_FOR(rows * n * 8)
for (int64_t k = 0; k < rows; ++k) {
const int64_t xb = rowoff(x, k, n);
for (int64_t c = 0; c < n; ++c) {
const float z = rad_philox_normal_s(sd, (uint64_t)stream, (uint64_t)(k * n + c));
stt(x, xb + c * xs, av * ldt(x, xb + c * xs) + omv * z);
}
}
return RAD_OK;
}
/* ================================================================== the tiled encoder
* A one-frame media larger than a tile (a reference picture or a keyframe) is encoded as vae.py's
* `tiled_encode` does: the pixel plane is cut into split_tiles_axis' tiles, each goes through the
* encoder alone, and the tiles' moments are blended into one latent plane. These ops are the plan,
* the cut and the blend; the encoder is the per-level ops, issued per tile. Tile starts, extents
* and counts come from `geom`, the request's (clip, H, W) on the device, never from the declared
* parameters. */
/* ------------------------------------------------------------------ vtile_plan */
/* The tiles of one frame of `geom` = (clip, H, W) pixels: split_tiles_axis over each spatial axis
* in latent units (`tile` a side, `overlap` the least blend, `ratio` pixels a latent), numbered
* row-major. Row t of y (i32 [M, 22]):
*
* [0] [1] the tile's first pixel (y0, x0)
* [2] [3] its pixel extent (th, tw): `tile` x ratio, except a lone short tile
* 3 L + 4..6 level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)), L = 0..5: venc_geom's
* level layout for one frame (levels 4 and 5 share a size)
*
* `M` is the band's bound, a ceiling only (band_rows); y must hold the tiles. */
int ref_vtile_plan(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *geom = &a->t[0], *y = &a->t[1];
const int64_t band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0);
if (tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(geom) < 3)
return RAD_E_SHAPE;
const int64_t H = ldi(geom, 1), W = ldi(geom, 2);
std::vector<int64_t> sy, sx, oy, ox;
if (H <= 0 || W <= 0 || H % ratio || W % ratio ||
!split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) ||
!split_tiles_axis(W / ratio, tile, overlap, &sx, &ox))
return RAD_E_SHAPE;
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
const int64_t M = band_rows(nh * nw, band);
if (M <= 0 || rows_of(y, 22) < M) return RAD_E_SHAPE;
REF_PAR_FOR(M)
for (int64_t t = 0; t < M; ++t) {
const int64_t i = t / nw, j = t % nw;
const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio;
const int64_t tw = std::min(tile, W / ratio - sx[(size_t)j]) * ratio;
const int64_t yb = rowoff(y, t, 22), ys = laststride(y);
const int64_t v[22] = { sy[(size_t)i] * ratio, sx[(size_t)j] * ratio, th, tw,
1, th, tw, 1, th / 2, tw / 2, 1, th / 4, tw / 4,
1, th / 8, tw / 8, 1, th / 16, tw / 16, 1, th / 16, tw / 16 };
for (int64_t c = 0; c < 22; ++c) st_int(y->dtype, y->data, yb + c * ys, v[c]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ vtile_crop */
/* One frame's pixel plane cut into vtile_plan's tiles: x f32 [>= H W, 3] is the plane (pixel
* (Y, X) at row Y W + X), geom = (clip, H, W) in pixels; y f32 [M, 3] holds the tiles' pixels
* tile-major, each tile's rows in plane order. The tiles overlap, so y is larger than x and a
* buffer of its own. `M` is a ceiling only (band_rows). */
int ref_vtile_crop(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2];
const int64_t band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0);
if (tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(geom) < 3)
return RAD_E_SHAPE;
const int64_t H = ldi(geom, 1), W = ldi(geom, 2);
std::vector<int64_t> sy, sx, oy, ox;
if (H <= 0 || W <= 0 || H % ratio || W % ratio ||
!split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) ||
!split_tiles_axis(W / ratio, tile, overlap, &sx, &ox))
return RAD_E_SHAPE;
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
std::vector<int64_t> off((size_t)(nh * nw + 1), 0);
for (int64_t i = 0; i < nh; ++i) {
const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio;
for (int64_t j = 0; j < nw; ++j)
off[(size_t)(i * nw + j + 1)] =
off[(size_t)(i * nw + j)] +
th * std::min(tile, W / ratio - sx[(size_t)j]) * ratio;
}
const int64_t M = band_rows(off.back(), band);
if (M <= 0 || rows_of(x, 3) < H * W || rows_of(y, 3) < M) return RAD_E_SHAPE;
REF_PAR_FOR(M * 3)
for (int64_t r = 0; r < M; ++r) {
const int64_t t = (int64_t)(std::upper_bound(off.begin(), off.end(), r) - off.begin()) - 1;
const int64_t i = t / nw, j = t % nw;
const int64_t tw = std::min(tile, W / ratio - sx[(size_t)j]) * ratio;
const int64_t k = r - off[(size_t)t];
const int64_t src = (sy[(size_t)i] * ratio + k / tw) * W + sx[(size_t)j] * ratio + k % tw;
const int64_t xb = rowoff(x, src, 3), yb = rowoff(y, r, 3), xs = laststride(x);
const int64_t ys = laststride(y);
for (int64_t c = 0; c < 3; ++c) stt(y, yb + c * ys, ldt(x, xb + c * xs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ vtile_join */
/* The tiles' moments blended into one latent plane, as vae.py's `tiled_encode` does: x holds the
* tiles' n-channel moments tile-major (vtile_crop's layout at latent extent), geom = (clip, lat_h,
* lat_w) in latents, and y f32 or bf16 [M, n] is the canvas, M = lat_h lat_w. Position (Y, X)
* belongs to the tile (i, j) whose range [start, next start) holds it, at (ly, lx) within it;
* T(i, j, ly, lx) is that tile's value. The neighbours are read unblended and the top blend comes
* before the left one; every product and sum rounds to x's dtype (`rd`), with
* wa(p, e) = rd(1 - rd(p / e)) and wb(p, e) = rd(p / e):
*
* v = T(i, j, ly, lx)
* v = rd(rd(T(i - 1, j, ly + tile - ev) * wa(ly, ev)) + rd(v * wb(ly, ev))) ev = ov_y[i - 1]
* v = rd(rd(T(i, j - 1, lx + tile - eh) * wa(lx, eh)) + rd(v * wb(lx, eh))) eh = ov_x[j - 1]
*
* the first when i > 0 and ly < ev, the second when j > 0 and lx < eh. Only a lone tile is short,
* and it has no neighbour, so a neighbour is always `tile` long on the blended axis. `M` is a
* ceiling only (band_rows). */
int ref_vtile_join(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2];
const int64_t band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
const int64_t overlap = p_int(a, "overlap", 0), n = p_int(a, "n", 0);
if (tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || numel(geom) < 3)
return RAD_E_SHAPE;
const int64_t H = ldi(geom, 1), W = ldi(geom, 2);
std::vector<int64_t> sy, sx, oy, ox;
if (H <= 0 || W <= 0 || !split_tiles_axis(H, tile, overlap, &sy, &oy) ||
!split_tiles_axis(W, tile, overlap, &sx, &ox))
return RAD_E_SHAPE;
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
const int64_t M = band_rows(H * W, band);
std::vector<int64_t> off((size_t)(nh * nw + 1), 0);
for (int64_t i = 0; i < nh; ++i) {
const int64_t th = std::min(tile, H - sy[(size_t)i]);
for (int64_t j = 0; j < nw; ++j)
off[(size_t)(i * nw + j + 1)] =
off[(size_t)(i * nw + j)] + th * std::min(tile, W - sx[(size_t)j]);
}
if (M <= 0 || rows_of(x, n) < off.back() || rows_of(y, n) < M) return RAD_E_SHAPE;
/* The owner tile of every canvas row and column. */
std::vector<int64_t> own_y((size_t)H), own_x((size_t)W);
for (int64_t Y = 0, i = 0; Y < H; ++Y) {
while (i + 1 < nh && Y >= sy[(size_t)(i + 1)]) ++i;
own_y[(size_t)Y] = i;
}
for (int64_t X = 0, j = 0; X < W; ++X) {
while (j + 1 < nw && X >= sx[(size_t)(j + 1)]) ++j;
own_x[(size_t)X] = j;
}
const uint32_t dt = x->dtype;
auto rd = [dt](float v) { return round_dt(dt, v); };
auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); };
auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); };
auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) {
const int64_t row = off[(size_t)(i * nw + j)] + ly * std::min(tile, W - sx[(size_t)j]) + lx;
return ldt(x, rowoff(x, row, n) + c * laststride(x));
};
const int64_t ys = laststride(y);
REF_PAR_FOR(M * n)
for (int64_t r = 0; r < M; ++r) {
const int64_t Y = r / W, X = r % W;
const int64_t i = own_y[(size_t)Y], j = own_x[(size_t)X];
const int64_t ly = Y - sy[(size_t)i], lx = X - sx[(size_t)j];
const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] : 0, eh = j > 0 ? ox[(size_t)(j - 1)] : 0;
const int64_t yb = rowoff(y, r, n);
for (int64_t c = 0; c < n; ++c) {
float v = T(i, j, ly, lx, c);
if (ly < ev)
v = rd(rd(T(i - 1, j, ly + tile - ev, lx, c) * wa(ly, ev)) +
rd(v * wb(ly, ev)));
if (lx < eh)
v = rd(rd(T(i, j - 1, ly, lx + tile - eh, c) * wa(lx, eh)) +
rd(v * wb(lx, eh)));
stt(y, yb + c * ys, v);
}
}
return RAD_OK;
}