From e9800392b43dac3217cd3a7968f9e880ac9dae8e Mon Sep 17 00:00:00 2001 From: gilby Date: Fri, 20 Nov 2026 09:47:50 +0100 Subject: [PATCH 1/5] hip flashnext: opt-in --mtp-drafts up to 7 on a lone stream (#3053) --- docs/recipes/qwen3.8-flash-next.md | 2 + zig/src/core/lanes/config.zig | 3 + zig/src/core/lanes/deep_chain_test.zig | 156 ++++++++++++++++++ zig/src/core/lanes/depth.zig | 13 +- zig/src/core/lanes/engine.zig | 5 +- zig/src/core/lanes/lanes.zig | 1 + zig/src/core/lanes/open.zig | 4 +- zig/src/core/lanes/shared_drafts.zig | 3 +- zig/src/families/flashnext/hip.zig | 1 + zig/src/families/flashnext/hip/facts.zig | 22 ++- zig/src/families/flashnext/hip/lanes.zig | 11 -- .../flashnext/hip/mtp_drafts_test.zig | 17 ++ zig/src/families/flashnext/hip/native.zig | 2 + zig/src/native/hip.zig | 33 ++-- zig/src/native/hip_families.zig | 15 ++ zig/src/native/mtp_drafts_hip_test.zig | 20 +++ 16 files changed, 264 insertions(+), 44 deletions(-) create mode 100644 zig/src/core/lanes/deep_chain_test.zig create mode 100644 zig/src/families/flashnext/hip/mtp_drafts_test.zig create mode 100644 zig/src/native/mtp_drafts_hip_test.zig diff --git a/docs/recipes/qwen3.8-flash-next.md b/docs/recipes/qwen3.8-flash-next.md index e0bc830e067..10ddec49ff3 100644 --- a/docs/recipes/qwen3.8-flash-next.md +++ b/docs/recipes/qwen3.8-flash-next.md @@ -536,6 +536,8 @@ zig build native-hip -Dhip=true -Dhip-arch=gfx1151 -Dhipcc=/usr/bin/hipcc -Dopti --parallel 1 --context 131072 ``` +The MTP head chains three drafts a stream by default. `--mtp-drafts N`, up to seven (the verify window's eight rows less the pending one), lets a stream that is alone in a round chain up to N; rounds shared by several streams keep at most three a stream, and `--tp` above 1 refuses more than three. Seven helps where a lone stream's drafts land often (greedy code and chat); on copy-heavy edit text, where copied drafts already fill most of the window, seven ran 0.8% slower than three on one Strix Halo iGPU (gfx1151), and on a sampled chat reply it ran 1% to 3% slower, so pick a lower N for that kind of work. `--mtp-drafts 0` stops the head's drafts. + ## Draft vocabulary provenance The Flash Next dump tool accepts `--draft-vocab default` for the shipped list, diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index 09df22cb2bd..94c02370b2f 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -36,6 +36,7 @@ pub const Model = struct { window_costs: []const Cost = &.{}, // forward ms by exact window width (timed at load) window_costs_lone: bool = false, // window_costs price a lone stream only; shared forwards use shared_costs shared_drafts: u32 = 0, // allocate_shared_drafts: a shared round's most head drafts a stream (0: drafts) + shared_mtp_cap: u32 = 0, // most head drafts a stream chains in a shared round; a lone one chains `drafts` (0: off) mtp_step_ms: f64 = 0.0, // one chained head step (timed at load) shared_step_ms: ?f64 = null, // a separate shared head step; null keeps mtp_step_ms draft_step_ms: f64 = 0.0, // a shared round's draft past a stream's first, as the backend's head runs it (0: priced free) @@ -110,6 +111,7 @@ pub const Config = struct { mtp_step_ms: f64, draft_step_ms: f64 = 0, // Model.draft_step_ms shared_drafts: u32 = 0, // Model.shared_drafts + shared_mtp_cap: u32 = 0, // Model.shared_mtp_cap lone_cost_tile: u32 = 0, // Model.lone_cost_tile context_copies: bool = false, // Model.context_copies, within the existing verification width enter_match: i64 = 8, // matching tokens a copy needs (rejects coincidental indentation) @@ -200,6 +202,7 @@ pub const Config = struct { }, .draft_step_ms = m.draft_step_ms, .shared_drafts = m.shared_drafts, + .shared_mtp_cap = m.shared_mtp_cap, }; } diff --git a/zig/src/core/lanes/deep_chain_test.zig b/zig/src/core/lanes/deep_chain_test.zig new file mode 100644 index 00000000000..fc04e852164 --- /dev/null +++ b/zig/src/core/lanes/deep_chain_test.zig @@ -0,0 +1,156 @@ +//! A lone stream chains up to a model's most drafts while shared rounds keep the model's shared cap. +const std = @import("std"); +const depth = @import("depth.zig"); + +const empty: @import("table.zig").Table = .{}; +const high: [7]f64 = @splat(0.95); +const low: [7]f64 = @splat(0.5); + +const NoCopy = struct { + fn copy(_: *anyopaque, _: *const depth.Who) bool { + return false; + } +}; + +fn rule(prior: []const f64, shared_cap: u32) depth.Rule { + return .{ + .gpa = std.testing.allocator, + .prior = prior, + .most_drafts = 7, + .shared_cap = shared_cap, + .family_costs = &empty, + .shared_costs = &empty, + .mtp_step_ms = 0, + .plain_guard = false, + .node_probabilities = false, + .batch_rows = 16, + }; +} + +fn who(state: *?depth.State) depth.Who { + return .{ .state = state, .draft_room = 100, .finished = false, .forced = false }; +} + +test "a lone stream asks for most_drafts on a high first-draft acceptance and stays low on a low one" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 3); + defer r.deinit(); + var s: ?depth.State = null; + defer if (s) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 7), try r.headDepth(&who(&s), null, probe)); + r.prior = &low; + var t: ?depth.State = null; + defer if (t) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 1), try r.headDepth(&who(&t), null, probe)); +} + +test "streams that share a round chain at most the shared cap each" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 3); + defer r.deinit(); + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + try std.testing.expect(out[0] > 0 and out[1] > 0); + try std.testing.expect(out[0] <= 3 and out[1] <= 3); +} + +test "a zero shared cap keeps the ladder's top of three for a lone stream and most_drafts for shared budgets" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 0); + defer r.deinit(); + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 3), try r.headDepth(&who(&a), null, probe)); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + try std.testing.expect(out[0] > 3 or out[1] > 3); +} + +test "under a confidence floor or node probabilities a shared round chains at most the cap; a lone stream chains seven" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + inline for (.{ .{ 0.5, false }, .{ null, false }, .{ null, true } }) |c| { + for ([_]u32{ 3, 0 }) |cap| { + var r = rule(&high, cap); + defer r.deinit(); + r.node_probabilities = true; + r.confidence_floor = c[0]; + r.granted_depth = c[1]; + var a: ?depth.State = null; + var b: ?depth.State = null; + defer if (a) |*x| x.deinit(std.testing.allocator); + defer if (b) |*x| x.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(i64, 7), try r.headDepth(&who(&a), null, probe)); + var whos = [_]depth.Who{ who(&a), who(&b) }; + var out: [2]i64 = undefined; + try r.budgets(&whos, probe, false, &out); + const want: i64 = if (cap == 0) 7 else 3; + try std.testing.expectEqualSlices(i64, &.{ want, want }, &out); + } + } +} + +test "allocated shared rows, granted or not, reserve at most the shared cap a stream" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const fake = @import("fake.zig"); + const S = @import("stream.zig").Stream; + const win = @import("windows.zig"); + for ([_]bool{ false, true }) |granted| { + for ([_]u32{ 3, 0 }) |cap| { + var cfg = try Cfg.Config.init(a, .{ .exact_width = 8, .drafts = 7, .shared_mtp_cap = cap, .allocate_shared_drafts = true, .draft_probabilities = granted, .granted_depth = granted, .batch_rows = 16 }, 8, 7); + defer cfg.deinit(a); + var back: fake.Fake = .{ .gpa = a }; + defer back.deinit(); + var clock: fake.FixedClock = .{}; + var e = @import("engine.zig").Engine.init(a, &cfg, back.backend(), clock.clock()); + defer e.deinit(); + var one = try S.init(a, .{ .id = "one", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer one.deinit(a); + var two = try S.init(a, .{ .id = "two", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer two.deinit(a); + try one.draft_chances.appendNTimes(a, 1, 7); + try two.draft_chances.appendNTimes(a, 1, 7); + const plans = [_]win.Plan{ .{ .stream = &one, .position = 0, .kind = .none }, .{ .stream = &two, .position = 0, .kind = .none } }; + var out: [2]i64 = undefined; + try @import("shared_drafts.zig").budgets(&e, &plans, &.{ 0, 1 }, &out); + const want: i64 = if (cap == 0) 7 else 3; + try std.testing.expectEqualSlices(i64, &.{ want, want }, &out); + } + } +} + +test "a stream that opens beside a live one takes at most the shared cap as its first drafts" { + const a = std.testing.allocator; + const Cfg = @import("config.zig"); + const fake = @import("fake.zig"); + const S = @import("stream.zig").Stream; + for ([_]u32{ 3, 0 }) |cap| { + var cfg = try Cfg.Config.init(a, .{ .exact_width = 8, .drafts = 7, .shared_mtp_cap = cap, .draft_probabilities = true, .batch_rows = 16 }, 8, 7); + defer cfg.deinit(a); + var back: fake.Fake = .{ .gpa = a }; + defer back.deinit(); + var clock: fake.FixedClock = .{}; + var e = @import("engine.zig").Engine.init(a, &cfg, back.backend(), clock.clock()); + defer e.deinit(); + var live = try S.init(a, .{ .id = "live", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer live.deinit(a); + var s = try S.init(a, .{ .id = "new", .prompt = &.{ 7, 13, 29 }, .max_new = 64 }); + defer s.deinit(a); + try std.testing.expectEqual(@as(u32, 7), try @import("open.zig").firstDepth(&e, &s, .head)); + try e.live.append(a, &live); + defer e.live.clearRetainingCapacity(); + try std.testing.expectEqual(@as(u32, if (cap == 0) 7 else 3), try @import("open.zig").firstDepth(&e, &s, .head)); + } +} diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index b6eeeaf861e..11e11b6639c 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -58,6 +58,7 @@ pub const Rule = struct { k: Constants = .{}, prior: []const f64, most_drafts: u32, + shared_cap: u32 = 0, // Model.shared_mtp_cap: most a shared round chains a stream; a lone one chains most_drafts (0: off) family_costs: *const Table, shared_costs: *const Table, mtp_step_ms: f64, @@ -172,7 +173,7 @@ pub const Rule = struct { if (r.confidence_floor != null and !who.sampled and !r.k.floor_rates) return most; const p = try r.rates(who); if (r.family_costs.empty()) { - const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else 3; + const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else if (r.shared_cap != 0) r.most_drafts else 3; return @max(1, @min(most, want)); } const st = try r.state(who); @@ -390,15 +391,15 @@ pub const Rule = struct { const streams = if (paired != null) total_streams else whos.len; // drafts lose here: none asked, no head pass if (r.plain_streams > 0 and whos.len >= r.plain_streams) return @memset(out, 0); + const top: i64 = if (r.shared_cap != 0) @min(r.most_drafts, r.shared_cap) else r.most_drafts; if (r.confidence_floor != null) { - for (whos, out) |*w, *o| o.* = try r.headDepth(w, null, probe); + for (whos, out) |*w, *o| o.* = @min(try r.headDepth(w, null, probe), top); return; } if (r.node_probabilities) { for (whos, out) |*w, *o| { - const inner = try r.headDepth(w, null, probe); - const granted: i64 = if (w.granted) |g| g else r.most_drafts; - o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, granted + r.k.draft_slack), probe); + const inner = @min(try r.headDepth(w, null, probe), top); + o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, @as(i64, w.granted orelse r.most_drafts) + r.k.draft_slack), probe); } if (r.granted_depth) capPass(out, r.batch_rows); if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHoldsFor(whos, sampled, out, total_streams); @@ -412,7 +413,7 @@ pub const Rule = struct { var made: usize = 0; defer for (probs[0..made]) |p| r.gpa.free(p); for (whos, most, probs[0..whos.len]) |w, *m, *p| { - m.* = @min(@as(i64, r.most_drafts), @max(1, w.draft_room - 1)); + m.* = @min(top, @max(1, w.draft_room - 1)); p.* = try alloc.chainProbabilities(r.gpa, try r.rates(w), @intCast(m.*)); made += 1; } diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index e29b22022c5..285fd9c9c27 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -66,6 +66,7 @@ pub const Engine = struct { .k = cfg.k, .prior = cfg.depth_prior, .most_drafts = cfg.most_drafts, + .shared_cap = cfg.shared_mtp_cap, .family_costs = &cfg.family_costs, .shared_costs = &cfg.shared_costs, .mtp_step_ms = cfg.mtp_step_ms, @@ -128,9 +129,7 @@ pub const Engine = struct { } if (live.items.len > 1 and e.cfg.family_streams) { // a shared round is synchronous: a stream that ran a step ahead lands its queued token first - for (live.items) |s| { - if (s.inflight != null) try e.landInflight(s); - } + for (live.items) |s| if (s.inflight != null) try e.landInflight(s); var kept: usize = 0; for (live.items) |s| { if (s.finished) continue; diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 5dd92e910b6..2672ab245b9 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -63,6 +63,7 @@ test { std.testing.refAllDecls(@This()); _ = @import("engine_test.zig"); _ = @import("plain_streams_test.zig"); + _ = @import("deep_chain_test.zig"); _ = @import("late_draft_test.zig"); _ = @import("long_loop.zig"); _ = @import("long_loop_test.zig"); diff --git a/zig/src/core/lanes/open.zig b/zig/src/core/lanes/open.zig index 684ab6b10ba..fa389f34136 100644 --- a/zig/src/core/lanes/open.zig +++ b/zig/src/core/lanes/open.zig @@ -145,8 +145,8 @@ fn openedCommitted(e: *Engine, s: *Stream, reach: Reach, hook: ?be.Committed) !v /// The first drafts' depth for `reach`. pub fn firstDepth(e: *Engine, s: *Stream, reach: Reach) !u32 { var who = win.who(s); - if (reach == .head and e.cfg.node_probabilities) return @intCast(try e.rule.headDepth(&who, null, win.probe(e))); - return @intCast(try e.rule.depth(who)); + const d = if (reach == .head and e.cfg.node_probabilities) try e.rule.headDepth(&who, null, win.probe(e)) else try e.rule.depth(who); + return @intCast(if (e.cfg.shared_mtp_cap > 0 and e.live.items.len > 0) @min(d, e.cfg.shared_mtp_cap) else d); // joins a shared round } /// Whether the backend can run a prompt pass a chunk at a time between rounds (`fillStream`). diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index fb265130e14..2582513acc8 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -33,7 +33,8 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ if (!s.drafts) continue; const cap = if (e.backend.vtable.draft_capacity) |f| f(e.backend.ptr, s) else e.cfg.most_drafts; const shared = if (e.cfg.shared_drafts > 0) e.cfg.shared_drafts else e.cfg.most_drafts; // Model.shared_drafts - const most = @min(cap, shared, e.cfg.most_drafts, if (limits) |l| l.depths[i] else e.cfg.most_drafts, @as(u32, @intCast(@max(0, s.draftRoom() - 1)))); + const chain = if (e.cfg.shared_mtp_cap > 0) e.cfg.shared_mtp_cap else e.cfg.most_drafts; // Model.shared_mtp_cap + const most = @min(cap, shared, chain, e.cfg.most_drafts, if (limits) |l| l.depths[i] else e.cfg.most_drafts, @as(u32, @intCast(@max(0, s.draftRoom() - 1)))); if (most == 0) continue; head.* = true; const cached = s.draft_chances.items; diff --git a/zig/src/families/flashnext/hip.zig b/zig/src/families/flashnext/hip.zig index f60dc1f6547..affce8c9db0 100644 --- a/zig/src/families/flashnext/hip.zig +++ b/zig/src/families/flashnext/hip.zig @@ -40,4 +40,5 @@ test { _ = native; _ = @import("hip/state_test.zig"); _ = @import("hip/fused_prep_test.zig"); + _ = @import("hip/mtp_drafts_test.zig"); } diff --git a/zig/src/families/flashnext/hip/facts.zig b/zig/src/families/flashnext/hip/facts.zig index fe82e50eab6..15378873419 100644 --- a/zig/src/families/flashnext/hip/facts.zig +++ b/zig/src/families/flashnext/hip/facts.zig @@ -1,10 +1,11 @@ //! The lane core's facts of a loaded Flash Next model, pure so a host test drives them without a device. const std = @import("std"); const lanes = @import("lanes"); +const hip = @import("hip"); const cache = @import("cache.zig"); -/// MTP drafts the HIP head takes at most: `--mtp-drafts` is refused past it (native/hip.zig's check). -pub const mtp_max_drafts: u32 = 3; +/// MTP drafts the HIP head takes at most: the window's rows less its pending token. +pub const mtp_max_drafts: u32 = cache.max_window - 1; /// The policy's `--mtp-drafts` capped at the head's. pub fn capDrafts(asked: u8) u32 { @@ -14,6 +15,9 @@ pub fn capDrafts(asked: u8) u32 { /// A shared round's copy window and a lone stream's first: the pending row and three copies; lone runs grow past it. const shared_copy_rows = 4; +/// Most head drafts a stream chains in a shared round; a lone stream chains the policy's drafts. +pub const shared_chain_drafts = 3; + /// The lane core's facts of a loaded model: `drafting` names a head that drafts, `drafts` its capped chains. pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) lanes.Model { return .{ @@ -24,6 +28,7 @@ pub fn factsFor(exact_width: u32, streams: usize, drafting: bool, drafts: u32) l .speculate = drafting, .speculate_early = false, .drafts = drafts, + .shared_mtp_cap = shared_chain_drafts, .hidden_rows = true, .batch_rows = @intCast(exact_width * streams), .max_streams = @intCast(streams), @@ -46,3 +51,16 @@ test "the extracted facts retain the loaded head drafting mode" { try std.testing.expectEqual(drafting, facts.draft_streams); } } + +test "the facts cap shared chains at three, and the default policy asks the lane core for three drafts" { + const a = std.testing.allocator; + const asked: u32 = (hip.Policy{}).mtp.drafts; + var cfg = try lanes.Config.init(a, factsFor(cache.max_window, 1, true, asked), cache.max_window, cache.max_window - 1); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + var deep = try lanes.Config.init(a, factsFor(cache.max_window, 1, true, 7), cache.max_window, cache.max_window - 1); + defer deep.deinit(a); + try std.testing.expectEqual(@as(u32, 7), deep.most_drafts); + try std.testing.expectEqual(@as(u32, 3), deep.shared_mtp_cap); +} diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index f3410a72f42..d7ebdeb81ff 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -486,14 +486,3 @@ pub const Fx = struct { f.free(kv.value); } }; - -test "MTP stays at three: the constant, the cap and the facts never report more" { - try std.testing.expectEqual(@as(u32, 3), facts_mod.mtp_max_drafts); - try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(3)); - try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts(7)); - const m = facts_mod.factsFor(cache.max_window, 2, true, facts_mod.capDrafts(7)); - try std.testing.expectEqual(@as(u32, 3), m.drafts); - var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); - defer cfg.deinit(std.testing.allocator); - try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); -} diff --git a/zig/src/families/flashnext/hip/mtp_drafts_test.zig b/zig/src/families/flashnext/hip/mtp_drafts_test.zig new file mode 100644 index 00000000000..e07da1050d4 --- /dev/null +++ b/zig/src/families/flashnext/hip/mtp_drafts_test.zig @@ -0,0 +1,17 @@ +//! The HIP head's MTP draft cap: the window's seven at most, the policy's default three. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const cache = @import("cache.zig"); +const facts_mod = @import("facts.zig"); + +test "MTP drafts reach the window's seven, and the policy's default stays three" { + try std.testing.expectEqual(@as(u32, 7), facts_mod.mtp_max_drafts); + try std.testing.expectEqual(@as(u32, 3), facts_mod.capDrafts((hip.Policy{}).mtp.drafts)); + try std.testing.expectEqual(@as(u32, 7), facts_mod.capDrafts(200)); + const m = facts_mod.factsFor(cache.max_window, 2, true, facts_mod.capDrafts(7)); + try std.testing.expectEqual(@as(u32, 7), m.drafts); + var cfg = try lanes.Config.init(std.testing.allocator, m, cache.max_window, cache.max_window - 1); + defer cfg.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(u32, 7), cfg.most_drafts); +} diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig index 90827bb5132..895f23a2405 100644 --- a/zig/src/families/flashnext/hip/native.zig +++ b/zig/src/families/flashnext/hip/native.zig @@ -12,6 +12,8 @@ const lanes_mod = @import("lanes.zig"); const worker = @import("worker.zig"); pub const model_type = "qwen4_exp"; +/// Most MTP drafts `--mtp-drafts` may ask of the head. +pub const mtp_max_drafts = @import("facts.zig").mtp_max_drafts; /// The MLX affine checkpoints the plan admits; the HIP products read 2- to 8-bit codes in groups of 32 to 128. pub const formats: []const []const u8 = &.{ "mlx-q3g32", "mlx-q4g32", "mlx-q6g32" }; /// Positions a stream holds when neither --context nor the checkpoint's config names a window. diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig index eed8a2d8eec..47d58449a2f 100644 --- a/zig/src/native/hip.zig +++ b/zig/src/native/hip.zig @@ -59,7 +59,7 @@ fn matrixRefused(comptime F: type, policy: hip.Policy, caps: hip.Caps) ?[]const } /// The tensor-parallel flags as the Python ROCm server checks them, and the flags this engine cannot take. -fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { +pub fn checkGroup(comptime F: type, a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.drafter != null) return refuse(a, problem, "--drafter: the HIP engine runs no DFlash2 drafter yet; serve without --drafter", .{}); if (o.tp != 1 and o.tp != 2 and o.tp != 4 and o.tp != 8) return refuse(a, problem, "--tp {d} is not a supported ROCm world size; choose 1, 2, 4 or 8", .{o.tp}); if (o.tp > 1 and o.master.len == 0) return refuse(a, problem, "--tp > 1 needs --master: rank 0's address on the link between the machines", .{}); @@ -68,7 +68,7 @@ fn checkGroup(a: Allocator, o: api.Open, problem: *[]const u8) Refused!void { if (o.tp == 1 and o.rank != 0) return refuse(a, problem, "--rank must be 0 when --tp 1", .{}); if (o.rank >= o.tp) return refuse(a, problem, "--rank {d} not in [0, --tp {d})", .{ o.rank, o.tp }); if (o.keep) |n| if (n < 0) return refuse(a, problem, "--checkpoint-slots must be 0 or more", .{}); - if (o.mtp_drafts) |n| if (n > 3) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most 3", .{n}); + if (o.mtp_drafts) |n| if (n > fam.mtpMost(F, o.tp)) return refuse(a, problem, "--mtp-drafts {d}: the HIP engine drafts at most {d}{s}", .{ n, fam.mtpMost(F, o.tp), if (fam.mtpMost(F, o.tp) < fam.mtpMost(F, 1)) " with --tp above 1" else "" }); if (o.mtp_confidence) |c| if (c < 0 or c > 1) return refuse(a, problem, "--mtp-confidence must be from 0 to 1", .{}); if (o.prompt_cache_gib) |g| if (g < 0) return refuse(a, problem, "--prompt-cache-gib must be 0 or more", .{}); } @@ -99,7 +99,7 @@ fn cacheRefused(o: api.Open) ?[]const u8 { /// Resolves the policy on rank 0 (defaults, flags, old variables, TF_POLICY), joins the group, sends it to the others. fn ready(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) (Refused || Allocator.Error)!Ready { - try checkGroup(a, o, problem); + try checkGroup(F, a, o, problem); if (cacheRefused(o)) |why| return refuse(a, problem, "{s}", .{why}); const native = modelContext(a, io, o.dir); const window = admission.contextWindow(o.context, native, F.default_context) catch |err| return switch (err) { @@ -499,48 +499,42 @@ test "the group flags: one rank source, a supported world, a master past one ran const a = arena.allocator(); var problem: []const u8 = ""; const base: api.Open = .{ .dir = "d", .model_type = "qwen3_5" }; - try checkGroup(a, base, &problem); + try checkGroup(qwen35.native, a, base, &problem); var two = base; two.tp = 2; two.master = "node0"; - try checkGroup(a, two, &problem); + try checkGroup(qwen35.native, a, two, &problem); var speed = base; speed.speed_up = "settings.json"; - try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, speed, &problem)); try std.testing.expect(std.mem.indexOf(u8, problem, "--speed-up") != null); speed.tp = 2; speed.master = "node0"; - try std.testing.expectError(error.Refused, checkGroup(a, speed, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, speed, &problem)); var three = two; three.tp = 3; - try std.testing.expectError(error.Refused, checkGroup(a, three, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, three, &problem)); var lone = two; lone.master = ""; - try std.testing.expectError(error.Refused, checkGroup(a, lone, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, lone, &problem)); var outside = two; outside.rank = 2; - try std.testing.expectError(error.Refused, checkGroup(a, outside, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, outside, &problem)); } -test "--drafter, and --mtp-drafts past three, are refused before any load, on every rank" { +test "--drafter is refused before any load, on every rank, until the HIP engine runs DFlash2" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var problem: []const u8 = ""; const drafted: api.Open = .{ .dir = "d", .model_type = "qwen3_5", .drafter = "/models/drafter" }; - try std.testing.expectError(error.Refused, checkGroup(a, drafted, &problem)); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, drafted, &problem)); try std.testing.expectStringStartsWith(problem, "--drafter: the HIP engine runs no DFlash2 drafter yet"); var follower = drafted; follower.tp = 2; follower.rank = 1; follower.master = "node0"; - try std.testing.expectError(error.Refused, checkGroup(a, follower, &problem)); - // three drafts and fewer are not refused - var o: api.Open = .{ .dir = "d", .model_type = "qwen4_exp", .mtp_drafts = 3 }; - try checkGroup(a, o, &problem); - o.mtp_drafts = 4; - try std.testing.expectError(error.Refused, checkGroup(a, o, &problem)); - try std.testing.expectEqualStrings("--mtp-drafts 4: the HIP engine drafts at most 3", problem); + try std.testing.expectError(error.Refused, checkGroup(qwen35.native, a, follower, &problem)); } test "--kv-cache fp8 is refused by name on HIP; bf16 caches are not" { @@ -567,6 +561,7 @@ test "matrix=on runs only where the matrix-core tiles exist; auto runs everywher test { _ = @import("draft_sources_hip_test.zig"); + _ = @import("mtp_drafts_hip_test.zig"); _ = @import("hip_confidence_test.zig"); } diff --git a/zig/src/native/hip_families.zig b/zig/src/native/hip_families.zig index 578661dc06f..30ae7b42e9b 100644 --- a/zig/src/native/hip_families.zig +++ b/zig/src/native/hip_families.zig @@ -50,6 +50,11 @@ pub fn confidenceFloor(comptime F: type, o: api.Open, rdna3_5_alone: bool, fallb return if (rdna3_5_alone) F.mtp_confidence_rdna3_5 else fallback; } +/// Most `--mtp-drafts` the family's head takes at `tp` ranks: its `mtp_max_drafts` on one rank, else three. +pub fn mtpMost(comptime F: type, tp: u32) u32 { + return if (@hasDecl(F, "mtp_max_drafts") and tp == 1) F.mtp_max_drafts else 3; +} + /// The family's offer, or the empty one (text, the host's defaults) when its Loaded carries none. pub fn offerOf(loaded: anytype) Offer { return if (comptime @hasField(@TypeOf(loaded), "offer")) loaded.offer else .{}; @@ -119,3 +124,13 @@ test "a Loaded without an offer gives the empty one; --vision with no offered im try std.testing.expect(textOnly(seen, empty)); try std.testing.expect(!textOnly(.{ .dir = "d", .model_type = "plain" }, empty)); } + +test "a family takes three MTP drafts unless it declares `mtp_max_drafts`, and three past one rank" { + const Deep = struct { + pub const mtp_max_drafts: u32 = 7; + }; + try std.testing.expectEqual(@as(u32, 3), mtpMost(Plain, 1)); + try std.testing.expectEqual(@as(u32, 7), mtpMost(Deep, 1)); + try std.testing.expectEqual(@as(u32, 3), mtpMost(Deep, 2)); + try std.testing.expectEqual(@as(u32, 3), mtpMost(Plain, 2)); +} diff --git a/zig/src/native/mtp_drafts_hip_test.zig b/zig/src/native/mtp_drafts_hip_test.zig new file mode 100644 index 00000000000..338057dd6e1 --- /dev/null +++ b/zig/src/native/mtp_drafts_hip_test.zig @@ -0,0 +1,20 @@ +//! The `--mtp-drafts` refusal by family and world size, before any load. +const std = @import("std"); +const api = @import("engine_api"); +const qwen35 = @import("qwen3_5"); +const flashnext = @import("flashnext"); +const hip = @import("hip.zig"); + +test "--mtp-drafts: Flash Next takes seven at --tp 1 and three above it, every other HIP family three; past that refused by name" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + inline for (.{ .{ flashnext.native, "qwen4_exp", 7, 1, "" }, .{ qwen35.native, "qwen3_5", 3, 1, "" }, .{ flashnext.native, "qwen4_exp", 3, 2, " with --tp above 1" }, .{ qwen35.native, "qwen3_5", 3, 2, "" } }) |c| { + var o: api.Open = .{ .dir = "d", .model_type = c[1], .mtp_drafts = c[2], .tp = c[3], .master = if (c[3] > 1) "node0" else "" }; + try hip.checkGroup(c[0], a, o, &problem); + o.mtp_drafts = c[2] + 1; + try std.testing.expectError(error.Refused, hip.checkGroup(c[0], a, o, &problem)); + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "--mtp-drafts {d}: the HIP engine drafts at most {d}{s}", .{ c[2] + 1, c[2], c[4] }), problem); + } +} From 724599cc255d815fca6fa564f43e2170545420fe Mon Sep 17 00:00:00 2001 From: gilby Date: Mon, 16 Nov 2026 15:04:03 +0100 Subject: [PATCH 2/5] tools: add eight copy-heavy file-edit prompts for bench_concurrent Wraps eight existing public tools/*.py files from this repository so concurrent copy-heavy drafting can be measured with tools/bench_concurrent.py. --- tools/bench_edit_prompts.json | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tools/bench_edit_prompts.json diff --git a/tools/bench_edit_prompts.json b/tools/bench_edit_prompts.json new file mode 100644 index 00000000000..5d800486d34 --- /dev/null +++ b/tools/bench_edit_prompts.json @@ -0,0 +1,42 @@ +[ + { + "name": "edit-draft_vocab_extend", + "kind": "completion", + "prompt": "Original file `draft_vocab_extend.py`:\n```python\n\"\"\"Extend a draft vocabulary with every id whose text holds characters of a script.\n\n`tools/draft_vocab.py` ranks ids by frequency over a corpus, which needs a corpus in the language\nyou care about. This tool needs none: it walks the tokenizer's ids, decodes each one, and adds the\nids whose text contains a character of the requested script to an existing list. That is what fixes\na workload whose language the shipped list does not cover -- a token outside the draft list can\nnever be drafted, so a list built for English and code leaves e.g. Chinese drafting nothing at all.\n\n python tools/draft_vocab_extend.py TOKENIZER_JSON BASE.txt OUT.txt --script cjk\n\nBoth the base list and the result are plain text, one id per line, sorted.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport unicodedata\n\nfrom tokenizers import Tokenizer\n\nSCRIPTS: dict[str, tuple[tuple[int, int], ...]] = {\n \"cjk\": ((0x3000, 0x303F), (0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF),\n (0xFF00, 0xFFEF), (0x20000, 0x2FA1F)),\n \"hangul\": ((0x1100, 0x11FF), (0x3130, 0x318F), (0xA960, 0xA97F), (0xAC00, 0xD7A3)),\n \"kana\": ((0x3040, 0x309F), (0x30A0, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)),\n \"cyrillic\": ((0x0400, 0x04FF), (0x0500, 0x052F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)),\n \"arabic\": ((0x0600, 0x06FF), (0x0750, 0x077F), (0x08A0, 0x08FF), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF)),\n \"devanagari\": ((0x0900, 0x097F), (0xA8E0, 0xA8FF)),\n \"thai\": ((0x0E00, 0x0E7F),),\n}\n\n\ndef in_scripts(text: str, ranges: tuple[tuple[int, int], ...]) -> bool:\n \"\"\"Whether ``text`` holds a character of any of the given code point ranges.\"\"\"\n\n if not text:\n return False\n if \"CJK\" in unicodedata.name(text[0], \"\") and any(a <= 0x4E00 <= b for a, b in ranges):\n return True\n for char in text:\n point = ord(char)\n if any(a <= point <= b for a, b in ranges):\n return True\n return False\n\n\ndef main() -> None:\n p = argparse.ArgumentParser()\n p.add_argument(\"tokenizer\", help=\"the checkpoint's tokenizer.json\")\n p.add_argument(\"base\", help=\"an existing draft vocabulary to extend (tools/draft_vocab.py writes one)\")\n p.add_argument(\"out\")\n p.add_argument(\"--script\", action=\"append\", required=True, choices=sorted(SCRIPTS),\n help=\"a script whose ids to add; repeat for more\")\n args = p.parse_args()\n\n tok = Tokenizer.from_file(args.tokenizer)\n vocab = tok.get_vocab_size(with_added_tokens=False)\n with open(args.base, encoding=\"utf-8\") as handle:\n base = {int(line) for line in handle if line.strip()}\n ranges = tuple(r for name in args.script for r in SCRIPTS[name])\n\n added: set[int] = set()\n for index in range(vocab):\n # byte-level BPE: a token is a byte blob, so a character test only works after decoding\n if in_scripts(tok.decode([index], skip_special_tokens=False), ranges):\n added.add(index)\n ids = sorted(base | added)\n with open(args.out, \"w\", encoding=\"utf-8\") as handle:\n handle.write(\"\".join(f\"{i}\\n\" for i in ids))\n print(f\"{args.base}: {len(base)} ids + {len(added - base)} {'/'.join(args.script)} ids \"\n f\"= {len(ids)} of {vocab} ({len(ids) / vocab:.1%}) -> {args.out}\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with every double-quoted string changed to single quotes, in full:\n```python\n" + }, + { + "name": "edit-zig_gate", + "kind": "completion", + "prompt": "Original file `zig_gate.py`:\n```python\n\"\"\"Release gate step for the native engine: passed cells as manifest entries, zig/gate.json from them, and a check.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport json\nfrom pathlib import Path\nimport sys\n\nfrom tensorfold import families, native\nfrom tensorfold.native import contract, switch\n\n\ndef _installed() -> tuple[Path, dict]:\n binary = native.binary()\n if binary is None:\n raise SystemExit(f\"no native engine in this install ({native.ROOT / native.BINARY})\")\n return binary, contract.capabilities(binary)\n\n\ndef cell(run: str, model: Path, backend: str = \"auto\") -> dict:\n \"\"\"The manifest entry for ``model`` on this machine with this install's bundle, checked against the schema.\"\"\"\n\n _, found = _installed()\n if found[\"chip\"] is None:\n raise SystemExit(\"the native engine reports no usable GPU here\")\n entry = {\"family\": families.model_type(model), \"format\": contract.weight_format(families.read_config(model)),\n \"backend\": switch.backend(backend), \"chip\": found[\"chip\"], \"run\": run, \"bundle\": native.bundle_digest()}\n contract.check(entry, contract.schema(\"gate\")[\"properties\"][\"entries\"][\"items\"])\n return entry\n\n\ndef write(out: Path, cells: list[Path], bundles: list[str] = ()) -> dict:\n \"\"\"zig/gate.json from cell files (an entry or a whole manifest each), sorted, deduplicated, checked.\"\"\"\n\n entries = []\n for path in cells:\n document = json.loads(path.read_text())\n entries += document[\"entries\"] if \"entries\" in document else [document]\n keep = sorted({json.dumps(entry, sort_keys=True) for entry in entries if not bundles or entry[\"bundle\"] in bundles})\n manifest = {\"schema\": 1, \"entries\": [json.loads(entry) for entry in keep]}\n contract.check(manifest, contract.schema(\"gate\"))\n out.write_text(json.dumps(manifest, indent=2) + \"\\n\")\n return manifest\n\n\ndef verify() -> int:\n \"\"\"Print this install's native engine, chip, bundle and the gate entries that name its bundle.\"\"\"\n\n _, found = _installed()\n digest = native.bundle_digest()\n entries = contract.manifest()[\"entries\"]\n mine = [entry for entry in entries if entry[\"bundle\"] == digest]\n print(json.dumps({\"version\": found[\"version\"], \"chip\": found[\"chip\"], \"bundle\": digest,\n \"entries\": len(entries), \"this_bundle\": mine}, indent=1))\n return 0 if mine else 1\n\n\ndef main(argv: list[str] | None = None) -> int:\n parser = argparse.ArgumentParser(description=__doc__)\n commands = parser.add_subparsers(dest=\"command\", required=True)\n one = commands.add_parser(\"cell\", help=\"print the entry for a cell whose native arm passed, run in that install\")\n one.add_argument(\"--run\", required=True, help=\"the release gate label, e.g. rel066a (public: no machine names)\")\n one.add_argument(\"--model\", required=True, type=Path, help=\"the checkpoint directory the arm served\")\n one.add_argument(\"--backend\", choices=(\"auto\", \"mlx\", \"cuda\"), default=\"auto\")\n out = commands.add_parser(\"write\", help=\"write zig/gate.json from cell files or manifests\")\n out.add_argument(\"--out\", required=True, type=Path)\n out.add_argument(\"--bundle\", action=\"append\", default=[], help=\"keep only entries for this bundle sha256\")\n out.add_argument(\"cells\", nargs=\"*\", type=Path)\n commands.add_parser(\"verify\", help=\"exit 0 only when this install's bundle has gate entries\")\n args = parser.parse_args(argv)\n if args.command == \"cell\":\n print(json.dumps(cell(args.run, args.model, args.backend), indent=1))\n return 0\n if args.command == \"write\":\n manifest = write(args.out, args.cells, args.bundle)\n print(f\"{args.out}: {len(manifest['entries'])} entries\", file=sys.stderr)\n return 0\n return verify()\n\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n```\n\nThe same file with the module docstring removed and nothing else changed, in full:\n```python\n" + }, + { + "name": "edit-clef_tokens", + "kind": "completion", + "prompt": "Original file `clef_tokens.py`:\n```python\n\"\"\"Record Clef's encode_record ids and spans for the server's clef_tokens.json fixture (CPU, checkpoint tokenizer).\"\"\"\n# usage: python3 -I tools/clef_tokens.py CLEF_DIR OUT_JSON (CLEF_DIR: Cloudflare/clef-flash at REVISION)\nimport importlib.util\nimport json\nimport os\nimport sys\n\nSOURCES = {\"repo\": \"Cloudflare/clef-flash\", \"revision\": \"fb4417d31c1d\", \"transformers\": \"5.22.1\", \"torch\": \"2.15\"}\nREVISION = \"fb4417d31c1d0f9e7e77f1141b40aaede7491e00\"\n\n\ndef records():\n \"\"\"The pinned records: every question type, the fallbacks, Unicode and combining marks, specials, truncation.\"\"\"\n out = [\n {\"state\": \"The door is open.\", \"questions\": {\"open\": {\"type\": \"noul\", \"instructions\": \"Is the door open?\"}}},\n {\"state\": {\"items\": [\"a\", \"b\"], \"n\": 3}, \"questions\": {\"pick\": {\"type\": \"choice\", \"instructions\": \"Pick one.\",\n \"criteria\": {\"zeta\": \"Last\", \"Alpha\": \"First\", \"\u00e9t\u00e9\": \"Summer\", \"beta\": None, \"10\": \"Ten\", \"9\": \"Nine\"}}}},\n {\"state\": \"Rate the reply.\", \"questions\": {\"q\": {\"type\": \"score\", \"instructions\": {\"rubric\": \"1-5\", \"strict\": True},\n \"criteria\": [\"awful\", \"poor\", \"fine\", \"good\", None]}}},\n {\"state\": \"x\", \"questions\": {\n \"missing\": {\"type\": \"noul\"}, \"none\": {\"type\": \"noul\", \"instructions\": None},\n \"empty\": {\"type\": \"noul\", \"instructions\": \"\"}, \"false\": {\"type\": \"noul\", \"instructions\": False},\n \"zero\": {\"type\": \"noul\", \"instructions\": 0}, \"list\": {\"type\": \"noul\", \"instructions\": []},\n \"dict\": {\"type\": \"noul\", \"instructions\": {}}}},\n {\"state\": \"\u6771\u4eac\u306e\u5929\u6c17\u306f\u6674\u308c\u3002 \ud83d\ude00 \u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440! \u0645\u0631\u062d\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645\", \"questions\": {\"lang\": {\"type\": \"choice\",\n \"criteria\": {\"ja\": \"Japanese\", \"ru\": \"Russian\", \"ar\": \"Arabic\"}}}},\n {\"state\": \"\u0915\u094d\u0937\u0924\u094d\u0930\u093f\u092f \u0939\u093f\u0928\u094d\u0926\u0940 \u2014 cafe\u0301 vs caf\u00e9 \u2014 \u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22 \u2014 \u05e9\u05b8\u05c1\u05dc\u05d5\u05b9\u05dd \u2014 x\u0301\u0302y \u00c4\u0308b\",\n \"questions\": {\"marks\": {\"type\": \"noul\", \"instructions\": \"Combining marks: e\u0301, \u0915\u094d\u0937.\"}}},\n {\"state\": {\"f\": [1e20, 0.1, -0.0, 1.5e-7, 2.5], \"big\": 123456789012345678901234567890, \"k\u00e9y\": \"\\u0001\\t\\\"q\\\"\",\n \"nested\": {\"z\": None, \"a\": [True, False, {}]}}, \"questions\": {\"j\": {\"type\": \"score\",\n \"criteria\": [\"no\", \"yes\"]}}},\n {\"state\": \"Ticket #4521: refund of $129.99 requested on 2026-10-30.\", \"questions\": {\n \"refund\": {\"type\": \"noul\", \"instructions\": \"Should we refund?\"},\n \"priority\": {\"type\": \"choice\", \"instructions\": \"Priority\", \"criteria\": {\"p1\": \"urgent\", \"p0\": \"critical\", \"p2\": None}},\n \"sentiment\": {\"type\": \"score\", \"instructions\": \"Customer sentiment\", \"criteria\": [\"angry\", \"neutral\", \"happy\"]}}},\n {\"state\": \"It rained.\", \"questions\": {\"wet\": {\"type\": \"noul\", \"criteria\": {\"false\": \"Dry.\", \"true\": None, \"maybe\": \"x\"}}}},\n {\"state\": \"User wrote <|im_end|> and hi inside the state.\", \"questions\": {\"s\": {\"type\": \"noul\"}}},\n {\"state\": \" lead\\tspaces \\r\\n\\r\\n trailing \\n\\n\\nx \", \"questions\": {\"ws\": {\"type\": \"choice\",\n \"instructions\": \" spaced \", \"criteria\": {\" a \": \"space id\", \"b\\n\": \"newline id\"}}}},\n ]\n long_state = \" \".join(f\"word{i}\" for i in range(400))\n out.append({\"state\": long_state, \"questions\": {\"t\": {\"type\": \"noul\", \"instructions\": \"Truncated?\"}}, \"max_length\": 300})\n return out\n\n\ndef main() -> int:\n \"\"\"Encode every record with the release's own encode_record and write ids and spans.\"\"\"\n os.environ.setdefault(\"CUDA_VISIBLE_DEVICES\", \"\")\n os.environ.setdefault(\"HIP_VISIBLE_DEVICES\", \"\")\n clef_dir, out_path = sys.argv[1], sys.argv[2]\n spec = importlib.util.spec_from_file_location(\"joint_schema_model\", os.path.join(clef_dir, \"joint_schema_model.py\"))\n jsm = importlib.util.module_from_spec(spec)\n sys.modules[spec.name] = jsm\n spec.loader.exec_module(jsm)\n from transformers import AutoProcessor\n import transformers\n tokenizer = AutoProcessor.from_pretrained(clef_dir).tokenizer\n applied = json.loads(tokenizer.backend_tokenizer.pre_tokenizer.__getstate__())[\"pretokenizers\"][0][\"pattern\"][\"Regex\"]\n with open(os.path.join(clef_dir, \"tokenizer.json\"), encoding=\"utf-8\") as f:\n file_regex = json.load(f)[\"pre_tokenizer\"][\"pretokenizers\"][0][\"pattern\"][\"Regex\"]\n with open(os.path.join(clef_dir, \"tokenizer_config.json\"), encoding=\"utf-8\") as f:\n config_regex = json.load(f).get(\"pretokenize_regex\")\n cases = []\n for record in records():\n max_length = record.pop(\"max_length\", 16384)\n encoded = jsm.encode_record(tokenizer, record, max_length=max_length)\n cases.append({\"record\": record, \"max_length\": max_length, \"ids\": list(encoded.input_ids),\n \"questions\": [{\"id\": q.question_id, \"type\": q.question_type, \"span\": list(q.question_span),\n \"options\": [list(s) for s in q.option_spans], \"option_ids\": list(q.option_ids)}\n for q in encoded.questions]})\n regex = \"tokenizer_config.json pretokenize_regex\" if applied == config_regex else \"tokenizer.json\"\n if applied not in (config_regex, file_regex):\n regex = \"neither file's\"\n out = {\"sources\": dict(SOURCES, revision_full=REVISION, transformers_seen=transformers.__version__,\n tokenizer_class=type(tokenizer).__name__, pretokenize=regex), \"cases\": cases}\n with open(out_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(out, f, ensure_ascii=False, separators=(\",\", \":\"))\n f.write(\"\\n\")\n print(f\"wrote {out_path}: {len(cases)} records, pre-tokenizer from {regex}\")\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n```\n\nThe same file with `import sys` added at the top and nothing else changed, in full:\n```python\n" + }, + { + "name": "edit-bench_thinking", + "kind": "completion", + "prompt": "Original file `bench_thinking.py`:\n```python\n\"\"\"Discover explicit thinking-off support once and label the requested benchmark mode.\"\"\"\nimport json\nimport urllib.request\n\nfrom bench_auth import authorize\n\n\ndef discover(base: str, model: str, api_key: str | None = None) -> dict:\n \"\"\"Only consistent booleans for this model are trusted; older servers remain unknown.\"\"\"\n out = {\"thinking_switch\": None, \"thinking_applicable\": None}\n try:\n request = urllib.request.Request(base.rstrip(\"/\") + \"/v1/models\", headers={\"Accept\": \"application/json\"})\n authorize(request, api_key)\n with urllib.request.urlopen(request, timeout=30) as response:\n raw = response.read(1_048_577)\n if len(raw) > 1_048_576:\n return out\n document = json.loads(raw)\n if not isinstance(document, dict) or not isinstance(document.get(\"data\"), list):\n return out\n entries = [entry.get(\"capabilities\", {}) for entry in document[\"data\"]\n if isinstance(entry, dict) and entry.get(\"id\") == model]\n for field in out:\n bits = [entry.get(field) if isinstance(entry, dict) else None for entry in entries]\n if bits and all(type(bit) is bool and bit is bits[0] for bit in bits):\n out[field] = bits[0]\n except (OSError, ValueError, TypeError):\n pass\n return out\n\n\ndef configure(items: list[dict], capabilities: dict | bool | None) -> list[dict]:\n \"\"\"Keep shared prompt definitions unchanged and retain unknown applicability for older servers.\"\"\"\n values = capabilities if isinstance(capabilities, dict) else {\"thinking_switch\": capabilities}\n return [{**item, **values} for item in items]\n\n\ndef mode(item: dict) -> str:\n \"\"\"Distinguish a verified off request, an unverified off request and a known unsupported switch.\"\"\"\n if item[\"kind\"] != \"chat\" or item.get(\"thinking_applicable\") is False:\n return \"not applicable\"\n switch = item.get(\"thinking_switch\")\n if switch is True:\n return \"off\"\n return \"default (thinking off unsupported)\" if switch is False else \"off requested (unverified)\"\n\n\ndef request_off(item: dict) -> bool:\n return item[\"kind\"] == \"chat\" and item.get(\"thinking_applicable\") is not False and item.get(\"thinking_switch\") is not False\n\n\ndef receipt(item: dict) -> dict:\n return {\"thinking\": mode(item), \"thinking_off_requested\": request_off(item),\n \"thinking_switch\": item.get(\"thinking_switch\"), \"thinking_applicable\": item.get(\"thinking_applicable\")}\n\n\ndef load_comparison(path: str | None) -> list[dict]:\n if path is None:\n return []\n with open(path, encoding=\"utf-8\") as source:\n value = json.load(source)\n rows = value.get(\"cells\") if isinstance(value, dict) else value\n if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):\n raise ValueError(\"comparison receipt must hold a row list or cells list\")\n return rows\n\n\ndef comparison(row: dict, previous: list[dict]) -> dict:\n def key(value):\n prompt = value.get(\"prompt\")\n if prompt == \"gpu-chat\":\n prompt = \"gpu-chat-no-think\"\n return prompt, value.get(\"temperature\"), value.get(\"streams\")\n def label(value):\n modes = value.get(\"thinking_modes\")\n return \", \".join(modes) if isinstance(modes, list) else value.get(\"thinking\", \"unknown\")\n matches = [old for old in previous if key(old) == key(row)]\n if not matches:\n return row\n same = all(label(old) == label(row) for old in matches)\n out = {**row, \"thinking_comparable\": same}\n if not same:\n out[\"comparison_warning\"] = \"Thinking labels differ; do not compare these rates\"\n out[\"comparison_thinking\"] = sorted({label(old) for old in matches})\n return out\n```\n\nThe same file with each function's first line followed by a `# TODO: review` comment, in full:\n```python\n" + }, + { + "name": "edit-draft_vocab", + "kind": "completion", + "prompt": "Original file `draft_vocab.py`:\n```python\n\"\"\"A draft vocabulary for a draft head: the most frequent token ids over some text, plus the lowest ids.\n\nDrafts never need to be exact (the target verifies every one), so a head can score a subset of the vocabulary and\nread proportionally fewer weights. A token outside the list can never be drafted, which costs speed, never\ncorrectness. Build it from public text only: the list ships with the package.\n\n python tools/draft_vocab.py TOKENIZER_JSON OUT.txt --size 32768 --min-count 10 'corpus/**/*.py' 'docs/**/*.md'\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport collections\nimport glob\nimport json\n\nimport sys\n\n\ndef text_main() -> None:\n from tokenizers import Tokenizer\n\n p = argparse.ArgumentParser()\n p.add_argument(\"tokenizer\")\n p.add_argument(\"out\")\n p.add_argument(\"patterns\", nargs=\"+\")\n p.add_argument(\"--size\", type=int, default=32768)\n p.add_argument(\"--keep-below\", type=int, default=1024, help=\"always keep ids below this (special tokens)\")\n p.add_argument(\"--max-bytes\", type=int, default=2_000_000, help=\"skip files larger than this\")\n p.add_argument(\"--min-count\", type=int, default=10,\n help=\"leave out ids seen fewer times (rare names and one-off words); the id prefix fills the rest\")\n p.add_argument(\"--added-tokens\", action=\"store_true\", help=\"always keep the tokenizer's added (special) tokens\")\n p.add_argument(\"--base\", help=\"an existing list kept whole (the new ids extend it)\")\n p.add_argument(\"--exclude\", help=\"ids never kept (tokens the privacy gate flags)\")\n args = p.parse_args()\n tok = Tokenizer.from_file(args.tokenizer)\n counts: collections.Counter = collections.Counter()\n files = sorted({f for pat in args.patterns for f in glob.glob(pat, recursive=True)})\n total = used = 0\n for path in files:\n try:\n with open(path, encoding=\"utf-8\") as handle:\n text = handle.read(args.max_bytes + 1)\n except (UnicodeDecodeError, OSError, IsADirectoryError):\n continue\n if not text or len(text) > args.max_bytes:\n continue\n ids = tok.encode(text).ids\n counts.update(ids)\n total += len(ids)\n used += 1\n keep = set(range(args.keep_below))\n if args.added_tokens:\n keep |= {t[\"id\"] for t in json.loads(open(args.tokenizer).read())[\"added_tokens\"]}\n if args.base:\n keep |= {int(t) for t in open(args.base).read().split()}\n drop = {int(t) for t in open(args.exclude).read().split()} if args.exclude else set()\n keep -= drop\n for tid, count in counts.most_common():\n if len(keep) >= args.size or count < args.min_count:\n break\n if tid not in drop:\n keep.add(tid)\n fill = iter(range(args.keep_below, tok.get_vocab_size()))\n while len(keep) < args.size: # the id prefix fills a short list\n t = next(fill)\n if t not in drop:\n keep.add(t)\n ids = sorted(keep)\n covered = sum(c for t, c in counts.items() if t in keep)\n with open(args.out, \"w\") as handle:\n handle.write(\"\\n\".join(str(i) for i in ids) + \"\\n\")\n print(json.dumps({\"files\": used, \"tokens\": total, \"size\": len(ids), \"coverage\": round(covered / max(1, total), 4),\n \"from_counts\": sum(1 for t, c in counts.items() if c >= args.min_count and t in keep)}))\n\n\ndef main() -> None:\n if len(sys.argv) > 1 and sys.argv[1] == \"responses\":\n from draft_vocab_responses import main as response_main\n response_main(sys.argv[2:])\n else:\n text_main()\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with the variable `args` renamed to `opts` everywhere, in full:\n```python\n" + }, + { + "name": "edit-bench_metrics", + "kind": "completion", + "prompt": "Original file `bench_metrics.py`:\n```python\n\"\"\"Prompt/TTFT rate, ITL, TPOT and round gaps from streamed chunk arrivals; docs/cache-benchmarks.md defines each.\"\"\"\nimport math\nimport statistics\n\nfrom bench_evidence import count\n\n# Old receipt keys still written beside their replacements, so readers of older receipts keep working.\nDEPRECATED = {\"prefill_tps\": \"prompt_ttft_tps\", \"aggregate_prefill_tps\": \"aggregate_prompt_ttft_tps\"}\nNOTE = {old: f\"deprecated: same value as {new}; prompt tokens over client TTFT, not the engine's prefill time\"\n for old, new in DEPRECATED.items()}\n\n\ndef rank(sorted_values: list[float], q: float) -> float | None:\n \"\"\"Nearest-rank percentile of an ascending list (None for an empty one).\"\"\"\n if not sorted_values:\n return None\n return sorted_values[max(0, math.ceil(len(sorted_values) * q) - 1)]\n\n\ndef arrivals(run: dict) -> list[float] | None:\n \"\"\"A reply's output chunk arrivals (every output kind); older run dicts without them give their text pieces.\"\"\"\n if \"output_times\" in run:\n return run[\"output_times\"]\n return [p[0] for p in run.get(\"pieces\") or []]\n\n\ndef samples(run: dict) -> tuple[list[float], bool] | None:\n \"\"\"A reply's chunk gaps in ms and whether each chunk is known to hold one token; None when unmatched.\"\"\"\n times, n = arrivals(run), count(run.get(\"tokens\"))\n if not run.get(\"complete\") or times is None or n is None or n < 2 or len(times) < 2 or len(times) > n:\n return None\n if any(b < a for a, b in zip(times, times[1:])):\n return None\n return [(b - a) * 1000 for a, b in zip(times, times[1:])], len(times) == n\n\n\ndef summary(itl: list[float], gaps: list[float], tokens: int, chunks: int, spans: int) -> dict:\n \"\"\"Token ITL/TPOT (ms; known only where every chunk held one token), chunk-level round gaps and estimates.\"\"\"\n itl, gaps = sorted(itl), sorted(gaps)\n return {\"itl_mean_ms\": statistics.fmean(itl) if itl else None, \"itl_p50_ms\": rank(itl, 0.5),\n \"itl_p95_ms\": rank(itl, 0.95), \"tpot_ms\": statistics.fmean(itl) if itl else None,\n \"chunk_tpot_estimate_ms\": sum(gaps) / spans if gaps and spans else None,\n \"round_gap_p50_ms\": rank(gaps, 0.5), \"round_gap_p95_ms\": rank(gaps, 0.95),\n \"round_gap_mean_ms\": statistics.fmean(gaps) if gaps else None,\n \"tokens_per_chunk\": tokens / chunks if chunks else None}\n\n\ndef prompt_ttft_tps(run: dict) -> float | None:\n \"\"\"prompt_tokens / client TTFT of a cold request (not engine prefill time); None for a reused or unverified one.\"\"\"\n prompt, ttft = count(run.get(\"prompt_tokens\")), run.get(\"ttft_s\")\n if run.get(\"cache_state\") != \"cold\" or not prompt or type(ttft) not in (int, float) or ttft <= 0:\n return None\n return prompt / ttft\n\n\ndef request(run: dict) -> dict:\n \"\"\"One request's figures (None where its stream does not support them).\"\"\"\n rate = prompt_ttft_tps(run)\n out = {\"prompt_ttft_tps\": rate, \"prefill_tps\": rate, \"token_timing\": None, **summary([], [], 0, 0, 0)}\n got = samples(run)\n if got is not None:\n gaps, per_token = got\n out.update(token_timing=\"token\" if per_token else \"chunk\",\n **summary(gaps if per_token else [], gaps, run[\"tokens\"], len(gaps) + 1, run[\"tokens\"] - 1))\n return out\n\n\ndef pooled(runs: list[dict]) -> dict:\n \"\"\"Every measurable stream's samples together (token ITL from one-token-a-chunk streams), and the aggregate rate.\"\"\"\n itl, gaps, tokens, chunks, spans, timed, token_timed = [], [], 0, 0, 0, 0, 0\n for r in runs:\n got = samples(r)\n if got is None:\n continue\n itl += got[0] if got[1] else []\n gaps += got[0]\n tokens += r[\"tokens\"]\n chunks += len(got[0]) + 1\n spans += r[\"tokens\"] - 1\n timed += 1\n token_timed += got[1]\n out = {\"streams_timed\": timed, \"streams_token_timed\": token_timed, **summary(itl, gaps, tokens, chunks, spans),\n \"aggregate_prompt_ttft_tps\": None}\n cold = [r for r in runs if prompt_ttft_tps(r) is not None and type(r.get(\"first\")) in (int, float)\n and type(r.get(\"sent\")) in (int, float)]\n if cold and len(cold) == len(runs):\n span = max(r[\"first\"] for r in cold) - min(r[\"sent\"] for r in cold)\n out[\"aggregate_prompt_ttft_tps\"] = sum(r[\"prompt_tokens\"] for r in cold) / span if span > 0 else None\n out[\"aggregate_prefill_tps\"] = out[\"aggregate_prompt_ttft_tps\"]\n return out\n```\n\nThe same file with all blank lines inside functions removed, in full:\n```python\n" + }, + { + "name": "edit-bench_evidence", + "kind": "completion", + "prompt": "Original file `bench_evidence.py`:\n```python\n\"\"\"Validated usage and output fingerprints shared by the HTTP benchmark clients.\"\"\"\nimport hashlib\nimport json\nimport re\n\n\ndef count(value):\n \"\"\"A server-reported nonnegative integer; missing, boolean and coerced numbers stay unknown.\"\"\"\n return value if type(value) is int and value >= 0 else None\n\n\ndef tool_pieces(delta):\n \"\"\"A delta's tool-call fragments as (index, type, name, arguments); a missing index is the fragment's position.\"\"\"\n calls = delta.get(\"tool_calls\") or []\n if not isinstance(calls, list):\n raise ValueError(\"invalid_tool_chunk\")\n out = []\n for position, call in enumerate(calls):\n function = (call.get(\"function\") or {}) if isinstance(call, dict) else None\n index = call.get(\"index\", position) if isinstance(call, dict) else None\n if not isinstance(function, dict) or type(index) is not int or index < 0:\n raise ValueError(\"invalid_tool_chunk\")\n parts = (call.get(\"type\") or \"\", function.get(\"name\") or \"\", function.get(\"arguments\") or \"\")\n if not all(isinstance(part, str) for part in parts):\n raise ValueError(\"invalid_tool_chunk\")\n out.append((index, *parts))\n return out\n\n\nclass Evidence:\n \"\"\"Hash each choice's content, reasoning and tool calls apart so network chunk boundaries cannot alter them.\"\"\"\n\n def __init__(self):\n self.choices = {}\n self.tools = {}\n self.observed_output = False\n\n def add(self, choice):\n \"\"\"Take one choice delta; returns the output kinds it carried (\"content\", \"reasoning\", \"tool\").\"\"\"\n delta = choice.get(\"delta\") or {}\n index = choice.get(\"index\", 0)\n content = choice.get(\"text\") or delta.get(\"content\") or \"\"\n reasoning = delta.get(\"reasoning_content\") or \"\"\n if not isinstance(content, str) or not isinstance(reasoning, str) or type(index) is not int or index < 0:\n raise ValueError(\"invalid_text_chunk\")\n calls = tool_pieces(delta)\n self.observed_output |= bool(content or reasoning)\n text, thought = self.choices.setdefault(index, (hashlib.sha256(), hashlib.sha256()))\n text.update(content.encode(\"utf-8\"))\n thought.update(reasoning.encode(\"utf-8\"))\n for at, kind, name, arguments in calls:\n parts = self.tools.setdefault((index, at), [\"\", [], []])\n parts[0] = parts[0] or kind\n parts[1].append(name)\n parts[2].append(arguments)\n tool = any(name or arguments for _, _, name, arguments in calls)\n return {kind for kind, seen in ((\"content\", content), (\"reasoning\", reasoning), (\"tool\", tool)) if seen}\n\n def digest(self):\n \"\"\"One choice: SHA-256 of its content and reasoning digests; several: of each choice's, in index order.\"\"\"\n empty = (hashlib.sha256(), hashlib.sha256())\n parts = [self.choices[i] for i in sorted(self.choices)] or [empty]\n each = [hashlib.sha256(text.digest() + thought.digest()) for text, thought in parts]\n return each[0].hexdigest() if len(each) == 1 else hashlib.sha256(b\"\".join(d.digest() for d in each)).hexdigest()\n\n def tool_digest(self):\n \"\"\"SHA-256 of the assembled calls (choice, index, type, name, arguments); server call ids are left out.\"\"\"\n calls = [[*key, kind, \"\".join(name), \"\".join(arguments)] for key in sorted(self.tools)\n for kind, name, arguments in [self.tools[key]]]\n return hashlib.sha256(json.dumps(calls, separators=(\",\", \":\")).encode(\"utf-8\")).hexdigest() if calls else None\n\n def finish(self, usage, runtime, complete):\n usage = usage if isinstance(usage, dict) else {}\n runtime = runtime if isinstance(runtime, dict) else {}\n details = usage.get(\"prompt_tokens_details\")\n details = details if isinstance(details, dict) else {}\n prompt = count(usage.get(\"prompt_tokens\"))\n cached = count(details.get(\"cached_tokens\"))\n tokens = count(usage.get(\"completion_tokens\"))\n valid = prompt is not None and cached is not None and cached <= prompt\n state = \"cold\" if valid and cached == 0 else \"reused\" if valid else \"unverified\"\n if not complete:\n state = \"unverified\"\n token_sha = runtime.get(\"token_sha\")\n if not isinstance(token_sha, str) or not re.fullmatch(r\"(?:[0-9a-f]{12}|[0-9a-f]{64})\", token_sha):\n token_sha = None\n token_sha256 = runtime.get(\"token_sha256\")\n if not isinstance(token_sha256, str) or not re.fullmatch(r\"[0-9a-f]{64}\", token_sha256):\n token_sha256 = None\n if token_sha and token_sha256 and not token_sha256.startswith(token_sha[:12]):\n token_sha256 = None\n verified_output = complete and self.observed_output\n return {\"prompt_tokens\": prompt, \"cached_tokens\": cached, \"tokens\": tokens, \"cache_state\": state,\n \"complete\": complete, \"token_sha\": token_sha if verified_output else None,\n \"token_sha256\": token_sha256 if verified_output else None,\n \"output_sha256\": self.digest() if verified_output else None,\n \"tool_calls\": len(self.tools), \"tool_sha256\": self.tool_digest() if complete else None}\n\n\ndef token_equal(left, right):\n \"\"\"Missing token hashes or failed/incomplete streams are unverified, never an equality pass.\"\"\"\n if left.get(\"error\") or right.get(\"error\") or not left.get(\"complete\") or not right.get(\"complete\"):\n return None\n a, b = left.get(\"token_sha256\"), right.get(\"token_sha256\")\n if not all(isinstance(v, str) and re.fullmatch(r\"[0-9a-f]{64}\", v) for v in (a, b)):\n return None\n return a == b\n```\n\nThe same file with `token_equal` renamed to `same_tokens`, in full:\n```python\n" + }, + { + "name": "edit-bench_fill", + "kind": "completion", + "prompt": "Original file `bench_fill.py`:\n```python\n\"\"\"A long prompt filling beside a running reply: what each side waits, every reply checked against its run alone.\"\"\"\nimport argparse\nimport json\nimport math\nimport sys\nimport threading\nimport time\nimport urllib.request\n\nfrom bench_auth import authorize, read_api_key\nfrom bench_evidence import token_equal\nimport bench_openai as bench\n\nif sys.version_info < (3, 11):\n sys.exit(f\"Python 3.11+ is required (this is {sys.version.split()[0]}); \"\n \"TensorFold's tools use PEP 604 unions. Try: python3.12 tools/bench_fill.py ...\")\n\nREPLY = \"Explain how a hash map handles collisions, with a small worked example in Python, then compare the approaches.\"\nREPLY_LEAD_S = 0.5 # a reply is decoding this long after it is sent\n\n\ndef largest_gaps(pieces: list) -> tuple[float | None, float | None]:\n \"\"\"The 95th percentile and the largest ms between a reply's text pieces.\"\"\"\n gaps = sorted((b[0] - a[0]) * 1000 for a, b in zip(pieces, pieces[1:]))\n if not gaps:\n return None, None\n return round(gaps[max(0, math.ceil(len(gaps) * 0.95) - 1)], 1), round(gaps[-1], 1)\n\n\ndef row(reply: dict, long_: dict) -> dict:\n \"\"\"One order's waits; both_done_s counts from whichever request went first.\"\"\"\n p95, largest = largest_gaps(reply[\"pieces\"])\n done = max(reply[\"pieces\"][-1][0], long_[\"pieces\"][-1][0])\n return {\"reply_s\": round(reply[\"pieces\"][-1][0] - reply[\"sent\"], 2), \"long_ttft_s\": round(long_[\"ttft_s\"], 2),\n \"both_done_s\": round(done - min(reply[\"sent\"], long_[\"sent\"]), 2),\n \"reply_gap_p95_ms\": p95, \"reply_gap_max_ms\": largest}\n\n\ndef summary(alone: dict, reply_first: dict, long_first: dict) -> dict:\n \"\"\"Each order beside the two runs alone; a reply is exact only when its hash is known and equals its run alone.\"\"\"\n return {\"alone\": {\"reply_s\": round(alone[\"reply\"][\"pieces\"][-1][0] - alone[\"reply\"][\"sent\"], 2),\n \"long_ttft_s\": round(alone[\"long\"][\"ttft_s\"], 2)},\n \"reply_first\": row(reply_first[\"reply\"], reply_first[\"long\"]),\n \"long_first\": row(long_first[\"reply\"], long_first[\"long\"]),\n \"exact\": all(token_equal(alone[side], order[side]) is True\n for order in (reply_first, long_first) for side in (\"reply\", \"long\")),\n \"cold\": all(r[\"long\"][\"cached_tokens\"] == 0 for r in (alone, reply_first, long_first))}\n\n\ndef request(args, key, item, tokens) -> dict:\n \"\"\"One greedy streamed request, stamped with when it was sent.\"\"\"\n sent = time.perf_counter()\n return {**bench.stream(args.base, args.model, item, tokens, 0, 1234, api_key=key), \"sent\": sent}\n\n\ndef together(args, key, first: tuple, second: tuple, lead_s: float) -> tuple[dict, dict]:\n \"\"\"`first` under way for `lead_s`, then `second` beside it; the two receipts in that order.\"\"\"\n results = [None, None]\n\n def run(at, spec):\n results[at] = request(args, key, *spec)\n\n threads = [threading.Thread(target=run, args=(at, spec)) for at, spec in enumerate((first, second))]\n threads[0].start()\n time.sleep(lead_s)\n threads[1].start()\n for t in threads:\n t.join()\n return results[0], results[1]\n\n\ndef main() -> None:\n p = argparse.ArgumentParser(description=__doc__)\n p.add_argument(\"base\")\n p.add_argument(\"model\")\n p.add_argument(\"--corpus\", required=True, help=\"a text file of at least --long tokens\")\n p.add_argument(\"--long\", type=int, default=65536, help=\"the long prompt's tokens\")\n p.add_argument(\"--reply\", type=int, default=1024, help=\"the running reply's tokens\")\n p.add_argument(\"--lead\", type=float, default=5.0, help=\"seconds the long prompt fills before the reply is sent\")\n p.add_argument(\"--output\")\n p.add_argument(\"--api-key-env\", metavar=\"NAME\", help=\"read the bearer API key from this environment variable\")\n args = p.parse_args()\n key = read_api_key(p, args.api_key_env)\n with open(args.corpus, encoding=\"utf-8\", errors=\"replace\") as f:\n body = json.dumps({\"prompt\": f.read(), \"add_special_tokens\": False}).encode()\n req = urllib.request.Request(args.base + \"/tokenize\", body, {\"Content-Type\": \"application/json\"})\n authorize(req, key)\n with urllib.request.urlopen(req, timeout=600) as r:\n ids = json.load(r)[\"tokens\"]\n if len(ids) < args.long:\n p.exit(1, f\"the corpus has {len(ids)} tokens; --long needs {args.long}\\n\")\n long_ask = ({\"name\": \"long\", \"kind\": \"completion\", \"prompt\": ids[:args.long]}, 64)\n reply_ask = ({\"name\": \"reply\", \"kind\": \"chat\", \"prompt\": REPLY}, args.reply)\n request(args, key, reply_ask[0], 16) # a warm start, so no order pays for a cold one\n alone = {\"long\": request(args, key, *long_ask), \"reply\": request(args, key, *reply_ask)}\n reply, long_ = together(args, key, reply_ask, long_ask, REPLY_LEAD_S)\n long2, reply2 = together(args, key, long_ask, reply_ask, args.lead)\n report = summary(alone, {\"reply\": reply, \"long\": long_}, {\"reply\": reply2, \"long\": long2})\n print(json.dumps(report), flush=True)\n if args.output:\n with open(args.output, \"w\") as f:\n json.dump(report, f, indent=1)\n if not report[\"cold\"]:\n p.exit(1, \"the long prompt reused cached tokens: serve with --prompt-cache-gib 0\\n\")\n if not report[\"exact\"]:\n p.exit(1, \"a reply's tokens differ beside the other request\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe same file with the `main` function renamed to `run` and its call updated, in full:\n```python\n" + } +] From e9506a304ce4217419df589054b5e59aafb1477f Mon Sep 17 00:00:00 2001 From: gilby Date: Wed, 18 Nov 2026 15:38:18 +0100 Subject: [PATCH 3/5] nemotron/hip: opt-in --mtp-drafts up to 15 on a lone stream Keep the four-row window and three drafts by default (and in shared rounds and at --tp > 1), while widening a lone stream's window up to 16 rows under --mtp-drafts 4..15 with shared rounds capped at three head drafts a stream and plan rows kept at max(4 * streams, min(streams * window, 32)). --- docs/recipes/nemotron-3.5.md | 19 +++ zig/src/families/nemotron/hip.zig | 1 + zig/src/families/nemotron/hip/costs.zig | 9 +- .../nemotron/hip/deep_drafts_test.zig | 151 ++++++++++++++++++ zig/src/families/nemotron/hip/engine.zig | 6 +- zig/src/families/nemotron/hip/head.zig | 4 +- zig/src/families/nemotron/hip/lanes.zig | 69 ++++---- zig/src/families/nemotron/hip/native.zig | 16 +- zig/src/families/nemotron/hip/round.zig | 35 +++- zig/src/families/nemotron/hip/worker.zig | 5 +- zig/src/hip/kernel_tests/nemotron/window.zig | 2 +- zig/src/native/draft_sources_hip_test.zig | 1 + zig/src/native/mtp_drafts_hip_test.zig | 12 +- zig/tests/nemotron_hip/gen.zig | 29 +++- 14 files changed, 305 insertions(+), 54 deletions(-) create mode 100644 zig/src/families/nemotron/hip/deep_drafts_test.zig diff --git a/docs/recipes/nemotron-3.5.md b/docs/recipes/nemotron-3.5.md index e947b47c60f..2a04b713a06 100644 --- a/docs/recipes/nemotron-3.5.md +++ b/docs/recipes/nemotron-3.5.md @@ -270,3 +270,22 @@ servers plus one `--no-drafts` server): | `bench_openai` code / chat (`--no-drafts`) | median tok/s | 86.2 / 86.1 | 87.9 / 87.9 | 1.00 token/round (1.828 GB read/token, ~160.7 GB/s greedy) | | `bench_concurrent` 1 / 2 / 4 streams | aggregate tok/s | 124.4 / 136.0-137.0 / 168.4-168.9 | 131.5-132.4 / 146.5 / 175.5-176.4 | 84/84 concurrent=alone; 48/48 alone=`"draft": false` | | `bench_cache` 2,048 / 7,099 / 28,333 tokens | cold TTFT (s) | — | 0.731-0.732 / 2.672-2.676 / 13.130-13.205 | 2,797-2,800 / 2,653-2,657 / 2,146-2,158 tok/s (repeated cold) | + +## Deep MTP drafts on HIP (opt-in) + +On one HIP rank (`--tp 1`), Nemotron 3.5 Lightning keeps its four-row verify window and three MTP drafts by default so latency, GTT memory and shared-round throughput stay as before. Passing `--mtp-drafts N` from `4` to `15` widens each stream's verify window to `N + 1` rows (up to sixteen) for a lone decoding stream, while shared multi-stream rounds stay capped at three head drafts per stream and 32 rows in the round plan (or `4 * streams` above eight streams; above `--tp 1`, `--mtp-drafts` remains capped at `3` and `--mtp-drafts 16` is refused by name). + +Measured on a Strix Halo (`gfx1151`, `TENSORFOLD_MEMORY_RESERVE_GIB=4 --context 131072 --parallel 4 --prompt-cache-gib 0`, greedy and sampled 256-token replies): + +| Checkpoint | Prompt suite (`L=1` unless noted) | `d=3` (default) | `d=5` | `d=7` | `d=11` | `d=15` | +|---|---|---|---|---|---|---| +| `Lightning-30B-A3B-MLX-4bit` | Edit copy (`T=1.0 / T=0.0`, tok/s) | `149.0 / 149.6` | `165.5 / 164.8` | `184.3 / 179.4` | `212.6 / 207.8` | `229.1 / 214.0` | +| `Lightning-30B-A3B-MLX-4bit` | Edit copy `L=2` agg (`T=1.0 / T=0.0`) | `151.6 / 156.6` | `178.3 / 170.4` | `187.0 / 182.8` | `172.8 / 175.2` | `188.7 / 187.1` | +| `Lightning-30B-A3B-MLX-4bit` | General `bench_prompts` (`T=1.0 / T=0.0`) | `125.5 / 131.4` | `125.9 / 131.3` | `125.5 / 133.0` | `124.9 / 134.4` | `124.6 / 135.2` | +| `Lightning-30B-A3B-MLX-4bit` | `fibonacci-raw` / `gpu-chat` (`T=0.0`) | `122.6 / 98.8` | `125.3 / 94.5` | `132.0 / 94.5` | `135.2 / 94.5` | `136.6 / 94.5` | +| `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP` | Edit copy (`T=1.0 / T=0.0`, tok/s) | `132.9 / 134.3` | `151.9 / 153.3` | `165.1 / 167.9` | `186.3 / 198.0` | `194.0 / 204.7` | +| `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP` | Edit copy `L=2` agg (`T=1.0 / T=0.0`) | `144.0 / 145.1` | `163.2 / 170.5` | `179.0 / 178.4` | `163.0 / 163.5` | `175.3 / 184.0` | +| `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP` | General `bench_prompts` (`T=1.0 / T=0.0`) | `104.8 / 124.1` | `110.7 / 125.0` | `110.5 / 123.8` | `110.0 / 122.6` | `109.6 / 120.9` | +| `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP` | `fibonacci-raw` / `gpu-chat` (`T=0.0`) | `122.8 / 91.8` | `123.3 / 95.8` | `122.5 / 96.4` | `123.9 / 94.7` | `122.7 / 96.8` | + +General prose and plain prompts are mixed or slightly slower at higher depth (`gpu-chat` at `T=0` drops from `98.8` to `94.5` tok/s on `Lightning-30B-A3B-MLX-4bit`, and `bench_prompts` at `T=0` drops from `124.1` to `120.9` tok/s on `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP`), whereas copy-heavy edits gain `43–54%` at one stream (`229.1` vs `149.0` tok/s on `MLX-4bit`; `204.7` vs `134.3` on `oQ4e`) and `20–27%` at two. Idle GTT across four `--parallel 4` streams grows by `+2,243.3 MiB` from `--mtp-drafts 3` (`1.15 GiB` per stream) to `--mtp-drafts 15` (`1.70 GiB` per stream). Every checked reply kept identical tokens across depths `3..15`, solo runs, concurrent runs, and `"draft": false` baselines (`100%` across `84` OpenAI, `588` concurrent/alone, and `336` serial checks per checkpoint) as well as across `12` prompt-cache reuse runs (`42/42` reused rows at `--mtp-drafts 7, 11, 15` with `--prompt-cache-gib 8`). diff --git a/zig/src/families/nemotron/hip.zig b/zig/src/families/nemotron/hip.zig index 46ee4298c98..87b332d7f66 100644 --- a/zig/src/families/nemotron/hip.zig +++ b/zig/src/families/nemotron/hip.zig @@ -27,6 +27,7 @@ pub const native = @import("hip/native.zig"); test { _ = @import("hip/prompt_test.zig"); + _ = @import("hip/deep_drafts_test.zig"); _ = config; _ = tensors; _ = plan; diff --git a/zig/src/families/nemotron/hip/costs.zig b/zig/src/families/nemotron/hip/costs.zig index bbfa75368fb..e21a2506b47 100644 --- a/zig/src/families/nemotron/hip/costs.zig +++ b/zig/src/families/nemotron/hip/costs.zig @@ -13,6 +13,7 @@ pub const Costs = shared.Costs; /// A scratch lane's kept length in the timings, and the positions it covers past it (the head steps' too). const at = 16; const room = 2 * shared.window * 4; +const timed_depth = 3; const Rig = struct { h: *Hip, @@ -63,10 +64,10 @@ const Rig = struct { } }; - /// One chained head step: a lone chain of the deepest depth from a scratch lane's (garbage) row. + /// One chained head step: a chain of `timed_depth` from a scratch lane's (garbage) row. fn step(r: *Rig, hd: *head.Head) !f64 { const run: Chain = .{ .r = r, .hd = hd }; - return try shared.mean(run, Chain.go) / head.max_depth; + return try shared.mean(run, Chain.go) / timed_depth; } const Chain = struct { @@ -78,7 +79,7 @@ const Rig = struct { const l = x.r.ls[0]; l.s.len = at; l.s.mtp_len = at; - var out: [head.max_depth]u32 = undefined; + var out: [timed_depth]u32 = undefined; var jobs = [_]head.Job{.{ .s = &l.s, .hidden = l.hidden.base(), .next = x.r.tokens[0][0..1], .out = &out }}; try h.e.fresh(); try x.hd.chains(h.e.ops(&h.e.arena), &jobs); @@ -98,6 +99,6 @@ pub fn measure(h: *Hip, out: *Costs) !void { try l.s.cover(&e.pool, at + room); l.s.len = at; } - try shared.forwards(&r, @min(lanes.max_window, e.plan.rows), streams, e.plan.rows, out); + try shared.forwards(&r, @min(e.window, e.plan.rows), streams, e.plan.rows, out); if (h.head) |hd| out.step_ms = try r.step(hd); } diff --git a/zig/src/families/nemotron/hip/deep_drafts_test.zig b/zig/src/families/nemotron/hip/deep_drafts_test.zig new file mode 100644 index 00000000000..f94beafae54 --- /dev/null +++ b/zig/src/families/nemotron/hip/deep_drafts_test.zig @@ -0,0 +1,151 @@ +//! Nemotron's deeper MTP windows: without --mtp-drafts past three the facts and lane bytes keep the four-row ones. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const round = @import("round.zig"); +const head = @import("head.zig"); +const hip_lanes = @import("lanes.zig"); +const native = @import("native.zig"); +const costs = @import("costs.zig"); + +const depth = lanes.depth; +const Table = lanes.table.Table; + +/// Representative forward ms by window rows and shared rows for depth-rule equivalence tests. +fn timed() costs.Costs { + var c: costs.Costs = .{ .step_ms = 0.83 }; + for ([_]f64{ 13.9, 15.1, 16.0, 16.9 }, 0..) |ms, i| c.window[i] = .{ .width = @intCast(i + 1), .ms = ms }; + c.windows = 4; + for ([_]u32{ 2, 4, 8, 12 }, [_]f64{ 15.0, 17.0, 21.5, 26.0 }, 0..) |w, ms, i| c.shared[i] = .{ .width = w, .ms = ms }; + c.shareds = 4; + return c; +} + +/// The facts as the engine reported them before deeper windows: four rows a window, three drafts, no shared cap. +fn before(streams: usize, c: *const costs.Costs) lanes.Model { + return .{ + .exact_width = 4, + .gpu_tokens = false, + .mtp = true, + .speculate = true, + .speculate_early = false, + .drafts = 3, + .hidden_rows = true, + .batch_rows = @intCast(4 * streams), + .max_streams = @intCast(streams), + .draft_streams = true, + .plain_guard = c.windows > 0, + .window_costs = c.window[0..c.windows], + .shared_costs = c.shared[0..c.shareds], + .mtp_step_ms = c.step_ms, + }; +} + +test "without --mtp-drafts the window, lane bytes and facts are the four-row ones plus a shared cap of three" { + const a = std.testing.allocator; + const asked = (hip.Policy{}).mtp.drafts; + const window = round.windowFor(asked); + try std.testing.expectEqual(@as(usize, 4), window); + try std.testing.expectEqual(native.laneBytesFor(32768, 4, 65536, 24_541_184, 2688, 2), native.laneBytesFor(32768, window, 65536, 24_541_184, 2688, 2)); + var c = timed(); + for ([_]usize{ 1, 3, 4 }) |streams| { + const at: hip_lanes.Setup = .{ .window = window, .rows = round.planRows(streams, window), .slots = streams }; + try std.testing.expectEqual(streams * window, at.rows); + var got = hip_lanes.factsFor(at, true, asked, &c); + try std.testing.expectEqual(@as(u32, 3), got.shared_mtp_cap); + got.shared_mtp_cap = 0; + try std.testing.expectEqualDeep(before(streams, &c), got); + var cfg = try lanes.Config.init(a, hip_lanes.factsFor(at, true, asked, &c), @intCast(window), @intCast(window - 1)); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, 3), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, 4), cfg.family_width); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + try std.testing.expectEqual(@as(u32, @intCast(4 * streams)), cfg.batch_rows); + } +} + +const NoCopy = struct { + fn copy(_: *anyopaque, _: *const depth.Who) bool { + return false; + } +}; + +fn ruleOf(prior: []const f64, family: *const Table, shared: *const Table, cap: u32, guard: bool) depth.Rule { + return .{ + .gpa = std.testing.allocator, + .prior = prior, + .most_drafts = 3, + .shared_cap = cap, + .family_costs = family, + .shared_costs = shared, + .mtp_step_ms = 0.83, + .plain_guard = guard, + .node_probabilities = false, + .batch_rows = 16, + }; +} + +fn whoOf(state: *?depth.State) depth.Who { + return .{ .state = state, .draft_room = 100, .finished = false, .forced = false }; +} + +test "at three drafts the shared cap of three changes no lone depth and no shared budget" { + const a = std.testing.allocator; + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var family: Table = .{}; + defer family.deinit(a); + var shared: Table = .{}; + defer shared.deinit(a); + const c = timed(); + for (c.window[0..c.windows]) |x| try family.put(a, x.width, x.ms); + for (1..17) |w| try shared.put(a, @intCast(w), 13.0 + @as(f64, @floatFromInt(w))); + var none: Table = .{}; + defer none.deinit(a); + const priors = [_][3]f64{ .{ 0.95, 0.9, 0.85 }, .{ 0.85, 0.7, 0.6 }, .{ 0.5, 0.4, 0.3 } }; + for (&priors) |*prior| for ([_]*const Table{ &family, &none }) |fam| for ([_]bool{ false, true }) |guard| { + var old = ruleOf(prior, fam, &shared, 0, guard); + defer old.deinit(); + var new = ruleOf(prior, fam, &shared, 3, guard); + defer new.deinit(); + var so: [3]?depth.State = @splat(null); + var sn: [3]?depth.State = @splat(null); + defer for (&so, &sn) |*x, *y| { + if (x.*) |*s| s.deinit(a); + if (y.*) |*s| s.deinit(a); + }; + for (0..24) |r| { + const lone_old = try old.headDepth(&whoOf(&so[0]), null, probe); + try std.testing.expectEqual(lone_old, try new.headDepth(&whoOf(&sn[0]), null, probe)); + try old.observeDepth(whoOf(&so[0]), lone_old, @intCast(r % 4)); + try new.observeDepth(whoOf(&sn[0]), lone_old, @intCast(r % 4)); + var wo = [_]depth.Who{ whoOf(&so[1]), whoOf(&so[2]) }; + var wn = [_]depth.Who{ whoOf(&sn[1]), whoOf(&sn[2]) }; + var bo: [2]i64 = undefined; + var bn: [2]i64 = undefined; + try old.budgets(&wo, probe, false, &bo); + try new.budgets(&wn, probe, false, &bn); + try std.testing.expectEqualSlices(i64, &bo, &bn); + } + }; +} + +test "--mtp-drafts 4 to 15 widens the window to 16; shared rounds keep 3 drafts and at least default plan rows" { + const a = std.testing.allocator; + try std.testing.expectEqual(@as(usize, 15), head.max_depth); + try std.testing.expectEqual(@as(u32, 15), native.mtp_max_drafts); + var c = timed(); + for (4..16) |n| for ([_]usize{ 1, 2, 4, 8, 16 }) |streams| { + const asked: u8 = @intCast(n); + const window = round.windowFor(asked); + try std.testing.expectEqual(n + 1, window); + const at: hip_lanes.Setup = .{ .window = window, .rows = round.planRows(streams, window), .slots = streams }; + try std.testing.expectEqual(@max(streams * 4, @min(streams * window, 32)), at.rows); + var cfg = try lanes.Config.init(a, hip_lanes.factsFor(at, true, asked, &c), @intCast(window), @intCast(window - 1)); + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u32, asked), cfg.most_drafts); + try std.testing.expectEqual(@as(u32, @intCast(window)), cfg.family_width); + try std.testing.expectEqual(@as(u32, 3), cfg.shared_mtp_cap); + try std.testing.expectEqual(@as(u32, @intCast(at.rows)), cfg.batch_rows); + }; +} diff --git a/zig/src/families/nemotron/hip/engine.zig b/zig/src/families/nemotron/hip/engine.zig index 25b53c2500a..a781e8eb679 100644 --- a/zig/src/families/nemotron/hip/engine.zig +++ b/zig/src/families/nemotron/hip/engine.zig @@ -75,7 +75,8 @@ pub const Engine = struct { comm: ?hip.collective.Comm = null, arena: hip.Arena, pool: pages.Pool, - /// A lane round's plan and its windows, sized with the pool for `o.streams` streams of `rounds.max_window` rows. + /// A stream's window, its round plan and its windows, sized with the pool for `o.streams` streams. + window: usize, plan: rounds.Plan, wins: []rounds.Window, sized: bool, @@ -110,6 +111,7 @@ pub const Engine = struct { e.gpa = gpa; e.io = io; e.o = o; + e.window = rounds.windowFor(o.policy.mtp.drafts); e.stopped = false; e.driver = try hip.Runtime.open(); errdefer e.driver.close(); @@ -175,7 +177,7 @@ pub const Engine = struct { head_kv, ); errdefer e.pool.deinit(); - e.plan = try rounds.Plan.init(&e.driver, &e.pool, streams * rounds.max_window, streams, d.vocab); + e.plan = try rounds.Plan.init(&e.driver, &e.pool, rounds.planRows(streams, e.window), streams, d.vocab); errdefer e.plan.deinit(); e.wins = try e.gpa.alloc(rounds.Window, streams); e.sized = true; diff --git a/zig/src/families/nemotron/hip/head.zig b/zig/src/families/nemotron/hip/head.zig index e5d00fd0e3f..c9b4b0beb38 100644 --- a/zig/src/families/nemotron/hip/head.zig +++ b/zig/src/families/nemotron/hip/head.zig @@ -8,8 +8,8 @@ const pages = @import("pages.zig"); const Tensor = hip.ops.Tensor; -/// Drafts a chain holds at most. -pub const max_depth = 3; +/// Drafts a lone stream's chain holds at most. +pub const max_depth = 15; /// One stream's work of a head round: its model rows and the token after each, then the drafts chained from the last. pub const Job = struct { s: *pages.Stream, hidden: u64, next: []const u32, out: []u32, got: usize = 0 }; diff --git a/zig/src/families/nemotron/hip/lanes.zig b/zig/src/families/nemotron/hip/lanes.zig index afff904588a..f368e34fc15 100644 --- a/zig/src/families/nemotron/hip/lanes.zig +++ b/zig/src/families/nemotron/hip/lanes.zig @@ -20,6 +20,12 @@ const Tensor = hip.ops.Tensor; /// Rows a window holds at most: the pending token and the drafts (every width reproduces one-token steps). pub const max_window = round.max_window; +/// Most head drafts a stream chains in a round it shares; a lone stream chains up to `--mtp-drafts`. +pub const shared_chain_drafts = 3; + +/// Pure window and plan sizes passed to `factsFor` so host tests check `lanes.Model` without a device. +pub const Setup = struct { window: usize, rows: usize, slots: usize }; + pub const Lane = struct { s: pages.Stream, /// Each row's Mamba states of the last verify (slot 0 the state before it), for a keep of fewer rows. @@ -82,6 +88,29 @@ const Scratch = struct { } }; +/// The lane core's facts from window/plan sizes, drafting toggle, requested depth and timed costs. +pub fn factsFor(at: Setup, drafting: bool, drafts: u8, c: *const costs.Costs) lanes.Model { + // plain rounds compete with drafted ones once the forwards are timed + const timed = drafting and c.windows > 0; + return .{ + .exact_width = @intCast(at.window), + .gpu_tokens = false, + .mtp = drafting, + .speculate = drafting, + .speculate_early = false, + .drafts = @min(head.max_depth, drafts), + .shared_mtp_cap = shared_chain_drafts, + .hidden_rows = true, + .batch_rows = @intCast(at.rows), + .max_streams = @intCast(at.slots), + .draft_streams = drafting, + .plain_guard = timed, + .window_costs = c.window[0..c.windows], + .shared_costs = c.shared[0..c.shareds], + .mtp_step_ms = c.step_ms, + }; +} + pub const Hip = struct { gpa: std.mem.Allocator, e: *Engine, @@ -163,30 +192,14 @@ pub const Hip = struct { pub fn laneBytes(e: *const Engine) usize { const m = e.model_(); const state = pages.Stream.stateBytes(m.dims, e.act, e.cfg.count(.mamba)); - return state * (max_window + 2) + max_window * m.dims.hidden * e.act.size() + 4 * pages.pagesFor(e.o.capacity); + return state * (e.window + 2) + e.window * m.dims.hidden * e.act.size() + 4 * pages.pagesFor(e.o.capacity); } /// The facts the round loop reads at setup: exact windows, every stream's window in one round, batched drafts. pub fn facts(h: *const Hip) lanes.Model { - const drafting = h.head != null and h.e.o.policy.mtp.drafts > 0; - // plain rounds compete with drafted ones once the forwards are timed - const timed = drafting and h.costs.windows > 0; - return .{ - .exact_width = max_window, - .gpu_tokens = false, - .mtp = drafting, - .speculate = drafting, - .speculate_early = false, - .drafts = @min(head.max_depth, h.e.o.policy.mtp.drafts), - .hidden_rows = true, - .batch_rows = @intCast(h.e.plan.rows), - .max_streams = @intCast(h.e.plan.slots), - .draft_streams = drafting, - .plain_guard = timed, - .window_costs = h.costs.window[0..h.costs.windows], - .shared_costs = h.costs.shared[0..h.costs.shareds], - .mtp_step_ms = h.costs.step_ms, - }; + const e = h.e; + const drafting = h.head != null and e.o.policy.mtp.drafts > 0; + return factsFor(.{ .window = e.window, .rows = e.plan.rows, .slots = e.plan.slots }, drafting, e.o.policy.mtp.drafts, &h.costs); } pub fn drawer(h: *Hip) *draw.Drawer { @@ -231,9 +244,9 @@ pub const Hip = struct { errdefer h.gpa.destroy(l); var st = try e.openStream(); errdefer st.deinit(&e.pool); - var snaps = try hip.DeviceBuffer.alloc(&e.driver, (max_window + 1) * h.state_bytes); + var snaps = try hip.DeviceBuffer.alloc(&e.driver, (e.window + 1) * h.state_bytes); errdefer snaps.free(); - var hidden = try hip.DeviceBuffer.alloc(&e.driver, max_window * m.dims.hidden * e.act.size()); + var hidden = try hip.DeviceBuffer.alloc(&e.driver, e.window * m.dims.hidden * e.act.size()); errdefer hidden.free(); l.* = .{ .s = st, .snaps = snaps, .hidden = hidden }; return l; @@ -264,7 +277,7 @@ pub const Hip = struct { pub fn begin(h: *Hip, s: *lanes.Stream) !*Lane { const e = h.e; const prompt = s.prompt(); - if (prompt.len == 0 or prompt.len + s.max_new + max_window + 1 > e.o.capacity) return error.PromptTooLong; + if (prompt.len == 0 or prompt.len + s.max_new + e.window + 1 > e.o.capacity) return error.PromptTooLong; // refused before the other ranks hear the prompt: a rank that fails a step it was sent leaves the group for (prompt) |t| if (t >= e.model_().dims.vocab) return error.TokenOutsideVocabulary; const gop = try h.streams.map.getOrPut(h.gpa, s); @@ -275,7 +288,7 @@ pub const Hip = struct { gop.value_ptr.* = l; l.id = try h.streams.idOf(s); // pages for the whole request are promised now, so no round runs out of them - const total = prompt.len + s.max_new + max_window + 1; + const total = prompt.len + s.max_new + e.window + 1; const need = pages.pagesFor(total); if (!h.prefix.store.reclaim(need)) return error.OutOfPages; l.s.promised = need; @@ -382,7 +395,7 @@ pub const Hip = struct { for (ws, 0..) |w, i| { const l = try h.streams.get(w.stream); try glue.settle(h, l); - const n = try glue.windowTokens(w, l.held[0..l.held_n], l.s.len, &h.sc.tokens[i]); + const n = try glue.windowTokens(w, l.held[0..l.held_n], l.s.len, h.sc.tokens[i][0..e.window]); try l.s.cover(&e.pool, l.s.len + n); try h.syncPages(l); h.sc.lanes[i] = l; @@ -429,9 +442,9 @@ pub const Hip = struct { h.sc.firsts[i] = try glue.firstToken(&h.streams.drawn, r); break :blk h.sc.firsts[i..][0..1]; }; - if (next.len == 0 or next.len > max_window) return error.PositionMismatch; + if (next.len == 0 or next.len > e.window) return error.PositionMismatch; // the chained steps write the head's keys past the kept rows: their pages must be the stream's own - try l.s.cover(&e.pool, l.s.len + head.max_depth); + try l.s.cover(&e.pool, l.s.len + e.window - 1); try h.syncPages(l); if (tracing()) std.log.info( "trace {s} draft at {d}: pairs {any}, depth {d}", @@ -442,7 +455,7 @@ pub const Hip = struct { .s = &l.s, .hidden = l.hidden.base(), .next = next, - .out = l.held[0..@min(r.depth, head.max_depth)], + .out = l.held[0..@min(r.depth, e.window - 1)], }; } try e.fresh(); diff --git a/zig/src/families/nemotron/hip/native.zig b/zig/src/families/nemotron/hip/native.zig index ae40fb15ea9..36d7b818794 100644 --- a/zig/src/families/nemotron/hip/native.zig +++ b/zig/src/families/nemotron/hip/native.zig @@ -16,6 +16,13 @@ const widths = @import("widths.zig"); pub const model_type = "nemotron_h"; pub const formats = admit.formats; +/// MTP drafts the HIP head chains on one rank: `--mtp-drafts` is refused past this. +pub const mtp_max_drafts: u32 = @import("head.zig").max_depth; + +/// Device bytes one lane holds (`window` tokens, `rw` window rows); `pub` so `deep_drafts_test.zig` checks it. +pub fn laneBytesFor(window: usize, rw: usize, page: u64, state: u64, hidden: u64, act: u64) u64 { + return pages.pagesFor(window + rw + 1) * page + state * (rw + 2) + rw * hidden * act; +} /// Positions a stream holds when neither --context nor the checkpoint's config names a window. pub const default_context: i64 = 32768; /// The engine cuts prompts itself. @@ -206,14 +213,13 @@ fn prepare( else => steps.refuseAll(a, problem, "the native HIP engine cannot load {s} ({t})", .{ dir, err }), }; errdefer e.deinit(); - const capacity: usize = window + hip_lanes.max_window + 1; + const capacity: usize = window + e.window + 1; const token = try plan.tokenBytes(c, o.world, act, v.mtp); const state = try plan.streamBytes(c, o.world, act); const page = token * pages.tokens; const snap = state + c.hidden * act; // a lane: its pages, its Mamba state, its window's snapshots and the head's rows - const lane: u64 = pages.pagesFor(capacity) * page + state * (hip_lanes.max_window + 2) + - hip_lanes.max_window * c.hidden * act; + const lane: u64 = laneBytesFor(window, e.window, page, state, c.hidden, act); const fixed: u64 = v.weights + admit.scratch_bytes + (64 << 20); if (fixed >= room) return heard(steps, problem, admit.tooBig(a, v, .{ .window = window, .room = room }, problem)); const left = room - fixed; @@ -272,7 +278,7 @@ fn prepare( cache.pages, cache.snaps, e.o.chunk, - hip_lanes.max_window, + e.window, }); return .{ .e = e, .streams = streams, .cache = cache, .startup = startup }; } @@ -326,7 +332,7 @@ pub fn open( return .{ .backend = backend.backend(), .facts = backend.facts(), - .rows = hip_lanes.max_window, + .rows = @intCast(p.e.window), .ctx = own, .deinit = release, .streams = p.streams, diff --git a/zig/src/families/nemotron/hip/round.zig b/zig/src/families/nemotron/hip/round.zig index 2eac1a16c7f..182bdc5f1c7 100644 --- a/zig/src/families/nemotron/hip/round.zig +++ b/zig/src/families/nemotron/hip/round.zig @@ -10,8 +10,25 @@ const Ops = hip.ops.Ops; const Tensor = hip.ops.Tensor; const pops = hip.plan_ops; -/// Rows a stream's window holds at most: the pending token and the drafts (every width reproduces one-token steps). -pub const max_window = 4; +/// Rows a stream's window holds by default: the pending token and three drafts. +pub const default_window = 4; + +/// Rows a lone stream's window holds at most when `--mtp-drafts` opts in past three. +pub const max_window = 16; + +/// Shared round row ceiling up to eight streams (above eight, `planRows` keeps `streams * default_window`). +pub const shared_cap_rows = 32; + +/// Window rows for a policy's `--mtp-drafts`: four up to three drafts (exact baseline), else `asked + 1` up to sixteen. +pub fn windowFor(asked: u8) usize { + return if (asked <= 3) default_window else @min(max_window, @as(usize, asked) + 1); +} + +/// Plan rows for `streams` and `window`: at least `streams * default_window`, and up to `shared_cap_rows` past four. +pub fn planRows(streams: usize, window: usize) usize { + if (window <= default_window) return streams * window; + return @max(streams * default_window, @min(streams * window, shared_cap_rows)); +} /// Shortest span the attention walk covers; spans double from here (a row's bits do not depend on the span). pub const min_span = 128; @@ -267,3 +284,17 @@ test "security: a round refuses a token at or past the vocabulary before its pla const win: Window = .{ .s = undefined, .pos = 0, .tokens = &.{ 7, 8 } }; try std.testing.expectError(error.TokenOutsideVocabulary, p.send(&.{win}, 4096, undefined)); } + +test "windowFor holds four up to three drafts and tracks --mtp-drafts up to 16; planRows keeps shared floor" { + for (0..4) |n| try std.testing.expectEqual(@as(usize, 4), windowFor(@intCast(n))); + for (4..16) |n| try std.testing.expectEqual(n + 1, windowFor(@intCast(n))); + try std.testing.expectEqual(@as(usize, 16), windowFor(16)); + try std.testing.expectEqual(@as(usize, 16), windowFor(255)); + for ([_]usize{ 1, 2, 4, 8, 16 }) |s| try std.testing.expectEqual(4 * s, planRows(s, 4)); + try std.testing.expectEqual(@as(usize, 16), planRows(1, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(2, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(4, 16)); + try std.testing.expectEqual(@as(usize, 32), planRows(8, 8)); + try std.testing.expectEqual(@as(usize, 64), planRows(16, 8)); + try std.testing.expectEqual(@as(usize, 64), planRows(16, 16)); +} diff --git a/zig/src/families/nemotron/hip/worker.zig b/zig/src/families/nemotron/hip/worker.zig index 544dfc1e16d..df27d9e690b 100644 --- a/zig/src/families/nemotron/hip/worker.zig +++ b/zig/src/families/nemotron/hip/worker.zig @@ -64,10 +64,7 @@ pub const Worker = struct { if (n > ls.len) return error.WindowTooWide; var at: usize = 2; for (0..n) |i| { - if (at + 2 > m.len or m[at + 1] > lanes.max_window or at + 2 + m[ - at + - 1 - ] > m.len) return error.WindowTooWide; + if (at + 2 > m.len or m[at + 1] > w.h.e.window or at + 2 + m[at + 1] > m.len) return error.WindowTooWide; ls[i] = try f.lane(m[at]); toks[i] = m[at + 2 ..][0..m[at + 1]]; at += 2 + m[at + 1]; diff --git a/zig/src/hip/kernel_tests/nemotron/window.zig b/zig/src/hip/kernel_tests/nemotron/window.zig index 2d4bc3d5363..3e58bfddcd7 100644 --- a/zig/src/hip/kernel_tests/nemotron/window.zig +++ b/zig/src/hip/kernel_tests/nemotron/window.zig @@ -158,7 +158,7 @@ test "the Mamba window's two launches write the bytes of the mixer a row at a ti .{ .heads = 4, .dh = 64, .groups = 2 }, }; var cases: usize = 0; - for (shapes) |sh| for ([_]usize{ 1, 2, 3, 4, 7, 17 }) |rows| for ([_]bool{ true, false }) |snaps| { + for (shapes) |sh| for ([_]usize{ 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 16, 17 }) |rows| for ([_]bool{ true, false }) |snaps| { try rig.expect( try window(t, &rng, sh, rows, snaps), "mamba window {d} heads, {d} groups, {d} rows, snapshots {}: the bytes differ", diff --git a/zig/src/native/draft_sources_hip_test.zig b/zig/src/native/draft_sources_hip_test.zig index 475b23d0c5a..f9b1e123be4 100644 --- a/zig/src/native/draft_sources_hip_test.zig +++ b/zig/src/native/draft_sources_hip_test.zig @@ -24,6 +24,7 @@ test "draft sources: HIP Nemotron checkpoint head and explicit zero" { var b: n.lanes.Hip = undefined; b.e = &e; b.costs = .{}; + e.window = 4; e.plan.rows = 16; e.plan.slots = 4; e.o.policy.mtp.drafts = 3; diff --git a/zig/src/native/mtp_drafts_hip_test.zig b/zig/src/native/mtp_drafts_hip_test.zig index 338057dd6e1..8ac86a5913b 100644 --- a/zig/src/native/mtp_drafts_hip_test.zig +++ b/zig/src/native/mtp_drafts_hip_test.zig @@ -3,14 +3,22 @@ const std = @import("std"); const api = @import("engine_api"); const qwen35 = @import("qwen3_5"); const flashnext = @import("flashnext"); +const nemotron = @import("nemotron"); const hip = @import("hip.zig"); -test "--mtp-drafts: Flash Next takes seven at --tp 1 and three above it, every other HIP family three; past that refused by name" { +test "--mtp-drafts: Flash Next takes seven and Nemotron fifteen at --tp 1, three above it, others three; past that refused by name" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var problem: []const u8 = ""; - inline for (.{ .{ flashnext.native, "qwen4_exp", 7, 1, "" }, .{ qwen35.native, "qwen3_5", 3, 1, "" }, .{ flashnext.native, "qwen4_exp", 3, 2, " with --tp above 1" }, .{ qwen35.native, "qwen3_5", 3, 2, "" } }) |c| { + inline for (.{ + .{ flashnext.native, "qwen4_exp", 7, 1, "" }, + .{ nemotron.native, "nemotron_h", 15, 1, "" }, + .{ qwen35.native, "qwen3_5", 3, 1, "" }, + .{ flashnext.native, "qwen4_exp", 3, 2, " with --tp above 1" }, + .{ nemotron.native, "nemotron_h", 3, 2, " with --tp above 1" }, + .{ qwen35.native, "qwen3_5", 3, 2, "" }, + }) |c| { var o: api.Open = .{ .dir = "d", .model_type = c[1], .mtp_drafts = c[2], .tp = c[3], .master = if (c[3] > 1) "node0" else "" }; try hip.checkGroup(c[0], a, o, &problem); o.mtp_drafts = c[2] + 1; diff --git a/zig/tests/nemotron_hip/gen.zig b/zig/tests/nemotron_hip/gen.zig index 62dacb6aa55..702d89869bb 100644 --- a/zig/tests/nemotron_hip/gen.zig +++ b/zig/tests/nemotron_hip/gen.zig @@ -215,6 +215,12 @@ pub fn decode(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !v ); } +fn widen(j: *group.Group.Joined, k: usize) void { + if (k > nem.round.default_window) { + j.policy.mtp.drafts = @intCast(@min(k - 1, nem.head.max_depth)); + } +} + /// The ids after the prompt once as one window of rows and once a row at a time: the same logits bits, or not. pub fn window(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !void { const a = try parse(args); @@ -222,12 +228,13 @@ pub fn window(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !v defer gpa.free(ids); var j = try a.g.join(gpa, io, a.dir); defer j.close(); + const k = a.steps; + if (k == 0 or k > nem.round.max_window or ids.len <= k) return error.MissingArgument; + widen(&j, k); const e = try a.g.engine(gpa, io, a.dir, j, .{ .capacity = 4096, .streams = 2, .mtp = a.mtp }); defer e.deinit(); const m = e.model_(); const v = m.dims.vocab; - const k = a.steps; - if (ids.len <= k) return error.MissingArgument; const prompt = ids[0 .. ids.len - k]; const tail = ids[ids.len - k ..]; const once = try gpa.alloc(f32, k * v); @@ -307,6 +314,7 @@ pub fn rounds(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !v const n = a.streams; const k = a.steps; if (n == 0 or k == 0 or k > nem.round.max_window or ids.len <= k + n) return error.MissingArgument; + widen(&j, k); const e = try a.g.engine(gpa, io, a.dir, j, .{ .capacity = 4096, .streams = n, .mtp = a.mtp }); defer e.deinit(); const m = e.model_(); @@ -318,14 +326,27 @@ pub fn rounds(gpa: std.mem.Allocator, io: std.Io, args: []const [:0]const u8) !v defer gpa.free(streams); const rows = try gpa.alloc(nem.round.Rows, n); defer gpa.free(rows); - // stream i's prompt ends i tokens earlier and its window holds k - (i mod k) rows, so positions and widths differ + // Split at the round plan's row ceiling once `k` widens past the default 4-row window across streams. + var uncapped: usize = 0; + for (0..n) |i| uncapped += k - i % k; + const capped = uncapped > e.plan.rows; + if (capped and (e.window <= nem.round.default_window or e.plan.rows != nem.round.planRows(n, e.window))) { + return error.WindowTooWide; + } + var rem: usize = if (capped) e.plan.rows else uncapped; var total: usize = 0; var opened: usize = 0; defer for (streams[0..opened]) |*s| e.closeStream(s); for (streams, 0..) |*s, i| { s.* = try e.openStream(); opened += 1; - const width = k - i % k; + const width = if (!capped) + k - i % k + else if (i == 0) + @min(k, rem - (n - 1)) + else + @min(rem - (n - 1 - i), (rem + n - 1 - i) / (n - i)); + rem -= width; _ = try e.prompt(s, ids[0 .. ids.len - k - i]); try s.cover(&e.pool, s.len + width); rows[i] = .{ From 045c8e05aad1d450dc2623cbab535b9270a22532 Mon Sep 17 00:00:00 2001 From: gilby Date: Fri, 20 Nov 2026 09:48:55 +0100 Subject: [PATCH 4/5] changelog: #3613 under Unreleased --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70e5da15ecf..5acadeff5a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -202,6 +202,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA lanes: a one-stream reply keeps the draft depth it priced until another depth wins by 5% on the expected tokens a millisecond, and a probe one draft deeper is verified instead of being trimmed by the lone window's own prices; one noisy round no longer leaves a reply at one draft for the rest of it (#3468). - Core: Drama 3's `torch.save` reader moves to `core/torch_pth.zig` (its zip container to `core/torch_zip.zig`) and its WAV code to `core/wav.zig`; the reader also opens a root of nested state dicts, naming tensors by their keys joined with `/` (`openNested`), and returns a tensor's stored bytes at a given dtype and shape (`readRaw`), with host tests; Drama 3's generated and served audio stays byte-identical on Metal (#3719, for #3615). Thanks to @BobClawblaw. +- Nemotron 3.5 Lightning on HIP: `--mtp-drafts` up to `15` at `--tp 1` widens a lone stream's verify window up to sixteen rows while keeping the four-row default and capping shared rounds at three head drafts a stream; on `gfx1151`, `L=1` edit prompts rise from `149.0` to `229.1` tok/s on `Lightning-30B-A3B-MLX-4bit` (`134.3` to `204.7` greedy on `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP`), `gpu-chat` greedy runs at `94.5` vs `98.8` tok/s (full table in `docs/recipes/nemotron-3.5.md`), with identical tokens (#3613, part of #3394). - Desktop: a new conversation on the built-in engine asks for its title after the first run settles, not beside it, so the title no longer competes with that run; cancelling or renaming during the run skips it (#4072, refs #3606). Thanks to @AIFlowML. From 808cb796b476b45165e3039504eae7e8c42b6a60 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:55:54 +0000 Subject: [PATCH 5/5] changelog: #3613's line from lines/3613.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5acadeff5a3..bbe9cd9d877 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 +- Nemotron on HIP: at `--tp 1`, `--mtp-drafts` takes up to 15, widening a lone stream's verify window up to 16 rows; unset or at 3 or fewer the window stays at four rows, rounds shared by several streams chain at most three drafts a stream, and above `--tp 1` more than three is refused by name (#3613, refs #3394). Thanks to @gilby. + - Server: opt-in --tool-think-close bounds thinking for required or named tool calls so the call has room in max_tokens; the flag defaults off and keeps smaller thinking budgets (#4157). Thanks to @jayleaton. - CUDA: Drama 3 loads compact NVFP4 checkpoints as stored, stages held experts in slot order, and masks routing to their original ids (#4144). Thanks to @plotarmordev. @@ -202,7 +204,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA lanes: a one-stream reply keeps the draft depth it priced until another depth wins by 5% on the expected tokens a millisecond, and a probe one draft deeper is verified instead of being trimmed by the lone window's own prices; one noisy round no longer leaves a reply at one draft for the rest of it (#3468). - Core: Drama 3's `torch.save` reader moves to `core/torch_pth.zig` (its zip container to `core/torch_zip.zig`) and its WAV code to `core/wav.zig`; the reader also opens a root of nested state dicts, naming tensors by their keys joined with `/` (`openNested`), and returns a tensor's stored bytes at a given dtype and shape (`readRaw`), with host tests; Drama 3's generated and served audio stays byte-identical on Metal (#3719, for #3615). Thanks to @BobClawblaw. -- Nemotron 3.5 Lightning on HIP: `--mtp-drafts` up to `15` at `--tp 1` widens a lone stream's verify window up to sixteen rows while keeping the four-row default and capping shared rounds at three head drafts a stream; on `gfx1151`, `L=1` edit prompts rise from `149.0` to `229.1` tok/s on `Lightning-30B-A3B-MLX-4bit` (`134.3` to `204.7` greedy on `NVIDIA-Nemotron-3.5-Lightning-30B-A3B-oQ4e-HIP`), `gpu-chat` greedy runs at `94.5` vs `98.8` tok/s (full table in `docs/recipes/nemotron-3.5.md`), with identical tokens (#3613, part of #3394). - Desktop: a new conversation on the built-in engine asks for its title after the first run settles, not beside it, so the title no longer competes with that run; cancelling or renaming during the run skips it (#4072, refs #3606). Thanks to @AIFlowML.