Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
1be6dc0
Windows: a platform layer and host builds that pass
BobClawblaw Oct 12, 2026
e5bb3bc
Windows: CUDA kernels, the native server and the GPU suites on sm_89
BobClawblaw Oct 12, 2026
1f87b27
Windows: pull into the hub cache, HOME, and the whole test step
BobClawblaw Oct 12, 2026
996a50f
Windows: build notes, strip before install, formatting
BobClawblaw Oct 12, 2026
aac93d2
Default port 8888
BobClawblaw Oct 12, 2026
81f5576
qwen3_5: serve Qwen3.5-2B on CUDA
BobClawblaw Oct 13, 2026
3ace97e
qwen3_5: serve Qwen3.8-27B on CUDA, one arena for a model's device me…
BobClawblaw Oct 14, 2026
6b85f22
qwen3_5: replay each decode shape as a CUDA graph
BobClawblaw Oct 14, 2026
b19e0d7
qwen3_5: DFlash2 drafts for Qwen3.8-27B on CUDA
BobClawblaw Oct 14, 2026
288ba03
qwen3_5: tree drafts on CUDA, the kept path replayed from a log
BobClawblaw Oct 14, 2026
61fc2bf
docs: the Qwen hybrids on CUDA in the Windows page and the README
BobClawblaw Oct 14, 2026
6aaf241
qwen3_5, platform: comments on one line
BobClawblaw Oct 14, 2026
8107ee2
Windows: checkpoint reads skip the page cache
BobClawblaw Oct 14, 2026
693533e
Windows: the signal handler type allows address 1, for aarch64
BobClawblaw Oct 14, 2026
f53ae20
docs: Windows as a target in the README and the Windows page
BobClawblaw Oct 14, 2026
e875ee2
CI: the host unit tests on Windows
BobClawblaw Oct 14, 2026
38ecce5
qwen3_5: the drafter reads TF_TIMING through the platform layer
BobClawblaw Oct 14, 2026
1817823
qwen3_5: the drafter takes a prompt longer than its tap ring
BobClawblaw Oct 14, 2026
b811a3b
qwen3_5 cuda: prompt chunks past 32 rows see the right keys, and tree…
BobClawblaw Oct 14, 2026
0a0856b
Windows: the server goldens and the Cortheon fuzz step on Windows hosts
BobClawblaw Oct 14, 2026
ccd06b9
cuda: cuBLASLt opens by its Windows DLL name
BobClawblaw Oct 14, 2026
045abbd
Windows: writes on an O_APPEND descriptor land at the end whole
BobClawblaw Oct 14, 2026
bdfeb84
golden check: a request-log mismatch names the first differing line
BobClawblaw Oct 14, 2026
39de039
lane core and native CUDA host for two-rank families with a vision to…
BobClawblaw Oct 14, 2026
153d6b4
golden check: the request log compares with LF endings on either side
BobClawblaw Oct 14, 2026
22d92e4
lane host: a warm pass that steps aside is not launched after its can…
BobClawblaw Oct 15, 2026
ef73ec3
tf_video: the includes back under its one-line header
BobClawblaw Oct 15, 2026
cc5d9d1
vision inputs: a server without --vision refuses image parts in the f…
BobClawblaw Oct 15, 2026
aaed024
qwen_image.formatSeconds: t * 10 rounded in integers, not f128, so te…
BobClawblaw Oct 15, 2026
9e6dfcd
lane host: a set-up job's kept entry stays pinned until its restore r…
BobClawblaw Oct 15, 2026
8570e06
qwen3_5: attention chunks follow each row's own keys, not the forward…
BobClawblaw Oct 15, 2026
5e1c3fe
qwen3_5: the DFlash2 config's divisors must be positive, and staging …
BobClawblaw Oct 15, 2026
52b82fc
prompt cache: an entry removed while pinned is dead to lookups and fr…
BobClawblaw Oct 15, 2026
92c9ef4
Merge branch 'pr-853' into qwen35-vision
BobClawblaw Oct 15, 2026
73f06f1
qwen3_5: image rows and M-RoPE positions in the CUDA forward
BobClawblaw Oct 15, 2026
a10b4de
qwen3_5: the vision tower on CUDA, and --vision on the Qwen engine
BobClawblaw Oct 15, 2026
ac94f8f
tf-qwen35-cuda: vision and mrope checks
BobClawblaw Oct 15, 2026
7ad45b6
native/cuda: drop the doc comment learnBytes left behind on toGib
BobClawblaw Oct 15, 2026
3217063
CI on #885: the server's image paths build on Windows; lean and a tra…
BobClawblaw Oct 15, 2026
55c47f9
tf-qwen35-cuda vision: the tower's rows bounded, exit 1 outside them
BobClawblaw Oct 15, 2026
5296eb1
tf-qwen35-cuda: one-line comments within 120 columns (the lean check)
BobClawblaw Oct 15, 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 14, 2026
commit 6b85f22799d796fc19982657c1e68834f63ebff5
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