diff --git a/docs/environment-names.md b/docs/environment-names.md index b94cc61bb54..f6a120bcd40 100644 --- a/docs/environment-names.md +++ b/docs/environment-names.md @@ -571,6 +571,7 @@ reports the setting's own value, does not count as logging. | `TF_FLASHNEXT_SHARD_HEAD` | release, tool, test | other | | `TF_FLASHNEXT_SHARED_SIDE` | release, tool, test | other | | `TF_FLASHNEXT_SPLIT_DENSE` | release, tool, test | other | +| `TF_FLASHNEXT_STATE_PAGES` | release, tool, test | other | | `TF_FLASHNEXT_TABLE_WARM` | release, tool, test | other | | `TF_FLASHNEXT_TEMPERATURE` | release, tool, test | other | | `TF_FLASHNEXT_TOP_K` | release, tool, test | other | diff --git a/docs/environment.md b/docs/environment.md index 87d9fe2f296..1792fb988e4 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -273,6 +273,7 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_GATHER_EARLY` | Exactly `0` or `1`; default off. `1` gathers a shared pass's n-gram rows for every stream in one pool call, so the pass shares one distinct-row read and one set of parked readers; the rows, their order and every reply are the per-stream call's | | `TF_FLASHNEXT_PROFILE` | Exactly `0` or `1`; default off | | `TF_FLASHNEXT_VERIFY_HOST_LOGITS` | Exactly `0` or `1`; default off | +| `TF_FLASHNEXT_STATE_PAGES` | Exactly `0` or `1`; default off; `1` needs `TF_FLASHNEXT_KV_PAGES` | | `TF_FLASHNEXT_PREFILL_MTP_LEAN` | Exactly `0` or `1`; default off. For eligible lane-free prompt-only MTP rounds, `1` keeps only the KV/indexer caches, skips unread proposal work and graph capture, and bounds each prompt piece by 3,072 rows and one quarter of the admitted scratch capacity; capacity permitting, pieces remain wider than the default 256 rows | | `TF_FLASHNEXT_DRAFTS` | Whole draft count; default 6, then clamped to 1 through 15 | | `TF_FLASHNEXT_DRAFTS_GREEDY` | Whole draft count; default 8, then clamped to 1 through 15 | diff --git a/docs/profiles.md b/docs/profiles.md index ebf47c55bac..fbfb3cc200e 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -54,7 +54,8 @@ Coverage includes: dense/MoE, Flash Next, Kolibri-1, Gemma 4, Spark2.5, Dory, LFM2.5-24B-A2B, Muse Spark Open, Ripple, Inkling 2 Mini): `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS`, exact `1` only. -- Flash Next on CUDA: `TF_FLASHNEXT_KV_PAGES`, `TF_FLASHNEXT_KV_PAGES_ALL`. +- Flash Next on CUDA: `TF_FLASHNEXT_KV_PAGES`, `TF_FLASHNEXT_KV_PAGES_ALL`, `TF_FLASHNEXT_STATE_PAGES` (exact `1`, with + `TF_FLASHNEXT_KV_PAGES`). - Dory on CUDA: `TENSORFOLD_DORY_KV_PAGES`, full-attention caches in pool pages unless it is exactly `0`; unset, every stream's caches are contiguous and made at open. - Gemma 4 on CUDA: `TENSORFOLD_GEMMA4_KV_PAGES`, global caches in pool pages by default, where `0` keeps them linear. diff --git a/zig/src/core/kv_groups.zig b/zig/src/core/kv_groups.zig index 1c37387220b..6f0bbdc13f5 100644 --- a/zig/src/core/kv_groups.zig +++ b/zig/src/core/kv_groups.zig @@ -38,6 +38,18 @@ pub fn state(bytes: u64, page: u64) Fit { return .{ .rows = 0, .pages = n, .pad = n * page - bytes }; } +/// A stream's state as pieces on whole pages (kv_pieces.zig): how many, the pages they take, their bytes. +pub const Pieces = struct { + n: u32, + pages: u32, + bytes: u64, + + /// The bytes the pages hold past the pieces: alignment and the tail no piece fits. + pub fn pad(p: Pieces, page: u64) u64 { + return p.pages * page - p.bytes; + } +}; + /// What the load report reads: the pool's group and page, and the kinds beside it in or outside the pool. pub const Shape = struct { full: Group, @@ -45,6 +57,9 @@ pub const Shape = struct { page_rows: u32, window: ?Group = null, // rows outside the pool: a sliding window's rings run: u64 = 0, // a stream's state as a run of the pool's pages + pieces: ?Pieces = null, // a stream's state as pieces on any of the pool's pages + fixed: u64 = 0, // a lane's fixed part outside the pool, shown when `outside` > 0 + outside: u64 = 0, // of `fixed`, buffers wider than a page snap: u64 = 0, // a kept snapshot's slot outside the pool /// One layer's share of a page: the rows of the full group's layer a page holds. @@ -70,6 +85,8 @@ pub fn line(a: Allocator, s: Shape) ![]u8 { try rowsPart(o, g, s); } if (s.run > 0) try statePart(o, "state run, in the pool", s.run, page); + if (s.pieces) |p| try o.print("; state, in the pool as pieces: {d} pieces, {f} on {d} page{s} a lane, {f} padding ({d:.1} %)", .{ p.n, size(p.bytes), p.pages, if (p.pages == 1) "" else "s", size(p.pad(page)), pct(p.pad(page), p.pages * page) }); + if (s.outside > 0) try o.print("; a lane's fixed part, outside the pool and counted at admission: {f}, {f} of it buffers wider than a page", .{ size(s.fixed), size(s.outside) }); if (s.snap > 0) try statePart(o, "snapshot, outside the pool", s.snap, page); return w.toOwnedSlice(); } diff --git a/zig/src/core/kv_pieces.zig b/zig/src/core/kv_pieces.zig new file mode 100644 index 00000000000..8ae8d917c69 --- /dev/null +++ b/zig/src/core/kv_pieces.zig @@ -0,0 +1,107 @@ +//! A stream's state as pieces on whole pool pages: each piece inside one page, any pages, first-fit decreasing. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const groups = @import("kv_groups.zig"); + +/// Where a piece lies: its page among the stream's state pages (Lease.state), and its byte offset in that page. +pub const Place = struct { page: u32, offset: u64 }; + +/// Pieces placed on pages, in the caller's order; the same sizes and page always give the same map. +pub const Map = struct { + at: []Place, + sizes: []u64, + page: u64, + pages: u32, + + pub fn deinit(m: *Map, gpa: Allocator) void { + gpa.free(m.at); + gpa.free(m.sizes); + m.* = undefined; + } + + /// The pieces' count, pages and bytes, as the layout and the load report read them. + pub fn summary(m: Map) groups.Pieces { + var bytes: u64 = 0; + for (m.sizes) |n| bytes += n; + return .{ .n = @intCast(m.sizes.len), .pages = m.pages, .bytes = bytes }; + } + + /// Piece `i`'s device address: `ids` are the stream's state pages, `base` the pool's first page. + pub fn addr(m: Map, i: usize, base: u64, ids: []const u32) u64 { + return base + @as(u64, ids[m.at[i].page]) * m.page + m.at[i].offset; + } +}; + +/// `sizes` packed first-fit decreasing on pages of `page` bytes, each piece starting at a multiple of `alignment`. +pub fn pack(gpa: Allocator, sizes: []const u64, page: u64, alignment: u64) error{ PieceOverPage, OutOfMemory }!Map { + const order = try gpa.alloc(u32, sizes.len); + defer gpa.free(order); + for (order, 0..) |*o, i| o.* = @intCast(i); + const By = struct { + sizes: []const u64, + al: u64, + fn more(c: @This(), a: u32, b: u32) bool { + const x = std.mem.alignForward(u64, c.sizes[a], c.al); + const y = std.mem.alignForward(u64, c.sizes[b], c.al); + return x > y or (x == y and a < b); + } + }; + std.sort.pdq(u32, order, By{ .sizes = sizes, .al = alignment }, By.more); + const at = try gpa.alloc(Place, sizes.len); + errdefer gpa.free(at); + var used: std.ArrayList(u64) = .empty; // bytes taken on each page so far + defer used.deinit(gpa); + for (order) |i| { + const n = std.mem.alignForward(u64, sizes[i], alignment); + if (n > page) return error.PieceOverPage; + const k = for (used.items, 0..) |u, k| { + if (page - u >= n) break k; + } else blk: { + try used.append(gpa, 0); + break :blk used.items.len - 1; + }; + at[i] = .{ .page = @intCast(k), .offset = used.items[k] }; + used.items[k] += n; + } + const own = try gpa.dupe(u64, sizes); + return .{ .at = at, .sizes = own, .page = page, .pages = @intCast(used.items.len) }; +} + +/// Every piece inside one page of the map's and no two overlapping; a wrong map is refused by name. +pub fn check(gpa: Allocator, m: Map) error{ PieceOverPage, PiecesOverlap, OutOfMemory }!void { + const order = try gpa.alloc(u32, m.at.len); + defer gpa.free(order); + for (order, 0..) |*o, i| { + o.* = @intCast(i); + if (m.at[i].page >= m.pages or m.at[i].offset + m.sizes[i] > m.page) return error.PieceOverPage; + } + const By = struct { + at: []const Place, + fn less(c: @This(), a: u32, b: u32) bool { + const x = c.at[a]; + const y = c.at[b]; + return x.page < y.page or (x.page == y.page and x.offset < y.offset); + } + }; + std.sort.pdq(u32, order, By{ .at = m.at }, By.less); + for (order[0..order.len -| 1], order[@min(1, order.len)..]) |a, b| { + const x = m.at[a]; + const y = m.at[b]; + if (x.page == y.page and x.offset + m.sizes[a] > y.offset) return error.PiecesOverlap; + } +} + +test { + _ = @import("kv_pieces_test.zig"); +} + +/// The n-th highest of distinct `ids` (n <= ids.len), so the n highest are those at or above it; maxInt for n = 0. +pub fn nthHighest(ids: []const u32, n: usize) u32 { + var cut: u32 = std.math.maxInt(u32); + for (0..n) |_| { + var best: u32 = 0; + for (ids) |id| best = if (id < cut and id >= best) id else best; + cut = best; + } + return cut; +} diff --git a/zig/src/core/kv_pieces_test.zig b/zig/src/core/kv_pieces_test.zig new file mode 100644 index 00000000000..06600bd9325 --- /dev/null +++ b/zig/src/core/kv_pieces_test.zig @@ -0,0 +1,103 @@ +//! The packer on Flash Next's sizes (256-row pages with its MTP head): page counts, checks and refusals. +const std = @import("std"); +const pieces = @import("kv_pieces.zig"); +const t = std.testing; +const gpa = t.allocator; + +// Flash Next's state and draft pieces, whole layers: recurrence, conv tail, MTP tail and projection, a page head +const rec: u64 = 48 * 128 * 128 * 4; +const conv: u64 = 3 * 10240 * 2; +const tail: u64 = 9 * 4 * 2560 * 2; +const proj: u64 = 32 * 16480 * 2; +const page_head: u64 = 256 * (2 * 2 * 256 * 2 + 128 * 2) * 13 + 64 * 128 * 2 * 13; + +fn flashNext(late: bool) !std.ArrayList(u64) { + var s: std.ArrayList(u64) = .empty; + errdefer s.deinit(gpa); + try s.appendNTimes(gpa, rec, 36); + try s.appendNTimes(gpa, conv, 36); + try s.append(gpa, tail); + try s.appendNTimes(gpa, rec, 36); // spares + try s.appendNTimes(gpa, conv, 36); // saved conv windows + try s.appendNTimes(gpa, proj, 36); // saved projection rows + try s.appendSlice(gpa, &.{ tail, 32 * 4 * 2560 * 2, 4 * 2560 * 2, 32768 * 2, 32 * 16 + 32 * 64 * 6 }); + if (late) { + try s.append(gpa, 256); + try s.appendNTimes(gpa, 48 * (16 * 128 + 48 * 128 + 48 * 2) * 4, 36); + } + return s; +} + +test "Flash Next at 256-row pages with its head: pages and pieces as counted by hand, every piece inside one page" { + try t.expectEqual(@as(u64, 7_880_704), page_head); + for ([_]bool{ false, true }, [_]u32{ 37, 45 }, [_]u32{ 186, 223 }) |late, pages, n| { + var s = try flashNext(late); + defer s.deinit(gpa); + var m = try pieces.pack(gpa, s.items, page_head, 256); + defer m.deinit(gpa); + try pieces.check(gpa, m); + const sum = m.summary(); + try t.expectEqual(n, sum.n); + try t.expectEqual(pages, sum.pages); + for (m.at) |p| try t.expectEqual(@as(u64, 0), p.offset % 256); + } + var s = try flashNext(false); + defer s.deinit(gpa); + var state = try pieces.pack(gpa, s.items[0..73], page_head, 256); // the stream's own state alone + defer state.deinit(gpa); + try t.expectEqual(@as(u32, 18), state.pages); + var all = try pieces.pack(gpa, s.items, page_head, 256); + defer all.deinit(gpa); + try t.expectEqual(@as(u64, 21_577_216), all.summary().pad(page_head)); +} + +test "packing is deterministic: the same sizes give the same places, piece order kept" { + var s = try flashNext(true); + defer s.deinit(gpa); + var a = try pieces.pack(gpa, s.items, page_head, 256); + defer a.deinit(gpa); + var b = try pieces.pack(gpa, s.items, page_head, 256); + defer b.deinit(gpa); + try t.expectEqualSlices(pieces.Place, a.at, b.at); + try t.expectEqualSlices(u64, s.items, a.sizes); + var ids: [45]u32 = undefined; + for (&ids, 0..) |*id, k| id.* = @intCast(90 - 2 * k); // any pages, in any order + for (a.at, 0..) |p, i| try t.expectEqual(0x1000 + @as(u64, ids[p.page]) * page_head + p.offset, a.addr(i, 0x1000, &ids)); +} + +test "a piece wider than a page is refused by name, and an empty list takes no page" { + try t.expectError(error.PieceOverPage, pieces.pack(gpa, &.{ 10, 4097 }, 4096, 256)); + try t.expectError(error.PieceOverPage, pieces.pack(gpa, &.{4000}, 4096, 256 * 64)); // aligned past the page + var m = try pieces.pack(gpa, &.{}, 4096, 256); + defer m.deinit(gpa); + try t.expectEqual(@as(u32, 0), m.pages); + try pieces.check(gpa, m); +} + +test "first fit decreasing: small pieces fill the larger ones' gaps, ties in the caller's order" { + var m = try pieces.pack(gpa, &.{ 100, 3000, 3000, 700, 1000 }, 4096, 256); + defer m.deinit(gpa); + try t.expectEqual(@as(u32, 2), m.pages); + try t.expectEqual(pieces.Place{ .page = 0, .offset = 0 }, m.at[1]); + try t.expectEqual(pieces.Place{ .page = 1, .offset = 0 }, m.at[2]); + try t.expectEqual(pieces.Place{ .page = 0, .offset = 3072 }, m.at[4]); + try t.expectEqual(pieces.Place{ .page = 1, .offset = 3072 }, m.at[3]); + try t.expectEqual(pieces.Place{ .page = 1, .offset = 3840 }, m.at[0]); + try pieces.check(gpa, m); + try t.expectEqual(@as(u64, 2 * 4096 - 7800), m.summary().pad(4096)); +} + +test "a wrong map is refused: two pieces overlapping, a piece past its page or past the map's pages" { + var m = try pieces.pack(gpa, &.{ 1000, 1000, 1000 }, 4096, 256); + defer m.deinit(gpa); + try pieces.check(gpa, m); + const keep = m.at[1]; + m.at[1].offset = m.at[0].offset + 512; + try t.expectError(error.PiecesOverlap, pieces.check(gpa, m)); + m.at[1] = .{ .page = 0, .offset = 3584 }; + try t.expectError(error.PieceOverPage, pieces.check(gpa, m)); + m.at[1] = .{ .page = 1, .offset = 0 }; + try t.expectError(error.PieceOverPage, pieces.check(gpa, m)); + m.at[1] = keep; + try pieces.check(gpa, m); +} diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index 298c5da1461..719e71d4848 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -3,10 +3,11 @@ const std = @import("std"); const Allocator = std.mem.Allocator; pub const groups = @import("kv_groups.zig"); pub const retirement = @import("kv_pool_retire.zig"); - +pub const pieces = @import("kv_pieces.zig"); test { _ = @import("kv_groups_test.zig"); _ = @import("kv_pool_trim_cost_test.zig"); + _ = pieces; } /// A family's stream memory: a fixed part at any length, paged caches a token, and a kept snapshot's slot. @@ -21,6 +22,10 @@ pub const Layout = struct { snap_bytes: u64, /// Bytes a running stream takes from the pages beside its keys and values, as one run of whole pages (0: none). run_bytes: u64 = 0, + /// A running stream's state as pieces on any whole pages of its lease (kv_pieces), in place of a run. + pieces: ?groups.Pieces = null, + /// Of `fixed_bytes`, buffers wider than a page each stream holds outside the pool (the load report shows them). + outside: u64 = 0, /// Layers `token_bytes` spans, so a row is token_bytes / full_layers in each (0: not named, one row a token). full_layers: u32 = 0, /// A sliding window's rows outside the pool, by bytes a row a layer (null: none, or not named). @@ -39,7 +44,7 @@ pub const Layout = struct { /// The groups the load report shows: the pool's, the window outside it, the state run and a snapshot slot. pub fn shape(l: Layout) groups.Shape { - return .{ .full = l.group(), .named = l.full_layers > 0, .page_rows = l.page_tokens, .window = l.window, .run = l.run_bytes, .snap = l.snap_bytes }; + return .{ .full = l.group(), .named = l.full_layers > 0, .page_rows = l.page_tokens, .window = l.window, .run = l.run_bytes, .pieces = l.pieces, .fixed = l.fixed_bytes, .outside = l.outside, .snap = l.snap_bytes }; } pub fn pageBytes(l: Layout) u64 { @@ -51,9 +56,14 @@ pub const Layout = struct { return @intCast((tokens + l.page_tokens - 1) / l.page_tokens); } - /// Pages a request reserves at admission: its prompt, its reply and one last verify window, and its run. + /// Pages a request reserves at admission: its prompt, its reply and one last verify window, and its state. pub fn need(l: Layout, prompt: u64, max_tokens: u64, window: u64) usize { - return l.pages(prompt + max_tokens + window) + l.runPages(); + return l.pages(prompt + max_tokens + window) + l.statePages(); + } + + /// Pages a running stream's state takes beside its keys and values: its pieces' pages, else its run's. + pub fn statePages(l: Layout) usize { + return if (l.pieces) |p| p.pages else l.runPages(); } /// Consecutive pages a running stream's `run_bytes` take. @@ -129,7 +139,7 @@ pub fn plan(l: Layout, b: Budget) error{ NoStream, TooMany }!Plan { if (b.engine + own > b.room or b.lanes == 0) return error.NoStream; var left = b.room - b.engine - own; const extra: u64 = b.lanes - 1; - const each = l.fixed_bytes + (1 + l.runPages()) * l.pageBytes(); + const each = l.fixed_bytes + (1 + l.statePages()) * l.pageBytes(); const fit = @min(extra, left / each); if (fit < extra and b.fixed) return error.TooMany; left -= fit * l.fixed_bytes; @@ -140,7 +150,7 @@ pub fn plan(l: Layout, b: Budget) error{ NoStream, TooMany }!Plan { const kept = if (b.slots_only) cache - split(cache, l.snap_bytes, b.snaps).snaps * l.snap_bytes else cache / 1_000_000 * b.kept_ppm + cache % 1_000_000 * b.kept_ppm / 1_000_000; // the cache's share as pages const c = split(cache - kept, l.snap_bytes, b.snaps); left -= c.snaps * l.snap_bytes + c.copied; - const most: u64 = if (b.window > 0) (fit + @intFromBool(b.engine_paged)) * l.pages(b.window) + fit * l.runPages() + kept / l.pageBytes() else std.math.maxInt(u64); + const most: u64 = if (b.window > 0) (fit + @intFromBool(b.engine_paged)) * l.pages(b.window) + fit * l.statePages() + kept / l.pageBytes() else std.math.maxInt(u64); return .{ .lanes = @intCast(1 + fit), .snaps = c.snaps, .copied = c.copied, .pages = @intCast(@min((left + own) / l.pageBytes(), most)), .kept = kept, .taken = taken }; } @@ -149,7 +159,7 @@ pub fn holds(l: Layout, b: Budget) bool { const own = ownPages(l, b); if (b.engine + own > b.room or b.lanes == 0) return false; const left = b.room - b.engine - own; - const each = l.fixed_bytes + (1 + l.runPages()) * l.pageBytes(); + const each = l.fixed_bytes + (1 + l.statePages()) * l.pageBytes(); const fit = @min(@as(u64, b.lanes - 1), left / each); const rest = left - fit * l.fixed_bytes; // what the cache and the pages share, as in plan return rest -| held(l, b, fit, windows(l, b, rest) - 1) >= b.cache; @@ -170,7 +180,7 @@ pub fn holding(l: Layout, b: Budget, n: usize) struct { gib: ?u64, most: usize } /// The pages the cache leaves the other streams: a page and a run each, or `more` windows if those are more. fn held(l: Layout, b: Budget, fit: u64, more: u64) u64 { - return @max(fit * (1 + l.runPages()), more * l.pages(b.window)) * l.pageBytes(); + return @max(fit * (1 + l.statePages()), more * l.pages(b.window)) * l.pageBytes(); } /// Windows set aside before the cache, the engine's own among them: as many as the room holds and `rest` holds whole. @@ -186,10 +196,11 @@ fn ownPages(l: Layout, b: Budget) u64 { return if (b.engine_paged) l.pages(b.window) * l.pageBytes() else 0; } -/// A stream's reservation: pages promised but not yet taken, and the pages it holds in token order (its table). +/// A stream's reservation: pages promised not taken, its table's pages in token order, its state's pages (takeState). pub const Lease = struct { promised: usize = 0, ids: std.ArrayList(u32) = .empty, + state: std.ArrayList(u32) = .empty, }; /// Where a stream's page table goes on the device: `ids[from..]` written at entry `from`. @@ -302,7 +313,7 @@ pub const Pool = struct { } /// Ownership changes update page classes once; holders and leases remain the authoritative per-page state. - fn ownership(p: *Pool, id: usize, refs: u32, leased: u32) void { + pub fn ownership(p: *Pool, id: usize, refs: u32, leased: u32) void { const r = p.refs[id]; const l = p.leased[id]; p.nreclaimable = p.nreclaimable - @intFromBool(r == 1 and l == 0) + @intFromBool(refs == 1 and leased == 0); @@ -420,6 +431,8 @@ pub const Pool = struct { return id; } + pub const takeState = @import("kv_pool_take_state.zig").takeState; + /// Pages a store's resume retained for this stream (its matched path), at the head of its table. pub fn adopt(p: *Pool, l: *Lease, ids: []const u32) error{OutOfMemory}!void { p.enter(); @@ -560,7 +573,9 @@ pub const Pool = struct { defer p.leave(); p.unpromise(l); for (l.ids.items) |id| if (id != retirement.none) p.unlease(id); + for (l.state.items) |id| p.unlease(id); l.ids.deinit(p.gpa); + l.state.deinit(p.gpa); l.* = .{}; } }; @@ -577,4 +592,5 @@ test { _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); _ = @import("kv_reclaim_test.zig"); + _ = @import("kv_pool_state_test.zig"); } diff --git a/zig/src/core/kv_pool_state_test.zig b/zig/src/core/kv_pool_state_test.zig new file mode 100644 index 00000000000..429f151f97e --- /dev/null +++ b/zig/src/core/kv_pool_state_test.zig @@ -0,0 +1,150 @@ +//! State pieces on any pages of a lease: admitted and counted, fragmentation, failures, the load report's pad. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const t = std.testing; + +const mib: u64 = 1 << 20; + +/// A run of 10 pages, or the same state as 37 pieces on 10 pages (page 4 MiB, 64 KiB a token). +const run: kv.Layout = .{ .fixed_bytes = 64 * mib, .token_bytes = 64 << 10, .page_tokens = 64, .snap_bytes = 0, .run_bytes = 10 * 4 * mib - 1 }; +const pieced: kv.Layout = .{ .fixed_bytes = 64 * mib, .token_bytes = 64 << 10, .page_tokens = 64, .snap_bytes = 0, .pieces = .{ .n = 37, .pages = 10, .bytes = 36 * mib } }; + +test "pieces count as their pages wherever a run counted: need, plan, holds" { + try t.expectEqual(@as(usize, 10), pieced.statePages()); + try t.expectEqual(@as(usize, 10), run.statePages()); + try t.expectEqual(run.need(2048, 4096, 16), pieced.need(2048, 4096, 16)); + const g: u64 = 1 << 30; + for ([_]kv.Budget{ + .{ .room = 40 * g, .engine = g, .lanes = 4, .window = 16384 + 16 }, + .{ .room = 2 * g + 2 * (64 * mib + 11 * 4 * mib) + mib, .engine = 2 * g, .lanes = 8 }, + .{ .room = 40 * g, .engine = g, .lanes = 4, .cache = 2 * g, .window = 8192, .engine_paged = true }, + }) |b| { + try t.expectEqual(try kv.plan(run, b), try kv.plan(pieced, b)); + try t.expectEqual(kv.holds(run, b), kv.holds(pieced, b)); + } + var fewer = pieced; + fewer.pieces.?.pages = 9; + try t.expectEqual(run.need(1, 0, 0) - 1, fewer.need(1, 0, 0)); +} + +test "a lane's fixed part counts at admission: more of it outside the pool admits fewer streams" { + const g: u64 = 1 << 30; + const b: kv.Budget = .{ .room = 2 * g + 3 * (64 * mib + 11 * 4 * mib) + mib, .engine = 2 * g, .lanes = 8 }; + try t.expectEqual(@as(u32, 4), (try kv.plan(pieced, b)).lanes); + var wide = pieced; + wide.fixed_bytes += 48 * mib; + wide.outside = 48 * mib; + try t.expectEqual(@as(u32, 3), (try kv.plan(wide, b)).lanes); +} + +test "takeState holds any free pages from the promise; finish gives them back with the table's" { + var p = try kv.Pool.init(t.allocator, 16, 4096); + defer p.deinit(); + const load = p.census(); + var l: kv.Lease = .{}; + try p.promise(&l, 7); + try p.takeState(&l, 4); + try p.cover(&l, 2, null); + try t.expectEqual(@as(usize, 4), l.state.items.len); + try t.expectEqual(@as(usize, 1), l.promised); + try t.expectEqual(@as(usize, 6), p.census().leased); + try t.expectEqual(@as(usize, 0), p.reclaimable()); // a state page is never the store's to reclaim + for (l.state.items) |id| try t.expectEqual(@as(u32, 1), p.holders(id)); + try t.expectError(error.PastReservation, p.takeState(&l, 2)); + try t.expectEqual(@as(usize, 1), l.promised); + p.finish(&l); + try t.expectEqual(load, p.census()); + try t.expect(p.idle()); +} + +test "fragmentation: no two free pages side by side, a run is refused, the same state as pieces admits" { + var p = try kv.Pool.init(t.allocator, 8, 4096); + defer p.deinit(); + var all: [8]u32 = undefined; + try t.expect(p.hold(&all)); + for ([_]u32{ 1, 3, 5, 7 }) |id| try p.drop(id); // the store keeps every other page + var a: kv.Lease = .{}; + try p.promise(&a, 4); + try t.expectEqual(@as(?u32, null), p.claimRun(&a, 2)); // today's run: LaneMemory + try p.takeState(&a, 4); + try t.expectEqual(@as(usize, 0), p.available()); + var got = a.state.items[0..4].*; + std.mem.sort(u32, &got, {}, std.sort.asc(u32)); + try t.expectEqualSlices(u32, &.{ 1, 3, 5, 7 }, &got); + p.finish(&a); + for ([_]u32{ 0, 2, 4, 6 }) |id| try p.drop(id); + try t.expect(p.idle()); +} + +test "LEAK: a failed state allocation, a cancel after open and a failed table write leave the pool as at load" { + var p = try kv.Pool.init(t.allocator, 16, 4096); + defer p.deinit(); + const load = p.census(); + var fail = std.testing.FailingAllocator.init(t.allocator, .{ .fail_index = 0 }); + const keep = p.gpa; + p.gpa = fail.allocator(); + var l: kv.Lease = .{}; + try p.promise(&l, 6); + try t.expectError(error.OutOfMemory, p.takeState(&l, 4)); + try t.expectEqual(@as(usize, 6), l.promised); // nothing taken + p.finish(&l); + p.gpa = keep; + try t.expectEqual(load, p.census()); + try p.promise(&l, 6); + try p.takeState(&l, 4); + p.finish(&l); // cancelled after open + try t.expectEqual(load, p.census()); + const Bad = struct { + fn write(_: *anyopaque, _: []const u32, _: usize) anyerror!void { + return error.Upload; + } + }; + var ctx: u8 = 0; + try p.promise(&l, 6); + try p.takeState(&l, 4); + try t.expectError(error.Upload, p.cover(&l, 2, .{ .ctx = &ctx, .write = Bad.write })); + try t.expectEqual(@as(usize, 0), l.ids.items.len); + p.finish(&l); + try t.expectEqual(load, p.census()); + try t.expect(p.idle()); +} + +test "the load report shows a lane's pieces, their pages and pad, and its fixed part outside the pool" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var l = pieced; + l.outside = 48 * mib; + l.fixed_bytes += 48 * mib; + const shown = try kv.groups.line(arena.allocator(), l.shape()); + const want = "KV page groups: one page 4.00 MiB, 64 rows of the full group; full: layers not named, 64.00 KiB a token, " ++ + "64 rows a page, 0 B padding (0.0 %); state, in the pool as pieces: 37 pieces, 36.00 MiB on 10 pages a lane, " ++ + "4.00 MiB padding (10.0 %); a lane's fixed part, outside the pool and counted at admission: 112.00 MiB, " ++ + "48.00 MiB of it buffers wider than a page"; + try t.expectEqualStrings(want, shown); + const plain = try kv.groups.line(arena.allocator(), run.shape()); // no pieces, nothing outside: today's line + try t.expect(std.mem.indexOf(u8, plain, "pieces") == null and std.mem.indexOf(u8, plain, "fixed part") == null); +} + +test "takeState takes the highest free ids and keeps the free stack's order, so table pages still come from the bottom" { + var p = try kv.Pool.init(t.allocator, 12, 4096); + defer p.deinit(); + var a: kv.Lease = .{}; + try p.promise(&a, 5); + try p.takeState(&a, 3); + try t.expectEqualSlices(u32, &.{ 11, 10, 9 }, a.state.items); + var b: kv.Lease = .{}; + try p.promise(&b, 4); + try p.takeState(&b, 2); + try t.expectEqualSlices(u32, &.{ 8, 7 }, b.state.items); + const Ok = struct { + fn write(_: *anyopaque, _: []const u32, _: usize) anyerror!void {} + }; + var ctx: u8 = 0; + try p.cover(&a, 2, .{ .ctx = &ctx, .write = Ok.write }); + try p.cover(&b, 2, .{ .ctx = &ctx, .write = Ok.write }); + try t.expectEqualSlices(u32, &.{ 0, 1 }, a.ids.items); + try t.expectEqualSlices(u32, &.{ 2, 3 }, b.ids.items); + p.finish(&a); + p.finish(&b); + try t.expect(p.idle()); +} diff --git a/zig/src/core/kv_pool_take_state.zig b/zig/src/core/kv_pool_take_state.zig new file mode 100644 index 00000000000..9a2e1c4fb28 --- /dev/null +++ b/zig/src/core/kv_pool_take_state.zig @@ -0,0 +1,25 @@ +//! Pool.takeState: a running stream's state pages (kv_pieces), kept apart so kv_pool.zig stays within 600 lines. +const kv = @import("kv_pool.zig"); +const Pool = kv.Pool; +const Lease = kv.Lease; +const pieces = @import("kv_pieces.zig"); + +/// `n` pages from `l`'s promise for its state, held until `finish`: the highest free ids: KV pages stay together. +pub fn takeState(p: *Pool, l: *Lease, n: usize) error{ PastReservation, OutOfMemory }!void { + p.enter(); + defer p.leave(); + if (l.promised < n) return error.PastReservation; + try l.state.ensureUnusedCapacity(p.gpa, n); + const cut = pieces.nthHighest(p.free[0..p.nfree], n); + var kept: usize = 0; + for (p.free[0..p.nfree]) |id| if (id >= cut) { + p.ownership(id, 1, 1); // held as a lease holds its pages: never the store's to reclaim + l.state.appendAssumeCapacity(id); + } else { + p.free[kept] = id; + kept += 1; + }; + p.nfree = kept; + l.promised -= n; + p.promised -= n; +} diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 7df3d132830..4ce7edc81d4 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -26,6 +26,7 @@ pub const Switch = enum { TF_KV_PAGE_DISK, TF_FLASHNEXT_KV_PAGES, TF_FLASHNEXT_KV_PAGES_ALL, + TF_FLASHNEXT_STATE_PAGES, TF_KV_PAGES, TF_GLM_KV_HOST, TF_GLM_KV_HOST_SHARED, @@ -182,6 +183,7 @@ pub const entries = [_]Entry{ .{ .id = .TF_KV_SHARE, .families = &.{ "gemma4", "gemma4_unified", "kolibri1", "spark2_5", "glm5_next", "glm_moe_dsa", "dory", "hy_v4_flash" }, .class = .identical, .effect = "Keep prompt states over the core KV pool", .evidence = "#1657" }, .{ .id = .TF_FLASHNEXT_KV_PAGES, .families = flash, .class = .experimental, .effect = "KV pool page size; no profile qualifies it yet", .evidence = "#1660" }, .{ .id = .TF_FLASHNEXT_KV_PAGES_ALL, .families = flash, .class = .debug, .syntax = .one, .effect = "Put every stream on pool pages for checks", .evidence = "#1660" }, + .{ .id = .TF_FLASHNEXT_STATE_PAGES, .families = flash, .class = .identical, .syntax = .one, .effect = "Pool lanes keep states and draft buffers as pieces on any pages, no run", .evidence = "#2444" }, .{ .id = .TF_KV_PAGES, .families = glm, .class = .identical, .syntax = .auto, .effect = "GLM KV pool pages; auto from two ranks with BF16, windows with FP8", .evidence = "#1322" }, .{ .id = .TF_KV_PAGES, .families = &.{ "nemotron_h", "nemotron_h_omni" }, .class = .identical, .report_values = &.{ "0", "all" }, .effect = "Nemotron KV pool pages by default; exact 0 disables, exact all pages every stream", .evidence = "#781" }, .{ .id = .TF_GLM_KV_HOST, .families = glm, .class = .identical, .syntax = .one, .effect = "Keep the DSA layers' latent rows on pinned host pages", .evidence = "#1795" }, diff --git a/zig/src/families/flashnext/cuda_kv_init_test.zig b/zig/src/families/flashnext/cuda_kv_init_test.zig index baac3c44830..80dc5f7c06c 100644 --- a/zig/src/families/flashnext/cuda_kv_init_test.zig +++ b/zig/src/families/flashnext/cuda_kv_init_test.zig @@ -239,6 +239,27 @@ const Slow = struct { fn streamDestroy(_: cuda.abi.Stream) callconv(.c) cuda.abi.Result { return 0; } + /// `pool`'s arena as `mapped.len` pieces, none mapped, through this VMM; counts from zero. + fn lazy(s: *@import("cuda_kv_arena.zig").Arena.Pieces, pool: *pages.Pool, mapped: []bool) void { + const piece = @import("cuda_kv_arena.zig").piece_bytes; + s.vmm.va = pool.arena.buf.ptr; + s.vmm.va_len = mapped.len * piece; + s.vmm.next = s.vmm.va; + s.vmm.granularity = 2 << 20; + s.vmm.device = 0; + s.vmm.prop = .{}; + s.vmm.failed = null; + s.vmm.api.create = create; + s.vmm.api.release = ok64; + s.vmm.api.map = map; + s.vmm.api.unmap = unmap; + s.vmm.api.setAccess = @ptrCast(&access); + s.lazy = .{ .base = pool.arena.buf.ptr, .len = pool.arena.buf.len, .piece = piece, .mapped = mapped }; + pool.arena.pieces = s; + caller = std.Thread.getCurrentId(); + on_caller.store(0, .monotonic); + created.store(0, .monotonic); + } }; test "kv safety: Flash Next open into unmapped pieces beside a running stream waits for the arena's thread, not on a map" { @@ -261,24 +282,8 @@ test "kv safety: Flash Next open into unmapped pieces beside a running stream wa pool.arena.pieces = null; pool.deinit(); }; - s.vmm.va = pool.arena.buf.ptr; - s.vmm.va_len = 6 * arena.piece_bytes; - s.vmm.next = s.vmm.va; - s.vmm.granularity = 2 << 20; - s.vmm.device = 0; - s.vmm.prop = .{}; - s.vmm.failed = null; - s.vmm.api.create = Slow.create; - s.vmm.api.release = Slow.ok64; - s.vmm.api.map = Slow.map; - s.vmm.api.unmap = Slow.unmap; - s.vmm.api.setAccess = @ptrCast(&Slow.access); var mapped: [6]bool = @splat(false); - s.lazy = .{ .base = pool.arena.buf.ptr, .len = pool.arena.buf.len, .piece = arena.piece_bytes, .mapped = &mapped }; - pool.arena.pieces = &s; - Slow.caller = std.Thread.getCurrentId(); - Slow.on_caller.store(0, .monotonic); - Slow.created.store(0, .monotonic); + Slow.lazy(&s, pool, &mapped); // alone: no stream can wait, so nothing is posted and the open maps on its own thread, as before try std.testing.expect(!pool.waits(320, false)); @@ -372,3 +377,61 @@ test "the window's waits: off, a request near a page boundary posts no page its pool.deinit(); try Device.released(); } + +test "kv safety: a pieced open beside a running stream posts its scattered state pages and its pages, then maps none" { + const arena = @import("cuda_kv_arena.zig"); + var d = cuda.paging_test_device.Device.driver(); + d.api.cuCtxGetCurrent = Slow.getCurrent; + d.api.cuCtxSetCurrent = Slow.setCurrent; + d.api.cuStreamCreate = Slow.streamCreate; + d.api.cuStreamDestroy_v2 = Slow.streamDestroy; + var e = engine(&d); + e.round_graph = .{}; + defer cuda.completion.drain(&d, e.stream.*, "the test driver must drain before it leaves"); + const l = try pages.layoutPieces(1024, 256, null, 0); + const pb = l.pageBytes(); + const count = 4 * arena.piece_bytes / pb; + const pool = try pages.Pool.init(gpa, &e, l, 1024, null, 2, count); + var s: arena.Arena.Pieces = .{ .gpa = gpa, .vmm = undefined, .d = &d, .io = std.testing.io }; + var live = true; + defer if (live) { + if (s.ahead) |*x| x.deinit(); + pool.arena.pieces = null; + pool.deinit(); + }; + var mapped: [4]bool = @splat(false); + Slow.lazy(&s, pool, &mapped); + // the store holds every page, then frees every other one of the last piece and the first 8: no run is free + const store = try gpa.alloc(u32, count); + defer gpa.free(store); + try std.testing.expect(pool.pool.hold(store)); + const freed = try gpa.alloc(bool, count); + defer gpa.free(freed); + @memset(freed, false); + var id = count - 1; + while (id * pb >= 3 * arena.piece_bytes) : (id -= 2) freed[id] = true; + @memset(freed[0..8], true); + for (0..count) |i| if (freed[count - 1 - i]) try pool.pool.drop(@intCast(count - 1 - i)); // page 0 on top + try std.testing.expect(pool.pool.findRun(l.statePages()) == null); // no run the state could take: pieces only + + try std.testing.expect(!pool.waits(512, false)); // alone: nothing posted, the open maps on its own thread + try std.testing.expect(s.ahead == null and std.mem.indexOfScalar(bool, &mapped, true) == null); + try std.testing.expect(pool.waits(512, true)); // beside a stream: its state pages' piece 3 and its pages' piece 0 + s.ahead.?.settle(); + try std.testing.expectEqualSlices(bool, &.{ true, false, false, true }, &mapped); + try std.testing.expect(!pool.waits(512, true)); // mapped: the open goes on + var seq = try pool.open(512); + try std.testing.expectEqual(@as(u32, 0), Slow.on_caller.load(.monotonic)); // the open mapped nothing itself + try std.testing.expectEqual(l.statePages(), pool.lanes[0].lease.state.items.len); + for (pool.lanes[0].lease.state.items) |x| try std.testing.expect(x * pb >= 3 * arena.piece_bytes and freed[x]); + try std.testing.expect(pool.close(&seq)); + + s.ahead.?.deinit(); + s.ahead = null; + s.lazy.?.unmapAll(.{ .be = s.vmm.backend(), .seek = undefined }); + for (freed, 0..) |f, x| if (!f) try pool.pool.drop(@intCast(x)); + try std.testing.expect(pool.pool.idle()); + pool.arena.pieces = null; + live = false; + pool.deinit(); +} diff --git a/zig/src/families/flashnext/cuda_kv_lanes.zig b/zig/src/families/flashnext/cuda_kv_lanes.zig index d2e0160e3f0..b169488717d 100644 --- a/zig/src/families/flashnext/cuda_kv_lanes.zig +++ b/zig/src/families/flashnext/cuda_kv_lanes.zig @@ -23,6 +23,15 @@ pub fn pagingOf(v: ?[]const u8) !usize { return n; } +/// TF_FLASHNEXT_STATE_PAGES=1 (with TF_FLASHNEXT_KV_PAGES): a lane's states and draft buffers as pieces, no run. +pub fn statePages() !bool { + return statePagesOf(@import("core").profile.get(.TF_FLASHNEXT_STATE_PAGES)); +} + +pub fn statePagesOf(v: ?[]const u8) !bool { + return @import("sys").environment.value(bool, "TF_FLASHNEXT_STATE_PAGES", v, false) catch error.BadFlashNextStatePages; +} + /// TF_FLASHNEXT_KV_PAGES_ALL=1: every stream on pages, none on its own contiguous caches (checks). pub fn pagedOnly() bool { const v = @import("core").profile.get(.TF_FLASHNEXT_KV_PAGES_ALL) orelse return false; @@ -57,6 +66,65 @@ pub fn layout(capacity: usize, tokens: usize, head: ?Head, extra: usize) kv.Layo return .{ .fixed_bytes = mostPages(capacity, tokens) * 4 + extra, .token_bytes = pages.pageBytesOf(tokens, layers) / tokens, .page_tokens = @intCast(tokens), .snap_bytes = 0, .run_bytes = run }; } +/// `layout` with the run as pieces (TF_FLASHNEXT_STATE_PAGES): their pages; the draft's wide block in the fixed part. +pub fn layoutPieces(capacity: usize, tokens: usize, head: ?Head, extra: usize) !kv.Layout { + var l = layout(capacity, tokens, head, extra); + var buf: [32 << 10]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&buf); + var m = pieceMap(fba.allocator(), head, l.pageBytes()) catch |err| { + const why = "TF_FLASHNEXT_KV_PAGES={d}: a page holds {d} bytes, a lane's largest piece {d}: set {d} or more"; + const args = .{ tokens, l.pageBytes(), largestPiece(head), smallestRows(head) }; + if (err == error.PieceOverPage and !@import("builtin").is_test) std.log.err(why, args); + return err; + }; + defer m.deinit(fba.allocator()); + const outside = if (head) |h| mtp.Draft.wideBytes(h.rows) else 0; + l.run_bytes = 0; + l.pieces = m.summary(); + l.fixed_bytes += outside; + l.outside = outside; + return l; +} + +/// A lane's piece sizes in order: each DeltaNet layer's state, then its conv tail, the n-gram tail; then the head's. +fn pieceSizes(gpa: std.mem.Allocator, sizes: *std.ArrayList(u64), head: ?Head) !void { + try sizes.appendNTimes(gpa, state_bytes, wt.linear_n); + try sizes.appendNTimes(gpa, conv_bytes, wt.linear_n); + try sizes.append(gpa, tail_bytes); + if (head) |h| try mtp.Draft.pieceSizes(gpa, sizes, h.draft_n); +} + +/// A lane's largest piece as the packer places it (256-byte aligned). +pub fn largestPiece(head: ?Head) u64 { + var buf: [32 << 10]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&buf); + var sizes: std.ArrayList(u64) = .empty; + pieceSizes(fba.allocator(), &sizes, head) catch unreachable; // a few hundred sizes, well inside buf + return std.mem.alignForward(u64, std.mem.max(u64, sizes.items), 256); +} + +/// The smallest TF_FLASHNEXT_KV_PAGES whose page holds a lane's largest piece (the head's layer widens a page). +pub fn smallestRows(head: ?Head) usize { + const most = largestPiece(head); + var n: usize = wt.index_ratio; + while (pages.valid(n) and layout(0, n, head, 0).pageBytes() < most) n += wt.index_ratio; + return n; +} + +/// A lane's pieces packed on `page_bytes` pages and checked. +fn pieceMap(gpa: std.mem.Allocator, head: ?Head, page_bytes: u64) !kv.pieces.Map { + var sizes: std.ArrayList(u64) = .empty; + defer sizes.deinit(gpa); + try pieceSizes(gpa, &sizes, head); + var m = try kv.pieces.pack(gpa, sizes.items, page_bytes, 256); + errdefer m.deinit(gpa); + try kv.pieces.check(gpa, m); + return m; +} + +/// Pieces of a lane's own state: 36 states, 36 conv tails, the n-gram tail; the head's follow. +const seq_pieces = 2 * wt.linear_n + 1; + /// Where a stream's caches came from: no pool, the one stream on its own caches beside a pool, or a pool lane. pub const From = enum { none, own, pool }; @@ -101,8 +169,8 @@ pub const State = struct { } }; -/// One pool lane: its cache's views (its run's states, its stream's pages), that stream's lease and its run. -const Lane = struct { seq: prompt.Seq, lease: kv.Lease = .{}, used: bool = false, run: u32 = 0 }; +/// One pool lane: its cache's views, that stream's lease, its run (or pieces) and its draft's wide block if pieced. +const Lane = struct { seq: prompt.Seq, lease: kv.Lease = .{}, used: bool = false, run: u32 = 0, wide: ?cuda.DeviceBuffer = null }; pub const Pool = struct { gpa: std.mem.Allocator, @@ -113,6 +181,8 @@ pub const Pool = struct { pool: kv.Pool, arena: @import("cuda_kv_arena.zig").Arena, lanes: []Lane, + /// Where each piece of a lane's state lies on its state pages (TF_FLASHNEXT_STATE_PAGES), else null: a run. + map: ?kv.pieces.Map = null, /// `streams` lanes and `count` pages of layout `l`, made and touched now; a lane holds only its table idle. pub fn init(gpa: std.mem.Allocator, e: *prompt.Engine, l: kv.Layout, capacity: usize, head: ?Head, streams: usize, count: usize) !*Pool { @@ -132,13 +202,22 @@ pub const Pool = struct { errdefer arena.free(); p.* = .{ .gpa = gpa, .e = e, .layout = l, .capacity = capacity, .head = head, .pool = try kv.Pool.init(gpa, count, page_bytes), .arena = arena, .lanes = &.{} }; errdefer p.pool.deinit(); + if (l.pieces != null) p.map = try pieceMap(gpa, head, page_bytes); + errdefer if (p.map) |*m| m.deinit(gpa); + if (l.pieces) |want| if (!std.meta.eql(p.map.?.summary(), want)) return error.FlashNextPiecesMoved; p.lanes = try gpa.alloc(Lane, streams); errdefer gpa.free(p.lanes); var made: usize = 0; - errdefer for (p.lanes[0..made]) |*x| x.seq.deinit(gpa); + errdefer for (p.lanes[0..made]) |*x| { + x.seq.deinit(gpa); + if (x.wide) |*b| b.free(); + }; for (p.lanes) |*x| { x.* = .{ .seq = try p.laneSeq() }; made += 1; + if (p.map != null) if (head) |h| { + x.wide = try cuda.DeviceBuffer.alloc(e.driver, mtp.Draft.wideBytes(h.rows)); + }; } errdefer cuda.completion.drain(e.driver, e.stream.*, "flashnext: failed pool initialization did not drain"); if (!arena.lazy()) try arena.buf.fill8(0, e.stream.handle); // pieces are zeroed as they map @@ -177,22 +256,24 @@ pub const Pool = struct { cuda.completion.drain(p.e.driver, p.e.stream.*, "flashnext: the pool did not drain at close"); for (p.lanes) |*x| { if (x.used) { - p.pool.releaseRun(x.run, p.layout.runPages()); + if (p.map == null) p.pool.releaseRun(x.run, p.layout.runPages()); p.pool.finish(&x.lease); } x.seq.deinit(p.gpa); + if (x.wide) |*b| b.free(); } p.gpa.free(p.lanes); + if (p.map) |*m| m.deinit(p.gpa); p.arena.free(); p.pool.deinit(); p.gpa.destroy(p); } - /// Whether a lane is free, the pool can promise a cache of `cap` rows and a run now, and a run is free. + /// Whether a lane is free, the pool can promise a cache of `cap` rows and its state now, and a run is free. pub fn fits(p: *const Pool, cap: usize) bool { if (cap > p.capacity + windowRows()) return false; - const k = p.layout.runPages(); - for (p.lanes) |x| if (!x.used) return p.pool.fits(p.layout.pages(cap) + k) and p.pool.findRun(k) != null; + const k = p.layout.statePages(); + for (p.lanes) |x| if (!x.used) return p.pool.fits(p.layout.pages(cap) + k) and (p.map != null or p.pool.findRun(k) != null); return false; } @@ -200,15 +281,18 @@ pub const Pool = struct { pub fn waits(p: *Pool, cap: usize, others: bool) bool { // alone, or a piece the thread failed: false; the open maps on its own thread, as before (or fails: LaneMemory) if (!others or !p.arena.lazy()) return false; - const k = p.layout.runPages(); + const k = p.layout.statePages(); const n = p.layout.pages(cap); var ids: [2048]u32 = undefined; if (n > ids.len or !p.pool.fits(n + k)) return false; - const run = p.pool.findRun(k) orelse return false; + const held = stateIds(&p.pool, k, p.map != null); + if (held.from == held.to) return false; // no run free: the open waits for one (LaneMemory) const pb = p.layout.pageBytes(); var posted = false; - if (!p.meet(@as(u64, run) * pb, k * pb, &posted)) return false; - for (nextPages(&p.pool, k, ids[0..n])) |id| if (!p.meet(@as(u64, id) * pb, pb, &posted)) return false; + if (p.map != null) { + for (p.pool.free[0..p.pool.nfree]) |id| if (held.has(id) and !p.meet(@as(u64, id) * pb, pb, &posted)) return false; + } else if (!p.meet(@as(u64, held.from) * pb, k * pb, &posted)) return false; + for (nextPages(&p.pool, held, ids[0..n])) |id| if (!p.meet(@as(u64, id) * pb, pb, &posted)) return false; return posted; } @@ -227,14 +311,17 @@ pub const Pool = struct { const x = for (p.lanes) |*x| { if (!x.used) break x; } else return error.LaneMemory; - const k = p.layout.runPages(); + const k = p.layout.statePages(); const n = p.layout.pages(cap); if (n > mostPages(p.capacity, p.layout.page_tokens)) return error.PromptTooLong; try p.pool.promise(&x.lease, n + k); errdefer p.pool.finish(&x.lease); - // the run first: pages fill from the bottom, runs from the top; a fragmented pool waits (LaneMemory) - const run = p.pool.claimRun(&x.lease, k) orelse return error.LaneMemory; - errdefer p.pool.releaseRun(run, k); + // the run first: pages fill from the bottom, runs from the top; fragmented, it waits (LaneMemory); pieces: any + const run = if (p.map != null) blk: { + try p.pool.takeState(&x.lease, k); + break :blk 0; + } else p.pool.claimRun(&x.lease, k) orelse return error.LaneMemory; + errdefer if (p.map == null) p.pool.releaseRun(run, k); errdefer cuda.completion.drain(p.e.driver, p.e.stream.*, "flashnext: a failed lane open did not drain"); var up: Upload = .{ .p = p, .table = x.seq.paged.?.table }; try p.pool.cover(&x.lease, n, .{ .ctx = &up, .write = Upload.write }); @@ -252,10 +339,20 @@ pub const Pool = struct { return p.arena.buf.ptr + @as(u64, x.run) * p.layout.pageBytes(); } - /// The lane's states as views of its run, laid out afresh (a kept window swaps state buffers with the head's). + /// The lane's states as views of its run or its pieces, laid out afresh (a kept window swaps them with the head's). fn mapStates(p: *Pool, seq: *prompt.Seq) !void { - if (p.layout.runPages() * p.layout.pageBytes() < seqRunBytes()) return error.FlashNextRunTooShort; const x = p.laneOf(seq).?; + if (p.map) |m| { + const d = p.e.driver; + const ids = x.lease.state.items; + const pb = p.layout.pageBytes(); + for (ids) |id| try p.arena.ensure(@as(u64, id) * pb, pb, p.e.stream.handle); + for (seq.state, 0..) |*b, i| b.* = .{ .d = d, .ptr = m.addr(i, p.arena.buf.ptr, ids), .len = state_bytes, .borrowed = true }; + for (seq.conv, 0..) |*b, i| b.* = .{ .d = d, .ptr = m.addr(wt.linear_n + i, p.arena.buf.ptr, ids), .len = conv_bytes, .borrowed = true }; + seq.tail = .{ .d = d, .ptr = m.addr(2 * wt.linear_n, p.arena.buf.ptr, ids), .len = tail_bytes, .borrowed = true }; + return; + } + if (p.layout.runPages() * p.layout.pageBytes() < seqRunBytes()) return error.FlashNextRunTooShort; try p.arena.ensure(@as(u64, x.run) * p.layout.pageBytes(), p.layout.runPages() * p.layout.pageBytes(), p.e.stream.handle); var at = p.runBase(x); for (seq.conv) |*b| { @@ -273,6 +370,13 @@ pub const Pool = struct { pub fn draft(p: *Pool, seq: *const prompt.Seq, cap: usize) !mtp.Draft { const h = p.head orelse return error.FlashNextRunTooShort; const x = p.laneOf(seq) orelse return error.UnknownStream; + if (p.map) |m| { + var at: [4 * wt.linear_n + 6]u64 = undefined; + const n = m.at.len - seq_pieces; + if (n > at.len) return error.FlashNextRunTooShort; + for (at[0..n], seq_pieces..) |*a, i| a.* = m.addr(i, p.arena.buf.ptr, x.lease.state.items); + return mtp.Draft.initPieces(p.gpa, p.e.driver, cap, h.draft_n, h.rows, &x.seq.paged.?, at[0..n], (x.wide orelse return error.FlashNextRunTooShort).ptr); + } const run_len = p.layout.runPages() * p.layout.pageBytes(); if (run_len < seqRunBytes()) return error.FlashNextRunTooShort; return mtp.Draft.initIn(p.gpa, p.e.driver, cap, h.draft_n, h.rows, &x.seq.paged.?, p.runBase(x) + seqRunBytes(), run_len - seqRunBytes()); @@ -289,7 +393,7 @@ pub const Pool = struct { const x = p.laneOf(seq) orelse return false; if (!x.used) return true; cuda.completion.drain(p.e.driver, p.e.stream.*, "flashnext: a closed stream did not drain"); - p.pool.releaseRun(x.run, p.layout.runPages()); + if (p.map == null) p.pool.releaseRun(x.run, p.layout.runPages()); p.pool.finish(&x.lease); p.mapAhead(false); // on the arena's thread: the reply's last token, sent after this, does not wait for it if (seq.media) |*m| m.deinit(); // the stream's image state, held by its copy @@ -306,12 +410,12 @@ pub const Pool = struct { const pb = p.layout.pageBytes(); const s = p.e.stream.handle; if (runs) { - const k = @min(p.layout.runPages() * p.lanes.len, p.pool.total()); + const k = @min(p.layout.statePages() * p.lanes.len, p.pool.total()); p.arena.ensure((p.pool.total() - k) * pb, k * pb, s) catch return; } var ids: [1024]u32 = undefined; // two pieces' worth: a request's pages and a keep's held ones const n: usize = @intCast(@min(ids.len, @max(1, 2 * @import("cuda_kv_arena.zig").piece_bytes / pb))); - for (nextPages(&p.pool, p.layout.runPages(), ids[0..n])) |id| { + for (nextPages(&p.pool, stateIds(&p.pool, p.layout.statePages(), p.map != null), ids[0..n])) |id| { if (!runs) p.arena.post(@as(u64, id) * pb, pb) else p.arena.ensure(@as(u64, id) * pb, pb, s) catch return; } } @@ -363,15 +467,32 @@ test "TF_FLASHNEXT_KV_PAGES: unset, empty or whitespace-only text reads as no pa try t.expectError(error.BadFlashNextKvPages, pagingOf(" ")); } -/// The page ids the free stack hands an open out next, past the run of `run_pages` it claims first, into `out`. -pub fn nextPages(pool: *const kv.Pool, run_pages: usize, out: []u32) []u32 { - const run = if (run_pages > 0) pool.findRun(run_pages) else null; +/// Free ids in [from, to): those an open takes for its state before its pages. +pub const Held = struct { + from: u32, + to: u32, + + pub fn has(h: Held, id: u32) bool { + return id >= h.from and id < h.to; + } +}; + +/// The free ids an open of `k` state pages takes first: its run, or (pieced) takeState's k highest; empty: none. +pub fn stateIds(pool: *const kv.Pool, k: usize, pieced: bool) Held { + if (k == 0) return .{ .from = 0, .to = 0 }; + if (pieced) return .{ .from = kv.pieces.nthHighest(pool.free[0..pool.nfree], k), .to = std.math.maxInt(u32) }; + const r = pool.findRun(k) orelse return .{ .from = 0, .to = 0 }; + return .{ .from = r, .to = r + @as(u32, @intCast(k)) }; +} + +/// The page ids the free stack hands an open out next, past the state ids `held` it takes first, into `out`. +pub fn nextPages(pool: *const kv.Pool, held: Held, out: []u32) []u32 { var n: usize = 0; var i = pool.nfree; while (i > 0 and n < out.len) { i -= 1; const id = pool.free[i]; - if (run) |r| if (id >= r and id < r + run_pages) continue; + if (held.has(id)) continue; out[n] = id; n += 1; } @@ -382,12 +503,13 @@ test "mapped ahead: the pages the free stack hands out next, page 0 first, then var pool = try kv.Pool.init(std.testing.allocator, 64, 4096); defer pool.deinit(); var out: [100]u32 = undefined; - try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2, 3 }, nextPages(&pool, 0, out[0..4])); + const none = stateIds(&pool, 0, false); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2, 3 }, nextPages(&pool, none, out[0..4])); var held: [5]u32 = undefined; try std.testing.expect(pool.hold(&held)); - try std.testing.expectEqualSlices(u32, &.{ 5, 6, 7, 8 }, nextPages(&pool, 0, out[0..4])); // what a keep leaves next + try std.testing.expectEqualSlices(u32, &.{ 5, 6, 7, 8 }, nextPages(&pool, none, out[0..4])); // what a keep leaves next for (held) |id| pool.release(id); - try std.testing.expectEqual(@as(usize, 64), nextPages(&pool, 0, &out).len); + try std.testing.expectEqual(@as(usize, 64), nextPages(&pool, none, &out).len); try std.testing.expect(pool.idle()); } @@ -403,7 +525,7 @@ test "mapped ahead: after a close the next pages are the freed and fresh ones, n pool.releaseRun(run, 4); // close: the run back, then the lane's pages pool.finish(&l); var out: [8]u32 = undefined; - const next = nextPages(&pool, 4, &out); + const next = nextPages(&pool, stateIds(&pool, 4, false), &out); for (next) |id| try std.testing.expect(id < run); // the run the next open claims again is no page it is handed try std.testing.expect(std.mem.indexOfScalar(u32, next, 8) != null); // the first fresh page past the keep's for (held) |id| pool.release(id); @@ -434,4 +556,5 @@ test { _ = @import("cuda_kv_init_test.zig"); _ = @import("cuda_kv_lifetime_test.zig"); _ = @import("cuda_kv_arena.zig"); + _ = @import("cuda_kv_pieces_test.zig"); } diff --git a/zig/src/families/flashnext/cuda_kv_pieces_test.zig b/zig/src/families/flashnext/cuda_kv_pieces_test.zig new file mode 100644 index 00000000000..95c82a6d562 --- /dev/null +++ b/zig/src/families/flashnext/cuda_kv_pieces_test.zig @@ -0,0 +1,208 @@ +//! TF_FLASHNEXT_STATE_PAGES: a lane's states and draft buffers as pieces on any pages of its lease, on a fake device. +const std = @import("std"); +const cuda = @import("cuda"); +const kv = @import("core").kv_pool; +const lanes = @import("cuda_kv_lanes.zig"); +const mtp = @import("cuda_mtp.zig"); +const wt = @import("cuda_prompt_wt.zig"); +const E = @import("cuda_prompt.zig").Engine; +const D = cuda.paging_test_device.Device; +const Draft = @import("cuda_mtp_draft.zig").Draft; +const t = std.testing; + +const head: lanes.Head = .{ .draft_n = 32768, .rows = 1536 }; + +var queue: cuda.Stream = undefined; +fn engine(d: *cuda.Driver) E { + var e: E = undefined; + e.driver = d; + queue = .{ .d = d, .handle = D.stream }; + e.stream = &queue; + e.eos = 0; + e.round_graph = .{}; + return e; +} + +test "TF_FLASHNEXT_STATE_PAGES is exact 0 or 1: words, 2 and padded text are refused by name, blank is unset" { + try t.expect(!try lanes.statePagesOf(null)); + try t.expect(!try lanes.statePagesOf(" ")); + try t.expect(!try lanes.statePagesOf("0")); + try t.expect(try lanes.statePagesOf("1")); + for ([_][]const u8{ "off", "false", "no", "on", "true", "yes", "2", " 0", "1 ", "01" }) |v| + try t.expectError(error.BadFlashNextStatePages, lanes.statePagesOf(v)); +} + +fn withLate(on: bool) bool { + const was = Draft.late_on; + Draft.late_on = on; + return was; +} + +test "Flash Next pieces at 256-row pages: 37 pages with the head (45 with pending rows), 18 without, wide block fixed" { + const was = withLate(false); + defer Draft.late_on = was; + const run = lanes.layout(40960, 256, head, 0); + const l = try lanes.layoutPieces(40960, 256, head, 0); + try t.expectEqual(@as(usize, 41), run.statePages()); + try t.expectEqual(kv.groups.Pieces{ .n = 186, .pages = 37, .bytes = 288_993_792 }, l.pieces.?); // 48-row windows + try t.expectEqual(@as(usize, 37), l.statePages()); + try t.expectEqual(@as(u64, 0), l.run_bytes); + try t.expectEqual(@as(u64, 31_457_280 + 23_838_720), l.outside); + try t.expectEqual(run.fixed_bytes + l.outside, l.fixed_bytes); + try t.expectEqual(run.pageBytes(), l.pageBytes()); + Draft.late_on = true; + const late = try lanes.layoutPieces(40960, 256, head, 0); + try t.expectEqual(@as(u32, 223), late.pieces.?.n); + try t.expectEqual(@as(u32, 45), late.pieces.?.pages); + const plain = try lanes.layoutPieces(40960, 256, null, 0); + try t.expectEqual(@as(u32, 73), plain.pieces.?.n); + try t.expectEqual(@as(u32, 18), plain.pieces.?.pages); + try t.expectEqual(@as(u64, 0), plain.outside); + try t.expectError(error.PieceOverPage, lanes.layoutPieces(40960, 64, null, 0)); // a 3 MiB state past a page +} + +test "the smallest page that holds a lane's largest piece: 104 rows with the head, 112 without; one step less refuses" { + try t.expectEqual(@as(u64, 3 << 20), lanes.largestPiece(head)); // a layer's DeltaNet state + try t.expectEqual(@as(u64, 3 << 20), lanes.largestPiece(null)); + try t.expectEqual(@as(usize, 104), lanes.smallestRows(head)); + try t.expectEqual(@as(usize, 112), lanes.smallestRows(null)); + for ([_]?lanes.Head{ head, null }) |h| { + const n = lanes.smallestRows(h); + _ = try lanes.layoutPieces(40960, n, h, 0); + try t.expectError(error.PieceOverPage, lanes.layoutPieces(40960, n - wt.index_ratio, h, 0)); + } + const why = @import("cuda_lanes_explain.zig").explain(error.PieceOverPage).?; + try t.expect(std.mem.indexOf(u8, why, "128") == null); // no fixed floor: the log names the page +} + +/// The lane's pieces as [ptr, ptr + len) ranges: its state, conv tails, tail; with `d`, the head's too. +fn ranges(a: std.mem.Allocator, seq: anytype, d: ?*const Draft) !std.ArrayList([2]u64) { + var r: std.ArrayList([2]u64) = .empty; + errdefer r.deinit(a); + for (seq.state) |b| try r.append(a, .{ b.ptr, b.ptr + b.len }); + for (seq.conv) |b| try r.append(a, .{ b.ptr, b.ptr + b.len }); + try r.append(a, .{ seq.tail.ptr, seq.tail.ptr + seq.tail.len }); + const x = d orelse return r; + for (x.spare) |b| try r.append(a, .{ b.ptr, b.ptr + b.len }); + for (x.keep.layers, 0..) |lk, layer| if (wt.linearLayer(layer)) { + try r.append(a, .{ lk.hist, lk.hist + x.layout.conv }); + try r.append(a, .{ lk.proj, lk.proj + mtp.max_rows * x.layout.proj }); + }; + try r.append(a, .{ x.saved_tail, x.saved_tail + x.layout.nrow_at - x.layout.tail_at }); + try r.append(a, .{ x.saved_nrow, x.saved_nrow + x.layout.saved - x.layout.nrow_at }); + for ([_]cuda.DeviceBuffer{ x.out, x.dlogits, x.best }) |b| try r.append(a, .{ b.ptr, b.ptr + b.len }); + return r; +} + +/// Every range inside one of `ids`' pages of the arena, and no two ranges overlapping. +fn expectPlaced(r: [][2]u64, base: u64, page: u64, ids: []const u32) !void { + for (r) |x| { + const at = (x[0] - base) / page; + try t.expect(std.mem.indexOfScalar(u32, ids, @intCast(at)) != null); + try t.expect(x[1] <= base + (at + 1) * page); + } + std.mem.sort([2]u64, r, {}, struct { + fn less(_: void, a: [2]u64, b: [2]u64) bool { + return a[0] < b[0]; + } + }.less); + for (r[0 .. r.len - 1], r[1..]) |a, b| try t.expect(a[1] <= b[0]); +} + +test "fragmentation: no free consecutive run, a run lane waits, a pieces lane opens on the scattered pages" { + var d = D.driver(); + var e = engine(&d); + defer cuda.completion.drain(&d, e.stream.*, "the test driver must drain before it leaves"); + for ([_]bool{ false, true }) |pieced| { + const l = if (pieced) try lanes.layoutPieces(1024, 256, null, 0) else lanes.layout(1024, 256, null, 0); + const k = l.statePages(); + const count = 2 * (k + 1) + 2; + const p = try lanes.Pool.init(t.allocator, &e, l, 1024, null, 1, count); + defer p.deinit(); + const store = try t.allocator.alloc(u32, count); + defer t.allocator.free(store); + try t.expect(p.pool.hold(store)); + var i: u32 = 1; + while (i < count) : (i += 2) try p.pool.drop(i); // the store keeps every other page: no two free side by side + if (!pieced) { + try t.expectError(error.LaneMemory, p.open(1)); + try t.expect(!p.fits(1)); + } else { + try t.expect(p.fits(1)); + var seq = try p.open(1); + var r = try ranges(t.allocator, &seq, null); + defer r.deinit(t.allocator); + const x = &p.lanes[0]; + for (x.lease.state.items) |id| try t.expect(id % 2 == 1); + try expectPlaced(r.items, p.arena.buf.ptr, l.pageBytes(), x.lease.state.items); + try t.expect(p.close(&seq)); + } + i = 0; + while (i < count) : (i += 2) try p.pool.drop(i); + try t.expect(p.pool.idle()); + } +} + +test "two lanes with the head: every piece inside its own lane's state pages, none on another's or on KV pages" { + const was = withLate(true); + defer Draft.late_on = was; + var d = D.driver(); + var e = engine(&d); + defer cuda.completion.drain(&d, e.stream.*, "the test driver must drain before it leaves"); + const l = try lanes.layoutPieces(1024, 256, head, 0); + const p = try lanes.Pool.init(t.allocator, &e, l, 1024, head, 2, 2 * (l.statePages() + 6)); + defer p.deinit(); + var seqs: [2]@import("cuda_prompt.zig").Seq = undefined; + var drafts: [2]Draft = undefined; + var all: std.ArrayList([2]u64) = .empty; + defer all.deinit(t.allocator); + for (&seqs, &drafts, 0..) |*s, *dr, j| { + s.* = try p.open(1024); + dr.* = try p.draft(s, 1024); + var r = try ranges(t.allocator, s, dr); + defer r.deinit(t.allocator); + try expectPlaced(r.items, p.arena.buf.ptr, l.pageBytes(), p.lanes[j].lease.state.items); + try all.appendSlice(t.allocator, r.items); + const w = p.lanes[j].wide.?; + try t.expectEqual(w.ptr, dr.streams.ptr); + try t.expect(dr.logits.ptr + dr.logits.len <= w.ptr + w.len and dr.streams.ptr + dr.streams.len <= dr.logits.ptr); + try t.expect(dr.log != null and dr.keep.layers[0].log_ctl == dr.log.?.ptr); + for (p.lanes[j].lease.ids.items) |id| try t.expect(std.mem.indexOfScalar(u32, p.lanes[j].lease.state.items, id) == null); + } + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(t.allocator); + for (p.lanes) |x| try ids.appendSlice(t.allocator, x.lease.state.items); + try expectPlaced(all.items, p.arena.buf.ptr, l.pageBytes(), ids.items); + for (&seqs, &drafts) |*s, *dr| { + dr.deinit(); + try t.expect(p.close(s)); + } + try t.expect(p.pool.idle()); +} + +test "LEAK: a failed open on pieces and a failed wide block at init leave the pool and the device as before" { + var d = D.driver(); + var e = engine(&d); + defer { + D.fail_wait = false; + cuda.completion.drain(&d, e.stream.*, "the test driver must drain before it leaves"); + } + const l = try lanes.layoutPieces(1024, 256, null, 0); + const p = try lanes.Pool.init(t.allocator, &e, l, 1024, null, 1, l.statePages() + 6); + defer p.deinit(); + const load = p.pool.census(); + D.fail_wait = true; // the table upload's wait fails: open unwinds every page it took + try t.expectError(error.NotReady, p.open(1)); + D.fail_wait = false; + try t.expectEqual(load, p.pool.census()); + D.fail_fill = true; // the state clear fails after its pages and table are in + try t.expectError(error.NotReady, p.open(1)); + D.fail_wait = false; + try t.expectEqual(load, p.pool.census()); + var seq = try p.open(1); + try t.expect(p.close(&seq)); + try t.expectEqual(load, p.pool.census()); + var bad = l; + bad.pieces.?.pages += 1; // a layout from another packing is refused before any lane exists + try t.expectError(error.FlashNextPiecesMoved, lanes.Pool.init(t.allocator, &e, bad, 1024, null, 1, 8)); +} diff --git a/zig/src/families/flashnext/cuda_lanes_explain.zig b/zig/src/families/flashnext/cuda_lanes_explain.zig index fe6365c5df0..abf7597d0f4 100644 --- a/zig/src/families/flashnext/cuda_lanes_explain.zig +++ b/zig/src/families/flashnext/cuda_lanes_explain.zig @@ -7,6 +7,7 @@ pub fn open(err: anyerror) ?[]const u8 { error.FlashNextRanksNeedModelopt => "--tp 2 splits Flash Next's ModelOpt and TFQ checkpoints only; serve this MLX checkpoint on one GPU, without --tp", error.FlashNextRanksOnCapturedGlue => "--tp 2 runs Flash Next's own glue, not a captured set: set TENSORFOLD_CUDA_KERNELS=native, or serve on one GPU", error.BadFlashNextKvPages, error.BadFlashNextPageTest, error.FlashNextPagesUnsupported, error.UnsupportedCheckpoint => explain(err), + error.BadFlashNextStatePages, error.FlashNextStatePagesNeedKvPages, error.PieceOverPage => explain(err), error.UnsupportedLearningFormat, error.TrainingOnCapturedGlue => explain(err), error.VisionWithoutTower => @import("engine_api").visionWords("this Flash Next checkpoint", err), else => null, @@ -20,6 +21,9 @@ pub fn explain(err: anyerror) ?[]const u8 { error.OutOfDeviceMemory => "the GPU had no memory left for this request's caches: retry once another request ends", error.BadFlashNextKvPages, error.BadFlashNextPageTest => "TF_FLASHNEXT_KV_PAGES and _PAGE_TEST take positions a page, a multiple of 4", error.FlashNextPagesUnsupported => "TF_FLASHNEXT_KV_PAGES needs one rank, our own glue and no --slide: unset it", + error.BadFlashNextStatePages => "TF_FLASHNEXT_STATE_PAGES takes 1 (states as pieces on pool pages) or 0", + error.FlashNextStatePagesNeedKvPages => "TF_FLASHNEXT_STATE_PAGES puts pool lanes' states on pages: set TF_FLASHNEXT_KV_PAGES too", + error.PieceOverPage => "TF_FLASHNEXT_STATE_PAGES: a page must hold a lane's largest piece (a layer's 3 MiB state); the log above names the smallest page that does", error.UnsupportedCheckpoint => "the checkpoint differs from the supported Flash Next CUDA layout; the log names its config field", error.DecodeGraphWithDenseSplit => "TF_FLASHNEXT_DECODE_GRAPH is not qualified with the dense split: unset it or set TF_FLASHNEXT_SPLIT_DENSE=0", error.RankDisconnected, error.RankTimeout, error.RemoteRank, error.BadRankFrame => "a tensor-parallel rank failed; restart both ranks from the same checkpoint before retrying", diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 6fe1da8e5e7..1dde04ad396 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -38,6 +38,8 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu if (o.slide and captured != null) return error.TrainingOnCapturedGlue; const page_tokens = try @import("cuda_kv_lanes.zig").paging(); if (page_tokens > 0 and (o.tp != 1 or o.slide or captured != null)) return error.FlashNextPagesUnsupported; + const state_pages = try @import("cuda_kv_lanes.zig").statePages(); + if (state_pages and page_tokens == 0) return error.FlashNextStatePagesNeedKvPages; // pending DeltaNet rows run on one GPU only: TF_FLASHNEXT_KEEP_LATE=1 with tensor parallel is refused const Draft = @import("cuda_mtp_draft.zig").Draft; const late_fits = o.tp == 1; @@ -132,7 +134,9 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu // the lane's head runs at the engine's chunk: its cache on the stream's pages, its buffers in the run own.kv.head = if (own.head) |h| .{ .draft_n = h.ids.len, .rows = own.engine.chunk } else null; const head_bytes = if (own.head) |h| mtp.Draft.bytes(window, h.ids.len, own.engine.chunk, own.engine.heads) else 0; - own.kv.layout = @import("cuda_kv_lanes.zig").layout(o.context, page_tokens, own.kv.head, stream_bytes - own_seq_bytes - head_bytes); + const kvl = @import("cuda_kv_lanes.zig"); + const extra = stream_bytes - own_seq_bytes - head_bytes; + own.kv.layout = if (state_pages) try kvl.layoutPieces(o.context, page_tokens, own.kv.head, extra) else kvl.layout(o.context, page_tokens, own.kv.head, extra); } if (own.ranks) |r| try load_cache.finishAfter(.{ r, std.math.maxInt(u64) }, ranks.Session.room) else load_cache.finish(); // the weights are in: the n-gram table into the page cache behind them, so the first prompt finds its rows in RAM diff --git a/zig/src/families/flashnext/cuda_mtp_draft.zig b/zig/src/families/flashnext/cuda_mtp_draft.zig index 638b772be1f..ce2cf2c801a 100644 --- a/zig/src/families/flashnext/cuda_mtp_draft.zig +++ b/zig/src/families/flashnext/cuda_mtp_draft.zig @@ -85,6 +85,9 @@ pub const Draft = struct { best: cuda.DeviceBuffer, /// Before a window: each DeltaNet layer's conv window and (from the pass) projection rows; the n-gram tail. saved: cuda.DeviceBuffer, + /// Where the saved n-gram tail and the window's n-gram rows are (in `saved`, or pieces of their own). + saved_tail: u64 = 0, + saved_nrow: u64 = 0, /// A window's DeltaNet end states: swapped in when every row is kept, else the kept rows replay on the sequence's. spare: [linear_n]cuda.DeviceBuffer = undefined, /// Where `saved` holds each piece and how large the spares are, at the model's heads (its sequence's). @@ -276,9 +279,67 @@ pub const Draft = struct { } li += 1; } + d.saved_tail = d.saved.ptr + d.layout.tail_at; + d.saved_nrow = d.saved.ptr + d.layout.nrow_at; d.aim(); } + /// A pool lane's draft pieces in initPieces' order; streams and logits, wider than a page, are wideBytes' block. + pub fn pieceSizes(gpa: std.mem.Allocator, out: *std.ArrayList(u64), draft_n: usize) !void { + const l = Layout.of(pool_heads); + try out.appendNTimes(gpa, l.state, linear_n); // spares + try out.appendNTimes(gpa, l.conv, linear_n); // saved conv windows + try out.appendNTimes(gpa, max_rows * l.proj, linear_n); // saved projection rows + // saved n-gram tail and rows, the head's output row, the draft head's scores, best values + try out.appendSlice(gpa, &.{ l.nrow_at - l.tail_at, l.saved - l.nrow_at, wide * 2, draft_n * 2, bestBytes(l.rows) }); + if (!late()) return; + try out.append(gpa, log_ctl_bytes); // the pending-row log's control word, then each layer's log + try out.appendNTimes(gpa, layer_log_bytes, linear_n); + } + + /// A pool lane's `streams` and `logits` in one block outside the pool, each on a 256-byte boundary. + pub fn wideBytes(rows: usize) usize { + const a = std.mem.alignForward; + return a(usize, @max(rows, max_rows) * wide * 2, 256) + a(usize, max_rows * vocab * 2, 256); + } + + /// A pool lane's head on pieces: its cache on `paged`'s pages, `at` pieceSizes' addresses, `block` wideBytes'. + pub fn initPieces(gpa: std.mem.Allocator, driver: *cuda.Driver, cap: usize, draft_n: usize, rows: usize, paged: *const pages.Paged, at: []const u64, block: u64) !Draft { + const l = Layout.of(pool_heads); + if (at.len != 3 * linear_n + 5 + if (late()) 1 + linear_n else 0) return error.FlashNextRunTooShort; + const B = struct { + fn of(dr: *const cuda.Driver, ptr: u64, n: usize) cuda.DeviceBuffer { + return .{ .d = dr, .ptr = ptr, .len = n, .borrowed = true }; + } + }; + const head = wt.attn_n; + const rows_cap = @max(rows, max_rows); + const streams_len = std.mem.alignForward(usize, rows_cap * wide * 2, 256); + var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .gpa = gpa, .cap = cap, .rows_cap = rows_cap, .kc = B.of(driver, paged.at(head, .key), 0), .vc = B.of(driver, paged.at(head, .value), 0), .ikc = B.of(driver, paged.at(head, .index), 0), .pooled = B.of(driver, paged.at(head, .pooled), 0), .pg = paged.pg(), .streams = B.of(driver, block, rows_cap * wide * 2), .out = undefined, .logits = B.of(driver, block + streams_len, max_rows * vocab * 2), .dlogits = undefined, .best = undefined, .saved = B.of(driver, 0, 0), .host = undefined, .layout = l }; + const n = linear_n; + for (&d.spare, at[0..n]) |*b, ptr| b.* = B.of(driver, ptr, l.state); + d.saved_tail = at[3 * n]; + d.saved_nrow = at[3 * n + 1]; + d.out = B.of(driver, at[3 * n + 2], wide * 2); + d.dlogits = B.of(driver, at[3 * n + 3], draft_n * 2); + d.best = B.of(driver, at[3 * n + 4], bestBytes(l.rows)); + if (late()) d.log = B.of(driver, at[3 * n + 5], log_ctl_bytes); + var li: usize = 0; + for (&d.keep.layers, 0..) |*lk, layer| { + if (!wt.linearLayer(layer)) continue; + lk.hist = at[n + li]; + lk.proj = at[2 * n + li]; + if (d.log) |b| { + lk.log = at[3 * n + 6 + li]; + lk.log_ctl = b.ptr; + } + li += 1; + } + d.host = try gpa.alloc(u16, @max(max_rows * vocab, draft_n)); + d.aim(); + return d; + } + /// Device bytes `initIn` takes from a run: every buffer but the head's cache, each on a 256-byte boundary. pub fn runBytes(draft_n: usize, rows: usize) usize { return bytes(0, draft_n, rows, pool_heads) + (7 + linear_n) * 256; diff --git a/zig/src/families/flashnext/cuda_mtp_graphs_test.zig b/zig/src/families/flashnext/cuda_mtp_graphs_test.zig index bb84ef5fff2..df64122f92a 100644 --- a/zig/src/families/flashnext/cuda_mtp_graphs_test.zig +++ b/zig/src/families/flashnext/cuda_mtp_graphs_test.zig @@ -93,6 +93,8 @@ const Draft = struct { out: Buf = .{ .ptr = 0x2000_0000 }, dlogits: Buf = .{ .ptr = 0x2100_0000 }, saved: Buf = .{ .ptr = 0x2200_0000 }, + saved_tail: u64 = 0x2200_1000, + saved_nrow: u64 = 0x2200_2000, keep: parts.Keep = .{}, }; @@ -345,7 +347,14 @@ test "rank graphs: a rollback's key holds every buffer the replay touches and it var gen = q; gen.gen += 1; try expectMoved(base, wg.RollbackKey.init(&gen, &d, 2, &s)); - const drafts: [4]Draft = .{ .{ .gen = 2, .keep = d.keep }, .{ .saved = .{ .ptr = 0x2200_0100 }, .keep = d.keep }, kept(d, 0x8000_0100, 0x8100_0000), kept(d, 0x8000_0000, 0x8100_0100) }; + const drafts: [6]Draft = .{ + .{ .gen = 2, .keep = d.keep }, + .{ .saved = .{ .ptr = 0x2200_0100 }, .keep = d.keep }, + .{ .saved_tail = 0x2200_1100, .keep = d.keep }, + .{ .saved_nrow = 0x2200_2100, .keep = d.keep }, + kept(d, 0x8000_0100, 0x8100_0000), + kept(d, 0x8000_0000, 0x8100_0100), + }; for (&drafts) |*x| try expectMoved(base, wg.RollbackKey.init(&q, x, 2, &s)); var other_s = s; other_s.h += 0x100; diff --git a/zig/src/families/flashnext/cuda_mtp_ops.zig b/zig/src/families/flashnext/cuda_mtp_ops.zig index da41ddfefd0..8bcd73048bc 100644 --- a/zig/src/families/flashnext/cuda_mtp_ops.zig +++ b/zig/src/families/flashnext/cuda_mtp_ops.zig @@ -91,8 +91,8 @@ fn verifyTail(o: anytype, seq: *prompt.Seq, d: *Draft, ids: []const u32, hooks: // the same copies and row best in the same order, inside the window's graph when it has one var tail: graph_tail.Tail = .{}; if (keeps) { - tail.before = .{ .dst = d.saved.ptr + d.layout.tail_at, .src = seq.tail.ptr, .n = ple_tail_n * wide * 2 }; - tail.after = .{ .dst = d.saved.ptr + d.layout.nrow_at, .n = n * wide * 2 }; + tail.before = .{ .dst = d.saved_tail, .src = seq.tail.ptr, .n = ple_tail_n * wide * 2 }; + tail.after = .{ .dst = d.saved_nrow, .n = n * wide * 2 }; } if (ahead) { tail.head = o.h; @@ -106,9 +106,9 @@ fn verifyTail(o: anytype, seq: *prompt.Seq, d: *Draft, ids: []const u32, hooks: try o.e.forward(@TypeOf(o.tri), o.tri, seq, ids, with); d.best_queued = ahead; } else { - if (keeps) try copyAsync(o.stream(), d.saved.ptr + d.layout.tail_at, seq.tail.ptr, ple_tail_n * wide * 2); + if (keeps) try copyAsync(o.stream(), d.saved_tail, seq.tail.ptr, ple_tail_n * wide * 2); try o.e.forward(@TypeOf(o.tri), o.tri, seq, ids, hooks); - if (keeps) try copyAsync(o.stream(), d.saved.ptr + d.layout.nrow_at, o.e.batch_s.?.ple_nrow, n * wide * 2); + if (keeps) try copyAsync(o.stream(), d.saved_nrow, o.e.batch_s.?.ple_nrow, n * wide * 2); } } /// The head's work over a sequence: prompt pass, verify windows, rollback, forward and chains; `Tri` launches kernels. @@ -355,14 +355,14 @@ pub fn Ops(comptime Tri: type) type { d.rows = n; d.history = seq.history; @memcpy(d.ids[0..n], ids); - if (keeps) try copyAsync(o.stream(), d.saved.ptr + d.layout.tail_at, seq.tail.ptr, ple_tail_n * wide * 2); + if (keeps) try copyAsync(o.stream(), d.saved_tail, seq.tail.ptr, ple_tail_n * wide * 2); w.* = .{ .seq = seq, .ids = ids, .keep = if (keeps) &d.keep else null, .streams = d.streams.ptr, .logits = d.logits.ptr }; } try o.e.windows(Tri, o.tri, wins, out); var row0: usize = 0; for (ds, idss, wins) |d, ids, w| { const keeps = w.keep != null; - if (keeps) try copyAsync(o.stream(), d.saved.ptr + d.layout.nrow_at, o.e.batch_s.?.ple_nrow + row0 * wide * 2, ids.len * wide * 2); + if (keeps) try copyAsync(o.stream(), d.saved_nrow, o.e.batch_s.?.ple_nrow + row0 * wide * 2, ids.len * wide * 2); d.open = keeps; row0 += ids.len; } diff --git a/zig/src/families/flashnext/cuda_mtp_roll.zig b/zig/src/families/flashnext/cuda_mtp_roll.zig index 964ff6365f9..98c11ee1c40 100644 --- a/zig/src/families/flashnext/cuda_mtp_roll.zig +++ b/zig/src/families/flashnext/cuda_mtp_roll.zig @@ -22,7 +22,7 @@ pub fn lateRoll(o: anytype, seq: *prompt.Seq, d: *Draft, keep: usize) !void { t.j[n] = .{ .win = seq.conv[n].ptr, .hist = lk.hist, .rows = lk.proj, .stride = @intCast(gdn.proj_width), .taps = @intCast(gdn.taps - 1), .c = @intCast(gdn.conv_dim) }; n += 1; } - t.j[n] = .{ .win = seq.tail.ptr, .hist = d.saved.ptr + d.layout.tail_at, .rows = d.saved.ptr + d.layout.nrow_at, .stride = @intCast(wt.wide), .taps = @intCast(wt.ple_tail_n), .c = @intCast(wt.wide) }; + t.j[n] = .{ .win = seq.tail.ptr, .hist = d.saved_tail, .rows = d.saved_nrow, .stride = @intCast(wt.wide), .taps = @intCast(wt.ple_tail_n), .c = @intCast(wt.wide) }; n += 1; t.n = @intCast(n); var a: cuda.Args = .{}; @@ -44,8 +44,8 @@ const Replay = struct { pub fn run(r: @This()) !void { const k = &r.e.batch_k; const rs = r.s; - try copyAsync(r.st, r.seq.tail.ptr, r.d.saved.ptr + r.d.layout.tail_at, wt.ple_tail_n * wt.wide * 2); - try shift(k, r.st, r.seq.tail.ptr, r.d.saved.ptr + r.d.layout.nrow_at, wt.wide, r.keep, wt.ple_tail_n, wt.wide); + try copyAsync(r.st, r.seq.tail.ptr, r.d.saved_tail, wt.ple_tail_n * wt.wide * 2); + try shift(k, r.st, r.seq.tail.ptr, r.d.saved_nrow, wt.wide, r.keep, wt.ple_tail_n, wt.wide); var li: usize = 0; for (r.e.layers[0..r.e.n_layers], 0..) |*lw, layer| { if (!lw.linear) continue; diff --git a/zig/src/families/flashnext/cuda_window_graph.zig b/zig/src/families/flashnext/cuda_window_graph.zig index 066322cf898..caf6e2f4830 100644 --- a/zig/src/families/flashnext/cuda_window_graph.zig +++ b/zig/src/families/flashnext/cuda_window_graph.zig @@ -207,7 +207,7 @@ pub const RollbackKey = struct { pub fn init(seq: anytype, d: anytype, keep: usize, s: *const parts.Scratch) RollbackKey { var h: Hash = .{}; - h.values(&[_]u64{ seq.gen, d.gen, seq.tail.ptr, d.saved.ptr, s.h, s.cap }); + h.values(&[_]u64{ seq.gen, d.gen, seq.tail.ptr, d.saved.ptr, d.saved_tail, d.saved_nrow, s.h, s.cap }); for (seq.conv) |b| h.values(&[_]u64{b.ptr}); for (seq.state) |b| h.values(&[_]u64{b.ptr}); h.keep(&d.keep); diff --git a/zig/src/native/cuda_kv_pool.zig b/zig/src/native/cuda_kv_pool.zig index 4315e5b1043..2afc231b2ef 100644 --- a/zig/src/native/cuda_kv_pool.zig +++ b/zig/src/native/cuda_kv_pool.zig @@ -4,9 +4,7 @@ const api = @import("engine_api"); const kv_pool = @import("core").kv_pool; const budget = @import("cuda_memory.zig"); const Allocator = std.mem.Allocator; - pub const Plan = kv_pool.Plan; - /// A family whose other streams take pages (Nemotron's) names their layout; any other allocates a window each (null). pub fn layout(loaded: anytype) ?kv_pool.Layout { return if (comptime @hasField(@TypeOf(loaded), "layout")) loaded.layout else null; @@ -85,30 +83,33 @@ test "a pool's census is in tokens, and a run shows only where the family needs try std.testing.expectEqual(@as(?bool, false), census(.{ .pool = &p, .page_tokens = 64, .run_pages = 8 }).run); } -/// The plan's view of a wrapped family: drafter buffers join the fixed part; no free stream pays its window first. -pub fn served(l: ?kv_pool.Layout, free_streams: u32, family_bytes: u64, stream_bytes: u64, room: u64) struct { layout: ?kv_pool.Layout, room: u64 } { +/// A wrapped family's plan: drafters join the fixed part, no free stream pays its window, `spare` pays an extra lane. +pub fn served(l: ?kv_pool.Layout, free_streams: u32, family_bytes: u64, stream_bytes: u64, room: u64, spare: bool) struct { layout: ?kv_pool.Layout, room: u64 } { var out = l orelse return .{ .layout = null, .room = room }; out.fixed_bytes += stream_bytes -| family_bytes; - return .{ .layout = out, .room = if (free_streams == 0) room -| stream_bytes else room }; + return .{ .layout = out, .room = (if (free_streams == 0) room -| stream_bytes else room) -| if (spare) out.outside else 0 }; } test "a wrapped family's plan: drafter buffers a stream, a first window without a free stream" { const l: kv_pool.Layout = .{ .fixed_bytes = 10, .token_bytes = 1, .page_tokens = 4, .snap_bytes = 1 }; - const nemotron = served(l, 1, 500, 500, 1000); // its own sequence is in the model's bytes: nothing moves + const nemotron = served(l, 1, 500, 500, 1000, false); // its own sequence is in the model's bytes: nothing moves try std.testing.expectEqual(@as(u64, 10), nemotron.layout.?.fixed_bytes); try std.testing.expectEqual(@as(u64, 1000), nemotron.room); - const qwen = served(l, 0, 500, 530, 1000); // a drafter's 30 bytes a stream, the first stream's 530 first + const qwen = served(l, 0, 500, 530, 1000, false); // a drafter's 30 bytes a stream, the first stream's 530 first try std.testing.expectEqual(@as(u64, 40), qwen.layout.?.fixed_bytes); try std.testing.expectEqual(@as(u64, 470), qwen.room); - try std.testing.expectEqual(@as(?kv_pool.Layout, null), served(null, 0, 1, 2, 3).layout); + try std.testing.expectEqual(@as(?kv_pool.Layout, null), served(null, 0, 1, 2, 3, true).layout); + var outside = l; + outside.outside = 100; // TF_QWEN_KV_SHARE: the lane past the plan's holds its taps and ring outside the pool + try std.testing.expectEqual(@as(u64, 370), served(outside, 0, 500, 530, 1000, true).room); + try std.testing.expectEqual(@as(u64, 470), served(outside, 0, 500, 530, 1000, false).room); } - /// served() on the family's layout; a family that places a drafter's buffers itself (pagedLayout) plans it again. -pub fn wrapped(comptime F: type, loaded: anytype, free: u32, stream_bytes: u64, room: u64) @TypeOf(served(null, 0, 0, 0, 0)) { +pub fn wrapped(comptime F: type, loaded: anytype, free: u32, stream_bytes: u64, room: u64) @TypeOf(served(null, 0, 0, 0, 0, false)) { const own = comptime @hasDecl(F, "pagedLayout"); const l = layout(loaded); const planned = if (own) (if (l != null) F.pagedLayout(loaded.ctx, stream_bytes - loaded.stream_bytes) else null) else l; - return served(planned, free, if (own) stream_bytes else loaded.stream_bytes, stream_bytes, room); + return served(planned, free, if (own) stream_bytes else loaded.stream_bytes, stream_bytes, room, allOnPages(loaded) or enginePaged(loaded)); } /// Every stream on the pool's pages, the engine's own window idle (Qwen's TF_QWEN_KV_SHARE and TF_QWEN_KV_PAGES_ALL). @@ -171,7 +172,7 @@ pub fn budgetOf(comptime F: type, l: kv_pool.Layout, room: u64, o: api.Open, win probe.cache = std.math.maxInt(u64); const all = kv_pool.plan(l, probe) catch return out; const left = if (!engine_paged and out.window > 0) - room -| (@as(u64, all.lanes - 1) *| (l.fixed_bytes +| (l.pages(out.window) + l.runPages()) *| l.pageBytes())) + room -| (@as(u64, all.lanes - 1) *| (l.fixed_bytes +| (l.pages(out.window) + l.statePages()) *| l.pageBytes())) else all.snaps * l.snap_bytes + all.copied + all.kept; out.cache = budget.cacheBytes(null, left, 0); @@ -184,7 +185,7 @@ pub fn plan(comptime F: type, a: Allocator, l: kv_pool.Layout, room: u64, o: api return kv_pool.plan(l, budgetOf(F, l, room, o, window, host_mode, engine_paged, kept_ppm, slots)) catch |e| { problem.* = switch (e) { error.NoStream => if (engine_paged) try std.fmt.allocPrint(a, "the CUDA memory budget fits no stream beside the model: one at a {d}-token window takes {d:.2} GiB of KV pages, and the budget leaves {d:.2} GiB", .{ window, toGib(l.pages(window + rows) * l.pageBytes()), toGib(room) }) else "the CUDA memory budget fits no stream beside the model", - error.TooMany => try std.fmt.allocPrint(a, "--parallel {d} needs {d:.2} GiB for its other streams' fixed parts, state runs and a page each, and the CUDA memory budget leaves {d:.2} GiB: serve fewer, or free device memory", .{ o.lanes, toGib((o.lanes - 1) * (l.fixed_bytes + (1 + l.runPages()) * l.pageBytes())), toGib(room) }), + error.TooMany => try std.fmt.allocPrint(a, "--parallel {d} needs {d:.2} GiB for its other streams' fixed parts, state {s} and a page each, and the CUDA memory budget leaves {d:.2} GiB: serve fewer, or free device memory", .{ o.lanes, toGib((o.lanes - 1) * (l.fixed_bytes + (1 + l.statePages()) * l.pageBytes())), if (l.pieces == null) "runs" else "pages", toGib(room) }), }; return null; }; @@ -509,7 +510,6 @@ test "CUDA cache default scales pool copies after full stream windows without cu explicit.prompt_cache_gib = 0; try std.testing.expectEqual(@as(u64, 0), budgetOf(F, l, 88 * GiB, explicit, 6144, false, true, 0, null).cache); } - test "CUDA cache default leaves seven full windows beside an unpaged engine" { const GiB: u64 = 1 << 30; const l: kv_pool.Layout = .{ .fixed_bytes = 0, .token_bytes = 1 << 20, .page_tokens = 1, .snap_bytes = 0 }; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index a57bca7aaef..12147fb2498 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -303,6 +303,7 @@ const stock_rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_GATHER_EARLY", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (1: one pooled n-gram gather a shared pass; default 0)" }, .{ .name = "TF_FLASHNEXT_PROFILE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_VERIFY_HOST_LOGITS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_FLASHNEXT_STATE_PAGES", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0; 1 needs TF_FLASHNEXT_KV_PAGES)" }, .{ .name = "TF_FLASHNEXT_PREFILL_MTP_LEAN", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps only MTP KV/indexer caches during prefill)" }, .{ .name = "TF_FLASHNEXT_DRAFTS", .scope = .flashnext, .kind = .size, .forms = "a whole draft count from 0 to the native size maximum (default 6; clamped to 1 through 15)" }, .{ .name = "TF_FLASHNEXT_DRAFTS_GREEDY", .scope = .flashnext, .kind = .size, .forms = "a whole draft count from 0 to the native size maximum (default 8; clamped to 1 through 15)" }, diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 4722672f5d9..e734222846f 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 55 settings: 34 switches, 13 integers, 3 reals, 5 structured" { +test "Flash Next strict env: the table holds all 56 settings: 35 switches, 13 integers, 3 reals, 5 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_") or std.mem.startsWith(u8, r.name, "FZ_") or std.mem.eql(u8, r.name, "TENSORFOLD_CHECKPOINT_SHA256")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 34, 13, 3, 5 }, counts); + try t.expectEqual([4]usize{ 35, 13, 3, 5 }, counts); } test "Flash Next strict env: unset reads the caller default and every row keeps its blank contract" { diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 934a901b980..cc87945dba6 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -265,6 +265,19 @@ test "environment: LFM2's and LFM3's page switches are exact 0 or 1, refused by } } +test "environment: TF_FLASHNEXT_STATE_PAGES is exact 0 or 1, refused when Flash Next loads, before any device work" { + const name = "TF_FLASHNEXT_STATE_PAGES"; + for ([_][]const u8{ "off", "false", "no", "on", "true", "yes", "2", " 0", "1 ", "01" }) |raw| { + try t.expectError(error.InvalidEnvironment, e.parse(name, raw)); + const why = (try e.refusal(a, Env{ .name = name, .raw = raw }, .{ .flashnext = true })).?; + defer a.free(why); + try t.expect(std.mem.indexOf(u8, why, name) != null); + try t.expect((try e.refusal(a, Env{ .name = name, .raw = raw }, .{ .cuda = true })) == null); + } + try t.expect(!try e.value(bool, name, null, false)); + try t.expect(try e.value(bool, name, "1", false)); +} + test "environment: real settings are finite, keep their lower bound and optional cap, and read as floats" { try t.expectEqual(@as(f64, 3.25), try e.value(f64, "TF_DSV41_GRAPH_FLOOR_GIB", "3.25", 0)); try t.expectEqual(@as(f64, 0), try e.value(f64, "TF_DSV41_GRAPH_FLOOR_GIB", "0", 1)); diff --git a/zig/src/platform/environment_valid_cases.zig b/zig/src/platform/environment_valid_cases.zig index 408801fb037..4b98e37f8a0 100644 --- a/zig/src/platform/environment_valid_cases.zig +++ b/zig/src/platform/environment_valid_cases.zig @@ -184,6 +184,8 @@ pub const valid = [_]Case{ .{ .name = "TF_Q35_DFLASH_ABSORB_BATCH", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .raw = "1", .n = 1 }, + .{ .name = "TF_FLASHNEXT_STATE_PAGES", .raw = "0", .n = 0 }, + .{ .name = "TF_FLASHNEXT_STATE_PAGES", .raw = "1", .n = 1 }, .{ .name = "TENSORFOLD_LFM3_KV_PAGES", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_LFM3_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_ROCE_GID_INDEX", .raw = "2147483647", .n = 2147483647 }, diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index af194a556aa..f2ad2898238 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -120,7 +120,7 @@ zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95 zig/src/cuda/vit.zig 222f8151384518297c157e6dd270c04674ae288d8a180e5e1d117a5ce41c86ed raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention); #4127: pointwiseGamma launches tf_vit_pointwise_gamma for Inkling 2's layer scale zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig 318500bd273d45ed2a2021252ee447e0a25a390f85c7534a79d9781883e19301 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged; this change: a one-rank prompt chunk before the last that nothing taps skips its last layer's MLP stream and experts, which head(.none) never reads; outputs unchanged -zig/src/families/flashnext/cuda_batch_state.zig 6dbb21651fc1d68bf466e83c0a6b8c2f7e3787ea033acb9534b1c8bc8bd753a8 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; #3368 (the scratch sized by the checkpoint's slot count and shared width; default-shape replies unchanged); y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL); hc_part holds a trainer's kept read-out (keep_rows) +zig/src/families/flashnext/cuda_batch_state.zig 6dbb21651fc1d68bf466e83c0a6b8c2f7e3787ea033acb9534b1c8bc8bd753a8 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; #3368 (the scratch sized by the checkpoint's slot count and shared width; default-shape replies unchanged); y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged; #4544 (opt-in TF_FLASHNEXT_GRAPH_TAIL); hc_part holds a trainer's kept read-out (keep_rows) zig/src/families/flashnext/cuda_collective.zig 06e373706605a3929f2bb9d07412200e14a38afa9c58210bd493e9f20d678941 raw adds sumBlock, the in-place FP32 reduce-scatter with sum's peer check, deadline and abort; no served change on its own; #2974: stage plain round inputs before capture/replay and release its executable before communicator abort zig/src/families/flashnext/cuda_compare_main.zig ade014dfec88f0b386076cdc093ea20710d7bf36c33ff566ca2caf472064695b raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) zig/src/families/flashnext/cuda_config.zig 566b351b5fbb5a373e48e4e71486301bf362e9d9d6edfb600aa8e6484bcf17f0 raw #3368 (num_experts_per_tok and shared_expert_intermediate_size select a supported shape, any other refused by name; default-shape replies unchanged) @@ -135,9 +135,9 @@ zig/src/families/flashnext/cuda_images.zig 4696ef29dc81f30882f964d69a71c5378b247 zig/src/families/flashnext/cuda_images_test.zig 4278e5241f6c7e0e710e9a8ddf0482855db158eeee2463200a2c2de32c9dadd7 raw #3164 (resumed image rows tested) zig/src/families/flashnext/cuda_lanes.zig a181a74b11f82ef4e03116cf6d65d0fed56c9501ddadfae979099ba467ecfd21 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219, #2919 (the resolved rank and world reach visionBytes) zig/src/families/flashnext/cuda_lanes_admission_test.zig eef300305c40846de8d362f32d1f5274fd3896fa3959a658cf72b86a394949cc raw this branch: the admission test's capacity expects the load's window buffers (mtp.bufferRows()) -zig/src/families/flashnext/cuda_lanes_load.zig 0a02e4fa0de0b596c9b75164f414a039a0fa4424166b6b5a242d616476ca98df raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged; #3368 (a captured kernel set with another shape refused by name; default-shape replies unchanged); #3368 (a captured kernel set with another shape refused by name; default-shape replies unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3368 (a captured kernel set with another shape refused by name; the head load takes the engine's widths; default-shape replies unchanged); #4538 (draft KV cache bytes and dtype reported after the real load; scheduling unchanged); TFQ TP: admit mode == .tfq3 at --tp 2 alongside .modelopt +zig/src/families/flashnext/cuda_lanes_load.zig 20751c046dd0658163e7e46cda2fb1537936ee557921b80ee69101d32abfa9ff raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged; #3368 (a captured kernel set with another shape refused by name; default-shape replies unchanged); #3368 (a captured kernel set with another shape refused by name; default-shape replies unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3368 (a captured kernel set with another shape refused by name; the head load takes the engine's widths; default-shape replies unchanged); #4538 (draft KV cache bytes and dtype reported after the real load; scheduling unchanged); TFQ TP: admit mode == .tfq3 at --tp 2 alongside .modelopt; #2898: TF_FLASHNEXT_STATE_PAGES=1 places the state and MTP head on lease pages; off, every new branch is skipped and replies are unchanged zig/src/families/flashnext/cuda_lanes_restore_test.zig 7f0fb220570bb65e9f1212b8def2201a128390d69fb900db5a73d50360d36838 raw #2974: stage plain round inputs before capture/replay and release its executable before communicator abort -zig/src/families/flashnext/cuda_launch.zig d3a4157ae546144e70010ef46f0d294256aa506dfe39b31ead03eeb5397833c3 raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests; #3368 (topkMany takes the slot count, a captured set serves the default shape only; default-shape replies unchanged); exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests; D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL) +zig/src/families/flashnext/cuda_launch.zig d3a4157ae546144e70010ef46f0d294256aa506dfe39b31ead03eeb5397833c3 raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests; #3368 (topkMany takes the slot count, a captured set serves the default shape only; default-shape replies unchanged); exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests; #4544 (opt-in TF_FLASHNEXT_GRAPH_TAIL) zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw zig/src/families/flashnext/cuda_media_test.zig 4292f8f7c8f8bf4efd0dfaaa5a6c63e11568f85534127a0ce9feb0ab0be05120 raw zig/src/families/flashnext/cuda_mix.zig 248a2a86b3f377531f5b713c408ba99f73604510f4afe34ffae52615d5863c2c raw @@ -147,9 +147,9 @@ zig/src/families/flashnext/cuda_modelopt_experts.zig de779975629770b33ad5c0ebf9a zig/src/families/flashnext/cuda_moe.zig 87ba75343c1d228800ed9fcc6d933f1175df172c008e14a8c7a64ff7011bed44 raw zig/src/families/flashnext/cuda_mtp.zig acd317a915c6d25b2be1088a745fa61a322af3d7b01333fed55ceaca7099f827 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run), the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits, headBytes counts the split's scratch (split_bytes); #3368 (the MTP layer's shared width must be the main layers' or the routed width, refused by name otherwise; default-shape replies unchanged); #3368 (the MTP layer's shared width must be the main layers' or the routed width, refused by name otherwise; default-shape replies unchanged); main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, #3368 (the MTP layer's shared width must be the main layers' or the routed width, refused by name otherwise; the head takes the engine's widths, so config.json has one reader; default-shape replies unchanged); #3368 (the MTP layer's shared width must be the main layers' or the routed width, refused by name otherwise; the head takes the engine's widths, so config.json has one reader; default-shape replies unchanged); the head's byte estimate prices the shared expert at its gate_proj's width, so a 1280-wide one counts its 3,072,000 extra bytes (placement's 1 GiB allowance unchanged); #4529 (opt-in cache-only MTP prefill; default off) zig/src/families/flashnext/cuda_mtp_check.zig f5dc61929bdc9e0e968bde9dfed00f3e761c50281b29663a0f139a773deafc0b raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); probeServed and windowCheck sweep every width the buffers hold against their one-token steps; #3512: Flash Next settings through platform/environment.zig, malformed text refused at startup; valid values keep their meaning -zig/src/families/flashnext/cuda_mtp_draft.zig 3bbb3afb99068514b7f93a23560eeace3a643ba06aa28158fa4aa971c9819fcb raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader); a window's scores, best values and saved pieces size at the load's bufferRows(); main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader); D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL) +zig/src/families/flashnext/cuda_mtp_draft.zig 2ccad14446dadf62f650a2f3d1e804ef0155e1165a898d16742f3bbf41305c30 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader); a window's scores, best values and saved pieces size at the load's bufferRows(); main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader); #4544 (opt-in TF_FLASHNEXT_GRAPH_TAIL); #2898: TF_FLASHNEXT_STATE_PAGES=1 places the state and MTP head on lease pages; off, every new branch is skipped and replies are unchanged zig/src/families/flashnext/cuda_mtp_load.zig 2cef7eeb8c41490429079852b4a3a0659594930dac0cdddcbd1f1fe4a35095d6 raw main 3a56d4eb92 (the draft head's mode read through platform/environment.zig: unset or blank keeps affine4, bf16 keeps the stored rows; kernels and launch counts unchanged) -zig/src/families/flashnext/cuda_mtp_ops.zig 6523760755a3fde610590ec6eab4b5daaa34a3f81abceb93048aa1c273a3c0fa raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; a verify window's width is checked against the served window (mtp.rowsOk); main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL); main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; D1040 (opt-in TF_FLASHNEXT_GRAPH_TAIL); K28 adaptation (graph tail on one GPU only; TP keeps eager row best); #4529 (opt-in cache-only MTP prefill; default off); #5332 (lean pieces bounded by cap/4 and 3,072; default cap/2 unchanged) +zig/src/families/flashnext/cuda_mtp_ops.zig 9de9d3686500643bd0fbb7ad41eb32307bb8cc43074fe76773380e308536d5b8 raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; a verify window's width is checked against the served window (mtp.rowsOk); main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; #4544 (opt-in TF_FLASHNEXT_GRAPH_TAIL); main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; #4544 (opt-in TF_FLASHNEXT_GRAPH_TAIL); K28 adaptation (graph tail on one GPU only; TP keeps eager row best); #4529 (opt-in cache-only MTP prefill; default off); #5332 (lean pieces bounded by cap/4 and 3,072; default cap/2 unchanged); #2898: TF_FLASHNEXT_STATE_PAGES=1 places the state and MTP head on lease pages; off, every new branch is skipped and replies are unchanged zig/src/families/flashnext/cuda_norms.zig c6ca7f9c1a9049c0f9d512fe2a38c2672a2e96b5c060d6cec2bca0d39e34bad0 raw zig/src/families/flashnext/cuda_ple.zig 67a72c1b98802b07ea2fb136a52fac017b632eceb761315292102a890555b229 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); the shared pass gathers its lanes in one pool call (Split and part reachable from cuda_ple_gather_lanes.zig); every row is the per-stream call's; #5188 (environment settings through the registry; accepted values and replies unchanged); #3512: Flash Next settings through platform/environment.zig, malformed text refused at startup; valid values keep their meaning zig/src/families/flashnext/cuda_ple_check.zig e8b7cac1e0d3718f106482f6cff7375c0063e1757c46814bd40da435c83ba8ed raw @@ -191,4 +191,4 @@ zig/src/families/inkling2/metal/backend.zig a044a05d061fc524c911208c6a8a47637c26 zig/src/families/inkling2/metal/forward_final.zig 51f7d543c16cd18133860dc8ac3c1381a90be52605913005d229c2770e64c1fd raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun zig/src/families/inkling2/metal/prefill_chunks.zig 8767fb1051541768f2ec0420013030d723697b3fa04a63312ec9d61340d5ba69 raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun zig/src/families/inkling2/metal/prefill_feed.zig 3f361563fa08f5fbc206f4c3519601b44b503a0e400dfdc25835a866a44d30bd raw #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun -zig/src/platform/environment.zig 40b2ad16af33bb1e3ff5c02a283273fa2c9d07a81873e003625410b3911431d6 raw #6396: TF_QWEN4_PROFILE registered (diagnostic, off by default); #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun +zig/src/platform/environment.zig b718adb05f32aff3a4f5d2282ae7772fed888306702d885a611f45d9fb357fbe raw #6396: TF_QWEN4_PROFILE registered (diagnostic, off by default); #5693: opt-in queued prompt chunks; main decode and relative-bias paths retained; device equality and timing unrun