From da025e7e9f9640623d496991a863385bc76d4cfc Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:46:54 +0900 Subject: [PATCH 1/3] glm cuda: each decode window width keeps its faster expert form GLM's load-time race summed the 2-, 4- and 8-row windows and one draft step of its classic and factored NVFP4 expert forms, then ran every decode window on the winner. A sum hides the widths it loses: at TP=4 the factored form wins at 1 and 8 rows but loses at 4 and 6, so four streams without drafts decode about 2% slower than on classic. Both forms give the same bits (the NVFP4 fact contract holds the factored tiles and waves to the decode form's sums), so each window can take either. The race now times both forms at all ten widths, keeps classic at a width unless factored is more than 1% faster there, and prices each width at its kept form's time instead of timing the table again. A window runs on the form of the narrowest timed width that holds it: rank 0 sends the forms as a bit a row count, and the record keeps a bit a width. Records carry the build's hash in their key, so no record of a single-form build is read for its forms. The race sweeps every width five times on both forms, untimed, before it times a window, then each width's timed windows take the two forms in turn, classic first on even rounds and factored first on odd ones. Timed one form after the other, the order picked the form: on four GB10s at TP=4 a log of every run showed classic's narrow widths up to 60% over their later time in a load's first 4 s, and a 4 to 6% drift through the race on one form, so two launches of one build kept different forms at 3, 4, 6 and 12 rows. Five sweeps of both forms take about 5.4 s there. TF_GLM_EXPERT_FORM now names one form for every width: the warm-up sweeps that form ten times and the load times the windows and the draft step at it, and a load that times nothing sends it to every rank for every row count. The startup line names one form when every width shares it, else the more common form and the widths where the other runs (experts factored, classic at 4 and 6 rows). --- docs/environment.md | 2 +- docs/recipes/glm-5.3-flash-cuda.md | 22 ++- zig/glm_lane_costs_host.zig | 150 ++++++++++++++---- zig/src/families/glm/cuda_experts.zig | 8 +- zig/src/families/glm/cuda_follow.zig | 12 +- .../families/glm/cuda_lane_cost_measure.zig | 79 ++++++--- zig/src/families/glm/cuda_lane_costs.zig | 60 +++++-- zig/src/families/glm/cuda_moe.zig | 2 +- zig/src/platform/environment.zig | 2 +- 9 files changed, 254 insertions(+), 83 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 04abee035f0..0f302bb129b 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -64,7 +64,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_DFLASH2_LOG` | Whole unsigned 64-bit count of DFlash2 rounds whose drafts are logged; default 0 | | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | -| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use (the same bits either way), also at a load that times nothing; unset or blank races the two when a build first loads with drafts and scratch context and keeps the winner, else classic; read on rank 0, which chooses every rank's form | +| `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use at every width (the same bits either way), also at a load that times nothing; unset or blank races the two at each timed width when a build first loads with drafts and scratch context and keeps each width's winner, else classic; read on rank 0, which chooses every rank's forms | | `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` | | `TF_GLM_KV_HOST_GIB` | GLM on CUDA: a finite GiB amount of at least 0 for the DSA layers' pinned host pages; unset or blank uses one full window and 16 rows a page | | `TF_GLM_RANK` | GLM-5.3-Flash on CUDA: a whole rank index from 0 through 4294967295, set with `TF_GLM_WORLD`; unset with it gives one rank | diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index 4eb79aed667..19b14a6915d 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -135,14 +135,20 @@ range (0.25% at least), and inside the rest. Other checkpoints and sampled repli ## Window prices Decode windows reach 32 rows and MTP chains 15 drafts. With drafts and enough scratch context, rank 0 races -classic NVFP4 experts against the factored form over real text on every rank, keeping the faster form with the same -bits. MTP also times windows of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows, with straight lines between them, and a -chained draft step. Its startup line reports `glm: windows (timed)` and the expert form. DFlash2 keeps the existing -seed forward and step prices in lone and shared rounds; it times only the target expert-form race and reports -`glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or published to the lane core. -`TF_GLM_EXPERT_FORM=classic` or `factored` names the form instead and skips the race, so launches compare at one -form, and a load that times nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts -`(TF_GLM_EXPERT_FORM)` after the form's word. +classic NVFP4 experts against the factored form, which gives the same bits, over real text on every rank at windows +of 1, 2, 3, 4, 6, 8, 12, 16, 24 and 32 rows. Five untimed sweeps of every width on both forms come first, then each +width's timed windows take the two forms in turn, classic first on even rounds and factored first on odd ones, so +neither form is timed in a load's first seconds, and a drift through the race or a window right after a switch of +form falls on both alike. Each width keeps its faster form, classic unless factored is more than 1% faster, and a +window runs on the form of the narrowest timed width that holds it. `TF_GLM_EXPERT_FORM=classic` or `factored` +names one form for every width instead and skips the race, so launches compare at one form, and a load that times +nothing still runs it (`glm: expert form (untimed)`); a named form's startup line puts `(TF_GLM_EXPERT_FORM)` after +the form's word. MTP prices each width at its kept form's time, with straight lines between them, and a chained +draft step. Its startup line reports `glm: windows (timed)` and the forms: one word when every width shares one, +else the more common form and the widths where the other runs, as in `experts factored, classic at 4 and 6 rows`. +DFlash2 keeps the existing seed forward and step prices in lone and shared rounds; it times only the target +expert-form race and reports `glm: expert form (timed)`. No unused DFlash2 window or draft-step table is measured or +published to the lane core. The measurements stay in `~/.cache/tensorfold/window-costs`, keyed by the build, GPU/driver, full checkpoint and drafter identity, drafter precision, rank count, layer limit, L2-prefetch options, loaded NVFP4 decode warps, KDA and matmul diff --git a/zig/glm_lane_costs_host.zig b/zig/glm_lane_costs_host.zig index 76518cdb770..d1ffc50ce16 100644 --- a/zig/glm_lane_costs_host.zig +++ b/zig/glm_lane_costs_host.zig @@ -1,23 +1,36 @@ //! The production load-time measurement controller over recording timers, without devices or a checkpoint. const std = @import("std"); -const costs = @import("glm").lane_costs; +const glm = @import("glm"); +const costs = glm.lane_costs; const cuda = @import("cuda"); const t = std.testing; +const m = costs.measurements; const Recording = struct { windows: [costs.widths.len]usize = @splat(0), drafts: usize = 0, - forms: [3]bool = undefined, changes: usize = 0, - fact: bool = false, - pub fn form(r: *@This(), fact: bool) !void { - if (r.changes >= r.forms.len) return error.TooManyFormChanges; - r.forms[r.changes] = fact; + fact: u64 = 0, + ratio: [costs.widths.len]f64 = @splat(0.8), // a factored window's time over a classic one's, by width + runs: usize = 0, // windows run so far + slow: usize = 0, // the first this many windows run 15 ms over, as in a load's first seconds + drift: f64 = 0, // a window's time moves by this fraction a window run before it + switched: [2]f64 = .{ 0, 0 }, // classic's and factored's fraction over right after a window on the other form + last: ?bool = null, // the last window's form, factored or not + pub fn form(r: *@This(), fact: u64) !void { r.changes += 1; r.fact = fact; } + fn classic(i: usize) f64 { + return 20 + @as(f64, @floatFromInt(costs.widths[i])); + } pub fn window(r: *@This(), i: usize) !f64 { r.windows[i] += 1; - return (20 + @as(f64, @floatFromInt(costs.widths[i]))) * @as(f64, if (r.fact) 0.8 else 1); + defer r.runs += 1; + const f = (r.fact >> @intCast(i)) & 1 != 0; + defer r.last = f; + const after = if (r.last) |l| (if (l != f) r.switched[@intFromBool(f)] else 0) else 0; + const ms = classic(i) * (if (f) r.ratio[i] else 1) * (1 + after); + return ms * (1 + r.drift * @as(f64, @floatFromInt(r.runs))) + @as(f64, if (r.runs < r.slow) 15 else 0); } pub fn draft(r: *@This(), depth: usize) !f64 { r.drafts += 1; @@ -25,52 +38,121 @@ const Recording = struct { } }; -test "GLM load prices: DFlash2 races expert forms without timing unused windows or head steps" { +/// Each width's windows in a race: the untimed sweeps on both forms, then seven timed on each. +const raced = 2 * m.sweeps + 14; + +test "GLM load prices: DFlash2 races the forms at every width without timing head steps or keeping prices" { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, true, null); - try t.expectEqual([3]bool{ false, true, true }, r.forms); + const kept = try m.measure(&r, true, null); + try t.expectEqual(m.all, r.fact); + try t.expectEqual(m.all, kept.fact); try t.expectEqual(@as(usize, 0), r.drafts); - for (r.windows, 0..) |count, i| { - const expected: usize = if (i == 1 or i == 3 or i == 5) 16 else if (i == costs.widths.len - 1) 8 else 0; - try t.expectEqual(expected, count); - } - try t.expect(costs.measurements.reusable(kept, true)); - try t.expect(!costs.measurements.reusable(kept, false)); + for (r.windows) |count| try t.expectEqual(raced, count); + try t.expect(m.reusable(kept, true)); + try t.expect(!m.reusable(kept, false)); try t.expect(costs.tableFor(kept, true) == null); } -test "GLM load prices: MTP retains every timed width and the two-level head slope" { +test "GLM load prices: MTP keeps each width's raced time as its price, then the two-level head slope" { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, false, null); - try t.expectEqual([3]bool{ false, true, true }, r.forms); - try t.expectEqual(@as(usize, 32), r.drafts); - for (r.windows, 0..) |count, i| { - const expected: usize = 8 + @as(usize, if (i == 1 or i == 3 or i == 5) 16 else if (i == costs.widths.len - 1) 8 else 0); - try t.expectEqual(expected, count); + const kept = try m.measure(&r, false, null); + try t.expectEqual(m.all, r.fact); + try t.expectEqual(@as(usize, 16), r.drafts); + for (r.windows, kept.ms, 0..) |count, ms, i| { + try t.expectEqual(raced, count); + try t.expectApproxEqAbs(Recording.classic(i) * 0.8, ms, 1e-12); } try t.expectApproxEqAbs(@as(f64, 0.5), kept.step_ms, 1e-12); - try t.expect(costs.measurements.reusable(kept, false)); - try t.expect(!costs.measurements.reusable(kept, true)); + try t.expect(m.reusable(kept, false)); + try t.expect(!m.reusable(kept, true)); try t.expect(costs.tableFor(kept, false) != null); try t.expect(costs.tableFor(kept, true) == null); } +test "GLM load prices: each width keeps the form its windows ran faster on, and classic inside the margin" { + var r: Recording = .{}; + r.ratio = .{ 0.995, 0.97, 0.97, 1.02, 1.02, 0.97, 0.97, 0.97, 0.97, 0.97 }; + const kept = try m.measure(&r, false, null); + const want = m.all & ~@as(u64, 0b1_1001); // classic at 1 row (inside the margin), 4 and 6 + try t.expectEqual(want, r.fact); + try t.expectEqual(want, kept.fact); + for (kept.ms, 0..) |ms, i| { + const f = if ((want >> @intCast(i)) & 1 != 0) r.ratio[i] else 1; + try t.expectApproxEqAbs(Recording.classic(i) * f, ms, 1e-12); + } +} + +test "GLM load prices: a dip is timed again at each width's own form, not the last raced one" { + var r: Recording = .{}; + r.ratio = @splat(0.97); + r.ratio[0] = 0.995; // inside the margin: 1 row stays classic + r.ratio[1] = 0.9; // 2 rows then dip under 1 row's price + const kept = try m.measure(&r, false, null); + try t.expectEqual(@as(u64, 0), kept.fact & 1); + try t.expect(r.windows[0] > raced); + try t.expectApproxEqAbs(Recording.classic(0), kept.ms[0], 1e-12); // a factored retime would lower it +} + test "GLM load prices: a named expert form is set once, before the warm-up, and no forms race" { for ([_]bool{ false, true }) |pin| for ([_]bool{ false, true }) |block| { var r: Recording = .{}; - const kept = try costs.measurements.measure(&r, block, pin); + const kept = try m.measure(&r, block, pin); try t.expectEqual(@as(usize, 1), r.changes); - try t.expectEqual(pin, r.forms[0]); - try t.expectEqual(@as(u64, @intFromBool(pin)), kept.fact); + try t.expectEqual(m.every(pin), r.fact); + try t.expectEqual(m.every(pin), kept.fact); try t.expectEqual(@as(usize, if (block) 0 else 16), r.drafts); - for (r.windows, 0..) |count, i| { - const warm: usize = if (i == costs.widths.len - 1) 8 else 0; - try t.expectEqual(warm + @as(usize, if (block) 0 else 8), count); - } - try t.expect(costs.measurements.reusable(kept, block)); + // as many untimed windows a width as a race's sweeps, then one fastest-of; DFlash2 times none + for (r.windows) |count| try t.expectEqual(@as(usize, if (block) 0 else 2 * m.sweeps + 8), count); + try t.expect(m.reusable(kept, block)); }; } +test "GLM load prices: a slow start outlasting the old warm-up decides no width's form and sets no price" { + var r: Recording = .{}; + r.ratio = @splat(1); // the two forms alike: classic at every width + r.slow = 48; // longer than a warm-up at the widest alone, as the slowest observed start was + const kept = try m.measure(&r, false, null); + try t.expectEqual(@as(u64, 0), kept.fact); + for (kept.ms, 0..) |ms, i| try t.expectApproxEqAbs(Recording.classic(i), ms, 1e-12); +} + +test "GLM load prices: a drift through the race falls on both forms alike" { + const Case = struct { drift: f64, ratio: f64, want: u64 }; + // faster as it runs with the forms alike, then slower with factored 2% faster at every width + for ([_]Case{ .{ .drift = -0.0002, .ratio = 1, .want = 0 }, .{ .drift = 0.0002, .ratio = 0.98, .want = m.all } }) |c| { + var r: Recording = .{}; + r.ratio = @splat(c.ratio); + r.drift = c.drift; + const kept = try m.measure(&r, true, null); + try t.expectEqual(c.want, kept.fact); + } +} + +test "GLM load prices: a window run slow right after the other form decides no width's form" { + var r: Recording = .{}; + r.ratio = @splat(0.97); + r.switched = .{ 0.04, 0.13 }; // classic 4% and factored 13% over right after the other form + const kept = try m.measure(&r, false, null); + try t.expectEqual(m.all, kept.fact); + for (kept.ms, 0..) |ms, i| try t.expectApproxEqAbs(Recording.classic(i) * 0.97, ms, 1e-12); +} + +test "GLM load prices: a window takes the form of the narrowest timed width that holds it" { + try t.expectEqual(@as(u64, 0), m.rows(0)); + try t.expectEqual(~@as(u64, 0), m.rows(m.all)); + try t.expectEqual(@as(u64, 1 << 3), m.rows(1 << 3)); // 4 rows alone + try t.expectEqual(@as(u64, 0b11 << 4), m.rows(1 << 4)); // 6 rows: 5 and 6 + try t.expectEqual(~@as(u64, 0) << 24, m.rows(1 << 9)); // 32 rows: 25 and on + var ks: glm.experts.Kernels = undefined; + ks.fact = m.rows(m.all & ~@as(u64, 0b1_1000)); + for ([_]usize{ 0, 4, 5, 6 }) |rows| try t.expect(!ks.factored(rows)); + for ([_]usize{ 1, 3, 7, 32, 33, 64, 4096 }) |rows| try t.expect(ks.factored(rows)); + var k: m.Kept = .{ .ms = @splat(1), .step_ms = 0, .fact = m.all }; + try t.expect(m.reusable(k, false)); + k.fact = m.all + 1; + try t.expect(!m.reusable(k, false)); +} + const Device = struct { fn attribute(out: *c_int, attr: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) cuda.abi.Result { out.* = if (attr == .compute_capability_major) 12 else 1; @@ -98,7 +180,7 @@ test "GLM load prices: an oversized NCCL setting disables the cache without reje a.free(v); } else _ = env.unsetenv(variable); } - var e: @import("glm").engine.Engine = undefined; + var e: glm.engine.Engine = undefined; e.settings = .{}; e.checkpoint_digest = @splat(1); e.share.world = 2; diff --git a/zig/src/families/glm/cuda_experts.zig b/zig/src/families/glm/cuda_experts.zig index f70972f84de..449abdc9330 100644 --- a/zig/src/families/glm/cuda_experts.zig +++ b/zig/src/families/glm/cuda_experts.zig @@ -17,7 +17,13 @@ pub const Kernels = struct { nvfp4: cuda.experts.Nvfp4Experts, b32: ?cuda.experts32.Nvfp4b32Experts, // loaded for a csf0_v1 checkpoint alone (wantsBlock32) router: cuda.grouped.Router, - fact: bool = false, // decode windows on NVFP4's factored tiles (the same bits): load timing picks it (cuda_lane_costs) + fact: u64 = 0, // bit r - 1: a decode window of r rows on NVFP4's factored tiles (the same bits); load timing picks them by width (cuda_lane_costs) + + /// Whether a decode window of `rows` runs on the factored tiles; past 64 rows, as 64 do. + pub fn factored(ks: *const Kernels, rows: usize) bool { + const r = @min(rows, 64); + return r > 0 and (ks.fact >> @intCast(r - 1)) & 1 != 0; + } /// `plans`: the loaded experts module (its plan kernels); `block32`: block 32's image too, for these values. pub fn load(d: *const cuda.Driver, plans: cuda.Module, sms: u32, block32: ?cuda.experts32.Values) !Kernels { diff --git a/zig/src/families/glm/cuda_follow.zig b/zig/src/families/glm/cuda_follow.zig index 940dceac462..1e8724243b5 100644 --- a/zig/src/families/glm/cuda_follow.zig +++ b/zig/src/families/glm/cuda_follow.zig @@ -24,7 +24,7 @@ pub const Header = extern struct { n: u32 = 0, // ids that follow depth: u32 = 0, // draft: drafts to chain; chunk: where it starts; shared: its parts flags: u32 = 0, // begin: sampled; draft: from the prompt (1), chances (2); prefill, chunk: prompt_logprobs (1); chunk: indexer rows split (2); verify, shared: whole rows; snapshots: pages shared - a: u64 = 0, // begin: the prompt cache's pages first in its table; keep: rows; prefill, chunk: the kept state it resumes (0: none); redraw: the prompt's length + a: u64 = 0, // begin: the prompt cache's pages first in its table; keep: rows; prefill, chunk: the kept state it resumes (0: none); redraw: the prompt's length; form: a bit a window's rows seed: u64 = 0, // begin: the sampling seed; prefill, chunk: the kept state's position temperature: f64 = 0, top_p: f64 = 0, @@ -323,10 +323,10 @@ pub const Leader = struct { try x.e.draftBlock(reqs); } - /// Every rank's decode windows on the factored expert form or not (the same bits; load timing picks it). - pub fn expertForm(x: Leader, fact: bool) !void { - try x.send(.{ .kind = @backingInt(Kind.form), .a = @intFromBool(fact) }, &.{}); - x.e.m.experts.fact = fact; + /// Every rank's expert forms, bit r - 1 for a window of r rows (the same bits; load timing picks them by width). + pub fn expertForm(x: Leader, forms: u64) !void { + try x.send(.{ .kind = @backingInt(Kind.form), .a = forms }, &.{}); + x.e.m.experts.fact = forms; } /// The other ranks leave their loops. @@ -420,7 +420,7 @@ pub fn follow(e: *Engine, link: *Link) !void { try e.prefillMany(decoded, &firsts); }, .keep => try e.keep(@intCast(h.a)), - .form => e.m.experts.fact = h.a != 0, + .form => e.m.experts.fact = h.a, .draft => { const ids = try e.gpa.dupe(u32, step.ids); defer e.gpa.free(ids); diff --git a/zig/src/families/glm/cuda_lane_cost_measure.zig b/zig/src/families/glm/cuda_lane_cost_measure.zig index f4d00545c80..cecfb80d04b 100644 --- a/zig/src/families/glm/cuda_lane_cost_measure.zig +++ b/zig/src/families/glm/cuda_lane_cost_measure.zig @@ -2,13 +2,21 @@ const std = @import("std"); const rule = @import("lanes").cost_rule; pub const widths = [_]u32{ 1, 2, 3, 4, 6, 8, 12, 16, 24, 32 }; -const race = [_]usize{ 1, 3, 5 }; const margin = 0.01; -const warm = 8; +/// Untimed sweeps of every width before one is timed (both forms when racing): a TP=4 load's first 4 s ran 60% slow. +pub const sweeps = 5; const levels = [2]usize{ 1, 8 }; +/// `fact` holds a bit a width, set where that width's windows run on the factored form. pub const Kept = extern struct { ms: [widths.len]f64, step_ms: f64, fact: u64 }; +/// Every width on the factored form. +pub const all: u64 = (1 << widths.len) - 1; -/// Warm the target, race its expert forms unless `pin` names one, then measure only the prices this drafter consumes. +/// Every width on one form. +pub fn every(factored: bool) u64 { + return if (factored) all else 0; +} + +/// Warm the target, race its expert forms by width unless `pin` names one, then time the prices this drafter consumes. pub fn measure(timer: anytype, block: bool, pin: ?bool) !Kept { const Window = struct { timer: @TypeOf(timer), @@ -24,31 +32,64 @@ pub fn measure(timer: anytype, block: bool, pin: ?bool) !Kept { }; const w: Window = .{ .timer = timer }; const d: Draft = .{ .timer = timer }; - if (pin) |f| try timer.form(f); - for (0..warm) |_| _ = try w.time(widths.len - 1); - const fact = pin orelse race: { - var forms: [2]f64 = .{ 0, 0 }; - for (&forms, [_]bool{ false, true }) |*sum, f| { - try timer.form(f); - for (race) |i| sum.* += try rule.fastest(w, i); - if (!block) sum.* += try rule.fastest(d, levels[0]); + var k: Kept = .{ .ms = @splat(0), .step_ms = 0, .fact = every(pin orelse false) }; + if (pin) |f| { + try timer.form(every(f)); + if (block) return k; + for (0..2 * sweeps) |_| for (0..widths.len) |i| { + _ = try w.time(i); + }; + for (&k.ms, 0..) |*m, i| m.* = try rule.fastest(w, i); + } else { + // a width runs factored only where its windows beat classic's by the margin; its time is its price + const forms = try race(timer, w); + for (forms[0], forms[1], 0..) |classic, factored, i| { + if (factored < classic * (1 - margin)) k.fact |= @as(u64, 1) << @intCast(i); } - const won = forms[1] < forms[0] * (1 - margin); - try timer.form(won); - break :race won; - }; - var k: Kept = .{ .ms = @splat(0), .step_ms = 0, .fact = @intFromBool(fact) }; - if (block) return k; - for (&k.ms, 0..) |*m, i| m.* = try rule.fastest(w, i); + try timer.form(k.fact); + if (block) return k; + for (&k.ms, forms[0], forms[1], 0..) |*m, classic, factored, i| m.* = if (on(k.fact, i)) factored else classic; + } try rule.smooth(w, &k.ms); const chain = [2]f64{ try rule.fastest(d, levels[0]), try rule.fastest(d, levels[1]) }; k.step_ms = @max(0, (chain[1] - chain[0]) / @as(f64, @floatFromInt(levels[1] - levels[0]))); return k; } +/// Each form's fastest window by width: sweeps, then turns both ways, so no load's start, drift or switch picks one. +fn race(timer: anytype, w: anytype) ![2][widths.len]f64 { + const both = [2]u64{ 0, all }; + for (0..sweeps) |_| for (0..widths.len) |i| for (both) |f| { + try timer.form(f); + _ = try w.time(i); + }; + var ms: [2][widths.len]f64 = @splat(@splat(std.math.inf(f64))); + for (0..widths.len) |i| for (0..rule.reps) |r| for (0..2) |k| { + const p = k ^ (r & 1); // classic first on even rounds, factored on odd ones: a switch weighs on both alike + try timer.form(both[p]); + ms[p][i] = @min(ms[p][i], try w.time(i)); + }; + return ms; +} + +fn on(fact: u64, i: usize) bool { + return (fact >> @intCast(i)) & 1 != 0; +} + +/// A bit a row count from 1: a window takes the form of the narrowest timed width that holds it, past 32 the widest's. +pub fn rows(fact: u64) u64 { + var out: u64 = 0; + var i: usize = 0; + for (1..65) |r| { + while (i + 1 < widths.len and widths[i] < r) i += 1; + if (on(fact, i)) out |= @as(u64, 1) << @intCast(r - 1); + } + return out; +} + /// A form-only entry cannot masquerade as a window table, or the other way around. pub fn reusable(k: Kept, block: bool) bool { - if (k.fact > 1) return false; + if (k.fact & ~all != 0) return false; if (block) { for (k.ms) |m| if (m != 0) return false; return k.step_ms == 0; diff --git a/zig/src/families/glm/cuda_lane_costs.zig b/zig/src/families/glm/cuda_lane_costs.zig index 3e798ed90c2..b69018198ab 100644 --- a/zig/src/families/glm/cuda_lane_costs.zig +++ b/zig/src/families/glm/cuda_lane_costs.zig @@ -1,4 +1,4 @@ -//! Rank 0 keeps MTP prices and each drafter's expert-form choice per build and timing identity. +//! Rank 0 keeps MTP prices and each drafter's expert forms by window width per build and timing identity. const std = @import("std"); const sys = @import("sys"); const cuda = @import("cuda"); @@ -67,7 +67,7 @@ pub fn price(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: const parts = try keyParts(e, ctx, &name, &shape, pin); const key = if (parts) |v| cache.key(gpa, io, &v) catch null else null; if (key) |k| if (cache.load(Kept, gpa, io, k)) |kept| if (reuses(kept, block, pin)) { - try x.expertForm(kept.fact != 0); + try x.expertForm(measurements.rows(kept.fact)); try x.idle(); report(kept, "kept", block, pin != null); return tableFor(kept, block); @@ -94,7 +94,7 @@ pub fn price(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: /// A kept record stands for this load when it holds prices and, under a named form, was kept at that form. fn reuses(kept: Kept, block: bool, pin: ?bool) bool { - return measurements.reusable(kept, block) and (pin == null or pin.? == (kept.fact != 0)); + return measurements.reusable(kept, block) and (pin == null or kept.fact == measurements.every(pin.?)); } /// TF_GLM_EXPERT_FORM on rank 0, which chooses every rank's form: null races classic and factored, else the one named. @@ -106,7 +106,7 @@ fn pinnedForm() !?bool { /// A load that times nothing still sends a named form to every rank; unnamed, the forms stay classic. fn untimed(x: anytype, pin: ?bool) !?Table { const f = pin orelse return null; - try x.expertForm(f); + try x.expertForm(measurements.rows(measurements.every(f))); try x.idle(); std.log.info(untimed_line, .{if (f) "factored" else "classic"}); return null; @@ -118,7 +118,8 @@ const form_line = "glm: expert form ({s}): {s}{s}; DFlash2 keeps its seed window const untimed_line = "glm: expert form (untimed): {s} (TF_GLM_EXPERT_FORM)"; fn report(k: Kept, how: []const u8, block: bool, pinned: bool) void { - const form = if (k.fact != 0) "factored" else "classic"; + var buf: [64]u8 = undefined; + const form = words(k.fact, &buf); if (block) { std.log.info(form_line, .{ how, form, named(pinned) }); return; @@ -130,6 +131,25 @@ fn named(pinned: bool) []const u8 { return if (pinned) " (TF_GLM_EXPERT_FORM)" else ""; } +/// One word when every width shares a form, else the more common form and the widths where the other runs. +fn words(fact: u64, buf: []u8) []const u8 { + if (fact == 0) return "classic"; + if (fact == measurements.all) return "factored"; + const most = @as(usize, @popCount(fact)) * 2 > widths.len; + const other = if (most) measurements.all & ~fact else fact; + const head = std.fmt.bufPrint(buf, "{s}, {s} at", .{ if (most) "factored" else "classic", if (most) "classic" else "factored" }) catch return "by width"; + var len = head.len; + var left: usize = @popCount(other); + for (widths, 0..) |w, i| { + if ((other >> @intCast(i)) & 1 == 0) continue; + left -= 1; + const sep: []const u8 = if (len == head.len) " " else if (left == 0) " and " else ", "; + len += (std.fmt.bufPrint(buf[len..], "{s}{d}", .{ sep, w }) catch return "by width").len; + } + len += (std.fmt.bufPrint(buf[len..], " {s}", .{if (other == 1) "row" else "rows"}) catch return "by width").len; + return buf[0..len]; +} + /// Cache identity: the GPU and driver, this checkpoint and drafter, the settings a window's time follows, a named form. pub fn keyParts(e: *const engine.Engine, ctx: *const cuda.Context, name: []u8, shape: []u8, pin: ?bool) !?[3][]const u8 { const at = cacheShape(e, try ctx.capability(), try ctx.d.version(), shape, pin) orelse return null; @@ -179,8 +199,8 @@ const Scratch = struct { held: [@max(max_held, engine.max_drafts)]u32 = undefined, chances: [@max(max_held, engine.max_drafts)]f64 = undefined, - pub fn form(s: *Scratch, fact: bool) !void { - try s.x.expertForm(fact); + pub fn form(s: *Scratch, fact: u64) !void { + try s.x.expertForm(measurements.rows(fact)); } pub fn window(s: *Scratch, i: usize) !f64 { @@ -303,11 +323,11 @@ test "GLM cost identity: a named form's startup line ends at (TF_GLM_EXPERT_FORM test "GLM cost identity: a load that times nothing sends a named form to every rank once, and nothing unnamed" { const Leader = struct { - form: ?bool = null, + form: ?u64 = null, sent: usize = 0, idles: usize = 0, - pub fn expertForm(l: *@This(), fact: bool) !void { - l.form = fact; + pub fn expertForm(l: *@This(), forms: u64) !void { + l.form = forms; l.sent += 1; } pub fn idle(l: *@This()) !void { @@ -317,7 +337,7 @@ test "GLM cost identity: a load that times nothing sends a named form to every r for ([_]?bool{ null, false, true }) |pin| { var l: Leader = .{}; try std.testing.expect((try untimed(&l, pin)) == null); - try std.testing.expectEqual(pin, l.form); + try std.testing.expectEqual(if (pin) |f| @as(?u64, measurements.rows(measurements.every(f))) else null, l.form); try std.testing.expectEqual(@as(usize, @intFromBool(pin != null)), l.sent); try std.testing.expectEqual(l.sent, l.idles); } @@ -354,6 +374,22 @@ test "GLM cost identity: a record kept at one named form is not reused at the ot try std.testing.expect(reuses(classic, false, false) and reuses(classic, false, null)); try std.testing.expect(!reuses(classic, false, true)); var factored = classic; - factored.fact = 1; + factored.fact = measurements.every(true); try std.testing.expect(reuses(factored, false, true) and !reuses(factored, false, false)); + // a record raced by width stands for the race alone, not for either named form + var mixed = classic; + mixed.fact = 1; + try std.testing.expect(reuses(mixed, false, null) and !reuses(mixed, false, true) and !reuses(mixed, false, false)); +} + +test "GLM cost identity: a raced line names the more common form and the widths where the other runs" { + var buf: [64]u8 = undefined; + const all = measurements.all; + try std.testing.expectEqualStrings("classic", words(0, &buf)); + try std.testing.expectEqualStrings("factored", words(all, &buf)); + try std.testing.expectEqualStrings("factored, classic at 4 and 6 rows", words(all & ~@as(u64, 0b11000), &buf)); + try std.testing.expectEqualStrings("factored, classic at 32 rows", words(all >> 1, &buf)); + try std.testing.expectEqualStrings("classic, factored at 1 row", words(1, &buf)); + try std.testing.expectEqualStrings("classic, factored at 1, 2 and 32 rows", words(0b10_0000_0011, &buf)); + try std.testing.expectEqualStrings("classic, factored at 8, 12, 16, 24 and 32 rows", words(0b11_1110_0000, &buf)); } diff --git a/zig/src/families/glm/cuda_moe.zig b/zig/src/families/glm/cuda_moe.zig index edde69f93dc..b1ec2495952 100644 --- a/zig/src/families/glm/cuda_moe.zig +++ b/zig/src/families/glm/cuda_moe.zig @@ -64,7 +64,7 @@ pub fn body(k: Kernels, stream: cuda.Stream, l: Layer, s: Scratch, x: u64, x_str if (k.prof) |p| p.mark(stream, .router); defer if (k.prof) |p| p.mark(stream, .routed); if (l.exl3) |w| return exl3.run(k.exl3, k.experts, stream, w, s.x3, s.plan, x, x_stride, s.pick, slots, rows, l.count, d, l.routed.width, l.routed.limit, prompt, s.ey, s.eact); - const plan: experts.Plan = .{ .route = s.plan, .slots = slots, .experts = l.count + 1, .prompt = prompt, .fact = !prompt and k.experts.fact and l.routed.format == .nvfp4 }; + const plan: experts.Plan = .{ .route = s.plan, .slots = slots, .experts = l.count + 1, .prompt = prompt, .fact = !prompt and k.experts.factored(rows) and l.routed.format == .nvfp4 }; try experts.route(k.experts, stream, s.pick, rows * slots, plan); try experts.run(k.experts, stream, .gate_up, l.routed, plan, x, x_stride, rows, s.eact, shared_id); try experts.run(k.experts, stream, if (prompt) .down else .down_f32, l.routed, plan, s.eact, l.routed.width, rows, s.ey, shared_id); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index b35c321abfe..0b7a4b97652 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -118,7 +118,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_DRAFT_CONFIDENCE", .scope = .glm, .kind = .real, .max = 1, .forms = "a finite chain-chance cut from 0 to 1 (default 0.7)" }, // 2^31 - 32: GLM's slots, the window and its 32 verify rows (glm/cuda_native.zig's capacity), keep i32 positions .{ .name = "TF_GLM_CONTEXT_CEILING", .scope = .glm, .kind = .u64, .first_digit = true, .min = 1, .max = 2147483616, .forms = "a whole token count from 1 to 2147483616 (the window GLM-5.3-Flash may serve in place of config.json's)" }, - .{ .name = "TF_GLM_EXPERT_FORM", .scope = .glm, .kind = .word, .words = &.{ "classic", "factored" }, .forms = "classic or factored (unset races the two when a build first loads)" }, + .{ .name = "TF_GLM_EXPERT_FORM", .scope = .glm, .kind = .word, .words = &.{ "classic", "factored" }, .forms = "classic or factored at every width (unset races the two at each width when a build first loads)" }, .{ .name = "TF_DSV41_MHC_DEFER", .scope = .dsv41, .kind = .toggle, .trim = " \t", .no_word = false, .forms = "0, 1, true, false, on, off or yes (any case)" }, .{ .name = "TF_DSV41_COEF_LATE", .scope = .dsv41, .kind = .toggle, .trim = " \t", .no_word = false, .forms = "0, 1, true, false, on, off or yes (any case)" }, .{ .name = "TF_DSV41_LOOKUP", .scope = .dsv41, .kind = .toggle, .trim = " \t", .forms = "0, 1, true, false, on, off, yes or no (any case); blank turns lookup drafts off" }, From 484c7fcd98cf059cd6feee620d4406ce0de84de1 Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:47:41 +0900 Subject: [PATCH 2/3] changelog: #3249 under Unreleased From 9caefe35c8fe1bb54579eb5796dfd34ca6f03bdc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:28:32 +0000 Subject: [PATCH 3/3] changelog: #3249 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b46c5a08203..7c395ac6c04 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 +- GLM-5.3-Flash on CUDA: the load races the classic and factored expert forms, which give the same bits, at each of its ten timed decode window widths and keeps the faster one at each (classic unless factored is more than 1% faster), instead of one form for every window; a window takes the form of the narrowest timed width that holds it, and `TF_GLM_EXPERT_FORM` names one form for every width (#3249). Thanks to @Bizuayeu. + - Pull: gated and private Hugging Face repos come down with your token: `HF_TOKEN`, then `HUGGING_FACE_HUB_TOKEN`, then the one token file the `hf` tools read (`HF_TOKEN_PATH`, else `$HF_HOME/token`, else `~/.cache/huggingface/token`). The token goes only to the hub's own host (`huggingface.co`, or `HF_ENDPOINT`'s), never to the storage hosts downloads are redirected to, and is never printed; a repo the hub refuses is named, with whether a token is missing or lacks access (#3524). - Windows: when a checkpoint load releases the pages it has finished with, the process's working set is trimmed too, so those pages stop crowding a unified-memory budget; Linux and macOS are unchanged (#3866). Thanks to @ElderOrb.