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
Draw shared Flash Next picks with the upstream GPU sampler
  • Loading branch information
cwschroeder committed Oct 16, 2026
commit 8cee8efddfc08cbf783aecc95a743d143d67010e
2 changes: 1 addition & 1 deletion build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } },
.imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "kernel_sources", .module = engine.import_table.get("kernel_sources").? } },
}) });
b.step("tf-flashnext-batch", "Flash Next shared rounds against fresh legacy replies with prompt admission and cancellation").dependOn(&b.addInstallArtifact(batch, .{}).step);
return exe;
Expand Down
18 changes: 14 additions & 4 deletions docs/recipes/qwen3.8-flash-next.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,20 +95,30 @@ pass.
Additional slots allocate caches for the selected context. Startup reserves their metadata and the prompt-cache
budget, then checks the physical footprint before accepting requests. A fixed slot count that does not fit is
refused; lower the count, context or prompt-cache budget. `--prompt-cache-over-cap` overrides only the prompt-cache
budget. Shared sessions sample: a request with a temperature draws each token on the host from the head's logits
with the server's keyed sampler (top-k, top-p, min-p, a `seed` or one derived from the prompt), so a sampled reply is
the same with drafting on and off and alone or beside other streams. `--parallel 1` still decodes greedily only.
budget. Shared sessions draw sampled tokens with the same GPU sampler as the single-Mac `--parallel 1` path.
Each packed window uses its own seed, sampling settings and absolute token positions. The two-Mac path remains
greedy only. The model gate below must verify sampled token parity across routes, drafting and batch composition.

The shared host's residency set includes the engine, session caches and metadata, shared hidden rows and later
prompt snapshots. Residency stays within 70% of RAM even when the load limit is raised; a refused set leaves the
server running without it. `FLASHNEXT_NO_RESIDENCY=1` disables the set. With a prompt cache, background warm turns
keep the end of a reply as the single-request host does. Idle latency and throughput need fresh measurements.

The checkpoint gate compares shared replies with fresh legacy replies, with drafting off and on, then checks
prompt admission, cancellation, slot reuse and a restored prefix while another request remains active:

```bash
zig build tf-flashnext-batch
zig-out/bin/tf-flashnext-batch --sampling-only
python tools/zig/flashnext_batch_prompts.py MODEL_DIR /tmp/flashnext-prompts
FZ_N=128 zig-out/bin/tf-flashnext-batch MODEL_DIR /tmp/flashnext-prompts/*.json
FZ_SAMPLE=1 FZ_N=128 zig-out/bin/tf-flashnext-batch MODEL_DIR /tmp/flashnext-prompts/*.json
```

Run with one model process on the GPU. For a served comparison with identical requests and settings:
These device gates require exclusive GPU use. `--sampling-only` uses synthetic logits and checks distinct seeds,
positions and row offsets against the shared GPU-rule reference, including untouched greedy and spare rows.
`FZ_SAMPLE=1` repeats the model gate with fixed seeds per prompt. Compilation alone does not pass either gate.
For a served comparison with identical requests and settings:

```bash
zig build native
Expand Down
17 changes: 6 additions & 11 deletions zig/src/families/flashnext/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,10 @@ const Buf = fz.Buf;
const mtl = @import("metal");
const segments = @import("../../core/segments.zig");
const slots = @import("slots.zig");
const sample = @import("host_sample.zig");
const sample = @import("batch_sample.zig");
const think = @import("think.zig");
const batch_costs = @import("batch_costs.zig");

/// Row `row` of a [rows, VOCAB] bf16 logits buffer, drawn with `p` keyed at `position`.
fn drawRow(gpa: std.mem.Allocator, logits: Buf, row: usize, p: lanes.Sampling, position: u64) !u32 {
const bytes = logits.b.contents()[logits.off + row * fz.VOCAB * 2 ..][0 .. fz.VOCAB * 2];
return sample.draw(gpa, @as([*]const u16, @ptrCast(@alignCast(bytes.ptr)))[0..fz.VOCAB], p, position);
}

pub const Backend = struct {
gpa: std.mem.Allocator,
e: *Engine,
Expand Down Expand Up @@ -280,7 +274,7 @@ pub const Backend = struct {
s.first = try fz.Prompt.chunkN(ps[0..call.parts], &s.m, b.gpa, prompt[at..end]);
// Sample before the next forward replaces the last prompt row's logits.
if (end == prompt.len) if (sample.active(stream.sampling)) |p| {
s.first = try drawRow(b.gpa, s.m.t.logits, 0, p, prompt.len);
s.first = try sample.first(b.e, &s.m, p, @intCast(prompt.len));
};
for (ps[0..call.parts], 0..) |p, k| {
const start = at + segments.start(call.rows, call.parts, k);
Expand Down Expand Up @@ -440,12 +434,13 @@ pub const Backend = struct {
const cb = b.e.r.queue.commandBuffer();
b.e.r.enc = cb.compute(.serial);
try forward.encode(b.e, segs[0..windows.len], plan.total, t.ids8);
@memcpy(b.e.draw_at.b.slice(u32, fz.MAXR)[0..plan.total], plan.keys[0..plan.total]);
for (windows, 0..) |w, i| if (sample.active(w.stream.sampling)) |p| {
sample.encode(b.e.r.enc, b.e.r.draw_pipe, t.logits, b.e.draw_at, t.picks, plan.starts[i], w.rows(), p);
};
try b.primary.finish(cb);
Session.copy(b.primary.last, b.hidden, plan.total * fz.WIDE * 2);
for (out, 0..) |o, i| @memcpy(o.sampled, t.picks.b.slice(u32, plan.total)[plan.starts[i]..][0..o.sampled.len]);
for (windows, out, 0..) |w, o, i| if (sample.active(w.stream.sampling)) |p| {
for (o.sampled, w.positions, 0..) |*tok, pos, j| tok.* = try drawRow(b.gpa, t.logits, plan.starts[i] + j, p, pos);
};
b.window_count += 1;
if (windows.len > 1) b.shared_count += 1;
if (std.c.getenv("FZ_BATCH_LOG") != null)
Expand Down
26 changes: 26 additions & 0 deletions zig/src/families/flashnext/batch_sample.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Shared windows use the legacy engine's GPU sampler with each stream's absolute draw positions.
const lanes = @import("lanes");
const mtl = @import("metal");
const fz = @import("replay.zig");
const Engine = @import("engine.zig").Engine;
const sample = @import("sample.zig");

pub fn active(params: ?lanes.Sampling) ?lanes.Sampling {
const p = params orelse return null;
return if (p.temperature > 0) p else null;
}

/// Buffer offsets isolate each window; its positions must be filled before the command buffer is committed.
pub fn encode(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, logits: fz.Buf, positions: fz.Buf, picks: fz.Buf, row: usize, rows: usize, p: lanes.Sampling) void {
sample.draw(enc, pipe, logits.at(row * fz.VOCAB * 2), positions.at(row * 4), picks.at(row * 4), rows, fz.VOCAB, p);
}

/// The last prompt row's pick, before another prompt or draft overwrites its logits.
pub fn first(e: *Engine, model: *fz.Model, p: lanes.Sampling, position: u32) !u32 {
e.draw_at.b.slice(u32, fz.MAXR)[0] = position;
const cb = e.r.queue.commandBuffer();
e.r.enc = cb.compute(.serial);
encode(e.r.enc, e.r.draw_pipe, model.t.logits, e.draw_at, model.t.picks, 0, 1, p);
try model.finish(cb);
return model.t.picks.b.slice(u32, 1)[0];
}
2 changes: 1 addition & 1 deletion zig/src/families/flashnext/host_sample.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Keyed bf16 sampling with bounded top-k or sorted wide candidates, matching the reference draw.
//! Historical bf16 host sampler; shared serving uses batch_sample.zig and the GPU rule.
const std = @import("std");
const lanes = @import("lanes");

Expand Down
1 change: 1 addition & 0 deletions zig/src/tensorfold.zig
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub const nemotron = @import("families/nemotron/nemotron.zig");
pub const flashnext_replay = @import("families/flashnext/replay.zig");
pub const flashnext_rows = @import("families/flashnext/rows_load.zig");
pub const flashnext_sample = @import("families/flashnext/host_sample.zig");
pub const flashnext_batch_sample = @import("families/flashnext/batch_sample.zig");
pub const flashnext_engine = @import("families/flashnext/engine.zig");
pub const flashnext_snapshot = @import("families/flashnext/snapshot.zig");
pub const flashnext_session = @import("families/flashnext/session.zig");
Expand Down
38 changes: 27 additions & 11 deletions zig/tests/flashnext_batch.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Checkpoint gate: shared target rounds against fresh legacy greedy replies, including admission and cancellation.
//! Checkpoint gate: shared target rounds against legacy replies, including seeded draws, admission and cancellation.
const std = @import("std");
const mtl = @import("metal");
const tf = @import("tensorfold");
Expand Down Expand Up @@ -32,11 +32,15 @@ const Reply = struct {
return false;
}
fn marked(_: *anyopaque, _: usize) void {}
fn out(r: *Reply) fx.Out {
return .{ .ctx = r, .prefilled = prefilled, .tokens = emitted, .cancelled = cancelled, .marked = marked };
fn out(r: *Reply, sampling: ?lanes.Sampling) fx.Out {
return .{ .ctx = r, .prefilled = prefilled, .tokens = emitted, .cancelled = cancelled, .marked = marked, .sampling = sampling };
}
};

fn samplingFor(enabled: bool, index: usize) ?lanes.Sampling {
return if (enabled) .{ .seed = 1234 + index, .temperature = 0.7, .top_k = 40, .top_p = 0.9, .min_p = 0.05 } else null;
}

fn prompt(a: std.mem.Allocator, path: []const u8) ![]u32 {
const f = try mtl.MappedFile.open(try std.fmt.allocPrintSentinel(a, "{s}", .{path}, 0));
defer f.deinit();
Expand Down Expand Up @@ -109,9 +113,18 @@ fn draftDepths(a: std.mem.Allocator, back: *Backend, prompts: []const []u32) !vo
pub fn main(init: std.process.Init) !void {
const a = init.arena.allocator();
const args = try init.minimal.args.toSlice(a);
if (args.len < 4) return error.ExpectedModelAndTwoPromptFiles;
const pool = mtl.objc.Pool.push();
defer pool.pop();
if (args.len == 2 and std.mem.eql(u8, args[1], "--sampling-only"))
return @import("flashnext_batch_sample.zig").check(init.gpa);
if (args.len < 4) return error.ExpectedModelAndTwoPromptFiles;
const sampled = if (std.c.getenv("FZ_SAMPLE")) |v| blk: {
const text = std.mem.span(v);
if (std.mem.eql(u8, text, "1")) break :blk true;
if (std.mem.eql(u8, text, "0")) break :blk false;
return error.BadSamplingFlag;
} else false;
std.debug.print("GATE sampled {any}: temperature0.7 top_k40 top_p0.9 min_p0.05 seeds1234+prompt_index\n", .{sampled});
const n: u32 = if (std.c.getenv("FZ_N")) |v| try std.fmt.parseInt(u32, std.mem.span(v), 10) else 32;
if (n < 8) return error.NeedEightReplyTokens;
const count = args.len - 2;
Expand All @@ -125,17 +138,17 @@ pub fn main(init: std.process.Init) !void {
var capacity: usize = 1024;
var baseline_seconds: f64 = 0;
var baseline_mtp_seconds: f64 = 0;
for (args[2..], prompts, refs) |path, *ids, *ref| {
for (args[2..], prompts, refs, 0..) |path, *ids, *ref, i| {
ids.* = try prompt(a, path);
capacity = @max(capacity, ids.len + n + fx.MARGIN);
ref.* = .{ .a = a };
const start = mtl.clock.seconds();
_ = try eng.generateFrom(ids.*, 0, &.{}, n, &.{}, 0, .{}, ref.out());
_ = try eng.generateFrom(ids.*, 0, &.{}, n, &.{}, 0, .{}, ref.out(samplingFor(sampled, i)));
baseline_seconds += mtl.clock.seconds() - start;
if (ref.tokens.items.len != n) return error.ShortBaseline;
var drafted: Reply = .{ .a = a };
const mtp_start = mtl.clock.seconds();
_ = try eng.generateFrom(ids.*, 0, &.{}, n, &.{}, null, .{}, drafted.out());
_ = try eng.generateFrom(ids.*, 0, &.{}, n, &.{}, null, .{}, drafted.out(samplingFor(sampled, i)));
baseline_mtp_seconds += mtl.clock.seconds() - mtp_start;
if (!std.mem.eql(u32, drafted.tokens.items, ref.tokens.items)) return error.LegacyMtpTokenMismatch;
}
Expand Down Expand Up @@ -168,6 +181,7 @@ pub fn main(init: std.process.Init) !void {
.prompt = ids,
.max_new = n,
.drafts = drafts,
.sampling = samplingFor(sampled, i),
});
defer for (streams) |*s| s.deinit(init.gpa);
const start = mtl.clock.seconds();
Expand All @@ -189,11 +203,11 @@ pub fn main(init: std.process.Init) !void {
std.debug.print("PASS drafts {any}: {d} streams, {d} exact tokens, {d} shared forwards, {d:.3}s, legacy serial {d:.3}s\n", .{ drafts, count, count * n, back.shared_count - before, seconds, baseline });
std.debug.print("MEASURE chain {any}: draft calls {d}, waits {d}, draft {d:.6}s, total {d:.6}s\n", .{ mode.chain, back.draft_calls - draft_before, back.draft_waits - waits_before, back.draft_seconds - draft_seconds_before, seconds });
// Admit a third prompt after a shared round, cancel its peer, and reuse the released slot.
var first = try lanes.Stream.init(init.gpa, .{ .id = "survivor", .prompt = prompts[0], .max_new = n, .drafts = drafts });
var first = try lanes.Stream.init(init.gpa, .{ .id = "survivor", .prompt = prompts[0], .max_new = n, .drafts = drafts, .sampling = samplingFor(sampled, 0) });
defer first.deinit(init.gpa);
var cancelled = try lanes.Stream.init(init.gpa, .{ .id = "cancelled", .prompt = prompts[1], .max_new = n, .drafts = drafts });
var cancelled = try lanes.Stream.init(init.gpa, .{ .id = "cancelled", .prompt = prompts[1], .max_new = n, .drafts = drafts, .sampling = samplingFor(sampled, 1) });
defer cancelled.deinit(init.gpa);
var admitted = try lanes.Stream.init(init.gpa, .{ .id = "admitted", .prompt = prompts[1], .max_new = n, .drafts = drafts });
var admitted = try lanes.Stream.init(init.gpa, .{ .id = "admitted", .prompt = prompts[1], .max_new = n, .drafts = drafts, .sampling = samplingFor(sampled, 1) });
defer admitted.deinit(init.gpa);
try core.addStream(&first);
try core.addStream(&cancelled);
Expand All @@ -212,20 +226,22 @@ pub fn main(init: std.process.Init) !void {
.prompt = prompts[longest],
.max_new = 1,
.drafts = drafts,
.sampling = samplingFor(sampled, longest),
.reuse = .{ .marks = &marks, .hook = .{ .ptr = &mark, .at = Mark.at } },
});
defer primer.deinit(init.gpa);
try core.addStream(&primer);
if (mark.err) |err| return err;
const saved = mark.saved orelse return error.NoSnapshot;
defer Backend.snapDrop(&back, saved);
var peer = try lanes.Stream.init(init.gpa, .{ .id = "cache-peer", .prompt = prompts[0], .max_new = n, .drafts = drafts });
var peer = try lanes.Stream.init(init.gpa, .{ .id = "cache-peer", .prompt = prompts[0], .max_new = n, .drafts = drafts, .sampling = samplingFor(sampled, 0) });
defer peer.deinit(init.gpa);
var resumed = try lanes.Stream.init(init.gpa, .{
.id = "cache-resumed",
.prompt = prompts[longest],
.max_new = n,
.drafts = drafts,
.sampling = samplingFor(sampled, longest),
.reuse = .{ .saved = saved, .at = marks[0] },
});
defer resumed.deinit(init.gpa);
Expand Down
70 changes: 70 additions & 0 deletions zig/tests/flashnext_batch_sample.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! A device gate for sampled windows with distinct seeds and positions, with untouched greedy and spare rows.
const std = @import("std");
const mtl = @import("metal");
const tf = @import("tensorfold");
const fz = tf.flashnext_replay;
const sample = tf.flashnext_batch_sample;

pub fn check(a: std.mem.Allocator) !void {
const dev = try mtl.Device.init();
defer dev.deinit();
const lib = try mtl.Library.fromSource(dev, @import("kernel_sources").nemotron_sample, mtl.CompileOptions.mlx());
defer lib.deinit();
const pipe = try mtl.Pipeline.init(dev, lib, "tf_sample_full", false);
defer pipe.deinit();
const q = try dev.queue();
defer q.deinit();
const logits = try dev.buffer(fz.MAXR * fz.VOCAB * 2, fz.opts);
defer logits.deinit();
const positions = try dev.buffer(fz.MAXR * 4, fz.opts);
defer positions.deinit();
const picks = try dev.buffer(fz.MAXR * 4, fz.opts);
defer picks.deinit();
const plan = try tf.flashnext_batch_meta.Plan.init(&.{
.{ .slot = 3, .pos = 19, .rows = 3 },
.{ .slot = 0, .pos = 2047, .rows = 2 },
.{ .slot = 5, .pos = 9000, .rows = 1 },
}, 10000);
const expected_positions = [_]u32{ 20, 21, 22, 2048, 2049, 9001 };
const settings = [_]?tf.lanes.Sampling{
.{ .seed = 1, .temperature = 0.7, .top_k = 20, .top_p = 0.95 },
null,
.{ .seed = 1 << 63 | 4, .temperature = 1.3, .top_k = 0, .top_p = 0.8, .min_p = 0.05 },
};
var rng = std.Random.DefaultPrng.init(11);
const random = rng.random();
for (logits.slice(u16, fz.MAXR * fz.VOCAB)) |*word| {
const x: f32 = random.floatNorm(f32) * 2;
const bits: u32 = @bitCast(x);
word.* = @truncate((bits + 0x7FFF + ((bits >> 16) & 1)) >> 16);
}
const sentinel = 0xDEAD_BEEF;
@memset(picks.slice(u32, fz.MAXR), sentinel);
@memset(positions.slice(u32, fz.MAXR), sentinel);
@memcpy(positions.slice(u32, fz.MAXR)[0..plan.total], plan.keys[0..plan.total]);
const cb = q.commandBuffer();
const enc = cb.compute(.serial);
for (settings, 0..) |setting, i| if (setting) |p| {
const start = plan.starts[i];
const end = if (i + 1 < settings.len) plan.starts[i + 1] else plan.total;
sample.encode(enc, pipe, .{ .b = logits }, .{ .b = positions }, .{ .b = picks }, start, end - start, p);
};
enc.end();
cb.commit();
cb.wait();
if (cb.failure() != null) return error.SampleCommandFailed;
const row = try a.alloc(f32, fz.VOCAB);
defer a.free(row);
for (0..fz.MAXR) |r| {
const setting: ?tf.lanes.Sampling = if (r < 3) settings[0] else if (r == 5) settings[2] else null;
const expected = if (setting) |p| blk: {
for (row, logits.slice(u16, fz.MAXR * fz.VOCAB)[r * fz.VOCAB ..][0..fz.VOCAB]) |*x, w|
x.* = @bitCast(@as(u32, w) << 16);
break :blk try tf.lanes.gpu_full.sample(a, row, p, expected_positions[r], null);
} else sentinel;
if (picks.slice(u32, fz.MAXR)[r] != expected) return error.PackedSampleMismatch;
if (positions.slice(u32, fz.MAXR)[r] != (if (r < plan.total) expected_positions[r] else sentinel))
return error.DrawPositionsOverwritten;
}
std.debug.print("PASS GPU sampling: two seeds, unequal positions, packed windows and untouched greedy/spare rows\n", .{});
}
Loading