From 20e4ddb5033555b43a5513e673766a1e92a17fe2 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/21] 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 fe375b146b3d0ba8abdc2bca5999bac65fb74377 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/21] 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 93f98b4d68f91760fc8b89409e6648fd43b4eb15 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/21] 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 72240ebf0a930f2d63664bc28be28be793322f5f 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/21] 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 3dca10f64a22593bcd14d81ca4c2c783888dd6fa 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/21] 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 191218c5b8e03435bca2513b00d55e1fae9ef595 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/21] 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 9382cbc24bd9b31a21c06a7342e424da362c6850 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 07/21] changelog: #2973's line quotes the served result on both chips, not synthetic layer times # Conflicts: # CHANGELOG.md From 32a3f1ef7a2b4ef6a98a9e0fdb9736b4dabd6e35 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:59:24 +0000 Subject: [PATCH 08/21] changelog: one #2973 line under Unreleased, the served result, with the thank-you Drop the older synthetic M5 Max paragraph that the served-results line replaced, and end the kept line with "Thanks to @gilby." as main's lines for his work do. # Conflicts: # CHANGELOG.md From d18b4bc4637eb548157ecdee683dadc7283e1eb8 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 09/21] 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 23a947599319b8f9342c002c5caa0e654f9be95f 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 10/21] 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 d857bbe89ffff65403ef2f86482c5f3598226156 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 11/21] 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 cda0cb534328daecbab665c18a0a23109cbb7606 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 12/21] 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 afaf202bf719bb40af25aa398acb71ac98da09e3 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 13/21] 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 cf67ec6986e07f4a945b2054d08f9cd3bd5bed5f 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 14/21] 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 18c0f5afd1ba9f280e9bd2b86f2fb1b3ec24a54e 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 15/21] 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 02ebd30323707f351705b43b266e622019ec1e9c 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 16/21] 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 0f9eaa4dd98bc29e3f7f6b6e506c0f44550beb84 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 17/21] 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 130df9756d98ac9555cf8625046631ffb8e56edc 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 18/21] 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 14b8c9a6c59dbfdb0dcba42e0caa2dc98287b2ae 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 19/21] 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 9da1cef48ac3fb047df4078e3719c07a1bc179a7 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 20/21] 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 0bbac8128c77c5651ab50aea187ce4746c77e957 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 21/21] 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).