radiance 1.13.0

New models:
- Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls
- M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% ->
  92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints
- Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by
  default; Ornith-1.5-122B compose files

Speed:
- Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default):
  the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13%
- Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a
  step at 25-41K context), and the prefill KV split for small launches (a short turn over a long
  context decodes the other sequences 27% faster in that step)
- MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows:
  TranslateGemma +2-5% at 2-8 streams)
- ParoQuant int4/int5 tiled GEMMs 6-9% faster
- Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one
  that ends its requests, and the MTP head's first draft no longer collapses after short chats in
  the prefix cache

Features:
- --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3)
- MiniMax-H3: reference media and keyframe conditioning with the VAE encoders
- Krea 2 rebalance presets balanced, detail and subtle
- The dashboard's request history; a stall watch that reports a frozen step's thread and stack
- rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's
  per-layer embeddings read ahead off the step path
- A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container

Fixes:
- The two-rank all-reduce checks that a peer's push has landed before reducing it
- z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit
- MiniMax-H3's modulation rows

Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is
--weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT,
R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
Deadcode committed 2026-10-27 16:47:35 +01:00
198 files changed
+20904 -3240

No files matched your search

+15 -39
View File
@@ -566,34 +566,14 @@ int ref_kv_store(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ kv_store_streamed */
/* The store of a streamed group: the host mirror is the truth, the device pool is a cache of it.
*
* A streamed group's ring is `slots` blocks deep while the block-id space is `blocks`, and a block
* may be absent from it. This op is `kv_store` with the two copies the group keeps:
*
* host[b] is written ALWAYS, at the block's identity row, whatever the map says;
* kv_cache[res[b]] is written only when `res[b] >= 0`, i.e. the block is resident now.
*
* The residency test belongs in the writer rather than in the resolve, and this is the case that
* decides it: at decode the block this step's tokens land in is the block the last step already
* made resident (a block is `ratio` tokens of one sequence), so a writer that only wrote the
* mirror would leave the ring holding that block's first tokens and every later token missing -
* and the resolve, seeing the block resident, would not copy it. Writing the ring when resident
* and the mirror always means a host block is never stale and a slot never holds a block the
* mirror disagrees with, which is the property the resolve's copy relies on.
*
* The order the caller must keep is store, then resolve, then attention (arch/common/
* rad_block_attn_gated_fp8.h): the block the current step writes may be absent from the ring, and
* the resolve then copies whole blocks out of the mirror, so it must see this step's bytes.
*
* The two planes are the same bytes in the same paged layout
* (`[notional block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot), so one conversion
* writes both: the mirror is described as an E4M3 plane over the same row pitch and the loop
* stores into `host` and, when resident, `kv_cache`.
*
* `res` is read, not written: residency is the resolve's decision (libref/ref_kvstream.cpp). A
* `res` entry outside [-1, slots) for a block this call touches, or a slot naming a block past the
* id space, is a state fault and is refused before anything is written. */
/* 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];
@@ -606,10 +586,8 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
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 (the fp8 QSA family) or bf16 (the default cache dtype). Streaming is dtype-agnostic
* beyond the writer: both planes are byte planes of the same paged layout whose pitch is one
* block, so 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 and is refused. */
/* 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;
@@ -617,8 +595,8 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE;
if (host->rank != 2) return RAD_E_SHAPE;
/* One block of one layer. Both planes are dense rows of it: a padded mirror row would copy a
* block's bytes over its neighbour's, and the two copies must address the same offsets. */
/* 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];
@@ -643,7 +621,7 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
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 the next step's copies plausible and wrong. */
* 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));
@@ -653,8 +631,7 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL;
}
/* The mirror, seen as the plane it holds (E4M3 or bf16): same bytes, same writer, so the two
* copies cannot round differently. */
/* 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);
@@ -666,8 +643,7 @@ int ref_kv_store_streamed(const RadArgs* a, RadStream) {
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 resident block keeps its slot current; a non-resident one is written to the mirror
* alone and the resolve copies the whole block in when it selects it. */
/* 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) {
+36 -23
View File
@@ -51,13 +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). A `stride` s > 1 (causal only, a reach of at least s) keeps
* every s-th output row: the left pad is the reach less s, and a sequence of L rows (every bound a
* whole number of strides) gives L / s, y's and res's rows the input's over s. `cu_div` reads the
* bounds in units that many input rows apart: sequence e is input rows [cu[e] / cu_div,
* cu[e+1] / cu_div), each bound a multiple of cu_div stride. `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];
@@ -65,33 +66,45 @@ 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), cd = p_int(a, "cu_div", 1);
const int64_t st = p_int(a, "stride", 1), pp = p_int(a, "pad", -1), cd = p_int(a, "cu_div", 1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) ||
cd < 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 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). */
for (int64_t e = 0; e <= n_seq; ++e)
* 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) / cd, r1 = cu_at(cu, n_seq) / cd;
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 / st || rows_of(x, cin) < r1)
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 / st) return RAD_E_SHAPE;
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. */
const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2;
REF_PAR_FOR((r1 - r0) / st * cout * cin * k)
for (int64_t r = r0 / st; r < r1 / st; ++r) {
const int64_t e = seq_of(cu, n_seq, r * st * cd);
const int64_t s0 = cu_at(cu, e) / cd, s1 = cu_at(cu, e + 1) / cd;
* 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;
+27
View File
@@ -465,6 +465,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) {
+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
+80 -241
View File
@@ -1,231 +1,81 @@
/* ref_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and
* the ring slots its device pool actually holds (docs/KV-STREAMING.md §3.4 and §4.3, docs/OPS.md
* "Sparse attention (QSA)").
* 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.
*
* ============================== What it sits between ==============================
* `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.
*
* `qsa_select` already dereferences the attention group's block table: it writes
* `sel[q][i] = tb[b]`, the group's POOL PAGE ID (`r4d_qsa_select_bf16.hip:254`, `:686`), and
* `attn_paged` uses each entry as a raw pool page index with no indirection
* (`r4d_attn_decode_h256_gqa6.hip:268`, `:322`; `r4d_attn_paged_gqa8.hip`). When the group's KV
* streams, the device pool is `slots` blocks deep and the block-id space is `blocks`, so a block id
* is no longer an address: `blk * kv_block_stride` would walk out of the layer and silently read
* another layer's bytes. `kv_resolve` turns every selected block id into the ring slot holding it,
* copies the block in from the pinned host mirror when it is not resident, and rewrites `sel` in
* place. Nothing below the rewrite changes: `sel` is the only place the sparse path names KV
* storage, so `attn_paged` reads a resolved table exactly as it reads a fully resident one.
* 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.
*
* `nsel` and `seqused` stay what `qsa_select` wrote them: the attention's length over the table is
* a token count inside the blocks, not an address, so the rewrite leaves both alone.
* 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.
*
* ============================== The operands, exactly ==============================
* 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:
*
* # name role dtype shape what it is
* 0 sel inout i32 [M, sel_pitch] block ids in, ring slots out
* 1 nsel in i32 [M] valid entries of each row
* 2 res inout i32 [blocks] block -> slot, or -1; -2 in flight
* 3 slot_block inout i32 [slots] slot -> block, or -1 free
* 4 slot_state inout i32 [slots, 2] [s,0] epoch of last use, [s,1] heat
* 5 ctl inout i32 [16] the control block (below)
* 6 host in u8 [blocks, block_bytes] the layer's host mirror, identity layout
* 7 kv_cache inout bytes [slots, block_bytes] the layer's ring, as RAD_KV(group, layer)
* [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
*
* Order follows the read order of the algorithm, with the cache last as in `kv_store`. `sel` and
* `nsel` keep `qsa_select`'s positions 5 and 6 relative to each other, so the pair reads the same
* way in both ops.
* 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.
*
* **The miss list is not an operand.** It is a per-call temporary, and a temporary is the row's
* scratch in this codebase (`qsa_select`'s split workspace, docs/OPS.md "qsa_select"): an operand
* would enter the arena planner, the recorded pass's ranges and the tape key for bytes nothing
* outside one launch reads. A device row that needs one declares
* `(next_pow2(slots) + slots) * 4` bytes through `RadKernelInfo::scratch`, laid out
* `int32 miss_block[next_pow2(slots)]` -- the ascending miss list, padded because a launch too wide
* for the kernel's shared claim list sorts it here -- then `int32 miss_slot[slots]`; this reference
* sorts locally and needs none.
* One call:
*
* ============================== The parameters ==============================
* 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.
*
* M query rows to resolve; ranged, since a prefill chunk and a decode step differ
* blocks the group's logical block count (the id space, `res`'s extent)
* slots the ring depth (the device pool's extent, `slot_block`'s extent)
* sel_pitch the selection's row pitch in entries (topk + 1); also the bound `nsel` may not pass
* block_bytes bytes one block of ONE layer occupies: the host mirror's row pitch, the pool's slot
* pitch, and the length of every copy
* Then ctl[0..2] take the epoch, hand and placement, the counters grow (lookups count entries), and
* the maxima are updated.
*
* `block_bytes` rather than `block_size` (the block's token count) because the op moves bytes and
* never reads an element: it is the same code at every cache layout (`fp8`, `fp8_v4`, `k6_v4`,
* `bf16`), and it is the number a vectorised copy has to constrain (a block is a whole number of
* 16-byte lanes). It is deliberately NOT a `block_size` key: `Builder::find_kv_consumer` binds a KV
* group to the first unclaimed op after it that carries `block_size`, and the group's block size
* must keep coming off the resolved attention kernel, not off the op that only copies its pages.
* 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.
*
* `sel_pitch` and `block_bytes` are also pitches the operands carry (`sel.stride[0]`,
* `host.stride[0]`), and this reference requires them to agree: a resolve that read one pitch and
* wrote another would rewrite a row into its neighbour. Stating them in the schema puts them in the
* resolved geometry, where a kernel may constrain them, and in the shape hook, which needs them to
* size `sel` and the two planes.
* 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.
*
* `slots` is the ring depth, and the OPERAND states it, exactly as `sel`'s extent states `M` and
* its row pitch states `sel_pitch`: `slot_block`'s extent is the ring the call may address and the
* parameter is the ceiling the caller declared. Declare cannot know the ring -- the pool is planned
* after the program is built, and a plugin sees only the context bound -- so the declared `slots` is
* the context and a ring the engine sized smaller (--kv-resident) arrives as a shorter
* operand. A call may never address more than the declaration: `slots > slots_declared` is refused.
*
* ============================== The control block ==============================
*
* `ctl` is 16 int32s, the same [0..9] layout the reference design uses
* (`Strata-main/include/strata/kernels/kv_stream.hpp:78`), 8-byte aligned so the counters can be
* read as u64:
*
* [0] epoch the value the last call used (0 in a fresh block, so the first call is 1)
* [1] hand the CLOCK hand, in [0, slots)
* [2] misses blocks placed by the last call
* [3] overflow 1 once a call could not place every miss; latched, never cleared here
* [4..5] u64 misses every block ever placed
* [6..7] u64 lookups every selection entry ever resolved
* [8..9] u64 calls
* [10] maximum union the largest number of DISTINCT blocks one call has selected
* (hits + misses), so a ring's depth can be sized from measurement
* [11] maximum misses the largest number of blocks one call has placed
* [12] maximum claims the largest number of DISTINCT absent blocks one call has claimed: the
* length of the sorted miss list, so it is what a claim-list capacity has
* to hold. One call's claims are bounded by its lookups, `sum_q nsel[q] <=
* M * sel_pitch` (every claim is a selection entry), and the engine's
* worst case is `max_seqs * sel_pitch`; a device kernel sizes its list from
* those operands rather than a constant (libr4d/r4d_kv_resolve.hip), and
* this is the counter that says whether it did.
* [13..15] zero, reserved
*
* `res`, `slot_block` and `slot_state` are state as well, and the caller brings them up: `res` and
* `slot_block` FILLED WITH -1, `slot_state` and `ctl` ZEROED (one `fill` each, or the group's
* bring-up). That is the reset: there is no separate reset op, because a residency map is fixed at
* bring-up and lives as long as the pool does. Entering a call with any `res` entry of -2, a
* `slot_block` outside [-1, blocks), a `res` outside [-1, slots) or a hand outside [0, slots) is a
* state fault and is refused rather than guessed at. The epoch is a wrap-around i32 counter, only
* ever compared for equality; it would take 2^31 calls - over two years of decoding - for a stale
* stamp to read as a fresh one, and `slot_state[s,1]` would still be the sweep's second chance.
*
* `slot_state[s,1]` is a **two-bit heat counter in [0, 3]** inside an i32 (31 bits unused, so the
* policy needs no new field, no extra per-slot memory and no ABI change). It is bumped by one, and
* clamped at 3, on every use of the slot -- a hit or a placement -- once a slot a call, and halved
* when the sweep passes the slot. Zeroed at bring-up and written nowhere else, so a fresh ring
* starts cold and a negative value is not reachable from a legal state; a reader treats it as cold
* rather than letting a fault strand the sweep.
*
* ============================== The semantics, in order ==============================
*
* 1. **epoch bump.** epoch = ctl[0] + 1.
* 2. **one lookup per distinct block.** For row q ascending, then entry i ascending, over
* i in [0, nsel[q]) (entries at or past nsel[q] are `qsa_select`'s -1 padding and are not
* touched): b = sel[q][i].
* res[b] >= 0 -> a hit: slot_state[res[b],0] = epoch and, the first time this call stamps
* that slot, slot_state[res[b],1] = min(old + 1, 3). One bump a SLOT a
* call, not one an entry: a block twenty rows name gains one step of heat,
* the same as one a single row names, so the counter measures the calls
* that wanted the block and not the width of the selection.
* res[b] == -1 -> a miss, claimed once: res[b] = -2 and b appended to the miss list.
* res[b] == -2 -> already claimed by an earlier entry; nothing. This is what makes the pass
* one lookup per block without a second structure: the map is its own set.
* 3. **the miss list is ascending block id.** Not first-appearance order: a block claimed by row 3
* must not evict a different slot from a block claimed by row 0 depending on which thread got
* there first, or two implementations of one contract would place the same blocks in different
* slots and `sel` would differ. Ascending is a fact about the claim set, not about the map, so
* a device implementation orders the claim list itself (a sort of at most `M * sel_pitch` ids);
* nothing here needs a pass over `blocks`, which is the id space and not the call's size.
* 4. **one victim per miss, in that order: identity, a free slot, then a CLOCK (second chance)
* sweep.** For each missed b in ascending order, if `b < slots` and slot b is available --
* `slot_state[b,0] != epoch` and `slot_block[b]` is either -1 or b itself -- the victim is slot
* b, and the hand does not move. This is a placement preference only: it takes a slot only when
* that slot is free, so it can never evict, and leaving the hand alone means a miss it cannot
* place falls through to exactly the walk below, from exactly the hand it would have seen. Two
* things make it worth having: it maps a block's id to its own slot while the context is
* shorter than the ring, and adjacent block ids then sit in adjacent slots of one layer's
* stripe, which is the order the attention's gather reads them in. Otherwise, visit slots from
* the hand, one at a time, wrapping. A FREE slot -- slot_block[s] == -1 -- is taken before any
* resident block is considered: evicting costs a copy on the next call and a free slot costs
* nothing, so the ring fills its empty region first. A slot with slot_state[s,0] == epoch was
* claimed or hit by this call and is passed, free or not, and keeps its heat counter; this is
* the "never take a slot this call itself uses" rule. When a whole turn finds no free slot, the
* same walk is the CLOCK sweep, with the two-bit heat counter in place of the one-bit
* reference:
* - a slot holding a block whose counter is non-zero: halve it (old >> 1) and pass it. A
* saturated 3 survives exactly two passes (3 -> 1 -> 0), a freshly used 1 exactly one,
* and a slot nothing has wanted for two sweeps is the victim on the next visit.
* - otherwise (a block, counter 0): take it.
* The hand still PICKS the victim -- this is a per-visit decision, not a search -- so the
* policy needs no reduction, no barrier and no extra traffic: an add-and-clamp where a
* constant store was, and a shift where a zero was. That is the whole reason it is affordable
* where an exact LRU is not: the epoch-ordered minimum costs a collective reduction per miss.
* The hand advances one slot per visit, so it ends just past the last slot taken. How many
* slots are free is counted before the sweep; a placement into a free slot makes it live and an
* eviction re-points a live one, so the count only falls to zero and a full ring goes straight
* to CLOCK. The free
* scan is side-effect free when it finds nothing -- it halves no counter and leaves the hand
* where it started -- so a full ring's victim is the sweep's alone. A free slot is taken
* without regard to its stale counter. The CLOCK sweep may
* visit at most 3 * slots slots; every write clamps the counter to 3, so two passes halve any
* value to 0 (docs/KV-STREAMING.md §3.4) and the third places the miss.
* 5. **re-point both maps** as each victim is taken: if the slot held block `old`, res[old] = -1;
* slot_block[s] = b, slot_state[s] = {epoch, min(old + 1, 3)}, res[b] = s. A placement is a
* use, so it carries the same bump a hit does; the victim's counter is 0 by construction (the
* sweep only takes a cold slot), so this is 1 in the common case, and the `min` is what keeps
* the two-bit range true for a slot taken by identity or from the free region.
* 6. **copy**: for each placed (b, s), block_bytes from host[b] into the pool's slot s. A copy is
* a byte copy; nothing is converted, so a streamed block is bit-identical to the block the
* writer put in the mirror.
* 7. **rewrite**: for every entry in [0, nsel[q]), sel[q][i] = res[b] when that is >= 0. Entries
* at or past nsel[q] keep their -1.
*
* `ctl[2] = placed`, `ctl[0] = epoch`, `ctl[1] = hand`, and the counters grow by `placed`, the
* number of entries read (one a lookup, as phase 2 defines a lookup: per entry, not per distinct
* block) and one. The three maxima are the sizes this op exists to measure: `ctl[10]` is the
* largest union one call has selected -- the number a ring must hold -- `ctl[11]` the largest number
* of blocks one call has placed, i.e. how much of that union was not already resident, and
* `ctl[12]` the largest number of claims one call has made, which is the depth the miss list had to
* hold.
*
* ============================== Overflow ==============================
*
* The ring must hold every DISTINCT block one call selects: a hit holds a slot and a miss needs
* another, so the condition is `hits + misses <= slots`. What that union is depends on the launch:
* at decode it is at most `max_seqs * (sel_pitch - 1)`, while above `qsa_exact_to` prefill issues a
* row per query and a launch's union can be a chunk's worth of the history, which is why the engine
* measures it (ctl[10]) instead of assuming a bound.
*
* It is not silent when it does: a miss left unplaced by the sweep reverts to `res[b] = -1`, and
* `ctl[3]` is latched to 1 with `ctl[2]` counting only what was placed. The selection rewrite then
* writes SLOT 0 for every entry whose block is not resident -- a safe address inside the ring, not
* the block's slot. The entry cannot be left holding the block id: on device that value is an
* address past the ring which `attn_paged` dereferences without a bounds check, so a step whose
* resolve overflowed would fault or read another layer's bytes. Slot 0 is defined memory holding a
* real block's KV, so the step produces wrong numbers rather than a fault -- and a caller that finds
* `ctl[3]` set must DISCARD the step, which is the only reading that keeps the engine honest: it
* never serves output computed against a table whose entries do not name their blocks.
*
* ============================== Statefulness ==============================
*
* The op keeps state across calls - the epoch, the hand, the heat counters and its counters - so it
* is not concurrent: two of its launches must never overlap, and the engine must not reorder one
* against another. That is the `rad_kernel_concurrent` promise (`abi/rad_abi.h:493`), which is
* given per row; a plugin's row list lives beside it, and libr4d's is the `kStateful[]` prefix
* table inside `rad_kernel_concurrent` (`libr4d/r4d_rows.cpp:8748-8770`, "A new row with
* stream-ordered state belongs in the list above"). Both kernel rows for this op therefore stay
* out of that list. The absence of the promise is always safe: without it the engine orders the
* launch behind everything before it, which is exactly what the map needs.
*
* Being stateful is not the same as being unrecordable. The op is a pure function of
* device-resident state whose addresses and pitches never change after bring-up (the maps, the
* ring and the mirror are fixed-size from the group's declaration), so a recorded pass replays it
* correctly; rewriting contents is fine, changing a pitch would force a re-record (docs/
* KV-STREAMING.md §3.4, core/runtime/ctx.cpp's pass key).
*
* ============================== Why this file is the oracle ==============================
*
* It is the obvious serial form of the contract above: one pass over the entries, one sorted miss
* list, one second-chance walk of the slots, one memcpy per miss, one rewrite. Two device
* implementations compared against it must agree on which slot every block lands in, which is the
* part a fast parallel sweep could get right on hits and wrong on victims.
* 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"
@@ -272,8 +122,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
if (M <= 0) return RAD_E_SHAPE;
if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE;
/* The map and the counts are one format, written by one op and read by the writer and the
* sweep: i32, dense. */
/* 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;
@@ -282,8 +131,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
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 (see "The
* parameters"). */
/* 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;
@@ -291,8 +139,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE;
if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE;
/* One block of one layer: the mirror's row and the pool's slot are the same bytes, and the
* copy length `block_bytes` is both pitches. */
/* 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;
@@ -308,7 +155,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
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, so phase 7 writes values it did not have to re-read ---- */
* 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);
@@ -335,7 +182,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
const int32_t b = (int32_t)ent[e];
const int32_t s = R[b];
if (s >= 0) {
/* One bump a slot a call (see "The semantics", step 2). */
/* 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]);
@@ -352,13 +199,10 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
/* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot
* this call uses ---- */
/* Identity first (see "The semantics", step 4): a missed block whose id fits the ring and whose
* own slot is free takes that slot and leaves the hand alone, so the fallback below runs from
* the hand it would always have run from. A free slot is not a victim (see step 4): the ring's
* empty region fills before any resident block is evicted. The free scan halves no counter
* and does not move the hand when it finds nothing, so a full ring takes the CLOCK victim it
* always took. The count below is what lets a full ring go straight to CLOCK: no placement
* frees a slot and no eviction does either, so a count of zero holds for the rest of the call. */
/* 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;
@@ -406,8 +250,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
R[b] = (int32_t)victim;
++placed;
}
/* A miss the sweep could not place is not resident: undo the claim, so the next call may claim
* it again, and leave its selection entries naming the block (see "Overflow"). */
/* 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 ---- */
@@ -421,15 +264,14 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
/* ---- 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 entry of a miss the sweep could not place names slot 0, not its block id: the id is
* an address outside the ring (see "Overflow"). ctl[3] is what says the table is unusable. */
/* 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 is over DISTINCT blocks, so it is counted from the slots this call stamped (every
* block it hit or placed leaves the call's epoch there) plus the misses it could not place:
* entries repeat, a selection names one block per row and many rows share swaths of history. */
/* 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;
@@ -438,10 +280,7 @@ int ref_kv_resolve(const RadArgs* a, RadStream) {
C[1] = (int32_t)hand;
C[2] = (int32_t)placed;
if (overflow) C[3] = 1;
/* The sizes the counters report: the union this call selected and the part of it that had to
* be copied in.
* A ring sized for the largest union a launch selects is the whole answer to "how large does the
* ring have to be" (docs/KV-STREAMING.md §3.4). */
/* 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();
+12
View File
@@ -88,6 +88,7 @@ int ref_act_mul (const RadArgs*, RadStream);
int ref_mul_weight (const RadArgs*, RadStream);
int ref_seg_mean (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);
@@ -173,6 +174,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);
@@ -184,6 +186,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);
@@ -350,6 +356,7 @@ REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
REF_SHAPE_FN(ref_seg_mean);
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);
@@ -428,6 +435,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);
@@ -438,6 +446,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);
+89 -23
View File
@@ -403,10 +403,8 @@ 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` with the group's two copies: `host` is the authoritative mirror
* (always written) and `res` is the residency map that says whether the block is in the ring. The
* parameters are kv_store's, because the layout and the conversion are the same; `res` is read,
* never written, since residency is `kv_resolve`'s decision. */
/* 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")
@@ -468,12 +466,7 @@ 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, docs/KV-STREAMING.md §3.4). No
* `block_size`: the op moves whole blocks by the byte and never reads an element, and a
* `block_size` key would make it a KV group's consumer, taking the binding away from the resolved
* attention kernel (Builder::find_kv_consumer). `sel_pitch` and `block_bytes` are the selection's
* row pitch and one block of one layer's byte extent. The miss list is the row's scratch, not an
* operand. */
/* 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"),
@@ -791,19 +784,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") };
@@ -864,6 +861,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") };
@@ -890,9 +898,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. */
@@ -907,6 +918,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"),
@@ -957,7 +973,7 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
/* ---- audio generation (ref_audio.cpp) */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal"), P_INTO("stride"),
P_INTO("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") };
@@ -1140,6 +1156,10 @@ static const RadOpSchema kSchemas[] = {
{ "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." },
@@ -1685,7 +1705,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),
@@ -1762,6 +1784,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 "
@@ -1777,6 +1805,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, "
@@ -1795,10 +1837,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, "
@@ -1820,6 +1867,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 "
@@ -1868,7 +1920,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 "
@@ -2155,6 +2209,8 @@ SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's ro
ref_seg_mean),
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",
@@ -2454,6 +2510,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",
@@ -2461,6 +2519,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",
@@ -2482,6 +2546,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,
+122 -25
View File
@@ -559,6 +559,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);
@@ -1455,16 +1465,11 @@ 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. Same geometry as `kv_store`, with the mirror and the residency map beside
* the ring: the mirror is one block a row of the same byte pitch.
*
* The described call touches ONE block, resident in ring slot 0. The draw vocabulary cannot express
* an injective residency map (block -> slot is a permutation, and a draw is a free choice per
* entry), and two blocks drawing one slot would make two tokens write the same ring byte -- a race
* the parallel rerun rightly reports. So the generated case exercises the conversion, the positions
* within a block, the mirror write and the resident ring write; a partly resident map and the
* mirror-only step are built by hand in tests/ref_test.cpp and libavx's hand cases. `M <= block_size`
* keeps every token on its own position of that one block. */
/* 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);
@@ -1674,15 +1679,10 @@ 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 described as block ids, which is what
* `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch.
*
* A described residency map can only be an all-resident one: the description vocabulary draws an
* index in [0, idx_max) or a non-negative constant, and a cold entry is -1 (`res[b] == -1`, an
* absent block), which no draw expresses. So a tool that calls this op cold sees every block
* resident, which exercises the epoch, the rewrite and the bookkeeping but never a miss, an
* eviction or a copy. The service-shaped cases (a partly resident pool, a second chance, an
* eviction, an overflow) are built by hand in tests/ref_test.cpp and in libavx's hand cases. */
/* 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);
@@ -2643,6 +2643,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) {
@@ -2666,6 +2667,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. */
@@ -2680,6 +2682,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);
@@ -2691,10 +2707,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) {
@@ -3022,6 +3039,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);
@@ -3174,6 +3207,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
@@ -3280,23 +3368,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);
const int64_t st = gi(p, n_p, "stride", 1), dil = gi(p, n_p, "dil", 1);
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || st < 1 ||
(st > 1 && (!causal || dil * (k - 1) + 1 < st || M % st)) || gi(p, n_p, "cu_div", 1) != 1)
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);
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 / st, cout }); /* res */
o.t(D, { M / st, 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);
}
+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;
}