Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
qwen27 CUDA: the scratch sized by --parallel; prompt chunk rows and a…
… host token table by env

The server sized the scratch for 16 streams of 16 rows at any --parallel, and the attention partials in it grow
with the window: on a 24 GB card no 32K stream fit beside it. The scratch now takes `streams` windows (the lane
core's admission and the cost curve follow), so --parallel 1 needs one stream's rows.

- TF_QWEN27_PROMPT_ROWS: a prompt chunk's rows (default 4096; 1024 frees ~1 GiB at a ~10% slower prompt).
- TF_QWEN27_HOST_EMBED=1: the token table in mapped host memory (0.67 GiB; only prompt rows read it).
  • Loading branch information
CanadaApollo6 committed Oct 13, 2026
commit c78ecb499ec114710f34cc769edfc430cfec4451
5 changes: 3 additions & 2 deletions zig/src/cli/qwen27_cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ pub fn main(init: std.process.Init) !u8 {
defer ctx.deinit();
const clock = std.Io.Clock.awake;
var t0 = clock.now(init.io).toNanoseconds();
const e = try qwen.Engine.init(gpa, init.io, &ctx, o.model, o.kernels, .{ .context = o.context });
const rows_env = if (std.c.getenv("TF_QWEN27_PROMPT_ROWS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch return error.BadPromptRows else qwen.engine.prompt_rows;
const e = try qwen.Engine.init(gpa, init.io, &ctx, o.model, o.kernels, .{ .context = o.context, .prompt_rows = rows_env });
defer e.deinit();
std.debug.print("loaded in {d:.1}s, weights {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(init.io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(e.w.bytes())) / (1 << 30) });
if (windows) return checkWindows(gpa, arena, init.io, e, prompts, o.dump, o.cases);
Expand Down Expand Up @@ -435,7 +436,7 @@ fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.E
m.accepted += len - 1;
}
try f.commit(parts[0..n], paths[0..n]);
try qwen.drafts.absorb(d, f.ops, e.scratch.taps, e.scratch.copy_items, kept[0..n]);
try qwen.drafts.absorb(d, f.ops, e.scratch.taps, e.scratch.window_rows, e.scratch.copy_items, kept[0..n]);
for (live[0..n]) |k| {
const m = &ms[k];
if (m.out.items.len >= count or e.w.isEos(m.out.items[m.out.items.len - 1])) m.done = true;
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/qwen27/cuda/drafts.zig
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,12 @@ pub fn propose(d: *dr.DFlash2, asks: []const Ask) !void {
pub const Kept = struct { x: *Stream, rows: []const u32 };

/// add_taps_streams: every stream's kept rows' taps gathered after the round's rows, then absorbed in one batch.
pub fn absorb(d: *dr.DFlash2, ops: kern.Ops, taps: u64, copy_items: u64, kept: []const Kept) !void {
pub fn absorb(d: *dr.DFlash2, ops: kern.Ops, taps: u64, round_rows: usize, copy_items: u64, kept: []const Kept) !void {
var items: std.ArrayList(kern.Copy) = .empty;
defer items.deinit(d.gpa);
var absorbs: [st.max_streams]dr.Absorb = undefined;
const row = taps_width * bf;
const gathered = taps + st.round_rows * row;
const gathered = taps + round_rows * row; // after the round's rows
for (kept, 0..) |k, j| {
for (k.rows) |r| try items.append(d.gpa, .{ .dst = gathered + items.items.len * row, .src = taps + r * row, .bytes = row });
absorbs[j] = .{ .ctx = &k.x.ctx, .rows = k.rows.len };
Expand Down
12 changes: 8 additions & 4 deletions zig/src/families/qwen27/cuda/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize {
return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n };
}

pub const Options = struct { context: usize };
/// `streams`: a shared round's windows at most (the scratch's window rows follow); `prompt_rows`: a prompt chunk's rows.
pub const Options = struct { context: usize, streams: usize = st.max_streams, prompt_rows: usize = prompt_rows };

pub const Engine = struct {
gpa: std.mem.Allocator,
Expand All @@ -29,6 +30,7 @@ pub const Engine = struct {
w: wts.Weights,
scratch: st.Scratch,
context: usize,
prompt_rows: usize,

pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine {
const cfg = try c.Config.read(gpa, io, dir);
Expand All @@ -38,13 +40,15 @@ pub const Engine = struct {
e.gpa = gpa;
e.ctx = ctx;
e.context = o.context;
if (o.prompt_rows < 1) return error.BadPromptRows;
e.prompt_rows = o.prompt_rows;
e.s = try cuda.Stream.init(ctx.d, true);
errdefer e.s.deinit();
e.k = try kern.Kernels.load(gpa, io, ctx, kernels, g.linear_v_heads);
errdefer e.k.deinit();
e.w = try wts.load(gpa, io, e.ops(), dir, cfg);
errdefer e.w.deinit();
e.scratch = try st.Scratch.init(gpa, ctx.d, g, prompt_rows, o.context);
e.scratch = try st.Scratch.init(gpa, ctx.d, g, o.prompt_rows, o.context, o.streams);
errdefer e.scratch.deinit();
try e.s.synchronize();
return e;
Expand Down Expand Up @@ -77,9 +81,9 @@ pub const Engine = struct {
if (prompt.len >= seq.capacity) return error.PromptTooLong;
try seq.reset(e.ops(), e.w.g);
var f = e.forward();
const n = (prompt.len + prompt_rows - 1) / prompt_rows;
const n = (prompt.len + e.prompt_rows - 1) / e.prompt_rows;
for (0..n) |j| {
const b = chunkBounds(0, prompt.len, prompt_rows, j);
const b = chunkBounds(0, prompt.len, e.prompt_rows, j);
try f.chunk(prompt[b[0]..b[1]], seq, j == n - 1);
}
}
Expand Down
8 changes: 4 additions & 4 deletions zig/src/families/qwen27/cuda/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ pub const Forward = struct {
const g_ = f.g();
const w = f.w;
const S = pieces.len;
if (S == 0 or S > st.max_streams) return error.InvalidQwenWindows;
if (S == 0 or S > s.streams()) return error.InvalidQwenWindows;
var starts: [st.max_streams + 1]usize = undefined;
starts[0] = 0;
for (pieces, 0..) |p, k| {
Expand Down Expand Up @@ -329,7 +329,7 @@ pub const Forward = struct {
defer items.deinit(f.gpa);
var lin_n: usize = 0;
for (0..g_.layers) |i| if (c.linear(i)) {
const cat = s.conv_cat + lin_n * st.max_streams * keep * row;
const cat = s.conv_cat + lin_n * s.streams() * keep * row;
for (pieces, 0..) |p, k| try items.append(f.gpa, .{ .dst = cat + k * keep * row, .src = p.seq.conv[i], .bytes = keep * row });
lin_n += 1;
};
Expand All @@ -340,7 +340,7 @@ pub const Forward = struct {
at_layer[i] = items.items.len;
if (c.linear(i)) {
// the last `keep` rows of [kept rows; the stream's prompt rows]
const cat = s.conv_cat + lin_n * st.max_streams * keep * row;
const cat = s.conv_cat + lin_n * s.streams() * keep * row;
for (pieces, 0..) |p, k| {
const n = p.ids.len;
const o = starts[k];
Expand Down Expand Up @@ -378,7 +378,7 @@ pub const Forward = struct {
try f.ops.prefillDense(s.y, d.z, s.z, W);
try f.ops.prefillDense(s.y, d.b, s.b, W);
try f.ops.prefillDense(s.y, d.a, s.a, W);
const cat = s.conv_cat + lin_n * st.max_streams * keep * row;
const cat = s.conv_cat + lin_n * s.streams() * keep * row;
try f.t.gdnPre(s.qkv, cat, d.conv, s.windows, s.sids, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape());
for (pieces, 0..) |p, k| {
const o = starts[k];
Expand Down
9 changes: 4 additions & 5 deletions zig/src/families/qwen27/cuda/lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const st = @import("state.zig");
const Engine = @import("engine.zig").Engine;
const Part = @import("forward.zig").Part;
const Forward = @import("forward.zig").Forward;
const prompt_rows = @import("engine.zig").prompt_rows;
const dl = @import("draft_load.zig");
const dr = @import("draft.zig");
const drafts = @import("drafts.zig");
Expand Down Expand Up @@ -78,7 +77,7 @@ pub const Cuda = struct {

/// The facts the round loop reads: 16-row windows in one forward; with DFlash2, host trees with node chances.
pub fn facts(x: *const Cuda) lanes.Model {
var m: lanes.Model = .{ .exact_width = st.max_rows, .hidden_rows = true, .batch_rows = st.round_rows, .max_streams = @min(x.streams, st.max_streams), .streams_exact = true };
var m: lanes.Model = .{ .exact_width = st.max_rows, .hidden_rows = true, .batch_rows = @intCast(x.e.scratch.window_rows), .max_streams = @intCast(@min(x.streams, x.e.scratch.window_rows / st.max_rows)), .streams_exact = true };
if (x.drafter != null) {
m.mtp = true;
m.speculate = true;
Expand Down Expand Up @@ -248,14 +247,14 @@ pub const Cuda = struct {
continue;
};
const ids = s.prompt();
if (ids.len > prompt_rows) {
if (ids.len > x.e.prompt_rows) {
x.prefillOpened(s, seq) catch |e| {
x.dropSeq(s);
err.* = e;
};
continue;
}
if (n == st.max_streams or rows + ids.len > prompt_rows) {
if (n == x.e.scratch.streams() or rows + ids.len > x.e.prompt_rows) {
x.pass(streams, errs, pieces[0..n], which[0..n]);
n = 0;
rows = 0;
Expand Down Expand Up @@ -471,7 +470,7 @@ pub const Cuda = struct {
na += 1;
}
const f = x.e.forward();
try drafts.absorb(d, f.ops, x.e.scratch.taps, x.e.scratch.copy_items, kept[0..nk]);
try drafts.absorb(d, f.ops, x.e.scratch.taps, x.e.scratch.window_rows, x.e.scratch.copy_items, kept[0..nk]);
try drafts.propose(d, asks[0..na]);
}

Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/qwen27/cuda/lone.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub fn prefill(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, promp
ctx.skip(tap_from);
var f = e.forward();
f.taps = e.scratch.taps;
const rows = @import("engine.zig").prompt_rows;
const rows = e.prompt_rows;
const chunks = (prompt.len + rows - 1) / rows;
for (0..chunks) |j| {
const b = @import("engine.zig").chunkBounds(0, prompt.len, rows, j);
Expand Down
15 changes: 10 additions & 5 deletions zig/src/families/qwen27/cuda/native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ pub const model_type = "qwen3_5";
pub const formats: []const []const u8 = &.{"mlx-q4g64"};
pub const default_context: i64 = 32768;
pub const max_segments: u32 = 1;
pub const prompt_rows: u32 = engine.prompt_rows;
/// A prompt chunk's rows: TF_QWEN27_PROMPT_ROWS, else engine.prompt_rows (set when the server opens the model).
pub var prompt_rows: u32 = engine.prompt_rows;

pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null };
/// `streams`: --parallel, the shared round's windows at most (the scratch is sized for them).
pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, streams: u32 = most_streams };

/// A lone drafted stream's own driver (none here: one stream decodes in the lane core too, as under --parallel).
pub const LoneRun = *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: *anyopaque, committed: *const fn (*anyopaque) void, yield: *const fn (*anyopaque) bool) anyerror!bool;
Expand Down Expand Up @@ -67,11 +69,14 @@ const most_streams = 32;

pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded {
// the 27B's glue runs the Python engine's Triton kernels, captured on this chip (no own glue kernels yet)
const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context });
const streams: u32 = @max(1, @min(o.streams, st.max_streams));
if (getenv("TF_QWEN27_PROMPT_ROWS")) |v| prompt_rows = std.fmt.parseInt(u32, v, 10) catch return error.BadPromptRows;
if (prompt_rows < 16) return error.BadPromptRows;
const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context, .streams = streams, .prompt_rows = prompt_rows });
errdefer e.deinit();
const own = try gpa.create(Owned);
errdefer gpa.destroy(own);
own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, most_streams) };
own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, streams) };
errdefer own.lanes.deinit();
if (o.drafts) if (try drafterDir(gpa, io, o.drafter)) |draft_dir| {
defer gpa.free(draft_dir);
Expand All @@ -80,7 +85,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [
own.lanes.drafter = own.draft;
std.log.info("DFlash2 drafts every stream: {s}", .{draft_dir});
// the forward's ms by rows: a shared round's tree widths follow the curve
try own.lanes.calibrate(io, most_streams);
try own.lanes.calibrate(io, streams);
};
return .{
.backend = own.lanes.backend(),
Expand Down
8 changes: 4 additions & 4 deletions zig/src/families/qwen27/cuda/round.zig
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub const Round = struct {
/// The conv rows gdn_pre reads for layer `i` (its DeltaNet index `j`): the stream's own, or the stacked copy.
pub fn conv(r: *const Round, parts: []const Part, s: *const st.Scratch, g: c.Geometry, i: usize, j: usize) u64 {
if (!r.multi) return parts[0].seq.conv[i];
return s.conv_cat + j * st.max_streams * (c.conv_taps - 1) * g.convDim() * bf;
return s.conv_cat + j * s.streams() * (c.conv_taps - 1) * g.convDim() * bf;
}

/// Layer `i`'s attention cache offsets: tree_forward's (one stream, by layer) or the packed (layer, streams) rows.
Expand Down Expand Up @@ -117,7 +117,7 @@ fn plans(gpa: std.mem.Allocator, parts: []const Part, starts: []const usize, mul

/// Uploads the round's inputs and runs attention's _paths; the caller's layer loop reads the returned Round.
pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, g: c.Geometry, parts: []const Part) !Round {
if (parts.len == 0 or parts.len > st.max_streams) return error.InvalidQwenWindows;
if (parts.len == 0 or parts.len > s.streams()) return error.InvalidQwenWindows;
var W: usize = 0;
var r: Round = undefined;
r.starts_host[0] = 0;
Expand All @@ -128,7 +128,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch,
W += p.tokens.len;
r.starts_host[k + 1] = W;
}
if (W > st.round_rows) return error.WindowTooWide;
if (W > s.window_rows) return error.WindowTooWide;
r.rows = W;
r.streams = parts.len;
r.multi = parts.len > 1;
Expand Down Expand Up @@ -222,7 +222,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch,
for (parts) |p| try offs.appendSlice(gpa, &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) });
continue;
}
const cat = s.conv_cat + j * st.max_streams * keep * g.convDim() * bf;
const cat = s.conv_cat + j * s.streams() * keep * g.convDim() * bf;
for (parts, 0..) |p, k| {
try ptrs.append(gpa, p.seq.rec[i]);
try stack.append(gpa, .{ .dst = cat + k * keep * g.convDim() * bf, .src = p.seq.conv[i], .bytes = keep * g.convDim() * bf });
Expand Down
22 changes: 15 additions & 7 deletions zig/src/families/qwen27/cuda/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ pub const AttnRecord = struct { k: u64, v: u64 };
pub const Scratch = struct {
arena: Arena,
rows: usize,
window_rows: usize, // a shared round's rows at most: max_rows a stream
// the residual stream and the normed rows with their group sums
x: u64,
h: u64,
Expand Down Expand Up @@ -192,9 +193,11 @@ pub const Scratch = struct {
attn_records: []AttnRecord, // by layer: the round's rotated keys and values
gpa: std.mem.Allocator,

/// Scratch for prompt chunks of `prompt_rows` and windows of `max_rows`, over caches of `capacity` positions.
pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, g: c.Geometry, prompt_rows: usize, capacity: usize) !Scratch {
/// Scratch for prompt chunks of `prompt_rows` and rounds of `streams` windows of `max_rows`, over caches of `capacity` positions.
pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, g: c.Geometry, prompt_rows: usize, capacity: usize, stream_count: usize) !Scratch {
if (stream_count < 1 or stream_count > max_streams) return error.BadStreams;
var s: Scratch = undefined;
s.window_rows = max_rows * stream_count;
s.gpa = gpa;
s.records = try gpa.alloc(GdnRecord, g.layers);
errdefer gpa.free(s.records);
Expand All @@ -208,9 +211,14 @@ pub const Scratch = struct {
return s;
}

/// The streams a shared round or batched prompt may hold.
pub fn streams(s: *const Scratch) usize {
return s.window_rows / max_rows;
}

fn layout(s: *Scratch, g: c.Geometry, prompt_rows: usize, capacity: usize) !void {
const R = @max(prompt_rows, round_rows);
const W = round_rows;
const W = s.window_rows;
const R = @max(prompt_rows, W);
const bf = 2;
const chunks = (capacity + W + tri.chunk - 1) / tri.chunk;
// attention.plan_host: a query tile's items per committed chunk and folded group
Expand Down Expand Up @@ -271,14 +279,14 @@ pub const Scratch = struct {
s.part_m = try A.take(chunks * W * g.query_heads * 4);
s.part_l = try A.take(chunks * W * g.query_heads * 4);
s.conv_tmp = try A.take((c.conv_taps - 1 + R) * g.convDim() * bf);
s.conv_old = try A.take(max_streams * g.layers * (c.conv_taps - 1) * g.convDim() * bf);
s.conv_old = try A.take(s.streams() * g.layers * (c.conv_taps - 1) * g.convDim() * bf);
s.copy_items = try A.take(2 * copy_items * @sizeOf(kern.Copy));
s.taps = try A.take(R * 5 * g.hidden * bf);
s.taps = try A.take(@max(R, 2 * W) * 5 * g.hidden * bf); // a round's rows, then its kept rows gathered
s.replay_table = try A.take(g.layers * (4 + max_streams) * 8);
s.replay_rows = try A.take(max_streams * (W + 1) * 4);
s.round = try A.take((6 * W + max_streams + 1 + W * c.conv_taps + W + 4 * max_streams + 3 * items * max_streams + W + 32) * 4); // + each part's 16-byte padding
s.tables = try A.take(g.layers * max_streams * 8);
s.conv_cat = try A.take(g.layers * max_streams * (c.conv_taps - 1) * g.convDim() * bf);
s.conv_cat = try A.take(g.layers * s.streams() * (c.conv_taps - 1) * g.convDim() * bf);
for (0..g.layers) |i| {
if (c.linear(i)) {
s.records[i] = .{
Expand Down
Loading