From cb005c30ed8f5d587e7fa8d21e47f5975dc836f7 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 00:25:16 +0000 Subject: [PATCH 1/7] Flash Next native: TENSORFOLD_FN_PROFILE times rank 0's backend calls; TENSORFOLD_FN_CONFIDENCE sets the draft cut Development measures for the draft and round tuning: each call kind's ms a round and the host's time between calls, logged every that many rounds; the head's confidence cut (0.70) as a knob both ranks read. --- zig/src/families/flashnext_cuda/forward.zig | 14 ++++ zig/src/families/flashnext_cuda/native.zig | 53 +++++++++++++-- zig/src/families/flashnext_cuda/prof.zig | 72 +++++++++++++++++++++ 3 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 zig/src/families/flashnext_cuda/prof.zig diff --git a/zig/src/families/flashnext_cuda/forward.zig b/zig/src/families/flashnext_cuda/forward.zig index 1ccb116a781..3a3abbdd1da 100644 --- a/zig/src/families/flashnext_cuda/forward.zig +++ b/zig/src/families/flashnext_cuda/forward.zig @@ -477,6 +477,8 @@ pub const Engine = struct { multi_gdn: bool = true, multi_layers: [2]u64 = .{ 0, 0 }, // shared attention layers in one launch a kernel, and those the set had no variant for stage_ms: f64 = 0, // host time staging windows (ids, n-gram rows) + enq_ms: f64 = 0, // verify forwards' host time until the picks' read-back (launches, staging) + wait_ms: f64 = 0, // and the read-back's wait for the GPU gpu_ms: f64 = 0, // GPU time of verify windows (events around the step), when ``timing`` timing: bool = false, split: [3]f64 = .{ 0, 0, 0 }, // staging: ids upload, n-gram ids, table rows @@ -1563,6 +1565,7 @@ pub fn verify(e: *Engine, s: *Seq, ids: []const u32, out: []u32) !void { const b = &e.buf; var toks: [16]i64 = undefined; for (ids, 0..) |t, i| toks[i] = t; + const t0 = std.Io.Timestamp.now(e.io, .awake); try room(e, s, R + 1); try stage(e, b, s, toks[0..ids.len]); var ev: [2]cuda.Event = undefined; @@ -1580,7 +1583,9 @@ pub fn verify(e: *Engine, s: *Seq, ids: []const u32, out: []u32) !void { }; if (try applyMasks(e, b.logits, &.{.{ .s = s, .row0 = 0, .rows = R }})) try candidates(e, b, b.logits, HEAD_N, 0, e.vocab_offset, R); var picks: [16]Pick = undefined; + const t1 = std.Io.Timestamp.now(e.io, .awake); try readPicks(e, b, R, picks[0..ids.len]); + split(e, t0, t1); for (out[0..ids.len], picks[0..ids.len]) |*o, p| o.* = @intCast(p.tok); if (s.sampling) |rule| { // row r draws the token at position pos + 1 + r var want: [16]Want = undefined; @@ -1592,6 +1597,12 @@ pub fn verify(e: *Engine, s: *Seq, ids: []const u32, out: []u32) !void { @memcpy(s.last_tokens[0..ids.len], toks[0..ids.len]); } +fn split(e: *Engine, t0: std.Io.Timestamp, t1: std.Io.Timestamp) void { + const t2 = std.Io.Timestamp.now(e.io, .awake); + e.enq_ms += @as(f64, @floatFromInt(t0.durationTo(t1).toNanoseconds())) / 1e6; + e.wait_ms += @as(f64, @floatFromInt(t1.durationTo(t2).toNanoseconds())) / 1e6; +} + /// A stream's window in a shared round: its sequence and its rows' tokens (the pending one, then its drafts). pub const Part = struct { s: *Seq, ids: []const u32 }; @@ -1610,6 +1621,7 @@ pub fn verifyShared(e: *Engine, parts: []const Part, out: []u32) !void { } const b = &e.buf; if (R > b.rows) return error.WindowTooWide; + const t0 = std.Io.Timestamp.now(e.io, .awake); for (segs[0..parts.len]) |sg| try room(e, sg.s, sg.rows + 1); try stageParts(e, b, parts, segs[0..parts.len]); if (e.multi_gdn) try chainTable(e, b, segs[0..parts.len]); @@ -1623,7 +1635,9 @@ pub fn verifyShared(e: *Engine, parts: []const Part, out: []u32) !void { _ = try applyMasks(e, b.logits, segs[0..parts.len]); try candidates(e, b, b.logits, HEAD_N, 0, e.vocab_offset, R); var picks: [max_parts * 16]Pick = undefined; + const t1 = std.Io.Timestamp.now(e.io, .awake); try readPicks(e, b, R, picks[0..@intCast(R)]); + split(e, t0, t1); for (out[0..@intCast(R)], picks[0..@intCast(R)]) |*o, p| o.* = @intCast(p.tok); var want: [max_parts * 16]Want = undefined; var nw: usize = 0; diff --git a/zig/src/families/flashnext_cuda/native.zig b/zig/src/families/flashnext_cuda/native.zig index f8bd1cb1097..80cbdd5e325 100644 --- a/zig/src/families/flashnext_cuda/native.zig +++ b/zig/src/families/flashnext_cuda/native.zig @@ -10,6 +10,7 @@ const api = @import("api.zig"); const weights = @import("weights.zig"); const forward = @import("forward.zig"); const vision = @import("vision.zig"); +const Prof = @import("prof.zig").Prof; const be = lanes.backend; pub const model_type = "qwen4_exp"; @@ -62,7 +63,8 @@ const max_depth = max_rows - 1; const grow_margin = 2 * max_rows + 2; /// The head stops at a draft it gives less than this (the Python engine's --mtp-confidence, the recipe's 0.70); /// the slots past it are held with chance 0, so the lane core's allocator leaves them out of the window. -const draft_confidence: f64 = 0.7; +/// TENSORFOLD_FN_CONFIDENCE overrides it (a measurement's knob; both ranks must see the same value). +var draft_confidence: f64 = 0.7; // -- the protocol rank 0 sends rank 1 --------------------------------------------------------------------------- @@ -287,6 +289,7 @@ const Owned = struct { gfull: []u32 = &.{}, // a grammar row's bits over the whole vocabulary gbits: [2][]u32 = .{ &.{}, &.{} }, // a round's grammar rows, each rank's half (rank 1: what the frames carry) growsbuf: [batch_rows]u32 = undefined, + prof: Prof = .{}, // TENSORFOLD_FN_PROFILE (prof.zig) /// The scratch grammar rows need, made on first use. fn gramScratch(self: *Owned) !void { @@ -500,6 +503,8 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.gpa = gpa; own.io = io; own.rank = o.rank; + own.prof = if (o.rank == 0) .init() else .{}; + if (std.c.getenv("TENSORFOLD_FN_CONFIDENCE")) |v| draft_confidence = std.fmt.parseFloat(f64, std.mem.span(v)) catch draft_confidence; // the link and the communicator first, while memory is fresh (NCCL registers its buffers at its first use) own.link = if (o.rank == 0) try cuda.tp_link.Link.lead(o.master_port, 600_000) else try cuda.tp_link.Link.follow(io, try std.Io.net.IpAddress.parse(o.master orelse return error.NoMaster, o.master_port), 600_000); @@ -520,6 +525,10 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.store = try weights.load(gpa, io, &own.ctx, &own.kernels, dir, o.rank); errdefer own.store.deinit(); own.e = try forward.init(gpa, io, &own.ctx, &own.kernels, &own.store, .{ .context = o.context, .max_rows = batch_rows, .depth = if (o.drafts) max_depth else 0, .kv_bits = o.kv_bits }); + if (own.prof.every > 0) { + own.prof.enq = &own.e.enq_ms; + own.prof.wait = &own.e.wait_ms; + } errdefer forward.deinit(own.e); try forward.prefetchTables(own.e); // the n-gram tables paged in (and locked) before the first request { // the sequences' caches grow within what is free now, less the server's reserve and a margin (a GB10 shares @@ -757,19 +766,51 @@ fn of(p: *anyopaque) *Owned { } const vtable: be.Backend.VTable = .{ - .prefill = prefillFn, - .prefill_many = prefillManyFn, + .prefill = timedPrefill, + .prefill_many = timedPrefillMany, .first = firstFn, .queue = queueFn, .read = readFn, - .verify = verifyFn, - .keep = keepFn, - .draft = draftFn, + .verify = timedVerify, + .keep = timedKeep, + .draft = timedDraft, .release = releaseFn, .probabilities = probabilitiesFn, .refused = refusedFn, }; +fn timedPrefill(p: *anyopaque, s: *lanes.Stream) anyerror!void { + const t = of(p).prof.begin(of(p).io); + defer of(p).prof.end(of(p).io, .prefill, t, 0, 0); + return prefillFn(p, s); +} + +fn timedPrefillMany(p: *anyopaque, ss: []const *lanes.Stream) anyerror!bool { + const t = of(p).prof.begin(of(p).io); + defer of(p).prof.end(of(p).io, .prefills, t, 0, ss.len); + return prefillManyFn(p, ss); +} + +fn timedVerify(p: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const t = of(p).prof.begin(of(p).io); + var rows: usize = 0; + for (windows) |w| rows += w.rows(); + defer of(p).prof.end(of(p).io, if (windows.len > 1) .shared else .verify, t, rows, if (windows.len > 1) windows.len else 0); + return verifyFn(p, windows, out); +} + +fn timedKeep(p: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const t = of(p).prof.begin(of(p).io); + defer of(p).prof.end(of(p).io, .keep, t, 0, 0); + return keepFn(p, windows, paths); +} + +fn timedDraft(p: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const t = of(p).prof.begin(of(p).io); + defer of(p).prof.end(of(p).io, if (requests.len > 1) .drafts else .draft, t, 0, 0); + return draftFn(p, requests); +} + /// A new sequence for the stream and its prompt (the head absorbs it); the first token is drawn here. fn prefillFn(p: *anyopaque, s: *lanes.Stream) anyerror!void { const self = of(p); diff --git a/zig/src/families/flashnext_cuda/prof.zig b/zig/src/families/flashnext_cuda/prof.zig new file mode 100644 index 00000000000..7c34ad414ff --- /dev/null +++ b/zig/src/families/flashnext_cuda/prof.zig @@ -0,0 +1,72 @@ +//! TENSORFOLD_FN_PROFILE=: rank 0's backend calls timed by kind, and the host's time between them, logged +//! every that many rounds (0 or unset: off). A development measure; it changes nothing it times. +const std = @import("std"); + +pub const Kind = enum { prefill, prefills, verify, shared, keep, draft, drafts, gap }; +const N = @typeInfo(Kind).@"enum".field_names.len; + +pub const Prof = struct { + every: u64 = 0, + ms: [N]f64 = @splat(0), + n: [N]u64 = @splat(0), + rows: u64 = 0, // verify rows (lone and shared) + parts: u64 = 0, // streams in shared rounds + last: ?std.Io.Timestamp = null, + enq: ?*f64 = null, // the engine's verify host time until read-back, and its wait there (forward.zig) + wait: ?*f64 = null, + + pub fn init() Prof { + const v = std.c.getenv("TENSORFOLD_FN_PROFILE") orelse return .{}; + return .{ .every = std.fmt.parseInt(u64, std.mem.span(v), 10) catch 0 }; + } + + /// The call's start (null when off); the time since the previous call ended counts as host time between calls. + pub fn begin(p: *Prof, io: std.Io) ?std.Io.Timestamp { + if (p.every == 0) return null; + const now = std.Io.Timestamp.now(io, .awake); + if (p.last) |l| { + const gap = since(l, now); + if (gap < 200) { // longer: the server was idle + p.ms[@intFromEnum(Kind.gap)] += gap; + p.n[@intFromEnum(Kind.gap)] += 1; + } + } + return now; + } + + pub fn end(p: *Prof, io: std.Io, kind: Kind, t0: ?std.Io.Timestamp, rows: usize, parts: usize) void { + const t = t0 orelse return; + const now = std.Io.Timestamp.now(io, .awake); + p.ms[@intFromEnum(kind)] += since(t, now); + p.n[@intFromEnum(kind)] += 1; + p.rows += rows; + p.parts += parts; + p.last = now; + const rounds = p.n[@intFromEnum(Kind.verify)] + p.n[@intFromEnum(Kind.shared)]; + if ((kind == .verify or kind == .shared) and rounds >= p.every) p.flush(); + } + + fn flush(p: *Prof) void { + const rounds: f64 = @floatFromInt(p.n[@intFromEnum(Kind.verify)] + p.n[@intFromEnum(Kind.shared)]); + var buf: [512]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + w.print("flash next profile: {d} rounds, {d:.1} rows and {d:.2} streams a shared round; ms a round:", .{ + rounds, @as(f64, @floatFromInt(p.rows)) / rounds, + if (p.n[@intFromEnum(Kind.shared)] > 0) @as(f64, @floatFromInt(p.parts)) / @as(f64, @floatFromInt(p.n[@intFromEnum(Kind.shared)])) else 0, + }) catch {}; + for (0..N) |i| if (p.n[i] > 0) w.print(" {s} {d:.2} (x{d:.2})", .{ + @tagName(@as(Kind, @enumFromInt(i))), p.ms[i] / rounds, @as(f64, @floatFromInt(p.n[i])) / rounds, + }) catch {}; + if (p.enq) |enq| if (p.wait) |wt| { + w.print("; verify launch {d:.2} wait {d:.2}", .{ enq.* / rounds, wt.* / rounds }) catch {}; + enq.* = 0; + wt.* = 0; + }; + std.log.info("{s}", .{w.buffered()}); + p.* = .{ .every = p.every, .enq = p.enq, .wait = p.wait }; + } +}; + +fn since(a: std.Io.Timestamp, b: std.Io.Timestamp) f64 { + return @as(f64, @floatFromInt(a.durationTo(b).toNanoseconds())) / 1e6; +} From e6a1e79c7b1e380fbbfc055f81d33982a5fc1373 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 02:53:50 +0000 Subject: [PATCH 2/7] Flash Next native: the engine's timing flag and counters set at init The engine is built field by field, so a field's default never applies: the verify timing flag (events around every step when set) and the counters were whatever the allocator's memory held. --- zig/src/families/flashnext_cuda/forward.zig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/zig/src/families/flashnext_cuda/forward.zig b/zig/src/families/flashnext_cuda/forward.zig index 3a3abbdd1da..2dcba1cbcad 100644 --- a/zig/src/families/flashnext_cuda/forward.zig +++ b/zig/src/families/flashnext_cuda/forward.zig @@ -629,6 +629,10 @@ pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *api.Ctx, kernels: *api.Ker e.confidence = 0; e.stage_ms = 0; e.split = .{ 0, 0, 0 }; + e.timing = false; // the engine is built field by field: a default left out is whatever the allocator held + e.gpu_ms = 0; + e.enq_ms = 0; + e.wait_ms = 0; e.graphs = .init(gpa); return e; } From b10cd8ecf121e589b813057739d3f686f3565fe8 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 00:30:42 +0000 Subject: [PATCH 3/7] Lane host: TENSORFOLD_ADMIT_GATHER_MS, an idle engine's one request waits for others to share its prompt pass Requests sent together arrive a few ms apart; the first, admitted alone, held the rest up for its own prompt pass. --- zig/src/core/lane_host.zig | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index a3701ccac63..a86b645279b 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -60,6 +60,7 @@ pub const LaneHost = struct { started: bool = false, prefill_sent: bool = false, // a lone driver's prefilled event went out began: i96 = 0, + gathered: bool = false, // admission waited for others to join this request's prompt pass (gather) prefilled: ?i96 = null, entry: ?*pc.Entry = null, // the kept state the backend restores, until its prompt pass reports marks: []const u32 = &.{}, // where the pass keeps states (gpa-owned) @@ -337,6 +338,7 @@ pub const LaneHost = struct { const waiting = h.queued.items.len; const free = h.info_.lanes -| h.admitted.items.len; h.unlock(); + if (waiting == 1 and free >= 2 and h.gather()) return true; if (waiting < 2 or free < 2) return h.admitOne(); var jobs: [lanes.Engine.max_together]*Job = undefined; var n: usize = 0; @@ -362,6 +364,35 @@ pub const LaneHost = struct { return true; } + /// TENSORFOLD_ADMIT_GATHER_MS: an idle engine's one waiting request waits this long for others to share its prompt + /// pass (requests sent together arrive a few ms apart; the first admitted alone holds the rest up for its pass). + /// True when it waited (the caller admits again), false when off or busy. + fn gather(h: *LaneHost) bool { + const ms = gatherMs(); + if (ms == 0 or h.core.activeCount() != 0) return false; + h.lock(); + defer h.unlock(); + if (h.queued.items.len != 1 or h.queued.items[0].gathered) return false; + h.queued.items[0].gathered = true; + const t0 = std.Io.Timestamp.now(h.io, .awake); + while (true) { + const spent: i64 = @intCast(@divFloor(t0.durationTo(std.Io.Timestamp.now(h.io, .awake)).toNanoseconds(), std.time.ns_per_ms)); + if (spent >= ms) break; + h.wake.waitTimeout(h.io, &h.mutex, .{ .duration = .{ .raw = .fromMilliseconds(ms - spent), .clock = .awake } }) catch {}; + } + return true; + } + + fn gatherMs() i64 { + const Once = struct { + var ms: ?i64 = null; + }; + if (Once.ms) |m| return m; + const v = std.c.getenv("TENSORFOLD_ADMIT_GATHER_MS"); + Once.ms = if (v) |x| std.fmt.parseInt(i64, std.mem.span(x), 10) catch 0 else 0; + return Once.ms.?; + } + /// The next queued request into the admitted ones (null: none waits or no lane is free). fn takeJob(h: *LaneHost) ?*Job { h.lock(); From 59c4fda933b6afc61b575bc4452d9b26aaea9695 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 01:14:08 +0000 Subject: [PATCH 4/7] tests/cuda: fn-gathers, the forward's partial-sum gathers timed eager, in one graph and between split graphs --- zig/tests/cuda/fn_gathers.zig | 118 ++++++++++++++++++++++++++++++++++ zig/tests/cuda/main.zig | 1 + 2 files changed, 119 insertions(+) create mode 100644 zig/tests/cuda/fn_gathers.zig diff --git a/zig/tests/cuda/fn_gathers.zig b/zig/tests/cuda/fn_gathers.zig new file mode 100644 index 00000000000..62a7b5c8b77 --- /dev/null +++ b/zig/tests/cuda/fn_gathers.zig @@ -0,0 +1,118 @@ +//! fn-gathers [rows ...]: the forward's partial-sum gathers (fp32, rows x 2560 a rank) +//! timed between the two ranks: back to back eager, captured in one CUDA graph, and eager between small graphs, each +//! with a memset between gathers (a forward's dependency chain). NCCL_* settings come from the environment. + +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const Gpu = check.Gpu; + +const D = 2560; +const N = 96; // gathers a forward + +pub fn run(gpu: Gpu, args: []const [:0]const u8) !void { + const io = gpu.io; + const rank = try std.fmt.parseInt(u8, args[0], 10); + const port = try std.fmt.parseInt(u16, args[2], 10); + var link = if (rank == 0) try cuda.tp_link.Link.lead(port, 300_000) + else try cuda.tp_link.Link.follow(io, try std.Io.net.IpAddress.parse(args[1], port), 300_000); + defer link.close(); + var nccl = try cuda.nccl.Library.open(); + defer nccl.close(); + const comm = try cuda.tp_link.communicator(&nccl, link); + var stream = try cuda.Stream.init(gpu.d, true); + defer stream.deinit(); + const send = try cuda.DeviceBuffer.alloc(gpu.d, 16 * D * 4); + const recv = try cuda.DeviceBuffer.alloc(gpu.d, 2 * 16 * D * 4); + const pad = try cuda.DeviceBuffer.alloc(gpu.d, 64 * 1024); + var rows_list: [8]usize = undefined; + var nr: usize = 0; + for (args[3..]) |a| { + rows_list[nr] = try std.fmt.parseInt(usize, a, 10); + nr += 1; + } + if (nr == 0) { + rows_list[0..3].* = .{ 1, 6, 16 }; + nr = 3; + } + const Ctx = struct { + nccl: *cuda.nccl.Library, + comm: cuda.nccl.Comm, + stream: cuda.Stream, + d: *const cuda.Driver, + send: u64, + recv: u64, + pad: u64, + + fn gather(c: @This(), count: usize) !void { + try c.nccl.check(c.nccl.api.ncclAllGather(c.send, c.recv, count, .f32, c.comm, c.stream.handle), "gather"); + } + fn touch(c: @This()) !void { + try c.d.check(c.d.api.cuMemsetD32Async(c.pad, 0, 1024, c.stream.handle), "memset"); + } + }; + const c: Ctx = .{ .nccl = &nccl, .comm = comm, .stream = stream, .d = gpu.d, .send = send.ptr, .recv = recv.ptr, .pad = pad.ptr }; + for (0..20) |_| try c.gather(D); // connect and warm + try stream.synchronize(); + for (rows_list[0..nr]) |rows| { + const count = rows * D; + // eager, back to back with a memset between + var best_e: f64 = std.math.inf(f64); + for (0..5) |_| { + try c.gather(count); + try stream.synchronize(); + const t = std.Io.Timestamp.now(io, .awake); + for (0..N) |_| { + try c.touch(); + try c.gather(count); + } + try stream.synchronize(); + best_e = @min(best_e, us(io, t) / N); + } + // one graph of N gathers (memsets between) + try cuda.graph.beginCapture(stream, .thread_local); + for (0..N) |_| { + try c.touch(); + try c.gather(count); + } + var g = try cuda.graph.endCapture(stream); + const ex = try g.instantiate(); + g.deinit(); + try ex.upload(stream); + var best_g: f64 = std.math.inf(f64); + for (0..6) |rep| { + try c.gather(count); + try stream.synchronize(); + const t = std.Io.Timestamp.now(io, .awake); + try ex.launchOn(stream); + try stream.synchronize(); + if (rep > 0) best_g = @min(best_g, us(io, t) / N); + } + // eager gathers between one-memset graphs (graphs split around the collectives) + try cuda.graph.beginCapture(stream, .thread_local); + try c.touch(); + var g2 = try cuda.graph.endCapture(stream); + const ex2 = try g2.instantiate(); + g2.deinit(); + try ex2.upload(stream); + var best_s: f64 = std.math.inf(f64); + for (0..5) |_| { + try c.gather(count); + try stream.synchronize(); + const t = std.Io.Timestamp.now(io, .awake); + for (0..N) |_| { + try ex2.launchOn(stream); + try c.gather(count); + } + try stream.synchronize(); + best_s = @min(best_s, us(io, t) / N); + } + std.debug.print("rank {d}: {d} rows ({d} KiB a rank): us a gather: eager {d:.1}, one graph {d:.1}, split graphs {d:.1}\n", .{ + rank, rows, count * 4 / 1024, best_e, best_g, best_s }); + } + check.pass("rank {d}: gathers timed", .{rank}); +} + +fn us(io: std.Io, t: std.Io.Timestamp) f64 { + return @as(f64, @floatFromInt(t.durationTo(std.Io.Timestamp.now(io, .awake)).toNanoseconds())) / 1e3; +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 7a681fc0310..04aefb8ace3 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -97,6 +97,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "fn-ext")) return fn_ext.extCall(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "fn-aot")) return @import("fn_native.zig").aotLoad(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "fn-native")) return @import("fn_forward.zig").native(gpu, rest); + if (std.mem.eql(u8, cmd, "fn-gathers")) return @import("fn_gathers.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "video-prep")) return @import("fn_vision.zig").videoPrep(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "vision-prep")) return @import("fn_vision.zig").prep(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "fn-vision")) return @import("fn_vision.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); From 26dfaba65b195a195c6d1f928e79aaeb7a168092 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 01:17:56 +0000 Subject: [PATCH 5/7] Flash Next native: captured steps can end a graph at each cross-rank gather (TENSORFOLD_FN_SPLIT_GRAPHS) The gathers then run eager between the graph segments, the same work in the same order (the payload and the sum untouched). fn-native's "split" word runs the exactness checks that way. --- zig/src/families/flashnext_cuda/forward.zig | 45 +++++++----- zig/src/families/flashnext_cuda/native.zig | 1 + zig/src/families/flashnext_cuda/plan.zig | 78 +++++++++++++++++++++ zig/tests/cuda/fn_forward.zig | 1 + 4 files changed, 108 insertions(+), 17 deletions(-) create mode 100644 zig/src/families/flashnext_cuda/plan.zig diff --git a/zig/src/families/flashnext_cuda/forward.zig b/zig/src/families/flashnext_cuda/forward.zig index 2dcba1cbcad..43764f27f6c 100644 --- a/zig/src/families/flashnext_cuda/forward.zig +++ b/zig/src/families/flashnext_cuda/forward.zig @@ -13,6 +13,7 @@ const kern = @import("kern.zig"); const ngram_mod = @import("ngram.zig"); const grow_mod = @import("grow.zig"); const draw_mod = @import("draw.zig"); +const plan = @import("plan.zig"); const lanes = @import("lanes"); pub const devstore = @import("devstore.zig"); pub const api_ = api; @@ -482,7 +483,10 @@ pub const Engine = struct { gpu_ms: f64 = 0, // GPU time of verify windows (events around the step), when ``timing`` timing: bool = false, split: [3]f64 = .{ 0, 0, 0 }, // staging: ids upload, n-gram ids, table rows - graphs: std.AutoHashMap(GKey, cuda.graph.Exec) = undefined, + graphs: std.AutoHashMap(GKey, plan.Plan) = undefined, + /// Captured steps end a graph at each cross-rank gather, which runs eager between the segments (TENSORFOLD_FN_SPLIT_GRAPHS). + split_gathers: bool = false, + rec: ?*plan.Recorder = null, // the capture in progress, which takes the gathers its step issues }; const GKey = struct { kind: u8, rows: i64, par: u1, sig: [3]i64, seq: usize }; @@ -536,28 +540,29 @@ fn capture(e: *Engine, kind: u8, s: *Seq, R: i64) !void { } if (stale) |o| { var ex = e.graphs.fetchRemove(o).?.value; - ex.deinit(); + ex.deinit(e.gpa); } - try cuda.graph.beginCapture(e.k.stream, .thread_local); + var rec: plan.Recorder = .{ .gpa = e.gpa, .stream = e.k.stream, .split = e.split_gathers }; + try rec.begin(); + if (e.split_gathers) e.rec = &rec; + defer e.rec = null; body(e, kind, s, R) catch |err| { - if (cuda.graph.endCapture(e.k.stream)) |g| { - var gg = g; - gg.deinit(); - } else |_| {} + rec.abandon(); return err; }; - var g = try cuda.graph.endCapture(e.k.stream); - defer g.deinit(); - const ex = try g.instantiate(); - try ex.upload(e.k.stream); - try e.graphs.put(key, ex); + var p = rec.finish() catch |err| { + rec.abandon(); + return err; + }; + errdefer p.deinit(e.gpa); + try e.graphs.put(key, p); } /// ``body`` from its graph (captured the first time this width, parity and geometry run). fn step(e: *Engine, kind: u8, s: *Seq, R: i64) !void { if (!e.use_graphs or e.k.sync_each or s.img != null or (kind == 0 and s.sampling != null)) return body(e, kind, s, R); // image and sampled sequences: eager try capture(e, kind, s, R); - return e.graphs.get(keyOf(e, kind, s, R)).?.launchOn(e.k.stream); + return e.graphs.get(keyOf(e, kind, s, R)).?.launch(e.ctx.nccl, e.ctx.comm, e.k.stream); } @@ -757,7 +762,7 @@ pub fn freeSeq(e: *Engine, s: *Seq) void { while (it.next()) |en| if (en.key_ptr.seq == @intFromPtr(s)) gone.append(e.gpa, en.key_ptr.*) catch {}; for (gone.items) |key| { var ex = e.graphs.fetchRemove(key).?.value; - ex.deinit(); + ex.deinit(e.gpa); } detach(e, s); s.grow.deinit(); @@ -769,8 +774,14 @@ pub fn freeSeq(e: *Engine, s: *Seq) void { // -- the forward ---------------------------------------------------------------------------------------------------- const Pending = struct { g: u64, inj: u64 }; +/// Both ranks' ``count`` values from ``send`` into ``recv`` in rank order; inside a split capture, between its graphs. +fn gather(e: *Engine, send: u64, recv: u64, count: usize, dt: cuda.nccl.DataType) !void { + if (e.rec) |r| return r.gather(.{ .send = send, .recv = recv, .count = count, .dt = dt }); + try e.ctx.nccl.check(e.ctx.nccl.api.ncclAllGather(send, recv, count, dt, e.ctx.comm, e.k.stream.handle), "ncclAllGather"); +} + fn allGather(e: *Engine, send: u64, recv: u64, count: usize) !void { - try e.ctx.nccl.check(e.ctx.nccl.api.ncclAllGather(send, recv, count, .f32, e.ctx.comm, e.k.stream.handle), "ncclAllGather"); + try gather(e, send, recv, count, .f32); } /// forward._readout_b16: norm (unless done), down with SiLU and inject gates, up and the mix -> mixed [R, D]. @@ -994,7 +1005,7 @@ fn finish(e: *Engine, b: *Buffers, mixer: HCW, R: i64, pending: Pending) !i64 { /// Each row's greedy token across both ranks' shards: our candidate kernel and an all-gather (rows <= 16). fn candidates(e: *Engine, b: *Buffers, logits: u64, cols: i64, id_map: u64, offset: i64, rows: i64) !void { try kern.rowsTop(&e.k, logits, cols, id_map, offset, b.cand, rows); - try e.ctx.nccl.check(e.ctx.nccl.api.ncclAllGather(b.cand, b.gath, @intCast(4 * rows), .i32, e.ctx.comm, e.k.stream.handle), "candidates"); + try gather(e, b.cand, b.gath, @intCast(4 * rows), .i32); } const Pick = struct { tok: i64, p: f64 }; @@ -1218,7 +1229,7 @@ fn mtpComputeSegs(e: *Engine, b: *Buffers, segs: []const Seg, n: i64) !void { if (segs.len == 1) try candidates(e, b, b.logits, e.dh.n, e.draft_ids.ptr, 0, 1) else { const rows: i64 = @intCast(segs.len); try kern.rowsTopStrided(k, b.logits, e.dh.n, headStride(e), e.draft_ids.ptr, 0, b.cand, rows); - try e.ctx.nccl.check(e.ctx.nccl.api.ncclAllGather(b.cand, b.gath, @intCast(4 * rows), .i32, e.ctx.comm, k.stream.handle), "candidates"); + try gather(e, b.cand, b.gath, @intCast(4 * rows), .i32); } } diff --git a/zig/src/families/flashnext_cuda/native.zig b/zig/src/families/flashnext_cuda/native.zig index 80cbdd5e325..c15bfc5877e 100644 --- a/zig/src/families/flashnext_cuda/native.zig +++ b/zig/src/families/flashnext_cuda/native.zig @@ -525,6 +525,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.store = try weights.load(gpa, io, &own.ctx, &own.kernels, dir, o.rank); errdefer own.store.deinit(); own.e = try forward.init(gpa, io, &own.ctx, &own.kernels, &own.store, .{ .context = o.context, .max_rows = batch_rows, .depth = if (o.drafts) max_depth else 0, .kv_bits = o.kv_bits }); + if (std.c.getenv("TENSORFOLD_FN_SPLIT_GRAPHS")) |v| own.e.split_gathers = std.mem.eql(u8, std.mem.span(v), "1"); if (own.prof.every > 0) { own.prof.enq = &own.e.enq_ms; own.prof.wait = &own.e.wait_ms; diff --git a/zig/src/families/flashnext_cuda/plan.zig b/zig/src/families/flashnext_cuda/plan.zig new file mode 100644 index 00000000000..6df5db77750 --- /dev/null +++ b/zig/src/families/flashnext_cuda/plan.zig @@ -0,0 +1,78 @@ +//! A captured step as CUDA graph segments split at its cross-rank gathers, which run eager between them: a gather +//! between the nodes inside a graph costs several times one launched on the stream. The same work in the same order. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const Gather = struct { send: u64, recv: u64, count: usize, dt: cuda.nccl.DataType }; +pub const Item = union(enum) { graph: cuda.graph.Exec, gather: Gather }; + +pub const Plan = struct { + items: []Item, + + pub fn deinit(p: *Plan, gpa: std.mem.Allocator) void { + for (p.items) |*it| switch (it.*) { + .graph => |*g| g.deinit(), + .gather => {}, + }; + gpa.free(p.items); + p.* = undefined; + } + + pub fn launch(p: Plan, nccl: *cuda.nccl.Library, comm: cuda.nccl.Comm, stream: cuda.Stream) !void { + for (p.items) |it| switch (it) { + .graph => |g| try g.launchOn(stream), + .gather => |g| try nccl.check(nccl.api.ncclAllGather(g.send, g.recv, g.count, g.dt, comm, stream.handle), "ncclAllGather"), + }; + } +}; + +/// What a capture records: each segment's graph, ended and instantiated at a gather (``split``) or at the end. +pub const Recorder = struct { + gpa: std.mem.Allocator, + stream: cuda.Stream, + split: bool, + items: std.ArrayList(Item) = .empty, + + pub fn begin(r: *Recorder) !void { + try cuda.graph.beginCapture(r.stream, .thread_local); + } + + /// The capture so far as one segment (none when it captured nothing). + fn cut(r: *Recorder) !void { + var g = try cuda.graph.endCapture(r.stream); + defer g.deinit(); + if (try g.nodeCount() == 0) return; + const ex = try g.instantiate(); + errdefer { + var x = ex; + x.deinit(); + } + try ex.upload(r.stream); + try r.items.append(r.gpa, .{ .graph = ex }); + } + + /// A gather inside the capture: the segment before it ends, the gather runs eager at replay, a new one begins. + pub fn gather(r: *Recorder, g: Gather) !void { + try r.cut(); + try r.items.append(r.gpa, .{ .gather = g }); + try r.begin(); + } + + pub fn finish(r: *Recorder) !Plan { + try r.cut(); + return .{ .items = try r.items.toOwnedSlice(r.gpa) }; + } + + /// An abandoned capture: the capture ended and the segments made so far freed. + pub fn abandon(r: *Recorder) void { + if (cuda.graph.endCapture(r.stream)) |g| { + var gg = g; + gg.deinit(); + } else |_| {} + for (r.items.items) |*it| switch (it.*) { + .graph => |*g| g.deinit(), + .gather => {}, + }; + r.items.deinit(r.gpa); + } +}; diff --git a/zig/tests/cuda/fn_forward.zig b/zig/tests/cuda/fn_forward.zig index a1f1fa36cba..fcf00500484 100644 --- a/zig/tests/cuda/fn_forward.zig +++ b/zig/tests/cuda/fn_forward.zig @@ -61,6 +61,7 @@ pub fn native(gpu: Gpu, args: []const [:0]const u8) !void { for (args[@min(9, args.len)..]) |a| { if (std.mem.eql(u8, a, "nomultigdn")) e.multi_gdn = false; if (std.mem.eql(u8, a, "nomultiattn")) e.multi_attn = false; + if (std.mem.eql(u8, a, "split")) e.split_gathers = true; // graphs split at the gathers (eager between) } // "multi=on|off" between benches below: both on or both off from there std.debug.print("rank {d}: shared rounds: DeltaNet {s}, attention {s}\n", .{ rank, if (e.multi_gdn) "one launch" else "per stream", if (e.multi_attn) "one launch" else "per stream" }); From 9c706dbb84f6f2a8c15982c9ca4bbc9c00b72dbf Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 01:30:10 +0000 Subject: [PATCH 6/7] Flash Next native: TENSORFOLD_FN_CHANCES, what the allocator gets for each held draft (step, chain or off) step (as before): the head's probability given the drafts before it; chain: its chance of landing (the product); off: no per-node chances, the depth rule sizes chains from acceptance by depth as the Python engine's Flash Next does. --- zig/src/families/flashnext_cuda/native.zig | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/zig/src/families/flashnext_cuda/native.zig b/zig/src/families/flashnext_cuda/native.zig index c15bfc5877e..f00b22e8e9c 100644 --- a/zig/src/families/flashnext_cuda/native.zig +++ b/zig/src/families/flashnext_cuda/native.zig @@ -65,6 +65,10 @@ const grow_margin = 2 * max_rows + 2; /// the slots past it are held with chance 0, so the lane core's allocator leaves them out of the window. /// TENSORFOLD_FN_CONFIDENCE overrides it (a measurement's knob; both ranks must see the same value). var draft_confidence: f64 = 0.7; +/// What the lane core's allocator gets for a held draft (TENSORFOLD_FN_CHANCES, a measurement's knob): ``step`` the +/// head's probability for it given the drafts before it, ``chain`` that times theirs (its chance of landing), ``off`` +/// none (the depth rule sizes chains from each stream's acceptance by depth, as the Python engine's Flash Next does). +var chances: enum { step, chain, off } = .step; // -- the protocol rank 0 sends rank 1 --------------------------------------------------------------------------- @@ -504,6 +508,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.io = io; own.rank = o.rank; own.prof = if (o.rank == 0) .init() else .{}; + if (std.c.getenv("TENSORFOLD_FN_CHANCES")) |v| chances = std.meta.stringToEnum(@TypeOf(chances), std.mem.span(v)) orelse chances; if (std.c.getenv("TENSORFOLD_FN_CONFIDENCE")) |v| draft_confidence = std.fmt.parseFloat(f64, std.mem.span(v)) catch draft_confidence; // the link and the communicator first, while memory is fresh (NCCL registers its buffers at its first use) own.link = if (o.rank == 0) try cuda.tp_link.Link.lead(o.master_port, 600_000) @@ -578,7 +583,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .hidden_rows = o.drafts, .max_streams = if (o.drafts) max_streams else 1, .batch_rows = batch_rows, .window_costs = own.costs[0..own.cost_count], .mtp_step_ms = own.mtp_ms, .shared_costs = own.shared[0..own.shared_count], - .draft_probabilities = o.drafts, .draft_streams = o.drafts }, + .draft_probabilities = o.drafts and chances != .off, .draft_streams = o.drafts }, .rows = if (o.drafts) max_rows else 1, .stream_bytes = forward.seqBytes(own.e), .ctx = own, @@ -1289,6 +1294,9 @@ fn probabilitiesFn(p: *anyopaque, s: *lanes.Stream, out: []f64) anyerror!bool { const l = self.lanes_by.getPtr(s) orelse return false; if (out.len > l.nheld) return false; @memcpy(out, l.probs[0..out.len]); + if (chances == .chain) for (1..out.len) |i| { + out[i] *= out[i - 1]; + }; return true; } From 7b1870d34f82ef49e15e63a5552094f63c79ca0a Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Sat, 10 Oct 2026 03:37:00 +0000 Subject: [PATCH 7/7] Flash Next native: the split capture's switch and recorder set at init --- zig/src/families/flashnext_cuda/forward.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zig/src/families/flashnext_cuda/forward.zig b/zig/src/families/flashnext_cuda/forward.zig index 43764f27f6c..c5786fb7e78 100644 --- a/zig/src/families/flashnext_cuda/forward.zig +++ b/zig/src/families/flashnext_cuda/forward.zig @@ -638,6 +638,8 @@ pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *api.Ctx, kernels: *api.Ker e.gpu_ms = 0; e.enq_ms = 0; e.wait_ms = 0; + e.split_gathers = false; + e.rec = null; e.graphs = .init(gpa); return e; }