diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dab926ffe5..fd0173d5cab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -610,6 +610,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Server: chat and completion streams can carry the exact committed token IDs. A client opts in with `stream_options.tensorfold_token_stream_version: 1`; the stream then interleaves `tensorfold.token.chunk` events (an offset and the committed IDs, including reasoning, tool markup and EOS tokens) with the usual chunks, and every chunk carries a `tensorfold_stream` anchor (the token count so far and the last ID, plus each logprob entry's raw token position when entries are present). `capabilities --json` reports `token_stream_versions: [1]`. Unknown versions, non-streaming requests and Cortheon multi-round replies get HTTP 400 before generation. Streams without the option are unchanged. exo's proposed TensorFold backend reads these IDs instead of retokenizing text (#3285). +- GLM-5.3-Flash on CUDA: with `TF_GLM_COPIES=1`, `TF_GLM_COPY_SHARE=1` lets copies in shared rounds grow on the lone ramp up to their stream's share of the round's rows (15 tokens at two streams, 7 at four), where every shared copy stayed three tokens wide. Default off, and refused without `TF_GLM_COPIES=1`; replies are unchanged (#3333). + - README: Pick a model gains a GLM-5.3-Flash Jammed XSFP4 NZ5 row, the checkpoint in the `NVFP4_NZ5` form that #2894 reads, and the GLM CUDA recipe names it beside Jammed XSFP4 (#2981). Thanks to @Bizuayeu. - HIP, Qwen3.8-Flash-Next on one RDNA 3.5 GPU (gfx1150 to gfx1153) serving alone: MTP draft chains now stop under a 0.8 confidence floor by default (was 0.3), found by the same one-rank rule `prefill_step` uses; `--mtp-confidence` still overrides it, and other HIP GPUs and families keep 0.3. Replies are unchanged. On a Strix Halo iGPU (gfx1151) one stream decodes about 6% faster and four streams 2.8% (greedy) to 4.6% (sampled) faster (#2697). Thanks to @gilby. diff --git a/docs/environment.md b/docs/environment.md index 6f04814c4ae..89e23ae767f 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -56,6 +56,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_VISION_HOST` | Exactly `0` or `1`; default off (GLM vision weights on the device) | | `TF_GLM_PROF` | Exactly `0` or `1`; default off (no GLM section timing). On, a prompt step is one chunk, with no pair or solo steps, so its prompt timings are of that shape | | `TF_GLM_LINK_WAIT` | Exactly `0` or `1`; default off (short GLM steps go to the other ranks unwaited) | +| `TF_GLM_COPY_SHARE` | Exactly `0` or `1`; default off. `1`, with `TF_GLM_COPIES=1`, lets copies in shared rounds grow on the lone ramp to their stream's share of the round's rows; refused without `TF_GLM_COPIES=1`; read at GLM's open | | `TF_GLM_PDL` | Exactly `0` or `1`; default on (GLM's kernels and its qmmf linears use dependent launches) | | `TF_GLM_PROMPT_STEPS` | Exactly `0` or `1`; default on (GLM prompt passes in chunks); read on rank 0 | | `TF_GLM_SHARED` | Exactly `0` or `1`; default on (GLM windows share a forward); read on rank 0 | diff --git a/docs/recipes/cuda-lane-copies.md b/docs/recipes/cuda-lane-copies.md index b3800e884ad..a7fdb89f7f5 100644 --- a/docs/recipes/cuda-lane-copies.md +++ b/docs/recipes/cuda-lane-copies.md @@ -24,6 +24,13 @@ With the opt-in, `--mtp-confidence` caps the head's probability prefix using the rows remain costed. The allocator can choose plain instead of a head proposal. The default confidence path is unchanged. No row-cost learner is added here; live learned target costs belong to the lane core (#2111). +`TF_GLM_COPY_SHARE=1`, with `TF_GLM_COPIES=1`, lets a copy in a shared round take the lone ramp too (`2w+1` after a +copy kept whole, back to the first copy's three tokens after a miss), capped at its stream's share of the round's 32 +rows less its pending row: 15 tokens at two streams, 7 at four, and three from seven streams on. Without it every copy +in a shared round stays three tokens wide, and only a stream alone ramps. The cap leaves the other streams' rows open; +the prices still decide what fills them. Unset or 0 keeps the facts above, and 1 without `TF_GLM_COPIES=1` refuses at +the open. With `TF_GLM_SHARED=0` each stream's copy keeps three tokens, and Recall keeps its width. + Load timing covers short contexts and one stream, and the seed tables came from an older DFlash2 profile, so neither establishes total round cost at a new checkpoint, long context, rank layout or high concurrency. Keep the default off until exact TP=2 whole-model replies and measured cost pass: baseline/OFF/ON/ON/OFF, greedy and seeded chat/code, one and eight streams, short/32K/64K context, cold prompts diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index 09df22cb2bd..7e6e7d1eaba 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -22,6 +22,7 @@ pub const Model = struct { exact_width: u32 = 1, // the widest window that reproduces one-token steps bit for bit first_copy_rows: u32 = 0, // a lone stream's first copy window (0: the exact width) + shared_copy_ramp: bool = false, // a shared round's copy takes the lone ramp too, to its stream's share of the rows gpu_tokens: bool = false, // one-token rounds may run a step ahead (pipelined) mtp: bool = false, // a draft head is loaded speculate: bool = false, // the head can draft from a verify's rows @@ -72,6 +73,7 @@ pub const Config = struct { max_copy: u32, own_copy_rates: bool = false, // Model.own_copy_rates first_copy: u32, + shared_copy_ramp: bool = false, // Model.shared_copy_ramp, with shared rounds (family_streams) base_width: u32, family_mtp: bool, speculate_early: bool, @@ -161,6 +163,7 @@ pub const Config = struct { .max_copy = max_copy, .own_copy_rates = m.own_copy_rates, .first_copy = first_copy, + .shared_copy_ramp = m.shared_copy_ramp and streams, .base_width = @min(width, first_copy + 1), .family_mtp = m.mtp and width >= 2 and m.speculate, .speculate_early = m.speculate_early and !(m.root_copies and m.copy_drafts), diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index e29b22022c5..01565cd6a02 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -297,7 +297,7 @@ pub const Engine = struct { const own: usize = own_end - 1; if (p.kind == .copy) { win.observeCopied(e, s, p.recalled, own_kept, own); - if (e.alone) { + if (e.alone or e.cfg.shared_copy_ramp) { const width = s.copy_width orelse e.cfg.first_copy; s.copy_width = if (own_kept == own) @min(e.cfg.max_copy, 2 * width + 1) else e.cfg.first_copy; } diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 3f7ebcd6e05..2232be07b9a 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -77,6 +77,7 @@ test { _ = @import("drafted_chances_test.zig"); _ = @import("drafted_copy_test.zig"); _ = @import("root_copy_test.zig"); + _ = @import("shared_copy_test.zig"); _ = @import("drafted_grammar_test.zig"); _ = @import("windows_grammar_test.zig"); _ = @import("windows_chances_test.zig"); diff --git a/zig/src/core/lanes/shared_copy_test.zig b/zig/src/core/lanes/shared_copy_test.zig new file mode 100644 index 00000000000..dfc31c3eab6 --- /dev/null +++ b/zig/src/core/lanes/shared_copy_test.zig @@ -0,0 +1,115 @@ +//! Shared-round copy widths: first_copy as before, or with Model.shared_copy_ramp the lone ramp to a stream's share. +const std = @import("std"); +const cfg = @import("config.zig"); +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const fake = @import("fake.zig"); +const Suffix = @import("proposer.zig").SuffixLookup; +const a = std.testing.allocator; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; + +/// The fake target's reply (its pattern): forty distinct ids, so a copy can run past three; the prompt is it twice. +const reply: [40]u32 = blk: { + var r: [40]u32 = undefined; + for (&r, 0..) |*t, i| t.* = @intCast(20 + i); + break :blk r; +}; +const prompt = reply ++ reply; + +/// From step `at` on, the target replies with `pattern` instead, so the copies it holds miss. +const Turn = struct { at: usize, pattern: []const u32 }; + +fn model(ramp: bool, shared: bool) cfg.Model { + return .{ .exact_width = 32, .first_copy_rows = 4, .batch_rows = 32, .hidden_rows = shared, .copy_match = 4, .shared_copy_ramp = ramp }; +} + +/// Run a stream for each of `copying` (true: a suffix proposer) and note each one's window rows a step in `rows`. +fn run(m: cfg.Model, copying: []const bool, rows: [][8]usize, turn: ?Turn) !void { + var conf = try cfg.Config.init(a, m, 32, 31); + defer conf.deinit(a); + var target: fake.Fake = .{ .gpa = a, .probe_prompt = prompt.len, .cycle_after = 0, .pattern = &reply }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var core = Engine.init(a, &conf, target.backend(), clock.clock()); + defer core.deinit(); + const n = copying.len; + var suffixes: [8]Suffix = undefined; + var streams: [8]Stream = undefined; + for (suffixes[0..n], streams[0..n], copying) |*p, *s, copy| { + p.* = try Suffix.init(a, .{ .min_match = 4 }); + s.* = try Stream.init(a, .{ .id = "copy", .prompt = &prompt, .max_new = 400, .proposer = if (copy) p.proposer() else null }); + } + defer for (suffixes[0..n], streams[0..n]) |*p, *s| { + s.deinit(a); + p.deinit(); + }; + for (streams[0..n]) |*s| try core.addStream(s); + var before: [8]usize = @splat(std.math.maxInt(usize)); + for (rows, 0..) |*step, i| { + if (turn) |t| if (i == t.at) { + target.pattern = t.pattern; + for (before[0..n], streams[0..n]) |*b, *s| b.* = s.emitted().len; + }; + step.* = @splat(0); + try core.step(); + for (step[0..n], streams[0..n]) |*r, *s| r.* = target.lanes.get(s).?.rows.items.len; + } + // every token kept is the target's own reply, so a missed copy's rows were rolled back + for (streams[0..n], before[0..n]) |*s, b| for (s.emitted(), 0..) |t, k| { + const want = if (k < b) reply[k % reply.len] else turn.?.pattern[k % turn.?.pattern.len]; + try expectEqual(want, t); + }; +} + +test "shared copies: without the ramp a shared round's copy keeps first_copy's four rows" { + var rows: [6][8]usize = undefined; + try run(model(false, true), &.{ true, true }, &rows, null); + for (rows) |step| for (step[0..2]) |r| try expect(r <= 4); + try expectEqual(@as(usize, 4), rows[0][0]); +} + +test "shared copies: the ramp grows two streams' copies to their share and starts over after a miss" { + const other = [_]u32{ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75 }; + var rows: [40][8]usize = undefined; + try run(model(true, true), &.{ true, true }, &rows, .{ .at = 5, .pattern = &other }); + for (0..2) |i| { + // 32 rows shared by two streams: 16 a window, its copy 15; step 5's copy misses the new reply + for ([_]usize{ 4, 8, 16, 16, 16, 16 }, 0..) |want, j| try expectEqual(want, rows[j][i]); + var j: usize = 6; + while (j < rows.len and rows[j][i] == 1) j += 1; + try expect(j + 3 <= rows.len); + for ([_]usize{ 4, 8, 16 }, j..) |want, k| try expectEqual(want, rows[k][i]); + } +} + +test "shared copies: eight streams keep four-row copies, and so do streams that share no round" { + var rows: [6][8]usize = undefined; + const eight: [8]bool = @splat(true); + try run(model(true, true), &eight, &rows, null); + for (rows) |step| for (step) |r| try expect(r <= 4); + try expectEqual(@as(usize, 4), rows[5][7]); + var conf = try cfg.Config.init(a, model(true, false), 32, 31); + defer conf.deinit(a); + try expect(!conf.family_streams and !conf.shared_copy_ramp); + try run(model(true, false), &.{ true, true }, &rows, null); + for (rows) |step| for (step[0..2]) |r| try expect(r <= 4); + try expectEqual(@as(usize, 4), rows[5][1]); +} + +test "shared copies: a copy keeps to its stream's share of the round, leaving the other streams their rows" { + const copying = [_]bool{ true, false, true, false }; + var rows: [6][8]usize = undefined; + try run(model(true, true), ©ing, &rows, null); + for (rows) |step| { + var copied: usize = 0; + var total: usize = 0; + for (step[0..4], copying) |r, copy| { + if (copy) copied += r - 1 else try expectEqual(@as(usize, 1), r); + total += r; + } + try expect(copied <= 2 * (32 / 4 - 1)); // each copy at most its share of the 32 rows less its pending row + try expect(total <= 32); + } + try expectEqual(@as(usize, 8), rows[5][0]); +} diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index c2ff650a4df..9738e8884d6 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -212,7 +212,7 @@ pub fn copyProposal(e: *Engine, s: *Stream) !Copy { if (s.proposer) |p| if (!e.alone or e.cfg.lone_copies) { // a priced proposer's drafts are as it gives them, its none too: no width, length or match gate, no Recall if (p.vtable.priced) return .{ .tokens = p.propose(s.context.items, @min(@as(i64, e.cfg.max_copy), s.draftRoom() - 1)) catch &.{} }; - const copied = p.proposeAfter(s.context.items, &.{}, most) catch &.{}; + const copied = p.proposeAfter(s.context.items, &.{}, @min(@as(i64, sharedWidth(e, s, width)), s.draftRoom() - 1)) catch &.{}; const least: usize = if (e.alone and e.cfg.context_copies) 1 else 2; if (copied.len >= least and p.lastMatch() >= e.cfg.enter_match) return .{ .tokens = copied }; }; @@ -222,6 +222,14 @@ pub fn copyProposal(e: *Engine, s: *Stream) !Copy { return if (got.len >= 2) .{ .tokens = got, .recalled = true } else .{}; } +/// Config.shared_copy_ramp: a shared round's copy takes its stream's ramp, to the stream's share of the rows less one. +fn sharedWidth(e: *const Engine, s: *const Stream, width: u32) u32 { + if (e.alone or !e.cfg.shared_copy_ramp) return width; + var live: u32 = 0; + for (e.live.items) |x| live += @intFromBool(!x.finished and !x.paused); + return @min(s.copy_width orelse e.cfg.first_copy, @max(e.cfg.first_copy, e.cfg.batch_rows / @max(live, 1) -| 1)); +} + pub fn copyAhead(ptr: *anyopaque, w: *const depth.Who) bool { const e: *Engine = @ptrCast(@alignCast(ptr)); const s: *Stream = @ptrCast(@alignCast(w.stream.?)); diff --git a/zig/src/families/glm/cuda_copy_policy.zig b/zig/src/families/glm/cuda_copy_policy.zig index 01850143725..8004b92f42e 100644 --- a/zig/src/families/glm/cuda_copy_policy.zig +++ b/zig/src/families/glm/cuda_copy_policy.zig @@ -1,6 +1,25 @@ //! GLM's opt-in copy facts; acceptance estimates and cost allocation stay in the shared lane core. const lanes = @import("lanes"); const engine = @import("cuda_engine.zig"); +const environment = @import("sys").environment; + +/// TF_GLM_COPY_SHARE=1: TF_GLM_COPIES=1's copies in shared rounds take the lone ramp, to a stream's share of the rows. +pub const share_switch = "TF_GLM_COPY_SHARE"; + +/// What the open read: copies on (TF_GLM_COPIES=1 and drafts), and their shared-round ramp (TF_GLM_COPY_SHARE=1). +pub const Policy = struct { copies: bool = false, share: bool = false }; + +/// The open's policy from TF_GLM_COPIES (its own reader) and TF_GLM_COPY_SHARE (the shared parser's row). +pub fn read(drafts: bool) !Policy { + return policy(drafts, try @import("cuda").priority_copies.read("TF_GLM_COPIES", true), environment.Process.get(.{}, share_switch)); +} + +/// `asked`: TF_GLM_COPIES=1. SHARE=1 without it is refused, not read as off; drafts off turns both off. +pub fn policy(drafts: bool, asked: bool, share: ?[]const u8) !Policy { + const wide = try environment.value(bool, share_switch, share, false); + if (wide and !asked) return error.GlmCopyShareWithoutCopies; + return .{ .copies = asked and drafts, .share = wide and drafts }; +} /// With DFlash2: a window's ms by rows on two GB10s (EXL3, TF_GLM_PROF: 86 to 107 ms at 5 to 8), shared as glm_cuda's. pub const window_costs = costTable(@import("cuda_forward.zig").window_rows, 52.0, 6.8); @@ -13,8 +32,8 @@ fn costTable(comptime n: usize, comptime one: f64, comptime row: f64) [n]lanes.c } /// The serving drafts switch wins; unset keeps the family's facts. `measured`: timed prices, so no seed tables. -pub fn apply(base: lanes.Model, enabled: bool, measured: bool) lanes.Model { - if (!enabled or !base.mtp) return base; +pub fn apply(base: lanes.Model, p: Policy, measured: bool) lanes.Model { + if (!p.copies or !base.mtp) return base; var m = base; m.root_copies = true; m.context_copies = true; @@ -27,6 +46,7 @@ pub fn apply(base: lanes.Model, enabled: bool, measured: bool) lanes.Model { m.shared_drafts = 0; // Keep head confidence in the backend's probabilities so every copy still pays its target-window cost. m.draft_confidence = null; + m.shared_copy_ramp = p.share; return m; } diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index 4d601ab113e..77a210365d4 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -12,6 +12,7 @@ const switches = [_]Name{ .{ .name = "TF_GLM_VISION_HOST" }, .{ .name = "TF_GLM_PROF" }, .{ .name = "TF_GLM_LINK_WAIT" }, + .{ .name = "TF_GLM_COPY_SHARE" }, .{ .name = "TF_GLM_PDL", .default = true }, .{ .name = "TF_GLM_PROMPT_STEPS", .default = true }, .{ .name = "TF_GLM_SHARED", .default = true }, @@ -190,3 +191,25 @@ test "TF_GLM_CONTEXT_CEILING's largest window is the last whose slots, verify ro try t.expect(capacity(@intCast(most)) <= @as(usize, std.math.maxInt(i32)) + 1); try t.expect(capacity(@intCast(most + 1)) > @as(usize, std.math.maxInt(i32)) + 1); } + +test "GLM strict env: TF_GLM_COPY_SHARE=1 widens TF_GLM_COPIES=1's copies and is refused without them" { + const cp = @import("cuda_copy_policy.zig"); + for ([_]bool{ false, true }) |drafts| { + for ([_]?[]const u8{ null, "", " ", "0" }) |raw| for ([_]bool{ false, true }) |asked| { + try t.expectEqual(cp.Policy{ .copies = asked and drafts }, try cp.policy(drafts, asked, raw)); + }; + try t.expectEqual(cp.Policy{ .copies = drafts, .share = drafts }, try cp.policy(drafts, true, "1")); + try t.expectError(error.GlmCopyShareWithoutCopies, cp.policy(drafts, false, "1")); + for ([_][]const u8{ "2", "yes", " 1" }) |raw| try t.expectError(error.InvalidEnvironment, cp.policy(drafts, true, raw)); + } + _ = env.unsetenv("TF_GLM_COPIES"); + _ = env.setenv(cp.share_switch, "1", 1); + defer _ = env.unsetenv(cp.share_switch); + try t.expectError(error.GlmCopyShareWithoutCopies, cp.read(true)); + _ = env.setenv("TF_GLM_COPIES", "1", 1); + defer _ = env.unsetenv("TF_GLM_COPIES"); + try t.expectEqual(cp.Policy{ .copies = true, .share = true }, try cp.read(true)); + try t.expectEqual(cp.Policy{}, try cp.read(false)); + // the open's refusal reaches the server in GLM's words + try t.expect(@import("cuda_native.zig").explain(null, error.GlmCopyShareWithoutCopies) != null); +} diff --git a/zig/src/families/glm/cuda_lanes.zig b/zig/src/families/glm/cuda_lanes.zig index 37eedcc152a..a784ad96ca4 100644 --- a/zig/src/families/glm/cuda_lanes.zig +++ b/zig/src/families/glm/cuda_lanes.zig @@ -124,9 +124,9 @@ pub const Lanes = struct { } /// Root/context copies use the same verify/keep path and shared cost allocator as every target window. - pub fn factsWithCopies(self: *Lanes, enabled: bool) lanes.Model { - self.copy_confidence = enabled and self.x.e.mtp; - return copy_policy.apply(self.facts(), enabled, self.x.e.drafter == null and self.costs != null); + pub fn factsWithCopies(self: *Lanes, policy: copy_policy.Policy) lanes.Model { + self.copy_confidence = policy.copies and self.x.e.mtp; + return copy_policy.apply(self.facts(), policy, self.x.e.drafter == null and self.costs != null); } fn of(ptr: *anyopaque) *Lanes { diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index e933c6b4c81..8ea1dc77b94 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -178,7 +178,7 @@ const Owned = struct { lanes: glm_lanes.Lanes, layout: ?kv.Layout, share: usize, // TF_KV_SHARE: states the shared store over the pool's pages keeps (0: the host store) - copies: bool, // TF_GLM_COPIES=1: verified root and context copies + copies: @import("cuda_copy_policy.zig").Policy, // TF_GLM_COPIES=1: verified root and context copies (and TF_GLM_COPY_SHARE) }; const env = @import("sys").env; @@ -237,7 +237,7 @@ fn openRank(a: StartArgs, set: ranks.Settings) !Loaded { const o = a.o; const p = a.p; const roce_bytes = a.roce_bytes; - const copies = try cuda.priority_copies.read("TF_GLM_COPIES", o.drafts); + const copies = try @import("cuda_copy_policy.zig").read(o.drafts); var load_cache = @import("core").checkpoint.cache.Load.begin(io, p.world > 1); defer load_cache.deinit(); // TF_KV_SHARE keeps prompts as the pool's pages: refused before the weights load, every rank told (startup) @@ -521,6 +521,7 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.GlmShareNeedsPages => "TF_KV_SHARE keeps prompts as KV pool pages: set TF_KV_PAGES=on as well", error.GlmShareTooMany => std.fmt.comptimePrint("TF_KV_SHARE keeps at most {d} states: set {d} or fewer", .{ kv.most_snaps, kv.most_snaps }), error.BadCopyPolicy => "TF_GLM_COPIES: expected 0 or 1 for verified root/context copies", + error.GlmCopyShareWithoutCopies => "TF_GLM_COPY_SHARE=1 widens TF_GLM_COPIES=1's copies in shared rounds: set TF_GLM_COPIES=1 as well, or unset TF_GLM_COPY_SHARE", error.InvalidEnvironment => "a TF_GLM_* setting is malformed: the error line before this one names it, its value and the accepted form", error.GlmKvHostNeedsPages => "TF_GLM_KV_HOST keeps the KV pool's pages in host memory: set TF_KV_PAGES=on (and --kv-cache bf16) as well", error.TooManyRanks => std.fmt.comptimePrint( diff --git a/zig/src/native/copy_drafts_cuda_test.zig b/zig/src/native/copy_drafts_cuda_test.zig index 793905ef465..3ffeb59782d 100644 --- a/zig/src/native/copy_drafts_cuda_test.zig +++ b/zig/src/native/copy_drafts_cuda_test.zig @@ -6,14 +6,7 @@ const be = lanes.backend; const Family = enum { gemma4, spark25, kolibri1, dory, minimax, minimax_head, glm_mtp, glm_block }; fn facts(family: Family, enabled: bool) lanes.Model { switch (family) { - .glm_mtp, .glm_block => { - const f = @import("glm_cuda"); - var e: f.engine.Engine = undefined; - e.mtp = true; - e.drafter = if (family == .glm_block) @ptrFromInt(16) else null; - var b: f.lanes.Lanes = .{ .x = .{ .e = &e, .link = undefined } }; - return b.factsWithCopies(enabled); - }, + .glm_mtp, .glm_block => return glmFacts(family == .glm_block, enabled, false), .gemma4 => { const f = @import("gemma4_cuda"); var m: f.forward.Model = undefined; @@ -66,6 +59,16 @@ fn facts(family: Family, enabled: bool) lanes.Model { } const families = std.enums.values(Family); +/// GLM's facts with TF_GLM_COPIES=1 (`copies`) and TF_GLM_COPY_SHARE=1 (`share`), for MTP or DFlash2 (`block`). +fn glmFacts(block: bool, copies: bool, share: bool) lanes.Model { + const f = @import("glm_cuda"); + var e: f.engine.Engine = undefined; + e.mtp = true; + e.drafter = if (block) @ptrFromInt(16) else null; + var b: f.lanes.Lanes = .{ .x = .{ .e = &e, .link = undefined } }; + return b.factsWithCopies(.{ .copies = copies, .share = share }); +} + // Literal main facts for eight slots; independent of the candidate adapters' facts. fn mainFacts(family: Family) lanes.Model { if (family == .glm_mtp or family == .glm_block) { @@ -152,7 +155,7 @@ test "CUDA lane copies: three matches refuse, four enter, disabled copies and mi } } -const Stats = struct { zeros: usize = 0, heads: usize = 0, copied: usize = 0, rejected: usize = 0, trace: u64 = 0 }; +const Stats = struct { zeros: usize = 0, heads: usize = 0, copied: usize = 0, rejected: usize = 0, widest: usize = 0, trace: u64 = 0 }; threadlocal var current: ?*Stats = null; fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) !void { @@ -172,6 +175,7 @@ fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void current.?.trace = std.hash.Wyhash.hash(current.?.trace, std.mem.sliceAsBytes(w.tokens)); if (w.held == 0 and w.tokens.len > 0) { current.?.copied += 1; + current.?.widest = @max(current.?.widest, w.rows()); if (!std.mem.eql(u32, w.tokens, o.sampled[0..w.tokens.len])) current.?.rejected += 1; } } @@ -256,6 +260,36 @@ test "CUDA lane copies: real core copies equal plain tokens solo shared sampled }; } +test "CUDA lane copies: GLM's TF_GLM_COPY_SHARE adds only the shared ramp, and nothing without TF_GLM_COPIES" { + for ([_]bool{ false, true }) |block| { + var want = glmFacts(block, true, false); + try std.testing.expect(!want.shared_copy_ramp); + want.shared_copy_ramp = true; + try std.testing.expectEqualDeep(want, glmFacts(block, true, true)); + try std.testing.expectEqualDeep(mainFacts(if (block) .glm_block else .glm_mtp), glmFacts(block, false, true)); + var cfg = try lanes.Config.init(a, want, want.exact_width, want.exact_width - 1); + defer cfg.deinit(a); + try std.testing.expect(cfg.shared_copy_ramp and cfg.family_streams); + } +} + +test "CUDA lane copies: GLM's shared ramp widens shared rounds' copies past four rows and keeps plain tokens" { + for ([_]bool{ false, true }) |block| for ([_]bool{ false, true }) |sampled| { + const plain = try run(glmFacts(block, true, false), 1, sampled, false, false, false); + for ([_]usize{ 2, 4 }) |count| { + const narrow = try run(glmFacts(block, true, false), count, sampled, true, false, false); + const wide = try run(glmFacts(block, true, true), count, sampled, true, false, false); + for (narrow.tokens[0..count], wide.tokens[0..count]) |n, w| { + try std.testing.expectEqualSlices(u32, &plain.tokens[0], &n); + try std.testing.expectEqualSlices(u32, &plain.tokens[0], &w); + } + // the prompt repeats every four tokens: a shared copy is three at first_copy, four on the ramp + try std.testing.expect(narrow.stats.copied > 0 and narrow.stats.widest <= 4); + try std.testing.expectEqual(@as(usize, 5), wide.stats.widest); + } + }; +} + test "CUDA lane copies: cancel a copied round and the next request equals fresh plain" { for (families) |family| { const m = facts(family, true); @@ -346,7 +380,7 @@ test "CUDA lane copies: GLM uses paid target costs and expensive copies get zero const backend = b.backend(); try std.testing.expect(try backend.vtable.probabilities.?(backend.ptr, &s, &probabilities)); try std.testing.expect(probabilities[1] > 0.6 and probabilities[2] > 0.5); - const on = b.factsWithCopies(true); + const on = b.factsWithCopies(.{ .copies = true }); try std.testing.expect(try backend.vtable.probabilities.?(backend.ptr, &s, &probabilities)); try std.testing.expectEqualSlices(f64, &.{ 0.8, 0, 0 }, &probabilities); try std.testing.expectEqual(@as(?f64, 0.7), b.facts().draft_confidence); @@ -354,7 +388,7 @@ test "CUDA lane copies: GLM uses paid target costs and expensive copies get zero try std.testing.expectEqual(@as(usize, 0), costly[0]); try std.testing.expectEqual(@as(?f64, null), on.draft_confidence); target.mtp = false; - try std.testing.expectEqualDeep(b.facts(), b.factsWithCopies(true)); + try std.testing.expectEqualDeep(b.facts(), b.factsWithCopies(.{ .copies = true })); try std.testing.expectEqualStrings("TF_GLM_COPIES: expected 0 or 1 for verified root/context copies", f.native.explain(null, error.BadCopyPolicy).?); } @@ -400,7 +434,7 @@ test "CUDA lane copies: GLM confidence bounds the actual held offer even when wi target.drafter = null; var b: f.lanes.Lanes = .{ .x = .{ .e = &target, .link = undefined }, .mtp_confidence = 0.7 }; defer b.lanes.deinit(a); - var m = b.factsWithCopies(true); + var m = b.factsWithCopies(.{ .copies = true }); m.shared_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 2, .ms = 10 }, .{ .width = 3, .ms = 0.1 }, .{ .width = 4, .ms = 0.1 } }; var cfg = try lanes.Config.init(a, m, 8, 3); defer cfg.deinit(a); @@ -423,7 +457,7 @@ test "CUDA lane copies: GLM confidence bounds the actual held offer even when wi try std.testing.expect(plans[0].count() <= count); } b.mtp_confidence = 0.7; - _ = b.factsWithCopies(false); + _ = b.factsWithCopies(.{}); try lanes.Engine.testing.askDrafts(&e, &.{.{ .stream = &s, .depth = 3, .position = 1, .follow = &.{}, .rows = null, .start = 0 }}); try std.testing.expectEqual(@as(u32, 3), s.next.?.count); } @@ -456,11 +490,11 @@ test "GLM window prices: MTP takes timed prices and DFlash2 keeps every consumed for ([_]?*@TypeOf(e.drafter.?.*){ null, @ptrFromInt(16) }) |drafter| { e.drafter = drafter; var b: f.lanes.Lanes = .{ .x = .{ .e = &e, .link = undefined } }; - const seeded = b.factsWithCopies(true); + const seeded = b.factsWithCopies(.{ .copies = true }); try std.testing.expect(seeded.window_costs[0].ms > 50); b.costs = f.lane_costs.table(k); for ([_]bool{ false, true }) |copies| { - const m = b.factsWithCopies(copies); + const m = b.factsWithCopies(.{ .copies = copies }); try std.testing.expectEqual(@as(usize, f.lanes.max_rows), m.window_costs.len); const family: Family = if (drafter == null) .glm_mtp else .glm_block; const main = mainFacts(family); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 8809e92f90f..f10286c478f 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -109,6 +109,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_VISION_HOST", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROF", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_LINK_WAIT", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_GLM_COPY_SHARE", .scope = .glm, .kind = .flag, .forms = "0 or 1 (1, with TF_GLM_COPIES=1: copies in shared rounds take the lone ramp)" }, .{ .name = "TF_GLM_PDL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROMPT_STEPS", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_SHARED", .scope = .glm, .kind = .flag, .forms = "0 or 1" },