diff --git a/CHANGELOG.md b/CHANGELOG.md index d40b180c320..38a06f37130 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- GLM-5.3-Flash on CUDA: with `--learn-conversations`, conversation states are kept on disk through the rows store, so after an eviction or a restart the next turn reads its state back instead of prefilling the whole conversation; at TP>1 every rank's part goes to rank 0's disk, so a state is read back on every rank or none (#1411, fixes #1312). Thanks to @wojo. + +- Qwen on Metal: with `TF_Q27_KV_GROW=` (a multiple of 16; 0 or unset is off) a serve's K/V slots start at that many rows, grow as their streams do and give the rows back when a stream ends, and drafter tap rings grow the same way; replies are byte-identical with it on or off (#1896). Thanks to @grantoverton. + +- LFM3 on Metal: warm turns, so a tool loop whose re-rendered history changes mid-conversation re-prefills only from the first changed token, with outputs identical to a fresh run (#N). + - Server: `tensorfold capabilities --json` now lists `TENSORFOLD_PARALLEL` and the other environment variables `serve` honours, so the desktop app's Engine variables page accepts them (#N, fixes #3684). - Tests: host tests record where capped prompt chunks cut while another stream is live, family by family (#N). diff --git a/docs/api.md b/docs/api.md index e96b374b412..67937128809 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1453,7 +1453,9 @@ store for each model and build. That store takes the place of `--learn`'s store with the flag neither reads nor writes the prefix files a plain `--learn` server keeps, and they stay on disk until the cap below needs their room. After a restart, a crash or an eviction from RAM, the next turn reads the latest state back instead of reading the conversation again from its first token. Qwen3.8-27B, Nemotron, Flash Next and GLM-5.3-Flash on -one Mac, and Nemotron, the Qwen3.5 hybrids and Flash Next on CUDA, keep them; other engines refuse the flag at startup. +one Mac, and Nemotron, the Qwen3.5 hybrids, Flash Next and GLM-5.3-Flash on CUDA keep them; other engines refuse the +flag at startup. GLM-5.3-Flash on CUDA across ranks writes every rank's part to rank 0's disk, so a state is read back +on every rank or on none; it takes neither `--spill-gib` nor `--checkpoint-slots`. The engine stages an owned copy between rounds, and an I/O thread writes and fsyncs it. Staging has a 1 GiB byte permit and at most eight jobs. Qwen3.8-27B widens the permit to one whole state at its `--context`, with none of its rows on diff --git a/docs/environment.md b/docs/environment.md index dd6b10d55d3..1f33729eddc 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -88,6 +88,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | +| `TF_LFM3_METAL_WARM_TURNS` | Exactly `0` or `1`; default off. Uses one-row LFM3 Metal prefill even with caching disabled. A prompt cache enables background warm turns. | | `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs; `0` keeps Metal 3. DeepSeek-V4.1 defaults to `1` where the Mac has Metal 4 (its device test rigs to `0`); Macs without it stay on Metal 3 | | `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows, every 1,024 rounds; default 0 | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | diff --git a/zig/src/core/lane_host_warm_test.zig b/zig/src/core/lane_host_warm_test.zig index 89bf574ef2b..1effc5338c2 100644 --- a/zig/src/core/lane_host_warm_test.zig +++ b/zig/src/core/lane_host_warm_test.zig @@ -39,6 +39,24 @@ const Box = struct { } }; +const FakeSnaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!prompt_cache.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: prompt_cache.Saved) anyerror!void { + return error.BackendRestores; + } + fn drop(ptr: *anyopaque, saved: prompt_cache.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } +}; +const fake_snap_vtable: prompt_cache.Snapshots.VTable = .{ .bytes = FakeSnaps.bytes, .save = FakeSnaps.save, .restore = FakeSnaps.restore, .drop = FakeSnaps.drop }; + /// Chunks the fake ran for prompt-only streams. const WarmChunks = struct { n: std.atomic.Value(usize) = .init(0), @@ -190,23 +208,6 @@ test "a warm pass its cache keeps nothing of runs no chunk: no planned mark, and test "a warm_usable store keeps a warm pass's grid mark but not its end off the grid; without it, the end too" { const gpa = std.testing.allocator; - const pc = api.prompt_cache; - const Snaps = struct { - fn bytes(_: *anyopaque, at: u32) u64 { - return 64 + 4 * @as(u64, at); - } - fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - return f.save(@ptrCast(@alignCast(owner.?)), at); - } - fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { - return error.BackendRestores; - } - fn drop(ptr: *anyopaque, saved: pc.Saved) void { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - f.drop(saved); - } - }; for ([_]bool{ true, false }) |usable| { var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); defer cfg.deinit(gpa); @@ -216,7 +217,7 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); defer core.deinit(); // dots.mocr's rules, scaled down: a grid of 4 and no request starts, so only multiples of 4 resume - var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 400); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 400); defer store.deinit(); var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); host.cache = &store; @@ -241,23 +242,6 @@ test "a warm_usable store keeps a warm pass's grid mark but not its end off the test "a one-snapshot store keeps the warm pass's usable mark over an unusable end; the next request resumes the mark" { const gpa = std.testing.allocator; - const pc = api.prompt_cache; - const Snaps = struct { - fn bytes(_: *anyopaque, at: u32) u64 { - return 64 + 4 * @as(u64, at); - } - fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - return f.save(@ptrCast(@alignCast(owner.?)), at); - } - fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { - return error.BackendRestores; - } - fn drop(ptr: *anyopaque, saved: pc.Saved) void { - const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); - f.drop(saved); - } - }; for ([_]bool{ true, false }) |usable| { var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); defer cfg.deinit(gpa); @@ -270,7 +254,7 @@ test "a one-snapshot store keeps the warm pass's usable mark over an unusable en // The 128-row cut and 192-row warm end, scaled to a grid of 4: the end at 6 is off it. // A budget of one snapshot (88 B) fits either state, never both. - var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .planned = true, .grid = 4, .warm = .on, .warm_usable = usable }, 100); defer store.deinit(); var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2, .warm_turns = true }); host.cache = &store; @@ -486,3 +470,71 @@ test "a warm pass gives way to a request still filling its prompt: no quiet wait try std.testing.expectEqual(@as(usize, @intFromBool(quiet == 0)), behind.chunks.load(.monotonic)); } } + +test "a re-rendered tool history restores its rewind row and matches a fresh reply" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + var store = prompt_cache.Store.init(gpa, .{ .ptr = &target, .vtable = &fake_snap_vtable }, .{ .chunk = 1, .min_prompt = 0, .warm = .waits }, 8192); + defer store.deinit(); + + const Reply = struct { + box: Box = .{}, + ids: [4]u32 = undefined, + cached: u32 = 0, + + fn event(ctx: *anyopaque, id: Id, e: *const Event) void { + const reply: *@This() = @ptrCast(@alignCast(ctx)); + switch (e.*) { + .prefilled => |count| reply.cached = count, + .tokens => |ids| @memcpy(reply.ids[reply.box.tokens..][0..ids.len], ids), + else => {}, + } + Box.event(&reply.box, id, e); + } + }; + + // The follow-up omits the assistant's reasoning, retaining the tool call and adding its result. + const predicted = [_]u32{ 1, 2, 3, 4, 70, 71, 80, 81, 9 }; + const rendered = [_]u32{ 1, 2, 3, 4, 80, 81, 9, 90, 91, 10 }; + const diff: u32 = @intCast(std.mem.indexOfDiff(u32, &predicted, &rendered).?); + const warm: Request = .{ + .prompt = &predicted, + .max_tokens = 0, + .background = true, + .history_len = predicted.len, + .rewind_len = diff, + .born = 2, + .decode_spans = &.{.{ 2, 8 }}, + }; + const next: Request = .{ .prompt = &rendered, .max_tokens = 4, .decode_spans = &.{.{ 2, 6 }} }; + var warm_reply: Reply = .{}; + var fresh_reply: Reply = .{}; + for ([_]?*prompt_cache.Store{ &store, null }, [_]*Reply{ &warm_reply, &fresh_reply }) |cache, reply| { + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 }); + host.decoded_rows = true; + host.cache = cache; + host.advertiseCache(cache); + try host.start(); + defer host.stop(); + if (cache != null) { + var box: Box = .{}; + try host.engine().submit(1, &warm, .{ .ctx = &box, .event = Box.event }); + try std.testing.expectEqual(Reason.length, box.wait()); + const continued = predicted ++ [_]u32{90}; + const kept = store.find(&continued, &.{}, warm.decode_spans) orelse return error.WarmEndMissing; + try std.testing.expectEqual(@as(u32, predicted.len), kept.at); + } + try host.engine().submit(2, &next, .{ .ctx = reply, .event = Reply.event }); + try std.testing.expectEqual(Reason.length, reply.box.wait()); + try std.testing.expectEqual(reply.ids.len, reply.box.tokens); + } + try std.testing.expectEqual(diff, warm_reply.cached); + try std.testing.expectEqual(@as(u32, 0), fresh_reply.cached); + try std.testing.expectEqualSlices(u32, &fresh_reply.ids, &warm_reply.ids); +} diff --git a/zig/src/core/rows_pool_select_test.zig b/zig/src/core/rows_pool_select_test.zig index b15e756c8a0..beab09be119 100644 --- a/zig/src/core/rows_pool_select_test.zig +++ b/zig/src/core/rows_pool_select_test.zig @@ -86,3 +86,115 @@ test "restore selection: pooled buffers trim only when supported and never steal s.release(borrowed); } } + +test "restore selection: a pool without trim reads into the spare storage an eviction leaves, as a keep would" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + defer a.free(dir); + var prompt: [64]u32 = undefined; + for (&prompt, 0..) |*token, i| token.* = @intCast(100 + i); + const rules: pc.Rules = .{ .min_prompt = 0, .min_gap = 1, .lookahead = 1 }; + { + var f: Fake = .{ .gpa = a, .at = 20, .sum = fresh(prompt[0..20]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 1000); + defer s.deinit(); + s.disk = r; + try t.expect(s.keep(&prompt, 20, null, &.{}, &.{})); + while (rows.write.step(r)) {} + } + var f: Fake = .{ .gpa = a, .at = 5, .sum = fresh(prompt[0..5]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + table.trim = null; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 240); + defer s.deinit(); + try t.expect(s.keep(&prompt, 5, null, &.{}, &.{})); + const borrowed = s.entries.items[0]; + borrowed.borrowers = 1; + prompt[0] = 999; + f.at = 30; // another conversation's state: its storage, once evicted, can take the read (120 >= 110) + f.sum = fresh(prompt[0..30]); + try t.expect(s.keep(&prompt, 30, null, &.{}, &.{})); + prompt[0] = 100; + s.disk = r; + try t.expectEqual(.disk, rows.read.resumable(&s, &prompt, &.{}, &.{}).from); + const restored = rows.read.recall(&s, &prompt, 64, &.{}, &.{}, borrowed).?; + try t.expectEqual(@as(u32, 20), restored.at); + try t.expectEqual(@as(u64, 1), r.counts.reads); + try t.expectEqual(@as(u64, 1), s.counts.evicted); + try t.expect(s.held + s.spare() <= s.budget); + try family.vtable.restore(family.ptr, null, restored.saved); + try t.expectEqual(fresh(&prompt), f.pass(&s, &prompt, .{ .from = restored.at })); + s.release(borrowed); +} + +/// A disk read into new storage, whatever spare storage the pool holds. +const Fresh = struct { + const api: rows.Image = .{ .parts = Image.parts, .gather = Image.gather, .blank = blank, .scatter = Image.scatter }; + fn blank(ptr: *anyopaque, at: u32) !pc.Saved { + const f: *Fake = @ptrCast(@alignCast(ptr)); + const previous = f.at; + f.at = at; + defer f.at = previous; + return f.snapshots().vtable.save(ptr, null, at); + } +}; + +test "restore selection: a pool that also trims reads a disk state only within its budget, whatever it reuses" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + defer a.free(dir); + var prompt: [64]u32 = undefined; + for (&prompt, 0..) |*token, i| token.* = @intCast(100 + i); + const rules: pc.Rules = .{ .min_prompt = 0, .min_gap = 1, .lookahead = 1 }; + { + var f: Fake = .{ .gpa = a, .at = 20, .sum = fresh(prompt[0..20]) }; + var table = f.pooled().vtable.*; + table.rows = &Image.api; + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 1000); + defer s.deinit(); + s.disk = r; + try t.expect(s.keep(&prompt, 20, null, &.{}, &.{})); + while (rows.write.step(r)) {} + } + var f: Fake = .{ .gpa = a, .at = 5, .sum = fresh(prompt[0..5]) }; + var table = f.pooled().vtable.*; + table.rows = &Fresh.api; + try t.expect(table.reuses != null and table.trim != null); + const family: pc.Snapshots = .{ .ptr = &f, .vtable = &table }; + const r = try rows.Rows.open(a, family, options(dir)); + defer r.deinit(); + var s = pc.Store.init(a, family, rules, 240); + defer s.deinit(); + try t.expect(s.keep(&prompt, 5, null, &.{}, &.{})); + const borrowed = s.entries.items[0]; + borrowed.borrowers = 1; + prompt[0] = 999; + f.at = 30; // another conversation's state: once evicted, its spare storage is one the family says takes the read + f.sum = fresh(prompt[0..30]); + try t.expect(s.keep(&prompt, 30, null, &.{}, &.{})); + prompt[0] = 100; + s.disk = r; + try t.expectEqual(.disk, rows.read.resumable(&s, &prompt, &.{}, &.{}).from); + const restored = rows.read.recall(&s, &prompt, 64, &.{}, &.{}, borrowed).?; + try t.expectEqual(@as(u32, 20), restored.at); + try t.expectEqual(@as(u64, 1), r.counts.reads); + try t.expectEqual(@as(u64, 1), s.counts.evicted); + try t.expect(s.held + s.spare() <= s.budget); // the spare storage was trimmed for the new storage, not left over it + try family.vtable.restore(family.ptr, null, restored.saved); + try t.expectEqual(fresh(&prompt), f.pass(&s, &prompt, .{ .from = restored.at })); + s.release(borrowed); +} diff --git a/zig/src/core/rows_read.zig b/zig/src/core/rows_read.zig index 244367d3af2..129a86b2202 100644 --- a/zig/src/core/rows_read.zig +++ b/zig/src/core/rows_read.zig @@ -51,10 +51,10 @@ fn one(r: *Rows, name: Name, kind: file.Kind, ext: []const u8, at: u32, ranges: return o.trailer.payload + o.trailer.meta + @sizeOf(file.Trailer); } -/// Whether a family refused what a file holds (words that differ, a size or a range that does not fit its blank). +/// Whether a family refused what a file holds (words that differ, of another world or layout; a size or range unfit). fn refused(err: anyerror) bool { return switch (err) { - error.SnapshotSize, error.BadKeptRange, error.DiskWords, error.KeptWordsDiffer => true, + error.SnapshotSize, error.BadKeptRange, error.DiskWords, error.KeptWordsDiffer, error.DiskWorld, error.DiskLayout => true, else => false, }; } @@ -128,9 +128,9 @@ fn attempt(s: *pc.Store, prompt: []const u32, born: u32, starts: []const u32, sp const name = candidate.name; const bytes = r.blankBytes(candidate.at); if (bytes > s.budget or s.most == 0) return have; - if (!ready(s, bytes)) present(r, chosen) catch |err| return failed(before, candidate.at, err, have); // nothing goes to make room for a state whose file is gone + if (!ready(s, candidate.at, bytes)) present(r, chosen) catch |err| return failed(before, candidate.at, err, have); // nothing goes to make room for a state whose file is gone if (r.spill != .off) r.touch(chosen); // the newest: the spills that make room for it push older states off first - while (!ready(s, bytes)) { + while (!ready(s, candidate.at, bytes)) { if (s.family.vtable.trim) |trim| { const spare = s.spare(); trim(s.family.ptr, s.budget -| s.held -| bytes); @@ -165,8 +165,11 @@ fn attempt(s: *pc.Store, prompt: []const u32, born: u32, starts: []const u32, sp return e; } -fn ready(s: *const pc.Store, bytes: u64) bool { +fn ready(s: *const pc.Store, at: u32, bytes: u64) bool { if (s.held > s.budget or s.entries.items.len >= s.most) return false; + const f = s.family.vtable; + // a pool without trim reads into spare storage that takes the state, as a keep would + if (f.trim == null) if (f.reuses) |reuses| if (reuses(s.family.ptr, at)) return true; const room = s.budget - s.held; const spare = s.spare(); return spare <= room and bytes <= room - spare; diff --git a/zig/src/core/rows_refusal_test.zig b/zig/src/core/rows_refusal_test.zig index 5b298996e9b..668a9884cee 100644 --- a/zig/src/core/rows_refusal_test.zig +++ b/zig/src/core/rows_refusal_test.zig @@ -84,6 +84,8 @@ const cases = [_]Case{ .{ .piece = .shared, .err = error.BadKeptRange, .mine = false, .other = false }, .{ .piece = .own, .err = error.DiskWords, .mine = false, .other = true }, // the state's own file .{ .piece = .own, .err = error.KeptWordsDiffer, .mine = false, .other = true }, + .{ .piece = .own, .err = error.DiskWorld, .mine = false, .other = true }, // written by another number of ranks + .{ .piece = .own, .err = error.DiskLayout, .mine = false, .other = true }, // or in another layout .{ .piece = .own, .err = error.ScatterFailed, .mine = true, .other = true }, // a link failing: the disk is fine .{ .piece = .shared, .err = error.OutOfMemory, .mine = true, .other = true }, }; diff --git a/zig/src/core/rows_select.zig b/zig/src/core/rows_select.zig index d6ac457847a..cb82666a458 100644 --- a/zig/src/core/rows_select.zig +++ b/zig/src/core/rows_select.zig @@ -56,12 +56,15 @@ fn capacity(s: *const pc.Store, have: ?*pc.Entry) ?u64 { var protected: usize = 0; const f = s.family.vtable; for (s.entries.items) |e| { - if (e == have or e.borrowers > 0) protected += 1 else if (f.spare == null or f.trim != null) { + if (e == have or e.borrowers > 0) protected += 1 else if (f.spare == null or f.trim != null or f.reuses != null) { reclaimable +|= e.bytes; } } + if (protected >= s.most) return null; + // a pool that reuses spare storage without trimming it (GLM's snapshot pages): a read takes spare or evicted pages + if (f.reuses != null and f.trim == null) return s.spare() +| reclaimable; const fixed = (s.held -| reclaimable) +| if (f.trim == null) s.spare() else 0; - if (protected >= s.most or fixed > s.budget) return null; + if (fixed > s.budget) return null; return s.budget - fixed; } diff --git a/zig/src/core/rows_test.zig b/zig/src/core/rows_test.zig index e809569c9cb..d14a8c2b7b1 100644 --- a/zig/src/core/rows_test.zig +++ b/zig/src/core/rows_test.zig @@ -247,16 +247,18 @@ fn gridRequest(a: Allocator, s: *pc.Store, f: *Fake, p: []const u32, history: u3 return .{ .from = plan.from, .sum = f.sum }; } -test "a grid family's requests name no chunk starts: its states go to disk on the grid and resume after a restart" { +/// A grid family's states through one writer (`sync`: the test's thread, else the I/O worker), read after a restart. +fn gridRoundTrip(sync: bool, tag: []const u8) !void { const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator(); var buf: [128]u8 = undefined; - const dir = root(&buf, "grid"); + const dir = root(&buf, tag); defer rmTree(dir); const grid: pc.Rules = .{ .lookahead = 1, .min_prompt = 0, .min_gap = 1, .planned = true, .grid = 512 }; var o = options(dir); + o.sync_writes = sync; o.planned = true; o.grid = 512; const p = try prompt(a, 0, 5, 1300); // the engine cuts its chunks on the grid: 512 and 1024 @@ -268,7 +270,7 @@ test "a grid family's requests name no chunk starts: its states go to disk on th defer s.deinit(); s.disk = r; _ = try gridRequest(a, &s, &f, p, 1200); - drain(r); + _ = rows.write.drain(r, rows.write.nowNs() + 3 * std.time.ns_per_s); // the worker publishes the states try std.testing.expect(r.states.items.len > 0); for (r.states.items) |st| { try std.testing.expectEqual(@as(u32, 0), st.at % 512); @@ -289,6 +291,14 @@ test "a grid family's requests name no chunk starts: its states go to disk on th try std.testing.expectEqual(@as(u64, 1), r.counts.reads); } +test "a grid family's requests name no chunk starts: its states go to disk on the grid and resume after a restart" { + try gridRoundTrip(true, "grid"); +} + +test "a grid family's chunk starts reach the I/O worker's writes as well, the writer GLM's store uses" { + try gridRoundTrip(false, "grid-worker"); +} + test "an entry evicted before its write leaves the queue; once written, an eviction costs nothing" { const gpa = std.testing.allocator; var arena: std.heap.ArenaAllocator = .init(gpa); diff --git a/zig/src/families/glm/cuda.zig b/zig/src/families/glm/cuda.zig index b2ad60c6f0c..394e488e33e 100644 --- a/zig/src/families/glm/cuda.zig +++ b/zig/src/families/glm/cuda.zig @@ -44,6 +44,8 @@ pub const native = @import("cuda_native.zig"); pub const snapshots = @import("cuda_snapshots.zig"); pub const kv_host = @import("cuda_kv_host.zig"); pub const pdl = @import("cuda_pdl.zig"); +pub const disk_image = @import("cuda_disk_image.zig"); +pub const disk_ranks = @import("cuda_disk_ranks.zig"); test { _ = lane_costs; @@ -74,6 +76,8 @@ test { _ = prompt_solo; _ = @import("cuda_l2pf.zig"); _ = prompt_pair; + _ = @import("cuda_disk_image.zig"); + _ = @import("cuda_disk_ranks_test.zig"); _ = experts; _ = exl3; _ = vision; diff --git a/zig/src/families/glm/cuda_disk_image.zig b/zig/src/families/glm/cuda_disk_image.zig new file mode 100644 index 00000000000..ce6bfc18760 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_image.zig @@ -0,0 +1,322 @@ +//! A GLM kept state's disk image on one rank: its parts at a position, and where each image byte sits in its lease. +const std = @import("std"); +const cuda = @import("cuda"); +const st_mod = @import("cuda_state.zig"); +const sparse = @import("cuda_sparse.zig"); +const Config = @import("config.zig").Config; +const pages = @import("cuda_snapshot_pages.zig"); +const State = st_mod.State; +const window_rows = st_mod.window_rows; + +/// The image's first bytes: the format, the position, the head's rows, both ring bases, the KDA copy bits, the layout. +pub const Words = struct { + at: u64, + mtp_len: u64, + base: u64, + mtp_base: u64, + cur: u64, + world: u64, // the ranks that wrote it + layout: Layout = .unsplit, + owner: u64 = no_owner, // the rank holding its latent rows alone (split layouts); unsplit: no_owner + + pub const count = 9; + pub const bytes: u64 = count * 8; + const format: u64 = 1; + + /// Which rows each rank's image holds: unsplit, every rank every row (the only layout written so far). + pub const Layout = enum(u64) { unsplit = 0, _ }; + pub const no_owner: u64 = std.math.maxInt(u64); + + pub fn encode(w: Words) [count]u64 { + return .{ format, w.at, w.mtp_len, w.base, w.mtp_base, w.cur, w.world, @backingInt(w.layout), w.owner }; + } + + /// Words read back, refused by name unless this format at `at`, written by `world` ranks in this server's `layout`. + pub fn decode(x: [count]u64, at: u32, world: u32, layout: Layout) !Words { + if (x[0] != format or x[1] != at) return error.DiskWords; + if (x[6] != world) return error.DiskWorld; + const l: Layout = @fromBackingInt(@intCast(x[7])); + if (l != layout) return error.DiskLayout; + if (if (l == .unsplit) x[8] != no_owner else x[8] >= world) return error.DiskLayout; + return .{ .at = x[1], .mtp_len = x[2], .base = x[3], .mtp_base = x[4], .cur = x[5], .world = x[6], .layout = l, .owner = x[8] }; + } +}; + +/// A part as the rows store takes it: `row` bytes for each `per` tokens from position 0, or the state's own (row 0). +pub const Part = struct { bytes: u64, row: u32 = 0, per: u32 = 1 }; + +/// `len` image bytes from `img`: the words, `lease` bytes into the state's lease, or zeros the lease does not hold. +pub const Seg = struct { img: u64, len: u64, from: union(enum) { words, lease: u64, zeros } }; + +/// What a rank's kept state holds, read from a sequence of the engine (its addresses are not used past here). +pub const Shape = struct { + prefix: u64, // the sequence's own fields before its caches: KDA conv and states, a window's saved rows + tail: u64, // its fields after them: the head's position and first-draft row + layers: u32, // DSA layers, whose rows are shared by position + latent: u32, // a latent row's bytes + scales: bool, // fp8 latent rows: a 4-byte scale each + ring_rows: u32, + ring_row: u32, + pk_rows: u32, + pooled_row: u32, + capacity: u32, + head: bool, // the MTP head's caches are kept (drafting) + window: u64, // the prefix's bytes before a verify window's rows (its KDA projections and saves, read by its keep) + draft: u64, // the tail's bytes before the first-draft row (written at a prompt pass's end) + + pub fn of(st: *const State, c: *const Config, capacity: usize, head: bool) !Shape { + if (st.rings.len == 0) return error.SnapshotShape; + const base = st.arena.buf.ptr; + const first = if (st.table != 0) st.rings[0] else if (st.caches.len > 0) st.caches[0].lc else st.mtp_caches.lc; + const end = if (st.table != 0) st.table else base + st.arena.buf.len; + if (first < base or st.mtp_pos_dev < first or end < st.mtp_pos_dev) return error.SnapshotShape; + if (st.proj < base or first < st.proj or st.prompt_hidden < st.mtp_pos_dev or end < st.prompt_hidden) return error.SnapshotShape; + const fp8 = st.mtp_caches.ls != 0; + return .{ + .window = st.proj - base, + .draft = st.prompt_hidden - st.mtp_pos_dev, + .prefix = first - base, + .tail = end - st.mtp_pos_dev, + .layers = @intCast(st.caches.len), + .latent = c.kv_lora * @as(u32, if (fp8) 1 else 2), + .scales = fp8, + .ring_rows = @intCast(st.ring_rows), + .ring_row = @intCast(st.ring_row), + .pk_rows = @intCast(capacity / sparse.pool + 2), + .pooled_row = c.i_dim * 2, + .capacity = @intCast(capacity), + .head = head, + }; + } + + /// Rows the image keeps of the head's caches at `at`: a verify window past it, as the cache charges a state. + pub fn headRows(sh: Shape, at: u32) u32 { + return @min(sh.capacity, at + window_rows); + } +}; + +/// One cache's parts in the lease's order, for `n` rows: latent, scales, the two index rings, the pooled keys. +fn cache(sh: Shape, n: u64) [5]u64 { + return .{ + n * sh.latent, + if (sh.scales) n * 4 else 0, + @min(n, sh.ring_rows) * sh.ring_row, + @min(n, sh.ring_rows) * sh.ring_row, + @min(n / sparse.pool + 2, sh.pk_rows) * sh.pooled_row, + }; +} + +/// The longest state an image holds: the capacity's whole pools (`parts` takes no other position). +pub fn longest(sh: Shape) u32 { + return sh.capacity - sh.capacity % sparse.pool; +} + +/// The image at `at` (a chunk start): the words, the prefix, each DSA layer's rows, the head's caches, the tail. +pub fn parts(sh: Shape, at: u32, out: *std.ArrayList(Part), a: std.mem.Allocator) !void { + if (at == 0 or at % sparse.pool != 0 or at > sh.capacity) return error.SnapshotShape; + try out.appendSlice(a, &.{ .{ .bytes = Words.bytes }, .{ .bytes = sh.prefix } }); + const pooled: u64 = at / sparse.pool; + for (0..sh.layers) |_| { + const c = cache(sh, at); + try out.append(a, .{ .bytes = c[0], .row = sh.latent }); + if (sh.scales) try out.append(a, .{ .bytes = c[1], .row = 4 }); + try out.appendSlice(a, &.{ .{ .bytes = c[2] }, .{ .bytes = c[3] } }); + // whole pools are rows by position; the pool past them and the spare row stay the state's own + try out.appendSlice(a, &.{ .{ .bytes = pooled * sh.pooled_row, .row = sh.pooled_row, .per = sparse.pool }, .{ .bytes = c[4] - pooled * sh.pooled_row } }); + } + if (sh.head) for (cache(sh, sh.headRows(at))) |n| if (n > 0) try out.append(a, .{ .bytes = n }); + try out.append(a, .{ .bytes = sh.tail }); +} + +/// The image's segments in order for a state at `at` whose head holds `mtp_len` rows (0 without a head). +pub fn segments(sh: Shape, at: u32, mtp_len: u64, out: *std.ArrayList(Seg), a: std.mem.Allocator) !void { + if (sh.head and mtp_len > sh.headRows(at)) return error.SnapshotShape; + var img: u64 = Words.bytes; + var lease: u64 = 0; + try out.append(a, .{ .img = 0, .len = Words.bytes, .from = .words }); + const f = front(sh, at); + try out.append(a, .{ .img = img, .len = f, .from = .{ .lease = 0 } }); + img += f; + lease += f; + if (sh.head) for (cache(sh, sh.headRows(at)), cache(sh, mtp_len)) |full, held| { + if (held > 0) try out.append(a, .{ .img = img, .len = held, .from = .{ .lease = lease } }); + if (full > held) try out.append(a, .{ .img = img + held, .len = full - held, .from = .zeros }); + img += full; + lease += held; + }; + if (sh.tail > 0) try out.append(a, .{ .img = img, .len = sh.tail, .from = .{ .lease = lease } }); +} + +/// The image bytes after the words that sit in the lease as in the image: the prefix and every DSA layer's parts. +pub fn front(sh: Shape, at: u32) u64 { + var n: u64 = sh.prefix; + for (0..sh.layers) |_| for (cache(sh, at)) |x| { + n += x; + }; + return n; +} + +/// The lease bytes of a state at `at` whose head holds `mtp_len` rows (layout.Plan's length for it). +pub fn leaseBytes(sh: Shape, at: u32, mtp_len: u64) u64 { + var n: u64 = sh.prefix + sh.tail; + for (0..sh.layers) |_| for (cache(sh, at)) |x| { + n += x; + }; + if (sh.head) for (cache(sh, mtp_len)) |x| { + n += x; + }; + return n; +} + +/// Rank 0's image bytes at `at` (its head counted at a verify window past `at`). +pub fn imageBytes(sh: Shape, at: u32) u64 { + var n: u64 = Words.bytes + front(sh, at) + sh.tail; + if (sh.head) for (cache(sh, sh.headRows(at))) |x| { + n += x; + }; + return n; +} + +/// `len` bytes at `off` of rank `rank`'s image; `shared`: past rank 0's prefix, the same bytes every rank holds. +pub const Piece = struct { rank: u32, off: u64, len: u64, shared: bool }; + +/// The store's image at `at`: rank 0's, then each other rank's prefix (rank 0's bytes stand for all the rest). +pub fn storeParts(sh: Shape, prefixes: []const u64, at: u32, out: *std.ArrayList(Part), a: std.mem.Allocator) !void { + try parts(sh, at, out, a); + for (prefixes[1..]) |p| try out.append(a, .{ .bytes = p }); +} + +/// Store image bytes [off, off + len) split by rank: rank 0's image, then rank r's prefix after its words. +pub fn route(sh: Shape, prefixes: []const u64, at: u32, off: u64, len: u64, out: *std.ArrayList(Piece), a: std.mem.Allocator) !void { + const own = Words.bytes + sh.prefix; // rank 0's bytes no other rank holds + var start: u64 = 0; // the section's first store byte + for (prefixes, 0..) |p, r| { + const size = if (r == 0) imageBytes(sh, at) else p; + defer start += size; + const lo = @max(off, start); + const hi = @min(off + len, start + size); + if (lo >= hi) continue; + if (r > 0) { + try out.append(a, .{ .rank = @intCast(r), .off = Words.bytes + lo - start, .len = hi - lo, .shared = false }); + continue; + } + if (lo < own) try out.append(a, .{ .rank = 0, .off = lo, .len = @min(hi, own) - lo, .shared = false }); + if (hi > own) try out.append(a, .{ .rank = 0, .off = @max(lo, own), .len = hi - @max(lo, own), .shared = true }); + } + if (off + len > start) return error.SnapshotShape; +} + +/// `len` store image bytes at `off`. +pub const Span = struct { off: u64, len: u64 }; + +/// Store image bytes no prompt pass to `at` writes: each rank's window rows, pools past the whole ones, the draft row. +pub fn unwritten(sh: Shape, prefixes: []const u64, windows: []const u64, at: u32, mtp_len: u64, out: *std.ArrayList(Span), a: std.mem.Allocator) !void { + if (windows.len != prefixes.len or windows.len == 0 or windows[0] != sh.window) return error.SnapshotShape; + if (sh.head and mtp_len > sh.headRows(at)) return error.SnapshotShape; + var img: u64 = Words.bytes + sh.prefix; + try out.append(a, .{ .off = Words.bytes + sh.window, .len = sh.prefix - sh.window }); + for (0..sh.layers) |_| { + const c = cache(sh, at); + const whole = at / sparse.pool * sh.pooled_row; + img += c[0] + c[1] + c[2] + c[3]; + try out.append(a, .{ .off = img + whole, .len = c[4] - whole }); + img += c[4]; + } + if (sh.head) { + const full = cache(sh, sh.headRows(at)); + const held = cache(sh, mtp_len)[4]; + const whole = mtp_len / sparse.pool * sh.pooled_row; + img += full[0] + full[1] + full[2] + full[3]; + try out.append(a, .{ .off = img + whole, .len = held - whole }); // past `held`, the image's zeros + img += full[4]; + } + try out.append(a, .{ .off = img + sh.draft, .len = sh.tail - sh.draft }); + img += sh.tail; + for (prefixes[1..], windows[1..]) |p, w| { + if (w > p) return error.SnapshotShape; + try out.append(a, .{ .off = img + w, .len = p - w }); // a rank's section is its prefix alone + img += p; + } +} + +/// Zeros `spans` of `bytes`, store image bytes from `from`, where they overlap. +pub fn clear(spans: []const Span, from: u64, bytes: []u8) void { + for (spans) |s| { + const lo = @max(s.off, from); + const hi = @min(s.off + s.len, from + bytes.len); + if (lo < hi) @memset(bytes[@intCast(lo - from)..@intCast(hi - from)], 0); + } +} + +/// Copies between `host` and image bytes [off, off + host.len) of a lease: out (lease to host) or in. +pub const Copy = struct { + d: *const cuda.Driver, + pool: *const pages.Pool, + lease: *const pages.Lease, + segs: []const Seg, + words: *[Words.count]u64, + + pub fn run(c: Copy, off: u64, host: []u8, out: bool) !void { + const end = off + host.len; + for (c.segs) |s| { + const lo = @max(off, s.img); + const hi = @min(end, s.img + s.len); + if (lo >= hi) continue; + const h = host[@intCast(lo - off)..][0..@intCast(hi - lo)]; + switch (s.from) { + .words => { + const w = std.mem.asBytes(c.words)[@intCast(lo - s.img)..][0..h.len]; + if (out) @memcpy(h, w) else @memcpy(w, h); + }, + .zeros => if (out) @memset(h, 0), + .lease => |at| try c.leased(at + (lo - s.img), h, out), + } + } + } + + /// `len` device bytes at `src` into image bytes from `off`, queued on `stream`: no host copy (a link's buffer). + pub fn fromDevice(c: Copy, off: u64, src: u64, len: u64, stream: cuda.abi.Stream) !void { + const arena = c.pool.arena orelse return error.NoSnapshotRoom; + const end = off + len; + for (c.segs) |s| { + const lo = @max(off, s.img); + const hi = @min(end, s.img + s.len); + if (lo >= hi) continue; + const at = switch (s.from) { + .words => return error.SnapshotShape, // the words go with the seal, from the host + .zeros => continue, + .lease => |x| x + (lo - s.img), + }; + if (at + (hi - lo) > c.lease.ids.items.len * pages.page) return error.SnapshotSize; + var done: u64 = 0; + while (done < hi - lo) { + const x = at + done; + const n = @min(hi - lo - done, pages.page - x % pages.page); + const dev = arena.ptr() + @as(u64, c.lease.ids.items[@intCast(x / pages.page)]) * pages.page + x % pages.page; + try c.d.check(c.d.api.cuMemcpyDtoDAsync_v2(dev, src + (lo - off) + done, @intCast(n), stream), "cuMemcpyDtoDAsync"); + done += n; + } + } + } + + /// Lease bytes from `at`, a page at a time (each page is a run of the snapshot arena). + fn leased(c: Copy, at: u64, host: []u8, out: bool) !void { + const arena = c.pool.arena orelse return error.NoSnapshotRoom; + if (at + host.len > c.lease.ids.items.len * pages.page) return error.SnapshotSize; + var done: usize = 0; + while (done < host.len) { + const x = at + done; + const n = @min(host.len - done, pages.page - x % pages.page); + const dev = arena.ptr() + @as(u64, c.lease.ids.items[@intCast(x / pages.page)]) * pages.page + x % pages.page; + const p = host[done..][0..n]; + if (out) { + try cuda.memory.download(c.d, dev, p); // staged through the pinned buffer on an integrated GPU + } else try c.d.check(c.d.api.cuMemcpyHtoD_v2(dev, p.ptr, n), "cuMemcpyHtoD"); + done += n; + } + } +}; + +test { + _ = @import("cuda_disk_image_test.zig"); +} diff --git a/zig/src/families/glm/cuda_disk_image_test.zig b/zig/src/families/glm/cuda_disk_image_test.zig new file mode 100644 index 00000000000..9b2e7c6d812 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_image_test.zig @@ -0,0 +1,411 @@ +//! GLM's disk image on a driver whose device memory is host memory: sizes against the snapshot plan, a round trip. +const std = @import("std"); +const cuda = @import("cuda"); +const weights = @import("cuda_weights.zig"); +const shard = @import("cuda_shard.zig"); +const image = @import("cuda_disk_image.zig"); +const State = @import("cuda_state.zig").State; +const Plan = @import("cuda_snapshot_layout.zig").Plan; +const pages = @import("cuda_snapshot_pages.zig"); +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const expectError = std.testing.expectError; + +/// Device addresses are host addresses: allocations from the page allocator, copies and fills as memcpy and memset. +pub const H = struct { + var held: [16]struct { ptr: u64 = 0, len: usize = 0 } = @splat(.{}); + fn bytes(p: u64, n: usize) []u8 { + return @as([*]u8, @ptrFromInt(p))[0..n]; + } + fn alloc(out: *u64, n: usize) callconv(.c) cuda.abi.Result { + const m = std.heap.page_allocator.alloc(u8, n) catch return 2; + for (&held) |*h| if (h.ptr == 0) { + h.* = .{ .ptr = @intFromPtr(m.ptr), .len = n }; + out.* = h.ptr; + return 0; + }; + std.heap.page_allocator.free(m); + return 2; + } + fn free(p: u64) callconv(.c) cuda.abi.Result { + for (&held) |*h| if (h.ptr == p) { + std.heap.page_allocator.free(bytes(h.ptr, h.len)); + h.* = .{}; + return 0; + }; + return 1; + } + fn set(p: u64, v: u8, n: usize) callconv(.c) cuda.abi.Result { + @memset(bytes(p, n), v); + return 0; + } + fn dtod(dst: u64, src: u64, n: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + @memcpy(bytes(dst, n), bytes(src, n)); + return 0; + } + fn dtoh(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) cuda.abi.Result { + @memcpy(@as([*]u8, @ptrCast(dst.?))[0..n], bytes(src, n)); + return 0; + } + fn htod(dst: u64, src: ?*const anyopaque, n: usize) callconv(.c) cuda.abi.Result { + @memcpy(bytes(dst, n), @as([*]const u8, @ptrCast(src.?))[0..n]); + return 0; + } + fn wait(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return 0; + } + fn contextDevice(out: *cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; + return 0; + } + fn deviceAttribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; // a discrete card: cuda.memory.download copies straight to the host + return 0; + } + pub fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.api.cuMemAlloc_v2 = alloc; + d.api.cuMemFree_v2 = free; + d.api.cuMemsetD8_v2 = set; + d.api.cuMemcpyDtoDAsync_v2 = dtod; + d.api.cuMemcpyDtoH_v2 = dtoh; + d.api.cuMemcpyHtoD_v2 = htod; + d.api.cuStreamSynchronize = wait; + d.api.cuCtxGetDevice = contextDevice; + d.api.cuDeviceGetAttribute = deviceAttribute; + return d; + } +}; + +pub const capacity = 6144; // past the index rings' 4,096 rows, so a state at the end holds a full ring + +/// TP=2 rank 0's shapes on KDA, DSA, KDA, DSA layers. +pub const Model = struct { + layers: [4]weights.Layer, + w: weights.Weights, + + pub fn init(m: *Model) !void { + for (&m.layers, [_]bool{ false, true, false, true }) |*l, mla| l.mixer = if (mla) .{ .mla = undefined } else .{ .kda = undefined }; + m.w = undefined; + m.w.config = .{}; + m.w.share = try shard.Share.of(&m.w.config, 0, 2); + m.w.layers = &m.layers; + } +}; + +test "GLM disk image: the lease bytes the image counts are the snapshot plan's, at each position and head length" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + for ([_]bool{ false, true }) |kv8| { + var st = try State.initFormat(std.testing.allocator, &d, &m.w, capacity, kv8); + defer st.deinit(); + for ([_]bool{ false, true }) |head| { + const sh = try image.Shape.of(&st, &m.w.config, capacity, head); + for ([_]u32{ 2048, 4096, 6144 }) |at| { + for ([_]u64{ at - 1, at, sh.headRows(at) }) |mtp| { + const plan = try Plan.init(&st, &m.w.config, at, if (head) mtp else null, 0); + try expectEqual(@as(u64, plan.len), image.leaseBytes(sh, at, if (head) mtp else 0)); + } + } + } + } +} + +test "GLM disk image: the longest state is a position the store's parts take, so the staging floor prices it" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + // capacities off and on a pool's edge: rows.attach prices `longest` and falls back to its default on an error + for ([_]usize{ capacity, capacity + 1, capacity + 3 }) |cap| { + var st = try State.initFormat(a, &d, &m.w, cap, false); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, cap, true); + const at = image.longest(sh); + try expect(at <= cap and cap - at < 4 and at % 4 == 0); + var parts: std.ArrayList(image.Part) = .empty; + defer parts.deinit(a); + try image.storeParts(sh, &.{ sh.prefix, sh.prefix }, at, &parts, a); + try expect(parts.items.len > 0); + try expectError(error.SnapshotShape, image.storeParts(sh, &.{ sh.prefix, sh.prefix }, at + 4, &parts, a)); + } +} + +test "GLM disk image: the store's rows are by position from 0 in whole blocks; rings, pools in progress and the head are its own" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + var st = try State.initFormat(std.testing.allocator, &d, &m.w, capacity, true); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, capacity, true); + const a = std.testing.allocator; + var list: std.ArrayList(image.Part) = .empty; + defer list.deinit(a); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + const at: u32 = 6144; + try image.parts(sh, at, &list, a); + try image.segments(sh, at, at, &segs, a); + var total: u64 = 0; + var rows: usize = 0; + for (list.items) |p| { + total += p.bytes; + if (p.row == 0) continue; + rows += 1; + try expect(256 % p.per == 0); + try expectEqual(@as(u64, at / p.per) * p.row, p.bytes); // a pooled part counts the whole pools alone + } + try expectEqual(@as(usize, 3 * 2), rows); // each DSA layer's latent rows, scales and whole pools + const last = segs.items[segs.items.len - 1]; + try expectEqual(total, last.img + last.len); + try expectEqual(@as(u64, 2 * 256), list.items[7].bytes); // layer 0's pools past `at`: the spare rows + try expectError(error.SnapshotShape, image.segments(sh, at, sh.headRows(at) + 1, &segs, a)); +} + +test "GLM disk image: a kept state's image read out of its lease restores every planned byte into another sequence" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + const c = &m.w.config; + var st = try State.initFormat(a, &d, &m.w, capacity, false); + defer st.deinit(); + for (H.bytes(st.arena.buf.ptr, st.arena.buf.len), 0..) |*b, i| b.* = @truncate(i *% 31 +% 7); + var pool = try pages.Pool.init(a, &d, 64 << 20, false); + defer pool.deinit(); + const stream: cuda.Stream = .{ .d = &d, .handle = null }; + const at: u32 = 2048; + const mtp: u64 = at - 1; // a head one row behind: its last image row is not in the lease + const sh = try image.Shape.of(&st, c, capacity, true); + const plan = try Plan.init(&st, c, at, mtp, 0); + var kept = try pool.take(plan.len); + defer pool.give(&kept); + try pool.move(stream, &kept, &plan, true); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + try image.segments(sh, at, mtp, &segs, a); + const last = segs.items[segs.items.len - 1]; + const img = try a.alloc(u8, @intCast(last.img + last.len)); + defer a.free(img); + var words = (image.Words{ .at = at, .mtp_len = mtp, .base = 0, .mtp_base = 0, .cur = 0b10, .world = 2 }).encode(); + const out: image.Copy = .{ .d = &d, .pool = &pool, .lease = &kept, .segs = segs.items, .words = &words }; + const cut = [_]u64{ 0, 1000, plan.len / 2, img.len }; // the store asks for ranges, not the whole image + for (cut[0..3], cut[1..]) |lo, hi| try out.run(lo, img[@intCast(lo)..@intCast(hi)], true); + for (segs.items) |s| if (s.from == .zeros) for (img[@intCast(s.img)..][0..@intCast(s.len)]) |b| try expectEqual(@as(u8, 0), b); + // a blank state as a disk read takes it (room for the head's whole window), filled from the image + var blank = try pool.take(@intCast(image.leaseBytes(sh, at, sh.headRows(at)))); + defer pool.give(&blank); + var back: [image.Words.count]u64 = undefined; + const in: image.Copy = .{ .d = &d, .pool = &pool, .lease = &blank, .segs = segs.items, .words = &back }; + try in.run(0, img, false); + const w = try image.Words.decode(back, at, 2, .unsplit); + try expectEqual(mtp, w.mtp_len); + try expectEqual(@as(u64, 0b10), w.cur); + try expectError(error.DiskWords, image.Words.decode(back, at + 2048, 2, .unsplit)); + var fresh = try State.initFormat(a, &d, &m.w, capacity, false); + defer fresh.deinit(); + const into = try Plan.init(&fresh, c, at, w.mtp_len, 0); + try expectEqual(plan.len, into.len); + try pool.move(stream, &blank, &into, false); + for (plan.parts[0..plan.count], into.parts[0..into.count]) |x, y| { + try std.testing.expectEqualSlices(u8, H.bytes(x.live, x.len), H.bytes(y.live, y.len)); + } +} + +test "GLM disk image: the store's image is rank 0's then each other rank's prefix, and routes every byte once" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + var st = try State.initFormat(a, &d, &m.w, capacity, true); + defer st.deinit(); + const sh = try image.Shape.of(&st, &m.w.config, capacity, true); + const at: u32 = 4096; + const prefixes = [_]u64{ sh.prefix, sh.prefix - 4096, sh.prefix + 512 }; // TP=3: heads one by one + var list: std.ArrayList(image.Part) = .empty; + defer list.deinit(a); + try image.storeParts(sh, &prefixes, at, &list, a); + var total: u64 = 0; + for (list.items) |p| total += p.bytes; + try expectEqual(image.imageBytes(sh, at) + prefixes[1] + prefixes[2], total); + var pieces: std.ArrayList(image.Piece) = .empty; + defer pieces.deinit(a); + var seen: [3]u64 = .{ 0, 0, 0 }; + var shared: u64 = 0; + const cuts = [_]u64{ 0, 40, image.Words.bytes + sh.prefix - 8, image.imageBytes(sh, at) + 100, total }; // ranges across the seams + for (cuts[0 .. cuts.len - 1], cuts[1..]) |lo, hi| { + pieces.clearRetainingCapacity(); + try image.route(sh, &prefixes, at, lo, hi - lo, &pieces, a); + var n: u64 = 0; + for (pieces.items) |p| { + n += p.len; + seen[p.rank] += p.len; + if (p.shared) shared += p.len; + if (p.rank > 0) try expect(p.off >= image.Words.bytes and p.off + p.len <= image.Words.bytes + prefixes[p.rank] and !p.shared); + if (p.shared) try expect(p.rank == 0 and p.off >= image.Words.bytes + sh.prefix); + } + try expectEqual(hi - lo, n); + } + try expectEqual(image.imageBytes(sh, at), seen[0]); + try expectEqual(prefixes[1], seen[1]); + try expectEqual(prefixes[2], seen[2]); + try expectEqual(image.imageBytes(sh, at) - image.Words.bytes - sh.prefix, shared); + try expectError(error.SnapshotShape, image.route(sh, &prefixes, at, total - 4, 8, &pieces, a)); +} + +/// The fields of an engine the kept-state functions read, over a host-memory driver. +const Fake = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stream: cuda.Stream, + c: @import("config.zig").Config, + cur: struct { st: State, in_head: usize = 0 }, + capacity: usize = capacity, + mtp: bool = true, + snaps: std.AutoHashMapUnmanaged(u64, @import("cuda_engine_types.zig").Snap) = .empty, + snap_pages: ?pages.Pool = null, + share_pages: bool = false, +}; + +test "GLM disk image: a disk read's blank state is refused until sealed, and its seal checks the words" { + const snaps = @import("cuda_snapshots.zig"); + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + var e: Fake = .{ .gpa = a, .d = &d, .stream = .{ .d = &d, .handle = null }, .c = m.w.config, .cur = .{ .st = try State.initFormat(a, &d, &m.w, capacity, false) } }; + defer e.cur.st.deinit(); + e.snap_pages = try pages.Pool.init(a, &d, 256 << 20, false); + defer e.snap_pages.?.deinit(); + try e.snaps.ensureTotalCapacity(a, 8); + defer e.snaps.deinit(a); + const at: u32 = 2048; + try snaps.blankAs(&e, 7, at); + defer { + var s = e.snaps.get(7).?; + snaps.free(&e, &s); + } + try expectError(error.StateKept, snaps.blankAs(&e, 7, at)); + try expectError(error.UnsealedState, snaps.restore(&e, 7)); + try expectError(error.DiskWords, snaps.seal(&e, 7, at + @import("cuda_state.zig").window_rows + 1, .{ 0, 0 }, 0)); // a head past its verify window + try expectError(error.DiskWords, snaps.seal(&e, 7, at, .{ 0, 0 }, @as(u64, 1) << @intCast(e.cur.st.cur.len))); // a copy bit no layer has + try expectError(error.DiskWords, snaps.seal(&e, 7, at - 1, .{ at + 1, 0 }, 0)); // a main ring based past the state + try expectError(error.DiskWords, snaps.seal(&e, 7, at - 1, .{ 0, at }, 0)); // a head ring based past its rows + try snaps.seal(&e, 7, at - 1, .{ 3, 5 }, 0b01); + const s = e.snaps.get(7).?; + const sh = try image.Shape.of(&e.cur.st, &e.c, capacity, true); + try expectEqual(image.leaseBytes(sh, at, at - 1), @as(u64, s.len)); + try expectEqual(@as(usize, at - 1), s.mtp_len); + try expectEqual([2]usize{ 3, 5 }, s.bases); + try std.testing.expectEqualSlices(u1, &.{ 1, 0 }, s.cur); + try expectError(error.StateKept, snaps.seal(&e, 7, at, .{ 0, 0 }, 0)); + const far: u32 = capacity - 1024; // a state past the rings' rows + const back: u32 = far - @as(u32, @intCast(e.cur.st.ring_rows)); // the least base whose ring still holds its rows + try snaps.blankAs(&e, 8, far); + defer { + var held = e.snaps.get(8).?; + snaps.free(&e, &held); + } + try expectError(error.DiskWords, snaps.seal(&e, 8, far, .{ back - 1, back }, 0)); // a main ring too far back + try expectError(error.DiskWords, snaps.seal(&e, 8, far, .{ back, back - 1 }, 0)); // a head ring too far back + try snaps.seal(&e, 8, far, .{ back, back }, 0); + try snaps.blankAs(&e, 9, far); + defer { + var held = e.snaps.get(9).?; + snaps.free(&e, &held); + } + try snaps.seal(&e, 9, 0, .{ back, 0 }, 0); // no head rows yet (as without drafts): the main ring holds the state's rows +} + +test "GLM disk image: the words record the world, the layout and the owner, and a read refuses another by name" { + const at: u32 = 4096; + const w: image.Words = .{ .at = at, .mtp_len = 7, .base = 1, .mtp_base = 2, .cur = 0b1, .world = 3 }; + const x = w.encode(); + try expectEqual(@as(u64, 72), image.Words.bytes); + try expectEqual(@as(usize, image.Words.bytes), @sizeOf(@TypeOf(x))); + // an unsplit state: every rank holds every row, so no rank owns it + try std.testing.expectEqualSlices(u64, &.{ 3, 0, image.Words.no_owner }, x[6..]); + try expectEqual(w, try image.Words.decode(x, at, 3, .unsplit)); + try expectError(error.DiskWorld, image.Words.decode(x, at, 2, .unsplit)); // written by three ranks, read by two + try expectError(error.DiskWorld, image.Words.decode(x, at, 4, .unsplit)); + const split: image.Words.Layout = @fromBackingInt(@intCast(1)); + try expectError(error.DiskLayout, image.Words.decode(x, at, 3, split)); // this server splits, the image does not + var y = x; + y[7] = 1; // an image of a split layout read unsplit + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, .unsplit)); + const owned = try image.Words.decode(y[0..8].* ++ [1]u64{2}, at, 3, split); + try expectEqual(@as(u64, 2), owned.owner); + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, split)); // a split image names an owner rank + try expectError(error.DiskLayout, image.Words.decode(y[0..8].* ++ [1]u64{3}, at, 3, split)); + y = x; + y[8] = 0; // an unsplit image that names an owner + try expectError(error.DiskLayout, image.Words.decode(y, at, 3, .unsplit)); + y = x; + y[0] = 2; // the format comes first: a format this server does not read is DiskWords, whatever its layout + try expectError(error.DiskWords, image.Words.decode(y, at, 2, .unsplit)); +} + +/// A state's store image at `at` for two ranks, rank 1's prefix a copy of rank 0's: what the load's probe gathers. +fn storeImage(a: std.mem.Allocator, d: *const cuda.Driver, pool: *pages.Pool, st: *const State, c: *const @import("config.zig").Config, sh: image.Shape, at: u32, mtp: u64) ![]u8 { + const plan = try Plan.init(st, c, at, mtp, 0); + var kept = try pool.take(plan.len); + defer pool.give(&kept); + try pool.move(.{ .d = d, .handle = null }, &kept, &plan, true); + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(a); + try image.segments(sh, at, mtp, &segs, a); + const own = image.imageBytes(sh, at); + const out = try a.alloc(u8, @intCast(own + sh.prefix)); + errdefer a.free(out); + @memset(out[0..image.Words.bytes], 0); // the words are not the probe's question + const copy: image.Copy = .{ .d = d, .pool = pool, .lease = &kept, .segs = segs.items, .words = undefined }; + try copy.run(image.Words.bytes, out[image.Words.bytes..@intCast(own)], true); + @memcpy(out[@intCast(own)..], out[image.Words.bytes..][0..@intCast(sh.prefix)]); + return out; +} + +test "GLM disk image: the probe's hash leaves out what a prompt pass does not write, whatever the slot ran before" { + var m: Model = undefined; + try m.init(); + var d = H.driver(); + const a = std.testing.allocator; + const c = &m.w.config; + var st = try State.initFormat(a, &d, &m.w, capacity, false); + defer st.deinit(); + for (H.bytes(st.arena.buf.ptr, st.arena.buf.len), 0..) |*b, i| b.* = @truncate(i *% 31 +% 7); + var pool = try pages.Pool.init(a, &d, 64 << 20, false); + defer pool.deinit(); + const at: u32 = 2048; + const mtp: u64 = at - 1; // the head a row behind: its last pool unfinished + const sh = try image.Shape.of(&st, c, capacity, true); + const prefixes = [_]u64{ sh.prefix, sh.prefix }; + var loose: std.ArrayList(image.Span) = .empty; + defer loose.deinit(a); + try image.unwritten(sh, &prefixes, &.{ sh.window, sh.window }, at, mtp, &loose, a); + try expectError(error.SnapshotShape, image.unwritten(sh, &prefixes, &.{ sh.window + 1, sh.window }, at, mtp, &loose, a)); + const before = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(before); + // what load's timed windows leave in the slot: a window's rows, keys past `at`'s whole pools, the first-draft row + const row = c.i_dim * 2; + const pool_rows = @import("cuda_sparse.zig").pool; + @memset(H.bytes(st.proj, st.caches[0].lc - st.proj), 0xa5); + for (st.caches) |x| @memset(H.bytes(x.pk + at / pool_rows * row, 2 * row), 0xa5); + @memset(H.bytes(st.mtp_caches.pk + mtp / pool_rows * row, 2 * row), 0xa5); + @memset(H.bytes(st.prompt_hidden, c.hidden * 2), 0xa5); + const after = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(after); + try expect(!std.mem.eql(u8, before, after)); // the image carries them: hashed whole, two loads named two stores + image.clear(loose.items, 0, before); + image.clear(loose.items, 0, after); + try std.testing.expectEqualSlices(u8, before, after); + // what the prompt writes still names the store: a KDA state, a whole pool's keys + for ([_]u64{ st.conv, st.caches[1].pk }) |p| { + H.bytes(p, 1)[0] ^= 1; + defer H.bytes(p, 1)[0] ^= 1; + const changed = try storeImage(a, &d, &pool, &st, c, sh, at, mtp); + defer a.free(changed); + image.clear(loose.items, 0, changed); + try expect(!std.mem.eql(u8, before, changed)); + } +} diff --git a/zig/src/families/glm/cuda_disk_ranks.zig b/zig/src/families/glm/cuda_disk_ranks.zig new file mode 100644 index 00000000000..5d63d7d1f0f --- /dev/null +++ b/zig/src/families/glm/cuda_disk_ranks.zig @@ -0,0 +1,250 @@ +//! A GLM kept state's disk image across ranks: rank 0's engine thread leases, fills, reads and seals each rank's copy. +const std = @import("std"); +const cuda = @import("cuda"); +const follow = @import("cuda_follow.zig"); +const image = @import("cuda_disk_image.zig"); +const snapshots = @import("cuda_snapshots.zig"); +const Engine = @import("cuda_engine.zig").Engine; + +/// Rank 0 at TP: its follow link, set by Link.lead, cleared by its deinit; null: one rank, every op local. +pub var link: ?*follow.Link = null; + +/// A disk step's op (Header.flags); its id is `a`, its image offset `seed`, its bytes `depth`, its rank `top_k`. +pub const Op = enum(u32) { blank = 1, rows, take, seal, prefixes }; +const kind = @backingInt(follow.Kind.disk); // each op crosses the follow link as a disk step, its bytes as the ids + +/// This rank's image shape (every sequence of the engine has the same). +pub fn shape(e: *const Engine) !image.Shape { + return image.Shape.of(&e.cur.st, &e.c, e.capacity, e.mtp); +} + +/// The words of a kept state on this rank: its position, head rows, ring bases, KDA copy bits and layout (unsplit). +pub fn wordsOf(e: *const Engine, id: u64) !image.Words { + const s = e.snaps.get(id) orelse return error.NoKeptState; + if (s.cur.len > 64) return error.SnapshotShape; + var cur: u64 = 0; + for (s.cur, 0..) |b, i| cur |= @as(u64, b) << @intCast(i); + return .{ .at = s.pos, .mtp_len = s.mtp_len, .base = s.bases[0], .mtp_base = s.bases[1], .cur = cur, .world = e.share.world }; +} + +/// Bytes [off, off + host.len) of this rank's image of `id`, out (lease to host) or in; unsealed: before its head only. +pub fn copy(e: *Engine, id: u64, off: u64, host: []u8, out: bool) !void { + const H = struct { + host: []u8, + out: bool, + fn run(h: @This(), c: image.Copy, at: u64) !void { + return c.run(at, h.host, h.out); + } + }; + return through(e, id, off, host.len, H{ .host = host, .out = out }); +} + +/// `len` device bytes at `src` into this rank's image of `id` from `off`, queued on `stream` (the caller waits). +pub fn copyDevice(e: *Engine, id: u64, off: u64, src: u64, len: u64, stream: cuda.Stream) !void { + const D = struct { + src: u64, + len: u64, + stream: cuda.Stream, + fn run(x: @This(), c: image.Copy, at: u64) !void { + return c.fromDevice(at, x.src, x.len, x.stream.handle); + } + }; + return through(e, id, off, len, D{ .src = src, .len = len, .stream = stream }); +} + +/// `how.run` on the image of `id` for `len` bytes from `off`, refused past an unsealed state's words and front. +fn through(e: *Engine, id: u64, off: u64, len: u64, how: anytype) !void { + const s = e.snaps.get(id) orelse return error.NoKeptState; + const sh = try shape(e); + const at: u32 = @intCast(s.pos); + if (s.len == 0 and off + len > image.Words.bytes + image.front(sh, at)) return error.DiskOrder; + var segs: std.ArrayList(image.Seg) = .empty; + defer segs.deinit(e.gpa); + try image.segments(sh, at, s.mtp_len, &segs, e.gpa); + var w = (try wordsOf(e, id)).encode(); + const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; + try how.run(image.Copy{ .d = e.d, .pool = pool, .lease = &s.lease, .segs = segs.items, .words = &w }, off); +} + +/// Rank 0's link at TP, else null (one rank: every op is local). +fn leader(e: *Engine) ?follow.Leader { + return .{ .e = e, .link = link orelse return null }; +} + +/// Rank 0: whether the other ranks sleep on their lines (no stream), and putting them back to sleep after disk steps. +pub fn asleep(e: *Engine) bool { + return if (leader(e)) |x| x.link.asleep else false; +} + +pub fn rest(e: *Engine) !void { + if (leader(e)) |x| try x.idle(); +} + +/// Rank 0: a new id leased at `at` on every rank (rank 0 first: the ranks' pools match, so theirs cannot fail apart). +pub fn blank(e: *Engine, at: u32) !u64 { + if (e.next_snap > std.math.maxInt(u32)) return error.SnapshotIdLimit; + const id = e.next_snap; + try snapshots.blankAs(e, id, at); + e.next_snap += 1; + // a failed step: rank 0's lease goes back, and its id is dropped at the next step (another rank may hold it) + errdefer snapshots.drop(e, id); + if (leader(e)) |x| try x.disk(.{ .kind = kind, .flags = @backingInt(Op.blank), .a = id, .seed = at }, &.{}); + return id; +} + +/// A piece's rank in a `rows` step for the bytes every rank holds: each rank's image at `off` past its own prefix. +pub const every: u32 = std.math.maxInt(u32); + +/// Bytes for rank `to`'s image at `off`, or for every rank's (`every`: `off` less rank 0's prefix, each adds its own). +pub const Piece = struct { to: u32, off: u64, bytes: []const u8 }; + +/// Rank 0 at TP: `pieces` into every rank's image of `id`, each step a table (4 words a piece) and one broadcast. +pub fn rows(e: *Engine, id: u64, pieces: []const Piece) !void { + const x = leader(e) orelse return error.NoRank; + const stage = std.mem.sliceAsBytes(x.link.ids); // the bytes on the host, then in the link's buffer after its header + var table: std.ArrayList(u32) = .empty; + defer table.deinit(e.gpa); + var i: usize = 0; + var done: usize = 0; // bytes of pieces[i] in earlier steps (a piece longer than the link goes in parts) + while (i < pieces.len) { + table.clearRetainingCapacity(); + var n: usize = 0; + while (i < pieces.len and n < stage.len and table.items.len + 4 <= x.link.ids.len) { + const p = pieces[i]; + const k = @min(p.bytes.len - done, stage.len - n); + const off = p.off + done; + try table.appendSlice(e.gpa, &.{ @truncate(off), @intCast(off >> 32), @intCast(k), p.to }); + @memcpy(stage[n..][0..k], p.bytes[done..][0..k]); + n += k; + done += k; + if (done == p.bytes.len) { + i += 1; + done = 0; + } + } + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.rows), .a = id, .depth = @intCast(n) }, table.items); + try x.link.stream.synchronize(); // the table's broadcasts read the buffer the bytes go to + try x.link.buf.upload(64, stage[0..n]); + try x.link.from(0, n); + try place(e, id, table.items, x.link.buf.ptr + 64, x.link.stream); + } +} + +/// A `rows` step's pieces for this rank, copied from `src` (the link's buffer) and waited for: the next step reuses it. +fn place(e: *Engine, id: u64, table: []const u32, src: u64, stream: cuda.Stream) !void { + const me: u32 = @intCast(e.share.rank); + const own = (try shape(e)).prefix; + var at: u64 = 0; + var i: usize = 0; + while (i < table.len) : (i += 4) { + const off = @as(u64, table[i]) | @as(u64, table[i + 1]) << 32; + const len: u64 = table[i + 2]; + if (table[i + 3] == every) try copyDevice(e, id, off + own, src + at, len, stream) else if (table[i + 3] == me) try copyDevice(e, id, off, src + at, len, stream); + at += len; + } + try stream.synchronize(); +} + +/// A `rows` step's table checked against its bytes and the link before a follower joins the broadcast. +fn fits(ids: []const u32, depth: u32, room: usize) !void { + if (ids.len % 4 != 0 or depth > room) return error.BadStep; + var n: u64 = 0; + var i: usize = 0; + while (i < ids.len) : (i += 4) n += ids[i + 2]; + if (n != depth) return error.BadStep; +} + +/// Rank 0: rank `rank`'s image bytes of `id` from `off` into `out`. +pub fn take(e: *Engine, rank: u32, id: u64, off: u64, out: []u8) !void { + if (rank == 0) return copy(e, id, off, out, true); + const x = leader(e) orelse return error.NoRank; + const room = x.link.ids.len * 4; + var done: usize = 0; + while (done < out.len) { + const n = @min(room, out.len - done); + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.take), .a = id, .seed = off + done, .depth = @intCast(n), .top_k = rank }, &.{}); + try x.link.from(rank, n); + try x.link.buf.download(64, out[done..][0..n]); + done += n; + } +} + +/// Rank 0: each other rank's bytes of `id` past its prefix (`each`) equal to `shared`, but for `loose` (zeros there). +pub fn same(e: *Engine, id: u64, each: []const u64, shared: []const u8, loose: []const image.Span, theirs: []u8) !void { + for (each[1..], 1..) |q, r| { + try take(e, @intCast(r), id, image.Words.bytes + q, theirs); + image.clear(loose, 0, theirs); + if (!std.mem.eql(u8, shared, theirs)) return error.RanksDiffer; + } +} + +/// Words read back for a state at `at`: refused by name unless this server's world and layout (unsplit) wrote them. +pub fn decode(e: *const Engine, x: [image.Words.count]u64, at: u32) !image.Words { + return image.Words.decode(x, at, @intCast(e.share.world), .unsplit); +} + +/// Rank 0: every rank's blank `id` sealed with `w` (its head's rows, ring bases and KDA copy bits). +pub fn seal(e: *Engine, id: u64, w: image.Words) !void { + try snapshots.seal(e, id, w.mtp_len, .{ w.base, w.mtp_base }, w.cur); + if (leader(e)) |x| { + const words = w.encode(); + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.seal), .a = id }, std.mem.bytesAsSlice(u32, std.mem.sliceAsBytes(&words))); + } +} + +/// Rank 0: every rank's prefix bytes in rank order (what it holds alone), and where its window rows begin in it. +pub fn prefixes(e: *Engine, out: []u64, windows: []u64) !void { + const sh = try shape(e); + if (windows.len != out.len) return error.NoRank; + const x = leader(e) orelse { + if (out.len != 1) return error.NoRank; + out[0] = sh.prefix; + windows[0] = sh.window; + return; + }; + try x.disk(.{ .kind = kind, .flags = @backingInt(Op.prefixes) }, &.{}); + try gather(x.link, e, sh.prefix, out); + try gather(x.link, e, sh.window, windows); +} + +fn gather(l: *follow.Link, e: *const Engine, mine: u64, out: []u64) !void { + try @import("cuda_ranks.zig").gather(u64, l.d, l.lib, l.comm, l.stream, e.share.rank, mine, out); +} + +/// A rank other than 0: rank 0's disk step on this rank's copy of its state. +pub fn step(e: *Engine, l: *follow.Link, h: follow.Header, ids: []const u32) !void { + if (h.flags < @backingInt(Op.blank) or h.flags > @backingInt(Op.prefixes)) return error.BadStep; + const op: Op = @fromBackingInt(h.flags); + const rank: u32 = @intCast(e.share.rank); + switch (op) { + .blank => try snapshots.blankAs(e, h.a, @intCast(h.seed)), + .seal => { + if (ids.len != image.Words.count * 2) return error.BadStep; + var x: [image.Words.count]u64 = undefined; + @memcpy(std.mem.sliceAsBytes(&x), std.mem.sliceAsBytes(ids)); + const w = try decode(e, x, @intCast((e.snaps.get(h.a) orelse return error.NoKeptState).pos)); + try snapshots.seal(e, h.a, w.mtp_len, .{ w.base, w.mtp_base }, w.cur); + }, + .rows => { + try fits(ids, h.depth, l.buf.len - 64); + try l.from(0, h.depth); + try place(e, h.a, ids, l.buf.ptr + 64, l.stream); + }, + .take => { + if (h.depth > l.ids.len * 4) return error.BadStep; + if (h.top_k == rank) { + const host = std.mem.sliceAsBytes(l.ids)[0..h.depth]; + try copy(e, h.a, h.seed, host, true); + try l.buf.uploadAsync(64, host, l.stream.handle); + } + try l.from(h.top_k, h.depth); + }, + .prefixes => { + var out: [64]u64 = undefined; + if (e.share.world > out.len) return error.BadStep; + const sh = try shape(e); + try gather(l, e, sh.prefix, out[0..e.share.world]); + try gather(l, e, sh.window, out[0..e.share.world]); + }, + } +} diff --git a/zig/src/families/glm/cuda_disk_ranks_test.zig b/zig/src/families/glm/cuda_disk_ranks_test.zig new file mode 100644 index 00000000000..b2db547e0b5 --- /dev/null +++ b/zig/src/families/glm/cuda_disk_ranks_test.zig @@ -0,0 +1,294 @@ +//! GLM disk steps across ranks on host memory and a fake link: a failed blank, byte order, refusals, shared bytes. +const std = @import("std"); +const cuda = @import("cuda"); +const ranks = @import("cuda_disk_ranks.zig"); +const image = @import("cuda_disk_image.zig"); +const follow = @import("cuda_follow.zig"); +const snapshots = @import("cuda_snapshots.zig"); +const pages = @import("cuda_snapshot_pages.zig"); +const fixture = @import("cuda_disk_image_test.zig"); +const State = @import("cuda_state.zig").State; +const Seq = @import("cuda_engine_types.zig").Seq; +const Engine = @import("cuda_engine.zig").Engine; +const t = std.testing; + +/// The link's kernel and NCCL: the put kernel records each step's header; a broadcast fails, or brings a rank's bytes. +const Wire = struct { + var fail = false; + var odd: c_int = 0; // a rank whose bytes differ from rank 0's (0: none) + var sent: [8]follow.Header = undefined; + var steps: usize = 0; + var casts: usize = 0; + + fn reset() void { + fail = false; + odd = 0; + steps = 0; + casts = 0; + } + fn byte(i: usize) u8 { + return @truncate(i *% 13 +% 5); + } + fn put(_: cuda.abi.Function, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, params: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + const w: *align(1) const follow.Words = @ptrCast(params.?[2].?); + if (steps < sent.len) @memcpy(std.mem.asBytes(&sent[steps]), std.mem.sliceAsBytes(w.w[0..16])); + steps += 1; + return 0; + } + fn broadcast(_: cuda.abi.DevicePtr, dst: cuda.abi.DevicePtr, n: usize, _: cuda.nccl.DataType, root: c_int, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) cuda.nccl.Result { + if (fail) return 1; + casts += 1; + if (root != 0) for (@as([*]u8, @ptrFromInt(dst))[0..n], 0..) |*b, i| { + b.* = byte(i) ^ @intFromBool(root == odd); + }; + return 0; + } + fn device(out: *cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; + return 0; + } + fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { + out.* = 0; // a discrete card: a download copies straight to the host + return 0; + } +}; + +/// A TP=2 engine's rank 0 over host memory (the fields the disk steps read), its snapshot pool and its link. +const Rig = struct { + m: fixture.Model, + d: cuda.Driver, + lib: cuda.nccl.Library, + seq: Seq, + e: *Engine, + buf: [64 + 64 * 4]u8 align(8), // the link's device buffer: header, then ids + ids: [64]u32, + link: follow.Link, + + fn init(x: *Rig) !void { + const a = t.allocator; + Wire.reset(); + try x.m.init(); + x.d = fixture.H.driver(); + x.d.api.cuLaunchKernel = Wire.put; + x.d.api.cuLaunchKernelEx = @import("cuda_pdl.zig").forwardEx(Wire.put); // GLM's launches go through cuda_pdl + x.d.api.cuCtxGetDevice = Wire.device; + x.d.api.cuDeviceGetAttribute = Wire.attribute; + x.lib = .{ .lib = undefined, .api = undefined }; + x.lib.api.ncclBroadcast = Wire.broadcast; + x.seq = .{ .st = try State.initFormat(a, &x.d, &x.m.w, fixture.capacity, false) }; + errdefer x.seq.st.deinit(); + const e = try a.create(Engine); + e.gpa = a; + e.d = &x.d; + e.c = x.m.w.config; + e.share = x.m.w.share; + e.cur = &x.seq; + e.capacity = fixture.capacity; + e.mtp = true; + e.slot = 0; + e.stream = .{ .d = &x.d, .handle = null }; + e.m.glue.put_words = .{ .d = &x.d, .handle = null }; + e.share_pages = false; + e.next_snap = 1; + e.announce = 0; + e.snaps = .empty; + e.dropped = .empty; + e.snap_pages = null; + x.e = e; + errdefer x.free(); + try e.snaps.ensureTotalCapacity(a, 8); + try e.dropped.ensureTotalCapacity(a, 9); + e.snap_pages = try pages.Pool.init(a, &x.d, 256 << 20, false); + x.link = .{ .d = &x.d, .lib = &x.lib, .comm = null, .stream = e.stream, .buf = .{ .d = &x.d, .ptr = @intFromPtr(&x.buf), .len = x.buf.len, .borrowed = true }, .ids = &x.ids, .gpa = a, .wait = false }; + } + + fn free(x: *Rig) void { + const e = x.e; + var it = e.snaps.valueIterator(); + while (it.next()) |s| snapshots.free(e, s); + e.snaps.deinit(e.gpa); + e.dropped.deinit(e.gpa); + if (e.snap_pages) |*p| p.deinit(); + e.gpa.destroy(e); + } + + fn deinit(x: *Rig) void { + ranks.link = null; + x.free(); + x.seq.st.deinit(); + } +}; + +const disk = @backingInt(follow.Kind.disk); + +fn op(o: ranks.Op) u32 { + return @backingInt(o); +} + +test "GLM disk ranks: a blank whose step fails on the link gives rank 0's lease back, and the next step drops it" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const pool = &x.e.snap_pages.?; + const all = pool.spare(); + Wire.fail = true; + try t.expectError(error.NcclFailed, ranks.blank(x.e, 2048)); + try t.expectEqual(@as(u32, 0), x.e.snaps.count()); + try t.expectEqual(all, pool.spare()); + try t.expectEqualSlices(u32, &.{1}, x.e.dropped.items); // the step may have reached the others: they drop it + Wire.reset(); + const id = try ranks.blank(x.e, 2048); + try t.expectEqual(@as(u64, 2), id); // the dropped id is not used again + try t.expectEqual(@as(usize, 2), Wire.steps); + try t.expectEqual(@backingInt(follow.Kind.drop), Wire.sent[0].kind); + try t.expectEqual(@as(u32, 1), Wire.sent[0].n); + try t.expectEqual(disk, Wire.sent[1].kind); + try t.expectEqual(op(.blank), Wire.sent[1].flags); + try t.expectEqual(id, Wire.sent[1].a); + try t.expect(pool.spare() < all); +} + +test "GLM disk ranks: rank 0's link carries the disk steps at TP only, and its deinit leaves none behind" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + var l = x.link; + l.ids = try t.allocator.alloc(u32, 4); + l.lead(true, 1); // one rank: every op stays local + try t.expect(l.asleep and ranks.link == null); + l.lead(false, 2); + try t.expect(!l.asleep and ranks.link == &l); + var other = x.link; + other.ids = try t.allocator.alloc(u32, 4); + other.deinit(); // another link's end leaves rank 0's + try t.expect(ranks.link == &l); + l.deinit(); + try t.expect(ranks.link == null); +} + +test "GLM disk ranks: a blank state takes bytes past its words and front only once sealed" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + const at: u32 = 2048; + const id = try ranks.blank(x.e, at); // one rank: no link + const front: usize = @intCast(image.Words.bytes + image.front(try ranks.shape(x.e), at)); + const buf = try t.allocator.alloc(u8, front + 64); + defer t.allocator.free(buf); + @memset(buf, 0); + try ranks.copy(x.e, id, 0, buf[0..front], false); + try t.expectError(error.DiskOrder, ranks.copy(x.e, id, front - 8, buf[0..16], false)); // across the front + try t.expectError(error.DiskOrder, ranks.copy(x.e, id, front, buf[0..1], true)); // read out, too + try snapshots.seal(x.e, id, at - 1, .{ 0, 0 }, 0); + try ranks.copy(x.e, id, front - 8, buf[0..16], false); + try ranks.copy(x.e, id, front, buf[0..1], true); +} + +test "GLM disk ranks: a follower refuses a disk step rank 0 does not send, before its states or the link" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + x.e.share.rank = 1; + const room = x.link.ids.len * 4; + const bad = [_]struct { h: follow.Header, n: usize }{ + .{ .h = .{ .kind = disk, .flags = 0 }, .n = 0 }, // no op + .{ .h = .{ .kind = disk, .flags = op(.prefixes) + 1 }, .n = 0 }, // past the last op + .{ .h = .{ .kind = disk, .flags = op(.seal), .a = 1 }, .n = 1 }, // words of another length + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = 8 }, .n = 3 }, // a table of part pieces + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = 9 }, .n = 4 }, // pieces of other bytes than the step's + .{ .h = .{ .kind = disk, .flags = op(.rows), .a = 1, .depth = @intCast(room + 1) }, .n = 0 }, // past the link + .{ .h = .{ .kind = disk, .flags = op(.take), .a = 1, .depth = @intCast(room + 1), .top_k = 0 }, .n = 0 }, // past the link + }; + x.ids[0..4].* = .{ image.Words.bytes, 0, 8, 1 }; // one piece of 8 bytes for rank 1 + for (bad) |b| try t.expectError(error.BadStep, ranks.step(x.e, &x.link, b.h, x.ids[0..b.n])); + x.e.share.world = 65; // more ranks than a gather holds + try t.expectError(error.BadStep, ranks.step(x.e, &x.link, .{ .kind = disk, .flags = op(.prefixes) }, &.{})); + try t.expectEqual(@as(u32, 0), x.e.snaps.count()); + try t.expectEqual(@as(usize, 0), Wire.casts); +} + +test "GLM disk ranks: each other rank's shared bytes come from past its own prefix and must equal rank 0's" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const prefixes = [_]u64{ 4096, 1024, 2048 }; // TP=3: each rank's own bytes first + var shared: [100]u8 = undefined; + for (&shared, 0..) |*b, i| b.* = Wire.byte(i); + var theirs: [100]u8 = undefined; + try ranks.same(x.e, 7, &prefixes, &shared, &.{}, &theirs); + try t.expectEqual(@as(usize, 2), Wire.steps); + for (Wire.sent[0..2], 1..) |h, r| { + try t.expectEqual(op(.take), h.flags); + try t.expectEqual(@as(u64, 7), h.a); + try t.expectEqual(@as(u32, @intCast(r)), h.top_k); + try t.expectEqual(image.Words.bytes + prefixes[r], h.seed); + try t.expectEqual(@as(u32, theirs.len), h.depth); + } + // bytes a prompt pass does not write are left out: rank 0's as zeros, each other rank's whatever it holds there + const loose = [_]image.Span{.{ .off = 10, .len = 20 }}; + image.clear(&loose, 0, &shared); + try t.expectError(error.RanksDiffer, ranks.same(x.e, 7, &prefixes, &shared, &.{}, &theirs)); + try ranks.same(x.e, 7, &prefixes, &shared, &loose, &theirs); + Wire.odd = 2; + try t.expectError(error.RanksDiffer, ranks.same(x.e, 7, &prefixes, &shared, &loose, &theirs)); +} + +test "GLM disk ranks: rank 0 sends a block's pieces for every rank in as few steps as the link holds, and copies the shared ones itself" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + ranks.link = &x.link; + const at: u32 = 2048; + const id = try ranks.blank(x.e, at); + const own = (try ranks.shape(x.e)).prefix; + var bytes: [440]u8 = undefined; + for (&bytes, 0..) |*b, i| b.* = Wire.byte(i); + const w = image.Words.bytes; + const pieces = [_]ranks.Piece{ + .{ .to = ranks.every, .off = w + 16, .bytes = bytes[0..100] }, // every rank's, past its own prefix + .{ .to = 1, .off = w + 8, .bytes = bytes[100..140] }, + .{ .to = 2, .off = w, .bytes = bytes[140..440] }, // longer than the link's room (256 bytes) with the rest + }; + try ranks.rows(x.e, id, &pieces); + try t.expectEqual(@as(usize, 3), Wire.steps); // the blank, then two rows steps for the 440 bytes + const want = [_]struct { depth: u32, n: u32 }{ .{ .depth = 256, .n = 12 }, .{ .depth = 184, .n = 4 } }; + for (Wire.sent[1..3], want) |h, g| { + try t.expectEqual(disk, h.kind); + try t.expectEqual(op(.rows), h.flags); + try t.expectEqual(id, h.a); + try t.expectEqual(g.depth, h.depth); + try t.expectEqual(g.n, h.n); + } + var got: [100]u8 = undefined; + try ranks.copy(x.e, id, own + w + 16, &got, true); // rank 0's own copy of the shared bytes + try t.expectEqualSlices(u8, bytes[0..100], &got); + try t.expectEqualSlices(u8, bytes[256..440], x.buf[64..][0..184]); // the last step's bytes went out whole +} + +test "GLM disk ranks: a follower copies its pieces and the shared ones from the step's broadcast, and no other rank's" { + var x: Rig = undefined; + try x.init(); + defer x.deinit(); + x.e.share.rank = 1; + const at: u32 = 2048; + try snapshots.blankAs(x.e, 3, at); + const own = (try ranks.shape(x.e)).prefix; + const w = image.Words.bytes; + var before: [64]u8 = undefined; + try ranks.copy(x.e, 3, w, &before, true); + for (x.buf[64..][0..100], 0..) |*b, i| b.* = Wire.byte(i); // the bytes as rank 0's broadcast leaves them + const table = [_]u32{ w + 4, 0, 50, ranks.every, w + 8, 0, 30, 1, w, 0, 20, 2 }; + @memcpy(x.ids[0..table.len], &table); + try ranks.step(x.e, &x.link, .{ .kind = disk, .flags = op(.rows), .a = 3, .depth = 100 }, x.ids[0..table.len]); + var got: [50]u8 = undefined; + try ranks.copy(x.e, 3, own + w + 4, &got, true); + try t.expectEqualSlices(u8, x.buf[64..][0..50], &got); + try ranks.copy(x.e, 3, w + 8, got[0..30], true); + try t.expectEqualSlices(u8, x.buf[64 + 50 ..][0..30], got[0..30]); + var after: [64]u8 = undefined; + try ranks.copy(x.e, 3, w, &after, true); + try t.expectEqualSlices(u8, before[0..8], after[0..8]); // rank 2's piece at w did not land here + try t.expectEqual(@as(usize, 1), Wire.casts); +} diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 1e8724243b5..3561a154bb5 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -16,7 +16,7 @@ const sparse = @import("cuda_sparse.zig"); const prompt_pair = @import("cuda_prompt_pair.zig"); const Engine = engine.Engine; -pub const Kind = enum(u32) { begin = 1, prefill, verify, keep, draft, end, drop, release, chunk, shared, image, block, many, redraw, idle, snapshots, pool, form, cuts }; +pub const Kind = enum(u32) { begin = 1, prefill, verify, keep, draft, end, drop, release, chunk, shared, image, block, many, redraw, idle, snapshots, pool, form, cuts, disk }; /// One step as it crosses: 64 bytes, then `n` u32 ids. pub const Header = extern struct { @@ -67,7 +67,14 @@ pub const Link = struct { return .{ .d = d, .lib = lib, .comm = comm, .stream = stream, .buf = buf, .ids = try gpa.alloc(u32, max_ids), .gpa = gpa, .wait = wait }; } + /// Rank 0, before it serves: whether the other ranks begin asleep; at TP its kept states' disk steps cross here. + pub fn lead(l: *Link, asleep: bool, world: usize) void { + l.asleep = asleep; + if (world > 1) @import("cuda_disk_ranks.zig").link = l; + } + pub fn deinit(l: *Link) void { + if (@import("cuda_disk_ranks.zig").link == l) @import("cuda_disk_ranks.zig").link = null; l.gpa.free(l.ids); l.buf.free(); } @@ -114,6 +121,14 @@ pub const Link = struct { try l.lib.check(l.lib.api.ncclBroadcast(ptr, ptr, bytes, .u8, 0, l.comm, l.stream.handle), "ncclBroadcast"); } + /// `bytes` after the header from rank `root` into every rank's buffer (a disk step's take: cuda_disk_ranks). + pub fn from(l: *Link, root: u32, bytes: usize) !void { + if (bytes == 0) return; + if (64 + bytes > l.buf.len) return error.TooManyIds; + try l.lib.check(l.lib.api.ncclBroadcast(l.buf.ptr + 64, l.buf.ptr + 64, bytes, .u8, @intCast(root), l.comm, l.stream.handle), "ncclBroadcast"); + try l.stream.synchronize(); + } + /// Other ranks: the next step and its ids (valid until the next receive). pub fn receive(l: *Link) !struct { h: Header, ids: []const u32 } { try l.bcast(first_bytes); @@ -329,6 +344,14 @@ pub const Leader = struct { x.e.m.experts.fact = forms; } + /// A kept state's disk step (cuda_disk_ranks): its op and ids to every rank. + pub fn disk(x: Leader, h: Header, ids: []const u32) !void { + try x.flush(); + var hh = h; + hh.kind = @backingInt(Kind.disk); + try x.send(hh, ids); + } + /// The other ranks leave their loops. pub fn end(x: Leader) !void { try x.send(.{ .kind = @backingInt(Kind.end) }, &.{}); @@ -363,7 +386,7 @@ pub fn follow(e: *Engine, link: *Link) !void { const step = try link.receive(); const h = step.h; const kind: Kind = @fromBackingInt(@intCast(h.kind)); - if (kind != .end and kind != .drop and kind != .shared and kind != .block and kind != .many and kind != .idle and kind != .snapshots and kind != .pool and kind != .form) try e.bind(h.slot); + if (kind != .end and kind != .drop and kind != .shared and kind != .block and kind != .many and kind != .idle and kind != .snapshots and kind != .pool and kind != .form and kind != .disk) try e.bind(h.slot); e.prompt_logprobs = if (promptRows(h)) .{} else null; e.structured = structuredStep(h); // rank 0 alone masks them switch (kind) { @@ -442,6 +465,7 @@ pub fn follow(e: *Engine, link: *Link) !void { e.share_pages = h.flags & 1 != 0; // TF_KV_SHARE on rank 0: a kept state leaves the shared store's pages out try @import("cuda_snapshots.zig").agree(e, h.a); }, + .disk => try @import("cuda_disk_ranks.zig").step(e, link, h, step.ids), .drop => for (step.ids) |id| e.dropState(id), .release => e.release(h.slot), .idle => cuda.tp_watch.sleep(e.io), diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index d3ee01332fa..17e42b8388d 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -368,7 +368,7 @@ fn finishRank(a: OpenArgs) !Loaded { // Rank 0 alone reads these: TF_GLM_PROMPT_STEPS=0 passes prompts whole, TF_GLM_SHARED=0 runs windows alone. const steps = try @import("sys").environment.value(bool, "TF_GLM_PROMPT_STEPS", ranks.environment("TF_GLM_PROMPT_STEPS"), true); const shared = try @import("sys").environment.value(bool, "TF_GLM_SHARED", ranks.environment("TF_GLM_SHARED"), true); - own.link.asleep = cuda.tp_watch.open(); // the other ranks begin asleep (follow): the first step wakes them + own.link.lead(cuda.tp_watch.open(), p.world); // the other ranks begin asleep (follow): the first step wakes them own.lanes = .{ .x = .{ .e = own.e, .link = &own.link }, .whole = !steps, .alone = !shared, .mtp_confidence = o.mtp_confidence }; const extra: u64 = (if (o.drafter != null) dflash.ring_bytes else 0) + if (own.e.images) |v| v.streamBytes() else @as(usize, 0); own.layout = if (set.pages) try pages_mod.layout(gpa, own.e, extra) else null; diff --git a/zig/src/families/glm/cuda_snapshot_pages.zig b/zig/src/families/glm/cuda_snapshot_pages.zig index 2e48cb6d4df..2b6f8040e26 100644 --- a/zig/src/families/glm/cuda_snapshot_pages.zig +++ b/zig/src/families/glm/cuda_snapshot_pages.zig @@ -19,7 +19,7 @@ const Arena = union(enum) { device: cuda.DeviceBuffer, host: struct { buf: cuda.HostBuffer, ptr: u64 }, - fn ptr(a: Arena) u64 { + pub fn ptr(a: Arena) u64 { return switch (a) { .device => |b| b.ptr, .host => |h| h.ptr, diff --git a/zig/src/families/glm/cuda_snapshots.zig b/zig/src/families/glm/cuda_snapshots.zig index bf8a9d7b6ce..8986ea83638 100644 --- a/zig/src/families/glm/cuda_snapshots.zig +++ b/zig/src/families/glm/cuda_snapshots.zig @@ -64,8 +64,42 @@ pub fn keepAs(e: anytype, id: u64) !void { } } +/// A disk read's state: `at`'s pages leased under rank 0's id on each rank, refused by `restore` until `seal`. +pub fn blankAs(e: anytype, id: u64, at: usize) !void { + if (e.snaps.contains(id)) return error.StateKept; + const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; + var lease = try pool.take(bytes(e, at)); + errdefer pool.give(&lease); + const cur = try e.gpa.alloc(u1, e.cur.st.cur.len); + @memset(cur, 0); + e.snaps.putAssumeCapacityNoClobber(id, .{ .lease = lease, .len = 0, .pos = at, .mtp_len = 0, .cur = cur, .bases = .{ 0, 0 } }); +} + +/// Whether an index ring of `rows` rows based at `base` holds every row up to `len`, as the image's ring bytes do. +fn ringHolds(base: usize, len: usize, rows: usize) bool { + return base <= len and len - base <= rows; +} + +/// A blank state made whole from its image's words (its bytes are in or follow): a restore takes it from here. +pub fn seal(e: anytype, id: u64, mtp_len: usize, bases: [2]usize, cur: u64) !void { + const s = e.snaps.getPtr(id) orelse return error.NoKeptState; + if (s.len != 0) return error.StateKept; + if (s.cur.len > 64 or (s.cur.len < 64 and cur >> @intCast(s.cur.len) != 0)) return error.DiskWords; + const head = if (e.mtp) @min(e.capacity, s.pos + @import("cuda_state.zig").window_rows) else 0; + if (mtp_len > head) return error.DiskWords; + const rows = e.cur.st.ring_rows; + if (!ringHolds(bases[0], s.pos, rows) or !ringHolds(bases[1], mtp_len, rows)) return error.DiskWords; + const n = try layout.Plan.size(&e.cur.st, &e.c, e.capacity, s.pos, if (e.mtp) mtp_len else null, s.shared); + if (n == 0 or n > s.lease.ids.items.len * pages.page) return error.SnapshotSize; + for (s.cur, 0..) |*b, i| b.* = @intCast(cur >> @intCast(i) & 1); + s.len = n; + s.mtp_len = mtp_len; + s.bases = bases; +} + pub fn restore(e: anytype, id: u64) !void { const s = e.snaps.getPtr(id) orelse return error.NoKeptState; + if (s.len == 0) return error.UnsealedState; const pool = if (e.snap_pages) |*p| p else return error.NoSnapshotCache; // the kept state's own parity picks the half a live-half keep carries; the slot's dead half stays as it is const plan = try layout.Plan.initFor(&e.cur.st, &e.c, s.pos, if (e.mtp) s.mtp_len else null, s.shared, s.cur); diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 482f985d076..215b87e059e 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -24,6 +24,12 @@ pub const pagesOn = kv_pages.on; pub const KvPages = kv_pages.KvPages; pub const KvSpan = kv_pages.KvSpan; const kvp = kv_pages.kvp; +const kv_grow = @import("kv_grow.zig"); +const kv_slots = @import("kv_slots.zig"); + +/// The host's hook for buffers a slot's K/V growth made. +pub const Grown = struct { ctx: *anyopaque, added: *const fn (ctx: *anyopaque, buffers: []const mtl.Buffer) void }; + /// Whether `cb` failed on the GPU; its Metal error (out of memory, a timeout) is logged with `what` it ran. pub fn gpuFailed(cb: mtl.CommandBuffer, what: []const u8) bool { const msg = cb.failure() orelse return false; @@ -51,6 +57,10 @@ pub const Runner = struct { ready: u32, // slots [0, ready) have their K/V rows; a later slot takes its own when first used (ensure) capacity: u32, kv: ?KvPages = null, + /// TF_Q27_KV_GROW: slots hold the rows their streams reached, grown by this step; null: the whole context. + kv_step: ?u32 = null, + /// A grown slot's new buffers, for the host's residency set (committed now, as a new slot's are). + grown: ?Grown = null, active: ?[32]u8 = null, failed: bool = false, capture_taps: bool = false, @@ -84,15 +94,19 @@ pub const Runner = struct { /// A runner of `slots` whose first `ready` take their K/V rows now, the rest when first used (ensure). pub fn initReady(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32) !Runner { - return build(a, m, slots, capacity, ready, false); + return build(a, m, slots, capacity, ready, false, null); } /// A runner whose slots all take their K/V rows from one arena of core-pool pages, each promised `capacity` rows. pub fn initPaged(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32) !Runner { - return build(a, m, slots, capacity, slots, true); + return build(a, m, slots, capacity, slots, true, null); + } + + pub fn initGrow(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, kv_step: ?u32) !Runner { + return build(a, m, slots, capacity, ready, false, kv_step); } - fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool) !Runner { + fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool, kv_step: ?u32) !Runner { if (slots == 0 or slots > attn.planning.max_streams or capacity == 0 or m.frame.capacity % 16 != 0 or ready == 0 or ready > slots) return error.BadRoundCapacity; const geometry = try attn.planning.Geometry.fromConfig(m.config, try @import("simd_attention.zig").sharedPrefix(m.device.tensorUnits())); const linear_index = try a.alloc(u32, m.config.layers); @@ -163,14 +177,15 @@ pub const Runner = struct { } const kv: ?KvPages = if (paged) try kv_pages.caches(a, m, na, slots, capacity, caches) else null; errdefer if (kv) |k| kv_pages.free(k); + const first = if (kv_step) |s| kv_grow.first(s, capacity) else capacity; if (!paged) for (0..na) |layer| for (0..ready) |slot| { - caches[layer * slots + slot] = try slotCache(a, m, &owned, capacity); + caches[layer * slots + slot] = try kv_slots.slotCache(a, m, &owned, first); }; const offsets = try a.alloc(u32, slots); errdefer a.free(offsets); @memset(offsets, 0); const taps = try Taps.init(m.device, m.frame.capacity, @intCast(m.config.hidden)); - return .{ .allocator = a, .model = m, .geometry = geometry, .gdn = pool, .attention = attention, .scratch = scratch, .bindings = bindings, .caches = caches, .linear_index = linear_index, .attention_index = attention_index, .offsets = offsets, .owned = owned, .taps = taps, .slots = slots, .ready = ready, .capacity = capacity, .kv = kv }; + return .{ .allocator = a, .model = m, .geometry = geometry, .gdn = pool, .attention = attention, .scratch = scratch, .bindings = bindings, .caches = caches, .linear_index = linear_index, .attention_index = attention_index, .offsets = offsets, .owned = owned, .taps = taps, .slots = slots, .ready = ready, .capacity = capacity, .kv = kv, .kv_step = kv_step }; } pub const cover = slot_pages.cover; @@ -189,36 +204,29 @@ pub const Runner = struct { return kv_pages.spans(r, a, slot, at, list); } - /// One slot's K/V rows across the attention layers. - pub fn slotBytes(r: *const Runner) usize { - return r.caches.len / r.slots * 2 * @as(usize, r.capacity) * r.model.config.kvDim() * 2; + pub const slotBytes = kv_slots.slotBytes; + pub const ensure = kv_slots.ensure; + pub const heldRows = kv_slots.heldRows; + /// Slot `slot` holds `need` K/V rows, grown layer by layer (kv_slots.zig). + pub fn reserve(r: *Runner, slot: u32, need: u32) !void { + return kv_slots.reserve(r, slot, need); } - /// Slot `slot`'s K/V rows (the next unready slot, as free slots are taken lowest first); its new buffers. - pub fn ensure(r: *Runner, slot: u32) ![]const mtl.Buffer { - if (slot < r.ready) return &.{}; - if (slot != r.ready) return error.SlotOutOfOrder; - const first = r.owned.items.len; - errdefer { - for (r.owned.items[first..]) |b| b.deinit(); - r.owned.shrinkRetainingCapacity(first); - } - const layers = r.caches.len / r.slots; - for (0..layers) |layer| r.caches[layer * r.slots + slot] = try slotCache(r.allocator, r.model, &r.owned, r.capacity); - r.ready += 1; - if (r.residency) |f| for (r.owned.items[first..]) |b| f.join(f.ctx, b); - return r.owned.items[first..]; - } - - /// The K/V buffers of the ready slots (for a residency set). - pub fn readyBuffers(r: *const Runner, a: std.mem.Allocator, out: *std.ArrayList(mtl.Buffer)) !void { - if (r.kv) |k| return out.appendSlice(a, &.{ k.arena, k.tables }); - for (0..r.caches.len / r.slots) |layer| for (0..r.ready) |slot| { - const c = r.caches[layer * r.slots + slot]; - try out.appendSlice(a, &.{ c.keys.buffer, c.values.buffer }); - }; + pub const releaseGrown = kv_slots.release; + + /// Emptied slot `slot` holds the rows a prompt of `need` tokens fills, without a copy (kv_slots.zig). + pub fn admit(r: *Runner, slot: u32, need: u32) !void { + return kv_slots.admit(r, slot, need); } + pub const busy = kv_slots.busy; + /// settleSlot for a hook that holds the runner as an opaque pointer (a drafter context's ring). + pub fn settleOpaque(ctx: *anyopaque, slot: u32) void { + const r: *Runner = @ptrCast(@alignCast(ctx)); + r.settleSlot(slot); + } + + pub const readyBuffers = kv_slots.readyBuffers; pub fn setResident(r: *Runner, hook: ?mtl.ResidencySet.Follow) void { @import("residency.zig").setRunner(r, hook); } @@ -274,6 +282,7 @@ pub const Runner = struct { if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; for (round.slots, round.windows) |slot, window| try r.cover(slot, window.start + @as(u32, @intCast(window.parents.len))); + for (round.slots, round.windows) |slot, window| try r.reserve(slot, window.start + @as(u32, @intCast(window.parents.len))); const paths = try r.allocator.alloc([]const u32, round.windows.len); defer r.allocator.free(paths); @memset(paths, &.{}); @@ -518,7 +527,7 @@ pub const Runner = struct { pub fn attentionPlan(r: *Runner, round: *const Round) !attn.Plan { var windows: [attn.planning.max_streams]attn.planning.Window = undefined; if (round.windows.len > windows.len) return error.AttentionStreams; - for (round.windows, 0..) |window, i| windows[i] = .{ .parents = window.parents, .start = window.start, .capacity = r.capacity }; + for (round.windows, round.slots, 0..) |window, slot, i| windows[i] = .{ .parents = window.parents, .start = window.start, .capacity = if (r.kv_step != null) r.heldRows(slot) else r.capacity }; var plan = try attn.Plan.init(r.allocator, windows[0..round.windows.len], r.geometry); if (r.attention.join != null) plan.pair(&.{}); // a stream's rows in pairs over the keys below its window return plan; @@ -565,22 +574,6 @@ pub const Runner = struct { } }; -fn slotCache(a: std.mem.Allocator, m: *Model, owned: *std.ArrayList(mtl.Buffer), capacity: u32) !attn.Cache { - const bytes = @as(usize, capacity) * m.config.kvDim() * 2; - const key = try allocation(a, m.device, owned, bytes); - const value = try allocation(a, m.device, owned, bytes); - return .{ .keys = .{ .buffer = key }, .values = .{ .buffer = value }, .capacity = capacity }; -} - -fn allocation(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), bytes: usize) !mtl.Buffer { - const b = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); - owned.append(a, b) catch |err| { - b.deinit(); - return err; - }; - return b; -} - fn fingerprint(round: *const Round) [32]u8 { var hash = std.crypto.hash.sha2.Sha256.init(.{}); hash.update(std.mem.sliceAsBytes(round.ids)); diff --git a/zig/src/families/qwen27/dflash/caches.zig b/zig/src/families/qwen27/dflash/caches.zig index f6fefc31fc6..450ce655942 100644 --- a/zig/src/families/qwen27/dflash/caches.zig +++ b/zig/src/families/qwen27/dflash/caches.zig @@ -4,7 +4,7 @@ const cfg = @import("config.zig"); pub fn Pair(comptime Buffer: type) type { return struct { keys: Buffer, values: Buffer }; } -/// `layers` rolling K/V caches of the window plus one block, as a stream's drafter context holds them. +/// `layers` rolling K/V caches of each layer's window plus one block, as a stream's drafter context holds them. pub fn newCaches(comptime Buffer: type, a: std.mem.Allocator, device: anytype, c: cfg.Config, layers: usize) ![]Pair(Buffer) { const Cache = Pair(Buffer); const caches = try a.alloc(Cache, layers); @@ -14,8 +14,8 @@ pub fn newCaches(comptime Buffer: type, a: std.mem.Allocator, device: anytype, c cache.keys.deinit(); cache.values.deinit(); }; - for (caches) |*cache| { - const bytes = @as(usize, c.window + 16) * c.kvWidth() * 2; + for (caches, 0..) |*cache, i| { + const bytes = @as(usize, c.layerWindow(i) + 16) * c.kvWidth() * 2; const keys = try device.buffer(bytes, @import("metal").ResourceOptions.shared | @import("metal").ResourceOptions.untracked); const values = device.buffer(bytes, @import("metal").ResourceOptions.shared | @import("metal").ResourceOptions.untracked) catch |err| { keys.deinit(); diff --git a/zig/src/families/qwen27/dflash/config.zig b/zig/src/families/qwen27/dflash/config.zig index fa290e327bc..58446bf8676 100644 --- a/zig/src/families/qwen27/dflash/config.zig +++ b/zig/src/families/qwen27/dflash/config.zig @@ -8,7 +8,10 @@ pub const tap_ids = [max_taps]u32{ 5, 19, 33, 47, 61, 0, 0, 0 }; /// incoai/Ornith-1.5-122B-DFlash2: six layers over Ornith-1.5-122B's 48, a block of 16. pub const flint_tap_ids = [max_taps]u32{ 5, 15, 26, 36, 46, 0, 0, 0 }; pub const ornith_tap_ids = [max_taps]u32{ 1, 7, 14, 20, 26, 32, 39, 45 }; +/// DFlash2 (conv kernels and a candidate selector) or z-lab's DFlash v1 (a plain qwen3 body, taps fused by fc). +pub const Variant = enum { dflash2, v1 }; pub const Config = struct { + variant: Variant = .dflash2, hidden: u32 = 5120, intermediate: u32 = 17408, layers: u32 = 5, @@ -28,6 +31,22 @@ pub const Config = struct { theta: f64 = 10000000, taps: [max_taps]u32 = tap_ids, tap_count: u32 = 5, + /// v1: the layers whose layer_types entry is full_attention (DFlash2 layers are all sliding). + full: [8]bool = @splat(false), + /// v1: the positions a stream's drafter context keeps (its full layers see all of them; 0: the window). + history: u32 = 0, + /// Positions kept: the ring's rows and the full layers' context; sliding layers see the last `window` - 1. + pub fn span(c: Config) u32 { + return if (c.variant == .v1 and c.history > c.window) c.history else c.window; + } + /// Rows layer `i` attends behind its block: its own window, or the whole span for a full layer. + pub fn layerWindow(c: Config, i: usize) u32 { + return if (c.full[i]) c.span() else c.window; + } + /// A ring row: v1 keeps fused, normed taps (fc and hidden_norm ran in the taps pass); DFlash2 keeps raw taps. + pub fn ringWidth(c: Config) u32 { + return if (c.variant == .v1) c.hidden else c.tapWidth(); + } pub fn qWidth(c: Config) u32 { return c.heads * c.head_dim; } @@ -46,13 +65,16 @@ pub const Config = struct { pub fn depth(c: Config) u32 { return c.block - 1; } + /// DFlash2: 15 a layer and six globals; v1: 11 a layer beside fc, hidden_norm and norm. pub fn tensorCount(c: Config) usize { - return 15 * @as(usize, c.layers) + 6; + return if (c.variant == .v1) 11 * @as(usize, c.layers) + 3 else 15 * @as(usize, c.layers) + 6; } + /// DFlash2: seven linears and two conv projections a layer, fc and the selector's projection; v1: seven and fc. pub fn linearCount(c: Config) usize { - return 9 * @as(usize, c.layers) + 2; + return if (c.variant == .v1) 7 * @as(usize, c.layers) + 1 else 9 * @as(usize, c.layers) + 2; } pub fn check(c: Config) !void { + if (c.variant == .v1) return c.checkV1(); const dimensions = [_]u32{ c.hidden, c.intermediate, c.layers, c.vocab, c.heads, c.kv_heads, c.head_dim, c.target_layers, c.group, c.rank, c.topk }; for (dimensions) |n| if (n == 0) return error.BadDraftConfig; if (c.hidden % 64 != 0 or c.intermediate % 64 != 0 or c.hidden % c.group != 0 or c.heads % c.kv_heads != 0 or c.head_dim % 2 != 0 or (c.block != 8 and c.block != 16) or c.conv != 2 or c.layers > 8 or c.mask >= c.vocab or c.topk > c.vocab or c.window < c.block) return error.BadDraftConfig; @@ -67,10 +89,30 @@ pub const Config = struct { _ = try std.math.mul(u32, c.hidden / c.group, 4); if (q % 64 != 0) return error.BadDraftConfig; } + /// The drafters name in the serving and startup lines: DFlash for z-labs v1 layout, DFlash2 for its successor. + pub fn kind(c: Config) []const u8 { + return if (c.variant == .v1) "DFlash" else "DFlash2"; + } /// A draft reads one target's taps and vocabulary: its width, vocabulary and tapped depth. pub fn bind(c: Config, hidden: usize, vocab: usize, layers: usize) !void { if (hidden != c.hidden or vocab != c.vocab or layers != c.target_layers) return error.DraftForAnotherTarget; } + /// v1 has no conv kernels and no selector (group, conv and rank zero); its lattice keeps the head's top-k. + fn checkV1(c: Config) !void { + const dimensions = [_]u32{ c.hidden, c.intermediate, c.layers, c.vocab, c.heads, c.kv_heads, c.head_dim, c.target_layers, c.topk, c.tap_count }; + for (dimensions) |n| if (n == 0) return error.BadDraftConfig; + if (c.group != 0 or c.conv != 0 or c.rank != 0) return error.BadDraftConfig; + if (c.hidden % 64 != 0 or c.intermediate % 64 != 0 or c.heads % c.kv_heads != 0 or c.head_dim % 2 != 0 or c.block < 2 or c.block > 16 or c.layers > 8 or c.tap_count > max_taps or c.mask >= c.vocab or c.topk > 16 or c.topk > c.vocab or c.window < c.block) return error.BadDraftConfig; + if (!std.math.isFinite(c.eps) or c.eps <= 0 or !std.math.isFinite(c.theta) or c.theta <= 0) return error.BadDraftConfig; + for (c.taps[0..c.tap_count]) |i| if (i >= c.target_layers) return error.BadDraftConfig; + for (c.taps[0..c.tap_count], 0..) |tap, i| for (c.taps[0..i]) |previous| if (tap == previous) return error.UnsupportedDraftTaps; + for (c.taps[c.tap_count..]) |unused| if (unused != 0) return error.BadDraftConfig; + for (c.full[c.layers..]) |unused| if (unused) return error.BadDraftConfig; + const q = try std.math.mul(u32, c.heads, c.head_dim); + _ = try std.math.mul(u32, c.kv_heads, c.head_dim); + _ = try std.math.mul(u32, c.hidden, c.tap_count); + if (q % 64 != 0) return error.BadDraftConfig; + } /// Published Qwen, Ornith and Flint shapes admitted by the shared Metal draft runtime. pub fn requireStock(c: Config) !void { try c.check(); @@ -108,6 +150,7 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Config { const o = try object(p.value); const d = try object(o.get("dflash_config") orelse return error.BadDraftConfig); const architectures = o.get("architectures") orelse return error.BadDraftConfig; + if (architectures == .array and architectures.array.items.len == 1 and architectures.array.items[0] == .string and std.mem.eql(u8, architectures.array.items[0].string, "DFlashDraftModel")) return parseV1(o, d); if (architectures != .array or architectures.array.items.len != 1 or architectures.array.items[0] != .string or !std.mem.eql(u8, architectures.array.items[0].string, "DFlash2DraftModel")) return error.BadDraftConfig; try text(o, "model_type", "qwen3"); try text(o, "dtype", "bfloat16"); @@ -136,6 +179,41 @@ pub fn parse(gpa: std.mem.Allocator, raw: []const u8) !Config { try c.requireStock(); return c; } +/// z-lab's DFlash v1 layout (DFlashDraftModel): its taps, block, mask and layer kinds from the config. +fn parseV1(o: std.json.ObjectMap, d: std.json.ObjectMap) !Config { + try text(o, "model_type", "qwen3"); + try text(o, "dtype", "bfloat16"); + try text(o, "hidden_act", "silu"); + for ([_][]const u8{ "attention_bias", "tie_word_embeddings" }) |key| { + const v = o.get(key) orelse return error.BadDraftConfig; + if (v != .bool or v.bool) return error.BadDraftConfig; + } + // the draft attends to its whole block both ways; a config that says otherwise is not this reading + if (o.get("is_causal")) |v| if (v != .bool or v.bool) return error.BadDraftConfig; + for ([_][]const u8{ "conv_group_size", "conv_kernel_size", "selector_rank", "selector_top_k" }) |key| if (d.get(key) != null) return error.BadDraftConfig; + const sliding = o.get("use_sliding_window") orelse return error.BadDraftConfig; + if (sliding != .bool or !sliding.bool or try number(o, "attention_dropout") != 0) return error.BadDraftConfig; + const rope = try object(o.get("rope_parameters") orelse return error.BadDraftConfig); + try text(rope, "rope_type", "default"); + if (o.get("rope_scaling")) |v| if (v != .null) return error.BadDraftConfig; + var c = Config{ .variant = .v1, .hidden = try integer(o, "hidden_size"), .intermediate = try integer(o, "intermediate_size"), .layers = try integer(o, "num_hidden_layers"), .vocab = try integer(o, "vocab_size"), .heads = try integer(o, "num_attention_heads"), .kv_heads = try integer(o, "num_key_value_heads"), .head_dim = try integer(o, "head_dim"), .target_layers = try integer(o, "num_target_layers"), .block = try integer(d, "block_size"), .mask = try integer(d, "mask_token_id"), .window = try integer(o, "sliding_window"), .group = 0, .conv = 0, .rank = 0, .topk = 16, .eps = @floatCast(try number(o, "rms_norm_eps")), .theta = try number(rope, "rope_theta"), .taps = @splat(0), .tap_count = 0 }; + const taps = d.get("target_layer_ids") orelse return error.BadDraftConfig; + if (taps != .array or taps.array.items.len == 0 or taps.array.items.len > max_taps) return error.BadDraftConfig; + for (taps.array.items, 0..) |v, i| { + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) return error.BadDraftConfig; + c.taps[i] = @intCast(v.integer); + } + c.tap_count = @intCast(taps.array.items.len); + if (c.layers == 0 or c.layers > 8) return error.BadDraftConfig; + const types = o.get("layer_types") orelse return error.BadDraftConfig; + if (types != .array or types.array.items.len != c.layers) return error.BadDraftConfig; + for (types.array.items, 0..) |v, i| { + if (v != .string) return error.BadDraftConfig; + if (std.mem.eql(u8, v.string, "full_attention")) c.full[i] = true else if (!std.mem.eql(u8, v.string, "sliding_attention")) return error.BadDraftConfig; + } + try c.check(); + return c; +} /// --drafter's config against the target's, from the two folders' config.json: a refusal comes before either loads. pub fn admit(gpa: std.mem.Allocator, io: std.Io, target_dir: []const u8, draft_dir: []const u8) !Config { @@ -280,3 +358,89 @@ test "Flint DFlash2 binds only its published target shape and post-block taps" { bad.theta = 10000000; try std.testing.expectError(error.NotStockDFlash2, bad.requireStock()); } +// z-lab/Qwen3.5-9B-DFlash's config.json, as published (Ornith-1.5-9B-DFlash publishes the same file). +const v1_fixture = + \\{"architectures":["DFlashDraftModel"],"attention_bias":false,"attention_dropout":0.0, + \\"auto_map":{"AutoModel":"dflash.DFlashDraftModel"},"bos_token_id":null, + \\"dflash_config":{"block_size":16,"mask_token_id":248077,"target_layer_ids":[1,5,9,13,17,21,25,29]}, + \\"dtype":"bfloat16","eos_token_id":248044,"head_dim":128,"hidden_act":"silu","hidden_size":4096, + \\"initializer_range":0.02,"intermediate_size":12288, + \\"layer_types":["sliding_attention","sliding_attention","sliding_attention","sliding_attention","sliding_attention","full_attention"], + \\"max_position_embeddings":262144,"max_window_layers":6,"model_type":"qwen3","num_attention_heads":32, + \\"num_hidden_layers":6,"num_key_value_heads":8,"num_target_layers":32,"pad_token_id":null,"rms_norm_eps":1e-06, + \\"rope_parameters":{"rope_theta":10000000,"rope_type":"default"},"sliding_window":4096,"tie_word_embeddings":false, + \\"transformers_version":"5.7.0","use_cache":true,"use_sliding_window":true,"vocab_size":248320} +; +test "the 9B target takes its own DFlash v1 drafter, and the 27B target refuses it by name" { + const a = std.testing.allocator; + const nine = try targetJson(a, 4096, 12288, 32, 16, 32); + defer a.free(nine); + const big = try targetJson(a, 5120, 17408, 64, 24, 48); + defer a.free(big); + try std.testing.expectEqual(Variant.v1, (try admitFolders(nine, v1_fixture)).variant); + try std.testing.expectError(error.DraftForAnotherTarget, admitFolders(big, v1_fixture)); +} +test "a DFlash v1 config reads its own taps, layer kinds, block and window" { + const c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(Variant.v1, c.variant); + try std.testing.expectEqual(@as(u32, 8), c.tap_count); + try std.testing.expectEqualSlices(u32, &.{ 1, 5, 9, 13, 17, 21, 25, 29 }, c.taps[0..8]); + try std.testing.expectEqual(@as(u32, 16), c.block); + try std.testing.expectEqual(@as(u32, 15), c.depth()); + try std.testing.expectEqual(@as(u32, 248077), c.mask); + try std.testing.expectEqual(@as(u32, 4096), c.window); + try std.testing.expectEqual(@as(u32, 4096), c.hidden); + try std.testing.expectEqual(@as(u32, 12288), c.intermediate); + try std.testing.expectEqual(@as(u32, 6), c.layers); + try std.testing.expectEqual(@as(u32, 32), c.target_layers); + try std.testing.expectEqualSlices(bool, &.{ false, false, false, false, false, true }, c.full[0..6]); + try std.testing.expectEqual(@as(u32, 32768), c.tapWidth()); + try std.testing.expectEqual(@as(u32, 0), c.rank); + try std.testing.expectEqual(@as(u32, 16), c.topk); +} +test "a DFlash v1 draft counts eleven tensors a layer and seven linears a layer beside fc" { + const c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(@as(usize, 69), c.tensorCount()); + try std.testing.expectEqual(@as(usize, 43), c.linearCount()); +} +test "a DFlash v1 config whose taps fall past the target or repeat is refused" { + const a = std.testing.allocator; + const past = try std.mem.replaceOwned(u8, a, v1_fixture, "25,29]", "25,32]"); + defer a.free(past); + try std.testing.expectError(error.BadDraftConfig, parse(a, past)); + const repeated = try std.mem.replaceOwned(u8, a, v1_fixture, "25,29]", "25,25]"); + defer a.free(repeated); + try std.testing.expectError(error.UnsupportedDraftTaps, parse(a, repeated)); +} +test "a DFlash v1 config that asks for a causal draft is refused" { + const a = std.testing.allocator; + const causal = try std.mem.replaceOwned(u8, a, v1_fixture, "\"attention_bias\":false", "\"attention_bias\":false,\"is_causal\":true"); + defer a.free(causal); + try std.testing.expectError(error.BadDraftConfig, parse(a, causal)); +} +test "a v1 draft keeps fused ring rows and gives its full layer the whole span" { + var c = try parse(std.testing.allocator, v1_fixture); + try std.testing.expectEqual(@as(u32, 4096), c.ringWidth()); + try std.testing.expectEqual(@as(u32, 4096), c.span()); + c.history = 32768; + try std.testing.expectEqual(@as(u32, 32768), c.span()); + try std.testing.expectEqual(@as(u32, 4096), c.layerWindow(0)); + try std.testing.expectEqual(@as(u32, 32768), c.layerWindow(5)); +} +test "DFlash2 keeps raw tap rows and its window everywhere" { + var c = Config{}; + c.history = 32768; + try std.testing.expectEqual(@as(u32, 25600), c.ringWidth()); + try std.testing.expectEqual(@as(u32, 2048), c.layerWindow(0)); + try std.testing.expectEqual(@as(u32, 2048), c.span()); +} +test "the stock DFlash2 config keeps its five taps and twenty-five-thousand-wide rows" { + const c = try parse(std.testing.allocator, fixture); + try std.testing.expectEqual(Variant.dflash2, c.variant); + try std.testing.expectEqual(@as(u32, 5), c.tap_count); + try std.testing.expectEqual(@as(u32, 25600), c.tapWidth()); +} +test "a v1 config names its drafter DFlash, and DFlash2 stays DFlash2" { + try std.testing.expectEqualStrings("DFlash", (try parse(std.testing.allocator, v1_fixture)).kind()); + try std.testing.expectEqualStrings("DFlash2", (try parse(std.testing.allocator, fixture)).kind()); +} diff --git a/zig/src/families/qwen27/dflash/execution.zig b/zig/src/families/qwen27/dflash/execution.zig index f9544da5a22..f30683f2b7b 100644 --- a/zig/src/families/qwen27/dflash/execution.zig +++ b/zig/src/families/qwen27/dflash/execution.zig @@ -22,6 +22,13 @@ fn rotate(ops: op.Ops, frame: u64, x: op.View, positions: []const u64, heads: u3 try y.check(x.rows, x.width, .bf16); return y; } +fn add(ops: op.Ops, frame: u64, x: op.View, y: op.View) !op.View { + const sum = ops.vtable.add orelse return error.DraftOperatorShape; + try y.check(x.rows, x.width, .bf16); + const z = try sum(ops.ptr, frame, x, y); + try z.check(x.rows, x.width, .bf16); + return z; +} /// `block`: rows a conv window spans; a batched pass stacks several streams' blocks. fn convolve(ops: op.Ops, frame: u64, x: op.View, dynamic: op.View, weights: w.Conv, branch: u32, residual: ?op.View, c: Config, block: u32) !op.View { try dynamic.check(x.rows, c.dynamicWidth(), .bf16); @@ -35,9 +42,9 @@ pub fn append(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, conte try preparation.check(); const c = g.config; try c.check(); - if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.window) - 1))) return error.BadDraftContext; + if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.span()) - 1))) return error.BadDraftContext; for (positions, 0..) |p, i| if (p != context.end + i or p >= next.end) return error.BadCommittedTaps; - try taps.check(@intCast(positions.len), c.tapWidth(), .bf16); + try taps.check(@intCast(positions.len), c.ringWidth(), .bf16); const frame = try ops.vtable.begin(ops.ptr); defer ops.vtable.release(ops.ptr, frame); const transaction = try ops.vtable.context_begin(ops.ptr, context); @@ -50,9 +57,9 @@ fn checkAppend(g: *const w.Graph, preparation: op.Preparation, context: op.Conte try preparation.check(); const c = g.config; try c.check(); - if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.window) - 1))) return error.BadDraftContext; + if (context.cache == 0 or context.begin > context.end or next.cache != context.cache or positions.len == 0 or next.end != try std.math.add(u64, context.end, positions.len) or next.begin != @max(context.begin, next.end -| (@as(u64, c.span()) - 1))) return error.BadDraftContext; for (positions, 0..) |p, i| if (p != context.end + i or p >= next.end) return error.BadCommittedTaps; - try taps.check(@intCast(positions.len), c.tapWidth(), .bf16); + try taps.check(@intCast(positions.len), c.ringWidth(), .bf16); } /// Where appended keys and values go: a transaction's context, or a batched pass's stream. @@ -62,8 +69,8 @@ fn encodeAppend(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, tap } fn encodeAppendTo(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, taps: op.View, positions: []const u64, frame: u64, sink: Sink) !void { const c = g.config; - const fusion = try project(ops, frame, taps, g.fusion, preparation.mode); - const hidden = try norm(ops, frame, fusion, g.hidden_norm, c.eps, 1, c.hidden); + // a v1 ring holds rows already fused and normed (the target's taps pass ran fc and hidden_norm) + const hidden = if (c.variant == .v1) taps else try norm(ops, frame, try project(ops, frame, taps, g.fusion, preparation.mode), g.hidden_norm, c.eps, 1, c.hidden); for (g.layers, 0..) |layer, i| { const raw_keys = try project(ops, frame, hidden, layer.attention.k, preparation.mode); const keys = try rotate(ops, frame, try norm(ops, frame, raw_keys, layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), positions, c.kv_heads, c); @@ -79,7 +86,7 @@ fn encodeAppendTo(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, t pub fn appendBlock(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, taps: op.View, positions: []const u64, next: op.Context, anchor: u32, block: u32) !op.Lattice { if (block < 2 or block > 16) return error.BadRuntimeBlock; try checkAppend(g, preparation, context, taps, positions, next); - if (anchor >= g.config.vocab or next.end - next.begin > g.config.window - 1) return error.BadDraftContext; + if (anchor >= g.config.vocab or next.end - next.begin > g.config.span() - 1) return error.BadDraftContext; const frame = try ops.vtable.begin(ops.ptr); defer ops.vtable.release(ops.ptr, frame); const transaction = try ops.vtable.context_begin(ops.ptr, context); @@ -99,7 +106,7 @@ pub const Consumer = struct { ptr: *anyopaque, call: *const fn (*anyopaque, u64, fn start(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, anchor: u32) !u64 { try preparation.check(); try g.config.check(); - if (anchor >= g.config.vocab or context.cache == 0 or context.begin > context.end or context.end - context.begin > g.config.window - 1) return error.BadDraftContext; + if (anchor >= g.config.vocab or context.cache == 0 or context.begin > context.end or context.end - context.begin > g.config.span() - 1) return error.BadDraftContext; return ops.vtable.begin(ops.ptr); } fn encode(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, context: op.Context, anchor: u32, frame: u64, block: u32, given: []const u32) !Output { @@ -127,7 +134,9 @@ pub fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation for (given, 1..) |t, i| ids[i] = t; var hidden = try ops.vtable.embed(ops.ptr, frame, g.embed, ids[0..rows]); try hidden.check(rows, c.hidden, .bf16); - for (g.layers, 0..) |layer, i| { + if (c.variant == .v1) { + hidden = try layersV1(ops, g, preparation, frame, hidden, positions[0..rows], streams[0].context, if (n > 1) contexts[0..n] else &.{}, block); + } else for (g.layers, 0..) |layer, i| { var residual = hidden; const xn = try norm(ops, frame, hidden, layer.input_norm, c.eps, 1, c.hidden); const dynamic = try project(ops, frame, xn, layer.attention_conv.projection, preparation.mode); @@ -156,9 +165,32 @@ pub fn encodeStreams(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation const head = try ops.vtable.head(ops.ptr, frame, final); if (head.logits.handle == 0 or head.logits.rows != headed or head.logits.dtype != .bf16 or head.logits.width == 0 or head.logits.width > c.vocab or head.logits.stride < head.logits.width) return error.DraftOperatorShape; if (head.token_ids) |mapping| try mapping.check(1, head.logits.width, .u32) else if (head.logits.width != c.vocab) return error.DraftCandidateId; - const projected = try project(ops, frame, final, g.hidden_projection, preparation.mode); + // a v1 draft has no selector projection: its lattice reads none (rank 0), so the final rows stand in + const projected = if (c.variant == .v1) final else try project(ops, frame, final, g.hidden_projection, preparation.mode); return .{ .head = head, .projected = projected }; } +/// A DFlash v1 body: attention and a SwiGLU MLP a layer, each added to its residual (no conv kernels). +fn layersV1(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, embedded: op.View, positions: []const u64, context: op.Context, contexts: []const op.Context, block: u32) !op.View { + const c = g.config; + const rows = embedded.rows; + var hidden = embedded; + for (g.layers, 0..) |layer, i| { + const xn = try norm(ops, frame, hidden, layer.input_norm, c.eps, 1, c.hidden); + const query = try rotate(ops, frame, try norm(ops, frame, try project(ops, frame, xn, layer.attention.q, preparation.mode), layer.attention.q_norm, c.eps, c.heads, c.head_dim), positions, c.heads, c); + const keys = try rotate(ops, frame, try norm(ops, frame, try project(ops, frame, xn, layer.attention.k, preparation.mode), layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), positions, c.kv_heads, c); + const values = try project(ops, frame, xn, layer.attention.v, preparation.mode); + const attended = try ops.vtable.attention(ops.ptr, frame, .{ .context = context, .config = c, .layer = @intCast(i), .query = query, .keys = keys, .values = values, .positions = positions, .streams = contexts, .block = block }); + try attended.check(rows, c.qWidth(), .bf16); + hidden = try add(ops, frame, hidden, try project(ops, frame, attended, layer.attention.o, preparation.mode)); + const post = try norm(ops, frame, hidden, layer.post_norm, c.eps, 1, c.hidden); + const gate = try project(ops, frame, post, layer.mlp.gate, preparation.mode); + const up = try project(ops, frame, post, layer.mlp.up, preparation.mode); + const activated = try ops.vtable.swiglu(ops.ptr, frame, gate, up); + try activated.check(rows, c.intermediate, .bf16); + hidden = try add(ops, frame, hidden, try project(ops, frame, activated, layer.mlp.down, preparation.mode)); + } + return hidden; +} /// A stream's new taps for a batched pass: absorbed into its caches before its block reads them. pub const Absorb = struct { taps: op.View, positions: []const u64 }; @@ -168,15 +200,14 @@ pub const Stacked = struct { taps: op.View, positions: []const u64, spans: []con /// One read of each absorb weight for every stacked row, each row's position its own stream's. pub fn encodeStacked(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, s: Stacked) !void { const c = g.config; - try s.taps.check(@intCast(s.positions.len), c.tapWidth(), .bf16); + try s.taps.check(@intCast(s.positions.len), c.ringWidth(), .bf16); var next: u32 = 0; for (s.spans) |span| { if (span.rows == 0 or span.first != next) return error.BadCommittedTaps; next += span.rows; } if (next != s.positions.len) return error.BadCommittedTaps; - const fusion = try project(ops, frame, s.taps, g.fusion, preparation.mode); - const hidden = try norm(ops, frame, fusion, g.hidden_norm, c.eps, 1, c.hidden); + const hidden = if (c.variant == .v1) s.taps else try norm(ops, frame, try project(ops, frame, s.taps, g.fusion, preparation.mode), g.hidden_norm, c.eps, 1, c.hidden); for (g.layers, 0..) |layer, i| { const raw_keys = try project(ops, frame, hidden, layer.attention.k, preparation.mode); const keys = try rotate(ops, frame, try norm(ops, frame, raw_keys, layer.attention.k_norm, c.eps, c.kv_heads, c.head_dim), s.positions, c.kv_heads, c); @@ -192,7 +223,7 @@ pub fn encodeStacked(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation /// Each stream's new taps through its own absorb pass, in stream order. pub fn encodeAbsorbs(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, frame: u64, absorbs: []const ?Absorb) !void { for (absorbs, 0..) |a, k| if (a) |x| { - try x.taps.check(@intCast(x.positions.len), g.config.tapWidth(), .bf16); + try x.taps.check(@intCast(x.positions.len), g.config.ringWidth(), .bf16); try encodeAppendTo(ops, g, preparation, x.taps, x.positions, frame, .{ .stream = @intCast(k) }); }; } @@ -202,7 +233,7 @@ pub fn absorbBlocks(ops: op.Ops, g: *const w.Graph, preparation: op.Preparation, try preparation.check(); try g.config.check(); if (block < 2 or block > 16 or streams.len < 2 or streams.len * block > 128 or out.len != streams.len or absorbs.len != streams.len) return error.BadRuntimeBlock; - for (streams) |s| if (s.anchor >= g.config.vocab or s.context.cache == 0 or s.context.begin > s.context.end or s.context.end - s.context.begin > g.config.window - 1) return error.BadDraftContext; + for (streams) |s| if (s.anchor >= g.config.vocab or s.context.cache == 0 or s.context.begin > s.context.end or s.context.end - s.context.begin > g.config.span() - 1) return error.BadDraftContext; if (stacked) |s| try encodeStacked(ops, g, preparation, frame, s) else try encodeAbsorbs(ops, g, preparation, frame, absorbs); const output = try encodeStreams(ops, g, preparation, streams, frame, block, &.{}); try ops.vtable.lattices(ops.ptr, frame, output.head, output.projected, g.config, block, out); diff --git a/zig/src/families/qwen27/dflash/execution_v1_test.zig b/zig/src/families/qwen27/dflash/execution_v1_test.zig new file mode 100644 index 00000000000..5619426f7cd --- /dev/null +++ b/zig/src/families/qwen27/dflash/execution_v1_test.zig @@ -0,0 +1,183 @@ +//! Fake operators prove the DFlash v1 schedule: a plain qwen3 body, two residual adds a layer, no conv, no selector. +const std = @import("std"); +const ck = @import("../checkpoint.zig"); +const cfg = @import("config.zig"); +const op = @import("operators.zig"); +const execution = @import("execution.zig"); +const fixtures = @import("fixtures.zig"); +const session = @import("session.zig"); +const selector = @import("selector.zig"); +const toy = fixtures.toy_v1; +const Fake = struct { + handle: u64 = 1, + projects: u32 = 0, + adds: u32 = 0, + attends: u32 = 0, + appends: u32 = 0, + commits: u32 = 0, + ids: [16]u32 = undefined, + positions: [16]u64 = undefined, + headed: u32 = 0, + fn self(ptr: *anyopaque) *Fake { + return @ptrCast(@alignCast(ptr)); + } + fn view(f: *Fake, rows: u32, width: u32) op.View { + f.handle += 1; + return .{ .handle = f.handle, .rows = rows, .width = width, .stride = width, .dtype = .bf16 }; + } + fn begin(ptr: *anyopaque) !u64 { + self(ptr).handle += 1; + return self(ptr).handle; + } + fn release(_: *anyopaque, _: u64) void {} + fn project(ptr: *anyopaque, _: u64, x: op.View, t: ck.Tensor, _: op.Mode) !op.View { + if (t.bytes.len == 0) return error.FakeAbsentWeight; + self(ptr).projects += 1; + return self(ptr).view(x.rows, @intCast(t.shape[0])); + } + fn norm(ptr: *anyopaque, _: u64, x: op.View, n: op.Norm) !op.View { + if (x.width != n.heads * n.head_dim) return error.FakeNormShape; + return self(ptr).view(x.rows, x.width); + } + fn embed(ptr: *anyopaque, _: u64, _: ck.Linear, ids: []const u32) !op.View { + @memcpy(self(ptr).ids[0..ids.len], ids); + return self(ptr).view(@intCast(ids.len), toy.hidden); + } + fn conv(_: *anyopaque, _: u64, _: op.View, _: op.Conv) !op.View { + return error.FakeV1HasNoConv; + } + fn rope(ptr: *anyopaque, _: u64, x: op.View, a: op.Rotary) !op.View { + if (a.positions.len <= 16) @memcpy(self(ptr).positions[0..a.positions.len], a.positions); + return self(ptr).view(x.rows, x.width); + } + fn attention(ptr: *anyopaque, _: u64, a: op.Attention) !op.View { + if (a.mask != .all_slots or a.layer != self(ptr).attends or a.query.rows != a.positions.len or a.positions[0] != a.context.end) return error.FakeAttentionOrder; + self(ptr).attends += 1; + return self(ptr).view(a.query.rows, a.config.qWidth()); + } + fn swiglu(ptr: *anyopaque, _: u64, a: op.View, b: op.View) !op.View { + if (a.width != b.width or a.rows != b.rows) return error.FakeMlpShape; + return self(ptr).view(a.rows, a.width); + } + fn add(ptr: *anyopaque, _: u64, x: op.View, y: op.View) !op.View { + if (x.rows != y.rows or x.width != y.width or x.width != toy.hidden) return error.FakeAddShape; + self(ptr).adds += 1; + return self(ptr).view(x.rows, x.width); + } + fn mask(ptr: *anyopaque, _: u64, x: op.View, first: u32, count: u32) !op.View { + if (first != 1 or count != x.rows - 1) return error.FakeAnchorShift; + return self(ptr).view(count, x.width); + } + fn head(ptr: *anyopaque, _: u64, x: op.View) !op.Head { + self(ptr).headed = x.rows; + return .{ .logits = self(ptr).view(x.rows, toy.vocab) }; + } + fn lattices(_: *anyopaque, _: u64, _: op.Head, _: op.View, _: cfg.Config, _: u32, _: []op.Lattice) !void { + return error.FakeBatchedHead; + } + fn streamAppend(_: *anyopaque, _: u64, _: u32, _: u32, _: op.View, _: op.View, _: []const u64) !void { + return error.FakeBatchedHead; + } + /// A chain: depth d's best candidate is token 10 + d, its runner-up far behind. + fn lattice(_: *anyopaque, _: u64, h: op.Head, _: op.View, c: cfg.Config) !op.Lattice { + const a = std.testing.allocator; + const ids = try a.alloc(u32, h.logits.rows * c.topk); + errdefer a.free(ids); + const unary = try a.alloc(f32, ids.len); + errdefer a.free(unary); + for (0..h.logits.rows) |d| { + ids[d * c.topk] = @intCast(10 + d); + unary[d * c.topk] = 0; + ids[d * c.topk + 1] = @intCast(40 + d); + unary[d * c.topk + 1] = -20; + } + return .{ .gpa = a, .depth = h.logits.rows, .topk = c.topk, .rank = c.rank, .candidates = ids, .unary = unary, .projected = try a.alloc(f32, 0) }; + } + fn contextBegin(_: *anyopaque, _: op.Context) !u64 { + return 1; + } + fn append(ptr: *anyopaque, _: u64, _: u64, layer: u32, k: op.View, v: op.View, positions: []const u64) !void { + const f = self(ptr); + if (layer != f.appends or k.rows != positions.len or v.rows != k.rows) return error.FakeAppendOrder; + f.appends += 1; + } + fn commit(ptr: *anyopaque, _: u64, _: u64, _: op.Context) !void { + self(ptr).commits += 1; + } + fn stage(_: *anyopaque, _: u64, _: u64, _: op.Context) !void {} + fn abort(_: *anyopaque, _: u64) void {} + fn ops(f: *Fake) op.Ops { + return .{ .ptr = f, .vtable = &.{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = attention, .swiglu = swiglu, .mask_rows = mask, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = contextBegin, .context_append = append, .context_commit = commit, .context_stage = stage, .context_abort = abort, .stream_append = streamAppend, .add = add } }; + } +}; +fn taps() session.Batch { + return .{ .values = .{ .handle = 99, .rows = 2, .width = toy.ringWidth(), .stride = toy.ringWidth(), .dtype = .bf16 }, .positions = &.{ 0, 1 }, .layers = toy.taps, .target_end = 2 }; +} + +test "a v1 block runs attention and an MLP a layer, two residual adds each, and heads its fifteen mask rows" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + var fake = Fake{}; + var state = try session.Session.init(toy, 1, 0); + const p = op.Preparation{ .mode = .bf16_reference }; + try state.absorb(fake.ops(), &g, p, taps()); + try std.testing.expectEqual(@as(u32, 3), fake.appends); + // the context append from fused ring rows: k and v a layer, no fc (the target's taps pass ran it) + try std.testing.expectEqual(@as(u32, 2 * 3), fake.projects); + fake.projects = 0; + var tree = try state.treeBlock(a, fake.ops(), &g, p, 5, try state.firstDraw(), 16, .{ .nodes = 15 }); + defer tree.deinit(); + try std.testing.expectEqualSlices(u32, &.{ 5, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62 }, &fake.ids); + try std.testing.expectEqualSlices(u64, &.{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }, &fake.positions); + try std.testing.expectEqual(@as(u32, 3), fake.attends); + try std.testing.expectEqual(@as(u32, 6), fake.adds); + // q, k, v, o, gate, up and down a layer, and no selector projection + try std.testing.expectEqual(@as(u32, 7 * 3), fake.projects); + try std.testing.expectEqual(@as(u32, 15), fake.headed); + // with no selector, a confident lattice is a chain of each depth's best + try std.testing.expectEqual(@as(usize, 15), tree.tokens.len); + for (tree.tokens, tree.parents, 0..) |token, parent, d| { + try std.testing.expectEqual(@as(u32, @intCast(10 + d)), token); + try std.testing.expectEqual(@as(i32, @intCast(d)) - 1, parent); + } +} +test "a v1 graph holds no conv or selector tensor" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + try std.testing.expectEqual(@as(usize, 11 * 3 + 3), store.keys.len); + try std.testing.expectEqual(@as(usize, 0), g.hidden_projection.bytes.len); + try std.testing.expectEqual(@as(usize, 0), g.predecessor.bytes.len); + for (g.layers) |l| try std.testing.expectEqual(@as(usize, 0), l.attention_conv.projection.bytes.len + l.mlp_conv.base.bytes.len); + try std.testing.expect(try g.nativeBytes() > 0); +} +test "a v1 block without an add operator is refused, not run without its residuals" { + const a = std.testing.allocator; + var store = try fixtures.Store.initConfig(a, toy); + defer store.deinit(); + var g = try store.graph(a); + defer g.deinit(); + var fake = Fake{}; + var vtable = fake.ops().vtable.*; + vtable.add = null; + const ops = op.Ops{ .ptr = &fake, .vtable = &vtable }; + try std.testing.expectError(error.DraftOperatorShape, execution.forwardBlock(ops, &g, .{ .mode = .bf16_reference }, .{ .cache = 1, .begin = 0, .end = 2 }, 5, 16)); +} + +test "a v1 drafter's context keeps its whole span, not just the sliding window" { + var c = toy; + c.history = 64; + const s = try session.Session.init(c, 1, 0); + var positions: [40]u64 = undefined; + for (&positions, 0..) |*p, i| p.* = i; + const next = try s.admit(.{ .values = .{ .handle = 2, .rows = 40, .width = c.ringWidth(), .stride = c.ringWidth(), .dtype = .bf16 }, .positions = &positions, .layers = c.taps, .target_end = 40 }); + try std.testing.expectEqual(@as(u64, 0), next.begin); + const windowed = try session.Session.init(toy, 1, 0); + const cropped = try windowed.admit(.{ .values = .{ .handle = 2, .rows = 40, .width = toy.ringWidth(), .stride = toy.ringWidth(), .dtype = .bf16 }, .positions = &positions, .layers = toy.taps, .target_end = 40 }); + try std.testing.expectEqual(@as(u64, 40 - 31), cropped.begin); +} diff --git a/zig/src/families/qwen27/dflash/fixtures.zig b/zig/src/families/qwen27/dflash/fixtures.zig index 4eb14e967f4..85b187f358a 100644 --- a/zig/src/families/qwen27/dflash/fixtures.zig +++ b/zig/src/families/qwen27/dflash/fixtures.zig @@ -4,56 +4,64 @@ const ck = @import("../checkpoint.zig"); const Config = @import("config.zig").Config; const weights = @import("weights.zig"); pub const toy = Config{ .hidden = 64, .intermediate = 128, .vocab = 64, .heads = 8, .kv_heads = 4, .head_dim = 8, .mask = 63, .window = 16, .rank = 16, .topk = 2 }; +/// A tiny DFlash v1 draft: three taps of an eight-layer target, a sixteen-row block, its last layer full. +pub const toy_v1 = Config{ .variant = .v1, .hidden = 64, .intermediate = 128, .layers = 3, .vocab = 64, .heads = 8, .kv_heads = 4, .head_dim = 8, .target_layers = 8, .block = 16, .mask = 62, .window = 32, .group = 0, .conv = 0, .rank = 0, .topk = 2, .taps = .{ 1, 3, 5, 0, 0, 0, 0, 0 }, .tap_count = 3, .full = .{ false, false, true, false, false, false, false, false } }; const Dimensions = struct { values: @FieldType(ck.Tensor, "shape"), rank: usize }; pub const Store = struct { arena: std.heap.ArenaAllocator, + config: Config = toy, keys: [][]const u8 = undefined, tensors: []ck.Tensor = undefined, embed: ck.Tensor = undefined, pub fn init(gpa: std.mem.Allocator) !Store { - var s = Store{ .arena = std.heap.ArenaAllocator.init(gpa) }; + return initConfig(gpa, toy); + } + /// Zeroed tensors for every name the draft of config `c` reads. + pub fn initConfig(gpa: std.mem.Allocator, c: Config) !Store { + var s = Store{ .arena = std.heap.ArenaAllocator.init(gpa), .config = c }; errdefer s.deinit(); const a = s.arena.allocator(); - s.keys = try weights.names(a, toy); + s.keys = try weights.names(a, c); s.tensors = try a.alloc(ck.Tensor, s.keys.len); for (s.keys, s.tensors) |name, *t| { - const shape = dims(name); + const shape = dims(c, name); var count: usize = 2; for (shape.values[0..shape.rank]) |n| count = try std.math.mul(usize, count, n); const data = try a.alloc(u8, count); @memset(data, 0); t.* = .{ .dtype = .bf16, .rank = @intCast(shape.rank), .shape = shape.values, .bytes = data }; } - const data = try a.alloc(u8, toy.vocab * toy.hidden * 2); + const data = try a.alloc(u8, c.vocab * c.hidden * 2); @memset(data, 0); - s.embed = .{ .dtype = .bf16, .rank = 2, .shape = .{ toy.vocab, toy.hidden, 1, 1, 1 }, .bytes = data }; + s.embed = .{ .dtype = .bf16, .rank = 2, .shape = .{ c.vocab, c.hidden, 1, 1, 1 }, .bytes = data }; return s; } pub fn deinit(s: *Store) void { s.arena.deinit(); } pub fn graph(s: *Store, gpa: std.mem.Allocator) !weights.Graph { - return weights.load(gpa, .{ .source = .{ .ptr = s, .getFn = get }, .names = s.keys }, toy, .{ .dense = s.embed }); + return weights.load(gpa, .{ .source = .{ .ptr = s, .getFn = get }, .names = s.keys }, s.config, .{ .dense = s.embed }); } fn get(ptr: *anyopaque, name: []const u8) !ck.Tensor { const s: *Store = @ptrCast(@alignCast(ptr)); for (s.keys, s.tensors) |key, t| if (std.mem.eql(u8, key, name)) return t; return error.MissingTensor; } - fn dims(name: []const u8) Dimensions { - if (std.mem.eql(u8, name, "fc.weight")) return .{ .values = .{ toy.hidden, toy.tapWidth(), 1, 1, 1 }, .rank = 2 }; - if (std.mem.eql(u8, name, "candidate_selector.hidden_projection.weight")) return .{ .values = .{ toy.rank, toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.startsWith(u8, name, "candidate_selector.")) return .{ .values = .{ toy.vocab, toy.rank, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "base_kernel")) return .{ .values = .{ 2, 2, toy.hidden, 1, 1 }, .rank = 3 }; - if (std.mem.endsWith(u8, name, "kernel_projection.weight")) return .{ .values = .{ toy.dynamicWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "q_proj.weight")) return .{ .values = .{ toy.qWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "k_proj.weight") or std.mem.endsWith(u8, name, "v_proj.weight")) return .{ .values = .{ toy.kvWidth(), toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "o_proj.weight")) return .{ .values = .{ toy.hidden, toy.qWidth(), 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "gate_proj.weight") or std.mem.endsWith(u8, name, "up_proj.weight")) return .{ .values = .{ toy.intermediate, toy.hidden, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "down_proj.weight")) return .{ .values = .{ toy.hidden, toy.intermediate, 1, 1, 1 }, .rank = 2 }; - if (std.mem.endsWith(u8, name, "q_norm.weight") or std.mem.endsWith(u8, name, "k_norm.weight")) return .{ .values = .{ toy.head_dim, 1, 1, 1, 1 }, .rank = 1 }; - return .{ .values = .{ toy.hidden, 1, 1, 1, 1 }, .rank = 1 }; + fn dims(toy_config: Config, name: []const u8) Dimensions { + const t = toy_config; + if (std.mem.eql(u8, name, "fc.weight")) return .{ .values = .{ t.hidden, t.tapWidth(), 1, 1, 1 }, .rank = 2 }; + if (std.mem.eql(u8, name, "candidate_selector.hidden_projection.weight")) return .{ .values = .{ t.rank, t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.startsWith(u8, name, "candidate_selector.")) return .{ .values = .{ t.vocab, t.rank, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "base_kernel")) return .{ .values = .{ 2, 2, t.hidden, 1, 1 }, .rank = 3 }; + if (std.mem.endsWith(u8, name, "kernel_projection.weight")) return .{ .values = .{ t.dynamicWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "q_proj.weight")) return .{ .values = .{ t.qWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "k_proj.weight") or std.mem.endsWith(u8, name, "v_proj.weight")) return .{ .values = .{ t.kvWidth(), t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "o_proj.weight")) return .{ .values = .{ t.hidden, t.qWidth(), 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "gate_proj.weight") or std.mem.endsWith(u8, name, "up_proj.weight")) return .{ .values = .{ t.intermediate, t.hidden, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "down_proj.weight")) return .{ .values = .{ t.hidden, t.intermediate, 1, 1, 1 }, .rank = 2 }; + if (std.mem.endsWith(u8, name, "q_norm.weight") or std.mem.endsWith(u8, name, "k_norm.weight")) return .{ .values = .{ t.head_dim, 1, 1, 1, 1 }, .rank = 1 }; + return .{ .values = .{ t.hidden, 1, 1, 1, 1 }, .rank = 1 }; } }; diff --git a/zig/src/families/qwen27/dflash/generation.zig b/zig/src/families/qwen27/dflash/generation.zig index ddc0596d550..fac34853731 100644 --- a/zig/src/families/qwen27/dflash/generation.zig +++ b/zig/src/families/qwen27/dflash/generation.zig @@ -23,6 +23,7 @@ pub const Generation = struct { pending: ?u32 = null, // runRound's next token as the last accept picked it; anything else that moves the target clears it pub fn init(a: std.mem.Allocator, runner: *Runner, draft: *Draft) !Generation { if (&runner.model.checkpoint != draft.backend.target.checkpoint or runner.model.config.hidden != draft.graph.config.hidden or runner.model.config.layers != draft.graph.config.target_layers) return error.TargetBinding; + try runner.taps.setFuser(runner.model.device, null); // a fused ring keeps its count: no drafter's fuser before use runner.capture_taps = true; try runner.taps.use(runner.model.device, draft.graph.config.tapIds()); const options = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; @@ -33,6 +34,9 @@ pub const Generation = struct { const matcher = try @import("round_gpu.zig").Matcher.init(runner.model.device); errdefer matcher.deinit(); const commit = try @import("core").tree_commit_gpu.Ops.init(runner.model.device); + errdefer commit.deinit(); + // a v1 ring keeps fused rows: the target's taps pass runs the drafter's fc and hidden_norm as they complete + if (draft.graph.config.variant == .v1) try runner.taps.setFuser(runner.model.device, try draft.fuser(runner.taps.capacity)); return .{ .allocator = a, .runner = runner, .draft = draft, .kept = kept, .taps = taps, .matcher = matcher, .commit = commit }; } pub fn deinit(g: Generation) void { @@ -163,7 +167,8 @@ pub const Generation = struct { const width: u32 = @intCast(g.runner.model.config.vocab); const shape = try g.matcher.encode(e, .{ .buf = logits.buffer, .off = logits.offset }, ids, parents, width, budget, eos); const result = @import("core").tree_commit_gpu.Ref{ .buf = g.matcher.buffers[4] }; - try g.commit.taps(e, result, .{ .buf = g.runner.taps.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = g.runner.taps.width, .capacity = g.runner.taps.capacity, .planes = @intCast(g.runner.taps.count) }); + const src = g.runner.taps.source(); + try g.commit.taps(e, result, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = src.width, .capacity = g.runner.taps.capacity, .planes = src.planes }); try g.commit.head(e, result, .{ .buf = logits.buffer, .off = logits.offset }, .{ .rows = shape.rows, .width = width, .stride = width }); return shape; } diff --git a/zig/src/families/qwen27/dflash/operators.zig b/zig/src/families/qwen27/dflash/operators.zig index 45ad1df88a0..de90332fddb 100644 --- a/zig/src/families/qwen27/dflash/operators.zig +++ b/zig/src/families/qwen27/dflash/operators.zig @@ -81,6 +81,8 @@ pub const Ops = struct { context_abort: *const fn (*anyopaque, u64) void, // a batched pass's stream k. stream_append: *const fn (*anyopaque, u64, u32, u32, View, View, []const u64) anyerror!void, + // x + y, row for row: a DFlash v1 layer's residuals (DFlash2 adds them inside its conv). + add: ?*const fn (*anyopaque, u64, View, View) anyerror!View = null, }; }; diff --git a/zig/src/families/qwen27/dflash/root.zig b/zig/src/families/qwen27/dflash/root.zig index 916cb4ccf51..777f7d66711 100644 --- a/zig/src/families/qwen27/dflash/root.zig +++ b/zig/src/families/qwen27/dflash/root.zig @@ -22,4 +22,5 @@ test { _ = @import("execution_test.zig"); _ = @import("absorb_batch.zig"); _ = @import("absorb_batch_test.zig"); + _ = @import("execution_v1_test.zig"); } diff --git a/zig/src/families/qwen27/dflash/runtime_backend.zig b/zig/src/families/qwen27/dflash/runtime_backend.zig index 8fe8da8697e..889e5288096 100644 --- a/zig/src/families/qwen27/dflash/runtime_backend.zig +++ b/zig/src/families/qwen27/dflash/runtime_backend.zig @@ -59,6 +59,7 @@ pub const Backend = struct { config: cfg.Config, primitives: core.draft_ops.Ops, attention: core.shared_attention.Attention, + attention_full: ?core.shared_attention.Attention = null, // a v1 full layer's, over the whole span topk: core.bf16_topk_gpu.Ops, head: @import("runtime_head.zig").Head, frame: Frame, @@ -82,6 +83,8 @@ pub const Backend = struct { errdefer primitives.deinit(); const attention = try core.shared_attention.Attention.init(a, target.device, .{ .query_heads = c.heads, .kv_heads = c.kv_heads, .head_dim = c.head_dim, .capacity = c.window + 16, .output = .bf16 }); errdefer attention.deinit(); + const attention_full: ?core.shared_attention.Attention = if (c.span() > c.window) try core.shared_attention.Attention.init(a, target.device, .{ .query_heads = c.heads, .kv_heads = c.kv_heads, .head_dim = c.head_dim, .capacity = c.span() + 16, .output = .bf16 }) else null; + errdefer if (attention_full) |x| x.deinit(); const topk = try core.bf16_topk_gpu.Ops.init(target.device); errdefer topk.deinit(); var head = try @import("runtime_head.zig").Head.init(a, target.device, target.weights.head); @@ -89,7 +92,7 @@ pub const Backend = struct { // the trimmed head's shape is the drafter's own: compile its pipeline here, not in the first draft round try target.kernels.prepareDecode(head.linear); const caches = try newCaches(a, target.device, c, c.layers); - return .{ .allocator = a, .target = target, .checkpoint = checkpoint, .config = c, .primitives = primitives, .attention = attention, .topk = topk, .head = head, .frame = .{ .allocator = a, .device = target.device, .queue = target.queue }, .caches = caches }; + return .{ .allocator = a, .target = target, .checkpoint = checkpoint, .config = c, .primitives = primitives, .attention = attention, .attention_full = attention_full, .topk = topk, .head = head, .frame = .{ .allocator = a, .device = target.device, .queue = target.queue }, .caches = caches }; } pub fn setResident(b: *Backend, hook: ?mtl.ResidencySet.Follow) void { @import("../residency.zig").setDraft(b, hook); @@ -108,6 +111,7 @@ pub const Backend = struct { freeCaches(b.allocator, b.caches); b.head.deinit(); b.topk.deinit(); + if (b.attention_full) |x| x.deinit(); b.attention.deinit(); b.primitives.deinit(); } @@ -150,6 +154,26 @@ pub const Backend = struct { pub fn linear(name: []const u8, rank: usize) bool { return rank == 2 and std.mem.endsWith(u8, name, ".weight"); } + /// `rows` rows of x (contiguous, `w`'s width) through linear `w` into y, outside any drafter frame. + pub fn encodeLinear(b: *Backend, e: mtl.ComputeEncoder, w: ck.Tensor, mode: op.Mode, x: Ref, y: Ref, rows: u32) !void { + const n: u32 = @intCast(w.shape[0]); + const k: u32 = @intCast(w.shape[1]); + if (mode == .bf16_reference) { + try b.primitives.linear(e, x, try b.weight(w), y, .{ .rows = rows, .n = n, .k = k, .x_stride = k, .w_stride = k, .y_stride = n }); + } else if (b.tiled.get(@intFromPtr(w.bytes.ptr))) |t| { + simd.encode(e, try simd.call(&b.simd.?, t.n, t.k, rows, false, false, 0), t.matrix(), x.buf, x.off, y.buf, y.off); + } else { + const adapter = b.prepared.get(@intFromPtr(w.bytes.ptr)) orelse return error.DraftPreparationUnqualified; + var first: u32 = 0; + while (first < rows) : (first += 16) { + try adapter.encode(e, .{ .buf = x.buf, .off = x.off + @as(usize, first) * k * 2 }, .{ .buf = y.buf, .off = y.off + @as(usize, first) * n * 2 }, @min(rows - first, 16)); + } + } + } + /// The attention whose capacity is layer `layer`'s window. + pub fn attentionFor(b: *const Backend, layer: u32) *const core.shared_attention.Attention { + return if (b.config.layerWindow(layer) > b.config.window) &b.attention_full.? else &b.attention; + } pub fn ops(b: *Backend) op.Ops { return .{ .ptr = b, .vtable = &callbacks.vtable }; } diff --git a/zig/src/families/qwen27/dflash/runtime_callbacks.zig b/zig/src/families/qwen27/dflash/runtime_callbacks.zig index ccf6de7fda8..00d6938484b 100644 --- a/zig/src/families/qwen27/dflash/runtime_callbacks.zig +++ b/zig/src/families/qwen27/dflash/runtime_callbacks.zig @@ -89,6 +89,18 @@ fn swiglu(ptr: *anyopaque, epoch: u64, g: op.View, u: op.View) !op.View { e.barrier(); return y; } +fn add(ptr: *anyopaque, epoch: u64, x: op.View, y: op.View) !op.View { + const b = backend(ptr); + const e = try b.encoder(epoch); + if (x.rows != y.rows or x.width != y.width or x.dtype != .bf16 or y.dtype != .bf16 or x.stride != x.width or y.stride != y.width) return error.DraftOperatorShape; + const z = try b.frame.alloc(x.rows, x.width, .bf16); + const xr = try b.frame.ref(x); + const yr = try b.frame.ref(y); + const zr = try b.frame.ref(z); + b.target.glue.residual(e, .{ .buffer = xr.buf, .offset = xr.off }, .{ .buffer = yr.buf, .offset = yr.off }, .{ .buffer = zr.buf, .offset = zr.off }, x.width, x.rows); + e.barrier(); + return z; +} fn maskRows(ptr: *anyopaque, epoch: u64, x: op.View, first: u32, rows: u32) !op.View { const b = backend(ptr); _ = try b.encoder(epoch); @@ -153,4 +165,4 @@ fn lattices(ptr: *anyopaque, epoch: u64, h: op.Head, projected: op.View, c: Conf made += 1; } } -pub const vtable = op.Ops.VTable{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = context.attention, .swiglu = swiglu, .mask_rows = maskRows, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = context.begin, .context_append = context.append, .context_commit = context.commit, .context_stage = context.stage, .context_abort = context.abort, .stream_append = context.streamAppend }; +pub const vtable = op.Ops.VTable{ .begin = begin, .release = release, .project = project, .norm = norm, .embed = embed, .conv = conv, .rope = rope, .attention = context.attention, .swiglu = swiglu, .mask_rows = maskRows, .head = head, .lattice = lattice, .lattices = lattices, .context_begin = context.begin, .context_append = context.append, .context_commit = context.commit, .context_stage = context.stage, .context_abort = context.abort, .stream_append = context.streamAppend, .add = add }; diff --git a/zig/src/families/qwen27/dflash/runtime_context.zig b/zig/src/families/qwen27/dflash/runtime_context.zig index c76c34028c1..f50cd9f4537 100644 --- a/zig/src/families/qwen27/dflash/runtime_context.zig +++ b/zig/src/families/qwen27/dflash/runtime_context.zig @@ -23,7 +23,7 @@ pub fn append(ptr: *anyopaque, transaction: u64, epoch: u64, layer: u32, keys: o try values.check(keys.rows, keys.width, .bf16); if (b.appended != 0 and b.appended_rows != positions.len) return error.BadCommittedTaps; for (positions, 0..) |position, i| if (position != b.context.end + i) return error.BadCommittedTaps; - try appendRows(b, e, b.caches[layer], keys, values, positions); + try appendRows(b, e, b.caches[layer], layer, keys, values, positions); b.appended |= @as(u32, 1) << @intCast(layer); b.appended_rows = @intCast(positions.len); } @@ -33,24 +33,25 @@ pub fn streamAppend(ptr: *anyopaque, epoch: u64, stream: u32, layer: u32, keys: if (b.transaction != null or stream >= b.batch.len or layer >= b.config.layers or positions.len == 0) return error.BadDraftContext; try keys.check(@intCast(positions.len), b.config.kvWidth(), .bf16); try values.check(keys.rows, keys.width, .bf16); - try appendRows(b, e, b.batch[stream][layer], keys, values, positions); + try appendRows(b, e, b.batch[stream][layer], layer, keys, values, positions); } /// Rows' keys and values into `cache` at their positions' ring slots, 16 a dispatch. -fn appendRows(b: *Backend, e: @import("metal").ComputeEncoder, cache: @import("runtime_backend.zig").Cache, keys: op.View, values: op.View, positions: []const u64) !void { +fn appendRows(b: *Backend, e: @import("metal").ComputeEncoder, cache: @import("runtime_backend.zig").Cache, layer: u32, keys: op.View, values: op.View, positions: []const u64) !void { + const window = b.config.layerWindow(layer); const k = try b.frame.ref(keys); const v = try b.frame.ref(values); var first: usize = 0; while (first < positions.len) : (first += 16) { const count = @min(positions.len - first, 16); var slots: [16]u32 = undefined; - for (slots[0..count], 0..) |*slot, i| slot.* = @intCast(positions[first + i] % b.config.window); + for (slots[0..count], 0..) |*slot, i| slot.* = @intCast(positions[first + i] % window); const off = first * b.config.kvWidth() * 2; - try b.attention.appendKv(e, slots[0..count], .{ .buf = k.buf, .off = k.off + off }, .{ .buf = v.buf, .off = v.off + off }, .{ .buf = cache.keys }, .{ .buf = cache.values }); + try b.attentionFor(layer).appendKv(e, slots[0..count], .{ .buf = k.buf, .off = k.off + off }, .{ .buf = v.buf, .off = v.off + off }, .{ .buf = cache.keys }, .{ .buf = cache.values }); e.barrier(); } } fn ready(b: *Backend, transaction: u64, epoch: u64, next: op.Context) !void { - if (b.transaction != transaction or transaction != epoch or b.appended != (@as(u32, 1) << @intCast(b.config.layers)) - 1 or next.cache != b.context.cache or next.end != b.context.end + b.appended_rows or next.begin != @max(b.context.begin, next.end -| (@as(u64, b.config.window) - 1))) return error.BadDraftContext; + if (b.transaction != transaction or transaction != epoch or b.appended != (@as(u32, 1) << @intCast(b.config.layers)) - 1 or next.cache != b.context.cache or next.end != b.context.end + b.appended_rows or next.begin != @max(b.context.begin, next.end -| (@as(u64, b.config.span()) - 1))) return error.BadDraftContext; } pub fn commit(ptr: *anyopaque, transaction: u64, epoch: u64, next: op.Context) !void { const b = cast(ptr); @@ -81,11 +82,11 @@ pub fn abort(ptr: *anyopaque, transaction: u64) void { b.staged = null; } } -fn gather(b: *Backend, e: @import("metal").ComputeEncoder, context: op.Context, cache: @import("metal").Buffer, out: Ref) !void { +fn gather(b: *Backend, e: @import("metal").ComputeEncoder, context: op.Context, cache: @import("metal").Buffer, window: u32, out: Ref) !void { const rows: u32 = @intCast(context.end - context.begin); if (rows == 0) return; - const at: u32 = @intCast(context.begin % b.config.window); - const first = @min(rows, b.config.window - at); + const at: u32 = @intCast(context.begin % window); + const first = @min(rows, window - at); const width = b.config.kvWidth(); try b.copy(e, .{ .buf = cache, .off = @as(usize, at) * width * 2 }, out, first, width); if (first < rows) try b.copy(e, .{ .buf = cache }, .{ .buf = out.buf, .off = out.off + @as(usize, first) * width * 2 }, rows - first, width); @@ -107,12 +108,14 @@ pub fn attention(ptr: *anyopaque, epoch: u64, p: op.Attention) !op.View { } /// Query rows [first, first + rows) against `context`'s cached keys and their own, into the same rows of `result`. -fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, context: op.Context, caches: []const @import("runtime_backend.zig").Cache, first: u32, rows: u32, result: op.View) !void { +fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, kept: op.Context, caches: []const @import("runtime_backend.zig").Cache, first: u32, rows: u32, result: op.View) !void { + const window = b.config.layerWindow(p.layer); + const context = layerContext(kept, window); const context_rows: u32 = @intCast(context.end - context.begin); const keys = context_rows + rows; // An unwrapped context is contiguous in the cache: the query rows go behind it and attention reads in place. - const at: u32 = @intCast(context.begin % b.config.window); - const in_place = at + context_rows <= b.config.window and at + keys <= b.config.window + 16; + const at: u32 = @intCast(context.begin % window); + const in_place = at + context_rows <= window and at + keys <= window + 16; var k: Ref = undefined; var v: Ref = undefined; if (in_place) { @@ -123,8 +126,8 @@ fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, const merged_v = try b.frame.alloc(keys, b.config.kvWidth(), .bf16); k = try b.frame.ref(merged_k); v = try b.frame.ref(merged_v); - try gather(b, e, context, caches[p.layer].keys, k); - try gather(b, e, context, caches[p.layer].values, v); + try gather(b, e, context, caches[p.layer].keys, window, k); + try gather(b, e, context, caches[p.layer].values, window, v); } const off = @as(usize, context_rows) * b.config.kvWidth() * 2; const own_k = try b.frame.ref(p.keys); @@ -133,16 +136,27 @@ fn attendRows(b: *Backend, e: @import("metal").ComputeEncoder, p: op.Attention, try b.copy(e, .{ .buf = own_v.buf, .off = own_v.off + @as(usize, first) * p.values.stride * 2 }, .{ .buf = v.buf, .off = v.off + off }, rows, p.values.width); const mask = try b.frame.alloc(rows, keys, .u8); const mask_ref = try b.frame.ref(mask); - try fillMask(mask_ref.buf.contents()[mask_ref.off..][0 .. @as(usize, rows) * keys], context_rows, rows, b.config.window, b.config.block); + try fillMask(mask_ref.buf.contents()[mask_ref.off..][0 .. @as(usize, rows) * keys], context_rows, rows, window, b.config.block); const q = try b.frame.ref(p.query); const y = try b.frame.ref(result); const scale = 1.0 / @sqrt(@as(f32, @floatFromInt(b.config.head_dim))); const R = @import("core").shared_attention.Ref; const views = [_]R{ .{ .buf = q.buf, .off = q.off + @as(usize, first) * p.query.stride * 2 }, .{ .buf = k.buf, .off = k.off }, .{ .buf = v.buf, .off = v.off }, .{ .buf = mask_ref.buf, .off = mask_ref.off }, .{ .buf = y.buf, .off = y.off + @as(usize, first) * result.stride * 2 } }; // Long contexts share each 256-key chunk across the query heads of one KV head. - if (keys > 1024) try b.attention.encodeSplit(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]) else try b.attention.encode(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]); + const attend = b.attentionFor(p.layer); + if (keys > 1024) try attend.encodeSplit(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]) else try attend.encode(e, rows, keys, keys, scale, views[0], views[1], views[2], views[3], views[4]); } +/// The rows a layer of window `window` attends: the kept context's last `window` - 1 (all of it for a full layer). +pub fn layerContext(kept: op.Context, window: u32) op.Context { + return .{ .cache = kept.cache, .begin = @max(kept.begin, kept.end -| (@as(u64, window) - 1)), .end = kept.end }; +} +test "a sliding layer attends its own window of a longer kept context, a full layer all of it" { + const kept = op.Context{ .cache = 1, .begin = 0, .end = 10000 }; + try std.testing.expectEqual(@as(u64, 10000 - 4095), layerContext(kept, 4096).begin); + try std.testing.expectEqual(@as(u64, 0), layerContext(kept, 32768).begin); + try std.testing.expectEqual(@as(u64, 7), layerContext(.{ .cache = 1, .begin = 7, .end = 100 }, 4096).begin); +} /// Slots before `trained` cannot see later slots, retaining their trained-block mask. pub fn fillMask(out: []u8, context_rows: u32, queries: u32, window: u32, trained: u32) !void { if (queries == 0 or window == 0 or context_rows >= window or trained == 0) return error.BadDraftContext; diff --git a/zig/src/families/qwen27/dflash/runtime_lattice.zig b/zig/src/families/qwen27/dflash/runtime_lattice.zig index e55d6f82092..46e8143743b 100644 --- a/zig/src/families/qwen27/dflash/runtime_lattice.zig +++ b/zig/src/families/qwen27/dflash/runtime_lattice.zig @@ -10,9 +10,10 @@ fn value(r: @import("runtime_frame.zig").Ref, at: usize) f32 { pub fn read(a: std.mem.Allocator, frame: *const Frame, topk: op.View, hidden: op.View, c: Config, head: op.Head) !op.Lattice { if (!frame.completed) return error.DraftLatticeShape; try topk.check(head.logits.rows, @sizeOf(@import("core").bf16_topk.Row), .u8); - try hidden.check(head.logits.rows, c.rank, .bf16); + // rank 0 (a v1 draft): no selector projection to read, whatever `hidden` holds + if (c.rank > 0) try hidden.check(head.logits.rows, c.rank, .bf16); const picked = try frame.ref(topk); - const projected = try frame.ref(hidden); + const projected = if (c.rank > 0) try frame.ref(hidden) else picked; const mapping = if (head.token_ids) |ids| try frame.ref(ids) else null; const count = @as(usize, head.logits.rows) * c.topk; var out = op.Lattice{ .gpa = a, .depth = head.logits.rows, .topk = c.topk, .rank = c.rank, .candidates = try a.alloc(u32, count), .unary = undefined, .projected = undefined }; diff --git a/zig/src/families/qwen27/dflash/runtime_model.zig b/zig/src/families/qwen27/dflash/runtime_model.zig index 7e17c52792a..85719aa673a 100644 --- a/zig/src/families/qwen27/dflash/runtime_model.zig +++ b/zig/src/families/qwen27/dflash/runtime_model.zig @@ -9,6 +9,8 @@ const Backend = @import("runtime_backend.zig").Backend; const Target = @import("../model.zig").Model; const Session = @import("session.zig").Session; const op = @import("operators.zig"); +const tap_ring = @import("../tap_ring.zig"); +const kv_grow = @import("../kv_grow.zig"); const execution = @import("execution.zig"); const absorb_batch = @import("absorb_batch.zig"); const selector = @import("selector.zig"); @@ -26,12 +28,18 @@ pub const Model = struct { tree_block: u32 = 16, pending: mtl.Buffer, committed_end: u64 = 0, + fuse_out: ?mtl.Buffer = null, // fc's rows before hidden_norm, for the target's taps pass + fuse_rows: u32 = 0, absorb_batch: bool = false, // TF_Q27_DFLASH_ABSORB_BATCH: a shared round's streams absorb in one pass absorb_batches: u64 = 0, // stacked absorb passes absorb_batch_rows: u64 = 0, // rows those passes took absorb_passes_saved: u64 = 0, // per-stream weight passes they replaced pub fn load(a: std.mem.Allocator, io: std.Io, target: *Target, dir: []const u8, mode: op.Mode) !*Model { - return optIn(try loadBound(a, io, backend_mod.Target.qwen(target), dir, mode)); + return loadSpan(a, io, target, dir, mode, 0); + } + /// `history`: positions a v1 drafter keeps for its full layers (the served span); 0 keeps the window. + pub fn loadSpan(a: std.mem.Allocator, io: std.Io, target: *Target, dir: []const u8, mode: op.Mode, history: u32) !*Model { + return optIn(try loadBoundSpan(a, io, backend_mod.Target.qwen(target), dir, mode, history)); } /// The 27B's own switch: a family that shares this drafter through a bound target keeps the per-stream absorb. fn optIn(m: *Model) !*Model { @@ -40,12 +48,16 @@ pub const Model = struct { return m; } pub fn loadBound(a: std.mem.Allocator, io: std.Io, target: backend_mod.Target, dir: []const u8, mode: op.Mode) !*Model { + return loadBoundSpan(a, io, target, dir, mode, 0); + } + fn loadBoundSpan(a: std.mem.Allocator, io: std.Io, target: backend_mod.Target, dir: []const u8, mode: op.Mode, history: u32) !*Model { if (mode == .python_q4g64) return error.DraftPreparationUnqualified; const path = try std.fs.path.join(a, &.{ dir, "config.json" }); defer a.free(path); const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20)); defer a.free(text); - const c = try cfg.parse(a, text); + var c = try cfg.parse(a, text); + if (c.variant == .v1) c.history = history; try c.bind(target.config.hidden, target.config.vocab, target.config.layers); const shards = try core.checkpoint_host.shardFiles(a, io, dir); defer core.checkpoint_host.freeShardFiles(a, shards); @@ -63,6 +75,8 @@ pub const Model = struct { model.allocator = a; model.tree_block = 16; model.committed_end = 0; + model.fuse_out = null; + model.fuse_rows = 0; model.absorb_batch = false; model.absorb_batches = 0; model.absorb_batch_rows = 0; @@ -78,7 +92,7 @@ pub const Model = struct { errdefer model.graph.deinit(); if (mode == .prepared_q4_reference) try model.backend.prepare(); model.checkpoint.closeFiles(); - model.pending = try target.device.buffer(@as(usize, c.window) * c.tapWidth() * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + model.pending = try target.device.buffer(@as(usize, c.span()) * c.ringWidth() * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); errdefer model.pending.deinit(); model.session = try Session.init(c, 1, 0); model.preparation = .{ .mode = mode, .quantization_verified = mode == .prepared_q4_reference, .source_sha256 = if (mode == .prepared_q4_reference) core.affine4.signature() else @splat(0) }; @@ -86,6 +100,7 @@ pub const Model = struct { } pub fn deinit(m: *Model) void { if (m.absorb_batches > 0) std.log.info("qwen27: DFlash2 absorb batches {d}, rows {d}, weight passes saved {d}", .{ m.absorb_batches, m.absorb_batch_rows, m.absorb_passes_saved }); + if (m.fuse_out) |b| b.deinit(); m.graph.deinit(); m.backend.deinit(); m.pending.deinit(); @@ -107,30 +122,49 @@ pub const Model = struct { m.session = try Session.init(m.graph.config, 1, 0); m.committed_end = 0; } + /// The target's taps pass fuses rows for this v1 drafter: fc then hidden_norm on up to `rows` rows a pass. + pub fn fuser(m: *Model, rows: u32) !@import("../taps.zig").Fuser { + if (m.graph.config.variant != .v1 or rows == 0) return error.BadDraftOptions; + if (m.fuse_out) |b| b.deinit(); + m.fuse_out = null; + m.fuse_out = try m.backend.target.device.buffer(@as(usize, rows) * m.graph.config.hidden * 2, opts); + m.fuse_rows = rows; + return .{ .ptr = m, .width = m.graph.config.hidden, .encode = fuseEncode }; + } + fn fuseEncode(ptr: *anyopaque, e: mtl.ComputeEncoder, x: @import("../projection.zig").Ref, y: @import("../projection.zig").Ref, rows: u32) !void { + const m: *Model = @ptrCast(@alignCast(ptr)); + if (rows == 0 or rows > m.fuse_rows or m.backend.failed) return error.BadCommittedTaps; + const c = m.graph.config; + const out = m.fuse_out.?; + try m.backend.encodeLinear(e, m.graph.fusion, m.preparation.mode, .{ .buf = x.buffer, .off = x.offset }, .{ .buf = out }, rows); + e.barrier(); + try m.backend.primitives.norm(e, .{ .buf = out }, try m.backend.weight(m.graph.hidden_norm), .{ .buf = y.buffer, .off = y.offset }, .{ .rows = rows, .heads = 1, .dim = c.hidden, .x_stride = c.hidden, .y_stride = c.hidden, .eps = c.eps }); + e.barrier(); + } pub fn absorb(m: *Model, taps: @import("runtime_backend.zig").Ref, rows: u32) !void { if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or rows == 0 or rows > 128) return error.BadCommittedTaps; try m.ring().absorb(taps.buf, taps.off, rows); } /// The committed taps the drafter reads, as a ring a lane's state copies. pub fn ring(m: *Model) @import("../tap_ring.zig").Ring { - return .{ .buf = m.pending, .end = &m.committed_end, .window = m.graph.config.window, .stride = @as(usize, m.graph.config.tapWidth()) * 2 }; + return .{ .buf = m.pending, .end = &m.committed_end, .window = m.graph.config.span(), .stride = @as(usize, m.graph.config.ringWidth()) * 2 }; } pub fn flush(m: *Model) !void { if (m.backend.failed or m.backend.frame.active or m.backend.transaction != null or m.committed_end == 0 or m.session.context.end > m.committed_end) return error.BadDraftContext; - const begin = m.committed_end -| (@as(u64, m.graph.config.window) - 1); + const begin = m.committed_end -| (@as(u64, m.graph.config.span()) - 1); if (m.session.context.end < begin) { m.session.context = .{ .cache = 1, .begin = begin, .end = begin }; m.session.ready = false; m.backend.context = m.session.context; } - const stride = @as(usize, m.graph.config.tapWidth()) * 2; + const stride = @as(usize, m.graph.config.ringWidth()) * 2; while (m.session.context.end < m.committed_end) { const first = m.session.context.end; - const slot: u32 = @intCast(first % m.graph.config.window); - const rows: u32 = @intCast(@min(@min(m.committed_end - first, 128), m.graph.config.window - slot)); + const slot: u32 = @intCast(first % m.graph.config.span()); + const rows: u32 = @intCast(@min(@min(m.committed_end - first, 128), m.graph.config.span() - slot)); var positions: [128]u64 = undefined; for (positions[0..rows], 0..) |*position, i| position.* = first + i; - const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.tapWidth()); + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.ringWidth()); try m.session.absorb(m.backend.ops(), &m.graph, m.preparation, .{ .values = view, .positions = positions[0..rows], .layers = m.graph.config.taps, .target_end = first + rows }); } } @@ -206,10 +240,10 @@ pub const Model = struct { defer ops.vtable.release(ops.ptr, frame); var absorbs: [8]?execution.Absorb = @splat(null); var positions: [8][128]u64 = undefined; - const stride = @as(usize, c.tapWidth()) * 2; + const stride = @as(usize, c.ringWidth()) * 2; for (news[0..n], absorbs[0..n], 0..) |f, *a, k| if (f) |x| { for (positions[k][0..x.rows], 0..) |*p, i| p.* = x.first + i; - a.* = .{ .taps = try m.backend.frame.add(.{ .buf = x.ring, .off = @as(usize, x.slot) * stride }, x.rows, c.tapWidth(), c.tapWidth(), .bf16), .positions = positions[k][0..x.rows] }; + a.* = .{ .taps = try m.backend.frame.add(.{ .buf = x.ring, .off = @as(usize, x.slot) * stride }, x.rows, c.ringWidth(), c.ringWidth(), .bf16), .positions = positions[k][0..x.rows] }; }; var spans: [8]absorb_batch.Span = undefined; var stacked_positions: [absorb_batch.max_rows]u64 = undefined; @@ -250,7 +284,7 @@ pub const Model = struct { const plan = absorb_batch.plan(counts[0..news.len], spans) orelse return null; const last = plan[plan.len - 1]; const rows = last.first + last.rows; - const width = m.graph.config.tapWidth(); + const width = m.graph.config.ringWidth(); const stride = @as(usize, width) * 2; const taps = try m.backend.frame.alloc(rows, width, .bf16); const out = try m.backend.frame.ref(taps); @@ -265,7 +299,7 @@ pub const Model = struct { /// A short run of committed taps the session lacks, for a batched frame to absorb (null: none, or flush first). const Fresh = struct { ring: mtl.Buffer, slot: u32, rows: u32, first: u64, next: op.Context }; fn fresh(m: *const Model) ?Fresh { - const window = m.graph.config.window; + const window = m.graph.config.span(); const span = @import("catchup.zig").fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, window) orelse return null; return .{ .ring = m.pending, .slot = span.slot, .rows = span.rows, .first = span.first, .next = .{ .cache = m.session.context.cache, .begin = span.begin, .end = m.committed_end } }; } @@ -281,14 +315,14 @@ pub const Model = struct { if (m.committed_end == 0) return error.DraftContextNotReady; const block = @min(m.tree_block, nodes + 1); if (block < 2) return .{ .gpa = m.allocator, .tokens = &.{}, .parents = &.{}, .scores = &.{} }; - const window = m.graph.config.window; + const window = m.graph.config.span(); if (@import("catchup.zig").fresh(m.session.ready, m.session.context.begin, m.session.context.end, m.committed_end, window)) |span| { const rows = span.rows; const slot = span.slot; var positions: [128]u64 = undefined; for (positions[0..rows], 0..) |*position, i| position.* = m.session.context.end + i; - const stride = @as(usize, m.graph.config.tapWidth()) * 2; - const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.tapWidth()); + const stride = @as(usize, m.graph.config.ringWidth()) * 2; + const view = try m.backend.frame.borrow(.{ .buf = m.pending, .off = @as(usize, slot) * stride }, rows, m.graph.config.ringWidth()); return m.session.absorbTreeBlock(m.allocator, m.backend.ops(), &m.graph, m.preparation, .{ .values = view, .positions = positions[0..rows], .layers = m.graph.config.taps, .target_end = m.session.context.end + rows }, pending, block, options); } try m.flush(); @@ -304,21 +338,69 @@ pub const Context = struct { caches: []Cache, session: Session, context: op.Context = .{ .cache = 1, .begin = 0, .end = 0 }, + device: mtl.Device, + span: u32, // the ring's window + stride: usize, // a ring row's bytes + held: u32, // the ring's rows: the span unless it grows as used + step: ?u32 = null, // a ring that grows as used (TF_Q27_KV_GROW): its first rows and step + settle: ?Settle = null, // the slot's pending reads land before its ring's buffer changes + + /// The runner's wait for a blit still reading the slot (Runner.settleSlot). + pub const Settle = struct { ctx: *anyopaque, slot: u32, run: *const fn (ctx: *anyopaque, slot: u32) void }; - /// `drafting`: the stream drafts its own trees, so it gets K/V caches; else only its ring. + /// `drafting`: the stream drafts its own trees, so it gets K/V caches; its ring grows by `step` (null: the span). pub fn init(a: std.mem.Allocator, m: *const Model, drafting: bool) !*Context { + return initGrow(a, m, drafting, null); + } + + pub fn initGrow(a: std.mem.Allocator, m: *const Model, drafting: bool, step: ?u32) !*Context { const c = m.graph.config; const device = m.backend.target.device; const x = try a.create(Context); errdefer a.destroy(x); - const pending = try device.buffer(@as(usize, c.window) * c.tapWidth() * 2, opts); + const grows = step; // drafter frames wait for their ring reads before closing: a ring grows between them + const held = if (grows) |s| kv_grow.first(s, c.span()) else c.span(); + const pending = try device.buffer(@as(usize, held) * c.ringWidth() * 2, opts); errdefer pending.deinit(); const caches = try backend_mod.newCaches(a, device, c, if (drafting) c.layers else 0); errdefer backend_mod.freeCaches(a, caches); - x.* = .{ .pending = pending, .caches = caches, .session = try Session.init(c, 1, 0) }; + x.* = .{ .pending = pending, .caches = caches, .session = try Session.init(c, 1, 0), .device = device, .span = c.span(), .stride = @as(usize, c.ringWidth()) * 2, .held = held, .step = grows }; x.setResident(m.backend.residency); return x; } + /// The ring's buffer holding `rows` (Ring.Grow): a wider one takes every held row at its place. + fn growRing(ctx: *anyopaque, rows: u32) anyerror!mtl.Buffer { + const x: *Context = @ptrCast(@alignCast(ctx)); + if (rows <= x.held) return x.pending; + const stride = x.stride; + const next = tap_ring.grownRows(x.held, rows, x.step.?, x.span); + const fresh = try x.device.buffer(@as(usize, next) * stride, opts); + if (x.settle) |s| s.run(s.ctx, s.slot); + tap_ring.carry(x.pending, fresh, x.held, stride); + std.log.info("qwen27: slot {d} taps ring grew from {d} to {d} rows", .{ if (x.settle) |h| h.slot else 0, x.held, next }); + x.swapRing(fresh, next); + return fresh; + } + /// The ring back to its first rows once its stream left; nothing reads the old rows once `settle` returns. + fn shrinkRing(x: *Context) !void { + const s = x.step orelse return; + const first = kv_grow.first(s, x.span); + if (x.held <= first) return; + const stride = x.stride; + const fresh = try x.device.buffer(@as(usize, first) * stride, opts); + if (x.settle) |h| h.run(h.ctx, h.slot); + std.log.info("qwen27: slot {d} taps ring gave back {d} to {d} rows", .{ if (x.settle) |h| h.slot else 0, x.held, first }); + x.swapRing(fresh, first); + } + fn swapRing(x: *Context, fresh: mtl.Buffer, rows: u32) void { + if (x.residency) |f| { + f.leave(f.ctx, x.pending); + f.join(f.ctx, fresh); + } + x.pending.deinit(); + x.pending = fresh; + x.held = rows; + } pub fn setResident(x: *Context, hook: ?mtl.ResidencySet.Follow) void { if (x.residency) |f| x.apply(f, false); x.residency = hook; @@ -336,13 +418,14 @@ pub const Context = struct { } /// Empty, as Model.reset leaves the model's own. pub fn reset(x: *Context, c: cfg.Config) !void { + try x.shrinkRing(); x.committed_end = 0; x.session = try Session.init(c, 1, 0); x.context = .{ .cache = 1, .begin = 0, .end = 0 }; } /// Its taps ring, where the lane backend absorbs the stream's kept rows while it is parked. pub fn ring(x: *Context, c: cfg.Config) @import("../tap_ring.zig").Ring { - return .{ .buf = x.pending, .end = &x.committed_end, .window = c.window, .stride = @as(usize, c.tapWidth()) * 2 }; + return .{ .buf = x.pending, .end = &x.committed_end, .window = c.span(), .stride = @as(usize, c.ringWidth()) * 2, .grow = if (x.step != null) .{ .ctx = x, .run = growRing } else null }; } /// Its buffers, for a residency set. pub fn buffers(x: *const Context, list: *std.ArrayList(mtl.Buffer), a: std.mem.Allocator) !void { diff --git a/zig/src/families/qwen27/dflash/selector.zig b/zig/src/families/qwen27/dflash/selector.zig index c15dfb19ab3..f6e0e9aaf1b 100644 --- a/zig/src/families/qwen27/dflash/selector.zig +++ b/zig/src/families/qwen27/dflash/selector.zig @@ -84,7 +84,8 @@ fn expand(g: *const weights.Graph, lattice: op.Lattice, options: Options, first: } pub fn propose(gpa: std.mem.Allocator, g: *const weights.Graph, lattice: op.Lattice, anchor: u32, first_position: u64, options: Options) !Tree { try g.config.check(); - for ([_]weights.Tensor{ g.predecessor, g.successor }) |t| if (t.dtype != .bf16 or t.rank != 2 or t.shape[0] != g.config.vocab or t.shape[1] != g.config.rank) return error.DraftCodebookShape; + // a v1 draft has no codebooks (rank 0): its edges score nothing and its tree follows each depth's marginals + if (g.config.rank > 0) for ([_]weights.Tensor{ g.predecessor, g.successor }) |t| if (t.dtype != .bf16 or t.rank != 2 or t.shape[0] != g.config.vocab or t.shape[1] != g.config.rank) return error.DraftCodebookShape; try lattice.check(g.config); if (anchor >= g.config.vocab or options.nodes > 63 or options.children == 0 or options.children > 16 or lattice.topk > 16 or !std.math.isFinite(options.tau) or options.tau <= 0 or !std.math.isFinite(options.edge) or !std.math.isFinite(options.noise_weight) or !std.math.isFinite(options.temperature) or options.temperature <= 0) return error.BadDraftSelector; if (!std.math.isFinite(options.overhead_ms) or options.overhead_ms < 0) return error.BadDraftCosts; diff --git a/zig/src/families/qwen27/dflash/session.zig b/zig/src/families/qwen27/dflash/session.zig index 28199fa7c0d..8c35fb4f46f 100644 --- a/zig/src/families/qwen27/dflash/session.zig +++ b/zig/src/families/qwen27/dflash/session.zig @@ -17,11 +17,11 @@ pub const Session = struct { } pub fn admit(s: Session, batch: Batch) !op.Context { if (!std.mem.eql(u32, batch.layers[0..s.config.tap_count], s.config.tapIds()) or batch.positions.len == 0) return error.BadCommittedTaps; - try batch.values.check(@intCast(batch.positions.len), s.config.tapWidth(), .bf16); + try batch.values.check(@intCast(batch.positions.len), s.config.ringWidth(), .bf16); const end = try std.math.add(u64, s.context.end, batch.positions.len); if (end != batch.target_end) return error.BadCommittedTaps; for (batch.positions, 0..) |position, i| if (position != s.context.end + i or position >= batch.target_end) return error.BadCommittedTaps; - const begin = @max(s.context.begin, end -| (@as(u64, s.config.window) - 1)); + const begin = @max(s.context.begin, end -| (@as(u64, s.config.span()) - 1)); return .{ .cache = s.context.cache, .begin = begin, .end = end }; } pub fn absorb(s: *Session, ops: op.Ops, graph: *const weights.Graph, preparation: op.Preparation, batch: Batch) !void { diff --git a/zig/src/families/qwen27/dflash/weights.zig b/zig/src/families/qwen27/dflash/weights.zig index 570230cce5d..de2931eee68 100644 --- a/zig/src/families/qwen27/dflash/weights.zig +++ b/zig/src/families/qwen27/dflash/weights.zig @@ -34,6 +34,11 @@ pub const Graph = struct { }; const suffixes = [_][]const u8{ "input_layernorm.weight", "post_attention_layernorm.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", "self_attn.q_norm.weight", "self_attn.k_norm.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight", "attention_conv.kernel_projection.weight", "attention_conv.base_kernel", "mlp_conv.kernel_projection.weight", "mlp_conv.base_kernel" }; const globals = [_][]const u8{ "fc.weight", "hidden_norm.weight", "norm.weight", "candidate_selector.hidden_projection.weight", "candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook" }; +/// A DFlash v1 draft's own tensors: the first eleven suffixes a layer, and fc, hidden_norm and norm. +const v1_suffixes = suffixes[0..11]; +const v1_globals = globals[0..3]; +/// A tensor a v1 draft does not have (its conv and selector slots): no bytes, never bound to a kernel. +pub const absent = Tensor{ .dtype = .bf16, .rank = 0, .shape = @splat(1), .bytes = &.{} }; pub fn names(gpa: std.mem.Allocator, c: Config) ![][]const u8 { const result = try gpa.alloc([]const u8, c.tensorCount()); var made: usize = 0; @@ -41,11 +46,12 @@ pub fn names(gpa: std.mem.Allocator, c: Config) ![][]const u8 { for (result[0..made]) |name| gpa.free(name); gpa.free(result); } - for (globals) |name| { + const v1 = c.variant == .v1; + for (if (v1) v1_globals else &globals) |name| { result[made] = try gpa.dupe(u8, name); made += 1; } - for (0..c.layers) |i| for (suffixes) |suffix| { + for (0..c.layers) |i| for (if (v1) v1_suffixes else &suffixes) |suffix| { result[made] = try std.fmt.allocPrint(gpa, "layers.{d}.{s}", .{ i, suffix }); made += 1; }; @@ -99,6 +105,7 @@ pub fn load(gpa: std.mem.Allocator, source: Inventory, c: Config, embed: ck.Line const src = source.source; const layers = try gpa.alloc(Layer, c.layers); errdefer gpa.free(layers); + if (c.variant == .v1) return loadV1(gpa, src, c, layers, embed); for (layers, 0..) |*l, i| l.* = .{ .input_norm = try layerTensor(src, i, "input_layernorm.weight", &.{c.hidden}), .post_norm = try layerTensor(src, i, "post_attention_layernorm.weight", &.{c.hidden}), @@ -110,6 +117,37 @@ pub fn load(gpa: std.mem.Allocator, source: Inventory, c: Config, embed: ck.Line return .{ .gpa = gpa, .config = c, .layers = layers, .fusion = try get(src, "fc.weight", &.{ c.hidden, c.tapWidth() }), .hidden_norm = try get(src, "hidden_norm.weight", &.{c.hidden}), .norm = try get(src, "norm.weight", &.{c.hidden}), .hidden_projection = try get(src, "candidate_selector.hidden_projection.weight", &.{ c.rank, c.hidden }), .predecessor = try get(src, "candidate_selector.predecessor_codebook", &.{ c.vocab, c.rank }), .successor = try get(src, "candidate_selector.successor_codebook", &.{ c.vocab, c.rank }), .embed = embed }; } +/// v1 layers: the qwen3 body alone; the conv and selector slots stay `absent`. +fn loadV1(gpa: std.mem.Allocator, src: ck.Source, c: Config, layers: []Layer, embed: ck.Linear) !Graph { + const none = Conv{ .projection = absent, .base = absent }; + for (layers, 0..) |*l, i| l.* = .{ + .input_norm = try layerTensor(src, i, "input_layernorm.weight", &.{c.hidden}), + .post_norm = try layerTensor(src, i, "post_attention_layernorm.weight", &.{c.hidden}), + .attention = .{ .q = try layerTensor(src, i, "self_attn.q_proj.weight", &.{ c.qWidth(), c.hidden }), .k = try layerTensor(src, i, "self_attn.k_proj.weight", &.{ c.kvWidth(), c.hidden }), .v = try layerTensor(src, i, "self_attn.v_proj.weight", &.{ c.kvWidth(), c.hidden }), .o = try layerTensor(src, i, "self_attn.o_proj.weight", &.{ c.hidden, c.qWidth() }), .q_norm = try layerTensor(src, i, "self_attn.q_norm.weight", &.{c.head_dim}), .k_norm = try layerTensor(src, i, "self_attn.k_norm.weight", &.{c.head_dim}) }, + .mlp = .{ .gate = try layerTensor(src, i, "mlp.gate_proj.weight", &.{ c.intermediate, c.hidden }), .up = try layerTensor(src, i, "mlp.up_proj.weight", &.{ c.intermediate, c.hidden }), .down = try layerTensor(src, i, "mlp.down_proj.weight", &.{ c.hidden, c.intermediate }) }, + .attention_conv = none, + .mlp_conv = none, + }; + return .{ .gpa = gpa, .config = c, .layers = layers, .fusion = try get(src, "fc.weight", &.{ c.hidden, c.tapWidth() }), .hidden_norm = try get(src, "hidden_norm.weight", &.{c.hidden}), .norm = try get(src, "norm.weight", &.{c.hidden}), .hidden_projection = absent, .predecessor = absent, .successor = absent, .embed = embed }; +} + +test "a DFlash v1 inventory is its sixty-nine qwen3 names, no conv or selector" { + const a = std.testing.allocator; + var c = Config{ .variant = .v1, .hidden = 4096, .intermediate = 12288, .layers = 6, .target_layers = 32, .block = 16, .mask = 248077, .window = 4096, .group = 0, .conv = 0, .rank = 0, .topk = 16, .taps = .{ 1, 5, 9, 13, 17, 21, 25, 29 }, .tap_count = 8 }; + c.full[5] = true; + try c.check(); + const list = try names(a, c); + defer freeNames(a, list); + try inventory(a, list, c); + try std.testing.expectEqual(@as(usize, 69), list.len); + for (list) |name| { + try std.testing.expect(std.mem.indexOf(u8, name, "conv") == null); + try std.testing.expect(std.mem.indexOf(u8, name, "selector") == null); + } + try std.testing.expectEqualStrings("fc.weight", list[0]); + try std.testing.expectEqualStrings("layers.5.mlp.down_proj.weight", list[list.len - 1]); +} + test "inventory is81exact names including unsuffixed BF16codebooks" { const a = std.testing.allocator; const list = try names(a, .{}); diff --git a/zig/src/families/qwen27/kv_grow.zig b/zig/src/families/qwen27/kv_grow.zig new file mode 100644 index 00000000000..dd69edc4178 --- /dev/null +++ b/zig/src/families/qwen27/kv_grow.zig @@ -0,0 +1,46 @@ +//! Grow-as-used K/V (opt-in): a slot holds the rows its stream reached, not the whole context. +const std = @import("std"); + +/// One blit of a K/V buffer's head into a wider buffer, in bytes. +pub const Move = struct { from: usize, to: usize, len: usize }; + +/// TF_Q27_KV_GROW: the rows a slot starts with and grows by (a multiple of 16); unset or 0 keeps every slot full. +pub fn step(text: ?[]const u8) !?u32 { + const value = text orelse return null; + const n = std.fmt.parseInt(u32, value, 10) catch return error.BadKvGrowStep; + if (n == 0) return null; + if (n % 16 != 0) return error.BadKvGrowStep; + return n; +} + +/// A slot's first rows: one step, at most the context. +pub fn first(s: u32, context: u32) u32 { + return @min(s, context); +} + +/// Rows for `need`: the need rounded up to the step, or a quarter more than `held`, at most the context. +pub fn rows(held: u32, need: u32, s: u32, context: u32) u32 { + if (need <= held) return held; + const rounded = (@as(u64, need) + s - 1) / s * s; + const quarter = @as(u64, held) + held / 4; + return @intCast(@min(@max(rounded, quarter), context)); +} + +/// An empty slot's rows for a prompt of `need`: rounded up to the step, at least one step, at most the context. +pub fn admitted(need: u32, s: u32, context: u32) u32 { + const rounded = (@as(u64, need) + s - 1) / s * s; + return @intCast(@min(@max(rounded, s), context)); +} + +/// Head h of a [heads][old][dim] bf16 buffer to its place in a [heads][new][dim] one. +pub fn moves(out: []Move, heads: usize, dim: usize, old: u32, new: u32) []Move { + std.debug.assert(out.len >= heads and new >= old); + const row = dim * @sizeOf(u16); + for (out[0..heads], 0..) |*m, h| m.* = .{ .from = h * old * row, .to = h * new * row, .len = @as(usize, old) * row }; + return out[0..heads]; +} + +/// A slot's K and V bytes across `layers` attention layers at `r` rows of `kv` bf16 values. +pub fn slotBytes(layers: usize, kv: usize, r: u32) usize { + return layers * 2 * @as(usize, r) * kv * @sizeOf(u16); +} diff --git a/zig/src/families/qwen27/kv_slots.zig b/zig/src/families/qwen27/kv_slots.zig new file mode 100644 index 00000000000..7ab70ddc1b2 --- /dev/null +++ b/zig/src/families/qwen27/kv_slots.zig @@ -0,0 +1,167 @@ +//! Grow-as-used K/V for a runner's slots (TF_Q27_KV_GROW): grow before rows are written, give back once a slot is free. +const std = @import("std"); +const mtl = @import("metal"); +const Model = @import("model.zig").Model; +const Runner = @import("decode_round.zig").Runner; +const gpuFailed = @import("decode_round.zig").gpuFailed; +const attn = @import("attention.zig"); +const kv_grow = @import("kv_grow.zig"); + +/// Slot `slot` holds `need` K/V rows: layer by layer, a wider pair takes every old byte at its place (waited blit). +pub fn reserve(r: *Runner, slot: u32, need: u32) !void { + const s = r.kv_step orelse return; + if (slot >= r.ready) return error.SlotNotReady; + const held = r.heldRows(slot); + if (need <= held) return; + if (need > r.capacity) return error.AttentionCapacity; + r.settleSlot(slot); + if (r.failed or r.active != null) return error.RoundNotReady; + const rows = kv_grow.rows(held, need, s, r.capacity); + const layers = r.caches.len / r.slots; + const bytes = @as(usize, rows) * r.model.config.kvDim() * 2; + // one layer at a time, so growth holds at most one layer's old pair beside the new rows + for (0..layers) |layer| { + const at = layer * r.slots + slot; + const c = r.caches[at]; + if (c.capacity >= rows) continue; // grown before an earlier failure + if (c.keys.offset != 0 or c.values.offset != 0 or c.key_stride != 0 or c.value_stride != 0) return error.KvGrowLayout; + var fresh: [2]mtl.Buffer = undefined; + fresh[0] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[0].deinit(); + fresh[1] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[1].deinit(); + const old = [2]mtl.Buffer{ c.keys.buffer, c.values.buffer }; + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = r.model.queue.commandBuffer(); + const e = cb.blit(); + var moves: [attn.planning.max_streams]kv_grow.Move = undefined; + for (old, fresh) |from, to| { + for (kv_grow.moves(&moves, r.model.config.kv_heads, r.model.config.head_dim, c.capacity, rows)) |mv| e.copy(from, mv.from, to, mv.to, mv.len); + } + e.end(); + cb.commit(); + cb.wait(); + if (gpuFailed(cb, "a slot's K/V growth")) return error.RoundGpuFailure; + } + swapPair(r, at, fresh, rows); + } + std.log.info("qwen27: slot {d} K/V grew from {d} to {d} rows ({d} of {d} MiB held)", .{ slot, held, rows, kv_grow.slotBytes(layers, r.model.config.kvDim(), rows) >> 20, r.slotBytes() >> 20 }); +} + +/// Slot `slot` back to its first rows once no stream holds it and no blit reads it: its rows are gone (offset 0). +pub fn release(r: *Runner, slot: u32) !void { + const s = r.kv_step orelse return; + return refit(r, slot, kv_grow.first(s, r.capacity)); +} + +/// An emptied slot takes the rows a prompt of `need` tokens fills, at once and without a copy (a fresh pass). +pub fn admit(r: *Runner, slot: u32, need: u32) !void { + const s = r.kv_step orelse return; + if (need > r.capacity) return error.AttentionCapacity; + return refit(r, slot, kv_grow.admitted(need, s, r.capacity)); +} + +/// Every layer of empty slot `slot` holds exactly `first` rows: new buffers where it holds any other count. +fn refit(r: *Runner, slot: u32, first: u32) !void { + if (slot >= r.ready) return; + var held: u32 = 0; + for (0..r.caches.len / r.slots) |layer| held = @max(held, r.caches[layer * r.slots + slot].capacity); + if (held == first and r.heldRows(slot) == first) return; + r.settleSlot(slot); + if (r.failed) return error.RoundNotReady; + const bytes = @as(usize, first) * r.model.config.kvDim() * 2; + for (0..r.caches.len / r.slots) |layer| { + const at = layer * r.slots + slot; + const c = r.caches[at]; + if (c.capacity == first) continue; + var fresh: [2]mtl.Buffer = undefined; + fresh[0] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer fresh[0].deinit(); + fresh[1] = try r.model.device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + swapPair(r, at, fresh, first); + } + r.offsets[slot] = 0; + std.log.info("qwen27: slot {d} K/V refit from {d} to {d} rows", .{ slot, held, first }); +} + +/// Cache `at` takes `fresh` (`rows` each); its old pair leaves the residency set and is freed. +fn swapPair(r: *Runner, at: usize, fresh: [2]mtl.Buffer, rows: u32) void { + const c = r.caches[at]; + for ([_]mtl.Buffer{ c.keys.buffer, c.values.buffer }, fresh) |from, to| { + for (r.owned.items) |*b| if (b.id == from.id) { + b.* = to; + }; + if (r.residency) |f| { + f.leave(f.ctx, from); + f.join(f.ctx, to); + } + from.deinit(); + } + r.caches[at] = .{ .keys = .{ .buffer = fresh[0] }, .values = .{ .buffer = fresh[1] }, .capacity = rows }; + if (r.grown) |g| g.added(g.ctx, &fresh); +} + +/// One slot's K/V rows across the attention layers. +pub fn slotBytes(r: *const Runner) usize { + return r.caches.len / r.slots * 2 * @as(usize, r.capacity) * r.model.config.kvDim() * 2; +} + +/// Slot `slot`'s K/V rows (the next unready slot, as free slots are taken lowest first); its new buffers. +pub fn ensure(r: *Runner, slot: u32) ![]const mtl.Buffer { + if (slot < r.ready) return &.{}; + if (slot != r.ready) return error.SlotOutOfOrder; + const first = r.owned.items.len; + errdefer { + for (r.owned.items[first..]) |b| b.deinit(); + r.owned.shrinkRetainingCapacity(first); + } + const layers = r.caches.len / r.slots; + const rows = if (r.kv_step) |s| kv_grow.first(s, r.capacity) else r.capacity; + for (0..layers) |layer| r.caches[layer * r.slots + slot] = try slotCache(r.allocator, r.model, &r.owned, rows); + r.ready += 1; + if (r.residency) |f| for (r.owned.items[first..]) |b| f.join(f.ctx, b); + return r.owned.items[first..]; +} + +/// The K/V rows slot `slot` holds now: the fewest any attention layer holds. +pub fn heldRows(r: *const Runner, slot: u32) u32 { + var rows: u32 = std.math.maxInt(u32); + for (0..r.caches.len / r.slots) |layer| rows = @min(rows, r.caches[layer * r.slots + slot].capacity); + return rows; +} + +/// Whether a blit still reads slot `slot` (without waiting for it). +pub fn busy(r: *const Runner, slot: u32) bool { + const cb = r.reading[slot] orelse return false; + return switch (cb.status()) { + .completed, .@"error" => false, + else => true, + }; +} + +/// The K/V buffers of the ready slots (for a residency set). +pub fn readyBuffers(r: *const Runner, a: std.mem.Allocator, out: *std.ArrayList(mtl.Buffer)) !void { + if (r.kv) |k| return out.appendSlice(a, &.{ k.arena, k.tables }); + for (0..r.caches.len / r.slots) |layer| for (0..r.ready) |slot| { + const c = r.caches[layer * r.slots + slot]; + try out.appendSlice(a, &.{ c.keys.buffer, c.values.buffer }); + }; +} + +pub fn slotCache(a: std.mem.Allocator, m: *Model, owned: *std.ArrayList(mtl.Buffer), capacity: u32) !attn.Cache { + const bytes = @as(usize, capacity) * m.config.kvDim() * 2; + const key = try allocation(a, m.device, owned, bytes); + const value = try allocation(a, m.device, owned, bytes); + return .{ .keys = .{ .buffer = key }, .values = .{ .buffer = value }, .capacity = capacity }; +} + +fn allocation(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), bytes: usize) !mtl.Buffer { + const b = try device.buffer(bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + owned.append(a, b) catch |err| { + b.deinit(); + return err; + }; + return b; +} diff --git a/zig/src/families/qwen27/prompt_memory.zig b/zig/src/families/qwen27/prompt_memory.zig index 9d224f9710e..1b5b59d1b57 100644 --- a/zig/src/families/qwen27/prompt_memory.zig +++ b/zig/src/families/qwen27/prompt_memory.zig @@ -19,8 +19,21 @@ pub fn frameBytes(c: Config, rows: u32) usize { return buffers(frame.allocationSizes(c, rows)) + (if (rows > frame.small_rows) buffers(frame.decodeSizes(c, rows)) else 0); } +/// A prompt row's tap bytes: `planes` raw planes, plus a fusing drafter's row-major copy, fc rows and fused row. +pub fn tapRowBytes(hidden: usize, planes: usize, fused: bool) usize { + return (planes + if (fused) planes + 2 else 0) * hidden * 2; +} +test "qwen27 memory: an eight-tap fusing drafter's prompt taps cost what its planes and fusion buffers hold" { + try std.testing.expectEqual(@as(usize, 5 * 5120 * 2), tapRowBytes(5120, 5, false)); + try std.testing.expectEqual(@as(usize, 18 * 4096 * 2), tapRowBytes(4096, 8, true)); +} + /// Frame bytes already belong to the model; these are the runner's future bytes at its peak (`planes`: its tap planes). pub fn runnerBytes(c: Config, context: u32, slots: u32, rows: u32, shared: bool, ring: usize, planes: usize) !usize { + return runnerBytesTaps(c, context, slots, rows, shared, ring, tapRowBytes(c.hidden, planes, false)); +} +/// runnerBytes with the drafter's own tap row bytes (tapRowBytes). +pub fn runnerBytesTaps(c: Config, context: u32, slots: u32, rows: u32, shared: bool, ring: usize, tap_row: usize) !usize { var attention: usize = 0; for (0..c.layers) |i| attention += @intFromBool(c.kind(i) == .attention); const linear = c.layers - attention; @@ -31,7 +44,7 @@ pub fn runnerBytes(c: Config, context: u32, slots: u32, rows: u32, shared: bool, const kv = attention * @as(usize, slots) * buffers([_]usize{ @as(usize, context) * c.kvDim() * 2, @as(usize, context) * c.kvDim() * 2 }); const bindings = attention * buffers([_]usize{ (planning.global_words + planning.max_streams * planning.stream_words) * 4, planning.max_streams * 16, rows * 16 }); const before = if (slots > 1) buffers([_]usize{budget.state}) else 0; - const taps = buffers([_]usize{@as(usize, rows) * planes * c.hidden * 2}); + const taps = buffers([_]usize{@as(usize, rows) * tap_row}); return kv + bindings + before + taps + buffers(scratch.sizes) + buffers(budget.allocationSizes()) + slots * (ring + (256 << 20)); } @@ -43,11 +56,12 @@ pub const Fit = struct { ring: usize = 0, /// The runner's tap planes: the 27B's five, or the drafter's own count. planes: usize = 5, + tap_row: usize = 0, // tapRowBytes for the drafter's taps; 0: five raw planes current_rows: u32, left: usize, pub fn cost(f: Fit, rows: u32, slots: u32) !usize { - return (try runnerBytes(f.config, f.context, slots, rows, f.shared, f.ring, f.planes)) + (frameBytes(f.config, rows) -| frameBytes(f.config, f.current_rows)); + return (try runnerBytesTaps(f.config, f.context, slots, rows, f.shared, f.ring, if (f.tap_row > 0) f.tap_row else tapRowBytes(f.config.hidden, f.planes, false))) + (frameBytes(f.config, rows) -| frameBytes(f.config, f.current_rows)); } pub fn choose(f: Fit, requested: u32, explicit: bool) !u32 { diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index 9e3043ebcc4..1cf0d0492ae 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -32,6 +32,7 @@ pub const model = @import("model.zig"); pub const moe_gpu = @import("moe_gpu.zig"); pub const projection = @import("projection.zig"); pub const prompt_memory = @import("prompt_memory.zig"); +pub const kv_grow = @import("kv_grow.zig"); pub const prompt_rows = @import("prompt_rows.zig"); pub const prompt_marks = @import("prompt_marks.zig"); pub const prompt_tail = @import("prompt_tail.zig"); diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index bb14753233e..32daac24729 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -27,6 +27,7 @@ pub fn setRunner(r: anytype, hook: ?mtl.ResidencySet.Follow) void { pub fn appendDraft(b: anytype, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { try fields.append(a, list, &b.attention); + if (b.attention_full) |*x| try fields.append(a, list, x); try fields.append(a, list, &b.topk); try list.appendSlice(a, b.head.owned.items); try list.appendSlice(a, b.frame.pool.items); @@ -42,6 +43,7 @@ pub fn appendDraft(b: anytype, a: std.mem.Allocator, list: *std.ArrayList(mtl.Bu fn draftBuffers(b: anytype, hook: mtl.ResidencySet.Follow, joining: bool) void { fields.apply(&b.attention, hook, joining); + if (b.attention_full) |*x| fields.apply(x, hook, joining); fields.apply(&b.topk, hook, joining); for (b.head.owned.items) |buffer| fields.one(buffer, hook, joining); for (b.caches) |*c| fields.apply(c, hook, joining); diff --git a/zig/src/families/qwen27/snapshot.zig b/zig/src/families/qwen27/snapshot.zig index 695e712bc08..84491d33bf5 100644 --- a/zig/src/families/qwen27/snapshot.zig +++ b/zig/src/families/qwen27/snapshot.zig @@ -240,7 +240,10 @@ pub fn restoreSlot(a: std.mem.Allocator, r: *Runner, slot: u32, ring: ?Ring, st: try st.landed(); try r.reset(slot); try r.cover(slot, st.at); // a paged slot's pages for the state's rows before the copy writes them - try copy(a, r, slot, ring, st, false); + try r.reserve(slot, st.at); // a slot whose K/V and ring grow as used holds the state's rows first + var held = ring; + if (held) |*g| try g.hold(st.at); + try copy(a, r, slot, held, st, false); r.offsets[slot] = st.at; if (ring) |g| g.end.* = st.draft_end; } @@ -253,12 +256,15 @@ pub fn moveSlot(a: std.mem.Allocator, r: *Runner, from: u32, from_ring: ?Ring, t if (from_ring) |g| if (g.end.* != at) return error.NotAtMark; try r.reset(to); try r.cover(to, at); + try r.reserve(to, at); + var to_held = to_ring; + if (to_held) |*g| try g.hold(at); var src: std.ArrayList(Part) = .empty; defer src.deinit(a); var dst: std.ArrayList(Part) = .empty; defer dst.deinit(a); try parts(r, from, from_ring, at, &src, a, false); - try parts(r, to, to_ring, at, &dst, a, false); + try parts(r, to, to_held, at, &dst, a, false); if (src.items.len != dst.items.len) return error.SnapshotLayout; const pool = mtl.objc.Pool.push(); defer pool.pop(); diff --git a/zig/src/families/qwen27/tap_ring.zig b/zig/src/families/qwen27/tap_ring.zig index 3360a3d954e..27fb1d378f9 100644 --- a/zig/src/families/qwen27/tap_ring.zig +++ b/zig/src/families/qwen27/tap_ring.zig @@ -1,12 +1,17 @@ //! A stream's committed target taps over the drafter's window, by position modulo the window. const std = @import("std"); const mtl = @import("metal"); +const kv_grow = @import("kv_grow.zig"); pub const Ring = struct { buf: mtl.Buffer, end: *u64, // taps committed so far (the stream's fed tokens) window: u32, stride: usize, // one row's bytes + grow: ?Grow = null, // a ring that holds the rows its stream reached: the buffer holding `rows`; null: the window + + /// The buffer holding at least `rows` rows (it may be a new one; the old rows stay at their places). + pub const Grow = struct { ctx: *anyopaque, run: *const fn (ctx: *anyopaque, rows: u32) anyerror!mtl.Buffer }; /// Rows [off, off + rows) of `taps` follow the committed ones. pub fn absorb(r: Ring, taps: mtl.Buffer, off: usize, rows: u32) !void { @@ -18,18 +23,35 @@ pub const Ring = struct { pub fn absorbBytes(r: Ring, data: []const u8, rows: u32) !void { if (rows == 0 or data.len != @as(usize, rows) * r.stride) return error.BadCommittedTaps; const end = try std.math.add(u64, r.end.*, rows); + const buf = if (r.grow) |g| try g.run(g.ctx, @intCast(@min(end, r.window))) else r.buf; var first: usize = 0; while (first < rows) { const slot: usize = @intCast((r.end.* + first) % r.window); const count = @min(rows - first, r.window - slot); - @memcpy(r.buf.contents()[slot * r.stride ..][0 .. count * r.stride], data[first * r.stride ..][0 .. count * r.stride]); + @memcpy(buf.contents()[slot * r.stride ..][0 .. count * r.stride], data[first * r.stride ..][0 .. count * r.stride]); first += count; } r.end.* = end; } + /// The ring holds a state of `rows` tokens before a blit writes it (a restore); its buffer may change. + pub fn hold(r: *Ring, rows: u64) !void { + if (r.grow) |g| r.buf = try g.run(g.ctx, @intCast(@min(rows, r.window))); + } + /// Ring bytes a state after `at` tokens needs: slots [0, at) until the ring wraps, then all of it. pub fn bytes(r: Ring, at: u64) usize { return @as(usize, @intCast(@min(at, r.window))) * r.stride; } }; + +/// Rows a growing ring takes for `need`: the K/V growth rule, at most the window. +pub fn grownRows(held: u32, need: u32, step: u32, window: u32) u32 { + return kv_grow.rows(held, need, step, window); +} + +/// A grown ring's first `held` rows into its new buffer, at the same places (the CPU writes rings). +pub fn carry(old: mtl.Buffer, new: mtl.Buffer, held: u32, stride: usize) void { + const n = @as(usize, held) * stride; + @memcpy(new.contents()[0..n], old.contents()[0..n]); +} diff --git a/zig/src/families/qwen27/taps.zig b/zig/src/families/qwen27/taps.zig index 418871042e5..a879f377d67 100644 --- a/zig/src/families/qwen27/taps.zig +++ b/zig/src/families/qwen27/taps.zig @@ -6,10 +6,20 @@ const Glue = @import("glue_gpu.zig").Kernels; /// The 27B drafter's tap layers, the default before a drafter sets its own. pub const layers = [_]usize{ 5, 19, 33, 47, 61 }; +/// The most tap planes a drafter may name (a DFlash v1 draft names up to eight). pub const max_planes = 8; +/// A drafter's fusion of a row's taps (fc then hidden_norm), encoded where the taps complete. +pub const Fuser = struct { ptr: *anyopaque, width: u32, encode: *const fn (*anyopaque, mtl.ComputeEncoder, Ref, Ref, u32) anyerror!void }; +/// Where accepted rows gather from: the raw planes, or one plane of fused rows. +pub const Source = struct { buffer: mtl.Buffer, width: u32, planes: u32 }; + pub const Taps = struct { buffer: mtl.Buffer, + fuser: ?Fuser = null, + fused: ?mtl.Buffer = null, // [capacity][fuser width] + rowmajor: ?mtl.Buffer = null, // [capacity][count * width]: a row's planes side by side, fc's input + identity: ?mtl.Buffer = null, // 0, 1, ... capacity - 1: every row, for the row-major gather capacity: u32, width: u32, seen: u16 = 0, @@ -27,6 +37,7 @@ pub const Taps = struct { /// A drafter's tap layers; the buffer grows to their count when it holds fewer planes, never shrinks. pub fn use(t: *Taps, device: mtl.Device, ids: []const u32) !void { if (ids.len == 0 or ids.len > max_planes) return error.BadTapIndex; + if (t.fuser != null and ids.len != t.count) return error.BadTapShape; // a fused ring keeps its tap count if (ids.len > t.planes) { const grown = try planesBuffer(device, t.capacity, t.width, ids.len); t.buffer.deinit(); @@ -43,9 +54,44 @@ pub const Taps = struct { } pub fn deinit(t: Taps) void { + t.dropFused(); t.buffer.deinit(); } + fn dropFused(t: Taps) void { + if (t.fused) |b| b.deinit(); + if (t.rowmajor) |b| b.deinit(); + if (t.identity) |b| b.deinit(); + } + + /// Completed taps fused for a drafter whose ring keeps fused rows; null: planes stay raw. + pub fn setFuser(t: *Taps, device: mtl.Device, f: ?Fuser) !void { + t.dropFused(); + t.fuser = null; + t.fused = null; + t.rowmajor = null; + t.identity = null; + const fuser = f orelse return; + if (fuser.width == 0) return error.BadTapShape; + const options = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const fused = try device.buffer(@as(usize, t.capacity) * fuser.width * 2, options); + errdefer fused.deinit(); + const rowmajor = try device.buffer(@as(usize, t.capacity) * t.count * t.width * 2, options); + errdefer rowmajor.deinit(); + const identity = try device.buffer(@as(usize, t.capacity) * 4, options); + for (identity.slice(u32, t.capacity), 0..) |*x, i| x.* = @intCast(i); + t.fuser = fuser; + t.fused = fused; + t.rowmajor = rowmajor; + t.identity = identity; + } + + /// The rows accepted taps gather from. + pub fn source(t: Taps) Source { + if (t.fused) |f| return .{ .buffer = f, .width = t.fuser.?.width, .planes = 1 }; + return .{ .buffer = t.buffer, .width = t.width, .planes = @intCast(t.count) }; + } + pub fn begin(t: *Taps) void { t.seen = 0; t.rows = 0; @@ -61,6 +107,13 @@ pub const Taps = struct { e.barrier(); t.seen |= bit; t.rows = rows; + if (t.fuser) |f| if (t.seen == (@as(u16, 1) << @intCast(t.count)) - 1) { + const kept = Ref{ .buffer = t.identity.? }; + try glue.tapRows(e, .{ .buffer = t.buffer }, kept, .{ .buffer = t.rowmajor.? }, .{ .rows = rows, .width = t.width, .capacity = t.capacity, .planes = @intCast(t.count) }); + e.barrier(); + try f.encode(f.ptr, e, .{ .buffer = t.rowmajor.? }, .{ .buffer = t.fused.? }, rows); + e.barrier(); + }; } pub fn plane(t: Taps, index: usize) !Ref { @@ -69,7 +122,7 @@ pub const Taps = struct { } pub fn complete(t: Taps) !void { - if (t.count == 0 or t.count > t.planes or t.seen != (@as(u16, 1) << @intCast(t.count)) - 1) return error.IncompleteTaps; + if (t.count == 0 or t.count > t.planes or t.seen != fullMask(t.count)) return error.IncompleteTaps; } pub fn accepted(t: Taps, glue: Glue, e: mtl.ComputeEncoder, path: []const u32, kept: Ref, out: Ref) !void { @@ -77,11 +130,21 @@ pub const Taps = struct { if (path.len == 0) return; if (path.len > t.rows) return error.BadTapGather; for (path) |row| if (row >= t.rows) return error.BadTapGather; - try glue.tapRows(e, .{ .buffer = t.buffer }, kept, out, .{ .rows = @intCast(path.len), .width = t.width, .capacity = t.capacity, .planes = @intCast(t.count) }); + const s = t.source(); + try glue.tapRows(e, .{ .buffer = s.buffer }, kept, out, .{ .rows = @intCast(path.len), .width = s.width, .capacity = t.capacity, .planes = s.planes }); e.barrier(); } }; +fn fullMask(count: usize) u16 { + return @intCast((@as(u16, 1) << @intCast(count)) - 1); +} + +test "eight tap planes complete when all eight are seen" { + try std.testing.expectEqual(@as(u16, 0xff), fullMask(8)); + try std.testing.expectEqual(@as(u16, 0x1f), fullMask(5)); +} + test "DFlash tap ids name completed target blocks" { try std.testing.expectEqualSlices(usize, &.{ 5, 19, 33, 47, 61 }, &layers); } diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 449016e155c..bdb9afe91a6 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -402,7 +402,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a const store = try gpa.create(pc.Store); errdefer gpa.destroy(store); // rules and budget from the family's snap_* declarations (cuda_snaps.zig) - const image: ?*const pc.rows.Image = if (F == nemotron.native) &cuda_disk.image else if (comptime cuda_disk.keptDisk(F)) |K| &K.image else null; + const image: ?*const pc.rows.Image = if (F == nemotron.native) &cuda_disk.image else if (F == @import("glm_cuda").native) &@import("cuda_glm_disk.zig").image else if (comptime cuda_disk.keptDisk(F)) |K| &K.image else null; const copies: pc.Snapshots = .{ .ptr = loaded.target, .vtable = &snaps.Snaps(F, image).vtable }; var rules = snaps.passRules(F, @import("cuda_startup.zig").rows(F, loaded)); if (o.tp != 1) rules.warm = .off; // no warm passes across ranks: the cache keeps as without warm turns @@ -416,7 +416,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a try kv_pages.store(F, store, loaded, kept); // its snapshot slots, before a disk probe takes one h.store = store; if (o.learn_conversations) if (o.learn) |root| { - if (F == nemotron.native) try cuda_disk.attach(a, io, &g.ctx, o, root, kernels, loaded, store); + if (F == nemotron.native) try cuda_disk.attach(a, io, &g.ctx, o, root, kernels, loaded, store) else if (F == @import("glm_cuda").native) try @import("cuda_glm_disk.zig").attach(a, io, &g.ctx, o, root, kernels, loaded, store); if (comptime cuda_disk.keptDisk(F)) |K| try cuda_disk.attachKept(K, F.model_type, a, io, &g.ctx, o, root, kernels, loaded, store); }; } @@ -559,6 +559,7 @@ test { _ = kv_pages; _ = drafted; _ = cuda_disk; // its tests run under test-cuda-disk-open-host's filter + _ = @import("cuda_glm_disk.zig"); _ = @import("cuda_disk_identity_test.zig"); _ = cuda_witness; _ = @import("cuda_pool_after_warmup.zig"); diff --git a/zig/src/native/cuda_glm_disk.zig b/zig/src/native/cuda_glm_disk.zig new file mode 100644 index 00000000000..bb9674fa4bd --- /dev/null +++ b/zig/src/native/cuda_glm_disk.zig @@ -0,0 +1,266 @@ +//! GLM-5.3-Flash's CUDA kept states on disk (--learn-conversations): every rank's part in rank 0's files. +const std = @import("std"); +const cuda = @import("cuda"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const glm = @import("glm_cuda"); +const cuda_disk = @import("cuda_disk.zig"); +const img = glm.disk_image; +const ranks = glm.disk_ranks; +const rows = api.prompt_cache.rows; +const Engine = glm.engine.Engine; +const Kept = glm.engine.Kept; +const Allocator = std.mem.Allocator; + +pub const image: rows.Image = .{ .parts = parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; + +/// Every rank's prefix bytes, read at attach (the process serves one model; rank 0 alone serves). +var prefix_buf: [8]u64 = undefined; +var prefixes: []const u64 = &.{}; +/// Where each rank's verify window rows begin in its prefix (the probe's hash leaves them out). +var window_buf: [prefix_buf.len]u64 = undefined; + +fn engineOf(ptr: *anyopaque) *Engine { + return @ptrCast(@alignCast(ptr)); +} + +fn parts(ptr: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { + var list: std.ArrayList(img.Part) = .empty; + defer list.deinit(a); + try img.storeParts(try ranks.shape(engineOf(ptr)), prefixes, at, &list, a); + for (list.items) |p| try out.append(a, .{ .bytes = p.bytes, .row = p.row, .per = p.per }); +} + +/// The other ranks asleep before a disk call go back to sleep after it (their lines, not NCCL, wait meanwhile). +const Rest = struct { + e: *Engine, + asleep: bool, + + fn of(e: *Engine) Rest { + return .{ .e = e, .asleep = ranks.asleep(e) }; + } + + fn done(r: Rest) void { + if (r.asleep) ranks.rest(r.e) catch |err| std.log.warn("glm: the ranks did not sleep after a disk step ({s})", .{@errorName(err)}); + } +}; + +fn gather(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, out: []u8) anyerror!void { + const e = engineOf(ptr); + const k: *Kept = @ptrCast(@alignCast(saved)); + const rest = Rest.of(e); + defer rest.done(); + var pieces: std.ArrayList(img.Piece) = .empty; + defer pieces.deinit(e.gpa); + const sh = try ranks.shape(e); + var o: usize = 0; + for (ranges) |g| { + pieces.clearRetainingCapacity(); + try img.route(sh, prefixes, k.at, g.off, g.len, &pieces, e.gpa); + for (pieces.items) |p| { + const n: usize = @intCast(p.len); + try ranks.take(e, p.rank, k.id, p.off, out[o..][0..n]); + o += n; + } + } +} + +/// A new id leased at `at` on every rank, filled by `scatter` and sealed by the words in its last one. +fn blank(ptr: *anyopaque, at: u32) anyerror!api.prompt_cache.Saved { + const e = engineOf(ptr); + const rest = Rest.of(e); + defer rest.done(); + const k = try e.gpa.create(Kept); + errdefer e.gpa.destroy(k); + k.* = .{ .id = try ranks.blank(e, at), .at = at }; + return @ptrCast(k); +} + +/// The last scatter brings the state's own file, words first: every rank seals it then (the words place the head). +fn scatter(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, in: []const u8) anyerror!void { + const e = engineOf(ptr); + const k: *Kept = @ptrCast(@alignCast(saved)); + const rest = Rest.of(e); + defer rest.done(); + if (ranges.len > 0 and ranges[0].off == 0) { + if (ranges[0].len < img.Words.bytes) return error.DiskWords; + var x: [img.Words.count]u64 = undefined; + @memcpy(std.mem.sliceAsBytes(&x), in[0..img.Words.bytes]); + try ranks.seal(e, k.id, try ranks.decode(e, x, k.at)); + } + var pieces: std.ArrayList(img.Piece) = .empty; + defer pieces.deinit(e.gpa); + var out: std.ArrayList(ranks.Piece) = .empty; // at TP: the other ranks' bytes and the shared ones, in few steps + defer out.deinit(e.gpa); + const sh = try ranks.shape(e); + var o: usize = 0; + for (ranges) |g| { + pieces.clearRetainingCapacity(); + try img.route(sh, prefixes, k.at, g.off, g.len, &pieces, e.gpa); + for (pieces.items) |p| { + const n: usize = @intCast(p.len); + const bytes = in[o..][0..n]; + o += n; + if (p.rank == 0 and p.off < img.Words.bytes) continue; // the words went with the seal + if (prefixes.len == 1 or (p.rank == 0 and !p.shared)) { + try ranks.copy(e, k.id, p.off, @constCast(bytes), false); + } else try out.append(e.gpa, .{ .to = if (p.shared) ranks.every else p.rank, .off = if (p.shared) p.off - prefixes[0] else p.off, .bytes = bytes }); + } + } + if (out.items.len > 0) try ranks.rows(e, k.id, out.items); +} + +fn whole(ptr: *anyopaque, saved: api.prompt_cache.Saved) bool { + const k: *Kept = @ptrCast(@alignCast(saved)); + const s = engineOf(ptr).snaps.get(k.id) orelse return false; + return s.len != 0; +} + +/// A fixed prompt's store image hashed, other ranks' shared bytes checked equal: both but the bytes it never writes. +fn probe(a: Allocator, io: std.Io, backend: lanes.backend.Backend, e: *Engine) !struct { hash: u64, rate: f64 } { + const mark: u32 = glm.native.prompt_rows; + var toks: [glm.native.prompt_rows + 40]u32 = undefined; + for (&toks, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + const Hook = struct { + e: *Engine, + saved: ?*anyopaque = null, + failed: ?anyerror = null, + fn at(p: *anyopaque, _: *lanes.Stream, m: u32) void { + const h: *@This() = @ptrCast(@alignCast(p)); + h.saved = glm.native.snap_save(h.e, null, m) catch |err| { + h.failed = err; + return; + }; + } + }; + var hook: Hook = .{ .e = e }; + const marks = [_]u32{mark}; + var s = try lanes.Stream.init(a, .{ .id = "probe", .prompt = &toks, .max_new = 1, .drafts = e.mtp, .reuse = .{ .marks = &marks, .hook = .{ .ptr = &hook, .at = Hook.at } } }); + defer s.deinit(a); + const t0 = std.Io.Clock.awake.now(io).toNanoseconds(); + backend.vtable.prefill(backend.ptr, &s) catch |err| { + backend.vtable.release(backend.ptr, &s); + return err; + }; + const ns = std.Io.Clock.awake.now(io).toNanoseconds() - t0; + backend.vtable.release(backend.ptr, &s); + const saved = hook.saved orelse return hook.failed orelse error.ProbeUnmarked; + defer glm.native.snap_drop(e, saved); + const k: *Kept = @ptrCast(@alignCast(saved)); + const sh = try ranks.shape(e); + const own = img.imageBytes(sh, mark); + var total = own; + for (prefixes[1..]) |p| total += p; + const bytes = try a.alloc(u8, @intCast(total)); + try gather(e, saved, &.{.{ .off = 0, .len = total }}, bytes); + var loose: std.ArrayList(img.Span) = .empty; + try img.unwritten(sh, prefixes, window_buf[0..prefixes.len], mark, (try ranks.wordsOf(e, k.id)).mtp_len, &loose, a); + img.clear(loose.items, 0, bytes); + const from = img.Words.bytes + sh.prefix; + const shared = bytes[@intCast(from)..@intCast(own)]; + var past: std.ArrayList(img.Span) = .empty; // the spans past rank 0's prefix, as spans of `shared` + for (loose.items) |x| if (x.off >= from) try past.append(a, .{ .off = x.off - from, .len = x.len }); + try ranks.same(e, k.id, prefixes, shared, past.items, try a.alloc(u8, shared.len)); + try ranks.rest(e); + return .{ .hash = std.hash.Wyhash.hash(0x676c6d, bytes), .rate = @as(f64, @floatFromInt(toks.len)) / (@as(f64, @floatFromInt(@max(ns, 1))) / 1e9) }; +} + +/// What --learn-conversations refuses before it reads a rank: TF_KV_SHARE, and more ranks than `prefix_buf` holds. +fn refusal(e: *const Engine) !void { + // TF_KV_SHARE leaves a kept state's prefix pages in the pool's prompt cache, outside the lease the image reads + if (e.share_pages) return error.KvShareWithLearnConversations; + if (e.share.world > prefix_buf.len) return error.TooManyRanks; +} + +/// --learn-conversations: every rank's prefix read, the identity probed on this thread, the store attached. +pub fn attach(a: Allocator, io: std.Io, ctx: *const cuda.Context, o: api.Open, root: []const u8, kernels: ?[]const u8, loaded: anytype, store: *api.prompt_cache.Store) !void { + const e: *Engine = loaded.target; + refusal(e) catch |err| { + if (err == error.KvShareWithLearnConversations) std.log.err("--learn-conversations: GLM-5.3-Flash's disk images read a kept state's whole lease, and TF_KV_SHARE leaves its prefix pages out of it; serve without one of them", .{}); + return err; + }; + try ranks.prefixes(e, prefix_buf[0..e.share.world], window_buf[0..e.share.world]); + prefixes = prefix_buf[0..e.share.world]; + const sh = try ranks.shape(e); + var facts: std.ArrayList(u64) = .empty; + try facts.appendSlice(a, &.{ e.share.world, sh.capacity, sh.ring_rows, sh.tail, @intFromBool(sh.head), @intFromBool(sh.scales), @intFromBool(e.drafter != null) }); + try facts.appendSlice(a, prefixes); + const p = try probe(a, io, loaded.backend, e); + const id = try cuda_disk.identityOf(a, io, ctx, o.dir, kernels, facts.items, p.hash, .{ .family = o.model_type, .backend = "cuda" }); + const r = try open(store, o, root, id, img.longest(sh)); + r.prefill_rate = p.rate; + std.log.info("glm: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB; {d} ranks' parts; a save stages up to {d} MiB)", .{ r.dir, r.states.items.len, r.held() >> 20, r.cap >> 20, prefixes.len, r.staging_bytes >> 20 }); +} + +/// The store for `id` through the shared attach, whose staging floor takes a `longest`-token state whole (rows.attach). +fn open(store: *api.prompt_cache.Store, o: api.Open, root: []const u8, id: u64, longest: u32) !*rows.Rows { + const gibs = struct { + fn bytes(g: f64) u64 { + return @intFromFloat(g * (1 << 30)); + } + }.bytes; + // spill stays off: an eviction would gather on rank 0 mid-pass while the other ranks wait in the gate's all-reduce + return rows.attach(store.gpa, store, .{ .root = root, .identity = id, .cap = gibs(o.learn_gib), .floor = gibs(o.learn_min_free_gib), .daily = gibs(o.learn_daily_gib), .lookahead = store.rules.lookahead, .planned = store.rules.planned, .grid = store.rules.grid, .longest = longest }); +} + +test "GLM disk attach: TF_KV_SHARE and more ranks than the prefixes hold are refused by name" { + const e = try std.testing.allocator.create(Engine); + defer std.testing.allocator.destroy(e); + e.share_pages = false; + e.share.world = prefix_buf.len; + try refusal(e); + e.share.world = prefix_buf.len + 1; + try std.testing.expectError(error.TooManyRanks, refusal(e)); + e.share.world = 2; + e.share_pages = true; + try std.testing.expectError(error.KvShareWithLearnConversations, refusal(e)); +} + +test "CUDA disk open: GLM's store takes the shared attach's staging floor, so a 125K-token state is staged, not StagingFull" { + const gpa = std.testing.allocator; + const T = struct { + const token = 18_944; // about 18.5 KiB a token, as a served state's files measure (683 MiB at 36,864 tokens) + fn parts(_: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { + try out.append(a, .{ .bytes = @as(u64, at) * token, .row = token }); + } + fn bytes(_: *anyopaque, _: u32) u64 { + return 0; + } + fn save(_: *anyopaque, _: ?*anyopaque, _: u32) anyerror!api.prompt_cache.Saved { + return error.Unused; + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: api.prompt_cache.Saved) anyerror!void {} + fn drop(_: *anyopaque, _: api.prompt_cache.Saved) void {} + }; + const sized: rows.Image = .{ .parts = T.parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try tmp.dir.realPathFileAlloc(std.testing.io, ".", gpa); + defer gpa.free(root); + var family: u8 = 0; + const vt: api.prompt_cache.Snapshots.VTable = .{ .bytes = T.bytes, .save = T.save, .restore = T.restore, .drop = T.drop, .rows = &sized }; + const default = (rows.Options{ .root = "", .identity = 0, .cap = 0, .floor = 0, .daily = 0 }).staging_bytes; + const window = 131_072; + // a RAM store that keeps the state, and one too small for it: the floor is the state's charge within that budget + for ([_]u64{ 8 << 30, 1 << 29 }) |budget| { + var store = api.prompt_cache.Store.init(gpa, .{ .ptr = &family, .vtable = &vt }, .{ .lookahead = 1 }, budget); + const r = open(&store, .{ .dir = "d", .model_type = "glm", .learn = root, .learn_conversations = true }, root, 7, window) catch |e| { + store.deinit(); + return e; + }; + defer r.deinit(); + defer store.deinit(); // the store before its disk, as the rows fixtures close them + try std.testing.expectEqual(r, store.disk.?); + try std.testing.expectEqual(rows.Spill.off, r.spill); + const long = try rows.write.coldCharge(r, 124_928); // the conversation the default skipped (StagingFull) + try std.testing.expect(long > default); + if (budget > long) { + try std.testing.expect(r.staging_bytes >= long); // the permit a save's stage step asks `fits` of + try std.testing.expectEqual(try rows.write.coldCharge(r, window), r.staging_bytes); // the longest, whole + } else try std.testing.expectEqual(default, r.staging_bytes); + } +} + +test { + std.testing.refAllDecls(@This()); +} diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 7c4b71ddbd3..88081b45b83 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -64,7 +64,7 @@ pub fn place(comptime F: type, a: std.mem.Allocator, o: api.Open) !?[]const u8 { return null; } -/// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron; null: `o` may open `F`. +/// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron, GLM or a kept_disk family. pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if (comptime @hasDecl(F, "kvHostRefusal")) if (F.kvHostRefusal(o)) |why| return why; if (qwen35Tp(F, o)) |why| return why; // ahead of every flag's own refusal: no rank of this family serves yet @@ -74,11 +74,16 @@ pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if ((o.tp != 1 or (o.given.rank and o.rank != 0)) and !ranked) return no_ranks; // ahead of the drafter's and --learn-conversations' refusals (--spill-gib sets that flag), on a line of its own if (o.spill == .evicted and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--spill-gib keeps evicted states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; + // GLM's disk store writes every rank's part between passes and stages nothing at eviction (cuda_glm_disk.attach) + if (F == @import("glm_cuda").native and (o.spill != .off or o.keep != null)) return "--spill-gib and --checkpoint-slots: GLM-5.3-Flash on CUDA keeps states on disk with --learn-conversations alone; serve it without them"; + // a live-half keep holds one KDA half, and GLM's disk image holds both (cuda_disk_image.zig) + if (F == @import("glm_cuda").native and o.learn_conversations and @import("glm_cuda").snapshots.layout.liveHalfEnabled()) + return "--learn-conversations and TF_GLM_KV_LIVE_HALF=1: GLM-5.3-Flash's disk image holds both KDA halves and a live-half keep one; serve without one of them"; if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) { if (@hasDecl(F, "drafter_refusal")) return F.drafter_refusal; // a family without an MTP head says so itself return "--drafter loads a separate drafter, and this CUDA family drafts with its own MTP head: serve without --drafter"; } - if (o.learn_conversations and F != nemotron.native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; + if (o.learn_conversations and F != nemotron.native and F != @import("glm_cuda").native and @import("cuda_disk.zig").keptDisk(F) == null) return "--learn-conversations keeps conversation states on disk for Nemotron, GLM-5.3-Flash, the Qwen hybrids, Flash Next, Gemma 4, Dory and Spark2.5 only on CUDA: serve this model without it"; if (o.learn_conversations and o.tp > 1) if (@import("cuda_disk.zig").keptDisk(F)) |K| if (@hasDecl(K, "one_rank") and K.one_rank) return "--learn-conversations keeps one rank's states on disk for this CUDA family: serve without --tp or without --learn-conversations"; if (o.kv8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "kv8"))) return "--kv-cache fp8: this CUDA family keeps bf16 caches; serve without it"; if (o.prompt_int8 and !(@hasDecl(F, "Options") and @hasField(F.Options, "prompt_int8"))) return "--prompt-precision int8: this CUDA family's prompt matmuls take bf16 inputs; serve without it"; @@ -277,7 +282,7 @@ test "a family with no head of its own words its --drafter refusal" { try std.testing.expectEqualStrings("--drafter: none yet", family(Headless, .{ .dir = "d", .model_type = "m", .drafter = "x" }) orelse ""); } -test "--learn-conversations opens Nemotron and a family whose states declare a disk image, no other" { +test "--learn-conversations opens Nemotron, GLM-5.3-Flash and a family whose states declare a disk image, no other" { const Other = struct {}; const Imaged = struct { pub const kept_disk = struct {}; @@ -302,6 +307,7 @@ test "--learn-conversations opens Nemotron and a family whose states declare a d try std.testing.expect(family(AllRanks, .{ .dir = "d", .model_type = "m", .tp = 2, .learn_conversations = true }) == null); try std.testing.expectStringStartsWith(family(Other, .{ .dir = "d", .model_type = "m", .learn_conversations = true }) orelse "", "--learn-conversations keeps"); try std.testing.expect(family(nemotron.native, .{ .dir = "d", .model_type = "nemotron_h", .learn_conversations = true }) == null); + try std.testing.expect(family(@import("glm_cuda").native, .{ .dir = "d", .model_type = "glm5_next", .learn_conversations = true }) == null); } test "CUDA MTP controls respect window and probability bounds" { @@ -357,27 +363,38 @@ test "--prompt-cache-gib is refused by name for a family that keeps no prompts, try std.testing.expect(family(@import("lfm2_moe_cuda").native, .{ .dir = "d", .model_type = "lfm2_moe", .prompt_cache_gib = 4 }) == null); } -test "--spill-gib and --checkpoint-slots open the families with a disk image; the rest refuse them by name" { +test "--spill-gib and --checkpoint-slots open the families with a disk image; GLM and the rest refuse them by name" { const spilled: api.Open = .{ .dir = "d", .model_type = "m", .learn = "/s", .learn_conversations = true, .spill = .evicted, .keep = 2 }; try std.testing.expect(backend(spilled) == null); try std.testing.expect(family(nemotron.native, spilled) == null); try std.testing.expect(family(@import("qwen35").native, spilled) == null); try std.testing.expect(family(@import("qwen35").native_moe, spilled) == null); try std.testing.expect(family(@import("flashnext").native, spilled) == null); + const glm = @import("glm_cuda").native; // its states go to disk with --learn-conversations alone + try std.testing.expectStringStartsWith(family(glm, spilled) orelse "", "--spill-gib keeps evicted states"); + const finish: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .spill = .finish }; + try std.testing.expectStringStartsWith(family(glm, finish) orelse "", "--spill-gib and --checkpoint-slots: GLM"); + const slots: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .keep = 2 }; + try std.testing.expectStringStartsWith(family(glm, slots) orelse "", "--spill-gib and --checkpoint-slots: GLM"); + try std.testing.expect(family(glm, .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true }) == null); const Other = struct {}; try std.testing.expectStringStartsWith(family(Other, spilled) orelse "", "--spill-gib keeps evicted states"); try std.testing.expectStringStartsWith(backend(.{ .dir = "d", .model_type = "m", .keep = 2 }) orelse "", "--checkpoint-slots sets how many"); try std.testing.expect(backend(.{ .dir = "d", .model_type = "m" }) == null); } -test "GLM keeps its prompt states in the process: no disk image, so --spill-gib and --learn-conversations refuse" { +test "GLM keeps its prompt states on disk with --learn-conversations alone, and refuses it with TF_GLM_KV_LIVE_HALF=1" { // TF_GLM_KV_LIVE_HALF's keeps omit the dead KDA half; they must never reach a store a server without the flag reads const glm = @import("glm_cuda").native; try std.testing.expect(@import("cuda_disk.zig").keptDisk(glm) == null); const spill: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true, .spill = .evicted }; try std.testing.expectStringStartsWith(family(glm, spill) orelse "", "--spill-gib keeps evicted states"); const learn: api.Open = .{ .dir = "d", .model_type = "glm5_next", .learn = "/s", .learn_conversations = true }; - try std.testing.expectStringStartsWith(family(glm, learn) orelse "", "--learn-conversations keeps"); + try std.testing.expect(family(glm, learn) == null); + const env = @import("sys").env; + try std.testing.expectEqual(@as(c_int, 0), env.setenv("TF_GLM_KV_LIVE_HALF", "1", 1)); + defer _ = env.unsetenv("TF_GLM_KV_LIVE_HALF"); + try std.testing.expectStringStartsWith(family(glm, learn) orelse "", "--learn-conversations and TF_GLM_KV_LIVE_HALF=1"); } /// The scopes this open's startup check covers, from its flags and model type. diff --git a/zig/src/native/lfm3.zig b/zig/src/native/lfm3.zig index 9c13198c767..9255b131ed7 100644 --- a/zig/src/native/lfm3.zig +++ b/zig/src/native/lfm3.zig @@ -41,6 +41,7 @@ fn cacheRules() api.prompt_cache.Rules { } pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const warm_turns = try @import("sys").environment.read(bool, "TF_LFM3_METAL_WARM_TURNS", false); const pool = mtl.objc.Pool.push(); defer pool.pop(); var config = q.config.Config.read(gpa, io, o.dir) catch |err| { @@ -76,7 +77,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.gpa = gpa; h.model = model; h.resident = null; - const chunk = prompt_chunk; + // Every prompt row, including decoded history, uses the one-row forward in warm mode. + const chunk: u32 = if (warm_turns) 1 else prompt_chunk; h.metal = try q.backend.Metal.init(gpa, model, .{ .capacity = window, .chunk = chunk, .streams = @max(o.lanes, 2) }); errdefer h.metal.deinit(); const per_stream = q.state.cacheBytes(&model.config.layer_types, window); @@ -92,7 +94,9 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.clock = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "lfm3", .lanes = served, .context_window = @intCast(window), .prefill_step = chunk, .structures = true, .vision = null }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "lfm3", .lanes = served, .context_window = @intCast(window), .prefill_step = prompt_chunk, .structures = true, .vision = null }); + h.host.decoded_rows = warm_turns; + if (warm_turns) h.host.info_.prefill_min_chunk = 1; h.cache = null; var why: []const u8 = ""; const dev = model.device; @@ -110,12 +114,18 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.host.info_.prompt_cache_plan = plan; if (plan.budget_bytes > 0) { const S = q.backend.Snaps; + const rules: api.prompt_cache.Rules = if (warm_turns) + .{ .chunk = 1, .min_prompt = 0, .warm = .waits } + else + cacheRules(); h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = S.bytes, .save = S.save, .restore = S.restore, .drop = S.drop }, - }, cacheRules(), plan.budget_bytes); + }, rules, plan.budget_bytes); h.host.cache = &h.cache.?; h.host.info_.prompt_cache = true; + h.host.info_.warm_turns = warm_turns; + if (warm_turns) h.host.warm_quiet = 150 * std.time.ns_per_ms; } errdefer if (h.cache) |*store| store.deinit(); try mtl.resident.streams.hold(h, io, "lfm3"); diff --git a/zig/src/native/qwen27_draft.zig b/zig/src/native/qwen27_draft.zig index a030c8995bd..a92f7ef3f1b 100644 --- a/zig/src/native/qwen27_draft.zig +++ b/zig/src/native/qwen27_draft.zig @@ -70,6 +70,7 @@ pub const Draft = struct { defer pool.pop(); d.generation.deinit(); d.runner.capture_taps = d.previous_capture; + d.runner.taps.setFuser(d.runner.model.device, null) catch unreachable; // dropping a fuser allocates nothing d.runner.taps.ids = d.previous_taps; d.runner.taps.count = d.previous_count; d.model.backend.profile(null); // a borrowed drafter outlives the host and its trace diff --git a/zig/src/native/qwen27_keep.zig b/zig/src/native/qwen27_keep.zig index 75adc3ddb8a..005f6c1a647 100644 --- a/zig/src/native/qwen27_keep.zig +++ b/zig/src/native/qwen27_keep.zig @@ -42,7 +42,8 @@ const Commit = struct { const e = cb.compute(.concurrent); var ended = false; errdefer if (!ended) e.end(); - try g.commit.taps(e, ref, .{ .buf = r.taps.buffer }, .{ .buf = g.taps }, .{ .rows = rows, .width = r.taps.width, .capacity = r.taps.capacity, .planes = @intCast(r.taps.count) }); + const src = r.taps.source(); + try g.commit.taps(e, ref, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = rows, .width = src.width, .capacity = r.taps.capacity, .planes = src.planes }); try g.commit.head(e, ref, .{ .buf = logits.buffer, .off = logits.offset }, .{ .rows = rows, .width = vocab, .stride = vocab }); e.end(); ended = true; @@ -97,7 +98,8 @@ pub fn encodeTail(ptr: *anyopaque, e: mtl.ComputeEncoder) !void { const shape = try g.matcher.encode(e, .{ .buf = logits.buffer, .off = logits.offset }, b.round.?.ids, b.round.?.windows[0].parents, vocab, contract.max_rows, &.{}); const ref = tf.tree_commit_gpu.Ref{ .buf = g.matcher.buffers[4] }; try r.taps.complete(); - try g.commit.taps(e, ref, .{ .buf = r.taps.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = r.taps.width, .capacity = r.taps.capacity, .planes = @intCast(r.taps.count) }); + const src = r.taps.source(); + try g.commit.taps(e, ref, .{ .buf = src.buffer }, .{ .buf = g.taps }, .{ .rows = shape.rows, .width = src.width, .capacity = r.taps.capacity, .planes = src.planes }); const metric = mtl.pass_metrics.phase(.keep); defer metric.end(); std.debug.assert(b.prepared_keep == null); diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index d6a534466f2..43f840d7b98 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -95,6 +95,7 @@ pub const Metal = struct { standing: @import("qwen27_resume.zig").Standing = .{}, // what slot 0 stands at once its stream left (#1197) rewind: ?mtl.Buffer = null, // slot 0's DeltaNet states and taps at its last pass's history end slot_resume: bool = true, // TF_QWEN27_SLOT_RESUME: a later prompt resumes where slot 0 stands (0: off) + give_back: [max_streams]bool = @splat(false), // a free slot's grown K/V and ring wait to go back (slots.giveBack) draft_block: @import("qwen27_draft_block.zig").Lone = .{}, // TF_Q27_DFLASH_ADAPTIVE_BLOCK: a lone stream's block rows pub fn init(gpa: std.mem.Allocator, runner: *q.decode_round.Runner, draft: ?*Draft) !*Metal { @@ -123,7 +124,10 @@ pub const Metal = struct { if (draft) |d| { const g = d.model.ring(); b.gathered_taps = try device.buffer(batch_rows * g.stride, opts); - for (b.contexts[1..runner.ready], 1..) |*x, slot| x.* = try Context.init(gpa, d.model, slot < b.draft_slots); + for (b.contexts[1..runner.ready], 1..) |*x, slot| { + x.* = try Context.initGrow(gpa, d.model, slot < b.draft_slots, runner.kv_step); + x.*.?.settle = .{ .ctx = runner, .slot = @intCast(slot), .run = q.decode_round.Runner.settleOpaque }; + } } return b; } @@ -353,11 +357,12 @@ pub const Metal = struct { std.debug.assert(r.active == null); if (r.active != null) return error.RoundNotReady; try r.taps.complete(); - try q.tap_gather.gather(r.taps.buffer.contents()[0..r.taps.buffer.length()], r.taps.capacity, r.taps.rows, r.taps.width, r.taps.count, rows[0..n], out.contents()[0..out.length()]); + const src = r.taps.source(); + try q.tap_gather.gather(src.buffer.contents()[0..src.buffer.length()], r.taps.capacity, r.taps.rows, src.width, src.planes, rows[0..n], out.contents()[0..out.length()]); var at: usize = 0; for (paths, b.windows[0..b.count]) |path, slot| { const g = b.ringOf(slot).?; - if (g.stride != r.taps.width * r.taps.count * 2) return error.BadTapGather; + if (g.stride != @as(usize, src.width) * src.planes * 2) return error.BadTapGather; // a v1 ring: one fused plane if (b.early[slot] == 0) { try g.absorb(out, at * g.stride, @intCast(path.len)); at += path.len; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 1fc0e4bd164..e8bdc4f58e1 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -21,6 +21,10 @@ const disk = @import("qwen27_disk.zig"); const images = @import("qwen27_images.zig"); const Mtp = @import("qwen27_mtp.zig").Mtp; const Allocator = std.mem.Allocator; +const helpers = @import("qwen27_served_helpers.zig"); +const room = helpers.room; +const drafterRefusal = helpers.drafterRefusal; +const gibBytes = helpers.gibBytes; pub const Options = struct { context: u32, @@ -199,12 +203,6 @@ fn shareRoom(h: *const Host, why: *[]const u8) !u64 { return share_fit.room(cache_fit.ram(), cache_fit.footprint(), try laterFootprint(h), guards); } -/// Room left beside the weights and an 8 GiB margin. -fn room(model: *const q.model.Model) usize { - const dev = model.device; - return q.prompt_memory.room(dev.maxWorkingSet(), dev.allocated(), cap()) catch 0; -} - /// TF_QWEN27_WORKING_SET_BYTES: a development cap on the device's reported working set. const cap = reserve.cap; @@ -307,12 +305,6 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato return h; } -/// Why --drafter is refused before the target or the drafter loads. -fn drafterRefusal(a: Allocator, dir: []const u8, drafter: []const u8, err: anyerror) ![]const u8 { - if (err == error.DraftForAnotherTarget) return std.fmt.allocPrint(a, "--drafter {s} drafts for another target: its width, vocabulary or tapped layers do not fit {s} (DraftForAnotherTarget)", .{ drafter, dir }); - return std.fmt.allocPrint(a, "--drafter {s} is not a drafter the native Qwen engine serves for {s} ({s}): it takes z-lab/Qwen3.8-27B-DFlash2 as released, for Qwen3.8-27B", .{ drafter, dir, @errorName(err) }); -} - /// A loaded model served as `open` serves one, `drafter` bound in place of `o.drafter`; both stay the caller's. pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q.dflash.runtime_model.Model, o: Options, a: Allocator, why: *[]const u8) !*Host { const setup = tf.startup_receipt.span(.runtime_setup); @@ -344,7 +336,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q const gpa = if (profiling) h.counted.allocator() else parent; var draft_model = drafter; const owns_draft = drafter == null and o.drafter != null; - if (owns_draft) draft_model = q.dflash.runtime_model.Model.load(gpa, io, model, o.drafter.?, if (o.drafter_bits == 4) .prepared_q4_reference else .bf16_reference) catch |err| { + if (owns_draft) draft_model = q.dflash.runtime_model.Model.loadSpan(gpa, io, model, o.drafter.?, if (o.drafter_bits == 4) .prepared_q4_reference else .bf16_reference, capacity + window) catch |err| { why.* = try std.fmt.allocPrint(a, "the native Qwen3.8-27B drafter cannot load {s} ({s})", .{ o.drafter.?, @errorName(err) }); return error.DrafterLoad; }; @@ -355,7 +347,8 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q const shared = try q.simd_attention.sharedPrefix(model.device.tensorUnits()); // the MTP head's keys and values: one more attention layer a slot, beside the drafter's ring when there is one const head_kv: usize = if (mtp_on) @as(usize, capacity + window) * model.config.kvDim() * 2 * 2 else 0; - const fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + var fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + if (draft_model) |d| fit_prompt.tap_row = memory.tapRowBytes(model.config.hidden, d.graph.config.tap_count, d.graph.config.variant == .v1); const rows = try reserve.rows(fit_prompt, model.device.generation(), window); const slots = fit_prompt.streams(rows, o.streams_fixed) catch |err| { const dev = model.device; @@ -369,7 +362,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q model.frame.deinit(); model.frame = next; } - std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytes(model.config, capacity + window, slots, rows, shared, fit_prompt.ring, fit_prompt.planes) }); + std.log.info("qwen27: prompt capacity={d} rows, startup stream and scratch reserve={d} bytes", .{ rows, try memory.runnerBytesTaps(model.config, capacity + window, slots, rows, shared, fit_prompt.ring, if (fit_prompt.tap_row > 0) fit_prompt.tap_row else memory.tapRowBytes(model.config.hidden, fit_prompt.planes, false)) }); h.gpa = gpa; h.model = model; h.owns_model = false; @@ -378,8 +371,14 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.resident = null; h.disk_stage = null; h.vision = o.images; // closed with the host; a failed attach leaves it to the caller - h.trace = null; // TF_QWEN27_METAL_KV_PAGES=1: every slot's rows in pages; Fit charged each its window - h.runner = try if (try q.decode_round.pagesOn()) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initReady(gpa, model, slots, capacity + window, 1); + h.trace = null; + const paged = try q.decode_round.pagesOn(); + const kv_step = if (paged) null else q.kv_grow.step(@import("sys").environment.rawText("TF_Q27_KV_GROW")) catch |err| { + why.* = "TF_Q27_KV_GROW must be 0 (off) or a row count that is a multiple of 16"; + return err; + }; + h.runner = try if (paged) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initGrow(gpa, model, slots, capacity + window, 1, kv_step); + if (kv_step) |s| std.log.info("qwen27: K/V grows as used: a slot starts at {d} rows and grows by {d} or a quarter, up to {d}", .{ q.kv_grow.first(s, capacity + window), s, capacity + window }); errdefer h.runner.deinit(); if (profileEvery()) |every| { h.trace = .{ .queue = model.queue, .report_every = every }; // enabled once measure() has priced the windows @@ -393,6 +392,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.back.serial_copy_match = policy.serialCopyMatch(units, window, lanes_value); h.back.chunk = h.runner.promptRows(@min(rows, reserve.requested(model.device.generation(), model.config.moe()))); h.back.grow = .{ .ctx = h, .room = Host.roomFor, .added = Host.added }; + h.runner.grown = .{ .ctx = h, .added = Host.added }; h.back.vision = o.images; if (h.draft != null or mtp_on) try h.back.measure(io); h.mtp = null; @@ -411,7 +411,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.core = lanes.Engine.init(gpa, &h.cfg, if (h.wrap) |*w| w.backend() else h.back.backend(), h.clock.clock()); errdefer h.core.deinit(); const offer: ?api.Vision = if (o.images) |v| .{ .ctx = h, .prepare = Host.prepareImage, .image_token = v.c.image_token, .markers = &v.markers, .image_tokens = v.capacity, .max_images = v.max_images, .image_share = if (o.vision) |x| x.image_share else .request, .explain = tf.qwen_vl.geometry.problem } else null; - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .draft_sources = .{ .drafter = if (h.draft != null) .{ .kind = "DFlash2", .name = o.drafter_name orelse o.drafter orelse "" } else if (mtp_on) .{ .kind = "MTP", .name = q.gpu_weights.mtp_file } else null }, .structures = @import("qwen27_masks.zig").supported, .penalties = true, .lanes = slots, .context_window = capacity, .prefill_step = @intCast(h.back.chunk), .decode_share = o.decode_share, .vision = offer }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .draft_sources = .{ .drafter = if (h.draft) |d| .{ .kind = d.model.graph.config.kind(), .name = o.drafter_name orelse o.drafter orelse "" } else if (mtp_on) .{ .kind = "MTP", .name = q.gpu_weights.mtp_file } else null }, .structures = @import("qwen27_masks.zig").supported, .penalties = true, .lanes = slots, .context_window = capacity, .prefill_step = @intCast(h.back.chunk), .decode_share = o.decode_share, .vision = offer }); h.host.memory = .{ .ctx = h, .read = readMemory }; h.host.explain = .{ .text = words }; h.host.decoded_rows = true; // a reply's rows prefill with the bits decoding gave them, with the cache on or off @@ -447,10 +447,9 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (h.trace) |*t| t.enabled = true; // serving rounds count from here: measure() timed whole, unsplit buffers try h.host.start(); tf.startup_receipt.span(.model_ready).end(); - std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else 0, .images = o.images != null }}); + std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else 0, .drafter = if (h.draft) |d| d.model.graph.config.kind() else "DFlash2", .images = o.images != null }}); return h; } - test "qwen27 startup: draft stream count, singular text and optional suffixes" { const limit = try lb.draftSlots(); const limited = platform.c.getenv("TF_Q27_DRAFT_SLOTS") != null; @@ -504,11 +503,6 @@ fn laterRoom(h: *const Host) u64 { return share_fit.room(cache_fit.ram(), cache_fit.footprint(), laterFootprint(h) catch return 0, guards); } -/// --prompt-cache-gib's bytes (0 or less: none). -fn gibBytes(gib: f64) u64 { - return if (gib > 0) std.math.lossyCast(u64, gib * cache_fit.GiB) else 0; -} - /// Reserve later buffers and the loaded share's priced bytes that its construction left outside the footprint. fn laterFootprint(h: *const Host) !u64 { const tower: u64 = if (h.back.vision) |v| v.firstUse() else 0; diff --git a/zig/src/native/qwen27_served_helpers.zig b/zig/src/native/qwen27_served_helpers.zig new file mode 100644 index 00000000000..8d530d2b820 --- /dev/null +++ b/zig/src/native/qwen27_served_helpers.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const cache_fit = @import("cache_fit.zig"); +const reserve = @import("qwen27_reserve.zig"); + +/// Room left beside the weights and an 8 GiB margin. +pub fn room(model: *const q.model.Model) usize { + const dev = model.device; + return q.prompt_memory.room(dev.maxWorkingSet(), dev.allocated(), reserve.cap()) catch 0; +} + +/// Why --drafter is refused before the target or the drafter loads. +pub fn drafterRefusal(a: std.mem.Allocator, dir: []const u8, drafter: []const u8, err: anyerror) ![]const u8 { + if (err == error.DraftForAnotherTarget) return std.fmt.allocPrint(a, "--drafter {s} drafts for another target: its width, vocabulary or tapped layers do not fit {s} (DraftForAnotherTarget)", .{ drafter, dir }); + return std.fmt.allocPrint(a, "--drafter {s} is not a drafter the native Qwen engine serves for {s} ({s}): it takes z-lab/Qwen3.8-27B-DFlash2 as released for Qwen3.8-27B, or a DFlash drafter (DFlashDraftModel) made for this target", .{ drafter, dir, @errorName(err) }); +} + +/// --prompt-cache-gib's bytes (0 or less: none). +pub fn gibBytes(gib: f64) u64 { + return if (gib > 0) std.math.lossyCast(u64, gib * cache_fit.GiB) else 0; +} diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 05f231e67b6..f12947f6c93 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -43,6 +43,7 @@ pub fn opening(b: *Metal, s: *lanes.Stream, slot: u32) !Fill { if (resumed == 0) { if (d) |x| try x.reset() else try b.runner.reset(slot); try clearContext(b, slot); + try b.runner.admit(slot, @intCast(ids.len)); // a fresh pass: the slot takes its prompt's rows at once } s.cached = resumed; var at: usize = resumed; @@ -214,6 +215,7 @@ pub fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { /// A pass that failed or went back to the queue frees its slot, pages and promise (a standing slot 0's rows stay). fn drop(b: *Metal, slot: u32) void { + b.give_back[slot] = b.runner.kv_step != null; b.runner.release(slot, slot == 0 and b.standing.tokens.len > 0); b.owners[slot] = null; } @@ -410,7 +412,8 @@ pub fn ready(b: *Metal, slot: u32, s: *const lanes.Stream) !void { defer added.deinit(b.gpa); try added.appendSlice(b.gpa, try b.runner.ensure(slot)); if (context_missing) { - const x = try Context.init(b.gpa, b.draft.?.model, drafting); + const x = try Context.initGrow(b.gpa, b.draft.?.model, drafting, b.runner.kv_step); + x.settle = .{ .ctx = b.runner, .slot = slot, .run = q.decode_round.Runner.settleOpaque }; b.contexts[slot] = x; try x.buffers(&added, b.gpa); } @@ -419,8 +422,12 @@ pub fn ready(b: *Metal, slot: u32, s: *const lanes.Stream) !void { /// A drafter context's bytes: the taps ring, and K/V caches when the slot drafts. fn contextBytes(c: q.dflash.config.Config, drafting: bool) usize { - const ring = @as(usize, c.window) * c.tapWidth() * 2; - return ring + if (drafting) @as(usize, c.layers) * 2 * (@as(usize, c.window) + 16) * c.kvWidth() * 2 else 0; + const ring = @as(usize, c.span()) * c.ringWidth() * 2; + var caches: usize = 0; + if (drafting) for (0..c.layers) |i| { + caches += 2 * (@as(usize, c.layerWindow(i)) + 16) * c.kvWidth() * 2; + }; + return ring + caches; } /// A free slot for a new stream, slot 0 (the drafter's) first. @@ -450,10 +457,29 @@ pub fn unbind(b: *Metal, s: *lanes.Stream) void { var live: usize = 0; for (b.owners[0..b.runner.slots]) |owner| live += @intFromBool(owner != null); if (live <= 1) b.runner.trimBefore(); + b.give_back[slot] = b.runner.kv_step != null; + giveBack(b); +} + +/// Free, unread slots give back grown K/V and rings without waiting; slot 0 keeps what a next turn resumes from. +pub fn giveBack(b: *Metal) void { + for (0..b.runner.slots) |k| { + if (!b.give_back[k]) continue; + const slot: u32 = @intCast(k); + if (b.owners[k] != null) { + b.give_back[k] = false; + continue; + } + if ((slot == 0 and b.standing.tokens.len > 0) or b.runner.busy(slot)) continue; + b.give_back[k] = false; + b.runner.releaseGrown(slot) catch |err| std.log.warn("qwen27: slot {d} keeps its K/V ({s})", .{ slot, @errorName(err) }); + clearContext(b, slot) catch {}; + } } /// A promote unbind left for later, once no round is pending: a stream still in slot 0 or none to move ends it. pub fn promoteDue(b: *Metal) void { + giveBack(b); if (!b.promote_due or b.round != null) return; b.promote_due = false; promote(b); diff --git a/zig/src/native/qwen27_startup.zig b/zig/src/native/qwen27_startup.zig index c4bb22aa306..1a8421c5269 100644 --- a/zig/src/native/qwen27_startup.zig +++ b/zig/src/native/qwen27_startup.zig @@ -3,14 +3,19 @@ const std = @import("std"); /// The startup line's drafting clause: the smaller of `streams` and `draft_slots`, or "" when none draft. pub fn draftWording(buf: []u8, streams: u32, draft_slots: u32) ![]const u8 { + return draftWordingKind(buf, "DFlash2", streams, draft_slots); +} + +/// draftWording for a drafter named `kind` (config.kind(): DFlash for z-lab's v1 layout, DFlash2 for its successor). +pub fn draftWordingKind(buf: []u8, kind: []const u8, streams: u32, draft_slots: u32) ![]const u8 { const drafts = @min(streams, draft_slots); if (drafts == 0) return ""; if (drafts == streams) { - if (streams == 1) return "DFlash2 drafts for the only stream"; - if (streams == 2) return "DFlash2 drafts for both streams"; - return std.fmt.bufPrint(buf, "DFlash2 drafts for all {d} streams", .{streams}); + if (streams == 1) return std.fmt.bufPrint(buf, "{s} drafts for the only stream", .{kind}); + if (streams == 2) return std.fmt.bufPrint(buf, "{s} drafts for both streams", .{kind}); + return std.fmt.bufPrint(buf, "{s} drafts for all {d} streams", .{ kind, streams }); } - return std.fmt.bufPrint(buf, "DFlash2 drafts for {d} of {d} streams", .{ drafts, streams }); + return std.fmt.bufPrint(buf, "{s} drafts for {d} of {d} streams", .{ kind, drafts, streams }); } pub const StartupLine = struct { @@ -18,12 +23,22 @@ pub const StartupLine = struct { context: u32, draft_slots: u32, images: bool, + drafter: []const u8 = "DFlash2", // the drafter's name in the line (config.kind()) pub fn format(line: StartupLine, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.print("Qwen3.8-27B: {d} stream{s} of {d} tokens", .{ line.streams, if (line.streams == 1) "" else "s", line.context }); var wording: [64]u8 = undefined; - const drafting = draftWording(&wording, line.streams, line.draft_slots) catch return error.WriteFailed; + const drafting = draftWordingKind(&wording, line.drafter, line.streams, line.draft_slots) catch return error.WriteFailed; if (drafting.len > 0) try w.print(", {s}", .{drafting}); if (line.images) try w.writeAll(", images read"); } }; + +test "qwen27 startup: a v1 drafter's line names DFlash, a DFlash2 drafter's stays DFlash2" { + var buf: [96]u8 = undefined; + const v1 = try std.fmt.bufPrint(&buf, "{f}", .{StartupLine{ .streams = 2, .context = 4096, .draft_slots = 8, .images = false, .drafter = "DFlash" }}); + try std.testing.expectEqualStrings("Qwen3.8-27B: 2 streams of 4096 tokens, DFlash drafts for both streams", v1); + var two: [96]u8 = undefined; + const stock = try std.fmt.bufPrint(&two, "{f}", .{StartupLine{ .streams = 1, .context = 4096, .draft_slots = 8, .images = false }}); + try std.testing.expectEqualStrings("Qwen3.8-27B: 1 stream of 4096 tokens, DFlash2 drafts for the only stream", stock); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 37a6e68359f..e09a7fd7483 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -102,6 +102,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_HEAD_GEOMETRY", .scope = .metal, .kind = .size, .forms = "a whole nonnegative native-size geometry count" }, .{ .name = "TF_PROMPT_ROWS", .scope = .metal, .kind = .prompt, .forms = "a multiple of 16 from 128 to 2048 for native serving" }, .{ .name = "TF_ANE_COLUMNS", .scope = .metal, .kind = .u32, .forms = "a whole column count from 0 to 4294967295 (0 disables the share)" }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .scope = .metal, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_METAL4", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps Metal 3; 1 sends the work of a family that supports it through Metal 4 on macOS 26 and later, the default for DeepSeek-V4.1 there)" }, .{ .name = "TF_METAL4_TIMELINE", .scope = .metal, .kind = .u32, .forms = "a whole round count from 0 to 4294967295 (0, the default, stamps nothing; n stamps every stage of n rounds of each kind on a Metal 4 queue and logs them)" }, .{ .name = "TF_DSV41_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 logs DeepSeek-V4.1 Metal decode rounds' host and GPU milliseconds by rows)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 6f8286185e8..38f5cba9526 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -43,6 +43,8 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "1", .n = 1 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "0", .n = 0 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "1", .n = 1 }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "0", .n = 0 }, + .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "1", .n = 1 }, .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "0", .n = 0 }, .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .raw = "0", .n = 0 }, diff --git a/zig/src/qwen27_memory_test.zig b/zig/src/qwen27_memory_test.zig index 5fbd5181755..799e765d8bd 100644 --- a/zig/src/qwen27_memory_test.zig +++ b/zig/src/qwen27_memory_test.zig @@ -144,3 +144,127 @@ test "qwen27 memory: a refusal advises lowering parallel, the raise, or lowering try std.testing.expectEqualStrings(c.text, try std.fmt.bufPrint(&buf, "{f}", .{c.advice})); } } + +const kv_grow = @import("families/qwen27/kv_grow.zig"); + +test "qwen27 memory: grow-as-used K/V is off unless TF_Q27_KV_GROW names a 16-row step" { + try std.testing.expectEqual(@as(?u32, null), try kv_grow.step(null)); + try std.testing.expectEqual(@as(?u32, null), try kv_grow.step("0")); + try std.testing.expectEqual(@as(?u32, 4096), try kv_grow.step("4096")); + try std.testing.expectEqual(@as(?u32, 16), try kv_grow.step("16")); + for ([_][]const u8{ "", "-1", "15", "4097", "x", "99999999999" }) |text| try std.testing.expectError(error.BadKvGrowStep, kv_grow.step(text)); +} + +test "qwen27 memory: a slot starts at one step and grows to the need, a quarter more, or the context" { + // first rows: one step, never past the context + try std.testing.expectEqual(@as(u32, 4096), kv_grow.first(4096, 32784)); + try std.testing.expectEqual(@as(u32, 2000), kv_grow.first(4096, 2000)); + // enough already: unchanged + try std.testing.expectEqual(@as(u32, 4096), kv_grow.rows(4096, 4096, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 4096), kv_grow.rows(4096, 10, 4096, 32784)); + // the need rounded up to the step + try std.testing.expectEqual(@as(u32, 8192), kv_grow.rows(4096, 4097, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 32768), kv_grow.rows(4096, 30001, 4096, 32784)); + // a quarter more than held when that is past the rounded need + try std.testing.expectEqual(@as(u32, 20480), kv_grow.rows(16384, 16385, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 20480), kv_grow.rows(16384, 16385, 16, 32784)); + // never past the context + try std.testing.expectEqual(@as(u32, 32784), kv_grow.rows(32768, 32780, 4096, 32784)); + try std.testing.expectEqual(@as(u32, 32784), kv_grow.rows(28672, 28673, 4096, 32784)); +} + +test "qwen27 memory: an emptied slot takes its prompt's rows at once, at least one step, at most the context" { + try std.testing.expectEqual(@as(u32, 4096), kv_grow.admitted(1, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 4096), kv_grow.admitted(4096, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 8192), kv_grow.admitted(4097, 4096, 131088)); + // one growth for a 65,536-token prompt, where growing from the first rows takes ten + try std.testing.expectEqual(@as(u32, 65536), kv_grow.admitted(65536, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 131088), kv_grow.admitted(131080, 4096, 131088)); + try std.testing.expectEqual(@as(u32, 2000), kv_grow.admitted(64, 4096, 2000)); +} + +test "qwen27 memory: growing moves every K/V head to its place in the wider buffer" { + // 4 heads of dim 256 in bf16: head h starts at h * rows * 256 * 2 bytes + var moves: [4]kv_grow.Move = undefined; + const got = kv_grow.moves(&moves, 4, 256, 4096, 8192); + try std.testing.expectEqual(@as(usize, 4), got.len); + for (got, 0..) |m, h| { + try std.testing.expectEqual(h * 4096 * 256 * 2, m.from); + try std.testing.expectEqual(h * 8192 * 256 * 2, m.to); + try std.testing.expectEqual(@as(usize, 4096 * 256 * 2), m.len); + } + // the old buffer's bytes are exactly covered, the new head regions never overlap + try std.testing.expectEqual(@as(usize, 4 * 4096 * 256 * 2), got[3].from + got[3].len); + try std.testing.expect(got[2].to + got[2].len <= got[3].to); + // a slot's bytes at a row count, for the residency set and the memory receipts + try std.testing.expectEqual(@as(usize, 8 * 2 * 4096 * 1024 * 2), kv_grow.slotBytes(8, 1024, 4096)); +} + +const tap_ring = @import("families/qwen27/tap_ring.zig"); +const Ring = tap_ring.Ring; +const mtl_fake = @import("metal"); + +/// A ring that starts at `held` rows and grows by tap_ring.grow, as a parked slot's ring does. +const Growing = struct { + buf: mtl_fake.Buffer, + held: u32, + window: u32, + stride: usize, + asks: u32 = 0, + fn make(n: u32, stride: usize) !mtl_fake.Buffer { + const data = try std.testing.allocator.alignedAlloc(u8, .@"16", n * stride); + @memset(data, 0); + return .{ .id = n, .data = data }; + } + fn free(b: mtl_fake.Buffer) void { + std.testing.allocator.free(b.data); + } + fn run(ctx: *anyopaque, want: u32) anyerror!mtl_fake.Buffer { + const g: *Growing = @ptrCast(@alignCast(ctx)); + g.asks += 1; + if (want <= g.held) return g.buf; + const next = tap_ring.grownRows(g.held, want, 16, g.window); + const fresh = try make(next, g.stride); + tap_ring.carry(g.buf, fresh, g.held, g.stride); + free(g.buf); + g.buf = fresh; + g.held = next; + return fresh; + } +}; + +test "qwen27 memory: a growing taps ring holds the same rows at the same places as a whole-window ring" { + const window: u32 = 64; + const stride: usize = 4; + var whole_end: u64 = 0; + var grow_end: u64 = 0; + const whole_buf = try Growing.make(window, stride); + defer Growing.free(whole_buf); + var g = Growing{ .buf = try Growing.make(16, stride), .held = 16, .window = window, .stride = stride }; + defer Growing.free(g.buf); + const whole = Ring{ .buf = whole_buf, .end = &whole_end, .window = window, .stride = stride }; + var growing = Ring{ .buf = g.buf, .end = &grow_end, .window = window, .stride = stride, .grow = .{ .ctx = &g, .run = Growing.run } }; + const src = try Growing.make(128, stride); + defer Growing.free(src); + var next: u32 = 1; + for ([_]u32{ 5, 11, 1, 20, 30, 40 }) |n| { // past 16, 32 and the 64-row window: grows, then wraps + for (0..n) |i| std.mem.writeInt(u32, src.contents()[i * stride ..][0..4], next + @as(u32, @intCast(i)), .little); + next += n; + try whole.absorb(src, 0, n); + try growing.absorb(src, 0, n); + try std.testing.expectEqual(whole_end, grow_end); + const first = whole_end -| window; + for (first..whole_end) |pos| { + const at = (pos % window) * stride; + try std.testing.expectEqualSlices(u8, whole_buf.contents()[at..][0..stride], g.buf.contents()[at..][0..stride]); + } + } + try std.testing.expectEqual(window, g.held); // a wrapped ring holds the whole window + // a restore into the ring asks for its rows first; a held ring is not asked to grow + var restored = Ring{ .buf = g.buf, .end = &grow_end, .window = window, .stride = stride, .grow = .{ .ctx = &g, .run = Growing.run } }; + try restored.hold(200); + try std.testing.expectEqual(window, g.held); + try std.testing.expectEqual(@as(u32, 16), tap_ring.grownRows(16, 3, 16, 64)); + try std.testing.expectEqual(@as(u32, 48), tap_ring.grownRows(16, 33, 16, 64)); + try std.testing.expectEqual(@as(u32, 64), tap_ring.grownRows(48, 49, 16, 64)); +}