Archived
merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port
Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.
Notable reconciliations:
* videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
(i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
so upstream models keep refusing them as unknown tasks; input_reference,
the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
coexist with refs/ref2va; the prompt put() helper hoisted to block scope
for the media branch.
* video_schedule(): upstream's (steps, video_tokens, refine) keeps its
positional slots; the port's shift_video/shift_audio overrides move to the
tail so upstream's schedule tests call unchanged.
* r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
upstream's wadd/norm_once/norm parameters.
* tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
staging dir -- plugin .so files still land in the absolute
RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
relative bin/, which needs no root.
Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
a1a75da7e9
415 files changed
+78837
-5310
No files matched your search
@@ -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
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
@@ -729,6 +730,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),
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/* GLM's compressed index keys: channel-wise learned pooling, then a normalized
|
||||
* Hadamard and power-of-two E4M3 quantization. Pooling the raw keys by a mean,
|
||||
* or omitting either BF16 boundary, changes sparse selection. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
int ref_dsa_query(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
|
||||
x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != x.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]);
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float lo = v[i + j], hi = v[i + j + h];
|
||||
v[i + j] = lo + hi;
|
||||
v[i + j + h] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_dsa_score(const RadArgs* a, RadStream) {
|
||||
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qs = a->t[1];
|
||||
const auto& gate = a->t[2];
|
||||
RadTensor k = a->t[3], ks = a->t[4];
|
||||
const bool packed = k.dtype == RAD_U8;
|
||||
if (packed) {
|
||||
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
|
||||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
|
||||
((uintptr_t)k.data & 3))
|
||||
return RAD_E_SHAPE;
|
||||
ks = {};
|
||||
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
|
||||
ks.dtype = RAD_F32;
|
||||
ks.rank = 1;
|
||||
ks.shape[0] = k.shape[0];
|
||||
ks.stride[0] = k.stride[0] / 4;
|
||||
k.dtype = RAD_F8E4M3;
|
||||
k.rank = 2;
|
||||
k.shape[1] = 128;
|
||||
k.stride[1] = 1;
|
||||
}
|
||||
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8];
|
||||
const RadTensor* cu_part = rad_arg_in(a, 9);
|
||||
const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0);
|
||||
const int64_t part = p_int(a, "row_part", -1);
|
||||
if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && gate.rank == 2 &&
|
||||
q.shape[0] == gate.shape[0] * h && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = gate.shape[0];
|
||||
q.shape[2] = q.shape[1];
|
||||
q.shape[1] = h;
|
||||
q.stride[2] = q.stride[1];
|
||||
q.stride[1] = q.stride[0];
|
||||
q.stride[0] *= h;
|
||||
qs.shape[0] = gate.shape[0];
|
||||
qs.shape[1] = h;
|
||||
qs.stride[1] = qs.stride[0];
|
||||
qs.stride[0] *= h;
|
||||
}
|
||||
if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h ||
|
||||
q.shape[2] != n || qs.rank != 2 || gate.rank != 2 || qs.shape[0] != q.shape[0] ||
|
||||
gate.shape[0] != q.shape[0] || qs.shape[1] != h || gate.shape[1] != h || k.rank != 2 ||
|
||||
k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 ||
|
||||
cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 ||
|
||||
nc.shape[0] != bt.shape[0] || out.rank != 2 ||
|
||||
(part < 0 ? out.shape[0] != q.shape[0]
|
||||
: out.shape[0] < 1 || q.shape[0] < (part + 1) * out.shape[0]) ||
|
||||
out.shape[1] > bt.shape[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (cu_part && (part < 0 || cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0]))
|
||||
return part < 0 ? RAD_E_INVAL : RAD_E_SHAPE;
|
||||
if (cu_part && cu_part->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
|
||||
ks.dtype != RAD_F32 || gate.dtype != RAD_F32 || bt.dtype != RAD_I32 ||
|
||||
cu.dtype != RAD_I32 || nc.dtype != RAD_I32 || out.dtype != RAD_F32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 9; ++i)
|
||||
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
|
||||
const float norm = 1.0f / std::sqrt((float)(h * n));
|
||||
/* A part scores out's rows from step row part * rows; the query operands span the step. */
|
||||
const int64_t row0 = part > 0 ? part * out.shape[0] : 0;
|
||||
if (cu_part)
|
||||
for (int64_t s = 0; s < cu.shape[0]; ++s)
|
||||
st_int(RAD_I32, cu_part->data, s * cu_part->stride[0],
|
||||
ld_int(cu.dtype, cu.data, s * cu.stride[0]) - row0);
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t o = 0; o < out.shape[0]; ++o) {
|
||||
const int64_t r = row0 + o;
|
||||
int64_t seq = -1;
|
||||
for (int64_t s = 0; s < bt.shape[0]; ++s)
|
||||
if (r >= ld_int(cu.dtype, cu.data, s * cu.stride[0]) &&
|
||||
r < ld_int(cu.dtype, cu.data, (s + 1) * cu.stride[0])) {
|
||||
seq = s;
|
||||
break;
|
||||
}
|
||||
const int64_t live = seq >= 0 ? ld_int(nc.dtype, nc.data, seq * nc.stride[0]) : 0;
|
||||
for (int64_t b = 0; b < out.shape[1]; ++b) {
|
||||
const int64_t page =
|
||||
seq >= 0 && b < live
|
||||
? ld_int(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1])
|
||||
: -1;
|
||||
float result = -INFINITY;
|
||||
if (page >= 0 && page < k.shape[0]) {
|
||||
result = 0;
|
||||
for (int64_t head = 0; head < h; ++head) {
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) *
|
||||
ldt(&k, page * k.stride[0] + d * k.stride[1]);
|
||||
result += std::max(dot, 0.0f) *
|
||||
ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) *
|
||||
ldt(&gate, r * gate.stride[0] + head * gate.stride[1]);
|
||||
}
|
||||
result *= ldt(&ks, page * ks.stride[0]) * norm;
|
||||
}
|
||||
stt(&out, o * out.stride[0] + b * out.stride[1], result);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_dsa_pool(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE;
|
||||
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
|
||||
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
|
||||
if (cache &&
|
||||
(n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 ||
|
||||
page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 ||
|
||||
cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 ||
|
||||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
|
||||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
|
||||
return RAD_E_SHAPE;
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 ||
|
||||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data ||
|
||||
!q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 ||
|
||||
q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio ||
|
||||
kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != q.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float gate[16], mx = -INFINITY;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
gate[j] = ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + (n + d) * laststride(&kg)) +
|
||||
ldt(&ape, rowoff(&ape, j, n) + d * laststride(&ape));
|
||||
mx = std::max(mx, gate[j]);
|
||||
}
|
||||
float num = 0, den = 0;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
const float p = std::exp(gate[j] - mx);
|
||||
num += p * ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + d * laststride(&kg));
|
||||
den += p;
|
||||
}
|
||||
v[d] = bf16_to_f32(f32_to_bf16(num / den));
|
||||
}
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float x = v[i + j], y = v[i + j + h];
|
||||
v[i + j] = x + y;
|
||||
v[i + j + h] = x - y;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
const float target = am * (1.0f / 448.0f);
|
||||
int exp = 0;
|
||||
const float frac = std::frexp(target, &exp);
|
||||
const float scale = std::ldexp(1.0f, exp - (frac == 0.5f));
|
||||
stt(&s, rowoff(&s, r, 1), scale);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, rowoff(&q, r, n) + d * laststride(&q),
|
||||
std::clamp(v[d] / scale, -448.0f, 448.0f));
|
||||
if (cache) {
|
||||
const int64_t p = ld_int(page->dtype, page->data, r * page->stride[0]);
|
||||
if (p >= 0 && p < cache->shape[0]) {
|
||||
auto* dst = (uint8_t*)cache->data + p * cache->stride[0];
|
||||
for (int d = 0; d < 128; ++d)
|
||||
dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]];
|
||||
std::memcpy(dst + 128, &scale, sizeof(scale));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+421
-15
@@ -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);
|
||||
@@ -311,7 +341,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 = std::fmax(ldt(t, offlin(t, m)), clamp); /* ref pins are floors */
|
||||
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);
|
||||
@@ -573,6 +604,221 @@ int ref_flow_res_multistep(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kd_input, kd_step */
|
||||
/* A k-diffusion sampler over a discrete-time (VP-trained) denoiser, run in the variance-exploding
|
||||
* form x = x0 + sigma eps: the lane holds x in f32, the model reads c_in x with
|
||||
* c_in = 1 / sqrt(sigma^2 + 1), and a step turns the model's output into the clean estimate D and
|
||||
* moves x along the schedule (docs/OPS.md, "Image generation"). Every product and sum is one f32
|
||||
* rounding in the order written; libm's log, expm1 and sqrt. */
|
||||
|
||||
namespace {
|
||||
|
||||
enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 };
|
||||
|
||||
/* One entry's per-step constants, from its sigmas and guidance. */
|
||||
struct KdEntry {
|
||||
float s = 0, sn = 0, w = 0;
|
||||
float cskip = 0, cout = 0; /* v-prediction's c_skip and c_out */
|
||||
float sup = 0, sdown = 0; /* the ancestral step's split of sigma_next */
|
||||
float ratio = 0, em = 0; /* DPM++ 2M: sigma_next / sigma, expm1(-h) */
|
||||
float c1 = 0, c2 = 0; /* DPM++ 2M's second-order blend of D and the last D */
|
||||
bool second = false;
|
||||
};
|
||||
|
||||
KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) {
|
||||
KdEntry k;
|
||||
k.s = s;
|
||||
k.sn = sn;
|
||||
k.w = w;
|
||||
const float s2p = s * s + 1.0f;
|
||||
k.cskip = 1.0f / s2p;
|
||||
k.cout = s / std::sqrt(s2p);
|
||||
if (sampler == kSamplerEulerAncestral) {
|
||||
const float s2 = s * s, sn2 = sn * sn;
|
||||
const float up2 = sn2 * (s2 - sn2) / s2;
|
||||
float sup = std::sqrt(up2);
|
||||
if (!(sup < sn)) sup = sn;
|
||||
const float dn2 = sn2 - sup * sup;
|
||||
k.sup = sup;
|
||||
k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f);
|
||||
} else if (sampler == kSamplerDpmpp2m && sn > 0.0f) {
|
||||
const float t = -std::log(s), tn = -std::log(sn);
|
||||
const float h = tn - t;
|
||||
k.ratio = sn / s;
|
||||
k.em = std::expm1(-h);
|
||||
if (!first) {
|
||||
const float hl = t - (-std::log(sp));
|
||||
const float r = hl / h;
|
||||
k.c2 = 1.0f / (2.0f * r);
|
||||
k.c1 = 1.0f + k.c2;
|
||||
k.second = true;
|
||||
}
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The clean estimate from the model's output `o` at x. */
|
||||
inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) {
|
||||
return v_pred ? x * k.cskip - o * k.cout : x - k.s * o;
|
||||
}
|
||||
|
||||
/* x after the step, from x, the guided estimate D, the lane's last estimate and the noise. */
|
||||
inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) {
|
||||
if (sampler == kSamplerEuler) {
|
||||
const float d = (x - D) / k.s;
|
||||
return x + (k.sn - k.s) * d;
|
||||
}
|
||||
if (sampler == kSamplerEulerAncestral) {
|
||||
const float d = (x - D) / k.s;
|
||||
float xn = x + d * (k.sdown - k.s);
|
||||
if (k.sn > 0.0f) xn = xn + nz * k.sup;
|
||||
return xn;
|
||||
}
|
||||
if (k.sn == 0.0f) return D;
|
||||
const float Dd = k.second ? k.c1 * D - k.c2 * hist : D;
|
||||
return k.ratio * x - k.em * Dd;
|
||||
}
|
||||
|
||||
inline uint64_t kd_seed(const RadTensor* seed, int64_t e) {
|
||||
return (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) |
|
||||
((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The model's input for every entry that moves a lane (pair != -2): on a first step the lane
|
||||
* becomes the seed's normal stream times sqrt(1 + sigma^2) (k-diffusion's start at the schedule's
|
||||
* largest sigma), then y = rd(x / sqrt(sigma^2 + 1)) at the entry's rows and, when it is guided, at
|
||||
* its pair's rows too (the negative entry reads the same latent). */
|
||||
int ref_kd_input(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3];
|
||||
const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *y = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(y, n);
|
||||
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
|
||||
if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq ||
|
||||
numel(seed) < 2 * n_seq)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows)
|
||||
return RAD_E_SHAPE;
|
||||
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
|
||||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows)))
|
||||
return RAD_E_SHAPE;
|
||||
if (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
|
||||
const float s = ldt(sg, offlin(sg, e));
|
||||
const float init = std::sqrt(1.0f + s * s), cin = 1.0f / std::sqrt(s * s + 1.0f);
|
||||
const bool first = (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst) != 0;
|
||||
const uint64_t sd = kd_seed(seed, e);
|
||||
REF_PAR_FOR(len * n * 8)
|
||||
for (int64_t k = 0; k < len; ++k) {
|
||||
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
|
||||
const int64_t yb = rowoff(y, b0 + k, n), ys = laststride(y);
|
||||
const int64_t pb = pr >= 0 ? rowoff(y, p0 + k, n) : 0;
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init);
|
||||
const float v = ldt(st, sb + c * ss) * cin;
|
||||
stt(y, yb + c * ys, v);
|
||||
if (pr >= 0) stt(y, pb + c * ys, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One sampler step for every entry that moves a lane (pair != -2), x the lane's f32 state:
|
||||
*
|
||||
* D = eps: x - sigma o v: x / (sigma^2 + 1) - o sigma / sqrt(sigma^2 + 1)
|
||||
* D = pair >= 0 ? D(o_u) + cfg (D(o_c) - D(o_u)) : D(o_c)
|
||||
*
|
||||
* then by the entry's sampler: 0 Euler, x + (sigma_next - sigma)(x - D) / sigma; 1 Euler ancestral
|
||||
* (eta 1): the step to sigma_down plus sigma_up times the seed's stream 1 + step; 2 DPM++ 2M:
|
||||
* (sigma_next / sigma) x - expm1(-h) D', D' blending D with the lane's last estimate after the first
|
||||
* step, and D itself at sigma_next 0. Flag 4 writes D to the preview; every step leaves D in
|
||||
* `hist` for the next. */
|
||||
int ref_kd_step(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 14)) return RAD_E_INVAL;
|
||||
const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3];
|
||||
const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7];
|
||||
const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11];
|
||||
const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = t_in(a, 14);
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
const char* pred = p_str(a, "pred", "eps");
|
||||
const bool v_pred = pred && !std::strcmp(pred, "v");
|
||||
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL;
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n);
|
||||
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
|
||||
for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
|
||||
if (numel(t) < n_seq) return RAD_E_SHAPE;
|
||||
if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows)
|
||||
return RAD_E_SHAPE;
|
||||
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
|
||||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e));
|
||||
const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e));
|
||||
if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED;
|
||||
if ((f & kPreview) && !pv) return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
|
||||
const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e));
|
||||
const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e));
|
||||
const uint64_t stream = (uint64_t)(uint32_t)(1 + ld_int(stp->dtype, stp->data, offlin(stp, e)));
|
||||
const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)),
|
||||
ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm,
|
||||
(f & kFirst) != 0);
|
||||
const uint64_t sd = kd_seed(seed, e);
|
||||
REF_PAR_FOR(len * n * 8)
|
||||
for (int64_t k = 0; k < len; ++k) {
|
||||
const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O);
|
||||
const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0;
|
||||
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
|
||||
const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float x = ldt(st, sb + c * ss);
|
||||
float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os));
|
||||
if (pr >= 0) {
|
||||
const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os));
|
||||
D = Du + K.w * (D - Du);
|
||||
}
|
||||
if (f & kPreview)
|
||||
stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D);
|
||||
const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f
|
||||
? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f;
|
||||
stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz));
|
||||
stt(hs, hb + c * hss, D);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chan_affine */
|
||||
/* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration,
|
||||
* not weights), each value rounded to bf16 as upstream holds it: mode `fma` is
|
||||
@@ -617,6 +863,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) {
|
||||
@@ -626,14 +874,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];
|
||||
@@ -646,7 +896,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)
|
||||
@@ -658,6 +908,50 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ im2col_nhwc */
|
||||
/* conv2d_nhwc's receptive fields as rows, so a convolution is a GEMM against its own weight read as
|
||||
* [cout, cin k k]: x is [Hin, Win * cin] (rows at their own pitch), y [Ho * Wo, cin * k * k], and
|
||||
* row oy * Wo + ox, column (ci k + i) k + j holds the value conv2d_nhwc multiplies weight
|
||||
* [o, ci, i, j] by -- x at the tap's position read through `up` and `pad` as conv2d_nhwc reads it,
|
||||
* 0 in the padding. The output size follows from x's; y must have exactly Ho * Wo rows. A copy:
|
||||
* the values are stored as they are (rounded only when y is narrower than x). */
|
||||
int ref_im2col_nhwc(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 cin = p_int(a, "cin", 0), k = p_int(a, "k", 0);
|
||||
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 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE;
|
||||
if (x->rank != 2 || x->shape[1] % cin) return RAD_E_SHAPE;
|
||||
const int64_t Hin = x->shape[0], Win = x->shape[1] / cin, kk = cin * k * k;
|
||||
if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Hv = Hin * up, Wv = Win * up;
|
||||
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;
|
||||
const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
|
||||
if (Ho <= 0 || Wo <= 0 || rows_of(y, kk) != Ho * Wo) return RAD_E_SHAPE;
|
||||
const int64_t xr = x->stride[0], xs = laststride(x), ys = laststride(y);
|
||||
REF_PAR_FOR(Ho * Wo * kk)
|
||||
for (int64_t oy = 0; oy < Ho; ++oy)
|
||||
for (int64_t ox = 0; ox < Wo; ++ox) {
|
||||
const int64_t yb = rowoff(y, oy * Wo + ox, kk);
|
||||
for (int64_t ci = 0; ci < cin; ++ci)
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
const int64_t iy = oy * stride + i - pt;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
const int64_t ix = ox * stride + j - pl;
|
||||
const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv;
|
||||
const float v = in ? ldt(x, (iy / up) * xr + ((ix / up) * cin + ci) * xs)
|
||||
: 0.0f;
|
||||
stt(y, yb + ((ci * k + i) * k + j) * ys, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ l2norm_chan */
|
||||
/* An image norm over each pixel's channels, as upstream's three bf16 tensors:
|
||||
* n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act`
|
||||
@@ -798,6 +1092,31 @@ int ref_gelu_tanh(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gelu_quick */
|
||||
/* CLIP's quick_gelu as torch evaluates it in a reduced dtype, three stored tensors:
|
||||
* a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s). */
|
||||
int ref_gelu_quick(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);
|
||||
if (n <= 0) 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;
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
|
||||
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float v = ldt(x, xb + c * xs);
|
||||
const float t = round_dt(dt, 1.702f * v);
|
||||
const float s = round_dt(dt, 1.0f / (1.0f + std::exp(-t)));
|
||||
stt(y, yb + c * ys, v * s);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index is a skip. */
|
||||
int ref_scatter_add_rows(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
@@ -967,3 +1286,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;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
/* Routing and index head gates are F32 projections in GLM, even with BF16 hidden states. */
|
||||
int ref_gemm_nt_f32(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &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 < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 ||
|
||||
x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r)
|
||||
for (int64_t col = 0; col < n; ++col) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < k; ++j)
|
||||
sum += ldt(&x, r * x.stride[0] + j * x.stride[1]) *
|
||||
ldt(&w, col * w.stride[0] + j * w.stride[1]);
|
||||
stt(&y, r * y.stride[0] + col * y.stride[1], sum);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Single-group noaux_tc routing: correction changes selection, never the mixture weights. */
|
||||
int ref_router_sigmoid_topk(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &weights = a->t[3];
|
||||
const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0);
|
||||
const float scale = p_f32(a, "route_scale", 0);
|
||||
const bool norm = p_int(a, "norm", 0) != 0;
|
||||
if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(scale) || scale <= 0 ||
|
||||
lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
|
||||
bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || ids.rank != 2 ||
|
||||
weights.rank != 2 || ids.shape[0] != lg.shape[0] || weights.shape[0] != lg.shape[0] ||
|
||||
ids.shape[1] != k || weights.shape[1] != k || !lg.data || !bias.data || !ids.data ||
|
||||
!weights.data)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < lg.shape[0]; ++r) {
|
||||
float scores[512], select[512], chosen[512];
|
||||
int index[512];
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
scores[e] = act_sigmoid(ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg)));
|
||||
select[e] = scores[e] + ldt(&bias, e * laststride(&bias));
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
int best = -1;
|
||||
for (int64_t e = 0; e < ne; ++e)
|
||||
if (select[e] > -INFINITY && (best < 0 || select[e] > select[best])) best = (int)e;
|
||||
if (best < 0) return RAD_E_SHAPE;
|
||||
index[j] = best;
|
||||
chosen[j] = scores[best];
|
||||
sum += chosen[j];
|
||||
select[best] = -INFINITY;
|
||||
}
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
st_int(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]);
|
||||
stt(&weights, rowoff(&weights, r, k) + j * laststride(&weights),
|
||||
chosen[j] * (norm ? scale / (sum + 1e-20f) : scale));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GLM clamps the gate only above, but clamps the up branch on both sides. */
|
||||
int ref_swiglu_clamped(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &gu = a->t[0], &y = a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const float limit = p_f32(a, "limit", 0);
|
||||
if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data ||
|
||||
!y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < y.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu);
|
||||
const float g = std::min(ldt(&gu, b + i * s), limit);
|
||||
const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit);
|
||||
stt(&y, rowoff(&y, r, n) + i * laststride(&y), act_silu(g) * u);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -252,6 +252,59 @@ int ref_hc_write(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ hc_project */
|
||||
/* The control vector's projection: h[row, s*n + i] -= scale * (h . v) * v, for each of the hc
|
||||
* streams s, on the rows whose `on` flag is 1.
|
||||
*
|
||||
* `v` is one layer's unit direction (the engine normalises the file's rows when it uploads them)
|
||||
* and `scale` is the norm the file stored for that layer, so this is exactly llama.cpp's
|
||||
* `--cvec-mode project` with its `llama_adapter_cvec` (the package's 02-cvec-projection-mode
|
||||
* patch): the dot is taken per hyper-connection stream, as `mul_mat` over a [n, hc, tokens] view
|
||||
* gives it, and not on the stream mean.
|
||||
*
|
||||
* A row whose flag is 0 is not touched: no read, no write, so an unprojected request's activations
|
||||
* are the stock model's. (A deployment that merely *has* the table loaded is not bit-identical to
|
||||
* one without it -- the table's VRAM moves the expert/KV plan -- but that is placement, not this
|
||||
* op.)
|
||||
*
|
||||
* `on` is an int32 per row (core derive.cpp's `projection_on_rows`); the direction is f32. */
|
||||
int ref_hc_project(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor* h = &a->t[0];
|
||||
const RadTensor* v = &a->t[1];
|
||||
const RadTensor* on = &a->t[2];
|
||||
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const int64_t hc = p_int(a, "hc", 0);
|
||||
const float sc = p_f32(a, "scale", 1.0f);
|
||||
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
|
||||
if (numel(v) < n) return RAD_E_SHAPE;
|
||||
const int64_t hn = hc * n;
|
||||
|
||||
const int64_t rows = rows_of(h, hn);
|
||||
if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE;
|
||||
|
||||
/* Rows are independent: each dot is over one row's own streams. The parallel index is the
|
||||
* (row, stream) pair, so one row's hc streams may run on different threads without sharing an
|
||||
* accumulator. */
|
||||
REF_PAR_FOR(rows * hc)
|
||||
for (int64_t k = 0; k < rows * hc; ++k) {
|
||||
const int64_t r = k / hc, c = k % hc;
|
||||
if (ld_int(on->dtype, on->data, offlin(on, r)) == 0) continue;
|
||||
const int64_t hb = rowoff(h, r, hn), hs = laststride(h);
|
||||
const int64_t vb = rowoff(v, 0, n), vl = laststride(v);
|
||||
double acc = 0.0;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
acc += (double) ldt(h, hb + (c * n + i) * hs) * (double) ldt(v, vb + i * vl);
|
||||
const float g = (float) (acc * (double) sc);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t j = hb + (c * n + i) * hs;
|
||||
stt(h, j, ldt(h, j) - g * ldt(v, vb + i * vl));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== mtp_enter
|
||||
*
|
||||
* The multi-token-prediction head's entry for a model whose residual stream is `hc` wide.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
/* Bounded per-channel Kimi Delta Attention. Cache rows are complete candidate states,
|
||||
* so the accepted-prefix index restores the recurrence without trying to invert a delta.
|
||||
* Prefill commits only its final state; verify preserves every candidate for rejection. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) {
|
||||
return t.data && t.shape[0] == tokens &&
|
||||
((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) ||
|
||||
(t.rank == 2 && t.shape[1] == heads * dim));
|
||||
}
|
||||
int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) {
|
||||
return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) +
|
||||
d * laststride(&t);
|
||||
}
|
||||
}
|
||||
|
||||
int ref_kda_update(const RadArgs* a, RadStream) {
|
||||
if (!a || a->n_t < 13) return RAD_E_INVAL;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
if (!rad_arg_in(a, i)) return RAD_E_INVAL;
|
||||
if (!rad_arg_in(a, 12)) return RAD_E_INVAL;
|
||||
const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
|
||||
const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool verify = !std::strcmp(mode, "verify");
|
||||
const char* form = p_str(a, "state_form", "per_candidate");
|
||||
const bool anchor = !std::strcmp(form, "anchor");
|
||||
if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
|
||||
if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED;
|
||||
if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL;
|
||||
if (H <= 0 || K <= 0 || K > 128 || V <= 0 || V > 128 || !std::isfinite(lower) || lower >= 0 ||
|
||||
!std::isfinite(eps) || eps <= 0 || !std::isfinite(scale))
|
||||
return RAD_E_SHAPE;
|
||||
const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &beta = a->t[4];
|
||||
const auto &alog = a->t[5], &bias = a->t[6], &state = a->t[7], &idx = a->t[8], &cu = a->t[9];
|
||||
const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11);
|
||||
const auto& out = a->t[12];
|
||||
if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE;
|
||||
const int64_t T = q.shape[0], N = cu.shape[0] - 1;
|
||||
if (T < 1) return RAD_E_SHAPE;
|
||||
if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) ||
|
||||
!headed(beta, T, H, 1) || !headed(out, T, H, V) || numel(&alog) != H ||
|
||||
numel(&bias) != H * K || state.rank != 4 || state.dtype != RAD_F32 || state.shape[1] != H ||
|
||||
state.shape[2] != V || state.shape[3] != K || idx.dtype != RAD_I32 || idx.rank != 2 ||
|
||||
idx.shape[0] < N || idx.shape[1] < 1 ||
|
||||
(accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) ||
|
||||
(init && (init->dtype != RAD_I32 || numel(init) < N)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t width = idx.shape[1], slots = state.shape[0];
|
||||
/* Check every address before writing any state, so a malformed batch cannot leave a
|
||||
* partially committed prefix when the host reference reports an error. */
|
||||
for (int64_t seq = 0; seq < N; ++seq) {
|
||||
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
|
||||
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na =
|
||||
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
|
||||
if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) ||
|
||||
(verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t j = 0; j < width; ++j)
|
||||
if (ld_int(idx.dtype, idx.data, seq * idx.stride[0] + j * idx.stride[1]) >= slots)
|
||||
return RAD_E_SHAPE;
|
||||
if (anchor) {
|
||||
const int64_t read = ld_int(idx.dtype, idx.data, seq * idx.stride[0]);
|
||||
const int64_t scratch =
|
||||
ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]);
|
||||
if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE;
|
||||
if (verify && read >= 0 &&
|
||||
(!init || ld_int(init->dtype, init->data, offlin(init, seq))))
|
||||
for (int64_t h = 0; h < H; ++h) {
|
||||
const float count =
|
||||
ldt(&state, scratch * state.stride[0] + h * state.stride[1]);
|
||||
if (!std::isfinite(count) || count < 0 || count > 32 ||
|
||||
count != std::floor(count) || (count > 0 && na > count))
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t sh = 0; sh < N * H; ++sh) {
|
||||
const int64_t seq = sh / H, head = sh % H;
|
||||
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
|
||||
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
|
||||
if (begin == end) continue;
|
||||
const int64_t na =
|
||||
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
|
||||
const int64_t read =
|
||||
ld_int(idx.dtype, idx.data,
|
||||
seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]);
|
||||
if (read < 0) {
|
||||
for (int64_t t = begin; t < end; ++t)
|
||||
for (int64_t e = 0; e < V; ++e) stt(&out, off(out, t, head, e, V), 0);
|
||||
continue;
|
||||
}
|
||||
float S[128 * 128], qn[128], kn[128], decay[128];
|
||||
const bool initialized = !init || ld_int(init->dtype, init->data, offlin(init, seq)) != 0;
|
||||
const int64_t sb = read * state.stride[0] + head * state.stride[1];
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
S[e * K + d] =
|
||||
initialized ? ldt(&state, sb + e * state.stride[2] + d * state.stride[3]) : 0;
|
||||
const int64_t scratch =
|
||||
anchor ? ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1])
|
||||
: 0;
|
||||
auto factor_at = [&](int64_t i) {
|
||||
return scratch * state.stride[0] + head * state.stride[1] + (i / K) * state.stride[2] +
|
||||
(i % K) * state.stride[3];
|
||||
};
|
||||
constexpr int factors = 385;
|
||||
if (anchor && verify) {
|
||||
const int replay = initialized ? (int)ldt(&state, factor_at(0)) : 0;
|
||||
for (int t = 0; t < (replay ? na : 0); ++t) {
|
||||
const int f = 1 + t * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
kn[d] = ldt(&state, factor_at(f + d));
|
||||
decay[d] = ldt(&state, factor_at(f + 256 + d));
|
||||
}
|
||||
const float bt = ldt(&state, factor_at(f + 384));
|
||||
for (int e = 0; e < 128; ++e) {
|
||||
float prediction = 0;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
S[e * K + d] *= decay[d];
|
||||
prediction += S[e * K + d] * kn[d];
|
||||
}
|
||||
const float delta = bt * (ldt(&state, factor_at(f + 128 + e)) - prediction);
|
||||
for (int d = 0; d < 128; ++d) S[e * K + d] += delta * kn[d];
|
||||
}
|
||||
}
|
||||
// Publish only the accepted prefix. Current candidates remain in registers.
|
||||
for (int e = 0; e < 128; ++e)
|
||||
for (int d = 0; d < 128; ++d)
|
||||
stt(&state, sb + e * state.stride[2] + d * state.stride[3], S[e * K + d]);
|
||||
}
|
||||
const float gain = std::exp(ldt(&alog, head * laststride(&alog)));
|
||||
for (int64_t t = begin; t < end; ++t) {
|
||||
float qs = 0, ks = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] = ldt(&q, off(q, t, head, d, K));
|
||||
kn[d] = ldt(&k, off(k, t, head, d, K));
|
||||
qs += qn[d] * qn[d];
|
||||
ks += kn[d] * kn[d];
|
||||
}
|
||||
const float qi = scale / std::sqrt(qs + eps), ki = 1.0f / std::sqrt(ks + eps);
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] *= qi;
|
||||
kn[d] *= ki;
|
||||
const float z = gain * (ldt(&g, off(g, t, head, d, K)) +
|
||||
ldt(&bias, (head * K + d) * laststride(&bias)));
|
||||
decay[d] = std::exp(lower / (1.0f + std::exp(-z)));
|
||||
}
|
||||
const float bt = 1.0f / (1.0f + std::exp(-ldt(&beta, off(beta, t, head, 0, 1))));
|
||||
if (anchor && verify) {
|
||||
const int f = 1 + (int)(t - begin) * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
stt(&state, factor_at(f + d), kn[d]);
|
||||
stt(&state, factor_at(f + 256 + d), decay[d]);
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
stt(&state, factor_at(f + 128 + e), ldt(&v, off(v, t, head, e, V)));
|
||||
stt(&state, factor_at(f + 384), bt);
|
||||
}
|
||||
for (int64_t e = 0; e < V; ++e) {
|
||||
float predicted = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
S[e * K + d] *= decay[d];
|
||||
predicted += S[e * K + d] * kn[d];
|
||||
}
|
||||
const float delta = bt * (ldt(&v, off(v, t, head, e, V)) - predicted);
|
||||
float result = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
S[e * K + d] += delta * kn[d];
|
||||
result += S[e * K + d] * qn[d];
|
||||
}
|
||||
stt(&out, off(out, t, head, e, V), result);
|
||||
}
|
||||
if ((!anchor && verify) || (!verify && t + 1 == end)) {
|
||||
const int64_t write =
|
||||
ld_int(idx.dtype, idx.data,
|
||||
seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]);
|
||||
if (write >= 0)
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
stt(&state,
|
||||
write * state.stride[0] + head * state.stride[1] +
|
||||
e * state.stride[2] + d * state.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
}
|
||||
if (anchor) stt(&state, factor_at(0), verify ? (float)(end - begin) : 0.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+13
-5
@@ -101,8 +101,8 @@ int ref_lora_shrink(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* operands: t, slot, lora_b, scale, y (inout) */
|
||||
int ref_lora_expand(const RadArgs* a, RadStream) {
|
||||
/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */
|
||||
static int lora_expand_impl(const RadArgs* a, bool bf16_t) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4];
|
||||
const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
|
||||
@@ -127,9 +127,11 @@ int ref_lora_expand(const RadArgs* a, RadStream) {
|
||||
if (s < 0) continue; /* a base row: not read, not written */
|
||||
const int64_t t0 = m * mt.rs, b0 = s * pb.s0 + n * pb.s1;
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < R; ++j)
|
||||
acc += ((const float*)T->data)[t0 + j * mt.cs] *
|
||||
ld_dt(LB->dtype, LB->data, b0 + j * pb.s2);
|
||||
for (int64_t j = 0; j < R; ++j) {
|
||||
float tv = ((const float*)T->data)[t0 + j * mt.cs];
|
||||
if (bf16_t) tv = rad_bf16_to_f32(rad_f32_to_bf16(tv));
|
||||
acc += tv * ld_dt(LB->dtype, LB->data, b0 + j * pb.s2);
|
||||
}
|
||||
const float sc = ((const float*)SC->data)[s * sc_r + n * sc_c];
|
||||
const int64_t o = m * ys_r + n * ys_c;
|
||||
/* `sc * acc` and then the add, each rounded: the order is the definition. */
|
||||
@@ -138,3 +140,9 @@ int ref_lora_expand(const RadArgs* a, RadStream) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_lora_expand(const RadArgs* a, RadStream) { return lora_expand_impl(a, false); }
|
||||
|
||||
/* lora_expand with t rounded to bf16; the order of the sum is free, so j ascending is one of the
|
||||
* answers it allows. */
|
||||
int ref_lora_expand_mm(const RadArgs* a, RadStream) { return lora_expand_impl(a, true); }
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/* Manifold-constrained hyper-connections. The residual mixing matrix is indexed
|
||||
* [source, destination]; transposing it leaves every shape valid and changes the model.
|
||||
* The first Sinkhorn pass is softmax + eps, then column normalization. Later passes
|
||||
* add eps to both denominators. These are separate operations from Qwen's hc_read/write. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
bool matrix(const RadTensor& t, int64_t rows, int64_t cols) {
|
||||
return t.data && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
|
||||
bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps,
|
||||
float* heps) {
|
||||
*n = p_int(a, "n", 0);
|
||||
*hc = p_int(a, "hc", 0);
|
||||
*iters = p_int(a, "iterations", 0);
|
||||
*eps = p_f32(a, "eps", 0);
|
||||
*heps = p_f32(a, "hc_eps", 0);
|
||||
return *n > 0 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) &&
|
||||
std::isfinite(*heps) && *eps > 0 && *heps >= 0;
|
||||
}
|
||||
|
||||
/* The outputs' shapes, shared by mhc_pre and mhc_pre_finish. */
|
||||
bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows,
|
||||
int64_t n, int64_t hc) {
|
||||
const int64_t mix = hc * (hc + 2);
|
||||
return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 &&
|
||||
numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix &&
|
||||
matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) &&
|
||||
post.dtype == RAD_F32 && comb.dtype == RAD_F32;
|
||||
}
|
||||
|
||||
/* Row r from its RMS-scaled coefficients: gates, Sinkhorn mixing and the collapse of h. */
|
||||
void finish_row(const float* coeff, const RadTensor& h, const RadTensor& scale,
|
||||
const RadTensor& base, const RadTensor& x, const RadTensor& post,
|
||||
const RadTensor& comb, int64_t r, int64_t n, int64_t hc, int64_t iters,
|
||||
float heps) {
|
||||
float pre[8], c[64];
|
||||
const int64_t hb = rowoff(&h, r, hc * n), hs = laststride(&h);
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
pre[j] =
|
||||
1.0f / (1.0f +
|
||||
std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) +
|
||||
heps;
|
||||
const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) +
|
||||
ldt(&base, (hc + j) * laststride(&base));
|
||||
stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z)));
|
||||
}
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
float mx = -INFINITY;
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
const int64_t q = 2 * hc + j * hc + k;
|
||||
c[j * hc + k] =
|
||||
coeff[q] * ldt(&scale, 2 * laststride(&scale)) + ldt(&base, q * laststride(&base));
|
||||
mx = std::max(mx, c[j * hc + k]);
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
c[j * hc + k] = std::exp(c[j * hc + k] - mx);
|
||||
sum += c[j * hc + k];
|
||||
}
|
||||
for (int64_t k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps;
|
||||
}
|
||||
for (int64_t it = 0; it < iters; ++it) {
|
||||
if (it)
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
float sum = 0;
|
||||
for (int64_t k = 0; k < hc; ++k) sum += c[j * hc + k];
|
||||
for (int64_t k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps;
|
||||
}
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) sum += c[j * hc + k];
|
||||
for (int64_t j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps;
|
||||
}
|
||||
}
|
||||
const int64_t cb = rowoff(&comb, r, hc * hc), cs = laststride(&comb);
|
||||
for (int64_t j = 0; j < hc * hc; ++j) stt(&comb, cb + j * cs, c[j]);
|
||||
const int64_t xb = rowoff(&x, r, n), xs = laststride(&x);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) v += pre[j] * ldt(&h, hb + (j * n + i) * hs);
|
||||
stt(&x, xb + i * xs, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int ref_mhc_pre(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2);
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float coeff[80];
|
||||
const int64_t hb = rowoff(&h, r, width), hs = laststride(&h);
|
||||
float sq = 0;
|
||||
for (int64_t i = 0; i < width; ++i) {
|
||||
const float v = ldt(&h, hb + i * hs);
|
||||
sq += v * v;
|
||||
}
|
||||
const float inv = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float dot = 0;
|
||||
const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn);
|
||||
for (int64_t i = 0; i < width; ++i) dot += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs);
|
||||
coeff[j] = dot * inv;
|
||||
}
|
||||
finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_pre_partial(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0);
|
||||
const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || first < 0 || count < 1 ||
|
||||
first + count > hc * n / chunk)
|
||||
return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc);
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!matrix(part, rows, count * S) || part.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t hb = rowoff(&h, r, width), hs = laststride(&h);
|
||||
const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part);
|
||||
for (int64_t c = 0; c < count; ++c) {
|
||||
const int64_t lo = (first + c) * chunk;
|
||||
for (int64_t j = 0; j < S; ++j) {
|
||||
float sum = 0;
|
||||
if (j < mix) {
|
||||
const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn);
|
||||
for (int64_t i = lo; i < lo + chunk; ++i)
|
||||
sum += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs);
|
||||
} else if (j == mix) {
|
||||
for (int64_t i = lo; i < lo + chunk; ++i) {
|
||||
const float v = ldt(&h, hb + i * hs);
|
||||
sum += v * v;
|
||||
}
|
||||
}
|
||||
stt(&part, pb + (c * S + j) * ps, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_pre_finish(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const int64_t chunk = p_int(a, "chunk", 0);
|
||||
if (chunk <= 0 || (hc * n) % chunk) return RAD_E_SHAPE;
|
||||
const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc), chunks = width / chunk;
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float coeff[80];
|
||||
const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part);
|
||||
float sq = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps);
|
||||
const float inv = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float dot = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) dot += ldt(&part, pb + (c * S + j) * ps);
|
||||
coeff[j] = dot * inv;
|
||||
}
|
||||
finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_post(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &x = a->t[0], &h = a->t[1], &post = a->t[2], &comb = a->t[3], &out = a->t[4];
|
||||
if (x.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = x.shape[0];
|
||||
if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(post, rows, hc) ||
|
||||
!matrix(comb, rows, hc * hc) || !matrix(out, rows, hc * n) || out.data == h.data ||
|
||||
post.dtype != RAD_F32 || comb.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t hb = rowoff(&h, r, hc * n), cb = rowoff(&comb, r, hc * hc);
|
||||
const int64_t pb = rowoff(&post, r, hc), xb = rowoff(&x, r, n);
|
||||
const int64_t ob = rowoff(&out, r, hc * n);
|
||||
for (int64_t k = 0; k < hc; ++k)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&comb, cb + (j * hc + k) * laststride(&comb)) *
|
||||
ldt(&h, hb + (j * n + i) * laststride(&h));
|
||||
v += ldt(&post, pb + k * laststride(&post)) * ldt(&x, xb + i * laststride(&x));
|
||||
stt(&out, ob + (k * n + i) * laststride(&out), v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_contract(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &x = a->t[1];
|
||||
if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) ||
|
||||
!matrix(x, h.shape[0], n))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < h.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h));
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/* Absorbed MLA: one latent vector is both the attention key and value. The
|
||||
* per-query table already contains the selected complete pages plus its tail.
|
||||
* `scale` comes from the original query/key head width, NOT the latent width. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
/* Both projections share the checkpoint's [head,(K|V),latent] matrix.
|
||||
* Absorb: q @ Wk. Expand: attention_latent @ Wv^T. No per-head KV cache. */
|
||||
int ref_mla_project(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
RadTensor x = a->t[0], y = a->t[2];
|
||||
const auto& w = a->t[1];
|
||||
const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0),
|
||||
l = p_int(a, "latent_dim", 0);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand");
|
||||
auto heads_view = [&](RadTensor& t, int64_t width) {
|
||||
if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) {
|
||||
t.rank = 3;
|
||||
t.shape[1] = h;
|
||||
t.shape[2] = width;
|
||||
t.stride[2] = t.stride[1];
|
||||
t.stride[1] *= width;
|
||||
}
|
||||
};
|
||||
heads_view(x, absorb ? d : l);
|
||||
heads_view(y, absorb ? l : d);
|
||||
if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 ||
|
||||
y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) ||
|
||||
w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h ||
|
||||
y.shape[2] != (absorb ? l : d))
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r)
|
||||
for (int64_t head = 0; head < h; ++head)
|
||||
for (int64_t col = 0; col < (absorb ? l : d); ++col) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < (absorb ? d : l); ++j) {
|
||||
const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j;
|
||||
sum += ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]) *
|
||||
ldt(&w, wr * w.stride[0] + wc * w.stride[1]);
|
||||
}
|
||||
stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mla_attn(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4];
|
||||
const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0),
|
||||
bs = p_int(a, "block_size", 0);
|
||||
const float scale = p_f32(a, "scale", 0);
|
||||
if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
|
||||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 ||
|
||||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 ||
|
||||
bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 ||
|
||||
out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d ||
|
||||
bt.dtype != RAD_I32 || len.dtype != RAD_I32)
|
||||
return RAD_E_SHAPE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t job = 0; job < q.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
const int64_t live = std::clamp(ld_int(len.dtype, len.data, r * len.stride[0]), (int64_t)0,
|
||||
bt.shape[1] * bs);
|
||||
auto key_offset = [&](int64_t token) -> int64_t {
|
||||
const int64_t page =
|
||||
ld_int(bt.dtype, bt.data, r * bt.stride[0] + (token / bs) * bt.stride[1]);
|
||||
return page < 0 || page >= kv.shape[0]
|
||||
? -1
|
||||
: page * kv.stride[0] + (token % bs) * kv.stride[2];
|
||||
};
|
||||
auto dot = [&](int64_t base) -> float {
|
||||
float v = 0;
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
v += ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]) *
|
||||
ldt(&kv, base + c * kv.stride[3]);
|
||||
return v * scale;
|
||||
};
|
||||
float max = -INFINITY;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const auto base = key_offset(j);
|
||||
if (base >= 0) max = std::max(max, dot(base));
|
||||
}
|
||||
float val[2048] = {}, den = 0;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const auto base = key_offset(j);
|
||||
if (base < 0) continue;
|
||||
const float w = std::exp(dot(base) - max);
|
||||
den += w;
|
||||
for (int64_t c = 0; c < d; ++c) val[c] += w * ldt(&kv, base + c * kv.stride[3]);
|
||||
}
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2],
|
||||
den > 0 ? val[c] / den : 0);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+2
-1
@@ -492,7 +492,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
|
||||
if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE;
|
||||
}
|
||||
mw[(size_t)e] = as_mat(&we[(size_t)e], k);
|
||||
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false);
|
||||
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k,
|
||||
we[(size_t)e].dtype == RAD_FP4E2M1);
|
||||
}
|
||||
|
||||
const int64_t fy = N / parts;
|
||||
|
||||
@@ -59,8 +59,15 @@ int ref_rmsnorm (const RadArgs*, RadStream);
|
||||
int ref_rmsnorm_p (const RadArgs*, RadStream);
|
||||
int ref_rmsnorm_add (const RadArgs*, RadStream);
|
||||
int ref_hc_enter (const RadArgs*, RadStream);
|
||||
int ref_mhc_pre (const RadArgs*, RadStream);
|
||||
int ref_mhc_pre_partial (const RadArgs*, RadStream);
|
||||
int ref_mhc_pre_finish (const RadArgs*, RadStream);
|
||||
int ref_mhc_post (const RadArgs*, RadStream);
|
||||
int ref_mhc_contract (const RadArgs*, RadStream);
|
||||
int ref_kda_update (const RadArgs*, RadStream);
|
||||
int ref_hc_read (const RadArgs*, RadStream);
|
||||
int ref_hc_write (const RadArgs*, RadStream);
|
||||
int ref_hc_project (const RadArgs*, RadStream);
|
||||
int ref_mtp_enter (const RadArgs*, RadStream);
|
||||
int ref_layernorm (const RadArgs*, RadStream);
|
||||
int ref_grid_embed (const RadArgs*, RadStream);
|
||||
@@ -68,6 +75,14 @@ int ref_grid_embed_aa (const RadArgs*, RadStream);
|
||||
int ref_add (const RadArgs*, RadStream);
|
||||
int ref_mul (const RadArgs*, RadStream);
|
||||
int ref_silu_mul (const RadArgs*, RadStream);
|
||||
int ref_swiglu_clamped (const RadArgs*, RadStream);
|
||||
int ref_router_sigmoid_topk(const RadArgs*, RadStream);
|
||||
int ref_dsa_pool(const RadArgs*, RadStream);
|
||||
int ref_dsa_query(const RadArgs*, RadStream);
|
||||
int ref_gemm_nt_f32(const RadArgs*, RadStream);
|
||||
int ref_mla_project(const RadArgs*, RadStream);
|
||||
int ref_dsa_score(const RadArgs*, RadStream);
|
||||
int ref_mla_attn(const RadArgs*, RadStream);
|
||||
int ref_gelu_mul (const RadArgs*, RadStream);
|
||||
int ref_act_mul (const RadArgs*, RadStream);
|
||||
int ref_mul_weight (const RadArgs*, RadStream);
|
||||
@@ -104,6 +119,7 @@ int ref_had_quant_act_i8 (const RadArgs*, RadStream);
|
||||
int ref_quant_act_fp8 (const RadArgs*, RadStream);
|
||||
int ref_quant_cols_fp8 (const RadArgs*, RadStream);
|
||||
int ref_had_quant_act_fp8 (const RadArgs*, RadStream);
|
||||
int ref_had_quant_act_i8g (const RadArgs*, RadStream);
|
||||
int ref_givens_dense_quant(const RadArgs*, RadStream);
|
||||
int ref_givens_rotate(const RadArgs*, RadStream);
|
||||
int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
|
||||
@@ -123,6 +139,7 @@ int ref_gemm_nt_q_bias (const RadArgs*, RadStream);
|
||||
/* Runtime LoRA's two halves, per-row adapter slot (ref_lora.cpp). */
|
||||
int ref_lora_shrink (const RadArgs*, RadStream);
|
||||
int ref_lora_expand (const RadArgs*, RadStream);
|
||||
int ref_lora_expand_mm (const RadArgs*, RadStream);
|
||||
int ref_embed_lookup (const RadArgs*, RadStream);
|
||||
int ref_embed_lookup_q (const RadArgs*, RadStream);
|
||||
int ref_logits_gemm (const RadArgs*, RadStream);
|
||||
@@ -130,6 +147,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);
|
||||
@@ -144,6 +165,8 @@ int ref_lane_gather(const RadArgs*, RadStream);
|
||||
int ref_lane_store(const RadArgs*, RadStream);
|
||||
int ref_randn_lanes(const RadArgs*, RadStream);
|
||||
int ref_flow_euler(const RadArgs*, RadStream);
|
||||
int ref_kd_input(const RadArgs*, RadStream);
|
||||
int ref_kd_step(const RadArgs*, RadStream);
|
||||
int ref_rms_mod(const RadArgs*, RadStream);
|
||||
int ref_rms_mod_quant_fp8(const RadArgs*, RadStream);
|
||||
int ref_flow_x0_step(const RadArgs*, RadStream);
|
||||
@@ -159,6 +182,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);
|
||||
@@ -181,13 +222,16 @@ 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_im2col_nhwc(const RadArgs*, RadStream);
|
||||
int ref_l2norm_chan(const RadArgs*, RadStream);
|
||||
int ref_d2s_add(const RadArgs*, RadStream);
|
||||
int ref_s2d_avg_add(const RadArgs*, RadStream);
|
||||
int ref_to_rgba8(const RadArgs*, RadStream);
|
||||
int ref_gelu_tanh(const RadArgs*, RadStream);
|
||||
int ref_gelu_quick(const RadArgs*, RadStream);
|
||||
int ref_scatter_add_rows(const RadArgs*, RadStream);
|
||||
int ref_attn_prefix_self(const RadArgs*, RadStream);
|
||||
int ref_qsa_block_key (const RadArgs*, RadStream);
|
||||
@@ -268,8 +312,15 @@ REF_SHAPE_FN(ref_rmsnorm);
|
||||
REF_SHAPE_FN(ref_rmsnorm_p);
|
||||
REF_SHAPE_FN(ref_rmsnorm_add);
|
||||
REF_SHAPE_FN(ref_hc_enter);
|
||||
REF_SHAPE_FN(ref_mhc_pre);
|
||||
REF_SHAPE_FN(ref_mhc_pre_partial);
|
||||
REF_SHAPE_FN(ref_mhc_pre_finish);
|
||||
REF_SHAPE_FN(ref_mhc_post);
|
||||
REF_SHAPE_FN(ref_mhc_contract);
|
||||
REF_SHAPE_FN(ref_kda_update);
|
||||
REF_SHAPE_FN(ref_hc_read);
|
||||
REF_SHAPE_FN(ref_hc_write);
|
||||
REF_SHAPE_FN(ref_hc_project);
|
||||
REF_SHAPE_FN(ref_mtp_enter);
|
||||
REF_SHAPE_FN(ref_layernorm);
|
||||
REF_SHAPE_FN(ref_grid_embed);
|
||||
@@ -277,6 +328,14 @@ REF_SHAPE_FN(ref_grid_embed_aa);
|
||||
REF_SHAPE_FN(ref_add);
|
||||
REF_SHAPE_FN(ref_mul);
|
||||
REF_SHAPE_FN(ref_silu_mul);
|
||||
REF_SHAPE_FN(ref_swiglu_clamped);
|
||||
REF_SHAPE_FN(ref_router_sigmoid_topk);
|
||||
REF_SHAPE_FN(ref_dsa_pool);
|
||||
REF_SHAPE_FN(ref_dsa_query);
|
||||
REF_SHAPE_FN(ref_gemm_nt_f32);
|
||||
REF_SHAPE_FN(ref_mla_project);
|
||||
REF_SHAPE_FN(ref_dsa_score);
|
||||
REF_SHAPE_FN(ref_mla_attn);
|
||||
REF_SHAPE_FN(ref_gelu_mul);
|
||||
REF_SHAPE_FN(ref_act_mul);
|
||||
REF_SHAPE_FN(ref_mul_weight);
|
||||
@@ -312,6 +371,7 @@ REF_SHAPE_FN(ref_had_quant_act_i8);
|
||||
REF_SHAPE_FN(ref_quant_act_fp8);
|
||||
REF_SHAPE_FN(ref_quant_cols_fp8);
|
||||
REF_SHAPE_FN(ref_had_quant_act_fp8);
|
||||
REF_SHAPE_FN(ref_had_quant_act_i8g);
|
||||
REF_SHAPE_FN(ref_givens_dense_quant);
|
||||
REF_SHAPE_FN(ref_givens_rotate);
|
||||
REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
|
||||
@@ -329,12 +389,17 @@ REF_SHAPE_FN(ref_gemm_nt_q);
|
||||
REF_SHAPE_FN(ref_gemm_nt_q_bias);
|
||||
REF_SHAPE_FN(ref_lora_shrink);
|
||||
REF_SHAPE_FN(ref_lora_expand);
|
||||
REF_SHAPE_FN(ref_lora_expand_mm);
|
||||
REF_SHAPE_FN(ref_embed_lookup);
|
||||
REF_SHAPE_FN(ref_embed_lookup_q);
|
||||
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);
|
||||
@@ -348,6 +413,8 @@ REF_SHAPE_FN(ref_lane_gather);
|
||||
REF_SHAPE_FN(ref_lane_store);
|
||||
REF_SHAPE_FN(ref_randn_lanes);
|
||||
REF_SHAPE_FN(ref_flow_euler);
|
||||
REF_SHAPE_FN(ref_kd_input);
|
||||
REF_SHAPE_FN(ref_kd_step);
|
||||
REF_SHAPE_FN(ref_rms_mod);
|
||||
REF_SHAPE_FN(ref_rms_mod_quant_fp8);
|
||||
REF_SHAPE_FN(ref_flow_x0_step);
|
||||
@@ -362,6 +429,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);
|
||||
@@ -382,13 +464,16 @@ 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_im2col_nhwc);
|
||||
REF_SHAPE_FN(ref_l2norm_chan);
|
||||
REF_SHAPE_FN(ref_d2s_add);
|
||||
REF_SHAPE_FN(ref_s2d_avg_add);
|
||||
REF_SHAPE_FN(ref_to_rgba8);
|
||||
REF_SHAPE_FN(ref_gelu_tanh);
|
||||
REF_SHAPE_FN(ref_gelu_quick);
|
||||
REF_SHAPE_FN(ref_scatter_add_rows);
|
||||
REF_SHAPE_FN(ref_attn_prefix_self);
|
||||
REF_SHAPE_FN(ref_qsa_block_key);
|
||||
|
||||
+8
-3
@@ -15,6 +15,7 @@
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
using namespace ref;
|
||||
@@ -101,7 +102,8 @@ int ref_qsa_score(const RadArgs* a, RadStream) {
|
||||
/* ------------------------------------------------------------------ qsa_select */
|
||||
/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks
|
||||
* n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked
|
||||
* by max(score, 0). At most `topk` are taken: all of them when that many or fewer are live, else
|
||||
* by max(score, 0); with `signed` 1 the live ones are those with a finite score, ranked by it (so
|
||||
* -0 ties +0). At most `topk` are taken: all of them when that many or fewer are live, else
|
||||
* every block above the topk-th largest value in block order, then the blocks equal to it in block
|
||||
* order until topk are taken. The partial page bt[n] follows when (pos + 1) % ratio != 0 and
|
||||
* n < width, and -1 pads the row to topk + 1. nsel counts the entries, seqused is
|
||||
@@ -112,7 +114,9 @@ int ref_qsa_select(const RadArgs* a, RadStream) {
|
||||
const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3];
|
||||
const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7];
|
||||
const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t sgn = p_int(a, "signed", 0);
|
||||
if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE;
|
||||
if (sgn != 0 && sgn != 1) return RAD_E_INVAL;
|
||||
if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]);
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
@@ -136,8 +140,9 @@ int ref_qsa_select(const RadArgs* a, RadStream) {
|
||||
std::vector<int64_t> live;
|
||||
for (int64_t b = 0; b < n; ++b) {
|
||||
const float v = ldt(sc, m * s_rs + b * s_cs);
|
||||
if (ldi(bt, s * bt_rs + b * bt_cs) < 0 || !(v > -1e30f)) continue;
|
||||
val[(size_t)b] = v > 0.0f ? v : 0.0f;
|
||||
if (ldi(bt, s * bt_rs + b * bt_cs) < 0) continue;
|
||||
if (sgn ? !std::isfinite(v) : !(v > -1e30f)) continue;
|
||||
val[(size_t)b] = sgn ? v : v > 0.0f ? v : 0.0f;
|
||||
live.push_back(b);
|
||||
}
|
||||
std::vector<int64_t> take;
|
||||
|
||||
+14
-3
@@ -360,8 +360,11 @@ int ref_quant_cols_fp8(const RadArgs* a, RadStream) {
|
||||
* ~0.2% error per group (a fifth of the int4 grid's own error).
|
||||
*
|
||||
* The output is not interchangeable with quant_act_fp8's: only a weight plane stored as w4a8h
|
||||
* carries the matching rotation and /g. */
|
||||
int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
* carries the matching rotation and /g.
|
||||
*
|
||||
* had_quant_act_i8g is the same at int8 codes (`top` 127), for the i8a8h weight, whose scale
|
||||
* carries the /g the same way. */
|
||||
static int had_quant_act_q8(const RadArgs* a, float top) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
@@ -383,7 +386,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
const int64_t k0 = gi * g;
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
|
||||
fwht(buf, g);
|
||||
const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, 448.0f, q,
|
||||
const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, top, q,
|
||||
qb + k0 * qs, qs);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
@@ -391,6 +394,14 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
return had_quant_act_q8(a, 448.0f);
|
||||
}
|
||||
|
||||
int ref_had_quant_act_i8g(const RadArgs* a, RadStream) {
|
||||
return had_quant_act_q8(a, 127.0f);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- givens_rotate */
|
||||
/* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages`
|
||||
* rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
|
||||
|
||||
+349
-7
@@ -118,8 +118,33 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st
|
||||
OPD_O("num_accepted"), OUT("y") };
|
||||
|
||||
static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") };
|
||||
/* The control vector's projection (libref/ref_hc.cpp, core/cvec.h): one unit direction per layer and a
|
||||
* per-row switch. `v` is f32 whatever the stream's dtype is, because the engine uploads the table
|
||||
* in f32; `on` is an int32 row mask (core derive.cpp's `projection_on_rows`). */
|
||||
static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") };
|
||||
static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") };
|
||||
static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") };
|
||||
static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") };
|
||||
static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") };
|
||||
static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") };
|
||||
static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"),
|
||||
P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"),
|
||||
P_STR("mode"), P_STR("dtype"), P_STRO("state_form") };
|
||||
static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"),
|
||||
WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"),
|
||||
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
|
||||
/* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the
|
||||
* sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */
|
||||
static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
@@ -137,6 +162,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
|
||||
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") };
|
||||
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") };
|
||||
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
|
||||
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
|
||||
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") };
|
||||
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") };
|
||||
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
|
||||
OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score"), OUT_O("cu_part") };
|
||||
static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"),
|
||||
OPD_O("page"), INOUT_O("cache") };
|
||||
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
|
||||
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") };
|
||||
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
/* `div` divides the rounded sum, rounded again (default 1, the plain sum): a mean of branches
|
||||
* summed pairwise, as a vocoder averages its residual blocks. */
|
||||
@@ -276,8 +317,10 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_
|
||||
static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"),
|
||||
OUT("y") };
|
||||
|
||||
/* `split_n` is libr4d's (docs/OPS.md): ref never splits K, so it accepts and ignores it. */
|
||||
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
|
||||
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") };
|
||||
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"),
|
||||
P_INTO("split_n") };
|
||||
/* The bias form has no parts (`pb1`/`pb2`); only the plain product supports them. */
|
||||
static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
|
||||
P_STR("dtype") };
|
||||
@@ -332,6 +375,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. */
|
||||
@@ -381,7 +431,7 @@ static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads")
|
||||
static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"),
|
||||
OUT("score") };
|
||||
static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"),
|
||||
P_INT("ratio"), P_INT("seqs") };
|
||||
P_INT("ratio"), P_INT("seqs"), P_INTO("signed") };
|
||||
static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"),
|
||||
OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") };
|
||||
static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"),
|
||||
@@ -658,6 +708,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"),
|
||||
@@ -666,12 +723,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. */
|
||||
@@ -693,12 +752,25 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma
|
||||
OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"),
|
||||
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
|
||||
INOUT("state"), INOUT_O("preview") };
|
||||
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
|
||||
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"),
|
||||
OPD("seed"), OPD("cu_seqlens"), INOUT("state"),
|
||||
OUT("y") };
|
||||
static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"),
|
||||
OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"),
|
||||
OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"),
|
||||
OPD("cu_seqlens"), INOUT("state"), INOUT("hist"),
|
||||
INOUT_O("preview") };
|
||||
/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */
|
||||
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
|
||||
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
|
||||
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") };
|
||||
static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") };
|
||||
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
|
||||
P_STR("pad"), P_INT("up"), P_STR("dtype") };
|
||||
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
|
||||
static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") };
|
||||
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
|
||||
@@ -761,7 +833,7 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
|
||||
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
|
||||
P_INTO("reflect") };
|
||||
P_INTO("reflect"), P_STRO("tpad"), P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
|
||||
OPD_O("res"), OUT("y") };
|
||||
/* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */
|
||||
@@ -777,6 +849,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"),
|
||||
@@ -836,6 +954,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 */
|
||||
@@ -857,6 +977,33 @@ static const RadOpSchema kSchemas[] = {
|
||||
"is what every fused implementation does." },
|
||||
{ "hc_enter", ARR(pHcWrite), ARR(oHcEnter),
|
||||
"h[s] = x for each of the hc streams -- the wide residual stream's first value. Shares `hc_write`'s parameter list." },
|
||||
{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre),
|
||||
"Manifold hyper-connection read: RMS-scaled projection of the whole hc*n residual, sigmoid "
|
||||
"pre/post gates and Sinkhorn mixing. x has dtype, post and comb are f32. comb is indexed "
|
||||
"[source,destination]. First pass is row softmax + hc_eps then column normalization; later "
|
||||
"passes add hc_eps to both normalization denominators. hc is 2..8; iterations is 1..256." },
|
||||
{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial),
|
||||
"mhc_pre's projection split by residual columns. Chunk c covers columns [c*chunk, (c+1)*chunk) "
|
||||
"of the hc*n row; for chunks [first, first+chunks) part[m, (c-first)*S + j] is the sum over the "
|
||||
"chunk of h*fn[j] for j < hc*(hc+2) and of h*h for j = hc*(hc+2), with S = hc*(hc+2)+1 rounded "
|
||||
"up to a multiple of 4 and the slots past the last zero. chunk divides hc*n. Tensor-parallel "
|
||||
"ranks each compute their chunks and an all_gather (row = chunks*S) joins them." },
|
||||
{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish),
|
||||
"mhc_pre from mhc_pre_partial's matrix over all hc*n/chunk chunks: each coefficient and the sum "
|
||||
"of squares is the sum of its chunks' partials (the order is the implementation's), then "
|
||||
"mhc_pre's gates, Sinkhorn mixing and collapse of h. part and mhc_pre_partial over every chunk "
|
||||
"together are mhc_pre." },
|
||||
{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost),
|
||||
"out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]. post and comb are f32; "
|
||||
"out must not alias h. No normalization of the residual stream." },
|
||||
{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract),
|
||||
"x[i] = mean over hc streams h[stream,i], rounded once to dtype." },
|
||||
{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate),
|
||||
"L2-normalized KDA: per-channel decay exp(lower_bound*sigmoid(exp(A_log)*(a+dt_bias))), "
|
||||
"beta=sigmoid(b), S*=decay; S+=beta*(v-S*k)*k; o=scale*S*q. State is f32 [slot,heads,V,K]. "
|
||||
"verify reads state_idx[seq,num_accepted-1] and writes each candidate state_idx[seq,t]; "
|
||||
"prefill reads/writes column zero, committing only the final state. cu offsets are absolute; "
|
||||
"has_init=0 starts from zero and a negative initial slot emits zero output. No output norm." },
|
||||
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
|
||||
"The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, "
|
||||
"one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); "
|
||||
@@ -870,6 +1017,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "hc_write", ARR(pHcWrite), ARR(oHcWrite),
|
||||
"The write half: h[s] += inj[s] * y, for each of the hc streams of h. In place, and `h` is the "
|
||||
"UNNORMED stream the paired hc_read was handed -- the normalisation never enters the residual." },
|
||||
{ "hc_project", ARR(pHcProject), ARR(oHcProject),
|
||||
"The control vector's projection (llama.cpp's `--cvec-mode project`): for each of the hc "
|
||||
"streams of a row whose `on` flag is 1, h[s] -= scale * (h[s] . v) * v, with v that layer's unit "
|
||||
"direction and scale the norm the file stored. The dot is per stream, not on the stream mean. A "
|
||||
"row whose flag is 0 is not read and not written, so an unprojected request is byte-identical to "
|
||||
"a deployment with no vector loaded." },
|
||||
{ "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter),
|
||||
"The MTP head's entry for a wide residual stream: x[k*n+i] = fc_h[i] . grouped_norm(h)[k] "
|
||||
"+ fc_e[i] . norm(e), for each of the hc sub-streams k. `ngroup` == hc is one rsqrt per "
|
||||
@@ -893,6 +1046,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." },
|
||||
@@ -940,6 +1103,18 @@ static const RadOpSchema kSchemas[] = {
|
||||
"keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit "
|
||||
"= qf.k * ln(1+e)/ln2 + qf.relk[i-j]; softcap * tanh(logit / softcap); softmax; .v. f32, one "
|
||||
"rounding." },
|
||||
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
|
||||
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
|
||||
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
|
||||
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." },
|
||||
{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore),
|
||||
"Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." },
|
||||
{ "dsa_query", ARR(pMnD), ARR(oQuantFp8),
|
||||
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." },
|
||||
{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool),
|
||||
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." },
|
||||
{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp),
|
||||
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." },
|
||||
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
|
||||
"y[i] = silu(gate_up[i]) * gate_up[n + i]. The GATE IS THE FIRST HALF, which is the order "
|
||||
"rad-convert fuses gate and up into one weight in." },
|
||||
@@ -1073,6 +1248,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation "
|
||||
"block cannot straddle the end of a row. NOT interchangeable with quant_act_fp8 in either "
|
||||
"direction: the consumer must be a weight that was rotated the same way." },
|
||||
/* Its int8 twin, the activation of the i8a8h GEMMs; the factor of `group` is the weight's here
|
||||
* too. */
|
||||
{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
|
||||
"quant_act_i8g with a Walsh-Hadamard rotation of width `group` along n first: scale = "
|
||||
"amax(rotated) / 127 per group, [M, n/group] in f32, n a multiple of `group`. Pairs with an i8 "
|
||||
"weight rotated the same way, its scale carrying the factor of `group` (dtype i8a8h)." },
|
||||
/* The calibration op, the only one no forward pass issues: it runs under a calibration flag and
|
||||
* its output is read at convert time, in another process, through a file. `dtype` is the input's:
|
||||
* fp8a8 where the tap is a quantiser's output, bf16 without `a_scale` for a plain activation. */
|
||||
@@ -1100,6 +1281,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"y = q * scale, the inverse of quant_act_i8g. It does NOT undo a rotation." },
|
||||
|
||||
{ "gemm_nt", ARR(pGemm), ARR(oGemm), "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate." },
|
||||
{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm),
|
||||
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." },
|
||||
{ "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias),
|
||||
"gemm_nt with a per-column bias added in f32, rounded to y's dtype; then, optionally, `act` of "
|
||||
"that (\"gelu\" exact, \"gelu_tanh\" the tanh approximation, \"none\"), rounded; then `res` "
|
||||
@@ -1119,6 +1302,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
"slot[m] is in [0, S), f32 accumulate, j ascending, one rounding to y's dtype. A base row's `y` "
|
||||
"is neither read nor written, so it stays bit for bit what the GEMM wrote (not y + 0: that "
|
||||
"turns -0 into +0)." },
|
||||
{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand),
|
||||
"lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] + "
|
||||
"scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding to y's dtype. "
|
||||
"A base row's `y` is neither read nor written. A row's bytes may depend on M: the generators' "
|
||||
"expand, whose passes are many rows of one adapter." },
|
||||
|
||||
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
|
||||
"Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per "
|
||||
@@ -1132,6 +1320,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." },
|
||||
@@ -1189,6 +1384,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"when rows == n. `act` is \"sigmoid\" or \"none\", and it applies to the SCALAR. With `add` "
|
||||
"present the form is y = bf16(x * act(s)) + add -- the product NARROWED before the sum, which "
|
||||
"is what makes the fused form bit-identical to the pair it replaces." },
|
||||
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
|
||||
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
|
||||
{ "router_topk", ARR(pRouter), ARR(oRouter),
|
||||
"Softmax over ALL n_expert logits, then the top_k by probability with ties to the lower expert "
|
||||
"id, then -- if `norm` -- renormalise the kept weights to sum to one." },
|
||||
@@ -1397,6 +1594,15 @@ static const RadOpSchema kSchemas[] = {
|
||||
"one Euler step of a flow-matching sampler per entry that moves a lane: guidance against the "
|
||||
"paired entry, x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)), a preview of the clean "
|
||||
"latent with flag 4, the kept region of a repaint restored with flag 2 (docs/OPS.md)." },
|
||||
{ "kd_input", ARR(pLane), ARR(oKdInput),
|
||||
"a k-diffusion sampler's model input per entry that moves a lane: on a first step the lane "
|
||||
"becomes its seed's normal stream times sqrt(1 + sigma^2); y = rd(x / sqrt(sigma^2 + 1)) at the "
|
||||
"entry's rows and at its pair's (docs/OPS.md)." },
|
||||
{ "kd_step", ARR(pKdStep), ARR(oKdStep),
|
||||
"one k-diffusion sampler step over a discrete-time denoiser per entry that moves a lane: the "
|
||||
"clean estimate D from an eps or v output, guided against the pair, then Euler, Euler ancestral "
|
||||
"or DPM++ 2M by the entry's sampler, the lane f32; flag 4 previews D, `hist` keeps it "
|
||||
"(docs/OPS.md)." },
|
||||
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
|
||||
"a per-channel affine from two parameter lists of n values (rounded to bf16): `fma` is "
|
||||
"bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul). `round` 0 keeps the lists and "
|
||||
@@ -1406,6 +1612,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
"the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input "
|
||||
"upsampled nearest-neighbour; `pad` same (k/2 a side) or down (0 above and left, 1 below and "
|
||||
"right)." },
|
||||
{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary),
|
||||
"conv2d_nhwc's receptive fields as rows: x [Hin, Win * cin], y [Hout * Wout, cin * k * k], row "
|
||||
"oy * Wout + ox and column (ci * k + i) * k + j the value conv2d_nhwc multiplies weight[o, ci, "
|
||||
"i, j] by (0 in the padding), so y @ w.reshape(cout, cin * k * k)^T + b is the convolution; "
|
||||
"`up`, `pad` and `stride` as conv2d_nhwc reads them." },
|
||||
{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm),
|
||||
"each row normalised to unit L2 (eps 1e-12), times sqrt(n), times gamma -- three bf16 roundings "
|
||||
"-- then `act` none or silu: an image decoder's channel norm." },
|
||||
@@ -1419,6 +1630,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them: "
|
||||
"round(clamp(bf16(bf16(clamp(x) / 2) + 0.5), 0, 1) * 255), u8 out." },
|
||||
{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." },
|
||||
{ "gelu_quick", ARR(pMnD), ARR(oUnary),
|
||||
"CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." },
|
||||
{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows),
|
||||
"x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." },
|
||||
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
|
||||
@@ -1512,6 +1725,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 "
|
||||
@@ -1578,6 +1838,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 */
|
||||
@@ -1711,6 +1974,18 @@ SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D
|
||||
ref_rmsnorm_add),
|
||||
SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
|
||||
ref_hc_enter),
|
||||
SIMPLE("ref_mhc_pre", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", DT_FLOAT,
|
||||
ref_mhc_pre),
|
||||
SIMPLE("ref_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold residual projection partials", DT_FLOAT,
|
||||
ref_mhc_pre_partial),
|
||||
SIMPLE("ref_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold residual gates from projection partials", DT_FLOAT,
|
||||
ref_mhc_pre_finish),
|
||||
SIMPLE("ref_mhc_post", "mhc_post", "norm", "manifold residual source-to-destination update", DT_FLOAT,
|
||||
ref_mhc_post),
|
||||
SIMPLE("ref_mhc_contract", "mhc_contract", "norm", "mean of manifold residual streams", DT_FLOAT,
|
||||
ref_mhc_contract),
|
||||
SIMPLE("ref_kda_update", "kda_update", "gdn", "bounded per-channel delta recurrence and candidate rollback", DT_FLOAT,
|
||||
ref_kda_update),
|
||||
ROWL("ref_hc_read", "hc_read", "norm",
|
||||
"gated residual read: grouped norm, low-rank gate, stream mix",
|
||||
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined",
|
||||
@@ -1721,6 +1996,9 @@ ROWL("ref_mtp_enter", "mtp_enter", "norm",
|
||||
ref_check_dtypes, ref_mtp_enter, ref::ref_layout_mtp),
|
||||
SIMPLE("ref_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y",
|
||||
DT_FLOAT, ref_hc_write),
|
||||
SIMPLE("ref_hc_project", "hc_project", "norm",
|
||||
"control vector: h[s] -= scale * (h[s] . v) * v where the row's flag is on",
|
||||
DT_FLOAT, ref_hc_project),
|
||||
SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT,
|
||||
ref_layernorm),
|
||||
SIMPLE("ref_grid_embed", "grid_embed", "elem",
|
||||
@@ -1730,11 +2008,31 @@ SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem",
|
||||
ref_grid_embed_aa),
|
||||
SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add),
|
||||
SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul),
|
||||
SIMPLE("ref_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT,
|
||||
ref_mla_attn),
|
||||
SIMPLE("ref_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT,
|
||||
ref_dsa_score),
|
||||
SIMPLE("ref_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT,
|
||||
ref_dsa_pool),
|
||||
SIMPLE("ref_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT,
|
||||
ref_dsa_query),
|
||||
SIMPLE("ref_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
|
||||
ref_gemm_nt_f32),
|
||||
SIMPLE("ref_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT,
|
||||
ref_mla_project),
|
||||
SIMPLE("ref_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT,
|
||||
ref_swiglu_clamped),
|
||||
SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
|
||||
ref_silu_mul),
|
||||
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",
|
||||
@@ -1816,6 +2114,10 @@ SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant",
|
||||
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
|
||||
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
|
||||
ref_had_quant_act_fp8),
|
||||
SIMPLE("ref_had_quant_act_i8g", "had_quant_act_i8g", "quant",
|
||||
"width-`group` Hadamard, then the symmetric int8 quantiser, one scale per group",
|
||||
"float in, i8 out, f32 scale per group; n a multiple of group",
|
||||
ref_had_quant_act_i8g),
|
||||
SIMPLE("ref_gram_accum", "gram_accum", "quant",
|
||||
"h += x^T x over a dequantised E4M3 activation, or a plain bf16 one -- the Gram matrix "
|
||||
"GPTQ calibrates on",
|
||||
@@ -1848,6 +2150,9 @@ SIMPLE("ref_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base
|
||||
SIMPLE("ref_lora_expand", "lora_expand", "gemm",
|
||||
"y += scale * (t B[slot]^T) per row, base rows untouched",
|
||||
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand),
|
||||
SIMPLE("ref_lora_expand_mm", "lora_expand_mm", "gemm",
|
||||
"y += scale * (bf16(t) B[slot]^T) per row, base rows untouched",
|
||||
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand_mm),
|
||||
|
||||
ROW("ref_attn_paged", "attn_paged", "attn",
|
||||
"paged causal / sliding-window attention, any query length",
|
||||
@@ -1856,6 +2161,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),
|
||||
@@ -1865,6 +2175,8 @@ SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary
|
||||
|
||||
SIMPLE("ref_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row",
|
||||
DT_FLOAT, ref_scale_rows),
|
||||
SIMPLE("ref_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
|
||||
ref_router_sigmoid_topk),
|
||||
SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
|
||||
ref_router_topk),
|
||||
SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
|
||||
@@ -1978,10 +2290,16 @@ SIMPLE("ref_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's
|
||||
DT_FLOAT, ref_randn_lanes),
|
||||
SIMPLE("ref_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance",
|
||||
DT_FLOAT, ref_flow_euler),
|
||||
SIMPLE("ref_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT,
|
||||
ref_kd_input),
|
||||
SIMPLE("ref_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT,
|
||||
ref_kd_step),
|
||||
SIMPLE("ref_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists",
|
||||
DT_FLOAT, ref_chan_affine),
|
||||
SIMPLE("ref_conv2d_nhwc", "conv2d_nhwc", "elem", "an image convolution, channels innermost",
|
||||
DT_FLOAT, ref_conv2d_nhwc),
|
||||
SIMPLE("ref_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows",
|
||||
DT_FLOAT, ref_im2col_nhwc),
|
||||
SIMPLE("ref_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu",
|
||||
DT_FLOAT, ref_l2norm_chan),
|
||||
SIMPLE("ref_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT,
|
||||
@@ -1990,6 +2308,7 @@ SIMPLE("ref_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added
|
||||
ref_s2d_avg_add),
|
||||
SIMPLE("ref_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, ref_to_rgba8),
|
||||
SIMPLE("ref_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, ref_gelu_tanh),
|
||||
SIMPLE("ref_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, ref_gelu_quick),
|
||||
SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT,
|
||||
ref_scatter_add_rows),
|
||||
SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn",
|
||||
@@ -2031,6 +2350,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",
|
||||
@@ -2064,6 +2404,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 */
|
||||
|
||||
+569
-12
@@ -336,6 +336,95 @@ int ref_hc_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
return o.finish("hc_enter", operand, out);
|
||||
}
|
||||
|
||||
int ref_kda_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const char* form = gs(p, n_p, "state_form");
|
||||
// Replay records and aliased engine index columns require a hand-built fixture.
|
||||
if (form && !std::strcmp(form,"anchor")) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0);
|
||||
const int64_t K = gi(p, n_p, "head_k", 0), V = gi(p, n_p, "head_v", 0);
|
||||
if (M < 1 || H < 1 || K < 1 || K > 128 || V < 1 || V > 128) return RAD_E_UNSUPPORTED;
|
||||
const char* mode = gs(p, n_p, "mode");
|
||||
const int64_t history = mode && !std::strcmp(mode, "verify") ? M : 1;
|
||||
Opd o;
|
||||
o.t(D, {M, H, K}); o.t(D, {M, H, K}); o.t(D, {M, H, V});
|
||||
o.t(D, {M, H, K}); o.t(D, {M, H});
|
||||
o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H * K});
|
||||
o.t((uint32_t)RAD_F32, {history + 1, H, V, K});
|
||||
o.t_idx({1, history}, history + 1, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE);
|
||||
o.t_idx({2}, M, -1, (uint32_t)RAD_OPD_F_IDX_CU);
|
||||
o.t_idx({1}, 0, 1, 0); o.t_idx({1}, 0, 1, 0);
|
||||
o.t(D, {M, H, V});
|
||||
return o.finish("kda_update", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_pre_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n});
|
||||
o.t((uint32_t)RAD_F32, {3});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2)});
|
||||
o.t(D, {M, n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc});
|
||||
o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
return o.finish("mhc_pre", operand, out);
|
||||
}
|
||||
|
||||
static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
|
||||
int ref_mhc_pre_partial_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
|
||||
const int64_t chunk = gi(p, n_p, "chunk", 0), chunks = gi(p, n_p, "chunks", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || chunks <= 0)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n});
|
||||
o.t((uint32_t)RAD_F32, {M, chunks * mhc_part_stride(hc)});
|
||||
return o.finish("mhc_pre_partial", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_pre_finish_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
|
||||
const int64_t chunk = gi(p, n_p, "chunk", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t((uint32_t)RAD_F32, {M, hc * n / chunk * mhc_part_stride(hc)});
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {3});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2)});
|
||||
o.t(D, {M, n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc});
|
||||
o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
return o.finish("mhc_pre_finish", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_post_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, n}); o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc}); o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
o.t(D, {M, hc * n});
|
||||
return o.finish("mhc_post", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_contract_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n}); o.t(D, {M, n});
|
||||
return o.finish("mhc_contract", operand, out);
|
||||
}
|
||||
|
||||
int ref_hc_write_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);
|
||||
@@ -347,6 +436,17 @@ int ref_hc_write_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
return o.finish("hc_write", operand, out);
|
||||
}
|
||||
|
||||
int ref_hc_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t hc = gi(p, n_p, "hc", 0);
|
||||
Opd o;
|
||||
o.t(D, { M, hc * n }); /* h, in place */
|
||||
o.t((uint32_t) RAD_F32, { n }); /* v: one layer's unit direction */
|
||||
o.t((uint32_t) RAD_I32, { M }); /* on: 1 = this row takes the projection */
|
||||
return o.finish("hc_project", operand, out);
|
||||
}
|
||||
|
||||
int ref_mtp_enter_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);
|
||||
@@ -583,6 +683,88 @@ int ref_attn_local_rel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
|
||||
return o.finish("attn_local_rel", operand, out);
|
||||
}
|
||||
|
||||
int ref_swiglu_clamped_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return ref_silu_mul_shape(p, n_p, operand, out);
|
||||
}
|
||||
int ref_router_sigmoid_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0),
|
||||
k = gi(p, n_p, "top_k", 0);
|
||||
if (M < 1 || ne < 1 || ne > 512 || k < 1 || k > ne) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, ne });
|
||||
o.t(RAD_F32, { ne });
|
||||
o.t_idx({ M, k }, ne, -1, 0);
|
||||
o.t(D, { M, k });
|
||||
return o.finish("router_sigmoid_topk", operand, out);
|
||||
}
|
||||
int ref_mla_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0),
|
||||
l = gi(p, n_p, "latent_dim", 0);
|
||||
const char* mode = gs(p, n_p, "mode");
|
||||
const bool absorb = mode && !std::strcmp(mode, "absorb"),
|
||||
expand = mode && !std::strcmp(mode, "expand");
|
||||
if (M < 1 || h < 1 || d < 1 || l < 1 || (!absorb && !expand)) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, h, absorb ? d : l });
|
||||
o.t(RAD_BF16, { h * 2 * d, l });
|
||||
o.t(RAD_BF16, { M, h, absorb ? l : d });
|
||||
return o.finish("mla_project", operand, out);
|
||||
}
|
||||
int ref_dsa_query_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 < 1 || n < 1 || n > 256 || (n & (n - 1))) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, n });
|
||||
o.t(RAD_F8E4M3, { M, n });
|
||||
o.t(RAD_F32, { M, 1 });
|
||||
return o.finish("dsa_query", operand, out);
|
||||
}
|
||||
int ref_dsa_pool_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), ratio = gi(p, n_p, "ratio", 0);
|
||||
if (M < 1 || n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M * ratio, 2 * n });
|
||||
o.t(RAD_F32, { ratio, n });
|
||||
o.t(RAD_F8E4M3, { M, n });
|
||||
o.t(RAD_F32, { M, 1 });
|
||||
o.skip();
|
||||
o.skip(); // Optional paged cache writes use a hand-built unique page list.
|
||||
return o.finish("dsa_pool", operand, out);
|
||||
}
|
||||
int ref_dsa_score_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), H = gi(p, n_p, "heads", 0);
|
||||
const int64_t B = gi(p, n_p, "blocks", 0), S = gi(p, n_p, "seqs", 0), pages = S * B;
|
||||
if (M < 1 || n < 1 || H < 1 || H > 64 || B < 1 || S < 1 || S > M) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_F8E4M3, { M, H, n });
|
||||
o.t_fill(RAD_F32, { M, H }, RAD_FILL_SIGMOID, 0);
|
||||
o.t(RAD_F32, { M, H });
|
||||
o.t(RAD_F8E4M3, { pages, n });
|
||||
o.t_fill(RAD_F32, { pages }, RAD_FILL_SIGMOID, 0);
|
||||
o.t_idx({ S, B }, pages, -1, 0);
|
||||
o.t_idx({ S + 1 }, M, -1, RAD_OPD_F_IDX_CU);
|
||||
o.t_idx({ S }, 0, B, 0);
|
||||
o.t(RAD_F32, { M, B });
|
||||
o.skip(); // cu_part: a part's rebased bounds, exercised by the split's own tests.
|
||||
return o.finish("dsa_score", operand, out);
|
||||
}
|
||||
int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "latent_dim", 0),
|
||||
H = gi(p, n_p, "heads", 0);
|
||||
const int64_t B = gi(p, n_p, "blocks", 0), bs = gi(p, n_p, "block_size", 0),
|
||||
pages = std::max((int64_t)2, B * M);
|
||||
if (M < 1 || D < 1 || D > 2048 || H < 1 || B < 1 || bs < 1) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t dtype = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(dtype, { M, H, D });
|
||||
o.t(dtype, { pages, 1, bs, D });
|
||||
o.t_idx({ M, B }, pages, -1, 0);
|
||||
o.t_idx({ M }, 0, B * bs, 0);
|
||||
o.t(dtype, { M, H, D });
|
||||
return o.finish("mla_attn", operand, out);
|
||||
}
|
||||
int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
@@ -873,6 +1055,18 @@ int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD
|
||||
return o.finish("had_quant_act_fp8", operand, out);
|
||||
}
|
||||
|
||||
/* quant_act_i8g's extents: the rotation changes the values, not the shapes. */
|
||||
int ref_had_quant_act_i8g_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
Opd o;
|
||||
o.t(D, { M, n }); /* x */
|
||||
o.t((uint32_t)RAD_I8, { M, n }); /* q */
|
||||
o.t((uint32_t)RAD_F32, { M, ng }); /* scale (amax / 127) */
|
||||
return o.finish("had_quant_act_i8g", operand, out);
|
||||
}
|
||||
|
||||
/* The int8 rotated forms: `group` is the Walsh-Hadamard rotation width (libr4d's `had`) and the
|
||||
* scale is one per row, carrying the 1/sqrt(group) normalisation (ref_quant.cpp). Describing it as
|
||||
* [M, n/group] would leave the tail of every scale buffer unwritten by both sides, comparing two
|
||||
@@ -929,6 +1123,15 @@ int ref_dequant_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
|
||||
/* ================================================================== gemm */
|
||||
|
||||
int ref_gemm_nt_f32_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), K = gi(p, n_p, "K", 0);
|
||||
if (M < 1 || N < 1 || K < 1) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, K });
|
||||
o.t(RAD_F32, { N, K });
|
||||
o.t(RAD_F32, { M, N });
|
||||
return o.finish("gemm_nt_f32", operand, out);
|
||||
}
|
||||
int ref_gemm_nt_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);
|
||||
@@ -969,8 +1172,10 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
|
||||
const int64_t group = gi(p, n_p, "group", 0);
|
||||
const char* q = gs(p, n_p, "dtype");
|
||||
auto is = [&](const char* s) { return q && std::strcmp(q, s) == 0; };
|
||||
const bool a8 = is("fp8a8"), a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8");
|
||||
const bool i8 = is("i8a8"), mx = is("mxfp4a8");
|
||||
const bool f32s = is("fp8a8f32");
|
||||
const bool a8 = is("fp8a8") || f32s, a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8");
|
||||
/* i8a8h is i8a8's operands; its rotation is in the values. */
|
||||
const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8");
|
||||
if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
/* Neither has a bias form in any architecture. */
|
||||
@@ -1012,7 +1217,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
|
||||
o.skip(); /* a_scale */
|
||||
}
|
||||
o.t((uint32_t)RAD_F8E4M3, { N, K }); /* b -- the checkpoint's own bytes */
|
||||
o.t((uint32_t)RAD_BF16, { nb, kb }); /* b_scale -- weight_scale_inv, per 128x128 */
|
||||
/* b_scale -- weight_scale_inv, per 128x128; f32 at fp8a8f32 */
|
||||
o.t(f32s ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16, { nb, kb });
|
||||
}
|
||||
if (bias) {
|
||||
o.t((uint32_t)RAD_BF16, { N }); /* bias */
|
||||
@@ -1070,6 +1276,10 @@ int ref_lora_expand_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
return o.finish("lora_expand", operand, out);
|
||||
}
|
||||
|
||||
int ref_lora_expand_mm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return ref_lora_expand_shape(p, n_p, operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== attention
|
||||
*
|
||||
* The paged layout (ref_ops.h):
|
||||
@@ -1144,6 +1354,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);
|
||||
@@ -1457,7 +1721,8 @@ struct MoeScaleGrid { int64_t rows, k; };
|
||||
static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) {
|
||||
const char* d = gs(p, n_p, "dtype");
|
||||
auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; };
|
||||
if (is("fp8a8")) return { g, g };
|
||||
if (is("fp8a8") || is("fp8a8f32")) return { g, g };
|
||||
if (is("mxfp4a8")) return { 1, 32 };
|
||||
if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g };
|
||||
if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 };
|
||||
if (is("w4nl32a8h")) return { 1, g / 4 };
|
||||
@@ -1487,14 +1752,21 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
|
||||
const char* kind = gs(p, n_p, "dtype");
|
||||
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
|
||||
const auto SD = kind && !std::strcmp(kind, "fp8a8f32") ? (uint32_t)RAD_F32 : D;
|
||||
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
|
||||
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
|
||||
o.t((uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); /* w -- the even experts */
|
||||
o.t(D, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); /* w_scale */
|
||||
/* w -- the even experts; mxfp4a8 carries e2m1 codes with an E8M0 byte per (row, 32 of K) */
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne0, N0, K0 });
|
||||
if (mx) o.t_idx_dt(RAD_U8, { ne0, N0, (K0 + 31) / 32 }, 0, 127, 0); /* w_scale */
|
||||
else o.t(SD, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k });
|
||||
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
|
||||
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
|
||||
o.t((uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); /* w_odd -- the odd experts */
|
||||
o.t(D, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); /* w_odd_scale */
|
||||
/* w_odd -- the odd experts */
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne1, N1, K1 });
|
||||
if (mx) o.t_idx_dt(RAD_U8, { ne1, N1, (K1 + 31) / 32 }, 0, 127, 0); /* w_odd_scale */
|
||||
else o.t(SD, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k });
|
||||
o.t(D, { M * k, N }); /* y -- in sorted order */
|
||||
return o.finish("moe_gemm_q", operand, out);
|
||||
}
|
||||
@@ -1522,10 +1794,13 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
|
||||
const char* kind = gs(p, n_p, "dtype");
|
||||
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
|
||||
auto cls = [&](int q) {
|
||||
const int64_t nq = (ne + 3 - q) / 4;
|
||||
o.t((uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
|
||||
o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
|
||||
if (mx) o.t_idx_dt(RAD_U8, {nq, Nq[q], (Kq[q] + 31) / 32}, 0, 127, 0);
|
||||
else o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
|
||||
};
|
||||
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
|
||||
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
|
||||
@@ -2212,7 +2487,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 */
|
||||
@@ -2231,7 +2509,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 */
|
||||
@@ -2363,6 +2643,53 @@ int ref_flow_euler_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return o.finish("flow_euler", operand, out);
|
||||
}
|
||||
|
||||
/* The k-diffusion sampler's two ops over flow_euler's entries: two equal-length entries where M
|
||||
* allows, the lanes f32, sigmas drawn in (0, 1) so every logarithm and root is of a positive
|
||||
* value. Flags draw only the first step (bit 1): the preview needs its optional operand and
|
||||
* neither op repaints; the hand-written cases take the rest. */
|
||||
int ref_kd_input_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), st = gi(p, n_p, "stride", 0);
|
||||
if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1;
|
||||
if (M > S * st) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t F = (uint32_t)RAD_F32;
|
||||
Opd o;
|
||||
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
|
||||
o.t_idx({ S }, S, -1, 0); /* pair */
|
||||
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ S }, 2, -1, 0); /* flags */
|
||||
o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(F, { REF_LANES * st, n }); /* state, INOUT */
|
||||
o.t(act_dt(p, n_p), { M, n }); /* y */
|
||||
return o.finish("kd_input", operand, out);
|
||||
}
|
||||
|
||||
int ref_kd_step_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), st = gi(p, n_p, "stride", 0);
|
||||
if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1;
|
||||
if (M > S * st) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t F = (uint32_t)RAD_F32;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), { M, n }); /* out */
|
||||
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
|
||||
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_next */
|
||||
o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_prev */
|
||||
o.t(F, { S }); /* cfg */
|
||||
o.t_idx({ S }, S, -1, 0); /* pair */
|
||||
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ S }, 2, -1, 0); /* flags */
|
||||
o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */
|
||||
o.t_idx({ S }, 3, -1, 0); /* sampler */
|
||||
o.t_idx({ S }, 64, -1, 0); /* step */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(F, { REF_LANES * st, n }); /* state, INOUT */
|
||||
o.t(F, { REF_LANES * st, n }); /* hist, INOUT */
|
||||
o.t(F, { REF_LANES * st, n }); /* preview, INOUT */
|
||||
return o.finish("kd_step", operand, out);
|
||||
}
|
||||
|
||||
/* ---- an image decoder's convolutions and shortcuts. Sizes are read off the operands and M counts
|
||||
* output pixels, so this picks eight columns where M allows (a row with both edges and an interior)
|
||||
* and the input that produces that output; otherwise it declines. */
|
||||
@@ -2397,6 +2724,27 @@ int ref_conv2d_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o
|
||||
return o.finish("conv2d_nhwc", operand, out);
|
||||
}
|
||||
|
||||
/* conv2d_nhwc's geometry with the receptive fields as y's rows: M output pixels of cin k k values. */
|
||||
int ref_im2col_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), k = gi(p, n_p, "k", 0);
|
||||
const int64_t stride = gi(p, n_p, "stride", 1), up = gi(p, n_p, "up", 1);
|
||||
const char* pad = gs(p, n_p, "pad");
|
||||
if (M <= 0 || cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_UNSUPPORTED;
|
||||
const bool down = pad && !std::strcmp(pad, "down");
|
||||
const int64_t pads = down ? 1 : 2 * (k / 2);
|
||||
const int64_t Wo = cols_for(M, 1), Ho = Wo ? M / Wo : 0;
|
||||
if (!Wo) return RAD_E_UNSUPPORTED;
|
||||
const int64_t Hv = (Ho - 1) * stride + k - pads, Wv = (Wo - 1) * stride + k - pads;
|
||||
if (Hv <= 0 || Wv <= 0 || Hv % up || Wv % up) return RAD_E_UNSUPPORTED;
|
||||
if ((Hv + pads - k) / stride + 1 != Ho || (Wv + pads - k) / stride + 1 != Wo)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { Hv / up, (Wv / up) * cin }); /* x */
|
||||
o.t(D, { Ho * Wo, cin * k * k }); /* y */
|
||||
return o.finish("im2col_nhwc", operand, out);
|
||||
}
|
||||
|
||||
int ref_d2s_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
|
||||
if (M <= 0 || cin <= 0 || cout <= 0) return RAD_E_UNSUPPORTED;
|
||||
@@ -2506,6 +2854,14 @@ int ref_gelu_tanh_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
|
||||
o.t(D, { M, n });
|
||||
return o.finish("gelu_tanh", operand, out);
|
||||
}
|
||||
int ref_gelu_quick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, n });
|
||||
o.t(D, { M, n });
|
||||
return o.finish("gelu_quick", operand, out);
|
||||
}
|
||||
int ref_scatter_add_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);
|
||||
@@ -3043,3 +3399,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);
|
||||
}
|
||||
+24
-6
@@ -370,8 +370,18 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) {
|
||||
* ((W + pl + pr - k) / stride + 1) (floor divisions)
|
||||
*
|
||||
* with ft / bk and pt / pb / pl / pr the front / back and top / bottom / left / right pads. The
|
||||
* time axis is always zero-padded; `reflect` mirrors each spatial axis once, torch's `reflect`
|
||||
* (x[-n] = x[n], x[D + n] = x[D - 2 - n]), so each pad must be below the axis it pads. */
|
||||
* time axis is zero-padded unless `tpad` says otherwise (below); `reflect` mirrors each spatial
|
||||
* axis once, torch's `reflect` (x[-n] = x[n], x[D + n] = x[D - 2 - n]), so each pad must be below
|
||||
* the axis it pads.
|
||||
*
|
||||
* `tpad` sets the frames' padding (rows and columns stay zero-padded): `zero` (the default),
|
||||
* `replicate` (the edge frame repeated, kt/2 a side: LTX-2's decoder) or `causal` (the first
|
||||
* frame repeated kt - 1 times in front, nothing after: LTX-2's encoder). With `causal`, `tpre`
|
||||
* more copies of the first frame stand in front of those, and y has T + tpre frames (LTX-2's
|
||||
* temporal downsampler, which prepends its first frame before its convolution). It folds into
|
||||
* the same grid math: replicate keeps ft = kt / 2 and clamps the time reads to the volume;
|
||||
* causal-`tpre` takes ft = kt - 1 + tpre and bk = 0, clamping below. `tpad` `causal` repeats
|
||||
* where `causal` 1 zeroes, and the two are refused together. */
|
||||
static int64_t idiv_floor(int64_t a, int64_t b) {
|
||||
const int64_t q = a / b;
|
||||
return (a % b && (a < 0) != (b < 0)) ? q - 1 : q;
|
||||
@@ -382,21 +392,27 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) {
|
||||
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 sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
|
||||
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
|
||||
const char* pads = p_str(a, "pad", "same");
|
||||
const bool down = pads && !std::strcmp(pads, "down");
|
||||
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
|
||||
(causal && tpad) /* zero-causal and replicated-causal contradict */ ||
|
||||
!(!pads || !std::strcmp(pads, "same") || down))
|
||||
return RAD_E_SHAPE;
|
||||
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
|
||||
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
|
||||
const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2);
|
||||
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
|
||||
const int64_t ft = causal ? kt - 1 : kt / 2, bk = causal ? 0 : kt / 2;
|
||||
const int64_t ft = causal ? kt - 1 : tpad == 2 ? kt - 1 + tpre : kt / 2;
|
||||
const int64_t bk = (causal || tpad == 2) ? 0 : kt / 2;
|
||||
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= W)) return RAD_E_SHAPE;
|
||||
@@ -418,7 +434,9 @@ 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 * st + dz - ft;
|
||||
int64_t tz = t * st + dz - ft;
|
||||
if (tpad) /* replicate and causal-tpre clamp; `zero`/`causal` pad */
|
||||
tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
|
||||
if (tz < 0 || tz >= T) continue;
|
||||
for (int64_t kh = 0; kh < k; ++kh) {
|
||||
int64_t iy = i * sp + kh - pt;
|
||||
|
||||
Reference in new issue
Block a user