Skip to content
Closed
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
12 changes: 12 additions & 0 deletions docs/environment-names.md
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,8 @@ reports the setting's own value, does not count as logging.
| `TF_QWEN_KV_SHARE` | release, tool, test | other |
| `TF_QWEN_KV_SNAPSHOT_GPU` | release, tool, test | other |
| `TF_QWEN_LAZY_SAVE` | release, tool, test | other |
| `TF_QWEN_MERGE_WIDE` | release, tool, test | other |
| `TF_QWEN_MERGE_WIDE_VERIFY` | release, tool, test | other |
| `TF_QWEN_LAZY_SAVE_VERIFY` | release, tool, test | other |
| `TF_QWEN_PDL` | release, tool, test | other |
| `TF_QWEN_POOL_LOG` | release, tool, test | logs |
Expand Down Expand Up @@ -853,6 +855,16 @@ reports the setting's own value, does not count as logging.
| `TF_TP_STATS` | release, tool, test | logs |
| `TF_TP_TRACE` | release, tool, test | logs |
| `TF_TP_WORLD` | release, tool, test | other |
| `TF_X_DRAFT_CACHE` | release, tool, test | writes, loads |
| `TF_X_DRAFT_CACHE_DIR` | release, tool, test | writes, loads |
| `TF_X_EXE_PREHASH` | release, tool, test | other |
| `TF_X_GEMV_MANY` | release, tool, test | other |
| `TF_X_MLP_SEG` | release, tool, test | other |
| `TF_X_PROBE_CACHE` | release, tool, test | writes, loads |
| `TF_X_PROBE_CACHE_DIR` | release, tool, test | writes, loads |
| `TF_X_START_COPY` | release, tool, test | other |
| `TF_X_START_HASH` | release, tool, test | logs |
| `TF_X_START_LOG` | release, tool, test | logs |
| `TMP` | release, tool, test | writes |
| `TMPDIR` | release, tool, test | writes |
| `USERPROFILE` | release, tool, test | writes-content, loads |
Expand Down
10 changes: 10 additions & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ 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_QWEN_LAZY_SAVE` | Qwen 3.5/3.8 on CUDA: exactly `0` or `1`, read once; unset is `0`. `1` leaves a kept prompt state's key/value rows in the whole (unpaged) cache that wrote them: a save copies only the recurrent state, and a restore into the same cache copies only that back. The rows reach the host, into one pinned buffer a conversation's states share as prefixes, before the cache rewrites them or the disk tier reads the state. A save leaves its rows only when a host buffer already has room for them (the cache's own, or a budgeted spare it then takes); otherwise it copies everything as with the switch unset, so no turn pins more than it does today. A conversation's buffer is freed with the last state that reads it. States are charged their full size against `--prompt-cache-gib`, as with the switch unset. Bytes are only moved, so tokens and output are unchanged; paged caches and device-memory saves keep today's path. |
| `TF_QWEN_MERGE_WIDE` | Qwen 3.5/3.8 on CUDA: exactly `0` or `1`, read once when the kernels resolve; unset is `0`. `1` runs the decode attention merge with a thread a head value instead of a warp a (row, query head): every thread walks the row's chunk partials in the same order with the same operands, so each output keeps the warp merge's bits and tokens are unchanged. |
| `TF_QWEN_MERGE_WIDE_VERIFY` | With `TF_QWEN_MERGE_WIDE=1`: `0`, `1` or `2`; unset is `0`. `1` also runs the warp merge into the logits scratch and compares the live rows with the wide merge's byte for byte, trapping on a difference; `2` plants one difference, so a run that does not trap proves nothing. A check for new GPUs and checkpoints, slower than either path alone. |
| `TF_X_START_LOG` | Qwen and every CUDA start: exactly `0` or `1`, read once; unset is `0`. `1` prints one line a start-up phase on stderr, `[x-start] <unix seconds.micros> <what>`, with the weight copies so far: their count, bytes, host and device time. Wall-clock stamps, so a launcher's own stamp before exec lines up. Diagnostics only. |
| `TF_X_START_HASH` | With a CUDA start: exactly `0` or `1`, read once; unset is `0`. `1` hashes the loaded weights after the load (the engine's arena, the drafter's arena and its host codebooks) and prints one line each, the proof that a load switch moved the same bytes. Diagnostics only, slower than a plain start. |
| `TF_X_START_COPY` | With a CUDA start: `0` to `32`, read once; unset or `0` is off. `N` uploads the weights through three 16 MiB pinned buffers that `N` host threads fill while the device copy of the piece before runs on the default stream, instead of one thread copying into a pageable buffer and the driver copying that again. The same bytes land in the same order before an upload returns, so tokens and output are unchanged; the setting ends when the model load does. |
| `TF_X_EXE_PREHASH` | With a CUDA start: exactly `0` or `1`, read once; unset is `0`. `1` reads the running binary once on a thread of its own while the model loads, into the two SHA-256 streams a start needs later (the kept-state identity and the window-cost key), each reader taking the result only for the very file it would have hashed. The same bytes into the same hashers, so the same digests. |
| `TF_X_DRAFT_CACHE` | Qwen 3.5/3.8 on CUDA with `--drafter`, Linux only: exactly `0` or `1`, read once; unset is `0`. `1` keeps the drafter's quantized affine-4 tables on disk, keyed on the quantizer's version, the drafter file's identity and its shape, so a start reads 3.8 GB of bf16 weights' tables instead of quantizing them again. A start verifies every block hash before it uses a byte and checks each entry's shape against the projection it stands for; any miss, mismatch or error quantizes as before. The tables are the bytes `quantize` returned, so replies do not change. |
| `TF_X_DRAFT_CACHE_DIR` | With `TF_X_DRAFT_CACHE=1`: a path without control characters; unset keeps the tables in `~/.cache/tensorfold/draft-quant`. |
| `TF_X_PROBE_CACHE` | Qwen 3.5/3.8 on CUDA with `--learn-conversations`: `0`, `1` or `verify`; unset is `0`. `1` keeps the kept-state identity probe (a 4,136-token prompt pass whose saved state is hashed into the store's identity, timed for the disk-or-prefill rate) in a small file keyed on the code, the checkpoint, the device, the command line and the switches, so the next start reads it instead of running the probe. `verify` runs the probe anyway, says whether the kept hash equals the fresh one, and keeps the fresh one. Any miss or error runs the probe as before; the kept rate is a timing of paths that give the same rows. |
| `TF_X_PROBE_CACHE_DIR` | With `TF_X_PROBE_CACHE` set: a path without control characters; unset keeps the records in `~/.cache/tensorfold/x-start-probe`. |
| `TF_QWEN_LAZY_SAVE_VERIFY` | With `TF_QWEN_LAZY_SAVE=1`: exactly `0` or `1`, read once; unset is `0`. `1` also copies every lazy save's rows to the host and, at every restore that copied no rows, compares the cache's rows with them piece by piece, logging each difference as `VERIFY:`. A check, 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_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 |
Expand Down
2 changes: 2 additions & 0 deletions zig/kernels/cuda/qwen35.cu
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,8 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35_attn_merge(Geo geo, cons
for (int i = 0; i < DPL; i++) OUT[(m * QH + qh) * HD + lane * DPL + i] = __float2bfloat16_rn(acc[i] / lsum);
}

// TF_QWEN_MERGE_WIDE and its verify mode: a thread per head value, and the byte check against the warp merge.
#include "qwen35_merge_wide.cuh"
// A 256-thread block's outputs' 64-entry group sums into XS (null: none); rows are whole groups, so a block's are too.
__device__ __forceinline__ void block_sums(__nv_bfloat16* done, size_t total, float* XS) {
if (XS == nullptr) return;
Expand Down
46 changes: 46 additions & 0 deletions zig/kernels/cuda/qwen35_merge_wide.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// tf_q35_attn_merge with 256 threads a (head, row), a value each: the same chunk loop and fmaf operands, same bytes.
extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_merge_wide(Geo geo, const float* __restrict__ PM, const float* __restrict__ PL,
const float* __restrict__ PO, const Seg* __restrict__ segs,
const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc,
const int* __restrict__ P, __nv_bfloat16* __restrict__ OUT) {
static_assert(HD == 256, "a thread per head value");
__shared__ float sm[MAXCH], sl[MAXCH];
const int QH = geo.qh;
const int d = threadIdx.x, qh = blockIdx.x;
if (past_rows(P, blockIdx.y)) return;
const size_t m = blockIdx.y;
const int keys = segs[rowseg[m]].len + rows_seen(rowanc[m]);
const int ck = chunk_keys(keys), nch = (keys + ck - 1) / ck;
const size_t base = (m * QH + qh) * MAXCH;
if (d < nch) {
sm[d] = PM[base + d];
sl[d] = PL[base + d];
}
__syncthreads();
float mx = -INFINITY;
for (int c = 0; c < nch; c++)
if (sl[c] > 0.0f) mx = fmaxf(mx, sm[c]);
float lsum = 0.0f, acc = 0.0f;
#pragma unroll 8
for (int c = 0; c < nch; c++) {
if (!(sl[c] > 0.0f)) continue;
const float e = __expf(sm[c] - mx);
lsum = fmaf(sl[c], e, lsum);
acc = fmaf(PO[(base + c) * HD + d], e, acc);
}
OUT[(m * QH + qh) * HD + d] = __float2bfloat16_rn(acc / lsum);
}

// TF_QWEN_MERGE_WIDE_VERIFY: the wide merge's live rows against the warp merge's, byte for byte; a difference traps.
extern "C" __global__ void __launch_bounds__(256) tf_q35_merge_check(const unsigned short* __restrict__ A, const unsigned short* __restrict__ B,
int width, const int* __restrict__ P, int plant) {
if (past_rows(P, blockIdx.x)) return;
const size_t row = blockIdx.x;
for (int i = threadIdx.x; i < width; i += blockDim.x) {
bool bad = A[row * width + i] != B[row * width + i];
// plant flips row 0's first value: the negative control, a run that does not trap proves nothing.
if (plant && row == 0 && i == 0) bad = !bad;
if (bad) __trap();
}
}

2 changes: 2 additions & 0 deletions zig/src/core/lanes/cost_identity.zig
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const FileReader = struct {
};

pub fn fromFile(file: std.Io.File, io: std.Io, trace: bool) !Seed {
// x-start (arm 11): the seed TF_X_EXE_PREHASH computed while the model loaded, when it read this very file
if (!trace and @import("builtin").os.tag == .linux) if (@import("sys").file_identity.prehashedFor(file.handle)) |p| if (p.size < max_executable_bytes) return .{ .prefix = p.seed, .executable_sha256 = null };
return fromSource(FileReader{ .file = file, .io = io }, trace);
}

Expand Down
15 changes: 13 additions & 2 deletions zig/src/cuda/affine4_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub const Affine4Kernels = struct {
split: ?Split, // every GPU but GB10: lane_gemv's slices on CTAs of their own (one stream's decode() at a time)
pdl: bool, // GB10: the decode kernels launch with programmatic dependent launch
wide_verify: bool, // off GB10: verify windows of 17 to 32 rows share one weight pass (sm_120, when its engine says)
// gate sweep (test only, default off): GB10's paths on other GPUs, read once at load
many_test: bool = false, // TF_X_GEMV_MANY=1: decodeMany takes gemvMany (one PDL grid, K slices kept in a CTA)
seg_mlp: bool = false, // TF_X_MLP_SEG=1: decode MLP gate and up as one decodeMany launch (windows of 16 rows or fewer)

/// From loaded qmm_group, qmm_prefill, lane_gemv and affine4_pack modules; GB10 decodes without the split form.
pub fn resolve(d: *const Driver, group_mod: Module, prefill_mod: Module, gemv_mod: Module, pack_mod: Module, sms: usize, gb10: bool) !Affine4Kernels {
Expand Down Expand Up @@ -98,6 +101,9 @@ pub const Affine4Kernels = struct {
a.gemv_blocks = @max(1, try a.gemv_fn.occupancy(128, group_smem)) * sms;
a.pdl = gb10;
a.wide_verify = false;
a.many_test = sweepOn(@import("sys").environment.rawText("TF_X_GEMV_MANY"));
a.seg_mlp = sweepOn(@import("sys").environment.rawText("TF_X_MLP_SEG"));
if (a.many_test or a.seg_mlp) std.log.info("gate sweep: {s}TF_X_GEMV_MANY {s}TF_X_MLP_SEG", .{ if (a.many_test) "on" else "off", if (a.seg_mlp) "on" else "off" });
a.split = if (gb10) null else try Split.initFor(d, segs_max);
return a;
}
Expand Down Expand Up @@ -151,7 +157,7 @@ pub const Affine4Kernels = struct {
/// decode() of each projection of one input; without GB10 one segmented launch, each keeping its split's bits.
pub fn decodeMany(a: *const Affine4Kernels, s: Stream, x: u64, xs: u64, outs: []const Out, rows: usize) !void {
if (rows > max_rows) return error.WindowTooWide;
if (a.pdl and outs.len > 1) return a.gemvMany(s, x, xs, outs, rows);
if ((a.pdl or a.many_test) and outs.len > 1) return a.gemvMany(s, x, xs, outs, rows);
const sp = a.split orelse {
for (outs) |o| try a.decode(s, x, xs, o.q, o.out, rows);
return;
Expand Down Expand Up @@ -213,7 +219,7 @@ pub const Affine4Kernels = struct {

/// One decode-sized PDL grid over independent persistent member grids.
pub fn gemvMany(a: *const Affine4Kernels, s: Stream, x: u64, xs: u64, outs: []const Out, rows: usize) !void {
if (!a.pdl or rows == 0 or rows > max_rows) return error.WindowTooWide;
if (!(a.pdl or a.many_test) or rows == 0 or rows > max_rows) return error.WindowTooWide;
if (outs.len < 2 or outs.len > segs_max) return error.TooManyParts;
var parts: linear.GemvManyParts = std.mem.zeroes(linear.GemvManyParts);
var blocks: usize = 0;
Expand Down Expand Up @@ -432,6 +438,11 @@ test {
_ = @import("gemv_many_host_test.zig");
}

/// A gate-sweep switch: exactly "1" turns one on, anything else (unset included) leaves it off.
fn sweepOn(v: ?[]const u8) bool {
return if (v) |s| std.mem.eql(u8, s, "1") else false;
}

/// Only the two ordinary Qwen prompt projections from the GB10 profile use this opt-in tile.
pub fn promptStages2Shape(n: usize, k: usize, rows: usize) bool {
return rows > 16 and rows <= 8192 and n == 5120 and (k == 17408 or k == 6144);
Expand Down
2 changes: 2 additions & 0 deletions zig/src/cuda/context.zig
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ pub const Context = struct {
var dev: abi.Device = 0;
try d.check(d.api.cuDeviceGet(&dev, ordinal), "cuDeviceGet");
var ctx: abi.Context = null;
@import("xstart.zig").mark("primary context retain begins");
try d.check(d.api.cuDevicePrimaryCtxRetain(&ctx, dev), "cuDevicePrimaryCtxRetain");
@import("xstart.zig").mark("primary context retained");
errdefer _ = d.api.cuDevicePrimaryCtxRelease_v2(dev);
try d.check(d.api.cuCtxSetCurrent(ctx), "cuCtxSetCurrent");
try @import("context_health.zig").retain(d, ctx);
Expand Down
10 changes: 7 additions & 3 deletions zig/src/cuda/copy_source.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const streams = @import("stream.zig");
const budget = @import("copy_source_budget.zig");
const durable = std.heap.page_allocator;
const capture_scope = @import("copy_source_capture.zig");
const start_copy = @import("start_copy.zig");
threadlocal var current_context: abi.Context = null;
var mutex: custody_sync.Mutex = .{};
var changed: custody_sync.Condition = .{};
Expand Down Expand Up @@ -210,7 +211,7 @@ fn completed(d: *const Driver, context: abi.Context, stream: abi.Stream, all: bo
releaseTracked(n);
}
}
fn hasRetained(d: *const Driver, context: abi.Context) bool {
pub fn hasRetained(d: *const Driver, context: abi.Context) bool {
lock();
defer unlock();
var at = head;
Expand Down Expand Up @@ -310,6 +311,10 @@ pub fn streamDone(d: *const Driver, stream: abi.Stream) @import("driver.zig").Er
/// The allocator argument is a compatibility hint; escaped custody never borrows it.
pub fn synchronousCopy(d: *const Driver, dst: u64, bytes: []const u8, gpa: std.mem.Allocator) @import("driver.zig").Error!void {
if (capture_scope.active(d, current_context)) return error.UnownedCaptureSource;
if (bytes.len > 0 and start_copy.mine()) {
if (hasRetained(d, current_context)) try synchronizeContext(d);
return start_copy.copy(d, current_context, dst, bytes);
}
var at: usize = 0;
while (at < bytes.len) {
const n = @min(bytes.len - at, 64 << 20);
Expand All @@ -329,8 +334,7 @@ fn syncChunk(d: *const Driver, dst: u64, bytes: []const u8, _: std.mem.Allocator
n.driver = @intFromPtr(d);
n.context = current_context;
n.data = .{ .cpu = owned };
@memcpy(owned, bytes);
const result = d.api.cuMemcpyHtoD_v2(dst, owned.ptr, owned.len);
const result = start_copy.timedUpload(d, dst, owned, bytes);
synchronizeStream(d, null) catch |e| {
transferred = true;
n.failed = true;
Expand Down
2 changes: 2 additions & 0 deletions zig/src/cuda/driver.zig
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ pub const Driver = struct {
};
}
const d: Driver = .{ .lib = lib, .api = api, .func_name = lib.lookup(FuncGetName, "cuFuncGetName") };
@import("xstart.zig").mark("cuInit begins");
try d.check(api.cuInit(0), "cuInit");
@import("xstart.zig").mark("cuInit done");
var buf: [256]u8 = undefined;
if (d.tooOld(&buf)) |why| {
std.log.err("{s}", .{why});
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 @@ -5,6 +5,8 @@ pub const abi = @import("abi.zig");
pub const Driver = @import("driver.zig").Driver;
pub const priority_copies = @import("priority_copies.zig");
pub const copy_source = @import("copy_source.zig");
pub const start_copy = @import("start_copy.zig");
pub const xstart = @import("xstart.zig");
pub const completion = @import("completion.zig");
pub const paging_test_device = if (@import("builtin").is_test) @import("paging_test_device.zig") else struct {};
pub const Error = @import("driver.zig").Error;
Expand Down
Loading
Loading