Skip to content

Commit 1874ffe

Browse files
committed
Flash Next shared sessions sample: a request's temperature draws each token on the host from the head's logits
The first token from the prompt pass's last row, each verify row from the window's logits, with the lane core's keyed sampler (top-k in one pass over bf16 keys, equal to qwen3_5's draw; families/flashnext/sample.zig, the same file as ashhart#719). Sampled replies are the same drafted and undrafted, alone and beside other streams; greedy replies are unchanged.
1 parent 77ebc3f commit 1874ffe

6 files changed

Lines changed: 133 additions & 4 deletions

File tree

‎docs/recipes/qwen3.8-flash-next.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ New requests join between rounds, and cancelling a request releases its slot for
7777
Additional slots allocate caches for the selected context. Startup reserves their metadata and the prompt-cache
7878
budget, then checks the physical footprint before accepting requests. A fixed slot count that does not fit is
7979
refused; lower the count, context or prompt-cache budget. `--prompt-cache-over-cap` overrides only the prompt-cache
80-
budget. Greedy decoding remains required, so clients must send temperature 0.
80+
budget. Shared sessions sample: a request with a temperature draws each token on the host from the head's logits
81+
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
82+
the same with drafting on and off and alone or beside other streams. `--parallel 1` still decodes greedily only.
8183

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

‎zig/flashnext_host.zig‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@
22
test {
33
_ = @import("src/families/flashnext/host_test.zig");
44
_ = @import("src/families/flashnext/pack.zig");
5+
_ = @import("src/families/flashnext/sample.zig");
56
_ = @import("src/families/flashnext/batch_meta_test.zig");
67
}

‎zig/src/families/flashnext/backend.zig‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,19 @@ const Stream = lanes.Stream;
1212
const Buf = fz.Buf;
1313
const mtl = @import("metal");
1414
const segments = @import("../../core/segments.zig");
15+
const sample = @import("sample.zig");
16+
17+
/// A stream's sampling when it samples (a temperature above 0); null: the GPU's argmax stands.
18+
fn sampling(stream: *const Stream) ?lanes.Sampling {
19+
const p = stream.sampling orelse return null;
20+
return if (p.temperature > 0) p else null;
21+
}
22+
23+
/// Row `row` of a [rows, VOCAB] bf16 logits buffer, drawn with `p` keyed at `position`.
24+
fn drawRow(gpa: std.mem.Allocator, logits: Buf, row: usize, p: lanes.Sampling, position: u64) !u32 {
25+
const bytes = logits.b.contents()[logits.off + row * fz.VOCAB * 2 ..][0 .. fz.VOCAB * 2];
26+
return sample.draw(gpa, @as([*]const u16, @ptrCast(@alignCast(bytes.ptr)))[0..fz.VOCAB], p, position);
27+
}
1528

1629
pub const Backend = struct {
1730
gpa: std.mem.Allocator,
@@ -120,7 +133,6 @@ pub const Backend = struct {
120133
const pool = mtl.objc.Pool.push();
121134
defer pool.pop();
122135
const b = self(ptr);
123-
if (stream.sampling) |p| if (p.temperature > 0) return error.GreedyOnly;
124136
const prompt = stream.prompt();
125137
if (prompt.len == 0) return error.EmptyPrompt;
126138
try b.settle();
@@ -162,6 +174,10 @@ pub const Backend = struct {
162174
end = at + call.rows;
163175
const ps = [2]*fz.Prompt{ b.e.pr, b.e.pr2 };
164176
s.first = try fz.Prompt.chunkN(ps[0..call.parts], &s.m, b.gpa, prompt[at..end]);
177+
// the pass's last row's logits are in the model's head buffer until the next forward: a sampled first token now
178+
if (end == prompt.len) if (sampling(stream)) |p| {
179+
s.first = try drawRow(b.gpa, s.m.t.logits, 0, p, prompt.len);
180+
};
165181
for (ps[0..call.parts], 0..) |p, k| {
166182
const start = at + segments.start(call.rows, call.parts, k);
167183
const rows = segments.rows(call.rows, call.parts, k);
@@ -243,6 +259,9 @@ pub const Backend = struct {
243259
try b.primary.finish(cb);
244260
Session.copy(b.primary.last, b.hidden, plan.total * fz.WIDE * 2);
245261
for (out, 0..) |o, i| @memcpy(o.sampled, t.picks.b.slice(u32, plan.total)[plan.starts[i]..][0..o.sampled.len]);
262+
for (windows, out, 0..) |w, o, i| if (sampling(w.stream)) |p| {
263+
for (o.sampled, w.positions, 0..) |*tok, pos, j| tok.* = try drawRow(b.gpa, t.logits, plan.starts[i] + j, p, pos);
264+
};
246265
b.window_count += 1;
247266
if (windows.len > 1) b.shared_count += 1;
248267
if (std.c.getenv("FZ_BATCH_LOG") != null)
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
//! The keyed host sampler over a bf16 logits row, in one pass: the top-k candidates by an order-preserving integer key
2+
//! of each bf16 word, then lanes.sampling.choose. The candidates, their order and the draw equal `reference`, which is
3+
//! qwen3_5/backend.zig's draw without its mask (two passes in f64), kept here for wide top-k and the tests.
4+
const std = @import("std");
5+
const lanes = @import("lanes");
6+
7+
/// k at most this takes the one-pass path; a wider (or unlimited) top-k takes the reference's.
8+
pub const MAX_K = 256;
9+
10+
/// A bf16 word's order as an unsigned key: larger floats give larger keys, -0 and +0 the same.
11+
fn key(word: u16) u16 {
12+
const w = if (word == 0x8000) 0 else word;
13+
return if (w & 0x8000 != 0) ~w else w | 0x8000;
14+
}
15+
16+
fn value(word: u16) f64 {
17+
return @as(f32, @bitCast(@as(u32, word) << 16));
18+
}
19+
20+
/// qwen3_5/backend.zig's draw without a mask: the unchanged top-k candidates for the keyed sampler.
21+
pub fn reference(gpa: std.mem.Allocator, logits: []const u16, p: lanes.Sampling, position: u64) !u32 {
22+
var best: ?usize = null;
23+
for (logits, 0..) |word, id| {
24+
const x = value(word);
25+
if (!std.math.isFinite(x)) return error.NonfiniteQwenLogits;
26+
if (best == null or x > value(logits[best.?])) best = id;
27+
}
28+
if (p.temperature <= 0) return @intCast(best.?);
29+
const allowed = logits.len;
30+
const k = if (p.top_k == 0) allowed else @min(allowed, p.top_k);
31+
const values = try gpa.alloc(f64, k);
32+
defer gpa.free(values);
33+
const ids = try gpa.alloc(u64, k);
34+
defer gpa.free(ids);
35+
var filled: usize = 0;
36+
for (logits, 0..) |word, id| {
37+
const x = value(word);
38+
if (k == allowed) {
39+
values[filled] = x;
40+
ids[filled] = id;
41+
filled += 1;
42+
continue;
43+
}
44+
if (filled == k and x <= values[k - 1]) continue;
45+
var at = @min(filled, k - 1);
46+
while (at > 0 and x > values[at - 1]) : (at -= 1) {
47+
values[at] = values[at - 1];
48+
ids[at] = ids[at - 1];
49+
}
50+
values[at] = x;
51+
ids[at] = id;
52+
filled = @min(filled + 1, k);
53+
}
54+
return @intCast(try lanes.sampling.choose(gpa, values, ids, position, p));
55+
}
56+
57+
/// Row `row` of a [rows, vocab] bf16 logits buffer whose bytes start at `base`.
58+
pub fn row(base: [*]const u8, vocab: usize, at: usize) []const u16 {
59+
return @as([*]const u16, @ptrCast(@alignCast(base + at * vocab * 2)))[0..vocab];
60+
}
61+
62+
/// The draw for `logits` with `p` keyed at `position` (p.temperature above 0).
63+
pub fn draw(gpa: std.mem.Allocator, logits: []const u16, p: lanes.Sampling, position: u64) !u32 {
64+
const k: usize = p.top_k;
65+
if (k == 0 or k > MAX_K or k >= logits.len) return reference(gpa, logits, p, position);
66+
var keys: [MAX_K]u16 = undefined;
67+
var ids: [MAX_K]u64 = undefined;
68+
var filled: usize = 0;
69+
for (logits, 0..) |word, id| {
70+
if (word & 0x7f80 == 0x7f80) return error.NonfiniteQwenLogits; // exponent all ones: inf or nan
71+
const x = key(word);
72+
if (filled == k and x <= keys[k - 1]) continue;
73+
var at = @min(filled, k - 1);
74+
while (at > 0 and x > keys[at - 1]) : (at -= 1) {
75+
keys[at] = keys[at - 1];
76+
ids[at] = ids[at - 1];
77+
}
78+
keys[at] = x;
79+
ids[at] = id;
80+
filled = @min(filled + 1, k);
81+
}
82+
var values: [MAX_K]f64 = undefined;
83+
for (ids[0..filled], values[0..filled]) |id, *v| v.* = value(logits[id]);
84+
return @intCast(try lanes.sampling.choose(gpa, values[0..filled], ids[0..filled], position, p));
85+
}
86+
87+
test "the one-pass draw equals the reference on random rows with ties, signed zeros and every top-k" {
88+
const gpa = std.testing.allocator;
89+
var rng = std.Random.DefaultPrng.init(7);
90+
const r = rng.random();
91+
const words = try gpa.alloc(u16, 4096);
92+
defer gpa.free(words);
93+
for (0..40) |trial| {
94+
for (words) |*w| {
95+
const f: f32 = @floatCast(r.floatNorm(f64) * 3.0);
96+
w.* = @intCast(@as(u32, @bitCast(f)) >> 16);
97+
}
98+
for (0..64) |j| words[r.uintLessThan(usize, words.len)] = words[j]; // ties
99+
words[r.uintLessThan(usize, words.len)] = 0x8000;
100+
words[r.uintLessThan(usize, words.len)] = 0;
101+
for ([_]u32{ 1, 2, 20, 64, 256 }) |k| for ([_]f64{ 0.6, 1.0, 1.5 }) |t| {
102+
const p: lanes.Sampling = .{ .seed = trial * 31 + k, .temperature = t, .top_k = k, .top_p = 0.95 };
103+
const pos: u64 = trial * 7 + k;
104+
try std.testing.expectEqual(try reference(gpa, words, p, pos), try draw(gpa, words, p, pos));
105+
};
106+
}
107+
}

‎zig/src/native/flashnext_batch_host.zig‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, dump: ?[]const
5454
errdefer h.core.deinit();
5555
const plan = try fit.budget(cache_gib, over, 0, a, why, "");
5656
eng.snap_pool.max = plan.budget_bytes;
57-
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "flashnext-zig", .lanes = slots, .greedy_only = true, .context_window = @intCast(window), .prefill_step = @intCast(eng.pr.step), .prompt_cache_plan = plan });
57+
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 });
5858
h.cache = null;
5959
if (plan.budget_bytes > 0) {
6060
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);
@@ -72,7 +72,6 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, dump: ?[]const
7272

7373
fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 {
7474
return switch (err) {
75-
error.GreedyOnly => "the native Flash Next engine decodes greedily only: send temperature 0",
7675
error.ContextFull => "the prompt and max_tokens do not fit this server's --context",
7776
else => null,
7877
};

‎zig/src/tensorfold.zig‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ pub const segments = @import("core/segments.zig");
1515
pub const row_projection = @import("core/row_projection.zig");
1616
pub const nemotron = @import("families/nemotron/nemotron.zig");
1717
pub const flashnext_replay = @import("families/flashnext/replay.zig");
18+
pub const flashnext_sample = @import("families/flashnext/sample.zig");
1819
pub const flashnext_engine = @import("families/flashnext/engine.zig");
1920
pub const flashnext_snapshot = @import("families/flashnext/snapshot.zig");
2021
pub const flashnext_session = @import("families/flashnext/session.zig");

0 commit comments

Comments
 (0)