Archived
radiance 1.8.0
- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text on OpenAI's /v1/videos, block fp8 on two cards - music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech - speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket - runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105) - several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes the snapshot store by --max-num-seqs (#108) - the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound, ModelOpt NVFP4 (#110) - the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106) - plugin ABI 21: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
91127395ee
commit
7a7707a955
179 files changed
+37542
-1892
No files matched your search
+66
-30
@@ -264,9 +264,15 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
|
||||
* itself (a chunked encoder's windows). `cu_div` reads cu_seqlens in units of that many rows:
|
||||
* a segment is rows [cu[s] / cu_div, cu[s+1] / cu_div). */
|
||||
const int64_t window = p_int(a, "window", 0);
|
||||
/* Non-causal only: the window's right side, key j visible when j - i < window_right; 0 is
|
||||
* `window`'s. A sliding encoder layer that sees `l` keys behind and `r` ahead is window l + 1,
|
||||
* window_right r + 1. */
|
||||
const int64_t wright = p_int(a, "window_right", 0);
|
||||
const int64_t block = p_int(a, "block", 0);
|
||||
const int64_t cdiv = p_int(a, "cu_div", 1);
|
||||
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE;
|
||||
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0 || wright < 0 ||
|
||||
(wright > 0 && (causal || window == 0)))
|
||||
return RAD_E_SHAPE;
|
||||
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
|
||||
/* [tokens, heads, head_dim], or [tokens, heads * head_dim] as a column slice of a fused
|
||||
@@ -308,7 +314,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
|
||||
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
|
||||
if (window > 0) {
|
||||
jbeg = std::max<int64_t>(b0, i - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(b1, i + window);
|
||||
if (!causal) jend = std::min<int64_t>(b1, i + (wright > 0 ? wright : window));
|
||||
}
|
||||
if (block > 0) {
|
||||
const int64_t blk = b0 + (i - b0) / block * block;
|
||||
@@ -477,6 +483,15 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot,
|
||||
}
|
||||
}
|
||||
|
||||
/* A position as the rotation reads it, divided by the position scale in f32: an integer operand's
|
||||
* value, or a float operand's own value (a fractional coordinate, such as a video decoder's
|
||||
* normalised grid already multiplied by 2 pi). */
|
||||
static inline float rope_pos(const RadTensor* pos, int64_t off, float div) {
|
||||
const uint32_t dt = pos->dtype;
|
||||
const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16;
|
||||
return (flt ? ld_dt(dt, pos->data, off) : (float)ld_int(dt, pos->data, off)) / div;
|
||||
}
|
||||
|
||||
/* "11 11 10" -> {11, 11, 10}. Absent is no sections. */
|
||||
static int rope_sections(const RadArgs* a, int64_t* sec) {
|
||||
const char* v = p_str(a, "sections", nullptr);
|
||||
@@ -551,6 +566,12 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
}
|
||||
const RadLlama3 l3 = rad_llama3_args(a);
|
||||
if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL;
|
||||
if (l3.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || multi) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = l3.frequency(f.inv[i]);
|
||||
}
|
||||
for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f;
|
||||
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
@@ -564,10 +585,9 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
float p[8];
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
if (multi) {
|
||||
for (int64_t c = 0; c < n_comp; ++c)
|
||||
p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div;
|
||||
for (int64_t c = 0; c < n_comp; ++c) p[c] = rope_pos(pos, c * pcs + m * pms, div);
|
||||
} else {
|
||||
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div;
|
||||
const float one = rope_pos(pos, offlin(pos, m), div);
|
||||
for (int c = 0; c < 8; ++c) p[c] = one;
|
||||
}
|
||||
const int64_t row = m * rs;
|
||||
@@ -581,14 +601,16 @@ int ref_rope(const RadArgs* a, RadStream) {
|
||||
/* ------------------------------------------------------------------ qk_norm_rope */
|
||||
/* QK-norm and rotation in one op: an RMS norm over each head_dim-wide q and k head against its own
|
||||
* gain vector, then RoPE. `v_norm` 1 also RMS-norms each v head with unit gain and no rotation
|
||||
* (Gemma 4's weightless value norm); otherwise v heads are untouched.
|
||||
* (Gemma 4's weightless value norm); otherwise v heads are untouched. An absent gain is a unit
|
||||
* gain, without `wadd` (a video decoder's weightless q and k norms); `rotary_dim` 0 is the norm
|
||||
* alone, and then `positions` may be absent.
|
||||
*
|
||||
* The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does;
|
||||
* libr4d's r4d_qk_norm_rope_gate matches this. A fused kernel keeping f32 across the seam would be
|
||||
* half a ULP better and fail the comparison. */
|
||||
int ref_qk_norm_rope(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
|
||||
if (a->n_t < 4 || !t_in(a, 0)) return RAD_E_INVAL;
|
||||
const RadTensor *qkv = &a->t[0], *pos = t_in(a, 1), *qw = t_in(a, 2), *kw = t_in(a, 3);
|
||||
|
||||
const int64_t head_dim = p_int(a, "head_dim", 0);
|
||||
const int64_t n_head = p_int(a, "n_head", 0);
|
||||
@@ -600,16 +622,21 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
|
||||
const int v_norm = (int)p_int(a, "v_norm", 0);
|
||||
/* `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j, start + 2j + 1):
|
||||
* the complex-number form of Qwen-Image's 3-axis rotary. `imrope` is `rope`'s interleaved
|
||||
* M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). */
|
||||
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
|
||||
const int mode = p_enum(a, "mode", kModes, 5, 0);
|
||||
* M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). `axial` is `rope`'s axial
|
||||
* form (a 3-axis video rotary over NeoX pairs), its section ladders applied with rank-1
|
||||
* positions too, every component then being that one position. */
|
||||
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" };
|
||||
const int mode = p_enum(a, "mode", kModes, 6, 0);
|
||||
if (mode < 0) return RAD_E_UNSUPPORTED;
|
||||
const bool blocks = mode == 2 || mode == 3;
|
||||
const bool adjacent = mode == 3;
|
||||
const bool im = mode == 4;
|
||||
const bool axial = mode == 5;
|
||||
int64_t rot = p_int(a, "rotary_dim", head_dim);
|
||||
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
|
||||
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
|
||||
if (head_dim <= 0 || n_head <= 0 || rot < 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
|
||||
if ((qw && numel(qw) < head_dim) || (kw && numel(kw) < head_dim)) return RAD_E_SHAPE;
|
||||
const bool turn = rot > 0;
|
||||
if (turn && !pos) return RAD_E_INVAL;
|
||||
|
||||
/* Blocks: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired
|
||||
* (start + j, start + sec[c] + j) and turned by position component comps[c] at
|
||||
@@ -617,11 +644,11 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
|
||||
* rotated prefix exactly. Positions are [C, M], component-major. */
|
||||
int64_t sec[8] = {}, comp[8] = {};
|
||||
int n_sec = 0;
|
||||
if (im) {
|
||||
if (turn && (im || axial)) {
|
||||
n_sec = rope_sections(a, sec);
|
||||
if (n_sec < 3) return RAD_E_SHAPE;
|
||||
if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE;
|
||||
}
|
||||
if (blocks) {
|
||||
if (turn && blocks) {
|
||||
n_sec = rope_sections(a, sec);
|
||||
if (n_sec <= 0) return RAD_E_SHAPE;
|
||||
int64_t total = 0;
|
||||
@@ -639,23 +666,31 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
|
||||
if (k != n_sec) return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
const bool multi = pos->rank >= 2;
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
const bool multi = pos && pos->rank >= 2;
|
||||
const int64_t n_comp = multi ? pos->shape[0] : 1;
|
||||
const int64_t M = multi ? pos->shape[1] : numel(pos);
|
||||
if (multi && !blocks && !im) return RAD_E_SHAPE;
|
||||
if (multi && im && n_comp < 3) return RAD_E_SHAPE;
|
||||
for (int c = 0; blocks && c < n_sec; ++c)
|
||||
if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE;
|
||||
const int64_t M = !pos ? rows_of(qkv, stride_row) : multi ? pos->shape[1] : numel(pos);
|
||||
if (turn) {
|
||||
if (multi && !blocks && !im && !axial) return RAD_E_SHAPE;
|
||||
if (multi && im && n_comp < 3) return RAD_E_SHAPE;
|
||||
if (multi && axial && n_comp < n_sec) return RAD_E_SHAPE;
|
||||
for (int c = 0; blocks && c < n_sec; ++c)
|
||||
if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE;
|
||||
}
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
|
||||
const int64_t rs = row_stride(qkv, stride_row);
|
||||
const int64_t ds = laststride(qkv);
|
||||
RopeFreq f;
|
||||
/* No `ladder` parameter here: the fused norm+rope measures by `rot`. */
|
||||
if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f));
|
||||
else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f));
|
||||
if (turn && im)
|
||||
RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f));
|
||||
else if (turn && axial)
|
||||
RAD_REF_TRY(rope_freqs(ROPE_AXIAL, rot, rot, theta, sec, n_sec, &f));
|
||||
else if (turn)
|
||||
RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f));
|
||||
const int pair_mode = im ? (int)ROPE_IMROPE : axial ? (int)ROPE_AXIAL : mode;
|
||||
|
||||
/* RMS-norms one head in place, against gain `w` (+ wadd), or unit gain without one. */
|
||||
auto norm_head = [&](int64_t base, const RadTensor* w) {
|
||||
@@ -675,19 +710,20 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
float p[8];
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
if (multi) {
|
||||
if (turn && multi) {
|
||||
for (int64_t c = 0; c < n_comp && c < 8; ++c)
|
||||
p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div;
|
||||
} else {
|
||||
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div;
|
||||
p[c] = rope_pos(pos, c * pcs + m * pms, div);
|
||||
} else if (turn) {
|
||||
const float one = rope_pos(pos, offlin(pos, m), div);
|
||||
for (int c = 0; c < 8; ++c) p[c] = one;
|
||||
}
|
||||
const int64_t row = m * rs;
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
|
||||
const int64_t base = row + h * head_dim * ds;
|
||||
norm_head(base, h < n_head ? qw : kw);
|
||||
if (!turn) continue;
|
||||
if (!blocks) {
|
||||
rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p);
|
||||
rope_head(qkv, base, ds, rot, pair_mode, f, p);
|
||||
continue;
|
||||
}
|
||||
int64_t start = 0;
|
||||
|
||||
@@ -0,0 +1,728 @@
|
||||
/* ref_audio.cpp -- the audio generator's ops (docs/OPS.md, "Audio generation").
|
||||
*
|
||||
* An audio generator writes a piece frame by frame with a language model and a depth decoder over
|
||||
* residual codebooks, sampled with guidance between branches; a denoiser turns runs of frames
|
||||
* (windows) into latents; a vocoder of 1-D convolutions plays them. These are the ops that are not
|
||||
* already a language model's or an image generator's.
|
||||
*
|
||||
* Rounding follows the reference models, which run in bf16 and round every tensor they
|
||||
* materialise; where an op stands for several reference tensors, the libref function says which
|
||||
* roundings it keeps. Per-pass extents (a window's latents, a sequence's rows) come from the
|
||||
* operands; parameters are fixed at declare.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include "rad_philox.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A window entry's flags (RadAudioGenBatch, RAD_AGEN_F_*), restated because a kernel library
|
||||
* compiles against rad_abi.h, not the run phase's header. */
|
||||
enum { kFirst = 1, kLast = 8, kJoin = 16 };
|
||||
|
||||
inline float rbf(float v) { return round_dt(RAD_BF16, v); }
|
||||
|
||||
/* The Philox stream an audio window's noise is drawn from, and the one a frame's picks are. */
|
||||
inline uint64_t window_stream(int64_t k) { return 1 + (uint64_t)k; }
|
||||
inline uint64_t frame_stream(int64_t f) { return ((uint64_t)1 << 32) + (uint64_t)f; }
|
||||
|
||||
inline uint64_t seed_at(const RadTensor* s, int64_t i) {
|
||||
return (uint64_t)(uint32_t)ld_int(s->dtype, s->data, offlin(s, 2 * i)) |
|
||||
((uint64_t)(uint32_t)ld_int(s->dtype, s->data, offlin(s, 2 * i + 1)) << 32);
|
||||
}
|
||||
|
||||
inline int64_t ldi(const RadTensor* t, int64_t i) {
|
||||
return ld_int(t->dtype, t->data, offlin(t, i));
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ conv1d */
|
||||
/* A 1-D convolution over sequences of rows, channels innermost: x [rows, cin], y [rows, cout],
|
||||
* `cu_seqlens` bounding each sequence (row indices of both operands, as every sequenced op reads
|
||||
* them), outside of which the input reads zero (each sequence is padded on its own). w is
|
||||
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
|
||||
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
|
||||
* dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none,
|
||||
* tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */
|
||||
int ref_conv1d(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2];
|
||||
const RadTensor *res = t_in(a, 3), *y = &a->t[4], *b = t_in(a, 5);
|
||||
if (!y->data) return RAD_E_INVAL;
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
|
||||
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
|
||||
const char* act = p_str(a, "act", "none");
|
||||
const bool tanh_out = act && !std::strcmp(act, "tanh");
|
||||
const bool clamp_out = act && !std::strcmp(act, "clamp");
|
||||
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
|
||||
if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE;
|
||||
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
|
||||
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2;
|
||||
REF_PAR_FOR((r1 - r0) * cout * cin * k)
|
||||
for (int64_t r = r0; r < r1; ++r) {
|
||||
const int64_t e = seq_of(cu, n_seq, r);
|
||||
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
|
||||
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
|
||||
for (int64_t co = 0; co < cout; ++co) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t kk = 0; kk < k; ++kk) {
|
||||
const int64_t ir = r + kk * dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
const int64_t xb = rowoff(x, ir, cin), xs = laststride(x);
|
||||
for (int64_t ci = 0; ci < cin; ++ci)
|
||||
acc += ldt(w, (co * cin + ci) * k + kk) * ldt(x, xb + ci * xs);
|
||||
}
|
||||
if (b) acc += ldt(b, co);
|
||||
if (res) acc += ldt(res, rowoff(res, r, cout) + co * laststride(res));
|
||||
if (tanh_out) acc = ref_tanh(acc);
|
||||
if (clamp_out) acc = acc < -1.0f ? -1.0f : (acc > 1.0f ? 1.0f : acc);
|
||||
stt(y, yb + co * ys, acc);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv_t1d */
|
||||
/* A transposed 1-D convolution of kernel `k` >= stride (2 stride by default) and padding `pad`
|
||||
* ((k - stride) / 2 by default, which needs k - stride even; 0 is the causal form, the full
|
||||
* output's last k - stride rows dropped), so each sequence grows exactly `stride` times: x
|
||||
* [rows, cin] in sequences `cu_seqlens`, y [rows * stride, cout] in the same sequences scaled. w
|
||||
* is PyTorch's ConvTranspose1d weight [cin, cout, k], b [cout]; sequence e is input rows
|
||||
* [cu[e], cu[e+1]) and output rows [stride cu[e], stride cu[e+1]). Output row o of a sequence
|
||||
* reads every input row i of the same sequence with 0 <= (o + pad) - i stride < k: with
|
||||
* q = (o + pad) / stride and r = (o + pad) % stride, the taps t = 0, 1, .. while r + t stride < k,
|
||||
* y[o] = b + sum_t x[q - t] w[:, :, r + t stride], in that order. f32 accumulation, one
|
||||
* rounding. */
|
||||
int ref_conv_t1d(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *cu = &a->t[3], *y = &a->t[4];
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), s = p_int(a, "stride", 0);
|
||||
/* Without `pad`, the symmetric (k - stride) / 2, which needs k - stride even. */
|
||||
const int64_t K = p_int(a, "k", 2 * s), pad = p_int(a, "pad", -1);
|
||||
const int64_t P = pad >= 0 ? pad : (K - s) / 2;
|
||||
if (cin <= 0 || cout <= 0 || s <= 0 || K < s || (pad < 0 && ((K - s) & 1))) return RAD_E_SHAPE;
|
||||
const int64_t taps = (K + s - 1) / s;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(x, cin) < r1 || rows_of(y, cout) < r1 * s) return RAD_E_SHAPE;
|
||||
if (numel(w) < cin * cout * K || numel(b) < cout) return RAD_E_SHAPE;
|
||||
REF_PAR_FOR((r1 - r0) * s * cout * cin * taps)
|
||||
for (int64_t o = r0 * s; o < r1 * s; ++o) {
|
||||
const int64_t e = seq_of(cu, n_seq, o / s);
|
||||
const int64_t i0 = cu_at(cu, e), i1 = cu_at(cu, e + 1);
|
||||
const int64_t lo = o - i0 * s; /* the output row within its sequence */
|
||||
const int64_t q = (lo + P) / s, rr = (lo + P) % s;
|
||||
const int64_t yb = rowoff(y, o, cout), ys = laststride(y);
|
||||
for (int64_t co = 0; co < cout; ++co) {
|
||||
float acc = ldt(b, co);
|
||||
for (int64_t t = 0; rr + t * s < K; ++t) {
|
||||
const int64_t qi = q - t, tap = rr + t * s;
|
||||
if (qi < 0 || i0 + qi >= i1) continue;
|
||||
const int64_t xb = rowoff(x, i0 + qi, cin), xs = laststride(x);
|
||||
for (int64_t ci = 0; ci < cin; ++ci)
|
||||
acc += ldt(w, (ci * cout + co) * K + tap) * ldt(x, xb + ci * xs);
|
||||
}
|
||||
stt(y, yb + co * ys, acc);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ snake */
|
||||
/* Snake, per channel: y = x + sin(alpha x)^2 / (alpha + 1e-9), alpha [n]. With `beta` [n], the
|
||||
* SnakeBeta form y = x + (1 / (beta + 1e-9)) sin(alpha x)^2. With `log` 1 both are stored as their
|
||||
* logarithms and exponentiated first, as the reference does each pass. f32, one rounding. */
|
||||
int ref_snake(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *al = &a->t[1], *y = &a->t[2], *be = t_in(a, 3);
|
||||
const int64_t n = p_int(a, "n", 0), lg = p_int(a, "log", 0);
|
||||
if (n <= 0 || numel(al) < n || (be && numel(be) < n) || lg < 0 || lg > 1) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, n);
|
||||
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
|
||||
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 al_c = lg ? ref_exp(ldt(al, c)) : ldt(al, c);
|
||||
const float sn = ref_sin(v * al_c);
|
||||
if (be) {
|
||||
const float b_c = lg ? ref_exp(ldt(be, c)) : ldt(be, c);
|
||||
stt(y, yb + c * ys, v + 1.0f / (b_c + 1e-9f) * (sn * sn));
|
||||
} else {
|
||||
stt(y, yb + c * ys, v + sn * sn / (al_c + 1e-9f));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ snake_aa */
|
||||
/* BigVGAN's alias-free SnakeBeta over each sequence (diffusers' MiniMaxH3AudioActivation1d:
|
||||
* UpSample1d, SnakeBeta, DownSample1d), rows samples and channels innermost, all in f32. Per
|
||||
* channel c of a sequence of L rows:
|
||||
*
|
||||
* xp the sequence replicate-padded by P = k / ratio - 1 rows on each side
|
||||
* u ratio * conv_transpose1d(xp, f_up, stride ratio), cropped by P ratio + (k - ratio) / 2
|
||||
* rows at the start and P ratio + (k - ratio + 1) / 2 at the end, so L ratio rows remain:
|
||||
* u_full[o] = sum over input rows i with 0 <= o - i ratio < k of f_up[o - i ratio] xp[i],
|
||||
* in ascending i
|
||||
* a u + (1 / (B + 1e-9)) sin(A u)^2, A = exp(alpha[c]) and B = exp(beta[c]) with `log` 1
|
||||
* (alpha[c] and beta[c] themselves otherwise), as `snake` evaluates it
|
||||
* y[o] sum over j < k of f_down[j] ap[o ratio + j] in ascending j, ap being a replicate-padded
|
||||
* by k / 2 rows on the right and k / 2 on the left less one for an even k
|
||||
*
|
||||
* so a sequence keeps its length. f_up and f_down are the checkpoint's [1, 1, k] Kaiser filters,
|
||||
* read for every channel. */
|
||||
int ref_snake_aa(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *al = &a->t[1], *be = &a->t[2], *fu = &a->t[3];
|
||||
const RadTensor *fd = &a->t[4], *cu = &a->t[5], *y = &a->t[6];
|
||||
const int64_t n = p_int(a, "n", 0), R = p_int(a, "ratio", 0), k = p_int(a, "k", 0);
|
||||
const int64_t lg = p_int(a, "log", 0);
|
||||
if (n <= 0 || R <= 0 || k < R || lg < 0 || lg > 1) return RAD_E_SHAPE;
|
||||
if (numel(al) < n || numel(be) < n || numel(fu) < k || numel(fd) < k) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(x, n) < r1 || rows_of(y, n) < r1) return RAD_E_SHAPE;
|
||||
const int64_t P = k / R - 1, crop = P * R + (k - R) / 2, pl = k / 2 - (k % 2 == 0 ? 1 : 0);
|
||||
std::vector<float> fup((size_t)k), fdn((size_t)k);
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
fup[(size_t)j] = ldt(fu, offlin(fu, j));
|
||||
fdn[(size_t)j] = ldt(fd, offlin(fd, j));
|
||||
}
|
||||
REF_PAR_FOR_DYN((r1 - r0) * n * k * 4)
|
||||
for (int64_t ec = 0; ec < n_seq * n; ++ec) {
|
||||
const int64_t e = ec / n, c = ec % n;
|
||||
const int64_t s0 = cu_at(cu, e), L = cu_at(cu, e + 1) - s0;
|
||||
if (L <= 0) continue;
|
||||
const float A = lg ? ref_exp(ldt(al, c)) : ldt(al, c);
|
||||
const float B = lg ? ref_exp(ldt(be, c)) : ldt(be, c);
|
||||
/* Row i of the padded sequence. */
|
||||
auto xp = [&](int64_t i) {
|
||||
const int64_t q = std::min(std::max<int64_t>(i - P, 0), L - 1);
|
||||
return ldt(x, rowoff(x, s0 + q, n) + c * laststride(x));
|
||||
};
|
||||
std::vector<float> act((size_t)(L * R));
|
||||
for (int64_t m = 0; m < L * R; ++m) {
|
||||
const int64_t o = crop + m;
|
||||
const int64_t i_lo = o < k ? 0 : (o - k) / R + 1;
|
||||
const int64_t i_hi = std::min(o / R, L + 2 * P - 1);
|
||||
float acc = 0.0f;
|
||||
for (int64_t i = i_lo; i <= i_hi; ++i) acc += fup[(size_t)(o - i * R)] * xp(i);
|
||||
const float u = (float)R * acc;
|
||||
const float sn = ref_sin(u * A);
|
||||
act[(size_t)m] = u + 1.0f / (B + 1e-9f) * (sn * sn);
|
||||
}
|
||||
for (int64_t o = 0; o < L; ++o) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
const int64_t m = std::min(std::max<int64_t>(o * R + j - pl, 0), L * R - 1);
|
||||
acc += fdn[(size_t)j] * act[(size_t)m];
|
||||
}
|
||||
stt(y, rowoff(y, s0 + o, n) + c * laststride(y), acc);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cfg_topk_sample */
|
||||
/* One pick per lane from `rep` branch rows of logits (rows rep i .. rep i + rep - 1 are lane i's
|
||||
* branches, the conditional first), with guidance: g = u + cfg (c - u) between the first two
|
||||
* branches, or c alone when rep is 1; `cfg` [n] f32, when bound, is each lane's guidance in place
|
||||
* of the parameter. With `penalty` (the repetition penalty) and a lane's history `hist`
|
||||
* [lanes, n_vocab] i32 (`lane` [n] naming the row), every id the history holds has its g divided
|
||||
* by the penalty when positive and multiplied by it otherwise; frame 0 clears the lane's row
|
||||
* first, and the pick is recorded in it. Ids in [sup_lo, sup_hi) are never candidates. With
|
||||
* `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates
|
||||
* the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and
|
||||
* drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream).
|
||||
* The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or
|
||||
* bf16; seed [n, 2]; frame [n]. */
|
||||
int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *lg = &a->t[0], *seed = &a->t[1], *fr = &a->t[2], *ids = &a->t[3];
|
||||
const RadTensor *cfgs = t_in(a, 4), *lane = t_in(a, 5), *hist = t_in(a, 6);
|
||||
const int64_t V = p_int(a, "n_vocab", 0), K = p_int(a, "k", 0), rep = p_int(a, "rep", 1);
|
||||
const int64_t ck = p_int(a, "cond_k", 0), stream = p_int(a, "stream", 0);
|
||||
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
|
||||
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
|
||||
const float pen = p_f32(a, "penalty", 1.0f);
|
||||
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
|
||||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n = numel(ids) / rep;
|
||||
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
|
||||
(cfgs && numel(cfgs) < n) || (lane && numel(lane) < n))
|
||||
return RAD_E_SHAPE;
|
||||
std::vector<float> g((size_t)V), c((size_t)V);
|
||||
std::vector<int64_t> idx((size_t)V);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t cb = rowoff(lg, rep * i, V), cs = laststride(lg);
|
||||
for (int64_t j = 0; j < V; ++j) c[(size_t)j] = ldt(lg, cb + j * cs);
|
||||
if (rep == 2) {
|
||||
const float gi = cfgs ? ldt(cfgs, offlin(cfgs, i)) : cfg;
|
||||
const int64_t ub = rowoff(lg, rep * i + 1, V);
|
||||
for (int64_t j = 0; j < V; ++j) {
|
||||
const float u = ldt(lg, ub + j * cs);
|
||||
g[(size_t)j] = u + gi * (c[(size_t)j] - u);
|
||||
}
|
||||
} else {
|
||||
g = c;
|
||||
}
|
||||
/* The lane's history: cleared at its first frame, then each id it holds penalised. */
|
||||
int64_t hb = -1;
|
||||
if (hist) {
|
||||
const int64_t L = ldi(lane, i);
|
||||
if (L < 0 || (L + 1) * V > numel(hist)) return RAD_E_SHAPE;
|
||||
hb = L * V;
|
||||
if (ldi(fr, i) == 0)
|
||||
for (int64_t j = 0; j < V; ++j)
|
||||
st_int(hist->dtype, hist->data, offlin(hist, hb + j), 0);
|
||||
for (int64_t j = 0; j < V; ++j)
|
||||
if (ldi(hist, hb + j) != 0) {
|
||||
float& v = g[(size_t)j];
|
||||
v = v > 0.0f ? v / pen : v * pen;
|
||||
}
|
||||
}
|
||||
/* The candidates: every entry outside the suppressed range, or those at or above the
|
||||
* conditional's ck-th largest. */
|
||||
int64_t nc = 0;
|
||||
auto open = [&](int64_t j) { return j < sup_lo || j >= sup_hi; };
|
||||
if (ck > 0) {
|
||||
std::vector<float> cc = c;
|
||||
std::nth_element(cc.begin(), cc.begin() + (ck - 1), cc.end(), std::greater<float>());
|
||||
const float thr = cc[(size_t)(ck - 1)];
|
||||
for (int64_t j = 0; j < V; ++j)
|
||||
if (c[(size_t)j] >= thr && open(j)) idx[(size_t)nc++] = j;
|
||||
} else {
|
||||
for (int64_t j = 0; j < V; ++j)
|
||||
if (open(j)) idx[(size_t)nc++] = j;
|
||||
}
|
||||
if (nc == 0) return RAD_E_SHAPE;
|
||||
const int64_t kk = std::min(K, nc);
|
||||
std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc,
|
||||
[&](int64_t p, int64_t q) {
|
||||
return g[(size_t)p] > g[(size_t)q] ||
|
||||
(g[(size_t)p] == g[(size_t)q] && p < q);
|
||||
});
|
||||
const float m = g[(size_t)idx[0]] / temp;
|
||||
double tot = 0;
|
||||
std::vector<double> e((size_t)kk);
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
e[(size_t)t] = std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m));
|
||||
tot += e[(size_t)t];
|
||||
}
|
||||
const double u = (double)rad_philox_uniform_s(seed_at(seed, i), frame_stream(ldi(fr, i)),
|
||||
(uint64_t)stream) * tot;
|
||||
int64_t pick = idx[(size_t)(kk - 1)];
|
||||
double acc = 0;
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
acc += e[(size_t)t];
|
||||
if (u < acc) { pick = idx[(size_t)t]; break; }
|
||||
}
|
||||
for (int64_t r = 0; r < rep; ++r)
|
||||
st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
|
||||
if (hist) st_int(hist->dtype, hist->data, offlin(hist, hb + pick), 1);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rvq_embed */
|
||||
/* A frame's embedding from its residual codes: codes [n_codes, rows] (code-major, so each
|
||||
* codebook's picks are one dense row), t0 the first codebook's table read at code + off0, t1 the
|
||||
* other codebooks' stacked tables, codebook k (k >= 1) at code + (k - 1) vocab. As the reference
|
||||
* rounds its tensors: y = bf16(bf16(t0[.] + bf16(sum_k t1[.])) * scale); with `round` 1 the whole
|
||||
* sum is one f32 accumulation in codebook order, times scale, rounded once to y's dtype (a sum of
|
||||
* every codebook's embedding, as torch's sum over the codebook axis rounds). A first code outside
|
||||
* t0 leaves its row unwritten; a later code outside t1 adds nothing. */
|
||||
int ref_rvq_embed(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *codes = &a->t[0], *t0 = &a->t[1], *t1 = &a->t[2], *y = &a->t[3];
|
||||
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
|
||||
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
const int64_t round1 = p_int(a, "round", 0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, D);
|
||||
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
|
||||
const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D);
|
||||
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
|
||||
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
|
||||
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
|
||||
REF_PAR_FOR(rows * D * K)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0;
|
||||
if (c0 < 0 || c0 >= r0) continue;
|
||||
std::vector<float> acc((size_t)D, 0.0f);
|
||||
const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D);
|
||||
if (round1)
|
||||
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0));
|
||||
for (int64_t k = 1; k < K; ++k) {
|
||||
const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
|
||||
if (ck < 0 || ck >= r1) continue;
|
||||
const int64_t tb = rowoff(t1, ck, D);
|
||||
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1));
|
||||
}
|
||||
for (int64_t d = 0; d < D; ++d) {
|
||||
const float s = round1 ? acc[(size_t)d]
|
||||
: rbf(ldt(t0, b0 + d * laststride(t0)) + rbf(acc[(size_t)d]));
|
||||
stt(y, yb + d * laststride(y), s * scale);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ frame_mix_store */
|
||||
/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale))
|
||||
* with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row
|
||||
* rep i of each plane belonging to lane[i]'s frame[i] (a plane holds every branch's row, the
|
||||
* conditional first). Stored at dst[lane * stride + frame - 1] when frame >= 1 and
|
||||
* status[lane] >= 0 (frame 0 only moves past the prompt; a negative status ended the piece). */
|
||||
int ref_frame_mix_store(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *hid = &a->t[0], *lw = &a->t[1], *sc = &a->t[2], *lane = &a->t[3];
|
||||
const RadTensor *fr = &a->t[4], *st = &a->t[5], *dst = &a->t[6];
|
||||
const int64_t D = p_int(a, "n_embd", 0), L = p_int(a, "L", 0), stride = p_int(a, "stride", 0);
|
||||
const int64_t rep = p_int(a, "rep", 1);
|
||||
if (D <= 0 || L <= 0 || stride <= 0 || rep < 1 || numel(lw) < L || numel(sc) < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n = numel(lane), plane = rows_of(hid, D) / L;
|
||||
if (n <= 0 || plane < rep * n || numel(fr) < n) return RAD_E_SHAPE;
|
||||
std::vector<float> wl((size_t)L);
|
||||
float mx = -INFINITY;
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
wl[(size_t)l] = rbf(ldt(lw, l));
|
||||
mx = std::max(mx, wl[(size_t)l]);
|
||||
}
|
||||
double tot = 0;
|
||||
for (int64_t l = 0; l < L; ++l) tot += std::exp((double)(wl[(size_t)l] - mx));
|
||||
for (int64_t l = 0; l < L; ++l)
|
||||
wl[(size_t)l] = rbf((float)(std::exp((double)(wl[(size_t)l] - mx)) / tot));
|
||||
const float scale = rbf(ldt(sc, 0));
|
||||
const int64_t drows = rows_of(dst, D);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t ln = ldi(lane, i), f = ldi(fr, i);
|
||||
if (f < 1 || ln < 0 || ln >= numel(st) || ldi(st, ln) < 0) continue;
|
||||
const int64_t row = ln * stride + f - 1;
|
||||
if (f > stride || row >= drows) return RAD_E_SHAPE;
|
||||
const int64_t yb = rowoff(dst, row, D);
|
||||
for (int64_t d = 0; d < D; ++d) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t l = 0; l < L; ++l)
|
||||
acc += wl[(size_t)l] *
|
||||
ldt(hid, rowoff(hid, l * plane + rep * i, D) + d * laststride(hid));
|
||||
stt(dst, yb + d * laststride(dst), rbf(acc) * scale);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ end_status */
|
||||
/* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end`
|
||||
* (the model ended the piece), else the pick. */
|
||||
int ref_end_status(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *ids = &a->t[0], *lane = &a->t[1], *st = &a->t[2];
|
||||
const int64_t end = p_int(a, "end", -1), rep = p_int(a, "rep", 1);
|
||||
const int64_t n = numel(lane);
|
||||
if (n <= 0 || rep < 1 || numel(ids) < rep * n) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t ln = ldi(lane, i), v = ldi(ids, rep * i);
|
||||
if (ln < 0 || ln >= numel(st)) return RAD_E_SHAPE;
|
||||
st_int(st->dtype, st->data, offlin(st, ln), v == end ? -1 : v);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ frame_store */
|
||||
/* A frame's codes into its lane's history: dst[(lane[i] n_codes + k) stride + frame[i] - skip] =
|
||||
* codes[k, rep i] for every k, when frame[i] >= skip and status[lane[i]] >= 0. codes is code-major
|
||||
* [n_codes, rows] (a codebook's picks one row, each lane's `rep` times); dst [lanes * n_codes,
|
||||
* stride] holds each lane's codebooks as rows over its frames, so a run of frames is a block. */
|
||||
int ref_frame_store(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *codes = &a->t[0], *lane = &a->t[1], *fr = &a->t[2], *st = &a->t[3];
|
||||
const RadTensor *dst = &a->t[4];
|
||||
const int64_t K = p_int(a, "n_codes", 0), stride = p_int(a, "stride", 0);
|
||||
const int64_t rep = p_int(a, "rep", 1), skip = p_int(a, "skip", 0);
|
||||
if (K <= 0 || stride <= 0 || rep < 1 || skip < 0) return RAD_E_SHAPE;
|
||||
const int64_t n = numel(lane);
|
||||
if (n <= 0 || numel(fr) < n || numel(codes) < K * rep * n) return RAD_E_SHAPE;
|
||||
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rep * n;
|
||||
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t L = ldi(lane, i), f = ldi(fr, i) - skip;
|
||||
if (L < 0 || L >= numel(st)) return RAD_E_SHAPE;
|
||||
if (f < 0 || ldi(st, L) < 0) continue;
|
||||
if (f >= stride || (L + 1) * K * stride > numel(dst)) return RAD_E_SHAPE;
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
st_int(dst->dtype, dst->data, offlin(dst, (L * K + k) * stride + f),
|
||||
ld_int(codes->dtype, codes->data, k * kp + rep * i * rp));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ resample_nearest */
|
||||
/* Rows resampled nearest-neighbour as torch's interpolate(mode="nearest") does, in f32: output row
|
||||
* j reads input row min(floor(j * (in / out)), in - 1), `in` and `out` the operands' row counts. */
|
||||
int ref_resample_nearest(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 in = rows_of(x, n), out = rows_of(y, n);
|
||||
if (in <= 0 || out <= 0) return RAD_E_SHAPE;
|
||||
const float scale = (float)in / (float)out;
|
||||
for (int64_t j = 0; j < out; ++j) {
|
||||
const int64_t src = std::min<int64_t>((int64_t)std::floor((float)j * scale), in - 1);
|
||||
const int64_t xb = rowoff(x, src, n), yb = rowoff(y, j, n);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
stt(y, yb + c * laststride(y), ldt(x, xb + c * laststride(x)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ fourier_embed */
|
||||
/* Random Fourier features of a time in [0, 1]: y = [cos(2 pi t w) | sin(2 pi t w)], w [n / 2]
|
||||
* (a trained projection). With `round` 1 every tensor the bf16 reference holds is rounded: t, then
|
||||
* bf16(2 pi t), then the product with w, then each cosine and sine. t is f32 [M]. */
|
||||
int ref_fourier_embed(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *t = &a->t[0], *w = &a->t[1], *y = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const bool rnd = p_int(a, "round", 0) != 0;
|
||||
if (n <= 0 || (n & 1) || numel(w) < n / 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, n);
|
||||
if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE;
|
||||
const float two_pi = 6.28318530717958647692f;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float tv = ldt(t, offlin(t, r));
|
||||
if (rnd) tv = rbf(rbf(tv) * two_pi);
|
||||
else tv *= two_pi;
|
||||
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
|
||||
for (int64_t i = 0; i < n / 2; ++i) {
|
||||
float ang = tv * ldt(w, i);
|
||||
if (rnd) ang = rbf(ang);
|
||||
stt(y, yb + i * ys, ref_cos(ang));
|
||||
stt(y, yb + (n / 2 + i) * ys, ref_sin(ang));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ win_input */
|
||||
/* A denoiser's input rows for its window entries: entry e's latent rows (lat_cu) are
|
||||
* [lat | zeros | cond] from lane win_lane[e] of the latent state `lat` [lanes * stride, n_lat] and
|
||||
* of the window conditioning `cond` [lanes * stride, n_cond], `stride` rows a lane. An entry
|
||||
* that is an unconditional branch (pair -2) takes zeros for its conditioning.
|
||||
* y [rows, n_lat + n_zero + n_cond]. */
|
||||
int ref_win_input(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 6)) return RAD_E_INVAL;
|
||||
const RadTensor *lat = &a->t[0], *cond = &a->t[1], *lcu = &a->t[2], *wl = &a->t[3];
|
||||
const RadTensor *pair = &a->t[4], *y = &a->t[5];
|
||||
const int64_t C = p_int(a, "n_lat", 0), Z = p_int(a, "n_zero", 0), D = p_int(a, "n_cond", 0);
|
||||
const int64_t stride = p_int(a, "stride", 0), W = C + Z + D;
|
||||
if (C <= 0 || Z < 0 || D <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t S = numel(lcu) - 1;
|
||||
if (S <= 0 || numel(wl) < S || numel(pair) < S) return RAD_E_SHAPE;
|
||||
if (rows_of(y, W) < cu_at(lcu, S)) return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < S; ++e) {
|
||||
const int64_t L = ldi(wl, e), neg = ldi(pair, e) == -2;
|
||||
const int64_t b0 = cu_at(lcu, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e);
|
||||
if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, C) ||
|
||||
(len > 0 && (b0 < 0 || b0 + len > rows_of(y, W))) ||
|
||||
(len > 0 && !neg && (L + 1) * stride > rows_of(cond, D)))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t k = 0; k < len; ++k) {
|
||||
const int64_t yb = rowoff(y, b0 + k, W), ys = laststride(y);
|
||||
const int64_t lb = rowoff(lat, L * stride + k, C);
|
||||
for (int64_t c = 0; c < C; ++c) stt(y, yb + c * ys, ldt(lat, lb + c * laststride(lat)));
|
||||
for (int64_t c = 0; c < Z; ++c) stt(y, yb + (C + c) * ys, 0.0f);
|
||||
const int64_t cb = rowoff(cond, L * stride + k, D);
|
||||
for (int64_t c = 0; c < D; ++c)
|
||||
stt(y, yb + (C + Z + c) * ys, neg ? 0.0f : ldt(cond, cb + c * laststride(cond)));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ win_prep */
|
||||
/* A window step's start, for each entry that moves its lane (pair != -2):
|
||||
* FIRST the lane's latent rows become the window's noise, element (k, c) of
|
||||
* rad_philox_normal_s(seed, 1 + win_index, k n + c) as bf16, and with JOIN the first `ov`
|
||||
* rows are kept in `noise`;
|
||||
* JOIN the first min(ov, rows) rows are bound to the previous window's end:
|
||||
* bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev)), t = bf16(t[e]).
|
||||
* `lat` [lanes * stride, n], `prev` and `noise` [lanes * ov, n]. */
|
||||
int ref_win_prep(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 10)) return RAD_E_INVAL;
|
||||
const RadTensor *fl = &a->t[0], *t = &a->t[1], *seed = &a->t[2], *widx = &a->t[3];
|
||||
const RadTensor *wl = &a->t[4], *pair = &a->t[5], *lcu = &a->t[6], *prev = &a->t[7];
|
||||
const RadTensor *noise = &a->t[8], *lat = &a->t[9];
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0);
|
||||
if (n <= 0 || stride <= 0 || ov < 0 || ov > stride) return RAD_E_SHAPE;
|
||||
const int64_t S = numel(lcu) - 1;
|
||||
if (S <= 0 || numel(fl) < S || numel(t) < S || numel(widx) < S || numel(wl) < S ||
|
||||
numel(pair) < S)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < S; ++e) {
|
||||
if (ldi(pair, e) == -2) continue;
|
||||
const int64_t f = ldi(fl, e), L = ldi(wl, e);
|
||||
const int64_t len = cu_at(lcu, e + 1) - cu_at(lcu, e);
|
||||
if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) ||
|
||||
(ov && (L + 1) * ov > rows_of(noise, n)) ||
|
||||
((f & kFirst) && numel(seed) < 2 * (e + 1)) ||
|
||||
((f & kJoin) && ov && len > 0 && (L + 1) * ov > rows_of(prev, n)))
|
||||
return RAD_E_SHAPE;
|
||||
if (f & kFirst) {
|
||||
const uint64_t sd = seed_at(seed, e), sm = window_stream(ldi(widx, e));
|
||||
for (int64_t k = 0; k < len; ++k)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float v = rbf(rad_philox_normal_s(sd, sm, (uint64_t)(k * n + c)));
|
||||
stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat), v);
|
||||
if ((f & kJoin) && k < ov)
|
||||
stt(noise, rowoff(noise, L * ov + k, n) + c * laststride(noise), v);
|
||||
}
|
||||
}
|
||||
if (f & kJoin) {
|
||||
const float tb = rbf(ldt(t, offlin(t, e)));
|
||||
const float wn = rbf(1.0f - rbf((1.0f - 1e-6f) * tb));
|
||||
const int64_t m = std::min(ov, len);
|
||||
for (int64_t k = 0; k < m; ++k)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float nz =
|
||||
ldt(noise, rowoff(noise, L * ov + k, n) + c * laststride(noise));
|
||||
const float pv = ldt(prev, rowoff(prev, L * ov + k, n) + c * laststride(prev));
|
||||
stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat),
|
||||
rbf(rbf(wn * nz) + rbf(tb * pv)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ win_finish */
|
||||
/* A window's end, for each entry that moves its lane and carries LAST: with JOIN its first
|
||||
* min(ov, rows) rows become the previous window's end exactly; then the rows
|
||||
* [max(0, rows - 2 ov), max(that, rows - ov)) of the latent and of the conditioning are kept as
|
||||
* the next window's `prev` and `prev_cond`. `lat` [lanes * stride, n], `cond` [lanes * stride,
|
||||
* n_cond], `prev` [lanes * ov, n], `prev_cond` [lanes * ov, n_cond]. */
|
||||
int ref_win_finish(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *fl = &a->t[0], *pair = &a->t[1], *wl = &a->t[2], *lcu = &a->t[3];
|
||||
const RadTensor *cond = &a->t[4], *lat = &a->t[5], *prev = &a->t[6], *pc = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0), D = p_int(a, "n_cond", 0);
|
||||
const int64_t stride = p_int(a, "stride", 0), ov = p_int(a, "ov", 0);
|
||||
if (n <= 0 || D <= 0 || stride <= 0 || ov <= 0 || ov > stride) return RAD_E_SHAPE;
|
||||
const int64_t S = numel(lcu) - 1;
|
||||
if (S <= 0 || numel(fl) < S || numel(wl) < S || numel(pair) < S) return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < S; ++e) {
|
||||
const int64_t f = ldi(fl, e);
|
||||
if (ldi(pair, e) == -2 || !(f & kLast)) continue;
|
||||
const int64_t L = ldi(wl, e), len = cu_at(lcu, e + 1) - cu_at(lcu, e);
|
||||
if (L < 0 || len > stride || (L + 1) * stride > rows_of(lat, n) ||
|
||||
(L + 1) * ov > rows_of(prev, n) || (L + 1) * ov > rows_of(pc, D) ||
|
||||
(len > ov && (L + 1) * stride > rows_of(cond, D)))
|
||||
return RAD_E_SHAPE;
|
||||
if (f & kJoin)
|
||||
for (int64_t k = 0; k < std::min(ov, len); ++k)
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
stt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat),
|
||||
ldt(prev, rowoff(prev, L * ov + k, n) + c * laststride(prev)));
|
||||
const int64_t s0 = std::max<int64_t>(0, len - 2 * ov);
|
||||
const int64_t s1 = std::max<int64_t>(s0, len - ov);
|
||||
for (int64_t k = s0; k < s1; ++k) {
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
stt(prev, rowoff(prev, L * ov + k - s0, n) + c * laststride(prev),
|
||||
ldt(lat, rowoff(lat, L * stride + k, n) + c * laststride(lat)));
|
||||
for (int64_t c = 0; c < D; ++c)
|
||||
stt(pc, rowoff(pc, L * ov + k - s0, D) + c * laststride(pc),
|
||||
ldt(cond, rowoff(cond, L * stride + k, D) + c * laststride(cond)));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chan_split */
|
||||
/* Channel groups to sequences: x [rows, parts * n] becomes y [parts * rows, n], y[p rows + r] =
|
||||
* x[r, p n .. p n + n): a stereo latent's two halves as two streams for a vocoder. */
|
||||
int ref_chan_split(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), P = p_int(a, "parts", 0);
|
||||
if (n <= 0 || P <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, n) / P;
|
||||
if (rows <= 0 || rows_of(x, P * n) < rows) return RAD_E_SHAPE;
|
||||
for (int64_t p = 0; p < P; ++p)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, P * n), yb = rowoff(y, p * rows + r, n);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
stt(y, yb + c * laststride(y), ldt(x, xb + (p * n + c) * laststride(x)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ interleave2 */
|
||||
/* Two streams of samples interleaved, y [rows, 2] = (a[r], b[r]): a vocoder's left and right
|
||||
* outputs as a stereo buffer. */
|
||||
int ref_interleave2(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x0 = &a->t[0], *x1 = &a->t[1], *y = &a->t[2];
|
||||
const int64_t rows = rows_of(y, 2);
|
||||
if (rows <= 0 || numel(x0) < rows || numel(x1) < rows) return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
stt(y, rowoff(y, r, 2), ldt(x0, offlin(x0, r)));
|
||||
stt(y, rowoff(y, r, 2) + laststride(y), ldt(x1, offlin(x1, r)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ iota */
|
||||
/* y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`: row
|
||||
* indices a model's fixed layout names (a depth decoder's position p in every sequence of its
|
||||
* frame), or the positions of equal sequences laid end to end. */
|
||||
int ref_iota(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 1)) return RAD_E_INVAL;
|
||||
const RadTensor* y = &a->t[0];
|
||||
const int64_t start = p_int(a, "start", 0), step = p_int(a, "step", 1);
|
||||
const int64_t period = p_int(a, "period", 0);
|
||||
const int64_t n = numel(y);
|
||||
if (n <= 0 || period < 0) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
st_int(y->dtype, y->data, offlin(y, i), start + (period ? i % period : i) * step);
|
||||
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),
|
||||
* so a model's derived bounds are made there too. */
|
||||
int ref_cu_repeat(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *len = &a->t[0], *y = &a->t[1];
|
||||
const int64_t mult = p_int(a, "mult", 1);
|
||||
const int64_t n = numel(y);
|
||||
if (n <= 0 || numel(len) < 1 || mult <= 0) return RAD_E_SHAPE;
|
||||
const int64_t l = ldi(len, 0);
|
||||
for (int64_t j = 0; j < n; ++j) st_int(y->dtype, y->data, offlin(y, j), j * l * mult);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -426,6 +426,10 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam
|
||||
* without doing the work. */
|
||||
#define RAD_REF_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0)
|
||||
|
||||
/* quant_act_i8g's rule for one row of `n` (ref_gen.cpp): returns the scale (amax/127, 1 for an
|
||||
* all-zero row) and writes the codes rint(clamp(x * (1/scale), +-127)) to `code`, which may be `x`. */
|
||||
float ref_q8_row(const float* x, int64_t n, float* code);
|
||||
|
||||
static inline const RadTensor* t_in(const RadArgs* a, int i) { return rad_arg_in(a, i); }
|
||||
static inline bool have(const RadArgs* a, int n) { return rad_args_have(a, n) != 0; }
|
||||
|
||||
|
||||
@@ -251,11 +251,14 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
|
||||
/* ------------------------------------------------------------------ add / mul */
|
||||
/* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which
|
||||
* broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a
|
||||
* plausible number. */
|
||||
* plausible number. `add` with `div` stores rd(rd(a + b) / div), rd y's dtype: the last step of a
|
||||
* mean summed pairwise, (b0 + b1 + b2) / 3 as a vocoder averages its residual blocks. */
|
||||
static int elementwise2(const RadArgs* a, bool mul) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", numel(Y));
|
||||
const float div = mul ? 1.0f : p_f32(a, "div", 1.0f);
|
||||
if (!(div != 0.0f) || !std::isfinite(div)) return RAD_E_INVAL;
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE;
|
||||
@@ -269,7 +272,9 @@ static int elementwise2(const RadArgs* a, bool mul) {
|
||||
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float u = ldt(A, ab + i * as), v = ldt(B, bb + i * bs);
|
||||
stt(Y, yb + i * ys, mul ? u * v : u + v);
|
||||
float s = mul ? u * v : u + v;
|
||||
if (div != 1.0f) s = round_dt(Y->dtype, s) / div;
|
||||
stt(Y, yb + i * ys, s);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -652,13 +657,15 @@ int ref_conv2d_unfold(const RadArgs* a, RadStream) {
|
||||
|
||||
/* ------------------------------------------------------------------ conv1d_dw */
|
||||
/* A causal depthwise convolution over time: y[t, c] = sum_j w[c, j] * x[t - (k-1) + j, c], the
|
||||
* rows before the segment's start (cu[s] / cu_div) read as zeros. `w` is PyTorch's depthwise
|
||||
* [C, 1, k]. f32 accumulation, one rounding. */
|
||||
* rows before the segment's start (cu[s] / cu_div) read as zeros, plus `b` [C] when bound. `w` is
|
||||
* PyTorch's depthwise [C, 1, k]. f32 accumulation, one rounding. */
|
||||
int ref_conv1d_dw(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
|
||||
const RadTensor *B = t_in(a, 4);
|
||||
const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1);
|
||||
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE;
|
||||
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K || (B && numel(B) < C))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t S = numel(cu) - 1;
|
||||
if (S <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
|
||||
@@ -681,6 +688,7 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) {
|
||||
if (tt < t0) continue;
|
||||
acc += ldt(X, rowoff(X, tt, C) + c * xs) * ldt(Wt, c * K + j);
|
||||
}
|
||||
if (B) acc += ldt(B, c);
|
||||
stt(Y, yb + c * ys, acc);
|
||||
}
|
||||
}
|
||||
|
||||
+199
-28
@@ -26,14 +26,15 @@ enum { kFirst = 1, kInpaint = 2, kPreview = 4 };
|
||||
|
||||
inline float rbf(float v) { return round_dt(RAD_BF16, v); }
|
||||
|
||||
/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it. */
|
||||
int parse_list(const char* s, std::vector<float>* out) {
|
||||
/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it, or
|
||||
* kept in f32 with `bf16` false. */
|
||||
int parse_list(const char* s, std::vector<float>* out, bool bf16 = true) {
|
||||
out->clear();
|
||||
while (s && *s) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s, &end);
|
||||
if (end == s) break;
|
||||
out->push_back(rbf((float)v));
|
||||
out->push_back(bf16 ? rbf((float)v) : (float)v);
|
||||
s = end;
|
||||
}
|
||||
return (int)out->size();
|
||||
@@ -78,11 +79,15 @@ int ref_ln_mod(const RadArgs* a, RadStream) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gate_add */
|
||||
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ): a residual added through its sequence's gate. */
|
||||
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ): a residual added through its sequence's gate.
|
||||
* With `act` none the gate is g itself, unrounded: x = bf16(x + bf16(g[seq] * y)). */
|
||||
int ref_gate_add(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *y = &a->t[0], *g = &a->t[1], *cu = &a->t[2], *x = &a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
static const char* kActs[] = { "tanh", "none" };
|
||||
const int act = p_enum(a, "act", kActs, 2, 0);
|
||||
if (act < 0 || act > 1) return RAD_E_INVAL;
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1;
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
|
||||
@@ -93,7 +98,8 @@ int ref_gate_add(const RadArgs* a, RadStream) {
|
||||
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs)));
|
||||
const float gv = ldt(g, e * g_rs + i * g_cs);
|
||||
const float t = act ? gv : round_dt(x->dtype, ref_tanh(gv));
|
||||
const float p = round_dt(x->dtype, t * ldt(y, yb + i * ys));
|
||||
stt(x, xb + i * xs, ldt(x, xb + i * xs) + p);
|
||||
}
|
||||
@@ -156,6 +162,108 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */
|
||||
/* The checks both forms share: `s` holds [shift | scale] in each of its n_seq rows, `g` a gate
|
||||
* row per sequence when `gated`, and every row operand at least `rows` rows. */
|
||||
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 ||
|
||||
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;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Row r of sequence e into o[0, n). With `gated` the branch is added first through the gate row,
|
||||
* x = bf16(x + bf16(g[e] * y[r])) (no tanh), and stored; then an RMS norm with a gain and the
|
||||
* sequence's shift and scale, each step a tensor the upstream bf16 model stores:
|
||||
*
|
||||
* n1 = bf16(x * rsqrt(mean(x^2) + eps)) n2 = bf16(n1 * w)
|
||||
* m = bf16(n2 * bf16(1 + scale[e])) z = bf16(m + shift[e])
|
||||
*
|
||||
* 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`. */
|
||||
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) {
|
||||
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);
|
||||
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float p = round_dt(x->dtype, ldt(g, e * g_rs + i * g_cs) * ldt(y, yb + i * ys));
|
||||
stt(x, xb + i * xs, ldt(x, xb + i * xs) + p);
|
||||
}
|
||||
}
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) { const float v = ldt(x, xb + i * xs); 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);
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
|
||||
/* A diffusion transformer's adaptive RMS norm with a shift (MiniMax-H3's
|
||||
* `norm(h) * (1 + scale) + shift`), the gated residual of the branch before it optionally first;
|
||||
* the norm chain rounds to z's dtype. */
|
||||
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 *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);
|
||||
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());
|
||||
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]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* rms_mod in front of a quantised linear: the norm chain in bf16, then the codes and scales as
|
||||
* ref_quant_act_fp8 writes them over that bf16 row (ln_mod_quant_fp8's rule), z written when
|
||||
* 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 *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);
|
||||
if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
|
||||
RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated));
|
||||
if (numel(sc) < rows * ngrp || (z && rows_of(z, n) < rows)) return RAD_E_SHAPE;
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
std::vector<float> o((size_t)n);
|
||||
rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data());
|
||||
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);
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const float* og = o.data() + gi * grp;
|
||||
const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q,
|
||||
qb + gi * grp * qs, qs);
|
||||
stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ timestep_embed */
|
||||
/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})], h = n / 2, where
|
||||
* f_i = exp(-ln(max_period) * i / h) in f32 and t' = scale * t -- or, with `round` 1, the value
|
||||
@@ -298,12 +406,13 @@ int ref_randn_lanes(const RadArgs* a, RadStream) {
|
||||
* noise the image's own stream (randn_lanes). At the last step sigma_next is 0 and the kept
|
||||
* region is the picture's latent exactly. */
|
||||
int ref_flow_euler(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 13)) return RAD_E_INVAL;
|
||||
/* inp, mask and preview are optional: a sampler without repaint or previews passes none. */
|
||||
if (!have(a, 9) || !t_in(a, 11)) return RAD_E_INVAL;
|
||||
const RadTensor *v = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3];
|
||||
const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7];
|
||||
const RadTensor *cu = &a->t[8];
|
||||
const RadTensor *inp = t_in(a, 9), *mask = t_in(a, 10);
|
||||
const RadTensor *st = &a->t[11];
|
||||
const RadTensor *st = t_in(a, 11);
|
||||
const RadTensor *pv = t_in(a, 12);
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
@@ -357,31 +466,71 @@ int ref_flow_euler(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ flow_x0_step */
|
||||
/* One sampler step over a lane's rows in f32, as diffusers' MiniMaxH3Scheduler.step takes it: the
|
||||
* velocity points toward the data, so the clean estimate is d = x + (1 - t) v, and the step blends
|
||||
* the sample toward it by the schedule's ratio. Each product and sum is one f32 rounding:
|
||||
*
|
||||
* st = f32(1 - t) d = f32(x + f32(st * v)) r = f32(sigma_next / sigma)
|
||||
* x' = f32(f32(r * x) + f32(f32(1 - r) * d))
|
||||
*
|
||||
* t, sigma and sigma_next are one value each: t the timestep the transformer was conditioned on,
|
||||
* sigma and sigma_next the schedule's entries, kept apart because 1 - (1 - sigma) is not exact in
|
||||
* f32. x' is stored at x's dtype. */
|
||||
int ref_flow_x0_step(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *v = &a->t[0], *t = &a->t[1], *sg = &a->t[2], *sgn = &a->t[3], *x = &a->t[4];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(x, n);
|
||||
if (rows <= 0 || rows_of(v, n) < rows || numel(t) < 1 || numel(sg) < 1 || numel(sgn) < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const float st = 1.0f - ldt(t, offlin(t, 0));
|
||||
const float r = ldt(sgn, offlin(sgn, 0)) / ldt(sg, offlin(sg, 0));
|
||||
const float omr = 1.0f - r;
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t k = 0; k < rows; ++k) {
|
||||
const int64_t vb = rowoff(v, k, n), vs = laststride(v);
|
||||
const int64_t xb = rowoff(x, k, n), xs = laststride(x);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float xv = ldt(x, xb + c * xs);
|
||||
const float d = xv + st * ldt(v, vb + c * vs);
|
||||
stt(x, xb + c * xs, r * xv + omr * 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
|
||||
* bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */
|
||||
* bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). With `round` 0 the lists stay
|
||||
* f32 and so does the arithmetic, rounded once into y: rd(f32(x * mul) + add) and
|
||||
* rd(f32(x - add) / mul), as an f32 model denormalises an f32 latent. */
|
||||
int ref_chan_affine(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);
|
||||
const int64_t n = p_int(a, "n", 0), rnd = p_int(a, "round", 1);
|
||||
if (rnd < 0 || rnd > 1) return RAD_E_INVAL;
|
||||
std::vector<float> mul, add;
|
||||
if (n <= 0 || parse_list(p_str(a, "mul", ""), &mul) != n ||
|
||||
parse_list(p_str(a, "add", ""), &add) != n)
|
||||
if (n <= 0 || parse_list(p_str(a, "mul", ""), &mul, rnd) != n ||
|
||||
parse_list(p_str(a, "add", ""), &add, rnd) != n)
|
||||
return RAD_E_SHAPE;
|
||||
const char* mode = p_str(a, "mode", "fma");
|
||||
const bool inv = mode && !std::strcmp(mode, "inv");
|
||||
if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL;
|
||||
const int64_t rows = rows_of(y, n);
|
||||
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
|
||||
/* The inner product's or difference's rounding: y's dtype, or none. */
|
||||
const uint32_t mid = rnd ? y->dtype : (uint32_t)RAD_F32;
|
||||
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);
|
||||
stt(y, yb + c * ys, inv ? round_dt(y->dtype, v - add[c]) / mul[c]
|
||||
: round_dt(y->dtype, v * mul[c]) + add[c]);
|
||||
stt(y, yb + c * ys, inv ? round_dt(mid, v - add[c]) / mul[c]
|
||||
: round_dt(mid, v * mul[c]) + add[c]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -607,7 +756,7 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) {
|
||||
/* quant_act_i8g's rule for one row of `n`: the scale (amax/127, 1 for an all-zero row) and the
|
||||
* codes rint(clamp(x * (1/scale), +-127)), in f32 as the device computes them. `code` may be `x`:
|
||||
* each code is written after its value is read. */
|
||||
static float ref_q8_row(const float* x, int64_t n, float* code) {
|
||||
float ref::ref_q8_row(const float* x, int64_t n, float* code) {
|
||||
float am = 0.0f;
|
||||
for (int64_t d = 0; d < n; ++d) am = std::max(am, std::fabs(x[d]));
|
||||
const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
|
||||
@@ -619,8 +768,11 @@ static float ref_q8_row(const float* x, int64_t n, float* code) {
|
||||
|
||||
int ref_attn_prefix_self(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 12) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *kv = &a->t[3];
|
||||
const RadTensor *bt = &a->t[4], *su = &a->t[5], *cu = &a->t[6], *o = &a->t[11];
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[6], *o = &a->t[11];
|
||||
/* The paged prefix (cache, block table, per-sequence prefix lengths), all three or none: with
|
||||
* none every sequence's prefix is empty. */
|
||||
const RadTensor *kv = t_in(a, 3), *bt = t_in(a, 4), *su = t_in(a, 5);
|
||||
if ((kv == nullptr) != (bt == nullptr) || (kv == nullptr) != (su == nullptr)) return RAD_E_INVAL;
|
||||
const RadTensor *kdes = t_in(a, 7), *vdes = t_in(a, 8);
|
||||
/* The int8 Q.K form: own keys' codes and scales are given; everything else is quantised here. */
|
||||
const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10);
|
||||
@@ -628,38 +780,50 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
|
||||
const bool i8 = std::strcmp(qk, "i8") == 0;
|
||||
if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return RAD_E_INVAL;
|
||||
if (i8 && (kdes || vdes)) return RAD_E_UNSUPPORTED;
|
||||
/* The fp8 P.V form: `v` E4M3 codes with a scale per column in `v_scale` (quant_cols_fp8), each
|
||||
* weight exp(s - max) taken to E4M3 at 448 times its value, o = sum(w v) v_scale /
|
||||
* (448 sum exp(s - max)); prefix-free only. */
|
||||
const RadTensor* vsc = a->n_t > 12 ? t_in(a, 12) : nullptr;
|
||||
const char* pv = p_str(a, "pv", "bf16");
|
||||
const bool pv8 = std::strcmp(pv, "fp8") == 0;
|
||||
if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL;
|
||||
if (pv8 && (kv || kdes || vdes)) return RAD_E_UNSUPPORTED;
|
||||
const int64_t head_dim = p_int(a, "head_dim", 0), gqa = p_int(a, "gqa", 1);
|
||||
const int causal = (int)p_int(a, "causal", 0);
|
||||
const int64_t block_size = kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0);
|
||||
const int64_t block_size = !kv ? 1 : kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0);
|
||||
/* The widest head held in the stack rows below. */
|
||||
constexpr int64_t kHdMax = 1024;
|
||||
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
|
||||
if (head_dim > kHdMax) return RAD_E_UNSUPPORTED;
|
||||
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
|
||||
/* Without a cache the key heads are the own keys' width over head_dim. */
|
||||
const int64_t kv_heads = kv ? (kv->rank == 4 ? kv->shape[1] : 0)
|
||||
: k->rank >= 3 ? k->shape[k->rank - 2]
|
||||
: k->rank == 2 ? k->shape[1] / head_dim : 0;
|
||||
if (kv_heads <= 0) return RAD_E_SHAPE;
|
||||
const int64_t q_heads = kv_heads * gqa, n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0 || numel(su) < n_seq) return RAD_E_SHAPE;
|
||||
if (n_seq <= 0 || (su && numel(su) < n_seq)) return RAD_E_SHAPE;
|
||||
/* The rows are cu's span, which need not start at 0: a segment of a longer sequence is passed
|
||||
* as its two bounding offsets. */
|
||||
const int64_t r_first = cu_at(cu, 0), rows = cu_at(cu, n_seq) - r_first;
|
||||
if (rows <= 0) return RAD_E_SHAPE;
|
||||
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq;
|
||||
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[0] : max_blocks;
|
||||
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[1] : 1;
|
||||
const int64_t max_blocks = !bt ? 0 : bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq;
|
||||
const int64_t bt_rs = bt && bt->rank >= 2 ? bt->stride[0] : max_blocks;
|
||||
const int64_t bt_cs = bt && bt->rank >= 2 ? bt->stride[1] : 1;
|
||||
/* Every prefix key must have a block-table entry. */
|
||||
for (int64_t s = 0; s < n_seq; ++s)
|
||||
for (int64_t s = 0; su && s < n_seq; ++s)
|
||||
if (ld_int(su->dtype, su->data, offlin(su, s)) > max_blocks * block_size) return RAD_E_SHAPE;
|
||||
const int64_t q_rs = row_stride(q, q_heads * head_dim), k_rs = row_stride(k, kv_heads * head_dim);
|
||||
const int64_t v_rs = row_stride(v, kv_heads * head_dim), o_rs = row_stride(o, q_heads * head_dim);
|
||||
const int64_t k8_rs = i8 ? row_stride(k8, kv_heads * head_dim) : 0;
|
||||
const int64_t ks_rs = i8 ? row_stride(ks, kv_heads) : 0;
|
||||
const int64_t sb = kv->stride[0], sh = kv->stride[1], so = kv->stride[2];
|
||||
const int64_t sb = kv ? kv->stride[0] : 0, sh = kv ? kv->stride[1] : 0;
|
||||
const int64_t so = kv ? kv->stride[2] : 0;
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
REF_PAR_FOR_DYN(rows * q_heads * head_dim * 64)
|
||||
for (int64_t idx = 0; idx < rows * q_heads; ++idx) {
|
||||
const int64_t h = idx % q_heads, r = r_first + idx / q_heads, kh = h / gqa;
|
||||
const int64_t s = seq_of(cu, n_seq, r), b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1);
|
||||
const int64_t i = r - b0, P = ld_int(su->dtype, su->data, offlin(su, s));
|
||||
const int64_t i = r - b0, P = su ? ld_int(su->dtype, su->data, offlin(su, s)) : 0;
|
||||
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
|
||||
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
|
||||
const int64_t qb = r * q_rs + h * head_dim;
|
||||
@@ -709,8 +873,9 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = 0; j < nk; ++j) {
|
||||
const float wgt = ref_exp(dot(j) - mx);
|
||||
sum += wgt;
|
||||
const float p = ref_exp(dot(j) - mx);
|
||||
sum += p;
|
||||
const float wgt = pv8 ? round_dt(RAD_F8E4M3, 448.0f * p) : p;
|
||||
if (j < P) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] += wgt * pkey(j, d, true);
|
||||
} else {
|
||||
@@ -720,7 +885,13 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
|
||||
}
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
const int64_t ob = r * o_rs + h * head_dim;
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d, acc[d] * inv);
|
||||
if (pv8) {
|
||||
const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d)
|
||||
stt(o, ob + d, acc[d] * ldt(vsc, offlin(vsc, kh * head_dim + d)) * inv8);
|
||||
} else {
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d, acc[d] * inv);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+20
-28
@@ -3,28 +3,23 @@
|
||||
* lora_shrink t[m, j] = sum_k x(m, k) * A[s, j, k] s = slot[m]
|
||||
* lora_expand y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * B[s, n, j]
|
||||
*
|
||||
* A step mixes rows of several adapters and rows of none, so the adapter is a PER-ROW operand: a
|
||||
* row whose slot is outside [0, S) is a BASE row and neither op touches it. That is stronger than
|
||||
* "adds zero": `y + 0` turns a -0 into +0, and the promise the engine makes is that a base row is
|
||||
* bit-for-bit what the gemm wrote. So shrink writes nothing into a base row of `t` and expand does
|
||||
* no read-modify-write of a base row of `y` at all -- not a store of the value it read, no store.
|
||||
* The adapter is a per-row operand, since a step mixes rows of several adapters and rows of none.
|
||||
* A row whose slot is outside [0, S) is a base row and neither op touches it: shrink writes nothing
|
||||
* into its `t` row and expand neither reads nor stores its `y` row, so a base row stays bit for bit
|
||||
* what the gemm wrote (`y + 0` would turn -0 into +0).
|
||||
*
|
||||
* x(m, k) IS THE VALUE gemm_nt_q USES FOR THAT ACTIVATION ELEMENT, read the same way: the row and
|
||||
* column strides of `a` (a column slice of a fused projection arrives with the whole projection's
|
||||
* row stride), and the scale stream through ref_gemm.h's make_scales, which is gemm_nt_q's own
|
||||
* reading of `a_scale`. A code times its group's scale is one f32 product; a bf16, f16 or f32
|
||||
* activation is its value as it stands. One more rounding than gemm_nt_q's group sub-sum makes on
|
||||
* a quantised activation, and it is the contract (docs/OPS.md): the LoRA term is a low-rank
|
||||
* correction, and folding the scale per element keeps the kernels free of a group loop.
|
||||
* x(m, k) is the value gemm_nt_q uses for that activation element, read the same way: through the
|
||||
* row and column strides of `a` (a column slice of a fused projection keeps the whole projection's
|
||||
* row stride) and through ref_gemm.h's make_scales for `a_scale`. A code times its group's scale is
|
||||
* one f32 product and a float activation is its value. That is one more rounding than gemm_nt_q's
|
||||
* group sub-sum, and it is the contract (docs/OPS.md): it keeps the kernels free of a group loop.
|
||||
*
|
||||
* THE SUM IS PER ROW AND ITS ORDER IS FIXED: k ascending for shrink, j ascending for expand, one
|
||||
* f32 accumulator, no FMA (libref/CMakeLists.txt). Nothing here depends on M or on another row --
|
||||
* the batch a row arrives in cannot change its bytes, which is what lets the engine claim "mixed
|
||||
* batch == the same request alone" for the LoRA term.
|
||||
* The sum is per row in a fixed order (k ascending for shrink, j ascending for expand, one f32
|
||||
* accumulator, no FMA: libref/CMakeLists.txt), so a row's bytes do not depend on M or on the rows
|
||||
* batched with it.
|
||||
*
|
||||
* EVERY EXTENT IS THE OPERAND'S, and the parameters are cross-checks (ref_ops.h): `M` is the band,
|
||||
* so the rows are `t`'s for shrink and `y`'s for expand, and `K`, `N`, `R`, `S` say how to read the
|
||||
* tensors and are refused where the tensors are too small for them.
|
||||
* Every extent is the operand's and the parameters are cross-checks (ref_ops.h): `M` is the band,
|
||||
* and `K`, `N`, `R`, `S` say how to read the tensors and are refused where a tensor is too small.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_gemm.h"
|
||||
@@ -40,9 +35,8 @@ static inline int64_t row_slot(const RadTensor* slot, int64_t m, int64_t S) {
|
||||
return (s >= 0 && s < S) ? s : -1;
|
||||
}
|
||||
|
||||
/* A pool operand [S, rows, cols]: its three strides. The pools are whole declared buffers and so
|
||||
* dense in the engine; a rank-3 tensor is read through its own strides anyway, because "the
|
||||
* engine's buffers are dense" is a fact about one caller and not about the op. */
|
||||
/* A pool operand [S, rows, cols]: its three strides. The engine's pools are dense, but a rank-3
|
||||
* tensor is read through its own strides: density is a fact about one caller, not about the op. */
|
||||
struct Pool3 { int64_t s0, s1, s2; };
|
||||
static inline Pool3 pool3(const RadTensor* t, int64_t rows, int64_t cols) {
|
||||
if (t->rank == 3) return Pool3{ t->stride[0], t->stride[1], t->stride[2] };
|
||||
@@ -77,12 +71,10 @@ int ref_lora_shrink(const RadArgs* a, RadStream) {
|
||||
if (coded_act(X->dtype) && !XS) return RAD_E_INVAL; /* a code without its scale */
|
||||
if (T->dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
|
||||
/* gemm_nt_q's reading of the scale stream, and a `group` cross-check: the stream states the
|
||||
* group, and a parameter whose GRID disagrees with it is a caller describing other bytes. The
|
||||
* grid -- groups along K -- and not the number, because a K no wider than one group has one
|
||||
* group whatever `group` says (a 64-wide row under 128), and from two groups up one power of
|
||||
* two gives each count. Absent the stream the parameter says nothing: a bf16 activation has no
|
||||
* scale whatever `group` holds. */
|
||||
/* gemm_nt_q's reading of the scale stream, and a `group` cross-check: a parameter whose grid
|
||||
* (groups along K) disagrees with the stream's describes other bytes. The grid and not the
|
||||
* number, because a K no wider than one group has one group whatever `group` says. Without a
|
||||
* stream the parameter says nothing: a float activation has no scale. */
|
||||
const Scales SA = make_scales(XS, M, K, false);
|
||||
const int64_t gp = p_int(a, "group", 0);
|
||||
if (gp > 0 && SA.p && (K + gp - 1) / gp != (K + SA.group - 1) / SA.group) return RAD_E_SHAPE;
|
||||
|
||||
@@ -101,6 +101,7 @@ int ref_quant_act_i8 (const RadArgs*, RadStream);
|
||||
int ref_quant_act_i8g (const RadArgs*, RadStream);
|
||||
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_givens_dense_quant(const RadArgs*, RadStream);
|
||||
int ref_givens_rotate(const RadArgs*, RadStream);
|
||||
@@ -142,6 +143,36 @@ 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_rms_mod(const RadArgs*, RadStream);
|
||||
int ref_rms_mod_quant_fp8(const RadArgs*, RadStream);
|
||||
int ref_flow_x0_step(const RadArgs*, RadStream);
|
||||
/* ref_video.cpp */
|
||||
int ref_patch_unfold(const RadArgs*, RadStream);
|
||||
int ref_vtile_gather(const RadArgs*, RadStream);
|
||||
int ref_vtile_stitch(const RadArgs*, RadStream);
|
||||
int ref_grid_pos3(const RadArgs*, RadStream);
|
||||
/* ref_vsa.cpp */
|
||||
int ref_vsa_select(const RadArgs*, RadStream);
|
||||
int ref_attn_vsa(const RadArgs*, RadStream);
|
||||
/* ref_audio.cpp */
|
||||
int ref_conv1d(const RadArgs*, RadStream);
|
||||
int ref_conv_t1d(const RadArgs*, RadStream);
|
||||
int ref_snake(const RadArgs*, RadStream);
|
||||
int ref_snake_aa(const RadArgs*, RadStream);
|
||||
int ref_cfg_topk_sample(const RadArgs*, RadStream);
|
||||
int ref_rvq_embed(const RadArgs*, RadStream);
|
||||
int ref_frame_mix_store(const RadArgs*, RadStream);
|
||||
int ref_end_status(const RadArgs*, RadStream);
|
||||
int ref_frame_store(const RadArgs*, RadStream);
|
||||
int ref_resample_nearest(const RadArgs*, RadStream);
|
||||
int ref_fourier_embed(const RadArgs*, RadStream);
|
||||
int ref_win_input(const RadArgs*, RadStream);
|
||||
int ref_win_prep(const RadArgs*, RadStream);
|
||||
int ref_win_finish(const RadArgs*, RadStream);
|
||||
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_chan_affine(const RadArgs*, RadStream);
|
||||
int ref_conv2d_nhwc(const RadArgs*, RadStream);
|
||||
int ref_l2norm_chan(const RadArgs*, RadStream);
|
||||
@@ -270,6 +301,7 @@ REF_SHAPE_FN(ref_quant_act_i8);
|
||||
REF_SHAPE_FN(ref_quant_act_i8g);
|
||||
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_givens_dense_quant);
|
||||
REF_SHAPE_FN(ref_givens_rotate);
|
||||
@@ -307,6 +339,33 @@ 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_rms_mod);
|
||||
REF_SHAPE_FN(ref_rms_mod_quant_fp8);
|
||||
REF_SHAPE_FN(ref_flow_x0_step);
|
||||
REF_SHAPE_FN(ref_patch_unfold);
|
||||
REF_SHAPE_FN(ref_vtile_gather);
|
||||
REF_SHAPE_FN(ref_vtile_stitch);
|
||||
REF_SHAPE_FN(ref_grid_pos3);
|
||||
REF_SHAPE_FN(ref_vsa_select);
|
||||
REF_SHAPE_FN(ref_attn_vsa);
|
||||
REF_SHAPE_FN(ref_conv1d);
|
||||
REF_SHAPE_FN(ref_conv_t1d);
|
||||
REF_SHAPE_FN(ref_snake);
|
||||
REF_SHAPE_FN(ref_snake_aa);
|
||||
REF_SHAPE_FN(ref_cfg_topk_sample);
|
||||
REF_SHAPE_FN(ref_rvq_embed);
|
||||
REF_SHAPE_FN(ref_frame_mix_store);
|
||||
REF_SHAPE_FN(ref_end_status);
|
||||
REF_SHAPE_FN(ref_frame_store);
|
||||
REF_SHAPE_FN(ref_resample_nearest);
|
||||
REF_SHAPE_FN(ref_fourier_embed);
|
||||
REF_SHAPE_FN(ref_win_input);
|
||||
REF_SHAPE_FN(ref_win_prep);
|
||||
REF_SHAPE_FN(ref_win_finish);
|
||||
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_chan_affine);
|
||||
REF_SHAPE_FN(ref_conv2d_nhwc);
|
||||
REF_SHAPE_FN(ref_l2norm_chan);
|
||||
|
||||
@@ -316,6 +316,39 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- quant_cols_fp8 */
|
||||
/* E4M3 codes with ONE scale per column over all M rows: scale[c] = amax_r |x[r, c]| times 1/448
|
||||
* in f32 (1 for an all-zero column), y = clamp(x * (1/scale), +-448) rounded to nearest even. The
|
||||
* value side of an attention's fp8 P.V: a column is one dimension of one head, so the scale
|
||||
* multiplies out of the sum over keys. */
|
||||
int ref_quant_cols_fp8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *y = &a->t[1], *s = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = numel(x) / n;
|
||||
if (rows <= 0 || numel(y) < rows * n || numel(s) < n) return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(x), ys = laststride(y), ss = laststride(s);
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
float amax = 0.0f;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const float m = std::fabs(ldt(x, rowoff(x, r, n) + c * xs));
|
||||
if (m > amax) amax = m;
|
||||
}
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float v = ldt(x, rowoff(x, r, n) + c * xs) * inv;
|
||||
if (v > 448.0f) v = 448.0f;
|
||||
if (v < -448.0f) v = -448.0f;
|
||||
stt(y, rowoff(y, r, n) + c * ys, v);
|
||||
}
|
||||
stt(s, c * ss, sc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- had_quant_act_fp8 */
|
||||
/* The same quantiser with a `group`-wide Hadamard before the absmax, which lowers the maximum the
|
||||
* grid is scaled by.
|
||||
|
||||
+339
-27
@@ -138,6 +138,9 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side")
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
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. */
|
||||
static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") };
|
||||
/* `scalar` 1 says `w` is one element rather than one row; kernels read that off the operand, but a
|
||||
* shape description needs the parameter. */
|
||||
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
|
||||
@@ -173,7 +176,8 @@ static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD
|
||||
OUT("y") };
|
||||
static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y"),
|
||||
WGT_O("b") };
|
||||
/* `M` is the table's rows, one per distance. */
|
||||
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
|
||||
P_STR("dtype") };
|
||||
@@ -205,6 +209,8 @@ static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") };
|
||||
/* No `asum`: it exists for asymmetric integer grids and fp8 is symmetric (as libr4d/r4d_rows.cpp
|
||||
* notes). */
|
||||
static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") };
|
||||
static const RadParamSpec pQuantCols[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oQuantCols[] = { OPD("x"), OUT("y"), OUT("scale") };
|
||||
/* ParoQuant's rotation, one per part, to f16 for the 16-bit GEMMs. The tables are the "givens"
|
||||
* encoding's (abi/rad_encoding.h) and are weight operands, so they are placed with their weight. */
|
||||
static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
|
||||
@@ -285,13 +291,13 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"
|
||||
static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"),
|
||||
WGT("bias"), OUT("y") };
|
||||
|
||||
/* RUNTIME LoRA, the two halves of y += scale * (B . (A . x)) at a trunk GEMM, per row: `slot` names
|
||||
/* Runtime LoRA, the two halves of y += scale * (B . (A . x)) at a trunk GEMM, per row: `slot` names
|
||||
* each row's adapter and a row outside [0, S) is a base row neither op touches. `a`/`a_scale` are
|
||||
* the GEMM's own first two operands, read as gemm_nt_q reads them, and `y` is its output. The pools
|
||||
* (`lora_a` [S, R, K], `lora_b` [S, N, R], `scale` [S, N]) are ordinary inputs and not weights: the
|
||||
* engine owns them as program buffers and copies an adapter into a slot between steps, so there is
|
||||
* no declared weight for an issue to name. `group` is OPTIONAL and 0 means no scale stream; `dtype`
|
||||
* is the tensor dtype name (rad_dtype_name) of `a` for shrink and of `y` for expand. */
|
||||
* (`lora_a` [S, R, K], `lora_b` [S, N, R], `scale` [S, N]) are inputs, not weights: the engine owns
|
||||
* them as program buffers and copies an adapter into a slot between steps. `group` is optional, 0
|
||||
* meaning no scale stream; `dtype` is the tensor dtype name (rad_dtype_name) of `a` for shrink and
|
||||
* of `y` for expand. */
|
||||
static const RadParamSpec pLoraShrink[] = { P_INT("M"), P_INT("K"), P_INT("R"), P_INT("S"),
|
||||
P_INTO("group"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLoraShrink[] = { OPD("a"), OPD_O("a_scale"), OPD("slot"),
|
||||
@@ -322,7 +328,8 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
|
||||
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_STR("dtype"), P_F64O("scale"),
|
||||
P_INTO("max_seqlen"), P_INTO("window"),
|
||||
P_INTO("cu_div"), P_INTO("block") };
|
||||
P_INTO("cu_div"), P_INTO("block"),
|
||||
P_INTO("window_right") };
|
||||
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OUT("out") };
|
||||
|
||||
@@ -339,7 +346,9 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he
|
||||
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
|
||||
P_F64O("yarn_factor"), P_F64O("yarn_low"),
|
||||
P_F64O("yarn_high"), P_F64O("yarn_magnitude"),
|
||||
P_STRO("ladder") };
|
||||
P_STRO("ladder"), P_F64O("llama3_factor"),
|
||||
P_F64O("llama3_low"), P_F64O("llama3_high"),
|
||||
P_F64O("llama3_orig") };
|
||||
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
|
||||
|
||||
/* The cos/sin plane a fused prologue reads instead of theta, at each position's own row of a
|
||||
@@ -399,8 +408,10 @@ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT
|
||||
P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"),
|
||||
P_F64O("wadd"), P_INTO("v_norm"), P_STRO("sections"),
|
||||
P_STRO("comps") };
|
||||
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"),
|
||||
WGT("k_w") };
|
||||
/* `positions` may be absent at `rotary_dim` 0 (the norm alone), and an absent gain is a unit
|
||||
* one. */
|
||||
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD_O("positions"), WGT_O("q_w"),
|
||||
WGT_O("k_w") };
|
||||
|
||||
/* ---- mixture of experts ------------------------------------------------------------------- */
|
||||
static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"),
|
||||
@@ -646,11 +657,26 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"),
|
||||
/* ---- image generation (ref_gen.cpp) --------------------------------------------------------- */
|
||||
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 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"),
|
||||
P_INT("gated"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"),
|
||||
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"),
|
||||
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"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"),
|
||||
OUT_O("z") };
|
||||
/* `t`, `sigma` and `sigma_next` are one f32 value each. */
|
||||
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
|
||||
INOUT("x") };
|
||||
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
|
||||
P_INTO("round"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
|
||||
@@ -664,8 +690,9 @@ 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") };
|
||||
/* `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_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") };
|
||||
@@ -677,11 +704,113 @@ static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") };
|
||||
static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"),
|
||||
P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
|
||||
P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") };
|
||||
static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"),
|
||||
OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"),
|
||||
P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk"),
|
||||
P_STRO("pv") };
|
||||
static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD_O("kv_cache"),
|
||||
OPD_O("block_table"), OPD_O("seqused"), OPD("cu_seqlens"),
|
||||
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"),
|
||||
OPD_O("k_scale"), OUT("out") };
|
||||
OPD_O("k_scale"), OUT("out"), OPD_O("v_scale") };
|
||||
|
||||
/* ---- video generation (ref_video.cpp). `geom` is the request's latent geometry, i32 on the
|
||||
* device: (F, Hp, Wp) for patch_unfold, (frames, H, W) for vtile_gather and (frames, H, W, first,
|
||||
* last) for vtile_stitch. */
|
||||
static const RadParamSpec pPatchUnfold[] = { P_INT("M"), P_INT("C"), P_INT("pt"), P_INT("ph"),
|
||||
P_INT("pw"), P_STR("mul"), P_STR("add"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oPatchUnfold[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pVtileGather[] = { P_INT("M"), P_INT("n"), P_INT("tile"),
|
||||
P_INT("overlap"), P_INT("frames"), P_INT("period"),
|
||||
P_INT("n_reg"), P_STR("dtype") };
|
||||
static const RadOperandSpec oVtileGather[] = { OPD("x"), WGT("reg"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("scale"), P_INT("pt"), P_INT("skip"),
|
||||
P_INT("keep"), P_INT("blend"), P_INT("period"),
|
||||
P_STR("mean"), P_STR("std") };
|
||||
static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") };
|
||||
/* `y` is [3, >= M], component-major at its own row pitch. */
|
||||
static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_INT("W"),
|
||||
P_INT("period"), P_F64("scale") };
|
||||
static const RadOperandSpec oGridPos3[] = { OUT("y") };
|
||||
/* ---- video sparse attention (ref_vsa.cpp). `segs` cuts the rows into dense segments and the
|
||||
* video grid, last; `geom` is the request's RadVideoGeom on the device (RAD_VGEOM_*). The two ops
|
||||
* share their parameters: attn_vsa recomputes k from `sparsity`. `v` of vsa_select is read for
|
||||
* `coarse` alone, and attn_vsa's `gate` comes with its `coarse`. */
|
||||
static const RadParamSpec pVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"),
|
||||
P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"),
|
||||
P_F64("sparsity"), P_F64O("scale") };
|
||||
static const RadOperandSpec oVsaSelect[] = { OPD("q"), OPD("k"), OPD_O("v"), OPD("segs"),
|
||||
OPD("geom"), OUT("sel"), OUT_O("coarse") };
|
||||
/* attn_vsa adds attn_prefix_self's int8 Q.K form at the end: `qk` "i8" with `k_i8` and `k_scale`,
|
||||
* quant_act_i8g's codes and scales of k at group head_dim. */
|
||||
static const RadParamSpec pAttnVsa[] = { P_INT("M"), P_INT("head_dim"), P_INT("tile_t"),
|
||||
P_INT("tile_h"), P_INT("tile_w"), P_INT("patch"),
|
||||
P_F64("sparsity"), P_F64O("scale"), P_STRO("qk"),
|
||||
P_STRO("pv") };
|
||||
static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("segs"),
|
||||
OPD("geom"), OPD("sel"), OPD_O("coarse"),
|
||||
OPD_O("gate"), OUT("out"), OPD_O("k_i8"),
|
||||
OPD_O("k_scale"), OPD_O("v_scale") };
|
||||
|
||||
/* ---- audio generation (ref_audio.cpp) */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
P_INTO("causal") };
|
||||
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
|
||||
OUT("y"), WGT_O("b") };
|
||||
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
|
||||
P_STR("dtype"), P_INTO("pad"), P_INTO("k") };
|
||||
static const RadOperandSpec oConvT1d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("cu_seqlens"),
|
||||
OUT("y") };
|
||||
static const RadParamSpec pSnake[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("log") };
|
||||
static const RadOperandSpec oSnake[] = { OPD("x"), WGT("alpha"), OUT("y"), WGT_O("beta") };
|
||||
static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"),
|
||||
P_INTO("log"), P_STR("dtype") };
|
||||
static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"), WGT("f_up"),
|
||||
WGT("f_down"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
|
||||
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
|
||||
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
|
||||
P_INTO("sup_hi"), P_F64O("penalty") };
|
||||
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
|
||||
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
|
||||
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
|
||||
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
|
||||
P_STR("dtype"), P_INTO("round") };
|
||||
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
|
||||
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
|
||||
P_INTO("rep"), P_STR("dtype") };
|
||||
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
|
||||
OPD("frame"), OPD("status"), INOUT("dst") };
|
||||
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
|
||||
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
|
||||
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
|
||||
P_INTO("rep"), P_INTO("skip") };
|
||||
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
|
||||
OPD("status"), INOUT("dst") };
|
||||
static const RadParamSpec pFourier[] = { P_INT("M"), P_INT("n"), P_INTO("round"), P_STR("dtype") };
|
||||
static const RadOperandSpec oFourier[] = { OPD("t"), WGT("w"), OUT("y") };
|
||||
static const RadParamSpec pWinInput[] = { P_INT("M"), P_INT("n_lat"), P_INT("n_zero"),
|
||||
P_INT("n_cond"), P_INT("stride"), P_STR("dtype") };
|
||||
static const RadOperandSpec oWinInput[] = { OPD("lat"), OPD("cond"), OPD("lat_cu"), OPD("win_lane"),
|
||||
OPD("pair"), OUT("y") };
|
||||
static const RadParamSpec pWinPrep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_INT("ov"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oWinPrep[] = { OPD("flags"), OPD("t"), OPD("seed"), OPD("win_index"),
|
||||
OPD("win_lane"), OPD("pair"), OPD("lat_cu"),
|
||||
OPD("prev"), INOUT("noise"), INOUT("lat") };
|
||||
static const RadParamSpec pWinFinish[] = { P_INT("M"), P_INT("n"), P_INT("n_cond"), P_INT("stride"),
|
||||
P_INT("ov"), P_STR("dtype") };
|
||||
static const RadOperandSpec oWinFinish[] = { OPD("flags"), OPD("pair"), OPD("win_lane"),
|
||||
OPD("lat_cu"), OPD("cond"), INOUT("lat"),
|
||||
INOUT("prev"), INOUT("prev_cond") };
|
||||
static const RadParamSpec pChanSplit[] = { P_INT("M"), P_INT("n"), P_INT("parts"), P_STR("dtype") };
|
||||
static const RadParamSpec pInterleave[] = { P_INT("M"), P_STR("dtype") };
|
||||
static const RadOperandSpec oInterleave2[] = { OPD("a"), OPD("b"), OUT("y") };
|
||||
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 RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
|
||||
|
||||
/* ================================================================== the schema table */
|
||||
static const RadOpSchema kSchemas[] = {
|
||||
@@ -733,9 +862,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
"antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a "
|
||||
"triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps "
|
||||
"normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." },
|
||||
{ "add", ARR(pMnD), ARR(oBinary),
|
||||
{ "add", ARR(pAdd), ARR(oBinary),
|
||||
"y = a + b. An operand carrying exactly n elements against a taller output broadcasts along "
|
||||
"rows; nothing else broadcasts." },
|
||||
"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`." },
|
||||
{ "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 "
|
||||
@@ -766,7 +896,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"as [cout, cin*kh*kw] is the convolution. Segments, cu_div and valid as conv2d's." },
|
||||
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
|
||||
"Causal depthwise convolution over time: y[t, c] = sum_j w[c, 0, j] * x[t - (k-1) + j, c], rows "
|
||||
"before the segment's start (cu/cu_div) read as zeros. f32 sum, one rounding." },
|
||||
"before the segment's start (cu/cu_div) read as zeros, plus the optional bias b[c]. f32 sum, "
|
||||
"one rounding." },
|
||||
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin),
|
||||
"Row d: sin(d * inv[i]) then cos(d * inv[i]) over n/2 timescales, inv[i] = exp(i * "
|
||||
"-log(max_timescale) / max(n/2 - 1, 1)), each step in f32, rounded once." },
|
||||
@@ -869,6 +1000,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
"scale shaped [M, ceil(n/group)] in f32. An all-zero group gets scale 1, not scale 0: the GEMM "
|
||||
"multiplies this scale by the weight's block scale, and a zero here would erase that one. Rows "
|
||||
"are dim 0, so a rank-3 activation is one row per token and not one per head." },
|
||||
{ "quant_cols_fp8", ARR(pQuantCols), ARR(oQuantCols),
|
||||
"E4M3 codes with one scale per column over all M rows: scale[c] = amax_r |x[r, c]| / 448 (1 for "
|
||||
"an all-zero column), y = clamp(x / scale, +-448). An attention's values for its fp8 P.V, where "
|
||||
"a column's scale multiplies out of the sum over keys." },
|
||||
{ "rmsnorm_quant_fp8", ARR(pRmsQuantFp8), ARR(oRmsQuantFp8),
|
||||
"RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The residual "
|
||||
"add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over is the bf16 "
|
||||
@@ -948,7 +1083,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
"t[m, j] = sum_k x(m, k) * lora_a[s, j, k] for each row m whose s = slot[m] is in [0, S), f32 "
|
||||
"accumulate, k ascending; x(m, k) is the value gemm_nt_q uses for that element of `a` (a code "
|
||||
"times its group's scale from `a_scale`, a float as it is). A row outside [0, S) is a base row "
|
||||
"and its `t` row is NOT WRITTEN. A row's bytes do not depend on M or on any other row." },
|
||||
"and its `t` row is not written. A row's bytes do not depend on M or on any other row." },
|
||||
{ "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand),
|
||||
"y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m whose s = "
|
||||
"slot[m] is in [0, S), f32 accumulate, j ascending, one rounding to y's dtype. A base row's `y` "
|
||||
@@ -964,8 +1099,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
|
||||
"Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is "
|
||||
"attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < "
|
||||
"window; 0 none. `block` cuts a segment into blocks of that many rows from its start, each "
|
||||
"attending within itself; 0 none." },
|
||||
"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." },
|
||||
{ "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." },
|
||||
@@ -1004,11 +1140,18 @@ static const RadOpSchema kSchemas[] = {
|
||||
"`sections` of frequencies, one ladder), \"imrope\" (Qwen3-VL's interleaved sections) or "
|
||||
"\"axial\" (contiguous sections, each on its own ladder -- a 2-D rotary). `positions` is [M], "
|
||||
"or [C, M] component-major for a multi-component mode; with [M] every component is that one. "
|
||||
"`scale` divides the position; `rotary_dim` is optional and defaults to head_dim." },
|
||||
"An f32 `positions` holds the positions as they are (fractional coordinates), an integer one "
|
||||
"integers. "
|
||||
"`scale` divides the position; `rotary_dim` is optional and defaults to head_dim. `llama3_*` "
|
||||
"applies Llama 3's frequency scaling (factor, low and high frequency factors, the original "
|
||||
"length)." },
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope),
|
||||
"Per-head RMS norm of q and k against their own gains, then rope. THE NORM OUTPUT IS ROUNDED "
|
||||
"TO THE TENSOR'S DTYPE BEFORE THE ROTATION, which is what the unfused pair does. `v_norm` 1 "
|
||||
"also RMS-norms each v head with a unit gain, unrotated." },
|
||||
"also RMS-norms each v head with a unit gain, unrotated. An absent gain is a unit gain "
|
||||
"without `wadd`; `rotary_dim` 0 is the norm alone, `positions` then optional. `mode` "
|
||||
"\"axial\" is rope's axial (its section ladders also over rank-1 positions), and f32 "
|
||||
"positions are read as rope reads them." },
|
||||
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
"y[m, i] = x[m, i] * act(s[m]): one scalar per ROW, broadcast ACROSS the row. `mul` broadcasts "
|
||||
@@ -1201,8 +1344,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the row's "
|
||||
"sequence's modulation row of `s` ([n_seq, >= n] at its own pitch). A diffusion transformer's "
|
||||
"adaptive norm without a shift." },
|
||||
{ "gate_add", ARR(pMnD), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual added through its sequence's gate row." },
|
||||
{ "gate_add", ARR(pGateAdd), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual added through its sequence's gate row; "
|
||||
"with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))." },
|
||||
{ "timestep_embed", ARR(pTimestep), ARR(oTimestep),
|
||||
"the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2)) with "
|
||||
"t' = scale * t; `round` 1 takes t through bf16 at scale and back first, as diffusers' "
|
||||
@@ -1223,7 +1367,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"latent with flag 4, the kept region of a repaint restored with flag 2 (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)." },
|
||||
"bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul). `round` 0 keeps the lists and "
|
||||
"the arithmetic in f32, rounded once into y: rd(f32(x * mul) + add), rd(f32(x - add) / mul)." },
|
||||
{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc),
|
||||
"an image convolution, channels innermost: x [Hin, Win * cin] and y [Hout, Wout * cout] dense, "
|
||||
"the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input "
|
||||
@@ -1253,6 +1398,115 @@ static const RadOpSchema kSchemas[] = {
|
||||
"rint(clamp(x * (1/scale), +-127))), the query and each prefix key are quantised by the same "
|
||||
"rule per (row, head), and a score is the exact integer dot product times both scales. `k` is "
|
||||
"then not read for the own rows." },
|
||||
/* ---- video generation -------------------------------------------------------------------- */
|
||||
{ "rms_mod", ARR(pRmsMod), ARR(oRmsMod),
|
||||
"a DiT's adaptive RMS norm with a shift: with `gated` 1 first x = bf16(x + bf16(g[seq] * y)) "
|
||||
"(no tanh), stored; then n1 = bf16(x * rsqrt(mean(x^2) + eps)), n2 = bf16(n1 * w), "
|
||||
"m = bf16(n2 * bf16(1 + scale[seq])), z = bf16(m + shift[seq]), `s` [n_seq, >= 2n] holding "
|
||||
"[shift | scale] at its own pitch." },
|
||||
{ "rms_mod_quant_fp8", ARR(pRmsModQ), ARR(oRmsModQ),
|
||||
"rms_mod with the norm chain in bf16, then (q, scale) = quant_act_fp8(z, group) as "
|
||||
"ln_mod_quant_fp8 makes them; z written when bound." },
|
||||
{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0),
|
||||
"a sampler step toward a data-ward velocity's clean estimate, in f32: st = 1 - t, "
|
||||
"d = x + st v, r = sigma_next / sigma, x = r x + (1 - r) d, each product and sum rounded "
|
||||
"once; t, sigma and sigma_next one value each (MiniMax-H3's scheduler)." },
|
||||
{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold),
|
||||
"patch rows [F Hp Wp, C pt ph pw] (geom = (F, Hp, Wp)) unfolded to voxel rows "
|
||||
"[(F pt) (Hp ph) (Wp pw), C] and denormalised, f32(f32(x * mul[c]) + add[c]) with `mul` and "
|
||||
"`add` lists of C f32 values." },
|
||||
{ "vtile_gather", ARR(pVtileGather), ARR(oVtileGather),
|
||||
"a video decoder's tiles out of voxel rows [frames H W, n] (geom = (frames, H, W)): each axis "
|
||||
"split into tile-wide tiles at least `overlap` apart (diffusers' _split_tiles), tile k at rows "
|
||||
"[k period, (k + 1) period) of y as its frames tile tile voxels, then n_reg rows of `reg`, then "
|
||||
"zeros." },
|
||||
{ "vtile_stitch", ARR(pVtileStitch), ARR(oVtileStitch),
|
||||
"a decoded chunk's tiles stitched into frames (each tile's kept range, blended with the tile "
|
||||
"above and then the tile to the left, both as decoded), the first `blend` kept frames blended "
|
||||
"with `prev` unless the chunk is first, prev refilled from the chunk's tail (also emitted "
|
||||
"when it is last), then bytes round(255 clamp(v std + mean, 0, 1)); geom = (frames, H, W, "
|
||||
"first, last), u8 out." },
|
||||
{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3),
|
||||
"a video decoder's rotary positions over tiles of `period` rows: token (t, i, j) of a tile's "
|
||||
"T x H x W gets f32(scale) * (2 (c + 0.5) / n - 1) on each axis, in f32 as torch makes it, "
|
||||
"the rest of the period 0; y f32 [3, >= M] component-major at its own row pitch." },
|
||||
{ "vsa_select", ARR(pVsa), ARR(oVsaSelect),
|
||||
"video sparse attention's tile selection. Tiles: each dense segment of `segs` in chunks of "
|
||||
"tile_t tile_h tile_w rows (P prefix tiles), then tile_t x tile_h x tile_w boxes over the "
|
||||
"F x Hp x Wp video grid (geom's frames, height / patch, width / patch), box (a, b, c) tile "
|
||||
"P + (a nb + b) nc + c (V of them). S = f32 tile means of q and k, dotted, times scale; a video "
|
||||
"query tile's sel[h][i][0, k) is its k = max(1, min(ceil((1 - sparsity) V), V)) (f64) video "
|
||||
"tiles of largest S, ties to the lower, ascending. With `coarse` (and `v`): softmax over all "
|
||||
"tiles of S times the tile means of v, rounded once." },
|
||||
{ "attn_vsa", ARR(pAttnVsa), ARR(oAttnVsa),
|
||||
"video sparse attention: a prefix query tile sees every tile, a video one the prefix tiles and "
|
||||
"its k tiles of `sel` (k ascending video tiles, RAD_E_INVAL otherwise); f32 softmax with the "
|
||||
"max subtracted. With `coarse` and `gate`: out = rd(rd(o) + coarse[h][tile] gate), rd the "
|
||||
"output's dtype." },
|
||||
{ "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 "
|
||||
"dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each "
|
||||
"sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1])." },
|
||||
{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d),
|
||||
"a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` "
|
||||
"((k - stride) / 2 by default, 0 the causal form): each sequence of x [rows, cin] grows "
|
||||
"`stride` times into y [rows * stride, cout], output row o reading the input rows i with "
|
||||
"0 <= o + pad - i stride < k; PyTorch's [cin, cout, k] weight and a bias." },
|
||||
{ "snake", ARR(pSnake), ARR(oSnake),
|
||||
"the snake activation per channel: x + sin(alpha x)^2 / (alpha + 1e-9), or with `beta` "
|
||||
"x + (1 / (beta + 1e-9)) sin(alpha x)^2; `log` 1 stores both as logarithms." },
|
||||
{ "snake_aa", ARR(pSnakeAa), ARR(oSnakeAa),
|
||||
"BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled `ratio` "
|
||||
"times by the transposed `f_up` filter, SnakeBeta, replicate-padded and filtered by `f_down` "
|
||||
"at stride `ratio` (docs/OPS.md has the paddings and crops); `log` 1 reads alpha and beta "
|
||||
"as logarithms." },
|
||||
{ "cfg_topk_sample", ARR(pCfgTopk), ARR(oCfgTopk),
|
||||
"one pick a lane from `rep` branch rows of logits (1 or 2, conditional first): guidance "
|
||||
"u + cfg (c - u) (`cfg` [n] per lane when bound), a repetition `penalty` over the lane's "
|
||||
"history `hist` (cleared at frame 0, the pick recorded), ids in [sup_lo, sup_hi) never "
|
||||
"candidates, with `cond_k` > 0 only the entries where c reaches its cond_k-th largest, the k "
|
||||
"largest kept (ties to the lower index), over `temp`, softmax, drawn by inverse CDF with "
|
||||
"rad_philox_uniform_s(seed, 2^32 + frame, stream); written to every one of the lane's slots." },
|
||||
{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed),
|
||||
"a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum "
|
||||
"of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or "
|
||||
"with `round` 1 one f32 sum in codebook order times scale, rounded once." },
|
||||
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
|
||||
"a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, "
|
||||
"stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." },
|
||||
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
|
||||
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
|
||||
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
|
||||
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = "
|
||||
"codes[k, rep i] when frame >= skip and status[lane] >= 0." },
|
||||
{ "resample_nearest", ARR(pMnD), ARR(oUnary),
|
||||
"rows resampled nearest-neighbour: output row j reads input row min(floor(j * in / out), "
|
||||
"in - 1) in f32, the row counts read off the operands." },
|
||||
{ "fourier_embed", ARR(pFourier), ARR(oFourier),
|
||||
"[cos(2 pi t w) | sin(2 pi t w)] of t [M] f32 and a trained w [n / 2]; `round` 1 rounds each "
|
||||
"tensor a bf16 reference holds (t, 2 pi t, the product, each cosine and sine)." },
|
||||
{ "win_input", ARR(pWinInput), ARR(oWinInput),
|
||||
"a denoiser's input for its window entries: [lat | zeros | cond] from each entry's lane of the "
|
||||
"latent and conditioning states, zeros for the conditioning of an unconditional entry "
|
||||
"(pair -2)." },
|
||||
{ "win_prep", ARR(pWinPrep), ARR(oWinPrep),
|
||||
"a window step's start for each entry that moves its lane: flag 1 draws the window's noise "
|
||||
"(rad_philox_normal_s(seed, 1 + win_index, .)) into the lane, keeping its first `ov` rows with "
|
||||
"flag 16; flag 16 binds the first rows to the previous window's end, "
|
||||
"bf16(bf16(1 - bf16((1 - 1e-6) t)) noise + bf16(t prev))." },
|
||||
{ "win_finish", ARR(pWinFinish), ARR(oWinFinish),
|
||||
"a window's end (flag 8): with flag 16 its first rows become the previous window's end "
|
||||
"exactly; rows [max(0, n - 2 ov), max(.., n - ov)) of the latent and the conditioning are kept "
|
||||
"as the next window's prev and prev_cond." },
|
||||
{ "chan_split", ARR(pChanSplit), ARR(oUnary),
|
||||
"x [rows, parts * n] to y [parts * rows, n]: each channel group a sequence of its own." },
|
||||
{ "interleave2", ARR(pInterleave), ARR(oInterleave2),
|
||||
"two streams interleaved, y [rows, 2] = (a[r], b[r])." },
|
||||
{ "iota", ARR(pIota), ARR(oIota),
|
||||
"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." },
|
||||
};
|
||||
|
||||
/* ================================================================== the kernel table */
|
||||
@@ -1463,6 +1717,8 @@ SIMPLE("ref_quant_act_i8g", "quant_act_i8g", "quant",
|
||||
"float in, i8 out, f32 scale", ref_quant_act_i8g),
|
||||
SIMPLE("ref_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser",
|
||||
"float in, fp8_e4m3 out, f32 scale", ref_quant_act_fp8),
|
||||
SIMPLE("ref_quant_cols_fp8", "quant_cols_fp8", "quant", "E4M3 with one scale per column",
|
||||
"float in, fp8_e4m3 out, f32 scale", ref_quant_cols_fp8),
|
||||
/* The fused fp8 forms, so a host-backend run can start on an fp8 model (see ref_quant.cpp). */
|
||||
SIMPLE("ref_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant",
|
||||
"RMS norm, optional residual add, and the E4M3 quantiser in one pass",
|
||||
@@ -1632,7 +1888,8 @@ SIMPLE("ref_sample_merge_topk", "sample_merge_topk", "sample",
|
||||
"vocab-parallel candidate merge", DT_FLOAT, ref_sample_merge_topk),
|
||||
SIMPLE("ref_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + a sequence's scale row)",
|
||||
DT_FLOAT, ref_ln_mod),
|
||||
SIMPLE("ref_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, ref_gate_add),
|
||||
SIMPLE("ref_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT,
|
||||
ref_gate_add),
|
||||
SIMPLE("ref_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
|
||||
"gated residual, gainless layer norm times (1 + scale row), block-scaled E4M3",
|
||||
DT_FLOAT, ref_ln_mod_quant_fp8),
|
||||
@@ -1664,6 +1921,61 @@ SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]",
|
||||
ref_scatter_add_rows),
|
||||
SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn",
|
||||
"attention over a paged prefix and the step's own rows", DT_FLOAT, ref_attn_prefix_self),
|
||||
SIMPLE("ref_rms_mod", "rms_mod", "norm",
|
||||
"gated residual, RMS norm with a gain times (1 + scale row) plus a shift row", DT_FLOAT,
|
||||
ref_rms_mod),
|
||||
SIMPLE("ref_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
|
||||
"gated residual, modulated RMS norm, block-scaled E4M3", DT_FLOAT, ref_rms_mod_quant_fp8),
|
||||
SIMPLE("ref_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate",
|
||||
DT_FLOAT, ref_flow_x0_step),
|
||||
SIMPLE("ref_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows",
|
||||
DT_FLOAT, ref_patch_unfold),
|
||||
SIMPLE("ref_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent",
|
||||
DT_FLOAT, ref_vtile_gather),
|
||||
SIMPLE("ref_vtile_stitch", "vtile_stitch", "elem",
|
||||
"decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT,
|
||||
ref_vtile_stitch),
|
||||
SIMPLE("ref_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles",
|
||||
DT_FLOAT, ref_grid_pos3),
|
||||
SIMPLE("ref_vsa_select", "vsa_select", "attn",
|
||||
"video sparse attention's top-k tiles by pooled score, and the coarse branch",
|
||||
"float q, k, v and coarse; i32 segs, geom and sel", ref_vsa_select),
|
||||
SIMPLE("ref_attn_vsa", "attn_vsa", "attn",
|
||||
"block-sparse attention over the prefix and selected video tiles, the gated coarse term",
|
||||
"float q, k, v, coarse, gate and out; i32 segs, geom and sel", ref_attn_vsa),
|
||||
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",
|
||||
DT_FLOAT, ref_conv_t1d),
|
||||
SIMPLE("ref_snake", "snake", "elem", "the snake activation", DT_FLOAT, ref_snake),
|
||||
SIMPLE("ref_snake_aa", "snake_aa", "elem", "the alias-free SnakeBeta: upsample, snake, downsample",
|
||||
DT_FLOAT, ref_snake_aa),
|
||||
SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick a lane",
|
||||
DT_FLOAT, ref_cfg_topk_sample),
|
||||
SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
|
||||
DT_FLOAT, ref_rvq_embed),
|
||||
SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane",
|
||||
DT_FLOAT, ref_frame_mix_store),
|
||||
SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
|
||||
ref_end_status),
|
||||
SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
|
||||
ref_frame_store),
|
||||
SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
|
||||
DT_ANY, ref_resample_nearest),
|
||||
SIMPLE("ref_fourier_embed", "fourier_embed", "elem", "random Fourier features of a time",
|
||||
DT_FLOAT, ref_fourier_embed),
|
||||
SIMPLE("ref_win_input", "win_input", "elem", "a denoiser's input from the window states",
|
||||
DT_FLOAT, ref_win_input),
|
||||
SIMPLE("ref_win_prep", "win_prep", "elem", "a window step's noise and overlap", DT_FLOAT,
|
||||
ref_win_prep),
|
||||
SIMPLE("ref_win_finish", "win_finish", "elem", "a window's end and the overlap it hands on",
|
||||
DT_FLOAT, ref_win_finish),
|
||||
SIMPLE("ref_chan_split", "chan_split", "elem", "channel groups to sequences", DT_ANY,
|
||||
ref_chan_split),
|
||||
SIMPLE("ref_interleave2", "interleave2", "elem", "two streams interleaved", DT_ANY,
|
||||
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),
|
||||
};
|
||||
|
||||
/* ================================================================== plugin exports */
|
||||
|
||||
+526
-15
@@ -65,9 +65,11 @@
|
||||
|
||||
/* rad_param_find / rad_param_getdim / rad_param_gets / rad_dtype_parse. */
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_runtime.h" /* RAD_VGEOM_N */
|
||||
#include "rad_sample.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <initializer_list>
|
||||
@@ -531,6 +533,7 @@ int ref_conv1d_dw_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
|
||||
o.t(D, { C, 1, K }); /* w */
|
||||
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M / cdiv, C }); /* y */
|
||||
o.skip(); /* b */
|
||||
return o.finish("conv1d_dw", operand, out);
|
||||
}
|
||||
|
||||
@@ -809,6 +812,16 @@ int ref_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
return o.finish("quant_act_fp8", operand, out);
|
||||
}
|
||||
|
||||
int ref_quant_cols_fp8_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);
|
||||
Opd o;
|
||||
o.t(D, { M, n }); /* x */
|
||||
o.t((uint32_t)RAD_F8E4M3, { M, n }); /* y */
|
||||
o.t((uint32_t)RAD_F32, { n }); /* scale, one a column (amax / 448) */
|
||||
return o.finish("quant_cols_fp8", operand, out);
|
||||
}
|
||||
|
||||
/* `n` is K on both axes of the accumulator: h is [n, n], not [M, n]. */
|
||||
int ref_gram_accum_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);
|
||||
@@ -1009,14 +1022,13 @@ int ref_gemm_nt_q_bias_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
|
||||
return gemm_q_shape(p, n_p, operand, true, out);
|
||||
}
|
||||
|
||||
/* RUNTIME LoRA. `slot` is drawn in [0, S] -- S ITSELF IS A BASE ROW, one past the pool -- so a cold
|
||||
* draw exercises the rows neither op may touch as well as the adapter rows; a draw never yields
|
||||
* -1, which is the other spelling of a base row, so that one is a hand case (tests/lora_test.cpp,
|
||||
* ref_test). A single row is drawn in [0, S): a one-row call whose row drew S would write nothing,
|
||||
* and a comparison of nothing proves nothing (rad-avx-check refuses it as vacuous). The scale stream exists only beside a coded activation: a bf16, f16 or f32 `a` is
|
||||
* read as it stands, the way gemm_nt_q's fp8a16 form reads it, and an fp8 or i8 one without its
|
||||
* scale is refused by the launch. `group` defaults to the 128 every block-scaled checkpoint and
|
||||
* quantiser in this project uses when the geometry does not state one. */
|
||||
/* Runtime LoRA. `slot` is drawn in [0, S], S itself being a base row one past the pool, so a cold
|
||||
* draw covers the rows neither op may touch as well as the adapter rows. A draw never yields -1,
|
||||
* the other spelling of a base row, which is a hand case (tests/lora_ops_test.cpp, ref_test). A
|
||||
* single row is drawn in [0, S): a one-row call whose row drew S would write nothing, which
|
||||
* rad-avx-check refuses as vacuous. The scale stream exists only beside a coded activation; a float
|
||||
* `a` is read as it stands, as gemm_nt_q's fp8a16 form reads it. `group` defaults to 128, the
|
||||
* block every block-scaled checkpoint and quantiser here uses, when the geometry states none. */
|
||||
int ref_lora_shrink_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), K = gi(p, n_p, "K", 0);
|
||||
@@ -1187,9 +1199,14 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
* interleaved q/gate view that parameters cannot describe; opshapes.h declines it.) */
|
||||
o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */
|
||||
/* `blocks` takes positions [C, M], component-major, C one past the largest `comps` entry (the
|
||||
* section count without `comps`). */
|
||||
* section count without `comps`); `axial` one component a section. Without a rotation
|
||||
* (`rotary_dim` 0) the positions are not passed. */
|
||||
const char* mode = gs(p, n_p, "mode");
|
||||
if (mode && !std::strcmp(mode, "blocks")) {
|
||||
const bool blocks = mode && !std::strcmp(mode, "blocks");
|
||||
const bool axial = mode && !std::strcmp(mode, "axial");
|
||||
if (gi(p, n_p, "rotary_dim", hd) == 0) {
|
||||
o.skip(); /* positions */
|
||||
} else if (blocks || axial) {
|
||||
int64_t nc = 0;
|
||||
for (const char* q = gs(p, n_p, "sections"); q && *q; ) {
|
||||
char* e = nullptr;
|
||||
@@ -1198,7 +1215,7 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
|
||||
++nc;
|
||||
q = e;
|
||||
}
|
||||
if (const char* cs = gs(p, n_p, "comps")) {
|
||||
if (const char* cs = blocks ? gs(p, n_p, "comps") : nullptr) {
|
||||
int64_t mx = -1;
|
||||
for (const char* q = cs; *q; ) {
|
||||
char* e = nullptr;
|
||||
@@ -2172,6 +2189,58 @@ int ref_ln_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
o.t(D, { M, n }); /* z */
|
||||
return o.finish("ln_mod_quant_fp8", operand, out);
|
||||
}
|
||||
/* rms_mod's branch and gate are passed when `gated`, and absent otherwise. */
|
||||
int ref_rms_mod_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;
|
||||
if (gi(p, n_p, "gated", 0)) {
|
||||
o.t(D, { M, n }); /* y */
|
||||
o.t(D, { 1, n }); /* g: one sequence */
|
||||
} else {
|
||||
o.skip();
|
||||
o.skip();
|
||||
}
|
||||
o.t(D, { 1, 2 * n }); /* s: [shift | scale] */
|
||||
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 */
|
||||
return o.finish("rms_mod", operand, out);
|
||||
}
|
||||
int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
if (gi(p, n_p, "gated", 0)) {
|
||||
o.t(D, { M, n }); /* y */
|
||||
o.t(D, { 1, n }); /* g */
|
||||
} else {
|
||||
o.skip();
|
||||
o.skip();
|
||||
}
|
||||
o.t(D, { 1, 2 * n }); /* s */
|
||||
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 */
|
||||
o.t((uint32_t)RAD_F32, { M, ng }); /* scale */
|
||||
o.t(D, { M, n }); /* z */
|
||||
return o.finish("rms_mod_quant_fp8", operand, out);
|
||||
}
|
||||
/* The sampler's three scalars in (0, 1), the state f32. */
|
||||
int ref_flow_x0_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);
|
||||
const uint32_t F = (uint32_t)RAD_F32;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), { M, n }); /* v */
|
||||
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t */
|
||||
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */
|
||||
o.t_fill(F, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_next */
|
||||
o.t(F, { M, n }); /* x, INOUT */
|
||||
return o.finish("flow_x0_step", operand, out);
|
||||
}
|
||||
int ref_gate_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
@@ -2345,13 +2414,24 @@ int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
const uint32_t Q = act_dt(p, n_p);
|
||||
const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype"));
|
||||
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv;
|
||||
/* `max_ctx` 0 declares the prefix-free form: no cache, block table or prefix lengths. */
|
||||
const bool pre = gi(p, n_p, "max_ctx", -1) != 0;
|
||||
const char* pv = gs(p, n_p, "pv");
|
||||
const bool pv8 = pv && !std::strcmp(pv, "fp8");
|
||||
if (pv8 && pre) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(Q, { M, nh, hd }); /* q */
|
||||
o.t(Q, { M, kvh, hd }); /* k */
|
||||
o.t(Q, { M, kvh, hd }); /* v */
|
||||
o.t(KV, { S * max_blocks, kvh, bs, 2 * hd }); /* kv_cache */
|
||||
o.t_idx({ S, max_blocks }, S * max_blocks, -1, 0); /* block_table: may repeat */
|
||||
o.t_idx({ S }, 0, P, 0); /* seqused: the prefix depth */
|
||||
o.t(pv8 ? (uint32_t)RAD_F8E4M3 : Q, { M, kvh, hd }); /* v */
|
||||
if (pre) {
|
||||
o.t(KV, { S * max_blocks, kvh, bs, 2 * hd }); /* kv_cache */
|
||||
o.t_idx({ S, max_blocks }, S * max_blocks, -1, 0); /* block_table: may repeat */
|
||||
o.t_idx({ S }, 0, P, 0); /* seqused: the prefix depth */
|
||||
} else {
|
||||
o.skip();
|
||||
o.skip();
|
||||
o.skip();
|
||||
}
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.skip(); /* k_descale */
|
||||
o.skip(); /* v_descale */
|
||||
@@ -2364,6 +2444,8 @@ int ref_attn_prefix_self_shape(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
o.skip();
|
||||
}
|
||||
o.t(Q, { M, nh, hd }); /* out */
|
||||
if (pv8) o.t((uint32_t)RAD_F32, { kvh * hd }); /* v_scale: one a column */
|
||||
else o.skip();
|
||||
return o.finish("attn_prefix_self", operand, out);
|
||||
}
|
||||
|
||||
@@ -2408,3 +2490,432 @@ int ref_scatter_add_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDe
|
||||
o.t(D, { 4 * M, n }); /* x, inout */
|
||||
return o.finish("scatter_add_rows", operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== video generation
|
||||
*
|
||||
* The request's geometry is a device operand, and a description can only draw an index operand
|
||||
* as one value throughout, so every axis of `geom` is one extent c: a c x c x c grid (and, for
|
||||
* vtile_stitch, a chunk that is its video's first and last). The ranged M is the output's rows;
|
||||
* an M below what the grid writes declines, and rows past it are left as drawn. */
|
||||
|
||||
/* The tiles split_tiles (ref_video.cpp) lays over `len` latent units, 0 where none fit. */
|
||||
static int64_t tile_count(int64_t len, int64_t tile, int64_t overlap) {
|
||||
if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return 0;
|
||||
if (tile >= len) return len == tile ? 1 : 0;
|
||||
int64_t nt = (len + tile - 1) / tile;
|
||||
while (tile * nt - overlap * (nt - 1) - len < 0) ++nt;
|
||||
return nt;
|
||||
}
|
||||
|
||||
/* A 2 x 2 x 2 grid of patches. */
|
||||
int ref_patch_unfold_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0);
|
||||
const int64_t pt = gi(p, n_p, "pt", 0), ph = gi(p, n_p, "ph", 0), pw = gi(p, n_p, "pw", 0);
|
||||
const int64_t c = 2, vol = pt * ph * pw;
|
||||
if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || M < c * c * c * vol) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { c * c * c, C * vol }); /* x: patch rows */
|
||||
o.t_idx({ 3 }, 0, c, 0); /* geom: (F, Hp, Wp) */
|
||||
o.t(D, { M, C }); /* y: voxel rows */
|
||||
return o.finish("patch_unfold", operand, out);
|
||||
}
|
||||
|
||||
/* A latent of `frames` frames, as tall and as wide as it is long. */
|
||||
int ref_vtile_gather_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), tile = gi(p, n_p, "tile", 0);
|
||||
const int64_t ov = gi(p, n_p, "overlap", 0), c = gi(p, n_p, "frames", 0);
|
||||
const int64_t period = gi(p, n_p, "period", 0), n_reg = gi(p, n_p, "n_reg", 0);
|
||||
const int64_t nt = tile_count(c, tile, ov);
|
||||
if (n <= 0 || nt <= 0 || n_reg < 0 || period < c * tile * tile + n_reg ||
|
||||
M < nt * nt * period)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { c * c * c, n }); /* x: voxel rows */
|
||||
o.t(D, { n_reg > 0 ? n_reg : 1, n }); /* reg */
|
||||
o.t_idx({ 3 }, 0, c, 0); /* geom: (frames, H, W) */
|
||||
o.t(D, { M, n }); /* y */
|
||||
return o.finish("vtile_gather", operand, out);
|
||||
}
|
||||
|
||||
/* The smallest grid the chunk's frames and the tile fit. */
|
||||
int ref_vtile_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 ov = gi(p, n_p, "overlap", 0), S = gi(p, n_p, "scale", 0);
|
||||
const int64_t pt = gi(p, n_p, "pt", 0), skip = gi(p, n_p, "skip", 0);
|
||||
const int64_t keep = gi(p, n_p, "keep", 0), blend = gi(p, n_p, "blend", 0);
|
||||
const int64_t period = gi(p, n_p, "period", 0);
|
||||
if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep <= 0 || blend < 0 || blend > keep)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const int64_t c = std::max(tile, (2 * skip + keep + blend + pt - 1) / pt);
|
||||
const int64_t nt = tile_count(c, tile, ov), npx = c * S * c * S;
|
||||
if (nt <= 0 || period < c * tile * tile || M < (keep + blend) * npx) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { nt * nt * period, 3 * pt * S * S }); /* x: the decoded tiles */
|
||||
o.t_idx({ 5 }, 0, c, 0); /* geom: first and last set */
|
||||
o.t(D, { blend > 0 ? blend * npx : 1, 3 }); /* prev, INOUT */
|
||||
o.t((uint32_t)RAD_U8, { M, 3 }); /* y */
|
||||
return o.finish("vtile_stitch", operand, out);
|
||||
}
|
||||
|
||||
int ref_grid_pos3_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((uint32_t)RAD_F32, { 3, M }); /* y: one row a component */
|
||||
return o.finish("grid_pos3", operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== video sparse attention
|
||||
*
|
||||
* The tiles come from the values of `segs` and `geom`, which a description draws only as
|
||||
* cumulative lengths and as one value c in every entry. So the grid is a cube of c frames and
|
||||
* c / patch rows and columns, c the smallest that gives every axis an edge box (more than one box,
|
||||
* the last short), and `segs` cuts M into M / (F Hp Wp) segments of the grid's rows each, the last
|
||||
* the video; an M not a multiple of the grid declines. `n_head` (default 2) and `dtype` (default
|
||||
* bf16) are the description's, as is `coarse`: 0 leaves the optional operands out.
|
||||
*
|
||||
* attn_vsa's `sel` is drawn as one value, the first video tile, which is a selection only at
|
||||
* k = 1; any other sparsity declines (the hand-built cases build selections,
|
||||
* libavx/avx_check_hand.cpp). */
|
||||
namespace {
|
||||
|
||||
struct VsaGeo {
|
||||
int64_t M, hd, nh, c, n_seg, P, V, N, k;
|
||||
uint32_t D;
|
||||
bool coarse;
|
||||
};
|
||||
|
||||
/* An axis of `len` units over boxes of `t` has more than one box, the last short; a box of one
|
||||
* unit needs only a second unit. */
|
||||
bool vsa_edge(int64_t len, int64_t t) { return t > 1 ? len > t && len % t != 0 : len > 1; }
|
||||
|
||||
int vsa_geo(const RadParam* p, int n_p, VsaGeo* g) {
|
||||
g->M = gi(p, n_p, "M", 0);
|
||||
g->hd = gi(p, n_p, "head_dim", 0);
|
||||
g->nh = gi(p, n_p, "n_head", 2);
|
||||
const int64_t tt = gi(p, n_p, "tile_t", 0), th = gi(p, n_p, "tile_h", 0);
|
||||
const int64_t tw = gi(p, n_p, "tile_w", 0), patch = gi(p, n_p, "patch", 0);
|
||||
const double sparsity = rad_param_getf(p, n_p, "sparsity", -1.0);
|
||||
if (g->M <= 0 || g->hd <= 0 || g->nh <= 0 || tt <= 0 || th <= 0 || tw <= 0 || patch <= 0 ||
|
||||
!(sparsity >= 0.0 && sparsity < 1.0))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
int64_t c = 1;
|
||||
while (c <= 4096 && !(vsa_edge(c, tt) && vsa_edge(c / patch, th) && vsa_edge(c / patch, tw)))
|
||||
++c;
|
||||
const int64_t hp = c / patch, rows = c * hp * hp, TT = tt * th * tw;
|
||||
if (c > 4096 || g->M % rows != 0) return RAD_E_UNSUPPORTED;
|
||||
g->c = c;
|
||||
g->n_seg = g->M / rows;
|
||||
g->P = (g->n_seg - 1) * ((rows + TT - 1) / TT);
|
||||
g->V = ((c + tt - 1) / tt) * ((hp + th - 1) / th) * ((hp + tw - 1) / tw);
|
||||
g->N = g->P + g->V;
|
||||
const double keep = (1.0 - sparsity) * (double)g->V;
|
||||
g->k = std::max<int64_t>(1, std::min<int64_t>((int64_t)std::ceil(keep), g->V));
|
||||
g->D = act_dt(p, n_p);
|
||||
g->coarse = gi(p, n_p, "coarse", 1) != 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int ref_vsa_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
VsaGeo g{};
|
||||
if (vsa_geo(p, n_p, &g) != RAD_OK) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* q */
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* k */
|
||||
if (g.coarse) o.t(g.D, { g.M, g.nh, g.hd }); else o.skip(); /* v */
|
||||
o.t_idx({ g.n_seg + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* segs */
|
||||
o.t_idx({ RAD_VGEOM_N }, 0, g.c, 0); /* geom: c everywhere */
|
||||
/* A tile row and a slot past the selection's, which nothing writes. */
|
||||
o.t((uint32_t)RAD_I32, { g.nh, g.N + 1, g.k + 1 }); /* sel */
|
||||
if (g.coarse) o.t(g.D, { g.nh, g.N + 1, g.hd }); else o.skip(); /* coarse */
|
||||
return o.finish("vsa_select", operand, out);
|
||||
}
|
||||
|
||||
int ref_attn_vsa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
VsaGeo g{};
|
||||
if (vsa_geo(p, n_p, &g) != RAD_OK || g.k != 1) return RAD_E_UNSUPPORTED;
|
||||
const char* pv = gs(p, n_p, "pv");
|
||||
const bool pv8 = pv && !std::strcmp(pv, "fp8");
|
||||
Opd o;
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* q */
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* k */
|
||||
o.t(pv8 ? (uint32_t)RAD_F8E4M3 : g.D, { g.M, g.nh, g.hd }); /* v */
|
||||
o.t_idx({ g.n_seg + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* segs */
|
||||
o.t_idx({ RAD_VGEOM_N }, 0, g.c, 0); /* geom: c everywhere */
|
||||
o.t_idx({ g.nh, g.N, 1 }, g.N, g.P, 0); /* sel: the first video tile */
|
||||
if (g.coarse) {
|
||||
o.t(g.D, { g.nh, g.N, g.hd }); /* coarse */
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* gate */
|
||||
} else {
|
||||
o.skip();
|
||||
o.skip();
|
||||
}
|
||||
o.t(g.D, { g.M, g.nh, g.hd }); /* out */
|
||||
const char* qk = gs(p, n_p, "qk");
|
||||
if (qk && !std::strcmp(qk, "i8")) {
|
||||
o.t((uint32_t)RAD_I8, { g.M, g.nh, g.hd }); /* k_i8 */
|
||||
o.t((uint32_t)RAD_F32, { g.M, g.nh }); /* k_scale */
|
||||
} else {
|
||||
o.skip();
|
||||
o.skip();
|
||||
}
|
||||
if (pv8) o.t((uint32_t)RAD_F32, { g.nh * g.hd }); /* v_scale: one a column */
|
||||
else o.skip();
|
||||
return o.finish("attn_vsa", operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== audio generation
|
||||
* Sequenced ops (the convolutions) are described over two sequences where M allows; lane ops over
|
||||
* REF_LANES lanes, as the image generator's are. */
|
||||
static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; }
|
||||
|
||||
int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
|
||||
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
|
||||
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t S = two_seqs(M);
|
||||
Opd o;
|
||||
o.t(D, { M, cin }); /* x */
|
||||
o.t(D, { cout, cin, k }); /* w */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M, cout }); /* res */
|
||||
o.t(D, { M, cout }); /* y */
|
||||
o.t(D, { cout }); /* b */
|
||||
return o.finish("conv1d", operand, out);
|
||||
}
|
||||
|
||||
int ref_conv_t1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
|
||||
const int64_t s = gi(p, n_p, "stride", 0), k = gi(p, n_p, "k", 2 * s);
|
||||
const int64_t pad = gi(p, n_p, "pad", -1);
|
||||
if (M <= 0 || cin <= 0 || cout <= 0 || s <= 0 || k < s || (pad < 0 && ((k - s) & 1)))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, cin }); /* x */
|
||||
o.t(D, { cin, cout, k }); /* w */
|
||||
o.t(D, { cout }); /* b */
|
||||
o.t_idx({ two_seqs(M) + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M * s, cout }); /* y */
|
||||
return o.finish("conv_t1d", operand, out);
|
||||
}
|
||||
|
||||
int ref_snake_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 }); /* x */
|
||||
/* alpha in (0, 1): a trained alpha is positive, and 1 / alpha near zero is no test. */
|
||||
o.t_fill((uint32_t)RAD_F32, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* alpha */
|
||||
o.t(D, { M, n }); /* y */
|
||||
o.skip(); /* beta */
|
||||
return o.finish("snake", operand, out);
|
||||
}
|
||||
|
||||
int ref_snake_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t R = gi(p, n_p, "ratio", 0), k = gi(p, n_p, "k", 0);
|
||||
if (M <= 0 || n <= 0 || R <= 0 || k < R) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p), F = (uint32_t)RAD_F32;
|
||||
Opd o;
|
||||
o.t(D, { M, n }); /* x */
|
||||
o.t_fill(F, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* alpha */
|
||||
o.t_fill(F, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* beta */
|
||||
o.t(F, { 1, 1, k }); /* f_up */
|
||||
o.t(F, { 1, 1, k }); /* f_down */
|
||||
o.t_idx({ two_seqs(M) + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M, n }); /* y */
|
||||
return o.finish("snake_aa", operand, out);
|
||||
}
|
||||
|
||||
int ref_cfg_topk_sample_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), V = gi(p, n_p, "n_vocab", 0), rep = gi(p, n_p, "rep", 1);
|
||||
if (M <= 0 || V <= 0 || rep < 1 || M % rep) return RAD_E_UNSUPPORTED;
|
||||
const int64_t n = M / rep;
|
||||
Opd o;
|
||||
o.t((uint32_t)RAD_F32, { M, V }); /* logits */
|
||||
o.t_idx({ 2 * n }, (int64_t)1 << 30, -1, 0); /* seed */
|
||||
o.t_idx({ n }, 9000, -1, 0); /* frame */
|
||||
o.t_idx({ M }, V, -1, 0); /* ids */
|
||||
o.skip(); /* cfg */
|
||||
o.skip(); /* lane */
|
||||
o.skip(); /* hist */
|
||||
return o.finish("cfg_topk_sample", operand, out);
|
||||
}
|
||||
|
||||
int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0);
|
||||
const int64_t K = gi(p, n_p, "n_codes", 0), voc = gi(p, n_p, "vocab", 0);
|
||||
const int64_t off0 = gi(p, n_p, "off0", 0);
|
||||
if (M <= 0 || D <= 0 || K < 1 || voc <= 0 || off0 < 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t B = (uint32_t)RAD_BF16;
|
||||
Opd o;
|
||||
o.t_idx({ K, M }, voc, -1, 0); /* codes */
|
||||
o.t(B, { off0 + voc, D }); /* t0 */
|
||||
o.t(B, { (K > 1 ? K - 1 : 1) * voc, D }); /* t1 */
|
||||
o.t(act_dt(p, n_p), { M, D }); /* y */
|
||||
return o.finish("rvq_embed", operand, out);
|
||||
}
|
||||
|
||||
int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0);
|
||||
const int64_t st = gi(p, n_p, "stride", 0);
|
||||
if (M <= 0 || D <= 0 || L <= 0 || st <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t A = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(A, { L * 2 * M, D }); /* hid: two branch rows a lane */
|
||||
o.t((uint32_t)RAD_F32, { L }); /* logits */
|
||||
o.t_fill((uint32_t)RAD_F32, { 1 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* scale */
|
||||
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ M }, st + 1, -1, 0); /* frame, 0 included */
|
||||
o.t_idx({ REF_LANES }, 8, -1, 0); /* status */
|
||||
o.t(A, { REF_LANES * st, D }); /* dst, INOUT */
|
||||
return o.finish("frame_mix_store", operand, out);
|
||||
}
|
||||
|
||||
int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), end = gi(p, n_p, "end", 0);
|
||||
if (M <= 0 || rep < 1 || M > REF_LANES) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
/* Ids over [0, 2 end): about half the lanes end. */
|
||||
o.t_idx({ rep * M }, end > 0 ? 2 * end : 2, -1, 0); /* ids */
|
||||
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ REF_LANES }, 8, -1, 0); /* status, INOUT */
|
||||
return o.finish("end_status", operand, out);
|
||||
}
|
||||
|
||||
int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0);
|
||||
const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1);
|
||||
if (M <= 0 || K <= 0 || st <= 0 || rep < 1 || M > REF_LANES) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t_idx({ K, rep * M }, 2048, -1, 0); /* codes */
|
||||
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ M }, st, -1, 0); /* frame */
|
||||
o.t_idx({ REF_LANES }, 8, -1, 0); /* status */
|
||||
o.t_idx({ REF_LANES * K, st }, 2048, -1, 0); /* dst, INOUT */
|
||||
return o.finish("frame_store", operand, out);
|
||||
}
|
||||
|
||||
int ref_resample_nearest_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);
|
||||
Opd o;
|
||||
o.t(D, { M / 3 + 1, n }); /* x: fewer rows than y */
|
||||
o.t(D, { M, n }); /* y */
|
||||
return o.finish("resample_nearest", operand, out);
|
||||
}
|
||||
|
||||
int ref_fourier_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
if (M <= 0 || n <= 0 || (n & 1)) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t_fill((uint32_t)RAD_F32, { M }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t in (0, 1) */
|
||||
o.t((uint32_t)RAD_F32, { n / 2 }); /* w */
|
||||
o.t(act_dt(p, n_p), { M, n }); /* y */
|
||||
return o.finish("fourier_embed", operand, out);
|
||||
}
|
||||
|
||||
int ref_win_input_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, "n_lat", 0), Z = gi(p, n_p, "n_zero", 0);
|
||||
const int64_t Dc = gi(p, n_p, "n_cond", 0), st = gi(p, n_p, "stride", 0);
|
||||
if (M <= 0 || C <= 0 || Z < 0 || Dc <= 0 || st <= 0) return RAD_E_UNSUPPORTED;
|
||||
const int64_t S = lane_entries(p, n_p, M, st);
|
||||
if (M > S * st) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t A = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(A, { REF_LANES * st, C }); /* lat */
|
||||
o.t(A, { REF_LANES * st, Dc }); /* cond */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */
|
||||
o.t_idx({ S }, REF_LANES, -1, 0); /* win_lane */
|
||||
o.t_idx({ S }, S, -1, 0); /* pair */
|
||||
o.t(A, { M, C + Z + Dc }); /* y */
|
||||
return o.finish("win_input", operand, out);
|
||||
}
|
||||
|
||||
int ref_win_prep_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);
|
||||
const int64_t ov = gi(p, n_p, "ov", 0);
|
||||
if (M <= 0 || n <= 0 || st <= 0 || ov <= 0 || ov > st) return RAD_E_UNSUPPORTED;
|
||||
const int64_t S = lane_entries(p, n_p, M, st);
|
||||
if (M > S * st) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t B = (uint32_t)RAD_BF16;
|
||||
Opd o;
|
||||
o.t_idx({ S }, 32, -1, 0); /* flags: every bit drawn */
|
||||
o.t_fill((uint32_t)RAD_F32, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* t */
|
||||
o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */
|
||||
o.t_idx({ S }, 64, -1, 0); /* win_index */
|
||||
/* Distinct: two entries moving one lane would race. */
|
||||
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* win_lane */
|
||||
o.t_idx({ S }, S, -1, 0); /* pair */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */
|
||||
o.t(B, { REF_LANES * ov, n }); /* prev */
|
||||
o.t(B, { REF_LANES * ov, n }); /* noise, INOUT */
|
||||
o.t(B, { REF_LANES * st, n }); /* lat, INOUT */
|
||||
return o.finish("win_prep", operand, out);
|
||||
}
|
||||
|
||||
int ref_win_finish_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), Dc = gi(p, n_p, "n_cond", 0);
|
||||
const int64_t st = gi(p, n_p, "stride", 0), ov = gi(p, n_p, "ov", 0);
|
||||
if (M <= 0 || n <= 0 || Dc <= 0 || st <= 0 || ov <= 0 || ov > st) return RAD_E_UNSUPPORTED;
|
||||
const int64_t S = lane_entries(p, n_p, M, st);
|
||||
if (M > S * st) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t B = (uint32_t)RAD_BF16;
|
||||
Opd o;
|
||||
o.t_idx({ S }, 32, -1, 0); /* flags */
|
||||
o.t_idx({ S }, S, -1, 0); /* pair */
|
||||
o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* win_lane */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* lat_cu */
|
||||
o.t(B, { REF_LANES * st, Dc }); /* cond */
|
||||
o.t(B, { REF_LANES * st, n }); /* lat, INOUT */
|
||||
o.t(B, { REF_LANES * ov, n }); /* prev, INOUT */
|
||||
o.t(B, { REF_LANES * ov, Dc }); /* prev_cond, INOUT */
|
||||
return o.finish("win_finish", operand, out);
|
||||
}
|
||||
|
||||
int ref_chan_split_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), P = gi(p, n_p, "parts", 0);
|
||||
if (M <= 0 || n <= 0 || P <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, P * n }); /* x */
|
||||
o.t(D, { P * M, n }); /* y */
|
||||
return o.finish("chan_split", operand, out);
|
||||
}
|
||||
|
||||
int ref_interleave2_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;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M }); /* a */
|
||||
o.t(D, { M }); /* b */
|
||||
o.t((uint32_t)RAD_F32, { M, 2 }); /* y */
|
||||
return o.finish("interleave2", operand, out);
|
||||
}
|
||||
|
||||
int ref_iota_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
if (M <= 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t_idx({ M }, 1, -1, 0); /* y */
|
||||
return o.finish("iota", operand, out);
|
||||
}
|
||||
|
||||
int ref_cu_repeat_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({ 1 }, 1000, -1, 0); /* len */
|
||||
o.t_idx({ M }, 1, -1, 0); /* y */
|
||||
return o.finish("cu_repeat", operand, out);
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
/* ref_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video
|
||||
* generation"): the denoised latent's patch rows unfolded to voxels, the tiles a video decoder
|
||||
* runs over, gathered from the latent and stitched back into frames, and the rotary positions of
|
||||
* a tile's tokens.
|
||||
*
|
||||
* Per-request geometry (a video's frames, height and width) comes from a `geom` operand the run
|
||||
* phase writes on the device, never from the parameters, which are fixed at declare. The tiles
|
||||
* are diffusers' AutoencoderKLMiniMaxH3 tiling in latent units, and the stitch rounds where its
|
||||
* bf16 blends round.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#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));
|
||||
}
|
||||
|
||||
/* A space-separated list of floats, kept in f32: a video's latent and pixel statistics are f32
|
||||
* tensors upstream, unlike the bf16 lists chan_affine reads. */
|
||||
int parse_f32_list(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();
|
||||
}
|
||||
|
||||
/* The tiles over one axis of `len` latent units, diffusers' _split_tiles in latent units: a tile
|
||||
* at least as long as the axis is the whole axis (and must be exactly as long, every tile being
|
||||
* tile x tile); otherwise the fewest tiles whose union covers the axis with every overlap at
|
||||
* least `overlap`, the slack added to the overlaps one unit at a time round-robin from the first,
|
||||
* and start[i + 1] = start[i] + tile - ov[i]. False where no such layout exists. */
|
||||
bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector<int64_t>* start,
|
||||
std::vector<int64_t>* ov) {
|
||||
start->clear();
|
||||
ov->clear();
|
||||
if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return false;
|
||||
if (tile >= len) {
|
||||
start->push_back(0);
|
||||
return len == tile;
|
||||
}
|
||||
int64_t nt = (len + tile - 1) / tile;
|
||||
while (tile * nt - overlap * (nt - 1) - len < 0) ++nt;
|
||||
ov->assign((size_t)(nt - 1), overlap);
|
||||
const int64_t rem = tile * nt - overlap * (nt - 1) - len;
|
||||
for (int64_t i = 0; i < rem; ++i) (*ov)[(size_t)(i % (nt - 1))] += 1;
|
||||
start->push_back(0);
|
||||
for (int64_t i = 0; i + 1 < nt; ++i) start->push_back(start->back() + tile - (*ov)[(size_t)i]);
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ patch_unfold */
|
||||
/* A video latent's patch rows unfolded to voxel rows and denormalised. x [F Hp Wp, C pt ph pw]
|
||||
* holds patch (f, i, j), frame-major then row-major, its column (c, a, b, d) at
|
||||
* c pt ph pw + a ph pw + b pw + d; y [(F pt) (Hp ph) (Wp pw), C] holds voxel (t, yy, xx)
|
||||
* row-major:
|
||||
*
|
||||
* y[(t, yy, xx), c] = f32(f32(x[(t / pt, yy / ph, xx / pw), (c, t % pt, yy % ph, xx % pw)]
|
||||
* * mul[c]) + add[c])
|
||||
*
|
||||
* `geom` is (F, Hp, Wp), the request's latent grid in patches. `mul` and `add` are C values each,
|
||||
* kept in f32 (the reference denormalises f32 latents with an f32 deviation and mean). y holds at
|
||||
* least the voxels' rows; rows past them are not written. */
|
||||
int ref_patch_unfold(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *geom = &a->t[1], *y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0);
|
||||
const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0);
|
||||
std::vector<float> mul, add;
|
||||
if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32_list(p_str(a, "mul", ""), &mul) != C ||
|
||||
parse_f32_list(p_str(a, "add", ""), &add) != C || numel(geom) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t F = ldi(geom, 0), Hp = ldi(geom, 1), Wp = ldi(geom, 2);
|
||||
if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Hv = Hp * ph, Wv = Wp * pw, K = C * pt * ph * pw, rows = F * pt * Hv * Wv;
|
||||
if (rows_of(y, C) < rows || rows_of(x, K) < F * Hp * Wp) return RAD_E_SHAPE;
|
||||
REF_PAR_FOR(rows * C)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t t = r / (Hv * Wv), yy = (r / Wv) % Hv, xx = r % Wv;
|
||||
const int64_t patch = ((t / pt) * Hp + yy / ph) * Wp + xx / pw;
|
||||
const int64_t sub = ((t % pt) * ph + yy % ph) * pw + xx % pw;
|
||||
const int64_t xb = rowoff(x, patch, K), xs = laststride(x);
|
||||
const int64_t yb = rowoff(y, r, C), ys = laststride(y);
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
stt(y, yb + c * ys,
|
||||
ldt(x, xb + (c * pt * ph * pw + sub) * xs) * mul[(size_t)c] + add[(size_t)c]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ grid_pos3 */
|
||||
/* A video decoder's rotary positions over consecutive tiles: row m is token k = m % period of its
|
||||
* tile, the tile's T x H x W tokens first ((t, i, j) row-major) and the period's remaining rows
|
||||
* (register tokens) at position 0. Each axis is the token's centre normalised to [-1, 1) and
|
||||
* scaled, in f32 as torch's 2 * (arange(0.5, n) / n) - 1 makes it:
|
||||
*
|
||||
* g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1) y[axis][m] = f32(f32(scale) g)
|
||||
*
|
||||
* y is f32 [3, >= M], component-major, each component a row at the operand's own pitch (a [3, M]
|
||||
* view of a wider buffer); M is its row length. */
|
||||
int ref_grid_pos3(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 1)) return RAD_E_INVAL;
|
||||
const RadTensor* y = &a->t[0];
|
||||
const int64_t T = p_int(a, "T", 0), H = p_int(a, "H", 0), W = p_int(a, "W", 0);
|
||||
const int64_t period = p_int(a, "period", 0);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
if (T <= 0 || H <= 0 || W <= 0 || period < T * H * W || y->rank != 2 || y->shape[0] < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t M = y->shape[1], rs = y->stride[0], cs = y->stride[1];
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
auto g = [](int64_t c, int64_t n) {
|
||||
const float q = ((float)c + 0.5f) / (float)n;
|
||||
return 2.0f * q - 1.0f;
|
||||
};
|
||||
REF_PAR_FOR(M * 3)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const int64_t k = m % period;
|
||||
float p[3] = { 0.0f, 0.0f, 0.0f };
|
||||
if (k < T * H * W) {
|
||||
p[0] = scale * g(k / (H * W), T);
|
||||
p[1] = scale * g((k / W) % H, H);
|
||||
p[2] = scale * g(k % W, W);
|
||||
}
|
||||
for (int c = 0; c < 3; ++c) stt(y, c * rs + m * cs, p[c]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_gather */
|
||||
/* The tiles a video decoder runs over, gathered from voxel rows x [frames H W, n] ((t, yy, xx)
|
||||
* row-major), `geom` = (frames, H, W) in latent units, its frames those of the `frames`
|
||||
* parameter. Each spatial axis is split by split_tiles (`tile`, `overlap`) and the tiles are taken
|
||||
* row-major over (row band, column band). Tile k is rows [k period, (k + 1) period) of y: its
|
||||
* frames tile tile voxels (t, ty, tx) row-major, from x's row (t, start_y + ty, start_x + tx);
|
||||
* then reg's first `n_reg` rows (a decoder's register tokens) in y's dtype; then zero rows to the
|
||||
* period. y holds at least n_tiles period rows. */
|
||||
int ref_vtile_gather(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *reg = &a->t[1], *geom = &a->t[2], *y = &a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0), tile = p_int(a, "tile", 0);
|
||||
const int64_t overlap = p_int(a, "overlap", 0), frames = p_int(a, "frames", 0);
|
||||
const int64_t period = p_int(a, "period", 0), n_reg = p_int(a, "n_reg", 0);
|
||||
const int64_t vox = frames * tile * tile;
|
||||
if (n <= 0 || tile <= 0 || frames <= 0 || n_reg < 0 || period < vox + n_reg ||
|
||||
numel(geom) < 3 || rows_of(reg, n) < n_reg)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = ldi(geom, 1), W = ldi(geom, 2);
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (ldi(geom, 0) != frames || !split_tiles(H, tile, overlap, &sy, &oy) ||
|
||||
!split_tiles(W, tile, overlap, &sx, &ox))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nw = (int64_t)sx.size(), rows = (int64_t)sy.size() * nw * period;
|
||||
if (rows_of(y, n) < rows || rows_of(x, n) < frames * H * W) return RAD_E_SHAPE;
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t row = 0; row < rows; ++row) {
|
||||
const int64_t k = row / period, p = row % period;
|
||||
const int64_t yb = rowoff(y, row, n), ys = laststride(y);
|
||||
if (p < vox) {
|
||||
const int64_t t = p / (tile * tile), ty = (p / tile) % tile, tx = p % tile;
|
||||
const int64_t src = (t * H + sy[(size_t)(k / nw)] + ty) * W + sx[(size_t)(k % nw)] + tx;
|
||||
const int64_t xb = rowoff(x, src, n), xs = laststride(x);
|
||||
for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(x, xb + c * xs));
|
||||
} else if (p < vox + n_reg) {
|
||||
const int64_t rb = rowoff(reg, p - vox, n), rs = laststride(reg);
|
||||
for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, ldt(reg, rb + c * rs));
|
||||
} else {
|
||||
for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, 0.0f);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_stitch */
|
||||
/* A decoded chunk's tiles stitched into frames, blended with the previous chunk's overlap, and
|
||||
* written as RGB bytes.
|
||||
*
|
||||
* x is the decoder's output over vtile_gather's tiles, [>= n_tiles period, 3 pt scale scale]:
|
||||
* tile k's row k period + (lt tile + ty) tile + tx, column
|
||||
* c pt scale^2 + a scale^2 + b scale + d, is colour c of pixel (ty scale + b, tx scale + d) of clip
|
||||
* frame lt pt + a. `geom` = (frames, H, W, first, last): the chunk's latent geometry, and whether
|
||||
* it is its video's first and last chunk (nonzero). Tiles are split_tiles' over H and W.
|
||||
*
|
||||
* Every product and sum below rounds to x's dtype (rd), as the reference's bf16 blends do, with
|
||||
* wa(p, e) = rd(1 - rd(p / e)) and wb(p, e) = rd(p / e). Pixel (Y, X) of clip frame fc belongs to
|
||||
* the tile (i, j) whose kept range holds it, [start_i scale, start_{i+1} scale) (the last tile to
|
||||
* its end), at (ly, lx) within it; T(i, j, ly, lx) is that tile's decoded value. The spatial
|
||||
* stitch blends the top ev = ov_y[i-1] scale rows with the tile above and then the left
|
||||
* eh = ov_x[j-1] scale columns with the tile to the left, both neighbours as decoded (never
|
||||
* blended):
|
||||
*
|
||||
* V = rd(rd(T(i-1, j, ly + tile scale - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev)))
|
||||
* when i > 0 and ly < ev, else T(i, j, ly, lx)
|
||||
* S = rd(rd(T(i, j-1, ly, lx + tile scale - eh) wa(lx, eh)) + rd(V wb(lx, eh)))
|
||||
* when j > 0 and lx < eh, else V
|
||||
*
|
||||
* Output frame k < keep is clip frame skip + k, its first `blend` frames blended with `prev`
|
||||
* unless the chunk is its video's first, v = rd(rd(prev[k] wa(k, blend)) + rd(S wb(k, blend)));
|
||||
* prev then becomes the frames S(2 skip + keep + k'), k' < blend, at prev's dtype; with `last`
|
||||
* those frames follow the kept ones in y. A byte is round-half-even(255 clamp(f32(f32(v std[c]) +
|
||||
* mean[c]), 0, 1)), `mean` and `std` three f32 values each. y is u8 [frames_out, H scale,
|
||||
* W scale, 3] and prev [blend, H scale, W scale, 3]; y holds at least the frames' rows. */
|
||||
int ref_vtile_stitch(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *geom = &a->t[1], *prev = &a->t[2], *y = &a->t[3];
|
||||
const int64_t tile = p_int(a, "tile", 0), overlap = p_int(a, "overlap", 0);
|
||||
const int64_t S = p_int(a, "scale", 0), pt = p_int(a, "pt", 0), skip = p_int(a, "skip", 0);
|
||||
const int64_t keep = p_int(a, "keep", 0), blend = p_int(a, "blend", 0);
|
||||
const int64_t period = p_int(a, "period", 0);
|
||||
std::vector<float> mean, stdv;
|
||||
if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep <= 0 || blend < 0 || blend > keep ||
|
||||
parse_f32_list(p_str(a, "mean", ""), &mean) != 3 ||
|
||||
parse_f32_list(p_str(a, "std", ""), &stdv) != 3 || numel(geom) < 5 || y->dtype != RAD_U8)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t frames = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2);
|
||||
const bool first = ldi(geom, 3) != 0, last = ldi(geom, 4) != 0;
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (frames <= 0 || 2 * skip + keep + blend > frames * pt || period < frames * tile * tile ||
|
||||
!split_tiles(H, tile, overlap, &sy, &oy) || !split_tiles(W, tile, overlap, &sx, &ox))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size(), cols = 3 * pt * S * S;
|
||||
if (rows_of(x, cols) < nh * nw * period) return RAD_E_SHAPE;
|
||||
const int64_t Hp = H * S, Wp = W * S, npx = Hp * Wp;
|
||||
const int64_t fout = keep + (last ? blend : 0);
|
||||
if (rows_of(y, 3) < fout * npx || (blend > 0 && rows_of(prev, 3) < blend * npx))
|
||||
return RAD_E_SHAPE;
|
||||
/* The owner tile and the offset in it of every pixel row and column. */
|
||||
std::vector<int64_t> own_y((size_t)Hp), own_x((size_t)Wp);
|
||||
for (int64_t Y = 0, i = 0; Y < Hp; ++Y) {
|
||||
while (i + 1 < nh && Y >= sy[(size_t)(i + 1)] * S) ++i;
|
||||
own_y[(size_t)Y] = i;
|
||||
}
|
||||
for (int64_t X = 0, j = 0; X < Wp; ++X) {
|
||||
while (j + 1 < nw && X >= sx[(size_t)(j + 1)] * S) ++j;
|
||||
own_x[(size_t)X] = j;
|
||||
}
|
||||
const uint32_t dt = x->dtype;
|
||||
auto rd = [dt](float v) { return round_dt(dt, v); };
|
||||
auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); };
|
||||
auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); };
|
||||
auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t fc, int64_t c) {
|
||||
const int64_t row = (i * nw + j) * period + ((fc / pt) * tile + ly / S) * tile + lx / S;
|
||||
const int64_t col = ((c * pt + fc % pt) * S + ly % S) * S + lx % S;
|
||||
return ldt(x, rowoff(x, row, cols) + col * laststride(x));
|
||||
};
|
||||
auto stitch = [&](int64_t fc, int64_t Y, int64_t X, int64_t c) {
|
||||
const int64_t i = own_y[(size_t)Y], j = own_x[(size_t)X];
|
||||
const int64_t ly = Y - sy[(size_t)i] * S, lx = X - sx[(size_t)j] * S;
|
||||
float v = T(i, j, ly, lx, fc, c);
|
||||
const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] * S : 0;
|
||||
if (ly < ev) {
|
||||
const float up = T(i - 1, j, ly + tile * S - ev, lx, fc, c);
|
||||
v = rd(rd(up * wa(ly, ev)) + rd(v * wb(ly, ev)));
|
||||
}
|
||||
const int64_t eh = j > 0 ? ox[(size_t)(j - 1)] * S : 0;
|
||||
if (lx < eh) {
|
||||
const float left = T(i, j - 1, ly, lx + tile * S - eh, fc, c);
|
||||
v = rd(rd(left * wa(lx, eh)) + rd(v * wb(lx, eh)));
|
||||
}
|
||||
return v;
|
||||
};
|
||||
auto byte = [&](int64_t f, int64_t px, int64_t c, float v) {
|
||||
float p = v * stdv[(size_t)c] + mean[(size_t)c];
|
||||
p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p);
|
||||
stt(y, rowoff(y, f * npx + px, 3) + c * laststride(y), p * 255.0f);
|
||||
};
|
||||
REF_PAR_FOR(npx * 3 * (fout + blend) * 4)
|
||||
for (int64_t px = 0; px < npx; ++px) {
|
||||
const int64_t Y = px / Wp, X = px % Wp;
|
||||
for (int64_t c = 0; c < 3; ++c) {
|
||||
for (int64_t k = 0; k < keep; ++k) {
|
||||
float v = stitch(skip + k, Y, X, c);
|
||||
if (!first && k < blend) {
|
||||
const int64_t pb = rowoff(prev, k * npx + px, 3);
|
||||
const float pv = ldt(prev, pb + c * laststride(prev));
|
||||
v = rd(rd(pv * wa(k, blend)) + rd(v * wb(k, blend)));
|
||||
}
|
||||
byte(k, px, c, v);
|
||||
}
|
||||
for (int64_t k = 0; k < blend; ++k) {
|
||||
const float v = stitch(2 * skip + keep + k, Y, X, c);
|
||||
if (last) byte(keep + k, px, c, v);
|
||||
stt(prev, rowoff(prev, k * npx + px, 3) + c * laststride(prev), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
/* ref_vsa.cpp -- video sparse attention (docs/OPS.md, "Video sparse attention"): the tile
|
||||
* selection and the block-sparse attention a step-distilled MiniMax-H3 was trained with.
|
||||
*
|
||||
* A pass's rows are one packed sequence cut by `segs` (cumulative row offsets from 0) into
|
||||
* segments: every segment but the last is dense (the text, the soundtrack), the last is the video
|
||||
* grid of F x Hp x Wp patch rows, (t, h, w) row-major, its extents read from the `geom` operand the
|
||||
* run phase writes on the device (RAD_VGEOM_*), never from the parameters, which are fixed at
|
||||
* declare. The tiles, at most TT = tile_t tile_h tile_w rows each:
|
||||
*
|
||||
* prefix each dense segment cut on its own into chunks of TT rows from its start, the last
|
||||
* chunk shorter, an empty segment none; tiles 0 .. P-1 in segment order
|
||||
* video boxes of tile_t x tile_h x tile_w over the grid, edge boxes smaller; box (a, b, c)
|
||||
* is tile P + (a nb + b) nc + c, nb and nc the boxes along h and w; V of them
|
||||
*
|
||||
* A tile's rows are taken in its (t, h, w) raster order, which fixes the order of every f32 sum
|
||||
* over a tile. Video query tiles keep the k = max(1, min(ceil((1 - sparsity) V), V)) video tiles
|
||||
* of largest pooled score, k computed in f64 as the trained schedule computes it, and see the
|
||||
* prefix tiles besides; prefix query tiles see every tile.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_gemm.h" /* row_stride */
|
||||
#include "ref_ops.h"
|
||||
#include "rad_runtime.h" /* RAD_VGEOM_* */
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
|
||||
/* `sparsity` at full precision, since k is computed from it in f64; NaN when absent, which every
|
||||
* caller refuses. As p_f32, an integer or string spelling is read for a direct caller. */
|
||||
double p_f64(const RadArgs* a, const char* k) {
|
||||
const RadParam* p = p_find(a, k);
|
||||
if (!p) return NAN;
|
||||
if (p->kind == RAD_P_F64) return p->dval;
|
||||
if (p->kind == RAD_P_STR && p->sval) return std::strtod(p->sval, nullptr);
|
||||
if (p->kind == RAD_P_INT) return (double)p->ival;
|
||||
return NAN;
|
||||
}
|
||||
|
||||
/* A call's tiles. */
|
||||
struct Tiles {
|
||||
int64_t R = 0; /* rows the tiles cover, segs[n_seg] */
|
||||
int64_t v0 = 0; /* the video grid's first row */
|
||||
int64_t tt = 0, th = 0, tw = 0; /* the box */
|
||||
int64_t F = 0, Hp = 0, Wp = 0; /* the grid */
|
||||
int64_t nb = 0, nc = 0; /* boxes along h and w */
|
||||
int64_t P = 0, V = 0, N = 0, k = 0;
|
||||
std::vector<int64_t> start, len; /* the prefix tiles' rows */
|
||||
};
|
||||
|
||||
/* The tiles of this call; RAD_E_SHAPE where `segs` is not cumulative offsets from 0 covering at
|
||||
* least one row and at most `rows`, the last segment is not the grid's F Hp Wp rows, a box extent
|
||||
* or `patch` is not positive, or `sparsity` is outside [0, 1). */
|
||||
int tiles_of(const RadArgs* a, const RadTensor* segs, const RadTensor* geom, int64_t rows,
|
||||
Tiles* g) {
|
||||
g->tt = p_int(a, "tile_t", 0);
|
||||
g->th = p_int(a, "tile_h", 0);
|
||||
g->tw = p_int(a, "tile_w", 0);
|
||||
const int64_t patch = p_int(a, "patch", 0);
|
||||
const double sparsity = p_f64(a, "sparsity");
|
||||
if (g->tt <= 0 || g->th <= 0 || g->tw <= 0 || patch <= 0 ||
|
||||
!(sparsity >= 0.0 && sparsity < 1.0))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n_seg = numel(segs) - 1;
|
||||
if (n_seg < 1 || numel(geom) <= RAD_VGEOM_LAT_W || cu_at(segs, 0) != 0) return RAD_E_SHAPE;
|
||||
for (int64_t s = 0; s < n_seg; ++s)
|
||||
if (cu_at(segs, s + 1) < cu_at(segs, s)) return RAD_E_SHAPE;
|
||||
g->R = cu_at(segs, n_seg);
|
||||
g->v0 = cu_at(segs, n_seg - 1);
|
||||
if (g->R <= 0 || g->R > rows) return RAD_E_SHAPE; /* zero rows is not a call */
|
||||
g->F = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_FRAMES));
|
||||
g->Hp = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_H)) / patch;
|
||||
g->Wp = ld_int(geom->dtype, geom->data, offlin(geom, RAD_VGEOM_LAT_W)) / patch;
|
||||
/* Each extent at most the rows first, so the product cannot overflow. */
|
||||
const int64_t vr = g->R - g->v0;
|
||||
if (g->F <= 0 || g->Hp <= 0 || g->Wp <= 0 || g->F > vr || g->Hp > vr || g->Wp > vr ||
|
||||
g->F * g->Hp * g->Wp != vr)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t TT = g->tt * g->th * g->tw;
|
||||
g->start.clear();
|
||||
g->len.clear();
|
||||
for (int64_t s = 0; s + 1 < n_seg; ++s)
|
||||
for (int64_t r = cu_at(segs, s), e = cu_at(segs, s + 1); r < e; r += TT) {
|
||||
g->start.push_back(r);
|
||||
g->len.push_back(std::min(TT, e - r));
|
||||
}
|
||||
g->nb = (g->Hp + g->th - 1) / g->th;
|
||||
g->nc = (g->Wp + g->tw - 1) / g->tw;
|
||||
g->P = (int64_t)g->start.size();
|
||||
g->V = (g->F + g->tt - 1) / g->tt * g->nb * g->nc;
|
||||
g->N = g->P + g->V;
|
||||
const double keep = (1.0 - sparsity) * (double)g->V;
|
||||
g->k = std::max<int64_t>(1, std::min<int64_t>((int64_t)std::ceil(keep), g->V));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Video tile j's box, [t0, t1) x [h0, h1) x [w0, w1) of the grid. */
|
||||
struct Box { int64_t t0, t1, h0, h1, w0, w1; };
|
||||
Box box_of(const Tiles& g, int64_t j) {
|
||||
const int64_t b = j - g.P, c = b % g.nc, bh = (b / g.nc) % g.nb, at = b / (g.nc * g.nb);
|
||||
return { at * g.tt, std::min(g.F, (at + 1) * g.tt), bh * g.th, std::min(g.Hp, (bh + 1) * g.th),
|
||||
c * g.tw, std::min(g.Wp, (c + 1) * g.tw) };
|
||||
}
|
||||
|
||||
int64_t tile_size(const Tiles& g, int64_t j) {
|
||||
if (j < g.P) return g.len[(size_t)j];
|
||||
const Box x = box_of(g, j);
|
||||
return (x.t1 - x.t0) * (x.h1 - x.h0) * (x.w1 - x.w0);
|
||||
}
|
||||
|
||||
/* fn(row) for every row of tile j, in its raster order. */
|
||||
template <class Fn>
|
||||
void tile_rows(const Tiles& g, int64_t j, Fn&& fn) {
|
||||
if (j < g.P) {
|
||||
for (int64_t r = g.start[(size_t)j], e = r + g.len[(size_t)j]; r < e; ++r) fn(r);
|
||||
return;
|
||||
}
|
||||
const Box x = box_of(g, j);
|
||||
for (int64_t t = x.t0; t < x.t1; ++t)
|
||||
for (int64_t h = x.h0; h < x.h1; ++h)
|
||||
for (int64_t w = x.w0; w < x.w1; ++w) fn(g.v0 + (t * g.Hp + h) * g.Wp + w);
|
||||
}
|
||||
|
||||
/* An operand read as [rows, n_head, head_dim]: rank 3, or rank 2 [rows, n_head head_dim] as a
|
||||
* column slice of a wider projection at its own row pitch (attn_dense's reading). */
|
||||
struct Heads {
|
||||
const RadTensor* t;
|
||||
int64_t rs, hs, ds;
|
||||
};
|
||||
Heads heads_of(const RadTensor* t, int64_t nh, int64_t hd) {
|
||||
Heads v{ t, 0, 0, 0 };
|
||||
v.ds = t->rank >= 2 ? t->stride[t->rank - 1] : 1;
|
||||
v.hs = t->rank >= 3 ? t->stride[t->rank - 2] : hd * v.ds;
|
||||
v.rs = row_stride(t, nh * hd);
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The head count `q` carries, or 0 when its shape is not [rows, n_head, head_dim] or
|
||||
* [rows, n_head head_dim]. */
|
||||
int64_t heads_in(const RadTensor* q, int64_t hd) {
|
||||
if (q->rank >= 3) return q->shape[q->rank - 1] == hd ? q->shape[q->rank - 2] : 0;
|
||||
if (q->rank == 2) return q->shape[1] % hd == 0 ? q->shape[1] / hd : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Rows of a per-(head, tile) operand, [n_head, tiles_cap, cols] read as [n_head tiles_cap, cols]:
|
||||
* tiles_cap, or 0 when the rows do not split evenly over the heads. */
|
||||
int64_t tiles_cap(const RadTensor* t, int64_t cols, int64_t nh) {
|
||||
const int64_t r = rows_of(t, cols);
|
||||
return r % nh == 0 ? r / nh : 0;
|
||||
}
|
||||
|
||||
/* The selection's order: the larger score first, NaN above every number (torch.topk's ranking),
|
||||
* equal scores (+0 and -0 among them) tied. */
|
||||
inline bool above(float a, float b) {
|
||||
if (a != a) return b == b;
|
||||
return b == b && a > b;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ vsa_select */
|
||||
/* Per head h and tile i, the f32 means of q, k and (with `coarse`) v over the tile's rows, each
|
||||
* summed in the tile's raster order and divided by its size:
|
||||
*
|
||||
* S[h][i][j] = f32(dot(qp[h][i], kp[h][j]) * scale) the dot an f32 sum in ascending d
|
||||
*
|
||||
* For a video query tile i, sel[h][i][0 .. k) is the k video tiles j of largest S[h][i][j],
|
||||
* ties to the lower tile, in ascending tile order: the k-th largest score is the threshold, every
|
||||
* tile above it is taken and the ties at it from the lowest. Prefix query tiles' rows of `sel`
|
||||
* and its slots past k are not written.
|
||||
*
|
||||
* With `coarse` (and `v`, read for it alone), for every tile i: p = softmax over all N tiles of
|
||||
* S[h][i][:] (the max subtracted, e_j = exp(S_j - max) summed in ascending j, p_j = e_j / sum),
|
||||
* coarse[h][i][d] = sum over ascending j of p_j vp[h][j][d], rounded once to coarse's dtype.
|
||||
* `sel` is i32 [n_head, tiles_cap >= N, k_cap >= k], `coarse` [n_head, tiles_cap >= N,
|
||||
* head_dim]. */
|
||||
int ref_vsa_select(const RadArgs* a, RadStream) {
|
||||
const RadTensor *q = t_in(a, 0), *k = t_in(a, 1), *v = t_in(a, 2), *segs = t_in(a, 3);
|
||||
const RadTensor *geom = t_in(a, 4), *sel = t_in(a, 5), *co = t_in(a, 6);
|
||||
if (!q || !k || !segs || !geom || !sel) return RAD_E_INVAL;
|
||||
if (!v != !co) return RAD_E_SHAPE;
|
||||
if (sel->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
const int64_t hd = p_int(a, "head_dim", 0);
|
||||
if (hd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t nh = heads_in(q, hd);
|
||||
if (nh <= 0) return RAD_E_SHAPE;
|
||||
Tiles g;
|
||||
RAD_REF_TRY(tiles_of(a, segs, geom, numel(q) / (nh * hd), &g));
|
||||
const int64_t need = g.R * nh * hd;
|
||||
if (numel(k) < need || (v && numel(v) < need)) return RAD_E_SHAPE;
|
||||
const int64_t kc = sel->rank ? sel->shape[sel->rank - 1] : 0;
|
||||
const int64_t scap = tiles_cap(sel, kc, nh);
|
||||
if (kc < g.k || scap < g.N) return RAD_E_SHAPE;
|
||||
const int64_t ccap = co ? tiles_cap(co, hd, nh) : 0;
|
||||
if (co && (co->shape[co->rank - 1] != hd || ccap < g.N)) return RAD_E_SHAPE;
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd));
|
||||
const Heads Q = heads_of(q, nh, hd), K = heads_of(k, nh, hd);
|
||||
const Heads Vh = v ? heads_of(v, nh, hd) : Heads{ nullptr, 0, 0, 0 };
|
||||
const int64_t N = g.N, P = g.P;
|
||||
|
||||
/* The pooled means, [n_head][N][head_dim] each. */
|
||||
std::vector<float> qp((size_t)(nh * N * hd)), kp(qp.size()), vp(co ? qp.size() : 0);
|
||||
REF_PAR_FOR(nh * g.R * hd * (co ? 3 : 2))
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
const int64_t h = u / N, j = u % N;
|
||||
float* qs = &qp[(size_t)(u * hd)];
|
||||
float* ks = &kp[(size_t)(u * hd)];
|
||||
float* vs = co ? &vp[(size_t)(u * hd)] : nullptr;
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
qs[d] = ks[d] = 0.0f;
|
||||
if (vs) vs[d] = 0.0f;
|
||||
}
|
||||
tile_rows(g, j, [&](int64_t r) {
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
qs[d] += ldt(q, r * Q.rs + h * Q.hs + d * Q.ds);
|
||||
ks[d] += ldt(k, r * K.rs + h * K.hs + d * K.ds);
|
||||
if (vs) vs[d] += ldt(v, r * Vh.rs + h * Vh.hs + d * Vh.ds);
|
||||
}
|
||||
});
|
||||
const float n = (float)tile_size(g, j);
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
qs[d] /= n;
|
||||
ks[d] /= n;
|
||||
if (vs) vs[d] /= n;
|
||||
}
|
||||
}
|
||||
|
||||
REF_PAR_FOR(nh * N * N * hd)
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
const int64_t h = u / N, i = u % N;
|
||||
if (i < P && !co) continue;
|
||||
/* Scores against every tile when the coarse branch needs them, else the video tiles. */
|
||||
const int64_t j0 = co ? 0 : P;
|
||||
std::vector<float> S((size_t)N, 0.0f);
|
||||
const float* qs = &qp[(size_t)(u * hd)];
|
||||
for (int64_t j = j0; j < N; ++j) {
|
||||
const float* ks = &kp[(size_t)((h * N + j) * hd)];
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d) dot += qs[d] * ks[d];
|
||||
S[(size_t)j] = dot * scale;
|
||||
}
|
||||
if (i >= P) {
|
||||
const int64_t V = g.V, kk = g.k;
|
||||
std::vector<float> ord(S.begin() + P, S.end());
|
||||
std::nth_element(ord.begin(), ord.begin() + (kk - 1), ord.end(), above);
|
||||
const float thr = ord[(size_t)(kk - 1)];
|
||||
int64_t ties = kk;
|
||||
for (int64_t j = 0; j < V; ++j) ties -= above(S[(size_t)(P + j)], thr);
|
||||
const int64_t sb = rowoff(sel, h * scap + i, kc), ss = laststride(sel);
|
||||
int64_t n = 0;
|
||||
for (int64_t j = 0; j < V; ++j) {
|
||||
const float s = S[(size_t)(P + j)];
|
||||
const bool take = above(s, thr) || (!above(thr, s) && ties-- > 0);
|
||||
if (take) st_int(sel->dtype, sel->data, sb + (n++) * ss, P + j);
|
||||
}
|
||||
}
|
||||
if (co) {
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = 0; j < N; ++j) if (S[(size_t)j] > mx) mx = S[(size_t)j];
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = 0; j < N; ++j) {
|
||||
S[(size_t)j] = ref_exp(S[(size_t)j] - mx);
|
||||
sum += S[(size_t)j];
|
||||
}
|
||||
std::vector<float> acc((size_t)hd, 0.0f);
|
||||
for (int64_t j = 0; j < N; ++j) {
|
||||
const float p = S[(size_t)j] / sum;
|
||||
const float* vs = &vp[(size_t)((h * N + j) * hd)];
|
||||
for (int64_t d = 0; d < hd; ++d) acc[(size_t)d] += p * vs[d];
|
||||
}
|
||||
const int64_t cb = rowoff(co, h * ccap + i, hd), cs = laststride(co);
|
||||
for (int64_t d = 0; d < hd; ++d) stt(co, cb + d * cs, acc[(size_t)d]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_vsa */
|
||||
/* Block-sparse softmax attention over the tiles, per head (q, k and v share their heads). A query
|
||||
* row of tile i sees the rows of every tile when i < P, else of the prefix tiles and the k video
|
||||
* tiles sel[h][i][0 .. k); each such row of `sel` must be k ascending video tiles, RAD_E_INVAL
|
||||
* otherwise, checked before anything is written. Keys are taken by ascending tile and each tile
|
||||
* in its raster order: every score f32(dot * scale) (the dot an f32 sum in ascending d), their
|
||||
* max, then e = exp(score - max) and e v accumulated in that order, o = acc * (1 / sum).
|
||||
*
|
||||
* out = o without coarse and gate
|
||||
* out = f32(rd(o) + f32(coarse[h][i] * gate[r, h])) with them
|
||||
*
|
||||
* rd rounding to out's dtype and the result rounded again by the store: FastVideo's inference
|
||||
* epilogue, the sparse output in bf16 and then out.addcmul_(coarse, gate) in bf16 with f32
|
||||
* arithmetic. `coarse` is vsa_select's, `gate` per element like q; both or neither.
|
||||
*
|
||||
* `qk` "i8" is the int8 score form: `k_i8` and `k_scale` are k's codes and per-(row, head) scales
|
||||
* as quant_act_i8g writes them at group head_dim, the query row is quantised here by the same rule,
|
||||
* and a score is f32(f32(f32(dot * q_scale) * k_scale) * scale) with the dot the codes' exact sum;
|
||||
* `k` is not read.
|
||||
*
|
||||
* `pv` "fp8" is the fp8 P.V form: `v` holds E4M3 codes with a scale per column in `v_scale`
|
||||
* (quant_cols_fp8), each weight p = exp(s - max) is taken to E4M3 at 448 p, and
|
||||
* o = (sum w v) v_scale / (448 sum p) in f32. */
|
||||
int ref_attn_vsa(const RadArgs* a, RadStream) {
|
||||
const RadTensor *q = t_in(a, 0), *k = t_in(a, 1), *v = t_in(a, 2), *segs = t_in(a, 3);
|
||||
const RadTensor *geom = t_in(a, 4), *sel = t_in(a, 5), *co = t_in(a, 6), *gt = t_in(a, 7);
|
||||
const RadTensor* o = t_in(a, 8);
|
||||
const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10), *vsc = a->n_t > 11 ? t_in(a, 11) : nullptr;
|
||||
if (!q || !k || !v || !segs || !geom || !sel || !o) return RAD_E_INVAL;
|
||||
const char* pv = p_str(a, "pv", "bf16");
|
||||
const bool pv8 = std::strcmp(pv, "fp8") == 0;
|
||||
if ((!pv8 && std::strcmp(pv, "bf16") != 0) || pv8 != (vsc != nullptr)) return RAD_E_INVAL;
|
||||
if (!co != !gt) return RAD_E_SHAPE;
|
||||
const char* qk = p_str(a, "qk", "bf16");
|
||||
const bool i8 = std::strcmp(qk, "i8") == 0;
|
||||
if ((!i8 && std::strcmp(qk, "bf16") != 0) || i8 != (k8 != nullptr) || i8 != (ks != nullptr))
|
||||
return RAD_E_INVAL;
|
||||
if (sel->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
const int64_t hd = p_int(a, "head_dim", 0);
|
||||
if (hd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t nh = heads_in(q, hd);
|
||||
if (nh <= 0) return RAD_E_SHAPE;
|
||||
Tiles g;
|
||||
RAD_REF_TRY(tiles_of(a, segs, geom, numel(q) / (nh * hd), &g));
|
||||
const int64_t need = g.R * nh * hd;
|
||||
if (numel(k) < need || numel(v) < need || numel(o) < need || (gt && numel(gt) < need))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t kc = sel->rank ? sel->shape[sel->rank - 1] : 0;
|
||||
const int64_t scap = tiles_cap(sel, kc, nh);
|
||||
if (kc < g.k || scap < g.N) return RAD_E_SHAPE;
|
||||
const int64_t ccap = co ? tiles_cap(co, hd, nh) : 0;
|
||||
if (co && (co->shape[co->rank - 1] != hd || ccap < g.N)) return RAD_E_SHAPE;
|
||||
const int64_t N = g.N, P = g.P, kk = g.k, ss = laststride(sel);
|
||||
for (int64_t h = 0; h < nh; ++h)
|
||||
for (int64_t i = P; i < N; ++i) {
|
||||
const int64_t sb = rowoff(sel, h * scap + i, kc);
|
||||
int64_t prev = P - 1;
|
||||
for (int64_t s = 0; s < kk; ++s) {
|
||||
const int64_t j = ld_int(sel->dtype, sel->data, sb + s * ss);
|
||||
if (j <= prev || j >= N) return RAD_E_INVAL;
|
||||
prev = j;
|
||||
}
|
||||
}
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd));
|
||||
const Heads Q = heads_of(q, nh, hd), K = heads_of(k, nh, hd), Vh = heads_of(v, nh, hd);
|
||||
const Heads O = heads_of(o, nh, hd);
|
||||
const Heads G = gt ? heads_of(gt, nh, hd) : Heads{ nullptr, 0, 0, 0 };
|
||||
const Heads K8 = i8 ? heads_of(k8, nh, hd) : Heads{ nullptr, 0, 0, 0 };
|
||||
const int64_t ks_rs = i8 ? row_stride(ks, nh) : 0;
|
||||
if (i8 && (numel(k8) < need || numel(ks) < g.R * nh)) return RAD_E_SHAPE;
|
||||
|
||||
REF_PAR_REGION(nh * g.R * hd * 64)
|
||||
{
|
||||
float* const ws = ws_get((size_t)(g.R + 2 * hd));
|
||||
float* const sc = ws;
|
||||
float* const qf = ws + g.R;
|
||||
float* const acc = qf + hd;
|
||||
std::vector<int64_t> vis;
|
||||
REF_FOR_DYN
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
const int64_t h = u / N, i = u % N;
|
||||
vis.clear();
|
||||
for (int64_t j = 0; j < (i < P ? N : P); ++j) vis.push_back(j);
|
||||
if (i >= P) {
|
||||
const int64_t sb = rowoff(sel, h * scap + i, kc);
|
||||
for (int64_t s = 0; s < kk; ++s)
|
||||
vis.push_back(ld_int(sel->dtype, sel->data, sb + s * ss));
|
||||
}
|
||||
const int64_t cb = co ? rowoff(co, h * ccap + i, hd) : 0;
|
||||
const int64_t cs = co ? laststride(co) : 0;
|
||||
tile_rows(g, i, [&](int64_t r) {
|
||||
const int64_t qb = r * Q.rs + h * Q.hs, ob = r * O.rs + h * O.hs;
|
||||
for (int64_t d = 0; d < hd; ++d) qf[d] = ldt(q, qb + d * Q.ds);
|
||||
const float qs = i8 ? ref_q8_row(qf, hd, qf) : 1.0f;
|
||||
/* Pass one: every visible key's score, and the max. */
|
||||
int64_t n = 0;
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j : vis)
|
||||
tile_rows(g, j, [&](int64_t c) {
|
||||
float dot = 0.0f;
|
||||
if (i8) {
|
||||
/* Integers below 2^24 in magnitude: the f32 sum is exact. */
|
||||
const int64_t kb = c * K8.rs + h * K8.hs;
|
||||
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(k8, kb + d * K8.ds);
|
||||
dot = dot * qs * ldt(ks, c * ks_rs + h);
|
||||
} else {
|
||||
const int64_t kb = c * K.rs + h * K.hs;
|
||||
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(k, kb + d * K.ds);
|
||||
}
|
||||
dot *= scale;
|
||||
sc[n++] = dot;
|
||||
if (dot > mx) mx = dot;
|
||||
});
|
||||
if (mx == -INFINITY) {
|
||||
for (int64_t d = 0; d < hd; ++d) stt(o, ob + d * O.ds, 0.0f);
|
||||
return;
|
||||
}
|
||||
/* Pass two: exponentiate and accumulate in the same order. */
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f;
|
||||
float sum = 0.0f;
|
||||
n = 0;
|
||||
for (int64_t j : vis)
|
||||
tile_rows(g, j, [&](int64_t c) {
|
||||
const float p = ref_exp(sc[n++] - mx);
|
||||
sum += p;
|
||||
const float w = pv8 ? round_dt(RAD_F8E4M3, 448.0f * p) : p;
|
||||
const int64_t vb = c * Vh.rs + h * Vh.hs;
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] += w * ldt(v, vb + d * Vh.ds);
|
||||
});
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
float y = pv8 ? acc[d] * ldt(vsc, offlin(vsc, h * hd + d)) * inv8
|
||||
: acc[d] * inv;
|
||||
if (co) {
|
||||
const float c = ldt(co, cb + d * cs);
|
||||
const float e = ldt(gt, r * G.rs + h * G.hs + d * G.ds);
|
||||
y = round_dt(o->dtype, y) + c * e;
|
||||
}
|
||||
stt(o, ob + d * O.ds, y);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
Reference in new issue
Block a user