From a0ffda1abe7314141e2ca2fe96f66db88ba37b4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:40:28 +0000 Subject: [PATCH 1/7] gemma4 cuda: the global layers' caches in pages of the core pool, every stream leasing; sliding layers keep their rings The window_pages kernels already read keys and values through a slot's page table at head dim 512, so this changes only where the global caches live and who writes them; no kernel changes. - A page is 256 positions (window_attention.page_unit: a decode chunk, whole prompt tiles) of every global layer's K and V; the arena holds each layer's K region, then its V region, page id p at rows [256 p, ...). - Loaded.layout with engine_paged, as lfm2_moe's and Dory's: open makes one slot's rings, the host plans the pool and calls attach (the arena, the slots' rings and tables). A stream is promised its prompt, reply and one verify window at its prompt pass, takes pages as its rows reach them and gives them back when it ends; fits is the host's admission. The idle server logs the pool's census. - Writes: the rows kernel writes no global cache when paged; tf_wrows_put copies its k and v rows (the same bits it would have stored) into the pages. - The decode and prompt windows of the global layers carry pg, in the target forward and in the assistant, which reads the target's pages through the same table. Kept states stay copies: a global layer's rows are walked through the slot's pages. - TENSORFOLD_GEMMA4_KV_PAGES=0 (or Options.kv_pages = false) keeps the linear caches made at open. tf-cuda-test gemma4-pages MODEL TEXT N [DRAFTER] runs the same prompts on linear and paged caches (pages leased in a shuffled order, a pool the ended streams' pages must be reused from) and wants the same replies and last-row logits, solo, sampled, two streams in a round and resumed from a kept state. --- zig/src/families/gemma4/cuda_backend.zig | 25 +++ zig/src/families/gemma4/cuda_native.zig | 12 +- zig/src/families/gemma4/cuda_snap.zig | 26 ++++ zig/tests/cuda/gemma4_pages_tests.zig | 190 +++++++++++++++++++++++ zig/tests/cuda/main.zig | 2 + 5 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 zig/tests/cuda/gemma4_pages_tests.zig diff --git a/zig/src/families/gemma4/cuda_backend.zig b/zig/src/families/gemma4/cuda_backend.zig index 70f2b19a3db..98ada265587 100644 --- a/zig/src/families/gemma4/cuda_backend.zig +++ b/zig/src/families/gemma4/cuda_backend.zig @@ -19,6 +19,8 @@ pub const prompt_rows = fwd.prompt_rows; pub const round_rows = fwd.round_rows; /// The widest window a stream verifies: one-row steps and every wider window give a row the same bits. pub const max_window = 16; +/// Pages a request holds at most: its prompt, its reply and one last verify window (cuda_shared.zig). +pub const pagesFor = shared.pagesFor; /// Drawn tokens a handle names (a ring; read before the round loop could wrap it). const ring = 1024; @@ -100,6 +102,12 @@ pub const Gemma = struct { return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .free = free, .tok = tok, .picks = picks, .greedy = greedy, .meta = meta, .slot_bufs = bufs }; } + /// The pool's free pages in a seeded random order, leased in that order (a check's hook). + pub fn shufflePages(x: *Gemma, seed: u64) void { + var prng = std.Random.DefaultPrng.init(seed); + if (x.pool) |*p| prng.random().shuffle(u32, p.free[0..p.nfree]); + } + pub fn deinit(x: *Gemma) void { var it = x.lanes.valueIterator(); while (it.next()) |l| { @@ -533,9 +541,19 @@ pub const Gemma = struct { x.s.synchronize() catch {}; b.free(); } + if (x.lanes.count() == 0) x.report(); } } + /// The idle server's line: nothing promised, every page free (kept states are copies, not pages). + fn report(x: *const Gemma) void { + if (@import("builtin").is_test) return; + const p = x.pool orelse return; + const c = p.census(); + const ok = p.idle() and c.free == c.total; + std.log.info("kv pool idle{s}: promised {d}, free {d} + store {d} == total {d}", .{ if (ok) "" else " (UNEVEN)", c.promised, c.free, c.kept, c.total }); + } + fn release(ptr: *anyopaque, s: *Stream) void { self(ptr).dropLane(s); } @@ -591,3 +609,10 @@ test "shared head costs: Gemma CUDA assistant and DFlash retain costed copy gran b.m = &m; try @import("cuda_head_cost_test.zig").check(b.facts()); } + +test "a request holds its prompt, its reply and one verify window in whole pages of 256 positions" { + try std.testing.expectEqual(@as(usize, 1), pagesFor(1, 1)); + try std.testing.expectEqual(@as(usize, 1), pagesFor(200, 40)); + try std.testing.expectEqual(@as(usize, 2), pagesFor(200, 41)); + try std.testing.expectEqual(@as(usize, 129), pagesFor(32768, 0)); +} diff --git a/zig/src/families/gemma4/cuda_native.zig b/zig/src/families/gemma4/cuda_native.zig index 93affff172d..b9a6e9f335b 100644 --- a/zig/src/families/gemma4/cuda_native.zig +++ b/zig/src/families/gemma4/cuda_native.zig @@ -52,8 +52,8 @@ const native = @This(); /// The server's reading of the room left after the weights; null if unreadable. pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -/// No `precision` field: the server refuses --precision for this family by name. --vision: the 12B's image embedder. -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null, vision: ?cv.Limits = null, drafter: ?[]const u8 = null }; +/// No `precision` field (refused by name). --vision: the 12B's embedder. kv_pages false, or the env =0: linear caches. +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null, vision: ?cv.Limits = null, drafter: ?[]const u8 = null, kv_pages: bool = true }; pub const Loaded = struct { backend: lanes.backend.Backend, @@ -97,6 +97,11 @@ const Plan = struct { } }; +/// Whether the global layers' caches lease the pool's pages: asked, and not turned off by TENSORFOLD_GEMMA4_KV_PAGES=0. +fn pagesOn(o: Options) bool { + return o.kv_pages and !envOff("TENSORFOLD_GEMMA4_KV_PAGES"); +} + /// The device bytes of the image path's workspace (the 31B's tower or the 12B's embedder), 0 without --vision. fn visionBytes(vision: bool, tower: bool) u64 { if (!vision) return 0; @@ -123,7 +128,8 @@ fn positions(context: usize) usize { pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { if (kernels != null) return error.CapturedKernels; if (o.lanes_fixed and o.lanes > be.round_rows) return error.ParallelPastRound; - const paged = try @import("core").kv_prompts.sharing() > 0; + // TF_KV_SHARE keeps prompts as the pool's pages, so it pages too; otherwise the default, unless turned off + const paged = try @import("core").kv_prompts.sharing() > 0 or pagesOn(o); const own = try gpa.create(Owned); errdefer gpa.destroy(own); own.* = .{ .gpa = gpa, .w = undefined, .k = undefined, .s = undefined, .m = undefined, .gb = undefined }; diff --git a/zig/src/families/gemma4/cuda_snap.zig b/zig/src/families/gemma4/cuda_snap.zig index df3a22e7690..b561b0a54e8 100644 --- a/zig/src/families/gemma4/cuda_snap.zig +++ b/zig/src/families/gemma4/cuda_snap.zig @@ -181,3 +181,29 @@ test "a state holds global layers' positions and each sliding ring's last window const last = runs.items[runs.items.len - 1]; try testing.expectEqual([3]usize{ (12 << 30) + 4096 * gb, 2 * 5 * 1023 * sb + at * gb, at * gb }, last); } + +test "a paged state takes a global layer's positions through the slot's pages, a run a page, in position order" { + var k = [_]u64{ 1 << 30, 2 << 30, 3 << 30, 4 << 30, 5 << 30, 6 << 30 }; + var v = [_]u64{ 7 << 30, 8 << 30, 9 << 30, 10 << 30, 11 << 30, 12 << 30 }; + var ids = [_]u32{ 0, 0, 0, 0, 7, 2, 9, 0 }; // slot 1's row: pages 7, 2, 9, then unmapped + var m: fwd.Model = undefined; + m.geo = cfg.unified12b; + m.layers = 6; // layer 5 is global + m.context = 4 * fwd.pages.tokens; + m.paged = true; + m.ids = &ids; + m.kc = &k; + m.vc = &v; + const at = 2 * fwd.pages.tokens + 10; // pages 7 and 2 whole, then 10 rows of page 9 + const gb = 1 * 512 * 2; + var runs: std.ArrayList([3]usize) = .empty; + defer runs.deinit(testing.allocator); + try each(&m, 1, at, 0, Count{ .runs = &runs }, Count.add); + try testing.expectEqual(@as(usize, 5 * 2 + 2 * 3), runs.items.len); // a sliding cache's 522 rows: one run each + const pt = fwd.pages.tokens; + const kr = runs.items[runs.items.len - 6 ..][0..3]; + try testing.expectEqual([3]usize{ (6 << 30) + 7 * pt * gb, kr[0][1], pt * gb }, kr[0]); + try testing.expectEqual([3]usize{ (6 << 30) + 2 * pt * gb, kr[0][1] + pt * gb, pt * gb }, kr[1]); + try testing.expectEqual([3]usize{ (6 << 30) + 9 * pt * gb, kr[0][1] + 2 * pt * gb, 10 * gb }, kr[2]); + try testing.expectEqual(bytes(&m, at), runs.items[runs.items.len - 1][1] + runs.items[runs.items.len - 1][2]); +} diff --git a/zig/tests/cuda/gemma4_pages_tests.zig b/zig/tests/cuda/gemma4_pages_tests.zig new file mode 100644 index 00000000000..45b7ac2a86b --- /dev/null +++ b/zig/tests/cuda/gemma4_pages_tests.zig @@ -0,0 +1,190 @@ +//! Gemma 4's global caches as pool pages against linear ones: replies and last-row logits byte-equal, pages reused. +const std = @import("std"); +const core = @import("core"); +const lanes = @import("lanes"); +const g4 = @import("gemma4_cuda"); +const check = @import("check.zig"); +const Gpu = check.Gpu; + +const native = g4.native31; +const snap = g4.snap; +const be = g4.backend; + +/// Prompt lengths: inside one page, across pages and the 512-row chunk grid, and one more through freed pages. +const lens = [_]usize{ 200, 1300, 700 }; +/// A kept state inside the second prompt: off the chunk grid and the page grid. +const mark: u32 = 1000; + +const Out = struct { ids: []u32, logits: []u8, cached: u64 }; +const Result = struct { solo: [lens.len]Out, sampled: Out, pair: [2][]u32, resumed: Out }; +const Opened = @typeInfo(@typeInfo(@TypeOf(native.openDrafter)).@"fn".return_type.?).error_union.payload; + +const Keep = struct { + gb: *be.Gemma, + saved: ?*snap.Saved = null, + fn hook(ptr: *anyopaque, s: *lanes.Stream, at: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + if (at == mark) k.saved = k.gb.saveState(s, at) catch null; + } +}; + +const Case = struct { prompt: []const u32, drafts: bool, sampling: ?lanes.Sampling = null, reuse: lanes.stream.Reuse = .{} }; + +/// One stream, its prompt stepped as the lane host runs it: reply, last-row logits, rows resumed. +fn run(gpu: Gpu, engine: *lanes.Engine, gb: *be.Gemma, c: Case, count: u32) !Out { + const gpa = gpu.gpa; + var s = try lanes.Stream.init(gpa, .{ .id = "g", .prompt = c.prompt, .max_new = count, .sampling = c.sampling, .drafts = c.drafts, .reuse = c.reuse }); + defer s.deinit(gpa); + var first = true; + while (!try engine.fillStream(&s, first)) first = false; + const logits = try gpa.alloc(u8, g4.config.vocab * 2); + errdefer gpa.free(logits); + try gb.s.synchronize(); + const l = gb.lanes.get(&s) orelse return error.UnknownStream; + try gb.d.check(gb.d.api.cuMemcpyDtoH_v2(logits.ptr, l.last, logits.len), "cuMemcpyDtoH"); + while (engine.activeCount() > 0) try engine.step(); + try idle(gb); + return .{ .ids = try gpa.dupe(u32, s.emitted()), .logits = logits, .cached = if (s.reuse_failed) 0 else s.cached }; +} + +/// Two streams in shared rounds: their replies. +fn pair(gpu: Gpu, engine: *lanes.Engine, gb: *be.Gemma, a: []const u32, b: []const u32, drafts: bool, count: u32) ![2][]u32 { + const gpa = gpu.gpa; + var sa = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = a, .max_new = count, .drafts = drafts }); + defer sa.deinit(gpa); + var sb = try lanes.Stream.init(gpa, .{ .id = "b", .prompt = b, .max_new = count, .drafts = drafts }); + defer sb.deinit(gpa); + for ([_]*lanes.Stream{ &sa, &sb }) |s| { + var first = true; + while (!try engine.fillStream(s, first)) first = false; + } + while (engine.activeCount() > 0) try engine.step(); + try idle(gb); + const ra = try gpa.dupe(u32, sa.emitted()); + errdefer gpa.free(ra); + return .{ ra, try gpa.dupe(u32, sb.emitted()) }; +} + +/// Paged: every stream ended, so nothing is promised and every page is free again. +fn idle(gb: *const be.Gemma) !void { + const p = gb.pool orelse return; + const c = p.census(); + try check.expect(p.idle() and c.free == c.total, "gemma4 pages: the idle pool holds promised {d}, free {d} of {d}", .{ c.promised, c.free, c.total }); +} + +fn free(gpa: std.mem.Allocator, o: Out) void { + gpa.free(o.ids); + gpa.free(o.logits); +} + +fn freeResult(gpa: std.mem.Allocator, r: Result) void { + for (r.solo) |o| free(gpa, o); + free(gpa, r.sampled); + for (r.pair) |p| gpa.free(p); + free(gpa, r.resumed); +} + +/// One model with linear or paged global caches through every case. +fn pass(gpu: Gpu, model: []const u8, drafter: ?[]const u8, paged: bool, prompts: [lens.len][]const u32, scrub: []const u32, count: u32) !Result { + const gpa = gpu.gpa; + var loaded = try native.open(gpa, gpu.io, gpu.ctx, model, null, .{ .context = 8192, .drafts = drafter != null, .lanes = 2, .drafter = drafter, .kv_pages = paged }); + defer loaded.deinit(loaded.ctx); + try check.expect((loaded.layout != null) == paged, "gemma4 pages: open made the caches asked for", .{}); + var opened: ?Opened = null; + defer if (opened) |o| o.close(o.ctx); + if (drafter) |dir| opened = try native.openDrafter(gpa, gpu.io, loaded.ctx, dir, 4); + const gb = loaded.target; + if (paged) { // the two widest requests at once; the rest lease pages the ended ones gave back, in a shuffled order + const pool = be.pagesFor(lens[0], count) + be.pagesFor(lens[1], count); + var sequential: usize = 0; + for (lens) |n| sequential += be.pagesFor(n, count); + try check.expect(sequential > pool, "gemma4 pages: the solo runs take more pages than the pool holds", .{}); + try native.attach(loaded.ctx, 1, pool); + gb.shufflePages(0x6e4); + } + var drafted: ?lanes.drafted.Drafted = if (opened) |o| try lanes.drafted.Drafted.init(gpa, loaded.backend, o.drafter) else null; + defer if (drafted) |*d| d.deinit(); + const facts = if (drafted) |*d| d.facts(loaded.facts) else loaded.facts; + var cfg = try lanes.Config.init(gpa, facts, loaded.rows, loaded.rows - 1); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, if (drafted) |*d| d.backend() else loaded.backend, clock.clock()); + defer engine.deinit(); + const drafts = drafter != null; + + var r: Result = undefined; + var made: usize = 0; + errdefer for (r.solo[0..made]) |o| free(gpa, o); + for (prompts, &r.solo) |p, *o| { + o.* = try run(gpu, &engine, gb, .{ .prompt = p, .drafts = drafts }, count); + made += 1; + } + const sp: lanes.Sampling = .{ .seed = 3, .temperature = 1.0, .top_k = 0, .top_p = 0.95 }; + r.sampled = try run(gpu, &engine, gb, .{ .prompt = prompts[1], .drafts = drafts, .sampling = sp }, count); + errdefer free(gpa, r.sampled); + r.pair = try pair(gpu, &engine, gb, prompts[0], prompts[1], drafts, count); + errdefer for (r.pair) |p| gpa.free(p); + // a state kept at the mark, another prompt through the slot, then the prompt resumed from it + var keep: Keep = .{ .gb = gb }; + defer if (keep.saved) |v| gb.dropState(v); + var ms = [_]u32{mark}; + const kept = try run(gpu, &engine, gb, .{ .prompt = prompts[1][0 .. mark + 100], .drafts = drafts, .reuse = .{ .marks = &ms, .hook = .{ .ptr = &keep, .at = Keep.hook } } }, 2); // two: a reply of one ends at its first token + free(gpa, kept); + const v = keep.saved orelse return error.NothingKept; + free(gpa, try run(gpu, &engine, gb, .{ .prompt = scrub, .drafts = drafts }, 2)); + r.resumed = try run(gpu, &engine, gb, .{ .prompt = prompts[1], .drafts = drafts, .reuse = .{ .saved = v, .at = mark } }, count); + return r; +} + +fn same(bad: *usize, what: []const u8, a: []const u8, b: []const u8) void { + const eq = std.mem.eql(u8, a, b); + if (!eq) bad.* += 1; + std.debug.print("RESULT gemma4 pages {s}: {s}\n", .{ what, if (eq) "same" else "DIFFER" }); +} + +/// tf-cuda-test gemma4-pages MODEL TEXT N [DRAFTER]: paged global caches give the linear caches' bytes, case by case. +pub fn pages(gpu: Gpu, rest: []const []const u8) !void { + if (rest.len < 3) return error.MissingArguments; + const gpa = gpu.gpa; + const count = try std.fmt.parseInt(u32, rest[2], 10); + const drafter: ?[]const u8 = if (rest.len > 3) rest[3] else null; + var tok = try core.tokenizer.loadTokenizer(gpu.io, gpa, rest[0]); + defer tok.deinit(); + const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, rest[1], gpa, .limited(1 << 26)); + defer gpa.free(text); + const enc = try tok.encode(gpa, text); + defer gpa.free(enc); + if (enc.len == 0) return error.EmptyText; + var buf: [lens.len + 1][lens[1]]u32 = undefined; + var prompts: [lens.len][]const u32 = undefined; + for (&buf, 0..) |*b, j| { // each prompt from its own place in the text; the last is the scrub's + b[0] = 2; + for (b[1..], 0..) |*t, i| t.* = enc[(i + 977 * j) % enc.len]; + } + for (&prompts, lens, 0..) |*p, n, j| p.* = buf[j][0..n]; + const scrub = buf[lens.len][0..lens[2]]; + + const linear = try pass(gpu, rest[0], drafter, false, prompts, scrub, count); + defer freeResult(gpa, linear); + const paged = try pass(gpu, rest[0], drafter, true, prompts, scrub, count); + defer freeResult(gpa, paged); + var bad: usize = 0; + var what: [96]u8 = undefined; + for (linear.solo, paged.solo, lens) |a, b, n| { + same(&bad, try std.fmt.bufPrint(&what, "prompt of {d}: reply", .{n}), std.mem.sliceAsBytes(a.ids), std.mem.sliceAsBytes(b.ids)); + same(&bad, try std.fmt.bufPrint(&what, "prompt of {d}: last-row logits", .{n}), a.logits, b.logits); + } + same(&bad, "sampled reply", std.mem.sliceAsBytes(linear.sampled.ids), std.mem.sliceAsBytes(paged.sampled.ids)); + same(&bad, "sampled last-row logits", linear.sampled.logits, paged.sampled.logits); + for (linear.pair, paged.pair, 0..) |a, b, i| { + same(&bad, try std.fmt.bufPrint(&what, "two streams, stream {d}: reply", .{i}), std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); + same(&bad, try std.fmt.bufPrint(&what, "two streams, stream {d}: paged == its solo reply", .{i}), std.mem.sliceAsBytes(b), std.mem.sliceAsBytes(paged.solo[i].ids)); + } + same(&bad, "resumed at the mark: reply", std.mem.sliceAsBytes(linear.resumed.ids), std.mem.sliceAsBytes(paged.resumed.ids)); + same(&bad, "resumed at the mark: last-row logits", linear.resumed.logits, paged.resumed.logits); + same(&bad, "paged resumed == paged fresh", std.mem.sliceAsBytes(paged.resumed.ids), std.mem.sliceAsBytes(paged.solo[1].ids)); + if (paged.resumed.cached != mark or linear.resumed.cached != mark) bad += 1; + std.debug.print("RESULT gemma4 pages resumed rows: linear {d}, paged {d} (want {d})\n", .{ linear.resumed.cached, paged.resumed.cached, mark }); + try check.expect(bad == 0, "gemma4 pages: {d} checks failed", .{bad}); + check.pass("gemma4 pages: global caches in shuffled pool pages give the linear caches' replies and logits ({d} tokens{s}), shared rounds and a kept state's resume included, ended streams' pages reused", .{ count, if (drafter != null) ", drafted" else "" }); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 66f0e530349..8d6325bcc52 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -274,6 +274,7 @@ const usage = \\ dory-prefill MODEL LOOPS TEXT N Dory prompt time alone at 512, 2k, 8k and 16k rows (DORY_PAGED=1: on pages) \\ gemma4-states MODEL DRAFTER TEXT N Gemma 4 + DFlash: stepped passes keep the drafter's context, resumed == fresh \\ spark25-pages MODEL TEXT N Spark2.5: full-layer caches in pool pages == linear ones, replies and logits + \\ gemma4-pages MODEL TEXT N [DRAFTER] Gemma 4: global caches in pool pages == linear ones, replies and logits \\ kolibri-reference MODEL IDS Kolibri-1's layer 0 and head against float64 from the checkpoint (prompt and decode rows) \\ kolibri-layers MODEL IDS Kolibri-1's window edge (513 keys) and its fifth layer's full reach, on the checkpoint \\ kolibri-full MODEL IDS N Kolibri-1: eager rows, steps, drafted, sampled, shared rounds, cuts and kept states alike @@ -515,6 +516,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.startsWith(u8, cmd, "dory-")) return dory_serve.run(gpu, cmd, rest); if (std.mem.eql(u8, cmd, "gemma4-states")) return @import("gemma4_states_tests.zig").states(gpu, rest); if (std.mem.eql(u8, cmd, "spark25-pages")) return @import("spark25_pages_tests.zig").pages(gpu, rest); + if (std.mem.eql(u8, cmd, "gemma4-pages")) return @import("gemma4_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "dory")) return dory_tests.greedy(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "kolibri-reference")) return kolibri_layer_tests.reference(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-layers")) return kolibri_layer_tests.layers(gpu, try arg(rest, 0), try arg(rest, 1)); From f36ed96f35e85a837284bb5f9980bb4670249f77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:38:20 +0100 Subject: [PATCH 2/7] gemma4 states check: a paged model attaches its pool (both lanes' widest) before the passes --- zig/tests/cuda/gemma4_states_tests.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/tests/cuda/gemma4_states_tests.zig b/zig/tests/cuda/gemma4_states_tests.zig index 65a45066063..4ac521de53a 100644 --- a/zig/tests/cuda/gemma4_states_tests.zig +++ b/zig/tests/cuda/gemma4_states_tests.zig @@ -56,6 +56,7 @@ pub fn states(gpu: Gpu, rest: []const []const u8) !void { defer loaded.deinit(loaded.ctx); const opened = try native.openDrafter(gpa, gpu.io, loaded.ctx, rest[1], 4); defer opened.close(opened.ctx); + if (loaded.layout != null) try native.attach(loaded.ctx, 1, 2 * g4.backend.pagesFor(8192, 0)); // paged: both lanes' widest var drafted = try lanes.drafted.Drafted.init(gpa, loaded.backend, opened.drafter); defer drafted.deinit(); const facts = drafted.facts(loaded.facts); From 19ca89b79430dcec06f503083955fe7cb824dc34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:11:58 +0100 Subject: [PATCH 3/7] cuda: paged decode reads take a tile's page once a tile, not once a key (tree attention and head dim 512 _pg kernels), SASS of the others unchanged --- zig/kernels/cuda/tree_attention.cu | 13 ++++++++++++- zig/kernels/cuda/window_rows512.cuh | 14 ++++++++++++++ .../core/contract/registry_shared_attention.zig | 12 ++++++------ zig/src/core/contract/window_rows_records.zig | 2 +- 4 files changed, 33 insertions(+), 8 deletions(-) diff --git a/zig/kernels/cuda/tree_attention.cu b/zig/kernels/cuda/tree_attention.cu index a0c818960fd..3b2b79cbf24 100644 --- a/zig/kernels/cuda/tree_attention.cu +++ b/zig/kernels/cuda/tree_attention.cu @@ -121,12 +121,23 @@ __device__ __forceinline__ bool tree_group( // tile t's keys and values into stage st (committed keys, then the row's path), one cp.async group auto load = [&](int t, int st) { uint4* const kd = kv0 + st * 2 * HB * C; + // PG: a tile's committed keys in one page take its row once a tile (the same addresses as committed()) + const int kt = t * HB; + int64_t tile = -1; + if constexpr (sizeof...(P) != 0) { + const Pg& g = (pg, ...); + if (kt < p && kt % g.tok + HB <= g.tok) + tile = (int64_t)g.tab[s * g.stride + kt / g.tok] * g.page + ((int64_t)(kt % g.tok) * hk + kh) * D; + } for (int i = lane; i < HB * C; i += 32) { const int key = t * HB + i / C; const bool in = key < k1; const __nv_bfloat16* ksrc; const __nv_bfloat16* vsrc; - if (key < p) { + if (key < p && tile >= 0) { + ksrc = kc + tile + (int64_t)(key - kt) * hk * D; + vsrc = vc + tile + (int64_t)(key - kt) * hk * D; + } else if (key < p) { ksrc = committed(kc, key); vsrc = committed(vc, key); } else { // the row's own path: key p + j is path row j diff --git a/zig/kernels/cuda/window_rows512.cuh b/zig/kernels/cuda/window_rows512.cuh index e5c962009ef..5e6d5ff3028 100644 --- a/zig/kernels/cuda/window_rows512.cuh +++ b/zig/kernels/cuda/window_rows512.cuh @@ -42,11 +42,25 @@ __device__ __forceinline__ void part_staged(const __nv_bfloat16* __restrict__ q, constexpr bool busy = true; const auto stage = [&](const __nv_bfloat16* cache, int t) { uint4* dst = tiles + (t % NSG) * TK * C; + // PG: a tile's keys in one page take its row once a tile (the same addresses as a page a key) + int64_t tile = -1; + if constexpr (sizeof...(P) != 0) { + const Pg& g = (pg, ...); + const int a = k0 + t * TK, b = k0 + min(t * TK + TK - 1, nk - 1); + if (a / g.tok == b / g.tok) + tile = g.tab[(slot != nullptr ? slot[r] : 0) * g.stride + a / g.tok] * g.page + + (static_cast(a % g.tok) * hk + kh) * D; + } for (int i = threadIdx.x; i < TK * C; i += NT) { const int jj = t * TK + i / C; if constexpr (sizeof...(P) != 0) { // a page a key: any tok, a tile may cross pages const Pg& g = (pg, ...); const int key = k0 + min(jj, nk - 1); + if (tile >= 0) { + cp16z(dst + i, cache + tile + (static_cast(key - k0 - t * TK) * hk * D) + (i % C) * 8, + jj < nk); + continue; + } const int64_t id = g.tab[(slot != nullptr ? slot[r] : 0) * g.stride + key / g.tok]; cp16z(dst + i, cache + id * g.page + (static_cast(key % g.tok) * hk + kh) * D + (i % C) * 8, jj < nk); diff --git a/zig/src/core/contract/registry_shared_attention.zig b/zig/src/core/contract/registry_shared_attention.zig index e2dc834d58a..7801fb9216e 100644 --- a/zig/src/core/contract/registry_shared_attention.zig +++ b/zig/src/core/contract/registry_shared_attention.zig @@ -17,12 +17,12 @@ pub fn records(comptime Record: type) [39]Record { .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1", .symbol = "tf_tree_part_256_w1", .image = "tree_attention", .threads = 32, .dynamic = 40960, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 253, .static = 0, .bound = 32 }, .{ .regs = 253, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_part_256_w1s3", .symbol = "tf_tree_part_256_w1s3", .image = "tree_attention", .threads = 32, .dynamic = 57344, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 251, .static = 0, .bound = 32 }, .{ .regs = 251, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_merge", .symbol = "tf_tree_merge", .image = "tree_attention", .threads = 256 }, .usage = .{ .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 114, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_shared_pg", .symbol = "tf_tree_shared_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 199, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 }, .{ .regs = 208, .static = 0, .bound = 128 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_shared_w1_pg", .symbol = "tf_tree_shared_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 195, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_shared_w1s3_pg", .symbol = "tf_tree_shared_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 192, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_part_pg", .symbol = "tf_tree_part_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 204, .static = 0, .bound = 128 }, .{ .regs = 204, .static = 0, .bound = 128 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_part_w1_pg", .symbol = "tf_tree_part_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, - .{ .launch = .{ .name = "tree attention tf_tree_part_w1s3_pg", .symbol = "tf_tree_part_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 199, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_pg", .symbol = "tf_tree_shared_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 195, .static = 0, .bound = 128 }, .{ .regs = 195, .static = 0, .bound = 128 }, .{ .regs = 195, .static = 0, .bound = 128 }, .{ .regs = 192, .static = 0, .bound = 128 }, .{ .regs = 192, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_w1_pg", .symbol = "tf_tree_shared_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_shared_w1s3_pg", .symbol = "tf_tree_shared_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 193, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 }, .{ .regs = 168, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_pg", .symbol = "tf_tree_part_pg", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 198, .static = 0, .bound = 128 }, .{ .regs = 198, .static = 0, .bound = 128 }, .{ .regs = 198, .static = 0, .bound = 128 }, .{ .regs = 215, .static = 0, .bound = 128 }, .{ .regs = 215, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_w1_pg", .symbol = "tf_tree_part_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 196, .static = 0, .bound = 32 }, .{ .regs = 196, .static = 0, .bound = 32 }, .{ .regs = 196, .static = 0, .bound = 32 }, .{ .regs = 189, .static = 0, .bound = 32 }, .{ .regs = 189, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "tree attention tf_tree_part_w1s3_pg", .symbol = "tf_tree_part_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 49152, .opt_in = true }, .usage = .{ .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 198, .static = 0, .bound = 32 }, .{ .regs = 191, .static = 0, .bound = 32 }, .{ .regs = 191, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_shared_256_pg", .symbol = "tf_tree_shared_256_pg", .image = "tree_attention", .threads = 128, .dynamic = 73728, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "tree attention tf_tree_shared_256_w1_pg", .symbol = "tf_tree_shared_256_w1_pg", .image = "tree_attention", .threads = 32, .dynamic = 40960, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 249, .static = 0, .bound = 32 }, .{ .regs = 249, .static = 0, .bound = 32 } } }, .{ .launch = .{ .name = "tree attention tf_tree_shared_256_w1s3_pg", .symbol = "tf_tree_shared_256_w1s3_pg", .image = "tree_attention", .threads = 32, .dynamic = 57344, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 255, .static = 0, .bound = 32 }, .{ .regs = 248, .static = 0, .bound = 32 }, .{ .regs = 248, .static = 0, .bound = 32 } } }, diff --git a/zig/src/core/contract/window_rows_records.zig b/zig/src/core/contract/window_rows_records.zig index 6d518b0d831..ca00a891601 100644 --- a/zig/src/core/contract/window_rows_records.zig +++ b/zig/src/core/contract/window_rows_records.zig @@ -15,7 +15,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "window_pages tf_wrows_merge_256_pg", .symbol = "tf_wrows_merge_256_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 48, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_prompt_256_pg", .symbol = "tf_wrows_prompt_256_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 246, .static = 144, .bound = 256 }, .{ .regs = 246, .static = 144, .bound = 256 }, .{ .regs = 246, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_prompt_256_p32_pg", .symbol = "tf_wrows_prompt_256_p32_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 250, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 } } }, - .{ .launch = .{ .name = "window_pages tf_wrows_part_512_pg", .symbol = "tf_wrows_part_512_pg", .image = "window_pages", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 154, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 157, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 }, .{ .regs = 128, .static = 17536, .bound = 256 } } }, + .{ .launch = .{ .name = "window_pages tf_wrows_part_512_pg", .symbol = "tf_wrows_part_512_pg", .image = "window_pages", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 148, .static = 17536, .bound = 256 }, .{ .regs = 154, .static = 17536, .bound = 256 }, .{ .regs = 154, .static = 17536, .bound = 256 }, .{ .regs = 122, .static = 17536, .bound = 256 }, .{ .regs = 122, .static = 17536, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_merge_512_pg", .symbol = "tf_wrows_merge_512_pg", .image = "window_pages", .threads = 256 }, .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 }, .{ .regs = 64, .static = 128, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_prompt_512_pg", .symbol = "tf_wrows_prompt_512_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 250, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 251, .static = 144, .bound = 256 }, .{ .regs = 253, .static = 144, .bound = 256 }, .{ .regs = 253, .static = 144, .bound = 256 } } }, .{ .launch = .{ .name = "window_pages tf_wrows_prompt_512_p32_pg", .symbol = "tf_wrows_prompt_512_p32_pg", .image = "window_pages", .threads = 256, .dynamic = 81920, .opt_in = true }, .usage = .{ .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 }, .{ .regs = 255, .static = 144, .bound = 256 } } }, From 389368b1cbb13cbee32c1404fd50cdb5d350cae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:49:49 +0100 Subject: [PATCH 4/7] gemma4 cuda: a server with a drafter keeps the global layers' caches linear, paged only without one --- zig/src/families/gemma4/cuda_native.zig | 6 +++--- zig/tests/cuda/gemma4_pages_tests.zig | 13 +++++++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/zig/src/families/gemma4/cuda_native.zig b/zig/src/families/gemma4/cuda_native.zig index b9a6e9f335b..22e266b1d6c 100644 --- a/zig/src/families/gemma4/cuda_native.zig +++ b/zig/src/families/gemma4/cuda_native.zig @@ -52,7 +52,7 @@ const native = @This(); /// The server's reading of the room left after the weights; null if unreadable. pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; -/// No `precision` field (refused by name). --vision: the 12B's embedder. kv_pages false, or the env =0: linear caches. +/// No `precision` field (refused by name). --vision: the 12B's embedder. kv_pages false, a drafter or env =0: linear. pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, lanes: u32 = 8, lanes_fixed: bool = false, room: ?Room = null, vision: ?cv.Limits = null, drafter: ?[]const u8 = null, kv_pages: bool = true }; pub const Loaded = struct { @@ -97,9 +97,9 @@ const Plan = struct { } }; -/// Whether the global layers' caches lease the pool's pages: asked, and not turned off by TENSORFOLD_GEMMA4_KV_PAGES=0. +/// Global caches in pool pages: asked, no drafter (its paged verify trails main), TENSORFOLD_GEMMA4_KV_PAGES not 0. fn pagesOn(o: Options) bool { - return o.kv_pages and !envOff("TENSORFOLD_GEMMA4_KV_PAGES"); + return o.kv_pages and !(o.drafts and o.drafter != null) and !envOff("TENSORFOLD_GEMMA4_KV_PAGES"); } /// The device bytes of the image path's workspace (the 31B's tower or the 12B's embedder), 0 without --vision. diff --git a/zig/tests/cuda/gemma4_pages_tests.zig b/zig/tests/cuda/gemma4_pages_tests.zig index 45b7ac2a86b..4aa40e64f34 100644 --- a/zig/tests/cuda/gemma4_pages_tests.zig +++ b/zig/tests/cuda/gemma4_pages_tests.zig @@ -84,17 +84,18 @@ fn freeResult(gpa: std.mem.Allocator, r: Result) void { free(gpa, r.resumed); } -/// One model with linear or paged global caches through every case. +/// One model with linear or paged global caches through every case (a drafter keeps them linear: open's rule). fn pass(gpu: Gpu, model: []const u8, drafter: ?[]const u8, paged: bool, prompts: [lens.len][]const u32, scrub: []const u32, count: u32) !Result { const gpa = gpu.gpa; var loaded = try native.open(gpa, gpu.io, gpu.ctx, model, null, .{ .context = 8192, .drafts = drafter != null, .lanes = 2, .drafter = drafter, .kv_pages = paged }); defer loaded.deinit(loaded.ctx); - try check.expect((loaded.layout != null) == paged, "gemma4 pages: open made the caches asked for", .{}); + const pages_on = paged and drafter == null; + try check.expect((loaded.layout != null) == pages_on, "gemma4 pages: open made the caches asked for (a drafter: linear)", .{}); var opened: ?Opened = null; defer if (opened) |o| o.close(o.ctx); if (drafter) |dir| opened = try native.openDrafter(gpa, gpu.io, loaded.ctx, dir, 4); const gb = loaded.target; - if (paged) { // the two widest requests at once; the rest lease pages the ended ones gave back, in a shuffled order + if (pages_on) { // the two widest requests at once; the rest lease pages the ended ones gave back, in a shuffled order const pool = be.pagesFor(lens[0], count) + be.pagesFor(lens[1], count); var sequential: usize = 0; for (lens) |n| sequential += be.pagesFor(n, count); @@ -186,5 +187,9 @@ pub fn pages(gpu: Gpu, rest: []const []const u8) !void { if (paged.resumed.cached != mark or linear.resumed.cached != mark) bad += 1; std.debug.print("RESULT gemma4 pages resumed rows: linear {d}, paged {d} (want {d})\n", .{ linear.resumed.cached, paged.resumed.cached, mark }); try check.expect(bad == 0, "gemma4 pages: {d} checks failed", .{bad}); - check.pass("gemma4 pages: global caches in shuffled pool pages give the linear caches' replies and logits ({d} tokens{s}), shared rounds and a kept state's resume included, ended streams' pages reused", .{ count, if (drafter != null) ", drafted" else "" }); + if (drafter != null) { + check.pass("gemma4 pages: with a drafter the default keeps linear global caches, and its replies and logits are the linear caches' ({d} tokens, drafted)", .{count}); + return; + } + check.pass("gemma4 pages: global caches in shuffled pool pages give the linear caches' replies and logits ({d} tokens), shared rounds and a kept state's resume included, ended streams' pages reused", .{count}); } From 3c696c68f339a51e30f0814e130be1a32e49db0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:51:04 +0100 Subject: [PATCH 5/7] gemma4 cuda: the global pages' counts, attach, slots and leases move to cuda_pages.zig, the code unchanged --- zig/src/families/gemma4/cuda.zig | 2 ++ zig/src/families/gemma4/cuda_backend.zig | 26 ++---------------------- zig/src/families/gemma4/cuda_shared.zig | 22 ++++++++++++++++++++ zig/tests/cuda/gemma4_pages_tests.zig | 2 +- 4 files changed, 27 insertions(+), 25 deletions(-) diff --git a/zig/src/families/gemma4/cuda.zig b/zig/src/families/gemma4/cuda.zig index 73b1342c5de..8295ebe8f13 100644 --- a/zig/src/families/gemma4/cuda.zig +++ b/zig/src/families/gemma4/cuda.zig @@ -11,6 +11,7 @@ pub const kernels = @import("cuda_kernels.zig"); pub const forward = @import("cuda_forward.zig"); pub const snap = @import("cuda_snap.zig"); pub const backend = @import("cuda_backend.zig"); +pub const shared = @import("cuda_shared.zig"); pub const assistant = @import("cuda_assistant.zig"); pub const vision = @import("cuda_vision.zig"); pub const dflash = @import("cuda_dflash.zig"); @@ -45,6 +46,7 @@ test { _ = @import("cuda_forward.zig"); _ = @import("cuda_snap.zig"); _ = @import("cuda_backend.zig"); + _ = @import("cuda_shared.zig"); _ = @import("cuda_assistant.zig"); _ = @import("cuda_assistant_weights.zig"); _ = @import("cuda_vision.zig"); diff --git a/zig/src/families/gemma4/cuda_backend.zig b/zig/src/families/gemma4/cuda_backend.zig index 98ada265587..48fafe62ac2 100644 --- a/zig/src/families/gemma4/cuda_backend.zig +++ b/zig/src/families/gemma4/cuda_backend.zig @@ -19,7 +19,7 @@ pub const prompt_rows = fwd.prompt_rows; pub const round_rows = fwd.round_rows; /// The widest window a stream verifies: one-row steps and every wider window give a row the same bits. pub const max_window = 16; -/// Pages a request holds at most: its prompt, its reply and one last verify window (cuda_shared.zig). +/// Pages a request holds at most (cuda_shared.zig). pub const pagesFor = shared.pagesFor; /// Drawn tokens a handle names (a ring; read before the round loop could wrap it). const ring = 1024; @@ -102,12 +102,6 @@ pub const Gemma = struct { return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .free = free, .tok = tok, .picks = picks, .greedy = greedy, .meta = meta, .slot_bufs = bufs }; } - /// The pool's free pages in a seeded random order, leased in that order (a check's hook). - pub fn shufflePages(x: *Gemma, seed: u64) void { - var prng = std.Random.DefaultPrng.init(seed); - if (x.pool) |*p| prng.random().shuffle(u32, p.free[0..p.nfree]); - } - pub fn deinit(x: *Gemma) void { var it = x.lanes.valueIterator(); while (it.next()) |l| { @@ -541,19 +535,10 @@ pub const Gemma = struct { x.s.synchronize() catch {}; b.free(); } - if (x.lanes.count() == 0) x.report(); + if (x.lanes.count() == 0) shared.report(x); } } - /// The idle server's line: nothing promised, every page free (kept states are copies, not pages). - fn report(x: *const Gemma) void { - if (@import("builtin").is_test) return; - const p = x.pool orelse return; - const c = p.census(); - const ok = p.idle() and c.free == c.total; - std.log.info("kv pool idle{s}: promised {d}, free {d} + store {d} == total {d}", .{ if (ok) "" else " (UNEVEN)", c.promised, c.free, c.kept, c.total }); - } - fn release(ptr: *anyopaque, s: *Stream) void { self(ptr).dropLane(s); } @@ -609,10 +594,3 @@ test "shared head costs: Gemma CUDA assistant and DFlash retain costed copy gran b.m = &m; try @import("cuda_head_cost_test.zig").check(b.facts()); } - -test "a request holds its prompt, its reply and one verify window in whole pages of 256 positions" { - try std.testing.expectEqual(@as(usize, 1), pagesFor(1, 1)); - try std.testing.expectEqual(@as(usize, 1), pagesFor(200, 40)); - try std.testing.expectEqual(@as(usize, 2), pagesFor(200, 41)); - try std.testing.expectEqual(@as(usize, 129), pagesFor(32768, 0)); -} diff --git a/zig/src/families/gemma4/cuda_shared.zig b/zig/src/families/gemma4/cuda_shared.zig index bdb23ebd6f0..236f4f97826 100644 --- a/zig/src/families/gemma4/cuda_shared.zig +++ b/zig/src/families/gemma4/cuda_shared.zig @@ -29,6 +29,21 @@ pub fn admits(x: anytype, prompt: usize, max_new: usize) bool { return if (x.pool) |*p| p.fits(pagesFor(prompt, max_new)) else true; } +/// The pool's free pages in a seeded random order, leased in that order (a check's hook). +pub fn shufflePages(x: anytype, seed: u64) void { + var prng = std.Random.DefaultPrng.init(seed); + if (x.pool) |*p| prng.random().shuffle(u32, p.free[0..p.nfree]); +} + +/// The idle server's line: nothing promised, every page free (kept states are copies, not pages). +pub fn report(x: anytype) void { + if (@import("builtin").is_test) return; + const p = x.pool orelse return; + const c = p.census(); + const ok = p.idle() and (x.prompts != null or c.free == c.total); // TF_KV_SHARE: the store holds pages + std.log.info("kv pool idle{s}: promised {d}, free {d} + store {d} == total {d}", .{ if (ok) "" else " (UNEVEN)", c.promised, c.free, c.kept, c.total }); +} + pub fn reach(x: anytype, l: anytype, end: usize) !void { const p = if (x.pool) |*p| p else return; const n = pagesOf(end); @@ -174,3 +189,10 @@ pub fn legacyOpening(comptime Lane: type, x: anytype, s: *Stream) !*Lane { s.fill_at.store(@intCast(l.fill.?), .monotonic); return l; } + +test "a request holds its prompt, its reply and one verify window in whole pages of 256 positions" { + try std.testing.expectEqual(@as(usize, 1), pagesFor(1, 1)); + try std.testing.expectEqual(@as(usize, 1), pagesFor(200, 40)); + try std.testing.expectEqual(@as(usize, 2), pagesFor(200, 41)); + try std.testing.expectEqual(@as(usize, 129), pagesFor(32768, 0)); +} diff --git a/zig/tests/cuda/gemma4_pages_tests.zig b/zig/tests/cuda/gemma4_pages_tests.zig index 4aa40e64f34..533739bf790 100644 --- a/zig/tests/cuda/gemma4_pages_tests.zig +++ b/zig/tests/cuda/gemma4_pages_tests.zig @@ -101,7 +101,7 @@ fn pass(gpu: Gpu, model: []const u8, drafter: ?[]const u8, paged: bool, prompts: for (lens) |n| sequential += be.pagesFor(n, count); try check.expect(sequential > pool, "gemma4 pages: the solo runs take more pages than the pool holds", .{}); try native.attach(loaded.ctx, 1, pool); - gb.shufflePages(0x6e4); + g4.shared.shufflePages(gb, 0x6e4); } var drafted: ?lanes.drafted.Drafted = if (opened) |o| try lanes.drafted.Drafted.init(gpa, loaded.backend, o.drafter) else null; defer if (drafted) |*d| d.deinit(); From 3d157afe5fea6155097ad8826c0f7c6ed7edd6ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:09:06 +0100 Subject: [PATCH 6/7] cuda window_rows: the paged decode merge replays a non-finite head in a noinline helper, so its fast path builds no page lookup --- zig/src/core/contract/registry.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index dbd2cbb833a..66cab0e0b96 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -216,6 +216,7 @@ pub const CudaSet = struct { release: limits.Nvcc, usage: []const Override }; /// The later releases' sets, rising by release; a tree's images are checked against the newest at or below their own. pub const cuda_sets = [_]CudaSet{ .{ .release = .{ .major = 13, .minor = 2 }, .usage = &([_]Override{ + .{ .name = "window_pages tf_wrows_merge_512_pg", .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, .{ .name = "moe tf_moe_topk_sigmoid_score_warp", .usage = .{ .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 } } }, .{ .name = "norms tf_rms_rows", .usage = .{ .{ .regs = 32, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 } } }, .{ .name = "lane_gemv", .usage = .{ .{ .regs = 64, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 }, .{ .regs = 66, .static = 0, .bound = 128 } } }, From 6f4afdcc3eeafb91f0bb6c546ea5ef57516ddc2b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:01:39 +0000 Subject: [PATCH 7/7] changelog: #1619 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 270c7731058..4f0831ea8af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Gemma 4 on CUDA keeps its global layers' caches in pages of the core KV pool, every stream on pages, so with `TF_KV_SHARE` its prompts can be kept and resumed as pool pages; unset, tokens and speed are unchanged (#1619, part of #1657). Thanks to @jschmied. + - TensorFold Starlight moves to its own repository, [ashhart/tf-starlight](https://github.com/ashhart/tf-starlight), with its history: it pins the TensorFold release it is tested with and checks the engine contract against that release in CI (#1972, fixes #1970). - DeepSeek-V4.1 on Metal, part one: its kernels, the decoder over every layer, Engram, prompt chunks and DSpark drafts, each checked against float64 references (#1710-#1719). Serving it on Metal follows with #1720-#1722. Thanks to @gilby.