Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
b923e55
Windows: a platform layer and host builds that pass
BobClawblaw Oct 12, 2026
60c6892
Windows: CUDA kernels, the native server and the GPU suites on sm_89
BobClawblaw Oct 12, 2026
9c36621
Windows: pull into the hub cache, HOME, and the whole test step
BobClawblaw Oct 12, 2026
2f626e1
Windows: build notes, strip before install, formatting
BobClawblaw Oct 12, 2026
ec0ddc5
Default port 8888
BobClawblaw Oct 12, 2026
3c57c14
qwen3_5: serve Qwen3.5-2B on CUDA
BobClawblaw Oct 13, 2026
84c58d3
qwen3_5: serve Qwen3.8-27B on CUDA, one arena for a model's device me…
BobClawblaw Oct 14, 2026
a087521
qwen3_5: replay each decode shape as a CUDA graph
BobClawblaw Oct 14, 2026
c3861d3
qwen3_5: DFlash2 drafts for Qwen3.8-27B on CUDA
BobClawblaw Oct 14, 2026
9b8d4af
qwen3_5: tree drafts on CUDA, the kept path replayed from a log
BobClawblaw Oct 14, 2026
b5b5c4b
docs: the Qwen hybrids on CUDA in the Windows page and the README
BobClawblaw Oct 14, 2026
cf2cdf1
qwen3_5, platform: comments on one line
BobClawblaw Oct 14, 2026
221c2b5
Windows: checkpoint reads skip the page cache
BobClawblaw Oct 14, 2026
522d17d
Windows: the signal handler type allows address 1, for aarch64
BobClawblaw Oct 14, 2026
d1ea47f
docs: Windows as a target in the README and the Windows page
BobClawblaw Oct 14, 2026
95f879e
CI: the host unit tests on Windows
BobClawblaw Oct 14, 2026
7efc823
qwen3_5: the drafter reads TF_TIMING through the platform layer
BobClawblaw Oct 14, 2026
85bb88d
qwen3_5: the drafter takes a prompt longer than its tap ring
BobClawblaw Oct 14, 2026
e01d423
qwen3_5 cuda: prompt chunks past 32 rows see the right keys, and tree…
BobClawblaw Oct 14, 2026
0baccf3
Windows: the server goldens and the Cortheon fuzz step on Windows hosts
BobClawblaw Oct 14, 2026
40159f8
cuda: cuBLASLt opens by its Windows DLL name
BobClawblaw Oct 14, 2026
cdb735b
Windows: writes on an O_APPEND descriptor land at the end whole
BobClawblaw Oct 14, 2026
a63ec9b
golden check: a request-log mismatch names the first differing line
BobClawblaw Oct 14, 2026
d7fb12f
golden check: the request log compares with LF endings on either side
BobClawblaw Oct 14, 2026
02d3e2e
qwen3_5: attention chunks follow each row's own keys, not the forward…
BobClawblaw Oct 15, 2026
e7744bc
qwen3_5: the DFlash2 config's divisors must be positive, and staging …
BobClawblaw Oct 15, 2026
48dcc42
Windows: 1.0.12's new code through the platform layer
BobClawblaw Oct 16, 2026
1d0a11f
docs: 1.0.12's new pages at the default port, 8888
BobClawblaw Oct 16, 2026
26e9b68
lanes recorder: a stream's new file is never made through a link ther…
BobClawblaw Oct 16, 2026
a1f54b4
qwen3_5 cuda: the drafter's top-k over many blocks a row, the same id…
BobClawblaw Oct 16, 2026
b3e306b
qwen3_5 cuda: group sums made once a projection input, the norm writi…
BobClawblaw Oct 16, 2026
cc0fc9e
qwen3_5 cuda: greedy rows' argmax in two stages over many blocks, a r…
BobClawblaw Oct 16, 2026
44005ad
qwen3_5 cuda: a group's sum a thread, in eight 16-byte loads, its ent…
BobClawblaw Oct 16, 2026
48a6622
lanes: a drafter may grow its own trees (Facts.tree_nodes), read back…
BobClawblaw Oct 16, 2026
aa214f9
qwen3_5 cuda: DFlash2 drafts best-first trees of up to 15 nodes, four…
BobClawblaw Oct 16, 2026
c7eea82
qwen3_5 cuda: the delta rule loads a row's inputs while the row befor…
BobClawblaw Oct 16, 2026
a76fd79
qwen3_5 cuda: a hold's chain, lanes and best-first tree in cuda_draft…
BobClawblaw Oct 16, 2026
d15bf69
qwen3_5 cuda: DFlash2 drafts 16-row blocks as the reference does; gro…
BobClawblaw Oct 16, 2026
6f7acde
qwen3_5 cuda: Landing's comment on one line
BobClawblaw Oct 16, 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
qwen3_5: replay each decode shape as a CUDA graph
A forward's launches (the embedding to the kept rows' logits) are captured
the first time a shape (rows, windows, recording) is seen and replayed after;
the attention chunk count moves into the per-forward table so a graph stays
valid as caches grow. Prompt chunks stay uncaptured: their GEMMs dwarf the
launches, and each length would be a graph of its own.

A new graph's first run pays the Windows driver's stall (about a second on a
wide model), so `reserve` also captures the shared rounds' shapes, a row of
each of 1 to n streams, at load.

Bit for bit the same logits; on an RTX 4090 the 2B steps in 2.8 ms instead of
5.3 (served: 324 tok/s, 1,560 across eight streams) and the 27B in 23.8 ms
instead of 26.9 (served: 40 tok/s, 243 across eight).
  • Loading branch information
BobClawblaw committed Oct 16, 2026
commit a087521799fd58dbbfdd27cf081a15c6b439e060
15 changes: 10 additions & 5 deletions zig/kernels/cuda/qwen35.cu
Original file line number Diff line number Diff line change
Expand Up @@ -322,15 +322,18 @@ extern "C" __global__ void __launch_bounds__(256) tf_q35_rope(Geo geo, __nv_bflo
}
}

// Causal attention over a segment's cache, ck keys a block: grid (chunks, kvh, rows), block qh / kvh warps, a warp a
// query head of the kv head's group. Partials (max, sum, out) at slot (row, qh, chunk); empty chunks leave sum 0.
// Causal attention over a segment's cache, P[1] keys a block over P[0] chunks (read from the device, so a captured
// forward replays as caches grow): grid (chunks at most, kvh, rows), block qh / kvh warps, a warp a query head of
// the kv head's group. Partials (max, sum, out) at slot (row, qh, chunk); empty chunks leave sum 0.
extern "C" __global__ void tf_q35_attn_partial(Geo geo, const __nv_bfloat16* __restrict__ Q, const Seg* __restrict__ segs,
const int* __restrict__ rowseg, int layer, int nch, int ck, float scale,
const int* __restrict__ rowseg, int layer, const int* __restrict__ P, float scale,
float* __restrict__ PM, float* __restrict__ PL, float* __restrict__ PO) {
constexpr int DPL = HD / 32;
const int nch = P[0], ck = P[1];
const int QH = geo.qh, KVH = geo.kvh;
const int lane = threadIdx.x & 31, g = threadIdx.x >> 5;
const int c = blockIdx.x, h = blockIdx.y;
if (c >= nch) return;
const size_t m = blockIdx.z;
const int qh = h * (QH / KVH) + g;
const Seg sg = segs[rowseg[m]];
Expand Down Expand Up @@ -377,10 +380,12 @@ extern "C" __global__ void tf_q35_attn_partial(Geo geo, const __nv_bfloat16* __r
for (int i = 0; i < DPL; i++) PO[slot * HD + lane * DPL + i] = o[i];
}

// The chunks' partials into each (row, query head)'s output, rows qh * HD wide. Grid (qh, rows), a warp each.
// The P[0] chunks' partials into each (row, query head)'s output, rows qh * HD wide. Grid (qh, rows), a warp each.
extern "C" __global__ void __launch_bounds__(32) tf_q35_attn_merge(Geo geo, const float* __restrict__ PM, const float* __restrict__ PL,
const float* __restrict__ PO, int nch, __nv_bfloat16* __restrict__ OUT) {
const float* __restrict__ PO, const int* __restrict__ P,
__nv_bfloat16* __restrict__ OUT) {
constexpr int DPL = HD / 32;
const int nch = P[0];
const int QH = geo.qh;
const int lane = threadIdx.x, qh = blockIdx.x;
const size_t m = blockIdx.y;
Expand Down
110 changes: 82 additions & 28 deletions zig/src/families/qwen3_5/cuda_engine.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Qwen3.5's hybrid text models on CUDA (the 2B, Qwen3.8-27B): the affine-4 projections through cuda.qlinear, the
//! glue in qwen35.cu, one forward for any mix of streams' windows. Each stream owns its recurrences, convolution tails
//! and KV cache (Cache); the widths come from config.json (cuda_geometry.zig), the weights from cuda_weights.zig.
//! A forward's launches are captured into a CUDA graph the first time its shape is seen and replayed after.
const std = @import("std");
const cuda = @import("cuda");
const core = @import("core");
Expand Down Expand Up @@ -172,14 +173,17 @@ pub const Engine = struct {
host_logits: cuda.HostBuffer,
/// The kept rows' device draws, when forward was given them.
tokens: [most_verify]u32 = undefined,
/// The captured forwards by shape (`Shape.key`): the launches from the embedding to the head.
graphs: std.AutoHashMapUnmanaged(u32, cuda.graph.Exec) = .empty,

const ids_at = 0;
const segs_at = max_rows * 4;
const rowseg_at = segs_at + max_segs * @sizeOf(Seg);
const rules_at = rowseg_at + max_rows * 4;
const meta_at = rules_at + most_verify * @sizeOf(cuda.sample.Rule);
const tokens_at = meta_at + most_verify * 4;
const tables_len = tokens_at + most_verify * 4;
const params_at = tokens_at + most_verify * 4; // the attention chunks and their width
const tables_len = params_at + 2 * 4;

pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8) !*Engine {
if (!cuda.kernels.available) return error.BuiltWithoutKernels;
Expand All @@ -195,6 +199,7 @@ pub const Engine = struct {
e.verify_rows = std.math.clamp(snapshot_budget / (g.deltas() * (g.recBytes() + g.convBytes())), 1, most_verify);
e.window_rows = @min(most_window, e.verify_rows);
e.arena_at = 0;
e.graphs = .empty;
e.stream = try cuda.Stream.init(d, true);
errdefer e.stream.deinit();
e.arena = try DeviceBuffer.alloc(d, weights.total(g) + try e.scratch(.measure));
Expand Down Expand Up @@ -240,6 +245,9 @@ pub const Engine = struct {
}

pub fn deinit(e: *Engine) void {
var it = e.graphs.valueIterator();
while (it.next()) |x| x.deinit();
e.graphs.deinit(e.gpa);
e.host_logits.free();
e.staged.free();
e.tables.free();
Expand Down Expand Up @@ -363,15 +371,82 @@ pub const Engine = struct {
m.* = @intCast(p.position -% 1); // sample.cu keys row r at meta + r + 1
}
}
// attention chunks: at most max_chunks a row, each a multiple of 128 keys
const ck = @max(128, (widest + max_chunks * 128 - 1) / (max_chunks * 128) * 128);
const params = std.mem.bytesAsSlice(c_int, st[params_at..][0..8]);
params[0] = @intCast((widest + ck - 1) / ck);
params[1] = @intCast(ck);
try e.tables.uploadAsync(0, st, e.stream.handle);
const shape: Shape = .{ .total = @intCast(total), .nseg = @intCast(parts.len), .record = record, .prompt = prompt };
if (prompt) {
// uncaptured: a prompt chunk's GEMMs dwarf its launches, and each length would be a graph of its own,
// paying the driver's stall on a new graph's first run (about a second on a wide model)
try e.body(shape);
} else {
const gop = try e.graphs.getOrPut(e.gpa, shape.key());
if (!gop.found_existing) {
errdefer _ = e.graphs.remove(shape.key());
// captured, nothing runs: the replay below is this shape's first run
try cuda.graph.beginCapture(e.stream, .thread_local);
e.body(shape) catch |err| {
var broken = cuda.graph.endCapture(e.stream) catch return err;
broken.deinit();
return err;
};
var captured = try cuda.graph.endCapture(e.stream);
defer captured.deinit();
gop.value_ptr.* = try captured.instantiate();
}
try gop.value_ptr.launchOn(e.stream);
}
for (parts) |p| p.cache.len += p.rows;
switch (keep) {
.draws => |pk| {
const toks = e.tables.ptr + tokens_at;
for (pk, 0..) |p, i| {
const row = e.logits + i * g.vocab * 2;
if (p.rule != null) {
try e.draws.draw(e.stream, row, g.vocab, e.tables.ptr + rules_at + i * @sizeOf(cuda.sample.Rule), e.tables.ptr + meta_at + i * 4, 0, toks + i * 4, 1, null, null);
} else try e.run(e.fns.argmax, .{ 1, 1, 1 }, .{ 1024, 1, 1 }, .{ row, @as(c_int, @intCast(g.vocab)), toks + i * 4 });
}
try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(e.host_logits.bytes.ptr, toks, total * 4, e.stream.handle), "cuMemcpyDtoHAsync");
try e.stream.synchronize();
@memcpy(e.tokens[0..total], e.host_logits.slice(u32)[0..total]);
},
.logits, .last => {
const out = e.host_logits.bytes[0 .. heads * g.vocab * 2];
try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(out.ptr, e.logits, out.len, e.stream.handle), "cuMemcpyDtoHAsync");
try e.stream.synchronize();
if (keep == .last) @memcpy(parts[0].cache.logits, e.rowLogits(0));
},
}
}

/// A forward's shape, which fixes its launches: its tables and the caches' lengths are read on the device.
const Shape = struct {
total: u8,
nseg: u8,
record: bool,
prompt: bool,

fn key(s: Shape) u32 {
return @as(u32, s.total) | @as(u32, s.nseg) << 8 | @as(u32, @intFromBool(s.record)) << 16 | @as(u32, @intFromBool(s.prompt)) << 17;
}
};

/// The launches of a forward of `shape`, from the embedding to the kept rows' logits (captured once a shape).
fn body(e: *Engine, shape: Shape) !void {
const g = e.g;
const total: usize = shape.total;
const nseg: usize = shape.nseg;
const record = shape.record;
const prompt = shape.prompt;
const heads: usize = if (record) total else 1;
const t_ids = e.tables.ptr + ids_at;
const t_segs = e.tables.ptr + segs_at;
const t_rows = e.tables.ptr + rowseg_at;
const nseg = parts.len;
const t_params = e.tables.ptr + params_at;
const geo = e.geo;
// attention chunks: at most max_chunks a row, each a multiple of 128 keys
const ck = @max(128, (widest + max_chunks * 128 - 1) / (max_chunks * 128) * 128);
const nch = (widest + ck - 1) / ck;
const group = g.q_heads / g.kv_heads;

try e.run(e.fns.embed, .{ total, 1, 1 }, .{ 256, 1, 1 }, .{ t_ids, e.embed_w, e.embed_s, e.embed_b, e.h, @as(c_int, @intCast(g.hidden)) });
Expand Down Expand Up @@ -403,8 +478,8 @@ pub const Engine = struct {
try e.run(e.fns.head_norm, .{ total * g.q_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.qraw, m.q_norm, e.qn, @as(c_int, @intCast(g.q_heads)), @as(c_int, @intCast(2 * aw)), @as(c_int, 2 * head_dim), g.eps });
try e.run(e.fns.head_norm, .{ total * g.kv_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.kraw, m.k_norm, e.kn, @as(c_int, @intCast(g.kv_heads)), @as(c_int, @intCast(g.kv_heads * head_dim)), @as(c_int, head_dim), g.eps });
try e.run(e.fns.rope, .{ total, 1, 1 }, .{ head_dim, 1, 1 }, .{ geo, e.qn, e.kn, e.vraw, t_segs, t_rows, ai });
try e.run(e.fns.attn_partial, .{ nch, g.kv_heads, total }, .{ 32 * group, 1, 1 }, .{ geo, e.qn, t_segs, t_rows, ai, @as(c_int, @intCast(nch)), @as(c_int, @intCast(ck)), @as(f32, 1.0 / 16.0), e.pm, e.pl, e.po });
try e.run(e.fns.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, .{ geo, e.pm, e.pl, e.po, @as(c_int, @intCast(nch)), e.y });
try e.run(e.fns.attn_partial, .{ max_chunks, g.kv_heads, total }, .{ 32 * group, 1, 1 }, .{ geo, e.qn, t_segs, t_rows, ai, t_params, @as(f32, 1.0 / 16.0), e.pm, e.pl, e.po });
try e.run(e.fns.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, .{ geo, e.pm, e.pl, e.po, t_params, e.y });
try e.run(e.fns.attn_gate, .{ (total * aw + 255) / 256, 1, 1 }, .{ 256, 1, 1 }, .{ geo, e.y, e.qraw, e.mix, @as(c_int, @intCast(total)) });
try e.proj(m.o, e.mix, e.r, total, prompt);
ai += 1;
Expand All @@ -420,27 +495,6 @@ pub const Engine = struct {
try e.norm(true, e.final_norm, total);
// the head over the kept rows
try e.proj(e.head, e.x + (total - heads) * g.hidden * 2, e.logits, heads, false);
for (parts) |p| p.cache.len += p.rows;
switch (keep) {
.draws => |pk| {
const toks = e.tables.ptr + tokens_at;
for (pk, 0..) |p, i| {
const row = e.logits + i * g.vocab * 2;
if (p.rule != null) {
try e.draws.draw(e.stream, row, g.vocab, e.tables.ptr + rules_at + i * @sizeOf(cuda.sample.Rule), e.tables.ptr + meta_at + i * 4, 0, toks + i * 4, 1, null, null);
} else try e.run(e.fns.argmax, .{ 1, 1, 1 }, .{ 1024, 1, 1 }, .{ row, @as(c_int, @intCast(g.vocab)), toks + i * 4 });
}
try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(e.host_logits.bytes.ptr, toks, total * 4, e.stream.handle), "cuMemcpyDtoHAsync");
try e.stream.synchronize();
@memcpy(e.tokens[0..total], e.host_logits.slice(u32)[0..total]);
},
.logits, .last => {
const out = e.host_logits.bytes[0 .. heads * g.vocab * 2];
try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(out.ptr, e.logits, out.len, e.stream.handle), "cuMemcpyDtoHAsync");
try e.stream.synchronize();
if (keep == .last) @memcpy(parts[0].cache.logits, e.rowLogits(0));
},
}
}

/// Row `i`'s logits from the newest forward that kept logits.
Expand Down
11 changes: 11 additions & 0 deletions zig/src/families/qwen3_5/cuda_native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ fn reserve(p: *anyopaque, streams: u32) anyerror!void {
try cache.reset(l.e);
l.pool.appendAssumeCapacity(cache);
}
// the shared rounds' shapes, a row of each of 1 to `streams` streams, captured now: a new graph's first run
// pays the driver's stall too (about a second on a wide model)
var parts: [E.max_segs]E.Part = undefined;
var ids: [E.max_segs]u32 = @splat(0);
var picks: [E.max_segs]E.Draw = undefined;
for (0..@min(streams, E.max_segs)) |n| {
parts[n] = .{ .cache = l.pool.items[n], .rows = 1 };
picks[n] = .{ .rule = null, .position = 1 };
try l.e.forward(parts[0 .. n + 1], ids[0 .. n + 1], .{ .draws = picks[0 .. n + 1] });
for (l.pool.items[0 .. n + 1]) |cache| try cache.reset(l.e);
}
}

/// A request this engine refuses, in words; null: none of its own.
Expand Down