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
@@ -50,6 +50,9 @@ set(AVX_KERNEL_SRC
|
||||
avx_misc.cpp
|
||||
avx_gen.cpp
|
||||
avx_gen_attn.cpp
|
||||
avx_video.cpp
|
||||
avx_vsa.cpp
|
||||
avx_audio.cpp
|
||||
)
|
||||
|
||||
# The flag sets, written out because each states which instructions the object may contain.
|
||||
|
||||
+80
-4
@@ -3,7 +3,7 @@
|
||||
The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time by CPU feature.
|
||||
|
||||
libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host
|
||||
implementation, and it is a slow reference. libavx implements all 123 of libref's ops with the
|
||||
implementation, and it is a slow reference. libavx implements all 150 of libref's ops with the
|
||||
same schemas and the same answers to a tolerance, the image generator's included (below).
|
||||
|
||||
cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH=<radiance prefix> && cmake --build build-avx -j4
|
||||
@@ -64,7 +64,7 @@ four levels and the engine never reaches it.
|
||||
|
||||
Every op `libref` implements, `libavx` implements, so the selector resolves no op of a CPU-only
|
||||
deployment to libref: Flash-Next's QSA indexer, the DFlash2 drafters' convolution and the image
|
||||
generator included. `rad-avx-check` fails on any missing op, and reports a row that returns
|
||||
and audio generators included. `rad-avx-check` fails on any missing op, and reports a row that returns
|
||||
`RAD_E_UNSUPPORTED` separately from one that is absent: a declining row is worse than none, because
|
||||
the selector resolves to it and the step fails at issue rather than at declare.
|
||||
|
||||
@@ -76,6 +76,7 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the
|
||||
| `attn_local_rel` | a right context; head_dim or left context + 1 over 2048 | the same |
|
||||
| `rope`, `qk_norm_rope`, `qsa_block_key` | an unknown `mode`; for `rope`, an unknown `ladder` | the same |
|
||||
| `rope` | YaRN with `axial` or a position scale | the same |
|
||||
| `rope` | Llama 3 scaling beside YaRN, with `axial`, or over multi-component positions | the same |
|
||||
| `rope` | a rotary half-width over 1024 | the same |
|
||||
| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
|
||||
| `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same |
|
||||
@@ -91,8 +92,10 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the
|
||||
|
||||
Everything but the last two rows refuses exactly where libref does, so the selector never
|
||||
resolves a geometry to libavx that libref would have served. The per-entry image ops
|
||||
(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) check every entry before writing any,
|
||||
where libref writes the entries before a bad one; they return libref's code, and refuse (with
|
||||
(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) and the audio generator's
|
||||
(`frame_mix_store`, `end_status`, `frame_store`, `win_input`, `win_prep`, `win_finish`, and
|
||||
`cfg_topk_sample` with a lane history or a suppressed id range) check every entry before writing
|
||||
any, where libref writes the entries before a bad one; they return libref's code, and refuse (with
|
||||
`RAD_E_SHAPE`) the entries libref would read or write past an operand for.
|
||||
|
||||
`moe_gemm_q` and `moe_gemm_q_mod4` carry layout hooks for Qwen3.8-Flash-Next's codebook experts
|
||||
@@ -566,6 +569,76 @@ activation. With a bf16-pair path for block fp8 the fp8 container would cost abo
|
||||
one does. The decoder takes about 1.3 s at 512 x 512 and 5 s at 1024 x 1024, the condition (the
|
||||
8B text encoder and the DiT over about 100 prompt tokens) about 0.6 s in bf16 and 8 s in fp8.
|
||||
|
||||
## Audio generation
|
||||
|
||||
MiniMax-Music3 (`arch/minimaxmusic3`) adds 16 ops (`avx_audio.cpp`), and a speech model's frame
|
||||
loop and causal codec one more (`frame_store`) and these forms: a causal `conv1d`, the causal
|
||||
`conv_t1d` (`pad` 0, odd strides, a kernel of one stride), SnakeBeta (`snake` with `beta`, both as
|
||||
logarithms with `log`), and a sampler that suppresses reserved ids, takes each lane's guidance and
|
||||
penalises a lane's earlier picks (`hist`, cleared at frame 0). The sampler (`cfg_topk_sample`),
|
||||
the window noise and its overlap binding (`win_prep`), the frame embeddings (`rvq_embed` in both
|
||||
roundings, `frame_mix_store`, `fourier_embed`), the code history (`frame_store`), the window copies
|
||||
and the index helpers are libref's bit for bit, held to zero error by the hand-built cases: a seed
|
||||
gives the same codes, the same noise and the same piece on both host libraries. With a history the
|
||||
sampler takes its lanes in order, as libref does, since two entries may share a lane's row.
|
||||
`cfg_topk_sample` and `frame_mix_store` keep libref's two roundings where they multiply and add
|
||||
(`keep`). The vocoder's three ops reduce in other orders and are held to the tolerance table:
|
||||
|
||||
- **`conv1d`** is GEMMs over bands of patch rows, as `conv2d_nhwc`: the weight re-laid once a launch
|
||||
as `[cout][k][cin]`, an output row's patch its k input rows' channel runs (zeros outside its own
|
||||
sequence), each band one `gemm_nt_into` into f32 rows, then the residual and the tanh or the
|
||||
clamp, rounded once. A 1-wide kernel over a dense input reads x in place.
|
||||
- **`conv_t1d`** is one GEMM per phase: output row q s + r - pad reads input rows q, q - 1, ..
|
||||
against taps r, r + s, .. below k (phases of one kernel may differ by a tap: kernel 9 at stride 5
|
||||
takes two taps in phases 0 to 3 and one in phase 4), so a phase's rows are a GEMM over
|
||||
`[x[q] | x[q - 1] | ..]` patch rows and the weight re-laid per phase as `[cout][taps][cin]`.
|
||||
- **`snake`** squares a sine reduced to [-pi/2, pi/2] (the sign does not matter once squared) and
|
||||
evaluated as an odd Taylor polynomial through r^13; a row with an argument past 8192, where the
|
||||
three-part pi stops being exact, is computed again with the libm sine. SnakeBeta's multiplier
|
||||
1 / (beta + 1e-9) is taken once a channel, as libref takes it.
|
||||
- **`snake_aa`** (BigVGAN's alias-free SnakeBeta, MiniMax-H3's vocoder) works on bands of 64 output
|
||||
rows, channels innermost: a band computes the upsampled rows its filter reads into scratch (a
|
||||
row a function of its index, so neighbouring bands agree where they overlap), with `snake`'s
|
||||
sine, and filters them down; both sums run in libref's order.
|
||||
|
||||
At the vocoder's third stage (384 channels), bf16, this machine (`rad-avx-bench --op <op>`):
|
||||
|
||||
| op | geometry | libref, 1 thread | avx512, 1 thread | avx512, 16 threads |
|
||||
|---|---|---|---|---|
|
||||
| conv1d | 7 taps, dilation 3, 384 -> 384, 8192 rows | 10.9 s | 56.8 ms, 298 GFLOP/s | 6.5 ms, 2.6 TFLOP/s |
|
||||
| conv1d | 1 x 1, 384 -> 384, 8192 rows | 1.57 s | 9.7 ms, 250 GFLOP/s | 1.4 ms, 1.7 TFLOP/s |
|
||||
| conv_t1d | stride 4, 768 -> 384, 2048 -> 8192 rows | 6.33 s | 34.7 ms, 279 GFLOP/s | 3.8 ms, 2.5 TFLOP/s |
|
||||
| snake | 8192 x 384 | 20.3 ms | 1.2 ms, 10.5 GB/s | 0.32 ms, 39 GB/s |
|
||||
|
||||
A window's vocode (two streams, 689 latents to 705536 samples each, four upsampling stages of
|
||||
three residual units) is about 2.2 TFLOP, of the order of a second on 16 cores at these rates; the
|
||||
96-channel last stage was not timed. On one thread the convolutions reach 36-43% of the bf16
|
||||
dot-product ceiling, against the image decoder's 70-88%; they have not been tuned.
|
||||
|
||||
## Video generation
|
||||
|
||||
MiniMax-H3 adds eight ops (`avx_gen.cpp`, `avx_video.cpp`, and `snake_aa` in `avx_audio.cpp`)
|
||||
and these forms: `qk_norm_rope`
|
||||
`axial` over f32 positions (its positions a view of a wider plane), with absent gains and as the
|
||||
norm alone; `rope` over f32 positions; `gate_add` without tanh; `add` with `div`; `chan_affine` in
|
||||
f32; `conv_t1d` at any kernel of a stride or more; `conv1d` with its clamp; and `snake_aa` above.
|
||||
The sampler step (`flow_x0_step`), the patch unfold, the decoder's tiles (`vtile_gather`), their
|
||||
stitch into bytes (`vtile_stitch`) and their positions (`grid_pos3`) are libref's bit for bit, held
|
||||
to zero error by the hand-built cases: a seed gives the same video bytes on both host libraries.
|
||||
The stitch blends a line of a tile at a time, each product and sum a pass of the line through x's
|
||||
dtype; the frames that refill the overlap run after the frames that read it, so no row is read
|
||||
after another task rewrote it. `rms_mod` and its quantised form reduce in another order and are
|
||||
held to the tolerance table.
|
||||
|
||||
Its step-distilled form's video sparse attention adds two (`avx_vsa.cpp`). `vsa_select`'s
|
||||
selection is libref's bit for bit, since one tile more or less changes what a whole query tile
|
||||
sees: the tile means sum rows in libref's order with the vector lanes across the head, and each
|
||||
score's dot runs over the head in libref's order with the vector lanes across tiles and every
|
||||
product rounded before its add. Its coarse branch is held to the tolerance. `attn_vsa` is one task
|
||||
per (head, query tile), 64 keys of a visible tile packed at a time for broadcast products and an
|
||||
online softmax, as `attn_prefix_self`'s f32 form; a prefix query tile sees every tile, so the tasks
|
||||
are scheduled dynamically.
|
||||
|
||||
## Design choices
|
||||
|
||||
Each choice below was measured on the platform above. The variants that did not pay are recorded
|
||||
@@ -628,6 +701,9 @@ and spills a 16-register file, costing more than the FMA saves, so the AVX and A
|
||||
avx_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp the kernels; compiled 4x
|
||||
avx_gen.cpp the image generator's norms, sampler, lanes and decoder ops; compiled 4x
|
||||
avx_gen_attn.cpp attn_prefix_self, the generator's attention; compiled 4x
|
||||
avx_video.cpp the video decoder's patch unfold, tiles, stitch and positions; compiled 4x
|
||||
avx_vsa.cpp video sparse attention: the tile selection and the attention; compiled 4x
|
||||
avx_audio.cpp the audio generator's vocoder, sampler, embeddings and window ops; compiled 4x
|
||||
avx_harness.h plugin loading, row selection, the operand draw, guarded buffers, the
|
||||
geometry table -- shared by both tools
|
||||
avx_cases.cpp the geometries; one table so the check and the bench cannot disagree
|
||||
|
||||
+85
-42
@@ -532,7 +532,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
const RadTensor* v, const RadTensor* cu,
|
||||
const RadTensor* o, int64_t D, int64_t gqa,
|
||||
int64_t kv_heads, int causal, int64_t window,
|
||||
int64_t block, int64_t cdiv, float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
|
||||
int64_t wright, int64_t block, int64_t cdiv,
|
||||
float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
|
||||
int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs,
|
||||
int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs,
|
||||
int64_t o_ds) {
|
||||
@@ -589,7 +590,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
int64_t jbeg = 0, jend = causal ? q1 : len;
|
||||
if (window > 0) {
|
||||
jbeg = std::max<int64_t>(0, q0 - window + 1);
|
||||
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + window);
|
||||
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + wright);
|
||||
}
|
||||
if (block > 0) {
|
||||
jbeg = std::max<int64_t>(jbeg, q0 / block * block);
|
||||
@@ -617,7 +618,8 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
for (int64_t j = 0; j < kt; ++j) {
|
||||
const int64_t d = i - (j0 + j);
|
||||
bool ok = !causal || d >= 0;
|
||||
if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window));
|
||||
if (window > 0)
|
||||
ok = ok && (causal ? d < window : (d < window && -d < wright));
|
||||
if (block > 0) ok = ok && i / block == (j0 + j) / block;
|
||||
if (!ok) S[r * KT + j] = -INFINITY;
|
||||
}
|
||||
@@ -729,12 +731,16 @@ AVX_KERNEL(attn_dense) {
|
||||
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
|
||||
const int64_t gqa = p_int(a, "gqa", 1);
|
||||
const int causal = (int)p_int(a, "causal", 0);
|
||||
/* As libref: causal, i - j < window; non-causal, |i - j| < window; 0 means none. A `block`
|
||||
* cuts a segment into blocks attending within themselves; `cu_div` reads cu_seqlens in units
|
||||
* that many rows apart. */
|
||||
const int64_t window = p_int(a, "window", 0);
|
||||
/* As libref: causal, i - j < window; non-causal, |i - j| < window, or i - j < window and
|
||||
* j - i < window_right when that is given; 0 means none. A `block` cuts a segment into blocks
|
||||
* attending within themselves; `cu_div` reads cu_seqlens in units that many rows apart. */
|
||||
const int64_t window = p_int(a, "window", 0), wright_p = p_int(a, "window_right", 0);
|
||||
const int64_t block = p_int(a, "block", 0), 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_p < 0 ||
|
||||
(wright_p > 0 && (causal || window == 0)))
|
||||
return RAD_E_SHAPE;
|
||||
/* The right side of a non-causal window. */
|
||||
const int64_t wright = wright_p > 0 ? wright_p : window;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
|
||||
/* A rank-2 operand is [tokens, heads * head_dim]: its head count is width / head_dim. */
|
||||
@@ -768,8 +774,8 @@ AVX_KERNEL(attn_dense) {
|
||||
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
#if AVX_LEVEL == 3
|
||||
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, block, cdiv,
|
||||
scale, q_rs,
|
||||
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, wright, block,
|
||||
cdiv, scale, q_rs,
|
||||
q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds))
|
||||
return RAD_OK;
|
||||
#endif
|
||||
@@ -792,7 +798,7 @@ AVX_KERNEL(attn_dense) {
|
||||
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);
|
||||
}
|
||||
if (block > 0) {
|
||||
const int64_t blk = b0 + (i - b0) / block * block;
|
||||
@@ -1067,6 +1073,14 @@ AVX_KERNEL(kv_store) {
|
||||
* frequencies, and for `axial` a frequency ladder per section. Same rule as libref's rope_freqs. */
|
||||
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
|
||||
|
||||
/* A position as libref's rope_pos reads it, divided by the position scale: a float operand's own
|
||||
* value (a fractional coordinate), an integer operand's integer. */
|
||||
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 ? ldt(pos, off) : (float)ldi(pos, off)) / div;
|
||||
}
|
||||
|
||||
/* cos in [0, half), sin in [half, rot): the layout `rope_table` writes.
|
||||
*
|
||||
* Not sincosf: it gives the same bits but glibc's joint wrapper is slower than two separate
|
||||
@@ -1218,6 +1232,14 @@ AVX_KERNEL(rope) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
}
|
||||
/* Llama 3's frequency scaling, refused beside YaRN or a multi-component mode as libref
|
||||
* refuses it. */
|
||||
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 < half; ++i) invf[i] = l3.frequency(invf[i]);
|
||||
}
|
||||
for (int64_t i = nfreq; i < half; ++i) invf[i] = 0.0f;
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
@@ -1229,10 +1251,10 @@ AVX_KERNEL(rope) {
|
||||
float* buf = scratch_f32_b((size_t)rot);
|
||||
if (multi) {
|
||||
float pc[8];
|
||||
for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
|
||||
for (int64_t c = 0; c < n_comp; ++c) pc[c] = rope_pos(pos, c * pcs + m * pms, div);
|
||||
angles_multi(cs, invf, comp, half, pc);
|
||||
} else {
|
||||
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
|
||||
angles(cs, invf, half, rope_pos(pos, offlin(pos, m), div));
|
||||
}
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
|
||||
@@ -1244,14 +1266,16 @@ AVX_KERNEL(rope) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qk_norm_rope */
|
||||
/* Per-head RMS norm with its own gain, then RoPE.
|
||||
/* Per-head RMS norm with its own gain, then RoPE. An absent gain is a unit gain without `wadd`,
|
||||
* and `rotary_dim` 0 is the norm alone, `positions` then optional (libref).
|
||||
*
|
||||
* The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does
|
||||
* (and libr4d's r4d_qk_norm_rope_gate matches): it is stored with out_row and re-read by the
|
||||
* rotation rather than kept in f32. */
|
||||
AVX_KERNEL(qk_norm_rope) {
|
||||
if (!rad_args_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 || a->n_t < 4 || !rad_arg_in(a, 0)) return RAD_E_INVAL;
|
||||
const RadTensor *qkv = &a->t[0], *pos = rad_arg_in(a, 1);
|
||||
const RadTensor *qw = rad_arg_in(a, 2), *kw = rad_arg_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);
|
||||
@@ -1263,22 +1287,26 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
const int v_norm = (int)p_int(a, "v_norm", 0);
|
||||
/* libref's modes: `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j,
|
||||
* start + 2j + 1), Qwen-Image's 3-axis rotary; `imrope` is `rope`'s interleaved M-RoPE over
|
||||
* NeoX pairs (Qwen3-VL's text attention). */
|
||||
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
|
||||
const int mode = p_enum(a, "mode", kModes, 5, ROPE_NEOX);
|
||||
* NeoX pairs (Qwen3-VL's text attention); `axial` is `rope`'s axial form, its section ladders
|
||||
* over rank-1 positions too. */
|
||||
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" };
|
||||
const int mode = p_enum(a, "mode", kModes, 6, ROPE_NEOX);
|
||||
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;
|
||||
const 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` mode (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
|
||||
* (start + j, start + sec[c] + j), rotated by position component comps[c]. */
|
||||
int64_t sec[8] = {}, comp[8] = {};
|
||||
int n_sec = 0;
|
||||
if (im) {
|
||||
if (turn && (im || axial)) {
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(v, &end, 10);
|
||||
@@ -1287,9 +1315,9 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
sec[n_sec++] = x;
|
||||
v = end;
|
||||
}
|
||||
if (n_sec < 3) return RAD_E_SHAPE;
|
||||
if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE;
|
||||
}
|
||||
if (blocks) {
|
||||
if (turn && blocks) {
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(v, &end, 10);
|
||||
@@ -1314,16 +1342,20 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
if (k != n_sec) return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
const bool multi = pos->rank >= 2;
|
||||
const bool multi = pos && pos->rank >= 2;
|
||||
const int64_t n_comp = multi ? pos->shape[0] : 1;
|
||||
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 || n_comp > 8) return RAD_E_SHAPE;
|
||||
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
|
||||
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 || n_comp > 8) return RAD_E_SHAPE;
|
||||
}
|
||||
/* The component axis at the operand's own pitch: a [C, M] view of a wider plane. */
|
||||
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;
|
||||
const int64_t M = multi ? pos->shape[1] : numel(pos);
|
||||
const int64_t M = !pos ? rows_of(qkv, stride_row) : multi ? pos->shape[1] : numel(pos);
|
||||
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
|
||||
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
|
||||
const int64_t ds = laststride(qkv);
|
||||
@@ -1337,9 +1369,19 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
float* gq = tab + 2 * half;
|
||||
float* gk = tab + 2 * half + head_dim;
|
||||
/* imrope's component per frequency, as libref's rope_freqs: 1 where i % 3 == 1 and
|
||||
* i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. */
|
||||
const bool by_comp = blocks || (im && multi);
|
||||
if (!blocks) {
|
||||
* i < 3 * sec[1], 2 where i % 3 == 2 and i < 3 * sec[2], 0 elsewhere. axial's sections are
|
||||
* contiguous, each its own ladder theta^(-2j / (2 sec[c])) and filling rot / 2 exactly. */
|
||||
const bool by_comp = blocks || (im && multi) || axial;
|
||||
if (axial) {
|
||||
int64_t i = 0;
|
||||
for (int c = 0; c < n_sec; ++c)
|
||||
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
|
||||
if (i >= half) return RAD_E_SHAPE;
|
||||
invf[i] = 1.0f / sc_pow(theta, (float)(2 * j) / (float)(2 * sec[c]));
|
||||
pcomp[i] = (float)c;
|
||||
}
|
||||
if (i != half) return RAD_E_SHAPE;
|
||||
} else if (!blocks) {
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
invf[i] = 1.0f / sc_pow(theta, (float)(2 * i) / (float)rot);
|
||||
pcomp[i] = !im ? 0.0f
|
||||
@@ -1355,19 +1397,19 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
}
|
||||
}
|
||||
for (int64_t d = 0; d < head_dim; ++d) {
|
||||
gq[d] = ldt(qw, d * laststride(qw)) + wadd;
|
||||
gk[d] = ldt(kw, d * laststride(kw)) + wadd;
|
||||
gq[d] = qw ? ldt(qw, d * laststride(qw)) + wadd : 1.0f;
|
||||
gk[d] = kw ? ldt(kw, d * laststride(kw)) + wadd : 1.0f;
|
||||
}
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
float pc[8];
|
||||
if (multi)
|
||||
float pc[8] = {};
|
||||
if (turn && multi)
|
||||
for (int64_t c = 0; c < n_comp && c < 8; ++c)
|
||||
pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
|
||||
else
|
||||
pc[0] = (float)ldi(pos, offlin(pos, m)) / div;
|
||||
pc[c] = rope_pos(pos, c * pcs + m * pms, div);
|
||||
else if (turn)
|
||||
for (float& v : pc) v = rope_pos(pos, offlin(pos, m), div);
|
||||
const int64_t row = m * rs;
|
||||
/* cos and sin, then for adjacent pairs the same per rotated channel: cc[2i] = cc[2i+1]
|
||||
* = cos_i, ss[2i] = -sin_i, ss[2i+1] = sin_i, so channel d becomes
|
||||
@@ -1404,8 +1446,9 @@ AVX_KERNEL(qk_norm_rope) {
|
||||
/* Store through the operand's dtype; the rotation re-reads it (see above). */
|
||||
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
|
||||
else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
|
||||
if (!turn) continue;
|
||||
if (!blocks) {
|
||||
rope_head(qkv, base, ds, rot, im ? (int)ROPE_NEOX : mode, cs, half, rbuf);
|
||||
rope_head(qkv, base, ds, rot, im || axial ? (int)ROPE_NEOX : mode, cs, half, rbuf);
|
||||
continue;
|
||||
}
|
||||
if (pairs_vec) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+234
-9
@@ -43,6 +43,8 @@ std::vector<Case> build_cases() {
|
||||
add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) },
|
||||
EB(5, 645, w, 2));
|
||||
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3));
|
||||
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt), HF("div", 3.0) },
|
||||
EB(9, 645, w, 3));
|
||||
add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3));
|
||||
add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
|
||||
add("gelu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
|
||||
@@ -132,6 +134,10 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
|
||||
|
||||
/* One scale per column over the rows: no group. */
|
||||
add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
|
||||
add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25));
|
||||
|
||||
/* Quantisation. 128 is the real grid; 64 tests a second block edge. n = 256 is divisible by
|
||||
* both, which the had_* forms require (a rotation block may not straddle the row end). */
|
||||
for (int group : { 64, 128 }) {
|
||||
@@ -254,13 +260,12 @@ std::vector<Case> build_cases() {
|
||||
2.0 * M * 192 * 256);
|
||||
add("gemm_nt_q_gated", { HI("M", 7), HI("N", 512), HI("K", 256), HI("group", 128),
|
||||
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
|
||||
/* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself -- a base row --
|
||||
* comes up in every case of more than one row and the comparison covers rows neither op may
|
||||
* touch (a single row draws an adapter, or the case would compare nothing). M = 1 takes the
|
||||
* shrink's team-over-columns arm and 9 and 65 its team-over-rows one; K = 1000
|
||||
* leaves a partial scale group and a vector tail at every level; R = 48 is not a power of two.
|
||||
* The dtype is `a`'s for shrink -- the coded ones with their scale stream -- and `y`'s for
|
||||
* expand. */
|
||||
/* Runtime LoRA. libref's description draws `slot` in [0, S], so S itself, a base row, comes
|
||||
* up in every case of more than one row (a single row draws an adapter, or the case would
|
||||
* compare nothing). M = 1 takes the shrink's team-over-columns arm and 9 and 65 its
|
||||
* team-over-rows one; K = 1000 leaves a partial scale group and a vector tail at every level;
|
||||
* R = 48 is not a power of two. The dtype is `a`'s for shrink (the coded ones with their scale
|
||||
* stream) and `y`'s for expand. */
|
||||
for (int M : { 1, 9, 65 }) {
|
||||
for (const char* dt : { "f32", "bf16", "f16", "fp8_e4m3", "i8" })
|
||||
for (int K : { 256, 1000 })
|
||||
@@ -300,6 +305,12 @@ std::vector<Case> build_cases() {
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
|
||||
HI("max_seqlen", 24), HI("window", 5) });
|
||||
/* A non-causal window reaching further right than left (a sliding encoder layer that sees 4
|
||||
* keys behind and 7 ahead). */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), HI("causal", 0),
|
||||
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
|
||||
HI("window", 5), HI("window_right", 8) });
|
||||
/* Blocks: each segment cut into blocks of 7 rows that attend within themselves (a chunked
|
||||
* encoder's windows), the last block of a segment short. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
@@ -436,6 +447,13 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0),
|
||||
HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") });
|
||||
/* Llama 3's frequency scaling at a depth decoder's settings (theta 5e5, factor 32, original
|
||||
* length 16): kept, blended and divided frequencies all present. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 500000.0), HF("scale", 1.0), HS("mode", "neox"),
|
||||
HF("llama3_factor", 32.0), HF("llama3_low", 0.001953125),
|
||||
HF("llama3_high", 0.0078125), HF("llama3_orig", 16.0), HS("dtype", dt) });
|
||||
/* A rotary wider than 1024 (libref takes up to 2048, i.e. 1024 frequencies), plain and with
|
||||
* contiguous sections, and QSA's key at the same width. */
|
||||
add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1),
|
||||
@@ -456,6 +474,18 @@ std::vector<Case> build_cases() {
|
||||
add("rope", { HI("M", 12), HI("head_dim", 72), HI("n_head", 4), HI("n_head_kv", 4),
|
||||
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"),
|
||||
HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) });
|
||||
/* MiniMax-H3's: the DiT's 3-axis rotary over 96 of 128 channels, the video decoder's
|
||||
* over 48 of 64; and the norm alone (rotary_dim 0, no positions). f32 positions and
|
||||
* absent gains are avx_check_hand.cpp's. */
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 2), HI("n_head_kv", 2),
|
||||
HF("theta", 10000.0), HF("eps", 1e-5), HS("mode", "axial"),
|
||||
HI("rotary_dim", 96), HS("sections", "16 16 16"), HS("dtype", dt) });
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
|
||||
HF("theta", 100.0), HF("eps", 1e-5), HS("mode", "axial"),
|
||||
HI("rotary_dim", 48), HS("sections", "8 8 8"), HS("dtype", dt) });
|
||||
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 10000.0), HF("eps", 1e-6), HI("rotary_dim", 0),
|
||||
HI("v_norm", 1), HS("dtype", dt) });
|
||||
add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) });
|
||||
/* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by
|
||||
* avx_check's hand-built case. */
|
||||
@@ -617,6 +647,8 @@ std::vector<Case> build_cases() {
|
||||
EB(7, 645, dt[0] == 'f' ? 4 : 2, 2));
|
||||
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt) },
|
||||
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
|
||||
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt), HS("act", "none") },
|
||||
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
|
||||
for (int gated : { 1, 0 })
|
||||
add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt) });
|
||||
@@ -631,8 +663,10 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", dt) });
|
||||
add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
|
||||
for (const char* mode : { "fma", "inv" })
|
||||
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
|
||||
HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt) });
|
||||
for (int round : { 1, 0 })
|
||||
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
|
||||
HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt),
|
||||
HI("round", round) });
|
||||
for (const char* act : { "silu", "none" })
|
||||
add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) });
|
||||
add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) });
|
||||
@@ -671,6 +705,187 @@ std::vector<Case> build_cases() {
|
||||
HI("n_head", 4), HS("qk", qk) });
|
||||
}
|
||||
|
||||
/* ================================================================== video generation
|
||||
*
|
||||
* MiniMax-H3's DiT row ops at an odd width, both gated forms; its sampler step over an f32
|
||||
* state; the decoder's patch unfold, tiles, stitch and positions over the cube geometry
|
||||
* libref describes (one value in every `geom` entry). Uneven grids, a chunk between two
|
||||
* others and views of wider planes are avx_check_hand.cpp's. */
|
||||
static const std::string kStd24 = [] {
|
||||
std::string s;
|
||||
for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.4 + 0.07 * i);
|
||||
return s;
|
||||
}();
|
||||
static const std::string kMean24 = [] {
|
||||
std::string s;
|
||||
for (int i = 0; i < 24; ++i) s += (i ? " " : "") + std::to_string(0.031 * i - 0.37);
|
||||
return s;
|
||||
}();
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (int gated : { 1, 0 }) {
|
||||
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated),
|
||||
HS("dtype", dt) });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt) });
|
||||
}
|
||||
add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
|
||||
for (int pt : { 1, 4 })
|
||||
add("patch_unfold", { HI("M", 8 * 4 * pt), HI("C", 24), HI("pt", pt), HI("ph", 2),
|
||||
HI("pw", 2), HS("mul", kStd24.c_str()),
|
||||
HS("add", kMean24.c_str()), HS("dtype", dt) });
|
||||
/* Three frames of 3 x 3: two tiles of 2 a side overlapping by 1, two register rows and
|
||||
* one zero row a tile. */
|
||||
add("vtile_gather", { HI("M", 60), HI("n", 37), HI("tile", 2), HI("overlap", 1),
|
||||
HI("frames", 3), HI("period", 15), HI("n_reg", 2), HS("dtype", dt) });
|
||||
}
|
||||
/* A 3 x 3 latent of 3 frames, 2 x 2 tiles a row apart past their voxels, decoded at scale 2
|
||||
* and two clip frames a latent one: the kept frames and the overlap of a video's only
|
||||
* chunk. */
|
||||
add("vtile_stitch", { HI("M", 108), HI("tile", 2), HI("overlap", 1), HI("scale", 2),
|
||||
HI("pt", 2), HI("skip", 1), HI("keep", 2), HI("blend", 1),
|
||||
HI("period", 13), HS("mean", "0.485 0.456 0.406"),
|
||||
HS("std", "0.229 0.224 0.225") });
|
||||
add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27),
|
||||
HF("scale", 6.283185307179586) });
|
||||
|
||||
/* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2
|
||||
* after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without
|
||||
* the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after
|
||||
* one segment (P 4, V 12). attn_vsa at k = 1, the one selection a description draws; the
|
||||
* others are avx_check_hand.cpp's. `n_head`, `coarse` and `dtype` are the description's. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (int coarse : { 1, 0 }) {
|
||||
add("vsa_select", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2),
|
||||
HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.8),
|
||||
HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) });
|
||||
add("attn_vsa", { HI("M", 81), HI("head_dim", 64), HI("tile_t", 2), HI("tile_h", 2),
|
||||
HI("tile_w", 2), HI("patch", 1), HF("sparsity", 0.9),
|
||||
HI("n_head", 2), HI("coarse", coarse), HS("dtype", dt) });
|
||||
}
|
||||
for (double sp : { 0.5, 0.0 })
|
||||
add("vsa_select", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4),
|
||||
HI("tile_w", 4), HI("patch", 2), HF("sparsity", sp),
|
||||
HI("n_head", 2), HS("dtype", dt) });
|
||||
add("attn_vsa", { HI("M", 500), HI("head_dim", 128), HI("tile_t", 4), HI("tile_h", 4),
|
||||
HI("tile_w", 4), HI("patch", 2), HF("sparsity", 0.95), HI("n_head", 2),
|
||||
HS("dtype", dt) });
|
||||
}
|
||||
|
||||
/* ================================================================== audio generation
|
||||
*
|
||||
* The vocoder's convolutions over two sequences (a stereo latent's halves as libref describes
|
||||
* them), odd channel counts, the codec's kernel widths and dilations and every stride an
|
||||
* upsampling block uses; the sampler at both branch counts, with and without the conditional
|
||||
* candidate cut; the window ops over three and four entries, so the drawn flags reach FIRST,
|
||||
* JOIN and LAST in several combinations. The first case of each op stays inside libref's four
|
||||
* lanes at twice its rows, which the zero-row check describes. */
|
||||
for (const char* dt : { "f32", "bf16", "f16" }) {
|
||||
for (int dil : { 1, 3 })
|
||||
for (const char* act : { "none", "tanh" })
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
|
||||
HI("dil", dil), HS("act", act), HS("dtype", dt) });
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 3), HI("dil", 9),
|
||||
HS("dtype", dt) });
|
||||
add("conv1d", { HI("M", 9), HI("cin", 33), HI("cout", 17), HI("k", 1), HI("dil", 1),
|
||||
HS("dtype", dt) });
|
||||
/* Causal: all of the padding on the left (odd k; an even k is a hand-built case, which
|
||||
* libref's description does not draw). */
|
||||
for (int dil : { 1, 3 })
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
|
||||
HI("dil", dil), HI("causal", 1), HS("dtype", dt) });
|
||||
for (int s : { 2, 4, 8 })
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
|
||||
HS("dtype", dt) });
|
||||
/* The causal transposed form, a codec's upsampler: no padding, a sequence's first
|
||||
* output rows reading its first input row alone. */
|
||||
for (int s : { 2, 4, 8 })
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
|
||||
HI("pad", 0), HS("dtype", dt) });
|
||||
/* A kernel of one stride (one tap a phase), without padding and with some. An odd stride
|
||||
* is a hand-built case, which libref's description does not draw. */
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2),
|
||||
HI("k", 2), HS("dtype", dt) });
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 4),
|
||||
HI("k", 4), HI("pad", 1), HS("dtype", dt) });
|
||||
/* BigVGAN's upsamplers: kernel 9 at stride 5 (three taps in some phases, two in
|
||||
* others), and a kernel of six strides whose padding passes a stride. */
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 5),
|
||||
HI("k", 9), HS("dtype", dt) });
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", 2),
|
||||
HI("k", 12), HS("dtype", dt) });
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7), HI("dil", 1),
|
||||
HS("act", "clamp"), HS("dtype", dt) });
|
||||
add("snake", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
|
||||
add("snake", { HI("M", 6), HI("n", 645), HI("log", 1), HS("dtype", dt) });
|
||||
/* The alias-free SnakeBeta at BigVGAN's 12-tap filters over two sequences, and an odd
|
||||
* filter at ratio 3. */
|
||||
for (int lg : { 0, 1 })
|
||||
add("snake_aa", { HI("M", 24), HI("n", 37), HI("ratio", 2), HI("k", 12),
|
||||
HI("log", lg), HS("dtype", dt) });
|
||||
add("snake_aa", { HI("M", 10), HI("n", 645), HI("ratio", 3), HI("k", 7), HS("dtype", dt) });
|
||||
add("resample_nearest", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
|
||||
add("resample_nearest", { HI("M", 4), HI("n", 64), HS("dtype", dt) });
|
||||
add("chan_split", { HI("M", 9), HI("n", 645), HI("parts", 2), HS("dtype", dt) });
|
||||
add("chan_split", { HI("M", 5), HI("n", 64), HI("parts", 3), HS("dtype", dt) });
|
||||
add("interleave2", { HI("M", 645), HS("dtype", dt) });
|
||||
}
|
||||
for (int rep : { 1, 2 })
|
||||
for (int ck : { 0, 40 })
|
||||
add("cfg_topk_sample", { HI("M", 4 * rep), HI("n_vocab", 645), HI("k", 50),
|
||||
HI("rep", rep), HI("cond_k", ck), HF("cfg", 1.5),
|
||||
HI("stream", 3), HS("dtype", "f32") });
|
||||
add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2),
|
||||
HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0),
|
||||
HS("dtype", "f32") });
|
||||
/* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a
|
||||
* candidate), a temperature, the penalty idle without a history. */
|
||||
for (int rep : { 1, 2 })
|
||||
add("cfg_topk_sample", { HI("M", 2 * rep), HI("n_vocab", 645), HI("k", 50),
|
||||
HI("rep", rep), HF("cfg", 4.0), HF("temp", 0.9), HI("stream", 0),
|
||||
HI("sup_lo", 600), HI("sup_hi", 644), HF("penalty", 1.1),
|
||||
HS("dtype", "f32") });
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (double sc : { 1.0, 0.7 })
|
||||
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64),
|
||||
HI("off0", 5), HF("scale", sc), HS("dtype", dt) });
|
||||
/* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */
|
||||
for (double sc : { 1.0, 0.7 })
|
||||
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64),
|
||||
HI("off0", 0), HF("scale", sc), HI("round", 1), HS("dtype", dt) });
|
||||
add("frame_mix_store", { HI("M", 2), HI("n_embd", 645), HI("L", 9), HI("stride", 5),
|
||||
HI("rep", 2), HS("dtype", dt) });
|
||||
add("frame_mix_store", { HI("M", 4), HI("n_embd", 64), HI("L", 3), HI("stride", 2),
|
||||
HI("rep", 1), HS("dtype", dt) });
|
||||
for (int round : { 1, 0 })
|
||||
add("fourier_embed", { HI("M", 5), HI("n", 256), HI("round", round),
|
||||
HS("dtype", dt) });
|
||||
add("win_input", { HI("M", 24), HI("n_lat", 37), HI("n_zero", 0), HI("n_cond", 64),
|
||||
HI("stride", 12), HS("dtype", dt) });
|
||||
add("win_input", { HI("M", 36), HI("n_lat", 64), HI("n_zero", 3), HI("n_cond", 37),
|
||||
HI("stride", 16), HS("dtype", dt) });
|
||||
for (int ov : { 6, 16 })
|
||||
add("win_prep", { HI("M", 32), HI("n", 64), HI("stride", 16), HI("ov", ov),
|
||||
HS("dtype", dt) });
|
||||
add("win_prep", { HI("M", 64), HI("n", 37), HI("stride", 16), HI("ov", 4),
|
||||
HS("dtype", dt) });
|
||||
add("win_finish", { HI("M", 32), HI("n", 64), HI("n_cond", 37), HI("stride", 16),
|
||||
HI("ov", 6), HS("dtype", dt) });
|
||||
add("win_finish", { HI("M", 64), HI("n", 64), HI("n_cond", 37), HI("stride", 16),
|
||||
HI("ov", 4), HS("dtype", dt) });
|
||||
add("win_finish", { HI("M", 36), HI("n", 37), HI("n_cond", 64), HI("stride", 12),
|
||||
HI("ov", 5), HS("dtype", dt) });
|
||||
}
|
||||
add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) });
|
||||
add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) });
|
||||
add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2),
|
||||
HI("skip", 0) });
|
||||
add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1),
|
||||
HI("skip", 1) });
|
||||
add("iota", { HI("M", 645), HI("start", 3), HI("step", 2) });
|
||||
add("iota", { HI("M", 7), HI("start", -5), HI("step", 1) });
|
||||
add("cu_repeat", { HI("M", 5), HI("mult", 3) });
|
||||
add("cu_repeat", { HI("M", 9), HI("mult", 1) });
|
||||
|
||||
/* ================================================================== speed-only, at model size
|
||||
*
|
||||
* Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels;
|
||||
@@ -880,6 +1095,16 @@ std::vector<Case> build_cases() {
|
||||
2.0 * 1024 * 12288 * 4096);
|
||||
speed("gemm_nt_q", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HI("group", 128),
|
||||
HS("dtype", "fp8a8") }, 0, 2.0 * 1024 * 12288 * 4096);
|
||||
/* The music vocoder's third stage (384 channels; a window's two streams there are 88192 rows,
|
||||
* timed over 8192): a residual unit's dilated 7-tap convolution and its 1 x 1, the stage's
|
||||
* stride-4 upsampling from 768 channels, and the snake before each. */
|
||||
speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 7), HI("dil", 3),
|
||||
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384 * 7);
|
||||
speed("conv1d", { HI("M", 8192), HI("cin", 384), HI("cout", 384), HI("k", 1), HI("dil", 1),
|
||||
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 384);
|
||||
speed("conv_t1d", { HI("M", 2048), HI("cin", 768), HI("cout", 384), HI("stride", 4),
|
||||
HS("dtype", "bf16") }, 0, 2.0 * 8192 * 384 * 2 * 768);
|
||||
speed("snake", { HI("M", 8192), HI("n", 384), HS("dtype", "bf16") }, 8192.0 * 384 * 2 * 2, 0);
|
||||
|
||||
return c;
|
||||
}
|
||||
@@ -19,6 +19,7 @@
|
||||
* be unchanged, and the parallel rerun applies as for the table (avx_check.cpp). */
|
||||
#include "avx_check.h"
|
||||
#include "rad_planes.h"
|
||||
#include "rad_runtime.h" /* RAD_VGEOM_* */
|
||||
#include "rad_sample.h"
|
||||
#ifdef AVX_CHECK_CORE_DECODER
|
||||
#include "format/encoding.h"
|
||||
@@ -1944,6 +1945,45 @@ void gen_cases(std::vector<Hand>& hs) {
|
||||
.pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* ---- the prefix-free form: no cache, block table or prefix lengths; two entries of
|
||||
* 37 and 8 rows, bf16 and int8 scores, columns of a fused projection. */
|
||||
for (const bool pv8 : { false, true })
|
||||
for (const bool i8 : { false, true })
|
||||
for (const int causal : { 0, 1 }) {
|
||||
const int64_t T = 45, kvh = 2, gqa = 1, qh = 2, hd = 64;
|
||||
const int64_t W = (qh + 2 * kvh) * hd;
|
||||
char nm[128];
|
||||
std::snprintf(nm, sizeof nm, "no prefix, 2 entries%s%s%s%s", i8 ? ", i8" : "",
|
||||
pv8 ? ", fp8 P.V" : "", causal ? ", causal" : "", sfx.c_str());
|
||||
Hand h(nm, "attn_prefix_self", dt == RAD_F32 ? 1e-4 : 2e-2);
|
||||
h.view(dt, { T, qh * hd }, { W, 1 }, T * W, hfill(280))
|
||||
.view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(281));
|
||||
if (pv8) h.dense(RAD_F8E4M3, { T, kvh * hd }, hfill(282, 64.0f));
|
||||
else h.view(dt, { T, kvh * hd }, { W, 1 }, T * W, hfill(282));
|
||||
h.none().none().none()
|
||||
.idx({ 0, 37, T })
|
||||
.none().none();
|
||||
if (i8) {
|
||||
h.dense(RAD_I8, { T, kvh * hd }, [](int64_t i) {
|
||||
return (float)((int)((i * 41) % 255) - 127);
|
||||
})
|
||||
.dense(RAD_F32, { T, kvh }, [](int64_t i) {
|
||||
return 0.004f + 0.0005f * (float)(i % 5);
|
||||
});
|
||||
} else {
|
||||
h.none().none();
|
||||
}
|
||||
h.view(dt, { T, qh * hd }, { W, 1 }, T * W, zero, true);
|
||||
if (pv8) h.dense(RAD_F32, { kvh * hd }, [](int64_t i) {
|
||||
return 0.01f + 0.001f * (float)(i % 11);
|
||||
});
|
||||
else h.none();
|
||||
h.pi("q_len", T).pi("head_dim", hd).pi("gqa", gqa).pi("block_size", 16)
|
||||
.pi("causal", causal).ps("q_dtype", dn).ps("kv_dtype", dn).pi("max_ctx", 0)
|
||||
.pf("scale", 1.0 / std::sqrt((double)hd)).ps("qk", i8 ? "i8" : "bf16")
|
||||
.ps("pv", pv8 ? "fp8" : "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* One segment of a longer sequence: cu is its two bounding offsets, rows [5, 30), and
|
||||
* the rows outside it stay as they were. */
|
||||
@@ -2004,6 +2044,360 @@ void gen_cases(std::vector<Hand>& hs) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the video generator */
|
||||
/* Forms libref's descriptions do not draw: f32 positions as a [3, M] view of a wider plane, absent
|
||||
* gains and a partial rotary; the DiT's norm over three entries (one empty) with [shift | scale] a
|
||||
* column slice of a wider modulation table; a latent grid of different extents on every axis, so
|
||||
* the tiles overlap unevenly; a chunk between two others (the temporal blend and the overlap it
|
||||
* hands on), a last one and a first one; positions into a view of a wider plane. Everything but
|
||||
* the norms and the rotaries is held to zero error: libref's arithmetic bit for bit. */
|
||||
void video_cases(std::vector<Hand>& hs) {
|
||||
const auto zero = [](int64_t) { return 0.0f; };
|
||||
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
|
||||
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
|
||||
const std::string sfx = std::string(", ") + dn;
|
||||
const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3;
|
||||
|
||||
/* ---- the rotaries: positions f32, component-major, rows 32 apart ------------------- */
|
||||
{
|
||||
const int64_t M = 9, hd = 128, nh = 2, nkv = 2, W = (nh + 2 * nkv) * hd;
|
||||
const auto pos = [](int64_t i) { return 0.37f * (float)(i % 32) - 2.5f; };
|
||||
Hand h(("the DiT's axial 16 16 16 over 96 of 128, f32 positions" + sfx).c_str(),
|
||||
"qk_norm_rope", norm_tol);
|
||||
h.dense(dt, { M, W }, hfill(400), true)
|
||||
.view(RAD_F32, { 3, M }, { 32, 1 }, 96, pos)
|
||||
.dense(dt, { hd }, hfill(401, 0.1f))
|
||||
.dense(dt, { hd }, hfill(402, 0.1f))
|
||||
.pi("M", M).pi("head_dim", hd).pi("n_head", nh).pi("n_head_kv", nkv)
|
||||
.pf("theta", 10000.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 96)
|
||||
.ps("sections", "16 16 16");
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* The decoder's: no gains, positions 2 pi (2 (c + 0.5) / n - 1), theta 100. */
|
||||
const int64_t hv = 64, Wv = 3 * 4 * hv;
|
||||
const auto vpos = [](int64_t i) {
|
||||
const int64_t c = i / 32, m = i % 32;
|
||||
const int64_t n = c == 0 ? 3 : 4, k = c == 0 ? m % 3 : c == 1 ? (m / 4) % 4 : m % 4;
|
||||
return 6.2831855f * (2.0f * (((float)k + 0.5f) / (float)n) - 1.0f);
|
||||
};
|
||||
Hand g(("the decoder's axial 8 8 8 over 48 of 64, no gains" + sfx).c_str(),
|
||||
"qk_norm_rope", norm_tol);
|
||||
g.dense(dt, { M, Wv }, hfill(403), true)
|
||||
.view(RAD_F32, { 3, M }, { 32, 1 }, 96, vpos)
|
||||
.none().none()
|
||||
.pi("M", M).pi("head_dim", hv).pi("n_head", 4).pi("n_head_kv", 4)
|
||||
.pf("theta", 100.0).pf("eps", 1e-5).ps("mode", "axial").pi("rotary_dim", 48)
|
||||
.ps("sections", "8 8 8");
|
||||
hs.push_back(std::move(g));
|
||||
|
||||
Hand r(("rope over fractional f32 positions, scale 2" + sfx).c_str(), "rope",
|
||||
norm_tol);
|
||||
r.dense(dt, { M, 4 * 64 }, hfill(404), true)
|
||||
.dense(RAD_F32, { M }, [](int64_t i) { return 0.73f * (float)i - 1.1f; })
|
||||
.pi("M", M).pi("head_dim", 64).pi("n_head", 2).pi("n_head_kv", 1)
|
||||
.pf("theta", 10000.0).pf("scale", 2.0).ps("mode", "neox");
|
||||
hs.push_back(std::move(r));
|
||||
}
|
||||
|
||||
/* ---- the DiT's norm: three entries (one empty), [shift | scale] at a 6n pitch ------- */
|
||||
{
|
||||
const int64_t R = 11, D = 160, W6 = 6 * D;
|
||||
for (const bool gated : { true, false }) {
|
||||
Hand h((std::string(gated ? "gated" : "ungated") + ", three entries, s at a 6n "
|
||||
"pitch" + sfx).c_str(), "rms_mod", norm_tol);
|
||||
if (gated) {
|
||||
h.dense(dt, { R, D }, hfill(410))
|
||||
.view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(411, 0.5f));
|
||||
} else {
|
||||
h.none().none();
|
||||
}
|
||||
h.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(412, 0.5f))
|
||||
.dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; })
|
||||
.idx({ 0, 4, 4, R })
|
||||
.dense(dt, { R, D }, hfill(413, 2.0f), true)
|
||||
.dense(dt, { R, D }, zero, true)
|
||||
.pi("M", R).pi("n", D).pf("eps", 1e-5).pi("gated", gated ? 1 : 0)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
Hand q((std::string(gated ? "gated" : "ungated") + ", quantised, three entries" +
|
||||
sfx).c_str(), "rms_mod_quant_fp8", 1e-2);
|
||||
if (gated) {
|
||||
q.dense(dt, { R, D }, hfill(414))
|
||||
.view(dt, { 3, D }, { W6, 1 }, 3 * W6, hfill(415, 0.5f));
|
||||
} else {
|
||||
q.none().none();
|
||||
}
|
||||
q.view(dt, { 3, 2 * D }, { W6, 1 }, 3 * W6, hfill(416, 0.5f))
|
||||
.dense(dt, { D }, [](int64_t i) { return 0.8f + 0.003f * (float)i; })
|
||||
.idx({ 0, 4, 4, R })
|
||||
.dense(dt, { R, D }, hfill(417, 2.0f), true)
|
||||
.dense(RAD_F8E4M3, { R, D }, zero, true)
|
||||
.dense(RAD_F32, { R, D / 32 }, zero, true)
|
||||
.dense(RAD_BF16, { R, D }, zero, true)
|
||||
.pi("M", R).pi("n", D).pf("eps", 1e-5).pi("group", 32)
|
||||
.pi("gated", gated ? 1 : 0).ps("dtype", dn);
|
||||
hs.push_back(std::move(q));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the sampler: a bf16 velocity into an f32 state ------------------------------- */
|
||||
{
|
||||
Hand h(("bf16 velocity, f32 state, rows at a wider pitch" + sfx).c_str(),
|
||||
"flow_x0_step", 0.0);
|
||||
h.dense(dt, { 7, 96 }, hfill(420, 2.0f))
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.3046875f; })
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.6953125f; })
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.4413f; })
|
||||
.view(RAD_F32, { 7, 96 }, { 101, 1 }, 7 * 101, hfill(421), true)
|
||||
.pi("M", 7).pi("n", 96).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
|
||||
/* ---- the decoder's geometry: 3 frames of 6 x 9 latents, tiles of 4 over 1 ------------ *
|
||||
* Rows split 6 -> starts 0, 2 (overlap 2); columns 9 -> 0, 2, 5 (overlaps 2, 1). */
|
||||
{
|
||||
Hand h(("2 x 3 x 2 patches of 2 x 2 x 2, rows past the voxels" + sfx).c_str(),
|
||||
"patch_unfold", 0.0);
|
||||
h.dense(RAD_F32, { 12, 5 * 8 }, hfill(430, 3.0f))
|
||||
.idx({ 2, 3, 2 })
|
||||
.dense(dt, { 100, 5 }, hfill(431), true)
|
||||
.pi("M", 100).pi("C", 5).pi("pt", 2).pi("ph", 2).pi("pw", 2)
|
||||
.ps("mul", "0.5 1.25 -2 0.3 1.7").ps("add", "0.1 -0.2 0.3 0 2.5").ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* Two register rows and two zero rows a tile. */
|
||||
const int64_t n = 37, period = 52, tiles = 6;
|
||||
Hand g(("6 x 9 in tiles of 4 over 1, registers and zero rows" + sfx).c_str(),
|
||||
"vtile_gather", 0.0);
|
||||
g.dense(dt, { 3 * 6 * 9, n }, hfill(432))
|
||||
.dense(dt, { 2, n }, hfill(433))
|
||||
.idx({ 3, 6, 9 })
|
||||
.dense(dt, { tiles * period, n }, hfill(434), true)
|
||||
.pi("M", tiles * period).pi("n", n).pi("tile", 4).pi("overlap", 1).pi("frames", 3)
|
||||
.pi("period", period).pi("n_reg", 2).ps("dtype", dn);
|
||||
hs.push_back(std::move(g));
|
||||
|
||||
/* The decoded tiles at scale 2, two clip frames a latent one: skip 1, keep 3, blend 1;
|
||||
* each tile's 48 token rows, then 4 rows the stitch does not read. */
|
||||
struct Chunk { int first, last; const char* what; };
|
||||
static const Chunk kChunks[] = { { 0, 0, "a chunk between two others" },
|
||||
{ 0, 1, "a video's last chunk" },
|
||||
{ 1, 0, "a video's first chunk" } };
|
||||
const int64_t npx = 12 * 18;
|
||||
for (const Chunk& ch : kChunks) {
|
||||
const int64_t fout = 3 + (ch.last ? 1 : 0);
|
||||
Hand s((std::string(ch.what) + ", 6 x 9 in tiles of 4 over 1" + sfx).c_str(),
|
||||
"vtile_stitch", 0.0);
|
||||
s.dense(dt, { tiles * period, 3 * 2 * 2 * 2 }, hfill(435, 2.0f))
|
||||
.idx({ 3, 6, 9, ch.first, ch.last })
|
||||
.dense(RAD_BF16, { npx, 3 }, hfill(436, 2.0f), true)
|
||||
.dense(RAD_U8, { fout * npx, 3 }, zero, true)
|
||||
.pi("M", fout * npx).pi("tile", 4).pi("overlap", 1).pi("scale", 2).pi("pt", 2)
|
||||
.pi("skip", 1).pi("keep", 3).pi("blend", 1).pi("period", period)
|
||||
.ps("mean", "0.485 0.456 0.406").ps("std", "0.229 0.224 0.225");
|
||||
hs.push_back(std::move(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- positions into a [3, 40] view of a [3, 64] plane ---------------------------------- */
|
||||
{
|
||||
Hand h("two periods of 2 x 3 x 4 and its registers, rows 64 apart", "grid_pos3", 0.0);
|
||||
h.view(RAD_F32, { 3, 40 }, { 64, 1 }, 192, [](int64_t) { return -7.0f; }, true)
|
||||
.pi("M", 40).pi("T", 2).pi("H", 3).pi("W", 4).pi("period", 27)
|
||||
.pf("scale", 6.283185307179586);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== video sparse attention
|
||||
* What libref's descriptions cannot draw: uneven dense segments (13 and 14 rows: a tile each in
|
||||
* boxes of 4, two each in boxes of 2) before a 6 x 5 x 7 grid (a 10 x 14 latent at patch 2) with
|
||||
* edge boxes on every axis, and `geom`'s other entries holding values no tile reads; q, k, v and
|
||||
* the gate at a fused projection's row pitch and the output at a pitch of its own; `sel` and
|
||||
* `coarse` wider than the tiles and the selection; attn_vsa over selections of every size from 1
|
||||
* to V that are not a top-k of anything; and what both refuse. Outputs start as a sentinel, so an
|
||||
* element one side writes and the other leaves shows as a difference, and attn_vsa's `sel` holds
|
||||
* one wherever the op must not read. */
|
||||
|
||||
/* attn_vsa's `sel`, [nh, cap, kc]: per head and video query tile, k distinct video tiles of
|
||||
* [P, N) in ascending order, drawn from `seed`; `fill` everywhere else. */
|
||||
std::vector<float> vsa_selection(int64_t nh, int64_t cap, int64_t kc, int64_t P, int64_t N,
|
||||
int64_t k, uint64_t seed, float fill) {
|
||||
std::vector<float> s((size_t)(nh * cap * kc), fill);
|
||||
std::vector<int64_t> pool;
|
||||
uint64_t x = seed;
|
||||
for (int64_t h = 0; h < nh; ++h)
|
||||
for (int64_t i = P; i < N; ++i) {
|
||||
pool.clear();
|
||||
for (int64_t j = P; j < N; ++j) pool.push_back(j);
|
||||
for (int64_t a = 0; a < k; ++a) {
|
||||
const int64_t b = a + (int64_t)(hsplitmix(x) % (uint64_t)(N - P - a));
|
||||
std::swap(pool[(size_t)a], pool[(size_t)b]);
|
||||
}
|
||||
std::sort(pool.begin(), pool.begin() + k);
|
||||
for (int64_t a = 0; a < k; ++a)
|
||||
s[(size_t)((h * cap + i) * kc + a)] = (float)pool[(size_t)a];
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void vsa_cases(std::vector<Hand>& hs) {
|
||||
const int64_t R = 237, NH = 2, HD = 64, W = 4 * NH * HD, WO = NH * HD + 24;
|
||||
const auto sentinel = [](int64_t) { return -7.0f; };
|
||||
const auto geom = [](int64_t i) {
|
||||
return i == RAD_VGEOM_LAT_FRAMES ? 6.0f : i == RAD_VGEOM_LAT_H ? 10.0f
|
||||
: i == RAD_VGEOM_LAT_W ? 14.0f : (float)(1000 + i);
|
||||
};
|
||||
struct Geo { int64_t tt, P, V; const char* what; };
|
||||
static const Geo kGeo[] = { { 4, 2, 8, "boxes of 4" }, { 2, 4, 36, "boxes of 2" } };
|
||||
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
|
||||
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
|
||||
const double sel_tol = dt == RAD_F32 ? 1e-5 : 6e-3, att_tol = dt == RAD_F32 ? 1e-4 : 2e-2;
|
||||
for (const Geo& g : kGeo)
|
||||
for (const double sp : { 0.8, 0.0, 0.95 }) {
|
||||
const int64_t N = g.P + g.V;
|
||||
const int64_t k = std::max<int64_t>(
|
||||
1, std::min<int64_t>((int64_t)std::ceil((1.0 - sp) * (double)g.V), g.V));
|
||||
char sfx[96];
|
||||
std::snprintf(sfx, sizeof sfx, ", 13 | 14 then 6 x 5 x 7, %s, sparsity %g, %s",
|
||||
g.what, sp, dn);
|
||||
for (const bool coarse : { true, false }) {
|
||||
Hand h((std::string(coarse ? "q, k, v at a pitch, coarse" : "q, k at a pitch, "
|
||||
"no coarse") + sfx).c_str(), "vsa_select", sel_tol);
|
||||
h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(500))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(501));
|
||||
if (coarse) h.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(502, 2.0f));
|
||||
else h.none();
|
||||
h.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
|
||||
.dense(RAD_I32, { NH, N + 2, k + 2 }, sentinel, true);
|
||||
if (coarse) h.dense(dt, { NH, N + 1, HD }, sentinel, true);
|
||||
else h.none();
|
||||
h.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
|
||||
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
const std::vector<float> sv =
|
||||
vsa_selection(NH, N + 1, k + 1, g.P, N, k, 503 + (uint64_t)k, -9.0f);
|
||||
Hand a((std::string(coarse ? "q, k, v, gate at a pitch, coarse, out at its "
|
||||
"own" : "q, k, v at a pitch, out at its own") + sfx +
|
||||
", a drawn selection").c_str(), "attn_vsa", att_tol);
|
||||
a.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f))
|
||||
.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
|
||||
.dense(RAD_I32, { NH, N + 1, k + 1 },
|
||||
[sv](int64_t i) { return sv[(size_t)i]; });
|
||||
if (coarse) {
|
||||
a.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508));
|
||||
} else {
|
||||
a.none().none();
|
||||
}
|
||||
a.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
|
||||
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
|
||||
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp);
|
||||
hs.push_back(std::move(a));
|
||||
if (!coarse) continue;
|
||||
/* The int8 score form: k's codes and per-(row, head) scales beside it. */
|
||||
Hand q8((std::string("int8 scores, coarse") + sfx + ", a drawn selection").c_str(),
|
||||
"attn_vsa", att_tol);
|
||||
q8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(506, 2.0f))
|
||||
.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
|
||||
.dense(RAD_I32, { NH, N + 1, k + 1 },
|
||||
[sv](int64_t i) { return sv[(size_t)i]; })
|
||||
.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508))
|
||||
.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
|
||||
.dense(RAD_I8, { R, NH * HD }, [](int64_t i) {
|
||||
return (float)((int)((i * 53) % 255) - 127);
|
||||
})
|
||||
.dense(RAD_F32, { R, NH }, [](int64_t i) { return 0.004f + 0.0005f * (float)(i % 9); })
|
||||
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
|
||||
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8");
|
||||
hs.push_back(std::move(q8));
|
||||
/* The same with the fp8 P.V form: E4M3 values and a scale per column. */
|
||||
Hand p8((std::string("int8 scores, fp8 P.V, coarse") + sfx +
|
||||
", a drawn selection").c_str(), "attn_vsa", att_tol);
|
||||
p8.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(504))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(505))
|
||||
.dense(RAD_F8E4M3, { R, NH * HD }, hfill(506, 64.0f))
|
||||
.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N }, geom)
|
||||
.dense(RAD_I32, { NH, N + 1, k + 1 },
|
||||
[sv](int64_t i) { return sv[(size_t)i]; })
|
||||
.dense(dt, { NH, N + 1, HD }, hfill(507, 0.5f))
|
||||
.view(dt, { R, NH * HD }, { W, 1 }, R * W, hfill(508))
|
||||
.view(dt, { R, NH * HD }, { WO, 1 }, R * WO, sentinel, true)
|
||||
.dense(RAD_I8, { R, NH * HD }, [](int64_t i) {
|
||||
return (float)((int)((i * 53) % 255) - 127);
|
||||
})
|
||||
.dense(RAD_F32, { R, NH }, [](int64_t i) {
|
||||
return 0.004f + 0.0005f * (float)(i % 9);
|
||||
})
|
||||
.dense(RAD_F32, { NH * HD }, [](int64_t i) {
|
||||
return 0.01f + 0.001f * (float)(i % 13);
|
||||
})
|
||||
.pi("M", R).pi("head_dim", HD).pi("tile_t", g.tt).pi("tile_h", g.tt)
|
||||
.pi("tile_w", g.tt).pi("patch", 2).pf("sparsity", sp).ps("qk", "i8")
|
||||
.ps("pv", "fp8");
|
||||
hs.push_back(std::move(p8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- refusals: nothing written --------------------------------------------------------- */
|
||||
const int64_t N = 10, k = 2;
|
||||
std::vector<float> sv = vsa_selection(NH, N, k, 2, N, k, 509, -9.0f);
|
||||
std::swap(sv[(size_t)(5 * k)], sv[(size_t)(5 * k + 1)]); /* head 0, tile 5: descending */
|
||||
struct Bad { const char* what; int rc; bool gate; float frames; };
|
||||
static const Bad kBad[] = {
|
||||
{ "a selection row out of order", RAD_E_INVAL, true, 6.0f },
|
||||
{ "coarse without its gate", RAD_E_SHAPE, false, 6.0f },
|
||||
{ "a grid of 5 frames short of the last segment", RAD_E_SHAPE, true, 5.0f },
|
||||
};
|
||||
for (const Bad& b : kBad) {
|
||||
const float fr = b.frames;
|
||||
const std::vector<float> sel = b.rc == RAD_E_INVAL
|
||||
? sv : vsa_selection(NH, N, k, 2, N, k, 509, -9.0f);
|
||||
Hand a((std::string("refused: ") + b.what).c_str(), "attn_vsa", 2e-2);
|
||||
a.dense(RAD_BF16, { R, NH * HD }, hfill(510))
|
||||
.dense(RAD_BF16, { R, NH * HD }, hfill(511))
|
||||
.dense(RAD_BF16, { R, NH * HD }, hfill(512))
|
||||
.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N },
|
||||
[fr, geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? fr : geom(i); })
|
||||
.dense(RAD_I32, { NH, N, k }, [sel](int64_t i) { return sel[(size_t)i]; })
|
||||
.dense(RAD_BF16, { NH, N, HD }, hfill(513));
|
||||
if (b.gate) a.dense(RAD_BF16, { R, NH * HD }, hfill(514));
|
||||
else a.none();
|
||||
a.dense(RAD_BF16, { R, NH * HD }, sentinel, true)
|
||||
.pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4)
|
||||
.pi("patch", 2).pf("sparsity", 0.8).refuses(b.rc);
|
||||
hs.push_back(std::move(a));
|
||||
}
|
||||
{
|
||||
Hand s("refused: a grid of 5 frames short of the last segment", "vsa_select", 6e-3);
|
||||
s.dense(RAD_BF16, { R, NH * HD }, hfill(515))
|
||||
.dense(RAD_BF16, { R, NH * HD }, hfill(516))
|
||||
.none()
|
||||
.idx({ 0, 13, 27, R })
|
||||
.dense(RAD_I32, { RAD_VGEOM_N },
|
||||
[geom](int64_t i) { return i == RAD_VGEOM_LAT_FRAMES ? 5.0f : geom(i); })
|
||||
.dense(RAD_I32, { NH, N, k }, sentinel, true)
|
||||
.none()
|
||||
.pi("M", R).pi("head_dim", HD).pi("tile_t", 4).pi("tile_h", 4).pi("tile_w", 4)
|
||||
.pi("patch", 2).pf("sparsity", 0.8).refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(s));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the QSA indexer and DFlash2
|
||||
* What libref's descriptions cannot draw: cu not starting at 0 and rows no sequence holds, -1
|
||||
* pages, the score plane as a column slice of the declared width, the block keys in the KV
|
||||
@@ -3013,6 +3407,481 @@ void encoder_cases(std::vector<Hand>& hs) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the audio generator */
|
||||
/* Forms libref's descriptions do not draw: weights at a trained snake's scale (the drawn 0.02
|
||||
* leaves the sine almost linear) and arguments past the polynomial's range, SnakeBeta, several
|
||||
* sequences of uneven length starting past row 0 with an empty one, a convolution without its bias
|
||||
* and residual, a causal one with an even kernel, a depthwise one with a bias, transposed ones at
|
||||
* odd strides and at a kernel of one stride, sampler rows full of ties, a sampler with per-lane
|
||||
* guidance and a history (one lane twice), the window entries the run phase issues: unconditional
|
||||
* branches (pair -2), every flag combination, a window shorter than its overlap, a frame 0, an
|
||||
* ended lane; codes as a block of a wider plane; and refusals that must write nothing. Everything
|
||||
* but the convolutions and snake is held to zero error. */
|
||||
void audio_cases(std::vector<Hand>& hs) {
|
||||
const auto zero = [](int64_t) { return 0.0f; };
|
||||
for (const uint32_t dt : { (uint32_t)RAD_F32, (uint32_t)RAD_BF16 }) {
|
||||
const char* dn = dt == RAD_F32 ? "f32" : "bf16";
|
||||
const std::string sfx = std::string(", ") + dn;
|
||||
const double norm_tol = dt == RAD_F32 ? 1e-5 : 6e-3;
|
||||
{
|
||||
/* alpha 0.25 .. 4.2 and x in [-8, 8]: arguments to about 34. Row 3 holds 30000 (past
|
||||
* the polynomial's range, so the row takes the libm sine), row 2 a NaN, row 4 an
|
||||
* infinity. */
|
||||
const int64_t n = 67;
|
||||
Hand h(("trained alphas, a large argument, NaN and infinity" + sfx).c_str(), "snake",
|
||||
norm_tol);
|
||||
h.dense(dt, { 5, n }, [n](int64_t i) {
|
||||
if (i == 3 * n + 4) return 30000.0f;
|
||||
if (i == 2 * n + 10) return NAN;
|
||||
if (i == 4 * n + 66) return INFINITY;
|
||||
return hfill(260, 8.0f)(i);
|
||||
})
|
||||
.dense(RAD_F32, { n }, [](int64_t c) { return 0.25f + 0.06f * (float)c; })
|
||||
.dense(dt, { 5, n }, zero, true)
|
||||
.pi("M", 5).pi("n", n).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Three sequences from row 2, the second empty, no bias and no residual; rows 0, 1,
|
||||
* 16 and 17 of y are outside every sequence and keep their bytes. */
|
||||
const int64_t cin = 20, cout = 13;
|
||||
Hand h(("rows 2..16 in three sequences, no bias or residual, tanh" + sfx).c_str(),
|
||||
"conv1d", norm_tol);
|
||||
h.dense(dt, { 18, cin }, hfill(261))
|
||||
.dense(dt, { cout, cin, 5 }, hfill(262, 0.3f))
|
||||
.idx({ 2, 7, 7, 16 })
|
||||
.none()
|
||||
.dense(dt, { 18, cout }, hfill(263), true)
|
||||
.none()
|
||||
.pi("M", 18).pi("cin", cin).pi("cout", cout).pi("k", 5).pi("dil", 2)
|
||||
.ps("act", "tanh").ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* x rows at a wider pitch than its channels, with the residual and the bias. */
|
||||
Hand g(("input rows at a wider pitch, residual and bias" + sfx).c_str(), "conv1d",
|
||||
norm_tol);
|
||||
g.view(dt, { 16, cin }, { cin + 3, 1 }, 16 * (cin + 3), hfill(264))
|
||||
.dense(dt, { cout, cin, 3 }, hfill(265, 0.3f))
|
||||
.idx({ 0, 9, 16 })
|
||||
.dense(dt, { 16, cout }, hfill(266))
|
||||
.dense(dt, { 16, cout }, zero, true)
|
||||
.dense(dt, { cout }, hfill(267, 0.5f))
|
||||
.pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 3).pi("dil", 1)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(g));
|
||||
}
|
||||
for (const int64_t s : { 4, 2 }) {
|
||||
/* Sequences of 3, 1 and 5 rows from row 1: output rows [s, 10 s); the first s rows of
|
||||
* y keep their bytes. */
|
||||
const int64_t cin = 12, cout = 7;
|
||||
Hand h(("three uneven sequences from row 1, stride " + std::to_string(s) + sfx).c_str(),
|
||||
"conv_t1d", norm_tol);
|
||||
h.dense(dt, { 10, cin }, hfill(268))
|
||||
.dense(dt, { cin, cout, 2 * s }, hfill(269, 0.3f))
|
||||
.dense(dt, { cout }, hfill(270, 0.5f))
|
||||
.idx({ 1, 4, 5, 10 })
|
||||
.dense(dt, { 10 * s, cout }, hfill(271), true)
|
||||
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Lanes 2, 0, 1, 3 of four ten-row lanes, overlap 4, seven channels (a Philox block of
|
||||
* four straddles rows): FIRST | JOIN over a whole window; the same flags on an
|
||||
* unconditional branch, which moves nothing; JOIN alone over a window of 3 rows,
|
||||
* shorter than the overlap; FIRST alone over 6 rows. */
|
||||
static const uint32_t kSeeds[8] = { 0x9e3779b9u, 1u, 7u, 0u, 3u, 0xfffffffeu, 11u,
|
||||
0x80000001u };
|
||||
Hand h(("every flag combination, an unconditional entry, a short window" + sfx).c_str(),
|
||||
"win_prep", 0.0);
|
||||
h.idx({ 17, 17, 16, 1 })
|
||||
.dense(RAD_F32, { 4 }, [](int64_t i) { return 0.7f - 0.13f * (float)i; })
|
||||
.raw(RAD_U32, { 8 }, kSeeds)
|
||||
.idx({ 0, 5, 2, 9 })
|
||||
.idx({ 2, 0, 1, 3 })
|
||||
.idx({ 1, -2, -1, -1 })
|
||||
.idx({ 0, 10, 20, 23, 29 })
|
||||
.dense(RAD_BF16, { 16, 7 }, hfill(272))
|
||||
.dense(RAD_BF16, { 16, 7 }, hfill(273), true)
|
||||
.dense(RAD_BF16, { 40, 7 }, hfill(274), true)
|
||||
.pi("M", 29).pi("n", 7).pi("stride", 10).pi("ov", 4).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* LAST | JOIN over a whole window; LAST over 7 rows (rows - 2 ov < 0, so the kept
|
||||
* overlap starts at row 0); LAST on an unconditional branch; JOIN without LAST. */
|
||||
Hand h(("LAST with and without JOIN, a short window, two skipped" + sfx).c_str(),
|
||||
"win_finish", 0.0);
|
||||
h.idx({ 24, 8, 8, 16 })
|
||||
.idx({ -1, -1, -2, 0 })
|
||||
.idx({ 1, 3, 2, 0 })
|
||||
.idx({ 0, 10, 17, 20, 25 })
|
||||
.dense(dt, { 40, 5 }, hfill(275))
|
||||
.dense(RAD_BF16, { 40, 7 }, hfill(276), true)
|
||||
.dense(RAD_BF16, { 16, 7 }, hfill(277), true)
|
||||
.dense(dt, { 16, 5 }, hfill(278), true)
|
||||
.pi("M", 25).pi("n", 7).pi("n_cond", 5).pi("stride", 10).pi("ov", 4)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Lane 1 twice, the second an unconditional branch (zeros for its conditioning). */
|
||||
Hand h(("an unconditional entry beside its conditional one" + sfx).c_str(),
|
||||
"win_input", 0.0);
|
||||
h.dense(dt, { 24, 9 }, hfill(279))
|
||||
.dense(dt, { 24, 5 }, hfill(280))
|
||||
.idx({ 0, 6, 12, 15 })
|
||||
.idx({ 1, 1, 0 })
|
||||
.idx({ 1, -2, -1 })
|
||||
.dense(dt, { 15, 16 }, hfill(281), true)
|
||||
.pi("M", 15).pi("n_lat", 9).pi("n_zero", 2).pi("n_cond", 5).pi("stride", 8)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Four lanes, two branch rows each: entry 0 at frame 0 (moves past the prompt only),
|
||||
* entry 1 on an ended lane, entries 2 and 3 stored. */
|
||||
Hand h(("frame 0, an ended lane, two stored" + sfx).c_str(), "frame_mix_store", 0.0);
|
||||
h.dense(dt, { 3 * 8, 37 }, hfill(282, 4.0f))
|
||||
.dense(RAD_F32, { 3 }, [](int64_t l) { return l == 0 ? 0.3f : l == 1 ? -1.2f : 2.0f; })
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 1.7f; })
|
||||
.idx({ 2, 0, 3, 1 })
|
||||
.idx({ 0, 3, 2, 5 })
|
||||
.idx({ -1, 2, 5, 7 })
|
||||
.dense(dt, { 20, 37 }, hfill(283), true)
|
||||
.pi("M", 4).pi("n_embd", 37).pi("L", 3).pi("stride", 5).pi("rep", 2)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Codes past either table: row 1's first code (its row is not written), row 2's
|
||||
* second (skipped in the sum). Code-major [3, 4]. */
|
||||
static const int32_t kCodes[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 };
|
||||
Hand h(("codes past either table" + sfx).c_str(), "rvq_embed", 0.0);
|
||||
h.raw(RAD_I32, { 3, 4 }, kCodes)
|
||||
.dense(RAD_BF16, { 12, 9 }, hfill(284))
|
||||
.dense(RAD_BF16, { 20, 9 }, hfill(285))
|
||||
.dense(dt, { 4, 9 }, hfill(286), true)
|
||||
.pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
|
||||
.pf("scale", 0.75).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (int round : { 1, 0 }) {
|
||||
/* A trained projection's scale: angles to about 25 radians. */
|
||||
Hand h(("trained frequencies, round " + std::to_string(round) + sfx).c_str(),
|
||||
"fourier_embed", 0.0);
|
||||
h.dense(RAD_F32, { 5 }, [](int64_t i) { return i == 4 ? 1.0f : 0.23f * (float)i; })
|
||||
.dense(RAD_F32, { 32 }, hfill(287, 4.0f))
|
||||
.dense(dt, { 5, 64 }, zero, true)
|
||||
.pi("M", 5).pi("n", 64).pi("round", round).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h(("ten rows down to four" + sfx).c_str(), "resample_nearest", 0.0);
|
||||
h.dense(dt, { 10, 7 }, hfill(288))
|
||||
.dense(dt, { 4, 7 }, zero, true)
|
||||
.pi("M", 4).pi("n", 7).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h(("three groups of input rows at a wider pitch" + sfx).c_str(), "chan_split",
|
||||
0.0);
|
||||
h.view(dt, { 5, 21 }, { 25, 1 }, 125, hfill(289))
|
||||
.dense(dt, { 15, 7 }, zero, true)
|
||||
.pi("M", 5).pi("n", 7).pi("parts", 3).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (int lg : { 0, 1 }) {
|
||||
/* SnakeBeta over x in [-8, 8]: alpha and beta as a codec stores them (logarithms in
|
||||
* [-1, 1], `log` 1) or as positive values. */
|
||||
const int64_t n = 37;
|
||||
const std::function<float(int64_t)> al =
|
||||
lg ? hfill(291) : std::function<float(int64_t)>([](int64_t c) {
|
||||
return 0.3f + 0.05f * (float)c;
|
||||
});
|
||||
const std::function<float(int64_t)> be =
|
||||
lg ? hfill(292) : std::function<float(int64_t)>([](int64_t c) {
|
||||
return 0.2f + 0.03f * (float)c;
|
||||
});
|
||||
Hand h(("SnakeBeta, alpha and beta as " + std::string(lg ? "logarithms" : "values") +
|
||||
sfx).c_str(), "snake", norm_tol);
|
||||
h.dense(dt, { 4, n }, hfill(293, 8.0f))
|
||||
.dense(RAD_F32, { n }, al)
|
||||
.dense(dt, { 4, n }, zero, true)
|
||||
.dense(RAD_F32, { n }, be)
|
||||
.pi("M", 4).pi("n", n).pi("log", lg).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* Two segments from row 1, with a bias; row 0 keeps its bytes. */
|
||||
const int64_t C = 21;
|
||||
Hand h(("two segments from row 1, with a bias" + sfx).c_str(), "conv1d_dw", norm_tol);
|
||||
h.dense(dt, { 12, C }, hfill(294))
|
||||
.dense(dt, { C, 1, 5 }, hfill(295, 0.4f))
|
||||
.idx({ 1, 6, 12 })
|
||||
.dense(dt, { 12, C }, zero, true)
|
||||
.dense(dt, { C }, hfill(296, 0.5f))
|
||||
.pi("M", 12).pi("n", C).pi("k", 5).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (int dil : { 1, 3 }) {
|
||||
/* Causal with an even kernel (a codec's), two sequences, a bias. */
|
||||
const int64_t cin = 20, cout = 13;
|
||||
Hand h(("causal, k 4, dilation " + std::to_string(dil) + sfx).c_str(), "conv1d",
|
||||
norm_tol);
|
||||
h.dense(dt, { 16, cin }, hfill(296 + dil))
|
||||
.dense(dt, { cout, cin, 4 }, hfill(300, 0.3f))
|
||||
.idx({ 0, 7, 16 })
|
||||
.none()
|
||||
.dense(dt, { 16, cout }, zero, true)
|
||||
.dense(dt, { cout }, hfill(301, 0.5f))
|
||||
.pi("M", 16).pi("cin", cin).pi("cout", cout).pi("k", 4).pi("dil", dil)
|
||||
.pi("causal", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const int64_t s : { 5, 3 }) {
|
||||
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
|
||||
* from row 1. */
|
||||
const int64_t cin = 12, cout = 7;
|
||||
Hand h(("odd stride " + std::to_string(s) + ", causal" + sfx).c_str(), "conv_t1d",
|
||||
norm_tol);
|
||||
h.dense(dt, { 10, cin }, hfill(314 + s))
|
||||
.dense(dt, { cin, cout, 2 * s }, hfill(320, 0.3f))
|
||||
.dense(dt, { cout }, hfill(321, 0.5f))
|
||||
.idx({ 1, 4, 5, 10 })
|
||||
.dense(dt, { 10 * s, cout }, hfill(322), true)
|
||||
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const int64_t s : { 5, 2 }) {
|
||||
/* BigVGAN's upsamplers (kernel 9 at stride 5, pad 2; kernel 12 at stride 2, its
|
||||
* default pad 5 past a stride) over sequences of 3, 1 and 5 rows from row 1. */
|
||||
const int64_t cin = 12, cout = 7, K = s == 5 ? 9 : 12;
|
||||
Hand h(("kernel " + std::to_string(K) + " at stride " + std::to_string(s) +
|
||||
", three uneven sequences" + sfx).c_str(), "conv_t1d", norm_tol);
|
||||
h.dense(dt, { 10, cin }, hfill(330 + s))
|
||||
.dense(dt, { cin, cout, K }, hfill(336, 0.3f))
|
||||
.dense(dt, { cout }, hfill(337, 0.5f))
|
||||
.idx({ 1, 4, 5, 10 })
|
||||
.dense(dt, { 10 * s, cout }, hfill(338), true)
|
||||
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", K)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const int64_t k : { 12, 7 }) {
|
||||
/* The alias-free SnakeBeta over sequences of 5, 1 and 9 rows from row 1 (row 0 and
|
||||
* rows past 16 keep their bytes), at a trained scale: alpha and beta logarithms,
|
||||
* x in [-4, 4], a smooth low-pass pair of filters. */
|
||||
const int64_t n = 21;
|
||||
const auto lowpass = [k](int64_t j) {
|
||||
const float t = ((float)j + 0.5f) / (float)k - 0.5f;
|
||||
return (1.0f - 4.0f * t * t) / (float)k * 1.5f;
|
||||
};
|
||||
Hand h(("three uneven sequences, filters of " + std::to_string(k) + sfx).c_str(),
|
||||
"snake_aa", norm_tol);
|
||||
h.dense(dt, { 18, n }, hfill(340, 4.0f))
|
||||
.dense(RAD_F32, { n }, hfill(341, 0.8f))
|
||||
.dense(RAD_F32, { n }, hfill(342, 0.8f))
|
||||
.dense(RAD_F32, { 1, 1, k }, lowpass)
|
||||
.dense(RAD_F32, { 1, 1, k }, lowpass)
|
||||
.idx({ 1, 6, 7, 16 })
|
||||
.dense(dt, { 18, n }, hfill(343), true)
|
||||
.pi("M", 18).pi("n", n).pi("ratio", 2).pi("k", k).pi("log", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* A kernel of one stride at an odd stride: each output row reads one input row. */
|
||||
const int64_t cin = 12, cout = 7, s = 3;
|
||||
Hand h(("kernel 3 at stride 3" + sfx).c_str(), "conv_t1d", norm_tol);
|
||||
h.dense(dt, { 10, cin }, hfill(323))
|
||||
.dense(dt, { cin, cout, s }, hfill(324, 0.3f))
|
||||
.dense(dt, { cout }, hfill(325, 0.5f))
|
||||
.idx({ 1, 4, 5, 10 })
|
||||
.dense(dt, { 10 * s, cout }, hfill(326), true)
|
||||
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("k", s)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The causal transposed form over sequences of 3, 1 and 5 rows from row 1. */
|
||||
const int64_t cin = 12, cout = 7, s = 4;
|
||||
Hand h(("the causal form over three uneven sequences" + sfx).c_str(), "conv_t1d",
|
||||
norm_tol);
|
||||
h.dense(dt, { 10, cin }, hfill(302))
|
||||
.dense(dt, { cin, cout, 2 * s }, hfill(303, 0.3f))
|
||||
.dense(dt, { cout }, hfill(304, 0.5f))
|
||||
.idx({ 1, 4, 5, 10 })
|
||||
.dense(dt, { 10 * s, cout }, hfill(305), true)
|
||||
.pi("M", 10).pi("cin", cin).pi("cout", cout).pi("stride", s).pi("pad", 0)
|
||||
.ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* One rounding of the whole sum, with codes past either table (row 1's first code
|
||||
* leaves its row unwritten, row 2's second adds nothing). Code-major [3, 4]. */
|
||||
static const int32_t kCodes1[12] = { 3, 10, 0, -2, 4, 1, -15, 7, 9, 2, 5, 0 };
|
||||
Hand h(("one rounding, codes past either table" + sfx).c_str(), "rvq_embed", 0.0);
|
||||
h.raw(RAD_I32, { 3, 4 }, kCodes1)
|
||||
.dense(RAD_BF16, { 12, 9 }, hfill(306))
|
||||
.dense(RAD_BF16, { 20, 9 }, hfill(307))
|
||||
.dense(dt, { 4, 9 }, hfill(308), true)
|
||||
.pi("M", 4).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
|
||||
.pf("scale", 0.75).pi("round", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* The codes as a block of a wider plane (a lane's history over a run of frames): rows
|
||||
* at pitch 11, read at the operand's strides. */
|
||||
Hand g(("one rounding, codes a block of a wider plane" + sfx).c_str(), "rvq_embed",
|
||||
0.0);
|
||||
g.view(RAD_I32, { 3, 5 }, { 11, 1 }, 33, [](int64_t i) { return (float)(i % 9); })
|
||||
.dense(RAD_BF16, { 12, 9 }, hfill(309))
|
||||
.dense(RAD_BF16, { 20, 9 }, hfill(310))
|
||||
.dense(dt, { 5, 9 }, zero, true)
|
||||
.pi("M", 5).pi("n_embd", 9).pi("n_codes", 3).pi("vocab", 10).pi("off0", 2)
|
||||
.pf("scale", 1.0).pi("round", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(g));
|
||||
}
|
||||
}
|
||||
{
|
||||
/* Logits on a grid of 0.05 over [-1, 1]: ties throughout, at the k-th place and at the
|
||||
* conditional's cond_k-th. Three lanes, two branches each. */
|
||||
static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u };
|
||||
const auto grid = [](int64_t i) { return std::round(hfill(290)(i) * 20.0f) / 20.0f; };
|
||||
Hand h("ties at the cut and in the guided order", "cfg_topk_sample", 0.0);
|
||||
h.dense(RAD_F32, { 6, 40 }, grid)
|
||||
.raw(RAD_U32, { 6 }, kSeeds)
|
||||
.idx({ 0, 17, 123456 })
|
||||
.dense(RAD_I32, { 6 }, zero, true)
|
||||
.pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pi("cond_k", 9).pf("cfg", 1.5)
|
||||
.pi("stream", 2).ps("dtype", "f32");
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
Hand g("one branch, every entry a candidate, a temperature", "cfg_topk_sample", 0.0);
|
||||
g.dense(RAD_F32, { 3, 40 }, grid)
|
||||
.raw(RAD_U32, { 6 }, kSeeds)
|
||||
.idx({ 4, 4, 9 })
|
||||
.dense(RAD_I32, { 3 }, zero, true)
|
||||
.pi("M", 3).pi("n_vocab", 40).pi("k", 40).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.6)
|
||||
.pi("stream", 0).ps("dtype", "f32");
|
||||
hs.push_back(std::move(g));
|
||||
}
|
||||
{
|
||||
/* A speech model's frame: three lanes with their own guidance, each lane's history of
|
||||
* earlier picks penalised (lane 2 at frame 0, its row cleared first), reserved ids
|
||||
* suppressed; the picks recorded in the history. */
|
||||
static const uint32_t kSeeds[6] = { 5u, 0u, 0xdeadbeefu, 7u, 1u, 1u };
|
||||
Hand h("guidance a lane, a history, reserved ids", "cfg_topk_sample", 0.0);
|
||||
h.dense(RAD_F32, { 6, 40 }, hfill(311, 3.0f))
|
||||
.raw(RAD_U32, { 6 }, kSeeds)
|
||||
.idx({ 4, 0, 9 })
|
||||
.dense(RAD_I32, { 6 }, zero, true)
|
||||
.dense(RAD_F32, { 3 }, [](int64_t i) { return 1.0f + 1.5f * (float)i; })
|
||||
.idx({ 1, 2, 3 })
|
||||
.dense(RAD_I32, { 4, 40 }, [](int64_t i) { return (float)((i * 7) % 3 == 0); }, true)
|
||||
.pi("M", 6).pi("n_vocab", 40).pi("k", 12).pi("rep", 2).pf("cfg", 1.0).pf("temp", 0.9)
|
||||
.pi("stream", 0).pi("sup_lo", 36).pi("sup_hi", 39).pf("penalty", 1.1)
|
||||
.ps("dtype", "f32");
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* One lane twice, in order: logits 4 - 0.5 j at temperature 0.01, so each entry takes its
|
||||
* best candidate; the first takes id 0, which the second sees penalised (4 / 1.5 falls
|
||||
* below id 1's 3.5). */
|
||||
static const uint32_t kSeeds2[4] = { 9u, 0u, 9u, 0u };
|
||||
Hand g("one lane twice: the second entry sees the first's pick", "cfg_topk_sample", 0.0);
|
||||
g.dense(RAD_F32, { 2, 40 }, [](int64_t i) { return 4.0f - 0.5f * (float)(i % 40); })
|
||||
.raw(RAD_U32, { 4 }, kSeeds2)
|
||||
.idx({ 3, 4 })
|
||||
.dense(RAD_I32, { 2 }, zero, true)
|
||||
.none()
|
||||
.idx({ 1, 1 })
|
||||
.dense(RAD_I32, { 2, 40 }, zero, true)
|
||||
.pi("M", 2).pi("n_vocab", 40).pi("k", 3).pi("rep", 1).pf("cfg", 1.0).pf("temp", 0.01)
|
||||
.pi("stream", 0).pf("penalty", 1.5).ps("dtype", "f32")
|
||||
.expect(3, { 0, 1 });
|
||||
hs.push_back(std::move(g));
|
||||
|
||||
/* Refusals before anything is written: a lane past the history, every id suppressed, and
|
||||
* the conditional's best ids all suppressed. */
|
||||
Hand r1("a lane past the history", "cfg_topk_sample", 0.0);
|
||||
r1.dense(RAD_F32, { 2, 40 }, hfill(312))
|
||||
.raw(RAD_U32, { 2 }, kSeeds)
|
||||
.idx({ 0 })
|
||||
.dense(RAD_I32, { 2 }, zero, true)
|
||||
.none()
|
||||
.idx({ 5 })
|
||||
.dense(RAD_I32, { 4, 40 }, zero, true)
|
||||
.pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pf("cfg", 2.0)
|
||||
.pi("stream", 0).pf("penalty", 1.1).ps("dtype", "f32")
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(r1));
|
||||
Hand r2("every id suppressed", "cfg_topk_sample", 0.0);
|
||||
r2.dense(RAD_F32, { 1, 40 }, hfill(313))
|
||||
.raw(RAD_U32, { 2 }, kSeeds)
|
||||
.idx({ 2 })
|
||||
.dense(RAD_I32, { 1 }, zero, true)
|
||||
.pi("M", 1).pi("n_vocab", 40).pi("k", 5).pi("rep", 1).pf("cfg", 1.0)
|
||||
.pi("stream", 0).pi("sup_lo", 0).pi("sup_hi", 40).ps("dtype", "f32")
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(r2));
|
||||
Hand r3("the conditional's best ids all suppressed", "cfg_topk_sample", 0.0);
|
||||
r3.dense(RAD_F32, { 2, 40 }, [](int64_t i) {
|
||||
const int64_t j = i % 40;
|
||||
return j >= 10 && j < 15 ? 5.0f : -0.01f * (float)j;
|
||||
})
|
||||
.raw(RAD_U32, { 2 }, kSeeds)
|
||||
.idx({ 2 })
|
||||
.dense(RAD_I32, { 2 }, zero, true)
|
||||
.pi("M", 2).pi("n_vocab", 40).pi("k", 5).pi("rep", 2).pi("cond_k", 5).pf("cfg", 1.5)
|
||||
.pi("stream", 0).pi("sup_lo", 10).pi("sup_hi", 20).ps("dtype", "f32")
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(r3));
|
||||
}
|
||||
{
|
||||
/* Four entries, codes a block of a wider plane (pitch 11, each lane's two branch columns):
|
||||
* entry 0 at frame 0 under skip 1 (moves past the prompt), entry 3 on an ended lane,
|
||||
* entries 1 and 2 stored. */
|
||||
Hand h("frame 0 under skip, an ended lane, codes a block", "frame_store", 0.0);
|
||||
h.view(RAD_I32, { 3, 8 }, { 11, 1 }, 33, [](int64_t i) { return (float)(100 + i); })
|
||||
.idx({ 2, 0, 3, 1 })
|
||||
.idx({ 0, 3, 2, 5 })
|
||||
.idx({ 1, -1, 4, 2 })
|
||||
.dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true)
|
||||
.pi("M", 4).pi("n_codes", 3).pi("stride", 6).pi("rep", 2).pi("skip", 1);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
/* Refusals before anything is written: a frame past its lane's row, a lane past the
|
||||
* status. */
|
||||
Hand r1("a frame past its lane's row", "frame_store", 0.0);
|
||||
r1.idx({ 1, 2, 3, 4, 5, 6 })
|
||||
.idx({ 0, 1 })
|
||||
.idx({ 7, 2 })
|
||||
.idx({ 0, 0 })
|
||||
.dense(RAD_I32, { 6, 6 }, [](int64_t) { return -7.0f; }, true)
|
||||
.pi("M", 2).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 1)
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(r1));
|
||||
Hand r2("a lane past the status", "frame_store", 0.0);
|
||||
r2.idx({ 1, 2, 3 })
|
||||
.idx({ 4 })
|
||||
.idx({ 2 })
|
||||
.idx({ 0, 0, 0, 0 })
|
||||
.dense(RAD_I32, { 12, 6 }, [](int64_t) { return -7.0f; }, true)
|
||||
.pi("M", 1).pi("n_codes", 3).pi("stride", 6).pi("rep", 1).pi("skip", 0)
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(r2));
|
||||
}
|
||||
{
|
||||
/* Lane 2 ends (its pick is `end`), lanes 0 and 1 continue, lane 3 is not in the frame. */
|
||||
Hand h("an ending lane among continuing ones", "end_status", 0.0);
|
||||
h.idx({ 5, 5, 3, 3, 5, 5 })
|
||||
.idx({ 2, 0, 1 })
|
||||
.idx({ 7, 7, 7, 7 }, true)
|
||||
.pi("M", 3).pi("end", 5).pi("rep", 2)
|
||||
.expect(2, { 3, -1, -1, 7 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool hand_cases(const Check& ck) {
|
||||
@@ -3022,8 +3891,11 @@ bool hand_cases(const Check& ck) {
|
||||
anchor_cases(hs);
|
||||
packed_cases(hs);
|
||||
gen_cases(hs);
|
||||
video_cases(hs);
|
||||
vsa_cases(hs);
|
||||
qsa_cases(hs);
|
||||
encoder_cases(hs);
|
||||
audio_cases(hs);
|
||||
Broken broken;
|
||||
planes_cases(ck, hs, broken);
|
||||
|
||||
|
||||
@@ -32,12 +32,15 @@ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) {
|
||||
|
||||
/* ------------------------------------------------------------------ add / mul */
|
||||
/* y = a op b over the output's extent. A one-row `b` is broadcast down the rows; nothing else
|
||||
* broadcasts, so a shape bug fails instead of producing plausible numbers. */
|
||||
* broadcasts, so a shape bug fails instead of producing plausible numbers. `add`'s `div` divides
|
||||
* the sum rounded through y's dtype, as libref rounds it. */
|
||||
template <bool MUL>
|
||||
static int elementwise2(const RadArgs* a) {
|
||||
if (!rad_args_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;
|
||||
@@ -57,6 +60,13 @@ static int elementwise2(const RadArgs* a) {
|
||||
vf_storeu(sy + i, MUL ? vf_mul(u, v) : vf_add(u, v));
|
||||
}
|
||||
for (; i < n; ++i) sy[i] = MUL ? x[i] * y[i] : x[i] + y[i];
|
||||
if (div != 1.0f) {
|
||||
/* sa is free once x is read: the sum's narrowing goes through it. */
|
||||
roundtrip(Y->dtype, sy, n, sa);
|
||||
const vf vd = vf_set1(div);
|
||||
for (i = 0; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_div(vf_loadu(sy + i), vd));
|
||||
for (; i < n; ++i) sy[i] /= div;
|
||||
}
|
||||
out_row(Y, rowoff(Y, r, n), n, sy);
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -371,22 +381,27 @@ AVX_KERNEL(conv2d_unfold) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv1d_dw */
|
||||
/* libref's causal depthwise convolution over time. The weight is transposed to [k][C] once per
|
||||
* launch so each tap is a vector FMA over the row. */
|
||||
/* libref's causal depthwise convolution over time, plus the optional bias. The weight is
|
||||
* transposed to [k][C] once per launch so each tap is a vector FMA over the row. */
|
||||
AVX_KERNEL(conv1d_dw) {
|
||||
if (!rad_args_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 = rad_arg_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);
|
||||
if (Mx <= 0 || My <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
|
||||
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
|
||||
|
||||
float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64);
|
||||
/* The taps tap-major, then the bias (zeros when unbound), once a launch. */
|
||||
float* wt = (float*)scratch_raw((size_t)((K + 1) * C) * sizeof(float) + 64);
|
||||
float* bias = wt + K * C;
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
for (int64_t j = 0; j < K; ++j) wt[j * C + c] = ldt(Wt, (c * K + j) * laststride(Wt));
|
||||
for (int64_t c = 0; c < C; ++c) bias[c] = B ? ldt(B, c) : 0.0f;
|
||||
|
||||
for (int64_t s = 0; s < S; ++s) {
|
||||
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
|
||||
@@ -409,6 +424,8 @@ AVX_KERNEL(conv1d_dw) {
|
||||
vf_storeu(acc + c, vf_fma(vf_loadu(xr + c), vf_loadu(wr + c), vf_loadu(acc + c)));
|
||||
for (; c < C; ++c) acc[c] += xr[c] * wr[c];
|
||||
}
|
||||
if (B)
|
||||
for (int64_t c = 0; c < C; ++c) acc[c] += bias[c];
|
||||
out_row(Y, rowoff(Y, t, C), C, acc);
|
||||
}
|
||||
}
|
||||
|
||||
+159
-18
@@ -1,18 +1,19 @@
|
||||
/* avx_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation") except
|
||||
* attn_prefix_self (avx_gen_attn.cpp): the diffusion transformer's adaptive norms and gated
|
||||
* residual, the timestep embedding, the per-image latent lanes and the flow-matching sampler, and
|
||||
* the image decoder's convolution, channel norm, resampling shortcuts and pixel output.
|
||||
* the image decoder's convolution, channel norm, resampling shortcuts and pixel output; and a video
|
||||
* generator's modulated RMS norms and sampler step ("Video generation").
|
||||
*
|
||||
* Each op rounds where libref/ref_gen.cpp rounds, which is where the upstream bf16 model stores a
|
||||
* tensor. Rows are computed in f32 scratch and every such rounding is a pass through the stored
|
||||
* dtype (`narrow_row`), so a fused kernel produces the bytes of the unfused chain.
|
||||
*
|
||||
* Bit-exact with libref, not only within tolerance: randn_lanes and flow_euler (a seed gives the
|
||||
* same picture on every plugin, and the sampler's state feeds every later step), gate_add,
|
||||
* chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed. Where libref
|
||||
* multiplies and then adds in two roundings, `keep` stops the compiler from fusing the pair (this
|
||||
* plugin is built with -ffp-contract=fast, libref without contraction). The norms reduce in a
|
||||
* different order from libref's and are held to the tolerance table.
|
||||
* Bit-exact with libref, not only within tolerance: randn_lanes, flow_euler and flow_x0_step (a
|
||||
* seed gives the same picture on every plugin, and the sampler's state feeds every later step),
|
||||
* gate_add, chan_affine, to_rgba8, s2d_avg_add, d2s_add, the lane copies and timestep_embed.
|
||||
* Where libref multiplies and then adds in two roundings, `keep` stops the compiler from fusing
|
||||
* the pair (this plugin is built with -ffp-contract=fast, libref without contraction). The norms
|
||||
* reduce in a different order from libref's and are held to the tolerance table.
|
||||
*
|
||||
* Per-entry tables (a sequence's modulation row, its tanh gate) are built once per launch before
|
||||
* the parallel region, in scratch_raw; the row loops use only scratch_f32 / _b / _c, so the
|
||||
@@ -107,6 +108,12 @@ inline void mul_rows(float* v, const float* w, int64_t n) {
|
||||
for (; i < n; ++i) v[i] *= w[i];
|
||||
}
|
||||
|
||||
inline void mul_into(float* out, const float* a, const float* b, int64_t n) {
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(a + i), vf_loadu(b + i)));
|
||||
for (; i < n; ++i) out[i] = a[i] * b[i];
|
||||
}
|
||||
|
||||
inline void add_rows(float* v, const float* w, int64_t n) {
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_add(vf_loadu(v + i), vf_loadu(w + i)));
|
||||
@@ -116,7 +123,8 @@ inline void add_rows(float* v, const float* w, int64_t n) {
|
||||
/* An entry's modulation row through `f`, rounded to `dt`, for every entry: [n_seq][n] floats in
|
||||
* scratch_raw. `s` is [n_seq, >= n] at its own row pitch (a column slice of the shared
|
||||
* modulation projection), read as libref reads it. `f` 0 is 1 + s, 1 is tanh(s), the exact libm
|
||||
* tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element. */
|
||||
* tanh: a gate is per entry and column, so n_seq * n tanh calls per launch, not one per element.
|
||||
* `f` 2 is s itself, unrounded. */
|
||||
float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int f) {
|
||||
float* t = (float*)scratch_raw((size_t)(n_seq * n + 16) * sizeof(float));
|
||||
const int64_t rs = row_stride(s, n), cs = laststride(s);
|
||||
@@ -124,7 +132,7 @@ float* entry_rows(const RadTensor* s, int64_t n_seq, int64_t n, uint32_t dt, int
|
||||
float* row = t + e * n;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float v = ldt(s, e * rs + i * cs);
|
||||
row[i] = narrow1(dt, f ? sc_tanh(v) : 1.0f + v);
|
||||
row[i] = f == 2 ? v : narrow1(dt, f ? sc_tanh(v) : 1.0f + v);
|
||||
}
|
||||
}
|
||||
return t;
|
||||
@@ -173,14 +181,15 @@ inline uint64_t seed_of(const RadTensor* seed, int64_t e) {
|
||||
((uint64_t)(uint32_t)ldi(seed, offlin(seed, 2 * e + 1)) << 32);
|
||||
}
|
||||
|
||||
/* The bf16 values of a space-separated list (libref's parse_list): up to `cap` into out. */
|
||||
int64_t parse_list(const char* s, float* out, int64_t cap) {
|
||||
/* The bf16 values of a space-separated list (libref's parse_list), or with `bf16` false its f32
|
||||
* values: up to `cap` into out. */
|
||||
int64_t parse_list(const char* s, float* out, int64_t cap, bool bf16 = true) {
|
||||
int64_t k = 0;
|
||||
while (s && *s) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s, &end);
|
||||
if (end == s) break;
|
||||
if (k < cap) out[k] = narrow1(RAD_BF16, (float)v);
|
||||
if (k < cap) out[k] = bf16 ? narrow1(RAD_BF16, (float)v) : (float)v;
|
||||
++k;
|
||||
s = end;
|
||||
}
|
||||
@@ -217,15 +226,19 @@ AVX_KERNEL(ln_mod) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gate_add */
|
||||
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype. */
|
||||
/* x = bf16( x + bf16( bf16(tanh(g[seq])) * y ) ), the roundings in x's dtype; with `act` none the
|
||||
* gate is g itself, unrounded. */
|
||||
AVX_KERNEL(gate_add) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *Yv = &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(Yv, n), n_seq = numel(cu) - 1;
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const float* gate = entry_rows(G, n_seq, n, X->dtype, 1);
|
||||
const float* gate = entry_rows(G, n_seq, n, X->dtype, act ? 2 : 1);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
@@ -308,6 +321,89 @@ AVX_KERNEL(ln_mod_quant_fp8) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rms_mod / rms_mod_quant_fp8 */
|
||||
/* Both forms: with `gated` the branch added through the gate row (no tanh) and the residual stored
|
||||
* in x's dtype; then n1 = rd(x rsqrt(mean(x^2) + eps)), n2 = rd(n1 w), m = rd(n2 rd(1 + scale)),
|
||||
* z = rd(m + shift), rd the norm chain's dtype (z's for rms_mod, bf16 for the quantised form,
|
||||
* libref's rule). The sum of squares is the vector reduction, held to the tolerance table; every
|
||||
* rounding is a pass through the stored dtype, so the rest is libref's arithmetic. The per-entry
|
||||
* rows (1 + scale rounded, the shift and the gate) and the gain are built once a launch. */
|
||||
static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
if (a->n_t < (quant ? 9 : 7)) return RAD_E_INVAL;
|
||||
const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *W = &a->t[3];
|
||||
const RadTensor *cu = &a->t[4], *X = &a->t[5];
|
||||
const RadTensor *Q = quant ? &a->t[6] : nullptr, *SC = quant ? &a->t[7] : nullptr;
|
||||
const RadTensor* Z = quant ? rad_arg_in(a, 8) : &a->t[6];
|
||||
const int64_t n = p_int(a, "n", 0), grp = quant ? p_int(a, "group", 0) : 1;
|
||||
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 && (!Yv || !G))) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(quant ? Q : Z, n), n_seq = numel(cu) - 1, ngrp = n / grp;
|
||||
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(Yv, n) < rows || numel(G) < n_seq * n)) return RAD_E_SHAPE;
|
||||
if (quant && (numel(SC) < rows * ngrp || (Z && rows_of(Z, n) < rows))) return RAD_E_SHAPE;
|
||||
const uint32_t dt = quant ? (uint32_t)RAD_BF16 : Z->dtype;
|
||||
/* The tables from one scratch_raw call, [gain | shift | gate] a sequence and the weight row:
|
||||
* a second call may reallocate the first. */
|
||||
const int64_t tw = gated ? 3 * n : 2 * n;
|
||||
float* tabs = (float*)scratch_raw((size_t)(n_seq * tw + n + 32) * sizeof(float));
|
||||
{
|
||||
const int64_t s_rs = row_stride(S, 2 * n), s_cs = laststride(S);
|
||||
const int64_t g_rs = gated ? row_stride(G, n) : 0, g_cs = gated ? laststride(G) : 0;
|
||||
for (int64_t e = 0; e < n_seq; ++e)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float* row = tabs + e * tw;
|
||||
row[i] = narrow1(dt, 1.0f + ldt(S, e * s_rs + (n + i) * s_cs));
|
||||
row[n + i] = ldt(S, e * s_rs + i * s_cs);
|
||||
if (gated) row[2 * n + i] = ldt(G, e * g_rs + i * g_cs);
|
||||
}
|
||||
for (int64_t i = 0; i < n; ++i) tabs[n_seq * tw + i] = ldt(W, i * laststride(W));
|
||||
}
|
||||
const float* wrow = tabs + n_seq * tw;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(5 * n + 80));
|
||||
float *xs = buf, *v = buf + n + 16, *o = v + n + 16, *codes = o + n + 16;
|
||||
float* tmp = codes + n + 16;
|
||||
const float* ent = tabs + seq_of(cu, n_seq, r) * tw;
|
||||
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
|
||||
if (gated) {
|
||||
const float* yv = in_row(Yv, rowoff(Yv, r, n), n, codes);
|
||||
mul_into(v, ent + 2 * n, yv, n);
|
||||
narrow_row(X->dtype, v, n, tmp);
|
||||
add_rows(v, xv, n);
|
||||
narrow_row(X->dtype, v, n, tmp);
|
||||
out_row(X, rowoff(X, r, n), n, v);
|
||||
} else {
|
||||
std::memcpy(v, xv, (size_t)n * sizeof(float));
|
||||
}
|
||||
const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps);
|
||||
const vf vr = vf_set1(rs);
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) vf_storeu(o + i, vf_mul(vf_loadu(v + i), vr));
|
||||
for (; i < n; ++i) o[i] = v[i] * rs;
|
||||
narrow_row(dt, o, n, tmp);
|
||||
mul_rows(o, wrow, n);
|
||||
narrow_row(dt, o, n, tmp);
|
||||
mul_rows(o, ent, n);
|
||||
narrow_row(dt, o, n, tmp);
|
||||
add_rows(o, ent + n, n);
|
||||
if (!quant) {
|
||||
out_row(Z, rowoff(Z, r, n), n, o);
|
||||
continue;
|
||||
}
|
||||
narrow_row(dt, o, n, tmp);
|
||||
fp8_emit(o, codes, n, grp, Q, SC, Z, r);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(rms_mod) { return rms_mod_run(a, false); }
|
||||
AVX_KERNEL(rms_mod_quant_fp8) { return rms_mod_run(a, true); }
|
||||
|
||||
/* ------------------------------------------------------------------ timestep_embed */
|
||||
/* y[m] = [cos(t' f_0) .. cos(t' f_{h-1}) | sin(t' f_0) .. sin(t' f_{h-1})] with libref's libm
|
||||
* calls: a pass embeds one row per entry, so this is a few thousand transcendentals. */
|
||||
@@ -559,20 +655,60 @@ AVX_KERNEL(flow_euler) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ flow_x0_step */
|
||||
/* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and
|
||||
* r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own
|
||||
* rounding. */
|
||||
AVX_KERNEL(flow_x0_step) {
|
||||
if (!rad_args_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;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < rows; ++k) {
|
||||
float* buf = scratch_f32((size_t)(3 * n + 48));
|
||||
float *vs = buf, *xs = buf + n + 16, *o = xs + n + 16;
|
||||
const float* v = in_row(V, rowoff(V, k, n), n, vs);
|
||||
const float* x = in_row(X, rowoff(X, k, n), n, xs);
|
||||
const vf vst = vf_set1(st), vr = vf_set1(r), vo = vf_set1(omr);
|
||||
int64_t c = 0;
|
||||
for (; c + VF_N <= n; c += VF_N) {
|
||||
const vf xv = vf_loadu(x + c);
|
||||
const vf d = vf_add(xv, keep(vf_mul(vst, vf_loadu(v + c))));
|
||||
vf_storeu(o + c, vf_add(keep(vf_mul(vr, xv)), keep(vf_mul(vo, d))));
|
||||
}
|
||||
for (; c < n; ++c) {
|
||||
const float d = x[c] + keep(st * v[c]);
|
||||
o[c] = keep(r * x[c]) + keep(omr * d);
|
||||
}
|
||||
out_row(X, rowoff(X, k, n), n, o);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chan_affine */
|
||||
/* A per-channel affine from two lists of n bf16 values: `fma` is bf16(bf16(x * mul) + add), `inv`
|
||||
* is bf16(bf16(x - add) / mul), the inner rounding in y's dtype. */
|
||||
AVX_KERNEL(chan_affine) {
|
||||
if (!rad_args_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;
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", "");
|
||||
/* Each number takes at least two characters but the last, so this bounds the count. */
|
||||
const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2);
|
||||
float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float));
|
||||
float *mul = lists, *add = lists + cap;
|
||||
if (parse_list(ms, mul, cap) != n || parse_list(as, add, cap) != n) return RAD_E_SHAPE;
|
||||
if (parse_list(ms, mul, cap, rnd) != n || parse_list(as, add, cap, 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;
|
||||
@@ -589,16 +725,21 @@ AVX_KERNEL(chan_affine) {
|
||||
for (; c + VF_N <= n; c += VF_N)
|
||||
vf_storeu(t + c, vf_sub(vf_loadu(x + c), vf_loadu(add + c)));
|
||||
for (; c < n; ++c) t[c] = x[c] - add[c];
|
||||
narrow_row(Y->dtype, t, n, tmp);
|
||||
if (rnd) narrow_row(Y->dtype, t, n, tmp);
|
||||
for (c = 0; c + VF_N <= n; c += VF_N)
|
||||
vf_storeu(t + c, vf_div(vf_loadu(t + c), vf_loadu(mul + c)));
|
||||
for (; c < n; ++c) t[c] /= mul[c];
|
||||
} else {
|
||||
} else if (rnd) {
|
||||
for (; c + VF_N <= n; c += VF_N)
|
||||
vf_storeu(t + c, vf_mul(vf_loadu(x + c), vf_loadu(mul + c)));
|
||||
for (; c < n; ++c) t[c] = x[c] * mul[c];
|
||||
narrow_row(Y->dtype, t, n, tmp);
|
||||
add_rows(t, add, n);
|
||||
} else {
|
||||
for (; c + VF_N <= n; c += VF_N)
|
||||
vf_storeu(t + c, vf_add(keep(vf_mul(vf_loadu(x + c), vf_loadu(mul + c))),
|
||||
vf_loadu(add + c)));
|
||||
for (; c < n; ++c) t[c] = keep(x[c] * mul[c]) + add[c];
|
||||
}
|
||||
out_row(Y, rowoff(Y, r, n), n, t);
|
||||
}
|
||||
|
||||
+102
-12
@@ -52,9 +52,18 @@ struct Geo {
|
||||
int causal;
|
||||
int64_t hd, gqa, kvh, qh, n_seq, bs, max_blocks, bt_rs, bt_cs;
|
||||
int64_t q_rs, k_rs, v_rs, o_rs, k8_rs, ks_rs, sb, sh, so;
|
||||
int64_t rows_total; /* the fp8 P.V form's rows */
|
||||
float scale;
|
||||
};
|
||||
|
||||
/* f32 to the nearest E4M3 and back. */
|
||||
inline float e4m3_round(float x) {
|
||||
const uint8_t c = rad_f32_to_fp8e4m3(x);
|
||||
float y;
|
||||
cvt_fp8e4m3_to_f32(&c, &y, 1);
|
||||
return y;
|
||||
}
|
||||
|
||||
inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); }
|
||||
|
||||
/* One (entry, kv head)'s key sequence: P prefix keys then the entry's own rows from b0. */
|
||||
@@ -532,12 +541,77 @@ PS_BF16 void task_bf16(const Geo& g, const Seq& q, const uint8_t* pack, int64_t
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ attn_prefix_self, fp8 P.V */
|
||||
/* libref's fp8 P.V form, prefix-free, row by row: every score (bf16 or int8 form, libref's
|
||||
* order), the max, then p = exp(s - max) in f64 rounded to f32, w = e4m3(448 p), and
|
||||
* o = (sum w v) v_scale / (448 sum p), sums in key order. Two passes, as libref's, because the
|
||||
* weights are rounded against the row's final max. */
|
||||
static int ps_pv8(const Geo& g, const RadTensor* vsc) {
|
||||
const int64_t hd = g.hd, qh = g.qh;
|
||||
AVX_PARALLEL_FOR_IF(g.rows_total * qh * hd >= AVX_PAR_MIN)
|
||||
for (int64_t idx = 0; idx < g.rows_total * qh; ++idx) {
|
||||
const int64_t h = idx % qh, r = cu_at(g.cu, 0) + idx / qh, kh = h / g.gqa;
|
||||
int64_t s = 0;
|
||||
while (s + 1 < g.n_seq && r >= cu_at(g.cu, s + 1)) ++s;
|
||||
const int64_t b0 = cu_at(g.cu, s), b1 = cu_at(g.cu, s + 1), i = r - b0;
|
||||
const int64_t nk = g.causal ? i + 1 : b1 - b0;
|
||||
float* qf = scratch_f32((size_t)(3 * hd + nk));
|
||||
float* kf = qf + hd;
|
||||
float* acc = kf + hd;
|
||||
float* sc = acc + hd;
|
||||
for (int64_t d = 0; d < hd; ++d) qf[d] = ldt(g.q, r * g.q_rs + h * hd + d);
|
||||
float sq = 1.0f;
|
||||
if (g.i8) {
|
||||
float am = 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d) am = std::max(am, std::fabs(qf[d]));
|
||||
sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
|
||||
const float inv = 1.0f / sq;
|
||||
for (int64_t d = 0; d < hd; ++d)
|
||||
qf[d] = std::rint(std::min(std::max(qf[d] * inv, -127.0f), 127.0f));
|
||||
}
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = 0; j < nk; ++j) {
|
||||
const int64_t row = b0 + j;
|
||||
float dot = 0.0f;
|
||||
if (g.i8) {
|
||||
for (int64_t d = 0; d < hd; ++d) kf[d] = ldt(g.k8, row * g.k8_rs + kh * hd + d);
|
||||
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * kf[d];
|
||||
dot = dot * sq * ldt(g.ks, row * g.ks_rs + kh) * g.scale;
|
||||
} else {
|
||||
const int64_t kb = row * g.k_rs + kh * hd;
|
||||
for (int64_t d = 0; d < hd; ++d) dot += qf[d] * ldt(g.k, kb + d);
|
||||
dot *= g.scale;
|
||||
}
|
||||
sc[j] = dot;
|
||||
mx = std::max(mx, dot);
|
||||
}
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f;
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = 0; j < nk; ++j) {
|
||||
const float p = (float)std::exp((double)(sc[j] - mx));
|
||||
sum += p;
|
||||
const float w = e4m3_round(448.0f * p);
|
||||
const int64_t vb = (b0 + j) * g.v_rs + kh * hd;
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] += w * ldt(g.v, vb + d);
|
||||
}
|
||||
const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d)
|
||||
stt(g.o, r * g.o_rs + h * hd + d, acc[d] * ldt(vsc, offlin(vsc, kh * hd + d)) * inv8);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_prefix_self */
|
||||
AVX_KERNEL(attn_prefix_self) {
|
||||
if (a->n_t < 12) return RAD_E_INVAL;
|
||||
Geo g{};
|
||||
g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.kv = &a->t[3];
|
||||
g.bt = &a->t[4]; g.su = &a->t[5]; g.cu = &a->t[6]; g.o = &a->t[11];
|
||||
g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.cu = &a->t[6]; g.o = &a->t[11];
|
||||
/* The paged prefix, all three operands or none (every prefix empty). */
|
||||
g.kv = rad_arg_in(a, 3);
|
||||
g.bt = rad_arg_in(a, 4);
|
||||
g.su = rad_arg_in(a, 5);
|
||||
if ((g.kv == nullptr) != (g.bt == nullptr) || (g.kv == nullptr) != (g.su == nullptr))
|
||||
return RAD_E_INVAL;
|
||||
g.kdes = rad_arg_in(a, 7);
|
||||
g.vdes = rad_arg_in(a, 8);
|
||||
g.k8 = rad_arg_in(a, 9);
|
||||
@@ -548,19 +622,22 @@ AVX_KERNEL(attn_prefix_self) {
|
||||
g.hd = p_int(a, "head_dim", 0);
|
||||
g.gqa = p_int(a, "gqa", 1);
|
||||
g.causal = (int)p_int(a, "causal", 0);
|
||||
g.bs = g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0);
|
||||
g.bs = !g.kv ? 1 : g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0);
|
||||
if (g.hd <= 0 || g.gqa <= 0 || g.bs <= 0) return RAD_E_SHAPE;
|
||||
if (g.hd > PS_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
g.kvh = g.kv->rank == 4 ? g.kv->shape[1] : 0;
|
||||
/* Without a cache the key heads are the own keys' width over head_dim. */
|
||||
g.kvh = g.kv ? (g.kv->rank == 4 ? g.kv->shape[1] : 0)
|
||||
: g.k->rank >= 3 ? g.k->shape[g.k->rank - 2]
|
||||
: g.k->rank == 2 ? g.k->shape[1] / g.hd : 0;
|
||||
if (g.kvh <= 0) return RAD_E_SHAPE;
|
||||
g.qh = g.kvh * g.gqa;
|
||||
g.n_seq = numel(g.cu) - 1;
|
||||
if (g.n_seq <= 0 || numel(g.su) < g.n_seq) return RAD_E_SHAPE;
|
||||
if (g.n_seq <= 0 || (g.su && numel(g.su) < g.n_seq)) return RAD_E_SHAPE;
|
||||
if (cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0) <= 0) return RAD_E_SHAPE;
|
||||
g.max_blocks = g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq;
|
||||
g.bt_rs = g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks;
|
||||
g.bt_cs = g.bt->rank >= 2 ? g.bt->stride[1] : 1;
|
||||
for (int64_t s = 0; s < g.n_seq; ++s)
|
||||
g.max_blocks = !g.bt ? 0 : g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq;
|
||||
g.bt_rs = g.bt && g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks;
|
||||
g.bt_cs = g.bt && g.bt->rank >= 2 ? g.bt->stride[1] : 1;
|
||||
for (int64_t s = 0; g.su && s < g.n_seq; ++s)
|
||||
if (ldi(g.su, offlin(g.su, s)) > g.max_blocks * g.bs) return RAD_E_SHAPE;
|
||||
g.q_rs = row_stride(g.q, g.qh * g.hd);
|
||||
g.k_rs = row_stride(g.k, g.kvh * g.hd);
|
||||
@@ -568,15 +645,28 @@ AVX_KERNEL(attn_prefix_self) {
|
||||
g.o_rs = row_stride(g.o, g.qh * g.hd);
|
||||
g.k8_rs = g.i8 ? row_stride(g.k8, g.kvh * g.hd) : 0;
|
||||
g.ks_rs = g.i8 ? row_stride(g.ks, g.kvh) : 0;
|
||||
g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2];
|
||||
if (g.kv) { g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2]; }
|
||||
g.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)g.hd));
|
||||
/* The fp8 P.V form (libref's ref_attn_prefix_self): prefix-free, its own two-pass loop. */
|
||||
{
|
||||
const RadTensor* vsc = a->n_t > 12 ? rad_arg_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) {
|
||||
if (g.kv || g.kdes || g.vdes) return RAD_E_UNSUPPORTED;
|
||||
g.rows_total = cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0);
|
||||
return ps_pv8(g, vsc);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- which form, and each (entry, kv head)'s key sequence */
|
||||
[[maybe_unused]] bool bf16 = false;
|
||||
#if AVX_LEVEL == 3
|
||||
static const bool have_bf16 = __builtin_cpu_supports("avx512bf16");
|
||||
bf16 = have_bf16 && g.hd % 64 == 0 && g.gqa <= 16 && !g.kdes && !g.vdes &&
|
||||
g.q->dtype == RAD_BF16 && g.kv->dtype == RAD_BF16 && g.v->dtype == RAD_BF16 &&
|
||||
g.q->dtype == RAD_BF16 && (!g.kv || g.kv->dtype == RAD_BF16) &&
|
||||
g.v->dtype == RAD_BF16 &&
|
||||
(g.i8 || g.k->dtype == RAD_BF16);
|
||||
#endif
|
||||
const size_t tile_bytes =
|
||||
@@ -594,7 +684,7 @@ AVX_KERNEL(attn_prefix_self) {
|
||||
for (int64_t s = 0; s < g.n_seq; ++s) {
|
||||
Seq q{};
|
||||
q.s = s; q.kh = kh;
|
||||
q.P = ldi(g.su, offlin(g.su, s));
|
||||
q.P = g.su ? ldi(g.su, offlin(g.su, s)) : 0;
|
||||
q.b0 = cu_at(g.cu, s);
|
||||
q.len = std::max<int64_t>(0, cu_at(g.cu, s + 1) - q.b0);
|
||||
/* A negative prefix count makes key j own row b0 + j - P, as libref indexes it. */
|
||||
|
||||
+11
-1
@@ -83,7 +83,7 @@ int avx_par_force(int threads);
|
||||
/* ---- quantisation and rotation */ \
|
||||
X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \
|
||||
X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \
|
||||
X(dequant) \
|
||||
X(dequant) X(quant_cols_fp8) \
|
||||
X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \
|
||||
/* ---- gemm and the vocabulary edges */ \
|
||||
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
|
||||
@@ -108,6 +108,16 @@ int avx_par_force(int threads);
|
||||
X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \
|
||||
X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \
|
||||
X(scatter_add_rows) X(attn_prefix_self) \
|
||||
/* ---- video generation */ \
|
||||
X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \
|
||||
X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \
|
||||
X(attn_vsa) \
|
||||
/* ---- audio generation */ \
|
||||
X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \
|
||||
X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \
|
||||
X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \
|
||||
X(win_finish) X(chan_split) X(interleave2) X(iota) \
|
||||
X(cu_repeat) X(snake_aa) \
|
||||
/* ---- sampling, and the drafter's token walk */ \
|
||||
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
|
||||
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
|
||||
|
||||
+8
-10
@@ -1,19 +1,17 @@
|
||||
/* avx_lora.cpp -- runtime LoRA's two halves on the host: lora_shrink and lora_expand.
|
||||
*
|
||||
* libref/ref_lora.cpp is the DEFINITION and says what the ops are; this is the same arithmetic over
|
||||
* the same bytes with the dot products vectorised, which is the only difference and a tolerance
|
||||
* question (avx_check). What is EXACT, and has to be, is which rows are touched: a row whose slot
|
||||
* is outside [0, S) is a base row, its `t` row is never written and its `y` row is neither read nor
|
||||
* written -- not a store of what was read, no store -- because the engine promises that a base row
|
||||
* is bit for bit what the GEMM wrote.
|
||||
* libref/ref_lora.cpp defines the ops; this is the same arithmetic over the same bytes with the dot
|
||||
* products vectorised, a tolerance question (avx_check). Which rows are touched is exact: a row
|
||||
* whose slot is outside [0, S) is a base row, its `t` row is never written and its `y` row is
|
||||
* neither read nor stored, so it stays bit for bit what the GEMM wrote.
|
||||
*
|
||||
* x(m, k) is gemm_nt_q's activation value: the code times its group's scale, read through the same
|
||||
* scale-stream rule as avx_gemm.cpp (copied below for the reason avx_moe.cpp gives for its copy).
|
||||
*
|
||||
* THREADING. A row's dots never split, so its bytes do not depend on the team or on M. A prefill
|
||||
* has rows to spare and goes wide over them; a decode step has one row and R columns, so there the
|
||||
* row's activation is decoded once on the calling thread and the team goes wide over the columns.
|
||||
* Either way each output element is one dotf() over the same two f32 rows.
|
||||
* Threading: a row's dots never split, so its bytes do not depend on the team or on M. A prefill
|
||||
* goes wide over rows; a decode step has one row and R columns, so the row is decoded once on the
|
||||
* calling thread and the team goes wide over the columns. Either way each output element is one
|
||||
* dotf() over the same two f32 rows.
|
||||
*/
|
||||
#include "avx_common.h"
|
||||
#include "avx_vec.h"
|
||||
|
||||
@@ -34,6 +34,8 @@
|
||||
using namespace avx;
|
||||
|
||||
#include "avx_had.h"
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
/* Codes are stored with out_row; for RAD_I8 that is the vectorised clamp + cvtps/packs path
|
||||
* (avx_vec.h), bit-exact with libref's nearbyintf-and-clamp. */
|
||||
@@ -393,6 +395,43 @@ AVX_KERNEL(quant_act_fp8) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- quant_cols_fp8 */
|
||||
/* libref's ref_quant_cols_fp8: one scale per column over all rows (amax * (1/448), 1 for an
|
||||
* all-zero column), codes clamp(x * (1/scale), +-448) to nearest even. Two passes over the rows,
|
||||
* each row's columns at once: the column maxima, then the codes. */
|
||||
AVX_KERNEL(quant_cols_fp8) {
|
||||
if (!rad_args_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;
|
||||
std::vector<float> amax((size_t)n, 0.0f), inv((size_t)n);
|
||||
{
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
amax[(size_t)c] = std::max(amax[(size_t)c], std::fabs(v[c]));
|
||||
}
|
||||
}
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float sc = amax[(size_t)c] > 0.0f ? amax[(size_t)c] * (1.0f / 448.0f) : 1.0f;
|
||||
inv[(size_t)c] = 1.0f / sc;
|
||||
stt(s, c * laststride(s), sc);
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
float* out = scratch_f32_b((size_t)n);
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
out[c] = std::min(std::max(v[c] * inv[(size_t)c], -448.0f), 448.0f);
|
||||
out_row(y, rowoff(y, r, n), n, out);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
|
||||
/* RMS norm, optional residual add, and quant_act_fp8 in one pass.
|
||||
*
|
||||
|
||||
+268
-18
@@ -111,6 +111,8 @@ 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") };
|
||||
/* `add`'s `div` divides the rounded sum (libref's pAdd). */
|
||||
static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") };
|
||||
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
|
||||
/* `cap` is required (as in libref's pMnCap). */
|
||||
static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") };
|
||||
@@ -140,7 +142,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") };
|
||||
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oRelSin[] = { OUT("y") };
|
||||
@@ -167,6 +170,8 @@ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group
|
||||
static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") };
|
||||
static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") };
|
||||
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, as libref declares it: the tables come from the "givens" encoding
|
||||
* (abi/rad_encoding.h) and are weight operands, placed with the weight they belong to. */
|
||||
static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
|
||||
@@ -252,7 +257,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") };
|
||||
|
||||
@@ -267,7 +273,9 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_
|
||||
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") };
|
||||
|
||||
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
|
||||
@@ -316,8 +324,9 @@ static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_I
|
||||
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, and an absent gain is a unit one (libref). */
|
||||
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"),
|
||||
@@ -459,11 +468,23 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
|
||||
/* ---- image generation --------------------------------------------------------------------- */
|
||||
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") };
|
||||
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") };
|
||||
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") };
|
||||
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") };
|
||||
@@ -478,7 +499,7 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma
|
||||
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
|
||||
INOUT("state"), INOUT_O("preview") };
|
||||
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") };
|
||||
@@ -490,11 +511,107 @@ 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 (avx_video.cpp), as libref declares it ------------------------------ */
|
||||
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") };
|
||||
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 (avx_vsa.cpp), as libref declares it ------------------------- */
|
||||
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 (avx_audio.cpp), as libref declares it ------------------------------ */
|
||||
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") };
|
||||
|
||||
/* ---- vocabulary edges --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
@@ -579,8 +696,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
"x += a side x side position table resampled bilinearly to the row's grid." },
|
||||
{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed),
|
||||
"x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." },
|
||||
{ "add", ARR(pMnD), ARR(oBinary),
|
||||
"y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows." },
|
||||
{ "add", ARR(pAdd), ARR(oBinary),
|
||||
"y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows. With "
|
||||
"`div`, y = rd(rd(a + b) / div), bit for bit libref's." },
|
||||
{ "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same broadcast rule as `add`." },
|
||||
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
|
||||
"y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." },
|
||||
@@ -593,7 +711,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "conv2d", ARR(pConv2d), ARR(oConv2d),
|
||||
"segment-wise 2-D convolution over (time, width), channels innermost, optional row mask." },
|
||||
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
|
||||
"segment-wise causal depthwise convolution over time." },
|
||||
"segment-wise causal depthwise convolution over time, an optional bias." },
|
||||
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." },
|
||||
{ "conv2d_unfold", ARR(pConv2dUnfold), ARR(oConv2dUnfold),
|
||||
"a convolution's receptive fields as rows, columns in the weight's order." },
|
||||
@@ -634,6 +752,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
|
||||
"symmetric int8, one f32 scale per `group` contiguous elements, row-major." },
|
||||
{ "quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "symmetric block-scaled E4M3 quantiser." },
|
||||
{ "quant_cols_fp8", ARR(pQuantCols), ARR(oQuantCols), "E4M3 with one scale per column." },
|
||||
{ "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8),
|
||||
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: "
|
||||
"the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." },
|
||||
@@ -682,7 +801,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
|
||||
"paged causal / sliding-window attention, any query length, online-softmax so one pass over the "
|
||||
"cache suffices." },
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." },
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
|
||||
"dense varlen attention over cu_seqlens; a non-causal window may reach further right "
|
||||
"(`window_right`)." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
@@ -749,8 +870,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "ln_mod", ARR(pLnMod), ARR(oLnMod),
|
||||
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's "
|
||||
"modulation row of `s` ([n_seq, >= n] at its own pitch)." },
|
||||
{ "gate_add", ARR(pMnD), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), bit for bit libref's." },
|
||||
{ "gate_add", ARR(pGateAdd), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), or with `act` none the gate g itself, bit for bit "
|
||||
"libref's." },
|
||||
{ "timestep_embed", ARR(pTimestep), ARR(oTimestep),
|
||||
"the sinusoidal timestep embedding [cos | sin], libref's libm calls; `round` 1 takes t through "
|
||||
"bf16 at scale and back first." },
|
||||
@@ -767,7 +889,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the "
|
||||
"repaint's kept region; libref's roundings bit for bit." },
|
||||
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
|
||||
"a per-channel affine from two lists of n bf16 values, `fma` or `inv`." },
|
||||
"a per-channel affine from two lists of n bf16 values, `fma` or `inv`; `round` 0 keeps the "
|
||||
"lists and the arithmetic in f32, rounded once." },
|
||||
{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc),
|
||||
"an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the "
|
||||
"input upsampled nearest-neighbour, `pad` same or down." },
|
||||
@@ -786,6 +909,73 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
|
||||
"attention over `seqused[s]` prefix positions in the paged cache and the step's own rows, "
|
||||
"flash-attention tiles; `qk` \"i8\" is the int8 score form (docs/OPS.md)." },
|
||||
{ "rms_mod", ARR(pRmsMod), ARR(oRmsMod),
|
||||
"the gated residual (no tanh), then an RMS norm with a gain times bf16(1 + scale row) plus the "
|
||||
"shift row, `s` holding [shift | scale]; libref's roundings." },
|
||||
{ "rms_mod_quant_fp8", ARR(pRmsModQ), ARR(oRmsModQ),
|
||||
"rms_mod with its norm chain in bf16, then the E4M3 codes and scales of that row." },
|
||||
{ "flow_x0_step", ARR(pMnD), ARR(oFlowX0),
|
||||
"x = r x + (1 - r)(x + (1 - t) v), r = sigma_next / sigma, each step one f32 rounding, bit for "
|
||||
"bit libref's." },
|
||||
{ "patch_unfold", ARR(pPatchUnfold), ARR(oPatchUnfold),
|
||||
"patch rows to denormalised voxel rows, f32(f32(x * mul) + add), bit for bit libref's." },
|
||||
{ "vtile_gather", ARR(pVtileGather), ARR(oVtileGather),
|
||||
"a video decoder's tiles out of the latent's voxel rows, then the register rows and zeros." },
|
||||
{ "vtile_stitch", ARR(pVtileStitch), ARR(oVtileStitch),
|
||||
"decoded tiles blended into frames, the chunk overlap blended and kept, RGB bytes out; bit for "
|
||||
"bit libref's." },
|
||||
{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3),
|
||||
"a video decoder's rotary positions over its tiles, [3, >= M] at the operand's row pitch, bit "
|
||||
"for bit libref's." },
|
||||
{ "vsa_select", ARR(pVsa), ARR(oVsaSelect),
|
||||
"video sparse attention's tile selection over libref's tiles: the k video tiles of largest "
|
||||
"pooled score per video query tile, ascending, bit for bit libref's; with `coarse`, the softmax "
|
||||
"over every tile's score times the tiles' means of v." },
|
||||
{ "attn_vsa", ARR(pAttnVsa), ARR(oAttnVsa),
|
||||
"video sparse attention over libref's tiles: prefix queries dense, video queries the prefix "
|
||||
"and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded "
|
||||
"to its dtype." },
|
||||
{ "conv1d", ARR(pConv1d), ARR(oConv1d),
|
||||
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's "
|
||||
"[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside "
|
||||
"each sequence; `res` added after the bias, then `act` none, tanh or clamp. GEMMs over bands "
|
||||
"of patch rows." },
|
||||
{ "conv_t1d", ARR(pConvT1d), ARR(oConvT1d),
|
||||
"a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` "
|
||||
"((k - stride) / 2, or 0 the causal form), each sequence growing `stride` times; one GEMM a "
|
||||
"phase." },
|
||||
{ "snake", ARR(pSnake), ARR(oSnake),
|
||||
"x + sin(alpha x)^2 / (alpha + 1e-9) per channel, or SnakeBeta's x + sin(alpha x)^2 / "
|
||||
"(beta + 1e-9) with `beta`, both read as logarithms with `log` 1; a polynomial sine." },
|
||||
{ "snake_aa", ARR(pSnakeAa), ARR(oSnakeAa),
|
||||
"BigVGAN's alias-free SnakeBeta: replicate-padded upsampling by `f_up`, SnakeBeta, "
|
||||
"replicate-padded filtering by `f_down` at stride `ratio`; a polynomial sine." },
|
||||
{ "cfg_topk_sample", ARR(pCfgTopk), ARR(oCfgTopk),
|
||||
"one guided top-k pick a lane by inverse CDF over rad_philox_uniform_s, with a suppressed id "
|
||||
"range, a repetition penalty over each lane's history and per-lane guidance; bit for bit "
|
||||
"libref's." },
|
||||
{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed),
|
||||
"a frame's embedding from code-major residual codes, libref's roundings (`round` 1: one)." },
|
||||
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
|
||||
"a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." },
|
||||
{ "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, code-major rows over the lane's frames." },
|
||||
{ "resample_nearest", ARR(pMnD), ARR(oUnary),
|
||||
"rows resampled nearest-neighbour, the row counts read off the operands." },
|
||||
{ "fourier_embed", ARR(pFourier), ARR(oFourier),
|
||||
"[cos(2 pi t w) | sin(2 pi t w)], libref's libm calls and roundings." },
|
||||
{ "win_input", ARR(pWinInput), ARR(oWinInput),
|
||||
"a denoiser's input [lat | zeros | cond] from each window entry's lane." },
|
||||
{ "win_prep", ARR(pWinPrep), ARR(oWinPrep),
|
||||
"a window step's noise and overlap binding, bit for bit libref's." },
|
||||
{ "win_finish", ARR(pWinFinish), ARR(oWinFinish),
|
||||
"a window's end and the overlap it hands on." },
|
||||
{ "chan_split", ARR(pChanSplit), ARR(oUnary), "channel groups to sequences." },
|
||||
{ "interleave2", ARR(pInterleave), ARR(oInterleave2), "two streams interleaved, y [rows, 2]." },
|
||||
{ "iota", ARR(pIota), ARR(oIota), "y[i] = start + i * step." },
|
||||
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." },
|
||||
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
|
||||
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
|
||||
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
|
||||
@@ -1014,6 +1204,8 @@ SIMPLE("avx_had_quant_act_i8", "had_quant_act_i8", "quant",
|
||||
L(had_quant_act_i8)),
|
||||
SIMPLE("avx_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser",
|
||||
"float in, fp8_e4m3 out, f32 scale", L(quant_act_fp8)),
|
||||
SIMPLE("avx_quant_cols_fp8", "quant_cols_fp8", "quant", "E4M3 with one scale per column",
|
||||
"float in, fp8_e4m3 out, f32 scale", L(quant_cols_fp8)),
|
||||
SIMPLE("avx_had_quant_act_fp8", "had_quant_act_fp8", "quant",
|
||||
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
|
||||
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
|
||||
@@ -1141,7 +1333,8 @@ SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_s
|
||||
|
||||
SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry's scale row)",
|
||||
DT_FLOAT, L(ln_mod)),
|
||||
SIMPLE("avx_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, L(gate_add)),
|
||||
SIMPLE("avx_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT,
|
||||
L(gate_add)),
|
||||
SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
|
||||
"gated residual, adaptive norm and the E4M3 quantiser in one pass",
|
||||
"float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)),
|
||||
@@ -1174,6 +1367,63 @@ SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]",
|
||||
SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn",
|
||||
"attention over a paged prefix and the step's own rows, flash-attention tiles",
|
||||
"bf16 or f32 q, k, v and cache; int8 score form", L(attn_prefix_self)),
|
||||
SIMPLE("avx_rms_mod", "rms_mod", "norm",
|
||||
"gated residual, RMS norm with a gain times (1 + scale row) plus a shift row", DT_FLOAT,
|
||||
L(rms_mod)),
|
||||
SIMPLE("avx_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
|
||||
"gated residual, modulated RMS norm and the E4M3 quantiser in one pass", DT_FLOAT,
|
||||
L(rms_mod_quant_fp8)),
|
||||
SIMPLE("avx_flow_x0_step", "flow_x0_step", "elem", "a sampler step toward the clean estimate",
|
||||
DT_FLOAT, L(flow_x0_step)),
|
||||
SIMPLE("avx_patch_unfold", "patch_unfold", "elem", "patch rows to denormalised voxel rows",
|
||||
DT_FLOAT, L(patch_unfold)),
|
||||
SIMPLE("avx_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out of the latent",
|
||||
DT_FLOAT, L(vtile_gather)),
|
||||
SIMPLE("avx_vtile_stitch", "vtile_stitch", "elem",
|
||||
"decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT,
|
||||
L(vtile_stitch)),
|
||||
SIMPLE("avx_grid_pos3", "grid_pos3", "elem", "a video decoder's rotary positions over its tiles",
|
||||
DT_FLOAT, L(grid_pos3)),
|
||||
SIMPLE("avx_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", L(vsa_select)),
|
||||
SIMPLE("avx_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", L(attn_vsa)),
|
||||
|
||||
SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows",
|
||||
DT_FLOAT, L(conv1d)),
|
||||
SIMPLE("avx_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution, one GEMM a phase",
|
||||
DT_FLOAT, L(conv_t1d)),
|
||||
SIMPLE("avx_snake", "snake", "elem", "the snake activation", DT_FLOAT, L(snake)),
|
||||
SIMPLE("avx_snake_aa", "snake_aa", "elem", "the alias-free SnakeBeta: upsample, snake, downsample",
|
||||
DT_FLOAT, L(snake_aa)),
|
||||
SIMPLE("avx_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick a lane", DT_FLOAT,
|
||||
L(cfg_topk_sample)),
|
||||
SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
|
||||
DT_FLOAT, L(rvq_embed)),
|
||||
SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem",
|
||||
"a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)),
|
||||
SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
|
||||
L(end_status)),
|
||||
SIMPLE("avx_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
|
||||
L(frame_store)),
|
||||
SIMPLE("avx_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
|
||||
DT_ANY, L(resample_nearest)),
|
||||
SIMPLE("avx_fourier_embed", "fourier_embed", "elem", "random Fourier features of a time",
|
||||
DT_FLOAT, L(fourier_embed)),
|
||||
SIMPLE("avx_win_input", "win_input", "elem", "a denoiser's input from the window states",
|
||||
DT_FLOAT, L(win_input)),
|
||||
SIMPLE("avx_win_prep", "win_prep", "elem", "a window step's noise and overlap", DT_FLOAT,
|
||||
L(win_prep)),
|
||||
SIMPLE("avx_win_finish", "win_finish", "elem", "a window's end and the overlap it hands on",
|
||||
DT_FLOAT, L(win_finish)),
|
||||
SIMPLE("avx_chan_split", "chan_split", "elem", "channel groups to sequences", DT_ANY,
|
||||
L(chan_split)),
|
||||
SIMPLE("avx_interleave2", "interleave2", "elem", "two streams interleaved", DT_ANY,
|
||||
L(interleave2)),
|
||||
SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iota)),
|
||||
SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)),
|
||||
|
||||
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
|
||||
/* Its layout hook only validates: the table is read as stored and other encodings are refused
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
/* avx_video.cpp -- the video generator's ops around its decoder (docs/OPS.md, "Video
|
||||
* generation"): the 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.
|
||||
*
|
||||
* Bit-exact with libref (libref/ref_video.cpp): they are copies and roundings, and a seed must
|
||||
* give the same video bytes on both host libraries. Where libref multiplies and then adds in two
|
||||
* roundings, `keep` stops the compiler from fusing the pair (this plugin is built with
|
||||
* -ffp-contract=fast, libref without contraction); the stitch's bf16 blends are passes of whole
|
||||
* rows through x's dtype (`narrow_row`), so a product is rounded before the sum reads it.
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
|
||||
inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); }
|
||||
|
||||
/* v[0, n) rounded through dtype `dt` in place, as a store and reload rounds it. `tmp` holds n
|
||||
* floats. */
|
||||
inline void narrow_row(uint32_t dt, float* v, int64_t n, float* tmp) {
|
||||
if (dt == RAD_F32) return;
|
||||
row_from_f32(dt, v, tmp, n);
|
||||
row_to_f32(dt, tmp, v, n);
|
||||
}
|
||||
|
||||
/* A value the compiler may not fuse into the next add. */
|
||||
#if AVX_LEVEL == 0
|
||||
inline float keep(float x) { __asm__("" : "+x"(x)); return x; }
|
||||
#elif AVX_LEVEL == 3
|
||||
inline float keep(float x) { __asm__("" : "+v"(x)); return x; }
|
||||
#else
|
||||
inline float keep(float x) { __asm__("" : "+x"(x)); return x; }
|
||||
#endif
|
||||
|
||||
/* The f32 values of a space-separated list (libref's parse_f32_list): up to `cap` into out, the
|
||||
* count returned whatever it is. */
|
||||
int64_t parse_f32(const char* s, float* out, int64_t cap) {
|
||||
int64_t k = 0;
|
||||
while (s && *s) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s, &end);
|
||||
if (end == s) break;
|
||||
if (k < cap) out[k] = (float)v;
|
||||
++k;
|
||||
s = end;
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
/* libref's split_tiles: the tile starts and overlaps over `len` latent units. */
|
||||
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;
|
||||
}
|
||||
|
||||
/* A row copied between operands, converted through f32 as libref's element loop is. Whole-byte
|
||||
* float rows of one dtype are copied as bytes, which is the same thing for every non-NaN value. */
|
||||
inline void copy_row(const RadTensor* src, int64_t sb, const RadTensor* dst, int64_t db, int64_t n,
|
||||
float* scr) {
|
||||
const uint32_t dt = src->dtype;
|
||||
const bool flt = dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 ||
|
||||
dt == RAD_F8E5M2;
|
||||
if (flt && dt == dst->dtype && laststride(src) == 1 && laststride(dst) == 1) {
|
||||
const size_t w = (size_t)(rad_dtype_bits(dt) / 8);
|
||||
std::memcpy((char*)dst->data + (size_t)db * w, (const char*)src->data + (size_t)sb * w,
|
||||
(size_t)n * w);
|
||||
return;
|
||||
}
|
||||
out_row(dst, db, n, in_row(src, sb, n, scr));
|
||||
}
|
||||
|
||||
/* out[e] = rd(rd(a[e] wa) + rd(b[e] wb)) over e < cnt, pixels of three values with a weight pair
|
||||
* each (`ws` 1) or one pair for every pixel (`ws` 0), rd a pass through `dt`. `out` may be `b`;
|
||||
* `p2` and `tmp` hold cnt floats. */
|
||||
void blend_rgb(const float* a, const float* wa, const float* b, const float* wb, int64_t ws,
|
||||
int64_t cnt, float* out, float* p2, float* tmp, uint32_t dt) {
|
||||
for (int64_t e = 0; e < cnt; ++e) {
|
||||
p2[e] = b[e] * wb[(e / 3) * ws];
|
||||
out[e] = a[e] * wa[(e / 3) * ws];
|
||||
}
|
||||
narrow_row(dt, out, cnt, tmp);
|
||||
narrow_row(dt, p2, cnt, tmp);
|
||||
for (int64_t e = 0; e < cnt; ++e) out[e] += p2[e];
|
||||
narrow_row(dt, out, cnt, tmp);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ patch_unfold */
|
||||
/* Patch rows to denormalised voxel rows, f32(f32(x * mul[c]) + add[c]) (libref): a task is a
|
||||
* patch, its row read once and dealt into its pt ph pw voxel rows. */
|
||||
AVX_KERNEL(patch_unfold) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), pt = p_int(a, "pt", 0);
|
||||
const int64_t ph = p_int(a, "ph", 0), pw = p_int(a, "pw", 0);
|
||||
const char* ms = p_str(a, "mul", ""), *as = p_str(a, "add", "");
|
||||
/* Each number takes at least two characters but the last, so this bounds the count. */
|
||||
const int64_t cap = (int64_t)((std::strlen(ms) + std::strlen(as)) / 2 + 2);
|
||||
float* lists = (float*)scratch_raw((size_t)(2 * cap + 16) * sizeof(float));
|
||||
float *mul = lists, *add = lists + cap;
|
||||
if (C <= 0 || pt <= 0 || ph <= 0 || pw <= 0 || parse_f32(ms, mul, cap) != C ||
|
||||
parse_f32(as, add, cap) != C || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t F = at(G, 0), Hp = at(G, 1), Wp = at(G, 2);
|
||||
if (F <= 0 || Hp <= 0 || Wp <= 0) return RAD_E_SHAPE;
|
||||
const int64_t vol = pt * ph * pw, Hv = Hp * ph, Wv = Wp * pw, K = C * vol;
|
||||
if (rows_of(Y, C) < F * pt * Hv * Wv || rows_of(X, K) < F * Hp * Wp) return RAD_E_SHAPE;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(F * Hp * Wp * K >= AVX_PAR_MIN)
|
||||
for (int64_t pi = 0; pi < F * Hp * Wp; ++pi) {
|
||||
float* buf = scratch_f32((size_t)(K + C + 32));
|
||||
float *xs = buf, *row = buf + K + 16;
|
||||
const float* xr = in_row(X, rowoff(X, pi, K), K, xs);
|
||||
const int64_t f = pi / (Hp * Wp), i = (pi / Wp) % Hp, j = pi % Wp;
|
||||
for (int64_t sub = 0; sub < vol; ++sub) {
|
||||
const int64_t ta = sub / (ph * pw), yb = (sub / pw) % ph, xd = sub % pw;
|
||||
for (int64_t c = 0; c < C; ++c) row[c] = keep(xr[c * vol + sub] * mul[c]) + add[c];
|
||||
const int64_t r = ((f * pt + ta) * Hv + i * ph + yb) * Wv + j * pw + xd;
|
||||
out_row(Y, rowoff(Y, r, C), C, row);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ grid_pos3 */
|
||||
/* A tile's rotary positions, f32(scale) g(c, n), g(c, n) = f32(f32(2 f32((c + 0.5) / n)) - 1)
|
||||
* (libref): one value an axis index, taken once a launch. */
|
||||
AVX_KERNEL(grid_pos3) {
|
||||
if (!rad_args_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;
|
||||
float* g = (float*)scratch_raw((size_t)(T + H + W + 16) * sizeof(float));
|
||||
auto axis = [scale](int64_t c, int64_t n) {
|
||||
const float q = ((float)c + 0.5f) / (float)n;
|
||||
return scale * (keep(2.0f * q) - 1.0f);
|
||||
};
|
||||
for (int64_t c = 0; c < T; ++c) g[c] = axis(c, T);
|
||||
for (int64_t c = 0; c < H; ++c) g[T + c] = axis(c, H);
|
||||
for (int64_t c = 0; c < W; ++c) g[T + H + c] = axis(c, W);
|
||||
AVX_PARALLEL_FOR_IF(M * 3 >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const int64_t k = m % period;
|
||||
const bool tok = k < T * H * W;
|
||||
stt(Y, m * cs, tok ? g[k / (H * W)] : 0.0f);
|
||||
stt(Y, rs + m * cs, tok ? g[T + (k / W) % H] : 0.0f);
|
||||
stt(Y, 2 * rs + m * cs, tok ? g[T + H + k % W] : 0.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_gather */
|
||||
/* A video decoder's tiles out of the latent's voxel rows, then the register rows and zeros
|
||||
* (libref): one copied row a y row. */
|
||||
AVX_KERNEL(vtile_gather) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *R = &a->t[1], *G = &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(G) < 3 || rows_of(R, n) < n_reg)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = at(G, 1), W = at(G, 2);
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (at(G, 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;
|
||||
const int64_t* py = sy.data();
|
||||
const int64_t* px = sx.data();
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t row = 0; row < rows; ++row) {
|
||||
float* scr = scratch_f32((size_t)n + 16);
|
||||
const int64_t k = row / period, p = row % period, yb = rowoff(Y, row, n);
|
||||
if (p < vox) {
|
||||
const int64_t t = p / (tile * tile), ty = (p / tile) % tile, tx = p % tile;
|
||||
const int64_t src = (t * H + py[k / nw] + ty) * W + px[k % nw] + tx;
|
||||
copy_row(X, rowoff(X, src, n), Y, yb, n, scr);
|
||||
} else if (p < vox + n_reg) {
|
||||
copy_row(R, rowoff(R, p - vox, n), Y, yb, n, scr);
|
||||
} else {
|
||||
for (int64_t c = 0; c < n; ++c) scr[c] = 0.0f;
|
||||
out_row(Y, yb, n, scr);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_stitch */
|
||||
/* A decoded chunk's tiles stitched into frames, the chunk overlap blended and kept, RGB bytes out
|
||||
* (libref's rule and roundings). A task is one pixel row of one frame: each tile column's line of
|
||||
* the owner tile is read out of x, blended with the tile above's line and then the left tile's
|
||||
* (both as decoded), a whole line at a time, every product and sum a pass through x's dtype. The
|
||||
* kept frames are made first, reading `prev`; the frames that refill it after, in a second pass,
|
||||
* so no task reads a row another has rewritten. */
|
||||
AVX_KERNEL(vtile_stitch) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *PV = &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_n = p_int(a, "keep", 0), blend = p_int(a, "blend", 0);
|
||||
const int64_t period = p_int(a, "period", 0);
|
||||
float mean[3], stdv[3];
|
||||
if (tile <= 0 || S <= 0 || pt <= 0 || skip < 0 || keep_n <= 0 || blend < 0 ||
|
||||
blend > keep_n || parse_f32(p_str(a, "mean", ""), mean, 3) != 3 ||
|
||||
parse_f32(p_str(a, "std", ""), stdv, 3) != 3 || numel(G) < 5 || Y->dtype != RAD_U8)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t frames = at(G, 0), H = at(G, 1), W = at(G, 2);
|
||||
const bool first = at(G, 3) != 0, last = at(G, 4) != 0;
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (frames <= 0 || 2 * skip + keep_n + 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_n + (last ? blend : 0);
|
||||
if (rows_of(Y, 3) < fout * npx || (blend > 0 && rows_of(PV, 3) < blend * npx))
|
||||
return RAD_E_SHAPE;
|
||||
std::vector<int64_t> own_y((size_t)Hp);
|
||||
for (int64_t Yp = 0, i = 0; Yp < Hp; ++Yp) {
|
||||
while (i + 1 < nh && Yp >= sy[(size_t)(i + 1)] * S) ++i;
|
||||
own_y[(size_t)Yp] = i;
|
||||
}
|
||||
const uint32_t dt = X->dtype;
|
||||
const int64_t TW = tile * S, RW = Wp * 3, TW3 = TW * 3;
|
||||
const int64_t *psy = sy.data(), *psx = sx.data(), *poy = oy.data(), *pox = ox.data();
|
||||
const int64_t* pown = own_y.data();
|
||||
auto wb = [dt](int64_t p, int64_t e) { return narrow1(dt, (float)p / (float)e); };
|
||||
auto wa = [dt](int64_t p, int64_t e) {
|
||||
return narrow1(dt, 1.0f - narrow1(dt, (float)p / (float)e));
|
||||
};
|
||||
|
||||
/* Tile (i, j)'s decoded line at row ly of clip frame fc: out[lx * 3 + c], lx < TW. */
|
||||
auto tile_line = [&](int64_t i, int64_t j, int64_t ly, int64_t fc, float* out) {
|
||||
const int64_t base = (i * nw + j) * period + ((fc / pt) * tile + ly / S) * tile;
|
||||
const int64_t xs = laststride(X);
|
||||
for (int64_t tx = 0; tx < tile; ++tx) {
|
||||
const int64_t xb = rowoff(X, base + tx, cols);
|
||||
for (int64_t c = 0; c < 3; ++c) {
|
||||
const int64_t col0 = ((c * pt + fc % pt) * S + ly % S) * S;
|
||||
for (int64_t d = 0; d < S; ++d)
|
||||
out[(tx * S + d) * 3 + c] = ldt(X, xb + (col0 + d) * xs);
|
||||
}
|
||||
}
|
||||
};
|
||||
/* The stitched pixel row Yp of clip frame fc into row[0, RW). `l0`, `l1` hold TW3 floats,
|
||||
* `w` 2 TW, `p2` and `tmp` RW. */
|
||||
auto stitch_row = [&](int64_t fc, int64_t Yp, float* row, float* l0, float* l1, float* w,
|
||||
float* p2, float* tmp) {
|
||||
const int64_t i = pown[Yp], ly = Yp - psy[i] * S;
|
||||
const int64_t ev = i > 0 ? poy[i - 1] * S : 0;
|
||||
const float wv[2] = { ly < ev ? wa(ly, ev) : 0.0f, ly < ev ? wb(ly, ev) : 0.0f };
|
||||
for (int64_t j = 0; j < nw; ++j) {
|
||||
const int64_t x0 = psx[j] * S, x1 = j + 1 < nw ? psx[j + 1] * S : Wp;
|
||||
tile_line(i, j, ly, fc, l0);
|
||||
if (ly < ev) {
|
||||
tile_line(i - 1, j, ly + TW - ev, fc, l1);
|
||||
blend_rgb(l1, &wv[0], l0, &wv[1], 0, TW3, l0, p2, tmp, dt);
|
||||
}
|
||||
const int64_t eh = j > 0 ? std::min(pox[j - 1] * S, x1 - x0) : 0;
|
||||
if (eh > 0) {
|
||||
const int64_t full = pox[j - 1] * S;
|
||||
tile_line(i, j - 1, ly, fc, l1);
|
||||
for (int64_t lx = 0; lx < eh; ++lx) {
|
||||
w[lx] = wa(lx, full);
|
||||
w[TW + lx] = wb(lx, full);
|
||||
}
|
||||
blend_rgb(l1 + (TW - full) * 3, w, l0, w + TW, 1, eh * 3, l0, p2, tmp, dt);
|
||||
}
|
||||
std::memcpy(row + x0 * 3, l0, (size_t)((x1 - x0) * 3) * sizeof(float));
|
||||
}
|
||||
};
|
||||
/* Frame f's pixel row Yp as bytes. */
|
||||
auto bytes = [&](int64_t f, int64_t Yp, const float* row) {
|
||||
for (int64_t X0 = 0; X0 < Wp; ++X0) {
|
||||
const int64_t yb = rowoff(Y, f * npx + Yp * Wp + X0, 3);
|
||||
for (int64_t c = 0; c < 3; ++c) {
|
||||
float p = keep(row[X0 * 3 + c] * stdv[c]) + mean[c];
|
||||
p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p);
|
||||
stt(Y, yb + c * laststride(Y), p * 255.0f);
|
||||
}
|
||||
}
|
||||
};
|
||||
const size_t need = (size_t)(3 * RW + 2 * TW3 + 2 * TW + 96);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(keep_n * npx * 3 * 8 >= AVX_PAR_MIN)
|
||||
for (int64_t task = 0; task < keep_n * Hp; ++task) {
|
||||
const int64_t k = task / Hp, Yp = task % Hp;
|
||||
float* buf = scratch_f32(need);
|
||||
float *row = buf, *p2 = row + RW + 16, *tmp = p2 + RW + 16, *l0 = tmp + RW + 16;
|
||||
float *l1 = l0 + TW3 + 16, *w = l1 + TW3 + 16;
|
||||
stitch_row(skip + k, Yp, row, l0, l1, w, p2, tmp);
|
||||
if (!first && k < blend) {
|
||||
float* pr = l0; /* the overlap row, a line's worth at a time */
|
||||
const float pw[2] = { wa(k, blend), wb(k, blend) };
|
||||
for (int64_t x0 = 0; x0 < Wp; x0 += TW) {
|
||||
const int64_t cnt = std::min(TW, Wp - x0);
|
||||
for (int64_t e = 0; e < cnt * 3; ++e) {
|
||||
const int64_t pxi = k * npx + Yp * Wp + x0 + e / 3;
|
||||
pr[e] = ldt(PV, rowoff(PV, pxi, 3) + (e % 3) * laststride(PV));
|
||||
}
|
||||
blend_rgb(pr, &pw[0], row + x0 * 3, &pw[1], 0, cnt * 3, row + x0 * 3, p2, tmp, dt);
|
||||
}
|
||||
}
|
||||
bytes(k, Yp, row);
|
||||
}
|
||||
|
||||
AVX_PARALLEL_FOR_IF(blend * npx * 3 * 8 >= AVX_PAR_MIN)
|
||||
for (int64_t task = 0; task < blend * Hp; ++task) {
|
||||
const int64_t k = task / Hp, Yp = task % Hp;
|
||||
float* buf = scratch_f32(need);
|
||||
float *row = buf, *p2 = row + RW + 16, *tmp = p2 + RW + 16, *l0 = tmp + RW + 16;
|
||||
float *l1 = l0 + TW3 + 16, *w = l1 + TW3 + 16;
|
||||
stitch_row(2 * skip + keep_n + k, Yp, row, l0, l1, w, p2, tmp);
|
||||
if (last) bytes(keep_n + k, Yp, row);
|
||||
for (int64_t X0 = 0; X0 < Wp; ++X0) {
|
||||
const int64_t pb = rowoff(PV, k * npx + Yp * Wp + X0, 3);
|
||||
for (int64_t c = 0; c < 3; ++c) stt(PV, pb + c * laststride(PV), row[X0 * 3 + c]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
/* avx_vsa.cpp -- video sparse attention (docs/OPS.md, "Video sparse attention"): vsa_select's
|
||||
* top-k of pooled tile scores and its coarse branch, and attn_vsa's block-sparse attention.
|
||||
*
|
||||
* The tiles are libref's (libref/ref_vsa.cpp), read off the same operands with the same refusals
|
||||
* in the same order: each dense segment of `segs` in chunks of tile_t tile_h tile_w rows, then the
|
||||
* boxes over the video grid `geom` describes, a tile's rows in its (t, h, w) raster order.
|
||||
*
|
||||
* vsa_select's `sel` is libref's bit for bit: one tile more or less changes the keys a whole query
|
||||
* tile sees. The tile means are summed row by row in raster order with the vector lanes across
|
||||
* head_dim, each lane libref's sum, then divided by the size; a score's dot runs over d in
|
||||
* ascending order with each product rounded before the add (the lanes across tiles, `keep`
|
||||
* stopping the pair from fusing), then the scale; the selection is libref's threshold rule. The
|
||||
* coarse branch takes the vector exp and is held to the tolerance.
|
||||
*
|
||||
* attn_vsa: a task is one (head, query tile), up to 64 of its rows at a time. Per visible key tile,
|
||||
* 64 keys at a time are widened and packed (K as Kt [hd][64], V as [64][hp]), then S = Q K^T as
|
||||
* broadcast-against-tile products, the online softmax (the running max moved at tile boundaries)
|
||||
* and O += P V, avx_gen_attn.cpp's f32 form. Results differ from libref's two-pass softmax in
|
||||
* summation order and the rescales' roundings, within the attention tolerance. Each output row is
|
||||
* one task's, so they do not depend on the thread count.
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include "rad_runtime.h" /* RAD_VGEOM_* */
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
|
||||
/* ================================================================== the tiles (libref's) */
|
||||
inline int64_t at(const RadTensor* t, int64_t i) { return ldi(t, offlin(t, i)); }
|
||||
|
||||
/* `sparsity` at full precision: k is computed from it in f64. NaN when absent. */
|
||||
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;
|
||||
}
|
||||
|
||||
struct Tiles {
|
||||
int64_t R = 0, v0 = 0;
|
||||
int64_t tt = 0, th = 0, tw = 0;
|
||||
int64_t F = 0, Hp = 0, Wp = 0, nb = 0, nc = 0;
|
||||
int64_t P = 0, V = 0, N = 0, k = 0;
|
||||
std::vector<int64_t> start, len;
|
||||
};
|
||||
|
||||
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 || at(segs, 0) != 0) return RAD_E_SHAPE;
|
||||
for (int64_t s = 0; s < n_seg; ++s)
|
||||
if (at(segs, s + 1) < at(segs, s)) return RAD_E_SHAPE;
|
||||
g->R = at(segs, n_seg);
|
||||
g->v0 = at(segs, n_seg - 1);
|
||||
if (g->R <= 0 || g->R > rows) return RAD_E_SHAPE;
|
||||
g->F = at(geom, RAD_VGEOM_LAT_FRAMES);
|
||||
g->Hp = at(geom, RAD_VGEOM_LAT_H) / patch;
|
||||
g->Wp = at(geom, RAD_VGEOM_LAT_W) / patch;
|
||||
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 = at(segs, s), e = 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;
|
||||
}
|
||||
|
||||
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, ta = b / (g.nc * g.nb);
|
||||
return { ta * g.tt, std::min(g.F, (ta + 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);
|
||||
}
|
||||
|
||||
/* The n-th row of tile j in its raster order. */
|
||||
int64_t row_at(const Tiles& g, int64_t j, int64_t n) {
|
||||
if (j < g.P) return g.start[(size_t)j] + n;
|
||||
const Box x = box_of(g, j);
|
||||
const int64_t dh = x.h1 - x.h0, dw = x.w1 - x.w0;
|
||||
const int64_t t = x.t0 + n / (dh * dw), h = x.h0 + (n / dw) % dh, w = x.w0 + n % dw;
|
||||
return g.v0 + (t * g.Hp + h) * g.Wp + w;
|
||||
}
|
||||
|
||||
/* 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] (libref'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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* libref's selection order: the larger score first, NaN above every number, equal scores tied. */
|
||||
inline bool above(float a, float b) {
|
||||
if (a != a) return b == b;
|
||||
return b == b && a > b;
|
||||
}
|
||||
|
||||
/* A product the compiler may not fuse into the next add: libref rounds every product before the
|
||||
* sum (it is built without contraction, this plugin with -ffp-contract=fast). */
|
||||
inline vf keep(vf x) {
|
||||
#if AVX_LEVEL == 3
|
||||
__asm__("" : "+v"(x));
|
||||
#else
|
||||
__asm__("" : "+x"(x));
|
||||
#endif
|
||||
return x;
|
||||
}
|
||||
#if AVX_LEVEL >= 1
|
||||
inline float keep(float x) {
|
||||
#if AVX_LEVEL == 3
|
||||
__asm__("" : "+v"(x));
|
||||
#else
|
||||
__asm__("" : "+x"(x));
|
||||
#endif
|
||||
return x;
|
||||
}
|
||||
#endif
|
||||
|
||||
inline void axpy(float* acc, const float* x, float w, int64_t n) {
|
||||
const vf vw = vf_set1(w);
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N)
|
||||
vf_storeu(acc + i, vf_fma(vw, vf_loadu(x + i), vf_loadu(acc + i)));
|
||||
for (; i < n; ++i) acc[i] += w * x[i];
|
||||
}
|
||||
|
||||
/* The checks both ops share, in libref's order. */
|
||||
struct Call {
|
||||
Tiles g;
|
||||
int64_t hd = 0, nh = 0, kc = 0, scap = 0, ccap = 0;
|
||||
};
|
||||
|
||||
int common(const RadArgs* a, const RadTensor* q, const RadTensor* segs, const RadTensor* geom,
|
||||
Call* c) {
|
||||
c->hd = p_int(a, "head_dim", 0);
|
||||
if (c->hd <= 0) return RAD_E_SHAPE;
|
||||
c->nh = heads_in(q, c->hd);
|
||||
if (c->nh <= 0) return RAD_E_SHAPE;
|
||||
return tiles_of(a, segs, geom, numel(q) / (c->nh * c->hd), &c->g);
|
||||
}
|
||||
|
||||
int caps(const RadTensor* sel, const RadTensor* co, Call* c) {
|
||||
c->kc = sel->rank ? sel->shape[sel->rank - 1] : 0;
|
||||
c->scap = tiles_cap(sel, c->kc, c->nh);
|
||||
if (c->kc < c->g.k || c->scap < c->g.N) return RAD_E_SHAPE;
|
||||
c->ccap = co ? tiles_cap(co, c->hd, c->nh) : 0;
|
||||
if (co && (co->shape[co->rank - 1] != c->hd || c->ccap < c->g.N)) return RAD_E_SHAPE;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== attn_vsa's blocks */
|
||||
/* Keys per packed block and query rows per block. */
|
||||
enum { KT = 64, QB = 64 };
|
||||
#if AVX_LEVEL == 3
|
||||
constexpr int RB = 6;
|
||||
#else
|
||||
constexpr int RB = 2;
|
||||
#endif
|
||||
constexpr int64_t CK = 4 * VF_N;
|
||||
|
||||
inline int64_t padded(int64_t hd) { return (hd + CK - 1) / CK * CK; }
|
||||
|
||||
/* The next row block: `top` rows, the last two kept at four or more (avx_gen_attn.cpp). */
|
||||
inline int row_block(int64_t left, int top) {
|
||||
if (top < 4) return left >= top ? top : (int)left;
|
||||
if (left >= top + 4 || left == top) return top;
|
||||
return left > top ? (int)(left - 4) : (int)left;
|
||||
}
|
||||
|
||||
#define VSA_ROWS(fn, mb, ...) \
|
||||
switch (mb) { \
|
||||
case 6: fn<6>(__VA_ARGS__); break; \
|
||||
case 5: fn<5>(__VA_ARGS__); break; \
|
||||
case 4: fn<4>(__VA_ARGS__); break; \
|
||||
case 3: fn<3>(__VA_ARGS__); break; \
|
||||
case 2: fn<2>(__VA_ARGS__); break; \
|
||||
default: fn<1>(__VA_ARGS__); break; \
|
||||
}
|
||||
|
||||
/* S[i][0, 64) = Q[i] . K for MB_ query rows (pitch ldq) over the packed Kt. */
|
||||
template <int MB_>
|
||||
inline void qk_rows(const float* Q, int64_t ldq, const float* Kt, int64_t hd, float* S) {
|
||||
for (int64_t c = 0; c < KT; c += CK) {
|
||||
vf acc[MB_][4];
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
for (int v = 0; v < 4; ++v) acc[i][v] = vf_zero();
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
const float* kr = Kt + d * KT + c;
|
||||
const vf k0 = vf_loadu(kr), k1 = vf_loadu(kr + VF_N);
|
||||
const vf k2 = vf_loadu(kr + 2 * VF_N), k3 = vf_loadu(kr + 3 * VF_N);
|
||||
for (int i = 0; i < MB_; ++i) {
|
||||
const vf b = vf_set1(Q[i * ldq + d]);
|
||||
acc[i][0] = vf_fma(b, k0, acc[i][0]);
|
||||
acc[i][1] = vf_fma(b, k1, acc[i][1]);
|
||||
acc[i][2] = vf_fma(b, k2, acc[i][2]);
|
||||
acc[i][3] = vf_fma(b, k3, acc[i][3]);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
for (int v = 0; v < 4; ++v) vf_storeu(S + i * KT + c + v * VF_N, acc[i][v]);
|
||||
}
|
||||
}
|
||||
|
||||
/* acc[i][0, hp) += P[i] . V for MB_ rows over the block's `kt` keys. */
|
||||
template <int MB_>
|
||||
inline void pv_rows(float* acc, int64_t hp, const float* Pm, const float* Vt, int64_t kt) {
|
||||
for (int64_t c = 0; c < hp; c += CK) {
|
||||
vf o[MB_][4];
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
for (int v = 0; v < 4; ++v) o[i][v] = vf_loadu(acc + i * hp + c + v * VF_N);
|
||||
for (int64_t j = 0; j < kt; ++j) {
|
||||
const float* vr = Vt + j * hp + c;
|
||||
const vf v0 = vf_loadu(vr), v1 = vf_loadu(vr + VF_N);
|
||||
const vf v2 = vf_loadu(vr + 2 * VF_N), v3 = vf_loadu(vr + 3 * VF_N);
|
||||
for (int i = 0; i < MB_; ++i) {
|
||||
const vf p = vf_set1(Pm[i * KT + j]);
|
||||
o[i][0] = vf_fma(p, v0, o[i][0]);
|
||||
o[i][1] = vf_fma(p, v1, o[i][1]);
|
||||
o[i][2] = vf_fma(p, v2, o[i][2]);
|
||||
o[i][3] = vf_fma(p, v3, o[i][3]);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < MB_; ++i)
|
||||
for (int v = 0; v < 4; ++v) vf_storeu(acc + i * hp + c + v * VF_N, o[i][v]);
|
||||
}
|
||||
}
|
||||
|
||||
/* The online softmax over one block of R rows: m, l and acc (rows of `hp`) rescaled at a new
|
||||
* maximum, S replaced by exp(S - m). A row with nothing visible in the block becomes zeros. */
|
||||
void softmax_block(float* S, int64_t R, float* m, float* l, float* acc, int64_t hp) {
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
float* sr = S + r * KT;
|
||||
const float tmax = row_max(sr, KT);
|
||||
if (tmax == -INFINITY) {
|
||||
for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f;
|
||||
continue;
|
||||
}
|
||||
if (tmax > m[r]) {
|
||||
const float alpha = m[r] == -INFINITY ? 0.0f : sc_exp(m[r] - tmax);
|
||||
if (alpha != 1.0f) {
|
||||
float* ar = acc + r * hp;
|
||||
const vf va = vf_set1(alpha);
|
||||
for (int64_t d = 0; d < hp; d += VF_N)
|
||||
vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), va));
|
||||
l[r] *= alpha;
|
||||
}
|
||||
m[r] = tmax;
|
||||
}
|
||||
const vf vm = vf_set1(m[r]);
|
||||
for (int64_t j = 0; j < KT; j += VF_N)
|
||||
vf_storeu(sr + j, vf_exp(vf_sub(vf_loadu(sr + j), vm)));
|
||||
l[r] += row_sum(sr, KT);
|
||||
}
|
||||
}
|
||||
|
||||
struct Att {
|
||||
const Call* c;
|
||||
const RadTensor *q, *k, *v, *sel, *co, *gt, *o, *k8, *ks;
|
||||
Heads Q, K, Vh, O, G, K8;
|
||||
int64_t ks_rs;
|
||||
float scale;
|
||||
bool i8; /* the int8 score form (libref's ref_attn_vsa) */
|
||||
};
|
||||
|
||||
/* quant_act_i8g's rule for one row, in place: the codes rint(clamp(x * (1/scale), +-127)) and the
|
||||
* scale amax/127 (1 for an all-zero row). */
|
||||
float q8_row(float* x, int64_t n) {
|
||||
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;
|
||||
const float inv = 1.0f / sc;
|
||||
for (int64_t d = 0; d < n; ++d) x[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f));
|
||||
return sc;
|
||||
}
|
||||
|
||||
/* Query tile i of head h. */
|
||||
void attn_task(const Att& t, int64_t h, int64_t i) {
|
||||
const Tiles& g = t.c->g;
|
||||
const int64_t hd = t.c->hd, hp = padded(hd), P = g.P, kk = g.k;
|
||||
float* frame = scratch_f32((size_t)(QB * hd + QB * hp + QB * KT + 2 * QB + hd * KT + KT * hp +
|
||||
4 * hp + QB + KT) + 64);
|
||||
float* Qb = frame;
|
||||
float* acc = Qb + QB * hd;
|
||||
float* S = acc + QB * hp;
|
||||
float* m = S + QB * KT;
|
||||
float* l = m + QB;
|
||||
float* Kt = l + QB;
|
||||
float* Vt = Kt + hd * KT;
|
||||
float* row = Vt + KT * hp; /* 4 hp: a widened row, the epilogue's rows */
|
||||
float* qsc = row + 4 * hp; /* the int8 form's query scales, then key scales */
|
||||
float* ksc = qsc + QB;
|
||||
const int64_t sb = rowoff(t.sel, h * t.c->scap + i, t.c->kc), ss = laststride(t.sel);
|
||||
const int64_t nvis = i < P ? g.N : P + kk;
|
||||
auto vis = [&](int64_t n) {
|
||||
return n < P || i < P ? n : ldi(t.sel, sb + (n - P) * ss);
|
||||
};
|
||||
const int64_t sz = tile_size(g, i);
|
||||
for (int64_t q0 = 0; q0 < sz; q0 += QB) {
|
||||
const int64_t nq = std::min<int64_t>(QB, sz - q0);
|
||||
for (int64_t r = 0; r < nq; ++r) {
|
||||
float* qr = Qb + r * hd;
|
||||
const float* src = in_row(t.q, row_at(g, i, q0 + r) * t.Q.rs + h * t.Q.hs, hd, qr);
|
||||
if (src != qr) std::memcpy(qr, src, sizeof(float) * (size_t)hd);
|
||||
if (t.i8) qsc[r] = q8_row(qr, hd);
|
||||
m[r] = -INFINITY;
|
||||
l[r] = 0.0f;
|
||||
}
|
||||
std::memset(acc, 0, sizeof(float) * (size_t)(nq * hp));
|
||||
for (int64_t n = 0; n < nvis; ++n) {
|
||||
const int64_t j = vis(n), kz = tile_size(g, j);
|
||||
for (int64_t c0 = 0; c0 < kz; c0 += KT) {
|
||||
const int64_t kt = std::min<int64_t>(KT, kz - c0);
|
||||
for (int64_t jj = 0; jj < KT; ++jj) {
|
||||
float* vr = Vt + jj * hp;
|
||||
if (jj >= kt) {
|
||||
for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = 0.0f;
|
||||
std::memset(vr, 0, sizeof(float) * (size_t)hp);
|
||||
continue;
|
||||
}
|
||||
const int64_t kr = row_at(g, j, c0 + jj);
|
||||
const float* kx = t.i8 ? in_row(t.k8, kr * t.K8.rs + h * t.K8.hs, hd, row)
|
||||
: in_row(t.k, kr * t.K.rs + h * t.K.hs, hd, row);
|
||||
for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = kx[d];
|
||||
if (t.i8) ksc[jj] = ldt(t.ks, kr * t.ks_rs + h);
|
||||
const float* vx = in_row(t.v, kr * t.Vh.rs + h * t.Vh.hs, hd, vr);
|
||||
if (vx != vr) std::memcpy(vr, vx, sizeof(float) * (size_t)hd);
|
||||
for (int64_t d = hd; d < hp; ++d) vr[d] = 0.0f;
|
||||
}
|
||||
for (int64_t r = 0, mb; r < nq; r += mb) {
|
||||
mb = row_block(nq - r, RB);
|
||||
VSA_ROWS(qk_rows, mb, Qb + r * hd, hd, Kt, hd, S + r * KT);
|
||||
}
|
||||
const vf vs = vf_set1(t.scale);
|
||||
for (int64_t r = 0; r < nq; ++r) {
|
||||
float* sr = S + r * KT;
|
||||
if (t.i8) {
|
||||
/* libref's order: (dot * q scale) * k scale, then the softmax scale. */
|
||||
for (int64_t j2 = kt; j2 < KT; ++j2) ksc[j2] = 0.0f;
|
||||
const vf vq = vf_set1(qsc[r]);
|
||||
for (int64_t j2 = 0; j2 < KT; j2 += VF_N)
|
||||
vf_storeu(sr + j2, keep(vf_mul(keep(vf_mul(keep(vf_mul(
|
||||
vf_loadu(sr + j2), vq)), vf_loadu(ksc + j2))),
|
||||
vs)));
|
||||
} else {
|
||||
for (int64_t j2 = 0; j2 < KT; j2 += VF_N)
|
||||
vf_storeu(sr + j2, vf_mul(vf_loadu(sr + j2), vs));
|
||||
}
|
||||
for (int64_t j2 = kt; j2 < KT; ++j2) sr[j2] = -INFINITY;
|
||||
}
|
||||
softmax_block(S, nq, m, l, acc, hp);
|
||||
for (int64_t r = 0, mb; r < nq; r += mb) {
|
||||
mb = row_block(nq - r, RB);
|
||||
VSA_ROWS(pv_rows, mb, acc + r * hp, hp, S + r * KT, Vt, kt);
|
||||
}
|
||||
}
|
||||
}
|
||||
/* o = acc / l; with the coarse term o rounded to out's dtype, then + coarse gate, the
|
||||
* product rounded before the add as libref rounds it. */
|
||||
const uint32_t odt = t.o->dtype;
|
||||
float* tmp = row + hp;
|
||||
float* cb = row + 2 * hp;
|
||||
float* gb = row + 3 * hp;
|
||||
const float* cr =
|
||||
t.co ? in_row(t.co, rowoff(t.co, h * t.c->ccap + i, hd), hd, cb) : nullptr;
|
||||
for (int64_t r = 0; r < nq; ++r) {
|
||||
const int64_t qr = row_at(g, i, q0 + r);
|
||||
float* y = acc + r * hp;
|
||||
const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r];
|
||||
const vf vi = vf_set1(inv);
|
||||
int64_t d = 0;
|
||||
for (; d + VF_N <= hd; d += VF_N) vf_storeu(y + d, vf_mul(vf_loadu(y + d), vi));
|
||||
for (; d < hd; ++d) y[d] *= inv;
|
||||
if (cr) {
|
||||
if (odt != RAD_F32) {
|
||||
row_from_f32(odt, y, tmp, hd);
|
||||
row_to_f32(odt, tmp, y, hd);
|
||||
}
|
||||
const float* ge = in_row(t.gt, qr * t.G.rs + h * t.G.hs, hd, gb);
|
||||
d = 0;
|
||||
for (; d + VF_N <= hd; d += VF_N)
|
||||
vf_storeu(y + d, vf_add(vf_loadu(y + d),
|
||||
keep(vf_mul(vf_loadu(cr + d), vf_loadu(ge + d)))));
|
||||
for (; d < hd; ++d) y[d] = y[d] + keep(cr[d] * ge[d]);
|
||||
}
|
||||
out_row(t.o, qr * t.O.rs + h * t.O.hs, hd, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The fp8 P.V form of query tile i of head h (libref's ref_attn_vsa): per row every visible score
|
||||
* (bf16 or int8 form), the max, then p = exp(s - max) in f64 rounded to f32, w = e4m3(448 p), and
|
||||
* o = (sum w v) v_scale / (448 sum p), sums in key order; then the epilogue. Two passes, as libref,
|
||||
* because the weights are rounded against the row's final max. */
|
||||
void attn_task_pv8(const Att& t, const RadTensor* vsc, int64_t h, int64_t i) {
|
||||
const Tiles& g = t.c->g;
|
||||
const int64_t hd = t.c->hd, P = g.P, kk = g.k;
|
||||
const int64_t sb = rowoff(t.sel, h * t.c->scap + i, t.c->kc), ss = laststride(t.sel);
|
||||
const int64_t nvis = i < P ? g.N : P + kk;
|
||||
auto vis = [&](int64_t n) {
|
||||
return n < P || i < P ? n : ldi(t.sel, sb + (n - P) * ss);
|
||||
};
|
||||
int64_t nk = 0;
|
||||
for (int64_t n = 0; n < nvis; ++n) nk += tile_size(g, vis(n));
|
||||
float* qf = scratch_f32((size_t)(4 * hd + nk));
|
||||
float* kf = qf + hd;
|
||||
float* acc = kf + hd;
|
||||
float* y = acc + hd;
|
||||
float* sc = y + hd;
|
||||
const uint32_t odt = t.o->dtype;
|
||||
const int64_t sz = tile_size(g, i);
|
||||
for (int64_t q0 = 0; q0 < sz; ++q0) {
|
||||
const int64_t qr = row_at(g, i, q0);
|
||||
const float* src = in_row(t.q, qr * t.Q.rs + h * t.Q.hs, hd, qf);
|
||||
if (src != qf) std::memcpy(qf, src, sizeof(float) * (size_t)hd);
|
||||
const float qs = t.i8 ? q8_row(qf, hd) : 1.0f;
|
||||
int64_t m = 0;
|
||||
float mx = -INFINITY;
|
||||
for (int64_t n = 0; n < nvis; ++n) {
|
||||
const int64_t j = vis(n), kz = tile_size(g, j);
|
||||
for (int64_t c0 = 0; c0 < kz; ++c0) {
|
||||
const int64_t kr = row_at(g, j, c0);
|
||||
const float* kx = t.i8 ? in_row(t.k8, kr * t.K8.rs + h * t.K8.hs, hd, kf)
|
||||
: in_row(t.k, kr * t.K.rs + h * t.K.hs, hd, kf);
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d) dot = keep(dot + keep(qf[d] * kx[d]));
|
||||
if (t.i8) dot = keep(keep(dot * qs) * ldt(t.ks, kr * t.ks_rs + h));
|
||||
dot = keep(dot * t.scale);
|
||||
sc[m++] = dot;
|
||||
mx = std::max(mx, dot);
|
||||
}
|
||||
}
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] = 0.0f;
|
||||
float sum = 0.0f;
|
||||
m = 0;
|
||||
for (int64_t n = 0; n < nvis; ++n) {
|
||||
const int64_t j = vis(n), kz = tile_size(g, j);
|
||||
for (int64_t c0 = 0; c0 < kz; ++c0) {
|
||||
const int64_t kr = row_at(g, j, c0);
|
||||
const float p = (float)std::exp((double)(sc[m++] - mx));
|
||||
sum += p;
|
||||
const float w = narrow1(RAD_F8E4M3, 448.0f * p);
|
||||
const float* vx = in_row(t.v, kr * t.Vh.rs + h * t.Vh.hs, hd, kf);
|
||||
for (int64_t d = 0; d < hd; ++d) acc[d] = keep(acc[d] + keep(w * vx[d]));
|
||||
}
|
||||
}
|
||||
const float inv8 = sum > 0.0f ? 1.0f / (448.0f * sum) : 0.0f;
|
||||
for (int64_t d = 0; d < hd; ++d)
|
||||
y[d] = keep(keep(acc[d] * ldt(vsc, offlin(vsc, h * hd + d))) * inv8);
|
||||
if (t.co) {
|
||||
const int64_t cb = rowoff(t.co, h * t.c->ccap + i, hd), cs = laststride(t.co);
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
const float c = ldt(t.co, cb + d * cs);
|
||||
const float e = ldt(t.gt, qr * t.G.rs + h * t.G.hs + d * t.G.ds);
|
||||
y[d] = keep(narrow1(odt, y[d]) + keep(c * e));
|
||||
}
|
||||
}
|
||||
out_row(t.o, qr * t.O.rs + h * t.O.hs, hd, y);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ vsa_select */
|
||||
AVX_KERNEL(vsa_select) {
|
||||
const RadTensor *q = rad_arg_in(a, 0), *k = rad_arg_in(a, 1), *v = rad_arg_in(a, 2);
|
||||
const RadTensor *segs = rad_arg_in(a, 3), *geom = rad_arg_in(a, 4), *sel = rad_arg_in(a, 5);
|
||||
const RadTensor* co = rad_arg_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;
|
||||
Call c;
|
||||
if (const int rc = common(a, q, segs, geom, &c); rc < 0) return rc;
|
||||
const Tiles& g = c.g;
|
||||
const int64_t hd = c.hd, nh = c.nh, need = g.R * nh * hd;
|
||||
if (numel(k) < need || (v && numel(v) < need)) return RAD_E_SHAPE;
|
||||
if (const int rc = caps(sel, co, &c); rc < 0) return rc;
|
||||
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, V = g.V, kk = g.k;
|
||||
/* The scores run in whole vectors across tiles, through zero key columns up to Np: from tile
|
||||
* 0 for the coarse branch, else from the last multiple of the width at or below P. */
|
||||
const int64_t Np = (N + VF_N - 1) / VF_N * VF_N;
|
||||
const int64_t j0 = co ? 0 : P / VF_N * VF_N;
|
||||
|
||||
/* The tile means [n_head][N][hd], and the key means transposed, [n_head][hd][Np]. Kept at
|
||||
* their high-water size; the parallel regions read them through pointers taken here. */
|
||||
static thread_local std::vector<float> pool;
|
||||
const size_t per = (size_t)(nh * N * hd);
|
||||
pool.resize(per * (co ? 3 : 2) + (size_t)(nh * hd * Np));
|
||||
float* qp = pool.data();
|
||||
float* kp = qp + per;
|
||||
float* vp = co ? kp + per : nullptr;
|
||||
float* kt = kp + per * (co ? 2 : 1);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(nh * g.R * hd >= AVX_PAR_MIN)
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
const int64_t h = u / N, j = u % N;
|
||||
float* scr = scratch_f32((size_t)(hd + 16));
|
||||
float* means[3] = { qp + u * hd, kp + u * hd, vp ? vp + u * hd : nullptr };
|
||||
const RadTensor* src[3] = { q, k, v };
|
||||
const Heads* hv[3] = { &Q, &K, &Vh };
|
||||
for (int s = 0; s < 3; ++s) {
|
||||
float* mu = means[s];
|
||||
if (!mu) continue;
|
||||
std::memset(mu, 0, sizeof(float) * (size_t)hd);
|
||||
tile_rows(g, j, [&](int64_t r) {
|
||||
const float* x = in_row(src[s], r * hv[s]->rs + h * hv[s]->hs, hd, scr);
|
||||
int64_t d = 0;
|
||||
for (; d + VF_N <= hd; d += VF_N)
|
||||
vf_storeu(mu + d, vf_add(vf_loadu(mu + d), vf_loadu(x + d)));
|
||||
for (; d < hd; ++d) mu[d] += x[d];
|
||||
});
|
||||
const float n = (float)tile_size(g, j);
|
||||
const vf vn = vf_set1(n);
|
||||
int64_t d = 0;
|
||||
for (; d + VF_N <= hd; d += VF_N) vf_storeu(mu + d, vf_div(vf_loadu(mu + d), vn));
|
||||
for (; d < hd; ++d) mu[d] /= n;
|
||||
}
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(nh * Np * hd >= AVX_PAR_MIN)
|
||||
for (int64_t hdd = 0; hdd < nh * hd; ++hdd) {
|
||||
const int64_t h = hdd / hd, d = hdd % hd;
|
||||
float* kr = kt + hdd * Np;
|
||||
for (int64_t j = 0; j < N; ++j) kr[j] = kp[(h * N + j) * hd + d];
|
||||
for (int64_t j = N; j < Np; ++j) kr[j] = 0.0f;
|
||||
}
|
||||
|
||||
const int64_t kc = c.kc, scap = c.scap, ccap = c.ccap, ss = laststride(sel);
|
||||
AVX_PARALLEL_FOR_IF(nh * N * Np * hd >= AVX_PAR_MIN)
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
const int64_t h = u / N, i = u % N;
|
||||
if (i < P && !co) continue;
|
||||
float* frame = scratch_f32((size_t)(Np + V + hd) + 64);
|
||||
float* S = frame;
|
||||
float* ord = S + Np;
|
||||
float* acc = ord + V;
|
||||
const float* qs = qp + u * hd;
|
||||
const float* kth = kt + h * hd * Np;
|
||||
for (int64_t j = j0; j < Np; j += VF_N) vf_storeu(S + j, vf_zero());
|
||||
for (int64_t d = 0; d < hd; ++d) {
|
||||
const vf b = vf_set1(qs[d]);
|
||||
const float* kr = kth + d * Np;
|
||||
for (int64_t j = j0; j < Np; j += VF_N)
|
||||
vf_storeu(S + j, vf_add(vf_loadu(S + j), keep(vf_mul(b, vf_loadu(kr + j)))));
|
||||
}
|
||||
const vf vs = vf_set1(scale);
|
||||
for (int64_t j = j0; j < Np; j += VF_N) vf_storeu(S + j, vf_mul(vf_loadu(S + j), vs));
|
||||
if (i >= P) {
|
||||
std::copy(S + P, S + N, ord);
|
||||
std::nth_element(ord, ord + (kk - 1), ord + V, above);
|
||||
const float thr = ord[kk - 1];
|
||||
int64_t ties = kk;
|
||||
for (int64_t j = 0; j < V; ++j) ties -= above(S[P + j], thr);
|
||||
const int64_t sb = rowoff(sel, h * scap + i, kc);
|
||||
int64_t n = 0;
|
||||
for (int64_t j = 0; j < V; ++j) {
|
||||
const float s = S[P + j];
|
||||
if (above(s, thr) || (!above(thr, s) && ties-- > 0))
|
||||
st_int_dt(sel->dtype, sel->data, sb + (n++) * ss, P + j);
|
||||
}
|
||||
}
|
||||
if (co) {
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = 0; j < N; ++j) if (S[j] > mx) mx = S[j];
|
||||
const vf vm = vf_set1(mx);
|
||||
int64_t j = 0;
|
||||
for (; j + VF_N <= N; j += VF_N) vf_storeu(S + j, vf_exp(vf_sub(vf_loadu(S + j), vm)));
|
||||
for (; j < N; ++j) S[j] = sc_exp(S[j] - mx);
|
||||
const float sum = row_sum(S, N);
|
||||
std::memset(acc, 0, sizeof(float) * (size_t)hd);
|
||||
for (j = 0; j < N; ++j) axpy(acc, vp + (h * N + j) * hd, S[j] / sum, hd);
|
||||
out_row(co, rowoff(co, h * ccap + i, hd), hd, acc);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_vsa */
|
||||
AVX_KERNEL(attn_vsa) {
|
||||
const RadTensor *q = rad_arg_in(a, 0), *k = rad_arg_in(a, 1), *v = rad_arg_in(a, 2);
|
||||
const RadTensor *segs = rad_arg_in(a, 3), *geom = rad_arg_in(a, 4), *sel = rad_arg_in(a, 5);
|
||||
const RadTensor *co = rad_arg_in(a, 6), *gt = rad_arg_in(a, 7), *o = rad_arg_in(a, 8);
|
||||
const RadTensor *k8 = rad_arg_in(a, 9), *ks = rad_arg_in(a, 10);
|
||||
const RadTensor* vsc = a->n_t > 11 ? rad_arg_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;
|
||||
if (sel->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
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;
|
||||
Call c;
|
||||
if (const int rc = common(a, q, segs, geom, &c); rc < 0) return rc;
|
||||
const Tiles& g = c.g;
|
||||
const int64_t hd = c.hd, nh = c.nh, need = g.R * nh * hd;
|
||||
if (numel(k) < need || numel(v) < need || numel(o) < need || (gt && numel(gt) < need))
|
||||
return RAD_E_SHAPE;
|
||||
if (const int rc = caps(sel, co, &c); rc < 0) return rc;
|
||||
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 * c.scap + i, c.kc);
|
||||
int64_t prev = P - 1;
|
||||
for (int64_t s = 0; s < kk; ++s) {
|
||||
const int64_t j = ldi(sel, sb + s * ss);
|
||||
if (j <= prev || j >= N) return RAD_E_INVAL;
|
||||
prev = j;
|
||||
}
|
||||
}
|
||||
Att t{};
|
||||
t.c = &c;
|
||||
t.q = q; t.k = k; t.v = v; t.sel = sel; t.co = co; t.gt = gt; t.o = o;
|
||||
t.Q = heads_of(q, nh, hd);
|
||||
t.K = heads_of(k, nh, hd);
|
||||
t.Vh = heads_of(v, nh, hd);
|
||||
t.O = heads_of(o, nh, hd);
|
||||
t.G = gt ? heads_of(gt, nh, hd) : Heads{ nullptr, 0, 0, 0 };
|
||||
t.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd));
|
||||
t.i8 = i8;
|
||||
if (i8) {
|
||||
if (numel(k8) < need || numel(ks) < g.R * nh) return RAD_E_SHAPE;
|
||||
t.k8 = k8;
|
||||
t.ks = ks;
|
||||
t.K8 = heads_of(k8, nh, hd);
|
||||
t.ks_rs = row_stride(ks, nh);
|
||||
}
|
||||
/* Dynamic: a prefix query tile sees every tile, a video one the prefix and k tiles, and a
|
||||
* unit's arithmetic does not depend on the thread that runs it. */
|
||||
#ifdef _OPENMP
|
||||
AVX_PRAGMA(omp parallel for schedule(dynamic, 1) if(nh * g.R * hd >= AVX_PAR_MIN ||
|
||||
avx_par_forced()) num_threads(avx_team_size()))
|
||||
#endif
|
||||
for (int64_t u = 0; u < nh * N; ++u) {
|
||||
if (pv8) attn_task_pv8(t, vsc, u / N, u % N);
|
||||
else attn_task(t, u / N, u % N);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
Reference in new issue
Block a user