From 8a993b7de9bb2932f4fb5a36d0878a9a1aa5efe5 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 20:29:59 +0200 Subject: [PATCH 01/35] libavx: spread the 5-bit codes without _pdep_u64 -- BMI2 is not in level 3's flag set, and clang refuses to inline the intrinsic without it --- libavx/avx_gemm_tile.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libavx/avx_gemm_tile.cpp b/libavx/avx_gemm_tile.cpp index e8a4bfa1..6e5057bf 100644 --- a/libavx/avx_gemm_tile.cpp +++ b/libavx/avx_gemm_tile.cpp @@ -281,12 +281,16 @@ AVX_QB_TARGET __attribute__((target("bmi2"))) static void qb_codes_zp( const int64_t nb = left >= 32 ? 20 : left <= 0 ? 0 : (left * 5 + 7) / 8; alignas(8) uint8_t buf[24] = {}; std::memcpy(buf, row + i / 8 * 5, (size_t)nb); - const unsigned long long kLow5 = 0x1f1f1f1f1f1f1f1full; + /* Eight 5-bit codes spread to eight bytes. Not _pdep_u64: BMI2 is not in this level's + * flag set (avx_dispatch.cpp checks only F + BW + DQ + VL), and clang refuses to + * inline the intrinsic without it. */ uint64_t q[4]; for (int r = 0; r < 4; ++r) { uint64_t v = 0; std::memcpy(&v, buf + 5 * r, 8); - q[r] = _pdep_u64(v & 0xffffffffffull, kLow5); + uint64_t s = 0; + for (int k = 0; k < 8; ++k) s |= ((v >> (5 * k)) & 0x1fu) << (8 * k); + q[r] = s; } x = _mm256_set_epi64x((long long)q[3], (long long)q[2], (long long)q[1], (long long)q[0]); From 0c35fc8070b170764aba2a5131de898e89df61bb Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 20:52:57 +0200 Subject: [PATCH 02/35] libref, libavx, libr4d: cfg_topk_sample's top_p and ras_pick -- Fish Audio's nucleus over the whole candidate set, cut before the top-k, and its repetition-aware choice between two draws --- docs/OPS.md | 16 ++++-- libavx/avx_audio.cpp | 60 ++++++++++++++++++++++- libavx/avx_cases.cpp | 9 ++++ libavx/avx_isa.h | 2 +- libavx/avx_registry.cpp | 12 ++++- libr4d/r4d_audio.hip | 84 +++++++++++++++++++++++++++++-- libr4d/r4d_plugin.h | 1 + libr4d/r4d_rows.cpp | 18 ++++++- libr4d/r4d_selftest.cpp | 106 ++++++++++++++++++++++++++++++++++++---- libref/ref_audio.cpp | 66 ++++++++++++++++++++++++- libref/ref_ops.h | 2 + libref/ref_registry.cpp | 13 ++++- libref/ref_shapes.cpp | 15 ++++++ tests/ref_test.cpp | 3 ++ 14 files changed, 384 insertions(+), 23 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 0897ac51..1714484c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1171,10 +1171,11 @@ libref function says which (`libref/ref_audio.cpp`). | `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` | | `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? | | `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` | -| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | +| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | | `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` | | `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout | | `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout | +| `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` | | `frame_store` | `M`(range) `n_codes` `stride` `rep`/opt `skip`/opt | `codes`, `lane`, `frame`, `status`, `dst`:inout | | `resample_nearest` | `M`(range) `n` `dtype` | `x` → `y` | | `fourier_embed` | `M`(range) `n` `round`/opt `dtype` | `t`, `w`w → `y` | @@ -1198,8 +1199,17 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a `cond_k` > 0 only the entries where `c` reaches its `cond_k`-th largest value are. The `k` largest `g` (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and drawn by inverse CDF in descending `g`, `u = rad_philox_uniform_s(seed, 2^32 + frame, stream)` - (`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. `logits` - `[rep n, n_vocab]` f32 or bf16, `seed` `[n, 2]` u32 low word first, `frame` `[n]`. + (`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. With `top_p` < 1 + (Fish Audio's draw) the kept list is cut first: over the softmax of every candidate's `g / temp` + (its normaliser summed in index order), a kept rank whose inclusive cumulative probability in + descending `g` exceeds `top_p` is dropped, rank 0 never, so the nucleus is taken over the whole + distribution and the `k` cut applies after it. `logits` `[rep n, n_vocab]` f32 or bf16, `seed` + `[n, 2]` u32 low word first, `frame` `[n]`. +- `ras_pick`: Fish Audio's repetition-aware sampling, a choice between two draws of each lane: + `ids[rep i] = alt[rep i]` when `first[rep i]` is in `[lo, hi)` and the lane's window holds it, + else `first[rep i]`. The window `hist` `[lanes, win]` i32 is the lane's last `win` picks, oldest + first, -1 empty (`clear` 1 empties it first, for a piece's first pick); the pick then enters it + and the oldest leaves. A pick outside `[lo, hi)` (an end of speech) is never redrawn. - `end_status`: `status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]`. - `rvq_embed`: `codes` is code-major `[n_codes, rows]`, read at the operand's own strides (a block of a wider plane is a view); diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index 99e16e1a..7f2559f4 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -590,8 +590,10 @@ AVX_KERNEL(cfg_topk_sample) { const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0); const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f); const float pen = p_f32(a, "penalty", 1.0f); + const double top_p = (double)p_f32(a, "top_p", 1.0f); if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) || - sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane)) + sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) || + !(top_p >= 0)) return RAD_E_SHAPE; const int64_t n = numel(ids) / rep; if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n || @@ -650,11 +652,29 @@ AVX_KERNEL(cfg_topk_sample) { } else { for (int64_t j = 0; j < V; ++j) if (open(j)) idx[nc++] = j; } - const int64_t kk = std::min(K, nc); + /* top_p's normaliser over every candidate in index order (idx still is), as libref. */ + double z = 0; + if (top_p < 1.0) { + float gm = g[idx[0]]; + for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[idx[t]]); + const float m0 = gm / temp; + for (int64_t t = 0; t < nc; ++t) z += std::exp((double)(g[idx[t]] / temp - m0)); + } + int64_t kk = std::min(K, nc); std::partial_sort(idx, idx + kk, idx + nc, [g](int64_t p, int64_t q) { return g[p] > g[q] || (g[p] == g[q] && p < q); }); const float m = g[idx[0]] / temp; + if (top_p < 1.0) { + double cum = 0; + int64_t keep = 1; + for (int64_t t = 0; t < kk; ++t) { + cum += std::exp((double)(g[idx[t]] / temp - m)) / z; + if (t > 0 && cum > top_p) break; + keep = t + 1; + } + kk = keep; + } double tot = 0; for (int64_t t = 0; t < kk; ++t) { e[t] = std::exp((double)(g[idx[t]] / temp - m)); @@ -789,6 +809,42 @@ AVX_KERNEL(frame_mix_store) { return RAD_OK; } +/* ------------------------------------------------------------------ ras_pick */ +/* libref's rule: the first draw unless it lies in [lo, hi) and the lane's window of its last `win` + * picks holds it, then the alternative; the pick enters the window. Lanes are checked before + * anything is written and run in order, as two entries may share a lane's window. */ +AVX_KERNEL(ras_pick) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3]; + const RadTensor* ids = &a->t[4]; + const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0); + const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0); + const int64_t n = numel(lane); + if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 || + numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n) + return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t L = at(lane, i); + if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE; + } + for (int64_t i = 0; i < n; ++i) { + const int64_t hb = at(lane, i) * W; + if (clear) + for (int64_t w = 0; w < W; ++w) st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), -1); + const int64_t f = at(first, rep * i); + int64_t pick = f; + if (f >= lo && f < hi) + for (int64_t w = 0; w < W; ++w) + if (at(hist, hb + w) == f) { pick = at(alt, rep * i); break; } + for (int64_t r = 0; r < rep; ++r) + st_int_dt(ids->dtype, ids->data, offlin(ids, rep * i + r), pick); + for (int64_t w = 0; w + 1 < W; ++w) + st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), at(hist, hb + w + 1)); + st_int_dt(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ end_status */ /* status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]. */ AVX_KERNEL(end_status) { diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index cdc34b1b..5be9c307 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -998,6 +998,12 @@ std::vector build_cases() { add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2), HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0), HS("dtype", "f32") }); + /* Fish Audio's draw: the nucleus over the whole candidate set's softmax, then the top-k cut; + * at a small top_p the head alone, and above 1 none. */ + for (double tp : { 0.7, 0.05, 0.95 }) + add("cfg_topk_sample", { HI("M", 4), HI("n_vocab", 645), HI("k", 30), HI("rep", 1), + HF("cfg", 1.0), HF("temp", 0.7), HI("stream", 2), + HF("top_p", tp), HS("dtype", "f32") }); /* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a * candidate), a temperature, the penalty idle without a history. */ for (int rep : { 1, 2 }) @@ -1038,6 +1044,9 @@ std::vector build_cases() { } add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) }); add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) }); + add("ras_pick", { HI("M", 4), HI("win", 16), HI("lo", 1), HI("hi", 9), HI("rep", 1) }); + add("ras_pick", { HI("M", 2), HI("win", 4), HI("lo", 0), HI("hi", 12), HI("rep", 2), + HI("clear", 1) }); add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2), HI("skip", 0) }); add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1), diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 57fac4df..09b53658 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -134,7 +134,7 @@ int avx_par_force(int threads); X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \ X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \ X(win_finish) X(chan_split) X(interleave2) X(iota) \ - X(cu_repeat) X(snake_aa) X(int_affine) \ + X(cu_repeat) X(snake_aa) X(int_affine) X(ras_pick) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 11470960..ba115f6f 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -699,7 +699,8 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"), static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), - P_INTO("sup_hi"), P_F64O("penalty") }; + P_INTO("sup_hi"), P_F64O("penalty"), + P_F64O("top_p") }; static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"), OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), @@ -712,6 +713,10 @@ static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scal OPD("frame"), OPD("status"), INOUT("dst") }; static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") }; static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") }; +static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"), + P_INTO("rep"), P_INTO("clear") }; +static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"), + OUT("ids") }; static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), P_INTO("rep"), P_INTO("skip") }; static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"), @@ -1185,6 +1190,9 @@ static const RadOpSchema kSchemas[] = { "a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." }, { "end_status", ARR(pEndStatus), ARR(oEndStatus), "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." }, +{ "ras_pick", ARR(pRasPick), ARR(oRasPick), + "repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in the " + "lane's window of its last picks, else the first; the pick enters the window." }, { "frame_store", ARR(pFrameStore), ARR(oFrameStore), "a frame's codes into its lane's history, code-major rows over the lane's frames." }, { "resample_nearest", ARR(pMnD), ARR(oUnary), @@ -1714,6 +1722,8 @@ SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)), SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, L(end_status)), +SIMPLE("avx_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane", + DT_ANY, L(ras_pick)), SIMPLE("avx_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY, L(frame_store)), SIMPLE("avx_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour", diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 1cf06249..95f974ff 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -622,6 +622,11 @@ __device__ uint32_t kth_key(F val, int j0, int j1, int kth, int* sh) { // [sup_lo, sup_hi) are optional. The kept values are divided by the temperature, as libref divides: // a multiply by its inverse rounds differently and can move a pick across a CDF boundary. A lane // with no candidate left writes -1. +// +// `top_p` < 1 cuts the kept list where the whole candidate set's cumulative probability passes it +// (Fish Audio's draw). The normaliser is each thread's slice summed in index order, the slices +// then summed by thread 0 in thread order: index order as libref sums, associated differently, +// which in double moves a cut only for a cumulative within ~1e-16 of top_p. constexpr int kMaxK = 256; __global__ __launch_bounds__(kT) void cfg_topk_kernel( @@ -629,9 +634,10 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel( const int* __restrict__ frame, int* __restrict__ ids, int V, int K, int rep, int cond_k, float cfg, float temp, uint64_t stream, const float* __restrict__ cfgs, const int* __restrict__ lane, int* __restrict__ hist, int n_hist, int sup_lo, int sup_hi, - float pen) { + float pen, float top_p) { __shared__ int sh[8]; __shared__ int s_pre[kT]; + __shared__ double s_z[kT]; __shared__ float s_g[kMaxK]; __shared__ int s_i[kMaxK]; __shared__ float s_e[kMaxK]; @@ -721,8 +727,29 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel( s_pre[rank] = mi; } __syncthreads(); + if (top_p < 1.f) { + const float m = s_e[0] / temp; + double z = 0; + for (int j = j0; j < j1; ++j) + if (cand(j)) z += exp((double)(gval(j) / temp - m)); + s_z[tid] = z; + } + __syncthreads(); if (tid == 0) { const float m = s_e[0] / temp; + int kp = kk; + if (top_p < 1.f) { + double z = 0; + for (int t = 0; t < kT; ++t) z += s_z[t]; + double cum = 0; + kp = 1; + for (int t = 0; t < kk; ++t) { + cum += exp((double)(s_e[t] / temp - m)) / z; + if (t > 0 && cum > (double)top_p) break; + kp = t + 1; + } + } + const int kk = kp; double tot = 0; for (int t = 0; t < kk; ++t) tot += exp((double)(s_e[t] / temp - m)); const double u = (double)rad_philox_uniform_s(seed_of(seed, ln), @@ -820,6 +847,32 @@ __global__ __launch_bounds__(kT) void frame_mix_kernel( } } +// Fish Audio's repetition-aware choice between two draws, a thread a lane (libref's +// ref_ras_pick): the alternative where the first draw is in [lo, hi) and in the lane's window of +// its last `W` picks, the pick then entering the window. A lane whose window lies outside `hist` +// takes the first draw and keeps no window. +__global__ __launch_bounds__(kT) void ras_pick_kernel( + const int* __restrict__ first, const int* __restrict__ alt, const int* __restrict__ lane, + int* __restrict__ hist, int* __restrict__ ids, int n, int W, int lo, int hi, int rep, + int clear, long long n_hist) { + const int i = blockIdx.x * kT + threadIdx.x; + if (i >= n) return; + const int f = first[rep * i]; + const long long L = lane[i]; + int pick = f; + if (L >= 0 && (L + 1) * W <= n_hist) { + int* h = hist + L * W; + if (clear) + for (int w = 0; w < W; ++w) h[w] = -1; + if (f >= lo && f < hi) + for (int w = 0; w < W; ++w) + if (h[w] == f) { pick = alt[rep * i]; break; } + for (int w = 0; w + 1 < W; ++w) h[w] = h[w + 1]; + h[W - 1] = pick; + } + for (int r = 0; r < rep; ++r) ids[rep * i + r] = pick; +} + __global__ __launch_bounds__(kT) void end_status_kernel( const int* __restrict__ ids, const int* __restrict__ lane, int* __restrict__ status, int n, int rep, int end) { @@ -1303,9 +1356,11 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) { const long long sup_lo = r4d_geti_or(a, "sup_lo", 0), sup_hi = r4d_geti_or(a, "sup_hi", 0); const double cfg = r4d_getf(a, "cfg", 1.0), temp = r4d_getf(a, "temp", 1.0); const double pen = r4d_getf(a, "penalty", 1.0); + /* As f32, as libref and libavx read it, so all three cut at the same value. */ + const float top_p = (float)r4d_getf(a, "top_p", 1.0); if (V <= 0 || K <= 0 || K > kMaxK || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) || V > (1 << 16) * kT || sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || - !(pen > 0) || (!hist != !lane)) + !(pen > 0) || (!hist != !lane) || !(top_p >= 0.f)) return R4D_NO(RAD_E_SHAPE); long long rl = 0; const long long ll = r4d_rows_pitch(lg, V, &rl); @@ -1321,7 +1376,30 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) { cfgs ? (const float*)cfgs->data : nullptr, lane ? (const int*)lane->data : nullptr, hist ? (int*)hist->data : nullptr, hist ? (int)(r4d_numel(hist) / V) : 0, (int)sup_lo, (int)sup_hi, - (float)pen); + (float)pen, top_p); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_ras_pick(const RadArgs* a, RadStream s) { + const RadTensor *first = r4d_opt(a, 0), *alt = r4d_opt(a, 1), *lane = r4d_opt(a, 2); + const RadTensor *hist = r4d_opt(a, 3), *ids = r4d_opt(a, 4); + if (!first || !alt || !lane || !hist || !ids) return R4D_NO(RAD_E_INVAL); + if (!is_i32(first) || !is_i32(alt) || !is_i32(lane) || !is_i32(hist) || !is_i32(ids)) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(first) || !r4d_contig(alt) || !r4d_contig(lane) || !r4d_contig(hist) || + !r4d_contig(ids)) + return R4D_NO(RAD_E_STRIDE); + const long long W = r4d_geti_or(a, "win", 0), lo = r4d_geti_or(a, "lo", 0); + const long long hi = r4d_geti_or(a, "hi", 0), rep = r4d_geti_or(a, "rep", 1); + const long long clear = r4d_geti_or(a, "clear", 0); + const long long n = r4d_numel(lane); + if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 || + r4d_numel(first) < rep * n || r4d_numel(alt) < rep * n || r4d_numel(ids) < rep * n) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(ras_pick_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s, + (const int*)first->data, (const int*)alt->data, (const int*)lane->data, + (int*)hist->data, (int*)ids->data, (int)n, (int)W, (int)lo, (int)hi, + (int)rep, (int)clear, (long long)r4d_numel(hist)); return st_of(hipGetLastError()); } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 18c7625a..fcb48fb1 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -202,6 +202,7 @@ int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream); int r4d_rad_rvq_embed (const RadArgs*, RadStream); int r4d_rad_frame_mix_store (const RadArgs*, RadStream); int r4d_rad_end_status (const RadArgs*, RadStream); +int r4d_rad_ras_pick (const RadArgs*, RadStream); int r4d_rad_frame_store (const RadArgs*, RadStream); int r4d_rad_resample_nearest (const RadArgs*, RadStream); int r4d_rad_fourier_embed (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index a2930559..1bfaed4e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2391,7 +2391,8 @@ static const RadOperandSpec oSnake[] = { static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), - P_INTO("sup_hi"), P_F64O("penalty") }; + P_INTO("sup_hi"), P_F64O("penalty"), + P_F64O("top_p") }; static const RadOperandSpec oCfgTopk[] = { { "logits", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 }, { "ids", RAD_OPD_OUT, 0 }, { "cfg", RAD_OPD_IN, 1 }, { "lane", RAD_OPD_IN, 1 }, @@ -2415,6 +2416,12 @@ static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep" static const RadOperandSpec oEndStatus[] = { { "ids", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "status", RAD_OPD_INOUT, 0 }, }; +static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"), + P_INTO("rep"), P_INTO("clear") }; +static const RadOperandSpec oRasPick[] = { + { "first", RAD_OPD_IN, 0 }, { "alt", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, + { "hist", RAD_OPD_INOUT, 0 }, { "ids", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), P_INTO("rep"), P_INTO("skip") }; static const RadOperandSpec oFrameStore[] = { @@ -3335,6 +3342,9 @@ static const RadOpSchema kSchemas[] = { "a frame's conditioning row (softmax-weighted planes times scale) into its lane."), SCHEMA("end_status", pEndStatus, oEndStatus, "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."), + SCHEMA("ras_pick", pRasPick, oRasPick, + "repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in " + "the lane's window of its last picks, else the first; the pick enters the window."), SCHEMA("frame_store", pFrameStore, oFrameStore, "a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] " "= codes[k, rep i] when frame >= skip and status[lane] >= 0."), @@ -8292,6 +8302,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, 0, NOTUNE, nullptr, nullptr, r4d_rad_end_status }, +{ "ras_pick", "ras_pick", "elem", + "a repetition-aware choice between two draws a lane", "a thread a lane", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_ras_pick }, + { "frame_store", "frame_store", "elem", "a frame's codes into its lane's history", "a thread a (lane, code); dst contiguous", "i32", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index afb0e265..a071e8ba 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -5779,10 +5779,14 @@ void snake_cases(const Plugin& pl) { } } +/* Picks whose nucleus ended inside the top k, so that a top_p case is known to test the cut. */ +int64_t g_topp_cuts = 0; + /* ref_cfg_topk_sample's rule on the host, for one lane, over f32 logits. */ int ref_pick(const std::vector& lg, int64_t V, int64_t lane_row, int rep, float cfg, int64_t K, int64_t cond_k, float temp, int64_t sup_lo, int64_t sup_hi, float pen, - std::vector* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream) { + std::vector* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream, + float top_p = 1.0f) { std::vector c((size_t)V), g((size_t)V); for (int64_t j = 0; j < V; ++j) c[(size_t)j] = lg[(size_t)(rep * lane_row * V + j)]; if (rep == 2) { @@ -5815,11 +5819,28 @@ int ref_pick(const std::vector& lg, int64_t V, int64_t lane_row, int rep, if (open(j)) idx.push_back(j); } if (idx.empty()) return -1; - const int64_t kk = std::min(K, (int64_t)idx.size()); + double z = 0; + if (top_p < 1.0f) { + float gm = g[(size_t)idx[0]]; + for (const int64_t j : idx) gm = std::max(gm, g[(size_t)j]); + for (const int64_t j : idx) z += std::exp((double)(g[(size_t)j] / temp - gm / temp)); + } + int64_t kk = std::min(K, (int64_t)idx.size()); std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int64_t p, int64_t q) { return g[(size_t)p] > g[(size_t)q] || (g[(size_t)p] == g[(size_t)q] && p < q); }); const float m = g[(size_t)idx[0]] / temp; + if (top_p < 1.0f) { + double cum = 0; + int64_t keep = 1; + for (int64_t t = 0; t < kk; ++t) { + cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z; + if (t > 0 && cum > (double)top_p) break; + keep = t + 1; + } + if (keep < kk) ++g_topp_cuts; + kk = keep; + } double tot = 0; std::vector e((size_t)kk); for (int64_t t = 0; t < kk; ++t) { @@ -5844,16 +5865,26 @@ int ref_pick(const std::vector& lg, int64_t V, int64_t lane_row, int rep, void cfg_topk_cases(const Plugin& pl) { const RadKernelInfo* r = find(pl, "cfg_topk_sample"); if (!r) { ok("cfg_topk_sample", false, "row absent"); return; } - struct C { int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp; }; + struct C { + int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp; + float top_p = 1.0f; int64_t K = 50; + }; + /* The last two are Fish Audio's draws (arch/fishomni): its main pick over eos and 4096 + * semantic ids at temperature 0.7, nucleus 0.7, top 30, and its repetition-aware redraw at 1.0, + * 0.95, 30. */ for (const C& c : { C{ 2052, 2, true, true, 2048, 2051, 0, 0.9f }, C{ 2051, 1, true, false, 2048, 2051, 0, 0.9f }, C{ 2051, 2, false, true, 2048, 2051, 0, 0.9f }, - C{ 16385, 2, false, false, 0, 0, 50, 1.0f } }) { - const int64_t n = 3, lanes = 4, K = 50; - const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld", + C{ 16385, 2, false, false, 0, 0, 50, 1.0f }, + C{ 4097, 1, false, false, 0, 0, 0, 0.7f, 0.7f, 30 }, + C{ 4097, 1, false, false, 0, 0, 0, 1.0f, 0.95f, 30 } }) { + const int64_t n = 3, lanes = 4, K = c.K; + const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld" + " top_p %g k %lld", (long long)c.V, c.rep, c.hist ? " hist" : "", c.cfgs ? " per-lane cfg" : "", (long long)c.sup_lo, - (long long)c.sup_hi, (long long)c.cond_k); + (long long)c.sup_hi, (long long)c.cond_k, (double)c.top_p, + (long long)K); std::vector lane = { 2, 0, 3 }; std::vector cfgv = { 1.0f, 3.0f, 4.0f }; std::vector seed = { 7u, 0u, 0x9e3779b9u, 1u, 0xdeadbeefu, 0x12345u }; @@ -5876,6 +5907,9 @@ void cfg_topk_cases(const Plugin& pl) { for (size_t i = 0; i < lg.size(); ++i) { const float v = rnd() * 6.0f; lg[i] = (i % 97 == 0) ? 5.95f : v; + /* About 19 peaks a row hold most of the mass, so the nucleus ends inside the top + * 30 and the cut is what decides the pick. */ + if (c.top_p < 1.0f && i % 211 == 5) lg[i] = 12.0f + 4.0f * rnd(); } void* dlg = up_f32(lg); std::vector frame((size_t)n, f); @@ -5888,7 +5922,7 @@ void cfg_topk_cases(const Plugin& pl) { PI("rep", c.rep), PI("cond_k", c.cond_k), PF("cfg", 1.5), PF("temp", c.temp), PI("stream", 3), PS("dtype", "f32"), PI("sup_lo", c.sup_lo), PI("sup_hi", c.sup_hi), - PF("penalty", 1.1) }; + PF("penalty", 1.1), PF("top_p", c.top_p) }; const int rc = launch(r, { T(dlg, RAD_F32, { c.rep * n, c.V }), T(dseed, RAD_U32, { n, 2 }), T(dfr, RAD_I32, { n }), T(dids, RAD_I32, { c.rep * n }), tcfg, tlane, thist }, @@ -5901,7 +5935,8 @@ void cfg_topk_cases(const Plugin& pl) { const int want = ref_pick(lg, c.V, i, c.rep, c.cfgs ? cfgv[(size_t)i] : 1.5f, K, c.cond_k, c.temp, c.sup_lo, c.sup_hi, 1.1f, c.hist ? &hist : nullptr, - c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3); + c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3, + c.top_p); for (int t = 0; t < c.rep; ++t) if (got[(size_t)(c.rep * i + t)] != want) ++wrong; } @@ -5909,12 +5944,64 @@ void cfg_topk_cases(const Plugin& pl) { } ok((nm + " picks").c_str(), wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong, (long long)(4 * c.rep * n))); + if (c.top_p < 1.0f) { + ok((nm + " cuts").c_str(), g_topp_cuts > 0, "the nucleus never ended inside the top k"); + g_topp_cuts = 0; + } if (c.hist) ok((nm + " history").c_str(), hist_wrong == 0, fmt("%lld history entries differ", (long long)hist_wrong)); } } +/* ras_pick over four picks of three lanes, the first clearing their windows: the picks and the + * windows against libref's rule on the host, exactly. Draws repeat often (a band of 6 ids) so the + * redraw is exercised, and one is outside [lo, hi) (never redrawn). */ +void ras_pick_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "ras_pick"); + if (!r) { ok("ras_pick", false, "row absent"); return; } + const int64_t n = 3, lanes = 4, W = 4, lo = 1, hi = 6; + std::vector lane = { 2, 0, 3 }; + std::vector hist((size_t)(lanes * W), 5); + void* dlane = up_i32(lane); + void* dhist = up_i32(hist); + void* dids = dalloc((size_t)n * 4); + int64_t wrong = 0; + for (int step = 0; step < 4; ++step) { + std::vector first((size_t)n), alt((size_t)n); + for (int64_t i = 0; i < n; ++i) { + first[(size_t)i] = (int32_t)((step * 2 + i * 3) % 7); /* 0 is outside [lo, hi) */ + alt[(size_t)i] = (int32_t)(10 + step * 3 + i); + } + void* df = up_i32(first); + void* da = up_i32(alt); + const int clear = step == 0 ? 1 : 0; + std::vector ps = { PI("M", n), PI("win", W), PI("lo", lo), PI("hi", hi), + PI("rep", 1), PI("clear", clear) }; + const int rc = launch(r, { T(df, RAD_I32, { n }), T(da, RAD_I32, { n }), + T(dlane, RAD_I32, { n }), T(dhist, RAD_I32, { lanes, W }), + T(dids, RAD_I32, { n }) }, + ps); + if (rc != RAD_OK) { ok("ras_pick", false, "rc " + std::to_string(rc)); return; } + const std::vector got = down_i32(dids, (size_t)n); + for (int64_t i = 0; i < n; ++i) { + int32_t* h = hist.data() + lane[(size_t)i] * W; + if (clear) for (int64_t w = 0; w < W; ++w) h[w] = -1; + int32_t pick = first[(size_t)i]; + if (pick >= lo && pick < hi) + for (int64_t w = 0; w < W; ++w) + if (h[w] == pick) { pick = alt[(size_t)i]; break; } + for (int64_t w = 0; w + 1 < W; ++w) h[w] = h[w + 1]; + h[W - 1] = pick; + if (got[(size_t)i] != pick) ++wrong; + } + } + ok("ras_pick picks", wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong, + (long long)(4 * n))); + ok("ras_pick windows", differ(down_i32(dhist, hist.size()), hist) == 0, + "the windows differ from libref's rule"); +} + /* rvq_embed: libref's two roundings, the single rounding over bf16 and f32 tables into a bf16 or * f32 row, codes read as a block of a wider frame-major history (strides other than the dense * plane's), and a first code outside its table leaving the row unwritten. Exact. */ @@ -24971,6 +25058,7 @@ static void device_phase(const Plugin& pl) { if (sel("conv_t1d_bf16")) au::conv_t1d_cases(pl); if (sel("snake_bf16")) au::snake_cases(pl); if (sel("cfg_topk_sample")) au::cfg_topk_cases(pl); + if (sel("ras_pick")) au::ras_pick_cases(pl); if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl); if (sel("frame_store")) au::frame_store_cases(pl); if (sel("iota")) au::iota_cases(pl); diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index e7bb319a..fc87808a 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -256,6 +256,9 @@ int ref_snake_aa(const RadArgs* a, RadStream) { * `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates * the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and * drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream). + * With `top_p` < 1 the kept list is cut first where the cumulative probability of the whole + * candidate set's softmax over temp (summed in index order) passes top_p, as Fish Audio's sampler + * cuts it: a rank whose inclusive cumulative probability exceeds top_p is dropped, rank 0 never. * The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or * bf16; seed [n, 2]; frame [n]. */ int ref_cfg_topk_sample(const RadArgs* a, RadStream) { @@ -267,8 +270,10 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) { const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0); const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f); const float pen = p_f32(a, "penalty", 1.0f); + const double top_p = (double)p_f32(a, "top_p", 1.0f); if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) || - sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane)) + sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) || + !(top_p >= 0)) return RAD_E_SHAPE; const int64_t n = numel(ids) / rep; if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n || @@ -319,13 +324,32 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) { if (open(j)) idx[(size_t)nc++] = j; } if (nc == 0) return RAD_E_SHAPE; - const int64_t kk = std::min(K, nc); + /* The whole candidate set's normaliser, in index order (idx still is), for top_p. */ + double z = 0; + if (top_p < 1.0) { + float gm = g[(size_t)idx[0]]; + for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[(size_t)idx[(size_t)t]]); + const float m0 = gm / temp; + for (int64_t t = 0; t < nc; ++t) + z += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m0)); + } + int64_t kk = std::min(K, nc); std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc, [&](int64_t p, int64_t q) { return g[(size_t)p] > g[(size_t)q] || (g[(size_t)p] == g[(size_t)q] && p < q); }); const float m = g[(size_t)idx[0]] / temp; + if (top_p < 1.0) { + double cum = 0; + int64_t keep = 1; + for (int64_t t = 0; t < kk; ++t) { + cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z; + if (t > 0 && cum > top_p) break; + keep = t + 1; + } + kk = keep; + } double tot = 0; std::vector e((size_t)kk); for (int64_t t = 0; t < kk; ++t) { @@ -437,6 +461,44 @@ int ref_frame_mix_store(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ ras_pick */ +/* Fish Audio's repetition-aware sampling, the choice between two draws a lane: the first draw + * ids[rep i] = first[rep i], unless it lies in [lo, hi) and the lane's window (its last `win` + * picks, `hist` [lanes, win], oldest first, -1 empty) holds it, in which case the alternative + * draw alt[rep i] is taken. The pick then enters the window, its oldest entry leaving. `clear` 1 + * empties the lane's window first (a piece's first pick). A pick outside [lo, hi) (Fish's end of + * speech) is never redrawn. */ +int ref_ras_pick(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3]; + const RadTensor* ids = &a->t[4]; + const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0); + const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0); + const int64_t n = numel(lane); + if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 || + numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n) + return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t L = ldi(lane, i); + if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE; + } + for (int64_t i = 0; i < n; ++i) { + const int64_t hb = ldi(lane, i) * W; + if (clear) + for (int64_t w = 0; w < W; ++w) st_int(hist->dtype, hist->data, offlin(hist, hb + w), -1); + const int64_t f = ldi(first, rep * i); + int64_t pick = f; + if (f >= lo && f < hi) + for (int64_t w = 0; w < W; ++w) + if (ldi(hist, hb + w) == f) { pick = ldi(alt, rep * i); break; } + for (int64_t r = 0; r < rep; ++r) st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick); + for (int64_t w = 0; w + 1 < W; ++w) + st_int(hist->dtype, hist->data, offlin(hist, hb + w), ldi(hist, hb + w + 1)); + st_int(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ end_status */ /* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end` * (the model ended the piece), else the pick. */ diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 4c164a65..ac9ce75a 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -209,6 +209,7 @@ int ref_cfg_topk_sample(const RadArgs*, RadStream); int ref_rvq_embed(const RadArgs*, RadStream); int ref_frame_mix_store(const RadArgs*, RadStream); int ref_end_status(const RadArgs*, RadStream); +int ref_ras_pick(const RadArgs*, RadStream); int ref_frame_store(const RadArgs*, RadStream); int ref_resample_nearest(const RadArgs*, RadStream); int ref_fourier_embed(const RadArgs*, RadStream); @@ -448,6 +449,7 @@ REF_SHAPE_FN(ref_cfg_topk_sample); REF_SHAPE_FN(ref_rvq_embed); REF_SHAPE_FN(ref_frame_mix_store); REF_SHAPE_FN(ref_end_status); +REF_SHAPE_FN(ref_ras_pick); REF_SHAPE_FN(ref_frame_store); REF_SHAPE_FN(ref_resample_nearest); REF_SHAPE_FN(ref_fourier_embed); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 827188ca..60b0ef55 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -900,7 +900,8 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"), static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"), P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"), P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"), - P_INTO("sup_hi"), P_F64O("penalty") }; + P_INTO("sup_hi"), P_F64O("penalty"), + P_F64O("top_p") }; static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"), OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), @@ -913,6 +914,10 @@ static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scal OPD("frame"), OPD("status"), INOUT("dst") }; static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") }; static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") }; +static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"), + P_INTO("rep"), P_INTO("clear") }; +static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"), + OUT("ids") }; static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"), P_INTO("rep"), P_INTO("skip") }; static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"), @@ -1769,6 +1774,10 @@ static const RadOpSchema kSchemas[] = { "stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." }, { "end_status", ARR(pEndStatus), ARR(oEndStatus), "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." }, +{ "ras_pick", ARR(pRasPick), ARR(oRasPick), + "repetition-aware sampling: ids[rep i] = alt[rep i] where first[rep i] is in [lo, hi) and in " + "the lane's window of its last `win` picks (hist [lanes, win], -1 empty, cleared first with " + "`clear` 1), else first[rep i]; the pick then enters the window." }, { "frame_store", ARR(pFrameStore), ARR(oFrameStore), "a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = " "codes[k, rep i] when frame >= skip and status[lane] >= 0." }, @@ -2340,6 +2349,8 @@ SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning DT_FLOAT, ref_frame_mix_store), SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, ref_end_status), +SIMPLE("ref_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane", + DT_ANY, ref_ras_pick), SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY, ref_frame_store), SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f1fd4d8a..b9f074d7 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -3226,6 +3226,21 @@ int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("end_status", operand, out); } +int ref_ras_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), W = gi(p, n_p, "win", 0); + const int64_t hi = gi(p, n_p, "hi", 0); + if (M <= 0 || rep < 1 || W <= 0 || hi <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED; + Opd o; + /* Picks over a small band so the windows repeat them often enough to exercise the redraw. */ + const int64_t band = std::min(hi + 2, 12); + o.t_idx({ rep * M }, band, -1, 0); /* first */ + o.t_idx({ rep * M }, band, -1, 0); /* alt */ + o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ REF_LANES * W }, band, -1, 0); /* hist, INOUT */ + o.t_idx({ rep * M }, band, -1, 0); /* ids, OUT */ + return o.finish("ras_pick", operand, out); +} + int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0); const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 844b5be8..6d182677 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -970,6 +970,8 @@ TEST(op_vocabulary) { "conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store", "end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish", "chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store", + /* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws. */ + "ras_pick", /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ @@ -8124,6 +8126,7 @@ std::vector geometries() { G("frame_mix_store", "M", 2, a.i("M", R).i("n_embd", 8).i("L", 3).i("stride", 4) .i("rep", 2).s("dtype", "bf16")), G("end_status", "M", 2, a.i("M", R).i("end", 5).i("rep", 2)), + G("ras_pick", "M", 2, a.i("M", R).i("win", 4).i("lo", 1).i("hi", 9).i("rep", 1)), G("resample_nearest", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32")), G("fourier_embed", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("win_input", "M", 8, a.i("M", R).i("n_lat", 4).i("n_zero", 2).i("n_cond", 3) From baf6e89ecb27ac1e3df892b0265ba921936e545a Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 20:54:55 +0200 Subject: [PATCH 03/35] core: an audio generator of one branch over a hybrid language model -- the driver stages a delta net's state and convolution groups beside the paged one, with each entry's context and num_accepted, the generator loop zeroes the slots a request is granted, and a model may read its input with special tokens (its speaker tags) --- abi/rad_builder.h | 10 ++ core/build/rad_builder.cpp | 12 +++ core/engine.cpp | 38 ++++---- core/engine.h | 3 + core/engine_gen.cpp | 2 + core/gen/audio_driver.cpp | 185 ++++++++++++++++++++++++++++--------- core/gen/audio_driver.h | 27 +++++- core/server/audio_gen.cpp | 12 ++- core/server/iface.h | 4 + tests/abi_layout_rows.h | 2 + tests/abi_layout_table.h | 4 +- tests/audio_gen_test.cpp | 85 +++++++++++++++++ tests/speech_test.cpp | 22 +++++ 13 files changed, 339 insertions(+), 67 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 3e33597d..e122636d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -963,6 +963,16 @@ typedef struct RadAudioGenDecl { * latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */ int64_t voc_chunk; int64_t voc_context; + /* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the + * conditional one alone, for a model without guidance (no unconditional prompt is rendered, + * a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one + * entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then + * cost half. */ + int32_t branches; + /* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own + * text always is, so a caller can write the model's speaker tags. The plugin's + * rad_arch_text_prepare then refuses the control tokens a caller must not write. */ + int32_t input_special; } RadAudioGenDecl; int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index e97cac62..41915494 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1371,6 +1371,18 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { "instructions and needs {input} alone", nm); return RAD_E_INVAL; } + if (d->branches != 0 && d->branches != 1 && d->branches != 2) { + err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence " + "or 2 (0 means 2)", nm, (int)d->branches); + return RAD_E_INVAL; + } + /* One branch has no unconditional prompt to render and no guidance to apply. */ + if (d->branches == 1 && (d->neg_tmpl || d->default_cfg != 1.0)) { + err(RAD_E_INVAL, "declare_audio_generator '%s': a model of one branch has no " + "unconditional template and no guidance (default_cfg %g)", nm, + d->default_cfg); + return RAD_E_INVAL; + } if (d->neg_tmpl && !d->prompt_whole) { err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches " "of different lengths, which step together only as whole prompts; set " diff --git a/core/engine.cpp b/core/engine.cpp index 3256f380..dd8db874 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -438,22 +438,7 @@ int Engine::step_loop() { idle = 0; if (t_on) phase_mark(PH_PLAN); - /* Zero freshly assigned recurrent slots before the step that reads them. The manager - * records the grab but cannot write (StateClear in core/mem/kv.h); the list is empty except - * on a sequence's first step. Each rank clears by its own plan: the slot number is the - * scheduler's, but the state size depends on the heads this rank holds, which can differ - * per rank (rad_arch.h remainder_place). */ - for (const StateClear& c : ranks_[0]->kv.state_clears()) { - for (auto& rk : ranks_) { - const KVGroupPlan* gp = rk->kv.plan(c.group); - if (!gp || !gp->stateful()) continue; - const int64_t bytes = gp->layer_bytes_per_state(); - for (int64_t l = 0; l < gp->n_layers; ++l) - if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot)) - rad_memset_async(p, 0, bytes, rk->ctx.stream()); - } - } - ranks_[0]->kv.clear_state_clears(); + clear_fresh_states(); /* Entries that want logits rows, in BatchBuilder's out_ids order: those with * produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt @@ -1339,6 +1324,25 @@ void Engine::drain_completed() { for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id); } +/* Zero freshly assigned recurrent slots before the step that reads them. The manager records the + * grab but cannot write (StateClear in core/mem/kv.h); the list is empty except on a sequence's + * first step. Each rank clears by its own plan: the slot number is the scheduler's, but the state + * size depends on the heads this rank holds, which can differ per rank (rad_arch.h + * remainder_place). */ +void Engine::clear_fresh_states() { + for (const StateClear& c : ranks_[0]->kv.state_clears()) { + for (auto& rk : ranks_) { + const KVGroupPlan* gp = rk->kv.plan(c.group); + if (!gp || !gp->stateful()) continue; + const int64_t bytes = gp->layer_bytes_per_state(); + for (int64_t l = 0; l < gp->n_layers; ++l) + if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot)) + rad_memset_async(p, 0, bytes, rk->ctx.stream()); + } + } + ranks_[0]->kv.clear_state_clears(); +} + int Engine::serve(std::unique_ptr watch) { startup_watch_ = std::move(watch); if (ranks_.empty() || !ranks_[0]->ctx.program()) { @@ -2494,6 +2498,8 @@ int Engine::run_server() { in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps; in.default_cfg = ad.default_cfg; in.max_lanes = ad.max_lanes; + in.branches = ad.branches == 1 ? 1 : 2; + in.input_special = ad.input_special != 0; audio_bridge.drv = aud_gen_; audio_bridge.plugins = &plugins_; d.audio = &audio_bridge; diff --git a/core/engine.h b/core/engine.h index 4b07a680..40ccff48 100644 --- a/core/engine.h +++ b/core/engine.h @@ -355,6 +355,9 @@ private: gen::AudioDriver* aud_gen_ = nullptr; gen::VideoDriver* vid_gen_ = nullptr; int gen_loop(); + /* Zeroes the state slots the KV manager granted since the last step, on every rank's stream, + * before the step or pass that first reads them. */ + void clear_fresh_states(); bool serial_drafting() const; int advance_all(int mode, int round, bool from_proposal, int rows = -1); int issue_serial_drafter(int step, StepOut& so); diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index 27b286da..e4e02569 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -53,6 +53,8 @@ int Engine::gen_loop() { continue; } idle = 0; + /* A hybrid model's recurrent state: the slots a newly admitted request was granted. */ + clear_fresh_states(); if (const int ps = prepare_release(b); ps < 0) return stop(ps); for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot()); issue_what_.store(kIssueModel, std::memory_order_release); diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp index c40df146..37e52044 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -68,8 +68,22 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } struct Sizes { int64_t T = 0, S = 0, L = 0, NB = 0; + int64_t NG = 0; /* stateful KV groups */ }; +/* The paged full-attention group, and how many stateful groups sit beside it. */ +int32_t full_group(const Program& prog, int64_t* n_state) { + int32_t full = 0; + int64_t ns = 0; + for (size_t g = 1; g < prog.kv_groups.size(); ++g) { + const int kind = prog.kv_groups[g].decl.kind; + if (kind == RAD_KV_FULL && !full) full = (int32_t)g; + else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) ++ns; + } + if (n_state) *n_state = ns; + return full; +} + Sizes sizes_of(const Program& prog, int64_t block_size) { const RadAudioGenDecl& d = prog.audio_gen; Sizes z; @@ -77,6 +91,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { z.S = prog.ctx.max_seqs; z.L = d.max_lanes; z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0; + full_group(prog, &z.NG); return z; } @@ -110,6 +125,10 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { z.S * I, /* R_ESLOT */ z.S * I, /* R_LROW */ z.S * I, /* R_PREFIX */ + z.S * I, /* R_CTX */ + z.S * I, /* R_ACC */ + z.NG * z.S * I, /* R_SBT */ + z.NG * z.S * AudioDriver::kMaxStateWidth * I, /* R_SIDX */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -123,8 +142,10 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { } /* namespace */ int64_t AudioDriver::device_bytes(const Program& prog) { - if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0; - const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size); + if (!prog.is_audio_generator()) return 0; + const int32_t fg = full_group(prog, nullptr); + if (!fg) return 0; + const Sizes z = sizes_of(prog, prog.kv_groups[(size_t)fg].block_size); int64_t b[R_N][2]; return carve(z, b, R_N); } @@ -136,15 +157,39 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector(1, kv->state_index_width((int32_t)g)); + if (sg.width > kMaxStateWidth) { + RAD_ERR("audio generator: KV group %zu asks for %lld state slots a sequence; the " + "driver stages at most %lld", g, (long long)sg.width, + (long long)kMaxStateWidth); + return RAD_E_UNSUPPORTED; + } + state_groups_.push_back(sg); + } else { + n_full = -1; + break; + } + } + kv_group_ = full_group(prog, nullptr); + if (n_full != 1 || !kv_group_ || prog.kv_groups[(size_t)kv_group_].block_size <= 0) { + RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages one " + "paged full-attention group, the language model's, and the state and " + "convolution groups of a hybrid one beside it", prog.kv_groups.size() - 1); return RAD_E_UNSUPPORTED; } - kv_group_ = 1; - block_size_ = prog.kv_groups[1].block_size; + block_size_ = prog.kv_groups[(size_t)kv_group_].block_size; + nb_ = decl_.branches == 1 ? 1 : 2; const Sizes z = sizes_of(prog, block_size_); max_tok_ = z.T; max_seqs_ = z.S; @@ -154,13 +199,13 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector= 0; --i) free_lanes_.push_back((int32_t)i); return RAD_OK; @@ -224,7 +269,9 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { return RAD_E_INVAL; }; const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size(); - if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail) + if (nb_ == 1 && r->cfg != 0.0f && r->cfg != 1.0f) + return no("this model runs without guidance; guidance_scale must be 1"); + if (nb_ == 2 && !neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail) return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own " "markers"); if (T < 1 || std::max(T, Tn) > d.max_prompt) @@ -309,16 +356,19 @@ int AudioDriver::admit_locked() { const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg; /* The unconditional prompt: the request's own (the conditional one at guidance 1, which * makes the guided logits the conditional ones), or derived from the conditional one. */ - std::vector neg = r.tokens; - if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) { - neg = r.neg_tokens; - } else if (!neg_own_) { - for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i) - neg[(size_t)i] = decl_.neg_token; + std::vector neg; + if (nb_ > 1) { + neg = r.tokens; + if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) { + neg = r.neg_tokens; + } else if (!neg_own_) { + for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i) + neg[(size_t)i] = decl_.neg_token; + } } - /* Both branches for the whole piece, so nothing in flight ever waits for KV. */ + /* Every branch for the whole piece, so nothing in flight ever waits for KV. */ bool ok = true; - for (int b = 0; b < 2 && ok; ++b) { + for (int b = 0; b < nb_ && ok; ++b) { const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1; j.seq[b] = ((uint64_t)1 << 61) | next_seq_++; if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false; @@ -390,7 +440,7 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 for (size_t r = 0; r < ranks_.size(); ++r) { RadBatch& B = out_[r]; RadAudioGenBatch& A = aout_[r]; - RadKVGroupBatch& K = kout_[r]; + RadKVGroupBatch& K = kout_[r * (1 + state_groups_.size())]; const int ri = (int)r; B = RadBatch{}; B.step = step; @@ -412,8 +462,23 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 K.seqused = dptr(ri, R_USED); K.block_size = block_size_; K.max_blocks = max_blocks_; - B.n_kv_groups = 1; + /* A stateful group's block-table row is the sequence's slot, as the text scheduler + * stages it, so a kernel reading tables needs no second path. */ + for (size_t gi = 0; gi < state_groups_.size(); ++gi) { + RadKVGroupBatch& Ks = (&K)[1 + gi]; + Ks = RadKVGroupBatch{}; + Ks.group = (rad_kvgroup)state_groups_[gi].g; + Ks.block_table = dptr(ri, R_SBT) + gi * max_seqs_; + Ks.block_table_pitch = 1; + Ks.seqused = dptr(ri, R_USED); + Ks.state_index = dptr(ri, R_SIDX) + gi * max_seqs_ * kMaxStateWidth; + Ks.state_index_pitch = state_groups_[gi].width; + Ks.max_blocks = 1; + } + B.n_kv_groups = (int)(1 + state_groups_.size()); B.kv = &K; + B.ctx_lens = dptr(ri, R_CTX); + B.num_accepted = dptr(ri, R_ACC); } A = RadAudioGenBatch{}; A.lane = dptr(ri, R_LANE); @@ -438,6 +503,31 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 } } +void AudioDriver::stage_state(const std::vector& seqs, const std::vector& ctx) { + const int64_t n = (int64_t)seqs.size(); + int32_t* cl = hptr(R_CTX); + int32_t* acc = hptr(R_ACC); + for (int64_t e = 0; e < n; ++e) { + cl[e] = ctx[(size_t)e]; + /* One-based, as num_accepted always is: a pass commits every row it runs. */ + acc[e] = 1; + } + reg_[R_CTX].used = reg_[R_ACC].used = n * 4; + for (size_t gi = 0; gi < state_groups_.size(); ++gi) { + const StateGroup& sg = state_groups_[gi]; + int32_t* bt = hptr(R_SBT) + gi * max_seqs_; + int32_t* si = hptr(R_SIDX) + gi * max_seqs_ * kMaxStateWidth; + for (int64_t e = 0; e < n; ++e) { + bt[e] = kv_->state_slot(seqs[(size_t)e], sg.g); + kv_->state_index_row(seqs[(size_t)e], sg.g, si + e * sg.width, (int)sg.width); + } + } + if (!state_groups_.empty()) { + reg_[R_SBT].used = (int64_t)state_groups_.size() * max_seqs_ * 4; + reg_[R_SIDX].used = (int64_t)state_groups_.size() * max_seqs_ * kMaxStateWidth * 4; + } +} + /* The KV slot of position `p` in a sequence with this block table. */ static int32_t slot_of(const std::vector& bt, int64_t p, int64_t bs) { const int64_t bi = p / bs; @@ -517,12 +607,13 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; /* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */ const int64_t p0 = j.prompt_done; - int64_t cb[2]; + int64_t cb[2] = { 0, 0 }; if (decl_.prompt_whole) { cb[0] = j.T; - cb[1] = j.Tn; + cb[1] = nb_ > 1 ? j.Tn : 0; } else { - cb[0] = cb[1] = std::min(j.T - j.prompt_done, max_tok_ / 2); + cb[0] = std::min(j.T - j.prompt_done, max_tok_ / nb_); + cb[1] = nb_ > 1 ? cb[0] : 0; } const int64_t cmax = std::max(cb[0], cb[1]); int32_t* tok = hptr(R_TOK); @@ -530,12 +621,12 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { int32_t* slot = hptr(R_SLOT); int32_t* cu = hptr(R_CU); int64_t pitch = 1; - for (int b = 0; b < 2; ++b) + for (int b = 0; b < nb_; ++b) pitch = std::max(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size()); int32_t* btab = hptr(R_BT); int32_t* used = hptr(R_USED); cu[0] = 0; - for (int b = 0; b < 2; ++b) { + for (int b = 0; b < nb_; ++b) { const std::vector& src = b ? j.neg : j.req->tokens; const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); for (int64_t i = 0; i < cb[b]; ++i) { @@ -549,26 +640,31 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; used[b] = (int32_t)(p0 + cb[b]); } - const int64_t rows = cu[2]; + const int64_t rows = cu[nb_]; const bool last = p0 + cb[0] == j.T; - for (int b = 0; b < 2; ++b) { - hptr(R_ESLOT)[b] = 2 * j.lane + b; + std::vector seqs; + std::vector ctx; + for (int b = 0; b < nb_; ++b) { + hptr(R_ESLOT)[b] = nb_ * j.lane + b; hptr(R_LROW)[b] = cu[b + 1] - 1; hptr(R_PREFIX)[b] = (int32_t)p0; + seqs.push_back(j.seq[b]); + ctx.push_back((int32_t)p0); } - reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4; + stage_state(seqs, ctx); + reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = nb_ * 4; hptr(R_LANE)[0] = j.lane; hptr(R_LAST)[0] = last ? 1 : 0; hptr(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu); hptr(R_SEED)[1] = (uint32_t)(j.req->seed >> 32); reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4; - reg_[R_CU].used = 3 * 4; - reg_[R_BT].used = 2 * pitch * 4; - reg_[R_USED].used = 2 * 4; + reg_[R_CU].used = (nb_ + 1) * 4; + reg_[R_BT].used = nb_ * pitch * 4; + reg_[R_USED].used = nb_ * 4; reg_[R_LANE].used = reg_[R_LAST].used = 4; reg_[R_SEED].used = 8; if (upload() < 0) return nullptr; - base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); + base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); h_lane_.assign(1, j.lane); h_last_.assign(1, last ? 1 : 0); for (size_t r = 0; r < ranks_.size(); ++r) { @@ -586,7 +682,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - const int64_t L = (int64_t)js.size(), S = 2 * L; + const int64_t L = (int64_t)js.size(), S = nb_ * L; int32_t* tok = hptr(R_TOK); int32_t* pos = hptr(R_POS); int32_t* slot = hptr(R_SLOT); @@ -599,17 +695,19 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) int64_t pitch = 1; int32_t max_ctx = 0; for (const Job* j : js) - for (int b = 0; b < 2; ++b) + for (int b = 0; b < nb_; ++b) pitch = std::max(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size()); h_lane_.assign((size_t)L, 0); h_frame_.assign((size_t)L, 0); pass_.jobs.clear(); + std::vector seqs; + std::vector ctx; for (int64_t i = 0; i < L; ++i) { const Job& j = *js[(size_t)i]; - for (int b = 0; b < 2; ++b) { + for (int b = 0; b < nb_; ++b) { /* The frame's row follows the branch's prompt and its earlier frames. */ const int64_t p = (b ? j.Tn : j.T) + j.frame; - const int64_t e = 2 * i + b; + const int64_t e = nb_ * i + b; const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); tok[e] = 0; pos[e] = (int32_t)p; @@ -618,9 +716,11 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) for (int64_t k = 0; k < pitch; ++k) btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; used[e] = (int32_t)(p + 1); - hptr(R_ESLOT)[e] = 2 * j.lane + b; + hptr(R_ESLOT)[e] = nb_ * j.lane + b; hptr(R_LROW)[e] = (int32_t)e; max_ctx = std::max(max_ctx, (int32_t)(p + 1)); + seqs.push_back(j.seq[b]); + ctx.push_back((int32_t)p); } hptr(R_CFG)[i] = j.cfg; lane[i] = h_lane_[(size_t)i] = j.lane; @@ -630,6 +730,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) pass_.jobs.push_back(j.id); } cu[S] = (int32_t)S; + stage_state(seqs, ctx); reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4; reg_[R_CU].used = (S + 1) * 4; reg_[R_BT].used = S * pitch * 4; diff --git a/core/gen/audio_driver.h b/core/gen/audio_driver.h index bb986103..318b89c7 100644 --- a/core/gen/audio_driver.h +++ b/core/gen/audio_driver.h @@ -5,9 +5,15 @@ * `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads * through `submit()` and leave through their AudioTicket. * - * A request holds a lane and two KV sequences, its conditional and unconditional branches, from - * admission to its last window; both are reserved for the whole piece at admission (prompt plus - * every frame the request may make), so a request in flight never waits for KV. + * A request holds a lane and two KV sequences, its conditional and unconditional branches (one, + * for a model of one branch: RadAudioGenDecl::branches), from admission to its last window; they + * are reserved for the whole piece at admission (prompt plus every frame the request may make), so + * a request in flight never waits for KV. + * + * The language model's KV is one paged full-attention group, beside which a hybrid model keeps + * the linear-attention state and convolution groups of its recurrent layers (RAD_KV_LINEAR, + * RAD_KV_CONV): one slot a sequence each, staged as their `state_index` rows, zeroed by the engine + * before the pass that first reads them. * * Pass priority, one pass at a time: * @@ -54,6 +60,9 @@ public: /* The longest sequence a branch holds: the whole prompt and every frame. The KV group is * sized from it. */ static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; } + /* State slots a state_index row holds at most: the state, and the scratch a kernel serving + * speculation asks for (RadKVGroupBatch::state_index_pitch), which a generator never runs. */ + static constexpr int64_t kMaxStateWidth = 8; /* ---------------------------------------------------------- HTTP threads */ /* Queue a request, refused at once with `why` when it can never run. */ @@ -115,7 +124,10 @@ private: struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED, R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC, - R_ESLOT, R_LROW, R_PREFIX, R_N }; + R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_N }; + /* A hybrid model's stateful groups (linear-attention state, convolution history), each staged + * as one block-table word a sequence (its slot) and its state_index row. */ + struct StateGroup { int32_t g = 0; int64_t width = 1; }; template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { @@ -124,6 +136,9 @@ private: int upload(); void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step, bool kv, int64_t bt_pitch); + /* The stateful groups' rows for the entries of a PROMPT or FRAME pass, entry e being `seq[e]`, + * with each entry's context before the pass (ctx_lens). */ + void stage_state(const std::vector& seqs, const std::vector& ctx); int admit_locked(); void release_locked(Job& j); @@ -152,6 +167,8 @@ private: int64_t max_tok_ = 0, max_seqs_ = 0; int64_t block_size_ = 0, max_blocks_ = 0; int32_t kv_group_ = 0; + std::vector state_groups_; + int nb_ = 2; /* sequences a request: RadAudioGenDecl::branches */ bool neg_own_ = false; /* the unconditional prompt is the request's own */ std::vector ranks_; IKVManager* kv_ = nullptr; @@ -167,7 +184,7 @@ private: std::vector out_; /* one per rank */ std::vector aout_; - std::vector kout_; + std::vector kout_; /* [rank][1 + state groups] */ Pass pass_; bool frame_turn_ = true; /* FRAME goes first when both are due */ /* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */ diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index ebe50260..78c8e93b 100644 --- a/core/server/audio_gen.cpp +++ b/core/server/audio_gen.cpp @@ -14,8 +14,9 @@ * Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin * into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with * its special tokens and the texts without, so a caller cannot write the model's control tokens - * into a lyric. A model that declares the unconditional branch's own template gets that one - * rendered from the same texts. + * into a lyric; a model that declares `input_special` has its input tokenised with them too (its + * speaker tags), its prepare() refusing the control tokens. A model that declares the + * unconditional branch's own template gets that one rendered from the same texts. * * Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the * model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the @@ -156,6 +157,8 @@ int Server::speech_request(const json& body, const std::string& text, if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get() >= 1.0) || body["guidance_scale"].get() > 30.0) return fail(err_bad("guidance_scale", "expected a number in [1, 30]")); + if (info.branches == 1 && body["guidance_scale"].get() != 1.0) + return fail(err_unsupported("guidance_scale", "this model runs without guidance")); r->cfg = (float)body["guidance_scale"].get(); } bool seed_given = false; @@ -191,7 +194,10 @@ int Server::speech_request(const json& body, const std::string& text, } if (p == std::string::npos) break; const bool is_inst = p == a; - const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false); + /* The input keeps its special tokens only for a model that asks (its speaker tags); + * the plugin's prepare() has refused the ones a caller may not write. */ + const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, + /*parse_special=*/!is_inst && info.input_special); ids_out->insert(ids_out->end(), ids.begin(), ids.end()); at = p + (is_inst ? kInst : kInput).size(); } diff --git a/core/server/iface.h b/core/server/iface.h index 8cd70dd4..664bdae4 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -649,6 +649,10 @@ struct AudioGenInfo { int64_t sample_rate = 0, channels = 0; int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */ double default_cfg = 1.0; + /* RadAudioGenDecl::branches (1: no guidance) and ::input_special (the {input} slot is + * tokenised with special tokens). */ + int32_t branches = 2; + bool input_special = false; }; class IAudioGen { diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 0abae8bf..8187d639 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -169,6 +169,8 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole) ABI_FIELD(RadAudioGenDecl, first_frame) ABI_FIELD(RadAudioGenDecl, voc_chunk) ABI_FIELD(RadAudioGenDecl, voc_context) +ABI_FIELD(RadAudioGenDecl, branches) +ABI_FIELD(RadAudioGenDecl, input_special) ABI_STRUCT(RadAudioFormat) ABI_FIELD(RadAudioFormat, struct_size) ABI_FIELD(RadAudioFormat, audio_open) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 9ff6bc7a..ed92fab5 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -134,7 +134,7 @@ { "RadAudioGenBatch", "voc_left", 244, 4 }, { "RadAudioGenBatch", "voc_right", 248, 4 }, { "RadAudioGenBatch", "voc_frame0", 256, 8 }, -{ "RadAudioGenDecl", "", 0, 224 }, +{ "RadAudioGenDecl", "", 0, 232 }, { "RadAudioGenDecl", "name", 0, 8 }, { "RadAudioGenDecl", "tmpl", 8, 8 }, { "RadAudioGenDecl", "neg_token", 16, 4 }, @@ -166,6 +166,8 @@ { "RadAudioGenDecl", "first_frame", 204, 4 }, { "RadAudioGenDecl", "voc_chunk", 208, 8 }, { "RadAudioGenDecl", "voc_context", 216, 8 }, +{ "RadAudioGenDecl", "branches", 224, 4 }, +{ "RadAudioGenDecl", "input_special", 228, 4 }, { "RadAudioFormat", "", 0, 72 }, { "RadAudioFormat", "struct_size", 0, 4 }, { "RadAudioFormat", "audio_open", 8, 8 }, diff --git a/tests/audio_gen_test.cpp b/tests/audio_gen_test.cpp index c99cffcb..c076fba8 100644 --- a/tests/audio_gen_test.cpp +++ b/tests/audio_gen_test.cpp @@ -209,4 +209,89 @@ TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) { } } +/* A hybrid language model (paged attention beside a linear-attention state and a convolution + * group, as Qwen3.5's delta-net layers keep) of one branch: every pass stages one sequence a + * request, the state groups' rows are the sequence's slots, and each entry carries its context + * and a one-based num_accepted. The slots held at the prompt are the frames' too; guidance other + * than 1 is refused. */ +TEST(a_hybrid_model_of_one_branch_stages_its_state_groups) { + AudioFixture f; + f.prog.audio_gen = decl_chunked(); + f.prog.audio_gen.branches = 1; + f.prog.agen_str.name = "hybrid"; + f.prog.ctx.max_tok = 64; + f.prog.ctx.max_seqs = 8; + f.prog.kv_groups.emplace_back(); + for (int kind : { RAD_KV_FULL, RAD_KV_LINEAR, RAD_KV_CONV }) { + KVGroupInfo g; + g.name = kind == RAD_KV_FULL ? "attn" : kind == RAD_KV_LINEAR ? "state" : "conv"; + g.decl.kind = kind; + g.block_size = kind == RAD_KV_FULL ? 16 : 0; + f.prog.kv_groups.push_back(g); + } + f.kv.setup(f.prog.kv_groups, 1 << 20, 256, 4); + CHECK_OK(f.start()); + std::string why; + CHECK(f.drv.submit(f.req(2.0f), &why) < 0); + CHECK(has(why, "without guidance")); + CHECK_OK(f.drv.submit(f.req(1.0f), &why)); + + auto state_rows = [](const RadBatch* b, int32_t* st, int32_t* cv) { + *st = *cv = -2; + for (int i = 0; i < b->n_kv_groups; ++i) { + const RadKVGroupBatch& k = b->kv[i]; + if (k.group == 1) continue; + REQUIRE(k.state_index != nullptr && k.block_table != nullptr); + CHECK_EQ(k.block_table[0], k.state_index[0]); + (k.group == 2 ? *st : *cv) = k.state_index[0]; + } + }; + const RadBatch* b = f.drv.next(0); + REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT); + CHECK_EQ(b->n_seq, (int64_t)1); + CHECK_EQ(b->n_tok, (int64_t)4); + REQUIRE_EQ(b->n_kv_groups, 3); + int32_t st0 = 0, cv0 = 0; + state_rows(b, &st0, &cv0); + CHECK(st0 >= 0 && cv0 >= 0); + REQUIRE(b->ctx_lens != nullptr && b->num_accepted != nullptr); + CHECK_EQ(b->ctx_lens[0], 0); + CHECK_EQ(b->num_accepted[0], 1); + CHECK_EQ(b->agen_b->slot[0], b->agen_b->lane_h[0]); /* one branch: the slot is the lane */ + f.answer(b, 0, 0.0f); + CHECK_OK(f.drv.done()); + + b = f.drv.next(1); + REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_FRAME); + CHECK_EQ(b->n_seq, (int64_t)1); + CHECK_EQ(b->n_tok, (int64_t)1); + CHECK_EQ(b->positions[0], 4); /* after the four prompt rows */ + CHECK_EQ(b->ctx_lens[0], 4); + CHECK_EQ(b->num_accepted[0], 1); + int32_t st1 = 0, cv1 = 0; + state_rows(b, &st1, &cv1); + CHECK_EQ(st1, st0); + CHECK_EQ(cv1, cv0); +} + +/* The driver stages one paged group beside state groups: a second paged group is refused at init, + * by name. */ +TEST(a_second_paged_group_is_refused) { + AudioFixture f; + f.prog.audio_gen = decl_chunked(); + f.prog.agen_str.name = "two"; + f.prog.ctx.max_tok = 64; + f.prog.ctx.max_seqs = 8; + f.prog.kv_groups.emplace_back(); + for (int i = 0; i < 2; ++i) { + KVGroupInfo g; + g.name = i ? "b" : "a"; + g.decl.kind = RAD_KV_FULL; + g.block_size = 16; + f.prog.kv_groups.push_back(g); + } + f.kv.setup(f.prog.kv_groups, 1 << 20, 256, 4); + CHECK(f.start() < 0); +} + RAD_TEST_MAIN() diff --git a/tests/speech_test.cpp b/tests/speech_test.cpp index 6574c0f5..6cb7536f 100644 --- a/tests/speech_test.cpp +++ b/tests/speech_test.cpp @@ -174,6 +174,28 @@ TEST(a_speech_model_takes_optional_instructions_and_renders_its_unconditional_pr CHECK(m.last().neg_tokens.empty()); } +/* A model that declares input_special (its speaker tags are special tokens) has its input + * tokenised with them, and one of one branch refuses any guidance but 1 under its field; other + * models' input stays plain text. */ +TEST(a_model_that_asks_has_its_input_read_with_special_tokens_and_one_branch_has_no_guidance) { + Speech s; + s.gen.inf.tmpl_plain = "{input}"; + s.gen.inf.default_steps = 0; + s.gen.inf.input_special = true; + s.gen.inf.branches = 1; + s.f->tok.last_parse_special = false; + CHECK_EQ(s.post({ { "input", "hi" } }).status, 200); + CHECK(s.f->tok.last_parse_special); + CHECK_EQ(s.refused({ { "input", "hi" }, { "guidance_scale", 2.0 } }), + std::string("guidance_scale")); + CHECK_EQ(s.post({ { "input", "hi" }, { "guidance_scale", 1.0 } }).status, 200); + Speech m; + m.gen.inf.tmpl_plain = "{input}"; + m.gen.inf.default_steps = 0; + CHECK_EQ(m.post({ { "input", "hi" } }).status, 200); + CHECK(!m.f->tok.last_parse_special); +} + /* ================================================================== the response */ /* The whole piece: the windows in order whatever order they were played in, as a WAV whose header From 61abb990abeadddf8b8e168089a8e4b2b97fa61d Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 21:05:41 +0200 Subject: [PATCH 04/35] core/format: a torch.save checkpoint beside the safetensors, read as data -- stored zip entries mapped, the pickle run by a weights-only machine that refuses any other global or opcode by name; hfget fetches a .pth that is not the weights again (Fish Audio drama-3's codec) --- core/format/checkpoint.cpp | 54 +++- core/format/checkpoint.h | 3 + core/format/torch_zip.cpp | 633 +++++++++++++++++++++++++++++++++++++ core/format/torch_zip.h | 64 ++++ scripts/hfget.sh | 7 +- spec.md | 8 + tests/hf_model_test.cpp | 35 ++ tests/torch_zip_test.cpp | 341 ++++++++++++++++++++ 8 files changed, 1142 insertions(+), 3 deletions(-) create mode 100644 core/format/torch_zip.cpp create mode 100644 core/format/torch_zip.h create mode 100644 tests/torch_zip_test.cpp diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index f195e778..fb5a4029 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -852,7 +852,10 @@ int Checkpoint::open_safetensors(const std::string& path) { RAD_TRY(meta_merge_generation_config(md, &meta_)); RAD_TRY(meta_merge_preprocessor_configs(md, &meta_)); if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_; - if (!is_file && !is_index) RAD_TRY(add_companions()); + if (!is_file && !is_index) { + RAD_TRY(add_companions()); + RAD_TRY(add_torch_files()); + } /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { long long r = 0, c = 0; @@ -895,6 +898,55 @@ int Checkpoint::add_companions() { return RAD_OK; } +/* PyTorch checkpoints beside the safetensors (torch_zip.h): a model whose part ships only as a + * torch.save file, such as Fish Audio drama-3's codec.pth, read as data, never unpickled. Each is + * read under `.`, in name order. A file the weights-only reader refuses (a pickled training + * state, an optimiser) is not an error of the checkpoint, only of a plugin that maps its tensors, + * which then finds them absent; the warning says why. A torch copy of the model's own weights + * (`pytorch_model*.pth`, `consolidated*.pth`) is passed over, as the safetensors are read. */ +int Checkpoint::add_torch_files() { + std::vector files; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_regular_file(ec)) continue; + const std::string f = de.path().filename().string(); + if (f.size() <= 4 || f.compare(f.size() - 4, 4, ".pth") != 0) continue; + if (f.rfind("pytorch_model", 0) == 0 || f.rfind("consolidated", 0) == 0) continue; + files.push_back(f); + } + std::sort(files.begin(), files.end()); + for (const std::string& f : files) { + auto tz = std::make_unique(); + std::string why; + const std::string path = dir_ + "/" + f; + if (tz->open(path, &why) < 0) { + RAD_WARN("%s: not read (%s); a plugin that maps its tensors will not find them", + path.c_str(), why.c_str()); + continue; + } + const std::string prefix = f.substr(0, f.size() - 4) + "."; + for (const TorchTensor& t : tz->tensors()) { + if (index_.count(prefix + t.name)) { + RAD_ERR("%s: '%s%s' is already in the checkpoint", path.c_str(), prefix.c_str(), + t.name.c_str()); + return RAD_E_FORMAT; + } + SrcTensor s; + s.name = prefix + t.name; + s.rad_dtype = t.dtype; + s.shape = t.shape; + s.data = t.data; + s.bytes = (int64_t)t.bytes; + index_.emplace(s.name, tensors_.size()); + tensors_.push_back(std::move(s)); + } + RAD_INFO("%s: %zu tensors under '%s', read from the pickle as data", path.c_str(), + tz->tensors().size(), prefix.c_str()); + torch_.push_back(std::move(tz)); + } + return RAD_OK; +} + /* Which published quantisation this is, from quantization_config alone; import_piece checks the * tensors weight by weight, refusing a file at the first weight that disagrees. */ void Checkpoint::detect_import() { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 3846d1cb..e79bbda6 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -24,6 +24,7 @@ #include "../rad_internal.h" #include "../rad_core.h" #include "safetensors.h" +#include "torch_zip.h" #include "../text/gguf.h" #include @@ -187,6 +188,7 @@ private: int open_diffusers(); int open_sgm(); int add_companions(); + int add_torch_files(); int open_gguf(const std::string& path); void detect_import(); @@ -195,6 +197,7 @@ private: GgufFile gguf_; MetaOwn meta_; std::vector> shards_; + std::vector> torch_; std::vector tensors_; std::unordered_map index_; std::unordered_map index_shard_; /* name -> shards_ position */ diff --git a/core/format/torch_zip.cpp b/core/format/torch_zip.cpp new file mode 100644 index 00000000..8e1a0eec --- /dev/null +++ b/core/format/torch_zip.cpp @@ -0,0 +1,633 @@ +/* torch_zip.cpp -- the zip directory and the weights-only pickle machine (torch_zip.h). */ +#include "torch_zip.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace { + +/* ================================================================== the zip directory */ +struct Entry { + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +uint16_t u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } +uint32_t u32(const uint8_t* p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +uint64_t u64(const uint8_t* p) { return (uint64_t)u32(p) | ((uint64_t)u32(p + 4) << 32); } + +/* Every stored entry, by name. torch.save writes ZIP64 records past 4 GiB and pads each local + * header's extra field so a storage starts 64-byte aligned, which is why the data offset is read + * from the local header rather than assumed from the central one. */ +int zip_entries(const uint8_t* b, uint64_t n, std::unordered_map* out, + std::string* why) { + auto no = [&](const std::string& w) { + *why = w; + return RAD_E_FORMAT; + }; + if (n < 22) return no("too short to be a zip archive"); + /* The end-of-central-directory record: the last signature within a comment's reach. */ + int64_t eocd = -1; + const uint64_t lo = n > 22 + 65535 ? n - 22 - 65535 : 0; + for (uint64_t at = n - 22 + 1; at-- > lo;) + if (u32(b + at) == 0x06054b50) { + eocd = (int64_t)at; + break; + } + if (eocd < 0) return no("no zip end-of-central-directory record"); + if (u16(b + eocd + 4) != 0 || u16(b + eocd + 6) != 0) return no("a multi-disk zip archive"); + uint64_t count = u16(b + eocd + 10), cd_size = u32(b + eocd + 12), cd_off = u32(b + eocd + 16); + if (count == 0xffff || cd_size == 0xffffffffu || cd_off == 0xffffffffu) { + if (eocd < 20 || u32(b + eocd - 20) != 0x07064b50) + return no("a ZIP64 archive without its end-record locator"); + const uint64_t z = u64(b + eocd - 20 + 8); + if (n < 56 || z > n - 56 || u32(b + z) != 0x06064b50) + return no("a ZIP64 end record outside the file"); + count = u64(b + z + 32); + cd_size = u64(b + z + 40); + cd_off = u64(b + z + 48); + } + if (cd_off > n || cd_size > n - cd_off) return no("the central directory lies outside the file"); + if (count > ((uint64_t)1 << 20)) return no("more than a million zip entries"); + uint64_t at = cd_off; + const uint64_t end = cd_off + cd_size; + for (uint64_t i = 0; i < count; ++i) { + if (end - at < 46 || at > end || u32(b + at) != 0x02014b50) + return no("a malformed central directory entry"); + const uint16_t flags = u16(b + at + 8), method = u16(b + at + 10); + uint64_t csize = u32(b + at + 20), usize = u32(b + at + 24); + const uint64_t nl = u16(b + at + 28), el = u16(b + at + 30), cl = u16(b + at + 32); + uint64_t loff = u32(b + at + 42); + if (46 + nl + el + cl > end - at) return no("a central directory entry runs past its end"); + const std::string name((const char*)b + at + 46, (size_t)nl); + /* The ZIP64 extra field: an 8-byte value for each 32-bit field at its maximum, in order. */ + const uint8_t* ex = b + at + 46 + nl; + for (uint64_t e = 0; e + 4 <= el;) { + const uint64_t id = u16(ex + e), sz = u16(ex + e + 2); + if (e + 4 + sz > el) return no("a malformed extra field in '" + name + "'"); + if (id == 1) { + uint64_t f = e + 4; + const uint64_t fe = e + 4 + sz; + auto take = [&](uint64_t* v) { + if (*v != 0xffffffffu) return true; + if (f + 8 > fe) return false; + *v = u64(ex + f); + f += 8; + return true; + }; + if (!take(&usize) || !take(&csize) || !take(&loff)) + return no("a short ZIP64 extra field in '" + name + "'"); + } + e += 4 + sz; + } + if (flags & 1) return no("'" + name + "' is encrypted"); + if (method != 0) + return no("'" + name + "' is compressed (method " + std::to_string(method) + + "); torch.save stores its entries, and a compressed storage cannot be mapped"); + if (csize != usize) return no("'" + name + "' is stored with two different sizes"); + if (n < 30 || loff > n - 30 || u32(b + loff) != 0x04034b50) + return no("'" + name + "' has no local header where the directory places it"); + const uint64_t data = loff + 30 + u16(b + loff + 26) + u16(b + loff + 28); + if (data > n || usize > n - data) return no("'" + name + "' runs past the end of the file"); + if (!out->emplace(name, Entry{ b + data, usize }).second) + return no("'" + name + "' is in the archive twice"); + at += 46 + nl + el + cl; + } + return RAD_OK; +} + +/* ================================================================== the pickle machine */ +/* A value of the weights-only subset. Containers hold indices into the machine's pool, so a value + * reached twice through the memo is one value. */ +struct V { + enum K : uint8_t { None, Bool, Int, Float, Str, Bytes, Tuple, List, Dict, Global, Storage, + Tensor } k = None; + int64_t i = 0; /* Int, Bool; Storage: numel */ + double f = 0; + std::string s; /* Str, Bytes, Global's "module.name", Storage's key */ + std::vector a; /* Tuple, List; Dict: keys and values interleaved */ + uint32_t dtype = 0; /* Storage */ + std::string cls; /* Storage: its class */ + size_t storage = 0; /* Tensor */ + int64_t offset = 0; /* Tensor, in elements */ + std::vector shape, stride; /* Tensor */ +}; + +/* The storages torch writes a state dict's tensors into, and the dtype each holds. Doubles and + * complex storages have no RAD dtype and are refused by name where they appear. */ +uint32_t storage_dtype(const std::string& g) { + static const struct { const char* name; uint32_t dt; } kS[] = { + { "torch.FloatStorage", RAD_F32 }, { "torch.HalfStorage", RAD_F16 }, + { "torch.BFloat16Storage", RAD_BF16 }, { "torch.LongStorage", RAD_I64 }, + { "torch.IntStorage", RAD_I32 }, { "torch.ShortStorage", RAD_I16 }, + { "torch.CharStorage", RAD_I8 }, { "torch.ByteStorage", RAD_U8 }, + { "torch.BoolStorage", RAD_BOOL }, + }; + for (const auto& s : kS) + if (g == s.name) return s.dt; + return RAD_DT_INVALID; +} + +/* torch's weights-only allow-list, the part a state dict uses. */ +bool allowed_global(const std::string& g) { + return g == "collections.OrderedDict" || g == "torch._utils._rebuild_tensor_v2" || + g == "torch._utils._rebuild_parameter" || storage_dtype(g) != RAD_DT_INVALID; +} + +class Machine { +public: + Machine(const uint8_t* p, uint64_t n) : p_(p), n_(n) {} + + /* The pickle's result, or a negative status with `why`. */ + int run(size_t* result, std::string* why); + const V& at(size_t i) const { return pool_[i]; } + +private: + static constexpr size_t kMaxPool = (size_t)1 << 23; + static constexpr size_t kMaxStack = (size_t)1 << 20; + static constexpr uint64_t kMaxStr = (uint64_t)1 << 20; + + int no(const std::string& w) { + why_ = w + " at byte " + std::to_string(at_) + " of the pickle"; + return RAD_E_FORMAT; + } + bool need(uint64_t k) const { return n_ - at_ >= k; } + size_t add(V v) { + pool_.push_back(std::move(v)); + return pool_.size() - 1; + } + bool pop(size_t* v) { + if (stack_.size() <= (marks_.empty() ? 0 : marks_.back())) return false; + *v = stack_.back(); + stack_.pop_back(); + return true; + } + /* The items above the last mark, and the mark gone. */ + bool pop_mark(std::vector* items) { + if (marks_.empty()) return false; + const size_t m = marks_.back(); + marks_.pop_back(); + items->assign(stack_.begin() + (std::ptrdiff_t)m, stack_.end()); + stack_.resize(m); + return true; + } + int push(size_t v) { + if (stack_.size() >= kMaxStack || pool_.size() >= kMaxPool) + return no("the pickle builds more than its bounds allow"); + stack_.push_back(v); + return RAD_OK; + } + int str(uint64_t len, V::K k) { + if (len > kMaxStr || !need(len)) return no("a string past its bound or the pickle's end"); + V v; + v.k = k; + v.s.assign((const char*)p_ + at_, (size_t)len); + at_ += len; + return push(add(std::move(v))); + } + int integer(int64_t x) { + V v; + v.k = V::Int; + v.i = x; + return push(add(std::move(v))); + } + int global(const std::string& mod, const std::string& name) { + const std::string g = mod + "." + name; + if (!allowed_global(g)) + return no("the global '" + g + "', which a weights-only checkpoint does not name; " + "nothing in the file is run, so it is refused"); + V v; + v.k = V::Global; + v.s = g; + return push(add(std::move(v))); + } + int reduce(); + int persistent_id(); + + const uint8_t* p_; + uint64_t n_; + uint64_t at_ = 0; + std::vector pool_; + std::vector stack_, marks_; + std::unordered_map memo_; + std::string why_; +}; + +int Machine::persistent_id() { + size_t pid; + if (!pop(&pid)) return no("BINPERSID with nothing to read"); + const V& t = pool_[pid]; + /* ('storage', , key, location, numel) */ + if (t.k != V::Tuple || t.a.size() != 5 || pool_[t.a[0]].k != V::Str || + pool_[t.a[0]].s != "storage" || pool_[t.a[1]].k != V::Global || + pool_[t.a[2]].k != V::Str || pool_[t.a[4]].k != V::Int) + return no("a persistent id that is not a storage"); + V s; + s.k = V::Storage; + s.cls = pool_[t.a[1]].s; + s.dtype = storage_dtype(s.cls); + s.s = pool_[t.a[2]].s; + s.i = pool_[t.a[4]].i; + if (s.dtype == RAD_DT_INVALID) return no("the storage class '" + s.cls + "'"); + if (s.i < 0) return no("a storage of negative size"); + return push(add(std::move(s))); +} + +int Machine::reduce() { + size_t args, fn; + if (!pop(&args) || !pop(&fn)) return no("REDUCE without its callable and arguments"); + if (pool_[fn].k != V::Global) return no("REDUCE of something that is not a global"); + if (pool_[args].k != V::Tuple) return no("REDUCE with arguments that are not a tuple"); + const std::string g = pool_[fn].s; + const std::vector a = pool_[args].a; + if (g == "collections.OrderedDict") { + if (!a.empty()) return no("an OrderedDict built from arguments"); + V d; + d.k = V::Dict; + return push(add(std::move(d))); + } + if (g == "torch._utils._rebuild_tensor_v2") { + /* (storage, storage_offset, size, stride, requires_grad, backward_hooks[, metadata]) */ + if (a.size() < 4 || pool_[a[0]].k != V::Storage || pool_[a[1]].k != V::Int || + pool_[a[2]].k != V::Tuple || pool_[a[3]].k != V::Tuple) + return no("_rebuild_tensor_v2 with arguments that are not a tensor's"); + V t; + t.k = V::Tensor; + t.storage = a[0]; + t.offset = pool_[a[1]].i; + for (size_t d : pool_[a[2]].a) { + if (pool_[d].k != V::Int || pool_[d].i < 0) return no("a tensor size that is not one"); + t.shape.push_back(pool_[d].i); + } + for (size_t d : pool_[a[3]].a) { + if (pool_[d].k != V::Int) return no("a tensor stride that is not one"); + t.stride.push_back(pool_[d].i); + } + if (t.shape.size() != t.stride.size() || t.shape.size() > RAD_MAX_RANK) + return no("a tensor whose size and stride disagree, or of rank past " + + std::to_string(RAD_MAX_RANK)); + return push(add(std::move(t))); + } + if (g == "torch._utils._rebuild_parameter") { + /* (data, requires_grad, backward_hooks): the parameter is its tensor. */ + if (a.empty() || pool_[a[0]].k != V::Tensor) return no("_rebuild_parameter of a non-tensor"); + return push(a[0]); + } + return no("a call of '" + g + "'"); +} + +int Machine::run(size_t* result, std::string* why) { + auto fail = [&](int st) { + *why = why_; + return st; + }; + auto line = [&](std::string* out) { + const uint8_t* e = (const uint8_t*)std::memchr(p_ + at_, '\n', (size_t)(n_ - at_)); + if (!e || (uint64_t)(e - (p_ + at_)) > 4096) return false; + out->assign((const char*)p_ + at_, (size_t)(e - (p_ + at_))); + at_ = (uint64_t)(e - p_) + 1; + return true; + }; + int st = RAD_OK; + while (at_ < n_) { + const uint8_t op = p_[at_++]; + switch (op) { + case 0x80: /* PROTO */ + if (!need(1) || p_[at_] < 2 || p_[at_] > 5) return fail(no("a pickle protocol other than 2..5")); + ++at_; + break; + case 0x95: /* FRAME: a length hint */ + if (!need(8)) return fail(no("a truncated FRAME")); + at_ += 8; + break; + case 'c': { /* GLOBAL "module\nname\n" */ + std::string mod, name; + if (!line(&mod) || !line(&name)) return fail(no("a malformed GLOBAL")); + st = global(mod, name); + break; + } + case 0x93: { /* STACK_GLOBAL */ + size_t nm, md; + if (!pop(&nm) || !pop(&md) || pool_[nm].k != V::Str || pool_[md].k != V::Str) + return fail(no("STACK_GLOBAL without a module and a name")); + st = global(pool_[md].s, pool_[nm].s); + break; + } + case 'q': case 'r': case 0x94: { /* BINPUT, LONG_BINPUT, MEMOIZE */ + uint32_t k; + if (op == 'q') { + if (!need(1)) return fail(no("a truncated BINPUT")); + k = p_[at_++]; + } else if (op == 'r') { + if (!need(4)) return fail(no("a truncated LONG_BINPUT")); + k = u32(p_ + at_); + at_ += 4; + } else { + k = (uint32_t)memo_.size(); + } + if (stack_.empty()) return fail(no("a memo store with nothing to store")); + if (memo_.size() >= kMaxStack) return fail(no("a memo past its bound")); + memo_[k] = stack_.back(); + break; + } + case 'h': case 'j': { /* BINGET, LONG_BINGET */ + uint32_t k; + if (op == 'h') { + if (!need(1)) return fail(no("a truncated BINGET")); + k = p_[at_++]; + } else { + if (!need(4)) return fail(no("a truncated LONG_BINGET")); + k = u32(p_ + at_); + at_ += 4; + } + auto it = memo_.find(k); + if (it == memo_.end()) return fail(no("a memo read of an empty slot")); + st = push(it->second); + break; + } + case '(': /* MARK */ + if (marks_.size() >= kMaxStack) return fail(no("marks past their bound")); + marks_.push_back(stack_.size()); + break; + case ')': { /* EMPTY_TUPLE */ + V t; + t.k = V::Tuple; + st = push(add(std::move(t))); + break; + } + case 't': case 0x85: case 0x86: case 0x87: { /* TUPLE, TUPLE1..3 */ + V t; + t.k = V::Tuple; + if (op == 't') { + if (!pop_mark(&t.a)) return fail(no("TUPLE without a mark")); + } else { + const int k = op - 0x84; + t.a.resize((size_t)k); + for (int j = k - 1; j >= 0; --j) + if (!pop(&t.a[(size_t)j])) return fail(no("a short tuple")); + } + st = push(add(std::move(t))); + break; + } + case ']': case '}': { /* EMPTY_LIST, EMPTY_DICT */ + V c; + c.k = op == ']' ? V::List : V::Dict; + st = push(add(std::move(c))); + break; + } + case 'a': case 'e': { /* APPEND, APPENDS */ + std::vector items(1); + if (op == 'a') { + if (!pop(&items[0])) return fail(no("APPEND with nothing to append")); + } else if (!pop_mark(&items)) { + return fail(no("APPENDS without a mark")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::List) + return fail(no("APPEND to something that is not a list")); + V& l = pool_[stack_.back()]; + l.a.insert(l.a.end(), items.begin(), items.end()); + break; + } + case 's': case 'u': { /* SETITEM, SETITEMS */ + std::vector kv(2); + if (op == 's') { + if (!pop(&kv[1]) || !pop(&kv[0])) return fail(no("SETITEM without a pair")); + } else if (!pop_mark(&kv) || kv.size() % 2) { + return fail(no("SETITEMS without whole pairs")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("a SETITEM on something that is not a dict")); + V& d = pool_[stack_.back()]; + d.a.insert(d.a.end(), kv.begin(), kv.end()); + break; + } + case 'b': { /* BUILD: an OrderedDict's state (a state dict's _metadata), ignored */ + size_t state; + if (!pop(&state)) return fail(no("BUILD without a state")); + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("BUILD of something other than a dict")); + break; + } + case 'X': case 0x8c: case 0x8d: case 'B': case 'C': case 0x8e: { + /* BINUNICODE, SHORT_BINUNICODE, BINUNICODE8, BINBYTES, SHORT_BINBYTES, BINBYTES8 */ + uint64_t len; + const int w = (op == 0x8c || op == 'C') ? 1 : (op == 0x8d || op == 0x8e) ? 8 : 4; + if (!need((uint64_t)w)) return fail(no("a truncated string length")); + len = w == 1 ? p_[at_] : w == 4 ? u32(p_ + at_) : u64(p_ + at_); + at_ += (uint64_t)w; + st = str(len, (op == 'B' || op == 'C' || op == 0x8e) ? V::Bytes : V::Str); + break; + } + case 'J': /* BININT */ + if (!need(4)) return fail(no("a truncated BININT")); + st = integer((int32_t)u32(p_ + at_)); + at_ += 4; + break; + case 'K': /* BININT1 */ + if (!need(1)) return fail(no("a truncated BININT1")); + st = integer(p_[at_++]); + break; + case 'M': /* BININT2 */ + if (!need(2)) return fail(no("a truncated BININT2")); + st = integer(u16(p_ + at_)); + at_ += 2; + break; + case 0x8a: { /* LONG1: little-endian two's complement of up to 8 bytes here */ + if (!need(1)) return fail(no("a truncated LONG1")); + const uint64_t k = p_[at_++]; + if (k > 8 || !need(k)) return fail(no("a LONG1 wider than 64 bits")); + uint64_t v = 0; + for (uint64_t j = 0; j < k; ++j) v |= (uint64_t)p_[at_ + j] << (8 * j); + if (k > 0 && k < 8 && (p_[at_ + k - 1] & 0x80)) v |= ~(uint64_t)0 << (8 * k); + at_ += k; + st = integer((int64_t)v); + break; + } + case 'G': { /* BINFLOAT, big-endian */ + if (!need(8)) return fail(no("a truncated BINFLOAT")); + uint64_t v = 0; + for (int j = 0; j < 8; ++j) v = (v << 8) | p_[at_ + j]; + at_ += 8; + V f; + f.k = V::Float; + std::memcpy(&f.f, &v, 8); + st = push(add(std::move(f))); + break; + } + case 0x88: case 0x89: { /* NEWTRUE, NEWFALSE */ + V v; + v.k = V::Bool; + v.i = op == 0x88; + st = push(add(std::move(v))); + break; + } + case 'N': + st = push(add(V{})); + break; + case 'Q': + st = persistent_id(); + break; + case 'R': + st = reduce(); + break; + case '.': { /* STOP */ + size_t r; + if (!pop(&r)) return fail(no("STOP with nothing to return")); + *result = r; + return RAD_OK; + } + default: { + char hex[8]; + std::snprintf(hex, sizeof hex, "0x%02x", op); + return fail(no(std::string("the opcode ") + hex + + ", which a weights-only checkpoint does not use")); + } + } + if (st < 0) return fail(st); + } + return fail(no("no STOP before the pickle's end")); +} + +/* A state dict's tensors, nested dicts flattened to dotted names. */ +void walk(const Machine& m, size_t d, const std::string& prefix, + std::vector>* out) { + const V& v = m.at(d); + for (size_t j = 0; j + 1 < v.a.size(); j += 2) { + const V& k = m.at(v.a[j]); + if (k.k != V::Str) continue; + const V& x = m.at(v.a[j + 1]); + if (x.k == V::Tensor) out->emplace_back(prefix + k.s, v.a[j + 1]); + else if (x.k == V::Dict) walk(m, v.a[j + 1], prefix + k.s + ".", out); + } +} + +} /* namespace */ + +/* ================================================================== the file */ +TorchZipFile::~TorchZipFile() { close(); } + +void TorchZipFile::close() { + if (map_) ::munmap(map_, (size_t)bytes_); + if (fd_ >= 0) ::close(fd_); + map_ = nullptr; + base_ = nullptr; + bytes_ = 0; + fd_ = -1; + tensors_.clear(); +} + +int TorchZipFile::open(const std::string& path, std::string* why) { + close(); + path_ = path; + fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd_ < 0) { + *why = std::strerror(errno); + return RAD_E_IO; + } + struct stat st{}; + if (::fstat(fd_, &st) != 0) { + *why = std::strerror(errno); + close(); + return RAD_E_IO; + } + bytes_ = (uint64_t)st.st_size; + void* m = bytes_ ? ::mmap(nullptr, (size_t)bytes_, PROT_READ, MAP_PRIVATE, fd_, 0) : MAP_FAILED; + if (m == MAP_FAILED) { + *why = bytes_ ? std::string("mmap: ") + std::strerror(errno) : std::string("empty file"); + close(); + return bytes_ ? RAD_E_IO : RAD_E_FORMAT; + } + map_ = (uint8_t*)m; + base_ = map_; + const int s = parse(why); + if (s < 0) close(); + return s; +} + +int TorchZipFile::open_bytes(const uint8_t* data, uint64_t bytes, std::string* why) { + close(); + path_ = "(memory)"; + base_ = data; + bytes_ = bytes; + return parse(why); +} + +int TorchZipFile::parse(std::string* why) { + std::unordered_map ent; + RAD_TRY(zip_entries(base_, bytes_, &ent, why)); + /* The archive's one directory: the one holding data.pkl. */ + std::string dir; + int n_pkl = 0; + for (const auto& [name, e] : ent) { + const size_t sl = name.find('/'); + if (sl != std::string::npos && name.compare(sl, std::string::npos, "/data.pkl") == 0) { + dir = name.substr(0, sl + 1); + ++n_pkl; + } + } + if (n_pkl != 1) { + *why = n_pkl ? "more than one data.pkl" : "no /data.pkl: not a torch.save checkpoint"; + return RAD_E_FORMAT; + } + if (auto it = ent.find(dir + "byteorder"); it != ent.end() && + std::string((const char*)it->second.data, (size_t)it->second.bytes) != "little") { + *why = "a big-endian checkpoint"; + return RAD_E_FORMAT; + } + const Entry& pk = ent[dir + "data.pkl"]; + Machine m(pk.data, pk.bytes); + size_t root = 0; + RAD_TRY(m.run(&root, why)); + if (m.at(root).k != V::Dict) { + *why = "the pickle's result is not a state dict"; + return RAD_E_FORMAT; + } + std::vector> found; + walk(m, root, "", &found); + for (const auto& [name, ti] : found) { + const V& t = m.at(ti); + const V& s = m.at(t.storage); + auto it = ent.find(dir + "data/" + s.s); + if (it == ent.end()) { + *why = "'" + name + "' reads storage '" + s.s + "', which the archive does not hold"; + return RAD_E_FORMAT; + } + const int64_t esz = (int64_t)rad_dtype_bits(s.dtype) / 8; + int64_t numel = 1, want = 1; + bool contig = true; + for (size_t d = t.shape.size(); d-- > 0;) { + if (t.shape[d] != 1 && t.stride[d] != want) contig = false; + want *= t.shape[d]; + numel *= t.shape[d]; + } + if (!contig) { + *why = "'" + name + "' is not contiguous in its storage"; + return RAD_E_FORMAT; + } + if (t.offset < 0 || numel > s.i - t.offset || + (uint64_t)((t.offset + numel) * esz) > it->second.bytes) { + *why = "'" + name + "' does not fit its storage '" + s.s + "'"; + return RAD_E_FORMAT; + } + if (numel == 0) continue; + TorchTensor tt; + tt.name = name; + tt.dtype = s.dtype; + tt.storage = s.cls; + tt.shape = t.shape; + tt.data = it->second.data + t.offset * esz; + tt.bytes = (uint64_t)(numel * esz); + tensors_.push_back(std::move(tt)); + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/format/torch_zip.h b/core/format/torch_zip.h new file mode 100644 index 00000000..a0ef7d1a --- /dev/null +++ b/core/format/torch_zip.h @@ -0,0 +1,64 @@ +/* torch_zip.h -- a PyTorch checkpoint (torch.save's zip format) as tensors, read without running + * any of its pickle. + * + * A .pth from torch.save is a zip archive of stored entries: `/data.pkl`, a pickle of the + * state dict whose tensors name their bytes by a persistent id, `/data/` holding + * each storage's raw little-endian bytes, and `/byteorder`. Fish Audio's codec ships this + * way (drama-3's codec.pth), with no safetensors copy. + * + * Unpickling would run whatever the file names. This reads the pickle as data instead: a small + * machine over the opcodes a weights-only file uses, whose only callables are the ones torch's own + * `weights_only` loader allows a state dict (collections.OrderedDict, + * torch._utils._rebuild_tensor_v2 and _rebuild_parameter) and whose only classes are the typed + * storages. Any other global, any other opcode, a compressed or encrypted entry, or a storage that + * does not hold its tensor is refused by name. Every read is bounds-checked and the machine's + * stack, memo and object counts are capped. + * + * Storages are mmapped, not copied; a tensor must be contiguous in its storage. Nested dicts + * flatten to dotted names, and values that are not tensors (an epoch count) are skipped. + */ +#pragma once +#include "../rad_internal.h" + +#include +#include + +namespace rad { + +struct TorchTensor { + std::string name; + uint32_t dtype = RAD_DT_INVALID; + std::string storage; /* the torch storage class, for diagnostics */ + std::vector shape; /* row-major */ + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +class TorchZipFile { +public: + TorchZipFile() = default; + ~TorchZipFile(); + TorchZipFile(const TorchZipFile&) = delete; + TorchZipFile& operator=(const TorchZipFile&) = delete; + + /* RAD_OK, or a negative RAD_E_* with `why` saying what was refused. */ + int open(const std::string& path, std::string* why); + /* The same over bytes the caller keeps alive (a test's archive in memory). */ + int open_bytes(const uint8_t* data, uint64_t bytes, std::string* why); + void close(); + + const std::vector& tensors() const { return tensors_; } + const std::string& path() const { return path_; } + +private: + int parse(std::string* why); + + int fd_ = -1; + uint8_t* map_ = nullptr; + const uint8_t* base_ = nullptr; + uint64_t bytes_ = 0; + std::string path_; + std::vector tensors_; +}; + +} /* namespace rad */ diff --git a/scripts/hfget.sh b/scripts/hfget.sh index 62d9d6fb..1951cd0d 100755 --- a/scripts/hfget.sh +++ b/scripts/hfget.sh @@ -20,7 +20,10 @@ # earlier copy on 3 and refuses on the rest. # # Duplicate weight formats are skipped: when the listing holds any .safetensors, other weight -# formats (pickle .bin, ONNX, GGUF, ...) are not fetched. +# formats (pickle .bin, ONNX, GGUF, ...) are not fetched. A .pth is a duplicate only when it is the +# model's own weights again (`pytorch_model*.pth`, `consolidated*.pth`); any other is a part the +# safetensors do not hold (Fish Audio drama-3's codec.pth) and is fetched, as the checkpoint reader +# reads it (core/format/torch_zip.h). # # HFGET_JOBS concurrent transfers, default 4. These are long sequential reads: a few streams # saturate the link and more only make the destination seek. @@ -107,7 +110,7 @@ done echo "hfget: $page page(s) of listing" have_st=$(printf '%s' "$listing" | jq '[.[] | select(.path | endswith(".safetensors"))] | length') sel='.[] | select(.type == "file")' -[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|pth|msgpack|h5|onnx|onnx_data|gguf)$")) | not)' +[ "$have_st" -gt 0 ] && sel="$sel"' | select((.path | test("\\.(bin|msgpack|h5|onnx|onnx_data|gguf)$") or test("(^|/)(pytorch_model|consolidated)[^/]*\\.pth$")) | not)' list=$(mktemp "${TMPDIR:-/tmp}/hfget.XXXXXX") trap 'rm -f "$list" "$dest/.hfget-manifest.tmp"' EXIT INT TERM diff --git a/spec.md b/spec.md index 1ace7bff..52a4e17f 100644 --- a/spec.md +++ b/spec.md @@ -637,6 +637,14 @@ same path runs. Trivial means served as stored: `fp4_e2m1*e8m0[1x32]`, byte for byte; - GGUF `F32`, `F16` and `BF16`. +**A torch.save file beside the safetensors is read as data** (`core/format/torch_zip.h`), for a +model part that ships only that way (Fish Audio drama-3's `codec.pth`): its tensors join the +namespace under `.`. The zip's stored entries are mapped, and its pickle is read by a machine +over the weights-only subset (the state dict's `OrderedDict`, `_rebuild_tensor_v2`, +`_rebuild_parameter` and the typed storages), so nothing in the file runs; any other global or +opcode is refused by name, and the file is then left out with a warning. A torch copy of the +model's own weights (`pytorch_model*.pth`, `consolidated*.pth`) is passed over. + **Nothing is quantised at load.** A served form that needs quantisation (Flash-Next's int4 experts, an fp8 `lm_head` from a bf16 one) is converted ahead of time (§4.4). A direct load has no file tier, no mapped tier (a checkpoint is neither grouped by movement unit nor aligned for diff --git a/tests/hf_model_test.cpp b/tests/hf_model_test.cpp index 512d1547..0990868a 100644 --- a/tests/hf_model_test.cpp +++ b/tests/hf_model_test.cpp @@ -219,6 +219,41 @@ TEST(a_restart_serves_the_complete_copy_when_the_hub_cannot_be_reached) { } } +/* A hub whose repo holds safetensors beside a torch copy of the same weights and a codec that only + * ships as a .pth: the copies (pytorch_model*.pth, a pickle .bin) are skipped, the codec is + * fetched, since the checkpoint reader reads it (core/format/torch_zip.h). */ +const char* kCodecRepo = + "#!/bin/sh\n" + "out=''; url=''; prev=''\n" + "for a in \"$@\"; do\n" + " [ \"$prev\" = -o ] && out=\"$a\"\n" + " case \"$a\" in https://*) url=\"$a\";; esac\n" + " prev=\"$a\"\n" + "done\n" + "case \"$url\" in *api/models*)\n" + " printf '[{\"type\":\"file\",\"path\":\"model.safetensors\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"codec.pth\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"pytorch_model.pth\",\"size\":3}," + "{\"type\":\"file\",\"path\":\"pytorch_model.bin\",\"size\":3}]'; exit 0;; esac\n" + "[ -n \"$out\" ] && printf abc > \"$out\"\n" + "exit 0\n"; + +TEST(a_pth_that_is_not_the_weights_again_is_fetched_beside_the_safetensors) { + NEED_ARTIFACT(hfget_beside_this_binary()); + if (!on_path("jq")) SKIP("no jq on PATH, which hfget.sh needs"); + TempDir root; + REQUIRE(!root.path.empty()); + FakeCurl curl(kCodecRepo); + const std::string cmd = "sh '" + hfget_beside_this_binary() + + "' radiance-test-owner/radiance-test-model '" + root.path + + "' >/dev/null 2>&1"; + CHECK_EQ(std::system(cmd.c_str()), 0); + CHECK(fs::exists(root.path + "/model.safetensors")); + CHECK(fs::exists(root.path + "/codec.pth")); + CHECK(!fs::exists(root.path + "/pytorch_model.pth")); + CHECK(!fs::exists(root.path + "/pytorch_model.bin")); +} + /* With no --download-dir and neither XDG_CACHE_HOME nor HOME there is nowhere to fetch to, which * is refused by name before anything runs. */ TEST(a_repo_id_with_nowhere_to_fetch_to_is_refused) { diff --git a/tests/torch_zip_test.cpp b/tests/torch_zip_test.cpp new file mode 100644 index 00000000..edafee81 --- /dev/null +++ b/tests/torch_zip_test.cpp @@ -0,0 +1,341 @@ +/* torch_zip_test.cpp -- a PyTorch checkpoint read as data (core/format/torch_zip.h). + * + * Each case writes a torch.save archive the way torch lays one out (stored zip entries, a protocol + * 2 pickle of the state dict naming its storages by persistent id) with a small writer of the same + * subset, then reads it back: the tensors' names, dtypes, shapes and bytes, a nested dict, a + * parameter, a ZIP64 directory. The refusals are the point as much as the reads: a global outside + * the weights-only allow-list (the shape every malicious pickle has), an opcode it does not use, a + * compressed or truncated entry and a tensor its storage does not hold are each refused by name, + * with nothing run. + * + * RAD_TEST_TORCH_PTH, when set, names a real checkpoint (Fish Audio's codec.pth) that is opened as + * well; the case is skipped without it. + */ +#include "rad_test.h" +#include "format/torch_zip.h" +#include "format/checkpoint.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; + +namespace { + +/* ------------------------------------------------------------------ the pickle */ +struct Pkl { + std::string b; + void op(char c) { b += c; } + void u32(uint32_t v) { for (int i = 0; i < 4; ++i) b += (char)((v >> (8 * i)) & 0xff); } + void str(const std::string& s) { op('X'); u32((uint32_t)s.size()); b += s; } + void global(const std::string& mod, const std::string& name) { op('c'); b += mod + "\n" + name + "\n"; } + void integer(int64_t v) { + if (v >= 0 && v < 256) { op('K'); b += (char)v; } + else { op('J'); u32((uint32_t)(int32_t)v); } + } + void tuple_of(const std::vector& v) { op('('); for (int64_t x : v) integer(x); op('t'); } + void ordered_dict() { global("collections", "OrderedDict"); op(')'); op('R'); } +}; + +struct Tensor { + std::string name, storage_cls, key; + std::vector shape, stride; + int64_t offset = 0, numel = 0; /* the storage's elements */ + bool parameter = false; +}; + +/* One tensor's _rebuild_tensor_v2 call, optionally wrapped as a parameter. */ +void put_tensor(Pkl& p, const Tensor& t, const std::string& storage_mod = "torch") { + if (t.parameter) p.global("torch._utils", "_rebuild_parameter"); + p.global("torch._utils", "_rebuild_tensor_v2"); + p.op('('); + p.op('('); + p.str("storage"); + p.global(storage_mod, t.storage_cls); + p.str(t.key); + p.str("cpu"); + p.integer(t.numel); + p.op('t'); + p.op('Q'); + p.integer(t.offset); + p.tuple_of(t.shape); + p.tuple_of(t.stride); + p.op((char)0x89); /* requires_grad False */ + p.ordered_dict(); + p.op('t'); + p.op('R'); + if (t.parameter) { + /* (tensor, requires_grad, hooks): the tensor is below; build the argument tuple around it. */ + p.op((char)0x89); + p.ordered_dict(); + p.op((char)0x87); /* TUPLE3 */ + p.op('R'); + } +} + +/* A state dict of `ts`, and `nested` under "generator." as a second dict. */ +std::string state_dict(const std::vector& ts, const std::vector& nested = {}) { + Pkl p; + p.op((char)0x80); + p.b += (char)2; + p.ordered_dict(); + p.op('('); + for (const Tensor& t : ts) { + p.str(t.name); + put_tensor(p, t); + } + if (!nested.empty()) { + p.str("generator"); + p.ordered_dict(); + p.op('('); + for (const Tensor& t : nested) { + p.str(t.name); + put_tensor(p, t); + } + p.op('u'); + } + p.str("epoch"); /* a value that is not a tensor: skipped */ + p.integer(7); + p.op('u'); + /* The state dict's _metadata, as torch writes it: BUILD with a dict state. */ + p.op('}'); + p.op('b'); + p.op('.'); + return p.b; +} + +/* ------------------------------------------------------------------ the zip */ +struct ZipEntry { std::string name, data; uint16_t method = 0; }; + +void le(std::string* s, uint64_t v, int bytes) { + for (int i = 0; i < bytes; ++i) s->push_back((char)((v >> (8 * i)) & 0xff)); +} + +/* Stored entries, each local header's extra field padded so the data starts 64-byte aligned (as + * torch.save aligns storages), then the central directory, ZIP64 records when asked. */ +std::string zip_of(const std::vector& es, bool zip64 = false) { + std::string out, cd; + for (const ZipEntry& e : es) { + const uint64_t off = out.size(); + const uint64_t base = off + 30 + e.name.size() + 4; + const uint64_t pad = (64 - base % 64) % 64; + le(&out, 0x04034b50, 4); le(&out, 20, 2); le(&out, 0, 2); le(&out, e.method, 2); + le(&out, 0, 4); le(&out, 0, 4); + le(&out, e.data.size(), 4); le(&out, e.data.size(), 4); + le(&out, e.name.size(), 2); le(&out, 4 + pad, 2); + out += e.name; + le(&out, 0xcafe, 2); le(&out, pad, 2); out.append((size_t)pad, '\0'); + out += e.data; + std::string ex; + uint32_t loff32 = (uint32_t)off; + if (zip64) { + le(&ex, 1, 2); le(&ex, 8, 2); le(&ex, off, 8); + loff32 = 0xffffffffu; + } + le(&cd, 0x02014b50, 4); le(&cd, 45, 2); le(&cd, 45, 2); le(&cd, 0, 2); le(&cd, e.method, 2); + le(&cd, 0, 4); le(&cd, 0, 4); + le(&cd, e.data.size(), 4); le(&cd, e.data.size(), 4); + le(&cd, e.name.size(), 2); le(&cd, ex.size(), 2); le(&cd, 0, 2); + le(&cd, 0, 2); le(&cd, 0, 2); le(&cd, 0, 4); le(&cd, loff32, 4); + cd += e.name + ex; + } + const uint64_t cd_off = out.size(); + out += cd; + if (zip64) { + const uint64_t z = out.size(); + le(&out, 0x06064b50, 4); le(&out, 44, 8); le(&out, 45, 2); le(&out, 45, 2); + le(&out, 0, 4); le(&out, 0, 4); le(&out, es.size(), 8); le(&out, es.size(), 8); + le(&out, cd.size(), 8); le(&out, cd_off, 8); + le(&out, 0x07064b50, 4); le(&out, 0, 4); le(&out, z, 8); le(&out, 1, 4); + } + le(&out, 0x06054b50, 4); le(&out, 0, 2); le(&out, 0, 2); + le(&out, zip64 ? 0xffff : es.size(), 2); le(&out, zip64 ? 0xffff : es.size(), 2); + le(&out, zip64 ? 0xffffffffu : cd.size(), 4); le(&out, zip64 ? 0xffffffffu : cd_off, 4); + le(&out, 0, 2); + return out; +} + +std::string floats(std::initializer_list v) { + std::string s(v.size() * 4, '\0'); + std::memcpy(s.data(), v.begin(), s.size()); + return s; +} + +/* The archive of `pkl` with the storages "0" and "1": 6 and 4 floats. */ +std::string archive(const std::string& pkl, bool zip64 = false, uint16_t method = 0) { + return zip_of({ { "ck/data.pkl", pkl, method }, { "ck/byteorder", "little" }, + { "ck/data/0", floats({ 1, 2, 3, 4, 5, 6 }) }, + { "ck/data/1", floats({ 7, 8, 9, 10 }) } }, + zip64); +} + +std::vector two() { + return { Tensor{ "a.weight", "FloatStorage", "0", { 2, 3 }, { 3, 1 }, 0, 6 }, + Tensor{ "a.bias", "FloatStorage", "1", { 2 }, { 1 }, 2, 4, true } }; +} + +const TorchTensor* by_name(const TorchZipFile& f, const std::string& n) { + for (const TorchTensor& t : f.tensors()) + if (t.name == n) return &t; + return nullptr; +} + +float f32_at(const TorchTensor& t, int i) { + float v; + std::memcpy(&v, t.data + 4 * i, 4); + return v; +} + +} /* namespace */ + +/* The tensors as torch.save wrote them: names, dtype, shape, the bytes at the storage offset, a + * parameter's tensor, a nested dict's names dotted and an integer skipped; in a plain and a ZIP64 + * directory. */ +TEST(a_state_dict_reads_back_as_its_tensors) { + for (bool z64 : { false, true }) { + const std::string bytes = archive(state_dict(two(), { Tensor{ "x", "FloatStorage", "0", + { 3 }, { 1 }, 3, 6 } }), + z64); + TorchZipFile f; + std::string why; + REQUIRE_EQ(f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why), (int)RAD_OK); + CHECK_EQ(f.tensors().size(), (size_t)3); + const TorchTensor* w = by_name(f, "a.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->dtype, (uint32_t)RAD_F32); + CHECK(w->shape == std::vector({ 2, 3 })); + CHECK_EQ(w->bytes, (uint64_t)24); + CHECK_EQ(f32_at(*w, 5), 6.0f); + CHECK_EQ((uintptr_t)w->data % 64, (uintptr_t)bytes.data() % 64); /* mapped in place */ + const TorchTensor* bias = by_name(f, "a.bias"); + REQUIRE(bias != nullptr); + CHECK_EQ(f32_at(*bias, 0), 9.0f); /* storage 1 from element 2 */ + CHECK_EQ(f32_at(*bias, 1), 10.0f); + const TorchTensor* x = by_name(f, "generator.x"); + REQUIRE(x != nullptr); + CHECK_EQ(f32_at(*x, 0), 4.0f); + } +} + +/* What a malicious or foreign file holds is refused by name before anything is read past it: a + * global outside the allow-list (os.system, builtins.eval), a storage class that is not one, an + * opcode the subset does not use, a compressed entry, a pickle cut short, and a tensor that runs + * past its storage or is not contiguous in it. */ +TEST(anything_outside_the_weights_only_subset_is_refused_by_name) { + auto refused = [](const std::string& bytes, const char* want) { + TorchZipFile f; + std::string why; + const int st = f.open_bytes((const uint8_t*)bytes.data(), bytes.size(), &why); + CHECK(st < 0); + CHECK(has(why, want)); + if (!has(why, want)) std::fprintf(stderr, " want %s, why: %s\n", want, why.c_str()); + }; + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.global("os", "system"); + p.op('('); p.str("echo pwned"); p.op('t'); p.op('R'); p.op('.'); + refused(archive(p.b), "'os.system'"); + } + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.str("builtins"); p.str("eval"); p.op((char)0x93); + p.op('.'); + refused(archive(p.b), "'builtins.eval'"); + } + { + std::vector ts = two(); + ts[0].storage_cls = "DoubleStorage"; + refused(archive(state_dict(ts)), "torch.DoubleStorage"); + } + { + std::string pk = state_dict(two()); + pk.insert(pk.size() - 1, 1, 'i'); /* INST, an old way to build any object */ + refused(archive(pk), "opcode 0x69"); + } + refused(archive(state_dict(two()), false, 8), "compressed"); + { + const std::string pk = state_dict(two()); + refused(archive(pk.substr(0, pk.size() / 2)), "pickle"); + } + { + std::vector ts = two(); + ts[1].shape = { 3 }; /* three floats from element 2 of a 4-float storage */ + refused(archive(state_dict(ts)), "does not fit its storage"); + } + { + std::vector ts = two(); + ts[0].stride = { 1, 2 }; /* a transposed view */ + refused(archive(state_dict(ts)), "not contiguous"); + } + refused(zip_of({ { "data.pkl", state_dict(two()) } }), "no /data.pkl"); + refused(std::string("PK\x03\x04 is a local header, and this is not an archive"), + "end-of-central-directory"); +} + +/* A .pth beside the safetensors joins the checkpoint under its stem, so a plugin maps + * `codec.`; a torch copy of the model's own weights is passed over, and a file the reader + * refuses is left out with a warning rather than failing the checkpoint. */ +TEST(a_pth_beside_the_safetensors_joins_the_checkpoint_under_its_stem) { + std::string d = radtest::tmp_path("tz.XXXXXX"); + REQUIRE(mkdtemp(d.data()) != nullptr); + auto write = [&](const std::string& name, const std::string& bytes) { + FILE* f = std::fopen((d + "/" + name).c_str(), "wb"); + REQUIRE(f != nullptr); + std::fwrite(bytes.data(), 1, bytes.size(), f); + std::fclose(f); + }; + /* A one-tensor safetensors model and its config. */ + { + std::string hdr = "{\"w\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4]}}"; + while (hdr.size() % 8) hdr += ' '; + std::string st; + le(&st, hdr.size(), 8); + st += hdr + floats({ 1 }); + write("model.safetensors", st); + write("config.json", "{\"model_type\": \"tiny\"}"); + } + write("codec.pth", archive(state_dict(two()))); + write("pytorch_model.pth", archive(state_dict(two()))); + { + Pkl p; + p.op((char)0x80); p.b += (char)2; + p.global("os", "system"); + p.op('.'); + write("optimizer.pth", archive(p.b)); + } + Checkpoint ck; + REQUIRE_EQ(ck.open(d), (int)RAD_OK); + CHECK(ck.find("w") != nullptr); + const SrcTensor* w = ck.find("codec.a.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->rad_dtype, (uint32_t)RAD_F32); + CHECK(w->shape == std::vector({ 2, 3 })); + CHECK(ck.find("codec.a.bias") != nullptr); + CHECK(ck.find("pytorch_model.a.weight") == nullptr); + CHECK(ck.find("optimizer.a.weight") == nullptr); + std::filesystem::remove_all(d); +} + +/* A real torch.save checkpoint, when one is named: every tensor's bytes inside the file. */ +TEST(a_real_checkpoint_named_by_the_environment_reads) { + const char* p = std::getenv("RAD_TEST_TORCH_PTH"); + if (!p || !*p) SKIP("RAD_TEST_TORCH_PTH names no checkpoint"); + TorchZipFile f; + std::string why; + REQUIRE_EQ(f.open(p, &why), (int)RAD_OK); + CHECK(!f.tensors().empty()); + uint64_t bytes = 0; + for (const TorchTensor& t : f.tensors()) bytes += t.bytes; + std::fprintf(stderr, " %s: %zu tensors, %.1f MiB\n", p, f.tensors().size(), + (double)bytes / (1 << 20)); +} + +RAD_TEST_MAIN() From 832a88faac0b1eed81ce7709e15757e2736ed4c8 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 21:13:45 +0200 Subject: [PATCH 05/35] core: a speech model without instructions, and a refusal's reason from its text_prepare -- an audio generator may declare tmpl_plain alone (a request's instructions refused by name), and the reason a plugin leaves in the output buffer reaches the caller --- abi/rad_builder.h | 8 +++++--- core/build/rad_builder.cpp | 9 +++++++-- core/build/startup.cpp | 7 ++++++- core/build/startup.h | 2 +- core/engine.cpp | 5 +++-- core/server/audio_gen.cpp | 3 +++ tests/speech_test.cpp | 5 +++++ 7 files changed, 30 insertions(+), 9 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index e122636d..2480458f 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -902,7 +902,8 @@ typedef struct RadAudioGenDecl { /* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's * instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the * words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports - * one. Special tokens are spelled as text. */ + * one. Special tokens are spelled as text. NULL for a model that takes no instructions, which + * then declares `tmpl_plain` and has a request's instructions refused. */ const char* tmpl; /* The unconditional branch is the conditional prompt with every token but the first * `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches @@ -1430,8 +1431,9 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta); * * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included, * and returns the length the whole result needs without its NUL (call again with more room when - * it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so - * it keeps no state. */ + * it is >= cap), or a negative status for text the model cannot take, with the reason in `out` + * (NUL-terminated within `cap`) when it has one to give the caller. Called on HTTP threads, so it + * keeps no state. */ enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 }; int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 41915494..dc549198 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1361,7 +1361,12 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { : prog_.generator.layout != 0 ? "an image generator" : "a video generator"); return RAD_E_STATE; } - if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) { + if (!d->tmpl && !d->tmpl_plain) { + err(RAD_E_INVAL, "declare_audio_generator '%s': no prompt template (tmpl or tmpl_plain)", + nm); + return RAD_E_INVAL; + } + if (d->tmpl && (!std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}"))) { err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm); return RAD_E_INVAL; } @@ -1460,7 +1465,7 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { !buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out")) return RAD_E_INVAL; prog_.agen_str.name = nm; - prog_.agen_str.tmpl = d->tmpl; + prog_.agen_str.tmpl = d->tmpl ? d->tmpl : ""; prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : ""; prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : ""; prog_.audio_gen = *d; diff --git a/core/build/startup.cpp b/core/build/startup.cpp index fe5178ad..b08ee817 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -270,7 +270,12 @@ int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string std::string buf(in.size() * 2 + 64, '\0'); for (int tries = 0; tries < 2; ++tries) { const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size()); - if (n < 0) return (int)n; + if (n < 0) { + /* The plugin's reason, when it left one in the (zeroed) buffer. */ + buf.resize(std::strlen(buf.c_str())); + *out = std::move(buf); + return (int)n; + } if (n < (int64_t)buf.size()) { buf.resize((size_t)n); *out = std::move(buf); diff --git a/core/build/startup.h b/core/build/startup.h index d84b7ab7..78fe62d1 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -93,7 +93,7 @@ const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const * (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin * states no rewrite), or the plugin's negative status. */ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in, - std::string* out); + std::string* out); /* on a refusal, `out` is its reason or "" */ /* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports * none. */ diff --git a/core/engine.cpp b/core/engine.cpp index dd8db874..9c35f125 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2471,8 +2471,9 @@ int Engine::run_server() { std::string* why) const override { const int s = rad_tools_text_prepare(*plugins, field, in, out); if (s < 0 && why) - *why = s == RAD_E_INVAL ? "the model cannot take this text" - : std::string(rad_strerror(s)); + *why = !out->empty() ? *out + : s == RAD_E_INVAL ? "the model cannot take this text" + : std::string(rad_strerror(s)); return s; } int submit(std::unique_ptr r, std::string* why) override { diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index 78c8e93b..13eb7f05 100644 --- a/core/server/audio_gen.cpp +++ b/core/server/audio_gen.cpp @@ -110,6 +110,9 @@ int Server::speech_request(const json& body, const std::string& text, return fail(err_bad("instructions", "this model needs instructions, as a non-empty " "string: for a song its genre, mood, vocals and " "instruments")); + if (!inst.empty() && info.tmpl.empty()) + return fail(err_unsupported("instructions", "this model takes no instructions; its " + "direction is written in the input")); if (body.contains("speed") && !body["speed"].is_null() && !(body["speed"].is_number() && body["speed"].get() == 1.0)) return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions " diff --git a/tests/speech_test.cpp b/tests/speech_test.cpp index 6cb7536f..71109a6e 100644 --- a/tests/speech_test.cpp +++ b/tests/speech_test.cpp @@ -189,6 +189,11 @@ TEST(a_model_that_asks_has_its_input_read_with_special_tokens_and_one_branch_has CHECK_EQ(s.refused({ { "input", "hi" }, { "guidance_scale", 2.0 } }), std::string("guidance_scale")); CHECK_EQ(s.post({ { "input", "hi" }, { "guidance_scale", 1.0 } }).status, 200); + /* A model that declares no template with instructions refuses them by name. */ + s.gen.inf.tmpl.clear(); + CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", "calm" } }), + std::string("instructions")); + CHECK_EQ(s.post({ { "input", "hi" } }).status, 200); Speech m; m.gen.inf.tmpl_plain = "{input}"; m.gen.inf.default_steps = 0; From 346efdeb2e70e8c39d95d116fc14ee2f8a8d40c9 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 21:17:22 +0200 Subject: [PATCH 06/35] libref, libavx, libr4d: rvq_embed's clamp -- a code past a codebook smaller than the heads that wrote it reads the codebook's last row, as Fish Audio's codec reads its 1024-entry residual codebooks --- docs/OPS.md | 5 ++++- libavx/avx_audio.cpp | 9 +++++---- libavx/avx_cases.cpp | 3 +++ libavx/avx_registry.cpp | 2 +- libr4d/r4d_audio.hip | 14 ++++++++------ libr4d/r4d_rows.cpp | 2 +- libr4d/r4d_selftest.cpp | 19 ++++++++++++------- libref/ref_audio.cpp | 10 ++++++---- libref/ref_registry.cpp | 2 +- 9 files changed, 41 insertions(+), 25 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 1714484c..911623b2 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1172,7 +1172,7 @@ libref function says which (`libref/ref_audio.cpp`). | `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? | | `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` | | `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | -| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` | +| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` | | `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout | | `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout | | `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` | @@ -1216,6 +1216,9 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a `y = bf16(bf16(t0[c_0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale)`, or with `round` 1 one f32 sum of every codebook's row in codebook order, times `scale`, rounded once to `y`'s dtype. A first code outside `t0` leaves its row unwritten; a later code outside `t1` adds nothing. + With `clamp` n > 0 a code above `n - 1` reads row `n - 1` (before `off0` and the codebook's + offset; a negative code still reads nothing): a codec whose codebooks are smaller than the heads + that write its codes, as Fish Audio's 1024-entry residual codebooks under 4096-way heads. - `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`, when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes` diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index 7f2559f4..e5ae6799 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -713,17 +713,18 @@ AVX_KERNEL(rvq_embed) { const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0); const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0); const float scale = p_f32(a, "scale", 1.0f); - const int64_t round1 = p_int(a, "round", 0); - if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE; + const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE; const int64_t rows = rows_of(Y, D); if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE; const int64_t n0 = rows_of(t0, D), n1 = rows_of(t1, D); + auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; }; /* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */ const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows; const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; AVX_PARALLEL_FOR_IF(rows * D * K >= AVX_PAR_MIN) for (int64_t r = 0; r < rows; ++r) { - const int64_t c0 = ld_int_dt(codes->dtype, codes->data, r * rp) + off0; + const int64_t c0 = cl(ld_int_dt(codes->dtype, codes->data, r * rp)) + off0; if (c0 < 0 || c0 >= n0) continue; float* acc = scratch_f32((size_t)D + 16); float* buf = scratch_f32_b((size_t)D + 16); @@ -736,7 +737,7 @@ AVX_KERNEL(rvq_embed) { } for (int64_t k = 1; k < K; ++k) { const int64_t cb = - ld_int_dt(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc; + cl(ld_int_dt(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc; if (cb < 0 || cb >= n1) continue; const float* tr = in_row(t1, rowoff(t1, cb, D), D, buf); for (int64_t d = 0; d < D; ++d) acc[d] += tr[d]; diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 5be9c307..315f00eb 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -1015,6 +1015,9 @@ std::vector build_cases() { for (double sc : { 1.0, 0.7 }) add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64), HI("off0", 5), HF("scale", sc), HS("dtype", dt) }); + /* Codes past a codebook smaller than its heads read its last row (Fish Audio's codec). */ + add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 4), HI("vocab", 64), + HI("off0", 0), HF("scale", 1.0), HI("clamp", 40), HS("dtype", dt) }); /* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */ for (double sc : { 1.0, 0.7 }) add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64), diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index ba115f6f..cc0eb1e9 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -705,7 +705,7 @@ static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("fram OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), P_INT("vocab"), P_INT("off0"), P_F64("scale"), - P_STR("dtype"), P_INTO("round") }; + P_STR("dtype"), P_INTO("round"), P_INTO("clamp") }; static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 95f974ff..0d4ecdf5 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -788,15 +788,16 @@ __device__ __forceinline__ float ldtab(const void* t, int f32, size_t i) { __global__ __launch_bounds__(kT) void rvq_embed_kernel( const int* __restrict__ codes, int64_t kp, int64_t rp, const void* __restrict__ t0, int t0_f32, const void* __restrict__ t1, int t1_f32, void* __restrict__ y, int y_f32, int D, - int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1) { + int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1, int clamp) { const int r = blockIdx.x; - const int c0 = codes[(size_t)r * rp] + off0; + auto cl = [clamp](int c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; }; + const int c0 = cl(codes[(size_t)r * rp]) + off0; if (c0 < 0 || c0 >= r0) return; for (int d = threadIdx.x; d < D; d += kT) { const float e0 = ldtab(t0, t0_f32, (size_t)c0 * D + d); float acc = round1 ? e0 : 0.0f; for (int k = 1; k < K; ++k) { - const int ck = codes[(size_t)k * kp + (size_t)r * rp] + (k - 1) * voc; + const int ck = cl(codes[(size_t)k * kp + (size_t)r * rp]) + (k - 1) * voc; if (ck >= 0 && ck < r1) acc += ldtab(t1, t1_f32, (size_t)ck * D + d); } const float v = (round1 ? acc : bfr(e0 + bfr(acc))) * scale; @@ -1412,9 +1413,10 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) { return R4D_NO(RAD_E_DTYPE); const long long D = r4d_geti_or(a, "n_embd", 0), K = r4d_geti_or(a, "n_codes", 0); const long long voc = r4d_geti_or(a, "vocab", 0), off0 = r4d_geti_or(a, "off0", 0); - const long long round1 = r4d_geti_or(a, "round", 0); + const long long round1 = r4d_geti_or(a, "round", 0), clamp = r4d_geti_or(a, "clamp", 0); const double scale = r4d_getf(a, "scale", 1.0); - if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return R4D_NO(RAD_E_SHAPE); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) + return R4D_NO(RAD_E_SHAPE); long long ry = 0; const long long yl = r4d_rows_pitch(y, D, &ry); if (yl < 0 || !r4d_contig(t0) || !r4d_contig(t1)) return R4D_NO(RAD_E_STRIDE); @@ -1427,7 +1429,7 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) { t0->dtype == RAD_F32 ? 1 : 0, t1->data, t1->dtype == RAD_F32 ? 1 : 0, y->data, y->dtype == RAD_F32 ? 1 : 0, (int)D, (int)K, (int)voc, (int)off0, (int)(r4d_numel(t0) / D), (int)(r4d_numel(t1) / D), (float)scale, (int)yl, - (int)round1); + (int)round1, (int)clamp); return st_of(hipGetLastError()); } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 1bfaed4e..1ff67849 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2400,7 +2400,7 @@ static const RadOperandSpec oCfgTopk[] = { }; static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), P_INT("vocab"), P_INT("off0"), P_F64("scale"), - P_STR("dtype"), P_INTO("round") }; + P_STR("dtype"), P_INTO("round"), P_INTO("clamp") }; static const RadOperandSpec oRvqEmbed[] = { { "codes", RAD_OPD_IN, 0 }, { "t0", RAD_OPD_WEIGHT, 0 }, { "t1", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index a071e8ba..5371652b 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6009,9 +6009,12 @@ void rvq_embed_cases(const Plugin& pl) { const RadKernelInfo* r = find(pl, "rvq_embed_bf16"); if (!r) { ok("rvq_embed_bf16", false, "row absent"); return; } const int64_t D = 96, K = 5, voc = 11, off0 = 3, rows = 6, lanes = 2, stride = 9; - struct C { int round1; bool f32tab, f32y, block; }; + /* The last case clamps every code at 8 (`clamp`): codes 8..10 read row 7, and the later code + * past t1 reads its codebook's row 7 instead of nothing. */ + struct C { int round1; bool f32tab, f32y, block; int clamp = 0; }; for (const C& c : { C{ 0, false, false, false }, C{ 1, false, false, false }, - C{ 1, true, true, true }, C{ 1, false, true, true } }) { + C{ 1, true, true, true }, C{ 1, false, true, true }, + C{ 0, false, false, false, 8 } }) { std::vector t0 = randv((size_t)((voc + off0) * D), 1.0f); std::vector t1 = randv((size_t)((K - 1) * voc * D), 1.0f); void* d0 = c.f32tab ? up_f32(t0) : up_bf16(t0); @@ -6045,10 +6048,12 @@ void rvq_embed_cases(const Plugin& pl) { const float scale = 0.5f; std::vector ps = { PI("M", rows), PI("n_embd", D), PI("n_codes", K), PI("vocab", voc), PI("off0", off0), PF("scale", scale), - PS("dtype", c.f32y ? "f32" : "bf16"), PI("round", c.round1) }; - const std::string nm = fmt("rvq_embed_bf16 round %d %s tables -> %s%s", c.round1, + PS("dtype", c.f32y ? "f32" : "bf16"), PI("round", c.round1), + PI("clamp", c.clamp) }; + const std::string nm = fmt("rvq_embed_bf16 round %d %s tables -> %s%s clamp %d", c.round1, c.f32tab ? "f32" : "bf16", c.f32y ? "f32" : "bf16", - c.block ? ", codes a history block" : ""); + c.block ? ", codes a history block" : "", c.clamp); + auto cl = [&](int64_t v) { return c.clamp > 0 && v > c.clamp - 1 ? c.clamp - 1 : v; }; const int rc = launch(r, { tc, T(d0, c.f32tab ? RAD_F32 : RAD_BF16, { voc + off0, D }), T(d1, c.f32tab ? RAD_F32 : RAD_BF16, { (K - 1) * voc, D }), T(dy, ydt, { rows, D }) }, @@ -6056,13 +6061,13 @@ void rvq_embed_cases(const Plugin& pl) { if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } std::vector want = sentinel; for (int64_t i = 0; i < rows; ++i) { - const int64_t c0 = code[(size_t)i] + off0; + const int64_t c0 = cl(code[(size_t)i]) + off0; if (c0 < 0 || c0 >= voc + off0) continue; for (int64_t d = 0; d < D; ++d) { const float e0 = t0[(size_t)(c0 * D + d)]; float acc = c.round1 ? e0 : 0.0f; for (int64_t k = 1; k < K; ++k) { - const int64_t ck = code[(size_t)(k * rows + i)] + (k - 1) * voc; + const int64_t ck = cl(code[(size_t)(k * rows + i)]) + (k - 1) * voc; if (ck >= 0 && ck < (K - 1) * voc) acc += t1[(size_t)(ck * D + d)]; } const float s = c.round1 ? acc : bfr(e0 + bfr(acc)); diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index fc87808a..2144cc07 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -385,24 +385,26 @@ int ref_rvq_embed(const RadArgs* a, RadStream) { const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0); const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0); const float scale = p_f32(a, "scale", 1.0f); - const int64_t round1 = p_int(a, "round", 0); - if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE; + const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0); + if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE; const int64_t rows = rows_of(y, D); if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE; const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D); + /* `clamp`: a code above clamp - 1 reads row clamp - 1 (a negative one still reads nothing). */ + auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; }; /* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */ const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows; const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; REF_PAR_FOR(rows * D * K) for (int64_t r = 0; r < rows; ++r) { - const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0; + const int64_t c0 = cl(ld_int(codes->dtype, codes->data, r * rp)) + off0; if (c0 < 0 || c0 >= r0) continue; std::vector acc((size_t)D, 0.0f); const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D); if (round1) for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0)); for (int64_t k = 1; k < K; ++k) { - const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc; + const int64_t ck = cl(ld_int(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc; if (ck < 0 || ck >= r1) continue; const int64_t tb = rowoff(t1, ck, D); for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1)); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 60b0ef55..a4c99769 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -906,7 +906,7 @@ static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("fram OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") }; static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"), P_INT("vocab"), P_INT("off0"), P_F64("scale"), - P_STR("dtype"), P_INTO("round") }; + P_STR("dtype"), P_INTO("round"), P_INTO("clamp") }; static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; From f201c140ab68e2dc44d8437451f7f0a65fbea74c Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 21:24:19 +0200 Subject: [PATCH 07/35] core: a frame pass names the row before the frame's own -- its KV slot, position and context, for a frame head that attends at the row its hidden state comes from (Fish Audio drama-3's codebook tower) --- abi/rad_runtime.h | 9 +++++++++ core/gen/audio_driver.cpp | 12 ++++++++++++ core/gen/audio_driver.h | 3 ++- tests/abi_layout_rows.h | 3 +++ tests/abi_layout_table.h | 5 ++++- tests/audio_gen_test.cpp | 4 ++++ 6 files changed, 34 insertions(+), 2 deletions(-) diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 6fde1f91..b9c95569 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -466,6 +466,15 @@ typedef struct RadAudioGenBatch { /* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted * from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */ int64_t voc_frame0; + + /* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose + * hidden state the frame is sampled from -- as its KV slot, its position, and the context + * through it (position + 1). A model whose frame head attends at that row (Fish Audio + * drama-3's codebook tower, layers bound to the language model's full-attention group) issues + * those layers there, before the language model runs at the frame's own row. */ + const int32_t* prev_slot; + const int32_t* prev_pos; + const int32_t* prev_used; } RadAudioGenBatch; /* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp index 37e52044..c4567b7d 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -129,6 +129,9 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { z.S * I, /* R_ACC */ z.NG * z.S * I, /* R_SBT */ z.NG * z.S * AudioDriver::kMaxStateWidth * I, /* R_SIDX */ + z.S * I, /* R_PSLOT */ + z.S * I, /* R_PPOS */ + z.S * I, /* R_PUSED */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -499,6 +502,9 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 A.slot = dptr(ri, R_ESLOT); A.last_row = dptr(ri, R_LROW); A.prefix = dptr(ri, R_PREFIX); + A.prev_slot = dptr(ri, R_PSLOT); + A.prev_pos = dptr(ri, R_PPOS); + A.prev_used = dptr(ri, R_PUSED); B.agen_b = &A; } } @@ -716,6 +722,11 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) for (int64_t k = 0; k < pitch; ++k) btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; used[e] = (int32_t)(p + 1); + /* The row before, whose hidden state the frame is sampled from: the prompt's last + * row for the first frame. */ + hptr(R_PSLOT)[e] = slot_of(bt, p - 1, block_size_); + hptr(R_PPOS)[e] = (int32_t)(p - 1); + hptr(R_PUSED)[e] = (int32_t)p; hptr(R_ESLOT)[e] = nb_ * j.lane + b; hptr(R_LROW)[e] = (int32_t)e; max_ctx = std::max(max_ctx, (int32_t)(p + 1)); @@ -738,6 +749,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4; reg_[R_SEED].used = 2 * L * 4; reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4; + reg_[R_PSLOT].used = reg_[R_PPOS].used = reg_[R_PUSED].used = S * 4; if (upload() < 0) return nullptr; base_batches(S, S, 1, max_ctx, step, true, pitch); for (size_t r = 0; r < ranks_.size(); ++r) { diff --git a/core/gen/audio_driver.h b/core/gen/audio_driver.h index 318b89c7..55c1f9ed 100644 --- a/core/gen/audio_driver.h +++ b/core/gen/audio_driver.h @@ -124,7 +124,8 @@ private: struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED, R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC, - R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_N }; + R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_PSLOT, R_PPOS, R_PUSED, + R_N }; /* A hybrid model's stateful groups (linear-attention state, convolution history), each staged * as one block-table word a sequence (its slot) and its state_index row. */ struct StateGroup { int32_t g = 0; int64_t width = 1; }; diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 8187d639..f786dd91 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -137,6 +137,9 @@ ABI_FIELD(RadAudioGenBatch, voc_latents) ABI_FIELD(RadAudioGenBatch, voc_left) ABI_FIELD(RadAudioGenBatch, voc_right) ABI_FIELD(RadAudioGenBatch, voc_frame0) +ABI_FIELD(RadAudioGenBatch, prev_slot) +ABI_FIELD(RadAudioGenBatch, prev_pos) +ABI_FIELD(RadAudioGenBatch, prev_used) ABI_STRUCT(RadAudioGenDecl) ABI_FIELD(RadAudioGenDecl, name) ABI_FIELD(RadAudioGenDecl, tmpl) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index ed92fab5..a5f4a404 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -98,7 +98,7 @@ { "RadBuildCtx", "max_audio_frames", 88, 8 }, { "RadBuildCtx", "max_mixed_tok", 96, 8 }, { "RadBuildCtx", "kv_quant", 104, 4 }, -{ "RadAudioGenBatch", "", 0, 264 }, +{ "RadAudioGenBatch", "", 0, 288 }, { "RadAudioGenBatch", "n_lane", 0, 8 }, { "RadAudioGenBatch", "lane", 8, 8 }, { "RadAudioGenBatch", "lane_h", 16, 8 }, @@ -134,6 +134,9 @@ { "RadAudioGenBatch", "voc_left", 244, 4 }, { "RadAudioGenBatch", "voc_right", 248, 4 }, { "RadAudioGenBatch", "voc_frame0", 256, 8 }, +{ "RadAudioGenBatch", "prev_slot", 264, 8 }, +{ "RadAudioGenBatch", "prev_pos", 272, 8 }, +{ "RadAudioGenBatch", "prev_used", 280, 8 }, { "RadAudioGenDecl", "", 0, 232 }, { "RadAudioGenDecl", "name", 0, 8 }, { "RadAudioGenDecl", "tmpl", 8, 8 }, diff --git a/tests/audio_gen_test.cpp b/tests/audio_gen_test.cpp index c076fba8..7a4a86ef 100644 --- a/tests/audio_gen_test.cpp +++ b/tests/audio_gen_test.cpp @@ -267,6 +267,10 @@ TEST(a_hybrid_model_of_one_branch_stages_its_state_groups) { CHECK_EQ(b->n_tok, (int64_t)1); CHECK_EQ(b->positions[0], 4); /* after the four prompt rows */ CHECK_EQ(b->ctx_lens[0], 4); + /* The row the frame is sampled from: the prompt's last, at its slot. */ + CHECK_EQ(b->agen_b->prev_pos[0], 3); + CHECK_EQ(b->agen_b->prev_used[0], 4); + CHECK_EQ(b->agen_b->prev_slot[0], b->kv[0].slot_mapping[0] - 1); CHECK_EQ(b->num_accepted[0], 1); int32_t st1 = 0, cv1 = 0; state_rows(b, &st1, &cv1); From a01d1c1cd53b8f0ab6cad35cbf8a752680bd7ee4 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 22:42:58 +0200 Subject: [PATCH 08/35] fishomni: Fish Audio drama-3 -- the Qwen3.5-35B-A3B backbone with its block-fp8 experts at f32 scales, a 13-layer codebook tower over the backbone's full-attention cache, the main token over 4097 candidates with repetition-aware sampling, and Fish S2's modified DAC read from codec.pth; one branch on two cards, the input's speaker turns written as fish-speech's server writes them --- arch/fishomni/CMakeLists.txt | 10 + arch/fishomni/fishomni.cpp | 1818 ++++++++++++++++++++++++++++++++ data/recipes/drama3-fp8.recipe | 21 + tests/shipped_plugins_test.cpp | 67 +- 4 files changed, 1914 insertions(+), 2 deletions(-) create mode 100644 arch/fishomni/CMakeLists.txt create mode 100644 arch/fishomni/fishomni.cpp create mode 100644 data/recipes/drama3-fp8.recipe diff --git a/arch/fishomni/CMakeLists.txt b/arch/fishomni/CMakeLists.txt new file mode 100644 index 00000000..1894797a --- /dev/null +++ b/arch/fishomni/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(fishomni LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp) diff --git a/arch/fishomni/fishomni.cpp b/arch/fishomni/fishomni.cpp new file mode 100644 index 00000000..8217af63 --- /dev/null +++ b/arch/fishomni/fishomni.cpp @@ -0,0 +1,1818 @@ +/* fishomni -- Fish Audio drama-3 (FishOmniModel): speech from text, 44.1 kHz mono. + * + * ============================== THE MODEL ============================== + * + * Three networks (fish-speech's fish_speech/models/text2semantic/fish_omni/, Fish Audio's own + * reference, and its S2 codec): + * + * Backbone: the language model of Qwen3.5-35B-A3B, unchanged -- 40 layers of 2048, three gated + * delta-net layers to one gated attention layer (16 query heads over 2 KV heads of 256, NeoX + * rotary on 64 dims at theta 1e7), a routed feed-forward in every layer (256 experts of 512, 8 a + * token, and a gated shared expert of 512), (1 + w) norms. Only the routed experts are fp8 + * (`quant_method: bsgemm-moe`, E4M3 with an f32 scale a 128 x 128 block); everything else is + * bf16. A prompt row is a token; an audio row is one frame of the codec's ten codes, embedded as + * (E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2: the first code through its semantic token, + * the second through section 1 of the codebook table. + * + * Tower: 13 MTP-style layers that write a frame's codes 1..9 from the backbone's hidden state: + * four "shared" layers that inject code 0, then nine "per-codebook" layers, layer k injecting + * code k - 1 and its head drawing code k. Each layer is m = eh_proj([enorm(e); hnorm(h)]), one + * pre-norm block (gated attention with (1 + w) q/k norms and GPT-J rotary on 64 dims at 1e7, a + * SwiGLU of 6144), and a final norm. The attention is causal across time, over a cache of its + * own at the backbone's positions: the layers are bound as layers 40..52 of the backbone's + * full-attention KV group. The first shared layer also adds the summed embeddings of the input + * frame's codes 2..9, the ones the backbone never saw. + * + * Codec: Fish S2's modified DAC decoder: ten codebooks of dimension 8 (one of 4096, nine of + * 1024), each projected to 1024 and summed; an 8-layer transformer (16 heads of 64, a causal + * window of 128 frames); two 2x upsamplings with ConvNeXt blocks; four transposed convolutions + * (8, 8, 4, 2) with snake residual units; 2048 samples a frame. + * + * ============================== THE PASSES ============================== + * + * The core's audio generator in its chunked form, one branch a request (no guidance): + * + * PROMPT the backbone over the whole prompt; the last row's hidden state into the lane; the + * tower teacher-forced over every row. A prompt is text, so every row's label is text + * and every layer's code embedding is zero; the tower still runs, because its attention + * reads those rows' keys and values from every later frame. The last row's tower pass is + * the first frame's, and FRAME 0 overwrites it. + * FRAME frame j of every lane in flight. The main token is drawn from the hidden state of the + * row before the frame's (the prompt's last row for frame 0) over 4097 candidates (the + * end of speech and the 4096 semantic tokens), with Fish's repetition-aware choice + * between two draws; then the tower at that row's position draws codes 1..9; then the + * frame goes into the lane's history and the backbone runs over its embedding at the + * frame's own row. + * VOCODE a few kept frames of one lane through the codec, re-decoding the frames its outputs + * reach back to (every layer is causal), so no state is carried between chunks. + * + * ============================== TENSOR PARALLEL ============================== + * + * Two ranks. The backbone splits as Qwen3.6-35B-A3B does (heads, delta-net heads, expert width). + * The tower splits by heads and feed-forward width, an all-reduce after each output projection. + * The candidate head, the code tables, the nine heads, the samplers and the codec are + * replicated: every rank draws the same codes from the same logits and seeds, and plays the same + * samples. + */ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace fishomni { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +constexpr int64_t kMaxLanes = 4; +/* The longest prompt and speech. fish-speech's default request is 2048 frames (95 s); a plain + * prompt is a few dozen rows a sentence. */ +constexpr int64_t kMaxPrompt = 2048, kMaxFrames = 2048; +/* A frame: ten codes, code 0 of 4096 (the semantic band), codes 1..9 drawn from heads of 4096 and + * read by the codec through 1024-entry codebooks. */ +constexpr int64_t kCodes = 10, kVocab = 4096, kResVocab = 1024; +/* Token ids: the end of speech (<|im_end|>) and the semantic band <|semantic:0..4095|>. The main + * token is drawn over those 4097, in id order, so candidate 0 is the end and candidate c + 1 is + * semantic code c. */ +constexpr int64_t kEos = 248046, kSemBegin = 248099, kSemEnd = 252194, kCand = kVocab + 1; +/* The tower: four shared layers, then one a codebook after the first. */ +constexpr int kShared = 4, kTower = kShared + (int)kCodes - 1; +/* fish-speech's server and SDK defaults (sampling.py), the technical report's evaluation + * settings: temperature 0.7, top-p 0.7, top-k 30, for the main token and every head alike. */ +constexpr int64_t kTopK = 30; +static const double kTemp = 0.7, kTopP = 0.7; +/* The repetition-aware redraw, fixed by the training recipe (tower.py): when the first draw is + * semantic and among the last 16 main tokens, a second draw at temperature 1, top-p 0.95, + * top-k 30 is taken instead. */ +constexpr int64_t kRasWin = 16, kRasTopK = 30; +static const double kRasTemp = 1.0, kRasTopP = 0.95; + +/* The codec: 2048 samples a frame at 44.1 kHz. A chunk is at most kVocChunk frames; its outputs + * reach back about nine frames through the convolutions after the transformer (kConvCtx, rounded + * up), whose rows reach back kAttnWin - 1 frames. The dequantiser is per frame. */ +constexpr int64_t kSamplesPerFrame = 2048, kSampleRate = 44100; +constexpr int64_t kVocChunk = 16, kConvCtx = 12, kAttnWin = 128; +constexpr int64_t kVocContext = (kAttnWin - 1) + kConvCtx; +constexpr int64_t kConvFrames = kConvCtx + kVocChunk; +constexpr int64_t kCbDim = 8, kLat = 1024, kDec = 1536; +/* The codec transformer: 8 layers of 1024, 16 heads of 64, a SwiGLU of 3072. */ +constexpr int64_t kCtLayers = 8, kCtHeads = 16, kCtHeadDim = 64, kCtFf = 3072; +static const double kCtTheta = 10000.0, kCtEps = 1e-5; +/* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames, + * the two upsamplings', and each decoder block's output (8, 8, 4, 2 times). */ +constexpr int kRates = 8; +static const int64_t kRate[kRates] = { 1, 1, 2, 4, 32, 256, 1024, 2048 }; + +/* The prompt (reference-bracket-v1, the plain form: generate.py's build_drama3_prompt with no + * references). Every literal there is tokenised on its own; at these seams the joined text + * tokenises the same, since each one falls at a special token or a newline. The input gets its + * speaker tag in text_prepare. */ +static const char* kPlain = + "<|im_start|>system\nconvert the provided text to speech<|im_end|>\n" + "<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n<|voice|>"; + +/* Weight groups (movement units): the backbone's layers are 0..39 (the blocks' own), the tower's + * 40..52 like their KV layers, then the frame's tables and the codec. */ +enum : int { kGrpTower = 40, kGrpFrame = 53, kGrpCodec = 100 }; + +/* ================================================================== the networks */ +struct Layer { + int full = 0; + AttnGatedFP8 attn; + GdnFP8 gdn; + MoeFP8 mlp; +}; + +/* A tower layer (tower.py's TowerLayer): the code embedding and the two norms into eh_proj, the + * gated attention block over the paged cache, the SwiGLU, the final norm; a per-codebook layer's + * head and its draw. q, gate, k and v are four projections of the checkpoint's [Q | G | K | V] + * rows (paged attention reads a contiguous query, and the gate is not interleaved per head as the + * backbone's is). */ +struct TowerLayer { + rad_weight w_emb = 0, w_en = 0, w_hn = 0, w_eh = 0, w_an = 0; + rad_weight w_q = 0, w_g = 0, w_k = 0, w_v = 0, w_qn = 0, w_kn = 0, w_o = 0; + rad_weight w_fn = 0, w_gu = 0, w_down = 0, w_fin = 0, w_head = 0; + rad_op op_emb = 0, op_eadd = 0, op_en = 0, op_hn = 0, op_eh = 0, op_an = 0; + rad_op op_q = 0, op_g = 0, op_k = 0, op_v = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0; + rad_op op_attn = 0, op_kv = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_fn = 0, op_gu = 0, op_act = 0, op_down = 0, op_ar2 = 0, op_add2 = 0, op_fin = 0; + rad_op op_head = 0, op_samp = 0; +}; + +/* The codec transformer's layer: fused q|k|v with rotary at the frames' positions, causal + * attention over a 128-frame window, layer scales on both residual branches. */ +struct CodecLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qkv = 0, w_o = 0, w_gu = 0, w_down = 0, w_ls1 = 0, w_ls2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_o = 0, op_ls1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_ls2 = 0, op_add2 = 0; +}; + +/* A 2x upsampling and its ConvNeXt block. */ +struct Upsample { + rad_weight w_t = 0, b_t = 0, w_dw = 0, b_dw = 0, w_ln = 0, b_ln = 0, w_p1 = 0, b_p1 = 0; + rad_weight w_p2 = 0, b_p2 = 0, w_g = 0; + rad_op op_t = 0, op_dw = 0, op_ln = 0, op_p1 = 0, op_gelu = 0, op_p2 = 0, op_g = 0; + rad_op op_add = 0; +}; + +/* A causal weight-normalised conv with its bias. */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct VRes { + rad_weight a1 = 0, a2 = 0; + rad_op op_s1 = 0, op_s2 = 0; + VConv c1{}, c2{}; +}; +struct VBlock { + rad_weight a = 0, wt = 0, bt = 0; + rad_op op_s = 0, op_t = 0; + VRes res[3]; +}; + +struct Model { + Names nm{""}; + Geom g{}; /* the backbone's */ + Geom gt{}; /* the tower's */ + GdnFP8::Config gcfg{}; + MoeFP8::Config moecfg{}; + int64_t n_rot = 0, n_rot_t = 0, n_main = 0, lanes = 0; + rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0; + + /* ---- the backbone: the residual stream, its normed copy, and the blocks' working set */ + rad_buf b_x = 0; + ActFP8 a_h{}; + rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_rope_cs = 0; + ActFP8 a_attn{}; + ActFP8 a_in{}, a_go{}; + rad_buf b_ab = 0, b_gq = 0, b_gk = 0, b_gv = 0, b_gdec = 0, b_beta = 0, b_kkt = 0; + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0; + rad_buf b_egu = 0, b_edn = 0, b_emoe = 0; + ActFP8 a_eff{}; + rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0; + ActFP8 a_sff{}; + rad_weight w_tok = 0, w_out_norm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_rope_cs = 0; + std::vector layers; + + /* ---- a lane's state (PERSIST) */ + rad_buf b_hid = 0; /* [lanes, 2048] the last row's final-norm hidden state */ + rad_buf b_status = 0; /* [lanes] i32 */ + rad_buf b_hist = 0; /* [lanes * 10, kMaxFrames] i32: each lane's codes, codebook rows */ + rad_buf b_ras = 0; /* [lanes, 16] i32: the last 16 main picks (candidate indices) */ + rad_buf b_u = 0; /* [lanes, 2048] the last frame's codes 2..9, embedded and summed */ + + /* ---- the frame */ + rad_weight w_cand = 0; /* [4097, 2048] the lm_head's candidate rows */ + rad_weight w_cemb = 0; /* [4097, 2048] the embedding's candidate rows */ + rad_weight w_cb = 0; /* [9 * 4096, 2048] codebook table sections 1..9 */ + rad_buf b_plane = 0, b_slog = 0, b_first = 0, b_alt = 0, b_codes = 0, b_ug = 0, b_unew = 0; + rad_buf b_last = 0, b_hlog = 0; + rad_op op_hsel = 0, op_head = 0, op_samp = 0, op_samp_ras = 0, op_ras = 0, op_status = 0; + rad_op op_ugather = 0, op_plast = 0, op_pstore = 0, op_uzero = 0, op_rasinit = 0; + rad_op op_efill = 0, op_store = 0, op_u = 0, op_uscat = 0, op_fb = 0, op_fstore = 0; + + /* ---- the tower */ + TowerLayer tw[kTower]; + rad_buf b_te = 0, b_tcat = 0, b_tm = 0, b_th = 0, b_tq = 0, b_tg = 0, b_tk = 0, b_tv = 0; + rad_buf b_tattn = 0, b_to = 0, b_tgu = 0, b_tff = 0, b_tho = 0; + + /* ---- the codec (VOCODE) */ + rad_weight w_cbk[kCodes] = {}; + rad_op op_rq[kCodes] = {}; + VConv qo[kCodes]; + std::vector ct; + rad_weight w_cn = 0; + rad_op op_cn = 0, op_cnst = 0, op_ccu[kRates] = {}, op_fcast = 0; + Upsample up[2]; + VConv dec0{}; + VBlock vb[4]; + int64_t v_ups[4] = { 8, 8, 4, 2 }; + rad_weight w_fa = 0; + rad_op op_fs = 0; + VConv fin{}; + rad_buf b_rq = 0, b_cx = 0, b_ch = 0, b_cqkv = 0, b_cattn = 0, b_co = 0, b_cgu = 0, b_cff = 0; + rad_buf b_cconst = 0, b_ccu[kRates] = {}; + rad_buf b_ux[3] = {}, b_ua = 0, b_ub = 0, b_uh = 0, b_ug2 = 0; + rad_buf b_vs[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {}; + rad_buf b_vout = 0, b_audio = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== declare helpers */ +static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd, + rad_weight w, std::initializer_list x, rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", wadd), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + x, { y }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op gemm_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { x }, { y }); +} + +static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n, + std::initializer_list in, std::initializer_list out) { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + in, out); +} + +static rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); +} + +static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) { + return rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", mult)), + RAD_NOWEIGHTS), + { len }, { y }); +} + +static rad_op ar_op(RadBuilder* b, const Geom& g, rad_buf x) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* A frame draw: `k` largest, Fish's nucleus over the whole candidate set first (rad OPS.md, + * cfg_topk_sample's top_p), one row a lane, no guidance. */ +static rad_op draw_op(RadBuilder* b, int64_t lanes, int64_t n, int64_t k, double temp, + double top_p, int stream, rad_buf logits, rad_buf ids) { + return rw(b, RAD_OP(b, "cfg_topk_sample", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("n_vocab", n), + RAD_INT("k", k), RAD_INT("rep", 1), RAD_F64("cfg", 1.0), + RAD_F64("temp", temp), RAD_INT("stream", stream), + RAD_STR("dtype", "f32"), RAD_F64("top_p", top_p)), + RAD_NOWEIGHTS), + { logits }, { ids }); +} + +/* A plain weight copied from the checkpoint, declared at `dtype`, replicated. */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); +} + +/* ================================================================== check_format */ +/* The container's statement of what it is. Every mismatch below would still make sound -- a + * different template, another codebook layout, an fp8 format read as this one -- so each is a + * refusal by name rather than a silent default. */ +static int check_format(const RadModelMeta* meta) { + const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr); + const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr); + if (!method || std::strcmp(method, "bsgemm-moe") != 0) { + fprintf(stderr, "radiance: fishomni serves Fish Audio's released drama-3, whose routed " + "experts are block-scaled fp8 (quant_method 'bsgemm-moe'); this container " + "says '%s'\n", method ? method : "(none)"); + return RAD_E_UNSUPPORTED; + } + if (block) { + long long b0 = 0, b1 = 0; + if (std::sscanf(block, "%lld %lld", &b0, &b1) != 2) { b0 = 0; b1 = 0; } + if (b0 != RAD_FP8_BLOCK || b1 != RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: fishomni refuses weight_block_size [%lld, %lld]: libr4d's " + "block-scaled GEMMs are compiled at %d in both dimensions\n", + b0, b1, RAD_FP8_BLOCK); + return RAD_E_UNSUPPORTED; + } + } + const char* tv = rad_meta_gets(meta, "speech_template_version", ""); + if (std::strcmp(tv, "reference-bracket-v1") != 0) { + fprintf(stderr, "radiance: fishomni builds the reference-bracket-v1 prompt and this " + "checkpoint asks for '%s'\n", tv); + return RAD_E_UNSUPPORTED; + } + const char* ad = "audio_decoder_config"; + char k[96]; + auto ai = [&](const char* key, long long dflt) { + std::snprintf(k, sizeof k, "%s.%s", ad, key); + return rad_meta_geti(meta, k, dflt); + }; + auto as = [&](const char* key) { + std::snprintf(k, sizeof k, "%s.%s", ad, key); + return rad_meta_gets(meta, k, ""); + }; + if (rad_meta_geti(meta, "semantic_start_token_id", 0) != kSemBegin || + rad_meta_geti(meta, "semantic_end_token_id", 0) != kSemEnd || + rad_meta_geti(meta, "eos_token_id", 0) != kEos || + std::strcmp(as("decoder_type"), "codebook_mtp_shared") != 0 || + ai("num_codebooks", 0) != kCodes || ai("vocab_size", 0) != kVocab || + ai("vq_backbone_codebooks", 0) != 1 || ai("shared_enrichment_layers", 0) != kShared || + std::strcmp(as("vq_feature_placement"), "backbone_partial") != 0 || + std::strcmp(as("vq_feature_scope"), "all_vq") != 0) { + fprintf(stderr, "radiance: fishomni: not the released drama-3 layout (semantic tokens " + "%lld..%lld, end %lld, a codebook_mtp_shared tower of %d shared layers " + "over %lld codebooks of %lld, one codebook into the backbone)\n", + (long long)kSemBegin, (long long)kSemEnd, (long long)kEos, kShared, + (long long)kCodes, (long long)kVocab); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== the backbone */ +/* qwen35moe_fp8's trunk, written out (arch/qwen35_fp8/qwen35_fp8.cpp, QWEN35_MOE): the same + * blocks, metadata and names, without its drafters, vision tower and int8 build. Its bf16 linears + * (attention, delta net, shared expert) are served by LinearFP8's plain branch beside the fp8 + * experts. */ +static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m) { + Geom& g = m.g; + Names& nm = m.nm; + if (meta->n_expert <= 0) { + fprintf(stderr, "radiance: fishomni: the backbone declares no experts; drama-3's is " + "routed\n"); + return RAD_E_UNSUPPORTED; + } + bool have_interval = false; + const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval", + "full_attention_interval", 4, &have_interval); + if (interval <= 0) return RAD_E_INVAL; + RAD_ARCH_TRY(check_layer_schedule("fishomni", meta_text_gets(meta, "layer_types", nullptr), + g.n_layer, interval, {"full_attention"})); + m.n_main = g.n_layer; + + /* GemmaRMSNorm everywhere but the delta net's output norm (rad_block_gdn_fp8.h). */ + g.wadd = 1.0f; + g.wadd_qk = 1.0f; + + double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0); + if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0); + m.n_rot = prf > 0.0 ? (int64_t)(g.head_dim * prf) : 0; + if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot & 1)) { + fprintf(stderr, "radiance: fishomni: no usable rotary width (head_dim %lld)\n", + (long long)g.head_dim); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot)); + + GdnFP8::Config& gc = m.gcfg; + const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count", + "linear_num_key_heads", 0); + const int64_t n_head_v_all = meta_int2(meta, "qwen35.ssm.time_step_rank", + "linear_num_value_heads", 0); + gc.head_k = meta_int2(meta, "qwen35.ssm.state_size", "linear_key_head_dim", 0); + gc.head_v = meta_int2(meta, "qwen35.ssm.value_head_dim", "linear_value_head_dim", 0); + gc.conv_width = meta_int2(meta, "qwen35.ssm.conv_kernel", "linear_conv_kernel_dim", 0); + if (n_head_k_all <= 0 || n_head_v_all <= 0 || gc.head_k <= 0 || gc.head_v <= 0 || + gc.conv_width <= 0) { + fprintf(stderr, "radiance: fishomni: the container does not describe the delta-net " + "layers\n"); + return RAD_E_INVAL; + } + gc.chunk = 64; + RAD_ARCH_TRY(divide_or_fail(n_head_k_all, g.world, "linear_num_key_heads", &gc.n_head_k)); + RAD_ARCH_TRY(divide_or_fail(n_head_v_all, g.world, "linear_num_value_heads", &gc.n_head_v)); + + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int64_t v_dim = gc.v_dim(), conv_dim = gc.conv_dim(); + + /* ---- the KV groups. The full-attention group also holds the tower's 13 layers, bound below + * at 40..52 (declare_tower). */ + RadKVGroupDecl fd{}; + fd.kind = RAD_KV_FULL; + fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.n_head_kv = g.n_head_kv; + fd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + g.kv_dtype = rad_dtype_name(fd.dtype); + + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = gc.n_head_v; + sd.state_dim[0] = gc.head_v; + sd.state_dim[1] = gc.head_k; + m.kv_state = rad_decl_kv_group(b, nm.f("kv_gdn_state"), &sd); + + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 2 * gc.n_head_k + gc.n_head_v; + cd.head_dim = gc.head_k; + cd.conv_width = gc.conv_width; + m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd); + if (!m.kv_full || !m.kv_state || !m.kv_conv) return RAD_E_INVAL; + + /* ---- activations (qwen35_fp8.cpp says what each is) */ + m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); + m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd)); + m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim}); + m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim}); + m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot}, + RAD_BUF_PERSIST); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim)); + m.a_in.x = decl_b(b, nm.f("gdn_in"), g.act_dtype, {g.max_tok, conv_dim + v_dim}); + RAD_ARCH_TRY(m.a_in.declare_qs(b, nm, g, "gdn_in", conv_dim + v_dim)); + m.b_ab = decl_b(b, nm.f("gdn_ab"), g.act_dtype, {g.max_tok, gc.ab_dim()}); + m.b_gq = decl_b(b, nm.f("gdn_q"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k}); + m.b_gk = decl_b(b, nm.f("gdn_k"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k}); + m.b_gv = decl_b(b, nm.f("gdn_v"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); + m.b_gdec = decl_b(b, nm.f("gdn_g"), RAD_F32, {g.max_tok, gc.n_head_v}); + m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {g.max_tok, gc.n_head_v}); + m.b_kkt = decl_b(b, nm.f("gdn_kkt"), RAD_BF16, {g.max_tok, gc.n_head_v, gc.chunk}); + m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); + RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim)); + + /* ---- the routing geometry; `n_ff` is already the per-rank expert width */ + { + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = meta->n_expert; + mc.top_k = meta->n_expert_used > 0 ? meta->n_expert_used + : meta_int2(meta, "qwen35.expert_used_count", + "num_experts_per_tok", 0); + mc.n_ff_exp = g.n_ff; + mc.norm_topk = (int)meta_int2(meta, "qwen35.expert_weights_norm", "norm_topk_prob", 1); + const int64_t sh_all = meta_int2(meta, "qwen35.expert_shared_feed_forward_length", + "shared_expert_intermediate_size", 0); + if (sh_all > 0) + RAD_ARCH_TRY(divide_or_fail(sh_all, g.world, "shared_expert_intermediate_size", + &mc.n_ff_shared)); + const int64_t moe_rows = 2048; + mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; + if (mc.top_k <= 0 || mc.top_k > mc.n_expert) { + fprintf(stderr, "radiance: fishomni: top_k %lld is not in [1, %lld]\n", + (long long)mc.top_k, (long long)mc.n_expert); + return RAD_E_INVAL; + } + const int64_t R = g.max_tok, K = mc.rows * mc.top_k; + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k}); + m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k}); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K}); + m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert + 1}); + m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST); + m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp}); + m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp}); + m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)}); + m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd}); + if (mc.n_ff_shared > 0) { + m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared}); + m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared}); + m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared}); + m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)}); + m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1}); + } + } + + /* ---- the vocabulary edge. The embedding is row-sharded with the vocabulary and summed by the + * all-reduce below; there is no lm_head here, only its 4097 candidate rows (declare_frame). */ + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), + nm.ckpt("model.language_model.norm.weight"))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + /* Always issued by PROMPT, never folded into layer 0's norm: a frame's embedding is the same + * on every rank (replicated tables), and a reduction there would sum it world times. Exact: + * it sums disjoint rows. */ + if (g.world > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table", + RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, {m.b_rope_cs}); + + AttnGatedFP8::Wire aw{}; + aw.x = m.b_x; aw.h = m.a_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v; + aw.q = m.b_q; aw.attn = m.a_attn; + aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0; + + GdnFP8::Wire gw{}; + gw.x = m.b_x; gw.h = m.a_h; gw.in = m.a_in; gw.ab = m.b_ab; + gw.q = m.b_gq; gw.k = m.b_gk; gw.v = m.b_gv; + gw.gdec = m.b_gdec; gw.beta = m.b_beta; gw.kkt = m.b_kkt; gw.o = m.a_go; + + MoeFP8::Wire mw{}; + mw.x = m.b_x; mw.h = m.a_h; + mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew; + mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt; + mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe; + mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate; + + m.layers.resize((size_t)m.n_main); + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = is_full_attention(l, interval) ? 1 : 0; + /* embed_ar false: layer 0's norm takes no reduction (see op_embed_ar). */ + const LayerFold f = layer_fold(g, l, m.n_main, nullptr, 0, false); + const char* pre = "model.language_model.layers"; + if (lay.full) { + AttnGatedFP8::Src as{}; + as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l); + as.qg = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l); + as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l); + as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l); + as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l); + as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l); + as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as, + f.mix_fold, false, f.mix_ar_in, f.mix_ar_out)); + } else { + GdnFP8::Src gs{}; + gs.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l); + gs.in_qkv = nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l); + gs.in_a = nm.ckpt("%s.%lld.linear_attn.in_proj_a.weight", pre, (long long)l); + gs.in_b = nm.ckpt("%s.%lld.linear_attn.in_proj_b.weight", pre, (long long)l); + gs.in_z = nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l); + gs.conv1d = nm.ckpt("%s.%lld.linear_attn.conv1d.weight", pre, (long long)l); + gs.a_log = nm.ckpt("%s.%lld.linear_attn.A_log", pre, (long long)l); + gs.dt_bias = nm.ckpt("%s.%lld.linear_attn.dt_bias", pre, (long long)l); + gs.out_norm = nm.ckpt("%s.%lld.linear_attn.norm.weight", pre, (long long)l); + gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv)); + RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs, + f.mix_fold, false, f.mix_ar_in, f.mix_ar_out)); + } + MoeFP8::Src ms{}; + ms.cfg = m.moecfg; + ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l); + ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l); + ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l); + if (m.moecfg.n_ff_shared > 0) { + ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l); + ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l); + } + /* The experts' stored format, read from the layer's first: the release's scale planes are + * f32 (fp8a8f32), not the bf16 Qwen3.6's are. */ + RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg)); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add, + f.mlp_ar_in, f.mlp_ar_out)); + } + for (int64_t l = 0; l + 1 < m.n_main; ++l) + m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp; + + m.op_final_norm = norm_op(b, g.max_tok, g.n_embd, g.eps, 1.0, m.w_out_norm, {m.b_x}, + m.a_h.x); + if (!have_interval) + rad_note(b, "the container did not state full_attention_interval; assuming %lld, which " + "makes layers 3,7,... full attention", (long long)interval); + return m.op_embed && m.op_final_norm ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the frame's head */ +/* The lane state, the candidate head and the main token's two draws (FRAME, before the tower), + * and what PROMPT leaves in the lane. Declared in the order a frame issues them: buffer liveness + * follows declaration order. */ +static int declare_frame_head(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t S = m.lanes, D = m.g.n_embd, T = m.g.max_tok; + m.b_hid = decl_b(b, nm.f("frame.hid"), RAD_BF16, { S, D }, RAD_BUF_PERSIST); + m.b_status = decl_b(b, nm.f("frame.status"), RAD_I32, { S }, RAD_BUF_PERSIST); + m.b_hist = decl_b(b, nm.f("frame.history"), RAD_I32, { S * kCodes, kMaxFrames }, + RAD_BUF_PERSIST); + m.b_ras = decl_b(b, nm.f("frame.ras"), RAD_I32, { S, kRasWin }, RAD_BUF_PERSIST); + m.b_u = decl_b(b, nm.f("frame.unseen"), RAD_BF16, { S, D }, RAD_BUF_PERSIST); + m.b_plane = decl_b(b, nm.f("frame.plane"), RAD_BF16, { S, D }); + m.b_slog = decl_b(b, nm.f("frame.slog"), RAD_F32, { S, kCand }); + m.b_first = decl_b(b, nm.f("frame.first"), RAD_I32, { S }); + m.b_alt = decl_b(b, nm.f("frame.alt"), RAD_I32, { S }); + m.b_codes = decl_b(b, nm.f("frame.codes"), RAD_I32, { kCodes, S }); + m.b_ug = decl_b(b, nm.f("frame.ug"), RAD_BF16, { S, D }); + m.b_last = decl_b(b, nm.f("frame.last"), RAD_BF16, { S, D }); + + /* The main token's candidates: the lm_head's rows for the end of speech and the semantic band, + * in id order, replicated (the full head is vocab-sharded and 1 GB). The same rows of the + * embedding feed a frame back to the backbone, indexed by the same candidate. */ + const char* lm = nm.ckpt("lm_head.weight"); + const char* et = nm.ckpt("model.language_model.embed_tokens.weight"); + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cand.weight"), + { { lm, (int)kEos, 1 }, { lm, (int)kSemBegin, kVocab } })); + m.w_cand = decl_w(b, nm.f("frame.cand.weight"), RAD_BF16, { kCand, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpFrame)); + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cemb.weight"), + { { et, (int)kEos, 1 }, { et, (int)kSemBegin, kVocab } })); + m.w_cemb = decl_w(b, nm.f("frame.cemb.weight"), RAD_BF16, { kCand, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpFrame)); + /* The codebook table's sections 1..9; section 0 is never read (tower.py, embedding_sum). */ + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cb.weight"), + { { nm.ckpt("audio_decoder.codebook_embeddings.weight"), (int)kVocab, + (kCodes - 1) * kVocab } })); + m.w_cb = decl_w(b, nm.f("frame.cb.weight"), RAD_BF16, { (kCodes - 1) * kVocab, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpFrame)); + if (!m.w_cand || !m.w_cemb || !m.w_cb) return RAD_E_INVAL; + + /* ---- FRAME: the hidden states, the candidates' logits, the two draws and the choice */ + m.op_hsel = rows_op(b, "gather_rows", S, D, { m.b_hid }, { m.b_plane }); + m.op_head = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kCand), + RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cand)), + { m.b_plane }, { m.b_slog }); + m.op_samp = draw_op(b, S, kCand, kTopK, kTemp, kTopP, 0, m.b_slog, m.b_first); + m.op_samp_ras = draw_op(b, S, kCand, kRasTopK, kRasTemp, kRasTopP, 1, m.b_slog, m.b_alt); + /* The redraw: only a semantic first draw (candidates 1..4096), and only one the lane's last + * 16 picks hold; the prompt's rows are text, so its window starts empty (op_rasinit). */ + m.op_ras = rw(b, RAD_OP(b, "ras_pick", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("win", kRasWin), + RAD_INT("lo", 1), RAD_INT("hi", kCand), RAD_INT("rep", 1)), + RAD_NOWEIGHTS), + { m.b_first, m.b_alt, m.b_ras }, { m.b_codes, m.b_ras }); + m.op_status = rw(b, RAD_OP(b, "end_status", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("end", 0), + RAD_INT("rep", 1)), + RAD_NOWEIGHTS), + { m.b_codes }, { m.b_status }); + m.op_ugather = rows_op(b, "gather_rows", S, D, { m.b_u }, { m.b_ug }); + + /* ---- PROMPT: the last row's hidden state into the lane, an empty window and no unseen codes + * (the prompt's last row is text), and the tower's code embeddings, all zero for text labels */ + m.op_plast = rows_op(b, "gather_rows", S, D, { m.a_h.x }, { m.b_last }); + m.op_pstore = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_last }, { m.b_hid }); + m.op_uzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_u }); + m.op_rasinit = iota_op(b, kRasWin, -1, 0, m.b_ras); + m.b_tcat = decl_b(b, nm.f("tower.cat"), RAD_BF16, { T, 2 * D }); + m.op_efill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tcat }); + return m.op_hsel && m.op_head && m.op_samp && m.op_samp_ras && m.op_ras && m.op_status && + m.op_ugather && m.op_plast && m.op_pstore && m.op_uzero && m.op_rasinit && + m.op_efill + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the tower */ +static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + Geom& g = m.gt; + g = m.g; + const char* ad = "audio_decoder_config"; + char key[96]; + auto ai = [&](const char* k, long long d) { + std::snprintf(key, sizeof key, "%s.%s", ad, k); + return (int64_t)rad_meta_geti(meta, key, d); + }; + auto af = [&](const char* k, double d) { + std::snprintf(key, sizeof key, "%s.%s", ad, k); + return rad_meta_getf(meta, key, d); + }; + g.n_head_all = ai("n_head", 0); + g.n_head_kv_all = ai("n_local_heads", 0); + g.head_dim = ai("head_dim", 0); + g.n_ff_all = ai("intermediate_size", 0); + const double rot_frac = af("rotary_percent", 0.0); + g.eps = (float)af("norm_eps", 1e-6); + g.theta = (float)af("rope_base", 0.0); + if (ai("dim", 0) != g.n_embd || g.n_head_all <= 0 || g.n_head_kv_all <= 0 || + g.head_dim <= 0 || g.n_ff_all <= 0 || !(g.theta > 0.0f) || !(rot_frac > 0.0)) { + fprintf(stderr, "radiance: fishomni: the audio decoder config does not describe the " + "tower (dim %lld, %lld heads over %lld of %lld, ffn %lld)\n", + (long long)ai("dim", 0), (long long)g.n_head_all, (long long)g.n_head_kv_all, + (long long)g.head_dim, (long long)g.n_ff_all); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(divide_or_fail(g.n_head_all, g.world, "the tower's heads", &g.n_head)); + RAD_ARCH_TRY(divide_or_fail(g.n_head_kv_all, g.world, "the tower's KV heads", &g.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(g.n_ff_all, g.world, "the tower's feed-forward", &g.n_ff)); + g.rope_scale = 1.0f; + g.yarn = RadYarn{}; + g.rope_mc = false; + m.n_rot_t = (int64_t)(g.head_dim * rot_frac); + /* One KV group for the backbone's ten attention layers and these: the cache rows must match. */ + if (g.n_head_kv != m.g.n_head_kv || g.head_dim != m.g.head_dim) { + fprintf(stderr, "radiance: fishomni: the tower's KV heads (%lld of %lld) differ from the " + "backbone's (%lld of %lld), and they share one cache group\n", + (long long)g.n_head_kv, (long long)g.head_dim, (long long)m.g.n_head_kv, + (long long)m.g.head_dim); + return RAD_E_UNSUPPORTED; + } + + const int64_t T = g.max_tok, S = m.lanes, D = g.n_embd, hd = g.head_dim; + const int64_t qd = g.n_head * hd, kd = g.n_head_kv * hd, ff = g.n_ff; + const int64_t qd_all = g.n_head_all * hd, kd_all = g.n_head_kv_all * hd; + m.b_te = decl_b(b, nm.f("tower.e"), RAD_BF16, { S, D }); + m.b_tm = decl_b(b, nm.f("tower.m"), RAD_BF16, { T, D }); + m.b_th = decl_b(b, nm.f("tower.h"), RAD_BF16, { T, D }); + m.b_tq = decl_b(b, nm.f("tower.q"), RAD_BF16, { T, qd }); + m.b_tg = decl_b(b, nm.f("tower.g"), RAD_BF16, { T, qd }); + m.b_tk = decl_b(b, nm.f("tower.k"), RAD_BF16, { T, kd }); + m.b_tv = decl_b(b, nm.f("tower.v"), RAD_BF16, { T, kd }); + m.b_tattn = decl_b(b, nm.f("tower.attn"), RAD_BF16, { T, qd }); + m.b_to = decl_b(b, nm.f("tower.o"), RAD_BF16, { T, D }); + m.b_tgu = decl_b(b, nm.f("tower.gu"), RAD_BF16, { T, 2 * ff }); + m.b_tff = decl_b(b, nm.f("tower.ff"), RAD_BF16, { T, ff }); + m.b_tho = decl_b(b, nm.f("tower.out"), RAD_BF16, { T, D }); + m.b_hlog = decl_b(b, nm.f("tower.hlog"), RAD_F32, { S, kVocab }); + + for (int i = 0; i < kTower; ++i) { + TowerLayer& L = m.tw[i]; + const bool shared = i < kShared; + const int k = i - kShared; /* the per-codebook index, -1.. for shared */ + const int grp = kGrpTower + i, kvl = (int)m.n_main + i; + const char* pre = shared ? nm.ckpt("audio_decoder_mtp_shared.layers.%d", i) + : nm.ckpt("audio_decoder_mtp.layers.%d", k); + auto src = [&](const char* s) { return nm.ckpt("%s.%s", pre, s); }; + auto dn = [&](const char* s) { return nm.f("tower.%d.%s", i, s); }; + auto gain = [&](const char* d, const char* s, int64_t n) { + return wcopy(b, dn(d), src(s), RAD_F32, { n }, grp); + }; + + /* The code embedding. A layer that injects code 0 reads it by candidate (row 0 the end of + * speech, row c + 1 code c), so its table is the checkpoint's with row 0 again in front: + * fish-speech clamps the end's c0 to 0. The others read the code a head drew. */ + const char* tsrc = src(shared ? "semantic_embedding.weight" : "codebook_embedding.weight"); + const bool by_cand = shared || k == 0; + if (by_cand) RAD_ARCH_TRY(map_rows(b, dn("emb.weight"), { { tsrc, 0, 1 }, + { tsrc, 0, kVocab } })); + else RAD_ARCH_TRY(map_copy(b, dn("emb.weight"), tsrc)); + L.w_emb = decl_w(b, dn("emb.weight"), RAD_BF16, { by_cand ? kCand : kVocab, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(grp)); + L.w_en = gain("enorm.weight", "enorm.weight", D); + L.w_hn = gain("hnorm.weight", "hnorm.weight", D); + L.w_an = gain("attn_norm.weight", "transformer_layer.attention_norm.weight", D); + L.w_fn = gain("ffn_norm.weight", "transformer_layer.ffn_norm.weight", D); + L.w_fin = gain("final_norm.weight", "final_layernorm.weight", D); + L.w_qn = gain("q_norm.weight", "transformer_layer.attention.q_norm.weight", hd); + L.w_kn = gain("k_norm.weight", "transformer_layer.attention.k_norm.weight", hd); + L.w_eh = wcopy(b, dn("eh.weight"), src("eh_proj.weight"), RAD_BF16, { D, 2 * D }, grp); + + /* wqkv rows [Q | G | K | V], each a projection of its own, split by heads. */ + const char* wqkv = src("transformer_layer.attention.wqkv.weight"); + auto proj = [&](const char* d, int64_t first, int64_t rows, int64_t local) -> rad_weight { + if (map_rows(b, dn(d), { { wqkv, (int)first, rows } }) < 0) return 0; + return decl_w(b, dn(d), RAD_BF16, { local, D }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(grp)); + }; + L.w_q = proj("q.weight", 0, qd_all, qd); + L.w_g = proj("g.weight", qd_all, qd_all, qd); + L.w_k = proj("k.weight", 2 * qd_all, kd_all, kd); + L.w_v = proj("v.weight", 2 * qd_all + kd_all, kd_all, kd); + RAD_ARCH_TRY(map_copy(b, dn("o.weight"), src("transformer_layer.attention.wo.weight"))); + L.w_o = decl_w(b, dn("o.weight"), RAD_BF16, { D, qd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_COL, grp_layer(grp)); + RAD_ARCH_TRY(map_concat(b, dn("gate_up.weight"), + { src("transformer_layer.feed_forward.w1.weight"), + src("transformer_layer.feed_forward.w3.weight") })); + L.w_gu = decl_w(b, dn("gate_up.weight"), RAD_BF16, { 2 * ff, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_ROW, grp_layer(grp), 0, { ff, ff }); + RAD_ARCH_TRY(map_copy(b, dn("down.weight"), src("transformer_layer.feed_forward.w2.weight"))); + L.w_down = decl_w(b, dn("down.weight"), RAD_BF16, { D, ff }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_COL, grp_layer(grp)); + if (!L.w_emb || !L.w_en || !L.w_hn || !L.w_an || !L.w_fn || !L.w_fin || !L.w_qn || + !L.w_kn || !L.w_eh || !L.w_q || !L.w_g || !L.w_k || !L.w_v || !L.w_o || !L.w_gu || + !L.w_down) + return RAD_E_INVAL; + + /* ---- the ops, in the order a pass issues them. The embedding and its norm run in FRAME + * only; PROMPT's labels are text, whose embedding is zero, and so is its norm (op_efill + * zeroes that half of the concatenation once a prompt). */ + L.op_emb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", 1), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_emb, L.w_emb)), + { m.b_codes }, { m.b_te }); + if (i == 0) L.op_eadd = add_op(b, S, D, m.b_te, m.b_ug, m.b_te); + L.op_en = norm_op(b, S, D, g.eps, 1.0, L.w_en, { m.b_te }, m.b_tcat); + /* Layer 0's hidden state is the backbone's: the prompt's rows (PROMPT) or the frame's + * plane (FRAME); both stay live to here. */ + L.op_hn = i == 0 ? norm_op(b, T, D, g.eps, 1.0, L.w_hn, { m.a_h.x, m.b_plane }, m.b_tcat) + : norm_op(b, T, D, g.eps, 1.0, L.w_hn, { m.b_tho }, m.b_tcat); + L.op_eh = gemm_op(b, T, D, 2 * D, L.w_eh, m.b_tcat, m.b_tm); + L.op_an = norm_op(b, T, D, g.eps, 1.0, L.w_an, { m.b_tm }, m.b_th); + L.op_q = gemm_op(b, T, qd, D, L.w_q, m.b_th, m.b_tq); + L.op_g = gemm_op(b, T, qd, D, L.w_g, m.b_th, m.b_tg); + L.op_k = gemm_op(b, T, kd, D, L.w_k, m.b_th, m.b_tk); + L.op_v = gemm_op(b, T, kd, D, L.w_v, m.b_th, m.b_tv); + /* (1 + w) per head, always: the exporter never wrote attention_qk_norm (tower.py). */ + L.op_qn = norm_op(b, T * g.n_head, hd, g.eps, 1.0, L.w_qn, { m.b_tq }, m.b_tq); + L.op_kn = norm_op(b, T * g.n_head_kv, hd, g.eps, 1.0, L.w_kn, { m.b_tk }, m.b_tk); + /* Adjacent pairs (GPT-J), unlike the backbone's halves, over the first 64 dims. */ + L.op_rq = rw(b, decl_rope(b, g, T, hd, g.n_head, 0, m.n_rot_t, "gptj"), { m.b_tq }, + { m.b_tq }); + L.op_rk = rw(b, decl_rope(b, g, T, hd, g.n_head_kv, 0, m.n_rot_t, "gptj"), { m.b_tk }, + { m.b_tk }); + RAD_ARCH_TRY(rad_bind_layer_kv(b, kvl, m.kv_full)); + /* Declared before kv_store, which reads back the resolved block size. */ + L.op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", 0), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), + RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), + RAD_STR("kv_dtype", m.g.kv_dtype)), + RAD_NOWEIGHTS), + { m.b_tq }, { m.b_tattn }); + L.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, m.kv_full)), + RAD_STR("kv_dtype", m.g.kv_dtype)), + RAD_NOWEIGHTS), + { m.b_tk, m.b_tv }, {}); + L.op_sig = rows_op(b, "sigmoid", T, qd, { m.b_tg }, { m.b_tg }); + L.op_mul = rows_op(b, "mul", T, qd, { m.b_tattn, m.b_tg }, { m.b_tattn }); + L.op_o = gemm_op(b, T, D, qd, L.w_o, m.b_tattn, m.b_to); + L.op_ar1 = ar_op(b, g, m.b_to); + L.op_add1 = add_op(b, T, D, m.b_tm, m.b_to, m.b_tm); + L.op_fn = norm_op(b, T, D, g.eps, 1.0, L.w_fn, { m.b_tm }, m.b_th); + L.op_gu = gemm_op(b, T, 2 * ff, D, L.w_gu, m.b_th, m.b_tgu); + L.op_act = rows_op(b, "silu_mul", T, ff, { m.b_tgu }, { m.b_tff }); + L.op_down = gemm_op(b, T, D, ff, L.w_down, m.b_tff, m.b_to); + L.op_ar2 = ar_op(b, g, m.b_to); + L.op_add2 = add_op(b, T, D, m.b_tm, m.b_to, m.b_tm); + L.op_fin = norm_op(b, T, D, g.eps, 1.0, L.w_fin, { m.b_tm }, m.b_tho); + if (!L.op_emb || !L.op_en || !L.op_hn || !L.op_eh || !L.op_an || !L.op_q || !L.op_g || + !L.op_k || !L.op_v || !L.op_qn || !L.op_kn || !L.op_rq || !L.op_rk || !L.op_attn || + !L.op_kv || !L.op_sig || !L.op_mul || !L.op_o || !L.op_add1 || !L.op_fn || + !L.op_gu || !L.op_act || !L.op_down || !L.op_add2 || !L.op_fin || + (i == 0 && !L.op_eadd) || (g.world > 1 && (!L.op_ar1 || !L.op_ar2))) + return RAD_E_INVAL; + + /* A per-codebook layer's head draws code k + 1 (FRAME only). */ + if (!shared) { + L.w_head = wcopy(b, nm.f("tower.head.%d.weight", k), + nm.ckpt("audio_decoder_mtp.heads.%d.weight", k), RAD_BF16, + { kVocab, D }, grp); + L.op_head = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kVocab), + RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_head)), + { m.b_tho }, { m.b_hlog }); + L.op_samp = draw_op(b, S, kVocab, kTopK, kTemp, kTopP, 2 + k, m.b_hlog, m.b_codes); + if (!L.w_head || !L.op_head || !L.op_samp) return RAD_E_INVAL; + } + } + /* The codes stay live through the last layer: every layer's embedding reads them. */ + RAD_ARCH_TRY(rad_op_reads(b, m.tw[kTower - 1].op_samp, &m.b_codes, 1)); + return RAD_OK; +} + +/* ================================================================== the frame's tail */ +/* The frame into the lane's history, its unseen codes into the lane, and its embedding into the + * backbone's stream; after the backbone, the frame row's hidden state into the lane. */ +static int declare_frame_tail(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t S = m.lanes, D = m.g.n_embd; + m.b_unew = decl_b(b, nm.f("frame.unew"), RAD_BF16, { S, D }); + m.op_store = rw(b, RAD_OP(b, "frame_store", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_codes", kCodes), + RAD_INT("stride", kMaxFrames), RAD_INT("rep", 1), + RAD_INT("skip", 0)), + RAD_NOWEIGHTS), + { m.b_codes, m.b_status }, { m.b_hist }); + /* Codes 2..9 summed in f32 and rounded once, as embedding_bag does: sections 2..9. */ + m.op_u = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes - 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_codes }, { m.b_unew }); + m.op_uscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_unew }, { m.b_u }); + /* (E_lm[candidate] + E_cb[4096 + c1]) / sqrt 2, each sum rounded to bf16 as the reference's + * tensors are (tower.py, embed_backbone). */ + m.op_fb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0 / std::sqrt(2.0)), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cemb, m.w_cb)), + { m.b_codes }, { m.b_x }); + m.op_fstore = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.a_h.x }, { m.b_hid }); + return m.op_store && m.op_u && m.op_uscat && m.op_fb && m.op_fstore ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the codec */ +/* A causal conv whose weight the checkpoint keeps weight-normalised (folded at convert). */ +static int vconv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, int64_t rows, rad_buf x, rad_buf res, + rad_buf y, rad_buf cu, const char* act = "none") { + const char* wn = nm.f("%s.weight", dn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.parametrizations.weight.original0", src), + nm.ckpt("%s.parametrizations.weight.original1", src))); + v.w = decl_w(b, wn, RAD_BF16, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpCodec); + if (!v.w || !v.b) return RAD_E_INVAL; + const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout), + RAD_INT("k", k), RAD_INT("dil", dil), RAD_STR("act", act), + RAD_STR("dtype", "bf16"), RAD_INT("causal", 1) }; + const rad_weight ws[] = { v.w, v.b }; + v.op = res ? rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu, res }, { y }) + : rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu }, { y }); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +static rad_weight valpha(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t n) { + return wcopy(b, nm.f("%s.alpha", dn), nm.ckpt("%s.alpha", src), RAD_F32, { 1, n, 1 }, + kGrpCodec); +} + +static rad_op snake_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight a, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(a)), + { x }, { y }); +} + +static int declare_codec(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t NL = kVocContext + kVocChunk; /* frames through the transformer */ + const int64_t NC = kConvFrames; /* frames through the convolutions */ + const int64_t qd = kCtHeads * kCtHeadDim; + const char* q = "codec.quantizer"; + + /* ---- the dequantiser: each codebook's raw row (dimension 8) through its own 1x1 projection + * to 1024, summed into the transformer's stream. Code 0 is a candidate index (c0 + 1); codes + * 1..9 come from heads of 4096 and read 1024-entry codebooks clamped at 1023 (rvq.py). */ + m.b_rq = decl_b(b, nm.f("codec.rq"), RAD_BF16, { NL, kCbDim }); + m.b_cx = decl_b(b, nm.f("codec.x"), RAD_BF16, { NL, kLat }); + m.b_cconst = decl_b(b, nm.f("codec.nconv"), RAD_I32, { 1 }); + m.op_cnst = iota_op(b, 1, NC, 0, m.b_cconst); + for (int s = 0; s < kRates; ++s) { + m.b_ccu[s] = decl_b(b, nm.f("codec.cu%d", s), RAD_I32, { 2 }); + m.op_ccu[s] = s == 0 ? cu_op(b, 1, 0, m.b_ccu[0]) : cu_op(b, kRate[s], m.b_cconst, m.b_ccu[s]); + if (!m.op_ccu[s]) return RAD_E_INVAL; + } + for (int k = 0; k < kCodes; ++k) { + const char* qs = k == 0 ? nm.ckpt("%s.semantic_quantizer.quantizers.0", q) + : nm.ckpt("%s.quantizer.quantizers.%d", q, k - 1); + const int64_t bins = k == 0 ? kVocab : kResVocab; + m.w_cbk[k] = wcopy(b, nm.f("codec.cb%d.weight", k), nm.ckpt("%s.codebook.weight", qs), + RAD_BF16, { bins, kCbDim }, kGrpCodec); + m.op_rq[k] = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("n_embd", kCbDim), + RAD_INT("n_codes", 1), RAD_INT("vocab", bins), + RAD_INT("off0", k == 0 ? -1 : 0), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16"), + RAD_INT("clamp", k == 0 ? 0 : kResVocab)), + RAD_WEIGHTS(m.w_cbk[k], m.w_cbk[k])), + { m.b_hist }, { m.b_rq }); + /* The out-projection is the old-style weight norm (weight_g, weight_v). */ + VConv& v = m.qo[k]; + const char* wn = nm.f("codec.q%d.weight", k); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.out_proj.weight_g", qs), + nm.ckpt("%s.out_proj.weight_v", qs))); + v.w = decl_w(b, wn, RAD_BF16, { kLat, kCbDim, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("codec.q%d.bias", k), nm.ckpt("%s.out_proj.bias", qs), RAD_BF16, + { kLat }, kGrpCodec); + if (!m.w_cbk[k] || !m.op_rq[k] || !v.w || !v.b) return RAD_E_INVAL; + const RadParam ps[] = { RAD_RANGE("M", 1, NL), RAD_INT("cin", kCbDim), + RAD_INT("cout", kLat), RAD_INT("k", 1), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "bf16"), + RAD_INT("causal", 1) }; + const rad_weight ws[] = { v.w, v.b }; + v.op = k == 0 ? rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { m.b_rq, m.b_ccu[0] }, + { m.b_cx }) + : rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), + { m.b_rq, m.b_ccu[0], m.b_cx }, { m.b_cx }); + if (!v.op) return RAD_E_INVAL; + } + + /* ---- the post-quantiser transformer (modded_dac.py, WindowLimitedTransformer) */ + const char* pt = "codec.quantizer.post_module"; + m.b_ch = decl_b(b, nm.f("codec.h"), RAD_BF16, { NL, kLat }); + m.b_cqkv = decl_b(b, nm.f("codec.qkv"), RAD_BF16, { NL, 3 * qd }); + m.b_cattn = decl_b(b, nm.f("codec.attn"), RAD_BF16, { NL, qd }); + m.b_co = decl_b(b, nm.f("codec.o"), RAD_BF16, { NL, kLat }); + m.b_cgu = decl_b(b, nm.f("codec.gu"), RAD_BF16, { NL, 2 * kCtFf }); + m.b_cff = decl_b(b, nm.f("codec.ff"), RAD_BF16, { NL, kCtFf }); + m.ct.resize((size_t)kCtLayers); + for (int l = 0; l < kCtLayers; ++l) { + CodecLayer& L = m.ct[(size_t)l]; + auto src = [&](const char* s) { return nm.ckpt("%s.layers.%d.%s", pt, l, s); }; + auto dn = [&](const char* s) { return nm.f("codec.%d.%s", l, s); }; + L.w_n1 = wcopy(b, dn("n1.weight"), src("attention_norm.weight"), RAD_F32, { kLat }, + kGrpCodec); + L.w_n2 = wcopy(b, dn("n2.weight"), src("ffn_norm.weight"), RAD_F32, { kLat }, kGrpCodec); + L.w_ls1 = wcopy(b, dn("ls1.weight"), src("attention_layer_scale.gamma"), RAD_F32, + { kLat }, kGrpCodec); + L.w_ls2 = wcopy(b, dn("ls2.weight"), src("ffn_layer_scale.gamma"), RAD_F32, { kLat }, + kGrpCodec); + L.w_qkv = wcopy(b, dn("qkv.weight"), src("attention.wqkv.weight"), RAD_BF16, + { 3 * qd, kLat }, kGrpCodec); + L.w_o = wcopy(b, dn("o.weight"), src("attention.wo.weight"), RAD_BF16, { kLat, qd }, + kGrpCodec); + if (map_concat(b, dn("gate_up.weight"), + { src("feed_forward.w1.weight"), src("feed_forward.w3.weight") }) < 0) + return RAD_E_INVAL; + L.w_gu = decl_w(b, dn("gate_up.weight"), RAD_BF16, { 2 * kCtFf, kLat }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); + L.w_down = wcopy(b, dn("down.weight"), src("feed_forward.w2.weight"), RAD_BF16, + { kLat, kCtFf }, kGrpCodec); + /* Plain-gain RMS norms at eps 1e-5 (the codec's own RMSNorm, not the backbone's). */ + L.op_n1 = norm_op(b, NL, kLat, kCtEps, 0.0, L.w_n1, { m.b_cx }, m.b_ch); + L.op_qkv = gemm_op(b, NL, 3 * qd, kLat, L.w_qkv, m.b_ch, m.b_cqkv); + /* Adjacent pairs over all 64 dims, positions the frames' own in the piece, as a whole + * decode restarting at 0 would see them. */ + L.op_rope = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("head_dim", kCtHeadDim), + RAD_INT("n_head", kCtHeads), + RAD_INT("n_head_kv", kCtHeads), + RAD_F64("theta", kCtTheta), RAD_F64("scale", 1.0), + RAD_STR("mode", "gptj")), + RAD_NOWEIGHTS), + { m.b_cqkv }, { m.b_cqkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("head_dim", kCtHeadDim), + RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)kCtHeadDim)), + RAD_INT("max_seqlen", NL), RAD_INT("window", kAttnWin)), + RAD_NOWEIGHTS), + { m.b_cqkv }, { m.b_cattn }); + L.op_o = gemm_op(b, NL, kLat, qd, L.w_o, m.b_cattn, m.b_co); + L.op_ls1 = mulw_op(b, NL, kLat, L.w_ls1, m.b_co, m.b_co); + L.op_add1 = add_op(b, NL, kLat, m.b_cx, m.b_co, m.b_cx); + L.op_n2 = norm_op(b, NL, kLat, kCtEps, 0.0, L.w_n2, { m.b_cx }, m.b_ch); + L.op_gu = gemm_op(b, NL, 2 * kCtFf, kLat, L.w_gu, m.b_ch, m.b_cgu); + L.op_act = rows_op(b, "silu_mul", NL, kCtFf, { m.b_cgu }, { m.b_cff }); + L.op_down = gemm_op(b, NL, kLat, kCtFf, L.w_down, m.b_cff, m.b_co); + L.op_ls2 = mulw_op(b, NL, kLat, L.w_ls2, m.b_co, m.b_co); + L.op_add2 = add_op(b, NL, kLat, m.b_cx, m.b_co, m.b_cx); + if (!L.w_n1 || !L.w_n2 || !L.w_ls1 || !L.w_ls2 || !L.w_qkv || !L.w_o || !L.w_gu || + !L.w_down || !L.op_rope || !L.op_attn || !L.op_ls1 || !L.op_ls2 || !L.op_act) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_ccu[0], 1)); + } + /* The final norm over only the frames the convolutions read: the last nc. */ + m.w_cn = wcopy(b, nm.f("codec.norm.weight"), nm.ckpt("%s.norm.weight", pt), RAD_F32, { kLat }, + kGrpCodec); + m.b_ux[0] = decl_b(b, nm.f("codec.ux0"), RAD_BF16, { NC, kLat }); + m.op_cn = norm_op(b, NC, kLat, kCtEps, 0.0, m.w_cn, { m.b_cx }, m.b_ux[0]); + + /* ---- two 2x upsamplings, each a transposed conv of kernel 2 and a ConvNeXt block */ + m.b_ua = decl_b(b, nm.f("codec.ua"), RAD_BF16, { 4 * NC, kLat }); + m.b_ub = decl_b(b, nm.f("codec.ub"), RAD_BF16, { 4 * NC, kLat }); + m.b_uh = decl_b(b, nm.f("codec.uh"), RAD_BF16, { 4 * NC, 4 * kLat }); + m.b_ug2 = decl_b(b, nm.f("codec.ug"), RAD_BF16, { 4 * NC, 4 * kLat }); + for (int i = 0; i < 2; ++i) { + Upsample& U = m.up[i]; + const int64_t rin = NC << i, rout = NC << (i + 1); + const char* us = nm.ckpt("%s.upsample.%d", q, i); + auto w = [&](const char* dn, const char* s, uint32_t dt, + std::initializer_list sh) { + return wcopy(b, nm.f("codec.up%d.%s", i, dn), nm.ckpt("%s.%s", us, s), dt, sh, + kGrpCodec); + }; + U.w_t = w("t.weight", "0.conv.weight", RAD_BF16, { kLat, kLat, 2 }); + U.b_t = w("t.bias", "0.conv.bias", RAD_BF16, { kLat }); + U.w_dw = w("dw.weight", "1.dwconv.conv.weight", RAD_BF16, { kLat, 1, 7 }); + U.b_dw = w("dw.bias", "1.dwconv.conv.bias", RAD_BF16, { kLat }); + U.w_ln = w("ln.weight", "1.norm.weight", RAD_F32, { kLat }); + U.b_ln = w("ln.bias", "1.norm.bias", RAD_F32, { kLat }); + U.w_p1 = w("p1.weight", "1.pwconv1.weight", RAD_BF16, { 4 * kLat, kLat }); + U.b_p1 = w("p1.bias", "1.pwconv1.bias", RAD_BF16, { 4 * kLat }); + U.w_p2 = w("p2.weight", "1.pwconv2.weight", RAD_BF16, { kLat, 4 * kLat }); + U.b_p2 = w("p2.bias", "1.pwconv2.bias", RAD_BF16, { kLat }); + U.w_g = w("gamma", "1.gamma", RAD_F32, { kLat }); + m.b_ux[i + 1] = decl_b(b, nm.f("codec.ux%d", i + 1), RAD_BF16, { rout, kLat }); + U.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rin), RAD_INT("cin", kLat), + RAD_INT("cout", kLat), RAD_INT("stride", 2), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2)), + RAD_WEIGHTS(U.w_t, U.b_t)), + { m.b_ux[i], m.b_ccu[1 + i] }, { m.b_ux[i + 1] }); + U.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", kLat), + RAD_INT("k", 7), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_dw, U.b_dw)), + { m.b_ux[i + 1], m.b_ccu[2 + i] }, { m.b_ua }); + U.op_ln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", kLat), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_ln, U.b_ln)), + { m.b_ua }, { m.b_ub }); + U.op_p1 = gemm_bias_op(b, rout, 4 * kLat, kLat, U.w_p1, U.b_p1, m.b_ub, m.b_uh); + U.op_gelu = rows_op(b, "gelu", rout, 4 * kLat, { m.b_uh }, { m.b_ug2 }); + U.op_p2 = gemm_bias_op(b, rout, kLat, 4 * kLat, U.w_p2, U.b_p2, m.b_ug2, m.b_ua); + U.op_g = mulw_op(b, rout, kLat, U.w_g, m.b_ua, m.b_ua); + U.op_add = add_op(b, rout, kLat, m.b_ux[i + 1], m.b_ua, m.b_ux[i + 1]); + if (!U.w_t || !U.b_t || !U.w_dw || !U.b_dw || !U.w_ln || !U.b_ln || !U.w_p1 || !U.b_p1 || + !U.w_p2 || !U.b_p2 || !U.w_g || !U.op_t || !U.op_dw || !U.op_ln || !U.op_p1 || + !U.op_gelu || !U.op_p2 || !U.op_g || !U.op_add) + return RAD_E_INVAL; + } + + /* ---- the decoder: a conv into 1536 channels, four upsampling blocks, the output conv */ + const int64_t R0 = 4 * NC; /* rows at 4 a frame */ + int64_t rows[5], ch[5]; + rows[0] = R0; + ch[0] = kDec; + for (int i = 0; i < 4; ++i) { + rows[i + 1] = rows[i] * m.v_ups[i]; + ch[i + 1] = kDec >> (i + 1); + } + for (int s = 0; s < 5; ++s) { + m.b_vs[s] = decl_b(b, nm.f("codec.s%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vt[s] = decl_b(b, nm.f("codec.t%d", s), RAD_BF16, { rows[s], ch[s] }); + if (s > 0) { + m.b_va[s] = decl_b(b, nm.f("codec.a%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vb[s] = decl_b(b, nm.f("codec.b%d", s), RAD_BF16, { rows[s], ch[s] }); + } + } + const char* dd = "codec.decoder.model"; + RAD_ARCH_TRY(vconv(b, nm, m.dec0, "codec.dec0", nm.ckpt("%s.0.conv", dd), kLat, kDec, 7, 1, + R0, m.b_ux[2], 0, m.b_vs[0], m.b_ccu[3])); + static const int64_t kDil[3] = { 1, 3, 9 }; + for (int i = 0; i < 4; ++i) { + VBlock& B = m.vb[i]; + const int64_t ci = ch[i], co = ch[i + 1], s = m.v_ups[i]; + const char* bn = nm.f("codec.b%d", i); + const char* bs = nm.ckpt("%s.%d.block", dd, i + 1); + B.a = valpha(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.0", bs), ci); + B.op_s = snake_op(b, rows[i], ci, B.a, m.b_vs[i], m.b_vt[i]); + /* The transposed conv's weight norm is per input channel: its weight is [in, out, k]. */ + const char* wn = nm.f("%s.t.weight", bn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.1.conv.parametrizations.weight.original0", bs), + nm.ckpt("%s.1.conv.parametrizations.weight.original1", bs))); + B.wt = decl_w(b, wn, RAD_BF16, { ci, co, 2 * s }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + B.bt = wcopy(b, nm.f("%s.t.bias", bn), nm.ckpt("%s.1.conv.bias", bs), RAD_BF16, { co }, + kGrpCodec); + B.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[i]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", s), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2 * s)), + RAD_WEIGHTS(B.wt, B.bt)), + { m.b_vt[i], m.b_ccu[3 + i] }, { m.b_vs[i + 1] }); + if (!B.a || !B.wt || !B.bt || !B.op_t || !B.op_s) return RAD_E_INVAL; + /* Three residual units (dilations 1, 3, 9): x + conv2(snake2(conv1(snake1(x)))), x the + * stage buffer, written back in place by conv2's residual. */ + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* ub = nm.ckpt("%s.%d.block", bs, r + 2); + const int64_t R = rows[i + 1]; + U.a1 = valpha(b, nm, nm.f("%s.act1", un), nm.ckpt("%s.0", ub), co); + U.a2 = valpha(b, nm, nm.f("%s.act2", un), nm.ckpt("%s.2", ub), co); + U.op_s1 = snake_op(b, R, co, U.a1, m.b_vs[i + 1], m.b_vt[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.1.conv", ub), co, co, + 7, kDil[r], R, m.b_vt[i + 1], 0, m.b_va[i + 1], m.b_ccu[4 + i])); + U.op_s2 = snake_op(b, R, co, U.a2, m.b_va[i + 1], m.b_vb[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.3.conv", ub), co, co, + 1, 1, R, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], + m.b_ccu[4 + i])); + if (!U.a1 || !U.a2 || !U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + } + m.w_fa = valpha(b, nm, "codec.snake_out", nm.ckpt("%s.5", dd), ch[4]); + m.op_fs = snake_op(b, rows[4], ch[4], m.w_fa, m.b_vs[4], m.b_vt[4]); + m.b_vout = decl_b(b, nm.f("codec.out"), RAD_BF16, { rows[4], 1 }); + RAD_ARCH_TRY(vconv(b, nm, m.fin, "codec.conv_out", nm.ckpt("%s.6.conv", dd), ch[4], 1, 7, 1, + rows[4], m.b_vt[4], 0, m.b_vout, m.b_ccu[7], "tanh")); + m.b_audio = decl_b(b, nm.f("codec.audio"), RAD_F32, { kVocChunk * kSamplesPerFrame, 1 }, + RAD_BUF_PERSIST); + m.op_fcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, kVocChunk * kSamplesPerFrame), + RAD_INT("n", 1), RAD_STR("from", "bf16"), + RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_vout }, { m.b_audio }); + return m.w_cn && m.op_cn && m.w_fa && m.op_fs && m.op_fcast && m.op_cnst ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== declare */ +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + if (ctx->world_size > 2) { + fprintf(stderr, "radiance: fishomni: drama-3 is served on one or two cards (--tp 1 or 2): " + "its two KV heads and the tower's split stop at two ranks\n"); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + m.lanes = std::min(kMaxLanes, std::max(1, ctx->max_seqs)); + if (m.g.max_tok < kVocContext + kVocChunk) { + fprintf(stderr, "radiance: fishomni: a pass carries %lld rows; a codec chunk needs %lld\n", + (long long)m.g.max_tok, (long long)(kVocContext + kVocChunk)); + return RAD_E_INVAL; + } + + /* Declared in the order the passes issue them where it matters for liveness: the backbone + * first (PROMPT runs it before everything else), then the frame head, the tower, the frame's + * tail, and the codec. FRAME runs the head and the tower before the backbone; the buffers + * that cross that seam (`x`, `h`, the codes, the plane) are named by the ops on both sides, + * so their live ranges span it. */ + RAD_ARCH_TRY(declare_trunk(b, meta, ctx, m)); + RAD_ARCH_TRY(declare_frame_head(b, m)); + RAD_ARCH_TRY(declare_tower(b, meta, m)); + RAD_ARCH_TRY(declare_frame_tail(b, m)); + RAD_ARCH_TRY(declare_codec(b, m)); + + if (!ctx->shape_probe) { + RadAudioGenDecl d{}; + d.name = "drama-3"; + d.tmpl = nullptr; + d.tmpl_plain = kPlain; + d.prompt_whole = 1; + d.first_frame = 0; + d.max_prompt = kMaxPrompt; + d.max_frames = kMaxFrames; + d.frame_rate_num = kSampleRate; + d.frame_rate_den = kSamplesPerFrame; + d.lat_num = 1; + d.lat_den = 1; + d.samples_per_latent = kSamplesPerFrame; + d.sample_rate = kSampleRate; + d.channels = 1; + d.default_cfg = 1.0; + d.max_lanes = m.lanes; + d.status = m.b_status; + d.audio_out = m.b_audio; + d.voc_chunk = kVocChunk; + d.voc_context = kVocContext; + d.branches = 1; + d.input_special = 1; + RAD_ARCH_TRY(rad_declare_audio_generator(b, &d)); + } + rad_note(b, "rank %d/%d: drama-3 -- backbone %lld layers (%lld heads, %lld KV a rank; %lld " + "experts of %lld a rank, %lld a token), tower %d layers at KV layers %lld..%lld " + "(%lld heads a rank, ffn %lld), codec transformer %d layers, %lld lanes", + m.g.rank, m.g.world, (long long)m.n_main, (long long)m.g.n_head, + (long long)m.g.n_head_kv, (long long)m.moecfg.n_expert, (long long)m.moecfg.n_ff_exp, + (long long)m.moecfg.top_k, kTower, (long long)m.n_main, + (long long)(m.n_main + kTower - 1), (long long)m.gt.n_head, (long long)m.gt.n_ff, + (int)kCtLayers, (long long)m.lanes); + rad_note(b, "sampling: temperature %.2f, top-p %.2f, top-k %lld for the main token and every " + "head; a semantic first draw among the lane's last %lld picks is redrawn at " + "temperature %.2f, top-p %.2f, top-k %lld", + kTemp, kTopP, (long long)kTopK, (long long)kRasWin, kRasTemp, kRasTopP, + (long long)kRasTopK); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_trunk(RadCtx* c, const RadBatch* batch, const Model& m) { + const int64_t T = batch->n_tok; + if (m.op_rope_cs && T <= qk_fuse_rows(m.g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs)); + for (const Layer& l : m.layers) { + if (l.full) l.attn.step(c, batch); + else l.gdn.step(c, batch); + l.mlp.step(c, batch); + } + RAD_ISSUE_N(c, m.op_final_norm, T, brows(m.b_x, T), RAD_W(m.w_out_norm), brows(m.a_h.x, T)); +} + +/* Where the tower runs: its rows' positions and cache slots, the sequences' block tables, + * context lengths and bounds, and its first layer's hidden state. FRAME also embeds codes. */ +struct TowerAt { + int64_t R = 0; + int64_t max_q = 0; + RadOperand pos{}, slot{}, bt{}, used{}, cu{}; + rad_buf h0 = 0; + bool frame = false; + RadOperand seed{}, fidx{}; +}; + +static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) { + const Geom& g = m.gt; + const int64_t R = at.R, D = g.n_embd, hd = g.head_dim, Sx = m.lanes; + const int64_t qd = g.n_head * hd; + /* Row k of the code-major [10, lanes] plane, narrowed to this pass's lanes. */ + auto code = [&](int k) { + RadOperand o = brow_slice(m.b_codes, k, 1, Sx); + o.cols = R; + return o; + }; + for (int i = 0; i < kTower; ++i) { + const TowerLayer& L = m.tw[i]; + const int k = i - kShared; + if (at.frame) { + RAD_ISSUE_N(c, L.op_emb, R, code(k < 0 ? 0 : k), RAD_W(L.w_emb), RAD_W(L.w_emb), + brows(m.b_te, R)); + if (L.op_eadd) + RAD_ISSUE_N(c, L.op_eadd, R, brows(m.b_te, R), brows(m.b_ug, R), brows(m.b_te, R)); + RAD_ISSUE_N(c, L.op_en, R, brows(m.b_te, R), RAD_W(L.w_en), bcol(m.b_tcat, 0, D, R)); + } + RAD_ISSUE_N(c, L.op_hn, R, brows(i == 0 ? at.h0 : m.b_tho, R), RAD_W(L.w_hn), + bcol(m.b_tcat, D, D, R)); + RAD_ISSUE_N(c, L.op_eh, R, brows(m.b_tcat, R), RAD_W(L.w_eh), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_an, R, brows(m.b_tm, R), RAD_W(L.w_an), brows(m.b_th, R)); + RAD_ISSUE_N(c, L.op_q, R, brows(m.b_th, R), RAD_W(L.w_q), brows(m.b_tq, R)); + RAD_ISSUE_N(c, L.op_g, R, brows(m.b_th, R), RAD_W(L.w_g), brows(m.b_tg, R)); + RAD_ISSUE_N(c, L.op_k, R, brows(m.b_th, R), RAD_W(L.w_k), brows(m.b_tk, R)); + RAD_ISSUE_N(c, L.op_v, R, brows(m.b_th, R), RAD_W(L.w_v), brows(m.b_tv, R)); + RAD_ISSUE_N(c, L.op_qn, R * g.n_head, brows(m.b_tq, R), RAD_W(L.w_qn), brows(m.b_tq, R)); + RAD_ISSUE_N(c, L.op_kn, R * g.n_head_kv, brows(m.b_tk, R), RAD_W(L.w_kn), + brows(m.b_tk, R)); + RAD_ISSUE_N(c, L.op_rq, R, brows(m.b_tq, R), at.pos); + RAD_ISSUE_N(c, L.op_rk, R, brows(m.b_tk, R), at.pos); + RAD_ISSUE_N(c, L.op_kv, R, brows(m.b_tk, R), brows(m.b_tv, R), at.slot, + kv_cache(m.kv_full, (int)m.n_main + i)); + RAD_ISSUE_N(c, L.op_attn, at.max_q, brows(m.b_tq, R), + kv_cache(m.kv_full, (int)m.n_main + i), at.bt, at.used, RAD_NONE, RAD_NONE, + at.cu, brows(m.b_tattn, R)); + RAD_ISSUE_N(c, L.op_sig, R, brows(m.b_tg, R), brows(m.b_tg, R)); + RAD_ISSUE_N(c, L.op_mul, R, brows(m.b_tattn, R), brows(m.b_tg, R), brows(m.b_tattn, R)); + RAD_ISSUE_N(c, L.op_o, R, brows(m.b_tattn, R), RAD_W(L.w_o), brows(m.b_to, R)); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, R * D, brows(m.b_to, R), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, R, brows(m.b_tm, R), brows(m.b_to, R), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_fn, R, brows(m.b_tm, R), RAD_W(L.w_fn), brows(m.b_th, R)); + RAD_ISSUE_N(c, L.op_gu, R, brows(m.b_th, R), RAD_W(L.w_gu), brows(m.b_tgu, R)); + RAD_ISSUE_N(c, L.op_act, R, brows(m.b_tgu, R), brows(m.b_tff, R)); + RAD_ISSUE_N(c, L.op_down, R, brows(m.b_tff, R), RAD_W(L.w_down), brows(m.b_to, R)); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, R * D, brows(m.b_to, R), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, R, brows(m.b_tm, R), brows(m.b_to, R), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_fin, R, brows(m.b_tm, R), RAD_W(L.w_fin), brows(m.b_tho, R)); + if (at.frame && L.op_head) { + RAD_ISSUE_N(c, L.op_head, R, brows(m.b_tho, R), RAD_W(L.w_head), brows(m.b_hlog, R)); + RAD_ISSUE_N(c, L.op_samp, R, brows(m.b_hlog, R), at.seed, at.fidx, code(k + 1), + RAD_NONE, RAD_NONE, RAD_NONE); + } + } + (void)qd; +} + +static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t T = batch->n_tok, D = m.g.n_embd; + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_x, T)); + if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * D, brows(m.b_x, T), RAD_NONE); + step_trunk(c, batch, m); + + /* The lane: the prompt's last hidden state, an empty window, no unseen codes. */ + const int64_t S = batch->n_seq, lane = A->lane_h[0]; + RAD_ISSUE_N(c, m.op_plast, S, brows(m.a_h.x, T), praw(A->last_row, RAD_I32, S), + brows(m.b_last, S)); + RAD_ISSUE_N(c, m.op_pstore, S, brows(m.b_last, S), praw(A->slot, RAD_I32, S), + brows(m.b_hid, m.lanes)); + RAD_ISSUE_N(c, m.op_uzero, 1, brow_slice(m.b_u, lane, 1, D)); + { + RadOperand w = brow_slice(m.b_ras, lane, 1, kRasWin); + RAD_ISSUE_N(c, m.op_rasinit, kRasWin, w); + } + + /* The tower over every prompt row: the label of each is text, so every code embedding is 0. + * The last row's pass is FRAME 0's, which writes its cache rows again. */ + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv_full); + RAD_ISSUE_N(c, m.op_efill, T, bcol(m.b_tcat, 0, D, T)); + TowerAt at{}; + at.R = T; + at.max_q = batch->max_q_len; + at.pos = praw(batch->positions, RAD_I32, T); + at.slot = praw(kvb->slot_mapping, RAD_I32, T); + at.bt = praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + at.used = praw(kvb->seqused, RAD_I32, batch->n_seq); + at.cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + at.h0 = m.a_h.x; + step_tower(c, m, at); +} + +static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t S = A->n_lane, Sx = m.lanes; + const RadOperand seed = praw(A->seed, RAD_U32, 2 * S), frame = praw(A->frame, RAD_I32, S); + const RadOperand lanes = praw(A->lane, RAD_I32, S), slot = praw(A->slot, RAD_I32, S); + auto code = [&](int k) { + RadOperand o = brow_slice(m.b_codes, k, 1, Sx); + o.cols = S; + return o; + }; + + /* 1. the main token, from the hidden state of the row before the frame's */ + RAD_ISSUE_N(c, m.op_hsel, S, brows(m.b_hid, m.lanes), slot, brows(m.b_plane, S)); + RAD_ISSUE_N(c, m.op_head, S, brows(m.b_plane, S), RAD_W(m.w_cand), brows(m.b_slog, S)); + RAD_ISSUE_N(c, m.op_samp, S, brows(m.b_slog, S), seed, frame, brows(m.b_first, S), RAD_NONE, + RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, m.op_samp_ras, S, brows(m.b_slog, S), seed, frame, brows(m.b_alt, S), + RAD_NONE, RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, m.op_ras, S, brows(m.b_first, S), brows(m.b_alt, S), lanes, + brows(m.b_ras, m.lanes), code(0)); + RAD_ISSUE_N(c, m.op_status, S, code(0), lanes, brows(m.b_status, m.lanes)); + RAD_ISSUE_N(c, m.op_ugather, S, brows(m.b_u, m.lanes), slot, brows(m.b_ug, S)); + + /* 2. the tower at that row: its position, slot and context, the frame's own sequences */ + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv_full); + TowerAt at{}; + at.R = S; + at.max_q = 1; + at.pos = praw(A->prev_pos, RAD_I32, S); + at.slot = praw(A->prev_slot, RAD_I32, S); + at.bt = praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + at.used = praw(A->prev_used, RAD_I32, S); + at.cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + at.h0 = m.b_plane; + at.frame = true; + at.seed = seed; + at.fidx = frame; + step_tower(c, m, at); + + /* 3. the frame into the lane's history and the lane's unseen codes; the backbone over its + * embedding at the frame's own row */ + RAD_ISSUE_N(c, m.op_store, S, bcol_at(m.b_codes, 0, Sx, 0, S, kCodes), lanes, frame, + brows(m.b_status, m.lanes), brows(m.b_hist, m.lanes * kCodes)); + RadOperand sec2 = RAD_W(m.w_cb), sec3 = RAD_W(m.w_cb), sec1 = RAD_W(m.w_cb); + const int64_t D = m.g.n_embd; + sec1.rows = kVocab; + sec2.offset = kVocab * D; + sec2.rows = kVocab; + sec3.offset = 2 * kVocab * D; + sec3.rows = (kCodes - 3) * kVocab; + RAD_ISSUE_N(c, m.op_u, S, bcol_at(m.b_codes, 2, Sx, 0, S, kCodes - 2), sec2, sec3, + brows(m.b_unew, S)); + RAD_ISSUE_N(c, m.op_uscat, S, brows(m.b_unew, S), slot, brows(m.b_u, m.lanes)); + RAD_ISSUE_N(c, m.op_fb, S, bcol_at(m.b_codes, 0, Sx, 0, S, 2), RAD_W(m.w_cemb), sec1, + brows(m.b_x, S)); + step_trunk(c, batch, m); + RAD_ISSUE_N(c, m.op_fstore, S, brows(m.a_h.x, S), slot, brows(m.b_hid, m.lanes)); +} + +static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t nl = A->voc_latents, n = nl - A->voc_left, L = A->voc_lane; + const int64_t qd = kCtHeads * kCtHeadDim; + /* The convolutions run over the last kConvFrames frames, or all of them when fewer. */ + const int64_t nc = std::min(nl, kConvFrames), c0 = nl - nc; + const RadOperand nlen = praw(batch->cu_seqlens + 1, RAD_I32, 1); + const RadOperand clen = nc == nl ? nlen : brows(m.b_cconst, 1); + + /* 1. the bounds at each rate: the transformer's frames, then the convolutions' */ + if (nc != nl) RAD_ISSUE_N(c, m.op_cnst, 1, brows(m.b_cconst, 1)); + RAD_ISSUE_N(c, m.op_ccu[0], 2, nlen, brows(m.b_ccu[0], 2)); + for (int s = 1; s < kRates; ++s) RAD_ISSUE_N(c, m.op_ccu[s], 2, clen, brows(m.b_ccu[s], 2)); + + /* 2. the codes, dequantised: the lane's frames [voc_frame0, + nl) of each codebook */ + for (int k = 0; k < kCodes; ++k) { + RadOperand codes = bcol_at(m.b_hist, L * kCodes + k, kMaxFrames, A->voc_frame0, nl, 1); + RAD_ISSUE_N(c, m.op_rq[k], nl, codes, RAD_W(m.w_cbk[k]), RAD_W(m.w_cbk[k]), + brows(m.b_rq, nl)); + RAD_ISSUE_N(c, m.qo[k].op, nl, brows(m.b_rq, nl), RAD_W(m.qo[k].w), brows(m.b_ccu[0], 2), + k == 0 ? RAD_NONE : brows(m.b_cx, nl), brows(m.b_cx, nl), RAD_W(m.qo[k].b)); + } + + /* 3. the transformer over every frame of the pass */ + const RadOperand pos = praw(batch->positions, RAD_I32, nl); + const RadOperand cu = brows(m.b_ccu[0], 2); + for (const CodecLayer& Ly : m.ct) { + RAD_ISSUE_N(c, Ly.op_n1, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n1), brows(m.b_ch, nl)); + RAD_ISSUE_N(c, Ly.op_qkv, nl, brows(m.b_ch, nl), RAD_W(Ly.w_qkv), brows(m.b_cqkv, nl)); + RAD_ISSUE_N(c, Ly.op_rope, nl, brows(m.b_cqkv, nl), pos); + RAD_ISSUE_N(c, Ly.op_attn, nl, bcol(m.b_cqkv, 0, qd, nl), bcol(m.b_cqkv, qd, qd, nl), + bcol(m.b_cqkv, 2 * qd, qd, nl), cu, brows(m.b_cattn, nl)); + RAD_ISSUE_N(c, Ly.op_o, nl, brows(m.b_cattn, nl), RAD_W(Ly.w_o), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_ls1, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls1), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_add1, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); + RAD_ISSUE_N(c, Ly.op_n2, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n2), brows(m.b_ch, nl)); + RAD_ISSUE_N(c, Ly.op_gu, nl, brows(m.b_ch, nl), RAD_W(Ly.w_gu), brows(m.b_cgu, nl)); + RAD_ISSUE_N(c, Ly.op_act, nl, brows(m.b_cgu, nl), brows(m.b_cff, nl)); + RAD_ISSUE_N(c, Ly.op_down, nl, brows(m.b_cff, nl), RAD_W(Ly.w_down), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_ls2, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls2), brows(m.b_co, nl)); + RAD_ISSUE_N(c, Ly.op_add2, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); + } + RAD_ISSUE_N(c, m.op_cn, nc, brow_slice(m.b_cx, c0, nc, kLat), RAD_W(m.w_cn), + brows(m.b_ux[0], nc)); + + /* 4. the upsamplings, at 2 and 4 rows a frame */ + for (int i = 0; i < 2; ++i) { + const Upsample& U = m.up[i]; + const int64_t rin = nc << i, rout = nc << (i + 1); + RAD_ISSUE_N(c, U.op_t, rin, brows(m.b_ux[i], rin), RAD_W(U.w_t), RAD_W(U.b_t), + brows(m.b_ccu[1 + i], 2), brows(m.b_ux[i + 1], rout)); + RAD_ISSUE_N(c, U.op_dw, rout, brows(m.b_ux[i + 1], rout), RAD_W(U.w_dw), + brows(m.b_ccu[2 + i], 2), brows(m.b_ua, rout), RAD_W(U.b_dw)); + RAD_ISSUE_N(c, U.op_ln, rout, brows(m.b_ua, rout), RAD_W(U.w_ln), RAD_W(U.b_ln), + brows(m.b_ub, rout)); + RAD_ISSUE_N(c, U.op_p1, rout, brows(m.b_ub, rout), RAD_W(U.w_p1), RAD_W(U.b_p1), RAD_NONE, + brows(m.b_uh, rout)); + RAD_ISSUE_N(c, U.op_gelu, rout, brows(m.b_uh, rout), brows(m.b_ug2, rout)); + RAD_ISSUE_N(c, U.op_p2, rout, brows(m.b_ug2, rout), RAD_W(U.w_p2), RAD_W(U.b_p2), + RAD_NONE, brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_g, rout, brows(m.b_ua, rout), RAD_W(U.w_g), brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_add, rout, brows(m.b_ux[i + 1], rout), brows(m.b_ua, rout), + brows(m.b_ux[i + 1], rout)); + } + + /* 5. the decoder */ + int64_t rows[5]; + rows[0] = 4 * nc; + for (int i = 0; i < 4; ++i) rows[i + 1] = rows[i] * m.v_ups[i]; + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cub) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), brows(cub, 2), + res ? brows(res, R) : RAD_NONE, brows(y, R), RAD_W(v.b)); + }; + conv(m.dec0, m.b_ux[2], 0, m.b_vs[0], rows[0], m.b_ccu[3]); + for (int i = 0; i < 4; ++i) { + const VBlock& B = m.vb[i]; + const int64_t r0 = rows[i], r1 = rows[i + 1]; + RAD_ISSUE_N(c, B.op_s, r0, brows(m.b_vs[i], r0), RAD_W(B.a), brows(m.b_vt[i], r0), + RAD_NONE); + RAD_ISSUE_N(c, B.op_t, r0, brows(m.b_vt[i], r0), RAD_W(B.wt), RAD_W(B.bt), + brows(m.b_ccu[3 + i], 2), brows(m.b_vs[i + 1], r1)); + for (int r = 0; r < 3; ++r) { + const VRes& U = B.res[r]; + RAD_ISSUE_N(c, U.op_s1, r1, brows(m.b_vs[i + 1], r1), RAD_W(U.a1), + brows(m.b_vt[i + 1], r1), RAD_NONE); + conv(U.c1, m.b_vt[i + 1], 0, m.b_va[i + 1], r1, m.b_ccu[4 + i]); + RAD_ISSUE_N(c, U.op_s2, r1, brows(m.b_va[i + 1], r1), RAD_W(U.a2), + brows(m.b_vb[i + 1], r1), RAD_NONE); + conv(U.c2, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], r1, m.b_ccu[4 + i]); + } + } + RAD_ISSUE_N(c, m.op_fs, rows[4], brows(m.b_vs[4], rows[4]), RAD_W(m.w_fa), + brows(m.b_vt[4], rows[4]), RAD_NONE); + conv(m.fin, m.b_vt[4], 0, m.b_vout, rows[4], m.b_ccu[7]); + /* 6. the chunk's own samples: its last n frames */ + const int64_t ns = n * kSamplesPerFrame; + RAD_ISSUE_N(c, m.op_fcast, ns, brow_slice(m.b_vout, rows[4] - ns, ns, 1), brows(m.b_audio, ns)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->agen_b) { + rad_step_fail(c, "fishomni is an audio generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_PROMPT: step_prompt(c, batch, m); return; + case RAD_GEN_PASS_FRAME: step_frame(c, batch, m); return; + case RAD_GEN_PASS_VOCODE: step_vocode(c, batch, m); return; + default: + rad_step_fail(c, "fishomni: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = kMaxPrompt; + out->gen_audio = 1; + out->gen_ctx = kMaxPrompt + kMaxFrames + 1; + return RAD_OK; +} + +/* ================================================================== the request's text */ +/* A Unicode White_Space code point's length at `s`, else 0. Python's str.strip() without + * arguments also strips U+001C..U+001F, which fish-speech avoids (generate.py, + * UNICODE_WHITE_SPACE); so does this. */ +static size_t white_space_at(const unsigned char* s, size_t n) { + if (n >= 1 && ((s[0] >= 0x09 && s[0] <= 0x0D) || s[0] == 0x20)) return 1; + if (n >= 2 && s[0] == 0xC2 && (s[1] == 0x85 || s[1] == 0xA0)) return 2; + if (n >= 3 && s[0] == 0xE1 && s[1] == 0x9A && s[2] == 0x80) return 3; /* U+1680 */ + if (n >= 3 && s[0] == 0xE2 && s[1] == 0x80 && + ((s[2] >= 0x80 && s[2] <= 0x8A) || s[2] == 0xA8 || s[2] == 0xA9 || s[2] == 0xAF)) + return 3; /* U+2000..200A, 2028, 2029, 202F */ + if (n >= 3 && s[0] == 0xE2 && s[1] == 0x81 && s[2] == 0x9F) return 3; /* U+205F */ + if (n >= 3 && s[0] == 0xE3 && s[1] == 0x80 && s[2] == 0x80) return 3; /* U+3000 */ + return 0; +} + +/* The length of a canonical speaker tag at `s` (`<|speaker:N|>`, N 0..15 without a leading + * zero), else 0. */ +static size_t speaker_tag_at(const char* s, size_t n) { + static const char kHead[] = "<|speaker:"; + const size_t h = sizeof kHead - 1; + if (n < h || std::strncmp(s, kHead, h) != 0) return 0; + size_t i = h; + while (i < n && s[i] >= '0' && s[i] <= '9') ++i; + const size_t digits = i - h; + if (digits == 0 || digits > 2 || i + 1 >= n || s[i] != '|' || s[i + 1] != '>') return 0; + if (digits == 2 && s[h] == '0') return 0; + const int v = digits == 1 ? s[h] - '0' : (s[h] - '0') * 10 + (s[h + 1] - '0'); + return v <= 15 ? i + 2 : 0; +} + +static int64_t refuse(char* out, int64_t cap, const char* why) { + if (out && cap > 0) std::snprintf(out, (size_t)cap, "%s", why); + return RAD_E_INVAL; +} + +/* `s` without the Unicode White_Space at either end. */ +static std::string strip_white(const std::string& s) { + const unsigned char* u = (const unsigned char*)s.data(); + size_t a = 0, z = s.size(); + for (size_t w; a < z && (w = white_space_at(u + a, z - a)) > 0;) a += w; + /* From the back: a White_Space code point is one to three bytes, so try each ending. */ + for (bool more = true; more && z > a;) { + more = false; + for (size_t w = 1; w <= 3 && w <= z - a; ++w) + if (white_space_at(u + z - w, w) == w) { + z -= w; + more = true; + break; + } + } + return s.substr(a, z - a); +} + +/* What fish-speech's server hands the model (chunking.py, split_drama3_text): each speaker's turn + * as "<|speaker:N|> " and its text stripped of white space at both ends, turns joined by a newline, + * text before the first tag speaker 0's; untagged text stripped and given speaker 0 + * (generate.py, with_speaker_tag). Its model was trained on that form: the same two turns joined + * by a space instead are spoken through less often. `r` is validated already. */ +static std::string speaker_turns(const std::string& r) { + if (r.find("<|speaker") == std::string::npos) return "<|speaker:0|> " + strip_white(r); + std::string outs, id = "0"; + size_t at = 0; + auto turn = [&](const std::string& who, size_t a, size_t z) { + const std::string body = strip_white(r.substr(a, z - a)); + if (body.empty()) return; + if (!outs.empty()) outs += "\n"; + outs += "<|speaker:" + who + "|> " + body; + }; + for (size_t t = r.find("<|speaker"); t != std::string::npos;) { + turn(id, at, t); + const size_t len = speaker_tag_at(r.data() + t, r.size() - t); + id = r.substr(t + 10, len - 12); /* the digits between "<|speaker:" and "|>" */ + at = t + len; + t = r.find("<|speaker", at); + } + turn(id, at, r.size()); + return outs; +} + +/* generate.py's validate_drama3_text: the input is not empty, holds none of the tokens only the + * prompt builder writes, and names speakers only as <|speaker:0|> to <|speaker:15|>; then its + * speaker turns are written as the reference's server writes them (speaker_turns). */ +static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { + if (!in) return RAD_E_INVAL; + std::string r = in; + if (field == RAD_TEXT_INPUT) { + const unsigned char* u = (const unsigned char*)r.data(); + const size_t n = r.size(); + size_t lead = 0; + for (size_t w; lead < n && (w = white_space_at(u + lead, n - lead)) > 0;) lead += w; + bool blank = true; + for (size_t i = lead; i < n && blank;) { + const size_t w = white_space_at(u + i, n - i); + if (w == 0) blank = false; + else i += w; + } + if (blank) return refuse(out, cap, "the input is empty: there is nothing to speak"); + static const char* kStructural[] = { "<|im_start|>", "<|im_end|>", "<|voice|>", + "<|text|>", "<|interleave|>", "<|semantic:" }; + for (const char* t : kStructural) + if (r.find(t) != std::string::npos) { + char why[128]; + std::snprintf(why, sizeof why, "%s is written by the prompt builder, not the input", + t); + return refuse(out, cap, why); + } + for (size_t at = r.find("<|speaker"); at != std::string::npos; + at = r.find("<|speaker", at + 1)) + if (!speaker_tag_at(r.data() + at, n - at)) + return refuse(out, cap, "speaker tags are <|speaker:0|> to <|speaker:15|>"); + r = speaker_turns(r); + if (r.empty()) return refuse(out, cap, "the input is empty: there is nothing to speak"); + } + if ((int64_t)r.size() < cap) { + std::memcpy(out, r.data(), r.size()); + out[r.size()] = 0; + } + return (int64_t)r.size(); +} + +} /* namespace fishomni */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(fishomni) +extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) { + return fishomni::text_prepare(field, in, out, cap); +} +RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0", + "Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a " + "13-layer codebook tower over its full-attention cache, and Fish S2's modified " + "DAC; 44.1 kHz mono speech") +#endif diff --git a/data/recipes/drama3-fp8.recipe b/data/recipes/drama3-fp8.recipe new file mode 100644 index 00000000..9694078e --- /dev/null +++ b/data/recipes/drama3-fp8.recipe @@ -0,0 +1,21 @@ +# drama3-fp8.recipe -- Fish Audio drama-3 as its release ships it: block-scaled fp8 routed experts, +# everything else of the language model and the codebook tower bf16. +# +# rad-convert \ +# --recipe data/recipes/drama3-fp8.recipe -o drama3-fp8.rad +# +# The directory holds the model and codec.pth, its codec, which is read as checkpoint tensors +# under `codec.` (core/format/torch_zip.h). The model is kept as stored. The codec ships f32: +# its weight-normalised convolutions are folded here, and its linears, convolutions and +# codebooks cast to bf16, the precision fish-speech decodes at, while its norms, layer scales, +# ConvNeXt gains and snake parameters stay f32 -- read once a pass or less. + +codec.*.n1.weight cast dtype=f32 +codec.*.n2.weight cast dtype=f32 +codec.*.ls1.weight cast dtype=f32 +codec.*.ls2.weight cast dtype=f32 +codec.norm.weight cast dtype=f32 +codec.up*.ln.* cast dtype=f32 +codec.up*.gamma cast dtype=f32 +codec.*.alpha cast dtype=f32 +codec.* cast dtype=bf16 diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index a5a6967b..d95d2cc1 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -7,7 +7,9 @@ #include "rad_test.h" #include "plugin/registry.h" +#include "rad_builder.h" +#include #include #include #include @@ -88,8 +90,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, - { "flux3distilled", "" }, + { "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, + { "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, @@ -133,4 +135,65 @@ TEST(every_shipped_family_has_at_most_one_plugin_for_an_imported_checkpoint) { CHECK(!w8->arch_serves_imports); } +/* drama-3's input as fish-speech's server writes it (chunking.py, generate.py): each speaker's turn + * tagged and stripped, turns on lines of their own, untagged text speaker 0's; refused when empty, + * when it holds a token only the prompt builder writes, or when it names a speaker other than 0..15 + * the canonical way. A refusal leaves its reason in the output. */ +TEST(fishomni_writes_the_input_as_the_reference_server_does) { + Registry r; + const int st = r.load_dir(dir_of("architectures"), {}); + if (st == RAD_E_IO && r.plugins().empty()) + ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures")); + CHECK_OK(st); + const Plugin* p = r.plugin("fishomni"); + REQUIRE(p != nullptr); + REQUIRE(p->arch_text_prepare != nullptr); + auto prep = [&](const char* in, std::string* out) { + char buf[512] = {}; + const int64_t n = p->arch_text_prepare(RAD_TEXT_INPUT, in, buf, sizeof buf); + *out = buf; + return n; + }; + const struct { const char* in; const char* want; } ok[] = { + { "Hello there.", "<|speaker:0|> Hello there." }, + { " Hello there. \n", "<|speaker:0|> Hello there." }, + { "\xe3\x80\x80Hello\xc2\xa0", "<|speaker:0|> Hello" }, /* U+3000, U+00A0 */ + { "<|speaker:0|> Are you ready? <|speaker:1|> Always.", + "<|speaker:0|> Are you ready?\n<|speaker:1|> Always." }, + { "Hi <|speaker:12|>Hey <|speaker:3|> ", "<|speaker:0|> Hi\n<|speaker:12|> Hey" }, + { "<|speaker:2|>[laughs] Fine.", "<|speaker:2|> [laughs] Fine." }, + }; + for (const auto& c : ok) { + std::string got; + const int64_t n = prep(c.in, &got); + if (got != c.want) fprintf(stderr, " '%s' -> '%s'\n", c.in, got.c_str()); + CHECK_EQ(n, (int64_t)std::strlen(c.want)); + CHECK_EQ(got, std::string(c.want)); + } + const struct { const char* in; const char* why; } refused[] = { + { " \t", "empty" }, + { "<|speaker:1|> ", "empty" }, + { "Say <|im_end|> now", "<|im_end|>" }, + { "<|voice|>", "<|voice|>" }, + { "a <|semantic:12|> b", "<|semantic:" }, + { "<|speaker:16|> hi", "speaker tags" }, + { "<|speaker:01|> hi", "speaker tags" }, + { "<|speaker_change|> hi", "speaker tags" }, + }; + for (const auto& c : refused) { + std::string why; + CHECK(prep(c.in, &why) < 0); + if (why.find(c.why) == std::string::npos) fprintf(stderr, " '%s': %s\n", c.in, why.c_str()); + CHECK(why.find(c.why) != std::string::npos); + } + /* A short buffer still gets the length to retry with, and the instructions (which the model + * refuses before they get here) pass as written. */ + char tiny[4] = {}; + CHECK_EQ(p->arch_text_prepare(RAD_TEXT_INPUT, "Hello", tiny, sizeof tiny), + (int64_t)std::strlen("<|speaker:0|> Hello")); + char buf[64] = {}; + CHECK_EQ(p->arch_text_prepare(RAD_TEXT_INSTRUCTIONS, " calm ", buf, sizeof buf), 6); + CHECK_EQ(std::string(buf), std::string(" calm ")); +} + RAD_TEST_MAIN() From d886e4d0abe609483c9c99fb483ea92e39416e01 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 22:42:58 +0200 Subject: [PATCH 09/35] docs, compose: Fish Audio drama-3 -- the architecture with its traps and measured parity against fish-speech, serving it (speaker tags, direction in the input, the length, sampling), its recipe and compose file, and its licence --- README.md | 7 ++- deploy/compose/drama3.yaml | 16 ++++++ docs/ARCHITECTURES.md | 100 +++++++++++++++++++++++++++++++++++++ docs/GUIDE.md | 56 +++++++++++++++++++-- 4 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 deploy/compose/drama3.yaml diff --git a/README.md b/README.md index 3b980f2a..556397a4 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` | | MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | +| Fish Audio drama-3: speech with speaker tags and inline direction, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | | GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | @@ -110,7 +111,10 @@ from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays speech in a voice the request describes, made in 0.6 of its playing time on one card, its first streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written, over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use -only. +only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it +(`<|speaker:1|>`, `[laughs]`), at 0.3 of its playing time on two cards, its first streamed audio +0.23 s after the request; under the Fish Audio Community License a service that lets others +generate speech with it needs a licence from Fish Audio. ## Run with Docker @@ -193,6 +197,7 @@ four-rank rows have no compose file. The other models' flags are in their compos | MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` | | MiniMax-Music3 | `--tp 2` | | Breeze-TTS-2 | `--tp 1` | +| Fish Audio drama-3 | `--tp 2` | Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference) and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of diff --git a/deploy/compose/drama3.yaml b/deploy/compose/drama3.yaml new file mode 100644 index 00000000..6d95f2be --- /dev/null +++ b/deploy/compose/drama3.yaml @@ -0,0 +1,16 @@ +# Fish Audio drama-3 (fishaudio/drama-3) as released, its routed experts block-scaled fp8: speech on +# /v1/audio/speech, whole or streamed, and text spoken as it is written over the +# /v1/audio/speech/stream WebSocket. Speakers are named in the input (<|speaker:0|> to +# <|speaker:15|>) and so is the direction ([laughs], [whispering], a bracketed style). Two cards. +# Under the Fish Audio Community License, research, non-commercial use and small commercial use are +# free; a service that lets others generate speech (an API, a TTS site) needs a licence from Fish +# Audio, and so does imitating a real person's voice without their consent. +name: radiance-drama3 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-drama3 + command: > + --model /models/drama3-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 9c11fd90..4e23659c 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -29,6 +29,7 @@ plugin claims. | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | | `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | | `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card | +| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC (`codec.pth`, read as data); from the release directory, two cards | | `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) | | `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card | @@ -1310,6 +1311,105 @@ codes. Whisper large-v3 transcribes radiance's speech word for word. --- +# `fishomni`: Fish Audio drama-3, speech + +`arch/fishomni` declares an audio generator in its chunked form with one branch a request +(`rad_declare_audio_generator`, `branches` 1, `voc_chunk`): PROMPT runs the backbone over the +whole prompt and the codebook tower over every prompt row, FRAME draws one frame of every speech in +flight and runs the backbone over its embedding, VOCODE plays a lane's newest frames, sixteen at +most. It is served on `/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)), +on two cards. The checkpoint is the release directory; its codec, `codec.pth`, is read with it as +checkpoint tensors under `codec.` (a `torch.save` archive, read as data and never unpickled: +`core/format/torch_zip.h`). + +``` +backbone Qwen3.5-35B-A3B's language model, unchanged: 40 layers of 2048, three gated delta-net + layers to one gated attention layer (16 q / 2 kv heads of 256, NeoX rotary on 64 dims + at theta 1e7), 256 experts of 512 at top-8 and a gated shared expert of 512, (1 + w) + norms but the delta net's output norm. Only the routed experts are fp8 (E4M3 at an f32 + scale a 128 x 128 block, `quant_method: bsgemm-moe`); the rest is bf16. A prompt row is + a token; a frame's row is bf16(bf16(E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2): + code 0 through its semantic token, code 1 through section 1 of the codebook table +head the main token over 4097 candidates only, the end of speech (248046) and the 4096 + semantic tokens in id order: the lm_head's rows for them, replicated (the full head is + never declared) +tower 13 layers bound as layers 40..52 of the backbone's full-attention KV group, causal over + the whole sequence at the backbone's positions: 4 shared layers that inject code 0, then + one a codebook, layer k injecting code k - 1 and its head drawing code k (4096 outputs). + A layer is m = eh_proj([enorm(e); hnorm(h)]), a pre-norm block (q, gate, k, v from + wqkv's rows [Q 4096 | G 4096 | K 512 | V 512], (1 + w) q/k norms, GPT-J rotary on 64 + dims at 1e7, attention * sigmoid(gate), SwiGLU 6144), a final (1 + w) norm. The first + shared layer also adds the input frame's codes 2..9, embedded and summed in f32 +sampling fish-speech's server defaults: temperature 0.7, top-p 0.7 over the whole candidate set, + then top-k 30, for the main token and every head; a semantic first draw among the + lane's last 16 picks is redrawn at 1.0 / 0.95 / 30 (`ras_pick`) +codec Fish S2's modified DAC decoder: ten raw codebook rows of 8 (one of 4096, nine of 1024, + codes 1..9 clamped to 1023), each through its own weight-normed 1x1 projection to 1024 + and summed; 8 layers of 1024 (16 heads of 64, GPT-J rotary on all 64 at theta 1e4, + causal over 128 frames, plain RMS norms at 1e-5, layer scales); twice a transposed + conv k2 s2 and a ConvNeXt block; a causal conv k7 to 1536; four blocks of snake, a + weight-normed causal transposed conv (8, 8, 4, 2) and three residual units (dilations + 1, 3, 9); snake and a conv k7 to one channel, tanh: 2048 samples a frame, 44.1 kHz mono +``` + +The passes, which shift the tower by a row against the reference's loop: + +- **PROMPT** runs the backbone over the prompt and leaves its last row's final-norm hidden state in + the lane, then runs the tower over every row, teacher-forced: each row's label is the row after + it, which in a prompt is text, so every layer's code embedding is zero (the concatenation's + embedding half is filled with zeros once). The last row's tower pass belongs to the first frame; + FRAME 0 writes its cache rows again. +- **FRAME j** draws the main token from the hidden state of the row before the frame's (the + prompt's last for frame 0), runs the tower at THAT row's position, cache slot and context + (`RadAudioGenBatch::prev_slot`, `prev_pos`, `prev_used`) drawing codes 1..9, stores the frame, + and runs the backbone over its embedding at the frame's own row. + +Traps (each still speaks, wrongly): + +- **The experts' scale planes are f32**, not the bf16 of Qwen3.6-35B-A3B-FP8: the expert format is + read per layer (`MoeFP8::probe`), served as fp8a8f32. +- **The tower's wqkv is blocked, `[Q | G | K | V]`**, not the backbone's per-head `[q_h | gate_h]` + pairs; its rotary is GPT-J's adjacent pairs, not the backbone's halves; its q/k norms run with + `(1 + w)` although its config says `attention_qk_norm: false` (the exporter never wrote it). +- **`eh_proj` reads `[enorm(e); hnorm(h)]`**, the embedding half first. +- **Two masks.** A layer's code embedding is the label frame's, zero when the label is text; the + input frame's codes 2..9 go into the first shared layer only, zero when the input row is text. + The layers that inject code 0 read it by candidate, with the table's row 0 again in front: the + end of speech's code 0 is clamped to 0, as fish-speech clamps it. +- **The tower attends over the whole sequence**, prompt rows included, from 13 caches of its own; + it is not an 11-position depth decoder (`max_seq_len` 11 is left over from S2). +- **The candidates' softmax is over the 4097 only**, top-p over all of them and the top-k cut after + it; a full-vocabulary softmax keeps a different nucleus. +- **The codec's residual codebooks have 1024 entries** and the heads 4096 outputs: codes are clamped + at 1023 at decode (`rvq_embed`'s `clamp`). Its weight norm is per output channel for the convs + and per INPUT channel for the transposed convs (`[in, out, k]`), folded at convert. +- **The input is written as fish-speech's server writes it**: each speaker's turn + `<|speaker:N|> ` and its text stripped, turns joined by a newline, untagged text speaker 0's. + The same two turns joined by a space are spoken through far less often: for one two-line script, + one seed in six spoke both lines, against seven in ten with the newline. + +Against fish-speech's own PyTorch code (the CPU path: experts fp8, dequantised per forward, so +W8A16 where radiance runs W8A8), teacher-forced with radiance's codes over a 34-row prompt and 80 +frames: the prompt's token ids are identical; the backbone's hidden state is 5.3% from the +reference's (relative L2, median over the frames; cosine at least 0.993), the experts' fp8 +activations most of it; the main token's candidate logits 3.6% (KL 0.013 nats a frame, the same +argmax in 92.5% of frames); the nine heads' logits 1.35% (KL 0.007, the same argmax 93% of the time) +over the 79 frames that are spoken. Through the codec, radiance's chunked bf16 decode is 35.4 dB SNR +from the reference's whole-utterance bf16 decode of the same codes. Qwen3-ASR transcribes +radiance's speech word for word. + +The model's own failure is to stop after the first line of a script, or to fall silent until the +length runs out (vLLM-Omni's recipe and SGLang-Omni's notes describe it). Over 20 seeds of two +invented two-speaker lines, the second speaker was spoken in 14 and 17 of 20, and 2 and 3 takes ran +past 8 s; at a main top-k of 256 instead of 30 it was 14 and 15, with 5 long takes each, so the +reference's 30 stays. + +On two R9700s a sentence is made at 0.30 of the time it plays (3.67 s of speech in 1.08 s, 13.5 ms +a frame with the codec), a paragraph at 0.29 (11.6 s in 3.34 s); a stream's first audio comes +0.23 s after the request; four paragraphs at once make 50.4 s of speech in 5.15 s. + +--- + # `minimaxh3`: MiniMax-H3, video with sound `arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 6c89aebb..bb85198e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -282,6 +282,7 @@ and runs. | `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) | | `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) | | `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) | +| `fishomni` | Fish Audio drama-3, speech from text with speaker tags and inline direction (§5.15) | | `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) | | `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) | @@ -458,6 +459,12 @@ rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \ # bf16 (6 GB, one card) rad-convert /srv/models/BreezeBlue/Breeze-TTS-2 -o breeze-tts2-bf16.rad \ --recipe data/recipes/breeze-tts2-bf16.recipe + +# Fish Audio drama-3, speech (§5.15): the release directory, its codec in codec.pth read with it +# (a torch.save checkpoint read as data, never unpickled); the experts stay block fp8 as shipped, +# the codec is cast to bf16 (39 GB, two cards) +rad-convert /srv/models/fishaudio/drama-3 -o drama3-fp8.rad \ + --recipe data/recipes/drama3-fp8.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read @@ -1611,7 +1618,7 @@ a model that takes no images or video. A Qwen-VL container that states none uses | `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) | | `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) | | `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) | -| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2), `instructions` describing the voice; songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) | +| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2, `instructions` describing the voice; drama-3, speakers and direction in the input); songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) | | `GET /v1/audio/speech/stream` (WebSocket) | vLLM-Omni's realtime speech session: text streamed in, each sentence's audio streamed out as soon as the sentence is complete; needs an audio generation model (§5.15) | | `POST /v1/videos`, `GET /v1/videos[/:id[/content]]`, `DELETE /v1/videos/:id` | OpenAI's video jobs: a video with its soundtrack from a prompt, made in the background and downloaded as MP4; needs a video model (MiniMax-H3), else 501 (§5.16) | | `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) | @@ -2410,10 +2417,11 @@ socket. ### 5.15 Speech and music: `/v1/audio/speech` -An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model (Breeze-TTS-2) -speaks `input`, in a voice `instructions` may describe; a music model (MiniMax-Music3) sings `input` -as lyrics, as `instructions` describe the song (SGLang-Omni's reading of the route). Both are -converted from their release directories (§3.2). +An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model speaks `input`, +in a voice `instructions` may describe (Breeze-TTS-2) or with its speakers and direction written in +the input itself (drama-3); a music model (MiniMax-Music3) sings `input` as lyrics, as +`instructions` describe the song (SGLang-Omni's reading of the route). Each is converted from its +release directory (§3.2). #### Speech: Breeze-TTS-2 @@ -2442,6 +2450,44 @@ as it is spoken. On one R9700 a sentence is made at 0.6 of the time it plays (5. speed they play (43 s of speech in 12.1 s). Breeze-TTS-2 is licensed for research and non-commercial use only, and BreezeBlue counts hosting it as an API as commercial. +#### Speech: drama-3 + +```sh +radiance --model drama3-fp8.rad --tp 2 # two cards + +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "The lighthouse keeper counted seven ships before the fog rolled in."}' -o ships.wav +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ + "input": "<|speaker:0|> Did you lock the back door?\n<|speaker:1|> [sighs] I thought you did."}' \ + -o door.wav # 44.1 kHz mono, 16-bit +``` + +- **`input`** is the script. Speakers are named in it, `<|speaker:0|>` to `<|speaker:15|>`, and + text before any tag is speaker 0's; each speaker's turn is written as Fish Audio's server writes + it (the tag, a space, the turn's text stripped, each turn on a line of its own), so the turns may + be given on one line. The direction is written in the text too: point tags such as `[laughs]`, + `[sighs]` or `[pause]`, a bracketed style before a line (`[with bright eager excitement] We + won!`), `...`. The tokens only the prompt is built from (`<|im_start|>`, + `<|im_end|>`, `<|voice|>`, `<|text|>`, `<|interleave|>`, `<|semantic:...|>`) are refused, and so + is any other spelling of a speaker. +- **`instructions` are refused**, the direction being the input's; `guidance_scale` must be 1 (the + model runs one branch). Each speaker's voice is the model's choice, the same within a take: + cloning a voice from a recording is not served yet. +- **The length** is `duration` in seconds or `max_new_tokens` in frames (21.5 a second), up to 95 s; + the model ends the speech at the end of the script. The prompt holds at most 2048 tokens. +- **Sampling** is fish-speech's server's: temperature 0.7, top-p 0.7, top-k 30, with its + repetition-aware redraw of the first code. A take sometimes stops after its first line or falls + silent until its length runs out (the model's own failure, more often with several speakers); + another `seed` usually speaks the whole script. +- **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below. + +Speech is played sixteen frames (0.74 s) at a time as it is made. On two R9700s a sentence is made +at 0.30 of the time it plays (3.67 s of speech in 1.08 s) and a stream's first audio comes 0.23 s +after the request; four paragraphs at once make 50.4 s of speech in 5.15 s. drama-3 is under the +Fish Audio Community License: research, non-commercial and small commercial use are free; a +service that lets others generate speech needs a licence from Fish Audio, and so does imitating a +real person's voice without their consent. + #### Music: MiniMax-Music3 ```sh From 00f97038928dea4b2192e75e91420313d23a67d3 Mon Sep 17 00:00:00 2001 From: zivius Date: Tue, 20 Oct 2026 23:06:26 +0200 Subject: [PATCH 10/35] fishomni: sampling as SGLang-Omni draws -- temperature 1.0 and top-p 0.9 from Fish Audio's model card, the main token uncapped and each head at top-k 30; at fish-speech's server settings the model fell silent after a tag or a speaker's line in 8 of 40 short takes, here in none --- arch/fishomni/fishomni.cpp | 25 ++++++++++++++----------- docs/ARCHITECTURES.md | 30 +++++++++++++++++++++--------- docs/GUIDE.md | 9 +++++---- 3 files changed, 40 insertions(+), 24 deletions(-) diff --git a/arch/fishomni/fishomni.cpp b/arch/fishomni/fishomni.cpp index 8217af63..aec0d6e7 100644 --- a/arch/fishomni/fishomni.cpp +++ b/arch/fishomni/fishomni.cpp @@ -84,10 +84,13 @@ constexpr int64_t kCodes = 10, kVocab = 4096, kResVocab = 1024; constexpr int64_t kEos = 248046, kSemBegin = 248099, kSemEnd = 252194, kCand = kVocab + 1; /* The tower: four shared layers, then one a codebook after the first. */ constexpr int kShared = 4, kTower = kShared + (int)kCodes - 1; -/* fish-speech's server and SDK defaults (sampling.py), the technical report's evaluation - * settings: temperature 0.7, top-p 0.7, top-k 30, for the main token and every head alike. */ -constexpr int64_t kTopK = 30; -static const double kTemp = 0.7, kTopP = 0.7; +/* The draws: temperature 1.0 and top-p 0.9, the settings of Fish Audio's model card, for the main + * token and every head; the main token uncapped (256, cfg_topk_sample's widest) and each head at + * top-k 30, as SGLang-Omni draws them. fish-speech's server defaults (0.7, 0.7, 30 for both) make + * the model fall silent after a tag or a speaker's line and never come back: over 40 takes of + * four short scripts, 8 ran to their length in silence against none here (docs/ARCHITECTURES.md). */ +constexpr int64_t kMainTopK = 256, kHeadTopK = 30; +static const double kTemp = 1.0, kTopP = 0.9; /* The repetition-aware redraw, fixed by the training recipe (tower.py): when the first draw is * semantic and among the last 16 main tokens, a second draw at temperature 1, top-p 0.95, * top-k 30 is taken instead. */ @@ -717,7 +720,7 @@ static int declare_frame_head(RadBuilder* b, Model& m) { RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cand)), { m.b_plane }, { m.b_slog }); - m.op_samp = draw_op(b, S, kCand, kTopK, kTemp, kTopP, 0, m.b_slog, m.b_first); + m.op_samp = draw_op(b, S, kCand, kMainTopK, kTemp, kTopP, 0, m.b_slog, m.b_first); m.op_samp_ras = draw_op(b, S, kCand, kRasTopK, kRasTemp, kRasTopP, 1, m.b_slog, m.b_alt); /* The redraw: only a semantic first draw (candidates 1..4096), and only one the lane's last * 16 picks hold; the prompt's rows are text, so its window starts empty (op_rasinit). */ @@ -961,7 +964,7 @@ static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(L.w_head)), { m.b_tho }, { m.b_hlog }); - L.op_samp = draw_op(b, S, kVocab, kTopK, kTemp, kTopP, 2 + k, m.b_hlog, m.b_codes); + L.op_samp = draw_op(b, S, kVocab, kHeadTopK, kTemp, kTopP, 2 + k, m.b_hlog, m.b_codes); if (!L.w_head || !L.op_head || !L.op_samp) return RAD_E_INVAL; } } @@ -1374,11 +1377,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)m.moecfg.top_k, kTower, (long long)m.n_main, (long long)(m.n_main + kTower - 1), (long long)m.gt.n_head, (long long)m.gt.n_ff, (int)kCtLayers, (long long)m.lanes); - rad_note(b, "sampling: temperature %.2f, top-p %.2f, top-k %lld for the main token and every " - "head; a semantic first draw among the lane's last %lld picks is redrawn at " - "temperature %.2f, top-p %.2f, top-k %lld", - kTemp, kTopP, (long long)kTopK, (long long)kRasWin, kRasTemp, kRasTopP, - (long long)kRasTopK); + rad_note(b, "sampling: temperature %.2f, top-p %.2f for every draw, top-k %lld for the main " + "token and %lld for each head; a semantic first draw among the lane's last %lld " + "picks is redrawn at temperature %.2f, top-p %.2f, top-k %lld", + kTemp, kTopP, (long long)kMainTopK, (long long)kHeadTopK, (long long)kRasWin, + kRasTemp, kRasTopP, (long long)kRasTopK); return RAD_OK; } diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 4e23659c..0774c1d8 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -1340,9 +1340,9 @@ tower 13 layers bound as layers 40..52 of the backbone's full-attention KV g wqkv's rows [Q 4096 | G 4096 | K 512 | V 512], (1 + w) q/k norms, GPT-J rotary on 64 dims at 1e7, attention * sigmoid(gate), SwiGLU 6144), a final (1 + w) norm. The first shared layer also adds the input frame's codes 2..9, embedded and summed in f32 -sampling fish-speech's server defaults: temperature 0.7, top-p 0.7 over the whole candidate set, - then top-k 30, for the main token and every head; a semantic first draw among the - lane's last 16 picks is redrawn at 1.0 / 0.95 / 30 (`ras_pick`) +sampling temperature 1.0, top-p 0.9 over the whole candidate set, then the top-k: the main + token uncapped (256) and each head 30, as SGLang-Omni draws; a semantic first draw + among the lane's last 16 picks is redrawn at 1.0 / 0.95 / 30 (`ras_pick`) codec Fish S2's modified DAC decoder: ten raw codebook rows of 8 (one of 4096, nine of 1024, codes 1..9 clamped to 1023), each through its own weight-normed 1x1 projection to 1024 and summed; 8 layers of 1024 (16 heads of 64, GPT-J rotary on all 64 at theta 1e4, @@ -1386,7 +1386,8 @@ Traps (each still speaks, wrongly): - **The input is written as fish-speech's server writes it**: each speaker's turn `<|speaker:N|> ` and its text stripped, turns joined by a newline, untagged text speaker 0's. The same two turns joined by a space are spoken through far less often: for one two-line script, - one seed in six spoke both lines, against seven in ten with the newline. + at fish-speech's sampling, one seed in six spoke both lines, against seven in ten with the + newline. Against fish-speech's own PyTorch code (the CPU path: experts fp8, dequantised per forward, so W8A16 where radiance runs W8A8), teacher-forced with radiance's codes over a 34-row prompt and 80 @@ -1398,11 +1399,22 @@ over the 79 frames that are spoken. Through the codec, radiance's chunked bf16 d from the reference's whole-utterance bf16 decode of the same codes. Qwen3-ASR transcribes radiance's speech word for word. -The model's own failure is to stop after the first line of a script, or to fall silent until the -length runs out (vLLM-Omni's recipe and SGLang-Omni's notes describe it). Over 20 seeds of two -invented two-speaker lines, the second speaker was spoken in 14 and 17 of 20, and 2 and 3 takes ran -past 8 s; at a main top-k of 256 instead of 30 it was 14 and 15, with 5 long takes each, so the -reference's 30 stays. +The sampling is not fish-speech's server's (temperature 0.7, top-p 0.7, top-k 30 for every draw). +At those the model falls silent after a tag or a speaker's line and does not come back, the failure +vLLM-Omni's recipe and SGLang-Omni's notes describe; SGLang-Omni's comment puts it on the main +token's top-k cap, and the counts bear it out. Ten seeds each of four short scripts (an aside in +``, two two-speaker exchanges, a plain sentence), complete by Qwen3-ASR, and stuck (run to +the 400-frame limit in silence): + +| temperature, top-p, top-k (main / heads) | complete | stuck | +|---|---|---| +| 0.7, 0.7, 30 / 30 (fish-speech's server) | 28 / 40 | 8 / 40 | +| 1.0, 0.9, 30 / 30 (Fish Audio's model card) | 35 / 40 | 2 / 40 | +| 1.0, 0.9, 256 / 30 (SGLang-Omni) | 36 / 40 | 0 / 40 | + +The four misses at the last setting are a take that ended before the line after the whisper (twice), +a second speaker's single word, and one word the recogniser misheard; the whispered line itself is +spoken in all ten. A take still pauses a second or so around an aside. On two R9700s a sentence is made at 0.30 of the time it plays (3.67 s of speech in 1.08 s, 13.5 ms a frame with the codec), a paragraph at 0.29 (11.6 s in 3.34 s); a stream's first audio comes diff --git a/docs/GUIDE.md b/docs/GUIDE.md index bb85198e..b183f376 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2475,10 +2475,11 @@ curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json cloning a voice from a recording is not served yet. - **The length** is `duration` in seconds or `max_new_tokens` in frames (21.5 a second), up to 95 s; the model ends the speech at the end of the script. The prompt holds at most 2048 tokens. -- **Sampling** is fish-speech's server's: temperature 0.7, top-p 0.7, top-k 30, with its - repetition-aware redraw of the first code. A take sometimes stops after its first line or falls - silent until its length runs out (the model's own failure, more often with several speakers); - another `seed` usually speaks the whole script. +- **Sampling** is SGLang-Omni's: temperature 1.0 and top-p 0.9 (Fish Audio's model card), the + first code uncapped and each later code at top-k 30, with fish-speech's repetition-aware redraw + of the first code. fish-speech's server samples at 0.7, 0.7 and 30, where the model often falls + silent after a tag or a speaker's line and runs to its length (docs/ARCHITECTURES.md has the + counts). A take can still end before its last line; another `seed` usually speaks it all. - **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below. Speech is played sixteen frames (0.74 s) at a time as it is made. On two R9700s a sentence is made From 4e750fed018bee76cc4b0720b5aa1e7d8cec8d4e Mon Sep 17 00:00:00 2001 From: zivius Date: Wed, 21 Oct 2026 00:01:16 +0200 Subject: [PATCH 11/35] libref, libavx, libr4d: conv1d's stride and cu_div, and vq_encode -- a causal codec encoder's downsampling (the left pad the reach less the stride, every sequence a whole number of strides, the bounds read in samples at every rate) and one step of its residual quantiser, the code of greatest cosine and the residual it leaves (Fish Audio's codec encoding a reference) --- docs/OPS.md | 20 +++- libavx/avx_audio.cpp | 93 +++++++++++++++-- libavx/avx_cases.cpp | 17 +++ libavx/avx_check_hand.cpp | 16 +++ libavx/avx_isa.h | 1 + libavx/avx_registry.cpp | 12 ++- libr4d/r4d_audio.hip | 211 ++++++++++++++++++++++++++++++-------- libr4d/r4d_plugin.h | 1 + libr4d/r4d_rows.cpp | 22 +++- libr4d/r4d_selftest.cpp | 184 +++++++++++++++++++++++++++------ libref/ref_audio.cpp | 94 ++++++++++++++--- libref/ref_ops.h | 2 + libref/ref_registry.cpp | 13 ++- libref/ref_shapes.cpp | 28 ++++- tests/ref_test.cpp | 69 ++++++++++++- 15 files changed, 673 insertions(+), 110 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 911623b2..f072e385 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1167,12 +1167,13 @@ libref function says which (`libref/ref_audio.cpp`). | op | params | operands | |---|---|---| -| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? | +| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `cu_div`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? | | `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` | | `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? | | `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` | | `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | | `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` | +| `vq_encode` | `M`(range) `n` `dim` `bins` `dtype` | `x`:inout, `in_w`w, `in_b`w, `cb`w, `out_w`w, `out_b`w → `codes` | | `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout | | `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout | | `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` | @@ -1219,6 +1220,14 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a With `clamp` n > 0 a code above `n - 1` reads row `n - 1` (before `off0` and the codebook's offset; a negative code still reads nothing): a codec whose codebooks are smaller than the heads that write its codes, as Fish Audio's 1024-entry residual codebooks under 4096-way heads. +- `vq_encode`: one step of a residual vector quantiser with factorised, L2-normalised codes (DAC's, + as Fish Audio's codec encodes a reference): per row of `x` `[rows, n]`, `e = in_w x + in_b` + (`in_w` `[dim, n]`, a 1x1 convolution's weight); the code is the row of `cb` `[bins, dim]` of + greatest cosine with `e`, `(e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12))`, the lower index + on a tie (0 when no score is above -inf), written to `codes[i]` at the operand's own stride; then + `x -= out_w cb[code] + out_b` (`out_w` `[n, dim]`, the raw codebook row), rounded once into `x`. + f32 arithmetic. A chain of these over a codec's codebooks, each quantising what the last left, is + its residual quantiser. - `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`, when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes` @@ -1259,7 +1268,14 @@ input reads zero outside it. - `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding `dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output - clamp; a NaN stays NaN). f32 accumulation, one rounding. + clamp; a NaN stays NaN). f32 accumulation, one rounding. `stride` s > 1 (causal only, the reach + `dil (k - 1) + 1` at least s) pads `dil (k - 1) + 1 - s` on the left and keeps every s-th row: + output row `o` of a sequence reads input rows `o s - pad + t dil`, and sequence `e`'s rows + `[cu[e], cu[e+1])` become `[cu[e] / s, cu[e+1] / s)`, so every bound is a multiple of s; `res` + and `y` have the output's rows (a causal codec encoder's downsampling, as Fish Audio's). + `cu_div` reads the bounds in units that many input rows apart, as the other encoder ops do: + sequence `e` is input rows `[cu[e] / cu_div, cu[e+1] / cu_div)`, each bound a multiple of + `cu_div` times the stride, so one bounds array in samples serves every rate of an encoder. - `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even; 0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index e5ae6799..b59d4805 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -227,7 +227,10 @@ inline float sin_sq1(float v) { * k input rows' channel runs back to back, zeros outside its own sequence (padded on both sides, * or with `causal` on the left only). A band's patches are one gemm_nt_into call into f32 rows (the * bias added there); `res` and the tanh or the clamp to [-1, 1] are applied to the f32 rows, which - * are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. */ + * are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. With a + * `stride` (causal only) output row o's patch starts at input row o stride - pad, the pad the + * reach less the stride, and a sequence of L rows makes L / stride. `cu_div`: the bounds in units + * that many input rows apart, as libref reads them. */ AVX_KERNEL(conv1d) { if (!rad_args_have(a, 3) || a->n_t < 5) return RAD_E_INVAL; const RadTensor *X = &a->t[0], *W = &a->t[1], *cu = &a->t[2]; @@ -235,20 +238,26 @@ 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 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) + causal < 0 || causal > 1 || st < 1 || (st > 1 && (!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; - const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); - if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1) return RAD_E_SHAPE; + for (int64_t e = 0; 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; if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE; if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE; - const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2, KK = k * cin; + const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2, KK = k * cin; static thread_local std::vector wbuf, pbuf; static thread_local std::vector ybuf; @@ -264,8 +273,8 @@ AVX_KERNEL(conv1d) { 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. */ - const bool direct = k == 1 && X->rank == 2 && X->shape[1] == cin && X->stride[1] == 1 && - (X->dtype == RAD_BF16 || X->dtype == RAD_F32); + 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); if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64); ybuf.resize((size_t)(band * cout) + 16); @@ -282,10 +291,10 @@ 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); - const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1); + 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; for (int64_t t = 0; t < k; ++t) { - const int64_t ir = r + t * dil - pad; + const int64_t ir = r * st + t * dil - pad; patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16, pp + (size_t)(p * KK + t * cin) * ael); } @@ -757,6 +766,70 @@ AVX_KERNEL(rvq_embed) { return RAD_OK; } +/* ------------------------------------------------------------------ vq_encode */ +/* libref's step a row at a time: e as dim dot products over x's row, the codebook normalised once + * a launch (F.normalize's division) and scored against e normalised, ties to the lower index, the + * chosen raw row's out-projection subtracted and the row rounded once into x. */ +AVX_KERNEL(vq_encode) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3]; + const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6]; + const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0); + if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim || + numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n) + return RAD_E_SHAPE; + /* The weights dense in f32, held by this thread for the launch's parallel region. */ + auto dense = [](const RadTensor* t, int64_t m) { + std::vector v((size_t)m); + for (int64_t i = 0; i < m; ++i) v[(size_t)i] = ldt(t, i); + return v; + }; + const std::vector wi = dense(iw, dim * n), bi = dense(ib, dim); + const std::vector raw = dense(cb, bins * dim), wo = dense(ow, n * dim), bo = dense(ob, n); + std::vector cn((size_t)(bins * dim)); + for (int64_t c = 0; c < bins; ++c) { + const float* cr = raw.data() + c * dim; + float ss = 0.0f; + for (int64_t j = 0; j < dim; ++j) ss += cr[j] * cr[j]; + const float nrm = std::max(std::sqrt(ss), 1e-12f); + for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = cr[j] / nrm; + } + const float *Wi = wi.data(), *Bi = bi.data(), *Raw = raw.data(), *Cn = cn.data(); + const float *Wo = wo.data(), *Bo = bo.data(); + AVX_PARALLEL_FOR_IF(rows * (2 * n + bins) * dim >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n); + const float* xv = in_row(X, xb, n, scratch_f32((size_t)n + 16)); + float* e = scratch_f32_c((size_t)dim + 16); + float ss = 0.0f; + for (int64_t j = 0; j < dim; ++j) { + e[j] = dotf(Wi + j * n, xv, n) + Bi[j]; + ss += e[j] * e[j]; + } + const float nrm = std::max(std::sqrt(ss), 1e-12f); + for (int64_t j = 0; j < dim; ++j) e[j] /= nrm; + int64_t best = 0; + float bs = -INFINITY; + for (int64_t c = 0; c < bins; ++c) { + float s = 0.0f; + for (int64_t j = 0; j < dim; ++j) s += e[j] * Cn[c * dim + j]; + if (s > bs) { bs = s; best = c; } + } + st_int_dt(codes->dtype, codes->data, offlin(codes, r), best); + float* y = scratch_f32_b((size_t)n + 16); + const float* row = Raw + best * dim; + for (int64_t d = 0; d < n; ++d) { + float q = 0.0f; + for (int64_t j = 0; j < dim; ++j) q += Wo[d * dim + j] * row[j]; + y[d] = xv[d] - (q + Bo[d]); + } + out_row(X, xb, n, y); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ frame_mix_store */ /* m = bf16(bf16(sum_l w_l h_l) * bf16(scale)), w = bf16(softmax(bf16(logits))) in libref's double * arithmetic, the planes summed in order with each product rounded before its add (`keep`). Entries diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 315f00eb..82717a48 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -954,6 +954,13 @@ std::vector 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) }); + /* 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 }) + add("conv1d", { HI("M", 64), HI("cin", 20), HI("cout", 13), HI("k", 2 * s), + HI("dil", 1), HI("causal", 1), HI("stride", s), HS("dtype", dt) }); + add("conv1d", { HI("M", 64), HI("cin", 24), HI("cout", 16), HI("k", 2), HI("dil", 1), + HI("causal", 1), HI("stride", 2), HS("dtype", dt) }); for (int s : { 2, 4, 8 }) add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s), HS("dtype", dt) }); @@ -1050,6 +1057,16 @@ std::vector build_cases() { add("ras_pick", { HI("M", 4), HI("win", 16), HI("lo", 1), HI("hi", 9), HI("rep", 1) }); add("ras_pick", { HI("M", 2), HI("win", 4), HI("lo", 0), HI("hi", 12), HI("rep", 2), HI("clear", 1) }); + /* A codec encoder's residual quantiser step: DAC's eight-wide codes over a semantic codebook + * and a residual one, both dtypes; a dimension that is no vector's width. */ + for (const char* dt : { "f32", "bf16" }) { + add("vq_encode", { HI("M", 7), HI("n", 64), HI("dim", 8), HI("bins", 4096), + HS("dtype", dt) }); + add("vq_encode", { HI("M", 5), HI("n", 128), HI("dim", 8), HI("bins", 1024), + HS("dtype", dt) }); + } + add("vq_encode", { HI("M", 3), HI("n", 40), HI("dim", 5), HI("bins", 33), + HS("dtype", "f32") }); add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2), HI("skip", 0) }); add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1), diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index dc50cbc5..01c3e195 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -4010,6 +4010,22 @@ void audio_cases(std::vector& hs) { .pi("causal", 1).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. */ + const int64_t cin = 12, cout = 9, M = 8 * s; + Hand h(("stride " + std::to_string(s) + ", bounds in units of 8 rows" + sfx).c_str(), + "conv1d", norm_tol); + h.dense(dt, { M, cin }, hfill(330 + s)) + .dense(dt, { cout, cin, 2 * s }, hfill(334, 0.3f)) + .idx({ (int32_t)(16 * s), (int32_t)(48 * s), (int32_t)(64 * s) }) + .none() + .dense(dt, { M / s, cout }, hfill(335), true) + .dense(dt, { cout }, hfill(336, 0.5f)) + .pi("M", M).pi("cin", cin).pi("cout", cout).pi("k", 2 * s).pi("dil", 1) + .pi("causal", 1).pi("stride", s).pi("cu_div", 8).ps("dtype", dn); + hs.push_back(std::move(h)); + } for (const int64_t s : { 5, 3 }) { /* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows * from row 1. */ diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 09b53658..a2feb9bf 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -135,6 +135,7 @@ int avx_par_force(int threads); X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \ X(win_finish) X(chan_split) X(interleave2) X(iota) \ X(cu_repeat) X(snake_aa) X(int_affine) X(ras_pick) \ + X(vq_encode) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index cc0eb1e9..ae4cedf6 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -683,7 +683,8 @@ 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("causal"), P_INTO("stride"), + P_INTO("cu_div") }; static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"), OUT("y"), WGT_O("b") }; static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"), @@ -707,6 +708,10 @@ static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_ P_INT("vocab"), P_INT("off0"), P_F64("scale"), P_STR("dtype"), P_INTO("round"), P_INTO("clamp") }; static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; +static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"), + P_STR("dtype") }; +static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"), + WGT("out_w"), WGT("out_b"), OUT("codes") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), @@ -1186,6 +1191,9 @@ static const RadOpSchema kSchemas[] = { "libref's." }, { "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed), "a frame's embedding from code-major residual codes, libref's roundings (`round` 1: one)." }, +{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode), + "one residual vector quantiser step: the code of greatest cosine with in_w x + in_b, then " + "x -= out_w cb[code] + out_b; libref's arithmetic in another summation order." }, { "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), "a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." }, { "end_status", ARR(pEndStatus), ARR(oEndStatus), @@ -1718,6 +1726,8 @@ SIMPLE("avx_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick L(cfg_topk_sample)), SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes", DT_FLOAT, L(rvq_embed)), +SIMPLE("avx_vq_encode", "vq_encode", "elem", + "a residual quantiser's step: the nearest code by cosine", DT_FLOAT, L(vq_encode)), SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)), SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 0d4ecdf5..ca9c65b8 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -56,7 +56,7 @@ __device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) { // ---------------------------------------------------------------------------- conv1d // An implicit GEMM, r4d_gen.hip's conv_igemm_kernel cut to one dimension: y[row][cout] = sum -// over (tap, cin) of x[row + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored +// over (tap, cin) of x[row * stride + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored // tap-major (r4d_layout.cpp relayouts PyTorch's [cout][cin][k] at load), so a 64-wide K tile is // eight 16-byte reads of input rows. A chunk outside its row's sequence reads zeros, which is the // per-sequence padding. Eight waves, BP rows x BC output channels a block, the next K tile's @@ -77,7 +77,8 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res, const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end, - int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, + int res_ld, int act) { constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16; constexpr int CPR = C1_BK / 8; constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256; @@ -99,9 +100,9 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel( const int m = p0 + r; a_ok[i] = m < r_end; a_row[i] = a_ok[i] ? m : r_beg; - const int sq = seq_of(cu, n_seq, a_row[i]); - a_s0[i] = cu[sq]; - a_s1[i] = cu[sq + 1]; + const int sq = seq_of(cu, n_seq, a_row[i] * stride * cdiv); + a_s0[i] = cu[sq] / cdiv; + a_s1[i] = cu[sq + 1] / cdiv; a_t[i] = e / cin; a_ci[i] = e % cin; adst[i] = sA + r * C1_PITCH + e; @@ -122,7 +123,7 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel( const r4d_u32x4 zero = {0u, 0u, 0u, 0u}; auto loadA = [&](int i) -> r4d_u32x4 { if (!a_ok[i] || a_t[i] >= k) return zero; - const int ir = a_row[i] + a_t[i] * dil - pad; + const int ir = a_row[i] * stride + a_t[i] * dil - pad; if (ir < a_s0[i] || ir >= a_s1[i]) return zero; return *(const r4d_u32x4*)(x + (size_t)ir * x_ld + a_ci[i]); }; @@ -214,17 +215,18 @@ __global__ __launch_bounds__(kT) void conv1d_direct_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res, const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end, - int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, + int res_ld, int act) { const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; const int64_t total = (int64_t)(r_end - r_beg) * cout; if (t >= total) return; const int co = (int)(t % cout); const int row = r_beg + (int)(t / cout); - const int sq = seq_of(cu, n_seq, row); - const int s0 = cu[sq], s1 = cu[sq + 1]; + const int sq = seq_of(cu, n_seq, row * stride * cdiv); + const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv; float acc = 0.0f; for (int kk = 0; kk < k; ++kk) { - const int ir = row + kk * dil - pad; + const int ir = row * stride + kk * dil - pad; if (ir < s0 || ir >= s1) continue; const uint16_t* xp = x + (size_t)ir * x_ld; const uint16_t* wp = w + ((size_t)co * k + kk) * cin; @@ -384,14 +386,14 @@ __global__ __launch_bounds__(256) void conv_t1d_kernel( // the output channels, its K the (tap, channel) pairs, channel innermost. A thread stages one K // column a slab and steps it sixteen at a time, so no K index is divided after the first. -// conv1d's A: output row m's tap t reads input row m + t dil - pad of m's own sequence, zero -// outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an address -// clamped into x's first `r_end` rows and the zero selected after it. +// conv1d's A: output row m's tap t reads input row m stride + t dil - pad of m's own sequence, +// zero outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an +// address clamped into x's first `r_end` stride rows and the zero selected after it. template struct Conv1dRows { const float* x; const int* cu; - int n_seq, r_end, cin, k, dil, pad, x_ld; + int n_seq, r_end, cin, k, dil, pad, x_ld, stride, cdiv; int row[CNT], s0[CNT], s1[CNT]; int t = 0, ci = 0; __device__ void init(int first_row, int kk) { @@ -399,9 +401,9 @@ struct Conv1dRows { for (int j = 0; j < CNT; ++j) { const int m = first_row + 16 * j; row[j] = m < r_end ? m : -1; - const int sq = seq_of(cu, n_seq, m < r_end ? m : r_end - 1); - s0[j] = cu[sq]; - s1[j] = cu[sq + 1]; + const int sq = seq_of(cu, n_seq, (m < r_end ? m : r_end - 1) * stride * cdiv); + s0[j] = cu[sq] / cdiv; + s1[j] = cu[sq + 1] / cdiv; } t = kk / cin; ci = kk % cin; @@ -409,9 +411,10 @@ struct Conv1dRows { __device__ void fetch(float (&v)[CNT]) const { #pragma unroll for (int j = 0; j < CNT; ++j) { - const int ir = row[j] + t * dil - pad; + const int ir = row[j] * stride + t * dil - pad; const bool live = row[j] >= 0 && t < k && ir >= s0[j] && ir < s1[j]; - const int irc = ir < 0 ? 0 : (ir >= r_end ? r_end - 1 : ir); + const int x_rows = r_end * stride; + const int irc = ir < 0 ? 0 : (ir >= x_rows ? x_rows - 1 : ir); const float xv = x[(uint32_t)irc * (uint32_t)x_ld + (uint32_t)ci]; v[j] = live ? xv : 0.0f; } @@ -428,12 +431,13 @@ template __global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel( const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias, const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin, - int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld, + int act) { constexpr int TM = 8, BM = 16 * TM, BN = 16 * TN; const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4; const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; const int K = k * cin; - Conv1dRows la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld }; + Conv1dRows la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld, stride, cdiv }; r4d_f32::RowsLoader lw{ w, K, cout, K }; la.init(m0 + ty, tx); lw.init(n0 + ty, tx); @@ -458,16 +462,17 @@ __global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel( __global__ __launch_bounds__(kT) void conv1d_f32_direct_kernel( const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias, const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin, - int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) { + int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld, + int act) { const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; if (t >= (int64_t)rows * cout) return; const int co = (int)(t % cout); const int row = (int)(t / cout); - const int sq = seq_of(cu, n_seq, row); - const int s0 = cu[sq], s1 = cu[sq + 1]; + const int sq = seq_of(cu, n_seq, row * stride * cdiv); + const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv; float acc = 0.0f; for (int kk = 0; kk < k; ++kk) { - const int ir = row + kk * dil - pad; + const int ir = row * stride + kk * dil - pad; if (ir < s0 || ir >= s1) continue; const float* xp = x + (size_t)ir * x_ld; const float* wp = w + ((size_t)co * k + kk) * cin; @@ -806,6 +811,86 @@ __global__ __launch_bounds__(kT) void rvq_embed_kernel( } } +// One residual quantiser step (DAC's VectorQuantize), a workgroup a row of x. e = in_w x + in_b, +// each of its `dim` sums split over the workgroup and reduced through LDS; each thread then scores +// a strided run of the codebook against e normalised, every row normalised as it is read +// (F.normalize's division), and the workgroup's argmax keeps the lower index on a tie; last the +// chosen raw row's out-projection leaves x's row, rounded once. libref's arithmetic in another +// summation order. +constexpr int kVqMaxDim = 32; + +__global__ __launch_bounds__(kT) void vq_encode_kernel( + void* __restrict__ x, int x_f32, int x_ld, const void* __restrict__ iw, int iw_f32, + const void* __restrict__ ib, int ib_f32, const void* __restrict__ cb, int cb_f32, + const void* __restrict__ ow, int ow_f32, const void* __restrict__ ob, int ob_f32, + int* __restrict__ codes, int64_t code_st, int n, int dim, int bins) { + __shared__ float part[kT / 32][kVqMaxDim]; + __shared__ float e[kVqMaxDim], eh[kVqMaxDim]; + __shared__ float wbest[kT / 32]; + __shared__ int wcode[kT / 32]; + const int tid = threadIdx.x, wv = tid >> 5, ln = tid & 31; + const size_t xb = (size_t)blockIdx.x * x_ld; + auto ldx = [&](int d) { + return x_f32 ? ((const float*)x)[xb + d] : bf2f(((const uint16_t*)x)[xb + d]); + }; + for (int j = 0; j < dim; ++j) { + float acc = 0.0f; + for (int d = tid; d < n; d += kT) acc += ldtab(iw, iw_f32, (size_t)j * n + d) * ldx(d); + #pragma unroll + for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor(acc, o, 32); + if (ln == 0) part[wv][j] = acc; + } + __syncthreads(); + if (tid < dim) { + float acc = 0.0f; + for (int w = 0; w < kT / 32; ++w) acc += part[w][tid]; + e[tid] = acc + ldtab(ib, ib_f32, (size_t)tid); + } + __syncthreads(); + if (tid < dim) { + float ss = 0.0f; + for (int j = 0; j < dim; ++j) ss += e[j] * e[j]; + eh[tid] = e[tid] / fmaxf(sqrtf(ss), 1e-12f); + } + __syncthreads(); + // Each thread's best over its rows, ascending, so its first maximum is kept; INT_MAX none. + float bs = -INFINITY; + int bc = 0x7fffffff; + for (int c = tid; c < bins; c += kT) { + float ss = 0.0f; + for (int j = 0; j < dim; ++j) { + const float v = ldtab(cb, cb_f32, (size_t)c * dim + j); + ss += v * v; + } + const float nrm = fmaxf(sqrtf(ss), 1e-12f); + float dot = 0.0f; + for (int j = 0; j < dim; ++j) dot += eh[j] * (ldtab(cb, cb_f32, (size_t)c * dim + j) / nrm); + if (dot > bs) { bs = dot; bc = c; } + } + #pragma unroll + for (int o = 16; o > 0; o >>= 1) { + const float os = __shfl_xor(bs, o, 32); + const int oc = __shfl_xor(bc, o, 32); + if (os > bs || (os == bs && oc < bc)) { bs = os; bc = oc; } + } + if (ln == 0) { wbest[wv] = bs; wcode[wv] = bc; } + __syncthreads(); + float fs = wbest[0]; + int fc = wcode[0]; + for (int w = 1; w < kT / 32; ++w) + if (wbest[w] > fs || (wbest[w] == fs && wcode[w] < fc)) { fs = wbest[w]; fc = wcode[w]; } + const int code = fc == 0x7fffffff ? 0 : fc; // no score above -inf: code 0, as libref + if (tid == 0) codes[(size_t)blockIdx.x * code_st] = code; + for (int d = tid; d < n; d += kT) { + float q = 0.0f; + for (int j = 0; j < dim; ++j) + q += ldtab(ow, ow_f32, (size_t)d * dim + j) * ldtab(cb, cb_f32, (size_t)code * dim + j); + const float v = ldx(d) - (q + ldtab(ob, ob_f32, (size_t)d)); + if (x_f32) ((float*)x)[xb + d] = v; + else ((uint16_t*)x)[xb + d] = f32_to_bf16(v); + } +} + // dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]; a thread a (lane, code). A lane // outside `status`, or a frame past `stride` or a lane past `dst`, stores nothing (libref refuses // the call). @@ -1126,24 +1211,26 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) { return R4D_NO(RAD_E_DTYPE); const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1); - const long long causal = r4d_geti_or(a, "causal", 0); + const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1); + const long long cd = r4d_geti_or(a, "cu_div", 1); const int act = conv1d_act(r4d_gets(a, "act")); if (act < 0) return R4D_NO(RAD_E_INVAL); if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 || - causal > 1) + causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1) return R4D_NO(RAD_E_SHAPE); long long rx = 0, ry = 0, rr = 0; const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0; if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); const long long n_seq = r4d_numel(cu) - 1; - if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k || - (b && r4d_numel(b) < cout)) + if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) || + r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout)) return R4D_NO(RAD_E_SHAPE); const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr; - /* Both kernels read input row row + tap * dil - pad: half the reach a side, or all of it on - * the left for the causal form. */ - const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2); + /* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, or for + * the causal form all of it on the left less the stride (the sequences' bounds whole + * strides, as the op requires). */ + const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2); const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 && ((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0; const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr; @@ -1156,8 +1243,8 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) { dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data, bp, rp, (const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry, - (int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, - (int)rl, act); + (int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, + (int)xl, (int)yl, (int)rl, act); } else { constexpr int TP = 4, TC = 1, BP = 128, BC = 64; hipLaunchKernelGGL((conv1d_igemm_kernel), @@ -1165,15 +1252,15 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) { dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data, bp, rp, (const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry, - (int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, - (int)rl, act); + (int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, + (int)xl, (int)yl, (int)rl, act); } } else { hipLaunchKernelGGL(conv1d_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0, (hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data, bp, rp, (const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad, - (int)xl, (int)yl, (int)rl, act); + (int)st, (int)cd, (int)xl, (int)yl, (int)rl, act); } return st_of(hipGetLastError()); } @@ -1237,11 +1324,12 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { if (!r4d_contig(w) || (b && !r4d_contig(b)) || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0); const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1); - const long long causal = r4d_geti_or(a, "causal", 0); + const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1); + const long long cd = r4d_geti_or(a, "cu_div", 1); const int act = conv1d_act(r4d_gets(a, "act")); if (act < 0) return R4D_NO(RAD_E_INVAL); if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 || - causal > 1) + causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1) return R4D_NO(RAD_E_SHAPE); long long rx = 0, ry = 0, rr = 0; const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry); @@ -1249,18 +1337,19 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); const long long n_seq = r4d_numel(cu) - 1; /* The tile's loaders index x and w with 32-bit element offsets. */ - if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k || - (b && r4d_numel(b) < cout) || ry > 0x7fffffffll || (ry + 127) / 128 > 65535 || - ry * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32)) + if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) || + r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout) || ry > 0x7fffffffll || + (ry + 127) / 128 > 65535 || ry * st * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32)) return R4D_NO(RAD_E_SHAPE); - const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2); + const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2); const float* bp = b ? (const float*)b->data : nullptr; const float* rp = res ? (const float*)res->data : nullptr; if (cout < 16) { hipLaunchKernelGGL(conv1d_f32_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0, (hipStream_t)s, (const float*)x->data, (const float*)w->data, bp, rp, (const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, - (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act); + (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl, + (int)rl, act); return st_of(hipGetLastError()); } const int tn = cout > 64 ? 8 : cout > 32 ? 4 : 2; @@ -1269,7 +1358,8 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { hipLaunchKernelGGL((conv1d_f32_kernel), grid, dim3(r4d_f32::kThr), 0, (hipStream_t)s, \ (const float*)x->data, (const float*)w->data, bp, rp, \ (const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, \ - (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act) + (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl, \ + (int)rl, act) if (tn == 8) C1F(8); else if (tn == 4) C1F(4); else C1F(2); @@ -1433,6 +1523,37 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_vq_encode(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *iw = r4d_opt(a, 1), *ib = r4d_opt(a, 2); + const RadTensor *cb = r4d_opt(a, 3), *ow = r4d_opt(a, 4), *ob = r4d_opt(a, 5); + const RadTensor* codes = r4d_opt(a, 6); + if (!x || !iw || !ib || !cb || !ow || !ob || !codes) return R4D_NO(RAD_E_INVAL); + auto bf_or_f32 = [](const RadTensor* t) { return t->dtype == RAD_BF16 || t->dtype == RAD_F32; }; + if (!is_i32(codes) || !bf_or_f32(x) || !bf_or_f32(iw) || !bf_or_f32(ib) || !bf_or_f32(cb) || + !bf_or_f32(ow) || !bf_or_f32(ob)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), dim = r4d_geti_or(a, "dim", 0); + const long long bins = r4d_geti_or(a, "bins", 0); + if (n <= 0 || dim <= 0 || dim > kVqMaxDim || bins <= 0) return R4D_NO(RAD_E_SHAPE); + long long rx = 0; + const long long xl = r4d_rows_pitch(x, n, &rx); + if (xl < 0 || !r4d_contig(iw) || !r4d_contig(ib) || !r4d_contig(cb) || !r4d_contig(ow) || + !r4d_contig(ob)) + return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || r4d_numel(codes) < rx || r4d_numel(iw) < dim * n || r4d_numel(ib) < dim || + r4d_numel(cb) < bins * dim || r4d_numel(ow) < n * dim || r4d_numel(ob) < n || + rx > 0x7fffffffll) + return R4D_NO(RAD_E_SHAPE); + /* A code at the operand's own stride: a row of a code-major plane, or a column of one. */ + const long long cs = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1; + auto f32 = [](const RadTensor* t) { return t->dtype == RAD_F32 ? 1 : 0; }; + hipLaunchKernelGGL(vq_encode_kernel, dim3((unsigned)rx), dim3(kT), 0, (hipStream_t)s, x->data, + f32(x), (int)xl, iw->data, f32(iw), ib->data, f32(ib), cb->data, f32(cb), + ow->data, f32(ow), ob->data, f32(ob), (int*)codes->data, (int64_t)cs, + (int)n, (int)dim, (int)bins); + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_frame_mix_store(const RadArgs* a, RadStream s) { const RadTensor *hid = r4d_opt(a, 0), *lw = r4d_opt(a, 1), *sc = r4d_opt(a, 2); const RadTensor *lane = r4d_opt(a, 3), *fr = r4d_opt(a, 4), *st = r4d_opt(a, 5); diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index fcb48fb1..d106e1cc 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -200,6 +200,7 @@ int r4d_rad_conv_t1d_f32 (const RadArgs*, RadStream); int r4d_rad_snake (const RadArgs*, RadStream); int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream); int r4d_rad_rvq_embed (const RadArgs*, RadStream); +int r4d_rad_vq_encode (const RadArgs*, RadStream); int r4d_rad_frame_mix_store (const RadArgs*, RadStream); int r4d_rad_end_status (const RadArgs*, RadStream); int r4d_rad_ras_pick (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 1ff67849..f6dc9b7e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2372,7 +2372,8 @@ static const RadOperandSpec oAttnPS[] = { /* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("dil"), P_STRO("act"), P_STR("dtype"), - P_INTO("causal") }; + P_INTO("causal"), P_INTO("stride"), + P_INTO("cu_div") }; static const RadOperandSpec oConv1d[] = { { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, { "b", RAD_OPD_WEIGHT, 1 }, @@ -2405,6 +2406,13 @@ static const RadOperandSpec oRvqEmbed[] = { { "codes", RAD_OPD_IN, 0 }, { "t0", RAD_OPD_WEIGHT, 0 }, { "t1", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"), + P_STR("dtype") }; +static const RadOperandSpec oVqEncode[] = { + { "x", RAD_OPD_INOUT, 0 }, { "in_w", RAD_OPD_WEIGHT, 0 }, { "in_b", RAD_OPD_WEIGHT, 0 }, + { "cb", RAD_OPD_WEIGHT, 0 }, { "out_w", RAD_OPD_WEIGHT, 0 }, { "out_b", RAD_OPD_WEIGHT, 0 }, + { "codes", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; static const RadOperandSpec oFrameMix[] = { @@ -3338,6 +3346,9 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rvq_embed", pRvqEmbed, oRvqEmbed, "a frame's embedding from code-major residual codes, the first codebook's table and the " "others' stacked one, times `scale`; `round` 1 rounds the f32 sum once."), + SCHEMA("vq_encode", pVqEncode, oVqEncode, + "one residual vector quantiser step: the code of greatest cosine with in_w x + in_b " + "(the lower index on a tie), then x -= out_w cb[code] + out_b."), SCHEMA("frame_mix_store", pFrameMix, oFrameMix, "a frame's conditioning row (softmax-weighted planes times scale) into its lane."), SCHEMA("end_status", pEndStatus, oEndStatus, @@ -4825,6 +4836,8 @@ static const RadConstraint cRmsMod[] = { C_IN("dtype", "bf16"), C_DIV("n", 8), C static const RadConstraint cRmsModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192), C_EQ("group", 128) }; static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") }; +/* vq_encode: e's sums staged in LDS, a codebook dimension of 32 at most. */ +static const RadConstraint cVqEncode[] = { C_IN("dtype", "bf16 f32"), C_LE("dim", 32) }; static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64) }; static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") }; static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) }; @@ -8289,6 +8302,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenBf16), NOTUNE, nullptr, nullptr, r4d_rad_rvq_embed }, +{ "vq_encode", "vq_encode", "elem", + "a residual quantiser's step: the nearest code by cosine", "a workgroup a row, dim <= 32", + "bf16 or f32 rows and weights, f32 arithmetic, the row rounded once", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cVqEncode), NOTUNE, + nullptr, nullptr, r4d_rad_vq_encode }, + { "frame_mix_store_bf16", "frame_mix_store", "elem", "a frame's conditioning row into its lane", "a workgroup a lane, L <= 16", "bf16 planes and rows, f32 logits and scale", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 5371652b..f7f852fd 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -5607,18 +5607,28 @@ int64_t seq_of(const std::vector& cu, int64_t r) { return s; } -/* conv1d: the causal form beside the symmetric one, on the tiled and the direct kernels. */ +/* conv1d: the causal form beside the symmetric one, on the tiled and the direct kernels; strided + * causal forms (a codec encoder's downsampling, kernels of two strides and of one) over sequences + * of whole strides, the bounds also in units of 8 rows (cu_div, an encoder's samples). */ void conv1d_cases(const Plugin& pl) { const RadKernelInfo* r = find(pl, "conv1d_bf16"); if (!r) { ok("conv1d_bf16", false, "row absent"); return; } - struct C { int64_t cin, cout, k, dil; int causal, extras; }; - for (const C& c : { C{ 16, 32, 3, 2, 0, 0 }, C{ 16, 32, 3, 2, 1, 1 }, C{ 16, 128, 4, 1, 1, 0 }, - C{ 6, 3, 7, 3, 1, 1 }, C{ 6, 3, 2, 1, 1, 0 } }) { - const std::vector cu = { 0, 13, 30 }; - const int64_t M = 30; + struct C { int64_t cin, cout, k, dil; int causal, extras; int64_t st, cd = 1; }; + for (const C& c : { C{ 16, 32, 3, 2, 0, 0, 1 }, C{ 16, 32, 3, 2, 1, 1, 1 }, + C{ 16, 128, 4, 1, 1, 0, 1 }, C{ 6, 3, 7, 3, 1, 1, 1 }, + C{ 6, 3, 2, 1, 1, 0, 1 }, C{ 16, 32, 4, 1, 1, 0, 2 }, + C{ 16, 128, 16, 1, 1, 1, 8 }, C{ 6, 3, 8, 1, 1, 1, 4 }, + C{ 16, 32, 2, 1, 1, 0, 2 }, C{ 16, 64, 4, 1, 1, 1, 2, 8 }, + C{ 6, 3, 8, 1, 1, 0, 4, 8 } }) { + /* Bounds of whole strides: 13 and 30 rounded up to the stride; the op reads them times + * cu_div. */ + const int64_t s1 = (13 + c.st - 1) / c.st * c.st, s2 = (30 + c.st - 1) / c.st * c.st; + const std::vector cu = { 0, (int32_t)s1, (int32_t)s2 }; + const std::vector cu_op = { 0, (int32_t)(s1 * c.cd), (int32_t)(s2 * c.cd) }; + const int64_t M = s2, MO = M / c.st; std::vector x = randv((size_t)(M * c.cin), 1.0f); std::vector w = randv((size_t)(c.cout * c.cin * c.k), 0.3f); - std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f); + std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(MO * c.cout), 0.5f); void* dx = up_bf16(x); void* db = up_bf16(b); void* dres = up_bf16(res); @@ -5626,27 +5636,31 @@ void conv1d_cases(const Plugin& pl) { std::vector ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout), PI("k", c.k), PI("dil", c.dil), PS("act", c.extras ? "tanh" : "none"), PS("dtype", "bf16"), PI("causal", c.causal) }; - const std::string nm = fmt("conv1d_bf16 cin %lld cout %lld k %lld dil %lld causal %d%s", + if (c.st > 1) ps.push_back(PI("stride", c.st)); + if (c.cd > 1) ps.push_back(PI("cu_div", c.cd)); + const std::string nm = fmt("conv1d_bf16 cin %lld cout %lld k %lld dil %lld causal %d " + "stride %lld cu_div %lld%s", (long long)c.cin, (long long)c.cout, (long long)c.k, - (long long)c.dil, c.causal, c.extras ? " +bias+res+tanh" : ""); + (long long)c.dil, c.causal, (long long)c.st, (long long)c.cd, + c.extras ? " +bias+res+tanh" : ""); void* dw = stored_weight(r, ps, w, c.cout, c.cin * c.k, nm.c_str()); - void* dcu = up_i32(cu); - void* dy = dalloc((size_t)(M * c.cout) * 2); + void* dcu = up_i32(cu_op); + void* dy = dalloc((size_t)(MO * c.cout) * 2); if (!dw) continue; - RadTensor tres = T(dres, RAD_BF16, { M, c.cout }), tb = T(db, RAD_BF16, { c.cout }); + RadTensor tres = T(dres, RAD_BF16, { MO, c.cout }), tb = T(db, RAD_BF16, { c.cout }); if (!c.extras) { absent(tres); absent(tb); } const int rc = launch(r, { T(dx, RAD_BF16, { M, c.cin }), T(dw, RAD_BF16, { c.cout, c.cin, c.k }), - T(dcu, RAD_I32, { 3 }), tres, T(dy, RAD_BF16, { M, c.cout }), tb }, + T(dcu, RAD_I32, { 3 }), tres, T(dy, RAD_BF16, { MO, c.cout }), tb }, ps); if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } - const int64_t pad = c.causal ? c.dil * (c.k - 1) : c.dil * (c.k - 1) / 2; - std::vector want((size_t)(M * c.cout)); - for (int64_t row = 0; row < M; ++row) { - const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; + const int64_t pad = c.causal ? c.dil * (c.k - 1) + 1 - c.st : c.dil * (c.k - 1) / 2; + std::vector want((size_t)(MO * c.cout)); + for (int64_t row = 0; row < MO; ++row) { + const int64_t e = seq_of(cu, row * c.st), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; for (int64_t co = 0; co < c.cout; ++co) { float acc = 0.0f; for (int64_t kk = 0; kk < c.k; ++kk) { - const int64_t ir = row + kk * c.dil - pad; + const int64_t ir = row * c.st + kk * c.dil - pad; if (ir < s0 || ir >= s1) continue; for (int64_t ci = 0; ci < c.cin; ++ci) acc += w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)]; @@ -6081,6 +6095,104 @@ void rvq_embed_cases(const Plugin& pl) { } } +/* vq_encode at Fish Audio's codec geometry (n 1024, codes of dimension 8, a semantic codebook of + * 4096 and a residual one of 1024) and an odd one, bf16 and f32 rows, f32 and bf16 weights, the + * codes a dense row and a strided column: each code against the host's cosine argmax in double (a + * pick within 1e-5 of the best score is a near tie, not a miss), the row after against + * x - out_w cb[code] - out_b for the code the kernel took. */ +void vq_encode_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "vq_encode"); + if (!r) { ok("vq_encode", false, "row absent"); return; } + struct C { int64_t n, dim, bins, M; bool f32x, f32w; int64_t cst; }; + for (const C& c : { C{ 1024, 8, 4096, 37, false, true, 1 }, C{ 1024, 8, 1024, 37, false, true, 1 }, + C{ 1024, 8, 1024, 20, true, true, 3 }, C{ 1024, 8, 4096, 9, false, false, 1 }, + C{ 200, 5, 300, 11, true, false, 2 } }) { + const int64_t n = c.n, dim = c.dim, bins = c.bins, M = c.M; + std::vector x = randv((size_t)(M * n), 1.0f); + std::vector iw = randv((size_t)(dim * n), 1.0f / std::sqrt((float)n)); + std::vector ib = randv((size_t)dim, 0.1f), cb = randv((size_t)(bins * dim), 1.0f); + std::vector ow = randv((size_t)(n * dim), 0.3f), ob = randv((size_t)n, 0.1f); + /* A bf16 upload rounds the host copy to what the device holds. */ + const uint32_t wdt = c.f32w ? RAD_F32 : RAD_BF16, xdt = c.f32x ? RAD_F32 : RAD_BF16; + auto upw = [&](std::vector& w) { return c.f32w ? up_f32(w) : up_bf16(w); }; + void* dx = c.f32x ? up_f32(x) : up_bf16(x); + const std::vector plane((size_t)(M * c.cst), -7); + void* dc = up_i32(plane); + RadTensor tc = T(dc, RAD_I32, { M }); + tc.stride[0] = c.cst; + std::vector ps = { PI("M", M), PI("n", n), PI("dim", dim), PI("bins", bins), + PS("dtype", c.f32x ? "f32" : "bf16") }; + const std::string nm = fmt("vq_encode n %lld dim %lld bins %lld, %s rows, %s weights, " + "code stride %lld", (long long)n, (long long)dim, + (long long)bins, c.f32x ? "f32" : "bf16", + c.f32w ? "f32" : "bf16", (long long)c.cst); + const int rc = launch(r, { T(dx, xdt, { M, n }), T(upw(iw), wdt, { dim, n }), + T(upw(ib), wdt, { dim }), T(upw(cb), wdt, { bins, dim }), + T(upw(ow), wdt, { n, dim }), T(upw(ob), wdt, { n }), tc }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector got = down_i32(dc, plane.size()); + const std::vector gx = c.f32x ? down_f32(dx, x.size()) : down_bf16(dx, x.size()); + int64_t miss = 0, near = 0, gaps = 0; + std::vector want = x; + for (int64_t i = 0; i < M; ++i) { + std::vector e((size_t)dim); + double ss = 0; + for (int64_t j = 0; j < dim; ++j) { + double acc = ib[(size_t)j]; + for (int64_t d = 0; d < n; ++d) + acc += (double)iw[(size_t)(j * n + d)] * x[(size_t)(i * n + d)]; + e[(size_t)j] = acc; + ss += acc * acc; + } + const double en = std::max(std::sqrt(ss), 1e-12); + auto score = [&](int64_t k) { + const float* row = cb.data() + k * dim; + double cs = 0, dot = 0; + for (int64_t j = 0; j < dim; ++j) cs += (double)row[j] * row[j]; + const double cn = std::max(std::sqrt(cs), 1e-12); + for (int64_t j = 0; j < dim; ++j) dot += e[(size_t)j] / en * (row[j] / cn); + return dot; + }; + int64_t best = 0; + double bs = -1e300; + for (int64_t k = 0; k < bins; ++k) { + const double s = score(k); + if (s > bs) { bs = s; best = k; } + } + for (int64_t g = 1; g < c.cst; ++g) + if (got[(size_t)(i * c.cst + g)] != -7) ++gaps; + const int64_t k = got[(size_t)(i * c.cst)]; + if (k < 0 || k >= bins) { ++miss; continue; } + if (k != best) { + if (bs - score(k) <= 1e-5) ++near; + else ++miss; + } + for (int64_t d = 0; d < n; ++d) { + double q = ob[(size_t)d]; + for (int64_t j = 0; j < dim; ++j) + q += (double)ow[(size_t)(d * dim + j)] * cb[(size_t)(k * dim + j)]; + want[(size_t)(i * n + d)] = (float)(x[(size_t)(i * n + d)] - q); + } + } + ok((nm + " codes").c_str(), miss == 0 && gaps == 0, + fmt("%lld of %lld codes wrong (%lld near ties taken), %lld gaps of the strided codes " + "written", (long long)miss, (long long)M, (long long)near, (long long)gaps)); + if (c.f32x) { + /* f32 rows: against the f32 rows themselves (check() rounds its reference to bf16). */ + double e = 0, r2 = 0; + for (size_t i = 0; i < want.size(); ++i) { + e += ((double)gx[i] - want[i]) * ((double)gx[i] - want[i]); + r2 += (double)want[i] * want[i]; + } + const double rl = std::sqrt(e / std::max(r2, 1e-30)); + ok(fmt("%s residual (rel_l2 %.3g, bound 1e-05)", nm.c_str(), rl).c_str(), rl <= 1e-5); + } else { + check(nm + " residual", gx, want, 1e-2); + } + } +} + /* frame_store: each lane's codes into its block of the history, frames before `skip` and lanes * whose status ended the piece left alone. Exact. */ void frame_store_cases(const Plugin& pl) { @@ -9331,36 +9443,43 @@ void gate_add_none_case(const Plugin& pl) { /* conv1d at f32 at a BigVGAN's geometries: conv_pre's 2048 -> 1024 over 7 taps, the AMP blocks' * dilated 3/7/11 taps with the residual the output itself, the direct kernel's 8 channels and the - * final conv's one with its clamp. Two sequences, so a tap crossing a sequence's edge reads zero. */ + * final conv's one with its clamp; then a DAC encoder's strided causal downsampling (kernels of two + * strides, 2 to 8, and the quantizer's of one). Two sequences, so a tap crossing a sequence's edge + * reads zero; a strided case's sequences are whole strides. */ void conv1d_f32_cases(const Plugin& pl) { const RadKernelInfo* r = find(pl, "conv1d_f32"); if (!r) { ok("conv1d_f32", false, "row absent"); return; } - struct C { int64_t cin, cout, k, dil, M0, M1; int act, bias, res; }; /* res 2: y itself */ + struct C { int64_t cin, cout, k, dil, M0, M1; int act, bias, res; int64_t st = 1; }; /* res 2: y itself */ for (const C& c : { C{ 2048, 1024, 7, 1, 9, 15, 0, 1, 0 }, C{ 64, 128, 7, 1, 37, 60, 0, 1, 0 }, C{ 32, 32, 11, 5, 70, 41, 0, 1, 2 }, C{ 16, 16, 3, 3, 50, 77, 0, 1, 1 }, C{ 48, 40, 3, 1, 33, 30, 1, 1, 0 }, C{ 8, 8, 11, 5, 90, 64, 0, 1, 2 }, - C{ 8, 1, 7, 1, 100, 99, 2, 0, 0 }, C{ 64, 64, 11, 1, 200, 137, 2, 1, 2 } }) { + C{ 8, 1, 7, 1, 100, 99, 2, 0, 0 }, C{ 64, 64, 11, 1, 200, 137, 2, 1, 2 }, + C{ 64, 128, 4, 1, 36, 60, 0, 1, 0, 2 }, C{ 128, 256, 8, 1, 64, 40, 0, 1, 1, 4 }, + C{ 256, 512, 16, 1, 96, 136, 0, 1, 0, 8 }, C{ 8, 8, 16, 1, 32, 48, 0, 1, 0, 8 }, + C{ 64, 64, 2, 1, 50, 30, 0, 1, 2, 2 } }) { const std::vector cu = { 0, (int32_t)c.M0, (int32_t)(c.M0 + c.M1) }; - const int64_t M = c.M0 + c.M1; + const int64_t M = c.M0 + c.M1, MO = M / c.st; std::vector x = randv((size_t)(M * c.cin), 1.0f); std::vector w = randv((size_t)(c.cout * c.cin * c.k), 1.0f / std::sqrt((float)(c.cin * c.k))); - std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f); + std::vector b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(MO * c.cout), 0.5f); std::vector ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout), PI("k", c.k), PI("dil", c.dil), PS("act", c.act == 1 ? "tanh" : c.act == 2 ? "clamp" : "none"), PS("dtype", "f32") }; - const std::string nm = fmt("conv1d_f32 cin %lld cout %lld k %lld dil %lld%s%s%s", (long long)c.cin, + if (c.st > 1) { ps.push_back(PI("causal", 1)); ps.push_back(PI("stride", c.st)); } + const std::string nm = fmt("conv1d_f32 cin %lld cout %lld k %lld dil %lld%s%s%s%s", (long long)c.cin, (long long)c.cout, (long long)c.k, (long long)c.dil, + c.st > 1 ? fmt(" causal stride %lld", (long long)c.st).c_str() : "", c.bias ? " +bias" : "", c.res == 2 ? " +res in place" : c.res ? " +res" : "", c.act == 1 ? " tanh" : c.act == 2 ? " clamp" : ""); void* dw = stored_weight_f32(r, ps, w, c.cout, c.cin * c.k, nm.c_str()); if (!dw) continue; void* dx = up_f32(x); void* db = up_f32(b); - void* dy = up_f32(c.res == 2 ? res : std::vector((size_t)(M * c.cout), 0.0f)); + void* dy = up_f32(c.res == 2 ? res : std::vector((size_t)(MO * c.cout), 0.0f)); void* dr = up_f32(res); - RadTensor ty = T(dy, RAD_F32, { M, c.cout }); - RadTensor tr = c.res == 2 ? ty : T(dr, RAD_F32, { M, c.cout }); + RadTensor ty = T(dy, RAD_F32, { MO, c.cout }); + RadTensor tr = c.res == 2 ? ty : T(dr, RAD_F32, { MO, c.cout }); RadTensor tb = T(db, RAD_F32, { c.cout }); if (!c.res) absent(tr); if (!c.bias) absent(tb); @@ -9369,14 +9488,14 @@ void conv1d_f32_cases(const Plugin& pl) { T(up_i32(cu), RAD_I32, { 3 }), tr, ty, tb }, ps); if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } - const int64_t pad = c.dil * (c.k - 1) / 2; - std::vector want((size_t)(M * c.cout)); - for (int64_t row = 0; row < M; ++row) { - const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; + const int64_t pad = c.st > 1 ? c.dil * (c.k - 1) + 1 - c.st : c.dil * (c.k - 1) / 2; + std::vector want((size_t)(MO * c.cout)); + for (int64_t row = 0; row < MO; ++row) { + const int64_t e = seq_of(cu, row * c.st), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1]; for (int64_t co = 0; co < c.cout; ++co) { double acc = 0; for (int64_t kk = 0; kk < c.k; ++kk) { - const int64_t ir = row + kk * c.dil - pad; + const int64_t ir = row * c.st + kk * c.dil - pad; if (ir < s0 || ir >= s1) continue; for (int64_t ci = 0; ci < c.cin; ++ci) acc += (double)w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)]; @@ -25065,6 +25184,7 @@ static void device_phase(const Plugin& pl) { if (sel("cfg_topk_sample")) au::cfg_topk_cases(pl); if (sel("ras_pick")) au::ras_pick_cases(pl); if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl); + if (sel("vq_encode")) au::vq_encode_cases(pl); if (sel("frame_store")) au::frame_store_cases(pl); if (sel("iota")) au::iota_cases(pl); if (sel("gelu_bf16")) au::gelu_case(pl); diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index 2144cc07..68ba7b2e 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -51,8 +51,13 @@ inline int64_t ldi(const RadTensor* t, int64_t i) { * them), outside of which the input reads zero (each sequence is padded on its own). w is * PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding * dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it, - * dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none, - * tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */ + * dil (k - 1), on the left (any k). A `stride` s > 1 (causal only, a reach of at least s) keeps + * every s-th output row: the left pad is the reach less s, and a sequence of L rows (every bound a + * whole number of strides) gives L / s, y's and res's rows the input's over s. `cu_div` reads the + * bounds in units that many input rows apart: sequence e is input rows [cu[e] / cu_div, + * cu[e+1] / cu_div), each bound a multiple of cu_div stride. `res`, when bound, is added after the + * bias; then `act` (none, tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 + * accumulation, one rounding. */ int ref_conv1d(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2]; @@ -60,29 +65,38 @@ int ref_conv1d(const RadArgs* a, RadStream) { 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 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) + causal < 0 || causal > 1 || st < 1 || (st > 1 && (!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; - const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq); - if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE; + /* A stride takes each sequence of L rows to L / stride, so every bound is a whole number of + * strides (of cu_div units each). */ + for (int64_t e = 0; e <= n_seq; ++e) + if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE; + const int64_t r0 = cu_at(cu, 0) / cd, r1 = cu_at(cu, n_seq) / cd; + if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 / st || rows_of(x, cin) < r1) + return RAD_E_SHAPE; if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE; - if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE; - const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2; - REF_PAR_FOR((r1 - r0) * cout * cin * k) - for (int64_t r = r0; r < r1; ++r) { - const int64_t e = seq_of(cu, n_seq, r); - const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1); + if (res && rows_of(res, cout) < r1 / st) return RAD_E_SHAPE; + /* Causal: the reach is dil (k - 1) + 1 input rows and the left pad that less the stride, so + * output row o of a sequence reads input rows o stride - pad .. o stride + stride - 1. */ + const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2; + REF_PAR_FOR((r1 - r0) / st * cout * cin * k) + for (int64_t r = r0 / st; r < r1 / st; ++r) { + const int64_t 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 yb = rowoff(y, r, cout), ys = laststride(y); for (int64_t co = 0; co < cout; ++co) { float acc = 0.0f; for (int64_t kk = 0; kk < k; ++kk) { - const int64_t ir = r + kk * dil - pad; + const int64_t ir = r * st + kk * dil - pad; if (ir < s0 || ir >= s1) continue; const int64_t xb = rowoff(x, ir, cin), xs = laststride(x); for (int64_t ci = 0; ci < cin; ++ci) @@ -418,6 +432,62 @@ int ref_rvq_embed(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ vq_encode */ +/* One step of a residual vector quantiser with factorised, L2-normalised codes (DAC's + * VectorQuantize, as Fish Audio's codec encodes): per row of x [rows, n], e = in_w x + in_b + * (in_w [dim, n]); the code is the row of cb [bins, dim] of greatest cosine with e, + * (e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12)), the lower index on a tie; then + * x -= out_w cb[code] + out_b (out_w [n, dim], the raw codebook row), rounded once into x. f32, + * every sum in index order. A chain of these over a codec's codebooks is its residual quantiser, + * each step quantising what the last left. */ +int ref_vq_encode(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3]; + const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6]; + const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0); + if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim || + numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n) + return RAD_E_SHAPE; + /* The codebook normalised once, as F.normalize divides. */ + std::vector cn((size_t)(bins * dim)); + for (int64_t c = 0; c < bins; ++c) { + float ss = 0.0f; + for (int64_t j = 0; j < dim; ++j) ss += ldt(cb, c * dim + j) * ldt(cb, c * dim + j); + const float nrm = std::max(std::sqrt(ss), 1e-12f); + for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = ldt(cb, c * dim + j) / nrm; + } + REF_PAR_FOR(rows * (dim * n + bins * dim + n * dim)) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + std::vector e((size_t)dim); + float ss = 0.0f; + for (int64_t j = 0; j < dim; ++j) { + float acc = 0.0f; + for (int64_t d = 0; d < n; ++d) acc += ldt(iw, j * n + d) * ldt(x, xb + d * xs); + e[(size_t)j] = acc + ldt(ib, j); + ss += e[(size_t)j] * e[(size_t)j]; + } + const float nrm = std::max(std::sqrt(ss), 1e-12f); + for (int64_t j = 0; j < dim; ++j) e[(size_t)j] /= nrm; + int64_t best = 0; + float bs = -INFINITY; + for (int64_t c = 0; c < bins; ++c) { + float s = 0.0f; + for (int64_t j = 0; j < dim; ++j) s += e[(size_t)j] * cn[(size_t)(c * dim + j)]; + if (s > bs) { bs = s; best = c; } + } + st_int(codes->dtype, codes->data, offlin(codes, r), best); + for (int64_t d = 0; d < n; ++d) { + float q = 0.0f; + for (int64_t j = 0; j < dim; ++j) q += ldt(ow, d * dim + j) * ldt(cb, best * dim + j); + stt(x, xb + d * xs, ldt(x, xb + d * xs) - (q + ldt(ob, d))); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ frame_mix_store */ /* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale)) * with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row diff --git a/libref/ref_ops.h b/libref/ref_ops.h index ac9ce75a..622725bb 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -207,6 +207,7 @@ int ref_snake(const RadArgs*, RadStream); int ref_snake_aa(const RadArgs*, RadStream); int ref_cfg_topk_sample(const RadArgs*, RadStream); int ref_rvq_embed(const RadArgs*, RadStream); +int ref_vq_encode(const RadArgs*, RadStream); int ref_frame_mix_store(const RadArgs*, RadStream); int ref_end_status(const RadArgs*, RadStream); int ref_ras_pick(const RadArgs*, RadStream); @@ -447,6 +448,7 @@ REF_SHAPE_FN(ref_snake); REF_SHAPE_FN(ref_snake_aa); REF_SHAPE_FN(ref_cfg_topk_sample); REF_SHAPE_FN(ref_rvq_embed); +REF_SHAPE_FN(ref_vq_encode); REF_SHAPE_FN(ref_frame_mix_store); REF_SHAPE_FN(ref_end_status); REF_SHAPE_FN(ref_ras_pick); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index a4c99769..7503a0a0 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -884,7 +884,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") }; /* ---- audio generation (ref_audio.cpp) */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("dil"), P_STRO("act"), P_STR("dtype"), - P_INTO("causal") }; + P_INTO("causal"), P_INTO("stride"), + P_INTO("cu_div") }; static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"), OUT("y"), WGT_O("b") }; static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"), @@ -908,6 +909,10 @@ static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_ P_INT("vocab"), P_INT("off0"), P_F64("scale"), P_STR("dtype"), P_INTO("round"), P_INTO("clamp") }; static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") }; +static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"), + P_STR("dtype") }; +static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"), + WGT("out_w"), WGT("out_b"), OUT("codes") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), @@ -1769,6 +1774,10 @@ static const RadOpSchema kSchemas[] = { "a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum " "of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or " "with `round` 1 one f32 sum in codebook order times scale, rounded once." }, +{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode), + "one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest " + "cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded " + "once." }, { "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), "a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, " "stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." }, @@ -2345,6 +2354,8 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick DT_FLOAT, ref_cfg_topk_sample), SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes", DT_FLOAT, ref_rvq_embed), +SIMPLE("ref_vq_encode", "vq_encode", "elem", + "a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode), SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", DT_FLOAT, ref_frame_mix_store), SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index b9f074d7..def649be 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -3112,16 +3112,20 @@ static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; } int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0); - if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0)) + const int64_t st = gi(p, n_p, "stride", 1), dil = gi(p, n_p, "dil", 1); + if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || st < 1 || + (st > 1 && (!causal || dil * (k - 1) + 1 < st || M % st)) || gi(p, n_p, "cu_div", 1) != 1) return RAD_E_UNSUPPORTED; const uint32_t D = act_dt(p, n_p); - const int64_t S = two_seqs(M); + /* A strided convolution is described over one sequence: two would each need a whole number + * of strides. Bounds in coarser units (cu_div) are not drawn; ref_test checks them. */ + const int64_t S = st > 1 ? 1 : two_seqs(M); Opd o; o.t(D, { M, cin }); /* x */ o.t(D, { cout, cin, k }); /* w */ o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ - o.t(D, { M, cout }); /* res */ - o.t(D, { M, cout }); /* y */ + o.t(D, { M / st, cout }); /* res */ + o.t(D, { M / st, cout }); /* y */ o.t(D, { cout }); /* b */ return o.finish("conv1d", operand, out); } @@ -3199,6 +3203,22 @@ int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out return o.finish("rvq_embed", operand, out); } +int ref_vq_encode_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t dim = gi(p, n_p, "dim", 0), bins = gi(p, n_p, "bins", 0); + if (M <= 0 || n <= 0 || dim <= 0 || bins <= 0) return RAD_E_UNSUPPORTED; + const uint32_t F = (uint32_t)RAD_F32; + Opd o; + o.t(act_dt(p, n_p), { M, n }); /* x, INOUT */ + o.t(F, { dim, n }); /* in_w */ + o.t(F, { dim }); /* in_b */ + o.t(F, { bins, dim }); /* cb */ + o.t(F, { n, dim }); /* out_w */ + o.t(F, { n }); /* out_b */ + o.t_idx({ M }, bins, -1, 0); /* codes, OUT */ + return o.finish("vq_encode", operand, out); +} + int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0); const int64_t st = gi(p, n_p, "stride", 0); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 6d182677..560b6661 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -970,8 +970,9 @@ TEST(op_vocabulary) { "conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store", "end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish", "chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store", - /* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws. */ - "ras_pick", + /* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws, + * and its codec encoder's residual quantiser step. */ + "ras_pick", "vq_encode", /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ @@ -6998,6 +6999,68 @@ TEST(conv1d_act_clamp_bounds_the_output) { CHECK_EQ(y.at(2), -1.0f); CHECK_EQ(y.at(3), -0.75f); } +/* conv1d `stride`: Fish Audio's causal downsampling conv (modded_dac.py, CausalConvNet), the reach + * k less the stride padded on the left. k 4, stride 2 over [1..8] pads 2: windows [0 0 1 2], + * [1 2 3 4], [3 4 5 6], [5 6 7 8] against taps 1, 10, 100, 1000 are 2100, 4321, 6543, 8765. A + * second sequence [1 2 3 4] starts its own padding; a bound that is not a whole stride, and a + * stride on the symmetric form, are refused. `cu_div` reads the same bounds in samples. */ +TEST(conv1d_stride_downsamples_each_sequence_causally) { + T x(RAD_F32, {12, 1}); x.f({1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4}); + T w(RAD_F32, {1, 1, 4}); w.f({1, 10, 100, 1000}); + T cu(RAD_I32, {3}); cu.n({0, 8, 12}); + T y(RAD_F32, {6, 1}); + A a; a.t(x).t(w).t(cu).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4) + .i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32"); + CHECK_OK(run("conv1d", a)); + CHECK_EQ(y.at(0), 2100.0f); CHECK_EQ(y.at(1), 4321.0f); + CHECK_EQ(y.at(2), 6543.0f); CHECK_EQ(y.at(3), 8765.0f); + CHECK_EQ(y.at(4), 2100.0f); CHECK_EQ(y.at(5), 4321.0f); + T cu2(RAD_I32, {3}); cu2.n({0, 7, 12}); + A b; b.t(x).t(w).t(cu2).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4) + .i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32"); + CHECK_EQ(run("conv1d", b), RAD_E_SHAPE); + T w3(RAD_F32, {1, 1, 3}); w3.f({1, 1, 1}); + A c; c.t(x).t(w3).t(cu).tnull().t(y).i("M", 12).i("cin", 1).i("cout", 1).i("k", 3) + .i("dil", 1).i("stride", 2).s("dtype", "f32"); + CHECK_EQ(run("conv1d", c), RAD_E_SHAPE); + /* The same bounds in units of 4 rows (samples, 4 a row): the same rows; a bound that is not + * a whole number of strides in rows is refused. */ + T y2(RAD_F32, {6, 1}); + T cu4(RAD_I32, {3}); cu4.n({0, 32, 48}); + A d; d.t(x).t(w).t(cu4).tnull().t(y2).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4) + .i("dil", 1).i("causal", 1).i("stride", 2).i("cu_div", 4).s("dtype", "f32"); + CHECK_OK(run("conv1d", d)); + for (int64_t i = 0; i < 6; ++i) CHECK_EQ(y2.at(i), y.at(i)); + T cu6(RAD_I32, {3}); cu6.n({0, 28, 48}); + A e; e.t(x).t(w).t(cu6).tnull().t(y2).i("M", 12).i("cin", 1).i("cout", 1).i("k", 4) + .i("dil", 1).i("causal", 1).i("stride", 2).i("cu_div", 4).s("dtype", "f32"); + CHECK_EQ(run("conv1d", e), RAD_E_SHAPE); +} + +/* vq_encode by hand. in_w scales the first channel by 2; codebook rows 0 and 2 point the same way + * (a cosine tie, so the lower index), row 1 the other; out_w the identity and out_b + * [0.5, -0.5]. Row [4, 1]: e [8, 1], code 0, x - [1.5, -0.5] = [2.5, 1.5]. Row [-1, 3]: e [-2, 3], + * code 1, x - [0.5, 1.5] = [-1.5, 1.5]. Row [0, 0]: e 0, every cosine 0, code 0. */ +TEST(vq_encode_takes_the_nearest_code_by_cosine_and_leaves_the_residual) { + T x(RAD_F32, {3, 2}); x.f({4, 1, -1, 3, 0, 0}); + T iw(RAD_F32, {2, 2}); iw.f({2, 0, 0, 1}); + T ib(RAD_F32, {2}); ib.f({0, 0}); + T cb(RAD_F32, {3, 2}); cb.f({1, 0, 0, 2, 3, 0}); + T ow(RAD_F32, {2, 2}); ow.f({1, 0, 0, 1}); + T ob(RAD_F32, {2}); ob.f({0.5f, -0.5f}); + T codes(RAD_I32, {3}); codes.n({-1, -1, -1}); + A a; a.t(x).t(iw).t(ib).t(cb).t(ow).t(ob).t(codes).i("M", 3).i("n", 2).i("dim", 2) + .i("bins", 3).s("dtype", "f32"); + CHECK_OK(run("vq_encode", a)); + CHECK_EQ(codes.iat(0), 0); CHECK_EQ(codes.iat(1), 1); CHECK_EQ(codes.iat(2), 0); + CHECK_EQ(x.at(0), 2.5f); CHECK_EQ(x.at(1), 1.5f); + CHECK_EQ(x.at(2), -1.5f); CHECK_EQ(x.at(3), 1.5f); + CHECK_EQ(x.at(4), -1.5f); CHECK_EQ(x.at(5), 0.5f); + A b; b.t(x).t(iw).t(ib).t(cb).t(ow).t(ob).t(codes).i("M", 3).i("n", 2).i("dim", 2) + .i("bins", 4).s("dtype", "f32"); + CHECK_EQ(run("vq_encode", b), RAD_E_SHAPE); +} + /* snake_aa's paddings, with the activation the identity (alpha 0: sin(0 u) = 0). Ratio 2, filters * of 4: P = 1. Sequence [10, 20, 40] pads to [10, 10, 20, 40, 40]; the transposed f_up [1, 2, 3, 4] * gives [10, 20, 40, 60, 50, 80, 100, 160, 160, 240, 120, 160], doubled and cropped by 3 a side: @@ -8127,6 +8190,8 @@ std::vector geometries() { .i("rep", 2).s("dtype", "bf16")), G("end_status", "M", 2, a.i("M", R).i("end", 5).i("rep", 2)), G("ras_pick", "M", 2, a.i("M", R).i("win", 4).i("lo", 1).i("hi", 9).i("rep", 1)), + G("vq_encode", "M", 3, a.i("M", R).i("n", 16).i("dim", 4).i("bins", 24) + .s("dtype", "f32")), G("resample_nearest", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32")), G("fourier_embed", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("win_input", "M", 8, a.i("M", R).i("n_lat", 4).i("n_zero", 2).i("n_cond", 3) From bdc5c5b063eeb3dc025e04d20272d92b3bad54d8 Mon Sep 17 00:00:00 2001 From: zivius Date: Wed, 21 Oct 2026 00:41:57 +0200 Subject: [PATCH 12/35] core: references for an audio generator -- a request's clips of a voice and their transcripts (RadAudioGenDecl::tmpl_ref, ref_item), decoded to mono at the model's rate and padded to whole frames, each frame a prompt row the plugin encodes in the PROMPT pass (RadAudioGenBatch::ref_audio, ref_cu, ref_frame); /v1/audio/speech's and the streaming session's `references` --- abi/rad_builder.h | 31 ++++++-- abi/rad_runtime.h | 14 ++++ core/build/rad_builder.cpp | 36 +++++++++ core/engine.cpp | 6 ++ core/gen/audio.h | 6 ++ core/gen/audio_driver.cpp | 51 +++++++++++++ core/gen/audio_driver.h | 4 +- core/rad_core.h | 3 +- core/server/audio_gen.cpp | 140 ++++++++++++++++++++++++++++++---- core/server/iface.h | 5 ++ core/server/speech_stream.cpp | 2 +- tests/abi_layout_rows.h | 13 ++++ tests/speech_test.cpp | 109 ++++++++++++++++++++++++++ 13 files changed, 396 insertions(+), 24 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 2480458f..fd9022e4 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -974,6 +974,24 @@ typedef struct RadAudioGenDecl { * text always is, so a caller can write the model's speaker tags. The plugin's * rad_arch_text_prepare then refuses the control tokens a caller must not write. */ int32_t input_special; + /* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them, + * each a transcript and a clip of the voice saying it, which the plugin encodes into frames + * in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt + * of a request with references, `{references}` each of them rendered from `ref_item` in turn + * and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1, + * `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and + * `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before + * `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which + * prepare() has limited to those a caller may write), and so is the text after it. A clip is + * mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop` + * samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples` + * samples together. NULL `tmpl_ref`: references are refused. */ + const char* tmpl_ref; + const char* ref_item; + int64_t ref_rate; + int64_t ref_hop; + int64_t ref_max_samples; + int32_t ref_max; } RadAudioGenDecl; int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); @@ -1429,12 +1447,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta); * as given. Training data has conventions a client does not know -- section tags on lines of * their own and lower case, no markdown in a description -- and only the plugin knows them. * - * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included, - * and returns the length the whole result needs without its NUL (call again with more room when - * it is >= cap), or a negative status for text the model cannot take, with the reason in `out` - * (NUL-terminated within `cap`) when it has one to give the caller. Called on HTTP threads, so it - * keeps no state. */ -enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 }; + * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a + * reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the + * NUL included, and returns the length the whole result needs without its NUL (call again with + * more room when it is >= cap), or a negative status for text the model cannot take, with the + * reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on + * HTTP threads, so it keeps no state. */ +enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 }; int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap); /* The layout of a video generator's passes (rad_declare_video_generator), which only the model diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index b9c95569..88cc419c 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -475,6 +475,20 @@ typedef struct RadAudioGenBatch { const int32_t* prev_slot; const int32_t* prev_pos; const int32_t* prev_used; + + /* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its + * clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples + * ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the + * pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the + * clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages + * token 0; the plugin embeds the frame there instead. */ + int64_t n_ref; + int64_t ref_samples; + const float* ref_audio; + const int32_t* ref_cu; + const int32_t* ref_cu_h; + const int32_t* ref_frame; + const int32_t* ref_frame_h; } RadAudioGenBatch; /* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index dc549198..910fcfa0 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1376,6 +1376,33 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { "instructions and needs {input} alone", nm); return RAD_E_INVAL; } + /* References: a template with both of its slots, an item with one transcript before its one + * clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch + * would need references of its own). */ + if (d->tmpl_ref) { + auto once = [](const char* t, const char* k) { + const char* a = t ? std::strstr(t, k) : nullptr; + return a && !std::strstr(a + 1, k); + }; + const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr; + const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr; + if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") || + std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") || + !once(d->ref_item, "{text}") || !au || !tx || tx > au) { + err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and " + "{input} once each, and ref_item {text} before its one {audio}", nm); + return RAD_E_INVAL; + } + if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 || + d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) { + err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one " + "branch from whole prompts, clips at a rate (%lld Hz) in frames of " + "%lld samples, at most %d of them and %lld samples a request", nm, + (long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max, + (long long)d->ref_max_samples); + return RAD_E_INVAL; + } + } if (d->branches != 0 && d->branches != 1 && d->branches != 2) { err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence " "or 2 (0 means 2)", nm, (int)d->branches); @@ -1468,12 +1495,21 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { prog_.agen_str.tmpl = d->tmpl ? d->tmpl : ""; prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : ""; prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : ""; + prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : ""; + prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : ""; prog_.audio_gen = *d; /* As for the image generator: the Program is moved after declare; strings live in agen_str. */ prog_.audio_gen.name = nullptr; prog_.audio_gen.tmpl = nullptr; prog_.audio_gen.tmpl_plain = nullptr; prog_.audio_gen.neg_tmpl = nullptr; + prog_.audio_gen.tmpl_ref = nullptr; + prog_.audio_gen.ref_item = nullptr; + /* Without references the clips' geometry is nothing: the driver stages none. */ + if (!d->tmpl_ref) { + prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0; + prog_.audio_gen.ref_max = 0; + } return RAD_OK; } diff --git a/core/engine.cpp b/core/engine.cpp index 9c35f125..5fa2f4cc 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2501,6 +2501,12 @@ int Engine::run_server() { in.max_lanes = ad.max_lanes; in.branches = ad.branches == 1 ? 1 : 2; in.input_special = ad.input_special != 0; + in.tmpl_ref = pg.agen_str.tmpl_ref; + in.ref_item = pg.agen_str.ref_item; + in.ref_rate = ad.ref_rate; + in.ref_hop = ad.ref_hop; + in.ref_max_samples = ad.ref_max_samples; + in.ref_max = ad.ref_max; audio_bridge.drv = aud_gen_; audio_bridge.plugins = &plugins_; d.audio = &audio_bridge; diff --git a/core/gen/audio.h b/core/gen/audio.h index b879a537..f649c408 100644 --- a/core/gen/audio.h +++ b/core/gen/audio.h @@ -65,6 +65,12 @@ struct AudioRequest { * conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */ std::vector tokens; std::vector neg_tokens; + /* References (RadAudioGenDecl::tmpl_ref): the clips' samples end to end, each padded to whole + * frames; their bounds in samples, [clips + 1]; and for each row of `tokens` the frame of the + * clips it is, -1 for a token. All empty without references. */ + std::vector ref_audio; + std::vector ref_cu; + std::vector ref_frame; int64_t max_frames = 0; /* the most frames to make, >= 1 */ int32_t steps = 0; /* 0: the model's default */ float cfg = 0.0f; /* 0: the model's default */ diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp index c4567b7d..fabc6722 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -69,6 +69,7 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } struct Sizes { int64_t T = 0, S = 0, L = 0, NB = 0; int64_t NG = 0; /* stateful KV groups */ + int64_t RS = 0, RN = 0; /* references: samples and clips a request */ }; /* The paged full-attention group, and how many stateful groups sit beside it. */ @@ -92,6 +93,8 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { z.L = d.max_lanes; z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0; full_group(prog, &z.NG); + z.RS = d.ref_max_samples; + z.RN = d.ref_max; return z; } @@ -132,6 +135,9 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { z.S * I, /* R_PSLOT */ z.S * I, /* R_PPOS */ z.S * I, /* R_PUSED */ + z.RS * 4, /* R_RAUD */ + z.RN > 0 ? (z.RN + 1) * I : 0, /* R_RCU */ + z.RN > 0 ? z.T * I : 0, /* R_RFRM */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -286,6 +292,25 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { " seconds)"); if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000"); if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1"); + /* References: the clips the declaration allows, each a whole number of frames, and a frame + * for every row that names one. */ + if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty()) { + const int64_t n_ref = (int64_t)r->ref_cu.size() - 1, hop = d.ref_hop; + bool ok = d.ref_max > 0 && n_ref >= 1 && n_ref <= d.ref_max && r->ref_cu[0] == 0 && + r->ref_cu.back() == (int64_t)r->ref_audio.size() && + (int64_t)r->ref_audio.size() <= d.ref_max_samples && + (int64_t)r->ref_frame.size() == T; + for (int64_t i = 0; ok && i < n_ref; ++i) + ok = r->ref_cu[(size_t)i + 1] > r->ref_cu[(size_t)i] && r->ref_cu[(size_t)i + 1] % hop == 0; + const int64_t frames = ok ? r->ref_cu.back() / hop : 0; + for (int64_t t = 0; ok && t < T; ++t) + ok = r->ref_frame[(size_t)t] >= -1 && r->ref_frame[(size_t)t] < frames; + if (!ok) + return no(d.ref_max > 0 ? "the references do not fit this model: at most " + + std::to_string(d.ref_max) + " clips of whole frames, " + + std::to_string(d.ref_max_samples) + " samples together" + : std::string("this model takes no reference audio")); + } if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1)) return no("a piece of " + std::to_string(r->max_frames) + " frames after a " + std::to_string(T) + "-token prompt does not fit the KV cache even when it is " @@ -669,6 +694,22 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { reg_[R_USED].used = nb_ * 4; reg_[R_LANE].used = reg_[R_LAST].used = 4; reg_[R_SEED].used = 8; + /* The references: their clips, bounds and each row's frame (a whole prompt, so the rows are + * the prompt's own). */ + const AudioRequest& q = *j.req; + const int64_t n_ref = q.ref_cu.empty() ? 0 : (int64_t)q.ref_cu.size() - 1; + h_rcu_.clear(); + h_rfrm_.clear(); + if (n_ref > 0) { + std::memcpy(hptr(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4); + std::memcpy(hptr(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4); + std::memcpy(hptr(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4); + reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4; + reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4; + reg_[R_RFRM].used = cb[0] * 4; + h_rcu_ = q.ref_cu; + h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]); + } if (upload() < 0) return nullptr; base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); h_lane_.assign(1, j.lane); @@ -679,6 +720,16 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { A.n_lane = 1; A.lane_h = h_lane_.data(); A.last_h = h_last_.data(); + if (n_ref > 0) { + const int ri = (int)r; + A.n_ref = n_ref; + A.ref_samples = (int64_t)q.ref_audio.size(); + A.ref_audio = dptr(ri, R_RAUD); + A.ref_cu = dptr(ri, R_RCU); + A.ref_cu_h = h_rcu_.data(); + A.ref_frame = dptr(ri, R_RFRM); + A.ref_frame_h = h_rfrm_.data(); + } } pass_.kind = RAD_GEN_PASS_PROMPT; pass_.jobs.assign(1, j.id); diff --git a/core/gen/audio_driver.h b/core/gen/audio_driver.h index 55c1f9ed..561efb53 100644 --- a/core/gen/audio_driver.h +++ b/core/gen/audio_driver.h @@ -125,7 +125,7 @@ private: enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED, R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC, R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_PSLOT, R_PPOS, R_PUSED, - R_N }; + R_RAUD, R_RCU, R_RFRM, R_N }; /* A hybrid model's stateful groups (linear-attention state, convolution history), each staged * as one block-table word a sequence (its slot) and its state_index row. */ struct StateGroup { int32_t g = 0; int64_t width = 1; }; @@ -190,7 +190,7 @@ private: bool frame_turn_ = true; /* FRAME goes first when both are due */ /* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */ std::vector h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_, - h_wf0_, h_wnf_, h_lcu_; + h_wf0_, h_wnf_, h_lcu_, h_rcu_, h_rfrm_; mutable std::mutex mu_; std::deque> jobs_; /* arrival order */ diff --git a/core/rad_core.h b/core/rad_core.h index 6185bf76..ffeda16d 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -411,7 +411,8 @@ public: * strings point at `agen_str`, as the image generator's do at `gen_str`. */ RadAudioGenDecl audio_gen{}; struct AudioGenStrings { - std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */ + /* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */ + std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item; } agen_str; bool is_audio_generator() const { return audio_gen.max_lanes != 0; } /* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */ diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index 13eb7f05..4f658b01 100644 --- a/core/server/audio_gen.cpp +++ b/core/server/audio_gen.cpp @@ -11,6 +11,12 @@ * `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for * a speech one) and, for a model with a denoiser, `num_inference_steps`. * + * References, for a model that clones a voice (RadAudioGenDecl::tmpl_ref): `references` is an + * array of {"audio", "text"}, a clip of the voice (a data: URL or the base64 of an audio file, + * decoded to mono at the model's rate and padded to whole frames) and what it says; at most the + * model's count of them and seconds together. The prompt is then the references' template, each + * reference rendered from the model's item, its transcript and a row a frame of its clip. + * * Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin * into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with * its special tokens and the texts without, so a caller cannot write the model's control tokens @@ -30,6 +36,7 @@ #include "oai.h" #include "gen/audio.h" +#include "mm/media.h" #include "rad_internal.h" #include @@ -176,36 +183,141 @@ int Server::speech_request(const json& body, const std::string& text, r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); } + /* ---- the references: a clip of a voice and what it says, each */ + struct Ref { std::string text; int64_t frames = 0; }; + std::vector refs; + if (body.contains("references") && !body["references"].is_null()) { + const json& rs = body["references"]; + if (!rs.is_array()) + return fail(err_bad("references", "expected an array of {\"audio\", \"text\"}")); + if (!rs.empty() && info.tmpl_ref.empty()) + return fail(err_unsupported("references", "this model takes no reference audio; its " + "voice is described in the input")); + if ((int64_t)rs.size() > info.ref_max) + return fail(err_bad("references", "at most " + std::to_string(info.ref_max) + + " references a request")); + const int64_t hop = std::max(1, info.ref_hop); + r->ref_cu.assign(1, 0); + for (size_t i = 0; i < rs.size(); ++i) { + const std::string at = "references[" + std::to_string(i) + "]"; + const json& e = rs[i]; + if (!e.is_object()) + return fail(err_bad(at, "expected an object {\"audio\", \"text\"}")); + for (auto it = e.begin(); it != e.end(); ++it) + if (it.key() != "audio" && it.key() != "text") + return fail(err_bad(at + "." + it.key(), "a reference is its audio and its " + "text")); + if (!e.contains("audio") || !e["audio"].is_string()) + return fail(err_bad(at + ".audio", "the clip is required, as a data: URL or " + "base64 of an audio file")); + if (!e.contains("text") || !e["text"].is_string() || blank(e["text"].get())) + return fail(err_bad(at + ".text", "the clip's transcript is required, as a " + "non-empty string")); + /* The file: a data: URL, or its base64 alone (as fish-speech's server takes it). */ + const std::string& a = e["audio"].get_ref(); + std::vector bytes; + if (a.rfind("data:", 0) == 0) { + ApiError ue; + if (decode_media_url(a, at + ".audio", &bytes, &ue) < 0) return fail(ue); + } else if (!base64_decode(a, &bytes)) { + return fail(err_bad(at + ".audio", "invalid base64")); + } + /* Mono at the model's rate; one sample past what is left of the budget is decoded, + * so a clip too long is refused rather than cut. */ + const int64_t left = info.ref_max_samples - (int64_t)r->ref_audio.size(); + std::vector pcm; + std::string dwhy; + if (left < hop) + return fail(err_bad(at + ".audio", "the references are longer than this model " + "takes")); + if (mm::decode_audio(bytes.data(), bytes.size(), (int32_t)info.ref_rate, left + 1, + &pcm, &dwhy) < 0) + return fail(err_bad(at + ".audio", "the clip could not be used: " + dwhy)); + if (pcm.empty()) return fail(err_bad(at + ".audio", "the clip holds no audio")); + const int64_t padded = ((int64_t)pcm.size() + hop - 1) / hop * hop; + if (padded > left) + return fail(err_bad(at + ".audio", "the references hold more than " + + rad::fmt("%g", (double)info.ref_max_samples / + (double)info.ref_rate) + + " seconds together; this model takes no " + "more")); + pcm.resize((size_t)padded, 0.0f); + r->ref_audio.insert(r->ref_audio.end(), pcm.begin(), pcm.end()); + r->ref_cu.push_back((int32_t)r->ref_audio.size()); + Ref ref; + std::string why; + if (deps_.audio->prepare(RAD_TEXT_REFERENCE, e["text"].get(), &ref.text, + &why) < 0) + return fail(err_bad(at + ".text", why)); + ref.frames = padded / hop; + refs.push_back(std::move(ref)); + } + if (refs.empty()) r->ref_cu.clear(); + } + if (!refs.empty() && !inst.empty()) + return fail(err_unsupported("instructions", "a request with references takes no " + "instructions; the clips set the voice")); + /* ---- the prompt */ std::string i2, t2, why; if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0) return fail(err_bad("instructions", why)); if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0) return fail(err_bad("input", why)); + auto encode = [&](const std::string& t, bool special, std::vector* ids_out) { + if (t.empty()) return; + const auto ids = deps_.tok->encode(t, false, /*parse_special=*/special); + ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + }; + auto subst = [](std::string t, const std::string& key, const std::string& v) { + for (size_t p = t.find(key); p != std::string::npos; p = t.find(key, p + v.size())) + t.replace(p, key.size(), v); + return t; + }; + /* One reference (ref_item): its header, the transcript in it, tokenised as one segment with + * its special tokens (the speaker tags prepare() allows), a row a frame of its clip, and what + * follows the clip as another segment. */ + int64_t frame0 = 0; + auto render_ref = [&](size_t i, std::vector* ids_out) { + static const std::string kAudio = "{audio}"; + const std::string idx = std::to_string(i + 1); + const size_t a = info.ref_item.find(kAudio); + encode(subst(subst(info.ref_item.substr(0, a), "{index}", idx), "{text}", refs[i].text), + true, ids_out); + r->ref_frame.resize(ids_out->size(), -1); + for (int64_t f = 0; f < refs[i].frames; ++f) { + ids_out->push_back(0); + r->ref_frame.push_back((int32_t)(frame0 + f)); + } + frame0 += refs[i].frames; + encode(subst(info.ref_item.substr(a + kAudio.size()), "{index}", idx), true, ids_out); + }; /* A template a segment at a time: its own text with special tokens, each slot without. */ auto render = [&](const std::string& t, std::vector* ids_out) { - static const std::string kInst = "{instructions}", kInput = "{input}"; + static const std::string kInst = "{instructions}", kInput = "{input}", + kRefs = "{references}"; size_t at = 0; while (at <= t.size()) { - const size_t a = t.find(kInst, at), b = t.find(kInput, at); - const size_t p = std::min(a, b); - const std::string lit = - t.substr(at, p == std::string::npos ? std::string::npos : p - at); - if (!lit.empty()) { - const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true); - ids_out->insert(ids_out->end(), ids.begin(), ids.end()); - } + const size_t a = t.find(kInst, at), b = t.find(kInput, at), c = t.find(kRefs, at); + const size_t p = std::min(a, std::min(b, c)); + encode(t.substr(at, p == std::string::npos ? std::string::npos : p - at), true, + ids_out); if (p == std::string::npos) break; + if (p == c) { + for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out); + at = p + kRefs.size(); + continue; + } const bool is_inst = p == a; /* The input keeps its special tokens only for a model that asks (its speaker tags); * the plugin's prepare() has refused the ones a caller may not write. */ - const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, - /*parse_special=*/!is_inst && info.input_special); - ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out); at = p + (is_inst ? kInst : kInput).size(); } }; - render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens); + render(!refs.empty() ? info.tmpl_ref : inst.empty() ? info.tmpl_plain : info.tmpl, + &r->tokens); + if (!refs.empty()) r->ref_frame.resize(r->tokens.size(), -1); if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens); const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size()); if ((int64_t)n_prompt > info.max_prompt) @@ -234,7 +346,7 @@ HttpResponse Server::handle_speech(const HttpRequest& req) { static const char* kKnown[] = { "model", "input", "instructions", "voice", "response_format", "speed", "stream", "stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps", - "guidance_scale", "user", + "guidance_scale", "user", "references", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; diff --git a/core/server/iface.h b/core/server/iface.h index 664bdae4..442fc1d2 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -653,6 +653,11 @@ struct AudioGenInfo { * tokenised with special tokens). */ int32_t branches = 2; bool input_special = false; + /* RadAudioGenDecl's references: the prompt with them and one reference ("" when the model + * takes none), the clips' rate and frame, and the most of them and their samples. */ + std::string tmpl_ref, ref_item; + int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0; + int32_t ref_max = 0; }; class IAudioGen { diff --git a/core/server/speech_stream.cpp b/core/server/speech_stream.cpp index 120ed085..f600e1d1 100644 --- a/core/server/speech_stream.cpp +++ b/core/server/speech_stream.cpp @@ -214,7 +214,7 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) { static const char* kFields[] = { "type", "model", "instructions", "voice", "response_format", "speed", "seed", "max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user", - "stream_audio", "split_granularity", "text_input_mode", + "references", "stream_audio", "split_granularity", "text_input_mode", }; json fields = json::object(); for (auto it = j.begin(); it != j.end(); ++it) { diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index f786dd91..0f1d5bc0 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -140,6 +140,13 @@ ABI_FIELD(RadAudioGenBatch, voc_frame0) ABI_FIELD(RadAudioGenBatch, prev_slot) ABI_FIELD(RadAudioGenBatch, prev_pos) ABI_FIELD(RadAudioGenBatch, prev_used) +ABI_FIELD(RadAudioGenBatch, n_ref) +ABI_FIELD(RadAudioGenBatch, ref_samples) +ABI_FIELD(RadAudioGenBatch, ref_audio) +ABI_FIELD(RadAudioGenBatch, ref_cu) +ABI_FIELD(RadAudioGenBatch, ref_cu_h) +ABI_FIELD(RadAudioGenBatch, ref_frame) +ABI_FIELD(RadAudioGenBatch, ref_frame_h) ABI_STRUCT(RadAudioGenDecl) ABI_FIELD(RadAudioGenDecl, name) ABI_FIELD(RadAudioGenDecl, tmpl) @@ -174,6 +181,12 @@ ABI_FIELD(RadAudioGenDecl, voc_chunk) ABI_FIELD(RadAudioGenDecl, voc_context) ABI_FIELD(RadAudioGenDecl, branches) ABI_FIELD(RadAudioGenDecl, input_special) +ABI_FIELD(RadAudioGenDecl, tmpl_ref) +ABI_FIELD(RadAudioGenDecl, ref_item) +ABI_FIELD(RadAudioGenDecl, ref_rate) +ABI_FIELD(RadAudioGenDecl, ref_hop) +ABI_FIELD(RadAudioGenDecl, ref_max_samples) +ABI_FIELD(RadAudioGenDecl, ref_max) ABI_STRUCT(RadAudioFormat) ABI_FIELD(RadAudioFormat, struct_size) ABI_FIELD(RadAudioFormat, audio_open) diff --git a/tests/speech_test.cpp b/tests/speech_test.cpp index 71109a6e..15892228 100644 --- a/tests/speech_test.cpp +++ b/tests/speech_test.cpp @@ -201,6 +201,115 @@ TEST(a_model_that_asks_has_its_input_read_with_special_tokens_and_one_branch_has CHECK(!m.f->tok.last_parse_special); } +/* A 16-bit mono WAV of the given samples at `rate`. */ +static std::string wav_of(const std::vector& x, uint32_t rate) { + std::string d; + for (int16_t v : x) { + d.push_back((char)(v & 0xff)); + d.push_back((char)((v >> 8) & 0xff)); + } + auto u32 = [](uint32_t v) { + std::string b; + for (int i = 0; i < 4; ++i) b.push_back((char)((v >> (8 * i)) & 0xff)); + return b; + }; + auto u16 = [](uint16_t v) { return std::string{ (char)(v & 0xff), (char)(v >> 8) }; }; + return "RIFF" + u32((uint32_t)(36 + d.size())) + "WAVEfmt " + u32(16) + u16(1) + u16(1) + + u32(rate) + u32(rate * 2) + u16(2) + u16(16) + "data" + u32((uint32_t)d.size()) + d; +} + +/* A model that clones a voice takes references: each clip decoded at its rate and padded to + * whole frames, the prompt its references' template with each one's header, transcript and a row + * a frame (token 0, the clips' frames numbered in order), the rest of the rows -1. A data: URL and + * bare base64 both carry a clip. Refused by name: references on a model without them, too many, + * a reference without its text or clip or with an unknown field, a clip past the budget, and + * instructions beside them. */ +TEST(a_cloning_model_takes_references_as_clips_and_transcripts_in_its_prompt) { + if (!mm::decoder_available()) return; + Speech s; + s.gen.inf.tmpl_plain = "{input}"; + s.gen.inf.tmpl_ref = "R{references}|{input}"; + s.gen.inf.ref_item = "[{index}:{text}]{audio}."; + s.gen.inf.ref_rate = 8000; + s.gen.inf.ref_hop = 4; + s.gen.inf.ref_max_samples = 16; + s.gen.inf.ref_max = 2; + s.gen.inf.default_steps = 0; + s.gen.inf.branches = 1; + const std::string w1 = wav_of({ 1000, -2000, 3000, 4000, 5000 }, 8000); + const std::string w2 = wav_of({ -16384, 16384 }, 8000); + const std::string b1 = base64_encode((const uint8_t*)w1.data(), w1.size()); + const std::string b2 = base64_encode((const uint8_t*)w2.data(), w2.size()); + json refs = json::array({ json{ { "audio", b1 }, { "text", "one" } }, + json{ { "audio", "data:audio/wav;base64," + b2 }, + { "text", "two" } } }); + CHECK_EQ(s.post({ { "input", "hi" }, { "references", refs } }).status, 200); + const gen::AudioRequest& q = s.last(); + /* "R", "[1:one]", 2 frames, ".", "[2:two]", 1 frame, ".", "|hi". */ + const std::string head = "R[1:one]"; + std::vector want_tok, want_frame; + auto text = [&](const std::string& t) { + for (unsigned char c : t) { want_tok.push_back(c); want_frame.push_back(-1); } + }; + auto frames = [&](int32_t f0, int32_t n) { + for (int32_t f = 0; f < n; ++f) { want_tok.push_back(0); want_frame.push_back(f0 + f); } + }; + text(head); + frames(0, 2); + text(".[2:two]"); + frames(2, 1); + text(".|hi"); + CHECK(q.tokens == want_tok); + CHECK(q.ref_frame == want_frame); + REQUIRE(q.ref_cu.size() == 3); + CHECK_EQ(q.ref_cu[1], 8); + CHECK_EQ(q.ref_cu[2], 12); + REQUIRE(q.ref_audio.size() == 12); + CHECK(std::fabs(q.ref_audio[0] - 1000.0f / 32768.0f) < 1e-6f); + CHECK(std::fabs(q.ref_audio[1] + 2000.0f / 32768.0f) < 1e-6f); + CHECK_EQ(q.ref_audio[5], 0.0f); + CHECK_EQ(q.ref_audio[7], 0.0f); + CHECK(std::fabs(q.ref_audio[8] + 0.5f) < 1e-6f); + CHECK_EQ(q.ref_audio[11], 0.0f); + /* Without references the plain prompt, and no clips. */ + CHECK_EQ(s.post({ { "input", "hi" }, { "references", json::array() } }).status, 200); + CHECK(s.last().ref_cu.empty() && s.last().ref_frame.empty() && s.last().ref_audio.empty()); + + const json one = json{ { "audio", b1 }, { "text", "one" } }; + CHECK_EQ(s.refused({ { "input", "hi" }, { "references", json::array({ one, one, one }) } }), + std::string("references")); + CHECK_EQ(s.refused({ { "input", "hi" }, { "references", one } }), std::string("references")); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ json{ { "audio", b1 } } }) } }), + std::string("references[0].text")); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ json{ { "text", "x" } } }) } }), + std::string("references[0].audio")); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ json{ { "audio", b1 }, { "text", "x" }, + { "speaker", 1 } } }) } }), + std::string("references[0].speaker")); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ json{ { "audio", "@@@" }, + { "text", "x" } } }) } }), + std::string("references[0].audio")); + /* 8 and 8 samples fit the 16; a third frame past them does not. */ + const std::string w3 = wav_of(std::vector(9, 7), 8000); + const std::string b3 = base64_encode((const uint8_t*)w3.data(), w3.size()); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ one, json{ { "audio", b3 }, + { "text", "x" } } }) } }), + std::string("references[1].audio")); + CHECK_EQ(s.refused({ { "input", "hi" }, { "instructions", "calm" }, { "references", refs } }), + std::string("instructions")); + CHECK_EQ(s.refused({ { "input", "hi" }, + { "references", json::array({ json{ { "audio", b1 }, + { "text", "REFUSE" } } }) } }), + std::string("references[0].text")); + Speech m; + CHECK_EQ(m.refused(Speech::body({ { "references", refs } })), std::string("references")); +} + /* ================================================================== the response */ /* The whole piece: the windows in order whatever order they were played in, as a WAV whose header From 871aa7dd97a8000d3eb73ab8bb6044e4258593ff Mon Sep 17 00:00:00 2001 From: zivius Date: Wed, 21 Oct 2026 00:41:57 +0200 Subject: [PATCH 13/35] fishomni: voice cloning -- Fish S2's codec encoder (strided causal convolutions, a windowed transformer, two downsamplings and the residual quantiser) over a request's reference clips, their frames embedded as made frames are, the tower teacher-forced with them as fish-speech's prefill does, and the window of main picks seeded from the prompt; the reference prompt with each transcript tagged as the prompt builder tags it --- arch/fishomni/fishomni.cpp | 736 ++++++++++++++++++++++++++++----- data/recipes/drama3-fp8.recipe | 10 +- tests/shipped_plugins_test.cpp | 44 ++ 3 files changed, 689 insertions(+), 101 deletions(-) diff --git a/arch/fishomni/fishomni.cpp b/arch/fishomni/fishomni.cpp index aec0d6e7..9d424cd4 100644 --- a/arch/fishomni/fishomni.cpp +++ b/arch/fishomni/fishomni.cpp @@ -26,17 +26,24 @@ * Codec: Fish S2's modified DAC decoder: ten codebooks of dimension 8 (one of 4096, nine of * 1024), each projected to 1024 and summed; an 8-layer transformer (16 heads of 64, a causal * window of 128 frames); two 2x upsamplings with ConvNeXt blocks; four transposed convolutions - * (8, 8, 4, 2) with snake residual units; 2048 samples a frame. + * (8, 8, 4, 2) with snake residual units; 2048 samples a frame. Its encoder, for a reference + * clip, mirrors it: four blocks of snake residual units and strided causal convolutions (2, 4, + * 8, 8) with a 4-layer transformer (window 512 rows) after the last, two 2x downsamplings with + * ConvNeXt blocks, an 8-layer transformer (window 128 frames), and a residual quantiser, + * nearest code by cosine, the semantic codebook first. * * ============================== THE PASSES ============================== * * The core's audio generator in its chunked form, one branch a request (no guidance): * * PROMPT the backbone over the whole prompt; the last row's hidden state into the lane; the - * tower teacher-forced over every row. A prompt is text, so every row's label is text - * and every layer's code embedding is zero; the tower still runs, because its attention - * reads those rows' keys and values from every later frame. The last row's tower pass is - * the first frame's, and FRAME 0 overwrites it. + * tower teacher-forced over every row. A text prompt's labels are all text, so every + * layer's code embedding is zero; the tower still runs, because its attention reads + * those rows' keys and values from every later frame. With references the codec's + * encoder first turns their clips into frames, each a prompt row embedded as a made + * frame is; a row before a frame is labelled with it, a frame's row carries its unseen + * codes, and the window of main picks starts with the prompt's last frames. The last + * row's tower pass is the first frame's, and FRAME 0 overwrites it. * FRAME frame j of every lane in flight. The main token is drawn from the hidden state of the * row before the frame's (the prompt's last row for frame 0) over 4097 candidates (the * end of speech and the 4096 semantic tokens), with Fish's repetition-aware choice @@ -72,9 +79,14 @@ using namespace rad::arch; /* ================================================================== the model's constants */ constexpr int64_t kMaxLanes = 4; +/* References (voice cloning): at most 8 clips of 30 s together. fish-speech's server takes each + * up to 60 s; here the encoder's first stages, 64 and 128 channels at the samples' rate, hold + * about 170 MB a buffer at 30 s. A clip's frames are prompt rows. */ +constexpr int64_t kMaxRefFrames = 646; +constexpr int32_t kMaxRefs = 8; /* The longest prompt and speech. fish-speech's default request is 2048 frames (95 s); a plain - * prompt is a few dozen rows a sentence. */ -constexpr int64_t kMaxPrompt = 2048, kMaxFrames = 2048; + * prompt is a few dozen rows a sentence, and the references add a row a frame. */ +constexpr int64_t kMaxPrompt = 3072, kMaxFrames = 2048; /* A frame: ten codes, code 0 of 4096 (the semantic band), codes 1..9 drawn from heads of 4096 and * read by the codec through 1024-entry codebooks. */ constexpr int64_t kCodes = 10, kVocab = 4096, kResVocab = 1024; @@ -101,6 +113,7 @@ static const double kRasTemp = 1.0, kRasTopP = 0.95; * reach back about nine frames through the convolutions after the transformer (kConvCtx, rounded * up), whose rows reach back kAttnWin - 1 frames. The dequantiser is per frame. */ constexpr int64_t kSamplesPerFrame = 2048, kSampleRate = 44100; +constexpr int64_t kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame; /* 30.0 s */ constexpr int64_t kVocChunk = 16, kConvCtx = 12, kAttnWin = 128; constexpr int64_t kVocContext = (kAttnWin - 1) + kConvCtx; constexpr int64_t kConvFrames = kConvCtx + kVocChunk; @@ -108,6 +121,12 @@ constexpr int64_t kCbDim = 8, kLat = 1024, kDec = 1536; /* The codec transformer: 8 layers of 1024, 16 heads of 64, a SwiGLU of 3072. */ constexpr int64_t kCtLayers = 8, kCtHeads = 16, kCtHeadDim = 64, kCtFf = 3072; static const double kCtTheta = 10000.0, kCtEps = 1e-5; +/* The encoder (modded_dac.py's Encoder): four blocks, each three residual units and a strided + * causal conv (kernel two strides), a 4-layer transformer over a window of 512 rows after the + * last; the quantiser then halves the rate twice to the frames (rvq.py). Its rows are 1, 2, 8, 64 + * and 512 samples, then 1024 and 2048. */ +static const int64_t kEncStride[4] = { 2, 4, 8, 8 }; +constexpr int64_t kEncWin = 512, kEncLayers = 4; /* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames, * the two upsamplings', and each decoder block's output (8, 8, 4, 2 times). */ constexpr int kRates = 8; @@ -120,6 +139,15 @@ static const int64_t kRate[kRates] = { 1, 1, 2, 4, 32, 256, 1024, 2048 }; static const char* kPlain = "<|im_start|>system\nconvert the provided text to speech<|im_end|>\n" "<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n<|voice|>"; +/* With references: the system turn's instruction for them, then each one's numbered header, its + * transcript and its frames (the core tokenises the instruction apart from the first header, as + * fish-speech does: joined, ":\n\n" is one token), then the user turn as kPlain's. The + * transcript's speaker tag comes first in it, from text_prepare. */ +static const char* kRefPlain = + "<|im_start|>system\nconvert the provided text to speech reference to the following:" + "{references}<|im_end|>\n<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n" + "<|voice|>"; +static const char* kRefItem = "\n\n[Reference {index}]\nText: {text}\nSpeech: {audio}"; /* Weight groups (movement units): the backbone's layers are 0..39 (the blocks' own), the tower's * 40..52 like their KV layers, then the frame's tables and the codec. */ @@ -147,6 +175,9 @@ struct TowerLayer { rad_op op_attn = 0, op_kv = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar1 = 0, op_add1 = 0; rad_op op_fn = 0, op_gu = 0, op_act = 0, op_down = 0, op_ar2 = 0, op_add2 = 0, op_fin = 0; rad_op op_head = 0, op_samp = 0; + /* PROMPT with references: the label embedding over the prompt's rows (and layer 0's unseen + * codes), and its norm. */ + rad_op op_pemb = 0, op_peadd = 0, op_pen = 0; }; /* The codec transformer's layer: fused q|k|v with rotary at the frames' positions, causal @@ -180,6 +211,27 @@ struct VBlock { rad_op op_s = 0, op_t = 0; VRes res[3]; }; +/* An encoder block: three residual units, a snake, the strided conv. */ +struct EBlock { + VRes res[3]; + rad_weight a = 0; + rad_op op_s = 0; + VConv down{}; +}; +/* The quantiser's 2x downsampling: a strided causal conv (plain weights) and a ConvNeXt block. */ +struct EDown { + VConv c{}; + rad_weight w_dw = 0, b_dw = 0, w_ln = 0, b_ln = 0, w_p1 = 0, b_p1 = 0, w_p2 = 0, b_p2 = 0; + rad_weight w_g = 0; + rad_op op_dw = 0, op_ln = 0, op_p1 = 0, op_gelu = 0, op_p2 = 0, op_g = 0, op_add = 0; +}; +/* A residual quantiser step's weights, f32: the in-projection, the codebook, the out-projection. */ +struct EQuant { + rad_weight in_w = 0, in_b = 0, cb = 0, out_w = 0, out_b = 0; + rad_op op = 0; +}; +/* A codec transformer's working set: its residual stream and scratch. */ +struct CtSet { rad_buf x = 0, h = 0, qkv = 0, attn = 0, o = 0, gu = 0, ff = 0; }; struct Model { Names nm{""}; @@ -247,8 +299,29 @@ struct Model { rad_buf b_ux[3] = {}, b_ua = 0, b_ub = 0, b_uh = 0, b_ug2 = 0; rad_buf b_vs[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {}; rad_buf b_vout = 0, b_audio = 0; + + /* ---- the codec's encoder (PROMPT with references): the clips in, their frames' codes out + * into b_pc, the prompt rows' codes ([10, kMaxPrompt + 1] code-major, -2 and -1 at a token's + * row), from which the rows' embeddings and the tower's labels are read */ + rad_op op_ecast = 0, op_epos = 0, op_e5 = 0, op_etn = 0, op_pqn = 0; + VConv e0{}, e6{}; + EBlock eb[4]; + std::vector et, pq; + rad_weight w_etn = 0, w_e5 = 0, w_pqn = 0; + EDown ed[2]; + EQuant eq[kCodes]; + rad_op op_pc0 = 0, op_pc1 = 0, op_pfb = 0, op_pufill = 0, op_pu = 0, op_ptefill = 0; + rad_op op_rascopy = 0; + rad_buf b_ein = 0, b_ex[4] = {}, b_et[4] = {}, b_ea[4] = {}, b_ex4 = 0, b_et4 = 0, b_ea4 = 0; + CtSet ecs{}; + rad_buf b_epos = 0, b_ed1 = 0, b_ez = 0, b_dua = 0, b_dub = 0, b_duh = 0, b_dug = 0; + rad_buf b_pc = 0, b_pte = 0, b_pu = 0; }; +/* The width of the prompt rows' code plane: every row and one past the last, a token's (the last + * row's label). */ +constexpr int64_t kPcW = kMaxPrompt + 1; + static Model g_model[MAX_RANKS]; /* ================================================================== declare helpers */ @@ -825,6 +898,28 @@ static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) { m.b_tff = decl_b(b, nm.f("tower.ff"), RAD_BF16, { T, ff }); m.b_tho = decl_b(b, nm.f("tower.out"), RAD_BF16, { T, D }); m.b_hlog = decl_b(b, nm.f("tower.hlog"), RAD_F32, { S, kVocab }); + /* PROMPT with references: every row's label embedding, and its unseen codes (2..9 of the + * row's own frame, zero at a token's row), summed in f32 and rounded once as op_u's. */ + m.b_pte = decl_b(b, nm.f("tower.pe"), RAD_BF16, { T, D }); + m.b_pu = decl_b(b, nm.f("tower.pu"), RAD_BF16, { T, D }); + m.op_ptefill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_pte }); + m.op_pufill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_pu }); + m.op_pu = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes - 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_pc }, { m.b_pu }); + if (!m.op_ptefill || !m.op_pufill || !m.op_pu) return RAD_E_INVAL; for (int i = 0; i < kTower; ++i) { TowerLayer& L = m.tw[i]; @@ -897,6 +992,20 @@ static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) { { m.b_codes }, { m.b_te }); if (i == 0) L.op_eadd = add_op(b, S, D, m.b_te, m.b_ug, m.b_te); L.op_en = norm_op(b, S, D, g.eps, 1.0, L.w_en, { m.b_te }, m.b_tcat); + /* PROMPT with references: the label is the next row's frame, off the prompt rows' code + * plane a row on. Code 0 there is the frame's own c0, so a by-candidate table reads it + * one row on; a token row's code (-2 for code 0, -1 for the others) reads nothing, and + * its embedding stays the zero the fill leaves. */ + L.op_pemb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_codes", 1), RAD_INT("vocab", kVocab), + RAD_INT("off0", by_cand ? 1 : 0), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_emb, L.w_emb)), + { m.b_pc }, { m.b_pte }); + if (i == 0) L.op_peadd = add_op(b, T, D, m.b_pte, m.b_pu, m.b_pte); + L.op_pen = norm_op(b, T, D, g.eps, 1.0, L.w_en, { m.b_pte }, m.b_tcat); + if (!L.op_pemb || !L.op_pen || (i == 0 && !L.op_peadd)) return RAD_E_INVAL; /* Layer 0's hidden state is the backbone's: the prompt's rows (PROMPT) or the frame's * plane (FRAME); both stay live to here. */ L.op_hn = i == 0 ? norm_op(b, T, D, g.eps, 1.0, L.w_hn, { m.a_h.x, m.b_plane }, m.b_tcat) @@ -1013,7 +1122,33 @@ static int declare_frame_tail(RadBuilder* b, Model& m) { RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), { m.a_h.x }, { m.b_hid }); - return m.op_store && m.op_u && m.op_uscat && m.op_fb && m.op_fstore ? RAD_OK : RAD_E_INVAL; + /* PROMPT with references: a frame's row embedded as a made frame's is, off the rows' code + * plane (code 0 its own c0, so the candidate table is read one row on); a token's row, whose + * code 0 is -2, keeps its token's embedding. */ + m.op_pfb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, m.g.max_tok), RAD_INT("n_embd", D), + RAD_INT("n_codes", 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 1), RAD_F64("scale", 1.0 / std::sqrt(2.0)), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cemb, m.w_cb)), + { m.b_pc }, { m.b_x }); + /* ... and the lane's window of main picks starts with the prompt's last 16 rows', a frame's + * as its candidate (c0 + 1) and a token's as no pick (-2 + 1). */ + std::string src, one; + for (int64_t i = 0; i < kRasWin; ++i) { + src += (i ? " " : "") + std::to_string(i); + one += i ? " 1" : "1"; + } + m.op_rascopy = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, kRasWin), RAD_STR("src", src.c_str()), + RAD_STR("mul", one.c_str()), + RAD_STR("add", one.c_str())), + RAD_NOWEIGHTS), + { m.b_pc }, { m.b_ras }); + return m.op_store && m.op_u && m.op_uscat && m.op_fb && m.op_fstore && m.op_pfb && + m.op_rascopy + ? RAD_OK + : RAD_E_INVAL; } /* ================================================================== the codec */ @@ -1050,6 +1185,111 @@ static rad_op snake_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight a, rad { x }, { y }); } +/* An encoder's causal conv over the pass's clips: their bounds in samples, an input row holding + * `rate` of them (cu_div), `stride` input rows an output row. */ +static rad_op econv_op(RadBuilder* b, int64_t rows, int64_t cin, int64_t cout, int64_t k, + int64_t dil, int64_t stride, int64_t rate, rad_weight w, rad_weight bias, + rad_buf x, rad_buf res, rad_buf y) { + const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout), + RAD_INT("k", k), RAD_INT("dil", dil), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16"), RAD_INT("causal", 1), + RAD_INT("cu_div", rate), RAD_INT("stride", stride) }; + const int np = stride > 1 ? 10 : 9; + const rad_weight ws[] = { w, bias }; + return res ? rw(b, rad_decl_op(b, "conv1d", ps, np, ws, 2), { x, res }, { y }) + : rw(b, rad_decl_op(b, "conv1d", ps, np, ws, 2), { x }, { y }); +} + +/* An encoder conv, weight-normalised as vconv's. */ +static int econv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, int64_t stride, int64_t rate, int64_t rows, + rad_buf x, rad_buf res, rad_buf y) { + const char* wn = nm.f("%s.weight", dn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.parametrizations.weight.original0", src), + nm.ckpt("%s.parametrizations.weight.original1", src))); + v.w = decl_w(b, wn, RAD_BF16, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpCodec); + if (!v.w || !v.b) return RAD_E_INVAL; + v.op = econv_op(b, rows, cin, cout, k, dil, stride, rate, v.w, v.b, x, res, y); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +/* A codec transformer of `n` layers (modded_dac.py's WindowLimitedTransformer): plain-gain RMS + * norms at eps 1e-5, fused q|k|v with adjacent-pair rotary over all 64 dims at the rows' + * positions, causal attention over a window of `win` rows within each sequence, layer scales on + * both residual branches, over `rows` rows of B.x in place. Layer l's weights are `dn`.l.* from + * `src`.layers.l. The sequences are the buffer `cu`, or with none the pass's clips in samples, + * `cdiv` of them a row; the positions the buffer `pos`, or with none the pass's own. */ +static int declare_ct(RadBuilder* b, Names& nm, std::vector& ls, const char* dn, + const char* src, int n, int64_t rows, int64_t win, int64_t cdiv, + const CtSet& B, rad_buf cu, rad_buf pos) { + const int64_t qd = kCtHeads * kCtHeadDim; + ls.assign((size_t)n, CodecLayer{}); + for (int l = 0; l < n; ++l) { + CodecLayer& L = ls[(size_t)l]; + auto sr = [&](const char* x) { return nm.ckpt("%s.layers.%d.%s", src, l, x); }; + auto d = [&](const char* x) { return nm.f("%s.%d.%s", dn, l, x); }; + L.w_n1 = wcopy(b, d("n1.weight"), sr("attention_norm.weight"), RAD_F32, { kLat }, + kGrpCodec); + L.w_n2 = wcopy(b, d("n2.weight"), sr("ffn_norm.weight"), RAD_F32, { kLat }, kGrpCodec); + L.w_ls1 = wcopy(b, d("ls1.weight"), sr("attention_layer_scale.gamma"), RAD_F32, + { kLat }, kGrpCodec); + L.w_ls2 = wcopy(b, d("ls2.weight"), sr("ffn_layer_scale.gamma"), RAD_F32, { kLat }, + kGrpCodec); + L.w_qkv = wcopy(b, d("qkv.weight"), sr("attention.wqkv.weight"), RAD_BF16, + { 3 * qd, kLat }, kGrpCodec); + L.w_o = wcopy(b, d("o.weight"), sr("attention.wo.weight"), RAD_BF16, { kLat, qd }, + kGrpCodec); + if (map_concat(b, d("gate_up.weight"), + { sr("feed_forward.w1.weight"), sr("feed_forward.w3.weight") }) < 0) + return RAD_E_INVAL; + L.w_gu = decl_w(b, d("gate_up.weight"), RAD_BF16, { 2 * kCtFf, kLat }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); + L.w_down = wcopy(b, d("down.weight"), sr("feed_forward.w2.weight"), RAD_BF16, + { kLat, kCtFf }, kGrpCodec); + /* Plain-gain RMS norms at eps 1e-5 (the codec's own RMSNorm, not the backbone's). */ + L.op_n1 = norm_op(b, rows, kLat, kCtEps, 0.0, L.w_n1, { B.x }, B.h); + L.op_qkv = gemm_op(b, rows, 3 * qd, kLat, L.w_qkv, B.h, B.qkv); + /* Adjacent pairs over all 64 dims, positions the rows' own: a piece's frames as a whole + * decode restarting at 0 would see them, a clip's rows in the pass (attention reads only + * their differences). */ + L.op_rope = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), + RAD_INT("head_dim", kCtHeadDim), + RAD_INT("n_head", kCtHeads), + RAD_INT("n_head_kv", kCtHeads), + RAD_F64("theta", kCtTheta), RAD_F64("scale", 1.0), + RAD_STR("mode", "gptj")), + RAD_NOWEIGHTS), + { B.qkv }, { B.qkv }); + const RadParam ap[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", kCtHeadDim), + RAD_INT("gqa", 1), RAD_INT("causal", 1), RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)kCtHeadDim)), + RAD_INT("max_seqlen", rows), RAD_INT("window", win), + RAD_INT("cu_div", cdiv) }; + L.op_attn = rw(b, rad_decl_op(b, "attn_dense", ap, cdiv > 1 ? 9 : 8, nullptr, 0), + { B.qkv }, { B.attn }); + L.op_o = gemm_op(b, rows, kLat, qd, L.w_o, B.attn, B.o); + L.op_ls1 = mulw_op(b, rows, kLat, L.w_ls1, B.o, B.o); + L.op_add1 = add_op(b, rows, kLat, B.x, B.o, B.x); + L.op_n2 = norm_op(b, rows, kLat, kCtEps, 0.0, L.w_n2, { B.x }, B.h); + L.op_gu = gemm_op(b, rows, 2 * kCtFf, kLat, L.w_gu, B.h, B.gu); + L.op_act = rows_op(b, "silu_mul", rows, kCtFf, { B.gu }, { B.ff }); + L.op_down = gemm_op(b, rows, kLat, kCtFf, L.w_down, B.ff, B.o); + L.op_ls2 = mulw_op(b, rows, kLat, L.w_ls2, B.o, B.o); + L.op_add2 = add_op(b, rows, kLat, B.x, B.o, B.x); + if (!L.w_n1 || !L.w_n2 || !L.w_ls1 || !L.w_ls2 || !L.w_qkv || !L.w_o || !L.w_gu || + !L.w_down || !L.op_n1 || !L.op_qkv || !L.op_rope || !L.op_attn || !L.op_o || + !L.op_ls1 || !L.op_add1 || !L.op_n2 || !L.op_gu || !L.op_act || !L.op_down || + !L.op_ls2 || !L.op_add2) + return RAD_E_INVAL; + if (cu) RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &cu, 1)); + if (pos) RAD_ARCH_TRY(rad_op_reads(b, L.op_rope, &pos, 1)); + } + return RAD_OK; +} + static int declare_codec(RadBuilder* b, Model& m) { Names& nm = m.nm; const int64_t NL = kVocContext + kVocChunk; /* frames through the transformer */ @@ -1113,63 +1353,12 @@ static int declare_codec(RadBuilder* b, Model& m) { m.b_co = decl_b(b, nm.f("codec.o"), RAD_BF16, { NL, kLat }); m.b_cgu = decl_b(b, nm.f("codec.gu"), RAD_BF16, { NL, 2 * kCtFf }); m.b_cff = decl_b(b, nm.f("codec.ff"), RAD_BF16, { NL, kCtFf }); - m.ct.resize((size_t)kCtLayers); - for (int l = 0; l < kCtLayers; ++l) { - CodecLayer& L = m.ct[(size_t)l]; - auto src = [&](const char* s) { return nm.ckpt("%s.layers.%d.%s", pt, l, s); }; - auto dn = [&](const char* s) { return nm.f("codec.%d.%s", l, s); }; - L.w_n1 = wcopy(b, dn("n1.weight"), src("attention_norm.weight"), RAD_F32, { kLat }, - kGrpCodec); - L.w_n2 = wcopy(b, dn("n2.weight"), src("ffn_norm.weight"), RAD_F32, { kLat }, kGrpCodec); - L.w_ls1 = wcopy(b, dn("ls1.weight"), src("attention_layer_scale.gamma"), RAD_F32, - { kLat }, kGrpCodec); - L.w_ls2 = wcopy(b, dn("ls2.weight"), src("ffn_layer_scale.gamma"), RAD_F32, { kLat }, - kGrpCodec); - L.w_qkv = wcopy(b, dn("qkv.weight"), src("attention.wqkv.weight"), RAD_BF16, - { 3 * qd, kLat }, kGrpCodec); - L.w_o = wcopy(b, dn("o.weight"), src("attention.wo.weight"), RAD_BF16, { kLat, qd }, - kGrpCodec); - if (map_concat(b, dn("gate_up.weight"), - { src("feed_forward.w1.weight"), src("feed_forward.w3.weight") }) < 0) - return RAD_E_INVAL; - L.w_gu = decl_w(b, dn("gate_up.weight"), RAD_BF16, { 2 * kCtFf, kLat }, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); - L.w_down = wcopy(b, dn("down.weight"), src("feed_forward.w2.weight"), RAD_BF16, - { kLat, kCtFf }, kGrpCodec); - /* Plain-gain RMS norms at eps 1e-5 (the codec's own RMSNorm, not the backbone's). */ - L.op_n1 = norm_op(b, NL, kLat, kCtEps, 0.0, L.w_n1, { m.b_cx }, m.b_ch); - L.op_qkv = gemm_op(b, NL, 3 * qd, kLat, L.w_qkv, m.b_ch, m.b_cqkv); - /* Adjacent pairs over all 64 dims, positions the frames' own in the piece, as a whole - * decode restarting at 0 would see them. */ - L.op_rope = rw(b, RAD_OP(b, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("head_dim", kCtHeadDim), - RAD_INT("n_head", kCtHeads), - RAD_INT("n_head_kv", kCtHeads), - RAD_F64("theta", kCtTheta), RAD_F64("scale", 1.0), - RAD_STR("mode", "gptj")), - RAD_NOWEIGHTS), - { m.b_cqkv }, { m.b_cqkv }); - L.op_attn = rw(b, RAD_OP(b, "attn_dense", - RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("head_dim", kCtHeadDim), - RAD_INT("gqa", 1), RAD_INT("causal", 1), - RAD_STR("dtype", "bf16"), - RAD_F64("scale", 1.0 / std::sqrt((double)kCtHeadDim)), - RAD_INT("max_seqlen", NL), RAD_INT("window", kAttnWin)), - RAD_NOWEIGHTS), - { m.b_cqkv }, { m.b_cattn }); - L.op_o = gemm_op(b, NL, kLat, qd, L.w_o, m.b_cattn, m.b_co); - L.op_ls1 = mulw_op(b, NL, kLat, L.w_ls1, m.b_co, m.b_co); - L.op_add1 = add_op(b, NL, kLat, m.b_cx, m.b_co, m.b_cx); - L.op_n2 = norm_op(b, NL, kLat, kCtEps, 0.0, L.w_n2, { m.b_cx }, m.b_ch); - L.op_gu = gemm_op(b, NL, 2 * kCtFf, kLat, L.w_gu, m.b_ch, m.b_cgu); - L.op_act = rows_op(b, "silu_mul", NL, kCtFf, { m.b_cgu }, { m.b_cff }); - L.op_down = gemm_op(b, NL, kLat, kCtFf, L.w_down, m.b_cff, m.b_co); - L.op_ls2 = mulw_op(b, NL, kLat, L.w_ls2, m.b_co, m.b_co); - L.op_add2 = add_op(b, NL, kLat, m.b_cx, m.b_co, m.b_cx); - if (!L.w_n1 || !L.w_n2 || !L.w_ls1 || !L.w_ls2 || !L.w_qkv || !L.w_o || !L.w_gu || - !L.w_down || !L.op_rope || !L.op_attn || !L.op_ls1 || !L.op_ls2 || !L.op_act) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &m.b_ccu[0], 1)); + { + CtSet B; + B.x = m.b_cx; B.h = m.b_ch; B.qkv = m.b_cqkv; B.attn = m.b_cattn; B.o = m.b_co; + B.gu = m.b_cgu; B.ff = m.b_cff; + RAD_ARCH_TRY(declare_ct(b, nm, m.ct, "codec", pt, (int)kCtLayers, NL, kAttnWin, 1, B, + m.b_ccu[0], 0)); } /* The final norm over only the frames the convolutions read: the last nc. */ m.w_cn = wcopy(b, nm.f("codec.norm.weight"), nm.ckpt("%s.norm.weight", pt), RAD_F32, { kLat }, @@ -1311,6 +1500,204 @@ static int declare_codec(RadBuilder* b, Model& m) { : RAD_E_INVAL; } +/* ================================================================== the codec's encoder */ +/* Voice cloning: the PROMPT pass's reference clips to the codec's ten codes a frame + * (modded_dac.py's Encoder, then rvq.py's DownsampleResidualVectorQuantize), every clip at once, + * each a sequence of the pass's bounds, which are in samples and read at each rate through cu_div. + * In bf16, as fish-speech's server encodes a reference, every quantiser step in f32 (vq_encode) + * into the prompt rows' code plane at the clip's rows. + * + * Declared first: the clips are encoded before anything else of the pass runs, so the encoder's + * buffers are dead by the backbone's, and only the code plane, which the tower reads, lives on. */ +static int declare_encoder(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t L = kMaxRefSamples, D = kLat, qd = kCtHeads * kCtHeadDim; + const char* es = "codec.encoder.block"; + static const int64_t kDil[3] = { 1, 3, 9 }; + + m.b_ein = decl_b(b, nm.f("enc.in"), RAD_BF16, { L, 1 }); + m.op_ecast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, L), RAD_INT("n", 1), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_ein }); + int64_t rows = L, ch = 64, rate = 1; + for (int s = 0; s < 4; ++s) { + m.b_ex[s] = decl_b(b, nm.f("enc.x%d", s), RAD_BF16, { rows, ch }); + m.b_et[s] = decl_b(b, nm.f("enc.t%d", s), RAD_BF16, { rows, ch }); + m.b_ea[s] = decl_b(b, nm.f("enc.a%d", s), RAD_BF16, { rows, ch }); + rows /= kEncStride[s]; + ch *= 2; + } + const int64_t R4 = rows, R5 = R4 / 2, F = R5 / 2; /* 512, 1024 and 2048 samples a row */ + m.b_ex4 = decl_b(b, nm.f("enc.x4"), RAD_BF16, { R4, D }); + m.b_et4 = decl_b(b, nm.f("enc.t4"), RAD_BF16, { R4, D }); + m.b_ea4 = decl_b(b, nm.f("enc.a4"), RAD_BF16, { R4, D }); + RAD_ARCH_TRY(econv(b, nm, m.e0, "codec.enc.0", nm.ckpt("%s.0.conv", es), 1, 64, 7, 1, 1, 1, L, + m.b_ein, 0, m.b_ex[0])); + if (!m.op_ecast) return RAD_E_INVAL; + + /* ---- four blocks: three residual units (dilations 1, 3, 9: x + conv2(snake2(conv1(snake1 + * (x))))), a snake and the strided conv into the next block's rows */ + rows = L; + ch = 64; + for (int s = 0; s < 4; ++s) { + EBlock& B = m.eb[s]; + const char* bn = nm.f("codec.enc.b%d", s); + const char* bs = nm.ckpt("%s.%d.block", es, s + 1); + const rad_buf X = m.b_ex[s], T = m.b_et[s], A = m.b_ea[s]; + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* ub = nm.ckpt("%s.%d.block", bs, r); + U.a1 = valpha(b, nm, nm.f("%s.act1", un), nm.ckpt("%s.0", ub), ch); + U.a2 = valpha(b, nm, nm.f("%s.act2", un), nm.ckpt("%s.2", ub), ch); + U.op_s1 = snake_op(b, rows, ch, U.a1, X, T); + RAD_ARCH_TRY(econv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.1.conv", ub), ch, ch, + 7, kDil[r], 1, rate, rows, T, 0, A)); + U.op_s2 = snake_op(b, rows, ch, U.a2, A, T); + RAD_ARCH_TRY(econv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.3.conv", ub), ch, ch, + 1, 1, 1, rate, rows, T, X, X)); + if (!U.a1 || !U.a2 || !U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + B.a = valpha(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.3", bs), ch); + B.op_s = snake_op(b, rows, ch, B.a, X, T); + if (!B.a || !B.op_s) return RAD_E_INVAL; + const int64_t st = kEncStride[s]; + RAD_ARCH_TRY(econv(b, nm, B.down, nm.f("%s.down", bn), nm.ckpt("%s.4.conv", bs), ch, + 2 * ch, 2 * st, 1, st, rate, rows, T, 0, + s < 3 ? m.b_ex[s + 1] : m.b_ex4)); + rows /= st; + ch *= 2; + rate *= st; + } + + /* ---- the last block's transformer (window 512 rows) and its norm, a snake, a conv */ + m.ecs.x = m.b_ex4; + m.ecs.h = decl_b(b, nm.f("enc.h"), RAD_BF16, { R4, D }); + m.ecs.qkv = decl_b(b, nm.f("enc.qkv"), RAD_BF16, { R4, 3 * qd }); + m.ecs.attn = decl_b(b, nm.f("enc.attn"), RAD_BF16, { R4, qd }); + m.ecs.o = decl_b(b, nm.f("enc.o"), RAD_BF16, { R4, D }); + m.ecs.gu = decl_b(b, nm.f("enc.gu"), RAD_BF16, { R4, 2 * kCtFf }); + m.ecs.ff = decl_b(b, nm.f("enc.ff"), RAD_BF16, { R4, kCtFf }); + m.b_epos = decl_b(b, nm.f("enc.pos"), RAD_I32, { R4 }); + m.op_epos = iota_op(b, R4, 0, 1, m.b_epos); + const char* tsrc = nm.ckpt("%s.4.block.5", es); + RAD_ARCH_TRY(declare_ct(b, nm, m.et, "codec.enc.t", tsrc, (int)kEncLayers, R4, kEncWin, 512, + m.ecs, 0, m.b_epos)); + m.w_etn = wcopy(b, nm.f("codec.enc.t.norm.weight"), nm.ckpt("%s.norm.weight", tsrc), RAD_F32, + { D }, kGrpCodec); + m.op_etn = norm_op(b, R4, D, kCtEps, 0.0, m.w_etn, { m.b_ex4 }, m.b_et4); + m.w_e5 = valpha(b, nm, "codec.enc.snake_out", nm.ckpt("%s.5", es), D); + m.op_e5 = snake_op(b, R4, D, m.w_e5, m.b_et4, m.b_ea4); + RAD_ARCH_TRY(econv(b, nm, m.e6, "codec.enc.conv_out", nm.ckpt("%s.6.conv", es), D, D, 3, 1, 1, + 512, R4, m.b_ea4, 0, m.b_ex4)); + if (!m.op_epos || !m.w_etn || !m.op_etn || !m.w_e5 || !m.op_e5) return RAD_E_INVAL; + + /* ---- the quantiser's two 2x downsamplings: a strided conv (plain weights), a ConvNeXt + * block (causal depthwise conv, layer norm, GELU feed-forward, layer scale, residual) */ + m.b_ed1 = decl_b(b, nm.f("enc.d1"), RAD_BF16, { R5, D }); + m.b_ez = decl_b(b, nm.f("enc.z"), RAD_BF16, { F, D }); + m.b_dua = decl_b(b, nm.f("enc.dua"), RAD_BF16, { R5, D }); + m.b_dub = decl_b(b, nm.f("enc.dub"), RAD_BF16, { R5, D }); + m.b_duh = decl_b(b, nm.f("enc.duh"), RAD_BF16, { R5, 4 * D }); + m.b_dug = decl_b(b, nm.f("enc.dug"), RAD_BF16, { R5, 4 * D }); + for (int i = 0; i < 2; ++i) { + EDown& E = m.ed[i]; + const int64_t rin = i ? R5 : R4, rout = rin / 2, rr = i ? 1024 : 512; + const rad_buf xin = i ? m.b_ed1 : m.b_ex4, y = i ? m.b_ez : m.b_ed1; + const char* ds = nm.ckpt("codec.quantizer.downsample.%d", i); + auto w = [&](const char* dn, const char* sr, uint32_t dt, + std::initializer_list sh) { + return wcopy(b, nm.f("codec.enc.down%d.%s", i, dn), nm.ckpt("%s.%s", ds, sr), dt, sh, + kGrpCodec); + }; + E.c.w = w("weight", "0.conv.weight", RAD_BF16, { D, D, 2 }); + E.c.b = w("bias", "0.conv.bias", RAD_BF16, { D }); + E.w_dw = w("dw.weight", "1.dwconv.conv.weight", RAD_BF16, { D, 1, 7 }); + E.b_dw = w("dw.bias", "1.dwconv.conv.bias", RAD_BF16, { D }); + E.w_ln = w("ln.weight", "1.norm.weight", RAD_F32, { D }); + E.b_ln = w("ln.bias", "1.norm.bias", RAD_F32, { D }); + E.w_p1 = w("p1.weight", "1.pwconv1.weight", RAD_BF16, { 4 * D, D }); + E.b_p1 = w("p1.bias", "1.pwconv1.bias", RAD_BF16, { 4 * D }); + E.w_p2 = w("p2.weight", "1.pwconv2.weight", RAD_BF16, { D, 4 * D }); + E.b_p2 = w("p2.bias", "1.pwconv2.bias", RAD_BF16, { D }); + E.w_g = w("gamma", "1.gamma", RAD_F32, { D }); + if (!E.c.w || !E.c.b || !E.w_dw || !E.b_dw || !E.w_ln || !E.b_ln || !E.w_p1 || !E.b_p1 || + !E.w_p2 || !E.b_p2 || !E.w_g) + return RAD_E_INVAL; + E.c.op = econv_op(b, rin, D, D, 2, 1, 2, rr, E.c.w, E.c.b, xin, 0, y); + E.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", D), RAD_INT("k", 7), + RAD_INT("cu_div", 2 * rr), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.w_dw, E.b_dw)), + { y }, { m.b_dua }); + E.op_ln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", D), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.w_ln, E.b_ln)), + { m.b_dua }, { m.b_dub }); + E.op_p1 = gemm_bias_op(b, rout, 4 * D, D, E.w_p1, E.b_p1, m.b_dub, m.b_duh); + E.op_gelu = rows_op(b, "gelu", rout, 4 * D, { m.b_duh }, { m.b_dug }); + E.op_p2 = gemm_bias_op(b, rout, D, 4 * D, E.w_p2, E.b_p2, m.b_dug, m.b_dua); + E.op_g = mulw_op(b, rout, D, E.w_g, m.b_dua, m.b_dua); + E.op_add = add_op(b, rout, D, y, m.b_dua, y); + if (!E.c.op || !E.op_dw || !E.op_ln || !E.op_p1 || !E.op_gelu || !E.op_p2 || !E.op_g || + !E.op_add) + return RAD_E_INVAL; + } + + /* ---- the pre-quantiser transformer (8 layers, window 128 frames) and its norm, over the + * encoder's working set */ + const char* psrc = "codec.quantizer.pre_module"; + CtSet P = m.ecs; + P.x = m.b_ez; + RAD_ARCH_TRY(declare_ct(b, nm, m.pq, "codec.enc.pre", nm.ckpt("%s", psrc), (int)kCtLayers, F, + kAttnWin, kSamplesPerFrame, P, 0, m.b_epos)); + m.w_pqn = wcopy(b, nm.f("codec.enc.pre.norm.weight"), nm.ckpt("%s.norm.weight", psrc), + RAD_F32, { D }, kGrpCodec); + m.op_pqn = norm_op(b, F, D, kCtEps, 0.0, m.w_pqn, { m.b_ez }, m.b_ez); + if (!m.w_pqn || !m.op_pqn) return RAD_E_INVAL; + + /* ---- the prompt rows' codes: -2 for code 0 and -1 for the others at every row, then each + * clip's frames at their rows, the semantic step first and the nine residual ones after it, + * every step quantising what the last left of z */ + m.b_pc = decl_b(b, nm.f("enc.codes"), RAD_I32, { kCodes, kPcW }); + m.op_pc0 = iota_op(b, kPcW, -2, 0, m.b_pc); + m.op_pc1 = iota_op(b, (kCodes - 1) * kPcW, -1, 0, m.b_pc); + for (int k = 0; k < kCodes; ++k) { + EQuant& Q = m.eq[k]; + const char* qs = k == 0 ? nm.ckpt("codec.quantizer.semantic_quantizer.quantizers.0") + : nm.ckpt("codec.quantizer.quantizer.quantizers.%d", k - 1); + const int64_t bins = k == 0 ? kVocab : kResVocab; + const char* iw = nm.f("codec.enc.vq%d.in.weight", k); + const char* ow = nm.f("codec.enc.vq%d.out.weight", k); + RAD_ARCH_TRY(map_wnorm(b, iw, nm.ckpt("%s.in_proj.weight_g", qs), + nm.ckpt("%s.in_proj.weight_v", qs))); + RAD_ARCH_TRY(map_wnorm(b, ow, nm.ckpt("%s.out_proj.weight_g", qs), + nm.ckpt("%s.out_proj.weight_v", qs))); + Q.in_w = decl_w(b, iw, RAD_F32, { kCbDim, D, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + Q.in_b = wcopy(b, nm.f("codec.enc.vq%d.in.bias", k), nm.ckpt("%s.in_proj.bias", qs), + RAD_F32, { kCbDim }, kGrpCodec); + Q.cb = wcopy(b, nm.f("codec.enc.vq%d.codebook", k), nm.ckpt("%s.codebook.weight", qs), + RAD_F32, { bins, kCbDim }, kGrpCodec); + Q.out_w = decl_w(b, ow, RAD_F32, { D, kCbDim, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + Q.out_b = wcopy(b, nm.f("codec.enc.vq%d.out.bias", k), nm.ckpt("%s.out_proj.bias", qs), + RAD_F32, { D }, kGrpCodec); + if (!Q.in_w || !Q.in_b || !Q.cb || !Q.out_w || !Q.out_b) return RAD_E_INVAL; + Q.op = rw(b, RAD_OP(b, "vq_encode", + RAD_PARAMS(RAD_RANGE("M", 1, F), RAD_INT("n", D), + RAD_INT("dim", kCbDim), RAD_INT("bins", bins), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Q.in_w, Q.in_b, Q.cb, Q.out_w, Q.out_b)), + { m.b_ez }, { m.b_ez, m.b_pc }); + if (!Q.op) return RAD_E_INVAL; + } + return m.op_pc0 && m.op_pc1 ? RAD_OK : RAD_E_INVAL; +} + /* ================================================================== declare */ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx) return RAD_E_INVAL; @@ -1332,11 +1719,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_E_INVAL; } - /* Declared in the order the passes issue them where it matters for liveness: the backbone - * first (PROMPT runs it before everything else), then the frame head, the tower, the frame's - * tail, and the codec. FRAME runs the head and the tower before the backbone; the buffers - * that cross that seam (`x`, `h`, the codes, the plane) are named by the ops on both sides, - * so their live ranges span it. */ + /* Declared in the order the passes issue them where it matters for liveness: the codec's + * encoder first (PROMPT runs it before everything else when the request has references), the + * backbone, then the frame head, the tower, the frame's tail, and the codec. The rows' code + * plane the encoder leaves is named by the tower's ops too, so it lives across the backbone. + * FRAME runs the head and the tower before the backbone; the buffers that cross that seam + * (`x`, `h`, the codes, the plane) are named by the ops on both sides, so their live ranges + * span it. */ + RAD_ARCH_TRY(declare_encoder(b, m)); RAD_ARCH_TRY(declare_trunk(b, meta, ctx, m)); RAD_ARCH_TRY(declare_frame_head(b, m)); RAD_ARCH_TRY(declare_tower(b, meta, m)); @@ -1367,6 +1757,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.voc_context = kVocContext; d.branches = 1; d.input_special = 1; + d.tmpl_ref = kRefPlain; + d.ref_item = kRefItem; + d.ref_rate = kSampleRate; + d.ref_hop = kSamplesPerFrame; + d.ref_max_samples = kMaxRefSamples; + d.ref_max = kMaxRefs; RAD_ARCH_TRY(rad_declare_audio_generator(b, &d)); } rad_note(b, "rank %d/%d: drama-3 -- backbone %lld layers (%lld heads, %lld KV a rank; %lld " @@ -1386,6 +1782,107 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ================================================================== step */ +/* A codec transformer (declare_ct) over R rows of B.x. */ +static void step_ct(RadCtx* c, const std::vector& ls, int64_t R, const CtSet& B, + RadOperand pos, RadOperand cu) { + const int64_t qd = kCtHeads * kCtHeadDim; + for (const CodecLayer& Ly : ls) { + RAD_ISSUE_N(c, Ly.op_n1, R, brows(B.x, R), RAD_W(Ly.w_n1), brows(B.h, R)); + RAD_ISSUE_N(c, Ly.op_qkv, R, brows(B.h, R), RAD_W(Ly.w_qkv), brows(B.qkv, R)); + RAD_ISSUE_N(c, Ly.op_rope, R, brows(B.qkv, R), pos); + RAD_ISSUE_N(c, Ly.op_attn, R, bcol(B.qkv, 0, qd, R), bcol(B.qkv, qd, qd, R), + bcol(B.qkv, 2 * qd, qd, R), cu, brows(B.attn, R)); + RAD_ISSUE_N(c, Ly.op_o, R, brows(B.attn, R), RAD_W(Ly.w_o), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_ls1, R, brows(B.o, R), RAD_W(Ly.w_ls1), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_add1, R, brows(B.x, R), brows(B.o, R), brows(B.x, R)); + RAD_ISSUE_N(c, Ly.op_n2, R, brows(B.x, R), RAD_W(Ly.w_n2), brows(B.h, R)); + RAD_ISSUE_N(c, Ly.op_gu, R, brows(B.h, R), RAD_W(Ly.w_gu), brows(B.gu, R)); + RAD_ISSUE_N(c, Ly.op_act, R, brows(B.gu, R), brows(B.ff, R)); + RAD_ISSUE_N(c, Ly.op_down, R, brows(B.ff, R), RAD_W(Ly.w_down), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_ls2, R, brows(B.o, R), RAD_W(Ly.w_ls2), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_add2, R, brows(B.x, R), brows(B.o, R), brows(B.x, R)); + } +} + +/* A PROMPT pass's clips through the encoder (declare_encoder), their frames' codes into the + * prompt rows' code plane at the rows that name them. */ +static void step_encode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t L = A->ref_samples, D = kLat; + const RadOperand cu = praw(A->ref_cu, RAD_I32, A->n_ref + 1); + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, int64_t Ry) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), cu, res ? brows(res, R) : RAD_NONE, + brows(y, Ry), RAD_W(v.b)); + }; + RAD_ISSUE_N(c, m.op_ecast, L, praw(A->ref_audio, RAD_F32, L), brows(m.b_ein, L)); + conv(m.e0, m.b_ein, 0, m.b_ex[0], L, L); + int64_t R = L; + for (int s = 0; s < 4; ++s) { + const EBlock& B = m.eb[s]; + const rad_buf X = m.b_ex[s], T = m.b_et[s], Ab = m.b_ea[s]; + for (const VRes& U : B.res) { + RAD_ISSUE_N(c, U.op_s1, R, brows(X, R), RAD_W(U.a1), brows(T, R), RAD_NONE); + conv(U.c1, T, 0, Ab, R, R); + RAD_ISSUE_N(c, U.op_s2, R, brows(Ab, R), RAD_W(U.a2), brows(T, R), RAD_NONE); + conv(U.c2, T, X, X, R, R); + } + RAD_ISSUE_N(c, B.op_s, R, brows(X, R), RAD_W(B.a), brows(T, R), RAD_NONE); + conv(B.down, T, 0, s < 3 ? m.b_ex[s + 1] : m.b_ex4, R, R / kEncStride[s]); + R /= kEncStride[s]; + } + /* The last block's transformer, at the clips' rows of 512 samples; the snake and the conv. */ + RAD_ISSUE_N(c, m.op_epos, R, brows(m.b_epos, R)); + step_ct(c, m.et, R, m.ecs, brows(m.b_epos, R), cu); + RAD_ISSUE_N(c, m.op_etn, R, brows(m.b_ex4, R), RAD_W(m.w_etn), brows(m.b_et4, R)); + RAD_ISSUE_N(c, m.op_e5, R, brows(m.b_et4, R), RAD_W(m.w_e5), brows(m.b_ea4, R), RAD_NONE); + conv(m.e6, m.b_ea4, 0, m.b_ex4, R, R); + /* The quantiser's two downsamplings. */ + for (int i = 0; i < 2; ++i) { + const EDown& E = m.ed[i]; + const rad_buf xin = i ? m.b_ed1 : m.b_ex4, y = i ? m.b_ez : m.b_ed1; + const int64_t ro = R / 2; + conv(E.c, xin, 0, y, R, ro); + RAD_ISSUE_N(c, E.op_dw, ro, brows(y, ro), RAD_W(E.w_dw), cu, brows(m.b_dua, ro), + RAD_W(E.b_dw)); + RAD_ISSUE_N(c, E.op_ln, ro, brows(m.b_dua, ro), RAD_W(E.w_ln), RAD_W(E.b_ln), + brows(m.b_dub, ro)); + RAD_ISSUE_N(c, E.op_p1, ro, brows(m.b_dub, ro), RAD_W(E.w_p1), RAD_W(E.b_p1), RAD_NONE, + brows(m.b_duh, ro)); + RAD_ISSUE_N(c, E.op_gelu, ro, brows(m.b_duh, ro), brows(m.b_dug, ro)); + RAD_ISSUE_N(c, E.op_p2, ro, brows(m.b_dug, ro), RAD_W(E.w_p2), RAD_W(E.b_p2), RAD_NONE, + brows(m.b_dua, ro)); + RAD_ISSUE_N(c, E.op_g, ro, brows(m.b_dua, ro), RAD_W(E.w_g), brows(m.b_dua, ro)); + RAD_ISSUE_N(c, E.op_add, ro, brows(y, ro), brows(m.b_dua, ro), brows(y, ro)); + R = ro; + } + /* The pre-quantiser transformer and its norm at the frames: z. */ + const int64_t F = R; + CtSet P = m.ecs; + P.x = m.b_ez; + RAD_ISSUE_N(c, m.op_epos, F, brows(m.b_epos, F)); + step_ct(c, m.pq, F, P, brows(m.b_epos, F), cu); + RAD_ISSUE_N(c, m.op_pqn, F, brows(m.b_ez, F), RAD_W(m.w_pqn), brows(m.b_ez, F)); + + /* The rows' codes: a token's everywhere, then each run of rows naming consecutive frames + * quantised step by step into its columns. */ + RAD_ISSUE_N(c, m.op_pc0, kPcW, brow_slice(m.b_pc, 0, 1, kPcW)); + RAD_ISSUE_N(c, m.op_pc1, (kCodes - 1) * kPcW, brow_slice(m.b_pc, 1, kCodes - 1, kPcW)); + const int64_t T = batch->n_tok; + for (int64_t t = 0; t < T;) { + const int32_t f = A->ref_frame_h[t]; + if (f < 0 || f >= F) { ++t; continue; } + int64_t n = 1; + while (t + n < T && A->ref_frame_h[t + n] == f + n && f + n < F) ++n; + for (int k = 0; k < kCodes; ++k) { + const EQuant& Q = m.eq[k]; + RAD_ISSUE_N(c, Q.op, n, brow_slice(m.b_ez, f, n, D), RAD_W(Q.in_w), RAD_W(Q.in_b), + RAD_W(Q.cb), RAD_W(Q.out_w), RAD_W(Q.out_b), + bcol_at(m.b_pc, k, kPcW, t, n, 1)); + } + t += n; + } +} + static void step_trunk(RadCtx* c, const RadBatch* batch, const Model& m) { const int64_t T = batch->n_tok; if (m.op_rope_cs && T <= qk_fuse_rows(m.g) && !rope_mixed(batch)) @@ -1407,6 +1904,7 @@ struct TowerAt { rad_buf h0 = 0; bool frame = false; RadOperand seed{}, fidx{}; + bool labels = false; /* PROMPT with references: labels off the rows' code plane */ }; static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) { @@ -1429,6 +1927,17 @@ static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) { RAD_ISSUE_N(c, L.op_eadd, R, brows(m.b_te, R), brows(m.b_ug, R), brows(m.b_te, R)); RAD_ISSUE_N(c, L.op_en, R, brows(m.b_te, R), RAD_W(L.w_en), bcol(m.b_tcat, 0, D, R)); } + if (at.labels) { + /* Row r's label: the code plane's column r + 1. */ + RAD_ISSUE_N(c, m.op_ptefill, R, brows(m.b_pte, R)); + RAD_ISSUE_N(c, L.op_pemb, R, bcol_at(m.b_pc, k < 0 ? 0 : k, kPcW, 1, R, 1), + RAD_W(L.w_emb), RAD_W(L.w_emb), brows(m.b_pte, R)); + if (L.op_peadd) + RAD_ISSUE_N(c, L.op_peadd, R, brows(m.b_pte, R), brows(m.b_pu, R), + brows(m.b_pte, R)); + RAD_ISSUE_N(c, L.op_pen, R, brows(m.b_pte, R), RAD_W(L.w_en), + bcol(m.b_tcat, 0, D, R)); + } RAD_ISSUE_N(c, L.op_hn, R, brows(i == 0 ? at.h0 : m.b_tho, R), RAD_W(L.w_hn), bcol(m.b_tcat, D, D, R)); RAD_ISSUE_N(c, L.op_eh, R, brows(m.b_tcat, R), RAD_W(L.w_eh), brows(m.b_tm, R)); @@ -1471,9 +1980,21 @@ static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) { static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { const RadAudioGenBatch* A = batch->agen_b; const int64_t T = batch->n_tok, D = m.g.n_embd; + /* References: their clips encoded into the rows' code plane first. */ + const bool refs = A->n_ref > 0; + if (refs) step_encode(c, batch, m); RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * D, brows(m.b_x, T), RAD_NONE); + RadOperand sec1 = RAD_W(m.w_cb), sec2 = RAD_W(m.w_cb), sec3 = RAD_W(m.w_cb); + sec1.rows = kVocab; + sec2.offset = kVocab * D; + sec2.rows = kVocab; + sec3.offset = 2 * kVocab * D; + sec3.rows = (kCodes - 3) * kVocab; + if (refs) + RAD_ISSUE_N(c, m.op_pfb, T, bcol_at(m.b_pc, 0, kPcW, 0, T, 2), RAD_W(m.w_cemb), sec1, + brows(m.b_x, T)); step_trunk(c, batch, m); /* The lane: the prompt's last hidden state, an empty window, no unseen codes. */ @@ -1486,12 +2007,24 @@ static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { { RadOperand w = brow_slice(m.b_ras, lane, 1, kRasWin); RAD_ISSUE_N(c, m.op_rasinit, kRasWin, w); + /* A reference's frames among the last rows are picks the window has seen. */ + if (refs && T >= kRasWin) + RAD_ISSUE_N(c, m.op_rascopy, kRasWin, + bcol_at(m.b_pc, 0, kPcW, T - kRasWin, kRasWin, 1), w); } - /* The tower over every prompt row: the label of each is text, so every code embedding is 0. - * The last row's pass is FRAME 0's, which writes its cache rows again. */ + /* The tower over every prompt row. A text prompt's labels are all text, so every code + * embedding is 0; with references a row before a frame is labelled with it, and a frame's row + * also carries its unseen codes (tower.py, prefill). The last row's pass is FRAME 0's, which + * writes its cache rows again. */ const RadKVGroupBatch* kvb = kv_batch(batch, m.kv_full); - RAD_ISSUE_N(c, m.op_efill, T, bcol(m.b_tcat, 0, D, T)); + if (!refs) { + RAD_ISSUE_N(c, m.op_efill, T, bcol(m.b_tcat, 0, D, T)); + } else { + RAD_ISSUE_N(c, m.op_pufill, T, brows(m.b_pu, T)); + RAD_ISSUE_N(c, m.op_pu, T, bcol_at(m.b_pc, 2, kPcW, 0, T, kCodes - 2), sec2, sec3, + brows(m.b_pu, T)); + } TowerAt at{}; at.R = T; at.max_q = batch->max_q_len; @@ -1501,6 +2034,7 @@ static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { at.used = praw(kvb->seqused, RAD_I32, batch->n_seq); at.cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); at.h0 = m.a_h.x; + at.labels = refs; step_tower(c, m, at); } @@ -1566,7 +2100,6 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { const RadAudioGenBatch* A = batch->agen_b; const int64_t nl = A->voc_latents, n = nl - A->voc_left, L = A->voc_lane; - const int64_t qd = kCtHeads * kCtHeadDim; /* The convolutions run over the last kConvFrames frames, or all of them when fewer. */ const int64_t nc = std::min(nl, kConvFrames), c0 = nl - nc; const RadOperand nlen = praw(batch->cu_seqlens + 1, RAD_I32, 1); @@ -1587,23 +2120,11 @@ static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { } /* 3. the transformer over every frame of the pass */ - const RadOperand pos = praw(batch->positions, RAD_I32, nl); - const RadOperand cu = brows(m.b_ccu[0], 2); - for (const CodecLayer& Ly : m.ct) { - RAD_ISSUE_N(c, Ly.op_n1, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n1), brows(m.b_ch, nl)); - RAD_ISSUE_N(c, Ly.op_qkv, nl, brows(m.b_ch, nl), RAD_W(Ly.w_qkv), brows(m.b_cqkv, nl)); - RAD_ISSUE_N(c, Ly.op_rope, nl, brows(m.b_cqkv, nl), pos); - RAD_ISSUE_N(c, Ly.op_attn, nl, bcol(m.b_cqkv, 0, qd, nl), bcol(m.b_cqkv, qd, qd, nl), - bcol(m.b_cqkv, 2 * qd, qd, nl), cu, brows(m.b_cattn, nl)); - RAD_ISSUE_N(c, Ly.op_o, nl, brows(m.b_cattn, nl), RAD_W(Ly.w_o), brows(m.b_co, nl)); - RAD_ISSUE_N(c, Ly.op_ls1, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls1), brows(m.b_co, nl)); - RAD_ISSUE_N(c, Ly.op_add1, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); - RAD_ISSUE_N(c, Ly.op_n2, nl, brows(m.b_cx, nl), RAD_W(Ly.w_n2), brows(m.b_ch, nl)); - RAD_ISSUE_N(c, Ly.op_gu, nl, brows(m.b_ch, nl), RAD_W(Ly.w_gu), brows(m.b_cgu, nl)); - RAD_ISSUE_N(c, Ly.op_act, nl, brows(m.b_cgu, nl), brows(m.b_cff, nl)); - RAD_ISSUE_N(c, Ly.op_down, nl, brows(m.b_cff, nl), RAD_W(Ly.w_down), brows(m.b_co, nl)); - RAD_ISSUE_N(c, Ly.op_ls2, nl, brows(m.b_co, nl), RAD_W(Ly.w_ls2), brows(m.b_co, nl)); - RAD_ISSUE_N(c, Ly.op_add2, nl, brows(m.b_cx, nl), brows(m.b_co, nl), brows(m.b_cx, nl)); + { + CtSet B; + B.x = m.b_cx; B.h = m.b_ch; B.qkv = m.b_cqkv; B.attn = m.b_cattn; B.o = m.b_co; + B.gu = m.b_cgu; B.ff = m.b_cff; + step_ct(c, m.ct, nl, B, praw(batch->positions, RAD_I32, nl), brows(m.b_ccu[0], 2)); } RAD_ISSUE_N(c, m.op_cn, nc, brow_slice(m.b_cx, c0, nc, kLat), RAD_W(m.w_cn), brows(m.b_ux[0], nc)); @@ -1766,13 +2287,28 @@ static std::string speaker_turns(const std::string& r) { return outs; } -/* generate.py's validate_drama3_text: the input is not empty, holds none of the tokens only the - * prompt builder writes, and names speakers only as <|speaker:0|> to <|speaker:15|>; then its - * speaker turns are written as the reference's server writes them (speaker_turns). */ +/* generate.py's build_drama3_prompt for a reference's transcript: speaker 0's tag and a space in + * front unless a tag leads after white space (with_speaker_tag), and white space ahead of a + * leading tag moved behind it, so the tag follows "Text: " directly. `r` is validated already. */ +static std::string reference_text(const std::string& r) { + const unsigned char* u = (const unsigned char*)r.data(); + size_t lead = 0; + for (size_t w; lead < r.size() && (w = white_space_at(u + lead, r.size() - lead)) > 0;) + lead += w; + const size_t tag = speaker_tag_at(r.data() + lead, r.size() - lead); + if (!tag) return "<|speaker:0|> " + r; + return r.substr(lead, tag) + r.substr(0, lead) + r.substr(lead + tag); +} + +/* generate.py's validate_drama3_text: the input, or a reference's transcript, is not empty, holds + * none of the tokens only the prompt builder writes, and names speakers only as <|speaker:0|> to + * <|speaker:15|>; then the input's speaker turns are written as the reference's server writes + * them (speaker_turns), and a transcript is tagged as its prompt builder tags it. */ static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { if (!in) return RAD_E_INVAL; std::string r = in; - if (field == RAD_TEXT_INPUT) { + if (field == RAD_TEXT_INPUT || field == RAD_TEXT_REFERENCE) { + const bool ref = field == RAD_TEXT_REFERENCE; const unsigned char* u = (const unsigned char*)r.data(); const size_t n = r.size(); size_t lead = 0; @@ -1783,21 +2319,23 @@ static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { if (w == 0) blank = false; else i += w; } - if (blank) return refuse(out, cap, "the input is empty: there is nothing to speak"); + if (blank) + return refuse(out, cap, ref ? "the reference's text is empty: it is what its clip says" + : "the input is empty: there is nothing to speak"); static const char* kStructural[] = { "<|im_start|>", "<|im_end|>", "<|voice|>", "<|text|>", "<|interleave|>", "<|semantic:" }; for (const char* t : kStructural) if (r.find(t) != std::string::npos) { char why[128]; - std::snprintf(why, sizeof why, "%s is written by the prompt builder, not the input", - t); + std::snprintf(why, sizeof why, "%s is written by the prompt builder, not %s", t, + ref ? "a reference's text" : "the input"); return refuse(out, cap, why); } for (size_t at = r.find("<|speaker"); at != std::string::npos; at = r.find("<|speaker", at + 1)) if (!speaker_tag_at(r.data() + at, n - at)) return refuse(out, cap, "speaker tags are <|speaker:0|> to <|speaker:15|>"); - r = speaker_turns(r); + r = ref ? reference_text(r) : speaker_turns(r); if (r.empty()) return refuse(out, cap, "the input is empty: there is nothing to speak"); } if ((int64_t)r.size() < cap) { diff --git a/data/recipes/drama3-fp8.recipe b/data/recipes/drama3-fp8.recipe index 9694078e..90e814a8 100644 --- a/data/recipes/drama3-fp8.recipe +++ b/data/recipes/drama3-fp8.recipe @@ -7,8 +7,10 @@ # The directory holds the model and codec.pth, its codec, which is read as checkpoint tensors # under `codec.` (core/format/torch_zip.h). The model is kept as stored. The codec ships f32: # its weight-normalised convolutions are folded here, and its linears, convolutions and -# codebooks cast to bf16, the precision fish-speech decodes at, while its norms, layer scales, -# ConvNeXt gains and snake parameters stay f32 -- read once a pass or less. +# codebooks cast to bf16, the precision fish-speech decodes and encodes at, while its norms, +# layer scales, ConvNeXt gains and snake parameters stay f32 -- read once a pass or less. The +# encoder's residual quantiser (codec.enc.vq*) stays f32 too: each step is an argmax over +# cosines, which f32 weights decide as the reference's f32 encoder does. codec.*.n1.weight cast dtype=f32 codec.*.n2.weight cast dtype=f32 @@ -18,4 +20,8 @@ codec.norm.weight cast dtype=f32 codec.up*.ln.* cast dtype=f32 codec.up*.gamma cast dtype=f32 codec.*.alpha cast dtype=f32 +codec.enc.*norm.weight cast dtype=f32 +codec.enc.down*.ln.* cast dtype=f32 +codec.enc.down*.gamma cast dtype=f32 +codec.enc.vq* cast dtype=f32 codec.* cast dtype=bf16 diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index d95d2cc1..dcb120c9 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -196,4 +196,48 @@ TEST(fishomni_writes_the_input_as_the_reference_server_does) { CHECK_EQ(std::string(buf), std::string(" calm ")); } +/* A reference's transcript as generate.py's build_drama3_prompt writes it after "Text: ": speaker + * 0's tag and a space before untagged text, which is otherwise kept as given; white space before a + * leading tag moved behind it. The input's rules refuse the same tokens. */ +TEST(fishomni_tags_a_reference_transcript_as_the_prompt_builder_does) { + Registry r; + const int st = r.load_dir(dir_of("architectures"), {}); + if (st == RAD_E_IO && r.plugins().empty()) + ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures")); + CHECK_OK(st); + const Plugin* p = r.plugin("fishomni"); + REQUIRE(p != nullptr); + REQUIRE(p->arch_text_prepare != nullptr); + auto prep = [&](const char* in, std::string* out) { + char buf[512] = {}; + const int64_t n = p->arch_text_prepare(RAD_TEXT_REFERENCE, in, buf, sizeof buf); + *out = buf; + return n; + }; + const struct { const char* in; const char* want; } ok[] = { + { "We asked over twenty people.", "<|speaker:0|> We asked over twenty people." }, + { " Two spaces kept. ", "<|speaker:0|> Two spaces kept. " }, + { " <|speaker:1|>Hi there", "<|speaker:1|> Hi there" }, + { "<|speaker:3|> Hello. <|speaker:4|> Hi.", "<|speaker:3|> Hello. <|speaker:4|> Hi." }, + }; + for (const auto& c : ok) { + std::string got; + const int64_t n = prep(c.in, &got); + if (got != c.want) fprintf(stderr, " '%s' -> '%s'\n", c.in, got.c_str()); + CHECK_EQ(n, (int64_t)std::strlen(c.want)); + CHECK_EQ(got, std::string(c.want)); + } + const struct { const char* in; const char* why; } refused[] = { + { " \n ", "empty" }, + { "Then <|im_start|> came", "<|im_start|>" }, + { "<|speaker:20|> hi", "speaker tags" }, + }; + for (const auto& c : refused) { + std::string why; + CHECK(prep(c.in, &why) < 0); + if (why.find(c.why) == std::string::npos) fprintf(stderr, " '%s': %s\n", c.in, why.c_str()); + CHECK(why.find(c.why) != std::string::npos); + } +} + RAD_TEST_MAIN() From b1f4fccc52f9fde1b88f28d89f2fa81f9b851d40 Mon Sep 17 00:00:00 2001 From: zivius Date: Wed, 21 Oct 2026 00:59:56 +0200 Subject: [PATCH 14/35] docs: drama-3's voice cloning -- the references field (clips, transcripts, speakers), its limits and cost, the encoder against fish-speech's, and how closely cloned takes follow their reference --- README.md | 8 +++++--- docs/ARCHITECTURES.md | 38 ++++++++++++++++++++++++++++++++++---- docs/GUIDE.md | 24 ++++++++++++++++++++---- 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 556397a4..1e4bd75d 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` | | MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | -| Fish Audio drama-3: speech with speaker tags and inline direction, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` | +| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | | GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | @@ -112,9 +112,11 @@ speech in a voice the request describes, made in 0.6 of its playing time on one streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written, over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it -(`<|speaker:1|>`, `[laughs]`), at 0.3 of its playing time on two cards, its first streamed audio +(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference +clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio 0.23 s after the request; under the Fish Audio Community License a service that lets others -generate speech with it needs a licence from Fish Audio. +generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs +their consent. ## Run with Docker diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 0774c1d8..bbc6a557 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -29,7 +29,7 @@ plugin claims. | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | | `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | | `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card | -| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC (`codec.pth`, read as data); from the release directory, two cards | +| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction, its voices cloned from reference clips: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC, encoder and decoder (`codec.pth`, read as data); from the release directory, two cards | | `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) | | `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card | @@ -1350,15 +1350,26 @@ codec Fish S2's modified DAC decoder: ten raw codebook rows of 8 (one of 409 conv k2 s2 and a ConvNeXt block; a causal conv k7 to 1536; four blocks of snake, a weight-normed causal transposed conv (8, 8, 4, 2) and three residual units (dilations 1, 3, 9); snake and a conv k7 to one channel, tanh: 2048 samples a frame, 44.1 kHz mono +encoder the codec's, for a reference clip (mono 44.1 kHz, padded to whole frames): a causal + weight-normed conv k7 to 64; four blocks of three residual units (snake, conv k7 at + dilations 1, 3, 9, snake, conv k1) and a snake and a causal conv of kernel two strides + (2, 4, 8, 8), doubling the channels; after the last a 4-layer transformer (window 512 + rows); snake, conv k3; twice a causal conv k2 s2 (plain weights) and a ConvNeXt block; + the 8-layer pre-quantiser transformer (window 128 frames); the semantic codebook's + nearest code by cosine, then nine residual steps (`vq_encode`): ten codes a frame ``` The passes, which shift the tower by a row against the reference's loop: - **PROMPT** runs the backbone over the prompt and leaves its last row's final-norm hidden state in the lane, then runs the tower over every row, teacher-forced: each row's label is the row after - it, which in a prompt is text, so every layer's code embedding is zero (the concatenation's - embedding half is filled with zeros once). The last row's tower pass belongs to the first frame; - FRAME 0 writes its cache rows again. + it, which in a text prompt is text, so every layer's code embedding is zero (the + concatenation's embedding half is filled with zeros once). With references the codec's encoder + first turns the request's clips into frames, written into a code plane at the prompt rows that + name them (`RadAudioGenBatch::ref_frame`); a frame's row is embedded as a made frame's is, a row + before a frame is labelled with it, a frame's row carries its own codes 2..9, and the window of + main picks starts with the prompt's last 16 rows. The last row's tower pass belongs to the first + frame; FRAME 0 writes its cache rows again. - **FRAME j** draws the main token from the hidden state of the row before the frame's (the prompt's last for frame 0), runs the tower at THAT row's position, cache slot and context (`RadAudioGenBatch::prev_slot`, `prev_pos`, `prev_used`) drawing codes 1..9, stores the frame, @@ -1383,6 +1394,13 @@ Traps (each still speaks, wrongly): - **The codec's residual codebooks have 1024 entries** and the heads 4096 outputs: codes are clamped at 1023 at decode (`rvq_embed`'s `clamp`). Its weight norm is per output channel for the convs and per INPUT channel for the transposed convs (`[in, out, k]`), folded at convert. +- **The encoder's transformer window is 512 rows**, not the 128 frames of the quantiser's: the + window comes from `getattr` on a `functools.partial` config, which has no such attribute, so + fish-speech's default of 512 holds. Both its transformers and the codec's convolutions are + causal, so a clip right-padded to whole frames encodes its frames as the clip alone would. +- **The reference prompt is tokenised a literal at a time**: the instruction's closing `:` and the + first header's `\n\n` are one token when the two are joined. A transcript's speaker tag must + follow `Text: ` directly, so white space before it moves behind it. - **The input is written as fish-speech's server writes it**: each speaker's turn `<|speaker:N|> ` and its text stripped, turns joined by a newline, untagged text speaker 0's. The same two turns joined by a space are spoken through far less often: for one two-line script, @@ -1399,6 +1417,18 @@ over the 79 frames that are spoken. Through the codec, radiance's chunked bf16 d from the reference's whole-utterance bf16 decode of the same codes. Qwen3-ASR transcribes radiance's speech word for word. +The encoder against fish-speech's codec encoding the same clip (11.6 s, 250 frames) on the CPU: +radiance's bf16 encoder gives the f32 reference's semantic code in 99.2% of the frames, and its +residual codes in 97.6% (the first) down to 81.2% (the ninth); fish-speech's own bf16 encode gives +95.6% and 94.0% down to 71.2% against the same f32. The reference prompt's token ids are +fish-speech's. Cloning, scored by median F0 and Qwen3-ASR over eight seeds a case, the reference +clips drama-3's own takes of invented sentences: without a reference a sentence's eight takes are +eight voices (116 to 251 Hz); with a reference of a 188 Hz voice they come out at 175 to 210 Hz, +of a 200 Hz voice at 197 to 250 Hz, of a 108 Hz voice at 96 to 122 Hz; two references tagged as +speakers 0 and 1 voice a two-line exchange's turns at 193 to 210 Hz and 109 to 140 Hz. Every take +but one is transcribed word for word (the miss is "I'm" for "I am"). A 12 s clip adds 0.12 s +before a stream's first audio. + The sampling is not fish-speech's server's (temperature 0.7, top-p 0.7, top-k 30 for every draw). At those the model falls silent after a tag or a speaker's line and does not come back, the failure vLLM-Omni's recipe and SGLang-Omni's notes describe; SGLang-Omni's comment puts it on the main diff --git a/docs/GUIDE.md b/docs/GUIDE.md index b183f376..4bc18da1 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2460,6 +2460,11 @@ curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{ "input": "<|speaker:0|> Did you lock the back door?\n<|speaker:1|> [sighs] I thought you did."}' \ -o door.wav # 44.1 kHz mono, 16-bit +curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d @- \ + -o cloned.wav <` to `<|speaker:15|>`, and @@ -2471,10 +2476,20 @@ curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json `<|im_end|>`, `<|voice|>`, `<|text|>`, `<|interleave|>`, `<|semantic:...|>`) are refused, and so is any other spelling of a speaker. - **`instructions` are refused**, the direction being the input's; `guidance_scale` must be 1 (the - model runs one branch). Each speaker's voice is the model's choice, the same within a take: - cloning a voice from a recording is not served yet. + model runs one branch). Without references each speaker's voice is the model's choice, the same + within a take. +- **`references`** clone voices from recordings: an array of `{"audio": ..., "text": ...}`, the + clip a `data:` URL or the base64 of an audio file (anything ffmpeg reads, decoded to mono + 44.1 kHz), its text what the clip says; at most 8 clips and 30 s of audio together. A + reference's voice is the speaker its transcript is tagged with, speaker 0 when untagged, so a + dialogue gives each speaker a clip: `"<|speaker:1|> ..."` as the second reference's text voices + the input's `<|speaker:1|>` turns. The clips are encoded by the codec's own encoder in the + request's first pass, in bf16 as fish-speech's server encodes them (a 12 s clip adds about + 0.12 s before the first audio), and the prompt is fish-speech's with references: + `[Reference 1]`, its transcript and its frames, for each. - **The length** is `duration` in seconds or `max_new_tokens` in frames (21.5 a second), up to 95 s; - the model ends the speech at the end of the script. The prompt holds at most 2048 tokens. + the model ends the speech at the end of the script. The prompt holds at most 3072 tokens, a + reference adding 21.5 a second of its clip. - **Sampling** is SGLang-Omni's: temperature 1.0 and top-p 0.9 (Fish Audio's model card), the first code uncapped and each later code at top-k 30, with fish-speech's repetition-aware redraw of the first code. fish-speech's server samples at 0.7, 0.7 and 30, where the model often falls @@ -2550,7 +2565,8 @@ is complete, so the first audio waits for the first sentence rather than the who - **`session.config`** takes the fields of `POST /v1/audio/speech` but `input` (`instructions`, `voice`, `seed`, `guidance_scale`, `max_new_tokens` or `duration` for each sentence, `speed`, - `num_inference_steps` where the model has a denoiser), checked as that route checks them, and + `num_inference_steps` where the model has a denoiser, `references` where it clones a voice), + checked as that route checks them, and four of its own: `response_format` `pcm` (the default) or `wav`; `stream_audio`, false (the default) for one binary message a sentence or true for the audio as the model makes it; `split_granularity`, `sentence` (the default), `clause` (also at commas and semicolons) or `none` From 87701cb6b801bcd4de9398e100747f5f55222900 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:15 +0200 Subject: [PATCH 15/35] libr4d: mla_attn_rows_bf16 -- one key load for all 64 heads of a query row A third mla_attn row, at 64 heads. A workgroup takes one query row and all its heads, four waves to each group of sixteen, and loads each 16-token key chunk once for all of them, where the matrix row loads it once a tile of sixteen. The scores are K Q^T, tokens as the tile's rows and heads as its columns, so a head's running maximum and denominator stay in its lane; the waves of a group each take a quarter of the latent's dot products and add the four partials in one order, and the probabilities reach the value product through a permlanex16 swap instead of LDS. The next chunk's keys are fetched into registers while the current one is multiplied, two barriers a chunk. A row's bytes do not depend on the other rows of the batch. Under 32 rows the launcher runs the matrix row's kernel; r4d_mla_rows_pin_form, a test hook, pins the element-wise key load, 32 heads a workgroup, the rows kernel at any row count, or the matrix row's kernel at every row count (the form a KL measurement needs to tell this kernel's share of a row split's difference). Measured on gfx1201 (r4d_selftest --perfmla, one sequence past the DSA budget at 16k of context, 513 blocks): 512 rows x 64 heads take 3.9 ms, 35 TFLOP/s, against 12.3 ms on the matrix row, and the 4096 rows x 8 heads they stand for in a TP8 prefill chunk 14.0 ms on the paired union tile. Against the wave row the output stays within the matrix row's tolerance (max abs 2.4e-4 at 513 blocks). r4d_selftest checks it against libref at 1 to 33 rows, 32 and 64 heads, every fill and both key loads, and times it against the matrix row (--case mla_attn_rows_bf16, --perfmla at 64 heads). r4d_emu_mla runs it on the host against an f64 softmax, its forms bit for bit against each other, a run of rows against the same rows of the whole batch, and a mixed TP step (decodes, a verify window, a prefill past the budget, a fresh chunk) split by heads over the matrix row and by rows over this one, at runs that do and do not divide the step. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 14 +- libr4d/r4d.h | 4 + libr4d/r4d_mla.hip | 240 ++++++++++++++++++++++++ libr4d/r4d_plugin.h | 1 + libr4d/r4d_rows.cpp | 16 ++ libr4d/r4d_selftest.cpp | 58 ++++-- tests/plugin_test.cpp | 8 +- tests/r4d_emu/test_mla.cpp | 370 ++++++++++++++++++++++++++++++++----- 8 files changed, 645 insertions(+), 66 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index bfc09401..feb942c2 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2836,7 +2836,7 @@ contributes nothing, and a row with no visible key outputs zero. The softmax is rounded once. `scale` is positive and finite and comes from the original query/key head width, not the latent width (GLM: `1/sqrt(256)` against a latent of 512). -libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The +libr4d has three `mla_attn` rows, all at `latent_dim` 512, `block_size` 4 and up to 64 heads. The matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of @@ -2848,6 +2848,18 @@ by table position, with a second pass where the two differ. Other head counts ta workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks reserve; without scratch they compute unsplit. +At exactly 64 heads the rows row, `mla_attn_rows_bf16`, ranks above both. A workgroup takes one +query row and all its heads, four waves to each group of sixteen, and loads each 16-token key chunk +once for all of them, where the matrix row loads it once a tile of sixteen. The scores are +`K Q^T`, tokens as the tile's rows and heads as its columns, so a head's running maximum and +denominator stay in its lane; the four waves of a group each take a quarter of the latent's dot +products and add the four partials in one order, and the probabilities reach the value product +through a lane swap instead of LDS. The next chunk's keys are fetched while the current one is +multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives +the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher +runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a +workgroup), which no constraint routes to it. + `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. `mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored, diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 32463fa6..99a588b2 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -688,6 +688,10 @@ void r4d_hc_read_pin_prefill(int form); // wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to. // Bit-identical; r4d_selftest compares them and --perfmla times both. void r4d_mla_matrix_pin_form(int form); +// Test hook: pins the MLA rows row's form. 0 is the launcher's rule (64 heads a workgroup, vector +// key loads where aligned; the matrix row's kernel under 32 rows), 1 the element-wise key load +// (bit-identical to 3), 2 32 heads a workgroup, 3 the rows kernel of the rule at any row count. +void r4d_mla_rows_pin_form(int form); // Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the // next call, and returns how many launches the previous recording saw (which may exceed its cap). // Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip index 58f93126..d4d2c0d4 100644 --- a/libr4d/r4d_mla.hip +++ b/libr4d/r4d_mla.hip @@ -537,6 +537,178 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16); } } +/* ROWS gives a workgroup one query row and HG groups of sixteen heads, four waves a group, so a + * key chunk is loaded once for 16*HG heads instead of the head-tiled row's sixteen. GLM's prefill + * splits attention by rows, one rank holding all 64 heads of its rows; that is what this serves. + * + * Scores are S^T = K Q^T: tokens are the matrix rows and heads the columns, so a head is a lane + * and its running maximum and denominator stay in registers. Each wave of a group takes a quarter + * of the latent dimension; the four partial dot products meet in LDS and every wave of the group + * adds them in the same order, so all four hold identical scores and statistics. The + * probabilities become the second product's B operand with one permlanex16 swap, and each wave + * accumulates O^T for its quarter of the latent columns, the keys read transposed from the tile. + * The next chunk's keys are fetched into registers while the current one is multiplied, so a + * chunk costs two barriers. */ +constexpr int kRowsPitch = 520; +template +__global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const uint16_t* kv, + const int* bt, const int* len, + uint16_t* out, float* scratch, Meta m) { + constexpr int NT = HG * 128, LOADS = 16 * 64 / NT; + static_assert(LOADS * NT == 16 * 64 && LOADS <= 32, "a chunk's 16-byte pieces over the group"); + __shared__ __align__(16) uint16_t keys[2][16 * kRowsPitch]; + __shared__ __align__(32) float partial[HG * 4][32 * 8]; + __shared__ int visible[2][16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, quarter = wave & 3, + group = wave >> 2, r = blockIdx.x, split = blockIdx.z; + const int head = blockIdx.y * 16 * HG + group * 16 + (lane & 15); + const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs); + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + v8bf query[8]; + { + const uint16_t* qp = + q + (long)r * m.qr + (long)head * m.qh + quarter * 128 + 4 * (lane >> 4); +#pragma unroll + for (int s = 0; s < 8; ++s) { + union { + uint16_t h[8]; + v8bf f; + } u; +#pragma unroll + for (int e = 0; e < 4; ++e) { + u.h[e] = qp[s * 16 + e]; + u.h[4 + e] = qp[s * 16 + 8 + e]; + } + query[s] = u.f; + } + } + uint4 staged[LOADS]; + unsigned staged_ok = 0; + auto fetch = [&](int start) { +#pragma unroll + for (int j = 0; j < LOADS; ++j) { + const int flat = tid + j * NT, token = start + (flat >> 6), piece = flat & 63; + const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1; + const bool ok = page >= 0 && page < m.pages; + const long at = ok ? (long)page * m.kp + (token % m.bs) * m.kt + piece * 8 : 0; + if constexpr (WIDE) { + staged[j] = *(const uint4*)(kv + at); + if (!ok) staged[j] = make_uint4(0, 0, 0, 0); + } else { + uint32_t w[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) + w[i] = ok ? (uint32_t)kv[at + 2 * i] | (uint32_t)kv[at + 2 * i + 1] << 16 : 0u; + staged[j] = make_uint4(w[0], w[1], w[2], w[3]); + } + staged_ok = ok ? staged_ok | 1u << j : staged_ok & ~(1u << j); + } + }; + auto stash = [&](int b) { +#pragma unroll + for (int j = 0; j < LOADS; ++j) { + const int flat = tid + j * NT, token = flat >> 6, piece = flat & 63; + *(uint4*)(keys[b] + token * kRowsPitch + piece * 8) = staged[j]; + if (!piece) visible[b][token] = (int)(staged_ok >> j & 1u); + } + }; + v8f value[8]; +#pragma unroll + for (int mt = 0; mt < 8; ++mt) value[mt] = (v8f){ 0 }; + float run_max = -INFINITY, run_den = 0; + fetch(begin); + stash(0); + __syncthreads(); + int buf = 0; + for (int start = begin; start < end; start += 16) { + const bool more = start + 16 < end; + if (more) fetch(start + 16); + const uint16_t* tile = keys[buf]; + v8f dot = { 0 }; +#pragma unroll + for (int s = 0; s < 8; ++s) + dot = mma(frag(tile, kRowsPitch, 0, quarter * 128 + s * 16, lane), query[s], dot); + *(v8f*)&partial[wave][lane * 8] = dot; + __syncthreads(); + v8f score = *(const v8f*)&partial[group * 4][lane * 8]; +#pragma unroll + for (int k = 1; k < 4; ++k) score += *(const v8f*)&partial[group * 4 + k][lane * 8]; + float chunk_max = -INFINITY; +#pragma unroll + for (int e = 0; e < 8; ++e) { + score[e] = visible[buf][8 * (lane >> 4) + e] ? score[e] * m.scale : -INFINITY; + chunk_max = fmaxf(chunk_max, score[e]); + } + chunk_max = fmaxf(chunk_max, swap16(chunk_max)); + const float next_max = fmaxf(run_max, chunk_max); + const float alpha = isfinite(next_max) ? expf(run_max - next_max) : 1; + float p[8], sum = 0; +#pragma unroll + for (int e = 0; e < 8; ++e) { + p[e] = isfinite(score[e]) ? expf(score[e] - next_max) : 0; + sum += p[e]; + } + /* Both halves add tokens 0-7 before 8-15, so the sixteen lanes of a head agree. */ + const float other = swap16(sum); + run_den = run_den * alpha + (lane < 16 ? sum + other : other + sum); + run_max = next_max; + /* A B fragment's lane holds its head's tokens 0-3 and 8-11 (lanes 0-15) or 4-7 and 12-15 + * (16-31); a score lane holds 0-7 or 8-15. Each half sends the other the four it needs. */ + uint32_t hi[4], lo[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const uint16_t h0 = f32_to_bf16(p[2 * i]), h1 = f32_to_bf16(p[2 * i + 1]); + hi[i] = (uint32_t)h0 | (uint32_t)h1 << 16; + lo[i] = (uint32_t)f32_to_bf16(p[2 * i] - bf16_to_f32(h0)) | + (uint32_t)f32_to_bf16(p[2 * i + 1] - bf16_to_f32(h1)) << 16; + } + const bool low = lane < 16; + const uint32_t hx0 = r4d_xor_lane_u32<16>(low ? hi[2] : hi[0]), + hx1 = r4d_xor_lane_u32<16>(low ? hi[3] : hi[1]), + lx0 = r4d_xor_lane_u32<16>(low ? lo[2] : lo[0]), + lx1 = r4d_xor_lane_u32<16>(low ? lo[3] : lo[1]); + union { + uint32_t w[4]; + v8bf f; + } ph, pl; + ph.w[0] = low ? hi[0] : hx0; + ph.w[1] = low ? hi[1] : hx1; + ph.w[2] = low ? hx0 : hi[2]; + ph.w[3] = low ? hx1 : hi[3]; + pl.w[0] = low ? lo[0] : lx0; + pl.w[1] = low ? lo[1] : lx1; + pl.w[2] = low ? lx0 : lo[2]; + pl.w[3] = low ? lx1 : lo[3]; +#pragma unroll + for (int mt = 0; mt < 8; ++mt) { + const auto v = fragT(tile, kRowsPitch, quarter * 128 + mt * 16, 0, lane); + value[mt] *= alpha; + value[mt] = mma(v, ph.f, value[mt]); + value[mt] = mma(v, pl.f, value[mt]); + } + if (more) stash(buf ^ 1); + __syncthreads(); + buf ^= 1; + } +#pragma unroll + for (int mt = 0; mt < 8; ++mt) +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int col = quarter * 128 + mt * 16 + 8 * (lane >> 4) + e; + if (m.splits == 1) + out[(long)r * m.orr + (long)head * m.oh + col] = + f32_to_bf16(run_den > 0 ? value[mt][e] / run_den : 0); + else + scratch[(((long)r * m.heads + head) * m.splits + split) * PART + col] = + value[mt][e]; + } + if (m.splits > 1 && !quarter && lane < 16) { + float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART; + dst[D] = run_max; + dst[D + 1] = run_den; + } +} bool env_on(const char* name) { const char* e = std::getenv(name); return e && *e && *e != '0'; @@ -643,6 +815,70 @@ int body(const RadArgs* a, RadStream stream) { if (rc == RAD_OK && stats) report_stats(stream); return rc; } +/* r4d_mla_rows_pin_form: 0 is the launcher's rule (64 heads a workgroup, vector key loads where + * the cache is aligned, the matrix row's kernel under kRowsMin rows), 1 the element-wise key load, + * 2 thirty-two heads a workgroup, 3 the rule's rows kernel at any row count, 4 the matrix row's + * kernel at every row count. The pin is a test hook (r4d_selftest, r4d_emu); nothing else sets + * it. */ +int g_mla_rows_form = 0; +/* Under it, a decode step's rows at one rank, a workgroup a row leaves the card mostly idle, and + * the matrix row's four tiles a row and its splits are faster (r4d_selftest --case + * mla_attn_rows_bf16, M 7: 0.5x). */ +constexpr long kRowsMin = 32; +int rows_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4]; + if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || + len.dtype != RAD_I32) + return RAD_E_DTYPE; + for (int i = 0; i < 5; ++i) + if (!a->t[i].data) return RAD_E_INVAL; + const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0); + const float scale = (float)r4d_getf(a, "scale", 0); + if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 || + !std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 || + q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 || + q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 || + kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D || + kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || + bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs || + bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 || + len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 || + o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 || + o.stride[1] < D || o.stride[0] < heads * o.stride[1]) + return RAD_E_SHAPE; + if (heads % 32) return RAD_E_UNSUPPORTED; + const int form = g_mla_rows_form; + if (form == 4 || (!form && q.shape[0] < kRowsMin)) return body(a, stream); + const int group_heads = heads % 64 || form == 2 ? 32 : 64; + const long rows = q.shape[0], groups = heads / group_heads, jobs = rows * groups; + /* Short batches split the history until 64 workgroups run, two to each of the R9700's 32 + * WGPs, as far as 16-token chunks and the scratch's 2048 partials allow. */ + int splits = (int)std::min(64l, (64 + jobs - 1) / jobs); + splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + 15) / 16)); + splits = (int)std::max(1l, std::min((long)splits, 2048 / (rows * heads))); + if (!a->scratch || a->scratch_bytes < matrix_scratch_bytes) splits = 1; + const bool wide = form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) && + !(kv.stride[2] % 8); + Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2], + bt.stride[0], bt.stride[1], len.stride[0], o.stride[0], + o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1], + (int)bs, (int)kv.shape[0], splits, scale }; +#define ROWS_EMIT(HG, W) \ + R4D_EMIT(stream, (attend_rows), dim3(m.rows, (unsigned)groups, m.splits), \ + dim3(HG * 128), 0, (const uint16_t*)q.data, (const uint16_t*)kv.data, \ + (const int*)bt.data, (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m) + int rc; + if (group_heads == 64) + rc = wide ? ROWS_EMIT(4, true) : ROWS_EMIT(4, false); + else + rc = wide ? ROWS_EMIT(2, true) : ROWS_EMIT(2, false); +#undef ROWS_EMIT + if (rc == RAD_OK && splits > 1) + rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0, + (const float*)a->scratch, (uint16_t*)o.data, m); + return rc; +} } extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) { return body(a, stream); @@ -650,12 +886,16 @@ extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) { extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) { return body(a, stream); } +extern "C" int r4d_rad_mla_attn_rows(const RadArgs* a, RadStream stream) { + return rows_body(a, stream); +} extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) { return project_body(a, stream); } extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; } extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; } extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; } +extern "C" void r4d_mla_rows_pin_form(int form) { g_mla_rows_form = form; } /* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes, * second passes, raster chunks), then zeroed. */ extern "C" void r4d_mla_matrix_stats(unsigned long long* out) { diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index c3e4c7aa..d8b8c2ea 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -698,6 +698,7 @@ int r4d_rad_mla_attn(const RadArgs*, RadStream); int64_t r4d_rad_mla_attn_scratch(const RadArgs*); int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream); int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*); +int r4d_rad_mla_attn_rows(const RadArgs*, RadStream); int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream); int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 746340cb..e4446f9d 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4266,6 +4266,16 @@ static const RadConstraint cMlaMatrix[] = { C_GE("M", 1), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16") }; +/* GLM's prefill splits MLA by rows, a rank holding every head of its rows: the rows row loads a + * key chunk once for a workgroup of 64 heads and outranks the matrix row there. Measured on gfx1201 + * (r4d_selftest --perfmla 512 513 64 20 topk:16:16000), a rank's run of 512 rows takes 3.9 ms + * against 12.3 ms on the matrix row, and the 4096 rows x 8 heads it replaces 14.0 ms on the paired + * matrix row. Under 32 rows its launcher runs the matrix row's kernel (r4d_mla.hip); a bound on M + * here would cut every mla_attn band at 32, the eight-head ones too. */ +static const RadConstraint cMlaRows[] = { C_GE("M", 1), C_LE("M", 65535), + C_EQ("latent_dim", 512), C_EQ("heads", 64), + C_GE("blocks", 1), C_EQ("block_size", 4), + C_IN("dtype", "bf16") }; /* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase; * 28672 elements is that budget at hc 4. */ static const RadConstraint cMtpEnter[] = { @@ -5541,6 +5551,12 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr, r4d_shape_scale }, +{ "mla_attn_rows_bf16", "mla_attn", "attn", "row-tiled WMMA latent attention, one key load for 64 heads", + "latent_dim=512, heads=64, block_size=4", + "bf16 operands; FP32 probabilities via high/low BF16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 2, ROW(cMlaRows), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn_rows, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr, + r4d_shape_mla_attn }, { "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax", "latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4", "bf16 operands; FP32 probabilities via high/low BF16", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 0fb90270..66df3417 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -144,6 +144,7 @@ struct Plugin { void (*pin_qsel)(int) = nullptr; void (*pin_mla)(int) = nullptr; void (*mla_stats)(unsigned long long*) = nullptr; + void (*pin_mla_rows)(int) = nullptr; int (*record)(const void**, int) = nullptr; }; @@ -181,6 +182,7 @@ static bool load(Plugin* pl, const char* path) { okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel); okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla); okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats); + okall &= sym(pl->h, "r4d_mla_rows_pin_form", &pl->pin_mla_rows); okall &= sym(pl->h, "r4d_record_dispatches", &pl->record); return okall; } @@ -14008,25 +14010,28 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo const int rc = oracle->launch(&args, nullptr); ok("MLA host oracle", rc == RAD_OK); args.t = device.data(); - /* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix); - * other head counts must be refused rather than computed. */ - if (std::strstr(name, "matrix") && heads % 8) { + /* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix), + * the rows row groups of 32 or 64 heads; other head counts must be refused rather than + * computed. */ + const bool by_rows = std::strstr(name, "rows") != nullptr; + auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla; + if ((std::strstr(name, "matrix") && heads % 8) || (by_rows && heads % 32)) { args.scratch = nullptr; args.scratch_bytes = 0; const int grc = row->launch(&args, nullptr); st_stream_sync(nullptr); - ok(fmt("MLA %s refuses heads=%lld (not a multiple of 8) with RAD_E_UNSUPPORTED, no launch", - name, (long long)heads) + ok(fmt("MLA %s refuses heads=%lld (not a multiple of %d) with RAD_E_UNSUPPORTED, no launch", + name, (long long)heads, by_rows ? 32 : 8) .c_str(), grc == RAD_E_UNSUPPORTED); dlclose(ref); return; } - if (form && pl.pin_mla) pl.pin_mla(form); + if (form && pin) pin(form); const int64_t need = row->scratch ? row->scratch(&args) : 0; void* scratch = need > 0 ? dalloc((size_t)need + 256) : nullptr; if (need <= 0 || !scratch) { - if (form && pl.pin_mla) pl.pin_mla(0); + if (form && pin) pin(0); ok("MLA scratch allocation", false); dlclose(ref); return; @@ -14095,7 +14100,7 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo versus, base, name, base / us, shape); } } - if (form && pl.pin_mla) pl.pin_mla(0); + if (form && pin) pin(0); dlclose(ref); } @@ -14205,17 +14210,19 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, PS("dtype", "bf16") }; std::vector base, rule; auto run = [&](const char* name, int form, const char* label) { + const bool by_rows = std::strstr(name, "rows") != nullptr; + auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla; const RadKernelInfo* r = find(pl, name); if (!r) { std::printf(" %-34s row absent\n", label); return; } if (form >= 0) { - if (!pl.pin_mla) { + if (!pin) { std::printf(" %-34s no pin hook\n", label); return; } - pl.pin_mla(form); + pin(form); } RadArgs a; std::memset(&a, 0, sizeof(a)); @@ -14232,7 +14239,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, const int rc = r->launch(&a, nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf(" %-34s rc=%d (shape not served)\n", label, rc); - if (form >= 0) pl.pin_mla(0); + if (form >= 0) pin(0); return; } std::vector got(qh.size()); @@ -14253,7 +14260,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, st_ev_destroy(w1); } const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); - if (form >= 0) pl.pin_mla(0); + if (form >= 0) pin(0); char diff[192] = "reference"; if (base.empty()) base = got; @@ -14279,7 +14286,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, } if (form == 0) rule = got; std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff); - if (form >= 0 && pl.mla_stats) { + if (form >= 0 && !by_rows && pl.mla_stats) { /* One more launch with the conflict counters on, outside the timing. */ ScopedEnv counting("RADIANCE_MLA_CONFLICT_STATS", "1"); unsigned long long v[3]; @@ -14308,6 +14315,11 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load"); run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load"); } + if (heads == 64) { + run("mla_attn_rows_bf16", 0, "rows 64 heads, vector load"); + run("mla_attn_rows_bf16", 1, "rows 64 heads, element load"); + run("mla_attn_rows_bf16", 2, "rows 32 heads, vector load"); + } } static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepted_count, @@ -26663,6 +26675,26 @@ static void device_phase(const Plugin& pl) { for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); } } + if (sel("mla_attn_rows_bf16")) { + /* A rank's run of rows with all 64 heads (GLM's prefill split by rows), against the matrix + * row on the same operands. Under 32 rows the rule runs the matrix kernel, so the rows + * kernel is pinned there (form 3). */ + for (int requests : { 1, 2, 7, 33 }) + for (int64_t blocks : { 17, 513 }) + mla_check(pl, requests, 64, blocks, "mla_attn_rows_bf16", MlaFill::ragged, + "mla_attn_matrix_bf16", requests < 32 ? 3 : 0); + mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::full, "mla_attn_matrix_bf16", 3); + mla_check(pl, 2, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16", 3); + mla_check(pl, 33, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16"); + for (int64_t swaps : { 0, 4, 16, 64 }) + mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16", + 0, swaps); + mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, nullptr, 1); + mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, nullptr, 2, 16); + mla_check(pl, 7, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16", 0, 4); + mla_check(pl, 7, 32, 65, "mla_attn_rows_bf16", MlaFill::ragged, nullptr, 3); + mla_check(pl, 4, 40, 17, "mla_attn_rows_bf16"); + } if (sel("mla_attn_matrix_bf16")) { mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16"); mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16"); diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 4dd0689f..9699bcde 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -996,7 +996,8 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) { } /* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves - * every M up to its bound, a decode step's rows and a prefill chunk alike. */ + * every M up to its bound, a decode step's rows and a prefill chunk alike. At 64 heads the rows + * row ranks above both. */ TEST(libr4d_resolves_the_mla_attention_by_rows) { const std::string so = libr4d(); if (so.empty()) return; @@ -1010,6 +1011,11 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) { g.set_s("dtype", "bf16"); CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 "); CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 "); + // All 64 heads of a row, as GLM's prefill split by rows runs it: the rows row. + g.set_i("heads", 64); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_rows_bf16 "); + g.set_i("heads", 16); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_matrix_bf16 "); } /* ================================================================== constraints that are not intervals */ diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp index 95d125c7..e02eb53c 100644 --- a/tests/r4d_emu/test_mla.cpp +++ b/tests/r4d_emu/test_mla.cpp @@ -5,7 +5,9 @@ * blocks and neighbours share most blocks but rarely a table position. The conflict counters * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the * same operands: the union at the case's table width, the positional pairing on the table - * widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */ + * widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. + * The rows row (attend_rows, 64 heads of one row a workgroup) runs on its own cases, and a mixed + * TP step runs both ways, split by heads over the matrix row and by rows over the rows row. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -21,6 +23,7 @@ extern "C" void r4d_mla_matrix_pin_form(int form); extern "C" void r4d_mla_matrix_stats(unsigned long long* out); +extern "C" void r4d_mla_rows_pin_form(int form); namespace { @@ -106,9 +109,9 @@ void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng } } -int run(const Case& c, std::mt19937& rng) { - const int M = c.rows, H = c.heads, B = c.blocks; - std::vector bt, len; +/* The case's page tables and visible lengths; returns the pages the cache holds. */ +int fill_tables(const Case& c, std::mt19937& rng, std::vector& bt, std::vector& len) { + const int M = c.rows, B = c.blocks; int pages = 0; if (c.fill == Fill::topk) { topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages); @@ -144,25 +147,73 @@ int run(const Case& c, std::mt19937& rng) { len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7; } } + return pages; +} + +RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; +} + +/* An f64 softmax over each row's own table. */ +std::vector reference(int M, int H, int B, int pages, const std::vector& bt, + const std::vector& len, const std::vector& qb, + const std::vector& kvb, double scale) { + std::vector want((size_t)M * H * D); + std::vector sc; + for (int r = 0; r < M; ++r) + for (int h = 0; h < H; ++h) { + const int live = std::min(std::max(len[r], 0), B * BS); + sc.assign(live, -INFINITY); + double mx = -INFINITY; + auto row_of = [&](int j) -> const uint16_t* { + const int pg = bt[(size_t)r * B + j / BS]; + return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr; + }; + const uint16_t* qr = &qb[((size_t)r * H + h) * D]; + for (int j = 0; j < live; ++j) { + const uint16_t* k = row_of(j); + if (!k) continue; + double dot = 0; + for (int d = 0; d < D; ++d) + dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]); + sc[j] = dot * scale; + mx = std::max(mx, sc[j]); + } + std::vector acc(D, 0.0); + double sum = 0; + for (int j = 0; j < live; ++j) { + if (sc[j] == -INFINITY) continue; + const double w = std::exp(sc[j] - mx); + sum += w; + const uint16_t* k = row_of(j); + for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]); + } + for (int d = 0; d < D; ++d) + want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; + } + return want; +} + +int run(const Case& c, std::mt19937& rng) { + const int M = c.rows, H = c.heads, B = c.blocks; + std::vector bt, len; + const int pages = fill_tables(c, rng, bt, len); std::normal_distribution nrm(0.f, 1.f); std::vector qb((size_t)M * H * D), kvb((size_t)pages * BS * D); for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); std::vector out((size_t)M * H * D, 0xffff); - auto tens = [](void* p, uint32_t dt, std::vector shape) { - RadTensor t{}; - t.data = p; - t.dtype = dt; - t.rank = (uint32_t)shape.size(); - int64_t st = 1; - for (int i = (int)shape.size() - 1; i >= 0; --i) { - t.shape[i] = shape[i]; - t.stride[i] = st; - st *= shape[i]; - } - return t; - }; RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }), tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }), @@ -202,40 +253,7 @@ int run(const Case& c, std::mt19937& rng) { a.scratch_bytes = need; } - /* the f64 reference */ - std::vector want((size_t)M * H * D); - std::vector sc; - for (int r = 0; r < M; ++r) - for (int h = 0; h < H; ++h) { - const int live = std::min(std::max(len[r], 0), B * BS); - sc.assign(live, -INFINITY); - double mx = -INFINITY; - auto row_of = [&](int j) -> const uint16_t* { - const int pg = bt[(size_t)r * B + j / BS]; - return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr; - }; - const uint16_t* qr = &qb[((size_t)r * H + h) * D]; - for (int j = 0; j < live; ++j) { - const uint16_t* k = row_of(j); - if (!k) continue; - double dot = 0; - for (int d = 0; d < D; ++d) - dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]); - sc[j] = dot * scale; - mx = std::max(mx, sc[j]); - } - std::vector acc(D, 0.0); - double sum = 0; - for (int j = 0; j < live; ++j) { - if (sc[j] == -INFINITY) continue; - const double w = std::exp(sc[j] - mx); - sum += w; - const uint16_t* k = row_of(j); - for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]); - } - for (int d = 0; d < D; ++d) - want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; - } + const std::vector want = reference(M, H, B, pages, bt, len, qb, kvb, scale); /* Both pairings on the same operands: the positional one, on the table widened past the * union's lists, and at the case's own width the launcher's choice, the union, which must @@ -326,6 +344,227 @@ int run(const Case& c, std::mt19937& rng) { return fails; } +/* The rows row (attend_rows): one query row and 64 heads a workgroup, as GLM's prefill runs MLA + * split by rows. Each form against the f64 softmax and the forms bit for bit against each other + * (the element-wise key load; 32 heads a workgroup, whose heads sum alike); unsplit, a run of the + * rows against the same rows of the whole batch, since a rank computing its run must produce the + * bytes the batch would. */ +int run_rows(const Case& c, std::mt19937& rng) { + const int M = c.rows, H = c.heads, B = c.blocks; + std::vector bt, len; + const int pages = fill_tables(c, rng, bt, len); + std::normal_distribution nrm(0.f, 1.f); + std::vector qb((size_t)M * H * D), kvb((size_t)pages * BS * D); + for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); + for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); + const double scale = 0.0625; + const std::vector want = reference(M, H, B, pages, bt, len, qb, kvb, scale); + std::vector scratch; + auto launch = [&](int first, int rows, int form, std::vector& out) { + const size_t q0 = (size_t)first * H * D; + RadTensor t[5] = { tens(qb.data() + q0, RAD_BF16, { rows, H, D }), + tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), + tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }), + tens(len.data() + first, RAD_I32, { rows }), + tens(out.data() + q0, RAD_BF16, { rows, H, D }) }; + RadParam p[6]{}; + const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" }; + const long long vals[5] = { rows, D, H, B, BS }; + for (int i = 0; i < 5; ++i) { + p[i].key = keys[i]; + p[i].kind = RAD_P_INT; + p[i].ival = vals[i]; + } + p[5].key = "scale"; + p[5].kind = RAD_P_F64; + p[5].dval = scale; + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p; + a.n_p = 6; + if (c.scratch) { + const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a); + scratch.assign((size_t)need + 16, 0); + a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15); + a.scratch_bytes = need; + } + if (form < 0) return r4d_rad_mla_attn_matrix(&a, nullptr); + r4d_mla_rows_pin_form(form); + const int rc = r4d_rad_mla_attn_rows(&a, nullptr); + r4d_mla_rows_pin_form(0); + return rc; + }; + int fails = 0; + std::vector rule; + for (int form : { 3, 1, 2, 0 }) { + std::vector out((size_t)M * H * D, 0xffff); + const int rc = launch(0, M, form, out); + if (rc != RAD_OK) { + std::printf("%-40s form %d launch returned %d FAIL\n", c.name.c_str(), form, rc); + ++fails; + continue; + } + double max_err = 0; + long bad = 0; + for (size_t i = 0; i < out.size(); ++i) { + const float got = rad_bf16_to_f32(out[i]); + const double e = std::fabs(got - want[i]); + if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad; + if (std::isfinite(got)) max_err = std::max(max_err, e); + } + bool ok = bad == 0; + std::string note; + /* A split follows the workgroup count, which 32 heads a workgroup doubles; under 32 rows + * the rule is the matrix row's kernel. */ + if (form == 3) + rule = out; + else if (form == 0 && M < 32) { + std::vector matrix((size_t)M * H * D, 0xffff); + const int mrc = launch(0, M, -1, matrix); + if (mrc != RAD_OK || matrix != out) { + note = " (the rule under 32 rows is not the matrix row)"; + ok = false; + } + } else if ((form == 1 || !c.scratch) && out != rule) { + note = " (differs from form 3)"; + ok = false; + } + std::printf("%-40s form %d M %3d H %2d blocks %3d max_abs %.2e bad %ld%s %s\n", + c.name.c_str(), form, M, H, B, max_err, bad, note.c_str(), ok ? "PASS" : "FAIL"); + fails += !ok; + } + if (!c.scratch && M >= 3 && !rule.empty()) { + std::vector out((size_t)M * H * D, 0xffff); + const int rc = launch(1, M - 2, 3, out); + bool same = rc == RAD_OK, untouched = true; + for (int r = 0; r < M; ++r) + for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) { + if (r == 0 || r == M - 1) + untouched = untouched && out[i] == 0xffff; + else + same = same && out[i] == rule[i]; + } + std::printf("%-40s rows 1..%d alone: %s, rows outside %s %s\n", c.name.c_str(), M - 2, + same ? "bit-identical to the batch" : "DIFFER from the batch", + untouched ? "untouched" : "WRITTEN", same && untouched ? "PASS" : "FAIL"); + fails += !(same && untouched); + } + return fails; +} + +/* A TP step's attention both ways on one operand set: by heads, each of `world` ranks running + * the matrix row on its heads of every row (views into the whole [T, 64, 512]), and by rows, each + * rank the rows row on its run of ceil(T / world) rows with every head, the last run short. The + * step mixes what a step batch carries, decode rows first: single-row decodes on scattered tables, + * a verify window of four rows on one table, then a prefill continuing past the DSA budget and a + * fresh prompt's first chunk. Both forms against the f64 softmax; how far apart they are is + * printed. */ +int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) { + constexpr int H = 64, B = 65; + std::vector bt, len; + int pages = 0; + auto append = [&](const std::vector& t, const std::vector& l, int segment_pages) { + for (int v : t) bt.push_back(v >= 0 ? v + pages : v); + len.insert(len.end(), l.begin(), l.end()); + pages += segment_pages; + }; + { /* three decodes, each its own table with holes */ + std::vector t((size_t)3 * B), l(3); + for (int r = 0; r < 3; ++r) { + for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = b % 13 == 5 ? -1 : (b * 5 + r * 17) % (3 * B); + l[r] = B * BS - 1 - 3 * r; + } + append(t, l, 3 * B); + } + { /* a verify window: four rows of one sequence on one table */ + std::vector t((size_t)4 * B), l(4); + for (int r = 0; r < 4; ++r) { + for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = (b * 3 + 1) % B; + l[r] = B * BS - 4 + r + 1; + } + append(t, l, B); + } + { /* a prefill past the DSA budget: every row its own top blocks */ + std::vector t, l; + int segment = 0; + topk_tables(23, B, 1200, 4, rng, t, l, segment); + append(t, l, segment); + } + { /* a fresh prompt's chunk: causal on one table, rows starting at position 0 */ + std::vector t((size_t)fresh_rows * B, -1), l(fresh_rows); + for (int r = 0; r < fresh_rows; ++r) { + for (int b = 0; b <= r / BS && b < B; ++b) t[(size_t)r * B + b] = b; + l[r] = r + 1; + } + append(t, l, B); + } + const int T = (int)len.size(); + std::normal_distribution nrm(0.f, 1.f); + std::vector qb((size_t)T * H * D), kvb((size_t)pages * BS * D); + for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); + for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); + const double scale = 0.0625; + const std::vector want = reference(T, H, B, pages, bt, len, qb, kvb, scale); + auto launch = [&](bool by_rows, int first, int rows, int h0, int heads, + std::vector& out) { + const size_t at = ((size_t)first * H + h0) * D; + RadTensor t[5] = { tens(qb.data() + at, RAD_BF16, { rows, heads, D }), + tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), + tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }), + tens(len.data() + first, RAD_I32, { rows }), + tens(out.data() + at, RAD_BF16, { rows, heads, D }) }; + t[0].stride[0] = t[4].stride[0] = (int64_t)H * D; + RadParam p[6]{}; + const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" }; + const long long vals[5] = { rows, D, heads, B, BS }; + for (int i = 0; i < 5; ++i) { + p[i].key = keys[i]; + p[i].kind = RAD_P_INT; + p[i].ival = vals[i]; + } + p[5].key = "scale"; + p[5].kind = RAD_P_F64; + p[5].dval = scale; + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p; + a.n_p = 6; + if (!by_rows) return r4d_rad_mla_attn_matrix(&a, nullptr); + /* Runs this short take the matrix kernel by rule; the rows kernel is what is under test. */ + r4d_mla_rows_pin_form(3); + const int rc = r4d_rad_mla_attn_rows(&a, nullptr); + r4d_mla_rows_pin_form(0); + return rc; + }; + std::vector heads_out((size_t)T * H * D, 0xffff), rows_out((size_t)T * H * D, 0xffff); + const int per_heads = H / world, run = (T + world - 1) / world; + int fails = 0; + for (int rank = 0; rank < world; ++rank) { + fails += launch(false, 0, T, rank * per_heads, per_heads, heads_out) != RAD_OK; + const int first = rank * run, n = std::min(run, T - first); + if (n > 0) fails += launch(true, first, n, 0, H, rows_out) != RAD_OK; + } + long bad[2] = { 0, 0 }; + double max_err[2] = { 0, 0 }, apart = 0; + for (size_t i = 0; i < want.size(); ++i) { + const float got[2] = { rad_bf16_to_f32(heads_out[i]), rad_bf16_to_f32(rows_out[i]) }; + for (int f = 0; f < 2; ++f) { + const double e = std::fabs(got[f] - want[i]); + if (!std::isfinite(got[f]) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad[f]; + if (std::isfinite(got[f])) max_err[f] = std::max(max_err[f], e); + } + apart = std::max(apart, (double)std::fabs(got[0] - got[1])); + } + const bool ok = !fails && !bad[0] && !bad[1]; + std::printf("%-40s T %3d world %d run %2d last %2d heads max_abs %.2e bad %ld rows max_abs " + "%.2e bad %ld apart %.2e %s\n", + name, T, world, run, T - (world - 1) * run, max_err[0], bad[0], max_err[1], bad[1], + apart, ok ? "PASS" : "FAIL"); + return !ok; +} + /* The launcher prints the running totals every 1024th counted launch and must leave them * standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */ int periodic_report() { @@ -406,6 +645,18 @@ int main(int argc, char** argv) { { "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 }, { "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false }, }; + /* The rows row at 64 heads, and at 32, which it serves with two groups a workgroup. */ + std::vector rows_cases = { + { "rows: prefill, one table", 8, 64, 65, Fill::prefill }, + { "rows: topk d=4", 8, 64, 65, Fill::topk, 4, 600 }, + { "rows: topk d=16, 513 blocks", 3, 64, 513, Fill::topk, 16, 8192 }, + { "rows: repeated pages", 6, 64, 33, Fill::repeat }, + { "rows: ragged, holes and bad pages", 7, 64, 17, Fill::ragged }, + { "rows: ragged, split", 3, 64, 17, Fill::ragged, 0, 0, true }, + { "rows: prefill, one row, split", 1, 64, 65, Fill::prefill, 0, 0, true }, + { "rows: 32 heads", 5, 32, 33, Fill::prefill }, + { "rows: 32 heads, topk d=4, split", 2, 32, 33, Fill::topk, 4, 400, true }, + }; const char* filter = argc > 1 ? argv[1] : nullptr; int fails = 0; for (size_t i = 0; i < cases.size(); ++i) { @@ -413,6 +664,23 @@ int main(int argc, char** argv) { std::mt19937 rng(20261018u + (unsigned)i); fails += run(cases[i], rng); } + for (size_t i = 0; i < rows_cases.size(); ++i) { + if (filter && rows_cases[i].name.find(filter) == std::string::npos) continue; + std::mt19937 rng(20261020u + (unsigned)i); + fails += run_rows(rows_cases[i], rng); + } + /* T 45 over eight ranks: runs of 6, the last of 3; 37 over four: 10 and 7; 48: whole runs. */ + const struct { + const char* name; + int world, fresh; + } splits[] = { { "split: heads vs rows, 8 ranks", 8, 15 }, + { "split: heads vs rows, 4 ranks", 4, 7 }, + { "split: heads vs rows, whole runs", 8, 18 } }; + for (size_t i = 0; i < sizeof splits / sizeof splits[0]; ++i) { + if (filter && !std::strstr(splits[i].name, filter)) continue; + std::mt19937 rng(20261021u + (unsigned)i); + fails += run_split(splits[i].name, splits[i].world, splits[i].fresh, rng); + } if (!filter) fails += periodic_report(); std::printf("%d failure(s)\n", fails); return fails ? 1 : 0; From 7d7c66da552702e7e419009b64c0dbf539aa2751 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:15 +0200 Subject: [PATCH 16/35] arch/common: LinearFP8::step writes a run of rows from a given output row An optional `y0`: rows [r0, r0 + rows) of the input land at row y0 of the output instead of at row r0, so a rank's run of a step's rows can go to a buffer sized for the run. Unset, every branch issues what it did. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_fp8.h | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index b8ba87cd..9c17bae6 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -798,8 +798,10 @@ struct LinearFP8 { rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t K, RadWeightGroup grp); + /* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when + * that is set: a rank's run of a step's rows written to a buffer sized for the run. */ void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, - int64_t rows = 0) const; + int64_t rows = 0, int64_t y0 = -1) const; /* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane * gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and * total must be whole scale blocks. */ @@ -1428,10 +1430,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks * the operand count against the schema (core/runtime/issue.cpp). */ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0, - int64_t rows) const { + int64_t rows, int64_t y0) const { if (rows <= 0) rows = T - r0; + const int64_t yr = y0 < 0 ? r0 : y0; if (bf16) { - RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N)); + RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N)); return; } if (i8) { @@ -1440,7 +1443,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K), brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } /* The 4-bit weight's copies of the input start at their buffers' first row: they live only @@ -1450,13 +1453,13 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K), brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws), - brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (w4) { RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K)); RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws), - brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (paro5 && rot_split && rows > rot_split) { @@ -1465,14 +1468,14 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (paro5) { RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K)); RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE, - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (mx) { @@ -1486,12 +1489,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref)); return; } RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); } /* ================================================== an fp8 weight with no op of its own From eb14e4f64282350d362badb78816a0e189e76515 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:15 +0200 Subject: [PATCH 17/35] glm5next: the MLA row form, opt-in with RADIANCE_GLM_MLA_ROWS=1 -- a prefill-sized step by rows over the ranks, each rank with all 64 heads From GlmTp::kSplitRows each rank runs its run of the step's rows (GlmTp::run_of: ceil(T / world) rows, the last run shorter) through q_b, absorption, attention with all 64 heads (mla_attn_rows_bf16), expansion and o, and an all_gather of whole runs takes the all-reduce's place. The latent cache and the DSA selection are whole on every rank, so nothing is exchanged before the attention; each rank sends its run to seven peers, half the bytes of the two-shot all-reduce, through the same exchange instance. In a 4096-row chunk at 16k of context a rank's attention drops from 14.0 to 3.9 ms a layer on the kernel bench. The price is q_b, kv_b and o at full width on every rank: 120 MiB a layer, 1.29 GiB a card over the 11 trunk layers, and about 0.1 GiB of activations; the MTP layer keeps its heads. The full-width weights are whole views (RadWeightDecl::source) of blk.N.attn_q_b, attn_kv_b and attn_output, the head form's container entries, so they take the stored encoding (fp8a8f32, bf16) and need no name map; LinearFP8 gets `stored` for that, served by its block-fp8 branch only, and LinearFP8::step writes a run of rows from a given output row. The head form stays the default, unset or RADIANCE_GLM_MLA_ROWS=0, and declares none of it: that graph is the one before this change, byte for byte (the pinned hashes). The row form is not bit-identical to the head form, and GLM-5.3 turns that into a measurable divergence: over a 43k-position KL corpus at TP8 (English prose, German prose, code) the row form scores a mean KL of 0.033 against the head form (median 0.004, top-1 agreement 93.5 %), with greedy text unchanged. The projections are not the cause: q_b and o over a rank's rows give the head form's bytes (r4d_emu), and o summed as eight rank partials in the all-reduce's order (RADIANCE_GLM_MLA_ROWS=2, a test form, GlmMla::Form::rows_sliced_o) scores 0.032. The attention's rounding is: the rows kernel parts from the paired union tile in about 0.1 % of every row's outputs by one bf16 step (the union pairing sums a pair's second row in another order), and the 16-head tile, which parts in the same share of every second row only, halves the KL to 0.015. A bit-identical row form would run the union tile eight times a row over its own group of eight heads, without this kernel's gain, or need a rows kernel with the union's arithmetic; neither is here, so the form is opt-in. Measured on eight R9700 at Gen5 links, the same build: a 20k-token prefill 5074 tok/s in the row form against 4270 in the head form, BetterBench prefill at 22k 4984 against 4151, single stream 181.8 against 180.2 tok/s, eight streams 468 against 454. glm5next_test declares the block at one to eight ranks and checks the full-width views and their sources, the fp8a8f32 GEMMs, the gather's bound against the all-reduce's, each rank's operands at 300 rows (runs of 38, the last 34 at eight ranks) and the head form at 255; the o-slices form's eight GEMMs and seven adds; the model's counts and the TP8 pin under RADIANCE_GLM_MLA_ROWS=1 (0x1d378152c40f8834 / 0x82ed1094dbf4b637), with the default pins unchanged; and the row rule against both formulas it replaced. plugin_test resolves every band of every op the row form adds at eight ranks against libr4d, with no card. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_glm_mla.h | 191 ++++++++++++++++- arch/common/rad_fp8.h | 38 +++- arch/common/rad_glm_tp.h | 7 +- arch/glm5next/glm5next.cpp | 48 ++++- docs/ARCHITECTURES.md | 86 +++++--- docs/GUIDE.md | 1 + docs/OPS.md | 3 +- tests/glm5next_test.cpp | 359 +++++++++++++++++++++++++++++--- tests/plugin_test.cpp | 60 ++++++ 9 files changed, 717 insertions(+), 76 deletions(-) diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index 7c54e67d..f7ee83fa 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -3,14 +3,23 @@ * complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent * for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual. * - * Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and - * kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are - * replicated. */ + * Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the + * rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent + * cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead + * (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b, + * absorption, attention, expansion and the output projection with all 64 heads, then an + * all_gather lays the runs out as the whole step. The latent cache and the selection are whole on + * every rank already, so the split needs no other exchange. The gather moves half the bytes of + * the head form's all-reduce, and the attention loads each key once for all 64 heads of a row. + * The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q + * unset declares neither them nor the form. */ #ifndef RAD_BLOCK_GLM_MLA_H #define RAD_BLOCK_GLM_MLA_H #include "rad_fp8.h" #include "rad_glm_tp.h" +#include #include +#include namespace rad { namespace arch { @@ -88,11 +97,33 @@ struct MlaLatent { }; struct GlmMla { + /* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every + * step size and spares the full-width weights' VRAM; `rows` is the row form; `rows_sliced_o` + * the row form with o summed as the head form sums it (a test of how much of the two forms' + * difference is o's rounding). The plugin chooses; the block takes the choice through which + * RowsWire buffers it is given. */ + enum class Form { heads, rows, rows_sliced_o }; + /* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold + * world * rows_for(T) rows, since every rank's run is gathered at full length. */ + struct RowsWire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0; + ActFP8 attn{}; + /* Form::rows_sliced_o only: o in the head form's world K slices, each rounded to bf16 + * ([world * rows, 4096]), summed in f32 in ascending slice order as the exact all-reduce + * folds ranks (two [rows, 4096] f32 planes), rounded once. */ + rad_buf slices = 0, acc = 0, widened = 0; + }; struct Wire { ActFP8 input{}, q_low{}, attn{}; rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0; MlaLatent::Wire core{}; + RowsWire rows{}; }; + /* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */ + static constexpr int64_t kOutRowBytes = 4096 * 2; + static int64_t rows_for(int64_t T, int world) { + return GlmTp::run_rows(T, world, kOutRowBytes); + } Geom g{}; Wire w{}; int layer = 0; @@ -103,6 +134,12 @@ struct GlmMla { MlaLatent core{}; rad_weight q_gain = 0, kv_gain = 0; rad_op op_kv_norm = 0, op_store = 0, op_ar = 0; + LinearFP8 rows_q_b{}, rows_output{}; + QuantFP8 rows_quant{}; + rad_weight rows_kv_b = 0; + rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0; + std::vector rows_o_slices; + rad_op op_slice_first = 0, op_slice_widen = 0, op_slice_add = 0, op_slice_narrow = 0; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* prefix, rad_kvgroup group, bool reduce = true, bool defer_finish = false) { @@ -160,7 +197,126 @@ struct GlmMla { GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); if (reduce) op_ar = GlmTp::reduce(b, g, w.out); - return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL; + if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL; + return reduce ? declare_rows(b, nm, prefix) : RAD_OK; + } + /* Declared whatever the step size, as every TP split here is: arena levels declare again at a + * smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's, + * so both share one exchange instance and its scratch. */ + int declare_rows(RadBuilder* b, Names& nm, const char* prefix) { + const auto& r = w.rows; + if (!r.q || g.world < 2) return RAD_OK; + if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL; + const int64_t R = rows_for(g.max_tok, g.world); + const auto wg = grp_layer(layer); + /* Whole views of the head form's container entries: one stored weight each, whose + * encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */ + rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer); + RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536, + RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + w.q_low, r.q, R)); + rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer), + nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16, + { 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg); + if (!rows_kv_b) return RAD_E_INVAL; + auto project = [&](const char* mode, rad_buf in, rad_buf out) { + return rw(b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64), + RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512), + RAD_STR("mode", mode), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(rows_kv_b)), + { in }, { out }); + }; + op_rows_absorb = project("absorb", r.q, r.q_latent); + op_rows_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512), + RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks), + RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.q_latent, w.core.selected, w.core.length }, { r.attn_latent }); + op_rows_expand = project("expand", r.attn_latent, r.attn.x); + RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384)); + if (r.slices) { + RAD_ARCH_TRY(declare_o_slices(b, nm, prefix, R)); + } else { + rows_output.stored = nm.f("blk.%d.attn_output.weight", layer); + RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), + 4096, 16384, RAD_SHARD_NONE, wg, + { nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, + r.out, R)); + } + op_rows_gather = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.out }, { w.out }); + return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK + : RAD_E_INVAL; + } + /* The test form of o: slice k is the head form's rank k slice of the stored weight's columns, + * a GEMM over the matching columns of the quantised input. */ + int declare_o_slices(RadBuilder* b, Names& nm, const char* prefix, int64_t R) { + const auto& r = w.rows; + if (!r.acc || !r.widened) return RAD_E_INVAL; + const int64_t K = 16384 / g.world; + rows_o_slices.assign((size_t)g.world, LinearFP8{}); + for (int k = 0; k < g.world; ++k) { + auto& lin = rows_o_slices[(size_t)k]; + lin.stored = nm.f("blk.%d.attn_output.weight", layer); + RAD_ARCH_TRY(lin.declare(b, nm, g, nm.f("blk.%d.attn_output_rows%d", layer, k), 4096, + K, RAD_SHARD_COL, grp_layer(layer), + { nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.slices, R, + {}, k * K, (k + 1) * K)); + } + auto cast = [&](const char* from, const char* to, rad_buf x, rad_buf y) { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 4096), + RAD_STR("from", from), RAD_STR("to", to)), + RAD_NOWEIGHTS), + { x }, { y }); + }; + op_slice_first = cast("bf16", "f32", r.slices, r.acc); + op_slice_widen = cast("bf16", "f32", r.slices, r.widened); + op_slice_add = rw(b, + RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 4096), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { r.acc, r.widened }, { r.acc }); + op_slice_narrow = cast("f32", "bf16", r.acc, r.out); + return op_slice_first && op_slice_widen && op_slice_add && op_slice_narrow ? RAD_OK + : RAD_E_INVAL; + } + void step_o_slices(RadCtx* ctx, int64_t run, int64_t n) const { + const auto& r = w.rows; + const int64_t K = 16384 / g.world, G = K / RAD_FP8_BLOCK; + for (int k = 0; k < g.world; ++k) { + const auto& lin = rows_o_slices[(size_t)k]; + RAD_ISSUE_N(ctx, lin.op, n, bcol(r.attn.q, k * K, K, n), bcol(r.attn.s, k * G, G, n), + RAD_W(lin.w), RAD_W(lin.ws), brow_slice(r.slices, k * run, n, 4096), + RAD_NONE, RAD_NONE); + } + RAD_ISSUE_N(ctx, op_slice_first, n, brow_slice(r.slices, 0, n, 4096), brows(r.acc, n)); + for (int k = 1; k < g.world; ++k) { + RAD_ISSUE_N(ctx, op_slice_widen, n, brow_slice(r.slices, k * run, n, 4096), + brows(r.widened, n)); + RAD_ISSUE_N(ctx, op_slice_add, n, brows(r.acc, n), brows(r.widened, n), + brows(r.acc, n)); + } + RAD_ISSUE_N(ctx, op_slice_narrow, n, brows(r.acc, n), brows(r.out, n)); + } + /* From the TP split threshold, and while the last rank's run is not empty (always at that + * threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */ + bool rows_take(int64_t T) const { + return op_rows_gather && GlmTp::splits(T, g.world) && + (g.world - 1) * rows_for(T, g.world) < T; } void prepare(RadCtx* ctx, const RadBatch* batch) const { const auto* kb = kv_batch(batch, kv); @@ -173,17 +329,42 @@ struct GlmMla { kv_a.step(ctx, w.input, w.kv_raw, T); q_norm.step(ctx, T); RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T)); - q_b.step(ctx, w.q_low, w.core.q, T); + if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T); RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); } void finish(RadCtx* ctx, const RadBatch* batch) const { const int64_t T = batch->n_tok; + if (rows_take(T)) { + finish_rows(ctx, T); + return; + } core.step(ctx, T); attn_quant.step(ctx, T); output.step(ctx, w.attn, w.out, T); if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); } + /* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the + * gather sends its unwritten tail rows, which land past T. */ + void finish_rows(RadCtx* ctx, int64_t T) const { + const auto& r = w.rows; + const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes); + const int64_t first = run.first, n = run.rows; + rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0); + RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n)); + RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer), + brow_slice(w.core.selected, first, n, core.c.blocks), + brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n)); + RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b), + brows(r.attn.x, n)); + rows_quant.step(ctx, n); + if (r.slices) + step_o_slices(ctx, run.run, n); + else + rows_output.step(ctx, r.attn, r.out, n); + RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run), + brows(w.out, g.world * run.run)); + } }; } } // namespace rad::arch diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 9c17bae6..cb69f55e 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -745,6 +745,10 @@ struct LinearFP8 { * this is set; otherwise the linear reads unwritten arena bytes. */ bool reads_x = false; bool mapped = false; /* probe() made the name map; declare() does not make it again */ + /* The stored weight this linear's views take when it is not `.weight`: a second linear + * over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set + * before declare(); no name map is made, and only block fp8 is served this way. */ + const char* stored = nullptr; /* The weight's access class (rad_builder.h): read every pass by default; a linear run once a * request (an encoder's) says so, which lets placement keep it off the card. Set before * declare(). */ @@ -1039,9 +1043,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* Name map first: the weight's encoding, looked up through it, picks the branch below. */ const char* wn = nm.f("%s.weight", base); - if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); + if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src)); + const char* sw = stored ? stored : wn; RadEncoding enc{}; - const bool known = weight_enc(b, wn, &enc); + const bool known = weight_enc(b, sw, &enc); const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; @@ -1051,6 +1056,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * constraints. */ bf16 = g.w_bf16 || plain; if (bf16) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (known && !plain) { char en[256]; rad_enc_format(&enc, en, sizeof en); @@ -1089,6 +1099,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool rot8 = known && linear_is_w8h(enc); i8 = known && (linear_is_w8(enc) || rot8); if (i8) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (a.q8_fed && rot8 != a.q8_rot) { fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its " "producer wrote %s\n", wn, rot8 ? " rotated" : " plain", @@ -1148,6 +1163,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * codes, and (scale, zero) as `b_scale`. */ paro5 = known && linear_is_paro_w5(enc); if (paro5) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5; if (!a.x) { fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's " @@ -1214,6 +1234,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * whole 128s, the scale group. */ w4 = known && linear_is_w4(enc); if (w4) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (!a.x) { fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, " "and its input has none\n", wn); @@ -1284,6 +1309,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha paro = known && linear_is_paro_mxfp4(enc); mx = known && (linear_is_mxfp4(enc) || paro); if (mx) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (paro) { /* The rotation is applied to the activation, so this linear needs the input's bf16 * plane (probe() set reads_x) and quantises it itself. */ @@ -1395,10 +1425,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32; /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in * the checkpoint or made so by rad-convert's recipe. */ - w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, + w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, rp.w, rp.n); ws_row_div = RAD_FP8_BLOCK; - ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16, + ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n); if (!w || !ws) return RAD_E_INVAL; /* An uneven slice; the scale plane takes the same slice in blocks. */ diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h index 39a3d589..64d93c16 100644 --- a/arch/common/rad_glm_tp.h +++ b/arch/common/rad_glm_tp.h @@ -13,9 +13,10 @@ * row-interleaved all_gather, bit for bit the replicated projection * * The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered - * row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside - * its page tables, so its runs are multiples of four rows. The last rank's run may be short, or - * lie wholly past a small step (`run_of`). */ + * row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs + * are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its + * runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small + * step (`run_of`). */ #ifndef RAD_GLM_TP_H #define RAD_GLM_TP_H #include "rad_arch.h" diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index e2cfdc04..92aeb3c6 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -28,11 +28,27 @@ #include #include #include +#include +#include #include namespace glm5next { using namespace rad::arch; +/* The deployment switch of this plugin, read once a declare; docs/GUIDE.md lists it. + * RADIANCE_GLM_MLA_ROWS unset or 0 keeps the MLA's head form at every step size and declares none + * of the row form's full-width weights (1.29 GiB a card at eight ranks); 1 is the row form from + * GlmTp::kSplitRows; 2 is the row form with o summed as the head form sums it, a test of the two + * forms' difference (GlmMla::Form). The row form is opt-in: it is not bit-identical to the head + * form, and this model turns the rounding difference of a fraction of the attention outputs into + * a KL of 0.015 to 0.03 against it (docs/ARCHITECTURES.md). */ +static GlmMla::Form mla_form() { + const char* e = std::getenv("RADIANCE_GLM_MLA_ROWS"); + if (e && !std::strcmp(e, "1")) return GlmMla::Form::rows; + if (e && !std::strcmp(e, "2")) return GlmMla::Form::rows_sliced_o; + return GlmMla::Form::heads; +} + struct Layer { bool full = false, draft = false; ManifoldConn attn_hc{}, ffn_hc{}; @@ -46,6 +62,7 @@ struct Layer { struct Model { Names nm{}; Geom g{}; + GlmMla::Form form = GlmMla::Form::rows; std::vector layers; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; /* The streams and the step's stream-wide buffers. */ @@ -102,7 +119,9 @@ static int stream_buffers(RadBuilder* b, Model& m) { m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 }); m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 }); m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 }); - m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 }); + /* Rounded up to whole runs: the MLA row form gathers every rank's run at full length. */ + m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, + { g.world * GlmMla::rows_for(T, g.world), 4096 }); m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 }); @@ -132,9 +151,9 @@ static int kda_buffers(RadBuilder* b, Model& m) { kw.core.out = bf("recurrent_out", W); return RAD_OK; } -/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under - * TP the selection planes hold every rank's run of rows, which can reach past the step - * (DsaCache::part_rows). */ +/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then + * the row form's (Model::form). Under TP the selection planes hold every rank's run of rows, + * which can reach past the step (DsaCache::part_rows). */ static int mla_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; @@ -160,6 +179,21 @@ static int mla_buffers(RadBuilder* b, Model& m) { const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T; aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 }); aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ }); + if (g.world > 1 && m.form != GlmMla::Form::heads) { + auto& rows = aw.rows; + const int64_t R = GlmMla::rows_for(T, g.world); + rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 }); + rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 }); + RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R)); + rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 }); + if (m.form == GlmMla::Form::rows_sliced_o) { + rows.slices = decl_b(b, nm.f("rows_o_slices"), RAD_BF16, { g.world * R, 4096 }); + rows.acc = decl_b(b, nm.f("rows_o_sum"), RAD_F32, { R, 4096 }); + rows.widened = decl_b(b, nm.f("rows_o_slice_f32"), RAD_F32, { R, 4096 }); + } + } return RAD_OK; } static int indexer_buffers(RadBuilder* b, Model& m) { @@ -292,7 +326,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096)); if (lay.full) { - RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true)); + // The MTP layer keeps the head form: its row form would cost another 126 MB a card. + auto aw = m.aw; + if (draft) aw.rows = {}; + RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true)); DsaCache::Config c; c.blocks = (g.max_ctx + 3) / 4 + 1; c.work = (g.max_tok + 3) / 4 + g.max_seqs; @@ -398,6 +435,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c auto& g = m.g; m.nm = Names(ctx->scope); auto& nm = m.nm; + m.form = mla_form(); RAD_ARCH_TRY(geometry(g, meta, ctx, world)); RAD_ARCH_TRY(stream_buffers(b, m)); RAD_ARCH_TRY(kda_buffers(b, m)); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 9cde6552..1eb618fa 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -427,18 +427,19 @@ declared beside it when the container carries the tower and the deployment asks 654df43; for the tower and its processor, transformers' `glm5_next`. The plugin is one file over blocks in `arch/common`, one block a file; it declares the buffers -the blocks share, places them and issues the step's order. +the blocks share, places them and issues the step's order, and reads its one deployment switch +(`RADIANCE_GLM_MLA_ROWS`, docs/GUIDE.md) once a declare. | file | block | what | |---|---|---| | `rad_block_glm_mhc.h` | `ManifoldConn` | the four-stream residual's read and write | | `rad_block_glm_kda.h` | `GlmKda`, `KdaState` | the 34 linear layers and their recurrence | -| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers and their absorbed core | +| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers, in the head form or the row form | | `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection | | `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` | | `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 | | `rad_block_glm_vision.h` | `GlmVision`, `MediaRows` | the tower, and its rows over the embeddings | -| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection | +| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the one row rule, the split thresholds, the column split of a replicated f32 projection | ``` 45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16) @@ -534,45 +535,66 @@ at eight ranks each card holds 22.06 GiB of them, 19.67 GiB the routed experts. layer's latent, index and tail for every row and runs its MoE on the proposal rows only. **Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp` -declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and -8, the connection, router and index-gate splits at 1, 2, 4 and 8, the indexer's row split at 2 -and 8, the row rule at every world, each issue's operand count against the loaded kernel -libraries' schemas, and every declared weight against the served container's names and encodings. +declares and steps the whole plugin at 1 and 8 against pinned graph and step hashes (the head form, +the row form), the connection, router and index-gate splits at 1, 2, 4 and 8, +the indexer's row split at 2 and 8, the MLA row split at 1, 2, 4 and 8, the row rule at every +world, each issue's operand count against the loaded kernel libraries' schemas, and every declared +weight against the served container's names and encodings. -One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated -piece of work splits by rows over the ranks instead, each rank taking one run of ceil(T / world) -rows rounded up to whole 16-byte words of the row it gathers, because an `all_gather` moves whole -words: multiples of four rows for the indexer's one i32 length a row. The last run may be short; -a rank whose run lies wholly past a small step takes the first run and computes dead rows, so -every plane it gathers is written (`GlmTp::run_of`). The indexer also splits a smaller step, from -16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in -decode, the collective costs more than it saves and every rank runs the replicated form. +One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated or +head-split piece of work splits by rows over the ranks instead, each rank taking one run of +ceil(T / world) rows rounded up to whole 16-byte words of the row it gathers, because an +`all_gather` moves whole words: whole rows for the MLA's 4096-wide bf16 output, multiples of four +rows for the indexer's one i32 length a row. The last run may be short; a rank whose run lies +wholly past a small step takes the first run and computes dead rows, so every plane it gathers is +written (`GlmTp::run_of`). The indexer alone also splits a smaller step, from 16 rows once rows x +live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in decode, the collective +costs more than it saves and every rank runs the replicated or head-split form. - The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums them. The dense feed-forward splits its 12288 the same way. - MLA splits by whole heads: the rows of q_b and kv_b (8 heads a rank at eight) and the columns - of o. q_a, kv_a and the latent are replicated. + of o. q_a, kv_a and the latent are replicated. With `RADIANCE_GLM_MLA_ROWS=1`, from the + threshold, it splits by rows instead (`GlmMla::Form::rows`): each rank takes its run under the row rule, the last run shorter, + through q_b, absorption, attention with all 64 heads + (`mla_attn_rows_bf16`, docs/OPS.md), expansion and o, and an `all_gather` of whole runs takes the + all-reduce's place. The latent cache and the DSA selection are whole on every rank, so nothing + is exchanged before the attention. Each rank sends its run to seven peers, half the bytes of the + two-shot all-reduce, and the gather shares that all-reduce's exchange instance. The price is + q_b, kv_b and o at full width on every rank, 120 MiB a layer and 1.29 GiB a card over the 11 + trunk layers (the MTP layer keeps its heads), about 0.1 GiB of activations besides; `2` is the + row form with o summed as the head form sums it (`GlmMla::Form::rows_sliced_o`), a test of the + two forms' difference. The head form is the default because the row form is not bit-identical + to it, and this model turns that into a measurable divergence: against the head form over a + 43k-position corpus the row form scores a mean KL of 0.033 (median 0.004, top-1 agreement + 93.5 %), greedy text unchanged. The projections are not the cause (q_b and o give the head + form's bytes when o is summed as eight rank partials, and the KL stays at 0.032); the + attention's rounding is: the rows kernel parts from the paired tile in about 0.1 % of every + row's outputs by one bf16 step, and the 16-head tile, which parts in the same share of every + second row only, halves the KL to 0.015. Measured + on eight R9700 at Gen5 links, the same build: a 20k-token prefill 5074 tok/s in the row form + against 4270 in the head form; BetterBench single stream 181.8 against 180.2 tok/s, eight + parallel 468 against 454. - KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two rank-128 projections into the gates are replicated. - The indexer's key side is replicated: every rank keeps the whole index cache and its tail. Its query side splits by rows from the threshold: each rank scores its run under the row rule, - R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache - (`dsa_score` with `row_part`, the last run's rows past the step scoring `-inf`) and selects for - the rows of its run that exist, under the bounds the scorer rebased to the run's first row - (`cu_part`, docs/OPS.md); two `all_gather`s lay the runs' page tables and lengths end to end, - 513 and 1 i32 a row, 8 MiB a layer at a 4096-row chunk. The run's queries are all a rank needs, - so the query projection, its quantiser and the head gates run on the run's rows too, and the - gates need no gather; the bf16 projection stays on the step's rows where a run would be 64 rows - or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection - is the same kernels' answer to the same operands, so the joined table is bit-identical to one - rank's and MLA reads it unchanged. The scoring grows with the context (every row scores every - complete block of its sequence), so this is where long prompts gain: the score plane shrinks to - one run (256 MiB to 32 MiB at 64k of context and a 4096-row chunk). A smaller step splits too - from 16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`): eight sequences - verifying five drafts from about 22k of context, where the scoring of 48 rows outweighs the two - gathers; a single sequence's decode never does, and below both thresholds the indexer runs - whole. + R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache (`dsa_score` with `row_part`, + the last run's rows past the step scoring `-inf`) and selects for the rows of its run that exist, + under the bounds the scorer rebased to the run's first row (`cu_part`, docs/OPS.md); two + `all_gather`s lay the runs' page tables and lengths end to end, 513 and 1 i32 a row, 8 MiB a layer + at a 4096-row chunk. The run's queries are all a rank needs, so the query projection, its + quantiser and the head gates run on the run's rows too, and the gates need no gather; the bf16 + projection stays on the step's rows where a run would be 64 rows or fewer, the skinny band whose + split count a tuned configuration may set. Each row's selection is the same kernels' answer to + the same operands, so the joined table is bit-identical to one rank's and MLA reads it unchanged. + The scoring grows with the context (every row scores every complete block of its sequence), so + this is where long prompts gain: the score plane shrinks to one run (256 MiB to 32 MiB at 64k of + context and a 4096-row chunk). A smaller step splits too from 16 rows once rows x live blocks + reach 2^18 (`GlmTp::kSplitWork`): eight sequences verifying five drafts from about 22k of + context, where the scoring of 48 rows outweighs the two gathers; a single sequence's decode never + does, and below both thresholds the indexer runs whole. - The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. - The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 00968f9a..77f9f020 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3129,6 +3129,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | +| `RADIANCE_GLM_MLA_ROWS` | `arch/glm5next`'s MLA form in a prefill-sized pass. Unset or `0`: split by heads at every pass, the default, holding none of the full-width projections the row form needs. `1`: split by rows from 256 rows, faster in prefill, for 1.29 GiB a card at TP8 and not bit-identical to the default. `2`: the row form with o summed as the head form sums it, a test of the two forms' difference (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_AR_FENCE_FROM` | four-rank all-reduces of at least this many elements take a full fence before their flag (default 131072: prefill chunks, never decode or verify); cures a rare fresh-start divergence on the 31B at tp 4; `0` turns it off | | `RADIANCE_PREFETCH` | `0` declares none of the weight reads the Gemma 4 31B and its DFlash2 drafter issue beside each all-reduce at decode and verify heights (libr4d `prefetch`: the next GEMM's leading weight bytes read into the on-die cache while the collective leaves the memory idle); on by default at more than one rank where the kernel library serves the op | diff --git a/docs/OPS.md b/docs/OPS.md index feb942c2..30f22814 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2858,7 +2858,8 @@ through a lane swap instead of LDS. The next chunk's keys are fetched while the multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a -workgroup), which no constraint routes to it. +workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor +parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`). `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index c646a1c1..e3d5427c 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -331,9 +331,301 @@ TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { } } +/* GLM's MLA from the TP split threshold: each rank runs its run of the step's rows with all 64 + * heads, through q_b, kv_b and o at full width, and an all_gather lays the runs out, instead of + * its heads over every row and an all-reduce. Runs are ceil(T / world) rows, the last one short; + * the gather sends whole runs into an output of world runs. Below the threshold, and at TP1, the + * head form is unchanged, as it is unless the row form is opted into (the default). */ +TEST(glm_mla_splits_a_prefill_by_rows_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.kv_block = 4; + // The container's MLA entries; the row form's names are not among them. + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "attn_q_a.weight", fp8 }, + { "attn_kv_a.weight", fp8 }, + { "attn_q_b.weight", fp8 }, + { "attn_output.weight", fp8 }, + { "attn_kv_b.weight", rad_enc_plain(RAD_BF16) } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.max_ctx = 4096; + g.eps = 1e-5; + g.world = world; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + const int64_t T = 512, R = GlmMla::rows_for(T, world), H = 64 / world; + auto act = [&](ActFP8& a, const char* name, int64_t rows, int64_t width) { + a.x = decl_b(&b, name, RAD_BF16, { rows, width }); + return a.declare_qs(&b, nm, g, name, width, rows); + }; + GlmMla::Wire w; + REQUIRE_EQ(act(w.input, "normalized", T, 4096), RAD_OK); + w.q_raw = decl_b(&b, "q_raw", RAD_BF16, { T, 1536 }); + w.kv_raw = decl_b(&b, "kv_raw", RAD_BF16, { T, 512 }); + REQUIRE_EQ(act(w.q_low, "q_low", T, 1536), RAD_OK); + w.latent = decl_b(&b, "latent", RAD_BF16, { T, 512 }); + w.out = decl_b(&b, "attn_delta", RAD_BF16, { world * R, 4096 }); + w.core.q = decl_b(&b, "query", RAD_BF16, { T, 16384 / world }); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { T, H, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { T, H, 512 }); + REQUIRE_EQ(act(w.attn, "expanded", T, 16384 / world), RAD_OK); + w.core.out = w.attn.x; + w.core.selected = decl_b(&b, "selected", RAD_I32, { T, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { T }); + w.rows.q = decl_b(&b, "rows_query", RAD_BF16, { R, 16384 }); + w.rows.q_latent = decl_b(&b, "rows_q_latent", RAD_BF16, { R, 64, 512 }); + w.rows.attn_latent = decl_b(&b, "rows_attn_latent", RAD_BF16, { R, 64, 512 }); + REQUIRE_EQ(act(w.rows.attn, "rows_expanded", R, 16384), RAD_OK); + w.rows.out = decl_b(&b, "rows_out", RAD_BF16, { R, 4096 }); + GlmMla mla; + REQUIRE_EQ(mla.declare(&b, nm, g, 3, w, "model.layers.3.self_attn", kv), RAD_OK); + const bool rows = world > 1; + CHECK_EQ(mla.op_rows_gather != 0, rows); + CHECK_EQ(count_op(b, "all_gather"), rows ? 1 : 0); + CHECK_EQ(count_op(b, "mla_attn"), rows ? 2 : 1); + const RecWeight* head_q = find_w(b, "blk.3.attn_q_b.weight"); + REQUIRE(head_q); + CHECK_EQ(head_q->d.shape[0], 16384 / world); + if (!rows) { + CHECK(!find_w(b, "blk.3.attn_q_b_rows.weight")); + continue; + } + const RecWeight* q_b = find_w(b, "blk.3.attn_q_b_rows.weight"); + const RecWeight* kv_b = find_w(b, "blk.3.attn_kv_b_rows.weight"); + const RecWeight* o = find_w(b, "blk.3.attn_output_rows.weight"); + REQUIRE(q_b && kv_b && o); + CHECK_EQ(q_b->d.shard, RAD_SHARD_NONE); + CHECK_EQ(q_b->d.shape[0], 16384); + CHECK_EQ(q_b->d.shape[1], 1536); + CHECK_EQ(kv_b->d.shard, RAD_SHARD_NONE); + CHECK_EQ(kv_b->d.dtype, RAD_BF16); + CHECK_EQ(kv_b->d.shape[0], 32768); + CHECK_EQ(kv_b->d.shape[1], 512); + CHECK_EQ(o->d.shard, RAD_SHARD_NONE); + CHECK_EQ(o->d.shape[0], 4096); + CHECK_EQ(o->d.shape[1], 16384); + // The full-width weights are whole views of the head form's container entries, so + // they take its encoding (block fp8 at f32 scales) and need no name map of their own. + const auto source = [](const RecWeight* w) { + return std::string(w && w->d.source ? w->d.source : ""); + }; + CHECK_EQ(source(q_b), "blk.3.attn_q_b.weight"); + CHECK_EQ(source(find_w(b, "blk.3.attn_q_b_rows.scale")), "blk.3.attn_q_b.weight"); + CHECK_EQ(source(kv_b), "blk.3.attn_kv_b.weight"); + CHECK_EQ(source(o), "blk.3.attn_output.weight"); + CHECK_EQ(source(find_w(b, "blk.3.attn_output_rows.scale")), "blk.3.attn_output.weight"); + CHECK_EQ(find_w(b, "blk.3.attn_q_b_rows.scale")->d.dtype, RAD_F32); + for (const auto& map : b.maps) CHECK(map.declared.find("_rows") == std::string::npos); + CHECK_EQ(pstr(&b.ops[mla.rows_q_b.op - 1], "dtype"), "fp8a8f32"); + CHECK_EQ(pstr(&b.ops[mla.rows_output.op - 1], "dtype"), "fp8a8f32"); + CHECK_EQ(pstr(&b.ops[mla.q_b.op - 1], "dtype"), "fp8a8f32"); + const RecOp* attn = &b.ops[mla.op_rows_attn - 1]; + CHECK_EQ(pint(attn, "heads"), 64); + CHECK_EQ(pint(attn, "blocks"), 513); + CHECK_EQ(param(attn, "M")->ihi, R); + CHECK(attn->reads == + std::vector({ w.rows.q_latent, w.core.selected, w.core.length })); + const RecOp* gather = &b.ops[mla.op_rows_gather - 1]; + const RecOp* reduce = &b.ops[mla.op_ar - 1]; + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pstr(gather, "dtype"), "bf16"); + CHECK(!param(gather, "row")); + // The all-reduce's message bound, so the two share one exchange instance. + CHECK_EQ(param(gather, "numel")->ihi, param(reduce, "numel")->ihi); + CHECK(gather->reads == std::vector({ w.rows.out })); + CHECK(gather->writes == std::vector({ w.out })); + std::vector slots(T); + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots.data(); + RadBatch batch{}; + batch.kv = &kb; + batch.n_kv_groups = 1; + for (int64_t steps : { 300, 255 }) { + batch.n_tok = steps; + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + mla.prepare(&ctx, &batch); + mla.finish(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + auto issued = [&](rad_op op) { + return std::count_if(ctx.issues.begin(), ctx.issues.end(), + [&](const RecIssue& i) { return i.op == op; }); + }; + const bool split = steps >= GlmTp::kSplitRows; + CHECK_EQ(issued(mla.q_b.op), split ? 0 : 1); + CHECK_EQ(issued(mla.core.op_attn), split ? 0 : 1); + CHECK_EQ(issued(mla.op_ar), split ? 0 : 1); + CHECK_EQ(issued(mla.op_rows_attn), split ? 1 : 0); + CHECK_EQ(issued(mla.op_rows_gather), split ? 1 : 0); + if (!split) continue; + const int64_t run = (steps + world - 1) / world, first = rank * run, + n = std::min(run, steps - first); + for (const auto& i : ctx.issues) { + if (i.op == mla.rows_q_b.op) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[0].handle, w.q_low.q); + CHECK_EQ(i.opd[0].offset, first * 1536); + CHECK_EQ(i.opd[0].rows, n); + CHECK_EQ(i.opd[2].handle, mla.rows_q_b.w); + CHECK_EQ(i.opd[4].handle, w.rows.q); + CHECK_EQ(i.opd[4].offset, 0); + CHECK_EQ(i.opd[4].rows, n); + } else if (i.op == mla.op_rows_attn) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[1].kind, RAD_OPK_KV); + CHECK_EQ(i.opd[2].handle, w.core.selected); + CHECK_EQ(i.opd[2].offset, first * 513); + CHECK_EQ(i.opd[2].rows, n); + CHECK_EQ(i.opd[3].handle, w.core.length); + CHECK_EQ(i.opd[3].offset, first); + CHECK_EQ(i.opd[3].rows, n); + CHECK_EQ(i.opd[4].handle, w.rows.attn_latent); + } else if (i.op == mla.rows_output.op) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[2].handle, mla.rows_output.w); + CHECK_EQ(i.opd[4].handle, w.rows.out); + CHECK_EQ(i.opd[4].offset, 0); + } else if (i.op == mla.op_rows_gather) { + CHECK_EQ(i.n, run * 4096); + CHECK_EQ(i.opd[0].handle, w.rows.out); + CHECK_EQ(i.opd[0].rows, run); + CHECK_EQ(i.opd[1].handle, w.out); + CHECK_EQ(i.opd[1].rows, world * run); + } + } + // Eight ranks at 300 rows: runs of 38, the last 34. + if (world == 8) CHECK_EQ(n, rank == 7 ? 34 : 38); + } + } +} + +/* RADIANCE_GLM_MLA_ROWS=2, a test form: the row form's o as the head form computes it, eight + * column slices of the stored weight (each rank's), each GEMM rounded to bf16, then widened and + * added in f32 in ascending slice order and rounded once, as the exact all-reduce folds. */ +TEST(glm_mla_row_form_can_sum_o_as_the_head_form_does) { + using namespace rad::arch; + const int world = 8, rank = 3; + RadBuilder b; + b.kv_block = 4; + // The container's MLA entries; the row form's names are not among them. + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "attn_q_a.weight", fp8 }, + { "attn_kv_a.weight", fp8 }, + { "attn_q_b.weight", fp8 }, + { "attn_output.weight", fp8 }, + { "attn_kv_b.weight", rad_enc_plain(RAD_BF16) } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.max_ctx = 4096; + g.eps = 1e-5; + g.world = world; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + const int64_t T = 512, R = GlmMla::rows_for(T, world), H = 64 / world; + auto act = [&](ActFP8& a, const char* name, int64_t rows, int64_t width) { + a.x = decl_b(&b, name, RAD_BF16, { rows, width }); + return a.declare_qs(&b, nm, g, name, width, rows); + }; + GlmMla::Wire w; + REQUIRE_EQ(act(w.input, "normalized", T, 4096), RAD_OK); + w.q_raw = decl_b(&b, "q_raw", RAD_BF16, { T, 1536 }); + w.kv_raw = decl_b(&b, "kv_raw", RAD_BF16, { T, 512 }); + REQUIRE_EQ(act(w.q_low, "q_low", T, 1536), RAD_OK); + w.latent = decl_b(&b, "latent", RAD_BF16, { T, 512 }); + w.out = decl_b(&b, "attn_delta", RAD_BF16, { world * R, 4096 }); + w.core.q = decl_b(&b, "query", RAD_BF16, { T, 16384 / world }); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { T, H, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { T, H, 512 }); + REQUIRE_EQ(act(w.attn, "expanded", T, 16384 / world), RAD_OK); + w.core.out = w.attn.x; + w.core.selected = decl_b(&b, "selected", RAD_I32, { T, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { T }); + w.rows.q = decl_b(&b, "rows_query", RAD_BF16, { R, 16384 }); + w.rows.q_latent = decl_b(&b, "rows_q_latent", RAD_BF16, { R, 64, 512 }); + w.rows.attn_latent = decl_b(&b, "rows_attn_latent", RAD_BF16, { R, 64, 512 }); + REQUIRE_EQ(act(w.rows.attn, "rows_expanded", R, 16384), RAD_OK); + w.rows.out = decl_b(&b, "rows_out", RAD_BF16, { R, 4096 }); + w.rows.slices = decl_b(&b, "rows_o_slices", RAD_BF16, { world * R, 4096 }); + w.rows.acc = decl_b(&b, "rows_o_sum", RAD_F32, { R, 4096 }); + w.rows.widened = decl_b(&b, "rows_o_slice_f32", RAD_F32, { R, 4096 }); + GlmMla mla; + REQUIRE_EQ(mla.declare(&b, nm, g, 3, w, "model.layers.3.self_attn", kv), RAD_OK); + REQUIRE_EQ(mla.rows_o_slices.size(), (size_t)8); + CHECK(!find_w(b, "blk.3.attn_output_rows.weight")); + for (int k = 0; k < 8; ++k) { + const RecWeight* w = find_w(b, "blk.3.attn_output_rows" + std::to_string(k) + ".weight"); + REQUIRE(w); + CHECK_EQ(w->d.shard, RAD_SHARD_COL); + CHECK_EQ(w->d.shape[1], 2048); + CHECK(w->span_set); + CHECK_EQ(w->span_lo, k * 2048); + CHECK_EQ(w->span_hi, (k + 1) * 2048); + CHECK_EQ(std::string(w->d.source), "blk.3.attn_output.weight"); + } + std::vector slots(300); + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots.data(); + RadBatch batch{}; + batch.kv = &kb; + batch.n_kv_groups = 1; + batch.n_tok = 300; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 3; + ctx.world = 8; + mla.finish_rows(&ctx, 300); + std::vector order; + for (const auto& i : ctx.issues) order.push_back(i.op); + const int64_t run = 38; + int gemm = 0, adds = 0; + for (const auto& i : ctx.issues) { + for (int k = 0; k < 8; ++k) + if (i.op == mla.rows_o_slices[(size_t)k].op) { + ++gemm; + CHECK_EQ(i.opd[0].offset, k * 2048); + CHECK_EQ(i.opd[0].cols, 2048); + CHECK_EQ(i.opd[1].offset, k * 16); + CHECK_EQ(i.opd[1].cols, 16); + CHECK_EQ(i.opd[4].offset, k * run * 4096); + CHECK_EQ(i.opd[4].rows, run); + } + adds += i.op == mla.op_slice_add; + } + CHECK_EQ(gemm, 8); + CHECK_EQ(adds, 7); + CHECK_EQ(ctx.issues.back().op, mla.op_rows_gather); + CHECK_EQ(ctx.issues[ctx.issues.size() - 2].op, mla.op_slice_narrow); +} + TEST( glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { using namespace rad::arch; + // With the row form opted into; unset again however the case leaves. + struct RowsOn { + RowsOn() { setenv("RADIANCE_GLM_MLA_ROWS", "1", 1); } + ~RowsOn() { unsetenv("RADIANCE_GLM_MLA_ROWS"); } + } rows_on; const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; const char* vals[] = { "1", "4", "288", "2048" }; @@ -433,9 +725,10 @@ TEST( CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); // The split is declared on every rank whatever its step size; only rank 0 issues it here. const bool split = world > 1; - // 43 routers (MTP included), the 90 mHC reads, and each of the 12 indexers' page - // tables and lengths; the index head gates follow the indexer's rows, ungathered. - CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 : 0); + // 43 routers (MTP included), the 90 mHC reads, each of the 12 indexers' page + // tables and lengths (the index head gates follow the indexer's rows, + // ungathered), and the 11 MLA row forms (the MTP layer keeps its heads). + CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 + 11 : 0); CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); ctx.issues.clear(); batch.draft_pass = -1; @@ -482,12 +775,17 @@ TEST( CHECK(ctx.step_fail.empty()); { // 512 rows reach the split: each router runs on its column slice, each mHC - // read on its chunks and each indexer, its head gates included, on its run - // of query rows, all gathered but the gates; at TP1 nothing changes. + // read on its chunks, each indexer, its head gates included, on its run + // of query rows, and each MLA on its run of rows, all gathered but the + // gates; at TP1 nothing changes. const auto long_ops = issued_ops(b, ctx); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), - world > 1 ? 42 + 90 + 22 : 0); + world > 1 ? 42 + 90 + 22 + 11 : 0); + // 1 embedding, 45 attention and 45 expert reductions, less the 11 MLA ones. + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_reduce"), + world > 1 ? 91 - 11 : 0); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mla_attn"), 11); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), world > 1 ? 0 : 90); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), @@ -551,6 +849,10 @@ TEST( } } +/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and + * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row + * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its + * gathers' message as a range. */ /* From the split threshold each rank scores its run of the step's query rows (rows past the step * included, which score -inf) and selects for the rows of it that exist, against the bounds the * scorer rebased to the run's first row; two all_gathers join the runs' page tables and lengths @@ -722,10 +1024,6 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) { } } -/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and - * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row - * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its - * gathers' message as a range. */ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -1338,6 +1636,7 @@ TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) /* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill * after history, a mixed step, a decode step, a verify and its draft passes. */ + TEST(glm53_is_the_pinned_graph_and_steps) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -1355,10 +1654,16 @@ TEST(glm53_is_the_pinned_graph_and_steps) { struct Case { int world; uint64_t graph, steps; + bool heads_only = false; /* the default: the graph before the row form */ }; const Case cases[] = { { 1, 0x906897570034f5f5ull, 0x68ffc03d2b640d51ull }, - { 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull } }; + { 8, 0x1d378152c40f8834ull, 0x82ed1094dbf4b637ull }, + { 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull, true } }; for (const Case& cs : cases) { + if (cs.heads_only) + unsetenv("RADIANCE_GLM_MLA_ROWS"); + else + setenv("RADIANCE_GLM_MLA_ROWS", "1", 1); RadBuilder b; b.kv_block = 4; b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, @@ -1376,11 +1681,13 @@ TEST(glm53_is_the_pinned_graph_and_steps) { REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK); const uint64_t g = graph_hash(b); const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world); - fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n", - cs.world, (unsigned long long)g, (unsigned long long)s); + fprintf(stderr, " pin: glm5next world %d%s: graph 0x%016llxull, steps 0x%016llxull\n", + cs.world, cs.heads_only ? " heads only" : "", + (unsigned long long)g, (unsigned long long)s); CHECK_EQ(g, cs.graph); CHECK_EQ(s, cs.steps); } + unsetenv("RADIANCE_GLM_MLA_ROWS"); } /* ==================================================================== GLM-5.3's vision tower */ @@ -1766,13 +2073,13 @@ RAD_TEST_MAIN() /* ==================================================================== the row rule */ -/* GlmTp::run_rows is the one rule the indexer's runs follow, and it is the formula it replaced: - * 4 * ceil(T / (4 * world)) for the indexer's 4-byte lengths, ceil(T / world) for a row of whole - * 16-byte words. At the split threshold, around a chunk and at the largest step, for every - * world: run_of covers the step once with no overlap, the last run short where the step ends - * inside it, and a rank whose run lies wholly past a small step takes the first run instead, so - * the planes it writes and gathers are never unwritten. */ -TEST(glm_tp_row_rule_is_the_old_formula_and_covers_a_step_once) { +/* GlmTp::run_rows is the one rule the MLA's and the indexer's runs follow, and it is the two + * formulas it replaced: ceil(T / world) for the MLA's 8192-byte rows, 4 * ceil(T / (4 * world)) + * for the indexer's 4-byte lengths. At the split threshold, around a chunk and at the largest + * step, for every world: run_of covers the step once with no overlap, the last run short where + * the step ends inside it, and a rank whose run lies wholly past a small step takes the first + * run instead, so the planes it writes and gathers are never unwritten. */ +TEST(glm_tp_row_rule_is_the_two_old_formulas_and_covers_a_step_once) { using namespace rad::arch; for (int world : { 1, 2, 4, 8 }) for (int64_t T : { 1, 5, 6, 48, 255, 256, 257, 300, 2047, 2048, 2049, 4096 }) { @@ -1780,6 +2087,7 @@ TEST(glm_tp_row_rule_is_the_old_formula_and_covers_a_step_once) { const int64_t narrow = GlmTp::run_rows(T, world, 4); CHECK_EQ(wide, (T + world - 1) / world); CHECK_EQ(narrow, 4 * ((T + 4 * world - 1) / (4 * world))); + CHECK_EQ(GlmMla::rows_for(T, world), wide); CHECK_EQ(DsaCache::part_rows(T, world), narrow); CHECK(world * wide >= T); CHECK(world * narrow >= T); @@ -2136,12 +2444,11 @@ std::string as_expert_zero(std::string n) { } /* namespace */ /* Every weight the plugin declares reads an entry the served container holds: under its own name, - * or through `source` for a view (a scale plane), and every GEMM names the dtype its weight's - * stored encoding calls for: `fp8a8f32` on the f32-scaled block FP8, `mxfp4a8` on the MXFP4 - * experts, `bf16` on the plain linears. The encodings come from the table, as the container would - * answer. A weight declared under a name the container does not hold, or a GEMM at a dtype its - * weight's encoding does not call for, passes every host test and leaves bands with no kernel at - * the eight-card start. */ + * or through `source` for a view (a scale plane, the row form's full-width projections), and + * every GEMM names the dtype its weight's stored encoding calls for: `fp8a8f32` on the f32-scaled + * block FP8, `mxfp4a8` on the MXFP4 experts, `bf16` on the plain linears. The encodings come + * from the table, as the container would answer. A full-width view declared as its own weight + * at `fp8a8` passed every host test and left 88 bands with no kernel at the eight-card start. */ TEST(glm53_declares_the_served_containers_names_and_their_encodings) { const Glm53Container& c = glm53_container(); MetaKV mk = glm53_vl_meta(); diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 9699bcde..7ac1acf5 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -1018,6 +1018,66 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) { CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_matrix_bf16 "); } +/* GLM-5.3-Flash's MLA split by rows at eight ranks (arch/common/rad_block_glm_mla.h), with the + * parameters its ops declare against the container's encodings (block fp8 at f32 scales): every + * band of every op the row form adds resolves on the device, up to a 4096-token step's run of + * 512 rows. A form libr4d does not serve would stop a TP8 start at "resolved to no kernel". */ +TEST(libr4d_resolves_every_band_of_glm_mla_split_by_rows) { + const std::string so = libr4d(); + if (so.empty()) return; + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + r.set_device_fact(RAD_FACT_P2P, 1); + auto all_resolve = [&](const char* op, const char* ranged, int64_t lo, int64_t hi, + const Geometry& g) { + const std::vector bands = r.build_bands(op, ranged, lo, hi, g); + bool ok = !bands.empty(); + for (const Band& x : bands) ok = ok && x.dom[RAD_DOMAIN_DEVICE].row; + if (!ok) std::fprintf(stderr, " %s: %s\n", op, band_names(bands).c_str()); + return ok; + }; + const int64_t R = 512; + for (const auto& [n, k] : { std::pair{ 16384, 1536 }, { 4096, 16384 } }) { + Geometry g; + g.set_i("N", n); + g.set_i("K", k); + g.set_i("group", 128); + g.set_s("dtype", "fp8a8f32"); + CHECK(all_resolve("gemm_nt_q", "M", 1, R, g)); + } + for (const char* mode : { "absorb", "expand" }) { + Geometry g; + g.set_i("heads", 64); + g.set_i("head_dim", 256); + g.set_i("latent_dim", 512); + g.set_s("mode", mode); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("mla_project", "M", 1, R, g)); + } + { + Geometry g; + g.set_i("latent_dim", 512); + g.set_i("heads", 64); + g.set_i("blocks", 513); + g.set_i("block_size", 4); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("mla_attn", "M", 1, R, g)); + } + { + Geometry g; + g.set_i("n", 16384); + g.set_i("group", 128); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("quant_act_fp8", "M", 1, 4096, g)); + } + { + Geometry g; + g.set_i("world_size", 8); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("all_gather", "numel", 4096, 4096 * 4096, g)); + } +} + /* ================================================================== constraints that are not intervals */ namespace { std::string extra_dir() { return home() + "/testkernels/extra"; } From d90e19dc15fdadb699fbf509938bcc13adf2d1ee Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:15 +0200 Subject: [PATCH 18/35] r4d_emu: the MLA row form against the head form, element by element Three host checks of where GLM's MLA split by rows can part from the split by heads: - the f32-scale E4M3 GEMM gives a run of rows and a slice of columns the whole product's bytes there, so q_b and o at full width over a rank's rows match the head form's slices; - a TP8 step of 300 rows: each rank's run, placed as the all_gather places it (rank r's 38 rows at r * 38, the last 34), lands on its rows; - row by row on a prefill chunk past the DSA budget, bit for bit against the paired union tile: the 16-head tile gives the union's first rows exactly and differs from its second rows in about 0.1 % of their outputs by one bf16 step; the rows kernel differs in about 0.1 % of every row's outputs, by the same step. Co-Authored-By: Claude Opus 5.5 --- tests/r4d_emu/test_fp8f32.cpp | 45 +++++++++++++++ tests/r4d_emu/test_mla.cpp | 102 ++++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+) diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp index ed13c58a..4b94e9a8 100644 --- a/tests/r4d_emu/test_fp8f32.cpp +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -270,6 +270,51 @@ int main() { } } fails += grouped_cases(cases); + { + /* A run of rows and a slice of columns give the bytes the whole product has there: GLM's + * MLA split by rows computes q_b and o over a rank's rows at full width, the head form + * over every row at a slice of the columns (or of K, as eight rank partials). */ + const int M = 130, N = 1024, K = 512, kb = K / 128, r0 = 37, mr = 33, c0 = 256, nc = 256; + std::vector a((size_t)M * K), w((size_t)N * K); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); + std::vector as((size_t)M * kb), ws((size_t)(N / 128) * kb); + std::uniform_real_distribution oct(-6.f, 6.f); + for (auto& v : as) v = std::exp2(oct(rng)); + for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f; + auto gemm = [&](int rows, int cols, int row0, int col0, std::vector& y) { + y.assign((size_t)rows * cols, 0x7777); + RadTensor t[7] = { mat(a.data() + (size_t)row0 * K, RAD_F8E4M3, rows, K, K), + mat(as.data() + (size_t)row0 * kb, RAD_F32, rows, kb, kb), + mat(w.data() + (size_t)col0 * K, RAD_F8E4M3, cols, K, K), + mat(ws.data() + (size_t)(col0 / 128) * kb, RAD_F32, cols / 128, kb, + kb), + mat(y.data(), RAD_BF16, rows, cols, cols), RadTensor{}, RadTensor{} }; + RadParam p[5]{}; + p[0] = { "M", RAD_P_INT, rows }; + p[1] = { "N", RAD_P_INT, cols }; + p[2] = { "K", RAD_P_INT, K }; + p[3] = { "group", RAD_P_INT, 128 }; + p[4].key = "dtype"; + p[4].kind = RAD_P_STR; + p[4].sval = "fp8a8f32"; + RadArgs ar{}; + ar.t = t; + ar.n_t = 7; + ar.p = p; + ar.n_p = 5; + return r4d_rad_fp8_f32scale(&ar, nullptr); + }; + std::vector whole, part; + ++cases; + bool same = gemm(M, N, 0, 0, whole) == RAD_OK && gemm(mr, nc, r0, c0, part) == RAD_OK; + for (int r = 0; same && r < mr; ++r) + for (int c = 0; c < nc; ++c) + same = same && part[(size_t)r * nc + c] == whole[(size_t)(r0 + r) * N + c0 + c]; + std::printf("%s rows %d..%d x columns %d..%d alone against the %dx%d product\n", + same ? "ok " : "FAIL", r0, r0 + mr, c0, c0 + nc, M, N); + fails += !same; + } std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp index e02eb53c..55aa7cc0 100644 --- a/tests/r4d_emu/test_mla.cpp +++ b/tests/r4d_emu/test_mla.cpp @@ -541,10 +541,26 @@ int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) { std::vector heads_out((size_t)T * H * D, 0xffff), rows_out((size_t)T * H * D, 0xffff); const int per_heads = H / world, run = (T + world - 1) / world; int fails = 0; + /* What each rank's run buffer holds after its rows: written through the same launches into + * the plane at the run's rows, then copied out as the all_gather moves it, rank r's run of + * `run` rows to rows [r * run, (r + 1) * run) of a [world * run] output. */ + std::vector gathered((size_t)world * run * H * D, 0xffff); for (int rank = 0; rank < world; ++rank) { fails += launch(false, 0, T, rank * per_heads, per_heads, heads_out) != RAD_OK; const int first = rank * run, n = std::min(run, T - first); if (n > 0) fails += launch(true, first, n, 0, H, rows_out) != RAD_OK; + std::vector part((size_t)run * H * D, 0xeeee); + for (int r = 0; r < n; ++r) + std::copy(rows_out.begin() + (size_t)(first + r) * H * D, + rows_out.begin() + (size_t)(first + r + 1) * H * D, + part.begin() + (size_t)r * H * D); + std::copy(part.begin(), part.end(), gathered.begin() + (size_t)rank * run * H * D); + } + bool placed = true; + for (size_t i = 0; i < (size_t)T * H * D; ++i) placed = placed && gathered[i] == rows_out[i]; + if (!placed) { + std::printf("%-40s the gathered runs do not land on their rows FAIL\n", name); + ++fails; } long bad[2] = { 0, 0 }; double max_err[2] = { 0, 0 }, apart = 0; @@ -565,6 +581,87 @@ int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) { return !ok; } +/* The head form against the row form, row by row and bit by bit, on a TP8 prefill chunk past the + * DSA budget: the head form is the paired union tile (eight heads of rows 2i and 2i+1), the row + * form's two kernels are the 16-head matrix tile (RADIANCE_MLA_ROWS_FORM=4) and the rows kernel. + * The union's first row of a pair walks its own table in its own order, as the 16-head tile does, + * so it must agree to the bit; the second row and the rows kernel sum in other orders, within + * rounding. Printed: rows bit-identical, elements differing, and the largest step in bf16 units. */ +int run_rowwise(std::mt19937& rng) { + constexpr int H = 64, B = 65, M = 16; + std::vector bt, len; + int pages = 0; + topk_tables(M, B, 1200, 16, rng, bt, len, pages); + std::normal_distribution nrm(0.f, 1.f); + std::vector qb((size_t)M * H * D), kvb((size_t)pages * BS * D); + for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); + for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); + auto launch = [&](int kernel, int h0, int heads, std::vector& out) { + RadTensor t[5] = { tens(qb.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }), + tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), + tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }), + tens(out.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }) }; + t[0].stride[0] = t[4].stride[0] = (int64_t)H * D; + RadParam p[6]{}; + const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" }; + const long long vals[5] = { M, D, heads, B, BS }; + for (int i = 0; i < 5; ++i) { + p[i].key = keys[i]; + p[i].kind = RAD_P_INT; + p[i].ival = vals[i]; + } + p[5].key = "scale"; + p[5].kind = RAD_P_F64; + p[5].dval = 0.0625; + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p; + a.n_p = 6; + if (kernel < 2) return r4d_rad_mla_attn_matrix(&a, nullptr); + r4d_mla_rows_pin_form(3); + const int rc = r4d_rad_mla_attn_rows(&a, nullptr); + r4d_mla_rows_pin_form(0); + return rc; + }; + std::vector head((size_t)M * H * D), m16((size_t)M * H * D), rows((size_t)M * H * D); + int rc = 0; + for (int r = 0; r < 8; ++r) rc |= launch(0, r * 8, 8, head); + rc |= launch(1, 0, H, m16); + rc |= launch(2, 0, H, rows); + auto ord = [](uint16_t h) { return (h & 0x8000) ? -(int)(h & 0x7fff) : (int)h; }; + int fails = rc != RAD_OK; + for (const auto& [name, got] : { std::pair*>{ + "16-head tile", &m16 }, + { "rows kernel", &rows } }) { + int same_even = 0, same_odd = 0, max_ulp = 0; + long diff = 0; + double max_abs = 0; + for (size_t i = 0; i < head.size(); ++i) + max_abs = std::max(max_abs, (double)std::fabs(rad_bf16_to_f32((*got)[i]) - + rad_bf16_to_f32(head[i]))); + for (int r = 0; r < M; ++r) { + bool same = true; + for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) { + const int u = std::abs(ord((*got)[i]) - ord(head[i])); + same = same && !u; + diff += u != 0; + max_ulp = std::max(max_ulp, u); + } + (r % 2 ? same_odd : same_even) += same; + } + /* The 16-head tile must give the union's first rows bit for bit. */ + const bool ok = std::strcmp(name, "16-head tile") || same_even == M / 2; + std::printf("rowwise: %-12s vs head form (union pairs): rows bit-identical %d/%d first, " + "%d/%d second of a pair; %ld of %d elements differ, at most %d bf16 steps, " + "max abs %.2e %s\n", + name, same_even, M / 2, same_odd, M / 2, diff, M * H * D, max_ulp, max_abs, + ok ? "PASS" : "FAIL"); + fails += !ok; + } + return fails; +} + /* The launcher prints the running totals every 1024th counted launch and must leave them * standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */ int periodic_report() { @@ -669,11 +766,16 @@ int main(int argc, char** argv) { std::mt19937 rng(20261020u + (unsigned)i); fails += run_rows(rows_cases[i], rng); } + if (!filter || std::strstr("rowwise", filter)) { + std::mt19937 rng(20261022u); + fails += run_rowwise(rng); + } /* T 45 over eight ranks: runs of 6, the last of 3; 37 over four: 10 and 7; 48: whole runs. */ const struct { const char* name; int world, fresh; } splits[] = { { "split: heads vs rows, 8 ranks", 8, 15 }, + { "split: heads vs rows, 8 ranks, T 300", 8, 270 }, { "split: heads vs rows, 4 ranks", 4, 7 }, { "split: heads vs rows, whole runs", 8, 18 } }; for (size_t i = 0; i < sizeof splits / sizeof splits[0]; ++i) { From 3aded1bbf8bf33e50ce5eeceb87d1cdf745e3ef9 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:17 +0200 Subject: [PATCH 19/35] server: DELETE /sessions forgets one stored conversation A client that deleted a conversation, or compacted it past a prefix, knows the rest is dead before --prefix-cache-ttl does. DELETE /sessions/