Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
b523c90
Flash Next: opt-in continuous batching on native Metal
cwschroeder Oct 10, 2026
fd272ef
Preserve alternating benchmark receipts on the current upstream base
cwschroeder Oct 10, 2026
0c8d4d5
Apply Zig 0.17 formatting required by current CI
cwschroeder Oct 10, 2026
6dbf170
Flash Next: chain batch MTP drafts in one Metal command buffer
cwschroeder Oct 10, 2026
39824c6
Qualify experimental batch MTP chaining on M3 Ultra
cwschroeder Oct 10, 2026
77ebc3f
Attach final current-base host validation receipt
cwschroeder Oct 10, 2026
a5e409e
Flash Next shared sessions: FLASHNEXT_LOAD_LIMIT_GB lets the slots ta…
BobClawblaw Oct 11, 2026
1874ffe
Flash Next shared sessions sample: a request's temperature draws each…
BobClawblaw Oct 12, 2026
b7372ac
Flash Next's host sampler: an unlimited or wide top-k by a counting s…
BobClawblaw Oct 12, 2026
03cc874
FLASHNEXT_LOAD_LIMIT_GB covers the prompt cache too: the automatic bu…
BobClawblaw Oct 12, 2026
d519c08
Flash Next's wide top-k draw keeps a uniform that rounds to 1: its +i…
BobClawblaw Oct 12, 2026
5d59c76
Merge #8 from BobClawblaw: Flash Next shared sessions: FLASHNEXT_LOAD…
cwschroeder Oct 13, 2026
c930303
Merge #7 from BobClawblaw: Flash Next shared sessions sample: a reque…
cwschroeder Oct 13, 2026
04c8571
Merge upstream main (TensorFold 1.0.8) into Flash Next continuous bat…
cwschroeder Oct 13, 2026
3f24b00
Flash Next shared rounds priced from forwards timed at load; every st…
sethforprivacy Oct 12, 2026
5551aba
Flash Next shared sessions sized to the traffic: FLASHNEXT_SLOT_CONTE…
sethforprivacy Oct 12, 2026
a3085be
Flash Next: a lone request on the engine's GPU-side rounds, handed to…
sethforprivacy Oct 12, 2026
ba31b91
Flash Next sized sessions: grow on the reply's remaining work, never …
Oct 13, 2026
dd86083
Flash Next shared-round prices: time only on a session that holds the…
Oct 13, 2026
09c7262
Flash Next lone driver: read the prompt after the first token's commi…
Oct 13, 2026
3cb70f0
Merge #9 from sethforprivacy: Flash Next shared rounds priced from fo…
cwschroeder Oct 14, 2026
59df001
Merge feat/flashnext-continuous-batching (#9) into flashnext-batch-lone
Oct 14, 2026
0f679e2
Flash Next lone driver: lone's doc comment above lone again (commitFi…
Oct 14, 2026
198b3c5
Merge feat/flashnext-continuous-batching (#9) into flashnext-batch-se…
Oct 14, 2026
b1a4204
Flash Next: facts' priced-lone flag renamed from `lone`, which the me…
Oct 14, 2026
069ef4d
Flash Next sized sessions: a paused stream whose move fails ends with…
Oct 14, 2026
f70705a
Merge Flash Next batching onto current upstream, preserve both head c…
cwschroeder Oct 16, 2026
2f69e55
Merge reviewed lone-driver fixes alongside measured batching costs
cwschroeder Oct 16, 2026
15e424e
Merge sized sessions and migration failure handling with lone handoff
cwschroeder Oct 16, 2026
72d817c
Finish migration-failed peers after cancellation before freeing their…
cwschroeder Oct 16, 2026
1d0f0df
Port shared Flash Next session bindings to current upstream
cwschroeder Oct 16, 2026
dd1b741
Serve default Flash Next requests on memory-sized shared sessions
cwschroeder Oct 16, 2026
4e184b2
Retain shared-family tests after extracting the first-token lifetime …
cwschroeder Oct 16, 2026
fac5563
Describe the default shared route consistently in the README and recipe
cwschroeder Oct 16, 2026
f36482a
Gate default Flash Next serving with observed shared GPU rounds
cwschroeder Oct 16, 2026
b038a3d
Preserve Flash Next residency and lifecycle after the upstream rebase
cwschroeder Oct 16, 2026
8cee8ef
Draw shared Flash Next picks with the upstream GPU sampler
cwschroeder Oct 16, 2026
d0f6138
Avoid a second warmup when auto falls back to one Flash Next session
cwschroeder Oct 16, 2026
ef85c8b
Honor validated model load limits when keeping buffers resident
cwschroeder Oct 16, 2026
5164380
Refuse --parallel above one with --learn as with --speed-up; restore …
cwschroeder Oct 16, 2026
1bf016d
A warm pass its cache keeps nothing of is skipped: Flash Next's short…
BobClawblaw Oct 17, 2026
b2595ed
Flash Next reads images on one Mac with --vision: the shared Qwen-VL …
BobClawblaw Oct 17, 2026
c7d9f69
Flash Next's next-turn pass skips an image prompt on one Mac: its sta…
BobClawblaw Oct 17, 2026
557f5b8
Flash Next reads images on shared sessions: each stream's prompt pass…
BobClawblaw Oct 17, 2026
abab848
Flash Next reads videos with --vision: Qwen3-VL's frame pairs at two …
BobClawblaw Oct 17, 2026
4af9b08
Flash Next images and video documented; the video offer's Qwen layout…
BobClawblaw Oct 17, 2026
8a509ab
Flash Next image and video chats resume from the prompt cache: a kept…
BobClawblaw Oct 17, 2026
8e4ba6d
Flash Next shared sessions enforce structured output: verify rows mas…
BobClawblaw Oct 17, 2026
440ca2b
Flash Next's grammar mask under the kernel contract: fz_mask_rows in …
BobClawblaw Oct 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion zig/src/core/lanes/allocate.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ pub const Cost = struct { width: u32, ms: f64 };

/// Draft prefixes per stream with the most expected tokens a ms; fixed rows always run. Caller frees.
pub fn allocate(gpa: Allocator, fixed: []const u32, probs: []const []const f64, costs: *const Table, overhead_ms: f64, max_rows: u64) ![]u32 {
return allocatePriced(gpa, fixed, probs, costs, overhead_ms, max_rows, 0);
}

/// allocate, each stream's nodes past its first costing `step_ms` more (a head step drafts each of them).
pub fn allocatePriced(gpa: Allocator, fixed: []const u32, probs: []const []const f64, costs: *const Table, overhead_ms: f64, max_rows: u64, step_ms: f64) ![]u32 {
const counts = try gpa.alloc(u32, probs.len);
defer gpa.free(counts);
const best_counts = try gpa.alloc(u32, probs.len);
@memset(counts, 0);
@memset(best_counts, 0);
var rows: u64 = 0;
for (fixed) |f| rows += f;
var steps: f64 = 0;
var expected: f64 = @floatFromInt(rows);
const timed = !costs.empty();
var best = rate(costs, timed, rows, expected, overhead_ms);
Expand All @@ -31,9 +37,10 @@ pub fn allocate(gpa: Allocator, fixed: []const u32, probs: []const []const f64,
}
const s = pick orelse break;
counts[s] += 1;
if (counts[s] > 1) steps += 1;
rows += 1;
expected += pick_p;
const now = rate(costs, timed, rows, expected, overhead_ms);
const now = rate(costs, timed, rows, expected, overhead_ms + step_ms * steps);
if (now > best) {
best = now;
@memcpy(best_counts, counts);
Expand Down Expand Up @@ -114,6 +121,55 @@ test "allocate takes the widest round when no cost is timed" {
try std.testing.expectEqualSlices(u32, &.{ 2, 1 }, counts);
}

test "a priced draft step keeps a stream's later drafts out when they land too seldom to pay" {
const gpa = std.testing.allocator;
var costs = try extendCosts(gpa, &.{ .{ .width = 1, .ms = 10.0 }, .{ .width = 8, .ms = 12.0 } }, 8);
defer costs.deinit(gpa);
const probs = [_][]const f64{ &.{ 0.6, 0.3, 0.15 }, &.{ 0.6, 0.3, 0.15 } };
const free = try allocate(gpa, &.{ 1, 1 }, &probs, &costs, 2.0, 8);
defer gpa.free(free);
try std.testing.expectEqualSlices(u32, &.{ 3, 3 }, free);
const priced = try allocatePriced(gpa, &.{ 1, 1 }, &probs, &costs, 2.0, 8, 1.5);
defer gpa.free(priced);
try std.testing.expectEqualSlices(u32, &.{ 1, 1 }, priced);
}

test "a priced draft step leaves each stream's first draft free" {
const gpa = std.testing.allocator;
var flat = try extendCosts(gpa, &.{ .{ .width = 1, .ms = 10.0 }, .{ .width = 8, .ms = 10.0 } }, 8);
defer flat.deinit(gpa);
const probs = [_][]const f64{&.{0.5}};
// charged, the draft would cost 100 ms against 0.5 tokens: it stays because the first is free
const counts = try allocatePriced(gpa, &.{1}, &probs, &flat, 0.0, 8, 100.0);
defer gpa.free(counts);
try std.testing.expectEqualSlices(u32, &.{1}, counts);
}

test "a priced draft step cuts the stream whose later drafts land seldom and keeps the other's" {
const gpa = std.testing.allocator;
var flat = try extendCosts(gpa, &.{ .{ .width = 1, .ms = 10.0 }, .{ .width = 8, .ms = 10.0 } }, 8);
defer flat.deinit(gpa);
const probs = [_][]const f64{ &.{ 0.9, 0.85, 0.8 }, &.{ 0.9, 0.2, 0.1 } };
const priced = try allocatePriced(gpa, &.{ 1, 1 }, &probs, &flat, 0.0, 8, 1.0);
defer gpa.free(priced);
try std.testing.expectEqualSlices(u32, &.{ 3, 1 }, priced);
const free = try allocate(gpa, &.{ 1, 1 }, &probs, &flat, 0.0, 8);
defer gpa.free(free);
try std.testing.expectEqualSlices(u32, &.{ 3, 3 }, free);
}

test "a zero draft step prices rounds as allocate does" {
const gpa = std.testing.allocator;
var costs = try extendCosts(gpa, &.{ .{ .width = 1, .ms = 10.0 }, .{ .width = 8, .ms = 12.0 } }, 8);
defer costs.deinit(gpa);
const probs = [_][]const f64{ &.{ 0.9, 0.85, 0.8 }, &.{ 0.9, 0.2, 0.1 }, &.{0.4} };
const priced = try allocatePriced(gpa, &.{ 1, 1, 1 }, &probs, &costs, 2.0, 8, 0.0);
defer gpa.free(priced);
const free = try allocate(gpa, &.{ 1, 1, 1 }, &probs, &costs, 2.0, 8);
defer gpa.free(free);
try std.testing.expectEqualSlices(u32, free, priced);
}

test "extendCosts interpolates and extrapolates" {
const gpa = std.testing.allocator;
var t = try extendCosts(gpa, &.{ .{ .width = 4, .ms = 8.0 }, .{ .width = 2, .ms = 4.0 } }, 6);
Expand Down
3 changes: 3 additions & 0 deletions zig/src/core/lanes/config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub const Model = struct {
drafts: u32 = 1, // head drafts a round at most
window_costs: []const Cost = &.{}, // forward ms by exact window width (timed at load)
mtp_step_ms: f64 = 0.0, // one chained head step (timed at load)
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)
streams_exact: bool = true, // shared forwards keep each stream's bits
hidden_rows: bool = false, // the backend runs several streams' windows in one forward
batch_rows: u32 = 0, // a shared forward's rows at most (0: 32)
Expand Down Expand Up @@ -63,6 +64,7 @@ pub const Config = struct {
shared_costs: Table,
lane_costs: Table, // window ms by rows to 64 (lanes/plan_lanes.zig)
mtp_step_ms: f64,
draft_step_ms: f64 = 0, // Model.draft_step_ms
enter_match: i64 = 8, // matching tokens a copy needs (rejects coincidental indentation)
copy_rate: f64 = 0.94, // a copied token's chance of landing in allocation
lone_copies: bool = true, // Model.lone_copies
Expand Down Expand Up @@ -121,6 +123,7 @@ pub const Config = struct {
.lane_costs = try alloc.extendCosts(gpa, m.lane_costs, 64),
.mtp_step_ms = m.mtp_step_ms,
.k = .{ .depth_rate = if (m.depth_rate > 0) m.depth_rate else (Constants{}).depth_rate },
.draft_step_ms = m.draft_step_ms,
};
}

Expand Down
3 changes: 2 additions & 1 deletion zig/src/core/lanes/depth.zig
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub const Rule = struct {
family_costs: *const Table,
shared_costs: *const Table,
mtp_step_ms: f64,
draft_step_ms: f64 = 0, // a shared round's draft past a stream's first (budgets price it)
plain_guard: bool,
node_probabilities: bool,
batch_rows: u32,
Expand Down Expand Up @@ -220,7 +221,7 @@ pub const Rule = struct {
const ones = try r.gpa.alloc(u32, whos.len);
defer r.gpa.free(ones);
@memset(ones, 1);
const counts = try alloc.allocate(r.gpa, ones, probs, r.shared_costs, r.overheadMs(whos.len, sampled), @max(whos.len, r.batch_rows));
const counts = try alloc.allocatePriced(r.gpa, ones, probs, r.shared_costs, r.overheadMs(whos.len, sampled), @max(whos.len, r.batch_rows), r.draft_step_ms);
defer r.gpa.free(counts);
if (r.plain_guard) {
// no draft where none pays; a probe after a growing run of plain rounds
Expand Down
6 changes: 5 additions & 1 deletion zig/src/core/lanes/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub const Engine = struct {
.family_costs = &cfg.family_costs,
.shared_costs = &cfg.shared_costs,
.mtp_step_ms = cfg.mtp_step_ms,
.draft_step_ms = cfg.draft_step_ms,
.plain_guard = cfg.plain_guard,
.node_probabilities = cfg.node_probabilities,
.batch_rows = cfg.batch_rows,
Expand Down Expand Up @@ -293,7 +294,10 @@ pub const Engine = struct {
for (heads.items, budgets) |i, d| try e.draftLate(plans[i].stream, plans[i].position, outcomes[i].follow, outcomes[i].path, d);
}
try e.backend.keep(windows, paths);
const ms = e.clock.elapsedMs(.overhead);
// the drafts budgets priced past each stream's first are no part of the round's overhead
var steps: i64 = 0;
for (budgets) |d| steps += @max(0, d - 1);
const ms = e.clock.elapsedMs(.overhead) - e.cfg.draft_step_ms * @as(f64, @floatFromInt(steps));
try trail.event(e, &.{ f("ev", str("overhead")), f("streams", int(plans.len)), f("rows", int(total)), f("ms", ev.bits(ms)) });
try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled);
}
Expand Down
91 changes: 86 additions & 5 deletions zig/src/families/flashnext/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const Buf = fz.Buf;
const mtl = @import("metal");
const segments = @import("../../core/segments.zig");
const sample = @import("sample.zig");
const batch_costs = @import("batch_costs.zig");

/// A stream's sampling when it samples (a temperature above 0); null: the GPU's argmax stands.
fn sampling(stream: *const Stream) ?lanes.Sampling {
Expand All @@ -39,6 +40,8 @@ pub const Backend = struct {
draft_calls: u64 = 0,
draft_waits: u64 = 0,
draft_seconds: f64 = 0,
serial_drafts: bool = false, // FZ_BATCH_MTP_SERIAL=1: each stream's drafts in their own command buffers
costs: ?batch_costs.Costs = null, // timeCosts: the lane allocator's prices

pub fn init(gpa: std.mem.Allocator, e: *Engine, n: u32, capacity: usize) !Backend {
if (n < 2 or n > fz.MAXR or e.r.tp != null) return error.BadBatchSlots;
Expand All @@ -51,7 +54,28 @@ pub const Backend = struct {
made += 1;
}
const hidden = try e.r.device.buffer(fz.MAXR * fz.WIDE * 2, fz.opts);
return .{ .gpa = gpa, .e = e, .primary = e.m, .sessions = sessions, .hidden = .{ .b = hidden }, .chain_drafts = if (std.c.getenv("FZ_BATCH_MTP_CHAIN")) |v| v[0] == '1' else false };
const env = struct {
fn on(name: [*:0]const u8) bool {
return if (std.c.getenv(name)) |v| v[0] == '1' else false;
}
};
return .{ .gpa = gpa, .e = e, .primary = e.m, .sessions = sessions, .hidden = .{ .b = hidden }, .chain_drafts = env.on("FZ_BATCH_MTP_CHAIN"), .serial_drafts = env.on("FZ_BATCH_MTP_SERIAL") };
}

/// The lane allocator's prices, timed on the last session before any stream holds it; none (unpriced) when it can't be.
pub fn timeCosts(b: *Backend) !void {
if (std.c.getenv("FZ_BATCH_UNPRICED") != null) {
std.log.info("flash next: FZ_BATCH_UNPRICED=1: shared rounds unpriced, nothing timed", .{});
return;
}
const s = &b.sessions[b.sessions.len - 1];
if (!batch_costs.fits(s.m.cap)) {
std.log.info("flash next: a session holds {d} rows, under the {d} that timing shared rounds takes: shared rounds unpriced", .{ s.m.cap, batch_costs.ROWS });
return;
}
const c = try batch_costs.time(b, s);
b.costs = c;
std.log.info("flash next: shared forwards {d:.2} {d:.2} {d:.2} {d:.2} {d:.2} ms at 1, 2, 4, 8, 16 rows; a chained draft {d:.2} ms", .{ c.shared[0].ms, c.shared[1].ms, c.shared[3].ms, c.shared[7].ms, c.shared[15].ms, c.step_ms });
}

pub fn deinit(b: *Backend) void {
Expand All @@ -67,7 +91,11 @@ pub const Backend = struct {
}

pub fn facts(b: *Backend) lanes.Model {
return .{ .exact_width = fz.MAXR, .first_copy_rows = 4, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 8, .streams_exact = true, .hidden_rows = true, .batch_rows = fz.MAXR, .max_streams = @intCast(b.sessions.len), .draft_streams = false };
const c: ?*const batch_costs.Costs = if (b.costs) |*x| x else null;
// shared rounds priced from the timed forwards, each draft past a stream's first at a chained step's time; a
// lone stream's depth from the same (FZ_LONE_UNPRICED=1: the heuristic)
const lone = c != null and std.c.getenv("FZ_LONE_UNPRICED") == null;
return .{ .exact_width = fz.MAXR, .first_copy_rows = 4, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 8, .streams_exact = true, .hidden_rows = true, .batch_rows = fz.MAXR, .max_streams = @intCast(b.sessions.len), .draft_streams = !b.serial_drafts, .shared_costs = if (c) |x| &x.shared else &.{}, .draft_step_ms = if (c != null and !b.serial_drafts) c.?.step_ms else 0, .window_costs = if (lone) &c.?.shared else &.{}, .mtp_step_ms = if (lone) c.?.step_ms else 0 };
}

fn self(ptr: *anyopaque) *Backend {
Expand Down Expand Up @@ -106,7 +134,7 @@ pub const Backend = struct {
select: ?fz.Select,
shape: @TypeOf(@as(fz.Select, undefined).q_shape),
passed: @FieldType(Engine, "passed"),
fn restore(old: Binding, b: *Backend) void {
pub fn restore(old: Binding, b: *Backend) void {
b.e.m = old.model;
b.e.host = old.host;
b.e.cins = old.cins;
Expand All @@ -116,7 +144,7 @@ pub const Backend = struct {
}
};

fn bind(b: *Backend, s: *Session) !Binding {
pub fn bind(b: *Backend, s: *Session) !Binding {
const e = b.e;
const old: Binding = .{ .model = e.m, .host = e.host, .cins = e.cins, .select = e.r.sel, .shape = e.r.shapes.get("Kc_shape").?, .passed = e.passed };
try e.r.shapes.put(e.r.arena, "Kc_shape", s.shape);
Expand Down Expand Up @@ -206,7 +234,7 @@ pub const Backend = struct {
return @intCast(handle);
}

fn outputs(b: *Backend, s: *Session, row: usize) void {
pub fn outputs(b: *Backend, s: *Session, row: usize) void {
var li: usize = 0;
for (&s.m.layers) |*l| if (l.linear) {
l.cs[1] = .{ .b = b.e.o_cs, .off = (li * fz.MAXR + row) * fz.CS_ROW };
Expand Down Expand Up @@ -278,6 +306,7 @@ pub const Backend = struct {

fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void {
const b = self(ptr);
if (!b.serial_drafts) return b.draftTogether(requests);
for (requests) |r| {
const pool = mtl.objc.Pool.push();
defer pool.pop();
Expand Down Expand Up @@ -316,6 +345,58 @@ pub const Backend = struct {
}
}

/// Every request's absorb and chained drafts in one command buffer, one wait (a long follow absorbs alone first).
fn draftTogether(b: *Backend, requests: []const be.DraftRequest) !void {
const pool = mtl.objc.Pool.push();
defer pool.pop();
const start = mtl.clock.seconds();
var follows: [fz.MAXR][]const u32 = undefined;
var hiddens: [fz.MAXR]Buf = undefined;
var ones: [fz.MAXR][1]u32 = undefined;
if (requests.len > fz.MAXR) return error.DraftOutOfStep;
for (requests, 0..) |r, k| {
if (r.early or r.lanes != null or r.ranks or r.depth >= fz.MAXR) return error.DraftOutOfStep;
const s = try b.session(r.stream);
follows[k] = if (r.first) |f| blk: {
ones[k][0] = switch (f) {
.value => |v| v,
.handle => |h| @intCast(h),
};
break :blk ones[k][0..];
} else r.follow;
if (follows[k].len == 0) return error.DraftOutOfStep;
hiddens[k] = if (r.rows) |path| blk: {
try s.round.draft(r.start, path, follows[k].len);
break :blk b.hidden.at(s.row0 * fz.WIDE * 2);
} else s.last;
if (follows[k].len > fz.MAXR) { // all but the last MAXR rows absorbed first, on their own
const cut = follows[k].len - fz.MAXR;
const old = try b.bind(s);
defer old.restore(b);
_ = try s.m.mtpAbsorb(follows[k][0..cut], hiddens[k]);
hiddens[k] = hiddens[k].at(cut * fz.WIDE * 2);
follows[k] = follows[k][cut..];
b.draft_waits += (cut + fz.MAXR - 1) / fz.MAXR;
}
}
const cb = b.e.r.queue.commandBuffer();
b.e.r.enc = cb.compute(if (b.e.r.serial) .serial else .concurrent);
for (requests, 0..) |r, k| {
const s = try b.session(r.stream);
const old = try b.bind(s);
defer old.restore(b);
s.encodeDrafts(follows[k], hiddens[k], r.depth) catch |err| {
b.e.r.enc.end();
return err;
};
}
try b.primary.finish(cb);
for (requests) |r| (try b.session(r.stream)).heldDrafts(r.depth);
b.draft_waits += 1;
b.draft_calls += requests.len;
b.draft_seconds += mtl.clock.seconds() - start;
}

fn release(ptr: *anyopaque, stream: *Stream) void {
const b = self(ptr);
const kv = b.by.fetchRemove(stream) orelse return;
Expand Down
Loading