Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Flash Next reads videos with --vision: Qwen3-VL's frame pairs at two …
…a second, each "<X.Y seconds>" before its group, as transformers lays them out
  • Loading branch information
BobClawblaw committed Oct 17, 2026
commit abab848fcde0f7bb1902eb5145b5fe1163329db2
4 changes: 4 additions & 0 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ pub const VideoOffer = struct {
/// The tokens around each group's image tokens; the group's time follows as text.
group_open: u32,
group_close: u32,
/// The token each group's rows take; null: the image token.
group_token: ?u32 = null,
/// Qwen's layout (transformers' Qwen3VLProcessor): each group's time first, as "<X.Y seconds>", then the group.
time_first: bool = false,
/// The tokens the template wraps a video in (the video token among them): text that spells one stays text.
markers: []const u32 = &.{},
/// Video tokens one request may hold in all, videos, and frames sampled a video.
Expand Down
2 changes: 2 additions & 0 deletions zig/src/core/qwen_vl/config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub const Config = struct {
image_token: u32,
vision_start: u32,
vision_end: u32,
video_token: ?u32 = null, // the template's video placeholder; null: the checkpoint reads no video
min_pixels: u64,
max_pixels: u64,
rescale: f64,
Expand Down Expand Up @@ -59,6 +60,7 @@ pub const Config = struct {
inline for (.{ .{ "image_token_id", "image_token" }, .{ "vision_start_token_id", "vision_start" }, .{ "vision_end_token_id", "vision_end" } }) |kv| {
@field(c, kv[1]) = try positive(doc.object.get(kv[0]));
}
if (doc.object.get("video_token_id")) |v| c.video_token = try positive(v);
if (vc.object.get("in_channels")) |v| if (try positive(v) != 3) return error.VisionConfig;
const act = vc.object.get("hidden_act") orelse return error.VisionConfig;
if (act != .string or !std.mem.eql(u8, act.string, "gelu_pytorch_tanh")) return error.VisionConfig;
Expand Down
4 changes: 3 additions & 1 deletion zig/src/core/qwen_vl/qwen_vl.zig
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
//! Image input every Qwen3.5-VL checkpoint shares, backend-neutral: settings, geometry, M-RoPE, the tower's tables.
//! Image and video input every Qwen3.5-VL checkpoint shares, backend-neutral: settings, geometry, M-RoPE, the tower's tables.
pub const config = @import("config.zig");
pub const Config = config.Config;
pub const geometry = @import("geometry.zig");
pub const rope = @import("rope.zig");
pub const grid = @import("grid.zig");
pub const video = @import("video.zig");

test {
_ = config;
_ = geometry;
_ = rope;
_ = grid;
_ = video;
}
209 changes: 209 additions & 0 deletions zig/src/core/qwen_vl/video.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
//! A video's frames to Qwen-VL tower patches as transformers 5.17's Qwen3VLVideoProcessor makes them from PyAV's.
const std = @import("std");
const picture = @import("../picture/picture.zig");
const Config = @import("config.zig").Config;

pub const Error = error{ VideoTooShort, VideoTooLarge, BadVideo, OutOfMemory };

/// The processor's sampling: two frames a second, at least `min_frames` and at most `max_frames`.
pub const fps = 2.0;
pub const min_frames = 4;
pub const max_frames = 768;

/// A decoded video's facts (the PyAV loader's VideoMetadata) and its frames on request.
pub const Source = struct {
frames: u64,
rate_num: u64,
rate_den: u64,
width: u32,
height: u32,
ctx: *anyopaque,
/// The frames at `indices` (ascending, distinct), each handed to `sink` in order as RGB rows `stride` bytes apart.
decode: *const fn (ctx: *anyopaque, indices: []const u32, sink: *Sink) anyerror!void,

fn rate(s: Source) f64 {
return @as(f64, @floatFromInt(s.rate_num)) / @as(f64, @floatFromInt(s.rate_den));
}
};

/// Where decoded frames go: each resized to the plan's size.
pub const Sink = struct {
plan: *const Plan,
frames: []u8, // [distinct frames, h, w, 3]
scratch: std.mem.Allocator,
got: usize = 0,

/// The plan's next distinct frame, `w` x `h` RGB rows `stride` bytes apart.
pub fn take(s: *Sink, k: usize, rgb: []const u8, w: u32, h: u32, stride: usize) Error!void {
const p = s.plan;
if (k != s.got or k >= p.distinct.len or w != p.width or h != p.height) return error.BadVideo;
const dst = s.frames[k * p.frameBytes() ..][0..p.frameBytes()];
// torchvision's uint8 resize
try picture.resample.into(s.scratch, .torch, .{ .pixels = rgb, .width = w, .height = h, .stride = stride }, p.w, p.h, dst);
s.got += 1;
}
};

/// What a video becomes before any frame is decoded.
pub const Plan = struct {
indices: []u32, // the sampled frames in order, repeats kept (np.linspace(...).round())
distinct: []u32, // the frames decoded: indices without repeats, ascending
times: []f64, // one a pair: the mean of its two frames' times (_calculate_timestamps)
width: u32,
height: u32,
h: u32, // the resized frame
w: u32,

fn frameBytes(p: Plan) usize {
return @as(usize, p.h) * p.w * 3;
}

pub fn pairs(p: Plan) usize {
return (p.indices.len + 1) / 2;
}
};

/// numpy's round: a half goes to the even neighbour.
fn roundEven(x: f64) f64 {
const r = @round(x);
return if (@abs(x - @trunc(x)) == 0.5 and @mod(r, 2) != 0) r - std.math.sign(x) else r;
}

/// sample_frames: int(total / rate * fps) frames, clamped, at np.linspace(0, total - 1, n).round().
pub fn sample(a: std.mem.Allocator, s: Source, most: u32) Error![]u32 {
if (s.frames == 0 or s.rate_num == 0 or s.rate_den == 0) return error.VideoTooShort;
const want: u64 = @intFromFloat(@as(f64, @floatFromInt(s.frames)) / s.rate() * fps);
const n: u64 = @min(@max(want, min_frames), @min(max_frames, most), s.frames);
if (n < 2) return error.VideoTooShort;
const out = try a.alloc(u32, n);
const last: f64 = @floatFromInt(s.frames - 1);
const steps: f64 = @floatFromInt(n - 1);
for (out, 0..) |*o, i| o.* = @intFromFloat(roundEven(if (i == n - 1) last else @as(f64, @floatFromInt(i)) * (last / steps)));
return out;
}

/// The video processor's smart_resize(num_frames, height, width, temporal_factor=2, factor) at `min_px`..`max_px`.
pub fn smartResize(frames: u64, height: u32, width: u32, factor: u32, temporal: u32, min_px: u64, max_px: u64) Error![2]u32 {
if (frames < temporal) return error.VideoTooShort;
const f: f64 = @floatFromInt(factor);
var h: f64 = @floatFromInt(height);
var w: f64 = @floatFromInt(width);
if (h < f or w < f) {
const scale = @max(f / h, f / w);
h = @trunc(h * scale);
w = @trunc(w * scale);
}
if (@max(h, w) / @min(h, w) > 200) return error.VideoTooLarge;
const t: f64 = @floatFromInt(frames);
const tf: f64 = @floatFromInt(temporal);
var hb = roundEven(h / f) * f;
var wb = roundEven(w / f) * f;
const tb = roundEven(t / tf) * tf;
if (tb * hb * wb > @as(f64, @floatFromInt(max_px))) {
const beta = @sqrt(t * h * w / @as(f64, @floatFromInt(max_px)));
hb = @max(f, @floor(h / beta / f) * f);
wb = @max(f, @floor(w / beta / f) * f);
} else if (tb * hb * wb < @as(f64, @floatFromInt(min_px))) {
const beta = @sqrt(@as(f64, @floatFromInt(min_px)) / (t * h * w));
hb = @ceil(h * beta / f) * f;
wb = @ceil(w * beta / f) * f;
}
return .{ @intFromFloat(hb), @intFromFloat(wb) };
}

/// What `s` becomes at most `max_tokens` tokens and `most` sampled frames.
pub fn plan(a: std.mem.Allocator, s: Source, c: Config, max_tokens: u32, most: u32) Error!Plan {
const indices = try sample(a, s, most);
// a pair's token is `temporal` frames of factor x factor pixels: the budget caps the clip's pixels
const per_token: u64 = @as(u64, c.temporal) * c.factor() * c.factor();
const top = @min(c.max_pixels, @as(u64, max_tokens) * per_token);
const size = try smartResize(indices.len, s.height, s.width, c.factor(), c.temporal, @min(c.min_pixels, top), top);
var distinct: std.ArrayList(u32) = .empty;
for (indices) |i| if (distinct.items.len == 0 or distinct.items[distinct.items.len - 1] != i) try distinct.append(a, i);
const times = try a.alloc(f64, (indices.len + 1) / 2);
const r = s.rate();
for (times, 0..) |*t, g| {
const second = indices[@min(2 * g + 1, indices.len - 1)]; // the last index repeated to an even count
t.* = (@as(f64, @floatFromInt(indices[2 * g])) / r + @as(f64, @floatFromInt(second)) / r) / 2;
}
return .{ .indices = indices, .distinct = distinct.items, .times = times, .width = s.width, .height = s.height, .h = size[0], .w = size[1] };
}

/// One pair of frames ready for the tower.
pub const Pair = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 };
pub const Prepared = struct { groups: []Pair, times: []f64 };

/// `s` decoded, resized as it decodes, then normalized and cut into pairs (allocated in `a`).
pub fn prepare(a: std.mem.Allocator, s: Source, c: Config, max_tokens: u32, most: u32) anyerror!Prepared {
const p = try plan(a, s, c, max_tokens, most);
const frames = try a.alloc(u8, p.distinct.len * p.frameBytes());
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
var sink: Sink = .{ .plan = &p, .frames = frames, .scratch = arena.allocator() };
try s.decode(s.ctx, p.distinct, &sink);
if (sink.got != p.distinct.len) return error.BadVideo;
return .{ .groups = try patchify(a, p, frames, c), .times = p.times };
}

/// Each pair's patches in merge order, [channel, frame, y, x], normalized as the fused rescale; an odd last frame repeated.
pub fn patchify(a: std.mem.Allocator, p: Plan, frames: []const u8, c: Config) Error![]Pair {
const P = c.patch;
const M = c.merge;
const gh = p.h / P;
const gw = p.w / P;
const width = c.patchWidth();
var m: [3]f32 = undefined;
var sd: [3]f32 = undefined;
for (0..3) |ch| { // the fast processors' fused rescale and normalize: mean and std over the rescale
m[ch] = @floatCast(@as(f64, c.mean[ch]) / c.rescale);
sd[ch] = @floatCast(@as(f64, c.std[ch]) / c.rescale);
}
const out = try a.alloc(Pair, p.pairs());
for (out, 0..) |*pair, g| {
var slot: [2]usize = undefined; // each of the pair's frames' place among the decoded ones
for (&slot, 0..) |*k, t| k.* = std.mem.indexOfScalar(u32, p.distinct, p.indices[@min(2 * g + t, p.indices.len - 1)]).?;
const px = try a.alloc(f32, @as(usize, gh) * gw * width);
var row: usize = 0;
for (0..gh / M) |wy| for (0..gw / M) |wx| for (0..M) |my| for (0..M) |mx| {
const dst = px[row * width ..][0..width];
for (0..3) |ch| for (0..c.temporal) |t| {
const frame = frames[slot[@min(t, 1)] * p.frameBytes() ..][0..p.frameBytes()];
for (0..P) |dy| for (0..P) |dx| {
const y = (wy * M + my) * P + dy;
const x = (wx * M + mx) * P + dx;
dst[((ch * c.temporal + t) * P + dy) * P + dx] = (@as(f32, @floatFromInt(frame[(y * p.w + x) * 3 + ch])) - m[ch]) / sd[ch];
};
};
row += 1;
};
const id = picture.identity.withGrid(picture.identity.ofBytes(0x9e1d, std.mem.sliceAsBytes(px)), .{ gh, gw });
pair.* = .{ .pixels = px, .gh = gh, .gw = gw, .tokens = gh * gw / (M * M), .hash = id };
}
return out;
}

test "sampling: two frames a second over the clip, at least four, the last frame last" {
const a = std.testing.allocator;
var ctx: u8 = 0;
const decode = struct {
fn f(_: *anyopaque, _: []const u32, _: *Sink) anyerror!void {}
}.f;
const ten: Source = .{ .frames = 300, .rate_num = 30, .rate_den = 1, .width = 64, .height = 64, .ctx = &ctx, .decode = decode };
const s = try sample(a, ten, 768);
defer a.free(s);
try std.testing.expectEqual(@as(usize, 20), s.len);
try std.testing.expectEqual(@as(u32, 0), s[0]);
try std.testing.expectEqual(@as(u32, 299), s[19]);
try std.testing.expectEqual(@as(u32, 16), s[1]); // 15.736 rounds up
const one: Source = .{ .frames = 30, .rate_num = 30, .rate_den = 1, .width = 64, .height = 64, .ctx = &ctx, .decode = decode };
const f = try sample(a, one, 768);
defer a.free(f);
try std.testing.expectEqualSlices(u32, &.{ 0, 10, 19, 29 }, f); // 9.67, 19.33 round to the nearest
}

test "smart_resize keeps the clip's pixels inside the bounds, in multiples of the factor" {
try std.testing.expectEqual([2]u32{ 352, 640 }, try smartResize(20, 360, 640, 32, 2, 65536, 16777216));
const big = try smartResize(20, 1080, 1920, 32, 2, 65536, 16777216); // 20 x 1088 x 1920 is past the bound
try std.testing.expect(20 * @as(u64, big[0]) * big[1] <= 16777216 and big[0] % 32 == 0 and big[1] % 32 == 0);
try std.testing.expectError(error.VideoTooShort, smartResize(1, 64, 64, 32, 2, 1, 1 << 30));
}
8 changes: 7 additions & 1 deletion zig/src/native/flashnext_batch_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, dump: ?[]const
// FLASHNEXT_NO_LONE=1 keeps even lone requests on shared rounds.
if (eng.r.gdn_kept == null and std.c.getenv("FLASHNEXT_NO_LONE") == null) h.host.lone = .{ .ctx = h, .run = loneRun };
if (vis) |v| {
h.host.info_.vision = .{ .ctx = h, .prepare = prepareImage, .image_token = v.c.image_token, .markers = &v.markers, .image_tokens = v.capacity, .max_images = v.max_images };
h.host.info_.vision = images.offer(v, h, prepareImage, prepareVideo);
h.host.images_uncached = true; // the shifted frame (vis_prompt.frame): an image moves the rows before it
}
h.cache = null;
Expand Down Expand Up @@ -159,6 +159,12 @@ fn releaseImages(_: *anyopaque, p: *VisPrompt) void {
p.rows.deinit();
}

/// Info.vision's video prepare: on the HTTP thread.
fn prepareVideo(ctx: *anyopaque, a: std.mem.Allocator, src: api.VideoSource, max_tokens: u32, max_frames: u32) anyerror!api.PreparedVideo {
const h: *Host = @ptrCast(@alignCast(ctx));
return images.prepareVideo(h.vis.?, a, src, max_tokens, max_frames);
}

/// Info.vision's prepare: on the HTTP thread.
fn prepareImage(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage {
const h: *Host = @ptrCast(@alignCast(ctx));
Expand Down
8 changes: 7 additions & 1 deletion zig/src/native/flashnext_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ pub fn openWarmed(gpa: Allocator, io: std.Io, eng: *fx.Engine, window: i64, cach
const context_limit: i64 = tf.flashnext_replay.CAP - fx.MARGIN;
h.* = .{ .gpa = gpa, .io = io, .eng = eng, .follower = follower, .load_limit = limit orelse 0, .vis = vis, .info_ = .{ .name = "flashnext-zig", .prompt_cache_plan = cache_plan, .lanes = 1, .greedy_only = eng.r.tp != null, .context_window = @intCast(if (window > 0) @min(window, context_limit) else context_limit) } };
h.warm = .{ .queue = eng.r.queue };
if (vis) |v| h.info_.vision = .{ .ctx = h, .prepare = prepareImage, .image_token = v.c.image_token, .markers = &v.markers, .image_tokens = v.capacity, .max_images = v.max_images };
if (vis) |v| h.info_.vision = images.offer(v, h, prepareImage, prepareVideo);
// macOS unwires idle GPU memory within seconds: the engine's buffers join one set the idle keepalive's ticks use
if (std.c.getenv("FLASHNEXT_NO_RESIDENCY") == null) holdResident(h) catch |err| std.log.warn("flash next: no residency set ({s}): the first request after an idle second waits for the model's memory", .{@errorName(err)});
errdefer dropResident(h);
Expand Down Expand Up @@ -508,6 +508,12 @@ fn holdResident(h: *Host) !void {
h.eng.snap_pool.follow = r.follow(); // kept states' buffers join it, and leave it before they are freed
}

/// Info.vision's video prepare: on the HTTP thread.
fn prepareVideo(ctx: *anyopaque, a: Allocator, src: api.VideoSource, max_tokens: u32, max_frames: u32) anyerror!api.PreparedVideo {
const h: *Host = @ptrCast(@alignCast(ctx));
return images.prepareVideo(h.vis.?, a, src, max_tokens, max_frames);
}

/// Info.vision's prepare, on the HTTP thread: the tower's patches for an image's bytes.
fn prepareImage(ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage {
const h: *Host = @ptrCast(@alignCast(ctx));
Expand Down
Loading