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 01/73] 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 02/73] 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 03/73] 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 04/73] 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 05/73] 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 06/73] 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 07/73] 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 08/73] 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 09/73] 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 10/73] 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 11/73] 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 12/73] 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 13/73] 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 14/73] 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 15/73] 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 16/73] 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 17/73] 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 18/73] 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 19/73] 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 20/73] 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 */}