Skip to content
Next Next commit
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.
  • Loading branch information
BobClawblaw authored and xian committed Oct 10, 2026
commit cb005c30ed8f5d587e7fa8d21e47f5975dc836f7
14 changes: 14 additions & 0 deletions zig/src/families/flashnext_cuda/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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 };

Expand All @@ -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]);
Expand All @@ -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;
Expand Down
53 changes: 47 additions & 6 deletions zig/src/families/flashnext_cuda/native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 ---------------------------------------------------------------------------

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand Down Expand Up @@ -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);
Expand Down
72 changes: 72 additions & 0 deletions zig/src/families/flashnext_cuda/prof.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! TENSORFOLD_FN_PROFILE=<rounds>: 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;
}