From e2be75bc130d7291ac111c7354ee31dd0c29199b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:01:32 +0000 Subject: [PATCH 01/89] metal: Spark2.5's and Llama's prompt attention from one source, Llama at WINDOW and RING 0 (#2251) --- .../prompt_attention_nax.metal} | 6 +- zig/kernels/metal/llama/attention_nax.metal | 204 ------------------ zig/kernels/metal/sources.zig | 10 +- zig/src/families/llama/contracts.zig | 2 +- zig/tests/contract/metal_llama_controls.zig | 2 +- .../contract/metal_spark25_attention.zig | 2 +- 6 files changed, 12 insertions(+), 214 deletions(-) rename zig/kernels/metal/{spark25/attention_nax.metal => core/prompt_attention_nax.metal} (96%) delete mode 100644 zig/kernels/metal/llama/attention_nax.metal diff --git a/zig/kernels/metal/spark25/attention_nax.metal b/zig/kernels/metal/core/prompt_attention_nax.metal similarity index 96% rename from zig/kernels/metal/spark25/attention_nax.metal rename to zig/kernels/metal/core/prompt_attention_nax.metal index 7fcef62616b..08cff5f79a2 100644 --- a/zig/kernels/metal/spark25/attention_nax.metal +++ b/zig/kernels/metal/core/prompt_attention_nax.metal @@ -1,8 +1,8 @@ -// Spark2.5's prompt attention on the tensor units (gemma4's prompt kernel over a [slot, KVH, DH] cache). +// Spark2.5's and Llama's prompt attention on the tensor units (gemma4's prompt kernel over a [slot, KVH, DH] cache). #include "../nax.h" using namespace tfp; -// Defines: DH (256), NQ, G (query heads a key head), KVH, WINDOW (0: full), RING (0 or a multiple of 64), SCALE. +// Defines: TF_PROMPT_ATTENTION (its name), DH, NQ, G (query heads a key head), KVH, WINDOW (0: full), RING, SCALE. constant constexpr int LD = KVH * DH; constant constexpr float kMasked = -3.402823466e+38f; @@ -71,7 +71,7 @@ inline void prob_put(threadgroup PT* pt, int r, int c, short2 home, thread const // Q [R, NQ, DH] at positions p0..; K, V the layer's cache; O [R, NQ, DH]. P: rows, p0. A tile is RT rows of a head. [[max_total_threads_per_threadgroup(256)]] -[[kernel]] void sp_prompt_attention(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], +[[kernel]] void TF_PROMPT_ATTENTION(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], const device bfloat* V [[buffer(2)]], device bfloat* O [[buffer(3)]], constant int2& P [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], diff --git a/zig/kernels/metal/llama/attention_nax.metal b/zig/kernels/metal/llama/attention_nax.metal deleted file mode 100644 index c2642c4896f..00000000000 --- a/zig/kernels/metal/llama/attention_nax.metal +++ /dev/null @@ -1,204 +0,0 @@ -// Llama's prompt attention on the tensor units (gemma4's prompt kernel over a [position, KVH, DH] cache). -#include "../nax.h" -using namespace tfp; - -// Defines: DH (128), NQ, G (query heads a key head), KVH, SCALE. Every layer attends to every key before. - -constant constexpr int LD = KVH * DH; -constant constexpr float kMasked = -3.402823466e+38f; -constant constexpr float kLog2e = 1.44269504089f; - -// Row max (MAX) or sum over a fragment's 32 columns into r[0], r[1] (rows home.y, home.y + 8). -template -inline void fold(thread const frag& f, thread float* r) { - TF_UNROLL - for (short h = 0; h < 2; h++) { - const short b = 4 * h; - float t = MAX ? max(max(f[b], f[b + 1]), max(f[b + 2], f[b + 3])) : (f[b] + f[b + 1]) + (f[b + 2] + f[b + 3]); - const float u = simd_shuffle_xor(t, ushort(1)); - t = MAX ? max(t, u) : t + u; - const float w = simd_shuffle_xor(t, ushort(8)); - t = MAX ? max(t, w) : t + w; - r[h] = MAX ? max(r[h], t) : r[h] + t; - } -} - -constant constexpr int RT = 32; // query rows a tile -constant constexpr int NS = DH / 64; // simdgroups a tile, each its own 64 output columns -constant constexpr int KS = 32; // keys a simdgroup a block -constant constexpr int BKT = KS * NS; // keys a block -constant constexpr int PH = BKT < 128 ? BKT : 128; // keys whose probabilities cross threadgroup memory at once -constant constexpr int PP = PH + 8; // the probabilities' row pitch -using PT = float; - -template -inline frag blk(const device bfloat* p, int ld, int r, int c, short2 home) { -#ifndef TF_SIMD_FRAGS - const device bfloat* q = p + (r + home.y) * ld + c + home.x; - return frag(*(const device bfloat4*)q, *(const device bfloat4*)(q + 8 * ld)); -#else - frag f; - if (TR) { - frag_get_t(f, p, ld, r, c, home); - } else { - frag_get(f, p, ld, r, c, home); - } - return f; -#endif -} - -inline frag prob_frag(const threadgroup PT* pt, int r, int c, short2 home) { -#ifndef TF_SIMD_FRAGS - const threadgroup PT* q = pt + (r + home.y) * PP + c + home.x; - return frag(*(const threadgroup vec*)q, *(const threadgroup vec*)(q + 8 * PP)); -#else - frag f; - frag_get(f, pt, PP, r, c, home); - return f; -#endif -} - -inline void prob_put(threadgroup PT* pt, int r, int c, short2 home, thread const frag& s) { -#ifndef TF_SIMD_FRAGS - threadgroup PT* q = pt + (r + home.y) * PP + c + home.x; - *(threadgroup vec*)q = vec(s[0], s[1], s[2], s[3]); - *(threadgroup vec*)(q + 8 * PP) = vec(s[4], s[5], s[6], s[7]); -#else - TF_UNROLL - for (short e = 0; e < 8; e++) pt[(r + home.y + (e >> 2) * 8) * PP + c + home.x + TF_COL(e)] = PT(s[e]); -#endif -} - -// Q [R, NQ, DH] at positions p0..; K, V the layer's cache; O [R, NQ, DH]. P: rows, p0. A tile is RT rows of a head. -[[max_total_threads_per_threadgroup(256)]] -[[kernel]] void ll_prompt_attention(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], - const device bfloat* V [[buffer(2)]], device bfloat* O [[buffer(3)]], - constant int2& P [[buffer(4)]], - uint sg [[simdgroup_index_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { - const int R = P.x, p0 = P.y; - const int qh = int(tg.y), kv = qh / G; - const int r0 = int(tg.x) * RT; - const int q_rows = min(RT, R - r0); - const int qs = NQ * DH; - const device bfloat* q = Q + r0 * qs + qh * DH; - const device bfloat* kc = K + kv * DH; - const device bfloat* vc = V + kv * DH + int(sg) * 64; - const short2 home = frag_home(ushort(lane)); - threadgroup PT pt[RT * PP]; - threadgroup float rowmax[NS][RT]; - frag acc[8]; - TF_UNROLL - for (short i = 0; i < 8; i++) acc[i] = frag(0); - float top[4] = {kMasked, kMasked, kMasked, kMasked}, total[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - const int first_pos = p0 + r0, last_pos = p0 + r0 + q_rows - 1; // the tile's last key - for (int kb = 0; kb <= last_pos / BKT; kb++) { - const int kpos = kb * BKT + int(sg) * KS; - const device bfloat* kblk = kc + long(kpos) * LD; - frag s[4]; - TF_UNROLL - for (short i = 0; i < 4; i++) s[i] = frag(0); - for (int d = 0; d < DH / 16; d++) { - const frag k0 = blk(kblk, LD, 0, 16 * d, home); - const frag k1 = blk(kblk, LD, 16, 16 * d, home); - TF_UNROLL - for (short h = 0; h < 2; h++) { // rows past q_rows read inside the chunk's buffer; their outputs stay unwritten - const frag qf = blk(q, qs, 16 * h, 16 * d, home); - mma_16x32(s[2 * h], s[2 * h + 1], qf, k0, k1); - } - } - TF_UNROLL - for (short i = 0; i < 4; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) { - const int local = 16 * (i >> 1) + home.y + (e >> 2) * 8, row = first_pos + local; - const int col = kpos + 16 * (i & 1) + home.x + TF_COL(e); - s[i][e] = col > row ? kMasked : s[i][e] * (SCALE * kLog2e); - } - } - float top_new[4] = {top[0], top[1], top[2], top[3]}; - TF_UNROLL - for (short i = 0; i < 4; i++) fold(s[i], top_new + 2 * (i >> 1)); - if (home.x == 0) { - TF_UNROLL - for (short j = 0; j < 4; j++) rowmax[sg][home.y + 8 * j] = top_new[j]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - TF_UNROLL - for (short j = 0; j < 4; j++) { - for (int t = 0; t < NS; t++) top_new[j] = max(top_new[j], rowmax[t][home.y + 8 * j]); - } - TF_UNROLL - for (short i = 0; i < 4; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) { - s[i][e] = s[i][e] == kMasked ? 0.0f : fast::exp2(s[i][e] - top_new[2 * (i >> 1) + (e >> 2)]); - } - } - float keep[4]; - TF_UNROLL - for (short j = 0; j < 4; j++) { - keep[j] = top[j] == kMasked ? 0.0f : fast::exp2(top[j] - top_new[j]); - top[j] = top_new[j]; - total[j] = total[j] * keep[j]; - } - TF_UNROLL - for (short i = 0; i < 4; i++) fold(s[i], total + 2 * (i >> 1)); - TF_UNROLL - for (short i = 0; i < 8; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * keep[2 * (i >> 2) + (e >> 2)]; - } - for (int ph = 0; ph < BKT / PH; ph++) { - if (ph > 0) threadgroup_barrier(mem_flags::mem_threadgroup); // the phase before has read the tile - if (int(sg) / (PH / KS) == ph) { - TF_UNROLL - for (short i = 0; i < 4; i++) prob_put(pt, 16 * (i >> 1), int(sg) * KS - ph * PH + 16 * (i & 1), home, s[i]); - } - threadgroup_barrier(mem_flags::mem_threadgroup); - for (int kk = 0; kk < PH / 16; kk++) { - const int kp = kb * BKT + ph * PH + 16 * kk; - if (kp > last_pos) break; // keys past the tile's rows: masked, and their cache rows may hold anything - const int valid = min(16, last_pos + 1 - kp); // a value row never written would poison the tile as 0 x NaN - const device bfloat* vblk = vc + long(kp) * LD; - frag v0, v1; - TF_UNROLL - for (short d = 0; d < 4; d += 2) { - if (valid == 16) { - v0 = blk(vblk, LD, 0, 16 * d, home); - v1 = blk(vblk, LD, 0, 16 * d + 16, home); - } else { - frag_get_in(v0, vblk, LD, 0, 16 * d, home, valid, DH); - frag_get_in(v1, vblk, LD, 0, 16 * d + 16, home, valid, DH); - } - TF_UNROLL - for (short h = 0; h < 2; h++) { - const frag pf = prob_frag(pt, 16 * h, 16 * kk, home); - mma_16x32(acc[4 * h + d], acc[4 * h + d + 1], pf, v0, v1); - } - } - } - } - } - // the tile's totals: every simdgroup's partial sums, scaled alike by the shared maxes - threadgroup_barrier(mem_flags::mem_threadgroup); - if (home.x == 0) { - TF_UNROLL - for (short j = 0; j < 4; j++) rowmax[sg][home.y + 8 * j] = total[j]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - float inv[4]; - TF_UNROLL - for (short j = 0; j < 4; j++) { - float t = 0.0f; - for (int u = 0; u < NS; u++) t += rowmax[u][home.y + 8 * j]; - inv[j] = 1.0f / t; - } - device bfloat* o = O + r0 * qs + qh * DH + int(sg) * 64; - TF_UNROLL - for (short i = 0; i < 8; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) acc[i][e] = acc[i][e] * inv[2 * (i >> 2) + (e >> 2)]; - frag_put_in(acc[i], o, qs, 16 * (i >> 2), 16 * (i & 3), home, q_rows, 64); - } -} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index ee5748d68e6..5f178dd7400 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -214,14 +214,16 @@ pub const step5_attend_nax = @embedFile("step5/attend_nax.metal"); pub const step5_vision = vision_glue ++ @embedFile("step5/vision.metal"); /// Spark2.5's glue at its PyTorch rounding points: embed, fp32 residual adds and norms, rope, head gate, exact GELU. pub const spark25_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("spark25/glue.metal"); -/// Spark2.5's prompt attention on the tensor units (gemma4's prompt kernel; nax.h inlined at load). -pub const spark25_attention_nax = @embedFile("spark25/attention_nax.metal"); +/// Spark2.5's and Llama's prompt attention on the tensor units (gemma4's prompt kernel; nax.h inlined at load). +const prompt_attention_nax = @embedFile("core/prompt_attention_nax.metal"); +/// Spark2.5's prompt attention (core/prompt_attention_nax.metal as sp_prompt_attention). +pub const spark25_attention_nax = "#define TF_PROMPT_ATTENTION sp_prompt_attention\n" ++ prompt_attention_nax; /// Spark2.5's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). pub const spark25_gemm = gemm_nax ++ @embedFile("spark25/gemm.metal"); /// Llama's glue at HF's rounding points: embed, a bf16 residual and its norm, rope with bf16 cos and sin, SiLU. pub const llama_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("llama/glue.metal"); -/// Llama's prompt attention on the tensor units (gemma4's prompt kernel, every key; nax.h inlined at load). -pub const llama_attention_nax = @embedFile("llama/attention_nax.metal"); +/// Llama's prompt attention: core/prompt_attention_nax.metal as ll_prompt_attention (its loader: WINDOW and RING 0). +pub const llama_attention_nax = "#define TF_PROMPT_ATTENTION ll_prompt_attention\n" ++ prompt_attention_nax; /// Llama's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). pub const llama_gemm = gemm_nax ++ @embedFile("llama/gemm.metal"); /// The kernel contract's planted controls: one kernel breaking each gate (zig/tests/contract/). diff --git a/zig/src/families/llama/contracts.zig b/zig/src/families/llama/contracts.zig index 5fcb1ddefd1..dd580e42f6d 100644 --- a/zig/src/families/llama/contracts.zig +++ b/zig/src/families/llama/contracts.zig @@ -49,7 +49,7 @@ pub fn attentionSource(device: mtl.Device, a: std.mem.Allocator, g: Geometry) ![ pub fn attentionSourceHeads(device: mtl.Device, a: std.mem.Allocator, heads: usize, kv_heads: usize) ![]u8 { const body = try frags.source(device, a, ks.llama_attention_nax); defer a.free(body); - return std.fmt.allocPrint(a, "#define DH {d}\n#define NQ {d}\n#define G {d}\n#define KVH {d}\n#define SCALE {e}f\n{s}", .{ cfg.head_dim, heads, heads / kv_heads, kv_heads, cfg.headScale(), body }); + return std.fmt.allocPrint(a, "#define DH {d}\n#define NQ {d}\n#define G {d}\n#define KVH {d}\n#define WINDOW 0\n#define RING 0\n#define SCALE {e}f\n{s}", .{ cfg.head_dim, heads, heads / kv_heads, kv_heads, cfg.headScale(), body }); } /// The GEMM forms' text as model.zig builds it. diff --git a/zig/tests/contract/metal_llama_controls.zig b/zig/tests/contract/metal_llama_controls.zig index 3a536d1ee29..9f1624cd443 100644 --- a/zig/tests/contract/metal_llama_controls.zig +++ b/zig/tests/contract/metal_llama_controls.zig @@ -67,7 +67,7 @@ pub const Mutation = enum { .merge_unscaled_mass => .{ .from = "ls[b] * fast::exp(ms[b] - top) : 0.0f;", .to = "ls[b] : 0.0f;" }, .matvec_drops_tail => .{ .from = "for (uint i = 8 * lane; i < a.k; i += 256) {", .to = "for (uint i = 8 * lane; i + 256 - 8 * lane <= a.k; i += 256) {" }, .gemm_untransposed => .{ .from = "TF_GEMM_NAX_KERNEL(ll_gemm_00, bfloat16_t, false, true, false, false)", .to = "TF_GEMM_NAX_KERNEL(ll_gemm_00, bfloat16_t, false, false, false, false)" }, - .prompt_sees_next_key => .{ .from = "col > row ? kMasked", .to = "col > row + 1 ? kMasked" }, + .prompt_sees_next_key => .{ .from = "const bool out = col > row ||", .to = "const bool out = col > row + 1 ||" }, .q4_matvec_first_zero => .{ .from = "z = ll_q4_zero(Z, j, g, groups);", .to = "z = ll_q4_zero(Z, j, 0, groups);" }, .q4_dequant_reversed_nibbles => .{ .from = "out[e] = bfloat(ll_q4(word, e, z, s));", .to = "out[e] = bfloat(ll_q4(word, 7 - e, z, s));" }, }; diff --git a/zig/tests/contract/metal_spark25_attention.zig b/zig/tests/contract/metal_spark25_attention.zig index 42f36c1bd22..e2ad37c7b1e 100644 --- a/zig/tests/contract/metal_spark25_attention.zig +++ b/zig/tests/contract/metal_spark25_attention.zig @@ -1,4 +1,4 @@ -//! Spark-X2.6-4B's prompt attention (spark25/attention_nax.metal) as metal_model.zig builds it, both layer kinds. +//! Spark-X2.6-4B's prompt attention (core/prompt_attention_nax.metal) as metal_model.zig builds it, both layer kinds. const std = @import("std"); const mtl = @import("metal"); const tf = @import("tensorfold"); From c916bea0ff5b5beb44c66906887796f28b37d269 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:01:38 +0000 Subject: [PATCH 02/89] metal: a host test pins Llama's fold of the shared prompt attention at WINDOW 0 and RING 0 (#2251) Every line of core/prompt_attention_nax.metal that names WINDOW or RING must be one of its four guarded forms, the mask line among them, and Llama's loader must define both as 0 over the shared text, so a later edit can't unfold it. A control checks that an unguarded window term or a missing mask line fails. It runs in test-kernel-symbols-host. --- zig/tests/kernel_symbols.zig | 4 ++ zig/tests/prompt_attention_fold.zig | 80 +++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 zig/tests/prompt_attention_fold.zig diff --git a/zig/tests/kernel_symbols.zig b/zig/tests/kernel_symbols.zig index 21bb6f5cc91..87d81548f36 100644 --- a/zig/tests/kernel_symbols.zig +++ b/zig/tests/kernel_symbols.zig @@ -151,3 +151,7 @@ test "lookup scanner handles whitespace, comments and trailing commas but exclud try std.testing.expectEqualStrings("tf_one", names.items[0]); try std.testing.expectEqualStrings("tf_two", names.items[1]); } + +test { + _ = @import("prompt_attention_fold.zig"); +} diff --git a/zig/tests/prompt_attention_fold.zig b/zig/tests/prompt_attention_fold.zig new file mode 100644 index 00000000000..1604c0f3e84 --- /dev/null +++ b/zig/tests/prompt_attention_fold.zig @@ -0,0 +1,80 @@ +//! Llama's prompt attention: its loader's WINDOW 0 and RING 0 fold the shared text to its old full-attention kernel. +const std = @import("std"); + +const shared_path = "zig/kernels/metal/core/prompt_attention_nax.metal"; +const loader_path = "zig/src/families/llama/contracts.zig"; +const sources_path = "zig/kernels/metal/sources.zig"; + +/// The mask line: at WINDOW 0 its window term drops, leaving Llama's old `col > row`. +const mask_line = "const bool out = col > row || (WINDOW && col < row - WINDOW + 1);"; + +/// Every code line that may name WINDOW or RING: each guarded, so 0 gives Llama's old expression. +const guarded = [_][]const u8{ + "const int lo = WINDOW ? max(0, first_pos - WINDOW + 1) : 0;", + "const int slot = RING ? kpos % RING : kpos;", + mask_line, + "const device bfloat* vblk = vc + long(RING ? kp % RING : kp) * LD;", +}; + +fn identifier(ch: u8) bool { + return std.ascii.isAlphanumeric(ch) or ch == '_'; +} + +fn word(text: []const u8, name: []const u8) bool { + var start: usize = 0; + while (std.mem.indexOfPos(u8, text, start, name)) |at| { + const end = at + name.len; + if ((at == 0 or !identifier(text[at - 1])) and (end == text.len or !identifier(text[end]))) return true; + start = at + 1; + } + return false; +} + +/// Whether every code line naming WINDOW or RING is one of the guarded lines, the mask line among them. +fn folds(text: []const u8) bool { + var mask = false; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (std.mem.startsWith(u8, line, "//")) continue; + if (!word(line, "WINDOW") and !word(line, "RING")) continue; + const known = for (guarded) |g| { + if (std.mem.eql(u8, line, g)) break true; + } else false; + if (!known) return false; + if (std.mem.eql(u8, line, mask_line)) mask = true; + } + return mask; +} + +fn read(a: std.mem.Allocator, path: []const u8) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, a, .limited(4 << 20)); +} + +test "prompt attention fold: Llama's loader defines WINDOW 0 and RING 0 over the shared text, every use guarded" { + const a = std.testing.allocator; + const shared = try read(a, shared_path); + defer a.free(shared); + try std.testing.expect(folds(shared)); + const loader = try read(a, loader_path); + defer a.free(loader); + const at = std.mem.indexOf(u8, loader, "pub fn attentionSourceHeads(") orelse return error.NoLoader; + const end = std.mem.indexOfPos(u8, loader, at, "\n}\n") orelse return error.NoLoader; + try std.testing.expect(std.mem.indexOf(u8, loader[at..end], "#define WINDOW 0\\n#define RING 0\\n") != null); + const sources = try read(a, sources_path); + defer a.free(sources); + try std.testing.expect(std.mem.indexOf(u8, sources, "const prompt_attention_nax = @embedFile(\"core/prompt_attention_nax.metal\");") != null); + try std.testing.expect(std.mem.indexOf(u8, sources, "pub const llama_attention_nax = \"#define TF_PROMPT_ATTENTION ll_prompt_attention\\n\" ++ prompt_attention_nax;") != null); +} + +test "control: an unguarded window term or a missing mask line breaks the fold" { + const a = std.testing.allocator; + const shared = try read(a, shared_path); + defer a.free(shared); + const bare = try std.mem.replaceOwned(u8, a, shared, "(WINDOW && col", "(col"); + defer a.free(bare); + try std.testing.expect(!folds(bare)); + const unmasked = try std.mem.replaceOwned(u8, a, shared, mask_line, "const bool out = col > row;"); + defer a.free(unmasked); + try std.testing.expect(!folds(unmasked)); +} From 434fc62552cf0a8b6fbedf6cdbc9f61510972a96 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:01:47 +0000 Subject: [PATCH 03/89] Record the shared prompt attention under Unreleased --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef9e309bbb1..bc0f5384aba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: `zig build test-tokenizer-host` runs every tokenizer test, unfiltered, on the host without a GPU or shader compiler, and is part of the nightly Linux and macOS fast checks; before, CI reached only the tokenizer's two EOS policy tests (#3082). - Bench: add served agent-cache traces and token-qualified A/B comparisons (#3263). - CI: remove the redundant nightly Linux host shard while retaining the fast, compile, HIP and DeepSeek shards (#3276). +- Metal: Spark2.5 and Llama build their tensor-unit prompt attention from one shared source, Llama's at WINDOW 0 and RING 0; the compiled code is unchanged (#3269, part of #2251). Thanks to @jschmied. - Docs: the README is now a short quick start and docs list; setup, serve flags and model tables moved to the new run guide and supported models pages, and the Zig preview and 1.0.0 release notes moved into docs/ (#3170). Thanks to @jayleaton. From 3f07f6e12f133f5db3f9239471091e72f50c4eeb Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:50:44 +0100 Subject: [PATCH 04/89] dsv41 metal: time-dsv41-metal-synth times synthetic release-shape layers per row and dispatch class Six synthetic layers of the release's widths (one of each attention kind, few experts) are timed at 1-16 rows of one slot and at 4 slots x 1 row, each dispatch alone and the layer on the serving encoder, and split into FP8 rows, experts, attention and glue, with a 40-layer round weighted by kind. timing_real's report takes a launch (context and spans) so both harnesses share it. --- zig/build/dsv41_metal.zig | 11 ++ zig/tests/dsv41_metal/timing_real.zig | 80 ++++++++++---- zig/tests/dsv41_metal/timing_synth.zig | 146 +++++++++++++++++++++++++ 3 files changed, 214 insertions(+), 23 deletions(-) create mode 100644 zig/tests/dsv41_metal/timing_synth.zig diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index 1de16b75335..ba1a6593f31 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -96,6 +96,17 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const timing_run = b.addRunArtifact(b.addTest(.{ .root_module = timing })); timing_run.has_side_effects = true; b.step("time-dsv41-metal-real", "DeepSeek-V4.1 Metal: one release layer's decode timed at 1 and 4 rows").dependOn(&timing_run.step); + // synthetic layers of the release's shapes (no checkpoint): dispatch classes a row at 1-16 rows and 4 slots + const synth = b.createModule(.{ + .root_source_file = b.path("zig/tests/dsv41_metal/timing_synth.zig"), + .target = b.graph.host, + .optimize = .ReleaseFast, + .link_libc = true, + .imports = &.{ .{ .name = "dsv41_metal", .module = quick.pkg }, .{ .name = "metal", .module = metal }, .{ .name = "dsv41", .module = quick.host }, .{ .name = "kernel_sources", .module = sources } }, + }); + const synth_run = b.addRunArtifact(b.addTest(.{ .root_module = synth })); + synth_run.has_side_effects = true; + b.step("time-dsv41-metal-synth", "DeepSeek-V4.1 Metal: synthetic release-shape layers timed per row and dispatch class").dependOn(&synth_run.step); const ptime = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/prompt_time.zig"), .target = b.graph.host, diff --git a/zig/tests/dsv41_metal/timing_real.zig b/zig/tests/dsv41_metal/timing_real.zig index 5e41dbd0e09..58124a83c40 100644 --- a/zig/tests/dsv41_metal/timing_real.zig +++ b/zig/tests/dsv41_metal/timing_real.zig @@ -40,9 +40,9 @@ fn open(a: std.mem.Allocator, io: std.Io, dir: []const u8, layer: u32) !*fixture } /// Bytes written between timed launches so no weight stays in the GPU's caches, as in a 40-layer token. -const flush_bytes = 1 << 30; +pub const flush_bytes = 1 << 30; -fn flush(r: *fixture.Rig, junk: mtl.Buffer) void { +pub fn flush(r: *fixture.Rig, junk: mtl.Buffer) void { const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = r.queue.commandBuffer(); @@ -57,19 +57,19 @@ fn lessThan(_: void, x: f64, y: f64) bool { return x < y; } -fn median(v: []f64) f64 { +pub fn median(v: []f64) f64 { std.mem.sort(f64, v, {}, lessThan); return v[v.len / 2]; } /// The fastest of the runs: other GPU work on this Mac only ever adds time. -fn least(v: []f64) f64 { +pub fn least(v: []f64) f64 { std.mem.sort(f64, v, {}, lessThan); return v[0]; } /// Pipeline ids to names, by walking the Pipelines struct (glue and mv arrays by their registered names). -const Names = struct { +pub const Names = struct { ids: std.ArrayList(usize) = .empty, names: std.ArrayList([]const u8) = .empty, @@ -78,7 +78,7 @@ const Names = struct { try n.names.append(a, name); } - fn walk(n: *Names, a: std.mem.Allocator, comptime T: type, v: *const T, prefix: []const u8) !void { + pub fn walk(n: *Names, a: std.mem.Allocator, comptime T: type, v: *const T, prefix: []const u8) !void { switch (T) { mtl.Pipeline => return n.add(a, v.*, prefix), ?mtl.Pipeline => return if (v.*) |p| n.add(a, p, prefix), @@ -98,7 +98,7 @@ const Names = struct { } } - fn of(n: *const Names, id: ?mtl.objc.Id) []const u8 { + pub fn of(n: *const Names, id: ?mtl.objc.Id) []const u8 { const key = if (id) |i| @intFromPtr(i) else return "?"; for (n.ids.items, n.names.items) |k, v| if (k == key) return v; return "?"; @@ -119,13 +119,13 @@ fn clockOf(before: counters.ClockSample, after: counters.ClockSample) Clock { return .{ .spt = cpu / gpu * 1e-9 }; } -const Run = struct { host: f64, gpu: f64, enc: f64, each: []f64 }; +pub const Run = struct { host: f64, gpu: f64, enc: f64, each: []f64 }; /// The direct launch (host encode, GPU span), then its recording replayed whole and one dispatch an encoder. -fn once(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, rec: *recorder.Recording, rows: u32, samples: counters.SampleBuffer, pass: counters.ComputePass, conc: counters.ComputePass) !Run { - const w = &r.layers[0]; - const ctx = r.ctx(&r.slot, p0, rows); - try r.s.writeRows(&r.c, p0, rows); +fn once(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, rec: *recorder.Recording, l: Launch, samples: counters.SampleBuffer, pass: counters.ComputePass, conc: counters.ComputePass) !Run { + const w = l.w; + const ctx = l.ctx; + try r.s.writeSpans(&r.c, l.spans); const s = r.streams(); const pr = r.pres(); const io: pkg.layer.Io = .{ .x = s[0], .pre = pr[0], .x_out = s[1], .pre_out = pr[1] }; @@ -178,7 +178,45 @@ fn once(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, rec: *recorder. return out; } +/// One timed launch: a layer's weights, its context (one slot's rows, or segments) and the rows' spans. +pub const Launch = struct { w: *const pkg.weights.Layer, ctx: pkg.ctx.Ctx, spans: []const pkg.scratch.Span }; + +/// The launch of `rows` rows of the rig's first layer on its slot at `p0`. +fn single(r: *fixture.Rig, rows: u32, span: *[1]pkg.scratch.Span) Launch { + span[0] = .{ .p0 = p0, .n = rows }; + return .{ .w = &r.layers[0], .ctx = r.ctx(&r.slot, p0, rows), .spans = span }; +} + fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const Names, rows: u32, n: usize) !void { + var span: [1]pkg.scratch.Span = undefined; + const t = try time(a, r, junk, names, single(r, rows, &span), n); + t.print(r.layers[0].layer, rows, n, env("TF_DSV41_TIMING_EACH") != null); +} + +/// A launch's GPU time (concurrent and serial encoders, host encode) and its per-dispatch medians summed by kernel. +pub const Timing = struct { + gpu: f64, + gpu_med: f64, + host: f64, + enc: f64, + enc_med: f64, + sum: f64, + cls: []const []const u8, + tot: []const f64, + cnt: []const usize, + each: []const f64, + each_names: []const []const u8, + + pub fn print(t: Timing, layer: u32, rows: u32, n: usize, each: bool) void { + std.debug.print("layer {d}, {d} row(s), fastest of {d}, {d} dispatches:\n", .{ layer, rows, n, t.each.len }); + std.debug.print(" concurrent (serving) encoder {d:.1} us (median {d:.1}), host encode {d:.1} us; one serial encoder {d:.1} us (median {d:.1}); dispatches alone {d:.1} us\n", .{ t.gpu * 1e6, t.gpu_med * 1e6, t.host * 1e6, t.enc * 1e6, t.enc_med * 1e6, t.sum * 1e6 }); + std.debug.print(" x40: {d:.2} ms a round, {d:.1} tok/s at {d} row(s) a round (serial {d:.2} ms)\n", .{ 40 * t.gpu * 1e3, @as(f64, @floatFromInt(rows)) / (40 * t.gpu), rows, 40 * t.enc * 1e3 }); + for (t.cls, t.tot, t.cnt) |c, s, k| std.debug.print(" {s:<34} x{d:<3} {d:>9.1} us\n", .{ c, k, s * 1e6 }); + if (each) for (t.each, t.each_names, 0..) |v, nm, i| std.debug.print(" #{d:<3} {s:<34} {d:>9.1} us\n", .{ i, nm, v * 1e6 }); + } +}; + +pub fn time(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const Names, l: Launch, n: usize) !Timing { var rec: recorder.Recording = .{ .a = a }; defer rec.deinit(); const samples = try counters.SampleBuffer.init(r.device, 4096); @@ -190,7 +228,7 @@ fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const defer conc.deinit(); mtl.objc.msg(void, conc.id, "setDispatchType:", .{@as(usize, @backingInt(mtl.DispatchType.concurrent))}); const runs = try a.alloc(Run, n); - for (runs) |*x| x.* = try once(a, r, junk, &rec, rows, samples, pass, conc); + for (runs) |*x| x.* = try once(a, r, junk, &rec, l, samples, pass, conc); const v = try a.alloc(f64, n); for (runs, v) |x, *y| y.* = x.gpu; const gpu_med = median(v); @@ -209,10 +247,9 @@ fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const var pipes = try a.alloc(?mtl.objc.Id, d); { const re = recorder.start(&rec); - const ctx = r.ctx(&r.slot, p0, rows); const s = r.streams(); const pr = r.pres(); - try pkg.layer.encode(&ctx, re, &r.layers[0], .{ .x = s[0], .pre = pr[0], .x_out = s[1], .pre_out = pr[1] }); + try pkg.layer.encode(&l.ctx, re, l.w, .{ .x = s[0], .pre = pr[0], .x_out = s[1], .pre_out = pr[1] }); recorder.stop(re); var k: usize = 0; var pipe: ?mtl.objc.Id = null; @@ -225,11 +262,15 @@ fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const else => {}, }; } + const each = try a.alloc(f64, d); + const each_names = try a.alloc([]const u8, d); for (0..d) |i| { for (runs, v) |x, *y| y.* = x.each[i]; const m = least(v); + each[i] = m; sum += m; const name = names.of(pipes[i]); + each_names[i] = name; const at = for (cls.items, 0..) |c, j| { if (std.mem.eql(u8, c, name)) break j; } else blk: { @@ -241,14 +282,7 @@ fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const tot.items[at] += m; cnt.items[at] += 1; } - std.debug.print("layer {d}, {d} row(s), fastest of {d}, {d} dispatches:\n", .{ r.layers[0].layer, rows, n, d }); - std.debug.print(" concurrent (serving) encoder {d:.1} us (median {d:.1}), host encode {d:.1} us; one serial encoder {d:.1} us (median {d:.1}); dispatches alone {d:.1} us\n", .{ gpu * 1e6, gpu_med * 1e6, hst * 1e6, enc * 1e6, enc_med * 1e6, sum * 1e6 }); - std.debug.print(" x40: {d:.2} ms a round, {d:.1} tok/s at {d} row(s) a round (serial {d:.2} ms)\n", .{ 40 * gpu * 1e3, @as(f64, @floatFromInt(rows)) / (40 * gpu), rows, 40 * enc * 1e3 }); - for (cls.items, tot.items, cnt.items) |c, t, k| std.debug.print(" {s:<34} x{d:<3} {d:>9.1} us\n", .{ c, k, t * 1e6 }); - if (env("TF_DSV41_TIMING_EACH") != null) for (0..d) |i| { - for (runs, v) |x, *y| y.* = x.each[i]; - std.debug.print(" #{d:<3} {s:<34} {d:>9.1} us\n", .{ i, names.of(pipes[i]), least(v) * 1e6 }); - }; + return .{ .gpu = gpu, .gpu_med = gpu_med, .host = hst, .enc = enc, .enc_med = enc_med, .sum = sum, .cls = cls.items, .tot = tot.items, .cnt = cnt.items, .each = each, .each_names = each_names }; } /// Each dense FP8 projection of the layer alone at 1, 4 and 5 rows, by block kind, interleaved. diff --git a/zig/tests/dsv41_metal/timing_synth.zig b/zig/tests/dsv41_metal/timing_synth.zig new file mode 100644 index 00000000000..d5e2d3b9fa9 --- /dev/null +++ b/zig/tests/dsv41_metal/timing_synth.zig @@ -0,0 +1,146 @@ +//! Synthetic layers of the release's shapes timed per row: dispatch classes at 1-16 rows and 4 slots x 1 row. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fixture = @import("fixture.zig"); +const timing = @import("timing_real.zig"); + +const Ids = host.config.Ids; +const limit = 1280; +const p0 = 1101; + +fn env(name: [*:0]const u8) ?[]const u8 { + const v = std.c.getenv(name) orelse return null; + return std.mem.span(v); +} + +/// One layer of each kind the release serves, at its widths: window, full r2, reuse r2, full r1, reindex, reuse r1. +pub fn config(experts: u32) host.config.Config { + var c = fixture.config(); + const r: host.config.Config = .{}; + inline for (.{ "hidden", "heads", "q_lora", "o_lora", "o_groups", "expert_width", "index_heads", "index_dim", "index_topk", "candidate_blocks" }) |f| @field(c, f) = @field(r, f); + c.layers = 6; + c.vocab = 1024; + c.experts = experts; + c.compress_ratios = Ids.of(&.{ 0, 2, 2, 1, 1, 1 }); + c.kv_sources = Ids.of(&.{ 1, 3 }); + c.index_sources = Ids.of(&.{ 1, 3, 4 }); + c.candidate_source = 3; + return c; +} + +/// How many release layers each synthetic layer stands for (sums to 40). +const weight = [6]f64{ 2, 3, 15, 1, 4, 15 }; + +/// Kernel classes a per-row cost is split into, by the pipeline's field path. +const Class = enum { fp8, experts, attention, glue }; +const class_names = [_][]const u8{ "FP8 rows", "experts", "attention", "glue" }; + +fn classOf(name: []const u8) Class { + const has = struct { + fn f(n: []const u8, t: []const u8) bool { + return std.mem.indexOf(u8, n, t) != null; + } + }.f; + if (has(name, "p.fp8") or has(name, "p.mma")) return .fp8; + if (has(name, "p.experts") or has(name, "p.route") or has(name, "p.xmma")) return .experts; + if (has(name, "p.attn") or has(name, "p.index") or has(name, "p.cand") or has(name, "p.topk512") or has(name, "p.compress")) return .attention; + return .glue; +} + +const Split = struct { gpu: f64, sum: f64, by: [4]f64, n: usize }; + +fn split(t: timing.Timing) Split { + var s: Split = .{ .gpu = t.gpu, .sum = t.sum, .by = @splat(0), .n = t.each.len }; + for (t.each, t.each_names) |v, nm| s.by[@backingInt(classOf(nm))] += v; + return s; +} + +/// Every row's input is row 0's, so the rows share their experts (a greedy draft block, or T0 streams). +fn sameRows(r: *fixture.Rig, rows: u32) void { + const x = r.io[0].slice(u16, rows * 4 * r.c.hidden); + for (1..rows) |i| @memcpy(x[i * 4 * r.c.hidden ..][0 .. 4 * r.c.hidden], x[0 .. 4 * r.c.hidden]); + const pre = r.io[2].slice(f32, rows * 4); + for (1..rows) |i| @memcpy(pre[i * 4 ..][0..4], pre[0..4]); +} + +const Shape = struct { slots: u32, rows: u32 }; + +fn launchOf(r: *fixture.Rig, l: u32, sh: Shape, slots: []pkg.kv.Slot, spans: []pkg.scratch.Span, segs: []pkg.ctx.Seg) timing.Launch { + const total = sh.slots * sh.rows; + if (sh.slots == 1) { + spans[0] = .{ .p0 = p0, .n = sh.rows }; + return .{ .w = &r.layers[l], .ctx = r.ctx(&slots[0], p0, sh.rows), .spans = spans[0..1] }; + } + for (0..sh.slots) |i| { + const at: u32 = p0 + 3 * @as(u32, @intCast(i)); + spans[i] = .{ .p0 = at, .n = sh.rows }; + segs[i] = .{ .slot = &slots[i], .p0 = at, .r0 = @intCast(i * sh.rows), .n = sh.rows }; + } + var x = r.ctx(&slots[0], p0, total); + x.segs = segs[0..sh.slots]; + return .{ .w = &r.layers[l], .ctx = x, .spans = spans[0..sh.slots] }; +} + +fn printRow(label: []const u8, sh: Shape, s: Split, base: ?Split) void { + const rows = sh.slots * sh.rows; + std.debug.print(" {s:<10} {d:>2}x{d:<2} concurrent {d:>8.1} us, alone {d:>8.1} us:", .{ label, sh.slots, sh.rows, s.gpu * 1e6, s.sum * 1e6 }); + for (class_names, s.by) |nm, v| std.debug.print(" {s} {d:.1}", .{ nm, v * 1e6 }); + if (base) |b| if (rows > 1) { + const extra: f64 = @floatFromInt(rows - 1); + std.debug.print(" | a row: {d:.1}", .{(s.gpu - b.gpu) / extra * 1e6}); + for (class_names, s.by, b.by) |nm, v, w| std.debug.print(" {s} {d:.1}", .{ nm, (v - w) / extra * 1e6 }); + }; + std.debug.print("\n", .{}); +} + +test "dsv41 metal synthetic release-shape layers timed by dispatch class at 1-16 rows and 4 slots x 1 row" { + const n = if (env("TF_DSV41_TIMING_N")) |v| try std.fmt.parseInt(usize, v, 10) else 7; + const experts = if (env("TF_DSV41_SYNTH_EXPERTS")) |v| try std.fmt.parseInt(u32, v, 10) else 16; + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const r = try fixture.Rig.initMode(std.heap.page_allocator, std.testing.io, config(experts), limit, 5, .mapped); + defer r.deinit(); + const junk = try r.device.buffer(timing.flush_bytes, mtl.ResourceOptions.private); + defer junk.deinit(); + var names: timing.Names = .{}; + try names.walk(a, pkg.pipelines.Pipelines, &r.p, "p"); + var slots: [4]pkg.kv.Slot = undefined; + slots[0] = r.slot; + for (slots[1..]) |*s| s.* = try pkg.kv.Slot.init(std.heap.page_allocator, r.device, &r.c, limit); + defer for (slots[1..]) |*s| s.deinit(); + for (&slots, 0..) |*s, i| fixture.fillPast(&r.c, s, p0 + 3 * @as(u32, @intCast(i)), 21 + i); + const same = env("TF_DSV41_TIMING_DIFFERENT") == null; + // TF_DSV41_SYNTH_ROWS: a comma list of one slot's row counts (default 1,2,4,8,16), then 4 slots x 1 row + var list: [17]Shape = undefined; + var len: usize = 0; + var it = std.mem.tokenizeScalar(u8, env("TF_DSV41_SYNTH_ROWS") orelse "1,2,4,8,16", ','); + while (it.next()) |tok| : (len += 1) list[len] = .{ .slots = 1, .rows = try std.fmt.parseInt(u32, tok, 10) }; + list[len] = .{ .slots = 4, .rows = 1 }; + const shapes = list[0 .. len + 1]; + var round: [17]Split = @splat(.{ .gpu = 0, .sum = 0, .by = @splat(0), .n = 0 }); + std.debug.print("synthetic release-shape layers, {d} experts, {s} rows, fastest of {d} (us):\n", .{ experts, if (same) "identical" else "different", n }); + for (0..r.c.layers) |li| { + const l: u32 = @intCast(li); + std.debug.print("layer {d} ({s}, ratio {d}):\n", .{ l, @tagName(r.c.mode(l)), r.c.compressRatio(l) }); + var base: ?Split = null; + for (shapes, 0..) |sh, i| { + fixture.fillInput(r, sh.slots * sh.rows, 31); + if (same) sameRows(r, sh.slots * sh.rows); + var spans: [16]pkg.scratch.Span = undefined; + var segs: [16]pkg.ctx.Seg = undefined; + const t = try timing.time(a, r, junk, &names, launchOf(r, l, sh, &slots, &spans, &segs), n); + const s = split(t); + if (i == 0) base = s; + if (env("TF_DSV41_TIMING_EACH") != null) t.print(l, sh.slots * sh.rows, n, true); + printRow("", sh, s, base); + round[i].gpu += weight[li] * s.gpu; + round[i].sum += weight[li] * s.sum; + for (&round[i].by, s.by) |*x, v| x.* += weight[li] * v; + } + } + std.debug.print("40-layer round (layers weighted by kind; no head, Engram or host):\n", .{}); + for (shapes, round[0..shapes.len]) |sh, s| printRow("round", sh, s, round[0]); +} From 866be20aa860b3ffab376253f88fdba8b0fada73 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:50:53 +0100 Subject: [PATCH 05/89] dsv41 metal: FP8 projections of 6-16 decode rows on a simdgroup-matrix tile, bit-equal to the row kernel Launches of 6 to 16 rows run the dense FP8 projections on fp8_tile.metal: 8 or 16 columns a threadgroup, K split over up to 16 simdgroups in aligned power-of-two runs of groups, each 32-wide group summed from zero in four 8-wide MMA steps in k order (the prompt tile's group root), the groups' roots and the slices' roots in the same zero-padded pair tree the row kernel uses. Every row's bits are the row kernel's one row a launch; 1-5 rows keep the row kernel (chosen by row count only), since below 6 rows it reads the weights faster. Contract: six registrations (f32, bf16, a forced 16-column form, one simdgroup, the row kernel one row a launch as replaced baseline, the release wkv fixture), four planted controls, gate-5 records with M1/M2 limits, and an equality probe over every model FP8 shape at 1-16 rows, every form, the 16/17 seam and a batch with NaN and Inf planted. Device tests: the layer's kernel by row count, and four slots of two rows each in one launch against each alone. --- zig/kernels/metal/deepseek_v41/fp8_tile.metal | 185 ++++++++++++++ zig/kernels/metal/deepseek_v41/sources.zig | 2 + zig/runtime_sources/dsv41.zig | 2 +- .../core/contract/dsv41_fp8_tile_records.zig | 13 + zig/src/core/contract/dsv41_metal_records.zig | 1 + .../deepseek_v41/metal/contract_exports.zig | 1 + zig/src/families/deepseek_v41/metal/ctx.zig | 5 +- .../families/deepseek_v41/metal/fp8_tile.zig | 108 ++++++++ .../families/deepseek_v41/metal/pipelines.zig | 6 + zig/tests/contract/metal_dsv41_fp8_tile.zig | 232 ++++++++++++++++++ .../contract/metal_dsv41_fp8_tile_eq.zig | 121 +++++++++ zig/tests/contract/metal_dsv41_limits.zig | 4 + zig/tests/contract/metal_dsv41_main.zig | 8 +- zig/tests/dsv41_metal/layer_test.zig | 1 + zig/tests/dsv41_metal/multi_test.zig | 2 + zig/tests/dsv41_metal/tile_test.zig | 50 ++++ zig/tests/dsv41_metal/timing_fp8.zig | 84 +++++++ zig/tests/dsv41_metal/timing_synth.zig | 5 +- 18 files changed, 826 insertions(+), 4 deletions(-) create mode 100644 zig/kernels/metal/deepseek_v41/fp8_tile.metal create mode 100644 zig/src/core/contract/dsv41_fp8_tile_records.zig create mode 100644 zig/src/families/deepseek_v41/metal/fp8_tile.zig create mode 100644 zig/tests/contract/metal_dsv41_fp8_tile.zig create mode 100644 zig/tests/contract/metal_dsv41_fp8_tile_eq.zig create mode 100644 zig/tests/dsv41_metal/tile_test.zig create mode 100644 zig/tests/dsv41_metal/timing_fp8.zig diff --git a/zig/kernels/metal/deepseek_v41/fp8_tile.metal b/zig/kernels/metal/deepseek_v41/fp8_tile.metal new file mode 100644 index 00000000000..b8d9ea6fe27 --- /dev/null +++ b/zig/kernels/metal/deepseek_v41/fp8_tile.metal @@ -0,0 +1,185 @@ +// DeepSeek V4.1 dense FP8, 2-16 BF16 rows on simdgroup MMA: 8 columns a group, K split over simdgroups, one tree. +#include +using namespace metal; + +#ifndef TF_CTL +#define TF_CTL 0 +#endif + +struct TfDsv41Fp8TileArgs { + uint K, N, R, groups, per, sgs; + long xs, ws, ss, ys; // byte strides between the launches of a batch (grid y) +}; + +#define TF_TLD 36 // staged row stride of one column's 32 decoded K values (floats) +#define TF_TLV 10 // pair-tree levels a simdgroup's slice holds (up to 512 groups) + +inline float tf_dsv41_tile_e4m3(uint code) { + const float v = float(as_type(ushort((code & 0x7Fu) << 7))) * 256.0f; + const float s = (code & 0x80u) ? -v : v; + return (code & 0x7Fu) == 0x7Fu ? NAN : s; +} + +inline float tf_dsv41_tile_e8m0(uint code) { + if (code == 255u) return NAN; + return as_type(code == 0u ? 0x00400000u : code << 23); +} + +inline float tf_dsv41_tile_x(uint bits) { + const float v = as_type(bits << 16); + return (TF_CTL == 1 && !isfinite(v)) ? 0.0f : v; +} + +// Two codes of a word (bytes b, b + 2) as a half2 holding value / 256, sign included (the row kernel's fast path). +inline half2 tf_dsv41_tile_h2(uint word) { + return as_type(((word & 0x007F007Fu) << 7) | ((word & 0x00800080u) << 8)); +} + +// Eight weights of one column; a NaN code (0x7F, 0xFF) or a scale past 2^120 takes the per-code path, the same values. +inline void tf_dsv41_tile_w8(uint2 q, uint code, thread float (&v)[8]) { + const uint2 mag = q & 0x7F7F7F7Fu; + if (code > 247u || any(((mag + 0x01010101u) & 0x80808080u) != 0u)) { + const float sc = tf_dsv41_tile_e8m0(code); + for (uint b = 0; b < 8; ++b) v[b] = tf_dsv41_tile_e4m3(((b < 4 ? q.x : q.y) >> (8 * (b % 4))) & 0xFFu) * sc; + return; + } + const float x256 = tf_dsv41_tile_e8m0(code) * 256.0f; + for (uint j = 0; j < 2; ++j) { + const half2 a = tf_dsv41_tile_h2(q[j]), b = tf_dsv41_tile_h2(q[j] >> 8); + v[4 * j] = float(a.x) * x256; + v[4 * j + 1] = float(b.x) * x256; + v[4 * j + 2] = float(a.y) * x256; + v[4 * j + 3] = float(b.y) * x256; + } +} + +// Simdgroup sg: groups [sg * per, +per) of 8 * NJ columns, each from zero in 4 MMA steps, roots in one pair tree. +template +[[kernel, max_total_threads_per_threadgroup(512)]] void tf_dsv41_fp8_tile( + const device uchar* X0 [[buffer(0)]], const device uchar* W0 [[buffer(1)]], + const device uchar* S0 [[buffer(2)]], device uchar* Y0 [[buffer(3)]], + constant TfDsv41Fp8TileArgs& a [[buffer(4)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint tid [[thread_index_in_threadgroup]]) { + constexpr uint CB = 8 * NJ; + constexpr uint LQ = 32 / CB; // lanes a column's 32 bytes are read by + threadgroup float tgm[128 * TF_TLD]; + const device ushort* X = (const device ushort*)(X0 + long(tg.y) * a.xs); + const device uchar* W = W0 + long(tg.y) * a.ws; + const device uchar* S = S0 + long(tg.y) * a.ss; + device T* Y = (device T*)(Y0 + long(tg.y) * a.ys); + const uint qid = lane / 4; + const uint fm = (qid & 4) + ((lane / 2) % 4); + const uint fn = (qid & 2) * 2 + (lane % 2) * 2; + const uint n0 = tg.x * CB; + threadgroup float* wt = tgm + sg * CB * TF_TLD; + threadgroup float4* dst = (threadgroup float4*)(wt + (lane / LQ) * TF_TLD + (lane % LQ) * (32 / LQ)); + const device uchar* Wl = W + ulong(n0 + lane / LQ) * a.K + (lane % LQ) * (32 / LQ); + const device uchar* Sn = S + ulong(n0 / 32) * a.groups; + const device ushort* xr[RT]; + bool live[RT]; + for (uint t = 0; t < RT; ++t) { + const uint r = t * 8 + fm; + live[t] = r < a.R; + xr[t] = X + ulong(min(r, a.R - 1)) * a.K + fn; + } + uint levels = 0; + while ((1u << levels) < a.per) ++levels; + const uint g0 = sg * a.per; + const uint end = min(g0 + a.per, a.groups); + float stack[TF_TLV][RT][NJ][2]; + float chain[RT][NJ][2]; + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) chain[t][j][0] = chain[t][j][1] = 0.0f; + uint2 q[NJ]; + uint code = 0; + for (uint h = 0; h < NJ; ++h) q[h] = g0 < end ? *(const device uint2*)(Wl + g0 * 32 + 8 * h) : uint2(0); + if (g0 < end) code = Sn[g0]; + for (uint i = 0; i < a.per; ++i) { + const uint g = g0 + i; + float cur[RT][NJ][2]; + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) cur[t][j][0] = cur[t][j][1] = 0.0f; + if (g < end) { + for (uint h = 0; h < NJ; ++h) { + float v[8]; + tf_dsv41_tile_w8(q[h], code, v); + dst[2 * h] = float4(v[0], v[1], v[2], v[3]); + dst[2 * h + 1] = float4(v[4], v[5], v[6], v[7]); + } + if (g + 1 < end) { + for (uint h = 0; h < NJ; ++h) q[h] = *(const device uint2*)(Wl + (g + 1) * 32 + 8 * h); + code = Sn[g + 1]; + } + simdgroup_barrier(mem_flags::mem_threadgroup); + simdgroup_matrix acc[RT][NJ]; + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) acc[t][j] = simdgroup_matrix(0.0f); + for (uint s = 0; s < 4; ++s) { + simdgroup_matrix wb[NJ]; + for (uint j = 0; j < NJ; ++j) simdgroup_load(wb[j], wt + 8 * j * TF_TLD + 8 * s, TF_TLD, ulong2(0, 0), true); + for (uint t = 0; t < RT; ++t) { + const uint xb = live[t] ? *(const device uint*)(xr[t] + g * 32 + 8 * s) : 0u; + simdgroup_matrix xa; + xa.thread_elements()[0] = tf_dsv41_tile_x(xb & 0xFFFFu); + xa.thread_elements()[1] = tf_dsv41_tile_x(xb >> 16); + for (uint j = 0; j < NJ; ++j) simdgroup_multiply_accumulate(acc[t][j], xa, wb[j], acc[t][j]); + } + } + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) + for (uint e = 0; e < 2; ++e) { + const float r = acc[t][j].thread_elements()[e]; + cur[t][j][e] = TF_CTL == 3 ? float(half(r)) : r; + } + } + if (TF_CTL == 2) { + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) chain[t][j][0] += cur[t][j][0], chain[t][j][1] += cur[t][j][1]; + continue; + } + uint lv = 0; + while (lv < levels && ((i >> lv) & 1u)) { + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) + for (uint e = 0; e < 2; ++e) cur[t][j][e] = stack[lv][t][j][e] + cur[t][j][e]; + ++lv; + } + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) stack[lv][t][j][0] = cur[t][j][0], stack[lv][t][j][1] = cur[t][j][1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // roots [sg][column][row]: the staging blocks are free once every simdgroup has passed the barrier + threadgroup float* roots = tgm; + for (uint t = 0; t < RT; ++t) + for (uint j = 0; j < NJ; ++j) + for (uint e = 0; e < 2; ++e) + roots[(sg * CB + 8 * j + fn + e) * (RT * 8) + t * 8 + fm] = TF_CTL == 2 ? chain[t][j][e] : stack[levels][t][j][e]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint o = tid; o < CB * RT * 8; o += 32 * a.sgs) { + const uint col = o / (RT * 8), r = o % (RT * 8); + if (r >= a.R) continue; + float v[16]; + for (uint k = 0; k < 16; ++k) v[k] = k < a.sgs ? roots[(k * CB + col) * (RT * 8) + r] : 0.0f; + if (TF_CTL == 2) { + for (uint k = 1; k < a.sgs; ++k) v[0] += v[k]; + } else { + for (uint s = 1; s < 16; s *= 2) + for (uint i = 0; i < 16; i += 2 * s) v[i] += v[i + s]; + } + Y[ulong(r) * a.N + n0 + col] = T(v[0]); + } + if (TF_CTL == 4 && tg.x == 0 && tg.y == 0 && tid == 0) Y[ulong(a.R) * a.N] = T(1.0f); +} + +#define TF_TILE(RT, NJ, T, NAME) \ + template [[host_name(NAME)]] [[kernel]] decltype(tf_dsv41_fp8_tile) tf_dsv41_fp8_tile; +TF_TILE(1, 1, float, "tf_dsv41_fp8_tile_r8_c8_f32") +TF_TILE(1, 1, bfloat, "tf_dsv41_fp8_tile_r8_c8_bf16") +TF_TILE(2, 1, float, "tf_dsv41_fp8_tile_r16_c8_f32") +TF_TILE(2, 1, bfloat, "tf_dsv41_fp8_tile_r16_c8_bf16") +TF_TILE(1, 2, float, "tf_dsv41_fp8_tile_r8_c16_f32") +TF_TILE(1, 2, bfloat, "tf_dsv41_fp8_tile_r8_c16_bf16") +TF_TILE(2, 2, float, "tf_dsv41_fp8_tile_r16_c16_f32") +TF_TILE(2, 2, bfloat, "tf_dsv41_fp8_tile_r16_c16_bf16") diff --git a/zig/kernels/metal/deepseek_v41/sources.zig b/zig/kernels/metal/deepseek_v41/sources.zig index 9262341b67c..f15e31a0ff2 100644 --- a/zig/kernels/metal/deepseek_v41/sources.zig +++ b/zig/kernels/metal/deepseek_v41/sources.zig @@ -4,6 +4,8 @@ pub const fp8_mma = @embedFile("fp8_mma.metal"); /// DeepSeek V4.1 release FP8 dense projections: 32x32 blocks and split-invariant row sums. pub const fp8_rows = @embedFile("fp8_rows.metal"); +/// DeepSeek V4.1 release FP8 dense projections of 2-16 rows on simdgroup MMA, bit-equal to fp8_rows. +pub const fp8_tile = @embedFile("fp8_tile.metal"); /// DeepSeek V4.1 CSA2 attention: window, selected compressed rows and the sink over one shared latent row. pub const csa2_attn = @embedFile("csa2_attn.metal"); /// DeepSeek V4.1's copy of Kimi's expert plan, chains and combine: the E8M0 scale over its full range. diff --git a/zig/runtime_sources/dsv41.zig b/zig/runtime_sources/dsv41.zig index 1ba8cfd5c96..1a13bb818f8 100644 --- a/zig/runtime_sources/dsv41.zig +++ b/zig/runtime_sources/dsv41.zig @@ -5,7 +5,7 @@ const ks = @import("kernel_sources").dsv41; const Set = @import("set.zig").Set; const xm = @import("../src/families/deepseek_v41/metal/experts_mma.zig"); pub fn add(s: *Set, device: mtl.Device) !void { - inline for (.{ "fp8_mma", "fp8_rows", "csa2_attn", "topk512", "glue", "glue_tmp", "fused", "fold", "compress", "mv", "cand", "index", "engram", "hc" }) |name| + inline for (.{ "fp8_mma", "fp8_rows", "fp8_tile", "csa2_attn", "topk512", "glue", "glue_tmp", "fused", "fold", "compress", "mv", "cand", "index", "engram", "hc" }) |name| try s.raw("deepseek-v41", name, @field(ks, name)); try s.raw("deepseek-v41", "experts", try @import("../src/families/deepseek_v41/metal/experts.zig").source(s.a, "", &.{})); try s.raw("deepseek-v41", "expert-mma", try xm.source(s.a, "", &.{}, false)); diff --git a/zig/src/core/contract/dsv41_fp8_tile_records.zig b/zig/src/core/contract/dsv41_fp8_tile_records.zig new file mode 100644 index 00000000000..fdbcc58a1cb --- /dev/null +++ b/zig/src/core/contract/dsv41_fp8_tile_records.zig @@ -0,0 +1,13 @@ +//! DeepSeek V4.1 FP8 rows on the MMA tile: up to 16 simdgroups (512 threads, reserved; M1 and M2 build 512). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +const names = [_][]const u8{ "r8_c8_f32", "r8_c8_bf16", "r16_c8_f32", "r16_c8_bf16", "r8_c16_f32", "r8_c16_bf16", "r16_c16_f32", "r16_c16_bf16" }; +pub const records = blk: { + var out: [names.len]M = undefined; + for (names, 0..) |n, i| out[i] = .{ .name = "dsv41 fp8 tile tf_dsv41_fp8_tile_" ++ n, .threads = 512, .tg_memory = 18432, .reserved = 512, .m1 = 512, .m2 = 512 }; + break :blk out; +}; + +test "the DeepSeek V4.1 FP8 tile launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/dsv41_metal_records.zig b/zig/src/core/contract/dsv41_metal_records.zig index 68735c8a950..ff6b3e0ebc6 100644 --- a/zig/src/core/contract/dsv41_metal_records.zig +++ b/zig/src/core/contract/dsv41_metal_records.zig @@ -2,6 +2,7 @@ const M = @import("limits.zig").MetalLaunch; const head = @import("dsv41_fp8_records.zig").records ++ @import("dsv41_fp8_mma_records.zig").records ++ + @import("dsv41_fp8_tile_records.zig").records ++ @import("dsv41_topk512_records.zig").records ++ @import("dsv41_attn_records.zig").records ++ @import("dsv41_experts_records.zig").records ++ @import("dsv41_index_records.zig").records ++ @import("dsv41_engram_records.zig").records ++ @import("dsv41_glue_records.zig").records ++ diff --git a/zig/src/families/deepseek_v41/metal/contract_exports.zig b/zig/src/families/deepseek_v41/metal/contract_exports.zig index d30c285c094..862e01da10e 100644 --- a/zig/src/families/deepseek_v41/metal/contract_exports.zig +++ b/zig/src/families/deepseek_v41/metal/contract_exports.zig @@ -3,6 +3,7 @@ pub const fp8_mma = @import("fp8_mma.zig"); pub const index = @import("index.zig"); pub const engram = @import("engram.zig"); pub const fp8_rows = @import("fp8_rows.zig"); +pub const fp8_tile = @import("fp8_tile.zig"); pub const attn = @import("csa2_attn.zig"); pub const experts = @import("experts.zig"); pub const mv = @import("mv.zig"); diff --git a/zig/src/families/deepseek_v41/metal/ctx.zig b/zig/src/families/deepseek_v41/metal/ctx.zig index 25efd6a855a..00543636f96 100644 --- a/zig/src/families/deepseek_v41/metal/ctx.zig +++ b/zig/src/families/deepseek_v41/metal/ctx.zig @@ -65,8 +65,11 @@ pub const Ctx = struct { try x.projBatch(e, in, w, out, f32_out, .{}); } - /// `proj` over a batch of same-shape launches in one dispatch (fp8.Batch strides from the first one). + /// `proj` over a batch of same-shape launches in one dispatch; the kernel by row count, a row's bits the same. pub fn projBatch(x: *const Ctx, e: mtl.ComputeEncoder, in: Ref, w: weights.Fp8, out: Ref, f32_out: bool, b: fp8.Batch) !void { + const t = pipelines.fp8_tile; + const tc: t.Call = .{ .k = w.k, .n = w.n, .rows = x.rows, .out = if (f32_out) .f32 else .bf16 }; + if (t.takes(tc)) return t.encode(&x.p.tile, e, cv(t.Ref, in), cv(t.Ref, w.w), cv(t.Ref, w.s), cv(t.Ref, out), tc, .{ .n = b.n, .xs = b.xs, .ws = b.ws, .ss = b.ss, .ys = b.ys }); const call: fp8.Call = .{ .k = w.k, .n = w.n, .rows = x.rows, .split = fp8.splitOf(w.k), .out = if (f32_out) .f32 else .bf16 }; try fp8.encodeWhole(&x.p.fp8, e, cv(fp8.Ref, in), cv(fp8.Ref, w.w), cv(fp8.Ref, w.s), cv(fp8.Ref, out), call, b); } diff --git a/zig/src/families/deepseek_v41/metal/fp8_tile.zig b/zig/src/families/deepseek_v41/metal/fp8_tile.zig new file mode 100644 index 00000000000..14d54b4d83a --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/fp8_tile.zig @@ -0,0 +1,108 @@ +//! DeepSeek V4.1 release FP8 dense rows, up to 16, on simdgroup MMA: each row's bits are the row kernel's. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Out = enum { f32, bf16 }; +pub const Call = struct { k: u32, n: u32, rows: u32, out: Out = .f32 }; +/// Launches of one call shape in grid y: the byte strides from one launch's x, weight, scale and output to the next. +pub const Batch = struct { n: u32 = 1, xs: i64 = 0, ws: i64 = 0, ss: i64 = 0, ys: i64 = 0 }; + +/// Rows the decode forward takes this tile from: below them the row kernel reads the weights faster. +pub const min_rows = 6; +pub const max_rows = 16; +/// Simdgroups a threadgroup's K split takes at most, times its 8-column blocks (they share the staging memory). +pub const max_lanes = 16; +const max_per = 512; + +/// How a launch is cut: 8-column blocks a threadgroup (1 or 2) and simdgroups splitting K (a power of two). +pub const Form = struct { nj: u32, sgs: u32 }; + +const Args = extern struct { K: u32, N: u32, R: u32, groups: u32, per: u32, sgs: u32, xs: i64, ws: i64, ss: i64, ys: i64 }; + +pub const Pipelines = struct { + /// [8-row tiles - 1][8-column blocks - 1][out f32, bf16] + p: [2][2][2]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.dsv41.fp8_tile); + } + + /// The same kernels from other text: the contract's planted controls prefix a TF_CTL define. + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var made: usize = 0; + errdefer for (0..made) |i| out.p[i / 4][(i / 2) % 2][i % 2].deinit(); + inline for (.{ "r8", "r16" }, 0..) |t, i| inline for (.{ "c8", "c16" }, 0..) |cb, j| inline for (.{ "f32", "bf16" }, 0..) |o, k| { + out.p[i][j][k] = try mtl.Pipeline.init(device, lib, "tf_dsv41_fp8_tile_" ++ t ++ "_" ++ cb ++ "_" ++ o, false); + made += 1; + }; + return out; + } + + pub fn deinit(p: *Pipelines) void { + for (p.p) |t| for (t) |c| for (c) |x| x.deinit(); + } +}; + +fn padded(groups: u32) u32 { + return std.math.ceilPowerOfTwo(u32, groups) catch unreachable; +} + +/// A shape's form: 16 columns for the widest N, each simdgroup an aligned run of at least 8 groups; bits never change. +pub fn formOf(k: u32, n: u32) Form { + const nj: u32 = if (n >= 16384 and n % 16 == 0) 2 else 1; + return .{ .nj = nj, .sgs = std.math.clamp(padded(k / 32) / 8, 1, max_lanes / nj) }; +} + +fn valid(c: Call, f: Form) bool { + if (f.nj != 1 and f.nj != 2) return false; + if (f.sgs == 0 or f.sgs * f.nj > max_lanes or !std.math.isPowerOfTwo(f.sgs) or f.sgs > padded(c.k / 32)) return false; + return c.n % (8 * f.nj) == 0 and padded(c.k / 32) / f.sgs <= max_per; +} + +/// Whether the tile can run a call: 1-16 rows, whole 32x32 blocks, its slices within the tree it holds. +pub fn fits(c: Call) bool { + if (c.rows == 0 or c.rows > max_rows or c.k == 0 or c.k % 32 != 0 or c.n == 0 or c.n % 32 != 0) return false; + return valid(c, formOf(c.k, c.n)); +} + +/// Whether the decode forward runs a call here (by its row count only); a row's bits are the same either way. +pub fn takes(c: Call) bool { + return c.rows >= min_rows and fits(c); +} + +/// X [rows][K] bf16, W [N][K] E4M3, S [N/32][K/32] E8M0, Y [rows][N]; equal to fp8_rows at any row count or form. +pub fn encode(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, s: Ref, y: Ref, c: Call, b: Batch) !void { + return encodeAs(p, e, x, w, s, y, c, b, formOf(c.k, c.n)); +} + +/// `encode` with the form chosen by the caller; every valid form gives the same bits. +pub fn encodeAs(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, s: Ref, y: Ref, c: Call, b: Batch, f: Form) !void { + if (!fits(c) or b.n == 0) return error.BadFp8Shape; + if (!valid(c, f)) return error.BadFp8Split; + const groups = c.k / 32; + const args = Args{ .K = c.k, .N = c.n, .R = c.rows, .groups = groups, .per = padded(groups) / f.sgs, .sgs = f.sgs, .xs = b.xs, .ws = b.ws, .ss = b.ss, .ys = b.ys }; + e.setPipeline(p.p[if (c.rows > 8) 1 else 0][f.nj - 1][@backingInt(c.out)]); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + e.setBuffer(s.buf, s.off, 2); + e.setBuffer(y.buf, y.off, 3); + e.setValue(args, 4); + e.dispatchGroups(mtl.Size.of(c.n / (8 * f.nj), b.n, 1), mtl.Size.of(32 * f.sgs, 1, 1)); +} + +test "the tile's form covers every release shape within its tree" { + for ([_]u32{ 512, 1280, 2304, 4096, 5120, 6144, 8192, 15360 }) |k| { + const c: Call = .{ .k = k, .n = 64, .rows = min_rows }; + try std.testing.expect(takes(c)); + const f = formOf(k, 64); + try std.testing.expect(valid(c, f) and padded(k / 32) % f.sgs == 0); + } + try std.testing.expect(!takes(.{ .k = 5120, .n = 64, .rows = min_rows - 1 }) and fits(.{ .k = 5120, .n = 64, .rows = 1 })); + try std.testing.expect(!fits(.{ .k = 5120, .n = 64, .rows = 17 })); + try std.testing.expect(!valid(.{ .k = 5120, .n = 64, .rows = 2 }, .{ .nj = 2, .sgs = 16 })); +} diff --git a/zig/src/families/deepseek_v41/metal/pipelines.zig b/zig/src/families/deepseek_v41/metal/pipelines.zig index 832754fec4f..f2ca8170bd1 100644 --- a/zig/src/families/deepseek_v41/metal/pipelines.zig +++ b/zig/src/families/deepseek_v41/metal/pipelines.zig @@ -5,6 +5,7 @@ const sources = @import("kernel_sources"); const Config = @import("dsv41").config.Config; pub const fp8 = @import("fp8_rows.zig"); pub const fp8_mma = @import("fp8_mma.zig"); +pub const fp8_tile = @import("fp8_tile.zig"); pub const attn = @import("csa2_attn.zig"); pub const index = @import("index.zig"); pub const experts = @import("experts.zig"); @@ -39,6 +40,8 @@ pub fn check(c: *const Config) !void { pub const Pipelines = struct { fp8: fp8.Pipelines, + /// the decode rows' FP8 projections at 2-16 rows + tile: fp8_tile.Pipelines, mma: fp8_mma.Pipelines, attn: attn.Pipelines, index: index.Pipelines, @@ -62,6 +65,8 @@ pub const Pipelines = struct { var p: Pipelines = undefined; p.fp8 = try fp8.Pipelines.load(device); errdefer p.fp8.deinit(); + p.tile = try fp8_tile.Pipelines.load(device); + errdefer p.tile.deinit(); p.mma = try fp8_mma.Pipelines.load(device); errdefer p.mma.deinit(); p.attn = try attn.Pipelines.load(device); @@ -98,6 +103,7 @@ pub const Pipelines = struct { pub fn deinit(p: *Pipelines) void { p.fp8.deinit(); + p.tile.deinit(); p.mma.deinit(); p.attn.deinit(); p.index.deinit(); diff --git a/zig/tests/contract/metal_dsv41_fp8_tile.zig b/zig/tests/contract/metal_dsv41_fp8_tile.zig new file mode 100644 index 00000000000..1e78fac09bb --- /dev/null +++ b/zig/tests/contract/metal_dsv41_fp8_tile.zig @@ -0,0 +1,232 @@ +//! DeepSeek V4.1 FP8 rows on the MMA tile under the contract: the fp8_rows order's bits, forms, controls, equality. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("dsv41_fp8_ref.zig"); +const eq = @import("metal_dsv41_fp8_tile_eq.zig"); + +const c = contract.spec; +const g = contract.gates; +const tile = tf.dsv41_metal.fp8_tile; +const rows_k = tf.dsv41_metal.fp8_rows; +const base = "dsv41_fp8_tile "; + +/// A registration: output, forced form (null: the shape's), real fixture, the row kernel as baseline, planted fault. +pub const Variant = struct { out: tile.Out = .f32, form: ?tile.Form = null, fixture: bool = false, replaces: bool = false, ctl: u8 = 0 }; + +const real = [_]c.Shape{ + .{ .rows = 16, .n = 1280, .k = 5120 }, // wq_a + .{ .rows = 6, .n = 512, .k = 5120 }, // wkv + .{ .rows = 8, .n = 512, .k = 8192 }, // wo_b's K at a few columns + .{ .rows = 9, .n = 5120, .k = 2304 }, // shared w2 + .{ .rows = 16, .n = 256, .k = 1280 }, // wq_b's and ix_wq_b's K + .{ .rows = 7, .n = 1024, .k = 4096 }, // wo_a + .{ .rows = 12, .n = 64, .k = 15360 }, // the drafter's main_proj K +}; +const served = blk: { + var out: [real.len + 16]c.Shape = undefined; + for (real, 0..) |s, i| out[i] = s; + for (1..17) |r| out[real.len + r - 1] = .{ .rows = r, .n = 64, .k = 1536 }; // every row count + break :blk out; +}; + +pub fn spec(v: Variant, name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = ref.depth, + .out = if (v.out == .f32) .f32 else .bf16, + .tiles = if (v.fixture) .{ .{}, .{}, .{} } else .{ .{ .size = 16 }, .{ .size = 32, .step = 32, .min = 32 }, .{ .size = 256, .step = 32, .min = 32 } }, + .served = if (v.fixture) &.{ref.fixture.shape} else &served, + .replaces = if (v.replaces) "tf_dsv41_fp8_w* one row a launch" else null, + }; +} + +pub const Proj = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + v: Variant, + name: []const u8, + pipes: tile.Pipelines, + rows: rows_k.Pipelines, + f: ?ref.Fp8 = null, + fill: g.Fill = .random, + real_fixture: bool = false, + x: rig_.Ref = undefined, + w: rig_.Ref = undefined, + s: rig_.Ref = undefined, + y: rig_.Ref = undefined, + yb: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, name: []const u8) !Proj { + var p: Proj = .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .v = v, .name = name, .pipes = undefined, .rows = undefined }; + if (v.ctl == 0) { + p.pipes = try tile.Pipelines.load(device); + } else { + const text = try std.fmt.allocPrint(a, "#define TF_CTL {d}\n{s}", .{ v.ctl, sources.dsv41.fp8_tile }); + defer a.free(text); + p.pipes = try tile.Pipelines.loadSource(device, text); + } + errdefer p.pipes.deinit(); + p.rows = try rows_k.Pipelines.load(device); + return p; + } + + pub fn deinit(p: *Proj) void { + p.drop(); + p.pipes.deinit(); + p.rows.deinit(); + p.rig.deinit(); + } + + fn drop(p: *Proj) void { + if (p.f) |f| f.deinit(); + p.f = null; + p.rig.reset(); + } + + pub fn kernel(p: *Proj) g.Kernel { + const control: ?g.Gate = switch (p.v.ctl) { + 1 => .nonfinite, + 2 => .shapes, + 3 => .sums, + 4 => .repeat, + else => null, + }; + return .{ .spec = spec(p.v, p.name), .ctx = p, .vt = &vt, .control = control }; + } + + const vt = g.hooks(Proj); + + fn call(p: *const Proj) tile.Call { + const f = p.f.?; + return .{ .k = @intCast(f.shape.k), .n = @intCast(f.shape.n), .rows = @intCast(f.shape.rows), .out = p.v.out }; + } + + fn form(p: *const Proj) tile.Form { + const cl = p.call(); + const want = p.v.form orelse return tile.formOf(cl.k, cl.n); + // a forced form where the shape admits it, else the shape's own + const pad = std.math.ceilPowerOfTwo(u32, cl.k / 32) catch unreachable; + if (cl.n % (8 * want.nj) != 0 or want.sgs > pad or pad / want.sgs > 512) return tile.formOf(cl.k, cl.n); + return want; + } + + pub fn prepare(p: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + p.drop(); + if (!tile.fits(.{ .k = @intCast(shape.k), .n = @intCast(shape.n), .rows = @intCast(shape.rows) })) return false; + const f = try ref.Fp8.init(p.a, shape); + p.f = f; + p.fill = fill; + p.real_fixture = p.v.fixture and fill == .random and std.meta.eql(shape, ref.fixture.shape); + if (p.real_fixture) try ref.fixture.load(f, null) else f.fill(fill, seed); + const bytes = f.shape.rows * f.shape.n * c.size(spec(p.v, p.name).out); + p.x = try p.rig.input(std.mem.sliceAsBytes(f.x)); + p.w = try p.rig.input(f.codes); + p.s = try p.rig.input(f.scales); + p.y = try p.rig.output(bytes); + if (p.v.replaces) p.yb = try p.rig.scratch(bytes); + return true; + } + + fn at(r: rig_.Ref, extra: usize) tile.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; + } + + pub fn run(p: *Proj) !void { + const pass = p.rig.begin(); + try tile.encodeAs(&p.pipes, pass.e, at(p.x, 0), at(p.w, 0), at(p.s, 0), at(p.y, 0), p.call(), .{}, p.form()); + try p.rig.finish(pass); + } + + /// The row kernel's bytes on the same inputs, each row its own one-row launch. + pub fn replaced(p: *Proj) ![]const u8 { + const f = p.f.?; + const es = c.size(spec(p.v, p.name).out); + const pass = p.rig.begin(); + for (0..f.shape.rows) |r| { + const one: rows_k.Call = .{ .k = @intCast(f.shape.k), .n = @intCast(f.shape.n), .rows = 1, .split = rows_k.splitOf(@intCast(f.shape.k)), .out = if (p.v.out == .f32) .f32 else .bf16 }; + const rr = struct { + fn at(x: rig_.Ref, extra: usize) rows_k.Ref { + return .{ .buf = x.buf, .off = x.off + extra }; + } + }.at; + try rows_k.encodeWhole(&p.rows, pass.e, rr(p.x, 2 * r * f.shape.k), rr(p.w, 0), rr(p.s, 0), rr(p.yb, es * r * f.shape.n), one, .{}); + } + try p.rig.finish(pass); + return p.rig.bytes(p.yb, f.shape.rows * f.shape.n * es); + } + + pub fn count(p: *Proj) usize { + return p.f.?.outputs(); + } + + pub fn reference(p: *Proj, want: []f64, mag: []f64) !void { + const f = p.f.?; + if (!p.real_fixture) return f.reference(want, mag, p.v.out == .bf16); + try ref.npyF64(ref.fixture.ref_npy, want); + f.magnitudes(mag); + } + + /// Random inputs must reproduce the fp8_rows order bit for bit; stress inputs and the real fixture keep the bound. + pub fn bounds(p: *Proj, _: []const f64, _: []const f64, allow: []f64) !void { + if (p.real_fixture or p.fill == .stress) return; + @memset(allow, 0); + } + + pub fn simulate(p: *Proj, acc: c.Accum, order: g.Order, out: []f64) !void { + return p.f.?.simulate(acc, order, out); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + probes: std.ArrayList(*Proj) = .empty, + + const list = [_]struct { v: Variant, name: []const u8 }{ + .{ .v = .{}, .name = base ++ "f32" }, + .{ .v = .{ .out = .bf16 }, .name = base ++ "bf16" }, + .{ .v = .{ .form = .{ .nj = 2, .sgs = 8 } }, .name = base ++ "f32 16 columns" }, + .{ .v = .{ .out = .bf16, .form = .{ .nj = 1, .sgs = 1 } }, .name = base ++ "bf16 one simdgroup" }, + .{ .v = .{ .out = .bf16, .replaces = true }, .name = base ++ "bf16 against fp8_rows one row a launch" }, + .{ .v = .{ .fixture = true }, .name = base ++ "release wkv fixture" }, + .{ .v = .{ .ctl = 1 }, .name = base ++ "control: non-finite inputs flushed" }, + .{ .v = .{ .ctl = 2 }, .name = base ++ "control: group and slice roots added in a chain" }, + .{ .v = .{ .ctl = 3 }, .name = base ++ "control: group roots rounded to fp16" }, + .{ .v = .{ .ctl = 4 }, .name = base ++ "control: writes past its output" }, + }; + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a, .device = device, .queue = queue }; + for (list) |entry| { + if (only) |text| if (std.mem.indexOf(u8, entry.name, text) == null) continue; + const p = try a.create(Proj); + p.* = try Proj.init(a, device, queue, entry.v, entry.name); + try s.probes.append(a, p); + try kernels.append(a, p.kernel()); + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + s.a.destroy(s); + } + + /// Every model FP8 shape at 1-16 rows, every form, the 16/17 seam, NaN and Inf: the row kernel's bytes. + pub fn equality(s: *Suite, seed: u64) !usize { + const p = if (s.probes.items.len > 0) s.probes.items[0] else return 0; + if (p.v.ctl != 0) return 0; + return eq.run(s.a, &p.rig, &p.pipes, &p.rows, seed); + } +}; diff --git a/zig/tests/contract/metal_dsv41_fp8_tile_eq.zig b/zig/tests/contract/metal_dsv41_fp8_tile_eq.zig new file mode 100644 index 00000000000..42c6419beb4 --- /dev/null +++ b/zig/tests/contract/metal_dsv41_fp8_tile_eq.zig @@ -0,0 +1,121 @@ +//! The FP8 tile against the row kernel on the model's own shapes: rows at once == one row a launch, every form. +const std = @import("std"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("dsv41_fp8_ref.zig"); + +const c = contract.spec; +const tile = tf.dsv41_metal.fp8_tile; +const rows_k = tf.dsv41_metal.fp8_rows; + +/// K x N of every dense FP8 projection the decode forward runs (wo_a once a group, the drafter's main_proj last). +pub const shapes = [_][2]u32{ + .{ 5120, 1280 }, .{ 5120, 512 }, .{ 1280, 32768 }, .{ 4096, 1024 }, .{ 8192, 5120 }, + .{ 5120, 2304 }, .{ 2304, 5120 }, .{ 1280, 4096 }, .{ 15360, 5120 }, +}; +const forms = [_]tile.Form{ + .{ .nj = 1, .sgs = 1 }, .{ .nj = 1, .sgs = 2 }, .{ .nj = 1, .sgs = 4 }, .{ .nj = 1, .sgs = 8 }, + .{ .nj = 1, .sgs = 16 }, .{ .nj = 2, .sgs = 1 }, .{ .nj = 2, .sgs = 4 }, .{ .nj = 2, .sgs = 8 }, +}; +const all = 17; + +fn at(r: rig_.Ref, extra: usize) tile.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; +} + +fn rat(r: rig_.Ref, extra: usize) rows_k.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; +} + +/// Non-finite inputs and weights: NaN and both infinities in four rows, NaN codes, a NaN scale and a huge one. +fn plant(f: ref.Fp8) void { + f.fill(.nonfinite, 0); + const k = f.shape.k; + const groups = k / 32; + f.codes[3 * k + 7] = 0x7f; + f.codes[40 * k + k / 2] = 0xff; + f.scales[groups - 1] = 255; + f.scales[f.scales.len / 2] = 250; + f.x[9 * k + 5] = c.toBf16(std.math.inf(f32)); + f.x[14 * k + k - 3] = c.toBf16(std.math.nan(f32)); +} + +fn validForm(k: u32, n: u32, f: tile.Form) bool { + const pad = std.math.ceilPowerOfTwo(u32, k / 32) catch unreachable; + return n % (8 * f.nj) == 0 and f.sgs * f.nj <= tile.max_lanes and f.sgs <= pad and pad / f.sgs <= 512; +} + +/// Returns the launches whose bytes differ from the row kernel's (NaN payloads included). +pub fn run(a: std.mem.Allocator, rig: *rig_.Rig, pipes: *const tile.Pipelines, rows: *const rows_k.Pipelines, seed: u64) !usize { + _ = seed; + var bad: usize = 0; + var launches: usize = 0; + var nan_outputs: usize = 0; + for (shapes) |kn| for ([_]tile.Out{ .f32, .bf16 }) |out| { + rig.reset(); + const k = kn[0]; + const n = kn[1]; + const f = try ref.Fp8.init(a, .{ .rows = all, .n = n, .k = k }); + defer f.deinit(); + plant(f); + const es: usize = if (out == .f32) 4 else 2; + const bytes = all * @as(usize, n) * es; + const x = try rig.input(std.mem.sliceAsBytes(f.x)); + const w = try rig.input(f.codes); + const s = try rig.input(f.scales); + const want = try rig.output(bytes); + const got = try rig.output(bytes); + const one: rows_k.Call = .{ .k = k, .n = n, .rows = 1, .split = rows_k.splitOf(k), .out = if (out == .f32) .f32 else .bf16 }; + { + const pass = rig.begin(); + for (0..all) |r| try rows_k.encodeWhole(rows, pass.e, rat(x, 2 * r * k), rat(w, 0), rat(s, 0), rat(want, es * r * n), one, .{}); + try rig.finish(pass); + } + const base = rig.bytes(want, bytes); + for (0..all * @as(usize, n)) |i| { + if (out == .f32 and std.math.isNan(std.mem.bytesToValue(f32, base[4 * i ..][0..4]))) nan_outputs += 1; + } + // every row count and form from row 0; then 1-15 rows from row 1 (a later segment's rows) + for ([_]usize{ 0, 1 }) |first| for (1..tile.max_rows + 1 - first) |r| for (forms) |fm| { + if (!validForm(k, n, fm)) continue; + @memset(rig.bytes(got, bytes), 0xff); + const pass = rig.begin(); + const cl: tile.Call = .{ .k = k, .n = n, .rows = @intCast(r), .out = out }; + try tile.encodeAs(pipes, pass.e, at(x, 2 * first * k), at(w, 0), at(s, 0), at(got, es * first * n), cl, .{}, fm); + try rig.finish(pass); + launches += 1; + const span = es * n; + if (!std.mem.eql(u8, base[first * span ..][0 .. r * span], rig.bytes(got, bytes)[first * span ..][0 .. r * span])) { + bad += 1; + if (bad <= 8) std.debug.print("FAIL dsv41_fp8_tile equality {d}x{d} {s}: rows {d}..{d} form c{d}s{d}\n", .{ k, n, @tagName(out), first, first + r, 8 * fm.nj, fm.sgs }); + } + }; + // the 16/17 seam: 16 rows on the tile, the 17th on the row kernel, as the forward splits a 17-row window + { + @memset(rig.bytes(got, bytes), 0xff); + const pass = rig.begin(); + try tile.encode(pipes, pass.e, at(x, 0), at(w, 0), at(s, 0), at(got, 0), .{ .k = k, .n = n, .rows = 16, .out = out }, .{}); + try rows_k.encodeWhole(rows, pass.e, rat(x, 2 * 16 * k), rat(w, 0), rat(s, 0), rat(got, es * 16 * n), one, .{}); + try rig.finish(pass); + launches += 1; + if (!std.mem.eql(u8, base, rig.bytes(got, bytes))) bad += 1; + } + // a batch in grid y: three launches of 5 rows over the same weights, rows 0-4, 6-10 and 12-16 + { + @memset(rig.bytes(got, bytes), 0xff); + const pass = rig.begin(); + const b: tile.Batch = .{ .n = 3, .xs = @intCast(2 * 6 * k), .ys = @intCast(es * 6 * n) }; + try tile.encode(pipes, pass.e, at(x, 0), at(w, 0), at(s, 0), at(got, 0), .{ .k = k, .n = n, .rows = 5, .out = out }, b); + try rig.finish(pass); + launches += 1; + for ([_]usize{ 0, 6, 12 }) |r0| { + const span = es * n; + if (!std.mem.eql(u8, base[r0 * span ..][0 .. 5 * span], rig.bytes(got, bytes)[r0 * span ..][0 .. 5 * span])) bad += 1; + } + } + }; + const word = if (bad == 0) "PASS" else "FAIL"; + std.debug.print("{s} dsv41_fp8_tile equality: {d} model shapes x f32/bf16, rows 1-16 from row 0 and 1-15 from row 1 at every form, the 16/17 seam and a 3-launch batch ({d} launches, NaN/Inf planted, {d} NaN outputs in the f32 baselines) byte-equal to fp8_rows one row a launch: {d} differ\n", .{ word, shapes.len, launches, nan_outputs, bad }); + return bad; +} diff --git a/zig/tests/contract/metal_dsv41_limits.zig b/zig/tests/contract/metal_dsv41_limits.zig index 77e7c7ec0b6..c07ab959a3d 100644 --- a/zig/tests/contract/metal_dsv41_limits.zig +++ b/zig/tests/contract/metal_dsv41_limits.zig @@ -22,6 +22,10 @@ pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, if (!assemble) return @as(Launch, undefined); return .{ .decl = d, .function = fun, .here = sources.dsv41.fp8_mma, .pre_m5 = sources.dsv41.fp8_mma }; } + if (std.mem.startsWith(u8, d.name, "dsv41 fp8 tile ")) { + if (!assemble) return @as(Launch, undefined); + return .{ .decl = d, .function = fun, .here = sources.dsv41.fp8_tile, .pre_m5 = sources.dsv41.fp8_tile }; + } if (std.mem.startsWith(u8, d.name, "dsv41 attn ")) { if (!assemble) return @as(Launch, undefined); return .{ .decl = d, .function = fun, .here = sources.dsv41.csa2_attn, .pre_m5 = sources.dsv41.csa2_attn }; diff --git a/zig/tests/contract/metal_dsv41_main.zig b/zig/tests/contract/metal_dsv41_main.zig index 31caf058298..f33b104c4af 100644 --- a/zig/tests/contract/metal_dsv41_main.zig +++ b/zig/tests/contract/metal_dsv41_main.zig @@ -7,6 +7,7 @@ const g = contract.gates; const dsv41_route = @import("metal_dsv41_route.zig"); const dsv41_fp8_rows = @import("metal_dsv41_fp8_rows.zig"); const dsv41_fp8_mma = @import("metal_dsv41_fp8_mma.zig"); +const dsv41_fp8_tile = @import("metal_dsv41_fp8_tile.zig"); const dsv41_topk512 = @import("metal_dsv41_topk512.zig"); const dsv41_cand = @import("metal_dsv41_cand.zig"); const dsv41_attn = @import("metal_dsv41_attn.zig"); @@ -76,6 +77,7 @@ pub const Routes = struct { pub const Suites = struct { fp8: *dsv41_fp8_rows.Suite, fp8_mma: *dsv41_fp8_mma.Suite, + fp8_tile: *dsv41_fp8_tile.Suite, topk: *dsv41_topk512.Suite, cand: *dsv41_cand.Suite, attn: *dsv41_attn.Suite, @@ -102,6 +104,8 @@ pub const Suites = struct { errdefer fp8.destroy(); const fp8_mma = try dsv41_fp8_mma.Suite.create(a, device, queue, kernels, only); errdefer fp8_mma.destroy(); + const fp8_tile = try dsv41_fp8_tile.Suite.create(a, device, queue, kernels, only); + errdefer fp8_tile.destroy(); const topk = try dsv41_topk512.Suite.create(a, device, queue, kernels, only); errdefer topk.destroy(); const cand = try dsv41_cand.Suite.create(a, device, queue, kernels, only); @@ -142,7 +146,7 @@ pub const Suites = struct { errdefer fused5.destroy(); const glue_tmp2 = try dsv41_glue_tmp2.Suite.create(a, device, queue, kernels, only); errdefer glue_tmp2.destroy(); - return .{ .fp8 = fp8, .fp8_mma = fp8_mma, .topk = topk, .cand = cand, .attn = attn, .experts = experts, .xmma = xmma, .ix = ix, .engram = engram, .glue = glue, .compress = compress, .mv = mv, .vision = vision, .hc = hc, .fold = fold, .glue_tmp = glue_tmp, .fused = fused, .fused2 = fused2, .fused3 = fused3, .fused4 = fused4, .fused5 = fused5, .glue_tmp2 = glue_tmp2 }; + return .{ .fp8 = fp8, .fp8_mma = fp8_mma, .fp8_tile = fp8_tile, .topk = topk, .cand = cand, .attn = attn, .experts = experts, .xmma = xmma, .ix = ix, .engram = engram, .glue = glue, .compress = compress, .mv = mv, .vision = vision, .hc = hc, .fold = fold, .glue_tmp = glue_tmp, .fused = fused, .fused2 = fused2, .fused3 = fused3, .fused4 = fused4, .fused5 = fused5, .glue_tmp2 = glue_tmp2 }; } pub fn destroy(s: *Suites) void { @@ -166,6 +170,7 @@ pub const Suites = struct { s.attn.destroy(); s.cand.destroy(); s.topk.destroy(); + s.fp8_tile.destroy(); s.fp8_mma.destroy(); s.fp8.destroy(); } @@ -181,6 +186,7 @@ pub const Suites = struct { t.failed += try s.fp8_mma.invariance(seed); t.failed += try s.fp8_mma.accuracy(seed); if (std.c.getenv("TF_DSV41_TIME") != null) try s.fp8_mma.timing(io); + t.failed += try s.fp8_tile.equality(seed); t.failed += try s.topk.invariance(seed); if (std.c.getenv("TF_DSV41_TIME") != null) try s.topk.timing(io); t.failed += try s.cand.invariance(seed); diff --git a/zig/tests/dsv41_metal/layer_test.zig b/zig/tests/dsv41_metal/layer_test.zig index 40cc3be3fb2..9e3aa03a2a2 100644 --- a/zig/tests/dsv41_metal/layer_test.zig +++ b/zig/tests/dsv41_metal/layer_test.zig @@ -19,6 +19,7 @@ test { _ = @import("dspark_test.zig"); _ = @import("multi_test.zig"); _ = @import("units_test.zig"); + _ = @import("tile_test.zig"); } test "dsv41 metal: every stage of every layer kind within its float64 bound" { diff --git a/zig/tests/dsv41_metal/multi_test.zig b/zig/tests/dsv41_metal/multi_test.zig index 4819c786c6d..775c818ee71 100644 --- a/zig/tests/dsv41_metal/multi_test.zig +++ b/zig/tests/dsv41_metal/multi_test.zig @@ -154,6 +154,8 @@ test "dsv41 metal multi-slot forward: rows of 2, 3 and 4 slots in one launch equ bad += try compare(a, f, &.{ 1103, 640, 1100 }, &.{ 1, 4, 2 }, 310); bad += try compare(a, f, &.{ 1101, 1104, 1099, 97 }, &.{ 4, 4, 4, 4 }, 320); bad += try compare(a, f, &.{ 1101, 1102, 1103, 1104 }, &.{ 1, 1, 1, 1 }, 330); + // eight rows of four slots: the FP8 projections on the MMA tile, each slot's rows as alone + bad += try compare(a, f, &.{ 1101, 1102, 1103, 1104 }, &.{ 2, 2, 2, 2 }, 335); bad += try compare(a, f, &.{ 7, 128, 1101, 1279 - 6 }, &.{ 2, 6, 1, 7 }, 340); try testing.expectEqual(@as(usize, 0), bad); } diff --git a/zig/tests/dsv41_metal/tile_test.zig b/zig/tests/dsv41_metal/tile_test.zig new file mode 100644 index 00000000000..8f7e78c955c --- /dev/null +++ b/zig/tests/dsv41_metal/tile_test.zig @@ -0,0 +1,50 @@ +//! The decode layer picks its FP8 kernel by row count: the row kernel below the tile's rows, the MMA tile from them. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const fixture = @import("fixture.zig"); +const recorder = @import("recorder.zig"); + +const testing = std.testing; +const tile = pkg.pipelines.fp8_tile; + +/// Dispatches of one layer's encode at `rows` rows: on the tile, and on the row kernel's one-launch pipelines. +fn count(r: *fixture.Rig, rows: u32) ![2]usize { + var rec: recorder.Recording = .{ .a = testing.allocator }; + defer rec.deinit(); + const x = r.ctx(&r.slot, 1101, rows); + const s = r.streams(); + const pr = r.pres(); + const e = recorder.start(&rec); + try pkg.layer.encode(&x, e, &r.layers[1], .{ .x = s[0], .pre = pr[0], .x_out = s[1], .pre_out = pr[1] }); + recorder.stop(e); + var out: [2]usize = .{ 0, 0 }; + var pipe: ?mtl.objc.Id = null; + for (rec.ops.items) |op| switch (op) { + .pipe => |p| pipe = p, + .groups, .threads => { + for (r.p.tile.p) |t| for (t) |cb| for (cb) |q| { + out[0] += @intFromBool(pipe == q.id); + }; + for (r.p.fp8.whole) |k| for (k) |t| for (t) |q| { + out[1] += @intFromBool(pipe == q.id); + }; + }, + else => {}, + }; + return out; +} + +test "dsv41 metal: a layer's FP8 projections run on the row kernel below the tile's rows and on the tile from them" { + const r = try fixture.Rig.init(testing.allocator, testing.io, 1280, 44); + defer r.deinit(); + for (1..tile.max_rows + 1) |rows| { + const n = try count(r, @intCast(rows)); + if (rows < tile.min_rows) { + try testing.expect(n[0] == 0 and n[1] > 0); + } else { + try testing.expect(n[0] > 0 and n[1] == 0); + } + } + std.debug.print("PASS dsv41 metal FP8 kernel by rows: row kernel at 1-{d} rows, the MMA tile at {d}-16\n", .{ tile.min_rows - 1, tile.min_rows }); +} diff --git a/zig/tests/dsv41_metal/timing_fp8.zig b/zig/tests/dsv41_metal/timing_fp8.zig new file mode 100644 index 00000000000..bafd2dfdfd2 --- /dev/null +++ b/zig/tests/dsv41_metal/timing_fp8.zig @@ -0,0 +1,84 @@ +//! Each FP8 projection of a synthetic release-shape layer alone: the row kernel against the MMA tile at 1-16 rows. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const fixture = @import("fixture.zig"); +const timing = @import("timing_real.zig"); + +const counters = mtl.counters; +const fp8 = pkg.pipelines.fp8; +const tile = pkg.pipelines.fp8_tile; + +const Arm = union(enum) { rows, tile: tile.Form }; + +fn encode(r: *fixture.Rig, e: mtl.ComputeEncoder, w: pkg.weights.Fp8, x: mtl.Buffer, y: mtl.Buffer, rows: u32, arm: Arm) !void { + switch (arm) { + .rows => { + const call: fp8.Call = .{ .k = w.k, .n = w.n, .rows = rows, .split = fp8.splitOf(w.k), .out = .bf16 }; + try fp8.encodeWhole(&r.p.fp8, e, .{ .buf = x }, .{ .buf = w.w.buf, .off = w.w.off }, .{ .buf = w.s.buf, .off = w.s.off }, .{ .buf = y }, call, .{}); + }, + .tile => |f| { + const call: tile.Call = .{ .k = w.k, .n = w.n, .rows = rows, .out = .bf16 }; + try tile.encodeAs(&r.p.tile, e, .{ .buf = x }, .{ .buf = w.w.buf, .off = w.w.off }, .{ .buf = w.s.buf, .off = w.s.off }, .{ .buf = y }, call, .{}, f); + }, + } +} + +fn once(r: *fixture.Rig, junk: mtl.Buffer, samples: counters.SampleBuffer, pass: counters.ComputePass, w: pkg.weights.Fp8, x: mtl.Buffer, y: mtl.Buffer, rows: u32, arm: Arm) !f64 { + timing.flush(r, junk); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const before = counters.sampleClocks(r.device); + const cb = r.queue.commandBuffer(); + const e = try pass.compute(cb, samples, 0, 1); + try encode(r, e, w, x, y, rows, arm); + e.end(); + cb.commit(); + cb.wait(); + const res = try samples.resolveCompleted(2); + defer res.deinit(); + const after = counters.sampleClocks(r.device); + const cpu: f64 = @floatFromInt(after.cpu - before.cpu); + const gpu: f64 = @floatFromInt(after.gpu - before.gpu); + const v = res.values(); + return @as(f64, @floatFromInt(v[1].timestamp -% v[0].timestamp)) * cpu / gpu * 1e-9; +} + +/// Fastest of `n` cold launches of each arm, interleaved, and whether every tile arm wrote the row kernel's bytes. +pub fn run(r: *fixture.Rig, junk: mtl.Buffer, n: usize) !void { + const l = &r.layers[1]; + const Shape = struct { name: []const u8, w: pkg.weights.Fp8 }; + const shapes = [_]Shape{ .{ .name = "wq_a", .w = l.wq_a }, .{ .name = "wkv", .w = l.wkv }, .{ .name = "wq_b", .w = l.wq_b }, .{ .name = "wo_b", .w = l.wo_b }, .{ .name = "shared w1", .w = l.shared[0] }, .{ .name = "shared w2", .w = l.shared[1] }, .{ .name = "ix_wq_b", .w = l.ix_wq_b.? } }; + const x = try r.device.buffer(16 * 8192 * 2, mtl.ResourceOptions.shared); + defer x.deinit(); + var prng = std.Random.DefaultPrng.init(3); + for (x.slice(u16, 16 * 8192)) |*v| v.* = @as(u16, @intCast(0x3c00 + prng.random().uintLessThan(u16, 0x0400))) ^ (@as(u16, prng.random().int(u1)) << 15); + const ya = try r.device.buffer(16 * 32768 * 2, mtl.ResourceOptions.shared); + defer ya.deinit(); + const yb = try r.device.buffer(16 * 32768 * 2, mtl.ResourceOptions.shared); + defer yb.deinit(); + const samples = try counters.SampleBuffer.init(r.device, 64); + defer samples.deinit(); + const pass = try counters.ComputePass.init(); + defer pass.deinit(); + const forms = [_]tile.Form{ .{ .nj = 1, .sgs = 8 }, .{ .nj = 1, .sgs = 16 }, .{ .nj = 2, .sgs = 4 }, .{ .nj = 2, .sgs = 8 } }; + const t = try std.heap.page_allocator.alloc(f64, n); + defer std.heap.page_allocator.free(t); + var differ: usize = 0; + for (shapes) |sh| for ([_]u32{ 1, 2, 4, 5, 6, 7, 8, 12, 16 }) |rows| { + std.debug.print(" fp8 {s:<9} {d:>5}x{d:<5} {d:>2} row(s): rows", .{ sh.name, sh.w.k, sh.w.n, rows }); + for (t) |*v| v.* = try once(r, junk, samples, pass, sh.w, x, ya, rows, .rows); + std.debug.print(" {d:.1}", .{timing.least(t) * 1e6}); + if (rows >= 2) for (forms) |f| { + if (f.sgs > (std.math.ceilPowerOfTwo(u32, sh.w.k / 32) catch unreachable)) continue; + for (t) |*v| v.* = try once(r, junk, samples, pass, sh.w, x, yb, rows, .{ .tile = f }); + const mark: []const u8 = if (std.meta.eql(f, tile.formOf(sh.w.k, sh.w.n))) "*" else ""; + std.debug.print(" | c{d}s{d}{s} {d:.1}", .{ 8 * f.nj, f.sgs, mark, timing.least(t) * 1e6 }); + const bytes = 2 * @as(usize, rows) * sh.w.n; + if (!std.mem.eql(u8, ya.contents()[0..bytes], yb.contents()[0..bytes])) differ += 1; + }; + std.debug.print(" us\n", .{}); + }; + std.debug.print("{s} fp8 tile arms byte-equal to the row kernel: {d} differ\n", .{ if (differ == 0) "PASS" else "FAIL", differ }); + if (differ != 0) return error.TileDiffers; +} diff --git a/zig/tests/dsv41_metal/timing_synth.zig b/zig/tests/dsv41_metal/timing_synth.zig index d5e2d3b9fa9..f848450f087 100644 --- a/zig/tests/dsv41_metal/timing_synth.zig +++ b/zig/tests/dsv41_metal/timing_synth.zig @@ -5,6 +5,7 @@ const pkg = @import("dsv41_metal"); const host = @import("dsv41"); const fixture = @import("fixture.zig"); const timing = @import("timing_real.zig"); +const timing_fp8 = @import("timing_fp8.zig"); const Ids = host.config.Ids; const limit = 1280; @@ -43,7 +44,7 @@ fn classOf(name: []const u8) Class { return std.mem.indexOf(u8, n, t) != null; } }.f; - if (has(name, "p.fp8") or has(name, "p.mma")) return .fp8; + if (has(name, "p.fp8") or has(name, "p.tile") or has(name, "p.mma")) return .fp8; if (has(name, "p.experts") or has(name, "p.route") or has(name, "p.xmma")) return .experts; if (has(name, "p.attn") or has(name, "p.index") or has(name, "p.cand") or has(name, "p.topk512") or has(name, "p.compress")) return .attention; return .glue; @@ -105,6 +106,8 @@ test "dsv41 metal synthetic release-shape layers timed by dispatch class at 1-16 defer r.deinit(); const junk = try r.device.buffer(timing.flush_bytes, mtl.ResourceOptions.private); defer junk.deinit(); + // TF_DSV41_SYNTH_FP8: each FP8 projection alone, the row kernel against the tile at every simdgroup count + if (env("TF_DSV41_SYNTH_FP8") != null) return timing_fp8.run(r, junk, n); var names: timing.Names = .{}; try names.walk(a, pkg.pipelines.Pipelines, &r.p, "p"); var slots: [4]pkg.kv.Slot = undefined; From 7da5717e98eb1b644ef0ee9b46b0506a42395c7f Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:37:36 +0100 Subject: [PATCH 06/89] docs: the kernel contract's entry for DeepSeek V4.1's FP8 rows tile --- docs/kernel-contract.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index aa047d2c599..05df1565500 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -259,6 +259,14 @@ oracle in the kernel's fp32 order whose silu may move by exp's error, and the do DeepSeek-only copy of Kimi K3's chains with the full E8M0 scale range) against its bytes (also over the release's real FP4 expert bytes), each with four controls. The copied plan and combine (`tf_dsv41_route_plan`, `tf_dsv41_xp_combine`) are checked end to end through the GPU's own plan, and every launch is recorded for gate 5. +Metal also checks DeepSeek V4.1's FP8 rows tile (`fp8_tile.metal`, `tf_dsv41_fp8_tile_*`), which runs decode launches +of 6 to 16 rows on simdgroup MMA: one registration replaces `tf_dsv41_fp8_w*` run one row a launch and must be +bit-equal to it at every shape of its shapes gate (the seven release projections and every row count from 1 to 16), +beside f32, bf16, forced-form and release-fixture registrations against float64. A probe holds the tile byte-equal to +the row kernel one row a launch on every dense FP8 shape the decode forward runs, f32 and bf16, rows 1 to 16 from row 0 +and 1 to 15 from row 1 at every form, the 16/17 seam and a three-launch batch, with NaN and Inf planted. Four controls +go red: non-finite inputs flushed, group and slice roots added in a chain, group roots rounded to fp16, and writes past +its output. The row-split seam's four kernels (`pair_rows.metal`, launched by `pair_rows.zig`) move bf16 frames, never sums: `pair_stage` copies this rank's half of a frame row into the slot the relay sends, and `pair_gather` writes both halves of every row, its own natively and the peer's from the relayed frame. `pair_argmax` flags a row whose logits are not From 749d0ba4d5fc30fc2cd372fd2bdc6a6d0c927cef Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:46:56 +0000 Subject: [PATCH 07/89] changelog: #2973 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc0f5384aba..883c91b495a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- DeepSeek-V4.1 on Metal: decode launches of 6 to 16 rows (draft verify windows, alone or with other streams' rows) run the dense FP8 projections on a simdgroup-matrix tile that splits K over simdgroups in the row kernel's own group tree, so every row's bits equal the row kernel's one row at a time; launches of 1 to 5 rows keep the row kernel. On the release weights two drafted streams decode 3.7 to 5.5% faster on an M5 Ultra and 3.6 to 5.4% faster on an M3 Ultra, other stream counts are level, and every token is unchanged; `time-dsv41-metal-synth` times the dispatch classes per row without a checkpoint (#2973, part of #2984). + - Tools: add the heat-exchanger agent evaluation and its bounded Python execution helper (#3086). - Packaging: a Grafana dashboard for the engine's Prometheus metrics (TTFT and TPOT quantiles, decode rate, running and waiting requests, KV use, draft acceptance, prompt cache, memory and admission), with a host test that rejects unwritten metrics (#3141). From b49f65b549902a6e7f554b1ace2180c964f1e6fd Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:28:35 +0000 Subject: [PATCH 08/89] feat(images): stream step progress and previews while a picture generates With stream: true, an engine that reports its steps sends image_generation.progress after each denoising step and image_generation.completed with the PNG, then [DONE]; preview_interval adds image_generation.partial_image, a separate PNG of at most 128 pixels a side and 80 KiB, every N steps. The engine's observer is null unless the request streams, so a whole reply does no extra work and its bytes are unchanged; the final PNG is the same with or without progress and previews. A client that leaves or a failed write cancels at the next step. With n above 1 each picture streams its own steps in order on one stream. Fixes #3224 --- docs/api.md | 23 ++ zig/build/server.zig | 3 +- zig/src/core/engine_api.zig | 2 + zig/src/core/image_api.zig | 39 +++- zig/src/server/image_progress_queue.zig | 102 +++++++++ .../server/image_progress_test_harness.zig | 176 ++++++++++++++ zig/src/server/image_progress_wire.zig | 77 +++++++ zig/src/server/images_generations.zig | 54 ++++- zig/src/server/images_progress.zig | 64 ++++++ zig/src/server/images_progress_test.zig | 215 ++++++++++++++++++ .../server/images_sequence_progress_test.zig | 101 ++++++++ zig/src/server/root.zig | 2 + 12 files changed, 844 insertions(+), 14 deletions(-) create mode 100644 zig/src/server/image_progress_queue.zig create mode 100644 zig/src/server/image_progress_test_harness.zig create mode 100644 zig/src/server/image_progress_wire.zig create mode 100644 zig/src/server/images_progress.zig create mode 100644 zig/src/server/images_progress_test.zig create mode 100644 zig/src/server/images_sequence_progress_test.zig diff --git a/docs/api.md b/docs/api.md index 2ac6ea7f13f..fcd9adf2593 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1016,6 +1016,29 @@ The reply is written once every picture has finished. A refusal, a failed genera and returns that error with no pictures. A client that disconnects cancels the current picture, and the later pictures are never submitted. +## Image generation streams + +With `stream: true`, on an engine that reports its denoising steps, the route answers `text/event-stream`. After +each step it sends `image_generation.progress` with `index` (the picture, from 0), `seed`, `step` (from 1) and +`total_steps`; when the picture is done, `image_generation.completed` carries its `b64_json` PNG, `index` and +`seed`. With `n` above 1 the pictures follow one another on the same stream, each counting its own steps, and one +`data: [DONE]` ends it. Each event's `type` is its event name, OpenAI's for the completed picture and the previews. + +`preview_interval: N`, an integer from 1 through `steps` sent with `stream: true` to an engine that makes previews, +adds `image_generation.partial_image` after every Nth step's progress event. Its `b64_json` is a separate PNG of at +most 128 pixels a side and 81,920 bytes, with `width`, `height`, `step`, `total_steps`, `index`, `seed` and +`partial_image_index` (from 0). Previews do not change the picture: the final PNG bytes are the same with or without +`stream` and `preview_interval`, and no preview is made unless one is asked for. For example, +`{"model":"m","prompt":"A red kite","seed":42,"steps":8,"stream":true,"preview_interval":2}` sends progress for +steps 1 to 8, previews after steps 2, 4, 6 and 8, then the picture. + +A request without `stream`, or with `stream: false`, gets the whole JSON reply as before. `stream` on an engine +without step progress, `preview_interval` without `stream` or on an engine without previews, and a value out of +range are HTTP 400 before anything is submitted. A refusal before the stream starts is the usual HTTP error; once it +has started, a failure is an `error` event holding OpenAI's error object, then `data: [DONE]`, and the pictures +already completed stay sent. A client that disconnects, or a write that fails, cancels the picture at its next step, +and no later picture is submitted. + ## Embeddings `POST /v1/embeddings` takes OpenAI's body: `input` is one text, a list of texts, one list of token IDs or a list of diff --git a/zig/build/server.zig b/zig/build/server.zig index a01718a3998..8a1557bec05 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -102,7 +102,8 @@ pub fn testImports(b: *std.Build, m: *std.Build.Module, target: std.Build.Resolv /// Tool parsing and actual chat visibility checks share the aggregate's real modules. pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Build.Module, all: *std.Build.Step) void { - b.step("test-images-host", "Image route counts, seeds, refusals and cancellation without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "image sequence:", "images_generations_test." } })).step); + const images = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "image sequence", "image progress:", "images_generations_test." } })); + b.step("test-images-host", "Image route counts, seeds, step streams, previews and cancellation without devices").dependOn(&images.step); testImports(b, parser, b.graph.host, .debug); testImports(b, server, b.graph.host, .debug); b.step("test-token-stream-host", "Native token streams, semantic anchors and cancellation without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"token stream:"} })).step); diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index cecb0082881..1b358d4e303 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -128,6 +128,8 @@ pub const SpeechSubmitError = error{ Closed, Busy, InvalidRequest, Unsupported } pub const ImageRequest = @import("image_api.zig").ImageRequest; pub const ImageResult = @import("image_api.zig").ImageResult; pub const ImageInfo = @import("image_api.zig").ImageInfo; +pub const ImagePreview = @import("image_api.zig").ImagePreview; +pub const ImageObserver = @import("image_api.zig").ImageObserver; pub const ImageSubmitError = error{ Closed, Busy, InvalidRequest, Unsupported }; pub const Reason = enum { stop, length, cancelled, failed, silence }; diff --git a/zig/src/core/image_api.zig b/zig/src/core/image_api.zig index e67fee21c75..46e014b38eb 100644 --- a/zig/src/core/image_api.zig +++ b/zig/src/core/image_api.zig @@ -5,7 +5,30 @@ const std = @import("std"); pub const ImageResult = struct { bytes: usize = 0, reason: @import("engine_api.zig").Reason = .stop }; /// What the engine's image host serves, fixed once it has loaded: the host's stated limits, each one non-zero. -pub const ImageInfo = struct { max_side: u16, max_pixels: u32, max_steps: u32, max_prompt_tokens: u32 }; +pub const ImageInfo = struct { + max_side: u16, + max_pixels: u32, + max_steps: u32, + max_prompt_tokens: u32, + progress: bool = false, // the engine calls `reportStep` after each step, so `stream` is served + previews: bool = false, // the engine also passes a preview when `wantsPreview`, so `preview_interval` is served +}; + +/// A separate small PNG; borrowed only during the observer call, without changing the final image's state. +pub const ImagePreview = struct { + pub const max_side = 128; + pub const max_bytes = 80 * 1024; + png: []const u8, + width: u16, + height: u16, +}; + +/// Called once after each completed denoising step; false asks the engine to finish cancelled at this boundary. +pub const ImageObserver = struct { + ctx: *anyopaque, + publish: *const fn (*anyopaque, u32, u32, ?ImagePreview) bool, + preview_interval: u32 = 0, +}; /// The one picture a request carries, caller-owned until `finished`. pub const ImageRequest = struct { @@ -21,4 +44,18 @@ pub const ImageRequest = struct { png: *std.ArrayList(u8), /// The allocator `png` lives in: the engine appends with it, the caller frees with it. alloc: std.mem.Allocator, + /// Null keeps progress and preview work off; the observer lives until the finished event. + observer: ?ImageObserver = null, + + /// Whether `reportStep` for this step must carry a preview; false without an observer, so no preview is made. + pub fn wantsPreview(r: *const ImageRequest, step: u32) bool { + const o = r.observer orelse return false; + return o.preview_interval > 0 and step > 0 and step <= r.steps and step % o.preview_interval == 0; + } + + /// Publish after the step; a due preview is separate from the final PNG and valid until this call returns. + pub fn reportStep(r: *const ImageRequest, step: u32, preview: ?ImagePreview) bool { + const o = r.observer orelse return true; + return o.publish(o.ctx, step, r.steps, preview); + } }; diff --git a/zig/src/server/image_progress_queue.zig b/zig/src/server/image_progress_queue.zig new file mode 100644 index 00000000000..849b86e675a --- /dev/null +++ b/zig/src/server/image_progress_queue.zig @@ -0,0 +1,102 @@ +//! Bounded image-only progress handed from an engine thread to the request's writer. +const std = @import("std"); +const api = @import("engine_api"); + +pub const Frame = struct { step: u32, total: u32, preview: ?api.ImagePreview = null }; +pub const Read = struct { frame: ?Frame = null, finished: bool, reason: api.Reason, message: []const u8, problem: ?[]const u8 }; + +pub const Queue = struct { + io: std.Io, + gpa: std.mem.Allocator, + steps: u32, + preview_interval: u32, + mutex: std.Io.Mutex = .init, + changed: std.Io.Condition = .init, + cancelled: std.atomic.Value(bool) = .init(false), + frames: [200]Frame = undefined, + published: usize = 0, + consumed: usize = 0, + finished: bool = false, + reason: api.Reason = .stop, + message: []const u8 = "", + problem: ?[]const u8 = null, + + pub fn observer(q: *Queue) api.ImageObserver { + return .{ .ctx = q, .publish = publish, .preview_interval = q.preview_interval }; + } + pub fn sink(q: *Queue) api.Sink { + return .{ .ctx = q, .event = event }; + } + fn cast(ctx: *anyopaque) *Queue { + return @ptrCast(@alignCast(ctx)); + } + fn fail(q: *Queue, message: []const u8) bool { + q.problem = message; + q.cancelled.store(true, .release); + q.changed.signal(q.io); + return false; + } + fn publish(ctx: *anyopaque, step: u32, total: u32, preview: ?api.ImagePreview) bool { + const q = cast(ctx); + q.mutex.lockUncancelable(q.io); + defer q.mutex.unlock(q.io); + if (q.cancelled.load(.acquire) or q.finished) return false; + if (total != q.steps or step != q.published + 1 or step > total or q.published == q.frames.len) + return q.fail("the image engine reported invalid step progress"); + const due = q.preview_interval > 0 and step % q.preview_interval == 0; + if (due != (preview != null)) return q.fail("the image engine did not honor preview_interval"); + var frame: Frame = .{ .step = step, .total = total }; + if (preview) |p| { + if (p.width == 0 or p.height == 0 or p.width > api.ImagePreview.max_side or p.height > api.ImagePreview.max_side or + p.png.len == 0 or p.png.len > api.ImagePreview.max_bytes) + return q.fail("the image preview exceeds the 128-side or 81920-byte limit"); + frame.preview = .{ .png = q.gpa.dupe(u8, p.png) catch return q.fail("out of memory copying an image preview"), .width = p.width, .height = p.height }; + } + q.frames[q.published] = frame; + q.published += 1; + q.changed.signal(q.io); + return true; + } + fn event(ctx: *anyopaque, _: api.Id, value: *const api.Event) void { + const q = cast(ctx); + if (value.* != .finished) return; + q.mutex.lockUncancelable(q.io); + defer q.mutex.unlock(q.io); + if (q.finished) return; + q.reason = value.finished.reason; + q.message = q.gpa.dupe(u8, value.finished.message) catch ""; + if (q.reason != .failed and q.reason != .cancelled and q.published != q.steps) + q.problem = "the image engine finished before reporting every step"; + q.finished = true; + q.changed.signal(q.io); + } + pub fn next(q: *Queue) Read { + q.mutex.lockUncancelable(q.io); + defer q.mutex.unlock(q.io); + if (q.consumed == q.published and !q.finished and q.problem == null) + q.changed.waitTimeout(q.io, &q.mutex, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake } }) catch {}; + var out: Read = .{ .finished = q.finished, .reason = q.reason, .message = q.message, .problem = q.problem }; + if (q.consumed < q.published) { + out.frame = q.frames[q.consumed]; + q.consumed += 1; + } + return out; + } + pub fn cancelAndWait(q: *Queue, engine: api.Engine, id: api.Id) void { + q.cancelled.store(true, .release); + q.mutex.lockUncancelable(q.io); + const done = q.finished; + q.mutex.unlock(q.io); + if (!done) engine.cancel(id); + q.mutex.lockUncancelable(q.io); + defer q.mutex.unlock(q.io); + while (!q.finished) q.changed.waitUncancelable(q.io, &q.mutex); + } + pub fn freeFrame(q: *Queue, frame: Frame) void { + if (frame.preview) |p| q.gpa.free(p.png); + } + pub fn deinit(q: *Queue) void { + for (q.frames[q.consumed..q.published]) |frame| q.freeFrame(frame); + q.gpa.free(q.message); + } +}; diff --git a/zig/src/server/image_progress_test_harness.zig b/zig/src/server/image_progress_test_harness.zig new file mode 100644 index 00000000000..aae189a5f7c --- /dev/null +++ b/zig/src/server/image_progress_test_harness.zig @@ -0,0 +1,176 @@ +//! A fake denoiser that gates each step on its actual HTTP progress write, with borrowed preview scratch. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const root = @import("root.zig"); +const http = @import("http_conn.zig"); +const Bytes = @import("speech_stream_test.zig").Bytes; +const t = std.testing; + +pub const Fake = struct { + calls: usize = 0, + progress: bool = true, + previews: bool = true, + gate: bool = true, + inline_: bool = false, + ignore_cancel: bool = false, + reject: ?api.ImageSubmitError = null, + reject_at: ?usize = null, + fail_step: ?u32 = null, + early_stop: ?u32 = null, + invalid_step: bool = false, + oversized_preview: bool = false, + missing_preview: bool = false, + leave_after: ?u32 = null, + delivered: std.atomic.Value(u32) = .init(0), + steps_done: std.atomic.Value(u32) = .init(0), + preview_reads: std.atomic.Value(u32) = .init(0), + finished: std.atomic.Value(bool) = .init(false), + cancelled: std.atomic.Value(bool) = .init(false), + live: std.atomic.Value(bool) = .init(false), + gate_timeout: std.atomic.Value(bool) = .init(false), + cancels: usize = 0, + thread: ?std.Thread = null, + observed: bool = false, + seed: u64 = 0, + + pub fn engine(f: *Fake) api.Engine { + return .{ .ctx = f, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .submit_image = image } }; + } + fn cast(ctx: *anyopaque) *Fake { + return @ptrCast(@alignCast(ctx)); + } + fn info(ctx: *anyopaque) api.Info { + const f = cast(ctx); + const cap: api.ImageInfo = .{ .max_side = 1536, .max_pixels = 1572864, .max_steps = 200, .max_prompt_tokens = 4096, .progress = f.progress, .previews = f.previews }; + return .{ .text_generation = false, .image = cap }; + } + fn submit(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Closed; + } + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } + fn cancel(ctx: *anyopaque, _: api.Id) void { + const f = cast(ctx); + f.cancels += 1; + if (!f.ignore_cancel) f.cancelled.store(true, .release); + } + fn image(ctx: *anyopaque, id: api.Id, request: *const api.ImageRequest, sink: api.Sink) api.ImageSubmitError!void { + const f = cast(ctx); + f.calls += 1; + if (f.reject) |e| if (f.reject_at == null or f.reject_at == f.calls) return e; + f.join(); + f.seed = request.seed; + f.delivered.store(0, .release); + f.steps_done.store(0, .release); + f.preview_reads.store(0, .release); + f.finished.store(false, .release); + f.cancelled.store(false, .release); + f.observed = request.observer != null; + if (f.inline_) return work(f, id, request, sink); + f.thread = std.Thread.spawn(.{}, work, .{ f, id, request, sink }) catch return error.Busy; + } + fn work(f: *Fake, id: api.Id, request: *const api.ImageRequest, sink: api.Sink) void { + var reason: api.Reason = .stop; + for (1..request.steps + 1) |n| { + const step: u32 = @intCast(n); + if (f.cancelled.load(.acquire)) { + reason = .cancelled; + break; + } + f.steps_done.store(step, .release); + var preview: [12]u8 = undefined; + @memcpy(preview[0..8], "\x89PNG\r\n\x1a\n"); + std.mem.writeInt(u32, preview[8..12], step, .little); + const due = request.wantsPreview(step); + if (due) _ = f.preview_reads.fetchAdd(1, .monotonic); + const keep = request.reportStep(if (f.invalid_step) 0 else step, if (due and !f.missing_preview) .{ .png = &preview, .width = if (f.oversized_preview) 129 else 64, .height = 64 } else null); + @memset(&preview, 0xa5); + if (!keep) { + reason = .cancelled; + break; + } + if (f.observed and f.gate) { + var tries: usize = 0; + while (f.delivered.load(.acquire) < step and !f.cancelled.load(.acquire)) : (tries += 1) { + if (tries == 2000) { + f.gate_timeout.store(true, .release); + break; + } + std.Io.sleep(t.io, .fromMilliseconds(1), .awake) catch {}; + } + } + if (f.fail_step == step) { + reason = .failed; + break; + } + if (f.early_stop == step) break; + } + if (f.cancelled.load(.acquire)) reason = .cancelled; + if (reason == .stop) { + var hash: std.crypto.hash.sha2.Sha256 = .init(.{}); + hash.update(std.mem.sliceAsBytes(request.prompt)); + hash.update(std.mem.sliceAsBytes(request.negative)); + inline for (.{ "seed", "width", "height", "steps", "guidance" }) |field| hash.update(std.mem.asBytes(&@field(request, field))); + const bytes = hash.finalResult(); + request.png.appendSlice(request.alloc, "\x89PNG\r\n\x1a\n") catch {}; + request.png.appendSlice(request.alloc, &bytes) catch {}; + } + request.result.* = .{ .bytes = request.png.items.len, .reason = reason }; + f.finished.store(true, .release); + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = reason, .message = if (reason == .failed) "fake denoising failed" else "" } }); + } + pub fn join(f: *Fake) void { + if (f.thread) |thread| thread.join(); + f.thread = null; + } + fn gone(ctx: *anyopaque) bool { + const f = cast(ctx); + return if (f.leave_after) |step| f.delivered.load(.acquire) >= step else false; + } +}; + +const Wire = struct { + a: std.mem.Allocator, + fake: *Fake, + fail_step: ?u32, + fail_index: ?usize, + fail_head: bool, + bytes: std.ArrayList(u8) = .empty, + fn write(ctx: *anyopaque, bytes: []const u8) error{Closed}!void { + const w: *Wire = @ptrCast(@alignCast(ctx)); + if (w.fail_head and std.mem.startsWith(u8, bytes, "HTTP/")) return error.Closed; + w.bytes.appendSlice(w.a, bytes) catch return error.Closed; + if (std.mem.startsWith(u8, bytes, "event: image_generation.progress\n")) { + const at = std.mem.indexOf(u8, bytes, "data: ").? + 6; + const value = (json.parse(w.a, bytes[at..]) catch return error.Closed).ok; + const step: u32 = @intCast(value.get("step").?.int64().?); + const index: usize = @intCast(value.get("index").?.int64().?); + if (!w.fake.finished.load(.acquire)) w.fake.live.store(true, .release); + w.fake.delivered.store(step, .release); + if (w.fail_step == step and (w.fail_index == null or w.fail_index == index)) return error.Closed; + } + } +}; + +pub const Reply = struct { status: u16, body: []const u8, wire: []const u8 }; +pub fn ask(a: std.mem.Allocator, fake: *Fake, body: []const u8, fail_step: ?u32, fail_head: bool) !Reply { + return askAt(a, fake, body, fail_step, fail_head, null); +} +pub fn askAt(a: std.mem.Allocator, fake: *Fake, body: []const u8, fail_step: ?u32, fail_head: bool, fail_index: ?usize) !Reply { + var text: Bytes = .{}; + const srv = try root.Server.init(t.allocator, t.io, fake.engine(), text.text(), .{ .served_name = "m", .model_ids = &.{"m"} }, null); + defer srv.deinit(); + defer fake.join(); + var wire: Wire = .{ .a = a, .fake = fake, .fail_step = fail_step, .fail_index = fail_index, .fail_head = fail_head }; + var headers = [_]http.Header{.{ .name = "Content-Length", .value = try std.fmt.allocPrint(a, "{d}", .{body.len}) }}; + var conn: http.Conn = .{ .fd = -1, .peer = "", .buf = try a.dupe(u8, body), .end = body.len, .gpa = a, .method = "POST", .path = "/v1/images/generations", .version = "HTTP/1.1", .headers = &headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .gone_hook = .{ .ctx = fake, .call = Fake.gone } }; + defer conn.deinit(); + @import("routes.zig").dispatch(srv, &conn, a); + const split = std.mem.indexOf(u8, wire.bytes.items, "\r\n\r\n"); + return .{ .status = if (split != null) try std.fmt.parseInt(u16, wire.bytes.items[9..12], 10) else 0, .body = if (split) |at| wire.bytes.items[at + 4 ..] else "", .wire = wire.bytes.items }; +} diff --git a/zig/src/server/image_progress_wire.zig b/zig/src/server/image_progress_wire.zig new file mode 100644 index 00000000000..033acc2db90 --- /dev/null +++ b/zig/src/server/image_progress_wire.zig @@ -0,0 +1,77 @@ +//! Image SSE frames under OpenAI's image_generation event names, each built in its own short-lived arena. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const sse = @import("sse.zig"); +const errors = @import("errors.zig"); +const Conn = @import("http_conn.zig").Conn; +const log = @import("log.zig"); +const openai = @import("openai.zig"); + +pub const Writer = struct { + conn: *Conn, + started: bool = false, + + pub fn start(w: *Writer) error{Closed}!void { + if (w.started) return; + try sse.open(w.conn); + w.started = true; + w.conn.response_complete = false; + } + fn item(a: std.mem.Allocator, index: usize, seed: u64, kind: []const u8) !*json.Object { + const out = try json.newObject(a); + try out.put(a, "type", .{ .string = kind }); + try out.put(a, "index", try json.intValue(a, index)); + try out.put(a, "seed", try json.intValue(a, seed)); + return out; + } + fn encoded(a: std.mem.Allocator, bytes: []const u8) !json.Value { + const buffer = try a.alloc(u8, std.base64.standard.Encoder.calcSize(bytes.len)); + return .{ .string = std.base64.standard.Encoder.encode(buffer, bytes) }; + } + pub fn progress(w: *Writer, index: usize, seed: u64, step: u32, total: u32) error{Closed}!void { + var arena: std.heap.ArenaAllocator = .init(w.conn.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const out = item(a, index, seed, "image_generation.progress") catch return error.Closed; + out.put(a, "step", json.intValue(a, step) catch return error.Closed) catch return error.Closed; + out.put(a, "total_steps", json.intValue(a, total) catch return error.Closed) catch return error.Closed; + try sse.event(w.conn, a, "image_generation.progress", .{ .object = out }); + } + pub fn preview(w: *Writer, index: usize, seed: u64, step: u32, total: u32, interval: u32, picture: api.ImagePreview) error{Closed}!void { + var arena: std.heap.ArenaAllocator = .init(w.conn.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const out = item(a, index, seed, "image_generation.partial_image") catch return error.Closed; + const fields = .{ .{ "partial_image_index", step / interval - 1 }, .{ "step", step }, .{ "total_steps", total }, .{ "width", picture.width }, .{ "height", picture.height } }; + inline for (fields) |field| out.put(a, field[0], json.intValue(a, field[1]) catch return error.Closed) catch return error.Closed; + out.put(a, "b64_json", encoded(a, picture.png) catch return error.Closed) catch return error.Closed; + try sse.event(w.conn, a, "image_generation.partial_image", .{ .object = out }); + } + pub fn completed(w: *Writer, index: usize, seed: u64, png: []const u8) error{Closed}!void { + var arena: std.heap.ArenaAllocator = .init(w.conn.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const out = item(a, index, seed, "image_generation.completed") catch return error.Closed; + out.put(a, "b64_json", encoded(a, png) catch return error.Closed) catch return error.Closed; + try sse.event(w.conn, a, "image_generation.completed", .{ .object = out }); + } + pub fn done(w: *Writer) void { + sse.done(w.conn) catch return; + w.conn.response_complete = true; + } + pub fn refused(w: *Writer, cx: *errors.Cx, id: []const u8, e: errors.Refused) void { + if (e == error.OutOfMemory) { + cx.kind = .server; + cx.message = "out of memory"; + } + var buf: [1400]u8 = undefined; + log.line("{s}", .{log.refused(&buf, id, cx.message)}); + var arena: std.heap.ArenaAllocator = .init(w.conn.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const body = openai.wrapError(a, openai.errorBody(a, cx, null) catch return) catch return; + sse.event(w.conn, a, "error", body) catch return; + w.done(); + } +}; diff --git a/zig/src/server/images_generations.zig b/zig/src/server/images_generations.zig index b46810207c8..199ef3ef3f8 100644 --- a/zig/src/server/images_generations.zig +++ b/zig/src/server/images_generations.zig @@ -15,6 +15,7 @@ const Server = @import("server.zig").Server; const Conn = @import("http_conn.zig").Conn; const Mailbox = @import("mailbox.zig").Mailbox; const streaming = @import("speech_stream.zig"); +const progress = @import("images_progress.zig"); const Value = json.Value; const Cx = errors.Cx; const Allocator = std.mem.Allocator; @@ -32,7 +33,7 @@ const default_guidance: f32 = 3; const default_seed: u64 = 42; /// The body fields this route answers; `quality` and every other key are refused by name. -const served_fields = [_][]const u8{ "model", "prompt", "n", "size", "response_format", "negative_prompt", "seed", "steps", "guidance" }; +const served_fields = [_][]const u8{ "model", "prompt", "n", "size", "response_format", "negative_prompt", "seed", "steps", "guidance", "stream", "preview_interval" }; /// One checked request: exactly what the engine's image host needs. const Plan = struct { @@ -44,6 +45,8 @@ const Plan = struct { guidance: f32, seeds: [4]u64, count: u8, + stream: bool, + preview_interval: u32, }; pub fn post(srv: *Server, c: *Conn, a: Allocator) !void { @@ -59,6 +62,20 @@ pub fn post(srv: *Server, c: *Conn, a: Allocator) !void { defer png.deinit(srv.gpa); const raw = http_body.readJson(c, &cx) catch |e| return refused(c, a, &cx, id, e); const plan = prepare(srv, &cx, cap, raw) catch |e| return refused(c, a, &cx, id, e); + if (plan.stream) { + var writer: progress.Writer = .{ .conn = c }; + for (0..plan.count) |index| { + png.clearRetainingCapacity(); + var result: api.ImageResult = .{}; + const completed = progress.generate(srv, c, &cx, imageRequest(srv, plan, plan.seeds[index], &result, &png), plan.preview_interval, index, &writer) catch |e| { + if (writer.started) return writer.refused(&cx, id, e); + return refused(c, a, &cx, id, e); + }; + if (!completed) return; + } + writer.done(); + return log.line("images prompt={d} negative={d} count={d} stream seconds={d:.2}", .{ plan.prompt.len, plan.negative.len, plan.count, clock.seconds(clock.nowNs(srv.io) - received) }); + } const data = a.alloc(Value, plan.count) catch |e| return refused(c, a, &cx, id, e); for (data, 0..) |*item, index| { png.clearRetainingCapacity(); @@ -158,6 +175,20 @@ fn prepare(srv: *Server, cx: *Cx, cap: api.ImageInfo, raw: Value) errors.Refused if (given < 1 or given > steps_most) return cx.fail(.request, "steps must be from 1 to {d}", .{steps_most}); steps = @intCast(given); } + var stream = false; + if (raw.get("stream")) |v| { + if (v != .bool) return cx.refuse("stream must be a boolean"); + stream = v.bool; + } + if (stream and !cap.progress) return cx.refuse("stream is not supported: this image engine does not report step progress"); + var interval: u32 = 0; + if (raw.get("preview_interval")) |v| { + if (!stream) return cx.refuse("preview_interval requires stream: true"); + const n = v.int64() orelse return cx.refuse("preview_interval must be an integer from 1 through steps"); + if (n < 1 or n > steps) return cx.refuse("preview_interval must be an integer from 1 through steps"); + if (!cap.previews) return cx.refuse("preview_interval is not supported by this image engine"); + interval = @intCast(n); + } var guidance: f32 = default_guidance; if (raw.get("guidance")) |v| { const given = v.float64() orelse return cx.refuse("guidance must be a number"); @@ -182,13 +213,11 @@ fn prepare(srv: *Server, cx: *Cx, cap: api.ImageInfo, raw: Value) errors.Refused for (seeds[0..@intCast(count)], 0..) |*value, index| { value.* = (seed orelse default_seed) + @as(u64, @intCast(index)); } - return .{ .prompt = prompt_ids, .negative = negative_ids, .width = width, .height = height, .steps = steps, .guidance = guidance, .seeds = seeds, .count = @intCast(count) }; + return .{ .prompt = prompt_ids, .negative = negative_ids, .width = width, .height = height, .steps = steps, .guidance = guidance, .seeds = seeds, .count = @intCast(count), .stream = stream, .preview_interval = interval }; } -/// Submits once and waits for ``finished``; nothing has been written to the connection when it returns. -fn generate(srv: *Server, c: *Conn, cx: *Cx, plan: Plan, seed: u64, result: *api.ImageResult, png: *std.ArrayList(u8)) errors.Refused!void { - if (c.peerGone()) return cx.fail(.capacity, "the client left before the picture was ready", .{}); - const request: api.ImageRequest = .{ +fn imageRequest(srv: *Server, plan: Plan, seed: u64, result: *api.ImageResult, png: *std.ArrayList(u8)) api.ImageRequest { + return .{ .prompt = plan.prompt, .negative = plan.negative, .width = plan.width, @@ -200,17 +229,18 @@ fn generate(srv: *Server, c: *Conn, cx: *Cx, plan: Plan, seed: u64, result: *api .png = png, .alloc = srv.gpa, }; +} + +/// Submits once and waits for ``finished``; nothing has been written to the connection when it returns. +fn generate(srv: *Server, c: *Conn, cx: *Cx, plan: Plan, seed: u64, result: *api.ImageResult, png: *std.ArrayList(u8)) errors.Refused!void { + if (c.peerGone()) return cx.fail(.capacity, "the client left before the picture was ready", .{}); + const request = imageRequest(srv, plan, seed, result, png); var box: Mailbox = .{ .io = srv.io, .gpa = srv.gpa }; defer box.deinit(); const engine_id = srv.next_id.fetchAdd(1, .monotonic); if (srv.keepalive) |k| k.begin(); defer if (srv.keepalive) |k| k.end(); - srv.engine.submitImage(engine_id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return switch (e) { - error.Busy => @import("refusals.zig").count(srv, .engine_busy, cx.fail(.capacity, "the engine is busy; retry shortly", .{})), - error.Closed => cx.fail(.capacity, "the scheduler is closed", .{}), - error.InvalidRequest => cx.fail(.request, "the engine refused this image request's prompt, size or steps", .{}), - error.Unsupported => cx.fail(.capacity, "this model does not serve images", .{}), - }; + srv.engine.submitImage(engine_id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return progress.submitRefused(srv, cx, e); // The engine holds request, png and result until finished: this thread writes nothing before that. _ = streaming.settle(srv, c, &box, engine_id, null) orelse return cx.fail(.capacity, "the client left before the picture was ready", .{}); // the finished event is the last one: the reason it carried is the one the log and the refusals both read diff --git a/zig/src/server/images_progress.zig b/zig/src/server/images_progress.zig new file mode 100644 index 00000000000..78e7ee86d56 --- /dev/null +++ b/zig/src/server/images_progress.zig @@ -0,0 +1,64 @@ +//! One image job whose step observer feeds SSE; request storage stays owned until its finished event. +const api = @import("engine_api"); +const errors = @import("errors.zig"); +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Queue = @import("image_progress_queue.zig").Queue; +pub const Writer = @import("image_progress_wire.zig").Writer; + +/// The refusal for an engine that would not take a picture, the same for whole replies and streams; busy is counted. +pub fn submitRefused(srv: *Server, cx: *errors.Cx, e: api.ImageSubmitError) errors.Refused { + return switch (e) { + error.Busy => @import("refusals.zig").count(srv, .engine_busy, cx.fail(.capacity, "the engine is busy; retry shortly", .{})), + error.Closed => cx.fail(.capacity, "the scheduler is closed", .{}), + error.InvalidRequest => cx.fail(.request, "the engine refused this image request's prompt, size or steps", .{}), + error.Unsupported => cx.fail(.capacity, "this model does not serve images", .{}), + }; +} + +/// Streams one picture's steps and PNG; false: the client left or a write failed, and the engine has finished. +pub fn generate(srv: *Server, c: *Conn, cx: *errors.Cx, request: api.ImageRequest, interval: u32, index: usize, writer: *Writer) errors.Refused!bool { + if (c.peerGone()) return false; + var queue: Queue = .{ .io = srv.io, .gpa = srv.gpa, .steps = request.steps, .preview_interval = interval }; + defer queue.deinit(); + var owned = request; + owned.observer = queue.observer(); + const id = srv.next_id.fetchAdd(1, .monotonic); + if (srv.keepalive) |k| k.begin(); + defer if (srv.keepalive) |k| k.end(); + srv.engine.submitImage(id, &owned, queue.sink()) catch |e| return submitRefused(srv, cx, e); + writer.start() catch { + queue.cancelAndWait(srv.engine, id); + return false; + }; + while (true) { + const next = queue.next(); + defer if (next.frame) |frame| queue.freeFrame(frame); + if (next.problem) |why| { + queue.cancelAndWait(srv.engine, id); + return cx.fail(.server, "{s}", .{why}); + } + if (c.peerGone()) { + queue.cancelAndWait(srv.engine, id); + return false; + } + if (next.frame) |frame| { + writer.progress(index, request.seed, frame.step, frame.total) catch { + queue.cancelAndWait(srv.engine, id); + return false; + }; + if (frame.preview) |preview| writer.preview(index, request.seed, frame.step, frame.total, interval, preview) catch { + queue.cancelAndWait(srv.engine, id); + return false; + }; + continue; + } + if (!next.finished) continue; + request.result.reason = next.reason; + if (next.reason == .failed) + return cx.fail(.server, "{s}", .{if (next.message.len > 0) next.message else "the image generation failed"}); + if (next.reason == .cancelled) return cx.fail(.capacity, "the image generation was cancelled", .{}); + writer.completed(index, request.seed, request.png.items[0..@min(request.result.bytes, request.png.items.len)]) catch return false; + return true; + } +} diff --git a/zig/src/server/images_progress_test.zig b/zig/src/server/images_progress_test.zig new file mode 100644 index 00000000000..f5df8a49465 --- /dev/null +++ b/zig/src/server/images_progress_test.zig @@ -0,0 +1,215 @@ +//! Live image SSE, borrowed preview ownership, unchanged final bytes and cancellation at step boundaries. +const std = @import("std"); +const json = @import("json"); +const h = @import("image_progress_test_harness.zig"); +const t = std.testing; +const request = "{\"model\":\"m\",\"prompt\":\"hi\",\"negative_prompt\":\"fog\",\"steps\":5,\"seed\":7"; + +fn body(a: std.mem.Allocator, extra: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "{s}{s}}}", .{ request, extra }); +} +pub const Event = struct { kind: []const u8, value: json.Value }; +pub fn events(a: std.mem.Allocator, raw: []const u8) ![]Event { + var out: std.ArrayList(Event) = .empty; + var it = std.mem.splitSequence(u8, raw, "\n\n"); + while (it.next()) |frame| { + if (!std.mem.startsWith(u8, frame, "event: ")) continue; + const end = std.mem.indexOfScalar(u8, frame, '\n').?; + const at = std.mem.indexOf(u8, frame, "data: ").? + 6; + try out.append(a, .{ .kind = frame[7..end], .value = (try json.parse(a, frame[at..])).ok }); + } + return out.items; +} +pub fn decoded(a: std.mem.Allocator, value: json.Value) ![]const u8 { + const encoded = value.strField("b64_json").?; + const bytes = try a.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(encoded)); + try std.base64.standard.Decoder.decode(bytes, encoded); + return bytes; +} +fn completed(list: []const Event) !json.Value { + for (list) |event| if (std.mem.eql(u8, event.kind, "image_generation.completed")) return event.value; + return error.MissingCompleted; +} +fn stableBody(a: std.mem.Allocator, raw: []const u8) ![]const u8 { + const parsed = (try json.parse(a, raw)).ok; + try parsed.object.put(a, "created", try json.intValue(a, 0)); + return json.stringify(a, parsed, .{}); +} + +test "image progress: every step is written before finished and the final PNG equals the plain request" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var plain: h.Fake = .{}; + const solo = try h.ask(a, &plain, try body(a, ""), null, false); + try t.expectEqual(@as(u16, 200), solo.status); + var fake: h.Fake = .{}; + const streamed = try h.ask(a, &fake, try body(a, ",\"stream\":true"), null, false); + try t.expectEqual(@as(u16, 200), streamed.status); + try t.expect(std.mem.indexOf(u8, streamed.wire, "text/event-stream") != null); + const list = try events(a, streamed.body); + try t.expectEqual(@as(usize, 6), list.len); + for (list) |event| try t.expectEqualStrings(event.kind, event.value.strField("type").?); + for (list[0..5], 1..) |event, step| { + try t.expectEqualStrings("image_generation.progress", event.kind); + try t.expectEqual(@as(i64, @intCast(step)), event.value.get("step").?.int64().?); + try t.expectEqual(@as(i64, 5), event.value.get("total_steps").?.int64().?); + try t.expectEqual(@as(i64, 7), event.value.get("seed").?.int64().?); + try t.expectEqual(@as(i64, 0), event.value.get("index").?.int64().?); + } + const legacy = (try json.parse(a, solo.body)).ok.get("data").?.array[0]; + try t.expectEqualSlices(u8, try decoded(a, legacy), try decoded(a, try completed(list))); + try t.expect(fake.live.load(.acquire) and !fake.gate_timeout.load(.acquire)); + try t.expectEqual(@as(u32, 0), fake.preview_reads.load(.acquire)); + try t.expect(std.mem.endsWith(u8, streamed.body, "data: [DONE]\n\n")); +} + +test "image progress: requested previews are copied at the interval and preserve the final PNG bytes" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var solo: h.Fake = .{}; + const plain = try h.ask(a, &solo, try body(a, ""), null, false); + var fake: h.Fake = .{}; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true,\"preview_interval\":2"), null, false); + try t.expectEqual(@as(u16, 200), out.status); + const list = try events(a, out.body); + var previews: u32 = 0; + for (list) |event| if (std.mem.eql(u8, event.kind, "image_generation.partial_image")) { + previews += 1; + const bytes = try decoded(a, event.value); + try t.expectEqualStrings("\x89PNG\r\n\x1a\n", bytes[0..8]); + try t.expectEqual(previews * 2, std.mem.readInt(u32, bytes[8..12], .little)); + try t.expectEqual(@as(i64, previews * 2), event.value.get("step").?.int64().?); + try t.expectEqual(@as(i64, previews - 1), event.value.get("partial_image_index").?.int64().?); + try t.expectEqual(@as(i64, 64), event.value.get("width").?.int64().?); + }; + try t.expectEqual(@as(u32, 2), previews); + try t.expectEqual(previews, fake.preview_reads.load(.acquire)); + const legacy = (try json.parse(a, plain.body)).ok.get("data").?.array[0]; + try t.expectEqualSlices(u8, try decoded(a, legacy), try decoded(a, try completed(list))); +} + +test "image progress: no stream retains the whole JSON shape, explicit seed and no observer work" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var first: h.Fake = .{}; + var second: h.Fake = .{}; + const raw = "{\"model\":\"m\",\"prompt\":\"hi\",\"steps\":5,\"seed\":42}"; + const one = try h.ask(a, &first, raw, null, false); + const two = try h.ask(a, &second, "{\"model\":\"m\",\"prompt\":\"hi\",\"steps\":5,\"seed\":42,\"stream\":false}", null, false); + try t.expectEqual(@as(u16, 200), one.status); + try t.expectEqual(@as(u16, 200), two.status); + try t.expectEqualStrings(try stableBody(a, one.body), try stableBody(a, two.body)); + try t.expectEqual(@as(u64, 42), first.seed); + try t.expect(!first.observed and !second.observed); + try t.expectEqual(@as(u32, 0), first.preview_reads.load(.acquire)); + try t.expect(std.mem.indexOf(u8, one.wire, "event-stream") == null); +} + +test "image progress: malformed fields and unsupported engine capabilities refuse before submission" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][]const u8{ + ",\"stream\":1", ",\"preview_interval\":2", ",\"stream\":true,\"preview_interval\":0", + ",\"stream\":true,\"preview_interval\":6", ",\"stream\":true,\"preview_interval\":1.5", + }) |extra| { + var fake: h.Fake = .{}; + const out = try h.ask(a, &fake, try body(a, extra), null, false); + try t.expectEqual(@as(u16, 400), out.status); + try t.expectEqual(@as(usize, 0), fake.calls); + } + for ([_]h.Fake{ .{ .progress = false }, .{ .previews = false } }) |initial| { + var fake = initial; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true,\"preview_interval\":1"), null, false); + try t.expectEqual(@as(u16, 400), out.status); + try t.expect(std.mem.indexOf(u8, out.body, "not supported") != null); + try t.expectEqual(@as(usize, 0), fake.calls); + } +} + +test "image progress: a failed write cancels at the next step and the next request is unchanged" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]bool{ false, true }) |ignore| { + var fake: h.Fake = .{ .ignore_cancel = ignore }; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true"), 1, false); + try t.expectEqual(@as(u16, 200), out.status); + try t.expectEqual(@as(usize, 1), fake.cancels); + try t.expect(fake.finished.load(.acquire) and fake.steps_done.load(.acquire) <= 2); + try t.expect(std.mem.indexOf(u8, out.body, "image_generation.completed") == null); + const resumed = try h.ask(a, &fake, try body(a, ""), null, false); + var fresh: h.Fake = .{}; + const reference = try h.ask(a, &fresh, try body(a, ""), null, false); + try t.expectEqualStrings(try stableBody(a, reference.body), try stableBody(a, resumed.body)); + } +} + +test "image progress: a departed reader cancels at the next step and releases the observer" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: h.Fake = .{ .leave_after = 1 }; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true,\"preview_interval\":1"), null, false); + try t.expectEqual(@as(usize, 1), fake.cancels); + try t.expect(fake.finished.load(.acquire) and fake.steps_done.load(.acquire) <= 2); + try t.expect(std.mem.indexOf(u8, out.body, "image_generation.completed") == null); +} + +test "image progress: failures after headers are SSE errors; submission refusals retain HTTP 400" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var failed: h.Fake = .{ .fail_step = 3 }; + const out = try h.ask(a, &failed, try body(a, ",\"stream\":true"), null, false); + try t.expectEqual(@as(u16, 200), out.status); + try t.expect(std.mem.indexOf(u8, out.body, "event: error\n") != null); + try t.expect(std.mem.indexOf(u8, out.body, "fake denoising failed") != null); + try t.expect(std.mem.indexOf(u8, out.body, "image_generation.completed") == null); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, out.wire, "HTTP/1.1")); + var rejected: h.Fake = .{ .reject = error.InvalidRequest }; + const before = try h.ask(a, &rejected, try body(a, ",\"stream\":true"), null, false); + try t.expectEqual(@as(u16, 400), before.status); + try t.expect(std.mem.indexOf(u8, before.wire, "event-stream") == null); +} + +test "image progress: invalid engine steps, missing previews and over-limit previews fail without a final image" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]h.Fake{ .{ .invalid_step = true }, .{ .missing_preview = true }, .{ .oversized_preview = true }, .{ .early_stop = 2 } }) |initial| { + var fake = initial; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true,\"preview_interval\":1"), null, false); + try t.expectEqual(@as(u16, 200), out.status); + try t.expect(std.mem.indexOf(u8, out.body, "event: error\n") != null); + try t.expect(std.mem.indexOf(u8, out.body, "image_generation.completed") == null); + try t.expect(fake.finished.load(.acquire)); + } +} + +test "image progress: a full 200-step queue preserves every progress and preview while the reader catches up" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: h.Fake = .{ .gate = false, .inline_ = true }; + const out = try h.ask(a, &fake, "{\"model\":\"m\",\"prompt\":\"hi\",\"steps\":200,\"stream\":true,\"preview_interval\":1}", null, false); + try t.expectEqual(@as(u16, 200), out.status); + const list = try events(a, out.body); + try t.expectEqual(@as(usize, 401), list.len); + try t.expectEqual(@as(u32, 200), fake.preview_reads.load(.acquire)); + _ = try completed(list); +} + +test "image progress: a failed stream header still cancels and settles before freeing request storage" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: h.Fake = .{}; + const out = try h.ask(a, &fake, try body(a, ",\"stream\":true"), null, true); + try t.expectEqual(@as(u16, 0), out.status); + try t.expectEqual(@as(usize, 1), fake.cancels); + try t.expect(fake.finished.load(.acquire) and fake.steps_done.load(.acquire) <= 2); +} diff --git a/zig/src/server/images_sequence_progress_test.zig b/zig/src/server/images_sequence_progress_test.zig new file mode 100644 index 00000000000..d23dedd3df8 --- /dev/null +++ b/zig/src/server/images_sequence_progress_test.zig @@ -0,0 +1,101 @@ +//! The image count and streaming changes together, including a failure or disconnect after one complete picture. +const std = @import("std"); +const json = @import("json"); +const h = @import("image_progress_test_harness.zig"); +const frames = @import("images_progress_test.zig"); +const t = std.testing; +const seed: u64 = 9007199254740993; + +fn request(a: std.mem.Allocator, count: usize, chosen: u64, extra: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "{{\"model\":\"m\",\"prompt\":\"hi\",\"negative_prompt\":\"fog\",\"steps\":5,\"guidance\":2,\"size\":\"512x768\",\"n\":{d},\"seed\":{d}{s}}}", .{ count, chosen, extra }); +} + +test "image sequence progress: four streamed PNGs equal whole and solo requests with ordered seeds and steps" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var whole: h.Fake = .{}; + const plain = try h.ask(a, &whole, try request(a, 4, seed, ""), null, false); + try t.expectEqual(@as(u16, 200), plain.status); + const data = (try json.parse(a, plain.body)).ok.get("data").?.array; + try t.expectEqual(@as(usize, 4), data.len); + var streamed: h.Fake = .{}; + const out = try h.ask(a, &streamed, try request(a, 4, seed, ",\"stream\":true,\"preview_interval\":2"), null, false); + try t.expectEqual(@as(u16, 200), out.status); + const list = try frames.events(a, out.body); + try t.expectEqual(@as(usize, 32), list.len); + var index: usize = 0; + var step: i64 = 0; + var previews: usize = 0; + for (list) |event| { + try t.expectEqual(@as(i64, @intCast(index)), event.value.get("index").?.int64().?); + try t.expectEqual(@as(i64, @intCast(seed + index)), event.value.get("seed").?.int64().?); + if (std.mem.eql(u8, event.kind, "image_generation.progress")) { + step += 1; + try t.expectEqual(step, event.value.get("step").?.int64().?); + try t.expectEqual(@as(i64, 5), event.value.get("total_steps").?.int64().?); + } else if (std.mem.eql(u8, event.kind, "image_generation.partial_image")) { + previews += 1; + try t.expect(step == 2 or step == 4); + try t.expectEqual(step, event.value.get("step").?.int64().?); + } else { + try t.expectEqualStrings("image_generation.completed", event.kind); + try t.expectEqual(@as(i64, 5), step); + try t.expectEqualSlices(u8, try frames.decoded(a, data[index]), try frames.decoded(a, event.value)); + var solo: h.Fake = .{}; + const single = try h.ask(a, &solo, try request(a, 1, seed + index, ""), null, false); + try t.expectEqual(@as(u16, 200), single.status); + const item = (try json.parse(a, single.body)).ok.get("data").?.array[0]; + try t.expectEqualSlices(u8, try frames.decoded(a, item), try frames.decoded(a, event.value)); + index += 1; + step = 0; + } + } + try t.expectEqual(@as(usize, 4), index); + try t.expectEqual(@as(usize, 8), previews); + try t.expectEqual(@as(usize, 4), streamed.calls); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, out.wire, "HTTP/1.1")); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, out.body, "data: [DONE]")); + try t.expect(!streamed.gate_timeout.load(.acquire)); +} + +test "image sequence progress: second-picture refusal preserves only the first completed image and stops" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: h.Fake = .{ .reject = error.Busy, .reject_at = 2 }; + const out = try h.ask(a, &fake, try request(a, 4, seed, ",\"stream\":true"), null, false); + try t.expectEqual(@as(u16, 200), out.status); + try t.expectEqual(@as(usize, 2), fake.calls); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, out.wire, "HTTP/1.1")); + const list = try frames.events(a, out.body); + var complete: usize = 0; + for (list) |event| { + if (std.mem.eql(u8, event.kind, "image_generation.completed")) { + complete += 1; + try t.expectEqual(@as(i64, 0), event.value.get("index").?.int64().?); + } + } + try t.expectEqual(@as(usize, 1), complete); + try t.expect(std.mem.indexOf(u8, out.body, "the engine is busy") != null); + try t.expect(std.mem.endsWith(u8, out.body, "data: [DONE]\n\n")); +} + +test "image sequence progress: disconnect during picture two cancels at its next step and never submits three" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fake: h.Fake = .{}; + const out = try h.askAt(a, &fake, try request(a, 4, seed, ",\"stream\":true,\"preview_interval\":1"), 1, false, 1); + try t.expectEqual(@as(u16, 200), out.status); + try t.expectEqual(@as(usize, 2), fake.calls); + try t.expectEqual(@as(usize, 1), fake.cancels); + try t.expect(fake.finished.load(.acquire) and fake.steps_done.load(.acquire) <= 2); + const list = try frames.events(a, out.body); + var complete: usize = 0; + for (list) |event| if (std.mem.eql(u8, event.kind, "image_generation.completed")) { + complete += 1; + try t.expectEqual(@as(i64, 0), event.value.get("index").?.int64().?); + }; + try t.expectEqual(@as(usize, 1), complete); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index f4e14c53bf3..321ab5ba6e7 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -94,6 +94,8 @@ test { _ = @import("speech.zig"); _ = @import("images_generations.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("images_batch_test.zig"); // uses a socketpair test + if (comptime @import("builtin").os.tag != .windows) _ = @import("images_progress_test.zig"); // the same + if (comptime @import("builtin").os.tag != .windows) _ = @import("images_sequence_progress_test.zig"); // the same _ = @import("drama_cfg.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_cfg_test.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_stream_test.zig"); // over a Unix socket pair From 82a8c5590eb5bd0b86f180c61d68d16f095685d9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:46:58 +0000 Subject: [PATCH 09/89] changelog: #3245 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 883c91b495a..b05ebeca3d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Images: with `stream: true`, `POST /v1/images/generations` streams each denoising step's progress (`image_generation.progress`) and, with `preview_interval`, partial previews while the picture generates, then the PNG (#3245). + - DeepSeek-V4.1 on Metal: decode launches of 6 to 16 rows (draft verify windows, alone or with other streams' rows) run the dense FP8 projections on a simdgroup-matrix tile that splits K over simdgroups in the row kernel's own group tree, so every row's bits equal the row kernel's one row at a time; launches of 1 to 5 rows keep the row kernel. On the release weights two drafted streams decode 3.7 to 5.5% faster on an M5 Ultra and 3.6 to 5.4% faster on an M3 Ultra, other stream counts are level, and every token is unchanged; `time-dsv41-metal-synth` times the dispatch classes per row without a checkpoint (#2973, part of #2984). - Tools: add the heat-exchanger agent evaluation and its bounded Python execution helper (#3086). From 475df36ced239ceb8e97a77cfe76ff389f90a4ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:53:35 +0100 Subject: [PATCH 10/89] qwen3_5 cuda: a dense MLP's NVFP4 prompt gate, up and act in one lean pair launch, the same bytes prompt_lean gains a SwiGLU pair form: a 128 x 256 tile stages gate's two 64-column blocks and up's at the same features, each warp holds a feature's gate and up sums in one lane, and the epilogue rounds both to bf16 and takes tf_q35_mlp_act's steps. The two existing instances keep their SASS on sm_80/86/89/120/121 (renamed: int out kind, four trailing arguments). Qwen3.5 dense layers with NVFP4 gate and up take it for prompt rows past 16. --- docs/kernel-contract.md | 2 +- zig/kernels/cuda/prompt16.cu | 204 +------------- zig/kernels/cuda/prompt16_lean.cuh | 225 ++++++++++++++++ zig/src/core/contract/registry.zig | 3 +- zig/src/cuda/nvfp4.zig | 58 ++-- zig/src/families/qwen3_5/cuda_forward.zig | 7 +- zig/src/families/qwen3_5/cuda_modelopt.zig | 9 + zig/tests/cuda/contract_after.zig | 3 +- zig/tests/cuda/contract_prompt_swiglu.zig | 293 +++++++++++++++++++++ zig/tests/cuda/main.zig | 4 + 10 files changed, 595 insertions(+), 213 deletions(-) create mode 100644 zig/kernels/cuda/prompt16_lean.cuh create mode 100644 zig/tests/cuda/contract_prompt_swiglu.zig diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 05df1565500..3baf9193454 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -289,7 +289,7 @@ the once-rounded ones, each checked on its residual and its output, with four co bit-equal to them) and top-k, the latent top-k's decode form (bit-equal to `tf_super_topk`), the latent combine and shared add over bf16 share sums (bit-equal to `tf_super_combine` and `tf_super_moe_out` over the fp32 shares), the Mamba scan of a verify window (its host twin's bytes), qmm_group's cluster tile, lane_gemv and its split-K form (both -bit-equal to it), the split-K form segmented over projections of one input (bit-equal to `decode()` on each), prompt16's FP4 tile with bf16 and fp32 out, qmmf's FP4 tiles with fp32 out (K slices met in a +bit-equal to it), the split-K form segmented over projections of one input (bit-equal to `decode()` on each), prompt16's FP4 tile with bf16 and fp32 out and its gate/up SwiGLU pair (bit-equal to two lean products then `tf_q35_mlp_act`; controls: gate and up swapped, the gate's scale one fp32 ulp up), qmmf's FP4 tiles with fp32 out (K slices met in a cluster, fused, or by `reduce_kernel`), the checkpoint math's FP8 128-row prompt tiles (both slice meetings, bit-equal to the 64-row tiles) and NVFP4 experts: the decode-sized forms and the prompt tiles (up to down's NVFP4 rows, fp32 down and the down summing two width shares, each bit-equal to the kernels it replaces; sm_120 up), and the diff --git a/zig/kernels/cuda/prompt16.cu b/zig/kernels/cuda/prompt16.cu index b5ffc643d98..05413af9c7a 100644 --- a/zig/kernels/cuda/prompt16.cu +++ b/zig/kernels/cuda/prompt16.cu @@ -225,193 +225,7 @@ __device__ __forceinline__ void mbar_wait(uint64_t* b, uint32_t parity) { "r"(parity) : "memory"); } -template -struct LeanTile { - using T = Tile; - static constexpr int SMEM = T::SMEM + 2 * STAGES * 8; // the stages, then their full and empty barriers -}; - -// prompt_kernel's bits on a 128 x 256 tile: same fragments and mma chain over (g, kt); persistent, mbarrier ring -template -__global__ void __launch_bounds__(WM * WN * 32, 1) prompt_lean( - const __nv_bfloat16* __restrict__ x, const unsigned char* __restrict__ w, const uint8_t* __restrict__ bs, - float scale, void* __restrict__ out, int M, int N, int K, int npad, int ldx, int group) { - using T = Tile; - extern __shared__ __align__(128) unsigned char buf[]; - const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; - const int wm = warp / WN, wn = warp % WN; - const int KG = K / GS; - const int tiles = (M + BM - 1) / BM * ((N + BN - 1) / BN); - constexpr int TILE_BYTES = MODE == FP4 ? 64 * GS / 2 : 64 * GS; - constexpr int XC = BM * T::CHUNKS, WC = T::W / 16, SC = T::S / 16; - constexpr int XN = (XC + T::THREADS - 1) / T::THREADS, WNC = (WC + T::THREADS - 1) / T::THREADS; - constexpr int SN = SC > 0 ? (SC + T::THREADS - 1) / T::THREADS : 1; - constexpr int PER = SC > 0 ? T::S / (BN / 64) : 16; - const __nv_bfloat16* xs[XN]; - uint32_t xd[XN]; - bool xin[XN], xon[XN]; - const unsigned char* wsrc[WNC]; - bool win[WNC]; - const uint8_t* ssrc[SN]; - bool sin[SN]; - auto plan = [&](int tile) { // the copies of tile's groups - const int2 at = tile_of(tile, M, N, BM, BN, group); -#pragma unroll - for (int i = 0; i < XN; ++i) { - const int c = tid + i * T::THREADS, r = min(c / T::CHUNKS, BM - 1), ch = c % T::CHUNKS; - xs[i] = x + static_cast(min(at.x + r, M - 1)) * ldx + ch * 8; - xd[i] = r * T::ROW + swz(r, ch) * 16; - xin[i] = at.x + r < M; - xon[i] = c < XC; - } -#pragma unroll - for (int i = 0; i < WNC; ++i) { - const int c = tid + i * T::THREADS, t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16); - wsrc[i] = w + static_cast(at.y / 64 + t) * KG * TILE_BYTES + off * 16; - win[i] = c < WC && at.y + t * 64 < npad; - } -#pragma unroll - for (int i = 0; i < SN; ++i) { - const int c = tid + i * T::THREADS, t = c / (PER / 16), off = c % (PER / 16); - ssrc[i] = bs + static_cast(at.y / 64 + t) * KG * PER + off * 16; - sin[i] = c < SC && at.y + t * 64 < npad; - } - }; - uint64_t* full = reinterpret_cast(buf + STAGES * T::STAGE); - uint64_t* empty = full + STAGES; - auto stage = [&](int s) { return buf + s * T::STAGE; }; - // the copy stream: its count of issued stages, and the tile and group it copies next - uint32_t issued = 0; - int lt = blockIdx.x, lg = 0; - auto load = [&]() { - const int s = issued % STAGES; - if (issued >= STAGES) mbar_wait(&empty[s], (issued / STAGES - 1) & 1); - unsigned char* p = stage(s); -#pragma unroll - for (int i = 0; i < XN; ++i) - if (xon[i]) cp16z(p + xd[i], xs[i] + lg * GS, xin[i]); -#pragma unroll - for (int i = 0; i < WNC; ++i) - if (win[i]) cp16(p + T::X + (tid + i * T::THREADS) * 16, wsrc[i] + static_cast(lg) * TILE_BYTES); - if constexpr (SC > 0) { -#pragma unroll - for (int i = 0; i < SN; ++i) - if (sin[i]) cp16(p + T::X + T::W + (tid + i * T::THREADS) * 16, ssrc[i] + static_cast(lg) * PER); - } - mbar_copies(&full[s]); - ++issued; - if (++lg == KG) { - lg = 0; - lt += gridDim.x; - if (lt < tiles) plan(lt); - } - }; - - if (blockIdx.x >= tiles) return; - if (tid == 0) - for (int s = 0; s < STAGES; ++s) { - mbar_init(&full[s], T::THREADS); - mbar_init(&empty[s], T::THREADS / 32); - } - __syncthreads(); - plan(lt); - for (int s = 0; s < STAGES - 1 && lt < tiles; ++s) load(); - uint32_t used = 0; - for (int tile = blockIdx.x; tile < tiles; tile += gridDim.x) { - const int2 at = tile_of(tile, M, N, BM, BN, group); - const int m0 = at.x, n0 = at.y; - float acc[T::MT][T::NT][4]; -#pragma unroll - for (int i = 0; i < T::MT; ++i) -#pragma unroll - for (int j = 0; j < T::NT; ++j) -#pragma unroll - for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f; - for (int g = 0; g < KG; ++g, ++used) { - mbar_wait(&full[used % STAGES], (used / STAGES) & 1); - const unsigned char* p = stage(used % STAGES); - const unsigned char* pw = p + T::X; - const uint8_t* ps = p + T::X + T::W; - uint4 wq[T::NT]; - uint32_t sv[T::NT][4]; -#pragma unroll - for (int j = 0; j < T::NT; ++j) { - const int jj = wn * T::NT + j; - const int col = (jj & 7) * 8 + (lane >> 2); - if constexpr (MODE == FP4) { - const uint2 u = reinterpret_cast(pw)[jj * 32 + lane]; - wq[j] = make_uint4(u.x, u.y, 0u, 0u); - const uint32_t b4 = *reinterpret_cast(ps + (jj >> 3) * 256 + col * 4); - // fp8pair is lane-wise: two blocks a call, each half then copied to both (sv as prompt_kernel's) -#if TF_FP_NATIVE - const uint32_t s01 = tf_common::e4m3x2(b4), s23 = tf_common::e4m3x2(b4 >> 16); -#else - const uint32_t s01 = tf_common::fp8pair_unit(b4, 0x7B807B80u), s23 = tf_common::fp8pair_unit(b4 >> 16, 0x7B807B80u); -#endif - sv[j][0] = prmt(s01, 0u, 0x1010u); - sv[j][1] = prmt(s01, 0u, 0x3232u); - sv[j][2] = prmt(s23, 0u, 0x1010u); - sv[j][3] = prmt(s23, 0u, 0x3232u); - } else { - wq[j] = reinterpret_cast(pw)[jj * 32 + lane]; - } - } -#pragma unroll - for (int kt = 0; kt < GS / 16; ++kt) { - uint32_t a[T::MT][4]; -#pragma unroll - for (int i = 0; i < T::MT; ++i) { - const int r = wm * (BM / WM) + i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8; - const int ch = kt * 2 + (lane >> 4); - ldmatrix4(a[i], p + r * T::ROW + swz(r, ch) * 16); - } -#pragma unroll - for (int j = 0; j < T::NT; ++j) { - uint32_t b0, b1; - if constexpr (MODE == FP4) { - e2m1_pairs(kt < 2 ? wq[j].x : wq[j].y, kt & 1, b0, b1); - b0 = mul2(b0, sv[j][kt]); - b1 = mul2(b1, sv[j][kt]); - } else { - const uint32_t word = comp(wq[j], kt); - b0 = tf_common::fp8pair_unit(word & 0xFFFFu, 0x7B807B80u); - b1 = tf_common::fp8pair_unit(word >> 16, 0x7B807B80u); - } -#pragma unroll - for (int i = 0; i < T::MT; ++i) mma(acc[i][j], a[i], b0, b1); - } - } - __syncwarp(); - if (lane == 0) mbar_arrive(&empty[used % STAGES]); - if (lt < tiles) load(); - } -#pragma unroll - for (int i = 0; i < T::MT; ++i) -#pragma unroll - for (int j = 0; j < T::NT; ++j) { - const int col = n0 + wn * (BN / WN) + j * 8 + (lane & 3) * 2; -#pragma unroll - for (int h = 0; h < 2; ++h) { - const int row = m0 + wm * (BM / WM) + i * 16 + (lane >> 2) + h * 8; - if (row >= M) continue; - const float v0 = acc[i][j][2 * h] * scale, v1 = acc[i][j][2 * h + 1] * scale; - if (F32) { - float* dst = reinterpret_cast(out) + static_cast(row) * N + col; - if (col < N) dst[0] = v0; - if (col + 1 < N) dst[1] = v1; - } else { - __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(out) + static_cast(row) * N + col; - if (col + 1 < N && (N & 1) == 0) - *reinterpret_cast<__nv_bfloat162*>(dst) = __floats2bfloat162_rn(v0, v1); - else { - if (col < N) dst[0] = __float2bfloat16_rn(v0); - if (col + 1 < N) dst[1] = __float2bfloat16_rn(v1); - } - } - } - } - } -} +#include "prompt16_lean.cuh" // The instance the Zig launcher loads by name (PROMPT_TILE 4 in linear.py). template __global__ void prompt_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, int, int, int, int, int, int); @@ -420,12 +234,16 @@ template __global__ void prompt_kernel( void* __restrict__, int, int, int, int, int, int); template __global__ void prompt_kernel(const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, void* __restrict__, int, int, int, int, int, int); // The lean tile prompt() serves FP4 on: 128 x 256, eight warps of 128 x 32, three stages (bits equal to the above). -template __global__ void prompt_lean( - const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, - void* __restrict__, int, int, int, int, int, int); -template __global__ void prompt_lean( - const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, - void* __restrict__, int, int, int, int, int, int); +#define TF_LEAN_ARGS \ + const __nv_bfloat16* __restrict__, const unsigned char* __restrict__, const uint8_t* __restrict__, float, \ + void* __restrict__, int, int, int, int, int, int, const unsigned char* __restrict__, const uint8_t* __restrict__, \ + float, const int* __restrict__ +template __global__ void prompt_lean(TF_LEAN_ARGS); +template __global__ void prompt_lean(TF_LEAN_ARGS); +// The gate/up pair: two lean products then tf_q35_mlp_act's bytes in one launch (tf_prompt_lean_swiglu in nvfp4.zig). +template __global__ void prompt_lean(TF_LEAN_ARGS); +#undef TF_LEAN_ARGS + // BF16 prompt rows on qmmf's BF16 words with qmmf_kernel's sums (K slices from zero, added in order): the lane's bits. template diff --git a/zig/kernels/cuda/prompt16_lean.cuh b/zig/kernels/cuda/prompt16_lean.cuh new file mode 100644 index 00000000000..e66f3c23e49 --- /dev/null +++ b/zig/kernels/cuda/prompt16_lean.cuh @@ -0,0 +1,225 @@ +// prompt16.cu's lean tile (text included inside namespace tf_prompt16): prompt_lean and its gate/up SwiGLU form. +#pragma once + +template +struct LeanTile { + using T = Tile; + static constexpr int SMEM = T::SMEM + 2 * STAGES * 8; // the stages, then their full and empty barriers +}; + +// prompt_lean's outputs: the bf16 or fp32 product, or bf16(silu(gate) * up) of a gate/up pair (the act kernel's bits) +enum LeanOut : int { LEAN_BF16 = 0, LEAN_F32 = 1, LEAN_SWIGLU = 2 }; + +// prompt_kernel's bits on a 128 x 256 tile: same fragments and mma chain over (g, kt); persistent, mbarrier ring. +template +__global__ void __launch_bounds__(WM * WN * 32, 1) prompt_lean( + const __nv_bfloat16* __restrict__ x, const unsigned char* __restrict__ w, const uint8_t* __restrict__ bs, + float scale, void* __restrict__ out, int M, int N, int K, int npad, int ldx, int group, + const unsigned char* __restrict__ w2, const uint8_t* __restrict__ bs2, float scale2, + const int* __restrict__ P) { + using T = Tile; + constexpr bool F32 = OUT == LEAN_F32, PAIR = OUT == LEAN_SWIGLU; + constexpr int TN = PAIR ? BN / 2 : BN; // output columns a tile: a pair's 128 features (gate's and up's blocks) + static_assert(!PAIR || (MODE == FP4 && BN == 256 && WN == 8), "the pair tile is the FP4 128 x 256 lean tile"); + extern __shared__ __align__(128) unsigned char buf[]; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int wm = warp / WN, wn = warp % WN; + const int KG = K / GS; + const int tiles = (M + BM - 1) / BM * ((N + TN - 1) / TN); + constexpr int TILE_BYTES = MODE == FP4 ? 64 * GS / 2 : 64 * GS; + constexpr int XC = BM * T::CHUNKS, WC = T::W / 16, SC = T::S / 16; + constexpr int XN = (XC + T::THREADS - 1) / T::THREADS, WNC = (WC + T::THREADS - 1) / T::THREADS; + constexpr int SN = SC > 0 ? (SC + T::THREADS - 1) / T::THREADS : 1; + constexpr int PER = SC > 0 ? T::S / (BN / 64) : 16; + const __nv_bfloat16* xs[XN]; + uint32_t xd[XN]; + bool xin[XN], xon[XN]; + const unsigned char* wsrc[WNC]; + bool win[WNC]; + const uint8_t* ssrc[SN]; + bool sin[SN]; + auto plan = [&](int tile) { // the copies of tile's groups + const int2 at = tile_of(tile, M, N, BM, TN, group); +#pragma unroll + for (int i = 0; i < XN; ++i) { + const int c = tid + i * T::THREADS, r = min(c / T::CHUNKS, BM - 1), ch = c % T::CHUNKS; + xs[i] = x + static_cast(min(at.x + r, M - 1)) * ldx + ch * 8; + xd[i] = r * T::ROW + swz(r, ch) * 16; + xin[i] = at.x + r < M; + xon[i] = c < XC; + } +#pragma unroll + for (int i = 0; i < WNC; ++i) { + const int c = tid + i * T::THREADS, t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16); + const int tb = PAIR ? (t & 1) : t; // the pair's blocks 0, 1 are gate's, 2, 3 up's, at the same features + wsrc[i] = (PAIR && t >= 2 ? w2 : w) + static_cast(at.y / 64 + tb) * KG * TILE_BYTES + off * 16; + win[i] = c < WC && at.y + tb * 64 < npad; + } +#pragma unroll + for (int i = 0; i < SN; ++i) { + const int c = tid + i * T::THREADS, t = c / (PER / 16), off = c % (PER / 16); + const int tb = PAIR ? (t & 1) : t; + ssrc[i] = (PAIR && t >= 2 ? bs2 : bs) + static_cast(at.y / 64 + tb) * KG * PER + off * 16; + sin[i] = c < SC && at.y + tb * 64 < npad; + } + }; + uint64_t* full = reinterpret_cast(buf + STAGES * T::STAGE); + uint64_t* empty = full + STAGES; + auto stage = [&](int s) { return buf + s * T::STAGE; }; + // the copy stream: its count of issued stages, and the tile and group it copies next + uint32_t issued = 0; + int lt = blockIdx.x, lg = 0; + auto load = [&]() { + const int s = issued % STAGES; + if (issued >= STAGES) mbar_wait(&empty[s], (issued / STAGES - 1) & 1); + unsigned char* p = stage(s); +#pragma unroll + for (int i = 0; i < XN; ++i) + if (xon[i]) cp16z(p + xd[i], xs[i] + lg * GS, xin[i]); +#pragma unroll + for (int i = 0; i < WNC; ++i) + if (win[i]) cp16(p + T::X + (tid + i * T::THREADS) * 16, wsrc[i] + static_cast(lg) * TILE_BYTES); + if constexpr (SC > 0) { +#pragma unroll + for (int i = 0; i < SN; ++i) + if (sin[i]) cp16(p + T::X + T::W + (tid + i * T::THREADS) * 16, ssrc[i] + static_cast(lg) * PER); + } + mbar_copies(&full[s]); + ++issued; + if (++lg == KG) { + lg = 0; + lt += gridDim.x; + if (lt < tiles) plan(lt); + } + }; + + if (blockIdx.x >= tiles) return; + if (tid == 0) + for (int s = 0; s < STAGES; ++s) { + mbar_init(&full[s], T::THREADS); + mbar_init(&empty[s], T::THREADS / 32); + } + __syncthreads(); + plan(lt); + for (int s = 0; s < STAGES - 1 && lt < tiles; ++s) load(); + uint32_t used = 0; + for (int tile = blockIdx.x; tile < tiles; tile += gridDim.x) { + const int2 at = tile_of(tile, M, N, BM, TN, group); + const int m0 = at.x, n0 = at.y; + float acc[T::MT][T::NT][4]; +#pragma unroll + for (int i = 0; i < T::MT; ++i) +#pragma unroll + for (int j = 0; j < T::NT; ++j) +#pragma unroll + for (int e = 0; e < 4; ++e) acc[i][j][e] = 0.0f; + for (int g = 0; g < KG; ++g, ++used) { + mbar_wait(&full[used % STAGES], (used / STAGES) & 1); + const unsigned char* p = stage(used % STAGES); + const unsigned char* pw = p + T::X; + const uint8_t* ps = p + T::X + T::W; + uint4 wq[T::NT]; + uint32_t sv[T::NT][4]; +#pragma unroll + for (int j = 0; j < T::NT; ++j) { + // a pair's warp: gate subtiles 2wn, 2wn + 1, up's 16 + 2wn, 17 + 2wn (one feature's sums in one lane) + const int jj = PAIR ? (j >> 1) * 16 + 2 * wn + (j & 1) : wn * T::NT + j; + const int col = (jj & 7) * 8 + (lane >> 2); + if constexpr (MODE == FP4) { + const uint2 u = reinterpret_cast(pw)[jj * 32 + lane]; + wq[j] = make_uint4(u.x, u.y, 0u, 0u); + const uint32_t b4 = *reinterpret_cast(ps + (jj >> 3) * 256 + col * 4); + // fp8pair is lane-wise: two blocks a call, each half then copied to both (sv as prompt_kernel's) +#if TF_FP_NATIVE + const uint32_t s01 = tf_common::e4m3x2(b4), s23 = tf_common::e4m3x2(b4 >> 16); +#else + const uint32_t s01 = tf_common::fp8pair_unit(b4, 0x7B807B80u), s23 = tf_common::fp8pair_unit(b4 >> 16, 0x7B807B80u); +#endif + sv[j][0] = prmt(s01, 0u, 0x1010u); + sv[j][1] = prmt(s01, 0u, 0x3232u); + sv[j][2] = prmt(s23, 0u, 0x1010u); + sv[j][3] = prmt(s23, 0u, 0x3232u); + } else { + wq[j] = reinterpret_cast(pw)[jj * 32 + lane]; + } + } +#pragma unroll + for (int kt = 0; kt < GS / 16; ++kt) { + uint32_t a[T::MT][4]; +#pragma unroll + for (int i = 0; i < T::MT; ++i) { + const int r = wm * (BM / WM) + i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8; + const int ch = kt * 2 + (lane >> 4); + ldmatrix4(a[i], p + r * T::ROW + swz(r, ch) * 16); + } +#pragma unroll + for (int j = 0; j < T::NT; ++j) { + uint32_t b0, b1; + if constexpr (MODE == FP4) { + e2m1_pairs(kt < 2 ? wq[j].x : wq[j].y, kt & 1, b0, b1); + b0 = mul2(b0, sv[j][kt]); + b1 = mul2(b1, sv[j][kt]); + } else { + const uint32_t word = comp(wq[j], kt); + b0 = tf_common::fp8pair_unit(word & 0xFFFFu, 0x7B807B80u); + b1 = tf_common::fp8pair_unit(word >> 16, 0x7B807B80u); + } +#pragma unroll + for (int i = 0; i < T::MT; ++i) mma(acc[i][j], a[i], b0, b1); + } + } + __syncwarp(); + if (lane == 0) mbar_arrive(&empty[used % STAGES]); + if (lt < tiles) load(); + } + if constexpr (PAIR) { + const int rows = P != nullptr ? P[2] : M; // tf_q35_mlp_act's rows: the device count when there is one +#pragma unroll + for (int i = 0; i < T::MT; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int col = n0 + wn * 16 + j * 8 + (lane & 3) * 2; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int row = m0 + wm * (BM / WM) + i * 16 + (lane >> 2) + h * 8; + if (row >= rows) continue; + // the separate launches' bf16 gate and up, then tf_q35_mlp_act's float steps and rounding + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(out) + static_cast(row) * N + col; +#pragma unroll + for (int e = 0; e < 2; ++e) { + const float g = acc[i][j][2 * h + e] * scale, u = acc[i][j + 2][2 * h + e] * scale2; + const float gf = __bfloat162float(__float2bfloat16_rn(g)); + const float uf = __bfloat162float(__float2bfloat16_rn(u)); + if (col + e < N) dst[e] = __float2bfloat16_rn(gf / (1.0f + expf(-gf)) * uf); + } + } + } + } else { +#pragma unroll + for (int i = 0; i < T::MT; ++i) +#pragma unroll + for (int j = 0; j < T::NT; ++j) { + const int col = n0 + wn * (BN / WN) + j * 8 + (lane & 3) * 2; +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int row = m0 + wm * (BM / WM) + i * 16 + (lane >> 2) + h * 8; + if (row >= M) continue; + const float v0 = acc[i][j][2 * h] * scale, v1 = acc[i][j][2 * h + 1] * scale; + if (F32) { + float* dst = reinterpret_cast(out) + static_cast(row) * N + col; + if (col < N) dst[0] = v0; + if (col + 1 < N) dst[1] = v1; + } else { + __nv_bfloat16* dst = reinterpret_cast<__nv_bfloat16*>(out) + static_cast(row) * N + col; + if (col + 1 < N && (N & 1) == 0) + *reinterpret_cast<__nv_bfloat162*>(dst) = __floats2bfloat162_rn(v0, v1); + else { + if (col < N) dst[0] = __float2bfloat16_rn(v0); + if (col + 1 < N) dst[1] = __float2bfloat16_rn(v1); + } + } + } + } + } + } +} diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 146a3e3d19b..7923fd41617 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -21,7 +21,7 @@ pub const none: [limits.sms.len]U = @splat(.{ .regs = 0, .static = 0 }); const group_symbol = "_ZN12tf_qmm_group12group_kernelILi64ELi16ELi64ELi1ELi4ELi8ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii"; const gemv_symbol = "_ZN12tf_lane_gemv11gemv_kernelILi64ELi64ELi8EEEvPK13__nv_bfloat16PKfNS_4PartEiii"; const prompt_symbol = "_ZN11tf_prompt1613prompt_kernelILi{d}ELi128ELi128ELi2ELi2ELi2ELb{d}EEEvPK13__nv_bfloat16PKhS5_fPviiiiii"; -const lean_symbol = "_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELb{d}EEEvPK13__nv_bfloat16PKhS5_fPviiiiii"; +const lean_symbol = "_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELi{d}EEEvPK13__nv_bfloat16PKhS5_fPviiiiiiS5_S5_fPKi"; const qmmf_f32_symbol = "_ZN7tf_qmmf11qmmf_kernelILi0ELi{d}ELi64ELi1ELi4ELi4ELb1ELb{d}ELb{d}EEEvPK13__nv_bfloat16PKhS5_fPvPfiiiiiii"; const vision80_symbol = "_ZN20tf_prefill_attention13vision_kernelILi80ELi8EEEvPK13__nv_bfloat16PS1_iif"; const full72_symbol = "_ZN20tf_prefill_attention11full_kernelILi72ELi8ELi8EEEvPK13__nv_bfloat16PS1_iif"; @@ -48,6 +48,7 @@ pub const cuda = @import("flashnext_cuda_records.zig").cuda ++ [_]CudaRecord{ .{ .launch = .{ .name = "prompt16 FP4 fp32 out", .symbol = std.fmt.comptimePrint(prompt_symbol, .{ 0, 1 }), .image = "prompt16", .threads = 128, .dynamic = 41984 }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "prompt16 FP4 lean", .symbol = std.fmt.comptimePrint(lean_symbol, .{0}), .image = "prompt16", .threads = 256, .dynamic = 76848, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 253, .static = 0, .bound = 256 }, .{ .regs = 253, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "prompt16 FP4 lean fp32 out", .symbol = std.fmt.comptimePrint(lean_symbol, .{1}), .image = "prompt16", .threads = 256, .dynamic = 76848, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 251, .static = 0, .bound = 256 }, .{ .regs = 251, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "prompt16 FP4 lean SwiGLU pair", .symbol = std.fmt.comptimePrint(lean_symbol, .{2}), .image = "prompt16", .threads = 256, .dynamic = 76848, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 255, .static = 0, .bound = 256 }, .{ .regs = 247, .static = 0, .bound = 256 }, .{ .regs = 247, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "qmmf FP4 fp32 out 16-row tile", .symbol = std.fmt.comptimePrint(qmmf_f32_symbol, .{ 16, 0, 0 }), .image = "qmmf", .threads = 128, .dynamic = 17408 }, .usage = .{ .{ .regs = 88, .static = 0, .bound = 128 }, .{ .regs = 88, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "qmmf FP4 fp32 out 16-row tile, cluster of 8", .symbol = std.fmt.comptimePrint(qmmf_f32_symbol, .{ 16, 1, 0 }), .image = "qmmf", .threads = 128, .dynamic = 17408, .cluster = 8, .min_sm = 90 }, .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 78, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 }, .{ .regs = 48, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "qmmf FP4 fp32 out 32-row tile", .symbol = std.fmt.comptimePrint(qmmf_f32_symbol, .{ 32, 0, 0 }), .image = "qmmf", .threads = 128, .dynamic = 25600 }, .usage = .{ .{ .regs = 106, .static = 0, .bound = 128 }, .{ .regs = 106, .static = 0, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 64, .static = 0, .bound = 128 } } }, diff --git a/zig/src/cuda/nvfp4.zig b/zig/src/cuda/nvfp4.zig index 0cc13921c78..13cf22e4d30 100644 --- a/zig/src/cuda/nvfp4.zig +++ b/zig/src/cuda/nvfp4.zig @@ -70,6 +70,7 @@ pub const Prompt = struct { bf16_f32: Function, lean: Function, // prompt_lean FP4, bf16 out lean_f32: Function, // and fp32 out + lean_swiglu: Function, // a gate/up pair on the lean tile, bf16(silu(gate) * up) out sms: usize, // the current device's multiprocessors: prompt_lean's blocks (one a multiprocessor, tiles in turn) pub const Tile = enum { lean, classic }; @@ -95,9 +96,14 @@ pub const Prompt = struct { const lean_bn = 256; const lean_threads = 256; const lean_stages = 3; - const lean_name = "_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELb{d}" ++ - "EEEvPK13__nv_bfloat16PKhS5_fPviiiiii"; - pub const lean_symbols = [2][:0]const u8{ std.fmt.comptimePrint(lean_name, .{0}), std.fmt.comptimePrint(lean_name, .{1}) }; + const lean_name = "_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELi{d}" ++ + "EEEvPK13__nv_bfloat16PKhS5_fPviiiiiiS5_S5_fPKi"; + /// prompt_lean's LeanOut instances: bf16, fp32, and the gate/up pair's SwiGLU (prompt16_lean.cuh). + pub const lean_symbols = [3][:0]const u8{ + std.fmt.comptimePrint(lean_name, .{0}), + std.fmt.comptimePrint(lean_name, .{1}), + std.fmt.comptimePrint(lean_name, .{2}), + }; /// prompt16.cu LeanTile::SMEM: three stages, then a full and an empty barrier each. pub fn leanSharedBytes() u32 { @@ -130,11 +136,13 @@ pub const Prompt = struct { try lean.allowDynamicShared(leanSharedBytes()); const lean_f32 = try mod.function(lean_symbols[1]); try lean_f32.allowDynamicShared(leanSharedBytes()); + const lean_swiglu = try mod.function(lean_symbols[2]); + try lean_swiglu.allowDynamicShared(leanSharedBytes()); var dev: abi.Device = 0; try d.check(d.api.cuCtxGetDevice(&dev), "cuCtxGetDevice"); var sms: c_int = 0; try d.check(d.api.cuDeviceGetAttribute(&sms, .multiprocessor_count, dev), "cuDeviceGetAttribute"); - return .{ .mod = mod, .fp4 = fp4, .fp8 = fp8, .fp4_f32 = fp4_f32, .bf16 = bf16, .bf16_f32 = bf16_f32, .lean = lean, .lean_f32 = lean_f32, .sms = @intCast(@max(sms, 1)) }; + return .{ .mod = mod, .fp4 = fp4, .fp8 = fp8, .fp4_f32 = fp4_f32, .bf16 = bf16, .bf16_f32 = bf16_f32, .lean = lean, .lean_f32 = lean_f32, .lean_swiglu = lean_swiglu, .sms = @intCast(@max(sms, 1)) }; } pub fn unload(p: *Prompt) void { @@ -154,24 +162,36 @@ pub const Prompt = struct { /// matmulOut() on a chosen FP4 tile (FP8 has the classic one only); both write the same bits. pub fn matmulTile(p: Prompt, s: Stream, x: u64, ldx: usize, m: usize, w: qmmf.Weight, y: u64, out: qmmf.Out, tile: Tile) !void { - if (w.mode == .fp4 and tile == .lean) return run(s, x, ldx, m, w, y, if (out == .f32) p.lean_f32 else p.lean, .{ - .bm = lean_bm, - .bn = lean_bn, - .threads = lean_threads, - .shared = leanSharedBytes(), - .blocks = p.sms, - }); + if (w.mode == .fp4 and tile == .lean) return run(s, x, ldx, m, w, y, if (out == .f32) p.lean_f32 else p.lean, p.leanShape(lean_bn), null); const f = switch (w.mode) { .fp4 => if (out == .f32) p.fp4_f32 else p.fp4, .fp8 => if (out == .f32) return error.EpilogueNotBuilt else p.fp8, else => return error.FormatMismatch, }; - return run(s, x, ldx, m, w, y, f, .{ .bm = bm, .bn = bn, .threads = threads, .shared = sharedBytes(w.mode) }); + return run(s, x, ldx, m, w, y, f, .{ .bm = bm, .bn = bn, .threads = threads, .shared = sharedBytes(w.mode) }, null); + } + + /// y [m, n] = bf16(silu(gate) * up) in one lean launch: two matmulTile()s then tf_q35_mlp_act's bytes (`rows`: P). + pub fn swiglu(p: Prompt, s: Stream, x: u64, ldx: usize, m: usize, gate: qmmf.Weight, up: qmmf.Weight, y: u64, rows: u64) !void { + if (!pairs(gate, up)) return error.FormatMismatch; + return run(s, x, ldx, m, gate, y, p.lean_swiglu, p.leanShape(lean_bn / 2), .{ .w = up, .rows = rows }); + } + + /// Whether swiglu() takes this gate and up: both FP4 of one shape, whole 128-feature tiles. + pub fn pairs(gate: qmmf.Weight, up: qmmf.Weight) bool { + return gate.mode == .fp4 and up.mode == .fp4 and gate.n == up.n and gate.k == up.k and gate.npad == up.npad and + gate.n % (lean_bn / 2) == 0; + } + + fn leanShape(p: Prompt, columns: usize) Shape { + return .{ .bm = lean_bm, .bn = columns, .threads = lean_threads, .shared = leanSharedBytes(), .blocks = p.sms, .lean = true }; } - const Shape = struct { bm: usize, bn: usize, threads: u32, shared: u32, blocks: usize = std.math.maxInt(usize) }; + const Shape = struct { bm: usize, bn: usize, threads: u32, shared: u32, blocks: usize = std.math.maxInt(usize), lean: bool = false }; + /// The lean pair's second weight and the device row count (prompt_lean's trailing arguments). + const Pair = struct { w: qmmf.Weight, rows: u64 }; - fn run(s: Stream, x: u64, ldx: usize, m: usize, w: qmmf.Weight, y: u64, f: Function, t: Shape) !void { + fn run(s: Stream, x: u64, ldx: usize, m: usize, w: qmmf.Weight, y: u64, f: Function, t: Shape, pair: ?Pair) !void { const rows_t = (m + t.bm - 1) / t.bm; const band = @max(1, @min(rows_t, (12 << 20) / (t.bm * w.k * 2))); var args: launch_.Args = .{}; @@ -186,6 +206,13 @@ pub const Prompt = struct { args.add(@as(i32, @intCast(w.npad))); args.add(@as(i32, @intCast(if (m == 1) w.k else ldx))); args.add(@as(i32, @intCast(band))); + if (t.lean) { // prompt_lean's trailing arguments: the pair's up weight and row count, zeros for one product + const two: Pair = pair orelse .{ .w = .{ .mode = .fp4, .codes = 0, .scales = 0, .scale = 0, .n = 0, .k = 0, .npad = 0 }, .rows = 0 }; + args.add(two.w.codes); + args.add(two.w.scales); + args.add(two.w.scale); + args.add(two.rows); + } try launch_.launch(f, .{ .grid = .{ .x = @intCast(@min(t.blocks, rows_t * ((w.n + t.bn - 1) / t.bn))), .y = 1, .z = 1 }, .block = .{ .x = t.threads, .y = 1, .z = 1 }, @@ -220,7 +247,8 @@ pub const Prompt = struct { test "the prompt tile's shared bytes and instance names" { try std.testing.expectEqual(@as(u32, 41984), Prompt.sharedBytes(.fp4)); try std.testing.expectEqual(@as(u32, 76848), Prompt.leanSharedBytes()); // 3 x (16384 + 8192 + 1024) + 48 - try std.testing.expectEqualStrings("_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELb0EEEvPK13__nv_bfloat16PKhS5_fPviiiiii", Prompt.lean_symbols[0]); + const lean = "_ZN11tf_prompt1611prompt_leanILi0ELi128ELi256ELi1ELi8ELi3ELi2EEEvPK13__nv_bfloat16PKhS5_fPviiiiiiS5_S5_fPKi"; + try std.testing.expectEqualStrings(lean, Prompt.lean_symbols[2]); try std.testing.expectEqual(@as(u32, 49152), Prompt.sharedBytes(.fp8)); // 2 x (16384 + 8192): no scale tile try std.testing.expectEqualStrings("_ZN11tf_prompt1613prompt_kernelILi0ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKhS5_fPviiiiii", Prompt.symbols[0]); try std.testing.expectEqualStrings( diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 21742b846a0..1730be80f1f 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const sig = @import("cuda_signatures.zig"); const hooks = @import("cuda_learn_hooks.zig"); const geometry = @import("cuda_geometry.zig"); +const modelopt = @import("cuda_modelopt.zig"); const head_dim = geometry.head_dim; const max_chunks = 64; /// Prompt experts keep the shipped arithmetic boundary, independently of verification capacity. @@ -120,7 +121,9 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const rp: u64 = if (tail) 0 else t_params; switch (l.mlp) { .dense => |m| { - if (m.gate == .x3) { + // NVFP4 prompt rows: gate, up and the act in one lean pair launch, the same act bytes + const paired = e.learning == null and sums == 0 and try modelopt.swiglu(e, m.gate, m.up, x0, e.act, rows, prompt, rp); + if (paired) {} else if (m.gate == .x3) { try e.projMany(&.{ m.gate, m.up }, x0, &.{ e.gate, e.up }, rows, prompt); // one EXL3 group launch } else if (e.affine.pdl and !prompt and e.learning == null and m.gate == .a4 and m.up == .a4) { try e.projMany(&.{ m.gate, m.up }, e.x, &.{ e.gate, e.up }, total, false); @@ -131,7 +134,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { if (e.learning) |k| try k.mlp(i, e.gate, e.up, total); const n: c_longlong = @intCast(rows * g.intermediate); const act_args = .{ e.gate, e.up, e.act, n, rp, @as(c_int, @intCast(g.intermediate)), sums }; - try e.run(e.fns.mlp_act, .{ (rows * g.intermediate + 1023) / 1024, 1, 1 }, .{ 256, 1, 1 }, act_args); + if (!paired) try e.run(e.fns.mlp_act, .{ (rows * g.intermediate + 1023) / 1024, 1, 1 }, .{ 256, 1, 1 }, act_args); try e.projAgain(m.down, e.act, r0, rows, prompt); if (e.mlp) |k| try k.f(k.ctx, i, e.x, e.r, total, e.taught) else try e.pockets.add(e.stream, i, e.x, e.r, total, e.taught); }, diff --git a/zig/src/families/qwen3_5/cuda_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index 34317f46798..0c515c13160 100644 --- a/zig/src/families/qwen3_5/cuda_modelopt.zig +++ b/zig/src/families/qwen3_5/cuda_modelopt.zig @@ -317,6 +317,15 @@ pub fn project(e: *Engine, w: Weight, x: u64, out: u64, rows: usize, prompt: boo return l.decode(e.stream, w, in, out, rows); } +/// NVFP4 prompt gate and up in one lean pair launch into `act`, the bytes of main's path; false: not taken. +pub fn swiglu(e: *Engine, gate: Proj, up: Proj, x: u64, act: u64, rows: usize, prompt: bool, rows_at: u64) !bool { + if (!prompt or rows <= 16 or gate != .ql or up != .ql or gate.ql != .nvfp4 or up.ql != .nvfp4) return false; + const k = if (e.mo) |*m| m else return false; + if (!cuda.nvfp4.Prompt.pairs(gate.ql.nvfp4, up.ql.nvfp4)) return false; + try k.prompt.swiglu(e.stream, x, gate.ql.nvfp4.k, rows, gate.ql.nvfp4, up.ql.nvfp4, act, rows_at); + return true; +} + /// An fp32 tensor of one element. pub fn scalar(ck: *core.Checkpoint, name: []const u8) !f32 { const t = try ck.get(name); diff --git a/zig/tests/cuda/contract_after.zig b/zig/tests/cuda/contract_after.zig index 03a557ee3a3..961397f5480 100644 --- a/zig/tests/cuda/contract_after.zig +++ b/zig/tests/cuda/contract_after.zig @@ -15,7 +15,7 @@ pub fn keep(kernels: *std.ArrayList(g.Kernel), only: []const []const u8) void { kernels.shrinkRetainingCapacity(kept); } -/// The served, paged, pending, learning and lane suites of a full run. +/// The served, paged, pending, learning, lane and SwiGLU pair suites of a full run. pub fn suites(gpu: check.Gpu) !void { try @import("contract_qwen_served.zig").run(gpu); try @import("contract_qwen_pages.zig").run(gpu); @@ -23,4 +23,5 @@ pub fn suites(gpu: check.Gpu) !void { try @import("contract_qwen_pending.zig").run(gpu); try @import("contract_qwen_learning.zig").numerical(gpu); try @import("contract_fn_lanes.zig").run(gpu); + try @import("contract_prompt_swiglu.zig").run(gpu); } diff --git a/zig/tests/cuda/contract_prompt_swiglu.zig b/zig/tests/cuda/contract_prompt_swiglu.zig new file mode 100644 index 00000000000..62adba8dc47 --- /dev/null +++ b/zig/tests/cuda/contract_prompt_swiglu.zig @@ -0,0 +1,293 @@ +//! prompt_lean's gate/up SwiGLU pair: byte-equal to two lean products then tf_q35_mlp_act, with planted controls. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const gpu_check = @import("check.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const nvfp4 = cuda.nvfp4; + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// The 27B's MLP at 2048 and 4096 rows, a partial row tile, one row, 17 rows of 17 groups, 300 rows of 9 groups. +const served = [_]c.Shape{ + .{ .rows = 2048, .n = 17408, .k = 5120 }, .{ .rows = 4096, .n = 17408, .k = 5120 }, + .{ .rows = 129, .n = 17408, .k = 5120 }, .{ .rows = 1, .n = 128, .k = 64 }, + .{ .rows = 17, .n = 256, .k = 1088 }, .{ .rows = 300, .n = 384, .k = 576 }, +}; +/// The device row count's shapes: each drops 37 rows, so a row tile ends inside the launch's last one. +const counted = [_]c.Shape{ .{ .rows = 2048, .n = 17408, .k = 5120 }, .{ .rows = 129, .n = 17408, .k = 5120 }, .{ .rows = 300, .n = 384, .k = 576 } }; +/// Every bf16 bit pattern as a gate value (row r's gate is r's pattern), against 128 up values a row. +const sweep_shape = [_]c.Shape{.{ .rows = 65536, .n = 128, .k = 64 }}; + +const rule = "every output byte equals two prompt_lean products, then tf_q35_mlp_act, on the same rows and weights"; + +/// What a registration plants or covers: the served launch, a device row count, every gate value, or a control. +const Form = enum { served, device_rows, sweep, swapped, gate_ulp }; + +/// One FP4 weight's host fixture: e2m1 codes, e4m3 block scales, packed as the loader packs them. +const Weight = struct { + codes: []u8, + scales: []u8, + + fn init(a: std.mem.Allocator, n: usize, k: usize) !Weight { + return .{ .codes = try a.alloc(u8, n * k / 2), .scales = try a.alloc(u8, n * k / 16) }; + } + + fn deinit(w: Weight, a: std.mem.Allocator) void { + a.free(w.codes); + a.free(w.scales); + } + + /// Random codes and scales: magnitudes 1/8 ... 4, all nibbles; `stress` every nibble -6 at the largest scale. + fn fill(w: Weight, rng: std.Random, fill_: g.Fill) void { + for (w.codes) |*q| q.* = if (fill_ == .stress) 0xEE else rng.int(u8); + for (w.scales) |*s| s.* = if (fill_ == .stress) 0x7E else 0x20 + rng.uintLessThan(u8, 0x29); + if (fill_ == .nonfinite) w.scales[w.scales.len / 3] = 0x7F; // a NaN block scale + } + + fn upload(w: Weight, a: std.mem.Allocator, rig: *rig_.Rig, scale: f32, n: usize, k: usize) !cuda.qmmf.Weight { + const words = try a.alloc(u32, nvfp4.padded(n) / 64 * (k / nvfp4.group) * 512); + defer a.free(words); + nvfp4.packWords(words, w.codes, n, k); + const tiles = try a.alloc(u8, nvfp4.padded(n) * (k / 16)); + defer a.free(tiles); + nvfp4.packScales(tiles, w.scales, n, k); + return nvfp4.weight(try rig.input(std.mem.sliceAsBytes(words)), try rig.input(tiles), scale, n, k); + } +}; + +/// Sums near 1 ... 10 at K 5120 for these codes and scales, so silu's every branch is reached. +const gate_scale: f32 = 0.0123; +const up_scale: f32 = 0.0071; + +pub const Product = struct { + rig: rig_.Rig, + prompt: *const nvfp4.Prompt, + act: cuda.Function, + form: Form = .served, + gate: cuda.qmmf.Weight = undefined, + up: cuda.qmmf.Weight = undefined, + x: u64 = 0, + rows_at: u64 = 0, // the device row count's table (P[2]), 0 for none + rows: usize = 0, + n: usize = 0, + k: usize = 0, + out: u64 = 0, + base: [3]u64 = .{ 0, 0, 0 }, // the separate path's gate, up and act + + pub fn kernel(self: *Product) g.Kernel { + const name = switch (self.form) { + .served => "cuda prompt16 FP4 lean SwiGLU pair", + .device_rows => "cuda prompt16 FP4 lean SwiGLU pair, device row count", + .sweep => "cuda prompt16 FP4 lean SwiGLU pair, every bf16 gate value", + .swapped => "control: lean SwiGLU pair with gate and up swapped", + .gate_ulp => "control: lean SwiGLU pair with the gate's scale one fp32 ulp up", + }; + const control = self.form == .swapped or self.form == .gate_ulp; + return .{ .spec = .{ + .name = name, + .accum = .none, + .depth = noSums, + .out = .raw, + .replaces = if (control) null else "two prompt_lean products, then tf_q35_mlp_act", + .nan = .{ .stated = rule }, + .served = switch (self.form) { + .sweep => &sweep_shape, + .device_rows => &counted, + else => &served, + }, + }, .ctx = self, .vt = &vt, .control = if (control) .shapes else null }; + } + + const vt = g.hooks(Product); + + pub fn deinit(self: *Product) void { + self.rig.deinit(); + } + + pub fn prepare(self: *Product, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.rows == 0 or shape.k % 64 != 0 or shape.n % 128 != 0) return false; + const a = self.rig.gpu.gpa; + self.rows = shape.rows; + self.n = shape.n; + self.k = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const x = try a.alloc(u16, shape.rows * shape.k); + defer a.free(x); + for (x, 0..) |*v, i| v.* = switch (fill) { + .stress => c.toBf16(rng.float(f32) * 2.0e18 + 1.0e17), + else => if (i % 29 == 0) 0 else c.toBf16(rng.float(f32) * 4 - 2), + }; + if (fill == .nonfinite) for ([_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }, 0..) |v, r| { + if (r < shape.rows) x[r * shape.k + (r * 7 + 3) % shape.k] = c.toBf16(v); + }; + const wg = try Weight.init(a, shape.n, shape.k); + defer wg.deinit(a); + const wu = try Weight.init(a, shape.n, shape.k); + defer wu.deinit(a); + wg.fill(rng, fill); + wu.fill(rng, fill); + var gs = gate_scale; + if (self.form == .sweep) { // gate = x[r, 0]: a 1.0 code at input 0, scale 1, else 0; up skips input 0 + for (x, 0..) |*v, i| if (i % shape.k == 0) { + v.* = @intCast(i / shape.k); + }; + @memset(wg.codes, 0); + @memset(wg.scales, 0x38); + for (0..shape.n) |j| { + wg.codes[j * shape.k / 2] = 0x02; + wu.codes[j * shape.k / 2] &= 0xF0; + } + gs = 1.0; + } + self.x = try self.rig.input(std.mem.sliceAsBytes(x)); + self.gate = try wg.upload(a, &self.rig, gs, shape.n, shape.k); + self.up = try wu.upload(a, &self.rig, up_scale, shape.n, shape.k); + self.rows_at = 0; + if (self.form == .device_rows) { + const table = [4]i32{ 0, 0, @intCast(shape.rows - 37), 0 }; // P[2]: fewer rows than the launch's + self.rows_at = try self.rig.input(std.mem.sliceAsBytes(&table)); + } + for (&self.base, [_]usize{ 2, 2, 2 }) |*b, size| b.* = try self.rig.scratch(shape.rows * shape.n * size); + self.out = try self.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(self: *Product) !void { + var gate = self.gate; + var up = self.up; + if (self.form == .swapped) std.mem.swap(cuda.qmmf.Weight, &gate, &up); + if (self.form == .gate_ulp) gate.scale = std.math.nextAfter(f32, gate.scale, std.math.inf(f32)); + try self.prompt.swiglu(self.rig.s, self.x, self.k, self.rows, gate, up, self.out, self.rows_at); + try self.rig.s.synchronize(); + } + + /// main's path on the same inputs: the gate and up products, then the act kernel into an output-poisoned buffer. + pub fn replaced(self: *Product) ![]const u8 { + try self.separate(); + return self.rig.bytes(self.base[2], self.rows * self.n * 2); + } + + fn separate(self: *Product) !void { + const s = self.rig.s; + try self.prompt.matmulTile(s, self.x, self.k, self.rows, self.gate, self.base[0], .bf16, .lean); + try self.prompt.matmulTile(s, self.x, self.k, self.rows, self.up, self.base[1], .bf16, .lean); + const act: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.base[2], .len = self.rows * self.n * 2 }; + try act.fill8(0xff, s.handle); // as rig.output() poisons: rows past a device count stay unwritten in both + const total: c_longlong = @intCast(self.rows * self.n); + var a: cuda.Args = .{}; + a.add(self.base[0]); + a.add(self.base[1]); + a.add(self.base[2]); + a.add(total); + a.add(self.rows_at); + a.add(@as(c_int, @intCast(self.n))); + a.add(@as(u64, 0)); + const blocks: u32 = @intCast((self.rows * self.n + 1023) / 1024); + try cuda.launch.launch(self.act, .{ .grid = .{ .x = blocks, .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &a); + } + + pub fn check(self: *Product, _: g.Gate) !?[]const u8 { + const got = try self.rig.gpu.gpa.dupe(u8, try self.rig.outputBytes()); + defer self.rig.gpu.gpa.free(got); + const want = try self.replaced(); + return if (std.mem.eql(u8, got, want)) null else rule; + } + + pub fn count(self: *Product) usize { + return self.rows * self.n * 2; + } + + pub fn reference(_: *Product, _: []f64, _: []f64) !void {} + + /// Mean ns of `reps` fused launches, or of the separate path (two products and the act kernel). + fn time(self: *Product, fused: bool, reps: usize, io: std.Io) !i96 { + try self.rig.s.synchronize(); + const start = gpu_check.now(io); + for (0..reps) |_| { + if (fused) try self.run() else try self.separate(); + try self.rig.s.synchronize(); + } + return @divTrunc(gpu_check.now(io) - start, @as(i96, @intCast(reps))); + } +}; + +/// The act kernel's module (qwen35) and the registrations over one prompt module. +pub const Registrations = struct { + mod: cuda.Module, + items: [5]Product, + + pub fn init(gpu: gpu_check.Gpu, s: cuda.Stream, prompt: *const nvfp4.Prompt) !Registrations { + var mod = try cuda.Module.load(gpu.d, cuda.kernels.qwen35); + errdefer mod.unload(); + const act = try mod.function("tf_q35_mlp_act"); + var r: Registrations = .{ .mod = mod, .items = undefined }; + for (&r.items, std.enums.values(Form)) |*p, form| p.* = .{ .rig = .{ .gpu = gpu, .s = s }, .prompt = prompt, .act = act, .form = form }; + return r; + } + + pub fn deinit(self: *Registrations) void { + for (&self.items) |*p| p.deinit(); + self.mod.unload(); + } + + pub fn append(self: *Registrations, a: std.mem.Allocator, kernels: *std.ArrayList(g.Kernel)) !void { + for (&self.items) |*p| try kernels.append(a, p.kernel()); + } +}; + +/// The focused gate run (tf-cuda-test prompt-swiglu-contract); kernel-contract runs it after its registered gates. +pub fn run(gpu: gpu_check.Gpu) !void { + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var prompt = try nvfp4.Prompt.load(gpu.d); + defer prompt.unload(); + var registrations = try Registrations.init(gpu, s, &prompt); + defer registrations.deinit(); + var kernels: std.ArrayList(g.Kernel) = .empty; + defer kernels.deinit(gpu.gpa); + try registrations.append(gpu.gpa, &kernels); + var tally: g.Tally = .{}; + try g.runAll(gpu.gpa, kernels.items, 0x5719, &tally); + std.debug.print("SUMMARY prompt_swiglu: {d} pass, {d} fail; {d} controls red, {d} missed\n", .{ + tally.passed, tally.failed, tally.caught, tally.missed, + }); + try gpu_check.expect(tally.problems() == 0, "prompt_swiglu contract: {d} failures", .{tally.problems()}); +} + +/// Kernel-level A-B-A per shape: two lean products and the act kernel against the pair launch (not a served claim). +pub fn bench(gpu: gpu_check.Gpu) !void { + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var prompt = try nvfp4.Prompt.load(gpu.d); + defer prompt.unload(); + var registrations = try Registrations.init(gpu, s, &prompt); + defer registrations.deinit(); + const product = ®istrations.items[0]; + const cases = [_]c.Shape{ + .{ .rows = 2048, .n = 17408, .k = 5120 }, + .{ .rows = 4096, .n = 17408, .k = 5120 }, + .{ .rows = 8192, .n = 17408, .k = 5120 }, + }; + for (cases, 0..) |shape, i| { + _ = try product.prepare(shape, .random, 0x5719 + i); + _ = try product.time(true, 2, gpu.io); // warm both paths once + _ = try product.time(false, 2, gpu.io); + const a1 = try product.time(false, 7, gpu.io); + const b = try product.time(true, 7, gpu.io); + const a2 = try product.time(false, 7, gpu.io); + const ms = std.time.ns_per_ms; + const base: f64 = @floatFromInt(@divTrunc(a1 + a2, 2)); + std.debug.print("BENCH prompt_swiglu rows={d}: A1={d:.3} ms B={d:.3} ms A2={d:.3} ms separate/pair={d:.4}x\n", .{ + shape.rows, @as(f64, @floatFromInt(a1)) / ms, @as(f64, @floatFromInt(b)) / ms, + @as(f64, @floatFromInt(a2)) / ms, base / @as(f64, @floatFromInt(b)), + }); + } +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index c4243181959..92ea3191df8 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -259,6 +259,8 @@ const usage = \\ qmmf-prompt-repro isolate M=65 N=8240 K=2560 SK=4 BF16 without clusters \\ qmmf-prompt-bench rank0 normal-main weighted A-B-A timings, plus separate MTP hidden timings \\ qmm-prefill-many-bench same-process A-B-A screening for the GB10 launch fusion + \\ prompt-swiglu-contract the lean gate/up SwiGLU pair against two products and the act kernel, controls red + \\ prompt-swiglu-bench same-process A-B-A: the lean SwiGLU pair against two products and the act kernel \\ mtp-rows tf_q36m_attn_rows: gates 1-4 (byte-equal to tf_q36m_attn a segment) and float64 alone \\ qwen-pages qwen35.cu's attention cache through a page table: paged == contiguous, float64, red controls \\ qwen-shared-prefix [time] attn_rows's classes across streams on shared pages == each stream alone, red controls; time: A/B @@ -528,6 +530,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "qmm-prefill-many-contract")) return qmm_prefill_many_contract.run(gpu); if (std.mem.eql(u8, cmd, "qmm-prefill-tile22-contract")) return qmm_prefill_tile22_contract.run(gpu); if (std.mem.eql(u8, cmd, "qmm-prefill-many-bench")) return qmm_prefill_many_contract.bench(gpu); + if (std.mem.eql(u8, cmd, "prompt-swiglu-contract")) return @import("contract_prompt_swiglu.zig").run(gpu); + if (std.mem.eql(u8, cmd, "prompt-swiglu-bench")) return @import("contract_prompt_swiglu.zig").bench(gpu); if (std.mem.eql(u8, cmd, "mtp-rows")) return @import("contract_qwen_mtp_rows.zig").alone(gpu); if (std.mem.eql(u8, cmd, "qwen-pages")) return @import("contract_qwen_pages.zig").run(gpu); if (std.mem.eql(u8, cmd, "qwen-shared-prefix")) return @import("contract_qwen_shared_prefix.zig").run(gpu, rest); From 3597e64c8845b24b5b9eed4f338c45afa81ffc61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:53 +0100 Subject: [PATCH 11/89] qwen3_5 cuda: re-pin prompt16.cu and nvfp4.zig for the lean SwiGLU pair; inline four single-use imports in the CUDA test dispatcher The dispatcher sat at 600 lines on main, so the two new commands pushed it to 604 once applied there. --- zig/tests/cuda/main.zig | 12 ++++-------- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 92ea3191df8..7035712f1a4 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -34,7 +34,6 @@ const w4a8_tests = @import("w4a8_tests.zig"); const glm_exl3_tests = @import("glm_exl3_tests.zig"); const glm_kda_pad_check = @import("glm_kda_pad_check.zig"); const glm_vision_tests = @import("glm_vision_tests.zig"); -const glm_mm_fixed = @import("glm_mm_fixed_tests.zig"); const glm_mm_bench = @import("glm_mm_bench.zig"); const glm_index_check = @import("glm_index_check.zig"); const carveout_tests = @import("carveout_tests.zig"); @@ -57,10 +56,7 @@ const embed_tests = @import("embed_tests.zig"); const pocket_tests = @import("pocket_tests.zig"); const recapture_tests = @import("recapture_tests.zig"); const contract_tests = @import("contract_tests.zig"); -const gb10_many_contract = @import("contract_gb10_many.zig"); const qmm_prefill_many_contract = @import("contract_qmm_prefill_many.zig"); -const qmm_prefill_tile22_contract = @import("contract_qmm_prefill_tile22.zig"); -const glue_contract = @import("contract_flashnext_glue.zig"); const lfm2_attention_tests = @import("lfm2_attention_tests.zig"); const lfm2_kernel_tests = @import("lfm2_kernel_tests.zig"); const lfm2_vision_tests = @import("lfm2_vision_tests.zig"); @@ -350,7 +346,7 @@ fn arg(rest: []const [:0]const u8, i: usize) ![]const u8 { fn compileContractGlue() !void { // the contract glue's device path, built with the runner: prepare through the vtable const cores = std.Thread.getCpuCount() catch 1; if (cores != 0) return; - var g: glue_contract.Glue = undefined; + var g: @import("contract_flashnext_glue.zig").Glue = undefined; g.kind = .chain; const kernels = [_]@import("core").contract.gates.Kernel{g.kernel()}; for (kernels) |k| _ = try k.vt.prepare(k.ctx, .{ .rows = 0, .n = 0, .k = 0 }, .random, 0); @@ -444,7 +440,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "w4a8")) return w4a8_tests.run(gpu); if (std.mem.eql(u8, cmd, "glm-exl3")) return glm_exl3_tests.run_(gpu); if (std.mem.eql(u8, cmd, "glm-kda-pad-split")) return glm_kda_pad_check.run(gpu); - if (std.mem.eql(u8, cmd, "glm-mm-fixed")) return glm_mm_fixed.run(gpu); + if (std.mem.eql(u8, cmd, "glm-mm-fixed")) return @import("glm_mm_fixed_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "glm-mm-bench")) return glm_mm_bench.run(gpu); if (std.mem.eql(u8, cmd, "glm-index-check")) return glm_index_check.run(gpu); if (std.mem.eql(u8, cmd, "glm-kv-host-slots")) return glm_kv_host_slots.run(gpu); @@ -526,9 +522,9 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "q27-gemm")) return q27_gemm_tests.run(gpu); if (std.mem.eql(u8, cmd, "gdn-back-27b")) return gdn_back_tests.runShape(gpu, 5120, 64); if (std.mem.eql(u8, cmd, "kernel-contract")) return contract_tests.run(gpu, rest); - if (std.mem.eql(u8, cmd, "gb10-grouped-contract")) return gb10_many_contract.runAll(gpu); + if (std.mem.eql(u8, cmd, "gb10-grouped-contract")) return @import("contract_gb10_many.zig").runAll(gpu); if (std.mem.eql(u8, cmd, "qmm-prefill-many-contract")) return qmm_prefill_many_contract.run(gpu); - if (std.mem.eql(u8, cmd, "qmm-prefill-tile22-contract")) return qmm_prefill_tile22_contract.run(gpu); + if (std.mem.eql(u8, cmd, "qmm-prefill-tile22-contract")) return @import("contract_qmm_prefill_tile22.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmm-prefill-many-bench")) return qmm_prefill_many_contract.bench(gpu); if (std.mem.eql(u8, cmd, "prompt-swiglu-contract")) return @import("contract_prompt_swiglu.zig").run(gpu); if (std.mem.eql(u8, cmd, "prompt-swiglu-bench")) return @import("contract_prompt_swiglu.zig").bench(gpu); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index a60d94d6c22..e2f0cc0648d 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -49,7 +49,7 @@ zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a zig/kernels/cuda/prefill_attention.cu 905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu c5a6ca4513311d25282866de2185a056ec9746443a13094db80de62f7474255a raw -zig/kernels/cuda/prompt16.cu 972fb2f601da2d64549717d27e642363243b0e2df88cfeffa81452216e160ae4 raw +zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt zig/kernels/cuda/qmm.cu a55a9d00d9097c5f5bd88c8c538a0481fe13b37badd2e3faf4cdde9c86c9f93d raw zig/kernels/cuda/common/qmm_frag.cuh 418dce9d64df0b8751c8ca982ae3f93c5fc54e4aecb9a8df3f0780129dcb675a raw zig/kernels/cuda/common/router_tiles.cuh aab559bf104e3f47344deaa9ae10622b6962b8a77b398f572ba974055dfafd3c raw @@ -101,7 +101,7 @@ zig/src/cuda/module.zig 1f0a141cf7149a87ad456e96cb1830f0c137ad98af70071721918989 zig/src/cuda/mxfp8.zig 2bbe9ea41b462f633b68e7a32c06814a28e34dee284383788c0a8f06e8df2af4 raw zig/src/cuda/nccl.zig 30abc4b904e675916e9bb8c4701ca3f1e5615472da4a5e09d2476865d81afe65 raw commits 53abe4556, ba1a9a2bb, 05350da4c, 40dccba55, 6bdb12918, b923e554c, 7c9d845c0, 98a5dc657, 143ed758f, 6636e6964; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/norms.zig c6ac613ff91b31257b5bce55311d8cf38a785862bfad9eb0c7bf0b2ba7b0df95 raw -zig/src/cuda/nvfp4.zig 62bd32b4dcc7d4e7f077c2147adf65a1aea7744dda4845b06da72c946e6c5277 raw +zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7fb90928 raw #3252: launcher for the lean SwiGLU pair zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig 760f033510402806cb06e70eec45cfe068bd5cd029315a05c9c8c493c7f12b30 raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name) zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw From 10ea9635b08e19c5a254bd5aaf5bed55a2f4ccef Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:47:00 +0000 Subject: [PATCH 12/89] changelog: #3252 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b05ebeca3d1..39590ee6273 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: a dense Qwen 3.5 MLP's NVFP4 prompt gate, up and activation run in one launch for prompt rows past 16, with the same bytes (#3252). Thanks to @jschmied. + - Images: with `stream: true`, `POST /v1/images/generations` streams each denoising step's progress (`image_generation.progress`) and, with `preview_interval`, partial previews while the picture generates, then the PNG (#3245). - DeepSeek-V4.1 on Metal: decode launches of 6 to 16 rows (draft verify windows, alone or with other streams' rows) run the dense FP8 projections on a simdgroup-matrix tile that splits K over simdgroups in the row kernel's own group tree, so every row's bits equal the row kernel's one row at a time; launches of 1 to 5 rows keep the row kernel. On the release weights two drafted streams decode 3.7 to 5.5% faster on an M5 Ultra and 3.6 to 5.4% faster on an M3 Ultra, other stream counts are level, and every token is unchanged; `time-dsv41-metal-synth` times the dispatch classes per row without a checkpoint (#2973, part of #2984). From 917f2070dbc0d39e4d83d0d52a795bf2f9e02480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:13:55 +0100 Subject: [PATCH 13/89] cuda: one kept image for states in device buffers, Gemma 4 on disk (#840) native/cuda_kept.zig holds what Flash Next's kept_disk held: the image's words, the copies, the probe. A family declares a view of its layout. Flash Next moves onto it with its probe bytes and seed unchanged; its key gains the prompt files. Gemma 4 keeps its states on disk with --learn-conversations and --spill-gib. Keys bind the tokenizer's and template's bytes, a drafter's checkpoint and the KV form. A state over an image stays off disk: RAM alone tells which image. A stale key opens another namespace, a cold pass. --- zig/build/cuda_fault_host.zig | 2 +- zig/build/disk_identity_host.zig | 3 + zig/src/families/flashnext/cuda_disk.zig | 184 ++++--------- zig/src/families/flashnext/cuda_lanes.zig | 2 +- zig/src/families/gemma4/cuda.zig | 2 + zig/src/families/gemma4/cuda_backend.zig | 1 + zig/src/families/gemma4/cuda_disk.zig | 145 +++++++++++ zig/src/families/gemma4/cuda_native.zig | 1 + zig/src/families/gemma4/cuda_snap.zig | 17 +- zig/src/native/cuda.zig | 1 + zig/src/native/cuda_disk.zig | 13 +- zig/src/native/cuda_disk_policy_test.zig | 2 +- zig/src/native/cuda_kept.zig | 218 ++++++++++++++++ zig/src/native/cuda_kept_test.zig | 300 ++++++++++++++++++++++ 14 files changed, 744 insertions(+), 147 deletions(-) create mode 100644 zig/src/families/gemma4/cuda_disk.zig create mode 100644 zig/src/native/cuda_kept.zig create mode 100644 zig/src/native/cuda_kept_test.zig diff --git a/zig/build/cuda_fault_host.zig b/zig/build/cuda_fault_host.zig index f33c590233c..bebc6d3170a 100644 --- a/zig/build/cuda_fault_host.zig +++ b/zig/build/cuda_fault_host.zig @@ -4,7 +4,7 @@ const std = @import("std"); pub fn steps(b: *std.Build, cuda: *std.Build.Module, flashnext: *std.Build.Module, native: *std.Build.Module) void { b.step("test-cuda-context-health-host", "Sticky CUDA context faults and real graph-instantiation refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{ "CUDA context health:", "CUDA graph refusal:" } })).step); b.step("test-flashnext-loader-host", "The threaded NVFP4 expert loader: the loop's words, no pinned or device memory left after a failed load, geometry first").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{"Flash Next expert loader:"} })).step); - b.step("test-flashnext-completion-host", "Actual CUDA sequence rollback drains asynchronous destinations before release").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{"Flash Next completion:"} })).step); + b.step("test-flashnext-completion-host", "Actual CUDA sequence rollback drains asynchronous destinations before release").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"Flash Next completion:"} })).step); b.step("test-cuda-fault-admission-host", "Sticky context health reaches native status and queue admission").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA context health:"} })).step); b.step("test-cuda-readiness-host", "Real native readiness and synchronous startup preparation without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"family readiness reaches"} })).step); b.step("test-startup-log-host", "Ordered startup logs and early P2P facts without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"startup log:"} })).step); diff --git a/zig/build/disk_identity_host.zig b/zig/build/disk_identity_host.zig index 71afdced8ad..3944da1ecfc 100644 --- a/zig/build/disk_identity_host.zig +++ b/zig/build/disk_identity_host.zig @@ -4,6 +4,9 @@ pub fn steps(b: *std.Build, native: *std.Build.Module, all: *std.Build.Step) voi const open = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA disk open:"} })); b.step("test-cuda-disk-open-host", "CUDA's disk store takes --spill-gib's mode and --checkpoint-slots").dependOn(&open.step); all.dependOn(&open.step); + const kept = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA kept:"} })); + b.step("test-cuda-kept-host", "The shared kept image over host memory, stale keys through the real store").dependOn(&kept.step); + all.dependOn(&kept.step); const identity = b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"disk identity:"} })); b.step("test-disk-identity-host", "Actual CUDA identity, resolved profile values and stale disk misses").dependOn(&identity.step); all.dependOn(&identity.step); diff --git a/zig/src/families/flashnext/cuda_disk.zig b/zig/src/families/flashnext/cuda_disk.zig index fcf1dd94587..dddedaa7ee5 100644 --- a/zig/src/families/flashnext/cuda_disk.zig +++ b/zig/src/families/flashnext/cuda_disk.zig @@ -9,11 +9,15 @@ const sh = snap.shape; const Allocator = std.mem.Allocator; const words = 32; // the n-gram history, the position, whether the MTP head's rows follow -const Words = extern struct { history: [2]i64, at: u64, head: u64 }; -/// The image's parts at `at`: words, DeltaNet tails and states, each attention piece by layer, the tail, the head's. +/// The image's parts at `at`: words, then the state's own. pub fn partsOf(at: u32, head: bool, out: *std.ArrayList(rows.image.Part), a: Allocator) !void { try out.append(a, .{ .bytes = words }); + try body(at, head, out, a); +} + +/// DeltaNet tails and states, each attention piece by layer, the tail, the head's. +fn body(at: u32, head: bool, out: *std.ArrayList(rows.image.Part), a: Allocator) !void { try out.append(a, .{ .bytes = sh.linear * sh.conv }); try out.append(a, .{ .bytes = sh.linear * sh.state }); try attention(at, sh.attn, out, a); @@ -28,122 +32,76 @@ fn attention(at: u32, layers: usize, out: *std.ArrayList(rows.image.Part), a: Al for (0..layers) |_| try out.append(a, .{ .bytes = @as(u64, at / sh.ratio) * sh.index_row, .row = sh.index_row, .per = sh.ratio }); } -/// The disk tier of a Flash Next namespace `F` (its Cuda backend is the prompt cache's target). -pub fn Kept(comptime F: type) type { +/// The disk tier's view of a Flash Next namespace `F` (native/cuda_kept.zig; its Cuda is the prompt cache's target). +pub fn View(comptime F: type) type { return struct { - pub const image: rows.Image = .{ .parts = parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; - /// The states are one tensor rank's: --tp refuses --learn-conversations (native/cuda_refusal.zig). - pub const one_rank = true; + pub const Target = F.Cuda; + pub const State = snap.Snap; + pub const Words = extern struct { history: [2]i64, at: u64, head: u64 }; + pub const probe_seed: u64 = 0x666e; + pub const one_rank = true; // the states are one tensor rank's + + pub fn driver(c: *Target) *const cuda.Driver { + return c.engine.driver; + } - fn of(ptr: *anyopaque) *F.Cuda { - return @ptrCast(@alignCast(ptr)); + pub fn stream(c: *Target) cuda.Stream { + return c.stream; } - fn parts(ptr: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { - try partsOf(at, of(ptr).head != null, out, a); + pub fn buffers(st: *const State) [2]?cuda.DeviceBuffer { + return .{ st.buf, null }; } - fn copy(c: *F.Cuda, st: *snap.Snap, ranges: []const rows.image.Range, host: []u8, out: bool) !void { - const d = c.engine.driver; - // a later range's failure leaves earlier copies queued on `host`, which its caller then frees or reuses - errdefer cuda.completion.drain(d, c.stream, "a failed kept-state copy did not drain"); - var w: Words = .{ .history = st.history, .at = st.at, .head = @intFromBool(st.head) }; - var o: usize = 0; - for (ranges) |g| { - var off: usize = @intCast(g.off); - var len: usize = @intCast(g.len); - if (off + len > words + st.buf.len) return error.BadKeptRange; - if (off < words) { - const n = @min(len, words - off); - if (out) @memcpy(host[o..][0..n], std.mem.asBytes(&w)[off..][0..n]) else @memcpy(std.mem.asBytes(&w)[off..][0..n], host[o..][0..n]); - o += n; - off += n; - len -= n; - } - if (len == 0) continue; - const dev = st.buf.ptr + off - words; - if (out) { - try d.check(d.api.cuMemcpyDtoHAsync_v2(host[o..].ptr, dev, len, c.stream.handle), "cuMemcpyDtoHAsync"); - } else try d.check(d.api.cuMemcpyHtoDAsync_v2(dev, host[o..].ptr, len, c.stream.handle), "cuMemcpyHtoDAsync"); - o += len; - } - try c.stream.synchronize(); // `host` is the store's staging, reused by its next piece - if (out) return; - // a state read back stands where it was kept, with the head's rows as kept: else it restores nowhere + pub fn drafts(c: *const Target) bool { + return c.head != null; + } + + pub fn wordsOf(st: *const State) Words { + return .{ .history = st.history, .at = st.at, .head = @intFromBool(st.head) }; + } + + /// A state read back stands where it was kept, with the head's rows as kept: else it restores nowhere. + pub fn setWords(st: *State, w: Words) !void { if (w.at != st.at or w.head != @intFromBool(st.head)) return error.KeptWordsDiffer; st.history = w.history; } - fn gather(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, out: []u8) anyerror!void { - try copy(of(ptr), @ptrCast(@alignCast(saved)), ranges, out, true); + pub fn parts(c: *const Target, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) !void { + try body(at, c.head != null, out, a); } - fn scatter(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, in: []const u8) anyerror!void { - try copy(of(ptr), @ptrCast(@alignCast(saved)), ranges, @constCast(in), false); + pub fn save(c: *Target, s: *lanes.Stream, at: u32) !*State { + return @ptrCast(@alignCast(try F.snap_save(c, s, at))); + } + + pub fn drop(c: *Target, st: *State) void { + F.snap_drop(c, st); } /// A device buffer for `at` tokens with the head's rows if this server drafts, filled by `scatter`. - fn blank(ptr: *anyopaque, at: u32) anyerror!api.prompt_cache.Saved { - const c = of(ptr); + pub fn blank(c: *Target, at: u32) !*State { const head = c.head != null; const st = try c.gpa.create(snap.Snap); errdefer c.gpa.destroy(st); st.* = .{ .buf = try cuda.DeviceBuffer.alloc(c.engine.driver, snap.bytes(at, head, .full)), .at = at, .history = .{ 0, 0 }, .head = head }; - return @ptrCast(st); + return st; } /// A state from a stream that did not draft lacks the head's rows this server's parts name: it stays off disk. - fn whole(ptr: *anyopaque, saved: api.prompt_cache.Saved) bool { - const st: *const snap.Snap = @ptrCast(@alignCast(saved)); - return st.head == (of(ptr).head != null) and st.rank_id == 0 and st.heads.eql(.full); - } - - /// A fixed prompt's state at a mark inside its last chunk, hashed, and the prompt rate it took. - pub fn probe(a: Allocator, io: std.Io, backend: lanes.backend.Backend, target: *anyopaque) !struct { hash: u64, rate: f64 } { - const c = of(target); - var toks: [4096 + 40 + 7]u32 = undefined; - for (&toks, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); - const Hook = struct { - c: *F.Cuda, - saved: ?*anyopaque = null, - failed: ?anyerror = null, - fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { - const p: *@This() = @ptrCast(@alignCast(ptr)); - p.saved = F.snap_save(p.c, s, mark) catch |e| { - p.failed = e; - return; - }; - } - }; - var hook: Hook = .{ .c = c }; - defer if (hook.saved) |saved| F.snap_drop(c, saved); - const marks = [_]u32{4136}; - var s = try lanes.Stream.init(a, .{ .id = "probe", .prompt = &toks, .max_new = 1, .drafts = c.head != null, .reuse = .{ .marks = &marks, .hook = .{ .ptr = &hook, .at = Hook.at } } }); - defer s.deinit(a); - const ns = pass: { - defer backend.vtable.release(backend.ptr, &s); // once, whether the pass, its wait or nothing failed - const t0 = std.Io.Clock.awake.now(io).toNanoseconds(); - try backend.vtable.prefill(backend.ptr, &s); - try c.stream.synchronize(); - break :pass std.Io.Clock.awake.now(io).toNanoseconds() - t0; - }; - const saved = hook.saved orelse return hook.failed orelse error.ProbeUnmarked; - if (!whole(c, saved)) return error.ProbeUnmarked; - const st: *snap.Snap = @ptrCast(@alignCast(saved)); - const bytes = try a.alloc(u8, words + st.buf.len); - try copy(c, st, &.{.{ .off = 0, .len = bytes.len }}, bytes, true); - return .{ .hash = std.hash.Wyhash.hash(0x666e, bytes), .rate = @as(f64, @floatFromInt(toks.len)) / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; + pub fn whole(c: *const Target, st: *const State) bool { + return st.head == (c.head != null) and st.rank_id == 0 and st.heads.eql(.full); } /// What else the states depend on: whether the MTP head's rows are part of them. - pub fn facts(target: *anyopaque) [1]u64 { - return .{@intFromBool(of(target).head != null)}; + pub fn facts(c: *const Target) [1]u64 { + return .{@intFromBool(c.head != null)}; } /// The native key extends with policyOf under this domain (native/cuda_disk.zig keptKey). pub const policy_domain = "flash-cuda-policy-v1"; - pub fn policy(target: *anyopaque) [13]u64 { - return policyOf(of(target)); + pub fn policy(target: anytype) [13]u64 { + return policyOf(@as(*const Target, @ptrCast(@alignCast(target)))); } }; } @@ -226,51 +184,3 @@ test "the image's parts are cuda_snap.move's pieces in its order: sizes, offsets try std.testing.expectEqual(rows.image.imageBytes(parts.items), off); }; } - -/// A driver whose device copies, out or in, queue the first and refuse the next; `pending`: queued, not yet waited for. -const OneCopy = struct { - var queued: usize = 0; - var pending: usize = 0; - fn queue() cuda.abi.Result { - if (queued == 1) return cuda.abi.error_not_ready; // check() returns NotReady for it, logging nothing - queued += 1; - pending += 1; - return cuda.abi.success; - } - fn toHost(_: ?*anyopaque, _: u64, _: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { - return queue(); - } - fn toDevice(_: u64, _: ?*const anyopaque, _: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { - return queue(); - } - fn sync(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { - pending = 0; - return cuda.abi.success; - } -}; - -/// A Flash Next namespace whose Cuda has just the fields its image reads, and no MTP head. -const Bare = struct { - pub const Cuda = struct { gpa: Allocator, engine: struct { driver: *const cuda.Driver }, head: ?*anyopaque = null, stream: cuda.Stream }; -}; - -test "Flash Next completion: a kept state's copy out or in that fails part way drains the copies it queued" { - var d: cuda.Driver = undefined; - d.api.cuMemcpyDtoHAsync_v2 = OneCopy.toHost; - d.api.cuMemcpyHtoDAsync_v2 = OneCopy.toDevice; - d.api.cuStreamSynchronize = OneCopy.sync; - var c: Bare.Cuda = .{ .gpa = std.testing.allocator, .engine = .{ .driver = &d }, .stream = .{ .d = &d, .handle = @ptrFromInt(331) } }; - var st: snap.Snap = .{ .buf = .{ .d = &d, .ptr = 1 << 20, .len = 1024 }, .at = 0, .history = .{ 0, 0 }, .head = false }; - var host: [words + 1024]u8 = @splat(0); - const K = Kept(Bare); - // the words and half the state queue a copy; the driver refuses the other half, or that range runs past the state - for ([_]bool{ true, false }) |refused| for ([_]bool{ true, false }) |out| { - OneCopy.queued = 0; - OneCopy.pending = 0; - const ranges = [_]rows.image.Range{ .{ .off = 0, .len = words + 512 }, .{ .off = words + 512, .len = if (refused) 512 else 1024 } }; - const got = if (out) K.image.gather(&c, &st, &ranges, &host) else K.image.scatter(&c, &st, &ranges, &host); - try std.testing.expectError(if (refused) error.NotReady else error.BadKeptRange, got); - try std.testing.expectEqual(@as(usize, 1), OneCopy.queued); - try std.testing.expectEqual(@as(usize, 0), OneCopy.pending); // the caller's `host` may go: nothing copies on it - }; -} diff --git a/zig/src/families/flashnext/cuda_lanes.zig b/zig/src/families/flashnext/cuda_lanes.zig index 6aadd3ada56..3c2055f7c55 100644 --- a/zig/src/families/flashnext/cuda_lanes.zig +++ b/zig/src/families/flashnext/cuda_lanes.zig @@ -39,7 +39,7 @@ pub fn Namespace(comptime Tri: type) type { pub const snap_save = snaps.save; pub const snap_restore = snaps.restore; pub const snap_drop = snaps.drop; - pub const kept_disk = @import("cuda_disk.zig").Kept(@This()); // their disk image, as qwen3_5 declares its own + pub const kept_view = @import("cuda_disk.zig").View(@This()); // their disk image (native/cuda_kept.zig) /// TF_FLASHNEXT_KV_PAGES: the pool's lanes, the pages of a request's rows and a drafted window (kvl). pub const window_rows = kvl.window_rows; pub fn attach(p: *anyopaque, streams: u32, count: usize) !void { diff --git a/zig/src/families/gemma4/cuda.zig b/zig/src/families/gemma4/cuda.zig index 77f130682f2..17045321767 100644 --- a/zig/src/families/gemma4/cuda.zig +++ b/zig/src/families/gemma4/cuda.zig @@ -11,6 +11,7 @@ pub const weights = @import("cuda_weights.zig"); pub const kernels = @import("cuda_kernels.zig"); pub const forward = @import("cuda_forward.zig"); pub const snap = @import("cuda_snap.zig"); +pub const disk = @import("cuda_disk.zig"); pub const backend = @import("cuda_backend.zig"); pub const shared = @import("cuda_shared.zig"); pub const assistant = @import("cuda_assistant.zig"); @@ -47,6 +48,7 @@ test { _ = @import("cuda_kernels.zig"); _ = @import("cuda_forward.zig"); _ = @import("cuda_snap.zig"); + _ = @import("cuda_disk.zig"); _ = @import("cuda_backend.zig"); _ = @import("cuda_cap_test.zig"); _ = @import("cuda_solo.zig"); diff --git a/zig/src/families/gemma4/cuda_backend.zig b/zig/src/families/gemma4/cuda_backend.zig index c654f77d8ad..c2b87d38bc8 100644 --- a/zig/src/families/gemma4/cuda_backend.zig +++ b/zig/src/families/gemma4/cuda_backend.zig @@ -265,6 +265,7 @@ pub const Gemma = struct { const k = try snap.save(x.gpa, x.m, x.s, l.slot, at); errdefer snap.drop(x.gpa, x.s, k); if (x.keeper) |kp| try kp.keep(kp.ctx, s, k); + for (s.images) |im| k.images = k.images or im.at < at; return k; } diff --git a/zig/src/families/gemma4/cuda_disk.zig b/zig/src/families/gemma4/cuda_disk.zig new file mode 100644 index 00000000000..c044537c1d6 --- /dev/null +++ b/zig/src/families/gemma4/cuda_disk.zig @@ -0,0 +1,145 @@ +//! Gemma 4's kept states for the disk store (native/cuda_kept.zig): layout, a blank one, what they are read under. +const std = @import("std"); +const cuda = @import("cuda"); +const be = @import("cuda_backend.zig"); +const cfg = @import("cuda_config.zig"); +const fwd = @import("cuda_forward.zig"); +const snap = @import("cuda_snap.zig"); +const lanes = @import("lanes"); +const Allocator = std.mem.Allocator; + +pub const Target = be.Gemma; +pub const State = snap.Saved; +pub const probe_seed: u64 = 0x6734; + +/// Owned layers, K then V, as snap.each lays them; a ring's tail is the state's own, as is a drafter's context. +pub fn parts(t: *const Target, at: u32, out: anytype, a: Allocator) !void { + const m = t.m; + for (0..fwd.pages.ownLayers(m)) |i| for (0..2) |_| { + const row = snap.rowBytes(m, i); + if (cfg.global(i)) { + try out.append(a, .{ .bytes = @as(u64, at) * row, .row = @intCast(row) }); + } else try out.append(a, .{ .bytes = snap.tail(at) * row }); + }; + if (t.keeper) |kp| try out.append(a, .{ .bytes = kp.bytes(kp.ctx, at) }); +} + +pub fn buffers(st: *const State) [2]?cuda.DeviceBuffer { + return .{ st.buf, st.draft }; +} + +pub fn blank(t: *Target, at: u32) !*State { + return snap.blank(t.gpa, t.m, at, if (t.keeper) |kp| kp.bytes(kp.ctx, at) else 0); +} + +/// The target's rows are all here: not in the store's pages, no image RAM alone can tell. +pub fn probed(_: *const Target, st: *const State) bool { + return st.from == 0 and st.blob.len == 0 and !st.images; +} + +/// A state with images, or without the context a drafter keeps with it, stays off disk. +pub fn whole(t: *const Target, st: *const State) bool { + return probed(t, st) and (t.keeper == null or st.draft != null); +} + +pub fn drafts(_: *const Target) bool { + return false; // the probe hashes the target's rows; a drafter's checkpoint is in the key (promptHash) +} + +pub fn context(t: *const Target) usize { + return t.m.context; +} + +pub fn save(t: *Target, s: *lanes.Stream, at: u32) !*State { + return t.saveState(s, at); +} + +pub fn drop(t: *Target, st: *State) void { + t.dropState(st); +} + +/// The KV form past what the probe shows: the layers' rows, a ring's keys, pages or whole caches, a drafter's context. +pub fn facts(t: *const Target) [5]u64 { + const m = t.m; + var h = std.hash.Wyhash.init(0x6734); + const layers = fwd.pages.ownLayers(m); + for (0..layers) |i| h.update(std.mem.asBytes(&[_]u64{ snap.rowBytes(m, i), @intFromBool(cfg.global(i)) })); + return .{ layers, h.final(), cfg.window, @intFromBool(m.paged), @intFromBool(t.keeper != null) }; +} + +const testing = std.testing; + +const Piece = struct { bytes: u64, row: u32 = 0 }; + +const Offsets = struct { + ends: *std.ArrayList(u64), + fn add(c: Offsets, _: u64, off: usize, len: usize) anyerror!void { + try c.ends.append(testing.allocator, off + len); + } +}; + +fn model(m: *fwd.Model, k: []u64, v: []u64) void { + m.geo = cfg.unified12b; + m.layers = 6; // layer 5 is global + m.context = 4096; + m.paged = false; + m.kc = k; + m.vc = v; +} + +test "Gemma disk: the parts are snap.each's layers in its order, and a part's bytes are its copies'" { + var k = [_]u64{ 1 << 30, 2 << 30, 3 << 30, 4 << 30, 5 << 30, 6 << 30 }; + var v = [_]u64{ 7 << 30, 8 << 30, 9 << 30, 10 << 30, 11 << 30, 12 << 30 }; + var m: fwd.Model = undefined; + model(&m, &k, &v); + var t: Target = undefined; + t.m = &m; + t.keeper = null; + for ([_]u32{ 1, 1023, 1024, 2000, 4000 }) |at| { + var list: std.ArrayList(Piece) = .empty; + defer list.deinit(testing.allocator); + try parts(&t, at, &list, testing.allocator); + var ends: std.ArrayList(u64) = .empty; + defer ends.deinit(testing.allocator); + try snap.each(&m, 0, at, 0, Offsets{ .ends = &ends }, Offsets.add); + var off: u64 = 0; + for (list.items) |p| { + off += p.bytes; + try testing.expect(std.mem.indexOfScalar(u64, ends.items, off) != null); // a part ends where a copy does + } + try testing.expectEqual(snap.bytes(&m, at), off); + } +} + +const Draft = struct { + fn bytes(_: *anyopaque, at: usize) u64 { + return at * 64; + } + fn keep(_: *anyopaque, _: *const lanes.Stream, _: *snap.Saved) anyerror!void {} +}; + +test "Gemma disk: images and a missing drafter context stay off disk; a drafter or paging is another key" { + var k: [6]u64 = @splat(0); + var m: fwd.Model = undefined; + model(&m, &k, &k); + var t: Target = undefined; + t.m = &m; + t.keeper = null; + var st: State = .{ .at = 8, .buf = undefined }; + try testing.expect(whole(&t, &st)); + st.images = true; + try testing.expect(!whole(&t, &st)); + st.images = false; + const base = facts(&t); + var ctx: u8 = 0; + t.keeper = .{ .ctx = &ctx, .bytes = Draft.bytes, .keep = Draft.keep }; + try testing.expect(!whole(&t, &st) and probed(&t, &st)); // a kept state needs its drafter's context, a probe not + var list: std.ArrayList(Piece) = .empty; + defer list.deinit(testing.allocator); + try parts(&t, 8, &list, testing.allocator); + try testing.expectEqual(@as(u64, 8 * 64), list.items[list.items.len - 1].bytes); + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); + t.keeper = null; + m.paged = true; + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); +} diff --git a/zig/src/families/gemma4/cuda_native.zig b/zig/src/families/gemma4/cuda_native.zig index f9e7d135b6c..9678ae00f75 100644 --- a/zig/src/families/gemma4/cuda_native.zig +++ b/zig/src/families/gemma4/cuda_native.zig @@ -23,6 +23,7 @@ pub fn Family(comptime name: []const u8) type { pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; pub const snap_lookahead: u32 = 0; + pub const kept_view = @import("cuda_disk.zig"); // the disk store's image (native/cuda_kept.zig) pub const share_grid: u32 = be.prompt_rows; pub const window_rows: u32 = be.max_window; pub const attach = native.attach; diff --git a/zig/src/families/gemma4/cuda_snap.zig b/zig/src/families/gemma4/cuda_snap.zig index fca535a0a18..261fffc69f8 100644 --- a/zig/src/families/gemma4/cuda_snap.zig +++ b/zig/src/families/gemma4/cuda_snap.zig @@ -12,6 +12,7 @@ pub const Saved = struct { blob: []u32 = &.{}, // the copied rows in pages the store holds (TF_KV_SHARE), else in `buf` buf: cuda.DeviceBuffer, draft: ?cuda.DeviceBuffer = null, + images: bool = false, // its prompt held an image before `at`: RAM alone tells which one fn copyTo(k: *const Saved, m: *const fwd.Model, s: cuda.Stream, out: bool) Copy { if (k.blob.len > 0) return .{ .m = m, .s = s, .blob = .{ .ids = k.blob, .chunk = chunk(m), .regions = regions(m) }, .out = out }; @@ -20,11 +21,11 @@ pub const Saved = struct { }; /// Positions a sliding layer keeps at `at`: the keys the next row's window reaches back to. -fn tail(at: usize) usize { +pub fn tail(at: usize) usize { return @min(at, cfg.window - 1); } -fn rowBytes(m: *const fwd.Model, i: usize) usize { +pub fn rowBytes(m: *const fwd.Model, i: usize) usize { return m.geo.kvHeads(i) * cfg.headDim(i) * 2; } @@ -36,7 +37,7 @@ pub fn copyBytes(m: *const fwd.Model, at: usize, from: usize) u64 { } /// Each layer's cache, K then V, positions [first, at) of `slot` (full: from `from`), one copy a run, in order. -fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { +pub fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { if (from > 0 and (!m.paged or from % fwd.pages.tokens != 0 or from > at)) return error.KeptPagesUnpaged; var off: usize = 0; for (0..fwd.pages.ownLayers(m)) |i| for ([_][]u64{ m.kc, m.vc }) |cache| { @@ -113,6 +114,16 @@ pub fn blobPages(m: *const fwd.Model, at: usize, from: usize) usize { return Blob.pagesFor(copyBytes(m, at, from), chunk(m), regions(m)); } +/// A state of `at` positions in buffers of its own, `draft` bytes of drafter context: the disk store fills them. +pub fn blank(gpa: std.mem.Allocator, m: *const fwd.Model, at: u32, draft: u64) !*Saved { + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .buf = try cuda.DeviceBuffer.alloc(m.d, copyBytes(m, at, 0)) }; + errdefer k.buf.free(); + if (draft > 0) k.draft = try cuda.DeviceBuffer.alloc(m.d, draft); + return k; +} + /// Copy `slot`'s state at `at` (full layers from `from`) to new storage or `blob`'s pages, queued after its chunk. pub fn saveShared(gpa: std.mem.Allocator, m: *const fwd.Model, s: cuda.Stream, slot: usize, at: u32, from: u32, blob: []u32) !*Saved { if (at == 0 or at > m.context) return error.NotAtMark; diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 289b73ef742..3d82d04f024 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -544,6 +544,7 @@ test { _ = drafted; _ = cuda_disk; // its tests run under test-cuda-disk-open-host's filter _ = @import("cuda_disk_identity_test.zig"); + _ = @import("cuda_kept.zig"); } test "Learner ownership: actual native close drains Nemotron before any source, trainer or parent free" { try @import("nemotron_trainer_test.zig").run(Host, Host.serve, Host.close, false); diff --git a/zig/src/native/cuda_disk.zig b/zig/src/native/cuda_disk.zig index 0c6c03d8219..7ae164000f4 100644 --- a/zig/src/native/cuda_disk.zig +++ b/zig/src/native/cuda_disk.zig @@ -125,9 +125,10 @@ pub fn keptKey(comptime K: type, a: Allocator, io: std.Io, g: *const cuda.Contex const facts = K.facts(owner); // an array, or a slice const list: []const u64 = if (@typeInfo(@TypeOf(facts)) == .pointer) facts else &facts; const id = try identityOf(a, io, g, dir, kernels, list, probed, profile); - if (comptime !@hasDecl(K, "policy")) return id; - const resolved = K.policy(owner); - return persistence_policy.extend(id, K.policy_domain, &resolved); + const P = if (@hasDecl(K, "view")) K.view else K; // a kept image's family declares its policy in its view + if (comptime !@hasDecl(P, "policy")) return id; + const resolved = P.policy(owner); + return persistence_policy.extend(id, P.policy_domain, &resolved); } /// The identity's hash: the checkpoint, kernels, device, driver, a family's facts, then its probe's hash. @@ -233,6 +234,7 @@ pub fn attach(a: Allocator, io: std.Io, ctx: *const cuda.Context, o: api.Open, r /// The disk module of a family's kept states (image, probe, facts), or null: Nemotron's is this file's own. pub fn keptDisk(comptime F: type) ?type { + if (@hasDecl(F, "kept_view")) return @import("cuda_kept.zig").Kept(F.kept_view); return if (@hasDecl(F, "kept_disk")) F.kept_disk else null; } @@ -243,7 +245,10 @@ pub fn attachKept(comptime K: type, name: []const u8, a: Allocator, io: std.Io, if (@hasDecl(K, "bind")) K.bind(loaded.target, ctx); // the context the store's copies make current const p = try K.probe(a, io, loaded.backend, loaded.target); const staging = stagingOf(K, loaded.target); - try open(o, root, try keptKey(K, a, io, ctx, o.dir, kernels, loaded.target, p.hash, .{ .family = name, .backend = "cuda" }), p.rate, store, name, staging); + const id = try keptKey(K, a, io, ctx, o.dir, kernels, loaded.target, p.hash, .{ .family = name, .backend = "cuda" }); + // a kept image's key also binds the prompt's files and a drafter's checkpoint (native/cuda_kept.zig) + const key = if (comptime @hasDecl(K, "prompted")) try K.prompted(a, io, o, id) else id; + try open(o, root, key, p.rate, store, name, staging); } } diff --git a/zig/src/native/cuda_disk_policy_test.zig b/zig/src/native/cuda_disk_policy_test.zig index bfb77eb73b6..7e40928407a 100644 --- a/zig/src/native/cuda_disk_policy_test.zig +++ b/zig/src/native/cuda_disk_policy_test.zig @@ -132,7 +132,7 @@ const flash = @import("flashnext").native; fn flashKey(x: *Fixture, c: *flash.Cuda) !u64 { const g = x.gpu(); const profile: @import("disk_identity.zig").Profile = .{ .family = flash.model_type, .backend = "cuda" }; - return disk.keptKey(flash.kept_disk, x.arena.allocator(), t.io, &g, x.dir, null, @as(*anyopaque, c), 42, profile); + return disk.keptKey(disk.keptDisk(flash).?, x.arena.allocator(), t.io, &g, x.dir, null, @as(*anyopaque, c), 42, profile); } test "disk identity: Flash Next CUDA resolved prompt rows, kernel forms and expert grids miss with the same probe" { diff --git a/zig/src/native/cuda_kept.zig b/zig/src/native/cuda_kept.zig new file mode 100644 index 00000000000..7ba1a853416 --- /dev/null +++ b/zig/src/native/cuda_kept.zig @@ -0,0 +1,218 @@ +//! Kept states in device buffers on disk (--learn-conversations): one image, its copies, probe and identity facts. +const std = @import("std"); +const cuda = @import("cuda"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const disk_identity = @import("disk_identity.zig"); +const rows = api.prompt_cache.rows; +const Allocator = std.mem.Allocator; + +/// What the prompt's tokens came from, beside the weights the checkpoint's stamps bind. +const prompt_files = [_][]const u8{ + "tokenizer.json", + "tokenizer_config.json", + "tokenizer.model", + "chat_template.jinja", + "chat_template.json", +}; + +/// The words of a state that holds nothing but its position (and its family's Words otherwise). +const Position = extern struct { at: u64, pad: u64 = 0 }; + +/// The tokenizer's and template's bytes, then the drafter's checkpoint: what a family's image cannot show. +pub fn promptHash(a: Allocator, io: std.Io, dir: []const u8, drafter: ?[]const u8) !u64 { + var h = std.hash.Wyhash.init(0x6b70); + for (prompt_files) |name| { + const path = try std.fs.path.join(a, &.{ dir, name }); + defer a.free(path); + const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 28)) catch |e| switch (e) { + error.FileNotFound => continue, + else => return e, + }; + defer a.free(bytes); + h.update(name); + h.update(bytes); + } + if (drafter) |d| try disk_identity.checkpoint(&h, a, io, d); + return h.final(); +} + +/// The disk tier of a family's `View`: its target, state type, buffers, parts, blank and facts (kept_view). +pub fn Kept(comptime V: type) type { + return struct { + const Target = V.Target; + const State = V.State; + const Words = if (@hasDecl(V, "Words")) V.Words else Position; + const words = @sizeOf(Words); + + pub const image: rows.Image = .{ + .parts = parts, + .gather = gather, + .blank = blank, + .scatter = scatter, + .whole = if (@hasDecl(V, "whole")) whole else null, + }; + /// A family that splits over ranks keeps one rank's states: --tp refuses --learn-conversations. + pub const one_rank = @hasDecl(V, "one_rank") and V.one_rank; + + fn of(ptr: *anyopaque) *Target { + return @ptrCast(@alignCast(ptr)); + } + + fn driver(t: *Target) *const cuda.Driver { + return if (@hasDecl(V, "driver")) V.driver(t) else t.d; + } + + fn stream(t: *Target) cuda.Stream { + return if (@hasDecl(V, "stream")) V.stream(t) else t.s; + } + + fn wordsOf(st: *const State) Words { + return if (@hasDecl(V, "wordsOf")) V.wordsOf(st) else .{ .at = st.at }; + } + + /// A state read back stands where it was kept: else it restores nowhere. + fn setWords(st: *State, w: Words) !void { + if (@hasDecl(V, "setWords")) return V.setWords(st, w); + if (w.at != st.at) return error.KeptWordsDiffer; + } + + const Parts = std.ArrayList(rows.image.Part); + const Ranges = []const rows.image.Range; + const Saved = api.prompt_cache.Saved; + + fn parts(ptr: *anyopaque, at: u32, out: *Parts, a: Allocator) anyerror!void { + try out.append(a, .{ .bytes = words }); + try V.parts(of(ptr), at, out, a); + } + + /// Image ranges between `host` and the state's buffers; `host` is the store's: every copy lands before return. + fn copy(t: *Target, st: *State, ranges: Ranges, host: []u8, out: bool) !void { + const d = driver(t); + const s = stream(t); + // a later range's failure leaves earlier copies queued on `host`, which its caller then frees or reuses + errdefer cuda.completion.drain(d, s, "a failed kept-state copy did not drain"); + const bufs = V.buffers(st); + const first: usize = if (bufs[0]) |b| b.len else 0; + const held = first + if (bufs[1]) |b| b.len else 0; + var w = wordsOf(st); + var o: usize = 0; + for (ranges) |g| { + var off: usize = @intCast(g.off); + var len: usize = @intCast(g.len); + if (off + len > words + held) return error.BadKeptRange; + if (off < words) { + const n = @min(len, words - off); + const bytes = std.mem.asBytes(&w)[off..][0..n]; + if (out) @memcpy(host[o..][0..n], bytes) else @memcpy(bytes, host[o..][0..n]); + o += n; + off += n; + len -= n; + } + while (len > 0) { + const in = off - words; + const b = (if (in < first) bufs[0] else bufs[1]).?; + const at = if (in < first) in else in - first; + const n = @min(len, b.len - at); + const h = host[o..].ptr; + if (out) { + try d.check(d.api.cuMemcpyDtoHAsync_v2(h, b.ptr + at, n, s.handle), "cuMemcpyDtoHAsync"); + } else try d.check(d.api.cuMemcpyHtoDAsync_v2(b.ptr + at, h, n, s.handle), "cuMemcpyHtoDAsync"); + o += n; + off += n; + len -= n; + } + } + try s.synchronize(); + if (!out) try setWords(st, w); + } + + fn gather(ptr: *anyopaque, saved: Saved, ranges: Ranges, out: []u8) anyerror!void { + try copy(of(ptr), @ptrCast(@alignCast(saved)), ranges, out, true); + } + + fn scatter(ptr: *anyopaque, saved: Saved, ranges: Ranges, in: []const u8) anyerror!void { + try copy(of(ptr), @ptrCast(@alignCast(saved)), ranges, @constCast(in), false); + } + + fn blank(ptr: *anyopaque, at: u32) anyerror!Saved { + return @ptrCast(try V.blank(of(ptr), at)); + } + + fn whole(ptr: *anyopaque, saved: Saved) bool { + return V.whole(of(ptr), @ptrCast(@alignCast(saved))); + } + + /// Whether a probe's state is one to hash (a family's draft context is absent from a probe, which drafts none). + fn probed(t: *Target, st: *const State) bool { + if (@hasDecl(V, "probed")) return V.probed(t, st); + return if (@hasDecl(V, "whole")) V.whole(t, st) else true; + } + + /// A fixed prompt's state at a mark inside its last chunk, hashed, and the prompt rate it took. + pub fn probe(a: Allocator, io: std.Io, backend: anytype, ptr: anytype) !struct { hash: u64, rate: f64 } { + const t: *Target = @ptrCast(@alignCast(ptr)); // Flash Next's is opaque + var toks: [4096 + 40 + 7]u32 = undefined; + for (&toks, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + const count = if (@hasDecl(V, "context")) @min(toks.len, V.context(t) / 2) else toks.len; + const Hook = struct { + t: *Target, + saved: ?*State = null, + failed: ?anyerror = null, + fn at(p: *anyopaque, s: *lanes.Stream, mark: u32) void { + const h: *@This() = @ptrCast(@alignCast(p)); + h.saved = V.save(h.t, s, mark) catch |e| { + h.failed = e; + return; + }; + } + }; + var hook: Hook = .{ .t = t }; + defer if (hook.saved) |saved| V.drop(t, saved); + const marks = [_]u32{@intCast(count - 7)}; + var s = try lanes.Stream.init(a, .{ + .id = "probe", + .prompt = toks[0..count], + .max_new = 1, + .drafts = V.drafts(t), + .reuse = .{ .marks = &marks, .hook = .{ .ptr = &hook, .at = Hook.at } }, + }); + defer s.deinit(a); + const ns = pass: { + defer backend.vtable.release(backend.ptr, &s); // once, whether the pass, its wait or nothing failed + const t0 = std.Io.Clock.awake.now(io).toNanoseconds(); + try backend.vtable.prefill(backend.ptr, &s); + try stream(t).synchronize(); + break :pass std.Io.Clock.awake.now(io).toNanoseconds() - t0; + }; + const st = hook.saved orelse return hook.failed orelse error.ProbeUnmarked; + if (!probed(t, st)) return error.ProbeUnmarked; + const bufs = V.buffers(st); + const held = (if (bufs[0]) |b| b.len else 0) + (if (bufs[1]) |b| b.len else 0); + const bytes = try a.alloc(u8, words + held); + defer a.free(bytes); + try copy(t, st, &.{.{ .off = 0, .len = bytes.len }}, bytes, true); + const seconds = @as(f64, @floatFromInt(@max(ns, 1))) / 1e9; + const rate = @as(f64, @floatFromInt(count)) / seconds; + return .{ .hash = std.hash.Wyhash.hash(V.probe_seed, bytes), .rate = rate }; + } + + /// What the states depend on past the image and the probe: the family's KV form (keptKey). + pub fn facts(ptr: anytype) @typeInfo(@TypeOf(V.facts)).@"fn".return_type.? { + return V.facts(@as(*Target, @ptrCast(@alignCast(ptr)))); + } + + /// The family's view: keptKey reads its policy there when it declares one. + pub const view = V; + + /// `id` extended with promptHash: what the prompt's tokens came from, which the image cannot show. + pub fn prompted(a: Allocator, io: std.Io, o: api.Open, id: u64) !u64 { + const ph = [_]u64{try promptHash(a, io, o.dir, o.drafter)}; + return @import("persistence_policy.zig").extend(id, "kept-prompt-v1", &ph); + } + }; +} + +test { + _ = @import("cuda_kept_test.zig"); +} diff --git a/zig/src/native/cuda_kept_test.zig b/zig/src/native/cuda_kept_test.zig new file mode 100644 index 00000000000..a22bcfbfed2 --- /dev/null +++ b/zig/src/native/cuda_kept_test.zig @@ -0,0 +1,300 @@ +//! The shared kept image over a driver whose device memory is host memory, each family's view, and stale identities. +const std = @import("std"); +const cuda = @import("cuda"); +const api = @import("engine_api"); +const kept = @import("cuda_kept.zig"); +const disk = @import("cuda_disk.zig"); +const rows = api.prompt_cache.rows; +const t = std.testing; + +/// Device addresses are host addresses; a copy lands at once; `refuse` fails the next copy past `allowed`. +const Host = struct { + var allowed: usize = std.math.maxInt(usize); + var copies: usize = 0; + var pending: usize = 0; + fn queue() bool { + if (copies == allowed) return false; + copies += 1; + pending += 1; + return true; + } + fn toHost(out: ?*anyopaque, dev: u64, n: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + if (!queue()) return cuda.abi.error_not_ready; // check() returns NotReady for it, logging nothing + const p: [*]const u8 = @ptrFromInt(dev); + @memcpy(@as([*]u8, @ptrCast(out.?))[0..n], p[0..n]); + return cuda.abi.success; + } + fn toDevice(dev: u64, in: ?*const anyopaque, n: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + if (!queue()) return cuda.abi.error_not_ready; + const p: [*]u8 = @ptrFromInt(dev); + @memcpy(p[0..n], @as([*]const u8, @ptrCast(in.?))[0..n]); + return cuda.abi.success; + } + fn sync(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + pending = 0; + return cuda.abi.success; + } + fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.api.cuMemcpyDtoHAsync_v2 = toHost; + d.api.cuMemcpyHtoDAsync_v2 = toDevice; + d.api.cuStreamSynchronize = sync; + return d; + } +}; + +/// A family with a target's rows and a second buffer, as Gemma's drafter context. +const View = struct { + pub const Target = struct { + d: *const cuda.Driver, + s: cuda.Stream, + gpa: std.mem.Allocator = t.allocator, + restored: u32 = 0, + }; + pub const State = struct { at: u32, one: cuda.DeviceBuffer, two: ?cuda.DeviceBuffer }; + pub const probe_seed: u64 = 1; + pub fn buffers(st: *const State) [2]?cuda.DeviceBuffer { + return .{ st.one, st.two }; + } + pub fn facts(_: *const Target) [2]u64 { + return .{ 3, 4 }; + } + pub fn parts(_: *const Target, at: u32, out: anytype, a: std.mem.Allocator) !void { + try out.append(a, .{ .bytes = @as(u64, at) * 8, .row = 8 }); + try out.append(a, .{ .bytes = 32 }); + } + pub fn blank(x: *Target, at: u32) !*State { + const st = try x.gpa.create(State); + const rows_ = try x.gpa.alloc(u8, one(at)); + st.* = .{ .at = at, .one = buffer(x.d, rows_), .two = buffer(x.d, try x.gpa.alloc(u8, 32)) }; + return st; + } + fn one(at: u32) usize { + return @as(usize, at) * 8; + } +}; + +/// The store's copies of `View`: a state's rows are its position's, so a state read back shows it was read. +const Copies = struct { + fn of(p: *anyopaque) *View.Target { + return @ptrCast(@alignCast(p)); + } + fn state(p: api.prompt_cache.Saved) *View.State { + return @ptrCast(@alignCast(p)); + } + fn bytes(_: *anyopaque, at: u32) u64 { + return View.one(at) + 32; + } + fn save(p: *anyopaque, _: ?*anyopaque, at: u32) anyerror!api.prompt_cache.Saved { + const st = try View.blank(of(p), at); + for (hostOf(st.one), 0..) |*x, i| x.* = @truncate(i *% 31); + @memset(hostOf(st.two.?), 9); + return st; + } + fn restore(p: *anyopaque, _: ?*anyopaque, saved: api.prompt_cache.Saved) anyerror!void { + of(p).restored = state(saved).at; + for (hostOf(state(saved).one), 0..) |x, i| try t.expectEqual(@as(u8, @truncate(i *% 31)), x); + } + fn drop(p: *anyopaque, saved: api.prompt_cache.Saved) void { + const st = state(saved); + of(p).gpa.free(hostOf(st.one)); + of(p).gpa.free(hostOf(st.two.?)); + of(p).gpa.destroy(st); + } + const vtable: api.prompt_cache.Snapshots.VTable = .{ + .bytes = bytes, + .save = save, + .restore = restore, + .drop = drop, + .rows = &K.image, + }; +}; + +const K = kept.Kept(View); + +fn hostOf(b: cuda.DeviceBuffer) []u8 { + const p: [*]u8 = @ptrFromInt(b.ptr); + return p[0..b.len]; +} + +fn buffer(d: *const cuda.Driver, bytes: []u8) cuda.DeviceBuffer { + return .{ .d = d, .ptr = @intFromPtr(bytes.ptr), .len = bytes.len, .borrowed = true }; +} + +test "CUDA kept: an image's ranges cross the words and both buffers, and read back equal" { + var d = Host.driver(); + var target: View.Target = .{ .d = &d, .s = .{ .d = &d, .handle = @ptrFromInt(331) } }; + var a: [32]u8 = undefined; + var b: [32]u8 = undefined; + for (&a, &b, 0..) |*x, *y, i| { + x.* = @intCast(i); + y.* = @intCast(100 + i); + } + var st: View.State = .{ .at = 4, .one = buffer(&d, &a), .two = buffer(&d, &b) }; + Host.allowed = std.math.maxInt(usize); + var host: [16 + 64]u8 = undefined; + const all = [_]rows.image.Range{.{ .off = 0, .len = host.len }}; + try K.image.gather(&target, &st, &all, &host); + try t.expectEqual(@as(u64, 4), std.mem.readInt(u64, host[0..8], .little)); + try t.expectEqualSlices(u8, &a, host[16..48]); + try t.expectEqualSlices(u8, &b, host[48..80]); + @memset(&a, 0); + @memset(&b, 0); + const split = [_]rows.image.Range{ .{ .off = 40, .len = 40 }, .{ .off = 0, .len = 40 } }; + var parted: [80]u8 = undefined; + @memcpy(parted[0..40], host[40..80]); + @memcpy(parted[40..80], host[0..40]); + try K.image.scatter(&target, &st, &split, &parted); + try t.expectEqualSlices(u8, host[16..48], &a); + try t.expectEqualSlices(u8, host[48..80], &b); +} + +test "CUDA kept: a state whose words stand elsewhere is refused as a bad file" { + var d = Host.driver(); + var target: View.Target = .{ .d = &d, .s = .{ .d = &d, .handle = @ptrFromInt(331) } }; + var a: [32]u8 = undefined; + var st: View.State = .{ .at = 4, .one = buffer(&d, &a), .two = null }; + var host: [16]u8 = @splat(0); + host[0] = 5; + try t.expectError(error.KeptWordsDiffer, K.image.scatter(&target, &st, &.{.{ .off = 0, .len = 16 }}, &host)); +} + +test "Flash Next completion: a kept state's copy out or in that fails part way drains the copies it queued" { + var d = Host.driver(); + var target: View.Target = .{ .d = &d, .s = .{ .d = &d, .handle = @ptrFromInt(331) } }; + var a: [1024]u8 = undefined; + var st: View.State = .{ .at = 0, .one = buffer(&d, &a), .two = null }; + var host: [16 + 1024]u8 = @splat(0); + // the words and half the state queue a copy; the driver refuses the other half, or that range runs past the state + for ([_]bool{ true, false }) |refused| for ([_]bool{ true, false }) |out| { + Host.copies = 0; + Host.pending = 0; + Host.allowed = 1; + defer Host.allowed = std.math.maxInt(usize); + const second: u64 = if (refused) 512 else 1024; + const ranges = [_]rows.image.Range{ .{ .off = 0, .len = 16 + 512 }, .{ .off = 16 + 512, .len = second } }; + const image = K.image; + const got = if (out) + image.gather(&target, &st, &ranges, &host) + else + image.scatter(&target, &st, &ranges, &host); + try t.expectError(if (refused) error.NotReady else error.BadKeptRange, got); + try t.expectEqual(@as(usize, 1), Host.copies); + try t.expectEqual(@as(usize, 0), Host.pending); // the caller's `host` may go: nothing copies on it + }; +} + +test "CUDA kept: another tokenizer, template or drafter moves the key, a missing file does not fail" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + const bare = try kept.promptHash(a, t.io, dir, null); + try tmp.dir.writeFile(t.io, .{ .sub_path = "chat_template.jinja", .data = "one" }); + const template = try kept.promptHash(a, t.io, dir, null); + try t.expect(bare != template); + try tmp.dir.writeFile(t.io, .{ .sub_path = "chat_template.jinja", .data = "two" }); + try t.expect(template != try kept.promptHash(a, t.io, dir, null)); + const same = try kept.promptHash(a, t.io, dir, null); + try tmp.dir.writeFile(t.io, .{ .sub_path = "tokenizer.json", .data = "{}" }); + try t.expect(same != try kept.promptHash(a, t.io, dir, null)); + const plain = try kept.promptHash(a, t.io, dir, null); + (try tmp.dir.createDirPathOpen(t.io, "draft", .{})).close(t.io); + try tmp.dir.writeFile(t.io, .{ .sub_path = "draft/config.json", .data = "{}" }); + const drafted = try kept.promptHash(a, t.io, dir, try std.fs.path.join(a, &.{ dir, "draft" })); + try t.expect(plain != drafted); +} + +const Recording = struct { + fn name(out: [*]u8, _: c_int, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + @memcpy(out[0..5], "fake\x00"); + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 12; + return 0; + } + fn version(out: *c_int) callconv(.c) cuda.abi.Result { + out.* = 13000; + return 0; + } +}; + +const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .min_prompt = 0, .min_gap = 1 }; + +/// One turn of `prompt` through a store under `id`: where it resumes, its state written once it keeps one. +fn turn(a: std.mem.Allocator, root: []const u8, id: u64, target: *View.Target, prompt: []const u32, history: u32) !u32 { + const copies: api.prompt_cache.Snapshots = .{ .ptr = target, .vtable = &Copies.vtable }; + const cap: u64 = 1 << 34; + const options: rows.Options = .{ + .sync_writes = true, + .root = root, + .identity = id, + .cap = cap, + .floor = 0, + .daily = cap, + }; + const r = try rows.Rows.open(t.allocator, copies, options); + defer r.deinit(); + var s = api.prompt_cache.Store.init(t.allocator, copies, rules, 1 << 30); + defer s.deinit(); + s.disk = r; + const plan = try s.begin(a, prompt, history, &.{}, &.{}, null, &.{}); + for (plan.marks) |mark| if (mark > plan.from) { + _ = s.keep(prompt, mark, null, &.{}, &.{}); + }; + while (rows.write.step(r)) {} + return plan.from; +} + +test "CUDA kept: a saved state resumes under its own key, and a stale key misses and leaves it for its own" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = "{}" }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "chat_template.jinja", .data = "one" }); + const root = try std.fs.path.join(a, &.{ dir, "states" }); + var d = Host.driver(); + d.api.cuDeviceGetName = Recording.name; + d.api.cuDeviceGetAttribute = Recording.attribute; + d.api.cuDriverGetVersion = Recording.version; + const gpu: cuda.Context = .{ .d = &d, .device = 0, .handle = null }; + const key = struct { + fn of(arena_: std.mem.Allocator, g: *const cuda.Context, folder: []const u8, form: u64) !u64 { + const facts = [_]u64{ form, try kept.promptHash(arena_, t.io, folder, null) }; + const profile: @import("disk_identity.zig").Profile = .{ .family = "dory", .backend = "cuda" }; + return disk.identityOf(arena_, t.io, g, folder, null, &facts, 42, profile); + } + }.of; + const id = try key(a, &gpu, dir, 1); + var target: View.Target = .{ .d = &d, .s = .{ .d = &d, .handle = @ptrFromInt(331) } }; + const first = try a.alloc(u32, 1500); + for (first, 0..) |*x, i| x.* = @intCast(1000 + i); + const second = try std.mem.concat(a, u32, &.{ first[0..1401], &[_]u32{ 9, 8, 7, 6 } }); + try t.expectEqual(@as(u32, 0), try turn(a, root, id, &target, first, 1400)); + try t.expectEqual(@as(u32, 1400), try turn(a, root, id, &target, second, 1404)); + try t.expectEqual(@as(u32, 1400), target.restored); + target.restored = 0; + // another KV form, then another template: each its own namespace, a cold pass, the old state unread + try t.expectEqual(@as(u32, 0), try turn(a, root, try key(a, &gpu, dir, 2), &target, second, 1404)); + try tmp.dir.writeFile(t.io, .{ .sub_path = "chat_template.jinja", .data = "two" }); + const moved = try key(a, &gpu, dir, 1); + try t.expect(moved != id); + try t.expectEqual(@as(u32, 0), try turn(a, root, moved, &target, second, 1404)); + try t.expectEqual(@as(u32, 0), target.restored); + // its own key still resumes, at the state the second turn kept + try t.expectEqual(@as(u32, 1404), try turn(a, root, id, &target, second, 1404)); +} + +test "CUDA kept: Gemma 4 takes the store, a family without a view still refuses" { + const gemma = @import("gemma4_cuda"); + inline for (.{ gemma.native, gemma.native31 }) |F| try t.expect(comptime disk.keptDisk(F) != null); + const open: api.Open = .{ .dir = "d", .model_type = "gemma4", .learn_conversations = true }; + try t.expect(@import("cuda_refusal.zig").family(gemma.native31, open) == null); + try t.expect(comptime disk.keptDisk(@import("kolibri1").native) == null); +} From 357cc06496c82b8b6fa1cc5d2ecca7d477afdfdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:13:55 +0100 Subject: [PATCH 14/89] cuda: Dory and Spark2.5 keep their states on disk (#840) Their views over native/cuda_kept.zig: full caches as block rows, ring tails in the state's own file, the loop count, ring, row and paging in the key. --- docs/api.md | 4 +- zig/src/families/dory/cuda_disk.zig | 118 +++++++++++++++++++++++++ zig/src/families/dory/cuda_native.zig | 1 + zig/src/families/dory/cuda_snap.zig | 12 ++- zig/src/families/dory/dory.zig | 2 + zig/src/families/spark25/cuda_disk.zig | 117 ++++++++++++++++++++++++ zig/src/families/spark25/native.zig | 1 + zig/src/families/spark25/snap.zig | 14 ++- zig/src/families/spark25/spark25.zig | 2 + zig/src/native/cuda_kept_test.zig | 11 ++- zig/src/native/cuda_refusal.zig | 4 +- 11 files changed, 273 insertions(+), 13 deletions(-) create mode 100644 zig/src/families/dory/cuda_disk.zig create mode 100644 zig/src/families/spark25/cuda_disk.zig diff --git a/docs/api.md b/docs/api.md index fcd9adf2593..dfca2a579c0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1339,8 +1339,8 @@ deleted and its tokens are prefilled, and a write cut off midway leaves nothing needs `--spill-gib` or `--learn-conversations`. With `--learn-conversations` too, every state is still written behind, a staged write survives eviction of its RAM entry, and the cap is the smaller of `--learn-gib` and `--spill-gib`. `--learn-min-free-gib` and `--learn-daily-gib` apply to spilled states as well. The same four Mac -families take both flags, and so do three CUDA ones; the others refuse them at startup. Without either flag nothing -changes, and the routes below stay off. `TENSORFOLD_ROWS_SYNC=1` selects the previous synchronous writer for +families take both flags, and so do Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 on CUDA; the +others refuse them at startup. Without either flag nothing changes, and the routes below stay off. `TENSORFOLD_ROWS_SYNC=1` selects the previous synchronous writer for comparisons; its block and state files have the same bytes. That comparison writer retains blocking I/O; the bounded disk wait uses the threaded writer. `TF_IMPRINT_VERIFY=1` reads threaded writes back against their owned staging before publication. diff --git a/zig/src/families/dory/cuda_disk.zig b/zig/src/families/dory/cuda_disk.zig new file mode 100644 index 00000000000..38b1b9d6100 --- /dev/null +++ b/zig/src/families/dory/cuda_disk.zig @@ -0,0 +1,118 @@ +//! Dory's kept states for the disk store (native/cuda_kept.zig): their layout, a blank one, what they are read under. +const std = @import("std"); +const cuda = @import("cuda"); +const be = @import("cuda_backend.zig"); +const snap = @import("cuda_snap.zig"); +const lanes = @import("lanes"); +const Allocator = std.mem.Allocator; + +pub const Target = be.Dory; +pub const State = snap.Saved; +pub const probe_seed: u64 = 0x646f; + +/// Every cache, K then V, as snap.each lays them: a full one's rows from position 0, a ring's tail the state's own. +pub fn parts(t: *const Target, at: u32, out: anytype, a: Allocator) !void { + const m = t.m; + const row = m.c.kvDim() * 2; + for (m.sched.cache_kind[0..m.sched.caches]) |kind| for (0..2) |_| { + if (kind == .full) { + try out.append(a, .{ .bytes = @as(u64, at) * row, .row = @intCast(row) }); + } else try out.append(a, .{ .bytes = snap.tail(m.c.window, at) * row }); + }; +} + +pub fn buffers(st: *const State) [2]?cuda.DeviceBuffer { + return .{ st.buf, null }; +} + +pub fn blank(t: *Target, at: u32) !*State { + return snap.blank(t.gpa, t.m, at); +} + +pub fn drafts(_: *const Target) bool { + return false; // Dory's drafts come from the prompt's text: no head's state +} + +pub fn context(t: *const Target) usize { + return t.m.context; +} + +pub fn save(t: *Target, s: *lanes.Stream, at: u32) !*State { + return t.saveState(s, at); +} + +pub fn drop(t: *Target, st: *State) void { + t.dropState(st); +} + +/// The KV form past what the probe shows: loops and the state key, a ring's keys, a row, pages or whole caches. +pub fn facts(t: *const Target) [5]u64 { + const m = t.m; + const key = snap.keyOf(m.c); + return .{ key.loops, @backingInt(key.mode), m.c.window, m.c.kvDim(), @intFromBool(m.paged) }; +} + +const testing = std.testing; +const fwd = @import("cuda_model.zig"); +const config = @import("config.zig"); + +fn pinned(loops: usize) !config.Config { + const text = try config.pinnedText(testing.allocator); + defer testing.allocator.free(text); + var why: config.Why = .{}; + return (try config.parse(testing.allocator, text, &why)).withLoops(loops); +} + +const Piece = struct { bytes: u64, row: u32 = 0 }; + +const Offsets = struct { + ends: *std.ArrayList(u64), + fn add(c: Offsets, _: u64, off: usize, len: usize) anyerror!void { + try c.ends.append(testing.allocator, off + len); + } +}; + +test "Dory disk: the parts are snap.each's caches in its order, and a part's bytes are its copies'" { + var m: fwd.Model = undefined; + m.c = try pinned(2); + m.sched = @import("schedule.zig").build(m.c); + m.context = 8192; + m.paging = null; + m.ring = fwd.ringSize(fwd.prompt_rows, m.c.window); + var ks: [64]u64 = @splat(1 << 32); + m.k = ks[0..m.sched.caches]; + m.v = ks[0..m.sched.caches]; + var t: Target = undefined; + t.m = &m; + for ([_]u32{ 1, 1023, 1024, 4000, 8000 }) |at| { + var list: std.ArrayList(Piece) = .empty; + defer list.deinit(testing.allocator); + try parts(&t, at, &list, testing.allocator); + var ends: std.ArrayList(u64) = .empty; + defer ends.deinit(testing.allocator); + try snap.each(&m, 0, at, 0, Offsets{ .ends = &ends }, Offsets.add); + var off: u64 = 0; + for (list.items) |p| { + off += p.bytes; + try testing.expect(std.mem.indexOfScalar(u64, ends.items, off) != null); // a part ends where a copy does + } + try testing.expectEqual(snap.bytes(&m, at), off); + } +} + +test "Dory disk: another loop count, ring or paging is another key" { + var m: fwd.Model = undefined; + m.c = try pinned(2); + m.paged = false; + var t: Target = undefined; + t.m = &m; + const base = facts(&t); + m.c = try pinned(4); + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); + m.c = try pinned(2); + m.c.window -= 1; + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); + m.c = try pinned(2); + m.paged = true; + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); +} diff --git a/zig/src/families/dory/cuda_native.zig b/zig/src/families/dory/cuda_native.zig index 91efdffea6b..28dcdd00ab4 100644 --- a/zig/src/families/dory/cuda_native.zig +++ b/zig/src/families/dory/cuda_native.zig @@ -18,6 +18,7 @@ pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; /// A kept state is the caches through its position and nothing past it (no draft head reads a token on). pub const snap_lookahead: u32 = 0; +pub const kept_view = @import("cuda_disk.zig"); // the disk store's image (native/cuda_kept.zig) pub const takes_drafter = false; pub const drafter_refusal = "--drafter: Dory on CUDA loads no drafter; drafts come from the prompt's own text"; pub const explains_open = true; diff --git a/zig/src/families/dory/cuda_snap.zig b/zig/src/families/dory/cuda_snap.zig index 5dbef066ef9..d604ca22ba5 100644 --- a/zig/src/families/dory/cuda_snap.zig +++ b/zig/src/families/dory/cuda_snap.zig @@ -35,7 +35,7 @@ pub const Saved = struct { }; /// Positions a sliding ring keeps at `at`: a later row at `at` or past reads keys from at - window + 1 on. -fn tail(window: usize, at: usize) usize { +pub fn tail(window: usize, at: usize) usize { return @min(at, window - 1); } @@ -77,7 +77,7 @@ fn fullCache(m: *const fwd.Model, j: usize) usize { } /// Each cache, K then V, of `slot`: rings' last rows, full caches' [from, at), one copy a run, in order. -fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { +pub fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { const rb = m.c.kvDim() * 2; var off: usize = 0; for (0..m.sched.caches) |i| for ([_][]u64{ m.k, m.v }) |cache| { @@ -135,6 +135,14 @@ fn pieceAt(m: *const fwd.Model, region: usize, id: u32) u64 { return (if (region % 2 == 0) m.k else m.v)[i] + id * chunk(m); } +/// A state of `at` positions with its storage unset: the disk store fills it (cuda_disk.zig). +pub fn blank(gpa: std.mem.Allocator, m: *const fwd.Model, at: u32) !*Saved { + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .key = keyOf(m.c), .buf = try cuda.DeviceBuffer.alloc(m.d, @max(bytes(m, at), 256)) }; + return k; +} + /// Copy `slot`'s state at `at` into new storage, queued on `s` behind the chunk that ends there. pub fn save(gpa: std.mem.Allocator, m: *const fwd.Model, s: cuda.Stream, slot: usize, at: u32) !*Saved { if (at == 0 or at > m.context) return error.NotAtMark; diff --git a/zig/src/families/dory/dory.zig b/zig/src/families/dory/dory.zig index 53ed0677fb0..6bdf99f1de4 100644 --- a/zig/src/families/dory/dory.zig +++ b/zig/src/families/dory/dory.zig @@ -15,6 +15,7 @@ pub const cuda_pages = @import("cuda_pages.zig"); pub const cuda_run = @import("cuda_run.zig"); /// The native CUDA registry's entry (native/cuda.zig). pub const native = @import("cuda_native.zig"); +pub const cuda_disk = @import("cuda_disk.zig"); test { _ = @import("config.zig"); @@ -27,6 +28,7 @@ test { _ = @import("rope_test.zig"); _ = @import("cuda_kernels.zig"); _ = @import("cuda_backend.zig"); + _ = cuda_disk; _ = @import("cuda_snap.zig"); _ = @import("cuda_pages.zig"); _ = @import("cuda_run.zig"); diff --git a/zig/src/families/spark25/cuda_disk.zig b/zig/src/families/spark25/cuda_disk.zig new file mode 100644 index 00000000000..337902fdfb0 --- /dev/null +++ b/zig/src/families/spark25/cuda_disk.zig @@ -0,0 +1,117 @@ +//! Spark2.5's kept states for the disk store (native/cuda_kept.zig): layout, a blank one, what they are read under. +const std = @import("std"); +const cuda = @import("cuda"); +const be = @import("backend.zig"); +const cfg = @import("config.zig"); +const snap = @import("snap.zig"); +const lanes = @import("lanes"); +const Allocator = std.mem.Allocator; + +pub const Target = be.Spark; +pub const State = snap.Saved; +pub const probe_seed: u64 = 0x7370; + +/// Every layer, K then V, as snap.each lays them: a full one's rows from position 0, a ring's tail the state's own. +pub fn parts(t: *const Target, at: u32, out: anytype, a: Allocator) !void { + const m = t.m; + const row = snap.rowBytes(m); + for (0..m.layers) |i| for (0..2) |_| { + if (cfg.full(i)) { + try out.append(a, .{ .bytes = @as(u64, at) * row, .row = @intCast(row) }); + } else try out.append(a, .{ .bytes = snap.tail(at) * row }); + }; +} + +pub fn buffers(st: *const State) [2]?cuda.DeviceBuffer { + return .{ st.buf, null }; +} + +pub fn blank(t: *Target, at: u32) !*State { + return snap.blank(t.gpa, t.m, at); +} + +/// A state in the store's pages is not this image: TF_KV_SHARE refuses --learn-conversations, so it never comes. +pub fn whole(_: *const Target, st: *const State) bool { + return st.from == 0 and st.blob.len == 0 and st.buf != null; +} + +pub fn drafts(_: *const Target) bool { + return false; // Spark2.5's drafts come from the prompt's text: no head's state +} + +pub fn context(t: *const Target) usize { + return t.m.context; +} + +pub fn save(t: *Target, s: *lanes.Stream, at: u32) !*State { + return t.saveState(s, at); +} + +pub fn drop(t: *Target, st: *State) void { + t.dropState(st); +} + +/// The KV form past what the probe shows: the layers, a row, a ring's keys, pages or whole caches. +pub fn facts(t: *const Target) [4]u64 { + return .{ t.m.layers, snap.rowBytes(t.m), cfg.window, @intFromBool(t.m.paged) }; +} + +const testing = std.testing; +const fwd = @import("forward.zig"); + +const Piece = struct { bytes: u64, row: u32 = 0 }; + +const Offsets = struct { + ends: *std.ArrayList(u64), + fn add(c: Offsets, _: u64, off: usize, len: usize) anyerror!void { + try c.ends.append(testing.allocator, off + len); + } +}; + +test "Spark2.5 disk: the parts are snap.each's layers in its order, and a part's bytes are its copies'" { + var k = [_]u64{ 1 << 30, 2 << 30, 3 << 30, 4 << 30 }; + var v = [_]u64{ 7 << 30, 8 << 30, 9 << 30, 10 << 30 }; + var m: fwd.Model = undefined; + m.geo = cfg.spark4b; + m.layers = 4; // layer 3 is full + m.context = 4096; + m.paged = false; + m.kc = &k; + m.vc = &v; + var t: Target = undefined; + t.m = &m; + for ([_]u32{ 1, 511, 512, 1500, 4000 }) |at| { + var list: std.ArrayList(Piece) = .empty; + defer list.deinit(testing.allocator); + try parts(&t, at, &list, testing.allocator); + var ends: std.ArrayList(u64) = .empty; + defer ends.deinit(testing.allocator); + try snap.each(&m, 0, at, 0, Offsets{ .ends = &ends }, Offsets.add); + var off: u64 = 0; + for (list.items) |p| { + off += p.bytes; + try testing.expect(std.mem.indexOfScalar(u64, ends.items, off) != null); // a part ends where a copy does + } + try testing.expectEqual(snap.bytes(&m, at, 0), off); + } +} + +test "Spark2.5 disk: a state in pages stays off disk; paging or another geometry is another key" { + var m: fwd.Model = undefined; + m.geo = cfg.spark4b; + m.layers = 4; + m.paged = false; + var t: Target = undefined; + t.m = &m; + var ids = [_]u32{0}; + var st: State = .{ .at = 8, .blob = &ids }; + try testing.expect(!whole(&t, &st)); + st.blob = &.{}; + try testing.expect(!whole(&t, &st)); // no buffer either + const base = facts(&t); + m.paged = true; + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); + m.paged = false; + m.layers = 3; + try testing.expect(!std.mem.eql(u64, &base, &facts(&t))); +} diff --git a/zig/src/families/spark25/native.zig b/zig/src/families/spark25/native.zig index f4a26ebbf53..deb0ec3fe4a 100644 --- a/zig/src/families/spark25/native.zig +++ b/zig/src/families/spark25/native.zig @@ -18,6 +18,7 @@ pub const snap_lookahead: u32 = 0; pub const explains_open = true; /// A request's last verify window: its pages hold that many rows past its prompt and reply. pub const window_rows: u32 = be.max_window; +pub const kept_view = @import("cuda_disk.zig"); // the disk store's image (native/cuda_kept.zig) /// The server's reading of the room left after the weights; null if unreadable. pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; diff --git a/zig/src/families/spark25/snap.zig b/zig/src/families/spark25/snap.zig index 330aa28dcb1..6e3a422b592 100644 --- a/zig/src/families/spark25/snap.zig +++ b/zig/src/families/spark25/snap.zig @@ -19,11 +19,11 @@ pub const Saved = struct { }; /// Positions a sliding layer keeps at `at`: the keys the next row's window reaches back to. -fn tail(at: usize) usize { +pub fn tail(at: usize) usize { return @min(at, cfg.window - 1); } -fn rowBytes(m: *const fwd.Model) usize { +pub fn rowBytes(m: *const fwd.Model) usize { return m.geo.kvWidth() * 2; } @@ -35,7 +35,7 @@ pub fn bytes(m: *const fwd.Model, at: usize, from: usize) u64 { } /// Each layer's cache, K then V, positions [first, at) of `slot` (full: from `from`), one copy a run, in order. -fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { +pub fn each(m: *const fwd.Model, slot: usize, at: usize, from: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { if (from > 0 and (!m.paged or from % fwd.page_tokens != 0 or from > at)) return error.KeptPagesUnpaged; var off: usize = 0; const rb = rowBytes(m); @@ -112,6 +112,14 @@ pub fn blobPages(m: *const fwd.Model, at: usize, from: usize) usize { return Blob.pagesFor(bytes(m, at, from), chunk(m), regions(m)); } +/// A state of `at` positions in a buffer of its own: the disk store fills it (cuda_disk.zig). +pub fn blank(gpa: std.mem.Allocator, m: *const fwd.Model, at: u32) !*Saved { + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .buf = try cuda.DeviceBuffer.alloc(m.d, @max(1, bytes(m, at, 0))) }; + return k; +} + /// Copy `slot`'s state at `at` (full layers from `from`) to new storage or `blob`'s pages, queued after its chunk. pub fn save(gpa: std.mem.Allocator, m: *const fwd.Model, s: cuda.Stream, slot: usize, at: u32, from: u32, blob: []u32) !*Saved { if (at == 0 or at > m.context) return error.NotAtMark; diff --git a/zig/src/families/spark25/spark25.zig b/zig/src/families/spark25/spark25.zig index ed92eb5be90..d7798a2b5db 100644 --- a/zig/src/families/spark25/spark25.zig +++ b/zig/src/families/spark25/spark25.zig @@ -6,6 +6,7 @@ pub const forward = @import("forward.zig"); pub const snap = @import("snap.zig"); pub const backend = @import("backend.zig"); pub const native = @import("native.zig"); +pub const cuda_disk = @import("cuda_disk.zig"); test { _ = config; @@ -16,4 +17,5 @@ test { _ = backend; _ = native; _ = @import("prompt_tail.zig"); // which prompt rows the last layer runs + _ = cuda_disk; } diff --git a/zig/src/native/cuda_kept_test.zig b/zig/src/native/cuda_kept_test.zig index a22bcfbfed2..4c1c3e3aa4c 100644 --- a/zig/src/native/cuda_kept_test.zig +++ b/zig/src/native/cuda_kept_test.zig @@ -291,10 +291,13 @@ test "CUDA kept: a saved state resumes under its own key, and a stale key misses try t.expectEqual(@as(u32, 1404), try turn(a, root, id, &target, second, 1404)); } -test "CUDA kept: Gemma 4 takes the store, a family without a view still refuses" { +test "CUDA kept: Gemma 4, Dory and Spark2.5 take the store, a family without a view still refuses" { const gemma = @import("gemma4_cuda"); - inline for (.{ gemma.native, gemma.native31 }) |F| try t.expect(comptime disk.keptDisk(F) != null); - const open: api.Open = .{ .dir = "d", .model_type = "gemma4", .learn_conversations = true }; - try t.expect(@import("cuda_refusal.zig").family(gemma.native31, open) == null); + const dory = @import("dory"); + inline for (.{ gemma.native, gemma.native31, dory.native, @import("spark25").native }) |F| { + try t.expect(comptime disk.keptDisk(F) != null); + } + const open: api.Open = .{ .dir = "d", .model_type = "dory", .learn_conversations = true }; + try t.expect(@import("cuda_refusal.zig").family(dory.native, open) == null); try t.expect(comptime disk.keptDisk(@import("kolibri1").native) == null); } diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index d4a0c2ad3f8..070dd3294bc 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -56,12 +56,12 @@ pub fn family(comptime F: type, o: api.Open) ?[]const u8 { const ranked = @hasDecl(F, "Options") and @hasField(F.Options, "rank"); if (o.tp != 1 and !ranked) return no_ranks; // ahead of the drafter's and --learn-conversations' refusals (--spill-gib sets that flag), on a line of its own - if (o.spill == .evicted and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--spill-gib keeps evicted states on disk for Nemotron, the Qwen hybrids and Flash Next only on CUDA: serve this model without it"; + if (o.spill == .evicted and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--spill-gib keeps evicted states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) { if (@hasDecl(F, "drafter_refusal")) return F.drafter_refusal; // a family without an MTP head says so itself return "--drafter loads a separate drafter, and this CUDA family drafts with its own MTP head: serve without --drafter"; } - if (o.learn_conversations and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, the Qwen hybrids and Flash Next only on CUDA: serve this model without it"; + if (o.learn_conversations and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; if (o.learn_conversations and o.tp > 1) if (@import("cuda_disk.zig").keptDisk(F)) |K| if (@hasDecl(K, "one_rank") and K.one_rank) return "--learn-conversations keeps one rank's states on disk for this CUDA family: serve without --tp or without --learn-conversations"; if (o.kv8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "kv8"))) return "--kv-cache fp8: this CUDA family keeps bf16 caches; serve without it"; if (o.prompt_int8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "prompt_int8"))) return "--prompt-precision int8: this CUDA family's prompt matmuls take bf16 inputs; serve without it"; From 938fe57fa9a6d4901b48748faec70c163153ef81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:48:42 +0100 Subject: [PATCH 15/89] cuda disk: the kept image's tests hang off cuda_disk.zig, cuda.zig stays at 600 lines --- zig/src/native/cuda.zig | 1 - zig/src/native/cuda_disk.zig | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 3d82d04f024..289b73ef742 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -544,7 +544,6 @@ test { _ = drafted; _ = cuda_disk; // its tests run under test-cuda-disk-open-host's filter _ = @import("cuda_disk_identity_test.zig"); - _ = @import("cuda_kept.zig"); } test "Learner ownership: actual native close drains Nemotron before any source, trainer or parent free" { try @import("nemotron_trainer_test.zig").run(Host, Host.serve, Host.close, false); diff --git a/zig/src/native/cuda_disk.zig b/zig/src/native/cuda_disk.zig index 7ae164000f4..287534ff725 100644 --- a/zig/src/native/cuda_disk.zig +++ b/zig/src/native/cuda_disk.zig @@ -274,6 +274,7 @@ fn open(o: api.Open, root: []const u8, id: u64, rate: f64, store: *api.prompt_ca test { std.testing.refAllDecls(@This()); _ = @import("disk_spill.zig"); + _ = @import("cuda_kept.zig"); } test "a disk module that declares attach opens the store itself" { From e864d5b5e58044afbc1a8c791344c201d0f4fe20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:17:38 +0100 Subject: [PATCH 16/89] cuda kept: the store's permit takes a state at the served window, through core's bound (#2388) A Gemma 4 31B state at 9.3k tokens is 1.5 GiB, past the 1 GiB default: every save was skipped as StagingFull. Kept passes the served window as rows.Options.longest, so core prices one whole state within the RAM store's budget. Families without a window (Flash Next) keep the default permit. --- docs/api.md | 21 +++++++------- zig/src/native/cuda_disk.zig | 10 ++++--- zig/src/native/cuda_kept.zig | 6 ++++ zig/src/native/cuda_kept_test.zig | 47 +++++++++++++++++++++++++++++-- 4 files changed, 68 insertions(+), 16 deletions(-) diff --git a/docs/api.md b/docs/api.md index dfca2a579c0..69ab4fb1ba6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1340,16 +1340,17 @@ needs `--spill-gib` or `--learn-conversations`. With `--learn-conversations` too behind, a staged write survives eviction of its RAM entry, and the cap is the smaller of `--learn-gib` and `--spill-gib`. `--learn-min-free-gib` and `--learn-daily-gib` apply to spilled states as well. The same four Mac families take both flags, and so do Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 on CUDA; the -others refuse them at startup. Without either flag nothing changes, and the routes below stay off. `TENSORFOLD_ROWS_SYNC=1` selects the previous synchronous writer for -comparisons; its block and state files have the same bytes. That comparison writer retains blocking I/O; the bounded -disk wait uses the threaded writer. `TF_IMPRINT_VERIFY=1` reads threaded writes back against their owned staging before -publication. - -On CUDA, Nemotron, the Qwen3.5 hybrids and Flash Next take `--spill-gib` and `--checkpoint-slots` with the same store -and cap as a Mac. At an eviction the engine thread stages a copy of the state into host memory, waiting for the GPU -work that produced it, then releases its RAM entry and goes on; the I/O thread writes and fsyncs the copy while the -engine decodes. Staging holds at most 1 GiB and eight jobs: a state whose new bytes (rows neither on disk nor being -written) do not fit what is free is not saved, so one past 1 GiB never is, and a later request for it prefills. When the +others refuse them at startup. Without either flag nothing changes, and the routes below stay off. +`TENSORFOLD_ROWS_SYNC=1` selects the previous synchronous writer for comparisons; its block and state files have the +same bytes. That comparison writer retains blocking I/O; the bounded disk wait uses the threaded writer. +`TF_IMPRINT_VERIFY=1` reads threaded writes back against their owned staging before publication. + +On CUDA, Nemotron, the Qwen3.5 hybrids, Flash Next, Gemma 4, Dory and Spark2.5 take `--spill-gib` and +`--checkpoint-slots` with the same store and cap as a Mac. At an eviction the engine thread stages a copy of the state +into host memory, waiting for the GPU work that produced it, then releases its RAM entry and goes on; the I/O thread +writes and fsyncs the copy while the engine decodes. Staging holds at most 1 GiB and eight jobs; for Gemma 4, Dory and +Spark2.5 it holds one whole state at the served window, within the RAM cache's budget. A state whose new bytes (rows +neither on disk nor being written) do not fit what is free is not saved, and a later request for it prefills. When the engine closes, at a planned stop (SIGTERM or SIGINT) or an idle unload, it saves the states still in RAM, newest first, within the same disk cap and 20-second stop budget. While other streams run, a queued request whose state is on disk has it read ahead on an I/O thread, as described above. diff --git a/zig/src/native/cuda_disk.zig b/zig/src/native/cuda_disk.zig index 287534ff725..39f977862a6 100644 --- a/zig/src/native/cuda_disk.zig +++ b/zig/src/native/cuda_disk.zig @@ -229,7 +229,7 @@ fn probe(a: Allocator, io: std.Io, backend: lanes.backend.Backend, t: *Target) ! pub fn attach(a: Allocator, io: std.Io, ctx: *const cuda.Context, o: api.Open, root: []const u8, kernels: ?[]const u8, loaded: anytype, store: *api.prompt_cache.Store) !void { loaded.target.ctx = ctx; const id = try identity(a, io, ctx, o.dir, kernels, loaded.backend, loaded.target, o.model_type); - try open(o, root, id.id, id.rate, store, "nemotron", null); + try open(o, root, id.id, id.rate, store, "nemotron", null, 0); } /// The disk module of a family's kept states (image, probe, facts), or null: Nemotron's is this file's own. @@ -248,7 +248,8 @@ pub fn attachKept(comptime K: type, name: []const u8, a: Allocator, io: std.Io, const id = try keptKey(K, a, io, ctx, o.dir, kernels, loaded.target, p.hash, .{ .family = name, .backend = "cuda" }); // a kept image's key also binds the prompt's files and a drafter's checkpoint (native/cuda_kept.zig) const key = if (comptime @hasDecl(K, "prompted")) try K.prompted(a, io, o, id) else id; - try open(o, root, key, p.rate, store, name, staging); + const longest: u32 = if (comptime @hasDecl(K, "longest")) K.longest(loaded.target) else 0; + try open(o, root, key, p.rate, store, name, staging, longest); } } @@ -257,7 +258,7 @@ fn stagingOf(comptime K: type, t: anytype) ?u64 { return if (@hasDecl(K, "staging")) K.staging(t) else null; } -fn open(o: api.Open, root: []const u8, id: u64, rate: f64, store: *api.prompt_cache.Store, name: []const u8, staging: ?u64) !void { +fn open(o: api.Open, root: []const u8, id: u64, rate: f64, store: *api.prompt_cache.Store, name: []const u8, staging: ?u64, longest: u32) !void { const gibs = struct { fn bytes(g: f64) u64 { return @intFromFloat(g * (1 << 30)); @@ -266,6 +267,7 @@ fn open(o: api.Open, root: []const u8, id: u64, rate: f64, store: *api.prompt_ca // --spill-gib: evicted states only (or with --learn-conversations, both); --checkpoint-slots bounds RAM beside it var opts: rows.Options = .{ .root = root, .identity = id, .cap = gibs(o.learn_gib), .floor = gibs(o.learn_min_free_gib), .daily = gibs(o.learn_daily_gib), .lookahead = store.rules.lookahead, .planned = store.rules.planned, .grid = store.rules.grid, .spill = o.spill, .slots = @import("disk_spill.zig").slots(o) }; if (staging) |bytes| opts.staging_bytes = bytes; // else the store's own default + opts.longest = longest; // a whole state at the served window: core prices the permit (rows.attach) const r = try rows.attach(store.gpa, store, opts); r.prefill_rate = rate; std.log.info("{s}: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB)", .{ name, r.dir, r.states.items.len, r.held() >> 20, r.cap >> 20 }); @@ -295,7 +297,7 @@ test "CUDA disk open: --spill-gib's mode and --checkpoint-slots reach the store" // a disk module that opens the store itself, through this file's open, under a fixed identity and no device const K = struct { pub fn attach(_: Allocator, _: std.Io, _: *const cuda.Context, o: api.Open, root: []const u8, _: ?[]const u8, _: anytype, store: *api.prompt_cache.Store) !void { - try open(o, root, 7, 1.0, store, "fake", 3 << 30); + try open(o, root, 7, 1.0, store, "fake", 3 << 30, 0); } fn bytes(_: *anyopaque, _: u32) u64 { return 0; diff --git a/zig/src/native/cuda_kept.zig b/zig/src/native/cuda_kept.zig index 7ba1a853416..34b0f51abde 100644 --- a/zig/src/native/cuda_kept.zig +++ b/zig/src/native/cuda_kept.zig @@ -202,6 +202,12 @@ pub fn Kept(comptime V: type) type { return V.facts(@as(*Target, @ptrCast(@alignCast(ptr)))); } + /// The served window, a state the store's permit takes whole (rows.Options.longest); 0: the default permit. + pub fn longest(ptr: anytype) u32 { + if (comptime !@hasDecl(V, "context")) return 0; + return @intCast(V.context(@as(*Target, @ptrCast(@alignCast(ptr))))); + } + /// The family's view: keptKey reads its policy there when it declares one. pub const view = V; diff --git a/zig/src/native/cuda_kept_test.zig b/zig/src/native/cuda_kept_test.zig index 4c1c3e3aa4c..72f8f4cc8a4 100644 --- a/zig/src/native/cuda_kept_test.zig +++ b/zig/src/native/cuda_kept_test.zig @@ -266,9 +266,10 @@ test "CUDA kept: a saved state resumes under its own key, and a stale key misses const gpu: cuda.Context = .{ .d = &d, .device = 0, .handle = null }; const key = struct { fn of(arena_: std.mem.Allocator, g: *const cuda.Context, folder: []const u8, form: u64) !u64 { - const facts = [_]u64{ form, try kept.promptHash(arena_, t.io, folder, null) }; + const facts = [_]u64{form}; const profile: @import("disk_identity.zig").Profile = .{ .family = "dory", .backend = "cuda" }; - return disk.identityOf(arena_, t.io, g, folder, null, &facts, 42, profile); + const id = try disk.identityOf(arena_, t.io, g, folder, null, &facts, 42, profile); + return K.prompted(arena_, t.io, .{ .dir = folder, .model_type = "dory" }, id); // as attachKept extends it } }.of; const id = try key(a, &gpu, dir, 1); @@ -291,6 +292,48 @@ test "CUDA kept: a saved state resumes under its own key, and a stale key misses try t.expectEqual(@as(u32, 1404), try turn(a, root, id, &target, second, 1404)); } +/// `View` at a served window, which the store's permit takes whole. +const Windowed = struct { + pub const Target = View.Target; + pub const State = View.State; + pub const probe_seed = View.probe_seed; + pub const buffers = View.buffers; + pub const facts = View.facts; + pub const parts = View.parts; + pub const blank = View.blank; + pub var window: usize = 0; + pub fn context(_: *const Target) usize { + return window; + } +}; + +test "CUDA kept: core's permit takes a state at the served window whole, within the RAM store's budget" { + var d = Host.driver(); + var target: View.Target = .{ .d = &d, .s = .{ .d = &d, .handle = @ptrFromInt(331) } }; + const W = kept.Kept(Windowed); + try t.expectEqual(@as(u32, 0), K.longest(&target)); // no window declared: the store's default permit + Windowed.window = 1 << 28; // 2 GiB of rows at 8 bytes each, past the 1 GiB default + try t.expectEqual(@as(u32, 1 << 28), W.longest(&target)); + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); + defer t.allocator.free(root); + const vt: api.prompt_cache.Snapshots.VTable = .{ .bytes = Copies.bytes, .save = Copies.save, .restore = Copies.restore, .drop = Copies.drop, .rows = &W.image }; + const copies: api.prompt_cache.Snapshots = .{ .ptr = &target, .vtable = &vt }; + for ([_]u64{ 8 << 30, 3 << 29 }) |budget| { + var s = api.prompt_cache.Store.init(t.allocator, copies, rules, budget); + const options: rows.Options = .{ .root = root, .identity = 1, .cap = 1 << 34, .floor = 0, .daily = 1 << 34, .longest = W.longest(&target) }; + const r = rows.attach(t.allocator, &s, options) catch |e| { + s.deinit(); + return e; + }; + defer r.deinit(); + defer s.deinit(); // the store before its disk, as the rows fixtures close them + const whole = (@as(u64, 1 << 28) * 8) + 32 + 16; + if (budget > whole) try t.expect(r.staging_bytes > whole) else try t.expectEqual(budget, r.staging_bytes); + } +} + test "CUDA kept: Gemma 4, Dory and Spark2.5 take the store, a family without a view still refuses" { const gemma = @import("gemma4_cuda"); const dory = @import("dory"); From f31828d8d9383b6ba6440cda1b9637a1c446a252 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:17:38 +0100 Subject: [PATCH 17/89] docs: optimization ledger row 8, Gemma 4, Dory and Spark2.5 on CUDA open --- docs/optimization-ledger.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 967a44cc099..e67ea9e1304 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -56,7 +56,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 5. State walk | open C[#2392] | open C[#2392] | open [#2215] | open C[#2392] | open C[#2392] | | 6. KV ledger | done [#2127] | done [#2127] | done [#2127] | done [#2127] | done [#2127] | | 7. Host KV tier | yes | open [#1501] | done [#1795] | yes | yes | -| 8. Disk cache | done C[#1358] | done C[#1359] M[#519] | done M¹ open C[#1411] | yes | done C[#1413] M¹ | +| 8. Disk cache | done C[#1358] | done C[#1359] M[#519] | done M¹ open C[#1411] | open C[#3135] | done C[#1413] M¹ | | 9. FP8 KV | done [#886] | yes | done¹ | yes | yes | | 10. FP4/FP8 decode | yes | yes | yes | no (affine) | yes | | 11. Fused proj. | done [#1783] | done¹ | done¹ | done [#1783] | done [#1783] | @@ -88,7 +88,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 5. State walk | yes | yes | yes | yes | yes | | 6. KV ledger | done [#2127] | done [#2127] | done [#2127] | yes | yes | | 7. Host KV tier | yes | yes | yes | yes | yes | -| 8. Disk cache | yes | yes | yes | yes | done¹ | +| 8. Disk cache | yes | open [#3135] | open [#3135] | yes | done¹ | | 9. FP8 KV | yes | yes | yes | yes | no (FP8 by design) | | 10. FP4/FP8 decode | failed [#1448] | no (bf16) | yes | no (EXL3) | yes | | 11. Fused proj. | done¹ | done [#1783] | yes | done¹ | done¹ | @@ -524,6 +524,7 @@ below; these are estimates for planning a port, not results. [#1394]: https://github.com/ashhart/TensorFold/pull/1394 [#1411]: https://github.com/ashhart/TensorFold/pull/1411 [#1413]: https://github.com/ashhart/TensorFold/pull/1413 +[#3135]: https://github.com/ashhart/TensorFold/pull/3135 [#1423]: https://github.com/ashhart/TensorFold/pull/1423 [#1426]: https://github.com/ashhart/TensorFold/pull/1426 [#1434]: https://github.com/ashhart/TensorFold/pull/1434 From 7ba58e3ab5a11264734bd70d77db7b0ded3e2be8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:09:35 -0800 Subject: [PATCH 18/89] cuda disk: pin the shared kept view on the rebased source (#3135) --- zig/tests/fixtures/gradient-serving.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index e2f0cc0648d..ef0b99b3c27 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -129,7 +129,7 @@ zig/src/families/flashnext/cuda_hc.zig 01f897ac65d6edd2cd6ac76d97cb4d96619c25ffa zig/src/families/flashnext/cuda_head.zig fc6410e8b17d559a12d81fd4bee9ab4e65f6f8b0999796c68baba58efb8fe818 raw zig/src/families/flashnext/cuda_images.zig 5bd8a6c06cb69440522f4392794d9ef52b3760195b97d96f2316b1acac271bd4 raw zig/src/families/flashnext/cuda_images_test.zig df984d54d9de1bb732544785cddf82a124de2a7019041ed1f7483b2a4a2d7c99 raw -zig/src/families/flashnext/cuda_lanes.zig b17a890be34945e506970c577909896b52fa6e13b1024d326520ca6ab7583ab0 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file) +zig/src/families/flashnext/cuda_lanes.zig 8578e64c69611c219709f48a4ba646bfd01fa02d793d788ea7e577ae03d07808 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change) zig/src/families/flashnext/cuda_lanes_admission_test.zig 4b8052db793ba81f0e73e1b9bd77b1780bbc4fd550d90976d017da47e76faaa2 raw zig/src/families/flashnext/cuda_lanes_load.zig 241d091d4b5199325665d25ea5d4def81fd15660351a199773c596ca2025fa18 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw From ac9c1fe362e9c17a92f26e7d3e9ab59197063ffb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:47:01 +0000 Subject: [PATCH 19/89] changelog: #3135 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39590ee6273..5eec9ee9bf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: Gemma 4, Dory and Spark2.5 can keep conversations on disk through the shared kept-image store (#3135, part of #840). Thanks to @jschmied. + - CUDA: a dense Qwen 3.5 MLP's NVFP4 prompt gate, up and activation run in one launch for prompt rows past 16, with the same bytes (#3252). Thanks to @jschmied. - Images: with `stream: true`, `POST /v1/images/generations` streams each denoising step's progress (`image_generation.progress`) and, with `preview_interval`, partial previews while the picture generates, then the PNG (#3245). From af9e99c8b1036f188fc097816d9e7df2381d0020 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:30:14 +0000 Subject: [PATCH 20/89] nemotron cuda: Nemotron 3.5 Transcribe's language model (nemo_speechlm) from its bf16 weights, audio rows spliced after the embeds The checkpoint's llm.* tensors load as published: NeMo's layer names, fp32 A_log/D/dt_bias, the stacked [E, in, out] experts on the bf16 grouped format with the shared expert as experts E and E + 1, TE's empty _extra_state skipped. The audio encoder and CTC aligner tensors are left for the audio path. A prompt pass's audio rows replace the <|audio|> positions' embeddings, as image rows do. --- zig/src/families/nemotron/config.zig | 30 +++++- zig/src/families/nemotron/cuda.zig | 1 + zig/src/families/nemotron/cuda_audio.zig | 41 ++++++++ zig/src/families/nemotron/cuda_engine.zig | 4 + zig/src/families/nemotron/cuda_forward.zig | 2 + zig/src/families/nemotron/cuda_kernels.zig | 11 ++- zig/src/families/nemotron/cuda_load.zig | 17 +++- zig/src/families/nemotron/cuda_modelopt.zig | 2 +- zig/src/families/nemotron/cuda_native.zig | 2 +- zig/src/families/nemotron/cuda_salm.zig | 103 ++++++++++++++++++++ zig/src/families/nemotron/cuda_segments.zig | 1 + zig/src/families/nemotron/cuda_weights.zig | 13 ++- 12 files changed, 212 insertions(+), 15 deletions(-) create mode 100644 zig/src/families/nemotron/cuda_audio.zig create mode 100644 zig/src/families/nemotron/cuda_salm.zig diff --git a/zig/src/families/nemotron/config.zig b/zig/src/families/nemotron/config.zig index cb1152677e9..6ed9775a1b0 100644 --- a/zig/src/families/nemotron/config.zig +++ b/zig/src/families/nemotron/config.zig @@ -101,6 +101,7 @@ pub const Config = struct { eos_count: usize = 0, latent: usize = 0, // moe_latent_size: routed experts read and write this width between two bf16 projections omni: bool = false, // nemotron_h_omni: the text model's tensors sit under "language_model." + salm: bool = false, // nemo_speechlm (Nemotron 3.5 Transcribe): bf16 throughout, NeMo's names under "llm." shares: usize = 1, // latent MoE: expert widths cut in this many shares, summed in share order on every TP world held: ?usize = null, // a split checkpoint (tensorfold_tp): the one share its expert tensors hold rank: usize = 0, // this process's tensor-parallel rank of `world`: set at load, never by config.json @@ -147,6 +148,24 @@ pub const Config = struct { return if (self.omni) "language_model." else ""; } + /// The stem of layer i's names after prefix(): HF's "backbone.layers.", NeMo's "model.layers." (salm). + pub fn layerStem(self: Config) []const u8 { + return if (self.salm) "model.layers." else "backbone.layers."; + } + + /// The token table, the final norm and a Mamba layer's fp32 parameters by their names after prefix(). + pub fn embedName(self: Config) []const u8 { + return if (self.salm) "model.embed_tokens.weight" else "backbone.embeddings.weight"; + } + + pub fn normName(self: Config) []const u8 { + return if (self.salm) "model.norm.weight" else "backbone.norm_f.weight"; + } + + pub fn ssmParams(self: Config) []const u8 { + return if (self.salm) "_fp32_params." else ""; + } + /// The expert width shares this rank holds and sums before the ranks meet. pub fn ownShares(self: Config) usize { return self.shares / self.world; @@ -380,9 +399,10 @@ pub fn parse(allocator: std.mem.Allocator, text: []const u8, why: *Why) !Config var parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{}); defer parsed.deinit(); const root = parsed.value.object; - // nemotron_h_omni (Bolt) wraps the language model's config in llm_config, its quantization at the top + // nemotron_h_omni (Bolt, quantization at the top) and nemo_speechlm (Transcribe) wrap theirs in llm_config const wrapped = isType(root, "nemotron_h_omni"); - const o = if (wrapped) (llmConfig(root) orelse return error.BadConfig) else root; + const salm = isType(root, "nemo_speechlm"); + const o = if (wrapped or salm) (llmConfig(root) orelse return error.BadConfig) else root; if (!isType(o, "nemotron_h") and !isType(o, "nemotron_h_puzzle")) return error.NotNemotronH; var c = Config{ .hidden = try int(o, "hidden_size"), @@ -430,7 +450,7 @@ pub fn parse(allocator: std.mem.Allocator, text: []const u8, why: *Why) !Config c.layers = blocks.len; } // generation_config's [2, 11] is the omni wrapper's eos plus the language model's - if (wrapped) if (root.get("eos_token_id")) |e| eos(&c, e); + if (wrapped or salm) if (root.get("eos_token_id")) |e| eos(&c, e); if (o.get("eos_token_id")) |e| eos(&c, e); if (o.get("time_step_limit")) |v| if (v == .array and v.array.items.len == 2) { c.dt_min = @floatCast(try number(v.array.items[0])); @@ -443,7 +463,9 @@ pub fn parse(allocator: std.mem.Allocator, text: []const u8, why: *Why) !Config if (!c.bolt) c.shares = 2; try split(&c, root, why); }; - try quantization(&c, root, why); + c.salm = salm; + // the published bf16 weights, read per tensor as the ModelOpt loader reads a bf16 projection + if (salm) c.format = .modelopt else try quantization(&c, root, why); return c; } diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index 6221e18c247..b61b06d0ae0 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -23,6 +23,7 @@ pub const native = @import("cuda_native.zig"); pub const train = @import("cuda_train.zig"); /// Bolt's image tower (C-RADIO) and projector: one image's patches to the rows its `` placeholders take. pub const vision = @import("cuda_vision.zig"); +pub const audio = @import("cuda_audio.zig"); pub const sites = @import("cuda_sites.zig"); pub const train_ops = @import("cuda_train_ops.zig"); pub const glue = @import("cuda_glue.zig"); diff --git a/zig/src/families/nemotron/cuda_audio.zig b/zig/src/families/nemotron/cuda_audio.zig new file mode 100644 index 00000000000..785b9b949f1 --- /dev/null +++ b/zig/src/families/nemotron/cuda_audio.zig @@ -0,0 +1,41 @@ +//! Transcribe's audio on CUDA: a prompt pass's audio rows, spliced after each embed as image rows are. +const std = @import("std"); +const cuda = @import("cuda"); +const radio = @import("radio"); + +pub const Audio = struct { + gpa: std.mem.Allocator, + rows: radio.Rows, + spans: []radio.Span = &.{}, // the prompt pass in progress: each clip's rows from its first <|audio|> position + + /// A rows buffer of `limit` rows of the language model's width. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, limit: u32, hidden: usize) !*Audio { + const a = try gpa.create(Audio); + errdefer gpa.destroy(a); + a.* = .{ .gpa = gpa, .rows = try radio.Rows.init(d, limit, hidden) }; + return a; + } + + pub fn deinit(a: *Audio) void { + a.gpa.free(a.spans); + a.rows.deinit(); + a.gpa.destroy(a); + } + + /// One clip's bf16 rows (`rows.hidden` each) from host memory, standing at prompt positions [at, at + n). + pub fn set(a: *Audio, s: cuda.Stream, at: u32, bf16: []const u8) !void { + const w = a.rows.hidden * 2; + if (bf16.len == 0 or bf16.len % w != 0) return error.AudioRows; + const n: u32 = @intCast(bf16.len / w); + if (n > a.rows.limit) return error.AudioRows; + try a.rows.d.check(a.rows.d.api.cuMemcpyHtoDAsync_v2(a.rows.buf.ptr, bf16.ptr, bf16.len, s.handle), "cuMemcpyHtoDAsync"); + a.gpa.free(a.spans); + a.spans = try a.gpa.dupe(radio.Span, &.{.{ .at = at, .n = n, .row = 0, .image = 0 }}); + } + + /// Prompt rows [lo, hi) embedded at `emb` take the audio rows they cross. + pub fn splice(a: *const Audio, s: cuda.Stream, lo: usize, hi: usize, emb: u64) !void { + if (a.spans.len == 0) return; + try a.rows.splice(s, a.spans, @intCast(lo), @intCast(hi), emb); + } +}; diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 336fbf1f949..dbe981aa1d7 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -123,6 +123,7 @@ pub const Engine = struct { benchmark_group: ?[]const u8 = null, tp: ?cuda.tp_group.Group = null, // a latent MoE over ranks (TF_NEMOTRON_RANK of TF_NEMOTRON_WORLD) vision: ?*@import("cuda_vision.zig").Vision = null, // --vision: the tower and a prompt pass's image rows + audio: ?*@import("cuda_audio.zig").Audio = null, // a Transcribe checkpoint's audio rows for the prompt pass snap_host: bool = false, // kept prompt states in pinned host memory (cuda_reuse.zig), set when the host opens the engine load_pending: ?*weights.PendingLoad = null, load_has_weights: bool = false, @@ -162,6 +163,7 @@ pub const Engine = struct { if (opts.slide) return error.SlideNeedsMlx; // the learner reads MLX 4-bit projections try e.k.loadModelopt(ctx); } + if (e.c.salm) try e.k.loadBf16Experts(ctx); if (e.c.latent > 0) try e.k.loadLatent(); if (e.c.ck) try e.k.loadCk(ctx); // the ranks' lines first: a rank that never comes, refuses, fails or dies is named, not waited on @@ -336,6 +338,7 @@ pub const Engine = struct { e.side.join.deinit(); if (e.tp) |*g| g.close(); if (e.vision) |v| v.deinit(); + if (e.audio) |a| a.deinit(); e.stream.deinit(); if (e.benchmark_group) |b| e.gpa.free(b); e.gpa.destroy(e); @@ -421,6 +424,7 @@ pub const Engine = struct { f.untaught = e.bound.untaught; f.tp = if (e.tp) |*g| g else null; f.vision = e.vision; + f.audio = e.audio; if (dump == null and (e.c.latent > 0 or (e.c.experts <= 128 and e.c.slots() <= 8))) f.side = e.side; // tf_plan_routed's bounds; a latent MoE plans without it return f; } diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index b64e32aab43..999402a0c1b 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -58,6 +58,7 @@ pub const Forward = struct { pass: ?worker.Pass = null, // a window's jobs to the other rank under one header (null: one a job) flight: ?*worker.Flight = null, // a window's jobs out and replies in so far, which its failure reads vision: ?*const @import("cuda_vision.zig").Vision = null, // a prompt pass's image rows, spliced after its embeds + audio: ?*const @import("cuda_audio.zig").Audio = null, // a prompt pass's audio rows, spliced the same way page_elems: u64 = 0, // elements between a paged sequence's pages (its layers' K and V of state.chunk_keys rows) pub fn init(c: Config, w: *const weights.Weights, b: *const state.Buffers, ops: kern.Ops, max_len: usize, nch: usize, sampled: bool) Forward { @@ -472,6 +473,7 @@ pub const Forward = struct { const b = f.b; try f.embed(b.p_ids, b.emb, w.rows); if (f.vision) |v| try v.splice(f.ops.s, w.pos, w.pos + w.rows, b.emb); + if (f.audio) |a| try a.splice(f.ops.s, w.pos, w.pos + w.rows, b.emb); w.x = b.emb; } diff --git a/zig/src/families/nemotron/cuda_kernels.zig b/zig/src/families/nemotron/cuda_kernels.zig index f984124dd97..d1be32fa78f 100644 --- a/zig/src/families/nemotron/cuda_kernels.zig +++ b/zig/src/families/nemotron/cuda_kernels.zig @@ -82,6 +82,7 @@ pub const Kernels = struct { latent: ?@import("cuda_latent.zig").Fns = null, // a latent MoE's glue (loadLatent), else never ck: ?cuda.ck.Ck = null, // the checkpoint's own math (loadCk): FP8 rows and NVFP4 experts, sm_120 on ggml: ?cuda.ggml.Kernels = null, // loaded by loadGgml for a checkpoint with ggml blocks (Bolt's IQ2_XXS and Q8_0) + bf16x: ?cuda.experts.Bf16Experts = null, // loaded by loadBf16Experts for a bf16 checkpoint's experts (Transcribe) gb10: bool, discrete: bool, // the card has its own memory: checkpoint bytes reach it through page-locked slots @@ -128,6 +129,7 @@ pub const Kernels = struct { k.latent = null; k.ck = null; k.ggml = null; + k.bf16x = null; k.triton = if (triton_dir) |dir| try cuda.aot.Set.load(gpa, io, d, ctx.device, dir) else null; errdefer if (k.triton) |*t| t.deinit(); k.train = try train_ops.Kernels.load(d); @@ -156,6 +158,7 @@ pub const Kernels = struct { m.pack.unload(); } if (k.ggml) |*g| g.unload(); + if (k.bf16x) |*x| x.unload(); k.affine.deinit(); k.train.deinit(); if (k.triton) |*t| t.deinit(); @@ -191,6 +194,12 @@ pub const Kernels = struct { k.modelopt = .{ .lane = lane, .gemm = gemm, .experts = experts, .pack = try cuda.modelopt.Packer.load(k.d) }; } + /// The grouped bf16 experts a checkpoint's own bf16 experts run on (Nemotron 3.5 Transcribe). + pub fn loadBf16Experts(k: *Kernels, ctx: *const cuda.Context) !void { + if (k.bf16x != null) return; + k.bf16x = try cuda.experts.Bf16Experts.load(k.d, @intCast(try ctx.attribute(.multiprocessor_count))); + } + /// The ggml block kernels (IQ2_XXS experts, IQ2_XXS and Q8_0 projections, their repack) Bolt's export needs. pub fn loadGgml(k: *Kernels, ctx: *const cuda.Context) !void { if (k.ggml != null) return; @@ -313,7 +322,7 @@ pub const Ops = struct { /// Every grouped-expert format the kernels loaded (cuda/experts.zig). pub fn grouped(o: Ops) cuda.experts.Grouped { - return .{ .affine4 = &o.k.experts, .nvfp4 = if (o.k.modelopt) |*x| &x.experts else null, .iq2xxs = if (o.k.ggml) |*g| g else null }; + return .{ .affine4 = &o.k.experts, .nvfp4 = if (o.k.modelopt) |*x| &x.experts else null, .iq2xxs = if (o.k.ggml) |*g| g else null, .bf16 = if (o.k.bf16x) |*x| x else null }; } /// LatentMoE: z[r] = sum_k wt[r, k] y[r * k_slots + k], rows of `l` bf16 from fp32 pair rows (the shared combine). diff --git a/zig/src/families/nemotron/cuda_load.zig b/zig/src/families/nemotron/cuda_load.zig index 23d6766a1ad..7d8317f23e9 100644 --- a/zig/src/families/nemotron/cuda_load.zig +++ b/zig/src/families/nemotron/cuda_load.zig @@ -8,6 +8,7 @@ const kern = @import("cuda_kernels.zig"); const Source = @import("cuda_source.zig").Source; const latent = @import("cuda_latent.zig"); const modelopt = @import("cuda_modelopt.zig"); +const salm = @import("cuda_salm.zig"); const join = weights.join; const Block = weights.Block; pub const Pending = struct { @@ -76,6 +77,12 @@ fn fill(p: *Pending, io: std.Io, dir: []const u8, c: Config, with_mtp: bool) !vo var ck = try core.Checkpoint.openModel(gpa, io, dir); defer core.checkpoint.cache.close(&ck); try src.add(&ck); + // a Transcribe checkpoint: the audio encoder and the CTC aligner load apart; TE's _extra_state holds nothing + if (c.salm) { + for ([_][]const u8{ "perception.", "ctc_timestamp." }) |part| try ck.skip(part); + try salm.skipExtraState(&ck); + ck.scope = "llm."; + } const pre = c.prefix(); const readers = try core.checkpoint_read_ahead.optInReaders(); w.blocks = try gpa.alloc(Block, c.layers); @@ -86,13 +93,13 @@ fn fill(p: *Pending, io: std.Io, dir: []const u8, c: Config, with_mtp: bool) !vo var nb: [128]u8 = undefined; var pb: [128]u8 = undefined; const name = try std.fmt.bufPrint(&nm, "blocks.{d}", .{i}); - const norm = try ck.expect(try std.fmt.bufPrint(&pb, "{s}backbone.layers.{d}.norm.weight", .{ pre, i }), .bf16, &.{c.hidden}); + const norm = try ck.expect(try std.fmt.bufPrint(&pb, "{s}{s}{d}.norm.weight", .{ pre, c.layerStem(), i }), .bf16, &.{c.hidden}); var b: Block = .{ .kind = kind, .norm = try L.raw(try join(&nb, name, ".norm"), norm) }; - const mixer = try std.fmt.bufPrint(&pb, "{s}backbone.layers.{d}.mixer.", .{ pre, i }); + const mixer = try std.fmt.bufPrint(&pb, "{s}{s}{d}.mixer.", .{ pre, c.layerStem(), i }); switch (kind) { .mamba => b.mamba = try L.mamba(&ck, try join(&nb, name, ".mamba"), mixer), .attention => b.attn = try L.attention(&ck, try join(&nb, name, ".attn"), mixer), - .moe => b.moe = if (c.bolt) try modelopt.latent(L, &ck, try join(&nb, name, ".moe"), mixer, c, i) else if (c.latent > 0) try latent.load(L, &ck, try join(&nb, name, ".moe"), mixer, c, @intCast(i)) else try L.moe(&ck, try join(&nb, name, ".moe"), mixer, c), + .moe => b.moe = if (c.salm) try salm.moe(L, &ck, try join(&nb, name, ".moe"), mixer, c) else if (c.bolt) try modelopt.latent(L, &ck, try join(&nb, name, ".moe"), mixer, c, i) else if (c.latent > 0) try latent.load(L, &ck, try join(&nb, name, ".moe"), mixer, c, @intCast(i)) else try L.moe(&ck, try join(&nb, name, ".moe"), mixer, c), } w.blocks[i] = b; _ = try reading.check(); @@ -108,10 +115,10 @@ fn fill(p: *Pending, io: std.Io, dir: []const u8, c: Config, with_mtp: bool) !vo }; } var tail: [96]u8 = undefined; - w.norm_f = try L.raw("norm_f", try ck.expect(try std.fmt.bufPrint(&tail, "{s}backbone.norm_f.weight", .{pre}), .bf16, &.{c.hidden})); + w.norm_f = try L.raw("norm_f", try ck.expect(try std.fmt.bufPrint(&tail, "{s}{s}", .{ pre, c.normName() }), .bf16, &.{c.hidden})); w.head = try L.dense(&ck, "head", &.{try std.fmt.bufPrint(&tail, "{s}lm_head", .{pre})}); // a ModelOpt checkpoint keeps its MTP head in its own shards - if (c.format == .modelopt) if (!with_mtp) try ck.skip(try std.fmt.bufPrint(&tail, "{s}mtp.", .{pre})) else if (c.latent > 0) try latent.mtp(L, &ck, c) else try modelopt.mtp(L, &ck, c); + if (c.format == .modelopt) if (!with_mtp) try ck.skip(try std.fmt.bufPrint(&tail, "{s}mtp.", .{pre})) else if (c.salm) try salm.mtp(L, &ck, c) else if (c.latent > 0) try latent.mtp(L, &ck, c) else try modelopt.mtp(L, &ck, c); // the picture tower and its projector load with the image path (an omni checkpoint's other parts) if (c.omni) for ([_][]const u8{ "vision_model.", "mlp1.", "vision_projector." }) |part| try ck.skip(part); if (ck.unused() != 0) return error.UnusedCheckpointTensors; diff --git a/zig/src/families/nemotron/cuda_modelopt.zig b/zig/src/families/nemotron/cuda_modelopt.zig index c3baac3bfda..c5e4d0db4ea 100644 --- a/zig/src/families/nemotron/cuda_modelopt.zig +++ b/zig/src/families/nemotron/cuda_modelopt.zig @@ -322,7 +322,7 @@ fn experts(L: *Loader, ck: *core.Checkpoint, label: []const u8, pre: []const u8, /// The bf16 token table as stored. pub fn embed(L: *Loader, ck: *core.Checkpoint, c: Config) !W.Embed { var buf: [64]u8 = undefined; - const t = try ck.expect(try name(&buf, "{s}backbone.embeddings.weight", .{c.prefix()}), .bf16, &.{ c.vocab, c.hidden }); + const t = try ck.expect(try name(&buf, "{s}{s}", .{ c.prefix(), c.embedName() }), .bf16, &.{ c.vocab, c.hidden }); return .{ .w = try L.raw("embed.weight", t), .n = c.vocab, .k = c.hidden, .bf16 = true }; } diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index 208ad9effb6..2b885e87403 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -27,7 +27,7 @@ pub const slide = @import("cuda_slide.zig"); pub const model_type = "nemotron_h"; pub const explains_open = true; // explain() words open refusals too (--vision on a checkpoint without a tower) /// Nemotron 3.5 Bolt's config: the language model under llm_config, beside its vision tower's. -pub const also_model_types: []const []const u8 = &.{"nemotron_h_omni"}; +pub const also_model_types: []const []const u8 = &.{ "nemotron_h_omni", "nemo_speechlm" }; pub const formats: []const []const u8 = &.{ "mlx-q4g64", "modelopt-nvfp4", "modelopt-ggml" }; pub const default_context: i64 = engine.default_context; pub const max_segments: u32 = @import("cuda_segments.zig").MAX; diff --git a/zig/src/families/nemotron/cuda_salm.zig b/zig/src/families/nemotron/cuda_salm.zig new file mode 100644 index 00000000000..1a2d470e8e8 --- /dev/null +++ b/zig/src/families/nemotron/cuda_salm.zig @@ -0,0 +1,103 @@ +//! Transcribe's language model: NeMo's bf16 tensors as published, routed experts as x @ W, the shared one nn.Linear. + +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const W = @import("cuda_weights.zig"); +const kern = @import("cuda_kernels.zig"); +const modelopt = @import("cuda_modelopt.zig"); +const Config = @import("config.zig").Config; +const draft_ids = @import("draft_ids.zig"); + +const Loader = W.Loader; +const Tensor = core.checkpoint.Tensor; +const Bf16 = cuda.experts.Bf16Experts; + +fn name(buf: []u8, comptime fmt: []const u8, args: anytype) ![]const u8 { + return std.fmt.bufPrint(buf, fmt, args); +} + +/// Every TE `_extra_state` (empty bytes beside a projection) marked as used: there is nothing in them to read. +pub fn skipExtraState(ck: *core.Checkpoint) !void { + for (ck.files.items) |*f| for (f.names.keys()) |k| { + if (std.mem.endsWith(u8, k, "._extra_state")) try ck.used.put(ck.gpa, k, {}); + }; +} + +/// A MoE layer: the bf16 router, its fp32 bias, routed experts and the shared expert's halves as experts E and E + 1. +pub fn moe(L: *Loader, ck: *core.Checkpoint, label: []const u8, pre: []const u8, c: Config) !W.MoE { + var a: [128]u8 = undefined; + var b: [192]u8 = undefined; + const r = try modelopt.router(L, try name(&a, "{s}.router", .{label}), try ck.get(try name(&b, "{s}gate.weight", .{pre})), c); + const bias = try ck.expect(try name(&b, "{s}gate.e_score_correction_bias", .{pre}), .f32, &.{c.experts}); + return .{ .router = r, .bias = try L.raw(try name(&a, "{s}.bias", .{label}), bias), .experts = try experts(L, ck, label, pre, c) }; +} + +fn experts(L: *Loader, ck: *core.Checkpoint, label: []const u8, pre: []const u8, c: Config) !kern.Experts { + const k = &(L.ops.k.bf16x orelse return error.Bf16ExpertsNotLoaded); + const E = c.experts; + const w = c.expert_width; + const D = c.hidden; + var layer: kern.Experts = .{ .format = .bf16, .up = 0, .down = 0, .width = w, .dims = D, .experts = E + 2, .relu2 = true }; + var a: [128]u8 = undefined; + var b: [192]u8 = undefined; + for ([2]bool{ true, false }) |up| { + const n = if (up) w else D; + const kk = if (up) D else w; + const routed = try ck.expect(try name(&b, "{s}experts.{s}", .{ pre, if (up) "gate_and_up_projs" else "down_projs" }), .bf16, &.{ E, kk, n }); + const shared = if (up) + try ck.expect(try name(&b, "{s}shared_experts.up_proj.weight", .{pre}), .bf16, &.{ 2 * w, D }) + else + try ck.expect(try name(&b, "{s}shared_experts.down_proj.weight", .{pre}), .bf16, &.{ D, 2 * w }); + const base = try L.tmp(routed.bytes.len + shared.bytes.len); + try L.src.upload(base, routed.bytes); + try L.src.upload(base + routed.bytes.len, shared.bytes); + const out = try L.alloc(try name(&a, "{s}.experts.{s}", .{ label, if (up) "up" else "down" }), Bf16.bytes(E + 2, n, kk)); + try L.src.flush(); + const s = L.ops.s; + const one = Bf16.bytes(1, n, kk); + try k.pack(s, base, .{ .stride = kk * n, .ld = n, .in_out = true }, out, E, n, kk); + const sh = base + routed.bytes.len; + for (0..2) |h| { + const from: Bf16.Source = if (up) .{ .ld = D, .n0 = h * w, .in_out = false } else .{ .ld = 2 * w, .k0 = h * w, .in_out = false }; + try k.pack(s, sh, from, out + (E + h) * one, 1, n, kk); + } + if (up) layer.up = out else layer.down = out; + } + return layer; +} + +/// The MTP head as stored: bf16 attention, input projection and experts; the draft head is lm_head's bf16 rows. +pub fn mtp(L: *Loader, ck: *core.Checkpoint, c: Config) !void { + const p0 = "mtp.layers.0."; + const p1 = "mtp.layers.1.mixer."; + const att = p0 ++ "mixer."; + L.w.mtp = .{ + .enorm = try L.raw("mtp.enorm", try ck.expect(p0 ++ "enorm.weight", .bf16, &.{c.hidden})), + .hnorm = try L.raw("mtp.hnorm", try ck.expect(p0 ++ "hnorm.weight", .bf16, &.{c.hidden})), + .eh_proj = try modelopt.dense(L, ck, "mtp.eh_proj", &.{p0 ++ "eh_proj"}), + .attn_norm = try L.raw("mtp.attn_norm", try ck.expect(p0 ++ "norm.weight", .bf16, &.{c.hidden})), + .attn = .{ .qkv = try modelopt.dense(L, ck, "mtp.attn.qkv", &.{ att ++ "q_proj", att ++ "k_proj", att ++ "v_proj" }), .o = try modelopt.dense(L, ck, "mtp.attn.o", &.{att ++ "o_proj"}) }, + .moe_norm = try L.raw("mtp.moe_norm", try ck.expect("mtp.layers.1.norm.weight", .bf16, &.{c.hidden})), + .moe = try moe(L, ck, "mtp.moe", p1, c), + .final_norm = try L.raw("mtp.final_norm", try ck.expect("mtp.layers.1.final_layernorm.weight", .bf16, &.{c.hidden})), + }; + try draftHead(L, ck, c); +} + +/// head_rows: lm_head's bf16 rows for the draft ids, packed as a head of their own. +fn draftHead(L: *Loader, ck: *core.Checkpoint, c: Config) !void { + const m = if (L.ops.k.modelopt) |*x| x else return error.ModeloptNotLoaded; + const ids = try draft_ids.load(L.gpa, c.vocab); + defer L.gpa.free(ids); + const p = try modelopt.part(ck, "lm_head"); + if (p.kind != .bf16 or p.n != c.vocab or p.k != c.hidden) return error.UnexpectedTensor; + const host = try L.staging(ids.len * p.k * 2); + try W.gatherRows(L, p.w, ids, host); + const base = try L.tmp(host.len); + try L.ops.upload(base, host); + const out = try L.alloc("draft_head.weight", cuda.modelopt.padded(ids.len) * p.k * 2); + try m.pack.bf16Lane(L.ops.s, base, out, ids.len, p.k); + L.w.draft_head = .{ .bf16 = cuda.modelopt.bf16Weight(out, ids.len, p.k) }; + try W.draftIds(L, ids); +} diff --git a/zig/src/families/nemotron/cuda_segments.zig b/zig/src/families/nemotron/cuda_segments.zig index 39f1cb435e3..6f85672b61a 100644 --- a/zig/src/families/nemotron/cuda_segments.zig +++ b/zig/src/families/nemotron/cuda_segments.zig @@ -90,6 +90,7 @@ pub fn prefill(e: *Engine, s: *Segments, prompt: []const u32, head: ?*Head, part f.page_elems = e.pageBytes() / 2; f.untaught = e.bound.untaught; f.vision = e.vision; + f.audio = e.audio; seg[k] = .{ .f = f, .walk = .{ .rows = rows, .pos = e.pos + k * R } }; } try e.copied.record(e.stream); diff --git a/zig/src/families/nemotron/cuda_weights.zig b/zig/src/families/nemotron/cuda_weights.zig index 292f506500b..7c6ae6fb8c4 100644 --- a/zig/src/families/nemotron/cuda_weights.zig +++ b/zig/src/families/nemotron/cuda_weights.zig @@ -122,6 +122,11 @@ pub const Loader = struct { /// `.float()` of a bf16 tensor into the host staging buffer: exact. pub fn widened(L: *Loader, t: Tensor) ![]u8 { + if (t.dtype == .f32) { + const out = try L.staging(t.bytes.len); + @memcpy(out, try L.src.view(t.bytes)); + return L.host.items; + } if (t.dtype != .bf16) return error.UnexpectedTensor; const n = t.bytes.len / 2; const out = std.mem.bytesAsSlice(u32, try L.staging(n * 4)); @@ -375,13 +380,15 @@ pub const Loader = struct { m.conv_w = try L.alloc(try join(&a, name, ".conv_w"), L.host.items.len); try L.ops.upload(m.conv_w, L.host.items); m.conv_b = try L.widen(try join(&a, name, ".conv_b"), try ck.get(try join(&b, pre, "conv1d.bias"))); - const alog = try L.widened(try ck.get(try join(&b, pre, "A_log"))); + var fp: [128]u8 = undefined; + const ssm = try join(&fp, pre, L.w.config.ssmParams()); // Transcribe keeps these three in fp32 + const alog = try L.widened(try ck.get(try join(&b, ssm, "A_log"))); const src = try L.tmp(alog.len); try L.ops.upload(src, alog); m.a = try L.alloc(try join(&a, name, ".a"), alog.len); try L.ops.torch().mambaA(src, m.a, alog.len / 4); - m.d = try L.widen(try join(&a, name, ".d"), try ck.get(try join(&b, pre, "D"))); - m.dt_bias = try L.widen(try join(&a, name, ".dt_bias"), try ck.get(try join(&b, pre, "dt_bias"))); + m.d = try L.widen(try join(&a, name, ".d"), try ck.get(try join(&b, ssm, "D"))); + m.dt_bias = try L.widen(try join(&a, name, ".dt_bias"), try ck.get(try join(&b, ssm, "dt_bias"))); m.gnorm = try L.raw(try join(&a, name, ".gnorm"), try ck.get(try join(&b, pre, "norm.weight"))); return m; } From 8c72d6bedc0ca74def9beb6d37241a51b7a05c47 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:30:15 +0000 Subject: [PATCH 21/89] nemotron cuda: null bf16x in the hand-built load-recovery engines The Bolt load-recovery tests build an Engine by hand and null each optional kernel set; bf16x was left undefined, so deinit unloaded a garbage module (seven tests crashed on Linux and Windows CI). --- zig/src/native/cuda_load_gpu.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zig/src/native/cuda_load_gpu.zig b/zig/src/native/cuda_load_gpu.zig index 011531c48bb..23f31a93dff 100644 --- a/zig/src/native/cuda_load_gpu.zig +++ b/zig/src/native/cuda_load_gpu.zig @@ -190,6 +190,7 @@ test "native Bolt load failure keeps destinations and kernel GPU parents through e.k.d = d; e.k.modelopt = null; e.k.ggml = null; + e.k.bf16x = null; e.k.triton = null; e.k.affine.split = null; e.k.latent = null; @@ -299,6 +300,7 @@ fn partialEngine(g: *Gpu) !*nemotron.Engine { e.k.d = d; e.k.modelopt = null; e.k.ggml = null; + e.k.bf16x = null; e.k.triton = null; e.k.affine.split = null; e.k.latent = null; From 3bf8986711cfc82c75e1e399174569bf06809ee5 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 2 Nov 2026 19:09:42 +0000 Subject: [PATCH 22/89] nemotron cuda: fp32 conv1d.bias, A_log, D and dt_bias only from a Transcribe (salm) checkpoint, with a test --- zig/src/families/nemotron/cuda_weights.zig | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/zig/src/families/nemotron/cuda_weights.zig b/zig/src/families/nemotron/cuda_weights.zig index 7c6ae6fb8c4..44a24426bbf 100644 --- a/zig/src/families/nemotron/cuda_weights.zig +++ b/zig/src/families/nemotron/cuda_weights.zig @@ -120,14 +120,13 @@ pub const Loader = struct { return ptr; } - /// `.float()` of a bf16 tensor into the host staging buffer: exact. + /// `.float()` of a vector into the host staging buffer, exact (see `widening`). pub fn widened(L: *Loader, t: Tensor) ![]u8 { - if (t.dtype == .f32) { + if (try widening(t.dtype, L.w.config.salm) == .copy) { const out = try L.staging(t.bytes.len); @memcpy(out, try L.src.view(t.bytes)); return L.host.items; } - if (t.dtype != .bf16) return error.UnexpectedTensor; const n = t.bytes.len / 2; const out = std.mem.bytesAsSlice(u32, try L.staging(n * 4)); const in = try L.src.view(t.bytes); @@ -517,3 +516,19 @@ pub fn draftIds(L: *Loader, ids: []const u32) !void { try L.ops.upload(L.w.draft_ids, L.host.items); L.w.draft_count = ids.len; } + +/// How `widened` reads a vector: bf16 widened; fp32 copied, from Transcribe (salm) only; anything else refused. +fn widening(dtype: core.checkpoint.DType, salm: bool) !enum { widen, copy } { + if (dtype == .bf16) return .widen; + if (dtype == .f32 and salm) return .copy; + return error.UnexpectedTensor; +} + +test "the CUDA loader takes fp32 vectors only from a Transcribe (salm) checkpoint" { + const t = std.testing; + try t.expectEqual(.widen, try widening(.bf16, false)); + try t.expectEqual(.widen, try widening(.bf16, true)); + try t.expectEqual(.copy, try widening(.f32, true)); + try t.expectError(error.UnexpectedTensor, widening(.f32, false)); + try t.expectError(error.UnexpectedTensor, widening(.f16, true)); +} From 7314e4167e13b77025fe7be70d8b53fa68d179ea Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:37:58 -0600 Subject: [PATCH 23/89] nemo_audio: Nemotron 3.5 Transcribe's audio encoder on CUDA The perception encoder as a family of its own (zig/src/families/nemo_audio): WAV decoding, log-mel features and their per-feature normalisation, the ASR and streaming speaker transformers window by window (speaker cache and queue with AOSC compression, arXiv 2507.18446), the sinusoidal speaker fusion and the projection to the language model's width. Weights read as stored (bf16), perception.* only. nemotron/cuda_audio.zig holds the encoder, prepares clips (samples, rows, hash) and encodes each span at a prompt pass, up to an hour of audio. tf-cuda-test audio-check writes every stage under the reference dumps' names; audio-contract runs nemo_audio.cu's kernels through gates 1-4, each with a control built from nemo_audio.cuh. --- docs/kernel-contract.md | 6 + zig/build/cuda.zig | 10 +- zig/build/cuda_kernels.zig | 1 + zig/build/cuda_readback_sites.zig | 8 + zig/kernels/cuda/contract_controls_set.cu | 1 + .../cuda/contract_nemo_audio_controls.cuh | 36 ++ zig/kernels/cuda/nemo_audio.cu | 36 ++ zig/kernels/cuda/nemo_audio.cuh | 274 ++++++++++ .../core/contract/nemo_audio_cuda_records.zig | 24 + zig/src/core/contract/registry_joins.zig | 1 + zig/src/core/contract/registry_sets_test.zig | 1 + zig/src/cuda/kernels.zig | 1 + zig/src/families/nemo_audio/config.zig | 226 ++++++++ zig/src/families/nemo_audio/encoder.zig | 291 +++++++++++ zig/src/families/nemo_audio/kernels.zig | 147 ++++++ zig/src/families/nemo_audio/nemo_audio.zig | 16 + zig/src/families/nemo_audio/speaker.zig | 181 +++++++ zig/src/families/nemo_audio/wav.zig | 146 ++++++ zig/src/families/nemo_audio/weights.zig | 311 +++++++++++ zig/src/families/nemotron/cuda_audio.zig | 128 ++++- zig/tests/cuda/audio_check.zig | 84 +++ zig/tests/cuda/contract_family_sets.zig | 5 + zig/tests/cuda/contract_limits.zig | 2 +- zig/tests/cuda/contract_nemo_audio.zig | 113 ++++ zig/tests/cuda/contract_nemo_audio_attn.zig | 163 ++++++ zig/tests/cuda/contract_nemo_audio_feats.zig | 330 ++++++++++++ zig/tests/cuda/contract_nemo_audio_ref.zig | 104 ++++ zig/tests/cuda/contract_nemo_audio_rows.zig | 486 ++++++++++++++++++ zig/tests/cuda/main.zig | 2 + 29 files changed, 3125 insertions(+), 9 deletions(-) create mode 100644 zig/kernels/cuda/contract_nemo_audio_controls.cuh create mode 100644 zig/kernels/cuda/nemo_audio.cu create mode 100644 zig/kernels/cuda/nemo_audio.cuh create mode 100644 zig/src/core/contract/nemo_audio_cuda_records.zig create mode 100644 zig/src/families/nemo_audio/config.zig create mode 100644 zig/src/families/nemo_audio/encoder.zig create mode 100644 zig/src/families/nemo_audio/kernels.zig create mode 100644 zig/src/families/nemo_audio/nemo_audio.zig create mode 100644 zig/src/families/nemo_audio/speaker.zig create mode 100644 zig/src/families/nemo_audio/wav.zig create mode 100644 zig/src/families/nemo_audio/weights.zig create mode 100644 zig/tests/cuda/audio_check.zig create mode 100644 zig/tests/cuda/contract_nemo_audio.zig create mode 100644 zig/tests/cuda/contract_nemo_audio_attn.zig create mode 100644 zig/tests/cuda/contract_nemo_audio_feats.zig create mode 100644 zig/tests/cuda/contract_nemo_audio_ref.zig create mode 100644 zig/tests/cuda/contract_nemo_audio_rows.zig diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 3baf9193454..ffaf4740529 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -448,6 +448,12 @@ CUDA also checks MOSS-Image's glue (`moss_image.cu`: the norm, plain and modulat rows; situ; the gated add), each output within float64's range at its torch bf16 points (five controls, each dropping one point), and `vision_kernel` at head dim 128 against `contract_attn.zig`'s float64 reference (`moss-contract`). +CUDA also checks Nemotron 3.5 Transcribe's audio encoder glue (`nemo_audio.cu`: log-mel frames, their per-feature +normalisation, q/k norm and rotary in both stacks' forms, the speaker head's taps, ReLU and predictions, and the fusion +of the two branches), each output within float64's range at its bf16 points, and its head-64 attention against +`contract_attn.zig`'s float64 reference (`audio-contract`; eight controls built from `nemo_audio.cuh` with one thing +dropped each). + CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 49ad4ab3490..d9ec525b981 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -12,7 +12,7 @@ const flashnextModule = engines_build.flashnextModule; const glmCuda = engines_build.glmCuda; const lfm2Module = engines_build.lfm2Module; -pub fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen35: *std.Build.Module, qwen_vision: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module, radio: *std.Build.Module, living: *std.Build.Module, api: *std.Build.Module } { +pub fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen35: *std.Build.Module, qwen_vision: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module, radio: *std.Build.Module, nemo_audio: *std.Build.Module, living: *std.Build.Module, api: *std.Build.Module } { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); @@ -31,6 +31,9 @@ pub fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui nemotron.addImport("nemotron_draft_ids", draft_ids); const radio = radioModule(b, target, optimize, cuda, core, lanes); nemotron.addImport("radio", radio); + // Transcribe's audio encoder, which the nemotron family's audio rows come from + const nemo_audio = b.createModule(.{ .root_source_file = b.path("zig/src/families/nemo_audio/nemo_audio.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); + nemotron.addImport("nemo_audio", nemo_audio); nemotron.addImport("living", living); const qwen35 = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); qwen35.addImport("living", living); @@ -47,7 +50,7 @@ pub fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui qwen35.addImport("engine_api", b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} })); // core's prompt-cache types, the server's engine_api const qwen_vision = qwenVisionModule(b, target, optimize, cuda, core, lanes); qwen35.addImport("qwen_vision", qwen_vision); - return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .qwen35 = qwen35, .qwen_vision = qwen_vision, .tokenizer = tokenizer, .heat = heat, .radio = radio, .living = living, .api = qwen35.import_table.get("engine_api").? }; + return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .qwen35 = qwen35, .qwen_vision = qwen_vision, .tokenizer = tokenizer, .heat = heat, .radio = radio, .nemo_audio = nemo_audio, .living = living, .api = qwen35.import_table.get("engine_api").? }; } /// Linux targets: fatbins (-Dnvcc builds them, -Dfatbins embeds prebuilt ones), `tensorfold` and `tf-cuda-test`. @@ -101,6 +104,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("flashnext", flashnextModule(b, target, optimize, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api)); runner.addImport("lfm2", lfm2Module(b, target, optimize, cuda, mods.core)); runner.addImport("radio", mods.radio); + runner.addImport("nemo_audio", mods.nemo_audio); const exlr8 = exlr8_build.coreAlias(b, target, optimize, mods.core); runner.addImport("exlr8", exlr8); const exlr8_tests = exlr8_build.testModules(b, target, optimize, exlr8); @@ -352,7 +356,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st b.step("test-trainer-close-host", "Actual native close and real Flash Next trainer ownership sentinels").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"Save recovery:"} })).step); const template, const server_tests = @import("cuda_server_host.zig").steps(b, host, cuda, mods, native_modules, build_options, windows_port, step, server_steps); // the tokenizer's own tests (memo, steps, regex, unicode) run here: no other test binary reaches them - for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen35, mods.qwen_vision, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), lfm2Module(b, host, .debug, cuda, mods.core), mods.radio, mods.heat, mods.tokenizer, native_modules.api, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen35, mods.qwen_vision, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api), lfm2Module(b, host, .debug, cuda, mods.core), mods.radio, mods.nemo_audio, mods.heat, mods.tokenizer, native_modules.api, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); const selected = b.option([]const u8, "modelopt-host-filter", "One portable ModelOpt regression") orelse "modelopt host:"; const run = b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{selected} })); run.has_side_effects = true; diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 63519848f59..b0a1e837b3c 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -126,6 +126,7 @@ pub const kernels = [_]Kernel{ .{ .name = "dots_mocr", .flags = glue }, // ours: dots.mocr's text q|k|v RoPE, vision 2-D rotary and patch bias .{ .name = "vit", .flags = glue }, // ours: vision towers' LayerNorm, Linear epilogues, activations, unshuffle .{ .name = "moss_image", .flags = glue }, // ours: MOSS-Image's modulated norm, q/k rotary, situ, gated add + .{ .name = "nemo_audio", .flags = glue }, // ours: Nemotron Transcribe's audio encoder glue and head-64 attention .{ .name = "tree_round", .flags = &.{"-O3"} }, // ours: verified tree rounds for every family (cuda/tree_round.zig) .{ .name = "act_rows", .flags = &.{"-O3"} }, // ours: SwiGLU, output gates, group sums (cuda/act_rows.zig) .{ .name = "gemma4_ple", .flags = &.{"-O3"} }, // ours: Gemma 4 E-series per-layer inputs (gemma4/cuda_ple.zig) diff --git a/zig/build/cuda_readback_sites.zig b/zig/build/cuda_readback_sites.zig index 7fede488587..5a6ac4d4637 100644 --- a/zig/build/cuda_readback_sites.zig +++ b/zig/build/cuda_readback_sites.zig @@ -425,6 +425,14 @@ pub const sites = [_]Site{ .at = "ptr", .out = "std.mem.sliceAsBytes(out)[0..n]", }, + .{ + .path = "zig/tests/cuda/audio_check.zig", + .source = @embedFile("../tests/cuda/audio_check.zig"), + .ordinal = 1, + .setup = "const c = .{ .d = &rig.d }; const raw = rig.dest(u8, 46); const at = rig.src;", + .at = "at", + .out = "raw", + }, .{ .path = "zig/tests/cuda/radio_tests.zig", .source = @embedFile("../tests/cuda/radio_tests.zig"), diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index 3624ac10b03..bfd71fc467b 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -4,3 +4,4 @@ #include "contract_js_controls.cuh" #include "contract_dense_controls.cuh" #include "contract_experts_bf16_controls.cuh" +#include "contract_nemo_audio_controls.cuh" diff --git a/zig/kernels/cuda/contract_nemo_audio_controls.cuh b/zig/kernels/cuda/contract_nemo_audio_controls.cuh new file mode 100644 index 00000000000..08722a4aa5f --- /dev/null +++ b/zig/kernels/cuda/contract_nemo_audio_controls.cuh @@ -0,0 +1,36 @@ +// The contract's controls for nemo_audio.cu: each step built with CTL set, dropping what nemo_audio.cuh names. +#pragma once + +#include "nemo_audio.cuh" + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_mel(const float* __restrict__ X, long lo, long n, const tf_nemo_audio::bf16* __restrict__ win, const tf_nemo_audio::bf16* __restrict__ fb, const float* __restrict__ cs, const float* __restrict__ sn, tf_nemo_audio::bf16* __restrict__ out, int first, int valid, float preemph, float guard) { + tf_nemo_audio::mel(X, lo, n, win, fb, cs, sn, out, first, valid, preemph, guard); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_norm(const tf_nemo_audio::bf16* __restrict__ x, tf_nemo_audio::bf16* __restrict__ y, int frames, int valid, float eps) { + tf_nemo_audio::norm(x, y, frames, valid, eps); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_qk(tf_nemo_audio::bf16* __restrict__ qkv, const tf_nemo_audio::bf16* __restrict__ qw, const tf_nemo_audio::bf16* __restrict__ qb, const tf_nemo_audio::bf16* __restrict__ kw, const tf_nemo_audio::bf16* __restrict__ kb, const tf_nemo_audio::bf16* __restrict__ cs, const tf_nemo_audio::bf16* __restrict__ sn, int rows, int heads, int dim, float eps) { + tf_nemo_audio::qk(qkv, qw, qb, kw, kb, cs, sn, rows, heads, dim, eps); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_attn64(const tf_nemo_audio::bf16* __restrict__ qkv, tf_nemo_audio::bf16* __restrict__ out, int rows, int heads, float scale) { + tf_nemo_audio::attend<64, true>(qkv, out, rows, heads, scale); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_taps(const tf_nemo_audio::bf16* __restrict__ x, tf_nemo_audio::bf16* __restrict__ y, int rows, int width) { + tf_nemo_audio::taps(x, y, rows, width); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_relu(tf_nemo_audio::bf16* __restrict__ x, long count) { + tf_nemo_audio::relu(x, count); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_preds(const tf_nemo_audio::bf16* __restrict__ logits, float* __restrict__ out, int rows, int spk, int sub) { + tf_nemo_audio::preds(logits, out, rows, spk, sub); +} + +extern "C" __global__ void __launch_bounds__(256) tf_ctl_nemo_fuse(const tf_nemo_audio::bf16* __restrict__ an, const float* __restrict__ preds, const tf_nemo_audio::bf16* __restrict__ nw, const tf_nemo_audio::bf16* __restrict__ nb, const tf_nemo_audio::bf16* __restrict__ K, tf_nemo_audio::bf16* __restrict__ out, tf_nemo_audio::bf16* __restrict__ sn, int width, float thr, float eps) { + tf_nemo_audio::fuse(an, preds, nw, nb, K, out, sn, width, thr, eps); +} diff --git a/zig/kernels/cuda/nemo_audio.cu b/zig/kernels/cuda/nemo_audio.cu new file mode 100644 index 00000000000..cdea31a27d8 --- /dev/null +++ b/zig/kernels/cuda/nemo_audio.cu @@ -0,0 +1,36 @@ +// Nemotron 3.5 Transcribe's audio encoder kernels: nemo_audio.cuh's steps as served. +#include "nemo_audio.cuh" + +using tf_nemo_audio::bf16; + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_mel(const float* __restrict__ X, long lo, long n, const bf16* __restrict__ win, const bf16* __restrict__ fb, const float* __restrict__ cs, const float* __restrict__ sn, bf16* __restrict__ out, int first, int valid, float preemph, float guard) { + tf_nemo_audio::mel(X, lo, n, win, fb, cs, sn, out, first, valid, preemph, guard); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_norm(const bf16* __restrict__ x, bf16* __restrict__ y, int frames, int valid, float eps) { + tf_nemo_audio::norm(x, y, frames, valid, eps); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_qk(bf16* __restrict__ qkv, const bf16* __restrict__ qw, const bf16* __restrict__ qb, const bf16* __restrict__ kw, const bf16* __restrict__ kb, const bf16* __restrict__ cs, const bf16* __restrict__ sn, int rows, int heads, int dim, float eps) { + tf_nemo_audio::qk(qkv, qw, qb, kw, kb, cs, sn, rows, heads, dim, eps); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_attn64(const bf16* __restrict__ qkv, bf16* __restrict__ out, int rows, int heads, float scale) { + tf_nemo_audio::attend<64, false>(qkv, out, rows, heads, scale); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_taps(const bf16* __restrict__ x, bf16* __restrict__ y, int rows, int width) { + tf_nemo_audio::taps(x, y, rows, width); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_relu(bf16* __restrict__ x, long count) { + tf_nemo_audio::relu(x, count); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_preds(const bf16* __restrict__ logits, float* __restrict__ out, int rows, int spk, int sub) { + tf_nemo_audio::preds(logits, out, rows, spk, sub); +} + +extern "C" __global__ void __launch_bounds__(256) tf_nemo_fuse(const bf16* __restrict__ an, const float* __restrict__ preds, const bf16* __restrict__ nw, const bf16* __restrict__ nb, const bf16* __restrict__ K, bf16* __restrict__ out, bf16* __restrict__ sn, int width, float thr, float eps) { + tf_nemo_audio::fuse(an, preds, nw, nb, K, out, sn, width, thr, eps); +} diff --git a/zig/kernels/cuda/nemo_audio.cuh b/zig/kernels/cuda/nemo_audio.cuh new file mode 100644 index 00000000000..013b4f48bc6 --- /dev/null +++ b/zig/kernels/cuda/nemo_audio.cuh @@ -0,0 +1,274 @@ +// Transcribe's audio encoder glue, each sum in one fixed order; the controls build each step with CTL set (see CTL:). +#pragma once + +#include +#include + +#include "common/glue_math.cuh" +#include "common/reduce.cuh" + +namespace tf_nemo_audio { + +typedef __nv_bfloat16 bf16; + +__device__ __forceinline__ float ld(const bf16* p) { return __bfloat162float(*p); } +__device__ __forceinline__ float rb(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } + +using tf_common::warp_max; +using tf_common::warp_sum; + +constexpr int FFT = 512, BINS = FFT / 2 + 1, WIN = 400, HOP = 160, MELS = 128; +constexpr int WIN_AT = (FFT - WIN) / 2; // the window's place in its 512-sample frame +constexpr int PAD = FFT / 2; // zeros before the first sample (centred frames) + +// A frame a block: pre-emphasis, window, |DFT|^2, mel filters, log(mel + guard) to bf16. CTL: the last bin left out. +template +__device__ __forceinline__ void mel(const float* __restrict__ X, long lo, long n, const bf16* __restrict__ win, + const bf16* __restrict__ fb, const float* __restrict__ cs, + const float* __restrict__ sn, bf16* __restrict__ out, int first, int valid, + float preemph, float guard) { + __shared__ float xw[WIN]; + __shared__ float pw[BINS]; + const int f = first + blockIdx.x; + bf16* o = out + (size_t)f * MELS; + if (f >= valid) { + if (threadIdx.x < MELS) o[threadIdx.x] = __float2bfloat16_rn(0.0f); + return; + } + for (int t = threadIdx.x; t < WIN; t += blockDim.x) { + const long i = (long)f * HOP - PAD + WIN_AT + t; + float y = 0.0f; + if (i >= 0 && i < n) y = i == 0 ? X[-lo] : __fsub_rn(X[i - lo], __fmul_rn(preemph, X[i - 1 - lo])); + xw[t] = __fmul_rn(y, ld(win + t)); + } + __syncthreads(); + for (int k = threadIdx.x; k < BINS; k += blockDim.x) { + float re = 0.0f, im = 0.0f; + for (int t = 0; t < WIN; ++t) { + const int j = (k * (t + WIN_AT)) & (FFT - 1); + re = __fmaf_rn(xw[t], cs[j], re); + im = __fmaf_rn(xw[t], sn[j], im); + } + pw[k] = __fadd_rn(__fmul_rn(re, re), __fmul_rn(im, im)); + } + __syncthreads(); + for (int m = threadIdx.x; m < MELS; m += blockDim.x) { + const bf16* row = fb + (size_t)m * BINS; + float a = 0.0f; + for (int k = 0; k < (CTL ? BINS - 1 : BINS); ++k) a = __fmaf_rn(ld(row + k), pw[k], a); + o[m] = __float2bfloat16_rn(logf(__fadd_rn(a, guard))); + } +} + +// Each feature over `valid` frames: (x - mean) / (sd + eps), sd with n - 1, 8 warps' sums in order. CTL: sd with n. +template +__device__ __forceinline__ void norm(const bf16* __restrict__ x, bf16* __restrict__ y, int frames, int valid, + float eps) { + __shared__ float part[8][32]; + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, c = blockIdx.x * 32 + lane; + float s = 0.0f; + for (int f = w; f < valid; f += 8) s = __fadd_rn(s, ld(x + (size_t)f * MELS + c)); + part[w][lane] = s; + __syncthreads(); + float total = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) total = __fadd_rn(total, part[i][lane]); + const float mean = __fdiv_rn(total, (float)valid); + __syncthreads(); + s = 0.0f; + for (int f = w; f < valid; f += 8) { + const float d = __fsub_rn(ld(x + (size_t)f * MELS + c), mean); + s = __fmaf_rn(d, d, s); + } + part[w][lane] = s; + __syncthreads(); + total = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) total = __fadd_rn(total, part[i][lane]); + const float sd = __fadd_rn(__fsqrt_rn(__fdiv_rn(total, (float)(CTL ? valid : valid - 1))), eps); + for (int f = w; f < frames; f += 8) { + const float v = f < valid ? __fdiv_rn(__fsub_rn(ld(x + (size_t)f * MELS + c), mean), sd) : 0.0f; + y[(size_t)f * MELS + c] = __float2bfloat16_rn(v); + } +} + +// q, k heads LayerNormed (qw set), dims (i, i + 32) turned with bf16 products, a warp a head. CTL: a c not rounded. +template +__device__ __forceinline__ void qk(bf16* __restrict__ qkv, const bf16* __restrict__ qw, const bf16* __restrict__ qb, + const bf16* __restrict__ kw, const bf16* __restrict__ kb, + const bf16* __restrict__ cs, const bf16* __restrict__ sn, int rows, int heads, + int dim, float eps) { + const int r = blockIdx.x, slot = blockIdx.y * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (r >= rows || slot >= 2 * heads) return; + bf16* h = qkv + (size_t)r * 3 * heads * dim + (size_t)slot * dim; + const int per = dim / 32; // 2 or 4: dims lane + 32 e + float v[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) v[e] = e < per ? ld(h + lane + 32 * e) : 0.0f; + if (qw != nullptr) { + const bool q = slot < heads; + const bf16* nw = q ? qw : kw; + const bf16* nb = q ? qb : kb; + float s = 0.0f; +#pragma unroll + for (int e = 0; e < 4; ++e) s = __fadd_rn(s, v[e]); + const float mean = __fdiv_rn(warp_sum(s), (float)dim); + s = 0.0f; +#pragma unroll + for (int e = 0; e < 4; ++e) + if (e < per) s = __fmaf_rn(__fsub_rn(v[e], mean), __fsub_rn(v[e], mean), s); + const float rstd = __fdiv_rn(1.0f, __fsqrt_rn(__fadd_rn(__fdiv_rn(warp_sum(s), (float)dim), eps))); +#pragma unroll + for (int e = 0; e < 4; ++e) + if (e < per) { + const int d = lane + 32 * e; + v[e] = rb(__fadd_rn(__fmul_rn(__fmul_rn(__fsub_rn(v[e], mean), rstd), ld(nw + d)), ld(nb + d))); + } + } + const float c = ld(cs + (size_t)r * 32 + lane), sv = ld(sn + (size_t)r * 32 + lane); + const float a = v[0], b = v[1]; + const float ac = CTL ? __fmul_rn(a, c) : rb(__fmul_rn(a, c)); + v[0] = rb(__fsub_rn(ac, rb(__fmul_rn(b, sv)))); + v[1] = rb(__fadd_rn(rb(__fmul_rn(b, c)), rb(__fmul_rn(a, sv)))); +#pragma unroll + for (int e = 0; e < 4; ++e) + if (e < per) h[lane + 32 * e] = __float2bfloat16_rn(v[e]); +} + +constexpr int AT_WARPS = 8, AT_TILE = 64, AT_KEYS = 1024; + +// Every row over every key, a warp a query row: f32 scores, sums in key order, rows up to AT_KEYS. CTL: drops a key. +template +__device__ __forceinline__ void attend(const bf16* __restrict__ qkv, bf16* __restrict__ out, int rows, int heads, + float scale) { + constexpr int RS = D + 2, PER = D / 32; // padded rows: a lane a key reads its own bank + __shared__ float sc[AT_WARPS][AT_KEYS]; + __shared__ float qs[AT_WARPS][D]; + __shared__ bf16 tile[AT_TILE * RS]; + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, head = blockIdx.y; + const int r = blockIdx.x * AT_WARPS + w, keys = CTL ? rows - 1 : rows; + const bool live = r < rows; + const size_t stride = (size_t)3 * heads * D; + const bf16* q = qkv + (size_t)(live ? r : 0) * stride + (size_t)head * D; + for (int d = lane; d < D; d += 32) qs[w][d] = ld(q + d); + const int tiles = (keys + AT_TILE - 1) / AT_TILE; + for (int t = 0; t < tiles; ++t) { + __syncthreads(); + for (int i = threadIdx.x; i < AT_TILE * D; i += blockDim.x) { + const int key = t * AT_TILE + i / D, d = i % D; + tile[(i / D) * RS + d] = key < keys ? qkv[(size_t)key * stride + (size_t)(heads + head) * D + d] : bf16(); + } + __syncthreads(); + for (int j = lane; j < AT_TILE; j += 32) { + const int key = t * AT_TILE + j; + if (key >= keys) break; + float s = 0.0f; +#pragma unroll 8 + for (int d = 0; d < D; ++d) s = __fmaf_rn(qs[w][d], __bfloat162float(tile[j * RS + d]), s); + sc[w][key] = __fmul_rn(s, scale); + } + } + __syncwarp(); + float m = -INFINITY; + for (int key = lane; key < keys; key += 32) m = fmaxf(m, sc[w][key]); + m = warp_max(m); + float l = 0.0f; + for (int key = lane; key < keys; key += 32) { + const float p = tf_glue::tf_exp(__fsub_rn(sc[w][key], m)); + sc[w][key] = p; + l = __fadd_rn(l, p); + } + l = warp_sum(l); + __syncwarp(); + float acc[PER]; +#pragma unroll + for (int e = 0; e < PER; ++e) acc[e] = 0.0f; + for (int t = 0; t < tiles; ++t) { + __syncthreads(); + for (int i = threadIdx.x; i < AT_TILE * D; i += blockDim.x) { + const int key = t * AT_TILE + i / D, d = i % D; + tile[(i / D) * RS + d] = key < keys ? qkv[(size_t)key * stride + (size_t)(2 * heads + head) * D + d] : bf16(); + } + __syncthreads(); + const int n = min(AT_TILE, keys - t * AT_TILE); + for (int j = 0; j < n; ++j) { + const float p = sc[w][t * AT_TILE + j]; +#pragma unroll + for (int e = 0; e < PER; ++e) acc[e] = __fmaf_rn(p, __bfloat162float(tile[j * RS + lane + 32 * e]), acc[e]); + } + } + if (!live) return; + bf16* o = out + ((size_t)r * heads + head) * D; +#pragma unroll + for (int e = 0; e < PER; ++e) o[lane + 32 * e] = __float2bfloat16_rn(__fdiv_rn(acc[e], l)); +} + +// The kernel-3 conv's taps: y [r][c 3 + k] = x[r + k - 1][c], zeros past either end. CTL: the taps one row late. +template +__device__ __forceinline__ void taps(const bf16* __restrict__ x, bf16* __restrict__ y, int rows, int width) { + const int r = blockIdx.x; + for (int i = threadIdx.x; i < 3 * width; i += blockDim.x) { + const int c = i / 3, k = i % 3, from = r + k - (CTL ? 0 : 1); + y[(size_t)r * 3 * width + i] = from >= 0 && from < rows ? x[(size_t)from * width + c] : bf16(); + } +} + +// x = max(x, 0) in place, NaN kept. CTL: fmaxf, which drops a NaN. +template +__device__ __forceinline__ void relu(bf16* __restrict__ x, long count) { + const long i = (long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + if (CTL) + x[i] = __float2bfloat16_rn(fmaxf(ld(x + i), 0.0f)); + else if (ld(x + i) < 0.0f) + x[i] = __float2bfloat16_rn(0.0f); +} + +// preds [r][s] = bf16(mean over `sub` rows of bf16(sigmoid(logits))), as f32. CTL: the sigmoids not rounded. +template +__device__ __forceinline__ void preds(const bf16* __restrict__ logits, float* __restrict__ out, int rows, int spk, + int sub) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * spk) return; + const int r = i / spk, s = i % spk; + float a = 0.0f; + for (int j = 0; j < sub; ++j) { + const float p = tf_glue::tf_sigmoid(ld(logits + ((size_t)r * sub + j) * spk + s)); + a = __fadd_rn(a, CTL ? p : rb(p)); + } + out[i] = rb(__fdiv_rn(a, (float)sub)); +} + +// out = bf16(an + bf16(LN8(preds > thr) . K)), sn the normed activity when set; a block a row. CTL: product unrounded. +template +__device__ __forceinline__ void fuse(const bf16* __restrict__ an, const float* __restrict__ preds, + const bf16* __restrict__ nw, const bf16* __restrict__ nb, + const bf16* __restrict__ K, bf16* __restrict__ out, bf16* __restrict__ sn, + int width, float thr, float eps) { + __shared__ float a[8]; + const int r = blockIdx.x; + if (threadIdx.x == 0) { + float v[8], s = 0.0f; + for (int i = 0; i < 8; ++i) { + v[i] = preds[(size_t)r * 8 + i] > thr ? 1.0f : 0.0f; + s = __fadd_rn(s, v[i]); + } + const float mean = __fdiv_rn(s, 8.0f); + s = 0.0f; + for (int i = 0; i < 8; ++i) s = __fmaf_rn(__fsub_rn(v[i], mean), __fsub_rn(v[i], mean), s); + const float rstd = __fdiv_rn(1.0f, __fsqrt_rn(__fadd_rn(__fdiv_rn(s, 8.0f), eps))); + for (int i = 0; i < 8; ++i) { + a[i] = rb(__fadd_rn(__fmul_rn(__fmul_rn(__fsub_rn(v[i], mean), rstd), ld(nw + i)), ld(nb + i))); + if (sn != nullptr) sn[(size_t)r * 8 + i] = __float2bfloat16_rn(a[i]); + } + } + __syncthreads(); + for (int c = threadIdx.x; c < width; c += blockDim.x) { + float p = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) p = __fmaf_rn(a[i], ld(K + (size_t)i * width + c), p); + out[(size_t)r * width + c] = __float2bfloat16_rn(__fadd_rn(ld(an + (size_t)r * width + c), CTL ? p : rb(p))); + } +} + +} // namespace tf_nemo_audio diff --git a/zig/src/core/contract/nemo_audio_cuda_records.zig b/zig/src/core/contract/nemo_audio_cuda_records.zig new file mode 100644 index 00000000000..ecb744fe8d4 --- /dev/null +++ b/zig/src/core/contract/nemo_audio_cuda_records.zig @@ -0,0 +1,24 @@ +//! Nemotron 3.5 Transcribe's audio encoder launches (nemo_audio.cu): its glue and head-64 attention. +const registry = @import("registry.zig"); + +/// nvcc 13.2's usage from each SM's cubin (sm_120 and sm_121 without the 1 KiB the driver reserves). +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "nemo_audio tf_nemo_mel", .symbol = "tf_nemo_mel", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 34, .static = 2628, .bound = 256 }, .{ .regs = 42, .static = 2628, .bound = 256 }, .{ .regs = 42, .static = 2628, .bound = 256 }, .{ .regs = 40, .static = 2628, .bound = 256 }, .{ .regs = 40, .static = 2628, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_norm", .symbol = "tf_nemo_norm", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 1024, .bound = 256 }, .{ .regs = 32, .static = 1024, .bound = 256 }, .{ .regs = 32, .static = 1024, .bound = 256 }, .{ .regs = 36, .static = 1024, .bound = 256 }, .{ .regs = 36, .static = 1024, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_qk", .symbol = "tf_nemo_qk", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_attn64", .symbol = "tf_nemo_attn64", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 52, .static = 43264, .bound = 256 }, .{ .regs = 53, .static = 43264, .bound = 256 }, .{ .regs = 53, .static = 43264, .bound = 256 }, .{ .regs = 69, .static = 43264, .bound = 256 }, .{ .regs = 69, .static = 43264, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_taps", .symbol = "tf_nemo_taps", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_relu", .symbol = "tf_nemo_relu", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_preds", .symbol = "tf_nemo_preds", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 29, .static = 0, .bound = 256 }, .{ .regs = 29, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "nemo_audio tf_nemo_fuse", .symbol = "tf_nemo_fuse", .image = "nemo_audio", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 32, .bound = 256 }, .{ .regs = 38, .static = 32, .bound = 256 }, .{ .regs = 38, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 }, .{ .regs = 40, .static = 32, .bound = 256 } } }, +}; + +test "Transcribe audio CUDA: every launch is in the live registry and fits every SM" { + const t = @import("std").testing; + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(@import("std").mem.eql(u8, active.launch.name, r.launch.name)); + try t.expectEqual(@as(usize, 1), found); + try t.expectEqual(@as(usize, 0), try registry.checkCuda(t.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index a13efe2350c..89fc2034c7b 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -18,6 +18,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("pocket_records.zig").cuda ++ @import("minimax_cuda_records.zig").cuda ++ @import("moss_image_cuda_records.zig").cuda ++ + @import("nemo_audio_cuda_records.zig").cuda ++ @import("exl3_dense_records.zig").cuda ++ @import("exl3_finish_records.zig").cuda ++ @import("lfm2_moe_cuda_records.zig").cuda ++ diff --git a/zig/src/core/contract/registry_sets_test.zig b/zig/src/core/contract/registry_sets_test.zig index 43979dd1ab3..3355ced4199 100644 --- a/zig/src/core/contract/registry_sets_test.zig +++ b/zig/src/core/contract/registry_sets_test.zig @@ -55,4 +55,5 @@ test { _ = @import("proposal_sampling_records.zig"); _ = @import("pocket_records.zig"); _ = @import("experts_bf16_records.zig"); + _ = @import("nemo_audio_cuda_records.zig"); } diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 58512acd76c..caff055d30e 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -58,6 +58,7 @@ pub const lfm2_moe: []const u8 = if (available) &Blob("fatbin_lfm2_moe").bytes e pub const dots_mocr: []const u8 = if (available) &Blob("fatbin_dots_mocr").bytes else &.{}; pub const vit: []const u8 = if (available) &Blob("fatbin_vit").bytes else &.{}; pub const moss_image: []const u8 = if (available) &Blob("fatbin_moss_image").bytes else &.{}; +pub const nemo_audio: []const u8 = if (available) &Blob("fatbin_nemo_audio").bytes else &.{}; pub const scan_rows: []const u8 = if (available) &Blob("fatbin_scan_rows").bytes else &.{}; pub const nemotron_ops: []const u8 = if (available) &Blob("fatbin_nemotron_ops").bytes else &.{}; pub const lane_gemv: []const u8 = if (available) &Blob("fatbin_lane_gemv").bytes else &.{}; diff --git a/zig/src/families/nemo_audio/config.zig b/zig/src/families/nemo_audio/config.zig new file mode 100644 index 00000000000..b4e7660d904 --- /dev/null +++ b/zig/src/families/nemo_audio/config.zig @@ -0,0 +1,226 @@ +//! Nemotron 3.5 Transcribe's audio side from config.json, and the geometry a clip's samples take through it. +const std = @import("std"); +const Value = std.json.Value; +const Object = std.json.ObjectMap; + +/// One transformer stack: the ASR branch or the speaker branch's encoder. +pub const Stack = struct { + width: usize, + heads: usize, + layers: usize, + ffn: usize, + rot: usize, // leading dims of each head that turn with RoPE (rotary_fraction of the head, all of it when unset) + qk_norm: bool, + base: f32, + + pub fn dim(s: Stack) usize { + return s.width / s.heads; + } +}; + +pub const Config = struct { + asr: Stack, + spk: Stack, + speakers: usize, // the speaker branch's slots (num_spks) + head_width: usize, // the speaker head's hidden width (tf_d_model) + output: usize, // the language model's width (perception.output_dim) + threshold: f32, // a slot is active past it (speaker_activity_threshold) + kernel_scale: f32, // spk_kernel_scale + boost_latest: f32, // the speaker cache's scores: frames new to it (scores_boost_latest) + score_floor: f32, // a slot's frame scores only from this probability (pred_score_threshold) + strong_rate: f32, + weak_rate: f32, + sil_per_speaker: usize, // silence rows a slot keeps in the speaker cache (spkcache_sil_frames_per_spk) + + pub const rate = 16000; + pub const hop = 160; // window_stride 0.01 s + pub const window = 400; // window_size 0.025 s + pub const fft = 512; + pub const bins = fft / 2 + 1; + pub const features = 128; + pub const stack = 8; // frames to a row (feature stacking) + /// What the dumps show beyond config.json: pre-emphasis, the log's guard, the per-feature normalisation's epsilon. + pub const preemph: f32 = 0.97; + pub const log_guard: f32 = 1.0 / 16777216.0; + pub const norm_eps: f32 = 1e-5; + pub const eps: f32 = 1e-5; // every LayerNorm + /// The windows the encoder takes a long clip in (dumps): 4000-frame cores with 400 frames of context each side. + pub const core = 4000; + pub const context = 400; + /// The speaker branch's streaming state between windows (dumps): its cache and queue rows. + pub const cache_rows = 188; + pub const fifo_rows = 40; + /// The audio a request may hold: the model card's one hour. + pub const max_seconds = 3600; + + /// The audio side, or error.NoAudioEncoder for a config without one; error.UnsupportedAudio names a setting off it. + pub fn parse(a: std.mem.Allocator, text: []const u8) !Config { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const doc = try std.json.parseFromSliceLeaky(Value, arena.allocator(), text, .{}); + const root = object(doc) orelse return error.BadConfig; + const per = object(root.get("perception")) orelse return error.NoAudioEncoder; + const pe = object(root.get("pe_encoder_config")) orelse return error.NoAudioEncoder; + try preprocessor(object(per.get("preprocessor")) orelse return error.BadConfig); + const diar = object(pe.get("diarization_model_cfg")) orelse return error.BadConfig; + const mods = object(diar.get("sortformer_modules")) orelse return error.BadConfig; + try preprocessor(object(diar.get("preprocessor")) orelse return error.BadConfig); + if (!eql(pe.get("asr_normalize_type"), "per_feature") or !eql(pe.get("diar_normalize_type"), "NA")) return error.UnsupportedAudio; + if (!eql(pe.get("speaker_feature_mode"), "thresholded")) return error.UnsupportedAudio; + const c: Config = .{ + .asr = try readStack(object(pe.get("asr_encoder_cfg")) orelse return error.BadConfig), + .spk = try readStack(object(diar.get("encoder")) orelse return error.BadConfig), + .speakers = try size(mods.get("num_spks")), + .head_width = try size(mods.get("tf_d_model")), + .output = try size(per.get("output_dim")), + .threshold = @floatCast(try float(pe.get("speaker_activity_threshold"))), + .kernel_scale = @floatCast(try float(pe.get("spk_kernel_scale"))), + .boost_latest = @floatCast(try float(mods.get("scores_boost_latest"))), + .score_floor = @floatCast(try float(mods.get("pred_score_threshold"))), + .strong_rate = @floatCast(try float(mods.get("strong_boost_rate"))), + .weak_rate = @floatCast(try float(mods.get("weak_boost_rate"))), + .sil_per_speaker = try size(mods.get("spkcache_sil_frames_per_spk")), + }; + if (c.speakers != 8 or c.head_width == 0 or c.output == 0 or c.speakers * (c.sil_per_speaker + 1) > cache_rows) return error.UnsupportedAudio; + return c; + } + + /// Mel frames the preprocessor gives n samples, the zero frame past the end included. + pub fn frames(n: usize) usize { + return n / hop + 1; + } + + /// The rows a clip of n samples gives the language model: its valid frames, eight to a row. + pub fn rows(n: usize) usize { + return std.math.divCeil(usize, n / hop, stack) catch unreachable; + } + + /// The most rows a request's audio takes (one hour). + pub fn limit() u32 { + return @intCast(rows(max_seconds * rate)); + } +}; + +/// Window i of a clip of `f` frames (`valid` of them valid): the frames it reads and the rows of its output kept. +pub const Window = struct { start: usize, end: usize, rows: usize, lo: usize, hi: usize }; + +/// One window a 4000-frame core of the `valid` frames (4200 valid frames take two, as the frames_4200 dump shows). +pub fn windowCount(valid: usize) usize { + return @max(1, std.math.divCeil(usize, valid, Config.core) catch unreachable); +} + +pub fn window(f: usize, valid: usize, i: usize) Window { + const core0 = i * Config.core; + const start = core0 -| Config.context; + const end = @min(f, core0 + Config.core + Config.context); + const total = std.math.divCeil(usize, valid, Config.stack) catch unreachable; + const lo = (core0 - start) / Config.stack; + const kept = @min(std.math.divCeil(usize, @min(f, core0 + Config.core) - core0, Config.stack) catch unreachable, total - core0 / Config.stack); + // rows of nothing but frames past the valid end are left out, which a key mask would do + const rows = std.math.divCeil(usize, @min(end, valid) - start, Config.stack) catch unreachable; + return .{ .start = start, .end = end, .rows = rows, .lo = lo, .hi = lo + kept }; +} + +fn preprocessor(p: Object) !void { + if (!eql(p.get("window"), "hann") or (try size(p.get("features"))) != Config.features or (try size(p.get("n_fft"))) != Config.fft or (try size(p.get("sample_rate"))) != Config.rate) return error.UnsupportedAudio; + if (@abs(try float(p.get("window_size")) - 0.025) > 1e-9 or @abs(try float(p.get("window_stride")) - 0.01) > 1e-9) return error.UnsupportedAudio; + if (p.get("frame_splicing")) |v| if ((try size(v)) != 1) return error.UnsupportedAudio; +} + +fn readStack(o: Object) !Stack { + const width = try size(o.get("d_model")); + const heads = try size(o.get("n_heads")); + if (width == 0 or heads == 0 or width % heads != 0) return error.BadConfig; + const dim = width / heads; + const fraction = if (o.get("rotary_fraction")) |v| try float(v) else 1.0; + const rot: usize = @intFromFloat(@as(f64, @floatFromInt(dim)) * fraction); + if (!eql(o.get("self_attention_model"), "rope") or !eql(o.get("attn_mode"), "full") or !truthy(o.get("pre_block_norm"))) return error.UnsupportedAudio; + if ((try size(o.get("subsampling_factor"))) != Config.stack or truthy(o.get("qkv_bias")) or truthy(o.get("xscaling"))) return error.UnsupportedAudio; + if (rot != 64 or rot > dim or (dim != 64 and dim != 128)) return error.UnsupportedAudio; // nemo_audio.cu turns 64 dims + const base = if (o.get("rope_base")) |v| try float(v) else 10000.0; + return .{ .width = width, .heads = heads, .layers = try size(o.get("n_layers")), .ffn = @intFromFloat(@as(f64, @floatFromInt(width)) * try float(o.get("ff_expansion"))), .rot = rot, .qk_norm = truthy(o.get("qk_norm")), .base = @floatCast(base) }; +} + +fn object(v: ?Value) ?Object { + const x = v orelse return null; + return if (x == .object) x.object else null; +} + +fn eql(v: ?Value, s: []const u8) bool { + const x = v orelse return false; + return x == .string and std.mem.eql(u8, x.string, s); +} + +fn truthy(v: ?Value) bool { + const x = v orelse return false; + return x == .bool and x.bool; +} + +fn size(v: ?Value) !usize { + const x = v orelse return error.BadConfig; + if (x != .integer or x.integer < 0) return error.BadConfig; + return @intCast(x.integer); +} + +fn float(v: ?Value) !f64 { + const x = v orelse return error.BadConfig; + return switch (x) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.BadConfig, + }; +} + +test "nemo audio rows: the dumps' clips" { + const clips = [_][2]usize{ .{ 30560, 24 }, .{ 56080, 44 }, .{ 93680, 74 }, .{ 470400, 368 }, .{ 312160, 244 }, .{ 547440, 428 }, .{ 2087520, 1631 } }; + for (clips) |c| try std.testing.expectEqual(c[1], Config.rows(c[0])); + try std.testing.expectEqual(@as(u32, 45000), Config.limit()); +} + +test "nemo audio windows: the long clip's four, and one for a clip that fits" { + const f = Config.frames(2087520); + try std.testing.expectEqual(@as(usize, 13048), f); + try std.testing.expectEqual(@as(usize, 4), windowCount(f - 1)); + const want = [_]Window{ + .{ .start = 0, .end = 4400, .rows = 550, .lo = 0, .hi = 500 }, + .{ .start = 3600, .end = 8400, .rows = 600, .lo = 50, .hi = 550 }, + .{ .start = 7600, .end = 12400, .rows = 600, .lo = 50, .hi = 550 }, + .{ .start = 11600, .end = 13048, .rows = 181, .lo = 50, .hi = 181 }, + }; + for (want, 0..) |w, i| try std.testing.expectEqual(w, window(f, f - 1, i)); + try std.testing.expectEqual(@as(usize, 1), windowCount(547440 / Config.hop)); + try std.testing.expectEqual(Window{ .start = 0, .end = 3422, .rows = 428, .lo = 0, .hi = 428 }, window(3422, 3421, 0)); +} + +test "nemo audio windows: a row of nothing but the zero frame is not encoded or kept" { + // 8 * 160 * 30 samples: 240 valid frames, the 241st (zero) frame alone in row 30 + const n = 8 * 160 * 30; + try std.testing.expectEqual(@as(usize, 30), Config.rows(n)); + const w = window(Config.frames(n), n / Config.hop, 0); + try std.testing.expectEqual(@as(usize, 30), w.rows); + try std.testing.expectEqual(@as(usize, 30), w.hi); +} + +test "nemo audio windows: 4200 valid frames take two windows, 500 rows and 25 kept" { + try std.testing.expectEqual(@as(usize, 2), windowCount(4200)); + const w0 = window(4201, 4200, 0); + const w1 = window(4201, 4200, 1); + try std.testing.expectEqual(@as(usize, 525), w0.rows); + try std.testing.expectEqual(@as(usize, 500), w0.hi - w0.lo); + try std.testing.expectEqual(@as(usize, 75), w1.rows); + try std.testing.expectEqual(@as(usize, 25), w1.hi - w1.lo); +} + +test "nemo audio windows: the kept rows cover every row once" { + for ([_]usize{ 2, 4001, 4401, 8000, 8401, 8801, 12345, 40001 }) |f| { + const valid = f - 1; + var next: usize = 0; + for (0..windowCount(valid)) |i| { + const w = window(f, valid, i); + try std.testing.expectEqual(next, w.start / Config.stack + w.lo); + try std.testing.expect(w.hi <= w.rows); + next += w.hi - w.lo; + } + try std.testing.expectEqual(std.math.divCeil(usize, valid, 8) catch unreachable, next); + } +} diff --git a/zig/src/families/nemo_audio/encoder.zig b/zig/src/families/nemo_audio/encoder.zig new file mode 100644 index 00000000000..8700e67c970 --- /dev/null +++ b/zig/src/families/nemo_audio/encoder.zig @@ -0,0 +1,291 @@ +//! Transcribe's audio encoder on CUDA: log-mel, the ASR and streaming speaker models by window, fusion, projection. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("config.zig"); +const Config = cfg.Config; +const Stack = cfg.Stack; +const weights = @import("weights.zig"); +const Weights = weights.Weights; +const Tower = weights.Tower; +const Kernels = @import("kernels.zig").Kernels; +const speaker = @import("speaker.zig"); +const Allocator = std.mem.Allocator; +const vit = cuda.vit; + +pub const Kind = enum { bf16, f32 }; + +/// Where the check CLI takes each stage: `rows` x `cols` values `ld` apart at `at` (from `row0`), stream not synced. +pub const Dump = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, s: cuda.Stream, name: []const u8, at: u64, row0: usize, rows: usize, cols: usize, ld: usize, kind: Kind) anyerror!void, + layers: bool = false, // every transformer layer's input, q k v and output too + + fn emit(d: ?Dump, s: cuda.Stream, name: []const u8, at: u64, row0: usize, rows: usize, cols: usize, kind: Kind) !void { + const x = d orelse return; + try x.put(x.ctx, s, name, at, row0, rows, cols, cols, kind); + } +}; + +/// Samples staged to the device at once: the frames of one mel launch and their context. +const chunk_frames = 4096; +const chunk_samples = chunk_frames * Config.hop + 2 * Config.fft; +/// The most rows one transformer call holds: an ASR window, or the speaker cache, queue and a window. +const asr_rows = (Config.core + 2 * Config.context) / Config.stack; +const spk_rows = Config.cache_rows + Config.fifo_rows + asr_rows; + +pub const Encoder = struct { + gpa: Allocator, + d: *const cuda.Driver, + c: Config, + w: Weights, + k: Kernels, + vk: vit.Kernels, + at: vit.Attention, + g: vit.Gemms, + scratch: cuda.DeviceBuffer, + stage: cuda.copy_source.Stage, + b: Buffers, + bytes: u64, // on the device: weights, scratch and the Linears' workspace + + const Buffers = struct { samples: u64, mel: u64, norm: u64, h: u64, x: u64, a: u64, wide: u64, acc: u64, seq: u64, cache: u64, fifo: u64, preds: u64 }; + + /// The encoder from checkpoint `dir`: its config.json's audio side and its `perception.*` tensors. + pub fn init(gpa: Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8) !Encoder { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 24)); + defer gpa.free(text); + const c = try Config.parse(gpa, text); + if (c.asr.width > vit.norm_most or c.spk.width > vit.norm_most or c.spk.dim() != 64 or c.asr.dim() != 128) return error.UnsupportedAudio; + var w = try Weights.load(gpa, io, d, dir, &c); + errdefer w.deinit(gpa); + var k = try Kernels.load(d); + errdefer k.unload(); + var vk = try vit.Kernels.load(d); + errdefer vk.unload(); + var at = try vit.Attention.load(d); + errdefer at.unload(); + var g = try vit.Gemms.init(gpa, d); + errdefer g.deinit(); + const frames = Config.limit() * Config.stack; + const row = @max(asr_rows * c.asr.width, spk_rows * c.spk.width, Config.stack * spk_rows * c.head_width); + const wide = @max(asr_rows * @max(3 * c.asr.width, c.asr.ffn), spk_rows * @max(3 * c.spk.width, c.spk.ffn, Config.stack * c.head_width), asr_rows * c.output); + const sizes = [_]usize{ 4 * chunk_samples, 2 * frames * Config.features, 2 * frames * Config.features, 2 * row, 2 * row, 2 * row, 2 * wide, 4 * wide, 2 * spk_rows * c.spk.width, 2 * Config.cache_rows * c.spk.width, 2 * Config.fifo_rows * c.spk.width, 4 * spk_rows * c.speakers }; + var total: usize = 0; + for (sizes) |sz| total += std.mem.alignForward(usize, sz, 256); + var scratch = try cuda.DeviceBuffer.alloc(d, total); + errdefer scratch.free(); + var ptrs: [sizes.len]u64 = undefined; + var off: usize = 0; + for (sizes, &ptrs) |sz, *p| { + p.* = try scratch.at(off); + off += std.mem.alignForward(usize, sz, 256); + } + var stage: cuda.copy_source.Stage = .{}; + errdefer stage.deinit(); + _ = try stage.take(d, 4 * chunk_samples); + const b: Buffers = .{ .samples = ptrs[0], .mel = ptrs[1], .norm = ptrs[2], .h = ptrs[3], .x = ptrs[4], .a = ptrs[5], .wide = ptrs[6], .acc = ptrs[7], .seq = ptrs[8], .cache = ptrs[9], .fifo = ptrs[10], .preds = ptrs[11] }; + return .{ .gpa = gpa, .d = d, .c = c, .w = w, .k = k, .vk = vk, .at = at, .g = g, .scratch = scratch, .stage = stage, .b = b, .bytes = w.bytes + total + g.workspace.len }; + } + + pub fn deinit(e: *Encoder) void { + e.stage.deinit(); + e.scratch.free(); + e.g.deinit(); + e.at.unload(); + e.vk.unload(); + e.k.unload(); + e.w.deinit(e.gpa); + } + + /// The rows a clip of n samples takes. + pub fn rows(n: usize) usize { + return Config.rows(n); + } + + /// A clip's rows, bf16 [rows(samples.len)][output] at `out`; the rows written. + pub fn encode(e: *Encoder, s: cuda.Stream, samples: []const f32, out: u64, dump: ?Dump) !usize { + const n = samples.len; + const valid = n / Config.hop; + if (valid < 2) return error.AudioTooShort; + if (n > Config.max_seconds * Config.rate) return error.AudioTooLong; + const total = Config.rows(n); + const padded = total * Config.stack; // frames the stacked rows read + try e.features(s, samples, padded, valid); + try Dump.emit(dump, s, "mel.raw", e.b.mel, 0, padded, Config.features, .bf16); + try e.k.norm(s, e.b.mel, e.b.norm, padded, valid, Config.norm_eps); + try Dump.emit(dump, s, "mel.asr_normalized_full", e.b.norm, 0, padded, Config.features, .bf16); + var st: speaker.State = .{}; + var row0: usize = 0; + const f = Config.frames(n); + const count = cfg.windowCount(valid); + for (0..count) |i| { + const win = cfg.window(f, valid, i); + const base = st.cache + st.fifo; + try e.speakers(s, &st, win, i, i + 1 < count, dump); + try e.asr(s, win, i, dump); + try e.fuse(s, win, e.b.preds + 4 * (base + win.lo) * e.c.speakers, row0, out, dump); + row0 += win.hi - win.lo; + } + std.debug.assert(row0 == total); + return total; + } + + /// The log-mel features of frames [0, padded) into mel, a chunk of samples staged at a time. + fn features(e: *Encoder, s: cuda.Stream, samples: []const f32, padded: usize, valid: usize) !void { + const w = &e.w; + var first: usize = 0; + while (first < padded) : (first += chunk_frames) { + const frames = @min(chunk_frames, padded - first); + const lo = @min(samples.len, (first * Config.hop) -| (Config.fft / 2 - (Config.fft - Config.window) / 2 + 1)); + const hi = @min(samples.len, (first + frames) * Config.hop + Config.fft); + const bytes = std.mem.sliceAsBytes(samples[lo..hi]); + if (bytes.len > 0) { + @memcpy(try e.stage.take(e.d, bytes.len), bytes); + try e.stage.copyTo(e.scratch, e.b.samples - e.scratch.ptr, s); + } + try e.k.mel(s, e.b.samples, lo, samples.len, w.window, w.fb, w.dft_cos, w.dft_sin, e.b.mel, first, frames, valid, Config.preemph, Config.log_guard); + } + } + + /// One window's speaker call ([cache; queue; window rows] to preds), then, unless it is the last, the next state. + fn speakers(e: *Encoder, s: cuda.Stream, st: *speaker.State, win: cfg.Window, i: usize, carry: bool, dump: ?Dump) !void { + const c = e.c; + const b = e.b; + const w = &e.w; + const sw = c.spk.width; + const row = 2 * sw; + const base = st.cache + st.fifo; + const n = base + win.rows; + try e.copy(s, b.seq, b.cache, st.cache * row); + try e.copy(s, b.seq + st.cache * row, b.fifo, st.fifo * row); + try e.g.run(s, b.mel + 2 * win.start * Config.features, w.spk.pre, b.seq + base * row, win.rows, sw, Config.stack * Config.features, .bf16); + try named(dump, s, "spk.call{d}.pre_encode_out", .{i}, b.seq + base * row, 0, win.rows, sw, sw, .bf16); + try named(dump, s, "spk.call{d}.enc_in", .{i}, b.seq, 0, n, sw, sw, .bf16); + try e.vk.layerNorm(s, b.seq, w.spk.embed, w.spk.embed_bias, b.h, n, sw, Config.eps); + try named(dump, s, "spk.call{d}.embed_norm_out", .{i}, b.h, 0, n, sw, sw, .bf16); + try e.transformer(s, &w.spk, c.spk, n, "spk_enc", dump); + try e.vk.layerNorm(s, b.h, w.spk.final, w.spk.final_bias, b.x, n, sw, Config.eps); + try named(dump, s, "spk.call{d}.final_norm_out", .{i}, b.x, 0, n, sw, sw, .bf16); + try e.head(s, n, i, dump); + try named(dump, s, "spk.w{d}.preds", .{i}, b.preds + 4 * (base + win.lo) * c.speakers, 0, win.hi - win.lo, c.speakers, c.speakers, .f32); + if (!carry) return; + // the state update reads the call's predictions on the host: a readback a window + try s.synchronize(); + const p = try e.gpa.alloc(f32, n * c.speakers); + defer e.gpa.free(p); + try e.scratch.download(b.preds - e.scratch.ptr, std.mem.sliceAsBytes(p)); + const next = try speaker.update(e.gpa, &c, st, p, win.lo, win.hi); + var r: usize = 0; + while (r < next.cache_len) { + var run: usize = 1; + switch (next.cache[r]) { + .sil => try e.copy(s, b.cache + r * row, w.sil, row), + .row => |x| { + while (r + run < next.cache_len and std.meta.eql(next.cache[r + run], speaker.Pick{ .row = x + @as(u32, @intCast(run)) })) run += 1; + try e.copy(s, b.cache + r * row, b.seq + x * row, run * row); + }, + } + r += run; + } + for (next.fifo[0..next.fifo_len], 0..) |x, j| try e.copy(s, b.fifo + j * row, b.seq + x * row, row); + try named(dump, s, "spk.w{d}.state_after.spkcache", .{i}, b.cache, 0, next.cache_len, sw, sw, .bf16); + try named(dump, s, "spk.w{d}.state_after.fifo", .{i}, b.fifo, 0, next.fifo_len, sw, sw, .bf16); + } + + /// The speaker head on the speaker model's output (x, n rows): each row's eight sub-rows to predictions in preds. + fn head(e: *Encoder, s: cuda.Stream, n: usize, i: usize, dump: ?Dump) !void { + const c = e.c; + const b = e.b; + const w = &e.w; + const hw = c.head_width; + const sub = Config.stack * n; + try vit.linear(&e.g, &e.vk, s, b.acc, b.x, w.enc_proj, w.enc_proj_bias, b.a, n, hw, c.spk.width); + try named(dump, s, "spk_head.encoder_proj.call{d}.out", .{i}, b.a, 0, n, hw, hw, .bf16); + try e.k.taps(s, b.a, b.h, n, hw); + try vit.linear(&e.g, &e.vk, s, b.acc, b.h, w.up, w.up_bias, b.wide, n, Config.stack * hw, 3 * hw); + try named(dump, s, "spk_head.subpixel_upsample.call{d}.out", .{i}, b.wide, 0, n, Config.stack * hw, Config.stack * hw, .bf16); + try e.k.relu(s, b.wide, sub * hw); + try vit.linear(&e.g, &e.vk, s, b.acc, b.wide, w.hidden, w.hidden_bias, b.x, sub, hw, hw); + try named(dump, s, "spk_head.first_hidden_to_hidden.call{d}.out", .{i}, b.x, 0, sub, hw, hw, .bf16); + try e.k.relu(s, b.x, sub * hw); + try vit.linear(&e.g, &e.vk, s, b.acc, b.x, w.spks, w.spks_bias, b.a, sub, c.speakers, hw); + try named(dump, s, "spk_head.single_hidden_to_spks.call{d}.out", .{i}, b.a, 0, sub, c.speakers, c.speakers, .bf16); + try e.k.preds(s, b.a, b.preds, n, c.speakers, Config.stack); + } + + /// One window through the ASR transformer, its output in x. + fn asr(e: *Encoder, s: cuda.Stream, win: cfg.Window, i: usize, dump: ?Dump) !void { + const b = e.b; + const w = &e.w; + const aw = e.c.asr.width; + try named(dump, s, "asr.w{d}.stacked", .{i}, b.norm + 2 * win.start * Config.features, 0, win.rows, Config.stack * Config.features, Config.stack * Config.features, .bf16); + try e.g.run(s, b.norm + 2 * win.start * Config.features, w.asr.pre, b.x, win.rows, aw, Config.stack * Config.features, .bf16); + try named(dump, s, "asr.w{d}.pre_encode_out", .{i}, b.x, 0, win.rows, aw, aw, .bf16); + try e.vk.layerNorm(s, b.x, w.asr.embed, w.asr.embed_bias, b.h, win.rows, aw, Config.eps); + try named(dump, s, "asr.w{d}.embed_norm_out", .{i}, b.h, 0, win.rows, aw, aw, .bf16); + try e.transformer(s, &w.asr, e.c.asr, win.rows, "asr", dump); + try e.vk.layerNorm(s, b.h, w.asr.final, w.asr.final_bias, b.x, win.rows, aw, Config.eps); + try named(dump, s, "asr.w{d}.final_norm_out", .{i}, b.x, 0, win.rows, aw, aw, .bf16); + } + + /// The pre-norm layers on h (n rows): attention with q and k turned, then the GELU feed-forward, each added back. + fn transformer(e: *Encoder, s: cuda.Stream, t: *const Tower, cs: Stack, n: usize, comptime tag: []const u8, dump: ?Dump) !void { + const b = e.b; + const w = cs.width; + const dim = cs.dim(); + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(dim)))); + const deep: ?Dump = if (dump) |d| (if (d.layers) d else null) else null; + for (t.layers, 0..) |l, i| { + try named(deep, s, "layers." ++ tag ++ ".L{d:0>2}.in", .{i}, b.h, 0, n, w, w, .bf16); + try e.vk.layerNorm(s, b.h, l.norm1, l.norm1_bias, b.x, n, w, Config.eps); + try e.g.run(s, b.x, l.qkv, b.wide, n, 3 * w, w, .bf16); + try named(deep, s, "layers." ++ tag ++ ".L{d:0>2}.attn.w_qkv_out", .{i}, b.wide, 0, n, 3 * w, 3 * w, .bf16); + try e.k.qk(s, b.wide, l.qk_norm, t.cos, t.sin, n, cs.heads, dim, Config.eps); + try named(deep, s, "layers." ++ tag ++ ".L{d:0>2}.attn.rope_out_q", .{i}, b.wide, 0, n, w, 3 * w, .bf16); + try named(deep, s, "layers." ++ tag ++ ".L{d:0>2}.attn.rope_out_k", .{i}, b.wide + 2 * w, 0, n, w, 3 * w, .bf16); + if (dim == 64) try e.k.attention(s, b.wide, b.a, n, cs.heads, scale) else try e.at.full(s, b.wide, b.a, n, cs.heads, dim, scale); + try vit.linearAct(&e.g, &e.vk, s, b.acc, b.a, l.out, l.out_bias, b.x, n, w, w, b.h, b.h, .none); + try e.vk.layerNorm(s, b.h, l.norm2, l.norm2_bias, b.x, n, w, Config.eps); + try vit.linearAct(&e.g, &e.vk, s, b.acc, b.x, l.ff1, l.ff1_bias, b.wide, n, cs.ffn, w, null, b.wide, .gelu); + try vit.linearAct(&e.g, &e.vk, s, b.acc, b.wide, l.ff2, l.ff2_bias, b.x, n, w, cs.ffn, b.h, b.h, .none); + try named(deep, s, "layers." ++ tag ++ ".L{d:0>2}.out", .{i}, b.h, 0, n, w, w, .bf16); + } + } + + /// A window's kept ASR rows (x from row lo) normed, their speakers' activity added, projected into out from row0. + fn fuse(e: *Encoder, s: cuda.Stream, win: cfg.Window, preds: u64, row0: usize, out: u64, dump: ?Dump) !void { + const c = e.c; + const b = e.b; + const w = &e.w; + const aw = c.asr.width; + const kept = win.hi - win.lo; + const in = b.x + 2 * win.lo * aw; + try Dump.emit(dump, s, "fusion.asr_norm_in", in, row0, kept, aw, .bf16); + try e.vk.layerNorm(s, in, w.asr_norm, w.asr_norm_bias, b.a, kept, aw, Config.eps); + try Dump.emit(dump, s, "fusion.asr_norm_out", b.a, row0, kept, aw, .bf16); + try e.k.fuse(s, b.a, preds, w.diar_norm, w.diar_norm_bias, w.kernel, b.h, if (dump != null) b.wide else null, kept, aw, c.threshold, Config.eps); + try Dump.emit(dump, s, "fusion.spk_norm_out", b.wide, row0, kept, c.speakers, .bf16); + try Dump.emit(dump, s, "pe.out.fused", b.h, row0, kept, aw, .bf16); + const to = out + 2 * row0 * c.output; + try vit.linear(&e.g, &e.vk, s, b.acc, b.h, w.proj, w.proj_bias, to, kept, c.output, aw); + try Dump.emit(dump, s, "rows.final", to, row0, kept, c.output, .bf16); + } + + fn copy(e: *Encoder, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + if (bytes == 0) return; + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } +}; + +fn named(dump: ?Dump, s: cuda.Stream, comptime fmt: []const u8, args: anytype, at: u64, row0: usize, rows_: usize, cols: usize, ld: usize, kind: Kind) !void { + const d = dump orelse return; + var buf: [96]u8 = undefined; + try d.put(d.ctx, s, try std.fmt.bufPrint(&buf, fmt, args), at, row0, rows_, cols, ld, kind); +} + +test "nemo audio encoder: scratch rows cover the largest calls" { + try std.testing.expectEqual(@as(usize, 600), asr_rows); + try std.testing.expectEqual(@as(usize, 828), spk_rows); + try std.testing.expect(spk_rows <= @import("kernels.zig").attention_rows and spk_rows <= weights.rope_rows); +} diff --git a/zig/src/families/nemo_audio/kernels.zig b/zig/src/families/nemo_audio/kernels.zig new file mode 100644 index 00000000000..8463a37d64c --- /dev/null +++ b/zig/src/families/nemo_audio/kernels.zig @@ -0,0 +1,147 @@ +//! nemo_audio.cu's launches: mel features, their norm, q/k norm and rotary, head-64 attention, speaker head, fusion. +const std = @import("std"); +const cuda = @import("cuda"); + +/// The most rows one head-64 attention call takes (the kernel's score row in shared memory). +pub const attention_rows = 1024; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn ceil(n: usize, d: usize) u32 { + return @intCast((n + d - 1) / d); +} + +pub const Kernels = struct { + mod: cuda.Module, + mel_fn: cuda.Function, + norm_fn: cuda.Function, + qk_fn: cuda.Function, + attn_fn: cuda.Function, + taps_fn: cuda.Function, + relu_fn: cuda.Function, + preds_fn: cuda.Function, + fuse_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.nemo_audio); + errdefer mod.unload(); + return .{ + .mod = mod, + .mel_fn = try mod.function("tf_nemo_mel"), + .norm_fn = try mod.function("tf_nemo_norm"), + .qk_fn = try mod.function("tf_nemo_qk"), + .attn_fn = try mod.function("tf_nemo_attn64"), + .taps_fn = try mod.function("tf_nemo_taps"), + .relu_fn = try mod.function("tf_nemo_relu"), + .preds_fn = try mod.function("tf_nemo_preds"), + .fuse_fn = try mod.function("tf_nemo_fuse"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } + + /// Frames [first, first + frames) of out bf16 [frame][128] from x (f32 samples [lo, ...) of n); zeros from `valid`. + pub fn mel(k: *const Kernels, s: cuda.Stream, x: u64, lo: usize, n: usize, window: u64, fb: u64, cs: u64, sn: u64, out: u64, first: usize, frames: usize, valid: usize, preemph: f32, guard: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(lo))); + a.add(@as(i64, @intCast(n))); + for ([_]u64{ window, fb, cs, sn, out }) |p| a.add(p); + a.add(int(first)); + a.add(int(valid)); + a.add(preemph); + a.add(guard); + try go(k.mel_fn, s, .{ .x = @intCast(frames) }, &a); + } + + /// y bf16 [frames][128]: each feature of x normalised over its first `valid` frames, zeros after them. + pub fn norm(k: *const Kernels, s: cuda.Stream, x: u64, y: u64, frames: usize, valid: usize, eps: f32) !void { + if (valid < 2) return error.AudioTooShort; + var a: cuda.Args = .{}; + a.add(x); + a.add(y); + a.add(int(frames)); + a.add(int(valid)); + a.add(eps); + try go(k.norm_fn, s, .{ .x = 128 / 32 }, &a); + } + + /// qkv [rows][3 heads dim] in place: q and k heads LayerNormed (with `qk_norm`), then turned. + pub fn qk(k: *const Kernels, s: cuda.Stream, qkv: u64, qk_norm: ?[4]u64, cs: u64, sn: u64, rows: usize, heads: usize, dim: usize, eps: f32) !void { + if (dim != 64 and dim != 128) return error.UnsupportedShape; + var a: cuda.Args = .{}; + a.add(qkv); + for (qk_norm orelse [4]u64{ 0, 0, 0, 0 }) |p| a.add(p); + a.add(cs); + a.add(sn); + for ([_]usize{ rows, heads, dim }) |v| a.add(int(v)); + a.add(eps); + try go(k.qk_fn, s, .{ .x = @intCast(rows), .y = ceil(2 * heads, 8) }, &a); + } + + /// out [rows][heads 64] = softmax(q k^T scale) v of qkv [rows][3 heads 64]. + pub fn attention(k: *const Kernels, s: cuda.Stream, qkv: u64, out: u64, rows: usize, heads: usize, scale: f32) !void { + if (rows == 0) return; + if (rows > attention_rows) return error.AudioRows; + var a: cuda.Args = .{}; + a.add(qkv); + a.add(out); + a.add(int(rows)); + a.add(int(heads)); + a.add(scale); + try go(k.attn_fn, s, .{ .x = ceil(rows, 8), .y = @intCast(heads) }, &a); + } + + /// y [rows][3 width]: each row's three taps (the row before, itself, the row after) channel-major. + pub fn taps(k: *const Kernels, s: cuda.Stream, x: u64, y: u64, rows: usize, width: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(y); + a.add(int(rows)); + a.add(int(width)); + try go(k.taps_fn, s, .{ .x = @intCast(rows) }, &a); + } + + pub fn relu(k: *const Kernels, s: cuda.Stream, x: u64, count: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(count))); + try go(k.relu_fn, s, .{ .x = ceil(count, 256) }, &a); + } + + /// preds f32 [rows][spk]: the mean of each row's `sub` sigmoids of logits bf16 [rows sub][spk]. + pub fn preds(k: *const Kernels, s: cuda.Stream, logits: u64, out: u64, rows: usize, spk: usize, sub: usize) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, spk, sub }) |v| a.add(int(v)); + try go(k.preds_fn, s, .{ .x = ceil(rows * spk, 256) }, &a); + } + + /// out [rows][width] = an + LN(preds > thr) . kernel; sn (optional) [rows][8] the normed activity. + pub fn fuse(k: *const Kernels, s: cuda.Stream, an: u64, preds_: u64, nw: u64, nb: u64, kernel: u64, out: u64, sn: ?u64, rows: usize, width: usize, thr: f32, eps: f32) !void { + if (rows == 0) return; + var a: cuda.Args = .{}; + for ([_]u64{ an, preds_, nw, nb, kernel, out, sn orelse 0 }) |p| a.add(p); + a.add(int(width)); + a.add(thr); + a.add(eps); + try go(k.fuse_fn, s, .{ .x = @intCast(rows) }, &a); + } +}; + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, a: *cuda.Args) !void { + if (grid.x == 0) return; + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, s, a); +} + +test "nemo audio launch geometry" { + try std.testing.expectEqual(@as(u32, 104), ceil(828, 8)); + try std.testing.expectEqual(@as(u32, 2), ceil(2 * 8, 8)); + try std.testing.expectEqual(@as(u32, 3), ceil(2 * 10, 8)); +} diff --git a/zig/src/families/nemo_audio/nemo_audio.zig b/zig/src/families/nemo_audio/nemo_audio.zig new file mode 100644 index 00000000000..b3e711ee5bc --- /dev/null +++ b/zig/src/families/nemo_audio/nemo_audio.zig @@ -0,0 +1,16 @@ +//! Nemotron 3.5 Transcribe's audio encoder (the checkpoint's `perception.*`) on CUDA, and the WAV files it reads. +pub const Config = @import("config.zig").Config; +pub const Encoder = @import("encoder.zig").Encoder; +pub const Dump = @import("encoder.zig").Dump; +pub const Kind = @import("encoder.zig").Kind; +pub const wav = @import("wav.zig"); +pub const kernels = @import("kernels.zig"); + +test { + _ = @import("config.zig"); + _ = @import("wav.zig"); + _ = @import("speaker.zig"); + _ = @import("weights.zig"); + _ = @import("kernels.zig"); + _ = @import("encoder.zig"); +} diff --git a/zig/src/families/nemo_audio/speaker.zig b/zig/src/families/nemo_audio/speaker.zig new file mode 100644 index 00000000000..949cdee27cd --- /dev/null +++ b/zig/src/families/nemo_audio/speaker.zig @@ -0,0 +1,181 @@ +//! The speaker branch's streaming state between windows (speaker cache and queue, arXiv 2507.18446), on the host. +const std = @import("std"); +const Config = @import("config.zig").Config; +const Allocator = std.mem.Allocator; + +/// A cache row: a row of the call's sequence, or the learnable silence row. +pub const Pick = union(enum) { row: u32, sil }; + +/// The cache and queue a call starts with: rows [0, cache) of its sequence, then [cache, cache + fifo). +pub const State = struct { + cache: usize = 0, + fifo: usize = 0, + sil: [Config.cache_rows]bool = @splat(false), // cache rows that are the silence row (their predictions read as 0) +}; + +/// The next call's cache and queue, as rows of this call's sequence. +pub const Next = struct { + cache: [Config.cache_rows]Pick = undefined, + cache_len: usize = 0, + fifo: [Config.fifo_rows]u32 = undefined, + fifo_len: usize = 0, +}; + +/// The state after a call ([cache; fifo; window], preds `p`, window rows [lo, hi)): queue, overflow, compressed cache. +pub fn update(a: Allocator, c: *const Config, st: *State, p: []const f32, lo: usize, hi: usize) !Next { + const k = c.speakers; + const base = st.cache + st.fifo; + var queue: std.ArrayList(u32) = .empty; + defer queue.deinit(a); + for (st.cache..base) |r| try queue.append(a, @intCast(r)); + for (base + lo..base + hi) |r| try queue.append(a, @intCast(r)); + const popped = queue.items.len -| Config.fifo_rows; + var next: Next = .{}; + for (queue.items[popped..], 0..) |r, i| next.fifo[i] = r; + next.fifo_len = queue.items.len - popped; + // the candidates: the old cache (silence rows predict 0), then what the queue let go + const n = st.cache + popped; + const rows = try a.alloc(Pick, n); + defer a.free(rows); + const preds = try a.alloc(f64, n * k); + defer a.free(preds); + for (0..n) |i| { + const r: u32 = if (i < st.cache) @intCast(i) else queue.items[i - st.cache]; + const sil = i < st.cache and st.sil[i]; + rows[i] = if (sil) .sil else .{ .row = r }; + for (0..k) |s| preds[i * k + s] = if (sil) 0 else p[r * k + s]; + } + if (n <= Config.cache_rows) { + @memcpy(next.cache[0..n], rows); + next.cache_len = n; + } else { + const chosen = try compress(a, c, preds, n, @max(st.cache, Config.cache_rows)); + defer a.free(chosen); + for (chosen, 0..) |x, i| next.cache[i] = if (x) |t| rows[t] else .sil; + next.cache_len = chosen.len; + } + st.cache = next.cache_len; + st.fifo = next.fifo_len; + for (next.cache[0..next.cache_len], 0..) |x, i| st.sil[i] = x == .sil; + return next; +} + +/// The cache's rows from `n` candidates, speaker by speaker in time order (null: silence); `new_from` on are new. +pub fn compress(a: Allocator, c: *const Config, preds: []const f64, n: usize, new_from: usize) ![]?usize { + const k = c.speakers; + const sil = c.sil_per_speaker; + const col = n + sil; // a speaker's scores, its silence slots last + const score = try a.alloc(f64, k * col); + defer a.free(score); + // a frame's score for speaker s: log p_s + sum over the others of log(1 - p_j); none under the floor + for (0..n) |t| { + var rest: f64 = 0; + for (0..k) |s| rest += @log(clip(1 - preds[t * k + s])); + for (0..k) |s| { + const ps = preds[t * k + s]; + var v = @log(clip(ps)) + (rest - @log(clip(1 - ps))); + if (ps < c.score_floor) v = -std.math.inf(f64) else if (t >= new_from) v += c.boost_latest; + score[s * col + t] = v; + } + } + // each speaker's best frames boosted twice, then a wider set once, so every speaker keeps some + const per: f64 = @as(f64, @floatFromInt(Config.cache_rows - k * sil)) / @as(f64, @floatFromInt(k)); + const order = try a.alloc(usize, n); + defer a.free(order); + const half = -@log(0.5); + for ([2]struct { f64, f64 }{ .{ c.strong_rate, 2 * half }, .{ c.weak_rate, half } }) |b| { + const top: usize = @intFromFloat(@floor(per * b[0])); + for (0..k) |s| { + const v = score[s * col ..][0..n]; + rank(order, v); + for (order[0..@min(top, n)]) |t| { + if (std.math.isFinite(v[t])) v[t] += b[1]; + } + } + } + for (0..k) |s| for (0..sil) |j| { + score[s * col + n + j] = std.math.inf(f64); + }; + const flat = try a.alloc(usize, k * col); + defer a.free(flat); + rank(flat, score); + const keep = flat[0..Config.cache_rows]; + std.mem.sortUnstable(usize, keep, {}, std.sort.asc(usize)); + const out = try a.alloc(?usize, keep.len); + for (keep, out) |i, *o| { + const s = i / col; + const t = i % col; + o.* = if (t < n and std.math.isFinite(score[s * col + t])) t else null; + } + return out; +} + +fn clip(x: f64) f64 { + return std.math.clamp(x, 1e-30, 1.0); +} + +/// order = the indices of v from highest to lowest, ties in index order. +fn rank(order: []usize, v: []const f64) void { + for (order, 0..) |*o, i| o.* = i; + const Ctx = struct { + v: []const f64, + fn above(ctx: @This(), x: usize, y: usize) bool { + return ctx.v[x] > ctx.v[y]; + } + }; + std.sort.block(usize, order, Ctx{ .v = v }, Ctx.above); +} + +fn testConfig() Config { + const stack: @import("config.zig").Stack = .{ .width = 512, .heads = 8, .layers = 1, .ffn = 1, .rot = 64, .qk_norm = false, .base = 10000 }; + return .{ .asr = stack, .spk = stack, .speakers = 8, .head_width = 192, .output = 1, .threshold = 0.5, .kernel_scale = 1, .boost_latest = 0.05, .score_floor = 0.25, .strong_rate = 0.75, .weak_rate = 1.5, .sil_per_speaker = 1 }; +} + +test "nemo audio speaker state: the first window fills the queue, its overflow joins the cache" { + const a = std.testing.allocator; + const c = testConfig(); + var st: State = .{}; + const p = try a.alloc(f32, 60 * 8); + defer a.free(p); + @memset(p, 0); + const next = try update(a, &c, &st, p, 0, 60); + try std.testing.expectEqual(@as(usize, 20), next.cache_len); + try std.testing.expectEqual(@as(usize, 40), next.fifo_len); + try std.testing.expectEqual(Pick{ .row = 19 }, next.cache[19]); + try std.testing.expectEqual(@as(u32, 20), next.fifo[0]); + try std.testing.expectEqual(@as(u32, 59), next.fifo[39]); +} + +test "nemo audio speaker state: a short window pops nothing from a queue with room" { + const a = std.testing.allocator; + const c = testConfig(); + var st: State = .{}; + var p: [30 * 8]f32 = @splat(0); + const next = try update(a, &c, &st, &p, 0, 30); + try std.testing.expectEqual(@as(usize, 0), next.cache_len); + try std.testing.expectEqual(@as(usize, 30), next.fifo_len); +} + +test "nemo audio speaker cache: one active speaker keeps its best frames, silence rows fill the other speakers" { + const a = std.testing.allocator; + const c = testConfig(); + const n = 300; + const preds = try a.alloc(f64, n * 8); + defer a.free(preds); + @memset(preds, 1e-6); + // speaker 0 active on frames 100..299, most sure on the later ones + for (100..n) |t| preds[t * 8] = 0.5 + 0.4 * @as(f64, @floatFromInt(t - 100)) / 200.0; + const out = try compress(a, &c, preds, n, 188); + defer a.free(out); + try std.testing.expectEqual(@as(usize, 188), out.len); + var frames: usize = 0; + var last: usize = 0; + for (out) |x| if (x) |t| { + try std.testing.expect(t >= 100 and (frames == 0 or t > last)); + last = t; + frames += 1; + }; + // 180 of speaker 0's frames: 188 less every speaker's silence row + try std.testing.expectEqual(@as(usize, 180), frames); + try std.testing.expect(out[180] == null); +} diff --git a/zig/src/families/nemo_audio/wav.zig b/zig/src/families/nemo_audio/wav.zig new file mode 100644 index 00000000000..16c819420e1 --- /dev/null +++ b/zig/src/families/nemo_audio/wav.zig @@ -0,0 +1,146 @@ +//! A WAV file's samples as the encoder reads them: mono 16 kHz, each sample a float in [-1, 1). +const std = @import("std"); + +pub const rate = 16000; + +/// RIFF WAVE, one channel at 16 kHz: PCM 16, 24 or 32-bit (scaled by 2^-(bits-1)) or IEEE float32. Caller frees. +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ![]f32 { + if (bytes.len < 12 or !std.mem.eql(u8, bytes[0..4], "RIFF") or !std.mem.eql(u8, bytes[8..12], "WAVE")) return error.NotWav; + var at: usize = 12; + var format: ?Format = null; + var data: ?[]const u8 = null; + while (at + 8 <= bytes.len) { + const len = std.mem.readInt(u32, bytes[at + 4 ..][0..4], .little); + if (len > bytes.len - at - 8) return error.BadWav; + const body = bytes[at + 8 ..][0..len]; + if (std.mem.eql(u8, bytes[at..][0..4], "fmt ")) format = try Format.parse(body); + if (std.mem.eql(u8, bytes[at..][0..4], "data")) data = body; + at += 8 + len + (len & 1); + } + const f = format orelse return error.BadWav; + const d = data orelse return error.BadWav; + if (f.channels != 1) return error.WavNotMono; + if (f.rate != rate) return error.WavNot16k; + const width: usize = f.bits / 8; + const out = try gpa.alloc(f32, d.len / width); + errdefer gpa.free(out); + for (out, 0..) |*o, i| { + o.* = f.sample(d[i * width ..][0..width]); + if (!std.math.isFinite(o.*)) return error.WavNotFinite; + } + return out; +} + +const Format = struct { + float: bool, + channels: u16, + rate: u32, + bits: u16, + + fn parse(body: []const u8) !Format { + if (body.len < 16) return error.BadWav; + var tag = std.mem.readInt(u16, body[0..2], .little); + // WAVE_FORMAT_EXTENSIBLE: the subformat GUID's first two bytes are the format tag + if (tag == 0xFFFE and body.len >= 26) tag = std.mem.readInt(u16, body[24..26], .little); + const f: Format = .{ .float = tag == 3, .channels = std.mem.readInt(u16, body[2..4], .little), .rate = std.mem.readInt(u32, body[4..8], .little), .bits = std.mem.readInt(u16, body[14..16], .little) }; + const pcm = tag == 1 and (f.bits == 16 or f.bits == 24 or f.bits == 32); + if (!pcm and !(f.float and f.bits == 32)) return error.UnsupportedWav; + return f; + } + + fn sample(f: Format, p: []const u8) f32 { + if (f.float) return @bitCast(std.mem.readInt(u32, p[0..4], .little)); + return switch (f.bits) { + 16 => @as(f32, @floatFromInt(std.mem.readInt(i16, p[0..2], .little))) / 32768.0, + 24 => @as(f32, @floatFromInt(std.mem.readInt(i24, p[0..3], .little))) / 8388608.0, + else => @as(f32, @floatFromInt(std.mem.readInt(i32, p[0..4], .little))) / 2147483648.0, + }; + } +}; + +fn fixture(buf: []u8, tag: u16, channels: u16, hz: u32, bits: u16, payload: []const u8) []const u8 { + return fixtureFmt(buf, tag, null, channels, hz, bits, payload); +} + +/// A WAV file; `sub`: WAVE_FORMAT_EXTENSIBLE (tag 0xFFFE) with this subformat tag in a 40-byte fmt chunk. +fn fixtureFmt(buf: []u8, tag: u16, sub: ?u16, channels: u16, hz: u32, bits: u16, payload: []const u8) []const u8 { + const fmt_len: u32 = if (sub == null) 16 else 40; + @memcpy(buf[0..4], "RIFF"); + std.mem.writeInt(u32, buf[4..8], @intCast(20 + fmt_len + payload.len), .little); + @memcpy(buf[8..16], "WAVEfmt "); + std.mem.writeInt(u32, buf[16..20], fmt_len, .little); + std.mem.writeInt(u16, buf[20..22], tag, .little); + std.mem.writeInt(u16, buf[22..24], channels, .little); + std.mem.writeInt(u32, buf[24..28], hz, .little); + std.mem.writeInt(u32, buf[28..32], hz * channels * bits / 8, .little); + std.mem.writeInt(u16, buf[32..34], channels * bits / 8, .little); + std.mem.writeInt(u16, buf[34..36], bits, .little); + if (sub) |t| { + std.mem.writeInt(u16, buf[36..38], 22, .little); // cbSize + std.mem.writeInt(u16, buf[38..40], bits, .little); // valid bits + std.mem.writeInt(u32, buf[40..44], 4, .little); // channel mask: front centre + @memcpy(buf[44..60], &[_]u8{ 0, 0, 0, 0, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }); + std.mem.writeInt(u16, buf[44..46], t, .little); + } + const at = 20 + fmt_len; + @memcpy(buf[at..][0..4], "data"); + std.mem.writeInt(u32, buf[at + 4 ..][0..4], @intCast(payload.len), .little); + @memcpy(buf[at + 8 ..][0..payload.len], payload); + return buf[0 .. at + 8 + payload.len]; +} + +test "nemo audio wav: PCM16 and float32 samples, scaled as stored" { + const gpa = std.testing.allocator; + var buf: [64]u8 = undefined; + const pcm = [_]u8{ 0x00, 0x80, 0xff, 0x7f, 0x00, 0x40 }; + const s = try decode(gpa, fixture(&buf, 1, 1, rate, 16, &pcm)); + defer gpa.free(s); + try std.testing.expectEqualSlices(f32, &.{ -1.0, 32767.0 / 32768.0, 0.5 }, s); + const floats = [_]f32{ 0.25, -0.125 }; + const g = try decode(gpa, fixture(&buf, 3, 1, rate, 32, std.mem.sliceAsBytes(&floats))); + defer gpa.free(g); + try std.testing.expectEqualSlices(f32, &floats, g); +} + +test "nemo audio wav: other rates, stereo, 8-bit and truncated chunks are refused" { + const gpa = std.testing.allocator; + var buf: [64]u8 = undefined; + const pcm = [_]u8{ 0, 0, 0, 0 }; + try std.testing.expectError(error.WavNot16k, decode(gpa, fixture(&buf, 1, 1, 44100, 16, &pcm))); + try std.testing.expectError(error.WavNotMono, decode(gpa, fixture(&buf, 1, 2, rate, 16, &pcm))); + try std.testing.expectError(error.UnsupportedWav, decode(gpa, fixture(&buf, 1, 1, rate, 8, &pcm))); + const whole = fixture(&buf, 1, 1, rate, 16, &pcm); + try std.testing.expectError(error.BadWav, decode(gpa, whole[0 .. whole.len - 2])); + try std.testing.expectError(error.NotWav, decode(gpa, "RIFX")); +} + +test "nemo audio wav: PCM24, PCM32 and WAVE_FORMAT_EXTENSIBLE, scaled as stored" { + const gpa = std.testing.allocator; + var buf: [96]u8 = undefined; + const p24 = [_]u8{ 0x00, 0x00, 0x80, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x40 }; + const a = try decode(gpa, fixture(&buf, 1, 1, rate, 24, &p24)); + defer gpa.free(a); + try std.testing.expectEqualSlices(f32, &.{ -1.0, 8388607.0 / 8388608.0, 0.5 }, a); + const p32 = [_]u8{ 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0xc0 }; + const b = try decode(gpa, fixture(&buf, 1, 1, rate, 32, &p32)); + defer gpa.free(b); + try std.testing.expectEqualSlices(f32, &.{ -1.0, 0.5, -0.5 }, b); + const p16 = [_]u8{ 0x00, 0x40, 0x00, 0xc0 }; + const c = try decode(gpa, fixtureFmt(&buf, 0xFFFE, 1, 1, rate, 16, &p16)); + defer gpa.free(c); + try std.testing.expectEqualSlices(f32, &.{ 0.5, -0.5 }, c); + const floats = [_]f32{ 0.25, -0.125 }; + const d = try decode(gpa, fixtureFmt(&buf, 0xFFFE, 3, 1, rate, 32, std.mem.sliceAsBytes(&floats))); + defer gpa.free(d); + try std.testing.expectEqualSlices(f32, &floats, d); + try std.testing.expectError(error.WavNotMono, decode(gpa, fixtureFmt(&buf, 0xFFFE, 1, 2, rate, 16, &p16))); +} + +test "nemo audio wav: a float sample that is NaN or infinite is refused" { + const gpa = std.testing.allocator; + var buf: [64]u8 = undefined; + inline for (.{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }) |bad| { + const floats = [_]f32{ 0.25, bad, -0.125 }; + try std.testing.expectError(error.WavNotFinite, decode(gpa, fixture(&buf, 3, 1, rate, 32, std.mem.sliceAsBytes(&floats)))); + } +} diff --git a/zig/src/families/nemo_audio/weights.zig b/zig/src/families/nemo_audio/weights.zig new file mode 100644 index 00000000000..36e128ca33a --- /dev/null +++ b/zig/src/families/nemo_audio/weights.zig @@ -0,0 +1,311 @@ +//! The audio encoder's `perception.*` tensors as stored (bf16) in one allocation, plus DFT, rotary and speaker tables. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const cfg = @import("config.zig"); +const Config = cfg.Config; +const Stack = cfg.Stack; +const Allocator = std.mem.Allocator; +const st = core.safetensors; + +const prefix = "perception."; +const asr_at = "perception.encoder.asr_encoder."; +const spk_at = "perception.encoder.diarization_model.encoder."; +const head_at = "perception.encoder.diarization_model.sortformer_modules."; +/// The rotary table's rows: the most rows one speaker call holds (its cache, queue and a whole window). +pub const rope_rows = 1024; + +pub const Layer = struct { + norm1: u64, + norm1_bias: u64, + qkv: u64, // [3 width, width], no bias: q rows, then k, then v, head by head + qk_norm: ?[4]u64, // q weight, q bias, k weight, k bias [dim] (the ASR stack's) + out: u64, + out_bias: u64, + norm2: u64, + norm2_bias: u64, + ff1: u64, + ff1_bias: u64, + ff2: u64, + ff2_bias: u64, +}; + +pub const Tower = struct { + pre: u64, // pre_encode.proj [width, 8 * 128], no bias + embed: u64, + embed_bias: u64, + final: u64, + final_bias: u64, + cos: u64, // bf16 [rope_rows][32] + sin: u64, + layers: []Layer, +}; + +pub const Weights = struct { + memory: cuda.DeviceBuffer, + window: u64, // bf16 [400] + fb: u64, // bf16 [128][257] + dft_cos: u64, // f32 [512] + dft_sin: u64, + asr: Tower, + spk: Tower, + enc_proj: u64, // [head, spk width] + enc_proj_bias: u64, + up: u64, // [8 head, head 3]: the kernel-3 upsampling convolution, (channel, tap) columns + up_bias: u64, + hidden: u64, + hidden_bias: u64, + spks: u64, // [8, head] + spks_bias: u64, + sil: u64, // learnable_sil_emb [spk width] + asr_norm: u64, + asr_norm_bias: u64, + diar_norm: u64, + diar_norm_bias: u64, + kernel: u64, // bf16 [8][asr width]: speaker s's sinusoid at its position s + proj: u64, // [output, asr width] + proj_bias: u64, + bytes: u64, + + /// `dir`'s perception tensors on the device, checked against `c`. + pub fn load(gpa: Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, c: *const Config) !Weights { + var files = try open(gpa, io, dir); + defer { + for (files.items) |*f| f.close(io); + files.deinit(gpa); + } + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var p: Planner = .{ .a = arena.allocator(), .files = files.items }; + var w: Weights = undefined; + w.asr.layers = try gpa.alloc(Layer, c.asr.layers); + errdefer gpa.free(w.asr.layers); + w.spk.layers = try gpa.alloc(Layer, c.spk.layers); + errdefer gpa.free(w.spk.layers); + try p.plan(&w, c); + w.memory = try cuda.DeviceBuffer.alloc(d, p.bytes); + errdefer { + d.synchronize() catch {}; + w.memory.free(); + } + for (p.pieces.items) |piece| try w.memory.upload(piece.dst, piece.bytes); + w.bytes = p.bytes; + const base = w.memory.ptr; + shift(&w, base); + shift(&w.asr, base); + shift(&w.spk, base); + for (w.asr.layers) |*l| shiftLayer(l, base); + for (w.spk.layers) |*l| shiftLayer(l, base); + return w; + } + + pub fn deinit(w: *Weights, gpa: Allocator) void { + w.memory.free(); + gpa.free(w.asr.layers); + gpa.free(w.spk.layers); + w.* = undefined; + } +}; + +const Piece = struct { bytes: []const u8, dst: u64 }; + +const Planner = struct { + a: Allocator, + files: []const st.File, + pieces: std.ArrayList(Piece) = .empty, + bytes: u64 = 0, + taken: std.StringHashMapUnmanaged(void) = .empty, + + fn place(p: *Planner, bytes: []const u8) !u64 { + const at = std.mem.alignForward(u64, p.bytes, 256); + try p.pieces.append(p.a, .{ .bytes = bytes, .dst = at }); + p.bytes = at + bytes.len; + return at; + } + + /// `name` as stored (bf16 of `shape`), an offset from the allocation's start. + fn take(p: *Planner, name: []const u8, shape: []const usize) !u64 { + for (p.files) |*f| if (f.get(name)) |t| { + if (!t.is(.bf16, shape)) { + std.log.err("{s}: {t} {any}, expected bf16 {any}", .{ name, t.dtype, t.shape[0..t.rank], shape }); + return error.UnexpectedTensor; + } + try p.taken.put(p.a, try p.a.dupe(u8, name), {}); + return p.place(t.bytes); + }; + std.log.err("checkpoint has no tensor {s}", .{name}); + return error.MissingTensor; + } + + fn takef(p: *Planner, comptime fmt: []const u8, args: anytype, shape: []const usize) !u64 { + var buf: [160]u8 = undefined; + return p.take(try std.fmt.bufPrint(&buf, fmt, args), shape); + } + + fn plan(p: *Planner, w: *Weights, c: *const Config) !void { + w.window = try p.take(prefix ++ "preprocessor.featurizer.window", &.{Config.window}); + w.fb = try p.take(prefix ++ "preprocessor.featurizer.fb", &.{ 1, Config.features, Config.bins }); + const twiddles = try dft(p.a); + w.dft_cos = try p.place(std.mem.sliceAsBytes(twiddles[0])); + w.dft_sin = try p.place(std.mem.sliceAsBytes(twiddles[1])); + try p.tower(&w.asr, asr_at, c.asr); + try p.tower(&w.spk, spk_at, c.spk); + const sw = c.spk.width; + const hw = c.head_width; + w.enc_proj = try p.take(head_at ++ "encoder_proj.weight", &.{ hw, sw }); + w.enc_proj_bias = try p.take(head_at ++ "encoder_proj.bias", &.{hw}); + w.up = try p.take(head_at ++ "subpixel_upsample.weight", &.{ Config.stack * hw, hw, 3 }); + w.up_bias = try p.take(head_at ++ "subpixel_upsample.bias", &.{Config.stack * hw}); + w.hidden = try p.take(head_at ++ "first_hidden_to_hidden.weight", &.{ hw, hw }); + w.hidden_bias = try p.take(head_at ++ "first_hidden_to_hidden.bias", &.{hw}); + w.spks = try p.take(head_at ++ "single_hidden_to_spks.weight", &.{ c.speakers, hw }); + w.spks_bias = try p.take(head_at ++ "single_hidden_to_spks.bias", &.{c.speakers}); + w.sil = try p.take(head_at ++ "learnable_sil_emb", &.{sw}); + w.asr_norm = try p.take(prefix ++ "encoder.asr_norm.weight", &.{c.asr.width}); + w.asr_norm_bias = try p.take(prefix ++ "encoder.asr_norm.bias", &.{c.asr.width}); + w.diar_norm = try p.take(prefix ++ "encoder.diar_norm.weight", &.{c.speakers}); + w.diar_norm_bias = try p.take(prefix ++ "encoder.diar_norm.bias", &.{c.speakers}); + w.kernel = try p.place(std.mem.sliceAsBytes(try speakerKernel(p.a, c.speakers, c.asr.width, c.kernel_scale))); + w.proj = try p.take(prefix ++ "proj.weight", &.{ c.output, c.asr.width }); + w.proj_bias = try p.take(prefix ++ "proj.bias", &.{c.output}); + // left unread: the speaker branch's own featurizer and hidden_to_spks, which this serving mode never calls + const unread = [_][]const u8{ "encoder.diarization_model.preprocessor.", "encoder.diarization_model.sortformer_modules.hidden_to_spks." }; + for (p.files) |*f| for (f.names.keys()) |k| { + if (!std.mem.startsWith(u8, k, prefix) or p.taken.contains(k)) continue; + const skip = for (unread) |u| { + if (std.mem.startsWith(u8, k[prefix.len..], u)) break true; + } else false; + if (skip) continue; + std.log.err("the audio encoder has a tensor these kernels do not read: {s}", .{k}); + return error.UnreadTensor; + }; + } + + fn tower(p: *Planner, t: *Tower, comptime at: []const u8, s: Stack) !void { + const n = s.width; + t.pre = try p.take(at ++ "pre_encode.proj.weight", &.{ n, Config.stack * Config.features }); + t.embed = try p.take(at ++ "embed_norm.weight", &.{n}); + t.embed_bias = try p.take(at ++ "embed_norm.bias", &.{n}); + t.final = try p.take(at ++ "final_norm.weight", &.{n}); + t.final_bias = try p.take(at ++ "final_norm.bias", &.{n}); + const angles = try rope(p.a, s); + t.cos = try p.place(std.mem.sliceAsBytes(angles[0])); + t.sin = try p.place(std.mem.sliceAsBytes(angles[1])); + const dim = s.dim(); + for (t.layers, 0..) |*l, i| { + l.norm1 = try p.takef(at ++ "layers.{d}.norm1.weight", .{i}, &.{n}); + l.norm1_bias = try p.takef(at ++ "layers.{d}.norm1.bias", .{i}, &.{n}); + l.qkv = try p.takef(at ++ "layers.{d}.attn.w_qkv.weight", .{i}, &.{ 3 * n, n }); + l.qk_norm = if (s.qk_norm) .{ + try p.takef(at ++ "layers.{d}.attn.q_norm.weight", .{i}, &.{dim}), + try p.takef(at ++ "layers.{d}.attn.q_norm.bias", .{i}, &.{dim}), + try p.takef(at ++ "layers.{d}.attn.k_norm.weight", .{i}, &.{dim}), + try p.takef(at ++ "layers.{d}.attn.k_norm.bias", .{i}, &.{dim}), + } else null; + l.out = try p.takef(at ++ "layers.{d}.attn.out_proj.weight", .{i}, &.{ n, n }); + l.out_bias = try p.takef(at ++ "layers.{d}.attn.out_proj.bias", .{i}, &.{n}); + l.norm2 = try p.takef(at ++ "layers.{d}.norm2.weight", .{i}, &.{n}); + l.norm2_bias = try p.takef(at ++ "layers.{d}.norm2.bias", .{i}, &.{n}); + l.ff1 = try p.takef(at ++ "layers.{d}.ffn.net.0.weight", .{i}, &.{ s.ffn, n }); + l.ff1_bias = try p.takef(at ++ "layers.{d}.ffn.net.0.bias", .{i}, &.{s.ffn}); + l.ff2 = try p.takef(at ++ "layers.{d}.ffn.net.3.weight", .{i}, &.{ n, s.ffn }); + l.ff2_bias = try p.takef(at ++ "layers.{d}.ffn.net.3.bias", .{i}, &.{n}); + } + } +}; + +/// Every u64 field but the byte count moved by `base`. +fn shift(s: anytype, base: u64) void { + const info = @typeInfo(@TypeOf(s.*)).@"struct"; + inline for (info.field_names, info.field_types) |name, T| if (T == u64 and comptime !std.mem.eql(u8, name, "bytes")) { + @field(s, name) += base; + }; +} + +fn shiftLayer(l: *Layer, base: u64) void { + shift(l, base); + if (l.qk_norm) |*q| for (q) |*x| { + x.* += base; + }; +} + +fn bf16(x: f64) u16 { + const f: f32 = @floatCast(x); + const u: u32 = @bitCast(f); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); // round to nearest even (finite inputs) +} + +/// cos and sin of 2 pi j / 512, j < 512, as f32. +pub fn dft(a: Allocator) ![2][]f32 { + const c = try a.alloc(f32, Config.fft); + const s = try a.alloc(f32, Config.fft); + for (c, s, 0..) |*x, *y, j| { + const t = 2.0 * std.math.pi * @as(f64, @floatFromInt(j)) / Config.fft; + x.* = @floatCast(@cos(t)); + y.* = @floatCast(@sin(t)); + } + return .{ c, s }; +} + +/// bf16 cos and sin [rope_rows][rot / 2] of row p's angle p base^(-2i / rot), i < rot / 2. +pub fn rope(a: Allocator, s: Stack) ![2][]u16 { + const half = s.rot / 2; + const c = try a.alloc(u16, rope_rows * half); + const n = try a.alloc(u16, rope_rows * half); + for (0..rope_rows) |p| for (0..half) |i| { + const inv = std.math.pow(f64, s.base, -2.0 * @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(s.rot))); + const t = @as(f64, @floatFromInt(p)) * inv; + c[p * half + i] = bf16(@cos(t)); + n[p * half + i] = bf16(@sin(t)); + }; + return .{ c, n }; +} + +/// bf16 [speakers][width]: scale sin(s w_i) at column 2i and scale cos(s w_i) at 2i + 1, w_i = 10000^(-2i / width). +pub fn speakerKernel(a: Allocator, speakers: usize, width: usize, scale: f32) ![]u16 { + const k = try a.alloc(u16, speakers * width); + for (0..speakers) |s| for (0..width / 2) |i| { + const t = @as(f64, @floatFromInt(s)) * std.math.pow(f64, 10000.0, -2.0 * @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(width))); + k[s * width + 2 * i] = bf16(scale * @sin(t)); + k[s * width + 2 * i + 1] = bf16(scale * @cos(t)); + }; + return k; +} + +/// The shards with a perception tensor, each read for its perception names alone. +fn open(gpa: Allocator, io: std.Io, dir: []const u8) !std.ArrayList(st.File) { + var out: std.ArrayList(st.File) = .empty; + errdefer { + for (out.items) |*f| f.close(io); + out.deinit(gpa); + } + const paths = try core.checkpoint.shardFiles(gpa, io, dir); + defer core.checkpoint.freeShardFiles(gpa, paths); + for (paths) |path| { + var f = try st.File.openPrefix(gpa, io, path, prefix); + if (f.names.count() == 0) { + f.close(io); + continue; + } + try out.append(gpa, f); + } + if (out.items.len == 0) return error.NoAudioEncoder; + return out; +} + +test "nemo audio tables: bf16 rounding, the speaker kernel's first rows" { + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(1.0)); + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(1.00390625)); // a tie rounds to even + try std.testing.expectEqual(@as(u16, 0x3f82), bf16(1.01171875)); + const a = std.testing.allocator; + const k = try speakerKernel(a, 8, 1280, 1.0); + defer a.free(k); + try std.testing.expectEqual(@as(u16, 0), k[0]); // sin 0 + try std.testing.expectEqual(@as(u16, 0x3f80), k[1]); // cos 0 + try std.testing.expectEqual(bf16(@sin(1.0)), k[1280]); + const r = try rope(a, .{ .width = 512, .heads = 8, .layers = 1, .ffn = 1, .rot = 64, .qk_norm = false, .base = 10000 }); + defer a.free(r[0]); + defer a.free(r[1]); + try std.testing.expectEqual(bf16(@cos(3.0)), r[0][3 * 32]); + try std.testing.expectEqual(bf16(@sin(3.0 * std.math.pow(f64, 10000.0, -2.0 / 64.0))), r[1][3 * 32 + 1]); +} diff --git a/zig/src/families/nemotron/cuda_audio.zig b/zig/src/families/nemotron/cuda_audio.zig index 785b9b949f1..39797704465 100644 --- a/zig/src/families/nemotron/cuda_audio.zig +++ b/zig/src/families/nemotron/cuda_audio.zig @@ -1,27 +1,116 @@ -//! Transcribe's audio on CUDA: a prompt pass's audio rows, spliced after each embed as image rows are. +//! Transcribe's audio on CUDA: a prompt pass's clips through the audio encoder into rows, spliced as image rows are. const std = @import("std"); const cuda = @import("cuda"); const radio = @import("radio"); +const nemo_audio = @import("nemo_audio"); + +/// A clip in a prompt: its samples (16 kHz mono) and the prompt position of its first `<|audio|>` row. +pub const Clip = struct { samples: []const f32, at: u32 }; + +/// A WAV file as the encoder reads it: its samples, the rows it takes, a hash of the samples for the prompt cache. +pub const Prepared = struct { + samples: []f32, + rows: u32, + hash: u64, + + pub fn deinit(p: *Prepared, a: std.mem.Allocator) void { + a.free(p.samples); + } +}; + +/// The rows a request's audio may take in all: an hour of it. +pub fn limit() u32 { + return nemo_audio.Config.limit(); +} + +/// A WAV file's samples and rows; error.AudioTooShort or error.AudioTooLong past what the encoder takes. +pub fn prepare(a: std.mem.Allocator, data: []const u8) !Prepared { + const samples = try nemo_audio.wav.decode(a, data); + errdefer a.free(samples); + if (samples.len / nemo_audio.Config.hop < 2) return error.AudioTooShort; + if (samples.len > nemo_audio.Config.max_seconds * nemo_audio.Config.rate) return error.AudioTooLong; + const hash = std.hash.Wyhash.hash(0x6e656d6f61756469, std.mem.sliceAsBytes(samples)); + return .{ .samples = samples, .rows = @intCast(nemo_audio.Config.rows(samples.len)), .hash = hash }; +} + +/// The clips a prompt pass from `from` reads, in prompt order, their rows back to back from row 0. +pub fn plan(a: std.mem.Allocator, clips: []const Clip, from: u32) ![]radio.Span { + var out: std.ArrayList(radio.Span) = .empty; + errdefer out.deinit(a); + var row: u32 = 0; + var end: u32 = 0; + for (clips, 0..) |c, i| { + const n: u32 = @intCast(nemo_audio.Config.rows(c.samples.len)); + if (c.at < end or n == 0) return error.AudioSpans; // in order, apart, each with rows + end = std.math.add(u32, c.at, n) catch return error.AudioSpans; + if (end <= from) continue; // a restored prefix holds these rows' states already + try out.append(a, .{ .at = c.at, .n = n, .row = row, .image = @intCast(i) }); + row = std.math.add(u32, row, n) catch return error.AudioSpans; + } + return out.toOwnedSlice(a); +} pub const Audio = struct { gpa: std.mem.Allocator, rows: radio.Rows, spans: []radio.Span = &.{}, // the prompt pass in progress: each clip's rows from its first <|audio|> position + encoder: ?*nemo_audio.Encoder = null, // null: rows come from the host (`set`) /// A rows buffer of `limit` rows of the language model's width. - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, limit: u32, hidden: usize) !*Audio { + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, rows_limit: u32, hidden: usize) !*Audio { const a = try gpa.create(Audio); errdefer gpa.destroy(a); - a.* = .{ .gpa = gpa, .rows = try radio.Rows.init(d, limit, hidden) }; + a.* = .{ .gpa = gpa, .rows = try radio.Rows.init(d, rows_limit, hidden) }; + return a; + } + + /// The checkpoint's audio encoder and a rows buffer for an hour of audio in the language model's width. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, hidden: usize) !*Audio { + const enc = try gpa.create(nemo_audio.Encoder); + errdefer gpa.destroy(enc); + enc.* = try nemo_audio.Encoder.init(gpa, io, d, dir); + errdefer enc.deinit(); + if (enc.c.output != hidden) return error.AudioWidth; + const a = try init(gpa, d, limit(), hidden); + a.encoder = enc; return a; } pub fn deinit(a: *Audio) void { - a.gpa.free(a.spans); + a.end(); + if (a.encoder) |e| { + e.deinit(); + a.gpa.destroy(e); + } a.rows.deinit(); a.gpa.destroy(a); } + /// Device bytes the encoder and the rows buffer hold. + pub fn bytes(a: *const Audio) u64 { + return a.rows.buf.len + if (a.encoder) |e| e.bytes else 0; + } + + /// A prompt pass from row `from`: the clips whose rows end past it, through the encoder into the rows buffer. + pub fn begin(a: *Audio, s: cuda.Stream, clips: []const Clip, from: usize) !void { + a.end(); + if (clips.len == 0) return; + const enc = a.encoder orelse return error.NoAudioEncoder; + a.spans = try plan(a.gpa, clips, @intCast(from)); + errdefer a.end(); + if (radio.rows.total(a.spans) > a.rows.limit) return error.AudioRows; + for (a.spans) |sp| { + const n = try enc.encode(s, clips[sp.image].samples, a.rows.at(sp), null); + if (n != sp.n) return error.AudioRows; + } + } + + /// The pass ended: no rows splice into later passes until another begins. + pub fn end(a: *Audio) void { + if (a.spans.len > 0) a.gpa.free(a.spans); + a.spans = &.{}; + } + /// One clip's bf16 rows (`rows.hidden` each) from host memory, standing at prompt positions [at, at + n). pub fn set(a: *Audio, s: cuda.Stream, at: u32, bf16: []const u8) !void { const w = a.rows.hidden * 2; @@ -29,7 +118,7 @@ pub const Audio = struct { const n: u32 = @intCast(bf16.len / w); if (n > a.rows.limit) return error.AudioRows; try a.rows.d.check(a.rows.d.api.cuMemcpyHtoDAsync_v2(a.rows.buf.ptr, bf16.ptr, bf16.len, s.handle), "cuMemcpyHtoDAsync"); - a.gpa.free(a.spans); + a.end(); a.spans = try a.gpa.dupe(radio.Span, &.{.{ .at = at, .n = n, .row = 0, .image = 0 }}); } @@ -39,3 +128,32 @@ pub const Audio = struct { try a.rows.splice(s, a.spans, @intCast(lo), @intCast(hi), emb); } }; + +test "audio plan: clips in prompt order, rows back to back, a restored prefix's clip left out" { + const a = std.testing.allocator; + const one: [30560]f32 = @splat(0); // 24 rows + const two: [56080]f32 = @splat(0); // 44 rows + const clips = [_]Clip{ .{ .samples = &one, .at = 43 }, .{ .samples = &two, .at = 80 } }; + const all = try plan(a, &clips, 0); + defer a.free(all); + try std.testing.expectEqual(@as(usize, 2), all.len); + try std.testing.expectEqual(radio.Span{ .at = 80, .n = 44, .row = 24, .image = 1 }, all[1]); + const later = try plan(a, &clips, 67); + defer a.free(later); + try std.testing.expectEqual(radio.Span{ .at = 80, .n = 44, .row = 0, .image = 1 }, later[0]); + const overlapping = [_]Clip{ .{ .samples = &one, .at = 43 }, .{ .samples = &two, .at = 50 } }; + try std.testing.expectError(error.AudioSpans, plan(a, &overlapping, 0)); +} + +test "audio limit: an hour of audio's rows" { + try std.testing.expectEqual(@as(u32, 45000), limit()); +} + +test "audio begin: a pass refused after planning leaves no spans for the next one" { + var enc: nemo_audio.Encoder = undefined; + var a: Audio = .{ .gpa = std.testing.allocator, .rows = .{ .d = undefined, .buf = undefined, .hidden = 8, .limit = 10 }, .encoder = &enc }; + const one: [30560]f32 = @splat(0); // 24 rows, over the limit of 10 + const clips = [_]Clip{.{ .samples = &one, .at = 43 }}; + try std.testing.expectError(error.AudioRows, a.begin(undefined, &clips, 0)); + try std.testing.expectEqual(@as(usize, 0), a.spans.len); +} diff --git a/zig/tests/cuda/audio_check.zig b/zig/tests/cuda/audio_check.zig new file mode 100644 index 00000000000..198d2696f85 --- /dev/null +++ b/zig/tests/cuda/audio_check.zig @@ -0,0 +1,84 @@ +//! `audio-check MODEL WAV OUT [layers]`: one clip's every encoder stage to OUT (f32 safetensors, the dumps' names). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const nemo_audio = @import("nemo_audio"); +const check = @import("check.zig"); + +const Stage = struct { cols: usize, rows: usize = 0, values: std.ArrayList(f32) = .empty }; + +const Collect = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stages: std.StringArrayHashMapUnmanaged(Stage) = .empty, + + fn put(ctx: *anyopaque, s: cuda.Stream, name: []const u8, at: u64, row0: usize, rows: usize, cols: usize, ld: usize, kind: nemo_audio.Kind) anyerror!void { + const c: *Collect = @ptrCast(@alignCast(ctx)); + const got = try c.stages.getOrPut(c.gpa, name); + if (!got.found_existing) { + got.key_ptr.* = try c.gpa.dupe(u8, name); + got.value_ptr.* = .{ .cols = cols }; + } + const st = got.value_ptr; + // a stage written once a call (row0 0 each time) runs on from the call before + if (st.cols != cols or (st.rows != row0 and row0 != 0)) return error.StageRows; + if (rows == 0) return; + try s.synchronize(); + const size: usize = if (kind == .f32) 4 else 2; + const raw = try c.gpa.alloc(u8, ((rows - 1) * ld + cols) * size); + defer c.gpa.free(raw); + try cuda.memory.download(c.d, at, raw); + for (0..rows) |r| for (0..cols) |j| { + const i = r * ld + j; + const v: f32 = if (kind == .f32) std.mem.bytesAsValue(f32, raw[4 * i ..][0..4]).* else @bitCast(@as(u32, std.mem.readInt(u16, raw[2 * i ..][0..2], .little)) << 16); + try st.values.append(c.gpa, v); + }; + st.rows += rows; + } + + fn deinit(c: *Collect) void { + for (c.stages.keys(), c.stages.values()) |k, *v| { + c.gpa.free(k); + v.values.deinit(c.gpa); + } + c.stages.deinit(c.gpa); + } +}; + +pub fn run(gpu: check.Gpu, model: []const u8, wav_path: []const u8, out_path: []const u8, layers: bool) !void { + const a = gpu.gpa; + const data = try std.Io.Dir.cwd().readFileAlloc(gpu.io, wav_path, a, .limited(1 << 31)); + defer a.free(data); + const samples = try nemo_audio.wav.decode(a, data); + defer a.free(samples); + var enc = try nemo_audio.Encoder.init(a, gpu.io, gpu.d, model); + defer enc.deinit(); + const rows = nemo_audio.Encoder.rows(samples.len); + var out = try cuda.DeviceBuffer.alloc(gpu.d, rows * enc.c.output * 2); + defer out.free(); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + // one pass to warm the Linears' plans, then the timed one, then the one that writes every stage + _ = try enc.encode(s, samples, out.ptr, null); + try s.synchronize(); + const t0 = check.now(gpu.io); + const written = try enc.encode(s, samples, out.ptr, null); + try s.synchronize(); + const ms = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e6; + var c: Collect = .{ .gpa = a, .d = gpu.d }; + defer c.deinit(); + _ = try enc.encode(s, samples, out.ptr, .{ .ctx = &c, .put = Collect.put, .layers = layers }); + try s.synchronize(); + var tensors: std.ArrayList(core.shard_edit.New) = .empty; + defer tensors.deinit(a); + var shapes: std.ArrayList([2]usize) = .empty; + defer shapes.deinit(a); + try shapes.ensureTotalCapacity(a, c.stages.count()); + for (c.stages.keys(), c.stages.values()) |k, v| { + shapes.appendAssumeCapacity(.{ v.rows, v.cols }); + try tensors.append(a, .{ .name = k, .dtype = .f32, .shape = &shapes.items[shapes.items.len - 1], .bytes = std.mem.sliceAsBytes(v.values.items) }); + } + try core.shard_edit.create(a, out_path, &.{}, tensors.items); + std.debug.print("RESULT audio-check {s}: {d} samples, {d} rows, {d} stages, encode {d:.1} ms\n", .{ wav_path, samples.len, written, tensors.items.len, ms }); + try check.expect(written == rows, "audio-check: {d} rows written, expected {d}", .{ written, rows }); +} diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index ed1bdc8d345..e112ebd3f9f 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -14,6 +14,7 @@ pub const Sets = struct { pocket: *@import("contract_pocket.zig").Set, minimax: *@import("contract_minimax.zig").Set, moss: *@import("contract_moss_image.zig").Set, + nemo_audio: *@import("contract_nemo_audio.zig").Set, modelopt: *@import("contract_flashnext_modelopt.zig").Set, grouped: *Grouped, flashnext: *@import("contract_flashnext_more.zig").Set, @@ -32,6 +33,8 @@ pub const Sets = struct { errdefer minimax.deinit(); const moss = try @import("contract_moss_image.zig").Set.init(gpu, s, a, list); errdefer moss.deinit(); + const nemo_audio = try @import("contract_nemo_audio.zig").Set.init(gpu, s, a, list); + errdefer nemo_audio.deinit(); const modelopt = try @import("contract_flashnext_modelopt.zig").Set.init(gpu, s, a, list); errdefer modelopt.deinit(); const grouped = try gpu.gpa.create(Grouped); @@ -64,6 +67,7 @@ pub const Sets = struct { .pocket = pocket, .minimax = minimax, .moss = moss, + .nemo_audio = nemo_audio, .modelopt = modelopt, .grouped = grouped, .flashnext = flashnext, @@ -85,6 +89,7 @@ pub const Sets = struct { sets.grouped.deinit(); sets.gpa.destroy(sets.grouped); sets.modelopt.deinit(); + sets.nemo_audio.deinit(); sets.moss.deinit(); sets.minimax.deinit(); sets.pocket.deinit(); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 1f970b29532..236fccbff92 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -30,7 +30,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "h3")) return &h3_image.bytes; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "moss_image", "lfm2_moe", "lfm2", "dots_mocr" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "lfm2_moe", "lfm2", "dots_mocr" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/cuda/contract_nemo_audio.zig b/zig/tests/cuda/contract_nemo_audio.zig new file mode 100644 index 00000000000..ec28b17fd02 --- /dev/null +++ b/zig/tests/cuda/contract_nemo_audio.zig @@ -0,0 +1,113 @@ +//! Transcribe's audio encoder kernels (nemo_audio.cu) under the contract, each with a control (audio-contract). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const nemo_audio = @import("nemo_audio"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const r = @import("contract_nemo_audio_ref.zig"); +const feats = @import("contract_nemo_audio_feats.zig"); +const steps = @import("contract_nemo_audio_rows.zig"); +const full = @import("contract_nemo_audio_attn.zig"); + +const g = core.contract.gates; +const K = nemo_audio.kernels.Kernels; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + k: K, + ctl: cuda.Module, + mels: [2]feats.Mel = undefined, + norms: [2]feats.Norm = undefined, + qks: [3]steps.Qk = undefined, + attns: [2]full.Full = undefined, + copies: [4]steps.Copy = undefined, + preds: [2]steps.Preds = undefined, + fuses: [2]steps.Fuse = undefined, + + /// The set, its kernels appended to `list` (each control after the kernel it breaks). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var k = try K.load(gpu.d); + errdefer k.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); + set.* = .{ .gpa = gpu.gpa, .k = k, .ctl = ctl }; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + const ends: r.Ends = .{ .a = gpu.gpa }; + var w = k; + w.mel_fn = try ctl.function("tf_ctl_nemo_mel"); + set.mels[0] = .{ .rig = rig, .k = k, .name = "cuda nemo audio tf_nemo_mel", .ends = ends }; + set.mels[1] = .{ .rig = rig, .k = w, .name = "control: nemo audio tf_nemo_mel drops the last bin", .control = .shapes, .ends = ends }; + w = k; + w.norm_fn = try ctl.function("tf_ctl_nemo_norm"); + set.norms[0] = .{ .rig = rig, .k = k, .name = "cuda nemo audio tf_nemo_norm", .ends = ends }; + set.norms[1] = .{ .rig = rig, .k = w, .name = "control: nemo audio tf_nemo_norm sd over n", .control = .shapes, .ends = ends }; + w = k; + w.qk_fn = try ctl.function("tf_ctl_nemo_qk"); + set.qks[0] = .{ .rig = rig, .k = k, .normed = true, .name = "cuda nemo audio tf_nemo_qk asr (q/k LayerNorm, 10 x 128)", .ends = ends }; + set.qks[1] = .{ .rig = rig, .k = w, .normed = true, .name = "control: nemo audio tf_nemo_qk drops bf16(a cos)", .control = .shapes, .ends = ends }; + set.qks[2] = .{ .rig = rig, .k = k, .normed = false, .name = "cuda nemo audio tf_nemo_qk speaker (8 x 64)", .ends = ends }; + w = k; + w.attn_fn = try ctl.function("tf_ctl_nemo_attn64"); + set.attns[0] = .{ .rig = rig, .k = k, .name = "cuda nemo audio tf_nemo_attn64 (full attention)" }; + set.attns[1] = .{ .rig = rig, .k = w, .name = "control: nemo audio tf_nemo_attn64 drops the last key", .control = .shapes }; + w = k; + w.taps_fn = try ctl.function("tf_ctl_nemo_taps"); + w.relu_fn = try ctl.function("tf_ctl_nemo_relu"); + set.copies[0] = .{ .rig = rig, .k = k, .relu = false, .name = "cuda nemo audio tf_nemo_taps" }; + set.copies[1] = .{ .rig = rig, .k = w, .relu = false, .name = "control: nemo audio tf_nemo_taps a row late", .control = .shapes }; + set.copies[2] = .{ .rig = rig, .k = k, .relu = true, .name = "cuda nemo audio tf_nemo_relu" }; + set.copies[3] = .{ .rig = rig, .k = w, .relu = true, .name = "control: nemo audio tf_nemo_relu drops NaN (fmaxf)", .control = .nonfinite }; + w = k; + w.preds_fn = try ctl.function("tf_ctl_nemo_preds"); + set.preds[0] = .{ .rig = rig, .k = k, .name = "cuda nemo audio tf_nemo_preds", .ends = ends }; + set.preds[1] = .{ .rig = rig, .k = w, .name = "control: nemo audio tf_nemo_preds drops bf16(sigmoid)", .control = .shapes, .ends = ends }; + w = k; + w.fuse_fn = try ctl.function("tf_ctl_nemo_fuse"); + set.fuses[0] = .{ .rig = rig, .k = k, .name = "cuda nemo audio tf_nemo_fuse", .ends = ends }; + set.fuses[1] = .{ .rig = rig, .k = w, .name = "control: nemo audio tf_nemo_fuse drops bf16(a K)", .control = .shapes, .ends = ends }; + for (&set.mels) |*x| try list.append(a, x.kernel()); + for (&set.norms) |*x| try list.append(a, x.kernel()); + for (&set.qks) |*x| try list.append(a, x.kernel()); + for (&set.attns) |*x| try list.append(a, x.kernel()); + for (&set.copies) |*x| try list.append(a, x.kernel()); + for (&set.preds) |*x| try list.append(a, x.kernel()); + for (&set.fuses) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.mels) |*x| x.deinit(); + for (&set.norms) |*x| x.deinit(); + for (&set.qks) |*x| x.deinit(); + for (&set.attns) |*x| x.deinit(); + for (&set.copies) |*x| x.deinit(); + for (&set.preds) |*x| x.deinit(); + for (&set.fuses) |*x| x.deinit(); + set.ctl.unload(); + set.k.unload(); + set.gpa.destroy(set); + } +}; + +/// The audio encoder kernels' gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x6e656d6f, &t); + std.debug.print("SUMMARY nemo audio: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "audio-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} diff --git a/zig/tests/cuda/contract_nemo_audio_attn.zig b/zig/tests/cuda/contract_nemo_audio_attn.zig new file mode 100644 index 00000000000..e69db26eea8 --- /dev/null +++ b/zig/tests/cuda/contract_nemo_audio_attn.zig @@ -0,0 +1,163 @@ +//! tf_nemo_attn64 under the contract: the speaker stack's full attention at head dim 64, head by head. +const std = @import("std"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); +const nemo_audio = @import("nemo_audio"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const D = 64; + +/// A score's 64 products, then the P x V chain over every key in order. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn scale() f32 { + return 1.0 / @sqrt(@as(f32, D)); +} + +/// Shape: heads (rows), head width (n), rows L (k): a short clip's, the first window's and a full window's calls. +pub fn spec(name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = keyChain, + .ops = 3, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 64 } }, + .served = &.{ .{ .rows = 8, .n = D, .k = 828 }, .{ .rows = 8, .n = D, .k = 550 }, .{ .rows = 8, .n = D, .k = 74 } }, + .sums = .{ .why = "P stays fp32 through the P x V sums: gates 1 and 3 hold each output to attention_ref's float64 bound" }, + }; +} + +pub const Full = struct { + rig: rig_.Rig, + k: nemo_audio.kernels.Kernels, + name: []const u8, + control: ?g.Gate = null, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + /// [L, 3 heads 128]: q heads, then k, then v (tf_moss_qk's packed rows) + qkv: []u16 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn deinit(self: *Full) void { + self.rig.gpu.gpa.free(self.qkv); + if (self.r) |*r| r.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Full) g.Kernel { + return .{ .spec = spec(self.name), .ctx = self, .vt = &vt, .control = self.control }; + } + + const vt = g.hooks(Full); + + fn stride(self: *const Full) usize { + return 3 * self.shape.rows * D; + } + + fn at(self: *const Full, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * self.stride() + (which * self.shape.rows + head) * D ..][0..D]; + } + + pub fn prepare(self: *Full, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0 or shape.k > nemo_audio.kernels.attention_rows) return false; + const a = self.rig.gpu.gpa; + self.shape = shape; + const L = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, D, L); + a.free(self.qkv); + self.qkv = &.{}; + self.qkv = try a.alloc(u16, L * self.stride()); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(L * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Full) void { + const L = self.shape.k; + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + self.at(0, 0, 0)[3] = nan; + self.at(L - 1, 2, 0)[7] = inf; + self.at(L / 2, 2, 0)[9] = ninf; + if (L >= 3) { + self.at(1, 2, 0)[11] = inf; + self.at(2, 2, 0)[11] = ninf; + } + if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Full, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const key = try a.alloc(u16, D); + defer a.free(key); + for (key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.shape.rows) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), key); + for (0..D) |e| { + attn.mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Full) !void { + try self.k.attention(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, scale()); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Full) usize { + return self.shape.k * self.shape.rows * D; + } + + /// Output head i (row i / heads, head i % heads) over every row's key and value. + pub fn load(self: *Full, i: usize, hd: *attn.Head) !void { + const row = i / self.shape.rows; + const head = i % self.shape.rows; + for (hd.q, self.at(row, 0, head)) |*y, x| y.* = c.fromBf16(x); + for (0..self.shape.k) |j| for (0..D) |e| { + hd.k[j * D + e] = c.fromBf16(self.at(j, 1, head)[e]); + hd.v[j * D + e] = c.fromBf16(self.at(j, 2, head)[e]); + }; + hd.n = self.shape.k; + } + + fn heads(self: *Full) usize { + return self.shape.k * self.shape.rows; + } + + pub fn check(self: *Full, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.heads(), scale(), try self.rig.outputBytes(), gate); + } + + pub fn reference(self: *Full, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.heads(), scale(), want, mag); + } + + pub fn simulate(self: *Full, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.heads(), scale(), acc, order, out); + } +}; diff --git a/zig/tests/cuda/contract_nemo_audio_feats.zig b/zig/tests/cuda/contract_nemo_audio_feats.zig new file mode 100644 index 00000000000..8af60eb8dbd --- /dev/null +++ b/zig/tests/cuda/contract_nemo_audio_feats.zig @@ -0,0 +1,330 @@ +//! tf_nemo_mel and tf_nemo_norm under the contract: log-mel frames and their per-feature normalisation. +const std = @import("std"); +const nemo_audio = @import("nemo_audio"); +const rig_ = @import("contract_rig.zig"); +const r = @import("contract_nemo_audio_ref.zig"); + +const c = r.c; +const g = r.g; +const Range = r.Range; +const Ends = r.Ends; +const bf = r.bf; +const K = nemo_audio.kernels; + +const fft = 512; +const bins = 257; +const win = 400; +const mels = 128; +const preemph: f32 = 0.97; +const guard: f32 = 1.0 / 16777216.0; + +// --- tf_nemo_mel: pre-emphasis, window, |DFT|^2, mel filters, log, one frame a block ------------------------------ + +fn melDepth(_: c.Shape) usize { + return win; +} + +/// Rows: frames (the last one past the valid ones), n: mel bins, k: the window. +const mel_served = [_]c.Shape{ .{ .rows = 192, .n = mels, .k = win }, .{ .rows = 586, .n = mels, .k = win }, .{ .rows = 4096, .n = mels, .k = win } }; + +pub const Mel = struct { + rig: rig_.Rig, + k: K.Kernels, + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []f32 = &.{}, + w: []u16 = &.{}, // the window [400], then the filters [128][257] + cs: [fft]f32 = undefined, + sn: [fft]f32 = undefined, + ins: [4]u64 = @splat(0), + out: u64 = 0, + ends: Ends, + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = melDepth, .ops = 8, .out = .bf16, .served = &mel_served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "a log of filtered powers: the log shrinks a sum's error to a few bf16 output ulps" } }; + } + pub fn deinit(t: *Mel) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Mel) void { + const a = t.rig.gpu.gpa; + a.free(t.x); + a.free(t.w); + t.x = &.{}; + t.w = &.{}; + } + pub fn kernel(t: *Mel) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Mel); + + pub fn prepare(t: *Mel, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows < 2) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const a = t.rig.gpu.gpa; + const n = shape.rows * 160; + t.x = try a.alloc(f32, n); + t.w = try a.alloc(u16, win + mels * bins); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + r.randomF32(rng, t.x, if (fill == .stress) -64 else -1, if (fill == .stress) 64 else 1); + r.randomBf16(rng, t.w[0..win], 0, 1); + r.randomBf16(rng, t.w[win..], 0, 0.05); + if (fill == .nonfinite) { + t.x[5] = std.math.nan(f32); + t.x[(shape.rows - 2) * 160] = std.math.inf(f32); + t.x[(shape.rows - 2) * 160 + 7] = -std.math.inf(f32); + } + for (&t.cs, &t.sn, 0..) |*x, *y, j| { + const ang = 2.0 * std.math.pi * @as(f64, @floatFromInt(j)) / fft; + x.* = @floatCast(@cos(ang)); + y.* = @floatCast(@sin(ang)); + } + t.ins[0] = try r.input(&t.rig, t.x); + t.ins[1] = try r.input(&t.rig, t.w); + t.ins[2] = try r.input(&t.rig, &t.cs); + t.ins[3] = try r.input(&t.rig, &t.sn); + t.out = try t.rig.output(shape.rows * mels * 2); + return true; + } + + pub fn run(t: *Mel) !void { + const n = t.shape.rows * 160; + try t.k.mel(t.rig.s, t.ins[0], 0, n, t.ins[1], t.ins[1] + 2 * win, t.ins[2], t.ins[3], t.out, 0, t.shape.rows, t.shape.rows - 1, preemph, guard); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Mel) usize { + return t.shape.rows * mels; + } + + /// Frame f's windowed samples, as the kernel's fp32 steps make them. + fn frame(t: *Mel, f: usize, xw: *[win]f32) void { + for (xw, 0..) |*o, i| { + const at = @as(isize, @intCast(f * 160 + i)) - 200; + var y: f32 = 0; + if (at >= 0 and at < t.x.len) { + const u: usize = @intCast(at); + y = if (u == 0) t.x[0] else t.x[u] - preemph * t.x[u - 1]; + } + o.* = y * c.fromBf16(t.w[i]); + } + } + + /// The frame's powers: each bin's re and im sums in `acc`/`order` (null: float64 with its fp32 range). + fn powers(t: *Mel, xw: *const [win]f32, how: ?struct { c.Accum, g.Order }, pw: *[bins]f64, pr: *[bins]Range) void { + var terms: [2][win]f64 = undefined; + for (0..bins) |k| { + var part: [2]Range = undefined; + var v: [2]f64 = undefined; + for (0..2) |q| { + var s: f64 = 0; + var mag: f64 = 0; + for (0..win) |i| { + const j = (k * (i + 56)) % fft; + terms[q][i] = @as(f64, xw[i]) * @as(f64, if (q == 0) t.cs[j] else t.sn[j]); + s += terms[q][i]; + mag += @abs(terms[q][i]); + } + v[q] = if (how) |h| r.rows.sumIn(h[0], h[1], &terms[q]) else s; + part[q] = r.sumRange(s, mag, win); + } + pw[k] = v[0] * v[0] + v[1] * v[1]; + pr[k] = r.sq(part[0]).fp32(0.5).add(r.sq(part[1]).fp32(0.5)).fp32(0.5); + } + } + + fn values(t: *Mel, how: ?struct { c.Accum, g.Order }, want: []f64, mag: []f64, ends: *Ends) void { + var xw: [win]f32 = undefined; + var pw: [bins]f64 = undefined; + var pr: [bins]Range = undefined; + var terms: [bins]f64 = undefined; + for (0..t.shape.rows) |f| { + if (f + 1 >= t.shape.rows) { + for (0..mels) |m| ends.put(want, mag, f * mels + m, 0, Range.of(0)); + continue; + } + t.frame(f, &xw); + t.powers(&xw, how, &pw, &pr); + for (0..mels) |m| { + var s: f64 = 0; + var lo: f64 = 0; + var hi: f64 = 0; + for (0..bins) |k| { + const w: f64 = c.fromBf16(t.w[win + m * bins + k]); + terms[k] = w * pw[k]; + s += terms[k]; + lo += w * pr[k].lo; + hi += w * pr[k].hi; + } + if (how) |h| s = r.rows.sumIn(h[0], h[1], &terms); + const e = c.gamma(bins, 0x1p-24) * hi; + const rr = (Range{ .lo = @max(lo - e, 0), .hi = hi + e }).add(Range.of(guard)).fp32(0.5).up(log).fp32(r.log_ulps).bf16(); + ends.put(want, mag, f * mels + m, bf(@log(s + guard)), rr); + } + } + } + + pub fn reference(t: *Mel, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + t.values(null, want, mag, &t.ends); + } + pub fn bounds(t: *Mel, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Mel, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + pub fn simulate(t: *Mel, acc: c.Accum, order: g.Order, out: []f64) !void { + const a = t.rig.gpu.gpa; + var scratch: Ends = .{ .a = a }; + defer scratch.deinit(); + try scratch.size(t.count()); + const mag = try a.alloc(f64, out.len); + defer a.free(mag); + t.values(.{ acc, order }, out, mag, &scratch); + } +}; + +fn log(x: f64) f64 { + return @log(x); +} + +// --- tf_nemo_norm: each feature over the valid frames, (x - mean) / (sd + eps) ------------------------------------- + +/// A warp's frames in turn (one in eight), then the eight warps' partials. +fn normDepth(s: c.Shape) usize { + return (s.k + 7) / 8 + 8; +} + +/// Rows: frames written (eight to a row), k: the valid ones, n: features. +const norm_served = [_]c.Shape{ .{ .rows = 592, .n = mels, .k = 585 }, .{ .rows = 3424, .n = mels, .k = 3421 }, .{ .rows = 13048, .n = mels, .k = 13047 } }; + +pub const Norm = struct { + rig: rig_.Rig, + k: K.Kernels, + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []u16 = &.{}, + ins: [1]u64 = @splat(0), + out: u64 = 0, + ends: Ends, + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = normDepth, .ops = 6, .out = .bf16, .served = &norm_served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the outputs are the sums' own quotients: a feature's mean and spread cancel their scale, leaving a sum's error a few bf16 ulps" } }; + } + pub fn deinit(t: *Norm) void { + t.rig.gpu.gpa.free(t.x); + t.ends.deinit(); + t.rig.deinit(); + } + pub fn kernel(t: *Norm) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Norm); + + pub fn prepare(t: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + var s = shape; + if (s.k >= s.rows) s.k = s.rows - 1; // the single-shape gates' clamped rows: one frame past the valid ones + if (s.k < 2) return false; + t.rig.reset(); + const a = t.rig.gpu.gpa; + a.free(t.x); + t.shape = s; + t.x = try a.alloc(u16, s.rows * mels); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + r.randomBf16(rng, t.x, if (fill == .stress) -24 else -12, 4); + if (fill == .nonfinite) { + t.x[0 * mels + 3] = r.nan16; + t.x[1 * mels + 9] = r.inf16; + t.x[2 * mels + 9] = r.ninf16; + t.x[1 * mels + 20] = r.ninf16; + } + t.ins[0] = try r.input(&t.rig, t.x); + t.out = try t.rig.output(s.rows * mels * 2); + return true; + } + + pub fn run(t: *Norm) !void { + try t.k.norm(t.rig.s, t.ins[0], t.out, t.shape.rows, t.shape.k, 1e-5); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Norm) usize { + return t.shape.rows * mels; + } + + fn values(t: *Norm, how: ?struct { c.Accum, g.Order }, want: []f64, mag: []f64, ends: *Ends) !void { + const a = t.rig.gpu.gpa; + const valid = t.shape.k; + const depth = normDepth(t.shape); + const col = try a.alloc(f64, valid); + defer a.free(col); + const terms = try a.alloc(f64, valid); + defer a.free(terms); + const nv: f64 = @floatFromInt(valid); + for (0..mels) |m| { + var s: f64 = 0; + var abs: f64 = 0; + for (col, 0..) |*v, f| { + v.* = c.fromBf16(t.x[f * mels + m]); + s += v.*; + abs += @abs(v.*); + } + if (how) |h| s = r.rows.sumIn(h[0], h[1], col); + const mean = s / nv; + const mr = r.scale(r.sumRange(s, abs, depth), 1 / nv).fp32(0.5); + var ss: f64 = 0; + var hi: f64 = 0; + var lo: f64 = 0; + for (col, terms) |v, *d| { + d.* = (v - mean) * (v - mean); + ss += d.*; + const dr = r.sq(r.sub(Range.of(v), mr).fp32(0.5)); + lo += dr.lo; + hi += dr.hi; + } + if (how) |h| ss = r.rows.sumIn(h[0], h[1], terms); + const e = c.gamma(@floatFromInt(depth), 0x1p-24) * hi; + const vr = r.scale(Range{ .lo = lo - e, .hi = hi + e }, 1 / (nv - 1)).fp32(0.5); + const sdr = (Range{ .lo = @sqrt(@max(vr.lo, 0)), .hi = @sqrt(vr.hi) }).fp32(0.5).add(Range.of(1e-5)).fp32(0.5); + const sd = @sqrt(ss / (nv - 1)) + 1e-5; + for (0..t.shape.rows) |f| { + const i = f * mels + m; + if (f >= valid) { + ends.put(want, mag, i, 0, Range.of(0)); + continue; + } + const v = col[f]; + ends.put(want, mag, i, bf((v - mean) / sd), r.div(r.sub(Range.of(v), mr).fp32(0.5), sdr).bf16()); + } + } + } + + pub fn reference(t: *Norm, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + try t.values(null, want, mag, &t.ends); + } + pub fn bounds(t: *Norm, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Norm, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + pub fn simulate(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + const a = t.rig.gpu.gpa; + var scratch: Ends = .{ .a = a }; + defer scratch.deinit(); + try scratch.size(t.count()); + const mag = try a.alloc(f64, out.len); + defer a.free(mag); + try t.values(.{ acc, order }, out, mag, &scratch); + } +}; diff --git a/zig/tests/cuda/contract_nemo_audio_ref.zig b/zig/tests/cuda/contract_nemo_audio_ref.zig new file mode 100644 index 00000000000..a1ce1d8ce59 --- /dev/null +++ b/zig/tests/cuda/contract_nemo_audio_ref.zig @@ -0,0 +1,104 @@ +//! Transcribe's audio kernel tests' shared parts: float64 values at the kernels' rounding points and their ranges. +const std = @import("std"); +const mi = @import("contract_moss_image_ref.zig"); + +pub const c = mi.c; +pub const g = mi.g; +pub const rows = mi.rows; +pub const Range = mi.Range; +pub const Ends = mi.Ends; +pub const bf = mi.bf; +pub const randomBf16 = mi.randomBf16; +pub const nan16 = mi.nan16; +pub const inf16 = mi.inf16; +pub const ninf16 = mi.ninf16; +pub const input = mi.input; +pub const eps: f32 = 1e-5; +const u32_ = 0x1p-24; + +/// glue_math.cuh's tf_exp and IEEE division and square root under the glue flags; CUDA's logf. +pub const exp_ulps = 2; +pub const log_ulps = 1; + +/// Why gate 4 proves no fp16 or bf16 margin for these kernels. +pub const few_terms = "a few terms of bounded size before a bf16 output: an fp16 or bf16 sum's error stays within a few output ulps"; + +/// A sum of `depth` fp32 roundings deep: its float64 value widened by gamma(depth) of its terms' magnitude. +pub fn sumRange(sum: f64, mag: f64, depth: usize) Range { + const e = c.gamma(@floatFromInt(depth), u32_) * mag; + return .{ .lo = sum - e, .hi = sum + e }; +} + +pub fn neg(a: Range) Range { + return .{ .lo = -a.hi, .hi = -a.lo }; +} + +pub fn sub(a: Range, b: Range) Range { + return a.add(neg(b)); +} + +pub fn sq(a: Range) Range { + if (a.lo <= 0 and a.hi >= 0) return .{ .lo = 0, .hi = @max(a.lo * a.lo, a.hi * a.hi) }; + return .{ .lo = @min(a.lo * a.lo, a.hi * a.hi), .hi = @max(a.lo * a.lo, a.hi * a.hi) }; +} + +/// a / b, b positive, one correctly rounded fp32 division. +pub fn div(a: Range, b: Range) Range { + return a.mul(b.recip()).fp32(0.5); +} + +pub fn scale(a: Range, s: f64) Range { + return a.mul(Range.of(s)); +} + +pub fn randomF32(rng: std.Random, out: []f32, lo: f32, hi: f32) void { + for (out) |*v| v.* = lo + rng.float(f32) * (hi - lo); +} + +/// A LayerNorm over `x` (fp32 sums `depth` deep) to the weights' bf16 point: each output's value and range. +pub fn layerNorm(x: []const f64, w: []const f64, b: []const f64, depth: usize, out: []f64, ranges: []Range) void { + const n: f64 = @floatFromInt(x.len); + var s: f64 = 0; + var mag: f64 = 0; + for (x) |v| { + s += v; + mag += @abs(v); + } + const mean = s / n; + const mr = scale(sumRange(s, mag, depth), 1 / n).fp32(0.5); + var ss: f64 = 0; + var lo: f64 = 0; + var hi: f64 = 0; + for (x) |v| { + ss += (v - mean) * (v - mean); + const d = sq(sub(Range.of(v), mr).fp32(0.5)); + lo += d.lo; + hi += d.hi; + } + const e = c.gamma(@floatFromInt(depth), u32_) * hi; + const vr = scale(Range{ .lo = lo - e, .hi = hi + e }, 1 / n).fp32(0.5).add(Range.of(eps)).fp32(0.5); + const sd = (Range{ .lo = @sqrt(@max(vr.lo, 0)), .hi = @sqrt(vr.hi) }).fp32(0.5); + const rstd = Range.of(1).mul(sd.recip()).fp32(0.5); + const inv = 1 / @sqrt(ss / n + eps); + for (x, w, b, out, ranges) |v, wi, bi, *o, *r| { + o.* = bf((v - mean) * inv * wi + bi); + r.* = sub(Range.of(v), mr).fp32(0.5).mul(rstd).fp32(0.5).mul(Range.of(wi)).fp32(0.5).add(Range.of(bi)).fp32(0.5).bf16(); + } +} + +/// The same LayerNorm with its two sums run in `acc`, `order` (gate 4's replay): the outputs at the bf16 point. +pub fn layerNormIn(acc: c.Accum, order: g.Order, a: std.mem.Allocator, x: []const f64, w: []const f64, b: []const f64, out: []f64) !void { + const n: f64 = @floatFromInt(x.len); + const mean = rows.sumIn(acc, order, x) / n; + const t = try a.alloc(f64, x.len); + defer a.free(t); + for (t, x) |*d, v| d.* = (v - mean) * (v - mean); + const inv = 1 / @sqrt(rows.sumIn(acc, order, t) / n + eps); + for (x, w, b, out) |v, wi, bi, *o| o.* = bf((v - mean) * inv * wi + bi); +} + +pub fn bfs(a: std.mem.Allocator, x: []const u16) ![]f64 { + const out = try a.alloc(f64, x.len); + for (out, x) |*o, v| o.* = c.fromBf16(v); + return out; +} diff --git a/zig/tests/cuda/contract_nemo_audio_rows.zig b/zig/tests/cuda/contract_nemo_audio_rows.zig new file mode 100644 index 00000000000..4fc69642257 --- /dev/null +++ b/zig/tests/cuda/contract_nemo_audio_rows.zig @@ -0,0 +1,486 @@ +//! tf_nemo_qk, _taps, _relu, _preds and _fuse under the contract: row steps at their bf16 rounding points. +const std = @import("std"); +const nemo_audio = @import("nemo_audio"); +const rig_ = @import("contract_rig.zig"); +const r = @import("contract_nemo_audio_ref.zig"); + +const c = r.c; +const g = r.g; +const Range = r.Range; +const Ends = r.Ends; +const bf = r.bf; +const K = nemo_audio.kernels; + +fn noSums(_: c.Shape) usize { + return 0; +} + +fn served(comptime list: []const usize, n: usize, k: usize) [list.len]c.Shape { + var out: [list.len]c.Shape = undefined; + for (&out, list) |*o, x| o.* = .{ .rows = x, .n = n, .k = k }; + return out; +} + +/// Rows the speaker model's calls take (a short clip, the first window, a full one) and the ASR windows'. +const spk_calls = [_]usize{ 74, 550, 828 }; +const asr_calls = [_]usize{ 74, 550, 600 }; +const kept = [_]usize{ 74, 500, 131 }; + +// --- tf_nemo_qk: q and k heads LayerNormed (the ASR stack), then dims (i, i + 32) turned ----------------------------- + +/// A lane's four values in turn, then the warp's five shuffles. +fn qkDepth(_: c.Shape) usize { + return 4 + 5; +} + +const qk_asr = served(&asr_calls, 10, 128); +const qk_spk = served(&spk_calls, 8, 64); + +pub const Qk = struct { + rig: rig_.Rig, + k: K.Kernels, + normed: bool, // the ASR stack's form: 10 heads of 128 with q/k LayerNorm; else 8 heads of 64 + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []u16 = &.{}, + v: []u16 = &.{}, // q weight, q bias, k weight, k bias [dim]; then cos, sin [rows][32] + ins: [2]u64 = @splat(0), + out: u64 = 0, + ends: Ends, + + pub fn spec(name: []const u8, normed: bool) c.Spec { + return .{ .name = name, .accum = if (normed) .f32 else .none, .depth = if (normed) qkDepth else noSums, .ops = 8, .mids = 3, .out = .bf16, .served = if (normed) &qk_asr else &qk_spk, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = r.few_terms } }; + } + pub fn deinit(t: *Qk) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Qk) void { + t.rig.gpu.gpa.free(t.x); + t.rig.gpu.gpa.free(t.v); + t.x = &.{}; + t.v = &.{}; + } + pub fn kernel(t: *Qk) g.Kernel { + return .{ .spec = spec(t.name, t.normed), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Qk); + + pub fn prepare(t: *Qk, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const a = t.rig.gpu.gpa; + const d = shape.k; + const w = 3 * shape.n * d; + t.x = try a.alloc(u16, shape.rows * w); + t.v = try a.alloc(u16, 4 * d + 2 * 32 * shape.rows); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + r.randomBf16(rng, t.x, if (fill == .stress) -40 else -3, if (fill == .stress) 40 else 3); + for (0..4) |i| r.randomBf16(rng, t.v[i * d ..][0..d], if (i % 2 == 0) 0.5 else -0.5, if (i % 2 == 0) 1.5 else 0.5); + r.randomBf16(rng, t.v[4 * d ..], -1, 1); + if (fill == .nonfinite) { + t.x[5] = r.nan16; // row 0, q head 0 + t.x[w + shape.n * d + 3] = r.inf16; // row 1, k head 0 + t.x[2 * w + 2 * shape.n * d + 1] = r.ninf16; // row 2, v: copied as it is + t.x[3 * w + d + 40] = r.ninf16; // row 3, q head 1 + } + t.ins[0] = try r.input(&t.rig, t.x); + t.ins[1] = try r.input(&t.rig, t.v); + t.out = try t.rig.output(t.x.len * 2); + return true; + } + + /// In place on a copy of the rows: the output buffer takes them first. + pub fn run(t: *Qk) !void { + const d = t.shape.k; + try t.rig.gpu.d.check(t.rig.gpu.d.api.cuMemcpyDtoDAsync_v2(t.out, t.ins[0], t.x.len * 2, t.rig.s.handle), "cuMemcpyDtoDAsync"); + const v = t.ins[1]; + const norms: ?[4]u64 = if (t.normed) .{ v, v + 2 * d, v + 4 * d, v + 6 * d } else null; + try t.k.qk(t.rig.s, t.out, norms, v + 8 * d, v + 8 * d + 64 * t.shape.rows, t.shape.rows, t.shape.n, d, r.eps); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Qk) usize { + return t.x.len; + } + + fn values(t: *Qk, how: ?struct { c.Accum, g.Order }, want: []f64, mag: []f64, ends: *Ends) !void { + const a = t.rig.gpu.gpa; + const d = t.shape.k; + const h = t.shape.n; + const w = 3 * h * d; + const vals = try r.bfs(a, t.v); + defer a.free(vals); + const x = try a.alloc(f64, d); + defer a.free(x); + const y = try a.alloc(f64, d); + defer a.free(y); + const yr = try a.alloc(Range, d); + defer a.free(yr); + for (0..t.shape.rows) |row| { + for (0..3 * h) |slot| { + const at = row * w + slot * d; + for (x, t.x[at..][0..d]) |*o, b| o.* = c.fromBf16(b); + if (slot >= 2 * h) { + for (x, 0..) |v, i| ends.put(want, mag, at + i, v, Range.of(v)); + continue; + } + if (t.normed) { + const nw = vals[if (slot < h) 0 else 2 * d..][0..d]; + const nb = vals[if (slot < h) d else 3 * d..][0..d]; + r.layerNorm(x, nw, nb, qkDepth(t.shape), y, yr); + if (how) |m| try r.layerNormIn(m[0], m[1], a, x, nw, nb, y); + } else for (x, y, yr) |v, *o, *q| { + o.* = v; + q.* = Range.of(v); + } + for (0..d) |i| { + if (i >= 64) { + ends.put(want, mag, at + i, y[i], yr[i]); + continue; + } + const l = i % 32; + const cs = vals[4 * d + row * 32 + l]; + const sn = vals[4 * d + 32 * t.shape.rows + row * 32 + l]; + const p = if (i < 32) .{ y[i], y[i + 32] } else .{ y[i - 32], y[i] }; + const pr = if (i < 32) .{ yr[i], yr[i + 32] } else .{ yr[i - 32], yr[i] }; + const C = Range.of(cs); + const S = Range.of(sn); + if (i < 32) ends.put(want, mag, at + i, bf(bf(p[0] * cs) - bf(p[1] * sn)), r.sub(pr[0].mul(C).fp32(0.5).bf16(), pr[1].mul(S).fp32(0.5).bf16()).fp32(0.5).bf16()) else ends.put(want, mag, at + i, bf(bf(p[1] * cs) + bf(p[0] * sn)), pr[1].mul(C).fp32(0.5).bf16().add(pr[0].mul(S).fp32(0.5).bf16()).fp32(0.5).bf16()); + } + } + } + } + + pub fn reference(t: *Qk, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + try t.values(null, want, mag, &t.ends); + } + pub fn bounds(t: *Qk, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Qk, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + pub fn simulate(t: *Qk, acc: c.Accum, order: g.Order, out: []f64) !void { + var scratch: Ends = .{ .a = t.rig.gpu.gpa }; + defer scratch.deinit(); + try scratch.size(t.count()); + const mag = try t.rig.gpu.gpa.alloc(f64, out.len); + defer t.rig.gpu.gpa.free(mag); + try t.values(.{ acc, order }, out, mag, &scratch); + } +}; + +// --- tf_nemo_taps and tf_nemo_relu: copies, exact --- + +const taps_served = served(&spk_calls, 192, 3); +const relu_served = served(&spk_calls, 1536, 1); + +pub const Copy = struct { + rig: rig_.Rig, + k: K.Kernels, + relu: bool, // tf_nemo_relu in place on a copy; else tf_nemo_taps + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []u16 = &.{}, + in: u64 = 0, + out: u64 = 0, + + pub fn spec(name: []const u8, relu: bool) c.Spec { + return .{ .name = name, .accum = .none, .depth = noSums, .out = .bf16, .served = if (relu) &relu_served else &taps_served }; + } + pub fn deinit(t: *Copy) void { + t.rig.gpu.gpa.free(t.x); + t.rig.deinit(); + } + pub fn kernel(t: *Copy) g.Kernel { + return .{ .spec = spec(t.name, t.relu), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Copy); + + pub fn prepare(t: *Copy, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0) return false; + t.rig.reset(); + const a = t.rig.gpu.gpa; + a.free(t.x); + t.shape = shape; + t.x = try a.alloc(u16, shape.rows * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + r.randomBf16(prng.random(), t.x, -4, 4); + if (fill == .nonfinite) { + t.x[1] = r.nan16; + t.x[shape.n + 2] = r.inf16; + t.x[2 * shape.n + 3] = r.ninf16; + } + t.in = try r.input(&t.rig, t.x); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Copy) !void { + if (t.relu) { + try t.rig.gpu.d.check(t.rig.gpu.d.api.cuMemcpyDtoDAsync_v2(t.out, t.in, t.x.len * 2, t.rig.s.handle), "cuMemcpyDtoDAsync"); + try t.k.relu(t.rig.s, t.out, t.x.len); + } else try t.k.taps(t.rig.s, t.in, t.out, t.shape.rows, t.shape.n); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Copy) usize { + return if (t.relu) t.x.len else 3 * t.x.len; + } + + pub fn reference(t: *Copy, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + if (t.relu) { + const v: f64 = c.fromBf16(t.x[i]); + w.* = if (v < 0) 0 else v; + } else { + const row = i / (3 * n); + const from = @as(isize, @intCast(row + i % 3)) - 1; + w.* = if (from >= 0 and from < t.shape.rows) c.fromBf16(t.x[@as(usize, @intCast(from)) * n + (i % (3 * n)) / 3]) else 0; + } + m.* = if (std.math.isFinite(w.*)) @abs(w.*) else 0; + } + } +}; + +// --- tf_nemo_preds: the mean of eight bf16 sigmoids ---------------------------------------------------------------- + +fn predsDepth(_: c.Shape) usize { + return 8; +} + +const preds_served = served(&spk_calls, 8, 8); + +pub const Preds = struct { + rig: rig_.Rig, + k: K.Kernels, + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []u16 = &.{}, + in: u64 = 0, + out: u64 = 0, + ends: Ends, + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = predsDepth, .ops = 4, .out = .f32, .store = .bf16, .served = &preds_served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = r.few_terms } }; + } + pub fn deinit(t: *Preds) void { + t.rig.gpu.gpa.free(t.x); + t.ends.deinit(); + t.rig.deinit(); + } + pub fn kernel(t: *Preds) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Preds); + + pub fn prepare(t: *Preds, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0) return false; + t.rig.reset(); + const a = t.rig.gpu.gpa; + a.free(t.x); + t.shape = shape; + t.x = try a.alloc(u16, shape.rows * 64); + var prng = std.Random.DefaultPrng.init(seed); + r.randomBf16(prng.random(), t.x, -8, 8); + if (fill == .nonfinite) { + t.x[3] = r.nan16; + t.x[64 + 9] = r.inf16; + t.x[128 + 10] = r.ninf16; + } + t.in = try r.input(&t.rig, t.x); + t.out = try t.rig.output(shape.rows * 8 * 4); + return true; + } + + pub fn run(t: *Preds) !void { + try t.k.preds(t.rig.s, t.in, t.out, t.shape.rows, 8, 8); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Preds) usize { + return t.shape.rows * 8; + } + + fn values(t: *Preds, how: ?struct { c.Accum, g.Order }, want: []f64, mag: []f64, ends: *Ends) void { + var p: [8]f64 = undefined; + for (0..t.shape.rows) |row| for (0..8) |s| { + var lo: f64 = 0; + var hi: f64 = 0; + var sum: f64 = 0; + for (&p, 0..) |*o, j| { + const x: f64 = c.fromBf16(t.x[(row * 8 + j) * 8 + s]); + o.* = bf(1 / (1 + @exp(-x))); + const er = Range.of(@exp(-x)).fp32(r.exp_ulps).add(Range.of(1)).fp32(0.5).recip().fp32(0.5).bf16(); + lo += er.lo; + hi += er.hi; + sum += o.*; + } + if (how) |h| sum = r.rows.sumIn(h[0], h[1], &p); + const e = c.gamma(8, 0x1p-24) * hi; + ends.put(want, mag, row * 8 + s, bf(sum / 8), r.scale(Range{ .lo = lo - e, .hi = hi + e }, 0.125).bf16()); + }; + } + + pub fn reference(t: *Preds, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + t.values(null, want, mag, &t.ends); + } + pub fn bounds(t: *Preds, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Preds, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + pub fn simulate(t: *Preds, acc: c.Accum, order: g.Order, out: []f64) !void { + var scratch: Ends = .{ .a = t.rig.gpu.gpa }; + defer scratch.deinit(); + try scratch.size(t.count()); + const mag = try t.rig.gpu.gpa.alloc(f64, out.len); + defer t.rig.gpu.gpa.free(mag); + t.values(.{ acc, order }, out, mag, &scratch); + } +}; + +// --- tf_nemo_fuse: the normed ASR row plus the speakers' normed activity through the kernel -------------------------- + +fn fuseDepth(_: c.Shape) usize { + return 8; +} + +const width = 1280; +const fuse_served = served(&kept, width, 8); + +pub const Fuse = struct { + rig: rig_.Rig, + k: K.Kernels, + name: []const u8, + control: ?g.Gate = null, + shape: c.Shape = undefined, + x: []u16 = &.{}, // the normed ASR rows [rows][1280], then the norm's weight and bias [8], then the kernel [8][1280] + p: []f32 = &.{}, + ins: [2]u64 = @splat(0), + out: u64 = 0, + ends: Ends, + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = fuseDepth, .ops = 8, .mids = 2, .out = .bf16, .served = &fuse_served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = r.few_terms } }; + } + pub fn deinit(t: *Fuse) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + fn free(t: *Fuse) void { + t.rig.gpu.gpa.free(t.x); + t.rig.gpu.gpa.free(t.p); + t.x = &.{}; + t.p = &.{}; + } + pub fn kernel(t: *Fuse) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = t.control }; + } + const vt = g.hooks(Fuse); + + pub fn prepare(t: *Fuse, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const a = t.rig.gpu.gpa; + const n = shape.rows * width; + t.x = try a.alloc(u16, n + 16 + 8 * width); + t.p = try a.alloc(f32, shape.rows * 8); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + r.randomBf16(rng, t.x[0..n], -3, 3); + r.randomBf16(rng, t.x[n .. n + 8], 0.5, 1.5); + r.randomBf16(rng, t.x[n + 8 .. n + 16], -0.5, 0.5); + r.randomBf16(rng, t.x[n + 16 ..], -1, 1); + for (t.p, 0..) |*v, i| v.* = if (i % 5 == 0) 0.5 else rng.float(f32); // 0.5 itself is not active + if (fill == .nonfinite) { + t.x[2] = r.nan16; + t.x[width + 4] = r.inf16; + t.x[2 * width + 4] = r.ninf16; + t.x[n + 16 + 3 * width + 7] = r.nan16; // a kernel column: every row's output there + t.p[9] = std.math.nan(f32); // a NaN prediction is not active + } + t.ins[0] = try r.input(&t.rig, t.x); + t.ins[1] = try r.input(&t.rig, t.p); + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Fuse) !void { + const n = t.shape.rows * width; + const x = t.ins[0]; + try t.k.fuse(t.rig.s, x, t.ins[1], x + 2 * n, x + 2 * n + 16, x + 2 * n + 32, t.out, null, t.shape.rows, width, 0.5, r.eps); + try t.rig.s.synchronize(); + } + + pub fn count(t: *Fuse) usize { + return t.shape.rows * width; + } + + fn values(t: *Fuse, how: ?struct { c.Accum, g.Order }, want: []f64, mag: []f64, ends: *Ends) !void { + const a = t.rig.gpu.gpa; + const n = t.shape.rows * width; + const v = try r.bfs(a, t.x[n..]); + defer a.free(v); + var act: [8]f64 = undefined; + var y: [8]f64 = undefined; + var yr: [8]Range = undefined; + var terms: [8]f64 = undefined; + for (0..t.shape.rows) |row| { + for (&act, t.p[row * 8 ..][0..8]) |*o, p| o.* = if (p > 0.5) 1 else 0; + r.layerNorm(&act, v[0..8], v[8..16], 8, &y, &yr); + if (how) |h| try r.layerNormIn(h[0], h[1], a, &act, v[0..8], v[8..16], &y); + for (0..width) |col| { + var s: f64 = 0; + var pr = Range.of(0); + var abs: f64 = 0; + for (0..8) |i| { + const kv = v[16 + i * width + col]; + terms[i] = y[i] * kv; + s += terms[i]; + pr = pr.add(yr[i].mul(Range.of(kv))); + abs += @max(@abs(yr[i].lo), @abs(yr[i].hi)) * @abs(kv); + } + if (how) |h| s = r.rows.sumIn(h[0], h[1], &terms); + const e = c.gamma(8, 0x1p-24) * abs; + const an: f64 = c.fromBf16(t.x[row * width + col]); + const rr = Range.of(an).add((Range{ .lo = pr.lo - e, .hi = pr.hi + e }).bf16()).fp32(0.5).bf16(); + ends.put(want, mag, row * width + col, bf(an + bf(s)), rr); + } + } + } + + pub fn reference(t: *Fuse, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + try t.values(null, want, mag, &t.ends); + } + pub fn bounds(t: *Fuse, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *Fuse, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + pub fn simulate(t: *Fuse, acc: c.Accum, order: g.Order, out: []f64) !void { + var scratch: Ends = .{ .a = t.rig.gpu.gpa }; + defer scratch.deinit(); + try scratch.size(t.count()); + const mag = try t.rig.gpu.gpa.alloc(f64, out.len); + defer t.rig.gpu.gpa.free(mag); + try t.values(.{ acc, order }, out, mag, &scratch); + } +}; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 7035712f1a4..094c544f97a 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -187,6 +187,7 @@ const usage = \\ radio-processor REF PICS MODEL decoded RGB, processor pixels, float resizes and grids against the reference \\ radio-kernels RADIO's float-patch cast and position rows against host references (synthetic rows) \\ radio-attention the head-dim-80 tower attention's time at five sizes, outputs finite (synthetic rows) + \\ audio-check MODEL WAV OUT [layers] | audio-contract Transcribe's audio encoder: a clip's stages to OUT | gates 1-4 \\ gdn-back DeltaNet input gradients against FP64 \\ q4-back Affine input gradients against FP64 \\ moe-back Expert and router input gradients against FP64 @@ -502,6 +503,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "radio-processor")) return radio_tests.processor(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "radio-kernels")) return radio_tests.kernels(gpu); if (std.mem.eql(u8, cmd, "radio-attention")) return radio_tests.attention(gpu); + if (std.mem.eql(u8, cmd, "audio-contract")) return @import("contract_nemo_audio.zig").run(gpu) else if (std.mem.eql(u8, cmd, "audio-check")) return @import("audio_check.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), rest.len > 3 and std.mem.eql(u8, rest[3], "layers")); if (std.mem.eql(u8, cmd, "window-profile")) return @import("window_profile.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "tree-accept")) return @import("tree_accept.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "chunk-costs")) return chunk_costs.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); From 0cdb775f1e24fe1aae5765496456a71a667a0b63 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:47:11 -0600 Subject: [PATCH 24/89] nemo_audio: the speaker cache applies min_pos_scores_rate and pred_score_threshold as the release does, with brief-speaker tests A speaker's frame score is log max(p, pred_score_threshold) plus the other speakers' log(1 - p); frames under 0.5 never score. A score above log 0.5 is positive, and a speaker with floor(share x min_pos_scores_rate) positive scores keeps only those (share = (188 - 8 x silence rows) / 8, rounded down: 22 shipped, so 11). The latest boost and the strong and weak boost counts follow, from the same share. When fewer than 188 frames can score, the rest of the cache is silence rows, after the scored rows. Fitted to black-box NeMo dumps at several values of both keys and of spkcache_sil_frames_per_spk; the tests use window 0 of a brief-speaker clip and of a clip with 37 s of silence, against the release's own caches. --- zig/src/families/nemo_audio/config.zig | 9 +- zig/src/families/nemo_audio/speaker.zig | 190 +++++++++++++++++- .../nemo_audio/testdata/brief_spk_1_w0.f32 | Bin 0 -> 5520 bytes .../families/nemo_audio/testdata/gap37_w0.f32 | Bin 0 -> 1840 bytes 4 files changed, 188 insertions(+), 11 deletions(-) create mode 100644 zig/src/families/nemo_audio/testdata/brief_spk_1_w0.f32 create mode 100644 zig/src/families/nemo_audio/testdata/gap37_w0.f32 diff --git a/zig/src/families/nemo_audio/config.zig b/zig/src/families/nemo_audio/config.zig index b4e7660d904..0de91e86312 100644 --- a/zig/src/families/nemo_audio/config.zig +++ b/zig/src/families/nemo_audio/config.zig @@ -27,7 +27,8 @@ pub const Config = struct { threshold: f32, // a slot is active past it (speaker_activity_threshold) kernel_scale: f32, // spk_kernel_scale boost_latest: f32, // the speaker cache's scores: frames new to it (scores_boost_latest) - score_floor: f32, // a slot's frame scores only from this probability (pred_score_threshold) + score_clamp: f32, // a slot's probability counts at least this much in its own frame scores (pred_score_threshold) + min_pos_rate: f32, // a slot with floor(this x its share of the cache) positive scores keeps only those (min_pos_scores_rate) strong_rate: f32, weak_rate: f32, sil_per_speaker: usize, // silence rows a slot keeps in the speaker cache (spkcache_sil_frames_per_spk) @@ -50,6 +51,8 @@ pub const Config = struct { /// The speaker branch's streaming state between windows (dumps): its cache and queue rows. pub const cache_rows = 188; pub const fifo_rows = 40; + /// A slot's frames under this probability never score in the speaker cache (arXiv 2507.18446, step 3). + pub const speech = 0.5; /// The audio a request may hold: the model card's one hour. pub const max_seconds = 3600; @@ -76,11 +79,13 @@ pub const Config = struct { .threshold = @floatCast(try float(pe.get("speaker_activity_threshold"))), .kernel_scale = @floatCast(try float(pe.get("spk_kernel_scale"))), .boost_latest = @floatCast(try float(mods.get("scores_boost_latest"))), - .score_floor = @floatCast(try float(mods.get("pred_score_threshold"))), + .score_clamp = @floatCast(try float(mods.get("pred_score_threshold"))), + .min_pos_rate = @floatCast(try float(mods.get("min_pos_scores_rate"))), .strong_rate = @floatCast(try float(mods.get("strong_boost_rate"))), .weak_rate = @floatCast(try float(mods.get("weak_boost_rate"))), .sil_per_speaker = try size(mods.get("spkcache_sil_frames_per_spk")), }; + if (!(c.min_pos_rate >= 0)) return error.BadConfig; if (c.speakers != 8 or c.head_width == 0 or c.output == 0 or c.speakers * (c.sil_per_speaker + 1) > cache_rows) return error.UnsupportedAudio; return c; } diff --git a/zig/src/families/nemo_audio/speaker.zig b/zig/src/families/nemo_audio/speaker.zig index 949cdee27cd..9c972fe0067 100644 --- a/zig/src/families/nemo_audio/speaker.zig +++ b/zig/src/families/nemo_audio/speaker.zig @@ -67,19 +67,32 @@ pub fn compress(a: Allocator, c: *const Config, preds: []const f64, n: usize, ne const col = n + sil; // a speaker's scores, its silence slots last const score = try a.alloc(f64, k * col); defer a.free(score); - // a frame's score for speaker s: log p_s + sum over the others of log(1 - p_j); none under the floor + // speaker s's frame score: log max(p_s, score_clamp) + the others' log(1 - p_j); none while p_s < 0.5 for (0..n) |t| { var rest: f64 = 0; for (0..k) |s| rest += @log(clip(1 - preds[t * k + s])); for (0..k) |s| { const ps = preds[t * k + s]; - var v = @log(clip(ps)) + (rest - @log(clip(1 - ps))); - if (ps < c.score_floor) v = -std.math.inf(f64) else if (t >= new_from) v += c.boost_latest; - score[s * col + t] = v; + score[s * col + t] = if (ps < Config.speech) -std.math.inf(f64) else @log(clip(@max(ps, c.score_clamp))) + (rest - @log(clip(1 - ps))); } } + // per: a speaker's whole share after the silence rows; floor(per x min_pos_rate) scores over log 0.5 drop the rest + const per: f64 = @floatFromInt((Config.cache_rows - k * sil) / k); + const need = @floor(per * @as(f64, c.min_pos_rate)); + const pos = @log(0.5); + for (0..k) |s| { + const v = score[s * col ..][0..n]; + var count: f64 = 0; + for (v) |x| count += @floatFromInt(@intFromBool(x > pos)); + if (count >= need) for (v) |*x| { + if (!(x.* > pos)) x.* = -std.math.inf(f64); + }; + } + // frames new to the cache: a small boost + for (0..k) |s| for (@min(new_from, n)..n) |t| { + score[s * col + t] += c.boost_latest; + }; // each speaker's best frames boosted twice, then a wider set once, so every speaker keeps some - const per: f64 = @as(f64, @floatFromInt(Config.cache_rows - k * sil)) / @as(f64, @floatFromInt(k)); const order = try a.alloc(usize, n); defer a.free(order); const half = -@log(0.5); @@ -101,11 +114,15 @@ pub fn compress(a: Allocator, c: *const Config, preds: []const f64, n: usize, ne rank(flat, score); const keep = flat[0..Config.cache_rows]; std.mem.sortUnstable(usize, keep, {}, std.sort.asc(usize)); + // in index order, then the picks that could not score (fewer than the cache's rows did): silence rows at the end const out = try a.alloc(?usize, keep.len); - for (keep, out) |i, *o| { - const s = i / col; + @memset(out, null); + var o: usize = 0; + for (keep) |i| { const t = i % col; - o.* = if (t < n and std.math.isFinite(score[s * col + t])) t else null; + if (score[i] == -std.math.inf(f64)) continue; + out[o] = if (t < n and std.math.isFinite(score[i])) t else null; + o += 1; } return out; } @@ -128,7 +145,7 @@ fn rank(order: []usize, v: []const f64) void { fn testConfig() Config { const stack: @import("config.zig").Stack = .{ .width = 512, .heads = 8, .layers = 1, .ffn = 1, .rot = 64, .qk_norm = false, .base = 10000 }; - return .{ .asr = stack, .spk = stack, .speakers = 8, .head_width = 192, .output = 1, .threshold = 0.5, .kernel_scale = 1, .boost_latest = 0.05, .score_floor = 0.25, .strong_rate = 0.75, .weak_rate = 1.5, .sil_per_speaker = 1 }; + return .{ .asr = stack, .spk = stack, .speakers = 8, .head_width = 192, .output = 1, .threshold = 0.5, .kernel_scale = 1, .boost_latest = 0.05, .score_clamp = 0.25, .min_pos_rate = 0.5, .strong_rate = 0.75, .weak_rate = 1.5, .sil_per_speaker = 1 }; } test "nemo audio speaker state: the first window fills the queue, its overflow joins the cache" { @@ -179,3 +196,158 @@ test "nemo audio speaker cache: one active speaker keeps its best frames, silenc try std.testing.expectEqual(@as(usize, 180), frames); try std.testing.expect(out[180] == null); } + +/// brief_spk_1's first window (fp32), 460 rows: f32 [460][3], p of A, B, and 1 - prod(1 - p) of speakers 2-7 (< 0.02) +const brief = @embedFile("testdata/brief_spk_1_w0.f32"); + +fn briefCache(rate: f32, clamp: f32) !Next { + return briefCacheSil(rate, clamp, 1); +} + +fn briefCacheSil(rate: f32, clamp: f32, sil: usize) !Next { + const a = std.testing.allocator; + var c = testConfig(); + c.sil_per_speaker = sil; + c.min_pos_rate = rate; + c.score_clamp = clamp; + var p: [500 * 8]f32 = @splat(0); + for (0..460) |t| for (0..3) |s| { + p[t * 8 + s] = @bitCast(std.mem.readInt(u32, brief[(t * 3 + s) * 4 ..][0..4], .little)); + }; + var st: State = .{}; + return update(a, &c, &st, &p, 0, 500); +} + +/// The cache: speaker A's rows, its silence row, speaker B's rows, then the other six speakers' silence rows. +fn expectCache(next: Next, a_rows: []const [2]u32, b_rows: []const [2]u32) !void { + return expectCacheSil(next, a_rows, b_rows, 1); +} + +/// The same with `sil` silence rows a speaker. +fn expectCacheSil(next: Next, a_rows: []const [2]u32, b_rows: []const [2]u32, sil: usize) !void { + var want: [Config.cache_rows]Pick = @splat(.sil); + var i: usize = 0; + for (a_rows) |r| for (r[0]..r[1]) |t| { + want[i] = .{ .row = @intCast(t) }; + i += 1; + }; + i += sil; + for (b_rows) |r| for (r[0]..r[1]) |t| { + want[i] = .{ .row = @intCast(t) }; + i += 1; + }; + try std.testing.expectEqual(@as(usize, Config.cache_rows), next.cache_len); + for (want, next.cache[0..next.cache_len]) |w, x| try std.testing.expectEqual(w, x); +} + +const brief_a = [_][2]u32{ .{ 188, 211 }, .{ 213, 224 }, .{ 225, 228 }, .{ 241, 243 }, .{ 245, 247 }, .{ 290, 292 }, .{ 296, 298 }, .{ 299, 309 }, .{ 317, 327 }, .{ 333, 355 }, .{ 366, 375 }, .{ 385, 417 }, .{ 424, 460 } }; + +test "nemo audio speaker cache: a brief speaker with few positive scores keeps its 16 boosted rows (rate 0.5 and 1.0)" { + const b = [_][2]u32{ .{ 260, 270 }, .{ 271, 277 } }; + try expectCache(try briefCache(0.5, 0.25), &brief_a, &b); + try expectCache(try briefCache(1.0, 0.25), &brief_a, &b); +} + +test "nemo audio speaker cache: rate 0 keeps only a brief speaker's positive scores, A's rows take the rest" { + const a = [_][2]u32{ .{ 188, 230 }, .{ 233, 235 }, .{ 240, 247 }, .{ 290, 292 }, .{ 296, 309 }, .{ 317, 327 }, .{ 333, 355 }, .{ 366, 375 }, .{ 384, 417 }, .{ 424, 460 } }; + const b = [_][2]u32{ .{ 260, 261 }, .{ 267, 268 }, .{ 275, 277 } }; + try expectCache(try briefCache(0.0, 0.25), &a, &b); +} + +test "nemo audio speaker cache: frames under p = 0.5 never score" { + const a = std.testing.allocator; + const c = testConfig(); + const n = 300; + var preds: [n * 8]f64 = @splat(1e-6); + for (0..n) |t| preds[t * 8] = 0.99; + // speaker 1 at 0.3-0.49 on 40 frames where speaker 0 drops to 0.2: boosted, they would beat speaker 0's frames + for (100..140) |t| { + preds[t * 8] = 0.2; + preds[t * 8 + 1] = 0.3 + 0.19 * @as(f64, @floatFromInt(t - 100)) / 40.0; + } + const out = try compress(a, &c, &preds, n, 188); + defer a.free(out); + // speaker 0's 180 frames, then eight silence rows + for (out[0..180]) |x| try std.testing.expect(x != null and (x.? < 100 or x.? >= 140)); + for (out[180..]) |x| try std.testing.expect(x == null); +} + +test "nemo audio speaker cache: a clamp of 0.6 ranks a brief speaker's frames under 0.6 by the other speakers alone" { + // NeMo's cache for this window with pred_score_threshold 0.6: B's row 273 (p 0.598, A 0.176) gives way to 270 + const b = [_][2]u32{ .{ 260, 273 }, .{ 274, 277 } }; + try expectCache(try briefCache(0.5, 0.6), &brief_a, &b); +} + +test "nemo audio speaker cache: the rule needs floor(22 x min_pos_rate) positive scores" { + const a = std.testing.allocator; + var c = testConfig(); + const n = 400; + var preds: [n * 8]f64 = @splat(1e-6); + for (0..n) |t| preds[t * 8] = 0.99; + // speaker 1: 11 positive frames (0.62 against 0.1) and 5 more just over 0.5 + for (100..116) |t| { + preds[t * 8] = 0.1; + preds[t * 8 + 1] = if (t < 111) 0.62 else 0.52; + } + for ([_]f32{ 0.54, 0.55 }, [_]usize{ 11, 16 }) |rate, want| { + c.min_pos_rate = rate; + const out = try compress(a, &c, &preds, n, 188); + defer a.free(out); + var kept: usize = 0; + for (out) |x| kept += @intFromBool(x != null and x.? >= 100 and x.? < 116); + try std.testing.expectEqual(want, kept); + } +} + +/// gap37 (brief_spk_1's first 8 s, 37 s of zeros, the rest), window 0 (fp32): f32 [460], A's p (others < 0.001) +const gap = @embedFile("testdata/gap37_w0.f32"); + +test "nemo audio speaker cache: with only 92 frames over p = 0.5, the rest of the cache is silence rows at its end" { + const a = std.testing.allocator; + var c = testConfig(); + var p: [500 * 8]f32 = @splat(0); + for (0..460) |t| p[t * 8] = @bitCast(std.mem.readInt(u32, gap[t * 4 ..][0..4], .little)); + // NeMo's cache after this window, with pred_score_threshold 0.25 and 0.1 alike + for ([_]f32{ 0.25, 0.1 }) |clamp| { + c.score_clamp = clamp; + var st: State = .{}; + const next = try update(a, &c, &st, &p, 0, 500); + try std.testing.expectEqual(@as(usize, Config.cache_rows), next.cache_len); + var i: usize = 0; + for ([_][2]u32{ .{ 6, 30 }, .{ 32, 100 } }) |r| for (r[0]..r[1]) |t| { + try std.testing.expectEqual(Pick{ .row = @intCast(t) }, next.cache[i]); + i += 1; + }; + for (next.cache[i..next.cache_len]) |x| try std.testing.expectEqual(Pick.sil, x); + } +} + +test "nemo audio speaker cache: two silence rows a speaker share floor((188 - 16) / 8) = 21 rows each" { + const a = std.testing.allocator; + var c = testConfig(); + c.sil_per_speaker = 2; + const n = 400; + var preds: [n * 8]f64 = @splat(1e-6); + for (0..n) |t| preds[t * 8] = 0.99; + // speaker 1: 11 positive frames and 5 more just over 0.5; floor(21 x 0.565) = 11 fires, 21.5 or 22 would need 12 + for (100..116) |t| { + preds[t * 8] = 0.1; + preds[t * 8 + 1] = if (t < 111) 0.62 else 0.52; + } + c.min_pos_rate = 0.565; + const out = try compress(a, &c, &preds, n, 188); + defer a.free(out); + // A's frames, its two silence rows (161-162), B's 11, then 14 silence rows (174-187), as in NeMo's sil-2 cache + const a_rows = Config.cache_rows - 2 - 11 - 14; + for (out[0..a_rows]) |x| try std.testing.expect(x != null and (x.? < 100 or x.? >= 116)); + for (out[a_rows..][0..2]) |x| try std.testing.expect(x == null); + for (out[a_rows + 2 ..][0..11], 100..111) |x, t| try std.testing.expectEqual(@as(?usize, t), x); + for (out[a_rows + 13 ..]) |x| try std.testing.expect(x == null); +} + +test "nemo audio speaker cache: with two silence rows, a brief speaker's boosts count from the share 21 (15 rows, not 16)" { + // NeMo's fp32 sil-2 cache, window 0: B's 4 positives don't fire the rule, so it keeps floor(21 x 0.75) = 15 rows + const a = [_][2]u32{ .{ 188, 211 }, .{ 214, 218 }, .{ 220, 224 }, .{ 226, 228 }, .{ 242, 243 }, .{ 245, 247 }, .{ 290, 291 }, .{ 296, 298 }, .{ 299, 308 }, .{ 317, 327 }, .{ 333, 355 }, .{ 366, 375 }, .{ 385, 417 }, .{ 424, 460 } }; + const b = [_][2]u32{ .{ 260, 270 }, .{ 272, 277 } }; + try expectCacheSil(try briefCacheSil(0.5, 0.25, 2), &a, &b, 2); +} diff --git a/zig/src/families/nemo_audio/testdata/brief_spk_1_w0.f32 b/zig/src/families/nemo_audio/testdata/brief_spk_1_w0.f32 new file mode 100644 index 0000000000000000000000000000000000000000..5e19f4841a4217fb6e2a5bfbf9f44201bb102550 GIT binary patch literal 5520 zcmXAtd0bD;7sr!qAt_PXZ7sCinKSqME#JQPd2A)g5~(aDdlW@>?MX^Wi+TzPNvo2| z5>Y%PA%se0OC>x)c7Ai`_uu<qsH%N)c{F^MMUT1{*kjt`cs@M$J$ht1?gjyoj6$ucr$d4XJclA9!GR~`wnTr5Z_M^Fc4&b=>DaM^+$QZ7^N05^v?be(d~ zo!?Moe*@K19@L;r3_~)|OUlCA>u`3qD|$`&p;0gtZ`Wh?iG7lxd$T8Mp!S=8KY++X z+t4%0feRJLkBNKGeaarbgNQu87Tu$a`gFt1_8RnGy7_9yF1$o*&~TqfEV zMG<9ddt60%^VieF`od;>m$G%-72>iw0zaU<)+dvwb%f$}%1w(r$=fzH{D$&AXCOno z?;*G5K;eGr8-A3>7-HK#T8J*#DxI+D8}II3EO)S9B@K?d%lmvgFSn=}DfKR`=39N2 z3eii>N`@(V^L>8@3MYQe;U7^KT2ua!WJZM0r+wBj_8yLboY@8CedoCS`1o zrkZzPdcsx4k01j!>n5W*I%dbP2pIo35>-;3&)I{k-EQ=P^1=}VA-)iyN0fgTdqJ~O z020@VA0H3BG|P~ z2t`v)v&x3w?H^Hz$U5iY{(5aJ`dJp|0#~zRkQhsTvD4urzl7bpwT2J0NLHge)c$Ik zE!=kTLE?SsO_&Z%&f$z-Jy{5b-UrxSn;Z^<=noYveiSU-q0Ty-&8hiqBAC4}XX9(` zE&-+5V0YbK4a)Q%(*)0%|B6b}v$X?_qE<4VKjB2?{4 zMo%b@Zb^aP!vr=yt715*$g4xMsC|W!3OQn`jIUDmcJKk;pF!v*WuH$Guvl{?^X;V5 z0;o&;#fkBM77YcrchXL!XA?U3xs-Zk;O)Oab+KVnyE)3ZZW1Nqo3d-79iSXUy z4D;dCl6_FFx03DUNBUuycFml{zeCjlKsnlM@4qb^A-6yswb5_SyhflDGM3qWylp}C zyEzi$+`F|4FIBJM#5kWF`2+{|&Ei@pfBI)AB&Slpjb2!Ce)1w#SGI{or^7X89h_;tu~jbz;65`>uoU-^MY0XfCvde%DP{ zjE#+H0>94v$cE0-!}TVr&!%88W;}v(LFraLGNT-&o&mnK6)eVtRt*@IrqBFIDeMg% zX`LEZP|D2DQ}Rw*nTu@Dte z?!GnzhQ`a7|FP&KZf!oxiMlk(+z&UVg>&yHfABEGd!p^Qr<9vJSKwsdWOk3^HD}?9 zfm^v&ah_KP@WxA_+#$+4gP-G`za}&7GBb|A2dwhh*`^NOgv%XL!wrrK=mW9`TIMt~ZuUwMIh{3B3UU^I<)nqvdH&0pk7 zYxSj2e2~AnxykDBmk<)#dlWQA?v_5jQ-#BWi_xSX4U)@2=g`zKm$;nI8j>j+rlS5A zwYjox3;y}TSDeGsla}>=FXHQdyyTWjPg};dbX!dk60v`1F=~G;7aWeINRH{b@EfU) zsoqlOz3QYMw*Q|9+6YSjz;6}AAv-7jh!q4G5SZ-qX8c;Df zicZmQ@5QN;Q3WGe?a(PyBm={5vN$i;To1ck@|c#+y!Qm&#?~@>eCBN^Jad8NlzD7_ zayqCltD#%#29o!4Ot9v+K*3m5iO(Go1P9ue3x&6SOWLRJ<%2?>$k%AcOTR7jl(
6TO zrSZFj-K*;*X7}y+WpuxneL21@_c|`7Y%qc&s-4%EMm>yu1d=^zNUXEI~;!eC9;`nO`{wT<%tL-IOa=R${^K5ci(4RkIp6 z|9Q^x%eco1Mr!FIG2R0F-QeraD5fDNHrhe?5kr<=^Zc z;jYGcmdjP0o^V)cAbLgTd7~EqOQveDxV7DI9o7bOY|iZ-Z=gQglxb$(+(_u^-^22K zcuyY0{565;&r;)ogzMPL>T+b>M>u^ohH0IA(0|}>mdk4EwJ=?x)%pO5wcu;A7BLAa zW;L-U!kF|myNM1{yR9sefaw5sp5M(A$f6gDSk$pjlNls`TnjtT2G=#@lb;4Ip!TSp z9^};5;kb};(0eHf%+$lKlz;CmAQN*>;8m1w=N6E)(>-wj<&e@4@=d=Fj-i}%+L^o| zAJ~08PQDNCw&bz*K&xvFcyBFX{+!(;B?mo6;1D`~|JfuGRcDEVDEITRgU8Dc7v;PqgFWP&Vbab4X?L-o#eRJ)+%#&w zMUeX$vzbjwxZq=vMY=~H^LZshB)v~*;(4``x%U%J@$+WXp)?f@ZiiPY;?pB7g9iGU z8xJu;oc{^Sio_7}=a##0*^3U;v|*cN$idapgJV3cd*&~aMEp5q)4RJu4zIpW+%wZs z{%Wkgux7?KS;?$1af49Covp`euTNNxj^mMrV(ibgZlgA#JSEa7}Mv9i8kQpqq zP&Sbt2p=K1C2W?3DqF}?uWASmL0+=Do8#qE-f9Sy)yrk!p5}6mr6YuHjF*G8}CwfyoK zMcITsGOJ!oZdzN()TF7-;rx~@btJgG0>?LG^ZhQnVkOrjT%VeDe(Lg7_{2F)q@XoH z`u2(%q-r-J&3;C*7hk$~JG;HaSYffE_kEB7gekQD;f`LCkK+>;ZJY^Haq zoIyEZ*)uSyorLF64!NjI9`%pF$0%Feu7Hfq>g-**X~lVH4?4#3ZkN|Z$Z=^zrF6{d z!t>Cf_!)`X5>}lD0~24MbjnxPe}Z*0JJ{RlX1k1>NFC4gWOeW+a(>$ke2|W**!Ym# zP`QBPDLWk=%U3_Og8m-^1@$^D$+F@oa_zKS$RB-3dbigUNl$Fr#H3y~c%#j`$yRJ@ zb#OTkXJU6^x7ejp#aZ^agJhzQi?gH;M#bPb^$7G%YrlM<;Y^8tbS9tM5GaIxt>Vk) zN0BFVErV}E$f&EztcIqPkA}L42}pdKT{3=)*N`EsUi+^GP;?AM;`!WNHVqaTq$4pm z)1AU#K}7?r@69v(U`SLe)8{_PLGY@sis^P}Tm_8ino``?7qQN+LC zHP*VeQUJ&GlGetz#I05;jNTY8v8?GKsq<`v7i(8YjNbevrmMCJ55G^9#HDl)FZyPK zt#3%IiZh6P@fW`+@Y73W?;L}@N?|HTkI@4951W)>>wQRUjd8t}E+hMdEcREt^Dw0ZY1 zOHOs!0Sja6Fn(9mUM}cHmBofhH~IC?>$v~)RV{~~zQZej{Kfg&hgl}`7o<8(QFu|L zI=ZtaP~McPFLC!7!%r@xz2u9pyypEQM9h(w!5-xGuOQa@zw-+LwaT^Z4P!h#AKJ6! z?9F!gX9}DvG-WZizr+phsGaupH`*XCz?B zwILtSj%|5dVTS_GO)%!B=>D-dv_DfCdQ89%GCH`elfT$Vz0-IvA%N7sTqz_qC`#I@ zl89JC`)02qd;6zh@r`Y&5DKT74N)g$g%#sq!_R*?@hznO8^H!wUAC{dkf~6Tx0UVd zP}xAJzNf=tqtj;+%o;e8y?H))M#C$clPnHjs?UO>lL8rQhdIL^lSp)$&Z)Dn1*Yx) zg;FRtu23cQYu_PJuYUb|1$)!#-LR5z?= z`|;av*+CZ`F8G9$O018M=hy8xJFyNO<;~x@6F(mv**}vdk{|hMyxO5KSy#zqNtbF9 z*}cipro>>Z#3?+G=p1wvekl)=SS<)6Vbss?sRCKnJPC`r93^*z+o`=-58FTC4esPh zIk6XBom+ujQtxo0X4(~;#>vJ%Ss&V`s0=^k`m;Rk9A^%ye;Fb1zsGkW9vmiRpmUTz z`mBK4T8Zrc($NKvaQaCzB=%y-=T2c5TF2%;_~9NtXEK6m%g~j*;off>7V~CF?y#Lt zW%K;nJ_CY^quG1=uVbBfkcS!5ion{txUEu`@xAOzIO3>`#b?yWE7(M0$o^3bHSNYt z&sACM*=#q3!z+@Rc3E5A#n%hhAhBO)c07P(+0VG=l+_Xy;l7hG%h~lSd3Z1)h}D90 zw?sHuQqAtY?ehotaZv;3)A6J34J1)xKCrlY9{C=o>t(RLd>Zf(j!6!%Z*A@yl08LN ym?oE1RlwrJ9jJ?bd#Gg%EWFj9`TR>FfXAFRPPA9PQ-hr26^wK|V%~S1F@nIRWb{zv4MN zR!3Q8_ax5^Gw!qg3zj>^G7p%}V)YEm{B(lnR8kzcPc7dGH+?iNRITyi>|XHP!(pCF zpWwOkjBbYE7|*GX^4!L8o^xedpY?MXiOfqL;kkh!p1Z@UDeL94OcK*t?0cGOjS(*&Xk(ej4+K8Qa;+Q8qil{3146#rAMu{txWzz;Y&oJol}F z=T5L%%)C9Ur(o5TWhWVVY~L^0x0+e@|DHP2N{rta5$vu)=51zLlab8MR_rah8CmRI z)Sj{3>)2lBcrJYNaW2WH-ah2M<7ZQeoS@359TU6^yB@B_#+}8qD^f~rs=a8Qk}LJS zv4bXBI8et%Yr5~E6a8>WOgr@aXr5XGP5LC3TDis1@7Ks^SVaLnZCXp0>G#mZW6D^P zXyb95ImB&l$W3uUSF1Df*GVAyYB%i~Na4kKIqbqE&bwC7@5`S1Y z2Ey!|Kb~p&;KIUw-25gGP9L8@Nyr(jI(`bx{bAT3-H+U_Lr_#B!^(xL@D!DydR`8j z@kVrfbOT>(et`SNqi|V03ZsJqP<+>baq%S-e0~L|6lGZZWhI2`OVJc`5p{)$c-NJV zLiTDML6E- zghFl56K;|%5M8%Kz-wz94Yon2uN8!a%y9z5c&>+ex&h)tHBc9AfPdfo7^03fxEcBn{5Y?T zhf*aZdTT;{*AOy^25i6mn?6Y#p)WgcQNzMLm`>?Mo!}T z+Q`|k29n=bPC~3J$-JVC`2XuZ5z9Nt&waN@UR@0diK-z(l4cSyaGP|O_K~8NesbEs zmE7p8A^lz@B(1lU=thi_^ z4;pjGw(1HJpHxNo%3|`y_agaY<3(bgQA7$hTqnmK)RBm;M)LlA1&K7gN-n!!Be7=9 zMB09jT($2adDVAF{iVC)ka&PhG^)@)HMD3?v=;61d7r+^GNc!Db?DhsI#i*oPuI8` z(H?(YS{|!HpZ&c+c15VsrZQtHPTWE#k{u}Nai*ST9(4A4AnpIFSUF>T#f~UG6h6;7C<kUV8-CvIf`DRY$UR(fBzz|x zr|*IExi^~HypfUPg}0su;jt?Whn7X-ZCVu0NkUQZS2%=%1eiC=5FMQgW7T+g$O90p zaD?!=4TgK2&{TN_i3x&9n*_!=-gqNEgcNBMN@{sT#V6x Date: Tue, 17 Nov 2026 09:59:03 +0000 Subject: [PATCH 25/89] nemotron cuda: null audio and bf16x in main's hand-built subset-batch engines The two hand-built engines in cuda_subset_batch_test.zig start from undefined; they now null the Transcribe fields as cuda_load_gpu.zig's do, so no test reads or unloads a garbage pointer. --- zig/src/families/nemotron/cuda_subset_batch_test.zig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/zig/src/families/nemotron/cuda_subset_batch_test.zig b/zig/src/families/nemotron/cuda_subset_batch_test.zig index 927e0fe336c..54e5dbc1360 100644 --- a/zig/src/families/nemotron/cuda_subset_batch_test.zig +++ b/zig/src/families/nemotron/cuda_subset_batch_test.zig @@ -258,6 +258,7 @@ test "restored head: 15 and 16 token transitions reach mixed shrinking real chai e.k.d = &d; e.k.ck = null; e.k.ggml = null; + e.k.bf16x = null; const f: cuda.Function = .{ .d = &d, .handle = @ptrFromInt(1) }; const lane: cuda.qmmf.Lane = .{ .mod = undefined, .fns = @splat(@splat(f)), .f32_fns = @splat(@splat(f)), .reduce = @splat(f), .half = @splat(@splat(@splat(f))), .half_below = 0, .clusters = false }; e.k.modelopt = .{ .lane = lane, .gemm = undefined, .experts = undefined, .pack = undefined }; @@ -427,6 +428,7 @@ test "batched draws: eight parts take 15 or fewer greedy draw-side launches a le e.side = undefined; e.tp = null; e.vision = null; + e.audio = null; e.slot = 0; var bufs: @import("cuda_state.zig").Buffers = undefined; bufs.lane_part = 0; @@ -436,6 +438,7 @@ test "batched draws: eight parts take 15 or fewer greedy draw-side launches a le e.k.triton = null; e.k.ck = null; e.k.ggml = null; + e.k.bf16x = null; const f10: cuda.Function = .{ .d = &d, .handle = @ptrFromInt(10) }; const f1: cuda.Function = .{ .d = &d, .handle = @ptrFromInt(1) }; const lane: cuda.qmmf.Lane = .{ .mod = undefined, .fns = @splat(@splat(f1)), .f32_fns = @splat(@splat(f1)), .reduce = @splat(f1), .half = @splat(@splat(@splat(f1))), .half_below = 0, .clusters = false }; From 94ece19779d442f835e3286e3053d18dbaf82baa Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:59:03 +0000 Subject: [PATCH 26/89] nemotron cuda, tests/cuda: room under 600 lines after the rebase onto main Engine.record and its body move to cuda_seq_graphs.zig, Forward's lesson adapter call to cuda_lesson_trace.zig, and tf-cuda-test imports chunk_costs and nemotron_draw_tests where they run, as window-profile and tree-accept do. No behaviour changes. --- zig/src/families/nemotron/cuda_engine.zig | 33 +---------------- zig/src/families/nemotron/cuda_forward.zig | 12 +----- .../families/nemotron/cuda_lesson_trace.zig | 14 ++++++- zig/src/families/nemotron/cuda_seq_graphs.zig | 37 ++++++++++++++++++- zig/tests/cuda/main.zig | 6 +-- 5 files changed, 53 insertions(+), 49 deletions(-) diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index dbe981aa1d7..3aa6c32a334 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -261,38 +261,7 @@ pub const Engine = struct { head: struct { h: *Head, rows: usize, j: usize, vocab: @import("cuda_mtp.zig").Vocab }, }; - /// One graph of `body` on the bound sequence's buffers, instantiated and uploaded. - pub fn record(e: *Engine, body: Body) !cuda.graph.Exec { - const t0 = std.Io.Clock.awake.now(e.io); - try cuda.graph.beginCapture(e.stream, .thread_local); - e.recordBody(body) catch |err| { - if (cuda.graph.endCapture(e.stream)) |g| { - var x = g; - x.deinit(); - } else |_| {} - return err; - }; - var g = try cuda.graph.endCapture(e.stream); - defer g.deinit(); - const exec = try g.instantiate(); - try exec.upload(e.stream); - try e.stream.synchronize(); - e.stats.captures += 1; - e.stats.capture_ns += @intCast(std.Io.Clock.awake.now(e.io).toNanoseconds() - t0.toNanoseconds()); - return exec; - } - - fn recordBody(e: *Engine, body: Body) !void { - switch (body) { - .window => |w| { - const f = e.forward(null); - try f.windowSegs(&.{.{ .b = f.b, .row0 = 0, .rows = w.rows, .sampled = f.sampled, .mask = w.mask, .slot = f.slot, .untaught = f.untaught }}); - if (w.feed) return e.ops().serialFeed(e.b.sampled, e.b.ids, e.b.meta, e.history_dev); - try e.ops().download(std.mem.sliceAsBytes(e.pinned.slice(u32)[pin_sampled..][0..w.rows]), e.b.sampled); - }, - .head => |x| try x.h.level(x.rows, x.j, x.vocab), - } - } + pub const record = seq_graphs.record; /// Step `id`: the own sequence launches `own`; another launches its own capture of `body`, made the first time. pub fn launchGraph(e: *Engine, own: cuda.graph.Exec, id: u32, body: Body) !void { diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index 999402a0c1b..926dfee8e7f 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -8,12 +8,12 @@ const glue = @import("cuda_glue.zig"); const weights = @import("cuda_weights.zig"); const state = @import("cuda_state.zig"); const Dump = @import("cuda_dump.zig").Dump; -const train_ops = @import("cuda_train_ops.zig"); const lesson_route = @import("living").lesson_route; const kept = @import("cuda_marks.zig"); const latent = @import("cuda_latent.zig"); const worker = @import("cuda_worker.zig"); const window_marks = @import("cuda_window_marks.zig"); +const adapt = @import("cuda_lesson_trace.zig").adapt; pub const Delta = enum { none, dense, moe }; @@ -587,13 +587,3 @@ pub const Forward = struct { if (f.dump) |d| try d.tail(f.ops, b.p_logits, b.p_sampled, 1, c.vocab); } }; - -/// y += scale (x a^T) b over the blocks `route` opens on each row (x and y rows their strides apart, y bf16 or fp32). -fn adapt(o: kern.Ops, ad: weights.Adapter, x: u64, x_stride: usize, y: u64, y_stride: usize, y_f32: bool, rows: usize, route: *const lesson_route.Route) !void { - const t: train_ops.Ops = .{ .k = &o.k.train, .s = o.s }; - try t.loraIn(x, x_stride, ad.a, ad.xa, rows, ad.in, ad.rank, ad.xn); - var r = route.*; - if (ad.whole) r.whole = 1; - try t.gate(ad.xa, ad.xn, ad.tau, ad.gates, rows, ad.rank, ad.unit, &r, ad.latch, ad.score); - try t.loraOut(ad.xa, ad.b, y, y_stride, y_f32, rows, ad.out, ad.rank, ad.scale); -} diff --git a/zig/src/families/nemotron/cuda_lesson_trace.zig b/zig/src/families/nemotron/cuda_lesson_trace.zig index 0505e89d3fe..cdd783eb4cf 100644 --- a/zig/src/families/nemotron/cuda_lesson_trace.zig +++ b/zig/src/families/nemotron/cuda_lesson_trace.zig @@ -1,7 +1,9 @@ -//! Read the bound CUDA sequence's lesson buffers and optional developer trace. +//! Read the bound CUDA sequence's lesson buffers and optional developer trace, and apply a lesson's adapter. const std = @import("std"); const Engine = @import("cuda_engine.zig").Engine; const weights = @import("cuda_weights.zig"); +const kern = @import("cuda_kernels.zig"); +const train_ops = @import("cuda_train_ops.zig"); const lesson_route = @import("living").lesson_route; /// Any block's change, for the buffers every block shares (null: no lesson is attached). @@ -32,3 +34,13 @@ pub fn traceLessons(e: *const Engine) void { for (0..ad.rank / 16) |b| w.print(" {d:.2}/{d:.2}{s}", .{ score[b], need[b], if (flags[b] != 0) "*" else "" }) catch break; std.log.info("slide trace: decision row {d}: scores{s} (* acting)", .{ e.decide, w.buffered() }); } + +/// y += scale (x a^T) b over the blocks `route` opens on each row (x and y rows their strides apart, y bf16 or fp32). +pub fn adapt(o: kern.Ops, ad: weights.Adapter, x: u64, x_stride: usize, y: u64, y_stride: usize, y_f32: bool, rows: usize, route: *const lesson_route.Route) !void { + const t: train_ops.Ops = .{ .k = &o.k.train, .s = o.s }; + try t.loraIn(x, x_stride, ad.a, ad.xa, rows, ad.in, ad.rank, ad.xn); + var r = route.*; + if (ad.whole) r.whole = 1; + try t.gate(ad.xa, ad.xn, ad.tau, ad.gates, rows, ad.rank, ad.unit, &r, ad.latch, ad.score); + try t.loraOut(ad.xa, ad.b, y, y_stride, y_f32, rows, ad.out, ad.rank, ad.scale); +} diff --git a/zig/src/families/nemotron/cuda_seq_graphs.zig b/zig/src/families/nemotron/cuda_seq_graphs.zig index 09fb6965a41..6486a6fc1b4 100644 --- a/zig/src/families/nemotron/cuda_seq_graphs.zig +++ b/zig/src/families/nemotron/cuda_seq_graphs.zig @@ -1,8 +1,10 @@ -//! Graphs a sequence other than the engine's own captures on its own buffers, once each, and replays after. +//! A body's graph capture, and a sequence's own graphs (not the engine's captures) on its buffers, replayed after. const std = @import("std"); const platform = @import("sys"); const cuda = @import("cuda"); +const engine = @import("cuda_engine.zig"); +const Engine = engine.Engine; /// One sequence's captured graphs, by the step they run (a window's or a head level's id). pub const Graphs = std.AutoHashMapUnmanaged(u32, cuda.graph.Exec); @@ -31,3 +33,36 @@ pub fn logFromEnv() bool { const v = platform.c.getenv("TF_GRAPH_LOG") orelse return false; return std.mem.eql(u8, std.mem.span(v), "1"); } + +/// One graph of `body` on the bound sequence's buffers, instantiated and uploaded. +pub fn record(e: *Engine, body: Engine.Body) !cuda.graph.Exec { + const t0 = std.Io.Clock.awake.now(e.io); + try cuda.graph.beginCapture(e.stream, .thread_local); + recordBody(e, body) catch |err| { + if (cuda.graph.endCapture(e.stream)) |g| { + var x = g; + x.deinit(); + } else |_| {} + return err; + }; + var g = try cuda.graph.endCapture(e.stream); + defer g.deinit(); + const exec = try g.instantiate(); + try exec.upload(e.stream); + try e.stream.synchronize(); + e.stats.captures += 1; + e.stats.capture_ns += @intCast(std.Io.Clock.awake.now(e.io).toNanoseconds() - t0.toNanoseconds()); + return exec; +} + +fn recordBody(e: *Engine, body: Engine.Body) !void { + switch (body) { + .window => |w| { + const f = e.forward(null); + try f.windowSegs(&.{.{ .b = f.b, .row0 = 0, .rows = w.rows, .sampled = f.sampled, .mask = w.mask, .slot = f.slot, .untaught = f.untaught }}); + if (w.feed) return e.ops().serialFeed(e.b.sampled, e.b.ids, e.b.meta, e.history_dev); + try e.ops().download(std.mem.sliceAsBytes(e.pinned.slice(u32)[engine.pin_sampled..][0..w.rows]), e.b.sampled); + }, + .head => |x| try x.h.level(x.rows, x.j, x.vocab), + } +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 094c544f97a..2fa18ca0de0 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -13,12 +13,10 @@ const libs_tests = @import("libs_tests.zig"); const rank_scatter_tests = @import("rank_scatter_tests.zig"); const roce_gather_tests = @import("roce_gather_tests.zig"); const sample_tests = @import("sample_tests.zig"); -const nemotron_draw_tests = @import("nemotron_draw_tests.zig"); const glue_tests = @import("glue_tests.zig"); const resume_tests = @import("resume_tests.zig"); const prompt_cuts = @import("prompt_cuts.zig"); const shared_fork = @import("shared_fork.zig"); -const chunk_costs = @import("chunk_costs.zig"); const grouped_tests = @import("grouped_tests.zig"); const fp8_tests = @import("fp8_tests.zig"); const mxfp8_tests = @import("mxfp8_tests.zig"); @@ -466,7 +464,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "exl3-contract")) return @import("contract_exl3.zig").run(gpu); if (std.mem.eql(u8, cmd, "exl3-tp2")) return exl3_tp2_tests.run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else "none"); if (std.mem.eql(u8, cmd, "sample")) return sample_tests.draws(gpu); - if (std.mem.eql(u8, cmd, "nemotron-draws")) return nemotron_draw_tests.run(gpu); + if (std.mem.eql(u8, cmd, "nemotron-draws")) return @import("nemotron_draw_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "topk")) return sample_tests.topk(gpu); if (std.mem.eql(u8, cmd, "q35-argmax")) return sample_tests.q35Argmax(gpu); if (std.mem.eql(u8, cmd, "norms")) return norms_tests.run(gpu); @@ -506,7 +504,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "audio-contract")) return @import("contract_nemo_audio.zig").run(gpu) else if (std.mem.eql(u8, cmd, "audio-check")) return @import("audio_check.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), rest.len > 3 and std.mem.eql(u8, rest[3], "layers")); if (std.mem.eql(u8, cmd, "window-profile")) return @import("window_profile.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "tree-accept")) return @import("tree_accept.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); - if (std.mem.eql(u8, cmd, "chunk-costs")) return chunk_costs.run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "chunk-costs")) return @import("chunk_costs.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "resume")) return resume_tests.run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "marks")) return resume_tests.insideChunks(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "prompt-cuts")) return prompt_cuts.run(gpu, try arg(rest, 0), try arg(rest, 1)); From 7d93d49f3cc4bf44e961c2b620a1594a56480ff2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:59:29 +0000 Subject: [PATCH 27/89] CHANGELOG, gradient-serving: Nemotron 3.5 Transcribe on CUDA (#1631); re-pin kernels.zig for the nemo_audio image --- zig/tests/fixtures/gradient-serving.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ef0b99b3c27..87228dc7dae 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 4d70aa12e092f9837249978cef148b6e20d76b651181eddeb9a4ef5401cf3dfc raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check) +zig/src/cuda/kernels.zig 6e19f32d3549d949cefda734e1540afd9a50779a8d8cefa796afd6fe8e9aea9d raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig 7d2a91bfca8a08ae59df16ddf30d22226aba773cc814dd106930840ab344fc52 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From bc9f9051a11880c06a921324e29b0d0a4b68b8b4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:36 +0000 Subject: [PATCH 28/89] changelog: #1631 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eec9ee9bf8..ed9a5d3d050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Nemotron 3.5 Transcribe on CUDA: the language model loads from the bf16 release as published, with exact bf16 caches and no conversion. The audio encoder runs on the GPU: log-mel, the ASR encoder, the streaming speaker encoder and its cache, fusion and projection. `tf-cuda-test audio-check` writes every encoder stage. Every other Nemotron checkpoint loads as before, and audio input in the server follows in #1632 (#1631). Thanks to @BobClawblaw, and to @cwschroeder for the CI report. + - CUDA: Gemma 4, Dory and Spark2.5 can keep conversations on disk through the shared kept-image store (#3135, part of #840). Thanks to @jschmied. - CUDA: a dense Qwen 3.5 MLP's NVFP4 prompt gate, up and activation run in one launch for prompt rows past 16, with the same bytes (#3252). Thanks to @jschmied. From 4217669b0f5a58c7c592e9b5bf210ee0a83a775d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:33:17 +0000 Subject: [PATCH 29/89] Keep fixed shared draft work out of the verification row price --- zig/src/core/lanes/depth.zig | 13 ++-- zig/src/core/lanes/price_log_test.zig | 2 +- zig/src/core/lanes/shared_drafts.zig | 2 +- zig/src/core/lanes/shared_price.zig | 23 +++--- zig/src/core/lanes/shared_price_8_test.zig | 81 ++++++++++++++++++++++ zig/src/core/lanes/shared_price_test.zig | 21 +++--- 6 files changed, 113 insertions(+), 29 deletions(-) create mode 100644 zig/src/core/lanes/shared_price_8_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 8d7c793b9db..6fe95c2bc47 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -387,19 +387,19 @@ pub const Rule = struct { } } - /// Independent plain price and the row slope from a plain/drafted pair, at this exact count and mode. + /// A plain measurement changes only the zero-draft option, never the existing drafted curve. pub fn sharedPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { if (streams < 2 or !r.plain_guard or r.confidence_floor != null) return null; - var price = r.shared_price.price(streams, sampled, r.row_cost.extraMs(streams, sampled)) orelse return null; - // The independent plain point owns the intercept; row learning owns the signed, noise-tested slope. - if (r.k.learn_rows) price.row = r.row_cost.extraMs(streams, sampled); + const head = if (r.nearest(streams, sampled)) |o| o.head else 0; + var price = r.shared_price.price(streams, sampled, r.fixedMs(streams, sampled), head, r.row_cost.extraMs(streams, sampled)) orelse return null; + if (r.k.learn_rows) price.fixed = price.plain; return price; } /// Held drafts have already run; every verify option retains the round's same head fixed cost. pub fn verifyPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { var price = r.sharedPrice(streams, sampled) orelse return null; - const head = if (r.nearest(streams, sampled)) |o| o.head else 0; + const head = price.head; price.plain += head; price.fixed += head; return price; @@ -415,7 +415,7 @@ pub const Rule = struct { pub fn observeSharedPrice(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { if (streams > 1 and r.plain_guard and r.confidence_floor == null) { const residual = if (r.shared_costs.get(@intCast(rows))) |forward| ms - forward - head_ms else std.math.nan(f64); - try r.shared_price.observe(r.gpa, streams, rows, residual, sampled, plain, calibration); + try r.shared_price.observeHead(r.gpa, streams, rows, residual, head_ms, sampled, plain, calibration); } } @@ -502,6 +502,7 @@ test { _ = @import("shared_warmup_test.zig"); _ = @import("shared_head_price_test.zig"); _ = @import("shared_price_learning_test.zig"); + _ = @import("shared_price_8_test.zig"); } test { diff --git a/zig/src/core/lanes/price_log_test.zig b/zig/src/core/lanes/price_log_test.zig index 62cf8678d88..2290dd2fe3f 100644 --- a/zig/src/core/lanes/price_log_test.zig +++ b/zig/src/core/lanes/price_log_test.zig @@ -55,7 +55,7 @@ test "shared price log: a round line has its trial, rows, time, each stream's dr try r.observeShared(2, 4, 19, false, 0, false, false); out.clearRetainingCapacity(); try log.line(&out.writer, &r, &plans, &windows, .{ .trial = true, .sampled = false, .ms = 15, .head_ms = 0, .heads = &.{0}, .depths = &.{0} }); - try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=1.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); + try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=0.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); } const Env = struct { diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index f886081ceac..d99cee0bcfc 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -59,7 +59,7 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ } const paired = e.rule.sharedPrice(live, sampled); const counts = if (paired) |p| - try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, p.fixed, e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = neural, .least_rows = e.rule.row_cost.leastRows(live, sampled) }) + try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, p.fixed + p.head, e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .least_rows = e.rule.row_cost.leastRows(live, sampled) }) else try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, e.rule.overheadMs(@intCast(live), sampled), e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .row_ms = e.rule.row_cost.extraMs(live, sampled), .least_rows = e.rule.row_cost.leastRows(live, sampled) }); for (heads, out) |i, *budget| { diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index 8483ea6c69f..a6a7de15092 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -1,9 +1,9 @@ -//! Exact-count, exact-mode shared prices: a plain intercept and a drafted row excess. +//! Exact-count, exact-mode shared prices: an independent plain option alongside the existing drafted curve. const std = @import("std"); const Allocator = std.mem.Allocator; pub const every: u64 = 64; pub const stale: u64 = 256; -const Point = struct { residual: f64, rows: f64, at: u64 }; +const Point = struct { residual: f64, head: f64 = 0, at: u64 }; const Bucket = struct { streams: usize, sampled: bool, @@ -13,7 +13,7 @@ const Bucket = struct { plain: ?Point = null, draft: ?Point = null, }; -pub const Price = struct { plain: f64, fixed: f64, row: f64 }; +pub const Price = struct { plain: f64, fixed: f64, row: f64, head: f64 = 0 }; pub const Prices = struct { buckets: std.ArrayList(Bucket) = .empty, @@ -49,13 +49,17 @@ pub const Prices = struct { /// No drafting round moves the plain point; a count's first plain trial is a warm-up, each later one replaces it. pub fn observe(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, sampled: bool, plain: bool, calibration: bool) !void { + return p.observeHead(a, streams, rows, residual, 0, sampled, plain, calibration); + } + + pub fn observeHead(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, head: f64, sampled: bool, plain: bool, calibration: bool) !void { const b = try p.get(a, streams, sampled); b.rounds +|= 1; if (calibration) b.last_probe = b.rounds; const trial = calibration and plain and rows == streams; if (trial) b.trials +|= 1; if (!std.math.isFinite(residual)) return; - const point: Point = .{ .residual = residual, .rows = @floatFromInt(rows), .at = b.rounds }; + const point: Point = .{ .residual = residual, .head = head, .at = b.rounds }; if (trial) { if (b.trials > 1) b.plain = point; } else if (plain and rows == streams) { @@ -64,21 +68,18 @@ pub const Prices = struct { } /// Until a plain round is measured, leave the existing allocator and its draft ranking in charge. - pub fn price(p: *const Prices, streams: usize, sampled: bool, row: f64) ?Price { + pub fn price(p: *const Prices, streams: usize, sampled: bool, fixed: f64, head: f64, row: f64) ?Price { const b = p.buckets.items[p.find(streams, sampled) orelse return null]; const plain = b.plain orelse return null; - var out: Price = .{ .plain = plain.residual, .fixed = plain.residual, .row = row }; - if (b.draft) |draft| if (draft.rows > plain.rows) { - out.row = @max(0, (draft.residual - plain.residual) / (draft.rows - plain.rows)); - }; - return out; + const draft = b.draft; + return .{ .plain = plain.residual, .fixed = if (draft) |v| v.residual else fixed, .row = row, .head = if (draft) |v| v.head else head }; } }; fn blend(to: *?Point, v: Point) void { if (to.*) |*old| { old.residual += 0.2 * (v.residual - old.residual); - old.rows += 0.2 * (v.rows - old.rows); + old.head += 0.2 * (v.head - old.head); old.at = v.at; } else to.* = v; } diff --git a/zig/src/core/lanes/shared_price_8_test.zig b/zig/src/core/lanes/shared_price_8_test.zig new file mode 100644 index 00000000000..81455fbd14f --- /dev/null +++ b/zig/src/core/lanes/shared_price_8_test.zig @@ -0,0 +1,81 @@ +//! Eight-stream calibration regression with a deterministic host cost record. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const Config = @import("config.zig").Config; +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +const costs = [_]@import("allocate.zig").Cost{ + .{ .width = 1, .ms = 38 }, + .{ .width = 8, .ms = 40 }, + .{ .width = 16, .ms = 42 }, + .{ .width = 32, .ms = 48 }, + .{ .width = 64, .ms = 65 }, + .{ .width = 68, .ms = 67 }, + .{ .width = 128, .ms = 120 }, +}; +const chances = [_]f64{ 0.9, 0.75, 0.6, 0.48, 0.39, 0.32, 0.26, 0.24, 0.17, 0.14, 0.115, 0.095, 0.08, 0.06, 0.04 }; +const heads = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 7 }; +const tokens: [15]u32 = @splat(7); +const want = [_]i64{ 8, 8, 8, 8, 7, 7, 7, 7 }; // 60 drafts over eight streams: 7.5 each + +fn probabilities(_: *anyopaque, _: *Stream, out: []f64) !bool { + @memcpy(out, chances[0..out.len]); + return true; +} + +fn check(e: *Engine, plans: *[8]win.Plan, streams: *[8]Stream) !void { + var budgets: [8]i64 = undefined; + try @import("shared_drafts.zig").budgets(e, plans, &heads, &budgets); + try t.expectEqualSlices(i64, &want, &budgets); + for (plans, streams) |*p, *s| p.* = .{ .stream = s, .position = 1, .kind = .head, .tokens = &tokens }; + try win.allocate(e, plans); + for (plans, want) |p, n| try t.expectEqual(@as(usize, @intCast(n)), p.count()); +} + +test "shared combined prices: eight streams keep 7.5 drafts across calibration of a fixed block cost" { + for ([_]bool{ false, true }) |sampled| { + var cfg = try Config.init(a, .{ .exact_width = 64, .mtp = true, .drafts = 15, .draft_probabilities = true, .allocate_shared_drafts = true, .draft_streams = true, .mtp_step_ms = 1, .copy_drafts = false, .plain_guard = true, .hidden_rows = true, .batch_rows = 128, .window_costs = &costs }, 64, 63); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var backend = target.backend(); + var vtable = backend.vtable.*; + vtable.probabilities = probabilities; + backend.vtable = &vtable; + var e = Engine.init(a, &cfg, backend, clock.clock()); + defer e.deinit(); + var streams: [8]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [8]win.Plan = undefined; + for (&streams, &plans) |*s, *p| { + s.* = try Stream.init(a, .{ .id = "eight", .prompt = &.{ 1, 2, 3 }, .max_new = 1000, .sampling = if (sampled) .{ .seed = 19, .temperature = 1 } else null }); + made += 1; + s.rounds = 1; + try s.draft_chances.appendSlice(a, &chances); + p.* = .{ .stream = s, .position = 1, .kind = .none }; + } + for (1..129) |round| { + const trial = try @import("shared_price.zig").calibrate(&e, &plans); + try t.expectEqual(round == 64 or round == 128, trial); + // Recorded host costs: 67 forward + 40 fixed draft work; plain is 40 forward + 2 overhead. + try e.rule.observeShared(8, if (trial) 8 else 68, if (trial) 42 else 107, sampled, if (trial) 0 else 8, trial, trial); + if (round == 63 or round == 64) { + try t.expect(e.rule.sharedPrice(8, sampled) == null); + try check(&e, &plans, &streams); + } + } + try check(&e, &plans, &streams); + const p = e.rule.sharedPrice(8, sampled).?; + try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); + try t.expectApproxEqAbs(@as(f64, 0), p.row, 1e-9); + // More plain observations cannot make the positive drafted options forget the block's fixed work. + for (0..32) |_| try e.rule.observeShared(8, 8, 42, sampled, 0, true, false); + try check(&e, &plans, &streams); + } +} diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index 07c6991641e..5372c0efa22 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -61,7 +61,7 @@ fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { try t.expect(e.rule.sharedPrice(2, sampled) != null); const p = e.rule.sharedPrice(2, sampled).?; try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); - try t.expectApproxEqAbs(row_ms, p.row, 1e-9); + try t.expectApproxEqAbs(@as(f64, 0), p.row, 1e-9); } if (row_ms > 5 and round == 129) try t.expectEqual(@as(usize, 2), target.last_rows); } @@ -119,22 +119,22 @@ test "shared prices: missing and stale trials obey exact independent count and m } } -test "shared prices: drafted work at plain width cannot update the intercept; two-point fit separates rows" { +test "shared prices: drafted work cannot update the intercept or invent a row slope" { var p: prices.Prices = .{}; defer p.deinit(a); try p.observe(a, 4, 4, 50, false, false, false); - try t.expect(p.price(4, false, 0) == null); + try t.expect(p.price(4, false, 6, 0, 0) == null); try p.observe(a, 4, 4, 2, false, true, false); try p.observe(a, 4, 8, 10, false, false, false); - const v = p.price(4, false, 99).?; + const v = p.price(4, false, 6, 0, 99).?; try t.expectEqual(@as(f64, 2), v.plain); - try t.expectEqual(@as(f64, 2), v.fixed); - try t.expectEqual(@as(f64, 2), v.row); - try t.expect(p.price(4, true, 0) == null); - try t.expect(p.price(2, false, 0) == null); + try t.expectEqual(@as(f64, 10), v.fixed); + try t.expectEqual(@as(f64, 99), v.row); + try t.expect(p.price(4, true, 6, 0, 0) == null); + try t.expect(p.price(2, false, 6, 0, 0) == null); } -test "shared prices: the round observer subtracts modeled heads before fitting rows" { +test "shared prices: the round observer retains fixed draft overhead separately from plain" { var table: @import("table.zig").Table = .{}; defer table.deinit(a); for (1..9) |n| try table.put(a, @intCast(n), 10); @@ -142,7 +142,8 @@ test "shared prices: the round observer subtracts modeled heads before fitting r defer r.deinit(); try r.observeShared(4, 4, 12, false, 0, true, false); try r.observeShared(4, 8, 32, false, 12, false, false); - try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.row); + try t.expectEqual(@as(f64, 0), r.sharedPrice(4, false).?.row); + try t.expect(r.sharedPrice(4, false).?.fixed > r.sharedPrice(4, false).?.plain); try r.observeShared(4, 4, 100, false, 12, false, false); try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.plain); } From a5b58c7430bf6cbc4630bfea66b62b0eb6851b8c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:42:33 +0000 Subject: [PATCH 30/89] Preserve chained head and copy prices beside explicit fixed block costs --- zig/build/lane_halt_host.zig | 2 +- zig/src/core/lanes/allocate.zig | 4 +- zig/src/core/lanes/config.zig | 2 + zig/src/core/lanes/depth.zig | 17 +- zig/src/core/lanes/depth_constants.zig | 1 + zig/src/core/lanes/drafted.zig | 1 + zig/src/core/lanes/drafter.zig | 1 + zig/src/core/lanes/price_log_test.zig | 2 +- zig/src/core/lanes/shared_drafts.zig | 2 +- zig/src/core/lanes/shared_price.zig | 29 +++- zig/src/core/lanes/shared_price_8_test.zig | 2 +- .../core/lanes/shared_price_modes_test.zig | 159 ++++++++++++++++++ zig/src/core/lanes/shared_price_test.zig | 21 ++- zig/src/families/qwen3_5/cuda_draft.zig | 2 +- 14 files changed, 218 insertions(+), 27 deletions(-) create mode 100644 zig/src/core/lanes/shared_price_modes_test.zig diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 848782b113e..5eff92e09d2 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -20,7 +20,7 @@ pub fn steps(b: *std.Build) void { b.step("test-lane-halt-host", "Halt ordering with a fake backend and no GPU dependencies").dependOn(&b.addRunArtifact(halt).step); b.step("test-lane-lone-host", "Existing lone-driver handoff and reclaim with a fake backend").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"lone driver"} })).step); b.step("test-lane-api-host", "Shared lane host and engine API CPU regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); - b.step("test-shared-price-learning-host", "Independent plain prices and signed row learning together without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"shared combined prices:"} })).step); + b.step("test-shared-price-learning-host", "Independent plain prices and signed row learning together without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{ "shared combined prices:", "shared price modes:" } })).step); b.step("test-wait-reasons-host", "Stored wait reasons in the load ledger with a fake backend and planner").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"wait reason ledger:"} })).step); b.step("test-conversation-cache-host", "Returning conversation eviction and queued-resume regressions without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{ "newest cache:", "queued cache:" } })).step); b.step("test-cache-progress-host", "One-state follow-ups and new conversations keep their next endpoint").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"queued cache: progress"} })).step); diff --git a/zig/src/core/lanes/allocate.zig b/zig/src/core/lanes/allocate.zig index 21520cb6dc2..43a75ac1549 100644 --- a/zig/src/core/lanes/allocate.zig +++ b/zig/src/core/lanes/allocate.zig @@ -18,6 +18,7 @@ pub fn allocate(gpa: Allocator, fixed: []const u32, probs: []const []const f64, /// What drafting the counted nodes costs: a head step each, or the deepest stream's steps when one batch drafts all. pub const HeadCost = struct { + block_ms: f64 = 0.0, // one fixed pass if any neural head runs; copies alone do not pay it step_ms: f64 = 0.0, plain_ms: ?f64 = null, // fixed residual for the zero-draft option, independently measured extra_step_ms: f64 = 0.0, // extra work past the first head step @@ -74,7 +75,8 @@ pub fn allocateDrafts(gpa: Allocator, fixed: []const u32, probs: []const []const const steps: f64 = @floatFromInt(if (head.batched) deepest -| @intFromBool(head.free_first) else drafts - (if (head.free_first) firsts else 0)); const extra_steps: f64 = @floatFromInt(if (head.batched) deepest -| 1 else drafts - firsts); if (rows < least) continue; - const now = rate(costs, timed, rows, expected, overhead_ms + head.step_ms * steps + head.extra_step_ms * extra_steps + rowTerm(costs, timed, head, rows, live)); + const block_ms = if (drafts > 0) head.block_ms else 0; + const now = rate(costs, timed, rows, expected, overhead_ms + block_ms + head.step_ms * steps + head.extra_step_ms * extra_steps + rowTerm(costs, timed, head, rows, live)); if (now > best or (!timed and head.step_ms == 0)) { best = now; @memcpy(best_counts, counts); diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index b7f0f20e41f..3dff73e82f1 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -12,6 +12,7 @@ pub const default_prior = [_]f64{ 0.85, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.5, 0. /// What a backend reports about its loaded model: the attributes the Python engine reads at setup. pub const Model = struct { + fixed_draft_block: bool = false, // a positive draft depth runs one fixed block pass learn_row_costs: bool = false, // shared_costs came from another machine: learn what a row costs here allocate_shared_drafts: bool = false, // reserve useful shared head rows before a proposal pass limit_shared_drafts: bool = false, // retain the cost rule's depth cap before reserving shared rows @@ -183,6 +184,7 @@ pub const Config = struct { .lane_costs = try alloc.extendCosts(gpa, m.lane_costs, 64), .mtp_step_ms = m.mtp_step_ms, .k = .{ + .fixed_draft_block = m.fixed_draft_block, .shared_step_ms = m.shared_step_ms, .depth_rate = if (m.depth_rate > 0) m.depth_rate else (Constants{}).depth_rate, .learn_rows = m.learn_row_costs, diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 6fe95c2bc47..47ed47343e5 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -346,7 +346,7 @@ pub const Rule = struct { @memset(ones, 1); const head: alloc.HeadCost = .{ .step_ms = r.sharedStepMs(), .batched = r.batched_heads, .row_ms = r.row_cost.extraMs(whos.len, sampled), .least_rows = r.row_cost.leastRows(whos.len, sampled) }; const all_counts = if (paired) |p| - try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, p.fixed, r.row_cost.capRows(streams, sampled, @max(streams, r.batch_rows)), .{ .plain_ms = p.plain, .step_ms = r.sharedStepMs(), .extra_step_ms = r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .row_ms = p.row, .least_rows = r.row_cost.leastRows(streams, sampled) }) + try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, if (r.k.fixed_draft_block) p.plain else p.fixed, r.row_cost.capRows(streams, sampled, @max(streams, r.batch_rows)), .{ .plain_ms = p.plain, .block_ms = if (r.k.fixed_draft_block) p.fixed + p.head - p.plain else 0, .step_ms = if (r.k.fixed_draft_block) 0 else r.sharedStepMs(), .extra_step_ms = if (r.k.fixed_draft_block) 0 else r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .row_ms = p.row, .least_rows = r.row_cost.leastRows(streams, sampled) }) else if (r.draft_step_ms != 0) try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, r.overheadMs(whos.len, sampled), r.row_cost.capRows(whos.len, sampled, @max(whos.len, r.batch_rows)), .{ .step_ms = r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .free_first = true, .row_ms = r.row_cost.extraMs(whos.len, sampled), .least_rows = head.least_rows }) else @@ -391,8 +391,16 @@ pub const Rule = struct { pub fn sharedPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { if (streams < 2 or !r.plain_guard or r.confidence_floor != null) return null; const head = if (r.nearest(streams, sampled)) |o| o.head else 0; - var price = r.shared_price.price(streams, sampled, r.fixedMs(streams, sampled), head, r.row_cost.extraMs(streams, sampled)) orelse return null; - if (r.k.learn_rows) price.fixed = price.plain; + const row = r.row_cost.extraMs(streams, sampled); + var price = (if (r.k.fixed_draft_block) + r.shared_price.blockPrice(streams, sampled, r.fixedMs(streams, sampled), head, row) + else + r.shared_price.price(streams, sampled, row)) orelse return null; + if (r.k.learn_rows) { + price.fixed = price.plain; + price.row = row; + } + if (!r.k.fixed_draft_block) price.head = head; return price; } @@ -415,7 +423,7 @@ pub const Rule = struct { pub fn observeSharedPrice(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { if (streams > 1 and r.plain_guard and r.confidence_floor == null) { const residual = if (r.shared_costs.get(@intCast(rows))) |forward| ms - forward - head_ms else std.math.nan(f64); - try r.shared_price.observeHead(r.gpa, streams, rows, residual, head_ms, sampled, plain, calibration); + try r.shared_price.observeHead(r.gpa, streams, rows, residual, head_ms, sampled, plain, calibration, r.k.fixed_draft_block); } } @@ -503,6 +511,7 @@ test { _ = @import("shared_head_price_test.zig"); _ = @import("shared_price_learning_test.zig"); _ = @import("shared_price_8_test.zig"); + _ = @import("shared_price_modes_test.zig"); } test { diff --git a/zig/src/core/lanes/depth_constants.zig b/zig/src/core/lanes/depth_constants.zig index fe914c3e8e3..ef87f217175 100644 --- a/zig/src/core/lanes/depth_constants.zig +++ b/zig/src/core/lanes/depth_constants.zig @@ -1,5 +1,6 @@ //! Depth policy and shared draft prices supplied by a model. pub const Constants = struct { + fixed_draft_block: bool = false, // draft work is fixed across positive depths shared_step_ms: ?f64 = null, // a shared round's head step, when it differs from the lone price depth_rate: f64 = 0.15, // weight of the newest round in a depth's acceptance diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index 362d9961f06..330f1125566 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -109,6 +109,7 @@ pub const Drafted = struct { m.allocate_shared_drafts = true; m.drafts = @min(d.depth, if (target.exact_width > 1) target.exact_width - 1 else 0); m.mtp_step_ms = d.step_ms; + m.fixed_draft_block = d.fixed_block; m.draft_prior = d.prior; m.plain_guard = d.plain_guard; m.draft_streams = d.batched; diff --git a/zig/src/core/lanes/drafter.zig b/zig/src/core/lanes/drafter.zig index 38314cfe150..66628bc77fd 100644 --- a/zig/src/core/lanes/drafter.zig +++ b/zig/src/core/lanes/drafter.zig @@ -8,6 +8,7 @@ const Allocator = @import("std").mem.Allocator; /// What the round loop's depth rule needs from the drafter itself (not from the target, whose own head may not exist). pub const Facts = struct { + fixed_block: bool = false, // every positive depth runs the same block pass limit_shared_drafts: bool = false, // retain the depth rule's head-step price before reserving shared rows depth: u32, // drafts a round at most step_ms: f64, // one more draft's cost (timed at load); the rule prices a round as forward(rows) + step_ms x drafts diff --git a/zig/src/core/lanes/price_log_test.zig b/zig/src/core/lanes/price_log_test.zig index 2290dd2fe3f..62cf8678d88 100644 --- a/zig/src/core/lanes/price_log_test.zig +++ b/zig/src/core/lanes/price_log_test.zig @@ -55,7 +55,7 @@ test "shared price log: a round line has its trial, rows, time, each stream's dr try r.observeShared(2, 4, 19, false, 0, false, false); out.clearRetainingCapacity(); try log.line(&out.writer, &r, &plans, &windows, .{ .trial = true, .sampled = false, .ms = 15, .head_ms = 0, .heads = &.{0}, .depths = &.{0} }); - try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=0.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); + try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=1.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); } const Env = struct { diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index d99cee0bcfc..fb265130e14 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -59,7 +59,7 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ } const paired = e.rule.sharedPrice(live, sampled); const counts = if (paired) |p| - try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, p.fixed + p.head, e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .least_rows = e.rule.row_cost.leastRows(live, sampled) }) + try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, if (e.rule.k.fixed_draft_block) p.plain else p.fixed, e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .block_ms = if (e.rule.k.fixed_draft_block) p.fixed + p.head - p.plain else 0, .step_ms = if (e.rule.k.fixed_draft_block) 0 else e.cfg.mtp_step_ms, .extra_step_ms = if (e.rule.k.fixed_draft_block) 0 else e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and alloc.pricedBatched(), .heads = neural, .row_ms = p.row, .least_rows = e.rule.row_cost.leastRows(live, sampled) }) else try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, e.rule.overheadMs(@intCast(live), sampled), e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .row_ms = e.rule.row_cost.extraMs(live, sampled), .least_rows = e.rule.row_cost.leastRows(live, sampled) }); for (heads, out) |i, *budget| { diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index a6a7de15092..a60cbc8a63c 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -3,7 +3,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; pub const every: u64 = 64; pub const stale: u64 = 256; -const Point = struct { residual: f64, head: f64 = 0, at: u64 }; +const Point = struct { residual: f64, rows: f64, head: f64 = 0, at: u64 }; const Bucket = struct { streams: usize, sampled: bool, @@ -49,36 +49,53 @@ pub const Prices = struct { /// No drafting round moves the plain point; a count's first plain trial is a warm-up, each later one replaces it. pub fn observe(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, sampled: bool, plain: bool, calibration: bool) !void { - return p.observeHead(a, streams, rows, residual, 0, sampled, plain, calibration); + return p.observeHead(a, streams, rows, residual, 0, sampled, plain, calibration, false); } - pub fn observeHead(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, head: f64, sampled: bool, plain: bool, calibration: bool) !void { + pub fn observeHead(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, head: f64, sampled: bool, plain: bool, calibration: bool, block: bool) !void { const b = try p.get(a, streams, sampled); b.rounds +|= 1; if (calibration) b.last_probe = b.rounds; const trial = calibration and plain and rows == streams; if (trial) b.trials +|= 1; if (!std.math.isFinite(residual)) return; - const point: Point = .{ .residual = residual, .head = head, .at = b.rounds }; + const point: Point = .{ .residual = residual, .rows = @floatFromInt(rows), .head = head, .at = b.rounds }; if (trial) { if (b.trials > 1) b.plain = point; } else if (plain and rows == streams) { blend(&b.plain, point); - } else if (rows > streams) blend(&b.draft, point); + } else if (rows > streams) { + if (block and b.draft != null and b.rounds -| b.draft.?.at >= stale) b.draft = null; + blend(&b.draft, point); + } } /// Until a plain round is measured, leave the existing allocator and its draft ranking in charge. - pub fn price(p: *const Prices, streams: usize, sampled: bool, fixed: f64, head: f64, row: f64) ?Price { + pub fn blockPrice(p: *const Prices, streams: usize, sampled: bool, fixed: f64, head: f64, row: f64) ?Price { const b = p.buckets.items[p.find(streams, sampled) orelse return null]; const plain = b.plain orelse return null; const draft = b.draft; + // A stale block observation cannot suppress the existing allocator's next positive probe forever. + if (draft) |v| if (b.rounds -| v.at >= stale) return null; return .{ .plain = plain.residual, .fixed = if (draft) |v| v.residual else fixed, .row = row, .head = if (draft) |v| v.head else head }; } + + /// Copy and chained-head models keep the measured row feedback, with head steps priced separately. + pub fn price(p: *const Prices, streams: usize, sampled: bool, row: f64) ?Price { + const b = p.buckets.items[p.find(streams, sampled) orelse return null]; + const plain = b.plain orelse return null; + var out: Price = .{ .plain = plain.residual, .fixed = plain.residual, .row = row }; + if (b.draft) |draft| if (draft.rows > plain.rows) { + out.row = @max(0, (draft.residual - plain.residual) / (draft.rows - plain.rows)); + }; + return out; + } }; fn blend(to: *?Point, v: Point) void { if (to.*) |*old| { old.residual += 0.2 * (v.residual - old.residual); + old.rows += 0.2 * (v.rows - old.rows); old.head += 0.2 * (v.head - old.head); old.at = v.at; } else to.* = v; diff --git a/zig/src/core/lanes/shared_price_8_test.zig b/zig/src/core/lanes/shared_price_8_test.zig index 81455fbd14f..69c578c2bfa 100644 --- a/zig/src/core/lanes/shared_price_8_test.zig +++ b/zig/src/core/lanes/shared_price_8_test.zig @@ -38,7 +38,7 @@ fn check(e: *Engine, plans: *[8]win.Plan, streams: *[8]Stream) !void { test "shared combined prices: eight streams keep 7.5 drafts across calibration of a fixed block cost" { for ([_]bool{ false, true }) |sampled| { - var cfg = try Config.init(a, .{ .exact_width = 64, .mtp = true, .drafts = 15, .draft_probabilities = true, .allocate_shared_drafts = true, .draft_streams = true, .mtp_step_ms = 1, .copy_drafts = false, .plain_guard = true, .hidden_rows = true, .batch_rows = 128, .window_costs = &costs }, 64, 63); + var cfg = try Config.init(a, .{ .fixed_draft_block = true, .exact_width = 64, .mtp = true, .drafts = 15, .draft_probabilities = true, .allocate_shared_drafts = true, .draft_streams = true, .mtp_step_ms = 1, .copy_drafts = false, .plain_guard = true, .hidden_rows = true, .batch_rows = 128, .window_costs = &costs }, 64, 63); defer cfg.deinit(a); var target: fake.Fake = .{ .gpa = a }; defer target.deinit(); diff --git a/zig/src/core/lanes/shared_price_modes_test.zig b/zig/src/core/lanes/shared_price_modes_test.zig new file mode 100644 index 00000000000..23a291c3931 --- /dev/null +++ b/zig/src/core/lanes/shared_price_modes_test.zig @@ -0,0 +1,159 @@ +//! Block passes, chained heads and copied rows retain their distinct costs through calibration. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const Config = @import("config.zig").Config; +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const fake = @import("fake.zig"); +const win = @import("windows.zig"); +const draft = @import("shared_drafts.zig"); +const costs = [_]@import("allocate.zig").Cost{ .{ .width = 1, .ms = 10 }, .{ .width = 64, .ms = 10 } }; +const chances = [_]f64{ 0.4, 0.04, 0.004, 0.0004 }; + +fn mtp(n: usize, sampled: bool, limited: bool, old_depth: u32) !void { + var cfg = try Config.init(a, .{ .exact_width = 16, .mtp = true, .speculate = true, .drafts = 4, .draft_prior = &.{ 0.4, 0.1, 0.1, 0.1 }, .mtp_step_ms = 2, .draft_step_ms = 1, .draft_streams = true, .copy_drafts = false, .allocate_shared_drafts = true, .limit_shared_drafts = limited, .plain_guard = true, .hidden_rows = true, .batch_rows = 64, .window_costs = &costs }, 16, 15); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + var streams: [8]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [8]win.Plan = undefined; + var heads: [8]usize = undefined; + var budgets: [8]i64 = undefined; + for (streams[0..n], plans[0..n], heads[0..n], 0..) |*s, *p, *h, i| { + s.* = try Stream.init(a, .{ .id = "mtp", .prompt = &.{ 1, 2, 3 }, .max_new = 1000, .sampling = if (sampled) .{ .seed = 19, .temperature = 1 } else null }); + made += 1; + s.rounds = 1; + try s.draft_chances.appendSlice(a, &chances); + p.* = .{ .stream = s, .position = 1, .kind = .none }; + h.* = i; + } + for (1..129) |round| { + const trial = try @import("shared_price.zig").calibrate(&e, plans[0..n]); + try t.expectEqual(round == 64 or round == 128, trial); + const head = @as(f64, @floatFromInt(old_depth)) * 2 + @as(f64, @floatFromInt(old_depth - 1)); + try e.rule.observeShared(@intCast(n), if (trial) n else n * (old_depth + 1), if (trial) 12 else 12 + head, sampled, if (trial) 0 else head, trial, trial); + if (round == 63 or round == 64 or round == 128) { + try draft.budgets(&e, plans[0..n], heads[0..n], budgets[0..n]); + const want: i64 = if (round < 128 and !limited) 4 else 1; + for (budgets[0..n], 0..) |got, i| { + errdefer std.debug.print("mtp n={d} sampled={any} limited={any} old_depth={d} round={d} i={d} budgets={any} price={any}\n", .{ n, sampled, limited, old_depth, round, i, budgets[0..n], e.rule.sharedPrice(n, sampled) }); + try t.expectEqual(want, got); + } + } + } + for (0..16) |_| try e.rule.observeShared(@intCast(n), n, 12, sampled, 0, true, false); + try draft.budgets(&e, plans[0..n], heads[0..n], budgets[0..n]); + for (budgets[0..n]) |got| try t.expectEqual(@as(i64, 1), got); + try t.expect(e.rule.sharedPrice(1, sampled) == null); +} + +test "shared price modes: MTP at two four eight streams pays steps before and after calibration" { + for ([_]usize{ 2, 4, 8 }) |n| for ([_]bool{ false, true }) |sampled| { + for ([_]bool{ false, true }) |limited| for ([_]u32{ 1, 3 }) |old_depth| try mtp(n, sampled, limited, old_depth); + }; +} + +const Copier = struct { + fn propose(_: *anyopaque, _: []const u32, _: i64) ![]const u32 { + return &.{ 7, 7, 7, 7 }; + } + fn match(_: *anyopaque) i64 { + return 100; + } + const vtable: @import("proposer.zig").Proposer.VTable = .{ .propose = propose, .last_match = match, .priced = true }; +}; + +test "shared price modes: mixed copied rows never pay a neural step or start a block pass" { + for ([_]bool{ false, true }) |block| { + var cfg = try Config.init(a, .{ .fixed_draft_block = block, .exact_width = 16, .mtp = true, .drafts = 4, .draft_streams = true, .mtp_step_ms = 4, .plain_guard = true, .hidden_rows = true, .batch_rows = 64, .allocate_shared_drafts = true, .window_costs = &costs }, 16, 15); + defer cfg.deinit(a); + cfg.copy_rate = 1; + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + e.alone = false; + try e.rule.observeShared(2, 2, 12, false, 0, true, false); + try e.rule.observeShared(2, 4, 16, false, 4, false, false); + var copy = try Stream.init(a, .{ .id = "copy", .prompt = &.{ 1, 2, 3 }, .max_new = 100, .proposer = .{ .ptr = &target, .vtable = &Copier.vtable } }); + defer copy.deinit(a); + var head = try Stream.init(a, .{ .id = "head", .prompt = &.{ 1, 2, 3 }, .max_new = 100 }); + defer head.deinit(a); + try head.draft_chances.appendSlice(a, &.{ 0.9, 0.01, 0.001, 0.0001 }); + const plans = [_]win.Plan{ .{ .stream = ©, .position = 1, .kind = .none }, .{ .stream = &head, .position = 1, .kind = .none } }; + var budgets: [1]i64 = undefined; + try draft.budgets(&e, &plans, &.{1}, &budgets); + try t.expectEqual(@as(i64, 0), budgets[0]); + if (!block) { + copy.proposer = null; + copy.drafts = false; + head.draft_chances.clearRetainingCapacity(); + try head.draft_chances.appendSlice(a, &.{ 0.8, 0.7, 0.01, 0.001 }); + cfg.mtp_step_ms = 1; + for ([_]f64{ 0, 10 }, [_]i64{ 2, 1 }) |extra, want| { + cfg.draft_step_ms = extra; + try draft.budgets(&e, &plans, &.{1}, &budgets); + try t.expectEqual(want, budgets[0]); + } + } + } +} + +test "shared price modes: copy-only shared windows retain the measured row feedback" { + var cfg = try Config.init(a, .{ .exact_width = 16, .plain_guard = true, .hidden_rows = true, .batch_rows = 64, .window_costs = &costs }, 16, 15); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + try e.rule.observeShared(2, 2, 12, false, 0, true, false); + try e.rule.observeShared(2, 10, 52, false, 0, false, false); + try t.expectApproxEqAbs(@as(f64, 5), e.rule.sharedPrice(2, false).?.row, 1e-9); + var one = try Stream.init(a, .{ .id = "copy-a", .prompt = &.{1}, .max_new = 100 }); + defer one.deinit(a); + var two = try Stream.init(a, .{ .id = "copy-b", .prompt = &.{1}, .max_new = 100 }); + defer two.deinit(a); + var plans = [_]win.Plan{ .{ .stream = &one, .position = 1, .kind = .copy, .tokens = &.{ 7, 7, 7, 7 } }, .{ .stream = &two, .position = 1, .kind = .copy, .tokens = &.{ 7, 7, 7, 7 } } }; + try win.allocate(&e, &plans); + try t.expectEqual(@as(usize, 2), plans[0].count()); + try t.expectEqual(@as(usize, 2), plans[1].count()); +} + +test "shared price modes: the wrapper carries a drafter's explicit fixed-block fact" { + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var drafter: @import("drafted_test.zig").FakeDrafter = .{}; + defer drafter.deinit(); + var wrapper = try @import("drafted.zig").Drafted.init(a, target.backend(), drafter.drafter()); + defer wrapper.deinit(); + try t.expect(!wrapper.facts(.{ .exact_width = 16 }).fixed_draft_block); + drafter.facts_.fixed_block = true; + const m = wrapper.facts(.{ .exact_width = 16 }); + try t.expect(m.fixed_draft_block); + var cfg = try Config.init(a, m, 16, 15); + defer cfg.deinit(a); + try t.expect(cfg.k.fixed_draft_block); +} + +test "shared price modes: a stale expensive block can be measured again without retaining the spike" { + const prices = @import("shared_price.zig"); + var p: prices.Prices = .{}; + defer p.deinit(a); + try p.observeHead(a, 4, 4, 2, 0, false, true, false, true); + try p.observeHead(a, 4, 8, 200, 4, false, false, false, true); + for (0..prices.stale - 1) |_| try p.observeHead(a, 4, 4, 2, 0, false, true, false, true); + try t.expectEqual(@as(f64, 200), p.blockPrice(4, false, 2, 0, 0).?.fixed); + try p.observeHead(a, 4, 4, 2, 0, false, true, false, true); + try t.expect(p.blockPrice(4, false, 2, 0, 0) == null); + try p.observeHead(a, 4, 8, 10, 2, false, false, false, true); + try t.expectEqual(@as(f64, 10), p.blockPrice(4, false, 2, 0, 0).?.fixed); + try t.expectEqual(@as(f64, 2), p.blockPrice(4, false, 2, 0, 0).?.head); +} diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index 5372c0efa22..07c6991641e 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -61,7 +61,7 @@ fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { try t.expect(e.rule.sharedPrice(2, sampled) != null); const p = e.rule.sharedPrice(2, sampled).?; try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); - try t.expectApproxEqAbs(@as(f64, 0), p.row, 1e-9); + try t.expectApproxEqAbs(row_ms, p.row, 1e-9); } if (row_ms > 5 and round == 129) try t.expectEqual(@as(usize, 2), target.last_rows); } @@ -119,22 +119,22 @@ test "shared prices: missing and stale trials obey exact independent count and m } } -test "shared prices: drafted work cannot update the intercept or invent a row slope" { +test "shared prices: drafted work at plain width cannot update the intercept; two-point fit separates rows" { var p: prices.Prices = .{}; defer p.deinit(a); try p.observe(a, 4, 4, 50, false, false, false); - try t.expect(p.price(4, false, 6, 0, 0) == null); + try t.expect(p.price(4, false, 0) == null); try p.observe(a, 4, 4, 2, false, true, false); try p.observe(a, 4, 8, 10, false, false, false); - const v = p.price(4, false, 6, 0, 99).?; + const v = p.price(4, false, 99).?; try t.expectEqual(@as(f64, 2), v.plain); - try t.expectEqual(@as(f64, 10), v.fixed); - try t.expectEqual(@as(f64, 99), v.row); - try t.expect(p.price(4, true, 6, 0, 0) == null); - try t.expect(p.price(2, false, 6, 0, 0) == null); + try t.expectEqual(@as(f64, 2), v.fixed); + try t.expectEqual(@as(f64, 2), v.row); + try t.expect(p.price(4, true, 0) == null); + try t.expect(p.price(2, false, 0) == null); } -test "shared prices: the round observer retains fixed draft overhead separately from plain" { +test "shared prices: the round observer subtracts modeled heads before fitting rows" { var table: @import("table.zig").Table = .{}; defer table.deinit(a); for (1..9) |n| try table.put(a, @intCast(n), 10); @@ -142,8 +142,7 @@ test "shared prices: the round observer retains fixed draft overhead separately defer r.deinit(); try r.observeShared(4, 4, 12, false, 0, true, false); try r.observeShared(4, 8, 32, false, 12, false, false); - try t.expectEqual(@as(f64, 0), r.sharedPrice(4, false).?.row); - try t.expect(r.sharedPrice(4, false).?.fixed > r.sharedPrice(4, false).?.plain); + try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.row); try r.observeShared(4, 4, 100, false, 12, false, false); try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.plain); } diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index 50da9d7a050..5c9d057ab8d 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -440,7 +440,7 @@ pub const Draft = struct { fn factsFn(p: *anyopaque) dr.Facts { const d = cast(p); // TF_NO_TREES=1: chains only (for comparing) - return .{ .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = platform.c.getenv("TF_NO_TREES") == null, .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) }; + return .{ .fixed_block = d.c.kind == .dflash2, .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = platform.c.getenv("TF_NO_TREES") == null, .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) }; } fn openFn(p: *anyopaque, s: *Stream) anyerror!void { From f48b6f79184edc3f58983733fd008d679207d7bc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:38 +0000 Subject: [PATCH 31/89] changelog: #3755 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed9a5d3d050..529b5d8a35d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Shared decoding: fixed DFlash2 block work stays separate from verification rows; MTP heads keep their step costs and copied rows keep their measured cost feedback (#3755). + - Nemotron 3.5 Transcribe on CUDA: the language model loads from the bf16 release as published, with exact bf16 caches and no conversion. The audio encoder runs on the GPU: log-mel, the ASR encoder, the streaming speaker encoder and its cache, fusion and projection. `tf-cuda-test audio-check` writes every encoder stage. Every other Nemotron checkpoint loads as before, and audio input in the server follows in #1632 (#1631). Thanks to @BobClawblaw, and to @cwschroeder for the CI report. - CUDA: Gemma 4, Dory and Spark2.5 can keep conversations on disk through the shared kept-image store (#3135, part of #840). Thanks to @jschmied. From 8c247634c932c9f6759626a188d66e59d2e25363 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:58:38 +0000 Subject: [PATCH 32/89] server: /score, TEI's texts and Cohere's /v2/rerank as shapes of the rerank route Each shape builds the existing rerank request and reads its results back: the same prompts, the same sigmoid(yes - no) scores and the same order, with TEI's raw_scores the label logit difference the score is the sigmoid of. A server whose model has no reranker labels, or whose engine has neither a score nor a decision hook, refuses them with HTTP 400 before any work. The routes join the inference key scope and only the two old aliases take PUT; a documents body at /rerank and /v1/rerank is unchanged. Host tests compare every shape with the existing response. Fixes #3174 --- docs/api.md | 40 +++- zig/build/rerank_host.zig | 6 +- zig/src/server/auth_scope.zig | 1 + zig/src/server/auth_scope_test.zig | 4 +- zig/src/server/rerank.zig | 63 +++--- zig/src/server/rerank_test.zig | 6 +- zig/src/server/root.zig | 1 + zig/src/server/routes.zig | 4 +- zig/src/server/score_routes.zig | 235 ++++++++++++++++++++++ zig/src/server/score_routes_test.zig | 288 +++++++++++++++++++++++++++ 10 files changed, 597 insertions(+), 51 deletions(-) create mode 100644 zig/src/server/score_routes.zig create mode 100644 zig/src/server/score_routes_test.zig diff --git a/docs/api.md b/docs/api.md index 69ab4fb1ba6..0fab69c75c9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -45,7 +45,7 @@ different scopes, or scopes a key the flags or environment already give, is refu | Scope | Routes | | --- | --- | -| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | +| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | | `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/models`, `/models`, `/v1/voices` | A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights, @@ -129,6 +129,9 @@ routes still require when keys are on. Without the flag no reply carries a CORS | `POST /v1/responses` | OpenAI's Responses API, run as the equivalent chat completion; streamed or non-streamed | | `GET /v1/responses` (WebSocket upgrade) | OpenAI's Responses [WebSocket mode](#websocket-mode): `response.create` events over one socket | | `GET /v1/responses/{id}`, `DELETE /v1/responses/{id}` | A stored response, or remove it | +| `POST /score`, `POST /v1/score` | Text-pair scores in request order, using the configured reranker | +| `POST /rerank`, `POST /v1/rerank` | Ranked documents; a `texts` body selects the TEI response shape | +| `POST /v2/rerank` | Cohere-style ranked `results` over the same score hook | | `POST /v1/decisions` | Choice, score, and yes/no probabilities from the next-token logits; no text is generated | | `POST /v1/imprint/resume` | How much of a chat body's conversation resumes, and from where ([on disk](#conversations-on-disk)) | | `POST /v1/imprint/load` | A chat body's conversation state read from disk into RAM now | @@ -218,6 +221,41 @@ context window before the first is scored, so a refused request costs no GPU wor `max_length` above it) returns HTTP 400 with `code` `context_length_exceeded`. An image or video part returns HTTP 400. Errors use the server's envelope, as on every route: `{"error": {"message", "type"}}`. +### Score and rerank compatibility shapes + +These translations use the same configured reranker, query/document template, yes/no label tokens and score or +decision hook described above. They add no engine or model support. Other models return HTTP 400, and an engine +without either scoring hook returns a named refusal. The routes require the `inference` key scope. Only the +existing `/rerank` and `/v1/rerank` aliases also accept PUT. + +| Request | Response | +| --- | --- | +| `/score` or `/v1/score`: `{"text_1":"query","text_2":["a","b"]}` | A list object whose `data` entries contain `index`, `object:"score"` and `score`, in input order; also `id`, `created`, `model` and token `usage` | +| `/rerank` or `/v1/rerank`: `{"query":"q","texts":["a","b"]}` | TEI-style array of `{index,score}`, best first; `return_text:true` adds `text` | +| `/v2/rerank`: `{"query":"q","documents":["a","b"]}` | `{id,results:[{index,relevance_score}],meta:{api_version:{version:"2"}}}` | + +`/score` accepts strings or non-empty string lists on either side. Equal-length lists are paired; one item on +either side broadcasts to the other list. Unequal longer lists are refused. Every pair is validated before any +inference. Scores are the existing sigmoid(yes minus no), not generation log probabilities. Pair-scoring requests +return every pair; rerank-only fields such as `top_n` or `return_documents` are refused there. + +A `texts` body with no `documents` selects the TEI shape; a `documents` body at `/rerank` or `/v1/rerank` keeps the +existing response and defaults. Both new rerank shapes return the same scores as that response, best first, equal +scores in request order, and `index` is the input's position in the request. Both take a positive integer `top_n` +(an extension on TEI, whose request has none), capped to the number of inputs. TEI inputs are strings; +`return_documents:true` is also taken as `return_text`. TEI `raw_scores:true` returns the label logit difference +(yes minus no) the score is the sigmoid of, sorted by that value before `top_n`, so scores that round to 1 still +rank. Cohere's v2 request takes string documents and returns `index` and `relevance_score` only; `{"text":...}` +objects and `return_documents:true` (Cohere v1's fields) are also taken, the latter adding a `document` object that +wraps a string as `{"text":...}` and returns a supplied object as sent. + +`model`, when given on the new shapes, must name this server or an alias. `instruction`/`instruct` and `max_length` +use the existing reranker semantics. TEI does not truncate unless `truncate:true`; only right truncation is +supported (`truncation_direction:"Right"`). Pair scoring also refuses an over-limit prompt by default; a positive +`truncate_prompt_tokens` explicitly sets its truncation cap, and cannot be combined with `max_length`. The normal +context-window check still applies. Cohere-style requests retain the reranker's default right truncation cap. +`rank_fields`, `max_tokens_per_doc` and `priority` are refused by name. No vendor billing units are invented. + ## OCR The native HIP engine reads page images through Mistral's OCR contract when it serves a model with an OCR reader diff --git a/zig/build/rerank_host.zig b/zig/build/rerank_host.zig index f83a3cc7ba7..74b80699359 100644 --- a/zig/build/rerank_host.zig +++ b/zig/build/rerank_host.zig @@ -1,8 +1,8 @@ -//! test-rerank-host: the /v1/rerank route and the reranker's labels on the CPU; TF_QWEN3_RERANK_* checks real ids. +//! test-rerank-host: the rerank and score routes and the reranker's labels; TF_QWEN3_RERANK_* checks real ids. const std = @import("std"); pub fn steps(b: *std.Build, server_tests: *std.Build.Module) void { - const run = b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"rerank:"} })); + const run = b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "rerank:", "score shapes:" } })); run.has_side_effects = true; // TF_QWEN3_RERANK_DIR and _REF are not cached inputs - b.step("test-rerank-host", "Reranker labels and the /v1/rerank route; TF_QWEN3_RERANK_* checks real ids").dependOn(&run.step); + b.step("test-rerank-host", "Reranker labels, /v1/rerank and its /score, TEI and /v2/rerank shapes; TF_QWEN3_RERANK_* checks real ids").dependOn(&run.step); } diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index 0f0d02d0b9d..cf11447cb1f 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -65,6 +65,7 @@ const inferring = [_][]const u8{ "/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings", "/v1/images/generations", "/decisions", "/v1/decisions", "/systemone", "/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr", + "/v2/rerank", "/score", "/v1/score", "/api/chat", "/api/generate", "/api/embed", "/api/show", "/apply-template", "/v1/apply-template", }; diff --git a/zig/src/server/auth_scope_test.zig b/zig/src/server/auth_scope_test.zig index b2cf767fb34..47c79080cae 100644 --- a/zig/src/server/auth_scope_test.zig +++ b/zig/src/server/auth_scope_test.zig @@ -61,14 +61,14 @@ const inference_routes = [_][]const u8{ "/responses", "/v1/messages", "/messages", "/messages/count_tokens", "/v1/messages/count_tokens", "/v1/tokenize", "/tokenize", "/v1/detokenize", "/detokenize", "/v1/audio/speech", "/v1/embeddings", "/decisions", "/v1/decisions", "/systemone", "/v1/systemone", -} ++ [_][]const u8{ "/apply-template", "/v1/apply-template" }; +} ++ [_][]const u8{ "/apply-template", "/v1/apply-template", "/rerank", "/v1/rerank", "/v2/rerank", "/score", "/v1/score" }; const read_routes = [_][]const u8{ "/metrics", "/v1/metrics", "/v1/load", "/memory", "/v1/memory", "/stats", "/dashboard", "/v1/benchmark/manifest" }; const private_routes = [_][]const u8{ "/v1/slide/learn", "/v1/slide/graph", "/v1/slide/fact/1", "/v1/recall", "/v1/imprint", "/v1/imprint/load", "/v1/imprint/resume", "/v1/responses/id", "/responses/id", "/x/models", "/x/completions", "/x/chat/completions", "/x/systemone", "/v1/completions/more", "/v1/../imprint/load", "/v1/%63ompletions", "/V1/COMPLETIONS", "/v1/completions#x", "http://h/v1/models", "/future/private", - "/slide/unknown.js", "/v1/completions/..", "/./v1/completions", + "/slide/unknown.js", "/v1/completions/..", "/./v1/completions", "/v2/score", "/v1/v2/rerank", }; test "auth scopes: route grants are exact and every other method or resource is refused" { diff --git a/zig/src/server/rerank.zig b/zig/src/server/rerank.zig index 90f406a5a4b..a0b3c7f952c 100644 --- a/zig/src/server/rerank.zig +++ b/zig/src/server/rerank.zig @@ -4,13 +4,11 @@ const api = @import("engine_api"); const json = @import("json"); const errors = @import("errors.zig"); const openai = @import("openai.zig"); -const http_body = @import("http_body.zig"); const reply_text = @import("reply_text.zig"); const model_text = @import("model_text.zig"); const wait = @import("wait_reason.zig"); const refusals = @import("refusals.zig"); const Server = @import("server.zig").Server; -const Conn = @import("http_conn.zig").Conn; const Value = json.Value; const Cx = errors.Cx; const Allocator = std.mem.Allocator; @@ -29,6 +27,8 @@ const Ask = struct { return_documents: bool, return_logits: bool, return_ids: bool, + /// False refuses a prompt past max_length instead of cutting it (the TEI and pair-score shapes' default). + truncate: bool = true, }; /// #1895's default cap on a prompt's tokens: the model card's max_length. @@ -37,57 +37,26 @@ pub const max_length_default = 8192; /// One document's score and the label logits it came from. const Scored = struct { score: f64, yes: f64, no: f64 }; -pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { - var cx: Cx = .{ .a = a }; - const raw = http_body.readJson(conn, &cx) catch |err| { - if (err == error.OutOfMemory) outOfMemory(&cx); - return sendErr(conn, &cx); - }; - const Gone = struct { - conn: *Conn, - fn check(g: @This()) bool { - return g.conn.peerGone(); - } - }; - const value = reply(srv, &cx, raw, Gone{ .conn = conn }) catch |err| { - if (err == error.Cancelled) { - conn.close = true; - return; - } - if (err == error.OutOfMemory) outOfMemory(&cx); - return sendErr(conn, &cx); - }; - send(conn, a, 200, value); -} - /// Compact separators and UTF-8 as it is. pub fn encode(a: Allocator, v: Value) Allocator.Error![]u8 { return json.stringify(a, v, .{ .compact = true, .ascii = false }) catch return error.OutOfMemory; } -fn send(conn: *Conn, a: Allocator, code: u16, v: Value) void { - conn.sendJson(code, encode(a, v) catch return); -} - -fn outOfMemory(cx: *Cx) void { - cx.kind = .server; - cx.message = "out of memory"; -} - /// The server's error envelope, as every route sends it: `{"error": {"message", "type", ...}}`. pub fn errorBody(cx: *const Cx) Allocator.Error!Value { return openai.wrapError(cx.a, try openai.errorBody(cx.a, cx, "documents")); } -fn sendErr(conn: *Conn, cx: *Cx) void { - const body = errorBody(cx) catch return; - send(conn, cx.a, cx.status(), body); -} - /// The ranked documents, or the refusal; `gone` says the client left (checked before each document's pass). pub fn reply(srv: *Server, cx: *Cx, body: Value, gone: anytype) Failure!Value { + return replyOptions(srv, cx, body, gone, true); +} + +/// `reply`, but a prompt past max_length is refused when `truncate` is false (score_routes.zig's shapes). +pub fn replyOptions(srv: *Server, cx: *Cx, body: Value, gone: anytype, truncate: bool) Failure!Value { const labels = srv.info.rerank orelse return cx.refuse("this model is not a reranker"); - const ask = try parse(cx, body); + var ask = try parse(cx, body); + ask.truncate = truncate; // each prompt is built in a scratch arena and dropped: a small body of many documents keeps no ids alive var scratch = std.heap.ArenaAllocator.init(srv.gpa); defer scratch.deinit(); @@ -150,6 +119,19 @@ pub fn reply(srv: *Server, cx: *Cx, body: Value, gone: anytype) Failure!Value { return build(srv, cx, ask, &frame, scored, tokens); } +/// The prompts `replyOptions` would score, built and checked with no engine work: a request of pairs checks all first. +pub fn validate(srv: *Server, cx: *Cx, body: Value, truncate: bool) errors.Refused!void { + var ask = try parse(cx, body); + ask.truncate = truncate; + var arena: std.heap.ArenaAllocator = .init(srv.gpa); + defer arena.deinit(); + var frame: ?Frame = null; + for (ask.documents, 0..) |doc, i| { + _ = arena.reset(.retain_capacity); + _ = try ready(srv, cx, arena.allocator(), ask, &frame, doc, i); + } +} + /// A failed pass: a server error while the engine is healthy, else the engine is unavailable. fn failed(srv: *Server, cx: *Cx) errors.Refused { return if (healthy(srv)) @@ -360,6 +342,7 @@ fn ready(srv: *Server, cx: *Cx, a: Allocator, ask: Ask, frame: *?Frame, document var ids = built.ids; const cap = ask.max_length; if (ids.len > cap) { + if (!ask.truncate) return cx.fail(.request, "document {d}: the prompt has {d} tokens, past max_length {d}, and truncation is disabled", .{ i, ids.len, cap }); const f = frame.* orelse try frameOf(srv, cx, ask); frame.* = f; // a tail this template renders otherwise for this document, a cut leaving no document token: refused diff --git a/zig/src/server/rerank_test.zig b/zig/src/server/rerank_test.zig index 50f737f771f..6504d7a9103 100644 --- a/zig/src/server/rerank_test.zig +++ b/zig/src/server/rerank_test.zig @@ -410,7 +410,7 @@ test "rerank: a client gone before a document stops before its pass" { } /// The bytes a dispatched request wrote back. -const Wire = struct { +pub const Wire = struct { bytes: std.ArrayList(u8) = .empty, fn write(ptr: *anyopaque, bytes: []const u8) error{Closed}!void { const w: *@This() = @ptrCast(@alignCast(ptr)); @@ -419,12 +419,12 @@ const Wire = struct { }; /// POSTs `body` to `path` through the server's dispatcher; the reply's bytes land in `wire`. -fn dispatch(srv: *Server, path: []const u8, body: []const u8, wire: *Wire) !void { +pub fn dispatch(srv: *Server, path: []const u8, body: []const u8, wire: *Wire) !void { return dispatchAs(srv, "POST", path, body, wire); } /// `dispatch` by `method`. -fn dispatchAs(srv: *Server, method: []const u8, path: []const u8, body: []const u8, wire: *Wire) !void { +pub fn dispatchAs(srv: *Server, method: []const u8, path: []const u8, body: []const u8, wire: *Wire) !void { const http = @import("http_conn.zig"); var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 321ab5ba6e7..04ec9f8b4ad 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -184,6 +184,7 @@ test { _ = @import("systemone.zig"); _ = @import("systemone_test.zig"); _ = @import("rerank_test.zig"); + _ = @import("score_routes_test.zig"); _ = @import("rerank_ids_test.zig"); _ = @import("rerank_cut_test.zig"); _ = @import("rerank_decide_test.zig"); diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 3cbd4ce6b79..71444334215 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -137,7 +137,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { const is_slide = std.mem.eql(u8, route, "/v1/slide/learn"); const imprint_op: ?api.ImprintOp = if (std.mem.eql(u8, route, "/v1/imprint/resume")) .where else if (std.mem.eql(u8, route, "/v1/imprint/load")) .load else null; const is_chat = std.mem.endsWith(u8, route, "/chat/completions"); - const is_rerank = std.mem.eql(u8, route, "/v1/rerank") or std.mem.eql(u8, route, "/rerank"); + const is_rerank = @import("score_routes.zig").route(route); const is_ocr = std.mem.eql(u8, route, "/v1/ocr"); const is_ollama_chat = std.mem.eql(u8, route, "/api/chat"); const is_ollama_generate = std.mem.eql(u8, route, "/api/generate"); @@ -162,7 +162,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { if (is_ollama_show) return ollama.show(srv, conn, a); if (is_slide) return slide.learn(srv, conn, a); if (imprint_op) |op| return imprint.post(srv, conn, a, op); - if (is_rerank) return @import("rerank.zig").post(srv, conn, a); + if (is_rerank) return @import("score_routes.zig").post(srv, conn, a); if (is_decisions) return decisions.post(srv, conn, a); if (is_systemone) return systemone.post(srv, conn, a); if (is_anthropic) return anthropic.post(srv, conn, a); diff --git a/zig/src/server/score_routes.zig b/zig/src/server/score_routes.zig new file mode 100644 index 00000000000..4ed36e9197d --- /dev/null +++ b/zig/src/server/score_routes.zig @@ -0,0 +1,235 @@ +//! Score and rerank wire formats translated onto the existing reranker prompt and score hooks. +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const rerank = @import("rerank.zig"); +const strip = @import("reply_text.zig").pyStrip; +const Server = @import("server.zig").Server; +const Conn = @import("http_conn.zig").Conn; +const Value = json.Value; +const Cx = errors.Cx; + +/// The routes this file answers: the pair-score aliases, both rerank aliases and Cohere's v2 path. +pub fn route(path: []const u8) bool { + for ([_][]const u8{ "/score", "/v1/score", "/rerank", "/v1/rerank", "/v2/rerank" }) |p| if (std.mem.eql(u8, path, p)) return true; + return false; +} + +/// The HTTP reply for every `route`, the legacy /rerank body included: one reader, one envelope. +pub fn post(srv: *Server, conn: *Conn, a: std.mem.Allocator) void { + var cx: Cx = .{ .a = a }; + const body = @import("http_body.zig").readJson(conn, &cx) catch |err| { + if (err == error.OutOfMemory) oom(&cx); + return sendError(conn, &cx); + }; + const Gone = struct { + conn: *Conn, + pub fn check(g: @This()) bool { + return g.conn.peerGone(); + } + }; + const out = reply(srv, &cx, @import("auth.zig").routePath(conn.path), body, Gone{ .conn = conn }) catch |err| { + if (err == error.Cancelled) { + conn.close = true; + return; + } + if (err == error.OutOfMemory) oom(&cx); + return sendError(conn, &cx); + }; + conn.sendJson(200, rerank.encode(a, out) catch return); +} +fn oom(cx: *Cx) void { + cx.kind = .server; + cx.message = "out of memory"; +} +fn sendError(conn: *Conn, cx: *Cx) void { + const body = rerank.errorBody(cx) catch return; + conn.sendJson(cx.status(), rerank.encode(cx.a, body) catch return); +} + +/// `path`'s shape as rerank.zig's request, its scores read back unchanged into that shape's response. +pub fn reply(srv: *Server, cx: *Cx, path: []const u8, body: Value, gone: anytype) rerank.Failure!Value { + const score = std.mem.eql(u8, path, "/score") or std.mem.eql(u8, path, "/v1/score"); + const cohere = std.mem.eql(u8, path, "/v2/rerank"); + const tei = !score and !cohere and body.has("texts") and !body.has("documents"); + if (!score and !cohere and !tei) return rerank.reply(srv, cx, body, gone); + if (srv.info.rerank == null) return cx.refuse("this model is not a reranker"); + if (srv.engine.vtable.score == null and srv.engine.vtable.decide == null) return cx.refuse("this engine does not score labels"); + if (body != .object) return cx.refuse("body must be a JSON object"); + if (body.field("model")) |model| { + if (model != .string) return cx.refuse("model must be a string"); + var found = false; + for (srv.config.model_ids) |id| found = found or std.mem.eql(u8, id, model.string); + if (!found) return cx.refuse("model is not served here"); + } + for ([_][]const u8{ "rank_fields", "max_tokens_per_doc", "priority" }) |name| if (body.has(name)) + return cx.fail(.request, "{s} is not supported", .{name}); + if (score) return scores(srv, cx, body, gone); + const key: []const u8 = if (tei) "texts" else "documents"; + const docs = body.get(key) orelse return cx.fail(.request, "{s} is required", .{key}); + if (docs != .array or docs.array.len == 0) return cx.fail(.request, "{s} must be a non-empty list", .{key}); + const query = body.get("query") orelse return cx.refuse("query is required"); + _ = try string(cx, query, "query"); + for (docs.array) |doc| { + if (tei or doc != .object) { + _ = try string(cx, doc, key); + } else { + _ = try string(cx, doc.get("text") orelse return cx.refuse("documents: text is required"), "documents.text"); + } + } + const count = try topN(cx, body, docs.array.len); + const returned = if (tei and body.field("return_text") != null) try flag(cx, body, "return_text", false) else try flag(cx, body, "return_documents", false); + const raw = if (tei) try flag(cx, body, "raw_scores", false) else false; + if (cohere and body.has("raw_scores")) return cx.refuse("raw_scores is only supported by the TEI texts shape"); + const truncate = if (tei) try flag(cx, body, "truncate", false) else true; + if (body.field("truncation_direction")) |direction| { + if (direction != .string or !(std.mem.eql(u8, direction.string, "Right") or std.mem.eql(u8, direction.string, "right"))) + return cx.refuse("truncation_direction: only Right is supported"); + } + const normalized = try request(cx, body, query, docs, raw); + const ranked = try rerank.replyOptions(srv, cx, normalized, gone, truncate); + const rows = ranked.get("results").?.array; + const translated = try cx.a.alloc(Value, rows.len); + for (rows, translated) |row, *item| { + const out = try json.newObject(cx.a); + try out.put(cx.a, "index", row.get("index").?); + const probability = row.get("relevance_score").?; + const value: Value = if (raw) blk: { + const meta = row.get("meta_info").?; + const difference = number(meta.get("logit_yes").?) - number(meta.get("logit_no").?); + if (!std.math.isFinite(difference)) return cx.fail(.server, "rerank inference failed", .{}); + break :blk .{ .float = difference }; + } else probability; + try out.put(cx.a, if (tei) "score" else "relevance_score", value); + if (returned) { + const document = docs.array[@intCast(row.get("index").?.int64().?)]; + if (tei) try out.put(cx.a, "text", document) else { + const wrapped = if (document == .object) document else blk: { + const d = try json.newObject(cx.a); + try d.put(cx.a, "text", document); + break :blk Value{ .object = d }; + }; + try out.put(cx.a, "document", wrapped); + } + } + item.* = .{ .object = out }; + } + if (raw) std.sort.insertion(Value, translated, {}, struct { + fn before(_: void, x: Value, y: Value) bool { + return number(x.get("score").?) > number(y.get("score").?); + } + }.before); + if (tei) return .{ .array = translated[0..count] }; + const out = try json.newObject(cx.a); + try out.put(cx.a, "id", .{ .string = try responseId(srv, cx, "rerank") }); + try out.put(cx.a, "results", .{ .array = translated[0..count] }); + const version = try json.newObject(cx.a); + try version.put(cx.a, "version", .{ .string = "2" }); + const meta = try json.newObject(cx.a); + try meta.put(cx.a, "api_version", .{ .object = version }); + try out.put(cx.a, "meta", .{ .object = meta }); + return .{ .object = out }; +} + +fn string(cx: *Cx, value: Value, name: []const u8) errors.Refused![]const u8 { + if (value != .string or strip(value.string).len == 0) return cx.fail(.request, "{s} must be a non-empty string", .{name}); + return value.string; +} +fn flag(cx: *Cx, body: Value, name: []const u8, default: bool) errors.Refused!bool { + const value = body.field(name) orelse return default; // TEI's truncate is nullable: null keeps the default + return if (value == .bool) value.bool else cx.fail(.request, "{s} must be a boolean", .{name}); +} +fn topN(cx: *Cx, body: Value, maximum: usize) errors.Refused!usize { + const value = body.field("top_n") orelse return maximum; + if (value != .int or value.int[0] == '-') return cx.refuse("top_n must be a positive integer"); + // a positive integer past usize still asks for every result, as rerank.zig reads it + const n = std.fmt.parseInt(usize, value.int, 10) catch maximum; + if (n == 0) return cx.refuse("top_n must be a positive integer"); + return @min(maximum, n); +} +fn number(v: Value) f64 { + return if (v == .float) v.float else @floatFromInt(v.int64().?); +} +fn responseId(srv: *Server, cx: *Cx, prefix: []const u8) ![]const u8 { + return std.fmt.allocPrint(cx.a, "{s}-{d}", .{ prefix, srv.next_id.fetchAdd(1, .monotonic) }); +} +/// rerank.zig's body for one query; document text is returned from the request itself, so rerank.zig sends none. +fn request(cx: *Cx, body: Value, query: Value, documents: Value, raw: bool) errors.Refused!Value { + const out = try json.newObject(cx.a); + try out.put(cx.a, "query", query); + try out.put(cx.a, "documents", documents); + try out.put(cx.a, "return_documents", .{ .bool = false }); + try out.put(cx.a, "return_logits", .{ .bool = raw }); + for ([_][]const u8{ "instruction", "instruct", "max_length" }) |key| if (body.get(key)) |value| try out.put(cx.a, key, value); + if (body.field("truncate_prompt_tokens")) |value| { + if (body.field("max_length") != null) return cx.refuse("max_length and truncate_prompt_tokens cannot both be set"); + if (value != .int or value.int64() == null or value.int64().? <= 0) return cx.refuse("truncate_prompt_tokens must be a positive integer"); + try out.put(cx.a, "max_length", value); + } + return .{ .object = out }; +} +fn strings(cx: *Cx, body: Value, key: []const u8) errors.Refused![]const Value { + const value = body.get(key) orelse return cx.fail(.request, "{s} is required", .{key}); + if (value == .string) { + _ = try string(cx, value, key); + return cx.a.dupe(Value, &.{value}); + } + if (value != .array or value.array.len == 0) return cx.fail(.request, "{s} must be a string or non-empty list", .{key}); + for (value.array) |v| _ = try string(cx, v, key); + return value.array; +} +/// vLLM's pair scores: one query's documents as one rerank.zig request, else one a pair, every pair checked first. +fn scores(srv: *Server, cx: *Cx, body: Value, gone: anytype) rerank.Failure!Value { + for ([_][]const u8{ "top_n", "return_documents", "return_text", "raw_scores" }) |key| if (body.has(key)) + return cx.fail(.request, "{s} is only supported by rerank requests", .{key}); + const left = try strings(cx, body, "text_1"); + const right = try strings(cx, body, "text_2"); + if (left.len != right.len and left.len != 1 and right.len != 1) return cx.refuse("text_1 and text_2 lists must have equal lengths or one item to broadcast"); + const n = @max(left.len, right.len); + const truncate = body.field("truncate_prompt_tokens") != null; + const data = try cx.a.alloc(Value, n); + var tokens: i64 = 0; + if (left.len == 1) { + const documents = try cx.a.dupe(Value, right); + const normalized = try request(cx, body, left[0], .{ .array = documents }, false); + const scored = try rerank.replyOptions(srv, cx, normalized, gone, truncate); + tokens = scored.get("usage").?.get("total_tokens").?.int64().?; + for (scored.get("results").?.array) |row| { + const i: usize = @intCast(row.get("index").?.int64().?); + data[i] = try scoreItem(cx, i, row.get("relevance_score").?); + } + } else { + const asks = try cx.a.alloc(Value, n); + for (asks, 0..) |*ask, i| { + if (gone.check()) return error.Cancelled; + const doc = right[if (right.len == 1) 0 else i]; + ask.* = try request(cx, body, left[i], .{ .array = try cx.a.dupe(Value, &.{doc}) }, false); + try rerank.validate(srv, cx, ask.*, truncate); + } + for (asks, data, 0..) |ask, *item, i| { + const scored = try rerank.replyOptions(srv, cx, ask, gone, truncate); + tokens += scored.get("usage").?.get("total_tokens").?.int64().?; + item.* = try scoreItem(cx, i, scored.get("results").?.array[0].get("relevance_score").?); + } + } + const usage = try json.newObject(cx.a); + try usage.put(cx.a, "prompt_tokens", try json.intValue(cx.a, tokens)); + try usage.put(cx.a, "completion_tokens", try json.intValue(cx.a, 0)); + try usage.put(cx.a, "total_tokens", try json.intValue(cx.a, tokens)); + const out = try json.newObject(cx.a); + try out.put(cx.a, "id", .{ .string = try responseId(srv, cx, "score") }); + try out.put(cx.a, "object", .{ .string = "list" }); + try out.put(cx.a, "created", try json.intValue(cx.a, std.Io.Clock.real.now(srv.io).toSeconds())); + try out.put(cx.a, "model", .{ .string = srv.config.served_name }); + try out.put(cx.a, "data", .{ .array = data }); + try out.put(cx.a, "usage", .{ .object = usage }); + return .{ .object = out }; +} + +fn scoreItem(cx: *Cx, index: usize, score: Value) errors.Refused!Value { + const row = try json.newObject(cx.a); + try row.put(cx.a, "index", try json.intValue(cx.a, index)); + try row.put(cx.a, "object", .{ .string = "score" }); + try row.put(cx.a, "score", score); + return .{ .object = row }; +} diff --git a/zig/src/server/score_routes_test.zig b/zig/src/server/score_routes_test.zig new file mode 100644 index 00000000000..84405e8f666 --- /dev/null +++ b/zig/src/server/score_routes_test.zig @@ -0,0 +1,288 @@ +//! Compatibility score/rerank requests through the real server dispatcher and existing fake score hook. +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const shapes = @import("score_routes.zig"); +const legacy = @import("rerank.zig"); +const fixtures = @import("rerank_test.zig"); +const Server = @import("server.zig").Server; +const t = std.testing; + +fn ask(srv: *Server, a: std.mem.Allocator, path: []const u8, body: []const u8) !json.Value { + var cx: errors.Cx = .{ .a = a }; + return shapes.reply(srv, &cx, path, (try json.parse(a, body)).ok, fixtures.Present{}); +} +fn index(row: json.Value) i64 { + return row.get("index").?.int64().?; +} +fn value(v: json.Value) f64 { + return if (v == .float) v.float else @floatFromInt(v.int64().?); +} + +const Fixture = struct { + text: fixtures.Text = .{}, + scorer: fixtures.Scorer = .{ .gpa = t.allocator, .table = &fixtures.table }, + pub fn open(f: *Fixture) !*Server { + return fixtures.serve(&f.text, &f.scorer); + } + pub fn deinit(f: *Fixture) void { + f.scorer.deinit(); + } +}; + +test "score shapes: pair scores keep request order, broadcast both sides and report usage" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const out = try ask(srv, a, "/score", "{\"model\":\"m\",\"text_1\":\"q\",\"text_2\":[\"low\",\"high\",\"mid\"]}"); + const rows = out.get("data").?.array; + try t.expectEqual(@as(usize, 3), rows.len); + for (rows, 0..) |row, i| { + try t.expectEqual(@as(i64, @intCast(i)), index(row)); + try t.expectEqualStrings("score", row.get("object").?.string); + } + try t.expect(value(rows[0].get("score").?) < value(rows[1].get("score").?)); + try t.expectEqualStrings("list", out.get("object").?.string); + try t.expectEqualStrings("m", out.get("model").?.string); + try t.expect(out.get("created").?.int64().? > 0); + try t.expect(out.get("usage").?.get("total_tokens").?.int64().? > 0); + try t.expectEqual(@as(i64, 0), out.get("usage").?.get("completion_tokens").?.int64().?); + const paired = try ask(srv, a, "/v1/score", "{\"text_1\":[\"q1\",\"q2\"],\"text_2\":[\"high\",\"low\"]}"); + try t.expectEqual(@as(usize, 2), paired.get("data").?.array.len); + try t.expect(std.mem.indexOf(u8, f.scorer.prompts.items[3], "|Q:q1|D:high") != null); + const broadcast = try ask(srv, a, "/score", "{\"text_1\":[\"q1\",\"q2\"],\"text_2\":\"mid\"}"); + try t.expectEqual(@as(usize, 2), broadcast.get("data").?.array.len); +} + +test "score shapes: every shape returns the legacy route's scores, order and label logits exactly" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: errors.Cx = .{ .a = a }; + const docs = "[\"mid\",\"low\",\"tie\",\"high\"]"; + const body = try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"documents\":{s},\"return_logits\":true}}", .{docs}); + const old = (try legacy.reply(srv, &cx, (try json.parse(a, body)).ok, fixtures.Present{})).get("results").?.array; + const tei = (try ask(srv, a, "/rerank", try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"texts\":{s}}}", .{docs}))).array; + const raw = (try ask(srv, a, "/rerank", try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"texts\":{s},\"raw_scores\":true}}", .{docs}))).array; + const cohere = (try ask(srv, a, "/v2/rerank", try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"documents\":{s}}}", .{docs}))).get("results").?.array; + const one = (try ask(srv, a, "/score", try std.fmt.allocPrint(a, "{{\"text_1\":\"q\",\"text_2\":{s}}}", .{docs}))).get("data").?.array; + const pairs = (try ask(srv, a, "/v1/score", try std.fmt.allocPrint(a, "{{\"text_1\":[\"q\",\"q\",\"q\",\"q\"],\"text_2\":{s}}}", .{docs}))).get("data").?.array; + for ([_][]const json.Value{ tei, raw, cohere }) |rows| try t.expectEqual(old.len, rows.len); + for (old, tei, raw, cohere) |want, x, r, c| { + const i: usize = @intCast(index(want)); + const score = want.get("relevance_score").?.float; + const meta = want.get("meta_info").?; + try t.expectEqual(index(want), index(x)); + try t.expectEqual(index(want), index(r)); + try t.expectEqual(index(want), index(c)); + try t.expectEqual(score, value(x.get("score").?)); + try t.expectEqual(score, value(c.get("relevance_score").?)); + try t.expectEqual(meta.get("logit_yes").?.float - meta.get("logit_no").?.float, value(r.get("score").?)); + try t.expectEqual(score, value(one[i].get("score").?)); + try t.expectEqual(score, value(pairs[i].get("score").?)); + } +} + +test "score shapes: TEI ranks stably, applies top_n and returns text only when requested" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const out = try ask(srv, a, "/rerank", "{\"query\":\"q\",\"texts\":[\"mid\",\"high\",\"tie\",\"low\"],\"top_n\":3,\"return_text\":true}"); + try t.expect(out == .array); + try t.expectEqual(@as(usize, 3), out.array.len); + try t.expectEqual(@as(i64, 1), index(out.array[0])); + try t.expectEqual(@as(i64, 0), index(out.array[1])); + try t.expectEqual(@as(i64, 2), index(out.array[2])); + try t.expectEqualStrings("high", out.array[0].get("text").?.string); + try t.expect(out.array[0].get("relevance_score") == null); + const plain = try ask(srv, a, "/v1/rerank", "{\"query\":\"q\",\"texts\":[\"low\",\"high\"],\"top_n\":9}"); + try t.expectEqual(@as(usize, 2), plain.array.len); + try t.expect(plain.array[0].get("text") == null); + const alias = try ask(srv, a, "/rerank", "{\"query\":\"q\",\"texts\":[\"high\"],\"return_documents\":true}"); + try t.expectEqualStrings("high", alias.array[0].get("text").?.string); + const past = try ask(srv, a, "/rerank", "{\"query\":\"q\",\"texts\":[\"low\",\"high\"],\"top_n\":92233720368547758080}"); + try t.expectEqual(@as(usize, 2), past.array.len); + const nulls = try ask(srv, a, "/rerank", "{\"query\":\"q\",\"texts\":[\"high\"],\"truncate\":null,\"truncation_direction\":null,\"return_text\":null}"); + try t.expect(nulls.array[0].get("text") == null); +} + +test "score shapes: raw TEI scores sort before top_n even when sigmoid scores saturate" { + const saturated = .{ .{ "x", 1000.0, 0.0 }, .{ "y", 2000.0, 0.0 } }; + var f: Fixture = .{}; + f.scorer.table = &saturated; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const out = try ask(srv, arena.allocator(), "/rerank", "{\"query\":\"q\",\"texts\":[\"x\",\"y\"],\"raw_scores\":true,\"top_n\":1}"); + try t.expectEqual(@as(i64, 1), index(out.array[0])); + try t.expectEqual(@as(f64, 2000), value(out.array[0].get("score").?)); +} + +test "score shapes: Cohere wraps string documents and preserves supplied document objects" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const out = try ask(srv, a, "/v2/rerank", "{\"query\":\"q\",\"documents\":[\"low\",{\"text\":\"high\",\"title\":\"kept\"},\"mid\"],\"top_n\":2,\"return_documents\":true}"); + const rows = out.get("results").?.array; + try t.expectEqual(@as(usize, 2), rows.len); + try t.expectEqual(@as(i64, 1), index(rows[0])); + try t.expectEqualStrings("kept", rows[0].get("document").?.get("title").?.string); + try t.expectEqualStrings("mid", rows[1].get("document").?.get("text").?.string); + try t.expect(std.mem.startsWith(u8, out.get("id").?.string, "rerank-")); + try t.expectEqualStrings("2", out.get("meta").?.get("api_version").?.get("version").?.string); + const omitted = try ask(srv, a, "/v2/rerank", "{\"query\":\"q\",\"documents\":[\"high\"]}"); + try t.expect(omitted.get("results").?.array[0].get("document") == null); +} + +test "score shapes: malformed fields and all score-pair bounds refuse before inference" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_]struct { path: []const u8, body: []const u8, message: []const u8 }{ + .{ .path = "/score", .body = "{\"text_1\":[\"q\",\"r\"],\"text_2\":[\"low\",\"mid\",\"high\"]}", .message = "equal lengths" }, + .{ .path = "/score", .body = "{\"text_1\":\"q\",\"text_2\":[\"low\",3]}", .message = "text_2" }, + .{ .path = "/score", .body = "{\"text_1\":\"q\",\"text_2\":\"high\",\"top_n\":1}", .message = "top_n" }, + .{ .path = "/score", .body = "{\"model\":\"other\",\"text_1\":\"q\",\"text_2\":\"high\"}", .message = "not served" }, + .{ .path = "/rerank", .body = "{\"query\":\"q\",\"texts\":[]}", .message = "texts" }, + .{ .path = "/rerank", .body = "{\"query\":\"q\",\"texts\":[\"high\"],\"top_n\":0}", .message = "top_n" }, + .{ .path = "/rerank", .body = "{\"query\":\"q\",\"texts\":[\"high\"],\"return_text\":1}", .message = "return_text" }, + .{ .path = "/rerank", .body = "{\"query\":\"q\",\"texts\":[\"high\"],\"truncation_direction\":\"Left\"}", .message = "Right" }, + .{ .path = "/v2/rerank", .body = "{\"query\":\"q\",\"documents\":[{}]}", .message = "text" }, + .{ .path = "/v2/rerank", .body = "{\"query\":\"q\",\"documents\":[\"high\"],\"return_documents\":\"yes\"}", .message = "return_documents" }, + .{ .path = "/v2/rerank", .body = "{\"query\":\"q\",\"documents\":[\"high\"],\"max_tokens_per_doc\":32}", .message = "max_tokens_per_doc" }, + }; + for (cases) |c| { + var cx: errors.Cx = .{ .a = a }; + try t.expectError(error.Refused, shapes.reply(srv, &cx, c.path, (try json.parse(a, c.body)).ok, fixtures.Present{})); + try t.expectEqual(@as(u16, 400), cx.status()); + try t.expect(std.mem.indexOf(u8, cx.message, c.message) != null); + try t.expectEqual(@as(usize, 0), f.scorer.prompts.items.len); + } + srv.info.context_window = 32; + const long = try a.alloc(u8, 100); + @memset(long, 'x'); + const body = try std.fmt.allocPrint(a, "{{\"text_1\":\"q\",\"text_2\":[\"low\",\"{s}\"]}}", .{long}); + var cx: errors.Cx = .{ .a = a }; + try t.expectError(error.Refused, shapes.reply(srv, &cx, "/score", (try json.parse(a, body)).ok, fixtures.Present{})); + try t.expectEqual(@as(usize, 0), f.scorer.prompts.items.len); + const pairs = try std.fmt.allocPrint(a, "{{\"text_1\":[\"q\",\"r\"],\"text_2\":[\"low\",\"{s}\"]}}", .{long}); + try t.expectError(error.Refused, shapes.reply(srv, &cx, "/score", (try json.parse(a, pairs)).ok, fixtures.Present{})); + try t.expectEqual(@as(usize, 0), f.scorer.prompts.items.len); +} + +test "score shapes: TEI truncation is explicit and legacy responses stay byte-identical" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const body = (try json.parse(a, "{\"query\":\"q\",\"documents\":[\"low\",\"high\"]}")).ok; + var cx: errors.Cx = .{ .a = a }; + const old = try legacy.reply(srv, &cx, body, fixtures.Present{}); + const translated = try shapes.reply(srv, &cx, "/v1/rerank", body, fixtures.Present{}); + try t.expectEqualStrings(try legacy.encode(a, old), try legacy.encode(a, translated)); + const long = try a.alloc(u8, 100); + @memset(long, 'x'); + const raw = try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"texts\":[\"{s}\"],\"max_length\":40}}", .{long}); + try t.expectError(error.Refused, shapes.reply(srv, &cx, "/rerank", (try json.parse(a, raw)).ok, fixtures.Present{})); + try t.expect(std.mem.indexOf(u8, cx.message, "truncation is disabled") != null); + const permitted = try std.fmt.allocPrint(a, "{{\"query\":\"q\",\"texts\":[\"{s}\"],\"max_length\":40,\"truncate\":true}}", .{long}); + try t.expectEqual(@as(usize, 1), (try ask(srv, a, "/rerank", permitted)).array.len); +} + +test "score shapes: dispatcher and key scopes include all aliases and keep PUT limited" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + const cases = [_][2][]const u8{ + .{ "/score", "{\"text_1\":\"q\",\"text_2\":\"high\"}" }, + .{ "/v1/score", "{\"text_1\":\"q\",\"text_2\":\"high\"}" }, + .{ "/rerank", "{\"query\":\"q\",\"texts\":[\"high\"]}" }, + .{ "/v2/rerank", "{\"query\":\"q\",\"documents\":[\"high\"]}" }, + }; + const scopes = @import("auth_scope.zig"); + for (cases) |c| { + var wire: fixtures.Wire = .{}; + defer wire.bytes.deinit(t.allocator); + try fixtures.dispatch(srv, c[0], c[1], &wire); + try t.expect(std.mem.indexOf(u8, wire.bytes.items, "200 OK") != null); + try t.expect(scopes.allows(.{ .inference = true }, "POST", c[0])); + try t.expect(!scopes.allows(.{ .read = true }, "POST", c[0])); + } + try t.expect(!scopes.allows(.{ .inference = true }, "PUT", "/score")); + try t.expect(!scopes.allows(.{ .inference = true }, "PUT", "/v2/rerank")); + for ([_][]const u8{ "/score", "/v1/score", "/v2/rerank" }) |path| { + var put: fixtures.Wire = .{}; + defer put.bytes.deinit(t.allocator); + try fixtures.dispatchAs(srv, "PUT", path, cases[0][1], &put); + try t.expect(std.mem.indexOf(u8, put.bytes.items, "501") != null); + } + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + var cx: errors.Cx = .{ .a = arena.allocator() }; + const body = (try json.parse(cx.a, cases[0][1])).ok; + srv.info.rerank = null; + try t.expectError(error.Refused, shapes.reply(srv, &cx, "/score", body, fixtures.Present{})); + try t.expectEqualStrings("this model is not a reranker", cx.message); + for (cases) |c| { + var wire: fixtures.Wire = .{}; + defer wire.bytes.deinit(t.allocator); + try fixtures.dispatch(srv, c[0], c[1], &wire); + try t.expect(std.mem.indexOf(u8, wire.bytes.items, "400 Bad Request") != null); + try t.expect(std.mem.indexOf(u8, wire.bytes.items, "this model is not a reranker") != null); + } + srv.info.rerank = .{ .yes = 7, .no = 9 }; + f.scorer.hook = false; + srv.engine = f.scorer.engine(); + for (cases) |c| { + try t.expectError(error.Refused, shapes.reply(srv, &cx, c[0], (try json.parse(cx.a, c[1])).ok, fixtures.Present{})); + try t.expectEqualStrings("this engine does not score labels", cx.message); + } +} + +test "score shapes: a departed client cancels every new shape before scoring" { + var f: Fixture = .{}; + defer f.deinit(); + const srv = try f.open(); + defer srv.deinit(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + var cx: errors.Cx = .{ .a = arena.allocator() }; + const Gone = struct { + pub fn check(_: @This()) bool { + return true; + } + }; + const cases = [_][2][]const u8{ + .{ "/score", "{\"text_1\":\"q\",\"text_2\":\"high\"}" }, + .{ "/rerank", "{\"query\":\"q\",\"texts\":[\"high\"]}" }, + .{ "/v2/rerank", "{\"query\":\"q\",\"documents\":[\"high\"]}" }, + }; + for (cases) |c| try t.expectError(error.Cancelled, shapes.reply(srv, &cx, c[0], (try json.parse(cx.a, c[1])).ok, Gone{})); + try t.expectEqual(@as(usize, 0), f.scorer.prompts.items.len); +} From 2d83ca6fd05e56d519773a784f242ba6feda8a41 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:03:27 +0000 Subject: [PATCH 33/89] Format the inferring route list after the rerank rebase --- zig/src/server/auth_scope.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index cf11447cb1f..d6db0ca0f42 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -65,9 +65,9 @@ const inferring = [_][]const u8{ "/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings", "/v1/images/generations", "/decisions", "/v1/decisions", "/systemone", "/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr", - "/v2/rerank", "/score", "/v1/score", - "/api/chat", "/api/generate", "/api/embed", "/api/show", - "/apply-template", "/v1/apply-template", + "/v2/rerank", "/score", "/v1/score", "/api/chat", + "/api/generate", "/api/embed", "/api/show", "/apply-template", + "/v1/apply-template", }; /// A gated request a key may make: the route as the dispatcher reads it, matched exactly, never by suffix. From 7c63941d94348d21f76157e9b3f445af89a02655 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:39 +0000 Subject: [PATCH 34/89] changelog: #3203 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 529b5d8a35d..a490b39dc75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: a reranker server also answers `/score`, TEI's `/rerank` with `texts` and Cohere's `/v2/rerank`, each translated onto the existing `/v1/rerank` path (#3203). + - Shared decoding: fixed DFlash2 block work stays separate from verification rows; MTP heads keep their step costs and copied rows keep their measured cost feedback (#3755). - Nemotron 3.5 Transcribe on CUDA: the language model loads from the bf16 release as published, with exact bf16 caches and no conversion. The audio encoder runs on the GPU: log-mel, the ASR encoder, the streaming speaker encoder and its cache, fusion and projection. `tf-cuda-test audio-check` writes every encoder stage. Every other Nemotron checkpoint loads as before, and audio input in the server follows in #1632 (#1631). Thanks to @BobClawblaw, and to @cwschroeder for the CI report. From f23f31407e56e1d462cd17325cd800ac55eb4bd5 Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:23:23 +0700 Subject: [PATCH 35/89] Keep device profile integer parsing out of compiler-rt --- zig/src/server/device/profile.zig | 68 +++++++++++++++++++++++++- zig/src/server/device/profile_test.zig | 27 ++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) diff --git a/zig/src/server/device/profile.zig b/zig/src/server/device/profile.zig index 38d69b1c249..8d85b22b2dd 100644 --- a/zig/src/server/device/profile.zig +++ b/zig/src/server/device/profile.zig @@ -37,10 +37,76 @@ pub fn load(a: Allocator, io: std.Io, file: []const u8) ?Doc { } pub fn parse(a: Allocator, bytes: []const u8) ?Doc { - const doc = std.json.parseFromSliceLeaky(Doc, a, bytes, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch return null; + const parsed = std.json.parseFromSlice(std.json.Value, a, bytes, .{ .parse_numbers = false }) catch return null; + defer parsed.deinit(); + const doc = readValue(Doc, a, parsed.value) catch return null; return if (doc.schema == schema) doc else null; } +// The typed integer parser's quad-float fallback pulls compiler-rt's memcpy into the native server. +fn readValue(comptime T: type, a: Allocator, source: std.json.Value) std.json.ParseFromValueError!T { + switch (@typeInfo(T)) { + .int => switch (source) { + .number_string, .string => |raw| return decimalInteger(T, raw), + else => return error.UnexpectedToken, + }, + .optional => |info| { + if (source == .null) return null; + return try readValue(info.child, a, source); + }, + .@"struct" => |info| { + if (source != .object) return error.UnexpectedToken; + var result: T = undefined; + inline for (info.field_names, info.field_types, info.field_attrs) |name, Field, attrs| { + @field(result, name) = if (source.object.get(name)) |v| + try readValue(Field, a, v) + else + attrs.defaultValue(Field) orelse return error.MissingField; + } + return result; + }, + .pointer => |info| { + if (info.size != .slice) @compileError("device profiles only contain slice pointers"); + if (info.child == u8 and source == .string) return a.dupe(u8, source.string); + if (source != .array) return error.UnexpectedToken; + const values = try a.alloc(info.child, source.array.items.len); + for (values, source.array.items) |*out, item| out.* = try readValue(info.child, a, item); + return values; + }, + .bool, .@"enum" => return std.json.innerParseFromValue(T, a, source, .{}), + else => @compileError("unsupported device profile type " ++ @typeName(T)), + } +} + +fn decimalInteger(comptime T: type, raw: []const u8) std.json.ParseFromValueError!T { + if (std.mem.indexOfAny(u8, raw, ".eE") == null) return std.fmt.parseInt(T, raw, 10); + const negative = raw[0] == '-'; + const unsigned = if (negative or raw[0] == '+') raw[1..] else raw; + const split = std.mem.indexOfAny(u8, unsigned, "eE") orelse unsigned.len; + const mantissa = unsigned[0..split]; + const exponent = if (split == unsigned.len) 0 else try std.fmt.parseInt(i64, unsigned[split + 1 ..], 10); + const point = std.mem.indexOfScalar(u8, mantissa, '.') orelse mantissa.len; + const decimal_places: i64 = @intCast(mantissa.len -| (point + 1)); + const significant = std.mem.trimEnd(u8, mantissa, "0"); + const zeros: i64 = @intCast(mantissa.len - significant.len); + var seen_digit = zeros != 0; + var value: T = 0; + for (significant, 0..) |ch, index| { + if (index == point) continue; + if (ch < '0' or ch > '9') return error.InvalidNumber; + seen_digit = true; + value = try std.math.add(T, try std.math.mul(T, value, 10), ch - '0'); + } + if (!seen_digit) return error.InvalidNumber; + if (value == 0) return 0; + if (negative) return error.Overflow; + const places = try std.math.add(i64, exponent, zeros - decimal_places); + if (places < 0) return error.InvalidNumber; + const power = std.math.cast(T, places) orelse return error.Overflow; + const scale = std.math.powi(T, 10, power) catch return error.Overflow; + return std.math.mul(T, value, scale); +} + pub fn write(w: *std.Io.Writer, doc: Doc) !void { try std.json.Stringify.value(doc, .{ .whitespace = .indent_2 }, w); try w.writeByte('\n'); diff --git a/zig/src/server/device/profile_test.zig b/zig/src/server/device/profile_test.zig index 84d6a226056..e59ba49b047 100644 --- a/zig/src/server/device/profile_test.zig +++ b/zig/src/server/device/profile_test.zig @@ -89,6 +89,33 @@ test "device profile: a driver that does not answer keeps the OS's listing and a try t.expectEqual(profile.Scan.full, mac.doc.scan); // sysctl is a Mac's whole story } +test "device profile: exact integer values and nested defaults survive decoding" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = + \\{"schema":1,"scanned_at":"2026-11-13T01:00:00Z","binary_version":"1.2.9", + \\ "fingerprint":"fixture","scan":"full", + \\ "machine":{"os":"linux","arch":"x86_64","ram":18446744073709551615, + \\ "gpus":[{"vendor":"nvidia","name":"Fixture GPU","sm":"12e1"}]}, + \\ "support":{"budget":18446744073709551615.0,"backend":"cuda","gpu":0,"new_field":[1,2]}} + ; + const doc = profile.parse(a, text).?; + try t.expectEqual(std.math.maxInt(u64), doc.machine.ram); + try t.expectEqual(std.math.maxInt(u64), doc.support.budget); + try t.expectEqual(@as(?usize, 0), doc.support.gpu); + try t.expectEqual(@as(u32, 120), doc.machine.gpus[0].sm); + try t.expectEqual(@as(u64, 0), doc.machine.gpus[0].memory); + try t.expectEqual(machine.Source.os, doc.machine.gpus[0].source); + try t.expectEqualStrings("Fixture GPU", doc.machine.gpus[0].name); + try t.expect(doc.support.certain); + for ([_][]const u8{ "-1", "1.5", "18446744073709551616", "1e20" }) |invalid| { + const bad = try std.mem.replaceOwned(u8, a, text, "18446744073709551615.0", invalid); + defer a.free(bad); + try t.expect(profile.parse(a, bad) == null); + } +} + test "device profile: the driver's GPUs replace the OS's NVIDIA entries in ordinal order and keep the rest" { var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); From 54aa7a471df8f0de6f8440f837b230bc0da291a5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:41 +0000 Subject: [PATCH 36/89] changelog: #3761 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a490b39dc75..b21778f0bbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- macOS: the native binary imports `_memcpy` from libSystem again, so the release link check passes; the saved device profile is decoded with checked decimal arithmetic and keeps its format (#3761, fixes #3760). Thanks to @AIFlowML. + - Server: a reranker server also answers `/score`, TEI's `/rerank` with `texts` and Cohere's `/v2/rerank`, each translated onto the existing `/v1/rerank` path (#3203). - Shared decoding: fixed DFlash2 block work stays separate from verification rows; MTP heads keep their step costs and copied rows keep their measured cost feedback (#3755). From fc1d64f416c1b653d1c6361291d1f661d1bc03a9 Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:59:34 +0700 Subject: [PATCH 37/89] Report known zero device memory budgets accurately --- zig/src/server/device/report.zig | 2 +- zig/src/server/device/report_test.zig | 12 +++++++++ zig/src/server/device/support.zig | 9 +++++-- zig/src/server/device/support_test.zig | 36 ++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 3 deletions(-) diff --git a/zig/src/server/device/report.zig b/zig/src/server/device/report.zig index 5c4626aa451..057f39f7f4d 100644 --- a/zig/src/server/device/report.zig +++ b/zig/src/server/device/report.zig @@ -75,7 +75,7 @@ pub fn full(w: *Writer, doc: profile.Doc, s: Support, version: []const u8, fits: try w.writeAll("\n"); for (s.unavailable) |u| try w.print(" Not here: {s}: {s}\n", .{ u.family, u.reason }); for (s.notes) |n| try w.print(" Note: {s}\n", .{n}); - if (s.budget > 0) try w.print(" Memory for model weights: {d:.1} GiB ({s})\n", .{ gibs(s.budget), s.budget_rule }) else try w.print(" Memory for model weights: {s}\n", .{s.budget_rule}); + if (s.budget_known) try w.print(" Memory for model weights: {d:.1} GiB ({s})\n", .{ gibs(s.budget), s.budget_rule }) else try w.print(" Memory for model weights: {s}\n", .{s.budget_rule}); } else try w.print("Not supported by tensorfold-native {s}: {s}\n", .{ version, s.reason }); try w.writeAll(if (fits.len > 0) "Models on disk:\n" else "Models on disk: none in the Hugging Face cache that this build serves\n"); for (fits) |f| { diff --git a/zig/src/server/device/report_test.zig b/zig/src/server/device/report_test.zig index 164948314c6..4bbb6c68e38 100644 --- a/zig/src/server/device/report_test.zig +++ b/zig/src/server/device/report_test.zig @@ -20,6 +20,18 @@ const cuda: support.Offer = .{ .version = "test", .backends = &.{"cuda"}, .famil .{ .model_type = "minimax_m3_vl", .formats = &.{"mlx-q3g64"} }, }, .kernel_sms = &support.release_sms }; +test "device report: a known zero weight budget is printed as a size" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var m = try parse.macos(a, "aarch64", fx.m5_ultra); + m.gpu_wired_limit = metal.margin; + const got = try scan.current(a, t.io, null, m, .{ .version = "test", .offer = metal }, "2026-11-13T01:22:01Z", false, true); + var out: std.Io.Writer.Allocating = .init(a); + try report.full(&out.writer, got.doc, got.support, "test", &.{}); + try t.expect(std.mem.indexOf(u8, out.written(), "Memory for model weights: 0.0 GiB (") != null); +} + fn summary(a: std.mem.Allocator, m: machine.Machine, o: support.Offer) ![]const u8 { var out: std.Io.Writer.Allocating = .init(a); try report.summary(&out.writer, m, try support.derive(a, m, o)); diff --git a/zig/src/server/device/support.zig b/zig/src/server/device/support.zig index f5169ccdb22..cb41a145079 100644 --- a/zig/src/server/device/support.zig +++ b/zig/src/server/device/support.zig @@ -37,8 +37,10 @@ pub const Support = struct { formats: []const []const u8 = &.{}, unavailable: []const Unavailable = &.{}, notes: []const []const u8 = &.{}, - /// Bytes for model weights under the backend's admission rule; 0 when unknown. + /// Bytes for model weights under the backend's admission rule. budget: u64 = 0, + /// Whether the memory inputs needed for the budget were available. + budget_known: bool = false, budget_rule: []const u8 = "", }; @@ -93,6 +95,7 @@ fn metal(a: Allocator, m: Machine, o: Offer) !Support { .unavailable = out.items, .notes = notes.items, .budget = limit -| o.margin, + .budget_known = m.ram > 0, .budget_rule = try std.fmt.allocPrint(a, "the Metal load limit ({d}% of RAM, at most the GPU working set) less a {d} GiB reserve", .{ o.metal_share, o.margin >> 30 }), }; } @@ -148,6 +151,7 @@ fn cuda(a: Allocator, m: Machine, o: Offer) !Support { .unavailable = out.items, .notes = notes.items, .budget = memory -| reserve, + .budget_known = memory > 0, .budget_rule = if (g.unified) "system RAM less the CUDA reserve (a tenth, at least 4 GiB); startup grants what is free then" else "device memory less the CUDA reserve (a 32nd, at least 1 GiB)", }; } @@ -175,6 +179,7 @@ fn vendor(a: Allocator, m: Machine, o: Offer, v: machine.Vendor, name: []const u .formats = try formats(a, o.families, &.{}), .notes = notes.items, .budget = g.memory -| o.margin, + .budget_known = g.memory > 0, .budget_rule = if (g.memory > 0) "device memory less a 2 GiB reserve" else "unknown: the OS lists no device memory for it", }; } @@ -237,7 +242,7 @@ pub fn fit(s: Support, families: []const Family, model_type: []const u8, bytes: if (!has(families, model_type)) return .not_served; if (s.backend == null) return .not_here; for (s.unavailable) |u| if (eql(u.family, model_type)) return .not_here; - if (s.budget > 0 and bytes > s.budget) return .too_large; + if (s.budget_known and bytes > s.budget) return .too_large; return .fits; } diff --git a/zig/src/server/device/support_test.zig b/zig/src/server/device/support_test.zig index df766bb10b3..df2b1f46f92 100644 --- a/zig/src/server/device/support_test.zig +++ b/zig/src/server/device/support_test.zig @@ -180,6 +180,42 @@ test "device support: a checkpoint on disk fits, is too large, does not run here try t.expectEqual(support.Verdict.not_served, support.fit(s, &metal_families, "deepseek_v4", 17 << 30)); } +test "device support: a reserve that exhausts known memory leaves no room for nonempty weights" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var mac = try parse.macos(a, "aarch64", fx.m5_ultra); + mac.gpu_wired_limit = metal.margin; + const constrained = try support.derive(a, mac, metal); + try t.expectEqual(@as(u64, 0), constrained.budget); + try t.expectEqual(support.Verdict.too_large, support.fit(constrained, metal.families, "nemotron_h", 1)); + try t.expectEqual(support.Verdict.fits, support.fit(constrained, metal.families, "nemotron_h", 0)); + + const pc: Machine = .{ .os = .linux, .arch = "x86_64", .ram = 16 << 30 }; + const cuda_cap = try support.derive(a, try driver(pc, a, 86, 1 << 30, false, "NVIDIA GPU"), release); + const cuda_unknown = try support.derive(a, try driver(pc, a, 86, 0, false, "NVIDIA GPU"), release); + try t.expectEqual(@as(u64, 0), cuda_cap.budget); + try t.expectEqual(@as(u64, 0), cuda_unknown.budget); + try t.expectEqual(support.Verdict.too_large, support.fit(cuda_cap, release.families, "nemotron_h", 1)); + try t.expectEqual(support.Verdict.fits, support.fit(cuda_unknown, release.families, "nemotron_h", 1)); + + const vendors = [_]struct { name: []const u8, vendor: machine.Vendor }{ + .{ .name = "hip", .vendor = .amd }, + .{ .name = "xpu", .vendor = .intel }, + }; + for (vendors) |v| { + const offer: support.Offer = .{ .version = "test", .backends = &.{v.name}, .families = &cuda_families }; + var host = pc; + var gpus = [_]machine.Gpu{.{ .vendor = v.vendor, .name = "Fixture GPU", .memory = 1 << 30 }}; + host.gpus = &gpus; + const capped = try support.derive(a, host, offer); + try t.expectEqual(support.Verdict.too_large, support.fit(capped, offer.families, "nemotron_h", 1)); + gpus[0].memory = 0; + const unknown = try support.derive(a, host, offer); + try t.expectEqual(support.Verdict.fits, support.fit(unknown, offer.families, "nemotron_h", 1)); + } +} + test "device support: the assumed release kernel set is the one the release build validates" { const text = try std.Io.Dir.cwd().readFileAlloc(t.io, "zig/build/cuda.zig", t.allocator, .limited(1 << 20)); defer t.allocator.free(text); From 098198d6894e1576fa750f3b6736ac3782da7eb8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:46:42 +0000 Subject: [PATCH 38/89] changelog: #3773 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b21778f0bbe..b156d9c1d7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- `tensorfold device`: when the memory reserve leaves a known zero bytes for weights, a nonempty checkpoint is reported too large and the text report shows 0.0 GiB; unknown memory keeps the old fallback (#3773, fixes #3770). Thanks to @AIFlowML. + - macOS: the native binary imports `_memcpy` from libSystem again, so the release link check passes; the saved device profile is decoded with checked decimal arithmetic and keeps its format (#3761, fixes #3760). Thanks to @AIFlowML. - Server: a reranker server also answers `/score`, TEI's `/rerank` with `texts` and Cohere's `/v2/rerank`, each translated onto the existing `/v1/rerank` path (#3203). From faf3e7acaec9e04e40b49a7a78224866b5fafddb Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:37:10 +0700 Subject: [PATCH 39/89] app: let sandboxed MCP executables load bundled frameworks --- app/electron/agent/mcp-app-bundle.test.ts | 77 +++++++++++++++++++++++ app/electron/agent/mcp-process.ts | 8 +++ 2 files changed, 85 insertions(+) create mode 100644 app/electron/agent/mcp-app-bundle.test.ts diff --git a/app/electron/agent/mcp-app-bundle.test.ts b/app/electron/agent/mcp-app-bundle.test.ts new file mode 100644 index 00000000000..9ca8622e2f1 --- /dev/null +++ b/app/electron/agent/mcp-app-bundle.test.ts @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createMcpServer, mcpSpawnSpec } from './mcp-process' +import { canUseMacSandbox } from './sandbox' + +function main() { + if (process.platform !== 'darwin' || !canUseMacSandbox()) { + console.log('SKIP MCP app bundle: macOS sandbox unavailable') + return + } + const compiler = spawnSync('/usr/bin/xcrun', ['--find', 'clang'], { encoding: 'utf8', timeout: 10_000 }) + const sdk = spawnSync('/usr/bin/xcrun', ['--sdk', 'macosx', '--show-sdk-path'], { encoding: 'utf8', timeout: 10_000 }) + if (compiler.status !== 0 || sdk.status !== 0) { + console.log('SKIP MCP app bundle: Xcode C compiler or macOS SDK unavailable') + return + } + // Use a private home fixture: the sandbox already permits the system temporary directories. + const root = mkdtempSync(path.join(os.homedir(), '.tensorfold-mcp-bundle-test-')) + try { + const cwd = path.join(root, 'workspace') + const contents = path.join(root, 'Fixture With Spaces.app', 'Contents') + const binary = path.join(contents, 'MacOS', 'fixture') + const library = path.join(contents, 'Frameworks', 'libfixture.dylib') + const resource = path.join(contents, 'Resources', 'fixture.txt') + const unrelated = path.join(root, 'Unrelated.app', 'Contents', 'private.txt') + for (const dir of [cwd, path.dirname(binary), path.dirname(library), path.dirname(resource), path.dirname(unrelated)]) { + mkdirSync(dir, { recursive: true }) + } + writeFileSync(resource, 'bundle resource') + writeFileSync(unrelated, 'unrelated data') + const librarySource = path.join(root, 'library.c') + const mainSource = path.join(root, 'main.c') + writeFileSync(librarySource, 'int fixture_value(void) { return 42; }\n') + writeFileSync(mainSource, [ + '#include ', + '#include ', + 'int fixture_value(void);', + 'int main(int argc, char **argv) {', + ' if (argc != 2 || strcmp(argv[1], "argument with spaces")) return 2;', + ' printf("loaded %d\\n", fixture_value());', + ' return 0;', + '}', + ].join('\n')) + for (const args of [ + ['-dynamiclib', librarySource, '-install_name', '@rpath/libfixture.dylib', '-o', library], + [mainSource, '-L', path.dirname(library), '-lfixture', '-Wl,-rpath,@executable_path/../Frameworks', '-o', binary], + ]) { + const built = spawnSync(compiler.stdout.trim(), ['-isysroot', sdk.stdout.trim(), ...args], { + encoding: 'utf8', timeout: 30_000, + }) + assert.equal(built.status, 0, built.stderr || built.error?.message) + } + const config = createMcpServer({ name: 'Bundle fixture', command: binary, args: ['argument with spaces'], cwd }) + const spec = mcpSpawnSpec(config) + assert.equal(spec.sandboxed, true) + const options = { cwd: spec.cwd, env: spec.env, encoding: 'utf8' as const, timeout: 10_000 } + const launched = spawnSync(spec.command, spec.args, options) + assert.equal(launched.status, 0, launched.stderr || launched.error?.message) + assert.equal(launched.stdout, 'loaded 42\n', 'dyld must load the sibling framework without splitting arguments') + + const probe = (script: string, file: string) => spawnSync(spec.command, [ + ...spec.args.slice(0, 2), '/bin/sh', '-c', script, 'fixture', file, + ], options) + assert.equal(probe('cat "$1"', resource).stdout, 'bundle resource') + assert.notEqual(probe('cat "$1"', unrelated).status, 0, 'other application bundles remain unreadable') + assert.notEqual(probe('printf changed > "$1"', resource).status, 0, 'the selected bundle remains read-only') + assert.equal(readFileSync(resource, 'utf8'), 'bundle resource') + console.log('MCP app bundle: framework loading, spaced arguments and sandbox boundaries passed') + } finally { + rmSync(root, { recursive: true, force: true }) + } +} + +main() diff --git a/app/electron/agent/mcp-process.ts b/app/electron/agent/mcp-process.ts index 90ff973a9ef..7ad02ad0b8f 100644 --- a/app/electron/agent/mcp-process.ts +++ b/app/electron/agent/mcp-process.ts @@ -290,6 +290,14 @@ function mcpSandboxReadRoots(config: McpServerConfig, cwd: string): string[] { roots.push(path.dirname(path.isAbsolute(raw) ? raw : path.resolve(cwd, raw))) } add(config.command) + if (process.platform === 'darwin') { + const executableDir = path.dirname(path.resolve(cwd, config.command)) + const contents = path.dirname(executableDir) + if (path.basename(executableDir) === 'MacOS' && path.basename(contents) === 'Contents' + && path.basename(path.dirname(contents)).endsWith('.app')) { + roots.push(contents) + } + } for (const arg of config.args) add(arg) return roots } From 51b01249008fdcbef4d6a8280c8d5bd23c7db9ef Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:56:15 +0700 Subject: [PATCH 40/89] test: verify MCP bundle access is denied for permission reasons --- app/electron/agent/mcp-app-bundle.test.ts | 19 ++++++++++++++++--- app/electron/agent/mcp-process.ts | 1 + 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/app/electron/agent/mcp-app-bundle.test.ts b/app/electron/agent/mcp-app-bundle.test.ts index 9ca8622e2f1..1a3f936d8cc 100644 --- a/app/electron/agent/mcp-app-bundle.test.ts +++ b/app/electron/agent/mcp-app-bundle.test.ts @@ -64,10 +64,23 @@ function main() { const probe = (script: string, file: string) => spawnSync(spec.command, [ ...spec.args.slice(0, 2), '/bin/sh', '-c', script, 'fixture', file, ], options) - assert.equal(probe('cat "$1"', resource).stdout, 'bundle resource') - assert.notEqual(probe('cat "$1"', unrelated).status, 0, 'other application bundles remain unreadable') - assert.notEqual(probe('printf changed > "$1"', resource).status, 0, 'the selected bundle remains read-only') + const assertDenied = (result: ReturnType, message: string) => { + assert.ifError(result.error) + assert.equal(result.signal, null, message) + assert.ok(result.status !== null && result.status !== 0, message) + assert.match(result.stderr, /Operation not permitted|Permission denied/, message) + } + const read = probe('cat "$1"', resource) + assert.equal(read.status, 0, read.stderr) + assert.equal(read.stdout, 'bundle resource') + assertDenied(probe('cat "$1"', unrelated), 'other application bundles remain unreadable') + assertDenied(probe('printf changed > "$1"', resource), 'the selected bundle remains read-only') assert.equal(readFileSync(resource, 'utf8'), 'bundle resource') + const argumentOnly = mcpSpawnSpec(createMcpServer({ command: '/bin/echo', args: [binary], cwd })) + const argumentRead = spawnSync(argumentOnly.command, [ + ...argumentOnly.args.slice(0, 2), '/bin/cat', resource, + ], options) + assertDenied(argumentRead, 'passing a bundle path as an argument does not grant access to its Contents') console.log('MCP app bundle: framework loading, spaced arguments and sandbox boundaries passed') } finally { rmSync(root, { recursive: true, force: true }) diff --git a/app/electron/agent/mcp-process.ts b/app/electron/agent/mcp-process.ts index 7ad02ad0b8f..efa21186871 100644 --- a/app/electron/agent/mcp-process.ts +++ b/app/electron/agent/mcp-process.ts @@ -290,6 +290,7 @@ function mcpSandboxReadRoots(config: McpServerConfig, cwd: string): string[] { roots.push(path.dirname(path.isAbsolute(raw) ? raw : path.resolve(cwd, raw))) } add(config.command) + // dyld resolves bundled frameworks and resources outside Contents/MacOS. if (process.platform === 'darwin') { const executableDir = path.dirname(path.resolve(cwd, config.command)) const contents = path.dirname(executableDir) From 5fa1fae62c99c23d0be9598435ea0678fd1dbc3e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:41:29 +0000 Subject: [PATCH 41/89] changelog: #3423 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b156d9c1d7c..2d4d0d210d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- App: MCP servers bundled inside macOS apps can load their own frameworks; the bundle stays read-only and other app bundles stay out of reach (#3423). Thanks to @AIFlowML. + - `tensorfold device`: when the memory reserve leaves a known zero bytes for weights, a nonempty checkpoint is reported too large and the text report shows 0.0 GiB; unknown memory keeps the old fallback (#3773, fixes #3770). Thanks to @AIFlowML. - macOS: the native binary imports `_memcpy` from libSystem again, so the release link check passes; the saved device profile is decoded with checked decimal arithmetic and keeps its format (#3761, fixes #3760). Thanks to @AIFlowML. From 4275b7a037d80257169fe61c80a208aecab517fb Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:44:31 +0700 Subject: [PATCH 42/89] app: show each Room's worktree and Git branch --- .../rooms/RoomView.attachments.test.tsx | 7 ++ app/src/components/rooms/RoomView.tsx | 2 + .../components/rooms/RoomWorktree.test.tsx | 94 +++++++++++++++++++ app/src/components/rooms/RoomWorktree.tsx | 40 ++++++++ 4 files changed, 143 insertions(+) create mode 100644 app/src/components/rooms/RoomWorktree.test.tsx create mode 100644 app/src/components/rooms/RoomWorktree.tsx diff --git a/app/src/components/rooms/RoomView.attachments.test.tsx b/app/src/components/rooms/RoomView.attachments.test.tsx index c0bf3666ea4..c0101d43c0b 100644 --- a/app/src/components/rooms/RoomView.attachments.test.tsx +++ b/app/src/components/rooms/RoomView.attachments.test.tsx @@ -20,6 +20,7 @@ new Function('require', 'module', 'exports', ts.transpileModule(readFileSync(pat const roomHelpers = helperModule.exports const components = new Proxy({}, { get: (_target, name) => name === '__esModule' ? true : () => null }) const AttachmentChips = () => null +const RoomWorktree = () => null let startCalls: any[] = [], rejectStart = false const store: any = { rooms: ['A', 'B'].map((id) => ({ id, name: id, projectId: 'p', seats: [{ id: 'seat', name: 'Builder', providerId: 'provider', model: 'model' }], events: [], state: 'idle', problem: '', memory: [] })), @@ -40,6 +41,7 @@ const imports: Record = { '../../lib/policy': { allowedProviders: () => [] }, '../../lib/voice': { speakText() {} }, './helpers': roomHelpers, './RoomPanels': components, './RoomGitBanner': components, './RoomTimeline': components, './RoomPlans': components, + './RoomWorktree': { RoomWorktree }, } const loaded = { exports: {} as any } new Function('require', 'module', 'exports', ts.transpileModule(readFileSync(path.join(__dirname, 'RoomView.tsx'), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true } }).outputText)((id: string) => { const reviewed = reviewedLanguageImport(id, imports); if (reviewed.matched) return reviewed.value; assert.ok(id in imports, `Reviewed import ${id}`); return imports[id] }, loaded, loaded.exports) @@ -90,3 +92,8 @@ const removedId = chips(node).props.items[0].id chips(node).props.onRemove(removedId); release?.(); await settle(); node = render() assert.equal(chips(node), undefined) console.log('room files retain independent failures, block incomplete submission, retain failed launch inputs, and reject stale scope/removal completions') + +store.rightPanelHidden = false +store.rooms[0].workspaceCwd = '/workspace/rooms/First room/code' +node = render('A') +assert.equal(all(node, (entry) => entry.type === RoomWorktree)[0]?.props.room.id, 'A', 'Room health must expose the open room worktree') diff --git a/app/src/components/rooms/RoomView.tsx b/app/src/components/rooms/RoomView.tsx index 18dda1756f9..9a96b2e03c6 100644 --- a/app/src/components/rooms/RoomView.tsx +++ b/app/src/components/rooms/RoomView.tsx @@ -30,6 +30,7 @@ import { } from './helpers' import { RoomAgentsSection, RoomCanvas, RoomFlowTicker, RoomStatePill, RoomStat, RoomSupervisorPanel, RoomTicketQueue } from './RoomPanels' import { RoomGitBanner } from './RoomGitBanner' +import { RoomWorktree } from './RoomWorktree' import { RoomTimeline, RoomHandoffStrip } from './RoomTimeline' import { RoomFinalGatePanel, RoomHandoffQueuePanel, RoomLivePlanPanel, RoomModePresets } from './RoomPlans' @@ -356,6 +357,7 @@ export function RoomView({ id }: { id: string }) { 0} /> + diff --git a/app/src/components/rooms/RoomWorktree.test.tsx b/app/src/components/rooms/RoomWorktree.test.tsx new file mode 100644 index 00000000000..6cf242533b3 --- /dev/null +++ b/app/src/components/rooms/RoomWorktree.test.tsx @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import React from 'react' +import ts from 'typescript' +import { fixtureText, reviewedLanguageImport } from '../preferences/language-test-fixture' + +let state: any, effect: { deps: unknown[]; cleanup?: () => void } | undefined +let pendingEffect: (() => void) | undefined +const requests: Array<{ cwd: string; workspace: unknown; resolve: (branch: string | null) => void; reject: (error: Error) => void }> = [] +const jsx = { jsx: React.createElement, jsxs: React.createElement, Fragment: React.Fragment } +const imports: Record = { + react: { + useState: () => [state, (next: unknown) => { state = next }], + useEffect: (run: () => void | (() => void), deps: unknown[]) => { + if (!effect || deps.some((value, index) => value !== effect!.deps[index])) pendingEffect = () => { + effect?.cleanup?.() + const cleanup = run() + effect = { deps, ...(cleanup ? { cleanup } : {}) } + } + }, + }, + 'react/jsx-runtime': { + ...jsx, + jsx: (type: any, props: any) => React.createElement(type, props), + jsxs: (type: any, props: any) => React.createElement(type, props), + }, + '../../lib/preferences/useAuthoredText': { useAuthoredText: () => fixtureText }, + '../../lib/icons': { Icon: () => null }, + '../../lib/ipc': { api: { getBranch: (cwd: string, workspace: unknown) => new Promise((resolve, reject) => { + requests.push({ cwd, workspace, resolve, reject }) + }) } }, +} +const loaded = { exports: {} as any } +const source = ts.transpileModule(readFileSync(path.join(__dirname, 'RoomWorktree.tsx'), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true }, +}).outputText +new Function('require', 'module', 'exports', source)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed import ${id}`) + return imports[id] +}, loaded, loaded.exports) + +const room = (id: string, cwd: string | null, extra: Record = {}) => ({ id, workspaceCwd: cwd, state: 'idle', ...extra }) +function render(value: ReturnType) { + const node = loaded.exports.RoomWorktree({ room: value }) + pendingEffect?.() + pendingEffect = undefined + return node +} +function text(node: any): string { + if (typeof node === 'string' || typeof node === 'number') return String(node) + if (!node || typeof node !== 'object') return '' + return React.Children.toArray(node.props?.children).map(text).join(' ') +} +async function settle() { for (let i = 0; i < 4; i++) await Promise.resolve() } + +assert.equal(render(room('new', null)), null, 'an unstarted room must not invent a worktree') +assert.equal(requests.length, 0) +const first = room('first', '/workspace/rooms/First room/code') +assert.match(text(render(first)), /First room\/code/, 'the actual worktree path is accessible while the branch loads') +assert.match(text(render(first)), /Workspace/, 'the label uses an existing translated source string') +assert.equal(requests.at(-1)?.cwd, first.workspaceCwd) +requests.at(-1)!.resolve('vontra/room-first123') +await settle() +assert.match(text(render(first)), /vontra\/room-first123/) + +const second = room('second', '/workspace/rooms/Second room/code') +assert.doesNotMatch(text(render(second)), /first123/, 'navigation immediately hides the previous branch') +const secondRequest = requests.at(-1)! +const third = room('third', '/workspace/rooms/Third room/code') +render(third) +secondRequest.resolve('vontra/room-second12') +await settle() +assert.doesNotMatch(text(render(third)), /second12/, 'late results cannot cross room boundaries') +requests.at(-1)!.reject(new Error('Git unavailable')) +await settle() +assert.match(text(render(third)), /Third room\/code/) +assert.doesNotMatch(text(render(third)), /vontra\/room-/, 'a failed lookup must not fabricate a branch') + +const ssh = room('ssh', '/remote/rooms/Remote room/code', { workspace: { kind: 'ssh', hostId: 'example-host', path: '/remote/project' } }) +render(ssh) +assert.deepEqual(requests.at(-1)?.workspace, { kind: 'ssh', hostId: 'example-host', path: ssh.workspaceCwd }) +requests.at(-1)!.resolve(null) +await settle() +assert.doesNotMatch(text(render(ssh)), /vontra\/room-/, 'a detached or unknown branch must not be guessed') + +const beforeRemote = requests.length +const projected = room('projected', '/remote/rooms/Projected room/code', { orchestratorHostId: 'example-orchestrator' }) +assert.match(text(render(projected)), /Projected room\/code/) +assert.equal(requests.length, beforeRemote, 'a projected remote path must never be inspected on the local host') +effect?.cleanup?.() +console.log('Room worktree identity: actual branch/path, navigation, stale replies, errors, SSH and projected rooms passed') diff --git a/app/src/components/rooms/RoomWorktree.tsx b/app/src/components/rooms/RoomWorktree.tsx new file mode 100644 index 00000000000..162b13e392e --- /dev/null +++ b/app/src/components/rooms/RoomWorktree.tsx @@ -0,0 +1,40 @@ +import { useEffect, useState } from 'react' +import { Icon } from '../../lib/icons' +import { api } from '../../lib/ipc' +import { useAuthoredText } from '../../lib/preferences/useAuthoredText' +import type { Room } from '../../lib/types' + +type WorktreeRoom = Pick + +export function RoomWorktree({ room }: { room: WorktreeRoom }) { + const tx = useAuthoredText() + const cwd = room.workspaceCwd?.trim() || null + const kind = room.workspace?.kind + const hostId = room.workspace?.hostId + const origin = room.orchestratorHostId + const scope = JSON.stringify([room.id, cwd, kind, hostId, origin]) + const [branch, setBranch] = useState<{ scope: string; name: string | null } | null>(null) + + useEffect(() => { + if (!cwd || origin) return + let current = true + const workspace = kind ? { kind, hostId, path: cwd } : null + api.getBranch(cwd, workspace) + .then((name) => { if (current) setBranch({ scope, name: name?.trim() || null }) }) + .catch(() => { if (current) setBranch({ scope, name: null }) }) + return () => { current = false } + }, [cwd, kind, hostId, origin, scope, room.state]) + + if (!cwd) return null + const name = branch?.scope === scope ? branch.name : null + return ( +
+
+ + {tx('Workspace')} +
+ {name &&
{name}
} +
{cwd}
+
+ ) +} From a3bfff2a2e970636ac2d677973c258e85cbfd131 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:41:30 +0000 Subject: [PATCH 43/89] changelog: #3463 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d4d0d210d5..a117b67031a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- App: Room health shows each Room's worktree path and its Git branch (#3463). Thanks to @AIFlowML. + - App: MCP servers bundled inside macOS apps can load their own frameworks; the bundle stays read-only and other app bundles stay out of reach (#3423). Thanks to @AIFlowML. - `tensorfold device`: when the memory reserve leaves a known zero bytes for weights, a nonempty checkpoint is reported too large and the text report shows 0.0 GiB; unknown memory keeps the old fallback (#3773, fixes #3770). Thanks to @AIFlowML. From 0f764361c64cbfb894faffeed84c5358b19a0ff2 Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:11:31 +0700 Subject: [PATCH 44/89] app: edit Kanban ticket details and restore archived cards --- .../components/Board.ticket-details.test.tsx | 51 ++++++++ app/src/components/Board.tsx | 5 +- .../components/board/TicketDetails.test.tsx | 101 ++++++++++++++++ app/src/components/board/TicketDetails.tsx | 110 ++++++++++++++++++ app/src/lib/ticket-details.test.ts | 27 +++++ app/src/lib/ticket-details.ts | 21 ++++ 6 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 app/src/components/Board.ticket-details.test.tsx create mode 100644 app/src/components/board/TicketDetails.test.tsx create mode 100644 app/src/components/board/TicketDetails.tsx create mode 100644 app/src/lib/ticket-details.test.ts create mode 100644 app/src/lib/ticket-details.ts diff --git a/app/src/components/Board.ticket-details.test.tsx b/app/src/components/Board.ticket-details.test.tsx new file mode 100644 index 00000000000..0460d449014 --- /dev/null +++ b/app/src/components/Board.ticket-details.test.tsx @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import React from 'react' +import ts from 'typescript' +import { fixtureText, reviewedLanguageImport } from './preferences/language-test-fixture' + +const TicketDetailsButton = () => null, TicketArchiveButton = () => null +const opened: string[] = [] +const ticket: any = { id: 'ticket', projectId: 'project', title: 'Full details', body: 'Untruncated text', type: 'task', priority: 'medium', effort: 'small', status: 'in_progress', tags: [], threadId: 'chat', order: 0 } +const state: any = { tickets: [ticket], rooms: [], projects: [{ id: 'project', name: 'Synthetic' }], settings: { providers: [] }, openThread: (id: string) => opened.push(id) } +const useStore = Object.assign((select: (value: any) => unknown) => select(state), { getState: () => state }) +const jsx = { jsx: (type: any, props: any) => React.createElement(type, props), jsxs: (type: any, props: any) => React.createElement(type, props), Fragment: React.Fragment } +const imports: Record = { + react: { useState: (initial: unknown) => [typeof initial === 'function' ? initial() : initial, () => {}], useEffect() {}, useMemo: (make: () => unknown) => make() }, + 'react/jsx-runtime': jsx, + clsx: (...values: unknown[]) => values.filter(Boolean).join(' '), + '../lib/preferences/useAuthoredText': { useAuthoredText: () => fixtureText }, + '../lib/preferences/language-packs': { authoredText: (_locale: string, value: string) => fixtureText(value) }, + '../lib/store': { useStore }, + '../lib/icons': { Icon: () => null }, + './ui': { Button: () => null, Menu: () => null, MenuItem: () => null }, + '../lib/policy': { allowedProviders: () => [], projectDefaultModel: () => ({}) }, + '../lib/provider-accounts': { modelDisplayName: (_provider: unknown, value: string) => value, providerModelGroups: () => [] }, + '../../shared/ticket-dependencies': { resolveTicketDependencies: () => ({ state: 'ready' }) }, + './board/TicketDetails': { TicketDetailsButton, TicketArchiveButton }, +} +const loaded = { exports: {} as any } +const output = ts.transpileModule(readFileSync(path.join(__dirname, 'Board.tsx'), 'utf8') + '\nexports.Card = Card;', { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true }, +}).outputText +new Function('require', 'module', 'exports', output)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed Board import ${id}`) + return imports[id] +}, loaded, loaded.exports) + +function find(node: any, type: unknown): any[] { + if (!node || typeof node !== 'object') return [] + return [...(node.type === type ? [node] : []), ...React.Children.toArray(node.props?.children).flatMap((child) => find(child, type))] +} +const card = loaded.exports.Card({ t: ticket, rooms: [], allTickets: [ticket], onDragStart() {}, onRun() {}, onSetMode() {} }) +assert.equal(find(card, TicketDetailsButton).length, 1, 'every card needs an explicit entry point to its full editable details') +assert.equal(find(card, TicketDetailsButton)[0].props.ticket, ticket) +card.props.onClick() +assert.deepEqual(opened, ['chat'], 'existing card navigation to the worker chat remains available') +const board = loaded.exports.Board({ projectId: 'project' }) +assert.equal(find(board, TicketArchiveButton).length, 1, 'the board needs a visible archive entry point') +assert.equal(find(board, TicketArchiveButton)[0].props.projectId, 'project') +console.log('Kanban cards expose details, the board exposes archives, and existing worker-chat navigation is preserved') diff --git a/app/src/components/Board.tsx b/app/src/components/Board.tsx index 7c94b8d2cf7..e7a7599a3d0 100644 --- a/app/src/components/Board.tsx +++ b/app/src/components/Board.tsx @@ -10,6 +10,7 @@ import { allowedProviders, projectDefaultModel } from '../lib/policy' import { modelDisplayName, providerModelGroups } from '../lib/provider-accounts' import type { KanbanPhaseModel, Project, ProjectKanbanSettings, Provider, Room, Ticket, TicketExecutionMode, TicketStatus, TicketWorkOptions } from '../lib/types' import { resolveTicketDependencies } from '../../shared/ticket-dependencies' +import { TicketDetailsButton, TicketArchiveButton } from './board/TicketDetails' const EXEC_MODES: { id: TicketExecutionMode; label: string; icon: IconName; desc: string }[] = [ { id: 'solo', get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Solo") }, icon: 'cpu', get desc() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "One agent on the configured model") } }, @@ -229,7 +230,8 @@ function Card({ className={clsx('group mb-2 rounded-xl border border-line bg-card p-3 shadow-card transition-colors hover:border-line-strong', t.threadId ? 'cursor-pointer' : activeRun ? 'cursor-default' : 'cursor-grab active:cursor-grabbing')} >
-
{t.title}
+
{t.title}
+
{t.body &&

{t.body}

} @@ -452,6 +454,7 @@ export function Board({ projectId }: { projectId: string }) {
+
{modelMode === 'single' ? tx("One model · {value0}", { value0: selectionLabel(singleModel, modelProviders) }) : tx("Phased models · Draft, ticket review, build, work review, final gate")}
diff --git a/app/src/components/board/TicketDetails.test.tsx b/app/src/components/board/TicketDetails.test.tsx new file mode 100644 index 00000000000..af658b1a56d --- /dev/null +++ b/app/src/components/board/TicketDetails.test.tsx @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import React from 'react' +import ts from 'typescript' +import * as edit from '../../lib/ticket-details' +import { fixtureText, reviewedLanguageImport } from '../preferences/language-test-fixture' + +let slots: any[] = [], cursor = 0 +const effects: Array<() => void> = [] +let closed = 0, failLoad = false +const calls: any[][] = [] +let resolve: (() => void) | undefined, reject: ((error: Error) => void) | undefined +const ticket: any = { id: 'ticket', projectId: 'project', title: 'Original', body: 'Full body\n'.repeat(60), type: 'task', priority: 'medium', effort: 'small', runState: null } +const state: any = { + tickets: [ticket], projects: [{ id: 'project' }], archives: { tickets: [] }, + updateTicket: (id: string, patch: unknown) => { calls.push(['save', id, patch]); return new Promise((yes, no) => { resolve = yes; reject = no }) }, + refreshArchives: async () => { if (failLoad) throw new Error('Synthetic archive load failed') }, + restoreItem: (...args: unknown[]) => { calls.push(['restore', ...args]); return new Promise((yes, no) => { resolve = yes; reject = no }) }, +} +const imports: Record = { + react: { + useState: (value: any) => { const index = cursor++; if (!(index in slots)) slots[index] = typeof value === 'function' ? value() : value; return [slots[index], (next: any) => { slots[index] = typeof next === 'function' ? next(slots[index]) : next }] }, + useRef: (value: any) => { const index = cursor++; if (!(index in slots)) slots[index] = { current: value }; return slots[index] }, + useEffect: (run: () => void) => { const index = cursor++; if (!(index in slots)) { slots[index] = true; effects.push(run) } }, + useId: () => 'ticket-dialog', + }, + 'react/jsx-runtime': { jsx: (type: any, props: any) => React.createElement(type, props), jsxs: (type: any, props: any) => React.createElement(type, props), Fragment: React.Fragment }, + 'react-dom': { createPortal: (node: unknown) => node }, + '../../lib/store': { useStore: Object.assign((select: (value: any) => unknown) => select(state), { getState: () => state }) }, + '../../lib/ticket-details': edit, + '../../lib/store/shared/merge': { archiveOriginHostId: (item: any) => item.orchestratorHostId ?? item.orchestratorId ?? null }, + '../../lib/store/shared/proxy-state': { projectedProjectHostId: (project: any) => project.executionTarget === 'orchestrator' ? project.orchestratorId ?? null : null }, + '../../lib/preferences/useAuthoredText': { useAuthoredText: () => fixtureText }, + '../navigation/useAccessibleDialog': { useAccessibleDialog() {} }, + '../../lib/icons': { Icon: () => null }, + '../OriginalDiagnostic': { OriginalDiagnostic: () => null }, +} +const loaded = { exports: {} as any } +const output = ts.transpileModule(readFileSync(path.join(__dirname, 'TicketDetails.tsx'), 'utf8') + '\nexports.TicketEditor = TicketEditor; exports.TicketArchive = TicketArchive;', { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true }, +}).outputText +new Function('require', 'module', 'exports', output)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed ticket dialog import ${id}`) + return imports[id] +}, loaded, loaded.exports) +const reset = () => { slots = []; effects.length = 0; calls.length = 0; closed = 0 } +const render = (component: string, props: unknown) => { cursor = 0; const node = loaded.exports[component](props); effects.splice(0).forEach((run) => run()); return node } +function find(node: any, type: unknown): any[] { + if (!node || typeof node !== 'object') return [] + return [...(node.type === type ? [node] : []), ...React.Children.toArray(node.props?.children).flatMap((child) => find(child, type))] +} +const settle = async () => { for (let i = 0; i < 12; i++) await Promise.resolve() } +const props = { ticket, onClose: () => closed++ } +let node = render('TicketEditor', props) +assert.equal(find(node, 'textarea')[0].props.value, ticket.body, 'the editor exposes all text without truncation') +find(node, 'input')[0].props.onChange({ target: { value: 'Revised' } }) +find(node, 'textarea')[0].props.onChange({ target: { value: 'Full revised description' } }) +for (const [index, value] of ['bug', 'urgent', 'large'].entries()) find(node, 'select')[index].props.onChange({ target: { value } }) +node = render('TicketEditor', props) +const submit = () => find(node, 'form')[0].props.onSubmit({ preventDefault() {} }) +submit(); submit() +assert.deepEqual(calls, [['save', 'ticket', { title: 'Revised', body: 'Full revised description', type: 'bug', priority: 'urgent', effort: 'large' }]], 'save is locked before a second click can enqueue another mutation') +reject!(new Error('Synthetic save failed')); await settle() +node = render('TicketEditor', props) +assert.equal(find(node, 'textarea')[0].props.value, 'Full revised description', 'failed saves retain the draft') +assert.equal(closed, 0) +assert.equal(find(node, 'p').some((item) => item.props.role === 'alert'), true) +submit(); resolve!(); await settle() +assert.equal(closed, 1) + +reset() +node = render('TicketEditor', { ...props, ticket: { ...ticket, runState: 'running' } }) +assert.equal(find(node, 'textarea')[0].props.readOnly, true) +assert.equal(find(node, 'select').every((item) => item.props.disabled), true) +find(node, 'form')[0].props.onSubmit({ preventDefault() {} }) +assert.equal(calls.length, 0, 'active work remains readable without allowing edits') + +reset() +state.archives.tickets = [{ ...ticket, id: 'archived', archivedAt: 1 }, { ...ticket, id: 'other-project', projectId: 'other', archivedAt: 1 }, { ...ticket, id: 'remote', orchestratorHostId: 'remote-host', archivedAt: 1 }] +node = render('TicketArchive', { projectId: 'project', onClose() {} }); await settle() +node = render('TicketArchive', { projectId: 'project', onClose() {} }) +assert.equal(find(node, 'section').length, 1, 'archives are filtered by both project and origin') +const restore = find(node, 'section')[0] +assert.equal(find(restore, 'p')[0].props.children, ticket.body) +find(restore, 'button')[0].props.onClick(); find(restore, 'button')[0].props.onClick() +assert.deepEqual(calls, [['restore', 'ticket', 'archived', null]], 'restore passes explicit local ownership and blocks duplicate requests') +resolve!(); await settle() +reset() +state.projects = [{ id: 'project', executionTarget: 'orchestrator', orchestratorId: 'remote-host' }] +node = render('TicketArchive', { projectId: 'project', onClose() {} }); await settle() +node = render('TicketArchive', { projectId: 'project', onClose() {} }) +find(find(node, 'section')[0], 'button')[0].props.onClick() +assert.deepEqual(calls, [['restore', 'ticket', 'remote', 'remote-host']], 'remote restores target the owning host') +reject!(new Error('Synthetic restore failed')); await settle() +node = render('TicketArchive', { projectId: 'project', onClose() {} }) +assert.equal(find(node, 'p').some((item) => item.props.role === 'alert'), true) +assert.equal(find(node, 'section').length, 1, 'failed restores retain the archived entry') +console.log('Ticket dialogs cover full-text edits, settings, duplicate saves, retained errors/drafts, active runs, scoped archives and local/remote restore routing') diff --git a/app/src/components/board/TicketDetails.tsx b/app/src/components/board/TicketDetails.tsx new file mode 100644 index 00000000000..4eec5a4651f --- /dev/null +++ b/app/src/components/board/TicketDetails.tsx @@ -0,0 +1,110 @@ +import { useEffect, useId, useRef, useState, type ReactNode } from 'react' +import { createPortal } from 'react-dom' +import { useStore } from '../../lib/store' +import type { Ticket } from '../../lib/types' +import { ticketDetails, ticketDetailsPatch, type TicketDetails } from '../../lib/ticket-details' +import { archiveOriginHostId } from '../../lib/store/shared/merge' +import { projectedProjectHostId } from '../../lib/store/shared/proxy-state' +import { useAuthoredText } from '../../lib/preferences/useAuthoredText' +import { useAccessibleDialog } from '../navigation/useAccessibleDialog' +import { Icon } from '../../lib/icons' +import { OriginalDiagnostic } from '../OriginalDiagnostic' + +const control = 'rounded-lg border border-line bg-card px-3 py-2 text-[13px] text-ink outline-none focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-50' + +function TicketDialog({ title, onClose, children }: { title: string; onClose(): void; children: ReactNode }) { + const tx = useAuthoredText(), id = useId(), dialog = useRef(null) + useAccessibleDialog({ open: true, onClose, dialogRef: dialog }) + return createPortal(
event.stopPropagation()}> +
+

{title}

+
{children}
+
+
, document.body) +} + +function TicketEditor({ ticket, onClose }: { ticket: Ticket; onClose(): void }) { + const tx = useAuthoredText() + const [original] = useState(() => ({ ...ticket })) + const [draft, setDraft] = useState(() => ticketDetails(ticket)) + const [busy, setBusy] = useState(false), [error, setError] = useState('') + const pending = useRef(false), alive = useRef(true) + const active = ticket.runState === 'queued' || ticket.runState === 'running' + useEffect(() => { alive.current = true; return () => { alive.current = false } }, []) + const close = () => { if (!pending.current) onClose() } + const update = (field: K, value: TicketDetails[K]) => setDraft((valueBefore) => ({ ...valueBefore, [field]: value })) + const save = async () => { + if (pending.current || active) return + pending.current = true; setBusy(true); setError('') + try { + const current = useStore.getState().tickets.find((candidate) => candidate.id === ticket.id && archiveOriginHostId(candidate) === archiveOriginHostId(original)) + const patch = ticketDetailsPatch(original, current, draft) + if (Object.keys(patch).length) await useStore.getState().updateTicket(ticket.id, patch) + if (alive.current) onClose() + } catch (reason) { if (alive.current) setError(reason instanceof Error ? reason.message : String(reason)) } + finally { pending.current = false; if (alive.current) setBusy(false) } + } + return +
{ event.preventDefault(); void save() }}> + +