radiance 1.9.0

New models:
- LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first
  frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2
  latent upsampler
- Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up
  to ten reference pictures, on one card
- GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze)
- Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81)

Engine:
- --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81)
- the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168)
- eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes)
- the dashboard shows the single-stream decode floor and its most recent window (Memoria)

Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses
namespaces (#119), system messages merged when a template refuses several (#137), a prefill
continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns
read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state.
Plugin ABI 24.
This commit is contained in:
Deadcode committed 2026-10-19 21:58:07 +02:00
1 parent 778cbf315e
commit 685ec5bd85
136 files changed
+18917 -3821

No files matched your search

+150
View File
@@ -353,6 +353,156 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_cross */
/* attn_dense with each entry's keys a run of their own: entry `s`'s queries are rows
* [cu[s], cu[s+1]) of `q` and its keys and values rows [cu_k[s], cu_k[s+1]) of `k` and `v`. With
* `causal` a query sees key j of its run when j <= its own index in its entry, both counted from
* the start: a video's rows reading its prompt (cross attention), or a padded prompt's rows of which
* the padding sees only the prompt. A query that sees no key is zero. */
int ref_attn_cross(const RadArgs* a, RadStream) {
if (!have(a, 6)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *cuk = &a->t[4];
const RadTensor *o = &a->t[5];
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
const int64_t kv_heads = q_heads / gqa;
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0 || numel(cuk) < n_seq + 1) return RAD_E_SHAPE;
const int64_t total_q = numel(q) / (q_heads * head_dim);
const int64_t total_k = numel(k) / (kv_heads * head_dim);
if (total_q <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
for (int64_t s = 0; s < n_seq; ++s)
if (cu_at(cu, s + 1) < cu_at(cu, s) || cu_at(cuk, s + 1) < cu_at(cuk, s) ||
cu_at(cu, s + 1) > total_q || cu_at(cuk, s + 1) > total_k)
return RAD_E_SHAPE;
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
REF_PAR_FOR(total_q * q_heads * head_dim * 64)
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
const int64_t b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1);
const int64_t k0 = cu_at(cuk, s), k1 = cu_at(cuk, s + 1);
for (int64_t i = b0; i < b1; ++i) {
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
const int64_t jend = causal ? std::min<int64_t>(k1, k0 + (i - b0) + 1) : k1;
float mx = -INFINITY;
for (int64_t j = k0; j < jend; ++j) {
const int64_t kb = j * k_rs + kh * k_hs;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
dot *= scale;
if (dot > mx) mx = dot;
}
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float sum = 0.0f;
for (int64_t j = k0; j < jend; ++j) {
const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
const float w = ref_exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
}
return RAD_OK;
}
/* attn_na3d: 3-D neighborhood attention, NATTEN's na3d (LTX-2.5's diffusion decoder). The rows of
* q, k, v and out are the voxels of the volume geom = (T, H, W), i32 on the device, (t, i, j)
* row-major. A query attends the keys of a window `kt` x `kh` x `kw` (each extent at most its
* axis) centred on it and shifted inward at the border: along an axis of L and window n the
* window starts at clamp(c - n / 2, 0, L - n). Per head, in f32: each score the dot over d
* ascending times `scale` (default 1 / sqrt(head_dim)), the window's keys in raster order, the
* softmax as attn_cross takes it (the maximum, then the exponentials' sum), the output rounded to
* its dtype. Rows past T H W are not written. */
int ref_attn_na3d(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *G = &a->t[3], *o = &a->t[4];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t kt = p_int(a, "kt", 0), kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
if (head_dim <= 0 || kt <= 0 || kh <= 0 || kw <= 0 || numel(G) < 3 || q->rank != 2)
return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t heads = q->shape[1] / head_dim;
const int64_t T = cu_at(G, 0), H = cu_at(G, 1), W = cu_at(G, 2);
if (heads <= 0 || q->shape[1] % head_dim || T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
const int64_t N = std::min(q->shape[0], T * H * W);
if (N <= 0 || numel(k) < N * heads * head_dim || numel(v) < N * heads * head_dim ||
numel(o) < N * heads * head_dim)
return RAD_E_SHAPE;
const int64_t nt = std::min(kt, T), nh = std::min(kh, H), nw = std::min(kw, W);
const int64_t q_ds = q->stride[1], q_rs = row_stride(q, heads * head_dim);
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1, k_rs = row_stride(k, heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1, v_rs = row_stride(v, heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1, o_rs = row_stride(o, heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
auto start = [](int64_t c, int64_t n, int64_t L) {
return std::min(std::max<int64_t>(c - n / 2, 0), L - n);
};
REF_PAR_FOR(N * heads * nt * nh * nw * head_dim)
for (int64_t rh = 0; rh < N * heads; ++rh) {
const int64_t r = rh / heads, h = rh % heads;
const int64_t t = r / (H * W), i = (r / W) % H, j = r % W;
const int64_t t0 = start(t, nt, T), i0 = start(i, nh, H), j0 = start(j, nw, W);
const int64_t qb = r * q_rs + h * head_dim * q_ds, ob = r * o_rs + h * head_dim * o_ds;
auto score = [&](int64_t key) {
const int64_t kb = key * k_rs + h * head_dim * k_ds;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
return dot * scale;
};
float mx = -INFINITY;
for (int64_t a1 = t0; a1 < t0 + nt; ++a1)
for (int64_t b1 = i0; b1 < i0 + nh; ++b1)
for (int64_t c1 = j0; c1 < j0 + nw; ++c1) mx = std::max(mx, score((a1 * H + b1) * W + c1));
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float sum = 0.0f;
for (int64_t a1 = t0; a1 < t0 + nt; ++a1)
for (int64_t b1 = i0; b1 < i0 + nh; ++b1)
for (int64_t c1 = j0; c1 < j0 + nw; ++c1) {
const int64_t key = (a1 * H + b1) * W + c1;
const float w = ref_exp(score(key) - mx);
sum += w;
const int64_t vb = key * v_rs + h * head_dim * v_ds;
for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ kv_store */
/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache is INOUT,
* not OUT: only mapped slots are touched and every other slot must survive, which the buffer
+34
View File
@@ -16,6 +16,7 @@
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
@@ -712,6 +713,39 @@ int ref_iota(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ int_affine */
/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the three lists space-separated integers
* of one length: shapes and sequence bounds a model derives from a pass's device geometry (a
* decoder's volume at each of its scales). y holds at least the lists' length. */
static int parse_ints(const char* s, int64_t* v, int cap) {
int n = 0;
while (s && *s) {
char* e = nullptr;
const long long x = std::strtoll(s, &e, 10);
if (e == s) break;
if (n == cap) return -1;
v[n++] = x;
s = e;
}
return n;
}
int ref_int_affine(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
int64_t src[16], mul[16], add[16];
const int n = parse_ints(p_str(a, "src", ""), src, 16);
if (n <= 0 || parse_ints(p_str(a, "mul", ""), mul, 16) != n ||
parse_ints(p_str(a, "add", ""), add, 16) != n || numel(y) < n)
return RAD_E_SHAPE;
for (int j = 0; j < n; ++j) {
if (src[j] >= numel(x)) return RAD_E_SHAPE;
const int64_t v = src[j] < 0 ? 0 : ld_int(x->dtype, x->data, offlin(x, src[j]));
st_int(y->dtype, y->data, offlin(y, j), v * mul[j] + add[j]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ cu_repeat */
/* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's
* lengths live on the device (a window's frames, the latents a vocoder decodes per channel group),
+137 -15
View File
@@ -168,7 +168,7 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
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) {
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(w) < n ||
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || (w && numel(w) < n) ||
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;
@@ -184,10 +184,17 @@ static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor
*
* The sum of squares is f32 in ascending order, read from the stored residual. `s` is
* [n_seq, >= 2n] at its own row pitch, shift = s[e, 0:n] and scale = s[e, n:2n] (a column slice
* of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`. */
* of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`.
*
* `wadd` is added to the gain in f32 (a zero-centred norm's 1 + w), and with `once` the norm and
* its gain round together, n2 = bf16(x rsqrt(...) (w + wadd)), as an f32 RMS norm with a gain
* stores its output (Krea 2's). With `layer` the norm is a LayerNorm (FLUX's, which has no gain:
* `w` absent), and with `none` there is no norm and no gain, n2 = x (LTX-2's text keys and values,
* modulated as they are). */
static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* s,
const RadTensor* w, const RadTensor* x, int64_t r, int64_t e, int64_t n,
float eps, bool gated, uint32_t dt, float* o) {
float eps, bool gated, uint32_t dt, float* o, float wadd = 0.0f,
bool once = false, bool layer = false, bool none = false) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
if (gated) {
const int64_t g_rs = row_stride(g, n), g_cs = laststride(g);
@@ -197,13 +204,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor*
stt(x, xb + i * xs, ldt(x, xb + i * xs) + p);
}
}
/* RMS: x rsqrt(mean(x^2) + eps). Layer: (x - mean) rsqrt(var + eps), the biased variance of
* the centred values; both sums f32 in ascending order. */
float mu = 0.0f;
if (layer) {
for (int64_t i = 0; i < n; ++i) mu += ldt(x, xb + i * xs);
mu /= (float)n;
}
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { const float v = ldt(x, xb + i * xs); ss += v * v; }
for (int64_t i = 0; i < n && !none; ++i) { const float v = ldt(x, xb + i * xs) - mu; ss += v * v; }
const float rs = 1.0f / std::sqrt(ss / (float)n + eps);
const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = laststride(w);
const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = w ? laststride(w) : 0;
for (int64_t i = 0; i < n; ++i) {
const float n1 = round_dt(dt, ldt(x, xb + i * xs) * rs);
const float n2 = round_dt(dt, n1 * ldt(w, i * ws));
const float v = ldt(x, xb + i * xs) - mu;
/* With no gain the norm is rounded once, as a norm without a weight stores it. */
const float n2 = none ? round_dt(dt, v)
: !w ? round_dt(dt, v * rs)
: once ? round_dt(dt, v * rs * (ldt(w, i * ws) + wadd))
: round_dt(dt, round_dt(dt, v * rs) * (ldt(w, i * ws) + wadd));
const float sc = round_dt(dt, 1.0f + ldt(s, e * s_rs + (n + i) * s_cs));
const float m = round_dt(dt, n2 * sc);
o[i] = round_dt(dt, m + ldt(s, e * s_rs + i * s_cs));
@@ -215,18 +233,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor*
* the norm chain rounds to z's dtype. */
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 = &a->t[3];
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 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);
const float wadd = p_f32(a, "wadd", 0.0f);
const bool once = p_int(a, "norm_once", 0) != 0;
const char* nk = p_str(a, "norm", "rms");
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
if (!layer && !none && std::strcmp(nk, "rms") != 0) return RAD_E_INVAL;
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));
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());
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);
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]);
}
@@ -238,11 +262,17 @@ int ref_rms_mod(const RadArgs* a, RadStream) {
* bound. */
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 = &a->t[3];
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 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);
const float wadd = p_f32(a, "wadd", 0.0f);
const bool once = p_int(a, "norm_once", 0) != 0;
const char* nk = p_str(a, "norm", "rms");
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
if (!layer && !none && std::strcmp(nk, "rms") != 0) return RAD_E_INVAL;
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));
@@ -250,7 +280,7 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) {
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());
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);
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);
@@ -283,7 +313,8 @@ int ref_timestep_embed(const RadArgs* a, RadStream) {
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 tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv;
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);
for (int64_t i = 0; i < h; ++i) {
const float f = ref_exp(coef * (float)i / (float)h);
@@ -545,6 +576,8 @@ int ref_chan_affine(const RadArgs* a, RadStream) {
* pad same k / 2 zeros on every side
* pad down no zeros above and left, one below and right: ZeroPad2d((0, 1, 0, 1)) then the conv,
* as a stride-2 downsample does
* pad causal k - 1 zeros above, none below, k / 2 a side across: a convolution causal along
* the rows (LTX-2's audio VAE, whose rows are time)
*
* f32 accumulation over (kh, kw, cin), the bias added, one rounding. */
int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
@@ -554,14 +587,16 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1);
const char* pad = p_str(a, "pad", "same");
const bool down = pad && !std::strcmp(pad, "down");
const bool causal = pad && !std::strcmp(pad, "causal");
if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE;
if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE;
const int64_t Hin = x->shape[0], Win = x->shape[1] / cin;
const int64_t Ho = y->shape[0], Wo = y->shape[1] / cout;
if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE;
const int64_t Hv = Hin * up, Wv = Win * up;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
return RAD_E_SHAPE;
if (numel(w) < cout * cin * k * k || numel(b) < cout) return RAD_E_SHAPE;
const int64_t xr = x->stride[0], yr = y->stride[0];
@@ -574,7 +609,7 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
const int64_t iy = oy * stride + kh - pt;
if (iy < 0 || iy >= Hv) continue;
for (int64_t kw = 0; kw < k; ++kw) {
const int64_t ix = ox * stride + kw - pt;
const int64_t ix = ox * stride + kw - pl;
if (ix < 0 || ix >= Wv) continue;
const int64_t xb = (iy / up) * xr + (ix / up) * cin;
for (int64_t ci = 0; ci < cin; ++ci)
@@ -895,3 +930,90 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ table_add */
/* y[r, l n + c] = x[r, c] + t[l, c] for every row of `x` and every row l of the table: a shared
* modulation plus each block's own learned table (Krea 2's, LTX-2's), all blocks in one pass. The
* sum is f32, rounded once to y's dtype. `x` and `y` are read at their own row pitches. */
int ref_table_add(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *T = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", 0), L = p_int(a, "L", 0);
if (n <= 0 || L <= 0 || numel(T) < L * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, L * n);
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
const int64_t xs = laststride(X), ys = laststride(Y), ts = laststride(T);
REF_PAR_FOR(rows * L * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, L * n);
for (int64_t l = 0; l < L; ++l)
for (int64_t c = 0; c < n; ++c)
stt(Y, yb + (l * n + c) * ys,
ldt(X, xb + c * xs) + ldt(T, (l * n + c) * ts));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ mix_rows */
/* y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows (Krea 2's
* text fusion folds twelve tapped layers of a token into one row). f32 sum in ascending i, rounded
* once to y's dtype. */
int ref_mix_rows(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
if (n <= 0 || k <= 0 || numel(W) < k) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || rows_of(X, n) < rows * k) return RAD_E_SHAPE;
const int64_t xs = laststride(X), ys = laststride(Y), ws = laststride(W);
REF_PAR_FOR(rows * n * k)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(Y, r, n);
for (int64_t c = 0; c < n; ++c) {
float acc = 0.0f;
for (int64_t i = 0; i < k; ++i)
acc += ldt(W, i * ws) * ldt(X, rowoff(X, r * k + i, n) + c * xs);
stt(Y, yb + c * ys, acc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ chan_stats */
/* A latent normalised or denormalised by per-channel statistics a VAE keeps as weights: `mean` and
* `s` [n], `s` a standard deviation, or with `var` 1 a variance (std = sqrt(s + eps), a BatchNorm's
* running statistics). Each statistic is rounded to y's dtype as the reference casts it, and
* every step is a tensor the reference stores: `denorm` y = rd(rd(x std) + mean), `norm`
* y = rd(rd(x - mean) / std). */
int ref_chan_stats(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Mn = &a->t[1], *Sd = &a->t[2], *Y = &a->t[3];
const int64_t n = p_int(a, "n", 0);
const bool var = p_int(a, "var", 0) != 0;
const float eps = p_f32(a, "eps", 0.0f);
const char* mode = p_str(a, "mode", "denorm");
const bool norm = std::strcmp(mode, "norm") == 0;
if (!norm && std::strcmp(mode, "denorm") != 0) return RAD_E_INVAL;
if (n <= 0 || numel(Mn) < n || numel(Sd) < n) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
const uint32_t dt = Y->dtype;
std::vector<float> mu((size_t)n), sd((size_t)n);
for (int64_t c = 0; c < n; ++c) {
mu[(size_t)c] = round_dt(dt, ldt(Mn, c * laststride(Mn)));
const float v = ldt(Sd, c * laststride(Sd));
sd[(size_t)c] = round_dt(dt, var ? std::sqrt(v + eps) : v);
}
const int64_t xs = laststride(X), ys = laststride(Y);
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
for (int64_t c = 0; c < n; ++c) {
const float x = ldt(X, xb + c * xs);
const float y = norm ? round_dt(dt, round_dt(dt, x - mu[(size_t)c]) / sd[(size_t)c])
: round_dt(dt, round_dt(dt, x * sd[(size_t)c]) + mu[(size_t)c]);
stt(Y, yb + c * ys, y);
}
}
return RAD_OK;
}
+722
View File
@@ -0,0 +1,722 @@
/* ref_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the
* per-head attention gate, and the sampler step that combines a step's guidance passes in the
* clean-estimate space.
*
* Every rounding follows the upstream model, which runs its transformer in bf16 and its rotary,
* guidance and sampler in f32 (diffusers' transformer_ltx2.py and pipeline_ltx2.py).
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace ref;
namespace {
inline int64_t ldi(const RadTensor* t, int64_t i) { return ld_int(t->dtype, t->data, offlin(t, i)); }
/* torch.linspace(0, 1, steps) in f64: the first half up from the start, the second down from the
* end, as torch computes it. */
double linspace01(int64_t i, int64_t steps) {
if (steps <= 1) return 0.0;
const double step = 1.0 / (double)(steps - 1);
return i < steps / 2 ? step * (double)i : 1.0 - step * (double)(steps - 1 - i);
}
int parse_list_f32(const char* s, std::vector<float>* out) {
out->clear();
while (s && *s) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s) break;
out->push_back((float)v);
s = end;
}
return (int)out->size();
}
/* Element (d, r) of a [C, M] operand at its own strides; an integer operand reads as its value. */
float pos_at(const RadTensor* p, int64_t d, int64_t r) {
const int64_t off = p->rank >= 2 ? d * p->stride[0] + r * p->stride[1] : r * laststride(p);
return ldt(p, off);
}
} /* namespace */
/* ------------------------------------------------------------------ rope_split */
/* LTX-2's rotary (LTX2AudioVideoRotaryPosEmbed, "split"): over the full width `dim` of all heads,
* P = dim / 2 pairs, the first `pad` = P - steps n_dims of them unrotated and the rest the
* frequency ladder freq[k] = f32(theta^linspace(0, 1, steps)[k] pi / 2) (f64 before the cast),
* steps = P / n_dims, its pairs interleaving the coordinates: pair pad + k n_dims + d turns by
* coordinate d at freq[k]. A coordinate c becomes the angle a = f32(f32(2 f32(c / max[d])) - 1)
* freq[k]. Head h owns pairs [h hd/2, (h+1) hd/2) and rotates its halves against each other,
*
* o1 = f32(f32(x1 cos a) - f32(x2 sin a)) o2 = f32(f32(x2 cos a) + f32(x1 sin a))
*
* rounded to x's dtype. `head0` is the first head this operand holds (a rank's share). `x` is
* [M, >= n_head head_dim] at its own row pitch; `positions` [n_dims, M], f32 or integer, at its own
* strides. */
int ref_rope_split(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *P = &a->t[1];
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
const int64_t dim = p_int(a, "dim", 0), nd = p_int(a, "n_dims", 0), h0 = p_int(a, "head0", 0);
const double theta = (double)p_f32(a, "theta", 10000.0f);
std::vector<float> mx;
if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd ||
parse_list_f32(p_str(a, "max", ""), &mx) != (int)nd)
return RAD_E_SHAPE;
const int64_t P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd, half = hd / 2;
const int64_t rows = rows_of(X, nh * hd);
if (rows <= 0 || P->rank < 1) return RAD_E_SHAPE;
std::vector<float> freq((size_t)steps);
for (int64_t k = 0; k < steps; ++k)
freq[(size_t)k] = (float)(std::pow(theta, linspace01(k, steps)) * M_PI / 2.0);
const int64_t xs = laststride(X);
REF_PAR_FOR(rows * nh * hd)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, nh * hd);
for (int64_t h = 0; h < nh; ++h)
for (int64_t i = 0; i < half; ++i) {
const int64_t p = (h0 + h) * half + i;
if (p < pad) continue; /* cos 1, sin 0: the value as it is */
const int64_t j = p - pad, d = j % nd, k = j / nd;
const float g = pos_at(P, d, r) / mx[(size_t)d];
const float ang = (2.0f * g - 1.0f) * freq[(size_t)k];
const float c = (float)std::cos((double)ang), s = (float)std::sin((double)ang);
const int64_t o1 = xb + (h * hd + i) * xs, o2 = xb + (h * hd + half + i) * xs;
const float x1 = ldt(X, o1), x2 = ldt(X, o2);
const float a1 = x1 * c, b1 = x2 * s, a2 = x2 * c, b2 = x1 * s;
stt(X, o1, a1 - b1);
stt(X, o2, a2 + b2);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ head_gate */
/* LTX-2's gated attention: each head's output times 2 sigmoid of its logit,
* x = rd(x rd(2 rd(sigmoid(g)))) (the sigmoid of the bf16 logit rounded, doubled exactly). `g` is
* [M, >= n_head], `x` [M, >= n_head head_dim], each at its own row pitch. */
int ref_head_gate(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *G = &a->t[0], *X = &a->t[1];
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
if (nh <= 0 || hd <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(X, nh * hd);
if (rows <= 0 || rows_of(G, nh) < rows) return RAD_E_SHAPE;
const int64_t xs = laststride(X), gs = laststride(G);
REF_PAR_FOR(rows * nh * hd)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, nh * hd), gb = rowoff(G, r, nh);
for (int64_t h = 0; h < nh; ++h) {
const float lg = ldt(G, gb + h * gs);
const float sg = round_dt(G->dtype, 1.0f / (1.0f + std::exp(-lg)));
const float gate = round_dt(X->dtype, 2.0f * sg);
for (int64_t i = 0; i < hd; ++i) {
const int64_t o = xb + (h * hd + i) * xs;
stt(X, o, ldt(X, o) * gate);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ ltx_guide */
/* One LTX-2 sampler step over a modality's latent `x` (f32 [M, n]) from its guidance passes'
* velocities (each [M, n] at its own pitch, read as f32 as the pipeline upcasts them):
*
* x0_p = f32(x - f32(v_p sigma)) for every pass p
* g = x0_c [+ f32(f32(gs - 1) f32(x0_c - x0_u))] [+ f32(stg f32(x0_c - x0_s))]
* [+ f32(f32(ms - 1) f32(x0_c - x0_m))] left to right, f32
* with rescale r > 0: g = f32(f32(r f32(g f32(std(x0_c) / std(g)))) + f32(f32(1 - r) g))
* v = f32(f32(x - g) / sigma) x = f32(x + f32(f32(sigma_next - sigma) v))
*
* A bracketed term is taken when its pass is bound and its coefficient is not zero (gs, ms 1;
* stg 0). std is the unbiased deviation over all M n values, accumulated in f64. `scales` is f32
* [4] (gs, stg, ms, r) and `sched` f32 [2] (sigma, sigma_next), both read on the device; `stats` is
* the implementation's scratch (libref leaves it untouched). */
int ref_ltx_guide(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *Vc = &a->t[0], *Vu = t_in(a, 1), *Vs = t_in(a, 2), *Vm = t_in(a, 3);
const RadTensor *Sc = &a->t[4], *Sh = &a->t[5], *X = &a->t[7];
const int64_t n = p_int(a, "n", 0);
if (n <= 0 || numel(Sc) < 4 || numel(Sh) < 2) return RAD_E_SHAPE;
const int64_t rows = rows_of(X, n);
if (rows <= 0 || rows_of(Vc, n) < rows || (Vu && rows_of(Vu, n) < rows) ||
(Vs && rows_of(Vs, n) < rows) || (Vm && rows_of(Vm, n) < rows))
return RAD_E_SHAPE;
const float gs = ldt(Sc, 0), stg = ldt(Sc, laststride(Sc)), ms = ldt(Sc, 2 * laststride(Sc));
const float rr = ldt(Sc, 3 * laststride(Sc));
const float sig = ldt(Sh, 0), sig_n = ldt(Sh, laststride(Sh));
const bool use_u = Vu && gs != 1.0f, use_s = Vs && stg != 0.0f, use_m = Vm && ms != 1.0f;
const float cu = gs - 1.0f, cm = ms - 1.0f;
const int64_t N = rows * n;
std::vector<float> x0c((size_t)N), g((size_t)N);
auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) {
return x - ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig;
};
REF_PAR_FOR(N)
for (int64_t r = 0; r < rows; ++r)
for (int64_t c = 0; c < n; ++c) {
const float x = ldt(X, rowoff(X, r, n) + c * laststride(X));
const float xc = x0(Vc, r, c, x);
float v = xc;
if (use_u) v = v + cu * (xc - x0(Vu, r, c, x));
if (use_s) v = v + stg * (xc - x0(Vs, r, c, x));
if (use_m) v = v + cm * (xc - x0(Vm, r, c, x));
x0c[(size_t)(r * n + c)] = xc;
g[(size_t)(r * n + c)] = v;
}
float fac = 1.0f, keep = 1.0f;
if (rr > 0.0f) {
auto stdev = [&](const std::vector<float>& v) {
double m = 0.0;
for (float e : v) m += e;
m /= (double)N;
double ss = 0.0;
for (float e : v) ss += ((double)e - m) * ((double)e - m);
return (float)std::sqrt(ss / (double)(N > 1 ? N - 1 : 1));
};
fac = stdev(x0c) / stdev(g);
keep = (float)(1.0 - (double)rr);
}
const float dt = sig_n - sig;
REF_PAR_FOR(N)
for (int64_t r = 0; r < rows; ++r)
for (int64_t c = 0; c < n; ++c) {
float v = g[(size_t)(r * n + c)];
if (rr > 0.0f) v = rr * (v * fac) + keep * v;
const int64_t o = rowoff(X, r, n) + c * laststride(X);
const float x = ldt(X, o);
const float vel = (x - v) / sig;
stt(X, o, x + dt * vel);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pixel_norm */
/* An RMS norm over each row's n values as a model computes it in bf16 tensors, every step stored:
*
* m = rd(sum_i rd(x_i^2) / n) (f32 sum in ascending i)
* rsqrt form: z_i = rd(x_i rd(1 / sqrt(rd(m + eps))))
* div form: z_i = rd(x_i / rd(sqrt(rd(m + eps))))
*
* then with `act` silu z = rd(z / (1 + exp(-z))), and with `mult` z = rd(z mult) (the text
* connectors' scale to the DiT's width). rd is y's dtype. LTX-2's VAE PerChannelRMSNorm
* and audio PixelNorm are the div form; its text connectors' per-layer norm the rsqrt form, whose
* output `ileave` interleaves: row r = t L + l of x (L = ileave) goes to columns c L + l of y's row
* t, the layer index innermost as the reference flattens [C, L]. */
int ref_pixel_norm(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), L = p_int(a, "ileave", 1);
const float eps = p_f32(a, "eps", 1e-6f), mult = p_f32(a, "mult", 1.0f);
static const char* const kForms[] = { "rsqrt", "div" };
static const char* const kActs[] = { "none", "silu" };
const int form = p_enum(a, "form", kForms, 2, 0), act = p_enum(a, "act", kActs, 2, 0);
if (form < 0 || act < 0 || n <= 0 || L <= 0) return RAD_E_INVAL;
const int64_t rows = rows_of(Y, n * L) * L;
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
const uint32_t dt = Y->dtype;
const int64_t xs = laststride(X), ys = laststride(Y);
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r / L, n * L), l = r % L;
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(X, xb + i * xs);
ss += round_dt(dt, v * v);
}
const float v = round_dt(dt, round_dt(dt, ss / (float)n) + eps);
const float s = form == 0 ? round_dt(dt, 1.0f / std::sqrt(v)) : round_dt(dt, std::sqrt(v));
for (int64_t i = 0; i < n; ++i) {
const float x = ldt(X, xb + i * xs);
float z = round_dt(dt, form == 0 ? x * s : x / s);
if (act == 1) z = round_dt(dt, z / (1.0f + std::exp(-z)));
if (mult != 1.0f) z = round_dt(dt, z * mult);
stt(Y, yb + (i * L + l) * ys, z);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ d2s3d / s2d3d */
/* LTX-2's video VAE resampling over voxel rows (row (t, i, j) of a T x H x W volume, channels
* innermost); `geom` is x's volume, i32 on the device. The packed channel of (c, a, b, d) is
* ((c st + a) sh + b) sw + d, a the frame offset, b the row's, d the column's.
*
* d2s3d, the upsampler's depth to space: y[(t st + a - drop, i sh + b, j sw + d), c] = x[(t, i,
* j), packed(c, a, b, d)], the first `drop` frames dropped (default st - 1, the causal mapping;
* T st - drop out). A copy. */
int ref_d2s3d(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
const int64_t sw = p_int(a, "sw", 1), drop = p_int(a, "drop", st - 1);
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || numel(G) < 3)
return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), P = st * sh * sw;
const int64_t To = T * st - drop, Ho = H * sh, Wo = W * sw;
if (T <= 0 || H <= 0 || W <= 0 || rows_of(X, C * P) < T * H * W ||
rows_of(Y, C) < To * Ho * Wo)
return RAD_E_SHAPE;
const int64_t xs = laststride(X), ys = laststride(Y);
REF_PAR_FOR(To * Ho * Wo * C)
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
const int64_t tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo;
const int64_t t = tt / st, aa = tt % st, i = ii / sh, b = ii % sh, j = jj / sw, d = jj % sw;
const int64_t xb = rowoff(X, (t * H + i) * W + j, C * P), yb = rowoff(Y, r, C);
for (int64_t c = 0; c < C; ++c)
stt(Y, yb + c * ys, ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs));
}
return RAD_OK;
}
/* s2d3d, the downsampler's space to depth: the volume with `tpre` frames prepended (frames 0 ..
* tpre - 1 again, the reference's hs[:, :, :st-1]) cut into st x sh x sw boxes, each box's values
* a packed row. `mode` copy writes the packed row (C st sh sw channels); `mean` averages each run
* of `group` consecutive packed channels (f32 sum, divided, rounded once; the residual's mean).
* With `add` 1 the result is added into y, y = rd(y + v). */
int ref_s2d3d(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
const int64_t sw = p_int(a, "sw", 1), tpre = p_int(a, "tpre", 0), grp = p_int(a, "group", 1);
const bool add = p_int(a, "add", 0) != 0;
static const char* const kModes[] = { "copy", "mean" };
const int mode = p_enum(a, "mode", kModes, 2, 0);
if (mode < 0) return RAD_E_INVAL;
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || numel(G) < 3)
return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), P = C * st * sh * sw;
const int64_t Tv = T + tpre;
if (T <= 0 || Tv % st || H % sh || W % sw || (mode == 1 && P % grp)) return RAD_E_SHAPE;
const int64_t To = Tv / st, Ho = H / sh, Wo = W / sw, Co = mode == 1 ? P / grp : P;
if (rows_of(X, C) < T * H * W || rows_of(Y, Co) < To * Ho * Wo) return RAD_E_SHAPE;
const int64_t xs = laststride(X), ys = laststride(Y);
const uint32_t dt = Y->dtype;
REF_PAR_FOR(To * Ho * Wo * P)
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
const int64_t t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo;
const int64_t yb = rowoff(Y, r, Co);
auto val = [&](int64_t q) { /* packed channel q of this box */
const int64_t d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st;
const int64_t c = q / (sw * sh * st);
const int64_t v = t * st + aa, tr = v < tpre ? v : v - tpre;
return ldt(X, rowoff(X, (tr * H + i * sh + b) * W + j * sw + d, C) + c * xs);
};
for (int64_t o = 0; o < Co; ++o) {
float v;
if (mode == 0) {
v = val(o);
} else {
float s = 0.0f;
for (int64_t q = o * grp; q < (o + 1) * grp; ++q) s += val(q);
v = round_dt(dt, s / (float)grp);
}
const int64_t oy = yb + o * ys;
stt(Y, oy, add ? round_dt(dt, ldt(Y, oy)) + round_dt(dt, v) : v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
/* LTX-2's patchifier, both ways, over dense 2-D operands whose shapes give the sizes. A patch of
* p x p pixels of C channels is one row of C p p values, channel c's offset (ph, pw) at
* c p p + pw p + ph with `order` wh (LTX-2's: the column offset outer) or c p p + ph p + pw with
* hw.
*
* pix_patch: an image x [H, W C] to patch rows y [H / p, (W / p) C p p]. A copy. */
static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) {
return c * p * p + (wh ? pw * p + ph : ph * p + pw);
}
int ref_pix_patch(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || X->shape[1] % C) return RAD_E_SHAPE;
const int64_t H = X->shape[0], W = X->shape[1] / C;
if (H <= 0 || W <= 0 || H % p || W % p || Y->shape[0] != H / p ||
Y->shape[1] != (W / p) * C * p * p)
return RAD_E_SHAPE;
const int64_t xr = X->stride[0], yr = Y->stride[0];
REF_PAR_FOR(H * W * C)
for (int64_t y = 0; y < H; ++y)
for (int64_t x = 0; x < W; ++x)
for (int64_t c = 0; c < C; ++c)
stt(Y, (y / p) * yr + (x / p) * C * p * p + patch_col(c, y % p, x % p, p, wh),
ldt(X, y * xr + x * C + c));
return RAD_OK;
}
/* patch_pix8: patch rows x [R, w C p p] (R a frame's patch rows times its frames) to RGB bytes
* y [R p, w p C], each byte round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)) with rd
* x's dtype, to_rgba8's rule. */
int ref_patch_pix8(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
X->shape[1] % (C * p * p))
return RAD_E_SHAPE;
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
const int64_t xr = X->stride[0], yr = Y->stride[0];
const uint32_t dt = X->dtype;
uint8_t* yb = (uint8_t*)Y->data;
REF_PAR_FOR(R * p * w * p * C)
for (int64_t y = 0; y < R * p; ++y)
for (int64_t x = 0; x < w * p; ++x)
for (int64_t c = 0; c < C; ++c) {
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
patch_col(c, y % p, x % p, p, wh));
const float cl = std::min(std::max(v, -1.0f), 1.0f);
float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f);
u = std::min(std::max(u, 0.0f), 1.0f);
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ vol_index */
/* A volume's voxel coordinates, the rotary positions of attention over it: geom = (T, H, W), i32
* on the device; y i32 [3, n] component-major (at its own row pitch), voxel m = (t H + i) W + j's
* (t, i, j) at column m, for m < min(n, T H W). */
int ref_vol_index(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *G = &a->t[0], *Y = &a->t[1];
if (numel(G) < 3 || Y->rank != 2 || Y->shape[0] != 3) return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), n = Y->shape[1];
if (T <= 0 || H <= 0 || W <= 0 || n <= 0) return RAD_E_SHAPE;
const int64_t m1 = std::min(n, T * H * W);
for (int64_t m = 0; m < m1; ++m) {
const int64_t v[3] = { m / (H * W), (m / W) % H, m % W };
for (int64_t c = 0; c < 3; ++c)
st_int(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */
/* A decoder run in tiles, as diffusers cuts and blends them: LTX-2's VAE (`tiled_decode`, rule
* `stride`) and LTX-2.5's diffusion decoder (`_tile_intervals`, rule `intervals`). Along an axis
* of L cells a tile starts at every multiple of `stride` below L; under `intervals` one tile covers
* an axis of `tile` or fewer cells, and while more than one start is left and the last leaves fewer
* than `min` cells, that start is dropped. A tile but the last is min(tile, L - start) long; the
* last runs to L. Tiles are raster-ordered over (time band, row band, column band); without
* `tile_t` there is one time band of every frame.
*
* tile_grid: the boxes of the grid geom = (T, H, W), i32 on the device, into y i32 [M, 8], row k
* (t, h, w, t0, y0, x0, k, count); the last time band is `tail` cells longer than its cut (frames
* past T a decoder carries, which its crop takes and its output drops). Rows past the count are
* zero, tiles past M not written. A row's (t, h, w) is a decoder's volume operand and its first six
* entries tile_crop's box. */
struct TileCut {
int64_t tile = 1, stride = 1, min = 1;
bool intervals = false;
int64_t count(int64_t L) const {
if (intervals && L <= tile) return 1;
int64_t n = (L + stride - 1) / stride;
while (intervals && n > 1 && L - (n - 1) * stride < min) --n;
return n;
}
int64_t len(int64_t L, int64_t k) const {
return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride);
}
};
static bool tile_cuts(const RadArgs* a, TileCut* s, TileCut* t) {
static const char* const kRules[] = { "stride", "intervals" };
const int rule = p_enum(a, "rule", kRules, 2, 0);
s->tile = p_int(a, "tile", 0);
s->stride = p_int(a, "stride", 0);
s->min = p_int(a, "min", 1);
s->intervals = rule == 1;
t->tile = p_int(a, "tile_t", 1 << 30);
t->stride = p_int(a, "stride_t", 1 << 30);
t->min = p_int(a, "min_t", 1);
t->intervals = rule == 1;
return rule >= 0 && s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->min > 0 &&
t->tile > 0 && t->stride > 0 && t->stride <= t->tile && t->min > 0;
}
int ref_tile_grid(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *G = &a->t[0], *Y = &a->t[1];
TileCut cs, ct;
const int64_t n = numel(Y) / 8, tail = p_int(a, "tail", 0);
if (!tile_cuts(a, &cs, &ct) || tail < 0 || n <= 0 || numel(G) < 3) return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2);
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
const int64_t nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj;
for (int64_t k = 0; k < n; ++k) {
int64_t row[8] = {};
if (k < count) {
const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj;
const int64_t v[8] = { ct.len(T, kt) + (kt == nt - 1 ? tail : 0), cs.len(H, i),
cs.len(W, j), kt * ct.stride, i * cs.stride, j * cs.stride, k,
count };
std::memcpy(row, v, sizeof row);
}
for (int64_t e = 0; e < 8; ++e) st_int(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]);
}
return RAD_OK;
}
/* tile_crop: one tile's voxels out of a volume. x [>= T H W, C] is the volume (row (t, yy, xx)
* row-major), geom its (T, H, W); box = (t, h, w, t0, y0, x0), i32 on the device (a tile_grid
* row); y [t h w, C], y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)]. A copy. */
int ref_tile_crop(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *G = &a->t[1], *B = &a->t[2], *Y = &a->t[3];
const int64_t C = p_int(a, "C", 0);
if (C <= 0 || numel(G) < 3 || numel(B) < 6) return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2);
const int64_t t = ldi(B, 0), h = ldi(B, 1), w = ldi(B, 2);
const int64_t t0 = ldi(B, 3), y0 = ldi(B, 4), x0 = ldi(B, 5);
if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H ||
x0 + w > W || rows_of(X, C) < T * H * W || rows_of(Y, C) < t * h * w)
return RAD_E_SHAPE;
const int64_t xs = laststride(X), ys = laststride(Y);
REF_PAR_FOR(t * h * w * C)
for (int64_t r = 0; r < t * h * w; ++r) {
const int64_t f = r / (h * w), i = (r / w) % h, j = r % w;
const int64_t xb = rowoff(X, ((t0 + f) * H + y0 + i) * W + x0 + j, C), yb = rowoff(Y, r, C);
for (int64_t c = 0; c < C; ++c) stt(Y, yb + c * ys, ldt(X, xb + c * xs));
}
return RAD_OK;
}
/* tile_stitch: decoded tiles to RGB bytes. geom = (T, H, W) is the grid the tiles cut (tail cells
* excluded); a cell is `scale` patches of p x p pixels a side and `scale_t` frames, the first cell
* of the video one frame (the causal mapping: T cells are scale_t T - scale_t + 1 frames). x is
* every tile's decoder output in tile order, back to back: tile (kt, i, j) with cells [t0, t1) in
* time is F = scale_t (t1 - t0), less scale_t - 1 when t0 is 0, frames of (h scale) x (w scale)
* rows of patches (pix_patch's columns, C p p a row). `first` is the first frame y holds, i32 [1].
*
* A pixel (Y, X) of frame n is time band kt's whose kept frames hold n (a band but the last keeps
* stride_t scale_t frames, the first scale_t - 1 fewer), then tile (i, j) = (Y / s, X / s) of that
* band, s = stride scale p, the last band of an axis keeping the rest. With R a tile's decoded
* value, every product and sum rounded to x's dtype (rd) and mix(a, b, k, e) =
* rd(rd(a f32(1 - k / e)) + rd(b f32(k / e))) (the quotients in f64), a band's picture S is
* diffusers' in-place blend_v then blend_h of its tiles:
*
* ev = min(rows of tile (i-1, j), rows of tile (i, j), (tile - stride) scale p), eh likewise
* up(c) = R(i-1, c)[rows(i-1) - ev + ly, .] the tile above's bottom margin
* A = mix(up(j-1)[., cols(j-1) - eh + lx], up(j)[., lx], lx, eh) when j > 0, lx < eh,
* else up(j)[., lx] (it was blended with its own left)
* V = mix(A, R(i, j)[ly, lx], ly, ev) when i > 0 and ly < ev, else R(i, j)[ly, lx]
* L = mix(up(j-1)[., cols(j-1) - eh + lx], R(i, j-1)[ly, cols(j-1) - eh + lx], ly, ev)
* when i > 0 and ly < ev, else R(i, j-1)[ly, cols(j-1) - eh + lx]
* S = mix(L, V, lx, eh) when j > 0 and lx < eh, else V
*
* and across time blend_t: frame f of band kt, f < et = min(F of band kt-1, F of band kt,
* (tile_t - stride_t) scale_t), is mix(S_{kt-1}[F_{kt-1} - et + f], S_kt[f], f, et). The byte is
* patch_pix8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8
* [n (H scale p), (W scale p) C], frames first .. first + n - 1. A tile above, to the left or
* before is never short enough for its own blends to reach the margin read here (a tile not last
* on its axis spans more than `stride`), so these are the reference's values exactly. */
struct TileStore {
TileCut cs, ct;
int64_t T, H, W, sc, st, nt, ni, nj, hsum, wsum;
TileStore(const TileCut& s, const TileCut& t, int64_t T_, int64_t H_, int64_t W_, int64_t sc_,
int64_t st_)
: cs(s), ct(t), T(T_), H(H_), W(W_), sc(sc_), st(st_), nt(t.count(T_)), ni(s.count(H_)),
nj(s.count(W_)), hsum(0), wsum(0) {
for (int64_t i = 0; i < ni; ++i) hsum += cs.len(H, i);
for (int64_t j = 0; j < nj; ++j) wsum += cs.len(W, j);
}
int64_t frames(int64_t kt) const {
return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0);
}
/* Tile (kt, i, j)'s first patch row. */
int64_t offset(int64_t kt, int64_t i, int64_t j) const {
int64_t before = 0;
for (int64_t q = 0; q < kt; ++q) before += frames(q);
int64_t left = 0, above = 0;
for (int64_t q = 0; q < j; ++q) left += cs.len(W, q);
for (int64_t q = 0; q < i; ++q) above += cs.len(H, q);
return sc * sc * (before * hsum * wsum + frames(kt) * (above * wsum + cs.len(H, i) * left));
}
int64_t rows() const { return offset(nt, 0, 0); }
};
int ref_tile_stitch(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *G = &a->t[1], *Fst = &a->t[2], *Y = &a->t[3];
TileCut cs, ct;
const int64_t sc = p_int(a, "scale", 0), st = p_int(a, "scale_t", 1);
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
if (!tile_cuts(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || numel(G) < 3 ||
numel(Fst) < 1 || Y->dtype != RAD_U8 || Y->rank != 2)
return RAD_E_SHAPE;
const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), f0 = ldi(Fst, 0);
const int64_t Hpx = H * sc * p, Wpx = W * sc * p, P = C * p * p;
if (T <= 0 || H <= 0 || W <= 0 || Y->shape[1] != Wpx * C || Y->shape[0] % Hpx) return RAD_E_SHAPE;
const int64_t nf = Y->shape[0] / Hpx;
const TileStore ts(cs, ct, T, H, W, sc, st);
if (nf <= 0 || f0 < 0 || f0 + nf > st * T - (st - 1) || rows_of(X, P) < ts.rows())
return RAD_E_SHAPE;
const int64_t s = cs.stride * sc * p, E = (cs.tile - cs.stride) * sc * p;
const int64_t Et = (ct.tile - ct.stride) * st, xs = laststride(X);
const uint32_t dt = X->dtype;
auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) {
const int64_t wp = cs.len(W, j) * sc, hp = cs.len(H, i) * sc;
const int64_t row = ts.offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p;
return ldt(X, rowoff(X, row, P) + patch_col(c, yy % p, xx % p, p, wh) * xs);
};
auto mix = [&](float va, float vb, int64_t k, int64_t e) {
const float wa = (float)(1.0 - (double)k / (double)e), wb = (float)((double)k / (double)e);
return round_dt(dt, round_dt(dt, va * wa) + round_dt(dt, vb * wb));
};
/* Band kt's spatially stitched value at its frame f. */
auto S = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) {
const int64_t i = std::min(Yp / s, ts.ni - 1), ly = Yp - i * s;
const int64_t j = std::min(Xp / s, ts.nj - 1), lx = Xp - j * s;
const int64_t ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0;
const int64_t ev = i > 0 ? std::min(std::min(ha, cs.len(H, i) * sc * p), E) : 0;
const int64_t wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0;
const int64_t eh = j > 0 ? std::min(std::min(wl, cs.len(W, j) * sc * p), E) : 0;
const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh;
float V = R(kt, i, j, f, ly, lx, c);
if (vb) {
const int64_t ya = ha - ev + ly;
float A = R(kt, i - 1, j, f, ya, lx, c);
if (hb) A = mix(R(kt, i - 1, j - 1, f, ya, wl - eh + lx, c), A, lx, eh);
V = mix(A, V, ly, ev);
}
if (hb) {
float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c);
if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev);
V = mix(L, V, lx, eh);
}
return V;
};
uint8_t* yb = (uint8_t*)Y->data;
const int64_t yr = Y->stride[0], band = ct.stride * st;
REF_PAR_FOR(nf * Hpx * Wpx * C)
for (int64_t r = 0; r < nf * Hpx; ++r) {
const int64_t n = f0 + r / Hpx, Yp = r % Hpx;
const int64_t kt = std::min((n + st - 1) / band, ts.nt - 1);
const int64_t f = n - (kt == 0 ? 0 : kt * band - (st - 1));
const int64_t et = kt > 0 ? std::min(std::min(ts.frames(kt - 1), ts.frames(kt)), Et) : 0;
for (int64_t Xp = 0; Xp < Wpx; ++Xp)
for (int64_t c = 0; c < C; ++c) {
float v = S(kt, f, Yp, Xp, c);
if (kt > 0 && f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f, Yp, Xp, c), v, f, et);
const float cl = std::min(std::max(v, -1.0f), 1.0f);
float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f);
u = std::min(std::max(u, 0.0f), 1.0f);
yb[r * yr + Xp * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ stft_logmel */
/* LTX-2's bandwidth extender's input: each channel's causal log-mel spectrogram, as its MelSTFT
* computes it in the vocoder's dtype. x [S, ch] (time rows, a channel a column), `basis`
* [2F, 1, nfft] (the windowed DFT, real rows then imaginary), `mel` [n_mel, F]; frame t of channel
* h reads samples t hop + j - (nfft - hop), zero before the start:
*
* s_k = rd(sum_j basis[k, j] x[.]) mag_k = rd(sqrt(rd(rd(re_k^2) + rd(im_k^2))))
* y[t, h n_mel + m] = rd(log(max(rd(sum_k mel[m, k] mag_k), rd(1e-5))))
*
* sums f32 in ascending order, rd y's dtype. y is [S / hop, ch n_mel]. */
int ref_stft_logmel(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *B = &a->t[1], *Mb = &a->t[2], *Y = &a->t[3];
const int64_t hop = p_int(a, "hop", 0), nfft = p_int(a, "nfft", 0), nm = p_int(a, "n_mel", 0);
const int64_t ch = p_int(a, "ch", 0);
if (hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_SHAPE;
const int64_t F = nfft / 2 + 1, S = rows_of(X, ch), frames = rows_of(Y, ch * nm);
if (S <= 0 || frames <= 0 || frames * hop > S || numel(B) < 2 * F * nfft || numel(Mb) < nm * F)
return RAD_E_SHAPE;
const uint32_t dt = Y->dtype;
const int64_t pad = nfft - hop, xs = laststride(X), ys = laststride(Y);
const float floor_v = round_dt(dt, 1e-5f);
REF_PAR_FOR(frames * ch * 2 * F * nfft)
for (int64_t t = 0; t < frames; ++t)
for (int64_t h = 0; h < ch; ++h) {
std::vector<float> mag((size_t)F);
for (int64_t k = 0; k < F; ++k) {
float re = 0.0f, im = 0.0f;
for (int64_t j = 0; j < nfft; ++j) {
const int64_t s = t * hop + j - pad;
if (s < 0) continue;
const float v = ldt(X, rowoff(X, s, ch) + h * xs);
re += ldt(B, k * nfft + j) * v;
im += ldt(B, (F + k) * nfft + j) * v;
}
re = round_dt(dt, re);
im = round_dt(dt, im);
mag[(size_t)k] = round_dt(dt, std::sqrt(round_dt(dt, round_dt(dt, re * re) +
round_dt(dt, im * im))));
}
const int64_t yb = rowoff(Y, t, ch * nm);
for (int64_t m = 0; m < nm; ++m) {
float s = 0.0f;
for (int64_t k = 0; k < F; ++k) s += ldt(Mb, m * F + k) * mag[(size_t)k];
const float mel = std::max(round_dt(dt, s), floor_v);
stt(Y, yb + (h * nm + m) * ys, std::log(mel));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ bwe_up */
/* LTX-2's bandwidth extender's output: the low-rate waveform x [S, ch] raised `ratio` times by its
* Hann-windowed sinc resampler (UpSample1d, width ceil(6 / 0.99), its taps in x's dtype), added to
* the extender's residual `res` [S ratio, ch], clamped to [-1, 1]:
*
* f[n] = rd(sinc(u) cos^2(clamp(u, -6, 6) pi / 12) 0.99 / ratio), u = f32(n / ratio - w) 0.99
* up[o] = rd(ratio rd(sum f[k] x[clamp(i - w, 0, S - 1)])), i ratio + k = o + 2 w ratio
* y[o] = clamp(rd(res[o] + up[o]), -1, 1)
*
* the filter's arithmetic f32 as torch builds it, rd x's dtype; y is f32 or x's dtype. */
int ref_bwe_up(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Rz = &a->t[1], *Y = &a->t[2];
const int64_t r = p_int(a, "ratio", 0), ch = p_int(a, "ch", 0);
if (r <= 0 || ch <= 0) return RAD_E_SHAPE;
const int64_t S = rows_of(X, ch), O = rows_of(Y, ch);
if (S <= 0 || O <= 0 || O > S * r || rows_of(Rz, ch) < O) return RAD_E_SHAPE;
const uint32_t dt = X->dtype;
const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * r + 1, off = 2 * w * r;
std::vector<float> f((size_t)K);
for (int64_t n = 0; n < K; ++n) {
const float u = ((float)n / (float)r - (float)w) * 0.99f;
const float uc = std::min(std::max(u, -6.0f), 6.0f);
const float cw = std::cos(uc * (float)M_PI / 6.0f / 2.0f);
const float pu = (float)M_PI * u;
const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu;
f[(size_t)n] = round_dt(dt, sinc * (cw * cw) * 0.99f / (float)r);
}
const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y);
REF_PAR_FOR(O * ch * K)
for (int64_t o = 0; o < O; ++o)
for (int64_t h = 0; h < ch; ++h) {
const int64_t u = o + off;
float acc = 0.0f;
for (int64_t k = u % r; k < K; k += r) {
const int64_t i = (u - k) / r; /* the padded input's index */
const int64_t s = std::min(std::max<int64_t>(i - w, 0), S - 1);
acc += f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs);
}
const float up = round_dt(dt, (float)r * round_dt(dt, acc));
const float v = round_dt(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up);
stt(Y, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f));
}
return RAD_OK;
}
+43
View File
@@ -144,6 +144,10 @@ int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_dense (const RadArgs*, RadStream);
int ref_attn_cross (const RadArgs*, RadStream);
int ref_table_add (const RadArgs*, RadStream);
int ref_mix_rows (const RadArgs*, RadStream);
int ref_chan_stats (const RadArgs*, RadStream);
int ref_kv_store (const RadArgs*, RadStream);
int ref_rope (const RadArgs*, RadStream);
int ref_rope_table (const RadArgs*, RadStream);
@@ -172,6 +176,24 @@ 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);
/* ref_ltx.cpp */
int ref_rope_split(const RadArgs*, RadStream);
int ref_head_gate(const RadArgs*, RadStream);
int ref_ltx_guide(const RadArgs*, RadStream);
int ref_pixel_norm(const RadArgs*, RadStream);
int ref_d2s3d(const RadArgs*, RadStream);
int ref_s2d3d(const RadArgs*, RadStream);
int ref_pix_patch(const RadArgs*, RadStream);
int ref_patch_pix8(const RadArgs*, RadStream);
int ref_vol_index(const RadArgs*, RadStream);
int ref_attn_na3d(const RadArgs*, RadStream);
int ref_tile_grid(const RadArgs*, RadStream);
int ref_tile_crop(const RadArgs*, RadStream);
int ref_tile_stitch(const RadArgs*, RadStream);
int ref_stft_logmel(const RadArgs*, RadStream);
int ref_bwe_up(const RadArgs*, RadStream);
/* ltx_guide's scratch, in f32 values: the deviations' partial sums of a device implementation. */
enum { kLtxGuideStats = 8200 };
/* ref_vsa.cpp */
int ref_vsa_select(const RadArgs*, RadStream);
int ref_attn_vsa(const RadArgs*, RadStream);
@@ -194,6 +216,7 @@ int ref_chan_split(const RadArgs*, RadStream);
int ref_interleave2(const RadArgs*, RadStream);
int ref_iota(const RadArgs*, RadStream);
int ref_cu_repeat(const RadArgs*, RadStream);
int ref_int_affine(const RadArgs*, RadStream);
int ref_chan_affine(const RadArgs*, RadStream);
int ref_conv2d_nhwc(const RadArgs*, RadStream);
int ref_l2norm_chan(const RadArgs*, RadStream);
@@ -362,6 +385,10 @@ REF_SHAPE_FN(ref_logits_gemm);
REF_SHAPE_FN(ref_attn_paged);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_attn_cross);
REF_SHAPE_FN(ref_table_add);
REF_SHAPE_FN(ref_mix_rows);
REF_SHAPE_FN(ref_chan_stats);
REF_SHAPE_FN(ref_kv_store);
REF_SHAPE_FN(ref_rope);
REF_SHAPE_FN(ref_rope_table);
@@ -388,6 +415,21 @@ 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_rope_split);
REF_SHAPE_FN(ref_head_gate);
REF_SHAPE_FN(ref_ltx_guide);
REF_SHAPE_FN(ref_pixel_norm);
REF_SHAPE_FN(ref_d2s3d);
REF_SHAPE_FN(ref_s2d3d);
REF_SHAPE_FN(ref_pix_patch);
REF_SHAPE_FN(ref_patch_pix8);
REF_SHAPE_FN(ref_vol_index);
REF_SHAPE_FN(ref_attn_na3d);
REF_SHAPE_FN(ref_tile_grid);
REF_SHAPE_FN(ref_tile_crop);
REF_SHAPE_FN(ref_tile_stitch);
REF_SHAPE_FN(ref_stft_logmel);
REF_SHAPE_FN(ref_bwe_up);
REF_SHAPE_FN(ref_vsa_select);
REF_SHAPE_FN(ref_attn_vsa);
REF_SHAPE_FN(ref_conv1d);
@@ -408,6 +450,7 @@ REF_SHAPE_FN(ref_chan_split);
REF_SHAPE_FN(ref_interleave2);
REF_SHAPE_FN(ref_iota);
REF_SHAPE_FN(ref_cu_repeat);
REF_SHAPE_FN(ref_int_affine);
REF_SHAPE_FN(ref_chan_affine);
REF_SHAPE_FN(ref_conv2d_nhwc);
REF_SHAPE_FN(ref_l2norm_chan);
+171 -5
View File
@@ -367,6 +367,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT(
P_INTO("window_right") };
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out") };
static const RadParamSpec pAttnCross[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
P_INT("causal"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oAttnCross[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OPD("cu_k"), OUT("out") };
static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"),
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") };
/* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by
* them; optional because a bf16 cache has none. */
@@ -693,6 +700,13 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"),
static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") };
static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") };
/* `act` is the gate's activation, "tanh" (the default) or "none". */
static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") };
static const RadOperandSpec oTableAdd[] = { OPD("x"), WGT("t"), OUT("y") };
static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"),
P_F64O("eps"), P_STR("dtype") };
static const RadOperandSpec oChanStats[] = { OPD("x"), WGT("mean"), WGT("s"), OUT("y") };
static const RadOperandSpec oMixRows[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") };
static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") };
static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
@@ -701,12 +715,14 @@ static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD(
INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") };
/* `s` is [n_seq, >= 2n], [shift | scale] in each row. */
static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"),
P_STR("dtype") };
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
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") };
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_INT("gated"), P_STR("dtype") };
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
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") };
/* `t`, `sigma` and `sigma_next` are one f32 value each. */
@@ -789,7 +805,8 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
* (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. */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
P_INT("kt"), P_STR("dtype"), 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. */
@@ -805,6 +822,52 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre
P_STR("dtype") };
static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") };
/* ---- LTX-2 (ref_ltx.cpp) */
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
P_INT("dim"), P_INT("n_dims"), P_F64("theta"),
P_STR("max"), P_INTO("head0"), P_STR("dtype") };
static const RadOperandSpec oRopeSplit[] = { INOUT("x"), OPD("positions") };
static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
P_STR("dtype") };
static const RadOperandSpec oHeadGate[] = { OPD("g"), INOUT("x") };
static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oLtxGuide[] = { OPD("vc"), OPD_O("vu"), OPD_O("vs"), OPD_O("vm"),
OPD("scales"), OPD("sched"), INOUT("stats"),
INOUT("x") };
static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"),
P_STRO("act"), P_INTO("ileave"), P_STR("dtype"),
P_F64O("mult") };
static const RadOperandSpec oPixelNorm[] = { OPD("x"), OUT("y") };
static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
P_INTO("drop"), P_STR("dtype") };
static const RadOperandSpec oD2s3d[] = { OPD("x"), OPD("geom"), OUT("y") };
static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
P_INTO("tpre"), P_INTO("group"), P_STR("mode"),
P_INTO("add"), P_STR("dtype") };
static const RadOperandSpec oS2d3d[] = { OPD("x"), OPD("geom"), INOUT("y") };
static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"),
P_STR("dtype") };
static const RadOperandSpec oPixPatch[] = { OPD("x"), OUT("y") };
static const RadParamSpec pVolIndex[] = { P_INT("M") };
static const RadOperandSpec oVolIndex[] = { OPD("geom"), OUT("y") };
static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"),
P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"),
P_INTO("min_t"), P_INTO("tail") };
static const RadOperandSpec oTileGrid[] = { OPD("geom"), OUT("y") };
static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") };
static const RadOperandSpec oTileCrop[] = { OPD("x"), OPD("geom"), OPD("box"), OUT("y") };
static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"),
P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"),
P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"),
P_INTO("scale_t"), P_INT("p"), P_INT("C"),
P_STRO("order"), P_STR("dtype") };
static const RadOperandSpec oTileStitch[] = { OPD("x"), OPD("geom"), OPD("first"), OUT("y") };
static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"),
P_INT("ch"), P_STR("dtype") };
static const RadOperandSpec oStftMel[] = { OPD("x"), WGT("basis"), WGT("mel"), OUT("y") };
static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") };
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"),
@@ -864,6 +927,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
P_INTO("period") };
static const RadOperandSpec oIota[] = { OUT("y") };
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
/* ================================================================== the schema table */
@@ -948,6 +1013,16 @@ static const RadOpSchema kSchemas[] = {
"rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last "
"sum of a mean taken pairwise." },
{ "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same one broadcast rule as `add`." },
{ "table_add", ARR(pTableAdd), ARR(oTableAdd),
"y[r, l n + c] = x[r, c] + t[l, c]: a shared modulation row plus each of L learned rows, f32 sum "
"rounded once; `M` is y's rows." },
{ "chan_stats", ARR(pChanStats), ARR(oChanStats),
"a latent through per-channel statistics held as weights: `denorm` y = rd(rd(x std) + mean), "
"`norm` y = rd(rd(x - mean) / std); std is `s`, or sqrt(s + eps) with `var` 1, each statistic "
"rounded to y's dtype." },
{ "mix_rows", ARR(pMixRows), ARR(oMixRows),
"y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows, f32 sum in "
"ascending i rounded once; `M` is y's rows." },
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
"y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row "
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." },
@@ -1203,6 +1278,13 @@ static const RadOpSchema kSchemas[] = {
"window, or i - j < window and j - i < window_right with `window_right`; 0 none. `block` cuts "
"a segment into blocks of that many rows from its start, each attending within itself; 0 "
"none." },
{ "attn_cross", ARR(pAttnCross), ARR(oAttnCross),
"attn_dense with each entry's keys a run of their own: queries rows [cu[s], cu[s+1]), keys and "
"values rows [cu_k[s], cu_k[s+1]); with `causal` a query sees key j of its run when j <= its own "
"index, both counted from their run's start. A query that sees no key is zero." },
{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d),
"3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the "
"kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." },
{ "kv_store", ARR(pKvStore), ARR(oKvStore),
"Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is "
"INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." },
@@ -1572,6 +1654,53 @@ 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)." },
{ "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 "
"interleaved; angle f32(f32(2 f32(c / max)) - 1) freq; each head's halves rotated against each "
"other in f32, rounded to x's dtype. `head0` is the operand's first head." },
{ "head_gate", ARR(pHeadGate), ARR(oHeadGate),
"x = rd(x rd(2 rd(sigmoid(g)))) per head: LTX-2's gated attention output." },
{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm),
"an RMS norm over each row's n values as bf16 tensors compute it, every step rounded to y's "
"dtype: m = rd(sum rd(x^2) / n), then x rd(rsqrt(rd(m + eps))) (`form` rsqrt) or "
"x / rd(sqrt(rd(m + eps))) (div), optionally silu; `ileave` L writes x's row t L + l to "
"columns c L + l of y's row t." },
{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d),
"depth to space over voxel rows: packed channel ((c st + a) sh + b) sw + d of x's row (t, i, j) "
"to y's (t st + a - (st - 1), i sh + b, j sw + d), the first st - 1 frames dropped." },
{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d),
"space to depth over voxel rows, `tpre` leading frames prepended: each st x sh x sw box a packed "
"row (`mode` copy), or each run of `group` packed channels averaged (mean); `add` adds into y." },
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch),
"an image [H, W C] to patch rows [H/p, (W/p) C p p], channel c's (ph, pw) at c p p + pw p + ph "
"(order wh) or c p p + ph p + pw (hw)." },
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch),
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule, pix_patch's channel "
"order." },
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex),
"a volume's voxel coordinates (t, i, j), component-major: attention's rotary positions." },
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid),
"the tiles of a grid as diffusers cuts them (`rule` stride: tiled_decode's, a tile every "
"`stride` cells; intervals: _tile_intervals', a short last remnant merged), in space and "
"optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile." },
{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop),
"one tile's voxels out of a volume: y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)], box "
"(t, h, w, t0, y0, x0)." },
{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch),
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h of each tile with the one "
"above and the one to its left, then blend_t of each time band with the one before, each kept to "
"its stride, then patch_pix8's bytes." },
{ "stft_logmel", ARR(pStftMel), ARR(oStftMel),
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel filterbank, every "
"stored tensor rounded to y's dtype: frames S / hop, columns h n_mel + m." },
{ "bwe_up", ARR(pBweUp), ARR(oBweUp),
"y = clamp(rd(res + up(x)), -1, 1): x raised `ratio` times by a Hann-windowed sinc resampler "
"(width ceil(6 / 0.99), taps in x's dtype, edges replicated)." },
{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide),
"LTX-2's sampler step: each pass's clean estimate x - v sigma, the guidance deltas (CFG, STG, "
"modality) added in f32, an optional rescale by the deviations' ratio, the velocity back and "
"an Euler step of x, all f32. `scales` f32[4] (gs, stg, ms, rescale), `sched` f32[2]." },
{ "conv1d", ARR(pConv1d), ARR(oConv1d),
"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 "
@@ -1636,6 +1765,9 @@ static const RadOpSchema kSchemas[] = {
"y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`." },
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat),
"bounds of equal sequences, y[j] = j * len[0] * mult over y's elements." },
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and "
"bounds derived from a pass's device geometry." },
};
/* ================================================================== the kernel table */
@@ -1819,6 +1951,12 @@ SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate
SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul),
SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT,
ref_mul_weight),
SIMPLE("ref_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT,
ref_table_add),
SIMPLE("ref_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT,
ref_mix_rows),
SIMPLE("ref_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights",
DT_FLOAT, ref_chan_stats),
SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT,
ref_seg_mean),
SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
@@ -1942,6 +2080,11 @@ ROW("ref_attn_paged", "attn_paged", "attn",
nullptr, nullptr, ref_attn_paged, nullptr),
SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
ref_attn_dense),
SIMPLE("ref_attn_cross", "attn_cross", "attn",
"dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT,
ref_attn_cross),
SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT,
ref_attn_na3d),
ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])),
nullptr, nullptr, ref_kv_store, nullptr),
@@ -2117,6 +2260,27 @@ 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_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,
ref_head_gate),
SIMPLE("ref_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT,
ref_ltx_guide),
SIMPLE("ref_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT,
ref_pixel_norm),
SIMPLE("ref_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, ref_d2s3d),
SIMPLE("ref_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, ref_s2d3d),
SIMPLE("ref_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, ref_pix_patch),
SIMPLE("ref_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, ref_patch_pix8),
SIMPLE("ref_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, ref_vol_index),
SIMPLE("ref_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, ref_tile_grid),
SIMPLE("ref_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, ref_tile_crop),
SIMPLE("ref_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT,
ref_tile_stitch),
SIMPLE("ref_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT,
ref_stft_logmel),
SIMPLE("ref_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped",
DT_FLOAT, ref_bwe_up),
SIMPLE("ref_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, channels innermost",
DT_FLOAT, ref_conv1d),
SIMPLE("ref_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution growing each sequence",
@@ -2150,6 +2314,8 @@ SIMPLE("ref_interleave2", "interleave2", "elem", "two streams interleaved", DT_A
ref_interleave2),
SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_iota),
SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat),
SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
ref_int_affine),
};
/* ================================================================== plugin exports */
+262 -2
View File
@@ -1328,6 +1328,60 @@ int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("attn_dense", operand, out);
}
int ref_attn_cross_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t gqa = gi(p, n_p, "gqa", 1);
if (M <= 0 || hd <= 0 || gqa <= 0) return RAD_E_UNSUPPORTED;
const int64_t nh = gqa, kvh = 1;
const uint32_t D = act_dt(p, n_p);
const int64_t S = n_seq_of(p, n_p);
/* As many key rows as query rows, each side bounded by its own [0, ..., T]. */
Opd o;
o.t(D, { M, nh, hd }); /* q */
o.t(D, { M, kvh, hd }); /* k */
o.t(D, { M, kvh, hd }); /* v */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_k */
o.t(D, { M, nh, hd }); /* out */
return o.finish("attn_cross", operand, out);
}
int ref_table_add_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), L = gi(p, n_p, "L", 0);
if (M <= 0 || n <= 0 || L <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { L, n }); /* t */
o.t(D, { M, L * n }); /* y */
return o.finish("table_add", operand, out);
}
int ref_mix_rows_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), k = gi(p, n_p, "k", 0);
if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M * k, n }); /* x */
o.t(D, { k }); /* w */
o.t(D, { M, n }); /* y */
return o.finish("mix_rows", operand, out);
}
int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { n }); /* mean */
o.t_fill(D, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* s -- a deviation or variance, > 0 */
o.t(D, { M, n }); /* y */
return o.finish("chan_stats", operand, out);
}
int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
@@ -2407,7 +2461,10 @@ int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
o.skip();
}
o.t(D, { 1, 2 * n }); /* s: [shift | scale] */
o.t(D, { n }); /* w */
/* A LayerNorm without a gain passes none, and no norm takes none. */
const char* nk = gs(p, n_p, "norm");
if (nk && (std::strcmp(nk, "layer") == 0 || std::strcmp(nk, "none") == 0)) o.skip(); /* w */
else o.t(D, { n }); /* w */
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 */
@@ -2426,7 +2483,9 @@ int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD
o.skip();
}
o.t(D, { 1, 2 * n }); /* s */
o.t(D, { n }); /* w */
const char* nk = gs(p, n_p, "norm");
if (nk && std::strcmp(nk, "layer") == 0) o.skip(); /* w: a LayerNorm without a gain */
else o.t(D, { n }); /* w */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M, n }); /* x, INOUT */
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */
@@ -3215,3 +3274,204 @@ int ref_cu_repeat_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
o.t_idx({ M }, 1, -1, 0); /* y */
return o.finish("cu_repeat", operand, out);
}
int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
if (M <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ 16 }, 1000, -1, 0); /* x */
o.t_idx({ M }, 1, -1, 0); /* y */
return o.finish("int_affine", operand, out);
}
/* ================================================================== LTX-2 (ref_ltx.cpp) */
int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0), nd = gi(p, n_p, "n_dims", 0);
if (M <= 0 || nh <= 0 || hd <= 0 || nd <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), { M, nh * hd }); /* x, INOUT */
o.t((uint32_t)RAD_F32, { nd, M }); /* positions */
return o.finish("rope_split", operand, out);
}
int ref_head_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
if (M <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, nh }); /* g */
o.t(D, { M, nh * hd }); /* x, INOUT */
return o.finish("head_gate", operand, out);
}
/* The four guidance passes bound, scales and sigmas in (0, 1): every term taken. */
int ref_ltx_guide_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p), F = (uint32_t)RAD_F32;
Opd o;
for (int i = 0; i < 4; ++i) o.t(D, { M, n }); /* vc, vu, vs, vm */
o.t_fill(F, { 4 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* scales */
o.t_fill(F, { 2 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sched */
o.t(F, { kLtxGuideStats }); /* stats, INOUT */
o.t(F, { M, n }); /* x, INOUT */
return o.finish("ltx_guide", operand, out);
}
/* The rest of LTX-2's: its VAE's norm, resampling and patches, its vocoder's spectrogram and
* resampler. A volume op's `geom` is the cube of side cube_side(M), M its input's rows. */
int ref_pixel_norm_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), L = gi(p, n_p, "ileave", 1);
if (M <= 0 || n <= 0 || L <= 0 || M % L) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { M / L, n * L }); /* y */
return o.finish("pixel_norm", operand, out);
}
int ref_d2s3d_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), c = cube_side(M);
const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1);
if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { c * c * c, C * st * sh * sw }); /* x */
o.t_idx({ 3 }, 0, c, 0); /* geom */
o.t(D, { (c * st - st + 1) * c * sh * c * sw, C }); /* y */
return o.finish("d2s3d", operand, out);
}
int ref_s2d3d_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), c = cube_side(M);
const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1);
const int64_t tpre = gi(p, n_p, "tpre", 0), g = gi(p, n_p, "group", 1);
const char* mode = gs(p, n_p, "mode");
const bool mean = mode && !std::strcmp(mode, "mean");
const int64_t P = C * st * sh * sw;
if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || g <= 0 ||
(c + tpre) % st || c % sh || c % sw || (mean && P % g))
return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { c * c * c, C }); /* x */
o.t_idx({ 3 }, 0, c, 0); /* geom */
o.t(D, { ((c + tpre) / st) * (c / sh) * (c / sw), mean ? P / g : P }); /* y, INOUT */
return o.finish("s2d3d", operand, out);
}
int ref_pix_patch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0);
const int64_t w = cols_for(M, 1), h = w ? M / w : 0;
if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { h * pp, w * pp * C }); /* x: the image */
o.t(D, { h, w * C * pp * pp }); /* y: patch rows */
return o.finish("pix_patch", operand, out);
}
/* attn_na3d over a c x c x c volume, two heads. */
int ref_attn_na3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), hd = gi(p, n_p, "head_dim", 0), c = cube_side(M);
if (c <= 0 || hd <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const int64_t V = c * c * c;
Opd o;
o.t(D, { V, 2 * hd }); /* q */
o.t(D, { V, 2 * hd }); /* k */
o.t(D, { V, 2 * hd }); /* v */
o.t_idx({ 3 }, 0, c, 0); /* geom */
o.t(D, { V, 2 * hd }); /* out */
return o.finish("attn_na3d", operand, out);
}
int ref_vol_index_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), c = cube_side(M);
if (c <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ 3 }, 0, c, 0); /* geom: c x c x c */
o.t_idx({ 3, c * c * c }, 1, -1, 0); /* y */
return o.finish("vol_index", operand, out);
}
/* The tiled decode's ops: a c x c x c volume (every geom entry c), tiles and boxes inside it. */
int ref_tile_grid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), stride = gi(p, n_p, "stride", 0);
int64_t k = 0;
while ((k + 1) * (k + 1) <= M) ++k;
if (k <= 0 || stride <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t_idx({ 3 }, 0, k * stride, 0); /* geom: k x k tiles */
o.t_idx({ M, 8 }, 1, -1, 0); /* y */
return o.finish("tile_grid", operand, out);
}
int ref_tile_crop_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);
int64_t k = 0;
while ((k + 1) * (k + 1) * (k + 1) <= M) ++k;
if (k <= 0 || C <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { 8 * k * k * k, C }); /* x: 2k x 2k x 2k */
o.t_idx({ 3 }, 0, 2 * k, 0); /* geom */
o.t_idx({ 6 }, 0, k, 0); /* box: k x k x k at (k, k, k) */
o.t(D, { k * k * k, C }); /* y */
return o.finish("tile_crop", operand, out);
}
int ref_tile_stitch_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 stride = gi(p, n_p, "stride", 0), sc = gi(p, n_p, "scale", 0);
const int64_t pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0);
if (tile <= 0 || stride <= 0 || stride > tile || sc <= 0 || pp <= 0 || C <= 0)
return RAD_E_UNSUPPORTED;
int64_t c = 0;
while ((c + 1) * (c + 1) * sc * pp <= M) ++c;
if (c <= 0) return RAD_E_UNSUPPORTED;
int64_t span = 0; /* the tiles' rows along an axis */
for (int64_t s0 = 0; s0 < c; s0 += stride) span += std::min(tile, c - s0);
Opd o;
o.t(act_dt(p, n_p), { c * sc * sc * span * span, C * pp * pp }); /* x: c frames of tiles */
o.t_idx({ 3 }, 0, c, 0); /* geom */
o.t_idx({ 1 }, 0, 0, 0); /* first: frame 0 */
o.t((uint32_t)RAD_U8, { c * c * sc * pp, c * sc * pp * C }); /* y: every frame */
return o.finish("tile_stitch", operand, out);
}
int ref_patch_pix8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0);
const int64_t w = cols_for(M, 1), R = w ? M / w : 0;
if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(act_dt(p, n_p), { R, w * C * pp * pp }); /* x: patch rows */
o.t((uint32_t)RAD_U8, { R * pp, w * pp * C }); /* y: bytes */
return o.finish("patch_pix8", operand, out);
}
int ref_stft_logmel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), hop = gi(p, n_p, "hop", 0), nfft = gi(p, n_p, "nfft", 0);
const int64_t nm = gi(p, n_p, "n_mel", 0), ch = gi(p, n_p, "ch", 0), F = nfft / 2 + 1;
if (M <= 0 || hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M * hop, ch }); /* x: samples */
o.t(D, { 2 * F, 1, nfft }); /* basis */
o.t(D, { nm, F }); /* mel */
o.t(D, { M, ch * nm }); /* y */
return o.finish("stft_logmel", operand, out);
}
int ref_bwe_up_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), r = gi(p, n_p, "ratio", 0), ch = gi(p, n_p, "ch", 0);
if (M <= 0 || r <= 0 || ch <= 0 || M % r) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M / r, ch }); /* x: the low-rate waveform */
o.t(D, { M, ch }); /* res */
o.t(D, { M, ch }); /* y */
return o.finish("bwe_up", operand, out);
}
+21 -7
View File
@@ -357,20 +357,30 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
* terms outside the volume zero. acc is f32, the taps in (dt, kh, kw) order and each tap's
* channels ascending; rd is y's dtype. With `res` the convolution's output is rounded before the
* 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. */
* itself: each output element reads its own residual before its write, and no other.
*
* `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). */
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];
const RadTensor *res = t_in(a, 4), *y = &a->t[5];
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(geom) < 3)
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0);
static const char* const kPads[] = { "zero", "replicate", "causal" };
const int tpad = p_enum(a, "tpad", kPads, 3, 0);
if (tpad < 0 || (tpre && tpad != 2)) return RAD_E_INVAL;
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 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 * H * W, taps = kt * k * k;
if (rows_of(y, cout) < rows || rows_of(x, cin) < rows || (res && rows_of(res, cout) < rows) ||
numel(w) < cout * cin * taps || numel(b) < cout)
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)
return RAD_E_SHAPE;
const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y);
const int64_t rs = res ? laststride(res) : 0;
@@ -382,7 +392,11 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
for (int64_t o = 0; o < cout; ++o) {
float acc = 0.0f;
for (int64_t dz = 0; dz < kt; ++dz) {
const int64_t tz = t + dz - pz;
/* 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);
if (tz < 0 || tz >= T) continue;
for (int64_t kh = 0; kh < k; ++kh) {
const int64_t iy = i + kh - ps;