Archived
radiance 1.13.0
New models: - Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls - M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% -> 92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints - Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by default; Ornith-1.5-122B compose files Speed: - Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default): the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13% - Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a step at 25-41K context), and the prefill KV split for small launches (a short turn over a long context decodes the other sequences 27% faster in that step) - MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows: TranslateGemma +2-5% at 2-8 streams) - ParoQuant int4/int5 tiled GEMMs 6-9% faster - Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one that ends its requests, and the MTP head's first draft no longer collapses after short chats in the prefix cache Features: - --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3) - MiniMax-H3: reference media and keyframe conditioning with the VAE encoders - Krea 2 rebalance presets balanced, detail and subtle - The dashboard's request history; a stall watch that reports a frozen step's thread and stack - rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's per-layer embeddings read ahead off the step path - A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container Fixes: - The two-rank all-reduce checks that a peer's push has landed before reducing it - z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit - MiniMax-H3's modulation rows Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is --weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT, R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
+8
-18
@@ -1061,17 +1061,10 @@ AVX_KERNEL(kv_store) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store_streamed */
|
||||
/* kv_store for a group whose KV streams: the host mirror is authoritative and the ring is a cache
|
||||
* of it. `host` is written ALWAYS, at the block's identity row; `kv_cache[res[block]]` only when
|
||||
* the residency map says the block is resident. libref/ref_attn.cpp (ref_kv_store_streamed) states
|
||||
* why the residency test belongs in the writer and not in the resolve: at decode the block a step
|
||||
* writes is usually already resident, so a mirror-only writer would leave the ring's copy of it
|
||||
* short of this step's tokens and the resolve would not re-copy a resident block.
|
||||
*
|
||||
* The two planes are the same bytes in the same paged layout, so one conversion writes both: the
|
||||
* mirror is a view of the same `[block, kv_heads, block_size, 2 * head_dim]` shape whose dtype is
|
||||
* the cache's, so the two copies cannot round differently. E4M3 converts as kv_store_fp8 does;
|
||||
* bf16 stores the value itself, as kv_store_bf16 does. `res` is read, never written. */
|
||||
/* kv_store for a streamed group (libref/ref_attn.cpp, ref_kv_store_streamed): `host` written
|
||||
* always, `kv_cache[res[block]]` only where the block is resident. Both planes are the same paged
|
||||
* layout seen as the cache's dtype, so one conversion writes both: E4M3 as kv_store_fp8, bf16 the
|
||||
* value itself. `res` is read, never written. */
|
||||
AVX_KERNEL(kv_store_streamed) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
|
||||
@@ -1084,16 +1077,14 @@ AVX_KERNEL(kv_store_streamed) {
|
||||
if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (host->dtype != RAD_U8) return RAD_E_DTYPE;
|
||||
/* E4M3 (the fp8 QSA family) or bf16 (the default cache dtype); a packed fp8_v4/k6_v4 group has
|
||||
* no streamed row. */
|
||||
/* E4M3 or bf16; a packed fp8_v4/k6_v4 group has no streamed row. */
|
||||
const bool fp8 = kv->dtype == RAD_F8E4M3;
|
||||
if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED;
|
||||
if (kv->rank != 4 || kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
|
||||
kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE;
|
||||
if (host->rank != 2) return RAD_E_SHAPE;
|
||||
|
||||
/* One block of one layer: both planes are dense rows of it, so the same offsets address the
|
||||
* same element of the same block in either. */
|
||||
/* Both planes are dense rows of one block of one layer, so one offset addresses both. */
|
||||
const int64_t EB = fp8 ? 1 : 2;
|
||||
const int64_t row = kv_heads * block_size * 2 * head_dim * EB;
|
||||
const int64_t slots = kv->shape[0], blocks = host->shape[0];
|
||||
@@ -1116,9 +1107,8 @@ AVX_KERNEL(kv_store_streamed) {
|
||||
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
|
||||
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
|
||||
|
||||
/* Refused before the first write, exactly as libref refuses it: a half-written mirror makes
|
||||
* the next step's copies plausible and wrong. (The device row cannot return a host status from
|
||||
* inside its kernel and guards these instead; a legal call never takes either path.) */
|
||||
/* Refused before the first write, as libref refuses it (the device row, which cannot return a
|
||||
* status from its kernel, guards these instead). */
|
||||
const int32_t* const R = (const int32_t*)res->data;
|
||||
for (int64_t t = 0; t < M; ++t) {
|
||||
const int64_t slot = ldi(sm, offlin(sm, t));
|
||||
|
||||
+28
-13
@@ -238,26 +238,40 @@ AVX_KERNEL(conv1d) {
|
||||
if (!Y->data) return RAD_E_INVAL;
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
|
||||
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
|
||||
const int64_t st = p_int(a, "stride", 1), cd = p_int(a, "cu_div", 1);
|
||||
const int64_t st = p_int(a, "stride", 1), ep = p_int(a, "pad", -1), cd = p_int(a, "cu_div", 1);
|
||||
const char* act = p_str(a, "act", "none");
|
||||
const bool tanh_out = act && !std::strcmp(act, "tanh");
|
||||
const bool clamp_out = act && !std::strcmp(act, "clamp");
|
||||
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) ||
|
||||
cd < 1)
|
||||
/* A stride takes one of two forms: causal (bounds in cu_div units, each sequence a multiple of
|
||||
* the stride) or, with `pad`, PyTorch's zero-padded one (bf16, one sequence, cu_div 1). */
|
||||
const bool padded = ep >= 0 && st > 1;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1 || st < 1 || (ep >= 0 && (st <= 1 || causal || cd != 1)) ||
|
||||
(st > 1 && ep < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e <= n_seq; ++e)
|
||||
const int64_t cdv = padded ? 1 : cd;
|
||||
for (int64_t e = 0; !padded && e <= n_seq; ++e)
|
||||
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
|
||||
/* r0, r1: the output rows, the input's over the stride. */
|
||||
const int64_t r0 = cu_at(cu, 0) / (cd * st), r1 = cu_at(cu, n_seq) / (cd * st);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1 * st)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t x0 = cu_at(cu, 0) / cdv, x1 = cu_at(cu, n_seq) / cdv;
|
||||
if (x0 < 0 || x1 <= x0 || rows_of(X, cin) < x1) return RAD_E_SHAPE;
|
||||
if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE;
|
||||
/* r0, r1: the output rows. A causal stride takes each sequence of L rows to L / stride; the
|
||||
* padded form has PyTorch's (L + 2 pad - dil (k - 1) - 1) / stride + 1, y exactly that many. */
|
||||
int64_t r0 = x0 / st, r1 = x1 / st;
|
||||
if (padded) {
|
||||
if (X->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (n_seq != 1 || x0 != 0 || x1 != rows_of(X, cin)) return RAD_E_SHAPE;
|
||||
r0 = 0;
|
||||
r1 = (x1 + 2 * ep - dil * (k - 1) - 1) / st + 1;
|
||||
}
|
||||
if (r0 >= r1) return RAD_E_SHAPE;
|
||||
if (padded ? rows_of(Y, cout) != r1 : rows_of(Y, cout) < r1) return RAD_E_SHAPE;
|
||||
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
|
||||
const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2, KK = k * cin;
|
||||
const int64_t pad = padded ? ep : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2),
|
||||
KK = k * cin;
|
||||
static thread_local std::vector<uint8_t> wbuf, pbuf;
|
||||
static thread_local std::vector<float> ybuf;
|
||||
|
||||
@@ -272,7 +286,8 @@ AVX_KERNEL(conv1d) {
|
||||
const bool b16 = X->dtype == RAD_BF16 && laststride(X) == 1;
|
||||
const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32;
|
||||
const size_t ael = b16 ? 2 : 4;
|
||||
/* A 1-wide kernel's patch row is x's own row. */
|
||||
/* A 1-wide kernel's patch row is x's own row; a strided op reads rows `stride` apart, so it
|
||||
* always builds patches. */
|
||||
const bool direct = k == 1 && st == 1 && X->rank == 2 && X->shape[1] == cin &&
|
||||
X->stride[1] == 1 && (X->dtype == RAD_BF16 || X->dtype == RAD_F32);
|
||||
const int64_t band = band_rows(KK, cout, r1 - r0);
|
||||
@@ -291,8 +306,8 @@ AVX_KERNEL(conv1d) {
|
||||
pt = mat_view(pp, adt, nb, KK);
|
||||
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
|
||||
for (int64_t p = 0; p < nb; ++p) {
|
||||
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r * st * cd);
|
||||
const int64_t s0 = cu_at(cu, e) / cd, s1 = cu_at(cu, e + 1) / cd;
|
||||
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r * st * cdv);
|
||||
const int64_t s0 = cu_at(cu, e) / cdv, s1 = cu_at(cu, e + 1) / cdv;
|
||||
for (int64_t t = 0; t < k; ++t) {
|
||||
const int64_t ir = r * st + t * dil - pad;
|
||||
patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16,
|
||||
|
||||
+50
-16
@@ -97,6 +97,10 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", dt) });
|
||||
add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035),
|
||||
HS("dtype", dt) }, EB(27, 645, w, 1));
|
||||
add("pool_cols", { HI("M", 27), HI("n", 648), HI("k", 9), HF("mult", 27.712812921102035),
|
||||
HS("dtype", dt) }, EB(27, 648, w, 1));
|
||||
add("pool_cols", { HI("M", 40), HI("n", 256), HI("k", 8), HS("dtype", dt) },
|
||||
EB(40, 256, w, 1));
|
||||
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
|
||||
EB(6, 645, w, 2));
|
||||
@@ -367,6 +371,11 @@ std::vector<Case> build_cases() {
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0),
|
||||
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
|
||||
HI("block", 7) });
|
||||
/* An audio encoder's attention: head_dim 256, no GQA, causal within a window. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 256), HI("gqa", 1), HI("causal", 1),
|
||||
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
|
||||
HI("window", 8) });
|
||||
/* Cross attention: each entry's keys a run of their own, both sides of `causal`. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int causal : { 0, 1 })
|
||||
@@ -429,9 +438,8 @@ std::vector<Case> build_cases() {
|
||||
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 16), HS("kv_dtype", "fp8_e4m3"), HF("k_scale", ks),
|
||||
HF("v_scale", 1.0 / ks) });
|
||||
/* The streamed store, on one block and one ring slot (see ref_shapes.cpp: a described map
|
||||
* cannot be an injective permutation, so a multi-block call could draw two blocks one slot).
|
||||
* The resident/mirror-only split is built by hand in avx_check_hand.cpp. */
|
||||
/* The streamed store, on one block and one ring slot (ref_shapes.cpp says why); the resident and
|
||||
* mirror-only split is built by hand in avx_check_hand.cpp. */
|
||||
for (double ks : { 1.0, 0.5 })
|
||||
add("kv_store_streamed", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 32), HS("kv_dtype", "fp8_e4m3"),
|
||||
@@ -544,14 +552,10 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", "f32") });
|
||||
add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3),
|
||||
HI("work", 3), HS("dtype", "f32") });
|
||||
/* The streamed group's residency map at a decode step's geometry and at the edges a check can
|
||||
* describe: a ring shallower than the id space and deeper than it, one query row, a pitch of
|
||||
* one, and a `block_bytes` that is not a multiple of a vector (a block is a whole number of
|
||||
* 16-byte lanes in practice, but nothing in the schema says so and the copy's tail must still
|
||||
* be right). libref describes the map as every block resident (ref_shapes.cpp), so these cases
|
||||
* exercise the epoch, the hit stamp, the rewrite and the bookkeeping; a miss, an eviction, a
|
||||
* second chance and an overflow need a cold map, which no description draws, and are built by
|
||||
* hand in avx_check_hand.cpp. */
|
||||
/* The residency map at a decode step's geometry and at the edges a description can reach: a ring
|
||||
* shallower and deeper than the id space, one query row, a pitch of one, and a `block_bytes`
|
||||
* that is not a whole vector (the copy's tail). The described map is all-resident, so misses,
|
||||
* evictions, second chances and overflow are built by hand in avx_check_hand.cpp. */
|
||||
add("kv_resolve", { HI("M", 4), HI("blocks", 300), HI("slots", 96), HI("sel_pitch", 33),
|
||||
HI("block_bytes", 256) });
|
||||
add("kv_resolve", { HI("M", 6), HI("blocks", 64), HI("slots", 128), HI("sel_pitch", 17),
|
||||
@@ -799,6 +803,8 @@ std::vector<Case> build_cases() {
|
||||
add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0),
|
||||
HF("max_period", 10000.0), HI("round", round),
|
||||
HS("dtype", dt) });
|
||||
for (int g : { 5, 1025 })
|
||||
add("timestep_embed", { HI("M", 3), HI("n", 8), HI("curve", g), HS("dtype", dt) });
|
||||
add("lane_gather", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2),
|
||||
HS("dtype", dt) });
|
||||
add("lane_store", { HI("M", 12), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
|
||||
@@ -918,6 +924,22 @@ std::vector<Case> build_cases() {
|
||||
add("grid_pos3", { HI("M", 40), HI("T", 2), HI("H", 3), HI("W", 4), HI("period", 27),
|
||||
HF("scale", 6.283185307179586) });
|
||||
|
||||
/* The tiled encoder over the shape functions' 20 x 20 latent plane: the encoder's tile 16
|
||||
* with its 4 overlap (two tiles an axis), and a 3-overlap-1 split (ten tiles an axis, one of
|
||||
* slack round-robin) that puts a live blend on every interior row and column. crop is drawn
|
||||
* at ratio 1 -- the plane is 20 x 20 pixels, its tiles' sum 30 x 30 either way; join reads
|
||||
* the moments' 30 x 30 rows into the 400-row canvas. */
|
||||
add("vtile_plan", { HI("M", 4), HI("tile", 16), HI("overlap", 4), HI("ratio", 16) });
|
||||
add("vtile_plan", { HI("M", 100), HI("tile", 3), HI("overlap", 1), HI("ratio", 1) });
|
||||
add("vtile_crop", { HI("M", 1024), HI("tile", 16), HI("overlap", 4), HI("ratio", 1),
|
||||
HS("dtype", "f32") });
|
||||
add("vtile_crop", { HI("M", 900), HI("tile", 3), HI("overlap", 1), HI("ratio", 1),
|
||||
HS("dtype", "bf16") });
|
||||
add("vtile_join", { HI("M", 400), HI("tile", 16), HI("overlap", 4), HI("n", 48),
|
||||
HS("dtype", "bf16") });
|
||||
add("vtile_join", { HI("M", 400), HI("tile", 3), HI("overlap", 1), HI("n", 5),
|
||||
HS("dtype", "f32") });
|
||||
|
||||
/* The latent upscaler over libref's cube volumes (c x c x c, the largest M holds; every geom
|
||||
* entry c, so the resize is the identity here): the 3-D convolution at odd channel counts,
|
||||
* kernels 3 x 3 x 3 and 3 x 1 x 1, with the residual (a separate buffer), and at MiniMax-H3's
|
||||
@@ -938,6 +960,9 @@ std::vector<Case> build_cases() {
|
||||
HS("act", act), HS("dtype", dt) });
|
||||
add("group_norm", { HI("M", 150), HI("n", 96), HI("groups", 4), HF("eps", 1e-5),
|
||||
HS("act", "silu"), HS("dtype", dt) });
|
||||
/* The video encoder's first level: four channels a group, eps 1e-6. */
|
||||
add("group_norm", { HI("M", 130), HI("n", 128), HI("groups", 32), HF("eps", 1e-6),
|
||||
HS("act", "silu"), HS("dtype", dt) });
|
||||
add("tconv_dw", { HI("M", 27), HI("n", 645), HI("k", 5), HS("dtype", dt) });
|
||||
add("tconv_dw", { HI("M", 64), HI("n", 37), HI("k", 3), HS("dtype", dt) });
|
||||
add("resize_bilinear", { HI("M", 27), HI("n", 645), HS("dtype", dt) });
|
||||
@@ -953,6 +978,10 @@ std::vector<Case> build_cases() {
|
||||
0, 2.0 * 27 * v.cin * v.cout * 27);
|
||||
add("flow_renoise", { HI("M", 9), HI("n", 96), HI("stream", 1), HS("dtype", "f32") });
|
||||
add("flow_renoise", { HI("M", 5), HI("n", 645), HI("stream", 7), HS("dtype", "f32") });
|
||||
add("cond_aug", { HI("M", 9), HI("n", 96), HI("stream", 2), HF("aug", 0.999),
|
||||
HS("dtype", "f32") });
|
||||
add("cond_aug", { HI("M", 5), HI("n", 645), HI("stream", 7), HF("aug", 0.5),
|
||||
HS("dtype", "f32") });
|
||||
|
||||
/* LTX-2: the video's 3-axis rotary (two padded pairs, a rank's second head), the cross
|
||||
* attentions' 1-axis one, the per-head gate and the guided step. */
|
||||
@@ -1029,6 +1058,13 @@ std::vector<Case> build_cases() {
|
||||
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) });
|
||||
/* The zero-padded strided form, a DAC encoder block's downsample: kernel 2 stride, pad
|
||||
* ceil(stride / 2), one sequence. The form is bf16 only. */
|
||||
if (std::strcmp(dt, "bf16") == 0)
|
||||
for (int s : { 2, 4, 5 })
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
|
||||
HI("dil", 1), HI("stride", s), HI("pad", (s + 1) / 2),
|
||||
HS("dtype", dt) });
|
||||
/* Strided, causal: Fish Audio's codec encoder downsamples with kernels of two strides
|
||||
* (2, 4, 8) and its quantiser with a kernel of one (k 2, stride 2). */
|
||||
for (int s : { 2, 4, 8 })
|
||||
@@ -1264,11 +1300,9 @@ std::vector<Case> build_cases() {
|
||||
(double)M * blocks * 8, 0);
|
||||
speed("qsa_select", { HI("M", 2048), HI("blocks", 16384), HI("topk", 512), HI("ratio", 4),
|
||||
HI("seqs", 1) }, 2048.0 * 16384 * 8, 0);
|
||||
/* The residency map at a decode step: an 8K-block id space over a 2048-slot ring (a group at
|
||||
* depth 3 with 256-token blocks), one query row and a four-row verify window, 512 selected
|
||||
* blocks a row. libref describes the map all-resident, so this times the two selection passes,
|
||||
* the compaction of the claim list, the rewrite and the bookkeeping; the block copies are one
|
||||
* per miss, and which blocks miss is a cache state the geometry does not carry. */
|
||||
/* The residency map at a decode step: an 8K-block id space over a 2048-slot ring, one query row
|
||||
* and a four-row verify, 512 blocks a row. All-resident, so this times the selection passes,
|
||||
* the claim compaction, the rewrite and the bookkeeping, not the copies. */
|
||||
for (const int64_t M : { 1, 4 })
|
||||
speed("kv_resolve", { HI("M", M), HI("blocks", 8192), HI("slots", 2048),
|
||||
HI("sel_pitch", 513), HI("block_bytes", 2048) },
|
||||
|
||||
+123
-10
@@ -2401,6 +2401,24 @@ void video_cases(std::vector<Hand>& hs) {
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
|
||||
/* ---- flow_res_multistep: a bf16 velocity, the f32 state and previous estimate both
|
||||
* INOUT at wider pitches; order 2 reads the previous estimate, order 1 is Euler ---- */
|
||||
for (float order : { 2.0f, 1.0f }) {
|
||||
Hand h((std::string(order >= 1.5f ? "two-estimate" : "Euler limit") +
|
||||
", bf16 velocity, f32 state and history" + sfx).c_str(),
|
||||
"flow_res_multistep", 0.0);
|
||||
h.dense(dt, { 7, 96 }, hfill(422, 2.0f))
|
||||
.view(RAD_F32, { 7, 96 }, { 99, 1 }, 7 * 99, hfill(423), true) /* x0, INOUT */
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.5625f; }) /* sigma */
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.625f; }) /* r */
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.24f; }) /* hb1 */
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return -0.005f; }) /* hb2 */
|
||||
.dense(RAD_F32, { 1 }, [order](int64_t) { return order; }) /* order */
|
||||
.view(RAD_F32, { 7, 96 }, { 101, 1 }, 7 * 101, hfill(424), true) /* x, INOUT */
|
||||
.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). */
|
||||
{
|
||||
@@ -2513,6 +2531,84 @@ void upscaler_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", R).pi("cin", ci).pi("cout", co).pi("k", 2).pi("kt", 3).ps("dtype", dn)
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(e));
|
||||
|
||||
/* The video encoder's convolution forms. The generated cases never stride, reflect
|
||||
* or pad one side only, so the downsample, a res block reflecting on every edge and
|
||||
* the one-frame case are written out here. */
|
||||
{
|
||||
/* (3 + 2 - 3) / 2 + 1 = 2 frames, (4 + 1 - 3) / 2 + 1 = 2 rows and
|
||||
* (5 + 1 - 3) / 2 + 1 = 2 columns: the pad below and right only, both strides,
|
||||
* and a column of reflected taps. */
|
||||
Hand h(("3 x 4 x 5 causal, stride 2 down reflect" + sfx).c_str(),
|
||||
"conv3d_ndhwc", tol);
|
||||
h.dense(dt, { 3 * 4 * 5, ci }, hfill(960))
|
||||
.dense(dt, { co, ci, 3, 3, 3 }, hfill(961, 0.3f))
|
||||
.dense(dt, { co }, hfill(962, 0.5f))
|
||||
.idx({ 3, 4, 5 })
|
||||
.none()
|
||||
.dense(dt, { 8, co }, hfill(963), true)
|
||||
.pi("M", 8).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
|
||||
.pi("stride", 2).pi("stride_t", 2).pi("causal", 1).ps("pad", "down")
|
||||
.pi("reflect", 1);
|
||||
hs.push_back(std::move(h));
|
||||
|
||||
Hand g(("2 x 2 x 3 causal reflect, a mirror on every edge" + sfx).c_str(),
|
||||
"conv3d_ndhwc", tol);
|
||||
g.dense(dt, { 12, ci }, hfill(964))
|
||||
.dense(dt, { co, ci, 3, 3, 3 }, hfill(965, 0.3f))
|
||||
.dense(dt, { co }, hfill(966, 0.5f))
|
||||
.idx({ 2, 2, 3 })
|
||||
.none()
|
||||
.dense(dt, { 12, co }, hfill(967), true)
|
||||
.pi("M", 12).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
|
||||
.pi("causal", 1).pi("reflect", 1);
|
||||
hs.push_back(std::move(g));
|
||||
|
||||
/* One frame in, one out: the causal pad's zero frames stand for the taps the
|
||||
* reference drops, and the residual is y itself. */
|
||||
Hand q(("one frame, causal reflect, residual in place" + sfx).c_str(),
|
||||
"conv3d_ndhwc", tol);
|
||||
q.dense(dt, { 4, ci }, hfill(968))
|
||||
.dense(dt, { co, ci, 3, 3, 3 }, hfill(969, 0.3f))
|
||||
.dense(dt, { co }, hfill(970, 0.5f))
|
||||
.idx({ 1, 2, 2 })
|
||||
.dense(dt, { 4, co }, hfill(971), true)
|
||||
.alias(4)
|
||||
.pi("M", 4).pi("cin", ci).pi("cout", co).pi("k", 3).pi("kt", 3).ps("dtype", dn)
|
||||
.pi("causal", 1).pi("reflect", 1);
|
||||
hs.push_back(std::move(q));
|
||||
|
||||
/* The refusals, with libref's error codes: a 5-wide kernel with a stride, a pad
|
||||
* neither `same` nor `down`, a reflect pad on an axis of 1, y short of the strided
|
||||
* output, and a zero stride. */
|
||||
const auto refusal = [&](const char* what, const std::vector<int64_t>& g3,
|
||||
int k, const char* pad, int stride, int causal,
|
||||
int reflect, int64_t yrows) {
|
||||
Hand z((std::string(what) + sfx).c_str(), "conv3d_ndhwc", tol);
|
||||
z.dense(dt, { 12, ci }, hfill(972))
|
||||
.dense(dt, { co, ci, (uint32_t)k, (uint32_t)k, (uint32_t)k }, hfill(973))
|
||||
.dense(dt, { co }, hfill(974))
|
||||
.idx(g3)
|
||||
.none()
|
||||
.dense(dt, { yrows, co }, zero, true)
|
||||
.pi("M", yrows).pi("cin", ci).pi("cout", co).pi("k", k).pi("kt", k)
|
||||
.ps("dtype", dn);
|
||||
if (stride != 1) z.pi("stride", stride);
|
||||
if (pad && *pad) z.ps("pad", pad);
|
||||
if (causal) z.pi("causal", causal);
|
||||
if (reflect) z.pi("reflect", reflect);
|
||||
z.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(z));
|
||||
};
|
||||
refusal("a stride with a 5-wide kernel is refused", { 2, 2, 3 }, 5, nullptr, 2, 0,
|
||||
0, 12);
|
||||
refusal("a reflect pad reaching an axis of 1 is refused", { 2, 1, 2 }, 3, nullptr,
|
||||
1, 1, 1, 4);
|
||||
refusal("a mirror pad is refused", { 2, 2, 3 }, 3, "mirror", 1, 0, 0, 12);
|
||||
refusal("y short of the strided output is refused", { 3, 4, 5 }, 3, "down", 2, 1,
|
||||
1, 7);
|
||||
refusal("a zero stride is refused", { 2, 2, 3 }, 3, nullptr, 0, 0, 0, 12);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- group_norm: stats f32 of exactly groups (2 + 3 1024) values --------------------- */
|
||||
@@ -3223,8 +3319,7 @@ void kv_cases(std::vector<Hand>& hs) {
|
||||
|
||||
/* Blocks 2 and 5 are resident; the selection names them, then 6 and 4. The epoch reaches both
|
||||
* hit slots, the misses are claimed once each and placed in ascending block order (4 then 6),
|
||||
* not in the order the rows name them. Pinned to the rule, so both libraries are held to it
|
||||
* and not only to each other. */
|
||||
* not in the order the rows name them. Pinned to the rule, not only to each other. */
|
||||
{
|
||||
Hand h = pool("hits take the epoch, misses land in block order", 2, 8, 4, 4, 8,
|
||||
{ 2, 5, 6, -1, 2, 4, -1, -1 }, { 3, 2 },
|
||||
@@ -3267,7 +3362,7 @@ void kv_cases(std::vector<Hand>& hs) {
|
||||
/* The heat counter, and the three shapes that separate it from a one-bit CLOCK. Slot 0 was hit
|
||||
* on two earlier calls (counter 2), slots 1 and 2 once each: a CLOCK sweep clears all three bits
|
||||
* and evicts slot 0 on its second pass, while 2 -> 1 -> 0 leaves slot 0 resident and takes slot
|
||||
* 1. Pinned to the victim, so both libraries are held to the rule and not only to each other. */
|
||||
* 1. Pinned to the victim. */
|
||||
{
|
||||
Hand h = pool("a slot hit twice survives two sweep passes", 1, 32, 3, 1, 8, { 20 }, { 1 },
|
||||
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1,
|
||||
@@ -3357,9 +3452,7 @@ void kv_cases(std::vector<Hand>& hs) {
|
||||
/* 2052 claims -- four rows of 513, which is what `--max-num-seqs 4` selects, and eight more than
|
||||
* the largest fixed list can hold. Every slot is free, so all 2052 are placed: ids 100..2099
|
||||
* take their own slot and the 52 past the ring (2100..2151) take the first free slots from the
|
||||
* hand, which are 0..51. Pinned, so both libraries are held to the placement and not only to
|
||||
* each other. The claim list is gathered from the selection, so the id space (`blocks`) is not
|
||||
* in the cost. */
|
||||
* hand, which are 0..51. Pinned to the placement. */
|
||||
{
|
||||
const int64_t M = 4, blocks = 4096, slots = 2100, pitch = 513, bbytes = 8, first = 100;
|
||||
std::vector<int64_t> sel, nsel((size_t)M, 513), res((size_t)blocks, -1),
|
||||
@@ -3380,8 +3473,8 @@ void kv_cases(std::vector<Hand>& hs) {
|
||||
* so the eight smallest ids are placed and the four largest revert to -1 with the
|
||||
* overflow latched. 1, 2, 3, 5 and 7 fit the ring and take their own slots; 9, 11 and 100 are
|
||||
* past it and take the first free slots from the hand, 0, then past the identity slots, 4 and
|
||||
* 6. The claim list cannot be clipped at the ring's depth -- the order the sweep takes is the
|
||||
* ascending order of the whole claim set. */
|
||||
* 6. The sweep's order is that of the whole claim set, so the list cannot be clipped at the
|
||||
* ring's depth first. */
|
||||
{
|
||||
Hand h = pool("12 claims in 8 slots place the eight smallest", 1, 4096, 8, 12, 8,
|
||||
{ 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 }, { 12 },
|
||||
@@ -3526,8 +3619,8 @@ void kvstream_cases(std::vector<Hand>& hs) {
|
||||
}
|
||||
/* The mirror's exact bytes, laid out by hand: four tokens fill both blocks at both offsets
|
||||
* with constants, so the paged layout [kv_heads][block_size][2 * head_dim] and the E4M3
|
||||
* encoding are pinned against an answer no library computes. Agreement alone cannot catch a
|
||||
* store that writes the right values at the wrong address or with the wrong scale. */
|
||||
* encoding are pinned against an answer no library computes: agreement alone cannot catch a
|
||||
* store that writes the right values to the wrong address or at the wrong scale. */
|
||||
{
|
||||
const int64_t blocks = 2, slots = 2, bs = 2, kvh = 1, hd = 2, M = 4;
|
||||
const int64_t lane = kvh * hd, row = kvh * bs * 2 * hd, span = M * 2 * lane;
|
||||
@@ -4535,6 +4628,26 @@ void audio_cases(std::vector<Hand>& hs) {
|
||||
.pi("causal", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
if (dt == (uint32_t)RAD_BF16) {
|
||||
/* The zero-padded strided form, bf16 only: one sequence, kernel 2 stride, pad
|
||||
* stride / 2, so 16 input rows give exactly 16 / stride output rows. */
|
||||
const int64_t cin = 20, cout = 13;
|
||||
for (const int64_t s : { 2, 4 }) {
|
||||
const int64_t k = 2 * s, in = 16, out = in / s;
|
||||
Hand h(("stride " + std::to_string(s) + ", even kernel, one sequence" + sfx)
|
||||
.c_str(),
|
||||
"conv1d", norm_tol);
|
||||
h.dense(dt, { in, cin }, hfill(350 + s))
|
||||
.dense(dt, { cout, cin, k }, hfill(356, 0.3f))
|
||||
.idx({ 0, in })
|
||||
.none()
|
||||
.dense(dt, { out, cout }, zero, true)
|
||||
.dense(dt, { cout }, hfill(357, 0.5f))
|
||||
.pi("M", in).pi("cin", cin).pi("cout", cout).pi("k", k).pi("dil", 1)
|
||||
.pi("stride", s).pi("pad", s / 2).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
}
|
||||
for (const int64_t s : { 2, 4 }) {
|
||||
/* A codec encoder's downsampling: kernel 2 stride, causal, the bounds in samples
|
||||
* (cu_div 8 input rows), two clips of 4 and 2 strides from input row 2 s. */
|
||||
|
||||
@@ -566,6 +566,37 @@ AVX_KERNEL(pool_rows) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pool_cols */
|
||||
/* As libref: the mean of every k consecutive columns of each row, summed in f32 and rounded to
|
||||
* y's dtype, then the multiplier and a second rounding (the unfused pair). pool_rows' dual.
|
||||
* Parallel over rows. */
|
||||
AVX_KERNEL(pool_cols) {
|
||||
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), k = p_int(a, "k", 0);
|
||||
const float mult = p_f32(a, "mult", 1.0f);
|
||||
if (n <= 0 || k <= 0 || n % k) return RAD_E_SHAPE;
|
||||
const int64_t M = rows_of(X, n), nw = n / k;
|
||||
if (M <= 0 || numel(Y) < M * nw) return RAD_E_SHAPE;
|
||||
const float inv = 1.0f / (float)k;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * nw * k >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
float* acc = scratch_f32((size_t)nw);
|
||||
float* sx = scratch_f32_b((size_t)n);
|
||||
const float* v = in_row(X, rowoff(X, r, n), n, sx);
|
||||
for (int64_t c = 0; c < nw; ++c) {
|
||||
float s = 0.0f;
|
||||
for (int64_t j = 0; j < k; ++j) s += v[c * k + j];
|
||||
acc[c] = s * inv;
|
||||
}
|
||||
roundtrip(Y->dtype, acc, nw, sx);
|
||||
for (int64_t c = 0; c < nw; ++c) acc[c] *= mult;
|
||||
out_row(Y, rowoff(Y, r, nw), nw, acc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ scale_rows */
|
||||
/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when the optional residual is passed.
|
||||
*
|
||||
|
||||
+93
-9
@@ -342,13 +342,18 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
const bool once = p_int(a, "norm_once", 0) != 0;
|
||||
const char* nk = p_str(a, "norm", "rms");
|
||||
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
|
||||
/* The optional trailing column map (slot 9 quantising, slot 7 plain): a sequence reads the
|
||||
* modulation table at its mapped row, so `s` and `g` may hold fewer rows than there are
|
||||
* sequences; the map's bound is the issuer's. */
|
||||
const RadTensor* cm = rad_arg_in(a, quant ? 9 : 7);
|
||||
if ((!layer && !none && std::strcmp(nk, "rms") != 0) || (none && W)) return RAD_E_INVAL;
|
||||
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 (cm && (cm->dtype != RAD_I32 || numel(cm) < n_seq)) return RAD_E_SHAPE;
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || (W && numel(W) < n) ||
|
||||
numel(S) < n_seq * 2 * n)
|
||||
(!cm && 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 (gated && (rows_of(Yv, n) < rows || (!cm && 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:
|
||||
@@ -358,13 +363,15 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
{
|
||||
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 e = 0; e < n_seq; ++e) {
|
||||
const int64_t col = cm ? (int64_t)ldt(cm, e) : e; /* the sequence's table row */
|
||||
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);
|
||||
row[i] = narrow1(dt, 1.0f + ldt(S, col * s_rs + (n + i) * s_cs));
|
||||
row[n + i] = ldt(S, col * s_rs + i * s_cs);
|
||||
if (gated) row[2 * n + i] = ldt(G, col * g_rs + i * g_cs);
|
||||
}
|
||||
}
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
tabs[n_seq * tw + i] = W ? ldt(W, i * laststride(W)) + wadd : 1.0f;
|
||||
}
|
||||
@@ -423,7 +430,10 @@ 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. */
|
||||
* calls: a pass embeds one row per entry, so this is a few thousand transcendentals. With
|
||||
* `curve` = G > 0 and a [G, n] f32 `table`, y[m] instead interpolates linearly between the
|
||||
* table's two rows around clamp01(max(t[m], clamp_min)) * (G - 1): a checkpoint's timestep
|
||||
* embedding precomputed on a grid, in place of the sinusoid and its MLP. */
|
||||
AVX_KERNEL(timestep_embed) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *T = &a->t[0], *Y = &a->t[1];
|
||||
@@ -431,16 +441,39 @@ AVX_KERNEL(timestep_embed) {
|
||||
const float scale = p_f32(a, "scale", 1000.0f);
|
||||
const double mp = p_f32(a, "max_period", 10000.0f);
|
||||
const int round = (int)p_int(a, "round", 0);
|
||||
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
|
||||
const float clamp = p_f32(a, "clamp_min", 0.0f);
|
||||
const int64_t grid = p_int(a, "curve", 0);
|
||||
if (n <= 0 || (!grid && (n & 1))) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || numel(T) < rows) return RAD_E_SHAPE;
|
||||
if (grid > 0) {
|
||||
const RadTensor* tab = rad_arg_in(a, 2);
|
||||
if (!tab) return RAD_E_INVAL;
|
||||
if (tab->dtype != (uint32_t)RAD_F32 || numel(tab) < grid * n) return RAD_E_SHAPE;
|
||||
float* buf = scratch_f32((size_t)n + 16);
|
||||
for (int64_t m = 0; m < rows; ++m) {
|
||||
const float tv = std::fmax(ldt(T, offlin(T, m)), clamp);
|
||||
const float pos = std::fmin(std::fmax(tv, 0.0f), 1.0f) * (float)(grid - 1);
|
||||
float i0f = std::floor(pos);
|
||||
if (i0f > (float)(grid - 2)) i0f = (float)(grid - 2);
|
||||
const float fr = pos - i0f;
|
||||
const int64_t i0 = (int64_t)i0f;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float a0 = ldt(tab, offlin(tab, i0 * n + i));
|
||||
const float a1 = ldt(tab, offlin(tab, (i0 + 1) * n + i));
|
||||
buf[i] = a0 + fr * (a1 - a0);
|
||||
}
|
||||
out_row(Y, rowoff(Y, m, n), n, buf);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
const int64_t h = n / 2;
|
||||
const float coef = (float)(-std::log(mp));
|
||||
float* buf = scratch_f32((size_t)(2 * n + 16));
|
||||
float *f = buf, *row = buf + n;
|
||||
for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h);
|
||||
for (int64_t m = 0; m < rows; ++m) {
|
||||
const float tv = ldt(T, offlin(T, m));
|
||||
const float tv = std::fmax(ldt(T, offlin(T, m)), clamp); /* clamp_min: a floor */
|
||||
const float tt = round == 3 ? narrow1(RAD_BF16, scale * narrow1(RAD_BF16, tv))
|
||||
: round == 2 ? scale * narrow1(RAD_BF16, tv)
|
||||
: round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
|
||||
@@ -912,6 +945,57 @@ AVX_KERNEL(flow_x0_step) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* x' = f32(f32(r x) + f32(hb1 d) + f32(hb2 x0)) when order >= 2, else the Euler form
|
||||
* f32(f32(r x) + f32((1 - r) d)), with d = f32(x + f32(sigma v)): libref's step bit for bit, `keep`
|
||||
* holding each product to its own rounding. x0 is the previous estimate (read here, d written back). */
|
||||
AVX_KERNEL(flow_res_multistep) {
|
||||
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *V = &a->t[0], *X0 = &a->t[1], *SG = &a->t[2], *RR = &a->t[3];
|
||||
const RadTensor *HB1 = &a->t[4], *HB2 = &a->t[5], *ORD = &a->t[6], *X = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, n);
|
||||
if (rows <= 0 || rows_of(V, n) < rows || rows_of(X0, n) < rows || numel(SG) < 1 ||
|
||||
numel(RR) < 1 || numel(HB1) < 1 || numel(HB2) < 1 || numel(ORD) < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const float sg = ldt(SG, offlin(SG, 0));
|
||||
const float r = ldt(RR, offlin(RR, 0));
|
||||
const float b1 = ldt(HB1, offlin(HB1, 0));
|
||||
const float b2 = ldt(HB2, offlin(HB2, 0));
|
||||
const bool two = ldt(ORD, offlin(ORD, 0)) >= 1.5f;
|
||||
const float omr = 1.0f - r;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < rows; ++k) {
|
||||
float* buf = scratch_f32((size_t)(5 * n + 64));
|
||||
float *vs = buf, *xs = buf + n + 16, *h0s = xs + n + 16, *o = h0s + n + 16, *o0 = o + 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 float* h0 = in_row(X0, rowoff(X0, k, n), n, h0s);
|
||||
const vf vsg = vf_set1(sg), vr = vf_set1(r), vb1 = vf_set1(b1), vb2 = vf_set1(b2),
|
||||
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(vsg, vf_loadu(v + c))));
|
||||
const vf a = keep(vf_mul(vr, xv));
|
||||
vf xo = two ? vf_add(vf_add(a, keep(vf_mul(vb1, d))), keep(vf_mul(vb2, vf_loadu(h0 + c))))
|
||||
: vf_add(a, keep(vf_mul(vo, d)));
|
||||
vf_storeu(o + c, xo);
|
||||
vf_storeu(o0 + c, d);
|
||||
}
|
||||
for (; c < n; ++c) {
|
||||
const float d = x[c] + keep(sg * v[c]);
|
||||
const float a = keep(r * x[c]);
|
||||
o[c] = two ? (a + keep(b1 * d)) + keep(b2 * h0[c]) : a + keep(omr * d);
|
||||
o0[c] = d;
|
||||
}
|
||||
out_row(X, rowoff(X, k, n), n, o);
|
||||
out_row(X0, rowoff(X0, k, n), n, o0);
|
||||
}
|
||||
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. */
|
||||
|
||||
+5
-4
@@ -87,9 +87,9 @@ int avx_par_force(int threads);
|
||||
X(scatter_rows) X(ngram_ids) \
|
||||
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
|
||||
X(scale_rows) X(scale) X(fill) X(act_mul) \
|
||||
X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \
|
||||
X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
|
||||
X(seg_sinusoid) X(conv2d_unfold) \
|
||||
X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \
|
||||
X(relu) X(clamp) X(conv2d) X(conv1d_dw) \
|
||||
X(rel_sinusoid) X(seg_sinusoid) X(conv2d_unfold) \
|
||||
/* ---- 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) \
|
||||
@@ -125,7 +125,8 @@ int avx_par_force(int threads);
|
||||
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) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \
|
||||
X(resize_bilinear) X(patch_fold) X(flow_renoise) \
|
||||
X(resize_bilinear) X(patch_fold) X(flow_renoise) X(flow_res_multistep) \
|
||||
X(cond_aug) X(vtile_plan) X(vtile_crop) X(vtile_join) \
|
||||
/* ---- LTX-2 */ \
|
||||
X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \
|
||||
X(d2s3d) X(s2d3d) X(pix_patch) \
|
||||
|
||||
+51
-123
@@ -1,47 +1,21 @@
|
||||
/* avx_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and
|
||||
* the ring slots its pool holds (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4).
|
||||
*
|
||||
* libref/ref_kvstream.cpp is the contract, and this file follows it line by line: the same
|
||||
* refusals in the same order, the same epoch, the same ascending miss order, the same victim from
|
||||
* the same CLOCK sweep over the same two-bit heat counter, so the same blocks land in the
|
||||
* same slots. That is the part a residency
|
||||
* map cannot get "close" on: `sel` becomes the attention's addressing, and two implementations
|
||||
* that agreed on residency but disagreed on a victim would read different KV for the same query.
|
||||
* libref/ref_kvstream.cpp is the contract, followed step for step: the same refusals in the same
|
||||
* order, the same epoch, miss order and CLOCK sweep over the same heat counter, so the same blocks
|
||||
* land in the same slots. A victim cannot be "close": `sel` becomes the attention's addressing.
|
||||
* A file of its own, as in libref, because the op belongs to no indexer: it moves bytes and keeps
|
||||
* state across calls.
|
||||
*
|
||||
* Why its own file rather than a section of avx_qsa.cpp: the op sits beside `qsa_select` in
|
||||
* docs/OPS.md but is not part of the indexer -- it walks no scores and rotates nothing, it moves
|
||||
* bytes and owns state across calls (epoch, hand, heat counters). libref keeps the same split
|
||||
* (ref_qsa.cpp / ref_kvstream.cpp), so the two libraries' files diff against each other.
|
||||
* The rewrite of a `sel` row (a gather of `res[b]`) and the block copy (a whole number of 16-byte
|
||||
* lanes at every cache layout) are vector work. The lookup/claim pass, the claim gather and the
|
||||
* sweep are serial by nature: two lanes naming one absent block would both claim it, two naming
|
||||
* one slot would race on its epoch, and the sweep's moving hand is the placement. They cost the
|
||||
* selection and the slots, never `blocks`, and the copies dominate a miss.
|
||||
*
|
||||
* ============================== what is and is not vector work ==============================
|
||||
*
|
||||
* The phases that can run wide do: the rewrite of a `sel` row (a gather of `res[b]` with the
|
||||
* negative results left in place) and the block copy (one block is a whole number of 16-byte lanes
|
||||
* at every cache layout, docs/OPS.md). The passes that cannot are the lookup/claim pass, the claim
|
||||
* gather and the CLOCK sweep, and none of them is a missed opportunity:
|
||||
*
|
||||
* the map is its own set (phase 2). Two lanes of one vector naming the same absent block would
|
||||
* both read -1 and both claim it, which is exactly the double claim -2 exists to prevent, and
|
||||
* two lanes naming the same resident slot would race on its epoch. The pass is one load and one
|
||||
* store per entry and is bounded by the selection, not by the cache. The claim gather and the
|
||||
* revert are the same pass twice more (`lookups` entries each) for the same reason: the list is a
|
||||
* fact about the selection, and the whole point of this form is that `blocks` -- the id space --
|
||||
* never enters a launch's cost.
|
||||
*
|
||||
* the sweep is a serial second-chance walk with a moving hand whose result is the placement
|
||||
* itself. Its cost is one pass over the slots per miss, and a miss is a cold block: the copies
|
||||
* dominate.
|
||||
*
|
||||
* No OpenMP anywhere: the op carries state from call to call (ctl's epoch, hand and counters), so
|
||||
* two of its launches must never overlap and one launch is a single serial unit of work. This is
|
||||
* why its row is absent from libr4d's concurrent prefix table; libavx's rows make no concurrency
|
||||
* promise at all.
|
||||
*
|
||||
* Scratch is the arena the other kernels use (avx_common.h), not RadArgs::scratch: the miss list
|
||||
* and the claim list are per-call temporaries, and the arena is already the plugin's answer for
|
||||
* one. The layout is `int32 miss_block[slots]`, `int32 miss_slot[slots]` -- what a device row
|
||||
* declares through RadKernelInfo::scratch -- followed by `int32 claim[lookups]`, the gathered claim
|
||||
* set this file needs only because it has no workgroup to sort in.
|
||||
* No OpenMP: the op's state makes one launch a serial unit, and two launches must never overlap.
|
||||
* Scratch is the arena (avx_common.h): `miss_block[slots]`, `miss_slot[slots]`, then
|
||||
* `claim[lookups]`, the gathered claim set this form sorts in place of a workgroup.
|
||||
*/
|
||||
#include "avx_common.h"
|
||||
#include "avx_vec.h"
|
||||
@@ -91,17 +65,11 @@ void kv_copy_block(uint8_t* dst, const uint8_t* src, int64_t n) {
|
||||
if (i < n) std::memcpy(dst + i, src + i, (size_t)(n - i));
|
||||
}
|
||||
|
||||
/* The claim list: every distinct block the selection claims, in block-id order. A claim exists only
|
||||
* where an entry names a block -- the lookup pass left it `-2` -- so the list is gathered from the
|
||||
* SELECTION, whose length is `lookups = sum_q nsel[q]`: a property of the call. It is deliberately
|
||||
* not a walk of `res` over `blocks`, which is the group's whole id space and says nothing about how
|
||||
* big one launch is. The map stays the dedup set: the first entry naming a claim marks it `-3`, so a
|
||||
* block several rows name enters the list once, and the marks are restored before the sweep sees the
|
||||
* map.
|
||||
*
|
||||
* The caller sorts the list; `cap` is the buffer's length and is `lookups` at least, because a
|
||||
* distinct claim costs at least one entry, so every claim is written. The contract needs the first
|
||||
* `slots` of that ascending order and nothing past them. */
|
||||
/* The claim list: every distinct block the selection claimed (left -2 by the lookup pass), in
|
||||
* selection order, gathered from the `lookups` entries rather than a walk of `res` over the id
|
||||
* space. The map stays the dedup set: the first entry naming a claim marks it -3, and the marks
|
||||
* are restored before the sweep. `cap` is at least `lookups`, so every claim fits; the caller
|
||||
* sorts the list and the contract needs only its first `slots`. */
|
||||
int64_t kv_claims(int32_t* res, int32_t* out, int64_t cap,
|
||||
const int32_t* sel, const int32_t* nsel, int64_t M, int64_t pitch) {
|
||||
int64_t n = 0;
|
||||
@@ -118,11 +86,9 @@ int64_t kv_claims(int32_t* res, int32_t* out, int64_t cap,
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Every claim the sweep could not place goes back to -1: the block is not resident, and the next
|
||||
* call may claim it again. A `res` entry still -2 here is by definition such a claim (a placed one
|
||||
* holds its slot), and it is named by at least one selection entry, so one pass over the selection
|
||||
* reaches all of them -- `lookups` entries instead of `blocks` map entries. The write is idempotent,
|
||||
* so entries that repeat a block are harmless. */
|
||||
/* Every claim the sweep could not place (still -2) goes back to -1, so a later call may claim it
|
||||
* again. Each is named by a selection entry, so one pass over the selection reaches all of them;
|
||||
* the write is idempotent. */
|
||||
void kv_relax_claims(int32_t* res, const int32_t* sel, const int32_t* nsel, int64_t M,
|
||||
int64_t pitch) {
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
@@ -132,14 +98,9 @@ void kv_relax_claims(int32_t* res, const int32_t* sel, const int32_t* nsel, int6
|
||||
}
|
||||
}
|
||||
|
||||
/* The rewrite: entry i becomes the slot holding its block, and an entry whose block could not be
|
||||
* placed becomes slot 0 -- a defined address inside the ring, because leaving the block id would
|
||||
* make the attention dereference past it. ctl[3] is what marks the table unusable ("Overflow" in
|
||||
* docs/OPS.md).
|
||||
*
|
||||
* The gather is safe by construction: the validation pass refused any entry outside [0, blocks)
|
||||
* before a byte was written. An entry at or past nsel[q] is never passed in, so `qsa_select`'s -1
|
||||
* padding survives. */
|
||||
/* The rewrite: each entry below nsel[q] becomes its block's slot, or slot 0 for a block that
|
||||
* could not be placed (the id would be an address past the ring; ctl[3] marks the table unusable).
|
||||
* The gather is safe: validation refused every entry outside [0, blocks). */
|
||||
void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) {
|
||||
int64_t i = 0;
|
||||
#if AVX_LEVEL >= 3
|
||||
@@ -148,9 +109,8 @@ void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) {
|
||||
const __m512i b = _mm512_loadu_si512((const void*)(row + i));
|
||||
const __m512i s = _mm512_mask_i32gather_epi32(zero, (__mmask16)0xFFFF, b,
|
||||
(const void*)res, 4);
|
||||
/* A gather that lands on a negative is a block this call could not place (-1) or one it
|
||||
* just claimed (-2): slot 0, not the id, exactly as the scalar tail writes it. Clamping
|
||||
* says that for the whole vector; masking the store instead would leave the id in place. */
|
||||
/* A negative gather (-1 unplaced, -2 claimed) becomes slot 0, as the scalar tail writes it:
|
||||
* clamping the whole vector, since a masked store would leave the id in place. */
|
||||
_mm512_storeu_si512((void*)(row + i), _mm512_max_epi32(s, zero));
|
||||
}
|
||||
#elif AVX_LEVEL >= 2
|
||||
@@ -159,7 +119,7 @@ void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) {
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
const __m256i b = _mm256_loadu_si256((const __m256i*)(row + i));
|
||||
const __m256i s = _mm256_mask_i32gather_epi32(zero, res, b, all, 4);
|
||||
/* s > -1 is s >= 0; a negative lane becomes 0 ("Overflow"), never the block id it holds. */
|
||||
/* s > -1 is s >= 0; a negative lane becomes 0, never the block id. */
|
||||
const __m256i ok = _mm256_cmpgt_epi32(s, all);
|
||||
_mm256_storeu_si256((__m256i*)(row + i), _mm256_blendv_epi8(zero, s, ok));
|
||||
}
|
||||
@@ -173,22 +133,8 @@ void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) {
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ kv_resolve */
|
||||
/* One call: bump the epoch; one lookup per distinct block (a hit stamps the slot with the epoch and
|
||||
* bumps its heat counter, an absent block becomes a claim and joins the miss list once); place one
|
||||
* victim per miss -- the block's own slot when its id fits the ring and that slot is free (a
|
||||
* context shorter than the ring maps block id to slot), otherwise a free slot first, then CLOCK from
|
||||
* the hand over the two-bit heat counter, which never takes a slot this call has stamped; re-point
|
||||
* both maps; copy each missed block from the mirror; rewrite every valid entry. `nsel` and the
|
||||
* attention's length are untouched:
|
||||
* a selection entry is an address, not a count.
|
||||
*
|
||||
* `kv_cache` is the RAD_KV operand the attention and `kv_store` take, and it is INOUT rather than
|
||||
* OUT: only the slots a miss lands in are written and every other slot of the ring must survive
|
||||
* for the blocks still resident there.
|
||||
*
|
||||
* An entry of a miss the sweep could not place is rewritten to slot 0, not left holding its block
|
||||
* id: on device the id is an address past the ring that `attn_paged` dereferences unchecked, and a
|
||||
* measured overflow must produce wrong numbers the caller discards (ctl[3]), not a fault. */
|
||||
/* One call, as libref's steps 1-7. `kv_cache` is inout: only the slots a miss lands in are
|
||||
* written, and every other slot keeps its resident block. */
|
||||
AVX_KERNEL(kv_resolve) {
|
||||
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *sel = &a->t[0], *nsel = &a->t[1], *res = &a->t[2], *sblk = &a->t[3];
|
||||
@@ -200,8 +146,7 @@ AVX_KERNEL(kv_resolve) {
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE;
|
||||
|
||||
/* The map and the counts are one format, written by one op and read by the writer and the
|
||||
* sweep: i32, dense. */
|
||||
/* The maps and counts are one format: i32, dense. */
|
||||
const RadTensor* const state[] = { sel, nsel, res, sblk, sst, ctl };
|
||||
for (const RadTensor* t : state)
|
||||
if (t->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
@@ -210,9 +155,8 @@ AVX_KERNEL(kv_resolve) {
|
||||
if (sel->stride[1] != 1 || sel->stride[0] != pitch) return RAD_E_STRIDE;
|
||||
if (numel(nsel) < M || nsel->stride[0] != 1) return RAD_E_SHAPE;
|
||||
if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE;
|
||||
/* The operand states the ring and the parameter is its declared ceiling, as `sel` states `M`
|
||||
* (libref/ref_kvstream.cpp, "The parameters"): the pool is planned after declare, so a ring the
|
||||
* engine sized smaller (--kv-resident) arrives as a shorter `slot_block`. */
|
||||
/* The operand states the ring, the parameter its declared ceiling: the pool is planned after
|
||||
* declare, so a ring --kv-resident sized smaller arrives as a shorter `slot_block`. */
|
||||
const int64_t slots = numel(sblk);
|
||||
if (slots < 1 || slots > slots_decl || sblk->stride[0] != 1) return RAD_E_SHAPE;
|
||||
if (sst->shape[0] < slots || sst->stride[1] != 1 || sst->stride[0] < 2) return RAD_E_STRIDE;
|
||||
@@ -220,8 +164,7 @@ AVX_KERNEL(kv_resolve) {
|
||||
if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE;
|
||||
if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE;
|
||||
|
||||
/* One block of one layer: the mirror's row and the pool's slot are the same bytes, and
|
||||
* `block_bytes` is both pitches -- the length of every copy. */
|
||||
/* The mirror's row and the pool's slot are both `block_bytes`, every copy's length. */
|
||||
int64_t hdense = 0, pdense = 0;
|
||||
if (kv_row_bytes(host, &hdense) != bbytes ||
|
||||
hdense * rad_dtype_bytes(host->dtype, 1) != bbytes)
|
||||
@@ -240,8 +183,8 @@ AVX_KERNEL(kv_resolve) {
|
||||
/* The counters are read and written as u64 inside an i32 block. */
|
||||
if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE;
|
||||
|
||||
/* ---- everything that can refuse, before anything is written; the entry count is summed here
|
||||
* so the counter and the claim list's length need no second look at `nsel` ---- */
|
||||
/* ---- everything that can refuse, before anything is written; the entry count summed here sizes
|
||||
* the counter and the claim list ---- */
|
||||
int64_t lookups = 0;
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
const int64_t n = NS[q];
|
||||
@@ -251,11 +194,9 @@ AVX_KERNEL(kv_resolve) {
|
||||
if (row[i] < 0 || row[i] >= blocks) return RAD_E_INVAL;
|
||||
lookups += n;
|
||||
}
|
||||
/* The map's own domain, over the whole of it. This is a state fault the contract refuses
|
||||
* (`-2` is never left by a call; a slot index outside the ring would address past it), not a
|
||||
* fallback: an entry the map holds and no selection entry names can only be found by looking
|
||||
* at the map, so this pass is `blocks` long in the reference and here alike. Everything that
|
||||
* acts on a claim is bounded by the selection, as above. */
|
||||
/* The map's own domain, over the whole map: a state fault the contract refuses, and only a
|
||||
* look at the map can find an entry no selection names. Everything acting on a claim is
|
||||
* bounded by the selection. */
|
||||
for (int64_t b = 0; b < blocks; ++b)
|
||||
if (R[b] < -1 || R[b] >= slots) return RAD_E_INVAL; /* -2 is never left by a call */
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
@@ -273,8 +214,7 @@ AVX_KERNEL(kv_resolve) {
|
||||
const int32_t b = row[i];
|
||||
const int32_t s = R[b];
|
||||
if (s >= 0) {
|
||||
/* The epoch stamps the slot; the heat counter gains one step, once a slot a call
|
||||
* (libref's step 2), so the counter measures calls that wanted the block. */
|
||||
/* Stamp the slot and bump its heat once a slot a call (libref's step 2). */
|
||||
if (ST[s * stp] != epoch) {
|
||||
ST[s * stp] = epoch;
|
||||
ST[s * stp + 1] = kv_heat_up(ST[s * stp + 1]);
|
||||
@@ -296,25 +236,18 @@ AVX_KERNEL(kv_resolve) {
|
||||
|
||||
/* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot
|
||||
* this call uses ---- */
|
||||
/* Identity first: a block whose id fits the ring and whose own slot is free goes there, so a
|
||||
* context shorter than the ring gets res[b] = b and the attention's run of adjacent ids reads
|
||||
* adjacent slots of one layer's stripe (libref's step 4; +2.07% at 16k, §26). It takes only a
|
||||
* free slot and does not move the hand, so it never evicts and the fallback below is the old
|
||||
* policy exactly, from the hand it would always have seen.
|
||||
*
|
||||
* Free before live: the ring's empty region fills before any resident block is evicted (see
|
||||
* libref's step 4). The free scan has no side effect when it finds nothing, so a full ring
|
||||
* takes the same CLOCK victim it always took. The count is what keeps a full ring from paying
|
||||
* that scan per miss: a placement makes a free slot live and an eviction re-points a live one,
|
||||
* so a zero count holds for the rest of the call. */
|
||||
/* Identity first (libref's step 4): a context shorter than the ring gets res[b] = b, so the
|
||||
* attention's adjacent ids read adjacent slots. It takes only a free slot and leaves the hand
|
||||
* alone. Then free slots before any resident block; the free scan changes nothing when it
|
||||
* finds nothing, and a zero free count holds for the rest of the call, so a full ring does not
|
||||
* pay the scan per miss. */
|
||||
int64_t free_left = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (SB[s] < 0 && ST[s * stp] != epoch) ++free_left;
|
||||
int64_t hand = C[1];
|
||||
int64_t placed = 0;
|
||||
/* More claims than the ring can hold means some miss was left unplaced by construction -- the
|
||||
* list here is the first `slots` of the claim set, so the sweep cannot discover it by running
|
||||
* out of misses -- and libref latches exactly that. */
|
||||
/* More claims than slots: some miss is unplaced by construction (the list is clipped at `slots`,
|
||||
* so the sweep cannot find out by running dry), and libref latches exactly that. */
|
||||
bool overflow = nclaims > slots;
|
||||
for (int64_t k = 0; k < nmiss; ++k) {
|
||||
const int32_t b = miss_block[k];
|
||||
@@ -348,8 +281,7 @@ AVX_KERNEL(kv_resolve) {
|
||||
}
|
||||
}
|
||||
if (victim < 0) {
|
||||
/* Every slot of the ring is stamped with this call's epoch: nothing left to take, and
|
||||
* taking a slot this call filled would break the table it is about to hand out. */
|
||||
/* Every slot is stamped by this call: taking one would break the table it hands out. */
|
||||
overflow = true;
|
||||
break;
|
||||
}
|
||||
@@ -376,22 +308,18 @@ AVX_KERNEL(kv_resolve) {
|
||||
for (int64_t q = 0; q < M; ++q) kv_rewrite_row(SE + q * pitch, NS[q], R);
|
||||
|
||||
/* ---- the bookkeeping ---- */
|
||||
/* Distinct blocks, counted from the slots this call stamped: a hit or a placed miss leaves the
|
||||
* call's epoch in its slot, and the misses it could not place are the rest of the union. Entry
|
||||
* counts would overcount, because many of a launch's rows share swaths of the history. */
|
||||
/* Distinct blocks: the slots this call stamped, plus the misses it could not place. Entry counts
|
||||
* would overcount, since rows share history. */
|
||||
int64_t used = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (ST[s * stp] == epoch) ++used;
|
||||
/* The union is over DISTINCT blocks, so it is the slots this call stamped plus the claims it
|
||||
* could not place -- exactly libref's count, and now that the whole claim set is known rather
|
||||
* than a list clipped at `slots`, an overflow reports the union it selected too. */
|
||||
/* libref's union, including a call that overflowed, since the whole claim set is known. */
|
||||
const int64_t uni = used + nclaims - placed;
|
||||
C[0] = epoch;
|
||||
C[1] = (int32_t)hand;
|
||||
C[2] = (int32_t)placed;
|
||||
if (overflow) C[3] = 1;
|
||||
/* The measured sizes: this call's selection union, the part of it that had to be copied in, and
|
||||
* the depth of its claim list. */
|
||||
/* The maxima: the union, the part copied in, and the claim list's depth. */
|
||||
if (uni > C[10]) C[10] = (int32_t)uni;
|
||||
if (placed > C[11]) C[11] = (int32_t)placed;
|
||||
if (nclaims > C[12]) C[12] = (int32_t)nclaims;
|
||||
|
||||
+59
-140
@@ -40,7 +40,6 @@
|
||||
#include <cstdlib>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
@@ -61,16 +60,6 @@
|
||||
|
||||
namespace {
|
||||
|
||||
/* Phase timers for one rank's gather, when RAD_PLE_TIMING is set: accumulated on the issuing
|
||||
* thread and printed by avx::row_gather. The ahead-reader thread accumulates and never prints. */
|
||||
struct PleTiming {
|
||||
bool on = std::getenv("RAD_PLE_TIMING") != nullptr;
|
||||
double find_ms = 0, pub_ms = 0, read_ms = 0, wait_ms = 0, dec_ms = 0, again_ms = 0;
|
||||
uint64_t enters = 0, bytes = 0;
|
||||
size_t spans = 0, hits = 0, claimed = 0, none = 0, theirs = 0;
|
||||
};
|
||||
thread_local PleTiming t_ple;
|
||||
|
||||
/* Prefetch distance, in rows, for cache lookups and decodes. Rows are scattered over an 80 MiB
|
||||
* cache and the set words over 4 MiB, so each is an L3 or DRAM miss. */
|
||||
constexpr long long kPrefetchRows = 8;
|
||||
@@ -292,12 +281,7 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) {
|
||||
* committed only as slots fill. */
|
||||
struct RowCache {
|
||||
static constexpr int kWays = 8;
|
||||
/* Slot count, overridable with RAD_PLE_CACHE_ROWS (rows, clamped to [2^16, 2^25]). Data cost
|
||||
* is `rows` * row bytes (160 at E4M3), so the shipped 2^19 rows is 80 MiB. The table's row
|
||||
* popularity is Zipfian: a larger cache holds a longer hot head of the distribution and
|
||||
* trades RAM directly for a lower miss rate on repeated traffic. Size it from measurement,
|
||||
* not the model -- RAD_PLE_TIMING prints the per-call hit counts the sweep reads. */
|
||||
static const uint64_t kRows;
|
||||
static constexpr uint64_t kRows = 1ull << 19;
|
||||
enum : uint64_t { EMPTY = 0, LOADING = 1, READY = 2 };
|
||||
|
||||
const TableFile* tf = nullptr;
|
||||
@@ -368,9 +352,8 @@ struct RowCache {
|
||||
}
|
||||
}
|
||||
|
||||
/* Where `key` sits, without claiming it: READY in *slot (decode from it), LOADING in *slot
|
||||
* (someone is reading it -- wait on the word), or ABSENT (*slot = -1; nobody has claimed the
|
||||
* row, so whoever wants it must hand it to a producer or claim it themselves). */
|
||||
/* Where `key` sits, without claiming it: HIT with *slot (decode from it), THEIRS with *slot (being
|
||||
* read), or NONE with *slot = -1. */
|
||||
Found lookup(uint64_t key, int64_t* slot) const {
|
||||
const uint64_t set = mix(key) & set_mask;
|
||||
const uint64_t s0 = set * kWays;
|
||||
@@ -384,11 +367,6 @@ struct RowCache {
|
||||
*slot = -1;
|
||||
return NONE;
|
||||
}
|
||||
|
||||
/* Read batches that failed outright (the ring refused, the disk errored): the consumers
|
||||
* waiting on those rows re-hand them to a producer, and this counter is how they notice that
|
||||
* their wait has a cause. */
|
||||
std::atomic<uint64_t> failed_reads{0};
|
||||
};
|
||||
|
||||
template <class T>
|
||||
@@ -399,21 +377,6 @@ T* anon_array(size_t count) {
|
||||
}
|
||||
|
||||
/* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */
|
||||
/* Defined out of line so the environment is read once, at first use. */
|
||||
const uint64_t RowCache::kRows = [] {
|
||||
unsigned long long v = 1ull << 19;
|
||||
if (const char* s = std::getenv("RAD_PLE_CACHE_ROWS")) {
|
||||
char* end = nullptr;
|
||||
const long long n = std::strtoll(s, &end, 10);
|
||||
if (end != s && n > 0) v = (uint64_t)n;
|
||||
}
|
||||
if (v < 1ull << 16) v = 1ull << 16;
|
||||
if (v > 1ull << 25) v = 1ull << 25;
|
||||
/* Whole sets: the set index is `mix(key) & set_mask` over kWays-way sets. */
|
||||
v -= v % kWays;
|
||||
return v;
|
||||
}();
|
||||
|
||||
RowCache* row_cache(const TableFile* tf, long long n) {
|
||||
static std::mutex mu;
|
||||
static std::vector<std::unique_ptr<RowCache>> caches;
|
||||
@@ -523,16 +486,6 @@ struct ReadRing {
|
||||
* one span per `stride` bytes, submitting and waiting in one call. Short reads fail. */
|
||||
int read_spans(const TableFile& tf, const SpanRead* r, unsigned count, long long n,
|
||||
long long stride, uint8_t* bounce) {
|
||||
if (!t_ple.on) return read_spans_now(tf, r, count, n, stride, bounce);
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const int s = read_spans_now(tf, r, count, n, stride, bounce);
|
||||
t_ple.read_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
t_ple.spans += count;
|
||||
return s;
|
||||
}
|
||||
int read_spans_now(const TableFile& tf, const SpanRead* r, unsigned count, long long n,
|
||||
long long stride, uint8_t* bounce) {
|
||||
const long long A = tf.align;
|
||||
unsigned tail = __atomic_load_n(sq_tail, __ATOMIC_RELAXED);
|
||||
for (unsigned i = 0; i < count; ++i) {
|
||||
@@ -549,7 +502,6 @@ struct ReadRing {
|
||||
s->user_data = (uint64_t)(e - a);
|
||||
sq_array[idx] = idx;
|
||||
++tail;
|
||||
t_ple.bytes += (uint64_t)(e - a);
|
||||
}
|
||||
__atomic_store_n(sq_tail, tail, __ATOMIC_RELEASE);
|
||||
int status = RAD_OK;
|
||||
@@ -557,7 +509,6 @@ struct ReadRing {
|
||||
while (got < count) {
|
||||
const long rc = syscall(__NR_io_uring_enter, fd, to_submit, count - got,
|
||||
IORING_ENTER_GETEVENTS, nullptr, (size_t)0);
|
||||
++t_ple.enters;
|
||||
if (rc < 0 && errno != EINTR && errno != EAGAIN && errno != EBUSY) return RAD_E_IO;
|
||||
if (rc > 0) to_submit -= (unsigned)rc < to_submit ? (unsigned)rc : to_submit;
|
||||
unsigned h = __atomic_load_n(cq_head, __ATOMIC_RELAXED);
|
||||
@@ -634,8 +585,6 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
|
||||
uint8_t* bounce = g.bounce_for((size_t)cnt * (size_t)stride, (size_t)A);
|
||||
const int rs = bounce ? rr.read_spans(tf, &reads[b], cnt, n, stride, bounce) : RAD_E_NOMEM;
|
||||
if (rs != RAD_OK) {
|
||||
rc.failed_reads.fetch_add(1, std::memory_order_release);
|
||||
rc.failed_reads.notify_all();
|
||||
for (size_t i = b; i < total; ++i)
|
||||
if (reads[i].slot >= 0)
|
||||
rc.word[reads[i].slot].store(RowCache::EMPTY, std::memory_order_release);
|
||||
@@ -656,9 +605,6 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
|
||||
std::memcpy(rc.data + (size_t)r.slot * (size_t)n, row, (size_t)n);
|
||||
rc.ref[r.slot].store(1, std::memory_order_relaxed);
|
||||
rc.word[r.slot].store(RowCache::ready(r.key), std::memory_order_release);
|
||||
/* Per-slot wakeup: a consumer waiting on THIS row proceeds now, without waiting for
|
||||
* the batch or the queue. Notify on a word nobody waits on costs a no-op futex wake. */
|
||||
rc.word[r.slot].notify_one();
|
||||
}
|
||||
rc.published.fetch_add(1, std::memory_order_release);
|
||||
rc.published.notify_all();
|
||||
@@ -668,16 +614,19 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The on-demand regime: decode steps want a hundred-odd rows now. The session's hot rows are
|
||||
* READY in the cache and decode from it; anything else is read straight from the file into its
|
||||
* output row -- no claims, no eviction bookkeeping, no queue round trip, no waiting on anybody.
|
||||
* Misses read here are deliberately not cached: the chunked prefill before decode has already
|
||||
* cached the prompt's rows, and a decode step's occasional new trigram is not worth a claim. */
|
||||
/* The decode regime: a step wants a hundred-odd rows now, and never waits on another thread's read.
|
||||
* Rows READY in the cache decode from it; a missing row whose slot is free to take is claimed and
|
||||
* read into the cache, so the ranks' gathers and the later steps that meet the same trigram find it
|
||||
* READY instead of reading the file again (Flash-Next decode at c4 lost 2.5% when these reads were
|
||||
* never cached); a row another thread is reading, or one with no slot, is read straight into its
|
||||
* output row. */
|
||||
constexpr long long kOnDemandMaxRows = 4096;
|
||||
|
||||
int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q,
|
||||
avx::RowDecode decode, const uint16_t* lut) {
|
||||
Gather& g = gather_state();
|
||||
const uint64_t me = owner_tag();
|
||||
if (!me) return RAD_E_UNSUPPORTED;
|
||||
const long long M = q.M, n = q.row_bytes, ne = q.n_embd, x_ld = q.x_ld;
|
||||
const long long base = tf.off + (long long)(q.tab - tf.lo);
|
||||
auto row_of = [&](long long m) { return (long long)q.ids[m] - q.voff; };
|
||||
@@ -686,36 +635,52 @@ int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::
|
||||
|
||||
g.src.clear();
|
||||
g.dst.clear();
|
||||
g.dm.clear();
|
||||
g.dw.clear();
|
||||
g.slot.resize((size_t)M);
|
||||
g.reads.clear();
|
||||
const auto tf0 = std::chrono::steady_clock::now();
|
||||
g.again.clear();
|
||||
for (long long m = 0; m < M; ++m) {
|
||||
uint16_t* dst = q.out + m * x_ld;
|
||||
if (pad(row_of(m))) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; }
|
||||
const uint64_t key = key_of(m);
|
||||
int64_t s = -1;
|
||||
if (rc.lookup(key, &s) == RowCache::HIT) {
|
||||
const RowCache::Found f = rc.find_or_claim(key, me, &s);
|
||||
g.slot[m] = s;
|
||||
if (f == RowCache::HIT) {
|
||||
g.src.push_back(rc.data + (size_t)s * (size_t)n);
|
||||
g.dst.push_back(dst);
|
||||
++t_ple.hits;
|
||||
continue;
|
||||
g.dm.push_back(m);
|
||||
g.dw.push_back(RowCache::ready(key));
|
||||
} else {
|
||||
/* THEIRS, MINE (a row twice in one call) and NONE are read directly: no wait. */
|
||||
g.reads.push_back({m, key, f == RowCache::CLAIMED ? s : -1});
|
||||
}
|
||||
g.reads.push_back({m, key, -1}); /* direct read, no claim */
|
||||
++t_ple.none;
|
||||
}
|
||||
t_ple.find_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tf0).count();
|
||||
if (!g.reads.empty()) {
|
||||
const auto tr0 = std::chrono::steady_clock::now();
|
||||
const int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
|
||||
t_ple.pub_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tr0).count();
|
||||
if (rs != RAD_OK) return rs;
|
||||
/* The claimed rows were published into the cache, not decoded: decode them from it. */
|
||||
for (const SpanRead& r : g.reads) {
|
||||
if (r.slot < 0) continue;
|
||||
g.src.push_back(rc.data + (size_t)r.slot * (size_t)n);
|
||||
g.dst.push_back(q.out + r.m * x_ld);
|
||||
g.dm.push_back(r.m);
|
||||
g.dw.push_back(RowCache::ready(r.key));
|
||||
}
|
||||
}
|
||||
const auto td0 = std::chrono::steady_clock::now();
|
||||
if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut);
|
||||
t_ple.dec_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - td0).count();
|
||||
return RAD_OK;
|
||||
if (g.src.empty()) return RAD_OK;
|
||||
/* The seqlock, as gather_rows reads it: a row whose word changed during the decode was taken
|
||||
* over, and is read again directly. */
|
||||
decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut);
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
for (size_t i = 0; i < g.dm.size(); ++i)
|
||||
if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i])
|
||||
g.again.push_back(g.dm[i]);
|
||||
if (g.again.empty()) return RAD_OK;
|
||||
g.reads.clear();
|
||||
for (long long m : g.again) g.reads.push_back({m, key_of(m), -1});
|
||||
return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
|
||||
}
|
||||
|
||||
/* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row
|
||||
@@ -723,8 +688,8 @@ int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::
|
||||
* decode from the cache. A row whose slot is taken over during the decode is read again directly. */
|
||||
int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q,
|
||||
long long first, avx::RowDecode decode, const uint16_t* lut) {
|
||||
/* Two regimes. A decode step wants a hundred-odd rows now: on-demand, direct, no queue. A
|
||||
* prefill chunk wants tens of thousands and has a known future: the producer-consumer queue. */
|
||||
/* A decode step's rows are read on demand; a prefill chunk's tens of thousands, whose future is
|
||||
* known, go through the claims and the read-ahead queue. */
|
||||
if (q.M <= kOnDemandMaxRows) return gather_ondemand(tf, rc, rr, q, decode, lut);
|
||||
Gather& g = gather_state();
|
||||
const uint64_t me = owner_tag();
|
||||
@@ -743,7 +708,6 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
|
||||
g.waits.clear();
|
||||
g.again.clear();
|
||||
|
||||
const auto tf0 = std::chrono::steady_clock::now();
|
||||
for (long long j = 0; j < M; ++j) {
|
||||
if (j + kPrefetchRows < M) {
|
||||
const long long mp = at(j + kPrefetchRows);
|
||||
@@ -756,27 +720,17 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
|
||||
const RowCache::Found f = rc.find_or_claim(key, me, &s);
|
||||
g.slot[m] = s;
|
||||
g.kind[m] = (uint8_t)f;
|
||||
if (f == RowCache::HIT) ++t_ple.hits;
|
||||
else if (f == RowCache::CLAIMED) ++t_ple.claimed;
|
||||
else if (f == RowCache::NONE) ++t_ple.none;
|
||||
else if (f == RowCache::THEIRS) ++t_ple.theirs;
|
||||
if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s});
|
||||
else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; }
|
||||
else if (f == RowCache::THEIRS) g.waits.push_back(m);
|
||||
}
|
||||
t_ple.find_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tf0).count();
|
||||
|
||||
const auto tp0 = std::chrono::steady_clock::now();
|
||||
int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
|
||||
t_ple.pub_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tp0).count();
|
||||
if (rs != RAD_OK) return rs;
|
||||
|
||||
/* Wait for rows other threads claimed to turn READY. `published` is read before the words, so
|
||||
* a batch landing after the scan makes the wait return at once. Released claims (failed reads)
|
||||
* and reused slots are read by this thread instead. */
|
||||
const auto tw0 = std::chrono::steady_clock::now();
|
||||
while (!g.waits.empty()) {
|
||||
const uint32_t e = rc.published.load(std::memory_order_acquire);
|
||||
size_t keep = 0;
|
||||
@@ -791,12 +745,9 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
|
||||
g.waits.resize(keep);
|
||||
if (keep) rc.published.wait(e, std::memory_order_acquire);
|
||||
}
|
||||
t_ple.wait_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tw0).count();
|
||||
|
||||
/* Decode all READY rows in one batch: each word is read before the bytes and again after the
|
||||
* batch (the seqlock), and rows whose word changed are read again. */
|
||||
const auto td0 = std::chrono::steady_clock::now();
|
||||
g.src.clear();
|
||||
g.dst.clear();
|
||||
g.dm.clear();
|
||||
@@ -819,17 +770,11 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
|
||||
for (size_t i = 0; i < g.dm.size(); ++i)
|
||||
if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i])
|
||||
g.again.push_back(g.dm[i]);
|
||||
t_ple.dec_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - td0).count();
|
||||
|
||||
if (g.again.empty()) return RAD_OK;
|
||||
const auto ta0 = std::chrono::steady_clock::now();
|
||||
g.reads.clear();
|
||||
for (long long m : g.again) g.reads.push_back({m, key_of(m), -1});
|
||||
const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
|
||||
t_ple.again_ms +=
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - ta0).count();
|
||||
return ra;
|
||||
return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
|
||||
}
|
||||
|
||||
/* ============================== the reader that runs a step ahead ==============================
|
||||
@@ -841,12 +786,9 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
|
||||
* missing rows while the chunk runs. The next call waits for LOADING rows as it would for the other
|
||||
* rank's.
|
||||
*
|
||||
* The queue is handed over sliced: each job carries at most `kJobRows` keys, claimed and published
|
||||
* one job at a time, in order. Claims are promises the consumer waits on (a slot LOADING for a row
|
||||
* it needs blocks the gather on the reader's progress), so a job must stay small: bounded claims
|
||||
* keep the promise horizon near, and a consumer that outruns the reader finds unclaimed rows it
|
||||
* can read itself instead of waiting behind the whole queue. Jobs keep the list's order, so the
|
||||
* nearest chunk's rows are always the reader's first work.
|
||||
* The rows go over in jobs of at most kJobRows keys, claimed and published one job at a time in
|
||||
* list order. A claim is a promise a gather may wait on, so jobs stay small: a gather that outruns
|
||||
* the reader finds unclaimed rows and reads them itself.
|
||||
*
|
||||
* Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims
|
||||
* and the next call reads those rows itself. The reader is detached and never destroyed. */
|
||||
@@ -855,17 +797,18 @@ struct AheadJob {
|
||||
RowCache* rc = nullptr;
|
||||
long long n = 0;
|
||||
std::vector<uint64_t> keys;
|
||||
bool retry = false; /* the keys a full set refused once already */
|
||||
};
|
||||
|
||||
/* One producer job's claim-read-publish sweep: ~2 ring batches, so the promise a job makes to a
|
||||
* consuming gather is paid in well under a second on any disk that can stream the table. */
|
||||
/* Keys per reader job, about two ring batches: a job's claims are promises a consuming gather may
|
||||
* wait on, so it stays short. */
|
||||
constexpr size_t kJobRows = 8192;
|
||||
|
||||
struct AheadReader {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::deque<AheadJob> urgent; /* a waiting consumer's own misses: served first */
|
||||
std::deque<AheadJob> q; /* the run-ahead queue: future chunks, in order */
|
||||
std::deque<AheadJob> urgent; /* keys a full set refused, tried once more first */
|
||||
std::deque<AheadJob> q; /* the read-ahead queue: future chunks, in order */
|
||||
uint64_t last = 0; /* hash of the last id list accepted */
|
||||
|
||||
void run() {
|
||||
@@ -881,10 +824,8 @@ struct AheadReader {
|
||||
else { j = std::move(q.front()); q.pop_front(); }
|
||||
}
|
||||
if (!rr || !me) continue;
|
||||
const auto t0 = t_ple.on ? std::chrono::steady_clock::now()
|
||||
: std::chrono::steady_clock::time_point();
|
||||
g.reads.clear();
|
||||
std::vector<uint64_t> retry; /* sets full of LOADING: claim again after a wave */
|
||||
std::vector<uint64_t> retry; /* sets full of LOADING rows: claim once more */
|
||||
for (size_t i = 0; i < j.keys.size(); ++i) {
|
||||
if (i + kPrefetchRows < j.keys.size())
|
||||
__builtin_prefetch(j.rc->set_line(j.keys[i + kPrefetchRows]));
|
||||
@@ -892,10 +833,8 @@ struct AheadReader {
|
||||
const auto f = j.rc->find_or_claim(j.keys[i], me, &slot);
|
||||
if (f == RowCache::CLAIMED)
|
||||
g.reads.push_back({0, j.keys[i], slot});
|
||||
else if (f == RowCache::NONE)
|
||||
else if (f == RowCache::NONE && !j.retry)
|
||||
retry.push_back(j.keys[i]);
|
||||
/* READY/HIT: already there (a rank's gather, or an earlier pass). MINE: ours
|
||||
* from an earlier pass -- published when its read lands. */
|
||||
}
|
||||
/* Every read has a slot, so nothing is decoded and there is no output. */
|
||||
(void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr,
|
||||
@@ -903,16 +842,10 @@ struct AheadReader {
|
||||
if (!retry.empty()) {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
AheadJob r;
|
||||
r.tf = j.tf; r.rc = j.rc; r.n = j.n; r.keys = std::move(retry);
|
||||
r.tf = j.tf; r.rc = j.rc; r.n = j.n; r.keys = std::move(retry); r.retry = true;
|
||||
urgent.push_front(std::move(r));
|
||||
cv.notify_one();
|
||||
}
|
||||
if (t_ple.on) {
|
||||
const double ms = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
std::fprintf(stderr, "ple[reader] keys %zu reads %zu %.1fms\n", j.keys.size(),
|
||||
g.reads.size(), ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -926,9 +859,8 @@ AheadReader* ahead_reader() {
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into
|
||||
* `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so
|
||||
* the nearest chunk's rows are its first work and a claim's promise horizon stays short. */
|
||||
/* Hands the rows of `q.ahead` (gathered by later calls) to the reader as kJobRows-key jobs in list
|
||||
* order, so the nearest chunk's rows come first. */
|
||||
void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) {
|
||||
uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc;
|
||||
for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; }
|
||||
@@ -993,7 +925,6 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
|
||||
if (!tfile) return ferr;
|
||||
#if defined(__linux__)
|
||||
if (tfile->fd >= 0) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
int why = 0;
|
||||
ReadRing* rr = read_ring(&why);
|
||||
if (!rr) {
|
||||
@@ -1007,18 +938,6 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
|
||||
const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0;
|
||||
const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut);
|
||||
if (rs != RAD_OK) return rs;
|
||||
const double wall =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
if (t_ple.on)
|
||||
std::fprintf(stderr,
|
||||
"ple[rank %lld] rows %lld: find %.1fms (hit %zu claimed %zu none %zu "
|
||||
"theirs %zu) pub %.1fms (ring %.1fms, %llu enters, %zu spans, "
|
||||
"%.1f MiB) wait %.1fms dec %.1fms again %.1fms | wall %.1fms\n",
|
||||
(long long)q.rank, (long long)q.M, t_ple.find_ms, t_ple.hits,
|
||||
t_ple.claimed, t_ple.none, t_ple.theirs, t_ple.pub_ms, t_ple.read_ms,
|
||||
(unsigned long long)t_ple.enters, t_ple.spans, t_ple.bytes / 1048576.0,
|
||||
t_ple.wait_ms, t_ple.dec_ms, t_ple.again_ms, wall);
|
||||
t_ple = {};
|
||||
/* Queue the rows a later call will gather, after this call's own rows. */
|
||||
if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q);
|
||||
return RAD_OK;
|
||||
|
||||
+69
-16
@@ -334,13 +334,9 @@ static const RadOperandSpec oKvStoreStreamed[] = { OPD("k"), OPD("v"), OPD("slot
|
||||
INOUT("kv_cache"), OPD("res"),
|
||||
INOUT("host") };
|
||||
|
||||
/* The residency map of a streamed group. Every operand is i32 state or a byte plane, so no dtype
|
||||
* parameter: the op is the same code at every cache layout. `kv_cache` is the same RAD_KV operand
|
||||
* (docs/OPS.md, `kv_resolve`) the attention and kv_store take, INOUT for the same reason kv_store's
|
||||
* is -- only the slots a miss lands in are written. No constraint either: `block_size` is
|
||||
* deliberately not a parameter here, because `Builder::find_kv_consumer` binds a KV group to the
|
||||
* first unclaimed op after it carrying `block_size`, and that must stay the resolved attention
|
||||
* kernel, not the op that only copies its pages. */
|
||||
/* The residency map of a streamed group: i32 state and byte planes, so no dtype parameter, and
|
||||
* no `block_size` (libref/ref_kvstream.cpp says why). `kv_cache` is inout: only the slots a miss
|
||||
* lands in are written. */
|
||||
static const RadParamSpec pKvResolve[] = { P_INT("M"), P_INT("blocks"), P_INT("slots"),
|
||||
P_INT("sel_pitch"), P_INT("block_bytes") };
|
||||
static const RadOperandSpec oKvResolve[] = { INOUT("sel"), OPD("nsel"), INOUT("res"),
|
||||
@@ -584,18 +580,22 @@ static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P
|
||||
P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("z") };
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("z"),
|
||||
OPD_O("colmap") };
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"),
|
||||
OUT_O("z") };
|
||||
OUT_O("z"), OPD_O("colmap") };
|
||||
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
|
||||
INOUT("x") };
|
||||
static const RadOperandSpec oFlowRM[] = { OPD("v"), INOUT("x0"), OPD("sigma"), OPD("r"),
|
||||
OPD("hb1"), OPD("hb2"), OPD("order"), INOUT("x") };
|
||||
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
|
||||
P_INTO("round"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
|
||||
P_INTO("round"), P_F64O("clamp_min"), P_INTO("curve"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y"), WGT_O("table") };
|
||||
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
|
||||
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") };
|
||||
@@ -653,6 +653,17 @@ static const RadParamSpec pVtileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("o
|
||||
P_INT("keep"), P_INT("blend"), P_INT("period"),
|
||||
P_STR("mean"), P_STR("std") };
|
||||
static const RadOperandSpec oVtileStitch[] = { OPD("x"), OPD("geom"), INOUT("prev"), OUT("y") };
|
||||
/* The tiled encoder (avx_video.cpp), as libref declares it: `geom` is the request's
|
||||
* (clip, H, W); plan and crop take it in pixels, join in latent units. */
|
||||
static const RadParamSpec pVtilePlan[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("ratio") };
|
||||
static const RadOperandSpec oVtilePlan[] = { OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pVtileCrop[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("ratio"), P_STR("dtype") };
|
||||
static const RadOperandSpec oVtileCrop[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pVtileJoin[] = { P_INT("M"), P_INT("tile"), P_INT("overlap"),
|
||||
P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oVtileJoin[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
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") };
|
||||
@@ -675,8 +686,9 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
|
||||
/* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes
|
||||
* patch_unfold's parameters and operands ------------------------------------------------------ */
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
|
||||
P_INTO("tpre") };
|
||||
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
|
||||
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
|
||||
P_INTO("reflect"), P_STRO("tpad"), P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
|
||||
OPD_O("res"), OUT("y") };
|
||||
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
|
||||
@@ -689,6 +701,9 @@ static const RadOperandSpec oResize[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") };
|
||||
static const RadParamSpec pCondAug[] = { P_INT("M"), P_INT("n"), P_INT("stream"), P_F64("aug"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oCondAug[] = { OPD("seed"), INOUT("x") };
|
||||
|
||||
/* ---- LTX-2 (avx_ltx.cpp) */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
@@ -739,7 +754,7 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
|
||||
/* ---- 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"), P_INTO("stride"),
|
||||
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
|
||||
P_INTO("cu_div") };
|
||||
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
|
||||
OUT("y"), WGT_O("b") };
|
||||
@@ -934,6 +949,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
|
||||
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
|
||||
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[m][c] = the mean of x[m]'s columns [c*k, c*k + k), rounded to y's dtype, times mult, rounded "
|
||||
"again." },
|
||||
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
|
||||
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
|
||||
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
|
||||
@@ -1199,6 +1217,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "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." },
|
||||
{ "flow_res_multistep", ARR(pMnD), ARR(oFlowRM),
|
||||
"d = x + sigma v, then x = r x + hb1 d + hb2 x0 (order 2) or r x + (1 - r) d (order 1), and "
|
||||
"d written back to x0; each product 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),
|
||||
@@ -1206,6 +1227,20 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "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." },
|
||||
{ "vtile_plan", ARR(pVtilePlan), ARR(oVtilePlan),
|
||||
"the tiled encoder's plan for one frame of geom = (clip, H, W) pixels: split_tiles_axis over "
|
||||
"the spatial axes in latent units (tile, overlap, pixels per latent ratio), tiles row-major; "
|
||||
"row t of the i32 [M, 22] y is the tile's first pixel (y0, x0), its pixel extent (th, tw) and "
|
||||
"level L's volume (1, th / 2^min(L, 4), tw / 2^min(L, 4)) for L = 0..5; M is the tile count." },
|
||||
{ "vtile_crop", ARR(pVtileCrop), ARR(oVtileCrop),
|
||||
"one frame's pixel plane [>= H W, 3] (geom = (clip, H, W) pixels) cut into vtile_plan's tiles: "
|
||||
"y [M, 3] the tiles' pixels tile-major, M the tiles' pixel count (sum of th tw)." },
|
||||
{ "vtile_join", ARR(pVtileJoin), ARR(oVtileJoin),
|
||||
"the tiled encoder's per-tile moments (vtile_crop's row layout at latent extent) blended into "
|
||||
"the canvas y [M, n], M = geom's (clip, lat_h, lat_w) lat_h lat_w: a canvas position's tile "
|
||||
"kept range, blended with the tile above and then the tile to the left, both RAW (never "
|
||||
"already blended), the products and sums rounding to x's dtype as the reference's bf16 blends "
|
||||
"do." },
|
||||
{ "grid_pos3", ARR(pGridPos3), ARR(oGridPos3),
|
||||
"a video decoder's rotary positions over its tiles, [3, >= M] at the operand's row pitch, bit "
|
||||
"for bit libref's." },
|
||||
@@ -1218,8 +1253,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
"and their `sel` tiles, blocked online softmax; the gated coarse term on the output rounded "
|
||||
"to its dtype." },
|
||||
{ "conv3d_ndhwc", ARR(pConv3d), ARR(oConv3d),
|
||||
"a 3-D convolution over voxel rows, `same` zero padding, PyTorch's [cout, cin, kt, k, k] "
|
||||
"weight, as GEMMs over bands of patch rows; with `res` (possibly y) rd(rd(acc + b) + res)." },
|
||||
"a 3-D convolution over voxel rows, PyTorch's [cout, cin, kt, k, k] weight, as GEMMs over "
|
||||
"bands of patch rows, `same` zero padding by default. `stride` and `stride_t` stride after "
|
||||
"the padding (3x3x3 only), `causal` 1 puts kt - 1 zero frames in front, `pad` `down` pads one "
|
||||
"row and column below and right only, `reflect` 1 mirrors the spatial padding. With `res` "
|
||||
"(possibly y) rd(rd(acc + b) + res)." },
|
||||
{ "group_norm", ARR(pGroupNorm), ARR(oGroupNorm),
|
||||
"a group norm over all rows, its statistics in f64 over fixed row blocks combined in order, "
|
||||
"then the optional [scale | shift] row and silu, one rounding; stats[0, 2 groups) the mean "
|
||||
@@ -1235,6 +1273,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise),
|
||||
"x = f32(f32(1 - s) x) + f32(s z), z the (seed, stream) normal stream at k n + c, bit for bit "
|
||||
"libref's." },
|
||||
{ "cond_aug", ARR(pCondAug), ARR(oCondAug),
|
||||
"x = f32(f32(a x) + f32(oma z)) with a the `aug` parameter and oma the f32 of the f64 1 - aug, "
|
||||
"z the (seed, stream) normal stream at k n + c, bit for bit libref's." },
|
||||
{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit),
|
||||
"LTX-2's split rotary over fractional coordinates, libref's arithmetic element by element." },
|
||||
{ "head_gate", ARR(pHeadGate), ARR(oHeadGate),
|
||||
@@ -1494,6 +1535,8 @@ SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's ro
|
||||
L(seg_mean)),
|
||||
SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
|
||||
DT_FLOAT, L(pool_rows)),
|
||||
SIMPLE("avx_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
|
||||
"multiplier", DT_FLOAT, L(pool_cols)),
|
||||
SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)),
|
||||
SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)),
|
||||
SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
|
||||
@@ -1776,6 +1819,8 @@ SIMPLE("avx_rms_mod_quant_fp8", "rms_mod_quant_fp8", "norm",
|
||||
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_flow_res_multistep", "flow_res_multistep", "elem",
|
||||
"a second-order sampler step on the clean estimate", DT_FLOAT, L(flow_res_multistep)),
|
||||
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",
|
||||
@@ -1783,6 +1828,12 @@ SIMPLE("avx_vtile_gather", "vtile_gather", "elem", "a video decoder's tiles out
|
||||
SIMPLE("avx_vtile_stitch", "vtile_stitch", "elem",
|
||||
"decoded tiles blended into frames, the chunk overlap, bytes out", DT_FLOAT,
|
||||
L(vtile_stitch)),
|
||||
SIMPLE("avx_vtile_plan", "vtile_plan", "elem", "the tiled encoder's per-tile geometry table",
|
||||
DT_ANY, L(vtile_plan)),
|
||||
SIMPLE("avx_vtile_crop", "vtile_crop", "elem", "a frame's pixel plane cut into encode tiles",
|
||||
DT_FLOAT, L(vtile_crop)),
|
||||
SIMPLE("avx_vtile_join", "vtile_join", "elem",
|
||||
"per-tile encoder moments blended into the latent canvas", DT_FLOAT, L(vtile_join)),
|
||||
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",
|
||||
@@ -1804,6 +1855,8 @@ SIMPLE("avx_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r
|
||||
L(patch_fold)),
|
||||
SIMPLE("avx_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma",
|
||||
DT_FLOAT, L(flow_renoise)),
|
||||
SIMPLE("avx_cond_aug", "cond_aug", "elem", "condition rows blended with fresh noise at a fixed aug",
|
||||
DT_FLOAT, L(cond_aug)),
|
||||
SIMPLE("avx_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT,
|
||||
L(rope_split)),
|
||||
SIMPLE("avx_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT,
|
||||
|
||||
+259
-25
@@ -1,7 +1,9 @@
|
||||
/* 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; and its latent upscaler's (docs/OPS.md, "The latent upscaler"): the 3-D convolution,
|
||||
* tokens; the encoder's plan, cut and blend for a picture too big for one volume (docs/OPS.md,
|
||||
* "Video generation"); and its latent upscaler's (docs/OPS.md, "The latent upscaler"): the 3-D
|
||||
* convolution,
|
||||
* the group norm, the temporal depthwise convolution, the per-frame resize, the fold back into
|
||||
* patch rows and the re-noising.
|
||||
*
|
||||
@@ -123,6 +125,19 @@ bool split_tiles(int64_t len, int64_t tile, int64_t overlap, std::vector<int64_t
|
||||
return true;
|
||||
}
|
||||
|
||||
/* libref's split_tiles_axis: the decoder's split, except that an axis no longer than a tile is one
|
||||
* tile, short if need be. */
|
||||
bool split_tiles_axis(int64_t len, int64_t tile, int64_t overlap, std::vector<int64_t>* start,
|
||||
std::vector<int64_t>* ov) {
|
||||
if (tile >= len) {
|
||||
start->clear();
|
||||
ov->clear();
|
||||
start->push_back(0);
|
||||
return len > 0 && tile > 0 && overlap >= 0 && overlap < tile;
|
||||
}
|
||||
return split_tiles(len, tile, overlap, start, ov);
|
||||
}
|
||||
|
||||
/* 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,
|
||||
@@ -440,19 +455,178 @@ AVX_KERNEL(vtile_stitch) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the tiled encoder
|
||||
* The plan, the cut and the blend of vae.py's `tiled_encode` (libref's section comment). */
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_plan */
|
||||
/* The plan one frame's encode runs over (libref): geom = (clip, H, W) the frame's extent in
|
||||
* pixels, split by split_tiles_axis over the spatial axes in latent units; row t of y (i32
|
||||
* [M, 22]) the tile's first pixel, its pixel extent, and the six level volumes. */
|
||||
/* The tile count comes from G; the ranged `M` is a ceiling only (band_rows). */
|
||||
AVX_KERNEL(vtile_plan) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
|
||||
const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0);
|
||||
if (tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = at(G, 1), W = at(G, 2);
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (H <= 0 || W <= 0 || H % ratio || W % ratio ||
|
||||
!split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) ||
|
||||
!split_tiles_axis(W / ratio, tile, overlap, &sx, &ox))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
|
||||
const int64_t M = band_rows(nh * nw, band);
|
||||
if (M <= 0 || rows_of(Y, 22) < M) return RAD_E_SHAPE;
|
||||
const int64_t* psy = sy.data(), *psx = sx.data();
|
||||
AVX_PARALLEL_FOR_IF(M >= AVX_PAR_MIN)
|
||||
for (int64_t t = 0; t < M; ++t) {
|
||||
const int64_t i = t / nw, j = t % nw;
|
||||
const int64_t th = std::min(tile, H / ratio - psy[(size_t)i]) * ratio;
|
||||
const int64_t tw = std::min(tile, W / ratio - psx[(size_t)j]) * ratio;
|
||||
const int64_t yb = rowoff(Y, t, 22), ys = laststride(Y);
|
||||
const int64_t v[22] = { psy[(size_t)i] * ratio, psx[(size_t)j] * ratio, th, tw,
|
||||
1, th, tw, 1, th / 2, tw / 2, 1, th / 4, tw / 4,
|
||||
1, th / 8, tw / 8, 1, th / 16, tw / 16, 1, th / 16, tw / 16 };
|
||||
for (int64_t c = 0; c < 22; ++c) st_int_dt(Y->dtype, Y->data, yb + c * ys, v[c]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_crop */
|
||||
/* One frame's pixel plane cut into the plan's tiles (libref): y f32 [M, 3] holds the tiles'
|
||||
* pixels tile-major, M the tiles' pixel count. Only the row the tile stands on is read. */
|
||||
AVX_KERNEL(vtile_crop) {
|
||||
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 band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
|
||||
const int64_t overlap = p_int(a, "overlap", 0), ratio = p_int(a, "ratio", 0);
|
||||
if (tile <= 0 || overlap < 0 || overlap >= tile || ratio <= 0 || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = at(G, 1), W = at(G, 2);
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (H <= 0 || W <= 0 || H % ratio || W % ratio ||
|
||||
!split_tiles_axis(H / ratio, tile, overlap, &sy, &oy) ||
|
||||
!split_tiles_axis(W / ratio, tile, overlap, &sx, &ox))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
|
||||
std::vector<int64_t> off((size_t)(nh * nw + 1), 0);
|
||||
for (int64_t i = 0; i < nh; ++i) {
|
||||
const int64_t th = std::min(tile, H / ratio - sy[(size_t)i]) * ratio;
|
||||
for (int64_t j = 0; j < nw; ++j)
|
||||
off[(size_t)(i * nw + j + 1)] =
|
||||
off[(size_t)(i * nw + j)] +
|
||||
th * std::min(tile, W / ratio - sx[(size_t)j]) * ratio;
|
||||
}
|
||||
const int64_t M = band_rows(off.back(), band);
|
||||
if (M <= 0 || rows_of(X, 3) < H * W || rows_of(Y, 3) < M) return RAD_E_SHAPE;
|
||||
const int64_t* psy = sy.data(), *psx = sx.data(), *poff = off.data();
|
||||
AVX_PARALLEL_FOR_IF(M * 3 >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
const int64_t t =
|
||||
(int64_t)(std::upper_bound(poff, poff + nh * nw + 1, r) - poff) - 1;
|
||||
const int64_t i = t / nw, j = t % nw;
|
||||
const int64_t tw = std::min(tile, W / ratio - psx[(size_t)j]) * ratio;
|
||||
const int64_t k = r - poff[t];
|
||||
const int64_t src = (psy[(size_t)i] * ratio + k / tw) * W + psx[(size_t)j] * ratio + k % tw;
|
||||
const int64_t xb = rowoff(X, src, 3), yb = rowoff(Y, r, 3), xs = laststride(X);
|
||||
const int64_t ys = laststride(Y);
|
||||
for (int64_t c = 0; c < 3; ++c) stt(Y, yb + c * ys, ldt(X, xb + c * xs));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vtile_join */
|
||||
/* The tiles' moments blended into one latent plane (libref): unblended neighbours, the top blend
|
||||
* before the left one, every product and sum rounded to x's dtype. */
|
||||
AVX_KERNEL(vtile_join) {
|
||||
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 band = p_int(a, "M", 0), tile = p_int(a, "tile", 0);
|
||||
const int64_t overlap = p_int(a, "overlap", 0), n = p_int(a, "n", 0);
|
||||
if (tile <= 0 || overlap < 0 || overlap >= tile || n <= 0 || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t H = at(G, 1), W = at(G, 2);
|
||||
std::vector<int64_t> sy, sx, oy, ox;
|
||||
if (H <= 0 || W <= 0 || !split_tiles_axis(H, tile, overlap, &sy, &oy) ||
|
||||
!split_tiles_axis(W, tile, overlap, &sx, &ox))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nh = (int64_t)sy.size(), nw = (int64_t)sx.size();
|
||||
const int64_t M = band_rows(H * W, band);
|
||||
std::vector<int64_t> off((size_t)(nh * nw + 1), 0);
|
||||
for (int64_t i = 0; i < nh; ++i) {
|
||||
const int64_t th = std::min(tile, H - sy[(size_t)i]);
|
||||
for (int64_t j = 0; j < nw; ++j)
|
||||
off[(size_t)(i * nw + j + 1)] =
|
||||
off[(size_t)(i * nw + j)] + th * std::min(tile, W - sx[(size_t)j]);
|
||||
}
|
||||
if (M <= 0 || rows_of(X, n) < off.back() || rows_of(Y, n) < M) return RAD_E_SHAPE;
|
||||
/* The owner tile of every canvas row and column. */
|
||||
std::vector<int64_t> own_y((size_t)H), own_x((size_t)W);
|
||||
for (int64_t Yp = 0, i = 0; Yp < H; ++Yp) {
|
||||
while (i + 1 < nh && Yp >= sy[(size_t)(i + 1)]) ++i;
|
||||
own_y[(size_t)Yp] = i;
|
||||
}
|
||||
for (int64_t X0 = 0, j = 0; X0 < W; ++X0) {
|
||||
while (j + 1 < nw && X0 >= sx[(size_t)(j + 1)]) ++j;
|
||||
own_x[(size_t)X0] = j;
|
||||
}
|
||||
const uint32_t dt = X->dtype;
|
||||
auto rd = [dt](float v) { return narrow1(dt, v); };
|
||||
auto wb = [&](int64_t p, int64_t e) { return rd((float)p / (float)e); };
|
||||
auto wa = [&](int64_t p, int64_t e) { return rd(1.0f - rd((float)p / (float)e)); };
|
||||
const int64_t* psy = sy.data(), *psx = sx.data(), *poff = off.data();
|
||||
const int64_t* pown_y = own_y.data(), *pown_x = own_x.data();
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
auto T = [&](int64_t i, int64_t j, int64_t ly, int64_t lx, int64_t c) {
|
||||
const int64_t row = poff[i * nw + j] + ly * std::min(tile, W - psx[(size_t)j]) + lx;
|
||||
return ldt(X, rowoff(X, row, n) + c * xs);
|
||||
};
|
||||
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
const int64_t Yp = r / W, X0 = r % W;
|
||||
const int64_t i = pown_y[Yp], j = pown_x[X0];
|
||||
const int64_t ly = Yp - psy[(size_t)i], lx = X0 - psx[(size_t)j];
|
||||
const int64_t ev = i > 0 ? oy[(size_t)(i - 1)] : 0, eh = j > 0 ? ox[(size_t)(j - 1)] : 0;
|
||||
const int64_t yb = rowoff(Y, r, n);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
float v = T(i, j, ly, lx, c);
|
||||
if (ly < ev)
|
||||
v = rd(rd(T(i - 1, j, ly + tile - ev, lx, c) * wa(ly, ev)) +
|
||||
rd(v * wb(ly, ev)));
|
||||
if (lx < eh)
|
||||
v = rd(rd(T(i, j - 1, ly, lx + tile - eh, c) * wa(lx, eh)) +
|
||||
rd(v * wb(lx, eh)));
|
||||
stt(Y, yb + c * ys, v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the latent upscaler
|
||||
* Voxel rows (t, i, j) of a T x H x W volume, channels innermost, the volume in `geom`. */
|
||||
|
||||
/* Division rounding toward negative infinity, as PyTorch's output-length formula takes it. */
|
||||
static int64_t idiv_floor(int64_t x, int64_t d) {
|
||||
const int64_t q = x / d;
|
||||
return (x % d && (x < 0) != (d < 0)) ? q - 1 : q;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv3d_ndhwc */
|
||||
/* A 3-D convolution as GEMMs over bands of patch rows, as conv2d_nhwc and conv1d take theirs. The
|
||||
* weight [cout, cin, kt, k, k] is re-laid once a launch as [cout][dt][kh][kw][cin] (bf16 copies
|
||||
* when it is bf16, f32 otherwise), so an output voxel's patch row is its kt k k input voxels'
|
||||
* channel runs back to back, zeros outside the volume: bf16 copies when x is bf16 with dense
|
||||
* rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias added there; each row
|
||||
* is then rounded once into y, or with `res` rounded to y's dtype, its residual row added and
|
||||
* rounded again. A band's residual rows are read before its rows of y are written, row by row,
|
||||
* so `res` may be y. The patches and the weight live in thread_local vectors that keep their
|
||||
* high-water size, leaving the GEMM's scratch arenas to it. */
|
||||
* channel runs back to back, zeros outside the volume (or `reflect`'s mirror): bf16 copies when x
|
||||
* is bf16 with dense rows, f32 otherwise. A band is one gemm_nt_into into f32 rows, the bias
|
||||
* added there; each row is then rounded once into y, or with `res` rounded to y's dtype, its
|
||||
* residual row added and rounded again. A band's residual rows are read before its rows of y are
|
||||
* written, row by row, so `res` may be y. The patches and the weight live in thread_local vectors
|
||||
* that keep their high-water size, leaving the GEMM's scratch arenas to it.
|
||||
*
|
||||
* The optional `stride`, `stride_t`, `causal`, `pad` and `reflect` are a causal video VAE's
|
||||
* convolution forms (libref's ref_conv3d_ndhwc, docs/OPS.md): output voxel (t, i, j) of the
|
||||
* T2 x H2 x W2 grid reads the input voxels from (t sz - pz0, i sy - py0, j sy - px0). */
|
||||
AVX_KERNEL(conv3d_ndhwc) {
|
||||
if (a->n_t < 6 || !rad_args_have(a, 4) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3];
|
||||
@@ -468,11 +642,33 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 ||
|
||||
numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t sy = p_int(a, "stride", 1), sz = p_int(a, "stride_t", 1);
|
||||
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
|
||||
const char* pads = p_str(a, "pad", "same");
|
||||
const bool down = pads && !std::strcmp(pads, "down");
|
||||
if (sy <= 0 || sz <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
|
||||
(causal && tpad) /* `causal` pads with zeros, `tpad` with copies */ ||
|
||||
!(!pads || !std::strcmp(pads, "same") || down))
|
||||
return RAD_E_SHAPE;
|
||||
const bool gen = sy != 1 || sz != 1 || causal || down || reflect;
|
||||
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
|
||||
const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2);
|
||||
if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = (T + tpre) * H * Wd, taps = kt * k * k, KK = taps * cin;
|
||||
if (rows_of(Y, cout) < rows || rows_of(X, cin) < T * H * Wd ||
|
||||
(R && rows_of(R, cout) < rows) || numel(W) < cout * KK || numel(B) < cout)
|
||||
/* The pads before (0) and after (1) each axis. `tpad` replicate centres the window as `zero`
|
||||
* does and clamps the reads to the volume; `tpad` causal puts kt - 1 + tpre copies of the
|
||||
* first frame in front, T + tpre frames out, the grid `causal` takes with zeros. */
|
||||
const int64_t pz0 = causal ? kt - 1 : tpad == 2 ? kt - 1 + tpre : kt / 2;
|
||||
const int64_t pz1 = (causal || tpad == 2) ? 0 : kt / 2;
|
||||
const int64_t py0 = down ? 0 : k / 2, py1 = down ? 1 : k / 2;
|
||||
const int64_t px0 = down ? 0 : k / 2, px1 = down ? 1 : k / 2;
|
||||
if (reflect && (std::max(py0, py1) >= H || std::max(px0, px1) >= Wd)) return RAD_E_SHAPE;
|
||||
const int64_t T2 = idiv_floor(T + pz0 + pz1 - kt, sz) + 1;
|
||||
const int64_t H2 = idiv_floor(H + py0 + py1 - k, sy) + 1;
|
||||
const int64_t W2 = idiv_floor(Wd + px0 + px1 - k, sy) + 1;
|
||||
if (T2 <= 0 || H2 <= 0 || W2 <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = T * H * Wd, orows = T2 * H2 * W2, taps = kt * k * k, KK = taps * cin;
|
||||
if (rows_of(Y, cout) < orows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < orows) ||
|
||||
numel(W) < cout * KK || numel(B) < cout)
|
||||
return RAD_E_SHAPE;
|
||||
static thread_local std::vector<uint8_t> wbuf, pbuf;
|
||||
static thread_local std::vector<float> ybuf;
|
||||
@@ -497,25 +693,29 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
const size_t ael = x16 ? 2 : 4;
|
||||
const int64_t want = std::min<int64_t>((int64_t)1 << 25,
|
||||
std::max<int64_t>((int64_t)1 << 23, 8 * cout * KK));
|
||||
const int64_t band = std::max<int64_t>(1, std::min(rows, want / KK));
|
||||
const int64_t band = std::max<int64_t>(1, std::min(orows, want / KK));
|
||||
pbuf.resize((size_t)(band * KK) * ael + 64);
|
||||
ybuf.resize((size_t)(band * cout) + 16);
|
||||
char* pp = (char*)pbuf.data();
|
||||
float* yp = ybuf.data();
|
||||
const int64_t pz = kt / 2, ps = k / 2;
|
||||
for (int64_t r0 = 0; r0 < rows; r0 += band) {
|
||||
const int64_t nb = std::min(band, rows - r0);
|
||||
for (int64_t r0 = 0; r0 < orows; r0 += band) {
|
||||
const int64_t nb = std::min(band, orows - r0);
|
||||
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
|
||||
for (int64_t pr = 0; pr < nb; ++pr) {
|
||||
const int64_t r = r0 + pr, t = r / (H * Wd), i = (r / Wd) % H, j = r % Wd;
|
||||
char* d = pp + (size_t)(pr * KK) * ael;
|
||||
for (int64_t br = 0; br < nb; ++br) {
|
||||
const int64_t r = r0 + br, t = r / (H2 * W2), i = (r / W2) % H2, j = r % W2;
|
||||
char* d = pp + (size_t)(br * KK) * ael;
|
||||
for (int64_t dz = 0; dz < kt; ++dz)
|
||||
for (int64_t kh = 0; kh < k; ++kh)
|
||||
for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) {
|
||||
int64_t tz = t + dz - pz;
|
||||
if (tpad == 1) tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
|
||||
else if (tpad == 2) tz = std::max<int64_t>(t + dz - (kt - 1) - tpre, 0);
|
||||
const int64_t iy = i + kh - ps, ix = j + kw - ps;
|
||||
int64_t tz = t * sz + dz - pz0;
|
||||
if (tpad) /* copies of the edge frame; `zero` and `causal` read zeros */
|
||||
tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
|
||||
int64_t iy = i * sy + kh - py0;
|
||||
int64_t ix = j * sy + kw - px0;
|
||||
if (reflect) { /* PyTorch's reflect: the edge itself is not repeated */
|
||||
if (iy < 0) iy = -iy; else if (iy >= H) iy = 2 * H - 2 - iy;
|
||||
if (ix < 0) ix = -ix; else if (ix >= Wd) ix = 2 * Wd - 2 - ix;
|
||||
}
|
||||
if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) {
|
||||
std::memset(d, 0, (size_t)cin * ael);
|
||||
continue;
|
||||
@@ -534,16 +734,16 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
const int st = gemm_nt_into(&pt, &wt, B, &yt, nb, cout, KK);
|
||||
if (st < 0) return st;
|
||||
AVX_PARALLEL_FOR_IF(nb * cout >= AVX_PAR_MIN)
|
||||
for (int64_t pr = 0; pr < nb; ++pr) {
|
||||
float* row = yp + pr * cout;
|
||||
for (int64_t br = 0; br < nb; ++br) {
|
||||
float* row = yp + br * cout;
|
||||
if (R) {
|
||||
float* buf = scratch_f32((size_t)(2 * cout + 32));
|
||||
float *tmp = buf, *rs = buf + cout + 16;
|
||||
narrow_row(Y->dtype, row, cout, tmp);
|
||||
const float* rr = in_row(R, rowoff(R, r0 + pr, cout), cout, rs);
|
||||
const float* rr = in_row(R, rowoff(R, r0 + br, cout), cout, rs);
|
||||
for (int64_t c = 0; c < cout; ++c) row[c] += rr[c];
|
||||
}
|
||||
out_row(Y, rowoff(Y, r0 + pr, cout), cout, row);
|
||||
out_row(Y, rowoff(Y, r0 + br, cout), cout, row);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -797,3 +997,37 @@ AVX_KERNEL(flow_renoise) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cond_aug */
|
||||
/* A visual condition's rows blended with noise (libref's ref_cond_aug, bit for bit):
|
||||
* x = f32(f32(a x) + f32(oma z)), oma the f32 of the f64 1 - aug, z the (seed, stream) normal
|
||||
* stream at k n + c. */
|
||||
AVX_KERNEL(cond_aug) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *SD = &a->t[0], *X = &a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0), sm = p_int(a, "stream", 0);
|
||||
const RadParam* ap = p_find(a, "aug");
|
||||
if (!ap || ap->kind != RAD_P_F64) return RAD_E_SHAPE;
|
||||
const double aug = ap->dval;
|
||||
if (n <= 0 || sm < 0 || !(aug >= 0.0 && aug < 1.0) || numel(SD) < 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, n);
|
||||
if (rows <= 0) return RAD_E_SHAPE;
|
||||
const float av = (float)aug, omv = (float)(1.0 - aug);
|
||||
const uint64_t sd = (uint64_t)(uint32_t)at(SD, 0) | ((uint64_t)(uint32_t)at(SD, 1) << 32);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n * 8 >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < rows; ++k) {
|
||||
float* buf = scratch_f32((size_t)(3 * n + 48));
|
||||
float *xs = buf, *z = xs + n + 16, *o = z + n + 16;
|
||||
const float* x = in_row(X, rowoff(X, k, n), n, xs);
|
||||
philox_normals_s(sd, (uint64_t)sm, (uint64_t)(k * n), n, z);
|
||||
const vf va = vf_set1(av), vo = vf_set1(omv);
|
||||
int64_t c = 0;
|
||||
for (; c + VF_N <= n; c += VF_N)
|
||||
vf_storeu(o + c, vf_add(keep(vf_mul(va, vf_loadu(x + c))),
|
||||
keep(vf_mul(vo, vf_loadu(z + c)))));
|
||||
for (; c < n; ++c) o[c] = keep(av * x[c]) + keep(omv * z[c]);
|
||||
out_row(X, rowoff(X, k, n), n, o);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
Reference in new issue
Block a user