diff --git a/docs/environment-names.md b/docs/environment-names.md index 3cf01392e09..942818c6ba4 100644 --- a/docs/environment-names.md +++ b/docs/environment-names.md @@ -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 | @@ -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 | diff --git a/docs/environment.md b/docs/environment.md index f4a24f451c9..b57f1ef0123 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -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] `, 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 | diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index e0a1ce7d8db..58b1fb16db3 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -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; diff --git a/zig/kernels/cuda/qwen35_merge_wide.cuh b/zig/kernels/cuda/qwen35_merge_wide.cuh new file mode 100644 index 00000000000..e13f2652355 --- /dev/null +++ b/zig/kernels/cuda/qwen35_merge_wide.cuh @@ -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(); + } +} + diff --git a/zig/src/core/lanes/cost_identity.zig b/zig/src/core/lanes/cost_identity.zig index b678dae0a50..c7cc38fbe98 100644 --- a/zig/src/core/lanes/cost_identity.zig +++ b/zig/src/core/lanes/cost_identity.zig @@ -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); } diff --git a/zig/src/cuda/affine4_kernels.zig b/zig/src/cuda/affine4_kernels.zig index a4cfda55697..588624b9bc1 100644 --- a/zig/src/cuda/affine4_kernels.zig +++ b/zig/src/cuda/affine4_kernels.zig @@ -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 { @@ -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; } @@ -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; @@ -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; @@ -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); diff --git a/zig/src/cuda/context.zig b/zig/src/cuda/context.zig index 3f82a4d9c2c..a8e9c4de850 100644 --- a/zig/src/cuda/context.zig +++ b/zig/src/cuda/context.zig @@ -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); diff --git a/zig/src/cuda/copy_source.zig b/zig/src/cuda/copy_source.zig index 95d4bd672c2..8be541fdaf3 100644 --- a/zig/src/cuda/copy_source.zig +++ b/zig/src/cuda/copy_source.zig @@ -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 = .{}; @@ -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; @@ -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); @@ -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; diff --git a/zig/src/cuda/driver.zig b/zig/src/cuda/driver.zig index 2ee2d530d7c..47d37368af9 100644 --- a/zig/src/cuda/driver.zig +++ b/zig/src/cuda/driver.zig @@ -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}); diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 1ef28094724..0850a2d5d06 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -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; diff --git a/zig/src/cuda/start_copy.zig b/zig/src/cuda/start_copy.zig new file mode 100644 index 00000000000..989d6abfc9e --- /dev/null +++ b/zig/src/cuda/start_copy.zig @@ -0,0 +1,198 @@ +//! TF_X_START_COPY=N: a synchronous upload through pinned buffers N host threads fill, the same bytes, the same order. +const std = @import("std"); +const memory = @import("memory.zig"); +const abi = @import("abi.zig"); +const custody_sync = @import("copy_source_sync.zig"); +const streams = @import("stream.zig"); +const xstart = @import("xstart.zig"); +const source = @import("copy_source.zig"); +const Driver = @import("driver.zig").Driver; + +// Three 16 MiB pinned buffers: N host threads fill one while the device copy of the piece before runs. +const fast_piece = 16 << 20; +const fast_slots = 3; +const FastJob = struct { dst: [*]u8 = undefined, src: [*]const u8 = undefined, len: usize = 0 }; +var fast_threads_env: ?usize = null; +fn fastThreads() usize { + if (fast_threads_env) |n| return n; + const n = xstart.copyThreads(); + fast_threads_env = n; + return n; +} +// Only the thread between begin and end (the model load) takes the fast path; every other upload does not. +var fast_owner: std.atomic.Value(u64) = .init(0); +fn threadKey() u64 { + return @as(u64, std.Thread.getCurrentId()) + 1; +} +pub fn mine() bool { + const o = fast_owner.load(.acquire); + return o != 0 and o == threadKey(); +} +/// The calling thread's uploads take the fast path until end (only when TF_X_START_COPY is set). +pub fn begin() void { + if (fastThreads() == 0) return; + fast_owner.store(threadKey(), .release); +} +/// Back to the old path; the pinned buffers are freed and the copy threads stop. Idempotent. +pub fn end() void { + if (fast_owner.load(.acquire) == 0) return; + fastRelease(); + fast_owner.store(0, .release); +} +var fast_d: ?*const Driver = null; +var fast_context: abi.Context = null; +var fast_buf: [fast_slots]?memory.HostBuffer = @splat(null); +var fast_ev: [fast_slots]abi.Event = @splat(null); +var fast_used: [fast_slots]bool = @splat(false); +var fast_poisoned = false; +var fast_workers: [32]?std.Thread = @splat(null); +var fast_count: usize = 0; // threads copying a piece, the caller's included +var fast_m: custody_sync.Mutex = .{}; +var fast_go: custody_sync.Condition = .{}; +var fast_done: custody_sync.Condition = .{}; +var fast_gen: u64 = 0; +var fast_pending: usize = 0; +var fast_quit = false; +var fast_job: FastJob = .{}; + +fn fastSlice(job: FastJob, i: usize, n: usize) void { + const from = job.len * i / n; + const to = job.len * (i + 1) / n; + if (to > from) @memcpy(job.dst[from..to], job.src[from..to]); +} + +fn fastWorker(i: usize) void { + var seen: u64 = 0; + while (true) { + fast_m.lock(); + while (fast_gen == seen and !fast_quit) fast_go.wait(&fast_m); + if (fast_quit) { + fast_m.unlock(); + return; + } + seen = fast_gen; + const job = fast_job; + const n = fast_count; + fast_m.unlock(); + fastSlice(job, i, n); + fast_m.lock(); + fast_pending -= 1; + if (fast_pending == 0) fast_done.broadcast(); + fast_m.unlock(); + } +} + +/// `dst` gets `src`'s bytes, copied by every pool thread (small pieces by the caller alone). +fn fastParallel(dst: []u8, src: []const u8) void { + const job: FastJob = .{ .dst = dst.ptr, .src = src.ptr, .len = src.len }; + if (fast_count <= 1 or src.len < 1 << 20) return fastSlice(job, 0, 1); + fast_m.lock(); + fast_job = job; + fast_pending = fast_count - 1; + fast_gen += 1; + fast_go.broadcast(); + fast_m.unlock(); + fastSlice(job, 0, fast_count); + fast_m.lock(); + while (fast_pending > 0) fast_done.wait(&fast_m); + fast_m.unlock(); +} + +fn fastSetup(d: *const Driver, context: abi.Context) @import("driver.zig").Error!void { + if (fast_poisoned) return error.Invalid; + if (fast_d) |old| { + if (old == d and fast_context == context) return; + fastRelease(); + } + errdefer fastRelease(); + fast_d = d; + fast_context = context; + for (&fast_buf, &fast_ev) |*b, *e| { + b.* = try memory.HostBuffer.alloc(d, fast_piece); + try d.check(d.api.cuEventCreate(e, abi.event_disable_timing), "cuEventCreate"); + } + const want = fastThreads(); + fast_quit = false; + fast_count = 1; + for (1..want) |i| { + fast_workers[i] = std.Thread.spawn(.{}, fastWorker, .{i}) catch break; + fast_count = i + 1; + } +} + +/// Waits for the pinned buffers' last copies, frees them and stops the copy threads (the next upload sets up again). +pub fn fastRelease() void { + const d = fast_d orelse return; + for (&fast_buf, &fast_ev, &fast_used) |*b, *e, *u| { + if (u.* and e.* != null and d.api.cuEventSynchronize(e.*) != abi.success) { + fast_poisoned = true; // a copy may still read the buffer: keep it, refuse the fast path from now on + return; + } + u.* = false; + if (e.* != null) _ = d.api.cuEventDestroy_v2(e.*); + e.* = null; + if (b.*) |*x| x.free(); + b.* = null; + } + fast_m.lock(); + fast_quit = true; + fast_go.broadcast(); + fast_m.unlock(); + for (&fast_workers) |*w| if (w.*) |t| { + t.join(); + w.* = null; + }; + fast_count = 0; + fast_d = null; + fast_context = null; +} + +pub fn copy(d: *const Driver, context: abi.Context, dst: u64, bytes: []const u8) @import("driver.zig").Error!void { + try fastSetup(d, context); + const timed = xstart.enabled(); + var host_ns: u64 = 0; + var at: usize = 0; + var piece: usize = 0; + errdefer fast_poisoned = true; // a failed copy may still read a buffer: never free or reuse them + while (at < bytes.len) : (piece += 1) { + const n = @min(bytes.len - at, fast_piece); + const k = piece % fast_slots; + if (fast_used[k]) try d.check(d.api.cuEventSynchronize(fast_ev[k]), "cuEventSynchronize"); + fast_used[k] = false; + const buf = fast_buf[k].?.bytes[0..n]; + const t0 = if (timed) xstart.monoNs() else 0; + fastParallel(buf, bytes[at..][0..n]); + if (timed) host_ns += xstart.monoNs() - t0; + try d.check(d.api.cuMemcpyHtoDAsync_v2(std.math.add(u64, dst, at) catch return error.Invalid, buf.ptr, n, null), "cuMemcpyHtoDAsync"); + try d.check(d.api.cuEventRecord(fast_ev[k], null), "cuEventRecord"); + fast_used[k] = true; + at += n; + } + const t1 = if (timed) xstart.monoNs() else 0; + try source.synchronizeStream(d, null); + for (&fast_used) |*u| u.* = false; + if (timed) { + _ = xstart.copy_host_ns.fetchAdd(host_ns, .monotonic); + _ = xstart.copy_dev_ns.fetchAdd(xstart.monoNs() - t1, .monotonic); + _ = xstart.copy_bytes.fetchAdd(bytes.len, .monotonic); + _ = xstart.copy_calls.fetchAdd(1, .monotonic); + } +} + + + +/// One default upload with the x-start timing marks around it: the host copy, then the device copy's issue. +pub fn timedUpload(d: *const Driver, dst: u64, owned: []u8, bytes: []const u8) abi.Result { + const timed = xstart.enabled(); + const t0 = if (timed) xstart.monoNs() else 0; + @memcpy(owned, bytes); + const t1 = if (timed) xstart.monoNs() else 0; + const result = d.api.cuMemcpyHtoD_v2(dst, owned.ptr, owned.len); + if (timed) { + _ = xstart.copy_host_ns.fetchAdd(t1 - t0, .monotonic); + _ = xstart.copy_dev_ns.fetchAdd(xstart.monoNs() - t1, .monotonic); + _ = xstart.copy_bytes.fetchAdd(bytes.len, .monotonic); + _ = xstart.copy_calls.fetchAdd(1, .monotonic); + } + return result; +} diff --git a/zig/src/cuda/xstart.zig b/zig/src/cuda/xstart.zig new file mode 100644 index 00000000000..b9635c39803 --- /dev/null +++ b/zig/src/cuda/xstart.zig @@ -0,0 +1,66 @@ +//! Start-up marks (TF_X_START_LOG), pinned weight uploads (TF_X_START_COPY) and weight hashes (TF_X_START_HASH). +const std = @import("std"); +const environment = @import("sys").environment; + +var state: std.atomic.Value(u8) = .init(0); // 0 unread, 1 off, 2 on + +pub fn enabled() bool { + const s = state.load(.monotonic); + if (s != 0) return s == 2; + const on = environment.read(bool, "TF_X_START_LOG", false) catch false; + state.store(if (on) 2 else 1, .monotonic); + return on; +} + +pub fn hashing() bool { + return environment.read(bool, "TF_X_START_HASH", false) catch false; +} + +/// TF_X_START_COPY as a thread count (0: off, the old path). +pub fn copyThreads() usize { + return @min(environment.read(u32, "TF_X_START_COPY", 0) catch 0, 32); +} + +/// A Qwen open's first mark, TF_X_EXE_PREHASH's hashing thread and TF_X_START_COPY's upload window. +pub fn openStart() void { + mark("qwen open begins"); + @import("sys").file_identity.prehash(); + @import("start_copy.zig").begin(); +} + +pub fn nowNs() i128 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.REALTIME, &ts); + return @as(i128, ts.sec) * 1_000_000_000 + ts.nsec; +} + +pub fn monoNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +/// Time the uploads spent, split: host copy (memcpy out of the page cache), the device copy and its wait. +pub var copy_host_ns: std.atomic.Value(u64) = .init(0); +pub var copy_dev_ns: std.atomic.Value(u64) = .init(0); +pub var copy_bytes: std.atomic.Value(u64) = .init(0); +pub var copy_calls: std.atomic.Value(u64) = .init(0); +pub var quant_ns: std.atomic.Value(u64) = .init(0); + +pub fn mark(comptime what: []const u8) void { + markf(what, .{}); +} + +pub fn markf(comptime fmt: []const u8, args: anytype) void { + if (!enabled()) return; + const t = nowNs(); + const sec: u64 = @intCast(@divFloor(t, 1_000_000_000)); + const us: u64 = @intCast(@divFloor(@mod(t, 1_000_000_000), 1000)); + std.debug.print("[x-start] {d}.{d:0>6} " ++ fmt ++ " | copies {d} {d:.3} GB host {d:.3}s dev {d:.3}s quant {d:.3}s\n", .{ sec, us } ++ args ++ .{ + copy_calls.load(.monotonic), + @as(f64, @floatFromInt(copy_bytes.load(.monotonic))) / 1e9, + @as(f64, @floatFromInt(copy_host_ns.load(.monotonic))) / 1e9, + @as(f64, @floatFromInt(copy_dev_ns.load(.monotonic))) / 1e9, + @as(f64, @floatFromInt(quant_ns.load(.monotonic))) / 1e9, + }); +} diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index f2ce7bcae5d..9d2bf1a81b7 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -112,6 +112,7 @@ pub const Draft = struct { pub fn init(gpa: std.mem.Allocator, io: std.Io, e: *E, dir: []const u8) !*Draft { const nodes = try tree.nodes(); const started = profile.now(io); + cuda.xstart.mark("drafter init begins"); const c = try Config.read(gpa, io, dir, e.g); const d = try gpa.create(Draft); errdefer gpa.destroy(d); @@ -122,6 +123,12 @@ pub const Draft = struct { inline for (@typeInfo(Fns).@"struct".field_names) |name| @field(d.fns, name) = try d.mod.function("tf_q35d_" ++ name); d.w = try weights.load(gpa, io, e, dir, .{ .hidden = c.hidden, .intermediate = c.intermediate, .layers = c.layers, .vocab = c.vocab, .q_width = c.qWidth(), .kv_width = c.kvWidth(), .head_dim = c.head_dim, .dynamic = c.dynamic(), .rank = c.rank, .taps = c.n_taps, .dflash2 = c.kind == .dflash2 }); errdefer d.w.deinit(gpa); + cuda.xstart.markf("drafter: weights loaded ({d} MiB)", .{d.w.arena_at >> 20}); + if (cuda.xstart.hashing()) { + const h = @import("cuda_xstart_hash.zig"); + try h.device(e.d, "drafter arena", d.w.arena.ptr, d.w.arena_at); + h.host("drafter codebooks", std.mem.sliceAsBytes(d.w.predecessor), std.mem.sliceAsBytes(d.w.successor)); + } if (c.kind == .dspine) d.spine = try spine.init(gpa, io, e, dir, c, d.mod); errdefer if (c.kind == .dspine) spine.deinit(gpa, d.spine); d.scratch = try DeviceBuffer.alloc(e.d, try d.scratchBytes()); @@ -160,6 +167,7 @@ pub const Draft = struct { t.steps = try gpa.alloc(tree.GrowNode, frame.max_streams * (engine.most_window + 1) * lanes.draft_tree.branch); t.captures = try gpa.alloc(tree.GrowTrace, frame.max_streams); } + cuda.xstart.mark("drafter: scratch, contexts and hold timing done"); return d; } /// The drafter's taps (the target's layers it reads). diff --git a/zig/src/families/qwen3_5/cuda_draft_quant_cache.zig b/zig/src/families/qwen3_5/cuda_draft_quant_cache.zig new file mode 100644 index 00000000000..8615b7a3b46 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_draft_quant_cache.zig @@ -0,0 +1,266 @@ +//! TF_X_DRAFT_CACHE: the DFlash2 drafter's affine-4 tables on disk, so a start reads them instead of quantizing again. +const std = @import("std"); +const builtin = @import("builtin"); +const linux = std.os.linux; +const cuda = @import("cuda"); + +const magic = "TFXDQ01\n"; +/// Bump when quantize's arithmetic or the entry layout changes: old files then miss. +const version = "x-start draft quant: MLX affine-4 group 64, scale bf16((max-min)/15) RNE, bias bf16(min), nibble round((w-bias)*(1/scale)) clamp 0..15, low first; entry (n u64, k u64, words, scales, biases)"; +const block = 16 << 20; +const Header = extern struct { magic: [8]u8, key: [32]u8, entries: u64, payload: u64, blocks: u64 }; + +fn flag() bool { + return @import("sys").environment.read(bool, "TF_X_DRAFT_CACHE", false) catch false; +} + +/// TF_X_DRAFT_CACHE_DIR when set, else ~/.cache/tensorfold/draft-quant, into `buf` when it does not fit the setting. +fn rootDir(buf: []u8) ![]const u8 { + const environment = @import("sys").environment; + if (try environment.path("TF_X_DRAFT_CACHE_DIR", environment.rawText("TF_X_DRAFT_CACHE_DIR"))) |v| return v; + const home = std.c.getenv("HOME") orelse return error.NoHome; + return std.fmt.bufPrint(buf, "{s}/.cache/tensorfold/draft-quant", .{std.mem.span(home)}); +} + +pub fn wordsLen(n: usize, k: usize) usize { + return n * k / 2; +} +pub fn tableLen(n: usize, k: usize) usize { + return n * (k / 64) * 2; +} + +pub const Cache = struct { + gpa: std.mem.Allocator, + path: [:0]u8, + // reading: the mapped file, the payload after the hashes, the next entry's offset + map: ?[]align(std.heap.page_size_min) const u8 = null, + payload: []const u8 = &.{}, + at: usize = 0, + entries: u64 = 0, + used: u64 = 0, + // writing: the entries as they are quantized + out: ?std.ArrayList(u8) = null, + written: u64 = 0, + failed: bool = false, + + pub fn reading(c: *const Cache) bool { + return c.map != null; + } + + /// The next entry's three parts when it is for an n-by-k projection, else null (the cache is then dropped). + pub fn next(c: *Cache, n: usize, k: usize) ?[3][]const u8 { + if (c.map == null) return null; + const wl = wordsLen(n, k); + const tl = tableLen(n, k); + if (c.used >= c.entries or c.at + 16 + wl + 2 * tl > c.payload.len) return c.miss(); + const en = std.mem.readInt(u64, c.payload[c.at..][0..8], .little); + const ek = std.mem.readInt(u64, c.payload[c.at + 8 ..][0..8], .little); + if (en != n or ek != k) return c.miss(); + const base = c.at + 16; + c.at = base + wl + 2 * tl; + c.used += 1; + return .{ c.payload[base..][0..wl], c.payload[base + wl ..][0..tl], c.payload[base + wl + tl ..][0..tl] }; + } + + fn miss(c: *Cache) ?[3][]const u8 { + // mid-load disagreement: the caller quantizes this and every later projection; nothing is written + c.failed = true; + c.unmap(); + return null; + } + + pub fn record(c: *Cache, n: usize, k: usize, parts: [3][]const u8) void { + const out = if (c.out) |*o| o else return; + var nk: [16]u8 = undefined; + std.mem.writeInt(u64, nk[0..8], n, .little); + std.mem.writeInt(u64, nk[8..16], k, .little); + out.appendSlice(c.gpa, &nk) catch return c.drop(); + for (parts) |p| out.appendSlice(c.gpa, p) catch return c.drop(); + c.written += 1; + } + + fn drop(c: *Cache) void { + if (c.out) |*o| o.deinit(c.gpa); + c.out = null; + } + + fn unmap(c: *Cache) void { + if (c.map) |m| std.posix.munmap(m); + c.map = null; + c.payload = &.{}; + } + + /// After a whole load: a file read to its end is fine; a fresh one is written (tmp, then rename). + pub fn finish(c: *Cache, key: [32]u8) void { + if (c.map != null and c.used != c.entries) { + cuda.xstart.mark("drafter quant cache: entries left over, not used again"); + } + const out = c.out orelse return; + if (c.failed) return; + write(c.gpa, c.path, key, c.written, out.items) catch |err| { + std.log.warn("x-start: drafter quant cache not written to {s}: {s}", .{ c.path, @errorName(err) }); + return; + }; + std.log.info("x-start: drafter quant cache written: {s} ({d} projections, {d} MiB)", .{ c.path, c.written, out.items.len >> 20 }); + } + + pub fn deinit(c: *Cache) void { + c.unmap(); + c.drop(); + c.gpa.free(c.path); + } +}; + +fn identity(h: *std.crypto.hash.sha2.Sha256, file: [:0]const u8) !void { + var st: linux.Statx = undefined; + const mask: linux.STATX = .{ .INO = true, .SIZE = true, .MTIME = true, .CTIME = true }; + if (linux.errno(linux.statx(linux.AT.FDCWD, file, 0, mask, &st)) != .SUCCESS) return error.StatFailed; + if (!st.mask.INO or !st.mask.SIZE or !st.mask.MTIME or !st.mask.CTIME) return error.StatFailed; + var buf: [128]u8 = undefined; + const line = try std.fmt.bufPrint(&buf, "{d}:{d} {d} {d} {d}.{d} {d}.{d}", .{ st.dev_major, st.dev_minor, st.ino, st.size, st.mtime.sec, st.mtime.nsec, st.ctime.sec, st.ctime.nsec }); + part(h, file); + part(h, line); +} + +fn part(h: *std.crypto.hash.sha2.Sha256, bytes: []const u8) void { + var len: [8]u8 = undefined; + std.mem.writeInt(u64, &len, bytes.len, .little); + h.update(&len); + h.update(bytes); +} + +/// The cache of folder `dir` and shape `shape`, or null when the switch is off or the folder has no model.safetensors. +pub fn open(gpa: std.mem.Allocator, dir: []const u8, shape: anytype, key_out: *[32]u8) ?Cache { + if (builtin.os.tag != .linux or !flag()) return null; + return openInner(gpa, dir, shape, key_out) catch |err| { + std.log.warn("x-start: drafter quant cache off for this start: {s}", .{@errorName(err)}); + return null; + }; +} + +fn openInner(gpa: std.mem.Allocator, dir: []const u8, shape: anytype, key_out: *[32]u8) !Cache { + const model = try std.fmt.allocPrintSentinel(gpa, "{s}/model.safetensors", .{dir}, 0); + defer gpa.free(model); + var h = std.crypto.hash.sha2.Sha256.init(.{}); + part(&h, version); + try identity(&h, model); + var sbuf: [512]u8 = undefined; + part(&h, try std.fmt.bufPrint(&sbuf, "{any}", .{shape})); + const key = h.finalResult(); + key_out.* = key; + var root_buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.allocPrintSentinel(gpa, "{s}/{s}.bin", .{ try rootDir(&root_buf), std.fmt.bytesToHex(key, .lower) }, 0); + errdefer gpa.free(path); + var c: Cache = .{ .gpa = gpa, .path = path }; + if (mapVerified(path, key)) |m| { + c.map = m.map; + c.payload = m.payload; + c.entries = m.entries; + cuda.xstart.markf("drafter quant cache: hit, {d} projections verified", .{m.entries}); + return c; + } else |err| { + cuda.xstart.markf("drafter quant cache: miss ({s}), quantizing and recording", .{@errorName(err)}); + } + c.out = .empty; + return c; +} + +const Mapped = struct { map: []align(std.heap.page_size_min) const u8, payload: []const u8, entries: u64 }; + +fn mapVerified(path: [:0]const u8, key: [32]u8) !Mapped { + const rc = linux.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0); + if (linux.errno(rc) != .SUCCESS) return error.NoFile; + const fd: linux.fd_t = @intCast(rc); + defer _ = linux.close(fd); + var st: linux.Statx = undefined; + if (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &st)) != .SUCCESS) return error.StatFailed; + if (st.size < @sizeOf(Header)) return error.Short; + const map = try std.posix.mmap(null, st.size, .{ .READ = true }, .{ .TYPE = .PRIVATE }, fd, 0); + errdefer std.posix.munmap(map); + const hd: *align(1) const Header = @ptrCast(map.ptr); + if (!std.mem.eql(u8, &hd.magic, magic) or !std.mem.eql(u8, &hd.key, &key)) return error.NotOurs; + const blocks = std.math.divCeil(u64, hd.payload, block) catch return error.NotOurs; + if (blocks != hd.blocks) return error.NotOurs; + const start = @sizeOf(Header) + 8 * blocks; + if (st.size != start + hd.payload) return error.Truncated; + const payload = map[start..][0..hd.payload]; + const sums = map[@sizeOf(Header)..][0 .. 8 * blocks]; + if (!verify(payload, sums)) return error.HashMismatch; + return .{ .map = map, .payload = payload, .entries = hd.entries }; +} + +fn blockHash(payload: []const u8, i: usize) u64 { + const from = i * block; + return std.hash.XxHash3.hash(0, payload[from..@min(payload.len, from + block)]); +} + +const Verify = struct { + payload: []const u8, + sums: []const u8, + bad: std.atomic.Value(bool) = .init(false), + fn run(v: *Verify, from: usize, to: usize) void { + for (from..to) |i| if (blockHash(v.payload, i) != std.mem.readInt(u64, v.sums[8 * i ..][0..8], .little)) v.bad.store(true, .monotonic); + } +}; + +fn verify(payload: []const u8, sums: []const u8) bool { + const blocks = sums.len / 8; + var v: Verify = .{ .payload = payload, .sums = sums }; + const cpus = std.Thread.getCpuCount() catch 1; + const t = @min(@max(cpus, 1), 16, @max(blocks, 1)); + var threads: [16]?std.Thread = @splat(null); + for (1..t) |i| threads[i] = std.Thread.spawn(.{}, Verify.run, .{ &v, blocks * i / t, blocks * (i + 1) / t }) catch blk: { + v.run(blocks * i / t, blocks * (i + 1) / t); + break :blk null; + }; + v.run(0, blocks / t); + for (threads[1..t]) |th| if (th) |x| x.join(); + return !v.bad.load(.monotonic); +} + +fn write(gpa: std.mem.Allocator, path: [:0]const u8, key: [32]u8, entries: u64, payload: []const u8) !void { + const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return error.BadPath; + try mkdirs(gpa, path[0..slash]); + const tmp = try std.fmt.allocPrintSentinel(gpa, "{s}.tmp.{d}", .{ path, linux.getpid() }, 0); + defer gpa.free(tmp); + const blocks = std.math.divCeil(u64, payload.len, block) catch unreachable; + const sums = try gpa.alloc(u8, 8 * blocks); + defer gpa.free(sums); + for (0..blocks) |i| std.mem.writeInt(u64, sums[8 * i ..][0..8], blockHash(payload, i), .little); + const hd: Header = .{ .magic = magic.*, .key = key, .entries = entries, .payload = payload.len, .blocks = blocks }; + const rc = linux.open(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, 0o644); + if (linux.errno(rc) != .SUCCESS) return error.CreateFailed; + const fd: linux.fd_t = @intCast(rc); + var ok = false; + defer { + _ = linux.close(fd); + if (!ok) _ = linux.unlink(tmp); + } + var off: u64 = 0; + for ([_][]const u8{ std.mem.asBytes(&hd), sums, payload }) |piece| { + var done: usize = 0; + while (done < piece.len) { + const n = linux.pwrite(fd, piece[done..].ptr, @min(piece.len - done, 1 << 30), @intCast(off)); + if (linux.errno(n) != .SUCCESS or n == 0) return error.WriteFailed; + done += n; + off += n; + } + } + if (linux.errno(linux.fsync(fd)) != .SUCCESS) return error.SyncFailed; + if (linux.errno(linux.rename(tmp, path)) != .SUCCESS) return error.RenameFailed; + ok = true; +} + +fn mkdirs(gpa: std.mem.Allocator, dir: []const u8) !void { + var i: usize = 1; + while (i <= dir.len) : (i += 1) { + if (i != dir.len and dir[i] != '/') continue; + const z = try gpa.dupeSentinel(u8, dir[0..i], 0); + defer gpa.free(z); + const rc = linux.mkdir(z, 0o755); + switch (linux.errno(rc)) { + .SUCCESS, .EXIST => {}, + else => return error.MkdirFailed, + } + } +} diff --git a/zig/src/families/qwen3_5/cuda_draft_weights.zig b/zig/src/families/qwen3_5/cuda_draft_weights.zig index 91f9ad7c7b5..c643285fa5e 100644 --- a/zig/src/families/qwen3_5/cuda_draft_weights.zig +++ b/zig/src/families/qwen3_5/cuda_draft_weights.zig @@ -8,6 +8,7 @@ const Affine4 = cuda.qlinear.Affine4; const DeviceBuffer = cuda.DeviceBuffer; const Engine = engine.Engine; const aligned = engine.aligned; +const quant_cache = @import("cuda_draft_quant_cache.zig"); pub const Layer = struct { input_norm: u64, @@ -92,6 +93,8 @@ const toBf16 = core.bf16_round.bits; /// MLX affine-4, group 64: scale bf16((max - min) / 15), bias bf16(min), nibbles round((w - bias) / scale), low first. fn quantize(gpa: std.mem.Allocator, w: []align(1) const u16, n: usize, k: usize) !struct { words: []u32, scales: []u16, biases: []u16 } { + const q0 = cuda.xstart.monoNs(); + defer _ = cuda.xstart.quant_ns.fetchAdd(cuda.xstart.monoNs() - q0, .monotonic); const groups = k / 64; const words = try gpa.alloc(u32, n * k / 8); errdefer gpa.free(words); @@ -129,14 +132,19 @@ fn quantize(gpa: std.mem.Allocator, w: []align(1) const u16, n: usize, k: usize) return .{ .words = words, .scales = scales, .biases = biases }; } -/// A bf16 (n, k) tensor quantized and packed through `stage` into the drafter's arena. -fn linear(gpa: std.mem.Allocator, e: *Engine, stage: *DeviceBuffer, w: *Weights, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize) !Affine4 { +/// A bf16 (n, k) tensor quantized and packed through `stage`; TF_X_DRAFT_CACHE's file gives or records the tables. +fn linear(gpa: std.mem.Allocator, e: *Engine, stage: *DeviceBuffer, w: *Weights, ck: *core.Checkpoint, qc: ?*quant_cache.Cache, name: []const u8, n: usize, k: usize) !Affine4 { const t = try ck.expect(name, .bf16, &.{ n, k }); - return linearRows(gpa, e, stage, w, std.mem.bytesAsSlice(u16, t.bytes), n, k); + if (qc) |c| if (c.next(n, k)) |parts| return packParts(e, stage, w, parts, n, k); + return linearRowsCached(gpa, e, stage, w, std.mem.bytesAsSlice(u16, t.bytes), n, k, qc); } /// bf16 (n, k) rows quantized to affine-4 and packed through `stage` into `w`'s arena (any arena owner with alloc). pub fn linearRows(gpa: std.mem.Allocator, e: *Engine, stage: *DeviceBuffer, w: anytype, rows: []align(1) const u16, n: usize, k: usize) !Affine4 { + return linearRowsCached(gpa, e, stage, w, rows, n, k, null); +} + +fn linearRowsCached(gpa: std.mem.Allocator, e: *Engine, stage: *DeviceBuffer, w: anytype, rows: []align(1) const u16, n: usize, k: usize, qc: ?*quant_cache.Cache) !Affine4 { if (rows.len != n * k) return error.UnexpectedTensor; const q = try quantize(gpa, rows, n, k); defer { @@ -145,6 +153,12 @@ pub fn linearRows(gpa: std.mem.Allocator, e: *Engine, stage: *DeviceBuffer, w: a gpa.free(q.biases); } const parts = [_][]const u8{ std.mem.sliceAsBytes(q.words), std.mem.sliceAsBytes(q.scales), std.mem.sliceAsBytes(q.biases) }; + if (qc) |c| c.record(n, k, parts); + return packParts(e, stage, w, parts, n, k); +} + +/// Quantized parts (words, scales, biases) staged and packed into `w`'s arena. +fn packParts(e: *Engine, stage: *DeviceBuffer, w: anytype, parts: [3][]const u8, n: usize, k: usize) !Affine4 { var raw: [3]u64 = undefined; var at: usize = 0; for (parts, &raw) |p, *r| { @@ -179,6 +193,10 @@ const none: Affine4 = .{ .w = 0, .s = 0, .b = 0, .n = 0, .k = 0, .npad = 0 }; pub fn load(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, s: Shape) !Weights { var ck = try core.Checkpoint.openModel(gpa, io, dir); defer core.checkpoint.cache.close(&ck); + var qkey: [32]u8 = undefined; + var qc = quant_cache.open(gpa, dir, s, &qkey); + defer if (qc) |*c| c.deinit(); + const qcp: ?*quant_cache.Cache = if (qc) |*c| c else null; var w: Weights = .{ .fc = undefined, .hidden_norm = 0, .final_norm = 0, .selector = none, .predecessor = &.{}, .successor = &.{}, .layers = &.{}, .arena = try DeviceBuffer.alloc(e.d, total(s)) }; errdefer w.arena.free(); try w.arena.fill8(0, null); @@ -186,11 +204,11 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, s: defer stage.free(); w.layers = try gpa.alloc(Layer, s.layers); errdefer gpa.free(w.layers); - w.fc = try linear(gpa, e, &stage, &w, &ck, "fc.weight", s.hidden, s.taps * s.hidden); + w.fc = try linear(gpa, e, &stage, &w, &ck, qcp, "fc.weight", s.hidden, s.taps * s.hidden); w.hidden_norm = try vector(&w, &ck, "hidden_norm.weight", &.{s.hidden}); w.final_norm = try vector(&w, &ck, "norm.weight", &.{s.hidden}); if (s.dflash2) { - w.selector = try linear(gpa, e, &stage, &w, &ck, "candidate_selector.hidden_projection.weight", s.rank, s.hidden); + w.selector = try linear(gpa, e, &stage, &w, &ck, qcp, "candidate_selector.hidden_projection.weight", s.rank, s.hidden); w.predecessor = try hostBf16(gpa, &ck, "candidate_selector.predecessor_codebook", &.{ s.vocab, s.rank }); w.successor = try hostBf16(gpa, &ck, "candidate_selector.successor_codebook", &.{ s.vocab, s.rank }); } @@ -209,26 +227,27 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, e: *Engine, dir: []const u8, s: l.* = .{ .input_norm = try vector(&w, &ck, try nm.of("input_layernorm.weight"), &.{s.hidden}), .post_norm = try vector(&w, &ck, try nm.of("post_attention_layernorm.weight"), &.{s.hidden}), - .q = try linear(gpa, e, &stage, &w, &ck, try nm.of("self_attn.q_proj.weight"), s.q_width, s.hidden), - .k = try linear(gpa, e, &stage, &w, &ck, try nm.of("self_attn.k_proj.weight"), s.kv_width, s.hidden), - .v = try linear(gpa, e, &stage, &w, &ck, try nm.of("self_attn.v_proj.weight"), s.kv_width, s.hidden), - .o = try linear(gpa, e, &stage, &w, &ck, try nm.of("self_attn.o_proj.weight"), s.hidden, s.q_width), + .q = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("self_attn.q_proj.weight"), s.q_width, s.hidden), + .k = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("self_attn.k_proj.weight"), s.kv_width, s.hidden), + .v = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("self_attn.v_proj.weight"), s.kv_width, s.hidden), + .o = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("self_attn.o_proj.weight"), s.hidden, s.q_width), .q_norm = try vector(&w, &ck, try nm.of("self_attn.q_norm.weight"), &.{s.head_dim}), .k_norm = try vector(&w, &ck, try nm.of("self_attn.k_norm.weight"), &.{s.head_dim}), - .gate = try linear(gpa, e, &stage, &w, &ck, try nm.of("mlp.gate_proj.weight"), s.intermediate, s.hidden), - .up = try linear(gpa, e, &stage, &w, &ck, try nm.of("mlp.up_proj.weight"), s.intermediate, s.hidden), - .down = try linear(gpa, e, &stage, &w, &ck, try nm.of("mlp.down_proj.weight"), s.hidden, s.intermediate), + .gate = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("mlp.gate_proj.weight"), s.intermediate, s.hidden), + .up = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("mlp.up_proj.weight"), s.intermediate, s.hidden), + .down = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("mlp.down_proj.weight"), s.hidden, s.intermediate), .attn_conv = none, .attn_base = 0, .mlp_conv = none, .mlp_base = 0, }; if (!s.dflash2) continue; - l.attn_conv = try linear(gpa, e, &stage, &w, &ck, try nm.of("attention_conv.kernel_projection.weight"), s.dynamic, s.hidden); + l.attn_conv = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("attention_conv.kernel_projection.weight"), s.dynamic, s.hidden); l.attn_base = try vector(&w, &ck, try nm.of("attention_conv.base_kernel"), &.{ 2, 2, s.hidden }); - l.mlp_conv = try linear(gpa, e, &stage, &w, &ck, try nm.of("mlp_conv.kernel_projection.weight"), s.dynamic, s.hidden); + l.mlp_conv = try linear(gpa, e, &stage, &w, &ck, qcp, try nm.of("mlp_conv.kernel_projection.weight"), s.dynamic, s.hidden); l.mlp_base = try vector(&w, &ck, try nm.of("mlp_conv.base_kernel"), &.{ 2, 2, s.hidden }); } + if (qcp) |c| c.finish(qkey); return w; } diff --git a/zig/src/families/qwen3_5/cuda_drafter_open.zig b/zig/src/families/qwen3_5/cuda_drafter_open.zig index c2ebaffb2f7..e07d93fce4a 100644 --- a/zig/src/families/qwen3_5/cuda_drafter_open.zig +++ b/zig/src/families/qwen3_5/cuda_drafter_open.zig @@ -100,6 +100,8 @@ fn closeMtp(p: *anyopaque) void { fn calibrateDrafter(p: *anyopaque) !lanes.drafter.Facts { const l: *Lanes = @ptrCast(@alignCast(p)); const d = l.calibration orelse return error.MissingCalibrationDrafter; + @import("cuda").start_copy.end(); // TF_X_START_COPY's window ends with the load + @import("cuda").xstart.mark("window costs begin"); if (d.n_costs == 0) { if (l.pool.items.len == 0 and !l.engine_paged) return error.MissingReservedQwenCache; // engine_paged: no reserved window, so the timing makes a window_rows cache of its own (null) @@ -110,6 +112,7 @@ fn calibrateDrafter(p: *anyopaque) !lanes.drafter.Facts { var phases = l.startup; phases.add(d.startup); phases.print(); + @import("cuda").xstart.mark("window costs done"); return d.drafter().facts(); } diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 23c39d501e3..c1a21ebc8b7 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -145,6 +145,7 @@ pub const Engine = struct { po: u64, logits: u64, mt2: @import("cuda_mt2.zig").Mt2, + merge: @import("cuda_merge_wide.zig").Merge = .{}, // TF_QWEN_MERGE_WIDE: a thread per value in the attention merge routed: routed.Scratch = .{}, // qwen3_5_moe's routed rows amax: u64, // the argmax slices' bests: most_verify rows of argmaxSlices(vocab) (f32, i32) picks: u64, // drawRows' slice scratch: most_verify rows of cuda.sample.Draws.row_scratch @@ -181,6 +182,8 @@ pub const Engine = struct { pub fn initStage(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kv8: bool, fit: ?hosted.Fit, prompt_rows_limit: usize, span: ?stage_fwd.Span, loops: ?u32) !*Engine { if (!cuda.kernels.available) return error.BuiltWithoutKernels; const started = profile.now(io); + const xs = cuda.xstart; + xs.mark("engine init begins"); var g = try stage_fwd.geometry(try Geometry.read(gpa, io, dir), span); if (loops) |n| g = try g.withLoops(n); const d = ctx.d; @@ -230,11 +233,16 @@ pub const Engine = struct { errdefer e.stream.deinit(); if (span != null) e.boundary = try cuda.HostBuffer.alloc(d, stage_fwd.bytes(g.hidden, grid_rows)); errdefer if (e.boundary) |*b| b.free(); + xs.mark("engine: stream made, checkpoint opens"); var ck = try core.Checkpoint.openModel(gpa, io, dir); defer core.checkpoint.cache.close(&ck); + xs.mark("engine: checkpoint open"); e.arena = try hosted.arena(e, io, ctx, &ck, fit); errdefer hosted.release(e); + xs.markf("engine: arena allocated ({d} MiB)", .{e.arena.len >> 20}); try e.arena.fill8(0, null); // touched once now: the driver commits memory on first touch, slowly + if (xs.enabled()) try cuda.copy_source.synchronizeStream(d, null); // timing only: the fill lands anyway + xs.mark("engine: arena zeroed"); const kk = cuda.kernels; const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack, kk.qwen35, kk.sample, kk.qwen35_keep, kk.affine8, kk.affine_prefill, kk.qwen35_kv8, kk.experts, kk.experts_prefill, kk.experts_pack, kk.moe, kk.experts3, kk.experts3_prefill, kk.prefill_attention, kk.gdn_prefill, kk.w4a8_prefill }; var loaded: usize = 0; @@ -243,6 +251,7 @@ pub const Engine = struct { e.mods[i] = try cuda.Module.load(d, img); loaded += 1; } + xs.mark("engine: 19 modules loaded"); if (g.loop) |c| if (c.mhc) |m| { e.mhc = try @import("cuda_mhc.zig").Runtime.load(d, m); }; @@ -268,6 +277,7 @@ pub const Engine = struct { e.plan = try cuda.grouped.Router.resolve(e.mods[10]); e.moe = try cuda.moe.Fns.resolve(e.mods[13]); inline for (@typeInfo(Fns).@"struct".field_names) |name| @field(e.fns, name) = try e.mods[4].function("tf_q35_" ++ name); + e.merge = try @import("cuda_merge_wide.zig").Merge.resolve(e.mods[4]); // bf16 tiles' two buffers for ([_]cuda.Function{ e.fns.attn_partial, e.fns.attn_rows, e.fns.attn_rows_join, e.fns.attn_partial_whole, e.fns.attn_rows_whole }) |f| try f.allowDynamicShared(@import("cuda_forward.zig").attn_tiles); inline for (@typeInfo(Keeps).@"struct".field_names) |name| @field(e.keeps, name) = try e.mods[6].function("tf_q35k_" ++ name); @@ -282,6 +292,7 @@ pub const Engine = struct { errdefer gpa.free(e.steps); e.layers = try gpa.alloc(Layer, g.layers); errdefer gpa.free(e.layers); + xs.mark("engine: kernels resolved, weights load"); if (g.exl3 or g.tfq3 or g.tfq5) { try tfq5w.loadQuantized(e, gpa, io, d, dir, g, &ck, @intCast(10 * major + minor), S.passRows(e)); } else { @@ -290,8 +301,11 @@ pub const Engine = struct { defer stage.free(); try weights.load(e, &ck, &stage); } + xs.markf("engine: weights loaded ({d} MiB of arena)", .{e.arena_at >> 20}); + if (xs.hashing()) try @import("cuda_xstart_hash.zig").device(e.d, "engine arena", e.arena.ptr, e.arena_at); if (e.mo) |*m| try m.reserveParts(e); try @import("cuda_engine_tail.zig").finish(e, io, started); + xs.mark("engine: tail and warm-ups done"); return e; } pub fn finishWarm(e: *Engine, io: std.Io, started: i96) !void { diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index c9adbe6c4fa..145159c157e 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -155,7 +155,11 @@ pub fn body(e: *E.Engine, shape: anytype) !void { if (!rows_only) try shared(e, if (shape.paged) e.fns.attn_partial else e.fns.attn_partial_whole, sig.attn_partial, .{ total, max_chunks, g.kv_heads }, 128, args); try shared(e, if (shape.join) e.fns.attn_rows_join else if (shape.paged) e.fns.attn_rows else e.fns.attn_rows_whole, sig.attn_rows, .{ groups, max_chunks, g.kv_heads }, 256, bf16_rows_args); } - try launch(e, e.fns.attn_merge, sig.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, .{ geo, e.pm, e.pl, e.po, t_segs, t_rows, t_anc, t_params, e.y }); + const merge_args = .{ geo, e.pm, e.pl, e.po, t_segs, t_rows, t_anc, t_params, e.y }; + if (e.merge.wide) |wide| { + try launch(e, wide, sig.attn_merge, .{ g.q_heads, total, 1 }, .{ 256, 1, 1 }, merge_args); + if (e.merge.verify != 0 and e.logits != 0) try @import("cuda_merge_wide.zig").check(e, total, aw, t_params); + } else try launch(e, e.fns.attn_merge, sig.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, merge_args); } // the tail's rows from their own pointers, so no device row count (0: the launch's rows are real) const gp: u64 = if (tail) 0 else t_params; @@ -185,7 +189,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const paired = e.learning == null and sums == 0 and try modelopt.swiglu(e, m.gate, m.up, x0, e.act, rows, prompt, rp); if (paired) {} else if (m.gate == .x3) { try e.projMany(&.{ m.gate, m.up }, x0, &.{ e.gate, e.up }, rows, prompt); // one EXL3 group launch - } else if (e.affine.pdl and !prompt and e.learning == null and m.gate == .a4 and m.up == .a4) { + } else if ((e.affine.pdl or (e.affine.seg_mlp and total <= cuda.qlinear.Affine4Kernels.max_rows)) and !prompt and e.learning == null and m.gate == .a4 and m.up == .a4) { try e.projMany(&.{ m.gate, m.up }, e.x, &.{ e.gate, e.up }, total, false); } else if (try @import("cuda_group_proj.zig").run(e, &.{ m.gate, m.up }, x0, &.{ e.gate, e.up }, rows, prompt)) {} else { try e.projAgain(m.gate, x0, e.gate, rows, prompt); diff --git a/zig/src/families/qwen3_5/cuda_merge_wide.zig b/zig/src/families/qwen3_5/cuda_merge_wide.zig new file mode 100644 index 00000000000..2b3bd1dce03 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_merge_wide.zig @@ -0,0 +1,29 @@ +//! TF_QWEN_MERGE_WIDE: the decode attention merge with a thread per head value, byte for byte the warp merge's. +const std = @import("std"); +const cuda = @import("cuda"); +const platform = @import("sys"); +const sig = @import("cuda_signatures.zig"); + +pub const Merge = struct { + wide: ?cuda.Function = null, + check: ?cuda.Function = null, + verify: u32 = 0, // TF_QWEN_MERGE_WIDE_VERIFY: 1 compares the live rows with the warp merge's, 2 plants one difference + + pub fn resolve(mod: cuda.Module) !Merge { + if (!try platform.environment.read(bool, "TF_QWEN_MERGE_WIDE", false)) return .{}; + const verify = try platform.environment.read(u32, "TF_QWEN_MERGE_WIDE_VERIFY", 0); + return .{ .wide = try mod.function("tf_q35_attn_merge_wide"), .check = if (verify != 0) try mod.function("tf_q35_merge_check") else null, .verify = verify }; + } +}; + +/// The warp merge's bytes into the logits scratch, then the live rows compared with the wide merge's in e.y. +pub fn check(e: anytype, total: usize, width: usize, t_params: u64) !void { + const g = e.g; + const geo = e.geo; + const t = e.tables.ptr; + const E = @import("cuda_engine.zig").Engine; + const args = .{ geo, e.pm, e.pl, e.po, t + E.segs_at, t + E.rowseg_at, t + E.rowanc_at, t_params, e.logits }; + sig.check(sig.attn_merge, @TypeOf(args)); + try e.run(e.fns.attn_merge, .{ g.q_heads, total, 1 }, .{ 32, 1, 1 }, args); + try e.run(e.merge.check.?, .{ total, 1, 1 }, .{ 256, 1, 1 }, .{ e.y, e.logits, @as(c_int, @intCast(width)), t_params, @as(c_int, @intFromBool(e.merge.verify == 2)) }); +} diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index 5f2946b8da0..c5a6ffedd9c 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -162,8 +162,10 @@ 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 { + cuda.xstart.openStart(); // TF_X_START_LOG's first mark, TF_X_EXE_PREHASH's thread, TF_X_START_COPY's window const clef = 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 }); var loaded = try openLanes(gpa, io, ctx, dir, kernels, o); + if (o.drafter == null) cuda.start_copy.end(); // no drafter load follows if (!clef) return loaded; errdefer loaded.deinit(loaded.ctx); if (loaded.layout != null) return error.QwenJointPages; diff --git a/zig/src/families/qwen3_5/cuda_xstart_hash.zig b/zig/src/families/qwen3_5/cuda_xstart_hash.zig new file mode 100644 index 00000000000..7a59efc1b5f --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_xstart_hash.zig @@ -0,0 +1,27 @@ +//! TF_X_START_HASH: hashes of the loaded weights, the proof that a load switch moved the same bytes. +const std = @import("std"); +const cuda = @import("cuda"); + +/// Device bytes [ptr, ptr + len) read back through a pinned buffer and hashed (xxh3-64); one line on stderr. +pub fn device(d: *const cuda.Driver, what: []const u8, ptr: u64, len: usize) !void { + try d.check(d.api.cuCtxSynchronize(), "cuCtxSynchronize"); + var buf = try cuda.HostBuffer.alloc(d, 256 << 20); + defer buf.free(); + var h = std.hash.XxHash3.init(0); + var at: usize = 0; + while (at < len) { + const n = @min(len - at, buf.bytes.len); + try d.check(d.api.cuMemcpyDtoH_v2(buf.bytes.ptr, ptr + at, n), "cuMemcpyDtoH"); + h.update(buf.bytes[0..n]); + at += n; + } + std.debug.print("[x-start] hash {s}: {d} bytes xxh3 {x:0>16}\n", .{ what, len, h.final() }); +} + +/// Host bytes hashed the same way, `a` then `b`. +pub fn host(what: []const u8, a: []const u8, b: []const u8) void { + var h = std.hash.XxHash3.init(0); + h.update(a); + h.update(b); + std.debug.print("[x-start] hash {s}: {d} bytes xxh3 {x:0>16}\n", .{ what, a.len + b.len, h.final() }); +} diff --git a/zig/src/native/cuda_disk.zig b/zig/src/native/cuda_disk.zig index 39f977862a6..760034a738e 100644 --- a/zig/src/native/cuda_disk.zig +++ b/zig/src/native/cuda_disk.zig @@ -243,9 +243,12 @@ pub fn attachKept(comptime K: type, name: []const u8, a: Allocator, io: std.Io, // a module that opens the store itself (several ranks' parts, say) declares attach, and takes identityOf from here if (comptime @hasDecl(K, "attach")) return K.attach(a, io, ctx, o, root, kernels, loaded, store) else { if (@hasDecl(K, "bind")) K.bind(loaded.target, ctx); // the context the store's copies make current - const p = try K.probe(a, io, loaded.backend, loaded.target); + cuda.xstart.mark("learn: identity probe begins"); + const p = try @import("xstart_probe_cache.zig").probe(K, a, io, ctx, o.dir, loaded.backend, loaded.target); + cuda.xstart.mark("learn: identity probe done"); const staging = stagingOf(K, loaded.target); const id = try keptKey(K, a, io, ctx, o.dir, kernels, loaded.target, p.hash, .{ .family = name, .backend = "cuda" }); + cuda.xstart.mark("learn: store key made"); // a kept image's key also binds the prompt's files and a drafter's checkpoint (native/cuda_kept.zig) const key = if (comptime @hasDecl(K, "prompted")) try K.prompted(a, io, o, id) else id; const longest: u32 = if (comptime @hasDecl(K, "longest")) K.longest(loaded.target) else 0; @@ -271,6 +274,7 @@ fn open(o: api.Open, root: []const u8, id: u64, rate: f64, store: *api.prompt_ca const r = try rows.attach(store.gpa, store, opts); r.prefill_rate = rate; std.log.info("{s}: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB)", .{ name, r.dir, r.states.items.len, r.held() >> 20, r.cap >> 20 }); + cuda.xstart.mark("learn: store open"); } test { diff --git a/zig/src/native/xstart_probe_cache.zig b/zig/src/native/xstart_probe_cache.zig new file mode 100644 index 00000000000..9dcf2c785c7 --- /dev/null +++ b/zig/src/native/xstart_probe_cache.zig @@ -0,0 +1,175 @@ +//! TF_X_PROBE_CACHE: --learn-conversations' identity probe kept in a small file, keyed on code, checkpoint and device. +const std = @import("std"); +const linux = std.os.linux; +const cuda = @import("cuda"); +const disk_identity = @import("disk_identity.zig"); +const file_identity = @import("sys").file_identity; +const Allocator = std.mem.Allocator; + +const magic = "TFXPC01\n"; +const Record = extern struct { magic: [8]u8, key: [32]u8, hash: u64, rate: f64, check: u64 }; +const Mode = enum { off, on, verify }; + +/// TF_X_PROBE_CACHE: 0 off, 1 use a kept record, verify runs the probe again and compares it with the record. +fn mode() Mode { + const n = @import("sys").environment.read(u32, "TF_X_PROBE_CACHE", 0) catch 0; + return switch (n) { + 0 => .off, + 1 => .on, + else => .verify, + }; +} + +fn readAll(a: Allocator, path: [:0]const u8) ![]u8 { + const rc = linux.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0); + if (linux.errno(rc) != .SUCCESS) return error.OpenFailed; + const fd: linux.fd_t = @intCast(rc); + defer _ = linux.close(fd); + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + var buf: [65536]u8 = undefined; + while (true) { + const n = linux.read(fd, &buf, buf.len); + if (linux.errno(n) != .SUCCESS) return error.ReadFailed; + if (n == 0) break; + try out.appendSlice(a, buf[0..n]); + } + return out.toOwnedSlice(a); +} + +fn part(h: *std.crypto.hash.sha2.Sha256, bytes: []const u8) void { + var len: [8]u8 = undefined; + std.mem.writeInt(u64, &len, bytes.len, .little); + h.update(&len); + h.update(bytes); +} + +fn lessThan(_: void, x: []const u8, y: []const u8) bool { + return std.mem.order(u8, x, y) == .lt; +} + +fn key(comptime K: type, a: Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8) ![32]u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + part(&h, "x-start probe cache v1"); + part(&h, @typeName(K)); + file_identity.bind(&h, try file_identity.running(a, io)); + var name_buf: [256]u8 = undefined; + const dev = try @import("cuda_disk.zig").deviceOf(ctx, &name_buf); + part(&h, dev.name); + h.update(std.mem.asBytes(&[_]u64{ dev.capability, dev.driver })); + try disk_identity.checkpoint(&h, a, io, dir); + const cmdline = try readAll(a, "/proc/self/cmdline"); + defer a.free(cmdline); + var args = std.mem.splitScalar(u8, cmdline, 0); + _ = args.next(); // the program name (a masked argv[0] names the same binary, bound above) + var drafter: ?[]const u8 = null; + var prev: []const u8 = ""; + while (args.next()) |arg| { + part(&h, arg); + if (std.mem.eql(u8, prev, "--drafter")) drafter = arg; + prev = arg; + } + if (drafter) |d| { + const path = try std.fmt.allocPrintSentinel(a, "{s}/model.safetensors", .{d}, 0); + defer a.free(path); + var st: linux.Statx = undefined; + const mask: linux.STATX = .{ .INO = true, .SIZE = true, .MTIME = true, .CTIME = true }; + if (linux.errno(linux.statx(linux.AT.FDCWD, path, 0, mask, &st)) == .SUCCESS) { + h.update(std.mem.asBytes(&[_]u64{ st.dev_major, st.dev_minor, st.ino, st.size, @bitCast(st.mtime.sec), st.mtime.nsec, @bitCast(st.ctime.sec), st.ctime.nsec })); + } else part(&h, "no drafter file"); + } + const environ = try readAll(a, "/proc/self/environ"); + defer a.free(environ); + var vars: std.ArrayList([]const u8) = .empty; + defer vars.deinit(a); + var it = std.mem.splitScalar(u8, environ, 0); + while (it.next()) |kv| { + // this switch and the observation-only ones are left out, so a verify start keys as a use + const skip = for ([_][]const u8{ "TF_X_PROBE_CACHE", "TF_X_START_LOG=", "TF_X_START_HASH=" }) |q| { + if (std.mem.startsWith(u8, kv, q)) break true; + } else false; + if (skip) continue; + for ([_][]const u8{ "TF_", "TENSORFOLD_", "CUDA_", "NVIDIA_" }) |prefix| if (std.mem.startsWith(u8, kv, prefix)) { + try vars.append(a, kv); + break; + }; + } + std.mem.sort([]const u8, vars.items, {}, lessThan); + for (vars.items) |kv| part(&h, kv); + return h.finalResult(); +} + +fn pathOf(a: Allocator, k: [32]u8) ![:0]u8 { + const environment = @import("sys").environment; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const set = try environment.path("TF_X_PROBE_CACHE_DIR", environment.rawText("TF_X_PROBE_CACHE_DIR")); + const folder: []const u8 = if (set) |v| v else blk: { + const home = std.c.getenv("HOME") orelse return error.NoHome; + break :blk try std.fmt.bufPrint(&buf, "{s}/.cache/tensorfold/x-start-probe", .{std.mem.span(home)}); + }; + return std.fmt.allocPrintSentinel(a, "{s}/{s}.bin", .{ folder, std.fmt.bytesToHex(k, .lower) }, 0); +} + +fn checkOf(r: Record) u64 { + return std.hash.XxHash3.hash(0x7873, std.mem.asBytes(&r)[0..@offsetOf(Record, "check")]); +} + +fn load(a: Allocator, path: [:0]const u8, k: [32]u8) ?Record { + const bytes = readAll(a, path) catch return null; + defer a.free(bytes); + if (bytes.len != @sizeOf(Record)) return null; + var r: Record = undefined; + @memcpy(std.mem.asBytes(&r), bytes); + if (!std.mem.eql(u8, &r.magic, magic) or !std.mem.eql(u8, &r.key, &k) or r.check != checkOf(r)) return null; + if (!(r.rate > 0) or !std.math.isFinite(r.rate)) return null; + return r; +} + +fn save(a: Allocator, path: [:0]const u8, k: [32]u8, hash: u64, rate: f64) void { + var r: Record = .{ .magic = magic.*, .key = k, .hash = hash, .rate = rate, .check = 0 }; + r.check = checkOf(r); + const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return; + var i: usize = 1; + while (i <= slash) : (i += 1) { + if (i != slash and path[i] != '/') continue; + const z = a.dupeSentinel(u8, path[0..i], 0) catch return; + defer a.free(z); + _ = linux.mkdir(z, 0o755); + } + const tmp = std.fmt.allocPrintSentinel(a, "{s}.tmp.{d}", .{ path, linux.getpid() }, 0) catch return; + defer a.free(tmp); + const rc = linux.open(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, 0o644); + if (linux.errno(rc) != .SUCCESS) return; + const fd: linux.fd_t = @intCast(rc); + const bytes = std.mem.asBytes(&r); + const n = linux.write(fd, bytes.ptr, bytes.len); + _ = linux.close(fd); + if (linux.errno(n) != .SUCCESS or n != bytes.len or linux.errno(linux.rename(tmp, path)) != .SUCCESS) _ = linux.unlink(tmp); +} + +/// K.probe, or its kept result (see the file's header). +pub fn probe(comptime K: type, a: Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, backend: anytype, target: anytype) !struct { hash: u64, rate: f64 } { + const m = mode(); + if (m == .off) { + const p = try K.probe(a, io, backend, target); + return .{ .hash = p.hash, .rate = p.rate }; + } + const k = key(K, a, io, ctx, dir) catch |err| { + std.log.warn("x-start: probe cache off for this start: {s}", .{@errorName(err)}); + const p = try K.probe(a, io, backend, target); + return .{ .hash = p.hash, .rate = p.rate }; + }; + const path = pathOf(a, k) catch null; + defer if (path) |x| a.free(x); + const kept: ?Record = if (path) |x| load(a, x, k) else null; + if (m == .on) if (kept) |r| { + std.log.info("x-start: probe cache hit: hash {x:0>16}, rate {d:.0} tokens/s (probe skipped)", .{ r.hash, r.rate }); + return .{ .hash = r.hash, .rate = r.rate }; + }; + const p = try K.probe(a, io, backend, target); + if (kept) |r| { + std.log.info("x-start: probe cache verify: kept hash {x:0>16} {s} fresh {x:0>16}; rate kept {d:.0}, fresh {d:.0}", .{ r.hash, if (r.hash == p.hash) "EQUALS" else "DIFFERS FROM", p.hash, r.rate, p.rate }); + } else std.log.info("x-start: probe cache miss: hash {x:0>16}, rate {d:.0} tokens/s kept for the next start", .{ p.hash, p.rate }); + if (path) |x| save(a, x, k, p.hash, p.rate); + return .{ .hash = p.hash, .rate = p.rate }; +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index bf984459e7d..4aac527d9e4 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -110,6 +110,16 @@ const stock_rules = [_]Rule{ .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission's floor and the memory's size still bound it)" }, .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission still fits its byte count in a 64-bit size)" }, .{ .name = "TF_QWEN_KEEP_LATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_X_START_LOG", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; one line a start-up phase on stderr, with the weight copies so far)" }, + .{ .name = "TF_X_START_HASH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; hash the loaded weights after the load, the proof a switch moved the same bytes)" }, + .{ .name = "TF_X_START_COPY", .scope = .cuda, .kind = .u32, .max = 32, .forms = "0 to 32 host threads copying weights into pinned buffers (0 or unset: off, the driver's own copy)" }, + .{ .name = "TF_X_EXE_PREHASH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; hash the running binary once, beside the model load)" }, + .{ .name = "TF_X_DRAFT_CACHE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; read the drafter's affine-4 tables from disk instead of quantizing them again)" }, + .{ .name = "TF_X_DRAFT_CACHE_DIR", .scope = .cuda, .kind = .path, .forms = "a path without control characters to the folder the drafter tables are kept in (default ~/.cache/tensorfold/draft-quant)" }, + .{ .name = "TF_X_PROBE_CACHE", .scope = .cuda, .kind = .word, .words = &.{ "0", "1", "verify" }, .forms = "0 (off), 1 (use a kept identity probe) or verify (run the probe again and compare it with the record)" }, + .{ .name = "TF_X_PROBE_CACHE_DIR", .scope = .cuda, .kind = .path, .forms = "a path without control characters to the folder the probe records are kept in (default ~/.cache/tensorfold/x-start-probe)" }, + .{ .name = "TF_QWEN_MERGE_WIDE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_QWEN_MERGE_WIDE_VERIFY", .scope = .cuda, .kind = .u32, .forms = "0 (off), 1 (compare the wide attention merge with the warp merge, trap on a difference) or 2 (the planted control: must trap)" }, .{ .name = "TF_Q35_GROUP_PROJ", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (1 groups same-input ModelOpt decode projections in one launch; default 0)" }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .scope = .cuda, .kind = .size, .min = 1, .max = 2147483647, .forms = "a whole page size from 1 to 2147483647 (unset: off)" }, .{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps shared-prefix snapshots on the device)" }, diff --git a/zig/src/platform/environment_valid_cases.zig b/zig/src/platform/environment_valid_cases.zig index fe64300059a..052119983d1 100644 --- a/zig/src/platform/environment_valid_cases.zig +++ b/zig/src/platform/environment_valid_cases.zig @@ -67,6 +67,21 @@ pub const valid = [_]Case{ .{ .name = "TENSORFOLD_RESTORE_PREFETCH_MS", .raw = "1099511627777", .n = 1099511627777 }, .{ .name = "TENSORFOLD_TOOL_ID_KEY_FILE", .raw = "/etc/tensorfold/tool id.key", .n = 0 }, .{ .name = "TF_RANK_SECRET_FILE", .raw = "/etc/tensorfold/rank.key", .n = 0 }, + .{ .name = "TF_QWEN_MERGE_WIDE", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_MERGE_WIDE", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_MERGE_WIDE_VERIFY", .raw = "2", .n = 2 }, + .{ .name = "TF_QWEN_MERGE_WIDE_VERIFY", .raw = "0", .n = 0 }, + .{ .name = "TF_X_START_LOG", .raw = "1", .n = 1 }, + .{ .name = "TF_X_START_HASH", .raw = "1", .n = 1 }, + .{ .name = "TF_X_START_COPY", .raw = "8", .n = 8 }, + .{ .name = "TF_X_START_COPY", .raw = "0", .n = 0 }, + .{ .name = "TF_X_EXE_PREHASH", .raw = "1", .n = 1 }, + .{ .name = "TF_X_DRAFT_CACHE", .raw = "1", .n = 1 }, + .{ .name = "TF_X_DRAFT_CACHE_DIR", .raw = "/var/tmp/draft-quant", .n = 0 }, + .{ .name = "TF_X_PROBE_CACHE", .raw = "1", .n = 1 }, + .{ .name = "TF_X_PROBE_CACHE", .raw = "verify", .n = 2 }, + .{ .name = "TF_X_PROBE_CACHE", .raw = "0", .n = 0 }, + .{ .name = "TF_X_PROBE_CACHE_DIR", .raw = "/var/tmp/x-start-probe", .n = 0 }, .{ .name = "TF_CACHE_WHY", .raw = "0", .n = 0 }, .{ .name = "TF_CACHE_WHY", .raw = "1", .n = 1 }, .{ .name = "TF_EXPLAIN", .raw = "0", .n = 0 }, diff --git a/zig/src/platform/file_identity.zig b/zig/src/platform/file_identity.zig index 03d0929bedf..2ec88d403bd 100644 --- a/zig/src/platform/file_identity.zig +++ b/zig/src/platform/file_identity.zig @@ -7,6 +7,15 @@ pub fn hash(io: std.Io, path: []const u8, maximum: u64) ![32]u8 { return hashFile(io, file, maximum); } +/// `hash` of the running binary, from the x-start prehash when it read this very file. +fn hashRunning(io: std.Io, path: []const u8, maximum: u64) ![32]u8 { + if (pre_thread == null and pre_value == null) return hash(io, path, maximum); + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + if (prehashedFor(file.handle)) |p| if (p.size <= maximum) return p.digest; + return hashFile(io, file, maximum); +} + /// An open file's bytes, checked against its stamps across the read; an open file keeps its inode if its path moves. pub fn hashFile(io: std.Io, file: std.Io.File, maximum: u64) ![32]u8 { return hashUntil(io, file, maximum, null); @@ -48,5 +57,80 @@ pub fn current(h: anytype, a: std.mem.Allocator, io: std.Io) !void { pub fn running(a: std.mem.Allocator, io: std.Io) ![32]u8 { const path = try std.process.executablePathAlloc(io, a); defer a.free(path); - return hash(io, path, 1 << 31); + return hashRunning(io, path, 1 << 31); +} + +// TF_X_EXE_PREHASH: the running binary read once while the model loads, into the two SHA-256 streams a start needs. +pub const Pre = struct { + digest: [32]u8, + seed: std.crypto.hash.sha2.Sha256, + dev: u64, + ino: u64, + size: u64, + mtime: [2]i64, + ctime: [2]i64, +}; +var pre_thread: ?std.Thread = null; +var pre_value: ?Pre = null; +var pre_joined = false; + +fn preFlag() bool { + return @import("environment.zig").read(bool, "TF_X_EXE_PREHASH", false) catch false; +} + +const linux = std.os.linux; + +fn statOf(fd: linux.fd_t) ?linux.Statx { + var st: linux.Statx = undefined; + const mask: linux.STATX = .{ .INO = true, .SIZE = true, .MTIME = true, .CTIME = true }; + if (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, mask, &st)) != .SUCCESS) return null; + return st; +} + +fn preRun() void { + const rc = linux.open("/proc/self/exe", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0); + if (linux.errno(rc) != .SUCCESS) return; + const fd: linux.fd_t = @intCast(rc); + defer _ = linux.close(fd); + const before = statOf(fd) orelse return; + var plain = std.crypto.hash.sha2.Sha256.init(.{}); + var seed = std.crypto.hash.sha2.Sha256.init(.{}); + var len: [8]u8 = undefined; + std.mem.writeInt(u64, &len, before.size, .little); + seed.update(&len); + var buf: [1 << 20]u8 = undefined; + var at: u64 = 0; + while (at < before.size) { + const want: usize = @intCast(@min(buf.len, before.size - at)); + const n = linux.pread(fd, &buf, want, @intCast(at)); + if (linux.errno(n) != .SUCCESS or n == 0) return; + plain.update(buf[0..n]); + seed.update(buf[0..n]); + at += n; + } + const after = statOf(fd) orelse return; + if (after.size != before.size or after.ino != before.ino or after.mtime.sec != before.mtime.sec or after.mtime.nsec != before.mtime.nsec or + after.ctime.sec != before.ctime.sec or after.ctime.nsec != before.ctime.nsec) return; + pre_value = .{ .digest = plain.finalResult(), .seed = seed, .dev = (@as(u64, before.dev_major) << 32) | before.dev_minor, .ino = before.ino, .size = before.size, .mtime = .{ before.mtime.sec, before.mtime.nsec }, .ctime = .{ before.ctime.sec, before.ctime.nsec } }; +} + +/// Starts the hashing thread once (only with TF_X_EXE_PREHASH set); call early in the load. +pub fn prehash() void { + if (pre_thread != null or pre_joined or !preFlag()) return; + pre_thread = std.Thread.spawn(.{}, preRun, .{}) catch null; +} + +/// The prehashed result when it was for the file open as `fd` (same stamps), else null. Joins the thread once. +pub fn prehashedFor(fd: linux.fd_t) ?Pre { + if (!pre_joined) { + if (pre_thread) |t| t.join(); + pre_thread = null; + pre_joined = true; + } + const p = pre_value orelse return null; + const st = statOf(fd) orelse return null; + const dev = (@as(u64, st.dev_major) << 32) | st.dev_minor; + if (dev != p.dev or st.ino != p.ino or st.size != p.size or st.mtime.sec != p.mtime[0] or st.mtime.nsec != p.mtime[1] or + st.ctime.sec != p.ctime[0] or st.ctime.nsec != p.ctime[1]) return null; + return p; }