From a206d31221af9b3be7095bb4282610c373db526d Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:56:48 +0900 Subject: [PATCH 001/158] glm cuda: the L2 prefetch's ffn-head site also reads a MoE layer's shared gate-up, after its router Site f read a MoE layer's router alone. The shared expert's gate-up runs on the same window once the routed experts are done, and its scales and codes now follow the router in the site's rows, inside the same budget. The table's test gives layer 1 a block FP8 shared gate-up and checks where the 12 MiB budget cuts it. --- zig/src/families/glm/cuda_l2pf.zig | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/zig/src/families/glm/cuda_l2pf.zig b/zig/src/families/glm/cuda_l2pf.zig index c5fefb0216b..9cdfda0e0f3 100644 --- a/zig/src/families/glm/cuda_l2pf.zig +++ b/zig/src/families/glm/cuda_l2pf.zig @@ -100,7 +100,10 @@ fn sources(l: weights.Layer, site: Site) Sources { }, }, .f => switch (l.ffn) { - .moe => |m| s.add(m.router), + .moe => |m| { + s.add(m.router); + s.proj(m.shared_gu); // read after the routed experts, which no table holds (the router picks them) + }, .dense => |m| switch (m.w) { .nvfp4 => |x| { s.lane(x.gate); @@ -310,10 +313,11 @@ test "the table: each site's sources in its matmuls' order, site n from the next d.mixer.mla.q_b = .{ .bf16 = 0x7000_0000 }; d.ffn = .{ .dense = undefined }; d.ffn.dense.w = .{ .bf16 = .{ .gu = 0x9000_0000, .down = 0xa000_0000 } }; - var e: weights.Layer = undefined; // layer 1: KDA on the lane and MoE + var e: weights.Layer = undefined; // layer 1: KDA on the lane and MoE, its shared expert block FP8 on the lane e.mixer = .{ .kda = k }; e.ffn = .{ .moe = undefined }; e.ffn.moe.router = 0x5000_0000; + e.ffn.moe.shared_gu = .{ .fp8g = .{ .mode = .fp8g, .codes = 0xb000_0000, .scales = 0x8000_0000, .n = 64, .k = 64, .npad = 64 } }; const MiB = 1 << 20; var bufs = [_]cuda.DeviceBuffer{ .{ .d = undefined, .ptr = 0x1000_0000, .len = 1 * MiB }, @@ -324,6 +328,8 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ .d = undefined, .ptr = 0x6000_0000, .len = 16 * MiB }, .{ .d = undefined, .ptr = 0x7000_0000, .len = 17 * MiB }, .{ .d = undefined, .ptr = 0x9000_0000, .len = 34 * MiB }, + .{ .d = undefined, .ptr = 0x8000_0000, .len = 1 * MiB }, + .{ .d = undefined, .ptr = 0xb000_0000, .len = 16 * MiB }, }; var rows: std.ArrayList([2]i64) = .empty; defer rows.deinit(t.allocator); @@ -333,8 +339,10 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ 0x1000_0000, 1 * MiB }, // layer 0's n: layer 1's qkv scales whole, then its codes' head .{ 0x2000_0000, 11 * MiB }, .{ 0x9000_0000, 12 * MiB }, // layer 0's f: its gate and up's head - .{ 0x5000_0000, 2 * MiB }, // layer 1's f: its router; its n would be the head's, its o is KDA's o - .{ 0x4000_0000, 12 * MiB }, + .{ 0x5000_0000, 2 * MiB }, // layer 1's f: its router, then its shared gate-up's scales and its codes' head + .{ 0x8000_0000, 1 * MiB }, + .{ 0xb000_0000, 9 * MiB }, + .{ 0x4000_0000, 12 * MiB }, // layer 1's o, KDA's o; its n would be the head's }; try t.expectEqualSlices([2]i64, &want, rows.items); try t.expectEqualSlices(Span, &.{ @@ -342,8 +350,8 @@ test "the table: each site's sources in its matmuls' order, site n from the next .{ .at = 2, .rows = 1, .bytes = 12 * MiB }, .{ .at = 3 }, // DSA: no site o .{ .at = 3 }, - .{ .at = 3, .rows = 1, .bytes = 2 * MiB }, - .{ .at = 4, .rows = 1, .bytes = 12 * MiB }, + .{ .at = 3, .rows = 3, .bytes = 12 * MiB }, + .{ .at = 6, .rows = 1, .bytes = 12 * MiB }, }, &spans); rows.clearRetainingCapacity(); try t.expect(!try table(t.allocator, bufs[1..], &.{ d, e }, 12 * MiB, &rows, &spans)); From d6b071b7927500a81b3b2a5dd0a061f519736086 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:13:50 +0000 Subject: [PATCH 002/158] changelog: #3156 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93f00f5d37b..fd64a3324f0 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: GLM's `TF_GLM_L2PF` site f now also prefetches a MoE layer's shared expert gate-up after its router within the same `TF_GLM_L2PF_MB` budget, giving about 1.0-1.2% faster decode at TP=2 on GB10 (mean of three alternating launches) with identical tokens (#3156). Thanks to @Bizuayeu. + - Desktop: the Terminal picker launches a registered Orchestrator CLI by its ID without forwarding the catalog command as a custom override, lists CLIs for the current project and host, and stops a click left stale by retargeting, project removal or a disabled host before dispatch; local custom commands and the remote refusal still apply (#3828, fixes #3824). Thanks to @AIFlowML. - Web: the OpenAI connection probe now uses the shared stream reader, so partial text followed by an error or early EOF fails the check instead of passing; the reader handles LF, CRLF and bare CR, including a CRLF split across chunks, and complete streams still pass the text-or-reasoning check (#3826, fixes #3823). Thanks to @AIFlowML. From 29884d6df1db3c9eaccd275f6c6cf81c876d17fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:03:16 +0100 Subject: [PATCH 003/158] flashnext cuda: the mixed PLE shard and the nested shards leave the page cache after load Shard 15 of the NVFP4 checkpoint holds the n-gram table beside 3.27 GiB of load-only tensors (embedding, HC, MTP, vision); the runtimePages guard skipped its release whole, and the final sweep listed only top-level *.safetensors while this checkpoint keeps its shards under tensors/. Now a shard drops everything but the n-gram tensors' pages (releaseExcept), and the sweep walks the index's shards (core.checkpoint.shardFiles). --- zig/cuda_checkpoint_cache_host.zig | 7 ++-- zig/src/core/checkpoint_cache.zig | 39 +++++++++---------- .../families/flashnext/cuda_lanes_load.zig | 2 +- zig/src/families/flashnext/cuda_prompt_wt.zig | 35 ++++++++++------- 4 files changed, 46 insertions(+), 37 deletions(-) diff --git a/zig/cuda_checkpoint_cache_host.zig b/zig/cuda_checkpoint_cache_host.zig index 816caa056cb..dd95787a1e6 100644 --- a/zig/cuda_checkpoint_cache_host.zig +++ b/zig/cuda_checkpoint_cache_host.zig @@ -109,10 +109,11 @@ test "CUDA load cache: DeepSeek finishes backbone and DSpark before the pack swe test "CUDA load cache: Flash Next sweep follows MTP and retains live PLE files" { const s = @embedFile("src/families/flashnext/cuda_lanes_load.zig"); - const drop = std.mem.indexOf(u8, s, ".dropPageCache(io, dir, e.ngram.files.items)") orelse return error.NoPleExclusion; + const drop = std.mem.indexOf(u8, s, ".dropPageCache(gpa, io, dir, e.ngram.files.items)") orelse return error.NoPleExclusion; try t.expect(std.mem.indexOf(u8, s, "mtp.Head.init").? < drop); const owner = @embedFile("src/families/flashnext/cuda_prompt_wt.zig"); - try t.expect(std.mem.indexOf(u8, owner, "if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator)") != null); + try t.expect(std.mem.indexOf(u8, owner, "if (runtimePage(name)) keep.append(scratch, self.f.get(name).?.bytes) catch return;") != null); + try t.expect(std.mem.indexOf(u8, owner, "self.f.releaseExcept(keep.items, scratch)") != null); } test "CUDA load cache: LFM2 decision model releases its direct-read fallback" { @@ -137,7 +138,7 @@ test "CUDA load cache: every TP load scope defers file advice through all-rank r const read = std.mem.indexOfPos(u8, source, start, last) orelse return error.NoLastLoad; try t.expect(start < read and read < ready); if (std.mem.eql(u8, path, "flashnext/cuda_lanes_load.zig")) { - const drop = std.mem.indexOf(u8, source, "dropPageCache(io,") orelse return error.NoSweep; + const drop = std.mem.indexOf(u8, source, "dropPageCache(gpa, io,") orelse return error.NoSweep; try t.expect(drop < ready); } } diff --git a/zig/src/core/checkpoint_cache.zig b/zig/src/core/checkpoint_cache.zig index 4c829a0b41e..d31f6d5d771 100644 --- a/zig/src/core/checkpoint_cache.zig +++ b/zig/src/core/checkpoint_cache.zig @@ -32,19 +32,15 @@ fn visit(io: Io, dir: []const u8, names: []const []const u8, comptime advise: an } /// Flash Next also closes shards while loading; its live PLE mappings must be excluded from the final sweep. -pub fn directory(io: Io, dir: []const u8, keep: anytype) void { +pub fn shards(io: Io, paths: []const [:0]u8, keep: anytype) void { if (@import("builtin").os.tag != .linux) return; - walk(io, dir, keep, drop); + walk(io, paths, keep, drop); } -fn walk(io: Io, dir: []const u8, keep: anytype, comptime advise: anytype) void { - var d = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var it = d.iterate(); - entries: while (it.next(io) catch null) |e| { - if (e.kind != .file and e.kind != .sym_link) continue; - if (!std.mem.endsWith(u8, e.name, ".safetensors")) continue; - const f = d.openFile(io, e.name, .{}) catch continue; +/// `paths` from the index (checkpoint.shardFiles), so shards nested under tensors/ are reached; held inodes skipped. +fn walk(io: Io, paths: []const [:0]u8, keep: anytype, comptime advise: anytype) void { + entries: for (paths) |path| { + const f = Io.Dir.cwd().openFile(io, path, .{}) catch continue; defer f.close(io); const stat = f.stat(io) catch continue; for (keep) |k| { @@ -89,30 +85,33 @@ test "checkpoint cache: last read precedes release and close on success and refu } } -test "checkpoint cache: final sweep excludes live PLE, subdirectories and unrelated files" { +test "checkpoint cache: final sweep reaches the index's nested shards and excludes live PLE and aliases" { var tmp = t.tmpDir(.{}); defer tmp.cleanup(); - for ([_][]const u8{ "model.safetensors", "mtp.safetensors", "ple.safetensors", "config.json" }) |name| + try tmp.dir.createDirPath(t.io, "tensors"); + for ([_][]const u8{ "tensors/model-1.safetensors", "tensors/model-2.safetensors", "tensors/ple.safetensors" }) |name| try tmp.dir.writeFile(t.io, .{ .sub_path = name, .data = name }); - try tmp.dir.createDirPath(t.io, "ssd.safetensors"); - try tmp.dir.writeFile(t.io, .{ .sub_path = "ssd.safetensors/expert.safetensors", .data = "runtime" }); - if (@import("builtin").os.tag != .windows) try tmp.dir.symLink(t.io, "ple.safetensors", "alias.safetensors", .{}); - const ple = try tmp.dir.openFile(t.io, "ple.safetensors", .{}); + if (@import("builtin").os.tag != .windows) try tmp.dir.symLink(t.io, "ple.safetensors", "tensors/alias.safetensors", .{}); + const ple = try tmp.dir.openFile(t.io, "tensors/ple.safetensors", .{}); defer ple.close(t.io); const keep = [_]struct { file: struct { file: Io.File } }{.{ .file = .{ .file = ple } }}; - const path = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); - defer t.allocator.free(path); + const root = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); + defer t.allocator.free(root); + var paths: [5][:0]u8 = undefined; + for (&paths, [_][]const u8{ "model-1", "model-2", "ple", "alias", "missing" }) |*p, name| + p.* = try std.fmt.allocPrintSentinel(t.allocator, "{s}/tensors/{s}.safetensors", .{ root, name }, 0); + defer for (paths) |p| t.allocator.free(p); const Spy = struct { var count: usize = 0; fn advise(f: Io.File) void { var buf: [64]u8 = undefined; const n = f.readPositionalAll(t.io, &buf, 0) catch unreachable; - std.debug.assert(std.mem.eql(u8, buf[0..n], "model.safetensors") or std.mem.eql(u8, buf[0..n], "mtp.safetensors")); + std.debug.assert(std.mem.startsWith(u8, buf[0..n], "tensors/model-")); count += 1; } }; Spy.count = 0; - walk(t.io, path, &keep, Spy.advise); + walk(t.io, &paths, &keep, Spy.advise); try t.expectEqual(@as(usize, 2), Spy.count); } diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 1e53ebfafb3..3ebc849aeb8 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -91,7 +91,7 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu own.confidence = try @import("sys").environment.read(f64, "TF_FLASHNEXT_CONFIDENCE", mtp.default_confidence); } errdefer if (own.head) |h| h.deinit(); - @import("cuda_prompt_wt.zig").dropPageCache(io, dir, e.ngram.files.items); + @import("cuda_prompt_wt.zig").dropPageCache(gpa, io, dir, e.ngram.files.items); const window = @min(o.context + mtp.max_rows, prompt.max_tokens); // and an attention block's block scores at the window (64 MiB at 262,144 tokens) _ = try own.engine.reserveScores(window, @min(o.context, own.engine.chunk)); diff --git a/zig/src/families/flashnext/cuda_prompt_wt.zig b/zig/src/families/flashnext/cuda_prompt_wt.zig index 423194ba607..1c7ed4b5124 100644 --- a/zig/src/families/flashnext/cuda_prompt_wt.zig +++ b/zig/src/families/flashnext/cuda_prompt_wt.zig @@ -79,24 +79,32 @@ const Shard = struct { } fn close(self: *Shard) void { - // A shard may mix loaded tensors with the n-gram table still read at runtime. - if (!runtimePages(self.f.names.keys())) self.f.release(std.heap.page_allocator); // no keep list: scratch unused + self.drop(std.heap.page_allocator); self.f.close(self.io); } + /// The shard's pages out of the page cache, except the n-gram table's: a shard may mix both (embed, HC, MTP). + fn drop(self: *const Shard, scratch: std.mem.Allocator) void { + var keep: std.ArrayList([]const u8) = .empty; + defer keep.deinit(scratch); + for (self.f.names.keys()) |name| if (runtimePage(name)) keep.append(scratch, self.f.get(name).?.bytes) catch return; + self.f.releaseExcept(keep.items, scratch); + } + fn get(self: *const Shard, name: []const u8) ?Tensor { return self.f.get(name); } }; -fn runtimePages(names: []const []const u8) bool { - for (names) |name| if (std.mem.indexOf(u8, name, ".ple_embedding.ngram_embedding.") != null) return true; - return false; +fn runtimePage(name: []const u8) bool { + return std.mem.indexOf(u8, name, ".ple_embedding.ngram_embedding.") != null; } -/// The final load-only sweep excludes the n-gram table's live mappings. -pub fn dropPageCache(io: std.Io, dir: []const u8, keep: anytype) void { - core.checkpoint.cache.directory(io, dir, keep); +/// The final load-only sweep over the index's shards excludes the n-gram table's live mappings. +pub fn dropPageCache(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, keep: anytype) void { + const paths = core.checkpoint.shardFiles(gpa, io, dir) catch return; + defer core.checkpoint.freeShardFiles(gpa, paths); + core.checkpoint.cache.shards(io, paths, keep); } pub const Store = struct { @@ -188,8 +196,8 @@ pub const Store = struct { /// Borrowers expire here; their shards stay open, pages dropped, until the load ends (or close if not kept). pub fn release(self: *Store) void { for (self.held.items) |h| { - // the borrowers' pages leave this process (their bytes are copied), except the n-gram table's (Shard.close) - if (!runtimePages(h.file.f.names.keys())) h.file.f.release(self.gpa); + // the borrowers' pages leave this process (their bytes are copied), except the n-gram table's + h.file.drop(self.gpa); self.released.append(self.gpa, h) catch { var kept = h.file; kept.close(); @@ -295,7 +303,7 @@ pub const Store = struct { } else try self.openShard(file); if (self.file) |*f| { // its pages dropped as close drops them: the n-gram table's stay - if (!runtimePages(f.f.names.keys())) f.f.release(self.gpa); + f.drop(self.gpa); self.released.appendAssumeCapacity(.{ .rel = self.rel, .file = f.* }); } self.rel = next.rel; @@ -579,6 +587,7 @@ test { } test "Flash Next load cache: a mixed PLE shard keeps its runtime pages" { - try std.testing.expect(runtimePages(&.{ "language_model.model.norm.weight", "language_model.model.layers.1.ple.ple_embedding.ngram_embedding.shards.0.weight" })); - try std.testing.expect(!runtimePages(&.{ "language_model.model.norm.weight", "language_model.mtp.norm.weight" })); + try std.testing.expect(runtimePage("language_model.model.layers.1.ple.ple_embedding.ngram_embedding.shards.0.weight")); + try std.testing.expect(!runtimePage("language_model.model.norm.weight")); + try std.testing.expect(!runtimePage("language_model.mtp.norm.weight")); } From 87515d8d5bb5ee71bc9fd0706b855796aac315c7 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 01:47:45 +0100 Subject: [PATCH 004/158] gradient-serving pins: the two Flash Next load files #3467 changes --- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 87228dc7dae..57f0dd3a51b 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -131,7 +131,7 @@ zig/src/families/flashnext/cuda_images.zig 5bd8a6c06cb69440522f4392794d9ef52b376 zig/src/families/flashnext/cuda_images_test.zig df984d54d9de1bb732544785cddf82a124de2a7019041ed1f7483b2a4a2d7c99 raw 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_load.zig 26596c5f9bb0fb01b96cb96b50d51a70cf8ef1ef4f2af91e33e6f4a0c74a6f10 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw zig/src/families/flashnext/cuda_launch.zig f8bebb5ed074e6c8ab8cef667cb01fa2bb1a2b2d6a4d3874a92291390278d9f7 raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay) zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw @@ -157,7 +157,7 @@ zig/src/families/flashnext/cuda_prompt.zig 64dfa63d6c9608d04b524689047f3f2bcf193 zig/src/families/flashnext/cuda_prompt_load.zig 334d68cfca85c15c9d986d0c6b4f8f2a38569309b21bdac6d365935d73c115cd raw zig/src/families/flashnext/cuda_prompt_main.zig 2543cd166dc80cd97b1ca1ce930a6150f9d36b52ee231744606f83bf54f0669d raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) zig/src/families/flashnext/cuda_prompt_step.zig e04030fb4a4fdb8780704a1bc0b5ba4b786159ab08a927fe32a636a893129d0c raw -zig/src/families/flashnext/cuda_prompt_wt.zig 9f0b8f853cc33e23c3ae3785c7031721615fc043e240161c84fb945e499e809f raw +zig/src/families/flashnext/cuda_prompt_wt.zig 4885be0ea938cfba80b34fbe9c160d200226761a73f8bd9d785172cbc7cef9bb raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged zig/src/families/flashnext/cuda_qmm.zig 6d035feb053691cc9750a369c86a5463d41ed942764ad85b861bb628c106dccf raw zig/src/families/flashnext/cuda_rank_engine.zig df6a83bcf80edfd94ac4474dbbc2e73818d40b7532430399af73f2eb95ccfa33 raw zig/src/families/flashnext/cuda_rank_media.zig e5c268c8cf257934bb49fe401ba6213ea8b108258bbfd4d06edb990d568c3c2b raw From 2e8bd28507df7298cb3ee5249c3aa4bd47032813 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:13:52 +0000 Subject: [PATCH 005/158] changelog: #3467 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd64a3324f0..2f5c67e8d9f 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 +- Flash Next on CUDA: after load, a mixed shard keeps only the n-gram table's pages in the page cache, and the final sweep reaches shards nested under `tensors/`, freeing about 3 GiB of page cache on the NVFP4 export with replies unchanged (#3467). Thanks to @jschmied. + - CUDA: GLM's `TF_GLM_L2PF` site f now also prefetches a MoE layer's shared expert gate-up after its router within the same `TF_GLM_L2PF_MB` budget, giving about 1.0-1.2% faster decode at TP=2 on GB10 (mean of three alternating launches) with identical tokens (#3156). Thanks to @Bizuayeu. - Desktop: the Terminal picker launches a registered Orchestrator CLI by its ID without forwarding the catalog command as a custom override, lists CLIs for the current project and host, and stops a click left stale by retargeting, project removal or a disabled host before dispatch; local custom commands and the remote refusal still apply (#3828, fixes #3824). Thanks to @AIFlowML. From e92353b411e35dce0d90b1e96b2c220b18cc6a1c 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 15:47:03 +0100 Subject: [PATCH 006/158] nemotron: drop the Living Weights copies the 10-17 revert left behind; pages read living's lesson_route --- zig/src/families/nemotron/choice.zig | 67 --- zig/src/families/nemotron/cuda_pages.zig | 2 +- zig/src/families/nemotron/editor.zig | 433 ---------------- zig/src/families/nemotron/lesson_route.zig | 121 ----- zig/src/families/nemotron/pocket_clock.zig | 37 -- zig/src/families/nemotron/pocket_dump.zig | 40 -- zig/src/families/nemotron/pocket_fit.zig | 286 ----------- zig/src/families/nemotron/pocket_forget.zig | 158 ------ .../families/nemotron/pocket_forget_test.zig | 464 ------------------ zig/src/families/nemotron/pocket_joint.zig | 46 -- zig/src/families/nemotron/pocket_pack.zig | 42 -- zig/src/families/nemotron/pocket_prefix.zig | 100 ---- zig/src/families/nemotron/probe.zig | 186 ------- zig/src/families/nemotron/router.zig | 260 ---------- zig/src/families/nemotron/subspace.zig | 216 -------- zig/src/families/nemotron/train_mode.zig | 47 -- 16 files changed, 1 insertion(+), 2504 deletions(-) delete mode 100644 zig/src/families/nemotron/choice.zig delete mode 100644 zig/src/families/nemotron/editor.zig delete mode 100644 zig/src/families/nemotron/lesson_route.zig delete mode 100644 zig/src/families/nemotron/pocket_clock.zig delete mode 100644 zig/src/families/nemotron/pocket_dump.zig delete mode 100644 zig/src/families/nemotron/pocket_fit.zig delete mode 100644 zig/src/families/nemotron/pocket_forget.zig delete mode 100644 zig/src/families/nemotron/pocket_forget_test.zig delete mode 100644 zig/src/families/nemotron/pocket_joint.zig delete mode 100644 zig/src/families/nemotron/pocket_pack.zig delete mode 100644 zig/src/families/nemotron/pocket_prefix.zig delete mode 100644 zig/src/families/nemotron/probe.zig delete mode 100644 zig/src/families/nemotron/router.zig delete mode 100644 zig/src/families/nemotron/subspace.zig delete mode 100644 zig/src/families/nemotron/train_mode.zig diff --git a/zig/src/families/nemotron/choice.zig b/zig/src/families/nemotron/choice.zig deleted file mode 100644 index 5f0bea0e6d2..00000000000 --- a/zig/src/families/nemotron/choice.zig +++ /dev/null @@ -1,67 +0,0 @@ -//! A lesson's block per layer: directions its fact's rows outweigh the steady rows along, the first rank its router's. -const std = @import("std"); -const subspace = @import("subspace.zig"); -const adapters = @import("learn_shape.zig"); - -const n = adapters.candidates; -const block = adapters.block; - -/// What each layer has seen of the steady rows and the fact's answer rows, along its candidate directions. -pub const Choice = struct { - gpa: std.mem.Allocator, - steady: []f64, // [layers, n, n]: the steady rows' second moment - facts: []f64, // [layers, n, n]: the fact's answer rows' second moment - coef: []f32, // [layers, block, n]: each layer's new directions in the candidates' terms - - pub fn init(gpa: std.mem.Allocator, layers: usize) !Choice { - return .{ - .gpa = gpa, - .steady = try gpa.alloc(f64, layers * n * n), - .facts = try gpa.alloc(f64, layers * n * n), - .coef = try gpa.alloc(f32, layers * block * n), - }; - } - - pub fn deinit(c: *Choice) void { - inline for (.{ "steady", "facts", "coef" }) |f| c.gpa.free(@field(c, f)); - } - - pub fn reset(c: *Choice) void { - @memset(c.steady, 0); - @memset(c.facts, 0); - } - - /// Layer l's unit rows [rows, n], steady or the fact's; row `first` (how an answer opens) weighs as all after it. - pub fn add(c: *Choice, l: usize, rows: []const f32, fact: bool, first: usize) void { - const m = (if (fact) c.facts else c.steady)[l * n * n ..][0 .. n * n]; - const count = rows.len / n; - for (0..count) |r| { - const p = rows[r * n ..][0..n]; - const w: f64 = if (r == first) @floatFromInt(@max(count - first - 1, 1)) else 1; - for (0..n) |i| for (0..n) |j| { - m[i * n + j] += w * p[i] * p[j]; - }; - } - } - - /// Every layer's directions. - pub fn choose(c: *Choice) !void { - var threads: [16]?std.Thread = @splat(null); - var failed: [16]?anyerror = @splat(null); - const layers = c.coef.len / (block * n); - const k = @min(threads.len, layers); - for (threads[0..k], 0..) |*t, i| t.* = std.Thread.spawn(.{}, share, .{ c, i, k, &failed[i] }) catch null; - for (threads[0..k], 0..) |t, i| if (t) |th| th.join() else share(c, i, k, &failed[i]); - for (failed[0..k]) |f| if (f) |e| return e; - } - - fn share(c: *Choice, from: usize, step: usize, failed: *?anyerror) void { - var l = from; - while (l < c.coef.len / (block * n)) : (l += step) { - const coef = c.coef[l * block * n ..][0 .. block * n]; - subspace.outweigh(c.gpa, c.facts[l * n * n ..][0 .. n * n], c.steady[l * n * n ..][0 .. n * n], n, block, coef) catch |e| { - failed.* = e; - }; - } - } -}; diff --git a/zig/src/families/nemotron/cuda_pages.zig b/zig/src/families/nemotron/cuda_pages.zig index 0950e8720df..0931d54b6fc 100644 --- a/zig/src/families/nemotron/cuda_pages.zig +++ b/zig/src/families/nemotron/cuda_pages.zig @@ -6,7 +6,7 @@ const Engine = @import("cuda_engine.zig").Engine; const state = @import("cuda_state.zig"); const reuse = @import("cuda_reuse.zig"); const mtp = @import("cuda_mtp.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; /// One paged sequence, made at load, and the lease of the stream that holds it. const Lane = struct { seq: *state.Seq, lease: kv.Lease = .{}, used: bool = false }; diff --git a/zig/src/families/nemotron/editor.zig b/zig/src/families/nemotron/editor.zig deleted file mode 100644 index 7723596fc68..00000000000 --- a/zig/src/families/nemotron/editor.zig +++ /dev/null @@ -1,433 +0,0 @@ -//! A fact written at its subject: rank-one changes to a few shared-expert down projections, other keys' outputs kept. -const std = @import("std"); -const adapters = @import("learn_shape.zig"); -const lesson_route = @import("lesson_route.zig"); -const subspace = @import("subspace.zig"); - -const examples = @import("lesson_examples.zig"); -const Example = examples.Example; -const pick = examples.pick; - -/// The MoE layers a fact's change is spread over, first to last; its target is the residual after the last. -pub const layers = [_]usize{ 13, 15, 17 }; -const target_layer = layers[layers.len - 1]; - -const hold: f32 = 1e2; // the kept keys' mean second moment against a fact's own key, when a change is solved -const history_weight: f32 = 1e3; // an earlier fact's key against one kept row: it must keep its output exactly -const target_steps = 30; // Adam steps on the nudge that makes the fact's answers come out -const reach: f32 = 0.1; // each nudge step's size against the residual's -const decay: f32 = 0.5; // the nudge's squared size against the residual's, added to its loss -const furthest: f32 = 4; // the nudge's size at most, against the residual's -const enough: f32 = 0.05; // a mean answer loss low enough that the nudge stops early - -const Phase = enum { kept, facts, target, edits, done }; - -/// The lesson's acting lessons and flags for a step: every lesson kept so far and, once written, this one. -pub const Acting = lesson_route.Acting; - -/// An editor over trainer T (Metal's: its key, residual and nudge). -pub fn Editor(comptime T: type) type { - return struct { - const Self = @This(); - gpa: std.mem.Allocator, - kept: [layers.len]std.ArrayList(f32) = @splat(.empty), // each layer's kept keys [rows, W], this lesson's - history: [layers.len]std.ArrayList(f32) = @splat(.empty), // each layer's keys of every fact written so far - facts: std.ArrayList(Example) = .empty, // the fact's examples that have a subject row, those with answers first - answered: usize = 0, // facts[0..answered] have answers: the nudge is found on those, the key read on all - stay: []const []const Example = &.{}, // the examples whose outputs the change must keep - keys: std.ArrayList(f32) = .empty, // [facts, layers, W]: each example's key at each layer, as last read - base: std.ArrayList(f32) = .empty, // [facts, D]: the residual after the target layer at the subject row, unchanged - now: std.ArrayList(f32) = .empty, // [facts, D]: the same as last read - delta: std.ArrayList(f32) = .empty, // [4, D]: the nudge, its Adam moments, and a round's gradient - phase: Phase = .done, - at: usize = 0, - round: usize = 0, - loss: f32 = 0, - first_loss: f32 = 0, - last_loss: f32 = 0, - size: f32 = 0, // the subject rows' mean residual length after the target layer - - pub fn init(gpa: std.mem.Allocator) Self { - return .{ .gpa = gpa }; - } - - pub fn deinit(e: *Self) void { - for (&e.kept) |*s| s.deinit(e.gpa); - for (&e.history) |*s| s.deinit(e.gpa); - inline for (.{ "facts", "keys", "base", "now", "delta" }) |f| @field(e, f).deinit(e.gpa); - } - - /// Examples naming a subject (`answered` set the nudge, `asked` add keys) and ones to keep; false if too few. - pub fn begin(e: *Self, answered: []const []const Example, asked: []const []const Example, stay: []const []const Example) !bool { - e.facts.clearRetainingCapacity(); - for (answered) |xs| for (xs) |ex| if (ex.subject > 0 and ex.subject < ex.start) try e.facts.append(e.gpa, ex); - e.answered = e.facts.items.len; - if (e.answered < 2) return false; - for (asked) |xs| for (xs) |ex| if (ex.subject > 0 and ex.subject < ex.start) try e.facts.append(e.gpa, ex); - for (&e.kept) |*s| s.clearRetainingCapacity(); - e.stay = stay; - e.next(.kept); - return true; - } - - /// One unit (keys, a nudge step or a layer's change) run with `acting`; true once every layer has its change. - pub fn step(e: *Self, t: *T, acting: Acting) !bool { - return switch (e.phase) { - .kept => e.keptOnce(t, acting), - .facts => e.factsOnce(t, acting), - .target => e.targetOnce(t, acting), - .edits => e.editsOnce(t, acting), - .done => true, - }; - } - - /// The fact's keys joined to every layer's history, once its lesson stays: later facts keep its outputs. - pub fn settle(e: *Self) !void { - const w = keyWidth(e); - if (w == 0) return; - for (0..e.facts.items.len) |i| for (0..layers.len) |j| { - try e.history[j].appendSlice(e.gpa, e.keys.items[(i * layers.len + j) * w ..][0..w]); - }; - } - - /// The kept edit rounded into each layer's codes, all before any write (`host`: codes, addRounded, commit). - pub fn fold(e: *Self, t: *T, host: anytype) !void { - const c = t.b.m.config; - const w = c.shared_width; - const d = c.hidden; - const h = try e.gpa.alloc(f32, w * w); - defer e.gpa.free(h); - const delta = try e.gpa.alloc(f32, d * w); - defer e.gpa.free(delta); - var fresh: [layers.len][]u32 = @splat(&.{}); - defer for (fresh) |f| e.gpa.free(f); - const first = t.sites.first(); - const ranks = t.sites.cap * adapters.block; - for (layers, 0..) |l, j| { - const site = &t.sites.list[l]; - const a = site.a.slice(f32, ranks * site.in)[first * site.in ..][0..site.in]; - const b = site.b.slice(f32, ranks * site.out)[first * site.out ..][0..site.out]; - for (0..d) |o| for (delta[o * w ..][0..w], a) |*x, ai| { - x.* = adapters.scale * b[o] * ai; - }; - const add = secondMoment(e.kept[j].items, e.history[j].items, w, h); - const codes = try host.codes(l); - fresh[j] = try e.gpa.dupe(u32, codes.words); - const changed = try host.addRounded(fresh[j], codes.scales, codes.biases, d, w, delta, h, add); - std.log.info("slide: layer {d}'s down projection takes the change in {d} of its {d} codes", .{ l, changed, d * w }); - } - for (layers, fresh) |l, f| { - @memcpy((try host.codes(l)).words, f); - try host.commit(l); - } - } - - fn keyWidth(e: *const Self) usize { - return if (e.facts.items.len == 0) 0 else e.keys.items.len / (e.facts.items.len * layers.len); - } - - fn turn(ex: Example, acting: Acting) lesson_route.Turn { - return .{ .decide = ex.decide, .bits = acting, .whole = true }; - } - - fn keptOnce(e: *Self, t: *T, acting: Acting) !bool { - var n: usize = 0; - for (e.stay) |xs| n += xs.len; - if (e.at == n) { - e.next(.facts); - return false; - } - const ex = pick(e.stay, e.at); - e.at += 1; - _ = try t.step(ex.ids, ex.start, .keys, turn(ex, acting)); - for (layers, &e.kept) |l, *rows| for (0..ex.ids.len - 1) |r| try widen(e.gpa, rows, t.key(l, r)); - return false; - } - - fn factsOnce(e: *Self, t: *T, acting: Acting) !bool { - const c = t.b.m.config; - if (e.at == 0) { - e.keys.clearRetainingCapacity(); - e.base.clearRetainingCapacity(); - try e.keys.appendNTimes(e.gpa, 0, e.facts.items.len * layers.len * c.shared_width); - try e.base.appendNTimes(e.gpa, 0, e.facts.items.len * c.hidden); - } - if (e.at == e.facts.items.len) { - e.now.clearRetainingCapacity(); - try e.now.appendSlice(e.gpa, e.base.items); - e.size = 0; - for (0..e.answered) |i| e.size += @sqrt(subspace.dot(row(e.base.items, i, c.hidden), row(e.base.items, i, c.hidden))); - e.size /= @floatFromInt(e.answered); - e.delta.clearRetainingCapacity(); - try e.delta.appendNTimes(e.gpa, 0, 4 * c.hidden); - e.next(.target); - return false; - } - const i = e.at; - e.at += 1; - try e.read(t, i, null, acting, true); - return false; - } - - /// Example i's key at every layer (or only layer `only`) and its residual after the target layer, as now. - fn read(e: *Self, t: *T, i: usize, only: ?usize, acting: Acting, unchanged: bool) !void { - const c = t.b.m.config; - const ex = e.facts.items[i]; - _ = try t.step(ex.ids, ex.start, .keys, turn(ex, acting)); - for (layers, 0..) |l, j| { - if (only) |o| if (o != j) continue; - for (e.keys.items[(i * layers.len + j) * c.shared_width ..][0..c.shared_width], t.key(l, ex.subject)) |*o, b| o.* = f32of(b); - } - const into = if (unchanged) e.base.items else e.now.items; - for (row(into, i, c.hidden), t.residual(target_layer + 1, ex.subject)) |*o, b| o.* = f32of(b); - } - - fn targetOnce(e: *Self, t: *T, acting: Acting) !bool { - const d = t.b.m.config.hidden; - const delta = e.delta.items[0..d]; - const grad = e.delta.items[3 * d ..][0..d]; - if (e.at == 0) @memset(grad, 0); - if (e.at < e.answered) { - const ex = e.facts.items[e.at]; - e.at += 1; - t.nudge = .{ .layers = .{ @as(u64, 1) << target_layer, 0, 0 }, .rows = .{ ex.subject, 0, 0 } }; - @memcpy(t.delta.slice(f32, t.b.m.config.layers * d)[target_layer * d ..][0..d], delta); - const got = try t.step(ex.ids, ex.start, .target, turn(ex, acting)); - e.loss += got.loss; - for (grad, t.push.slice(f32, t.b.m.config.layers * d)[target_layer * d ..][0..d]) |*g, p| g.* += p; - return false; - } - const n: f32 = @floatFromInt(e.answered); - const mean = e.loss / n; - if (e.round == 0) e.first_loss = mean; - e.loss = 0; - e.at = 0; - e.round += 1; - if (mean < enough or e.round > target_steps) { - e.last_loss = mean; - std.log.info("slide: the subject's target found in {d} steps, the answers' loss {d:.3} to {d:.3}, its nudge {d:.2} of the residual", .{ e.round - 1, e.first_loss, mean, @sqrt(subspace.dot(delta, delta)) / e.size }); - e.next(.edits); - return false; - } - const m = e.delta.items[d..][0..d]; - const v = e.delta.items[2 * d ..][0..d]; - const lr = reach * e.size / @sqrt(@as(f32, @floatFromInt(d))); - const t1: f32 = @floatFromInt(e.round); - for (delta, m, v, grad) |*x, *mm, *vv, g0| { - const g = g0 / n + 2 * decay * x.* / (e.size * e.size); - mm.* = 0.9 * mm.* + 0.1 * g; - vv.* = 0.999 * vv.* + 0.001 * g * g; - const mh = mm.* / (1 - std.math.pow(f32, 0.9, t1)); - const vh = vv.* / (1 - std.math.pow(f32, 0.999, t1)); - x.* -= lr * mh / (@sqrt(vh) + 1e-8); - } - const len = @sqrt(subspace.dot(delta, delta)); - if (len > furthest * e.size) for (delta) |*x| { - x.* *= furthest * e.size / len; - }; - return false; - } - - fn editsOnce(e: *Self, t: *T, acting: Acting) !bool { - if (e.round == layers.len) { - e.next(.done); - return true; - } - if (e.at < e.facts.items.len) { - const i = e.at; - e.at += 1; - try e.read(t, i, e.round, acting, false); - return false; - } - try e.edit(t, e.round, acting); - e.at = 0; - e.round += 1; - return false; - } - - /// Layer j's rank-one change: the mean key sent to its share of the nudge left, kept and earlier keys held. - fn edit(e: *Self, t: *T, j: usize, acting: Acting) !void { - const c = t.b.m.config; - const w = c.shared_width; - const d = c.hidden; - const n: f32 = @floatFromInt(e.facts.items.len); - const na: f32 = @floatFromInt(e.answered); - const work = try e.gpa.alloc(f32, w + w + d); - defer e.gpa.free(work); - const key = work[0..w]; - const u = work[w..][0..w]; - const left = work[2 * w ..][0..d]; - @memset(work, 0); - for (0..e.facts.items.len) |i| subspace.axpy(key, 1 / n, e.keys.items[(i * layers.len + j) * w ..][0..w]); - for (0..e.answered) |i| for (left, row(e.base.items, i, d), row(e.now.items, i, d), e.delta.items[0..d]) |*o, b, now, dl| { - o.* += (b + dl - now) / na; - }; - for (left) |*o| o.* /= @floatFromInt(layers.len - j); - try solve(e.gpa, e.kept[j].items, e.history[j].items, w, key, u); - const s = subspace.dot(key, u); - const site = &t.sites.list[layers[j]]; - const first = t.sites.first(); - const ranks = t.sites.cap * adapters.block; - const a = site.a.slice(f32, ranks * site.in)[first * site.in ..][0..site.in]; - const b = site.b.slice(f32, ranks * site.out)[first * site.out ..][0..site.out]; - for (a, u) |*o, x| o.* = x / (1 + s); - for (b, left) |*o, x| o.* = x / adapters.scale; - t.sites.attach(&t.b.m.weights, true); - var loss: f32 = 0; - for (e.facts.items[0..e.answered]) |ex| loss += (try t.step(ex.ids, ex.start, .loss, turn(ex, acting))).loss; - std.log.info("slide: change at layer {d}: the key's reach over the kept rows {d:.1}, its change {d:.2} of the residual; the answers' loss with it {d:.3} (the nudge's {d:.3})", .{ layers[j], s, @sqrt(subspace.dot(left, left)) / e.size, loss / na, e.last_loss }); - } - - fn next(e: *Self, phase: Phase) void { - e.phase = phase; - e.at = 0; - e.round = 0; - e.loss = 0; - } - }; -} - -/// A bf16's value. -fn f32of(b: u16) f32 { - return @bitCast(@as(u32, b) << 16); -} - -fn row(xs: []f32, i: usize, n: usize) []f32 { - return xs[i * n ..][0..n]; -} - -/// A bf16 row appended as f32. -fn widen(gpa: std.mem.Allocator, rows: *std.ArrayList(f32), from: []const u16) !void { - try rows.ensureUnusedCapacity(gpa, from.len); - for (from) |b| rows.appendAssumeCapacity(f32of(b)); -} - -/// h = hold X^T X / rows + history_weight H^T H; returns the fold's diagonal add: a hundredth of the kept part's mean. -fn secondMoment(x: []const f32, hist: []const f32, w: usize, h: []f32) f32 { - const rows = x.len / w; - const scale = hold / @as(f32, @floatFromInt(@max(rows, 1))); - @memset(h[0 .. w * w], 0); - const Share = struct { - fn run(xs: []const f32, width: usize, coef: f32, out: []f32, from: usize, to: usize) void { - const n = xs.len / width; - for (0..n) |r| { - const v = xs[r * width ..][0..width]; - for (from..to) |i| { - const f = coef * v[i]; - if (f != 0) subspace.axpy(out[i * width ..][0..width], f, v); - } - } - } - }; - const threads = @min(std.Thread.getCpuCount() catch 1, 32); - var spawned: [32]?std.Thread = @splat(null); - for (0..threads) |k| spawned[k] = std.Thread.spawn(.{}, Share.run, .{ x, w, scale, h, w * k / threads, w * (k + 1) / threads }) catch null; - for (0..threads) |k| if (spawned[k]) |th| th.join() else Share.run(x, w, scale, h, w * k / threads, w * (k + 1) / threads); - var mean: f32 = 0; - for (0..w) |i| mean += h[i * w + i]; - Share.run(hist, w, history_weight, h, 0, w); - if (mean == 0) for (0..w) |i| { // nothing kept: the facts' keys set it after all - mean += h[i * w + i]; - }; - return 1e-2 * mean / @as(f32, @floatFromInt(w)) + 1e-12; -} - -/// u = C^-1 k, C = hold X^T X / rows + history_weight H^T H + mu I (X kept keys, H facts'), by preconditioned CG. -fn solve(gpa: std.mem.Allocator, x: []const f32, h: []const f32, w: usize, k: []const f32, u: []f32) !void { - const rows = x.len / w; - const hist = h.len / w; - const work = try gpa.alloc(f32, 5 * w); - defer gpa.free(work); - const diag = work[0..w]; - const r = work[w..][0..w]; - const z = work[2 * w ..][0..w]; - const p = work[3 * w ..][0..w]; - const ap = work[4 * w ..][0..w]; - const scale = hold / @as(f32, @floatFromInt(@max(rows, 1))); - @memset(diag, 0); - for (0..rows) |i| for (diag, x[i * w ..][0..w]) |*dg, v| { - dg.* += scale * v * v; - }; - for (0..hist) |i| for (diag, h[i * w ..][0..w]) |*dg, v| { - dg.* += history_weight * v * v; - }; - var mean: f32 = 0; - for (diag) |dg| mean += dg; - const mu = 1e-2 * mean / @as(f32, @floatFromInt(w)) + 1e-12; - for (diag) |*dg| dg.* += mu; - @memset(u, 0); - @memcpy(r, k); - for (z, r, diag) |*zi, ri, dg| zi.* = ri / dg; - @memcpy(p, z); - var rz = subspace.dot(r, z); - const stop = 1e-4 * @sqrt(subspace.dot(k, k)); - for (0..400) |_| { - try apply(gpa, x, scale, h, w, mu, p, ap); - const pap = subspace.dot(p, ap); - if (!(pap > 0)) break; - const alpha = rz / pap; - if (!std.math.isFinite(alpha)) break; - subspace.axpy(u, alpha, p); - subspace.axpy(r, -alpha, ap); - if (@sqrt(subspace.dot(r, r)) < stop) break; - for (z, r, diag) |*zi, ri, dg| zi.* = ri / dg; - const rz2 = subspace.dot(r, z); - for (p, z) |*pi, zi| pi.* = zi + rz2 / rz * pi.*; - rz = rz2; - } - for (u) |*v| if (!std.math.isFinite(v.*)) { - v.* = 0; - }; -} - -/// ap = C p, with C as `solve` holds it, the rows' products spread over threads. -fn apply(gpa: std.mem.Allocator, x: []const f32, scale: f32, h: []const f32, w: usize, mu: f32, p: []const f32, ap: []f32) !void { - const threads = @min(std.Thread.getCpuCount() catch 1, 16); - const parts = try gpa.alloc(f32, threads * w); - defer gpa.free(parts); - @memset(parts, 0); - const Share = struct { - fn run(xs: []const f32, hs: []const f32, width: usize, sc: f32, pp: []const f32, out: []f32, from: usize, step: usize) void { - const n = xs.len / width; - var i = from; - while (i < n + hs.len / width) : (i += step) { - const v = if (i < n) xs[i * width ..][0..width] else hs[(i - n) * width ..][0..width]; - const cf = (if (i < n) sc else history_weight) * subspace.dot(v, pp); - subspace.axpy(out, cf, v); - } - } - }; - var spawned: [16]?std.Thread = @splat(null); - for (0..threads) |i| spawned[i] = std.Thread.spawn(.{}, Share.run, .{ x, h, w, scale, p, parts[i * w ..][0..w], i, threads }) catch null; - for (0..threads) |i| if (spawned[i]) |th| th.join() else Share.run(x, h, w, scale, p, parts[i * w ..][0..w], i, threads); - for (ap, p) |*o, v| o.* = mu * v; - for (0..threads) |i| for (ap, parts[i * w ..][0..w]) |*o, v| { - o.* += v; - }; -} - -test "the solve inverts the kept rows' held second moment, earlier facts' keys among them" { - const gpa = std.testing.allocator; - const w = 16; - var x: [40 * w]f32 = undefined; - var h: [3 * w]f32 = undefined; - var prng = std.Random.DefaultPrng.init(3); - for (&x) |*v| v.* = prng.random().float(f32) - 0.5; - for (&h) |*v| v.* = prng.random().float(f32) - 0.5; - var k: [w]f32 = undefined; - for (&k, 0..) |*v, i| v.* = @floatFromInt(i % 3); - var u: [w]f32 = undefined; - try solve(gpa, &x, &h, w, &k, &u); - var diag_mean: f32 = 0; - for (0..w) |i| { - for (0..40) |r| diag_mean += hold / 40 * x[r * w + i] * x[r * w + i]; - for (0..3) |r| diag_mean += history_weight * h[r * w + i] * h[r * w + i]; - } - const mu = 1e-2 * diag_mean / w + 1e-12; - for (0..w) |i| { - var s: f32 = mu * u[i]; - for (0..40) |r| s += hold / 40 * x[r * w + i] * subspace.dot(x[r * w ..][0..w], &u); - for (0..3) |r| s += history_weight * h[r * w + i] * subspace.dot(h[r * w ..][0..w], &u); - try std.testing.expectApproxEqAbs(k[i], s, 2e-2 * (1 + @abs(k[i]))); - } -} diff --git a/zig/src/families/nemotron/lesson_route.zig b/zig/src/families/nemotron/lesson_route.zig deleted file mode 100644 index f806c76abcb..00000000000 --- a/zig/src/families/nemotron/lesson_route.zig +++ /dev/null @@ -1,121 +0,0 @@ -//! How rows meet lessons in both gate kernels: the decision row scores each router, later rows carry those that clear. -const std = @import("std"); - -pub const max_slots = 64; // latch slots: a stream's replay id (a sequence's on CUDA), the trainer's the last -pub const max_blocks = @import("learn_shape.zig").max_blocks; -pub const trainer_slot = max_slots - 1; -pub const max_segments = 8; - -/// A stream without a decision row: none of its rows carry a lesson. -pub const none: i64 = std.math.maxInt(i32); - -/// No segments: no row carries a lesson. -pub const off: Route = .{}; - -/// Which lessons act on a reply, a bit a block. -pub const Acting = std.bit_set.Integer(max_blocks); - -/// A training example's decision row and the lessons acting after it (`whole`: on every row, as weight edits do). -pub const Turn = struct { decide: u32, bits: Acting = .empty, whole: bool = false }; - -/// A slot's latch flags (`latch`: u32 [max_slots, max_blocks]) set to `bits`, as a training pass reads them. -pub fn flag(latch: []u32, slot: u32, bits: Acting) void { - for (latch[slot * max_blocks ..][0..max_blocks], 0..) |*f, b| f.* = @intFromBool(bits.isSet(b)); -} - -/// A training pass over one example's `rows` rows: its latch is set before the pass (the trainer's slot). -pub fn trained(rows: usize, turn: Turn) Route { - var r: Route = .{ .known = 1, .whole = @intFromBool(turn.whole) }; - r.add(0, rows, 0, turn.decide, trainer_slot); - return r; -} - -pub const Route = extern struct { - count: u32 = 0, - known: u32 = 0, // 1: every latch was set before the pass, so rows after a decision row in it may act (training) - whole: u32 = 0, // 1: lessons edit the weights and act on every row (a training pass's flagged ones, else all) - pad: u32 = 0, - seg: [max_segments][4]i32 = std.mem.zeroes([max_segments][4]i32), - - /// The pass's rows `first`..`first + rows`, a stream's rows from position `pos`, its decision row at `decide`. - pub fn add(r: *Route, first: usize, rows: usize, pos: usize, decide: i64, slot: u32) void { - std.debug.assert(r.count < max_segments); - const at: i64 = if (decide == none) none else @as(i64, @intCast(first)) + decide - @as(i64, @intCast(pos)); - r.seg[r.count] = .{ @intCast(first), @intCast(rows), @intCast(std.math.clamp(at, -1, none)), @intCast(slot) }; - r.count += 1; - } - - /// The pass's rows `first`..`first + rows`, a stream past its decision row: its latch alone decides. - pub fn later(r: *Route, first: usize, rows: usize, slot: u32) void { - r.add(first, rows, 1, 0, slot); - } - - /// Segment s's decision row, when it lies in this pass (then the stream's latch is set after it). - pub fn decision(r: *const Route, s: usize) ?usize { - const g = r.seg[s]; - return if (g[2] >= g[0] and g[2] < g[0] + g[1]) @intCast(g[2]) else null; - } -}; - -test "a stream's rows carry a lesson only after its decision row" { - var r: Route = .{}; - r.add(0, 10, 100, 104, 3); // decision at position 104: pass row 4 - r.add(10, 2, 200, 150, 5); // decided in an earlier pass - r.add(12, 3, 7, none, 6); - try std.testing.expectEqual(@as(?usize, 4), r.decision(0)); - try std.testing.expectEqual(@as(?usize, null), r.decision(1)); - try std.testing.expect(r.seg[1][2] < r.seg[1][0]); - try std.testing.expect(r.seg[2][2] >= r.seg[2][0] + r.seg[2][1]); -} - -/// A pass's rows the pocket acts on, segment by segment in pass order: runs of rows between untaught streams' rows. -pub const Runs = struct { - first: usize = 0, // the open run's first row - rows: usize = 0, // and its rows so far - - /// The run a segment of `rows` rows closes, if any: an untaught segment ends the open run and is left out. - pub fn next(r: *Runs, rows: usize, untaught: bool) ?[2]usize { - if (!untaught) { - r.rows += rows; - return null; - } - const closed = r.last(); - r.* = .{ .first = r.first + r.rows + rows }; - return closed; - } - - /// The open run, once every segment is in. - pub fn last(r: *const Runs) ?[2]usize { - return if (r.rows > 0) .{ r.first, r.rows } else null; - } -}; - -test "the pocket's runs leave out the rows of streams that read the model as shipped" { - var r: Runs = .{}; - try std.testing.expectEqual(@as(?[2]usize, null), r.next(3, false)); - try std.testing.expectEqual(@as(?[2]usize, .{ 0, 3 }), r.next(2, true)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(4, true)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(1, false)); - try std.testing.expectEqual(@as(?[2]usize, null), r.next(2, false)); - try std.testing.expectEqual(@as(?[2]usize, .{ 9, 3 }), r.last()); - var all: Runs = .{}; - try std.testing.expectEqual(@as(?[2]usize, null), all.next(5, true)); - try std.testing.expectEqual(@as(?[2]usize, null), all.last()); -} - -/// The kept lessons (blocks below `blocks`) whose router scores reach what they need. -pub fn latched(score: []const f32, need: []const f32, blocks: usize) Acting { - var bits: Acting = .empty; - for (0..blocks) |b| if (need[b] > 0 and score[b] >= need[b]) bits.set(b); - return bits; -} - -test "a kept lesson acts on a reply only once its router score reaches what it needs" { - var score: [max_blocks]f32 = @splat(0); - var need: [max_blocks]f32 = @splat(0); - score[0..4].* = .{ 2.5, 1.2, 0, 3 }; - need[0..2].* = .{ 2, 1.5 }; - const four = latched(&score, &need, 4); - try std.testing.expect(four.isSet(0) and four.count() == 1); - try std.testing.expectEqual(@as(usize, 0), latched(&score, &need, 0).count()); -} diff --git a/zig/src/families/nemotron/pocket_clock.zig b/zig/src/families/nemotron/pocket_clock.zig deleted file mode 100644 index f4b539472b0..00000000000 --- a/zig/src/families/nemotron/pocket_clock.zig +++ /dev/null @@ -1,37 +0,0 @@ -//! Where a pocket lesson's round spends its time: wall seconds, trainer passes and rows of each phase, logged a round. -const std = @import("std"); - -/// A round's phases: examples read, inputs fitted, outputs fitted, the held-out loss read between steps, judging. -pub const Part = enum { read, fit, values, judge, check }; -const parts = std.enums.values(Part).len; - -/// Passes a trainer ran and the rows they held, counted as it steps. -pub const Count = struct { passes: usize = 0, rows: usize = 0 }; - -pub const Clock = struct { - seconds: [parts]f64 = @splat(0), - passes: [parts]usize = @splat(0), - rows: [parts]usize = @splat(0), - round: usize = 1, - - pub fn add(c: *Clock, part: Part, seconds: f64, before: Count, after: Count) void { - const i = @backingInt(part); - c.seconds[i] += seconds; - c.passes[i] += after.passes - before.passes; - c.rows[i] += after.rows - before.rows; - } - - /// The round's line, then the counts cleared for the next round. - pub fn end(c: *Clock) void { - const s = c.seconds; - var total: f64 = 0; - for (s) |x| total += x; - std.log.info("slide pocket: round {d} took {d:.1} s: read {d:.1} s ({d} passes, {d} rows), fit {d:.1} s, values {d:.1} s ({d} passes, {d} rows), judge {d:.1} s ({d} passes), check {d:.1} s ({d} passes)", .{ c.round, total, s[0], c.passes[0], c.rows[0], s[1], s[2], c.passes[2], c.rows[2], s[3], c.passes[3], s[4], c.passes[4] }); - c.* = .{ .round = c.round + 1 }; - } -}; - -/// Seconds on the awake clock. -pub fn now(io: std.Io) f64 { - return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; -} diff --git a/zig/src/families/nemotron/pocket_dump.zig b/zig/src/families/nemotron/pocket_dump.zig deleted file mode 100644 index b1f5d152a6a..00000000000 --- a/zig/src/families/nemotron/pocket_dump.zig +++ /dev/null @@ -1,40 +0,0 @@ -//! A lesson's read rows written out for offline study (TF_SLIDE_POCKET_DUMP=dir): inputs, labels and examples. -const std = @import("std"); -const platform = @import("sys"); - -/// `bytes` written to `path`. -fn put(path: [:0]const u8, bytes: []const u8) !void { - const f = platform.c.fopen(path, "wb") orelse return error.DumpOpen; - defer _ = platform.c.fclose(f); - if (platform.c.fwrite(bytes.ptr, 1, bytes.len, f) != bytes.len) return error.DumpWrite; -} - -/// Pocket `p`'s read rows under `dir` for `tag`: bf16 [read, slots, D], then their labels and examples as text. -pub fn write(p: anytype, dir: []const u8, tag: usize, d: usize) !void { - const a = p.gpa; - var path: [1024]u8 = undefined; - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-rows.bf16", .{ dir, tag }, 0), std.mem.sliceAsBytes(p.rows.items)); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(a); - try text.print(a, "{d} {d}", .{ p.moe.items.len, d }); - for (p.moe.items) |l| try text.print(a, " {d}", .{l}); - try text.append(a, '\n'); - var exs: usize = 0; - for (p.labels.items) |l| { - const ex = p.pickRead(l.ex).?.ex; - const key: i32 = if (l.key) |k| @backingInt(k) else -1; - try text.print(a, "{d} {d} {d} {d} {d} {d}\n", .{ @backingInt(l.kind), key, l.ex, l.row, ex.ids[l.row], if (l.row > 0) ex.ids[l.row - 1] else 0 }); - exs = @max(exs, l.ex + 1); - } - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-labels.txt", .{ dir, tag }, 0), text.items); - text.clearRetainingCapacity(); - for (0..exs) |i| { - const got = p.pickRead(i).?; - const ex = got.ex; - try text.print(a, "{d} {d} {d} {d} {d} {d}", .{ i, @backingInt(got.kind), ex.start, ex.decide, ex.subject, ex.value }); - for (ex.ids) |id| try text.print(a, " {d}", .{id}); - try text.append(a, '\n'); - } - try put(try std.mem.printSentinel(&path, "{s}/fact-{d}-examples.txt", .{ dir, tag }, 0), text.items); - std.log.info("slide pocket: the lesson's {d} read rows written to {s} for study", .{ p.labels.items.len, dir }); -} diff --git a/zig/src/families/nemotron/pocket_fit.zig b/zig/src/families/nemotron/pocket_fit.zig deleted file mode 100644 index 02c9d994934..00000000000 --- a/zig/src/families/nemotron/pocket_fit.zig +++ /dev/null @@ -1,286 +0,0 @@ -//! A pocket neuron's input weights by Adam on squared hinges: at least 1 on its fact's rows, below zero elsewhere. -const std = @import("std"); -const subspace = @import("subspace.zig"); - -pub const margin: f32 = 0.25; // how far below zero a fact's neuron sits on rows it stays silent on -pub const fit_steps = 500; // Adam steps fitting a neuron's input weights -pub const fit_rate: f32 = 0.01; // their step, the inputs scaled to unit length - -/// A read row to the open fact: a key row of a learned, held-out or other prompt, any other row, or left free. -pub const Kind = enum(u8) { fact, held, steady, other, none }; - -/// One MoE layer's fit: how its neuron's input product sits on each kind of row. -pub const Fit = struct { - fact_least: f32 = 0, // the lowest over the fact's own questions - fact_on: f32 = 0, // the share of them at 0.5 or more - held_mean: f32 = 0, - held_on: f32 = 0, - steady_most: f32 = 0, // the highest over other prompts' first reply rows - other_most: f32 = 0, // the highest over every other row read - fires: usize = 0, // rows it must stay silent on where it is above zero -}; - -/// Slot j's neuron fitted on its read rows, copied side by side first (a failure: zero, its slot last in line). -pub fn fitLayer(gpa: std.mem.Allocator, rows: []const u16, kinds: []const Kind, slots: usize, j: usize, d: usize, u: []f32, out: *Fit) void { - const own = gpa.alloc(u16, kinds.len * d) catch { - out.* = .{ .fires = std.math.maxInt(usize) }; - return; - }; - defer gpa.free(own); - const xs = gpa.alloc([]const u16, kinds.len) catch { - out.* = .{ .fires = std.math.maxInt(usize) }; - return; - }; - defer gpa.free(xs); - for (xs, 0..) |*x, i| { - @memcpy(own[i * d ..][0..d], rows[(i * slots + j) * d ..][0..d]); - x.* = own[i * d ..][0..d]; - } - out.* = fit(gpa, xs, kinds, d, u, false, fit_steps, 0) catch blk: { - @memset(u, 0); - break :blk .{ .fires = std.math.maxInt(usize) }; - }; -} - -/// Fits `u` on `xs` (from `u` if `warm`): at least 1 on fact rows, at most -margin elsewhere; first `fixed` rows kept. -pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, d: usize, u: []f32, warm: bool, steps: usize, fixed: usize) !Fit { - const n = kinds.len; - var scale: f32 = 0; - for (xs) |x| scale += @sqrt(squares(x)); - scale /= @floatFromInt(@max(n, 1)); - const inv = 1 / scale; - var counts: [5]f32 = @splat(0); - for (kinds) |k| counts[@backingInt(k)] += 1; - const w = try gpa.alloc(f32, 8 * d); - defer gpa.free(w); - @memset(w, 0); - const mean_fact = w[0..d]; - const mean_rest = w[d..][0..d]; - const m = w[2 * d ..][0..d]; - const v = w[3 * d ..][0..d]; - const g = w[4 * d ..][0..d]; - const parts = w[5 * d ..][0 .. 3 * d]; // each kind's rows on the wrong side, their hinges' sum: fact, steady, other - if (warm) { - for (u) |*o| o.* *= scale; - } else { - // a start: the fact's mean less the mean of the rows it stays silent on, sized so the fact's mean is 1 - for (kinds, xs) |k, x| switch (k) { - .fact => axpyRow(mean_fact, inv / @max(counts[0], 1), x), - .steady, .other => axpyRow(mean_rest, inv / @max(counts[2] + counts[3], 1), x), - .held, .none => {}, - }; - for (u, mean_fact, mean_rest) |*o, a, b| o.* = a - b; - const at_fact = subspace.dot(u, mean_fact); - if (at_fact > 0) for (u) |*o| { - o.* /= at_fact; - }; - } - const basis = try gpa.alloc(f32, 2 * fixed * d); - defer gpa.free(basis); - const own = basis[fixed * d ..]; - for (0..fixed) |i| for (own[i * d ..][0..d], xs[i]) |*o, b| { - o.* = bf(b) * inv; - }; - const rank = orthonormal(basis[0 .. fixed * d], own, d); - for (1..steps + 1) |s| { - // each kind weighed by its rows on the wrong side only: a few rows that still slip are pushed as hard as many - @memset(parts, 0); - var wrong: [3]f32 = @splat(0); - for (kinds, xs) |k, x| { - const z = dotRow(u, x) * inv; - switch (k) { - .fact => if (z < 1) { - wrong[0] += 1; - axpyRow(parts[0..d], -2 * (1 - z), x); - }, - .steady, .other => if (z > -margin) { - const at: usize = if (k == .steady) 1 else 2; - wrong[at] += 1; - axpyRow(parts[at * d ..][0..d], 2 * (z + margin), x); - }, - .held, .none => {}, - } - } - @memset(g, 0); - for (0..3) |at| subspace.axpy(g, inv / @max(wrong[at], 1), parts[at * d ..][0..d]); - const tt: f32 = @floatFromInt(s); - for (u, m, v, g) |ui, *mi, *vi, *gi| { - const gg = gi.* + 2e-4 * ui; - mi.* = 0.9 * mi.* + 0.1 * gg; - vi.* = 0.999 * vi.* + 0.001 * gg * gg; - gi.* = fit_rate * (mi.* / (1 - std.math.pow(f32, 0.9, tt))) / (@sqrt(vi.* / (1 - std.math.pow(f32, 0.999, tt))) + 1e-8); - } - // the step, less its part along the fixed rows' span - for (0..rank) |j| { - const b = basis[j * d ..][0..d]; - subspace.axpy(g, -subspace.dot(g, b), b); - } - for (u, g) |*ui, st| ui.* -= st; - } - var f: Fit = .{ .fact_least = std.math.inf(f32), .steady_most = -std.math.inf(f32), .other_most = -std.math.inf(f32) }; - for (kinds, xs) |k, x| { - const zi = dotRow(u, x) * inv; - switch (k) { - .fact => { - f.fact_least = @min(f.fact_least, zi); - f.fact_on += @floatFromInt(@intFromBool(zi >= 0.5)); - }, - .held => { - f.held_mean += if (zi > 0) zi * zi else 0; - f.held_on += @floatFromInt(@intFromBool(zi >= 0.5)); - }, - .steady => { - f.steady_most = @max(f.steady_most, zi); - f.fires += @intFromBool(zi > 0); - }, - .other => { - f.other_most = @max(f.other_most, zi); - f.fires += @intFromBool(zi > 0); - }, - .none => {}, - } - } - f.fact_on /= @max(counts[0], 1); - f.held_on /= @max(counts[1], 1); - f.held_mean /= @max(counts[1], 1); - for (u) |*o| o.* /= scale; - return f; -} - -const V = @Vector(8, f32); - -/// Eight bf16 values widened to f32, exactly. -inline fn widen8(b: []const u16) V { - const raw: @Vector(8, u32) = @as(@Vector(8, u16), b[0..8].*); - return @bitCast(raw << @splat(16)); -} - -fn bf(b: u16) f32 { - return @bitCast(@as(u32, b) << 16); -} - -/// a . b for f32 `a` and bf16 `b`: four sums of eight lanes, so no add waits on the one before it. -fn dotRow(a: []const f32, b: []const u16) f32 { - var acc: [4]V = @splat(@splat(0)); - var i: usize = 0; - while (i + 32 <= a.len) : (i += 32) { - inline for (&acc, 0..) |*x, k| x.* += @as(V, a[i + 8 * k ..][0..8].*) * widen8(b[i + 8 * k ..]); - } - while (i + 8 <= a.len) : (i += 8) acc[0] += @as(V, a[i..][0..8].*) * widen8(b[i..]); - var s = @reduce(.Add, (acc[0] + acc[1]) + (acc[2] + acc[3])); - while (i < a.len) : (i += 1) s += a[i] * bf(b[i]); - return s; -} - -/// y += c b for bf16 `b`. -fn axpyRow(y: []f32, c: f32, b: []const u16) void { - const cv: V = @splat(c); - var i: usize = 0; - while (i + 8 <= y.len) : (i += 8) y[i..][0..8].* = @as(V, y[i..][0..8].*) + cv * widen8(b[i..]); - while (i < y.len) : (i += 1) y[i] += c * bf(b[i]); -} - -/// b . b for bf16 `b`. -fn squares(b: []const u16) f32 { - var acc: V = @splat(0); - var i: usize = 0; - while (i + 8 <= b.len) : (i += 8) { - const x = widen8(b[i..]); - acc += x * x; - } - var s = @reduce(.Add, acc); - while (i < b.len) : (i += 1) s += bf(b[i]) * bf(b[i]); - return s; -} - -/// An orthonormal basis of `rows` ([k, d]) into `basis` by Gram-Schmidt run twice, rows in the span left out; its rank. -fn orthonormal(basis: []f32, rows: []const f32, d: usize) usize { - var rank: usize = 0; - for (0..rows.len / d) |i| { - const q = basis[rank * d ..][0..d]; - @memcpy(q, rows[i * d ..][0..d]); - const before = @sqrt(subspace.dot(q, q)); - for (0..2) |_| for (0..rank) |j| { - const b = basis[j * d ..][0..d]; - subspace.axpy(q, -subspace.dot(q, b), b); - }; - const len = @sqrt(subspace.dot(q, q)); - if (len <= 1e-3 * before) continue; - for (q) |*e| e.* /= len; - rank += 1; - } - return rank; -} - -pub fn dotBf16(a: []const f32, b: []const u16) f32 { - var s: f32 = 0; - for (a, b) |x, y| s += x * @as(f32, @bitCast(@as(u32, y) << 16)); - return s; -} - -pub fn normBf16(b: []const u16) f32 { - var s: f32 = 0; - for (b) |y| { - const f: f32 = @bitCast(@as(u32, y) << 16); - s += f * f; - } - return @sqrt(s); -} - -test "a neuron fires on its fact's rows and stays at zero on the rest; fitted again, it goes quiet on a new fact's" { - const gpa = std.testing.allocator; - const d = 64; - var prng = std.Random.DefaultPrng.init(9); - const r = prng.random(); - // a shared offset every row has (as hidden states do), and a direction each fact's rows lean along - var common: [d]f32 = undefined; - var fact_dir: [d]f32 = undefined; - var new_dir: [d]f32 = undefined; - for (&common, &fact_dir, &new_dir) |*c, *f, *g| { - c.* = 1 + r.floatNorm(f32) * 0.1; - f.* = r.floatNorm(f32); - g.* = r.floatNorm(f32); - } - const n_fact = 12; - const n_rest = 200; - const n_new = 12; - const rows = try gpa.alloc(u16, (n_fact + n_rest + n_new) * d); - defer gpa.free(rows); - for (0..n_fact + n_rest + n_new) |i| { - const lean: ?*const [d]f32 = if (i < n_fact) &fact_dir else if (i >= n_fact + n_rest) &new_dir else null; - for (0..d) |k| { - var v = common[k] + r.floatNorm(f32) * 0.5; - if (lean) |dir| v += 1.5 * dir[k]; - rows[i * d + k] = @truncate(@as(u32, @bitCast(v)) >> 16); - } - } - const xs = try gpa.alloc([]const u16, n_fact + n_rest); - defer gpa.free(xs); - const kinds = try gpa.alloc(Kind, n_fact + n_rest); - defer gpa.free(kinds); - for (xs, kinds, 0..) |*x, *k, i| { - x.* = rows[i * d ..][0..d]; - k.* = if (i < n_fact) .fact else .other; - } - var u: [d]f32 = undefined; - const first = try fit(gpa, xs, kinds, d, &u, false, fit_steps, 0); - try std.testing.expectEqual(@as(f32, 1), first.fact_on); - try std.testing.expectEqual(@as(usize, 0), first.fires); - // the new fact's rows, which nothing told it about, are where it is fitted again to stay quiet - const all = try gpa.alloc([]const u16, n_fact + n_rest + n_new); - defer gpa.free(all); - const kinds2 = try gpa.alloc(Kind, n_fact + n_rest + n_new); - defer gpa.free(kinds2); - for (all, kinds2, 0..) |*x, *k, i| { - x.* = rows[i * d ..][0..d]; - k.* = if (i < n_fact) .fact else if (i < n_fact + n_rest) .other else .steady; - } - const before = try gpa.dupe(f32, &u); - defer gpa.free(before); - const again = try fit(gpa, all, kinds2, d, &u, true, fit_steps / 2, n_fact); - try std.testing.expectEqual(@as(f32, 1), again.fact_on); - try std.testing.expectEqual(@as(usize, 0), again.fires); - try std.testing.expect(again.steady_most <= 0); - // its own rows were held fixed: each reads as it did before the refit - for (all[0..n_fact]) |x| try std.testing.expectApproxEqAbs(dotBf16(before, x), dotBf16(&u, x), 1e-3); -} diff --git a/zig/src/families/nemotron/pocket_forget.zig b/zig/src/families/nemotron/pocket_forget.zig deleted file mode 100644 index 014a0b571ae..00000000000 --- a/zig/src/families/nemotron/pocket_forget.zig +++ /dev/null @@ -1,158 +0,0 @@ -//! A fact deleted on request: its neurons' inputs zeroed, their layers rounded as a save writes them, kept to put back. -const std = @import("std"); -const pocket = @import("pocket.zig"); - -/// What the last delete changed, bit for bit as it was: whole layers' neurons and counts, every neuron's record. -pub const Kept = struct { - held: bool = false, // a delete not yet written by a save nor put back - stale: bool = false, // put back in memory, but a layer's upload failed: kept until the device takes them all - slots: std.ArrayList(usize) = .empty, // the pocket slots it changed - up: std.ArrayList(f32) = .empty, // [slots, neurons, D]: their input weights before - down: std.ArrayList(f32) = .empty, // [slots, neurons, D]: their outputs before - used: std.ArrayList(usize) = .empty, // [slots]: their counts before - learned: std.ArrayList(pocket.Learned) = .empty, // the session's neuron records before - learned_before: usize = 0, - marks: usize = 0, // retired lessons before - - pub fn deinit(k: *Kept, gpa: std.mem.Allocator) void { - inline for (.{ "slots", "up", "down", "used", "learned" }) |f| @field(k, f).deinit(gpa); - } - - fn clear(k: *Kept) void { - inline for (.{ "slots", "up", "down", "used", "learned" }) |f| @field(k, f).clearRetainingCapacity(); - k.held = false; - k.stale = false; - } -}; - -/// Whether a delete waits to be written: a save then writes the pocket even when nothing is left in it. -pub fn pending(p: anytype) bool { - return p.forgot.held; -} - -/// Whether a put-back is in memory but not yet on the device: replies are refused until `unforget` lands it. -pub fn stale(p: anytype) bool { - return p.forgot.stale; -} - -/// The last delete written into the shards: nothing is left to put back. -pub fn settle(p: anytype) void { - p.forgot.clear(); -} - -/// Neurons `gone` names that hold anything silenced, their layers rounded, freed at the top; how many held anything. -pub fn forget(p: anytype, t: anytype, host: anytype, gone: []const [2]u16) !usize { - try p.load(t, host); - const d = t.config().hidden; - const n = pocket.neurons * d; - const k = &p.forgot; - // a put-back the device has not taken yet is never dropped for a new delete - if (k.stale) return error.PutBackNotOnDevice; - k.clear(); - var held: usize = 0; - for (gone) |g| { - const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; - if (g[1] >= p.used.items[slot] or std.mem.allEqual(f32, p.neuron(p.up.items, slot, g[1], d), 0)) continue; - held += 1; - if (std.mem.indexOfScalar(usize, k.slots.items, slot) == null) try k.slots.append(p.gpa, slot); - } - // a replaced fact's neurons are zero already: nothing changes, nothing is kept - if (held == 0) return 0; - for (k.slots.items) |slot| { - try k.up.appendSlice(p.gpa, p.up.items[slot * n ..][0..n]); - try k.down.appendSlice(p.gpa, p.down.items[slot * n ..][0..n]); - try k.used.append(p.gpa, p.used.items[slot]); - } - try k.learned.appendSlice(p.gpa, p.learned.items); - // everything that can fail before the pocket moves is done here; anything that fails after puts it all back - try p.retired_lessons.ensureUnusedCapacity(p.gpa, p.learned.items.len); // a lesson at most for each record - k.learned_before = p.learned_before; - k.marks = p.retired_lessons.items.len; - k.held = true; - cut(p, t, host, gone) catch |e| { - // put back whole; if the device cannot take it, that is the failure to report, the snapshot kept - _ = unforget(p, t, host) catch |back| { - std.log.warn("slide pocket: a delete failed ({t}), and its put-back did not reach the device ({t})", .{ e, back }); - return back; - }; - return e; - }; - std.log.info("slide pocket: {d} neurons of a deleted fact zeroed in {d} layers", .{ held, k.slots.items.len }); - return held; -} - -/// The cut itself, after the snapshot: input weights zeroed, records out, layers rounded, freed and uploaded. -fn cut(p: anytype, t: anytype, host: anytype, gone: []const [2]u16) !void { - const d = t.config().hidden; - const n = pocket.neurons * d; - const k = &p.forgot; - for (gone) |g| { - const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; - if (g[1] >= p.used.items[slot]) continue; - // its input weights zeroed, so it never fires; its output stays, so the 4-bit groups it shares keep every bit - @memset(p.neuron(p.up.items, slot, g[1], d), 0); - // its record goes, so no later fact on the neuron is refitted as this one; its lesson's answers retire - var i: usize = 0; - while (i < p.learned.items.len) { - const e = p.learned.items[i]; - if (e.slot != slot or e.neuron != g[1]) { - i += 1; - continue; - } - if (std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) == null) p.retired_lessons.appendAssumeCapacity(e.lesson); - _ = p.learned.orderedRemove(i); - if (i < p.learned_before) p.learned_before -= 1; - } - } - for (k.slots.items) |slot| { - // the layer as its next save writes it, so the checks after this read what the shards will hold - try host.pocketRound(p.up.items[slot * n ..][0..n], p.down.items[slot * n ..][0..n]); - try settled(p.gpa, host, p.up.items[slot * n ..][0..n], p.down.items[slot * n ..][0..n]); - // neurons at the top whose input weights are zero are free; one below a kept neuron stays taken - while (p.used.items[slot] > 0 and std.mem.allEqual(f32, p.neuron(p.up.items, slot, p.used.items[slot] - 1, d), 0)) p.used.items[slot] -= 1; - try p.upload(t, host, slot); - } -} - -/// A rounded layer that a save would round to the same bits, else error.LayerRoundsAgain, so the delete is put back. -fn settled(gpa: std.mem.Allocator, host: anytype, up: []const f32, down: []const f32) !void { - const again = try gpa.alloc(f32, up.len + down.len); - defer gpa.free(again); - @memcpy(again[0..up.len], up); - @memcpy(again[up.len..], down); - try host.pocketRound(again[0..up.len], again[up.len..]); - const same = std.mem.eql(u8, std.mem.sliceAsBytes(again[0..up.len]), std.mem.sliceAsBytes(up)) and std.mem.eql(u8, std.mem.sliceAsBytes(again[up.len..]), std.mem.sliceAsBytes(down)); - if (!same) return error.LayerRoundsAgain; -} - -/// The last delete undone bit for bit; a layer the device does not take keeps the snapshot, and a call again retries. -pub fn unforget(p: anytype, t: anytype, host: anytype) !usize { - const k = &p.forgot; - if (!k.held) return 0; - try p.load(t, host); - try p.learned.ensureTotalCapacity(p.gpa, k.learned.items.len); - // the pocket whole as it was before any layer goes to the forward, so a failed upload leaves no layer half put back - const n = pocket.neurons * t.config().hidden; - for (k.slots.items, 0..) |slot, j| { - @memcpy(p.up.items[slot * n ..][0..n], k.up.items[j * n ..][0..n]); - @memcpy(p.down.items[slot * n ..][0..n], k.down.items[j * n ..][0..n]); - p.used.items[slot] = k.used.items[j]; - } - p.learned.clearRetainingCapacity(); - p.learned.appendSliceAssumeCapacity(k.learned.items); - p.learned_before = k.learned_before; - p.retired_lessons.shrinkRetainingCapacity(k.marks); - const back = k.slots.items.len; - var failed: ?anyerror = null; - for (k.slots.items) |slot| p.upload(t, host, slot) catch |e| { - failed = failed orelse e; - }; - if (failed) |e| { - k.stale = true; - std.log.warn("slide pocket: a deleted fact's {d} layers are put back in memory, but not all on the device ({t}): replies are refused until they are", .{ back, e }); - return error.PutBackNotOnDevice; - } - k.clear(); - std.log.info("slide pocket: a deleted fact's {d} layers put back as they were", .{back}); - return back; -} diff --git a/zig/src/families/nemotron/pocket_forget_test.zig b/zig/src/families/nemotron/pocket_forget_test.zig deleted file mode 100644 index 5500a6ef658..00000000000 --- a/zig/src/families/nemotron/pocket_forget_test.zig +++ /dev/null @@ -1,464 +0,0 @@ -//! A delete on a pocket of three facts: their neurons zeroed and rounded, freed at the top, put back bit for bit. -const std = @import("std"); -const cfg = @import("config.zig"); -const pocket = @import("pocket.zig"); -const forgetting = @import("pocket_forget.zig"); -const whole = @import("whole.zig"); -const examples = @import("lesson_examples.zig"); -const Shards = @import("pocket_shards.zig").Io(struct { - pub const shard_edit = @import("../../core/shard_edit.zig"); - pub const safetensors = @import("../../core/safetensors.zig"); - pub const affine4_host = @import("../../core/affine4_host.zig"); -}); - -const d = 64; -const layers = 4; // every MoE layer but the last holds a pocket: slots 0, 1 and 2 -const width = pocket.neurons * d; - -/// The trainer as the pocket reads it: only the model's shape. -const Trainer = struct { - c: cfg.Config, - - pub fn config(t: *const Trainer) cfg.Config { - return t.c; - } -}; - -const P = pocket.Pocket(Trainer); - -/// The backend: the pocket as the shards loaded it, and each layer's live copy as the forward reads it. -const Device = struct { - loaded_up: [layers][width]f32 = @splat(@splat(0)), - loaded_down: [layers][width]f32 = @splat(@splat(0)), - loaded_used: [layers]usize = @splat(0), - up: [layers][width]f32 = @splat(@splat(0)), - down: [layers][width]f32 = @splat(@splat(0)), - used: [layers]usize = @splat(0), - uploads: usize = 0, - saves: usize = 0, - gpa: std.mem.Allocator = std.testing.allocator, // what rounding allocates from - fail_at: usize = 0, // the upload, counted from one, that fails once (0: none) - fail_from: usize = 0, // the upload, counted from one, from which every upload fails (0: none) - failing: bool = false, // every upload fails - - pub fn pocketRead(h: *Device, l: usize, up: []f32, down: []f32) usize { - @memcpy(up, &h.loaded_up[l]); - @memcpy(down, &h.loaded_down[l]); - h.up[l] = h.loaded_up[l]; - h.down[l] = h.loaded_down[l]; - h.used[l] = h.loaded_used[l]; - return h.loaded_used[l]; - } - - pub fn pocket(h: *Device, l: usize, up: []const f32, down: []const f32, used: usize) !void { - if (h.failing or h.uploads + 1 == h.fail_at or (h.fail_from > 0 and h.uploads + 1 >= h.fail_from)) { - h.uploads += 1; - return error.UploadFailed; - } - @memcpy(&h.up[l], up); - @memcpy(&h.down[l], down); - h.used[l] = used; - h.uploads += 1; - } - - pub fn pocketRound(h: *Device, up: []f32, down: []f32) !void { - return Shards.round(h.gpa, d, up, down); - } -}; - -/// The learner's host as a save reaches it: `Device` above, and a write into the shards that counts itself. -const SaveHost = struct { - pub const Ctx = *Device; - - pub fn seconds(_: std.Io) f64 { - return 0; - } - - pub fn pocket(h: Ctx, l: usize, up: []const f32, down: []const f32, used: usize) !void { - return h.pocket(l, up, down, used); - } - - pub fn pocketRead(h: Ctx, l: usize, up: []f32, down: []f32) usize { - return h.pocketRead(l, up, down); - } - - pub fn pocketSave(h: Ctx, _: std.mem.Allocator, _: std.Io, _: []const usize, _: usize, _: []f32, _: []f32) !usize { - h.saves += 1; - return 0; - } -}; - -/// The learner as `whole.save` reads it: a pocket lesson kept, and its pocket. -const Learner = struct { - pub const Host = SaveHost; - method: whole.Method = .pocket, - pocketed: bool = false, - kept_rounds: u32 = 1, - pockets: P = .{ .gpa = std.testing.allocator, .mode = .auto }, - trainer: ?*Trainer, - b: *Device, - gpa: std.mem.Allocator = std.testing.allocator, - io: std.Io = std.testing.io, - owned: examples.Lesson = .{}, - - pub fn recalls(_: *Learner, _: []const examples.Example, _: bool) !bool { - return true; - } -}; - -/// Three facts as saved: A at (0, 0) and (1, 0); B at (0, 1) and (2, 0); C at (0, 2) and (1, 1), lessons 0, 1, 2. -fn three(h: *Device, p: *P, t: *Trainer) !void { - var prng = std.Random.DefaultPrng.init(11); - const r = prng.random(); - const held = [_][3]usize{ .{ 0, 0, 0 }, .{ 1, 0, 0 }, .{ 0, 1, 1 }, .{ 2, 0, 1 }, .{ 0, 2, 2 }, .{ 1, 1, 2 } }; - for (held) |x| { - for (h.loaded_up[x[0]][x[1] * d ..][0..d], h.loaded_down[x[0]][x[1] * d ..][0..d]) |*u, *v| { - u.* = r.floatNorm(f32) * 0.05; - v.* = r.floatNorm(f32) * 0.2; - } - h.loaded_used[x[0]] = @max(h.loaded_used[x[0]], x[1] + 1); - } - // the shards hold 4-bit values: the pocket as a save left it - for (0..layers) |l| try Shards.round(std.testing.allocator, d, &h.loaded_up[l], &h.loaded_down[l]); - try p.load(t, h); - for (held, 0..) |x, i| try p.learned.append(p.gpa, .{ .slot = x[0], .neuron = x[1], .key = .reply, .start = i, .count = 1, .subject = 0, .lesson = @intCast(x[2]) }); - p.learned_before = 4; // C, the last lesson, found A's and B's -} - -fn trainer() Trainer { - var c: cfg.Config = .{ .hidden = d, .vocab = 16, .layers = layers, .mamba_heads = 1, .mamba_head_dim = 1, .groups = 1, .state = 1, .conv_kernel = 4, .heads = 1, .kv_heads = 1, .head_dim = 1, .experts = 1, .top_k = 1, .expert_width = 64, .shared_width = 64, .routed_scaling = 1, .eps = 1e-5 }; - for (0..layers) |l| c.kinds[l] = .moe; - return .{ .c = c }; -} - -const b_neurons = [_][2]u16{ .{ 0, 1 }, .{ 2, 0 } }; - -test "a deleted fact's input weights go to zero, every output bit stays, its layers rounded as a save writes them" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // a lesson since the last save moved C's outputs in layer 0 off the 4-bit grid - for (p.neuron(p.down.items, 0, 2, d)) |*v| v.* *= 1.001; - const before_up = try std.testing.allocator.dupe(f32, p.up.items); - defer std.testing.allocator.free(before_up); - // what layer 0 is to hold: B's input weights zeroed, then the layer rounded on its own - var want_up: [width]f32 = p.up.items[0..width].*; - var want_down: [width]f32 = p.down.items[0..width].*; - @memset(want_up[1 * d ..][0..d], 0); - try Shards.round(std.testing.allocator, d, &want_up, &want_down); - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expect(forgetting.pending(&p)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&want_up), std.mem.sliceAsBytes(p.up.items[0..width])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&want_down), std.mem.sliceAsBytes(p.down.items[0..width])); - try std.testing.expect(std.mem.allEqual(f32, p.neuron(p.up.items, 2, 0, d), 0)); - // layer 2 as saved: B's input weights zero, every output bit as it was, B's own too, so no 4-bit group moves - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&h.loaded_down[2]), std.mem.sliceAsBytes(p.down.items[2 * width ..][0..width])); - // A's and C's input weights keep every bit; layer 1 was not touched at all - for ([_][2]usize{ .{ 0, 0 }, .{ 0, 2 }, .{ 1, 0 }, .{ 1, 1 } }) |x| try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(before_up[(x[0] * pocket.neurons + x[1]) * d ..][0..d]), std.mem.sliceAsBytes(p.neuron(p.up.items, x[0], x[1], d))); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&h.loaded_down[1]), std.mem.sliceAsBytes(p.down.items[width..][0..width])); - // layer 0's neuron 1 sits below C's, so it stays taken; layer 2 is empty again - try std.testing.expectEqualSlices(usize, &.{ 3, 2, 0 }, p.used.items); - // the forward reads exactly the pocket, and only the two layers changed were sent - try std.testing.expectEqual(@as(usize, 2), h.uploads); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(p.down.items[0..width]), std.mem.sliceAsBytes(&h.down[0])); - try std.testing.expectEqual(@as(usize, 0), h.used[2]); - // B's records are gone, so no later fact on its freed neuron is refitted as B; its lesson's answers retire - try std.testing.expectEqual(@as(usize, 4), p.learned.items.len); - for (p.learned.items) |e| try std.testing.expect(e.lesson != 1); - try std.testing.expectEqual(@as(usize, 2), p.learned_before); - try std.testing.expectEqualSlices(u32, &.{1}, p.retired_lessons.items); - forgetting.settle(&p); - try std.testing.expect(!forgetting.pending(&p)); -} - -test "a delete put back restores every bit it changed, in the pocket and in the forward" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // C's outputs off the grid, as a lesson not yet saved leaves them: the delete's rounding moves them - for (p.neuron(p.down.items, 0, 2, d)) |*v| v.* *= 1.001; - try p.upload(&t, &h, 0); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const used = try gpa.dupe(usize, p.used.items); - defer gpa.free(used); - const learned = try gpa.dupe(pocket.Learned, p.learned.items); - defer gpa.free(learned); - const live = h; - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expectEqual(@as(usize, 2), try forgetting.unforget(&p, &t, &h)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqualSlices(usize, used, p.used.items); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(learned), std.mem.sliceAsBytes(p.learned.items)); - try std.testing.expectEqual(@as(usize, 4), p.learned_before); - try std.testing.expectEqual(@as(usize, 0), p.retired_lessons.items.len); - for (0..layers - 1) |l| { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[l]), std.mem.sliceAsBytes(&h.up[l])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.down[l]), std.mem.sliceAsBytes(&h.down[l])); - try std.testing.expectEqual(live.used[l], h.used[l]); - } - try std.testing.expect(!forgetting.pending(&p)); - // with nothing to put back, a second put-back changes nothing - const sent = h.uploads; - try std.testing.expectEqual(@as(usize, 0), try forgetting.unforget(&p, &t, &h)); - try std.testing.expectEqual(sent, h.uploads); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} - -test "a replaced fact's neurons are zero already: nothing to delete, nothing changed or kept" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - // a newer fact replaced A: its neurons zeroed where they sit, their places taken - try p.retire(&t, &h, &.{ .{ 0, 0 }, .{ 1, 0 } }); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const sent = h.uploads; - try std.testing.expectEqual(@as(usize, 0), try forgetting.forget(&p, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 } })); - try std.testing.expect(!forgetting.pending(&p)); - try std.testing.expectEqual(sent, h.uploads); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} - -test "deleting every fact empties the pocket, and the delete still waits for a save to write it" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - try std.testing.expectEqual(@as(usize, 6), try forgetting.forget(&p, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 }, .{ 0, 1 }, .{ 2, 0 }, .{ 0, 2 }, .{ 1, 1 } })); - try std.testing.expect(p.empty()); - try std.testing.expect(forgetting.pending(&p)); - for (0..layers - 1) |l| try std.testing.expect(std.mem.allEqual(f32, &h.up[l], 0)); - try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2 }, p.retired_lessons.items); - try std.testing.expectEqual(@as(usize, 0), p.learned_before); -} - -test "a save after the last fact is deleted writes the emptied pocket; an untaught one stays unwritten" { - var t = trainer(); - var h: Device = .{}; - // a model never taught: nothing in the pocket, nothing written - var untaught: Learner = .{ .trainer = &t, .b = &h }; - defer untaught.pockets.deinit(); - try untaught.pockets.load(&t, &h); - try std.testing.expect(try whole.save(&untaught)); - try std.testing.expectEqual(@as(usize, 0), h.saves); - var l: Learner = .{ .trainer = &t, .b = &h }; - defer l.pockets.deinit(); - try three(&h, &l.pockets, &t); - _ = try forgetting.forget(&l.pockets, &t, &h, &.{ .{ 0, 0 }, .{ 1, 0 }, .{ 0, 1 }, .{ 2, 0 }, .{ 0, 2 }, .{ 1, 1 } }); - try std.testing.expect(try whole.save(&l)); - try std.testing.expectEqual(@as(usize, 1), h.saves); - try std.testing.expect(!forgetting.pending(&l.pockets)); -} - -/// The pocket's state a delete may change, copied: its weights, counts, records and retired lessons. -const Copy = struct { - up: []f32, - down: []f32, - used: []usize, - learned: []pocket.Learned, - learned_before: usize, - retired: []u32, - - fn of(p: *const P) !Copy { - const a = std.testing.allocator; - return .{ .up = try a.dupe(f32, p.up.items), .down = try a.dupe(f32, p.down.items), .used = try a.dupe(usize, p.used.items), .learned = try a.dupe(pocket.Learned, p.learned.items), .learned_before = p.learned_before, .retired = try a.dupe(u32, p.retired_lessons.items) }; - } - - fn expectSame(c: Copy, p: *const P) !void { - try c.expectFields(p); - try std.testing.expect(!forgetting.pending(p)); - } - - /// The pocket in memory as copied, its snapshot kept or not. - fn expectFields(c: Copy, p: *const P) !void { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.down), std.mem.sliceAsBytes(p.down.items)); - try std.testing.expectEqualSlices(usize, c.used, p.used.items); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(c.learned), std.mem.sliceAsBytes(p.learned.items)); - try std.testing.expectEqual(c.learned_before, p.learned_before); - try std.testing.expectEqualSlices(u32, c.retired, p.retired_lessons.items); - } - - fn free(c: Copy) void { - const a = std.testing.allocator; - a.free(c.up); - a.free(c.down); - a.free(c.used); - a.free(c.learned); - a.free(c.retired); - } -}; - -/// The forward's layers as the device holds them, for the pocket's slots. -fn expectLive(before: *const Device, now: *const Device) !void { - for (0..layers - 1) |l| { - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&before.up[l]), std.mem.sliceAsBytes(&now.up[l])); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&before.down[l]), std.mem.sliceAsBytes(&now.down[l])); - try std.testing.expectEqual(before.used[l], now.used[l]); - } -} - -test "an allocation or an upload that fails anywhere in a delete leaves the pocket and the forward as they were" { - var t = trainer(); - // each allocation of the delete in turn fails (the pocket's and the rounding's), until it goes through - var failures: usize = 0; - while (true) : (failures += 1) { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{ .gpa = failing.allocator() }; - var p: P = .{ .gpa = failing.allocator(), .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - failing.fail_index = failing.alloc_index + failures; - if (forgetting.forget(&p, &t, h, &b_neurons)) |n| { - try std.testing.expectEqual(@as(usize, 2), n); - break; - } else |e| try std.testing.expectEqual(error.OutOfMemory, e); - try before.expectSame(&p); - try expectLive(live, h); - } - try std.testing.expect(failures >= 5); - // an upload that fails once, at either changed layer: the pocket and the forward put back - for ([_]usize{ 1, 2 }) |at| { - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - h.fail_at = h.uploads + at; - try std.testing.expectError(error.UploadFailed, forgetting.forget(&p, &t, h, &b_neurons)); - try before.expectSame(&p); - try expectLive(live, h); - // and a retry goes through - try std.testing.expectEqual(@as(usize, 2), try forgetting.forget(&p, &t, h, &b_neurons)); - } - // a device that takes no upload: put back in memory, the snapshot kept and the pocket stale until one lands - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(h, &p, &t); - const before = try Copy.of(&p); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - h.failing = true; - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&p, &t, h, &b_neurons)); - try before.expectFields(&p); - try std.testing.expect(forgetting.stale(&p) and forgetting.pending(&p)); - h.failing = false; - try std.testing.expectEqual(@as(usize, 2), try forgetting.unforget(&p, &t, h)); - try before.expectSame(&p); - try expectLive(live, h); -} - -test "a put-back the device stops taking after one layer is cut keeps its snapshot, refuses, and lands once it can" { - var t = trainer(); - const h = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(h); - h.* = .{}; - var l: Learner = .{ .trainer = &t, .b = h }; - defer l.pockets.deinit(); - try three(h, &l.pockets, &t); - const before = try Copy.of(&l.pockets); - defer before.free(); - const live = try std.testing.allocator.create(Device); - defer std.testing.allocator.destroy(live); - live.* = h.*; - // the first changed layer (0) takes its cut; from the second upload on, the device takes nothing, put-back too - h.fail_from = h.uploads + 2; - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&l.pockets, &t, h, &b_neurons)); - // memory is as it was and the snapshot is kept, while the device still holds layer 0 cut and layer 2 as it was - try before.expectFields(&l.pockets); - try std.testing.expect(whole.stale(&l) and forgetting.pending(&l.pockets)); - try std.testing.expect(std.mem.allEqual(f32, h.up[0][1 * d ..][0..d], 0)); - try std.testing.expect(!std.mem.allEqual(f32, live.up[0][1 * d ..][0..d], 0)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[2]), std.mem.sliceAsBytes(&h.up[2])); - // until it lands, another delete is refused and a retry fails the same way, the snapshot kept - try std.testing.expectError(error.PutBackNotOnDevice, forgetting.forget(&l.pockets, &t, h, &b_neurons)); - try std.testing.expectError(error.PutBackNotOnDevice, whole.heal(&l)); - try std.testing.expect(whole.stale(&l)); - try before.expectFields(&l.pockets); - // the device takes uploads again: the retry lands every layer, and nothing is left to put back - h.fail_from = 0; - try whole.heal(&l); - try std.testing.expect(!whole.stale(&l)); - try before.expectSame(&l.pockets); - try expectLive(live, h); -} - -test "a delete whose cut layer would round to other values when saved is put back whole, nothing changed" { - var t = trainer(); - var h: Device = .{}; - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - try three(&h, &p, &t); - var prng = std.Random.DefaultPrng.init(3); - const r = prng.random(); - // slot 0's neurons far from zero next to their spread, until its cut layer would move when a save rounds it again - var cut_up: [width]f32 = undefined; - var cut_down: [width]f32 = undefined; - var moves = false; - for (0..20) |_| { - const spread = std.math.pow(f32, 10, -4 + 6 * r.float(f32)); - const offset = spread * 256 * r.float(f32) * @as(f32, if (r.boolean()) 1 else -1); - for (p.up.items[0..width], p.down.items[0..width]) |*u, *v| { - u.* = offset + spread * r.floatNorm(f32); - v.* = -offset + spread * r.floatNorm(f32); - } - @memcpy(&cut_up, p.up.items[0..width]); - @memcpy(&cut_down, p.down.items[0..width]); - @memset(cut_up[1 * d ..][0..d], 0); // B's neuron at slot 0 - try Shards.round(std.testing.allocator, d, &cut_up, &cut_down); - const once_up = cut_up; - const once_down = cut_down; - try Shards.round(std.testing.allocator, d, &cut_up, &cut_down); - moves = !std.mem.eql(u8, std.mem.sliceAsBytes(&once_up), std.mem.sliceAsBytes(&cut_up)) or !std.mem.eql(u8, std.mem.sliceAsBytes(&once_down), std.mem.sliceAsBytes(&cut_down)); - if (moves) break; - } - try std.testing.expect(moves); - try p.upload(&t, &h, 0); - const gpa = std.testing.allocator; - const up = try gpa.dupe(f32, p.up.items); - defer gpa.free(up); - const down = try gpa.dupe(f32, p.down.items); - defer gpa.free(down); - const live = h; - try std.testing.expectError(error.LayerRoundsAgain, forgetting.forget(&p, &t, &h, &b_neurons)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(p.up.items)); - try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(p.down.items)); - for (0..layers - 1) |l| try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&live.up[l]), std.mem.sliceAsBytes(&h.up[l])); - try std.testing.expect(!forgetting.pending(&p)); - try std.testing.expectEqual(@as(usize, 6), p.learned.items.len); -} diff --git a/zig/src/families/nemotron/pocket_joint.zig b/zig/src/families/nemotron/pocket_joint.zig deleted file mode 100644 index 6bbe409f9c2..00000000000 --- a/zig/src/families/nemotron/pocket_joint.zig +++ /dev/null @@ -1,46 +0,0 @@ -//! Earlier facts on the open fact's subject fitted with it: MEMIT-Merge's one value a subject, a fact at a time. -const std = @import("std"); - -/// The earlier subject neurons the open fact shares its subject with, their replayed answers, their outputs as now. -pub fn find(p: anytype, d: usize) !void { - p.joint.clearRetainingCapacity(); - p.joint_down.clearRetainingCapacity(); - p.joint_answers.clearRetainingCapacity(); - if (!p.joining or p.split[1] == 0 or p.subjects.items.len == 0) return; - var group: std.ArrayList(u32) = .empty; - defer group.deinit(p.gpa); - for (p.learned.items[0..p.learned_before]) |e| { - if (e.key != .subject or std.mem.indexOfScalar(u32, p.subjects.items, e.subject) == null) continue; - if (std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) != null) continue; - if (std.mem.indexOfScalar(u32, group.items, e.lesson) == null) try group.append(p.gpa, e.lesson); - } - const replay: []const @TypeOf(p.answered[0]) = if (p.steady.len > 2) p.steady[2] else &.{}; - for (replay, 0..) |ex, i| { - if (i >= p.replay_lessons.len or std.mem.indexOfScalar(u32, group.items, p.replay_lessons[i]) == null) continue; - if (p.keyRow(ex, .subject) != null) try p.joint_answers.append(p.gpa, ex); - } - // without their answers to hold them, earlier outputs would only bend to the new fact - if (p.joint_answers.items.len == 0) return; - for (p.learned.items[0..p.learned_before]) |e| if (e.key == .subject and std.mem.indexOfScalar(u32, group.items, e.lesson) != null) { - try p.joint.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron, .key = .subject }); - try p.joint_down.appendSlice(p.gpa, p.neuron(p.down.items, e.slot, e.neuron, d)); - }; - std.log.info("slide pocket: {d} neurons of {d} earlier facts on its subject fitted with it, on {d} of their answers", .{ p.joint.items.len, group.items.len, p.joint_answers.items.len }); -} - -/// Their outputs as the fit starts, after the open fact's (which start at zero). -pub fn seed(p: anytype, d: usize) void { - const k = p.taken.items.len; - @memcpy(p.v.adam.items[k * d ..][0 .. p.joint.items.len * d], p.joint_down.items); -} - -/// The earlier neurons as they were before the open fact fitted them (its lesson undone). -pub fn putBack(p: anytype, t: anytype, host: anytype, d: usize) !void { - for (p.joint.items, 0..) |x, j| { - @memcpy(p.neuron(p.down.items, x.slot, x.neuron, d), p.joint_down.items[j * d ..][0..d]); - try p.upload(t, host, x.slot); - } - p.joint.clearRetainingCapacity(); - p.joint_down.clearRetainingCapacity(); - p.joint_answers.clearRetainingCapacity(); -} diff --git a/zig/src/families/nemotron/pocket_pack.zig b/zig/src/families/nemotron/pocket_pack.zig deleted file mode 100644 index ebed647bb02..00000000000 --- a/zig/src/families/nemotron/pocket_pack.zig +++ /dev/null @@ -1,42 +0,0 @@ -//! The pocket's passes with their sequences side by side: as many as one pass of the trainer holds, run together. -const std = @import("std"); -const train_mode = @import("train_mode.zig"); -const lesson_route = @import("lesson_route.zig"); -const Example = @import("lesson_examples.zig").Example; - -pub const Seq = train_mode.Seq; -pub const Result = train_mode.Result; -const Mode = train_mode.Mode; - -/// How many of `seqs`, from the first, one pass of trainer t holds: as many as fit, at least one. -pub fn fits(t: anytype, seqs: []const Seq) usize { - if (!t.packs()) return @min(seqs.len, 1); - var rows: usize = 0; - var n: usize = 0; - while (n < seqs.len and n < t.spans.len) : (n += 1) { - rows += seqs[n].ids.len - 1 - seqs[n].skip; - if (rows > t.pack and n > 0) break; - } - return n; -} - -/// The sequence an example makes, its pocket unscaled and nothing nudged. -pub fn seq(ex: Example) Seq { - return .{ .ids = ex.ids, .start = ex.start, .decide = ex.decide }; -} - -/// The turn every pocket pass takes: lessons of the model itself, no router deciding. -pub const turn: lesson_route.Turn = .{ .decide = 0, .bits = lesson_route.Acting.empty, .whole = true }; - -/// Each of `xs` read in `mode` in as few passes as hold them, each one's result into `out`. -pub fn read(gpa: std.mem.Allocator, t: anytype, xs: []const Example, mode: Mode, out: []Result) !void { - const seqs = try gpa.alloc(Seq, xs.len); - defer gpa.free(seqs); - for (seqs, xs) |*s, ex| s.* = seq(ex); - var at: usize = 0; - while (at < seqs.len) { - const n = fits(t, seqs[at..]); - try t.pass(seqs[at..][0..n], mode, turn, out[at..][0..n]); - at += n; - } -} diff --git a/zig/src/families/nemotron/pocket_prefix.zig b/zig/src/families/nemotron/pocket_prefix.zig deleted file mode 100644 index ca854f38eee..00000000000 --- a/zig/src/families/nemotron/pocket_prefix.zig +++ /dev/null @@ -1,100 +0,0 @@ -//! A pocket fact's answers' prompts run once: their rows before any of its neurons fires never change while it learns. -const std = @import("std"); -const pack = @import("pocket_pack.zig"); -const train_mode = @import("train_mode.zig"); -const dotBf16 = @import("pocket_fit.zig").dotBf16; - -const Seq = train_mode.Seq; -const Span = train_mode.Span; - -const least = 16; // rows a prefix must hold to be worth a slot - -/// An answer's prefix: its rows before any open neuron fires (once a whole pass shows them), and its slot once drawn. -const Kept = struct { seen: bool = false, skip: usize = 0, slot: ?u32 = null }; - -/// The open fact's answers' prefixes (its own answers first, then those that are to stay). -pub const Prefixes = struct { - list: std.ArrayList(Kept) = .empty, - slots: u32 = 0, - skipped: usize = 0, // rows its steps did not run again - inputs: u64 = 0, // the pocket's input weights the prefixes were found under - - pub fn deinit(s: *Prefixes, gpa: std.mem.Allocator) void { - s.list.deinit(gpa); - } - - /// A fact's `n` answers begun, no prefix known. - pub fn begin(s: *Prefixes, gpa: std.mem.Allocator, n: usize) !void { - s.list.clearRetainingCapacity(); - try s.list.appendNTimes(gpa, .{}, n); - s.slots = 0; - s.skipped = 0; - s.inputs = 0; - } -}; - -/// A round of outputs begun: the prefixes found kept while the pocket's input weights are as they were found under. -pub fn round(p: anytype, s: *Prefixes) void { - var h = std.hash.Wyhash.init(0); - h.update(std.mem.sliceAsBytes(p.up.items)); - h.update(std.mem.sliceAsBytes(p.used.items)); - const now = h.final(); - if (now == s.inputs) return; - for (s.list.items) |*k| k.* = .{}; - s.slots = 0; - s.inputs = now; -} - -/// The slots freed with their states (a further round runs its answers' prefixes again from their next draw). -pub fn release(t: anytype, s: *Prefixes) !void { - try t.prefixSlots(0); - for (s.list.items) |*k| k.slot = null; - s.slots = 0; -} - -/// The drawn answers (`which`: their indexes) set to skip prefixes in slots; those shown but not yet kept primed first. -pub fn use(t: anytype, s: *Prefixes, seqs: []Seq, which: []const usize) !void { - if (!t.packs()) return; - var fresh: [32]Seq = undefined; - if (seqs.len > fresh.len) return error.BadPass; - var n: usize = 0; - for (seqs, which) |*q, w| { - const k = &s.list.items[w]; - if (k.slot == null and k.seen and k.skip >= least and s.slots < @TypeOf(t.prefixes).most) { - k.slot = s.slots; - s.slots += 1; - fresh[n] = .{ .ids = q.ids[0 .. k.skip + 1], .start = k.skip, .decide = k.skip - 1, .slot = k.slot.? }; - n += 1; - } - if (k.slot) |slot| { - q.skip = k.skip; - q.slot = slot; - s.skipped += k.skip; - } - } - if (n == 0) return; - try t.prefixSlots(s.slots); - var got: [32]train_mode.Result = undefined; - var at: usize = 0; - while (at < n) { - const m = pack.fits(t, fresh[at..n]); - try t.pass(fresh[at..][0..m], .prime, pack.turn, got[0..m]); - at += m; - } -} - -/// Answer `which` (`sq` at `sp`, run whole): its rows before an open neuron fires, its decision, answer and nudges. -pub fn learn(p: anytype, t: anytype, s: *Prefixes, sq: Seq, sp: Span, which: usize) void { - const k = &s.list.items[which]; - if (k.seen or sq.skip > 0) return; - k.seen = true; - const d = t.config().hidden; - var limit = @min(sq.decide, sq.start - 1); - for (sq.nudge.layers, sq.nudge.rows) |mask, row| if (mask != 0) { - limit = @min(limit, row); - }; - k.skip = rows: for (0..limit) |r| { - for (p.taken.items) |x| if (dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(p.moe.items[x.slot], sp.row(r))) > 0) break :rows r; - for (p.joint.items) |x| if (dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(p.moe.items[x.slot], sp.row(r))) > 0) break :rows r; - } else limit; -} diff --git a/zig/src/families/nemotron/probe.zig b/zig/src/families/nemotron/probe.zig deleted file mode 100644 index 1175275c7a6..00000000000 --- a/zig/src/families/nemotron/probe.zig +++ /dev/null @@ -1,186 +0,0 @@ -//! A measure, not a lesson: how far vectors fitted at one row of a few layers bring a fact's held-out answers back. -const std = @import("std"); -const examples = @import("lesson_examples.zig"); -const lesson_route = @import("lesson_route.zig"); -const subspace = @import("subspace.zig"); - -const Example = examples.Example; -const Acting = lesson_route.Acting; - -/// The row a setup's vectors go on: the reply's first (the assistant header) or the question's subject. -pub const Row = enum { decide, subject }; - -const steps = 30; // Adam steps a setup is fitted for -const reach: f32 = 0.05; // each step's size against the residual's -const decay: f32 = 0.05; // the vectors' squared size against the residual's, added to the loss -const furthest: f32 = 3; // a vector's size at most, against the residual's - -/// A probe over trainer T (Metal's: its residual and nudges). -pub fn Probe(comptime T: type) type { - return struct { - const Self = @This(); - const Setup = struct { row: Row, layers: u64 }; - - gpa: std.mem.Allocator, - answered: []const Example = &.{}, - held: []const Example = &.{}, - setups: std.ArrayList(Setup) = .empty, - setup: usize = 0, - round: usize = 0, - at: usize = 0, - judging: bool = false, - loss: f32 = 0, - first: f32 = 0, - final: f32 = 0, // the answers' loss at the last fitting round - back: usize = 0, // held-out answers that came back token for token - size: std.ArrayList(f32) = .empty, // [layers]: the row's mean residual length after each layer - state: std.ArrayList(f32) = .empty, // [4, layers, D]: the vectors, their Adam moments, a round's gradient - - pub fn init(gpa: std.mem.Allocator) Self { - return .{ .gpa = gpa }; - } - - pub fn deinit(p: *Self) void { - p.setups.deinit(p.gpa); - p.size.deinit(p.gpa); - p.state.deinit(p.gpa); - } - - /// A lesson's setups: the subject's row at MoE layers 13 to 25, then in windows of three MoE layers, two apart. - pub fn begin(p: *Self, t: *T, answered: []const Example, held: []const Example) !void { - const c = t.config(); - p.answered = answered; - p.held = held; - p.setups.clearRetainingCapacity(); - var moe: [64]usize = undefined; - var count_moe: usize = 0; - var mid: u64 = 0; - for (0..c.layers - 1) |l| if (c.kinds[l] == .moe) { - moe[count_moe] = l; - count_moe += 1; - if (l >= 13 and l <= 25) mid |= @as(u64, 1) << @intCast(l); - }; - try p.setups.append(p.gpa, .{ .row = .subject, .layers = mid }); - var w: usize = 0; - while (w + 3 <= count_moe) : (w += 2) { - var mask: u64 = 0; - for (moe[w..][0..3]) |l| mask |= @as(u64, 1) << @intCast(l); - try p.setups.append(p.gpa, .{ .row = .subject, .layers = mask }); - } - p.setup = 0; - try p.start(t); - } - - fn start(p: *Self, t: *T) !void { - const c = t.config(); - p.round = 0; - p.at = 0; - p.loss = 0; - p.judging = false; - p.back = 0; - p.size.clearRetainingCapacity(); - try p.size.appendNTimes(p.gpa, 0, c.layers); - p.state.clearRetainingCapacity(); - try p.state.appendNTimes(p.gpa, 0, 4 * c.layers * c.hidden); - } - - fn row(s: Setup, ex: Example) ?usize { - return switch (s.row) { - .decide => ex.decide, - .subject => if (ex.subject > 0 and ex.subject < ex.start) ex.subject else null, - }; - } - - /// One pass; true once every setup has been fitted and judged. - pub fn step(p: *Self, t: *T, acting: Acting) !bool { - if (p.setup == p.setups.items.len) return true; - const c = t.config(); - const d = c.hidden; - const n = c.layers * d; - const s = p.setups.items[p.setup]; - const vecs = p.state.items[0..n]; - const grad = p.state.items[3 * n ..][0..n]; - const list = if (p.judging) p.held else p.answered; - while (p.at < list.len) { - const ex = list[p.at]; - p.at += 1; - const r = row(s, ex) orelse continue; - t.nudge = .{ .layers = .{ s.layers, 0, 0 }, .rows = .{ r, 0, 0 } }; - @memcpy(t.delta.slice(f32, n), vecs); - const got = try t.step(ex.ids, ex.start, .target, .{ .decide = ex.decide, .bits = acting, .whole = true }); - p.loss += got.loss; - if (p.judging) { - p.back += @intFromBool(got.recalled); - return false; - } - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - for (grad[l * d ..][0..d], t.push.slice(f32, n)[l * d ..][0..d]) |*g, x| g.* += x; - if (p.round == 0) p.size.items[l] += norm(t.residual(l + 1, r)); - }; - return false; - } - const used = count(s, list); - const mean = p.loss / @as(f32, @floatFromInt(@max(used, 1))); - p.loss = 0; - p.at = 0; - if (p.judging) { - var len: f32 = 0; - var layers: usize = 0; - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - len += @sqrt(subspace.dot(vecs[l * d ..][0..d], vecs[l * d ..][0..d])) / p.size.items[l]; - layers += 1; - }; - const last = 63 - @clz(s.layers); - std.log.info("slide probe: the {t}'s row, {d} MoE layers from {d} to {d}: the answers' loss {d:.3} to {d:.3} in {d} steps, vectors {d:.2} of the residual each; held-out {d} of {d} come back, their loss {d:.3}", .{ s.row, layers, @ctz(s.layers), last, p.first, p.final, steps, len / @as(f32, @floatFromInt(@max(layers, 1))), p.back, used, mean }); - p.setup += 1; - if (p.setup < p.setups.items.len) try p.start(t); - return false; - } - if (p.round == 0) { - p.first = mean; - for (p.size.items) |*x| x.* /= @floatFromInt(@max(used, 1)); - } - p.round += 1; - p.final = mean; - if (p.round > steps) { - p.judging = true; - return false; - } - const m = p.state.items[n..][0..n]; - const v = p.state.items[2 * n ..][0..n]; - const tt: f32 = @floatFromInt(p.round); - for (0..c.layers) |l| if (s.layers >> @intCast(l) & 1 != 0) { - const size = p.size.items[l]; - const lr = reach * size / @sqrt(@as(f32, @floatFromInt(d))); - const x = vecs[l * d ..][0..d]; - for (x, m[l * d ..][0..d], v[l * d ..][0..d], grad[l * d ..][0..d]) |*xi, *mi, *vi, gi| { - const g = gi / @as(f32, @floatFromInt(@max(used, 1))) + 2 * decay * xi.* / (size * size); - mi.* = 0.9 * mi.* + 0.1 * g; - vi.* = 0.999 * vi.* + 0.001 * g * g; - xi.* -= lr * (mi.* / (1 - std.math.pow(f32, 0.9, tt))) / (@sqrt(vi.* / (1 - std.math.pow(f32, 0.999, tt))) + 1e-8); - } - const len = @sqrt(subspace.dot(x, x)); - if (len > furthest * size) for (x) |*xi| { - xi.* *= furthest * size / len; - }; - }; - @memset(grad, 0); - return false; - } - - fn count(s: Setup, list: []const Example) usize { - var k: usize = 0; - for (list) |ex| k += @intFromBool(row(s, ex) != null); - return k; - } - }; -} - -fn norm(b: []const u16) f32 { - var s: f32 = 0; - for (b) |x| { - const f: f32 = @bitCast(@as(u32, x) << 16); - s += f * f; - } - return @sqrt(s); -} diff --git a/zig/src/families/nemotron/router.zig b/zig/src/families/nemotron/router.zig deleted file mode 100644 index e221c50c6c1..00000000000 --- a/zig/src/families/nemotron/router.zig +++ /dev/null @@ -1,260 +0,0 @@ -//! A lesson's router: Fisher scores per layer, the best averaged; it acts past a bar read off left-out questions. -const std = @import("std"); -const shape = @import("learn_shape.zig"); -const subspace = @import("subspace.zig"); - -const n = shape.candidates; - -const ridge = 0.1; // of the scatter's mean diagonal: questions are few against 64 directions -const most_reads = 12; // layers a router averages: past the best dozen, weaker layers blur the fact's questions back in -const odd_share = 4; // one fact question in this many may word itself apart from the rest and go untaken - -pub const Fit = struct { - dir: []f32, // [layers, n]: each layer's direction, unit, in its candidates' terms - weight: []f32, // [layers]: each layer's share of the average over the other prompts' spread there (0: unread) - mean: []f32, // [layers]: the other prompts' mean score there - need: f32, // the average a reply's decision row must reach for the lesson to act on it - reads: u32, // layers with a share - fact_low: f32, // the average most fact questions left out of the fit reached (all but the oddest quarter) - fact_least: f32, // the lowest any of them reached - steady_high: f32, // the highest a steady prompt left out of the fit reached - - pub fn deinit(f: *Fit, gpa: std.mem.Allocator) void { - gpa.free(f.dir); - gpa.free(f.weight); - gpa.free(f.mean); - } - - /// Whether a fact question the fit never saw still scores above every steady prompt it never saw. - pub fn apart(f: *const Fit) bool { - return f.fact_low > f.steady_high; - } - - /// Router row `i` of `rows` (rows[l]: layer l's decision rows along its candidates) as the lesson scores it. - pub fn score(f: *const Fit, rows: []const []const f32, i: usize) f32 { - var s: f32 = 0; - for (rows, 0..) |r, l| { - if (f.weight[l] == 0) continue; - s += f.weight[l] * (subspace.dot(f.dir[l * n ..][0..n], r[i * n ..][0..n]) - f.mean[l]); - } - return s; - } -}; - -/// Sums over a set of rows, from which a mean and scatter come with any one row left out. -const Stats = struct { - count: f64 = 0, - sum: [n]f64 = @splat(0), - sq: [n * n]f64 = @splat(0), - - fn of(rows: []const f32) Stats { - var s: Stats = .{}; - for (0..rows.len / n) |r| s.add(rows[r * n ..][0..n], 1); - return s; - } - - fn add(s: *Stats, p: []const f32, w: f64) void { - s.count += w; - for (0..n) |i| { - s.sum[i] += w * p[i]; - for (0..n) |j| s.sq[i * n + j] += w * p[i] * p[j]; - } - } -}; - -/// Fisher's direction (unit) between two sets: (scatter + ridge)^-1 (mean difference). -fn fisher(pos: *const Stats, neg: *const Stats, out: []f32) !void { - var mean: [2][n]f64 = undefined; - const sets = [2]*const Stats{ pos, neg }; - var a: [n * n]f64 = @splat(0); - for (sets, 0..) |s, k| { - for (0..n) |i| mean[k][i] = s.sum[i] / s.count; - for (0..n) |i| for (0..n) |j| { - a[i * n + j] += s.sq[i * n + j] / s.count - mean[k][i] * mean[k][j]; - }; - } - var trace: f64 = 0; - for (0..n) |i| trace += a[i * n + i]; - for (0..n) |i| a[i * n + i] += ridge * trace / n + 1e-12; - var d: [n]f64 = undefined; - for (&d, mean[0], mean[1]) |*x, p, q| x.* = p - q; - try subspace.solve(&a, n, &d); - var size: f64 = 0; - for (d) |x| size += x * x; - for (out, d) |*o, x| o.* = @floatCast(x / @sqrt(@max(size, 1e-30))); -} - -/// One layer's direction from every row, and each row's score along the direction fitted without it. -fn layer(facts: []const f32, steady: []const f32, dir: []f32, fact_s: []f32, steady_s: []f32) !void { - const pos = Stats.of(facts); - const neg = Stats.of(steady); - try fisher(&pos, &neg, dir); - var d: [n]f32 = undefined; - for (fact_s, 0..) |*s, i| { - const p = facts[i * n ..][0..n]; - var less = pos; - less.add(p, -1); - try fisher(&less, &neg, &d); - s.* = subspace.dot(&d, p); - } - for (steady_s, 0..) |*s, j| { - const p = steady[j * n ..][0..n]; - var less = neg; - less.add(p, -1); - try fisher(&pos, &less, &d); - s.* = subspace.dot(&d, p); - } -} - -/// The steady rows' mean and spread of `s`, with row `skip` left out. -fn spread(s: []const f32, skip: ?usize) [2]f32 { - var sum: f64 = 0; - var sq: f64 = 0; - var count: f64 = 0; - for (s, 0..) |x, j| if (j != skip) { - sum += x; - sq += x * x; - count += 1; - }; - const m = sum / count; - return .{ @floatCast(m), @floatCast(@sqrt(@max(sq / count - m * m, 0)) + 1e-9) }; -} - -/// Each layer's share from fact scores `z` [layers, facts] less `skip`: top layers by median, above the steady mean. -fn shares(gpa: std.mem.Allocator, z: []const f32, layers: usize, nf: usize, skip: ?usize, out: []f32) !void { - const col = try gpa.alloc(f32, nf); - defer gpa.free(col); - const sep = try gpa.alloc(f32, layers); - defer gpa.free(sep); - for (0..layers) |l| { - var m: usize = 0; - for (0..nf) |i| if (i != skip) { - col[m] = z[l * nf + i]; - m += 1; - }; - std.mem.sort(f32, col[0..m], {}, std.sort.asc(f32)); - sep[l] = col[m / 2]; - } - const sorted = try gpa.dupe(f32, sep); - defer gpa.free(sorted); - std.mem.sort(f32, sorted, {}, std.sort.desc(f32)); - const bar = sorted[@min(most_reads, layers) - 1]; - var total: f32 = 0; - for (out, sep) |*w, x| { - w.* = if (x >= bar and x > 0) x else 0; - total += w.*; - } - for (out) |*w| w.* = if (total > 0) w.* / total else 0; -} - -/// The router from each layer's decision rows: facts[l] and steady[l] the same questions at every layer, [count, n]. -pub fn fit(gpa: std.mem.Allocator, facts: []const []const f32, steady: []const []const f32) !Fit { - const layers = facts.len; - const nf = facts[0].len / n; - const ns = steady[0].len / n; - if (nf < 2 or ns < 3) return error.TooFewQuestions; - const dir = try gpa.alloc(f32, layers * n); - errdefer gpa.free(dir); - const weight = try gpa.alloc(f32, layers); - errdefer gpa.free(weight); - const mean = try gpa.alloc(f32, layers); - errdefer gpa.free(mean); - const fact_s = try gpa.alloc(f32, layers * nf); - defer gpa.free(fact_s); - const steady_s = try gpa.alloc(f32, layers * ns); - defer gpa.free(steady_s); - const Share = struct { - fn run(from: usize, step: usize, ctx: anytype, out: *?anyerror) void { - var l = from; - while (l < ctx.layers) : (l += step) layer(ctx.facts[l], ctx.steady[l], ctx.dir[l * n ..][0..n], ctx.fact_s[l * ctx.nf ..][0..ctx.nf], ctx.steady_s[l * ctx.ns ..][0..ctx.ns]) catch |e| { - out.* = e; - }; - } - }; - const ctx = .{ .layers = layers, .facts = facts, .steady = steady, .dir = dir, .fact_s = fact_s, .steady_s = steady_s, .nf = nf, .ns = ns }; - var threads: [16]?std.Thread = @splat(null); - var errs: [16]?anyerror = @splat(null); - const k = @min(threads.len, layers); - for (threads[0..k], 0..) |*t, i| t.* = std.Thread.spawn(.{}, Share.run, .{ i, k, ctx, &errs[i] }) catch null; - for (threads[0..k], 0..) |t, i| if (t) |th| th.join() else Share.run(i, k, ctx, &errs[i]); - for (errs[0..k]) |e| if (e) |x| return x; - // every score standardised by the steady prompts' at its layer: a steady prompt's without its own - const z_fact = try gpa.alloc(f32, layers * nf); - defer gpa.free(z_fact); - const z_steady = try gpa.alloc(f32, layers * ns); - defer gpa.free(z_steady); - const spread_all = try gpa.alloc([2]f32, layers); - defer gpa.free(spread_all); - for (0..layers) |l| { - const s = steady_s[l * ns ..][0..ns]; - spread_all[l] = spread(s, null); - for (0..nf) |i| z_fact[l * nf + i] = (fact_s[l * nf + i] - spread_all[l][0]) / spread_all[l][1]; - for (0..ns) |j| { - const own = spread(s, j); - z_steady[l * ns + j] = (s[j] - own[0]) / own[1]; - } - } - // each left-out question's average over the layers chosen without it - const w = try gpa.alloc(f32, layers); - defer gpa.free(w); - const fact_avg = try gpa.alloc(f32, nf); - defer gpa.free(fact_avg); - for (fact_avg, 0..) |*avg, i| { - try shares(gpa, z_fact, layers, nf, i, w); - avg.* = 0; - for (0..layers) |l| avg.* += w[l] * z_fact[l * nf + i]; - } - try shares(gpa, z_fact, layers, nf, null, w); - var high: f32 = -std.math.inf(f32); - for (0..ns) |j| { - var avg: f32 = 0; - for (0..layers) |l| avg += w[l] * z_steady[l * ns + j]; - high = @max(high, avg); - } - std.mem.sort(f32, fact_avg, {}, std.sort.asc(f32)); - const low = fact_avg[nf / odd_share]; - var reads: u32 = 0; - for (0..layers) |l| { - weight[l] = w[l] / spread_all[l][1]; - mean[l] = spread_all[l][0]; - reads += @intFromBool(w[l] > 0); - } - // half way across the gap between left-out facts and steady prompts; on overlap, what most facts reach - const need = if (low > high) (low + high) / 2 else low; - return .{ .dir = dir, .weight = weight, .mean = mean, .need = need, .reads = reads, .fact_low = low, .fact_least = fact_avg[0], .steady_high = high }; -} - -test "a router clears questions it never saw about its fact, and steady prompts it never saw stay below it" { - const gpa = std.testing.allocator; - var prng = std.Random.DefaultPrng.init(11); - const r = prng.random(); - const layers = 6; - const nf = 8; - const ns = 60; - var facts: [layers][]f32 = undefined; - var steady: [layers][]f32 = undefined; - // facts share a direction the steady rows lack; every row then made unit - for (0..layers) |l| { - facts[l] = try gpa.alloc(f32, nf * n); - steady[l] = try gpa.alloc(f32, ns * n); - for (facts[l], 0..) |*x, i| x.* = r.floatNorm(f32) * 0.3 + @as(f32, if (i % n == l) 3 else 0); - for (steady[l]) |*x| x.* = r.floatNorm(f32) * 0.3; - for ([_][]f32{ facts[l], steady[l] }) |rows| for (0..rows.len / n) |q| { - const row = rows[q * n ..][0..n]; - const size = @sqrt(subspace.dot(row, row)); - for (row) |*x| x.* /= size; - }; - } - defer for (0..layers) |l| { - gpa.free(facts[l]); - gpa.free(steady[l]); - }; - var f = try fit(gpa, &facts, &steady); - defer f.deinit(gpa); - try std.testing.expect(f.apart()); - try std.testing.expect(f.need > f.steady_high and f.need < f.fact_low); - try std.testing.expectEqual(@as(u32, layers), f.reads); - // the fit's own rows: every fact above the bar, every steady prompt below it - for (0..nf) |i| try std.testing.expect(f.score(&facts, i) >= f.need); - for (0..ns) |j| try std.testing.expect(f.score(&steady, j) < f.need); -} diff --git a/zig/src/families/nemotron/subspace.zig b/zig/src/families/nemotron/subspace.zig deleted file mode 100644 index 4fe16eb109e..00000000000 --- a/zig/src/families/nemotron/subspace.zig +++ /dev/null @@ -1,216 +0,0 @@ -//! Small dense linear algebra for a lesson's directions: orthonormal rows, and where one set of rows outweighs another. -const std = @import("std"); - -const V = @Vector(8, f32); - -pub fn dot(x: []const f32, y: []const f32) f32 { - var acc: V = @splat(0); - var i: usize = 0; - while (i + 8 <= x.len) : (i += 8) acc += @as(V, x[i..][0..8].*) * @as(V, y[i..][0..8].*); - var s = @reduce(.Add, acc); - while (i < x.len) : (i += 1) s += x[i] * y[i]; - return s; -} - -/// y += c x. -pub fn axpy(y: []f32, c: f32, x: []const f32) void { - const cv: V = @splat(c); - var i: usize = 0; - while (i + 8 <= y.len) : (i += 8) y[i..][0..8].* = @as(V, y[i..][0..8].*) + cv * @as(V, x[i..][0..8].*); - while (i < y.len) : (i += 1) y[i] += c * x[i]; -} - -/// Rows of `m` made orthonormal in place, each against those before it twice over; a row that vanishes becomes zero. -pub fn orthonormal(m: []f32, rows: usize, len: usize) void { - for (0..rows) |j| { - const row = m[j * len ..][0..len]; - const size = @sqrt(dot(row, row)); - for (0..2) |_| for (0..j) |i| { - const prev = m[i * len ..][0..len]; - axpy(row, -dot(row, prev), prev); - }; - const left = @sqrt(dot(row, row)); - if (!(left > 1e-4 * size)) { - @memset(row, 0); - continue; - } - for (row) |*v| v.* /= left; - } -} - -/// Each row of `m` (rows x len) with its parts along the orthonormal rows of `basis` taken out, twice over. -pub fn remove(m: []f32, rows: usize, basis: []const f32, count: usize, len: usize) void { - for (0..rows) |q| { - const row = m[q * len ..][0..len]; - for (0..2) |_| for (0..count) |u| { - const dir = basis[u * len ..][0..len]; - axpy(row, -dot(row, dir), dir); - }; - } -} - -/// The k orthonormal directions (rows of out) where `more` (n x n) outweighs `less`: more v = mu (less + lambda) v. -pub fn outweigh(gpa: std.mem.Allocator, more: []const f64, less: []const f64, n: usize, k: usize, out: []f32) !void { - const l = try gpa.dupe(f64, less); - defer gpa.free(l); - var trace: f64 = 0; - for (0..n) |i| trace += l[i * n + i]; - const lambda = 1e-3 * trace / @as(f64, @floatFromInt(n)) + 1e-12; - for (0..n) |i| l[i * n + i] += lambda; - try cholesky(l, n); - const s = try gpa.alloc(f64, n * n); - defer gpa.free(s); - const t = try gpa.alloc(f64, n * n); - defer gpa.free(t); - @memcpy(t, more); - for (0..n) |col| lower(l, n, t, col); - for (0..n) |i| for (0..n) |j| { - s[i * n + j] = t[j * n + i]; - }; - for (0..n) |col| lower(l, n, s, col); - const vecs = try gpa.alloc(f64, n * n); - defer gpa.free(vecs); - jacobi(s, n, vecs); - const vals = try gpa.alloc(f64, n); - defer gpa.free(vals); - for (vals, 0..) |*v, i| v.* = s[i * n + i]; - const order = try gpa.alloc(usize, n); - defer gpa.free(order); - for (order, 0..) |*o, i| o.* = i; - std.mem.sort(usize, order, vals, struct { - fn bigger(v: []const f64, a: usize, b: usize) bool { - return v[a] > v[b]; - } - }.bigger); - const w = try gpa.alloc(f64, n); - defer gpa.free(w); - for (0..k) |q| { - for (w, 0..) |*x, i| x.* = vecs[i * n + order[q]]; - upper(l, n, w); - for (out[q * n ..][0..n], w) |*o, x| o.* = @floatCast(x); - } - orthonormal(out, k, n); -} - -/// x = a^-1 b for a symmetric positive definite a (n x n, overwritten by its Cholesky factor). -pub fn solve(a: []f64, n: usize, b: []f64) !void { - try cholesky(a, n); - solveFactored(a, n, b); -} - -/// x = a^-1 b given a's Cholesky factor (as `factor` leaves it). -pub fn solveFactored(l: []const f64, n: usize, b: []f64) void { - for (0..n) |i| { - var v = b[i]; - for (0..i) |k| v -= l[i * n + k] * b[k]; - b[i] = v / l[i * n + i]; - } - upper(l, n, b); -} - -/// a = L L^T in place, for solveFactored. -pub fn factor(a: []f64, n: usize) !void { - try cholesky(a, n); -} - -/// a = L L^T in place (L in the lower triangle, the upper zeroed); a must be symmetric positive definite. -fn cholesky(a: []f64, n: usize) !void { - for (0..n) |j| { - var d = a[j * n + j]; - for (0..j) |k| d -= a[j * n + k] * a[j * n + k]; - if (!(d > 0)) return error.NotPositiveDefinite; - const root = @sqrt(d); - a[j * n + j] = root; - for (j + 1..n) |i| { - var v = a[i * n + j]; - for (0..j) |k| v -= a[i * n + k] * a[j * n + k]; - a[i * n + j] = v / root; - } - for (j + 1..n) |k| a[j * n + k] = 0; - } -} - -/// Column `col` of m (n x n) replaced by L^-1 times it. -fn lower(l: []const f64, n: usize, m: []f64, col: usize) void { - for (0..n) |i| { - var v = m[i * n + col]; - for (0..i) |k| v -= l[i * n + k] * m[k * n + col]; - m[i * n + col] = v / l[i * n + i]; - } -} - -/// w replaced by L^-T w. -fn upper(l: []const f64, n: usize, w: []f64) void { - var i = n; - while (i > 0) { - i -= 1; - var v = w[i]; - for (i + 1..n) |k| v -= l[k * n + i] * w[k]; - w[i] = v / l[i * n + i]; - } -} - -/// A symmetric a (n x n) brought to its eigenvalues on the diagonal by Jacobi rotations; vecs' columns: eigenvectors. -fn jacobi(a: []f64, n: usize, vecs: []f64) void { - @memset(vecs, 0); - for (0..n) |i| vecs[i * n + i] = 1; - for (0..60) |_| { - var off: f64 = 0; - var all: f64 = 0; - for (0..n) |i| for (0..n) |j| { - all += a[i * n + j] * a[i * n + j]; - if (i != j) off += a[i * n + j] * a[i * n + j]; - }; - if (off <= 1e-24 * all) return; - for (0..n) |p| for (p + 1..n) |q| { - const apq = a[p * n + q]; - if (apq == 0) continue; - const theta = (a[q * n + q] - a[p * n + p]) / (2 * apq); - const t = std.math.sign(theta) / (@abs(theta) + @sqrt(theta * theta + 1)) + @as(f64, if (theta == 0) 1 else 0); - const c = 1 / @sqrt(t * t + 1); - const s = t * c; - for (0..n) |k| { - const akp = a[k * n + p]; - const akq = a[k * n + q]; - a[k * n + p] = c * akp - s * akq; - a[k * n + q] = s * akp + c * akq; - } - for (0..n) |k| { - const apk = a[p * n + k]; - const aqk = a[q * n + k]; - a[p * n + k] = c * apk - s * aqk; - a[q * n + k] = s * apk + c * aqk; - } - for (0..n) |k| { - const vkp = vecs[k * n + p]; - const vkq = vecs[k * n + q]; - vecs[k * n + p] = c * vkp - s * vkq; - vecs[k * n + q] = s * vkp + c * vkq; - } - }; - } -} - -test "orthonormal rows, and the direction one set of rows outweighs another along" { - const len = 64; - var avoid: [3 * len]f32 = undefined; - var seek: [2 * len]f32 = undefined; - var prng = std.Random.DefaultPrng.init(7); - for (&avoid) |*v| v.* = prng.random().float(f32) - 0.5; - for (&seek) |*v| v.* = prng.random().float(f32) - 0.5; - orthonormal(&avoid, 3, len); - remove(&seek, 2, &avoid, 3, len); - orthonormal(&seek, 2, len); - for (0..2) |q| { - const row = seek[q * len ..][0..len]; - try std.testing.expectApproxEqAbs(@as(f32, 1), dot(row, row), 1e-4); - for (0..3) |u| try std.testing.expectApproxEqAbs(@as(f32, 0), dot(row, avoid[u * len ..][0..len]), 1e-4); - } - // more is large on axis 0 and 1, less is large on axis 1: the best single direction is axis 0 - var more = [_]f64{ 4, 0, 0, 0, 4, 0, 0, 0, 1 }; - var less = [_]f64{ 1, 0, 0, 0, 9, 0, 0, 0, 1 }; - var out: [3]f32 = undefined; - try outweigh(std.testing.allocator, &more, &less, 3, 1, &out); - try std.testing.expectApproxEqAbs(@as(f32, 1), @abs(out[0]), 1e-4); - try std.testing.expectApproxEqAbs(@as(f32, 0), out[1], 1e-4); -} diff --git a/zig/src/families/nemotron/train_mode.zig b/zig/src/families/nemotron/train_mode.zig deleted file mode 100644 index d6b4a69dfc5..00000000000 --- a/zig/src/families/nemotron/train_mode.zig +++ /dev/null @@ -1,47 +0,0 @@ -//! What a training step does, for both backends' trainers. - -/// A step's loss, its gradient (and Adam: `learn`), inputs only (`reads`), or the gradient at a nudged row (`target`). -pub const Mode = enum { loss, grad, learn, avoid, seek, project, keys, target, prime }; - -/// Whether a step only reads the site inputs (sketches, projections or keys), with no loss. -pub fn reads(mode: Mode) bool { - return switch (mode) { - .avoid, .seek, .project, .keys, .prime => true, - else => false, - }; -} - -/// Where a `target` step nudges and reads the gradient: three rows, each after its mask's layers, row i's in third i. -pub const Nudge = struct { layers: [3]u64 = @splat(0), rows: [3]usize = @splat(0) }; - -/// The answer's mean loss, and whether each of its tokens was the likeliest at its row. -pub const Result = struct { loss: f32, recalled: bool }; - -/// A pass's sequence: tokens, answer start, decision row, pocket scale, nudges, and `skip` rows from prefix `slot`. -pub const Seq = struct { ids: []const u32, start: usize, decide: usize, scale: f32 = 1, nudge: Nudge = .{}, skip: usize = 0, slot: u32 = 0 }; - -/// Where each sequence of a pass sits: its first row, its rows (ids less the last and the skipped), its prefix. -pub const Span = struct { - at: usize, - rows: usize, - skip: usize = 0, - slot: u32 = 0, - - /// The pass's row holding the sequence's row r (r at least `skip`). - pub fn row(sp: Span, r: usize) usize { - return sp.at + r - sp.skip; - } -}; - -/// A sequence's rows that predict its answer: the first in the pass, where they sit among the head's rows, how many. -pub const Answer = struct { first: usize, at: usize, rows: usize }; - -/// Each sequence's answer rows, packed for the head (no other row's loss or gradient there is anything but zero). -pub fn answers(seqs: []const Seq, spans: []const Span, out: []Answer) usize { - var at: usize = 0; - for (seqs, spans, out) |sq, sp, *a| { - a.* = .{ .first = sp.row(sq.start - 1), .at = at, .rows = sq.ids.len - sq.start }; - at += a.rows; - } - return at; -} From 9aae35a6d6acbe4c082e0b71545e50efce7d9730 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:13:54 +0000 Subject: [PATCH 007/158] changelog: #3707 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f5c67e8d9f..1e41f745b73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Nemotron: the Living Weights copies left behind by the October revert are deleted and `cuda_pages` imports `living.lesson_route`, leaving one copy of the learner, pocket and lesson files (#3707). Thanks to @jschmied. + - Flash Next on CUDA: after load, a mixed shard keeps only the n-gram table's pages in the page cache, and the final sweep reaches shards nested under `tensors/`, freeing about 3 GiB of page cache on the NVFP4 export with replies unchanged (#3467). Thanks to @jschmied. - CUDA: GLM's `TF_GLM_L2PF` site f now also prefetches a MoE layer's shared expert gate-up after its router within the same `TF_GLM_L2PF_MB` budget, giving about 1.0-1.2% faster decode at TP=2 on GB10 (mean of three alternating launches) with identical tokens (#3156). Thanks to @Bizuayeu. From 23b9174130c807c8322f9a9d392c883a92609153 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:19:27 +0100 Subject: [PATCH 008/158] Ling-3.0-tiny MLA on Metal using existing k3_mla (#1247) --- zig/build/kernel_contract.zig | 13 + zig/build/ling_host.zig | 2 +- zig/kernels/metal/ling/mla.metal | 67 ++ zig/kernels/metal/ling/sources.zig | 1 + zig/src/families/ling/host_test.zig | 20 + zig/src/families/ling/mla.zig | 276 +++++ zig/src/families/ling/mla_rope_test.zig | 84 ++ zig/src/families/ling/oracle/ling_forward.py | 46 +- zig/src/families/ling/oracle/mla_dump.py | 222 ++++ zig/tests/ling_mla_gpu.zig | 1132 ++++++++++++++++++ 10 files changed, 1860 insertions(+), 3 deletions(-) create mode 100644 zig/kernels/metal/ling/mla.metal create mode 100644 zig/src/families/ling/mla.zig create mode 100644 zig/src/families/ling/mla_rope_test.zig create mode 100644 zig/src/families/ling/oracle/mla_dump.py create mode 100644 zig/tests/ling_mla_gpu.zig diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 3a270c4cf47..302036fc897 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -156,6 +156,19 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil }, }) }); b.step("test-ling-kda-gpu", "Ling KDA mixer on this GPU against kda.zig, using k3_kda").dependOn(&b.addRunArtifact(ling_kda_gpu).step); + const ling_mla_gpu = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_mla_gpu.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "mla", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/mla.zig") }) }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, + }, + }) }); + b.step("test-ling-mla-gpu", "Ling MLA mixer on this GPU around k3_mla, against mla.zig").dependOn(&b.addRunArtifact(ling_mla_gpu).step); } /// Linux: `kernel-contract` runs tf-cuda-test's kernel-contract command (kernels from -Dnvcc or -Dfatbins). diff --git a/zig/build/ling_host.zig b/zig/build/ling_host.zig index b802cbd518a..5706cc8e41c 100644 --- a/zig/build/ling_host.zig +++ b/zig/build/ling_host.zig @@ -7,6 +7,6 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu .target = target, }); const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); - b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer").dependOn(&run.step); + b.step("test-ling-host", "Ling family package: config, names, tiny fixtures, synth JSON, grouped routing, KDA mixer, MLA RoPE and mixer").dependOn(&run.step); test_step.dependOn(&run.step); } diff --git a/zig/kernels/metal/ling/mla.metal b/zig/kernels/metal/ling/mla.metal new file mode 100644 index 00000000000..008f3edbd4c --- /dev/null +++ b/zig/kernels/metal/ling/mla.metal @@ -0,0 +1,67 @@ +// Ling MLA extras around k3: RoPE (GPT-J pairs then halves) and per-head gate expand. +// k3_mla_* kernels are unchanged. Layout matches ling_forward.py rot() and HF +// apply_rotary_pos_emb_interleave: pair (z[2i], z[2i+1]) rotates to (out[i], out[32+i]). +#include +using namespace metal; + +constant constexpr uint LAT = 512, ROPE = 64, KEY = LAT + ROPE, NOPE = 128, VD = 128, QD = NOPE + ROPE; + +struct MlaRow { + uint slot, pos; +}; + +struct MlaArgs { + device bfloat* cache; + uint slot_keys, heads, head0, rows, q_stride, kv_stride, gate_stride, out_stride; + float eps, scale; +}; + +// cs is (rows, 32, 2) f32: host f64 cos/sin of pos*inv, rounded to f32. Kernels apply only. +inline float2 ling_apply(float x0, float x1, const device float* cs, uint row, uint i) { + const uint at = (row * (ROPE / 2) + i) * 2; + const float c = cs[at], s = cs[at + 1]; + return float2(fma(x0, c, -(x1 * s)), fma(x1, c, x0 * s)); +} + +inline device bfloat* ling_keys(constant MlaArgs& a, MlaRow r) { + return a.cache + ulong(r.slot) * a.slot_keys * KEY; +} + +// In-place GPT-J rotate of the 64 rope columns k3_mla_cache just copied. 32 threads, no early +// return: the threadgroup temp needs every lane at the barrier. Cache address is rows[row].pos. +kernel void tf_ling_mla_rope_cache(device const MlaRow* rows [[buffer(0)]], constant MlaArgs& a [[buffer(1)]], + device const float* cs [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + threadgroup float tmp[ROPE]; + device bfloat* dst = ling_keys(a, rows[row]) + ulong(rows[row].pos) * KEY + LAT; + const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, row, t); + tmp[t] = o.x; + tmp[t + ROPE / 2] = o.y; + threadgroup_barrier(mem_flags::mem_threadgroup); + dst[t] = bfloat(tmp[t]); + dst[t + ROPE / 2] = bfloat(tmp[t + ROPE / 2]); +} + +// Same rotate on q's rope region (offset NOPE in each head) in place. Angles from cs[row]. +kernel void tf_ling_mla_rope_q(device bfloat* q [[buffer(0)]], constant MlaArgs& a [[buffer(1)]], + device const float* cs [[buffer(2)]], + uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup float tmp[ROPE]; + const uint hl = tg.x, row = tg.y; + device bfloat* z = q + ulong(row) * a.q_stride + hl * QD + NOPE; + const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, row, t); + tmp[t] = o.x; + tmp[t + ROPE / 2] = o.y; + threadgroup_barrier(mem_flags::mem_threadgroup); + z[t] = bfloat(tmp[t]); + z[t + ROPE / 2] = bfloat(tmp[t + ROPE / 2]); +} + +// Broadcast each per-head gate to 128 value columns so k3_mla_uv keeps Kimi's stride. +kernel void tf_ling_mla_gate_expand(device const bfloat* g [[buffer(0)]], device bfloat* g2 [[buffer(1)]], + constant MlaArgs& a [[buffer(2)]], uint2 gid [[thread_position_in_grid]]) { + const uint col = gid.x, row = gid.y; + if (row >= a.rows || col >= a.heads * VD) return; + g2[row * a.gate_stride + col] = g[row * a.heads + col / VD]; +} diff --git a/zig/kernels/metal/ling/sources.zig b/zig/kernels/metal/ling/sources.zig index 5fac014e986..6863a6cae5c 100644 --- a/zig/kernels/metal/ling/sources.zig +++ b/zig/kernels/metal/ling/sources.zig @@ -1,2 +1,3 @@ //! Ling Metal kernel sources. pub const route = @embedFile("route.metal"); +pub const mla = @embedFile("mla.metal"); diff --git a/zig/src/families/ling/host_test.zig b/zig/src/families/ling/host_test.zig index e339b37f0c2..516726dd005 100644 --- a/zig/src/families/ling/host_test.zig +++ b/zig/src/families/ling/host_test.zig @@ -10,9 +10,29 @@ test { _ = @import("synth.zig"); _ = @import("route.zig"); _ = @import("kda.zig"); + _ = @import("mla.zig"); + _ = @import("mla_rope_test.zig"); } test "the float64 oracle handles tiny's null SwiGLU lists" { const src = @embedFile("oracle/ling_forward.py"); try std.testing.expect(std.mem.indexOf(u8, src, "null (Ling-3.0-tiny)") != null); } + +test "the float64 oracle's mla takes a pos0 so a chunk is not always arange(T) from 0" { + const src = @embedFile("oracle/ling_forward.py"); + try std.testing.expect(std.mem.indexOf(u8, src, "def mla(self, x, p, pos0=0)") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "def one_mla(") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "pos0 + torch.arange(T, dtype=torch.float64)") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "attends only over the rows it is given") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "kv_a_proj_with_mqa") != null); +} + +test "mla dump runs ling_forward.py --mla-layer for TFLINGA1" { + const src = @embedFile("oracle/mla_dump.py"); + try std.testing.expect(std.mem.indexOf(u8, src, "ling_forward.py") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "--mla-layer") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "TFLINGA1") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "Random values in Ling-3.0-tiny tensor shapes") != null); + try std.testing.expect(std.mem.indexOf(u8, src, "sys.argv") != null); +} diff --git a/zig/src/families/ling/mla.zig b/zig/src/families/ling/mla.zig new file mode 100644 index 00000000000..75b7ea3388a --- /dev/null +++ b/zig/src/families/ling/mla.zig @@ -0,0 +1,276 @@ +//! Ling MLA mixer after the linears: unabsorbed python-style (ling_forward.py mla), plus RoPE helpers. +const std = @import("std"); +const config = @import("config.zig"); +const bf16_round = @import("bf16_round"); + +pub const lat: u32 = 512; +pub const rope_dim: u32 = 64; +pub const nope: u32 = 128; +pub const vd: u32 = 128; +pub const key: u32 = lat + rope_dim; +pub const qd: u32 = nope + rope_dim; +pub const nfreq: u32 = rope_dim / 2; +pub const theta_tiny: f64 = 6_000_000; +pub const eps_tiny: f32 = 1e-6; + +pub const Shape = struct { + heads: u32, + eps: f32, + theta: f64, + + pub fn of(c: *const config.Config) Shape { + return .{ .heads = c.mla_heads, .eps = c.eps, .theta = c.rope_theta }; + } + + pub fn scale(s: Shape) f64 { + _ = s; + return 1.0 / @sqrt(@as(f64, @floatFromInt(qd))); + } + + pub fn outWidth(s: Shape) u32 { + return s.heads * vd; + } +}; + +/// 1 / theta ** (arange(0, rope, 2) / rope): frequency i is 2i / 64. +pub fn invFreq(theta: f64, i: usize) f64 { + return 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(rope_dim))); +} + +/// One 64-vector at absolute pos: even/odd pairs, then cat(a*c-b*s, b*c+a*s). out and z are rope_dim long. +pub fn rotate(out: []f64, z: []const f64, pos: u32, theta: f64) void { + std.debug.assert(out.len == rope_dim and z.len == rope_dim); + for (0..nfreq) |i| { + const ang = @as(f64, @floatFromInt(pos)) * invFreq(theta, i); + const c = @cos(ang); + const s = @sin(ang); + const a = z[2 * i]; + const b = z[2 * i + 1]; + out[i] = a * c - b * s; + out[nfreq + i] = b * c + a * s; + } +} + +/// T rows of 64 at pos0 + t, the chunk/resume case. out and z are T * rope_dim. +pub fn rotateRows(out: []f64, z: []const f64, rows: u32, pos0: u32, theta: f64) void { + std.debug.assert(out.len == rows * rope_dim and z.len == rows * rope_dim); + for (0..rows) |t| { + rotate(out[t * rope_dim ..][0..rope_dim], z[t * rope_dim ..][0..rope_dim], pos0 + @as(u32, @intCast(t)), theta); + } +} + +/// (T, H) to (T, H*128): each head gate repeated across the value columns. +pub fn expandGate(out: []u16, g: []const u16, rows: u32, heads: u32) void { + std.debug.assert(g.len == rows * heads and out.len == rows * heads * vd); + for (0..rows) |t| { + for (0..heads) |h| { + const v = g[t * heads + h]; + const lo = (t * heads + h) * vd; + for (0..vd) |d| out[lo + d] = v; + } + } +} + +fn r64(comptime round: bool, v: f64) f64 { + if (!round) return v; + return bf16_round.bf16(v); +} + +fn sig(x: f64) f64 { + if (x >= 0) { + const e = @exp(-x); + return 1.0 / (1.0 + e); + } + const e = @exp(x); + return e / (1.0 + e); +} + +fn mixAs( + comptime round: bool, + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + const H = s.heads; + const T = rows; + std.debug.assert(y.len == T * H * vd); + std.debug.assert(q.len == T * H * qd); + std.debug.assert(kv.len == T * key); + std.debug.assert(w_rms.len == lat); + std.debug.assert(kvb.len == H * (nope + vd) * lat); + std.debug.assert(g.len == T * H); + + const lat_t = try alloc.alloc(f64, T * lat); + defer alloc.free(lat_t); + const krope = try alloc.alloc(f64, T * rope_dim); + defer alloc.free(krope); + const qrope = try alloc.alloc(f64, T * H * rope_dim); + defer alloc.free(qrope); + const k_nope = try alloc.alloc(f64, T * H * nope); + defer alloc.free(k_nope); + const v = try alloc.alloc(f64, T * H * vd); + defer alloc.free(v); + + const eps: f64 = s.eps; + for (0..T) |t| { + var ss: f64 = 0; + for (0..lat) |i| { + const x: f64 = kv[t * key + i]; + ss += x * x; + } + const rstd = 1.0 / @sqrt(ss / @as(f64, lat) + eps); + for (0..lat) |i| { + const yn = @as(f64, kv[t * key + i]) * rstd; + lat_t[t * lat + i] = r64(round, r64(round, yn) * w_rms[i]); + } + var z: [rope_dim]f64 = undefined; + var out: [rope_dim]f64 = undefined; + for (0..rope_dim) |i| z[i] = kv[t * key + lat + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| krope[t * rope_dim + i] = r64(round, out[i]); + for (0..H) |h| { + for (0..rope_dim) |i| z[i] = q[(t * H + h) * qd + nope + i]; + rotate(&out, &z, pos0 + @as(u32, @intCast(t)), s.theta); + for (0..rope_dim) |i| qrope[(t * H + h) * rope_dim + i] = r64(round, out[i]); + } + } + + for (0..H) |h| { + for (0..T) |t| { + for (0..nope) |d| { + var acc: f64 = 0; + const w0 = ((h * (nope + vd) + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + k_nope[(t * H + h) * nope + d] = r64(round, acc); + } + for (0..vd) |d| { + var acc: f64 = 0; + const w0 = ((h * (nope + vd) + nope + d) * lat); + for (0..lat) |c| acc += lat_t[t * lat + c] * kvb[w0 + c]; + v[(t * H + h) * vd + d] = r64(round, acc); + } + } + } + + const sc = s.scale(); + const scores = try alloc.alloc(f64, H * T * T); + defer alloc.free(scores); + for (0..H) |h| { + for (0..T) |t| { + for (0..T) |k| { + if (k > t) { + scores[(h * T + t) * T + k] = -std.math.inf(f64); + continue; + } + var p: f64 = 0; + const qb = (t * H + h) * qd; + const kb = (k * H + h) * nope; + for (0..nope) |d| p += @as(f64, q[qb + d]) * k_nope[kb + d]; + const qr = (t * H + h) * rope_dim; + for (0..rope_dim) |d| p += qrope[qr + d] * krope[k * rope_dim + d]; + scores[(h * T + t) * T + k] = p * sc; + } + } + } + + for (0..H) |h| { + for (0..T) |t| { + var m: f64 = -std.math.inf(f64); + const row = scores[(h * T + t) * T ..][0..T]; + for (0..t + 1) |k| m = @max(m, row[k]); + var den: f64 = 0; + for (0..t + 1) |k| { + row[k] = @exp(row[k] - m); + den += row[k]; + } + for (0..t + 1) |k| row[k] /= den; + var o: [vd]f64 = @splat(0); + for (0..t + 1) |k| { + const a = row[k]; + const vb = (k * H + h) * vd; + for (0..vd) |d| o[d] += a * v[vb + d]; + } + const gate = r64(round, sig(g[t * H + h])); + for (0..vd) |d| y[(t * H + h) * vd + d] = r64(round, r64(round, o[d]) * gate); + } + } +} + +/// Unabsorbed MLA in float64, r = identity. Causal over the given rows; pos0 is RoPE only. +pub fn mixF64( + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + try mixAs(false, alloc, y, q, kv, w_rms, kvb, g, s, rows, pos0); +} + +/// Same mixer with r = bf16 at ling_forward.py's points (RMS, kv_b, rot, attn@v, gate). +pub fn mixBf16( + alloc: std.mem.Allocator, + y: []f64, + q: []const f32, + kv: []const f32, + w_rms: []const f32, + kvb: []const f32, + g: []const f32, + s: Shape, + rows: u32, + pos0: u32, +) !void { + try mixAs(true, alloc, y, q, kv, w_rms, kvb, g, s, rows, pos0); +} + +test "tiny MLA geometry is 16 heads, 512 latent, 64 rope, 128 nope/v, softmax 1/sqrt(192)" { + const tiny = @embedFile("fixtures/tiny_config.json"); + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, tiny, &why); + const s = Shape.of(&c); + try std.testing.expectEqual(@as(u32, 16), s.heads); + try std.testing.expectEqual(@as(u32, 512), lat); + try std.testing.expectEqual(@as(u32, 64), c.rope_dim); + try std.testing.expectEqual(@as(u32, 128), c.nope); + try std.testing.expectEqual(@as(u32, 128), c.v_dim); + try std.testing.expectEqual(config.RopeStyle.gptj, c.rope_style); + try std.testing.expectEqual(@as(f64, 6000000), s.theta); + try std.testing.expectEqual(@as(f32, @floatCast(s.scale())), c.smScale()); +} + +test "expandGate repeats each head value across 128 columns" { + const g = [_]u16{ 0x3f80, 0x4000, 0x4040, 0xc000 }; + var out: [2 * 2 * vd]u16 = undefined; + expandGate(&out, &g, 2, 2); + for (0..vd) |d| { + try std.testing.expectEqual(@as(u16, 0x3f80), out[d]); + try std.testing.expectEqual(@as(u16, 0x4000), out[vd + d]); + try std.testing.expectEqual(@as(u16, 0x4040), out[2 * vd + d]); + try std.testing.expectEqual(@as(u16, 0xc000), out[3 * vd + d]); + } +} + +test "mixF64 of zeros is zeros" { + const a = std.testing.allocator; + const s = Shape{ .heads = 1, .eps = eps_tiny, .theta = theta_tiny }; + var y: [vd]f64 = undefined; + const q: [qd]f32 = @splat(0); + const kv: [key]f32 = @splat(0); + const w: [lat]f32 = @splat(1); + const kvb: [1 * (nope + vd) * lat]f32 = @splat(0); + const g = [_]f32{0}; + try mixF64(a, &y, &q, &kv, &w, &kvb, &g, s, 1, 0); + for (y) |v| try std.testing.expectEqual(@as(f64, 0), v); +} diff --git a/zig/src/families/ling/mla_rope_test.zig b/zig/src/families/ling/mla_rope_test.zig new file mode 100644 index 00000000000..fd808e28aa2 --- /dev/null +++ b/zig/src/families/ling/mla_rope_test.zig @@ -0,0 +1,84 @@ +//! Ling MLA RoPE: GPT-J pairs then halves, matching ling_forward.py rot() and HF apply_rotary_pos_emb_interleave. +const std = @import("std"); +const config = @import("config.zig"); +const bf16_round = @import("bf16_round"); +const mla = @import("mla.zig"); + +pub const rope_dim: u32 = mla.rope_dim; +pub const nfreq: u32 = mla.nfreq; +pub const invFreq = mla.invFreq; +pub const rotate = mla.rotate; +pub const rotateRows = mla.rotateRows; + +fn tinyTheta() !f64 { + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, @embedFile("fixtures/tiny_config.json"), &why); + try std.testing.expectEqual(@as(u32, 64), c.rope_dim); + try std.testing.expectEqual(config.RopeStyle.gptj, c.rope_style); + try std.testing.expectEqual(@as(f64, 6000000), c.rope_theta); + try std.testing.expectEqual(@as(u32, 192), c.qkDim()); + try std.testing.expectEqual(@as(f32, @floatCast(1.0 / @sqrt(@as(f64, 192.0)))), c.smScale()); + return c.rope_theta; +} + +test "tiny MLA rope is 64 GPT-J columns, theta 6e6, softmax 1/sqrt(192)" { + _ = try tinyTheta(); +} + +test "pos 0 writes GPT-J pairs as halves: the identity rotation" { + const theta = try tinyTheta(); + var z: [rope_dim]f64 = undefined; + for (&z, 0..) |*v, i| v.* = @as(f64, @floatFromInt(i)) + 0.25; + var out: [rope_dim]f64 = undefined; + rotate(&out, &z, 0, theta); + for (0..nfreq) |i| { + try std.testing.expectEqual(z[2 * i], out[i]); + try std.testing.expectEqual(z[2 * i + 1], out[nfreq + i]); + } +} + +test "pos 1, 8 and 1024 rotate the first pair by pos radians (frequency 0 is theta^0 = 1)" { + const theta = try tinyTheta(); + try std.testing.expectEqual(@as(f64, 1), invFreq(theta, 0)); + var z: [rope_dim]f64 = @splat(0); + z[0] = 1; + z[1] = 0; + for ([_]u32{ 1, 8, 1024 }) |pos| { + var out: [rope_dim]f64 = undefined; + rotate(&out, &z, pos, theta); + const p: f64 = @floatFromInt(pos); + try std.testing.expectApproxEqAbs(@cos(p), out[0], 1e-12); + try std.testing.expectApproxEqAbs(@sin(p), out[nfreq], 1e-12); + for (1..nfreq) |i| { + try std.testing.expectEqual(@as(f64, 0), out[i]); + try std.testing.expectEqual(@as(f64, 0), out[nfreq + i]); + } + } +} + +test "a pos0 offset of 8 on four rows equals rotating each row at its absolute index" { + const theta = try tinyTheta(); + const rows: u32 = 4; + const pos0: u32 = 8; + var z: [rows * rope_dim]f64 = undefined; + for (&z, 0..) |*v, i| v.* = @as(f64, @floatFromInt(i % 17)) * 0.125 - 1.0; + var chunk: [rows * rope_dim]f64 = undefined; + rotateRows(&chunk, &z, rows, pos0, theta); + var fresh: [rows * rope_dim]f64 = undefined; + for (0..rows) |t| { + rotate(fresh[t * rope_dim ..][0..rope_dim], z[t * rope_dim ..][0..rope_dim], pos0 + @as(u32, @intCast(t)), theta); + } + for (&chunk, fresh) |a, b| try std.testing.expectEqual(a, b); +} + +test "round32 keeps signalling NaN 0x7f800001 and all-ones 0x7fffffff as NaN" { + const cases = [_]u32{ 0x7f800001, 0x7fffffff }; + for (cases) |u| { + const v: f32 = @bitCast(u); + try std.testing.expect(std.math.isNan(v)); + const h = bf16_round.bits(v); + try std.testing.expectEqual(@as(u16, @truncate((u >> 16) | 0x40)), h); + try std.testing.expect(std.math.isNan(bf16_round.value(h))); + try std.testing.expect(std.math.isNan(bf16_round.round32(v))); + } +} diff --git a/zig/src/families/ling/oracle/ling_forward.py b/zig/src/families/ling/oracle/ling_forward.py index 5f51f6b576e..857c01f2ffa 100644 --- a/zig/src/families/ling/oracle/ling_forward.py +++ b/zig/src/families/ling/oracle/ling_forward.py @@ -99,7 +99,17 @@ def kda(self, x, p): y = out / torch.sqrt((out * out).mean(-1, keepdim=True) + self.eps) * w * torch.sigmoid(gate) return self.lin(r(y).reshape(T, H * dk), p + "o_proj") - def mla(self, x, p): + def mla(self, x, p, pos0=0): + """One MLA layer. x is the pre-normed residual [T, hidden]. + + pos0 is the absolute index of row 0, used only for RoPE angles. + mla(x, pos0) attends only over the rows it is given, so with pos0 > 0 it is + that chunk as if it were the whole prompt, placed at pos0. It is not the same + rows taken out of a longer prompt (those also attend to the earlier tokens). + Metal-vs-reference therefore runs on whole prompts from pos0=0. Whole-vs-chunks + and resume-vs-fresh are Metal against Metal. Do not compare a Metal chunk + with mla(chunk, pos0). + """ c, r, ck = self.c, self.r, self.ck T, H = x.shape[0], c["num_attention_heads"] nope, rope, dv, lw = c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"], c["kv_lora_rank"] @@ -108,7 +118,7 @@ def mla(self, x, p): lat = self.norm(kv[:, :lw], ck.t(p + "kv_a_layernorm.weight")) kvb = self.lin(lat, p + "kv_b_proj").view(T, H, nope + dv) inv = 1.0 / c["rope_theta"] ** (torch.arange(0, rope, 2, dtype=torch.float64) / rope) - ang = torch.arange(T, dtype=torch.float64)[:, None] * inv + ang = (pos0 + torch.arange(T, dtype=torch.float64))[:, None] * inv cos, sin = torch.cos(ang), torch.sin(ang) def rot(z): # GPT-J pairs (rope_interleave), out in halves as HF's interleave helper writes them @@ -181,6 +191,14 @@ def mtp_logits(self, ids): return self.norm(x, ck.t(p + "final_layernorm.weight")) @ ck.lin("lm_head").T +def one_mla(ck, c, x, layer, r, pos0=0): + """One MLA layer's output [T, hidden] from its pre-normed input x. Same Model.mla, not a second copy. + + pos0 is for RoPE only; see Model.mla. Do not compare a Metal chunk to one_mla(..., pos0=n). + """ + return Model(ck, c, r).mla(x, f"model.layers.{layer}.attention.", pos0) + + def main(): a = argparse.ArgumentParser(description=__doc__) a.add_argument("ckpt", help="a ling-synth directory (config.json, model.safetensors) or a sharded checkpoint's") @@ -189,11 +207,35 @@ def main(): a.add_argument("--picks", help="route on these picks (i32 [MoE layers][tokens][top_k], the graph's) instead") a.add_argument("--mtp", help="also the MTP layer's logits (float64, bf16 points) and its own picks, to this file") a.add_argument("--ids", help="these tokens (i32, ling-lanes' OUT.ids) instead of the fixed walk; --tokens follows") + a.add_argument("--mla-layer", type=int, metavar="I", help="write one MLA layer's output from --acts instead of full-decoder logits") + a.add_argument("--pos0", type=int, default=0, help="RoPE origin of row 0 of --acts; attention is still only over these rows") + a.add_argument("--acts", help="float64 [T, hidden] pre-normed input for --mla-layer") o = a.parse_args() c = json.load(open(os.path.join(o.ckpt, "config.json"))) one = os.path.join(o.ckpt, "model.safetensors") ck = Ckpt(one if os.path.exists(one) else o.ckpt) V = c["vocab_size"] + if o.mla_layer is not None: + if not o.acts: + a.error("--mla-layer needs --acts") + i = o.mla_layer + stem = f"model.layers.{i}.attention.kv_a_proj_with_mqa" + if not any(k == stem or k.startswith(stem + ".") for k in ck.keys): + a.error(f"layer {i} has no {stem} in the checkpoint: not an MLA layer, or the index is not in this file") + hidden = c["hidden_size"] + raw = torch.frombuffer(bytearray(open(o.acts, "rb").read()), dtype=torch.float64) + if raw.numel() % hidden != 0: + a.error(f"--acts length {raw.numel()} is not a multiple of hidden {hidden}") + x = raw.view(-1, hidden) + T = x.shape[0] + with torch.no_grad(): + y64 = one_mla(ck, c, x, i, lambda z: z, o.pos0) + ybf = one_mla(ck, c, x, i, bf16, o.pos0) + with open(o.out, "wb") as f: + f.write(b"TFLINGA1" + struct.pack("<4I", T, hidden, i, o.pos0)) + f.write(y64.contiguous().numpy().tobytes() + ybf.contiguous().numpy().tobytes()) + print("mla layer", i, "tokens", T, "pos0", o.pos0, "rms", y64.pow(2).mean().sqrt().item()) + return if o.ids: ids = torch.frombuffer(bytearray(open(o.ids, "rb").read()), dtype=torch.int32).long() else: diff --git a/zig/src/families/ling/oracle/mla_dump.py b/zig/src/families/ling/oracle/mla_dump.py new file mode 100644 index 00000000000..2205679bc66 --- /dev/null +++ b/zig/src/families/ling/oracle/mla_dump.py @@ -0,0 +1,222 @@ +"""Tiny-shape MLA dump: ling_forward.py --mla-layer CLI (TFLINGA1) plus mixer inputs. + +Random values in Ling-3.0-tiny tensor shapes, not published checkpoint weights. +Layer 3 MLA tensors are seeded randn * initializer_range (0.02) at tiny's real widths +(hidden 1536, 16 heads, q_lora 256, kv_lora 512). There is no Ling-3.0-tiny +model.safetensors on disk. The CLI writes TFLINGA1 against that synth. +""" +from __future__ import annotations + +import importlib.util +import json +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import torch +from safetensors.torch import save_file + +HERE = Path(__file__).resolve().parent +FIXTURES = HERE.parent / "fixtures" +TINY_CONFIG = FIXTURES / "tiny_config.json" +LAYER = 3 +MAGIC_M1 = b"TFLINGM1" + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +lf = load("ling_forward", HERE / "ling_forward.py") + + +class FakeCkpt: + def __init__(self, tensors): + self.tensors = tensors + self.keys = set(tensors) + + def t(self, name): + return self.tensors[name] + + def lin(self, module): + return self.t(module + ".weight").double() + + +class CaptureModel(lf.Model): + def lin(self, x, module): + y = super().lin(x, module) + self.captured[module] = y.detach().clone() + if module.endswith("dense"): + self.y_pre_dense = x.detach().clone() + return y + + +def f32_bytes(t): + return t.detach().cpu().contiguous().to(torch.float32).numpy().tobytes() + + +def f64_bytes(t): + return t.detach().cpu().contiguous().to(torch.float64).numpy().tobytes() + + +def make_weights(cfg, g): + H = cfg["num_attention_heads"] + hidden = cfg["hidden_size"] + qa = cfg["q_lora_rank"] + lw = cfg["kv_lora_rank"] + nope, rope, dv = cfg["qk_nope_head_dim"], cfg["qk_rope_head_dim"], cfg["v_head_dim"] + p = f"model.layers.{LAYER}.attention." + scale = cfg.get("initializer_range", 0.02) + + def rand(*shape): + return torch.randn(*shape, generator=g, dtype=torch.float64) * scale + + def rand1(*shape): + return 0.5 + 0.5 * torch.randn(*shape, generator=g, dtype=torch.float64) + + return { + p + "q_a_proj.weight": rand(qa, hidden), + p + "q_a_layernorm.weight": rand1(qa), + p + "q_b_proj.weight": rand(H * (nope + rope), qa), + p + "kv_a_proj_with_mqa.weight": rand(lw + rope, hidden), + p + "kv_a_layernorm.weight": rand1(lw), + p + "kv_b_proj.weight": rand(H * (nope + dv), lw), + p + "g_proj.weight": rand(H, hidden), + p + "dense.weight": rand(hidden, H * dv), + } + + +def capture(cfg, tensors_f64, x, pos0): + p = f"model.layers.{LAYER}.attention." + model = CaptureModel(FakeCkpt(tensors_f64), cfg, lambda z: z) + model.captured = {} + model.y_pre_dense = None + with torch.no_grad(): + out = model.mla(x, p, pos0) + H = cfg["num_attention_heads"] + q = model.captured[p + "q_b_proj"].view(x.shape[0], H, -1) + kv = model.captured[p + "kv_a_proj_with_mqa"] + g = model.captured[p + "g_proj"] + return { + "q": q, + "kv": kv, + "g": g, + "y_pre": model.y_pre_dense, + "y": out, + "w_rms": tensors_f64[p + "kv_a_layernorm.weight"], + "kvb": tensors_f64[p + "kv_b_proj.weight"], + "Wo": tensors_f64[p + "dense.weight"], + } + + +def run_cli(ckpt_dir, acts_path, out_path, pos0): + subprocess.check_call( + [ + sys.executable, + str(HERE / "ling_forward.py"), + str(ckpt_dir), + str(out_path), + "--mla-layer", + str(LAYER), + "--acts", + str(acts_path), + "--pos0", + str(pos0), + ] + ) + + +def write_case_files(tmp, cfg, tensors_f32, x, pos0, a1_path): + ckpt_dir = Path(tmp) / "ckpt" + ckpt_dir.mkdir(exist_ok=True) + with open(ckpt_dir / "config.json", "w") as f: + json.dump(cfg, f, indent=2) + save_file(tensors_f32, ckpt_dir / "model.safetensors") + acts_path = Path(tmp) / f"acts_p{pos0}.bin" + acts_path.write_bytes(f64_bytes(x)) + run_cli(ckpt_dir, acts_path, a1_path, pos0) + raw = a1_path.read_bytes() + assert raw[:8] == b"TFLINGA1", raw[:8] + T, hidden, layer, p0 = struct.unpack_from("<4I", raw, 8) + assert T == x.shape[0] and hidden == cfg["hidden_size"] and layer == LAYER and p0 == pos0 + n = T * hidden + y64 = torch.frombuffer(bytearray(raw[24 : 24 + n * 8]), dtype=torch.float64).clone().view(T, hidden) + ybf = torch.frombuffer(bytearray(raw[24 + n * 8 : 24 + 2 * n * 8]), dtype=torch.float64).clone().view(T, hidden) + return y64, ybf + + +def pack_mixer(cfg, tensors_f64, cases, path): + H = cfg["num_attention_heads"] + hidden = cfg["hidden_size"] + w_rms = tensors_f64[f"model.layers.{LAYER}.attention.kv_a_layernorm.weight"] + kvb = tensors_f64[f"model.layers.{LAYER}.attention.kv_b_proj.weight"] + Wo = tensors_f64[f"model.layers.{LAYER}.attention.dense.weight"] + with open(path, "wb") as f: + f.write(MAGIC_M1) + f.write(struct.pack("<4I", hidden, LAYER, H, len(cases))) + f.write(f32_bytes(w_rms)) + f.write(f32_bytes(kvb)) + f.write(f32_bytes(Wo)) + for case in cases: + T = case["q"].shape[0] + f.write(struct.pack("<2I", T, case["pos0"])) + f.write(f32_bytes(case["q"].reshape(T, -1))) + f.write(f32_bytes(case["kv"])) + f.write(f32_bytes(case["g"])) + f.write(f64_bytes(case["y_pre"])) + f.write(f64_bytes(case["y64"])) + f.write(f64_bytes(case["ybf"])) + + +def main(): + out = Path(sys.argv[1] if len(sys.argv) > 1 else "/tmp/ling-mla-dumps") + out.mkdir(parents=True, exist_ok=True) + cfg = json.loads(TINY_CONFIG.read_text()) + g = torch.Generator().manual_seed(0x74696E79) + tensors_f64 = make_weights(cfg, g) + tensors_f32 = {k: v.float().contiguous() for k, v in tensors_f64.items()} + tensors_cli = {k: v.double() for k, v in tensors_f32.items()} + specs = ( + (4, 0, 0x6D6C61, "mla_tiny_t4_pos0.bin"), + (2, 30000, 0x6D6C62, "mla_tiny_t2_pos30000.bin"), + ) + packed = [] + with tempfile.TemporaryDirectory() as tmp: + for T, pos0, seed, a1_name in specs: + gx = torch.Generator().manual_seed(seed) + x = torch.randn(T, cfg["hidden_size"], generator=gx, dtype=torch.float64) + a1_path = out / a1_name + y64, ybf = write_case_files(tmp, cfg, tensors_f32, x, pos0, a1_path) + cap = capture(cfg, tensors_cli, x, pos0) + worst = (cap["y"] - y64).abs().max().item() + print(f"CaptureModel vs TFLINGA1 T={T} pos0={pos0} worst abs {worst:.6e}") + if worst > 1e-12: + raise SystemExit(f"CLI y64 does not match CaptureModel: {worst}") + packed.append( + { + "pos0": pos0, + "q": cap["q"], + "kv": cap["kv"], + "g": cap["g"], + "y_pre": cap["y_pre"], + "y64": y64, + "ybf": ybf, + } + ) + mixer_path = out / "mla_tiny_mixer.bin" + pack_mixer(cfg, tensors_cli, packed, mixer_path) + print("wrote", mixer_path, "bytes", mixer_path.stat().st_size) + for _, _, _, name in specs: + p = out / name + print("wrote", p, "bytes", p.stat().st_size) + + +if __name__ == "__main__": + main() diff --git a/zig/tests/ling_mla_gpu.zig b/zig/tests/ling_mla_gpu.zig new file mode 100644 index 00000000000..0448456ebe3 --- /dev/null +++ b/zig/tests/ling_mla_gpu.zig @@ -0,0 +1,1132 @@ +//! GPU check of Ling MLA around k3_mla: RoPE, head-gate expand, mixer vs mla.zig. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const metallib = @import("kimi_metallib"); + +const source = @import("ling_metal").mla; +const mla_splits: u32 = 16; + +const MlaRow = extern struct { slot: u32, pos: u32 }; +const MlaArgs = extern struct { + cache: u64, + slot_keys: u32, + heads: u32, + head0: u32, + rows: u32, + q_stride: u32, + kv_stride: u32, + gate_stride: u32, + out_stride: u32, + eps: f32, + scale: f32, +}; + +comptime { + if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); +} + +fn toBf16(v: f32) u16 { + const bits: u32 = @bitCast(v); + if (std.math.isNan(v)) return @truncate((bits >> 16) | 0x40); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); +} +fn fromBf16(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +fn fill(seed: *u64, n: usize, a: std.mem.Allocator) ![]f32 { + const x = try a.alloc(f32, n); + for (x) |*v| { + seed.* = seed.* *% 1103515245 +% 12345; + v.* = @as(f32, @floatFromInt((seed.* >> 16) & 0x7fff)) / 16384.0 - 1.0; + } + return x; +} + +fn putBf16(buf: mtl.Buffer, x: []const f32) void { + const d = buf.slice(u16, x.len); + for (x, d) |v, *o| o.* = toBf16(v); +} + +fn roundSlice(x: []f32) void { + for (x) |*v| v.* = fromBf16(toBf16(v.*)); +} + +/// Host f64 cos/sin of each row's pos, rounded to f32. Layout [t][i][comp] = t*64 + i*2 + comp. +fn writeCs(cs: []f32, rows: []const MlaRow, theta: f64) void { + std.debug.assert(cs.len >= rows.len * mla.nfreq * 2); + for (rows, 0..) |r, t| { + for (0..mla.nfreq) |i| { + const ang = @as(f64, @floatFromInt(r.pos)) * mla.invFreq(theta, i); + const at = (t * mla.nfreq + i) * 2; + cs[at] = @floatCast(@cos(ang)); + cs[at + 1] = @floatCast(@sin(ang)); + } + } +} + +const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + kimi: mtl.Library, + ling: mtl.Library, + cache: mtl.Pipeline, + qlat: mtl.Pipeline, + attend: mtl.Pipeline, + merge: mtl.Pipeline, + uv: mtl.Pipeline, + rope_cache: mtl.Pipeline, + rope_q: mtl.Pipeline, + gate_expand: mtl.Pipeline, + + fn init() !Gpu { + const device = try mtl.Device.init(); + errdefer device.deinit(); + const kimi = try mtl.Library.fromBytes(device, metallib.bytes); + errdefer kimi.deinit(); + const ling = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); + errdefer ling.deinit(); + const cache = try mtl.Pipeline.init(device, kimi, "k3_mla_cache", false); + errdefer cache.deinit(); + const qlat = try mtl.Pipeline.init(device, kimi, "k3_mla_qlat", false); + errdefer qlat.deinit(); + const attend = try mtl.Pipeline.init(device, kimi, "k3_mla_attend", false); + errdefer attend.deinit(); + const merge = try mtl.Pipeline.init(device, kimi, "k3_mla_merge", false); + errdefer merge.deinit(); + const uv = try mtl.Pipeline.init(device, kimi, "k3_mla_uv", false); + errdefer uv.deinit(); + const rope_cache = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_cache", false); + errdefer rope_cache.deinit(); + const rope_q = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_q", false); + errdefer rope_q.deinit(); + const gate_expand = try mtl.Pipeline.init(device, ling, "tf_ling_mla_gate_expand", false); + errdefer gate_expand.deinit(); + const queue = try device.queue(); + return .{ + .device = device, + .queue = queue, + .kimi = kimi, + .ling = ling, + .cache = cache, + .qlat = qlat, + .attend = attend, + .merge = merge, + .uv = uv, + .rope_cache = rope_cache, + .rope_q = rope_q, + .gate_expand = gate_expand, + }; + } + + fn deinit(g: *Gpu) void { + g.gate_expand.deinit(); + g.rope_q.deinit(); + g.rope_cache.deinit(); + g.uv.deinit(); + g.merge.deinit(); + g.attend.deinit(); + g.qlat.deinit(); + g.cache.deinit(); + g.ling.deinit(); + g.kimi.deinit(); + g.queue.deinit(); + g.device.deinit(); + } +}; + +const Launch = struct { + s: mla.Shape, + cap: u32, + b_q: mtl.Buffer, + b_kv: mtl.Buffer, + b_w: mtl.Buffer, + b_kvb: mtl.Buffer, + b_g: mtl.Buffer, + b_g2: mtl.Buffer, + b_y: mtl.Buffer, + b_rows: mtl.Buffer, + b_cache: mtl.Buffer, + b_qlat: mtl.Buffer, + b_partial: mtl.Buffer, + b_olat: mtl.Buffer, + b_cs: mtl.Buffer, + + fn open(g: Gpu, s: mla.Shape, cap: u32, q: []const f32, kv: []const f32, w_rms: []const f32, kvb: []const f32, gate: []const f32) !Launch { + const H = s.heads; + const shared = mtl.ResourceOptions.shared; + const b_q = try g.device.buffer(q.len * 2, shared); + const b_kv = try g.device.buffer(kv.len * 2, shared); + const b_w = try g.device.buffer(w_rms.len * 2, shared); + const b_kvb = try g.device.buffer(kvb.len * 2, shared); + const b_g = try g.device.buffer(gate.len * 2, shared); + const b_g2 = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_y = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_rows = try g.device.buffer(cap * @sizeOf(MlaRow), shared); + const b_cache = try g.device.buffer(cap * mla.key * 2, shared); + const b_qlat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_partial = try g.device.buffer(cap * H * mla_splits * (mla.lat + 2) * 4, shared); + const b_olat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_cs = try g.device.buffer(cap * mla.nfreq * 2 * 4, shared); + putBf16(b_q, q); + putBf16(b_kv, kv); + putBf16(b_w, w_rms); + putBf16(b_kvb, kvb); + putBf16(b_g, gate); + @memset(b_g2.slice(u16, cap * H * mla.vd), 0); + @memset(b_y.slice(u16, cap * H * mla.vd), 0); + @memset(b_cache.slice(u16, cap * mla.key), 0); + return .{ + .s = s, + .cap = cap, + .b_q = b_q, + .b_kv = b_kv, + .b_w = b_w, + .b_kvb = b_kvb, + .b_g = b_g, + .b_g2 = b_g2, + .b_y = b_y, + .b_rows = b_rows, + .b_cache = b_cache, + .b_qlat = b_qlat, + .b_partial = b_partial, + .b_olat = b_olat, + .b_cs = b_cs, + }; + } + + fn deinit(l: *Launch) void { + l.b_q.deinit(); + l.b_kv.deinit(); + l.b_w.deinit(); + l.b_kvb.deinit(); + l.b_g.deinit(); + l.b_g2.deinit(); + l.b_y.deinit(); + l.b_rows.deinit(); + l.b_cache.deinit(); + l.b_qlat.deinit(); + l.b_partial.deinit(); + l.b_olat.deinit(); + l.b_cs.deinit(); + } + + fn args(l: *Launch, n: u32) MlaArgs { + const H = l.s.heads; + const ow = H * mla.vd; + return .{ + .cache = l.b_cache.gpuAddress(), + .slot_keys = l.cap, + .heads = H, + .head0 = 0, + .rows = n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = ow, + .out_stride = ow, + .eps = l.s.eps, + .scale = @floatCast(l.s.scale()), + }; + } + + fn fillRows(l: *Launch, first: u32, n: u32) void { + const rows = l.b_rows.slice(MlaRow, n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first + @as(u32, @intCast(i)) }; + } + + fn fillCs(l: *Launch, n: u32) void { + writeCs(l.b_cs.slice(f32, n * mla.nfreq * 2), l.b_rows.slice(MlaRow, n), l.s.theta); + } + + fn dispatchMixer(l: *Launch, g: Gpu, first: u32, n: u32) !void { + const H = l.s.heads; + const a = l.args(n); + l.fillRows(first, n); + l.fillCs(n); + const q_off = first * a.q_stride * 2; + const kv_off = first * a.kv_stride * 2; + const g_off = first * H * 2; + const y_off = first * a.out_stride * 2; + const g2_off = first * a.gate_stride * 2; + const rw = mtl.ResourceUsage.read | mtl.ResourceUsage.write; + const cb = g.queue.commandBuffer(); + const e = cb.compute(.serial); + + e.setPipeline(g.cache); + e.setBuffer(l.b_kv, kv_off, 0); + e.setBuffer(l.b_w, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setValue(a, 3); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.qlat); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_qlat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(2, H, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_q); + e.setBuffer(l.b_q, q_off, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.attend); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_qlat, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setBuffer(l.b_partial, 0, 3); + e.setValue(a, 4); + e.useResource(l.b_cache, mtl.ResourceUsage.read); + const fit: u32 = @intCast(@min(32, g.attend.maxThreads() / 32)); + const groups = (H + fit - 1) / fit; + const per = (H + groups - 1) / groups; + e.dispatchGroups(mtl.Size.of(groups, mla_splits, n), mtl.Size.of(32 * per, 1, 1)); + + e.setPipeline(g.merge); + e.setBuffer(l.b_partial, 0, 0); + e.setBuffer(l.b_rows, 0, 1); + e.setBuffer(l.b_olat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.gate_expand); + e.setBuffer(l.b_g, g_off, 0); + e.setBuffer(l.b_g2, g2_off, 1); + e.setValue(a, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, n, 1), mtl.Size.of(128, 1, 1)); + + e.setPipeline(g.uv); + e.setBuffer(l.b_olat, 0, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_g2, g2_off, 2); + e.setBuffer(l.b_y, y_off, 3); + e.setValue(a, 4); + e.dispatchGroups(mtl.Size.of(mla.vd / 4, H, 1), mtl.Size.of(128, 1, 1)); + + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("GPU mixer failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + + fn y(l: *Launch) []u16 { + return l.b_y.slice(u16, l.cap * l.s.outWidth()); + } +}; + +const Dist = struct { rel_l2: f64, max_abs: f64 }; + +fn dist(got: []const f64, ref: []const f64) Dist { + var num: f64 = 0; + var den: f64 = 0; + var max_abs: f64 = 0; + for (got, ref) |a, b| { + const d = a - b; + num += d * d; + den += b * b; + max_abs = @max(max_abs, @abs(d)); + } + const rel = if (den == 0) @sqrt(num) else @sqrt(num) / @sqrt(den); + return .{ .rel_l2 = rel, .max_abs = max_abs }; +} + +fn bitsToF64(bits: []const u16, out: []f64) void { + for (bits, out) |h, *o| o.* = fromBf16(h); +} + +fn gateNamed(tag: []const u8, metal: []const u16, f64_y: []const f64, bf16_y: []const f64) !void { + const a = std.testing.allocator; + const metal_f = try a.alloc(f64, metal.len); + defer a.free(metal_f); + bitsToF64(metal, metal_f); + try gateNamedF64(tag, metal_f, f64_y, bf16_y); +} + +fn gateNamedF64(tag: []const u8, metal: []const f64, f64_y: []const f64, bf16_y: []const f64) !void { + const m = dist(metal, f64_y); + const b = dist(bf16_y, f64_y); + std.debug.print("{s} Metal-to-f64 rel L2 {e} max abs {e}; bf16-ref-to-f64 rel L2 {e} max abs {e}\n", .{ tag, m.rel_l2, m.max_abs, b.rel_l2, b.max_abs }); + if (m.rel_l2 > b.rel_l2 or m.max_abs > b.max_abs) { + std.debug.print("{s} gate miss: Metal further from f64 than bf16-ref\n", .{tag}); + return error.Gate; + } +} + +fn oProj(out: []f64, y: []const f64, wo: []const f32, rows: u32, hidden: u32, width: u32) void { + std.debug.assert(out.len == rows * hidden and y.len == rows * width and wo.len == hidden * width); + for (0..rows) |t| { + for (0..hidden) |j| { + var acc: f64 = 0; + const wr = j * width; + const yr = t * width; + for (0..width) |i| acc += y[yr + i] * @as(f64, wo[wr + i]); + out[t * hidden + j] = acc; + } + } +} + +fn takeU32(b: []const u8, off: *usize) u32 { + const v = std.mem.readInt(u32, b[off.*..][0..4], .little); + off.* += 4; + return v; +} + +fn takeF32s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f32 { + const x = try alloc.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 4]); + off.* += n * 4; + return x; +} + +fn takeF64s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f64 { + const x = try alloc.alloc(f64, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 8]); + off.* += n * 8; + return x; +} + +const k3_gpu_rows: u32 = 256; +const dump_dir = "/tmp/ling-mla-dumps"; +const dump_mixer_path = dump_dir ++ "/mla_tiny_mixer.bin"; +const dump_a1_t4_path = dump_dir ++ "/mla_tiny_t4_pos0.bin"; +const dump_a1_t2_path = dump_dir ++ "/mla_tiny_t2_pos30000.bin"; +const dump_py = "zig/src/families/ling/oracle/mla_dump.py"; + +const DumpCase = struct { + T: u32, + pos0: u32, + q: []f32, + kv: []f32, + g: []f32, + y_pre: []f64, + y64: []f64, + ybf: []f64, +}; + +const Dump = struct { + hidden: u32, + layer: u32, + heads: u32, + w: []f32, + kvb: []f32, + Wo: []f32, + cases: []DumpCase, + + fn load(alloc: std.mem.Allocator, bytes: []const u8) !Dump { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGM1")); + var off: usize = 8; + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const heads = takeU32(bytes, &off); + const n_cases = takeU32(bytes, &off); + const w = try takeF32s(alloc, bytes, &off, mla.lat); + errdefer alloc.free(w); + const kvb = try takeF32s(alloc, bytes, &off, heads * (mla.nope + mla.vd) * mla.lat); + errdefer alloc.free(kvb); + const Wo = try takeF32s(alloc, bytes, &off, hidden * heads * mla.vd); + errdefer alloc.free(Wo); + const cases = try alloc.alloc(DumpCase, n_cases); + errdefer alloc.free(cases); + for (cases) |*c| { + const T = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const q = try takeF32s(alloc, bytes, &off, T * heads * mla.qd); + const kv = try takeF32s(alloc, bytes, &off, T * mla.key); + const g = try takeF32s(alloc, bytes, &off, T * heads); + const y_pre = try takeF64s(alloc, bytes, &off, T * heads * mla.vd); + const y64 = try takeF64s(alloc, bytes, &off, T * hidden); + const ybf = try takeF64s(alloc, bytes, &off, T * hidden); + c.* = .{ .T = T, .pos0 = pos0, .q = q, .kv = kv, .g = g, .y_pre = y_pre, .y64 = y64, .ybf = ybf }; + } + try std.testing.expectEqual(bytes.len, off); + return .{ .hidden = hidden, .layer = layer, .heads = heads, .w = w, .kvb = kvb, .Wo = Wo, .cases = cases }; + } + + fn deinit(d: Dump, alloc: std.mem.Allocator) void { + for (d.cases) |c| { + alloc.free(c.q); + alloc.free(c.kv); + alloc.free(c.g); + alloc.free(c.y_pre); + alloc.free(c.y64); + alloc.free(c.ybf); + } + alloc.free(d.cases); + alloc.free(d.w); + alloc.free(d.kvb); + alloc.free(d.Wo); + } +}; + +fn parseA1(alloc: std.mem.Allocator, bytes: []const u8) !struct { T: u32, hidden: u32, layer: u32, pos0: u32, y64: []f64, ybf: []f64 } { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGA1")); + var off: usize = 8; + const T = takeU32(bytes, &off); + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const n = T * hidden; + const y64 = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(y64); + const ybf = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(ybf); + try std.testing.expectEqual(bytes.len, off); + return .{ .T = T, .hidden = hidden, .layer = layer, .pos0 = pos0, .y64 = y64, .ybf = ybf }; +} + +fn dupeRound(alloc: std.mem.Allocator, src: []const f32) ![]f32 { + const d = try alloc.dupe(f32, src); + roundSlice(d); + return d; +} + +fn expectBitsEqual(tag: []const u8, a: []const u16, b: []const u16) !void { + if (std.mem.eql(u16, a, b)) return; + var n: usize = 0; + var first: usize = 0; + for (a, b, 0..) |x, yv, i| { + if (x != yv) { + if (n == 0) first = i; + n += 1; + } + } + std.debug.print("{s} bits-equal miss: {d} of {d} first i={d} a={x} b={x}\n", .{ tag, n, a.len, first, a[first], b[first] }); + return error.BitsEqual; +} + +const Inputs = struct { + q: []f32, + kv: []f32, + w: []f32, + kvb: []f32, + g: []f32, + + fn make(alloc: std.mem.Allocator, s: mla.Shape, rows: u32, seed0: u64) !Inputs { + var seed = seed0; + const H = s.heads; + const q = try fill(&seed, rows * H * mla.qd, alloc); + const kv = try fill(&seed, rows * mla.key, alloc); + const w = try fill(&seed, mla.lat, alloc); + const kvb = try fill(&seed, H * (mla.nope + mla.vd) * mla.lat, alloc); + const g = try fill(&seed, rows * H, alloc); + for (w) |*v| v.* = 0.5 + 0.5 * v.*; + roundSlice(q); + roundSlice(kv); + roundSlice(w); + roundSlice(kvb); + roundSlice(g); + return .{ .q = q, .kv = kv, .w = w, .kvb = kvb, .g = g }; + } + + fn free(in: Inputs, alloc: std.mem.Allocator) void { + alloc.free(in.q); + alloc.free(in.kv); + alloc.free(in.w); + alloc.free(in.kvb); + alloc.free(in.g); + } +}; + +fn checkMixer(rows: u32) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const n = rows * s.outWidth(); + const want64 = try a.alloc(f64, n); + defer a.free(want64); + const want_bf = try a.alloc(f64, n); + defer a.free(want_bf); + try mla.mixF64(a, want64, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + try mla.mixBf16(a, want_bf, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try Gpu.init(); + defer g.deinit(); + var l = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer l.deinit(); + try l.dispatchMixer(g, 0, rows); + var buf: [64]u8 = undefined; + const tag = try std.fmt.bufPrint(&buf, "mla {d} rows", .{rows}); + try gateNamed(tag, l.y(), want64, want_bf); +} + +fn checkChunks() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try Gpu.init(); + defer g.deinit(); + var whole = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var chunks = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer chunks.deinit(); + try chunks.dispatchMixer(g, 0, 2); + try chunks.dispatchMixer(g, 2, 2); + try expectBitsEqual("whole vs chunks", whole.y(), chunks.y()); +} + +fn checkResume() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try Inputs.make(a, s, rows, 0x72657375); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try Gpu.init(); + defer g.deinit(); + var fresh = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer fresh.deinit(); + try fresh.dispatchMixer(g, 0, rows); + var continued = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer continued.deinit(); + try continued.dispatchMixer(g, 0, 2); + try continued.dispatchMixer(g, 2, 2); + const W = s.outWidth(); + try expectBitsEqual("resume vs fresh (all rows)", fresh.y(), continued.y()); + try expectBitsEqual("resume vs fresh (last 2)", fresh.y()[2 * W ..], continued.y()[2 * W ..]); +} + +fn checkRopeQ() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x7271; + const q = try fill(&seed, rows * H * mla.qd, a); + defer a.free(q); + roundSlice(q); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try Gpu.init(); + defer gpu.deinit(); + var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(l.b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q failed: {s}\n", .{why}); + return error.GpuFailed; + } + const got = l.b_q.slice(u16, q.len); + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = toBf16(@floatCast(out[i])); + const gbits = got[base + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(fromBf16(want) - fromBf16(gbits))); + } + } + } + std.debug.print("rope_q vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeQ; +} + +fn checkRopeCache() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + var seed: u64 = 0x7263; + const rope_in = try fill(&seed, rows * mla.rope_dim, a); + defer a.free(rope_in); + roundSlice(rope_in); + const H = s.heads; + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try Gpu.init(); + defer gpu.deinit(); + var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + const cache = l.b_cache.slice(u16, rows * mla.key); + @memset(cache, 0); + for (0..rows) |t| { + for (0..mla.rope_dim) |i| cache[t * mla.key + mla.lat + i] = toBf16(rope_in[t * mla.rope_dim + i]); + } + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache failed: {s}\n", .{why}); + return error.GpuFailed; + } + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = toBf16(@floatCast(out[i])); + const gbits = cache[t * mla.key + mla.lat + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(fromBf16(want) - fromBf16(gbits))); + } + } + std.debug.print("rope_cache vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeCache; +} + +fn checkExpand() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x6765; + const gate = try fill(&seed, rows * H, a); + defer a.free(gate); + roundSlice(gate); + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try Gpu.init(); + defer gpu.deinit(); + var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, gate); + defer l.deinit(); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.gate_expand); + e.setBuffer(l.b_g, 0, 0); + e.setBuffer(l.b_g2, 0, 1); + e.setValue(aa, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, rows, 1), mtl.Size.of(128, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("gate_expand failed: {s}\n", .{why}); + return error.GpuFailed; + } + const g_bits = l.b_g.slice(u16, rows * H); + const want = try a.alloc(u16, rows * H * mla.vd); + defer a.free(want); + mla.expandGate(want, g_bits, rows, H); + try expectBitsEqual("gate_expand", l.b_g2.slice(u16, want.len), want); +} + +test "Ling rope_q GPT-J halves vs host rotate" { + try checkRopeQ(); +} + +test "Ling rope_cache GPT-J halves vs host rotate" { + try checkRopeCache(); +} + +test "Ling gate_expand (T,H) to (T,H*128) bits-equal" { + try checkExpand(); +} + +test "MLA mixer Metal vs f64 and bf16-point on 2 rows from pos 0" { + try checkMixer(2); +} + +test "MLA mixer Metal vs f64 and bf16-point on 4 rows from pos 0" { + try checkMixer(4); +} + +test "MLA mixer 4 rows equals 2+2 bits-equal" { + try checkChunks(); +} + +test "MLA mixer resume vs fresh bits-equal" { + try checkResume(); +} + +fn fileOk(path: []const u8) bool { + std.Io.Dir.cwd().access(std.testing.io, path, .{}) catch return false; + return true; +} + +fn hasTorch(py: []const u8) bool { + const a = std.testing.allocator; + const r = std.process.run(a, std.testing.io, .{ + .argv = &.{ py, "-c", "import torch" }, + .stdout_limit = .limited(256), + .stderr_limit = .limited(4096), + }) catch return false; + defer a.free(r.stdout); + defer a.free(r.stderr); + return r.term.success(); +} + +fn findPython() ?[]const u8 { + if (std.c.getenv("TF_LING_PYTHON")) |p| { + const s = std.mem.span(p); + if (hasTorch(s)) return s; + } + if (hasTorch("python3")) return "python3"; + return null; +} + +fn ensureDumps() !void { + if (fileOk(dump_mixer_path) and fileOk(dump_a1_t4_path) and fileOk(dump_a1_t2_path)) return; + if (!fileOk(dump_py)) { + std.debug.print("skip: {s} not in cwd; TFLINGA1 dumps need ling_forward.py at test time\n", .{dump_py}); + return error.SkipZigTest; + } + const py = findPython() orelse { + std.debug.print("skip: no torch (set TF_LING_PYTHON or python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); + return error.SkipZigTest; + }; + const a = std.testing.allocator; + const r = try std.process.run(a, std.testing.io, .{ + .argv = &.{ py, dump_py, dump_dir }, + .stdout_limit = .limited(4096), + .stderr_limit = .limited(65536), + }); + defer a.free(r.stdout); + defer a.free(r.stderr); + if (!r.term.success()) { + std.debug.print("mla_dump.py failed: {s}{s}\n", .{ r.stdout, r.stderr }); + return error.DumpGen; + } + if (!fileOk(dump_mixer_path) or !fileOk(dump_a1_t4_path) or !fileOk(dump_a1_t2_path)) return error.DumpGen; +} + +fn readDump(path: []const u8) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, std.testing.allocator, .limited(32 << 20)); +} + +fn checkDumpFile(a1_path: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + try ensureDumps(); + const a = std.testing.allocator; + const mixer_bytes = try readDump(dump_mixer_path); + defer a.free(mixer_bytes); + const a1_bytes = try readDump(a1_path); + defer a.free(a1_bytes); + try checkDump(mixer_bytes, a1_bytes, case_i, tag, gpu); +} + +fn checkDump(mixer_bytes: []const u8, a1_bytes: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + const a = std.testing.allocator; + const dump = try Dump.load(a, mixer_bytes); + defer dump.deinit(a); + const a1 = try parseA1(a, a1_bytes); + defer a.free(a1.y64); + defer a.free(a1.ybf); + const c = dump.cases[case_i]; + try std.testing.expectEqual(a1.T, c.T); + try std.testing.expectEqual(a1.hidden, dump.hidden); + try std.testing.expectEqual(a1.layer, dump.layer); + try std.testing.expectEqual(a1.pos0, c.pos0); + try std.testing.expect(std.mem.eql(f64, a1.y64, c.y64)); + + const s = mla.Shape{ .heads = dump.heads, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const width = s.outWidth(); + const n_mix = c.T * width; + const mix64 = try a.alloc(f64, n_mix); + defer a.free(mix64); + try mla.mixF64(a, mix64, c.q, c.kv, dump.w, dump.kvb, c.g, s, c.T, c.pos0); + const d_pre = dist(mix64, c.y_pre); + std.debug.print("{s} mixF64-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_pre.rel_l2, d_pre.max_abs }); + const layer_mix = try a.alloc(f64, c.T * dump.hidden); + defer a.free(layer_mix); + oProj(layer_mix, mix64, dump.Wo, c.T, dump.hidden, width); + const d_layer = dist(layer_mix, a1.y64); + std.debug.print("{s} mixF64+o_proj-to-TFLINGA1 rel L2 {e} max abs {e}\n", .{ tag, d_layer.rel_l2, d_layer.max_abs }); + if (!gpu) return; + + const mix_bf = try a.alloc(f64, n_mix); + defer a.free(mix_bf); + const q_m = try dupeRound(a, c.q); + defer a.free(q_m); + const kv_m = try dupeRound(a, c.kv); + defer a.free(kv_m); + const w_m = try dupeRound(a, dump.w); + defer a.free(w_m); + const kvb_m = try dupeRound(a, dump.kvb); + defer a.free(kvb_m); + const g_m = try dupeRound(a, c.g); + defer a.free(g_m); + try mla.mixBf16(a, mix_bf, q_m, kv_m, w_m, kvb_m, g_m, s, c.T, c.pos0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu_dev = try Gpu.init(); + defer gpu_dev.deinit(); + var l = try Launch.open(gpu_dev, s, c.T, q_m, kv_m, w_m, kvb_m, g_m); + defer l.deinit(); + try l.dispatchMixer(gpu_dev, 0, c.T); + const metal_mix = try a.alloc(f64, n_mix); + defer a.free(metal_mix); + bitsToF64(l.y(), metal_mix); + const d_metal_pre = dist(metal_mix, c.y_pre); + std.debug.print("{s} Metal-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_metal_pre.rel_l2, d_metal_pre.max_abs }); + + const layer_bf = try a.alloc(f64, c.T * dump.hidden); + defer a.free(layer_bf); + const layer_metal = try a.alloc(f64, c.T * dump.hidden); + defer a.free(layer_metal); + oProj(layer_bf, mix_bf, dump.Wo, c.T, dump.hidden, width); + oProj(layer_metal, metal_mix, dump.Wo, c.T, dump.hidden, width); + var tbuf: [96]u8 = undefined; + const layer_tag = try std.fmt.bufPrint(&tbuf, "{s} TFLINGA1", .{tag}); + try gateNamedF64(layer_tag, layer_metal, a1.y64, layer_bf); +} + +fn checkRopeLargePos() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows_n: u32 = 2; + const first_pos: u32 = 29998; + const slot_keys: u32 = 30000; + const H = s.heads; + var seed: u64 = 0x72333030; + const q = try fill(&seed, rows_n * H * mla.qd, a); + defer a.free(q); + roundSlice(q); + const rope_in = try fill(&seed, rows_n * mla.rope_dim, a); + defer a.free(rope_in); + roundSlice(rope_in); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try Gpu.init(); + defer gpu.deinit(); + const shared = mtl.ResourceOptions.shared; + const b_q = try gpu.device.buffer(q.len * 2, shared); + defer b_q.deinit(); + putBf16(b_q, q); + const b_rows = try gpu.device.buffer(rows_n * @sizeOf(MlaRow), shared); + defer b_rows.deinit(); + const rows = b_rows.slice(MlaRow, rows_n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first_pos + @as(u32, @intCast(i)) }; + const b_cs = try gpu.device.buffer(rows_n * mla.nfreq * 2 * 4, shared); + defer b_cs.deinit(); + writeCs(b_cs.slice(f32, rows_n * mla.nfreq * 2), rows, s.theta); + const b_cache = try gpu.device.buffer(@as(usize, slot_keys) * mla.key * 2, shared); + defer b_cache.deinit(); + const cache = b_cache.slice(u16, slot_keys * mla.key); + for (0..rows_n) |t| { + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| cache[base + i] = toBf16(rope_in[t * mla.rope_dim + i]); + } + const aa = MlaArgs{ + .cache = b_cache.gpuAddress(), + .slot_keys = slot_keys, + .heads = H, + .head0 = 0, + .rows = rows_n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = H * mla.vd, + .out_stride = H * mla.vd, + .eps = s.eps, + .scale = @floatCast(s.scale()), + }; + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows_n, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const got_q = b_q.slice(u16, q.len); + const nq = rows_n * H * mla.rope_dim; + const metal_q = try a.alloc(f64, nq); + defer a.free(metal_q); + const f64_q = try a.alloc(f64, nq); + defer a.free(f64_q); + const bf_q = try a.alloc(f64, nq); + defer a.free(bf_q); + var k: usize = 0; + for (0..rows_n) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + for (0..mla.rope_dim) |i| { + f64_q[k] = out[i]; + bf_q[k] = fromBf16(toBf16(@floatCast(out[i]))); + metal_q[k] = fromBf16(got_q[base + i]); + k += 1; + } + } + } + const q_gate = gateNamedF64("rope_q pos 29998-29999", metal_q, f64_q, bf_q); + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.useResource(b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows_n, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const nc = rows_n * mla.rope_dim; + const metal_c = try a.alloc(f64, nc); + defer a.free(metal_c); + const f64_c = try a.alloc(f64, nc); + defer a.free(f64_c); + const bf_c = try a.alloc(f64, nc); + defer a.free(bf_c); + k = 0; + for (0..rows_n) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| { + f64_c[k] = out[i]; + bf_c[k] = fromBf16(toBf16(@floatCast(out[i]))); + metal_c[k] = fromBf16(cache[base + i]); + k += 1; + } + } + const c_gate = gateNamedF64("rope_cache pos 29998-29999", metal_c, f64_c, bf_c); + q_gate catch |e| return e; + c_gate catch |e| return e; +} + +fn checkLarge(rows: u32, left: u32, seed: u64, tag: []const u8) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try Inputs.make(a, s, rows, seed); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try Gpu.init(); + defer g.deinit(); + var whole = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var parts = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer parts.deinit(); + try parts.dispatchMixer(g, 0, left); + try parts.dispatchMixer(g, left, rows - left); + var buf: [96]u8 = undefined; + const t1 = try std.fmt.bufPrint(&buf, "{s} whole vs chunks", .{tag}); + try expectBitsEqual(t1, whole.y(), parts.y()); + var buf2: [96]u8 = undefined; + const t2 = try std.fmt.bufPrint(&buf2, "{s} resume vs fresh", .{tag}); + try expectBitsEqual(t2, whole.y(), parts.y()); +} + +test "TFLINGA1 tiny layer 3 T=4 pos0=0 Metal and mixF64 vs python f64" { + try checkDumpFile(dump_a1_t4_path, 0, "dump T=4 pos0=0", true); +} + +test "TFLINGA1 tiny layer 3 T=2 pos0=30000 mixF64 vs python host-only" { + try checkDumpFile(dump_a1_t2_path, 1, "dump T=2 pos0=30000", false); +} + +test "Ling rope_q and rope_cache at pos 29998-29999 vs f64" { + try checkRopeLargePos(); +} + +test "MLA mixer T=100 as 37+63 bits-equal" { + try checkLarge(100, 37, 0x74313030, "T=100"); +} + +test "MLA mixer T=257 as 256+1 bits-equal (k3 gpu_rows)" { + try checkLarge(257, k3_gpu_rows, 0x74323537, "T=257"); +} From 64c33dd3798d9585eeeb7bff31b8e62c9435d4cb Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:21:56 +0100 Subject: [PATCH 009/158] Ling MLA Metal: split GPU tests and one-line comments for lean check Split ling_mla_gpu.zig past 600 lines by job. One-line comments in mla.metal and one-line docstrings in the python oracle. Lean new vs main is 0. --- zig/kernels/metal/ling/mla.metal | 13 +- zig/src/families/ling/oracle/ling_forward.py | 16 +- zig/src/families/ling/oracle/mla_dump.py | 8 +- zig/tests/ling_mla_gpu.zig | 1134 +----------------- zig/tests/ling_mla_gpu_chunks.zig | 238 ++++ zig/tests/ling_mla_gpu_common.zig | 427 +++++++ zig/tests/ling_mla_gpu_dump.zig | 251 ++++ zig/tests/ling_mla_gpu_kernels.zig | 200 +++ zig/tests/ling_mla_gpu_mixer.zig | 38 + 9 files changed, 1170 insertions(+), 1155 deletions(-) create mode 100644 zig/tests/ling_mla_gpu_chunks.zig create mode 100644 zig/tests/ling_mla_gpu_common.zig create mode 100644 zig/tests/ling_mla_gpu_dump.zig create mode 100644 zig/tests/ling_mla_gpu_kernels.zig create mode 100644 zig/tests/ling_mla_gpu_mixer.zig diff --git a/zig/kernels/metal/ling/mla.metal b/zig/kernels/metal/ling/mla.metal index 008f3edbd4c..fcd813af9d5 100644 --- a/zig/kernels/metal/ling/mla.metal +++ b/zig/kernels/metal/ling/mla.metal @@ -1,6 +1,8 @@ // Ling MLA extras around k3: RoPE (GPT-J pairs then halves) and per-head gate expand. -// k3_mla_* kernels are unchanged. Layout matches ling_forward.py rot() and HF -// apply_rotary_pos_emb_interleave: pair (z[2i], z[2i+1]) rotates to (out[i], out[32+i]). + +// k3_mla_* kernels are unchanged. Layout matches ling_forward.py rot() and HF apply_rotary_pos_emb_interleave. + +// Pair (z[2i], z[2i+1]) rotates to (out[i], out[32+i]). #include using namespace metal; @@ -27,8 +29,11 @@ inline device bfloat* ling_keys(constant MlaArgs& a, MlaRow r) { return a.cache + ulong(r.slot) * a.slot_keys * KEY; } -// In-place GPT-J rotate of the 64 rope columns k3_mla_cache just copied. 32 threads, no early -// return: the threadgroup temp needs every lane at the barrier. Cache address is rows[row].pos. +// In-place GPT-J rotate of the 64 rope columns k3_mla_cache just copied. + +// 32 threads, no early return: the threadgroup temp needs every lane at the barrier. + +// Cache address is rows[row].pos. kernel void tf_ling_mla_rope_cache(device const MlaRow* rows [[buffer(0)]], constant MlaArgs& a [[buffer(1)]], device const float* cs [[buffer(2)]], uint row [[threadgroup_position_in_grid]], diff --git a/zig/src/families/ling/oracle/ling_forward.py b/zig/src/families/ling/oracle/ling_forward.py index 857c01f2ffa..aab4c520286 100644 --- a/zig/src/families/ling/oracle/ling_forward.py +++ b/zig/src/families/ling/oracle/ling_forward.py @@ -100,16 +100,7 @@ def kda(self, x, p): return self.lin(r(y).reshape(T, H * dk), p + "o_proj") def mla(self, x, p, pos0=0): - """One MLA layer. x is the pre-normed residual [T, hidden]. - - pos0 is the absolute index of row 0, used only for RoPE angles. - mla(x, pos0) attends only over the rows it is given, so with pos0 > 0 it is - that chunk as if it were the whole prompt, placed at pos0. It is not the same - rows taken out of a longer prompt (those also attend to the earlier tokens). - Metal-vs-reference therefore runs on whole prompts from pos0=0. Whole-vs-chunks - and resume-vs-fresh are Metal against Metal. Do not compare a Metal chunk - with mla(chunk, pos0). - """ + """One MLA layer. x is the pre-normed residual [T, hidden]; attends only over the rows it is given.""" c, r, ck = self.c, self.r, self.ck T, H = x.shape[0], c["num_attention_heads"] nope, rope, dv, lw = c["qk_nope_head_dim"], c["qk_rope_head_dim"], c["v_head_dim"], c["kv_lora_rank"] @@ -192,10 +183,7 @@ def mtp_logits(self, ids): def one_mla(ck, c, x, layer, r, pos0=0): - """One MLA layer's output [T, hidden] from its pre-normed input x. Same Model.mla, not a second copy. - - pos0 is for RoPE only; see Model.mla. Do not compare a Metal chunk to one_mla(..., pos0=n). - """ + """One MLA layer's output [T, hidden] from its pre-normed input x. Same Model.mla, not a second copy.""" return Model(ck, c, r).mla(x, f"model.layers.{layer}.attention.", pos0) diff --git a/zig/src/families/ling/oracle/mla_dump.py b/zig/src/families/ling/oracle/mla_dump.py index 2205679bc66..80f05157b2b 100644 --- a/zig/src/families/ling/oracle/mla_dump.py +++ b/zig/src/families/ling/oracle/mla_dump.py @@ -1,10 +1,4 @@ -"""Tiny-shape MLA dump: ling_forward.py --mla-layer CLI (TFLINGA1) plus mixer inputs. - -Random values in Ling-3.0-tiny tensor shapes, not published checkpoint weights. -Layer 3 MLA tensors are seeded randn * initializer_range (0.02) at tiny's real widths -(hidden 1536, 16 heads, q_lora 256, kv_lora 512). There is no Ling-3.0-tiny -model.safetensors on disk. The CLI writes TFLINGA1 against that synth. -""" +"""Tiny-shape MLA dump (TFLINGA1). Random values in Ling-3.0-tiny tensor shapes, not checkpoint weights.""" from __future__ import annotations import importlib.util diff --git a/zig/tests/ling_mla_gpu.zig b/zig/tests/ling_mla_gpu.zig index 0448456ebe3..15dc64e79d1 100644 --- a/zig/tests/ling_mla_gpu.zig +++ b/zig/tests/ling_mla_gpu.zig @@ -1,1132 +1,6 @@ //! GPU check of Ling MLA around k3_mla: RoPE, head-gate expand, mixer vs mla.zig. -const std = @import("std"); -const mtl = @import("metal"); -const mla = @import("mla"); -const metallib = @import("kimi_metallib"); - -const source = @import("ling_metal").mla; -const mla_splits: u32 = 16; - -const MlaRow = extern struct { slot: u32, pos: u32 }; -const MlaArgs = extern struct { - cache: u64, - slot_keys: u32, - heads: u32, - head0: u32, - rows: u32, - q_stride: u32, - kv_stride: u32, - gate_stride: u32, - out_stride: u32, - eps: f32, - scale: f32, -}; - -comptime { - if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); -} - -fn toBf16(v: f32) u16 { - const bits: u32 = @bitCast(v); - if (std.math.isNan(v)) return @truncate((bits >> 16) | 0x40); - return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); -} -fn fromBf16(h: u16) f32 { - return @bitCast(@as(u32, h) << 16); -} - -fn fill(seed: *u64, n: usize, a: std.mem.Allocator) ![]f32 { - const x = try a.alloc(f32, n); - for (x) |*v| { - seed.* = seed.* *% 1103515245 +% 12345; - v.* = @as(f32, @floatFromInt((seed.* >> 16) & 0x7fff)) / 16384.0 - 1.0; - } - return x; -} - -fn putBf16(buf: mtl.Buffer, x: []const f32) void { - const d = buf.slice(u16, x.len); - for (x, d) |v, *o| o.* = toBf16(v); -} - -fn roundSlice(x: []f32) void { - for (x) |*v| v.* = fromBf16(toBf16(v.*)); -} - -/// Host f64 cos/sin of each row's pos, rounded to f32. Layout [t][i][comp] = t*64 + i*2 + comp. -fn writeCs(cs: []f32, rows: []const MlaRow, theta: f64) void { - std.debug.assert(cs.len >= rows.len * mla.nfreq * 2); - for (rows, 0..) |r, t| { - for (0..mla.nfreq) |i| { - const ang = @as(f64, @floatFromInt(r.pos)) * mla.invFreq(theta, i); - const at = (t * mla.nfreq + i) * 2; - cs[at] = @floatCast(@cos(ang)); - cs[at + 1] = @floatCast(@sin(ang)); - } - } -} - -const Gpu = struct { - device: mtl.Device, - queue: mtl.Queue, - kimi: mtl.Library, - ling: mtl.Library, - cache: mtl.Pipeline, - qlat: mtl.Pipeline, - attend: mtl.Pipeline, - merge: mtl.Pipeline, - uv: mtl.Pipeline, - rope_cache: mtl.Pipeline, - rope_q: mtl.Pipeline, - gate_expand: mtl.Pipeline, - - fn init() !Gpu { - const device = try mtl.Device.init(); - errdefer device.deinit(); - const kimi = try mtl.Library.fromBytes(device, metallib.bytes); - errdefer kimi.deinit(); - const ling = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); - errdefer ling.deinit(); - const cache = try mtl.Pipeline.init(device, kimi, "k3_mla_cache", false); - errdefer cache.deinit(); - const qlat = try mtl.Pipeline.init(device, kimi, "k3_mla_qlat", false); - errdefer qlat.deinit(); - const attend = try mtl.Pipeline.init(device, kimi, "k3_mla_attend", false); - errdefer attend.deinit(); - const merge = try mtl.Pipeline.init(device, kimi, "k3_mla_merge", false); - errdefer merge.deinit(); - const uv = try mtl.Pipeline.init(device, kimi, "k3_mla_uv", false); - errdefer uv.deinit(); - const rope_cache = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_cache", false); - errdefer rope_cache.deinit(); - const rope_q = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_q", false); - errdefer rope_q.deinit(); - const gate_expand = try mtl.Pipeline.init(device, ling, "tf_ling_mla_gate_expand", false); - errdefer gate_expand.deinit(); - const queue = try device.queue(); - return .{ - .device = device, - .queue = queue, - .kimi = kimi, - .ling = ling, - .cache = cache, - .qlat = qlat, - .attend = attend, - .merge = merge, - .uv = uv, - .rope_cache = rope_cache, - .rope_q = rope_q, - .gate_expand = gate_expand, - }; - } - - fn deinit(g: *Gpu) void { - g.gate_expand.deinit(); - g.rope_q.deinit(); - g.rope_cache.deinit(); - g.uv.deinit(); - g.merge.deinit(); - g.attend.deinit(); - g.qlat.deinit(); - g.cache.deinit(); - g.ling.deinit(); - g.kimi.deinit(); - g.queue.deinit(); - g.device.deinit(); - } -}; - -const Launch = struct { - s: mla.Shape, - cap: u32, - b_q: mtl.Buffer, - b_kv: mtl.Buffer, - b_w: mtl.Buffer, - b_kvb: mtl.Buffer, - b_g: mtl.Buffer, - b_g2: mtl.Buffer, - b_y: mtl.Buffer, - b_rows: mtl.Buffer, - b_cache: mtl.Buffer, - b_qlat: mtl.Buffer, - b_partial: mtl.Buffer, - b_olat: mtl.Buffer, - b_cs: mtl.Buffer, - - fn open(g: Gpu, s: mla.Shape, cap: u32, q: []const f32, kv: []const f32, w_rms: []const f32, kvb: []const f32, gate: []const f32) !Launch { - const H = s.heads; - const shared = mtl.ResourceOptions.shared; - const b_q = try g.device.buffer(q.len * 2, shared); - const b_kv = try g.device.buffer(kv.len * 2, shared); - const b_w = try g.device.buffer(w_rms.len * 2, shared); - const b_kvb = try g.device.buffer(kvb.len * 2, shared); - const b_g = try g.device.buffer(gate.len * 2, shared); - const b_g2 = try g.device.buffer(cap * H * mla.vd * 2, shared); - const b_y = try g.device.buffer(cap * H * mla.vd * 2, shared); - const b_rows = try g.device.buffer(cap * @sizeOf(MlaRow), shared); - const b_cache = try g.device.buffer(cap * mla.key * 2, shared); - const b_qlat = try g.device.buffer(cap * H * mla.lat * 4, shared); - const b_partial = try g.device.buffer(cap * H * mla_splits * (mla.lat + 2) * 4, shared); - const b_olat = try g.device.buffer(cap * H * mla.lat * 4, shared); - const b_cs = try g.device.buffer(cap * mla.nfreq * 2 * 4, shared); - putBf16(b_q, q); - putBf16(b_kv, kv); - putBf16(b_w, w_rms); - putBf16(b_kvb, kvb); - putBf16(b_g, gate); - @memset(b_g2.slice(u16, cap * H * mla.vd), 0); - @memset(b_y.slice(u16, cap * H * mla.vd), 0); - @memset(b_cache.slice(u16, cap * mla.key), 0); - return .{ - .s = s, - .cap = cap, - .b_q = b_q, - .b_kv = b_kv, - .b_w = b_w, - .b_kvb = b_kvb, - .b_g = b_g, - .b_g2 = b_g2, - .b_y = b_y, - .b_rows = b_rows, - .b_cache = b_cache, - .b_qlat = b_qlat, - .b_partial = b_partial, - .b_olat = b_olat, - .b_cs = b_cs, - }; - } - - fn deinit(l: *Launch) void { - l.b_q.deinit(); - l.b_kv.deinit(); - l.b_w.deinit(); - l.b_kvb.deinit(); - l.b_g.deinit(); - l.b_g2.deinit(); - l.b_y.deinit(); - l.b_rows.deinit(); - l.b_cache.deinit(); - l.b_qlat.deinit(); - l.b_partial.deinit(); - l.b_olat.deinit(); - l.b_cs.deinit(); - } - - fn args(l: *Launch, n: u32) MlaArgs { - const H = l.s.heads; - const ow = H * mla.vd; - return .{ - .cache = l.b_cache.gpuAddress(), - .slot_keys = l.cap, - .heads = H, - .head0 = 0, - .rows = n, - .q_stride = H * mla.qd, - .kv_stride = mla.key, - .gate_stride = ow, - .out_stride = ow, - .eps = l.s.eps, - .scale = @floatCast(l.s.scale()), - }; - } - - fn fillRows(l: *Launch, first: u32, n: u32) void { - const rows = l.b_rows.slice(MlaRow, n); - for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first + @as(u32, @intCast(i)) }; - } - - fn fillCs(l: *Launch, n: u32) void { - writeCs(l.b_cs.slice(f32, n * mla.nfreq * 2), l.b_rows.slice(MlaRow, n), l.s.theta); - } - - fn dispatchMixer(l: *Launch, g: Gpu, first: u32, n: u32) !void { - const H = l.s.heads; - const a = l.args(n); - l.fillRows(first, n); - l.fillCs(n); - const q_off = first * a.q_stride * 2; - const kv_off = first * a.kv_stride * 2; - const g_off = first * H * 2; - const y_off = first * a.out_stride * 2; - const g2_off = first * a.gate_stride * 2; - const rw = mtl.ResourceUsage.read | mtl.ResourceUsage.write; - const cb = g.queue.commandBuffer(); - const e = cb.compute(.serial); - - e.setPipeline(g.cache); - e.setBuffer(l.b_kv, kv_off, 0); - e.setBuffer(l.b_w, 0, 1); - e.setBuffer(l.b_rows, 0, 2); - e.setValue(a, 3); - e.useResource(l.b_cache, rw); - e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); - - e.setPipeline(g.rope_cache); - e.setBuffer(l.b_rows, 0, 0); - e.setValue(a, 1); - e.setBuffer(l.b_cs, 0, 2); - e.useResource(l.b_cache, rw); - e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); - - e.setPipeline(g.qlat); - e.setBuffer(l.b_q, q_off, 0); - e.setBuffer(l.b_kvb, 0, 1); - e.setBuffer(l.b_qlat, 0, 2); - e.setValue(a, 3); - e.dispatchGroups(mtl.Size.of(2, H, 1), mtl.Size.of(256, 1, 1)); - - e.setPipeline(g.rope_q); - e.setBuffer(l.b_q, q_off, 0); - e.setValue(a, 1); - e.setBuffer(l.b_cs, 0, 2); - e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(32, 1, 1)); - - e.setPipeline(g.attend); - e.setBuffer(l.b_q, q_off, 0); - e.setBuffer(l.b_qlat, 0, 1); - e.setBuffer(l.b_rows, 0, 2); - e.setBuffer(l.b_partial, 0, 3); - e.setValue(a, 4); - e.useResource(l.b_cache, mtl.ResourceUsage.read); - const fit: u32 = @intCast(@min(32, g.attend.maxThreads() / 32)); - const groups = (H + fit - 1) / fit; - const per = (H + groups - 1) / groups; - e.dispatchGroups(mtl.Size.of(groups, mla_splits, n), mtl.Size.of(32 * per, 1, 1)); - - e.setPipeline(g.merge); - e.setBuffer(l.b_partial, 0, 0); - e.setBuffer(l.b_rows, 0, 1); - e.setBuffer(l.b_olat, 0, 2); - e.setValue(a, 3); - e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(256, 1, 1)); - - e.setPipeline(g.gate_expand); - e.setBuffer(l.b_g, g_off, 0); - e.setBuffer(l.b_g2, g2_off, 1); - e.setValue(a, 2); - e.dispatchThreads(mtl.Size.of(H * mla.vd, n, 1), mtl.Size.of(128, 1, 1)); - - e.setPipeline(g.uv); - e.setBuffer(l.b_olat, 0, 0); - e.setBuffer(l.b_kvb, 0, 1); - e.setBuffer(l.b_g2, g2_off, 2); - e.setBuffer(l.b_y, y_off, 3); - e.setValue(a, 4); - e.dispatchGroups(mtl.Size.of(mla.vd / 4, H, 1), mtl.Size.of(128, 1, 1)); - - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("GPU mixer failed: {s}\n", .{why}); - return error.GpuFailed; - } - } - - fn y(l: *Launch) []u16 { - return l.b_y.slice(u16, l.cap * l.s.outWidth()); - } -}; - -const Dist = struct { rel_l2: f64, max_abs: f64 }; - -fn dist(got: []const f64, ref: []const f64) Dist { - var num: f64 = 0; - var den: f64 = 0; - var max_abs: f64 = 0; - for (got, ref) |a, b| { - const d = a - b; - num += d * d; - den += b * b; - max_abs = @max(max_abs, @abs(d)); - } - const rel = if (den == 0) @sqrt(num) else @sqrt(num) / @sqrt(den); - return .{ .rel_l2 = rel, .max_abs = max_abs }; -} - -fn bitsToF64(bits: []const u16, out: []f64) void { - for (bits, out) |h, *o| o.* = fromBf16(h); -} - -fn gateNamed(tag: []const u8, metal: []const u16, f64_y: []const f64, bf16_y: []const f64) !void { - const a = std.testing.allocator; - const metal_f = try a.alloc(f64, metal.len); - defer a.free(metal_f); - bitsToF64(metal, metal_f); - try gateNamedF64(tag, metal_f, f64_y, bf16_y); -} - -fn gateNamedF64(tag: []const u8, metal: []const f64, f64_y: []const f64, bf16_y: []const f64) !void { - const m = dist(metal, f64_y); - const b = dist(bf16_y, f64_y); - std.debug.print("{s} Metal-to-f64 rel L2 {e} max abs {e}; bf16-ref-to-f64 rel L2 {e} max abs {e}\n", .{ tag, m.rel_l2, m.max_abs, b.rel_l2, b.max_abs }); - if (m.rel_l2 > b.rel_l2 or m.max_abs > b.max_abs) { - std.debug.print("{s} gate miss: Metal further from f64 than bf16-ref\n", .{tag}); - return error.Gate; - } -} - -fn oProj(out: []f64, y: []const f64, wo: []const f32, rows: u32, hidden: u32, width: u32) void { - std.debug.assert(out.len == rows * hidden and y.len == rows * width and wo.len == hidden * width); - for (0..rows) |t| { - for (0..hidden) |j| { - var acc: f64 = 0; - const wr = j * width; - const yr = t * width; - for (0..width) |i| acc += y[yr + i] * @as(f64, wo[wr + i]); - out[t * hidden + j] = acc; - } - } -} - -fn takeU32(b: []const u8, off: *usize) u32 { - const v = std.mem.readInt(u32, b[off.*..][0..4], .little); - off.* += 4; - return v; -} - -fn takeF32s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f32 { - const x = try alloc.alloc(f32, n); - @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 4]); - off.* += n * 4; - return x; -} - -fn takeF64s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f64 { - const x = try alloc.alloc(f64, n); - @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 8]); - off.* += n * 8; - return x; -} - -const k3_gpu_rows: u32 = 256; -const dump_dir = "/tmp/ling-mla-dumps"; -const dump_mixer_path = dump_dir ++ "/mla_tiny_mixer.bin"; -const dump_a1_t4_path = dump_dir ++ "/mla_tiny_t4_pos0.bin"; -const dump_a1_t2_path = dump_dir ++ "/mla_tiny_t2_pos30000.bin"; -const dump_py = "zig/src/families/ling/oracle/mla_dump.py"; - -const DumpCase = struct { - T: u32, - pos0: u32, - q: []f32, - kv: []f32, - g: []f32, - y_pre: []f64, - y64: []f64, - ybf: []f64, -}; - -const Dump = struct { - hidden: u32, - layer: u32, - heads: u32, - w: []f32, - kvb: []f32, - Wo: []f32, - cases: []DumpCase, - - fn load(alloc: std.mem.Allocator, bytes: []const u8) !Dump { - try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGM1")); - var off: usize = 8; - const hidden = takeU32(bytes, &off); - const layer = takeU32(bytes, &off); - const heads = takeU32(bytes, &off); - const n_cases = takeU32(bytes, &off); - const w = try takeF32s(alloc, bytes, &off, mla.lat); - errdefer alloc.free(w); - const kvb = try takeF32s(alloc, bytes, &off, heads * (mla.nope + mla.vd) * mla.lat); - errdefer alloc.free(kvb); - const Wo = try takeF32s(alloc, bytes, &off, hidden * heads * mla.vd); - errdefer alloc.free(Wo); - const cases = try alloc.alloc(DumpCase, n_cases); - errdefer alloc.free(cases); - for (cases) |*c| { - const T = takeU32(bytes, &off); - const pos0 = takeU32(bytes, &off); - const q = try takeF32s(alloc, bytes, &off, T * heads * mla.qd); - const kv = try takeF32s(alloc, bytes, &off, T * mla.key); - const g = try takeF32s(alloc, bytes, &off, T * heads); - const y_pre = try takeF64s(alloc, bytes, &off, T * heads * mla.vd); - const y64 = try takeF64s(alloc, bytes, &off, T * hidden); - const ybf = try takeF64s(alloc, bytes, &off, T * hidden); - c.* = .{ .T = T, .pos0 = pos0, .q = q, .kv = kv, .g = g, .y_pre = y_pre, .y64 = y64, .ybf = ybf }; - } - try std.testing.expectEqual(bytes.len, off); - return .{ .hidden = hidden, .layer = layer, .heads = heads, .w = w, .kvb = kvb, .Wo = Wo, .cases = cases }; - } - - fn deinit(d: Dump, alloc: std.mem.Allocator) void { - for (d.cases) |c| { - alloc.free(c.q); - alloc.free(c.kv); - alloc.free(c.g); - alloc.free(c.y_pre); - alloc.free(c.y64); - alloc.free(c.ybf); - } - alloc.free(d.cases); - alloc.free(d.w); - alloc.free(d.kvb); - alloc.free(d.Wo); - } -}; - -fn parseA1(alloc: std.mem.Allocator, bytes: []const u8) !struct { T: u32, hidden: u32, layer: u32, pos0: u32, y64: []f64, ybf: []f64 } { - try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGA1")); - var off: usize = 8; - const T = takeU32(bytes, &off); - const hidden = takeU32(bytes, &off); - const layer = takeU32(bytes, &off); - const pos0 = takeU32(bytes, &off); - const n = T * hidden; - const y64 = try takeF64s(alloc, bytes, &off, n); - errdefer alloc.free(y64); - const ybf = try takeF64s(alloc, bytes, &off, n); - errdefer alloc.free(ybf); - try std.testing.expectEqual(bytes.len, off); - return .{ .T = T, .hidden = hidden, .layer = layer, .pos0 = pos0, .y64 = y64, .ybf = ybf }; -} - -fn dupeRound(alloc: std.mem.Allocator, src: []const f32) ![]f32 { - const d = try alloc.dupe(f32, src); - roundSlice(d); - return d; -} - -fn expectBitsEqual(tag: []const u8, a: []const u16, b: []const u16) !void { - if (std.mem.eql(u16, a, b)) return; - var n: usize = 0; - var first: usize = 0; - for (a, b, 0..) |x, yv, i| { - if (x != yv) { - if (n == 0) first = i; - n += 1; - } - } - std.debug.print("{s} bits-equal miss: {d} of {d} first i={d} a={x} b={x}\n", .{ tag, n, a.len, first, a[first], b[first] }); - return error.BitsEqual; -} - -const Inputs = struct { - q: []f32, - kv: []f32, - w: []f32, - kvb: []f32, - g: []f32, - - fn make(alloc: std.mem.Allocator, s: mla.Shape, rows: u32, seed0: u64) !Inputs { - var seed = seed0; - const H = s.heads; - const q = try fill(&seed, rows * H * mla.qd, alloc); - const kv = try fill(&seed, rows * mla.key, alloc); - const w = try fill(&seed, mla.lat, alloc); - const kvb = try fill(&seed, H * (mla.nope + mla.vd) * mla.lat, alloc); - const g = try fill(&seed, rows * H, alloc); - for (w) |*v| v.* = 0.5 + 0.5 * v.*; - roundSlice(q); - roundSlice(kv); - roundSlice(w); - roundSlice(kvb); - roundSlice(g); - return .{ .q = q, .kv = kv, .w = w, .kvb = kvb, .g = g }; - } - - fn free(in: Inputs, alloc: std.mem.Allocator) void { - alloc.free(in.q); - alloc.free(in.kv); - alloc.free(in.w); - alloc.free(in.kvb); - alloc.free(in.g); - } -}; - -fn checkMixer(rows: u32) !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const in = try Inputs.make(a, s, rows, 0x6d6c61); - defer in.free(a); - const n = rows * s.outWidth(); - const want64 = try a.alloc(f64, n); - defer a.free(want64); - const want_bf = try a.alloc(f64, n); - defer a.free(want_bf); - try mla.mixF64(a, want64, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); - try mla.mixBf16(a, want_bf, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var g = try Gpu.init(); - defer g.deinit(); - var l = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer l.deinit(); - try l.dispatchMixer(g, 0, rows); - var buf: [64]u8 = undefined; - const tag = try std.fmt.bufPrint(&buf, "mla {d} rows", .{rows}); - try gateNamed(tag, l.y(), want64, want_bf); -} - -fn checkChunks() !void { - const a = std.testing.allocator; - const rows: u32 = 4; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const in = try Inputs.make(a, s, rows, 0x6d6c61); - defer in.free(a); - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var g = try Gpu.init(); - defer g.deinit(); - var whole = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer whole.deinit(); - try whole.dispatchMixer(g, 0, rows); - var chunks = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer chunks.deinit(); - try chunks.dispatchMixer(g, 0, 2); - try chunks.dispatchMixer(g, 2, 2); - try expectBitsEqual("whole vs chunks", whole.y(), chunks.y()); -} - -fn checkResume() !void { - const a = std.testing.allocator; - const rows: u32 = 4; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const in = try Inputs.make(a, s, rows, 0x72657375); - defer in.free(a); - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var g = try Gpu.init(); - defer g.deinit(); - var fresh = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer fresh.deinit(); - try fresh.dispatchMixer(g, 0, rows); - var continued = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer continued.deinit(); - try continued.dispatchMixer(g, 0, 2); - try continued.dispatchMixer(g, 2, 2); - const W = s.outWidth(); - try expectBitsEqual("resume vs fresh (all rows)", fresh.y(), continued.y()); - try expectBitsEqual("resume vs fresh (last 2)", fresh.y()[2 * W ..], continued.y()[2 * W ..]); -} - -fn checkRopeQ() !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const rows: u32 = 4; - const H = s.heads; - var seed: u64 = 0x7271; - const q = try fill(&seed, rows * H * mla.qd, a); - defer a.free(q); - roundSlice(q); - const kv = try a.alloc(f32, rows * mla.key); - defer a.free(kv); - @memset(kv, 0); - const w_rms: [mla.lat]f32 = @splat(1); - const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); - defer a.free(kvb_w); - @memset(kvb_w, 0); - const g = try a.alloc(f32, rows * H); - defer a.free(g); - @memset(g, 0); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var gpu = try Gpu.init(); - defer gpu.deinit(); - var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); - defer l.deinit(); - l.fillRows(0, rows); - l.fillCs(rows); - const aa = l.args(rows); - const cb = gpu.queue.commandBuffer(); - const e = cb.compute(.serial); - e.setPipeline(gpu.rope_q); - e.setBuffer(l.b_q, 0, 0); - e.setValue(aa, 1); - e.setBuffer(l.b_cs, 0, 2); - e.dispatchGroups(mtl.Size.of(H, rows, 1), mtl.Size.of(32, 1, 1)); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("rope_q failed: {s}\n", .{why}); - return error.GpuFailed; - } - const got = l.b_q.slice(u16, q.len); - var worst: f32 = 0; - var bits_miss: usize = 0; - for (0..rows) |t| { - for (0..H) |h| { - var z64: [mla.rope_dim]f64 = undefined; - var out: [mla.rope_dim]f64 = undefined; - const base = (t * H + h) * mla.qd + mla.nope; - for (0..mla.rope_dim) |i| z64[i] = q[base + i]; - mla.rotate(&out, &z64, @intCast(t), s.theta); - for (0..mla.rope_dim) |i| { - const want = toBf16(@floatCast(out[i])); - const gbits = got[base + i]; - if (want != gbits) bits_miss += 1; - worst = @max(worst, @abs(fromBf16(want) - fromBf16(gbits))); - } - } - } - std.debug.print("rope_q vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); - if (worst > 2e-3) return error.RopeQ; -} - -fn checkRopeCache() !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const rows: u32 = 4; - var seed: u64 = 0x7263; - const rope_in = try fill(&seed, rows * mla.rope_dim, a); - defer a.free(rope_in); - roundSlice(rope_in); - const H = s.heads; - const q = try a.alloc(f32, rows * H * mla.qd); - defer a.free(q); - @memset(q, 0); - const kv = try a.alloc(f32, rows * mla.key); - defer a.free(kv); - @memset(kv, 0); - const w_rms: [mla.lat]f32 = @splat(1); - const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); - defer a.free(kvb_w); - @memset(kvb_w, 0); - const g = try a.alloc(f32, rows * H); - defer a.free(g); - @memset(g, 0); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var gpu = try Gpu.init(); - defer gpu.deinit(); - var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); - defer l.deinit(); - const cache = l.b_cache.slice(u16, rows * mla.key); - @memset(cache, 0); - for (0..rows) |t| { - for (0..mla.rope_dim) |i| cache[t * mla.key + mla.lat + i] = toBf16(rope_in[t * mla.rope_dim + i]); - } - l.fillRows(0, rows); - l.fillCs(rows); - const aa = l.args(rows); - const cb = gpu.queue.commandBuffer(); - const e = cb.compute(.serial); - e.setPipeline(gpu.rope_cache); - e.setBuffer(l.b_rows, 0, 0); - e.setValue(aa, 1); - e.setBuffer(l.b_cs, 0, 2); - e.useResource(l.b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); - e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("rope_cache failed: {s}\n", .{why}); - return error.GpuFailed; - } - var worst: f32 = 0; - var bits_miss: usize = 0; - for (0..rows) |t| { - var z64: [mla.rope_dim]f64 = undefined; - var out: [mla.rope_dim]f64 = undefined; - for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; - mla.rotate(&out, &z64, @intCast(t), s.theta); - for (0..mla.rope_dim) |i| { - const want = toBf16(@floatCast(out[i])); - const gbits = cache[t * mla.key + mla.lat + i]; - if (want != gbits) bits_miss += 1; - worst = @max(worst, @abs(fromBf16(want) - fromBf16(gbits))); - } - } - std.debug.print("rope_cache vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); - if (worst > 2e-3) return error.RopeCache; -} - -fn checkExpand() !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const rows: u32 = 4; - const H = s.heads; - var seed: u64 = 0x6765; - const gate = try fill(&seed, rows * H, a); - defer a.free(gate); - roundSlice(gate); - const q = try a.alloc(f32, rows * H * mla.qd); - defer a.free(q); - @memset(q, 0); - const kv = try a.alloc(f32, rows * mla.key); - defer a.free(kv); - @memset(kv, 0); - const w_rms: [mla.lat]f32 = @splat(1); - const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); - defer a.free(kvb_w); - @memset(kvb_w, 0); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var gpu = try Gpu.init(); - defer gpu.deinit(); - var l = try Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, gate); - defer l.deinit(); - const aa = l.args(rows); - const cb = gpu.queue.commandBuffer(); - const e = cb.compute(.serial); - e.setPipeline(gpu.gate_expand); - e.setBuffer(l.b_g, 0, 0); - e.setBuffer(l.b_g2, 0, 1); - e.setValue(aa, 2); - e.dispatchThreads(mtl.Size.of(H * mla.vd, rows, 1), mtl.Size.of(128, 1, 1)); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("gate_expand failed: {s}\n", .{why}); - return error.GpuFailed; - } - const g_bits = l.b_g.slice(u16, rows * H); - const want = try a.alloc(u16, rows * H * mla.vd); - defer a.free(want); - mla.expandGate(want, g_bits, rows, H); - try expectBitsEqual("gate_expand", l.b_g2.slice(u16, want.len), want); -} - -test "Ling rope_q GPT-J halves vs host rotate" { - try checkRopeQ(); -} - -test "Ling rope_cache GPT-J halves vs host rotate" { - try checkRopeCache(); -} - -test "Ling gate_expand (T,H) to (T,H*128) bits-equal" { - try checkExpand(); -} - -test "MLA mixer Metal vs f64 and bf16-point on 2 rows from pos 0" { - try checkMixer(2); -} - -test "MLA mixer Metal vs f64 and bf16-point on 4 rows from pos 0" { - try checkMixer(4); -} - -test "MLA mixer 4 rows equals 2+2 bits-equal" { - try checkChunks(); -} - -test "MLA mixer resume vs fresh bits-equal" { - try checkResume(); -} - -fn fileOk(path: []const u8) bool { - std.Io.Dir.cwd().access(std.testing.io, path, .{}) catch return false; - return true; -} - -fn hasTorch(py: []const u8) bool { - const a = std.testing.allocator; - const r = std.process.run(a, std.testing.io, .{ - .argv = &.{ py, "-c", "import torch" }, - .stdout_limit = .limited(256), - .stderr_limit = .limited(4096), - }) catch return false; - defer a.free(r.stdout); - defer a.free(r.stderr); - return r.term.success(); -} - -fn findPython() ?[]const u8 { - if (std.c.getenv("TF_LING_PYTHON")) |p| { - const s = std.mem.span(p); - if (hasTorch(s)) return s; - } - if (hasTorch("python3")) return "python3"; - return null; -} - -fn ensureDumps() !void { - if (fileOk(dump_mixer_path) and fileOk(dump_a1_t4_path) and fileOk(dump_a1_t2_path)) return; - if (!fileOk(dump_py)) { - std.debug.print("skip: {s} not in cwd; TFLINGA1 dumps need ling_forward.py at test time\n", .{dump_py}); - return error.SkipZigTest; - } - const py = findPython() orelse { - std.debug.print("skip: no torch (set TF_LING_PYTHON or python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); - return error.SkipZigTest; - }; - const a = std.testing.allocator; - const r = try std.process.run(a, std.testing.io, .{ - .argv = &.{ py, dump_py, dump_dir }, - .stdout_limit = .limited(4096), - .stderr_limit = .limited(65536), - }); - defer a.free(r.stdout); - defer a.free(r.stderr); - if (!r.term.success()) { - std.debug.print("mla_dump.py failed: {s}{s}\n", .{ r.stdout, r.stderr }); - return error.DumpGen; - } - if (!fileOk(dump_mixer_path) or !fileOk(dump_a1_t4_path) or !fileOk(dump_a1_t2_path)) return error.DumpGen; -} - -fn readDump(path: []const u8) ![]u8 { - return std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, std.testing.allocator, .limited(32 << 20)); -} - -fn checkDumpFile(a1_path: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { - try ensureDumps(); - const a = std.testing.allocator; - const mixer_bytes = try readDump(dump_mixer_path); - defer a.free(mixer_bytes); - const a1_bytes = try readDump(a1_path); - defer a.free(a1_bytes); - try checkDump(mixer_bytes, a1_bytes, case_i, tag, gpu); -} - -fn checkDump(mixer_bytes: []const u8, a1_bytes: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { - const a = std.testing.allocator; - const dump = try Dump.load(a, mixer_bytes); - defer dump.deinit(a); - const a1 = try parseA1(a, a1_bytes); - defer a.free(a1.y64); - defer a.free(a1.ybf); - const c = dump.cases[case_i]; - try std.testing.expectEqual(a1.T, c.T); - try std.testing.expectEqual(a1.hidden, dump.hidden); - try std.testing.expectEqual(a1.layer, dump.layer); - try std.testing.expectEqual(a1.pos0, c.pos0); - try std.testing.expect(std.mem.eql(f64, a1.y64, c.y64)); - - const s = mla.Shape{ .heads = dump.heads, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const width = s.outWidth(); - const n_mix = c.T * width; - const mix64 = try a.alloc(f64, n_mix); - defer a.free(mix64); - try mla.mixF64(a, mix64, c.q, c.kv, dump.w, dump.kvb, c.g, s, c.T, c.pos0); - const d_pre = dist(mix64, c.y_pre); - std.debug.print("{s} mixF64-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_pre.rel_l2, d_pre.max_abs }); - const layer_mix = try a.alloc(f64, c.T * dump.hidden); - defer a.free(layer_mix); - oProj(layer_mix, mix64, dump.Wo, c.T, dump.hidden, width); - const d_layer = dist(layer_mix, a1.y64); - std.debug.print("{s} mixF64+o_proj-to-TFLINGA1 rel L2 {e} max abs {e}\n", .{ tag, d_layer.rel_l2, d_layer.max_abs }); - if (!gpu) return; - - const mix_bf = try a.alloc(f64, n_mix); - defer a.free(mix_bf); - const q_m = try dupeRound(a, c.q); - defer a.free(q_m); - const kv_m = try dupeRound(a, c.kv); - defer a.free(kv_m); - const w_m = try dupeRound(a, dump.w); - defer a.free(w_m); - const kvb_m = try dupeRound(a, dump.kvb); - defer a.free(kvb_m); - const g_m = try dupeRound(a, c.g); - defer a.free(g_m); - try mla.mixBf16(a, mix_bf, q_m, kv_m, w_m, kvb_m, g_m, s, c.T, c.pos0); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var gpu_dev = try Gpu.init(); - defer gpu_dev.deinit(); - var l = try Launch.open(gpu_dev, s, c.T, q_m, kv_m, w_m, kvb_m, g_m); - defer l.deinit(); - try l.dispatchMixer(gpu_dev, 0, c.T); - const metal_mix = try a.alloc(f64, n_mix); - defer a.free(metal_mix); - bitsToF64(l.y(), metal_mix); - const d_metal_pre = dist(metal_mix, c.y_pre); - std.debug.print("{s} Metal-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_metal_pre.rel_l2, d_metal_pre.max_abs }); - - const layer_bf = try a.alloc(f64, c.T * dump.hidden); - defer a.free(layer_bf); - const layer_metal = try a.alloc(f64, c.T * dump.hidden); - defer a.free(layer_metal); - oProj(layer_bf, mix_bf, dump.Wo, c.T, dump.hidden, width); - oProj(layer_metal, metal_mix, dump.Wo, c.T, dump.hidden, width); - var tbuf: [96]u8 = undefined; - const layer_tag = try std.fmt.bufPrint(&tbuf, "{s} TFLINGA1", .{tag}); - try gateNamedF64(layer_tag, layer_metal, a1.y64, layer_bf); -} - -fn checkRopeLargePos() !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const rows_n: u32 = 2; - const first_pos: u32 = 29998; - const slot_keys: u32 = 30000; - const H = s.heads; - var seed: u64 = 0x72333030; - const q = try fill(&seed, rows_n * H * mla.qd, a); - defer a.free(q); - roundSlice(q); - const rope_in = try fill(&seed, rows_n * mla.rope_dim, a); - defer a.free(rope_in); - roundSlice(rope_in); - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var gpu = try Gpu.init(); - defer gpu.deinit(); - const shared = mtl.ResourceOptions.shared; - const b_q = try gpu.device.buffer(q.len * 2, shared); - defer b_q.deinit(); - putBf16(b_q, q); - const b_rows = try gpu.device.buffer(rows_n * @sizeOf(MlaRow), shared); - defer b_rows.deinit(); - const rows = b_rows.slice(MlaRow, rows_n); - for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first_pos + @as(u32, @intCast(i)) }; - const b_cs = try gpu.device.buffer(rows_n * mla.nfreq * 2 * 4, shared); - defer b_cs.deinit(); - writeCs(b_cs.slice(f32, rows_n * mla.nfreq * 2), rows, s.theta); - const b_cache = try gpu.device.buffer(@as(usize, slot_keys) * mla.key * 2, shared); - defer b_cache.deinit(); - const cache = b_cache.slice(u16, slot_keys * mla.key); - for (0..rows_n) |t| { - const base = (first_pos + t) * mla.key + mla.lat; - for (0..mla.rope_dim) |i| cache[base + i] = toBf16(rope_in[t * mla.rope_dim + i]); - } - const aa = MlaArgs{ - .cache = b_cache.gpuAddress(), - .slot_keys = slot_keys, - .heads = H, - .head0 = 0, - .rows = rows_n, - .q_stride = H * mla.qd, - .kv_stride = mla.key, - .gate_stride = H * mla.vd, - .out_stride = H * mla.vd, - .eps = s.eps, - .scale = @floatCast(s.scale()), - }; - - { - const cb = gpu.queue.commandBuffer(); - const e = cb.compute(.serial); - e.setPipeline(gpu.rope_q); - e.setBuffer(b_q, 0, 0); - e.setValue(aa, 1); - e.setBuffer(b_cs, 0, 2); - e.dispatchGroups(mtl.Size.of(H, rows_n, 1), mtl.Size.of(32, 1, 1)); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("rope_q large pos failed: {s}\n", .{why}); - return error.GpuFailed; - } - } - const got_q = b_q.slice(u16, q.len); - const nq = rows_n * H * mla.rope_dim; - const metal_q = try a.alloc(f64, nq); - defer a.free(metal_q); - const f64_q = try a.alloc(f64, nq); - defer a.free(f64_q); - const bf_q = try a.alloc(f64, nq); - defer a.free(bf_q); - var k: usize = 0; - for (0..rows_n) |t| { - for (0..H) |h| { - var z64: [mla.rope_dim]f64 = undefined; - var out: [mla.rope_dim]f64 = undefined; - const base = (t * H + h) * mla.qd + mla.nope; - for (0..mla.rope_dim) |i| z64[i] = q[base + i]; - mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); - for (0..mla.rope_dim) |i| { - f64_q[k] = out[i]; - bf_q[k] = fromBf16(toBf16(@floatCast(out[i]))); - metal_q[k] = fromBf16(got_q[base + i]); - k += 1; - } - } - } - const q_gate = gateNamedF64("rope_q pos 29998-29999", metal_q, f64_q, bf_q); - - { - const cb = gpu.queue.commandBuffer(); - const e = cb.compute(.serial); - e.setPipeline(gpu.rope_cache); - e.setBuffer(b_rows, 0, 0); - e.setValue(aa, 1); - e.setBuffer(b_cs, 0, 2); - e.useResource(b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); - e.dispatchGroups(mtl.Size.of(rows_n, 1, 1), mtl.Size.of(32, 1, 1)); - e.end(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("rope_cache large pos failed: {s}\n", .{why}); - return error.GpuFailed; - } - } - const nc = rows_n * mla.rope_dim; - const metal_c = try a.alloc(f64, nc); - defer a.free(metal_c); - const f64_c = try a.alloc(f64, nc); - defer a.free(f64_c); - const bf_c = try a.alloc(f64, nc); - defer a.free(bf_c); - k = 0; - for (0..rows_n) |t| { - var z64: [mla.rope_dim]f64 = undefined; - var out: [mla.rope_dim]f64 = undefined; - for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; - mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); - const base = (first_pos + t) * mla.key + mla.lat; - for (0..mla.rope_dim) |i| { - f64_c[k] = out[i]; - bf_c[k] = fromBf16(toBf16(@floatCast(out[i]))); - metal_c[k] = fromBf16(cache[base + i]); - k += 1; - } - } - const c_gate = gateNamedF64("rope_cache pos 29998-29999", metal_c, f64_c, bf_c); - q_gate catch |e| return e; - c_gate catch |e| return e; -} - -fn checkLarge(rows: u32, left: u32, seed: u64, tag: []const u8) !void { - const a = std.testing.allocator; - const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; - const in = try Inputs.make(a, s, rows, seed); - defer in.free(a); - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - var g = try Gpu.init(); - defer g.deinit(); - var whole = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer whole.deinit(); - try whole.dispatchMixer(g, 0, rows); - var parts = try Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); - defer parts.deinit(); - try parts.dispatchMixer(g, 0, left); - try parts.dispatchMixer(g, left, rows - left); - var buf: [96]u8 = undefined; - const t1 = try std.fmt.bufPrint(&buf, "{s} whole vs chunks", .{tag}); - try expectBitsEqual(t1, whole.y(), parts.y()); - var buf2: [96]u8 = undefined; - const t2 = try std.fmt.bufPrint(&buf2, "{s} resume vs fresh", .{tag}); - try expectBitsEqual(t2, whole.y(), parts.y()); -} - -test "TFLINGA1 tiny layer 3 T=4 pos0=0 Metal and mixF64 vs python f64" { - try checkDumpFile(dump_a1_t4_path, 0, "dump T=4 pos0=0", true); -} - -test "TFLINGA1 tiny layer 3 T=2 pos0=30000 mixF64 vs python host-only" { - try checkDumpFile(dump_a1_t2_path, 1, "dump T=2 pos0=30000", false); -} - -test "Ling rope_q and rope_cache at pos 29998-29999 vs f64" { - try checkRopeLargePos(); -} - -test "MLA mixer T=100 as 37+63 bits-equal" { - try checkLarge(100, 37, 0x74313030, "T=100"); -} - -test "MLA mixer T=257 as 256+1 bits-equal (k3 gpu_rows)" { - try checkLarge(257, k3_gpu_rows, 0x74323537, "T=257"); +test { + _ = @import("ling_mla_gpu_kernels.zig"); + _ = @import("ling_mla_gpu_mixer.zig"); + _ = @import("ling_mla_gpu_chunks.zig"); } diff --git a/zig/tests/ling_mla_gpu_chunks.zig b/zig/tests/ling_mla_gpu_chunks.zig new file mode 100644 index 00000000000..412eaf117d3 --- /dev/null +++ b/zig/tests/ling_mla_gpu_chunks.zig @@ -0,0 +1,238 @@ +//! Ling MLA whole vs chunks, resume vs fresh, large-T and dump gates. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); +const dump = @import("ling_mla_gpu_dump.zig"); + +const k3_gpu_rows: u32 = 256; + +fn checkChunks() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var whole = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var chunks = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer chunks.deinit(); + try chunks.dispatchMixer(g, 0, 2); + try chunks.dispatchMixer(g, 2, 2); + try c.expectBitsEqual("whole vs chunks", whole.y(), chunks.y()); +} + +fn checkResume() !void { + const a = std.testing.allocator; + const rows: u32 = 4; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x72657375); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var fresh = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer fresh.deinit(); + try fresh.dispatchMixer(g, 0, rows); + var continued = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer continued.deinit(); + try continued.dispatchMixer(g, 0, 2); + try continued.dispatchMixer(g, 2, 2); + const W = s.outWidth(); + try c.expectBitsEqual("resume vs fresh (all rows)", fresh.y(), continued.y()); + try c.expectBitsEqual("resume vs fresh (last 2)", fresh.y()[2 * W ..], continued.y()[2 * W ..]); +} + +fn checkRopeLargePos() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows_n: u32 = 2; + const first_pos: u32 = 29998; + const slot_keys: u32 = 30000; + const H = s.heads; + var seed: u64 = 0x72333030; + const q = try c.fill(&seed, rows_n * H * mla.qd, a); + defer a.free(q); + c.roundSlice(q); + const rope_in = try c.fill(&seed, rows_n * mla.rope_dim, a); + defer a.free(rope_in); + c.roundSlice(rope_in); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + const shared = mtl.ResourceOptions.shared; + const b_q = try gpu.device.buffer(q.len * 2, shared); + defer b_q.deinit(); + c.putBf16(b_q, q); + const b_rows = try gpu.device.buffer(rows_n * @sizeOf(c.MlaRow), shared); + defer b_rows.deinit(); + const rows = b_rows.slice(c.MlaRow, rows_n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first_pos + @as(u32, @intCast(i)) }; + const b_cs = try gpu.device.buffer(rows_n * mla.nfreq * 2 * 4, shared); + defer b_cs.deinit(); + c.writeCs(b_cs.slice(f32, rows_n * mla.nfreq * 2), rows, s.theta); + const b_cache = try gpu.device.buffer(@as(usize, slot_keys) * mla.key * 2, shared); + defer b_cache.deinit(); + const cache = b_cache.slice(u16, slot_keys * mla.key); + for (0..rows_n) |t| { + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| cache[base + i] = c.toBf16(rope_in[t * mla.rope_dim + i]); + } + const aa = c.MlaArgs{ + .cache = b_cache.gpuAddress(), + .slot_keys = slot_keys, + .heads = H, + .head0 = 0, + .rows = rows_n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = H * mla.vd, + .out_stride = H * mla.vd, + .eps = s.eps, + .scale = @floatCast(s.scale()), + }; + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows_n, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const got_q = b_q.slice(u16, q.len); + const nq = rows_n * H * mla.rope_dim; + const metal_q = try a.alloc(f64, nq); + defer a.free(metal_q); + const f64_q = try a.alloc(f64, nq); + defer a.free(f64_q); + const bf_q = try a.alloc(f64, nq); + defer a.free(bf_q); + var k: usize = 0; + for (0..rows_n) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + for (0..mla.rope_dim) |i| { + f64_q[k] = out[i]; + bf_q[k] = c.fromBf16(c.toBf16(@floatCast(out[i]))); + metal_q[k] = c.fromBf16(got_q[base + i]); + k += 1; + } + } + } + const q_gate = c.gateNamedF64("rope_q pos 29998-29999", metal_q, f64_q, bf_q); + + { + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(b_cs, 0, 2); + e.useResource(b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows_n, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache large pos failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + const nc = rows_n * mla.rope_dim; + const metal_c = try a.alloc(f64, nc); + defer a.free(metal_c); + const f64_c = try a.alloc(f64, nc); + defer a.free(f64_c); + const bf_c = try a.alloc(f64, nc); + defer a.free(bf_c); + k = 0; + for (0..rows_n) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, first_pos + @as(u32, @intCast(t)), s.theta); + const base = (first_pos + t) * mla.key + mla.lat; + for (0..mla.rope_dim) |i| { + f64_c[k] = out[i]; + bf_c[k] = c.fromBf16(c.toBf16(@floatCast(out[i]))); + metal_c[k] = c.fromBf16(cache[base + i]); + k += 1; + } + } + const cache_gate = c.gateNamedF64("rope_cache pos 29998-29999", metal_c, f64_c, bf_c); + q_gate catch |e| return e; + cache_gate catch |e| return e; +} + +fn checkLarge(rows: u32, left: u32, seed: u64, tag: []const u8) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, seed); + defer in.free(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var whole = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer whole.deinit(); + try whole.dispatchMixer(g, 0, rows); + var parts = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer parts.deinit(); + try parts.dispatchMixer(g, 0, left); + try parts.dispatchMixer(g, left, rows - left); + var buf: [96]u8 = undefined; + const t1 = try std.fmt.bufPrint(&buf, "{s} whole vs chunks", .{tag}); + try c.expectBitsEqual(t1, whole.y(), parts.y()); + var buf2: [96]u8 = undefined; + const t2 = try std.fmt.bufPrint(&buf2, "{s} resume vs fresh", .{tag}); + try c.expectBitsEqual(t2, whole.y(), parts.y()); +} + +test "MLA mixer 4 rows equals 2+2 bits-equal" { + try checkChunks(); +} + +test "MLA mixer resume vs fresh bits-equal" { + try checkResume(); +} + +test "TFLINGA1 tiny layer 3 T=4 pos0=0 Metal and mixF64 vs python f64" { + try dump.checkDumpFile(dump.dump_a1_t4_path, 0, "dump T=4 pos0=0", true); +} + +test "TFLINGA1 tiny layer 3 T=2 pos0=30000 mixF64 vs python host-only" { + try dump.checkDumpFile(dump.dump_a1_t2_path, 1, "dump T=2 pos0=30000", false); +} + +test "Ling rope_q and rope_cache at pos 29998-29999 vs f64" { + try checkRopeLargePos(); +} + +test "MLA mixer T=100 as 37+63 bits-equal" { + try checkLarge(100, 37, 0x74313030, "T=100"); +} + +test "MLA mixer T=257 as 256+1 bits-equal (k3 gpu_rows)" { + try checkLarge(257, k3_gpu_rows, 0x74323537, "T=257"); +} diff --git a/zig/tests/ling_mla_gpu_common.zig b/zig/tests/ling_mla_gpu_common.zig new file mode 100644 index 00000000000..39b8b2316f0 --- /dev/null +++ b/zig/tests/ling_mla_gpu_common.zig @@ -0,0 +1,427 @@ +//! Shared Gpu/Launch/helpers for Ling MLA GPU tests around k3_mla. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const metallib = @import("kimi_metallib"); + +const source = @import("ling_metal").mla; +const mla_splits: u32 = 16; + +pub const MlaRow = extern struct { slot: u32, pos: u32 }; +pub const MlaArgs = extern struct { + cache: u64, + slot_keys: u32, + heads: u32, + head0: u32, + rows: u32, + q_stride: u32, + kv_stride: u32, + gate_stride: u32, + out_stride: u32, + eps: f32, + scale: f32, +}; + +comptime { + if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); +} + +pub fn toBf16(v: f32) u16 { + const bits: u32 = @bitCast(v); + if (std.math.isNan(v)) return @truncate((bits >> 16) | 0x40); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); +} +pub fn fromBf16(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +pub fn fill(seed: *u64, n: usize, a: std.mem.Allocator) ![]f32 { + const x = try a.alloc(f32, n); + for (x) |*v| { + seed.* = seed.* *% 1103515245 +% 12345; + v.* = @as(f32, @floatFromInt((seed.* >> 16) & 0x7fff)) / 16384.0 - 1.0; + } + return x; +} + +pub fn putBf16(buf: mtl.Buffer, x: []const f32) void { + const d = buf.slice(u16, x.len); + for (x, d) |v, *o| o.* = toBf16(v); +} + +pub fn roundSlice(x: []f32) void { + for (x) |*v| v.* = fromBf16(toBf16(v.*)); +} + +/// Host f64 cos/sin of each row's pos, rounded to f32. Layout [t][i][comp] = t*64 + i*2 + comp. +pub fn writeCs(cs: []f32, rows: []const MlaRow, theta: f64) void { + std.debug.assert(cs.len >= rows.len * mla.nfreq * 2); + for (rows, 0..) |r, t| { + for (0..mla.nfreq) |i| { + const ang = @as(f64, @floatFromInt(r.pos)) * mla.invFreq(theta, i); + const at = (t * mla.nfreq + i) * 2; + cs[at] = @floatCast(@cos(ang)); + cs[at + 1] = @floatCast(@sin(ang)); + } + } +} + +pub const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + kimi: mtl.Library, + ling: mtl.Library, + cache: mtl.Pipeline, + qlat: mtl.Pipeline, + attend: mtl.Pipeline, + merge: mtl.Pipeline, + uv: mtl.Pipeline, + rope_cache: mtl.Pipeline, + rope_q: mtl.Pipeline, + gate_expand: mtl.Pipeline, + + pub fn init() !Gpu { + const device = try mtl.Device.init(); + errdefer device.deinit(); + const kimi = try mtl.Library.fromBytes(device, metallib.bytes); + errdefer kimi.deinit(); + const ling = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); + errdefer ling.deinit(); + const cache = try mtl.Pipeline.init(device, kimi, "k3_mla_cache", false); + errdefer cache.deinit(); + const qlat = try mtl.Pipeline.init(device, kimi, "k3_mla_qlat", false); + errdefer qlat.deinit(); + const attend = try mtl.Pipeline.init(device, kimi, "k3_mla_attend", false); + errdefer attend.deinit(); + const merge = try mtl.Pipeline.init(device, kimi, "k3_mla_merge", false); + errdefer merge.deinit(); + const uv = try mtl.Pipeline.init(device, kimi, "k3_mla_uv", false); + errdefer uv.deinit(); + const rope_cache = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_cache", false); + errdefer rope_cache.deinit(); + const rope_q = try mtl.Pipeline.init(device, ling, "tf_ling_mla_rope_q", false); + errdefer rope_q.deinit(); + const gate_expand = try mtl.Pipeline.init(device, ling, "tf_ling_mla_gate_expand", false); + errdefer gate_expand.deinit(); + const queue = try device.queue(); + return .{ + .device = device, + .queue = queue, + .kimi = kimi, + .ling = ling, + .cache = cache, + .qlat = qlat, + .attend = attend, + .merge = merge, + .uv = uv, + .rope_cache = rope_cache, + .rope_q = rope_q, + .gate_expand = gate_expand, + }; + } + + pub fn deinit(g: *Gpu) void { + g.gate_expand.deinit(); + g.rope_q.deinit(); + g.rope_cache.deinit(); + g.uv.deinit(); + g.merge.deinit(); + g.attend.deinit(); + g.qlat.deinit(); + g.cache.deinit(); + g.ling.deinit(); + g.kimi.deinit(); + g.queue.deinit(); + g.device.deinit(); + } +}; + +pub const Launch = struct { + s: mla.Shape, + cap: u32, + b_q: mtl.Buffer, + b_kv: mtl.Buffer, + b_w: mtl.Buffer, + b_kvb: mtl.Buffer, + b_g: mtl.Buffer, + b_g2: mtl.Buffer, + b_y: mtl.Buffer, + b_rows: mtl.Buffer, + b_cache: mtl.Buffer, + b_qlat: mtl.Buffer, + b_partial: mtl.Buffer, + b_olat: mtl.Buffer, + b_cs: mtl.Buffer, + + pub fn open(g: Gpu, s: mla.Shape, cap: u32, q: []const f32, kv: []const f32, w_rms: []const f32, kvb: []const f32, gate: []const f32) !Launch { + const H = s.heads; + const shared = mtl.ResourceOptions.shared; + const b_q = try g.device.buffer(q.len * 2, shared); + const b_kv = try g.device.buffer(kv.len * 2, shared); + const b_w = try g.device.buffer(w_rms.len * 2, shared); + const b_kvb = try g.device.buffer(kvb.len * 2, shared); + const b_g = try g.device.buffer(gate.len * 2, shared); + const b_g2 = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_y = try g.device.buffer(cap * H * mla.vd * 2, shared); + const b_rows = try g.device.buffer(cap * @sizeOf(MlaRow), shared); + const b_cache = try g.device.buffer(cap * mla.key * 2, shared); + const b_qlat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_partial = try g.device.buffer(cap * H * mla_splits * (mla.lat + 2) * 4, shared); + const b_olat = try g.device.buffer(cap * H * mla.lat * 4, shared); + const b_cs = try g.device.buffer(cap * mla.nfreq * 2 * 4, shared); + putBf16(b_q, q); + putBf16(b_kv, kv); + putBf16(b_w, w_rms); + putBf16(b_kvb, kvb); + putBf16(b_g, gate); + @memset(b_g2.slice(u16, cap * H * mla.vd), 0); + @memset(b_y.slice(u16, cap * H * mla.vd), 0); + @memset(b_cache.slice(u16, cap * mla.key), 0); + return .{ + .s = s, + .cap = cap, + .b_q = b_q, + .b_kv = b_kv, + .b_w = b_w, + .b_kvb = b_kvb, + .b_g = b_g, + .b_g2 = b_g2, + .b_y = b_y, + .b_rows = b_rows, + .b_cache = b_cache, + .b_qlat = b_qlat, + .b_partial = b_partial, + .b_olat = b_olat, + .b_cs = b_cs, + }; + } + + pub fn deinit(l: *Launch) void { + l.b_q.deinit(); + l.b_kv.deinit(); + l.b_w.deinit(); + l.b_kvb.deinit(); + l.b_g.deinit(); + l.b_g2.deinit(); + l.b_y.deinit(); + l.b_rows.deinit(); + l.b_cache.deinit(); + l.b_qlat.deinit(); + l.b_partial.deinit(); + l.b_olat.deinit(); + l.b_cs.deinit(); + } + + pub fn args(l: *Launch, n: u32) MlaArgs { + const H = l.s.heads; + const ow = H * mla.vd; + return .{ + .cache = l.b_cache.gpuAddress(), + .slot_keys = l.cap, + .heads = H, + .head0 = 0, + .rows = n, + .q_stride = H * mla.qd, + .kv_stride = mla.key, + .gate_stride = ow, + .out_stride = ow, + .eps = l.s.eps, + .scale = @floatCast(l.s.scale()), + }; + } + + pub fn fillRows(l: *Launch, first: u32, n: u32) void { + const rows = l.b_rows.slice(MlaRow, n); + for (rows, 0..) |*r, i| r.* = .{ .slot = 0, .pos = first + @as(u32, @intCast(i)) }; + } + + pub fn fillCs(l: *Launch, n: u32) void { + writeCs(l.b_cs.slice(f32, n * mla.nfreq * 2), l.b_rows.slice(MlaRow, n), l.s.theta); + } + + pub fn dispatchMixer(l: *Launch, g: Gpu, first: u32, n: u32) !void { + const H = l.s.heads; + const a = l.args(n); + l.fillRows(first, n); + l.fillCs(n); + const q_off = first * a.q_stride * 2; + const kv_off = first * a.kv_stride * 2; + const g_off = first * H * 2; + const y_off = first * a.out_stride * 2; + const g2_off = first * a.gate_stride * 2; + const rw = mtl.ResourceUsage.read | mtl.ResourceUsage.write; + const cb = g.queue.commandBuffer(); + const e = cb.compute(.serial); + + e.setPipeline(g.cache); + e.setBuffer(l.b_kv, kv_off, 0); + e.setBuffer(l.b_w, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setValue(a, 3); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, rw); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.qlat); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_qlat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(2, H, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.rope_q); + e.setBuffer(l.b_q, q_off, 0); + e.setValue(a, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(32, 1, 1)); + + e.setPipeline(g.attend); + e.setBuffer(l.b_q, q_off, 0); + e.setBuffer(l.b_qlat, 0, 1); + e.setBuffer(l.b_rows, 0, 2); + e.setBuffer(l.b_partial, 0, 3); + e.setValue(a, 4); + e.useResource(l.b_cache, mtl.ResourceUsage.read); + const fit: u32 = @intCast(@min(32, g.attend.maxThreads() / 32)); + const groups = (H + fit - 1) / fit; + const per = (H + groups - 1) / groups; + e.dispatchGroups(mtl.Size.of(groups, mla_splits, n), mtl.Size.of(32 * per, 1, 1)); + + e.setPipeline(g.merge); + e.setBuffer(l.b_partial, 0, 0); + e.setBuffer(l.b_rows, 0, 1); + e.setBuffer(l.b_olat, 0, 2); + e.setValue(a, 3); + e.dispatchGroups(mtl.Size.of(H, n, 1), mtl.Size.of(256, 1, 1)); + + e.setPipeline(g.gate_expand); + e.setBuffer(l.b_g, g_off, 0); + e.setBuffer(l.b_g2, g2_off, 1); + e.setValue(a, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, n, 1), mtl.Size.of(128, 1, 1)); + + e.setPipeline(g.uv); + e.setBuffer(l.b_olat, 0, 0); + e.setBuffer(l.b_kvb, 0, 1); + e.setBuffer(l.b_g2, g2_off, 2); + e.setBuffer(l.b_y, y_off, 3); + e.setValue(a, 4); + e.dispatchGroups(mtl.Size.of(mla.vd / 4, H, 1), mtl.Size.of(128, 1, 1)); + + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("GPU mixer failed: {s}\n", .{why}); + return error.GpuFailed; + } + } + + pub fn y(l: *Launch) []u16 { + return l.b_y.slice(u16, l.cap * l.s.outWidth()); + } +}; + +pub const Dist = struct { rel_l2: f64, max_abs: f64 }; + +pub fn dist(got: []const f64, ref: []const f64) Dist { + var num: f64 = 0; + var den: f64 = 0; + var max_abs: f64 = 0; + for (got, ref) |a, b| { + const d = a - b; + num += d * d; + den += b * b; + max_abs = @max(max_abs, @abs(d)); + } + const rel = if (den == 0) @sqrt(num) else @sqrt(num) / @sqrt(den); + return .{ .rel_l2 = rel, .max_abs = max_abs }; +} + +pub fn bitsToF64(bits: []const u16, out: []f64) void { + for (bits, out) |h, *o| o.* = fromBf16(h); +} + +pub fn gateNamed(tag: []const u8, metal: []const u16, f64_y: []const f64, bf16_y: []const f64) !void { + const a = std.testing.allocator; + const metal_f = try a.alloc(f64, metal.len); + defer a.free(metal_f); + bitsToF64(metal, metal_f); + try gateNamedF64(tag, metal_f, f64_y, bf16_y); +} + +pub fn gateNamedF64(tag: []const u8, metal: []const f64, f64_y: []const f64, bf16_y: []const f64) !void { + const m = dist(metal, f64_y); + const b = dist(bf16_y, f64_y); + std.debug.print("{s} Metal-to-f64 rel L2 {e} max abs {e}; bf16-ref-to-f64 rel L2 {e} max abs {e}\n", .{ tag, m.rel_l2, m.max_abs, b.rel_l2, b.max_abs }); + if (m.rel_l2 > b.rel_l2 or m.max_abs > b.max_abs) { + std.debug.print("{s} gate miss: Metal further from f64 than bf16-ref\n", .{tag}); + return error.Gate; + } +} + +pub fn oProj(out: []f64, y: []const f64, wo: []const f32, rows: u32, hidden: u32, width: u32) void { + std.debug.assert(out.len == rows * hidden and y.len == rows * width and wo.len == hidden * width); + for (0..rows) |t| { + for (0..hidden) |j| { + var acc: f64 = 0; + const wr = j * width; + const yr = t * width; + for (0..width) |i| acc += y[yr + i] * @as(f64, wo[wr + i]); + out[t * hidden + j] = acc; + } + } +} + +pub fn expectBitsEqual(tag: []const u8, a: []const u16, b: []const u16) !void { + if (std.mem.eql(u16, a, b)) return; + var n: usize = 0; + var first: usize = 0; + for (a, b, 0..) |x, yv, i| { + if (x != yv) { + if (n == 0) first = i; + n += 1; + } + } + std.debug.print("{s} bits-equal miss: {d} of {d} first i={d} a={x} b={x}\n", .{ tag, n, a.len, first, a[first], b[first] }); + return error.BitsEqual; +} + +pub const Inputs = struct { + q: []f32, + kv: []f32, + w: []f32, + kvb: []f32, + g: []f32, + + pub fn make(alloc: std.mem.Allocator, s: mla.Shape, rows: u32, seed0: u64) !Inputs { + var seed = seed0; + const H = s.heads; + const q = try fill(&seed, rows * H * mla.qd, alloc); + const kv = try fill(&seed, rows * mla.key, alloc); + const w = try fill(&seed, mla.lat, alloc); + const kvb = try fill(&seed, H * (mla.nope + mla.vd) * mla.lat, alloc); + const g = try fill(&seed, rows * H, alloc); + for (w) |*v| v.* = 0.5 + 0.5 * v.*; + roundSlice(q); + roundSlice(kv); + roundSlice(w); + roundSlice(kvb); + roundSlice(g); + return .{ .q = q, .kv = kv, .w = w, .kvb = kvb, .g = g }; + } + + pub fn free(in: Inputs, alloc: std.mem.Allocator) void { + alloc.free(in.q); + alloc.free(in.kv); + alloc.free(in.w); + alloc.free(in.kvb); + alloc.free(in.g); + } +}; diff --git a/zig/tests/ling_mla_gpu_dump.zig b/zig/tests/ling_mla_gpu_dump.zig new file mode 100644 index 00000000000..9a94d0efd6f --- /dev/null +++ b/zig/tests/ling_mla_gpu_dump.zig @@ -0,0 +1,251 @@ +//! TFLINGM1/TFLINGA1 dump parsing and Metal-vs-python mixer check. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +const dump_dir = "/tmp/ling-mla-dumps"; +pub const dump_mixer_path = dump_dir ++ "/mla_tiny_mixer.bin"; +pub const dump_a1_t4_path = dump_dir ++ "/mla_tiny_t4_pos0.bin"; +pub const dump_a1_t2_path = dump_dir ++ "/mla_tiny_t2_pos30000.bin"; +const dump_py = "zig/src/families/ling/oracle/mla_dump.py"; + +fn takeU32(b: []const u8, off: *usize) u32 { + const v = std.mem.readInt(u32, b[off.*..][0..4], .little); + off.* += 4; + return v; +} + +fn takeF32s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f32 { + const x = try alloc.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 4]); + off.* += n * 4; + return x; +} + +fn takeF64s(alloc: std.mem.Allocator, b: []const u8, off: *usize, n: usize) ![]f64 { + const x = try alloc.alloc(f64, n); + @memcpy(std.mem.sliceAsBytes(x), b[off.* .. off.* + n * 8]); + off.* += n * 8; + return x; +} + +const DumpCase = struct { + T: u32, + pos0: u32, + q: []f32, + kv: []f32, + g: []f32, + y_pre: []f64, + y64: []f64, + ybf: []f64, +}; + +const Dump = struct { + hidden: u32, + layer: u32, + heads: u32, + w: []f32, + kvb: []f32, + Wo: []f32, + cases: []DumpCase, + + fn load(alloc: std.mem.Allocator, bytes: []const u8) !Dump { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGM1")); + var off: usize = 8; + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const heads = takeU32(bytes, &off); + const n_cases = takeU32(bytes, &off); + const w = try takeF32s(alloc, bytes, &off, mla.lat); + errdefer alloc.free(w); + const kvb = try takeF32s(alloc, bytes, &off, heads * (mla.nope + mla.vd) * mla.lat); + errdefer alloc.free(kvb); + const Wo = try takeF32s(alloc, bytes, &off, hidden * heads * mla.vd); + errdefer alloc.free(Wo); + const cases = try alloc.alloc(DumpCase, n_cases); + errdefer alloc.free(cases); + for (cases) |*case| { + const T = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const q = try takeF32s(alloc, bytes, &off, T * heads * mla.qd); + const kv = try takeF32s(alloc, bytes, &off, T * mla.key); + const g = try takeF32s(alloc, bytes, &off, T * heads); + const y_pre = try takeF64s(alloc, bytes, &off, T * heads * mla.vd); + const y64 = try takeF64s(alloc, bytes, &off, T * hidden); + const ybf = try takeF64s(alloc, bytes, &off, T * hidden); + case.* = .{ .T = T, .pos0 = pos0, .q = q, .kv = kv, .g = g, .y_pre = y_pre, .y64 = y64, .ybf = ybf }; + } + try std.testing.expectEqual(bytes.len, off); + return .{ .hidden = hidden, .layer = layer, .heads = heads, .w = w, .kvb = kvb, .Wo = Wo, .cases = cases }; + } + + fn deinit(d: Dump, alloc: std.mem.Allocator) void { + for (d.cases) |case| { + alloc.free(case.q); + alloc.free(case.kv); + alloc.free(case.g); + alloc.free(case.y_pre); + alloc.free(case.y64); + alloc.free(case.ybf); + } + alloc.free(d.cases); + alloc.free(d.w); + alloc.free(d.kvb); + alloc.free(d.Wo); + } +}; + +fn parseA1(alloc: std.mem.Allocator, bytes: []const u8) !struct { T: u32, hidden: u32, layer: u32, pos0: u32, y64: []f64, ybf: []f64 } { + try std.testing.expect(std.mem.eql(u8, bytes[0..8], "TFLINGA1")); + var off: usize = 8; + const T = takeU32(bytes, &off); + const hidden = takeU32(bytes, &off); + const layer = takeU32(bytes, &off); + const pos0 = takeU32(bytes, &off); + const n = T * hidden; + const y64 = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(y64); + const ybf = try takeF64s(alloc, bytes, &off, n); + errdefer alloc.free(ybf); + try std.testing.expectEqual(bytes.len, off); + return .{ .T = T, .hidden = hidden, .layer = layer, .pos0 = pos0, .y64 = y64, .ybf = ybf }; +} + +fn dupeRound(alloc: std.mem.Allocator, src: []const f32) ![]f32 { + const d = try alloc.dupe(f32, src); + c.roundSlice(d); + return d; +} + +fn fileOk(path: []const u8) bool { + std.Io.Dir.cwd().access(std.testing.io, path, .{}) catch return false; + return true; +} + +fn hasTorch(py: []const u8) bool { + const a = std.testing.allocator; + const r = std.process.run(a, std.testing.io, .{ + .argv = &.{ py, "-c", "import torch" }, + .stdout_limit = .limited(256), + .stderr_limit = .limited(4096), + }) catch return false; + defer a.free(r.stdout); + defer a.free(r.stderr); + return r.term.success(); +} + +fn findPython() ?[]const u8 { + if (std.c.getenv("TF_LING_PYTHON")) |p| { + const s = std.mem.span(p); + if (hasTorch(s)) return s; + } + if (hasTorch("python3")) return "python3"; + return null; +} + +fn ensureDumps() !void { + if (fileOk(dump_mixer_path) and fileOk(dump_a1_t4_path) and fileOk(dump_a1_t2_path)) return; + if (!fileOk(dump_py)) { + std.debug.print("skip: {s} not in cwd; TFLINGA1 dumps need ling_forward.py at test time\n", .{dump_py}); + return error.SkipZigTest; + } + const py = findPython() orelse { + std.debug.print("skip: no torch (set TF_LING_PYTHON or python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); + return error.SkipZigTest; + }; + const a = std.testing.allocator; + const r = try std.process.run(a, std.testing.io, .{ + .argv = &.{ py, dump_py, dump_dir }, + .stdout_limit = .limited(4096), + .stderr_limit = .limited(65536), + }); + defer a.free(r.stdout); + defer a.free(r.stderr); + if (!r.term.success()) { + std.debug.print("mla_dump.py failed: {s}{s}\n", .{ r.stdout, r.stderr }); + return error.DumpGen; + } + if (!fileOk(dump_mixer_path) or !fileOk(dump_a1_t4_path) or !fileOk(dump_a1_t2_path)) return error.DumpGen; +} + +fn readDump(path: []const u8) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(std.testing.io, path, std.testing.allocator, .limited(32 << 20)); +} + +pub fn checkDumpFile(a1_path: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + try ensureDumps(); + const a = std.testing.allocator; + const mixer_bytes = try readDump(dump_mixer_path); + defer a.free(mixer_bytes); + const a1_bytes = try readDump(a1_path); + defer a.free(a1_bytes); + try checkDump(mixer_bytes, a1_bytes, case_i, tag, gpu); +} + +fn checkDump(mixer_bytes: []const u8, a1_bytes: []const u8, case_i: usize, tag: []const u8, gpu: bool) !void { + const a = std.testing.allocator; + const dump = try Dump.load(a, mixer_bytes); + defer dump.deinit(a); + const a1 = try parseA1(a, a1_bytes); + defer a.free(a1.y64); + defer a.free(a1.ybf); + const case = dump.cases[case_i]; + try std.testing.expectEqual(a1.T, case.T); + try std.testing.expectEqual(a1.hidden, dump.hidden); + try std.testing.expectEqual(a1.layer, dump.layer); + try std.testing.expectEqual(a1.pos0, case.pos0); + try std.testing.expect(std.mem.eql(f64, a1.y64, case.y64)); + + const s = mla.Shape{ .heads = dump.heads, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const width = s.outWidth(); + const n_mix = case.T * width; + const mix64 = try a.alloc(f64, n_mix); + defer a.free(mix64); + try mla.mixF64(a, mix64, case.q, case.kv, dump.w, dump.kvb, case.g, s, case.T, case.pos0); + const d_pre = c.dist(mix64, case.y_pre); + std.debug.print("{s} mixF64-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_pre.rel_l2, d_pre.max_abs }); + const layer_mix = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_mix); + c.oProj(layer_mix, mix64, dump.Wo, case.T, dump.hidden, width); + const d_layer = c.dist(layer_mix, a1.y64); + std.debug.print("{s} mixF64+o_proj-to-TFLINGA1 rel L2 {e} max abs {e}\n", .{ tag, d_layer.rel_l2, d_layer.max_abs }); + if (!gpu) return; + + const mix_bf = try a.alloc(f64, n_mix); + defer a.free(mix_bf); + const q_m = try dupeRound(a, case.q); + defer a.free(q_m); + const kv_m = try dupeRound(a, case.kv); + defer a.free(kv_m); + const w_m = try dupeRound(a, dump.w); + defer a.free(w_m); + const kvb_m = try dupeRound(a, dump.kvb); + defer a.free(kvb_m); + const g_m = try dupeRound(a, case.g); + defer a.free(g_m); + try mla.mixBf16(a, mix_bf, q_m, kv_m, w_m, kvb_m, g_m, s, case.T, case.pos0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu_dev = try c.Gpu.init(); + defer gpu_dev.deinit(); + var l = try c.Launch.open(gpu_dev, s, case.T, q_m, kv_m, w_m, kvb_m, g_m); + defer l.deinit(); + try l.dispatchMixer(gpu_dev, 0, case.T); + const metal_mix = try a.alloc(f64, n_mix); + defer a.free(metal_mix); + c.bitsToF64(l.y(), metal_mix); + const d_metal_pre = c.dist(metal_mix, case.y_pre); + std.debug.print("{s} Metal-to-python mixer rel L2 {e} max abs {e}\n", .{ tag, d_metal_pre.rel_l2, d_metal_pre.max_abs }); + + const layer_bf = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_bf); + const layer_metal = try a.alloc(f64, case.T * dump.hidden); + defer a.free(layer_metal); + c.oProj(layer_bf, mix_bf, dump.Wo, case.T, dump.hidden, width); + c.oProj(layer_metal, metal_mix, dump.Wo, case.T, dump.hidden, width); + var tbuf: [96]u8 = undefined; + const layer_tag = try std.fmt.bufPrint(&tbuf, "{s} TFLINGA1", .{tag}); + try c.gateNamedF64(layer_tag, layer_metal, a1.y64, layer_bf); +} diff --git a/zig/tests/ling_mla_gpu_kernels.zig b/zig/tests/ling_mla_gpu_kernels.zig new file mode 100644 index 00000000000..c5be824d160 --- /dev/null +++ b/zig/tests/ling_mla_gpu_kernels.zig @@ -0,0 +1,200 @@ +//! Ling MLA kernels-alone: rope_q, rope_cache, gate_expand vs host. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +fn checkRopeQ() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x7271; + const q = try c.fill(&seed, rows * H * mla.qd, a); + defer a.free(q); + c.roundSlice(q); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_q); + e.setBuffer(l.b_q, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.dispatchGroups(mtl.Size.of(H, rows, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_q failed: {s}\n", .{why}); + return error.GpuFailed; + } + const got = l.b_q.slice(u16, q.len); + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + for (0..H) |h| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + const base = (t * H + h) * mla.qd + mla.nope; + for (0..mla.rope_dim) |i| z64[i] = q[base + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = c.toBf16(@floatCast(out[i])); + const gbits = got[base + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(c.fromBf16(want) - c.fromBf16(gbits))); + } + } + } + std.debug.print("rope_q vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeQ; +} + +fn checkRopeCache() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + var seed: u64 = 0x7263; + const rope_in = try c.fill(&seed, rows * mla.rope_dim, a); + defer a.free(rope_in); + c.roundSlice(rope_in); + const H = s.heads; + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + const g = try a.alloc(f32, rows * H); + defer a.free(g); + @memset(g, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, g); + defer l.deinit(); + const cache = l.b_cache.slice(u16, rows * mla.key); + @memset(cache, 0); + for (0..rows) |t| { + for (0..mla.rope_dim) |i| cache[t * mla.key + mla.lat + i] = c.toBf16(rope_in[t * mla.rope_dim + i]); + } + l.fillRows(0, rows); + l.fillCs(rows); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.rope_cache); + e.setBuffer(l.b_rows, 0, 0); + e.setValue(aa, 1); + e.setBuffer(l.b_cs, 0, 2); + e.useResource(l.b_cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("rope_cache failed: {s}\n", .{why}); + return error.GpuFailed; + } + var worst: f32 = 0; + var bits_miss: usize = 0; + for (0..rows) |t| { + var z64: [mla.rope_dim]f64 = undefined; + var out: [mla.rope_dim]f64 = undefined; + for (0..mla.rope_dim) |i| z64[i] = rope_in[t * mla.rope_dim + i]; + mla.rotate(&out, &z64, @intCast(t), s.theta); + for (0..mla.rope_dim) |i| { + const want = c.toBf16(@floatCast(out[i])); + const gbits = cache[t * mla.key + mla.lat + i]; + if (want != gbits) bits_miss += 1; + worst = @max(worst, @abs(c.fromBf16(want) - c.fromBf16(gbits))); + } + } + std.debug.print("rope_cache vs host rotate: bits miss {d} worst abs {e}\n", .{ bits_miss, worst }); + if (worst > 2e-3) return error.RopeCache; +} + +fn checkExpand() !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const rows: u32 = 4; + const H = s.heads; + var seed: u64 = 0x6765; + const gate = try c.fill(&seed, rows * H, a); + defer a.free(gate); + c.roundSlice(gate); + const q = try a.alloc(f32, rows * H * mla.qd); + defer a.free(q); + @memset(q, 0); + const kv = try a.alloc(f32, rows * mla.key); + defer a.free(kv); + @memset(kv, 0); + const w_rms: [mla.lat]f32 = @splat(1); + const kvb_w = try a.alloc(f32, H * (mla.nope + mla.vd) * mla.lat); + defer a.free(kvb_w); + @memset(kvb_w, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var gpu = try c.Gpu.init(); + defer gpu.deinit(); + var l = try c.Launch.open(gpu, s, rows, q, kv, &w_rms, kvb_w, gate); + defer l.deinit(); + const aa = l.args(rows); + const cb = gpu.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(gpu.gate_expand); + e.setBuffer(l.b_g, 0, 0); + e.setBuffer(l.b_g2, 0, 1); + e.setValue(aa, 2); + e.dispatchThreads(mtl.Size.of(H * mla.vd, rows, 1), mtl.Size.of(128, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("gate_expand failed: {s}\n", .{why}); + return error.GpuFailed; + } + const g_bits = l.b_g.slice(u16, rows * H); + const want = try a.alloc(u16, rows * H * mla.vd); + defer a.free(want); + mla.expandGate(want, g_bits, rows, H); + try c.expectBitsEqual("gate_expand", l.b_g2.slice(u16, want.len), want); +} + +test "Ling rope_q GPT-J halves vs host rotate" { + try checkRopeQ(); +} + +test "Ling rope_cache GPT-J halves vs host rotate" { + try checkRopeCache(); +} + +test "Ling gate_expand (T,H) to (T,H*128) bits-equal" { + try checkExpand(); +} diff --git a/zig/tests/ling_mla_gpu_mixer.zig b/zig/tests/ling_mla_gpu_mixer.zig new file mode 100644 index 00000000000..9abd25f4fee --- /dev/null +++ b/zig/tests/ling_mla_gpu_mixer.zig @@ -0,0 +1,38 @@ +//! Ling MLA mixer on Metal vs mla.zig f64 and bf16-point. +const std = @import("std"); +const mtl = @import("metal"); +const mla = @import("mla"); +const c = @import("ling_mla_gpu_common.zig"); + +fn checkMixer(rows: u32) !void { + const a = std.testing.allocator; + const s = mla.Shape{ .heads = 16, .eps = mla.eps_tiny, .theta = mla.theta_tiny }; + const in = try c.Inputs.make(a, s, rows, 0x6d6c61); + defer in.free(a); + const n = rows * s.outWidth(); + const want64 = try a.alloc(f64, n); + defer a.free(want64); + const want_bf = try a.alloc(f64, n); + defer a.free(want_bf); + try mla.mixF64(a, want64, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + try mla.mixBf16(a, want_bf, in.q, in.kv, in.w, in.kvb, in.g, s, rows, 0); + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var g = try c.Gpu.init(); + defer g.deinit(); + var l = try c.Launch.open(g, s, rows, in.q, in.kv, in.w, in.kvb, in.g); + defer l.deinit(); + try l.dispatchMixer(g, 0, rows); + var buf: [64]u8 = undefined; + const tag = try std.fmt.bufPrint(&buf, "mla {d} rows", .{rows}); + try c.gateNamed(tag, l.y(), want64, want_bf); +} + +test "MLA mixer Metal vs f64 and bf16-point on 2 rows from pos 0" { + try checkMixer(2); +} + +test "MLA mixer Metal vs f64 and bf16-point on 4 rows from pos 0" { + try checkMixer(4); +} From 809a722cc945a2e91fd35fd65152b05081b6b00b Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:18:29 +0100 Subject: [PATCH 010/158] Ling MLA Metal: kernel contract for rope_cache, rope_q, gate_expand Register tf_ling_mla_rope_cache, tf_ling_mla_rope_q and tf_ling_mla_gate_expand with planted source controls, the way Ling KDA and route were done in #3055. --- zig/build/kernel_contract.zig | 11 + zig/src/core/contract.zig | 1 + zig/src/core/contract/ling_mla_records.zig | 12 + zig/src/core/contract/registry_joins.zig | 1 + zig/tests/contract/metal_limits.zig | 5 + zig/tests/contract/metal_ling_mla.zig | 327 ++++++++++++++++++ .../contract/metal_ling_mla_controls.zig | 88 +++++ zig/tests/contract/metal_main.zig | 4 + 8 files changed, 449 insertions(+) create mode 100644 zig/src/core/contract/ling_mla_records.zig create mode 100644 zig/tests/contract/metal_ling_mla.zig create mode 100644 zig/tests/contract/metal_ling_mla_controls.zig diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 302036fc897..1e0a4dee504 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -29,6 +29,17 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { }) })); b.step("test-llama-controls-host", "Llama's source controls plant one fault without a device or shader compiler").dependOn(&llama_controls.step); step.dependOn(&llama_controls.step); + const ling_mla_controls = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/contract/metal_ling_mla_controls.zig"), + .target = b.graph.host, + .optimize = .debug, + .imports = &.{ + .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, + .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, + }, + }) })); + b.step("test-ling-mla-controls-host", "Ling MLA source controls plant one fault without a device or shader compiler").dependOn(&ling_mla_controls.step); + step.dependOn(&ling_mla_controls.step); const mapping_tf = b.createModule(.{ .root_source_file = b.path("zig/lfm2_mapping_tf.zig"), .imports = &.{ .{ .name = "metal", .module = mapping_stub }, .{ .name = "kernel_sources", .module = mapping_stub }, diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 24449e7175d..e6a3fc4355b 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -48,6 +48,7 @@ test { _ = @import("contract/metal_pair_records.zig"); _ = @import("contract/affine_gather_records.zig"); _ = @import("contract/flint_records.zig"); + _ = @import("contract/ling_mla_records.zig"); _ = spec; _ = gates; _ = rows; diff --git a/zig/src/core/contract/ling_mla_records.zig b/zig/src/core/contract/ling_mla_records.zig new file mode 100644 index 00000000000..ef706fa8efd --- /dev/null +++ b/zig/src/core/contract/ling_mla_records.zig @@ -0,0 +1,12 @@ +//! Ling MLA extras (tf_ling_mla_rope_cache, tf_ling_mla_rope_q, tf_ling_mla_gate_expand). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal ling mla tf_ling_mla_rope_cache", .threads = 32, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "metal ling mla tf_ling_mla_rope_q", .threads = 32, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "metal ling mla tf_ling_mla_gate_expand", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; + +test "the Ling MLA 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/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 89fc2034c7b..713ba42279b 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -81,6 +81,7 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("dsv41_metal_records.zig").records ++ @import("minimax_records.zig").records ++ @import("ling_route_records.zig").records ++ + @import("ling_mla_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("affine_gather_records.zig").records ++ @import("flint_records.zig").records ++ diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index dd38d01f48d..ba4a8387008 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -189,6 +189,11 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const body = @import("ling_metal").route; return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; } + if (std.mem.startsWith(u8, d.name, "metal ling mla ")) { + if (!assemble) return undefined; + const body = @import("ling_metal").mla; + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } if (std.mem.startsWith(u8, d.name, "nemotron paged ")) { if (!assemble) return undefined; return pagedLaunch(a, device, d, fun); diff --git a/zig/tests/contract/metal_ling_mla.zig b/zig/tests/contract/metal_ling_mla.zig new file mode 100644 index 00000000000..46a0dd42040 --- /dev/null +++ b/zig/tests/contract/metal_ling_mla.zig @@ -0,0 +1,327 @@ +//! Ling MLA extras under the contract: GPT-J RoPE on cache and q, and per-head gate expand. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ling_mla_controls.zig"); + +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; +const Mutation = controls.Mutation; + +const LAT: u32 = 512; +const ROPE: u32 = 64; +const KEY: u32 = LAT + ROPE; +const NOPE: u32 = 128; +const VD: u32 = 128; +const QD: u32 = NOPE + ROPE; +const NFREQ: u32 = ROPE / 2; +const HEADS: u32 = 16; +const THETA: f64 = 6_000_000; +const no_sums: c.Sums = .{ .f16 = 0, .bf16 = 0, .why = "no sums: elementwise rotate or a broadcast" }; + +const MlaRow = extern struct { slot: u32, pos: u32 }; +const MlaArgs = extern struct { + cache: u64, + slot_keys: u32, + heads: u32, + head0: u32, + rows: u32, + q_stride: u32, + kv_stride: u32, + gate_stride: u32, + out_stride: u32, + eps: f32, + scale: f32, +}; +comptime { + if (@sizeOf(MlaArgs) != 48) @compileError("MlaArgs must stay 48 bytes, matching k3"); +} + +fn none(_: c.Shape) usize { + return 0; +} + +fn invFreq(i: usize) f64 { + return 1.0 / std.math.pow(f64, THETA, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(ROPE))); +} + +pub fn spec(w: Which) c.Spec { + const rope = [_]c.Shape{ .{ .rows = 8, .n = HEADS, .k = ROPE }, .{ .rows = 1, .n = HEADS, .k = ROPE } }; + const cache = [_]c.Shape{ .{ .rows = 8, .n = 1, .k = ROPE }, .{ .rows = 1, .n = 1, .k = ROPE } }; + const gate = [_]c.Shape{ .{ .rows = 8, .n = HEADS * VD, .k = HEADS }, .{ .rows = 1, .n = HEADS * VD, .k = HEADS } }; + return switch (w) { + .rope_cache => .{ .name = "metal ling mla tf_ling_mla_rope_cache", .accum = .none, .depth = none, .ops = 2, .mids = 1, .out = .bf16, .in_place = true, .served = &cache, .sums = no_sums }, + .rope_q => .{ .name = "metal ling mla tf_ling_mla_rope_q", .accum = .none, .depth = none, .ops = 2, .mids = 1, .out = .bf16, .in_place = true, .served = &rope, .sums = no_sums }, + .gate_expand => .{ .name = "metal ling mla tf_ling_mla_gate_expand", .accum = .none, .depth = none, .out = .bf16, .served = &gate, .sums = no_sums }, + }; +} + +fn random16(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +fn plant(v: []u16, stride: usize, rows: usize, col: usize) void { + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (put, 0..) |f, r| if (r < rows) { + v[r * stride + col] = c.toBf16(f); + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + which: Which, + mutation: Mutation, + lib: mtl.Library, + pipe: mtl.Pipeline, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + q: []u16 = &.{}, + cache: []u16 = &.{}, + gate: []u16 = &.{}, + cs: []f32 = &.{}, + rows: []MlaRow = &.{}, + in_cs: rig_.Ref = undefined, + in_rows: rig_.Ref = undefined, + in_g: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which, mutation: Mutation) !Probe { + const plain = @import("ling_metal").mla; + const src = try controls.apply(a, plain, mutation); + defer a.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + return .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .which = which, + .mutation = mutation, + .lib = lib, + .pipe = try mtl.Pipeline.init(device, lib, controls.function(which), false), + }; + } + + fn drop(p: *Probe) void { + for ([_]*[]u16{ &p.q, &p.cache, &p.gate }) |s| { + p.a.free(s.*); + s.* = &.{}; + } + p.a.free(p.cs); + p.cs = &.{}; + p.a.free(p.rows); + p.rows = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.drop(); + p.rig.deinit(); + p.pipe.deinit(); + p.lib.deinit(); + } + + const vt = g.hooks(Probe); + + pub fn kernel(p: *Probe) g.Kernel { + var k: g.Kernel = .{ .spec = spec(p.which), .ctx = p, .vt = &vt }; + if (p.mutation != .none) { + k.spec.name = p.mutation.name(); + k.control = p.mutation.gate(); + } + return k; + } + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + switch (p.which) { + .rope_cache => if (s.k != ROPE or s.n != 1) return false, + .rope_q => if (s.k != ROPE or s.n != HEADS) return false, + .gate_expand => if (s.n != HEADS * VD or s.k != HEADS) return false, + } + if (s.rows == 0) return false; + p.drop(); + p.shape = s; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows: u32 = @intCast(s.rows); + p.rows = try p.a.alloc(MlaRow, rows); + for (p.rows, 0..) |*r, t| r.* = .{ .slot = 0, .pos = @intCast(t) }; + p.cs = try p.a.alloc(f32, rows * NFREQ * 2); + for (p.rows, 0..) |r, t| for (0..NFREQ) |i| { + const ang = @as(f64, @floatFromInt(r.pos)) * invFreq(i); + const at = (t * NFREQ + i) * 2; + p.cs[at] = @floatCast(@cos(ang)); + p.cs[at + 1] = @floatCast(@sin(ang)); + }; + p.in_cs = try p.rig.input(std.mem.sliceAsBytes(p.cs)); + switch (p.which) { + .rope_cache => { + p.cache = try p.a.alloc(u16, rows * KEY); + random16(rng, p.cache, -3, 3); + if (fill == .nonfinite) plant(p.cache, KEY, s.rows, LAT); + p.out = try p.rig.output(p.cache.len * 2); + }, + .rope_q => { + p.q = try p.a.alloc(u16, rows * HEADS * QD); + random16(rng, p.q, -3, 3); + if (fill == .nonfinite) plant(p.q, HEADS * QD, s.rows, NOPE); + p.out = try p.rig.output(p.q.len * 2); + }, + .gate_expand => { + p.gate = try p.a.alloc(u16, rows * HEADS); + random16(rng, p.gate, -2, 2); + if (fill == .nonfinite) plant(p.gate, HEADS, s.rows, 0); + p.in_g = try p.rig.input(std.mem.sliceAsBytes(p.gate)); + p.out = try p.rig.output(rows * HEADS * VD * 2); + }, + } + if (p.which == .rope_cache) p.in_rows = try p.rig.input(std.mem.sliceAsBytes(p.rows)); + return true; + } + + pub fn count(p: *Probe) usize { + const rows = p.shape.rows; + return switch (p.which) { + .rope_cache => rows * KEY, + .rope_q => rows * HEADS * QD, + .gate_expand => rows * HEADS * VD, + }; + } + + fn args(p: *Probe) MlaArgs { + const rows: u32 = @intCast(p.shape.rows); + return .{ + .cache = if (p.which == .rope_cache) p.out.buf.gpuAddress() + p.out.off else 0, + .slot_keys = rows, + .heads = HEADS, + .head0 = 0, + .rows = rows, + .q_stride = HEADS * QD, + .kv_stride = KEY, + .gate_stride = HEADS * VD, + .out_stride = HEADS * VD, + .eps = 1e-6, + .scale = 1, + }; + } + + pub fn run(p: *Probe) !void { + const rows = p.shape.rows; + switch (p.which) { + .rope_cache => @memcpy(p.rig.bytes(p.out, p.cache.len * 2), std.mem.sliceAsBytes(p.cache)), + .rope_q => @memcpy(p.rig.bytes(p.out, p.q.len * 2), std.mem.sliceAsBytes(p.q)), + .gate_expand => {}, + } + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.pipe); + const aa = p.args(); + switch (p.which) { + .rope_cache => { + e.setBuffer(p.in_rows.buf, p.in_rows.off, 0); + e.setValue(aa, 1); + e.setBuffer(p.in_cs.buf, p.in_cs.off, 2); + e.useResource(p.out.buf, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(32, 1, 1)); + }, + .rope_q => { + e.setBuffer(p.out.buf, p.out.off, 0); + e.setValue(aa, 1); + e.setBuffer(p.in_cs.buf, p.in_cs.off, 2); + e.dispatchGroups(mtl.Size.of(HEADS, rows, 1), mtl.Size.of(32, 1, 1)); + }, + .gate_expand => { + e.setBuffer(p.in_g.buf, p.in_g.off, 0); + e.setBuffer(p.out.buf, p.out.off, 1); + e.setValue(aa, 2); + e.dispatchThreads(mtl.Size.of(HEADS * VD, rows, 1), mtl.Size.of(128, 1, 1)); + }, + } + try p.rig.finish(pass); + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + const rows = p.shape.rows; + switch (p.which) { + .rope_cache => for (0..rows) |t| { + const z = p.cache[t * KEY ..][0..KEY]; + for (0..LAT) |i| { + want[t * KEY + i] = c.fromBf16(z[i]); + mag[t * KEY + i] = @abs(want[t * KEY + i]); + } + rotateRef(want[t * KEY + LAT ..][0..ROPE], mag[t * KEY + LAT ..][0..ROPE], z[LAT..][0..ROPE], p.cs[t * NFREQ * 2 ..][0 .. NFREQ * 2]); + }, + .rope_q => for (0..rows) |t| for (0..HEADS) |h| { + const base = (t * HEADS + h) * QD; + const z = p.q[base..][0..QD]; + for (0..NOPE) |i| { + want[base + i] = c.fromBf16(z[i]); + mag[base + i] = @abs(want[base + i]); + } + rotateRef(want[base + NOPE ..][0..ROPE], mag[base + NOPE ..][0..ROPE], z[NOPE..][0..ROPE], p.cs[t * NFREQ * 2 ..][0 .. NFREQ * 2]); + }, + .gate_expand => for (0..rows) |t| for (0..HEADS) |h| { + const v = c.fromBf16(p.gate[t * HEADS + h]); + const lo = (t * HEADS + h) * VD; + for (0..VD) |d| { + want[lo + d] = v; + mag[lo + d] = @abs(v); + } + }, + } + } +}; + +fn rotateRef(want: []f64, mag: []f64, z: []const u16, cs: []const f32) void { + for (0..NFREQ) |i| { + const x0: f64 = c.fromBf16(z[2 * i]); + const x1: f64 = c.fromBf16(z[2 * i + 1]); + const cv: f64 = cs[i * 2]; + const sv: f64 = cs[i * 2 + 1]; + want[i] = x0 * cv - x1 * sv; + want[NFREQ + i] = x1 * cv + x0 * sv; + mag[i] = @abs(x0) * @abs(cv) + @abs(x1) * @abs(sv); + mag[NFREQ + i] = mag[i]; + } +} + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const needle = only orelse return true; + return std.mem.indexOf(u8, name, needle) != null; +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + probes: std.ArrayList(*Probe) = .empty, + + pub fn collect(s: *Suite, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + for (std.enums.values(Which)) |w| { + const name = spec(w).name; + if (!wanted(only, name)) continue; + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = try Probe.init(s.a, s.device, s.queue, w, .none); + try s.probes.append(s.a, p); + try kernels.append(s.a, p.kernel()); + } + for (std.enums.values(Mutation)) |m| { + if (m == .none or !wanted(only, m.name())) continue; + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = try Probe.init(s.a, s.device, s.queue, m.which(), m); + try s.probes.append(s.a, p); + try kernels.append(s.a, p.kernel()); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_ling_mla_controls.zig b/zig/tests/contract/metal_ling_mla_controls.zig new file mode 100644 index 00000000000..31e96a46462 --- /dev/null +++ b/zig/tests/contract/metal_ling_mla_controls.zig @@ -0,0 +1,88 @@ +//! Planted controls for Ling MLA extras: one source edit a kernel, which gate 3 must report. +const std = @import("std"); +const contract = @import("contract"); + +pub const Which = enum { rope_cache, rope_q, gate_expand }; + +pub fn function(w: Which) []const u8 { + return switch (w) { + .rope_cache => "tf_ling_mla_rope_cache", + .rope_q => "tf_ling_mla_rope_q", + .gate_expand => "tf_ling_mla_gate_expand", + }; +} + +pub const Mutation = enum { + none, + rope_cache_cs0, + rope_q_cs0, + gate_head0, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .rope_cache_cs0 => "control: metal ling mla rope_cache, every row rotates at cs[0]", + .rope_q_cs0 => "control: metal ling mla rope_q, every row rotates at cs[0]", + .gate_head0 => "control: metal ling mla gate_expand, every head takes gate 0", + }; + } + + pub fn gate(m: Mutation) ?contract.gates.Gate { + return switch (m) { + .none => null, + else => .shapes, + }; + } + + pub fn which(m: Mutation) Which { + return switch (m) { + .none => unreachable, + .rope_cache_cs0 => .rope_cache, + .rope_q_cs0 => .rope_q, + .gate_head0 => .gate_expand, + }; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .rope_cache_cs0 => .{ + .from = "const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, row, t);", + .to = "const float2 o = ling_apply(float(dst[2 * t]), float(dst[2 * t + 1]), cs, 0, t);", + }, + .rope_q_cs0 => .{ + .from = "const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, row, t);", + .to = "const float2 o = ling_apply(float(z[2 * t]), float(z[2 * t + 1]), cs, 0, t);", + }, + .gate_head0 => .{ + .from = "g2[row * a.gate_stride + col] = g[row * a.heads + col / VD];", + .to = "g2[row * a.gate_stride + col] = g[row * a.heads];", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, text: []const u8, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +test "ling mla source control: each edit hits once" { + const a = std.testing.allocator; + const plain = @import("ling_metal").mla; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, plain, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectError(error.ControlEditMissing, apply(a, edited, m)); + try std.testing.expectEqual(contract.gates.Gate.shapes, m.gate().?); + } + const unchanged = try apply(a, plain, .none); + defer a.free(unchanged); + try std.testing.expectEqualStrings(plain, unchanged); +} diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index c72b53086c5..f85b2f1e705 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -8,6 +8,7 @@ const affine_k = @import("metal_affine.zig"); const gather_k = @import("metal_affine_gather.zig"); const topk_k = @import("metal_topk.zig"); const ling_route = @import("metal_ling_route.zig"); +const ling_mla = @import("metal_ling_mla.zig"); const tile_k = @import("metal_tile.zig"); const h3_k = @import("metal_h3.zig"); const h3_topk = @import("metal_h3_topk.zig"); @@ -353,6 +354,9 @@ pub fn main(init: std.process.Init) !u8 { ling = try ling_route.Route.init(a, device, queue); try kernels.append(a, ling.?.kernel()); } + var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; + defer ling_mla_set.deinit(); + try ling_mla_set.collect(&kernels, o.only); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; const p = try a.create(affine_k.Proj); From 971ac6abc6ba88a1388948b176d0f07f26f3827b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:13:55 +0000 Subject: [PATCH 011/158] changelog: #3609 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e41f745b73..3514af7915e 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 +- Metal: Ling-3.0-tiny's MLA layers run on Kimi's `k3_mla` kernels with three added kernels for cache and query RoPE and gate widening, registered with planted controls in the kernel contract (#3609). Thanks to @ThinkOffApp. + - Nemotron: the Living Weights copies left behind by the October revert are deleted and `cuda_pages` imports `living.lesson_route`, leaving one copy of the learner, pocket and lesson files (#3707). Thanks to @jschmied. - Flash Next on CUDA: after load, a mixed shard keeps only the n-gram table's pages in the page cache, and the final sweep reaches shards nested under `tensors/`, freeing about 3 GiB of page cache on the NVFP4 export with replies unchanged (#3467). Thanks to @jschmied. From 074a79f0a68f0d385ee1ba4a6daa9146e22b509e Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:05:35 +0700 Subject: [PATCH 012/158] app: honor the latest ticket review verdict --- .../agent/ticket-review-verdict.test.ts | 47 +++++++++++++++++++ app/electron/agent/tickets.ts | 42 +++++++---------- 2 files changed, 63 insertions(+), 26 deletions(-) create mode 100644 app/electron/agent/ticket-review-verdict.test.ts diff --git a/app/electron/agent/ticket-review-verdict.test.ts b/app/electron/agent/ticket-review-verdict.test.ts new file mode 100644 index 00000000000..b7b5f6e0702 --- /dev/null +++ b/app/electron/agent/ticket-review-verdict.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict' +import { roomFinalGateBlockers, ticketNeedsReviewAfterBuilder, ticketReviewGateState } from './tickets' +import type { Ticket, TicketEvidence } from './types' + +const finding: TicketEvidence = { id: 'finding', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 } +const approved: TicketEvidence = { id: 'approved', kind: 'review', summary: 'Reviewer approved; no blockers.', createdBy: 'Reviewer', createdAt: 20 } +const blocked: TicketEvidence = { id: 'blocked', kind: 'review', summary: 'Changes requested: regression in empty input handling.', createdBy: 'Reviewer', createdAt: 30 } +const waived: TicketEvidence = { id: 'waived', kind: 'note', summary: 'Review skipped: read-only source lookup, no code changes.', createdBy: 'Reviewer', createdAt: 20 } + +function ticket(evidence: TicketEvidence[], patch: Partial = {}): Ticket { + return { + id: 'ticket-fixture', projectId: 'project-fixture', roomId: 'room-fixture', title: 'Review the parser', body: '', + type: 'task', status: 'completed', priority: 'medium', effort: 'medium', tags: [], assignee: 'Builder', + parentId: null, threadId: null, runState: null, startedAt: null, order: 0, createdAt: 1, updatedAt: 40, + risk: 'high', allowedCapabilities: ['read'], requiredEvidence: ['Findings'], acceptanceCriteria: [], evidence, ...patch, + } +} + +let passed = 0 +function check(name: string, evidence: TicketEvidence[], allowed: boolean) { + const current = ticket(evidence) + assert.equal(ticketReviewGateState(current).hasReviewOrSkipAfterBuilder, allowed, name) + assert.equal(ticketNeedsReviewAfterBuilder(current), !allowed, name) + assert.deepEqual(roomFinalGateBlockers({ tickets: [current] }), allowed ? [] + : ['review evidence after builder or justified skip missing on: Review the parser.'], name) + passed++ +} + +check('an independent approval completes the gate', [finding, approved], true) +check('a later blocking verdict supersedes approval', [finding, approved, blocked], false) +check('another reviewer can reopen a ticket', [finding, approved, { ...blocked, createdBy: 'Second reviewer' }], false) +check('a fresh approval resolves the blocking verdict', [finding, approved, blocked, { ...approved, id: 'fresh', createdAt: 40 }], true) +check('an older blocking verdict does not override a newer approval', [finding, blocked, { ...approved, createdAt: 40 }], true) +check('timestamps take precedence over array order', [finding, blocked, approved], false) +check('the last verdict wins at equal timestamps', [finding, approved, { ...blocked, createdAt: 20 }], false) +check('a same-timestamp follow-up approval can resolve the verdict', [finding, blocked, { ...approved, createdAt: 30 }], true) +check('informational review notes do not revoke approval', [finding, approved, { ...blocked, summary: 'Reviewer inspected the examples.' }], true) +check('user approval records are not reviewer verdicts', [finding, approved, { ...blocked, kind: 'note', summary: 'User approval rejected for a separate action.' }], true) +check('a later blocking verdict supersedes a waiver', [finding, waived, blocked], false) +check('a justified later waiver can resolve read-only review', [finding, blocked, { ...waived, createdAt: 40 }], true) +check('a later self-review cannot reuse an older independent approval', [finding, approved, { ...approved, id: 'self', createdBy: 'Builder', createdAt: 40 }], false) + +const changed: TicketEvidence = { ...finding, kind: 'diff', summary: 'Changed src/parser.ts.' } +const green: TicketEvidence = { id: 'green', kind: 'test', summary: 'Parser tests passed.', createdBy: 'Builder', createdAt: 11 } +check('an invalid code-change waiver cannot bypass a blocking verdict', [changed, green, approved, blocked, { ...waived, createdAt: 40 }], false) + +console.log(`ticket review verdict: ${passed} cases passed`) diff --git a/app/electron/agent/tickets.ts b/app/electron/agent/tickets.ts index e7a68828e3f..74cdfc74eda 100644 --- a/app/electron/agent/tickets.ts +++ b/app/electron/agent/tickets.ts @@ -237,12 +237,11 @@ export interface TicketReviewGateState { export function ticketReviewGateState(ticket: Ticket): TicketReviewGateState { const evidence = meaningfulTicketEvidence(ticket) const builder = newestEvidence(evidence.filter(isBuilderEvidence)) - const review = newestReviewPassAfterBuilder(evidence) - const skip = newestReviewSkipAfterBuilder(evidence, ticket) + const review = newestReviewDecisionAfterBuilder(evidence) return { hasBuilderEvidence: !!builder, builderEvidenceBy: builder?.createdBy ?? null, - hasReviewOrSkipAfterBuilder: !!review || !!skip, + hasReviewOrSkipAfterBuilder: !!review, } } @@ -264,23 +263,15 @@ function newestEvidence(items: TicketEvidence[]): TicketEvidence | null { }, null) } -function newestReviewPassAfterBuilder(evidence: TicketEvidence[]): TicketEvidence | null { - return newestEvidence(evidence.filter((item) => { - if (!isReviewPassEvidence(item)) return false - const builder = newestBuilderEvidenceBefore(evidence, item) - if (!builder) return false - return !sameEvidenceCreator(builder, item) - })) -} - -function newestReviewSkipAfterBuilder(evidence: TicketEvidence[], ticket: Ticket): TicketEvidence | null { - if (hasCodeChangeEvidence(ticket)) return null - return newestEvidence(evidence.filter((item) => { - if (!isReviewSkipEvidence(item)) return false - const builder = newestBuilderEvidenceBefore(evidence, item) - if (!builder) return false - return !sameEvidenceCreator(builder, item) - })) +function newestReviewDecisionAfterBuilder(evidence: TicketEvidence[]): TicketEvidence | null { + const canSkip = !evidence.some(isCodeChangeEvidence) + const decision = newestEvidence(evidence.filter((item) => + isReviewPassEvidence(item) || canSkip && isReviewSkipEvidence(item) + || hasReviewerSignal(item) && isBlockingReviewEvidence(item), + )) + if (!decision || !(isReviewPassEvidence(decision) || canSkip && isReviewSkipEvidence(decision))) return null + const builder = newestBuilderEvidenceBefore(evidence, decision) + return builder && !sameEvidenceCreator(builder, decision) ? decision : null } function newestBuilderEvidenceBefore(evidence: TicketEvidence[], item: TicketEvidence): TicketEvidence | null { @@ -307,10 +298,6 @@ function hasUnresolvedExternalDestructiveApproval(ticket: Ticket): boolean { return !approvalAt || approvalAt < actionAt } -function hasCodeChangeEvidence(ticket: Ticket): boolean { - return meaningfulTicketEvidence(ticket).some(isCodeChangeEvidence) -} - function isBuilderEvidence(item: TicketEvidence): boolean { return !isReviewEvidence(item) && !isReviewSkipEvidence(item) } @@ -325,12 +312,15 @@ function isReviewEvidence(item: TicketEvidence): boolean { return item.kind === 'review' || /\b(reviewed|reviewer|verdict|approved|approval|blocking issues?|ready for final)\b/i.test(text) } +function hasReviewerSignal(item: TicketEvidence): boolean { + return item.kind === 'review' || /\b(reviewed|reviewer|review verdict|verdict)\b/i.test(evidenceText(item)) +} + function isReviewPassEvidence(item: TicketEvidence): boolean { if (isReviewSkipEvidence(item)) return false if (isBlockingReviewEvidence(item)) return false const text = evidenceText(item) - const reviewerSignal = item.kind === 'review' || /\b(reviewed|reviewer|review verdict|verdict)\b/i.test(text) - if (!reviewerSignal) return false + if (!hasReviewerSignal(item)) return false return /\b(approved|approval|pass(?:ed)?|verified|accepted|ready for final|ready to final|ready|finished|looks good|lgtm|no blockers?|no blocking issues?)\b/i.test(text) } From 92d711f4f8d84046357c089f9ebdb211b69d3ff6 Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:31:51 +0700 Subject: [PATCH 013/158] app: invalidate ticket reviews after new builder evidence --- .../agent/ticket-review-build.test.ts | 77 +++++++++++++++++++ app/electron/agent/tickets.ts | 25 ++++-- .../main/host/ticket-worker-evidence.test.ts | 73 ++++++++++++++++++ .../main/host/ticket-worker-runtime.ts | 6 +- 4 files changed, 172 insertions(+), 9 deletions(-) create mode 100644 app/electron/agent/ticket-review-build.test.ts create mode 100644 app/electron/main/host/ticket-worker-evidence.test.ts diff --git a/app/electron/agent/ticket-review-build.test.ts b/app/electron/agent/ticket-review-build.test.ts new file mode 100644 index 00000000000..99273f1ca46 --- /dev/null +++ b/app/electron/agent/ticket-review-build.test.ts @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict' +import { summarizeTicketWorkerOutcome } from '../main/host/ticket-helpers' +import { roomFinalGateBlockers, ticketNeedsReviewAfterBuilder, ticketReviewGateState } from './tickets' +import type { Thread, Ticket, TicketEvidence } from './types' + +const build: TicketEvidence = { id: 'build', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 } +const approval: TicketEvidence = { id: 'approval', kind: 'review', summary: 'Reviewer approved.', createdBy: 'Reviewer', createdAt: 20 } +const rebuild: TicketEvidence = { ...build, id: 'rebuild', summary: 'Inspected the follow-up implementation.', createdAt: 30 } +const waiver: TicketEvidence = { ...approval, id: 'waiver', kind: 'note', summary: 'Review skipped: read-only source lookup, no code changes.' } + +function ticket(evidence: TicketEvidence[]): Ticket { + return { + id: 'ticket-fixture', projectId: 'project-fixture', roomId: 'room-fixture', title: 'Follow-up implementation', body: '', + type: 'task', status: 'completed', priority: 'medium', effort: 'medium', tags: [], assignee: 'Builder', + parentId: null, threadId: null, runState: null, startedAt: null, order: 0, createdAt: 1, updatedAt: 90, + risk: 'high', allowedCapabilities: ['read'], requiredEvidence: ['Findings'], acceptanceCriteria: [], evidence, + } +} + +let passed = 0 +function check(name: string, evidence: TicketEvidence[], allowed: boolean, builder = 'Builder') { + const current = ticket(evidence) + assert.equal(ticketReviewGateState(current).hasReviewOrSkipAfterBuilder, allowed, name) + assert.equal(ticketReviewGateState(current).builderEvidenceBy, builder, name) + assert.equal(ticketNeedsReviewAfterBuilder(current), !allowed, name) + assert.deepEqual(roomFinalGateBlockers({ tickets: [current], greenEvidenceAt: 100 }), allowed ? [] + : ['review evidence after builder or justified skip missing on: Follow-up implementation.'], name) + passed++ +} + +function worker(phase: 'build' | 'review', at: number, createdBy: string | null, changes = false): TicketEvidence[] { + const now = Date.now + Date.now = () => at + try { + const thread = { + id: `${phase}-thread-${at}`, + timeline: [ + { id: 'read', kind: 'tool', path: 'src/parser.ts', state: 'ok' }, + ...(changes ? [{ id: 'edit', kind: 'tool', path: 'src/parser.ts', diff: [{ type: 'add', text: 'const value = 1' }], state: 'ok' }] : []), + { id: 'status', kind: 'tool', command: 'git status --short', output: '', state: 'ok' }, + { id: 'test', kind: 'tool', command: 'npm test', output: '2 passed', state: 'ok' }, + ], + } as unknown as Thread + return summarizeTicketWorkerOutcome(ticket([]), thread, phase, false, createdBy).evidence + } finally { Date.now = now } +} + +check('an approval does not cover later builder findings', [build, approval, rebuild], false) +check('timestamp order wins over insertion order', [rebuild, build, approval], false) +check('a fresh independent approval covers the rebuild', [build, approval, rebuild, { ...approval, id: 'fresh', createdAt: 40 }], true) +check('a waiver does not cover later builder findings', [build, waiver, rebuild], false) +check('a fresh justified waiver covers read-only work', [build, waiver, rebuild, { ...waiver, id: 'fresh-waiver', createdAt: 40 }], true) +check('a new builder is reported as the current builder', [build, approval, { ...rebuild, createdBy: 'Second builder' }], false, 'Second builder') +check('a review cannot cover a build at the same timestamp', [build, approval, { ...rebuild, createdAt: 20 }], false) + +const reviewRun = worker('review', 20, 'Reviewer') +const reviewOnly = ticket(reviewRun) +assert.deepEqual(ticketReviewGateState(reviewOnly), { hasBuilderEvidence: false, builderEvidenceBy: null, hasReviewOrSkipAfterBuilder: false }) +assert.equal(ticketNeedsReviewAfterBuilder(reviewOnly), false, 'a review cannot create builder evidence for another review') +assert.deepEqual(roomFinalGateBlockers({ tickets: [reviewOnly] }), ['review evidence after builder or justified skip missing on: Follow-up implementation.']) +passed++ +check('real reviewer verification is not a new build', [build, ...reviewRun], true) +check('review batch order does not alter builder ownership', [build, ...[...reviewRun].reverse()], true) +check('anonymous review batches keep the same verification behavior', [build, ...worker('review', 20, null)], true) +check('an actual later build worker invalidates the review', [build, ...reviewRun, ...worker('build', 30, 'Builder')], false) +check('a new review worker covers the actual rebuilt output', [build, ...reviewRun, ...worker('build', 30, 'Builder'), ...worker('review', 40, 'Reviewer')], true) + +const testResult = reviewRun.find((item) => item.kind === 'test')! +assert.ok(testResult, 'the host fixture must produce a verification record') +check('another thread cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'other-thread', ref: 'thread:other-run' }], false, 'Reviewer') +check('another actor cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'other-actor', createdBy: 'Second builder' }], false, 'Second builder') +check('a missing thread reference cannot inherit a review batch exemption', [build, ...reviewRun, { ...testResult, id: 'missing-ref', ref: null }], false, 'Reviewer') +check('a later run cannot reuse an earlier batch timestamp', [build, ...reviewRun, { ...testResult, id: 'later-run', createdAt: 30 }], false, 'Reviewer') +check('code changes made during a review still need independent review', [build, ...worker('review', 20, 'Reviewer', true)], false, 'Reviewer') +check('a different reviewer can approve the reviewer-made changes', [build, ...worker('review', 20, 'Reviewer', true), { ...approval, id: 'independent', createdBy: 'Second reviewer', createdAt: 30 }], true, 'Reviewer') + +console.log(`ticket review build freshness: ${passed} cases passed`) diff --git a/app/electron/agent/tickets.ts b/app/electron/agent/tickets.ts index 74cdfc74eda..f2b4949a2b0 100644 --- a/app/electron/agent/tickets.ts +++ b/app/electron/agent/tickets.ts @@ -236,8 +236,8 @@ export interface TicketReviewGateState { export function ticketReviewGateState(ticket: Ticket): TicketReviewGateState { const evidence = meaningfulTicketEvidence(ticket) - const builder = newestEvidence(evidence.filter(isBuilderEvidence)) - const review = newestReviewDecisionAfterBuilder(evidence) + const builder = newestBuilderEvidence(evidence) + const review = newestReviewDecisionAfterBuilder(evidence, builder) return { hasBuilderEvidence: !!builder, builderEvidenceBy: builder?.createdBy ?? null, @@ -263,19 +263,30 @@ function newestEvidence(items: TicketEvidence[]): TicketEvidence | null { }, null) } -function newestReviewDecisionAfterBuilder(evidence: TicketEvidence[]): TicketEvidence | null { +function newestReviewDecisionAfterBuilder(evidence: TicketEvidence[], builder: TicketEvidence | null): TicketEvidence | null { const canSkip = !evidence.some(isCodeChangeEvidence) const decision = newestEvidence(evidence.filter((item) => isReviewPassEvidence(item) || canSkip && isReviewSkipEvidence(item) || hasReviewerSignal(item) && isBlockingReviewEvidence(item), )) if (!decision || !(isReviewPassEvidence(decision) || canSkip && isReviewSkipEvidence(decision))) return null - const builder = newestBuilderEvidenceBefore(evidence, decision) - return builder && !sameEvidenceCreator(builder, decision) ? decision : null + return builder && builder.createdAt < decision.createdAt && !sameEvidenceCreator(builder, decision) ? decision : null } -function newestBuilderEvidenceBefore(evidence: TicketEvidence[], item: TicketEvidence): TicketEvidence | null { - return newestEvidence(evidence.filter((candidate) => isBuilderEvidence(candidate) && candidate.createdAt < item.createdAt)) +function newestBuilderEvidence(evidence: TicketEvidence[]): TicketEvidence | null { + const reviewBatches = new Set(evidence.filter((item) => item.kind === 'review') + .map(reviewBatchKey).filter((key): key is string => key !== null)) + return newestEvidence(evidence.filter((item) => { + if (!isBuilderEvidence(item)) return false + const verification = item.kind === 'test' || item.kind === 'command' + const batch = reviewBatchKey(item) + return !verification || isCodeChangeEvidence(item) || batch === null || !reviewBatches.has(batch) + })) +} + +function reviewBatchKey(item: TicketEvidence): string | null { + if (!item.ref?.startsWith('thread:') || item.ref.length === 'thread:'.length) return null + return JSON.stringify([item.createdAt, item.createdBy ?? null, item.ref]) } function sameEvidenceCreator(a: TicketEvidence, b: TicketEvidence): boolean { diff --git a/app/electron/main/host/ticket-worker-evidence.test.ts b/app/electron/main/host/ticket-worker-evidence.test.ts new file mode 100644 index 00000000000..acc6ee5ddb2 --- /dev/null +++ b/app/electron/main/host/ticket-worker-evidence.test.ts @@ -0,0 +1,73 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { settleTicketExecution, startTicketExecution, ticketReviewGateState, ticketStateAfterRun } from '../../agent/tickets' +import { summarizeTicketWorkerOutcome } from './ticket-helpers' +import type { Thread, Ticket, TimelineItem } from '../../agent/types' + +const source = readFileSync(path.resolve('electron/main/host/ticket-worker-runtime.ts'), 'utf8') +const start = source.indexOf('.finally(() => {') + '.finally(() => {'.length +const end = source.indexOf('\n })\n launched = true', start) +assert.ok(start > 0 && end > start, 'the production worker settlement must be present') +const settlement = source.slice(start, end) +const capture = source.match(/const timelineBaseline = ([^\n]+)/)?.[1] + +const oldDiff = { id: 'old-diff', kind: 'tool', path: 'src/parser.ts', state: 'ok', diff: [{ type: 'add', text: 'const value = 1' }] } as TimelineItem +const oldTest = { id: 'old-test', kind: 'tool', command: 'npm test', output: '2 passed', state: 'ok' } as TimelineItem +const currentRead = { id: 'current-read', kind: 'tool', path: 'src/parser.ts', state: 'ok' } as TimelineItem +const currentTest = { id: 'current-test', kind: 'tool', command: 'npm test', output: '3 passed', state: 'ok' } as TimelineItem + +function settle(previous: TimelineItem[], current: TimelineItem[], phase: 'build' | 'review' = 'review') { + const t = { id: 'reused-thread', status: 'running', timeline: [...previous] } as Thread + const timelineBaseline = capture ? new Function('thread', `return ${capture}`)(t) : previous.length + t.timeline.push(...current) + const ticket = { + id: 'ticket-fixture', title: 'Inspect parser', status: 'in_progress', risk: 'high', allowedCapabilities: ['read'], + evidence: [{ id: 'builder', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 }], + execution: startTicketExecution({ target: 'room', threadId: t.id, startedAt: 20 }), + } as Ticket + let outcome: string | null = null + let released = false + const scope = { + t, ticket, timelineBaseline, phase, model: 'fixture', room: null, job: null, + input: { source: { seat: phase === 'review' ? 'Reviewer' : 'Builder' } }, controller: new AbortController(), aborters: new Map(), + runLease: { release() { released = true } }, markUndrainedCues() {}, activeJob() { return null }, + appendRoomSupervisorEvent() {}, finishJob(_job: unknown, result: string) { outcome = result }, + persistThreads() {}, persistTickets() {}, emitTicket() {}, + summarizeTicketWorkerOutcome, ticketStateAfterRun, settleTicketExecution, + } + new Function(...Object.keys(scope), settlement)(...Object.values(scope)) + assert.ok(released, 'the real settlement still releases its run reservation') + assert.deepEqual(t.timeline, [...previous, ...current], 'scoping evidence retains the complete thread history') + return { ticket, outcome } +} + +const clean = settle([oldDiff, oldTest], [currentRead, currentTest]) +assert.equal(clean.ticket.evidence!.filter((item) => item.kind === 'diff').length, 0, 'old build diffs must not become reviewer-made changes') +assert.equal(clean.ticket.status, 'completed') +assert.equal(clean.outcome, 'completed') +assert.equal(ticketReviewGateState(clean.ticket).hasReviewOrSkipAfterBuilder, true) +assert.equal(ticketReviewGateState(clean.ticket).builderEvidenceBy, 'Builder') + +const recovered = settle([{ id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead, currentTest]) +assert.equal(recovered.ticket.status, 'completed', 'an earlier run error does not fail this review') +assert.equal(recovered.outcome, 'completed') + +const noCurrentTest = settle([oldTest], [currentRead]) +assert.ok(!noCurrentTest.ticket.evidence!.some((item) => item.kind === 'test'), 'old passing tests are not new verification') +assert.deepEqual(noCurrentTest.ticket.execution!.checks, []) + +const changed = settle([], [{ ...oldDiff, id: 'current-diff' }, currentTest]) +assert.ok(changed.ticket.evidence!.some((item) => item.kind === 'diff'), 'current reviewer changes remain recorded') +assert.equal(ticketReviewGateState(changed.ticket).hasReviewOrSkipAfterBuilder, false, 'reviewer-made changes still need independent review') + +const failed = settle([], [{ id: 'current-error', kind: 'error', text: 'This review failed.' } as TimelineItem]) +assert.equal(failed.ticket.status, 'needs_clarification') +assert.equal(failed.outcome, 'failed') +assert.ok(failed.ticket.evidence!.some((item) => item.kind === 'review' && item.summary.includes('blocked'))) +const rebuilt = settle([oldDiff, oldTest, { id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead], 'build') +assert.equal(rebuilt.ticket.status, 'review', 'a clean rebuild is not failed by an older run') +assert.equal(rebuilt.outcome, 'completed') +assert.ok(!rebuilt.ticket.evidence!.some((item) => item.kind === 'test' || item.kind === 'diff'), 'a rebuild only records its own output') +if (capture) assert.ok(source.indexOf('const timelineBaseline = ') < source.indexOf('thread.timeline.push(userItem)'), 'the boundary is frozen before this run appends events') +console.log('ticket worker evidence: 6 production-settlement scenarios passed') diff --git a/app/electron/main/host/ticket-worker-runtime.ts b/app/electron/main/host/ticket-worker-runtime.ts index 80afcc2fb34..ec0f72e9233 100644 --- a/app/electron/main/host/ticket-worker-runtime.ts +++ b/app/electron/main/host/ticket-worker-runtime.ts @@ -211,6 +211,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { store.threads.unshift(thread); persistThreads() sendToRenderer('thread:update', thread) } + const timelineBaseline = thread.timeline.length ticket.threadId = thread.id ticket.status = 'in_progress' ticket.runState = 'running' @@ -396,7 +397,8 @@ async function startTicketWork(input: TicketWorkerInput): Promise { markUndrainedCues(t, controller.signal.aborted ? 'canceled' : 'run ended') aborters.delete(t.id) runLease.release() - const failed = t.timeline.some((i) => i.kind === 'error') + const runTimeline = t.timeline.slice(timelineBaseline) + const failed = runTimeline.some((i) => i.kind === 'error') const interrupted = controller.signal.aborted t.status = failed ? 'error' : 'idle'; t.updatedAt = Date.now() // When the run was aborted/paused (no completion), park the ticket without @@ -406,7 +408,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { ticket.runState = settled.runState ticket.status = settled.status ticket.updatedAt = Date.now() - const summary = summarizeTicketWorkerOutcome(ticket, t, phase, failed, input.source?.seat ?? model) + const summary = summarizeTicketWorkerOutcome(ticket, { ...t, timeline: runTimeline }, phase, failed, input.source?.seat ?? model) if (ticket.execution) { ticket.execution = settleTicketExecution(ticket.execution, { outcome: { phase, failed, interrupted }, From 66cde0579cf6406a14c337f8ee63a3c2b6069caf Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:30:21 +0700 Subject: [PATCH 014/158] app: keep review notes and worker evidence scoped to their run --- .../agent/ticket-review-build.test.ts | 29 ++++ .../agent/ticket-review-verdict.test.ts | 6 + app/electron/agent/tickets.ts | 16 +- .../main/host/ticket-worker-evidence.test.ts | 160 +++++++++++++----- .../main/host/ticket-worker-runtime.ts | 33 +++- 5 files changed, 186 insertions(+), 58 deletions(-) diff --git a/app/electron/agent/ticket-review-build.test.ts b/app/electron/agent/ticket-review-build.test.ts index 99273f1ca46..b983eeb0934 100644 --- a/app/electron/agent/ticket-review-build.test.ts +++ b/app/electron/agent/ticket-review-build.test.ts @@ -53,6 +53,35 @@ check('a fresh justified waiver covers read-only work', [build, waiver, rebuild, check('a new builder is reported as the current builder', [build, approval, { ...rebuild, createdBy: 'Second builder' }], false, 'Second builder') check('a review cannot cover a build at the same timestamp', [build, approval, { ...rebuild, createdAt: 20 }], false) +const reviewBlocker: TicketEvidence = { + id: 'review-blocker', kind: 'note', summary: 'Blocker: parser validation failed.', + createdBy: 'Reviewer', createdAt: 20, ref: 'thread:review-fixture', +} +const blockedBatch = [{ ...approval, ref: reviewBlocker.ref }, reviewBlocker] +check('a reviewer blocker preserves the original builder identity', [build, ...blockedBatch], false) +check('reviewer blocker batches are independent of insertion order', [build, ...[...blockedBatch].reverse()], false) +check('a fresh approval resolves the reviewer blocker without a new build', [build, ...blockedBatch, { + ...approval, id: 'resolved', createdAt: 30, +}], true) +check('an unrelated note cannot inherit a review blocker batch', [build, ...blockedBatch.slice(0, 1), { + ...reviewBlocker, ref: 'thread:other-review', +}], true) +check('another actor cannot attach a review blocker batch', [build, blockedBatch[0], { + ...reviewBlocker, createdBy: 'Another actor', +}], true) +check('another timestamp cannot attach a review blocker batch', [build, blockedBatch[0], { + ...reviewBlocker, createdAt: 21, +}], true) +check('a blocker describing changed code is still a review finding', [build, blockedBatch[0], { + ...reviewBlocker, summary: 'Blocker: changed parser behavior fails validation.', +}], false) +check('an explicit empty blocker does not reject a review', [build, blockedBatch[0], { + ...reviewBlocker, summary: 'Blocker: none', +}], true) +check('a later builder run still invalidates approval without file events', [build, approval, { + ...build, id: 'builder-run', kind: 'note', summary: 'Builder worker finished the follow-up.', createdAt: 30, +}], false) + const reviewRun = worker('review', 20, 'Reviewer') const reviewOnly = ticket(reviewRun) assert.deepEqual(ticketReviewGateState(reviewOnly), { hasBuilderEvidence: false, builderEvidenceBy: null, hasReviewOrSkipAfterBuilder: false }) diff --git a/app/electron/agent/ticket-review-verdict.test.ts b/app/electron/agent/ticket-review-verdict.test.ts index b7b5f6e0702..cf6825a6a4a 100644 --- a/app/electron/agent/ticket-review-verdict.test.ts +++ b/app/electron/agent/ticket-review-verdict.test.ts @@ -27,6 +27,12 @@ function check(name: string, evidence: TicketEvidence[], allowed: boolean) { } check('an independent approval completes the gate', [finding, approved], true) +check('an ordinary later note does not revoke approval', [finding, approved, { + ...finding, id: 'reminder', kind: 'note', summary: 'Follow up with the documentation team tomorrow.', createdAt: 30, +}], true) +check('a later note describing code changes still requires review', [finding, approved, { + ...finding, id: 'changed-note', kind: 'note', summary: 'Changed the parser implementation.', createdAt: 30, +}, { ...finding, id: 'later-green', kind: 'test', summary: 'Parser tests passed.', createdAt: 31 }], false) check('a later blocking verdict supersedes approval', [finding, approved, blocked], false) check('another reviewer can reopen a ticket', [finding, approved, { ...blocked, createdBy: 'Second reviewer' }], false) check('a fresh approval resolves the blocking verdict', [finding, approved, blocked, { ...approved, id: 'fresh', createdAt: 40 }], true) diff --git a/app/electron/agent/tickets.ts b/app/electron/agent/tickets.ts index f2b4949a2b0..e8cfaaba3e7 100644 --- a/app/electron/agent/tickets.ts +++ b/app/electron/agent/tickets.ts @@ -236,7 +236,7 @@ export interface TicketReviewGateState { export function ticketReviewGateState(ticket: Ticket): TicketReviewGateState { const evidence = meaningfulTicketEvidence(ticket) - const builder = newestBuilderEvidence(evidence) + const builder = newestBuilderEvidence(evidence, ticket) const review = newestReviewDecisionAfterBuilder(evidence, builder) return { hasBuilderEvidence: !!builder, @@ -270,14 +270,17 @@ function newestReviewDecisionAfterBuilder(evidence: TicketEvidence[], builder: T || hasReviewerSignal(item) && isBlockingReviewEvidence(item), )) if (!decision || !(isReviewPassEvidence(decision) || canSkip && isReviewSkipEvidence(decision))) return null + const batch = reviewBatchKey(decision) + if (batch && evidence.some((item) => item.kind === 'note' && reviewBatchKey(item) === batch + && /^Blocker:/i.test(item.summary) && isBlockingReviewEvidence(item))) return null return builder && builder.createdAt < decision.createdAt && !sameEvidenceCreator(builder, decision) ? decision : null } -function newestBuilderEvidence(evidence: TicketEvidence[]): TicketEvidence | null { +function newestBuilderEvidence(evidence: TicketEvidence[], ticket: Ticket): TicketEvidence | null { const reviewBatches = new Set(evidence.filter((item) => item.kind === 'review') .map(reviewBatchKey).filter((key): key is string => key !== null)) return newestEvidence(evidence.filter((item) => { - if (!isBuilderEvidence(item)) return false + if (!isBuilderEvidence(item, ticket)) return false const verification = item.kind === 'test' || item.kind === 'command' const batch = reviewBatchKey(item) return !verification || isCodeChangeEvidence(item) || batch === null || !reviewBatches.has(batch) @@ -309,8 +312,11 @@ function hasUnresolvedExternalDestructiveApproval(ticket: Ticket): boolean { return !approvalAt || approvalAt < actionAt } -function isBuilderEvidence(item: TicketEvidence): boolean { - return !isReviewEvidence(item) && !isReviewSkipEvidence(item) +function isBuilderEvidence(item: TicketEvidence, ticket: Ticket): boolean { + if (isReviewEvidence(item) || isReviewSkipEvidence(item)) return false + if (item.kind === 'note' && /^Blocker:/i.test(item.summary)) return false + return item.kind !== 'note' || isCodeChangeEvidence(item) || /^Builder worker\b/i.test(item.summary) + || isExternalDestructiveActionEvidence(item, ticket) } function isReservationEvidence(item: TicketEvidence): boolean { diff --git a/app/electron/main/host/ticket-worker-evidence.test.ts b/app/electron/main/host/ticket-worker-evidence.test.ts index acc6ee5ddb2..d413c9885da 100644 --- a/app/electron/main/host/ticket-worker-evidence.test.ts +++ b/app/electron/main/host/ticket-worker-evidence.test.ts @@ -1,73 +1,139 @@ import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import path from 'node:path' -import { settleTicketExecution, startTicketExecution, ticketReviewGateState, ticketStateAfterRun } from '../../agent/tickets' -import { summarizeTicketWorkerOutcome } from './ticket-helpers' -import type { Thread, Ticket, TimelineItem } from '../../agent/types' - -const source = readFileSync(path.resolve('electron/main/host/ticket-worker-runtime.ts'), 'utf8') -const start = source.indexOf('.finally(() => {') + '.finally(() => {'.length -const end = source.indexOf('\n })\n launched = true', start) -assert.ok(start > 0 && end > start, 'the production worker settlement must be present') -const settlement = source.slice(start, end) -const capture = source.match(/const timelineBaseline = ([^\n]+)/)?.[1] +import { ticketReviewGateState } from '../../agent/tickets' +import type { AgentEvent, Job, Thread, Ticket, TimelineItem } from '../../agent/types' +import { store } from '../state' +import { createTicketWorkerRuntime } from './ticket-worker-runtime' const oldDiff = { id: 'old-diff', kind: 'tool', path: 'src/parser.ts', state: 'ok', diff: [{ type: 'add', text: 'const value = 1' }] } as TimelineItem const oldTest = { id: 'old-test', kind: 'tool', command: 'npm test', output: '2 passed', state: 'ok' } as TimelineItem const currentRead = { id: 'current-read', kind: 'tool', path: 'src/parser.ts', state: 'ok' } as TimelineItem const currentTest = { id: 'current-test', kind: 'tool', command: 'npm test', output: '3 passed', state: 'ok' } as TimelineItem -function settle(previous: TimelineItem[], current: TimelineItem[], phase: 'build' | 'review' = 'review') { - const t = { id: 'reused-thread', status: 'running', timeline: [...previous] } as Thread - const timelineBaseline = capture ? new Function('thread', `return ${capture}`)(t) : previous.length - t.timeline.push(...current) +interface Scenario { + phase?: 'build' | 'review' + rewrite?: 'trim' | 'replace' | 'reverse' | 'remove-current' + interrupted?: boolean +} + +function applyEvent(thread: Thread, event: AgentEvent): void { + if (event.type === 'item_add') thread.timeline.push(structuredClone(event.item)) + else if (event.type === 'item_update') Object.assign(thread.timeline.find((item) => item.id === event.id) ?? {}, event.patch) + else if (event.type === 'item_delta') { + const item = thread.timeline.find((candidate) => candidate.id === event.id) + if (item) item[event.field] = (item[event.field] ?? '') + event.chunk + } +} + +let passed = 0 +async function scenario(previous: TimelineItem[], current: TimelineItem[], options: Scenario = {}) { + const saved = { tickets: store.tickets, projects: store.projects, rooms: store.rooms, threads: store.threads, settings: store.settings } + const phase = options.phase ?? 'review' + const thread = { + id: 'reused-thread', projectId: 'project', title: 'Inspect parser', kind: 'task', cwd: '/workspace/project', + providerId: 'fixture', model: 'fixture', + status: 'idle', timeline: structuredClone(previous), apiMessages: [], createdAt: 1, updatedAt: 1, + } as Thread const ticket = { - id: 'ticket-fixture', title: 'Inspect parser', status: 'in_progress', risk: 'high', allowedCapabilities: ['read'], + id: 'ticket', projectId: 'project', threadId: thread.id, title: 'Inspect parser', body: '', type: 'task', + status: 'review', priority: 'medium', effort: 'small', tags: [], order: 0, createdAt: 1, updatedAt: 1, + parentId: null, assignee: 'Builder', runState: null, + risk: 'high', allowedCapabilities: ['read'], evidence: [{ id: 'builder', kind: 'file', summary: 'Inspected src/parser.ts.', createdBy: 'Builder', createdAt: 10 }], - execution: startTicketExecution({ target: 'room', threadId: t.id, startedAt: 20 }), } as Ticket - let outcome: string | null = null - let released = false - const scope = { - t, ticket, timelineBaseline, phase, model: 'fixture', room: null, job: null, - input: { source: { seat: phase === 'review' ? 'Reviewer' : 'Builder' } }, controller: new AbortController(), aborters: new Map(), - runLease: { release() { released = true } }, markUndrainedCues() {}, activeJob() { return null }, - appendRoomSupervisorEvent() {}, finishJob(_job: unknown, result: string) { outcome = result }, - persistThreads() {}, persistTickets() {}, emitTicket() {}, - summarizeTicketWorkerOutcome, ticketStateAfterRun, settleTicketExecution, + const provider = { id: 'fixture', name: 'Fixture', kind: 'local', models: ['fixture'], baseUrl: 'http://127.0.0.1:9897/v1', apiKey: '' } as const + const aborters = new Map() + let released = false, outcome: string | null = null, savedTimeline: TimelineItem[] = [], published = 0 + let settled!: () => void + const completion = new Promise((resolve) => { settled = resolve }) + let timer: ReturnType | undefined + try { + store.tickets = [ticket] + store.projects = [{ id: 'project', name: 'Fixture project', cwd: thread.cwd, memory: '', team: '', createdAt: 1, updatedAt: 1 }] + store.rooms = [] + store.threads = [thread] + store.settings = { ...saved.settings, providers: [{ ...provider, models: [...provider.models] }], activeProviderId: provider.id, activeModel: 'fixture' } + const runtime = createTicketWorkerRuntime({ + runAgent: async ({ emit, thread: active }) => { + const base = { runId: 'fixture-run', threadId: active.id } + for (const item of current) emit({ ...base, type: 'item_add', item: structuredClone(item) }) + if (options.rewrite === 'trim') active.timeline.splice(0, previous.length) + if (options.rewrite === 'replace') active.timeline = [] + if (options.rewrite === 'reverse') active.timeline.reverse() + if (options.rewrite === 'remove-current') { + active.timeline = active.timeline.filter((item) => item.id !== currentTest.id) + emit({ ...base, type: 'item_update', id: currentTest.id, patch: { state: 'ok', output: '3 ' } }) + emit({ ...base, type: 'item_delta', id: currentTest.id, field: 'output', chunk: 'passed' }) + } + emit({ ...base, type: 'item_update', id: oldDiff.id, patch: { state: 'ok' } }) + if (options.interrupted) aborters.get(active.id)!.abort() + savedTimeline = structuredClone(active.timeline) + }, + resolveWorkspaceCwd: async () => '/workspace/project', + inspectGitRepository: async () => ({ branch: 'fixture' }) as any, + persistThreads() {}, persistTickets() {}, emitTicket() { published++ }, appendRoomSupervisorEvent() {}, + claimJob: () => ({ id: 'job' }) as Job, patchJob: (job) => job, fullToolContext: () => ({}), + drainThreadCues: () => [], waitForThreadCue: async () => {}, approvalResolver: () => async () => 'deny', + timelineErrorSince: (active, start) => active.timeline.slice(start).find((item) => item.kind === 'error') ?? null, + timelineError: () => new Error('Synthetic agent error'), isHighRiskTool: () => false, emitToRenderer() {}, + addThreadNotice() {}, auditModelRoute: async () => {}, markRouteErrorRecovered() {}, injectThreadRouteHandoff: () => '', + aborters, workspaceMutationGuard: { + assertThreadStartAllowed() {}, + reserveStart: () => ({ addWorkspaceKeys() {}, addThreadId() {}, release() { released = true } }), + }, + applyEventToThread: applyEvent, activeJob: () => null, + finishJob: (_job, result) => { outcome = result; settled() }, markUndrainedCues() {}, effectiveContextLimit: () => 4096, + }) + assert.equal(await runtime.startTicketWork({ ticketId: ticket.id, opts: { phase } }), thread) + await Promise.race([completion, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Worker settlement timed out')), 2000) })]) + assert.ok(released, 'the production finalizer releases its run reservation') + assert.equal(aborters.size, 0, 'the production finalizer clears the active worker') + assert.equal(published, 2, 'startup and settlement both publish the ticket') + assert.equal(runtime.isTicketStarting(ticket.id), false) + assert.deepEqual(thread.timeline, savedTimeline, 'settlement leaves live conversation history intact') + passed++ + return { ticket, outcome } + } finally { + clearTimeout(timer) + Object.assign(store, saved) } - new Function(...Object.keys(scope), settlement)(...Object.values(scope)) - assert.ok(released, 'the real settlement still releases its run reservation') - assert.deepEqual(t.timeline, [...previous, ...current], 'scoping evidence retains the complete thread history') - return { ticket, outcome } } -const clean = settle([oldDiff, oldTest], [currentRead, currentTest]) -assert.equal(clean.ticket.evidence!.filter((item) => item.kind === 'diff').length, 0, 'old build diffs must not become reviewer-made changes') +const clean = await scenario([oldDiff, oldTest], [currentRead, currentTest]) +assert.equal(clean.ticket.evidence!.filter((item) => item.kind === 'diff').length, 0, 'old diffs are not reviewer-made changes') assert.equal(clean.ticket.status, 'completed') assert.equal(clean.outcome, 'completed') assert.equal(ticketReviewGateState(clean.ticket).hasReviewOrSkipAfterBuilder, true) assert.equal(ticketReviewGateState(clean.ticket).builderEvidenceBy, 'Builder') -const recovered = settle([{ id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead, currentTest]) -assert.equal(recovered.ticket.status, 'completed', 'an earlier run error does not fail this review') -assert.equal(recovered.outcome, 'completed') +for (const rewrite of ['trim', 'replace', 'reverse', 'remove-current'] as const) { + const result = await scenario([oldDiff, oldTest], [currentRead, currentTest], { rewrite }) + assert.deepEqual(result.ticket.execution!.checks, [{ command: 'npm test', passed: true }], `${rewrite} retains this run's verification`) + assert.ok(!result.ticket.evidence!.some((item) => item.kind === 'diff'), `${rewrite} excludes historical diffs`) +} + +const recovered = await scenario([{ id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead, currentTest]) +assert.equal(recovered.ticket.status, 'completed', 'old errors do not fail this review') -const noCurrentTest = settle([oldTest], [currentRead]) -assert.ok(!noCurrentTest.ticket.evidence!.some((item) => item.kind === 'test'), 'old passing tests are not new verification') +const noCurrentTest = await scenario([oldTest], [currentRead]) +assert.ok(!noCurrentTest.ticket.evidence!.some((item) => item.kind === 'test')) assert.deepEqual(noCurrentTest.ticket.execution!.checks, []) -const changed = settle([], [{ ...oldDiff, id: 'current-diff' }, currentTest]) -assert.ok(changed.ticket.evidence!.some((item) => item.kind === 'diff'), 'current reviewer changes remain recorded') -assert.equal(ticketReviewGateState(changed.ticket).hasReviewOrSkipAfterBuilder, false, 'reviewer-made changes still need independent review') +const changed = await scenario([], [{ ...oldDiff, id: 'current-diff' }, currentTest]) +assert.ok(changed.ticket.evidence!.some((item) => item.kind === 'diff')) +assert.equal(ticketReviewGateState(changed.ticket).hasReviewOrSkipAfterBuilder, false, 'reviewer-made changes need independent review') -const failed = settle([], [{ id: 'current-error', kind: 'error', text: 'This review failed.' } as TimelineItem]) +const failed = await scenario([], [{ id: 'current-error', kind: 'error', text: 'This review failed.' } as TimelineItem], { rewrite: 'replace' }) assert.equal(failed.ticket.status, 'needs_clarification') assert.equal(failed.outcome, 'failed') assert.ok(failed.ticket.evidence!.some((item) => item.kind === 'review' && item.summary.includes('blocked'))) -const rebuilt = settle([oldDiff, oldTest, { id: 'old-error', kind: 'error', text: 'Previous run failed.' } as TimelineItem], [currentRead], 'build') -assert.equal(rebuilt.ticket.status, 'review', 'a clean rebuild is not failed by an older run') + +const rebuilt = await scenario([oldDiff, oldTest], [currentRead], { phase: 'build' }) +assert.equal(rebuilt.ticket.status, 'review') assert.equal(rebuilt.outcome, 'completed') -assert.ok(!rebuilt.ticket.evidence!.some((item) => item.kind === 'test' || item.kind === 'diff'), 'a rebuild only records its own output') -if (capture) assert.ok(source.indexOf('const timelineBaseline = ') < source.indexOf('thread.timeline.push(userItem)'), 'the boundary is frozen before this run appends events') -console.log('ticket worker evidence: 6 production-settlement scenarios passed') +assert.ok(!rebuilt.ticket.evidence!.some((item) => item.kind === 'test' || item.kind === 'diff')) + +const interrupted = await scenario([oldTest], [currentRead], { interrupted: true }) +assert.equal(interrupted.ticket.status, 'in_progress') +assert.equal(interrupted.ticket.runState, null) +assert.equal(interrupted.outcome, 'paused') +console.log(`ticket worker evidence: ${passed} exported-runtime scenarios passed`) diff --git a/app/electron/main/host/ticket-worker-runtime.ts b/app/electron/main/host/ticket-worker-runtime.ts index ec0f72e9233..b0c6c5fbb2b 100644 --- a/app/electron/main/host/ticket-worker-runtime.ts +++ b/app/electron/main/host/ticket-worker-runtime.ts @@ -63,6 +63,9 @@ export async function awaitTicketStartupStep(pending: Promise, revalidate: } interface TicketWorkerRuntimeDeps { + runAgent?: typeof runAgent + resolveWorkspaceCwd?: typeof resolveWorkspaceCwd + inspectGitRepository?: typeof inspectGitRepository persistThreads(): void persistTickets(): void emitTicket(ticket: Ticket): void @@ -92,6 +95,9 @@ interface TicketWorkerRuntimeDeps { export function createTicketWorkerRuntime(deps: TicketWorkerRuntimeDeps): TicketWorkerRuntime { const { + runAgent: executeAgent = runAgent, + resolveWorkspaceCwd: resolveWorkerCwd = resolveWorkspaceCwd, + inspectGitRepository: inspectWorkerGit = inspectGitRepository, persistThreads, persistTickets, emitTicket, @@ -178,12 +184,12 @@ async function startTicketWork(input: TicketWorkerInput): Promise { : await runtimeProviderWithFreshModels(routeBaseProvider, providerAccountId) let model = resolvedRoute.model assertProviderEndpoint(provider) - const cwd = await resolveWorkspaceCwd(roomWorkspace || project?.cwd || store.settings.defaultCwd, 'ticket workspace') + const cwd = await resolveWorkerCwd(roomWorkspace || project?.cwd || store.settings.defaultCwd, 'ticket workspace') assertActiveTicketWorkOwnership(ticket, project, room, existingThread) const executionBranch = await awaitTicketStartupStep( - inspectGitRepository(cwd, 'ticket workspace').then((repo) => repo.branch).catch(() => null), + inspectWorkerGit(cwd, 'ticket workspace').then((repo) => repo.branch).catch(() => null), () => assertActiveTicketWorkOwnership(ticket, project, room, existingThread), ) @@ -211,7 +217,8 @@ async function startTicketWork(input: TicketWorkerInput): Promise { store.threads.unshift(thread); persistThreads() sendToRenderer('thread:update', thread) } - const timelineBaseline = thread.timeline.length + const previousItemIds = new Set(thread.timeline.map((item) => item.id)) + const runItems = new Map() ticket.threadId = thread.id ticket.status = 'in_progress' ticket.runState = 'running' @@ -265,7 +272,21 @@ async function startTicketWork(input: TicketWorkerInput): Promise { emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: userItem }) const t = thread - const emit = (e: AgentEvent) => { applyEventToThread(t, e); emitToRenderer(e) } + const emit = (e: AgentEvent) => { + applyEventToThread(t, e) + if (e.threadId === t.id && e.type === 'item_add' && !previousItemIds.has(e.item.id)) { + runItems.set(e.item.id, t.timeline.find((item) => item.id === e.item.id) ?? structuredClone(e.item)) + } else if (e.threadId === t.id && (e.type === 'item_update' || e.type === 'item_delta')) { + const owned = runItems.get(e.id) + if (owned) { + const live = t.timeline.find((item) => item.id === e.id) + if (live) runItems.set(e.id, live) + else if (e.type === 'item_update') Object.assign(owned, structuredClone(e.patch)) + else owned[e.field] = (owned[e.field] ?? '') + e.chunk + } + } + emitToRenderer(e) + } t.cwd = cwd t.providerId = baseProvider.id t.providerAccountId = providerAccountId @@ -302,7 +323,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { fullToolContext({ thread: t, provider: route.provider, model: route.model, signal: controller.signal }), allowedCapabilities, ) - await runAgent({ + await executeAgent({ responseLocale: selectedResponseLocale(store.settings.uiPreferences), thread: t, provider: route.provider, @@ -397,7 +418,7 @@ async function startTicketWork(input: TicketWorkerInput): Promise { markUndrainedCues(t, controller.signal.aborted ? 'canceled' : 'run ended') aborters.delete(t.id) runLease.release() - const runTimeline = t.timeline.slice(timelineBaseline) + const runTimeline = [...runItems.values()] const failed = runTimeline.some((i) => i.kind === 'error') const interrupted = controller.signal.aborted t.status = failed ? 'error' : 'idle'; t.updatedAt = Date.now() From 2103a02c629ff1980fd02648830e738875841518 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:14:00 +0000 Subject: [PATCH 015/158] changelog: #3484 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3514af7915e..3a92b364bb1 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 +- Desktop: a ticket can finalize only after a current independent review of its actual builder work; reviewer blockers stay with their batch and ordinary later notes no longer revoke approval (#3484). Thanks to @AIFlowML. + - Metal: Ling-3.0-tiny's MLA layers run on Kimi's `k3_mla` kernels with three added kernels for cache and query RoPE and gate widening, registered with planted controls in the kernel contract (#3609). Thanks to @ThinkOffApp. - Nemotron: the Living Weights copies left behind by the October revert are deleted and `cuda_pages` imports `living.lesson_route`, leaving one copy of the learner, pocket and lesson files (#3707). Thanks to @jschmied. From e19b2d19619919e0cbf468150867ac93c6f8688e Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:29:55 +0700 Subject: [PATCH 016/158] Use the native Qwen3.5-2B tap count in Desktop --- app/electron/agent/engine/geometry.ts | 2 +- app/electron/agent/engine/library.test.ts | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/app/electron/agent/engine/geometry.ts b/app/electron/agent/engine/geometry.ts index 7c8a95d2de1..a03b49bfc8b 100644 --- a/app/electron/agent/engine/geometry.ts +++ b/app/electron/agent/engine/geometry.ts @@ -32,7 +32,7 @@ const QWEN35: PinnedGeometry = { linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, - linear_conv_kernel_dim: 6144, + linear_conv_kernel_dim: 4, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, diff --git a/app/electron/agent/engine/library.test.ts b/app/electron/agent/engine/library.test.ts index 11027af03c5..940c2b70a4b 100644 --- a/app/electron/agent/engine/library.test.ts +++ b/app/electron/agent/engine/library.test.ts @@ -85,7 +85,23 @@ try { await fs.writeFile(path.join(wrongGeometry, 'config.json'), JSON.stringify({ model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 }, max_position_embeddings: 32768, text_config: { hidden_size: 1024, num_hidden_layers: 24, vocab_size: 151936 } })) const servedGeometry = path.join(modelsDir, 'served-geometry') await checkpoint(servedGeometry) - await fs.writeFile(path.join(servedGeometry, 'config.json'), JSON.stringify({ model_type: 'qwen3_5', quantization: { bits: 4, group_size: 64 }, max_position_embeddings: 32768, text_config: { hidden_size: 2048, num_hidden_layers: 24, vocab_size: 248320, intermediate_size: 6144, linear_num_key_heads: 16, linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, linear_conv_kernel_dim: 6144, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, full_attention_interval: 4 } })) + const servedConfig = { + model_type: 'qwen3_5', + quantization: { bits: 4, group_size: 64 }, + max_position_embeddings: 32768, + text_config: { + hidden_size: 2048, num_hidden_layers: 24, vocab_size: 248320, intermediate_size: 6144, + linear_num_key_heads: 16, linear_num_value_heads: 16, linear_key_head_dim: 128, linear_value_head_dim: 128, + linear_conv_kernel_dim: 4, num_attention_heads: 8, num_key_value_heads: 2, head_dim: 256, full_attention_interval: 4, + }, + } + await fs.writeFile(path.join(servedGeometry, 'config.json'), JSON.stringify(servedConfig)) + const wrongConvolution = path.join(modelsDir, 'wrong-convolution') + await checkpoint(wrongConvolution) + await fs.writeFile(path.join(wrongConvolution, 'config.json'), JSON.stringify({ + ...servedConfig, + text_config: { ...servedConfig.text_config, linear_conv_kernel_dim: 6144 }, + })) const incomplete = path.join(modelsDir, 'incomplete') await checkpoint(incomplete) await fs.writeFile(path.join(incomplete, 'model.safetensors.index.json'), JSON.stringify({ weight_map: { a: 'model-00001-of-00002.safetensors', b: 'model-00002-of-00002.safetensors' } })) @@ -111,6 +127,10 @@ try { assert.match(refused.reason!, /hidden size is 1024/) assert.match(refused.reason!, /UnsupportedQwenGeometry/) assert.equal(selected.models.find((model) => model.path === servedGeometry)?.loadable, true, 'the geometry the engine serves stays offered') + const refusedConvolution = selected.models.find((model) => model.path === wrongConvolution)! + assert.equal(refusedConvolution.complete, true) + assert.equal(refusedConvolution.loadable, false) + assert.match(refusedConvolution.reason!, /linear conv kernel dim is 6144/) assert.equal(selected.models.find((model) => model.path === foreign)?.complete, true) assert.match(selected.models.find((model) => model.path === incomplete)!.reason!, /missing.*shards/) assert.match(selected.models.find((model) => model.path === invalid)!.reason!, /safetensors/) From 898414fb0205303160c113e6e858712c196e5004 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:14:02 +0000 Subject: [PATCH 017/158] changelog: #3768 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a92b364bb1..a3e62d4367e 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 +- Desktop: the library scan uses four convolution taps for Qwen3.5-2B, so the supported checkpoint is offered instead of being refused at scan time; a checkpoint with the old value still gets a geometry refusal (#3768). Thanks to @AIFlowML. + - Desktop: a ticket can finalize only after a current independent review of its actual builder work; reviewer blockers stay with their batch and ordinary later notes no longer revoke approval (#3484). Thanks to @AIFlowML. - Metal: Ling-3.0-tiny's MLA layers run on Kimi's `k3_mla` kernels with three added kernels for cache and query RoPE and gate widening, registered with planted controls in the kernel contract (#3609). Thanks to @ThinkOffApp. From 24909b2d9480a446c93322c1e805962346b681dd Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:37:25 +0700 Subject: [PATCH 018/158] Accept OpenAI base URLs in Web engine settings --- web/tensorfold_web/engine.py | 2 +- web/tensorfold_web/engines.py | 4 +- web/tensorfold_web/replay.py | 2 +- web/tensorfold_web/server.py | 8 ++-- web/tensorfold_web/server_connect.py | 12 +++--- web/tensorfold_web/server_engine.py | 2 +- web/tensorfold_web/server_lessons.py | 3 +- web/tensorfold_web/settings.py | 11 +++++ web/tests/test_engine_base_url.py | 61 ++++++++++++++++++++++++++++ 9 files changed, 90 insertions(+), 15 deletions(-) create mode 100644 web/tests/test_engine_base_url.py diff --git a/web/tensorfold_web/engine.py b/web/tensorfold_web/engine.py index 3cdd0828256..3ec69d3e17b 100644 --- a/web/tensorfold_web/engine.py +++ b/web/tensorfold_web/engine.py @@ -287,7 +287,7 @@ def target(self) -> tuple[int, str, str | None]: """The generation, address and key, read together.""" with self.target_lock: - return self.generation, self.settings.engine_url.rstrip("/"), self.key_in_use() + return self.generation, settings_mod.engine_root(self.settings.engine_url), self.key_in_use() def retargeted(self) -> None: """The address or the key changed (the caller holds ``target_lock``): readings begun before are not used.""" diff --git a/web/tensorfold_web/engines.py b/web/tensorfold_web/engines.py index a9186c3dad7..1fbbf73f946 100644 --- a/web/tensorfold_web/engines.py +++ b/web/tensorfold_web/engines.py @@ -7,7 +7,7 @@ import httpx from . import native -from .settings import Settings +from .settings import Settings, engine_root @dataclass @@ -108,7 +108,7 @@ def _json(client: httpx.Client, url: str, headers: dict) -> dict | None: def identify(url: str, *, key: str | None = None, client: httpx.Client | None = None) -> Endpoint: - base = url.rstrip("/").removesuffix("/v1") + base = engine_root(url) headers = {"Authorization": f"Bearer {key}"} if key else {} own = client or httpx.Client(trust_env=False, timeout=3.0) try: diff --git a/web/tensorfold_web/replay.py b/web/tensorfold_web/replay.py index d238a334934..5461a5cac95 100644 --- a/web/tensorfold_web/replay.py +++ b/web/tensorfold_web/replay.py @@ -52,7 +52,7 @@ def _start(self, cid: str, target: dict) -> dict: if not isinstance(target.get("url"), str) or not target.get("model"): raise ValueError("another engine needs its address and a model") # a user or password in the address would be kept in the replay's title, settings and exports - url = settings_mod._engine_url(target["url"]).removesuffix("/v1") + url = settings_mod.engine_root(settings_mod._engine_url(target["url"])) target = {**target, "url": url} base, key, model, engine = url, target.get("key") or None, target["model"], target.get("label") or url else: diff --git a/web/tensorfold_web/server.py b/web/tensorfold_web/server.py index 32129cc4f42..edf669eafec 100644 --- a/web/tensorfold_web/server.py +++ b/web/tensorfold_web/server.py @@ -96,7 +96,7 @@ def create_app(*, settings: settings_mod.Settings | None = None, engine: Engine dl = Downloads() - proxy = Proxy(lambda: s.engine_url, eng.key_in_use, target=lambda: eng.target()[1:]) + proxy = Proxy(lambda: settings_mod.engine_root(s.engine_url), eng.key_in_use, target=lambda: eng.target()[1:]) def bench_target() -> tuple[str, str | None, str | None]: h = eng.status() @@ -104,7 +104,7 @@ def bench_target() -> tuple[str, str | None, str | None]: if h.status == "running": # a bare /health behind a key names no model: /v1/models does model = h.model or next(iter(engines.identify(s.engine_url, key=eng.key_in_use()).models), None) - return s.engine_url.rstrip("/").removesuffix("/v1"), eng.key_in_use(), model + return settings_mod.engine_root(s.engine_url), eng.key_in_use(), model runner = bench.Bench(bench_store or bench.Store(settings_mod.config_dir() / "bench.sqlite"), bench_target) @@ -410,7 +410,7 @@ def lesson_target() -> living.Target: h = eng.status() if h.status != "running" or not served_copy(): raise RuntimeError("serve a living copy first (Teach, then Serve)") - base = s.engine_url.rstrip("/").removesuffix("/v1") + base = settings_mod.engine_root(s.engine_url) return living.Target(base, eng.key_in_use(), h.model or eng.model or "") # left halfway by a stopped TensorFold Web @@ -470,7 +470,7 @@ def settled(name: str) -> None: def engine_get(path: str) -> httpx.Response: key = eng.key_in_use() - return httpx.get(trust_env=False, url=s.engine_url.rstrip("/").removesuffix("/v1") + path, timeout=10.0, + return httpx.get(trust_env=False, url=settings_mod.engine_root(s.engine_url) + path, timeout=10.0, headers={"Authorization": f"Bearer {key}"} if key else {}) def no_store(resp: Response) -> Response: diff --git a/web/tensorfold_web/server_connect.py b/web/tensorfold_web/server_connect.py index 6b64f6f4c04..be96ef2b60a 100644 --- a/web/tensorfold_web/server_connect.py +++ b/web/tensorfold_web/server_connect.py @@ -20,6 +20,7 @@ connect_ctx, lan_hostname, ) +from .settings import engine_root def install(app, eng, s, token) -> None: @@ -27,7 +28,8 @@ def install(app, eng, s, token) -> None: def connect(where: str = "here", relay: str = ""): h = eng.last_health or eng.health() - c = connect_ctx(s.engine_url, h.model if h else None, share=s.share, api_key=eng.key_in_use()) + root = engine_root(s.engine_url) + c = connect_ctx(root, h.model if h else None, share=s.share, api_key=eng.key_in_use()) if where == "away": u = urlsplit(relay) # a name or address and a port, nothing else: the recipes paste it into a shell @@ -38,10 +40,10 @@ def connect(where: str = "here", relay: str = ""): c = recipes.Ctx(base=base, key=s.api_key or eng.key_in_use() or "YOUR-KEY", model=c.model, docker_base=base, away=True) # asked of the engine itself (on its own address): a coding agent needs a long window, and its recipe says so - window = recipes.served_window(recipes.Ctx(base=s.engine_url.rstrip("/").removesuffix("/v1"), + window = recipes.served_window(recipes.Ctx(base=root, key=eng.key_in_use() or "local", model=c.model)) \ if h and h.status == "running" else None - return {"engine_url": s.engine_url, "share": s.share, + return {"engine_url": root, "share": s.share, "lan_url": f"http://{lan_hostname()}:{s.engine_port()}" if s.share else None, # the key that opens the engine now; a new one waiting for the restart is not copied before it works "api_key": eng.key_in_use(), "key_pending_restart": eng.key_pending_restart(), @@ -62,13 +64,13 @@ def connect_test(body: dict[str, Any]): if h.status != "running": raise HTTPException(409, "no model is being served; start one from Models") model = h.model or next(iter(engines.identify(s.engine_url, key=eng.key_in_use()).models), None) - c = recipes.Ctx(base=s.engine_url.rstrip("/").removesuffix("/v1"), key=eng.key_in_use() or "local", + c = recipes.Ctx(base=engine_root(s.engine_url), key=eng.key_in_use() or "local", model=model or "") return recipes.test(rec, c) @app.get("/api/connect/compose/open-webui") def connect_compose(): h = eng.last_health or eng.health() - c = connect_ctx(s.engine_url, h.model if h else None, share=s.share, api_key=eng.key_in_use()) + c = connect_ctx(engine_root(s.engine_url), h.model if h else None, share=s.share, api_key=eng.key_in_use()) return Response(recipes.compose(c), media_type="text/yaml", headers={"Content-Disposition": 'attachment; filename="docker-compose.yml"'}) diff --git a/web/tensorfold_web/server_engine.py b/web/tensorfold_web/server_engine.py index 8f1ece2e637..155adb80954 100644 --- a/web/tensorfold_web/server_engine.py +++ b/web/tensorfold_web/server_engine.py @@ -87,7 +87,7 @@ def access(request: Request): open_without_key = None if not engine_local: # does the engine answer anyone, without its key? try: - r = httpx.get(trust_env=False, url=s.engine_url.rstrip("/") + "/v1/models", timeout=2.0) + r = httpx.get(trust_env=False, url=settings_mod.engine_root(s.engine_url) + "/v1/models", timeout=2.0) open_without_key = r.status_code == 200 except httpx.HTTPError: open_without_key = None diff --git a/web/tensorfold_web/server_lessons.py b/web/tensorfold_web/server_lessons.py index 292d6aab35e..020e67e4b5a 100644 --- a/web/tensorfold_web/server_lessons.py +++ b/web/tensorfold_web/server_lessons.py @@ -16,6 +16,7 @@ living_versions, ) from .gate import Busy +from .settings import engine_root def install(app, cat, chore, chore_cancel, chore_lock, copy_name, creating, eng, gate, launch, lesson_target, run_chore, s, served_copy, teacher, wait_running) -> None: @@ -241,7 +242,7 @@ def living_facts(name: str): graph: dict = {} if served_copy() == name: try: - r = httpx.get(trust_env=False, url=s.engine_url.rstrip("/").removesuffix("/v1") + "/v1/slide/graph", timeout=5.0, + r = httpx.get(trust_env=False, url=engine_root(s.engine_url) + "/v1/slide/graph", timeout=5.0, headers={"Authorization": f"Bearer {eng.key_in_use()}"} if eng.key_in_use() else {}) graph = r.json() if r.status_code == 200 else {} except (httpx.HTTPError, ValueError): diff --git a/web/tensorfold_web/settings.py b/web/tensorfold_web/settings.py index 979185d6cbc..9024acc9eb0 100644 --- a/web/tensorfold_web/settings.py +++ b/web/tensorfold_web/settings.py @@ -23,6 +23,17 @@ def config_dir() -> Path: return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "tensorfold-web" +def engine_root(url: str) -> str: + """Accept an OpenAI API base URL while keeping the server's reverse-proxy prefix.""" + + with contextlib.suppress(ValueError): + parts = urlsplit(url) + path = parts.path.rstrip("/") + if parts.scheme in ("http", "https") and parts.netloc and path.endswith("/v1"): + return parts._replace(path=path.removesuffix("/v1")).geturl() + return url.rstrip("/") + + @dataclass class Settings: engine_url: str = DEFAULT_ENGINE diff --git a/web/tests/test_engine_base_url.py b/web/tests/test_engine_base_url.py new file mode 100644 index 00000000000..c83d9093301 --- /dev/null +++ b/web/tests/test_engine_base_url.py @@ -0,0 +1,61 @@ +import json + +import httpx +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from tensorfold_web import engine, gate, recipes, server_connect, server_settings, settings + + +@pytest.mark.parametrize("source", ["settings-api", "saved-on-disk"]) +@pytest.mark.parametrize(("address", "prefix"), [ + ("http://fixture.test/proxy", "/proxy"), + ("http://fixture.test/proxy/v1/", "/proxy"), + ("http://fixture.test/proxy/v1/v1", "/proxy/v1"), +]) +def test_compatible_engine_address_may_end_in_v1(tmp_path, monkeypatch, source, address, prefix): + def respond(request): + if request.url.path == prefix + "/health": + return httpx.Response(200, json={"status": "ok"}) + if request.url.path == prefix + "/v1/models": + return httpx.Response(200, json={"data": [{"id": "fixture"}]}) + return httpx.Response(404) + + monkeypatch.setattr(settings, "config_dir", lambda: tmp_path) + if source == "saved-on-disk": + settings.path().write_text(json.dumps({"engine_url": address, "remote": True})) + cfg = settings.load() + eng = engine.Engine(cfg) + eng._client.close() + eng._client = httpx.Client(transport=httpx.MockTransport(respond)) + try: + monkeypatch.setattr(recipes, "served_window", lambda _: None) + app = FastAPI() + server_settings.install(app, eng, gate.Gate(), cfg, lambda: settings.save(cfg), cfg.to_dict) + server_connect.install(app, eng, cfg, None) + with TestClient(app) as client: + if source == "settings-api": + saved = client.put("/api/settings", json={"engine_url": address, "remote": True}) + assert saved.status_code == 200 + assert settings.load().engine_url == (address.rstrip("/") if source == "settings-api" else address) + health = eng.health() + connect = client.get("/api/connect").json() + root = "http://fixture.test" + prefix + assert connect["engine_url"] == root + jan = next(r for r in connect["snippets"] if r["id"] == "jan") + assert (health.status, health.model, jan["snippet"].splitlines()[1]) == ( + "running", "fixture", "Base URL " + root + "/v1" + ) + finally: + eng._client.close() + + +@pytest.mark.parametrize(("address", "expected"), [ + ("http://v1", "http://v1"), + ("http://v1/v1/", "http://v1"), + ("https://fixture.test/proxy/v10", "https://fixture.test/proxy/v10"), + ("https://[::1]:8080/proxy/v1", "https://[::1]:8080/proxy"), +]) +def test_engine_url_normalizes_the_api_path_without_changing_the_authority(address, expected): + assert settings.engine_root(address) == expected From f669233c3b9056caf2ac623a89cd21d411332c21 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:14:04 +0000 Subject: [PATCH 019/158] changelog: #3831 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3e62d4367e..7752ee2a819 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 +- Web: the engine address may be an OpenAI base URL ending in `/v1` as well as a server root; health, the relay and Connect derive the server root with `engine_root` and append the API suffix once, and settings keeps the supplied address so a reverse-proxy prefix ending in `/v1` survives a reload (#3831, fixes #3830). Thanks to @AIFlowML. + - Desktop: the library scan uses four convolution taps for Qwen3.5-2B, so the supported checkpoint is offered instead of being refused at scan time; a checkpoint with the old value still gets a geometry refusal (#3768). Thanks to @AIFlowML. - Desktop: a ticket can finalize only after a current independent review of its actual builder work; reviewer blockers stay with their batch and ordinary later notes no longer revoke approval (#3484). Thanks to @AIFlowML. From 96480a07128c61f56f1a842063379f4c8a72966d Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:03:31 +0700 Subject: [PATCH 020/158] Keep Desktop export actions tied to the current preview --- app/src/components/ExportPanel.test.tsx | 129 ++++++++++++++++++++++++ app/src/components/ExportPanel.tsx | 75 +++++++++----- 2 files changed, 177 insertions(+), 27 deletions(-) create mode 100644 app/src/components/ExportPanel.test.tsx diff --git a/app/src/components/ExportPanel.test.tsx b/app/src/components/ExportPanel.test.tsx new file mode 100644 index 00000000000..c94f52d734b --- /dev/null +++ b/app/src/components/ExportPanel.test.tsx @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict' +import { find, harness, jsx, load, settle, text } from './reading/reading-test-harness' + +type Request = { threadId: string; options: { mode: string; redact: boolean } } +const hook = harness() +hook.hooks.useCallback = (callback: unknown) => hook.hooks.useRef(callback).current +const builds: (Request & { finish: (label: string) => void; fail: () => void })[] = [] +const saves: (Request & { finish: () => void })[] = [] +const copies: { json: string; finish: () => void }[] = [] +const windowFixture = new EventTarget() +Object.defineProperty(globalThis, 'window', { configurable: true, value: windowFixture }) +Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { + clipboard: { writeText: (json: string) => new Promise((finish) => copies.push({ json, finish })) }, +} }) + +const api = { + buildExport: (threadId: string, options: Request['options']) => new Promise((resolve, reject) => { + builds.push({ + threadId, + options, + finish: (label) => resolve({ json: label, bundle: { + thread: { title: label }, + stats: { messages: 0, toolCalls: 0, diffs: 0, denied: 0, errors: 0 }, + redactionReport: [], + } }), + fail: () => reject(new Error('synthetic build failure')), + }) + }), + saveExport: (threadId: string, options: Request['options']) => new Promise((resolve) => { + saves.push({ threadId, options, finish: () => resolve({ saved: true }) }) + }), +} +const { ExportPanel } = load('src/components/ExportPanel.tsx', { + react: hook.hooks, 'react/jsx-runtime': jsx, + clsx: (...classes: string[]) => classes.filter(Boolean).join(' '), + '../lib/ipc': { api }, '../lib/icons': { Icon: () => null }, +}) +const render = () => hook.render(() => ExportPanel()) +const open = () => windowFixture.dispatchEvent(new CustomEvent('vontra:export', { detail: { threadId: 'test-run' } })) +const button = (tree: ReturnType, label: string) => find(tree, (node) => node.type === 'button' && text(node) === label) +const setRedact = (checked: boolean) => find(render(), (node) => node.type === 'input').props.onChange({ target: { checked } }) +const preview = (tree: ReturnType) => text(find(tree, (node) => node.type === 'pre')) +const assertUnavailable = (tree: ReturnType) => { + assert.equal(button(tree, 'Copy JSON').props.disabled, true) + assert.equal(button(tree, 'Save…').props.disabled, true) +} + +render() +hook.flush() +open() +render() +hook.flush() +builds[0].finish('first preview') +await settle() +const ready = render() +assert.equal(preview(ready), 'first preview') +assert.equal(button(ready, 'Copy JSON').props.disabled, false) +assert.equal(button(ready, 'Save…').props.disabled, false) +const copy = button(ready, 'Copy JSON').props.onClick +const save = button(ready, 'Save…').props.onClick +const copying = copy() +const saving = save() +assert.equal(copies[0].json, 'first preview') +assert.deepEqual(saves[0].options, { mode: 'full', redact: true }) + +setRedact(false) +const staleCopy = copy() +const staleSave = save() +const pending = render() +assert.equal(preview(pending), 'Building…') +assert.equal(text(pending).includes('first preview'), false) +assertUnavailable(pending) +await Promise.all([staleCopy, staleSave]) +assert.equal(copies.length, 1) +assert.equal(saves.length, 1) +hook.flush() +assert.deepEqual(builds[1].options, { mode: 'full', redact: false }) +setRedact(true) +render() +hook.flush() +assert.deepEqual(builds[2].options, { mode: 'full', redact: true }) +copies[0].finish() +saves[0].finish() +await Promise.all([copying, saving]) +assert.equal(text(render()).includes('Saved'), false) +assertUnavailable(render()) +builds[2].finish('replacement preview') +await settle() +builds[1].fail() +await settle() +assert.equal(preview(render()), 'replacement preview') + +button(render(), 'Share packet').props.onClick() +render() +hook.flush() +assert.deepEqual(builds[3].options, { mode: 'share', redact: true }) +builds[3].fail() +await settle() +assert.equal(preview(render()), 'Nothing to export.') +assertUnavailable(render()) +button(render(), 'Full run').props.onClick() +render() +hook.flush() +button(render(), 'esc').props.onClick() +assert.equal(render(), null) +hook.flush() +open() +assertUnavailable(render()) +hook.flush() +assert.equal(builds[5].threadId, 'test-run') +builds[4].finish('closed preview') +await settle() +assert.equal(preview(render()), 'Building…') +assertUnavailable(render()) +builds[5].finish('reopened preview') +await settle() +const reopened = render() +assert.equal(preview(reopened), 'reopened preview') +const reopenedCopy = button(reopened, 'Copy JSON').props.onClick() +const reopenedSave = button(reopened, 'Save…').props.onClick() +assert.equal(copies[1].json, 'reopened preview') +assert.equal(saves[1].threadId, 'test-run') +assert.deepEqual(saves[1].options, { mode: 'full', redact: true }) +copies[1].finish() +saves[1].finish() +await Promise.all([reopenedCopy, reopenedSave]) +assert.ok(button(render(), 'Copied')) +assert.equal(text(render()).includes('Saved'), true) +hook.cleanup() diff --git a/app/src/components/ExportPanel.tsx b/app/src/components/ExportPanel.tsx index 51111c4e049..5c5e8d154d9 100644 --- a/app/src/components/ExportPanel.tsx +++ b/app/src/components/ExportPanel.tsx @@ -1,7 +1,7 @@ import { useAuthoredText } from '../lib/preferences/useAuthoredText' import { authoredText } from '../lib/preferences/language-packs' import { useStore as useLocaleStore } from '../lib/store' -import { useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import clsx from 'clsx' import { api } from '../lib/ipc' import { Icon, type IconName } from '../lib/icons' @@ -17,40 +17,52 @@ const MODES: { id: ExportMode; label: string; icon: IconName; blurb: string }[] { id: 'eval', get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Eval replay") }, icon: 'spark', blurb: 'Replay skeleton — prompts, tool calls and outcomes only; reasoning dropped, anonymized.' }, ] +type ExportSelection = { threadId: string; mode: ExportMode; redact: boolean } +type ExportPreview = { selection: ExportSelection; result: ExportResult | null } + export function ExportPanel() { const tx = useAuthoredText() - const [threadId, setThreadId] = useState(null) - const [mode, setMode] = useState('full') - const [redact, setRedact] = useState(true) - const [result, setResult] = useState(null) - const [building, setBuilding] = useState(false) + const [selection, setSelection] = useState(null) + const [preview, setPreview] = useState(null) const [saved, setSaved] = useState(null) const [copied, setCopied] = useState(false) - const reqRef = useRef(0) + const selectionRef = useRef(selection) + const choose = useCallback((next: ExportSelection | null) => { + selectionRef.current = next + setSelection(next) + setPreview(null) + setSaved(null) + setCopied(false) + }, []) useEffect(() => { const onOpen = (e: Event) => { const id = (e as CustomEvent).detail?.threadId - if (typeof id !== 'string') return - setThreadId(id); setMode('full'); setRedact(true); setSaved(null); setCopied(false) + if (typeof id !== 'string' || !id) return + choose({ threadId: id, mode: 'full', redact: true }) } window.addEventListener('vontra:export', onOpen as EventListener) return () => window.removeEventListener('vontra:export', onOpen as EventListener) - }, []) + }, [choose]) - // Rebuild the bundle whenever the target or options change (request-id guards races). useEffect(() => { - if (!threadId) { setResult(null); return } - const req = ++reqRef.current - setBuilding(true); setSaved(null); setCopied(false) + if (!selection) return + const { threadId, mode, redact } = selection + let active = true + const finish = (result: ExportResult | null) => { + if (active && selectionRef.current === selection) setPreview({ selection, result }) + } api.buildExport(threadId, { mode, redact }) - .then((r) => { if (req === reqRef.current) setResult(r) }) - .catch(() => { if (req === reqRef.current) setResult(null) }) - .finally(() => { if (req === reqRef.current) setBuilding(false) }) - }, [threadId, mode, redact]) - - if (!threadId) return null - const close = () => setThreadId(null) + .then(finish, () => finish(null)) + return () => { active = false } + }, [selection]) + + if (!selection) return null + const { threadId, mode, redact } = selection + const currentPreview = preview?.selection === selection ? preview : null + const building = currentPreview === null + const result = currentPreview?.result + const close = () => { if (selectionRef.current === selection) choose(null) } const bundle = result?.bundle const totalRedactions = bundle?.redactionReport.reduce((n, r) => n + r.count, 0) ?? 0 const evidence = bundle?.evidence @@ -59,13 +71,18 @@ export function ExportPanel() { : 0 const onCopy = async () => { - if (!result) return - try { await navigator.clipboard.writeText(result.json); setCopied(true); setTimeout(() => setCopied(false), 1600) } catch { /* clipboard blocked */ } + if (!result || selectionRef.current !== selection) return + try { + await navigator.clipboard.writeText(result.json) + if (selectionRef.current !== selection) return + setCopied(true) + setTimeout(() => { if (selectionRef.current === selection) setCopied(false) }, 1600) + } catch { /* clipboard blocked */ } } const onSave = async () => { - if (!threadId) return + if (!result || selectionRef.current !== selection) return const res = await api.saveExport(threadId, { mode, redact }) - if (res.saved) setSaved(res.path ?? 'saved') + if (res.saved && selectionRef.current === selection) setSaved(res.path ?? 'saved') } return ( @@ -86,7 +103,9 @@ export function ExportPanel() { {/* mode picker */}
{MODES.map((m) => ( - ))} @@ -95,7 +114,9 @@ export function ExportPanel() { {/* redaction control */}
diff --git a/app/src/components/bots/BotComposerSettings.test.tsx b/app/src/components/bots/BotComposerSettings.test.tsx index 472b124aacd..2dddba1e72b 100644 --- a/app/src/components/bots/BotComposerSettings.test.tsx +++ b/app/src/components/bots/BotComposerSettings.test.tsx @@ -55,7 +55,7 @@ function productionElement(file: string, tag: string, wrapper?: string) { } const renderThreadComposer = productionElement('../Thread.tsx', 'Composer', 'BotComposerSettings') const provider: Provider = { id: 'fixture', name: 'Fixture', kind: 'local', baseUrl: 'http://127.0.0.1', apiKey: '', models: ['fixture'] } -function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetting) { +function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetting, roomWorkerEffort?: ReasoningEffortSetting) { const thread = { id: 'captured-bot-fixture', bot } function Composer() { return React.createElement(picker.ModelPickerMenu, { @@ -65,10 +65,10 @@ function composer(bot: BotThreadConfig | undefined, effort: ReasoningEffortSetti detail: metadata.effortDisplayLabel(provider, 'fixture', effort), disabled: !!bot, }) } - return renderThreadComposer({ thread, Composer, BotComposerSettings: context.BotComposerSettings }) + return renderThreadComposer({ thread, roomWorkerEffort, Composer, BotComposerSettings: context.BotComposerSettings }) } const bot = (reasoningEffort?: ReasoningEffortSetting) => ({ reasoningEffort } as BotThreadConfig) -const markup = (captured: BotThreadConfig | undefined, global: ReasoningEffortSetting) => renderToStaticMarkup(composer(captured, global)) +const markup = (captured: BotThreadConfig | undefined, global: ReasoningEffortSetting, room?: ReasoningEffortSetting) => renderToStaticMarkup(composer(captured, global, room)) assert.match(markup(bot('low'), 'high'), />Low<\/span>/, 'the real thread/provider/picker wiring displays captured Low, not global High') assert.match(markup(bot('high'), 'low'), />High<\/span>/, 'captured High remains independent of global Low') assert.match(markup(bot(), 'high'), />High<\/span>/, 'a legacy bot without captured effort displays its global fallback') @@ -79,4 +79,7 @@ assert.match(markup(captured, 'medium'), />Low<\/span>/, 'changing the app setti const siblings = renderToStaticMarkup(React.createElement(React.Fragment, null, composer(captured, 'high'), composer(undefined, 'high'))) assert.equal((siblings.match(/>Low<\/span>/g) ?? []).length, 1) assert.equal((siblings.match(/>High<\/span>/g) ?? []).length, 1, 'a captured value cannot leak into an adjacent ordinary composer') +assert.match(markup(undefined, 'high', 'low'), />Low<\/span>/, 'the real worker composer displays captured Low instead of app High') +assert.match(markup(undefined, 'low', 'high'), />High<\/span>/, 'captured Room effort stays independent from app Low') +assert.match(markup(undefined, 'high'), />High<\/span>/, 'a completed worker returns to the ordinary app fallback') console.log('Bot composer checks passed: captured/legacy/global badges, actual parent wiring and sibling isolation.') diff --git a/app/src/components/bots/BotComposerSettings.tsx b/app/src/components/bots/BotComposerSettings.tsx index 0773efefeaa..bb77ae0eb8a 100644 --- a/app/src/components/bots/BotComposerSettings.tsx +++ b/app/src/components/bots/BotComposerSettings.tsx @@ -1,9 +1,10 @@ import { createContext, useContext, type ReactNode } from 'react' import type { BotThreadConfig } from '../../lib/types' -const BotComposerContext = createContext(undefined) +type CapturedComposerSettings = Pick +const BotComposerContext = createContext(undefined) -export function BotComposerSettings({ bot, children }: { bot?: BotThreadConfig; children: ReactNode }) { +export function BotComposerSettings({ bot, children }: { bot?: CapturedComposerSettings; children: ReactNode }) { return {children} } diff --git a/app/src/components/bots/BotReasoningEffort.test.tsx b/app/src/components/bots/BotReasoningEffort.test.tsx index 511d986e5bd..c1e66982748 100644 --- a/app/src/components/bots/BotReasoningEffort.test.tsx +++ b/app/src/components/bots/BotReasoningEffort.test.tsx @@ -7,18 +7,23 @@ import ts from 'typescript' import * as metadata from '../../lib/provider-model-metadata' import type { Provider } from '../../lib/types' -const source = readFileSync(new URL('./BotReasoningEffort.tsx', import.meta.url), 'utf8') -const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } }).outputText const jsx = (type: any, props: any, key: any) => React.createElement(type, { ...props, ...(key == null ? {} : { key }) }) -const imports: Record = { 'react/jsx-runtime': { jsx, jsxs: jsx }, '../../lib/provider-model-metadata': metadata } -const module = { exports: {} as any } -new Function('require', 'module', 'exports', output)((id: string) => { - const reviewed = reviewedLanguageImport(id, imports) - if (reviewed.matched) return reviewed.value - assert.ok(id in imports, `Reviewed component import ${id}`) - return imports[id] -}, module, module.exports) -const { BotReasoningEffort, effortForBotModel } = module.exports +function load(file: string, imports: Record) { + const source = readFileSync(new URL(file, import.meta.url), 'utf8') + const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } }).outputText + const module = { exports: {} as any } + new Function('require', 'module', 'exports', output)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed component import ${id}`) + return imports[id] + }, module, module.exports) + return module.exports +} +const control = load('../ReasoningEffortSelect.tsx', { + 'react/jsx-runtime': { jsx, jsxs: jsx }, '../lib/provider-model-metadata': metadata, +}) +const { BotReasoningEffort, effortForBotModel } = load('./BotReasoningEffort.tsx', { '../ReasoningEffortSelect': control }) const gemini: Provider = { id: 'gemini', name: 'Gemini API', kind: 'cloud', baseUrl: 'https://model.example.test/v1', apiKey: '', models: ['gemini-2.5-pro', 'gemini-3-pro'] } const choices = (provider?: Provider, model?: string) => { const tree = BotReasoningEffort({ provider, model, value: 'low', onChange() {} }) @@ -42,4 +47,5 @@ select.props.onChange({ target: { value: 'low' } }) assert.equal(selected, 'low', 'changing the rendered control updates the stored bot parameter') select.props.onChange({ target: { value: '' } }) assert.equal(selected, undefined) +assert.match(renderToStaticMarkup(BotReasoningEffort({ disabled: true, onChange() {} })), / onChange(event.target.value ? event.target.value as ReasoningEffortSetting : undefined)} className="h-10 w-full min-w-0 rounded-lg border border-line bg-card-2 px-2 text-[13px] text-ink"> - - {unavailable && } - {options.map((option) => )} - - -} +export { ReasoningEffortSelect as BotReasoningEffort, effortForModel as effortForBotModel } from '../ReasoningEffortSelect' diff --git a/app/src/components/rooms/RoomAgentsSection.tsx b/app/src/components/rooms/RoomAgentsSection.tsx new file mode 100644 index 00000000000..cfa93cc5d43 --- /dev/null +++ b/app/src/components/rooms/RoomAgentsSection.tsx @@ -0,0 +1,383 @@ +import { useAuthoredText } from '../../lib/preferences/useAuthoredText' +import { authoredText } from '../../lib/preferences/language-packs' +import { useStore as useLocaleStore } from '../../lib/store' +import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react' +import clsx from 'clsx' +import { useStore } from '../../lib/store' +import { basename, relativeTime } from '../../lib/format' +import { Icon, type IconName } from '../../lib/icons' +import { FileGlyph } from '../../lib/fileicon' +import { Button, Input } from '../ui' +import { allowedProviders, projectDefaultModel } from '../../lib/policy' +import { accountLabel, modelDisplayName, providerAccountChoices, providerModelGroups } from '../../lib/provider-accounts' +import { buildRoomAgentTree, type RoomAgentTreeNode } from '../../lib/room-agent-tree' +import type { AgentPreset, AgentRoleProfileId, FanOutBudget, Provider, Room, RoomSeatLane, Seat, Ticket } from '../../lib/types' +import { FAN_OUT_OPTIONS, FILE_TOOL_VERB, ROLE_PROFILES, Avatar, availableSeatName, isActiveRunState, modelChoiceValue, parseModelChoice, pickProvider, seatModelChoice } from './helpers' +import { ReasoningEffortSelect, effortForModel } from '../ReasoningEffortSelect' +import type { ReasoningEffortSetting } from '../../lib/types' + +const AGENT_NODE_STATUS_LABEL: Record = { + get idle() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Idle") }, + get active() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Active") }, + get done() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Done") }, + get failed() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Failed") }, +} + +function AgentStatusDot({ status }: { status: RoomAgentTreeNode['status'] }) { + const tx = useAuthoredText() + return ( + + ) +} + +function RoomAgentDelegates({ node }: { node: RoomAgentTreeNode | undefined }) { + const tx = useAuthoredText() + if (!node?.children.length) return null + return ( +
+
+ + {tx("Delegates")} + {node.children.length} +
+
+ {node.children.map((child) => )} +
+
+ ) +} + +function RoomAgentDelegateRow({ node }: { node: RoomAgentTreeNode }) { + const tx = useAuthoredText() + return ( +
+
+ +
+
+ {node.name} + {node.children.length > 0 && {node.children.length}} + {AGENT_NODE_STATUS_LABEL[node.status]} +
+
{node.detail}
+
+
+ {node.children.length > 0 && ( +
+ {node.children.map((child) => )} +
+ )} +
+ ) +} + +function roomSeatFocus(room: Room, tickets: Ticket[], seat: Seat, node: RoomAgentTreeNode | undefined): { label: string; detail: string; icon: IconName; tone: 'active' | 'blocked' | 'done' | 'idle' } { + const heartbeat = room.seatHeartbeats?.[seat.id] + if (heartbeat?.missedSince) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Stalled") }, detail: `missed heartbeat ${relativeTime(heartbeat.missedSince)}`, icon: 'warning', tone: 'blocked' } + } + + const pendingHandoff = [...room.events].reverse().find((event) => { + if (!(event.kind === 'ask' || event.kind === 'assign') || event.target !== seat.name) return false + return !room.events.some((candidate) => + candidate.createdAt > event.createdAt && + candidate.seat === seat.name && + !['yield', 'notice', 'error'].includes(candidate.kind), + ) + }) + if (pendingHandoff) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Answering handoff") }, detail: `${pendingHandoff.seat} is waiting`, icon: 'message', tone: 'active' } + } + + const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review' || isActiveRunState(t.runState))) + if (claimed) { + const running = isActiveRunState(claimed.runState) + return { label: running ? 'Worker running' : claimed.status === 'review' ? 'Reviewing' : 'Working ticket', detail: claimed.title, icon: running ? 'play' : 'check', tone: 'active' } + } + + if (node?.children.some((child) => child.status === 'active')) { + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Delegated") }, detail: `${node.children.filter((child) => child.status === 'active').length} active delegate${node.children.filter((child) => child.status === 'active').length === 1 ? '' : 's'}`, icon: 'branch', tone: 'active' } + } + + const last = [...room.events].reverse().find((event) => event.seat === seat.name && event.kind !== 'yield') + if (last) { + const label = last.kind === 'tool' ? `Used ${last.tool ?? 'tool'}` : last.kind === 'claim' ? 'Claimed work' : last.kind === 'final' ? 'Concluded' : `${last.kind[0]?.toUpperCase() ?? ''}${last.kind.slice(1)}` + return { label, detail: last.text.replace(/\s+/g, ' ').trim().slice(0, 90), icon: last.kind === 'tool' ? 'grid' : last.kind === 'final' ? 'check' : 'spark', tone: last.kind === 'final' ? 'done' : 'idle' } + } + + return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Available") }, detail: seat.lane ? `${seat.lane} lane` : 'Ready for a handoff', icon: 'clock', tone: 'idle' } +} + +function SeatFocusLine({ focus }: { focus: ReturnType }) { + const tx = useAuthoredText() + return ( +
+ + {focus.label} + {focus.detail} +
+ ) +} + +export function RoomAgentsSection({ + room, + providers, + tickets, + running, + adding, + setAdding, + setSeats, +}: { + room: Room + providers: Provider[] + tickets: Ticket[] + running: boolean + adding: boolean + setAdding: Dispatch> + setSeats: (seats: Seat[]) => void +}) { + const tx = useAuthoredText() + const defaultEffort = useStore((state) => state.settings?.reasoningEffort) + const modelGroups = providers.flatMap((provider) => providerModelGroups(provider).map((group) => ({ provider, group }))) + const agentTree = useMemo(() => buildRoomAgentTree(room), [room, tx]) + const agentTreeBySeat = useMemo(() => new Map(agentTree.map((node) => [node.seatName, node])), [agentTree, tx]) + const updateSeatModel = (seat: Seat, value: string) => { + const picked = parseModelChoice(value) + if (!picked) return + const provider = providers.find((candidate) => candidate.id === picked.providerId) + setSeats(room.seats.map((candidate) => candidate.id === seat.id ? { + ...candidate, ...picked, reasoningEffort: effortForModel(candidate.reasoningEffort, provider, picked.model), + } : candidate)) + } + const removeSeat = (seatId: string) => setSeats(room.seats.filter((seat) => seat.id !== seatId)) + + return ( +
+
+
+
{tx("Room agents")}
+
{tx("Pick the model each local or cloud agent uses.")}
+
+ +
+
+ {room.seats.map((seat) => { + const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review')) + const recentFiles = [...new Set([...room.events].reverse().filter((ev) => ev.seat === seat.name && ev.tool && ev.path && FILE_TOOL_VERB[ev.tool]).map((ev) => ev.path!))].slice(0, 2) + const seatProvider = providers.find((p) => p.id === seat.providerId) + const choiceValue = seatModelChoice(seat, providers) + const treeNode = agentTreeBySeat.get(seat.name) + const focus = roomSeatFocus(room, tickets, seat, treeNode) + return ( +
+
+ +
+
+ {seat.name} + {seat.roleProfileId && {seat.roleProfileId}} +
+
{seat.lane ? `${seat.lane} · ` : ''}{seat.role}
+
+ +
+ + +
+ setSeats(room.seats.map((candidate) => + candidate.id === seat.id ? { ...candidate, reasoningEffort } : candidate))} /> +
+ {seatProvider &&
{seatProvider.name}
} + {claimed &&
{claimed.title}
} + {recentFiles.length > 0 && ( +
+ {recentFiles.map((path) =>
{basename(path)}
)} +
+ )} + +
+ ) + })} + {adding && { setSeats([...room.seats, seat]); setAdding(false) }} onCancel={() => setAdding(false)} />} + {room.seats.length === 0 && !adding &&
{tx("No agents yet. Add one or use the preset below.")}
} +
+
+ ) +} + +function AddSeat({ room, running, onAdd, onCancel }: { room: Room; running: boolean; onAdd: (s: Seat) => void; onCancel: () => void }) { + const tx = useAuthoredText() + const settings = useStore((s) => s.settings)! + const project = useStore((s) => s.projects.find((p) => p.id === room.projectId)) ?? null + const agentPresets = (settings.agentPresets ?? []).filter((preset) => !preset.archivedAt && !preset.paused) + const pickerProviders = allowedProviders(settings.providers, project) + const def = projectDefaultModel(project, settings.providers) + // Name seats after their role (planner, planner-2, …) so the chosen role is + // visible in the name, and suggest a fitting model per role (#47): builders and + // operators run local; planners, reviewers and researchers run on a frontier + // (cloud) model. + const roleSeatName = (base: string) => { + const used = new Set(room.seats.map((s) => s.name.toLowerCase())) + if (!used.has(base.toLowerCase())) return base + for (let i = 2; i < 99; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}` + return base + } + const suggestModelFor = (laneFor: RoomSeatLane) => + pickProvider(pickerProviders, laneFor === 'development' || laneFor === 'operations' ? 'local' : 'cloud', def) + const [roleProfileId, setRoleProfileId] = useState('builder') + const [name, setName] = useState(() => roleSeatName('builder')) + const [nameTouched, setNameTouched] = useState(false) + const [role, setRole] = useState('Engineer') + const [lane, setLane] = useState('development') + const [fanOutBudget, setFanOutBudget] = useState('single') + // Seed the form with the model that fits the default 'builder' role (local). + const initialPick = suggestModelFor('development') + const [providerId, setProviderId] = useState(initialPick.provider?.id || def.providerId || pickerProviders[0]?.id || '') + const provider = pickerProviders.find((p) => p.id === providerId) || pickerProviders[0] + const [providerAccountId, setProviderAccountId] = useState(initialPick.provider ? initialPick.providerAccountId : (project?.defaultProviderAccountId ?? provider?.defaultAccountId ?? null)) + const accountChoices = provider ? providerAccountChoices(provider) : [] + const selectedAccount = accountChoices.find((account) => account.id === (providerAccountId ?? null)) ?? accountChoices[0] + const modelChoices = selectedAccount?.models?.length ? selectedAccount.models : (provider?.models ?? []) + const [model, setModel] = useState(initialPick.model || def.model || modelChoices[0] || '') + const [reasoningEffort, setReasoningEffort] = useState() + const selectedAccountLabel = provider ? accountLabel(provider, providerAccountId) : null + const noAllowedProviders = pickerProviders.length === 0 + const currentModelChoice = provider && model ? modelChoiceValue(provider.id, providerAccountId, model) : '' + + useEffect(() => { + setReasoningEffort((current) => effortForModel(current, provider, model)) + }, [provider, model]) + + useEffect(() => { + if (!provider) return + const account = providerAccountChoices(provider).find((choice) => choice.id === (providerAccountId ?? null)) ?? providerAccountChoices(provider)[0] + if ((providerAccountId ?? null) !== (account?.id ?? null)) setProviderAccountId(account?.id ?? null) + const models = account?.models?.length ? account.models : provider.models + if (models.length && !models.includes(model)) setModel(models[0]) + }, [provider?.id, providerAccountId, model, pickerProviders.length]) // eslint-disable-line + + const add = () => { + if (running || !provider || !model) return + const n = (name.trim() || role.toLowerCase()).replace(/\s+/g, '-') + onAdd({ id: crypto.randomUUID(), name: n, role: role.trim() || 'Agent', lane, roleProfileId, fanOutBudget, providerId: provider.id, providerAccountId: providerAccountId ?? null, model, reasoningEffort }) + } + const pickModel = (value: string) => { + const picked = parseModelChoice(value) + if (!picked) return + setProviderId(picked.providerId) + setProviderAccountId(picked.providerAccountId) + setModel(picked.model) + } + const applyAgentPreset = (presetId: string) => { + const preset = agentPresets.find((candidate) => candidate.id === presetId) + if (!preset) return + setName(availableSeatName(preset.name, room.seats)) + setNameTouched(true) + setRole(preset.role) + setLane(preset.lane) + setProviderId(preset.providerId) + setProviderAccountId(preset.providerAccountId ?? null) + setModel(preset.model) + setReasoningEffort(effortForModel(preset.reasoningEffort, pickerProviders.find((candidate) => candidate.id === preset.providerId), preset.model)) + } + + return ( +
+ {agentPresets.length > 0 && ( + + )} + + { setNameTouched(true); setName(e.target.value) }} placeholder={tx("Name (e.g. architect)")} className="mb-2 h-8" /> + setRole(e.target.value)} placeholder={tx("Role (e.g. Architect)")} className="mb-2 h-8" /> +
+ + +
+ {noAllowedProviders ? ( +
+ {tx("This project is local-only, but no local providers are configured.")}
+ ) : ( +
+ +
{provider?.name}{selectedAccountLabel ? ` · ${selectedAccountLabel}` : ''}
+
+ )} +
+ +
+
+ + +
+
+ ) +} diff --git a/app/src/components/rooms/RoomPanels.tsx b/app/src/components/rooms/RoomPanels.tsx index 4b99d5d7e1a..d9ba0cb7ba1 100644 --- a/app/src/components/rooms/RoomPanels.tsx +++ b/app/src/components/rooms/RoomPanels.tsx @@ -1,44 +1,18 @@ import { useAuthoredText } from '../../lib/preferences/useAuthoredText' -import { authoredText } from '../../lib/preferences/language-packs' -import { useStore as useLocaleStore } from '../../lib/store' -import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react' +import { useState } from 'react' import clsx from 'clsx' -import { useStore } from '../../lib/store' -import { basename, relativeTime } from '../../lib/format' -import { Icon, type IconName } from '../../lib/icons' +import { basename } from '../../lib/format' +import { Icon } from '../../lib/icons' import { FileGlyph } from '../../lib/fileicon' -import { Button, Input } from '../ui' -import { allowedProviders, projectDefaultModel } from '../../lib/policy' -import { accountLabel, modelDisplayName, providerAccountChoices, providerModelGroups } from '../../lib/provider-accounts' -import { buildRoomAgentTree, type RoomAgentTreeNode } from '../../lib/room-agent-tree' -import type { AgentPreset, AgentRoleProfileId, FanOutBudget, Job, Project, Provider, Room, RoomCollaborationMode, RoomEventItem, RoomMode, RoomSeatLane, RoomState, Seat, Ticket } from '../../lib/types' -import { - ACTIVE_ROOM_STATES, - FAN_OUT_OPTIONS, - FILE_TOOL_VERB, - ROLE_PROFILES, - ROOM_COLLABORATION_OPTIONS, - ROOM_MODE_OPTIONS, - ROOM_STATE_LABEL, - Avatar, - availableSeatName, - presetSeats, - seatForRole, - isActiveRunState, - modelChoiceValue, - parseModelChoice, - pickProvider, - roomJobDetail, - roomJobTitle, - roomSupervisorPhase, - seatModelChoice, - ticketFileRefsForDisplay, - ticketPhaseLabel, - ticketStatusLabel, - ticketWorkerLabel, -} from './helpers' +import { Button } from '../ui' +import { allowedProviders } from '../../lib/policy' +import { modelDisplayName } from '../../lib/provider-accounts' +import type { AgentRoleProfileId, Job, Project, Provider, Room, RoomCollaborationMode, RoomEventItem, RoomMode, RoomState, Seat, Ticket } from '../../lib/types' +import { ACTIVE_ROOM_STATES, ROLE_PROFILES, ROOM_COLLABORATION_OPTIONS, ROOM_MODE_OPTIONS, ROOM_STATE_LABEL, Avatar, presetSeats, seatForRole, isActiveRunState, roomJobDetail, roomJobTitle, roomSupervisorPhase, ticketFileRefsForDisplay, ticketPhaseLabel, ticketStatusLabel, ticketWorkerLabel } from './helpers' import type { RoomConflictBlocker } from './helpers' +export { RoomAgentsSection } from './RoomAgentsSection' + export function RoomSupervisorPanel({ room, roomState, @@ -295,212 +269,6 @@ export function RoomStat({ icon, label, value, accent }: { icon: 'cpu' | 'list' ) } -const AGENT_NODE_STATUS_LABEL: Record = { - get idle() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Idle") }, - get active() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Active") }, - get done() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Done") }, - get failed() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Failed") }, -} - -function AgentStatusDot({ status }: { status: RoomAgentTreeNode['status'] }) { - const tx = useAuthoredText() - return ( - - ) -} - -function RoomAgentDelegates({ node }: { node: RoomAgentTreeNode | undefined }) { - const tx = useAuthoredText() - if (!node?.children.length) return null - return ( -
-
- - {tx("Delegates")} - {node.children.length} -
-
- {node.children.map((child) => )} -
-
- ) -} - -function RoomAgentDelegateRow({ node }: { node: RoomAgentTreeNode }) { - const tx = useAuthoredText() - return ( -
-
- -
-
- {node.name} - {node.children.length > 0 && {node.children.length}} - {AGENT_NODE_STATUS_LABEL[node.status]} -
-
{node.detail}
-
-
- {node.children.length > 0 && ( -
- {node.children.map((child) => )} -
- )} -
- ) -} - -function roomSeatFocus(room: Room, tickets: Ticket[], seat: Seat, node: RoomAgentTreeNode | undefined): { label: string; detail: string; icon: IconName; tone: 'active' | 'blocked' | 'done' | 'idle' } { - const heartbeat = room.seatHeartbeats?.[seat.id] - if (heartbeat?.missedSince) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Stalled") }, detail: `missed heartbeat ${relativeTime(heartbeat.missedSince)}`, icon: 'warning', tone: 'blocked' } - } - - const pendingHandoff = [...room.events].reverse().find((event) => { - if (!(event.kind === 'ask' || event.kind === 'assign') || event.target !== seat.name) return false - return !room.events.some((candidate) => - candidate.createdAt > event.createdAt && - candidate.seat === seat.name && - !['yield', 'notice', 'error'].includes(candidate.kind), - ) - }) - if (pendingHandoff) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Answering handoff") }, detail: `${pendingHandoff.seat} is waiting`, icon: 'message', tone: 'active' } - } - - const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review' || isActiveRunState(t.runState))) - if (claimed) { - const running = isActiveRunState(claimed.runState) - return { label: running ? 'Worker running' : claimed.status === 'review' ? 'Reviewing' : 'Working ticket', detail: claimed.title, icon: running ? 'play' : 'check', tone: 'active' } - } - - if (node?.children.some((child) => child.status === 'active')) { - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Delegated") }, detail: `${node.children.filter((child) => child.status === 'active').length} active delegate${node.children.filter((child) => child.status === 'active').length === 1 ? '' : 's'}`, icon: 'branch', tone: 'active' } - } - - const last = [...room.events].reverse().find((event) => event.seat === seat.name && event.kind !== 'yield') - if (last) { - const label = last.kind === 'tool' ? `Used ${last.tool ?? 'tool'}` : last.kind === 'claim' ? 'Claimed work' : last.kind === 'final' ? 'Concluded' : `${last.kind[0]?.toUpperCase() ?? ''}${last.kind.slice(1)}` - return { label, detail: last.text.replace(/\s+/g, ' ').trim().slice(0, 90), icon: last.kind === 'tool' ? 'grid' : last.kind === 'final' ? 'check' : 'spark', tone: last.kind === 'final' ? 'done' : 'idle' } - } - - return { get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Available") }, detail: seat.lane ? `${seat.lane} lane` : 'Ready for a handoff', icon: 'clock', tone: 'idle' } -} - -function SeatFocusLine({ focus }: { focus: ReturnType }) { - const tx = useAuthoredText() - return ( -
- - {focus.label} - {focus.detail} -
- ) -} - -export function RoomAgentsSection({ - room, - providers, - tickets, - running, - adding, - setAdding, - setSeats, -}: { - room: Room - providers: Provider[] - tickets: Ticket[] - running: boolean - adding: boolean - setAdding: Dispatch> - setSeats: (seats: Seat[]) => void -}) { - const tx = useAuthoredText() - const modelGroups = providers.flatMap((provider) => providerModelGroups(provider).map((group) => ({ provider, group }))) - const agentTree = useMemo(() => buildRoomAgentTree(room), [room, tx]) - const agentTreeBySeat = useMemo(() => new Map(agentTree.map((node) => [node.seatName, node])), [agentTree, tx]) - const updateSeatModel = (seat: Seat, value: string) => { - const picked = parseModelChoice(value) - if (!picked) return - setSeats(room.seats.map((candidate) => candidate.id === seat.id ? { ...candidate, ...picked } : candidate)) - } - const removeSeat = (seatId: string) => setSeats(room.seats.filter((seat) => seat.id !== seatId)) - - return ( -
-
-
-
{tx("Room agents")}
-
{tx("Pick the model each local or cloud agent uses.")}
-
- -
-
- {room.seats.map((seat) => { - const claimed = tickets.find((t) => t.assignee === seat.name && t.projectId === room.projectId && t.roomId === room.id && (t.status === 'in_progress' || t.status === 'review')) - const recentFiles = [...new Set([...room.events].reverse().filter((ev) => ev.seat === seat.name && ev.tool && ev.path && FILE_TOOL_VERB[ev.tool]).map((ev) => ev.path!))].slice(0, 2) - const seatProvider = providers.find((p) => p.id === seat.providerId) - const choiceValue = seatModelChoice(seat, providers) - const treeNode = agentTreeBySeat.get(seat.name) - const focus = roomSeatFocus(room, tickets, seat, treeNode) - return ( -
-
- -
-
- {seat.name} - {seat.roleProfileId && {seat.roleProfileId}} -
-
{seat.lane ? `${seat.lane} · ` : ''}{seat.role}
-
- -
- - - {seatProvider &&
{seatProvider.name}
} - {claimed &&
{claimed.title}
} - {recentFiles.length > 0 && ( -
- {recentFiles.map((path) =>
{basename(path)}
)} -
- )} - -
- ) - })} - {adding && { setSeats([...room.seats, seat]); setAdding(false) }} onCancel={() => setAdding(false)} />} - {room.seats.length === 0 && !adding &&
{tx("No agents yet. Add one or use the preset below.")}
} -
-
- ) -} - // #52/#54 — the center "build your room" canvas. Drag a role into the room (or // click) to add an agent with a fitting model, then pick how they collaborate. // Shown before the huddle has a transcript, so room-building happens in the @@ -602,142 +370,3 @@ export function RoomCanvas({ room, providers, project, onSetSeats, onSetCollabor ) } - -function AddSeat({ room, onAdd, onCancel }: { room: Room; onAdd: (s: Seat) => void; onCancel: () => void }) { - const tx = useAuthoredText() - const settings = useStore((s) => s.settings)! - const project = useStore((s) => s.projects.find((p) => p.id === room.projectId)) ?? null - const agentPresets = (settings.agentPresets ?? []).filter((preset) => !preset.archivedAt && !preset.paused) - const pickerProviders = allowedProviders(settings.providers, project) - const def = projectDefaultModel(project, settings.providers) - // Name seats after their role (planner, planner-2, …) so the chosen role is - // visible in the name, and suggest a fitting model per role (#47): builders and - // operators run local; planners, reviewers and researchers run on a frontier - // (cloud) model. - const roleSeatName = (base: string) => { - const used = new Set(room.seats.map((s) => s.name.toLowerCase())) - if (!used.has(base.toLowerCase())) return base - for (let i = 2; i < 99; i++) if (!used.has(`${base}-${i}`)) return `${base}-${i}` - return base - } - const suggestModelFor = (laneFor: RoomSeatLane) => - pickProvider(pickerProviders, laneFor === 'development' || laneFor === 'operations' ? 'local' : 'cloud', def) - const [roleProfileId, setRoleProfileId] = useState('builder') - const [name, setName] = useState(() => roleSeatName('builder')) - const [nameTouched, setNameTouched] = useState(false) - const [role, setRole] = useState('Engineer') - const [lane, setLane] = useState('development') - const [fanOutBudget, setFanOutBudget] = useState('single') - // Seed the form with the model that fits the default 'builder' role (local). - const initialPick = suggestModelFor('development') - const [providerId, setProviderId] = useState(initialPick.provider?.id || def.providerId || pickerProviders[0]?.id || '') - const provider = pickerProviders.find((p) => p.id === providerId) || pickerProviders[0] - const [providerAccountId, setProviderAccountId] = useState(initialPick.provider ? initialPick.providerAccountId : (project?.defaultProviderAccountId ?? provider?.defaultAccountId ?? null)) - const accountChoices = provider ? providerAccountChoices(provider) : [] - const selectedAccount = accountChoices.find((account) => account.id === (providerAccountId ?? null)) ?? accountChoices[0] - const modelChoices = selectedAccount?.models?.length ? selectedAccount.models : (provider?.models ?? []) - const [model, setModel] = useState(initialPick.model || def.model || modelChoices[0] || '') - const selectedAccountLabel = provider ? accountLabel(provider, providerAccountId) : null - const noAllowedProviders = pickerProviders.length === 0 - const currentModelChoice = provider && model ? modelChoiceValue(provider.id, providerAccountId, model) : '' - - useEffect(() => { - if (!provider) return - const account = providerAccountChoices(provider).find((choice) => choice.id === (providerAccountId ?? null)) ?? providerAccountChoices(provider)[0] - if ((providerAccountId ?? null) !== (account?.id ?? null)) setProviderAccountId(account?.id ?? null) - const models = account?.models?.length ? account.models : provider.models - if (models.length && !models.includes(model)) setModel(models[0]) - }, [provider?.id, providerAccountId, model, pickerProviders.length]) // eslint-disable-line - - const add = () => { - if (!provider || !model) return - const n = (name.trim() || role.toLowerCase()).replace(/\s+/g, '-') - onAdd({ id: crypto.randomUUID(), name: n, role: role.trim() || 'Agent', lane, roleProfileId, fanOutBudget, providerId: provider.id, providerAccountId: providerAccountId ?? null, model }) - } - const pickModel = (value: string) => { - const picked = parseModelChoice(value) - if (!picked) return - setProviderId(picked.providerId) - setProviderAccountId(picked.providerAccountId) - setModel(picked.model) - } - const applyAgentPreset = (presetId: string) => { - const preset = agentPresets.find((candidate) => candidate.id === presetId) - if (!preset) return - setName(availableSeatName(preset.name, room.seats)) - setNameTouched(true) - setRole(preset.role) - setLane(preset.lane) - setProviderId(preset.providerId) - setProviderAccountId(preset.providerAccountId ?? null) - setModel(preset.model) - } - - return ( -
- {agentPresets.length > 0 && ( - - )} - - { setNameTouched(true); setName(e.target.value) }} placeholder={tx("Name (e.g. architect)")} className="mb-2 h-8" /> - setRole(e.target.value)} placeholder={tx("Role (e.g. Architect)")} className="mb-2 h-8" /> -
- - -
- {noAllowedProviders ? ( -
- {tx("This project is local-only, but no local providers are configured.")}
- ) : ( -
- -
{provider?.name}{selectedAccountLabel ? ` · ${selectedAccountLabel}` : ''}
-
- )} -
- - -
-
- ) -} diff --git a/app/src/lib/room-worker-effort.test.ts b/app/src/lib/room-worker-effort.test.ts new file mode 100644 index 00000000000..8f0721b7d64 --- /dev/null +++ b/app/src/lib/room-worker-effort.test.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict' +import { activeRoomWorkerEffort } from './room-worker-effort' +import type { Ticket } from './types' + +const ticket: Ticket = { + id: 'ticket', projectId: 'project', title: 'Synthetic work', body: '', type: 'task', status: 'in_progress', + priority: 'medium', effort: 'small', tags: [], parentId: null, assignee: 'Builder', threadId: 'worker', + runState: 'running', order: 1, createdAt: 1, updatedAt: 1, + execution: { target: 'room', threadId: 'worker', reasoningEffort: 'low', startedAt: 1, finishedAt: null, + checks: [], blockers: [], reviewVerdict: null }, +} +assert.equal(activeRoomWorkerEffort([ticket], 'worker'), 'low') +assert.equal(activeRoomWorkerEffort([ticket], 'other-thread'), undefined, 'effort is scoped to the actual thread') +assert.equal(activeRoomWorkerEffort([{ ...ticket, runState: null }], 'worker'), undefined, 'parked runs clear the override') +assert.equal(activeRoomWorkerEffort([{ ...ticket, runState: 'done' }], 'worker'), undefined, 'settled runs restore manual defaults') +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, finishedAt: 2 } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, threadId: 'old-worker' } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, target: 'solo' } }], 'worker'), undefined) +assert.equal(activeRoomWorkerEffort([{ ...ticket, execution: { ...ticket.execution!, reasoningEffort: undefined } }], 'worker'), undefined) +console.log('Room worker effort display checks passed: explicit thread ownership, active lifecycle and legacy/manual fallback.') diff --git a/app/src/lib/room-worker-effort.ts b/app/src/lib/room-worker-effort.ts new file mode 100644 index 00000000000..849b449905c --- /dev/null +++ b/app/src/lib/room-worker-effort.ts @@ -0,0 +1,7 @@ +import type { ReasoningEffortSetting, Ticket } from './types' + +export function activeRoomWorkerEffort(tickets: readonly Ticket[], threadId: string): ReasoningEffortSetting | undefined { + return tickets.find((ticket) => ticket.runState === 'running' && ticket.threadId === threadId + && ticket.execution?.target === 'room' && ticket.execution.threadId === threadId + && ticket.execution.finishedAt === null)?.execution?.reasoningEffort +} From e4758601b7dae8886a17bd9ecc2bbdf0693ce386 Mon Sep 17 00:00:00 2001 From: AIFlow_ML <154863472+AIFlowML@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:23:19 +0700 Subject: [PATCH 141/158] app: pass the Room run snapshot directly to ticket workers Keep worker effort consistent with the Room session even when saved configuration changes during startup. Reuse the typed worker launch contract, extend the real launch regressions, and retain startup guards after the host split. Refs #3328. --- app/electron/main/host/local-delete-archive.test.ts | 9 +++++++-- .../main/host/room-ticket-work-launch.test.ts | 5 ++++- app/electron/main/host/room-tools-runtime.ts | 1 + app/electron/main/host/room-worker-effort.test.ts | 8 +++++--- app/electron/main/host/ticket-worker-runtime.ts | 6 ++++-- app/electron/main/host/workspace-runtime-ipc.ts | 13 +++---------- 6 files changed, 24 insertions(+), 18 deletions(-) diff --git a/app/electron/main/host/local-delete-archive.test.ts b/app/electron/main/host/local-delete-archive.test.ts index 8b722c8b494..28163851077 100644 --- a/app/electron/main/host/local-delete-archive.test.ts +++ b/app/electron/main/host/local-delete-archive.test.ts @@ -108,9 +108,14 @@ assert.match(ticketWorker, /ticket\.archivedAt/, 'ticket worker rejects archived assert.ok(workerStart.lastIndexOf('inspectGitRepository') < workerStart.indexOf('ticket.status ='), 'all Git inspection awaits finish before ticket running state is committed') assert.ok(workerStart.indexOf('runLease.addWorkspaceKeys') < workerStart.indexOf('store.threads.unshift'), 'final-key lease conflicts fail before a new thread is persisted') -const roomStart = workspace.slice(workspace.indexOf('async function startRoomRun'), workspace.indexOf("handle('room:cancel'")) +const roomRuntime = source('./room-run-runtime.ts') +const roomStartAt = roomRuntime.indexOf('async function startRoomRun') +assert.ok(roomStartAt >= 0, 'the production Room startup remains discoverable') +const roomStart = roomRuntime.slice(roomStartAt) assert.match(roomStart, /Local room execution does not support SSH workspaces/, 'local room startup fails closed before SSH paths reach local Git') -assert.ok(roomStart.indexOf('reserveStart') < roomStart.indexOf('ensureRoomWorktree'), 'room startup reserves its workspace before asynchronous worktree setup') +const reservationAt = roomStart.indexOf('reserveRoomStartup(') +const worktreeAt = roomStart.indexOf('ensureRoomWorktree(') +assert.ok(reservationAt >= 0 && worktreeAt > reservationAt, 'room startup reserves its workspace before asynchronous worktree setup') assert.match(roomStart, /if \(!startupComplete\)[\s\S]*runLease\.release/, 'room prelaunch failures release the startup reservation') const instructionWriter = workspace.slice(workspace.indexOf('async function withProjectInstructionLease'), workspace.indexOf("handle('projects:get'")) diff --git a/app/electron/main/host/room-ticket-work-launch.test.ts b/app/electron/main/host/room-ticket-work-launch.test.ts index c0acc774645..16c7ef4e501 100644 --- a/app/electron/main/host/room-ticket-work-launch.test.ts +++ b/app/electron/main/host/room-ticket-work-launch.test.ts @@ -192,7 +192,8 @@ async function main() { } { - const h = buildHarness({ startTicketWork: async () => ({ id: 'unused' }), beforeWorkspace: () => { + const workerSources: any[] = [] + const h = buildHarness({ startTicketWork: async (input) => { workerSources.push(input.source); return { id: 'worker' } }, beforeWorkspace: () => { h.store.settings.reasoningEffort = 'medium' for (const seat of h.store.rooms[0].seats) seat.reasoningEffort = 'medium' } }) @@ -208,6 +209,8 @@ async function main() { await h.tool('delegate', { task: 'Review synthetic input', targetSeat: 'Legacy' }, 'Builder') assert.deepEqual(h.delegated.map(call => call.reasoningEffort), ['low', 'high', 'xhigh'], 'actual Room delegation captures origin, target and legacy app effort before workspace awaits') + await h.tool('start_ticket_work', { id: 't1', phase: 'build' }, 'Builder') + assert.equal(workerSources[0]?.reasoningEffort, 'low', 'ticket workers inherit the same Room run capture') console.log('ok - actual Room delegation forwards independent captured efforts') } console.log('room ticket work launch tests passed') diff --git a/app/electron/main/host/room-tools-runtime.ts b/app/electron/main/host/room-tools-runtime.ts index 8d357ffc256..6043e85e1ae 100644 --- a/app/electron/main/host/room-tools-runtime.ts +++ b/app/electron/main/host/room-tools-runtime.ts @@ -203,6 +203,7 @@ export function createRoomTools(ctx: WorkspaceRuntimeIpcDeps, runtimeScope: Room source: { roomId: runtimeScope.room.id, seat, + reasoningEffort: runtimeScope.seatEfforts.get(seatConfig.id) ?? runtimeScope.reasoningEffort, onSettled: ({ codeChanged, testsPassed, failed, jobId }) => { if (codeChanged) runtimeScope.lastCodeChangeAt = Date.now() if (testsPassed) runtimeScope.greenEvidenceAt = Date.now() diff --git a/app/electron/main/host/room-worker-effort.test.ts b/app/electron/main/host/room-worker-effort.test.ts index 785f5b1006e..9fd52c25c90 100644 --- a/app/electron/main/host/room-worker-effort.test.ts +++ b/app/electron/main/host/room-worker-effort.test.ts @@ -14,7 +14,8 @@ const code = ts.transpileModule(readFileSync(path.join(__dirname, 'ticket-worker }).outputText const observed: unknown[] = [] const expected: unknown[] = [] -for (const [global, configured] of [['high', 'low'], ['low', 'high'], ['high', undefined]] as const) { +for (const [global, configured, sourceEffort] of [['high', 'low', undefined], ['low', 'high', undefined], + ['high', undefined, undefined], ['high', 'medium', 'low']] as const) { for (const recover of [false, true]) { let releaseWorkspace!: (cwd: string) => void const workspace = new Promise(resolve => { releaseWorkspace = resolve }) @@ -53,6 +54,7 @@ for (const [global, configured] of [['high', 'low'], ['low', 'high'], ['high', u './ticket-helpers': { summarizeTicketWorkerOutcome: () => ({ text: 'Synthetic result', evidence: [], codeChanged: false, testsPassed: false, signals: { commands: [], blockers: [], files: [], diffs: [] } }) }, './workspace-mutation-guard': { lexicalLocalWorkspaceKey }, + './renderer-events': { sendToRenderer() {} }, '../../../shared/reasoning-effort': reasoning, './provider-runtime': { ticketWorkOptionsWithProjectRoute: (_project: any, opts: any) => opts, @@ -92,7 +94,7 @@ for (const [global, configured] of [['high', 'low'], ['low', 'high'], ['high', u applyEventToThread: noop, activeJob: () => null, finishJob: () => finish(), markUndrainedCues: noop, effectiveContextLimit: () => 16_384, }) - const pending = runtime.startTicketWork({ ticketId: ticket.id, source: { roomId: 'room', seat: 'Builder' } }) + const pending = runtime.startTicketWork({ ticketId: ticket.id, source: { roomId: 'room', seat: 'Builder', reasoningEffort: sourceEffort } }) assert.equal(requests.length, 0, 'workspace preparation genuinely pauses the production launch') seat.reasoningEffort = 'medium' store.settings.reasoningEffort = 'medium' @@ -107,7 +109,7 @@ for (const [global, configured] of [['high', 'low'], ['low', 'high'], ['high', u })]) } finally { clearTimeout(timer) } assert.equal(requests.length, recover ? 2 : 1, 'the actual worker executes initial and recovery routes') - const effort = configured ?? global + const effort = sourceEffort ?? configured ?? global observed.push({ global, configured, recover, routes: routeEfforts, requests: requests.map(request => request.reasoningEffort), captured, settled: ticket.execution?.reasoningEffort }) expected.push({ global, configured, recover, routes: Array(recover ? 2 : 1).fill(effort), diff --git a/app/electron/main/host/ticket-worker-runtime.ts b/app/electron/main/host/ticket-worker-runtime.ts index d2173165f83..17334773af1 100644 --- a/app/electron/main/host/ticket-worker-runtime.ts +++ b/app/electron/main/host/ticket-worker-runtime.ts @@ -6,7 +6,7 @@ import { assertProviderEndpoint, auditPreview } from '../../agent/security' import { normalizeTicketCapabilities, settleTicketExecution, startTicketExecution, ticketFileRefs, ticketStateAfterRun, ticketWorkPrompt } from '../../agent/tickets' import { restrictTicketToolContext } from '../../agent/ticket-tool-policy' import type { JobPatch } from '../../agent/jobs' -import type { AgentCue, AgentEvent, Job, Project, Provider, Room, Thread, Ticket, TicketWorkOptions, TimelineItem } from '../../agent/types' +import type { AgentCue, AgentEvent, Job, Project, Provider, ReasoningEffortSetting, Room, Thread, Ticket, TicketWorkOptions, TimelineItem } from '../../agent/types' import { store } from '../state' import { auditEvent, requireSecurityRole } from './audit' import { ensureRoomWorktree } from './room-worktree' @@ -22,6 +22,7 @@ import { sendToRenderer } from './renderer-events' export interface TicketWorkerSource { roomId?: string | null seat?: string | null + reasoningEffort?: ReasoningEffortSetting onSettled?: (summary: { codeChanged: boolean; testsPassed: boolean; failed: boolean; jobId?: string | null }) => void } @@ -143,7 +144,8 @@ async function startTicketWork(input: TicketWorkerInput): Promise { if (existingThread && aborters.has(existingThread.id)) throw new Error('Ticket work is already running.') const roomSeat = input.source?.roomId === room?.id ? room?.seats.find((seat) => seat.name === input.source?.seat) : undefined - const reasoningEffort = captureAgentReasoningEffort(roomSeat, store.settings.reasoningEffort) + const configuredEffort = input.source?.reasoningEffort === undefined ? roomSeat : input.source + const reasoningEffort = captureAgentReasoningEffort(configuredEffort, store.settings.reasoningEffort) const configuredWorkspace = room?.workspace ?? project.workspace ?? null if (configuredWorkspace?.kind === 'ssh') { throw new Error('Local ticket workers do not support SSH workspaces; run this ticket on its remote Orchestrator.') diff --git a/app/electron/main/host/workspace-runtime-ipc.ts b/app/electron/main/host/workspace-runtime-ipc.ts index 3f0b7553b8c..df570176abc 100644 --- a/app/electron/main/host/workspace-runtime-ipc.ts +++ b/app/electron/main/host/workspace-runtime-ipc.ts @@ -1,11 +1,12 @@ import { createRoomRunRuntime } from './room-run-runtime' +import type { TicketWorkerRuntime } from './ticket-worker-runtime' import { reserveRoomStartup, assertLocalTicketGenerationProject, requireActiveRoomForCancel, assertRecordMetadataNotPatched } from './workspace-startup-policy' export { reserveRoomStartup, assertLocalTicketGenerationProject, requireActiveRoomForCancel, assertRecordMetadataNotPatched } from './workspace-startup-policy' import { registerProjectMemoryIpc } from './project-memory-ipc' import type { runRoom as typedRunRoom } from '../../agent/rooms' -import type { Attachment, Job, Project, RemoteControlEvent, Room, RoomManualMemoryCommand, RoomMergeResult, Skill, Ticket, TicketWorkOptions, Thread } from '../../agent/types' +import type { Attachment, Job, Project, RemoteControlEvent, Room, RoomManualMemoryCommand, RoomMergeResult, Skill, Ticket, TicketWorkOptions } from '../../agent/types' import type { store as typedStore } from '../state' import type { handle as typedHandle } from './ipc' import { roomModeDefaults } from '../../agent/room-outcomes' @@ -27,15 +28,7 @@ export interface WorkspaceRuntimeIpc { startRoomRun(roomId: string, problem: string, attachments?: Attachment[]): Promise<{ ok: boolean; room?: Room }> } -type StartTicketWork = (input: { - ticketId: string - opts?: TicketWorkOptions - source?: { - roomId?: string | null - seat?: string | null - onSettled?: (summary: { codeChanged: boolean; testsPassed: boolean; failed: boolean; jobId?: string | null }) => void - } -}) => Promise +type StartTicketWork = TicketWorkerRuntime['startTicketWork'] export interface WorkspaceRuntimeIpcDeps { store: typeof typedStore From 480e0d35f3894e66846564e6dbe9b4b4d6cbc7fd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:55:08 +0000 Subject: [PATCH 142/158] changelog: #3514 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a9c77c6510..c8209934176 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. + - GLM-5.3-Flash on Metal: on Macs without tensor units (before M5), prompt processing uses vectorized GLM-only matmul, KDA and indexer kernels with 32-row matmul tiles; M5 Macs and every other Metal family keep their kernels, and the author's token hashes match main (#3921, refs #3152). Thanks to @gilby. - Changelog: #3125's entry appears once, under 1.2.10; the copy in 1.2.9's section, a release published before #3125 landed, is removed (#3916, refs #3125). Thanks to @Bizuayeu. From 9858e8f6b4adea055b877d65c15caa64aefbeb91 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Sun, 25 Oct 2026 16:30:22 +1100 Subject: [PATCH 143/158] server: replies written as messages to recipients split into reasoning, answer and tool calls A tokenizer with <|start|>, <|message|>, <|eom|> and <|eot|> as single tokens and a chat template that writes to=self messages (Muse Spark Open's) replies as messages to recipients. self is reasoning_content; user, commentary and no recipient are content; any other recipient is a tool call whose block becomes the markup tool_parse and tool_stream already read, so its arguments take the tools' schema types. While a reply streams, an unfinished header, a call message that has not closed and a partial marker are held back, so every split extends the last and the finished split extends them all; the finished reply feeds the call streamer once more, so a last call ended by the end token streams too. Harmony's tokenizers have no <|eom|> or <|eot|>, so gpt-oss replies keep their channel split; tests cover both formats whole and streamed. --- zig/src/server/chat.zig | 3 +- zig/src/server/chat_generation.zig | 7 +- zig/src/server/recipient_reply.zig | 116 +++++++++ zig/src/server/recipient_reply_test.zig | 300 ++++++++++++++++++++++++ zig/src/server/root.zig | 1 + zig/src/server/server.zig | 4 + 6 files changed, 427 insertions(+), 4 deletions(-) create mode 100644 zig/src/server/recipient_reply.zig create mode 100644 zig/src/server/recipient_reply_test.zig diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 8a591e5ddf6..f094a0dcf4b 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -5,6 +5,7 @@ const json = @import("json"); const errors = @import("errors.zig"); const fields_mod = @import("fields.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const tool_stream = @import("tool_stream.zig"); const prompt_mod = @import("prompt.zig"); const images = @import("images.zig"); @@ -275,7 +276,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)) or srv.recipients, .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished const result: Failure!Reply = blk: { diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 3868f69293c..d04ecdd731f 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -4,6 +4,7 @@ const api = @import("engine_api"); const json = @import("json"); const chat = @import("chat.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const tool_stream = @import("tool_stream.zig"); const tool_parse = @import("tool_parse.zig"); const tool_lfm2 = @import("tool_lfm2.zig"); @@ -154,7 +155,7 @@ pub const Generation = struct { if (g.thinking) { const original_close = try g.visible.closeOf(g.a, reply_text.decodeText, g.srv.text, g.srv.close_id); const close = try @import("tool_minimax.zig").closeAfterRewrite(g.a, raw_visible, g.tools, original_close); - const split = try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); + const split = if (g.srv.recipients) try recipient_reply.split(g.a, text, false) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); thought = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it if (thought.len > 0) try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), thought); answer = split.answer; @@ -307,7 +308,7 @@ pub const Generation = struct { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; } else if (g.thinking) { - const split = try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); + const split = if (g.srv.recipients) try recipient_reply.split(a, text, true) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); const r = reply_text.pyStrip(split.reasoning); reasoning = if (r.len > 0) r else null; content = split.answer; @@ -335,7 +336,7 @@ pub const Generation = struct { const final_text = if (g.thinking) content else text; if (std.mem.eql(u8, reason, "length")) { try c.finishCut(final_text, &out); - } else if (close.len > 0 or c.streamed) { + } else if (close.len > 0 or c.streamed or g.srv.recipients) { try c.finish(final_text, &out); } for (out.items) |d| try g.emit(sink, d); diff --git a/zig/src/server/recipient_reply.zig b/zig/src/server/recipient_reply.zig new file mode 100644 index 00000000000..8e0728aeb8a --- /dev/null +++ b/zig/src/server/recipient_reply.zig @@ -0,0 +1,116 @@ +//! Replies written as messages to recipients: `<|start|>assistant to=R<|message|>body<|eom|>`, the last one `<|eot|>`. +const std = @import("std"); +const reply_text = @import("reply_text.zig"); +const Allocator = std.mem.Allocator; +const Split = reply_text.Split; +const findTag = reply_text.findTag; + +const start = "<|start|>"; +const message = "<|message|>"; +const ends = [_][]const u8{ "<|eom|>", "<|eot|>" }; +const closers = ends ++ [_][]const u8{start}; + +/// Whether replies take this form: every marker is one token and the template writes `to=self` messages. +pub fn detect(text: anytype) bool { + for ([_][]const u8{ start, message, ends[0], ends[1] }) |m| if (text.tokenId(m) == null) return false; + return std.mem.indexOf(u8, text.templateSource(), "to=self") != null; +} + +/// `self` is reasoning; `user`, `commentary` and no recipient are the answer; any other recipient is a tool call. +const Kind = enum { reasoning, answer, call }; + +fn kindOf(header: []const u8) Kind { + const at = std.mem.indexOf(u8, header, "to=") orelse return .answer; + const rest = header[at + 3 ..]; + const r = rest[0 .. std.mem.indexOfAny(u8, rest, " \t\r\n") orelse rest.len]; + if (std.mem.eql(u8, r, "self")) return .reasoning; + if (r.len == 0 or std.mem.eql(u8, r, "user") or std.mem.eql(u8, r, "commentary")) return .answer; + return .call; +} + +/// One message's text after the last, a blank line between; leading whitespace off, so a streamed piece only grows. +fn add(a: Allocator, out: *std.ArrayList(u8), body: []const u8) Allocator.Error!void { + const piece = reply_text.pyLstrip(body); + if (piece.len == 0) return; + if (out.items.len > 0) try out.appendSlice(a, "\n\n"); + try out.appendSlice(a, piece); +} + +/// The template's attribute escapes (`esc_attr`) undone. +fn unescape(a: Allocator, s: []const u8) Allocator.Error![]const u8 { + if (std.mem.indexOfScalar(u8, s, '&') == null) return s; + const escapes = [_][2][]const u8{ .{ "&", "&" }, .{ """, "\"" }, .{ "'", "'" }, .{ "<", "<" }, .{ ">", ">" } }; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + outer: while (i < s.len) { + for (escapes) |e| if (std.mem.startsWith(u8, s[i..], e[0])) { + try out.appendSlice(a, e[1]); + i += e[0].len; + continue :outer; + }; + try out.append(a, s[i]); + i += 1; + } + return out.items; +} + +/// Each `` as Qwen3-Coder's `` block, which tool_parse and tool_stream read; null: none. +pub fn calls(a: Allocator, body: []const u8) Allocator.Error!?[]const u8 { + const invoke = "") orelse break; + const close = std.mem.indexOfPos(u8, body, q, "") orelse body.len; + if (out.items.len > 0) try out.append(a, '\n'); + try out.print(a, "\n\n", .{try unescape(a, body[s + invoke.len .. q])}); + var p = q + 2; + while (findTag(body[0..close], p, parameter)) |ps| { + const pq = std.mem.indexOfPos(u8, body[0..close], ps + parameter.len, "\">") orelse break; + const pe = std.mem.indexOfPos(u8, body[0..close], pq + 2, "") orelse close; + try out.print(a, "\n{s}\n\n", .{ try unescape(a, body[ps + parameter.len .. pq]), body[pq + 2 .. pe] }); + p = pe; + } + try out.appendSlice(a, "\n"); + pos = close; + } + return if (out.items.len > 0) out.items else null; +} + +/// (reasoning, answer) so far; a stream holds back open headers, open calls and partial markers, so each split grows. +pub fn split(a: Allocator, full: []const u8, finished: bool) Allocator.Error!Split { + var reasoning: std.ArrayList(u8) = .empty; + var answer: std.ArrayList(u8) = .empty; + var pos: usize = 0; + var any = false; + while (findTag(full, pos, message)) |m| { // the prompt ends at `<|start|>assistant`: the first header is ` to=R` + var header = full[pos..m]; + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + const b0 = m + message.len; + var b1 = full.len; + var next = full.len; + var closed = false; + for (closers) |e| if (findTag(full[0..b1], b0, e)) |at| { + b1 = at; + next = if (std.mem.eql(u8, e, start)) at else at + e.len; + closed = true; + }; + any = true; + if (!closed and !finished) { + var held: usize = 0; + for (closers) |e| held = @max(held, reply_text.partialTag(full[b0..b1], e)); + b1 -= held; + } + const body = full[b0..b1]; + switch (kindOf(header)) { + .reasoning => try add(a, &reasoning, body), + .answer => try add(a, &answer, body), + .call => if (closed or finished) try add(a, &answer, (try calls(a, body)) orelse body), + } + if (!closed) break; + pos = next; + } + if (!any and finished) return .{ .reasoning = "", .answer = reply_text.pyStrip(full) }; // no message markup at all + return .{ .reasoning = reasoning.items, .answer = answer.items }; +} diff --git a/zig/src/server/recipient_reply_test.zig b/zig/src/server/recipient_reply_test.zig new file mode 100644 index 00000000000..6660802d35c --- /dev/null +++ b/zig/src/server/recipient_reply_test.zig @@ -0,0 +1,300 @@ +//! Recipient replies (Muse Spark's template) split into reasoning, answer and calls, while Harmony replies keep theirs. +const std = @import("std"); +const api = @import("engine_api"); +const server = @import("root.zig"); +const json = server.json; +const model_text = @import("model_text.zig"); +const openai = @import("openai.zig"); +const recipient_reply = @import("recipient_reply.zig"); +const reply_text = @import("reply_text.zig"); +const tool_parse = @import("tool_parse.zig"); +const Conn = @import("http_conn.zig").Conn; + +const muse_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|eom|>", "<|eot|>" }; +const harmony_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|channel|>", "<|end|>", "<|return|>", "<|call|>" }; +const muse_eos = [_]u32{303}; // <|eot|> +const harmony_eos = [_]u32{304}; // <|return|> +const muse_template = "{{- '<|start|>assistant to=self<|message|>' -}}"; +const harmony_template = "{{- '<|start|>assistant<|channel|>commentary to=functions.' ~ name ~ '<|message|>' -}}"; +const all_bytes = blk: { + var all: [256]u8 = undefined; + for (&all, 0..) |*b, i| b.* = i; + break :blk all; +}; + +/// Bytes as tokens and each marker of the format as one token from 300; every prompt renders as "prompt". +const Text = struct { + harmony: bool = false, + + fn text(t: *@This()) model_text.Text { + return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } }; + } + + fn markers(t: *const Text) []const []const u8 { + return if (t.harmony) &harmony_markers else &muse_markers; + } + + fn piece(t: *const Text, id: u32) []const u8 { + return if (id >= 300) t.markers()[id - 300] else all_bytes[id..][0..1]; + } + + /// The reply's tokens: each marker the text spells is its token, every other byte its own. + fn tokens(t: *const Text, a: std.mem.Allocator, s: []const u8) ![]const u32 { + var out: std.ArrayList(u32) = .empty; + var i: usize = 0; + next: while (i < s.len) { + for (t.markers(), 0..) |m, k| if (std.mem.startsWith(u8, s[i..], m)) { + try out.append(a, @intCast(300 + k)); + i += m.len; + continue :next; + }; + try out.append(a, s[i]); + i += 1; + } + return out.items; + } + + fn encode(_: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const ids = try a.alloc(u32, input.len); + for (input, ids) |byte, *id| id.* = byte; + return ids; + } + + fn decode(ctx: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { + const t: *Text = @ptrCast(@alignCast(ctx)); + var out: std.ArrayList(u8) = .empty; + for (ids) |id| try out.appendSlice(a, t.piece(id)); + return out.items; + } + + fn tokenId(ctx: *anyopaque, p: []const u8) ?u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + for (t.markers(), 0..) |m, k| if (std.mem.eql(u8, m, p)) return @as(u32, @intCast(300 + k)); + return null; + } + + fn tokenString(ctx: *anyopaque, a: std.mem.Allocator, id: u32) std.mem.Allocator.Error![]u8 { + return decode(ctx, a, &.{id}); + } + + fn vocabSize(_: *anyopaque) u32 { + return 310; + } + + fn eosIds(ctx: *anyopaque) []const u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return if (t.harmony) &harmony_eos else &muse_eos; + } + + fn render(_: *anyopaque, a: std.mem.Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + return .{ .text = try (a.dupe(u8, "prompt")) }; + } + + fn templateSource(ctx: *anyopaque) []const u8 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return if (t.harmony) harmony_template else muse_template; + } +}; + +/// Answers `reply` in chunks of `stride` tokens. +const Script = struct { + reply: []const u32, + stride: usize, + eos: u32, + + fn engine(e: *@This()) api.Engine { + return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 4096 }; + } + + fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + const e: *Script = @ptrCast(@alignCast(ctx)); + sink.event(sink.ctx, id, &.{ .prefilled = 0 }); + var at: usize = 0; + while (at < e.reply.len) : (at = @min(at + e.stride, e.reply.len)) { + sink.event(sink.ctx, id, &.{ .tokens = e.reply[at..@min(at + e.stride, e.reply.len)] }); + } + const ended = e.reply.len > 0 and e.reply[e.reply.len - 1] == e.eos; + sink.event(sink.ctx, id, &.{ .finished = .{ .reason = if (ended) .stop else .length } }); + } + + fn cancel(_: *anyopaque, _: api.Id) void {} + + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// What a reply showed its client, whole or streamed: reasoning, content, the calls begun and their arguments. +const Shown = struct { + reasoning: std.ArrayList(u8) = .empty, + content: std.ArrayList(u8) = .empty, + arguments: std.ArrayList(u8) = .empty, + calls: usize = 0, + status: u16 = 0, + + fn out(s: *Shown) openai.Out { + return .{ .ctx = s, .vt = &.{ .open = open, .event = event, .reply = reply } }; + } + + fn deinit(s: *Shown) void { + for ([_]*std.ArrayList(u8){ &s.reasoning, &s.content, &s.arguments }) |l| l.deinit(std.testing.allocator); + } + + /// One message or delta object: its text fields appended, each call with an id counted, arguments appended. + fn take(s: *Shown, m: json.Value) !void { + const g = std.testing.allocator; + if (m.get("reasoning_content")) |v| if (v == .string) try s.reasoning.appendSlice(g, v.string); + if (m.get("content")) |v| if (v == .string) try s.content.appendSlice(g, v.string); + const list = m.get("tool_calls") orelse return; + if (list != .array) return; + for (list.array) |call| { + if (call.get("id") != null) s.calls += 1; + const f = call.get("function") orelse continue; + if (f.strField("arguments")) |args| try s.arguments.appendSlice(g, args); + } + } + + fn open(_: *anyopaque, _: usize) error{Closed}!void {} + + fn event(ctx: *anyopaque, payload: ?json.Value) error{Closed}!void { + const s: *Shown = @ptrCast(@alignCast(ctx)); + const p = payload orelse return; + const choices = p.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + const delta = choices.array[0].get("delta") orelse return; + s.take(delta) catch return error.Closed; + } + + fn reply(ctx: *anyopaque, status: u16, payload: json.Value) void { + const s: *Shown = @ptrCast(@alignCast(ctx)); + s.status = status; + const choices = payload.get("choices") orelse return; + if (choices != .array or choices.array.len == 0) return; + s.take(choices.array[0].get("message") orelse return) catch return; + } +}; + +fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Shown { + var text = settings; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var backend: Script = .{ .reply = try text.tokens(a, reply), .stride = stride, .eos = Text.eosIds(&text)[0] }; + var srv = try server.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), .{ + .served_name = "test-model", + .model_ids = &.{"test-model"}, + .enable_thinking = false, + .use_drafts = false, + }, null); + defer srv.deinit(); + const raw = (try json.parse(a, body)).ok; + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var shown: Shown = .{}; + openai.run(srv, a, shown.out(), .{ .conn = &conn }, true, raw); + return shown; +} + +const ask = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"max_tokens\":1024"; +const weather = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\"}}}}}]"; + +fn atem(comptime city: []const u8, comptime days: []const u8) []const u8 { + return "\n\n" ++ city ++ + "\n" ++ days ++ "\n\n"; +} + +const chat_reply = " to=self<|message|>The sky question is simple.<|eom|><|start|>assistant to=user<|message|>Blue sky.<|eot|>"; +const call_reply = " to=self<|message|>Two forecasts are needed.<|eom|><|start|>assistant to=commentary<|message|>Checking both." ++ + "<|eom|><|start|>assistant to=get_weather<|message|>" ++ atem("Paris", "3") ++ "<|eom|><|start|>assistant to=get_weather" ++ + "<|message|>" ++ atem("Oslo", "1") ++ "<|eot|>"; +const harmony_reply = "<|channel|>analysis<|message|>Think.<|end|><|start|>assistant<|channel|>final<|message|>Blue sky.<|return|>"; + +test "recipient replies: detected from the markers and the template, never for Harmony's tokens" { + var muse: Text = .{}; + var harmony: Text = .{ .harmony = true }; + try std.testing.expect(recipient_reply.detect(muse.text())); + try std.testing.expect(!recipient_reply.detect(harmony.text())); +} + +test "recipient replies: a split while streaming only grows, holds calls back, and the finished split extends it" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = call_reply[0 .. call_reply.len - "<|eot|>".len]; + const done = try recipient_reply.split(a, reply, true); + try std.testing.expectEqualStrings("Two forecasts are needed.", done.reasoning); + const xml = "\n\n\n{s}\n\n\n{s}\n\n" ++ + "\n"; + const want = try std.fmt.allocPrint(a, "Checking both.\n\n" ++ xml ++ "\n\n" ++ xml, .{ "Paris", "3", "Oslo", "1" }); + try std.testing.expectEqualStrings(want, done.answer); + var last: reply_text.Split = .{ .reasoning = "", .answer = "" }; + for (1..reply.len + 1) |n| { + const s = try recipient_reply.split(a, reply[0..n], false); + try std.testing.expect(std.mem.startsWith(u8, s.reasoning, last.reasoning)); + try std.testing.expect(std.mem.startsWith(u8, s.answer, last.answer)); + try std.testing.expect(std.mem.indexOf(u8, s.answer, "<|") == null and std.mem.indexOf(u8, s.answer, "atem") == null); + try std.testing.expect(std.mem.startsWith(u8, done.answer, s.answer)); + last = s; + } + try std.testing.expect(std.mem.indexOf(u8, last.answer, "Oslo") == null); // the open call waits for the reply's end + try std.testing.expectEqualStrings("plain", (try recipient_reply.split(a, " plain ", true)).answer); +} + +test "recipient replies: atem calls become OpenAI calls with schema-typed arguments" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; + const body = atem("Rio de Janeiro", "4"); + const parsed = try tool_parse.parse(a, (try recipient_reply.calls(a, body)).?, tools, null); + try std.testing.expectEqualStrings("", parsed.content); + const f = parsed.calls.?[0].get("function").?; + try std.testing.expectEqualStrings("get_weather", f.strField("name").?); + try std.testing.expectEqualStrings("{\"city\":\"Rio de Janeiro\",\"days\":4}", f.strField("arguments").?); + const named = (try recipient_reply.calls(a, "\n")).?; + try std.testing.expectEqualStrings("\n\n\n", named); + try std.testing.expect((try recipient_reply.calls(a, "no calls here")) == null); +} + +test "recipient replies: whole and streamed chats show the same reasoning, answer and calls" { + const cases = [_]struct { reply: []const u8, body: []const u8, content: []const u8, reasoning: []const u8, arguments: []const u8, calls: usize }{ + .{ .reply = chat_reply, .body = ask ++ "}", .content = "Blue sky.", .reasoning = "The sky question is simple.", .arguments = "", .calls = 0 }, + .{ .reply = call_reply, .body = ask ++ weather ++ "}", .content = "Checking both.", .reasoning = "Two forecasts are needed.", .arguments = "{\"city\":\"Paris\",\"days\":3}{\"city\":\"Oslo\",\"days\":1}", .calls = 2 }, + }; + for (cases) |c| { + var whole = try send(.{}, c.reply, 4096, c.body); + defer whole.deinit(); + try std.testing.expectEqual(@as(u16, 200), whole.status); + for ([_]usize{ 1, 7, 4096 }) |stride| { + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ c.body[0 .. c.body.len - 1], ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + var streamed = try send(.{}, c.reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings(c.content, s.content.items); + try std.testing.expectEqualStrings(c.reasoning, s.reasoning.items); + try std.testing.expectEqualStrings(c.arguments, s.arguments.items); + try std.testing.expectEqual(c.calls, s.calls); + } + } + } +} + +test "recipient replies: a Harmony reply keeps its final channel as content and analysis as reasoning" { + var whole = try send(.{ .harmony = true }, harmony_reply, 4096, ask ++ "}"); + defer whole.deinit(); + var streamed = try send(.{ .harmony = true }, harmony_reply, 1, ask ++ ",\"stream\":true}"); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("Think.", s.reasoning.items); + } +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index e9b9c34e064..47837fb69c7 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -60,6 +60,7 @@ test { _ = @import("reply_code.zig"); _ = @import("reply_text.zig"); _ = @import("reply_incremental_test.zig"); + _ = @import("recipient_reply_test.zig"); _ = @import("tool_parse.zig"); _ = @import("tool_lfm2.zig"); _ = @import("tool_lfm2_stream_test.zig"); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 0d6aa81092f..e18c9bc92d9 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -11,6 +11,7 @@ const request_guard = @import("request_guard.zig"); const metrics = @import("metrics.zig"); const model_text = @import("model_text.zig"); const reply_text = @import("reply_text.zig"); +const recipient_reply = @import("recipient_reply.zig"); const http_conn = @import("http_conn.zig"); const admission = @import("http_admission.zig"); const listener_mod = @import("listener.zig"); @@ -142,6 +143,8 @@ pub const Server = struct { late_system: []const u8 = "system", needs_user_after_tool: bool = false, markers: reply_text.Markers = reply_text.think_markers, + /// Replies are messages to recipients (`to=self` reasoning, `to=user` answer, a tool's name a call). + recipients: bool = false, close_id: ?u32 = null, // the close marker's own token, when the marker is one token chunks: chunk_plan.Plan = .{}, effort_levels: []const []const u8 = &.{}, @@ -227,6 +230,7 @@ pub const Server = struct { const minimax = text.tokenId(reply_text.mm_markers.close) != null; if (minimax) srv.markers = reply_text.mm_markers; srv.close_id = text.tokenId(srv.markers.close); + srv.recipients = recipient_reply.detect(text); const source = text.templateSource(); srv.effort_levels = try fields.effortLevels(a, source); // MiniMax-M3's template decides on its own; thinking off closes the block in the prompt (prompt.zig) From e9662caadc20536b9d9aede735778a5331e5b8bd Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Mon, 26 Oct 2026 21:49:43 +1100 Subject: [PATCH 144/158] server: recipient replies: a cut call is the reply's cut call, the prompt's open message read, thinking off kept off A call message max_tokens cuts stays open as far as it was written, named by its header until its invoke names the tool, so tool_stream reads it as the reply's cut call, whole and streamed, as #1299 made a GLM call; content never shows its markup. A stop string inside a call keeps the call's text, as the other formats keep theirs. The reply goes on from the prompt's last unclosed <|start|> header, so a generation prompt that already opened to=self<|message|> keeps the reasoning after it; Muse Spark Open's template ends at <|start|>assistant, with or without reasoning_effort. Only calls to offered tools become markup: with no tools, or a tool not offered, a call message stays as the model wrote it, as DSML, LFM2 and Qwen's XML calls do. Thinking off no longer turns the split's reasoning on: self messages stay out of the reply, and the template, which has no thinking switch, hears its lowest reasoning effort rather than its default (xhigh). Raw completion prompts keep the model's text. Tests cut a call before its invoke names the tool, inside a value, a value's closer, a parameter's name, between parameters, after the invoke closed, and in a call's header, at strides 1, 3, 7 and whole; and cover an opened prompt, no tools, an unoffered tool and thinking off. --- zig/src/server/chat.zig | 3 +- zig/src/server/chat_generation.zig | 16 ++- zig/src/server/prompt.zig | 2 +- zig/src/server/recipient_cut_test.zig | 69 ++++++++++ zig/src/server/recipient_reply.zig | 166 +++++++++++++++++------- zig/src/server/recipient_reply_test.zig | 141 ++++++++++++++++---- zig/src/server/root.zig | 1 + zig/src/server/server.zig | 3 + 8 files changed, 314 insertions(+), 87 deletions(-) create mode 100644 zig/src/server/recipient_cut_test.zig diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index f094a0dcf4b..5c62ae6f9b4 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -276,9 +276,10 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)) or srv.recipients, .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished + if (srv.recipients and input.prompt == null) gen.recipient = try recipient_reply.Reading.of(a, srv.text, request.prompt, input.tools, prepared.reasoning); const result: Failure!Reply = blk: { if (sink) |s| if (s.begin) |begin| begin(s.ctx, prepared.prompt_len) catch break :blk error.Cancelled; if (sink != null and input.tools.len > 0 and srv.text.vtable.format != .kimi) gen.calls = tool_stream.Streamer.init(a, input.tools) catch |e| break :blk e; diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index d04ecdd731f..f98a828d23d 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -56,6 +56,7 @@ pub const Generation = struct { token_ids: bool, // "return_token_ids": the response's tensorfold block carries the reply's token ids tools: []const Value, calls: ?tool_stream.Streamer = null, + recipient: ?recipient_reply.Reading = null, // a chat whose reply is messages to recipients (Muse Spark's) collected: std.ArrayList(u32) = .empty, visible: reply_text.Incremental = .{}, kimi: ?@import("kimi_reply.zig").Stream = null, @@ -152,10 +153,10 @@ pub const Generation = struct { const text = try @import("tool_minimax.zig").dsml(g.a, raw_visible, g.tools); // MiniMax-M3's calls as DSML var answer = text; var thought: []const u8 = ""; - if (g.thinking) { + if (g.thinking or g.recipient != null) { const original_close = try g.visible.closeOf(g.a, reply_text.decodeText, g.srv.text, g.srv.close_id); const close = try @import("tool_minimax.zig").closeAfterRewrite(g.a, raw_visible, g.tools, original_close); - const split = if (g.srv.recipients) try recipient_reply.split(g.a, text, false) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); + const split = if (g.recipient) |r| try r.split(g.a, text, .streaming) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); thought = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it if (thought.len > 0) try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), thought); answer = split.answer; @@ -304,11 +305,12 @@ pub const Generation = struct { const text = if (close.len > 0) try std.mem.concat(a, u8, &.{ visible, close }) else visible; var content: []const u8 = text; var reasoning: ?[]const u8 = null; + const read = g.thinking or g.recipient != null; // the reply's split text is its content if (native) |n| { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; - } else if (g.thinking) { - const split = if (g.srv.recipients) try recipient_reply.split(a, text, true) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); + } else if (read) { + const split = if (g.recipient) |r| try r.split(a, text, if (std.mem.eql(u8, reason, "length")) .cut else if (g.stops.matched(raw) != null) .stopped else .ended) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); const r = reply_text.pyStrip(split.reasoning); reasoning = if (r.len > 0) r else null; content = split.answer; @@ -326,17 +328,17 @@ pub const Generation = struct { const thought = g.streamed_reasoning.text.items; if (reasoning) |r| if (std.mem.startsWith(u8, r, thought) and r.len > thought.len) try g.emit(sink, try deltaOf(a, "reasoning_content", r[thought.len..])); - const shown = if (g.calls != null) try tool_stream.endProse(a, content, if (g.thinking) content else text, g.tools, reason, g.single) else content; + const shown = if (g.calls != null) try tool_stream.endProse(a, content, if (read) content else text, g.tools, reason, g.single) else content; const sent = g.streamed.text.items; const rest = if (std.mem.startsWith(u8, shown, sent) and shown.len > sent.len) shown[sent.len..] else ""; if (rest.len > 0) try g.emit(sink, .{ .string = rest }); if (g.calls) |*c| { // the streamer reads the closers as markup the model wrote, so the call ends with the same deltas var out: std.ArrayList(Value) = .empty; - const final_text = if (g.thinking) content else text; + const final_text = if (read) content else text; if (std.mem.eql(u8, reason, "length")) { try c.finishCut(final_text, &out); - } else if (close.len > 0 or c.streamed or g.srv.recipients) { + } else if (close.len > 0 or c.streamed or g.recipient != null) { try c.finish(final_text, &out); } for (out.items) |d| try g.emit(sink, d); diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index 763a683e4b9..a4c224a59d7 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -49,7 +49,7 @@ pub fn renderStarts(srv: *Server, cx: *Cx, messages: Value, tools: []const Value .tools = if (tools.len > 0) Value{ .array = @constCast(tools) } else null, .add_generation_prompt = generation, .enable_thinking = thinking, - .reasoning_effort = if (thinking) effort else cx.named_effort, // off: only an effort the request named + .reasoning_effort = if (thinking) effort else cx.named_effort orelse srv.off_effort, .clear_thinking = cx.clear_thinking, .tool_choice = cx.template_fields.get("tool_choice"), .response_format = cx.template_fields.get("response_format"), diff --git a/zig/src/server/recipient_cut_test.zig b/zig/src/server/recipient_cut_test.zig new file mode 100644 index 00000000000..6b619a25a0f --- /dev/null +++ b/zig/src/server/recipient_cut_test.zig @@ -0,0 +1,69 @@ +//! A recipient reply max_tokens cuts inside a call message: its cut call, whole and streamed, as #1299's GLM call. +const std = @import("std"); +const harness = @import("recipient_reply_test.zig"); +const Text = harness.Text; + +const head = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]," ++ + "\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"write_file\",\"parameters\":{\"type\":\"object\"," ++ + "\"properties\":{\"path\":{\"type\":\"string\"},\"content\":{\"type\":\"string\"},\"limit\":{\"type\":\"integer\"}}}}}]"; +const thought = " to=self<|message|>A file is needed.<|eom|>"; +const call = "<|start|>assistant to=write_file<|message|>"; +const path = "\n\nnotes.txt\n"; +const opened = path ++ "The history of"; +const rest = " the bicycle\n\n<|eot|>"; +const args = "{\"path\":\"notes.txt\",\"content\":\"The history of"; + +/// `cut` then `rest`, max_tokens at `cut`'s end: whole and streamed replies agree at every stride (null: unchecked). +fn expectCut(cut: []const u8, calls: usize, arguments: []const u8, content: ?[]const u8, extra: []const u8) !void { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var text: Text = .{}; + const n = (try text.tokens(a, cut)).len; + const body = try std.fmt.allocPrint(a, "{s},\"max_tokens\":{d}{s}", .{ head, n, extra }); + var whole = try harness.send(.{}, try std.mem.concat(a, u8, &.{ cut, rest }), 4096, try std.mem.concat(a, u8, &.{ body, "}" })); + defer whole.deinit(); + try std.testing.expectEqual(@as(u16, 200), whole.status); + for ([_]usize{ 1, 3, 7, 4096 }) |stride| { + var streamed = try harness.send(.{}, try std.mem.concat(a, u8, &.{ cut, rest }), stride, try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" })); + defer streamed.deinit(); + for ([_]*const harness.Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqual(calls, s.calls); + try std.testing.expectEqualStrings(arguments, s.arguments.items); + if (content) |c| try std.testing.expectEqualStrings(c, s.content.items); + for ([_][]const u8{ "atem", "\n\na.txt" ++ + "\n\n<|eom|>"; + try expectCut(thought ++ first ++ call ++ opened, 2, "{\"path\":\"a.txt\"}" ++ args, "", ""); + // inside a value's closer, between parameters, inside a parameter's name and after the invoke closed + try expectCut(thought ++ call ++ opened ++ "\n\n12"; + try expectCut(thought ++ call ++ limit, 1, "{\"limit\":12", "", ""); +} + +test "recipient cut: a call cut before its invoke names the tool is the header's call" { + inline for (.{ "", "\nassistant to=write_fi", 0, "", "", ""); +} + +test "recipient cut: the one-call policy hides the cut call" { + try expectCut(thought ++ call ++ opened, 0, "", null, ",\"parallel_tool_calls\":false"); +} diff --git a/zig/src/server/recipient_reply.zig b/zig/src/server/recipient_reply.zig index 8e0728aeb8a..b90c64e1dba 100644 --- a/zig/src/server/recipient_reply.zig +++ b/zig/src/server/recipient_reply.zig @@ -1,7 +1,10 @@ //! Replies written as messages to recipients: `<|start|>assistant to=R<|message|>body<|eom|>`, the last one `<|eot|>`. const std = @import("std"); +const json = @import("json"); const reply_text = @import("reply_text.zig"); +const tool_specs = @import("tool_specs.zig"); const Allocator = std.mem.Allocator; +const Value = json.Value; const Split = reply_text.Split; const findTag = reply_text.findTag; @@ -9,6 +12,12 @@ const start = "<|start|>"; const message = "<|message|>"; const ends = [_][]const u8{ "<|eom|>", "<|eot|>" }; const closers = ends ++ [_][]const u8{start}; +const block = ""; +const block_close = ""; +const invoke = "` as Qwen3-Coder's `` block, which tool_parse and tool_stream read; null: none. -pub fn calls(a: Allocator, body: []const u8) Allocator.Error!?[]const u8 { - const invoke = " 0 and std.ascii.eqlIgnoreCase(spelled, name)) return spelled; + } + return null; +} + +/// A call message as the `` markup tool_parse reads, a cut one left open; null: keep the model's text. +pub fn calls(a: Allocator, body: []const u8, recipient: []const u8, tools: []const Value, end: End) Allocator.Error!?[]const u8 { + if (tools.len == 0 or end == .stopped) return null; // no tools offered, or a stop string inside the call + const cut = end == .cut; + const lead = reply_text.pyLstrip(body); + if (!std.mem.startsWith(u8, lead, block) and !(cut and std.mem.startsWith(u8, block, lead))) return null; var out: std.ArrayList(u8) = .empty; var pos: usize = 0; while (findTag(body, pos, invoke)) |s| { - const q = std.mem.indexOfPos(u8, body, s + invoke.len, "\">") orelse break; - const close = std.mem.indexOfPos(u8, body, q, "") orelse body.len; + const q = std.mem.indexOfPos(u8, body, s + invoke.len, "\">") orelse break; // its name is still being written + const name = (try offered(a, try unescape(a, body[s + invoke.len .. q]), tools)) orelse return null; + const close = std.mem.indexOfPos(u8, body, q, invoke_close); + const stop = close orelse body.len; if (out.items.len > 0) try out.append(a, '\n'); - try out.print(a, "\n\n", .{try unescape(a, body[s + invoke.len .. q])}); + try out.print(a, "\n\n", .{name}); var p = q + 2; - while (findTag(body[0..close], p, parameter)) |ps| { - const pq = std.mem.indexOfPos(u8, body[0..close], ps + parameter.len, "\">") orelse break; - const pe = std.mem.indexOfPos(u8, body[0..close], pq + 2, "") orelse close; - try out.print(a, "\n{s}\n\n", .{ try unescape(a, body[ps + parameter.len .. pq]), body[pq + 2 .. pe] }); - p = pe; + while (findTag(body[0..stop], p, parameter)) |ps| { + const pq = std.mem.indexOfPos(u8, body[0..stop], ps + parameter.len, "\">") orelse break; // a cut name + const pe = std.mem.indexOfPos(u8, body[0..stop], pq + 2, parameter_close); + const value = body[pq + 2 .. pe orelse stop - (if (cut) reply_text.partialTag(body[pq + 2 .. stop], parameter_close) else 0)]; + try out.print(a, "\n{s}", .{ try unescape(a, body[ps + parameter.len .. pq]), value }); + if (pe == null and cut) return out.items; // a cut value: its closers never came + try out.appendSlice(a, "\n\n"); + p = pe orelse stop; } - try out.appendSlice(a, "\n"); - pos = close; + if (close == null and cut) return out.items; // cut between its parameters + try out.appendSlice(a, "\n"); + pos = if (close) |c| c + invoke_close.len else stop; + if (cut and findTag(body, pos, invoke) == null and findTag(body, pos, block_close) == null) return out.items; // block open + try out.appendSlice(a, ""); + } + if (out.items.len == 0 and cut and findTag(body, 0, block_close) == null) { // cut before its invoke names it + const name = (try offered(a, recipient, tools)) orelse return null; + return try std.fmt.allocPrint(a, "\n\n", .{name}); } return if (out.items.len > 0) out.items else null; } -/// (reasoning, answer) so far; a stream holds back open headers, open calls and partial markers, so each split grows. -pub fn split(a: Allocator, full: []const u8, finished: bool) Allocator.Error!Split { - var reasoning: std.ArrayList(u8) = .empty; - var answer: std.ArrayList(u8) = .empty; - var pos: usize = 0; - var any = false; - while (findTag(full, pos, message)) |m| { // the prompt ends at `<|start|>assistant`: the first header is ` to=R` - var header = full[pos..m]; - if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; - const b0 = m + message.len; - var b1 = full.len; - var next = full.len; - var closed = false; - for (closers) |e| if (findTag(full[0..b1], b0, e)) |at| { - b1 = at; - next = if (std.mem.eql(u8, e, start)) at else at + e.len; - closed = true; - }; - any = true; - if (!closed and !finished) { - var held: usize = 0; - for (closers) |e| held = @max(held, reply_text.partialTag(full[b0..b1], e)); - b1 -= held; +/// How one chat's reply reads: the message its prompt left open, the request's tools and thinking switch. +pub const Reading = struct { + /// The prompt after its last `<|start|>` when no end follows it (`assistant`, or `assistant to=self<|message|>`). + lead: []const u8 = "", + tools: []const Value = &.{}, + /// Thinking on: `self` messages are the reasoning; off, they stay out of the reply. + reasoning: bool = true, + + pub fn of(a: Allocator, text: anytype, prompt: []const u32, tools: []const Value, thinking: bool) Allocator.Error!Reading { + var r: Reading = .{ .tools = tools, .reasoning = thinking }; + const id = text.tokenId(start) orelse return r; + const at = std.mem.lastIndexOfScalar(u32, prompt, id) orelse return r; + const lead = try text.decode(a, prompt[at + 1 ..]); + for (ends) |e| if (std.mem.indexOf(u8, lead, e) != null) return r; + r.lead = lead; + return r; + } + + /// (reasoning, answer) so far; a stream holds back open headers, calls and partial markers, so each split grows. + pub fn split(r: Reading, a: Allocator, reply: []const u8, end: End) Allocator.Error!Split { + const full = if (r.lead.len > 0) try std.mem.concat(a, u8, &.{ r.lead, reply }) else reply; + var reasoning: std.ArrayList(u8) = .empty; + var answer: std.ArrayList(u8) = .empty; + var pos: usize = 0; + var any = false; + while (findTag(full, pos, message)) |m| { // the reply goes on from the prompt's lead + var header = full[pos..m]; + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + const b0 = m + message.len; + var b1 = full.len; + var next = full.len; + var closed = false; + for (closers) |e| if (findTag(full[0..b1], b0, e)) |at| { + b1 = at; + next = if (std.mem.eql(u8, e, start)) at else at + e.len; + closed = true; + }; + any = true; + if (!closed and end == .streaming) { + var held: usize = 0; + for (closers) |e| held = @max(held, reply_text.partialTag(full[b0..b1], e)); + b1 -= held; + } + const body = full[b0..b1]; + switch (kindOf(header)) { + .reasoning => if (r.reasoning) try add(a, &reasoning, body), + .answer => try add(a, &answer, body), + .call => if (closed or end != .streaming) { + const as = if (closed) .ended else end; + try add(a, &answer, (try calls(a, body, recipientOf(header).?, r.tools, as)) orelse body); + }, + } + if (!closed) break; + pos = next; } - const body = full[b0..b1]; - switch (kindOf(header)) { - .reasoning => try add(a, &reasoning, body), - .answer => try add(a, &answer, body), - .call => if (closed or finished) try add(a, &answer, (try calls(a, body)) orelse body), + if (!any and end != .streaming) { // no message markup at all; a header the reply was cut in is no answer + const plain = reply_text.pyStrip(reply); + return .{ .reasoning = "", .answer = if (std.mem.startsWith(u8, plain, "to=")) "" else plain }; } - if (!closed) break; - pos = next; + return .{ .reasoning = reasoning.items, .answer = answer.items }; } - if (!any and finished) return .{ .reasoning = "", .answer = reply_text.pyStrip(full) }; // no message markup at all - return .{ .reasoning = reasoning.items, .answer = answer.items }; -} +}; diff --git a/zig/src/server/recipient_reply_test.zig b/zig/src/server/recipient_reply_test.zig index 6660802d35c..21ddb054d0c 100644 --- a/zig/src/server/recipient_reply_test.zig +++ b/zig/src/server/recipient_reply_test.zig @@ -14,7 +14,7 @@ const muse_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|eom|>", "<|eo const harmony_markers = [_][]const u8{ "<|start|>", "<|message|>", "<|channel|>", "<|end|>", "<|return|>", "<|call|>" }; const muse_eos = [_]u32{303}; // <|eot|> const harmony_eos = [_]u32{304}; // <|return|> -const muse_template = "{{- '<|start|>assistant to=self<|message|>' -}}"; +const muse_template = "{%- set reasoning_effort_map = {'low': 8, 'xhigh': 512} -%}{{- '<|start|>assistant to=self<|message|>' -}}"; const harmony_template = "{{- '<|start|>assistant<|channel|>commentary to=functions.' ~ name ~ '<|message|>' -}}"; const all_bytes = blk: { var all: [256]u8 = undefined; @@ -22,9 +22,10 @@ const all_bytes = blk: { break :blk all; }; -/// Bytes as tokens and each marker of the format as one token from 300; every prompt renders as "prompt". -const Text = struct { +/// Bytes as tokens and each marker of the format as one token from 300; every prompt renders as `prompt`. +pub const Text = struct { harmony: bool = false, + prompt: []const u8 = "prompt<|start|>assistant", // rendered after `effort=E;`, the effort the template heard fn text(t: *@This()) model_text.Text { return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } }; @@ -39,7 +40,7 @@ const Text = struct { } /// The reply's tokens: each marker the text spells is its token, every other byte its own. - fn tokens(t: *const Text, a: std.mem.Allocator, s: []const u8) ![]const u32 { + pub fn tokens(t: *const Text, a: std.mem.Allocator, s: []const u8) ![]const u32 { var out: std.ArrayList(u32) = .empty; var i: usize = 0; next: while (i < s.len) { @@ -54,10 +55,9 @@ const Text = struct { return out.items; } - fn encode(_: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { - const ids = try a.alloc(u32, input.len); - for (input, ids) |byte, *id| id.* = byte; - return ids; + fn encode(ctx: *anyopaque, a: std.mem.Allocator, input: []const u8, _: bool) model_text.Error![]u32 { + const t: *Text = @ptrCast(@alignCast(ctx)); + return @constCast(try t.tokens(a, input)); } fn decode(ctx: *anyopaque, a: std.mem.Allocator, ids: []const u32) std.mem.Allocator.Error![]u8 { @@ -86,8 +86,9 @@ const Text = struct { return if (t.harmony) &harmony_eos else &muse_eos; } - fn render(_: *anyopaque, a: std.mem.Allocator, _: json.Value, _: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { - return .{ .text = try (a.dupe(u8, "prompt")) }; + fn render(ctx: *anyopaque, a: std.mem.Allocator, _: json.Value, o: model_text.RenderOptions, _: *[]const u8) model_text.Error!model_text.Rendered { + const t: *Text = @ptrCast(@alignCast(ctx)); + return .{ .text = try std.mem.concat(a, u8, &.{ "effort=", o.reasoning_effort orelse "none", ";", t.prompt }) }; } fn templateSource(ctx: *anyopaque) []const u8 { @@ -97,10 +98,12 @@ const Text = struct { }; /// Answers `reply` in chunks of `stride` tokens. -const Script = struct { +pub const Script = struct { reply: []const u32, stride: usize, eos: u32, + effort: [8]u8 = undefined, // the effort the submitted prompt was rendered with + effort_len: usize = 0, fn engine(e: *@This()) api.Engine { return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; @@ -110,8 +113,11 @@ const Script = struct { return .{ .context_window = 4096 }; } - fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void { + fn submit(ctx: *anyopaque, id: api.Id, request: *const api.Request, sink: api.Sink) api.SubmitError!void { const e: *Script = @ptrCast(@alignCast(ctx)); + const named = request.prompt["effort=".len..]; + e.effort_len = std.mem.indexOfScalar(u32, named, ';').?; + for (named[0..e.effort_len], e.effort[0..e.effort_len]) |t, *b| b.* = @intCast(t); sink.event(sink.ctx, id, &.{ .prefilled = 0 }); var at: usize = 0; while (at < e.reply.len) : (at = @min(at + e.stride, e.reply.len)) { @@ -133,23 +139,28 @@ const Script = struct { }; /// What a reply showed its client, whole or streamed: reasoning, content, the calls begun and their arguments. -const Shown = struct { +pub const Shown = struct { reasoning: std.ArrayList(u8) = .empty, content: std.ArrayList(u8) = .empty, arguments: std.ArrayList(u8) = .empty, calls: usize = 0, status: u16 = 0, + length: bool = false, // finish_reason "length" + effort: [8]u8 = undefined, + effort_len: usize = 0, fn out(s: *Shown) openai.Out { return .{ .ctx = s, .vt = &.{ .open = open, .event = event, .reply = reply } }; } - fn deinit(s: *Shown) void { + pub fn deinit(s: *Shown) void { for ([_]*std.ArrayList(u8){ &s.reasoning, &s.content, &s.arguments }) |l| l.deinit(std.testing.allocator); } /// One message or delta object: its text fields appended, each call with an id counted, arguments appended. - fn take(s: *Shown, m: json.Value) !void { + fn take(s: *Shown, choice: json.Value, key: []const u8) !void { + if (choice.strField("finish_reason")) |f| s.length = s.length or std.mem.eql(u8, f, "length"); + const m = choice.get(key) orelse return; const g = std.testing.allocator; if (m.get("reasoning_content")) |v| if (v == .string) try s.reasoning.appendSlice(g, v.string); if (m.get("content")) |v| if (v == .string) try s.content.appendSlice(g, v.string); @@ -169,8 +180,7 @@ const Shown = struct { const p = payload orelse return; const choices = p.get("choices") orelse return; if (choices != .array or choices.array.len == 0) return; - const delta = choices.array[0].get("delta") orelse return; - s.take(delta) catch return error.Closed; + s.take(choices.array[0], "delta") catch return error.Closed; } fn reply(ctx: *anyopaque, status: u16, payload: json.Value) void { @@ -178,11 +188,12 @@ const Shown = struct { s.status = status; const choices = payload.get("choices") orelse return; if (choices != .array or choices.array.len == 0) return; - s.take(choices.array[0].get("message") orelse return) catch return; + s.take(choices.array[0], "message") catch return; } }; -fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Shown { +/// `body` answered with `reply`'s tokens, `stride` at a time; the engine stops at the end token or after the reply. +pub fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Shown { var text = settings; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); @@ -191,7 +202,7 @@ fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Sho var srv = try server.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), .{ .served_name = "test-model", .model_ids = &.{"test-model"}, - .enable_thinking = false, + .enable_thinking = true, .use_drafts = false, }, null); defer srv.deinit(); @@ -199,10 +210,13 @@ fn send(settings: Text, reply: []const u8, stride: usize, body: []const u8) !Sho var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; var shown: Shown = .{}; openai.run(srv, a, shown.out(), .{ .conn = &conn }, true, raw); + @memcpy(shown.effort[0..backend.effort_len], backend.effort[0..backend.effort_len]); + shown.effort_len = backend.effort_len; return shown; } const ask = "{\"model\":\"test-model\",\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"max_tokens\":1024"; +const no_thinking = ",\"chat_template_kwargs\":{\"enable_thinking\":false}"; const weather = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\"," ++ "\"properties\":{\"city\":{\"type\":\"string\"},\"days\":{\"type\":\"integer\"}}}}}]"; @@ -229,7 +243,8 @@ test "recipient replies: a split while streaming only grows, holds calls back, a defer arena.deinit(); const a = arena.allocator(); const reply = call_reply[0 .. call_reply.len - "<|eot|>".len]; - const done = try recipient_reply.split(a, reply, true); + const reading: recipient_reply.Reading = .{ .lead = "assistant", .tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array }; + const done = try reading.split(a, reply, .ended); try std.testing.expectEqualStrings("Two forecasts are needed.", done.reasoning); const xml = "\n\n\n{s}\n\n\n{s}\n\n" ++ "\n"; @@ -237,7 +252,7 @@ test "recipient replies: a split while streaming only grows, holds calls back, a try std.testing.expectEqualStrings(want, done.answer); var last: reply_text.Split = .{ .reasoning = "", .answer = "" }; for (1..reply.len + 1) |n| { - const s = try recipient_reply.split(a, reply[0..n], false); + const s = try reading.split(a, reply[0..n], .streaming); try std.testing.expect(std.mem.startsWith(u8, s.reasoning, last.reasoning)); try std.testing.expect(std.mem.startsWith(u8, s.answer, last.answer)); try std.testing.expect(std.mem.indexOf(u8, s.answer, "<|") == null and std.mem.indexOf(u8, s.answer, "atem") == null); @@ -245,7 +260,7 @@ test "recipient replies: a split while streaming only grows, holds calls back, a last = s; } try std.testing.expect(std.mem.indexOf(u8, last.answer, "Oslo") == null); // the open call waits for the reply's end - try std.testing.expectEqualStrings("plain", (try recipient_reply.split(a, " plain ", true)).answer); + try std.testing.expectEqualStrings("plain", (try reading.split(a, " plain ", .ended)).answer); } test "recipient replies: atem calls become OpenAI calls with schema-typed arguments" { @@ -254,14 +269,15 @@ test "recipient replies: atem calls become OpenAI calls with schema-typed argume const a = arena.allocator(); const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; const body = atem("Rio de Janeiro", "4"); - const parsed = try tool_parse.parse(a, (try recipient_reply.calls(a, body)).?, tools, null); + const parsed = try tool_parse.parse(a, (try recipient_reply.calls(a, body, "get_weather", tools, .ended)).?, tools, null); try std.testing.expectEqualStrings("", parsed.content); const f = parsed.calls.?[0].get("function").?; try std.testing.expectEqualStrings("get_weather", f.strField("name").?); try std.testing.expectEqualStrings("{\"city\":\"Rio de Janeiro\",\"days\":4}", f.strField("arguments").?); - const named = (try recipient_reply.calls(a, "\n")).?; + const amp = (try json.parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"a&b\"}}]")).ok.array; + const named = (try recipient_reply.calls(a, "\n\n", "a&b", amp, .ended)).?; try std.testing.expectEqualStrings("\n\n\n", named); - try std.testing.expect((try recipient_reply.calls(a, "no calls here")) == null); + try std.testing.expect((try recipient_reply.calls(a, "no calls here", "get_weather", tools, .ended)) == null); } test "recipient replies: whole and streamed chats show the same reasoning, answer and calls" { @@ -289,12 +305,81 @@ test "recipient replies: whole and streamed chats show the same reasoning, answe } test "recipient replies: a Harmony reply keeps its final channel as content and analysis as reasoning" { - var whole = try send(.{ .harmony = true }, harmony_reply, 4096, ask ++ "}"); + var whole = try send(.{ .harmony = true }, harmony_reply, 4096, ask ++ no_thinking ++ "}"); defer whole.deinit(); - var streamed = try send(.{ .harmony = true }, harmony_reply, 1, ask ++ ",\"stream\":true}"); + var streamed = try send(.{ .harmony = true }, harmony_reply, 1, ask ++ no_thinking ++ ",\"stream\":true}"); defer streamed.deinit(); for ([_]*const Shown{ &whole, &streamed }) |s| { try std.testing.expectEqualStrings("Blue sky.", s.content.items); try std.testing.expectEqualStrings("Think.", s.reasoning.items); } } + +test "recipient replies: a prompt that opened the self message keeps the reasoning that follows it" { + const opened: Text = .{ .prompt = "prompt<|start|>assistant to=self<|message|>" }; + const reply = "The sky question is simple.<|eom|><|start|>assistant to=user<|message|>Blue sky.<|eot|>"; + var whole = try send(opened, reply, 4096, ask ++ "}"); + defer whole.deinit(); + for ([_]usize{ 1, 7, 4096 }) |stride| { + var streamed = try send(opened, reply, stride, ask ++ ",\"stream\":true}"); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("The sky question is simple.", s.reasoning.items); + } + // cut while it still reasons: the reasoning so far, no answer + var cut = try send(opened, "Still weighing the sky", stride, ask ++ ",\"stream\":true}"); + defer cut.deinit(); + try std.testing.expectEqualStrings("Still weighing the sky", cut.reasoning.items); + try std.testing.expectEqualStrings("", cut.content.items); + } +} + +test "recipient replies: a call to no offered tool stays as the model wrote it, never as other markup" { + const time = ",\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_time\",\"parameters\":{\"type\":\"object\"}}}]"; + const want = comptime "Checking both.\n\n" ++ atem("Paris", "3") ++ "\n\n" ++ atem("Oslo", "1"); + for ([_][]const u8{ "", time }) |tools| { + const body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, tools, "}" }); + defer std.testing.allocator.free(body); + var whole = try send(.{}, call_reply, 4096, body); + defer whole.deinit(); + for ([_]usize{ 1, 7, 4096 }) |stride| { + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, tools, ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + var streamed = try send(.{}, call_reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings(want, s.content.items); + try std.testing.expectEqual(@as(usize, 0), s.calls); + } + } + } +} + +test "recipient replies: thinking off keeps self messages out of the reply and the template at its lowest effort" { + for ([_][]const u8{ no_thinking, ",\"reasoning_effort\":\"none\"" }) |off| { + const body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, off, "}" }); + defer std.testing.allocator.free(body); + var whole = try send(.{}, chat_reply, 4096, body); + defer whole.deinit(); + const streamed_body = try std.mem.concat(std.testing.allocator, u8, &.{ ask, off, ",\"stream\":true}" }); + defer std.testing.allocator.free(streamed_body); + for ([_]usize{ 1, 7 }) |stride| { + var streamed = try send(.{}, chat_reply, stride, streamed_body); + defer streamed.deinit(); + for ([_]*const Shown{ &whole, &streamed }) |s| { + try std.testing.expectEqualStrings("Blue sky.", s.content.items); + try std.testing.expectEqualStrings("", s.reasoning.items); + try std.testing.expectEqualStrings("low", s.effort[0..s.effort_len]); + } + } + } + // thinking on: the template's default effort, or the named level nearest the request's + var on = try send(.{}, chat_reply, 4096, ask ++ "}"); + defer on.deinit(); + try std.testing.expectEqualStrings("none", on.effort[0..on.effort_len]); + try std.testing.expectEqualStrings("The sky question is simple.", on.reasoning.items); + var high = try send(.{}, chat_reply, 4096, ask ++ ",\"reasoning_effort\":\"high\"}"); + defer high.deinit(); + try std.testing.expectEqualStrings("xhigh", high.effort[0..high.effort_len]); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 47837fb69c7..0ce694f5a5d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -61,6 +61,7 @@ test { _ = @import("reply_text.zig"); _ = @import("reply_incremental_test.zig"); _ = @import("recipient_reply_test.zig"); + _ = @import("recipient_cut_test.zig"); _ = @import("tool_parse.zig"); _ = @import("tool_lfm2.zig"); _ = @import("tool_lfm2_stream_test.zig"); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index e18c9bc92d9..b25088eb0d2 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -148,6 +148,8 @@ pub const Server = struct { close_id: ?u32 = null, // the close marker's own token, when the marker is one token chunks: chunk_plan.Plan = .{}, effort_levels: []const []const u8 = &.{}, + /// The effort a recipient template hears with thinking off: it has no switch, so its lowest level, not its default. + off_effort: ?[]const u8 = null, thinking_switch: bool = false, video_decoder: bool = false, // libtfvideo loaded in `init`: with the video offer it decides video input (#3004) eos: []const u32 = &.{}, @@ -233,6 +235,7 @@ pub const Server = struct { srv.recipients = recipient_reply.detect(text); const source = text.templateSource(); srv.effort_levels = try fields.effortLevels(a, source); + if (srv.recipients and srv.effort_levels.len > 0) srv.off_effort = fields.coerceEffort("minimal", srv.effort_levels); // MiniMax-M3's template decides on its own; thinking off closes the block in the prompt (prompt.zig) srv.thinking_switch = minimax or std.mem.indexOf(u8, source, "enable_thinking") != null or std.mem.indexOf(u8, source, "thinking_mode") != null; From e97c96db97f54bf920c7dcc59cc0419e8172e0c5 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 27 Oct 2026 10:46:14 +1100 Subject: [PATCH 145/158] server: recipient replies: a streamed split reads only the bytes since the last call; a reply with no markup streams as it comes --- zig/src/server/chat_generation.zig | 4 +- zig/src/server/recipient_reply.zig | 169 ++++++++++++++++++------ zig/src/server/recipient_reply_test.zig | 46 ++++++- 3 files changed, 175 insertions(+), 44 deletions(-) diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index f98a828d23d..69fb3c771b3 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -156,7 +156,7 @@ pub const Generation = struct { if (g.thinking or g.recipient != null) { const original_close = try g.visible.closeOf(g.a, reply_text.decodeText, g.srv.text, g.srv.close_id); const close = try @import("tool_minimax.zig").closeAfterRewrite(g.a, raw_visible, g.tools, original_close); - const split = if (g.recipient) |r| try r.split(g.a, text, .streaming) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); + const split = if (g.recipient) |*r| try r.split(g.a, text, .streaming) else try reply_text.splitThinkingAt(g.a, text, false, g.srv.markers, close); thought = g.streamed_reasoning.after(reply_text.pyStrip(split.reasoning), true); // the whole reply strips it if (thought.len > 0) try g.streamed_reasoning.set(g.a, reply_text.pyStrip(split.reasoning), thought); answer = split.answer; @@ -310,7 +310,7 @@ pub const Generation = struct { const r = reply_text.pyStrip(n.reasoning); reasoning = if (r.len > 0) r else null; } else if (read) { - const split = if (g.recipient) |r| try r.split(a, text, if (std.mem.eql(u8, reason, "length")) .cut else if (g.stops.matched(raw) != null) .stopped else .ended) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); + const split = if (g.recipient) |*r| try r.split(a, text, if (std.mem.eql(u8, reason, "length")) .cut else if (g.stops.matched(raw) != null) .stopped else .ended) else try reply_text.splitThinkingAt(a, text, true, g.srv.markers, close_at.?); const r = reply_text.pyStrip(split.reasoning); reasoning = if (r.len > 0) r else null; content = split.answer; diff --git a/zig/src/server/recipient_reply.zig b/zig/src/server/recipient_reply.zig index b90c64e1dba..cdc7bcea40f 100644 --- a/zig/src/server/recipient_reply.zig +++ b/zig/src/server/recipient_reply.zig @@ -45,14 +45,6 @@ fn kindOf(header: []const u8) Kind { return .call; } -/// One message's text after the last, a blank line between; leading whitespace off, so a streamed piece only grows. -fn add(a: Allocator, out: *std.ArrayList(u8), body: []const u8) Allocator.Error!void { - const piece = reply_text.pyLstrip(body); - if (piece.len == 0) return; - if (out.items.len > 0) try out.appendSlice(a, "\n\n"); - try out.appendSlice(a, piece); -} - /// The template's attribute escapes (`esc_attr`) undone. fn unescape(a: Allocator, s: []const u8) Allocator.Error![]const u8 { if (std.mem.indexOfScalar(u8, s, '&') == null) return s; @@ -118,6 +110,41 @@ pub fn calls(a: Allocator, body: []const u8, recipient: []const u8, tools: []con return if (out.items.len > 0) out.items else null; } +/// The open message of a reply being read: its kind, recipient and body start, how far it was scanned and sent. +const Open = struct { kind: Kind, recipient: []const u8, b0: usize, scan: usize, sent: usize = 0, begun: bool = false }; + +/// The longest closer less a byte: a closer that began before a scan's end is found from this far back. +const reach = blk: { + var n: usize = 0; + for (closers) |e| n = @max(n, e.len); + break :blk n - 1; +}; + +/// `bytes` after `out`'s; a full list moves to a buffer twice the size, the old left intact for earlier splits. +fn keep(a: Allocator, out: *std.ArrayList(u8), bytes: []const u8) Allocator.Error!void { + if (out.items.len + bytes.len > out.capacity) { + const cap = @max(256, 2 * (out.items.len + bytes.len)); + const mem = try a.alloc(u8, cap); + @memcpy(mem[0..out.items.len], out.items); + out.items = mem[0..out.items.len]; + out.capacity = cap; + } + out.appendSliceAssumeCapacity(bytes); +} + +/// A stream's message text since the last call: the body's new bytes, leading whitespace off and a blank line first. +fn grow(a: Allocator, out: *std.ArrayList(u8), o: *Open, body: []const u8) Allocator.Error!void { + var piece = body[@min(o.sent, body.len)..]; + o.sent = @max(o.sent, body.len); + if (!o.begun) { + piece = reply_text.pyLstrip(piece); + if (piece.len == 0) return; + o.begun = true; + if (out.items.len > 0) try keep(a, out, "\n\n"); + } + try keep(a, out, piece); +} + /// How one chat's reply reads: the message its prompt left open, the request's tools and thinking switch. pub const Reading = struct { /// The prompt after its last `<|start|>` when no end follows it (`assistant`, or `assistant to=self<|message|>`). @@ -125,6 +152,21 @@ pub const Reading = struct { tools: []const Value = &.{}, /// Thinking on: `self` messages are the reasoning; off, they stay out of the reply. reasoning: bool = true, + /// What a streamed reply's text gave so far: each call reads only the bytes after the last (the reply grows). + st: State = .{}, + + const State = struct { + ready: bool = false, + at: usize = 0, // the reply read up to here: closed messages before it, or the open message's body start + open: ?Open = null, + any: bool = false, // a message seen + first: bool = true, // the next header is the reply's first, which the prompt's lead begins + reasoning: std.ArrayList(u8) = .empty, + answer: std.ArrayList(u8) = .empty, + len: usize = 0, // the reply's length at the last call, and its last bytes (the same reply grew since) + tail: [32]u8 = undefined, + tail_n: usize = 0, + }; pub fn of(a: Allocator, text: anytype, prompt: []const u32, tools: []const Value, thinking: bool) Allocator.Error!Reading { var r: Reading = .{ .tools = tools, .reasoning = thinking }; @@ -136,47 +178,92 @@ pub const Reading = struct { return r; } + /// A fresh read: new lists (an earlier split's text stays as it was), the lead's open message if it has one. + fn restart(r: *Reading, a: Allocator) Allocator.Error!void { + r.st = .{ .ready = true }; + const m = findTag(r.lead, 0, message) orelse return; + var header = r.lead[0..m]; + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + r.st.open = .{ .kind = kindOf(header), .recipient = try a.dupe(u8, recipientOf(header) orelse ""), .b0 = 0, .scan = 0 }; + r.st.any = true; + r.st.first = false; + } + + /// Whether `reply` is the last call's reply grown (else the read starts over). + fn grew(r: *const Reading, reply: []const u8) bool { + const st = &r.st; + if (!st.ready or reply.len < st.len) return false; + return std.mem.eql(u8, reply[st.len - st.tail_n .. st.len], st.tail[0..st.tail_n]); + } + + fn mark(r: *Reading, reply: []const u8) void { + r.st.len = reply.len; + r.st.tail_n = @min(reply.len, r.st.tail.len); + @memcpy(r.st.tail[0..r.st.tail_n], reply[reply.len - r.st.tail_n ..]); + } + + /// A reply with no header at its start (none in the prompt's lead): all of it is the answer, streamed as it comes. + fn plain(r: *const Reading, reply: []const u8, end: End) ?[]const u8 { + if (r.st.any) return null; + const p = reply_text.pyLstrip(reply); + if (std.mem.startsWith(u8, p, "<|") or std.mem.startsWith(u8, p, "to=")) return null; + if (end == .streaming and (p.len == 0 or std.mem.startsWith(u8, "<|", p) or std.mem.startsWith(u8, "to=", p))) return ""; + return reply_text.pyStrip(p); + } + + /// An open message's text into the split: reasoning and answer as they grow, a call once closed or at the end. + fn body(r: *Reading, a: Allocator, o: *Open, text: []const u8, done: bool, as: End) Allocator.Error!void { + switch (o.kind) { + .reasoning => if (r.reasoning) try grow(a, &r.st.reasoning, o, text), + .answer => try grow(a, &r.st.answer, o, text), + .call => if (done and !o.begun) try grow(a, &r.st.answer, o, (try calls(a, text, o.recipient, r.tools, as)) orelse text), + } + } + /// (reasoning, answer) so far; a stream holds back open headers, calls and partial markers, so each split grows. - pub fn split(r: Reading, a: Allocator, reply: []const u8, end: End) Allocator.Error!Split { - const full = if (r.lead.len > 0) try std.mem.concat(a, u8, &.{ r.lead, reply }) else reply; - var reasoning: std.ArrayList(u8) = .empty; - var answer: std.ArrayList(u8) = .empty; - var pos: usize = 0; - var any = false; - while (findTag(full, pos, message)) |m| { // the reply goes on from the prompt's lead - var header = full[pos..m]; - if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; - const b0 = m + message.len; - var b1 = full.len; - var next = full.len; + pub fn split(r: *Reading, a: Allocator, reply: []const u8, end: End) Allocator.Error!Split { + if (!r.grew(reply)) try r.restart(a); + defer r.mark(reply); + if (r.plain(reply, end)) |p| return .{ .reasoning = "", .answer = p }; + const st = &r.st; + while (true) { + if (st.open == null) { // the next header, the lead before the reply's first + const m = findTag(reply, st.at, message) orelse break; + var header = reply[st.at..m]; + if (st.first) header = try std.mem.concat(a, u8, &.{ r.lead, header }); + if (std.mem.startsWith(u8, header, start)) header = header[start.len..]; + st.first = false; + st.any = true; + st.open = .{ .kind = kindOf(header), .recipient = try a.dupe(u8, recipientOf(header) orelse ""), .b0 = m + message.len, .scan = m + message.len }; + st.at = m + message.len; + } + const o = &st.open.?; + var b1 = reply.len; + var next = reply.len; var closed = false; - for (closers) |e| if (findTag(full[0..b1], b0, e)) |at| { + for (closers) |e| if (findTag(reply[0..b1], o.scan, e)) |at| { b1 = at; next = if (std.mem.eql(u8, e, start)) at else at + e.len; closed = true; }; - any = true; - if (!closed and end == .streaming) { - var held: usize = 0; - for (closers) |e| held = @max(held, reply_text.partialTag(full[b0..b1], e)); - b1 -= held; - } - const body = full[b0..b1]; - switch (kindOf(header)) { - .reasoning => if (r.reasoning) try add(a, &reasoning, body), - .answer => try add(a, &answer, body), - .call => if (closed or end != .streaming) { - const as = if (closed) .ended else end; - try add(a, &answer, (try calls(a, body, recipientOf(header).?, r.tools, as)) orelse body); - }, + if (closed) { + try r.body(a, o, reply[o.b0..b1], true, .ended); + st.open = null; + st.at = next; + continue; } - if (!closed) break; - pos = next; + o.scan = @max(o.b0, reply.len -| reach); // a closer begun before the end is found next call + if (end == .streaming) { + var held: usize = 0; + for (closers) |e| held = @max(held, reply_text.partialTag(reply[o.b0..], e)); + try r.body(a, o, reply[o.b0 .. reply.len - held], false, end); + } else try r.body(a, o, reply[o.b0..], true, end); + break; } - if (!any and end != .streaming) { // no message markup at all; a header the reply was cut in is no answer - const plain = reply_text.pyStrip(reply); - return .{ .reasoning = "", .answer = if (std.mem.startsWith(u8, plain, "to=")) "" else plain }; + if (!st.any and end != .streaming) { // no message markup at all; a header the reply was cut in is no answer + const p = reply_text.pyStrip(reply); + return .{ .reasoning = "", .answer = if (std.mem.startsWith(u8, p, "to=")) "" else p }; } - return .{ .reasoning = reasoning.items, .answer = answer.items }; + return .{ .reasoning = st.reasoning.items, .answer = st.answer.items }; } }; diff --git a/zig/src/server/recipient_reply_test.zig b/zig/src/server/recipient_reply_test.zig index 21ddb054d0c..322189f5df9 100644 --- a/zig/src/server/recipient_reply_test.zig +++ b/zig/src/server/recipient_reply_test.zig @@ -243,7 +243,7 @@ test "recipient replies: a split while streaming only grows, holds calls back, a defer arena.deinit(); const a = arena.allocator(); const reply = call_reply[0 .. call_reply.len - "<|eot|>".len]; - const reading: recipient_reply.Reading = .{ .lead = "assistant", .tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array }; + var reading: recipient_reply.Reading = .{ .lead = "assistant", .tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array }; const done = try reading.split(a, reply, .ended); try std.testing.expectEqualStrings("Two forecasts are needed.", done.reasoning); const xml = "\n\n\n{s}\n\n\n{s}\n\n" ++ @@ -383,3 +383,47 @@ test "recipient replies: thinking off keeps self messages out of the reply and t defer high.deinit(); try std.testing.expectEqualStrings("xhigh", high.effort[0..high.effort_len]); } + +test "recipient replies: a streamed read goes on from the last call and equals a fresh read at every length" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; + for ([_][]const u8{ chat_reply, call_reply, " to=self<|message|>x<|eo" }) |reply| for ([_][]const u8{ "assistant", "assistant to=self<|message|>" }) |lead| { + var going: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + for (1..reply.len + 1) |n| { + var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + const want = try fresh.split(a, reply[0..n], .streaming); + const got = try going.split(a, reply[0..n], .streaming); + try std.testing.expectEqualStrings(want.reasoning, got.reasoning); + try std.testing.expectEqualStrings(want.answer, got.answer); + } + for ([_]recipient_reply.End{ .ended, .cut }) |end| { + var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; + var done = going; + const want = try fresh.split(a, reply, end); + const got = try done.split(a, reply, end); + try std.testing.expectEqualStrings(want.reasoning, got.reasoning); + try std.testing.expectEqualStrings(want.answer, got.answer); + } + }; +} + +test "recipient replies: a reply with no markup streams as it comes; one that may still be a header waits" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var r: recipient_reply.Reading = .{ .lead = "assistant" }; + const reply = " Blue sky, mostly. "; + var last: []const u8 = ""; + for (1..reply.len + 1) |n| { + const s = (try r.split(a, reply[0..n], .streaming)).answer; + try std.testing.expect(std.mem.startsWith(u8, s, last) and std.mem.startsWith(u8, "Blue sky, mostly.", s)); + last = s; + } + try std.testing.expectEqualStrings("Blue sky, mostly", (try r.split(a, reply[0 .. reply.len - 2], .streaming)).answer); + try std.testing.expectEqualStrings("Blue sky, mostly.", (try r.split(a, reply, .ended)).answer); + var h: recipient_reply.Reading = .{ .lead = "assistant" }; + for ([_][]const u8{ " t", " to", " to=se", " <" }) |p| try std.testing.expectEqualStrings("", (try h.split(a, p, .streaming)).answer); + try std.testing.expectEqualStrings("hi", (try h.split(a, " to=user<|message|>hi", .streaming)).answer); +} From 6c959be1438bfa39ac24f296fc18e9a411ccb088 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Tue, 27 Oct 2026 12:15:28 +1100 Subject: [PATCH 146/158] server: recipient replies: a streamed message holds its trailing whitespace back, as the finished reply strips it --- zig/src/server/recipient_reply.zig | 5 +++-- zig/src/server/recipient_reply_test.zig | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/zig/src/server/recipient_reply.zig b/zig/src/server/recipient_reply.zig index cdc7bcea40f..c2fdcb4f5c1 100644 --- a/zig/src/server/recipient_reply.zig +++ b/zig/src/server/recipient_reply.zig @@ -132,8 +132,9 @@ fn keep(a: Allocator, out: *std.ArrayList(u8), bytes: []const u8) Allocator.Erro out.appendSliceAssumeCapacity(bytes); } -/// A stream's message text since the last call: the body's new bytes, leading whitespace off and a blank line first. -fn grow(a: Allocator, out: *std.ArrayList(u8), o: *Open, body: []const u8) Allocator.Error!void { +/// A message's new text since the last call, its end's whitespace held back (the finished reply strips it). +fn grow(a: Allocator, out: *std.ArrayList(u8), o: *Open, text: []const u8) Allocator.Error!void { + const body = reply_text.pyRstrip(text); var piece = body[@min(o.sent, body.len)..]; o.sent = @max(o.sent, body.len); if (!o.begun) { diff --git a/zig/src/server/recipient_reply_test.zig b/zig/src/server/recipient_reply_test.zig index 322189f5df9..d08480daa9e 100644 --- a/zig/src/server/recipient_reply_test.zig +++ b/zig/src/server/recipient_reply_test.zig @@ -389,7 +389,8 @@ test "recipient replies: a streamed read goes on from the last call and equals a defer arena.deinit(); const a = arena.allocator(); const tools = (try json.parse(a, weather[",\"tools\":".len..])).ok.array; - for ([_][]const u8{ chat_reply, call_reply, " to=self<|message|>x<|eo" }) |reply| for ([_][]const u8{ "assistant", "assistant to=self<|message|>" }) |lead| { + const spaced = " to=self<|message|>Think.\n\nMore.\n\n<|eom|><|start|>assistant to=user<|message|>Done. \n<|eot|>"; + for ([_][]const u8{ chat_reply, call_reply, " to=self<|message|>x<|eo", spaced }) |reply| for ([_][]const u8{ "assistant", "assistant to=self<|message|>" }) |lead| { var going: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; for (1..reply.len + 1) |n| { var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; @@ -397,6 +398,7 @@ test "recipient replies: a streamed read goes on from the last call and equals a const got = try going.split(a, reply[0..n], .streaming); try std.testing.expectEqualStrings(want.reasoning, got.reasoning); try std.testing.expectEqualStrings(want.answer, got.answer); + for ([_][]const u8{ got.reasoning, got.answer }) |t| try std.testing.expect(t.len == 0 or !std.ascii.isWhitespace(t[t.len - 1])); } for ([_]recipient_reply.End{ .ended, .cut }) |end| { var fresh: recipient_reply.Reading = .{ .lead = lead, .tools = tools }; From c1e9398a0e10ff58c8da9cc3841e59789e371bf8 Mon Sep 17 00:00:00 2001 From: ajensenwaud Date: Wed, 28 Oct 2026 07:28:12 +1100 Subject: [PATCH 147/158] server: the sampling-field flag reader moves to fields.zig With main's loop-guard stop, chat.zig plus the recipient-reply hook reached 603 lines, past lean's 600. flag (Python's bool(fields.get(key))) is a fields helper, so it moves there unchanged; chat.zig calls fields_mod.flag. --- zig/src/server/chat.zig | 15 ++++----------- zig/src/server/fields.zig | 7 +++++++ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 5c62ae6f9b4..3eb1098fd7f 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -122,13 +122,6 @@ test "Server recovery: token staging allocation failure ends the loop without co } } -/// Python's ``bool(fields.get(key))`` on the sampling fields. -fn flag(f: Value, key: []const u8) ?bool { - const v = f.get(key) orelse return null; - if (v == .null) return null; - return v.truthy(); -} - /// A request rendered and checked but not submitted; it holds the preparing count until generate or release. pub const Prepared = struct { input: Input, @@ -162,13 +155,13 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa if (preparing) _ = srv.preparing.fetchAdd(1, .acq_rel); errdefer srv.release(preparing, null); if (gone.check()) return error.Cancelled; - const thinking = input.prompt == null and (flag(f, "enable_thinking") orelse srv.config.enable_thinking); + const thinking = input.prompt == null and (fields_mod.flag(f, "enable_thinking") orelse srv.config.enable_thinking); const instruct = input.prompt == null and !thinking and !input.own; // a client's chat with thinking off may take --instruct-sampling's set const reasoning = thinking and srv.info.capability(.reasoning) and (srv.text.vtable.format != .kimi or input.prompt == null); // the prompt renders `thinking`; the reply reads `reasoning` const asked = if (f.get("reasoning_effort")) |e| (if (e == .string) e.string else null) else null; const effort = srv.effortFor(asked); cx.named_effort = if (input.prompt == null) fields_mod.namedEffort(asked, srv.effort_levels) else null; // a raw prompt has no template - cx.clear_thinking = flag(f, "clear_thinking"); + cx.clear_thinking = fields_mod.flag(f, "clear_thinking"); cx.template_fields = f; const rendered = try prompt_mod.prepare(srv, cx, input, thinking, effort); if (gone.check()) return error.Cancelled; @@ -233,7 +226,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa request.prompt_logprobs = input.prompt_logprobs; if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); if (input.trace) |trace| trace.prepared(&request, thinking, effort); - return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; + return .{ .input = input, .request = request, .prompt_len = rendered.ids.len, .received = received, .thinking = thinking, .reasoning = reasoning, .effort = effort, .sampled = sampling != null, .drafts = drafts, .token_ids = fields_mod.flag(f, "return_token_ids") orelse false, .stops = stops_opt, .preparing = preparing, .frames = rendered.frames }; } /// Submit a prepared request and collect its reply; ``sink`` hears the stream (null: not streamed). @@ -276,7 +269,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .recover = input.prompt == null and request.structure == null }; defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished if (srv.recipients and input.prompt == null) gen.recipient = try recipient_reply.Reading.of(a, srv.text, request.prompt, input.tools, prepared.reasoning); diff --git a/zig/src/server/fields.zig b/zig/src/server/fields.zig index aad8720a231..c1449a84bb3 100644 --- a/zig/src/server/fields.zig +++ b/zig/src/server/fields.zig @@ -22,6 +22,13 @@ pub fn typeName(v: Value) []const u8 { }; } +/// Python's ``bool(fields.get(key))`` on the sampling fields. +pub fn flag(f: Value, key: []const u8) ?bool { + const v = f.get(key) orelse return null; + if (v == .null) return null; + return v.truthy(); +} + /// ``fields.get`` on a body that is not an object fails as Python's AttributeError does. pub fn requireObject(cx: *Cx, v: Value) errors.Refused!void { if (v != .object) return cx.fail(.other, "'{s}' object has no attribute 'get'", .{typeName(v)}); From 6289c5afe360df17601991bd8d229e5b6d70d0cb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:18:52 -0800 Subject: [PATCH 148/158] server: move the late-system probe to keep server.zig within 600 lines --- zig/src/server/late_system.zig | 14 ++++++++++++++ zig/src/server/server.zig | 9 +-------- 2 files changed, 15 insertions(+), 8 deletions(-) create mode 100644 zig/src/server/late_system.zig diff --git a/zig/src/server/late_system.zig b/zig/src/server/late_system.zig new file mode 100644 index 00000000000..b63efe0052e --- /dev/null +++ b/zig/src/server/late_system.zig @@ -0,0 +1,14 @@ +//! The startup probe for a template's late system role. +const std = @import("std"); +const json = @import("json"); +const model_text = @import("model_text.zig"); +const Allocator = std.mem.Allocator; + +/// ``template_late_system``: "system" when the template keeps a later system message in place, else "user". +pub fn lateSystem(a: Allocator, text: model_text.Text) ![]const u8 { + const probe_text = "tensorfold-late-system-probe"; + const probe = (try json.parse(a, "[{\"role\": \"system\", \"content\": \"s\"}, {\"role\": \"user\", \"content\": \"u\"}, {\"role\": \"assistant\", \"content\": \"a\"}, {\"role\": \"system\", \"content\": \"tensorfold-late-system-probe\"}, {\"role\": \"user\", \"content\": \"v\"}]")).ok; + var problem: []const u8 = ""; + const rendered = text.render(a, probe, .{ .add_generation_prompt = false }, &problem) catch return "user"; + return if (std.mem.indexOf(u8, rendered.text, probe_text) != null) "system" else "user"; +} diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index b25088eb0d2..2a3009396f0 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -563,14 +563,7 @@ fn seedBits(v: Value) u64 { if (std.fmt.parseInt(i128, v.int, 10)) |n| return @truncate(@as(u128, @bitCast(n))) else |_| return 0; } -/// ``template_late_system``: "system" when the template keeps a later system message in place, else "user". -fn lateSystem(a: Allocator, text: model_text.Text) ![]const u8 { - const probe_text = "tensorfold-late-system-probe"; - const probe = (try json.parse(a, "[{\"role\": \"system\", \"content\": \"s\"}, {\"role\": \"user\", \"content\": \"u\"}, {\"role\": \"assistant\", \"content\": \"a\"}, {\"role\": \"system\", \"content\": \"tensorfold-late-system-probe\"}, {\"role\": \"user\", \"content\": \"v\"}]")).ok; - var problem: []const u8 = ""; - const rendered = text.render(a, probe, .{ .add_generation_prompt = false }, &problem) catch return "user"; - return if (std.mem.indexOf(u8, rendered.text, probe_text) != null) "system" else "user"; -} +const lateSystem = @import("late_system.zig").lateSystem; /// With image input: whether a user turn holding an image part renders an image placeholder (else a startup warning). fn templateImages(srv: *Server) bool { From 425f8aa71e5ace76030655877f3350357d01c41e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:56:40 +0000 Subject: [PATCH 149/158] changelog: #1336 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8209934176..07902162afb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: replies in recipient-addressed messages (`to=self` … `<|eom|>`, `to=user` … `<|eot|>`, as Muse Spark Open's chat template writes them) are split into reasoning, answer and tool calls, where the whole reply, markers included, ended up in `content` (#1336). Thanks to @ajensenwaud. + - App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. - GLM-5.3-Flash on Metal: on Macs without tensor units (before M5), prompt processing uses vectorized GLM-only matmul, KDA and indexer kernels with 32-row matmul tiles; M5 Macs and every other Metal family keep their kernels, and the author's token hashes match main (#3921, refs #3152). Thanks to @gilby. From 2ead06352c5561797bfe81367127f9ce00165fd0 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:48:13 +0100 Subject: [PATCH 150/158] KV pool: host tier A Tier beside the Pool for families whose pages are cached on the device from a host store. The pool stays the only owner of page ids and of what is promised; the tier adds a second currency (device frames a stream may pin at once), the page-to-frame mapping, an LRU order, pins for the frames a call reads, a dirty flag so a frame is dropped only once its rows reached the host store, and a generation per frame so a table written before a frame was recycled is told from a current one. A stream can also be lent frames for its life, mapped to no page, for a family that manages them itself. The pool tells the tier when a page loses its last holder. It moves no bytes and uses no device API: the family copies what a miss names, and a snapshot reads canonical rows from the host store. Tests: reservation conservation in both currencies, eviction order, pin rules, lent frames, generation safety, canonical rows, a randomised serving loop that audits the mapping and checks every row read against the last write, two ranks in lockstep (and a step or a lent count taken by one rank caught by the digest), and mutants (no generation, no pin rule, dirty frames unpinned) that the checks fail on. A failed batch unmaps the misses it mapped (their generation moves on), a page is marked dirty only under a pin of the marking lease, a stream cannot end while it holds the last pin of a dirty page, and a family can lend a run of consecutive frames (lendRun). --- zig/src/core/kv_pool.zig | 12 + zig/src/core/kv_tier.zig | 432 ++++++++++++++++++++++++++ zig/src/core/kv_tier_test.zig | 564 ++++++++++++++++++++++++++++++++++ 3 files changed, 1008 insertions(+) create mode 100644 zig/src/core/kv_tier.zig create mode 100644 zig/src/core/kv_tier_test.zig diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index 0179b930ff2..d1912792608 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -216,6 +216,12 @@ pub const Notify = struct { /// A family's pool as the load ledger reads it: tokens a page, and the contiguous run it needs (0: none). pub const Source = struct { pool: *Pool, page_tokens: u32, run_pages: u32 = 0 }; +/// A tier's notice that a page lost its last holder (its frame, if any, is free again). +pub const Freed = struct { + ctx: *anyopaque, + call: *const fn (ctx: *anyopaque, id: u32) void, +}; + /// What an idle pool must show: nothing promised, every page free or the store's alone, none waiting on readers. pub const Census = struct { total: usize, free: usize, promised: usize, kept: usize, leased: usize, pending: usize = 0 }; @@ -237,6 +243,7 @@ pub const Pool = struct { ledger: ?Gate = null, // the lane host's ledger, the only test a promise passes; null: the pool's own pages depth: u8 = 0, // public changes in progress: the outermost one notifies, after nested calls and rollbacks retired: retirement.Retired = .{}, // pages a lease gave back mid-stream, until their readers are done + freed: ?Freed = null, pub fn init(gpa: Allocator, count: usize, page_bytes: u64) !Pool { const refs = try gpa.alloc(u32, count); @@ -557,8 +564,13 @@ pub const Pool = struct { } }; +/// The host tier: logical pages in host RAM and device frames that cache them (kv_tier.zig). +pub const tier = @import("kv_tier.zig"); +pub const Tier = tier.Tier; + test { _ = @import("kv_pool_test.zig"); + _ = @import("kv_tier.zig"); _ = @import("kv_pool_counts_test.zig"); _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig new file mode 100644 index 00000000000..3d40f1d98ca --- /dev/null +++ b/zig/src/core/kv_tier.zig @@ -0,0 +1,432 @@ +//! A host tier for the page pool: logical pages whose canonical rows live in host RAM, cached by device frames. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const Allocator = std.mem.Allocator; + +/// No frame (for a page) or no page (for a frame). +pub const none: u32 = std.math.maxInt(u32); + +/// What the ranks of one model agree on before they open a tier: the smallest of each. +pub const Shape = struct { + host_pages: usize, + frames: usize, + + pub fn agree(a: Shape, b: Shape) Shape { + return .{ .host_pages = @min(a.host_pages, b.host_pages), .frames = @min(a.frames, b.frames) }; + } +}; + +/// A deliberate bug a test turns on to show that the check beside it fails without the rule: never set outside tests. +pub const Fault = enum { none, keep_generation, ignore_pins, ignore_dirty, unpinned_dirty, keep_failed_miss }; + +/// A page a call pinned: its frame, the frame's generation, and whether the family must copy the page in. +pub const Fill = struct { page: u32, frame: u32, gen: u32, miss: bool }; + +/// A page's frame as a device table saw it: current while the frame's generation is the same. +pub const Ticket = struct { frame: u32, gen: u32 }; + +/// A stream's reservation in both currencies: pages (the pool's lease) and the frames it may pin at once. +pub const Lease = struct { + pages: kv.Lease = .{}, + frames: usize = 0, + pins: std.ArrayList(u32) = .empty, // one entry per pin, a page id + lent: std.ArrayList(u32) = .empty, // frames lent to the stream: mapped to no page, the family's to manage +}; + +pub const Census = struct { frames: usize, free: usize, resident: usize, pinned: usize, dirty: usize, promised: usize, lent: usize }; + +pub const Tier = struct { + gpa: Allocator, + pool: kv.Pool, // logical pages; the host store holds `pool.total()` of them + host: []u8, // canonical rows, `pool.total() * page_bytes`, borrowed (pinned host memory in a server) + frame_of: []u32, // per page: its frame or `none` + dirty: []bool, // per page: the frame holds rows the host store lacks + page_of: []u32, // per frame: its page or `none` + gen: []u32, // per frame: changes whenever the frame stops holding the page it held + stamp: []u64, // per frame: the LRU clock at its last use + pinned: []u32, // per frame: calls reading it + free_frames: []u32, + lent_mark: []bool, // per frame: lent to a lease + nfree: usize, + promised: usize = 0, // frames promised, summed over leases + nlent: usize = 0, // frames lent, summed over leases + clock: u64 = 0, + fault: Fault = .none, + + /// In place (the pool's release hook points here): `host.len / page_bytes` logical pages, `frames` frames. + pub fn init(t: *Tier, gpa: Allocator, host: []u8, frames: usize, page_bytes: u64) !void { + const npages: usize = @intCast(host.len / page_bytes); + var pool = try kv.Pool.init(gpa, npages, page_bytes); + errdefer pool.deinit(); + const frame_of = try gpa.alloc(u32, npages); + errdefer gpa.free(frame_of); + const dirty = try gpa.alloc(bool, npages); + errdefer gpa.free(dirty); + const page_of = try gpa.alloc(u32, frames); + errdefer gpa.free(page_of); + const gen = try gpa.alloc(u32, frames); + errdefer gpa.free(gen); + const stamp = try gpa.alloc(u64, frames); + errdefer gpa.free(stamp); + const pinned = try gpa.alloc(u32, frames); + errdefer gpa.free(pinned); + const free_frames = try gpa.alloc(u32, frames); + errdefer gpa.free(free_frames); + const lent_mark = try gpa.alloc(bool, frames); + @memset(frame_of, none); + @memset(dirty, false); + @memset(page_of, none); + @memset(gen, 0); + @memset(stamp, 0); + @memset(pinned, 0); + @memset(lent_mark, false); + for (free_frames, 0..) |*f, i| f.* = @intCast(frames - 1 - i); // frame 0 first + t.* = .{ .gpa = gpa, .pool = pool, .host = host, .frame_of = frame_of, .dirty = dirty, .page_of = page_of, .gen = gen, .stamp = stamp, .pinned = pinned, .free_frames = free_frames, .lent_mark = lent_mark, .nfree = frames }; + t.pool.freed = .{ .ctx = t, .call = freed }; + } + + pub fn deinit(t: *Tier) void { + t.pool.deinit(); + t.gpa.free(t.frame_of); + t.gpa.free(t.dirty); + t.gpa.free(t.page_of); + t.gpa.free(t.gen); + t.gpa.free(t.stamp); + t.gpa.free(t.pinned); + t.gpa.free(t.free_frames); + t.gpa.free(t.lent_mark); + t.* = undefined; + } + + pub fn count(t: *const Tier) usize { + return t.page_of.len; + } + + pub fn shape(t: *const Tier) Shape { + return .{ .host_pages = t.pool.total(), .frames = t.count() }; + } + + /// Promise `pages` pages and `n` frames to `l`, or neither: LaneMemory or FrameMemory, whichever does not fit. + pub fn reserve(t: *Tier, l: *Lease, pages: usize, n: usize) error{ LaneMemory, FrameMemory }!void { + if (t.promised + n > t.count()) return error.FrameMemory; + try t.pool.promise(&l.pages, pages); + t.promised += n; + l.frames += n; + } + + /// Whether `pages` and `n` frames could be promised now (the store's idle pages counted). + pub fn fits(t: *const Tier, pages: usize, n: usize) bool { + return t.promised + n <= t.count() and t.pool.fits(pages); + } + + /// `l` covers `n` pages, as `Pool.cover`. + pub fn cover(t: *Tier, l: *Lease, n: usize, table: ?kv.Table) !void { + return t.pool.cover(&l.pages, n, table); + } + + /// The frame of `id`, if it has one. + pub fn resident(t: *const Tier, id: u32) ?Ticket { + const f = t.frame_of[id]; + return if (f == none) null else .{ .frame = f, .gen = t.gen[f] }; + } + + /// Whether a table entry written from `tk` still names `id`'s rows. + pub fn valid(t: *const Tier, id: u32, tk: Ticket) bool { + return t.page_of[tk.frame] == id and t.gen[tk.frame] == tk.gen; + } + + /// Pin `id` for a call: a frame if it has none (a miss: copy `host_page(id)` in); FrameMemory past the promise. + pub fn pin(t: *Tier, l: *Lease, id: u32) error{ FrameMemory, OutOfMemory }!Fill { + if (t.pool.refs[id] == 0) std.debug.panic("kv tier: page {d} pinned while free", .{id}); + if (l.pins.items.len + l.lent.items.len >= l.frames) return error.FrameMemory; + try l.pins.ensureUnusedCapacity(t.gpa, 1); + var miss = false; + if (t.frame_of[id] == none) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.page_of[f] = id; + t.frame_of[id] = f; + miss = true; + } + const f = t.frame_of[id]; + t.pinned[f] += 1; + t.touch(id); + l.pins.appendAssumeCapacity(id); + return .{ .page = id, .frame = f, .gen = t.gen[f], .miss = miss }; + } + + /// Pin every page of `ids` into `out`, or none of them. + pub fn fill(t: *Tier, l: *Lease, ids: []const u32, out: []Fill) !void { + std.debug.assert(out.len >= ids.len); + var done: usize = 0; + errdefer { + for (ids[0..done]) |id| t.unpin(l, id) catch {}; + for (out[0..done]) |o| t.undo(o); // a miss was never copied in: its frame must not stay mapped + } + for (ids, 0..) |id, i| { + out[i] = try t.pin(l, id); + done += 1; + } + } + + /// The frame a failed batch took for a miss goes back unmapped (generation moved on), unless something pins it. + fn undo(t: *Tier, o: Fill) void { + if (t.fault == .keep_failed_miss or !o.miss or t.frame_of[o.page] != o.frame or t.pinned[o.frame] != 0) return; + t.unmap(o.frame); + t.free_frames[t.nfree] = o.frame; + t.nfree += 1; + } + + /// One pin of `id` fewer. Dirty: the last pin of a page whose rows the host store lacks cannot go (sync it first). + pub fn unpin(t: *Tier, l: *Lease, id: u32) error{ NotPinned, Dirty }!void { + var i = l.pins.items.len; + while (i > 0) : (i -= 1) if (l.pins.items[i - 1] == id) break; + if (i == 0) return error.NotPinned; + const f = t.frame_of[id]; + if (t.pinned[f] == 1 and t.dirty[id] and t.fault != .ignore_dirty) return error.Dirty; + _ = l.pins.orderedRemove(i - 1); + t.pinned[f] -= 1; + } + + /// Lend `n` frames to `l` for its life: mapped to no page, never a victim, counted in its promise like pins. + pub fn lend(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!void { + if (l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var taken: usize = 0; + errdefer t.giveBackTo(l, l.lent.items.len - taken); + while (taken < n) : (taken += 1) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(f); + t.nlent += 1; + } + } + + /// Lend `l` `n` consecutive free frames (a family's state run) for its life; the first frame, or FrameMemory. + pub fn lendRun(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!u32 { + if (n == 0 or l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + var start: usize = 0; + var run: usize = 0; + for (t.page_of, t.lent_mark, 0..) |p, m, f| { + if (p == none and !m) run += 1 else run = 0; + if (run == n) { + start = f + 1 - n; + break; + } + } else return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var kept: usize = 0; + for (t.free_frames[0..t.nfree]) |f| if (f < start or f >= start + n) { + t.free_frames[kept] = f; + kept += 1; + }; + t.nfree = kept; + for (start..start + n) |f| { + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(@intCast(f)); + } + t.nlent += n; + return @intCast(start); + } + + /// The frames lent to `l` go back to the free frames, their generation moved on. + pub fn giveBack(t: *Tier, l: *Lease) void { + t.giveBackTo(l, 0); + } + + fn giveBackTo(t: *Tier, l: *Lease, keep: usize) void { + while (l.lent.items.len > keep) { + const f = l.lent.pop().?; + t.gen[f] +%= 1; + t.lent_mark[f] = false; + t.free_frames[t.nfree] = f; + t.nfree += 1; + t.nlent -= 1; + } + } + + /// The LRU clock moves on for `id` (a hit the device saw, or a call that read it). + pub fn touch(t: *Tier, id: u32) void { + const f = t.frame_of[id]; + if (f == none) return; + t.clock += 1; + t.stamp[f] = t.clock; + } + + /// Rows were written into `id`'s frame, which `l` pins: the host store lacks them until `sync`. + pub fn markDirty(t: *Tier, l: *const Lease, id: u32) error{NotPinned}!void { + if (t.fault != .unpinned_dirty and std.mem.indexOfScalar(u32, l.pins.items, id) == null) return error.NotPinned; + if (t.frame_of[id] == none) std.debug.panic("kv tier: page {d} written with no frame", .{id}); + t.dirty[id] = true; + } + + /// The family copied `id`'s frame to `host_page(id)`: the frame may be dropped. + pub fn sync(t: *Tier, id: u32) void { + t.dirty[id] = false; + } + + /// Where a page's canonical rows go (a flush writes here). + pub fn host_page(t: *Tier, id: u32) []u8 { + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// The canonical rows of `id` for a snapshot or a fill; Unsynced while its frame holds rows not flushed yet. + pub fn canonical(t: *const Tier, id: u32) error{Unsynced}![]const u8 { + if (t.dirty[id]) return error.Unsynced; + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// Drop up to `n` unpinned frames, least recently used first; the count dropped. + pub fn evict(t: *Tier, n: usize) usize { + var done: usize = 0; + while (done < n) : (done += 1) { + const f = t.victim() orelse break; + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } + return done; + } + + /// Whether `l` can end: none of its pinned pages is left dirty and unpinned (a page only it holds goes with it). + pub fn canFinish(t: *const Tier, l: *const Lease) bool { + if (t.fault == .ignore_dirty) return true; + for (l.pins.items) |id| { + if (!t.dirty[id]) continue; + const f = t.frame_of[id]; + var mine: usize = 0; // this lease's own pins of the page + for (l.pins.items) |q| mine += @intFromBool(q == id); + if (f != none and t.pinned[f] > mine) continue; // another stream still pins it + const own = std.mem.indexOfScalar(u32, l.pages.ids.items, id) != null; + if (!own or t.pool.refs[id] > 1) return false; + } + for (l.pages.ids.items) |id| if (t.dirty[id] and t.pool.refs[id] > 1) return false; + return true; + } + + /// The stream ended: its pins, frames, promise and pages go back (a page nobody else holds loses its frame). + pub fn finish(t: *Tier, l: *Lease) void { + if (t.fault == .none and !t.canFinish(l)) std.debug.panic("kv tier: a stream ended with unflushed rows pinned or shared", .{}); + for (l.pins.items) |id| { + const f = t.frame_of[id]; + if (f != none) t.pinned[f] -= 1 else if (t.fault == .none) std.debug.panic("kv tier: pinned page {d} lost its frame", .{id}); + } + l.pins.deinit(t.gpa); + t.giveBack(l); + l.lent.deinit(t.gpa); + t.promised -= l.frames; + t.pool.finish(&l.pages); + l.* = .{}; + } + + pub fn census(t: *const Tier) Census { + var c: Census = .{ .frames = t.count(), .free = t.nfree, .resident = 0, .pinned = 0, .dirty = 0, .promised = t.promised, .lent = t.nlent }; + for (t.page_of, t.pinned) |p, n| { + c.resident += @intFromBool(p != none); + c.pinned += @intFromBool(n > 0); + } + for (t.dirty) |d| c.dirty += @intFromBool(d); + return c; + } + + /// Nothing promised, pinned or dirty, and every frame free or holding a page still held (the store's). + pub fn idle(t: *const Tier) bool { + const c = t.census(); + return t.pool.idle() and c.promised == 0 and c.pinned == 0 and c.dirty == 0 and c.lent == 0 and c.free + c.resident == c.frames; + } + + /// The mapping's own consistency; an error names the broken rule. Tests call it after every step. + pub fn audit(t: *const Tier) error{Broken}!void { + var mapped: usize = 0; + for (t.page_of, 0..) |p, f| { + if (p == none) { + if (t.pinned[f] != 0) return error.Broken; // a pin on an empty frame + continue; + } + mapped += 1; + if (t.frame_of[p] != f) return error.Broken; // page and frame disagree + if (t.pool.refs[p] == 0) return error.Broken; // a free page keeps a frame + } + if (mapped + t.nfree + t.nlent != t.count()) return error.Broken; // frames neither free, mapped nor lent, or two + for (t.free_frames[0..t.nfree]) |f| if (t.page_of[f] != none or t.lent_mark[f]) return error.Broken; + var marked: usize = 0; + for (t.lent_mark, t.page_of) |m, p| { + marked += @intFromBool(m); + if (m and p != none) return error.Broken; // a lent frame holds a page + } + if (marked != t.nlent) return error.Broken; + for (t.frame_of, 0..) |f, p| { + if (f != none and t.page_of[f] != p) return error.Broken; + if (t.dirty[p] and f == none) return error.Broken; // unflushed rows with no frame + } + if (t.promised > t.count()) return error.Broken; + } + + /// A hash of what two ranks must hold alike: mapping, generations, LRU order, pins, holders and promises. + pub fn digest(t: *const Tier) u64 { + var h = std.hash.Wyhash.init(0); + h.update(std.mem.sliceAsBytes(t.frame_of)); + h.update(std.mem.sliceAsBytes(t.page_of)); + h.update(std.mem.sliceAsBytes(t.gen)); + h.update(std.mem.sliceAsBytes(t.stamp)); + h.update(std.mem.sliceAsBytes(t.pinned)); + h.update(std.mem.sliceAsBytes(t.free_frames[0..t.nfree])); + h.update(std.mem.sliceAsBytes(t.pool.refs)); + h.update(std.mem.sliceAsBytes(t.pool.free[0..t.pool.nfree])); + const counts = [_]u64{ t.promised, t.pool.promised, t.clock, t.nlent }; + h.update(std.mem.sliceAsBytes(&counts)); + return h.final(); + } + + /// A free frame, or the least recently used unpinned one dropped. + fn takeFrame(t: *Tier) ?u32 { + if (t.nfree > 0) { + t.nfree -= 1; + return t.free_frames[t.nfree]; + } + const f = t.victim() orelse return null; + t.unmap(f); + return f; + } + + /// The mapped frame with the oldest stamp, not pinned and with no unflushed rows (the lowest index among equals). + fn victim(t: *const Tier) ?u32 { + var best: ?u32 = null; + for (t.page_of, 0..) |p, f| { + if (p == none) continue; + if (t.pinned[f] > 0 and t.fault != .ignore_pins) continue; + if (t.dirty[p] and t.fault != .ignore_dirty) continue; + if (best == null or t.stamp[f] < t.stamp[best.?]) best = @intCast(f); + } + return best; + } + + /// The frame stops holding its page: the generation moves on so a table naming it is stale. + fn unmap(t: *Tier, f: u32) void { + const p = t.page_of[f]; + if (t.dirty[p] and t.fault != .ignore_dirty) std.debug.panic("kv tier: frame {d} dropped with page {d} unflushed", .{ f, p }); + t.frame_of[p] = none; + t.dirty[p] = false; + t.page_of[f] = none; + if (t.fault != .keep_generation) t.gen[f] +%= 1; + } + + /// The pool freed `id` (its last holder let go): its frame is free again. + fn freed(ctx: *anyopaque, id: u32) void { + const t: *Tier = @ptrCast(@alignCast(ctx)); + const f = t.frame_of[id]; + if (f == none) return; + if (t.pinned[f] != 0 and t.fault == .none) std.debug.panic("kv tier: page {d} freed while pinned", .{id}); + t.dirty[id] = false; // the page is gone: rows nobody can read need no flush + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } +}; + +test { + _ = @import("kv_tier_test.zig"); +} diff --git a/zig/src/core/kv_tier_test.zig b/zig/src/core/kv_tier_test.zig new file mode 100644 index 00000000000..95437b2bea6 --- /dev/null +++ b/zig/src/core/kv_tier_test.zig @@ -0,0 +1,564 @@ +//! The host tier: two currencies, eviction order, pins, generations, canonical rows, lockstep ranks, mutants. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const kt = @import("kv_tier.zig"); +const Tier = kt.Tier; +const Lease = kt.Lease; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const gpa = std.testing.allocator; + +const page_bytes = 8; + +/// A tier of `pages` logical pages and `frames` frames over a host store and a fake device. +const Rig = struct { + host: []u8, + dev: []u8, + tier: Tier, + + fn open(r: *Rig, pages: usize, frames: usize) !void { + r.host = try gpa.alloc(u8, pages * page_bytes); + errdefer gpa.free(r.host); + @memset(r.host, 0); + r.dev = try gpa.alloc(u8, frames * page_bytes); + errdefer gpa.free(r.dev); + @memset(r.dev, 0); + try r.tier.init(gpa, r.host, frames, page_bytes); + } + + fn close(r: *Rig) void { + r.tier.deinit(); + gpa.free(r.host); + gpa.free(r.dev); + } + + fn frame(r: *Rig, f: u32) []u8 { + return r.dev[f * page_bytes ..][0..page_bytes]; + } + + /// A stream with `pages` pages covered and `frames` frames promised. + fn lease(r: *Rig, pages: usize, frames: usize) !Lease { + return r.leaseLent(pages, frames, 0); + } + + /// A stream that also has `lent` of its frames lent for its life. + fn leaseLent(r: *Rig, pages: usize, frames: usize, lent: usize) !Lease { + var l: Lease = .{}; + errdefer r.tier.finish(&l); + try r.tier.reserve(&l, pages, frames); + try r.tier.cover(&l, pages, null); + try r.tier.lend(&l, lent); + return l; + } + + /// Pin `id`, copying its canonical rows in on a miss. + fn pin(r: *Rig, l: *Lease, id: u32) !kt.Fill { + const f = try r.tier.pin(l, id); + if (f.miss) @memcpy(r.frame(f.frame), r.tier.host_page(id)); + return f; + } + + /// Write `b` into every row byte of the pinned page and flush it to the host store. + fn write(r: *Rig, l: *const Lease, id: u32, b: u8) void { + const tk = r.tier.resident(id).?; + @memset(r.frame(tk.frame), b); + r.tier.markDirty(l, id) catch unreachable; + } + + fn flush(r: *Rig, id: u32) void { + const tk = r.tier.resident(id).?; + @memcpy(r.tier.host_page(id), r.frame(tk.frame)); + r.tier.sync(id); + } +}; + +test "two currencies: a promise that fits one and not the other takes nothing, and finishing returns both" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + try std.testing.expectError(error.FrameMemory, t.reserve(&a, 1, 2)); // frames: 2 + 2 > 3 + try expectEqual(@as(usize, 0), a.pages.promised); + try expectEqual(@as(usize, 2), t.promised); + var b: Lease = .{}; + try std.testing.expectError(error.LaneMemory, t.reserve(&b, 5, 1)); // pages: 4 + 5 > 8 + try expectEqual(@as(usize, 2), t.promised); // the frame promise was not kept + try expectEqual(@as(usize, 0), t.pool.promised); + try expect(!t.fits(5, 1) and t.fits(4, 1) and !t.fits(4, 2)); + var c = try r.lease(4, 1); + try expect(!t.fits(1, 0)); // every page is promised or taken + t.finish(&a); + t.finish(&c); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "a lease cannot pin more frames than it promised, and a failed batch pins nothing" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + var out: [3]kt.Fill = undefined; + const ids = a.pages.ids.items; + try std.testing.expectError(error.FrameMemory, t.fill(&a, ids[0..3], &out)); + try expectEqual(@as(usize, 0), t.census().pinned); + try expectEqual(@as(usize, 0), a.pins.items.len); + try expect(t.resident(ids[0]) == null and t.resident(ids[1]) == null); // the misses of the failed batch were unmapped + try t.fill(&a, ids[0..2], out[0..2]); + try expect(out[0].miss and out[1].miss); + try expectEqual(@as(usize, 2), t.census().pinned); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[2])); + t.finish(&a); + try expect(t.idle()); +} + +test "eviction takes the least recently used unpinned frame, and a touch moves a page to the back" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(6, 1); + const ids = a.pages.ids.items; + for (ids[0..3]) |id| { // one frame promised: pin, read, unpin, three times over + _ = try r.pin(&a, id); + try t.unpin(&a, id); + } + try expectEqual(@as(usize, 3), t.census().resident); + t.touch(ids[0]); // order now 1, 2, 0 + const f = try r.pin(&a, ids[3]); // evicts page 1 + try expect(f.miss); + try expect(t.resident(ids[1]) == null and t.resident(ids[0]) != null and t.resident(ids[2]) != null); + try t.unpin(&a, ids[3]); + try expectEqual(@as(usize, 1), t.evict(1)); // page 2 is next + try expect(t.resident(ids[2]) == null and t.resident(ids[0]) != null); + try expectEqual(@as(usize, 2), t.evict(5)); // 0 and 3: all that is left + try expectEqual(@as(usize, 3), t.census().free); + try t.audit(); + t.finish(&a); +} + +test "pinned frames are never evicted, and a dirty page stays until its rows reach the host store" { + var r: Rig = undefined; + try r.open(8, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 1); + var b = try r.lease(2, 1); + const pa = a.pages.ids.items[0]; + const pb = b.pages.ids.items; + _ = try r.pin(&a, pa); + r.write(&a, pa, 7); + _ = try r.pin(&b, pb[0]); + try t.unpin(&b, pb[0]); + _ = try r.pin(&b, pb[1]); // the one frame that can go is pb[0]'s + try expect(t.resident(pa) != null and t.resident(pb[0]) == null); + try std.testing.expectError(error.Dirty, t.unpin(&a, pa)); + try expectEqual(@as(usize, 0), t.evict(2)); // pa pinned and dirty, pb[1] pinned + try t.unpin(&b, pb[1]); + try expectEqual(@as(usize, 1), t.evict(2)); // only pb[1] + try expect(t.resident(pa) != null); + try std.testing.expectError(error.Unsynced, t.canonical(pa)); + r.flush(pa); + try t.unpin(&a, pa); + try expectEqual(@as(u8, 7), (try t.canonical(pa))[3]); + try expectEqual(@as(usize, 1), t.evict(2)); + t.finish(&a); + t.finish(&b); + try expect(t.idle()); +} + +/// Whether a table entry written before a frame was dropped and filled again with the same page is taken for current. +fn staleAccepted(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 1); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(2, 1); + defer r.tier.finish(&a); + const p = a.pages.ids.items; + const f0 = try r.pin(&a, p[0]); + const old: kt.Ticket = .{ .frame = f0.frame, .gen = f0.gen }; + try r.tier.unpin(&a, p[0]); + _ = try r.pin(&a, p[1]); // the only frame is recycled + try r.tier.unpin(&a, p[1]); + _ = try r.pin(&a, p[0]); // and returns to the first page: same frame, new contents + try r.tier.unpin(&a, p[0]); + return r.tier.valid(p[0], old); +} + +test "generations: a recycled frame is not read through a table written before" { + try expect(!try staleAccepted(.none)); + try expect(try staleAccepted(.keep_generation)); // mutation: without the generation the stale table passes +} + +/// Whether a frame a call pins survives another stream's miss. +fn pinnedSurvives(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(2, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); // the oldest stamp, and pinned + _ = try r.pin(&b, b.pages.ids.items[0]); + try r.tier.unpin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + return r.tier.resident(pa) != null; +} + +test "pin rule: the frame a call holds survives a miss; mutation: ignoring pins evicts it" { + try expect(try pinnedSurvives(.none)); + try expect(!try pinnedSurvives(.ignore_pins)); +} + +test "freeing a page (its last holder lets go) frees its frame; a page the store still holds keeps it" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = try gpa.dupe(u32, a.pages.ids.items); // ids outlive the lease + defer gpa.free(p); + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 5); + r.flush(p[0]); + _ = try r.pin(&a, p[1]); + t.pool.retain(p[0]); // the prompt store keeps the first page + t.finish(&a); + try expect(t.resident(p[0]) != null and t.resident(p[1]) == null); + try expectEqual(@as(usize, 1), t.census().free); + try expectEqual(@as(u8, 5), (try t.canonical(p[0]))[0]); + try t.pool.drop(p[0]); + try expect(t.resident(p[0]) == null and t.idle()); + try t.audit(); +} + +/// A fake serving loop: streams open, pin, write, flush, unpin, finish; every row read equals the page's last write. +const Sim = struct { + r: Rig, + rng: std.Random.DefaultPrng, + slots: [3]?Lease = .{ null, null, null }, + model: [16]u8 = @splat(0), // the byte last written to a page (0: none) + next: u8 = 1, + misses: usize = 0, + reads: usize = 0, + + fn open(s: *Sim, seed: u64, frames: usize) !void { + s.* = .{ .r = undefined, .rng = .init(seed) }; + try s.r.open(16, frames); + } + + fn close(s: *Sim) void { + for (&s.slots) |*l| if (l.*) |*x| s.r.tier.finish(x); + s.r.close(); + } + + fn check(s: *Sim, id: u32, tk: kt.Ticket) !void { + if (s.model[id] == 0) return; + for (s.r.frame(tk.frame)) |x| try expectEqual(s.model[id], x); + s.reads += 1; + } + + fn step(s: *Sim) !void { + const t = &s.r.tier; + const rnd = s.rng.random(); + const op = rnd.uintLessThan(u32, 100); + const k = rnd.uintLessThan(usize, s.slots.len); + const l: *Lease = if (s.slots[k]) |*x| x else { + if (op < 60) s.slots[k] = s.r.leaseLent(4, 3, 1) catch null; + return; + }; + const ids = l.pages.ids.items; + const id = ids[rnd.uintLessThan(usize, ids.len)]; + switch (op) { + 0...34 => { + const f = s.r.pin(l, id) catch |e| { + if (e == error.FrameMemory and l.pins.items.len + l.lent.items.len >= l.frames) return; + return e; + }; + s.misses += @intFromBool(f.miss); + try s.check(id, .{ .frame = f.frame, .gen = f.gen }); + }, + 35...59 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + s.model[p] = s.next; + s.next = if (s.next == 255) 1 else s.next + 1; + s.r.write(l, p, s.model[p]); + }, + 60...79 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + if (t.dirty[p]) s.r.flush(p); + try t.unpin(l, p); + }, + 80...89 => _ = t.evict(1), + else => { + for (l.pins.items) |p| if (t.dirty[p]) s.r.flush(p); + for (ids) |p| s.model[p] = 0; + t.finish(l); + s.slots[k] = null; + }, + } + try t.audit(); + for (t.page_of, 0..) |p, f| if (p != kt.none and !t.dirty[p]) try s.check(p, .{ .frame = @intCast(f), .gen = t.gen[f] }); + } +}; + +test "a random serving loop with fewer frames than pages: the audit holds, every read equals the last write, and it ends idle" { + inline for (.{ 1, 2, 3 }) |seed| { + var s: Sim = undefined; + try s.open(seed, 6); + defer s.close(); + for (0..4000) |_| try s.step(); + try expect(s.misses > 100 and s.reads > 500); + for (&s.slots) |*l| if (l.*) |*x| { + for (x.pins.items) |p| if (s.r.tier.dirty[p]) s.r.flush(p); + s.r.tier.finish(x); + l.* = null; + }; + _ = s.r.tier.evict(100); + try expect(s.r.tier.idle()); + } +} + +test "two ranks in lockstep: the same openings and pins give the same frames, generations and order, step after step" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + for (0..3000) |_| { + try a.step(); + try b.step(); + try expectEqual(a.r.tier.digest(), b.r.tier.digest()); + } +} + +test "two ranks: a step only one rank takes is caught by the digest at once" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + var caught: ?usize = null; + for (0..3000) |i| { + try a.step(); + if (i == 1500) _ = b.r.tier.evict(1) else try b.step(); // rank 1 evicts instead of the step rank 0 took + if (a.r.tier.digest() != b.r.tier.digest()) { + caught = i; + break; + } + } + try expect(caught != null); +} + +test "ranks agree on the smaller shape before they open" { + const a: kt.Shape = .{ .host_pages = 100, .frames = 40 }; + const b: kt.Shape = .{ .host_pages = 90, .frames = 48 }; + try expectEqual(kt.Shape{ .host_pages = 90, .frames = 40 }, a.agree(b)); + try expectEqual(a.agree(b), b.agree(a)); +} + +test "lent frames: counted in the frame promise, never victims or mapped, back at finish with a new generation" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.leaseLent(4, 3, 2); // two lent, one left to pin + try expectEqual(@as(usize, 2), t.census().lent); + try expectEqual(@as(usize, 2), a.lent.items.len); + try std.testing.expectError(error.FrameMemory, t.lend(&a, 2)); + const gen0 = t.gen[a.lent.items[0]]; + var b = try r.lease(4, 1); + const ids = a.pages.ids.items; + _ = try r.pin(&a, ids[0]); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[1])); // the lent frames used the promise + try t.unpin(&a, ids[0]); + for (b.pages.ids.items) |id| { // misses cycle through the two frames left; the lent ones are never taken + _ = try r.pin(&b, id); + try t.unpin(&b, id); + _ = try r.pin(&a, ids[1]); + try t.unpin(&a, ids[1]); + for (a.lent.items) |f| try expect(t.page_of[f] == kt.none); + } + try expect(t.evict(10) <= 2); // only the mapped frames can go, the lent ones are not among them + try t.audit(); + const lent0 = a.lent.items[0]; + t.finish(&a); + try expect(t.gen[lent0] != gen0); + try expectEqual(@as(usize, 0), t.census().lent); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "ranks lending a different count are told apart by the digest" { + var a: Rig = undefined; + var b: Rig = undefined; + try a.open(8, 4); + defer a.close(); + try b.open(8, 4); + defer b.close(); + var la = try a.leaseLent(4, 3, 2); + defer a.tier.finish(&la); + var lb = try b.leaseLent(4, 3, 2); + defer b.tier.finish(&lb); + try expectEqual(a.tier.digest(), b.tier.digest()); + try b.tier.lend(&lb, 0); + var lc = try b.leaseLent(0, 1, 1); + defer b.tier.finish(&lc); + try expect(a.tier.digest() != b.tier.digest()); +} + +test "a lent run is consecutive frames, leaves the free frames, and comes back at finish" { + var r: Rig = undefined; + try r.open(8, 6); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 4); + _ = try r.pin(&a, a.pages.ids.items[0]); // a mapped frame in the way + const first = try t.lendRun(&a, 3); + try expectEqual(@as(usize, 3), t.census().lent); + for (a.lent.items, 0..) |f, i| try expectEqual(first + i, f); + try t.audit(); + var b = try r.lease(2, 2); + try std.testing.expectError(error.FrameMemory, t.lendRun(&b, 3)); // past b's promise + _ = try r.pin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + try std.testing.expectEqual(@as(usize, 0), t.nfree); // 1 mapped (a) + 3 lent + 2 mapped (b) + t.finish(&a); + t.finish(&b); + try expect(t.idle()); + try t.audit(); + var c = try r.lease(1, 6); + defer t.finish(&c); + try expectEqual(@as(u32, 0), try t.lendRun(&c, 6)); +} + +/// A failed batch, then the same pages pinned again through the rig: the frames must equal the host pages. +fn failedFillReads(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + r.tier.fault = fault; + for (r.host, 0..) |*b, i| b.* = @intCast(1 + i / page_bytes); // page k holds k + 1 + @memset(r.dev, 0xee); // the frames hold something else + var a = try r.lease(4, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try r.tier.audit(); + for (ids[0..2]) |id| { + const f = try r.pin(&a, id); + if (!std.mem.eql(u8, r.frame(f.frame), r.tier.host_page(id))) return false; + } + return true; +} + +test "a failed batch leaves no miss mapped: the pages pinned again read the host rows; mutation: keeping the mapping reads stale frames" { + try expect(try failedFillReads(.none)); + try expect(!try failedFillReads(.keep_failed_miss)); +} + +test "a failed batch moves the generation of the frames it unmapped" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(3, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + const before = [2]u32{ r.tier.gen[0], r.tier.gen[1] }; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try expect(r.tier.gen[0] != before[0] and r.tier.gen[1] != before[1]); + try expectEqual(@as(usize, 2), r.tier.census().free); +} + +test "dirty needs a pin by the lease: an unpinned frame cannot be marked; mutation: a dirty frame nobody pins starves a lease inside its promise" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(1, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + try r.tier.unpin(&a, pa); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&a, pa)); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&b, pa)); // pinned by nobody of b + try r.tier.audit(); + // the mutant lets the mark through on a frame no lease pins, and the only frame is then stuck + var m: Rig = undefined; + try m.open(4, 2); + defer m.close(); + m.tier.fault = .unpinned_dirty; + var c = try m.lease(2, 1); + defer m.tier.finish(&c); + var d = try m.lease(1, 1); + defer m.tier.finish(&d); + for (c.pages.ids.items) |pc| { // both frames hold c's pages, unpinned + _ = try m.pin(&c, pc); + try m.tier.unpin(&c, pc); + } + for (c.pages.ids.items) |pc| try m.tier.markDirty(&c, pc); + try std.testing.expectError(error.FrameMemory, m.pin(&d, d.pages.ids.items[0])); +} + +/// A lease that pins a dirty page it does not own, after the owner let go of its pin: whether it may end. +fn endsWithForeignDirty(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + var b = try r.lease(1, 1); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + _ = try r.pin(&b, pa); + r.write(&a, pa, 9); + try r.tier.unpin(&a, pa); // b still pins it + const ok = r.tier.canFinish(&b); + if (ok) { + r.tier.finish(&b); + r.flush(pa); // too late for a real stream; the test only wants the tier consistent to close + } else { + r.flush(pa); + r.tier.finish(&b); + } + r.tier.finish(&a); + return ok; +} + +test "a stream cannot end while it holds the last pin of a dirty page, its own table or not; mutation: ignoring dirty lets it" { + try expect(!try endsWithForeignDirty(.none)); + try expect(try endsWithForeignDirty(.ignore_dirty)); +} + +test "a stream ends cleanly once the dirty pages it pins are flushed, and one that shares a dirty page of its own cannot" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = a.pages.ids.items; + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 3); + try expect(t.canFinish(&a)); // its own page and its only holder: the page goes with it + t.pool.retain(p[0]); + try expect(!t.canFinish(&a)); // now another holder would read rows the host lacks + r.flush(p[0]); + try expect(t.canFinish(&a)); + const keep = p[0]; + t.finish(&a); + try t.pool.drop(keep); + try expect(t.idle()); +} From 124c482ab7c1dffb4344617821771cfb6ab553b4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:00:07 +0100 Subject: [PATCH 151/158] Validate host KV tier geometry before allocation --- zig/src/core/kv_tier.zig | 2 ++ zig/src/core/kv_tier_test.zig | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig index 3d40f1d98ca..fbd0ce23e33 100644 --- a/zig/src/core/kv_tier.zig +++ b/zig/src/core/kv_tier.zig @@ -55,6 +55,8 @@ pub const Tier = struct { /// In place (the pool's release hook points here): `host.len / page_bytes` logical pages, `frames` frames. pub fn init(t: *Tier, gpa: Allocator, host: []u8, frames: usize, page_bytes: u64) !void { + if (page_bytes == 0 or host.len % page_bytes != 0 or frames == 0 or host.len == 0) + return error.BadTierGeometry; const npages: usize = @intCast(host.len / page_bytes); var pool = try kv.Pool.init(gpa, npages, page_bytes); errdefer pool.deinit(); diff --git a/zig/src/core/kv_tier_test.zig b/zig/src/core/kv_tier_test.zig index 95437b2bea6..760c7d3d189 100644 --- a/zig/src/core/kv_tier_test.zig +++ b/zig/src/core/kv_tier_test.zig @@ -10,6 +10,33 @@ const gpa = std.testing.allocator; const page_bytes = 8; +test "tier geometry: zero page bytes, partial host pages, zero frames and zero pages refuse before allocation" { + var host: [9]u8 = undefined; + const Case = struct { bytes: usize, frames: usize = 1, page: u64 = page_bytes }; + for ([_]Case{ + .{ .bytes = 8, .page = 0 }, + .{ .bytes = 7 }, + .{ .bytes = 9 }, + .{ .bytes = 8, .frames = 0 }, + .{ .bytes = 0 }, + }) |c| { + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + var tier: Tier = undefined; + try std.testing.expectError(error.BadTierGeometry, tier.init(failing.allocator(), host[0..c.bytes], c.frames, c.page)); + try expect(!failing.has_induced_failure); + } +} + +test "tier geometry: one byte, one page and one frame is the smallest valid tier" { + var host = [_]u8{7}; + var tier: Tier = undefined; + try tier.init(gpa, &host, 1, 1); + defer tier.deinit(); + try expectEqual(@as(usize, 1), tier.pool.total()); + try expectEqual(@as(usize, 1), tier.count()); + try std.testing.expectEqualSlices(u8, &host, tier.host_page(0)); +} + /// A tier of `pages` logical pages and `frames` frames over a host store and a fake device. const Rig = struct { host: []u8, From c546da2107564d59b98d01180e7ff96a04762678 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:36:19 +0100 Subject: [PATCH 152/158] docs: reference the host KV tier PR in changelog From 34c68d10c721b2f32433e7ab850d837a5d5a8fca Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:01:16 +0100 Subject: [PATCH 153/158] docs: move host KV tier note to Unreleased From 431ed68adaf4f706859853d43ce9871c44cddafb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:57:44 -0800 Subject: [PATCH 154/158] KV pool: notify the host tier when retired pages become reusable --- zig/src/core/kv_pool.zig | 3 +- zig/src/core/kv_pool_freed_test.zig | 64 +++++++++++++++++++++++++++++ zig/src/core/kv_pool_retire.zig | 2 + 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 zig/src/core/kv_pool_freed_test.zig diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index d1912792608..22b6ca6fca3 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -216,7 +216,7 @@ pub const Notify = struct { /// A family's pool as the load ledger reads it: tokens a page, and the contiguous run it needs (0: none). pub const Source = struct { pool: *Pool, page_tokens: u32, run_pages: u32 = 0 }; -/// A tier's notice that a page lost its last holder (its frame, if any, is free again). +/// A tier's notice that a page has no holders or readers and its frame, if any, is free again. pub const Freed = struct { ctx: *anyopaque, call: *const fn (ctx: *anyopaque, id: u32) void, @@ -571,6 +571,7 @@ pub const Tier = tier.Tier; test { _ = @import("kv_pool_test.zig"); _ = @import("kv_tier.zig"); + _ = @import("kv_pool_freed_test.zig"); _ = @import("kv_pool_counts_test.zig"); _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); diff --git a/zig/src/core/kv_pool_freed_test.zig b/zig/src/core/kv_pool_freed_test.zig new file mode 100644 index 00000000000..80ba1438a2d --- /dev/null +++ b/zig/src/core/kv_pool_freed_test.zig @@ -0,0 +1,64 @@ +//! A tier frees frames only when the pool makes their pages reusable, including after delayed readers finish. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const t = std.testing; + +const Seen = struct { + calls: usize = 0, + fn call(ctx: *anyopaque, id: u32) void { + const s: *Seen = @ptrCast(@alignCast(ctx)); + std.debug.assert(id == 0); + s.calls += 1; + } +}; + +test "pool freed hook: lease, store and run release notify once after the last holder" { + for (0..3) |mode| { + var p = try kv.Pool.init(t.allocator, 1, 64); + defer p.deinit(); + var seen: Seen = .{}; + p.freed = .{ .ctx = &seen, .call = Seen.call }; + var l: kv.Lease = .{}; + try p.promise(&l, 1); + if (mode == 2) { + const id = p.claimRun(&l, 1).?; + p.releaseRun(id, 1); + p.finish(&l); + } else { + const id = try p.take(&l); + if (mode == 1) p.retain(id); + p.finish(&l); + if (mode == 1) { + try t.expectEqual(@as(usize, 0), seen.calls); + p.release(id); + } + } + try t.expectEqual(@as(usize, 1), seen.calls); + try t.expect(p.idle()); + } +} + +test "pool freed hook: a retired pinned frame survives until its reader settles" { + var host: [64]u8 = @splat(0); + var tier: kv.Tier = undefined; + try tier.init(t.allocator, &host, 1, 64); + defer tier.deinit(); + var l: kv.tier.Lease = .{}; + defer tier.finish(&l); + try tier.reserve(&l, 1, 1); + try tier.cover(&l, 1, null); + const id = l.pages.ids.items[0]; + const fill = try tier.pin(&l, id); + const ticket: kv.tier.Ticket = .{ .frame = fill.frame, .gen = fill.gen }; + try kv.retirement.retire(&tier.pool, &l.pages, 0, 7); + try t.expect(tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 0), tier.nfree); + try kv.retirement.settle(&tier.pool, 6); + try t.expect(tier.valid(id, ticket)); + try tier.unpin(&l, id); + try kv.retirement.settle(&tier.pool, 7); + try t.expect(!tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 1), tier.nfree); + try kv.retirement.settle(&tier.pool, 7); + try t.expectEqual(@as(usize, 1), tier.nfree); +} diff --git a/zig/src/core/kv_pool_retire.zig b/zig/src/core/kv_pool_retire.zig index d66b1c89c66..8d9a7664fcd 100644 --- a/zig/src/core/kv_pool_retire.zig +++ b/zig/src/core/kv_pool_retire.zig @@ -81,6 +81,7 @@ pub fn freeOrPend(p: *Pool, id: u32) void { const r = &p.retired; if (r.marked.items.len > 0 and r.tokens[id] > r.settled) return r.pending.appendAssumeCapacity(id); // room: one a page clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } @@ -98,6 +99,7 @@ pub fn settle(p: *Pool, token: u64) error{LaneMemory}!void { keep += 1; } else { clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } From ff195b20bb596571aa9576231c7a206cda1131e3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:56:42 +0000 Subject: [PATCH 155/158] changelog: #1501 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07902162afb..df91e71d873 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 +- Core KV pool: a host tier for the pool's pages, which refuses zero page bytes, partial host pages, zero frames and zero logical pages before it allocates (#1501, refs #1113). Thanks to @BlivionIaG. + - Server: replies in recipient-addressed messages (`to=self` … `<|eom|>`, `to=user` … `<|eot|>`, as Muse Spark Open's chat template writes them) are split into reasoning, answer and tool calls, where the whole reply, markers included, ended up in `content` (#1336). Thanks to @ajensenwaud. - App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. From 7ee5531cc50dec049fc1197fa9c3f735ac221180 Mon Sep 17 00:00:00 2001 From: vdalesandro <124216266+vdalesandro@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:36:32 -0300 Subject: [PATCH 156/158] glm: resolve TF_NCCL_LIB in the shared NCCL library loader --- zig/src/cuda/nccl.zig | 32 +++++++++++++++++++++++++-- zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 1 + 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/zig/src/cuda/nccl.zig b/zig/src/cuda/nccl.zig index c1248b72d71..59bf5c89617 100644 --- a/zig/src/cuda/nccl.zig +++ b/zig/src/cuda/nccl.zig @@ -44,7 +44,7 @@ pub const Config = extern struct { graph_stream_ordering: c_int = std.math.minInt(c_int), }; -pub const Error = platform.optional_libraries.Failure || error{ LibraryUnavailable, MissingSymbol, NcclFailed, NcclVersion }; +pub const Error = platform.optional_libraries.Failure || platform.environment.Error || error{ LibraryUnavailable, MissingSymbol, NcclFailed, NcclVersion }; pub const in_progress: Result = 7; // ncclInProgress: a non-blocking communicator's call is still running @@ -76,8 +76,13 @@ pub const Library = struct { lib: platform.DynLib, api: Api, + fn configuredPath() platform.environment.Error![]const u8 { + const environment = platform.environment; + return try environment.path("TF_NCCL_LIB", environment.Process.get(.{}, "TF_NCCL_LIB")) orelse "libnccl.so.2"; + } + pub fn open() Error!Library { - return openPath("libnccl.so.2"); + return openPath(try configuredPath()); } pub fn openPath(path: []const u8) Error!Library { @@ -145,6 +150,29 @@ pub const Library = struct { } }; +test "NCCL library: TF_NCCL_LIB overrides the default; unset and empty keep it" { + const name = "TF_NCCL_LIB"; + const saved = if (platform.getenv(name)) |v| try std.testing.allocator.dupeSentinel(u8, v, 0) else null; + defer if (saved) |v| { + _ = platform.env.setenv(name, v, 1); + std.testing.allocator.free(v); + } else { + _ = platform.env.unsetenv(name); + }; + try std.testing.expectEqual(@as(c_int, 0), platform.env.unsetenv(name)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "/fixture/nccl/libnccl.so.2", 1)); + try std.testing.expectEqualStrings("/fixture/nccl/libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, " ./nccl/libnccl.so.2 ", 1)); + try std.testing.expectEqualStrings(" ./nccl/libnccl.so.2 ", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "", 1)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, "libnccl.so.2\n", 1)); + try std.testing.expectError(error.InvalidEnvironment, Library.open()); + try std.testing.expectEqual(@as(c_int, 0), platform.env.setenv(name, " \t", 1)); + try std.testing.expectEqualStrings("libnccl.so.2", try Library.configuredPath()); +} + test "nonblocking communicator config preserves the public ABI defaults" { const c: Config = .{}; try std.testing.expectEqual(@as(usize, 96), @sizeOf(Config)); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index a72ee17de6d..3016e2d0a3d 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -48,6 +48,7 @@ pub const rules = [_]Rule{ .{ .name = "TENSORFOLD_RESTORE_PREFETCH_MS", .scope = .common, .kind = .u64, .trim = " \t", .first_digit = true, .forms = "whole unsigned 64-bit milliseconds (capped at 1099511627776)" }, .{ .name = "TENSORFOLD_TOOL_ID_KEY_FILE", .scope = .common, .kind = .path, .forms = "a path without control characters to a file only its owner can read, holding at least 32 key bytes" }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .scope = .cuda, .kind = .path, .forms = "a captured kernel set's folder without control characters, or native for the engine's own kernels" }, + .{ .name = "TF_NCCL_LIB", .scope = .cuda, .kind = .path, .forms = "an NCCL library path without control characters, or blank for libnccl.so.2" }, .{ .name = "TF_CUDA_DEVICE", .scope = .cuda, .kind = .device, .trim = " ", .forms = "a whole GPU ordinal from 0 to 4294967295, or empty for the default" }, .{ .name = "TF_CUDA_SEGMENTS", .scope = .cuda, .kind = .segments, .trim = " ", .forms = "a whole number from 1 to 4, or empty for the default" }, .{ .name = "TF_CUDA_CARVEOUT", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 2904279cd7e..8ad640caaa5 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -153,6 +153,7 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_TAP_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .raw = "/tmp/captured set", .n = 0 }, + .{ .name = "TF_NCCL_LIB", .raw = "/fixture/nccl/libnccl.so.2", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, .{ .name = "TF_DSV41_SMALL", .raw = "1", .n = 1 }, .{ .name = "TF_DSV41_ASSETS", .raw = "deepseek assets", .n = 0 }, From 80a89812db9a3eab12b03c489740b5d2076788ff Mon Sep 17 00:00:00 2001 From: vdalesandro <124216266+vdalesandro@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:28:38 -0300 Subject: [PATCH 157/158] nccl: the TP session reads TF_NCCL_LIB by the loader's rule; nccl.zig re-pinned Review follow-up for #3106. - zig/tests/fixtures/gradient-serving.tsv: the zig/src/cuda/nccl.zig row carries the new hash and this PR's number, so test-gradient-serving passes again. - Library.pathFrom(raw) holds the one rule (a path is kept as written; unset, empty and blank keep libnccl.so.2; a control byte is refused). Library.open applies it to the process environment as before, and fabric/tp/config.zig applies it to its own getter, so a set-but-blank TF_NCCL_LIB no longer opens a blank path there. A malformed value is error.BadSetting, like the other TP settings. Checked on a CPU-only host with Zig 0.17.0: test-gradient-serving (fails before the re-pin with "serving source changed: zig/src/cuda/nccl.zig", passes after), test-tp (the new config test fails on the old line and passes on the new one), test-runtime-host, test-environment-host, the nccl.zig tests, zig fmt --check and the lean check (0 new). No device run. --- zig/src/cuda/nccl.zig | 8 ++++++-- zig/src/fabric/tp/config.zig | 12 +++++++++++- zig/tests/fixtures/gradient-serving.tsv | 2 +- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/zig/src/cuda/nccl.zig b/zig/src/cuda/nccl.zig index 59bf5c89617..f362f24d692 100644 --- a/zig/src/cuda/nccl.zig +++ b/zig/src/cuda/nccl.zig @@ -76,9 +76,13 @@ pub const Library = struct { lib: platform.DynLib, api: Api, + /// TF_NCCL_LIB's value as the library to open: a path is kept as written; unset, empty and blank keep libnccl.so.2. + pub fn pathFrom(raw: ?[]const u8) platform.environment.Error![]const u8 { + return try platform.environment.path("TF_NCCL_LIB", raw) orelse "libnccl.so.2"; + } + fn configuredPath() platform.environment.Error![]const u8 { - const environment = platform.environment; - return try environment.path("TF_NCCL_LIB", environment.Process.get(.{}, "TF_NCCL_LIB")) orelse "libnccl.so.2"; + return pathFrom(platform.environment.Process.get(.{}, "TF_NCCL_LIB")); } pub fn open() Error!Library { diff --git a/zig/src/fabric/tp/config.zig b/zig/src/fabric/tp/config.zig index 0771cef1c6a..b34309164c5 100644 --- a/zig/src/fabric/tp/config.zig +++ b/zig/src/fabric/tp/config.zig @@ -2,6 +2,7 @@ const std = @import("std"); const log = @import("log.zig"); const graph_cache = @import("cuda").graph_cache; +const nccl = @import("cuda").nccl; pub const Backend = enum { /// NCCL for everything (the default). @@ -116,7 +117,7 @@ pub const Config = struct { if (get("TF_TP_FAILFAST")) |v| c.failfast = !(std.mem.eql(u8, v, "0") or std.mem.eql(u8, v, "off")); c.grace_ns = try seconds(get, "TF_TP_FAILFAST_GRACE_S", 1.0, 0, 60); c.report_ns = try seconds(get, "TF_TP_PEER_MEM_S", 0.5, 0.01, 60); - if (get("TF_NCCL_LIB")) |p| c.nccl_lib = p; + c.nccl_lib = nccl.Library.pathFrom(get("TF_NCCL_LIB")) catch return error.BadSetting; c.roce_hca = get("TF_TP_ROCE_HCA"); c.link = get("TF_TP_LINK"); c.roce_hcas = try int(u8, get, "TF_TP_ROCE_HCAS", 2, 1, 2); @@ -265,6 +266,15 @@ test "defaults: the plan link 7 ports past the rendezvous, NCCL, fail-fast on" { try std.testing.expectEqual(std.time.ns_per_s / 2, c.report_ns); } +test "TF_NCCL_LIB follows the loader's rule: a path is kept, blank keeps libnccl.so.2, a control byte is refused" { + Fake.pairs = &.{.{ "TF_NCCL_LIB", "/fixture/nccl/libnccl.so.2" }}; + try std.testing.expectEqualStrings("/fixture/nccl/libnccl.so.2", (try Config.parse(&Fake.get)).nccl_lib); + Fake.pairs = &.{.{ "TF_NCCL_LIB", " \t" }}; + try std.testing.expectEqualStrings("libnccl.so.2", (try Config.parse(&Fake.get)).nccl_lib); + Fake.pairs = &.{.{ "TF_NCCL_LIB", "libnccl.so.2\n" }}; + try std.testing.expectError(error.BadSetting, Config.parse(&Fake.get)); +} + test "bad settings are refused and the digest ignores the rank" { Fake.pairs = &.{.{ "TF_TP_RANK", "2" }}; try std.testing.expectError(error.BadSetting, Config.parse(&Fake.get)); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index a74b43c1474..883de89e707 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -99,7 +99,7 @@ zig/src/cuda/memory.zig 7d2a91bfca8a08ae59df16ddf30d22226aba773cc814dd106930840a zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw zig/src/cuda/module.zig 1f0a141cf7149a87ad456e96cb1830f0c137ad98af70071721918989b0720b92 raw 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/nccl.zig 005a4dd9ed6929b6022c4daff8d8d82c0ee43ea3e468221fd4a8de9ae6dde640 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; #3106 (Library.open reads TF_NCCL_LIB through pathFrom, shared with the TP session's settings; unset, empty and blank keep libnccl.so.2) zig/src/cuda/norms.zig c6ac613ff91b31257b5bce55311d8cf38a785862bfad9eb0c7bf0b2ba7b0df95 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 From ad8b5476aea00200646220af574b64ab1db67592 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:56:46 +0000 Subject: [PATCH 158/158] changelog: #3106 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index df91e71d873..f87b67855d8 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: `nccl.Library.open()` and the tensor-parallel config now resolve `TF_NCCL_LIB` through the shared path rule, so GLM, Flash Next's `--tp 2` collective, MiniMax M3 and TP sessions open the same library; unset, empty or blank values keep `libnccl.so.2`, and a value with control characters is refused (#3106). Thanks to @vdalesandro. + - Core KV pool: a host tier for the pool's pages, which refuses zero page bytes, partial host pages, zero frames and zero logical pages before it allocates (#1501, refs #1113). Thanks to @BlivionIaG. - Server: replies in recipient-addressed messages (`to=self` … `<|eom|>`, `to=user` … `<|eot|>`, as Muse Spark Open's chat template writes them) are split into reasoning, answer and tool calls, where the whole reply, markers included, ended up in `content` (#1336). Thanks to @ajensenwaud.