Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
115 changes: 111 additions & 4 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("host_sample.zig");
const think = @import("think.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.
Expand Down Expand Up @@ -40,6 +41,7 @@ pub const Backend = struct {
draft_calls: u64 = 0,
draft_waits: u64 = 0,
draft_seconds: f64 = 0,
lone_handoffs: u64 = 0, // lone streams the engine's rounds handed to the shared ones
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

Expand Down Expand Up @@ -94,8 +96,8 @@ pub const Backend = struct {
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 };
const lone_priced = c != null and std.c.getenv("FZ_LONE_UNPRICED") == null; // not `lone`: that names the lone driver
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_priced) &c.?.shared else &.{}, .mtp_step_ms = if (lone_priced) c.?.step_ms else 0 };
}

fn self(ptr: *anyopaque) *Backend {
Expand Down Expand Up @@ -160,13 +162,18 @@ pub const Backend = struct {
fn prefill(ptr: *anyopaque, stream: *Stream) anyerror!void {
const pool = mtl.objc.Pool.push();
defer pool.pop();
const b = self(ptr);
try self(ptr).fill(stream, null);
}

/// A stream's whole prompt pass, in session `slot` when given (free), else the first free one.
fn fill(b: *Backend, stream: *Stream, slot: ?usize) !void {
const prompt = stream.prompt();
if (prompt.len == 0) return error.EmptyPrompt;
try b.settle();
const i = for (b.sessions, 0..) |s, j| {
const i = slot orelse for (b.sessions, 0..) |s, j| {
if (!s.used) break j;
} else return error.NoFreeSlot;
if (b.sessions[i].used) return error.NoFreeSlot;
const s = &b.sessions[i];
if (prompt.len + stream.max_new + fz.MAXR + 1 > s.m.cap) return error.ContextFull;
try b.by.put(b.gpa, stream, i);
Expand Down Expand Up @@ -222,6 +229,91 @@ pub const Backend = struct {
s.m.mtp.drafted = 0;
}

/// Commits a lone stream's first token; its prompt as the context holds it after the commit, which can move it.
fn commitFirst(gpa: std.mem.Allocator, stream: *Stream, token: u32) ![]const u32 {
_ = try stream.commit(gpa, &.{token}, &.{});
return stream.prompt();
}

/// LaneHost's lone driver: the shared prompt pass into session 0, then the engine's rounds until done (false) or handed over (true).
pub fn lone(b: *Backend, stream: *Stream, hooks: anytype) !bool {
const pool = mtl.objc.Pool.push();
defer pool.pop();
const s = &b.sessions[0]; // the GPU-side rounds run on the engine's own buffers
if (s.used) return error.NoFreeSlot;
if (stream.prompt().len + stream.max_new + @import("engine.zig").MARGIN > s.m.cap) return error.ContextFull;
var handed = false;
defer if (!handed) release(b, stream);
try b.fill(stream, 0);
const prompt = try commitFirst(b.gpa, stream, s.first); // decode copies it to the rounds' history before any round commits
hooks.committed(hooks.ctx);
if (stream.finished) return false;
const Hooks = @TypeOf(hooks);
const Ctx = struct {
gpa: std.mem.Allocator,
stream: *Stream,
hooks: Hooks,
failed: ?anyerror = null,
fn prefilled(_: *anyopaque) void {}
fn tokens(p: *anyopaque, toks: []const u32) bool {
const c: *@This() = @ptrCast(@alignCast(p));
_ = c.stream.commit(c.gpa, toks, &.{}) catch |err| {
c.failed = err;
return true;
};
c.hooks.committed(c.hooks.ctx);
return c.stream.finished;
}
fn cancelled(p: *anyopaque) bool { // a request waits, or one is cancelled: the lane core takes over
const c: *@This() = @ptrCast(@alignCast(p));
return c.hooks.yield(c.hooks.ctx);
}
};
var c: Ctx = .{ .gpa = b.gpa, .stream = stream, .hooks = hooks };
var ho: Engine.Handoff = .{};
{
const old = try b.bind(s);
defer old.restore(b);
outputs(b, s, 0);
var watch = try think.Watch.init(.{}); // no thinking budget: lone_host_lone.fits keeps those in the lane core
const res = try b.e.decode(prompt, s.first, s.last, stream.max_new, stream.eos, null, &watch, .{ .ctx = &c, .prefilled = Ctx.prefilled, .tokens = Ctx.tokens, .cancelled = Ctx.cancelled }, &ho);
if (c.failed) |err| return err;
stream.rounds += res.rounds;
stream.drafted += res.drafted;
stream.accepted += res.accepted;
if (res.rounds > 0) stream.min_rows = if (stream.min_rows == 0) res.min_rows else @min(stream.min_rows, res.min_rows);
}
if (!ho.yielded) {
if (!stream.finished) { // the rounds ended where the stream did not (eos or length by the engine's count)
stream.finished = true;
stream.reason = .stop;
}
return false;
}
const ctx = stream.context.items;
const at = ho.cache; // the cache's rows: every committed token but the last, the next window's first
if (at + 1 != ctx.len or at < 2) return error.HandoffOutOfStep;
s.m.pos = at;
s.m.state = 0;
s.m.state_row = 0;
s.m.ple.hist = .{ ctx[at - 2], ctx[at - 1] };
s.m.mtp.pos = at;
s.m.mtp.drafted = 0;
s.m.mtp.pooled_n = @min(s.m.mtp.pooled_n, at / 4); // blocks the rounds pooled are pooled again here
for (&s.m.layers) |*l| if (!l.linear) {
l.pooled_n = @min(l.pooled_n, at / 4);
};
s.held_n = 0;
s.round = .{};
stream.cache_len = at;
stream.pending = ctx[at];
stream.next = null;
handed = true;
b.lone_handoffs += 1;
std.log.info("flash next: a lone stream at {d} tokens handed to the shared rounds ({d} handoffs)", .{ at, b.lone_handoffs });
return true;
}

fn first(ptr: *anyopaque, stream: *Stream, position: u64) anyerror!u64 {
const s = try self(ptr).session(stream);
if (position != s.m.pos) return error.PositionMismatch;
Expand Down Expand Up @@ -435,3 +527,18 @@ pub const Backend = struct {
snap.drop(self(ptr).gpa, @ptrCast(@alignCast(saved)));
}
};

test "a lone stream's prompt is read after its first token's commit moves the context" {
const gpa = std.testing.allocator;
const tokens = [_]u32{ 11, 12, 13, 14, 15, 16, 17 };
var stream = try Stream.init(gpa, .{ .id = "lone", .prompt = &tokens, .max_new = 4, .eos = &.{} });
defer stream.deinit(gpa);
stream.context.shrinkAndFree(gpa, stream.context.items.len); // full: the first token must grow it
var failing = std.testing.FailingAllocator.init(gpa, .{ .resize_fail_index = 0 }); // and not in place
const before = stream.context.items.ptr;
const prompt = try Backend.commitFirst(failing.allocator(), &stream, 99);
try std.testing.expect(stream.context.items.ptr != before);
try std.testing.expectEqual(stream.context.items.ptr, prompt.ptr);
try std.testing.expectEqualSlices(u32, &tokens, prompt);
try std.testing.expectEqualSlices(u32, &.{99}, stream.emitted());
}
30 changes: 27 additions & 3 deletions zig/src/families/flashnext/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -602,12 +602,23 @@ pub const Engine = struct {
}
out.prefilled(out.ctx);
pick = watch.first(pick);
var res: Result = .{ .reason = .length };
const first_stop = out.tokens(out.ctx, &.{pick}) or isEos(eos, pick);
try dr.flush(e, out); // after the first token: the slots, rows and tail stay put till the rounds
if (e.call_log) calls.log(if (r.tp) |tp| tp.rank else 0);
if (try e.agree(first_stop)) return .{ .reason = .stop };
if (max_tokens <= 1) return res;
if (max_tokens <= 1) return .{ .reason = .length };
return e.decode(prompt, pick, .{ .b = m.last.b, .off = m.last.off + (last_n - 1) * WIDE * 2 }, max_tokens, eos, depth, &watch, out, null);
}

/// Where `decode` left a stream it handed over: its state as a host round leaves it, `cache` rows in the cache.
pub const Handoff = struct { yielded: bool = false, cache: usize = 0 };

/// The GPU-side rounds after a prompt pass from `pick` and the last prompt row's `streams`; with `handoff` a cancel hands the stream over.
pub fn decode(e: *Engine, prompt: []const u32, pick: u32, streams: Buf, max_tokens: usize, eos: []const u32, depth: ?usize, watch: *think.Watch, out: Out, handoff: ?*Handoff) !Result {
const r = e.r;
const m = e.m;
defer e.hostMode();
var res: Result = .{ .reason = .length };
var emitted: usize = 1;
const ar = r.ar.b.slice(i32, fz.AR_WORDS);
if (m.state == 1) { // the state into the rounds' state buffers
Expand All @@ -631,7 +642,7 @@ pub const Engine = struct {
w[0] = pick;
if (depth0 > 0) { // the head: the last prompt row with the first token, then its chain
m.mtp.pos = prompt.len - 1;
w[1] = try m.mtpRun(&.{pick}, .{ .b = m.last.b, .off = m.last.off + (last_n - 1) * WIDE * 2 });
w[1] = try m.mtpRun(&.{pick}, streams);
for (2..depth0 + 1) |j| w[j] = try m.mtpChain(w[j - 1]);
}
const W0 = depth0 + 1;
Expand Down Expand Up @@ -679,6 +690,7 @@ pub const Engine = struct {
res.min_rows = @intCast(W0);
const rg = e.ring.slice(u32, fz.RING_WORDS * RING);
var failed: ?anyerror = null;
var kv_len: usize = m.pos; // the cache's rows after the rounds landed so far
while (true) {
const wr = widths[round % 4];
const cb = r.queue.commandBuffer();
Expand Down Expand Up @@ -778,6 +790,7 @@ pub const Engine = struct {
if (learn) res.accepted += keep - 1;
res.min_rows = @min(res.min_rows, @as(u32, @intCast(wd)));
done += 1;
kv_len += keep;
var take: usize = 0;
var stop = false;
while (take < got.len and emitted + take < max_tokens) {
Expand Down Expand Up @@ -810,9 +823,20 @@ pub const Engine = struct {
};
r.event_value = base + round + 1;
if (failed) |err| return err;
if (handoff) |h| if (res.reason == .cancelled) try e.handOver(h, round, kv_len);
return res;
}

/// The rounds handed over at `cache` rows: the round ahead already started as rounds do; the n-gram tail into the model's own buffer.
fn handOver(e: *Engine, h: *Handoff, round: usize, cache: usize) !void {
if (e.r.gdn_kept != null) return error.HandoffUnsupported; // kept states replay their rows in the next window
if ((round - 1) % 2 == 1) {
const n = PLE_TAIL * WIDE * 2;
@memcpy(e.cins[0].b.contents()[e.cins[0].off..][0..n], e.cins[1].b.contents()[e.cins[1].off..][0..n]);
}
h.* = .{ .yielded = true, .cache = cache };
}

/// Speed-up mode: whether to stop at a step both ranks take (rank 0 decides, rank 1 follows); alone, `quit`.
fn agree(e: *Engine, quit: bool) !bool {
return if (e.r.tp) |tp| (try tp.agree(quit, 0)).quit else quit;
Expand Down
9 changes: 8 additions & 1 deletion zig/src/native/flashnext_batch_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, dump: ?[]const
const plan = try fit.budgetUnder(cap, cache_gib, over, 0, a, why, ""); // the cache under the same limit as the sessions
eng.snap_pool.max = plan.budget_bytes;
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "flashnext-zig", .lanes = slots, .context_window = @intCast(window), .prefill_step = @intCast(eng.pr.step), .prompt_cache_plan = plan });
// a lone greedy request runs on the engine's GPU-side rounds until a second one arrives (FLASHNEXT_NO_LONE=1: shared rounds)
if (eng.r.gdn_kept == null and std.c.getenv("FLASHNEXT_NO_LONE") == null) h.host.lone = .{ .ctx = h, .run = loneRun };
h.cache = null;
if (plan.budget_bytes > 0) {
h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = &h.back, .vtable = &.{ .bytes = Backend.snapBytes, .save = Backend.snapSave, .restore = Backend.snapRestore, .drop = Backend.snapDrop, .charged = Backend.snapCharged, .spare = Backend.snapSpare, .trim = Backend.snapTrim, .reuses = Backend.snapReuses } }, .{ .lookahead = 1, .planned = true }, plan.budget_bytes);
Expand All @@ -80,10 +82,15 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, dump: ?[]const
h.warm = .{ .queue = eng.r.queue };
h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick };
try h.host.start();
std.log.info("Flash Next: {d} session slots, shared target forwards, {s}", .{ slots, if (h.back.serial_drafts) "serial MTP drafts" else "every stream's drafts in one command buffer" });
std.log.info("Flash Next: {d} session slots, shared target forwards, {s}{s}", .{ slots, if (h.back.serial_drafts) "serial MTP drafts" else "every stream's drafts in one command buffer", if (h.host.lone != null) "; a lone request on the engine's own rounds" else "" });
return .{ .engine = h.host.engine(), .close = close, .ctx = h };
}

fn loneRun(ctx: *anyopaque, s: *lanes.Stream, hooks: api.LoneHooks) anyerror!bool {
const h: *Host = @ptrCast(@alignCast(ctx));
return h.back.lone(s, hooks);
}

fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 {
return switch (err) {
error.ContextFull => "the prompt and max_tokens do not fit this server's --context",
Expand Down
1 change: 1 addition & 0 deletions zig/src/tensorfold.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ test {
_ = @import("families/flashnext/dense.zig"); // The core projection adapter keeps format, cuts and tiles.
_ = @import("families/flashnext/marks.zig"); // a call's marks
_ = @import("families/flashnext/think.zig"); // a thinking budget's close on the host
_ = @import("families/flashnext/backend.zig"); // the shared sessions' backend (a lone stream's prompt after its first commit)
_ = @import("families/flashnext/batch_costs.zig"); // the shared rounds' timing needs a session that holds it
_ = @import("families/flashnext/think_check.zig"); // and in the verdict kernels (Metal)
_ = @import("families/flashnext/sample.zig"); // a sampled window's draws on the GPU (Metal)
Expand Down