Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi
| `TF_QWEN_PROMPT_SPLITK` | Qwen3.8-27B on CUDA with `--kv-cache fp8`: exactly `0` or `1`, read once; unset is `0`. `1` runs a prompt chunk of 1 to 64 rows through split passes that spread the cached keys over every SM (tile maxima, a running-maximum scan, the weights, then the fold a head) instead of one block of the tile kernel a head pair, which leaves most SMs idle when a turn adds a few rows to a long conversation. Every output bit equals the tile kernel's, so tokens are unchanged; chunks of more rows, bf16 caches and other head layouts keep the tile kernel. The passes borrow the decode partials and logits scratch, so no memory is added. |
| `TF_QWEN_PROMPT_SPLITK_VERIFY` | With `TF_QWEN_PROMPT_SPLITK=1`: exactly `0` or `1`, read once; unset is `0`. `1` also runs the tile kernel on every split chunk and stops the process when any output bit differs. A check for new GPUs and checkpoints, slower than either path alone. |
| `TF_QWEN35_CHUNK_SOLO` | Qwen 3.5/3.6/3.8 on CUDA: 4096 or 8192 rows a foreground prompt pass while no other stream decodes (a background warm pass keeps 4096); unset, empty or 4096 is off, with main's scratch. Checked when the model loads, with the family's own message |
| `TF_CUDA_HOST_WFE` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` on an aarch64 Linux host with FEAT_WFxT parks the RoCE proxy's idle polls and GLM's token readback waits (greedy pick, sampled draw, step broadcast) in WFET on the waited word's exclusive monitor, with a 1 ms counter deadline (after a long idle stretch the proxy naps as it does unset); any unexpected driver result hands the wait back to the existing synchronize. Tokens are unchanged |
| `TF_GEMMA4_CHUNK_SOLO` | Gemma 4 on CUDA: a multiple of 512 from 512 through 4096; unset, empty or 512 is off. Checked when the model loads, with the family's own message |
| `TF_GEMMA4_ARGMAX_GRAPH` | Gemma 4 on CUDA: exactly `0` or `1`; default off. `1` captures a greedy verify round's argmax (the same `tf_round_bf16_argmax` over the same logits) in the target forward's graph, skips the drawn-token download no greedy entry reads, and stages each forward's ids, positions and slots in pinned memory; target tokens keep their bits |
| `TF_DRAMA_PREFILL_ROWS` | Drama 3 on CUDA: whole prompt rows a chunk, 1 through 1024; default 1. Checked when the checkpoint opens, with its own message |
Expand Down
5 changes: 4 additions & 1 deletion zig/src/cuda/driver.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ pub const Driver = struct {
api: abi.Api,
/// cuFuncGetName (CUDA 12.3+; optional: an older driver opens without it): a failed launch names its kernel
func_name: ?FuncGetName = null,
/// Optional, as cuFuncGetName: only TF_CUDA_HOST_WFE's stream waits use it.
write_value32: ?WriteValue32 = null,

pub const FuncGetName = *const fn (*?[*:0]const u8, abi.Function) callconv(.c) abi.Result;
pub const WriteValue32 = *const fn (abi.Stream, abi.DevicePtr, u32, c_uint) callconv(.c) abi.Result;

pub fn open() Error!Driver {
return openPath(platform.cuda_driver);
Expand All @@ -35,7 +38,7 @@ pub const Driver = struct {
return error.MissingSymbol;
};
}
const d: Driver = .{ .lib = lib, .api = api, .func_name = lib.lookup(FuncGetName, "cuFuncGetName") };
const d: Driver = .{ .lib = lib, .api = api, .func_name = lib.lookup(FuncGetName, "cuFuncGetName"), .write_value32 = lib.lookup(WriteValue32, "cuStreamWriteValue32_v2") };
try d.check(api.cuInit(0), "cuInit");
var buf: [256]u8 = undefined;
if (d.tooOld(&buf)) |why| {
Expand Down
359 changes: 359 additions & 0 deletions zig/src/cuda/host_wait.zig

Large diffs are not rendered by default.

22 changes: 10 additions & 12 deletions zig/src/cuda/roce.zig
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub const max_world = layout.max_world;
pub const peerIndex = layout.peerIndex;
pub const senderOf = layout.senderOf;
pub const firstUnreachable = layout.firstUnreachable;
const host_wait = @import("host_wait.zig");

const max_peers = max_world - 1;
const send_depth = 256;
Expand Down Expand Up @@ -151,13 +152,11 @@ pub const Gather = struct {
// every rank's queue pairs are ready to receive before any rank's probe write leaves
var words: [max_world]u32 = undefined;
const ready = exchange(u32, group, d, s, @intFromBool(connected), &words) catch |e| {
g.teardown();
gpa.destroy(g);
g.deinit(); // setup ran (every blob was ok), so g.gpa is gpa
return e;
};
if (!connected or std.mem.indexOfScalar(u32, ready, 0) != null) {
g.teardown();
gpa.destroy(g);
g.deinit();
return null;
}
// the connect probe: a token to every peer on every HCA, our writes completed and every peer's token in
Expand All @@ -169,19 +168,16 @@ pub const Gather = struct {
break :blk 1;
};
const verdicts = exchange(u32, group, d, s, reached, &words) catch |e| {
g.teardown();
gpa.destroy(g);
g.deinit();
return e;
};
if (std.mem.indexOfScalar(u32, verdicts, 0)) |r| { // every rank or none, as for every other failure above
g.teardown();
gpa.destroy(g);
g.deinit();
std.log.warn("RoCE all-gather: rank {d} has no RDMA path to every other rank (its log names the peer and the HCA); NCCL carries every gather. Every rank must reach every other: on a switch or a cable the same HCA index, on a switchless mesh the HCA on each peer's /24 (TF_ROCE_HCA naming one function a port); a ring of four has none. TF_ROCE=0 keeps this quiet", .{r});
return null;
}
g.startProxy() catch |e| {
g.teardown();
gpa.destroy(g);
g.deinit();
return e;
};
std.log.info("RoCE all-gather: {d} ranks, {d} HCA(s), {d} stripe(s) a peer, shards up to {d} KiB by RDMA writes", .{ g.world, g.n_hca, g.plan.stripes, g.max_bytes >> 10 });
Expand Down Expand Up @@ -429,16 +425,18 @@ pub const Gather = struct {
/// The proxy: spins on the doorbell and posts each sequence in order (a missed one from its slot's size).
fn proxy(g: *Gather) void {
const c = g.ctrl();
const wfe = host_wait.on();
const m: u64 = if (wfe) 7 else 63; // a park lasts up to 1 ms: the CQs drain every 8 parks, or every 64 polls
var idle: u64 = 0;
while (g.running.load(.monotonic)) {
const seq = @atomicLoad(u32, &c[layout.c_seq], .acquire);
if (seq == g.last_seq) {
idle += 1;
if (idle % 64 == 0) for (0..g.n_hca) |h| g.drain(h) catch {
if (idle & m == 0) for (0..g.n_hca) |h| g.drain(h) catch {
g.failed.store(true, .release);
return;
};
if (idle >= idle_spins) nap.pause();
if (wfe) host_wait.idle(&c[layout.c_seq], seq, idle) else if (idle >= idle_spins) nap.pause();
continue;
}
idle = 0;
Expand Down
2 changes: 2 additions & 0 deletions zig/src/cuda/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub const cublaslt = @import("cublaslt.zig");
pub const nccl = @import("nccl.zig");
pub const roce = @import("roce.zig");
pub const roce_pair_rule = @import("roce_pair_rule.zig");
pub const host_wait = @import("host_wait.zig");
pub const triton = @import("triton.zig");
pub const aot = @import("aot.zig");
pub const aot_pdl = @import("aot_pdl.zig");
Expand Down Expand Up @@ -117,6 +118,7 @@ test {
_ = train_q4;
_ = train_attn;
_ = @import("memory.zig");
_ = @import("host_wait.zig");
_ = @import("download_stage_test.zig");
_ = memory_receipt;
_ = @import("grouped.zig");
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/glm/cuda_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,11 @@ pub const max_drafts = 15;
/// A greedy pick as it crosses ranks: (value, id) and padding, so the RoCE gather (16-byte packs) can carry it.
const pair_bytes = 16;
const pick_rows = @import("cuda_engine_pick.zig").pick_rows;

/// A prompt pass's chunk rows (decode.prefill's).
pub const prompt_rows = fw.prefill_rows;
pub const solo_rows = fw.solo_rows;
pub const max_together = @import("cuda_state.zig").prompt_heads;
pub const Prompt = struct { slot: u32, ids: []const u32 };

/// A shared verify's max rows and streams: under hc_pre's 64-row block change; 16 streams take 2 rows each.
pub const shared_rows = 32;
pub const max_shared = 16;
Expand Down Expand Up @@ -84,6 +82,7 @@ pub const Engine = struct {
bm: fw.Buffers, // the MTP head's rows
bs: ?fw.Buffers = null, // shared verify windows (with the MTP head, as the lane core shares only then)
pairs: cuda.DeviceBuffer, // every rank's (value, id) of a greedy draw
waiter: cuda.host_wait.Waiter = .{}, // TF_CUDA_HOST_WFE: the greedy picks' parked waits
smp: sampler.Sampler,
seqs: std.ArrayList(?*Seq) = .empty, // every stream's sequence by slot (the lane backend's), slot 0 made at init
cur: *Seq = undefined, // the bound slot's: every step below runs on it
Expand Down Expand Up @@ -261,6 +260,7 @@ pub const Engine = struct {
e.prompt_out.free();
e.smp.deinit();
e.pairs.free();
e.waiter.deinit();
if (e.bs) |*b| b.deinit();
e.bm.deinit();
e.bd.deinit();
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/glm/cuda_engine_pick.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub fn greedyRows(e: *Engine, logits: u64, rows: usize, out: []u32) !void {
try cuda_pdl.launch(e.m.glue.top1, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 } }, e.stream, &a);
}
if (e.group) |g| try g.allGather(e.stream, mine, e.pairs.ptr, bytes) else try e.lib.check(e.lib.api.ncclAllGather(mine, e.pairs.ptr, bytes, .u8, e.comm, e.stream.handle), "ncclAllGather");
try e.stream.synchronize();
try e.waiter.synchronize(e.stream);
try e.checkGathers();
var all: [ranks.max_world * pick_rows][4]u32 = undefined;
try cuda.memory.download(e.d, e.pairs.ptr, std.mem.asBytes(&all)[0 .. world * bytes]);
Expand Down Expand Up @@ -58,7 +58,7 @@ fn pick(e: *Engine, logits: u64, sums: bool) !chance.Pick {
const stamp = @import("cuda_prof.zig").span(e.profiling_prompt, e.stream, .token_gather);
if (e.group) |g| try g.allGather(e.stream, mine, e.pairs.ptr, pair_bytes) else try e.lib.check(e.lib.api.ncclAllGather(mine, e.pairs.ptr, pair_bytes, .u8, e.comm, e.stream.handle), "ncclAllGather");
stamp.end();
try e.stream.synchronize();
try e.waiter.synchronize(e.stream);
try e.checkGathers();
var all: [ranks.max_world][4]u32 = undefined; // Engine.init refuses a larger world
try cuda.memory.download(e.d, e.pairs.ptr, std.mem.asBytes(&all)[0 .. world * pair_bytes]);
Expand Down
4 changes: 3 additions & 1 deletion zig/src/families/glm/cuda_follow.zig
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub const Link = struct {
ids: []u32, // host copy of the last step's ids
gpa: std.mem.Allocator,
wait: bool, // TF_GLM_LINK_WAIT=1: every step uploaded and waited for, as before the put
waiter: cuda.host_wait.Waiter = .{}, // TF_CUDA_HOST_WFE: the step broadcast's parked wait
asleep: bool = false, // rank 0: the other ranks sleep on their lines (cuda.tp_watch) until its next step

pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, lib: *const cuda.nccl.Library, comm: cuda.nccl.Comm, stream: cuda.Stream, asked_ids: usize) !Link {
Expand All @@ -77,11 +78,12 @@ pub const Link = struct {
if (@import("cuda_disk_ranks.zig").link == l) @import("cuda_disk_ranks.zig").link = null;
l.gpa.free(l.ids);
l.buf.free();
l.waiter.deinit();
}

fn bcast(l: *Link, bytes: usize) !void {
try l.post(bytes);
try l.stream.synchronize();
try l.waiter.synchronize(l.stream);
}

fn post(l: *Link, bytes: usize) !void {
Expand Down
4 changes: 3 additions & 1 deletion zig/src/families/glm/cuda_sampler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub const Sampler = struct {
meta: cuda.DeviceBuffer,
tok: cuda.DeviceBuffer,
prob: cuda.DeviceBuffer,
waiter: cuda.host_wait.Waiter = .{}, // TF_CUDA_HOST_WFE: the draw's parked wait

pub fn init(d: *const cuda.Driver, vocab: usize, rows: usize) !Sampler {
var m = try cuda.Module.load(d, cuda.kernels.sample);
Expand All @@ -66,6 +67,7 @@ pub const Sampler = struct {

pub fn deinit(s: *Sampler) void {
s.prob.free();
s.waiter.deinit();
s.tok.free();
s.meta.free();
s.rule.free();
Expand Down Expand Up @@ -96,7 +98,7 @@ pub const Sampler = struct {
args.add(s.tok.ptr);
args.add(s.prob.ptr);
try cuda.launch.launch(s.tf_draw, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 1024 } }, stream, &args);
try stream.synchronize();
try s.waiter.synchronize(stream);
try s.tok.download(0, std.mem.sliceAsBytes(out[0..rows]));
}

Expand Down
1 change: 1 addition & 0 deletions zig/src/platform/environment.zig
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ const stock_rules = [_]Rule{
.{ .name = "TENSORFOLD_LFM2_KV_PAGES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (unset leases pool pages)" },
.{ .name = "TENSORFOLD_LFM3_KV_PAGES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (unset leases pool pages)" },
.{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (an integrated GPU on Linux: 1 counts /proc/meminfo, 0 the CUDA pool)" },
.{ .name = "TF_CUDA_HOST_WFE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (1: the RoCE proxy and GLM's token readback waits park the core in aarch64 WFET instead of polling; needs FEAT_WFxT)" },
.{ .name = "TF_ROCE_GID_INDEX", .scope = .cuda, .kind = .u32, .forms = "a whole GID index from 0 to 2147483647" },
.{ .name = "TF_QWEN35_CHUNK_SOLO", .scope = .cuda, .kind = .size, .forms = "a solo prompt pass's rows, 4096 (off) or 8192" },
.{ .name = "TF_ROCE_HCA", .scope = .cuda, .kind = .names, .max = 2, .forms = "one or two RDMA device names, comma-separated (the RoCE all-gather stripes over at most two)" },
Expand Down
12 changes: 12 additions & 0 deletions zig/src/platform/environment_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,18 @@ test "environment: word switches take 0 and 1 and the word forms in any case; ex
try t.expectError(error.InvalidEnvironment, e.parse("TF_DSV41_KV_SPLIT", "true"));
}

test "environment: the host-wait switch is exact 0 or 1, refused by name when the CUDA backend starts" {
const name = "TF_CUDA_HOST_WFE";
for ([_][]const u8{ "true", "on", "yes", "01", " 1", "1 ", "2" }) |raw| {
try t.expectError(error.InvalidEnvironment, e.parse(name, raw));
const why = (try e.refusal(a, Env{ .name = name, .raw = raw }, .{ .cuda = true })).?;
defer a.free(why);
try t.expect(std.mem.indexOf(u8, why, name) != null);
}
try t.expect(!try e.value(bool, name, null, false));
try t.expect(!try e.value(bool, name, "0", false));
try t.expect(try e.value(bool, name, "1", false));
}
test "environment: the keep-others switch is exact 0 or 1, checked when the CUDA backend starts" {
const name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS";
for ([_][]const u8{ "true", "on", "yes", "01", " 1", "1 ", "2" }) |raw| {
Expand Down
2 changes: 2 additions & 0 deletions zig/src/platform/environment_valid_cases.zig
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub const valid = [_]Case{
.{ .name = "TF_CUDA_SEGMENTS", .raw = "4", .n = 4 },
.{ .name = "TF_CUDA_CARVEOUT", .raw = "0", .n = 0 },
.{ .name = "TF_CUDA_CARVEOUT", .raw = "1", .n = 1 },
.{ .name = "TF_CUDA_HOST_WFE", .raw = "0", .n = 0 },
.{ .name = "TF_CUDA_HOST_WFE", .raw = "1", .n = 1 },
.{ .name = "TF_CUDA_CARVEOUT_MIB", .raw = "1792", .n = 1792 },
.{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "0", .n = 0 },
.{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "1", .n = 1 },
Expand Down
Loading
Loading