Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
- Docs: `/health`'s `memory` on Metal is the process footprint from the families with a reader, not `{}`, and `/memory`'s `prompt_cache_plan` row names every Mac family that reports it, with Qwen3.5-2B under `--prompt-cache-gib` (#2439). Thanks to @Whq02.
- Kernel contract: a CPU affine projection (Qwen3.5-2B's 4-bit, group-64 `qmm` arithmetic on the host's cores, at the 2B's widths and chain counts) and a CPU RMS norm are registered and run through gates 1 to 4 with eight planted controls on any host with no device (`zig build cpu-contract`; CI's `test-kernel-contract`), and their output bytes are pinned the same at 1 to 16 threads and at column splits every 8 columns to 256 and every 256 beyond on x86_64 and arm64 (#2478, part of #2448). Thanks to @Whq02.
- Docs: `WINDOWS.md` says what the host suite needs on a Windows machine with no usable GPU (Zig alone), how to read the build runner's `failed command:` lines, which tests skip there and why, and how to unzip the Zig download quickly (#2479). Thanks to @Whq02.
- The CUDA Qwen3.5 lanes fill readout prompts in pieces for the joint schema head that follows: from row 0, each
piece's final-norm rows to the readout, 1,024 rows a piece unless the lane host caps it, as on HIP (#2384, part of
#2324). Thanks to @laudney.

## 1.2.4

Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
q35.addImport("cuda", cuda);
q35.addImport("core", mods.core);
q35.addImport("qwen35", mods.qwen35);
q35.addImport("lanes", mods.lanes);
const q35_install = b.addInstallArtifact(b.addExecutable(.{ .name = "tf-qwen35-cuda", .root_module = q35 }), .{});
b.getInstallStep().dependOn(&q35_install.step);
b.step("qwen35-cuda", "Build the Qwen CUDA forward and raw state receipt tool").dependOn(&q35_install.step);
Expand Down
42 changes: 39 additions & 3 deletions zig/src/families/qwen3_5/cuda_native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ const draws = @import("draw.zig");
const Draft = @import("cuda_draft.zig").Draft;
const cuda_rope = @import("cuda_rope.zig");
const prefill = @import("cuda_prefill.zig");
const readout = @import("cuda_readout.zig");
pub const Readout = readout.Readout;
pub const readout_piece_rows = readout.piece_rows;
const Fill = prefill.Fill;
const reuse = @import("cuda_reuse.zig");
const Mtp = @import("cuda_mtp.zig").Mtp;
Expand Down Expand Up @@ -141,8 +144,13 @@ pub fn ledgerPool(p: *anyopaque) ?*@import("core").kv_pool.Pool {
}

pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded {
if (kernels != null) return error.QwenHasNoCapturedKernels;
try decide.check(gpa, io, dir, .{ .drafter = o.drafter != null, .slide = o.slide, .vision = o.vision != null, .kv8 = o.kv8, .prompt_int8 = o.prompt_int8 });
return openLanes(gpa, io, ctx, dir, kernels, o);
}

/// `open` without the decision-only refusals: the runners open a BF16 backbone with a test readout through it.
pub fn openLanes(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded {
if (kernels != null) return error.QwenHasNoCapturedKernels;
if (o.slide and o.kv8) return error.UnsupportedLearningFormat;
const page_tokens = try pages_mod.paging();
const engine_paged = page_tokens > 0 and pages_mod.pagedOnly();
Expand Down Expand Up @@ -299,8 +307,11 @@ pub const Lanes = struct {
calibration: ?*Draft = null,
/// Prompt passes going a cut at a time (prefill_step), from their first step to their last.
fills: std.AutoHashMapUnmanaged(*lanes.Stream, Fill) = .empty,
/// The readout readout streams fill (none: they are refused) and each one's state, from its first piece to release.
readout: readout.Side = .{},

fn deinit(self: *Lanes) void {
self.readout.deinit(self.gpa, self.e); // drained and closed before any cache a pending piece writes goes
var it = self.caches.valueIterator();
while (it.next()) |cache| self.give(cache.*); // a pool lane's pages back, a window to the reserve
self.caches.deinit(self.gpa);
Expand Down Expand Up @@ -357,8 +368,31 @@ pub const Lanes = struct {
self.startup.add(try cost_adapter.measure(self, d, reserved));
}

/// The text streams' entries, and the same with a readout's completion once one is attached.
const text_vtable: be.Backend.VTable = .{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .reports_fill = true, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .prepare_features = prepareFeaturesFn, .features = featuresFn, .release = releaseFn };
const read_vtable: be.Backend.VTable = blk: {
var v = text_vtable;
v.readout_finish = readoutFinishFn;
break :blk v;
};

fn backend(self: *Lanes) be.Backend {
return .{ .ptr = self, .round_observer = if (self.trace) |x| x.observer() else null, .first_before_draft = true, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .reports_fill = true, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .prepare_features = prepareFeaturesFn, .features = featuresFn, .release = releaseFn } };
return .{ .ptr = self, .round_observer = if (self.trace) |x| x.observer() else null, .first_before_draft = true, .penalties = true, .vtable = if (self.readout.readout != null) &read_vtable else &text_vtable };
}

/// Readout streams from now on fill through `r` (one rank; before the first stream): the backend to hand on.
pub fn useReadout(self: *Lanes, r: Readout) be.Backend {
self.readout.readout = r;
return self.backend();
}

/// What the engine's readouts take, for its `Info` (null: none).
pub fn readouts(self: *const Lanes) ?lanes.readout.Info {
return if (self.readout.readout) |r| r.info else null;
}

fn readoutFinishFn(ptr: *anyopaque, stream: *lanes.Stream, logits: []u16) !void {
return readout.finish(cast(ptr), stream, logits);
}

/// A drafter's bytes in each lane's run: DFlash2's ring, or MTP's ring and state (0: no drafter).
Expand All @@ -383,10 +417,11 @@ pub const Lanes = struct {
}

fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void {
return prefill.run(cast(ptr), stream);
if (stream.readout != null) while (!try readout.step(cast(ptr), stream, 0)) {} else return prefill.run(cast(ptr), stream);
}

fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, max_rows: u32) !bool {
if (stream.readout != null) return readout.step(cast(ptr), stream, max_rows);
return prefill.step(cast(ptr), stream, max_rows);
}

Expand Down Expand Up @@ -529,6 +564,7 @@ pub const Lanes = struct {

fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void {
const self = cast(ptr);
readout.release(self, stream);
if (self.caches.fetchRemove(stream)) |entry| self.give(entry.value);
if (self.seen.fetchRemove(stream)) |entry| self.gpa.free(entry.value);
self.endFill(stream);
Expand Down
87 changes: 87 additions & 0 deletions zig/src/families/qwen3_5/cuda_readout.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Readouts on the CUDA Qwen3.5 engine: a state per stream, fed each prompt piece's final-norm rows (Keep.rows).
const std = @import("std");
const cuda = @import("cuda");
const lanes = @import("lanes");
const E = @import("cuda_engine.zig");

/// A readout's family side (the joint schema head): its streams' states, fed each piece's rows on the engine stream.
pub const Readout = struct {
ctx: *anyopaque,
info: lanes.readout.Info,
vtable: *const VTable,

pub const State = opaque {};
pub const VTable = struct {
/// The stream's state for `spec` over `prompt` (its tokens give the options' lexical rows).
open: *const fn (ctx: *anyopaque, spec: *const lanes.readout.Spec, prompt: []const u32) anyerror!*State,
/// `count` BF16 rows of the model's width from prompt row `first_row` at `rows`, valid until the next piece.
consume: *const fn (ctx: *anyopaque, st: *State, rows: u64, first_row: usize, count: usize, stream: cuda.Stream) anyerror!void,
finish: *const fn (ctx: *anyopaque, st: *State, logits: []u16) anyerror!void,
close: *const fn (ctx: *anyopaque, st: *State) void,
};
};

/// Rows a piece takes when the lane host names no cap, as on HIP.
pub const piece_rows = 1024;

/// The lanes' readout side: the readout (null: readout streams are refused) and each stream's progress.
pub const Side = struct {
readout: ?Readout = null,
open: std.AutoHashMapUnmanaged(*lanes.Stream, Open) = .empty,

pub const Open = struct { state: *Readout.State, at: usize };

/// Every open state closed once `e`'s queued work (a consume's) is done.
pub fn deinit(side: *Side, gpa: std.mem.Allocator, e: *E.Engine) void {
if (side.open.count() > 0) cuda.completion.drain(e.d, e.stream, "readout states did not drain");
var it = side.open.valueIterator();
while (it.next()) |o| side.readout.?.vtable.close(side.readout.?.ctx, o.state);
side.open.deinit(gpa);
}
};

/// One piece of a readout stream's prompt pass; true once its last row is consumed (`self`: cuda_native's Lanes).
pub fn step(self: anytype, stream: *lanes.Stream, max_rows: u32) !bool {
if (stream.isCancelled()) return error.Cancelled;
const r = self.readout.readout orelse return error.ReadoutsUnsupported;
if (!self.readout.open.contains(stream)) try begin(self, r, stream);
const o = self.readout.open.getPtr(stream).?;
const ids = stream.prompt();
const piece: usize = @min(E.max_rows, if (max_rows > 0) max_rows else piece_rows);
const end = @min(ids.len, o.at + piece);
try self.e.forward(&.{.{ .cache = try self.cacheOf(stream), .rows = end - o.at }}, ids[o.at..end], .rows);
try r.vtable.consume(r.ctx, o.state, self.e.x, o.at, end - o.at, self.e.stream);
o.at = end;
stream.fill_at.store(@intCast(end), .monotonic);
return end == ids.len;
}

/// A readout stream's first piece: a cache from row 0 (no prefix store, kept states or marks) and its state.
fn begin(self: anytype, r: Readout, stream: *lanes.Stream) !void {
const ids = stream.prompt();
if (ids.len == 0 or ids.len > self.capacity or self.caches.contains(stream)) return error.InvalidQwenPrompt;
const cache = try self.take(ids.len, 0);
errdefer self.give(cache);
try self.caches.put(self.gpa, stream, cache);
errdefer _ = self.caches.remove(stream);
try self.readout.open.ensureUnusedCapacity(self.gpa, 1);
const st = try r.vtable.open(r.ctx, stream.readout.?, ids);
self.readout.open.putAssumeCapacity(stream, .{ .state = st, .at = 0 });
stream.cached = 0;
}

/// A filled readout's logits from its state into the request's slice.
pub fn finish(self: anytype, stream: *lanes.Stream, logits: []u16) !void {
const r = self.readout.readout orelse return error.ReadoutsUnsupported;
const o = self.readout.open.get(stream) orelse return error.NotAReadout;
if (o.at != stream.prompt().len) return error.ReadoutUnfilled;
try r.vtable.finish(r.ctx, o.state, logits);
}

/// The stream's state closed once, whether it filled, failed or was cancelled (none before its first piece).
pub fn release(self: anytype, stream: *lanes.Stream) void {
const kv = self.readout.open.fetchRemove(stream) orelse return;
// a consume may still be queued on the engine stream (a cancel or a failure): it ends before its state goes
cuda.completion.drain(self.e.d, self.e.stream, "a readout's queued work did not drain");
self.readout.readout.?.vtable.close(self.readout.readout.?.ctx, kv.value.state);
}
13 changes: 12 additions & 1 deletion zig/src/native/cuda_bound.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ pub fn vtable(comptime H: type, v: be.Backend.VTable) be.Backend.VTable {
return x.inner.vtable.embedding.?(x.inner.ptr, s, out);
}
}.f else null,
.readout_finish = if (v.readout_finish != null) struct {
fn f(p: *anyopaque, s: *lanes.Stream, logits: []u16) anyerror!void {
const x = H.bind(p);
return x.inner.vtable.readout_finish.?(x.inner.ptr, s, logits);
}
}.f else null,
.prefill = struct {
fn f(p: *anyopaque, s: *lanes.Stream) anyerror!void {
const x = H.bind(p);
Expand Down Expand Up @@ -157,7 +163,11 @@ test "every entry the family's backend gives is forwarded, and none it leaves ou
interrupted.cancel_prefill = struct {
fn f(_: *anyopaque, _: *lanes.Stream) anyerror!void {}
}.f;
for ([_]be.Backend{ fake.backend(), fake.stepped(), fake.batchedSteps(), .{ .ptr = &fake, .vtable = &interrupted } }) |b| {
var readout = fake.stepped().vtable.*; // a Clef engine's: the readout's completion beside the stepped pass
readout.readout_finish = struct {
fn f(_: *anyopaque, _: *lanes.Stream, _: []u16) anyerror!void {}
}.f;
for ([_]be.Backend{ fake.backend(), fake.stepped(), fake.batchedSteps(), .{ .ptr = &fake, .vtable = &interrupted }, .{ .ptr = &fake, .vtable = &readout } }) |b| {
const w = vtable(H, b.vtable.*);
const info = @typeInfo(be.Backend.VTable).@"struct";
inline for (info.field_names, info.field_types) |name, T| {
Expand All @@ -166,6 +176,7 @@ test "every entry the family's backend gives is forwarded, and none it leaves ou
}
}
try std.testing.expect(vtable(H, fake.stepped().vtable.*).prefill_step != null);
try std.testing.expect(vtable(H, readout).readout_finish != null and vtable(H, fake.stepped().vtable.*).readout_finish == null);
}

test "each forwarded entry calls the family's entry of the same name, once" {
Expand Down
6 changes: 6 additions & 0 deletions zig/tests/qwen35_cuda_main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const usage =
\\TF_Q35_WINDOW=N fixes window/tree width (tree: at least 2); 0 keeps growing widths.
\\ tf-qwen35-cuda <model dir> rows <ids file> <out> [piece] | rows-last <ids file> | rows-cuts <ids file>
\\rows: final-norm rows as a readout keeps them (raw bf16); rows-last checks them against .last; rows-cuts reports.
\\ tf-qwen35-cuda <model dir> readout <ids file> [streams]: a test readout's rows alone, together, after a cancel
\\ tf-qwen35-cuda <model dir> kl <ids file> <out.json> <skip> <rows> [control|int8]
\\kl: bf16 caches against fp8 ones, teacher-forced: the first <skip> ids as prompt chunks, then <rows> ids in
\\windows, each row's KL(bf16 || fp8) of the next-token distributions, top-1 agreement and both losses on the next
Expand All @@ -40,6 +41,11 @@ pub fn main(init: std.process.Init) !u8 {
const bound: ?[2]f64 = if (bounded) .{ try std.fmt.parseFloat(f64, args[6]), try std.fmt.parseFloat(f64, args[7]) } else null;
return vision(init, a, args[1], args[3], try std.fmt.parseInt(u32, args[4], 10), bound, args[first..]);
}
if (args.len >= 4 and std.mem.eql(u8, args[2], "readout")) {
const code = try @import("qwen35_cuda_readout.zig").run(init, a, args);
if (code == 2) std.debug.print("{s}", .{usage});
return code;
}
if (args.len >= 4 and std.mem.startsWith(u8, args[2], "rows")) {
const code = try @import("qwen35_cuda_rows.zig").run(init, a, args);
if (code == 2) std.debug.print("{s}", .{usage});
Expand Down
Loading
Loading