From ce39aa8278607c240bea14e175282c5363ee0edd Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:47:48 +0900 Subject: [PATCH 01/59] glm cuda: NVFP4_NZ5 checkpoints, block 32's experts with E2M1's code 0b1000 read as +5 E2M1 spends two of its sixteen codes on zero. A quantized_layers entry of {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1", "code_map": "e2m1_nz5"} holds csf0_v1's tensors in the same layout and reads 0b1000 as +5. admitRecipes takes that pairing alone and refuses a code map beside any other recipe by module, and GLM's CUDA load refuses a checkpoint that declares both NVFP4_NZ5 and NVFP4 csf0_v1. nvfp4_experts32.cu gains NZ5 entries of its five launches: the same templates with fp4pair_nz5, which turns fp4pair's 0x8000 (-0) into 0x40A0 (+5), and the same sums in the same order. The image loads the E2M1 or the NZ5 entries as the checkpoint's modules declare, so a csf0_v1 checkpoint runs the entries it ran before and a block 16 one loads no block 32 image. The kernel contract holds each NZ5 entry bit-equal to the block 16 instance it replaces on the same values, a planted +5 written there as a 4 under a scale two e4m3 steps up, with E2M1's entry on NZ5's codes as the planted control; nvfp4_experts32_records.zig gives their limits under nvcc 13.0 and 13.3. tf-cuda-test nvfp4-nz5 compares each form's bytes with E2M1's kernels on the same values at widths 1,024, 704 and 640, on bf16 integer inputs so that a group's sum is exact before its scale. The FP4-Local recipe count in modelopt's test gains the new recipe's zero. --- CHANGELOG.md | 2 + docs/kernel-contract.md | 3 + docs/quantization.md | 11 + zig/kernels/cuda/common/fp_pairs.cuh | 6 + zig/kernels/cuda/nvfp4_experts32.cu | 63 +++--- .../core/contract/nvfp4_experts32_records.zig | 14 +- zig/src/core/modelopt.zig | 39 +++- zig/src/cuda/experts32.zig | 13 +- zig/src/families/glm/cuda_engine.zig | 2 +- zig/src/families/glm/cuda_experts.zig | 38 +++- zig/src/families/glm/cuda_formats.zig | 8 +- zig/src/families/glm/cuda_forward.zig | 4 +- zig/tests/cuda/contract_nvfp4_fact.zig | 64 +++++- zig/tests/cuda/contract_nvfp4_tile.zig | 10 +- zig/tests/cuda/glm_exl3_tests.zig | 2 +- zig/tests/cuda/main.zig | 3 + zig/tests/cuda/nvfp4_b32_tests.zig | 2 +- zig/tests/cuda/nvfp4_nz5_tests.zig | 203 ++++++++++++++++++ 18 files changed, 429 insertions(+), 58 deletions(-) create mode 100644 zig/tests/cuda/nvfp4_nz5_tests.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bcccc5867a..8847d5adaec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -345,6 +345,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Internal: core gains one walk for copying kept prompt states, and GLM's copies on CUDA and Metal go through it, with the same copies in the same order; other families keep their own loops. Nothing a user sees changes (#2215, part of #1293). Thanks to @jschmied. +- GLM-5.3-Flash on CUDA reads `NVFP4_NZ5` checkpoints: csf0_v1's layout with E2M1's second zero, code 0b1000, read as +5, in the same memory as csf0_v1; every other checkpoint loads and runs as before, with the same tokens. Thanks to @Bizuayeu. + - CUDA, opt-in build (`-Dnative-fp-decode`): qmmf's FP4 decode rows use the shared native e2m1 pair decode, `tf_common::e2m1_pairs`, which equals the existing decode on all 2^33 inputs; the default build's 113 fatbins are byte-identical and GB10 decode is level (#2721). Thanks to @jschmied. - Qwen3.8-27B on Metal: while a request runs, the keep-warm ticker now commits the residency sets' probe each interval, so the first command buffer after a wide prompt pass no longer waits in the kernel (likely for macOS to wire the model again; not traced). On an M5 Ultra with a 14 GiB prompt cache filling memory, five cold 24K- to 64K-token prompts in a row reach their first tokens 3.5% to 5.9% sooner in total; with the cache off, cold prompts are level. Replies are unchanged (#2725, fixes #2724). Thanks to @mrv777. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 837eaa5695b..fed5013aeff 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -405,6 +405,9 @@ CUDA also checks the bf16 experts (`experts_bf16.cu`, a checkpoint's own bf16 we and shared experts): relu^2 up, fp32 down and bf16 down, in the decode and prompt forms, against float64 (two controls: the fp32 down launched one 32-input group short, and a down summing in bf16). nvcc 13.2's prompt forms and 13.3's decode forms on sm_120 and sm_121 take other registers than 13.0's and have their own records. +CUDA also checks GLM's NVFP4_NZ5 block 32 experts (`tf_nvfp4_nz5_*`), each bit-equal to the block 16 instance it +replaces on the same values: a planted +5 is a 4 there under its scale two e4m3 steps up (x1.25), and the E2M1 +entry reading NVFP4_NZ5's codes, each +5 as -0, is the planted control. CUDA also checks Nemotron's pocket (`nemotron_ops.cu`, the learned neurons the living-weights learner adds beside the shared expert): relu^2 up into act rows and down added into the shared expert's slot, a block row a row and tiled, the down to fp32 and bf16, against float64, the neurons past the count NaN so a read of one shows (two controls: the up's diff --git a/docs/quantization.md b/docs/quantization.md index 37727cb76d9..7e8ff6114f2 100644 --- a/docs/quantization.md +++ b/docs/quantization.md @@ -164,6 +164,17 @@ GLM-5.3-Flash's CUDA engine reads csf0_v1 for its routed experts (`mlp.experts.N `down_proj`), every expert of a layer in that form, and loads its block 32 kernels only for such a checkpoint (`Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4` is one). +## NVFP4_NZ5: csf0_v1 with code 0b1000 read as +5 + +E2M1 spends two of its sixteen codes on zero: 0b1000 is -0. An entry of `{"quant_algo": "NVFP4_NZ5", "group_size": 32, +"weight_scale_encoding": "csf0_v1", "code_map": "e2m1_nz5"}` holds csf0_v1's tensors in the same layout and reads +0b1000 as +5, so a weight is `v(code) × e4m3(base + offset) × weight_scale_2`, where v is e2m1 for the other fifteen +codes and 5 for 0b1000; zero is written 0b0000. The values stay within ±6, and 5 has three significant bits, so its +products with e4m3 scales stay exact in bf16. `code_map` may be left out; beside any other recipe it is refused by +module, so a code map is never read as E2M1's. GLM-5.3-Flash's CUDA engine loads its block 32 kernels' NVFP4_NZ5 +entries (`tf_nvfp4_nz5_*`) for such a checkpoint (`Bizuayeu/GLM-5.3-Flash-Jammed-XSFP4-NZ5` is one), and refuses one +that declares both NVFP4_NZ5 and NVFP4 csf0_v1. + ## Native safetensors metadata The shared Zig safetensors index retains up to five dimensions, including temporal patch convolutions diff --git a/zig/kernels/cuda/common/fp_pairs.cuh b/zig/kernels/cuda/common/fp_pairs.cuh index abd1829da67..a93644f8992 100644 --- a/zig/kernels/cuda/common/fp_pairs.cuh +++ b/zig/kernels/cuda/common/fp_pairs.cuh @@ -25,6 +25,12 @@ __device__ __forceinline__ uint32_t fp4pair(uint32_t w, int s) { return r; } +// fp4pair with code 0b1000 read as +5 (NVFP4_NZ5): the one code fp4pair widens to 0x8000, -0, becomes 0x40A0. +__device__ __forceinline__ uint32_t fp4pair_nz5(uint32_t w, int s) { + const uint32_t r = fp4pair(w, s); + return r ^ (__vcmpeq2(r, 0x80008000u) & 0xC0A0C0A0u); +} + // Two E4M3 codes, the low two bytes of v, as a bf16x2 pair. __device__ __forceinline__ uint32_t fp8pair(uint32_t v) { const uint32_t t = ((v & 0x7Fu) << 4) | ((v & 0x80u) << 8) | ((v & 0x7F00u) << 12) | ((v & 0x8000u) << 16); diff --git a/zig/kernels/cuda/nvfp4_experts32.cu b/zig/kernels/cuda/nvfp4_experts32.cu index e42f0276c8f..dae6b9ee52f 100644 --- a/zig/kernels/cuda/nvfp4_experts32.cu +++ b/zig/kernels/cuda/nvfp4_experts32.cu @@ -17,9 +17,17 @@ using tf_common::ld_nc; using tf_common::ld_nc2; using tf_common::ld_nc32; using tf_common::fp4pair; +using tf_common::fp4pair_nz5; using tf_common::e4m3f; +// Two codes as a bf16 pair: E2M1's values, or NVFP4_NZ5's (0b1000 is +5) when NZ. +template +__device__ __forceinline__ uint32_t e2m1pair(uint32_t w, int s) { + if constexpr (NZ) return fp4pair_nz5(w, s); + else return fp4pair(w, s); +} + template struct Stage { uint4 w[M]; @@ -45,7 +53,7 @@ __device__ __forceinline__ void load_stage(Stage& st, const uint4* blk, int g } } -template +template __device__ __forceinline__ void compute_stage(float (&acc)[M][1][NTW][4], const Stage& st, const uint2* bq, bool hi) { #pragma unroll for (int m = 0; m < M; ++m) { @@ -64,7 +72,7 @@ __device__ __forceinline__ void compute_stage(float (&acc)[M][1][NTW][4], const for (int j = 0; j < NTW; ++j) { const uint32_t word = comp(st.w[m], j); float p[4] = {0.f, 0.f, 0.f, 0.f}; - mma(p, a0, a1, a2, a3, fp4pair(word, 8 * h), fp4pair(word, 8 * h + 4)); + mma(p, a0, a1, a2, a3, e2m1pair(word, 8 * h), e2m1pair(word, 8 * h + 4)); float(&a)[4] = acc[m][0][j]; a[0] = fmaf(p[0], sf[j][0], a[0]); a[1] = fmaf(p[1], sf[j][1], a[1]); @@ -77,7 +85,7 @@ __device__ __forceinline__ void compute_stage(float (&acc)[M][1][NTW][4], const } } -template +template __device__ __forceinline__ void k_loop(float (&acc)[M][1][NTW][4], const uint4* blk, const uint2* bq, int KG, int lane, int t, const __nv_bfloat16* x0, const __nv_bfloat16* x1, bool v0, bool v1) { constexpr int D = 2; @@ -90,7 +98,7 @@ __device__ __forceinline__ void k_loop(float (&acc)[M][1][NTW][4], const uint4* for (int d = 0; d < D; ++d) { const int g = g0 + d; if (g < KG) { - compute_stage(acc, st[d], bq, v1); + compute_stage(acc, st[d], bq, v1); if (g + D < KG) load_stage(st[d], blk, g + D, d, lane, t, x0, x1, v0, v1); } } @@ -98,7 +106,7 @@ __device__ __forceinline__ void k_loop(float (&acc)[M][1][NTW][4], const uint4* } // One unit of the decode form: a warp's 32 columns of item `unit / NB` over all K, then the epilogue. -template +template __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, @@ -124,7 +132,7 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, con for (int m = 0; m < M; ++m) #pragma unroll for (int j = 0; j < NTW; ++j) acc[m][0][j][0] = acc[m][0][j][1] = acc[m][0][j][2] = acc[m][0][j][3] = 0.f; - k_loop(acc, blk, bq, KG, lane, t, x0, x1, v0, v1); + k_loop(acc, blk, bq, KG, lane, t, x0, x1, v0, v1); #pragma unroll for (int m = 0; m < M; ++m) { const float g = __ldg(scale + e * M + m); @@ -137,7 +145,7 @@ __device__ __forceinline__ void unit_full(int unit, int lane, int gq, int t, con } } -template +template __device__ __forceinline__ void decode_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, @@ -146,7 +154,7 @@ __device__ __forceinline__ void decode_body(const __nv_bfloat16* __restrict__ X, const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; const int units = __ldg(counts) * NB; for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) - unit_full(unit, lane, gq, t, X, x_stride, slots, W, scale, KG, NB, items, members, out, N, limit, skip); + unit_full(unit, lane, gq, t, X, x_stride, slots, W, scale, KG, NB, items, members, out, N, limit, skip); } // The prompt form's tile: 16 RT rows a warp, WM x WN warps (BM pairs of one item by WN 32-column blocks a CTA). @@ -168,7 +176,7 @@ __device__ __forceinline__ uint32_t e4m3x2(uint32_t x) { return r; } -// a * b in bf16 pairs; exact for e2m1 codes times e4m3 scales (six significant bits at most). +// a * b in bf16 pairs; exact for e2m1 codes and NZ5's 5 times e4m3 scales (seven significant bits at most). __device__ __forceinline__ uint32_t mul2(uint32_t a, uint32_t b) { uint32_t r; asm("fma.rn.bf16x2 %0, %1, %2, %3;\n" : "=r"(r) : "r"(a), "r"(b), "r"(0x80008000u)); @@ -176,7 +184,7 @@ __device__ __forceinline__ uint32_t mul2(uint32_t a, uint32_t b) { } // Prompt rows, 64 inputs a stage, NT row tiles a warp. -template +template __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ members, void* __restrict__ out, int N, @@ -273,7 +281,7 @@ __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X #pragma unroll for (int j = 0; j < NTW; ++j) { const uint32_t word = comp(wv[m], j); - const uint32_t b0 = mul2(fp4pair(word, 8 * h), sv[m][j]), b1 = mul2(fp4pair(word, 8 * h + 4), sv[m][j]); + const uint32_t b0 = mul2(e2m1pair(word, 8 * h), sv[m][j]), b1 = mul2(e2m1pair(word, 8 * h + 4), sv[m][j]); #pragma unroll for (int r = 0; r < NT; ++r) mma(acc[m][r][j], xa[r].x, xb[r].x, xa[r].y, xb[r].y, b0, b1); } @@ -302,7 +310,7 @@ __device__ __forceinline__ void prompt_tiles(const __nv_bfloat16* __restrict__ X } } -template +template __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, @@ -315,7 +323,7 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, if (e == skip) return; // an expert the family computes itself, left alone as the decode form does const int nt = max(0, min(RT, (cnt - 16 * RT * ((threadIdx.x >> 5) / WN) + 15) >> 4)); #define TF_TILES(NT) \ - prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, first, cnt) + prompt_tiles(X, x_stride, slots, W, scale, KG, NB, members, out, N, limit, cbt, e, first, cnt) switch (nt) { case 4: TF_TILES(4); break; case 3: TF_TILES(3); break; @@ -327,27 +335,32 @@ __device__ __forceinline__ void prompt_body(const __nv_bfloat16* __restrict__ X, } } -// The decode form's entries, 4 warps a CTA: SwiGLU gate-up, fp32 and bf16 sums down. -#define TF_NVFP4_DECODE32(NAME, M, EPI) \ +// The decode form's entries, 4 warps a CTA: SwiGLU gate-up, fp32 and bf16 sums down; NZ reads NVFP4_NZ5's codes. +#define TF_NVFP4_DECODE32(NAME, M, EPI, NZ) \ extern "C" __global__ void __launch_bounds__(4 * 32) NAME( \ const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, \ const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, \ const int* __restrict__ members, void* __restrict__ out, int N, float limit, int skip) { \ - tf_nvfp4_experts32::decode_body(X, x_stride, slots, W, scale, KG, NB, items, counts, members, out, N, \ - limit, skip); \ + tf_nvfp4_experts32::decode_body(X, x_stride, slots, W, scale, KG, NB, items, counts, members, out, \ + N, limit, skip); \ } -TF_NVFP4_DECODE32(tf_nvfp4_decode32_swiglu, 2, 2) -TF_NVFP4_DECODE32(tf_nvfp4_decode32_down_f32, 1, 0) -TF_NVFP4_DECODE32(tf_nvfp4_decode32_down_bf16, 1, 3) +TF_NVFP4_DECODE32(tf_nvfp4_decode32_swiglu, 2, 2, false) +TF_NVFP4_DECODE32(tf_nvfp4_decode32_down_f32, 1, 0, false) +TF_NVFP4_DECODE32(tf_nvfp4_decode32_down_bf16, 1, 3, false) +TF_NVFP4_DECODE32(tf_nvfp4_nz5_decode32_swiglu, 2, 2, true) +TF_NVFP4_DECODE32(tf_nvfp4_nz5_decode32_down_f32, 1, 0, true) +TF_NVFP4_DECODE32(tf_nvfp4_nz5_decode32_down_bf16, 1, 3, true) // The prompt form's entries, 4 row tiles a warp in one row of WN warps: SwiGLU gate-up, bf16 sums down. -#define TF_NVFP4_PROMPT32(NAME, M, EPI, WN) \ +#define TF_NVFP4_PROMPT32(NAME, M, EPI, WN, NZ) \ extern "C" __global__ void __launch_bounds__(WN * 32) NAME( \ const __nv_bfloat16* __restrict__ X, int x_stride, int slots, const uint4* __restrict__ W, \ const float* __restrict__ scale, int KG, int NB, const int* __restrict__ items, const int* __restrict__ counts, \ const int* __restrict__ members, void* __restrict__ out, int N, float limit, int skip) { \ - tf_nvfp4_experts32::prompt_body(X, x_stride, slots, W, scale, KG, NB, items, counts, members, \ - out, N, limit, skip); \ + tf_nvfp4_experts32::prompt_body(X, x_stride, slots, W, scale, KG, NB, items, counts, \ + members, out, N, limit, skip); \ } -TF_NVFP4_PROMPT32(tf_nvfp4_prompt32_swiglu, 2, 2, 4) -TF_NVFP4_PROMPT32(tf_nvfp4_prompt32_down, 1, 3, 8) +TF_NVFP4_PROMPT32(tf_nvfp4_prompt32_swiglu, 2, 2, 4, false) +TF_NVFP4_PROMPT32(tf_nvfp4_prompt32_down, 1, 3, 8, false) +TF_NVFP4_PROMPT32(tf_nvfp4_nz5_prompt32_swiglu, 2, 2, 4, true) +TF_NVFP4_PROMPT32(tf_nvfp4_nz5_prompt32_down, 1, 3, 8, true) diff --git a/zig/src/core/contract/nvfp4_experts32_records.zig b/zig/src/core/contract/nvfp4_experts32_records.zig index d0a83c7a2c0..1360b79da62 100644 --- a/zig/src/core/contract/nvfp4_experts32_records.zig +++ b/zig/src/core/contract/nvfp4_experts32_records.zig @@ -1,4 +1,4 @@ -//! tf_nvfp4_decode32_* and tf_nvfp4_prompt32_* (nvfp4_experts32.cu): block 32 csf0 experts, nvcc 13.0, five SMs. +//! tf_nvfp4_decode32_*, tf_nvfp4_prompt32_* and the nz5 entries (nvfp4_experts32.cu): block 32, nvcc 13.0, five SMs. const registry = @import("registry.zig"); pub const cuda = [_]registry.CudaRecord{ @@ -7,10 +7,20 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_decode32_down_bf16", .symbol = "tf_nvfp4_decode32_down_bf16", .image = "nvfp4_experts32", .threads = 128 }, .usage = .{ .{ .regs = 93, .static = 0, .bound = 128 }, .{ .regs = 93, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_prompt32_swiglu", .symbol = "tf_nvfp4_prompt32_swiglu", .image = "nvfp4_experts32", .threads = 128, .dynamic = 33280 }, .usage = .{ .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 226, .static = 0, .bound = 128 }, .{ .regs = 226, .static = 0, .bound = 128 } } }, .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_prompt32_down", .symbol = "tf_nvfp4_prompt32_down", .image = "nvfp4_experts32", .threads = 256, .dynamic = 33280 }, .usage = .{ .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 140, .static = 0, .bound = 256 }, .{ .regs = 140, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_swiglu", .symbol = "tf_nvfp4_nz5_decode32_swiglu", .image = "nvfp4_experts32", .threads = 128 }, .usage = .{ .{ .regs = 127, .static = 0, .bound = 128 }, .{ .regs = 127, .static = 0, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_down_f32", .symbol = "tf_nvfp4_nz5_decode32_down_f32", .image = "nvfp4_experts32", .threads = 128 }, .usage = .{ .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_down_bf16", .symbol = "tf_nvfp4_nz5_decode32_down_bf16", .image = "nvfp4_experts32", .threads = 128 }, .usage = .{ .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_prompt32_swiglu", .symbol = "tf_nvfp4_nz5_prompt32_swiglu", .image = "nvfp4_experts32", .threads = 128, .dynamic = 33280 }, .usage = .{ .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 228, .static = 0, .bound = 128 }, .{ .regs = 228, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_prompt32_down", .symbol = "tf_nvfp4_nz5_prompt32_down", .image = "nvfp4_experts32", .threads = 256, .dynamic = 33280 }, .usage = .{ .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 142, .static = 0, .bound = 256 }, .{ .regs = 142, .static = 0, .bound = 256 } } }, }; -/// What nvcc 13.3 compiles differently: the prompt entries on sm_120 and sm_121. +/// What nvcc 13.3 compiles differently: the prompt entries on sm_120 and sm_121, and each nz5 entry there. pub const cuda_133 = [_]registry.Override{ .{ .name = "nvfp4_experts32 tf_nvfp4_prompt32_swiglu", .usage = .{ .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 252, .static = 0, .bound = 128 }, .{ .regs = 225, .static = 0, .bound = 128 }, .{ .regs = 225, .static = 0, .bound = 128 } } }, .{ .name = "nvfp4_experts32 tf_nvfp4_prompt32_down", .usage = .{ .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_swiglu", .usage = .{ .{ .regs = 127, .static = 0, .bound = 128 }, .{ .regs = 127, .static = 0, .bound = 128 }, .{ .regs = 128, .static = 0, .bound = 128 }, .{ .regs = 125, .static = 0, .bound = 128 }, .{ .regs = 125, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_down_f32", .usage = .{ .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_decode32_down_bf16", .usage = .{ .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_prompt32_swiglu", .usage = .{ .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 253, .static = 0, .bound = 128 }, .{ .regs = 226, .static = 0, .bound = 128 }, .{ .regs = 226, .static = 0, .bound = 128 } } }, + .{ .name = "nvfp4_experts32 tf_nvfp4_nz5_prompt32_down", .usage = .{ .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 154, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, }; diff --git a/zig/src/core/modelopt.zig b/zig/src/core/modelopt.zig index fd3ffbfaf24..a0269f164d0 100644 --- a/zig/src/core/modelopt.zig +++ b/zig/src/core/modelopt.zig @@ -18,6 +18,8 @@ pub const Recipe = enum { nvfp4_csf, /// NVFP4 with an e4m3 scale every 32 inputs: csf0_v1's row base plus 4-bit offset (experts32.Matrix). nvfp4_csf0, + /// NVFP4_NZ5: nvfp4_csf0's layout and scales, its code 0b1000 read as +5 in place of -0 (code_map e2m1_nz5). + nvfp4_nz5, /// W4A16_NVFP4: NVFP4 weights without an input scale. w4a16_nvfp4, /// MXFP8: e4m3 weights, a UE8M0 scale every 32 inputs. @@ -124,6 +126,14 @@ fn recipeOf(entry: ?std.json.ObjectMap) ?Recipe { const group = o.get("group_size"); const blocks = o.get("weight_block_size"); const encoding = o.get("weight_scale_encoding"); + const map = o.get("code_map"); + if (std.ascii.eqlIgnoreCase(algo, "NVFP4_NZ5")) { + const named = map == null or std.mem.eql(u8, text(map) orelse "", "e2m1_nz5"); + const csf0 = std.mem.eql(u8, text(encoding) orelse "", "csf0_v1"); + return if (named and csf0 and int(group) == csf0_group and blocks == null) .nvfp4_nz5 else null; + } + // a code map beside any other recipe: refused, not its values read as E2M1's + if (map != null) return null; if (std.ascii.eqlIgnoreCase(algo, "NVFP4") and std.mem.eql(u8, text(encoding) orelse "", "csf0_v1")) { return if (int(group) == csf0_group and blocks == null) .nvfp4_csf0 else null; } @@ -250,7 +260,7 @@ test "nvidia/GLM-5.3-Flash-FP4-Local's recipes: a module's, and its tensors' und var count = std.EnumArray(Recipe, usize).initFill(0); var it = r.modules.valueIterator(); while (it.next()) |v| count.getPtr(v.*).* += 1; - try std.testing.expectEqualSlices(usize, &.{ 0, 42, 0, 77, 205, 170, 0 }, &count.values); // the vision tower's MLPs too + try std.testing.expectEqualSlices(usize, &.{ 0, 42, 0, 0, 77, 205, 170, 0 }, &count.values); // the vision tower's MLPs too const at = "model.language_model.layers."; const cases = [_]struct { []const u8, ?Recipe }{ .{ at ++ "3.mlp.experts.17.gate_proj.weight", .nvfp4_csf }, // routed experts: one entry a layer @@ -371,6 +381,33 @@ test "csf0_v1 is NVFP4 at group 32 alone; a group of 32 without it, or any other , "m.e: NVFP4"); } +test "NVFP4_NZ5 is csf0_v1's layout read with 0b1000 as +5; a code map on any other recipe is refused by module" { + var why: Why = .{}; + var r = try admitRecipes(std.testing.allocator, + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": + \\ {"m.3.experts": {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1", "code_map": "e2m1_nz5"}, + \\ "m.4.experts": {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1"}}}} + , &why); + defer r.deinit(); + try std.testing.expectEqual(@as(?Recipe, .nvfp4_nz5), r.of("m.3.experts.0.gate_proj.weight")); + try std.testing.expectEqual(@as(?Recipe, .nvfp4_nz5), r.of("m.4.experts.7.down_proj.weight")); + try expectRecipesRefused( + \\, "quantized_layers": {"m.e": {"quant_algo": "NVFP4", "group_size": 32, "weight_scale_encoding": "csf0_v1", "code_map": "e2m1_nz5"}} + , "m.e: NVFP4"); + try expectRecipesRefused( + \\, "quantized_layers": {"m.e": {"quant_algo": "NVFP4", "group_size": 16, "code_map": "e2m1"}} + , "m.e: NVFP4"); + try expectRecipesRefused( + \\, "quantized_layers": {"m.e": {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1", "code_map": "e2m1"}} + , "m.e: NVFP4_NZ5"); + try expectRecipesRefused( + \\, "quantized_layers": {"m.e": {"quant_algo": "NVFP4_NZ5", "group_size": 32}} + , "m.e: NVFP4_NZ5"); + try expectRecipesRefused( + \\, "quantized_layers": {"m.e": {"quant_algo": "NVFP4_NZ5", "group_size": 16, "weight_scale_encoding": "csf0_v1"}} + , "m.e: NVFP4_NZ5"); +} + test "empty MIXED_PRECISION recipes retain their identity beside single-format NVFP4" { var why: Why = .{}; var mixed = try admitRecipes(std.testing.allocator, diff --git a/zig/src/cuda/experts32.zig b/zig/src/cuda/experts32.zig index 7f20278e1b9..3135c74c7f4 100644 --- a/zig/src/cuda/experts32.zig +++ b/zig/src/cuda/experts32.zig @@ -26,6 +26,9 @@ pub const Matrix = struct { } }; +/// The values a code names: E2M1's, or E2M1's with 0b1000 read as +5 in place of -0 (NVFP4_NZ5). +pub const Values = enum { e2m1, nz5 }; + pub const Nvfp4b32Experts = struct { mod: module.Module, fns: [3]module.Function, // by Epi @@ -41,6 +44,8 @@ pub const Nvfp4b32Experts = struct { pub const symbols = struct { pub const decode = [3][:0]const u8{ "tf_nvfp4_decode32_swiglu", "tf_nvfp4_decode32_down_f32", "tf_nvfp4_decode32_down_bf16" }; pub const prompt = [2][:0]const u8{ "tf_nvfp4_prompt32_swiglu", "tf_nvfp4_prompt32_down" }; + pub const decode_nz5 = [3][:0]const u8{ "tf_nvfp4_nz5_decode32_swiglu", "tf_nvfp4_nz5_decode32_down_f32", "tf_nvfp4_nz5_decode32_down_bf16" }; + pub const prompt_nz5 = [2][:0]const u8{ "tf_nvfp4_nz5_prompt32_swiglu", "tf_nvfp4_nz5_prompt32_down" }; }; /// The prompt entries' warps (32-column blocks) a CTA and matrices a block: SwiGLU gate-up, down. @@ -54,16 +59,18 @@ pub const Nvfp4b32Experts = struct { return stages * stage; } - pub fn load(d: *const driver.Driver, sms: usize) !Nvfp4b32Experts { + /// The entries that read codes as `values`: the same sums, the same layout. + pub fn load(d: *const driver.Driver, sms: usize, values: Values) !Nvfp4b32Experts { if (!kernels.available) return error.BuiltWithoutKernels; var mod = try module.Module.load(d, kernels.nvfp4_experts32); errdefer mod.unload(); var e: Nvfp4b32Experts = .{ .mod = mod, .fns = undefined, .resident = undefined, .prompt_fns = undefined }; - for (symbols.decode, &e.fns, &e.resident) |name, *f, *r| { + const nz5 = values == .nz5; + for (if (nz5) symbols.decode_nz5 else symbols.decode, &e.fns, &e.resident) |name, *f, *r| { f.* = try mod.function(name); r.* = @max(1, try f.occupancy(warps * 32, 0)) * sms; } - for (symbols.prompt, &e.prompt_fns, prompt_parts, prompt_wn) |name, *f, parts, wn| { + for (if (nz5) symbols.prompt_nz5 else symbols.prompt, &e.prompt_fns, prompt_parts, prompt_wn) |name, *f, parts, wn| { f.* = try mod.function(name); try f.allowDynamicShared(promptSmem(parts, wn)); } diff --git a/zig/src/families/glm/cuda_engine.zig b/zig/src/families/glm/cuda_engine.zig index 3cc2adec230..ac91dc2c2a8 100644 --- a/zig/src/families/glm/cuda_engine.zig +++ b/zig/src/families/glm/cuda_engine.zig @@ -155,7 +155,7 @@ pub const Engine = struct { const spans = try gpa.alloc(shard.Span, world); errdefer gpa.free(spans); for (spans, 0..) |*sp, q| sp.* = (try shard.Share.of(&c, q, world)).vocab; - const block32 = !exl3.isExl3(gpa, text) and try @import("cuda_experts.zig").wantsBlock32(gpa, text); + const block32 = if (exl3.isExl3(gpa, text)) null else try @import("cuda_experts.zig").wantsBlock32(gpa, text); var m = try fw.Modules.load(d, ctx, block32); errdefer m.deinit(); const pair = prompt_pair.wanted(o.settings.pair, o.settings.solo, world); diff --git a/zig/src/families/glm/cuda_experts.zig b/zig/src/families/glm/cuda_experts.zig index 48f4c2b5c71..f70972f84de 100644 --- a/zig/src/families/glm/cuda_experts.zig +++ b/zig/src/families/glm/cuda_experts.zig @@ -19,11 +19,11 @@ pub const Kernels = struct { router: cuda.grouped.Router, fact: bool = false, // decode windows on NVFP4's factored tiles (the same bits): load timing picks it (cuda_lane_costs) - /// `plans`: the loaded experts module (its plan kernels); `block32`: block 32's image too. - pub fn load(d: *const cuda.Driver, plans: cuda.Module, sms: u32, block32: bool) !Kernels { + /// `plans`: the loaded experts module (its plan kernels); `block32`: block 32's image too, for these values. + pub fn load(d: *const cuda.Driver, plans: cuda.Module, sms: u32, block32: ?cuda.experts32.Values) !Kernels { var nvfp4 = try cuda.experts.Nvfp4Experts.load(d, sms); errdefer nvfp4.unload(); - var b32: ?cuda.experts32.Nvfp4b32Experts = if (block32) try cuda.experts32.Nvfp4b32Experts.load(d, sms) else null; + var b32: ?cuda.experts32.Nvfp4b32Experts = if (block32) |v| try cuda.experts32.Nvfp4b32Experts.load(d, sms, v) else null; errdefer if (b32) |*x| x.unload(); return .{ .nvfp4 = nvfp4, .b32 = b32, .router = try cuda.grouped.Router.resolve(plans) }; } @@ -34,12 +34,14 @@ pub const Kernels = struct { } }; -/// Whether config.json declares a csf0_v1 module: block 32's kernels load for such a checkpoint alone. -pub fn wantsBlock32(gpa: std.mem.Allocator, config_json: []const u8) !bool { +/// The values config.json's csf0_v1 modules read their codes as, E2M1's or NVFP4_NZ5's; null when it declares none. +pub fn wantsBlock32(gpa: std.mem.Allocator, config_json: []const u8) !?cuda.experts32.Values { var why: core.modelopt.Why = .{}; var recipes = try core.modelopt.admitRecipes(gpa, config_json, &why); defer recipes.deinit(); - return recipes.has(.nvfp4_csf0); + const e2m1 = recipes.has(.nvfp4_csf0); + if (e2m1 and recipes.has(.nvfp4_nz5)) return error.UnsupportedQuant; // formats.admit names it at the entry + return if (recipes.has(.nvfp4_nz5)) .nz5 else if (e2m1) .e2m1 else null; } /// A grouped plan: the router's arrays, the slots a row holds, the experts; `fact`: decode rows on prompt-sized items. @@ -71,21 +73,39 @@ pub fn run(ks: *const Kernels, stream: cuda.Stream, which: Which, l: cuda.expert test "block 32's kernels are wanted for a csf0_v1 module alone, not for block 16's recipes or a single-format NVFP4" { const gpa = std.testing.allocator; - try std.testing.expect(try wantsBlock32(gpa, + try std.testing.expectEqual(@as(?cuda.experts32.Values, .e2m1), try wantsBlock32(gpa, \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": \\ {"m.3.experts": {"quant_algo": "NVFP4", "group_size": 32, "weight_scale_encoding": "csf0_v1"}, \\ "m.45.experts": {"quant_algo": "W4A16_NVFP4", "group_size": 16}}}} )); - try std.testing.expect(!try wantsBlock32(gpa, + try std.testing.expectEqual(@as(?cuda.experts32.Values, null), try wantsBlock32(gpa, \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": \\ {"m.3.experts": {"quant_algo": "NVFP4", "group_size": 16}, "m.45.experts": {"quant_algo": "W4A16_NVFP4", "group_size": 16}}}} )); - try std.testing.expect(!try wantsBlock32(gpa, + try std.testing.expectEqual(@as(?cuda.experts32.Values, null), try wantsBlock32(gpa, \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4", "config_groups": \\ {"g": {"weights": {"num_bits": 4, "type": "float", "group_size": 16}}}}} )); } +test "NVFP4_NZ5's modules want block 32's nz5 kernels, and a checkpoint that mixes them with E2M1's csf0_v1 is refused" { + const gpa = std.testing.allocator; + try std.testing.expectEqual(@as(?cuda.experts32.Values, .nz5), try wantsBlock32(gpa, + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": + \\ {"m.3.experts": {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1", "code_map": "e2m1_nz5"}, + \\ "m.45.experts": {"quant_algo": "W4A16_NVFP4", "group_size": 16}}}} + )); + const mixed = + \\{"quantization_config": {"quant_method": "modelopt", "quant_algo": "MIXED_PRECISION", "quantized_layers": + \\ {"m.3.experts": {"quant_algo": "NVFP4_NZ5", "group_size": 32, "weight_scale_encoding": "csf0_v1"}, + \\ "m.4.experts": {"quant_algo": "NVFP4", "group_size": 32, "weight_scale_encoding": "csf0_v1"}}}} + ; + try std.testing.expectError(error.UnsupportedQuant, wantsBlock32(gpa, mixed)); + var why: core.modelopt.Why = .{}; + try std.testing.expectError(error.UnsupportedQuant, @import("cuda_formats.zig").admit(gpa, mixed, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "both NVFP4 and NVFP4_NZ5") != null); +} + test "plan sizes as the Python family's" { try std.testing.expectEqual(@as(usize, 1 + 0), maxItems(1, 257, tile)); try std.testing.expectEqual(@as(usize, 9 + 2), maxItems(45, 9, tile)); // 9 experts used, 45 pairs: two more items of 16 diff --git a/zig/src/families/glm/cuda_formats.zig b/zig/src/families/glm/cuda_formats.zig index 377dae1e1d9..8dd0bbaf5cd 100644 --- a/zig/src/families/glm/cuda_formats.zig +++ b/zig/src/families/glm/cuda_formats.zig @@ -42,7 +42,7 @@ pub fn of(declared: Declared, stored: Stored) Refusal!Format { .mixed => |r| if (r) |recipe| switch (recipe) { .nvfp4, .w4a16_nvfp4 => f == .nvfp4, .nvfp4_csf => f == .nvfp4_csf, - .nvfp4_csf0 => f == .nvfp4_csf0, + .nvfp4_csf0, .nvfp4_nz5 => f == .nvfp4_csf0, .mxfp8 => f == .mxfp8, .fp8_pb_wo => f == .fp8_pb, // per-tensor FP8 with a static input scale (#1145's Qwen recipe): GLM's lanes read no such projection @@ -301,7 +301,11 @@ pub fn describe(buf: []u8, module: []const u8, declared: Declared, stored: Store /// The entry's check (modelopt.admitRecipes), its table dropped: weights.load reads it again beside the tensors. pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *core.modelopt.Why) !void { var recipes = try core.modelopt.admitRecipes(gpa, config_json, why); - recipes.deinit(); + defer recipes.deinit(); + if (recipes.has(.nvfp4_csf0) and recipes.has(.nvfp4_nz5)) { + why.set("ModelOpt MIXED_PRECISION: csf0_v1 modules as both NVFP4 and NVFP4_NZ5, whose codes an engine reads one way", .{}); + return error.UnsupportedQuant; + } } /// A routed expert's NVFP4 linear as read: plain scales, csf_32x2_v1's to decode, csf0_v1's; else refused by name. diff --git a/zig/src/families/glm/cuda_forward.zig b/zig/src/families/glm/cuda_forward.zig index e18dc98be0c..28c4e471686 100644 --- a/zig/src/families/glm/cuda_forward.zig +++ b/zig/src/families/glm/cuda_forward.zig @@ -54,8 +54,8 @@ pub const Modules = struct { quant: quant.Kernels, q4: q4.Kernels, - /// `block32`: a csf0_v1 checkpoint's block 32 experts' image too (experts.wantsBlock32). - pub fn load(d: *const cuda.Driver, ctx: *const cuda.Context, block32: bool) !Modules { + /// `block32`: a csf0_v1 checkpoint's block 32 experts' image too, for its codes' values (experts.wantsBlock32). + pub fn load(d: *const cuda.Driver, ctx: *const cuda.Context, block32: ?cuda.experts32.Values) !Modules { const k = cuda.kernels; var m: Modules = undefined; var n: usize = 0; diff --git a/zig/tests/cuda/contract_nvfp4_fact.zig b/zig/tests/cuda/contract_nvfp4_fact.zig index 741751dbea2..53692630243 100644 --- a/zig/tests/cuda/contract_nvfp4_fact.zig +++ b/zig/tests/cuda/contract_nvfp4_fact.zig @@ -11,8 +11,8 @@ const fx = cuda.experts.Nvfp4Experts; const Y = cuda.experts32.Nvfp4b32Experts; const grouped = cuda.grouped; -/// Fact up/down, a control, experts_waves' entries, 1-warp CTAs, two cut controls, block 32's five and its control. -pub const Kind = enum { up, down, control, up_waves, down_waves, up_half, up_one, down_one, down_bf16_one, relu2_one, up_waves_one, down_waves_one, up_half_one, cut_waves, cut_waves_one, b32_up, b32_down, b32_down_bf16, b32_prompt_up, b32_prompt_down, b32_control }; +/// Fact up/down, a control, waves' entries, 1-warp CTAs, two cut controls, block 32's and NVFP4_NZ5's five, controls. +pub const Kind = enum { up, down, control, up_waves, down_waves, up_half, up_one, down_one, down_bf16_one, relu2_one, up_waves_one, down_waves_one, up_half_one, cut_waves, cut_waves_one, b32_up, b32_down, b32_down_bf16, b32_prompt_up, b32_prompt_down, b32_control, nz5_up, nz5_down, nz5_down_bf16, nz5_prompt_up, nz5_prompt_down, nz5_control }; /// experts_waves.zig's entry a kind launches, or null for the prompt-tile and classic kinds. fn wavesEntry(kind: Kind) ?usize { @@ -26,7 +26,7 @@ fn wavesEntry(kind: Kind) ?usize { fn isDown(kind: Kind) bool { return switch (kind) { - .down, .down_waves, .down_one, .down_bf16_one, .down_waves_one, .cut_waves_one, .b32_down, .b32_down_bf16, .b32_prompt_down => true, + .down, .down_waves, .down_one, .down_bf16_one, .down_waves_one, .cut_waves_one, .b32_down, .b32_down_bf16, .b32_prompt_down, .nz5_down, .nz5_down_bf16, .nz5_prompt_down => true, else => false, }; } @@ -41,7 +41,7 @@ fn isOne(kind: Kind) bool { fn epiOf(kind: Kind) cuda.experts.Epi { return switch (kind) { - .down_bf16_one, .b32_down_bf16, .b32_prompt_down => .down_bf16, + .down_bf16_one, .b32_down_bf16, .b32_prompt_down, .nz5_down_bf16, .nz5_prompt_down => .down_bf16, else => if (isDown(kind)) .down_f32 else .up, }; } @@ -50,13 +50,22 @@ fn epiOf(kind: Kind) cuda.experts.Epi { fn isB32(kind: Kind) bool { return switch (kind) { .b32_up, .b32_down, .b32_down_bf16, .b32_prompt_up, .b32_prompt_down, .b32_control => true, + .nz5_up, .nz5_down, .nz5_down_bf16, .nz5_prompt_up, .nz5_prompt_down, .nz5_control => true, else => false, }; } /// Block 32's prompt entries, whose block 16 is the prompt tile and not the decode form. fn isB32Prompt(kind: Kind) bool { - return kind == .b32_prompt_up or kind == .b32_prompt_down; + return kind == .b32_prompt_up or kind == .b32_prompt_down or kind == .nz5_prompt_up or kind == .nz5_prompt_down; +} + +/// NVFP4_NZ5's kinds: block 32's entries that read 0b1000 as +5, against block 16 on the same values. +fn isNz5(kind: Kind) bool { + return switch (kind) { + .nz5_up, .nz5_down, .nz5_down_bf16, .nz5_prompt_up, .nz5_prompt_down, .nz5_control => true, + else => false, + }; } const experts = 4; @@ -130,6 +139,12 @@ pub fn spec(kind: Kind) c.Spec { .b32_prompt_up => .{ .name = "cuda nvfp4 block 32 prompt gate-up tf_nvfp4_prompt32_swiglu", .accum = .f32, .depth = depth, .ops = 1, .mids = 3, .out = .bf16, .replaces = "tf_nvfp4_prompt_swiglu", .nan = .{ .stated = rule }, .tiles = up32_tiles, .served = &b32_up_served, .sums = .{ .bf16 = 30, .why = why } }, .b32_prompt_down => .{ .name = "cuda nvfp4 block 32 prompt down tf_nvfp4_prompt32_down", .accum = .f32, .depth = depth, .ops = 1, .out = .bf16, .replaces = "tf_nvfp4_prompt_down", .nan = .{ .stated = rule }, .tiles = down32_tiles, .served = &b32_down_served, .sums = .{ .bf16 = 30, .why = why } }, .b32_control => .{ .name = "control: tf_nvfp4_decode32_swiglu on offsets with each byte's nibbles swapped, posing as the decode gate-up", .accum = .f32, .depth = depth, .ops = 1, .mids = 3, .out = .bf16, .replaces = "nvfp4_expert_kernel<2, 2, 4>", .nan = .{ .stated = rule }, .tiles = unit32, .served = b32_up_served[1..2] }, + .nz5_up => .{ .name = "cuda nvfp4 block 32 NVFP4_NZ5 decode gate-up tf_nvfp4_nz5_decode32_swiglu", .accum = .f32, .depth = depth, .ops = 1, .mids = 3, .out = .bf16, .replaces = "nvfp4_expert_kernel<2, 2, 4>", .nan = .{ .stated = rule }, .tiles = unit32, .served = &b32_up_served, .sums = .{ .bf16 = 30, .why = why } }, + .nz5_down => .{ .name = "cuda nvfp4 block 32 NVFP4_NZ5 decode down tf_nvfp4_nz5_decode32_down_f32", .accum = .f32, .depth = depth, .ops = 1, .out = .f32, .replaces = "nvfp4_expert_kernel<1, 0, 4>", .nan = .{ .stated = rule }, .tiles = unit32, .served = &b32_down_served }, + .nz5_down_bf16 => .{ .name = "cuda nvfp4 block 32 NVFP4_NZ5 decode down bf16 tf_nvfp4_nz5_decode32_down_bf16", .accum = .f32, .depth = depth, .ops = 1, .out = .bf16, .replaces = "nvfp4_expert_kernel<1, 3, 4>", .nan = .{ .stated = rule }, .tiles = unit32, .served = &b32_down_served, .sums = .{ .bf16 = 30, .why = why } }, + .nz5_prompt_up => .{ .name = "cuda nvfp4 block 32 NVFP4_NZ5 prompt gate-up tf_nvfp4_nz5_prompt32_swiglu", .accum = .f32, .depth = depth, .ops = 1, .mids = 3, .out = .bf16, .replaces = "tf_nvfp4_prompt_swiglu", .nan = .{ .stated = rule }, .tiles = up32_tiles, .served = &b32_up_served, .sums = .{ .bf16 = 30, .why = why } }, + .nz5_prompt_down => .{ .name = "cuda nvfp4 block 32 NVFP4_NZ5 prompt down tf_nvfp4_nz5_prompt32_down", .accum = .f32, .depth = depth, .ops = 1, .out = .bf16, .replaces = "tf_nvfp4_prompt_down", .nan = .{ .stated = rule }, .tiles = down32_tiles, .served = &b32_down_served, .sums = .{ .bf16 = 30, .why = why } }, + .nz5_control => .{ .name = "control: tf_nvfp4_decode32_swiglu on NVFP4_NZ5's codes, each +5 read as -0, posing as its nz5 entry", .accum = .f32, .depth = depth, .ops = 1, .mids = 3, .out = .bf16, .replaces = "nvfp4_expert_kernel<2, 2, 4>", .nan = .{ .stated = rule }, .tiles = unit32, .served = b32_up_served[1..2] }, }; } @@ -140,6 +155,7 @@ pub const Experts = struct { k1: *const fx, // Group's one tile: ?*const cuda.experts_tile.Tile = null, k32: ?*const Y = null, // block 32's kernels, under test in its kinds + k32nz: ?*const Y = null, // NVFP4_NZ5's entries, under test in its kinds router: grouped.Router, shape: c.Shape = undefined, x: []u16 = &.{}, // bf16 rows: a token's for up, a pair's for down @@ -147,6 +163,7 @@ pub const Experts = struct { scales: []u8 = &.{}, // [experts][parts][n][k/16] e4m3 bases: []u8 = &.{}, // block 32's: [experts][parts][n] e4m3 offsets: []u8 = &.{}, // block 32's: [experts][parts][n][k/64], a group a nibble + nz: []u8 = &.{}, // NVFP4_NZ5's codes: block 16's with each planted 4 a 0b1000 globals: [experts * 2]f32 = undefined, // [experts][parts] picks: []i32 = &.{}, allow_extra: []f64 = &.{}, // up: the SwiGLU roundings' share of each output's bound @@ -173,6 +190,7 @@ pub const Experts = struct { a.free(self.scales); a.free(self.bases); a.free(self.offsets); + a.free(self.nz); a.free(self.picks); a.free(self.allow_extra); self.x = &.{}; @@ -180,6 +198,7 @@ pub const Experts = struct { self.scales = &.{}; self.bases = &.{}; self.offsets = &.{}; + self.nz = &.{}; self.picks = &.{}; self.allow_extra = &.{}; } @@ -205,7 +224,7 @@ pub const Experts = struct { entry.served = &self.served; }; return .{ .spec = entry, .ctx = self, .vt = &vt, .control = switch (self.kind) { - .control, .cut_waves, .cut_waves_one, .b32_control => .shapes, + .control, .cut_waves, .cut_waves_one, .b32_control, .nz5_control => .shapes, else => null, } }; } @@ -279,6 +298,7 @@ pub const Experts = struct { .stress => self.stress(rng), } if (isB32(self.kind)) try self.jam(); + if (isNz5(self.kind)) try self.plant(rng, fill == .random); self.xd = try self.rig.input(std.mem.sliceAsBytes(self.x)); // pack on the host as the loader does: [E][n/32][k/32][parts][144] int32 const per = fx.bytes(1, n, k, self.parts()) / 4; @@ -340,7 +360,34 @@ pub const Experts = struct { const n = self.shape.n; const g64 = self.shape.k / 64; const at = (e * self.parts() + part) * n; - return .{ .codes = self.codesOf(e, part), .bases = self.bases[at..][0..n], .offsets = self.offsets[at * g64 ..][0 .. n * g64] }; + const per = n * self.shape.k / 2; + const codes = if (isNz5(self.kind)) self.nz[(e * self.parts() + part) * per ..][0..per] else self.codesOf(e, part); + return .{ .codes = codes, .bases = self.bases[at..][0..n], .offsets = self.offsets[at * g64 ..][0 .. n * g64] }; + } + + /// NVFP4_NZ5's codes (`nz`): no 0b1000 anywhere; planted groups hold +5s alone, block 16's 4s at a scale x1.25. + fn plant(self: *Experts, rng: std.Random, planted: bool) !void { + const k = self.shape.k; + const g16 = k / 16; + for (self.codes) |*b| { + if (b.* & 0x0f == 8) b.* &= 0xf0; + if (b.* >> 4 == 8) b.* &= 0x0f; + } + self.nz = try self.rig.gpu.gpa.dupe(u8, self.codes); + if (!planted) return; + for (0..experts * self.parts() * self.shape.n) |r| for (0..k / 32) |blk| { + const s = self.scales[r * g16 + 2 * blk]; + if (s & 7 != 0 or s + 2 > 0x7e or rng.uintLessThan(u8, 4) != 0) continue; // a quarter of the powers of two + const at = r * k / 2 + blk * 16; + @memset(self.codes[at..][0..16], 0); + @memset(self.nz[at..][0..16], 0); + for (0..1 + rng.uintLessThan(usize, 3)) |_| { + const i = rng.uintLessThan(usize, 32); + put(self.codes[at..], i, 6); // e2m1's 4 + put(self.nz[at..], i, 8); + } + @memset(self.scales[r * g16 + 2 * blk ..][0..2], s + 2); + }; } /// Gate 4: bf16-integer inputs, codes 4 and 6 at scale 1, K's halves mirrored: fp32 sums exact in any order. @@ -422,10 +469,11 @@ pub const Experts = struct { const plan = if (prompt) self.wide else self.plan; const items = grouped.maxItems(self.pairs(), experts, if (prompt) cuda.experts.promptTile(.nvfp4) else 16); if (under) { + const k32 = if (isNz5(self.kind) and self.kind != .nz5_control) self.k32nz.? else self.k32.?; l.format = .nvfp4_csf0; l.up = self.wd32; l.down = self.wd32; - if (prompt) try self.k32.?.runPrompt(self.rig.s, epi, in, l, plan, out, items, -1) else try self.k32.?.run(self.rig.s, epi, in, l, plan, out, items, -1); + if (prompt) try k32.runPrompt(self.rig.s, epi, in, l, plan, out, items, -1) else try k32.run(self.rig.s, epi, in, l, plan, out, items, -1); } else if (prompt) try self.k.runPrompt(self.rig.s, epi, in, l, plan, out, items, -1) else try self.k.run(self.rig.s, epi, in, l, plan, out, items, -1); } diff --git a/zig/tests/cuda/contract_nvfp4_tile.zig b/zig/tests/cuda/contract_nvfp4_tile.zig index 12d5467f691..aea59f3be3d 100644 --- a/zig/tests/cuda/contract_nvfp4_tile.zig +++ b/zig/tests/cuda/contract_nvfp4_tile.zig @@ -1,4 +1,4 @@ -//! K64 baseline, K32 candidates, decode waves, 1-warp CTAs and block 32: byte replacements, FP64 references, controls. +//! K64 baseline, K32 candidates, decode waves, 1-warp CTAs, block 32 and NVFP4_NZ5: byte replacements, FP64, controls. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -10,6 +10,7 @@ pub const Group = struct { one: cuda.experts.Nvfp4Experts, // at 1 warp a CTA (TF_NVFP4_DECODE_WARPS=1), under test tile: cuda.experts_tile.Tile, b32: cuda.experts32.Nvfp4b32Experts, + b32nz: cuda.experts32.Nvfp4b32Experts, // NVFP4_NZ5's entries entries: [kinds.len + 3]fact.Experts, // every kind, then the K32 tile's up, down and control const kinds = std.enums.values(fact.Kind); pub fn create(a: std.mem.Allocator, gpu: check.Gpu, stream: cuda.Stream, sms: usize, router: cuda.grouped.Router, kernels: *std.ArrayList(core.contract.gates.Kernel)) !*Group { @@ -22,15 +23,18 @@ pub const Group = struct { errdefer self.one.unload(); self.tile = try cuda.experts_tile.Tile.load(gpu.d, sms, .both); errdefer self.tile.unload(); - self.b32 = try cuda.experts32.Nvfp4b32Experts.load(gpu.d, sms); + self.b32 = try cuda.experts32.Nvfp4b32Experts.load(gpu.d, sms, .e2m1); errdefer self.b32.unload(); - for (&self.entries, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = stream }, .kind = if (i < kinds.len) kinds[i] else kinds[i - kinds.len], .k = &self.four, .k1 = &self.one, .k32 = &self.b32, .tile = if (i >= kinds.len) &self.tile else null, .router = router }; + self.b32nz = try cuda.experts32.Nvfp4b32Experts.load(gpu.d, sms, .nz5); + errdefer self.b32nz.unload(); + for (&self.entries, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = stream }, .kind = if (i < kinds.len) kinds[i] else kinds[i - kinds.len], .k = &self.four, .k1 = &self.one, .k32 = &self.b32, .k32nz = &self.b32nz, .tile = if (i >= kinds.len) &self.tile else null, .router = router }; errdefer for (&self.entries) |*x| x.deinit(); for (&self.entries) |*x| try kernels.append(a, try x.kernel()); return self; } pub fn destroy(self: *Group) void { for (&self.entries) |*x| x.deinit(); + self.b32nz.unload(); self.b32.unload(); self.tile.unload(); self.one.unload(); diff --git a/zig/tests/cuda/glm_exl3_tests.zig b/zig/tests/cuda/glm_exl3_tests.zig index c32af1b6b38..8db777a1e3c 100644 --- a/zig/tests/cuda/glm_exl3_tests.zig +++ b/zig/tests/cuda/glm_exl3_tests.zig @@ -235,7 +235,7 @@ pub fn run_(gpu: Gpu) !void { defer pm.unload(); var k = try glm.exl3.Kernels.load(gpu.d); defer k.unload(); - var ek = try glm.experts.Kernels.load(gpu.d, pm, @intCast(try gpu.ctx.attribute(.multiprocessor_count)), false); + var ek = try glm.experts.Kernels.load(gpu.d, pm, @intCast(try gpu.ctx.attribute(.multiprocessor_count)), null); defer ek.unload(); for ([_]bool{ true, false }) |one| { const s = try weights(&r, one); diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index deea592ffd5..57cfd83b804 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -104,6 +104,7 @@ const flashnext_nvfp4_tp_tests = @import("flashnext_nvfp4_tp_tests.zig"); const flashnext_fp8_experts_tests = @import("flashnext_fp8_experts_tests.zig"); const nvfp4_fact_tests = @import("nvfp4_fact_tests.zig"); const nvfp4_b32_tests = @import("nvfp4_b32_tests.zig"); +const nvfp4_nz5_tests = @import("nvfp4_nz5_tests.zig"); const lane_half_tests = @import("lane_half_tests.zig"); const flashnext_dense_hc_tests = @import("flashnext_dense_hc_tests.zig"); const flashnext_hc_tests = @import("flashnext_hc_tests.zig"); @@ -150,6 +151,7 @@ const usage = \\ moetile-bench alternate shared-down plus scatter and direct-slot GPU timings \\ nvfp4-fact NVFP4 experts' prompt tiles with the decode form's sums: its bytes at every row, FP64 \\ nvfp4-b32 block 32 experts with csf0 scales: block 16's bytes on equal scales, each form and width + \\ nvfp4-nz5 NVFP4_NZ5's block 32 experts: E2M1's bytes with each +5 a 4 under a scale 1.25x as large \\ lane-half lane half tiles (MXFP8, BF16): bytes equal to the 64-column tile, FP64, cold-weight time \\ flashnext-dense-hc dense connection weights and FP32 normalization against FP64 \\ flashnext-hc Flash Next's own hyper-connection and n-gram glue against float64 (synthetic rows) @@ -386,6 +388,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "moetile-bench")) return @import("moetile_tests.zig").bench(gpu); if (std.mem.eql(u8, cmd, "nvfp4-fact")) return nvfp4_fact_tests.run(gpu); if (std.mem.eql(u8, cmd, "nvfp4-b32")) return nvfp4_b32_tests.run(gpu); + if (std.mem.eql(u8, cmd, "nvfp4-nz5")) return nvfp4_nz5_tests.run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt")) return @import("qmmf_prompt_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt-contract")) return @import("contract_qmmf_prompt.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt-repro")) return @import("qmmf_prompt_tests.zig").repro(gpu); diff --git a/zig/tests/cuda/nvfp4_b32_tests.zig b/zig/tests/cuda/nvfp4_b32_tests.zig index a42a6aad5dc..c7c1261a85a 100644 --- a/zig/tests/cuda/nvfp4_b32_tests.zig +++ b/zig/tests/cuda/nvfp4_b32_tests.zig @@ -165,7 +165,7 @@ pub fn run(gpu: check.Gpu) !void { const sms: u32 = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); var x = try X.load(gpu.d, sms); defer x.unload(); - var y = try Y.load(gpu.d, sms); + var y = try Y.load(gpu.d, sms, .e2m1); defer y.unload(); const k: Kernels = .{ .x = &x, .y = &y, .router = try cuda.grouped.Router.resolve(mod) }; const bufs: Bufs = .{ diff --git a/zig/tests/cuda/nvfp4_nz5_tests.zig b/zig/tests/cuda/nvfp4_nz5_tests.zig new file mode 100644 index 00000000000..08993f49900 --- /dev/null +++ b/zig/tests/cuda/nvfp4_nz5_tests.zig @@ -0,0 +1,203 @@ +//! NVFP4_NZ5's block 32 experts against E2M1's: each +5 written as a 4 under a scale 1.25 times as large, equal bytes. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const rig = @import("flashnext_rig.zig"); +const Y = cuda.experts32.Nvfp4b32Experts; +const Matrix = cuda.experts32.Matrix; +const Layer = cuda.experts.Layer; +const d = 4096; +const widths = [_]usize{ 1024, 704, 640 }; // TP=2's rank and TP=3's two +const experts = 6; +const slots = 3; // two routed picks and the skipped shared slot +const rows_set = [_]usize{ 1, 7, 17, 22, 64, 65, 130 }; +const most = rows_set[rows_set.len - 1]; + +/// A launch's form: the decode or the prompt kernels, and the down's sums. +const Form = struct { prompt: bool, down: cuda.experts.Epi }; +const forms = [_]Form{ .{ .prompt = false, .down = .down_f32 }, .{ .prompt = false, .down = .down_bf16 }, .{ .prompt = true, .down = .down_bf16 } }; + +fn put(codes: []u8, i: usize, v: u8) void { + const b = &codes[i / 2]; + b.* = if (i % 2 == 0) (b.* & 0xf0) | v else (b.* & 0x0f) | v << 4; +} + +/// A matrix as NVFP4_NZ5 holds it (`nz`) and its values in E2M1 (`eq`): a planted group's +5 is a 4 at scale x1.25. +const Pair = struct { + nz: Matrix, + eq: Matrix, + + fn init(a: std.mem.Allocator, rng: std.Random, n: usize, k: usize) !Pair { + const codes = try a.alloc(u8, n * k / 2); + rng.bytes(codes); + for (codes) |*b| { // no 0b1000 outside a planted group: E2M1 reads it as -0 and NVFP4_NZ5 as +5 + if (b.* & 0x0f == 8) b.* &= 0xf0; + if (b.* >> 4 == 8) b.* &= 0x0f; + } + const bases = try a.alloc(u8, n); + for (bases) |*b| b.* = 0x20 + rng.uintLessThan(u8, 0x18); + const offsets = try a.alloc(u8, n * (k / 64)); + rng.bytes(offsets); + const eq_codes = try a.dupe(u8, codes); + const eq_offsets = try a.dupe(u8, offsets); + var planted: usize = 0; + for (0..n) |r| for (0..k / 32) |g| { + const byte = r * (k / 64) + g / 2; + const shift: u3 = if (g & 1 == 0) 0 else 4; + const off = (offsets[byte] >> shift) & 15; + if ((bases[r] + off) & 7 != 0 or off > 13) continue; // a power of two, with room for two steps (x1.25) + const at = r * k / 2 + g * 16; + @memset(codes[at..][0..16], 0); + @memset(eq_codes[at..][0..16], 0); + for (0..1 + rng.uintLessThan(usize, 3)) |_| { + const i = rng.uintLessThan(usize, 32); + put(codes[at..], i, 8); + put(eq_codes[at..], i, 6); // e2m1's 4 + } + eq_offsets[byte] += @as(u8, 2) << shift; + planted += 1; + }; + if (planted == 0) return error.NothingPlanted; + return .{ .nz = .{ .codes = codes, .bases = bases, .offsets = offsets }, .eq = .{ .codes = eq_codes, .bases = bases, .offsets = eq_offsets } }; + } +}; + +/// One width's experts on the device, both ways. +const Layers = struct { + eq: Layer, + nz: Layer, + + fn init(r: *rig.Rig, a: std.mem.Allocator, rng: std.Random, width: usize) !Layers { + const up = Y.bytes(1, width, d, 2) / 4; + const down = Y.bytes(1, d, width, 1) / 4; + const w = [_][]u32{ try a.alloc(u32, experts * up), try a.alloc(u32, experts * down), try a.alloc(u32, experts * up), try a.alloc(u32, experts * down) }; + for (0..experts) |e| { + const g: Pair = try .init(a, rng, width, d); + const u: Pair = try .init(a, rng, width, d); + const dn: Pair = try .init(a, rng, d, width); + Y.packGateUp(w[0][e * up ..][0..up], g.eq, u.eq, width, d); + Y.packOne(w[1][e * down ..][0..down], dn.eq, d, width); + Y.packGateUp(w[2][e * up ..][0..up], g.nz, u.nz, width, d); + Y.packOne(w[3][e * down ..][0..down], dn.nz, d, width); + } + const dg = try r.dev(std.mem.sliceAsBytes(r.f32s((experts + 1) * 2, 0.01, 0.03))); + const common: Layer = .{ .format = .nvfp4_csf0, .up = 0, .down = 0, .up_scale = dg, .down_scale = dg, .width = width, .dims = d, .experts = experts, .limit = 10.0 }; + var l: Layers = .{ .eq = common, .nz = common }; + l.eq.up = try r.dev(std.mem.sliceAsBytes(w[0])); + l.eq.down = try r.dev(std.mem.sliceAsBytes(w[1])); + l.nz.up = try r.dev(std.mem.sliceAsBytes(w[2])); + l.nz.down = try r.dev(std.mem.sliceAsBytes(w[3])); + return l; + } +}; + +/// `x` and `xd`, the gate-up's and the down's inputs: bf16 integers (ints), so a planted group's sum is exact. +const Bufs = struct { act: [2]u64, out: [2]u64, plan: cuda.grouped.Plan, x: u64, xd: u64, picks: u64 }; + +/// bf16 integers in [-8, 8]: each group's sum is exact before its scale, so a +5 under s equals a 4 under 1.25 s. +fn ints(a: std.mem.Allocator, rng: std.Random, n: usize) ![]u16 { + const out = try a.alloc(u16, n); + for (out) |*v| { + const f: f32 = @floatFromInt(rng.intRangeAtMost(i32, -8, 8)); + v.* = @intCast(@as(u32, @bitCast(f)) >> 16); // an integer's bf16 is its f32's top half + } + return out; +} + +fn clear(gpu: check.Gpu, r: *rig.Rig, p: u64, bytes: usize) !void { + try gpu.d.check(gpu.d.api.cuMemsetD8Async(p, 0xff, bytes, r.s.handle), "cuMemsetD8Async"); +} + +/// One form's gate-up and down, `ka` on `la` into the first buffers and `kb` on `lb` into the second: their bytes. +fn launch(gpu: check.Gpu, r: *rig.Rig, router: cuda.grouped.Router, b: Bufs, ka: *const Y, la: Layer, kb: *const Y, lb: Layer, rows: usize, f: Form) ![4][]u8 { + const pairs = rows * slots; + const width = la.width; + const t: usize = if (f.prompt) 64 else 16; + const items = cuda.grouped.maxItems(pairs, experts + 1, t); + try router.route(r.s, b.picks, pairs, experts + 1, t, b.plan); + for (b.act) |p| try clear(gpu, r, p, pairs * width * 2); + for (b.out) |p| try clear(gpu, r, p, pairs * d * 4); + const gate: cuda.experts.Rows = .{ .x = b.x, .stride = d, .slots = slots }; + const dn: cuda.experts.Rows = .{ .x = b.xd, .stride = width }; + for ([2]*const Y{ ka, kb }, [2]Layer{ la, lb }, b.act) |k, l, act| { + if (f.prompt) try k.runPrompt(r.s, .up, gate, l, b.plan, act, items, experts) else try k.run(r.s, .up, gate, l, b.plan, act, items, experts); + } + for ([2]*const Y{ ka, kb }, [2]Layer{ la, lb }, b.out) |k, l, out| { + if (f.prompt) try k.runPrompt(r.s, f.down, dn, l, b.plan, out, items, experts) else try k.run(r.s, f.down, dn, l, b.plan, out, items, experts); + } + return .{ try r.back(u8, b.act[0], pairs * width * 2), try r.back(u8, b.act[1], pairs * width * 2), try r.back(u8, b.out[0], pairs * d * 4), try r.back(u8, b.out[1], pairs * d * 4) }; +} + +/// Each routed pair of `bytes` holds a written row (a launch's outputs start as all ones). +fn written(bytes: []const u8, row: usize, rows: usize) !void { + for (0..rows * slots) |i| { + if (i % slots == slots - 1) continue; // the shared slot, skipped + try check.expect(std.mem.indexOfNone(u8, bytes[i * row ..][0..row], &.{0xff}) != null, "nvfp4-nz5: pair {d} of {d} rows unwritten", .{ i, rows }); + } +} + +/// A form at a row count: every routed pair written, NVFP4_NZ5's bytes equal to E2M1's on the same values. +fn compare(gpu: check.Gpu, r: *rig.Rig, router: cuda.grouped.Router, b: Bufs, e2m1: *const Y, nz5: *const Y, l: Layers, rows: usize, f: Form) !void { + const o = try launch(gpu, r, router, b, e2m1, l.eq, nz5, l.nz, rows, f); + try written(o[1], l.nz.width * 2, rows); + try written(o[3], if (f.down == .down_bf16) d * 2 else d * 4, rows); + try check.sameBytes("nvfp4-nz5 gate-up", o[1], o[0]); + try check.sameBytes("nvfp4-nz5 down", o[3], o[2]); +} + +/// The control: E2M1's kernels on NVFP4_NZ5's bytes read each +5 as -0, and both outputs part from the nz5 kernels'. +fn control(gpu: check.Gpu, r: *rig.Rig, router: cuda.grouped.Router, b: Bufs, e2m1: *const Y, nz5: *const Y, l: Layers, f: Form) !void { + const o = try launch(gpu, r, router, b, e2m1, l.nz, nz5, l.nz, most, f); + try check.expect(!std.mem.eql(u8, o[0], o[1]), "control: E2M1's gate-up on NVFP4_NZ5's codes parts from the nz5 kernel's", .{}); + try check.expect(!std.mem.eql(u8, o[2], o[3]), "control: E2M1's down on NVFP4_NZ5's codes parts from the nz5 kernel's", .{}); +} + +pub fn run(gpu: check.Gpu) !void { + var arena = std.heap.ArenaAllocator.init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x25); + const rng = prng.random(); + var r = try rig.Rig.init(gpu, a, rng); + defer r.deinit(); + const dx = try r.dev(std.mem.sliceAsBytes(try ints(a, rng, most * d))); + const picks = try a.alloc(i32, most * slots); + for (0..most) |row| { + // expert 0 takes most pairs (several 64-pair items), the others a few each + picks[row * slots] = if (row % 3 == 0) @intCast(1 + row % (experts - 1)) else 0; + picks[row * slots + 1] = @intCast(1 + (row * 7) % (experts - 1)); + picks[row * slots + 2] = experts; // the shared expert, skipped + } + const pairs_most = most * slots; + const plan: cuda.grouped.Plan = .{ + .members = try r.out(pairs_most * 4), + .items = try r.out(cuda.grouped.maxItems(pairs_most, experts + 1, 16) * 12), + .counts = try r.out(8), + .rank = try r.out(pairs_most * 4), + .hist = try r.out(((pairs_most + 1023) / 1024) * (experts + 1) * 4), + }; + var mod = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer mod.unload(); + const sms: u32 = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + var e2m1 = try Y.load(gpu.d, sms, .e2m1); + defer e2m1.unload(); + var nz5 = try Y.load(gpu.d, sms, .nz5); + defer nz5.unload(); + const router = try cuda.grouped.Router.resolve(mod); + const bufs: Bufs = .{ + .act = .{ try r.out(pairs_most * widths[0] * 2), try r.out(pairs_most * widths[0] * 2) }, + .out = .{ try r.out(pairs_most * d * 4), try r.out(pairs_most * d * 4) }, + .plan = plan, + .x = dx, + .xd = try r.dev(std.mem.sliceAsBytes(try ints(a, rng, pairs_most * widths[0]))), + .picks = try r.dev(std.mem.sliceAsBytes(picks)), + }; + for (widths) |width| { + const l: Layers = try .init(&r, a, rng, width); + for (forms) |f| { + for (rows_set) |rows| try compare(gpu, &r, router, bufs, &e2m1, &nz5, l, rows, f); + try control(gpu, &r, router, bufs, &e2m1, &nz5, l, f); + } + } + r.report("nvfp4-nz5: gate-up, fp32 and bf16 down, decode and prompt, at 1,024, 704 and 640: E2M1's bytes, each control red"); +} From 1894013ac4756f3c0db49adee3860f7fbdbe1d94 Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:08:59 +0900 Subject: [PATCH 02/59] changelog: NVFP4_NZ5's line waits for landing 1.2.7 was released after this branch's base. On that base the line would merge into 1.2.7's section, so it goes under Unreleased when the change lands. --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8847d5adaec..4bcccc5867a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -345,8 +345,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Internal: core gains one walk for copying kept prompt states, and GLM's copies on CUDA and Metal go through it, with the same copies in the same order; other families keep their own loops. Nothing a user sees changes (#2215, part of #1293). Thanks to @jschmied. -- GLM-5.3-Flash on CUDA reads `NVFP4_NZ5` checkpoints: csf0_v1's layout with E2M1's second zero, code 0b1000, read as +5, in the same memory as csf0_v1; every other checkpoint loads and runs as before, with the same tokens. Thanks to @Bizuayeu. - - CUDA, opt-in build (`-Dnative-fp-decode`): qmmf's FP4 decode rows use the shared native e2m1 pair decode, `tf_common::e2m1_pairs`, which equals the existing decode on all 2^33 inputs; the default build's 113 fatbins are byte-identical and GB10 decode is level (#2721). Thanks to @jschmied. - Qwen3.8-27B on Metal: while a request runs, the keep-warm ticker now commits the residency sets' probe each interval, so the first command buffer after a wide prompt pass no longer waits in the kernel (likely for macOS to wire the model again; not traced). On an M5 Ultra with a 14 GiB prompt cache filling memory, five cold 24K- to 64K-token prompts in a row reach their first tokens 3.5% to 5.9% sooner in total; with the cache off, cold prompts are level. Replies are unchanged (#2725, fixes #2724). Thanks to @mrv777. From 3655cac69a04ec242e786e457c81a0ee3443378c Mon Sep 17 00:00:00 2001 From: Bizuayeu <30091157+Bizuayeu@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:15:01 +0900 Subject: [PATCH 03/59] cuda source check: declare __vcmpeq2, which fp4pair_nz5 calls test_real_exl3_layout parses exl3_layout.cpp, whose includes reach common/fp_pairs.cuh, against the fixed SDK declarations in tools/zig/cuda_host. fp4pair_nz5 there calls __vcmpeq2, which they did not declare, so pytest failed. Declare it with the signature in CUDA 13.0's crt/device_functions.h, unsigned int __vcmpeq2(unsigned int a, unsigned int b). Only check_cuda_sources.py reads these headers: no kernel, engine or test binary changes. --- tools/zig/cuda_host/cuda_runtime.h | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/zig/cuda_host/cuda_runtime.h b/tools/zig/cuda_host/cuda_runtime.h index 2a63e2b086e..f0f54966ece 100644 --- a/tools/zig/cuda_host/cuda_runtime.h +++ b/tools/zig/cuda_host/cuda_runtime.h @@ -44,6 +44,7 @@ __device__ unsigned __funnelshift_l(unsigned,unsigned,unsigned); __device__ unsigned __funnelshift_r(unsigned,unsigned,unsigned); __device__ unsigned __dp4a(unsigned,unsigned,unsigned); __device__ int __dp4a(int,int,int); __device__ unsigned __byte_perm(unsigned,unsigned,unsigned); __device__ unsigned __brev(unsigned); +__device__ unsigned __vcmpeq2(unsigned,unsigned); __device__ int __clz(unsigned); __device__ int __popc(unsigned); __device__ int __popcll(unsigned long long); __device__ int __ffs(int); __device__ int __ffsll(long long); __device__ unsigned __umulhi(unsigned,unsigned); __device__ size_t __cvta_generic_to_shared(const void*); From 864b41deb829efbda2a08b9248beaf222debecf0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:21:47 +0000 Subject: [PATCH 04/59] cuda tests: nvfp4-nz5, contract_exl3 and dory_serve imported at their dispatch lines, so main.zig stays within 600 lines on today's main --- zig/tests/cuda/main.zig | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 57cfd83b804..3bb7404558a 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -45,7 +45,6 @@ const modelopt_tests = @import("modelopt_tests.zig"); const exl3_tests = @import("exl3_tests.zig"); const exl3_tp2_tests = @import("exl3_tp2_tests.zig"); const exl3_plan_bench = @import("exl3_plan_bench.zig"); -const exl3_contract = @import("contract_exl3.zig"); const exl3_candidate_tests = @import("exl3_candidate_tests.zig"); const experts3_tests = @import("experts3_tests.zig"); const moe_tests = @import("moe_tests.zig"); @@ -104,7 +103,6 @@ const flashnext_nvfp4_tp_tests = @import("flashnext_nvfp4_tp_tests.zig"); const flashnext_fp8_experts_tests = @import("flashnext_fp8_experts_tests.zig"); const nvfp4_fact_tests = @import("nvfp4_fact_tests.zig"); const nvfp4_b32_tests = @import("nvfp4_b32_tests.zig"); -const nvfp4_nz5_tests = @import("nvfp4_nz5_tests.zig"); const lane_half_tests = @import("lane_half_tests.zig"); const flashnext_dense_hc_tests = @import("flashnext_dense_hc_tests.zig"); const flashnext_hc_tests = @import("flashnext_hc_tests.zig"); @@ -123,7 +121,6 @@ const fn_hc_back_tests = @import("fn_hc_back_tests.zig"); const fn_pocket_tests = @import("fn_pocket_tests.zig"); const kolibri_tests = @import("kolibri_tests.zig"); const dory_tests = @import("dory_tests.zig"); -const dory_serve = @import("dory_serve_tests.zig"); const kolibri_layer_tests = @import("kolibri_layer_tests.zig"); const aot_fallback_tests = @import("aot_fallback_tests.zig"); const qwen_draft_frames = @import("qwen_draft_frames.zig"); @@ -388,7 +385,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "moetile-bench")) return @import("moetile_tests.zig").bench(gpu); if (std.mem.eql(u8, cmd, "nvfp4-fact")) return nvfp4_fact_tests.run(gpu); if (std.mem.eql(u8, cmd, "nvfp4-b32")) return nvfp4_b32_tests.run(gpu); - if (std.mem.eql(u8, cmd, "nvfp4-nz5")) return nvfp4_nz5_tests.run(gpu); + if (std.mem.eql(u8, cmd, "nvfp4-nz5")) return @import("nvfp4_nz5_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt")) return @import("qmmf_prompt_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt-contract")) return @import("contract_qmmf_prompt.zig").run(gpu); if (std.mem.eql(u8, cmd, "qmmf-prompt-repro")) return @import("qmmf_prompt_tests.zig").repro(gpu); @@ -468,7 +465,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "exl3-shapes")) return exl3_plan_bench.profileShapes(gpu, if (rest.len > 0) rest[0] else null); if (std.mem.eql(u8, cmd, "exl3-midm")) return exl3_plan_bench.midm(gpu); if (std.mem.eql(u8, cmd, "exl3-plans")) return exl3_plan_bench.run(gpu, if (rest.len > 0) rest[0] else null); - if (std.mem.eql(u8, cmd, "exl3-contract")) return exl3_contract.run(gpu); + if (std.mem.eql(u8, cmd, "exl3-contract")) return @import("contract_exl3.zig").run(gpu); if (std.mem.eql(u8, cmd, "exl3-tp2")) return exl3_tp2_tests.run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else "none"); if (std.mem.eql(u8, cmd, "sample")) return sample_tests.draws(gpu); if (std.mem.eql(u8, cmd, "nemotron-draws")) return nemotron_draw_tests.run(gpu); @@ -566,7 +563,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { } if (std.mem.eql(u8, cmd, "glm-loader-gate")) return glm_loader_gate.run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "glm-fp8g-shares")) return glm_fp8g_shares.run(gpu); - if (std.mem.startsWith(u8, cmd, "dory-")) return dory_serve.run(gpu, cmd, rest); + if (std.mem.startsWith(u8, cmd, "dory-")) return @import("dory_serve_tests.zig").run(gpu, cmd, rest); if (std.mem.eql(u8, cmd, "gemma4-states")) return @import("gemma4_states_tests.zig").states(gpu, rest); if (std.mem.eql(u8, cmd, "spark25-pages")) return @import("spark25_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "gemma4-pages")) return @import("gemma4_pages_tests.zig").pages(gpu, rest); From eec15294b8c84a99cbf0d465627b8a5b9e4b3b41 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:14:13 +0000 Subject: [PATCH 05/59] changelog: #2894 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bcccc5867a..04af662aa1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). +- GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. + - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). - Server: an image URL's host lookup stops at 3 seconds (or the request's deadline, if sooner) even when the system resolver keeps retrying, at most 64 lookups run at once, and a refused connection falls through to the host's next checked address (#3127). From 63a8668fb8db44864c068d771da28aae12b771e1 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:54:17 +0000 Subject: [PATCH 06/59] nemotron metal: prefill runs a chunk a call, so a new prompt no longer stalls other streams' rounds (#3021) The Metal backend now declares prefill_step and cancel_prefill beside reports_fill. The prompt pass moves out of backend.zig into prefill_metal.zig (the device side, unchanged) and prefill_steps.zig (whole pass and step, generic, with recording-fake tests). Both run the same chunk at prompt_flight's cuts, so replies are unchanged; each step lands the queue and reloads its own prompt ids before encoding, since the prompt buffer is shared. --- zig/build/prefill_widths_metal.zig | 6 + zig/src/families/nemotron/backend.zig | 99 +------ zig/src/families/nemotron/prefill_metal.zig | 149 ++++++++++ zig/src/families/nemotron/prefill_steps.zig | 67 +++++ .../families/nemotron/prefill_steps_test.zig | 266 ++++++++++++++++++ zig/src/metal_prefill_widths_compile.zig | 3 + 6 files changed, 496 insertions(+), 94 deletions(-) create mode 100644 zig/src/families/nemotron/prefill_metal.zig create mode 100644 zig/src/families/nemotron/prefill_steps.zig create mode 100644 zig/src/families/nemotron/prefill_steps_test.zig diff --git a/zig/build/prefill_widths_metal.zig b/zig/build/prefill_widths_metal.zig index bbba897dfcb..d577611bfb3 100644 --- a/zig/build/prefill_widths_metal.zig +++ b/zig/build/prefill_widths_metal.zig @@ -8,6 +8,12 @@ pub fn tests(b: *std.Build, parent: *std.Build.Step) void { run.has_side_effects = true; b.step("test-nemotron-prefill-widths-host", "Actual Nemotron cut and flight completion with recording buffers").dependOn(&run.step); parent.dependOn(&run.step); + // the same cuts a chunk a call (#3021): one chunk a step, a decode between chunks, the head's rows, a cancel + const steps_root = b.createModule(.{ .root_source_file = b.path("zig/src/families/nemotron/prefill_steps.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + const steps_run = b.addRunArtifact(b.addTest(.{ .root_module = steps_root, .filters = &.{"Nemotron Metal steps:"} })); + steps_run.has_side_effects = true; + b.step("test-nemotron-metal-steps-host", "Nemotron Metal's stepped prompt pass on recording fakes, no GPU").dependOn(&steps_run.step); + parent.dependOn(&steps_run.step); } pub fn compileHost(b: *std.Build, engine: *std.Build.Module, lanes: *std.Build.Module) void { diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 9cb12c4cf6d..013dcc74d3d 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -17,6 +17,7 @@ const head_tree = @import("head_tree.zig"); const prefill = @import("prefill.zig"); const head_block = @import("head_block.zig"); const snapshot = @import("snapshot.zig"); +const prefill_metal = @import("prefill_metal.zig"); const Model = @import("model.zig").Model; const nemotron_config = @import("config.zig"); const grammar = @import("grammar.zig"); @@ -60,6 +61,7 @@ pub const Metal = struct { wide: ?prefill.Prefill = null, // prompt chunks over fused_rows head: ?mtp.Head = null, caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + steps: @import("prefill_steps.zig").Steps = .{}, // prompt passes a chunk a call (prefill_step), by stream tokens: mtl.Buffer, // u32 [ring]: drawn tokens and host-fed ones prompt: mtl.Buffer, // u32 [capacity] fence: Fence, @@ -119,6 +121,7 @@ pub const Metal = struct { self.gpa.destroy(c.*); } self.caches.deinit(self.gpa); + self.steps.at.deinit(self.gpa); kv_pages.detach(self); if (self.head) |*h| h.deinit(); if (self.masks) |*m| m.deinit(); @@ -133,7 +136,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = grammar.firstMasked, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefill_metal.prefill, .prefill_step = prefill_metal.prefillStep, .cancel_prefill = prefill_metal.cancelPrefill, .first = firstFn, .first_masked = grammar.firstMasked, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true } }; } /// The round loop's setup facts, including this engine's measured head-step depth cap. @@ -231,99 +234,6 @@ pub const Metal = struct { // -- the vtable --------------------------------------------------------------------------------------------- - fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { - const self: *Metal = @ptrCast(@alignCast(ptr)); - const ids = s.prompt(); - try limits.check(ids.len, s.max_new, self.o.capacity); - if (s.isCancelled()) return error.Cancelled; - const rows_needed = @min(self.o.capacity, ids.len + s.max_new + max_lanes + 1); // the reply and a widest window past it - try self.drain(); - if (self.caches.get(s)) |old| { - old.deinit(&self.pool); - self.gpa.destroy(old); - _ = self.caches.remove(s); - } - const c = try @import("residency.zig").openCache(self, s, rows_needed); - @memcpy(self.prompt.slice(u32, ids.len), ids); - const Chunks = struct { - n: usize, - c: *st.Cache, - at: usize, - rows: usize, - fn encode(j: @This(), b: *Metal, e: *fwd.Enc) !void { - const d = b.m.config.hidden * 2; - const rows = j.rows; - const fresh = try b.pool.take(); - var out = b.scratch.x; // the chunk's final-normed rows - if (rows <= fused_rows) { - const segs = [_]fwd.Seg{.{ .rows = rows, .cache = j.c, .store = .full, .slot = @intCast(fresh) }}; - b.forward().body(e, &segs, b.prompt, j.at * 4); - } else { - const w = &b.wide.?; - w.chunk(e, b.forward(), j.c, b.prompt, j.at * 4, rows, fresh); - out = w.s.x; - } - j.c.advance(&b.pool, rows, fresh); - // the head's cache takes each row whose next token the prompt holds, as many rows a call as a window - const absorbed = @min(j.at + rows, j.n - 1) - j.at; - if (b.head) |*h| { - var r: usize = 0; - while (r < absorbed) : (r += max_window) h.absorb(e, j.c, @min(max_window, absorbed - r), out, r * d, b.prompt, (j.at + 1 + r) * 4); - } - j.c.start = 0; - j.c.rows = rows; - if (rows > fused_rows) { - // the last row where the first draw and the head read it - e.pipe(b.m.kernels.get("tf_copy_rows")); - e.buf(out, (rows - 1) * d, 0); - e.buf(b.scratch.x, 0, 1); - e.run(.{ d / 2, 1, 1 }, .{ 256, 1, 1 }); - j.c.rows = 1; - } - } - }; - s.cached = 0; - var at: usize = 0; - if (s.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there - const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); - if (snap.at < ids.len) if (snapshot.restore(self, c, snap)) |_| { - at = snap.at; - } else |_| {}; - s.cached = @intCast(at); - s.reuse_failed = at == 0; - } - s.fill_at.store(@intCast(at), .monotonic); // a restored prefix is done the moment it is restored - // a command buffer a chunk, each committed before the one ahead is waited on, so the GPU keeps a chunk queued - var k: usize = 0; - while (at < ids.len) { - const decision: ?usize = if (c.decide == lesson_route.none) null else @intCast(c.decide); - const rows = @import("prompt_flight.zig").rows(s, at, self.o.chunk, decision, &k); - if (s.isCancelled()) return error.Cancelled; // release() waits for the chunk still in flight - try kv_pages.grow(c, at + rows); - try @import("prompt_flight.zig").submit(self, s, Chunks{ .n = ids.len, .c = c, .at = at, .rows = rows }); - at += rows; - // landed tokens only: the newest chunk is still queued on the GPU - s.fill_at.store(@intCast(at - rows), .monotonic); - if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) hk.at(hk.ptr, s, @intCast(at)); - } - if (self.trace and c.decide != lesson_route.none) try self.traceLessons(c); - } - - /// Dev trace (TF_SLIDE_TRACE): the stream's router scores at its decision row and the lessons acting on its reply. - fn traceLessons(self: *Metal, c: *const st.Cache) !void { - const ad = layers.firstAdapter(&self.m.weights) orelse return; - try self.drain(); - const n = lesson_route.max_blocks; - const at: usize = @intCast(@max(c.rid, 0)); - const score = ad.score.slice(f32, lesson_route.max_slots * n)[at * n ..][0..n]; - const flags = ad.latch.slice(u32, lesson_route.max_slots * n)[at * n ..][0..n]; - const need = ad.need.slice(f32, n); - var line: [2048]u8 = undefined; - var w: std.Io.Writer = .fixed(&line); - for (0..ad.rank / 16) |b| w.print(" {d:.2}/{d:.2}{s}", .{ score[b], need[b], if (flags[b] != 0) "*" else "" }) catch break; - std.log.info("slide trace: decision row {d}: scores{s} (* acting)", .{ c.decide, w.buffered() }); - } - fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { const self: *Metal = @ptrCast(@alignCast(ptr)); return self.firstAt(s, position, null); @@ -581,6 +491,7 @@ pub const Metal = struct { self.drain() catch { @import("prompt_flight.zig").forget(self, s); }; + _ = self.steps.at.remove(s); // a stream that left mid-pass if (self.caches.fetchRemove(s)) |kv| { kv.value.deinit(&self.pool); self.gpa.destroy(kv.value); diff --git a/zig/src/families/nemotron/prefill_metal.zig b/zig/src/families/nemotron/prefill_metal.zig new file mode 100644 index 00000000000..93a8f8d59f7 --- /dev/null +++ b/zig/src/families/nemotron/prefill_metal.zig @@ -0,0 +1,149 @@ +//! Nemotron Metal's prompt pass on the device (prefill_steps.zig drives it): the cache, the prompt buffer, each chunk. +const std = @import("std"); +const lanes = @import("lanes"); +const backend = @import("backend.zig"); +const fwd = @import("forward.zig"); +const st = @import("state.zig"); +const kv_pages = @import("kv_pages.zig"); +const lesson_route = @import("living").lesson_route; +const layers = @import("layers.zig"); +const snapshot = @import("snapshot.zig"); +const pass = @import("prefill_steps.zig"); +const Metal = backend.Metal; + +/// One chunk's encode, as it was in backend.zig's prefill: the forward, the head's absorb, the last row kept. +const Chunks = struct { + n: usize, + c: *st.Cache, + at: usize, + rows: usize, + pub fn encode(j: @This(), b: *Metal, e: *fwd.Enc) !void { + const d = b.m.config.hidden * 2; + const rows = j.rows; + const fresh = try b.pool.take(); + var out = b.scratch.x; // the chunk's final-normed rows + if (rows <= backend.fused_rows) { + const segs = [_]fwd.Seg{.{ .rows = rows, .cache = j.c, .store = .full, .slot = @intCast(fresh) }}; + b.forward().body(e, &segs, b.prompt, j.at * 4); + } else { + const w = &b.wide.?; + w.chunk(e, b.forward(), j.c, b.prompt, j.at * 4, rows, fresh); + out = w.s.x; + } + j.c.advance(&b.pool, rows, fresh); + // the head's cache takes each row whose next token the prompt holds, as many rows a call as a window + const absorbed = pass.absorbed(j.at, rows, j.n); + if (b.head) |*h| { + var r: usize = 0; + while (r < absorbed) : (r += backend.max_window) h.absorb(e, j.c, @min(backend.max_window, absorbed - r), out, r * d, b.prompt, (j.at + 1 + r) * 4); + } + j.c.start = 0; + j.c.rows = rows; + if (rows > backend.fused_rows) { + // the last row where the first draw and the head read it + e.pipe(b.m.kernels.get("tf_copy_rows")); + e.buf(out, (rows - 1) * d, 0); + e.buf(b.scratch.x, 0, 1); + e.run(.{ d / 2, 1, 1 }, .{ 256, 1, 1 }); + j.c.rows = 1; + } + } +}; + +/// The device side of a pass for prefill_steps.zig: a stream's cache, the shared prompt buffer, each chunk's encode. +const Ops = struct { + m: *Metal, + + pub fn steps(o: Ops) *pass.Steps { + return &o.m.steps; + } + pub fn cap(o: Ops) usize { + return o.m.o.chunk; + } + fn cache(o: Ops, s: *lanes.Stream) *st.Cache { + return o.m.caches.get(s).?; + } + pub fn decision(o: Ops, s: *lanes.Stream) ?usize { + const c = o.cache(s); + return if (c.decide == lesson_route.none) null else @intCast(c.decide); + } + pub fn grow(o: Ops, s: *lanes.Stream, rows: usize) !void { + try kv_pages.grow(o.cache(s), rows); + } + pub fn body(o: Ops, s: *lanes.Stream, at: usize, rows: usize) Chunks { + return .{ .n = s.prompt_len, .c = o.cache(s), .at = at, .rows = rows }; + } + /// This prompt's ids into the prompt buffer the chunks read (the queue landed first). + pub fn load(o: Ops, s: *lanes.Stream) void { + const ids = s.prompt(); + @memcpy(o.m.prompt.slice(u32, ids.len), ids); + } + + /// The stream's cache opened, its ids loaded and a kept state restored: the row its pass starts from. + pub fn open(o: Ops, s: *lanes.Stream) !usize { + const self = o.m; + const ids = s.prompt(); + try backend.limits.check(ids.len, s.max_new, self.o.capacity); + if (s.isCancelled()) return error.Cancelled; + const rows_needed = @min(self.o.capacity, ids.len + s.max_new + backend.max_lanes + 1); // the reply and a widest window past it + try self.drain(); + if (self.caches.get(s)) |old| { + old.deinit(&self.pool); + self.gpa.destroy(old); + _ = self.caches.remove(s); + } + const c = try @import("residency.zig").openCache(self, s, rows_needed); + @memcpy(self.prompt.slice(u32, ids.len), ids); + s.cached = 0; + var at: usize = 0; + if (s.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) if (snapshot.restore(self, c, snap)) |_| { + at = snap.at; + } else |_| {}; + s.cached = @intCast(at); + s.reuse_failed = at == 0; + } + s.fill_at.store(@intCast(at), .monotonic); // a restored prefix is done the moment it is restored + return at; + } + + pub fn finish(o: Ops, s: *lanes.Stream) !void { + const c = o.cache(s); + if (o.m.trace and c.decide != lesson_route.none) try traceLessons(o.m, c); + } +}; + +fn of(ptr: *anyopaque) *Metal { + return @ptrCast(@alignCast(ptr)); +} + +/// The vtable's `prefill`: the whole pass, a command buffer a chunk, each committed before the one ahead is waited on. +pub fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + return pass.whole(of(ptr), Ops{ .m = of(ptr) }, s); +} + +/// The vtable's `prefill_step`: one chunk a call at the same cuts (no chunk_invariant: `max_rows` is never set). +pub fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + return pass.step(of(ptr), Ops{ .m = of(ptr) }, s); +} + +/// The vtable's `cancel_prefill`: no prompt work runs; the state at the last submitted chunk is kept once it lands. +pub fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + return pass.cancel(of(ptr), Ops{ .m = of(ptr) }, s); +} + +/// Dev trace (TF_SLIDE_TRACE): the stream's router scores at its decision row and the lessons acting on its reply. +fn traceLessons(self: *Metal, c: *const st.Cache) !void { + const ad = layers.firstAdapter(&self.m.weights) orelse return; + try self.drain(); + const n = lesson_route.max_blocks; + const at: usize = @intCast(@max(c.rid, 0)); + const score = ad.score.slice(f32, lesson_route.max_slots * n)[at * n ..][0..n]; + const flags = ad.latch.slice(u32, lesson_route.max_slots * n)[at * n ..][0..n]; + const need = ad.need.slice(f32, n); + var line: [2048]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + for (0..ad.rank / 16) |b| w.print(" {d:.2}/{d:.2}{s}", .{ score[b], need[b], if (flags[b] != 0) "*" else "" }) catch break; + std.log.info("slide trace: decision row {d}: scores{s} (* acting)", .{ c.decide, w.buffered() }); +} diff --git a/zig/src/families/nemotron/prefill_steps.zig b/zig/src/families/nemotron/prefill_steps.zig new file mode 100644 index 00000000000..ee20d85e932 --- /dev/null +++ b/zig/src/families/nemotron/prefill_steps.zig @@ -0,0 +1,67 @@ +//! Nemotron Metal's prompt pass, whole or a chunk a call (#3021): today's cuts, the MTP head's rows in each chunk. +const std = @import("std"); +const lanes = @import("lanes"); +const flight = @import("prompt_flight.zig"); +const Stream = lanes.Stream; + +/// Streams whose prompt passes run a chunk a call (prefill_step): each one's next prompt row. +pub const Steps = struct { at: std.AutoHashMapUnmanaged(*Stream, usize) = .empty }; + +/// Rows of a chunk from `at` whose next token the prompt holds (`n` tokens): the MTP head absorbs these. +pub fn absorbed(at: usize, rows: usize, n: usize) usize { + return @min(at + rows, n - 1) - at; +} + +/// One chunk from `at` at today's cut (`flight.rows`), submitted on `b`; the row after it. +pub fn chunk(b: anytype, ops: anytype, s: *Stream, at: usize, next: *usize) !usize { + const rows = flight.rows(s, at, ops.cap(), ops.decision(s), next); + if (s.isCancelled()) return error.Cancelled; // release() waits for the chunk still in flight + try ops.grow(s, at + rows); + try flight.submit(b, s, ops.body(s, at, rows)); + const end = at + rows; + s.fill_at.store(@intCast(at), .monotonic); // landed tokens only: the newest chunk is still queued on the GPU + if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); + return end; +} + +/// The whole pass (the vtable's `prefill`), as before: one chunk queued while the next is encoded. +pub fn whole(b: anytype, ops: anytype, s: *Stream) !void { + var at = try ops.open(s); + var next: usize = 0; + while (at < s.prompt_len) at = try chunk(b, ops, s, at, &next); + try ops.finish(s); +} + +/// One chunk a call (prefill_step) at the whole pass's cuts; true once the prompt's last chunk is submitted. +pub fn step(b: anytype, ops: anytype, s: *Stream) !bool { + const map = &ops.steps().at; + const got = try map.getOrPut(b.gpa, s); + if (!got.found_existing) got.value_ptr.* = ops.open(s) catch |e| { + _ = map.remove(s); + return e; + }; + errdefer _ = map.remove(s); + // the prompt buffer is every pass's: the chunks queued before this one land, then it holds this prompt + try b.drain(); + ops.load(s); + var next: usize = 0; + const end = try chunk(b, ops, s, map.get(s).?, &next); + if (end < s.prompt_len) { + map.getPtr(s).?.* = end; + return false; + } + _ = map.remove(s); + try ops.finish(s); + return true; +} + +/// The host cancels between chunks: once the queue lands, the state at the pass's last chunk end is kept. +pub fn cancel(b: anytype, ops: anytype, s: *Stream) !void { + const at = ops.steps().at.get(s) orelse return; + try b.drain(); + s.keepInterruptedPrefill(@intCast(at)); +} + +test { + _ = @import("prefill_steps_test.zig"); +} diff --git a/zig/src/families/nemotron/prefill_steps_test.zig b/zig/src/families/nemotron/prefill_steps_test.zig new file mode 100644 index 00000000000..f5d3438ebb7 --- /dev/null +++ b/zig/src/families/nemotron/prefill_steps_test.zig @@ -0,0 +1,266 @@ +//! Nemotron Metal's stepped prompt pass on recording fakes: today's cuts, a decode between chunks, the head's rows. +const std = @import("std"); +const lanes = @import("lanes"); +const pass = @import("prefill_steps.zig"); +const flight = @import("prompt_flight.zig"); +const be = lanes.backend; +const t = std.testing; +const gpa = t.allocator; + +const Kind = enum(u2) { prefill, step, verify, draft }; +const Buffer = struct { + pub fn wait(_: Buffer) void {} + pub fn release(_: Buffer) void {} + pub fn failure(_: Buffer) ?[]const u8 { + return null; + } + pub fn gpuSeconds(_: Buffer) f64 { + return 0.002; + } +}; +const Flight = struct { end: u64, cb: Buffer, kind: Kind, prompt: ?flight.Prompt = null }; + +/// The flight owner prompt_flight.zig drives, as prompt_flight_test.zig's: submissions queue, `land` waits. +const Queue = struct { + gpa: std.mem.Allocator = gpa, + next: u64 = 1, + landed: u64 = 0, + last_ms: f64 = 0, + gpu_ms: f64 = 0, + timing: struct { ms: [4]f64 = @splat(0), count: [4]usize = @splat(0) } = .{}, + flights: std.ArrayList(Flight) = .empty, + drains: usize = 0, + pub fn submit(q: *Queue, kind: Kind, end: u64, _: anytype) !void { + try q.flights.append(q.gpa, .{ .end = end, .kind = kind, .cb = .{} }); + } + pub fn land(q: *Queue) !void { + try flight.land(q); + } + pub fn drain(q: *Queue) !void { + q.drains += 1; + while (q.flights.items.len > 0) try q.land(); + } + fn deinit(q: *Queue) void { + q.flights.deinit(q.gpa); + } +}; + +const Event = union(enum) { chunk: struct { id: u8, at: usize, rows: usize }, load: u8, decode: u8, keep: u32 }; + +/// The device side as prefill_metal.zig's Ops: each chunk's rows and the head's absorbed rows recorded. +const Ops = struct { + log: *std.ArrayList(Event), + map: *pass.Steps, + queue: *Queue, + cap_rows: usize = 8, + decide: ?usize = null, + head: ?*std.ArrayList([2]usize) = null, // the MTP head's absorbed rows, [start, end) a chunk + loads_on_empty: *bool, // every load found the queue landed (the shared prompt buffer free) + + pub fn steps(o: Ops) *pass.Steps { + return o.map; + } + pub fn cap(o: Ops) usize { + return o.cap_rows; + } + pub fn decision(o: Ops, _: *lanes.Stream) ?usize { + return o.decide; + } + pub fn grow(_: Ops, _: *lanes.Stream, _: usize) !void {} + pub fn body(o: Ops, s: *lanes.Stream, at: usize, rows: usize) struct { rows: usize } { + o.log.append(gpa, .{ .chunk = .{ .id = s.id[0], .at = at, .rows = rows } }) catch @panic("out of memory"); + if (o.head) |h| h.append(gpa, .{ at, at + pass.absorbed(at, rows, s.prompt_len) }) catch @panic("out of memory"); + return .{ .rows = rows }; + } + pub fn load(o: Ops, s: *lanes.Stream) void { + if (o.queue.flights.items.len != 0) o.loads_on_empty.* = false; + o.log.append(gpa, .{ .load = s.id[0] }) catch @panic("out of memory"); + } + pub fn open(_: Ops, s: *lanes.Stream) !usize { + if (s.isCancelled()) return error.Cancelled; + return 0; + } + pub fn finish(_: Ops, _: *lanes.Stream) !void {} +}; + +/// main's cuts for the 29-token prompt: starts 3 and 20, decision row 12, cap 8 (as prompt_flight_test.zig). +const want = [_][2]usize{ .{ 0, 3 }, .{ 3, 8 }, .{ 11, 2 }, .{ 13, 7 }, .{ 20, 8 }, .{ 28, 1 } }; + +fn chunksOf(log: []const Event) ![][2]usize { + var out: std.ArrayList([2]usize) = .empty; + for (log) |e| if (e == .chunk) try out.append(gpa, .{ e.chunk.at, e.chunk.rows }); + return out.toOwnedSlice(gpa); +} + +test "Nemotron Metal steps: one call submits one chunk at today's cut, and the calls' chunks are the whole pass's" { + const ids: [29]u32 = @splat(7); + for ([_]bool{ false, true }) |stepped| { + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &ids, .max_new = 1, .chunks = &.{ 3, 20 } }); + defer s.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .decide = 12, .loads_on_empty = &empty }; + if (stepped) { + for (want, 0..) |w, i| { + const before = log.items.len; + try t.expectEqual(i + 1 == want.len, try pass.step(&q, ops, &s)); + const got = try chunksOf(log.items[before..]); + defer gpa.free(got); + try t.expectEqualSlices([2]usize, &.{w}, got); // exactly one chunk, today's + try t.expectEqual(@as(u32, @intCast(w[0])), s.fill_at.load(.monotonic)); // landed rows only + } + try t.expect(empty); // each step loaded this prompt's ids only once the queue had landed + try t.expectEqual(@as(usize, 0), map.at.count()); + } else try pass.whole(&q, ops, &s); + const got = try chunksOf(log.items); + defer gpa.free(got); + try t.expectEqualSlices([2]usize, &want, got); + try q.drain(); + try t.expectEqualSlices(u32, &.{ 3, 8, 2, 7, 8, 1 }, s.prefill_widths.items); + } +} + +test "Nemotron Metal steps: the MTP head absorbs every prompt row but the last, once, chunk by chunk" { + const ids: [29]u32 = @splat(7); + var s = try lanes.Stream.init(gpa, .{ .id = "h", .prompt = &ids, .max_new = 1, .chunks = &.{ 3, 20 } }); + defer s.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var head: std.ArrayList([2]usize) = .empty; + defer head.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .decide = 12, .head = &head, .loads_on_empty = &empty }; + while (!try pass.step(&q, ops, &s)) {} + // each chunk's own encode absorbs its rows: contiguous, 0..28 (row 28's next token is the first draw) + var at: usize = 0; + for (head.items) |h| { + try t.expectEqual(at, h[0]); + at = h[1]; + } + try t.expectEqual(@as(usize, 28), at); + try t.expectEqual(want.len, head.items.len); +} + +const Kept = struct { + log: *std.ArrayList(Event), + fn at(ptr: *anyopaque, _: *lanes.Stream, row: u32) void { + const k: *Kept = @ptrCast(@alignCast(ptr)); + k.log.append(gpa, .{ .keep = row }) catch @panic("out of memory"); + } +}; + +test "Nemotron Metal steps: a cancel between chunks lands the queue and keeps the state at the last chunk's end" { + const ids: [29]u32 = @splat(7); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var kept: Kept = .{ .log = &log }; + var s = try lanes.Stream.init(gpa, .{ .id = "c", .prompt = &ids, .max_new = 1, .chunks = &.{ 3, 20 }, .reuse = .{ .hook = .{ .ptr = &kept, .at = Kept.at } } }); + defer s.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .decide = 12, .loads_on_empty = &empty }; + for (0..2) |_| try t.expect(!try pass.step(&q, ops, &s)); + try t.expectEqual(@as(usize, 1), q.flights.items.len); // the second chunk still queued + try pass.cancel(&q, ops, &s); + try t.expectEqual(@as(usize, 0), q.flights.items.len); + try t.expectEqual(Event{ .keep = 11 }, log.items[log.items.len - 1]); +} + +/// The lanes fake with Nemotron's stepping in front (cap 4), every chunk, load and decode logged. +const Gem = struct { + fake: lanes.fake.Fake, + inner: be.Backend = undefined, + vt: be.Backend.VTable = undefined, + q: Queue = .{}, + map: pass.Steps = .{}, + log: std.ArrayList(Event) = .empty, + empty: bool = true, + + var current: *Gem = undefined; + + fn init(x: *Gem) be.Backend { + current = x; + x.inner = x.fake.backend(); + x.vt = x.inner.vtable.*; + x.vt.prefill_step = prefillStep; + x.vt.reports_fill = true; + x.vt.queue = queue; + x.vt.verify = verify; + return .{ .ptr = x.inner.ptr, .vtable = &x.vt }; + } + fn deinit(x: *Gem) void { + x.q.deinit(); + x.map.at.deinit(gpa); + x.log.deinit(gpa); + x.fake.deinit(); + } + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const x = current; + const done = try pass.step(&x.q, Ops{ .log = &x.log, .map = &x.map, .queue = &x.q, .cap_rows = 4, .loads_on_empty = &x.empty }, s); + if (done) { + try x.q.drain(); + try x.inner.vtable.prefill(ptr, s); // the fake's own state: its tokens follow the whole prompt + } + return done; + } + fn queue(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + try current.log.append(gpa, .{ .decode = s.id[0] }); + return current.inner.vtable.queue(ptr, s, feed, position); + } + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + for (windows) |w| try current.log.append(gpa, .{ .decode = w.stream.id[0] }); + return current.inner.vtable.verify(ptr, windows, out); + } +}; + +test "Nemotron Metal steps: another stream decodes between two chunks of a long prompt" { + var costs: [16]lanes.config.Cost = undefined; + for (&costs, 1..) |*c, w| c.* = .{ .width = @intCast(w), .ms = 5.0 + 0.8 * @as(f64, @floatFromInt(w)) }; + var cfg = try lanes.config.Config.init(gpa, .{ .exact_width = 16, .gpu_tokens = true, .window_costs = &costs, .hidden_rows = true, .batch_rows = 32, .max_streams = 8 }, 16, 15); + defer cfg.deinit(gpa); + var gem: Gem = .{ .fake = .{ .gpa = gpa } }; + defer gem.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, gem.init(), clock.clock()); + defer engine.deinit(); + try t.expect(engine.fills()); // the lane host now steps this backend's prompts (lane_host_fill.zig) + const short = [_]u32{ 5, 6, 7 }; + const long = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + var a = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = &short, .max_new = 20, .drafts = false }); + defer a.deinit(gpa); + var b = try lanes.Stream.init(gpa, .{ .id = "b", .prompt = &long, .max_new = 4, .drafts = false }); + defer b.deinit(gpa); + while (!try engine.fillStream(&a, gem.fake.prefill_count == 0)) {} + var first = true; + while (!try engine.fillStream(&b, first)) { + first = false; + try engine.step(); // stream a's round between b's chunks + } + var seen: [3]usize = undefined; + var n: usize = 0; + for (gem.log.items, 0..) |e, i| if (e == .chunk and e.chunk.id == 'b') { + seen[n] = i; + n += 1; + }; + try t.expectEqual(@as(usize, 3), n); + for (seen[0..2], seen[1..3]) |from, to| { + const between = for (gem.log.items[from..to]) |e| { + if (e == .decode and e.decode == 'a') break true; + } else false; + try t.expect(between); + } + try t.expect(gem.empty); // no chunk's ids went into the prompt buffer while another chunk was queued + while (engine.activeCount() > 0) try engine.step(); +} diff --git a/zig/src/metal_prefill_widths_compile.zig b/zig/src/metal_prefill_widths_compile.zig index 552cc02473f..df5206e93ae 100644 --- a/zig/src/metal_prefill_widths_compile.zig +++ b/zig/src/metal_prefill_widths_compile.zig @@ -5,6 +5,9 @@ const lanes = @import("lanes"); export fn nemotronPrefillWidthsCompile(b: *tf.nemotron.backend.Metal, s: *lanes.Stream) u8 { const backend = b.backend(); backend.prefill(s) catch return 1; + // the stepped pass and its cancel (#3021), which the lane host calls between rounds + _ = backend.vtable.prefill_step.?(backend.ptr, s, 0) catch return 1; + backend.vtable.cancel_prefill.?(backend.ptr, s) catch return 1; const first = backend.first(s, s.prompt_len) catch return 1; _ = backend.read(first) catch return 1; backend.release(s); From b48287f2ab9f64223800fed527121573c561a049 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:13:01 -0800 Subject: [PATCH 07/59] fix(metal): preserve Nemotron prompt overlap and cancelled progress --- CHANGELOG.md | 4 + zig/src/core/lane_host.zig | 1 + zig/src/core/lane_host_end.zig | 1 + zig/src/core/lane_host_load_account_test.zig | 21 +++++ zig/src/families/nemotron/backend.zig | 2 +- zig/src/families/nemotron/prefill_metal.zig | 3 +- zig/src/families/nemotron/prefill_steps.zig | 25 ++++- .../families/nemotron/prefill_steps_test.zig | 94 ++++++++++++++++++- 8 files changed, 142 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04af662aa1b..350a945bcb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -257,6 +257,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CI: the serving pins (`test-gradient-serving` and `test-qwen-serving-host`) run on every pull request, not only in the nightly, so a change to a pinned serving file carries its re-pin. `experts.zig` is re-pinned for #2843 (#3011). - Tests: the images route test fixture can no longer hang a test run on macOS. Its route closes its end of the socket on every exit and the client's writes are bounded, so a route that answers before reading a large body ends the write at once (#3010). +- Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). +- Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). +- Nemotron Metal keeps the prompt IDs and one queued chunk across consecutive prefill steps. + Cancellation publishes the landed prefix before keeping it and credits that work before retirement. - CUDA EXL3 grouped experts launch and size their storage at the caller's tile and pair count, so decode no longer launches three quarters of its grid empty, and Qwen3.6-35B-A3B EXL3 sizes its grouped storage for 36,864 pair rows instead of 163,904 (about 3 GB less); outputs are bit-equal (#2843, for #2823). diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index dbd26159689..dc305810180 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -301,6 +301,7 @@ pub const LaneHost = struct { } pub fn finish(h: *LaneHost, job: *Job, reason: Reason, message: []const u8) void { + if (reason == .cancelled) load.progress(h, job); h.lock(); h.memory_lanes = null; // a lane may have freed: the next admission asks the backend for memory again ledger.release(h, job); // its stream's caches are already freed (reaped, discarded or released) diff --git a/zig/src/core/lane_host_end.zig b/zig/src/core/lane_host_end.zig index d617c29d225..e3eb7434387 100644 --- a/zig/src/core/lane_host_end.zig +++ b/zig/src/core/lane_host_end.zig @@ -30,6 +30,7 @@ pub fn takeCancels(h: *LaneHost) void { h.unlock(); if (found) |job| { if (job.fill_began and job.prefilled == null and !job.stream.finished) if (h.core.backend.vtable.cancel_prefill) |keep_prefix| { + @import("lane_host_load.zig").calling(h, job); keep_prefix(h.core.backend.ptr, &job.stream) catch |err| { _ = dropFailed(h, job, err); continue; diff --git a/zig/src/core/lane_host_load_account_test.zig b/zig/src/core/lane_host_load_account_test.zig index c3ff82f1e63..9941a8b9e37 100644 --- a/zig/src/core/lane_host_load_account_test.zig +++ b/zig/src/core/lane_host_load_account_test.zig @@ -67,6 +67,27 @@ const Host = struct { const prompt: [1000]u32 = @splat(5); const request: api.Request = .{ .prompt = &prompt, .max_tokens = 4 }; +test "cancel retirement credits a newly landed tail once before discarding the pass" { + var x: Host = undefined; + try x.init(); + defer x.deinit(); + const j = try std.testing.allocator.create(Job); + j.* = x.job(&request, 0); + const Sink = struct { + fn event(_: *anyopaque, _: api.Id, _: *const api.Event) void {} + }; + j.sink = .{ .ctx = &x, .event = Sink.event }; + load.calling(&x.host, j); + Hand.wait(400); + j.stream.fill_at.store(400, .monotonic); + load.progress(&x.host, j); + load.calling(&x.host, j); + Hand.wait(400); + j.stream.fill_at.store(800, .monotonic); + x.host.finish(j, .cancelled, ""); + try std.testing.expectEqual([2]u64{ 800, 800 }, x.work()); +} + test "waiting between a pass's calls is not busy time; each chunk's work moves with its own time" { var x: Host = undefined; try x.init(); diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index 013dcc74d3d..208b412032b 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -491,7 +491,7 @@ pub const Metal = struct { self.drain() catch { @import("prompt_flight.zig").forget(self, s); }; - _ = self.steps.at.remove(s); // a stream that left mid-pass + self.steps.forget(s); // a stream that left mid-pass no longer owns the prompt ids if (self.caches.fetchRemove(s)) |kv| { kv.value.deinit(&self.pool); self.gpa.destroy(kv.value); diff --git a/zig/src/families/nemotron/prefill_metal.zig b/zig/src/families/nemotron/prefill_metal.zig index 93a8f8d59f7..0490f471b99 100644 --- a/zig/src/families/nemotron/prefill_metal.zig +++ b/zig/src/families/nemotron/prefill_metal.zig @@ -77,6 +77,7 @@ const Ops = struct { pub fn load(o: Ops, s: *lanes.Stream) void { const ids = s.prompt(); @memcpy(o.m.prompt.slice(u32, ids.len), ids); + o.m.steps.ids = s; } /// The stream's cache opened, its ids loaded and a kept state restored: the row its pass starts from. @@ -93,7 +94,7 @@ const Ops = struct { _ = self.caches.remove(s); } const c = try @import("residency.zig").openCache(self, s, rows_needed); - @memcpy(self.prompt.slice(u32, ids.len), ids); + o.load(s); s.cached = 0; var at: usize = 0; if (s.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there diff --git a/zig/src/families/nemotron/prefill_steps.zig b/zig/src/families/nemotron/prefill_steps.zig index ee20d85e932..92a855e39e1 100644 --- a/zig/src/families/nemotron/prefill_steps.zig +++ b/zig/src/families/nemotron/prefill_steps.zig @@ -5,7 +5,16 @@ const flight = @import("prompt_flight.zig"); const Stream = lanes.Stream; /// Streams whose prompt passes run a chunk a call (prefill_step): each one's next prompt row. -pub const Steps = struct { at: std.AutoHashMapUnmanaged(*Stream, usize) = .empty }; +pub const Steps = struct { + at: std.AutoHashMapUnmanaged(*Stream, usize) = .empty, + ids: ?*Stream = null, + + /// A retired stream cannot remain the shared prompt buffer's owner, even if its address is reused. + pub fn forget(steps: *Steps, s: *Stream) void { + _ = steps.at.remove(s); + if (steps.ids == s) steps.ids = null; + } +}; /// Rows of a chunk from `at` whose next token the prompt holds (`n` tokens): the MTP head absorbs these. pub fn absorbed(at: usize, rows: usize, n: usize) usize { @@ -41,11 +50,16 @@ pub fn step(b: anytype, ops: anytype, s: *Stream) !bool { return e; }; errdefer _ = map.remove(s); - // the prompt buffer is every pass's: the chunks queued before this one land, then it holds this prompt - try b.drain(); - ops.load(s); + // Another prompt's ids may replace the shared buffer only after all its readers have landed. + if (ops.steps().ids != s) { + try b.drain(); + ops.load(s); + } var next: usize = 0; - const end = try chunk(b, ops, s, map.get(s).?, &next); + const end = chunk(b, ops, s, map.get(s).?, &next) catch |err| { + if (err == error.Cancelled) try cancel(b, ops, s); + return err; + }; if (end < s.prompt_len) { map.getPtr(s).?.* = end; return false; @@ -59,6 +73,7 @@ pub fn step(b: anytype, ops: anytype, s: *Stream) !bool { pub fn cancel(b: anytype, ops: anytype, s: *Stream) !void { const at = ops.steps().at.get(s) orelse return; try b.drain(); + s.fill_at.store(@intCast(at), .monotonic); s.keepInterruptedPrefill(@intCast(at)); } diff --git a/zig/src/families/nemotron/prefill_steps_test.zig b/zig/src/families/nemotron/prefill_steps_test.zig index f5d3438ebb7..35588c262c1 100644 --- a/zig/src/families/nemotron/prefill_steps_test.zig +++ b/zig/src/families/nemotron/prefill_steps_test.zig @@ -74,10 +74,13 @@ const Ops = struct { } pub fn load(o: Ops, s: *lanes.Stream) void { if (o.queue.flights.items.len != 0) o.loads_on_empty.* = false; + o.map.ids = s; o.log.append(gpa, .{ .load = s.id[0] }) catch @panic("out of memory"); } - pub fn open(_: Ops, s: *lanes.Stream) !usize { + pub fn open(o: Ops, s: *lanes.Stream) !usize { if (s.isCancelled()) return error.Cancelled; + try o.queue.drain(); + o.load(s); return 0; } pub fn finish(_: Ops, _: *lanes.Stream) !void {} @@ -152,8 +155,10 @@ test "Nemotron Metal steps: the MTP head absorbs every prompt row but the last, const Kept = struct { log: *std.ArrayList(Event), - fn at(ptr: *anyopaque, _: *lanes.Stream, row: u32) void { + published: ?u32 = null, + fn at(ptr: *anyopaque, s: *lanes.Stream, row: u32) void { const k: *Kept = @ptrCast(@alignCast(ptr)); + k.published = s.fill_at.load(.monotonic); k.log.append(gpa, .{ .keep = row }) catch @panic("out of memory"); } }; @@ -176,6 +181,91 @@ test "Nemotron Metal steps: a cancel between chunks lands the queue and keeps th try pass.cancel(&q, ops, &s); try t.expectEqual(@as(usize, 0), q.flights.items.len); try t.expectEqual(Event{ .keep = 11 }, log.items[log.items.len - 1]); + try t.expectEqual(@as(?u32, 11), kept.published); + try t.expectEqual(@as(u32, 11), s.fill_at.load(.monotonic)); +} + +test "Nemotron Metal steps: consecutive chunks retain the prompt ids and one queued chunk" { + const ids: [29]u32 = @splat(7); + var s = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = &ids, .max_new = 1 }); + defer s.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .loads_on_empty = &empty }; + try t.expect(!try pass.step(&q, ops, &s)); + const drains = q.drains; + for (0..2) |_| { + try t.expect(!try pass.step(&q, ops, &s)); + try t.expectEqual(drains, q.drains); + try t.expectEqual(@as(usize, 1), q.flights.items.len); + } + var loads: usize = 0; + for (log.items) |e| if (e == .load) { + loads += 1; + }; + try t.expectEqual(@as(usize, 1), loads); + try t.expectEqualSlices(u32, &.{ 8, 8 }, s.prefill_widths.items); + try t.expect(empty); +} + +test "Nemotron Metal steps: changing the prompt owner drains before each id reload" { + const ids: [29]u32 = @splat(7); + var a = try lanes.Stream.init(gpa, .{ .id = "a", .prompt = &ids, .max_new = 1 }); + defer a.deinit(gpa); + var b = try lanes.Stream.init(gpa, .{ .id = "b", .prompt = &ids, .max_new = 1 }); + defer b.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .loads_on_empty = &empty }; + for ([_]*lanes.Stream{ &a, &a, &b, &a }) |s| try t.expect(!try pass.step(&q, ops, s)); + var loaded: std.ArrayList(u8) = .empty; + defer loaded.deinit(gpa); + for (log.items) |e| if (e == .load) { + try loaded.append(gpa, e.load); + }; + try t.expectEqualSlices(u8, "aba", loaded.items); + try t.expectEqual(@as(usize, 3), q.drains); + try t.expect(empty); +} + +test "Nemotron Metal steps: cancellation inside a step publishes and keeps its landed tail" { + const Stop = struct { + fn yes(_: *anyopaque) bool { + return true; + } + }; + const ids: [29]u32 = @splat(7); + var log: std.ArrayList(Event) = .empty; + defer log.deinit(gpa); + var kept: Kept = .{ .log = &log }; + var s = try lanes.Stream.init(gpa, .{ .id = "c", .prompt = &ids, .max_new = 1, .reuse = .{ .hook = .{ .ptr = &kept, .at = Kept.at } } }); + defer s.deinit(gpa); + var q: Queue = .{}; + defer q.deinit(); + var map: pass.Steps = .{}; + defer map.at.deinit(gpa); + var empty = true; + const ops: Ops = .{ .log = &log, .map = &map, .queue = &q, .loads_on_empty = &empty }; + for (0..2) |_| try t.expect(!try pass.step(&q, ops, &s)); + var stop: u8 = 0; + s.cancel_check = .{ .ptr = &stop, .check = Stop.yes }; + try t.expectError(error.Cancelled, pass.step(&q, ops, &s)); + try t.expectEqual(@as(?u32, 16), kept.published); + try t.expectEqual(@as(u32, 16), s.fill_at.load(.monotonic)); + try t.expectEqual(@as(usize, 0), q.flights.items.len); + try t.expectEqual(@as(usize, 0), map.at.count()); + map.forget(&s); + try t.expectEqual(@as(?*lanes.Stream, null), map.ids); } /// The lanes fake with Nemotron's stepping in front (cap 4), every chunk, load and decode logged. From eed8ed1f1e5e6c7144af3d3e966a4b1d8e7f11cd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:14:16 +0000 Subject: [PATCH 08/59] changelog: #3054's line from lines/3054.txt in place of its own --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 350a945bcb3..0045951297c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). +- Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). + - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). From 20ad33953d4a337f68c3440701caad6c60b16c01 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:01:13 +0000 Subject: [PATCH 09/59] changelog: back under Unreleased --- CHANGELOG.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0045951297c..3d7044bb2cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,11 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). +- Nemotron Metal keeps the prompt IDs and one queued chunk across consecutive prefill steps. + Cancellation publishes the landed prefix before keeping it and credits that work before retirement. - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). -- Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). - - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). @@ -259,10 +260,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CI: the serving pins (`test-gradient-serving` and `test-qwen-serving-host`) run on every pull request, not only in the nightly, so a change to a pinned serving file carries its re-pin. `experts.zig` is re-pinned for #2843 (#3011). - Tests: the images route test fixture can no longer hang a test run on macOS. Its route closes its end of the socket on every exit and the client's writes are bounded, so a route that answers before reading a large body ends the write at once (#3010). -- Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). -- Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). -- Nemotron Metal keeps the prompt IDs and one queued chunk across consecutive prefill steps. - Cancellation publishes the landed prefix before keeping it and credits that work before retirement. - CUDA EXL3 grouped experts launch and size their storage at the caller's tile and pair count, so decode no longer launches three quarters of its grid empty, and Qwen3.6-35B-A3B EXL3 sizes its grouped storage for 36,864 pair rows instead of 163,904 (about 3 GB less); outputs are bit-equal (#2843, for #2823). From 147db1b6b331830312951d1fe1cff6f185558784 Mon Sep 17 00:00:00 2001 From: tacosta <27917082+tacosta@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:52:38 +0000 Subject: [PATCH 10/59] fix(qwen3.5/cuda): yield background prefill between chunks --- .../qwen35-warm-prefill-20261111/README.md | 40 ++++ tools/bench_warm_turns.py | 217 ++++++++++++++++++ zig/build/cuda_family_host.zig | 4 +- zig/src/families/qwen3_5/cuda_prefill.zig | 81 +++++++ 4 files changed, 340 insertions(+), 2 deletions(-) create mode 100644 docs/receipts/qwen35-warm-prefill-20261111/README.md create mode 100644 tools/bench_warm_turns.py diff --git a/docs/receipts/qwen35-warm-prefill-20261111/README.md b/docs/receipts/qwen35-warm-prefill-20261111/README.md new file mode 100644 index 00000000000..3aff96c13fd --- /dev/null +++ b/docs/receipts/qwen35-warm-prefill-20261111/README.md @@ -0,0 +1,40 @@ +# Qwen 3.5 CUDA foreground-prefill yield + +## Scope + +This receipt covers the foreground-yield fix in this pull request. Before another chunk starts, `cuda_prefill.chunk` checks `stream.yields()`. When foreground work is waiting, it preserves the completed prefix with `keepInterruptedPrefill(f.at)` and returns `error.Yielded`. No new forward starts after the yield is observed. + +On the final rebase base, `93a2e93ec`, `cuda_native.prefillFn` routes a normal whole prompt through `prefill.run`; `run` calls `chunk` until the prompt completes. The warm pass uses this whole-prefill path, so it reaches the yield check. + +## Host regression + +On the narrowed head, `zig build test-qwen35-prefill-host --summary all` passed 17/17 tests. The new test confirms one completed chunk, retention of its exact prefix, and no second forward after yield. + +Both negative controls failed as intended: + +- Without the yield check, the test failed with `expected error.Yielded, found true`. +- With the yield check but without `keepInterruptedPrefill`, the test failed with `expected 1, found 0` for the saved-prefix callback. + +## GPU integration context + +These integration measurements were collected on 2026-11-11 against main base `ccad6e6cddf1536d14834b59e666b9d59bcb0c3c`, using combined candidate source `708f26effc0525623c909b3af37683e52124db33`. That source still contained the warm-turn enablement and other hunks now dropped from this PR. The measurements demonstrate the warm-prefill scenario, but are not measurements of this narrowed head and do not isolate the yield change's latency impact. They also predate the new yield-side `keepInterruptedPrefill` call; the host regression below tests that behavior. + +| Path | Cached tokens | Engine prefill | Client TTFT | Yields | +| --- | ---: | ---: | ---: | ---: | +| Main, cold continuation | 0 | 2.565895 s | 2.567245 s | 0 | +| Earlier combined branch, foreground request after 200 ms | 4,096 | 0.163107 s | 2.534763 s | 1 | + +The continuation token and output hashes matched. TTFT stayed near the cold latency because the chunk already in progress completed before foreground prefill resumed. A separate warm-boundary case reused 4,096 tokens and measured 2.576211 s cold prefill versus 0.163060 s after the warm pass, with matching hashes. + +The raw JSON and SHA-256 manifest for the full earlier qualification are in this [unlisted gist](https://gist.github.com/tacosta/ad6fd030862b9966791acf3d540a1591). Its records include exact token/output hashes, prompt lengths, cached-token counts, and engine prefill time distinct from client TTFT. + +## Environment and limits + +The earlier integration run used an NVIDIA GeForce RTX 5090 Laptop GPU (SM120, 24,463 MiB), Ubuntu 26.04 on Linux 7.0.0-43-generic, 32 GB RAM, CUDA 13.3, and Zig 0.17.0. The target was dense Qwen3.8-27B NVFP4. No immutable checkpoint revision was available; these file hashes identify the tested checkpoint: + +- `config.json`: `71fa01bb64de20971045cd82a82c0ebb25a54e1b0a3f09ef23cf5479e9c54df8` +- `tokenizer.json`: `0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3` +- `tokenizer_config.json`: `e5d078b00e6c1223b32444db8c1001dc71d86ceef8ee706b5bf084c3a43a1f9c` +- `model.safetensors.index.json`: `7aa103a2582b7d26631988de33dea19e8a308ee9c239e8e14feb374af30905e2` + +No Qwen MoE fit this GPU: the smallest available MoE weights were 22.02 GiB with a 24.06 GiB runtime floor, above 23.89 GiB total device memory. This PR adds no model arithmetic or kernel changes. Main-versus-head performance for the narrowed change was not remeasured; the previous sub-1% deltas were too small to draw a conclusion and do not establish the strict no-slower gate. diff --git a/tools/bench_warm_turns.py b/tools/bench_warm_turns.py new file mode 100644 index 00000000000..2b2c75d85c0 --- /dev/null +++ b/tools/bench_warm_turns.py @@ -0,0 +1,217 @@ +"""Measure a chat turn and its prefetched continuation without retaining prompt or reply text.""" +import argparse +import hashlib +import json +import sys +import time +import urllib.request + + +def request_json(base, path, body=None): + data = None if body is None else json.dumps(body).encode("utf-8") + headers = {} if data is None else {"Content-Type": "application/json"} + req = urllib.request.Request(base + path, data=data, headers=headers) + with urllib.request.urlopen(req, timeout=900) as response: + return json.load(response) + + +def load(base): + return request_json(base, "/v1/load") + + +def public_load(value): + return {key: item for key, item in value.items() if key not in ("instance", "timestamp", "model")} + + +def tokenize(base, messages): + body = {"messages": messages, "chat_template_kwargs": {"enable_thinking": False}} + return request_json(base, "/v1/tokenize", body)["tokens"] + + +def stream_chat(base, model, messages, max_tokens, seed): + body = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": 0, + "seed": seed, "stream": True, "stream_options": {"include_usage": True}, + "return_token_ids": True, "chat_template_kwargs": {"enable_thinking": False}} + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode("utf-8"), + headers={"Content-Type": "application/json"}) + sent = time.perf_counter() + first_output = None + contents, reasoning = [], [] + usage, runtime = {}, {} + finish_reason = None + done = False + with urllib.request.urlopen(req, timeout=900) as response: + headers = time.perf_counter() + for raw in response: + line = raw.decode("utf-8").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + done = True + break + event = json.loads(data) + usage = event.get("usage") or usage + runtime = event.get("tensorfold") or runtime + for choice in event.get("choices", []): + delta = choice.get("delta") or {} + content = delta.get("content") or "" + thought = delta.get("reasoning_content") or "" + if content or thought: + first_output = first_output or time.perf_counter() + contents.append(content) + reasoning.append(thought) + finish_reason = choice.get("finish_reason") or finish_reason + ended = time.perf_counter() + content, thought = "".join(contents), "".join(reasoning) + details = usage.get("prompt_tokens_details") or {} + return {"prompt_tokens": usage.get("prompt_tokens"), "cached_tokens": details.get("cached_tokens"), + "completion_tokens": usage.get("completion_tokens"), "client_ttft_seconds": + round(first_output - sent, 6) if first_output else None, + "client_headers_seconds": round(headers - sent, 6), "client_end_to_end_seconds": round(ended - sent, 6), + "engine_prefill_seconds": runtime.get("prefill_seconds"), + "engine_time_to_first_token_seconds": runtime.get("time_to_first_token"), + "prefill_widths": runtime.get("prefill_widths"), "token_sha256": runtime.get("token_sha256"), + "token_sha": runtime.get("token_sha"), "output_sha256": hashlib.sha256( + json.dumps([content, thought], ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest(), + "finish_reason": finish_reason, "complete": done and finish_reason is not None, + "content_sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(), "_content": content} + + +def int_at(value, *path): + for key in path: + if not isinstance(value, dict): + return None + value = value.get(key) + return value if type(value) is int and value >= 0 else None + + +def run(args): + base = args.base.rstrip("/") + fixture = (f"Warm-prefill qualification {args.case_id}.\n" + "alpha beta gamma delta\n" * args.repeat_lines + + "Answer with only the word READY.") + user = {"role": "user", "content": fixture} + first_messages = [user] + initial_ids = tokenize(base, first_messages) + before = load(base) + first = stream_chat(base, args.model, first_messages, args.max_tokens, args.seed) + first_finished_at = time.perf_counter() + answer = first.pop("_content", None) + if answer is None: + raise RuntimeError("first turn returned no answer") + follow_user = {"role": "user", "content": "What should the next line say? Answer with one word."} + history = [user, {"role": "assistant", "content": answer}, follow_user] + continuation_ids = tokenize(base, history) + a_ids = tokenize(base, [user, {"role": "assistant", "content": answer}, {"role": "user", "content": "A"}]) + b_ids = tokenize(base, [user, {"role": "assistant", "content": answer}, {"role": "user", "content": "B"}]) + common = next((i for i, pair in enumerate(zip(a_ids, b_ids)) if pair[0] != pair[1]), min(len(a_ids), len(b_ids))) + after_first = load(base) + ready = False + waited = 0.0 + started_before = int_at(before, "requests_started") or 0 + warm_started = False + if args.phase == "ready": + start_wait = time.perf_counter() + deadline = start_wait + args.warm_timeout + while time.perf_counter() < deadline: + state = load(base) + warm_started = (int_at(state, "requests_started") or 0) >= started_before + 2 + running = int_at(state, "running") + if warm_started and running == 0: + ready = True + break + time.sleep(0.05) + waited = round(time.perf_counter() - start_wait, 6) + elif args.phase == "yield": + time.sleep(args.warm_delay_ms / 1000) + waited = args.warm_delay_ms / 1000 + else: + time.sleep(args.warm_delay_ms / 1000) + waited = args.warm_delay_ms / 1000 + before_continuation = load(base) + warm_started = warm_started or (int_at(before_continuation, "requests_started") or 0) >= started_before + 2 + warm_running_at_continuation = (int_at(before_continuation, "running") or 0) > 0 + continuation_sent_at = time.perf_counter() + continuation = stream_chat(base, args.model, history, args.max_tokens, args.seed) + continuation.pop("_content", None) + after_continuation = load(base) + warm_yields_before = int_at(after_first, "background_yields") or 0 + warm_yields_after = int_at(after_continuation, "background_yields") or 0 + candidate_cached = continuation.get("cached_tokens") + if args.phase == "cold": + cache_ok = first.get("cached_tokens") == 0 + else: + cache_ok = type(candidate_cached) is int and candidate_cached >= min(4096, common) + yield_ok = args.phase != "yield" or (warm_running_at_continuation and warm_yields_after > warm_yields_before) + crossed_grid = len(initial_ids) < 4096 <= common + compare = None + if args.compare_file: + with open(args.compare_file, encoding="utf-8") as source: + reference = json.load(source) + ref_first = reference.get("first_turn", {}) + ref_cont = reference.get("continuation", {}) + compare = {"first_token_ids_equal": bool(first.get("token_sha256") and + first["token_sha256"] == ref_first.get("token_sha256")), + "continuation_token_ids_equal": bool(continuation.get("token_sha256") and + continuation["token_sha256"] == ref_cont.get("token_sha256")), + "first_output_equal": first.get("output_sha256") == ref_first.get("output_sha256"), + "continuation_output_equal": continuation.get("output_sha256") == ref_cont.get("output_sha256")} + report = {"schema_version": 1, "phase": args.phase, "case_id": args.case_id, "model": args.model, + "prompt_fixture_sha256": hashlib.sha256(fixture.encode("utf-8")).hexdigest(), + "repeat_lines": args.repeat_lines, "temperature": 0, "seed": args.seed, + "context_window": request_json(base, "/v1/models")["data"][0].get("context_length"), + "capabilities": request_json(base, "/v1/models")["data"][0].get("capabilities", {}), + "first_prompt_tokens_tokenizer": len(initial_ids), "shared_prefix_tokens_tokenizer": common, + "continuation_prompt_tokens_tokenizer": len(continuation_ids), "wait_seconds": waited, + "first_turn_to_continuation_seconds": round(continuation_sent_at - first_finished_at, 6), + "warm_ready_observed": ready, "warm_request_started": warm_started, + "warm_running_at_continuation": warm_running_at_continuation, "first_turn": first, + "continuation": continuation, "background_yields_delta": warm_yields_after - warm_yields_before, + "load_before": public_load(before), "load_after_first_turn": public_load(after_first), + "load_before_continuation": public_load(before_continuation), + "load_after_continuation": public_load(after_continuation), + "comparison": compare, + "assertions": {"first_prompt_tokenizer_count_matches_usage": first.get("prompt_tokens") == len(initial_ids), + "continuation_tokenizer_count_matches_usage": continuation.get("prompt_tokens") == len(continuation_ids), + "warm_prefix_crosses_4096_grid": args.phase == "cold" or crossed_grid, + "first_turn_starts_cold": first.get("cached_tokens") == 0, + "warm_pass_started": args.phase == "cold" or warm_started, + "continuation_cache_requirement": cache_ok, "yield_observed_when_requested": yield_ok, + "first_turn_complete": first.get("complete") is True, + "continuation_complete": continuation.get("complete") is True, + "comparison_exact_when_requested": compare is None or all(compare.values())}} + report["qualified"] = all(report["assertions"].values()) + encoded = json.dumps(report, indent=2) + "\n" + if args.output: + with open(args.output, "w", encoding="utf-8") as out: + out.write(encoded) + print(encoded, end="") + return 0 if report["qualified"] else 1 + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("base", help="native server base URL") + p.add_argument("model") + p.add_argument("--phase", choices=("cold", "ready", "yield"), required=True, + help="cold: do not wait for a candidate; ready: wait for the candidate pass; yield: arrive during it") + p.add_argument("--case-id", default="4k") + p.add_argument("--repeat-lines", type=int, default=820) + p.add_argument("--max-tokens", type=int, default=8) + p.add_argument("--seed", type=int, default=1234) + p.add_argument("--warm-delay-ms", type=float, default=200) + p.add_argument("--warm-timeout", type=float, default=120) + p.add_argument("--compare-file") + p.add_argument("--output") + args = p.parse_args(argv) + if args.repeat_lines < 1 or args.max_tokens < 1 or args.warm_delay_ms < 0 or args.warm_timeout < 0: + p.error("repeat-lines and max-tokens must be positive; delays cannot be negative") + try: + return run(args) + except Exception as exc: # Keep failures concise and avoid copying server error bodies into receipts. + print(f"qualification error: {type(exc).__name__}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 2313f026cee..88d87e1b580 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -20,8 +20,8 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B b.step("test-qwen35-shapes-host", "Captured window buckets for one and 2-8 rows without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"one-row and 2-8-row"} })).step); @import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); @import("cuda_groups_host.zig").host(b, cuda, mods, step); - const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen stepped prefill:", "Qwen whole prefill:", "Qwen prefill opening:" } })); - b.step("test-qwen35-prefill-host", "Stepped, whole and opening prompt lifecycle without devices").dependOn(&prefill.step); + const prefill = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen stepped prefill:", "Qwen whole prefill:", "Qwen prefill opening:", "a yielded pass keeps its completed prefix" } })); + b.step("test-qwen35-prefill-host", "Stepped, whole, opening and interrupted prompt lifecycle without devices").dependOn(&prefill.step); step.dependOn(&prefill.step); const draft_config = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"Qwen DFlash2 config:"} })); b.step("test-qwen35-draft-config-host", "DFlash2 attention declarations agree with the CUDA kernels before loading").dependOn(&draft_config.step); diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index 1d4ac8b6cef..e9326f8bbbd 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -44,6 +44,83 @@ fn capped(len: usize, chunks: []const u32, f: *Fill, max_rows: u32) usize { return lanes.step_cap.end(f.at, f.cold, max_rows, cap_grid); } +test "a yielded pass keeps its completed prefix and stops before the next chunk" { + const t = std.testing; + const len: usize = @as(usize, E.max_rows) + 1; + const ids = try t.allocator.alloc(u32, len); + defer t.allocator.free(ids); + @memset(ids, 3); + const Probe = struct { + stream: ?*lanes.Stream = null, + saves: usize = 0, + saved_at: u32 = 0, + fn cast(ctx: *anyopaque) *@This() { + return @ptrCast(@alignCast(ctx)); + } + fn yielded(ctx: *anyopaque) bool { + const p = cast(ctx); + return p.stream.?.fill_at.load(.monotonic) >= E.max_rows; + } + fn kept(ctx: *anyopaque, _: *lanes.Stream, at: u32) void { + const p = cast(ctx); + p.saves += 1; + p.saved_at = at; + } + }; + const FakeEngine = struct { + forwards: usize = 0, + fn forward(self: *@This(), parts: []const E.Part, ids_: []const u32, _: E.Keep) !void { + self.forwards += 1; + parts[0].cache.len += ids_.len; + parts[0].cache.written += ids_.len; + } + }; + const FakePrefix = struct { + fn keep(_: *@This(), _: *E.Cache, _: []const u32, _: usize) !void {} + }; + const FakePages = struct { + fn log(_: *@This(), _: usize, _: usize) void {} + }; + const FakeLanes = struct { + gpa: std.mem.Allocator, + e: FakeEngine = .{}, + cache: *E.Cache, + prefix: ?*FakePrefix = null, + pages: ?*FakePages = null, + fn cacheOf(self: *@This(), _: *lanes.Stream) !*E.Cache { + return self.cache; + } + }; + + var probe: Probe = .{}; + var cache: E.Cache = undefined; + cache.len = 0; + cache.written = 0; + var fake: FakeLanes = .{ .gpa = t.allocator, .cache = &cache }; + var stream = try lanes.Stream.init(t.allocator, .{ + .id = "yielded-prefix", + .prompt = ids, + .max_new = 1, + .yield_check = .{ .ptr = &probe, .check = Probe.yielded }, + .reuse = .{ + .marks = &.{}, + .hook = .{ .ptr = &probe, .at = Probe.kept }, + }, + }); + defer stream.deinit(t.allocator); + probe.stream = &stream; + var fill: Fill = .{ .at = 0, .media = null }; + + try t.expect(!try chunk(&fake, &stream, &fill, 0)); + try t.expectEqual(@as(usize, 1), fake.e.forwards); + try t.expectEqual(E.max_rows, fill.at); + try t.expectEqual(@as(usize, 0), probe.saves); + try t.expectError(error.Yielded, chunk(&fake, &stream, &fill, 0)); + try t.expectEqual(@as(usize, 1), fake.e.forwards); + try t.expectEqual(@as(usize, 1), probe.saves); + try t.expectEqual(E.max_rows, probe.saved_at); +} + pub fn run(self: anytype, stream: *lanes.Stream) !void { var f = try opening(self, stream); defer f.deinit(); @@ -160,6 +237,10 @@ pub fn chunk(self: anytype, stream: *lanes.Stream, f: *Fill, max_rows: u32) !boo stream.keepInterruptedPrefill(@intCast(f.at)); return error.Cancelled; } + if (stream.yields()) { + stream.keepInterruptedPrefill(@intCast(f.at)); + return error.Yielded; + } const cache = try self.cacheOf(stream); var images: ?E.Images = if (f.media) |m| .{ .features = m.features.ptr, .src = m.src, .pos = m.pos } else null; const end = capped(ids.len, stream.chunks, f, max_rows); From 22116c7ca3b042c2a5f92a0fb7c058fa02e11d06 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:14:17 +0000 Subject: [PATCH 11/59] changelog: #2873 under Unreleased --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d7044bb2cf..9770e7082de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel Cancellation publishes the landed prefix before keeping it and credits that work before retirement. - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). +- Qwen 3.5, 3.6 and 3.8 on CUDA: a background prompt fill stops between chunks when a foreground request is waiting, keeps the prefix it has already filled, and resumes from there; replies are unchanged (#2873, part of #2812). Thanks to @tacosta. + +- Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). + - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). From d2b37227a8b4431a71d87bf093786aadcfa35b62 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:01:54 +0000 Subject: [PATCH 12/59] changelog: each line once under Unreleased --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9770e7082de..092b98e2f11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). - Qwen 3.5, 3.6 and 3.8 on CUDA: a background prompt fill stops between chunks when a foreground request is waiting, keeps the prefix it has already filled, and resumes from there; replies are unchanged (#2873, part of #2812). Thanks to @tacosta. -- Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). - - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). From 6b331c93052227cc06c22c02b5f6443b09bdc210 Mon Sep 17 00:00:00 2001 From: gilby Date: Mon, 9 Nov 2026 17:07:34 +0100 Subject: [PATCH 13/59] flashnext hip: the draft step moves to draft_batch.zig and the head's forward takes segments --- .../families/flashnext/hip/draft_batch.zig | 80 +++++++++++++++++++ zig/src/families/flashnext/hip/head.zig | 32 ++++---- zig/src/families/flashnext/hip/lanes.zig | 69 +--------------- 3 files changed, 100 insertions(+), 81 deletions(-) create mode 100644 zig/src/families/flashnext/hip/draft_batch.zig diff --git a/zig/src/families/flashnext/hip/draft_batch.zig b/zig/src/families/flashnext/hip/draft_batch.zig new file mode 100644 index 00000000000..03651fdf8b5 --- /dev/null +++ b/zig/src/families/flashnext/hip/draft_batch.zig @@ -0,0 +1,80 @@ +//! The draft head's absorb-and-chain step over a shared round's lanes. +const std = @import("std"); +const cache = @import("cache.zig"); +const forward = @import("forward.zig"); +const head_mod = @import("head.zig"); +const lanes_mod = @import("lanes.zig"); + +const be = @import("lanes").backend; +const Fx = lanes_mod.Fx; +const Lane = lanes_mod.Lane; + +/// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. +pub fn draft(f: *Fx, requests: []const be.DraftRequest) anyerror!void { + const e = f.e; + const m = &e.weights.model; + const row_bytes = m.dims.wide() * m.act.size(); + for (requests) |r| { + const lane: *Lane = f.lanes.get(r.stream) orelse return error.UnknownStream; + if (lane.pending) |p| try f.mark(lane, if (r.rows) |kept| kept.len else p.rows); + lane.held_n = 0; + if (r.position != lane.caches.len + 1) return error.PositionMismatch; + const hc = if (lane.head) |*h| h else continue; + const token: u32 = if (r.rows != null) + r.follow[r.follow.len - 1] + else switch (r.first orelse return error.NoFirstToken) { + .handle => |at| f.drawn[at % lanes_mod.ring], + .value => |v| v, + }; + var follow_buf: [cache.max_window]u32 = undefined; + const follow: []const u32 = if (r.rows != null) r.follow else blk: { + follow_buf[0] = token; + break :blk follow_buf[0..1]; + }; + const start = lane.caches.len - follow.len; + try e.stream.synchronize(); + e.host.used = 0; + e.arena.reset(); + const o = e.ops(&e.arena); + var out = try head_mod.run( + o, + false, + m, + &e.host, + hc, + .{ .ptr = lane.streams.base(), .kind = m.act }, + follow, + start, + f.ones, + ); + var mixed = forward.at(out.mixed, (follow.len - 1) * m.dims.hidden); + var streams = out.streams.ptr + (follow.len - 1) * row_bytes; + const depth = @min(r.depth, lanes_mod.max_depth); + // a chain past the first round ends after a draft the head gives under the confidence (--mtp-confidence) + const stop_under: f32 = if (r.rows != null) @floatCast(e.o.policy.mtp.confidence) else 0.0; + var d: usize = 0; + var chained: usize = 0; + while (d < depth) : (d += 1) { + var tok: [1]u32 = undefined; + var prob: [1]f32 = undefined; + try head_mod.draws(o, m, &e.host, e.stream, mixed, 1, f.draft_ids, &tok, &prob); + lane.held[d] = tok[0]; + chained = d + 1; + if (d + 1 == depth or prob[0] < stop_under) break; + out = try head_mod.run( + o, + false, + m, + &e.host, + hc, + .{ .ptr = streams, .kind = m.act }, + &tok, + lane.caches.len + d, + f.ones, + ); + mixed = out.mixed; + streams = out.streams.ptr; + } + lane.held_n = chained; + } +} diff --git a/zig/src/families/flashnext/hip/head.zig b/zig/src/families/flashnext/hip/head.zig index ca0f0ecd763..0774e002a5d 100644 --- a/zig/src/families/flashnext/hip/head.zig +++ b/zig/src/families/flashnext/hip/head.zig @@ -24,16 +24,14 @@ pub fn caches( return cache.Caches.init(gpa, d, h.dims, &.{false}, cap, act, eos); } -/// `tokens` (each the token after its row) over `streams` from `pos`; `prompt`: a prompt chunk's rows on prompt tiles. +/// `segs`' tokens (the token after each row) over `streams`, segments in order; `prompt`: rows on prompt tiles. pub fn run( ops: Ops, prompt: bool, m: *const model.Model, host: *forward.Host, - c: *cache.Caches, + segs: []const forward.Seg, streams: Tensor, - tokens: []const u32, - pos: usize, ones: hip.DeviceBuffer, ) !Out { var o = ops; @@ -41,16 +39,22 @@ pub fn run( o.prefill = prompt; const w = &m.mtp.?; const d = w.dims; - const rows = tokens.len; + var rows: usize = 0; + for (segs) |g| rows += g.tokens.len; if (rows * d.streams * m.act.size() > ones.len) return error.HeadRowsPastOnes; const ids = try host.gpa.alloc(i32, rows); defer host.gpa.free(ids); const at_pos = try host.gpa.alloc(i32, rows); defer host.gpa.free(at_pos); - for (ids, at_pos, tokens, 0..) |*i, *p, t, r| { - if (t >= d.vocab) return error.InvalidToken; // embed reads the table at id unchecked - i.* = @intCast(t); - p.* = @intCast(pos + r); + var at: usize = 0; + for (segs) |g| { + for (g.tokens, 0..) |t, r| { + if (t >= d.vocab) return error.InvalidToken; // embed reads the table at id unchecked + ids[at + r] = @intCast(t); + at_pos[at + r] = @intCast(g.pos + r); + } + g.c.pooled = @min(g.c.pooled, g.pos / d.index_ratio); + at += g.tokens.len; } const dev_ids = try host.put(o, std.mem.sliceAsBytes(ids)); const dev_pos = try host.put(o, std.mem.sliceAsBytes(at_pos)); @@ -79,20 +83,18 @@ pub fn run( try forward.hcNorm(o, m, h, e, .{ .ptr = ones.base(), .kind = m.act }, x, l.ahc.scale, rows); const inject = try take(o, m.act, rows * d.streams); const mixed = try forward.hcPre(o, m, l.ahc, x, rows, inject); - const seg = [_]forward.Seg{.{ .c = c, .tokens = tokens, .pos = pos }}; - c.pooled = @min(c.pooled, pos / d.index_ratio); - const branch = try mixers.sparse(o, m, d, l.mixer.sparse, &seg, 0, mixed, rows, dev_pos, host, null); + const branch = try mixers.sparse(o, m, d, l.mixer.sparse, segs, 0, mixed, rows, dev_pos, host, null); try forward.hcNorm(o, m, h, branch, inject, x, l.mhc.scale, rows); const mixed2 = try forward.hcPre(o, m, l.mhc, x, rows, inject); const y = try hip.moe.run(o, m.act, l.moe, mixed2, rows, prompt); try forward.hcNorm(o, m, h, y, inject, x, w.mix.scale, rows); - c.pooled = (pos + rows) / d.index_ratio; + for (segs) |g| g.c.pooled = (g.pos + g.tokens.len) / d.index_ratio; return .{ .mixed = try forward.hcPre(o, m, w.mix, x, rows, null), .streams = h }; } /// The draft head's greedy token for each of `rows` mixed rows (argmax over the draft vocabulary) and its probability. pub fn draws( - o: Ops, + ops: Ops, m: *const model.Model, host: *forward.Host, s: hip.Stream, @@ -102,6 +104,8 @@ pub fn draws( out: []u32, probs: []f32, ) !void { + var o = ops; + o.window = true; const w = &m.mtp.?; const logits = try o.project(mixed, w.draft, rows, false); const arg = try o.arena.of(i32, 2 * rows); diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 1a807fe3ef3..0980ac58ae5 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -7,6 +7,7 @@ const Engine = @import("engine.zig").Engine; const cache = @import("cache.zig"); const forward = @import("forward.zig"); const head_mod = @import("head.zig"); +const draft_batch = @import("draft_batch.zig"); const load = @import("load.zig"); const worker = @import("worker.zig"); const snapshot = @import("snapshot.zig"); @@ -513,73 +514,7 @@ pub const Fx = struct { /// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { - const f = of(ptr); - const e = f.e; - const m = &e.weights.model; - const row_bytes = m.dims.wide() * m.act.size(); - for (requests) |r| { - const lane = f.lanes.get(r.stream) orelse return error.UnknownStream; - if (lane.pending) |p| try f.mark(lane, if (r.rows) |kept| kept.len else p.rows); - lane.held_n = 0; - if (r.position != lane.caches.len + 1) return error.PositionMismatch; - const hc = if (lane.head) |*h| h else continue; - const token: u32 = if (r.rows != null) - r.follow[r.follow.len - 1] - else switch (r.first orelse return error.NoFirstToken) { - .handle => |at| f.drawn[at % ring], - .value => |v| v, - }; - var follow_buf: [cache.max_window]u32 = undefined; - const follow: []const u32 = if (r.rows != null) r.follow else blk: { - follow_buf[0] = token; - break :blk follow_buf[0..1]; - }; - const start = lane.caches.len - follow.len; - try e.stream.synchronize(); - e.host.used = 0; - e.arena.reset(); - const o = e.ops(&e.arena); - var out = try head_mod.run( - o, - false, - m, - &e.host, - hc, - .{ .ptr = lane.streams.base(), .kind = m.act }, - follow, - start, - f.ones, - ); - var mixed = forward.at(out.mixed, (follow.len - 1) * m.dims.hidden); - var streams = out.streams.ptr + (follow.len - 1) * row_bytes; - const depth = @min(r.depth, max_depth); - // a chain past the first round ends after a draft the head gives under the confidence (--mtp-confidence) - const stop_under: f32 = if (r.rows != null) @floatCast(e.o.policy.mtp.confidence) else 0.0; - var d: usize = 0; - var chained: usize = 0; - while (d < depth) : (d += 1) { - var tok: [1]u32 = undefined; - var prob: [1]f32 = undefined; - try head_mod.draws(o, m, &e.host, e.stream, mixed, 1, f.draft_ids, &tok, &prob); - lane.held[d] = tok[0]; - chained = d + 1; - if (d + 1 == depth or prob[0] < stop_under) break; - out = try head_mod.run( - o, - false, - m, - &e.host, - hc, - .{ .ptr = streams, .kind = m.act }, - &tok, - lane.caches.len + d, - f.ones, - ); - mixed = out.mixed; - streams = out.streams.ptr; - } - lane.held_n = chained; - } + try draft_batch.draft(of(ptr), requests); } fn heldFn(ptr: *anyopaque, s: *lanes.Stream, _: std.mem.Allocator) anyerror!?lanes.stream.Held { From 5e3a6b6dd931c784d7d554ac75f0b1edb87543be Mon Sep 17 00:00:00 2001 From: gilby Date: Mon, 9 Nov 2026 17:07:46 +0100 Subject: [PATCH 14/59] flashnext hip: a shared round's streams draft in one head pass a step --- CHANGELOG.md | 1 + .../families/flashnext/hip/draft_batch.zig | 211 ++++++++++++++++-- zig/src/families/flashnext/hip/head.zig | 2 +- zig/src/families/flashnext/hip/lanes.zig | 23 +- 4 files changed, 198 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 092b98e2f11..f3224996a9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,6 +184,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - GLM-5.3-Flash on CUDA: `TF_GLM_CONTEXT_CEILING` (opt-in) lets GLM open windows past 1,048,576 tokens, read once when the model opens; with it unset nothing changes, and cold prompts and decode on two and three GB10s read level with main (#2765, refs #2663). Thanks to @Bizuayeu. - Metal on M5: prompt lane projections at every width (8-, 6-, 5-, 3- and 2-bit and the oQ mixes) take a chunk's 16-row blocks in one dispatch, as 4-bit already did; Qwen3.8-27B MLX 8-bit cold prompts are about 33% faster on an M5 Ultra (769 to 1,029 tok/s at 2K, 769 to 1,027 at 8K) with identical tokens, and decode is unchanged (#2851, for #2818). +- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged. - GLM-5.3-Flash: the DFlash2 drafter's startup line and docs give its licence as Apache-2.0, as its model card now says (#3084, for #1583). diff --git a/zig/src/families/flashnext/hip/draft_batch.zig b/zig/src/families/flashnext/hip/draft_batch.zig index 03651fdf8b5..cd260e550f6 100644 --- a/zig/src/families/flashnext/hip/draft_batch.zig +++ b/zig/src/families/flashnext/hip/draft_batch.zig @@ -1,5 +1,6 @@ -//! The draft head's absorb-and-chain step over a shared round's lanes. +//! The draft head's absorb-and-chain step over a shared round's lanes: serial, or one batched head pass a step. const std = @import("std"); +const hip = @import("hip"); const cache = @import("cache.zig"); const forward = @import("forward.zig"); const head_mod = @import("head.zig"); @@ -9,8 +10,26 @@ const be = @import("lanes").backend; const Fx = lanes_mod.Fx; const Lane = lanes_mod.Lane; +/// A stream drafting in a batched call: its lane, head caches, chain depth and its rows in the packed absorb. +const Slot = struct { + lane: *Lane, + hc: *cache.Caches, + depth: usize, + stop_under: f32, + tok: [1]u32 = undefined, + row_at: usize = 0, + row_n: usize = 0, + chained: usize = 0, +}; + /// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. pub fn draft(f: *Fx, requests: []const be.DraftRequest) anyerror!void { + if (requests.len > 1) return batched(f, requests); + return serial(f, requests); +} + +/// The serial path: a stream at a time, one head forward and one draw a step. +fn serial(f: *Fx, requests: []const be.DraftRequest) anyerror!void { const e = f.e; const m = &e.weights.model; const row_bytes = m.dims.wide() * m.act.size(); @@ -36,17 +55,8 @@ pub fn draft(f: *Fx, requests: []const be.DraftRequest) anyerror!void { e.host.used = 0; e.arena.reset(); const o = e.ops(&e.arena); - var out = try head_mod.run( - o, - false, - m, - &e.host, - hc, - .{ .ptr = lane.streams.base(), .kind = m.act }, - follow, - start, - f.ones, - ); + const seg = [_]forward.Seg{.{ .c = hc, .tokens = follow, .pos = start }}; + var out = try head_mod.run(o, false, m, &e.host, &seg, .{ .ptr = lane.streams.base(), .kind = m.act }, f.ones); var mixed = forward.at(out.mixed, (follow.len - 1) * m.dims.hidden); var streams = out.streams.ptr + (follow.len - 1) * row_bytes; const depth = @min(r.depth, lanes_mod.max_depth); @@ -61,20 +71,175 @@ pub fn draft(f: *Fx, requests: []const be.DraftRequest) anyerror!void { lane.held[d] = tok[0]; chained = d + 1; if (d + 1 == depth or prob[0] < stop_under) break; - out = try head_mod.run( - o, - false, - m, - &e.host, - hc, - .{ .ptr = streams, .kind = m.act }, - &tok, - lane.caches.len + d, - f.ones, - ); + const step = [_]forward.Seg{.{ .c = hc, .tokens = &tok, .pos = lane.caches.len + d }}; + out = try head_mod.run(o, false, m, &e.host, &step, .{ .ptr = streams, .kind = m.act }, f.ones); mixed = out.mixed; streams = out.streams.ptr; } lane.held_n = chained; } } + +/// The batched path: a packed absorb forward and one draw over every stream, then one head pass a step. +fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { + const e = f.e; + const m = &e.weights.model; + const d = m.dims; + const row_bytes = d.wide() * m.act.size(); + const hidden_bytes = d.hidden * m.act.size(); + if (requests.len > forward.max_segs) return error.TooManyStreams; + // the staging is reused across streams: the last forward's uploads must have left it + try e.stream.synchronize(); + e.host.used = 0; + e.arena.reset(); + const o = e.ops(&e.arena); + var slots: [forward.max_segs]Slot = undefined; + var segs: [forward.max_segs]forward.Seg = undefined; + var firsts: [forward.max_segs][1]u32 = undefined; + var n: usize = 0; + var rows: usize = 0; + for (requests) |r| { + const lane = f.lanes.get(r.stream) orelse return error.UnknownStream; + if (lane.pending) |p| try f.mark(lane, if (r.rows) |kept| kept.len else p.rows); + lane.held_n = 0; + if (r.position != lane.caches.len + 1) return error.PositionMismatch; + const hc = if (lane.head) |*h| h else continue; + const token: u32 = if (r.rows != null) + r.follow[r.follow.len - 1] + else switch (r.first orelse return error.NoFirstToken) { + .handle => |at| f.drawn[at % lanes_mod.ring], + .value => |v| v, + }; + const follow: []const u32 = if (r.rows != null) r.follow else blk: { + firsts[n][0] = token; + break :blk firsts[n][0..1]; + }; + slots[n] = .{ + .lane = lane, + .hc = hc, + .depth = @min(r.depth, lanes_mod.max_depth), + // a chain past the first round ends after a draft the head gives under the confidence (--mtp-confidence) + .stop_under = if (r.rows != null) @floatCast(e.o.policy.mtp.confidence) else 0.0, + .row_at = rows, + .row_n = follow.len, + }; + segs[n] = .{ .c = hc, .tokens = follow, .pos = lane.caches.len - follow.len }; + rows += follow.len; + n += 1; + } + if (n == 0) return; + // the kept residual rows of every stream packed one contiguous batch for the head's single forward + const packed_rows = try e.arena.take(rows * row_bytes); + for (slots[0..n]) |*s| { + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync( + @ptrFromInt(packed_rows + s.row_at * row_bytes), + @ptrFromInt(s.lane.streams.base()), + s.row_n * row_bytes, + e.stream.handle, + )); + } + const out = try head_mod.run(o, false, m, &e.host, segs[0..n], .{ .ptr = packed_rows, .kind = m.act }, f.ones); + var active: [forward.max_segs]usize = undefined; + var active_n: usize = 0; + for (slots[0..n], 0..) |*s, i| if (s.depth > 0) { + active[active_n] = i; + active_n += 1; + }; + if (active_n == 0) return; + // each stream chains from its last absorbed row: its mixed row gathered, its residual row kept in its lane + const mixed_rows = try e.arena.take(n * hidden_bytes); + for (slots[0..n], 0..) |*s, i| { + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync( + @ptrFromInt(mixed_rows + i * hidden_bytes), + @ptrFromInt(out.mixed.ptr + (s.row_at + s.row_n - 1) * hidden_bytes), + hidden_bytes, + e.stream.handle, + )); + if (s.depth > 0) try hip.raw.copy( + s.lane.streams, + 0, + out.streams.ptr + (s.row_at + s.row_n - 1) * row_bytes, + row_bytes, + e.stream.handle, + ); + } + var toks: [forward.max_segs]u32 = undefined; + var probs: [forward.max_segs]f32 = undefined; + try head_mod.draws( + o, + m, + &e.host, + e.stream, + .{ .ptr = mixed_rows, .kind = m.act }, + n, + f.draft_ids, + toks[0..n], + probs[0..n], + ); + var next: usize = 0; + for (active[0..active_n]) |si| { + const s = &slots[si]; + s.lane.held[0] = toks[si]; + s.chained = 1; + if (1 < s.depth and !(probs[si] < s.stop_under)) { + active[next] = si; + next += 1; + } + } + active_n = next; + var step: usize = 1; + while (active_n > 0) : (step += 1) { + const step_rows = try e.arena.take(active_n * row_bytes); + var step_segs: [forward.max_segs]forward.Seg = undefined; + for (active[0..active_n], 0..) |si, a| { + const s = &slots[si]; + s.tok[0] = s.lane.held[step - 1]; + step_segs[a] = .{ .c = s.hc, .tokens = &s.tok, .pos = s.lane.caches.len + step - 1 }; + try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync( + @ptrFromInt(step_rows + a * row_bytes), + @ptrFromInt(s.lane.streams.base()), + row_bytes, + e.stream.handle, + )); + } + const step_out = try head_mod.run( + o, + false, + m, + &e.host, + step_segs[0..active_n], + .{ .ptr = step_rows, .kind = m.act }, + f.ones, + ); + try head_mod.draws( + o, + m, + &e.host, + e.stream, + step_out.mixed, + active_n, + f.draft_ids, + toks[0..active_n], + probs[0..active_n], + ); + for (active[0..active_n], 0..) |si, a| try hip.raw.copy( + slots[si].lane.streams, + 0, + step_out.streams.ptr + a * row_bytes, + row_bytes, + e.stream.handle, + ); + next = 0; + for (active[0..active_n], 0..) |si, a| { + const s = &slots[si]; + s.lane.held[step] = toks[a]; + s.chained = step + 1; + if (step + 1 < s.depth and !(probs[a] < s.stop_under)) { + active[next] = si; + next += 1; + } + } + active_n = next; + } + for (slots[0..n]) |*s| s.lane.held_n = s.chained; +} diff --git a/zig/src/families/flashnext/hip/head.zig b/zig/src/families/flashnext/hip/head.zig index 0774e002a5d..c2a55d0f616 100644 --- a/zig/src/families/flashnext/hip/head.zig +++ b/zig/src/families/flashnext/hip/head.zig @@ -24,7 +24,7 @@ pub fn caches( return cache.Caches.init(gpa, d, h.dims, &.{false}, cap, act, eos); } -/// `segs`' tokens (the token after each row) over `streams`, segments in order; `prompt`: rows on prompt tiles. +/// `segs`' tokens over `streams` (a row each) from each segment's `pos`; `prompt`: rows on prompt tiles. pub fn run( ops: Ops, prompt: bool, diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig index 0980ac58ae5..8c84d8f2aec 100644 --- a/zig/src/families/flashnext/hip/lanes.zig +++ b/zig/src/families/flashnext/hip/lanes.zig @@ -17,7 +17,7 @@ const be = lanes.backend; const draw = serve.draw; /// Drawn tokens a handle names, newest last. -const ring = 1024; +pub const ring = 1024; /// Drafts the head holds for a stream at most. pub const max_depth = cache.max_window - 1; @@ -71,7 +71,7 @@ pub const Fx = struct { pub fn init(gpa: std.mem.Allocator, e: *Engine, streams: usize) !*Fx { const f = try gpa.create(Fx); errdefer gpa.destroy(f); - const n = @max(e.o.chunk, cache.max_window) * e.cfg.hc_count; + const n = @max(e.o.chunk, cache.max_window * streams) * e.cfg.hc_count; const one: u16 = if (e.act == .f16) 0x3c00 else 0x3f80; const host = try gpa.alloc(u16, n); defer gpa.free(host); @@ -217,7 +217,7 @@ pub const Fx = struct { .hidden_rows = true, .batch_rows = @intCast(cache.max_window * f.streams), .max_streams = @intCast(f.streams), - .draft_streams = false, + .draft_streams = drafting, }; } @@ -251,7 +251,7 @@ pub const Fx = struct { } /// The pending window's first `rows` rows kept; the other ranks keep the same. - fn mark(f: *Fx, lane: *Lane, rows: usize) !void { + pub fn mark(f: *Fx, lane: *Lane, rows: usize) !void { const p = lane.pending orelse return; if (f.link != null) try f.send(&.{ @backingInt(worker.Op.keep), lane.id, @intCast(rows), @intCast(p.rows) }); try f.e.keepWindow(&lane.caches, p.tokens[0..p.rows], rows); @@ -356,17 +356,10 @@ pub const Fx = struct { if (lane.head) |*hc| { // the head's keys for every prompt row with a next token (the last waits for the first draw) const n = if (last) rows - 1 else rows; - if (n > 0) _ = try head_mod.run( - e.ops(&e.arena), - true, - m, - &e.host, - hc, - out.streams, - prompt[at + 1 ..][0..n], - at, - f.ones, - ); + if (n > 0) { + const seg = [_]forward.Seg{.{ .c = hc, .tokens = prompt[at + 1 ..][0..n], .pos = at }}; + _ = try head_mod.run(e.ops(&e.arena), true, m, &e.host, &seg, out.streams, f.ones); + } } fill.at = to; if (fill.next < fill.count and to == fill.stops[fill.next]) { From 95af4ee8b252d895cb0c12b546165babd91d4d33 Mon Sep 17 00:00:00 2001 From: gilby Date: Thu, 12 Nov 2026 08:38:25 +0100 Subject: [PATCH 15/59] flashnext hip: the draft step draws on the stream's tile, a serial and a batched draft --- zig/src/families/flashnext/hip/draft_batch.zig | 4 +++- zig/src/families/flashnext/hip/engine.zig | 3 ++- zig/src/families/flashnext/hip/head.zig | 5 +++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/zig/src/families/flashnext/hip/draft_batch.zig b/zig/src/families/flashnext/hip/draft_batch.zig index cd260e550f6..e1d158ab7f2 100644 --- a/zig/src/families/flashnext/hip/draft_batch.zig +++ b/zig/src/families/flashnext/hip/draft_batch.zig @@ -67,7 +67,7 @@ fn serial(f: *Fx, requests: []const be.DraftRequest) anyerror!void { while (d < depth) : (d += 1) { var tok: [1]u32 = undefined; var prob: [1]f32 = undefined; - try head_mod.draws(o, m, &e.host, e.stream, mixed, 1, f.draft_ids, &tok, &prob); + try head_mod.draws(o, m, &e.host, e.stream, mixed, 1, f.draft_ids, &tok, &prob, false); lane.held[d] = tok[0]; chained = d + 1; if (d + 1 == depth or prob[0] < stop_under) break; @@ -175,6 +175,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { f.draft_ids, toks[0..n], probs[0..n], + true, ); var next: usize = 0; for (active[0..active_n]) |si| { @@ -221,6 +222,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { f.draft_ids, toks[0..active_n], probs[0..active_n], + true, ); for (active[0..active_n], 0..) |si, a| try hip.raw.copy( slots[si].lane.streams, diff --git a/zig/src/families/flashnext/hip/engine.zig b/zig/src/families/flashnext/hip/engine.zig index 4649fca4e00..e36b0924a28 100644 --- a/zig/src/families/flashnext/hip/engine.zig +++ b/zig/src/families/flashnext/hip/engine.zig @@ -327,7 +327,8 @@ pub const Engine = struct { defer hc.deinit(e.gpa); var ones = try hip.DeviceBuffer.alloc(&e.driver, rows * e.cfg.hc_count * e.act.size()); defer ones.free(); - _ = try head_mod.run(o, true, &e.weights.model, &e.host, &hc, out.streams, tokens, pos, ones); + const hsegs = [_]forward.Seg{.{ .c = &hc, .tokens = tokens, .pos = pos }}; + _ = try head_mod.run(o, true, &e.weights.model, &e.host, &hsegs, out.streams, ones); } _ = try e.logits(o, out.mixed, verify_rows); // the peak, not what is left at the end: each layer hands its scratch back when it is done diff --git a/zig/src/families/flashnext/hip/head.zig b/zig/src/families/flashnext/hip/head.zig index c2a55d0f616..d53e6a910b2 100644 --- a/zig/src/families/flashnext/hip/head.zig +++ b/zig/src/families/flashnext/hip/head.zig @@ -92,7 +92,7 @@ pub fn run( return .{ .mixed = try forward.hcPre(o, m, w.mix, x, rows, null), .streams = h }; } -/// The draft head's greedy token for each of `rows` mixed rows (argmax over the draft vocabulary) and its probability. +/// Each of `rows` mixed rows' greedy draft token and its probability; `window` on a shared round's rows, else a prompt's. pub fn draws( ops: Ops, m: *const model.Model, @@ -103,9 +103,10 @@ pub fn draws( ids: []const u32, out: []u32, probs: []f32, + window: bool, ) !void { var o = ops; - o.window = true; + o.window = window; const w = &m.mtp.?; const logits = try o.project(mixed, w.draft, rows, false); const arg = try o.arena.of(i32, 2 * rows); From 44cd2bae5f744869373632f5e78f927fb73061a4 Mon Sep 17 00:00:00 2001 From: gilby Date: Thu, 12 Nov 2026 08:38:25 +0100 Subject: [PATCH 16/59] flashnext hip: a GPU check runs two streams' drafts in one head pass against one at a time --- zig/build/flashnext_gpu.zig | 22 +++ zig/build/hip.zig | 4 +- .../flashnext/hip/draft_batch_test.zig | 168 ++++++++++++++++++ 3 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 zig/build/flashnext_gpu.zig create mode 100644 zig/src/families/flashnext/hip/draft_batch_test.zig diff --git a/zig/build/flashnext_gpu.zig b/zig/build/flashnext_gpu.zig new file mode 100644 index 00000000000..1bb1eaa7aeb --- /dev/null +++ b/zig/build/flashnext_gpu.zig @@ -0,0 +1,22 @@ +//! The Flash Next HIP GPU checks beside the model-free kernels in `hip-kernel-test`: no model server runs here. +const std = @import("std"); +const hydrox = @import("hip.zig"); + +/// The draft batch's check: two streams' drafts in one head pass against the same two one stream at a time. +pub fn draftBatch(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, gpu: hydrox.Engine, kernel_test_step: *std.Build.Step) void { + const draft_gpu = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/flashnext/hip/draft_batch_test.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "hip", .module = gpu.hip }, + .{ .name = "lanes", .module = gpu.lanes }, + .{ .name = "flashnext", .module = gpu.flashnext }, + }, + }) }); + const draft_run = b.addRunArtifact(draft_gpu); + draft_run.has_side_effects = true; // the checkpoint the test's env var names is not a cached input + b.step("draft-batch-gpu-build", "Compile the draft batch's GPU checks without running them").dependOn(&draft_gpu.step); + kernel_test_step.dependOn(&draft_run.step); +} diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 88c0f6fb363..b630b596d45 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -128,7 +128,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil @import("flashnext_reach.zig").wire(b, target, kernel_module, coreModule(b, target)); const kernel_test = b.addTest(.{ .root_module = kernel_module }); b.step("hip-kernel-build", "Compile the model-free kernels and their GPU tests without running them").dependOn(&kernel_test.step); - b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU").dependOn(&b.addRunArtifact(kernel_test).step); + const kernel_test_step = b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU"); + kernel_test_step.dependOn(&b.addRunArtifact(kernel_test).step); const tune_module = b.createModule(.{ .root_source_file = b.path("zig/src/hip/affine_tune.zig"), .target = target, .link_libc = true }); tune_module.addIncludePath(.{ .cwd_relative = hip_include }); tune_module.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); @@ -222,6 +223,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil qwen3_run.has_side_effects = true; // the checkpoints and oracle files named by TF_QWEN3_* are not cached inputs b.step("qwen3-hip-gpu-build", "Compile the Qwen3 dense GPU checks without running them").dependOn(&qwen3_gpu.step); b.step("qwen3-hip-gpu-test", "Qwen3 lastRows on the GPU against transformers (TF_QWEN3_EMBED_*, TF_QWEN3_RERANK_*)").dependOn(&qwen3_run.step); + @import("flashnext_gpu.zig").draftBatch(b, target, optimize, gpu, kernel_test_step); const parse_object = compile(b, .{ .name = hipcc, .resolved = hipcc_resolved, .device_lib = device_lib }, hip_arch, b.path("zig/kernels/hip/ops/vision.hip"), "parse-vision.hsaco"); @import("nemotron_parse_gpu.zig").gpuTests(b, target, host.hip, parse_object); @import("nemotron_parse_gpu.zig").modelTests(b, target, optimize, gpu.hip); diff --git a/zig/src/families/flashnext/hip/draft_batch_test.zig b/zig/src/families/flashnext/hip/draft_batch_test.zig new file mode 100644 index 00000000000..bb8218a3e3d --- /dev/null +++ b/zig/src/families/flashnext/hip/draft_batch_test.zig @@ -0,0 +1,168 @@ +//! Two streams drafting in one head pass a step against the same two drafting one at a time: caches, drafts, pooled. +const std = @import("std"); +const hip = @import("hip"); +const lanes = @import("lanes"); +const fx = @import("flashnext"); + +/// No per-thread alternate signal stack: its thread-local leaves HIP's threads too little stack to start. +pub const std_options: std.Options = .{ .signal_stack_size = null }; + +const t = std.testing; +const be = lanes.backend; + +/// Two short prompts of ordinary English ids: both are in any vocabulary, and they differ row for row. +const text = "372 13369 198 220 17 13 13258 19 3266 310 264 1283 12068 1794\n" ++ + "290 16147 11 11358 22986\n"; +/// A prompt token must be in the head's draft vocabulary (`draft_ids` here is every id below 248320). +const draft_vocab = 248320; + +fn env(a: std.mem.Allocator, key: []const u8, max: usize) !?[]u8 { + const v = t.environ.getAlloc(a, key) catch |err| switch (err) { + error.EnvironmentVariableMissing => return null, + else => return err, + }; + if (v.len > max) return error.EnvTooLong; + return v; +} + +/// Two prompts, each line blank-space separated ids (blank lines skipped); past the draft vocabulary is refused. +fn prompts(a: std.mem.Allocator, source: []const u8) ![2][]const u32 { + var out: [2][]const u32 = undefined; + var line = std.mem.splitScalar(u8, source, '\n'); + for (&out) |*p| { + const one = while (line.next()) |l| if (l.len > 0) break l else continue else return error.TwoPrompts; + var tokens: std.ArrayList(u32) = .empty; + var words = std.mem.tokenizeAny(u8, one, " \t\r"); + while (words.next()) |w| { + const tok = try std.fmt.parseInt(u32, w, 10); + if (tok >= draft_vocab) return error.PromptPastDraftVocab; + try tokens.append(a, tok); + } + if (tokens.items.len == 0) return error.EmptyPrompt; + p.* = try tokens.toOwnedSlice(a); + } + return out; +} + +/// The engine of TF_RV2696_DIR and its lane backend. +const Fixture = struct { + e: *fx.engine.Engine, + f: *fx.lanes.Fx, + b: be.Backend, + + /// `matrix=off`: the head layer's keys stay in a panel's cache that a 4 GiB aperture can hold. + fn init(gpa: std.mem.Allocator, dir: []const u8) !Fixture { + var notes: hip.Policy.Notes = .{}; + var policy = try hip.Policy.resolve("graphs=off,prefill_step=64,fill_rows=64", .none, ¬es); + policy.matrix = .off; + // no confidence cut: both paths chain their three steps, so the step's rows are compared too + policy.mtp.confidence = 0; + const main = try fx.engine.Engine.open(gpa, t.io, dir, .{ .policy = policy, .capacity = 1024, .chunk = 64, .want = 4 }); + errdefer main.deinit(); + if (main.weights.model.mtp == null) return error.NoMtpHead; + const f = try fx.lanes.Fx.init(gpa, main, 4); + errdefer f.deinit(); + if (f.drafts == 0) return error.NoDrafts; // a draft vocabulary the head step draws from + return .{ .e = main, .f = f, .b = fx.lanes.Fx.backend(f) }; + } + + fn deinit(x: *Fixture) void { + x.f.deinit(); + x.e.deinit(); + } + + fn lane(x: *Fixture, s: *lanes.stream.Stream) *fx.lanes.Lane { + return x.f.lanes.get(s).?; + } + + /// The prompt pass and the first token after it. + fn start(x: *Fixture, s: *lanes.stream.Stream) !u32 { + try x.b.prefill(s); + return x.b.read(try x.b.first(s, s.prompt_len)); + } + + /// A window of the prompt's first token, two host drafts and a keep of two rows: the rows a draft absorbs. + fn window(x: *Fixture, s: *lanes.stream.Stream, first: u32, drafts: [2]u32) ![3]u32 { + const positions = [3]u64{ s.prompt_len + 1, s.prompt_len + 2, s.prompt_len + 3 }; + const w = [_]be.Window{.{ .stream = s, .pending = first, .held = 0, .tokens = &drafts, .parents = null, .positions = &positions }}; + var sampled: [3]u32 = undefined; + var echo: [3]u32 = undefined; + var out = [_]be.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try x.b.verify(&w, &out); + try x.b.keep(&w, &.{&.{ 0, 1 }}); + return sampled; + } +}; + +/// The kept rows a stream's draft absorbs, in the window's order. +const kept_rows = [_]u32{ 0, 1 }; + +/// A stream's draft request after its window: the two kept rows' tokens (a named slice), `depth` drafts. +fn request(s: *lanes.stream.Stream, follow: []const u32, depth: u32) be.DraftRequest { + return .{ + .stream = s, + .follow = follow, + .rows = &kept_rows, + .start = s.prompt_len, + .position = s.prompt_len + 3, + .depth = @min(depth, fx.lanes.max_depth), + }; +} + +/// A draft's outcome for one stream: its held drafts, its head cache's rows and its pooled count. +const State = struct { + held: []u32, + pooled: usize, + mem: []u8, + + fn capture(a: std.mem.Allocator, x: *Fixture, s: *lanes.stream.Stream) !State { + const lane = x.lane(s); + const head = &lane.head.?; + const held = try a.alloc(u32, lane.held_n); + try x.b.vtable.held.?(x.b.ptr, s, held); + try x.e.stream.synchronize(); + const mem = try a.alloc(u8, head.layout.stateBytes(head.len)); + try head.mem.download(0, mem); + return .{ .held = held, .pooled = head.pooled, .mem = mem }; + } +}; + +test "two streams draft in one head pass a step as they do one stream at a time" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const dir = try env(a, "TF_RV2696_DIR", 4096) orelse return error.SkipZigTest; + const ps = try prompts(a, (try env(a, "TF_RV2696_PROMPTS", 1 << 16)) orelse text); + var x = try Fixture.init(a, dir); + defer x.deinit(); + // four streams: two draft in one call, and the same two prompts again, each drafted alone + var streams: [4]lanes.stream.Stream = undefined; + defer for (&streams) |*s| s.deinit(a); + for (&streams, [_][]const u32{ ps[0], ps[1], ps[0], ps[1] }) |*s, p| s.* = try lanes.stream.Stream.init(a, .{ .id = "draft-batch", .prompt = p, .max_new = 16 }); + var firsts: [4]u32 = undefined; + var sampled: [4][3]u32 = undefined; + for (&streams, &firsts, &sampled, [_][2]u32{ .{ 11, 12 }, .{ 21, 22 }, .{ 11, 12 }, .{ 21, 22 } }) |*s, *first, *sam, drafts| { + first.* = try x.start(s); + sam.* = try x.window(s, first.*, drafts); + } + const depth = @min(3, x.f.drafts); + try t.expect(depth > 0); + var follows: [4][2]u32 = undefined; + for (&follows, firsts, sampled) |*f, first, sam| f.* = .{ first, sam[1] }; + try x.b.draft(&[2]be.DraftRequest{ request(&streams[0], &follows[0], depth), request(&streams[1], &follows[1], depth) }); + var alone: [1]be.DraftRequest = undefined; + for (streams[2..], follows[2..]) |*s, *follow| { + alone[0] = request(s, follow, depth); + try x.b.draft(&alone); + } + // each head cache's kept rows and pooled count, and the drafts: the batch's as the alone drafts' + for (streams[0..2], streams[2..]) |*batched, *lone| { + const one = try State.capture(a, &x, batched); + const two = try State.capture(a, &x, lone); + try t.expectEqual(depth, one.held.len); // the confidence is 0: both paths chain every step + try t.expect(one.pooled > 0); // the pooled block both paths' last rows fill is inside the compared rows + try t.expectEqual(one.pooled, two.pooled); + try t.expectEqualSlices(u32, one.held, two.held); + try t.expectEqualSlices(u8, one.mem, two.mem); + } +} From 803d11030706cd24f1a6d84e3539687e90605d86 Mon Sep 17 00:00:00 2001 From: gilby Date: Thu, 12 Nov 2026 08:38:25 +0100 Subject: [PATCH 17/59] changelog: the draft batch's line ends with its number and the thanks --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3224996a9b..dee5e8ca1d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -185,6 +185,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Metal on M5: prompt lane projections at every width (8-, 6-, 5-, 3- and 2-bit and the oQ mixes) take a chunk's 16-row blocks in one dispatch, as 4-bit already did; Qwen3.8-27B MLX 8-bit cold prompts are about 33% faster on an M5 Ultra (769 to 1,029 tok/s at 2K, 769 to 1,027 at 8K) with identical tokens, and decode is unchanged (#2851, for #2818). - Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged. +- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged (#2696). Thanks to @gilby. - GLM-5.3-Flash: the DFlash2 drafter's startup line and docs give its licence as Apache-2.0, as its model card now says (#3084, for #1583). From b390a67952c79ef25c1d69bd4dafbcd08b2da250 Mon Sep 17 00:00:00 2001 From: gilby Date: Thu, 12 Nov 2026 09:25:52 +0100 Subject: [PATCH 18/59] flashnext hip: the batched draft keeps each stream's chain row in the arena, and the GPU check's variables are named for the family --- zig/build/flashnext_gpu.zig | 8 +++---- zig/build/hip.zig | 5 ++-- .../families/flashnext/hip/draft_batch.zig | 23 +++++-------------- .../flashnext/hip/draft_batch_test.zig | 6 ++--- zig/src/families/flashnext/hip/head.zig | 2 +- 5 files changed, 16 insertions(+), 28 deletions(-) diff --git a/zig/build/flashnext_gpu.zig b/zig/build/flashnext_gpu.zig index 1bb1eaa7aeb..51be2280440 100644 --- a/zig/build/flashnext_gpu.zig +++ b/zig/build/flashnext_gpu.zig @@ -3,7 +3,7 @@ const std = @import("std"); const hydrox = @import("hip.zig"); /// The draft batch's check: two streams' drafts in one head pass against the same two one stream at a time. -pub fn draftBatch(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, gpu: hydrox.Engine, kernel_test_step: *std.Build.Step) void { +pub fn draftBatch(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, gpu: hydrox.Engine) void { const draft_gpu = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/flashnext/hip/draft_batch_test.zig"), .target = target, @@ -16,7 +16,7 @@ pub fn draftBatch(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std }, }) }); const draft_run = b.addRunArtifact(draft_gpu); - draft_run.has_side_effects = true; // the checkpoint the test's env var names is not a cached input - b.step("draft-batch-gpu-build", "Compile the draft batch's GPU checks without running them").dependOn(&draft_gpu.step); - kernel_test_step.dependOn(&draft_run.step); + draft_run.has_side_effects = true; // the checkpoint TF_FLASHNEXT_DIR names is not a cached input + b.step("draft-batch-gpu-build", "Compile the draft batch's GPU checks (TF_FLASHNEXT_DIR, TF_FLASHNEXT_PROMPTS)").dependOn(&draft_gpu.step); + b.top_level_steps.get("hip-kernel-test").?.step.dependOn(&draft_run.step); } diff --git a/zig/build/hip.zig b/zig/build/hip.zig index b630b596d45..7d0da890b63 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -128,8 +128,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil @import("flashnext_reach.zig").wire(b, target, kernel_module, coreModule(b, target)); const kernel_test = b.addTest(.{ .root_module = kernel_module }); b.step("hip-kernel-build", "Compile the model-free kernels and their GPU tests without running them").dependOn(&kernel_test.step); - const kernel_test_step = b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU"); - kernel_test_step.dependOn(&b.addRunArtifact(kernel_test).step); + b.step("hip-kernel-test", "Every model-free kernel against its host reference on the GPU").dependOn(&b.addRunArtifact(kernel_test).step); const tune_module = b.createModule(.{ .root_source_file = b.path("zig/src/hip/affine_tune.zig"), .target = target, .link_libc = true }); tune_module.addIncludePath(.{ .cwd_relative = hip_include }); tune_module.addCSourceFile(.{ .file = b.path("zig/src/hip/device_arch.c"), .flags = &.{"-D__HIP_PLATFORM_AMD__"} }); @@ -223,7 +222,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil qwen3_run.has_side_effects = true; // the checkpoints and oracle files named by TF_QWEN3_* are not cached inputs b.step("qwen3-hip-gpu-build", "Compile the Qwen3 dense GPU checks without running them").dependOn(&qwen3_gpu.step); b.step("qwen3-hip-gpu-test", "Qwen3 lastRows on the GPU against transformers (TF_QWEN3_EMBED_*, TF_QWEN3_RERANK_*)").dependOn(&qwen3_run.step); - @import("flashnext_gpu.zig").draftBatch(b, target, optimize, gpu, kernel_test_step); + @import("flashnext_gpu.zig").draftBatch(b, target, optimize, gpu); const parse_object = compile(b, .{ .name = hipcc, .resolved = hipcc_resolved, .device_lib = device_lib }, hip_arch, b.path("zig/kernels/hip/ops/vision.hip"), "parse-vision.hsaco"); @import("nemotron_parse_gpu.zig").gpuTests(b, target, host.hip, parse_object); @import("nemotron_parse_gpu.zig").modelTests(b, target, optimize, gpu.hip); diff --git a/zig/src/families/flashnext/hip/draft_batch.zig b/zig/src/families/flashnext/hip/draft_batch.zig index e1d158ab7f2..e85686c6d02 100644 --- a/zig/src/families/flashnext/hip/draft_batch.zig +++ b/zig/src/families/flashnext/hip/draft_batch.zig @@ -10,7 +10,7 @@ const be = @import("lanes").backend; const Fx = lanes_mod.Fx; const Lane = lanes_mod.Lane; -/// A stream drafting in a batched call: its lane, head caches, chain depth and its rows in the packed absorb. +/// A stream drafting in a batched call: its lane, head caches, chain depth, packed rows and its current residual row. const Slot = struct { lane: *Lane, hc: *cache.Caches, @@ -20,6 +20,7 @@ const Slot = struct { row_at: usize = 0, row_n: usize = 0, chained: usize = 0, + chain: u64 = 0, }; /// The head absorbs each stream's kept rows (residual streams and the token after each), then chains its drafts. @@ -146,7 +147,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { active_n += 1; }; if (active_n == 0) return; - // each stream chains from its last absorbed row: its mixed row gathered, its residual row kept in its lane + // each stream chains from its last absorbed row: its mixed row gathered, its residual row's address kept const mixed_rows = try e.arena.take(n * hidden_bytes); for (slots[0..n], 0..) |*s, i| { try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync( @@ -155,13 +156,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { hidden_bytes, e.stream.handle, )); - if (s.depth > 0) try hip.raw.copy( - s.lane.streams, - 0, - out.streams.ptr + (s.row_at + s.row_n - 1) * row_bytes, - row_bytes, - e.stream.handle, - ); + s.chain = out.streams.ptr + (s.row_at + s.row_n - 1) * row_bytes; } var toks: [forward.max_segs]u32 = undefined; var probs: [forward.max_segs]f32 = undefined; @@ -198,7 +193,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { step_segs[a] = .{ .c = s.hc, .tokens = &s.tok, .pos = s.lane.caches.len + step - 1 }; try hip.runtime.check(e.driver.api.hipMemcpyDtoDAsync( @ptrFromInt(step_rows + a * row_bytes), - @ptrFromInt(s.lane.streams.base()), + @ptrFromInt(s.chain), row_bytes, e.stream.handle, )); @@ -224,13 +219,7 @@ fn batched(f: *Fx, requests: []const be.DraftRequest) anyerror!void { probs[0..active_n], true, ); - for (active[0..active_n], 0..) |si, a| try hip.raw.copy( - slots[si].lane.streams, - 0, - step_out.streams.ptr + a * row_bytes, - row_bytes, - e.stream.handle, - ); + for (active[0..active_n], 0..) |si, a| slots[si].chain = step_out.streams.ptr + a * row_bytes; next = 0; for (active[0..active_n], 0..) |si, a| { const s = &slots[si]; diff --git a/zig/src/families/flashnext/hip/draft_batch_test.zig b/zig/src/families/flashnext/hip/draft_batch_test.zig index bb8218a3e3d..143216e1aad 100644 --- a/zig/src/families/flashnext/hip/draft_batch_test.zig +++ b/zig/src/families/flashnext/hip/draft_batch_test.zig @@ -44,7 +44,7 @@ fn prompts(a: std.mem.Allocator, source: []const u8) ![2][]const u32 { return out; } -/// The engine of TF_RV2696_DIR and its lane backend. +/// The engine of TF_FLASHNEXT_DIR and its lane backend. const Fixture = struct { e: *fx.engine.Engine, f: *fx.lanes.Fx, @@ -131,8 +131,8 @@ test "two streams draft in one head pass a step as they do one stream at a time" var arena: std.heap.ArenaAllocator = .init(t.allocator); defer arena.deinit(); const a = arena.allocator(); - const dir = try env(a, "TF_RV2696_DIR", 4096) orelse return error.SkipZigTest; - const ps = try prompts(a, (try env(a, "TF_RV2696_PROMPTS", 1 << 16)) orelse text); + const dir = try env(a, "TF_FLASHNEXT_DIR", 4096) orelse return error.SkipZigTest; + const ps = try prompts(a, (try env(a, "TF_FLASHNEXT_PROMPTS", 1 << 16)) orelse text); var x = try Fixture.init(a, dir); defer x.deinit(); // four streams: two draft in one call, and the same two prompts again, each drafted alone diff --git a/zig/src/families/flashnext/hip/head.zig b/zig/src/families/flashnext/hip/head.zig index d53e6a910b2..c2d8f23d058 100644 --- a/zig/src/families/flashnext/hip/head.zig +++ b/zig/src/families/flashnext/hip/head.zig @@ -92,7 +92,7 @@ pub fn run( return .{ .mixed = try forward.hcPre(o, m, w.mix, x, rows, null), .streams = h }; } -/// Each of `rows` mixed rows' greedy draft token and its probability; `window` on a shared round's rows, else a prompt's. +/// Each mixed row's greedy draft token and probability; `window` for a shared round's rows, else a prompt's. pub fn draws( ops: Ops, m: *const model.Model, From eb671f102213bfc696c32d088cef8a8f352cdae7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:17:17 +0000 Subject: [PATCH 19/59] changelog: back under Unreleased --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dee5e8ca1d5..8dbd852692b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged. +- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged (#2696). Thanks to @gilby. - Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). - Nemotron Metal keeps the prompt IDs and one queued chunk across consecutive prefill steps. Cancellation publishes the landed prefix before keeping it and credits that work before retirement. @@ -184,8 +186,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - GLM-5.3-Flash on CUDA: `TF_GLM_CONTEXT_CEILING` (opt-in) lets GLM open windows past 1,048,576 tokens, read once when the model opens; with it unset nothing changes, and cold prompts and decode on two and three GB10s read level with main (#2765, refs #2663). Thanks to @Bizuayeu. - Metal on M5: prompt lane projections at every width (8-, 6-, 5-, 3- and 2-bit and the oQ mixes) take a chunk's 16-row blocks in one dispatch, as 4-bit already did; Qwen3.8-27B MLX 8-bit cold prompts are about 33% faster on an M5 Ultra (769 to 1,029 tok/s at 2K, 769 to 1,027 at 8K) with identical tokens, and decode is unchanged (#2851, for #2818). -- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged. -- Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged (#2696). Thanks to @gilby. - GLM-5.3-Flash: the DFlash2 drafter's startup line and docs give its licence as Apache-2.0, as its model card now says (#3084, for #1583). From 536cf0e0f1d83350f2d2e69bb544f61ed506123d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:11:57 +0000 Subject: [PATCH 20/59] docs: strict tools under tool_choice auto, and TENSORFOLD_TOOL_GRAMMAR What a strict tool's schema holds under auto, what each choice lets the model emit, which cases are refused and with which status, the server-wide switch and its legacy DeepSeek alias, and that LFM2's EBNF call rule is not grammar-held under auto. Docs only. --- docs/api.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/api.md b/docs/api.md index f74d829fbeb..1a47eba2936 100644 --- a/docs/api.md +++ b/docs/api.md @@ -714,6 +714,33 @@ backend mask hook. A missing library or grammar compilation error is also refuse The native GLM CUDA backend also supports token grammars, gathering vocabulary rows before rank 0 masks and draws. +### Strict tools under `tool_choice: "auto"` + +With tools offered and `tool_choice` omitted or `"auto"`, a tool marked `"strict": true` inside `function` is held +to its `parameters` schema when the backend has token-grammar support and the grammar library loads. The reply may be +plain text or calls, and text outside the call markup is free. Inside a call the name is one of the offered tools, a +strict tool's arguments must follow its schema, and a tool not marked strict takes any JSON object. +`parallel_tool_calls: false` allows one call; unset or `true` allows several. Auto never requires a call: a text-only +reply is not an error. Chat passes the tools through; Responses copies the tool's top-level `strict` into `function`. +Anthropic Messages tools carry no `strict` flag, so they are held only when the switch below is on. + +`TENSORFOLD_TOOL_GRAMMAR=1` holds every auto tools request the same way: each offered tool's arguments must follow +its schema, marked strict or not. Only the value `1` turns it on, with ASCII spaces around it ignored; unset, empty, +`0` and any other text leave it off, and none of those is refused at startup. Unset is the default. The switch +applies only to auto: `required` and a named function already constrain the reply to schema-valid calls, so it +changes nothing there. Where the backend lacks token-grammar support or the grammar library does not load, an auto +request is served unconstrained rather than refused; the `required` and named cases in that position are refused +before generation with HTTP 400 and the backend's or library's reason, as described above. A strict auto grammar +xgrammar cannot compile is also refused before generation with HTTP 400, for example: +`strict tools under tool_choice "auto" on backend 'qwen27': the grammar cannot be enforced: `. +LFM2's template writes its calls as one EBNF rule rather than a triggered tag, so strict tools under auto are not +grammar-held there. + +The legacy `TF_DSV41_TOOL_GRAMMAR` name takes `0` or `1`. When `TENSORFOLD_TOOL_GRAMMAR` is set, even to an empty +value, it is read instead and the legacy name is ignored, even if the legacy value is malformed. A malformed legacy +value without that override logs the accepted form at start and exits with status 1, for example: +`TF_DSV41_TOOL_GRAMMAR="true": expected 0 or 1 (ignored while TENSORFOLD_TOOL_GRAMMAR is set)`. + `grammar_budget: true` (native server, off by default) keeps a constrained reply completable within its token limit, so a required tool call or a JSON value cut by `max_tokens` still parses. Before each draw, a token is masked when no continuation after it reaches a place where the grammar could end within the draws left (`max_tokens`, counted after From 28337ca6942dfea623bc1b554668011d84dd0fc3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:50:56 +0000 Subject: [PATCH 21/59] changelog: #3235 under Unreleased --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dbd852692b..f15697ee435 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Docs: strict tools under `tool_choice: "auto"` and `TENSORFOLD_TOOL_GRAMMAR`: what a strict tool's schema holds, what is served unconstrained and what is refused, and the legacy DeepSeek alias (#3235, fixes #3177). + +- Qwen 3.5, 3.6 and 3.8 on CUDA: a background prompt fill stops between chunks when a foreground request is waiting, keeps the prefix it has already filled, and resumes from there; replies are unchanged (#2873, part of #2812). Thanks to @tacosta. + - Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged. - Qwen3.8-Flash-Next on HIP: when several streams draft in one round, the MTP head drafts them together, one forward and one draw a step instead of one per stream, as on CUDA and Metal; on a Strix Halo iGPU distinct-prompt decode is about 3% faster at 2 streams and 7% at 4, and one stream is unchanged. Replies are unchanged (#2696). Thanks to @gilby. - Nemotron on Metal: a new prompt is filled a chunk at a time between other streams' decode rounds, instead of stalling them for its whole prefill. Chunks are cut exactly as before, so replies are unchanged (#3054, part of #3021). From cf4555373554867a72c53263e905f203a03d4d96 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:17:51 +0000 Subject: [PATCH 22/59] changelog: each line once under Unreleased --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f15697ee435..270690572e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel Cancellation publishes the landed prefix before keeping it and credits that work before retirement. - Ling-3.0-tiny on Metal: the KDA mixer uses Kimi's existing `k3_kda` kernel (full-width gate, D=128, 4 taps) wired to Ling-tiny's 16 heads. Host `mixF64` is checked against a float64 dump of `oracle/kda_inner.py` (a stdlib copy of `ling_forward.py` Model.kda from conv through y, r = identity; that file is not imported and is not edited) on 16 heads x 2 and 4 rows (worst 8.3e-10 and 1.1e-9). The copy equals Model.kda at worst abs 2.8e-14 on those shapes (fake Ckpt, r = identity, `oracle/kda_vs_model.py`). `k3_kda` versus the dump is 0.0102 at 2 rows and 0.0119 at 4 rows, gated at 2 x (2^-7 of the largest |y|); true bf16 steps at those magnitudes are about 1.3 and 1.5 (values in [1, 2) share one step of 2^-7). `k3_kda` versus the f32 mixer is 0.001953 at 2 and 4 rows (gated under 0.01). `mix`/`mixF64` return `error.KdaWidthTooWide` when W > 2048 (ReleaseFast-safe; the stack conv window is 3 x 2048). Fixture inputs regenerate byte-identical; committed y matches a regenerate to within one float64 ulp, so they are numerically reproducible, not hash-reproducible. Every check uses r = identity and a fake Ckpt. No new kernel (for #1247). - Ling-3.0-tiny: a host KDA reference, and a Metal check that Kimi's `k3_kda` matches it at Ling-tiny's shape; nothing is served yet (part of #1247). -- Qwen 3.5, 3.6 and 3.8 on CUDA: a background prompt fill stops between chunks when a foreground request is waiting, keeps the prefix it has already filled, and resumes from there; replies are unchanged (#2873, part of #2812). Thanks to @tacosta. - - GLM-5.3-Flash on CUDA loads NVFP4_NZ5 checkpoints, whose block-32 routed experts read E2M1's code 0b1000 as +5; every other recipe and mix is refused by name, and E2M1 checkpoints load exactly as before (#2894). Thanks to @Bizuayeu. - Spark 2.5 and MiniMax-M3 on CUDA: the last layer of a prompt runs only on the rows something reads (the final rows, plus DSpark's drafter rows for MiniMax), as Qwen's already did; tokens unchanged (#3122). From 0c8a9e3db5cf7e188a9bc18e6c3056350ac80f66 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:20:24 +0000 Subject: [PATCH 23/59] Price shared plain rounds independently of drafted row costs --- zig/src/core/lanes/allocate.zig | 16 +- zig/src/core/lanes/depth.zig | 219 +++++------------------ zig/src/core/lanes/depth_test.zig | 170 ++++++++++++++++++ zig/src/core/lanes/engine.zig | 78 +------- zig/src/core/lanes/shared_drafts.zig | 10 +- zig/src/core/lanes/shared_price.zig | 83 +++++++++ zig/src/core/lanes/shared_price_test.zig | 144 +++++++++++++++ zig/src/core/lanes/shared_round.zig | 94 ++++++++++ zig/src/core/lanes/windows.zig | 8 +- 9 files changed, 569 insertions(+), 253 deletions(-) create mode 100644 zig/src/core/lanes/depth_test.zig create mode 100644 zig/src/core/lanes/shared_price.zig create mode 100644 zig/src/core/lanes/shared_price_test.zig create mode 100644 zig/src/core/lanes/shared_round.zig diff --git a/zig/src/core/lanes/allocate.zig b/zig/src/core/lanes/allocate.zig index 99426b5a0f1..21520cb6dc2 100644 --- a/zig/src/core/lanes/allocate.zig +++ b/zig/src/core/lanes/allocate.zig @@ -19,6 +19,9 @@ pub fn allocate(gpa: Allocator, fixed: []const u32, probs: []const []const f64, /// What drafting the counted nodes costs: a head step each, or the deepest stream's steps when one batch drafts all. pub const HeadCost = struct { step_ms: f64 = 0.0, + plain_ms: ?f64 = null, // fixed residual for the zero-draft option, independently measured + extra_step_ms: f64 = 0.0, // extra work past the first head step + heads: ?[]const bool = null, // copied rows do not run a neural head batched: bool = false, free_first: bool = false, row_ms: f64 = 0.0, // what each row past a stream's first costs past the table on this machine (below it: less) @@ -47,7 +50,7 @@ pub fn allocateDrafts(gpa: Allocator, fixed: []const u32, probs: []const []const var live: u64 = 0; for (fixed) |f| live += @intFromBool(f > 0); const least = @min(head.least_rows, max_rows); - var best = if (rows >= least) rate(costs, timed, rows, expected, overhead_ms + rowTerm(costs, timed, head, rows, live)) else -std.math.inf(f64); + var best = if (rows >= least) rate(costs, timed, rows, expected, (head.plain_ms orelse overhead_ms) + rowTerm(costs, timed, head, rows, live)) else -std.math.inf(f64); while (rows < max_rows) { // the likeliest next node, ties to the lowest stream (Python's heapq of (-p, stream)) var pick: ?usize = null; @@ -62,14 +65,16 @@ pub fn allocateDrafts(gpa: Allocator, fixed: []const u32, probs: []const []const } const s = pick orelse break; counts[s] += 1; - firsts += @intFromBool(counts[s] == 1); + const neural = if (head.heads) |mask| mask[s] else true; + firsts += @intFromBool(neural and counts[s] == 1); rows += 1; - drafts += 1; - deepest = @max(deepest, counts[s]); + drafts += @intFromBool(neural); + if (neural) deepest = @max(deepest, counts[s]); expected += pick_p; const steps: f64 = @floatFromInt(if (head.batched) deepest -| @intFromBool(head.free_first) else drafts - (if (head.free_first) firsts else 0)); + const extra_steps: f64 = @floatFromInt(if (head.batched) deepest -| 1 else drafts - firsts); if (rows < least) continue; - const now = rate(costs, timed, rows, expected, overhead_ms + head.step_ms * steps + rowTerm(costs, timed, head, rows, live)); + const now = rate(costs, timed, rows, expected, overhead_ms + head.step_ms * steps + head.extra_step_ms * extra_steps + rowTerm(costs, timed, head, rows, live)); if (now > best or (!timed and head.step_ms == 0)) { best = now; @memcpy(best_counts, counts); @@ -92,6 +97,7 @@ pub fn rowTerm(costs: *const Table, timed: bool, head: HeadCost, rows: u64, live fn rate(costs: *const Table, timed: bool, total: u64, expected: f64, overhead_ms: f64) f64 { var cost: f64 = 1.0; if (timed) cost = costs.get(@intCast(total)) orelse return -1.0; + if (cost + overhead_ms <= 0) return -1; return expected / (cost + overhead_ms); } diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 258d86b170e..a265e587890 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -67,9 +67,12 @@ pub const Rule = struct { shared_rounds: u64 = 0, greedy_overhead: std.ArrayList(Overhead) = .empty, // overhead from rounds without a sampled stream + shared_price: @import("shared_price.zig").Prices = .{}, + hold_order: []usize = &.{}, // reused hold ordering, at most batch_rows entries pub fn deinit(r: *Rule) void { + r.shared_price.deinit(r.gpa); r.gpa.free(r.hold_order); r.row_cost.deinit(r.gpa); r.round_ms.deinit(r.gpa); @@ -236,6 +239,10 @@ pub const Rule = struct { /// Granted holds kept, most expected drafts a row first, while they raise the next round's expected tokens a ms. pub fn payHolds(r: *Rule, whos: []const Who, sampled: bool, out: []i64) !void { + return r.payHoldsFor(whos, sampled, out, whos.len); + } + + pub fn payHoldsFor(r: *Rule, whos: []const Who, sampled: bool, out: []i64, streams: usize) !void { if (whos.len > r.batch_rows) return error.BadHoldStreamCount; if (r.hold_order.len == 0) r.hold_order = try r.gpa.alloc(usize, r.batch_rows); const order = r.hold_order[0..whos.len]; @@ -263,19 +270,20 @@ pub const Rule = struct { } }; std.mem.sort(usize, order[0..m], Ctx{ .r = r, .whos = whos }, Ctx.less); - const fixed = r.fixedMs(whos.len, sampled); - var rows: f64 = @floatFromInt(whos.len); + const paired = r.sharedPrice(streams, sampled); + const fixed = if (paired) |p| p.fixed else r.fixedMs(streams, sampled); + var rows: f64 = @floatFromInt(streams); var tokens = rows; - const plain = r.shared_costs.get(@intCast(whos.len)) orelse return; + const plain = r.shared_costs.get(@intCast(streams)) orelse return; const probe_ms = if (probes > 0) holdMs(r.k.hold_costs, probes, deepest) else 0; - var best = tokens / (plain + fixed + probe_ms); + var best = tokens / (plain + (if (paired) |p| p.plain else fixed) + probe_ms); var keep: usize = 0; for (order[0..m], 1..) |i, k| { rows += rowsOf(whos[i]); tokens += try r.gainOf(whos[i]); deepest = @max(deepest, out[i]); const verify = r.shared_costs.get(@intFromFloat(@ceil(rows))) orelse break; - const extra = r.row_cost.extraMs(whos.len, sampled) * (rows - @as(f64, @floatFromInt(whos.len))); + const extra = (if (paired) |p| p.row else r.row_cost.extraMs(streams, sampled)) * (rows - @as(f64, @floatFromInt(streams))); const now = tokens / (verify + (if (extra < 0) @max(extra, plain - verify) else extra) + fixed + holdMs(r.k.hold_costs, k + probes, deepest)); if (now > best) { best = now; @@ -297,6 +305,11 @@ pub const Rule = struct { /// Head drafts for the streams of a shared round, sized by allocation over their chain chances. pub fn budgets(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64) !void { + return r.budgetsFor(whos, probe, sampled, out, whos.len); + } + + /// Non-head streams still contribute their plain rows to a shared round's width and exact-count price. + pub fn budgetsFor(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64, streams: usize) !void { // drafts lose here: none asked, no head pass if (r.plain_streams > 0 and whos.len >= r.plain_streams) return @memset(out, 0); if (r.confidence_floor != null) { @@ -310,30 +323,35 @@ pub const Rule = struct { o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, granted + r.k.draft_slack), probe); } if (r.granted_depth) capPass(out, r.batch_rows); - if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHolds(whos, sampled, out); + if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHoldsFor(whos, sampled, out, streams); return; } const most = try r.gpa.alloc(i64, whos.len); defer r.gpa.free(most); - const probs = try r.gpa.alloc([]f64, whos.len); + const probs = try r.gpa.alloc([]f64, streams); + @memset(probs, &.{}); defer r.gpa.free(probs); var made: usize = 0; defer for (probs[0..made]) |p| r.gpa.free(p); - for (whos, most, probs) |w, *m, *p| { + for (whos, most, probs[0..whos.len]) |w, *m, *p| { m.* = @min(@as(i64, r.most_drafts), @max(1, w.draft_room - 1)); p.* = try alloc.chainProbabilities(r.gpa, try r.rates(w), @intCast(m.*)); made += 1; } - const ones = try r.gpa.alloc(u32, whos.len); + const ones = try r.gpa.alloc(u32, streams); defer r.gpa.free(ones); @memset(ones, 1); const head: alloc.HeadCost = .{ .step_ms = r.sharedStepMs(), .batched = r.batched_heads, .row_ms = r.row_cost.extraMs(whos.len, sampled), .least_rows = r.row_cost.leastRows(whos.len, sampled) }; - const counts = if (r.draft_step_ms != 0) + const paired = r.sharedPrice(streams, sampled); + const all_counts = if (paired) |p| + try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, p.fixed, r.row_cost.capRows(streams, sampled, @max(streams, r.batch_rows)), .{ .plain_ms = p.plain, .step_ms = r.sharedStepMs(), .extra_step_ms = r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .row_ms = p.row, .least_rows = r.row_cost.leastRows(streams, sampled) }) + else if (r.draft_step_ms != 0) try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, r.overheadMs(whos.len, sampled), r.row_cost.capRows(whos.len, sampled, @max(whos.len, r.batch_rows)), .{ .step_ms = r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .free_first = true, .row_ms = r.row_cost.extraMs(whos.len, sampled), .least_rows = head.least_rows }) else try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, r.fixedMs(whos.len, sampled), r.row_cost.capRows(whos.len, sampled, @max(whos.len, r.batch_rows)), head); - defer r.gpa.free(counts); - r.probeShared(whos, most, counts); + defer r.gpa.free(all_counts); + const counts = all_counts[0..whos.len]; + if (streams == whos.len) r.probeShared(whos, most, counts); if (r.plain_guard) { // no draft where none pays; a probe after a growing run of plain rounds for (whos, counts) |w, *c| { @@ -367,6 +385,21 @@ pub const Rule = struct { } } + /// Independent plain price and the row slope from a plain/drafted pair, at this exact count and mode. + pub fn sharedPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { + if (streams < 2 or !r.plain_guard or r.confidence_floor != null) return null; + return r.shared_price.price(streams, sampled, r.fixedMs(streams, sampled), r.row_cost.extraMs(streams, sampled)); + } + + /// Only completed timed shared rounds advance this count/mode's calibration clock. + pub fn observeShared(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { + if (streams > 1 and r.plain_guard and r.confidence_floor == null) { + if (r.shared_costs.get(@intCast(rows))) |forward| + try r.shared_price.observe(r.gpa, streams, rows, ms - forward - head_ms, sampled, plain, calibration); + } + try r.observeOverhead(streams, rows, ms, sampled, head_ms); + } + /// A shared round's ms beyond its forward at this many streams (the nearest measured count, first seen on ties). pub fn overheadMs(r: *const Rule, streams: usize, sampled: bool) f64 { const o = r.nearest(streams, sampled) orelse return 8.0; @@ -433,165 +466,9 @@ fn distance(a: u32, b: usize) usize { return if (x > b) x - b else b - x; } -test "a depth's acceptance estimate moves by the configured weight of the newest round" { - const gpa = std.testing.allocator; - const empty: Table = .{}; - var rule: Rule = .{ .gpa = gpa, .k = .{ .depth_rate = 0.08 }, .prior = &.{ 0.5, 0.5 }, .most_drafts = 2, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = false, .batch_rows = 8 }; - defer rule.deinit(); - var st: ?State = null; - defer if (st) |*s| s.deinit(gpa); - const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; - try rule.observeDepth(who, 2, 1); // the first draft landed, the second did not - try std.testing.expectApproxEqAbs(@as(f64, 0.54), st.?.p[0], 1e-12); - try std.testing.expectApproxEqAbs(@as(f64, 0.46), st.?.p[1], 1e-12); -} - -test "depth picks the most tokens a ms and probes deeper" { - const gpa = std.testing.allocator; - var fc: Table = .{}; - defer fc.deinit(gpa); - for (1..5) |w| try fc.put(gpa, @intCast(w), 5.0 + @as(f64, @floatFromInt(w))); - const shared: Table = .{}; - var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.9, 0.9, 0.9 }, .most_drafts = 3, .family_costs = &fc, .shared_costs = &shared, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = false, .batch_rows = 8 }; - defer rule.deinit(); - var st: ?State = null; - defer if (st) |*s| s.deinit(gpa); - const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; - try std.testing.expectEqual(@as(i64, 3), try rule.depth(who)); -} - -test "under a confidence floor a greedy stream drafts the most, and a sampled one keeps its rates' depth" { - const gpa = std.testing.allocator; - const empty: Table = .{}; - const No = struct { - fn copy(_: *anyopaque, _: *const Who) bool { - return false; - } - }; - var unused: u8 = 0; - const probe: Probe = .{ .ptr = &unused, .copy = No.copy }; - var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.5, 0.5, 0.5 }, .most_drafts = 3, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .confidence_floor = 0.5, .batch_rows = 8 }; - defer rule.deinit(); - var states: [2]?State = .{ null, null }; - defer for (&states) |*s| if (s.*) |*x| x.deinit(gpa); - const greedy: Who = .{ .state = &states[0], .draft_room = 100, .finished = false, .forced = false }; - const sampled: Who = .{ .state = &states[1], .draft_room = 100, .finished = false, .forced = false, .sampled = true }; - try std.testing.expectEqual(@as(i64, 3), try rule.headDepth(&greedy, null, probe)); - try std.testing.expectEqual(@as(i64, 1), try rule.headDepth(&sampled, null, probe)); // a first rate under 0.8: one draft -} - -test "a shared round's drafts come out the same whichever depths its overhead was measured at" { - const gpa = std.testing.allocator; - var shared: Table = .{}; - defer shared.deinit(gpa); - for (1..17) |w| try shared.put(gpa, @intCast(w), 10.0 + 2.0 * @as(f64, @floatFromInt(w))); - const empty: Table = .{}; - const No = struct { - fn copy(_: *anyopaque, _: *const Who) bool { - return false; - } - }; - var unused: u8 = 0; - const probe: Probe = .{ .ptr = &unused, .copy = No.copy }; - var got: [2][2]i64 = undefined; - for ([_][2]i64{ .{ 1, 1 }, .{ 3, 3 } }, &got) |measured, *out| { - var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.9, 0.8, 0.7, 0.6 }, .most_drafts = 4, .family_costs = &empty, .shared_costs = &shared, .mtp_step_ms = 3.0, .plain_guard = false, .node_probabilities = false, .batch_rows = 16 }; - defer rule.deinit(); - // two streams' round: their pending rows and the drafts verified, 3 ms of its own, then each drafted step - const rows: u64 = @intCast(2 + measured[0] + measured[1]); - const head = rule.headMs(&measured); - try rule.observeOverhead(2, rows, shared.get(@intCast(rows)).? + 3.0 + head, false, head); - var states: [2]?State = .{ null, null }; - defer for (&states) |*s| if (s.*) |*x| x.deinit(gpa); - var whos = [_]Who{ .{ .state = &states[0], .draft_room = 100, .finished = false, .forced = false }, .{ .state = &states[1], .draft_room = 100, .finished = false, .forced = false } }; - try rule.budgets(&whos, probe, false, out); - } - try std.testing.expectEqualSlices(i64, &got[0], &got[1]); -} - -test "granted depths in a shared round fit one hold pass: every block is as deep as the deepest" { - const empty: Table = .{}; - var rule: Rule = .{ .gpa = std.testing.allocator, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; - defer rule.deinit(); - var states: [8]?State = @splat(null); - defer for (&states) |*st| if (st.*) |*x| x.deinit(std.testing.allocator); - var whos: [8]Who = undefined; - for (&whos, &states, 0..) |*w, *st, i| w.* = .{ .state = st, .draft_room = 100, .finished = false, .forced = false, .granted = @intCast(i) }; - const No = struct { - fn copy(_: *anyopaque, _: *const Who) bool { - return false; - } - }; - var unused: u8 = 0; - var out: [8]i64 = undefined; - try rule.budgets(&whos, .{ .ptr = &unused, .copy = No.copy }, false, &out); - // a grant of none probes two; grants 1..7 that took every held draft, plus one; cut to 32 rows over eight blocks - try std.testing.expectEqualSlices(i64, &.{ 2, 2, 3, 4, 4, 4, 4, 4 }, &out); - try rule.budgets(whos[0..2], .{ .ptr = &unused, .copy = No.copy }, false, out[0..2]); - try std.testing.expectEqualSlices(i64, &.{ 2, 2 }, out[0..2]); // two blocks fit whole - for (whos[0..2]) |*w| w.grant_short = true; - try rule.budgets(whos[0..2], .{ .ptr = &unused, .copy = No.copy }, false, out[0..2]); - try std.testing.expectEqualSlices(i64, &.{ 2, 1 }, out[0..2]); // a grant short of the held drafts: no slack -} - -test "a copy ahead: one head draft beside it, or none when the head's drafts cost a pass of their own" { - const empty: Table = .{}; - const Yes = struct { - fn copy(_: *anyopaque, _: *const Who) bool { - return true; - } - }; - var unused: u8 = 0; - const probe: Probe = .{ .ptr = &unused, .copy = Yes.copy }; - var st: ?State = null; - defer if (st) |*x| x.deinit(std.testing.allocator); - const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false, .granted = 3 }; - for ([_]bool{ false, true }) |first| { - var rule: Rule = .{ .gpa = std.testing.allocator, .k = .{ .copy_first = first }, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; - defer rule.deinit(); - try std.testing.expectEqual(@as(i64, @intFromBool(!first)), try rule.headDepth(&who, null, probe)); - var out: [1]i64 = undefined; - var whos = [_]Who{who}; - try rule.budgets(&whos, probe, false, &out); - try std.testing.expectEqual(@as(i64, @intFromBool(!first)), out[0]); - } -} - -test "a granted hold stays only while its stream's expected drafts pay for the verify rows and the hold pass" { - const gpa = std.testing.allocator; - var shared: Table = .{}; - defer shared.deinit(gpa); - for (1..33) |w| try shared.put(gpa, @intCast(w), 10.0 + @as(f64, @floatFromInt(w))); - const empty: Table = .{}; - const cheap = [_]HoldCost{ .{ .streams = 1, .depth = 1, .ms = 1.0 }, .{ .streams = 8, .depth = 1, .ms = 4.5 } }; - var states: [4]?State = @splat(null); - defer for (&states) |*st| if (st.*) |*x| x.deinit(gpa); - const granted = [_]?u32{ 2, 2, 0, 1 }; - const gains = [_]?f64{ 1.8, 0.2, null, 0.9 }; - var whos: [4]Who = undefined; - for (&whos, &states, granted, gains) |*w, *st, g, x| w.* = .{ .state = st, .draft_room = 100, .finished = false, .forced = false, .granted = g, .gain = x }; - var rule: Rule = .{ .gpa = gpa, .k = .{ .hold_costs = &cheap }, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &shared, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; - defer rule.deinit(); - // 8 ms overhead: plain 4 / 22; stream 0 then 3 raise the rate (5.8 / 25, 6.7 / 26.5), stream 1 would lower it - var out = [_]i64{ 4, 4, 0, 3 }; - try rule.payHolds(&whos, false, &out); - try std.testing.expectEqualSlices(i64, &.{ 4, 0, 0, 3 }, &out); - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - rule.gpa = failing.allocator(); - out = .{ 4, 4, 0, 3 }; - try rule.payHolds(&whos, false, &out); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqualSlices(i64, &.{ 4, 0, 0, 3 }, &out); - rule.gpa = gpa; - const dear = [_]HoldCost{.{ .streams = 1, .depth = 1, .ms = 20.0 }}; - rule.k.hold_costs = &dear; - out = .{ 4, 4, 0, 3 }; - try rule.payHolds(&whos, false, &out); - try std.testing.expectEqualSlices(i64, &.{ 0, 0, 0, 0 }, &out); // no gain pays a 20 ms pass - whos[2].granted = 0; - out = .{ 4, 4, 2, 3 }; - try rule.payHolds(&whos, false, &out); - try std.testing.expectEqualSlices(i64, &.{ 0, 0, 2, 0 }, &out); // a probe after a grant of none keeps its hold +test { + _ = @import("depth_test.zig"); + _ = @import("shared_price_test.zig"); } test { diff --git a/zig/src/core/lanes/depth_test.zig b/zig/src/core/lanes/depth_test.zig new file mode 100644 index 00000000000..9fc1327fb38 --- /dev/null +++ b/zig/src/core/lanes/depth_test.zig @@ -0,0 +1,170 @@ +//! The original depth rule regressions. +const std = @import("std"); +const d = @import("depth.zig"); +const Rule = d.Rule; +const State = d.State; +const Who = d.Who; +const Probe = d.Probe; +const HoldCost = d.HoldCost; +const Table = @import("table.zig").Table; + +test "a depth's acceptance estimate moves by the configured weight of the newest round" { + const gpa = std.testing.allocator; + const empty: Table = .{}; + var rule: Rule = .{ .gpa = gpa, .k = .{ .depth_rate = 0.08 }, .prior = &.{ 0.5, 0.5 }, .most_drafts = 2, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = false, .batch_rows = 8 }; + defer rule.deinit(); + var st: ?State = null; + defer if (st) |*s| s.deinit(gpa); + const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; + try rule.observeDepth(who, 2, 1); // the first draft landed, the second did not + try std.testing.expectApproxEqAbs(@as(f64, 0.54), st.?.p[0], 1e-12); + try std.testing.expectApproxEqAbs(@as(f64, 0.46), st.?.p[1], 1e-12); +} + +test "depth picks the most tokens a ms and probes deeper" { + const gpa = std.testing.allocator; + var fc: Table = .{}; + defer fc.deinit(gpa); + for (1..5) |w| try fc.put(gpa, @intCast(w), 5.0 + @as(f64, @floatFromInt(w))); + const shared: Table = .{}; + var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.9, 0.9, 0.9 }, .most_drafts = 3, .family_costs = &fc, .shared_costs = &shared, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = false, .batch_rows = 8 }; + defer rule.deinit(); + var st: ?State = null; + defer if (st) |*s| s.deinit(gpa); + const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; + try std.testing.expectEqual(@as(i64, 3), try rule.depth(who)); +} + +test "under a confidence floor a greedy stream drafts the most, and a sampled one keeps its rates' depth" { + const gpa = std.testing.allocator; + const empty: Table = .{}; + const No = struct { + fn copy(_: *anyopaque, _: *const Who) bool { + return false; + } + }; + var unused: u8 = 0; + const probe: Probe = .{ .ptr = &unused, .copy = No.copy }; + var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.5, 0.5, 0.5 }, .most_drafts = 3, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .confidence_floor = 0.5, .batch_rows = 8 }; + defer rule.deinit(); + var states: [2]?State = .{ null, null }; + defer for (&states) |*s| if (s.*) |*x| x.deinit(gpa); + const greedy: Who = .{ .state = &states[0], .draft_room = 100, .finished = false, .forced = false }; + const sampled: Who = .{ .state = &states[1], .draft_room = 100, .finished = false, .forced = false, .sampled = true }; + try std.testing.expectEqual(@as(i64, 3), try rule.headDepth(&greedy, null, probe)); + try std.testing.expectEqual(@as(i64, 1), try rule.headDepth(&sampled, null, probe)); // a first rate under 0.8: one draft +} + +test "a shared round's drafts come out the same whichever depths its overhead was measured at" { + const gpa = std.testing.allocator; + var shared: Table = .{}; + defer shared.deinit(gpa); + for (1..17) |w| try shared.put(gpa, @intCast(w), 10.0 + 2.0 * @as(f64, @floatFromInt(w))); + const empty: Table = .{}; + const No = struct { + fn copy(_: *anyopaque, _: *const Who) bool { + return false; + } + }; + var unused: u8 = 0; + const probe: Probe = .{ .ptr = &unused, .copy = No.copy }; + var got: [2][2]i64 = undefined; + for ([_][2]i64{ .{ 1, 1 }, .{ 3, 3 } }, &got) |measured, *out| { + var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.9, 0.8, 0.7, 0.6 }, .most_drafts = 4, .family_costs = &empty, .shared_costs = &shared, .mtp_step_ms = 3.0, .plain_guard = false, .node_probabilities = false, .batch_rows = 16 }; + defer rule.deinit(); + // two streams' round: their pending rows and the drafts verified, 3 ms of its own, then each drafted step + const rows: u64 = @intCast(2 + measured[0] + measured[1]); + const head = rule.headMs(&measured); + try rule.observeOverhead(2, rows, shared.get(@intCast(rows)).? + 3.0 + head, false, head); + var states: [2]?State = .{ null, null }; + defer for (&states) |*s| if (s.*) |*x| x.deinit(gpa); + var whos = [_]Who{ .{ .state = &states[0], .draft_room = 100, .finished = false, .forced = false }, .{ .state = &states[1], .draft_room = 100, .finished = false, .forced = false } }; + try rule.budgets(&whos, probe, false, out); + } + try std.testing.expectEqualSlices(i64, &got[0], &got[1]); +} + +test "granted depths in a shared round fit one hold pass: every block is as deep as the deepest" { + const empty: Table = .{}; + var rule: Rule = .{ .gpa = std.testing.allocator, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; + defer rule.deinit(); + var states: [8]?State = @splat(null); + defer for (&states) |*st| if (st.*) |*x| x.deinit(std.testing.allocator); + var whos: [8]Who = undefined; + for (&whos, &states, 0..) |*w, *st, i| w.* = .{ .state = st, .draft_room = 100, .finished = false, .forced = false, .granted = @intCast(i) }; + const No = struct { + fn copy(_: *anyopaque, _: *const Who) bool { + return false; + } + }; + var unused: u8 = 0; + var out: [8]i64 = undefined; + try rule.budgets(&whos, .{ .ptr = &unused, .copy = No.copy }, false, &out); + // a grant of none probes two; grants 1..7 that took every held draft, plus one; cut to 32 rows over eight blocks + try std.testing.expectEqualSlices(i64, &.{ 2, 2, 3, 4, 4, 4, 4, 4 }, &out); + try rule.budgets(whos[0..2], .{ .ptr = &unused, .copy = No.copy }, false, out[0..2]); + try std.testing.expectEqualSlices(i64, &.{ 2, 2 }, out[0..2]); // two blocks fit whole + for (whos[0..2]) |*w| w.grant_short = true; + try rule.budgets(whos[0..2], .{ .ptr = &unused, .copy = No.copy }, false, out[0..2]); + try std.testing.expectEqualSlices(i64, &.{ 2, 1 }, out[0..2]); // a grant short of the held drafts: no slack +} + +test "a copy ahead: one head draft beside it, or none when the head's drafts cost a pass of their own" { + const empty: Table = .{}; + const Yes = struct { + fn copy(_: *anyopaque, _: *const Who) bool { + return true; + } + }; + var unused: u8 = 0; + const probe: Probe = .{ .ptr = &unused, .copy = Yes.copy }; + var st: ?State = null; + defer if (st) |*x| x.deinit(std.testing.allocator); + const who: Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false, .granted = 3 }; + for ([_]bool{ false, true }) |first| { + var rule: Rule = .{ .gpa = std.testing.allocator, .k = .{ .copy_first = first }, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; + defer rule.deinit(); + try std.testing.expectEqual(@as(i64, @intFromBool(!first)), try rule.headDepth(&who, null, probe)); + var out: [1]i64 = undefined; + var whos = [_]Who{who}; + try rule.budgets(&whos, probe, false, &out); + try std.testing.expectEqual(@as(i64, @intFromBool(!first)), out[0]); + } +} + +test "a granted hold stays only while its stream's expected drafts pay for the verify rows and the hold pass" { + const gpa = std.testing.allocator; + var shared: Table = .{}; + defer shared.deinit(gpa); + for (1..33) |w| try shared.put(gpa, @intCast(w), 10.0 + @as(f64, @floatFromInt(w))); + const empty: Table = .{}; + const cheap = [_]HoldCost{ .{ .streams = 1, .depth = 1, .ms = 1.0 }, .{ .streams = 8, .depth = 1, .ms = 4.5 } }; + var states: [4]?State = @splat(null); + defer for (&states) |*st| if (st.*) |*x| x.deinit(gpa); + const granted = [_]?u32{ 2, 2, 0, 1 }; + const gains = [_]?f64{ 1.8, 0.2, null, 0.9 }; + var whos: [4]Who = undefined; + for (&whos, &states, granted, gains) |*w, *st, g, x| w.* = .{ .state = st, .draft_room = 100, .finished = false, .forced = false, .granted = g, .gain = x }; + var rule: Rule = .{ .gpa = gpa, .k = .{ .hold_costs = &cheap }, .prior = &.{0.8}, .most_drafts = 9, .family_costs = &empty, .shared_costs = &shared, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = true, .granted_depth = true, .batch_rows = 32 }; + defer rule.deinit(); + // 8 ms overhead: plain 4 / 22; stream 0 then 3 raise the rate (5.8 / 25, 6.7 / 26.5), stream 1 would lower it + var out = [_]i64{ 4, 4, 0, 3 }; + try rule.payHolds(&whos, false, &out); + try std.testing.expectEqualSlices(i64, &.{ 4, 0, 0, 3 }, &out); + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + rule.gpa = failing.allocator(); + out = .{ 4, 4, 0, 3 }; + try rule.payHolds(&whos, false, &out); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqualSlices(i64, &.{ 4, 0, 0, 3 }, &out); + rule.gpa = gpa; + const dear = [_]HoldCost{.{ .streams = 1, .depth = 1, .ms = 20.0 }}; + rule.k.hold_costs = &dear; + out = .{ 4, 4, 0, 3 }; + try rule.payHolds(&whos, false, &out); + try std.testing.expectEqualSlices(i64, &.{ 0, 0, 0, 0 }, &out); // no gain pays a 20 ms pass + whos[2].granted = 0; + out = .{ 4, 4, 2, 3 }; + try rule.payHolds(&whos, false, &out); + try std.testing.expectEqualSlices(i64, &.{ 0, 0, 2, 0 }, &out); // a probe after a grant of none keeps its hold +} diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index ced3f315aeb..936d0f841e6 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -23,7 +23,7 @@ const Plan = win.Plan; const f = ev.f; const str = trail.str; const int = trail.int; -const Outcome = struct { got: []const u32, path: []const u32, cut: ?usize, follow: []const u32 }; +pub const Outcome = struct { got: []const u32, path: []const u32, cut: ?usize, follow: []const u32 }; const Result = struct { rows: u32, keep: u32, got: []const u32 }; const Unread = struct { event: usize, handle: u64 }; pub const Engine = struct { @@ -254,78 +254,10 @@ pub const Engine = struct { return .{ .rows = @intCast(rows), .keep = @intCast(o.path.len), .got = o.got }; } - /// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. - fn roundStreams(e: *Engine, entries: []*Stream) !void { - e.clock.start(); - try e.late.flush(e, Engine.askDrafts); - const a = e.arena.allocator(); - const plans = try a.alloc(Plan, entries.len); - for (entries, plans) |s, *p| p.* = try win.plan(e, s, null); - try win.allocate(e, plans); - try @import("grammar_parallel.zig").constrain(e, plans); - const windows = try a.alloc(be.Window, plans.len); - const out = try a.alloc(be.Verified, plans.len); - var total: u64 = 0; - for (plans, windows, out) |p, *w, *o| { - w.* = try win.build(e, p, false); - o.* = .{ .sampled = try a.alloc(u32, w.rows()), .drafts = try a.alloc(u32, w.rows() - 1), .rows = if (p.stream.logprobs != null) try a.alloc(LogRow, w.rows()) else &.{} }; - total += w.rows(); - } - try e.backend.verify(windows, out); - const outcomes = try a.alloc(Outcome, plans.len); - const paths = try a.alloc([]const u32, plans.len); - for (plans, windows, out, outcomes, paths) |p, w, o, *oc, *path| { - const tokens = try win.tokens(e, w, o); - oc.* = try e.conclude(p.stream, p, o.sampled, o.rows, tokens, try win.rowParents(e, w), w.positions); - path.* = oc.path; - const rows: u32 = @intCast(w.rows()); - p.stream.min_rows = if (p.stream.min_rows == 0) rows else @min(p.stream.min_rows, rows); - } - var heads: std.ArrayList(usize) = .empty; - for (plans, 0..) |p, i| { - if (e.cfg.family_mtp and p.stream.drafts) try heads.append(a, i); - } - const whos = try a.alloc(depth.Who, heads.items.len); - for (whos, heads.items) |*w, i| w.* = win.who(plans[i].stream); - const budgets = try a.alloc(i64, heads.items.len); - const sampled = win.anySampled(plans); - if (e.cfg.allocate_shared_drafts) - try @import("shared_drafts.zig").budgets(e, plans, heads.items, budgets) - else - try e.rule.budgets(whos, win.probe(e), sampled, budgets); - const ids = try a.alloc(ev.Value, heads.items.len); - for (ids, heads.items) |*id, i| id.* = str(plans[i].stream.id); - try trail.event(e, &.{ f("ev", str("budgets")), f("streams", .{ .list = ids }), f("depths", .{ .i64s = budgets }) }); - if (heads.items.len > 0 and e.cfg.draft_streams) { - // every stream's head in one batch (the backend drafts a depth for all of them at once) - const requests = try a.alloc(be.DraftRequest, heads.items.len); - for (requests, heads.items, budgets) |*r, i, d| { - const s = plans[i].stream; - r.* = .{ .stream = s, .follow = outcomes[i].follow, .rows = outcomes[i].path, .start = plans[i].position, .position = s.cache_len + 1, .depth = @intCast(d) }; - } - try e.askDrafts(requests); - } else { - for (heads.items, budgets) |i, d| try e.draftLate(plans[i].stream, plans[i].position, outcomes[i].follow, outcomes[i].path, d); - } - if (e.cfg.root_copies) for (heads.items, budgets) |i, *d| { - if (plans[i].stream.next) |held| if (held.count == 0) { - d.* = 0; - }; - }; - try e.backend.keep(windows, paths); - if (e.cfg.timed) { - // the drafts budgets priced past each stream's first are no part of the round's overhead - var steps: i64 = 0; - for (budgets) |d| steps = if (e.cfg.draft_streams and depth.pricedBatched()) @max(steps, d - 1) else steps + @max(0, d - 1); - const ms = e.clock.elapsedMs(.overhead) - e.cfg.draft_step_ms * @as(f64, @floatFromInt(steps)); - try trail.event(e, &.{ f("ev", str("overhead")), f("streams", int(plans.len)), f("rows", int(total)), f("ms", ev.bits(ms)) }); - try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); - } - if (e.backend.round_observer != null) e.backend.observed(paths); - } + const roundStreams = @import("shared_round.zig").run; /// Commit the target-sampled path (after the thinking budget's cut), each token with its path row's logprob row. - fn conclude(e: *Engine, s: *Stream, p: Plan, sampled: []const u32, rows_lp: []const LogRow, tokens: []const u32, parents: []const i32, positions: []const u64) !Outcome { + pub fn conclude(e: *Engine, s: *Stream, p: Plan, sampled: []const u32, rows_lp: []const LogRow, tokens: []const u32, parents: []const i32, positions: []const u64) !Outcome { const a = e.arena.allocator(); const rows = tokens.len; var path: []u32 = undefined; @@ -440,7 +372,7 @@ pub const Engine = struct { } /// Read the kept rows with their following tokens and ask the head for the next round's drafts. - fn draftLate(e: *Engine, s: *Stream, start: u64, follow: []const u32, path: []const u32, budget: ?i64) !void { + pub fn draftLate(e: *Engine, s: *Stream, start: u64, follow: []const u32, path: []const u32, budget: ?i64) !void { var w = win.who(s); const d: u32 = @intCast(try e.rule.headDepth(&w, budget, win.probe(e))); const request: be.DraftRequest = .{ .stream = s, .follow = follow, .rows = path, .start = start, .position = s.cache_len + 1, .depth = d }; @@ -451,7 +383,7 @@ pub const Engine = struct { pub const askDrafts = Engine.askDrafts; } else struct {}; - fn askDrafts(e: *Engine, original: []const be.DraftRequest) !void { + pub fn askDrafts(e: *Engine, original: []const be.DraftRequest) !void { const requests = try @import("root_copy.zig").prepare(e, original); for (requests) |r| try trail.event(e, &.{ f("ev", str("draft")), f("stream", str(r.stream.id)), f("depth", int(r.depth)), f("position", int(r.position)), f("follow", .{ .u32s = r.follow }), f("rows", if (r.rows) |x| .{ .u32s = x } else .null) }); // a lone stream's lanes: the head tree or chain + grafts with the most expected tokens a round time diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index 0a05931b3f9..b2aa247384a 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -57,7 +57,11 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ @memset(out, 0); return; } - const counts = try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, e.rule.overheadMs(@intCast(live), sampled), e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .row_ms = e.rule.row_cost.extraMs(live, sampled), .least_rows = e.rule.row_cost.leastRows(live, sampled) }); + const paired = e.rule.sharedPrice(live, sampled); + const counts = if (paired) |p| + try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, p.fixed, e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = neural, .least_rows = e.rule.row_cost.leastRows(live, sampled) }) + else + try alloc.allocateDrafts(a, fixed, probs, &e.cfg.shared_costs, e.rule.overheadMs(@intCast(live), sampled), e.rule.row_cost.capRows(live, sampled, @max(live, e.cfg.batch_rows)), .{ .row_ms = e.rule.row_cost.extraMs(live, sampled), .least_rows = e.rule.row_cost.leastRows(live, sampled) }); for (heads, out) |i, *budget| { budget.* = if (neural[i]) counts[i] else 0; } @@ -83,7 +87,7 @@ fn costLimits(e: *Engine, plans: []const win.Plan, heads: []const usize, sampled const probe: depth.Probe = .{ .ptr = e, .copy = noCopy }; if (e.cfg.granted_depth) { for (who, out) |*w, *d| d.* = try e.rule.headDepth(w, null, probe); // each stream's grant plus slack, once - } else try e.rule.budgets(who, probe, sampled, out); + } else try e.rule.budgetsFor(who, probe, sampled, out, plans.len); const limits = try a.alloc(u32, plans.len); @memset(limits, e.cfg.most_drafts); for (heads, out) |i, d| limits[i] = @intCast(@max(0, d)); @@ -103,7 +107,7 @@ fn payReserved(e: *Engine, who: []depth.Who, probs: []const []const f64, heads: for (probs[i][0..@min(kept, probs[i].len)]) |chance| gain += chance; w.gain = gain; } - try e.rule.payHolds(who, sampled, out); + try e.rule.payHoldsFor(who, sampled, out, probs.len); } test "shared draft prices: a short cached tree can grow when allocation returns more rows" { diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig new file mode 100644 index 00000000000..2f5528dd94b --- /dev/null +++ b/zig/src/core/lanes/shared_price.zig @@ -0,0 +1,83 @@ +//! Exact-count, exact-mode shared prices: a plain intercept and a drafted row excess. +const std = @import("std"); +const Allocator = std.mem.Allocator; +pub const every: u64 = 64; +pub const stale: u64 = 256; +const Point = struct { residual: f64, rows: f64, at: u64 }; +const Bucket = struct { + streams: usize, + sampled: bool, + rounds: u64 = 0, + last_probe: u64 = 0, + plain: ?Point = null, + draft: ?Point = null, +}; +pub const Price = struct { plain: f64, fixed: f64, row: f64 }; + +pub const Prices = struct { + buckets: std.ArrayList(Bucket) = .empty, + + pub fn deinit(p: *Prices, a: Allocator) void { + p.buckets.deinit(a); + } + + fn find(p: *const Prices, streams: usize, sampled: bool) ?usize { + for (p.buckets.items, 0..) |b, i| if (b.streams == streams and b.sampled == sampled) return i; + return null; + } + + fn get(p: *Prices, a: Allocator, streams: usize, sampled: bool) !*Bucket { + if (p.find(streams, sampled)) |i| return &p.buckets.items[i]; + try p.buckets.append(a, .{ .streams = streams, .sampled = sampled }); + return &p.buckets.items[p.buckets.items.len - 1]; + } + + /// Missing/stale plain prices earn a trial on round 64, then at least 64 completed rounds apart. + pub fn due(p: *Prices, a: Allocator, streams: usize, sampled: bool) !bool { + const b = try p.get(a, streams, sampled); + const next = b.rounds +| 1; + const old = if (b.plain) |v| next -| v.at >= stale else true; + return old and next -| b.last_probe >= every; + } + + /// The plain intercept is never updated by a round that verifies or prepares any draft. + pub fn observe(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, sampled: bool, plain: bool, calibration: bool) !void { + const b = try p.get(a, streams, sampled); + b.rounds +|= 1; + if (calibration) b.last_probe = b.rounds; + if (!std.math.isFinite(residual)) return; + const point: Point = .{ .residual = residual, .rows = @floatFromInt(rows), .at = b.rounds }; + if (plain and rows == streams) { + blend(&b.plain, point); + } else if (rows > streams) blend(&b.draft, point); + } + + /// Before a plain observation, its independent prior is 8 ms, never the drafted residual. + pub fn price(p: *const Prices, streams: usize, sampled: bool, fallback: f64, row: f64) ?Price { + const b = p.buckets.items[p.find(streams, sampled) orelse return null]; + var out: Price = .{ .plain = 8, .fixed = fallback, .row = row }; + const plain = b.plain orelse return out; + out.plain = plain.residual; + out.fixed = plain.residual; + if (b.draft) |draft| if (draft.rows > plain.rows) { + out.row = @max(0, (draft.residual - plain.residual) / (draft.rows - plain.rows)); + }; + return out; + } +}; + +fn blend(to: *?Point, v: Point) void { + if (to.*) |*old| { + old.residual += 0.2 * (v.residual - old.residual); + old.rows += 0.2 * (v.rows - old.rows); + old.at = v.at; + } else to.* = v; +} + +/// Explicit confidence, custom family trim and forced tokens retain their own policies. +pub fn calibrate(e: anytype, plans: anytype) !bool { + if (!e.cfg.timed or !e.cfg.family_mtp or !e.cfg.plain_guard or e.cfg.draft_confidence != null or + e.trim != null or plans.len < 2 or e.cfg.shared_costs.empty()) return false; + for (plans) |p| if (p.kind == .forced or p.stream.rounds == 0) return false; + return e.rule.shared_price.due(e.gpa, plans.len, @import("windows.zig").anySampled(plans)); +} diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig new file mode 100644 index 00000000000..1d599e15635 --- /dev/null +++ b/zig/src/core/lanes/shared_price_test.zig @@ -0,0 +1,144 @@ +//! Independent shared-price controls through the real allocator and a host fake target. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const prices = @import("shared_price.zig"); +const fake = @import("fake.zig"); +const be = @import("backend.zig"); +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const Config = @import("config.zig").Config; + +const Clock = struct { + target: *fake.Fake, + row_ms: f64, + fn clock(c: *@This()) be.Clock { + return .{ .ptr = c, .vtable = &.{ .start = start, .elapsed_ms = elapsed } }; + } + fn start(_: *anyopaque) void {} + fn elapsed(ptr: *anyopaque, _: be.Mark) f64 { + const c: *@This() = @ptrCast(@alignCast(ptr)); + return 12 + c.row_ms * @as(f64, @floatFromInt(c.target.last_rows -| 2)); + } +}; + +fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { + var conf = try Config.init(a, .{ .exact_width = 4, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 1, .draft_prior = &.{0.8}, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 4, .ms = 10 } }, .plain_guard = true, .hidden_rows = true }, 4, 3); + defer conf.deinit(a); + var target: fake.Fake = .{ .gpa = a, .head_accepts = 1 }; + defer target.deinit(); + var clock: Clock = .{ .target = &target, .row_ms = row_ms }; + var e = Engine.init(a, &conf, target.backend(), clock.clock()); + defer e.deinit(); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + for (&streams) |*s| { + s.* = try Stream.init(a, .{ .id = "price", .prompt = &.{ 1, 2, 3 }, .max_new = 800, .eos = &.{}, .drafts = !plain_only, .sampling = if (sampled) .{ .seed = 19, .temperature = 0.7 } else null }); + made += 1; + try e.addStream(s); + } + var previous_probe: usize = 0; + var probes: usize = 0; + var drafted_before: usize = 0; + var drafted_after: usize = 0; + var round: usize = 0; + while (e.activeCount() > 0) { + round += 1; + const due = if (!plain_only) try e.rule.shared_price.due(a, 2, sampled) else false; + try e.step(); + if (plain_only) continue; + if (due and target.last_rows == 2) { + try t.expect(round - previous_probe >= 64); + previous_probe = round; + probes += 1; + } + if (round < 64) drafted_before += @intFromBool(target.last_rows > 2); + if (round > 65 and e.activeCount() == 2) drafted_after += @intFromBool(target.last_rows > 2); + if (round == 64) { + const p = e.rule.sharedPrice(2, sampled).?; + try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); + try t.expectApproxEqAbs(row_ms, p.row, 1e-9); + } + if (row_ms > 5 and round == 65) try t.expectEqual(@as(usize, 2), target.last_rows); + } + if (!plain_only) { + try t.expect(drafted_before > 32); + if (row_ms > 5) try t.expectEqual(@as(usize, 0), drafted_after) else { + try t.expect(drafted_after > 200); + try t.expect(probes >= 2 and probes <= (round + 63) / 64); + } + } + var out: [2][800]u32 = undefined; + for (&out, &streams) |*tokens, s| { + try t.expectEqual(tokens.len, s.emitted().len); + @memcpy(tokens, s.emitted()); + } + return out; +} + +test "shared prices: cheaper plain wins after its first measurement and target tokens stay exact" { + for ([_]bool{ false, true }) |sampled| { + const oracle = try run(sampled, 9, true); + const got = try run(sampled, 9, false); + try t.expectEqualDeep(oracle, got); + } +} + +test "shared prices: profitable drafts keep winning with bounded plain calibration and exact tokens" { + for ([_]bool{ false, true }) |sampled| { + const oracle = try run(sampled, 0.5, true); + const got = try run(sampled, 0.5, false); + try t.expectEqualDeep(oracle, got); + } +} + +test "shared prices: missing and stale trials obey exact independent count and mode clocks" { + var p: prices.Prices = .{}; + defer p.deinit(a); + for (1..641) |round| { + const due = try p.due(a, 4, true); + try t.expectEqual(round == 64 or round == 320 or round == 576, due); + try t.expect(!try p.due(a, 4, false)); + try t.expect(!try p.due(a, 2, true)); + // Rechecking without completing a round cannot spend another calibration or age another mode. + try t.expectEqual(due, try p.due(a, 4, true)); + try p.observe(a, 4, if (due) 4 else 8, if (due) 2 else 6, true, due, due); + } + // A completed calibration that failed to measure a plain width still respects the 64-round spacing. + var q: prices.Prices = .{}; + defer q.deinit(a); + for (1..193) |round| { + const due = try q.due(a, 2, false); + try t.expectEqual(round % 64 == 0, due); + try q.observe(a, 2, 4, 12, false, false, due); + } +} + +test "shared prices: drafted work at plain width cannot update the intercept; two-point fit separates rows" { + var p: prices.Prices = .{}; + defer p.deinit(a); + try p.observe(a, 4, 4, 50, false, false, false); + try t.expectEqual(@as(f64, 8), p.price(4, false, 50, 0).?.plain); + try p.observe(a, 4, 4, 2, false, true, false); + try p.observe(a, 4, 8, 10, false, false, false); + const v = p.price(4, false, 100, 99).?; + try t.expectEqual(@as(f64, 2), v.plain); + try t.expectEqual(@as(f64, 2), v.fixed); + try t.expectEqual(@as(f64, 2), v.row); + try t.expect(p.price(4, true, 0, 0) == null); + try t.expect(p.price(2, false, 0, 0) == null); +} + +test "shared prices: the round observer subtracts modeled heads before fitting rows" { + var table: @import("table.zig").Table = .{}; + defer table.deinit(a); + for (1..9) |n| try table.put(a, @intCast(n), 10); + var r: @import("depth.zig").Rule = .{ .gpa = a, .prior = &.{0.8}, .most_drafts = 1, .family_costs = &table, .shared_costs = &table, .mtp_step_ms = 3, .plain_guard = true, .node_probabilities = false, .batch_rows = 8 }; + defer r.deinit(); + try r.observeShared(4, 4, 12, false, 0, true, false); + try r.observeShared(4, 8, 32, false, 12, false, false); + try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.row); + try r.observeShared(4, 4, 100, false, 12, false, false); + try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.plain); +} diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig new file mode 100644 index 00000000000..61ccce82b9c --- /dev/null +++ b/zig/src/core/lanes/shared_round.zig @@ -0,0 +1,94 @@ +//! Shared verification and draft scheduling, with bounded all-plain calibration rounds. +const std = @import("std"); +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const Plan = win.Plan; +const Outcome = @import("engine.zig").Outcome; +const LogRow = @import("logprob.zig").Row; +const win = @import("windows.zig"); +const be = @import("backend.zig"); +const depth = @import("depth.zig"); +const ev = @import("events.zig"); +const trail = @import("trail.zig"); +const f = ev.f; +const str = trail.str; +const int = trail.int; + +/// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. +pub fn run(e: *Engine, entries: []*Stream) !void { + e.clock.start(); + try e.late.flush(e, Engine.askDrafts); + const a = e.arena.allocator(); + const plans = try a.alloc(Plan, entries.len); + for (entries, plans) |s, *p| p.* = try win.plan(e, s, null); + const sampled = win.anySampled(plans); + const calibration = try @import("shared_price.zig").calibrate(e, plans); + if (calibration) { + // The flushed draft belonged to the preceding lone round; it is not a plain shared cost. + e.clock.start(); + for (plans) |*p| try @import("window_cut.zig").prefix(a, p, 0); + } else try win.allocate(e, plans); + try @import("grammar_parallel.zig").constrain(e, plans); + const windows = try a.alloc(be.Window, plans.len); + const out = try a.alloc(be.Verified, plans.len); + var total: u64 = 0; + for (plans, windows, out) |p, *w, *o| { + w.* = try win.build(e, p, false); + o.* = .{ .sampled = try a.alloc(u32, w.rows()), .drafts = try a.alloc(u32, w.rows() - 1), .rows = if (p.stream.logprobs != null) try a.alloc(LogRow, w.rows()) else &.{} }; + total += w.rows(); + } + try e.backend.verify(windows, out); + const outcomes = try a.alloc(Outcome, plans.len); + const paths = try a.alloc([]const u32, plans.len); + for (plans, windows, out, outcomes, paths) |p, w, o, *oc, *path| { + const tokens = try win.tokens(e, w, o); + oc.* = try e.conclude(p.stream, p, o.sampled, o.rows, tokens, try win.rowParents(e, w), w.positions); + path.* = oc.path; + const rows: u32 = @intCast(w.rows()); + p.stream.min_rows = if (p.stream.min_rows == 0) rows else @min(p.stream.min_rows, rows); + } + var heads: std.ArrayList(usize) = .empty; + for (plans, 0..) |p, i| { + if (e.cfg.family_mtp and p.stream.drafts) try heads.append(a, i); + } + const whos = try a.alloc(depth.Who, heads.items.len); + for (whos, heads.items) |*w, i| w.* = win.who(plans[i].stream); + const budgets = try a.alloc(i64, heads.items.len); + if (calibration) + @memset(budgets, 0) + else if (e.cfg.allocate_shared_drafts) + try @import("shared_drafts.zig").budgets(e, plans, heads.items, budgets) + else + try e.rule.budgetsFor(whos, win.probe(e), sampled, budgets, plans.len); + const ids = try a.alloc(ev.Value, heads.items.len); + for (ids, heads.items) |*id, i| id.* = str(plans[i].stream.id); + try trail.event(e, &.{ f("ev", str("budgets")), f("streams", .{ .list = ids }), f("depths", .{ .i64s = budgets }) }); + if (heads.items.len > 0 and e.cfg.draft_streams) { + // every stream's head in one batch (the backend drafts a depth for all of them at once) + const requests = try a.alloc(be.DraftRequest, heads.items.len); + for (requests, heads.items, budgets) |*r, i, d| { + const s = plans[i].stream; + r.* = .{ .stream = s, .follow = outcomes[i].follow, .rows = outcomes[i].path, .start = plans[i].position, .position = s.cache_len + 1, .depth = @intCast(d) }; + } + try e.askDrafts(requests); + } else { + for (heads.items, budgets) |i, d| try e.draftLate(plans[i].stream, plans[i].position, outcomes[i].follow, outcomes[i].path, d); + } + if (e.cfg.root_copies) for (heads.items, budgets) |i, *d| { + if (plans[i].stream.next) |held| if (held.count == 0) { + d.* = 0; + }; + }; + try e.backend.keep(windows, paths); + if (e.cfg.timed) { + // the drafts budgets priced past each stream's first are no part of the round's overhead + var steps: i64 = 0; + for (budgets) |d| steps = if (e.cfg.draft_streams and depth.pricedBatched()) @max(steps, d - 1) else steps + @max(0, d - 1); + const ms = e.clock.elapsedMs(.overhead) - e.cfg.draft_step_ms * @as(f64, @floatFromInt(steps)); + try trail.event(e, &.{ f("ev", str("overhead")), f("streams", int(plans.len)), f("rows", int(total)), f("ms", ev.bits(ms)) }); + var plain = total == plans.len; + for (budgets) |d| plain = plain and d == 0; + try e.rule.observeShared(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets), plain, calibration); + } + if (e.backend.round_observer != null) e.backend.observed(paths); +} diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index 0d93234bfee..51188936ef0 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -291,7 +291,13 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const own = if (live) try lone_costs.prices(e, plans[0]) else untimed; const costs = if (explicit) &untimed else if (live) &own else &e.cfg.shared_costs; const overhead = if (explicit or live) 0 else e.rule.overheadMs(plans.len, anySampled(plans)); - const counts = try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); + const paired = if (explicit or live) null else e.rule.sharedPrice(plans.len, anySampled(plans)); + const heads = try a.alloc(bool, plans.len); + for (plans, heads) |p, *h| h.* = p.kind == .head; + const counts = if (paired) |p| + try alloc.allocateDrafts(a, fixed, probs, costs, p.fixed, e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = heads, .least_rows = e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }) + else + try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); const trial = if (live) lone_costs.probe(e, plans[0]) else null; if (trial) |count| { counts[0] = count; From e543c0bd2a0b5de5cb0a3990f259616c1b70fd81 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:21:10 +0000 Subject: [PATCH 24/59] Exclude preceding deferred work from shared round timing --- zig/src/core/lanes/shared_round.zig | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 61ccce82b9c..67af251a8f4 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -16,16 +16,15 @@ const int = trail.int; /// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. pub fn run(e: *Engine, entries: []*Stream) !void { - e.clock.start(); try e.late.flush(e, Engine.askDrafts); + // A deferred lone draft belongs to the preceding round, not this shared round. + e.clock.start(); const a = e.arena.allocator(); const plans = try a.alloc(Plan, entries.len); for (entries, plans) |s, *p| p.* = try win.plan(e, s, null); const sampled = win.anySampled(plans); const calibration = try @import("shared_price.zig").calibrate(e, plans); if (calibration) { - // The flushed draft belonged to the preceding lone round; it is not a plain shared cost. - e.clock.start(); for (plans) |*p| try @import("window_cut.zig").prefix(a, p, 0); } else try win.allocate(e, plans); try @import("grammar_parallel.zig").constrain(e, plans); From 193a569882bbf8b7726d6aabef3f3097f1bd6383 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:23:28 +0000 Subject: [PATCH 25/59] Calibrate copied shared rounds when plain competes --- zig/src/core/lanes/shared_price.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index 2f5528dd94b..61bf1185fa1 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -76,7 +76,7 @@ fn blend(to: *?Point, v: Point) void { /// Explicit confidence, custom family trim and forced tokens retain their own policies. pub fn calibrate(e: anytype, plans: anytype) !bool { - if (!e.cfg.timed or !e.cfg.family_mtp or !e.cfg.plain_guard or e.cfg.draft_confidence != null or + if (!e.cfg.timed or !e.cfg.plain_guard or e.cfg.draft_confidence != null or e.trim != null or plans.len < 2 or e.cfg.shared_costs.empty()) return false; for (plans) |p| if (p.kind == .forced or p.stream.rounds == 0) return false; return e.rule.shared_price.due(e.gpa, plans.len, @import("windows.zig").anySampled(plans)); From 1463d69680cb4123b7b411cbacbae7d13ff2ea9f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:30:08 +0000 Subject: [PATCH 26/59] Keep existing shared choices until a plain round is measured --- zig/src/core/lanes/depth.zig | 2 +- zig/src/core/lanes/shared_drafts.zig | 9 ++- zig/src/core/lanes/shared_price.zig | 10 ++-- zig/src/core/lanes/shared_price_test.zig | 70 ++++++++++++++++++++++-- zig/src/core/lanes/shared_round.zig | 23 +++++--- zig/src/core/lanes/windows.zig | 11 ++-- 6 files changed, 99 insertions(+), 26 deletions(-) diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index a265e587890..d826fd18099 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -388,7 +388,7 @@ pub const Rule = struct { /// Independent plain price and the row slope from a plain/drafted pair, at this exact count and mode. pub fn sharedPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { if (streams < 2 or !r.plain_guard or r.confidence_floor != null) return null; - return r.shared_price.price(streams, sampled, r.fixedMs(streams, sampled), r.row_cost.extraMs(streams, sampled)); + return r.shared_price.price(streams, sampled, r.row_cost.extraMs(streams, sampled)); } /// Only completed timed shared rounds advance this count/mode's calibration clock. diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index b2aa247384a..d0b005bb997 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -87,7 +87,9 @@ fn costLimits(e: *Engine, plans: []const win.Plan, heads: []const usize, sampled const probe: depth.Probe = .{ .ptr = e, .copy = noCopy }; if (e.cfg.granted_depth) { for (who, out) |*w, *d| d.* = try e.rule.headDepth(w, null, probe); // each stream's grant plus slack, once - } else try e.rule.budgetsFor(who, probe, sampled, out, plans.len); + } else if (e.cfg.plain_guard) { + try e.rule.budgetsFor(who, probe, sampled, out, plans.len); + } else try e.rule.budgets(who, probe, sampled, out); const limits = try a.alloc(u32, plans.len); @memset(limits, e.cfg.most_drafts); for (heads, out) |i, d| limits[i] = @intCast(@max(0, d)); @@ -107,7 +109,10 @@ fn payReserved(e: *Engine, who: []depth.Who, probs: []const []const f64, heads: for (probs[i][0..@min(kept, probs[i].len)]) |chance| gain += chance; w.gain = gain; } - try e.rule.payHoldsFor(who, sampled, out, probs.len); + if (e.cfg.plain_guard) + try e.rule.payHoldsFor(who, sampled, out, probs.len) + else + try e.rule.payHolds(who, sampled, out); } test "shared draft prices: a short cached tree can grow when allocation returns more rows" { diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index 61bf1185fa1..4a4ea42e3b8 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -52,13 +52,11 @@ pub const Prices = struct { } else if (rows > streams) blend(&b.draft, point); } - /// Before a plain observation, its independent prior is 8 ms, never the drafted residual. - pub fn price(p: *const Prices, streams: usize, sampled: bool, fallback: f64, row: f64) ?Price { + /// Until a plain round is measured, leave the existing allocator and its draft ranking in charge. + pub fn price(p: *const Prices, streams: usize, sampled: bool, row: f64) ?Price { const b = p.buckets.items[p.find(streams, sampled) orelse return null]; - var out: Price = .{ .plain = 8, .fixed = fallback, .row = row }; - const plain = b.plain orelse return out; - out.plain = plain.residual; - out.fixed = plain.residual; + const plain = b.plain orelse return null; + var out: Price = .{ .plain = plain.residual, .fixed = plain.residual, .row = row }; if (b.draft) |draft| if (draft.rows > plain.rows) { out.row = @max(0, (draft.residual - plain.residual) / (draft.rows - plain.rows)); }; diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index 1d599e15635..0eb2423b768 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -119,15 +119,15 @@ test "shared prices: drafted work at plain width cannot update the intercept; tw var p: prices.Prices = .{}; defer p.deinit(a); try p.observe(a, 4, 4, 50, false, false, false); - try t.expectEqual(@as(f64, 8), p.price(4, false, 50, 0).?.plain); + try t.expect(p.price(4, false, 0) == null); try p.observe(a, 4, 4, 2, false, true, false); try p.observe(a, 4, 8, 10, false, false, false); - const v = p.price(4, false, 100, 99).?; + const v = p.price(4, false, 99).?; try t.expectEqual(@as(f64, 2), v.plain); try t.expectEqual(@as(f64, 2), v.fixed); try t.expectEqual(@as(f64, 2), v.row); - try t.expect(p.price(4, true, 0, 0) == null); - try t.expect(p.price(2, false, 0, 0) == null); + try t.expect(p.price(4, true, 0) == null); + try t.expect(p.price(2, false, 0) == null); } test "shared prices: the round observer subtracts modeled heads before fitting rows" { @@ -142,3 +142,65 @@ test "shared prices: the round observer subtracts modeled heads before fitting r try r.observeShared(4, 4, 100, false, 12, false, false); try t.expectEqual(@as(f64, 2), r.sharedPrice(4, false).?.plain); } + +test "shared prices: an unmeasured plain option keeps main's winning drafted width" { + var table: @import("table.zig").Table = .{}; + defer table.deinit(a); + for (1..13) |n| try table.put(a, @intCast(n), 10 + 2 * @as(f64, @floatFromInt(n))); + var r: @import("depth.zig").Rule = .{ .gpa = a, .prior = &.{0.2}, .most_drafts = 1, .family_costs = &table, .shared_costs = &table, .mtp_step_ms = 0, .plain_guard = true, .node_probabilities = false, .batch_rows = 12 }; + defer r.deinit(); + try r.observeShared(4, 8, table.get(8).? + 50, false, 0, false, false); + const old = r.overheadMs(4, false); + const paired = r.sharedPrice(4, false); + const probs = [_][]const f64{ &.{0.2}, &.{0.2}, &.{0.2}, &.{0.2} }; + const counts = try @import("allocate.zig").allocateDrafts(a, &.{ 1, 1, 1, 1 }, &probs, &table, if (paired) |p| p.fixed else old, 12, .{ .plain_ms = if (paired) |p| p.plain else null }); + defer a.free(counts); + try t.expectEqualSlices(u32, &.{ 1, 1, 1, 1 }, counts); + try r.observeShared(4, 4, table.get(4).? + 2, false, 0, true, false); + const p = r.sharedPrice(4, false).?; + const measured = try @import("allocate.zig").allocateDrafts(a, &.{ 1, 1, 1, 1 }, &probs, &table, p.fixed, 12, .{ .plain_ms = p.plain, .row_ms = p.row }); + defer a.free(measured); + try t.expectEqualSlices(u32, &.{ 0, 0, 0, 0 }, measured); +} + +test "shared prices: only independent plain timing excludes a preceding deferred draft" { + const ClockAtDraft = struct { + target: *fake.Fake, + at: usize = 0, + fn clock(c: *@This()) be.Clock { + return .{ .ptr = c, .vtable = &.{ .start = start, .elapsed_ms = elapsed } }; + } + fn start(ptr: *anyopaque) void { + const c: *@This() = @ptrCast(@alignCast(ptr)); + c.at = c.target.drafts_calls; + } + fn elapsed(ptr: *anyopaque, _: be.Mark) f64 { + const c: *@This() = @ptrCast(@alignCast(ptr)); + return 20 + 5 * @as(f64, @floatFromInt(c.target.drafts_calls - c.at)); + } + }; + for ([_]bool{ false, true }) |independent| { + var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 1, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 10 } }, .plain_guard = independent, .hidden_rows = true }, 8, 7); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a, .head_accepts = 1 }; + defer target.deinit(); + var clock: ClockAtDraft = .{ .target = &target }; + var backend = target.backend(); + backend.defer_lone_draft = true; + var e = Engine.init(a, &cfg, backend, clock.clock()); + defer e.deinit(); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + for (&streams, 0..) |*s, i| { + s.* = try Stream.init(a, .{ .id = "timing", .prompt = &.{ 1, 2, 3 }, .max_new = 40 }); + made += 1; + try e.addStream(s); + if (i == 0) try e.step(); + } + try t.expect(e.late.request != null); + try e.step(); + try t.expectEqual(target.drafts_calls - @as(usize, if (independent) 2 else 3), clock.at); + try t.expectEqual(@as(usize, 0), e.rule.shared_price.buckets.items.len - @intFromBool(independent)); + } +} diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 67af251a8f4..4de578fe92e 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -16,14 +16,19 @@ const int = trail.int; /// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. pub fn run(e: *Engine, entries: []*Stream) !void { + return if (e.cfg.plain_guard) runPriced(e, entries, true) else runPriced(e, entries, false); +} + +fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { + if (!independent) e.clock.start(); try e.late.flush(e, Engine.askDrafts); - // A deferred lone draft belongs to the preceding round, not this shared round. - e.clock.start(); + // Only the independent plain measurement excludes a preceding lone draft. + if (independent) e.clock.start(); const a = e.arena.allocator(); const plans = try a.alloc(Plan, entries.len); for (entries, plans) |s, *p| p.* = try win.plan(e, s, null); const sampled = win.anySampled(plans); - const calibration = try @import("shared_price.zig").calibrate(e, plans); + const calibration = independent and try @import("shared_price.zig").calibrate(e, plans); if (calibration) { for (plans) |*p| try @import("window_cut.zig").prefix(a, p, 0); } else try win.allocate(e, plans); @@ -57,8 +62,10 @@ pub fn run(e: *Engine, entries: []*Stream) !void { @memset(budgets, 0) else if (e.cfg.allocate_shared_drafts) try @import("shared_drafts.zig").budgets(e, plans, heads.items, budgets) + else if (independent) + try e.rule.budgetsFor(whos, win.probe(e), sampled, budgets, plans.len) else - try e.rule.budgetsFor(whos, win.probe(e), sampled, budgets, plans.len); + try e.rule.budgets(whos, win.probe(e), sampled, budgets); const ids = try a.alloc(ev.Value, heads.items.len); for (ids, heads.items) |*id, i| id.* = str(plans[i].stream.id); try trail.event(e, &.{ f("ev", str("budgets")), f("streams", .{ .list = ids }), f("depths", .{ .i64s = budgets }) }); @@ -85,9 +92,11 @@ pub fn run(e: *Engine, entries: []*Stream) !void { for (budgets) |d| steps = if (e.cfg.draft_streams and depth.pricedBatched()) @max(steps, d - 1) else steps + @max(0, d - 1); const ms = e.clock.elapsedMs(.overhead) - e.cfg.draft_step_ms * @as(f64, @floatFromInt(steps)); try trail.event(e, &.{ f("ev", str("overhead")), f("streams", int(plans.len)), f("rows", int(total)), f("ms", ev.bits(ms)) }); - var plain = total == plans.len; - for (budgets) |d| plain = plain and d == 0; - try e.rule.observeShared(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets), plain, calibration); + if (independent) { + var plain = total == plans.len; + for (budgets) |d| plain = plain and d == 0; + try e.rule.observeShared(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets), plain, calibration); + } else try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); } if (e.backend.round_observer != null) e.backend.observed(paths); } diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index 51188936ef0..16a6050928f 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -292,12 +292,11 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const costs = if (explicit) &untimed else if (live) &own else &e.cfg.shared_costs; const overhead = if (explicit or live) 0 else e.rule.overheadMs(plans.len, anySampled(plans)); const paired = if (explicit or live) null else e.rule.sharedPrice(plans.len, anySampled(plans)); - const heads = try a.alloc(bool, plans.len); - for (plans, heads) |p, *h| h.* = p.kind == .head; - const counts = if (paired) |p| - try alloc.allocateDrafts(a, fixed, probs, costs, p.fixed, e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = heads, .least_rows = e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }) - else - try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); + const counts = if (paired) |p| blk: { + const heads = try a.alloc(bool, plans.len); + for (plans, heads) |window, *h| h.* = window.kind == .head; + break :blk try alloc.allocateDrafts(a, fixed, probs, costs, p.fixed, e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = heads, .least_rows = e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); + } else try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); const trial = if (live) lone_costs.probe(e, plans[0]) else null; if (trial) |count| { counts[0] = count; From a7247a8570726d9d6d2a431cf6ca3ea2de729a2d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:32:27 +0000 Subject: [PATCH 27/59] Assert that the calibration fixture measured plain before reading it --- zig/src/core/lanes/shared_price_test.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index 0eb2423b768..13106a4fe62 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -56,6 +56,7 @@ fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { if (round < 64) drafted_before += @intFromBool(target.last_rows > 2); if (round > 65 and e.activeCount() == 2) drafted_after += @intFromBool(target.last_rows > 2); if (round == 64) { + try t.expect(e.rule.sharedPrice(2, sampled) != null); const p = e.rule.sharedPrice(2, sampled).?; try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); try t.expectApproxEqAbs(row_ms, p.row, 1e-9); From 58a719e6a6cbaa89f759ad6b9dae572159cf0989 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:14:59 +0000 Subject: [PATCH 28/59] Keep held drafts free of another drafting charge --- zig/src/core/lanes/depth.zig | 10 +++++ .../core/lanes/shared_verify_price_test.zig | 42 +++++++++++++++++++ zig/src/core/lanes/windows.zig | 11 +++-- 3 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 zig/src/core/lanes/shared_verify_price_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index d826fd18099..0f6a4e6ce99 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -391,6 +391,15 @@ pub const Rule = struct { return r.shared_price.price(streams, sampled, r.row_cost.extraMs(streams, sampled)); } + /// Held drafts have already run; every verify option retains the round's same head fixed cost. + pub fn verifyPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { + var price = r.sharedPrice(streams, sampled) orelse return null; + const head = if (r.nearest(streams, sampled)) |o| o.head else 0; + price.plain += head; + price.fixed += head; + return price; + } + /// Only completed timed shared rounds advance this count/mode's calibration clock. pub fn observeShared(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { if (streams > 1 and r.plain_guard and r.confidence_floor == null) { @@ -469,6 +478,7 @@ fn distance(a: u32, b: usize) usize { test { _ = @import("depth_test.zig"); _ = @import("shared_price_test.zig"); + _ = @import("shared_verify_price_test.zig"); } test { diff --git a/zig/src/core/lanes/shared_verify_price_test.zig b/zig/src/core/lanes/shared_verify_price_test.zig new file mode 100644 index 00000000000..6adb605f3fb --- /dev/null +++ b/zig/src/core/lanes/shared_verify_price_test.zig @@ -0,0 +1,42 @@ +//! Width selection spends rows on drafts already held; producing the next drafts is priced separately. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const Config = @import("config.zig").Config; +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +fn held(step_ms: f64, observed_head: f64, residual: f64, chance: f64) ![2]usize { + var cfg = try Config.init(a, .{ .exact_width = 4, .mtp = true, .drafts = 1, .draft_prior = &.{chance}, .mtp_step_ms = step_ms, .plain_guard = true, .hidden_rows = true, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 4, .ms = 10 } } }, 4, 3); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + try e.rule.observeShared(2, 2, 12, false, 0, true, false); + try e.rule.observeShared(2, 4, 12 + residual + observed_head, false, observed_head, false, false); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [2]win.Plan = undefined; + for (&streams, &plans) |*s, *p| { + s.* = try Stream.init(a, .{ .id = "held", .prompt = &.{1}, .max_new = 64 }); + made += 1; + p.* = .{ .stream = s, .position = 1, .kind = .head, .tokens = &.{7} }; + } + try win.allocate(&e, &plans); + return .{ plans[0].count(), plans[1].count() }; +} + +test "shared prices: verify never pays another step for an existing draft" { + try t.expectEqual([2]usize{ 1, 1 }, try held(3, 0, 1, 0.5)); + try t.expectEqual([2]usize{ 1, 1 }, try held(300, 0, 1, 0.5)); +} + +test "shared prices: each verify option retains the same measured head fixed cost" { + try t.expectEqual([2]usize{ 0, 0 }, try held(0, 0, 8, 0.4)); + try t.expectEqual([2]usize{ 1, 1 }, try held(0, 200, 8, 0.4)); +} diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index 16a6050928f..f9f0b3ddb72 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -291,12 +291,11 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { const own = if (live) try lone_costs.prices(e, plans[0]) else untimed; const costs = if (explicit) &untimed else if (live) &own else &e.cfg.shared_costs; const overhead = if (explicit or live) 0 else e.rule.overheadMs(plans.len, anySampled(plans)); - const paired = if (explicit or live) null else e.rule.sharedPrice(plans.len, anySampled(plans)); - const counts = if (paired) |p| blk: { - const heads = try a.alloc(bool, plans.len); - for (plans, heads) |window, *h| h.* = window.kind == .head; - break :blk try alloc.allocateDrafts(a, fixed, probs, costs, p.fixed, e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .step_ms = e.cfg.mtp_step_ms, .extra_step_ms = e.cfg.draft_step_ms, .batched = e.cfg.draft_streams and depth.pricedBatched(), .heads = heads, .least_rows = e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); - } else try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); + const paired = if (explicit or live) null else e.rule.verifyPrice(plans.len, anySampled(plans)); + const counts = if (paired) |p| + try alloc.allocateDrafts(a, fixed, probs, costs, p.fixed, e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .plain_ms = p.plain, .row_ms = p.row, .least_rows = e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }) + else + try alloc.allocateDrafts(a, fixed, probs, costs, overhead, if (explicit or live) @max(plans.len, e.cfg.batch_rows) else e.rule.row_cost.capRows(plans.len, anySampled(plans), @max(plans.len, e.cfg.batch_rows)), .{ .row_ms = if (explicit or live) 0 else e.rule.row_cost.extraMs(plans.len, anySampled(plans)), .least_rows = if (explicit or live) 0 else e.rule.row_cost.leastRows(plans.len, anySampled(plans)) }); const trial = if (live) lone_costs.probe(e, plans[0]) else null; if (trial) |count| { counts[0] = count; From 5328641f4cfd1b5da97b2f17ac9524bbcbd5d79d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:17:56 +0000 Subject: [PATCH 29/59] Keep unmeasured shared prices on the original head rule --- zig/src/core/lanes/depth.zig | 13 ++-- zig/src/core/lanes/shared_price_test.zig | 9 +-- zig/src/core/lanes/shared_round.zig | 11 +++- zig/src/core/lanes/shared_warm_price_test.zig | 66 +++++++++++++++++++ 4 files changed, 87 insertions(+), 12 deletions(-) create mode 100644 zig/src/core/lanes/shared_warm_price_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 0f6a4e6ce99..bdf57b83a30 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -242,7 +242,7 @@ pub const Rule = struct { return r.payHoldsFor(whos, sampled, out, whos.len); } - pub fn payHoldsFor(r: *Rule, whos: []const Who, sampled: bool, out: []i64, streams: usize) !void { + pub fn payHoldsFor(r: *Rule, whos: []const Who, sampled: bool, out: []i64, total_streams: usize) !void { if (whos.len > r.batch_rows) return error.BadHoldStreamCount; if (r.hold_order.len == 0) r.hold_order = try r.gpa.alloc(usize, r.batch_rows); const order = r.hold_order[0..whos.len]; @@ -270,7 +270,8 @@ pub const Rule = struct { } }; std.mem.sort(usize, order[0..m], Ctx{ .r = r, .whos = whos }, Ctx.less); - const paired = r.sharedPrice(streams, sampled); + const paired = r.sharedPrice(total_streams, sampled); + const streams = if (paired != null) total_streams else whos.len; const fixed = if (paired) |p| p.fixed else r.fixedMs(streams, sampled); var rows: f64 = @floatFromInt(streams); var tokens = rows; @@ -309,7 +310,9 @@ pub const Rule = struct { } /// Non-head streams still contribute their plain rows to a shared round's width and exact-count price. - pub fn budgetsFor(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64, streams: usize) !void { + pub fn budgetsFor(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64, total_streams: usize) !void { + const paired = r.sharedPrice(total_streams, sampled); + const streams = if (paired != null) total_streams else whos.len; // drafts lose here: none asked, no head pass if (r.plain_streams > 0 and whos.len >= r.plain_streams) return @memset(out, 0); if (r.confidence_floor != null) { @@ -323,7 +326,7 @@ pub const Rule = struct { o.* = if (r.granted_depth) inner else try r.headDepth(w, @min(inner, granted + r.k.draft_slack), probe); } if (r.granted_depth) capPass(out, r.batch_rows); - if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHoldsFor(whos, sampled, out, streams); + if (r.granted_depth and r.k.hold_costs.len > 0) try r.payHoldsFor(whos, sampled, out, total_streams); return; } const most = try r.gpa.alloc(i64, whos.len); @@ -342,7 +345,6 @@ pub const Rule = struct { defer r.gpa.free(ones); @memset(ones, 1); const head: alloc.HeadCost = .{ .step_ms = r.sharedStepMs(), .batched = r.batched_heads, .row_ms = r.row_cost.extraMs(whos.len, sampled), .least_rows = r.row_cost.leastRows(whos.len, sampled) }; - const paired = r.sharedPrice(streams, sampled); const all_counts = if (paired) |p| try alloc.allocateDrafts(r.gpa, ones, probs, r.shared_costs, p.fixed, r.row_cost.capRows(streams, sampled, @max(streams, r.batch_rows)), .{ .plain_ms = p.plain, .step_ms = r.sharedStepMs(), .extra_step_ms = r.draft_step_ms, .batched = r.batched_heads and pricedBatched(), .row_ms = p.row, .least_rows = r.row_cost.leastRows(streams, sampled) }) else if (r.draft_step_ms != 0) @@ -479,6 +481,7 @@ test { _ = @import("depth_test.zig"); _ = @import("shared_price_test.zig"); _ = @import("shared_verify_price_test.zig"); + _ = @import("shared_warm_price_test.zig"); } test { diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index 13106a4fe62..eb89435300d 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -164,7 +164,7 @@ test "shared prices: an unmeasured plain option keeps main's winning drafted wid try t.expectEqualSlices(u32, &.{ 0, 0, 0, 0 }, measured); } -test "shared prices: only independent plain timing excludes a preceding deferred draft" { +test "shared prices: only measured plain timing excludes a preceding deferred draft" { const ClockAtDraft = struct { target: *fake.Fake, at: usize = 0, @@ -180,7 +180,7 @@ test "shared prices: only independent plain timing excludes a preceding deferred return 20 + 5 * @as(f64, @floatFromInt(c.target.drafts_calls - c.at)); } }; - for ([_]bool{ false, true }) |independent| { + for ([_]bool{ false, true }) |independent| for ([_]bool{ false, true }) |measured| { var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 1, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 10 } }, .plain_guard = independent, .hidden_rows = true }, 8, 7); defer cfg.deinit(a); var target: fake.Fake = .{ .gpa = a, .head_accepts = 1 }; @@ -190,6 +190,7 @@ test "shared prices: only independent plain timing excludes a preceding deferred backend.defer_lone_draft = true; var e = Engine.init(a, &cfg, backend, clock.clock()); defer e.deinit(); + if (independent and measured) try e.rule.observeShared(2, 2, 12, false, 0, true, false); var streams: [2]Stream = undefined; var made: usize = 0; defer for (streams[0..made]) |*s| s.deinit(a); @@ -201,7 +202,7 @@ test "shared prices: only independent plain timing excludes a preceding deferred } try t.expect(e.late.request != null); try e.step(); - try t.expectEqual(target.drafts_calls - @as(usize, if (independent) 2 else 3), clock.at); + try t.expectEqual(target.drafts_calls - @as(usize, if (independent and measured) 2 else 3), clock.at); try t.expectEqual(@as(usize, 0), e.rule.shared_price.buckets.items.len - @intFromBool(independent)); - } + }; } diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 4de578fe92e..983d4e3bf26 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -20,10 +20,15 @@ pub fn run(e: *Engine, entries: []*Stream) !void { } fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { - if (!independent) e.clock.start(); + var sampled_before = false; + if (independent) for (entries) |s| { + sampled_before = sampled_before or s.sampling != null; + }; + const measured = independent and e.rule.sharedPrice(entries.len, sampled_before) != null; + if (!measured) e.clock.start(); try e.late.flush(e, Engine.askDrafts); - // Only the independent plain measurement excludes a preceding lone draft. - if (independent) e.clock.start(); + // An unmeasured plain price retains the original clock boundary. + if (measured) e.clock.start(); const a = e.arena.allocator(); const plans = try a.alloc(Plan, entries.len); for (entries, plans) |s, *p| p.* = try win.plan(e, s, null); diff --git a/zig/src/core/lanes/shared_warm_price_test.zig b/zig/src/core/lanes/shared_warm_price_test.zig new file mode 100644 index 00000000000..967ffaff4c1 --- /dev/null +++ b/zig/src/core/lanes/shared_warm_price_test.zig @@ -0,0 +1,66 @@ +//! A mixed round retains the legacy head-only rule until an independent plain observation exists. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const depth = @import("depth.zig"); +const Table = @import("table.zig").Table; + +fn noCopy(_: *anyopaque, _: *const depth.Who) bool { + return false; +} + +fn table() !Table { + var out: Table = .{}; + for (1..17) |n| try out.put(a, @intCast(n), 10 + 2 * @as(f64, @floatFromInt(n))); + return out; +} + +fn rule(costs: *Table) depth.Rule { + return .{ .gpa = a, .prior = &.{0.3}, .most_drafts = 1, .family_costs = costs, .shared_costs = costs, .mtp_step_ms = 0, .plain_guard = true, .node_probabilities = false, .batch_rows = 16 }; +} + +test "shared prices: one head among four unmeasured streams keeps the legacy draft and probe" { + var costs = try table(); + defer costs.deinit(a); + var r = rule(&costs); + defer r.deinit(); + var state: ?depth.State = null; + defer if (state) |*s| s.deinit(a); + var who = [_]depth.Who{.{ .state = &state, .draft_room = 20, .finished = false, .forced = false }}; + var out: [1]i64 = undefined; + try r.budgetsFor(&who, .{ .ptr = &r, .copy = noCopy }, false, &out, 4); + try t.expectEqual(@as(i64, 1), out[0]); + try t.expectEqual(@as(u64, 1), r.shared_rounds); + try t.expect(r.sharedPrice(4, false) == null); +} + +test "shared prices: unmeasured holds use the head count and its original fixed cost" { + var costs = try table(); + defer costs.deinit(a); + var r = rule(&costs); + defer r.deinit(); + r.k.hold_costs = &.{.{ .streams = 1, .depth = 1, .ms = 2 }}; + try r.observeOverhead(1, 1, 112, false, 0); + try r.observeOverhead(4, 4, 18, false, 0); + var state: ?depth.State = null; + const who = [_]depth.Who{.{ .state = &state, .draft_room = 20, .finished = false, .forced = false, .granted = 1, .gain = 0.3 }}; + var out = [_]i64{1}; + try r.payHoldsFor(&who, false, &out, 4); + try t.expectEqual(@as(i64, 1), out[0]); +} + +test "shared prices: a measured different stream count cannot reprice a warm mixed round" { + var costs = try table(); + defer costs.deinit(a); + var r = rule(&costs); + defer r.deinit(); + try r.observeShared(2, 2, 1002, false, 0, true, false); + var states: [2]?depth.State = @splat(null); + defer for (&states) |*state| if (state.*) |*st| st.deinit(a); + var who: [2]depth.Who = undefined; + for (&who, &states) |*w, *state| w.* = .{ .state = state, .draft_room = 20, .finished = false, .forced = false }; + var out: [2]i64 = undefined; + try r.budgetsFor(&who, .{ .ptr = &r, .copy = noCopy }, false, &out, 4); + try t.expectEqual(@as(u64, 1), r.shared_rounds); + try t.expect(r.sharedPrice(4, false) == null); +} From d160003c18226c887105a99fa075ce9ce0d2d276 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:21:02 +0000 Subject: [PATCH 30/59] Space plain trials independently of forward table coverage --- zig/src/core/lanes/depth.zig | 5 ++- .../core/lanes/shared_calibration_test.zig | 43 +++++++++++++++++++ zig/src/core/lanes/shared_price.zig | 11 ++++- 3 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 zig/src/core/lanes/shared_calibration_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index bdf57b83a30..bce5fd5fac6 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -405,8 +405,8 @@ pub const Rule = struct { /// Only completed timed shared rounds advance this count/mode's calibration clock. pub fn observeShared(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { if (streams > 1 and r.plain_guard and r.confidence_floor == null) { - if (r.shared_costs.get(@intCast(rows))) |forward| - try r.shared_price.observe(r.gpa, streams, rows, ms - forward - head_ms, sampled, plain, calibration); + const residual = if (r.shared_costs.get(@intCast(rows))) |forward| ms - forward - head_ms else std.math.nan(f64); + try r.shared_price.observe(r.gpa, streams, rows, residual, sampled, plain, calibration); } try r.observeOverhead(streams, rows, ms, sampled, head_ms); } @@ -482,6 +482,7 @@ test { _ = @import("shared_price_test.zig"); _ = @import("shared_verify_price_test.zig"); _ = @import("shared_warm_price_test.zig"); + _ = @import("shared_calibration_test.zig"); } test { diff --git a/zig/src/core/lanes/shared_calibration_test.zig b/zig/src/core/lanes/shared_calibration_test.zig new file mode 100644 index 00000000000..8568e1738ab --- /dev/null +++ b/zig/src/core/lanes/shared_calibration_test.zig @@ -0,0 +1,43 @@ +//! Calibration spacing follows executed trials even where the exact forward width has no price. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const prices = @import("shared_price.zig"); +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const Config = @import("config.zig").Config; +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +test "shared prices: a missing forward width cannot repeat a calibration or stop its clock" { + var cfg = try Config.init(a, .{ .exact_width = 4, .mtp = true, .drafts = 1, .plain_guard = true, .hidden_rows = true, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 4, .ms = 10 } } }, 4, 3); + defer cfg.deinit(a); + cfg.shared_costs.slots[2] = null; + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [2]win.Plan = undefined; + for (&streams, &plans) |*s, *p| { + s.* = try Stream.init(a, .{ .id = "calibration", .prompt = &.{1}, .max_new = 1000 }); + made += 1; + s.rounds = 1; + p.* = .{ .stream = s, .position = 1, .kind = .none }; + } + var trials: usize = 0; + for (1..193) |round| { + const due = try prices.calibrate(&e, &plans); + try t.expectEqual(round % 64 == 0, due); + if (due) { + trials += 1; + try t.expect(!try prices.calibrate(&e, &plans)); + } + try e.rule.observeShared(2, 2, 12, false, 0, true, due); + try t.expect(e.rule.sharedPrice(2, false) == null); + } + try t.expectEqual(@as(usize, 3), trials); +} diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index 4a4ea42e3b8..42ed79ec688 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -40,6 +40,12 @@ pub const Prices = struct { return old and next -| b.last_probe >= every; } + /// Spend the trial's spacing when it is selected, even if its forward width cannot be measured. + pub fn probed(p: *Prices, a: Allocator, streams: usize, sampled: bool) !void { + const b = try p.get(a, streams, sampled); + b.last_probe = b.rounds +| 1; + } + /// The plain intercept is never updated by a round that verifies or prepares any draft. pub fn observe(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, sampled: bool, plain: bool, calibration: bool) !void { const b = try p.get(a, streams, sampled); @@ -77,5 +83,8 @@ pub fn calibrate(e: anytype, plans: anytype) !bool { if (!e.cfg.timed or !e.cfg.plain_guard or e.cfg.draft_confidence != null or e.trim != null or plans.len < 2 or e.cfg.shared_costs.empty()) return false; for (plans) |p| if (p.kind == .forced or p.stream.rounds == 0) return false; - return e.rule.shared_price.due(e.gpa, plans.len, @import("windows.zig").anySampled(plans)); + const sampled = @import("windows.zig").anySampled(plans); + if (!try e.rule.shared_price.due(e.gpa, plans.len, sampled)) return false; + try e.rule.shared_price.probed(e.gpa, plans.len, sampled); + return true; } From ca69af80aedb86e2aecbaf49321705f63bddaac1 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:28:39 +0000 Subject: [PATCH 31/59] Match independent residuals to the priced head batching mode --- zig/src/core/lanes/depth.zig | 18 +++- zig/src/core/lanes/shared_head_price_test.zig | 97 +++++++++++++++++++ zig/src/core/lanes/shared_round.zig | 5 +- 3 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 zig/src/core/lanes/shared_head_price_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index bce5fd5fac6..5099a33bc36 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -404,11 +404,16 @@ pub const Rule = struct { /// Only completed timed shared rounds advance this count/mode's calibration clock. pub fn observeShared(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { + try r.observeSharedPrice(streams, rows, ms, sampled, head_ms, plain, calibration); + try r.observeOverhead(streams, rows, ms, sampled, head_ms); + } + + /// The independent residual uses the same batching policy as next-draft allocation. + pub fn observeSharedPrice(r: *Rule, streams: u32, rows: u64, ms: f64, sampled: bool, head_ms: f64, plain: bool, calibration: bool) !void { if (streams > 1 and r.plain_guard and r.confidence_floor == null) { const residual = if (r.shared_costs.get(@intCast(rows))) |forward| ms - forward - head_ms else std.math.nan(f64); try r.shared_price.observe(r.gpa, streams, rows, residual, sampled, plain, calibration); } - try r.observeOverhead(streams, rows, ms, sampled, head_ms); } /// A shared round's ms beyond its forward at this many streams (the nearest measured count, first seen on ties). @@ -440,8 +445,16 @@ pub const Rule = struct { /// The modeled time of a shared round's head steps for the depths it drafted. pub fn headMs(r: *const Rule, depths: []const i64) f64 { + return r.headCost(depths, r.batched_heads); + } + + pub fn pricedHeadMs(r: *const Rule, depths: []const i64) f64 { + return r.headCost(depths, r.batched_heads and pricedBatched()); + } + + fn headCost(r: *const Rule, depths: []const i64, batched: bool) f64 { var steps: i64 = 0; - for (depths) |d| steps = if (r.batched_heads) @max(steps, d) else steps + d; + for (depths) |d| steps = if (batched) @max(steps, d) else steps + d; return r.sharedStepMs() * @as(f64, @floatFromInt(steps)); } @@ -483,6 +496,7 @@ test { _ = @import("shared_verify_price_test.zig"); _ = @import("shared_warm_price_test.zig"); _ = @import("shared_calibration_test.zig"); + _ = @import("shared_head_price_test.zig"); } test { diff --git a/zig/src/core/lanes/shared_head_price_test.zig b/zig/src/core/lanes/shared_head_price_test.zig new file mode 100644 index 00000000000..5964c4717b7 --- /dev/null +++ b/zig/src/core/lanes/shared_head_price_test.zig @@ -0,0 +1,97 @@ +//! The observed row residual and the next-draft allocator use the same head batching switch. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const env = @import("sys").env; +const be = @import("backend.zig"); +const fake = @import("fake.zig"); +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const Config = @import("config.zig").Config; + +const Clock = struct { + target: fake.Fake = .{ .gpa = a, .head_accepts = 8 }, + step: f64, + extra: f64, + batched: bool, + sum: u32 = 0, + firsts: u32 = 0, + deepest: u32 = 0, + fn self(ptr: *anyopaque) *@This() { + return @ptrCast(@alignCast(ptr)); + } + fn clock(c: *@This()) be.Clock { + return .{ .ptr = c, .vtable = &.{ .start = start, .elapsed_ms = elapsed } }; + } + fn start(ptr: *anyopaque) void { + const c = self(ptr); + c.sum = 0; + c.firsts = 0; + c.deepest = 0; + } + fn elapsed(ptr: *anyopaque, _: be.Mark) f64 { + const c = self(ptr); + const steps = if (c.batched) c.deepest else c.sum; + const extra = if (c.batched) c.deepest -| 1 else c.sum - c.firsts; + return 12 + c.step * @as(f64, @floatFromInt(steps)) + c.extra * @as(f64, @floatFromInt(extra)); + } + fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const target: *fake.Fake = @ptrCast(@alignCast(ptr)); + const c: *@This() = @fieldParentPtr("target", target); + for (requests) |r| { + c.sum += r.depth; + c.firsts += @intFromBool(r.depth > 0); + c.deepest = @max(c.deepest, r.depth); + } + try target.backend().vtable.draft(ptr, requests); + } +}; + +fn run(batched: bool, step: f64, extra: f64) !void { + var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .speculate = true, .drafts = 2, .draft_prior = &.{ 1, 1 }, .mtp_step_ms = step, .draft_step_ms = extra, .draft_streams = true, .plain_guard = true, .hidden_rows = true, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 10 } } }, 8, 7); + defer cfg.deinit(a); + var clock: Clock = .{ .batched = batched, .step = step, .extra = extra }; + defer clock.target.deinit(); + var backend = clock.target.backend(); + var vtable = backend.vtable.*; + vtable.draft = Clock.draft; + backend.vtable = &vtable; + var e = Engine.init(a, &cfg, backend, clock.clock()); + defer e.deinit(); + try e.rule.observeShared(2, 2, 12, false, 0, true, false); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + for (&streams) |*s| { + s.* = try Stream.init(a, .{ .id = "heads", .prompt = &.{ 1, 2, 3 }, .max_new = 64 }); + made += 1; + try e.addStream(s); + } + var measured_rounds: usize = 0; + for (0..3) |_| { + errdefer std.debug.print("head test: batched={any} step={d} extra={d} firsts={d} sum={d} deepest={d} rows={d} price={any}\n", .{ batched, step, extra, clock.firsts, clock.sum, clock.deepest, clock.target.last_rows, e.rule.sharedPrice(2, false) }); + try e.step(); + try t.expect(clock.firsts == 2 and clock.sum > clock.deepest); + try t.expectEqual(@as(u32, if (batched or step < 1) 4 else 3), clock.sum); + measured_rounds += @intFromBool(clock.target.last_rows > 2); + try t.expectApproxEqAbs(@as(f64, 2), e.rule.sharedPrice(2, false).?.plain, 1e-9); + try t.expectApproxEqAbs(@as(f64, 0), e.rule.sharedPrice(2, false).?.row, 1e-9); + } + try t.expect(measured_rounds >= 2); +} + +test "shared prices: unbatched priced heads cannot leak into the learned row slope" { + const variable = "FZ_PRICE_BATCHED"; + const old = if (std.c.getenv(variable)) |v| try a.dupeSentinel(u8, std.mem.span(v), 0) else null; + defer { + if (old) |v| { + _ = env.setenv(variable, v, 1); + a.free(v); + } else _ = env.unsetenv(variable); + } + for ([_]bool{ false, true }) |batched| { + try t.expectEqual(@as(c_int, 0), env.setenv(variable, if (batched) "1" else "0", 1)); + try run(batched, 3, 2); + try run(batched, 0.2, 0.1); + } +} diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 983d4e3bf26..b39528938fa 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -100,8 +100,9 @@ fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { if (independent) { var plain = total == plans.len; for (budgets) |d| plain = plain and d == 0; - try e.rule.observeShared(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets), plain, calibration); - } else try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); + try e.rule.observeSharedPrice(@intCast(plans.len), total, ms, sampled, e.rule.pricedHeadMs(budgets), plain, calibration); + } + try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); } if (e.backend.round_observer != null) e.backend.observed(paths); } From 723661792ae6be8057ac1a276c08808577cca51a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 07:30:14 +0000 Subject: [PATCH 32/59] Pin mixed reservation caps and holds before plain timing --- zig/src/core/lanes/shared_warm_price_test.zig | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/zig/src/core/lanes/shared_warm_price_test.zig b/zig/src/core/lanes/shared_warm_price_test.zig index 967ffaff4c1..00dacb04a71 100644 --- a/zig/src/core/lanes/shared_warm_price_test.zig +++ b/zig/src/core/lanes/shared_warm_price_test.zig @@ -64,3 +64,42 @@ test "shared prices: a measured different stream count cannot reprice a warm mix try t.expectEqual(@as(u64, 1), r.shared_rounds); try t.expect(r.sharedPrice(4, false) == null); } + +fn reservation(granted: bool) !void { + const Config = @import("config.zig").Config; + const Stream = @import("stream.zig").Stream; + const Engine = @import("engine.zig").Engine; + const fake = @import("fake.zig"); + const win = @import("windows.zig"); + var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .drafts = 1, .draft_prior = &.{0.3}, .plain_guard = true, .hidden_rows = true, .allocate_shared_drafts = true, .limit_shared_drafts = !granted, .granted_depth = granted, .draft_probabilities = granted, .hold_costs = if (granted) &.{.{ .streams = 1, .depth = 1, .ms = 2 }} else &.{}, .window_costs = &.{ .{ .width = 1, .ms = 12 }, .{ .width = 8, .ms = 26 } } }, 8, 7); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + try e.rule.observeOverhead(1, 1, if (granted) 112 else 20, false, 0); + try e.rule.observeOverhead(4, 4, 118, false, if (granted) 100 else 0); + var streams: [4]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [4]win.Plan = undefined; + for (&streams, &plans, 0..) |*s, *p, i| { + s.* = try Stream.init(a, .{ .id = "mixed", .prompt = &.{1}, .max_new = 64, .drafts = i == 0 }); + made += 1; + s.granted = if (i == 0) 1 else null; + if (i == 0 and granted) try s.draft_chances.append(a, 0.3); + p.* = .{ .stream = s, .position = 1, .kind = .none }; + } + var out: [1]i64 = undefined; + try @import("shared_drafts.zig").budgets(&e, &plans, &.{0}, &out); + try t.expectEqual(@as(i64, 1), out[0]); +} + +test "shared prices: an unmeasured mixed reservation retains the original head depth limit" { + try reservation(false); +} + +test "shared prices: an unmeasured mixed reservation retains the original hold price" { + try reservation(true); +} From 558b448f2437148b5b368209664cc2d36fb05e0b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:59:13 +0000 Subject: [PATCH 33/59] Price shared plain rounds from warm plain trials A stream count's first all-plain trial pays one-off costs, and blending each later trial a fifth of the way kept that slow sample in the plain price for hundreds of rounds, so near-even drafts kept drafting. The first trial is now a warm-up whose sample is dropped (the existing allocator stays in charge until the next trial, `every` rounds on), and each later trial replaces the plain point. Natural plain rounds still blend as before; `due` is unchanged. --- zig/src/core/lanes/depth.zig | 1 + .../core/lanes/shared_calibration_test.zig | 28 ++- zig/src/core/lanes/shared_price.zig | 9 +- zig/src/core/lanes/shared_price_test.zig | 13 +- zig/src/core/lanes/shared_warmup_test.zig | 166 ++++++++++++++++++ 5 files changed, 203 insertions(+), 14 deletions(-) create mode 100644 zig/src/core/lanes/shared_warmup_test.zig diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 5099a33bc36..e10d0b6b732 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -496,6 +496,7 @@ test { _ = @import("shared_verify_price_test.zig"); _ = @import("shared_warm_price_test.zig"); _ = @import("shared_calibration_test.zig"); + _ = @import("shared_warmup_test.zig"); _ = @import("shared_head_price_test.zig"); } diff --git a/zig/src/core/lanes/shared_calibration_test.zig b/zig/src/core/lanes/shared_calibration_test.zig index 8568e1738ab..7cf33a16e94 100644 --- a/zig/src/core/lanes/shared_calibration_test.zig +++ b/zig/src/core/lanes/shared_calibration_test.zig @@ -9,9 +9,11 @@ const Config = @import("config.zig").Config; const fake = @import("fake.zig"); const win = @import("windows.zig"); -test "shared prices: a missing forward width cannot repeat a calibration or stop its clock" { +/// 192 rounds of two streams, the two-row forward priced from round `priced_from` on (null: never). +fn calibrations(priced_from: ?usize, want: []const usize, priced_at: ?usize) !void { var cfg = try Config.init(a, .{ .exact_width = 4, .mtp = true, .drafts = 1, .plain_guard = true, .hidden_rows = true, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 4, .ms = 10 } } }, 4, 3); defer cfg.deinit(a); + const two = cfg.shared_costs.slots[2]; cfg.shared_costs.slots[2] = null; var target: fake.Fake = .{ .gpa = a }; defer target.deinit(); @@ -28,16 +30,28 @@ test "shared prices: a missing forward width cannot repeat a calibration or stop s.rounds = 1; p.* = .{ .stream = s, .position = 1, .kind = .none }; } - var trials: usize = 0; + var trials: [4]usize = undefined; + var n: usize = 0; for (1..193) |round| { + if (priced_from == round) cfg.shared_costs.slots[2] = two; const due = try prices.calibrate(&e, &plans); - try t.expectEqual(round % 64 == 0, due); if (due) { - trials += 1; + trials[n] = round; + n += 1; try t.expect(!try prices.calibrate(&e, &plans)); } - try e.rule.observeShared(2, 2, 12, false, 0, true, due); - try t.expect(e.rule.sharedPrice(2, false) == null); + // between trials, drafted work at plain width: it never moves the plain point + try e.rule.observeShared(2, 2, 12, false, 0, due, due); + try t.expectEqual(if (priced_at) |at| round >= at else false, e.rule.sharedPrice(2, false) != null); } - try t.expectEqual(@as(usize, 3), trials); + try t.expectEqualSlices(usize, want, trials[0..n]); +} + +test "shared prices: a missing forward width cannot repeat a calibration or stop its clock" { + try calibrations(null, &.{ 64, 128, 192 }, null); +} + +test "shared prices: a count's first plain trial warms it up, measured or not, and the next one prices it" { + try calibrations(1, &.{ 64, 128 }, 128); + try calibrations(100, &.{ 64, 128 }, 128); } diff --git a/zig/src/core/lanes/shared_price.zig b/zig/src/core/lanes/shared_price.zig index 42ed79ec688..8483ea6c69f 100644 --- a/zig/src/core/lanes/shared_price.zig +++ b/zig/src/core/lanes/shared_price.zig @@ -9,6 +9,7 @@ const Bucket = struct { sampled: bool, rounds: u64 = 0, last_probe: u64 = 0, + trials: u64 = 0, // completed all-plain trials, the first of them a warm-up plain: ?Point = null, draft: ?Point = null, }; @@ -46,14 +47,18 @@ pub const Prices = struct { b.last_probe = b.rounds +| 1; } - /// The plain intercept is never updated by a round that verifies or prepares any draft. + /// No drafting round moves the plain point; a count's first plain trial is a warm-up, each later one replaces it. pub fn observe(p: *Prices, a: Allocator, streams: usize, rows: u64, residual: f64, sampled: bool, plain: bool, calibration: bool) !void { const b = try p.get(a, streams, sampled); b.rounds +|= 1; if (calibration) b.last_probe = b.rounds; + const trial = calibration and plain and rows == streams; + if (trial) b.trials +|= 1; if (!std.math.isFinite(residual)) return; const point: Point = .{ .residual = residual, .rows = @floatFromInt(rows), .at = b.rounds }; - if (plain and rows == streams) { + if (trial) { + if (b.trials > 1) b.plain = point; + } else if (plain and rows == streams) { blend(&b.plain, point); } else if (rows > streams) blend(&b.draft, point); } diff --git a/zig/src/core/lanes/shared_price_test.zig b/zig/src/core/lanes/shared_price_test.zig index eb89435300d..07c6991641e 100644 --- a/zig/src/core/lanes/shared_price_test.zig +++ b/zig/src/core/lanes/shared_price_test.zig @@ -54,14 +54,16 @@ fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { probes += 1; } if (round < 64) drafted_before += @intFromBool(target.last_rows > 2); - if (round > 65 and e.activeCount() == 2) drafted_after += @intFromBool(target.last_rows > 2); - if (round == 64) { + if (round > 129 and e.activeCount() == 2) drafted_after += @intFromBool(target.last_rows > 2); + // the first trial is the count's warm-up: the second one sets the plain price + if (round == 64) try t.expect(e.rule.sharedPrice(2, sampled) == null); + if (round == 128) { try t.expect(e.rule.sharedPrice(2, sampled) != null); const p = e.rule.sharedPrice(2, sampled).?; try t.expectApproxEqAbs(@as(f64, 2), p.plain, 1e-9); try t.expectApproxEqAbs(row_ms, p.row, 1e-9); } - if (row_ms > 5 and round == 65) try t.expectEqual(@as(usize, 2), target.last_rows); + if (row_ms > 5 and round == 129) try t.expectEqual(@as(usize, 2), target.last_rows); } if (!plain_only) { try t.expect(drafted_before > 32); @@ -78,7 +80,7 @@ fn run(sampled: bool, row_ms: f64, plain_only: bool) ![2][800]u32 { return out; } -test "shared prices: cheaper plain wins after its first measurement and target tokens stay exact" { +test "shared prices: cheaper plain wins after its first warm measurement and target tokens stay exact" { for ([_]bool{ false, true }) |sampled| { const oracle = try run(sampled, 9, true); const got = try run(sampled, 9, false); @@ -99,7 +101,8 @@ test "shared prices: missing and stale trials obey exact independent count and m defer p.deinit(a); for (1..641) |round| { const due = try p.due(a, 4, true); - try t.expectEqual(round == 64 or round == 320 or round == 576, due); + // the warm-up at 64 leaves the price missing, so the next trial comes `every` rounds on + try t.expectEqual(round == 64 or round == 128 or round == 384 or round == 640, due); try t.expect(!try p.due(a, 4, false)); try t.expect(!try p.due(a, 2, true)); // Rechecking without completing a round cannot spend another calibration or age another mode. diff --git a/zig/src/core/lanes/shared_warmup_test.zig b/zig/src/core/lanes/shared_warmup_test.zig new file mode 100644 index 00000000000..9fc4e203ca6 --- /dev/null +++ b/zig/src/core/lanes/shared_warmup_test.zig @@ -0,0 +1,166 @@ +//! A stream count's first plain trial pays one-off costs: the plain price comes from later trials alone. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const be = @import("backend.zig"); +const fake = @import("fake.zig"); +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const Config = @import("config.zig").Config; + +const plain_ms = 20.0; // a warm all-plain round of four streams +const warmup_ms = 4.0; // what the first all-plain round of four streams pays once +const forward_ms = 17.0; // the load-time table's four-row forward +const later_from = 200; // four-stream rounds from which every round costs `Case.later` more +const settled_from = 129; // the second trial's round and the one after it, which holds no drafts + +const Case = struct { + accept: f64, // the share of drafts the target keeps, spread evenly, and the streams' prior + row_ms: f64, // what a drafted row adds to a round + table_row_ms: f64, // what the load-time table charges a row past the fourth + later: f64 = 0, + max_new: u32, +}; + +const Target = struct { + target: fake.Fake = .{ .gpa = a }, + case: Case, + cold: bool = true, + ms: f64 = 0, + windows: usize = 0, + fours: u64 = 0, // shared rounds of four streams + credit: f64 = 0, + + fn of(ptr: *anyopaque) *Target { + const x: *fake.Fake = @ptrCast(@alignCast(ptr)); + return @fieldParentPtr("target", x); + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const h = of(ptr); + try h.target.backend().vtable.verify(ptr, windows, out); + h.windows = windows.len; + h.fours += @intFromBool(windows.len == 4); + const extra: f64 = @floatFromInt(h.target.last_rows - windows.len); + h.ms = plain_ms * @as(f64, @floatFromInt(windows.len)) / 4 + h.case.row_ms * extra; + if (h.fours >= later_from) h.ms += h.case.later; + // the streams' first round switches their prompts to decoding; the one-off cost lands on the next plain one + if (extra == 0 and windows.len == 4 and h.cold and windows[0].stream.rounds > 0) { + h.ms += warmup_ms; + h.cold = false; + } + } + + fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + const h = of(ptr); + for (requests) |r| { + if (r.depth > 0) h.credit += h.case.accept; + const kept = h.credit >= 1; + if (kept) h.credit -= 1; + h.target.head_accepts = @intFromBool(kept); + try h.target.backend().vtable.draft(ptr, &[_]be.DraftRequest{r}); + } + } + + fn start(_: *anyopaque) void {} + + fn elapsed(ptr: *anyopaque, _: be.Mark) f64 { + const h: *Target = @ptrCast(@alignCast(ptr)); + return h.ms; + } +}; + +const Run = struct { + tokens: [4][]u32, + trials: [8]u64 = @splat(0), // the four-stream round of each plain trial + count: usize = 0, + rounds_after: usize = 0, // four-stream rounds past `settled_from` but trials, and those that drafted + drafted_after: usize = 0, + + fn deinit(r: *Run) void { + for (r.tokens) |s| a.free(s); + } +}; + +/// Four streams on a fake target priced by `case`; with `drafts`, each trial's plain price is checked as it lands. +fn run(case: Case, sampled: bool, drafts: bool) !Run { + const costs = [_]@import("config.zig").Cost{ .{ .width = 1, .ms = 10 }, .{ .width = 4, .ms = forward_ms }, .{ .width = 8, .ms = forward_ms + 4 * case.table_row_ms } }; + // a slow estimate keeps each stream's acceptance near the target's own share + var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .speculate = true, .speculate_early = false, .drafts = 1, .draft_prior = &.{case.accept}, .depth_rate = 0.02, .copy_drafts = false, .plain_guard = true, .hidden_rows = true, .window_costs = &costs }, 8, 7); + defer cfg.deinit(a); + var h: Target = .{ .case = case }; + defer h.target.deinit(); + var backend = h.target.backend(); + var vtable = backend.vtable.*; + vtable.verify = Target.verify; + vtable.draft = Target.draft; + backend.vtable = &vtable; + var e = Engine.init(a, &cfg, backend, .{ .ptr = &h, .vtable = &.{ .start = Target.start, .elapsed_ms = Target.elapsed } }); + defer e.deinit(); + var streams: [4]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + for (&streams) |*s| { + s.* = try Stream.init(a, .{ .id = "warm", .prompt = &.{ 1, 2, 3 }, .max_new = case.max_new, .eos = &.{}, .drafts = drafts, .sampling = if (sampled) .{ .seed = 23, .temperature = 0.7 } else null }); + made += 1; + try e.addStream(s); + } + var out: Run = .{ .tokens = undefined }; + while (e.activeCount() > 0) { + const four = e.activeCount() == 4; + const due = drafts and four and try e.rule.shared_price.due(a, 4, sampled); + try e.step(); + if (!drafts or !four or h.windows != 4) continue; + const rows = h.target.last_rows; + // a trial's streams hold no drafts, so the round after it verifies none + const settled = h.fours > settled_from and (out.count == 0 or h.fours != out.trials[out.count - 1] + 1); + if (due and rows == 4) { + try t.expect(out.count < out.trials.len); + out.trials[out.count] = h.fours; + out.count += 1; + const price = e.rule.sharedPrice(4, sampled); + // the first trial is a warm-up: until the next one, the existing allocator stays in charge + if (out.count == 1) try t.expect(price == null) else { + const later: f64 = if (h.fours >= later_from) case.later else 0; + try t.expectApproxEqAbs(plain_ms + later - forward_ms, price.?.plain, 1e-9); + } + } else if (settled) { + out.rounds_after += 1; + out.drafted_after += @intFromBool(rows > 4); + } + } + for (&out.tokens, &streams) |*tokens, s| tokens.* = try a.dupe(u32, s.emitted()); + return out; +} + +fn exact(case: Case, sampled: bool) !Run { + var oracle = try run(case, sampled, false); + defer oracle.deinit(); + var got = try run(case, sampled, true); + errdefer got.deinit(); + for (oracle.tokens, got.tokens) |want, have| try t.expectEqualSlices(u32, want, have); + return got; +} + +test "shared prices: a slow first plain trial is dropped, so near-even drafts give way to plain rounds" { + // an 8-row round costs 1.63x a warm plain one: one draft a stream pays above 0.63 acceptance, not at 0.6 + const case: Case = .{ .accept = 0.6, .row_ms = 0.63 * plain_ms / 4.0, .table_row_ms = 2.25, .max_new = 700 }; + for ([_]bool{ false, true }) |sampled| { + var got = try exact(case, sampled); + defer got.deinit(); + try t.expect(got.rounds_after > 200); + try t.expectEqual(@as(usize, 0), got.drafted_after); + try t.expectEqualSlices(u64, &.{ 64, 128 }, got.trials[0..got.count]); + } +} + +test "shared prices: profitable drafts keep winning, and each later trial replaces the plain price" { + const case: Case = .{ .accept = 0.9, .row_ms = 0.5, .table_row_ms = 0.25, .later = 1, .max_new = 1400 }; + for ([_]bool{ false, true }) |sampled| { + var got = try exact(case, sampled); + defer got.deinit(); + // a missing price retries `every` rounds on, a measured one only once it is `stale` + try t.expectEqualSlices(u64, &.{ 64, 128, 384, 640 }, got.trials[0..got.count]); + try t.expectEqual(got.rounds_after, got.drafted_after); + } +} From 850650ee9562f45ca3fe34865b716ef9144ab18a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:59:13 +0000 Subject: [PATCH 34/59] Log what the shared plain-price rule sees, behind TF_SHARED_PRICE_LOG Off unless TF_SHARED_PRICE_LOG=1. A common-scope environment.zig row refuses any other text by name when a server starts, and the lane core reads it through the same parser at an engine's first priced shared round, which then logs the load-time shared forward costs and head steps. Each priced shared round after that logs one line: its trial flag, rows, time, the forward's table time, each stream's verified drafts and next depth, the plain and row prices the depths were chosen by, and each stream's acceptance estimates. Nothing it logs feeds back into a decision. --- docs/environment.md | 1 + zig/src/core/lanes/engine.zig | 1 + zig/src/core/lanes/price_log.zig | 73 ++++++++++++++++++++++ zig/src/core/lanes/price_log_test.zig | 90 +++++++++++++++++++++++++++ zig/src/core/lanes/shared_round.zig | 5 +- zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 2 + 7 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 zig/src/core/lanes/price_log.zig create mode 100644 zig/src/core/lanes/price_log_test.zig diff --git a/docs/environment.md b/docs/environment.md index 7c99c55d4db..c497fb8312f 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -16,6 +16,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TENSORFOLD_RESTORE_PREFETCH_MS` | Whole unsigned 64-bit milliseconds, capped at 1099511627776; default 30000 | | `TENSORFOLD_TOOL_ID_KEY_FILE` | The path of the file that holds the key for tool-call ids ([API](api.md#messages-and-tools)). The file must be a regular file, not a link, that only its owner can read or write (`chmod 600`), with 32 to 4096 bytes in it, and the path must not contain control characters. When this is unset, each server process makes its own random key. If the file is wrong, the server does not start; the message names this setting but never shows the path or what the file holds | | `TF_STARTUP_RECEIPT` | Exactly `0` or `1`; default off. `1` writes the startup and first completion receipts | +| `TF_SHARED_PRICE_LOG` | Exactly `0` or `1`; default off. `1` logs, at an engine's first priced shared round, the load-time shared forward costs and head steps, then one `shared price: round` line a priced shared round: its trial flag, rows, time, each stream's drafts and next depth, the plain and row prices and each stream's acceptance estimates | | `TF_CUDA_DEVICE` | Whole ordinal 0 through 4294967295, or empty; default 0 | | `TF_CUDA_SEGMENTS` | Whole count 1 through 4, or empty; default 1 | | `TENSORFOLD_CUDA_KERNELS` | A path without control characters, used as given: a captured kernel set's folder, or `native` for the engine's own kernels. Unset uses the binary's bundled set for the GPU when it has one, else the engine's own kernels. A family that runs only on the engine's own kernels (Qwen3 among them) refuses any other value; Qwen3 reads a blank value as unset | diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index 936d0f841e6..fe0bfbb5fb9 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -53,6 +53,7 @@ pub const Engine = struct { grammar_workers: @import("grammar_parallel.zig").State = .{}, arena: std.heap.ArenaAllocator, // a round's temporaries unread: std.ArrayList(Unread) = .empty, // queued draws the log reads at the step's end + price_log: ?bool = null, // TF_SHARED_PRICE_LOG, read at the first priced shared round (lanes/price_log.zig) pub fn init(gpa: Allocator, cfg: *const Config, backend: be.Backend, clock: be.Clock) Engine { return .{ .gpa = gpa, diff --git a/zig/src/core/lanes/price_log.zig b/zig/src/core/lanes/price_log.zig new file mode 100644 index 00000000000..17b9249bf48 --- /dev/null +++ b/zig/src/core/lanes/price_log.zig @@ -0,0 +1,73 @@ +//! TF_SHARED_PRICE_LOG=1: the load-time costs once, then a line a priced shared round with what the plain rule saw. +const std = @import("std"); +const Writer = std.Io.Writer; + +pub const name = "TF_SHARED_PRICE_LOG"; + +/// Read at an engine's first priced shared round, which then logs the load-time costs; bad text fails it by name. +pub fn enabled(e: anytype) !bool { + if (e.price_log) |on| return on; + const on = try @import("sys").environment.read(bool, name, false); + e.price_log = on; + if (on) try emit(e.gpa, load, .{&e.rule}); + return on; +} + +/// A timed round as the plain rule observes it: `ms` its time less extra draft steps, `head_ms` its priced head steps. +pub const Round = struct { trial: bool, sampled: bool, ms: f64, head_ms: f64, heads: []const usize, depths: []const i64 }; + +pub fn round(e: anytype, plans: anytype, windows: anytype, r: Round) !void { + try emit(e.gpa, line, .{ &e.rule, plans, windows, r }); +} + +fn emit(gpa: std.mem.Allocator, comptime write: anytype, args: anytype) !void { + var out: Writer.Allocating = .init(gpa); + defer out.deinit(); + try @call(.auto, write, .{&out.writer} ++ args); + std.log.info("{s}", .{out.written()}); +} + +/// The shared forward's load-time ms by rows, then the head's chained, shared and extra draft steps. +pub fn load(w: *Writer, r: anytype) !void { + try w.writeAll("shared price: load shared_ms="); + var first = true; + for (r.shared_costs.slots, 0..) |slot, rows| if (slot) |ms| { + try w.print("{s}{d}:{d:.3}", .{ if (first) "" else ",", rows, ms }); + first = false; + }; + try w.print(" step_ms={d:.3} shared_step_ms={d:.3} draft_step_ms={d:.3}", .{ r.mtp_step_ms, r.sharedStepMs(), r.draft_step_ms }); +} + +/// A round's trial flag, rows and time, each stream's verified drafts and next depth, the price that chose them. +pub fn line(w: *Writer, rule: anytype, plans: anytype, windows: anytype, r: Round) !void { + var rows: usize = 0; + for (windows) |x| rows += x.rows(); + try w.print("shared price: round streams={d} sampled={d} trial={d} rows={d} ms={d:.3} head={d:.3} forward=", .{ plans.len, @intFromBool(r.sampled), @intFromBool(r.trial), rows, r.ms, r.head_ms }); + if (rule.shared_costs.get(@intCast(rows))) |v| try w.print("{d:.3}", .{v}) else try w.writeByte('-'); + if (rule.sharedPrice(plans.len, r.sampled)) |p| try w.print(" plain={d:.3} row={d:.3}", .{ p.plain, p.row }) else try w.writeAll(" plain=- row=-"); + try w.writeAll(" drafts="); + for (windows, 0..) |x, i| try w.print("{s}{d}", .{ if (i == 0) "" else ",", x.rows() - 1 }); + try w.writeAll(" depths="); + for (0..plans.len) |i| { + if (i > 0) try w.writeByte(','); + const at = std.mem.indexOfScalar(usize, r.heads, i) orelse { + try w.writeByte('-'); + continue; + }; + try w.print("{d}", .{r.depths[at]}); + } + // each stream's acceptance estimate by depth, `/` between depths + try w.writeAll(" accept="); + for (plans, 0..) |p, i| { + if (i > 0) try w.writeByte(','); + const st = p.stream.depth orelse { + try w.writeByte('-'); + continue; + }; + for (st.p, 0..) |v, j| try w.print("{s}{d:.3}", .{ if (j == 0) "" else "/", v }); + } +} + +test { + _ = @import("price_log_test.zig"); +} diff --git a/zig/src/core/lanes/price_log_test.zig b/zig/src/core/lanes/price_log_test.zig new file mode 100644 index 00000000000..62cf8678d88 --- /dev/null +++ b/zig/src/core/lanes/price_log_test.zig @@ -0,0 +1,90 @@ +//! TF_SHARED_PRICE_LOG: off unless set, malformed text refused by name, and each line in its fixed form. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const sys = @import("sys"); +const log = @import("price_log.zig"); +const depth = @import("depth.zig"); +const Table = @import("table.zig").Table; + +const Window = struct { + n: usize, + pub fn rows(w: Window) usize { + return w.n; + } +}; +const Stream = struct { depth: ?depth.State }; +const Plan = struct { stream: *const Stream }; + +fn costs() !Table { + var table: Table = .{}; + for (1..5) |n| try table.put(a, @intCast(n), 10 + @as(f64, @floatFromInt(n))); + return table; +} + +fn rule(table: *const Table) depth.Rule { + return .{ .gpa = a, .prior = &.{0.6}, .most_drafts = 2, .family_costs = table, .shared_costs = table, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = false, .batch_rows = 4 }; +} + +test "shared price log: the load line lists the shared table by rows and the head steps" { + var table = try costs(); + defer table.deinit(a); + var r = rule(&table); + defer r.deinit(); + var out: std.Io.Writer.Allocating = .init(a); + defer out.deinit(); + try log.load(&out.writer, &r); + try t.expectEqualStrings("shared price: load shared_ms=1:11.000,2:12.000,3:13.000,4:14.000 step_ms=0.500 shared_step_ms=0.500 draft_step_ms=0.000", out.written()); +} + +test "shared price log: a round line has its trial, rows, time, each stream's drafts, depth and estimates, and the price" { + var table = try costs(); + defer table.deinit(a); + var r = rule(&table); + defer r.deinit(); + var rates = [_]f64{ 0.625, 0.5 }; + const streams = [_]Stream{ .{ .depth = .{ .p = &rates } }, .{ .depth = null } }; + const plans = [_]Plan{ .{ .stream = &streams[0] }, .{ .stream = &streams[1] } }; + const windows = [_]Window{ .{ .n = 2 }, .{ .n = 1 } }; + const round: log.Round = .{ .trial = false, .sampled = false, .ms = 15.25, .head_ms = 0.5, .heads = &.{0}, .depths = &.{1} }; + var out: std.Io.Writer.Allocating = .init(a); + defer out.deinit(); + try log.line(&out.writer, &r, &plans, &windows, round); + try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=0 rows=3 ms=15.250 head=0.500 forward=13.000 plain=- row=- drafts=1,0 depths=1,- accept=0.625/0.500,-", out.written()); + try r.observeShared(2, 2, 15, false, 0, true, false); + try r.observeShared(2, 4, 19, false, 0, false, false); + out.clearRetainingCapacity(); + try log.line(&out.writer, &r, &plans, &windows, .{ .trial = true, .sampled = false, .ms = 15, .head_ms = 0, .heads = &.{0}, .depths = &.{0} }); + try t.expectEqualStrings("shared price: round streams=2 sampled=0 trial=1 rows=3 ms=15.000 head=0.000 forward=13.000 plain=3.000 row=1.000 drafts=1,0 depths=0,- accept=0.625/0.500,-", out.written()); +} + +const Env = struct { + raw: []const u8, + pub fn get(v: Env, name: []const u8) ?[]const u8 { + return if (std.mem.eql(u8, name, log.name)) v.raw else null; + } +}; + +test "shared price log: off unset or 0, on at 1 and read once, other text refused by name" { + defer _ = sys.env.unsetenv(log.name); + var table = try costs(); + defer table.deinit(a); + const E = struct { gpa: std.mem.Allocator, rule: depth.Rule, price_log: ?bool = null }; + for ([_]?[:0]const u8{ null, "", "0", "1", "yes", "2" }) |raw| { + if (raw) |v| try t.expectEqual(@as(c_int, 0), sys.env.setenv(log.name, v, 1)) else _ = sys.env.unsetenv(log.name); + var e: E = .{ .gpa = a, .rule = rule(&table) }; + defer e.rule.deinit(); + const want = raw != null and std.mem.eql(u8, raw.?, "1"); + if (raw != null and (std.mem.eql(u8, raw.?, "yes") or std.mem.eql(u8, raw.?, "2"))) { + try t.expectError(error.InvalidEnvironment, log.enabled(&e)); + // the server's start refuses it first, with every backend's scopes off + const why = (try sys.environment.refusal(a, Env{ .raw = raw.? }, .{})).?; + defer a.free(why); + try t.expect(std.mem.startsWith(u8, why, log.name ++ "=\"")); + continue; + } + try t.expectEqual(want, try log.enabled(&e)); + try t.expectEqual(@as(c_int, 0), sys.env.setenv(log.name, if (want) "0" else "1", 1)); + try t.expectEqual(want, try log.enabled(&e)); + } +} diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index b39528938fa..626f93a3086 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -10,6 +10,7 @@ const be = @import("backend.zig"); const depth = @import("depth.zig"); const ev = @import("events.zig"); const trail = @import("trail.zig"); +const price_log = @import("price_log.zig"); const f = ev.f; const str = trail.str; const int = trail.int; @@ -100,7 +101,9 @@ fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { if (independent) { var plain = total == plans.len; for (budgets) |d| plain = plain and d == 0; - try e.rule.observeSharedPrice(@intCast(plans.len), total, ms, sampled, e.rule.pricedHeadMs(budgets), plain, calibration); + const head_ms = e.rule.pricedHeadMs(budgets); + if (try price_log.enabled(e)) try price_log.round(e, plans, windows, .{ .trial = calibration, .sampled = sampled, .ms = ms, .head_ms = head_ms, .heads = heads.items, .depths = budgets }); + try e.rule.observeSharedPrice(@intCast(plans.len), total, ms, sampled, head_ms, plain, calibration); } try e.rule.observeOverhead(@intCast(plans.len), total, ms, sampled, e.rule.headMs(budgets)); } diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index da45b7281d1..42c365f1692 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -33,6 +33,7 @@ pub fn isReal(kind: Kind) bool { pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .scope = .cuda, .kind = .flag, .blank_default = false, .forms = "0 or 1 (0 restores per-stream Flash Next row draws; default 1)" }, .{ .name = "TF_STARTUP_RECEIPT", .scope = .common, .kind = .flag, .forms = "0 or 1 (opt-in startup and first completion receipts)" }, + .{ .name = "TF_SHARED_PRICE_LOG", .scope = .common, .kind = .flag, .forms = "0 or 1 (1 logs the shared plain price, a line a round)" }, .{ .name = "TENSORFOLD_VIDEO_TOKENS", .scope = .common, .kind = .u64, .forms = "a nonnegative whole video-token budget (default 16384; unsigned 64-bit count)" }, .{ .name = "TENSORFOLD_MAX_PDF_PAGES", .scope = .common, .kind = .positive, .forms = "a whole number from 1 to 4294967295 (capped by --vision-max-images)" }, .{ .name = "TENSORFOLD_PRESSURE_CACHE_PERCENT", .scope = .common, .kind = .percent, .trim = " \t", .forms = "a whole percentage from 0 to 100" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index ee7e88fd763..f93b1bd8cf3 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -51,6 +51,8 @@ const valid = [_]Case{ .{ .name = "TENSORFOLD_TOOL_ID_KEY_FILE", .raw = "/etc/tensorfold/tool id.key", .n = 0 }, .{ .name = "TF_STARTUP_RECEIPT", .raw = "0", .n = 0 }, .{ .name = "TF_STARTUP_RECEIPT", .raw = "1", .n = 1 }, + .{ .name = "TF_SHARED_PRICE_LOG", .raw = "0", .n = 0 }, + .{ .name = "TF_SHARED_PRICE_LOG", .raw = "1", .n = 1 }, .{ .name = "TF_CUDA_DEVICE", .raw = " 3 ", .n = 3 }, .{ .name = "TF_CUDA_DEVICE", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TF_CUDA_SEGMENTS", .raw = " 1 ", .n = 1 }, From e872da389ab65e0568bd49eeb5854ec0fc73225b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:10:20 -0800 Subject: [PATCH 35/59] lanes: retain signed learning with independent plain prices Keep the measured plain intercept while the row learner owns its signed slope. Exercise both prices, the plain-width floor and all three measuring allocators. Refs #2605. --- zig/build/lane_halt_host.zig | 1 + zig/src/core/lanes/depth.zig | 6 +- .../core/lanes/shared_price_learning_test.zig | 86 +++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 zig/src/core/lanes/shared_price_learning_test.zig diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 938c7b99179..6bc67f291ec 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -13,6 +13,7 @@ pub fn steps(b: *std.Build) void { b.step("test-lane-halt-host", "Halt ordering with a fake backend and no GPU dependencies").dependOn(&b.addRunArtifact(halt).step); b.step("test-lane-lone-host", "Existing lone-driver handoff and reclaim with a fake backend").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"lone driver"} })).step); b.step("test-lane-api-host", "Shared lane host and engine API CPU regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); + b.step("test-shared-price-learning-host", "Independent plain prices and signed row learning together without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"shared combined prices:"} })).step); b.step("test-conversation-cache-host", "Returning conversation eviction and queued-resume regressions without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{ "newest cache:", "queued cache:" } })).step); b.step("test-cache-progress-host", "One-state follow-ups and new conversations keep their next endpoint").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"queued cache: progress"} })).step); b.step("test-snapshot-index-host", "Prompt-cache lookup index against the whole-store scan, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"snapshot index:"} })).step); diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index e10d0b6b732..8d7c793b9db 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -390,7 +390,10 @@ pub const Rule = struct { /// Independent plain price and the row slope from a plain/drafted pair, at this exact count and mode. pub fn sharedPrice(r: *const Rule, streams: usize, sampled: bool) ?@import("shared_price.zig").Price { if (streams < 2 or !r.plain_guard or r.confidence_floor != null) return null; - return r.shared_price.price(streams, sampled, r.row_cost.extraMs(streams, sampled)); + var price = r.shared_price.price(streams, sampled, r.row_cost.extraMs(streams, sampled)) orelse return null; + // The independent plain point owns the intercept; row learning owns the signed, noise-tested slope. + if (r.k.learn_rows) price.row = r.row_cost.extraMs(streams, sampled); + return price; } /// Held drafts have already run; every verify option retains the round's same head fixed cost. @@ -498,6 +501,7 @@ test { _ = @import("shared_calibration_test.zig"); _ = @import("shared_warmup_test.zig"); _ = @import("shared_head_price_test.zig"); + _ = @import("shared_price_learning_test.zig"); } test { diff --git a/zig/src/core/lanes/shared_price_learning_test.zig b/zig/src/core/lanes/shared_price_learning_test.zig new file mode 100644 index 00000000000..24e5fbb27be --- /dev/null +++ b/zig/src/core/lanes/shared_price_learning_test.zig @@ -0,0 +1,86 @@ +//! Independent plain prices coexist with signed row learning and width-reaching rounds. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const depth = @import("depth.zig"); +const alloc = @import("allocate.zig"); +const Table = @import("table.zig").Table; +const fake = @import("fake.zig"); +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const Config = @import("config.zig").Config; +const win = @import("windows.zig"); + +fn rule(table: *const Table) depth.Rule { + return .{ .gpa = a, .k = .{ .learn_rows = true }, .prior = &.{0.01}, .most_drafts = 2, .family_costs = table, .shared_costs = table, .mtp_step_ms = 0, .plain_guard = true, .node_probabilities = false, .batch_rows = 8 }; +} + +test "shared combined prices: a measured plain intercept and a falling row fit remain independent" { + var table = try alloc.extendCosts(a, &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 80 } }, 8); + defer table.deinit(a); + for ([_]bool{ false, true }) |sampled| { + var r = rule(&table); + defer r.deinit(); + for ([_]u64{ 2, 4, 6 }) |rows| for (0..8) |_| { + const residual = 4 - 8 * @as(f64, @floatFromInt(rows - 2)); + try r.observeShared(2, rows, table.get(@intCast(rows)).? + residual, sampled, 0, rows == 2, false); + }; + const p = r.sharedPrice(2, sampled).?; + try t.expectApproxEqAbs(@as(f64, 4), p.plain, 1e-9); + try t.expectApproxEqAbs(@as(f64, 4), p.fixed, 1e-9); + try t.expectApproxEqAbs(@as(f64, -8), p.row, 1e-9); + try t.expect(r.sharedPrice(3, sampled) == null); + try t.expect(r.sharedPrice(2, !sampled) == null); + const probs = [_][]const f64{ &.{ 0.5, 0.25 }, &.{ 0.5, 0.25 } }; + const counts = try alloc.allocateDrafts(a, &.{ 1, 1 }, &probs, &table, p.fixed, 8, .{ .plain_ms = p.plain, .row_ms = p.row }); + defer a.free(counts); + try t.expectEqualSlices(u32, &.{ 2, 2 }, counts); + } +} + +test "shared combined prices: negative row corrections stop at the streams plain width" { + var table = try alloc.extendCosts(a, &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 80 } }, 8); + defer table.deinit(a); + for (2..9) |rows| { + const paid = alloc.rowTerm(&table, true, .{ .row_ms = -25 }, rows, 2); + try t.expect(table.get(@intCast(rows)).? + paid >= table.get(2).?); + } + try t.expectApproxEqAbs(@as(f64, -60), alloc.rowTerm(&table, true, .{ .row_ms = -25 }, 8, 2), 1e-9); +} + +fn noCopy(_: *anyopaque, _: *const depth.Who) bool { + return false; +} + +test "shared combined prices: all three paired allocators reach the width being measured" { + for ([_]bool{ false, true }) |sampled| { + var cfg = try Config.init(a, .{ .exact_width = 8, .mtp = true, .drafts = 2, .draft_prior = &.{ 0.01, 0.01 }, .mtp_step_ms = 0, .plain_guard = true, .hidden_rows = true, .learn_row_costs = true, .window_costs = &.{ .{ .width = 1, .ms = 10 }, .{ .width = 8, .ms = 80 } } }, 8, 7); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + for (0..4) |_| try e.rule.observeShared(2, 2, 22, sampled, 0, true, false); + try t.expect(e.rule.sharedPrice(2, sampled) != null); + try t.expectEqual(@as(u64, 4), e.rule.row_cost.leastRows(2, sampled)); + var streams: [2]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [2]win.Plan = undefined; + for (&streams, &plans) |*s, *p| { + s.* = try Stream.init(a, .{ .id = "priced", .prompt = &.{1}, .max_new = 100, .sampling = if (sampled) .{ .seed = 73, .temperature = 0.7 } else null }); + made += 1; + p.* = .{ .stream = s, .position = 1, .kind = .head, .tokens = &.{ 7, 8 } }; + } + try win.allocate(&e, &plans); + try t.expectEqual(@as(usize, 2), plans[0].count() + plans[1].count()); + var who = [_]depth.Who{ win.who(&streams[0]), win.who(&streams[1]) }; + var out: [2]i64 = undefined; + var unused: u8 = 0; + try e.rule.budgetsFor(&who, .{ .ptr = &unused, .copy = noCopy }, sampled, &out, 2); + try t.expectEqualSlices(i64, &.{ 1, 1 }, &out); + try @import("shared_drafts.zig").budgets(&e, &plans, &.{ 0, 1 }, &out); + try t.expectEqualSlices(i64, &.{ 1, 1 }, &out); + } +} From acbbbfd1201ded66e58986fe4cf4cd2c2bc0e946 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:21:41 +0000 Subject: [PATCH 36/59] lanes: keep askDrafts private; the shared round gets it as an argument #2687 made Engine.askDrafts public so shared_round.zig could call it, and proposal_batch_host.zig refuses a public askDrafts at compile time (draft internals must stay private). The engine now passes its private draft call to shared_round.run instead. --- zig/src/core/lanes/engine.zig | 7 +++++-- zig/src/core/lanes/shared_round.zig | 11 ++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index fe0bfbb5fb9..fac42b2849b 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -255,7 +255,10 @@ pub const Engine = struct { return .{ .rows = @intCast(rows), .keep = @intCast(o.path.len), .got = o.got }; } - const roundStreams = @import("shared_round.zig").run; + /// The shared round lives in its own file; it gets the private draft call as an argument so `askDrafts` stays private. + fn roundStreams(e: *Engine, entries: []*Stream) !void { + return @import("shared_round.zig").run(e, entries, Engine.askDrafts); + } /// Commit the target-sampled path (after the thinking budget's cut), each token with its path row's logprob row. pub fn conclude(e: *Engine, s: *Stream, p: Plan, sampled: []const u32, rows_lp: []const LogRow, tokens: []const u32, parents: []const i32, positions: []const u64) !Outcome { @@ -384,7 +387,7 @@ pub const Engine = struct { pub const askDrafts = Engine.askDrafts; } else struct {}; - pub fn askDrafts(e: *Engine, original: []const be.DraftRequest) !void { + fn askDrafts(e: *Engine, original: []const be.DraftRequest) !void { const requests = try @import("root_copy.zig").prepare(e, original); for (requests) |r| try trail.event(e, &.{ f("ev", str("draft")), f("stream", str(r.stream.id)), f("depth", int(r.depth)), f("position", int(r.position)), f("follow", .{ .u32s = r.follow }), f("rows", if (r.rows) |x| .{ .u32s = x } else .null) }); // a lone stream's lanes: the head tree or chain + grafts with the most expected tokens a round time diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 626f93a3086..8c5336a294e 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -16,18 +16,19 @@ const str = trail.str; const int = trail.int; /// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. -pub fn run(e: *Engine, entries: []*Stream) !void { - return if (e.cfg.plain_guard) runPriced(e, entries, true) else runPriced(e, entries, false); +/// `ask` is the engine's private draft call, passed in so it stays private to the engine. +pub fn run(e: *Engine, entries: []*Stream, comptime ask: anytype) !void { + return if (e.cfg.plain_guard) runPriced(e, entries, true, ask) else runPriced(e, entries, false, ask); } -fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { +fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool, comptime ask: anytype) !void { var sampled_before = false; if (independent) for (entries) |s| { sampled_before = sampled_before or s.sampling != null; }; const measured = independent and e.rule.sharedPrice(entries.len, sampled_before) != null; if (!measured) e.clock.start(); - try e.late.flush(e, Engine.askDrafts); + try e.late.flush(e, ask); // An unmeasured plain price retains the original clock boundary. if (measured) e.clock.start(); const a = e.arena.allocator(); @@ -82,7 +83,7 @@ fn runPriced(e: *Engine, entries: []*Stream, comptime independent: bool) !void { const s = plans[i].stream; r.* = .{ .stream = s, .follow = outcomes[i].follow, .rows = outcomes[i].path, .start = plans[i].position, .position = s.cache_len + 1, .depth = @intCast(d) }; } - try e.askDrafts(requests); + try ask(e, requests); } else { for (heads.items, budgets) |i, d| try e.draftLate(plans[i].stream, plans[i].position, outcomes[i].follow, outcomes[i].path, d); } From 029f8139da255dbc2ddb11e6a97b428b0c0006fa Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:38:15 +0000 Subject: [PATCH 37/59] lanes: one-line comments for the shared round's draft argument (lean) --- zig/src/core/lanes/engine.zig | 2 +- zig/src/core/lanes/shared_round.zig | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index fac42b2849b..c780bde3ff9 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -255,7 +255,7 @@ pub const Engine = struct { return .{ .rows = @intCast(rows), .keep = @intCast(o.path.len), .got = o.got }; } - /// The shared round lives in its own file; it gets the private draft call as an argument so `askDrafts` stays private. + /// The shared round lives in its own file and takes the private draft call as an argument. fn roundStreams(e: *Engine, entries: []*Stream) !void { return @import("shared_round.zig").run(e, entries, Engine.askDrafts); } diff --git a/zig/src/core/lanes/shared_round.zig b/zig/src/core/lanes/shared_round.zig index 8c5336a294e..4d4572547df 100644 --- a/zig/src/core/lanes/shared_round.zig +++ b/zig/src/core/lanes/shared_round.zig @@ -15,8 +15,7 @@ const f = ev.f; const str = trail.str; const int = trail.int; -/// The stream windows of a shared round in one forward, then each verified, committed and drafted on its own. -/// `ask` is the engine's private draft call, passed in so it stays private to the engine. +/// A shared round's windows in one forward, each verified, committed and drafted alone; `ask` drafts their heads. pub fn run(e: *Engine, entries: []*Stream, comptime ask: anytype) !void { return if (e.cfg.plain_guard) runPriced(e, entries, true, ask) else runPriced(e, entries, false, ask); } From 9c11d43bd5d41ed8675cfbb9b11b5bdcdb6c6a28 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:48:27 +0000 Subject: [PATCH 38/59] changelog: #2687 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 270690572e5..8d4aff1ede6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Lanes: shared rounds price a plain (undrafted) round apart from drafted rows, from trial rounds whose first is a dropped warm-up, and fit row costs from plain and drafted widths, so only how many drafts a round asks for changes; on gfx1151 with Qwen3.6-35B-A3B and MTP it is level with main with tokens unchanged, and opt-in `TF_SHARED_PRICE_LOG=1` prints each shared round's prices (#2687, refs #2605). + - Docs: strict tools under `tool_choice: "auto"` and `TENSORFOLD_TOOL_GRAMMAR`: what a strict tool's schema holds, what is served unconstrained and what is refused, and the legacy DeepSeek alias (#3235, fixes #3177). - Qwen 3.5, 3.6 and 3.8 on CUDA: a background prompt fill stops between chunks when a foreground request is waiting, keeps the prefix it has already filled, and resumes from there; replies are unchanged (#2873, part of #2812). Thanks to @tacosta. From 49e7a42b4657270e7446ae7a2056a5fb6ddb4633 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:47:34 +0000 Subject: [PATCH 39/59] qwen27 served: the reply-end keep test names its history, and a step runs it "a reply's end is born with its request's prompt" built its reply stream without history_len, so keepEnd pinned nothing. Since a reply supersedes equal-born states on its token path (e5f75e8be7), the request's own history went first and the other conversation's state stayed: the test failed, and no build step ran it. The served host names the history on every request that keeps one, the pin 3487174e65 added; the test now does too. test-qwen27-reply-cache-host runs it. Serving is unchanged. --- zig/build/qwen27_host.zig | 2 +- zig/src/native/qwen27_reply_cache_test.zig | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/zig/build/qwen27_host.zig b/zig/build/qwen27_host.zig index cf88bae4818..5d0b5be5def 100644 --- a/zig/build/qwen27_host.zig +++ b/zig/build/qwen27_host.zig @@ -91,7 +91,7 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M b.step("test-qwen-dense-geometry-host", "Dense config and full-size packed headers without shaders or a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = engine, .filters = dense_names.items })).step); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_served.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } }); - b.step("test-qwen27-reply-cache-host", "Served reply keeps retain a reusable history within the cache caps").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"qwen27 reply cache:"} })).step); + b.step("test-qwen27-reply-cache-host", "Served reply keeps retain a reusable history within the cache caps").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "qwen27 reply cache:", "a reply's end keeps its prompt's born" } })).step); const startup_test = b.addTest(.{ .root_module = host, .filters = &.{"qwen27 startup:"} }); const startup_step = b.step("test-qwen27-startup-host", "Startup draft stream counts and suffixes without a GPU"); for ([_]?[]const u8{ null, "1" }) |value| { diff --git a/zig/src/native/qwen27_reply_cache_test.zig b/zig/src/native/qwen27_reply_cache_test.zig index 50d2be0d67c..e9f12880d04 100644 --- a/zig/src/native/qwen27_reply_cache_test.zig +++ b/zig/src/native/qwen27_reply_cache_test.zig @@ -23,7 +23,8 @@ pub fn replyBorn(keepEnd: anytype, snapshots: pc.Snapshots, live: *usize) !void for (&tokens, 0..) |*word, i| word.* = @intCast(1_000_000 + i); const prompt = tokens[0 .. at + 7]; try t.expect(store.keep(prompt, at, null, &.{}, &.{})); - var s = try lanes.Stream.init(a, .{ .id = "reply", .prompt = prompt, .max_new = 100 }); + // the request's rendered history ends at its mark: what keepEnd pins while both states fit + var s = try lanes.Stream.init(a, .{ .id = "reply", .prompt = prompt, .max_new = 100, .history_len = at }); defer s.deinit(a); try s.context.appendSlice(a, tokens[at + 7 ..]); keepEnd(&store, a, &s, tokens.len); From 4bed140a1ef5b48b76971dad79101b53131e048a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:59:07 +0000 Subject: [PATCH 40/59] changelog: #3012 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d4aff1ede6..cf915319006 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Tests: the Qwen3.8-27B reply-end keep test names its history, as the keep pin added on 10 Nov requires, and `test-qwen27-reply-cache-host` now runs it (#3012). + - Lanes: shared rounds price a plain (undrafted) round apart from drafted rows, from trial rounds whose first is a dropped warm-up, and fit row costs from plain and drafted widths, so only how many drafts a round asks for changes; on gfx1151 with Qwen3.6-35B-A3B and MTP it is level with main with tokens unchanged, and opt-in `TF_SHARED_PRICE_LOG=1` prints each shared round's prices (#2687, refs #2605). - Docs: strict tools under `tool_choice: "auto"` and `TENSORFOLD_TOOL_GRAMMAR`: what a strict tool's schema holds, what is served unconstrained and what is refused, and the legacy DeepSeek alias (#3235, fixes #3177). From 94124b70ab0eadf96776e6846201c8421d772aae Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:39:48 +0000 Subject: [PATCH 41/59] lanes: one stored wait reason per queued request, and per-reason load metrics (#2135) Each queued request holds one wait reason, decided where the host last tried to admit it (pick, choose, a family planner's wait or skip, takeJob's ledger promise) and cleared on admission; publishing the ledger only counts the stored reasons and never asks the family's pool. The planner's Verdict carries the reason with its wait or skip, and DeepSeek-V4.1 names kv_pool, memory_floor or prefill_concurrent from its own counters, so the floor is never reported as memory_pressure. /metrics gains requests_waiting_by_reason{reason} (all ten labels, summing to requests_waiting), request_failures_total{reason}, restore_fallbacks_total and request_refusals_total{reason}; /v1/load gains waiting_by_reason and refusals. Refusals are counted where the chat, embeddings, rerank and speech routes answer with a client code, and every reply's bytes are unchanged. Shape B as designed by devopsfortunato on #2196. Co-authored-by: devopsfortunato <57877156+devopsfortunato@users.noreply.github.com> --- docs/api.md | 23 +- zig/build/cuda_server_host.zig | 1 + zig/build/lane_halt_host.zig | 1 + zig/src/core/lane_halt_test.zig | 2 +- zig/src/core/lane_host.zig | 2 + zig/src/core/lane_host_admit.zig | 34 ++- zig/src/core/lane_host_end.zig | 7 +- zig/src/core/lane_host_load.zig | 28 ++- zig/src/core/lane_host_tests.zig | 5 + zig/src/core/lane_job.zig | 4 +- zig/src/core/lane_rounds.zig | 26 ++- zig/src/core/lane_rounds_test.zig | 6 +- zig/src/core/lane_wait_reason_test.zig | 216 +++++++++++++++++++ zig/src/core/load_ledger.zig | 36 +++- zig/src/core/wait_reason.zig | 42 ++++ zig/src/families/deepseek_v41/sched_host.zig | 5 +- zig/src/server/chat.zig | 11 +- zig/src/server/embeddings.zig | 9 +- zig/src/server/load_metrics.zig | 17 ++ zig/src/server/refusals.zig | 9 + zig/src/server/rerank.zig | 3 +- zig/src/server/root.zig | 1 + zig/src/server/speech.zig | 7 +- zig/src/server/wait_reason_ledger_test.zig | 70 ++++++ 24 files changed, 528 insertions(+), 37 deletions(-) create mode 100644 zig/src/core/lane_wait_reason_test.zig create mode 100644 zig/src/core/wait_reason.zig create mode 100644 zig/src/server/refusals.zig create mode 100644 zig/src/server/wait_reason_ledger_test.zig diff --git a/docs/api.md b/docs/api.md index 1a47eba2936..47592c9b820 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1077,13 +1077,16 @@ publishes `server_info{model,backend,version,instance}` (always 1; `instance` is so counters restart only with a new `instance`), `process_start_time_seconds`, `engine_parked` (1 while `--idle-unload` has closed the engine), `lanes`, and `http_requests_active{route}`: model requests from the end of their headers to the end of their reply, by route group (`chat_completions`, `completions`, `responses`, -`messages`, `embeddings`, `speech`, `other`). +`messages`, `embeddings`, `speech`, `other`), and `request_refusals_total{reason}`: requests refused with a client +code, one of `engine_busy`, `engine_unavailable` and `memory_pressure` (the [Waits](#waits) codes, counted where +the chat, embeddings, rerank and speech routes answer with them) or `invalid_request` (the 400 when the engine +itself refuses the request it was handed), every label always present. An engine on the shared lane host adds these groups, each complete or absent: | Group | Families | | --- | --- | -| Requests | `waiting_prompt_tokens` (prompt tokens of queued requests, before any kept prefix restores part of them), `filling_prompt_tokens_left` (absent while a backend without fill progress fills), `requests_started_total`, `requests_requeued_total`, `background_yields_total` | +| Requests | `requests_waiting_by_reason{reason}` (queued requests by the one wait reason each holds, every reason always present; they sum to `requests_waiting`), `request_failures_total{reason}` (requests the engine took and ended failed: `backend_prompt`, `backend_round`, `lane_memory_alone`, `prompt_too_large`), `restore_fallbacks_total` (requests whose saved prefix could not be restored, so they prefilled from zero and were served), `waiting_prompt_tokens` (prompt tokens of queued requests, before any kept prefix restores part of them), `filling_prompt_tokens_left` (absent while a backend without fill progress fills), `requests_started_total`, `requests_requeued_total`, `background_yields_total` | | Work | `scheduler_tokens_total{mode}` with `prefill_compute`, `prefill_cache` and `decode` (output tokens after each request's first), counted as the work happens, and `prefill_busy_seconds_total`: engine seconds in prompt calls whose work `prefill_compute` counted. The `prefill_compute` delta over its delta is the prefill rate. A family round planner publishes no work group | | Capacity | `kv_capacity_mode{mode}` (`window` or `paged`), `lanes_free`, and for a paged engine `kv_pool_capacity_tokens`, `kv_pool_available_tokens`, `kv_pool_reclaimable_tokens`, `kv_pool_promised_tokens` with `pool="main"`, and `kv_pool_run_available` where the family needs a contiguous run. Published by the CUDA lane host: `window` for an engine without a page plan, `paged` with GLM-5.3-Flash's pool on rank 0; other paged families leave the group out until they name their pool | @@ -1093,9 +1096,21 @@ While the engine is parked, none of these engine values is shown: neither the gr unload closes the engine, the engine values are already gone and `engine_parked` is still 0, since a request then gets 503 with a retry; it turns 1 once a request can reload the engine. +A queued request holds one wait reason, decided where the engine last tried to admit it and kept until it starts +or leaves; reading the ledger never asks the engine again. Three reasons are client codes, the same strings as in +[Waits](#waits): `engine_busy` (no lane is free, or nothing more specific held it yet), `engine_unavailable` (the +device is stale until a put-back reaches it) and `memory_pressure` (memory pressure holds admission to the streams +already running). The rest are internal reasons, never a client code: `kv_pool`, `memory_floor` and +`prefill_concurrent` (a family round planner waits for KV pool pages, for the memory floor, or passes a long prompt +over while others prefill; DeepSeek-V4.1 names them), `prefix_cut` (it waits for a cut another prompt is filling), +`state_read` (it waits for its disk state's read ahead), `ledger_bytes` (its caches' bytes do not fit the KV ledger +now) and `pool_room` (the family's pool has no room for it now). A request behind one that waits for the pool, the +ledger or the planner holds that request's reason. `memory_floor` is never counted under `memory_pressure`. + `GET /v1/load` returns the same ledger as one JSON object from one read: `instance`, `timestamp` (the read's wall -time), `model`, `parked`, `lanes`, `http_active` by route group, and, when present, the request counts, -`capacity` with its `pools`, `tokens` and `busy_us`. Keys of a group no host fills are left out. It follows the +time), `model`, `parked`, `lanes`, `http_active` by route group, `refusals` by code, and, when present, the request +counts with `waiting_by_reason` (the same reasons, summing to `waiting`), `capacity` with its `pools`, `tokens` and +`busy_us`. Keys of a group no host fills are left out. It follows the `/metrics` access rule, and `--metrics-open` opens it too. ## Admission diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 167ed1e775b..f9597f0ec19 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -20,6 +20,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod startup_receipt.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = startup_spans, .filters = &.{"startup receipt:"} })).step); startup_receipt.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"startup receipt:"} })).step); @import("q27_profile_host.zig").steps(b, server_tests); + b.step("test-wait-reasons-server-host", "The ledger's wait, refusal and failure labels in /metrics and /v1/load").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"wait reason ledger:"} })).step); // the open-connection limit, one address's share under pressure and its flags (#3048), on Linux hosts too b.step("test-connection-admission-host", "Connection limit, per-address share, trusted proxies and idle shedding").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "security: ", "connection CLI:" } })).step); b.step("test-drama-cfg-host", "Drama CFG CLI, HTTP and voice transitions without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"CFG"} })).step); diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 6bc67f291ec..20c9ec1aba5 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -14,6 +14,7 @@ pub fn steps(b: *std.Build) void { b.step("test-lane-lone-host", "Existing lone-driver handoff and reclaim with a fake backend").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"lone driver"} })).step); b.step("test-lane-api-host", "Shared lane host and engine API CPU regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); b.step("test-shared-price-learning-host", "Independent plain prices and signed row learning together without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"shared combined prices:"} })).step); + b.step("test-wait-reasons-host", "Stored wait reasons in the load ledger with a fake backend and planner").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"wait reason ledger:"} })).step); b.step("test-conversation-cache-host", "Returning conversation eviction and queued-resume regressions without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{ "newest cache:", "queued cache:" } })).step); b.step("test-cache-progress-host", "One-state follow-ups and new conversations keep their next endpoint").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"queued cache: progress"} })).step); b.step("test-snapshot-index-host", "Prompt-cache lookup index against the whole-store scan, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"snapshot index:"} })).step); diff --git a/zig/src/core/lane_halt_test.zig b/zig/src/core/lane_halt_test.zig index e83462fca7f..8e676773fa4 100644 --- a/zig/src/core/lane_halt_test.zig +++ b/zig/src/core/lane_halt_test.zig @@ -45,7 +45,7 @@ fn haltCase(release_at_stop: ?*bool) !void { fn beginAdmit(_: *anyopaque) void {} fn admit(ctx: *anyopaque, ask: api.Rounds.Ask, _: *[]const u8) api.Rounds.Verdict { const p = self(ctx); - for (p.seqs.items) |x| if (!x.decoding) return .wait; + for (p.seqs.items) |x| if (!x.decoding) return .{ .wait = .engine_busy }; p.seqs.append(gpa, .{ .key = ask.key, .n = ask.prompt.len }) catch return .refuse; return .admit; } diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index dc305810180..a4e73a0bb8a 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -359,11 +359,13 @@ pub const LaneHost = struct { }; if (ledger.never(h, h.queued.items[at])) { // past the whole budget alone: no release will ever make it fit const job = h.queued.orderedRemove(at); + h.load.failures[@backingInt(load.Failure.prompt_too_large)] += 1; h.unlock(); h.finish(job, .failed, ledger.too_big); return .failed; } if (!ledger.promise(h, h.queued.items[at])) { // bytes before any stream: the job stays queued, nothing taken + h.queued.items[at].wait_reason = .ledger_bytes; h.unlock(); return .none; } diff --git a/zig/src/core/lane_host_admit.zig b/zig/src/core/lane_host_admit.zig index 2674d86149a..9240480d2ff 100644 --- a/zig/src/core/lane_host_admit.zig +++ b/zig/src/core/lane_host_admit.zig @@ -6,23 +6,39 @@ const prefix = @import("lane_host_prefix.zig"); const fetch = @import("lane_host_fetch.zig"); const pressure = @import("lane_host_pressure.zig"); const ledger = @import("lane_host_ledger.zig"); +const Wait = @import("wait_reason.zig").Wait; -/// The queued job to admit (its index), or null to hold; the caller holds the lock. +/// The queued job to admit (its index), or null to hold, each job held stores why; the caller holds the lock. pub fn pick(h: *LaneHost) ?usize { - if (pressure.holds(h)) return null; // under memory pressure nothing starts or is read ahead + if (pressure.holds(h)) return hold(h, .memory_pressure); // under memory pressure nothing starts or is read ahead if (!h.stale) fetch.queue(h); // disk states read ahead for queued requests, a lane free or not // a stale device takes no reply: `learn.refuse` ends the queued ones instead - if (h.stale or h.queued.items.len == 0 or h.admitted.items.len >= @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes)) return null; + if (h.stale) return hold(h, .engine_unavailable); + if (h.queued.items.len == 0 or h.admitted.items.len >= @min(h.info_.lanes, h.memory_lanes orelse h.info_.lanes)) return hold(h, .engine_busy); prefix.release(h); // requests whose awaited cut is in (or will not come) go on first while (true) { // a request that waits for a cut another prompt is filling stays queued, passed over const at = choose(h) orelse return null; if (!prefix.waits(h, h.queued.items[at])) return at; + h.queued.items[at].wait_reason = .prefix_cut; } } +/// Every queued job waits for `why`; no job is picked. +fn hold(h: *LaneHost, why: Wait) ?usize { + for (h.queued.items) |j| j.wait_reason = why; + return null; +} + /// Whether queued `job` is passed over: it waits for another fill's cut or for its disk state's read. fn passed(h: *LaneHost, job: *const Job) bool { - return prefix.waiting(job) or fetch.held(h, job); + return passedFor(h, job) != null; +} + +/// What queued `job` is passed over for (null: it is not). +fn passedFor(h: *LaneHost, job: *const Job) ?Wait { + if (prefix.waiting(job)) return .prefix_cut; + if (fetch.held(h, job)) return .state_read; + return null; } /// Whether every queued request waits for a cut or a read: an idle engine sleeps until a read wakes it (lock held). @@ -34,19 +50,25 @@ pub fn holds(h: *LaneHost) bool { /// The head, or one behind a head that waits for pool room, passing over prefix and read waiters. fn choose(h: *LaneHost) ?usize { const first = for (h.queued.items, 0..) |j, i| { - if (!passed(h, j)) break i; + j.wait_reason = passedFor(h, j) orelse break i; } else return null; if (h.info_.admit == null and !ledger.priced(h)) return first; // alone: the whole pool is free (kept prefixes give their blocks back); a ledger counts leases, not live streams if (if (ledger.priced(h)) !ledger.outstanding(h) else h.core.activeCount() == 0) return first; const head = h.queued.items[first]; if (fits(h, head)) return first; + const room: Wait = if (ledger.priced(h)) .ledger_bytes else .pool_room; + head.wait_reason = room; if (head.waits_since == null) head.waits_since = h.admissions; // it waits on the streams admitted before it waited: while one runs, later requests that fit go first; then none do for (h.admitted.items) |j| if (j.seq < head.waits_since.?) { - for (h.queued.items[first + 1 ..], first + 1..) |j2, i| if (!passed(h, j2) and fits(h, j2)) return i; + for (h.queued.items[first + 1 ..], first + 1..) |j2, i| { + j2.wait_reason = passedFor(h, j2) orelse if (fits(h, j2)) return i else room; + } return null; }; + // the rest stay behind the head that waits for room + for (h.queued.items[first + 1 ..]) |j2| j2.wait_reason = passedFor(h, j2) orelse room; return null; } diff --git a/zig/src/core/lane_host_end.zig b/zig/src/core/lane_host_end.zig index e3eb7434387..e302b3b7dea 100644 --- a/zig/src/core/lane_host_end.zig +++ b/zig/src/core/lane_host_end.zig @@ -4,6 +4,7 @@ const fill = @import("lane_host_fill.zig"); const lane_halt = @import("lane_halt.zig"); const lane_stream = @import("lane_stream.zig"); const recalls = @import("lane_host_recall.zig"); +const load = @import("lane_host_load.zig"); const LaneHost = @import("lane_host.zig").LaneHost; const Job = LaneHost.Job; @@ -55,6 +56,7 @@ pub fn failed(h: *const LaneHost, err: anyerror) void { /// A request the backend failed: the failure hook hears the error and the request ends with the backend's words. pub fn dropFailed(h: *LaneHost, job: *Job, err: anyerror) bool { failed(h, err); + load.failed(h, .backend_prompt); return h.drop(job, h.words(err)); } @@ -128,6 +130,7 @@ pub fn failAll(h: *LaneHost, message: []const u8) void { fn endFailed(h: *LaneHost, job: *Job, message: []const u8) void { h.lock(); fill.unfill(h, job); + h.load.failures[@backingInt(load.Failure.backend_round)] += 1; h.unlock(); if (job.started and !job.stream.finished) h.core.discard(&job.stream); h.finish(job, .failed, message); @@ -167,11 +170,11 @@ pub fn requeue(h: *LaneHost, job: *Job) bool { h.queued.insert(h.gpa, 0, job) catch break :blk false; break :blk true; }; - @import("lane_host_load.zig").ended(job); // before the teardown: this attempt's time leaves with it + load.ended(job); // before the teardown: this attempt's time leaves with it if (waits) { h.load.requeued += 1; h.memory_lanes = others; // under the lock: a publish reads it - } + } else if (others == 0) h.load.failures[@backingInt(load.Failure.lane_memory_alone)] += 1; h.unlock(); if (!waits) { h.finish(job, .failed, if (others > 0) "out of memory" else alone_words); diff --git a/zig/src/core/lane_host_load.zig b/zig/src/core/lane_host_load.zig index 4eae5b4ac35..547b95a011b 100644 --- a/zig/src/core/lane_host_load.zig +++ b/zig/src/core/lane_host_load.zig @@ -4,6 +4,8 @@ const ledger = @import("load_ledger.zig"); const LaneHost = @import("lane_host.zig").LaneHost; const Job = LaneHost.Job; +pub const Failure = ledger.reasons.Failure; + const Published = struct { requests: ?ledger.Requests = null, work: ?ledger.Work = null, capacity: ?ledger.Capacity = null }; /// The host's ledger state; counters move under the host mutex, the producer and `last` under `mutex`. @@ -20,6 +22,8 @@ pub const State = struct { prefill_cache: u64 = 0, decode: u64 = 0, busy_ns: u64 = 0, + failures: [ledger.reasons.failures]u64 = @splat(0), + restore_fallbacks: u64 = 0, /// The pool's last census, from the thread that changed the pool (under `mutex`); null: no pool watched. pool: ?ledger.Pool = null, }; @@ -114,6 +118,7 @@ pub fn progress(h: *LaneHost, job: *Job) void { /// The pass reported: its remaining computed tokens, its restored ones and its time; the caller holds the host mutex. pub fn credit(h: *LaneHost, job: *Job) void { + h.load.restore_fallbacks += @intFromBool(job.stream.reuse_failed); // once a job: its pass reports once const p = &job.load; if (!p.on) return; take(h, p); @@ -185,6 +190,20 @@ fn capacity(h: *const LaneHost) ?ledger.Capacity { return .{ .mode = c.mode, .lanes_free = @intCast(lanes -| h.admitted.items.len) }; } +/// A request the host took ends failed for `why`; the caller does not hold the host mutex. +pub fn failed(h: *LaneHost, why: Failure) void { + h.lock(); + defer h.unlock(); + h.load.failures[@backingInt(why)] += 1; +} + +/// A saved prefix could not be restored: the request prefills from zero and is still served (no host mutex held). +pub fn fellBack(h: *LaneHost) void { + h.lock(); + defer h.unlock(); + h.load.restore_fallbacks += 1; +} + /// A background pass gave its lane up to foreground work. pub fn yielded(h: *LaneHost) void { h.lock(); @@ -195,7 +214,11 @@ pub fn yielded(h: *LaneHost) void { /// The `requests` group from the host's lists; the caller holds the host mutex. fn requests(h: *const LaneHost) ledger.Requests { var waiting_tokens: u64 = 0; - for (h.queued.items) |job| waiting_tokens += job.request.prompt.len; + var by_reason: [ledger.reasons.waits]u32 = @splat(0); + for (h.queued.items) |job| { + waiting_tokens += job.request.prompt.len; + by_reason[@backingInt(job.wait_reason)] += 1; // stored on the admission path: nothing is asked here + } const left = filling(h); return .{ .running = @intCast(h.admitted.items.len), @@ -206,6 +229,9 @@ fn requests(h: *const LaneHost) ledger.Requests { .started = h.load.started, .requeued = h.load.requeued, .yields = h.load.yields, + .waiting_by_reason = by_reason, + .failures = h.load.failures, + .restore_fallbacks = h.load.restore_fallbacks, }; } diff --git a/zig/src/core/lane_host_tests.zig b/zig/src/core/lane_host_tests.zig index ab38b0e3d89..fb77dfa0ddd 100644 --- a/zig/src/core/lane_host_tests.zig +++ b/zig/src/core/lane_host_tests.zig @@ -30,3 +30,8 @@ test { test { _ = @import("lane_activity_test.zig"); } + +test { + _ = @import("lane_wait_reason_test.zig"); + _ = @import("wait_reason.zig"); +} diff --git a/zig/src/core/lane_job.zig b/zig/src/core/lane_job.zig index da61b92559e..3ab668ee65e 100644 --- a/zig/src/core/lane_job.zig +++ b/zig/src/core/lane_job.zig @@ -44,9 +44,11 @@ pub const Job = struct { prefix: @import("lane_host_prefix.zig").Waiting = .{}, // its wait for another fill's cut, while queued fetch: @import("lane_host_fetch.zig").Ticket = .{}, // its disk state read ahead, while queued lease: @import("kv_ledger.zig").Lease = .{}, // its caches' bytes in the host's ledger, from admission to its end + wait_reason: @import("wait_reason.zig").Wait = .engine_busy, // while queued: the hold its last admission try met - /// Record first admission once, including a family planner and a background pass that later yields. + /// Record first admission once (a family planner's too, a yielding background pass's kept) and clear its wait. pub fn noteAdmission(job: *Job) void { + job.wait_reason = .engine_busy; if (job.admitted_ns == null) job.admitted_ns = std.Io.Clock.awake.now(job.host.io).toNanoseconds(); } diff --git a/zig/src/core/lane_rounds.zig b/zig/src/core/lane_rounds.zig index 5db725cadbf..77254a95048 100644 --- a/zig/src/core/lane_rounds.zig +++ b/zig/src/core/lane_rounds.zig @@ -9,6 +9,7 @@ const status = @import("lane_host_status.zig"); const ends = @import("lane_host_end.zig"); const rows_host = @import("lane_host_rows.zig"); const pressure = @import("lane_host_pressure.zig"); +const load = @import("lane_host_load.zig"); const LaneHost = host.LaneHost; const Job = LaneHost.Job; const Allocator = std.mem.Allocator; @@ -24,14 +25,16 @@ pub const Rounds = struct { } } else struct {}; - pub const Verdict = enum { admit, wait, skip, refuse }; + /// Why a request stays queued (wait_reason.zig): the planner names it with its `wait` or `skip`. + pub const Wait = @import("wait_reason.zig").Wait; + pub const Verdict = union(enum) { admit, wait: Wait, skip: Wait, refuse }; pub const Piece = struct { key: usize, start: u64, end: u64, save: bool, run: bool = true }; pub const Ask = struct { key: usize, prompt: []const u32, max_tokens: u32, submitted_s: f64 }; pub const VTable = struct { /// An admission pass starts (a lane is free and requests wait). begin_admit: *const fn (ctx: *anyopaque) void, - /// The next queued request: start it, wait (it and those behind it), skip past it, or refuse it (`words`). + /// The next queued request: start it, wait (it and those behind) or skip it, each naming why, or refuse it. admit: *const fn (ctx: *anyopaque, ask: Ask, words: *[]const u8) Verdict, /// The pass is decided: what runs before the admitted streams begin. admitted: *const fn (ctx: *anyopaque) anyerror!void, @@ -68,6 +71,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { rd.vtable.begin_admit(rd.ctx); var free = h.info_.lanes - h.admitted.items.len; var i: usize = 0; + var rest: ?Rounds.Wait = null; // why the jobs from `i` on wait, when the planner said while (i < h.queued.items.len and free > 0 and !pressure.holds(h)) { const job = h.queued.items[i]; var why: []const u8 = ""; @@ -83,14 +87,26 @@ fn round(h: *LaneHost, rd: Rounds) bool { _ = h.queued.orderedRemove(i); free -= 1; }, - .wait => break, - .skip => i += 1, + .wait => |r| { + rest = r; + break; + }, + .skip => |r| { + job.wait_reason = r; + i += 1; + }, .refuse => { if (refused.append(h.gpa, .{ .job = job, .why = why })) |_| {} else |_| break; _ = h.queued.orderedRemove(i); }, } } + // those behind a wait wait with it (FIFO); else the pass ran out of lanes, or pressure came + const behind: Rounds.Wait = rest orelse if (pressure.holds(h)) .memory_pressure else .engine_busy; + for (h.queued.items[@min(i, h.queued.items.len)..]) |job| job.wait_reason = behind; + } else { + const why: Rounds.Wait = if (h.stale) .engine_unavailable else if (pressure.holds(h)) .memory_pressure else .engine_busy; + for (h.queued.items) |job| job.wait_reason = why; } h.unlock(); for (refused.items) |x| h.finish(x.job, .failed, x.why); @@ -107,6 +123,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { _ = ends.dropFailed(h, job, e); continue; }; + if (b.damaged) load.fellBack(h); // its saved prefix was dropped: it prefills from 0 and is still served rd.vtable.began(rd.ctx, @intFromPtr(job), b.damaged); } // this round's pieces, a decode round of the streams decoding, then the prompts whose rows are in @@ -196,6 +213,7 @@ fn dropPiece(h: *LaneHost, job: *Job, message: []const u8) void { while (i < h.finals.items.len) { if (h.finals.items[i] == key) _ = h.finals.orderedRemove(i) else i += 1; } + load.failed(h, .backend_prompt); _ = h.drop(job, message); } diff --git a/zig/src/core/lane_rounds_test.zig b/zig/src/core/lane_rounds_test.zig index 89a07a09517..68c17235aa7 100644 --- a/zig/src/core/lane_rounds_test.zig +++ b/zig/src/core/lane_rounds_test.zig @@ -37,7 +37,7 @@ test "a round planner: prompts in pieces between the other streams' decode round const p = self(ctx); for (p.seqs.items) |x| if (!x.decoding) { p.waits += 1; - return .wait; + return .{ .wait = .engine_busy }; }; p.seqs.append(gpa, .{ .key = ask.key, .n = ask.prompt.len }) catch return .refuse; return .admit; @@ -249,7 +249,7 @@ test "under a round planner a learn request still steps while no request waits o const Idle = struct { fn none(_: *anyopaque) void {} fn admit(_: *anyopaque, _: api.Rounds.Ask, _: *[]const u8) api.Rounds.Verdict { - return .wait; + return .{ .wait = .engine_busy }; } fn admitted(_: *anyopaque) anyerror!void {} fn key(_: *anyopaque, _: usize) void {} @@ -416,7 +416,7 @@ test "a failed round ends the prompts whose finals it never ran: their lanes fre fn beginAdmit(_: *anyopaque) void {} fn admit(ctx: *anyopaque, ask: api.Rounds.Ask, _: *[]const u8) api.Rounds.Verdict { const p = self(ctx); - for (p.seqs.items) |x| if (!x.decoding) return .wait; + for (p.seqs.items) |x| if (!x.decoding) return .{ .wait = .engine_busy }; p.seqs.append(gpa, .{ .key = ask.key, .n = ask.prompt.len }) catch return .refuse; return .admit; } diff --git a/zig/src/core/lane_wait_reason_test.zig b/zig/src/core/lane_wait_reason_test.zig new file mode 100644 index 00000000000..c774110e300 --- /dev/null +++ b/zig/src/core/lane_wait_reason_test.zig @@ -0,0 +1,216 @@ +//! Wait reasons in the load ledger: stored on the admission path, read by the publish, one for each queued request. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const LaneHost = @import("lane_host.zig").LaneHost; +const admit = @import("lane_host_admit.zig"); +const ends = @import("lane_host_end.zig"); +const Ledger = api.load_ledger.Ledger; +const Requests = api.load_ledger.Requests; +const Wait = api.Rounds.Wait; +const Request = api.Request; + +const Rig = struct { + cfg: lanes.Config, + target: lanes.fake.Fake, + clock: lanes.fake.FixedClock = .{}, + core: lanes.Engine = undefined, + host: LaneHost = undefined, + + fn init(r: *Rig, info: api.Info, pieces: bool) !void { + const gpa = std.testing.allocator; + r.cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + r.target = .{ .gpa = gpa }; + r.clock = .{}; + r.core = lanes.Engine.init(gpa, &r.cfg, if (pieces) r.target.pieceBackend() else r.target.backend(), r.clock.clock()); + r.host = LaneHost.init(gpa, std.testing.io, &r.core, info); + } + + fn deinit(r: *Rig) void { + r.host.stop(); + r.core.deinit(); + r.target.deinit(); + r.cfg.deinit(std.testing.allocator); + } + + fn submit(r: *Rig, id: api.Id, request: *const Request) !void { + try r.host.engine().submit(id, request, .{ .ctx = r, .event = ignore }); + } + + fn ignore(_: *anyopaque, _: api.Id, _: *const api.Event) void {} +}; + +/// A DeepSeek-V4.1-like planner: a long prompt (first token 1) is passed over, any other waits for `second`. +const Plan = struct { + second: Wait = .kv_pool, + admits: u32 = 0, + + fn self(ctx: *anyopaque) *Plan { + return @ptrCast(@alignCast(ctx)); + } + fn none(_: *anyopaque) void {} + fn admitFn(ctx: *anyopaque, ask: api.Rounds.Ask, _: *[]const u8) api.Rounds.Verdict { + const p = self(ctx); + p.admits += 1; + return switch (ask.prompt[0]) { + 1 => .{ .skip = .prefill_concurrent }, + else => .{ .wait = p.second }, + }; + } + fn admitted(_: *anyopaque) anyerror!void {} + fn key(_: *anyopaque, _: usize) void {} + fn began(_: *anyopaque, _: usize, _: bool) void {} + fn plan(_: *anyopaque, pieces: *std.ArrayList(api.Rounds.Piece), finals: *std.ArrayList(usize)) anyerror!void { + pieces.clearRetainingCapacity(); + finals.clearRetainingCapacity(); + } + fn after(_: *anyopaque, _: f64, _: f64) void {} + fn rounds(p: *Plan) api.Rounds { + return .{ .ctx = p, .vtable = &.{ .begin_admit = none, .admit = admitFn, .admitted = admitted, .arm = key, .began = began, .plan = plan, .left = key, .after = after } }; + } +}; + +fn at(r: Requests, w: Wait) u32 { + return r.waiting_by_reason[@backingInt(w)]; +} + +const long = [_]u32{ 1, 5, 9, 2 }; +const second = [_]u32{ 2, 6, 5, 3 }; +const third = [_]u32{ 3, 5, 8, 9 }; +const fourth = [_]u32{ 4, 7, 1, 8 }; + +test "wait reason ledger: a planner's kv_pool, memory_floor and prefill_concurrent reach the ledger, not engine_busy" { + var rig: Rig = undefined; + try rig.init(.{ .lanes = 2 }, true); + defer rig.deinit(); + var pl: Plan = .{}; + rig.host.rounds = pl.rounds(); + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const ra: Request = .{ .prompt = &long, .max_tokens = 4 }; + const rb: Request = .{ .prompt = &second, .max_tokens = 4 }; + const rc: Request = .{ .prompt = &third, .max_tokens = 4 }; + try rig.submit(1, &ra); + try rig.submit(2, &rb); + try rig.submit(3, &rc); + errdefer ends.closeAll(&rig.host); + try std.testing.expectEqual(@as(u32, 3), at(ledger.read().requests.?, .engine_busy)); // not examined yet + _ = api.Rounds.Test.step(&rig.host); + var r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 3), r.waiting); + try std.testing.expectEqual(@as(u32, 1), at(r, .prefill_concurrent)); + try std.testing.expectEqual(@as(u32, 2), at(r, .kv_pool)); // the wait and the request behind it (FIFO) + try std.testing.expectEqual(@as(u32, 0), at(r, .engine_busy)); + pl.second = .memory_floor; + _ = api.Rounds.Test.step(&rig.host); + r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 2), at(r, .memory_floor)); + try std.testing.expectEqual(@as(u32, 0), at(r, .memory_pressure)); // the floor is not pressure + try std.testing.expectEqual(@as(u32, 0), at(r, .kv_pool)); + try std.testing.expectEqual(@as(u32, 1), at(r, .prefill_concurrent)); + try std.testing.expectEqual(@as(u32, 0), at(r, .engine_busy)); + ends.closeAll(&rig.host); + try std.testing.expectEqual(@as(u64, 0), ledger.read().requests.?.waitingTotal()); +} + +test "wait reason ledger: a fresh host publishes every reason, each at zero" { + var rig: Rig = undefined; + try rig.init(.{ .lanes = 2 }, false); + defer rig.deinit(); + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const r = ledger.read().requests.?; + try std.testing.expectEqual(std.enums.values(Wait).len, r.waiting_by_reason.len); + for (r.waiting_by_reason) |n| try std.testing.expectEqual(@as(u32, 0), n); + try std.testing.expectEqual(@as(u32, 0), r.waiting); +} + +test "wait reason ledger: the reasons sum to waiting through an admission and a cancel while queued" { + var rig: Rig = undefined; + try rig.init(.{ .lanes = 4 }, true); + defer rig.deinit(); + var pl: Plan = .{}; + rig.host.rounds = pl.rounds(); + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const ra: Request = .{ .prompt = &fourth, .max_tokens = 4 }; + const rb: Request = .{ .prompt = &long, .max_tokens = 4 }; + const rc: Request = .{ .prompt = &second, .max_tokens = 4 }; + const rd: Request = .{ .prompt = &third, .max_tokens = 4 }; + try rig.submit(1, &ra); + try rig.submit(2, &rb); + try rig.submit(3, &rc); + try rig.submit(4, &rd); + errdefer ends.closeAll(&rig.host); + // the head leaves the queue for a lane: its reason goes with it + const taken = rig.host.takeJob(); + try std.testing.expect(taken == .job); + _ = api.Rounds.Test.step(&rig.host); + var r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 1), r.running); + try std.testing.expectEqual(@as(u32, 3), r.waiting); + try std.testing.expectEqual(@as(u32, 1), at(r, .prefill_concurrent)); + try std.testing.expectEqual(@as(u32, 2), at(r, .kv_pool)); + try std.testing.expectEqual(@as(u64, r.waiting), r.waitingTotal()); + // the request passed over is cancelled while queued: its reason leaves with it + rig.host.engine().cancel(2); + ends.takeCancels(&rig.host); + r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 2), r.waiting); + try std.testing.expectEqual(@as(u32, 0), at(r, .prefill_concurrent)); + try std.testing.expectEqual(@as(u32, 2), at(r, .kv_pool)); + try std.testing.expectEqual(@as(u64, r.waiting), r.waitingTotal()); + ends.closeAll(&rig.host); + r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 0), r.running); + try std.testing.expectEqual(@as(u64, 0), r.waitingTotal()); +} + +/// A family pool that counts how often the host asks it. +const Counted = struct { + fn fits(ctx: *anyopaque, _: u32, _: u32) bool { + const calls: *u32 = @ptrCast(@alignCast(ctx)); + calls.* += 1; + return true; + } +}; + +test "wait reason ledger: publishing the ledger reads stored reasons and never asks the family's pool" { + var calls: u32 = 0; + var rig: Rig = undefined; + try rig.init(.{ .lanes = 1, .admit = .{ .ctx = &calls, .fits = Counted.fits } }, false); + defer rig.deinit(); + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const ra: Request = .{ .prompt = &second, .max_tokens = 4 }; + const rb: Request = .{ .prompt = &third, .max_tokens = 4 }; + const rc: Request = .{ .prompt = &fourth, .max_tokens = 4 }; + try rig.submit(1, &ra); + try rig.submit(2, &rb); + try rig.submit(3, &rc); + errdefer ends.closeAll(&rig.host); + for (0..8) |_| { // each unlock publishes: the requests group is built again every time + rig.host.lock(); + rig.host.unlock(); + } + try std.testing.expectEqual(@as(u32, 3), at(ledger.read().requests.?, .engine_busy)); + // an admission attempt decides the reason; the publishes after it only read it + rig.host.lock(); + rig.host.stale = true; + try std.testing.expect(admit.pick(&rig.host) == null); + rig.host.stale = false; + rig.host.unlock(); + for (0..8) |_| { + rig.host.lock(); + rig.host.unlock(); + } + const r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 3), at(r, .engine_unavailable)); + try std.testing.expectEqual(@as(u64, 3), r.waitingTotal()); + try std.testing.expectEqual(@as(u32, 0), calls); + ends.closeAll(&rig.host); +} diff --git a/zig/src/core/load_ledger.zig b/zig/src/core/load_ledger.zig index e855f0a7a0e..f115b6e401b 100644 --- a/zig/src/core/load_ledger.zig +++ b/zig/src/core/load_ledger.zig @@ -1,6 +1,8 @@ //! The server's load ledger: scheduler load a host publishes as it happens, read whole by /metrics and /v1/load. const std = @import("std"); const api = @import("engine_api.zig"); +/// The fixed wait, refusal and failure reasons the ledger counts by (wait_reason.zig). +pub const reasons = @import("wait_reason.zig"); /// The model routes `http_requests_active` counts apart; a fixed set, so the label never grows. pub const RouteGroup = enum { chat_completions, completions, responses, messages, embeddings, speech, other }; @@ -20,6 +22,19 @@ pub const Requests = struct { started: u64 = 0, requeued: u64 = 0, yields: u64 = 0, + /// The queued requests by their stored wait reason: they sum to `waiting`. + waiting_by_reason: [reasons.waits]u32 = @splat(0), + /// Requests the host took and ended failed, by reason. + failures: [reasons.failures]u64 = @splat(0), + /// Saved prefixes that could not be restored, so the request prefilled from zero and was served. + restore_fallbacks: u64 = 0, + + /// The queued requests over every wait reason: `waiting` when each queued request holds one reason. + pub fn waitingTotal(r: Requests) u64 { + var n: u64 = 0; + for (r.waiting_by_reason) |x| n += x; + return n; + } }; /// The `work` group: prompt and output tokens as they are computed, and the engine time of their prompt calls. @@ -64,6 +79,8 @@ pub const Snapshot = struct { parked: bool, lanes: u32, http: [groups]u32, + /// What clients were refused, by code: the server counts these, attached engine or not. + refusals: [reasons.refusals]u64 = @splat(0), requests: ?Requests = null, work: ?Work = null, capacity: ?Capacity = null, @@ -86,6 +103,7 @@ pub const Ledger = struct { parked: bool = false, lanes: u32 = 0, http: [groups]u32 = @splat(0), + refusals: [reasons.refusals]u64 = @splat(0), /// Raised by every attach and detach: a handle from before it writes nothing. epoch: u64 = 0, attached: ?api.Engine = null, @@ -159,12 +177,22 @@ pub const Ledger = struct { l.http[@backingInt(g)] -|= 1; } + /// A client was refused with `r`'s code. + pub fn refused(l: *Ledger, r: reasons.Refusal) void { + l.mutex.lockUncancelable(l.io); + defer l.mutex.unlock(l.io); + l.refusals[@backingInt(r)] += 1; + } + /// The ledger at one instant; counters carry every earlier host's. pub fn read(l: *Ledger) Snapshot { l.mutex.lockUncancelable(l.io); defer l.mutex.unlock(l.io); - var s: Snapshot = .{ .instance = l.instance, .start_s = l.start_s, .parked = l.parked, .lanes = l.lanes, .http = l.http }; - if (l.cur.requests) |r| s.requests = addRequests(r, l.base.requests.?); + var s: Snapshot = .{ .instance = l.instance, .start_s = l.start_s, .parked = l.parked, .lanes = l.lanes, .http = l.http, .refusals = l.refusals }; + if (l.cur.requests) |r| { + std.debug.assert(r.waitingTotal() == r.waiting); // one stored reason a queued request + s.requests = addRequests(r, l.base.requests.?); + } if (l.cur.work) |w| s.work = addWork(w, l.base.work.?); if (l.cur.capacity) |c| if (c.mode == .window or l.cur.pool != null) { s.capacity = c; @@ -181,6 +209,8 @@ fn fold(base: *Groups, cur: Groups) void { b.started += r.started; b.requeued += r.requeued; b.yields += r.yields; + for (&b.failures, r.failures) |*x, y| x.* += y; + b.restore_fallbacks += r.restore_fallbacks; } if (cur.work) |w| base.work = addWork(w, base.work.?); } @@ -191,6 +221,8 @@ fn addRequests(r: Requests, base: Requests) Requests { out.started += base.started; out.requeued += base.requeued; out.yields += base.yields; + for (&out.failures, base.failures) |*x, y| x.* += y; + out.restore_fallbacks += base.restore_fallbacks; return out; } diff --git a/zig/src/core/wait_reason.zig b/zig/src/core/wait_reason.zig new file mode 100644 index 00000000000..febc5daa224 --- /dev/null +++ b/zig/src/core/wait_reason.zig @@ -0,0 +1,42 @@ +//! Fixed reasons: a queued request's wait (the first three are server/wait_reason.zig's codes), refusals, failures. +const std = @import("std"); + +/// Why a queued request has not started: the hold its last admission attempt met, one reason a queued request. +pub const Wait = enum { + /// No lane is free, or nothing more specific held it yet. + engine_busy, + /// The device is stale: a put-back has not reached it, so no reply starts. + engine_unavailable, + /// Memory pressure holds admission to the streams already running. + memory_pressure, + /// The family's planner waits for KV pool pages that running requests hold. + kv_pool, + /// The family's planner waits for the memory floor (TF_DSV41_FLOOR_*); never counted as `memory_pressure`. + memory_floor, + /// The family's planner passes over a long prompt while others prefill (TF_DSV41_PREFILL_CONCURRENT). + prefill_concurrent, + /// It waits for a cut another prompt is filling (lane_host_prefix.zig). + prefix_cut, + /// It waits for its disk state's read ahead (lane_host_fetch.zig). + state_read, + /// Its caches' bytes do not fit the host's KV ledger now (lane_host_ledger.zig). + ledger_bytes, + /// The family's own pool has no room for it now (Info.admit). + pool_room, +}; + +/// What a client sees as a refusal: the three capacity codes and the engine's 400 for a request it cannot take. +pub const Refusal = enum { engine_busy, engine_unavailable, memory_pressure, invalid_request }; + +/// A request the host took and then ended failed, with its own words: not a refusal a client can retry by code. +pub const Failure = enum { backend_prompt, backend_round, lane_memory_alone, prompt_too_large }; + +pub const waits = std.enums.values(Wait).len; +pub const refusals = std.enums.values(Refusal).len; +pub const failures = std.enums.values(Failure).len; + +test "wait reason ledger: the client codes lead the set, each tag at its own index" { + try std.testing.expectEqual(@as(usize, 10), waits); + for (std.enums.values(Wait), 0..) |r, i| try std.testing.expectEqual(i, @backingInt(r)); + try std.testing.expectEqualStrings("memory_pressure", @tagName(std.enums.values(Wait)[2])); +} diff --git a/zig/src/families/deepseek_v41/sched_host.zig b/zig/src/families/deepseek_v41/sched_host.zig index 7d6bcc7d4df..0f66775857f 100644 --- a/zig/src/families/deepseek_v41/sched_host.zig +++ b/zig/src/families/deepseek_v41/sched_host.zig @@ -101,8 +101,9 @@ pub const SchedHost = struct { }; return .admit; }, - .wait => return .wait, - .skip => return .skip, + // the planner's own counters say which hold it met: the KV pool's pages or the memory floor + .wait => return .{ .wait = if (h.p.counts.pool_waits > before.pool_waits) .kv_pool else .memory_floor }, + .skip => return .{ .skip = .prefill_concurrent }, // its one skip: a long prompt past the concurrent bound .refuse => |r| { words.* = switch (r) { .too_large => "the request needs more KV pool pages than the pool has", diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 24fa9d58c84..f787cf581f2 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -13,6 +13,7 @@ const cached_tokens = @import("cached_tokens.zig"); const ids = @import("ids.zig"); const clock = @import("clock.zig"); const wait = @import("wait_reason.zig"); +const refusals = @import("refusals.zig"); const server_mod = @import("server.zig"); const Server = server_mod.Server; const chunk_plan = @import("chunk_plan.zig"); @@ -262,12 +263,12 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an if (srv.keepalive) |k| k.begin(); // the GPU is busy: the idle ticker holds its commits defer if (srv.keepalive) |k| k.end(); srv.engine.submit(id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return switch (e) { - error.Busy => cx.wait(wait.engine_busy, "the engine is busy; retry shortly", .{}), - error.Closed => cx.wait(wait.engine_unavailable, "the engine is unavailable; retry after it restarts", .{}), - error.InvalidSpans => cx.fail(.request, "the prompt span layout is invalid", .{}), - error.InvalidRequest => cx.fail(.request, "the request does not match the loaded model", .{}), + error.Busy => refusals.count(srv, .engine_busy, cx.wait(wait.engine_busy, "the engine is busy; retry shortly", .{})), + error.Closed => refusals.count(srv, .engine_unavailable, cx.wait(wait.engine_unavailable, "the engine is unavailable; retry after it restarts", .{})), + error.InvalidSpans => refusals.count(srv, .invalid_request, cx.fail(.request, "the prompt span layout is invalid", .{})), + error.InvalidRequest => refusals.count(srv, .invalid_request, cx.fail(.request, "the request does not match the loaded model", .{})), error.Stale => cx.fail(.server, "{s}", .{api.stale_message}), - error.MemoryPressure => cx.wait(wait.memory_pressure, "{s}", .{api.pressure_message}), + error.MemoryPressure => refusals.count(srv, .memory_pressure, cx.wait(wait.memory_pressure, "{s}", .{api.pressure_message})), }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; diff --git a/zig/src/server/embeddings.zig b/zig/src/server/embeddings.zig index dfa259feca2..c8a7724e5d8 100644 --- a/zig/src/server/embeddings.zig +++ b/zig/src/server/embeddings.zig @@ -8,6 +8,7 @@ const response = @import("embedding_response.zig"); const openai = @import("openai.zig"); const http_body = @import("http_body.zig"); const wait = @import("wait_reason.zig"); +const refusals = @import("refusals.zig"); const Conn = @import("http_conn.zig").Conn; const Server = @import("server.zig").Server; pub const Failure = errors.Refused || error{Cancelled}; @@ -29,10 +30,10 @@ pub fn reply(srv: *Server, cx: *errors.Cx, body: json.Value, gone: anytype) Fail const id = srv.next_id.fetchAdd(1, .monotonic); if (gone.check()) return error.Cancelled; const ended = @import("prompt_only_wait.zig").run(srv.engine, srv.io, id, &ask, gone) catch |err| return switch (err) { - error.InvalidRequest, error.InvalidSpans => cx.refuse("the embedding request does not match the model"), - error.Busy => cx.wait(wait.engine_busy, "the embedding engine is busy; retry shortly", .{}), - error.Closed, error.Stale => cx.wait(wait.engine_unavailable, "the embedding engine is unavailable", .{}), - error.MemoryPressure => cx.wait(wait.memory_pressure, "{s}", .{api.pressure_message}), + error.InvalidRequest, error.InvalidSpans => refusals.count(srv, .invalid_request, cx.refuse("the embedding request does not match the model")), + error.Busy => refusals.count(srv, .engine_busy, cx.wait(wait.engine_busy, "the embedding engine is busy; retry shortly", .{})), + error.Closed, error.Stale => refusals.count(srv, .engine_unavailable, cx.wait(wait.engine_unavailable, "the embedding engine is unavailable", .{})), + error.MemoryPressure => refusals.count(srv, .memory_pressure, cx.wait(wait.memory_pressure, "{s}", .{api.pressure_message})), }; switch (ended) { .cancelled => return error.Cancelled, diff --git a/zig/src/server/load_metrics.zig b/zig/src/server/load_metrics.zig index 6f3d6a3e84c..f7a8121d58e 100644 --- a/zig/src/server/load_metrics.zig +++ b/zig/src/server/load_metrics.zig @@ -3,6 +3,7 @@ const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); const ledger = api.load_ledger; +const reasons = ledger.reasons; const Allocator = std.mem.Allocator; const Value = json.Value; @@ -27,7 +28,17 @@ pub fn render(w: *std.Io.Writer, s: ledger.Snapshot, id: Identity) !void { try family(w, "http_requests_active", "gauge", "Model requests from the end of their headers to the end of their reply, by route group."); for (std.enums.values(ledger.RouteGroup)) |g| try w.print("{s}http_requests_active{{route=\"{s}\"}} {d}\n", .{ prefix, @tagName(g), s.active(g) }); + try family(w, "request_refusals_total", "counter", "Requests refused with a client code: the three capacity codes and the engine's invalid_request."); + for (std.enums.values(reasons.Refusal)) |x| + try w.print("{s}request_refusals_total{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), s.refusals[@backingInt(x)] }); if (s.requests) |r| { + try family(w, "requests_waiting_by_reason", "gauge", "Queued requests by the one wait reason each holds; they sum to requests_waiting."); + for (std.enums.values(reasons.Wait)) |x| + try w.print("{s}requests_waiting_by_reason{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), r.waiting_by_reason[@backingInt(x)] }); + try family(w, "request_failures_total", "counter", "Requests the engine took and then ended failed, by fixed reason."); + for (std.enums.values(reasons.Failure)) |x| + try w.print("{s}request_failures_total{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), r.failures[@backingInt(x)] }); + try gauge(w, "restore_fallbacks_total", "counter", "Requests whose saved prefix could not be restored: they prefilled from zero and were served.", r.restore_fallbacks); try gauge(w, "waiting_prompt_tokens", "gauge", "Prompt tokens of the queued requests, before any kept prefix restores part of them.", r.waiting_prompt_tokens); if (r.filling_left) |left| try gauge(w, "filling_prompt_tokens_left", "gauge", "Prompt tokens still to prefill in the foreground passes filling now.", left); try gauge(w, "requests_started_total", "counter", "Requests the engine accepted into its queue.", r.started); @@ -70,9 +81,15 @@ pub fn object(a: Allocator, s: ledger.Snapshot, now_s: f64, model: []const u8) A const http = try json.newObject(a); for (std.enums.values(ledger.RouteGroup)) |g| try http.put(a, @tagName(g), try json.intValue(a, s.active(g))); try o.put(a, "http_active", .{ .object = http }); + const refusals = try json.newObject(a); + for (std.enums.values(reasons.Refusal)) |x| try refusals.put(a, @tagName(x), try json.intValue(a, s.refusals[@backingInt(x)])); + try o.put(a, "refusals", .{ .object = refusals }); if (s.requests) |r| { try o.put(a, "running", try json.intValue(a, r.running)); try o.put(a, "waiting", try json.intValue(a, r.waiting)); + const by_reason = try json.newObject(a); + for (std.enums.values(reasons.Wait)) |x| try by_reason.put(a, @tagName(x), try json.intValue(a, r.waiting_by_reason[@backingInt(x)])); + try o.put(a, "waiting_by_reason", .{ .object = by_reason }); try o.put(a, "requests_started", try json.intValue(a, r.started)); try o.put(a, "requests_requeued", try json.intValue(a, r.requeued)); try o.put(a, "background_yields", try json.intValue(a, r.yields)); diff --git a/zig/src/server/refusals.zig b/zig/src/server/refusals.zig new file mode 100644 index 00000000000..16f19e57eb5 --- /dev/null +++ b/zig/src/server/refusals.zig @@ -0,0 +1,9 @@ +//! A client refusal counted by its code in the load ledger, beside the reply that names it. +const api = @import("engine_api"); +const Refused = @import("errors.zig").Refused; + +/// Counts `r` in the server's ledger and hands `err` back unchanged: the reply is the one the caller built. +pub fn count(srv: anytype, r: api.load_ledger.reasons.Refusal, err: Refused) Refused { + srv.load.refused(r); + return err; +} diff --git a/zig/src/server/rerank.zig b/zig/src/server/rerank.zig index 94419ec3f97..90f406a5a4b 100644 --- a/zig/src/server/rerank.zig +++ b/zig/src/server/rerank.zig @@ -8,6 +8,7 @@ const http_body = @import("http_body.zig"); const reply_text = @import("reply_text.zig"); const model_text = @import("model_text.zig"); const wait = @import("wait_reason.zig"); +const refusals = @import("refusals.zig"); const Server = @import("server.zig").Server; const Conn = @import("http_conn.zig").Conn; const Value = json.Value; @@ -154,7 +155,7 @@ fn failed(srv: *Server, cx: *Cx) errors.Refused { return if (healthy(srv)) cx.fail(.server, "rerank inference failed", .{}) else - cx.wait(wait.engine_unavailable, "the rerank engine is unavailable", .{}); + refusals.count(srv, .engine_unavailable, cx.wait(wait.engine_unavailable, "the rerank engine is unavailable", .{})); } fn healthy(srv: *Server) bool { diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index f57802c32fc..cd11aab1a5b 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -43,6 +43,7 @@ test { _ = @import("idle_unload.zig"); _ = @import("idle_unload_test.zig"); _ = @import("wait_reason_test.zig"); + _ = @import("wait_reason_ledger_test.zig"); _ = @import("name_priority_http_test.zig"); _ = @import("ws_frame.zig"); _ = @import("ws_upgrade.zig"); diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index b9a49c74d85..0c270a2e16e 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -159,6 +159,7 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf var held = srv.speech_inflight.load(.acquire); while (true) { if (held >= @max(1, srv.info.lanes)) { + srv.load.refused(.engine_busy); cx.code = wait.engine_busy; return fail(c, cx, id, metadata.*, .capacity, "speech output capacity is full"); } @@ -213,11 +214,15 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf releaseLane(srv, &lane_released); return switch (e) { error.Busy => blk: { + srv.load.refused(.engine_busy); cx.code = wait.engine_busy; break :blk fail(c, cx, id, metadata.*, .capacity, "the engine is busy; retry shortly"); }, error.Closed => fail(c, cx, id, metadata.*, .other, "the scheduler is closed"), - error.InvalidRequest => fail(c, cx, id, metadata.*, .request, "the engine refused this speech request's prompt, frame limit or sampling"), + error.InvalidRequest => blk: { + srv.load.refused(.invalid_request); + break :blk fail(c, cx, id, metadata.*, .request, "the engine refused this speech request's prompt, frame limit or sampling"); + }, error.Unsupported => fail(c, cx, id, metadata.*, .request, "this model does not support speech synthesis"), }; }; diff --git a/zig/src/server/wait_reason_ledger_test.zig b/zig/src/server/wait_reason_ledger_test.zig new file mode 100644 index 00000000000..71557c4c492 --- /dev/null +++ b/zig/src/server/wait_reason_ledger_test.zig @@ -0,0 +1,70 @@ +//! The ledger's reasons in the scrape and /v1/load: a fixed label set, the shared names the client codes use. +const std = @import("std"); +const api = @import("engine_api"); +const wait = @import("wait_reason.zig"); +const load_metrics = @import("load_metrics.zig"); +const ledger = api.load_ledger; +const reasons = ledger.reasons; + +fn snapshot() ledger.Snapshot { + return .{ .instance = @splat('a'), .start_s = 1793200000, .parked = false, .lanes = 2, .http = @splat(0) }; +} + +/// The label values `family` carries in `body`, each line's value checked to be 0. +fn labels(body: []const u8, family: []const u8, out: *std.ArrayList([]const u8)) !void { + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |line| { + const head = "tensorfold:"; + if (!std.mem.startsWith(u8, line, head) or !std.mem.startsWith(u8, line[head.len..], family)) continue; + const rest = line[head.len + family.len ..]; + if (rest.len == 0 or rest[0] != '{') continue; // another family that starts with the same name + try std.testing.expect(std.mem.startsWith(u8, rest, "{reason=\"")); + const end = std.mem.indexOf(u8, rest, "\"} ").?; + try std.testing.expectEqualStrings("0", rest[end + 3 ..]); + try out.append(std.testing.allocator, rest["{reason=\"".len..end]); + } +} + +test "wait reason ledger: a fresh host's scrape shows every wait reason at 0 and no other label" { + var out: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer out.deinit(); + var s = snapshot(); + s.requests = .{}; // what a fresh host publishes: nothing queued + try load_metrics.render(&out.writer, s, .{ .model = "m" }); + var seen: std.ArrayList([]const u8) = .empty; + defer seen.deinit(std.testing.allocator); + try labels(out.written(), "requests_waiting_by_reason", &seen); + try std.testing.expectEqual(std.enums.values(reasons.Wait).len, seen.items.len); + for (std.enums.values(reasons.Wait), seen.items) |r, label| try std.testing.expectEqualStrings(@tagName(r), label); + seen.clearRetainingCapacity(); + try labels(out.written(), "request_refusals_total", &seen); + try std.testing.expectEqual(@as(usize, 4), seen.items.len); + seen.clearRetainingCapacity(); + try labels(out.written(), "request_failures_total", &seen); + try std.testing.expectEqual(std.enums.values(reasons.Failure).len, seen.items.len); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "tensorfold:restore_fallbacks_total 0\n") != null); +} + +test "wait reason ledger: the capacity codes are the internal reasons' and the refusal counter's names" { + const shared = [_][]const u8{ wait.engine_busy, wait.engine_unavailable, wait.memory_pressure }; + for (shared, [_]reasons.Wait{ .engine_busy, .engine_unavailable, .memory_pressure }) |code, r| try std.testing.expectEqualStrings(code, @tagName(r)); + for (shared, [_]reasons.Refusal{ .engine_busy, .engine_unavailable, .memory_pressure }) |code, r| try std.testing.expectEqualStrings(code, @tagName(r)); + for (wait.all) |w| try std.testing.expect(std.meta.stringToEnum(reasons.Wait, w.code) == null); // queues nothing +} + +test "wait reason ledger: /v1/load names each queued reason and each refusal" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var s = snapshot(); + s.refusals[@backingInt(reasons.Refusal.memory_pressure)] = 2; + s.requests = .{ .waiting = 3 }; + s.requests.?.waiting_by_reason[@backingInt(reasons.Wait.kv_pool)] = 2; + s.requests.?.waiting_by_reason[@backingInt(reasons.Wait.memory_floor)] = 1; + const body = try @import("json").stringify(a, try load_metrics.object(a, s, 1793200001.5, "m"), .{}); + const flat = try std.mem.replaceOwned(u8, a, body, " ", ""); + for ([_][]const u8{ "\"waiting\":3", "\"kv_pool\":2", "\"memory_floor\":1", "\"memory_pressure\":2", "\"invalid_request\":0", "\"waiting_by_reason\":{", "\"refusals\":{" }) |key| { + if (std.mem.indexOf(u8, flat, key) == null) std.debug.print("missing {s} in {s}\n", .{ key, flat }); + try std.testing.expect(std.mem.indexOf(u8, flat, key) != null); + } +} From c22dc9b3d5633a439f56df04ebf87848d13f9f60 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:04:31 +0000 Subject: [PATCH 42/59] lanes: count every refusal a client sees, one restore fallback a request, DeepSeek's mapping tested on the host (#2135) request_refusals_total gains the admission flags' 429s under the code each reply carries (max_inflight_exceeded, max_inflight_per_key_exceeded, admission_capacity_exceeded, requests_per_second_exceeded), counted once at the request gate, and an images engine's busy 503 as engine_busy. request_failures_total is now always shown, the server's count beside the host's: the chat routes' 500 for a stale device is engine_stale, and a family planner's refusal, a failed reply with its own words and no code, is planner_refused. A begin that reports its saved entry damaged and the pass that then reports the failed restore count one fallback: each request carries whether its fallback is counted. DeepSeek-V4.1's verdict mapping moves from sched_host.zig into sched_verdict.zig, which a new host step (test-dsv41-wait-reasons-host, in both nightly DeepSeek lists) drives through a real lane host round into the ledger. The docs say the stored reasons are as of the last admission attempt. Every reply's bytes are unchanged. --- docs/api.md | 18 +- zig/build/dsv41_draft.zig | 2 + zig/build/host_ci.zig | 2 + zig/src/core/lane_host_load.zig | 12 +- zig/src/core/lane_job.zig | 1 + zig/src/core/lane_rounds.zig | 7 +- zig/src/core/lane_wait_reason_test.zig | 101 +++++++++++ zig/src/core/load_ledger.zig | 18 +- zig/src/core/wait_reason.zig | 17 +- zig/src/families/deepseek_v41/sched_host.zig | 11 +- .../families/deepseek_v41/sched_verdict.zig | 20 +++ .../deepseek_v41/sched_verdict_test.zig | 163 ++++++++++++++++++ zig/src/server/chat.zig | 2 +- zig/src/server/images_generations.zig | 2 +- zig/src/server/images_generations_test.zig | 16 ++ zig/src/server/load_metrics.zig | 8 +- zig/src/server/load_metrics_test.zig | 3 +- zig/src/server/refusals.zig | 23 ++- .../server/request_admission_http_test.zig | 21 +++ zig/src/server/request_gate.zig | 1 + zig/src/server/wait_reason_ledger_test.zig | 77 ++++++++- 21 files changed, 491 insertions(+), 34 deletions(-) create mode 100644 zig/src/families/deepseek_v41/sched_verdict.zig create mode 100644 zig/src/families/deepseek_v41/sched_verdict_test.zig diff --git a/docs/api.md b/docs/api.md index 47592c9b820..e6a3caa6062 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1077,16 +1077,22 @@ publishes `server_info{model,backend,version,instance}` (always 1; `instance` is so counters restart only with a new `instance`), `process_start_time_seconds`, `engine_parked` (1 while `--idle-unload` has closed the engine), `lanes`, and `http_requests_active{route}`: model requests from the end of their headers to the end of their reply, by route group (`chat_completions`, `completions`, `responses`, -`messages`, `embeddings`, `speech`, `other`), and `request_refusals_total{reason}`: requests refused with a client +`messages`, `embeddings`, `speech`, `other`), `request_refusals_total{reason}`: requests refused with a client code, one of `engine_busy`, `engine_unavailable` and `memory_pressure` (the [Waits](#waits) codes, counted where -the chat, embeddings, rerank and speech routes answer with them) or `invalid_request` (the 400 when the engine -itself refuses the request it was handed), every label always present. +the chat, embeddings, rerank and speech routes answer with them, and an images engine's busy 503 as `engine_busy`), +`invalid_request` (the 400 when the engine itself refuses the request it was handed), or an admission flag's 429 by +its code (`max_inflight_exceeded`, `max_inflight_per_key_exceeded`, `admission_capacity_exceeded`, +`requests_per_second_exceeded`; see [Admission](#admission)), and `request_failures_total{reason}`: requests that +ended failed with no refusal code. Its reasons are `backend_prompt`, `backend_round`, `lane_memory_alone` and +`prompt_too_large` (the engine took the request and it failed), `planner_refused` (a family round planner refused it +with its own words, as DeepSeek-V4.1 does for a request past its KV pool or its hard memory floor) and +`engine_stale` (the chat routes' 500 while the device is stale). Every label of both families is always present. An engine on the shared lane host adds these groups, each complete or absent: | Group | Families | | --- | --- | -| Requests | `requests_waiting_by_reason{reason}` (queued requests by the one wait reason each holds, every reason always present; they sum to `requests_waiting`), `request_failures_total{reason}` (requests the engine took and ended failed: `backend_prompt`, `backend_round`, `lane_memory_alone`, `prompt_too_large`), `restore_fallbacks_total` (requests whose saved prefix could not be restored, so they prefilled from zero and were served), `waiting_prompt_tokens` (prompt tokens of queued requests, before any kept prefix restores part of them), `filling_prompt_tokens_left` (absent while a backend without fill progress fills), `requests_started_total`, `requests_requeued_total`, `background_yields_total` | +| Requests | `requests_waiting_by_reason{reason}` (queued requests by the one wait reason each holds, every reason always present; they sum to `requests_waiting`), `restore_fallbacks_total` (requests whose saved prefix could not be restored, so they prefilled from zero and were served; once a request), `waiting_prompt_tokens` (prompt tokens of queued requests, before any kept prefix restores part of them), `filling_prompt_tokens_left` (absent while a backend without fill progress fills), `requests_started_total`, `requests_requeued_total`, `background_yields_total` | | Work | `scheduler_tokens_total{mode}` with `prefill_compute`, `prefill_cache` and `decode` (output tokens after each request's first), counted as the work happens, and `prefill_busy_seconds_total`: engine seconds in prompt calls whose work `prefill_compute` counted. The `prefill_compute` delta over its delta is the prefill rate. A family round planner publishes no work group | | Capacity | `kv_capacity_mode{mode}` (`window` or `paged`), `lanes_free`, and for a paged engine `kv_pool_capacity_tokens`, `kv_pool_available_tokens`, `kv_pool_reclaimable_tokens`, `kv_pool_promised_tokens` with `pool="main"`, and `kv_pool_run_available` where the family needs a contiguous run. Published by the CUDA lane host: `window` for an engine without a page plan, `paged` with GLM-5.3-Flash's pool on rank 0; other paged families leave the group out until they name their pool | @@ -1105,7 +1111,9 @@ already running). The rest are internal reasons, never a client code: `kv_pool`, over while others prefill; DeepSeek-V4.1 names them), `prefix_cut` (it waits for a cut another prompt is filling), `state_read` (it waits for its disk state's read ahead), `ledger_bytes` (its caches' bytes do not fit the KV ledger now) and `pool_room` (the family's pool has no room for it now). A request behind one that waits for the pool, the -ledger or the planner holds that request's reason. `memory_floor` is never counted under `memory_pressure`. +ledger or the planner holds that request's reason. `memory_floor` is never counted under `memory_pressure`. The +reasons are as of the engine's last admission attempt: a request queued behind one just admitted keeps its earlier +reason until the engine next tries to admit it. `GET /v1/load` returns the same ledger as one JSON object from one read: `instance`, `timestamp` (the read's wall time), `model`, `parked`, `lanes`, `http_active` by route group, `refusals` by code, and, when present, the request diff --git a/zig/build/dsv41_draft.zig b/zig/build/dsv41_draft.zig index 8fb3acdd52f..17a6189d52e 100644 --- a/zig/build/dsv41_draft.zig +++ b/zig/build/dsv41_draft.zig @@ -19,6 +19,8 @@ pub fn steps(b: *std.Build) void { const source = @import("dsv41_cuda.zig").module(b, b.graph.host, "serve_engine.zig", false); b.step("test-dsv41-serve-host", "Tokenizer, encoder goldens and serving contracts without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = source.import_table.get("dsv41_serve").? })).step); b.step("test-draft-dsv41-host", "DeepSeek draft source metadata without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = source, .filters = &.{"draft sources:"} })).step); + const verdicts = @import("dsv41_cuda.zig").module(b, b.graph.host, "sched_verdict_test.zig", false); + b.step("test-dsv41-wait-reasons-host", "DeepSeek planner verdicts reach the load ledger as their wait reasons, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = verdicts })).step); inline for (.{ false, true }) |cross| { const target = if (cross) b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .gnu }) else b.graph.host; const root = @import("dsv41_cuda.zig").module(b, target, "device_host_test.zig", cross); diff --git a/zig/build/host_ci.zig b/zig/build/host_ci.zig index 2d18639788e..8dd5a37a2e2 100644 --- a/zig/build/host_ci.zig +++ b/zig/build/host_ci.zig @@ -69,6 +69,7 @@ const linux_compile = [_][]const u8{ const linux_deepseek = [_][]const u8{ "test-dsv41-device-host", "test-dsv41-forward", + "test-dsv41-wait-reasons-host", "test-sessions-writes-host", }; @@ -298,6 +299,7 @@ const macos_deepseek = [_][]const u8{ "test-dsv41-device-host", "test-dsv41-draft", "test-dsv41-forward", + "test-dsv41-wait-reasons-host", "test-sessions-writes-host", }; diff --git a/zig/src/core/lane_host_load.zig b/zig/src/core/lane_host_load.zig index 547b95a011b..4f6c725b092 100644 --- a/zig/src/core/lane_host_load.zig +++ b/zig/src/core/lane_host_load.zig @@ -118,7 +118,7 @@ pub fn progress(h: *LaneHost, job: *Job) void { /// The pass reported: its remaining computed tokens, its restored ones and its time; the caller holds the host mutex. pub fn credit(h: *LaneHost, job: *Job) void { - h.load.restore_fallbacks += @intFromBool(job.stream.reuse_failed); // once a job: its pass reports once + if (job.stream.reuse_failed) fallback(h, job); const p = &job.load; if (!p.on) return; take(h, p); @@ -198,10 +198,16 @@ pub fn failed(h: *LaneHost, why: Failure) void { } /// A saved prefix could not be restored: the request prefills from zero and is still served (no host mutex held). -pub fn fellBack(h: *LaneHost) void { +pub fn fellBack(h: *LaneHost, job: *Job) void { h.lock(); defer h.unlock(); - h.load.restore_fallbacks += 1; + fallback(h, job); +} + +/// One restore fallback a request, under the host mutex: a damaged begin and its pass's `reuse_failed` count once. +fn fallback(h: *LaneHost, job: *Job) void { + h.load.restore_fallbacks += @intFromBool(!job.fell_back); + job.fell_back = true; } /// A background pass gave its lane up to foreground work. diff --git a/zig/src/core/lane_job.zig b/zig/src/core/lane_job.zig index 3ab668ee65e..3a5654a2e8c 100644 --- a/zig/src/core/lane_job.zig +++ b/zig/src/core/lane_job.zig @@ -45,6 +45,7 @@ pub const Job = struct { fetch: @import("lane_host_fetch.zig").Ticket = .{}, // its disk state read ahead, while queued lease: @import("kv_ledger.zig").Lease = .{}, // its caches' bytes in the host's ledger, from admission to its end wait_reason: @import("wait_reason.zig").Wait = .engine_busy, // while queued: the hold its last admission try met + fell_back: bool = false, // its saved prefix's restore fallback is counted (once a request) /// Record first admission once (a family planner's too, a yielding background pass's kept) and clear its wait. pub fn noteAdmission(job: *Job) void { diff --git a/zig/src/core/lane_rounds.zig b/zig/src/core/lane_rounds.zig index 77254a95048..02dc8520a41 100644 --- a/zig/src/core/lane_rounds.zig +++ b/zig/src/core/lane_rounds.zig @@ -23,6 +23,10 @@ pub const Rounds = struct { pub fn step(h: *LaneHost) bool { return round(h, h.rounds.?); } + /// Ends every request a stepped host still holds (a family's test has no engine thread to stop). + pub fn close(h: *LaneHost) void { + ends.closeAll(h); + } } else struct {}; /// Why a request stays queued (wait_reason.zig): the planner names it with its `wait` or `skip`. @@ -98,6 +102,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { .refuse => { if (refused.append(h.gpa, .{ .job = job, .why = why })) |_| {} else |_| break; _ = h.queued.orderedRemove(i); + h.load.failures[@backingInt(load.Failure.planner_refused)] += 1; // its reply: a failure, no code }, } } @@ -123,7 +128,7 @@ fn round(h: *LaneHost, rd: Rounds) bool { _ = ends.dropFailed(h, job, e); continue; }; - if (b.damaged) load.fellBack(h); // its saved prefix was dropped: it prefills from 0 and is still served + if (b.damaged) load.fellBack(h, job); // its saved prefix was dropped: it prefills from 0 and is still served rd.vtable.began(rd.ctx, @intFromPtr(job), b.damaged); } // this round's pieces, a decode round of the streams decoding, then the prompts whose rows are in diff --git a/zig/src/core/lane_wait_reason_test.zig b/zig/src/core/lane_wait_reason_test.zig index c774110e300..26bb1c35954 100644 --- a/zig/src/core/lane_wait_reason_test.zig +++ b/zig/src/core/lane_wait_reason_test.zig @@ -214,3 +214,104 @@ test "wait reason ledger: publishing the ledger reads stored reasons and never a try std.testing.expectEqual(@as(u32, 0), calls); ends.closeAll(&rig.host); } + +/// A planner that admits every request and fills each prompt in one piece, its final in the same round. +const Whole = struct { + keys: [4]usize = undefined, + lens: [4]u64 = undefined, + n: usize = 0, + planned: usize = 0, + + fn self(ctx: *anyopaque) *Whole { + return @ptrCast(@alignCast(ctx)); + } + fn none(_: *anyopaque) void {} + fn admitFn(ctx: *anyopaque, ask: api.Rounds.Ask, _: *[]const u8) api.Rounds.Verdict { + const p = self(ctx); + p.keys[p.n] = ask.key; + p.lens[p.n] = ask.prompt.len; + p.n += 1; + return .admit; + } + fn admitted(_: *anyopaque) anyerror!void {} + fn key(_: *anyopaque, _: usize) void {} + fn began(_: *anyopaque, _: usize, _: bool) void {} + fn plan(ctx: *anyopaque, pieces: *std.ArrayList(api.Rounds.Piece), finals: *std.ArrayList(usize)) anyerror!void { + const p = self(ctx); + pieces.clearRetainingCapacity(); + finals.clearRetainingCapacity(); + while (p.planned < p.n) : (p.planned += 1) { + try pieces.append(std.testing.allocator, .{ .key = p.keys[p.planned], .start = 0, .end = p.lens[p.planned] - 1, .save = false }); + try finals.append(std.testing.allocator, p.keys[p.planned]); + } + } + fn after(_: *anyopaque, _: f64, _: f64) void {} + fn rounds(p: *Whole) api.Rounds { + return .{ .ctx = p, .vtable = &.{ .begin_admit = none, .admit = admitFn, .admitted = admitted, .arm = key, .began = began, .plan = plan, .left = key, .after = after } }; + } +}; + +/// The fake target's begin with its saved entry damaged and its restore failed: both ways a fallback shows. +const Damaged = struct { + var base: *const lanes.backend.Backend.VTable = undefined; + var vt: lanes.backend.Backend.VTable = undefined; + fn begin(ptr: *anyopaque, s: *lanes.Stream) anyerror!lanes.backend.Backend.Begun { + var b = try base.begin.?(ptr, s); + b.damaged = true; + s.reuse_failed = true; + return b; + } + fn install(core: *lanes.Engine) void { + base = core.backend.vtable; + vt = base.*; + vt.begin = begin; + core.backend.vtable = &vt; + } +}; + +test "wait reason ledger: a damaged begin whose pass also reports the failed restore is one fallback" { + var rig: Rig = undefined; + try rig.init(.{ .lanes = 2 }, true); + defer rig.deinit(); + Damaged.install(&rig.core); + var pl: Whole = .{}; + rig.host.rounds = pl.rounds(); + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const ra: Request = .{ .prompt = &second, .max_tokens = 4 }; + try rig.submit(1, &ra); + errdefer ends.closeAll(&rig.host); + _ = api.Rounds.Test.step(&rig.host); + const r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 1), r.running); // begun, filled and reported in the one round + try std.testing.expectEqual(@as(u64, 1), r.restore_fallbacks); + ends.closeAll(&rig.host); +} + +test "wait reason ledger: a planner's refusal counts as a planner_refused failure and leaves the queue" { + var rig: Rig = undefined; + try rig.init(.{ .lanes = 2 }, true); + defer rig.deinit(); + const Refuse = struct { + fn admit(_: *anyopaque, _: api.Rounds.Ask, words: *[]const u8) api.Rounds.Verdict { + words.* = "too large for this server"; + return .refuse; + } + }; + var pl: Plan = .{}; + rig.host.rounds = pl.rounds(); + var vt = rig.host.rounds.?.vtable.*; + vt.admit = Refuse.admit; + rig.host.rounds.?.vtable = &vt; + var ledger: Ledger = .init(std.testing.io); + ledger.attach(rig.host.engine()); + defer ledger.detach(false); + const ra: Request = .{ .prompt = &second, .max_tokens = 4 }; + try rig.submit(1, &ra); + errdefer ends.closeAll(&rig.host); + _ = api.Rounds.Test.step(&rig.host); + const r = ledger.read().requests.?; + try std.testing.expectEqual(@as(u32, 0), r.waiting); + try std.testing.expectEqual(@as(u64, 1), r.failures[@backingInt(api.load_ledger.reasons.Failure.planner_refused)]); +} diff --git a/zig/src/core/load_ledger.zig b/zig/src/core/load_ledger.zig index f115b6e401b..fda1bf1767b 100644 --- a/zig/src/core/load_ledger.zig +++ b/zig/src/core/load_ledger.zig @@ -81,6 +81,8 @@ pub const Snapshot = struct { http: [groups]u32, /// What clients were refused, by code: the server counts these, attached engine or not. refusals: [reasons.refusals]u64 = @splat(0), + /// Failures the server answered without the host (`engine_stale`); `failed` adds the host's. + failures: [reasons.failures]u64 = @splat(0), requests: ?Requests = null, work: ?Work = null, capacity: ?Capacity = null, @@ -89,6 +91,12 @@ pub const Snapshot = struct { pub fn active(s: Snapshot, g: RouteGroup) u32 { return s.http[@backingInt(g)]; } + + /// Requests that ended failed for `r`: the server's count and the attached host's. + pub fn failed(s: Snapshot, r: reasons.Failure) u64 { + const host: u64 = if (s.requests) |q| q.failures[@backingInt(r)] else 0; + return s.failures[@backingInt(r)] + host; + } }; const Groups = struct { requests: ?Requests = null, work: ?Work = null, capacity: ?Capacity = null, pool: ?Pool = null }; @@ -104,6 +112,7 @@ pub const Ledger = struct { lanes: u32 = 0, http: [groups]u32 = @splat(0), refusals: [reasons.refusals]u64 = @splat(0), + failures: [reasons.failures]u64 = @splat(0), /// Raised by every attach and detach: a handle from before it writes nothing. epoch: u64 = 0, attached: ?api.Engine = null, @@ -184,11 +193,18 @@ pub const Ledger = struct { l.refusals[@backingInt(r)] += 1; } + /// A request ended failed for `r` before the host took it (the server's own count). + pub fn failed(l: *Ledger, r: reasons.Failure) void { + l.mutex.lockUncancelable(l.io); + defer l.mutex.unlock(l.io); + l.failures[@backingInt(r)] += 1; + } + /// The ledger at one instant; counters carry every earlier host's. pub fn read(l: *Ledger) Snapshot { l.mutex.lockUncancelable(l.io); defer l.mutex.unlock(l.io); - var s: Snapshot = .{ .instance = l.instance, .start_s = l.start_s, .parked = l.parked, .lanes = l.lanes, .http = l.http, .refusals = l.refusals }; + var s: Snapshot = .{ .instance = l.instance, .start_s = l.start_s, .parked = l.parked, .lanes = l.lanes, .http = l.http, .refusals = l.refusals, .failures = l.failures }; if (l.cur.requests) |r| { std.debug.assert(r.waitingTotal() == r.waiting); // one stored reason a queued request s.requests = addRequests(r, l.base.requests.?); diff --git a/zig/src/core/wait_reason.zig b/zig/src/core/wait_reason.zig index febc5daa224..5345b2eb6fd 100644 --- a/zig/src/core/wait_reason.zig +++ b/zig/src/core/wait_reason.zig @@ -25,11 +25,20 @@ pub const Wait = enum { pool_room, }; -/// What a client sees as a refusal: the three capacity codes and the engine's 400 for a request it cannot take. -pub const Refusal = enum { engine_busy, engine_unavailable, memory_pressure, invalid_request }; +/// A refusal by the code its client sees: the capacity codes, the engine's 400, the admission flags' 429s. +pub const Refusal = enum { + engine_busy, + engine_unavailable, + memory_pressure, + invalid_request, + max_inflight_exceeded, + max_inflight_per_key_exceeded, + admission_capacity_exceeded, + requests_per_second_exceeded, +}; -/// A request the host took and then ended failed, with its own words: not a refusal a client can retry by code. -pub const Failure = enum { backend_prompt, backend_round, lane_memory_alone, prompt_too_large }; +/// Ended failed with its own words, no refusal code: the host's four, its planner's refusal, a stale device at submit. +pub const Failure = enum { backend_prompt, backend_round, lane_memory_alone, prompt_too_large, planner_refused, engine_stale }; pub const waits = std.enums.values(Wait).len; pub const refusals = std.enums.values(Refusal).len; diff --git a/zig/src/families/deepseek_v41/sched_host.zig b/zig/src/families/deepseek_v41/sched_host.zig index 0f66775857f..ba37457e927 100644 --- a/zig/src/families/deepseek_v41/sched_host.zig +++ b/zig/src/families/deepseek_v41/sched_host.zig @@ -101,16 +101,7 @@ pub const SchedHost = struct { }; return .admit; }, - // the planner's own counters say which hold it met: the KV pool's pages or the memory floor - .wait => return .{ .wait = if (h.p.counts.pool_waits > before.pool_waits) .kv_pool else .memory_floor }, - .skip => return .{ .skip = .prefill_concurrent }, // its one skip: a long prompt past the concurrent bound - .refuse => |r| { - words.* = switch (r) { - .too_large => "the request needs more KV pool pages than the pool has", - .memory => "the prompt's prefill cannot fit in this server's memory now (TF_DSV41_FLOOR_HARD_GIB)", - }; - return .refuse; - }, + .wait, .skip, .refuse => return @import("sched_verdict.zig").held(v, before, h.p.counts, words), } } diff --git a/zig/src/families/deepseek_v41/sched_verdict.zig b/zig/src/families/deepseek_v41/sched_verdict.zig new file mode 100644 index 00000000000..c1772155037 --- /dev/null +++ b/zig/src/families/deepseek_v41/sched_verdict.zig @@ -0,0 +1,20 @@ +//! The planner's verdict as the lane host's (sched_host.zig): which hold a wait met, its one skip, a refusal's words. +const api = @import("engine_api"); +const sched = @import("kv").sched; + +/// The lane host's verdict for one the planner did not admit; `before` and `after`: its counts around the call. +pub fn held(v: sched.Verdict, before: sched.Counts, after: sched.Counts, words: *[]const u8) api.Rounds.Verdict { + return switch (v) { + .admit => .admit, // sched_host records the admission first + // the planner's own counters say which hold it met: the KV pool's pages or the memory floor + .wait => .{ .wait = if (after.pool_waits > before.pool_waits) .kv_pool else .memory_floor }, + .skip => .{ .skip = .prefill_concurrent }, // its one skip: a long prompt past the concurrent bound + .refuse => |r| blk: { + words.* = switch (r) { + .too_large => "the request needs more KV pool pages than the pool has", + .memory => "the prompt's prefill cannot fit in this server's memory now (TF_DSV41_FLOOR_HARD_GIB)", + }; + break :blk .refuse; + }, + }; +} diff --git a/zig/src/families/deepseek_v41/sched_verdict_test.zig b/zig/src/families/deepseek_v41/sched_verdict_test.zig new file mode 100644 index 00000000000..b5911a54127 --- /dev/null +++ b/zig/src/families/deepseek_v41/sched_verdict_test.zig @@ -0,0 +1,163 @@ +//! DeepSeek-V4.1's planner verdicts through sched_verdict.zig and a real lane host round into the load ledger. +const std = @import("std"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const sched = @import("kv").sched; +const held = @import("sched_verdict.zig").held; +const Ledger = api.load_ledger.Ledger; +const Snapshot = api.load_ledger.Snapshot; +const Request = api.Request; +const t = std.testing; +const gpa = t.allocator; + +/// The planner's side of `admit`, as kv/sched.zig answers: each verdict moves the counter the real planner moves. +const Planner = struct { + counts: sched.Counts = .{}, + /// What a request whose prompt starts with 2 waits for: the pool's pages or the memory floor. + floor: bool = false, + + fn self(ctx: *anyopaque) *Planner { + return @ptrCast(@alignCast(ctx)); + } + /// 1: a long prompt past the concurrent bound; 2: a hold; 3: more pages than the pool has. + fn verdict(p: *Planner, first: u32) sched.Verdict { + switch (first) { + 1 => { + p.counts.long_waits += 1; + return .skip; + }, + 2 => { + if (p.floor) p.counts.mem_waits += 1 else p.counts.pool_waits += 1; + return .wait; + }, + else => return .{ .refuse = .too_large }, + } + } + fn admit(ctx: *anyopaque, ask: api.Rounds.Ask, words: *[]const u8) api.Rounds.Verdict { + const p = self(ctx); + const before = p.counts; + const v = p.verdict(ask.prompt[0]); + return held(v, before, p.counts, words); + } + fn none(_: *anyopaque) void {} + fn admitted(_: *anyopaque) anyerror!void {} + fn key(_: *anyopaque, _: usize) void {} + fn began(_: *anyopaque, _: usize, _: bool) void {} + fn plan(_: *anyopaque, pieces: *std.ArrayList(api.Rounds.Piece), finals: *std.ArrayList(usize)) anyerror!void { + pieces.clearRetainingCapacity(); + finals.clearRetainingCapacity(); + } + fn after(_: *anyopaque, _: f64, _: f64) void {} + fn rounds(p: *Planner) api.Rounds { + return .{ .ctx = p, .vtable = &.{ .begin_admit = none, .admit = admit, .admitted = admitted, .arm = key, .began = began, .plan = plan, .left = key, .after = after } }; + } +}; + +/// One request's end, as its sink heard it. +const Box = struct { + reason: ?api.Reason = null, + message: [128]u8 = undefined, + len: usize = 0, + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + switch (e.*) { + .finished => |f| { + b.reason = f.reason; + b.len = @min(f.message.len, b.message.len); + @memcpy(b.message[0..b.len], f.message[0..b.len]); + }, + else => {}, + } + } +}; + +/// A lane host on the fake target whose rounds the test steps itself, with the ledger attached. +const Rig = struct { + cfg: lanes.Config, + target: lanes.fake.Fake, + clock: lanes.fake.FixedClock = .{}, + core: lanes.Engine, + host: api.LaneHost, + planner: Planner = .{}, + ledger: Ledger, + + fn init(r: *Rig) !void { + r.cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + r.target = .{ .gpa = gpa }; + r.clock = .{}; + r.core = lanes.Engine.init(gpa, &r.cfg, r.target.pieceBackend(), r.clock.clock()); + r.host = api.LaneHost.init(gpa, t.io, &r.core, .{ .lanes = 2 }); + r.planner = .{}; + r.host.rounds = r.planner.rounds(); + r.ledger = .init(t.io); + r.ledger.attach(r.host.engine()); + } + + fn deinit(r: *Rig) void { + api.Rounds.Test.close(&r.host); + r.ledger.detach(false); + r.host.stop(); + r.core.deinit(); + r.target.deinit(); + r.cfg.deinit(gpa); + } + + fn submit(r: *Rig, id: api.Id, request: *const Request, box: *Box) !void { + try r.host.engine().submit(id, request, .{ .ctx = box, .event = Box.event }); + } + + fn read(r: *Rig) Snapshot { + return r.ledger.read(); + } +}; + +fn waiting(s: Snapshot, w: api.Rounds.Wait) u32 { + return s.requests.?.waiting_by_reason[@backingInt(w)]; +} + +const long = [_]u32{ 1, 5, 9, 2 }; +const pages = [_]u32{ 2, 6, 5, 3 }; +const huge = [_]u32{ 3, 5, 8, 9 }; + +test "wait reason ledger: DeepSeek's long-prompt skip, KV pool wait and memory floor wait reach the ledger as theirs" { + var r: Rig = undefined; + try r.init(); + defer r.deinit(); + var boxes: [2]Box = .{ .{}, .{} }; + const a: Request = .{ .prompt = &long, .max_tokens = 4 }; + const b: Request = .{ .prompt = &pages, .max_tokens = 4 }; + try r.submit(1, &a, &boxes[0]); + try r.submit(2, &b, &boxes[1]); + _ = api.Rounds.Test.step(&r.host); + var s = r.read(); + try t.expectEqual(@as(u32, 2), s.requests.?.waiting); + try t.expectEqual(@as(u32, 1), waiting(s, .prefill_concurrent)); + try t.expectEqual(@as(u32, 1), waiting(s, .kv_pool)); + try t.expectEqual(@as(u32, 0), waiting(s, .memory_floor)); + try t.expectEqual(@as(u32, 0), waiting(s, .engine_busy)); + r.planner.floor = true; // the same request now waits for the memory floor, not the pool + _ = api.Rounds.Test.step(&r.host); + s = r.read(); + try t.expectEqual(@as(u32, 1), waiting(s, .memory_floor)); + try t.expectEqual(@as(u32, 0), waiting(s, .memory_pressure)); // the floor is never pressure + try t.expectEqual(@as(u32, 0), waiting(s, .kv_pool)); + try t.expectEqual(@as(u32, 1), waiting(s, .prefill_concurrent)); + try t.expectEqual(@as(u64, 0), s.failed(.planner_refused)); +} + +test "wait reason ledger: DeepSeek's refusal ends the request with its words and counts as planner_refused" { + var r: Rig = undefined; + try r.init(); + defer r.deinit(); + var box: Box = .{}; + const c: Request = .{ .prompt = &huge, .max_tokens = 4 }; + try r.submit(1, &c, &box); + try t.expectEqual(@as(u64, 0), r.read().failed(.planner_refused)); + _ = api.Rounds.Test.step(&r.host); + try t.expectEqual(@as(?api.Reason, .failed), box.reason); + try t.expectEqualStrings("the request needs more KV pool pages than the pool has", box.message[0..box.len]); + const s = r.read(); + try t.expectEqual(@as(u64, 1), s.failed(.planner_refused)); + try t.expectEqual(@as(u32, 0), s.requests.?.waiting); +} diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index f787cf581f2..1c0076d1845 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -267,7 +267,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an error.Closed => refusals.count(srv, .engine_unavailable, cx.wait(wait.engine_unavailable, "the engine is unavailable; retry after it restarts", .{})), error.InvalidSpans => refusals.count(srv, .invalid_request, cx.fail(.request, "the prompt span layout is invalid", .{})), error.InvalidRequest => refusals.count(srv, .invalid_request, cx.fail(.request, "the request does not match the loaded model", .{})), - error.Stale => cx.fail(.server, "{s}", .{api.stale_message}), + error.Stale => refusals.failure(srv, .engine_stale, cx.fail(.server, "{s}", .{api.stale_message})), error.MemoryPressure => refusals.count(srv, .memory_pressure, cx.wait(wait.memory_pressure, "{s}", .{api.pressure_message})), }; srv.release(preparing, null); // a background request waits only while a foreground one prepares diff --git a/zig/src/server/images_generations.zig b/zig/src/server/images_generations.zig index 318176a4037..b60112d2293 100644 --- a/zig/src/server/images_generations.zig +++ b/zig/src/server/images_generations.zig @@ -194,7 +194,7 @@ fn generate(srv: *Server, c: *Conn, cx: *Cx, plan: Plan, result: *api.ImageResul if (srv.keepalive) |k| k.begin(); defer if (srv.keepalive) |k| k.end(); srv.engine.submitImage(engine_id, &request, .{ .ctx = &box, .event = Mailbox.onEvent }) catch |e| return switch (e) { - error.Busy => cx.fail(.capacity, "the engine is busy; retry shortly", .{}), + error.Busy => @import("refusals.zig").count(srv, .engine_busy, cx.fail(.capacity, "the engine is busy; retry shortly", .{})), error.Closed => cx.fail(.capacity, "the scheduler is closed", .{}), error.InvalidRequest => cx.fail(.request, "the engine refused this image request's prompt, size or steps", .{}), error.Unsupported => cx.fail(.capacity, "this model does not serve images", .{}), diff --git a/zig/src/server/images_generations_test.zig b/zig/src/server/images_generations_test.zig index e20d42e2ba4..5ac26968c7c 100644 --- a/zig/src/server/images_generations_test.zig +++ b/zig/src/server/images_generations_test.zig @@ -457,6 +457,22 @@ test "error.Busy from the engine is a 503 with Retry-After" { try t.expect(std.mem.indexOf(u8, reply.body, "the engine is busy") != null); } +test "wait reason ledger: an images engine's Busy counts as an engine_busy refusal beside the same 503" { + var stub: Stub = .{ .inline_ = true, .submit_error = error.Busy }; + var s: Served = undefined; + try s.open(&stub, images_route, "{\"model\":\"m\",\"prompt\":\"hi\"}"); + defer s.deinit(); + const head = try s.readHead(); + try t.expect(std.mem.indexOf(u8, head, " 503 ") != null); + try t.expect(std.mem.indexOf(u8, try s.readRest(), "the engine is busy") != null); + s.join(&stub); + const counted = s.srv.load.read().refusals; + try t.expectEqual(@as(u64, 1), counted[@backingInt(api.load_ledger.reasons.Refusal.engine_busy)]); + var total: u64 = 0; + for (counted) |n| total += n; + try t.expectEqual(@as(u64, 1), total); +} + test "error.InvalidRequest from the engine is a 400 naming the refusal" { var stub: Stub = .{ .inline_ = true, .submit_error = error.InvalidRequest }; const reply = try ask(&stub, images_route, "{\"model\":\"m\",\"prompt\":\"hi\"}"); diff --git a/zig/src/server/load_metrics.zig b/zig/src/server/load_metrics.zig index f7a8121d58e..b37f610138a 100644 --- a/zig/src/server/load_metrics.zig +++ b/zig/src/server/load_metrics.zig @@ -28,16 +28,16 @@ pub fn render(w: *std.Io.Writer, s: ledger.Snapshot, id: Identity) !void { try family(w, "http_requests_active", "gauge", "Model requests from the end of their headers to the end of their reply, by route group."); for (std.enums.values(ledger.RouteGroup)) |g| try w.print("{s}http_requests_active{{route=\"{s}\"}} {d}\n", .{ prefix, @tagName(g), s.active(g) }); - try family(w, "request_refusals_total", "counter", "Requests refused with a client code: the three capacity codes and the engine's invalid_request."); + try family(w, "request_refusals_total", "counter", "Requests refused with a client code: capacity, the engine's invalid_request, admission."); for (std.enums.values(reasons.Refusal)) |x| try w.print("{s}request_refusals_total{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), s.refusals[@backingInt(x)] }); + try family(w, "request_failures_total", "counter", "Requests that ended failed with no refusal code, by fixed reason."); + for (std.enums.values(reasons.Failure)) |x| + try w.print("{s}request_failures_total{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), s.failed(x) }); if (s.requests) |r| { try family(w, "requests_waiting_by_reason", "gauge", "Queued requests by the one wait reason each holds; they sum to requests_waiting."); for (std.enums.values(reasons.Wait)) |x| try w.print("{s}requests_waiting_by_reason{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), r.waiting_by_reason[@backingInt(x)] }); - try family(w, "request_failures_total", "counter", "Requests the engine took and then ended failed, by fixed reason."); - for (std.enums.values(reasons.Failure)) |x| - try w.print("{s}request_failures_total{{reason=\"{s}\"}} {d}\n", .{ prefix, @tagName(x), r.failures[@backingInt(x)] }); try gauge(w, "restore_fallbacks_total", "counter", "Requests whose saved prefix could not be restored: they prefilled from zero and were served.", r.restore_fallbacks); try gauge(w, "waiting_prompt_tokens", "gauge", "Prompt tokens of the queued requests, before any kept prefix restores part of them.", r.waiting_prompt_tokens); if (r.filling_left) |left| try gauge(w, "filling_prompt_tokens_left", "gauge", "Prompt tokens still to prefill in the foreground passes filling now.", left); diff --git a/zig/src/server/load_metrics_test.zig b/zig/src/server/load_metrics_test.zig index aac7832e8e2..f0f9b2fd432 100644 --- a/zig/src/server/load_metrics_test.zig +++ b/zig/src/server/load_metrics_test.zig @@ -136,5 +136,6 @@ test "the /v1/load object carries every group a host fills, and only server valu } const parked = try loadBody(a, snapshot(true)); try std.testing.expect(has(parked, "\"parked\":true") and has(parked, "\"http_active\"")); - for ([_][]const u8{ "running", "tokens", "capacity", "busy_us", "fill_unknown" }) |key| try std.testing.expect(!has(parked, key)); + // as keys: a refusal label such as admission_capacity_exceeded is a server value, shown while parked too + for ([_][]const u8{ "\"running\":", "\"tokens\":", "\"capacity\":", "\"busy_us\":", "\"fill_unknown\":" }) |key| try std.testing.expect(!has(parked, key)); } diff --git a/zig/src/server/refusals.zig b/zig/src/server/refusals.zig index 16f19e57eb5..aa48a2d7292 100644 --- a/zig/src/server/refusals.zig +++ b/zig/src/server/refusals.zig @@ -1,9 +1,28 @@ -//! A client refusal counted by its code in the load ledger, beside the reply that names it. +//! A client refusal or failure counted by its reason in the load ledger, beside the reply that names it. +const std = @import("std"); const api = @import("engine_api"); +const admission = @import("request_admission.zig"); const Refused = @import("errors.zig").Refused; +const reasons = api.load_ledger.reasons; /// Counts `r` in the server's ledger and hands `err` back unchanged: the reply is the one the caller built. -pub fn count(srv: anytype, r: api.load_ledger.reasons.Refusal, err: Refused) Refused { +pub fn count(srv: anytype, r: reasons.Refusal, err: Refused) Refused { srv.load.refused(r); return err; } + +/// Counts a failure the server answered itself (no refusal code) and hands `err` back unchanged. +pub fn failure(srv: anytype, r: reasons.Failure, err: Refused) Refused { + srv.load.failed(r); + return err; +} + +/// An admission flag's 429, counted under the code its reply carries. +pub fn admitted(srv: anytype, reason: admission.Reason) void { + srv.load.refused(codeOf(reason)); +} + +/// The refusal named by the 429's code: the ledger's labels are the admission codes themselves. +pub fn codeOf(reason: admission.Reason) reasons.Refusal { + return std.meta.stringToEnum(reasons.Refusal, admission.code(reason)) orelse unreachable; +} diff --git a/zig/src/server/request_admission_http_test.zig b/zig/src/server/request_admission_http_test.zig index 15a8bbefef0..50ec053fdfd 100644 --- a/zig/src/server/request_admission_http_test.zig +++ b/zig/src/server/request_admission_http_test.zig @@ -184,6 +184,27 @@ test "admission HTTP: every model route refuses before its body and engine work; try t.expectEqual(@as(u32, 0), h.srv.generating.load(.acquire)); } +test "wait reason ledger: an admission 429 counts as a refusal under the code its reply carries" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var engine: Engine = .{}; + var h: Harness = .{}; + try h.start(&engine, null, .{ .max_inflight = 1 }); + defer h.deinit(); + var lease = h.srv.admission.acquire(t.io, .{ .max_inflight = 1 }, null).accepted; + defer lease.release(); + const reasons = api.load_ledger.reasons; + for (0..2) |_| { + const reply = try h.request(a, try requestText(a, "/v1/completions", "", completion)); + try expectStatus(reply, "HTTP/1.1 429 Too Many Requests\r\n"); + try t.expect(contains(reply, "\"code\": \"max_inflight_exceeded\"")); + } + const refusals = h.srv.load.read().refusals; + for (std.enums.values(reasons.Refusal)) |r| + try t.expectEqual(@as(u64, if (r == .max_inflight_exceeded) 2 else 0), refusals[@backingInt(r)]); +} + test "admission HTTP: verified keys get their own reservations and a parse error releases one" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); diff --git a/zig/src/server/request_gate.zig b/zig/src/server/request_gate.zig index 591e1ba771f..c40319e2031 100644 --- a/zig/src/server/request_gate.zig +++ b/zig/src/server/request_gate.zig @@ -70,6 +70,7 @@ pub fn enter(srv: *Server, a: Allocator, key_digest: ?[32]u8, group: RouteGroup, if (srv.config.admission.enabled()) switch (srv.admission.acquire(srv.io, srv.config.admission, key_digest)) { .accepted => |lease| e.held.lease = lease, .rejected => |refusal| { + @import("refusals.zig").admitted(srv, refusal.reason); // its 429 carries the code the ledger counts e.refusal = .{ .overloaded = refusal }; return e; }, diff --git a/zig/src/server/wait_reason_ledger_test.zig b/zig/src/server/wait_reason_ledger_test.zig index 71557c4c492..f302b17f9a9 100644 --- a/zig/src/server/wait_reason_ledger_test.zig +++ b/zig/src/server/wait_reason_ledger_test.zig @@ -38,7 +38,8 @@ test "wait reason ledger: a fresh host's scrape shows every wait reason at 0 and for (std.enums.values(reasons.Wait), seen.items) |r, label| try std.testing.expectEqualStrings(@tagName(r), label); seen.clearRetainingCapacity(); try labels(out.written(), "request_refusals_total", &seen); - try std.testing.expectEqual(@as(usize, 4), seen.items.len); + try std.testing.expectEqual(std.enums.values(reasons.Refusal).len, seen.items.len); + for (std.enums.values(reasons.Refusal), seen.items) |r, label| try std.testing.expectEqualStrings(@tagName(r), label); seen.clearRetainingCapacity(); try labels(out.written(), "request_failures_total", &seen); try std.testing.expectEqual(std.enums.values(reasons.Failure).len, seen.items.len); @@ -68,3 +69,77 @@ test "wait reason ledger: /v1/load names each queued reason and each refusal" { try std.testing.expect(std.mem.indexOf(u8, flat, key) != null); } } + +test "wait reason ledger: each admission flag's 429 code is a refusal label of the same name" { + const admission = @import("request_admission.zig"); + for (std.enums.values(admission.Reason)) |r| + try std.testing.expectEqualStrings(admission.code(r), @tagName(@import("refusals.zig").codeOf(r))); +} + +/// An engine whose every submit is refused with `err`; `Server.init` reads only `info`. +const Refusing = struct { + err: api.SubmitError, + fn engine(r: *Refusing) api.Engine { + return .{ .ctx = r, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; + } + fn info(_: *anyopaque) api.Info { + return .{ .context_window = 4096 }; + } + fn submit(ctx: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + const r: *Refusing = @ptrCast(@alignCast(ctx)); + return r.err; + } + fn cancel(_: *anyopaque, _: api.Id) void {} + fn status(_: *anyopaque, out: *api.Status, _: []u32) void { + out.* = .{}; + } + fn memory(_: *anyopaque, _: bool) ?api.Memory { + return null; + } +}; + +/// The route's answer, captured instead of sent to a socket. +const Wire = struct { + a: std.mem.Allocator, + bytes: std.ArrayList(u8) = .empty, + fn write(ctx: *anyopaque, bytes: []const u8) error{Closed}!void { + const w: *@This() = @ptrCast(@alignCast(ctx)); + w.bytes.appendSlice(w.a, bytes) catch return error.Closed; + } +}; + +test "wait reason ledger: a stale device's 500 counts as an engine_stale failure, not a refusal" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var refusing: Refusing = .{ .err = error.Stale }; + const srv = try @import("server.zig").Server.init(a, std.testing.io, refusing.engine(), @import("embedding_protocol_test.zig").ByteText.model(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .enable_thinking = false, + .use_drafts = false, + }, null); + defer srv.deinit(); + const http = @import("http_conn.zig"); + var conn = try http.Conn.init(a, -1, "fixture"); + defer conn.deinit(); + var wire: Wire = .{ .a = a }; + conn.write_hooks = .{ .ctx = &wire, .write = Wire.write }; + conn.method = "POST"; + conn.path = "/v1/completions"; + conn.version = "HTTP/1.1"; + conn.close = false; + conn.quiet_log = true; + const body = "{\"model\":\"m\",\"prompt\":\"x\",\"max_tokens\":1}"; + var length: [8]u8 = undefined; + var headers = [_]http.Header{.{ .name = "Content-Length", .value = try std.fmt.bufPrint(&length, "{d}", .{body.len}) }}; + conn.headers = &headers; + @memcpy(conn.buf[0..body.len], body); + conn.end = body.len; + srv.dispatch(&conn, a); + try std.testing.expect(std.mem.startsWith(u8, wire.bytes.items, "HTTP/1.1 500")); + try std.testing.expect(std.mem.indexOf(u8, wire.bytes.items, api.stale_message) != null); + const s = srv.load.read(); + try std.testing.expectEqual(@as(u64, 1), s.failed(.engine_stale)); + for (s.refusals) |n| try std.testing.expectEqual(@as(u64, 0), n); +} From 0a3267f664f4c7cfaab34f813e3be8a5a32911fc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:11:31 +0000 Subject: [PATCH 43/59] changelog: #3014 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf915319006..32b0947d619 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Metrics: every queued request carries one wait reason decided on the admission path, and DeepSeek-V4.1 names its own (`kv_pool`, `memory_floor`, `prefill_concurrent`). `/metrics` gains `requests_waiting_by_reason`, `request_refusals_total` and `request_failures_total` by code and `restore_fallbacks_total`, and `/v1/load` gains `waiting_by_reason` and `refusals`; replies are unchanged (#3014, for #2135). Thanks to @devopsfortunato for the design. + - Tests: the Qwen3.8-27B reply-end keep test names its history, as the keep pin added on 10 Nov requires, and `test-qwen27-reply-cache-host` now runs it (#3012). - Lanes: shared rounds price a plain (undrafted) round apart from drafted rows, from trial rounds whose first is a dropped warm-up, and fit row costs from plain and drafted widths, so only how many drafts a round asks for changes; on gfx1151 with Qwen3.6-35B-A3B and MTP it is level with main with tokens unchanged, and opt-in `TF_SHARED_PRICE_LOG=1` prints each shared round's prices (#2687, refs #2605). From 58d6167692241790607ef383f43cdb4392b181a8 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:17:14 +0000 Subject: [PATCH 44/59] environment: Metal Qwen paging, slot resume and slide checks by name (#2370) TF_QWEN27_SLOT_RESUME, TF_QWEN27_METAL_KV_PAGES, TF_QWEN35_METAL_KV_PAGES, TF_SLIDE_FIT_REDUCE, TF_SLIDE_TAKE_OUT_CHECK and TF_SLIDE_TAP_CHECK get rows in platform/environment and are read through it, so a malformed value is refused by name instead of read as a default. Unset or blank keeps today's defaults: resume on, pages off, the ordered fit reduction, both checks off. The two check switches move from on-when-set to exact 0 or 1. The two KV-page switches and the tree reduction get profile rows (arithmetic until a token-hash run says otherwise), and the docs list the six in the strict table. Host tests: each switch's forms, blank as unset and named refusals, valid-form coverage for the new rows, and profile-line reporting. --- docs/environment.md | 11 +++-- docs/profiles.md | 3 ++ zig/src/core/profile.zig | 6 +++ zig/src/families/qwen27/kv_pages.zig | 5 +-- zig/src/families/qwen3_5/cuda_train_more.zig | 2 +- zig/src/living/pocket_read.zig | 2 +- zig/src/native/qwen27_lanes.zig | 2 +- zig/src/native/qwen27_served.zig | 4 +- zig/src/native/qwen27_slots.zig | 5 +-- zig/src/native/qwen35.zig | 7 ++-- zig/src/platform/environment.zig | 6 +++ zig/src/platform/environment_test.zig | 42 ++++++++++++++++++++ zig/src/server/profile_line.zig | 13 ++++++ zig/src/server/slide.zig | 2 +- 14 files changed, 91 insertions(+), 19 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index c497fb8312f..4e11fbe8e26 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -50,6 +50,9 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; `1` has the 4-bit expert kernels read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values with fewer weight bytes; default 0 | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | +| `TF_QWEN27_SLOT_RESUME` | Qwen3.8-27B on Metal: exactly `0` or `1`; `0` stops slot 0 resuming a later prompt; unset or blank keeps it on | +| `TF_QWEN27_METAL_KV_PAGES` | Qwen3.8-27B on Metal: exactly `0` or `1`; `1` puts keys and values in core-pool pages (refused on Macs with tensor units); unset or blank is `0` | +| `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | | `TF_DSV41_SMALL` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` reads the checkpoint's config at its own small shapes (the served smoke test's tiny model); default 0 | | `TF_DSV41_ASSETS` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the Engram token map; unset or blank reads it beside the checkpoint | @@ -61,6 +64,9 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `LFM3_FUSE` | Whole u32 fusion mask; default 7 | | `TF_SLIDE_POCKET_KEY` | Exactly `auto`, `reply`, `subject` or `both`; default `auto` | | `TF_SLIDE_FIT_GIB` | Whole native-size nonnegative GiB count; default 4 | +| `TF_SLIDE_FIT_REDUCE` | Exactly `ordered` or `tree`: a fit's lane sums in order (the default) or as halves, quarters and pairs | +| `TF_SLIDE_TAKE_OUT_CHECK` | Exactly `0` or `1`; `1` takes every kept lesson out again to check the facts before it come back; default off | +| `TF_SLIDE_TAP_CHECK` | Exactly `0` or `1`; `1` checks a pass's tapped rows against a fresh run's; default off | | `TF_SLIDE_POCKET_DUMP` | A directory path without control characters, used as given; each lesson's read rows are written there for offline study. Unset or blank writes none | | `TF_SLIDE_FORGET_FAIL` | Whole u32 fact index, zero off; only checked in a slide-test-hooks build | @@ -132,12 +138,11 @@ The two row counts and the two draft counts keep their existing clamps after par These settings retain their existing boolean policies rather than gaining new aliases or refusals: - `TF_GRAPH_CACHE`: exact `0` or case-insensitive `off` disables graphs; every other value leaves the family's settings unchanged. -- `TF_QWEN27_SLOT_RESUME`: exact `0` disables resume; every other value keeps it enabled. - Kolibri pages: exact `TENSORFOLD_KOLIBRI_KV_PAGES=0` disables requested pages; other text keeps the option unchanged. - Dory pages: unset or exact `TENSORFOLD_DORY_KV_PAGES=0` uses windows; every other present value selects pages. - `TF_SLIDE_EDIT`, `TF_SLIDE_PROBE` and `TF_SLIDE_ROUTED` select modes by presence, even empty or `0`; probe wins over edit. -- `TF_COOP_SPLIT` retains its first-character `0` disabling rule, `TF_NEMOTRON_TRACE` its first-character `1` trace rule, - and `TF_SLIDE_FIT_REDUCE` its exact `tree` reduction selection. These developer switches keep their existing semantics. +- `TF_COOP_SPLIT` retains its first-character `0` disabling rule and `TF_NEMOTRON_TRACE` its first-character `1` trace + rule. These developer switches keep their existing semantics. - GLM: `GLM_EHPROJ_NAX` retains its first-character `0` disabling rule, `TF_GLM_DFLASH2_PROF` enables by presence, even empty or `0`, and `TF_KV_POISON` (also read by Nemotron) is on only for exact `1`. - The existing tool-grammar, rows-sync, log-time, memory-pressure and XPU-MTP boolean policies are unchanged. diff --git a/docs/profiles.md b/docs/profiles.md index ea57c78c107..c1592713124 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -59,6 +59,9 @@ Coverage includes: - Spark2.5 on CUDA: `TENSORFOLD_SPARK25_KV_PAGES`, full caches in pool pages by default, where `0` keeps them linear. - Nemotron-H on Metal: `TF_NEMOTRON_METAL_KV_PAGES`, where exactly `1` puts keys and values in the core pool's pages. +- Qwen on Metal: `TF_QWEN27_METAL_KV_PAGES` (the 27B) and `TF_QWEN35_METAL_KV_PAGES`, where exactly `1` puts keys and + values in the core pool's pages; `arithmetic` until a main-against-branch token-hash run says otherwise. +- Qwen3.5 slide learning on CUDA: `TF_SLIDE_FIT_REDUCE=tree` (`arithmetic`), which sums a fit's lanes in another order. - DeepSeek V4.1 on CUDA: the settings below, with no stable fallback. `identical` records the existing switch's token-preserving design and linked evidence; it is not a claim that the diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 1bde145ac83..bb06fa5904e 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -31,6 +31,9 @@ pub const Switch = enum { TENSORFOLD_GEMMA4_KV_PAGES, TENSORFOLD_SPARK25_KV_PAGES, TF_NEMOTRON_METAL_KV_PAGES, + TF_QWEN27_METAL_KV_PAGES, + TF_QWEN35_METAL_KV_PAGES, + TF_SLIDE_FIT_REDUCE, slide_learn_mode, TF_DSV41_EXPERT_TOPP, TF_DSV41_NUCLEUS, @@ -165,6 +168,9 @@ pub const entries = [_]Entry{ .{ .id = .TENSORFOLD_GEMMA4_KV_PAGES, .families = &.{ "gemma4", "gemma4_unified" }, .class = .identical, .report_values = &.{"0"}, .effect = "Global caches lease pool pages by default; 0 keeps them linear", .evidence = "#1619" }, .{ .id = .TENSORFOLD_SPARK25_KV_PAGES, .families = &.{"spark2_5"}, .class = .identical, .report_values = &.{"0"}, .effect = "Full caches lease pool pages by default; 0 keeps them linear", .evidence = "#1653" }, .{ .id = .TF_NEMOTRON_METAL_KV_PAGES, .families = &.{"nemotron_h"}, .backend = "metal", .class = .identical, .syntax = .one, .effect = "Only exact 1 puts keys and values in the core pool's pages; unset, whole caches made at open", .evidence = "#1537" }, + .{ .id = .TF_QWEN27_METAL_KV_PAGES, .families = &.{"qwen3_5"}, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the 27B's keys and values in core-pool pages; refused on Macs with tensor units", .evidence = "#2370; class until a main-against-branch token-hash run on a Mac without tensor units" }, + .{ .id = .TF_QWEN35_METAL_KV_PAGES, .families = qwen, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the streams' keys and values in core-pool pages; unset, whole caches at load", .evidence = "#2370; class until a main-against-branch token-hash run" }, + .{ .id = .TF_SLIDE_FIT_REDUCE, .families = &.{"qwen3_5"}, .class = .arithmetic, .report_values = &.{"tree"}, .effect = "tree sums a fit's lanes as halves, quarters and pairs instead of in order, so a learned result can differ", .evidence = "#2370" }, .{ .id = .TF_DSV41_EXPERT_TOPP, .families = &.{"deepseek_v41"}, .class = .experimental, .syntax = .present, .effect = "Expert top-p routing mass", .evidence = "#2370" }, .{ .id = .TF_DSV41_NUCLEUS, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Nucleus candidate count", .evidence = "#2370" }, .{ .id = .TF_DSV41_CONTEXT, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Slot position limit", .evidence = "#2370" }, diff --git a/zig/src/families/qwen27/kv_pages.zig b/zig/src/families/qwen27/kv_pages.zig index 9d24e88b266..7bbf9bfc114 100644 --- a/zig/src/families/qwen27/kv_pages.zig +++ b/zig/src/families/qwen27/kv_pages.zig @@ -8,9 +8,8 @@ const kv_pool = @import("core").kv_pool; pub const kvp = @import("core").metal_kv_pages; /// TF_QWEN27_METAL_KV_PAGES=1: every slot's keys and values in pages of the core pool (off by default). -pub fn on() bool { - const v = std.c.getenv("TF_QWEN27_METAL_KV_PAGES") orelse return false; - return std.mem.eql(u8, std.mem.span(v), "1"); +pub fn on() !bool { + return @import("sys").environment.read(bool, "TF_QWEN27_METAL_KV_PAGES", false); } /// A page: each attention layer's keys [kv_heads][256][head_dim] then its values, 256 rows of every layer. diff --git a/zig/src/families/qwen3_5/cuda_train_more.zig b/zig/src/families/qwen3_5/cuda_train_more.zig index 174bc40df45..601c2d4175b 100644 --- a/zig/src/families/qwen3_5/cuda_train_more.zig +++ b/zig/src/families/qwen3_5/cuda_train_more.zig @@ -34,7 +34,7 @@ pub fn fitDevice(t: anytype, jobs: []const living.pocket_fit.DeviceFit) !void { const d = jobs[0].d; const m = jobs[0].kinds.len; for (jobs) |j| if (j.d != d or j.kinds.len != m or j.steps != jobs[0].steps or j.below != jobs[0].below or j.rows.len < m * j.slots * d) return error.BadFit; - const tree = if (@import("sys").c.getenv("TF_SLIDE_FIT_REDUCE")) |v| std.mem.eql(u8, std.mem.span(v), "tree") else false; + const tree = try @import("sys").environment.read(u32, "TF_SLIDE_FIT_REDUCE", 0) == 1; // its words: ordered, tree const gib = try @import("sys").environment.read(usize, "TF_SLIDE_FIT_GIB", 4); const per = m * d * 2; const L = @max(1, @min(jobs.len, (gib << 30) / per)); diff --git a/zig/src/living/pocket_read.zig b/zig/src/living/pocket_read.zig index 05750cdd527..14eba952dc4 100644 --- a/zig/src/living/pocket_read.zig +++ b/zig/src/living/pocket_read.zig @@ -131,7 +131,7 @@ fn tapOne(p: anytype, t: anytype, ex: Example, kind: Kind, which: u32) !void { defer p.gpa.free(got); // the rows a pass reads: all but the last token, which only a pass's target reads try t.tapRows(ex.ids[0 .. ex.ids.len - 1], ex.context, want.items, p.moe.items, got); - if (comptime @hasDecl(@TypeOf(t.*), "pass")) if (std.c.getenv("TF_SLIDE_TAP_CHECK") != null) tapCheck(p, t, ex, want.items, got); + if (comptime @hasDecl(@TypeOf(t.*), "pass")) if (try @import("sys").environment.read(bool, "TF_SLIDE_TAP_CHECK", false)) tapCheck(p, t, ex, want.items, got); var at: usize = 0; for (rows.items) |r| { while (want.items[at] != r.row) at += 1; diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index 394590a14fa..b94e4c22320 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -113,7 +113,7 @@ pub const Metal = struct { errdefer kept.deinit(); const b = try gpa.create(Metal); errdefer gpa.destroy(b); - b.* = .{ .gpa = gpa, .runner = runner, .draft = draft, .tensor_units = tensor_units, .window = window, .copies = copies, .nodes = @import("qwen27_window.zig").nodes(window, copies), .ops = ops, .picks = picks, .kept = kept, .draft_slots = try draftSlots(), .slot_resume = slots.slotResumeEnv() }; + b.* = .{ .gpa = gpa, .runner = runner, .draft = draft, .tensor_units = tensor_units, .window = window, .copies = copies, .nodes = @import("qwen27_window.zig").nodes(window, copies), .ops = ops, .picks = picks, .kept = kept, .draft_slots = try draftSlots(), .slot_resume = try slots.slotResumeEnv() }; b.pass_profile = platform.c.getenv("TF_Q27_PASS_PROFILE") != null; errdefer b.freeContexts(); if (draft) |d| { diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index b307e195c09..ecde8c3e499 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -314,7 +314,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q const policy = @import("qwen27_window.zig"); const units = model.device.tensorUnits(); // the paged kernels have run only before the M5: a Mac with tensor units refuses the flag until they run there - if (q.decode_round.pagesOn() and units) { + if (try q.decode_round.pagesOn() and units) { why.* = "TF_QWEN27_METAL_KV_PAGES=1 has run only on Macs without tensor units (M1 to M4) so far; unset it on this Mac"; return error.KvPagesUntested; } @@ -372,7 +372,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.vision = o.images; // closed with the host; a failed attach leaves it to the caller h.trace = null; // TF_QWEN27_METAL_KV_PAGES=1: every slot's rows in core-pool pages now (Fit charged each its whole window above) - h.runner = try if (q.decode_round.pagesOn()) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initReady(gpa, model, slots, capacity + window, 1); + h.runner = try if (try q.decode_round.pagesOn()) q.decode_round.Runner.initPaged(gpa, model, slots, capacity + window) else q.decode_round.Runner.initReady(gpa, model, slots, capacity + window, 1); errdefer h.runner.deinit(); if (profileEvery()) |every| { h.trace = .{ .queue = model.queue, .report_every = every }; // enabled once measure() has priced the windows diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index d82558d64da..78cb0c54a69 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -202,9 +202,8 @@ pub fn endFill(b: *Metal, s: *lanes.Stream) void { } /// Slot 0 resumes a later prompt from where its last stream left it unless TF_QWEN27_SLOT_RESUME=0 (read at start). -pub fn slotResumeEnv() bool { - const v = std.c.getenv("TF_QWEN27_SLOT_RESUME") orelse return true; - return !std.mem.eql(u8, std.mem.span(v), "0"); +pub fn slotResumeEnv() !bool { + return @import("sys").environment.read(bool, "TF_QWEN27_SLOT_RESUME", true); } /// Whether slot 0 resumes in place: on, and without --vision (an image prompt's rows go by its images, not its ids). diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index b2d41cbe11a..d896988e90c 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -43,9 +43,8 @@ const Host = struct { }; /// TF_QWEN35_METAL_KV_PAGES=1: the streams' keys and values in pages of the core KV pool. -fn pagesOn() bool { - const v = std.c.getenv("TF_QWEN35_METAL_KV_PAGES") orelse return false; - return std.mem.eql(u8, std.mem.span(v), "1"); +fn pagesOn() !bool { + return @import("sys").environment.read(bool, "TF_QWEN35_METAL_KV_PAGES", false); } /// The pool beside the model under the load limit: kv_pool's plan of the streams and pages, made now; why not, or null. @@ -96,7 +95,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.metal = try q.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .chunk = chunk, .streams = @max(o.lanes, 2) }); errdefer h.metal.deinit(); // TF_QWEN35_METAL_KV_PAGES: the page plan sets the streams; otherwise each stream's whole cache is admitted at load - const paged = pagesOn(); + const paged = try pagesOn(); const served: u32 = if (paged) o.lanes else try metal_admit.streams(a, "qwen3.5", q.state.cacheBytes(@intCast(window)), metal_admit.room(model.device), o, @intCast(window), problem) orelse { h.metal.deinit(); model.deinit(); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 42c365f1692..f3294f65ce8 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -65,6 +65,9 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's 4-bit expert kernels read scales and biases through a 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, + .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, + .{ .name = "TF_QWEN27_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the 27B's keys and values in core-pool pages; unset or blank is 0)" }, + .{ .name = "TF_QWEN35_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the streams' keys and values in core-pool pages; unset or blank is 0)" }, .{ .name = "TF_DSV41_SMALL", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 reads a DeepSeek-V4.1 Metal checkpoint's config at its own small shapes)" }, .{ .name = "TF_DSV41_ASSETS", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's Engram token map" }, .{ .name = "TF_DSV41_ENGRAM_DIR", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's packed Engram tables" }, @@ -75,6 +78,9 @@ pub const rules = [_]Rule{ .{ .name = "TF_SLIDE_POCKET_KEY", .scope = .slide, .kind = .word, .words = &.{ "auto", "reply", "subject", "both" }, .forms = "auto, reply, subject or both" }, .{ .name = "TF_SLIDE_FIT_GIB", .scope = .slide, .kind = .size, .forms = "a whole nonnegative native-size GiB count" }, .{ .name = "TF_SLIDE_POCKET_DUMP", .scope = .slide, .kind = .path, .forms = "a directory path without control characters, where each lesson's read rows are written" }, + .{ .name = "TF_SLIDE_FIT_REDUCE", .scope = .slide, .kind = .word, .words = &.{ "ordered", "tree" }, .forms = "ordered or tree (a fit's lane sums in order, the default, or as halves, quarters and pairs)" }, + .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .scope = .slide, .kind = .flag, .forms = "0 or 1 (1 takes every kept lesson out again to check the facts before it come back)" }, + .{ .name = "TF_SLIDE_TAP_CHECK", .scope = .slide, .kind = .flag, .forms = "0 or 1 (1 checks tapped rows against a fresh run's)" }, .{ .name = "TF_SLIDE_FORGET_FAIL", .scope = .hooks, .kind = .u32, .trim = " ", .forms = "a whole fact index from 0 to 4294967295 (0 disables the planted failure)" }, .{ .name = "TF_GLM_HOST_CACHE", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_VISION_HOST", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index f93b1bd8cf3..e5376374400 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -95,6 +95,12 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .raw = "1", .n = 1 }, .{ .name = "GLM_EHPROJ_NAX", .raw = "0", .n = 0 }, .{ .name = "GLM_EHPROJ_NAX", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "XPU_A8_BITS", .raw = "4", .n = 4 }, .{ .name = "XPU_A8_BITS", .raw = "8", .n = 8 }, .{ .name = "LFM3_FUSE", .raw = "7", .n = 7 }, @@ -103,6 +109,12 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_POCKET_KEY", .raw = "subject", .n = 2 }, .{ .name = "TF_SLIDE_POCKET_KEY", .raw = "both", .n = 3 }, .{ .name = "TF_SLIDE_FIT_GIB", .raw = "4", .n = 4 }, + .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "ordered", .n = 0 }, + .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "tree", .n = 1 }, + .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .raw = "0", .n = 0 }, + .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .raw = "1", .n = 1 }, + .{ .name = "TF_SLIDE_TAP_CHECK", .raw = "0", .n = 0 }, + .{ .name = "TF_SLIDE_TAP_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TENSORFOLD_CUDA_KERNELS", .raw = "/tmp/captured set", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, @@ -294,3 +306,33 @@ test "environment: a legacy alias is checked only while its canonical name is un for ([_][]const u8{ "", "0", "1" }) |canonical| try t.expect((try e.refusal(a, Alias{ .canonical = canonical }, .{ .dsv41 = true })) == null); try t.expect((try e.refusal(a, Alias{ .canonical = null }, .{})) == null); } + +test "environment: the Metal Qwen and slide-learning switches take their forms, read blank as unset and name a refusal" { + const flags = [_][:0]const u8{ "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; + for (flags) |name| { + try t.expectEqual(@as(?u64, 0), try e.parse(name, "0")); + try t.expectEqual(@as(?u64, 1), try e.parse(name, "1")); + for ([_][]const u8{ "", " ", "\t" }) |raw| try t.expectEqual(@as(?u64, null), try e.parse(name, raw)); + for ([_][]const u8{ "00", "false", "2", "yes" }) |raw| { + try t.expectError(error.InvalidEnvironment, e.parse(name, raw)); + const why = (try e.refusal(a, Env{ .name = name, .raw = raw }, all)).?; + defer a.free(why); + try t.expect(std.mem.indexOf(u8, why, name) != null); + } + } + // unset and every valid value keep today's meaning: resume on unless 0, pages off unless 1 + try t.expect(try e.value(bool, "TF_QWEN27_SLOT_RESUME", null, true)); + try t.expect(try e.value(bool, "TF_QWEN27_SLOT_RESUME", "", true)); + try t.expect(!(try e.value(bool, "TF_QWEN27_SLOT_RESUME", "0", true))); + try t.expect(!(try e.value(bool, "TF_QWEN27_METAL_KV_PAGES", null, false))); + try t.expect(try e.value(bool, "TF_QWEN35_METAL_KV_PAGES", "1", false)); + try t.expectEqual(@as(?u64, 0), try e.parse("TF_SLIDE_FIT_REDUCE", "ordered")); + try t.expectEqual(@as(?u64, 1), try e.parse("TF_SLIDE_FIT_REDUCE", "tree")); + try t.expectEqual(@as(?u64, null), try e.parse("TF_SLIDE_FIT_REDUCE", "")); + for ([_][]const u8{ "Tree", "trees", "tre", "ordred" }) |raw| { + try t.expectError(error.InvalidEnvironment, e.parse("TF_SLIDE_FIT_REDUCE", raw)); + const why = (try e.refusal(a, Env{ .name = "TF_SLIDE_FIT_REDUCE", .raw = raw }, all)).?; + defer a.free(why); + try t.expect(std.mem.indexOf(u8, why, "TF_SLIDE_FIT_REDUCE") != null); + } +} diff --git a/zig/src/server/profile_line.zig b/zig/src/server/profile_line.zig index db7e43beb32..29000dbae5a 100644 --- a/zig/src/server/profile_line.zig +++ b/zig/src/server/profile_line.zig @@ -166,6 +166,9 @@ test "profile line: new rows and every grouped member report real names and scop .{ .name = "TF_SLIDE_EDIT", .raw = "0", .family = "nemotron_h", .backend = "metal", .class = "experimental" }, .{ .name = "TF_SLIDE_PROBE", .raw = "", .family = "nemotron_h", .backend = "cuda", .class = "experimental" }, .{ .name = "TF_SLIDE_ROUTED", .raw = "1", .family = "nemotron_h", .backend = "cuda", .class = "experimental" }, + .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, + .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, + .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "tree", .family = "qwen3_5", .backend = "cuda", .class = "arithmetic" }, }) |c| { const env: ExtraEnv = .{ .name = c.name, .value = c.raw }; const line = try format(a, .stable, c.family, c.backend, env); @@ -276,3 +279,13 @@ test "profile line: an empty or whitespace-only TF_KV_SHARE does not turn Dory's try std.testing.expect(std.mem.indexOf(u8, line, "TENSORFOLD_DORY_KV_PAGES") == null); } } + +test "profile line: Qwen's Metal paging shows only for exact 1, and the slide fit only for tree" { + const a = std.testing.allocator; + for ([_][2][]const u8{ .{ "TF_QWEN27_METAL_KV_PAGES", "0" }, .{ "TF_QWEN35_METAL_KV_PAGES", "0" }, .{ "TF_SLIDE_FIT_REDUCE", "ordered" } }) |c| { + const backend: []const u8 = if (std.mem.startsWith(u8, c[0], "TF_SLIDE")) "cuda" else "metal"; + const line = try format(a, .stable, "qwen3_5", backend, ExtraEnv{ .name = c[0], .value = c[1] }); + defer a.free(line); + try std.testing.expectEqualStrings("profile: stable; registered overrides: none", line); + } +} diff --git a/zig/src/server/slide.zig b/zig/src/server/slide.zig index e38d788b4da..3c2692c7cb5 100644 --- a/zig/src/server/slide.zig +++ b/zig/src/server/slide.zig @@ -309,7 +309,7 @@ pub fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone }; committed = true; // a diagnostic: every kept lesson taken out again, to see the facts before it come back as they were - if (std.c.getenv("TF_SLIDE_TAKE_OUT_CHECK") != null) { + if (@import("sys").environment.read(bool, "TF_SLIDE_TAKE_OUT_CHECK", false) catch false) { // malformed: logged by name and off takeOut(srv, a, &out, id, "taken out to check that a take-out puts the facts before it back (TF_SLIDE_TAKE_OUT_CHECK)"); afterTakeOut(srv, cx, o, id, before, &.{}, gone); asked_after = true; From f05fd7c7f10de3ff0e3bdeecf794e6c643f51c05 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:04:25 +0000 Subject: [PATCH 45/59] environment: drop TF_SLIDE_FIT_REDUCE; read the take-out check at start (#2370) TF_SLIDE_FIT_REDUCE leaves this change: its only reader, fitDevice, takes living.pocket_fit.DeviceFit, which does not exist, so nothing compiles it. Its row, profile entry and reader go back to main, and it stays in the lenient list. TF_SLIDE_TAKE_OUT_CHECK is read once when the server starts with --slide and kept in the config, so a malformed value is refused there by name instead of being logged at every kept lesson. Host test: the start-up read with and without --slide, and its refusals. --- docs/environment.md | 7 +++---- docs/profiles.md | 1 - zig/src/core/profile.zig | 2 -- zig/src/families/qwen3_5/cuda_train_more.zig | 2 +- zig/src/platform/environment.zig | 1 - zig/src/platform/environment_test.zig | 11 ----------- zig/src/server/profile_line.zig | 8 +++----- zig/src/server/serve.zig | 14 ++++++++++++++ zig/src/server/server.zig | 1 + zig/src/server/slide.zig | 2 +- 10 files changed, 23 insertions(+), 26 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 4e11fbe8e26..1e48b4dd78b 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -64,8 +64,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `LFM3_FUSE` | Whole u32 fusion mask; default 7 | | `TF_SLIDE_POCKET_KEY` | Exactly `auto`, `reply`, `subject` or `both`; default `auto` | | `TF_SLIDE_FIT_GIB` | Whole native-size nonnegative GiB count; default 4 | -| `TF_SLIDE_FIT_REDUCE` | Exactly `ordered` or `tree`: a fit's lane sums in order (the default) or as halves, quarters and pairs | -| `TF_SLIDE_TAKE_OUT_CHECK` | Exactly `0` or `1`; `1` takes every kept lesson out again to check the facts before it come back; default off | +| `TF_SLIDE_TAKE_OUT_CHECK` | Exactly `0` or `1`, read once when the server starts with `--slide`; `1` takes every kept lesson out again to check that the facts before it come back as they were; default off | | `TF_SLIDE_TAP_CHECK` | Exactly `0` or `1`; `1` checks a pass's tapped rows against a fresh run's; default off | | `TF_SLIDE_POCKET_DUMP` | A directory path without control characters, used as given; each lesson's read rows are written there for offline study. Unset or blank writes none | | `TF_SLIDE_FORGET_FAIL` | Whole u32 fact index, zero off; only checked in a slide-test-hooks build | @@ -141,8 +140,8 @@ These settings retain their existing boolean policies rather than gaining new al - Kolibri pages: exact `TENSORFOLD_KOLIBRI_KV_PAGES=0` disables requested pages; other text keeps the option unchanged. - Dory pages: unset or exact `TENSORFOLD_DORY_KV_PAGES=0` uses windows; every other present value selects pages. - `TF_SLIDE_EDIT`, `TF_SLIDE_PROBE` and `TF_SLIDE_ROUTED` select modes by presence, even empty or `0`; probe wins over edit. -- `TF_COOP_SPLIT` retains its first-character `0` disabling rule and `TF_NEMOTRON_TRACE` its first-character `1` trace - rule. These developer switches keep their existing semantics. +- `TF_COOP_SPLIT` retains its first-character `0` disabling rule, `TF_NEMOTRON_TRACE` its first-character `1` trace rule, + and `TF_SLIDE_FIT_REDUCE` its exact `tree` reduction selection. These developer switches keep their existing semantics. - GLM: `GLM_EHPROJ_NAX` retains its first-character `0` disabling rule, `TF_GLM_DFLASH2_PROF` enables by presence, even empty or `0`, and `TF_KV_POISON` (also read by Nemotron) is on only for exact `1`. - The existing tool-grammar, rows-sync, log-time, memory-pressure and XPU-MTP boolean policies are unchanged. diff --git a/docs/profiles.md b/docs/profiles.md index c1592713124..89b1e3078b2 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -61,7 +61,6 @@ Coverage includes: and values in the core pool's pages. - Qwen on Metal: `TF_QWEN27_METAL_KV_PAGES` (the 27B) and `TF_QWEN35_METAL_KV_PAGES`, where exactly `1` puts keys and values in the core pool's pages; `arithmetic` until a main-against-branch token-hash run says otherwise. -- Qwen3.5 slide learning on CUDA: `TF_SLIDE_FIT_REDUCE=tree` (`arithmetic`), which sums a fit's lanes in another order. - DeepSeek V4.1 on CUDA: the settings below, with no stable fallback. `identical` records the existing switch's token-preserving design and linked evidence; it is not a claim that the diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index bb06fa5904e..c752dbcfc8d 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -33,7 +33,6 @@ pub const Switch = enum { TF_NEMOTRON_METAL_KV_PAGES, TF_QWEN27_METAL_KV_PAGES, TF_QWEN35_METAL_KV_PAGES, - TF_SLIDE_FIT_REDUCE, slide_learn_mode, TF_DSV41_EXPERT_TOPP, TF_DSV41_NUCLEUS, @@ -170,7 +169,6 @@ pub const entries = [_]Entry{ .{ .id = .TF_NEMOTRON_METAL_KV_PAGES, .families = &.{"nemotron_h"}, .backend = "metal", .class = .identical, .syntax = .one, .effect = "Only exact 1 puts keys and values in the core pool's pages; unset, whole caches made at open", .evidence = "#1537" }, .{ .id = .TF_QWEN27_METAL_KV_PAGES, .families = &.{"qwen3_5"}, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the 27B's keys and values in core-pool pages; refused on Macs with tensor units", .evidence = "#2370; class until a main-against-branch token-hash run on a Mac without tensor units" }, .{ .id = .TF_QWEN35_METAL_KV_PAGES, .families = qwen, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the streams' keys and values in core-pool pages; unset, whole caches at load", .evidence = "#2370; class until a main-against-branch token-hash run" }, - .{ .id = .TF_SLIDE_FIT_REDUCE, .families = &.{"qwen3_5"}, .class = .arithmetic, .report_values = &.{"tree"}, .effect = "tree sums a fit's lanes as halves, quarters and pairs instead of in order, so a learned result can differ", .evidence = "#2370" }, .{ .id = .TF_DSV41_EXPERT_TOPP, .families = &.{"deepseek_v41"}, .class = .experimental, .syntax = .present, .effect = "Expert top-p routing mass", .evidence = "#2370" }, .{ .id = .TF_DSV41_NUCLEUS, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Nucleus candidate count", .evidence = "#2370" }, .{ .id = .TF_DSV41_CONTEXT, .families = &.{"deepseek_v41"}, .class = .arithmetic, .syntax = .present, .effect = "Slot position limit", .evidence = "#2370" }, diff --git a/zig/src/families/qwen3_5/cuda_train_more.zig b/zig/src/families/qwen3_5/cuda_train_more.zig index 601c2d4175b..174bc40df45 100644 --- a/zig/src/families/qwen3_5/cuda_train_more.zig +++ b/zig/src/families/qwen3_5/cuda_train_more.zig @@ -34,7 +34,7 @@ pub fn fitDevice(t: anytype, jobs: []const living.pocket_fit.DeviceFit) !void { const d = jobs[0].d; const m = jobs[0].kinds.len; for (jobs) |j| if (j.d != d or j.kinds.len != m or j.steps != jobs[0].steps or j.below != jobs[0].below or j.rows.len < m * j.slots * d) return error.BadFit; - const tree = try @import("sys").environment.read(u32, "TF_SLIDE_FIT_REDUCE", 0) == 1; // its words: ordered, tree + const tree = if (@import("sys").c.getenv("TF_SLIDE_FIT_REDUCE")) |v| std.mem.eql(u8, std.mem.span(v), "tree") else false; const gib = try @import("sys").environment.read(usize, "TF_SLIDE_FIT_GIB", 4); const per = m * d * 2; const L = @max(1, @min(jobs.len, (gib << 30) / per)); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index f3294f65ce8..67bcb4b6663 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -78,7 +78,6 @@ pub const rules = [_]Rule{ .{ .name = "TF_SLIDE_POCKET_KEY", .scope = .slide, .kind = .word, .words = &.{ "auto", "reply", "subject", "both" }, .forms = "auto, reply, subject or both" }, .{ .name = "TF_SLIDE_FIT_GIB", .scope = .slide, .kind = .size, .forms = "a whole nonnegative native-size GiB count" }, .{ .name = "TF_SLIDE_POCKET_DUMP", .scope = .slide, .kind = .path, .forms = "a directory path without control characters, where each lesson's read rows are written" }, - .{ .name = "TF_SLIDE_FIT_REDUCE", .scope = .slide, .kind = .word, .words = &.{ "ordered", "tree" }, .forms = "ordered or tree (a fit's lane sums in order, the default, or as halves, quarters and pairs)" }, .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .scope = .slide, .kind = .flag, .forms = "0 or 1 (1 takes every kept lesson out again to check the facts before it come back)" }, .{ .name = "TF_SLIDE_TAP_CHECK", .scope = .slide, .kind = .flag, .forms = "0 or 1 (1 checks tapped rows against a fresh run's)" }, .{ .name = "TF_SLIDE_FORGET_FAIL", .scope = .hooks, .kind = .u32, .trim = " ", .forms = "a whole fact index from 0 to 4294967295 (0 disables the planted failure)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index e5376374400..bba3055681a 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -109,8 +109,6 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_POCKET_KEY", .raw = "subject", .n = 2 }, .{ .name = "TF_SLIDE_POCKET_KEY", .raw = "both", .n = 3 }, .{ .name = "TF_SLIDE_FIT_GIB", .raw = "4", .n = 4 }, - .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "ordered", .n = 0 }, - .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "tree", .n = 1 }, .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .raw = "0", .n = 0 }, .{ .name = "TF_SLIDE_TAKE_OUT_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_SLIDE_TAP_CHECK", .raw = "0", .n = 0 }, @@ -326,13 +324,4 @@ test "environment: the Metal Qwen and slide-learning switches take their forms, try t.expect(!(try e.value(bool, "TF_QWEN27_SLOT_RESUME", "0", true))); try t.expect(!(try e.value(bool, "TF_QWEN27_METAL_KV_PAGES", null, false))); try t.expect(try e.value(bool, "TF_QWEN35_METAL_KV_PAGES", "1", false)); - try t.expectEqual(@as(?u64, 0), try e.parse("TF_SLIDE_FIT_REDUCE", "ordered")); - try t.expectEqual(@as(?u64, 1), try e.parse("TF_SLIDE_FIT_REDUCE", "tree")); - try t.expectEqual(@as(?u64, null), try e.parse("TF_SLIDE_FIT_REDUCE", "")); - for ([_][]const u8{ "Tree", "trees", "tre", "ordred" }) |raw| { - try t.expectError(error.InvalidEnvironment, e.parse("TF_SLIDE_FIT_REDUCE", raw)); - const why = (try e.refusal(a, Env{ .name = "TF_SLIDE_FIT_REDUCE", .raw = raw }, all)).?; - defer a.free(why); - try t.expect(std.mem.indexOf(u8, why, "TF_SLIDE_FIT_REDUCE") != null); - } } diff --git a/zig/src/server/profile_line.zig b/zig/src/server/profile_line.zig index 29000dbae5a..75d91ad1c68 100644 --- a/zig/src/server/profile_line.zig +++ b/zig/src/server/profile_line.zig @@ -168,7 +168,6 @@ test "profile line: new rows and every grouped member report real names and scop .{ .name = "TF_SLIDE_ROUTED", .raw = "1", .family = "nemotron_h", .backend = "cuda", .class = "experimental" }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .family = "qwen3_5", .backend = "metal", .class = "arithmetic" }, - .{ .name = "TF_SLIDE_FIT_REDUCE", .raw = "tree", .family = "qwen3_5", .backend = "cuda", .class = "arithmetic" }, }) |c| { const env: ExtraEnv = .{ .name = c.name, .value = c.raw }; const line = try format(a, .stable, c.family, c.backend, env); @@ -280,11 +279,10 @@ test "profile line: an empty or whitespace-only TF_KV_SHARE does not turn Dory's } } -test "profile line: Qwen's Metal paging shows only for exact 1, and the slide fit only for tree" { +test "profile line: Qwen's Metal paging shows only for exact 1" { const a = std.testing.allocator; - for ([_][2][]const u8{ .{ "TF_QWEN27_METAL_KV_PAGES", "0" }, .{ "TF_QWEN35_METAL_KV_PAGES", "0" }, .{ "TF_SLIDE_FIT_REDUCE", "ordered" } }) |c| { - const backend: []const u8 = if (std.mem.startsWith(u8, c[0], "TF_SLIDE")) "cuda" else "metal"; - const line = try format(a, .stable, "qwen3_5", backend, ExtraEnv{ .name = c[0], .value = c[1] }); + for ([_][2][]const u8{ .{ "TF_QWEN27_METAL_KV_PAGES", "0" }, .{ "TF_QWEN35_METAL_KV_PAGES", "0" } }) |c| { + const line = try format(a, .stable, "qwen3_5", "metal", ExtraEnv{ .name = c[0], .value = c[1] }); defer a.free(line); try std.testing.expectEqualStrings("profile: stable; registered overrides: none", line); } diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index b2cba36bf47..930958d72e9 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -162,6 +162,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { return 1; }, }; + const take_out_check = takeOutCheck(args.slide, env(s, "TF_SLIDE_TAKE_OUT_CHECK")) catch return 1; const salt = if (env(s, "TENSORFOLD_SEED_SALT")) |t| std.fmt.parseInt(i64, std.mem.trim(u8, t, " "), 10) catch { std.debug.print("tensorfold: TENSORFOLD_SEED_SALT={s}: an integer\n", .{t}); return 1; @@ -220,6 +221,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .compact_memory = args.compact_memory, .slide_graph = args.slide_graph, .slide_drift_gate = args.slide_drift_gate, + .slide_take_out_check = take_out_check, .slide_forget_fail = s.forget_fail, .cortheon = args.cortheon, .cortheon_search_key = env(s, "BRAVE_SEARCH_API_KEY"), @@ -428,6 +430,18 @@ test "the raise lifts a low soft limit, and a second raise does nothing" { try std.testing.expect(raiseOpenFileLimit() == null); } +/// TF_SLIDE_TAKE_OUT_CHECK, read once at start and only with --slide: a malformed value is refused here, by name. +fn takeOutCheck(slide: bool, raw: ?[]const u8) !bool { + return slide and try @import("sys").environment.value(bool, "TF_SLIDE_TAKE_OUT_CHECK", raw, false); +} + +test "Failure boundaries: TF_SLIDE_TAKE_OUT_CHECK is read once at start, only with --slide" { + try std.testing.expect(try takeOutCheck(true, "1")); + for ([_]?[]const u8{ null, "", "0" }) |raw| try std.testing.expect(!try takeOutCheck(true, raw)); + try std.testing.expect(!try takeOutCheck(false, "1")); + for ([_][]const u8{ "yes", "2", "on" }) |raw| try std.testing.expectError(error.InvalidEnvironment, takeOutCheck(true, raw)); +} + test "Failure boundaries: drain and SSE duration settings refuse non-finite or unrepresentable values" { try std.testing.expectEqual(@as(?f64, null), seconds("inf", 20)); try std.testing.expectEqual(@as(?f64, null), seconds("1e300", 20)); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 9ec1513bb9d..882ab169514 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -95,6 +95,7 @@ pub const Config = struct { /// --slide-graph: the file holding the Sliding Weights fact graph; null keeps the graph in memory. slide_graph: ?[]const u8 = null, slide_drift_gate: bool = false, + slide_take_out_check: bool = false, // TF_SLIDE_TAKE_OUT_CHECK=1 with --slide, read once at start /// A fact whose check a delete fails, to test its put-back (0: none); only -Dslide-test-hooks builds set it. slide_forget_fail: u32 = 0, /// --cortheon: Cortheon's program and server-run web research for chat requests; off changes no reply. diff --git a/zig/src/server/slide.zig b/zig/src/server/slide.zig index 3c2692c7cb5..5a6f978a225 100644 --- a/zig/src/server/slide.zig +++ b/zig/src/server/slide.zig @@ -309,7 +309,7 @@ pub fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone }; committed = true; // a diagnostic: every kept lesson taken out again, to see the facts before it come back as they were - if (@import("sys").environment.read(bool, "TF_SLIDE_TAKE_OUT_CHECK", false) catch false) { // malformed: logged by name and off + if (srv.config.slide_take_out_check) { // TF_SLIDE_TAKE_OUT_CHECK, read at start takeOut(srv, a, &out, id, "taken out to check that a take-out puts the facts before it back (TF_SLIDE_TAKE_OUT_CHECK)"); afterTakeOut(srv, cx, o, id, before, &.{}, gone); asked_after = true; From dfc83d868e4efd86534761d9f54bd8a92f89089a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:01:37 +0000 Subject: [PATCH 46/59] server: slide_forget_fail's note on its line, so server.zig stays at 600 with slide_take_out_check Comment-only: Config keeps every field and default. --- zig/src/server/server.zig | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 882ab169514..158ff512eeb 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -96,8 +96,7 @@ pub const Config = struct { slide_graph: ?[]const u8 = null, slide_drift_gate: bool = false, slide_take_out_check: bool = false, // TF_SLIDE_TAKE_OUT_CHECK=1 with --slide, read once at start - /// A fact whose check a delete fails, to test its put-back (0: none); only -Dslide-test-hooks builds set it. - slide_forget_fail: u32 = 0, + slide_forget_fail: u32 = 0, // a fact a delete fails to check, to test its put-back (0: none; test-hook builds) /// --cortheon: Cortheon's program and server-run web research for chat requests; off changes no reply. cortheon: bool = false, /// BRAVE_SEARCH_API_KEY: Cortheon searches through Brave instead of DuckDuckGo. From 4bf995ce3140d26cfbdc6dde07b7c4727ffe3e6b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:11:35 +0000 Subject: [PATCH 47/59] changelog: #3018 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32b0947d619..41719f2591c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Environment: the Metal Qwen KV paging and slot-resume switches and the slide checks refuse a malformed value by name, and `TF_SLIDE_TAKE_OUT_CHECK` is read once at start with `--slide` (#3018, for #2370). + - Metrics: every queued request carries one wait reason decided on the admission path, and DeepSeek-V4.1 names its own (`kv_pool`, `memory_floor`, `prefill_concurrent`). `/metrics` gains `requests_waiting_by_reason`, `request_refusals_total` and `request_failures_total` by code and `restore_fallbacks_total`, and `/v1/load` gains `waiting_by_reason` and `refusals`; replies are unchanged (#3014, for #2135). Thanks to @devopsfortunato for the design. - Tests: the Qwen3.8-27B reply-end keep test names its history, as the keep pin added on 10 Nov requires, and `test-qwen27-reply-cache-host` now runs it (#3012). From 83ad23d88cbea7010292f16d21c8e5029f3350da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:54:09 +0100 Subject: [PATCH 48/59] lfm2_moe: the attention caches in pages of the core pool, every stream leasing The kernels already read keys and values through a slot's page table, so the pool changes only what the table holds and how large the arena is; no kernel changes. A page is 512 positions of the ten attention layers' keys and values (10 MiB, 20 KiB a token); the conv states stay a fixed part a slot (240 KiB). - Loaded.layout with engine_paged, as Dory's: the plan sets a window of pages aside for the first stream; each stream leases its prompt, its reply and one verify window at its prompt pass and gives them back when it ends. A request that cannot lease waits (LaneMemory); fits is the host's admission. - Model.attach makes the arena and the tables and conv states of the slots the plan names; forward refuses rows past a slot's pages. The idle server logs the pool's census. - TENSORFOLD_LFM2_KV_PAGES=0 keeps every stream's own window of pages, made at open. Served on the GB10 at --parallel 8, 16k: drafted == plain and concurrent == solo, also with 8 long prompts on a 52-page pool where the last waits for pages; the replies equal the fixed pages' ones. --- docs/profiles.md | 2 + zig/src/core/profile.zig | 2 + zig/src/core/profile_test.zig | 6 +- zig/src/families/lfm2_moe/cuda_backend.zig | 94 +++++++++++-- zig/src/families/lfm2_moe/cuda_forward.zig | 1 + zig/src/families/lfm2_moe/cuda_model.zig | 148 +++++++++++++++++++-- zig/src/families/lfm2_moe/cuda_native.zig | 43 +++++- 7 files changed, 266 insertions(+), 30 deletions(-) diff --git a/docs/profiles.md b/docs/profiles.md index 89b1e3078b2..64f6d5ebbd8 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -57,6 +57,8 @@ Coverage includes: every stream's caches are contiguous and made at open. - Gemma 4 on CUDA: `TENSORFOLD_GEMMA4_KV_PAGES`, global caches in pool pages by default, where `0` keeps them linear. - Spark2.5 on CUDA: `TENSORFOLD_SPARK25_KV_PAGES`, full caches in pool pages by default, where `0` keeps them linear. +- LFM2.5-24B-A2B on CUDA: `TENSORFOLD_LFM2_KV_PAGES`, attention caches in pool pages by default, where `0` gives + each stream fixed pages made at open. - Nemotron-H on Metal: `TF_NEMOTRON_METAL_KV_PAGES`, where exactly `1` puts keys and values in the core pool's pages. - Qwen on Metal: `TF_QWEN27_METAL_KV_PAGES` (the 27B) and `TF_QWEN35_METAL_KV_PAGES`, where exactly `1` puts keys and diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index c752dbcfc8d..a1cf975eeb0 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -30,6 +30,7 @@ pub const Switch = enum { TF_PROMPT_ROWS, TENSORFOLD_GEMMA4_KV_PAGES, TENSORFOLD_SPARK25_KV_PAGES, + TENSORFOLD_LFM2_KV_PAGES, TF_NEMOTRON_METAL_KV_PAGES, TF_QWEN27_METAL_KV_PAGES, TF_QWEN35_METAL_KV_PAGES, @@ -166,6 +167,7 @@ pub const entries = [_]Entry{ .{ .id = .slide_learn_mode, .families = slide_cuda, .backend = "multiple", .scopes = &.{ .{ .backend = "cuda", .families = slide_cuda }, .{ .backend = "metal", .families = nemotron } }, .members = &.{ .{ .name = "TF_SLIDE_POCKET_KEY", .syntax = .auto }, .{ .name = "TF_SLIDE_EDIT", .syntax = .present, .families = nemotron }, .{ .name = "TF_SLIDE_PROBE", .syntax = .present, .families = nemotron }, .{ .name = "TF_SLIDE_ROUTED", .syntax = .present, .families = nemotron } }, .class = .experimental, .effect = "Pocket keying and presence-selected edit, probe or routed learning modes", .evidence = "#2370" }, .{ .id = .TENSORFOLD_GEMMA4_KV_PAGES, .families = &.{ "gemma4", "gemma4_unified" }, .class = .identical, .report_values = &.{"0"}, .effect = "Global caches lease pool pages by default; 0 keeps them linear", .evidence = "#1619" }, .{ .id = .TENSORFOLD_SPARK25_KV_PAGES, .families = &.{"spark2_5"}, .class = .identical, .report_values = &.{"0"}, .effect = "Full caches lease pool pages by default; 0 keeps them linear", .evidence = "#1653" }, + .{ .id = .TENSORFOLD_LFM2_KV_PAGES, .families = &.{"lfm2_moe"}, .class = .identical, .report_values = &.{"0"}, .effect = "Attention caches lease pool pages by default; 0 keeps fixed pages a stream", .evidence = "#1503" }, .{ .id = .TF_NEMOTRON_METAL_KV_PAGES, .families = &.{"nemotron_h"}, .backend = "metal", .class = .identical, .syntax = .one, .effect = "Only exact 1 puts keys and values in the core pool's pages; unset, whole caches made at open", .evidence = "#1537" }, .{ .id = .TF_QWEN27_METAL_KV_PAGES, .families = &.{"qwen3_5"}, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the 27B's keys and values in core-pool pages; refused on Macs with tensor units", .evidence = "#2370; class until a main-against-branch token-hash run on a Mac without tensor units" }, .{ .id = .TF_QWEN35_METAL_KV_PAGES, .families = qwen, .backend = "metal", .class = .arithmetic, .syntax = .one, .effect = "Only exact 1 puts the streams' keys and values in core-pool pages; unset, whole caches at load", .evidence = "#2370; class until a main-against-branch token-hash run" }, diff --git a/zig/src/core/profile_test.zig b/zig/src/core/profile_test.zig index 488e1a92a19..e9df04a5d2d 100644 --- a/zig/src/core/profile_test.zig +++ b/zig/src/core/profile_test.zig @@ -158,8 +158,8 @@ test "stable profile: Dory paging is on unless the value is exactly zero" { try t.expect(!e.differs("0")); } -test "stable profile: Gemma 4 and Spark2.5 paging is off only for exactly zero" { - inline for (.{ .TENSORFOLD_GEMMA4_KV_PAGES, .TENSORFOLD_SPARK25_KV_PAGES }) |id| { +test "stable profile: Gemma 4, Spark2.5 and LFM2.5 paging is off only for exactly zero" { + inline for (.{ .TENSORFOLD_GEMMA4_KV_PAGES, .TENSORFOLD_SPARK25_KV_PAGES, .TENSORFOLD_LFM2_KV_PAGES }) |id| { const e = p.entry(id); try t.expect(e.report_values != null and e.report_values.?.len == 1 and std.mem.eql(u8, e.report_values.?[0], "0")); try t.expectEqual(p.Class.identical, e.class); @@ -169,6 +169,8 @@ test "stable profile: Gemma 4 and Spark2.5 paging is off only for exactly zero" } try t.expect(p.entry(.TENSORFOLD_GEMMA4_KV_PAGES).applies("gemma4_unified", "cuda")); try t.expect(p.entry(.TENSORFOLD_SPARK25_KV_PAGES).applies("spark2_5", "cuda")); + try t.expect(p.entry(.TENSORFOLD_LFM2_KV_PAGES).applies("lfm2_moe", "cuda")); + try t.expect(!p.entry(.TENSORFOLD_LFM2_KV_PAGES).applies("lfm2_moe", "metal")); } test "stable profile: Nemotron's paging on Metal has its own scope" { diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig index f1827b208bc..5199cdf6a9e 100644 --- a/zig/src/families/lfm2_moe/cuda_backend.zig +++ b/zig/src/families/lfm2_moe/cuda_backend.zig @@ -6,6 +6,7 @@ const cfg = @import("config.zig"); const fwd = @import("cuda_forward.zig"); const mdl = @import("cuda_model.zig"); const kern = @import("cuda_kernels.zig"); +const kv = @import("core").kv_pool; const be = lanes.backend; const Stream = lanes.Stream; @@ -30,8 +31,14 @@ const Lane = struct { rule: u64, // sample.cu's Rule, when the stream samples sampled: bool = false, fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts + lease: kv.Lease = .{}, // a paged slot's pages }; +/// Pages a request holds: its prompt, its reply and one last verify window. +pub fn pagesFor(prompt: usize, max_new: usize) usize { + return (prompt + max_new + max_window + kern.page - 1) / kern.page; +} + pub const Lfm = struct { gpa: std.mem.Allocator, d: *const cuda.Driver, @@ -46,6 +53,7 @@ pub const Lfm = struct { meta: cuda.DeviceBuffer, // a draw's first position minus one, a window each slot_bufs: []cuda.DeviceBuffer, // a slot's last-row logits, then its rule: two a slot next: u64 = 0, + pool: ?kv.Pool = null, // the pages every slot leases (attach) /// The device bytes `init` allocates: the token and pick rings, metas, each slot's last row and rule. pub fn openBytes(slots: usize) usize { @@ -53,7 +61,7 @@ pub const Lfm = struct { } pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *mdl.Model, k: *const kern.Kernels, s: cuda.Stream) !Lfm { - const free = try gpa.alloc(bool, m.slots); + const free = try gpa.alloc(bool, m.slotCap()); errdefer gpa.free(free); @memset(free, true); const greedy = try gpa.alloc(bool, ring + round_rows); @@ -65,7 +73,7 @@ pub const Lfm = struct { errdefer picks.free(); var meta = try cuda.DeviceBuffer.alloc(d, round_rows * 16); errdefer meta.free(); - const bufs = try gpa.alloc(cuda.DeviceBuffer, 2 * m.slots); + const bufs = try gpa.alloc(cuda.DeviceBuffer, 2 * m.slotCap()); errdefer gpa.free(bufs); var made: usize = 0; errdefer for (bufs[0..made]) |*b| b.free(); @@ -76,9 +84,19 @@ pub const Lfm = struct { return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .free = free, .tok = tok, .picks = picks, .greedy = greedy, .meta = meta, .slot_bufs = bufs }; } + /// Makes a paged model's arena of `pages` pages for `extra + 1` slots, and the pool that leases them. + pub fn attach(x: *Lfm, extra: usize, pages: usize) !void { + try x.m.attach(x.s, extra, pages); + x.pool = try kv.Pool.init(x.gpa, pages, mdl.page_elems * 2); + } + pub fn deinit(x: *Lfm) void { var it = x.lanes.valueIterator(); - while (it.next()) |l| l.rows.deinit(x.gpa); + while (it.next()) |l| { + if (x.pool) |*p| p.finish(&l.lease); + l.rows.deinit(x.gpa); + } + if (x.pool) |*p| p.deinit(); x.lanes.deinit(x.gpa); for (x.slot_bufs) |*b| b.free(); x.gpa.free(x.slot_bufs); @@ -97,7 +115,7 @@ pub const Lfm = struct { /// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a forward. pub fn facts(x: *const Lfm) lanes.Model { - return .{ .exact_width = max_window, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = round_rows, .max_streams = @intCast(@min(x.m.slots, round_rows)) }; + return .{ .exact_width = max_window, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = round_rows, .max_streams = @intCast(@min(x.m.slotCap(), round_rows)) }; } fn self(ptr: *anyopaque) *Lfm { @@ -133,7 +151,39 @@ pub const Lfm = struct { } fn freeSlot(x: *const Lfm) ?usize { - return std.mem.indexOfScalar(bool, x.free, true); + return std.mem.indexOfScalar(bool, x.free[0..x.m.slots], true); + } + + fn fitsContext(x: *const Lfm, prompt: usize, max_new: usize) bool { + return prompt + max_new + max_window <= x.m.context; + } + + /// Whether a request could start now: a free slot and (paged) its pages; one that never fits passes. + pub fn admits(x: *const Lfm, prompt: usize, max_new: usize) bool { + if (!x.fitsContext(prompt, max_new)) return true; // its prompt pass refuses it by name + const p = x.pool orelse return x.freeSlot() != null; + return x.freeSlot() != null and p.fits(pagesFor(prompt, max_new)); + } + + const Map = struct { + x: *Lfm, + slot: usize, + fn write(ctx: *anyopaque, ids: []const u32, from: usize) anyerror!void { + const m: *const Map = @ptrCast(@alignCast(ctx)); + try m.x.m.mapPages(m.x.s, m.slot, ids[from..], from); + } + }; + + /// A free slot for the request, its pages leased now when paged; LaneMemory: not yet. + fn takeSlot(x: *Lfm, lease: *kv.Lease, prompt: usize, max_new: usize) !usize { + const slot = x.freeSlot() orelse return error.NoFreeSlot; + const p = if (x.pool) |*p| p else return slot; + const n = pagesFor(prompt, max_new); + try p.promise(lease, n); + errdefer p.finish(lease); + var map: Map = .{ .x = x, .slot = slot }; + try p.cover(lease, n, .{ .ctx = &map, .write = Map.write }); + return slot; } /// A prompt pass begins: a slot, the stream's rule, a kept state restored; where its first chunk starts. @@ -141,15 +191,16 @@ pub const Lfm = struct { const p = s.prompt(); if (p.len == 0) return error.EmptyPrompt; if (s.images.len > 0) return error.LfmTextOnly; - if (p.len + @as(usize, s.max_new) + max_window > x.m.context) return error.PastContext; + if (!x.fitsContext(p.len, s.max_new)) return error.PastContext; const got = try x.lanes.getOrPut(x.gpa, s); if (!got.found_existing) { - const slot = x.freeSlot() orelse { + var lease: kv.Lease = .{}; + const slot = x.takeSlot(&lease, p.len, s.max_new) catch |e| { x.lanes.removeByPtr(got.key_ptr); - return error.NoFreeSlot; + return e; }; x.free[slot] = false; - got.value_ptr.* = .{ .slot = slot, .last = x.slot_bufs[2 * slot].ptr, .rule = x.slot_bufs[2 * slot + 1].ptr }; + got.value_ptr.* = .{ .slot = slot, .last = x.slot_bufs[2 * slot].ptr, .rule = x.slot_bufs[2 * slot + 1].ptr, .lease = lease }; } const l = got.value_ptr; l.sampled = false; @@ -305,14 +356,35 @@ pub const Lfm = struct { } fn dropLane(x: *Lfm, s: *const Stream) void { - if (x.lanes.fetchRemove(s)) |kv| { - var l = kv.value; + if (x.lanes.fetchRemove(s)) |entry| { + var l = entry.value; + if (x.pool) |*p| { + p.finish(&l.lease); + x.m.unmapPages(l.slot); + } x.free[l.slot] = true; l.rows.deinit(x.gpa); + if (x.lanes.count() == 0) x.report(); } } + /// The idle server's line: nothing promised, every page free (kept states are copies, not pages). + fn report(x: *const Lfm) void { + if (@import("builtin").is_test) return; + const p = x.pool orelse return; + const c = p.census(); + const ok = p.idle() and c.free == c.total; + std.log.info("kv pool idle{s}: promised {d}, free {d} + store {d} == total {d}", .{ if (ok) "" else " (UNEVEN)", c.promised, c.free, c.kept, c.total }); + } + fn release(ptr: *anyopaque, s: *Stream) void { self(ptr).dropLane(s); } }; + +test "a request holds its prompt, its reply and one verify window in whole pages" { + try std.testing.expectEqual(@as(usize, 1), pagesFor(1, 1)); + try std.testing.expectEqual(@as(usize, 1), pagesFor(400, 96)); + try std.testing.expectEqual(@as(usize, 2), pagesFor(400, 97)); + try std.testing.expectEqual(@as(usize, 65), pagesFor(32768, 0)); +} diff --git a/zig/src/families/lfm2_moe/cuda_forward.zig b/zig/src/families/lfm2_moe/cuda_forward.zig index b0ac16a93af..723d2944536 100644 --- a/zig/src/families/lfm2_moe/cuda_forward.zig +++ b/zig/src/families/lfm2_moe/cuda_forward.zig @@ -148,6 +148,7 @@ pub fn forward(m: *const Model, k: *const Kernels, s: Stream, chains: []const Ch var rows: usize = 0; for (chains) |ch| { if (ch.tokens.len == 0 or ch.slot >= m.slots or ch.p0 + ch.tokens.len > m.context) return error.BadChain; + if (ch.p0 + ch.tokens.len > m.caps[ch.slot]) return error.PastPages; rows += ch.tokens.len; } if (rows > @as(usize, if (prompt) mdl.prompt_rows else mdl.round_rows) or (prompt and chains.len != 1)) return error.BadWindow; diff --git a/zig/src/families/lfm2_moe/cuda_model.zig b/zig/src/families/lfm2_moe/cuda_model.zig index 50f2c51277d..7d4b6364559 100644 --- a/zig/src/families/lfm2_moe/cuda_model.zig +++ b/zig/src/families/lfm2_moe/cuda_model.zig @@ -1,6 +1,7 @@ //! LFM2.5-24B-A2B's device state on CUDA: KV in 512-position pages, each slot's conv states, the scratch. const std = @import("std"); const cuda = @import("cuda"); +const kv = @import("core").kv_pool; const c = @import("config.zig"); const wts = @import("cuda_weights.zig"); const kern = @import("cuda_kernels.zig"); @@ -60,9 +61,13 @@ pub const Model = struct { w: *const wts.Weights, context: usize, // positions a slot holds: whole pages slots: usize, + paged: bool = false, // slots lease pages of the core pool (attach makes the arena), else each owns a window + pages: usize = 0, // pages in the arena arena: u64 = 0, // [pages][attention layer][K, V][512][kv_width] bf16 - table: u64 = 0, // int32 [slots][pages a slot]: slot s's pages s * per .. (s + 1) * per + table: u64 = 0, // int32 [slots][pages a slot]: slot s's page ids in position order states: u64 = 0, // bf16 [slots][conv layer][2][hidden] + ids: []u32 = &.{}, // the tables on the host + caps: []usize = &.{}, // positions slot s's pages cover inv: u64 = 0, // fp32 [head_dim / 2]: RoPE's inverse frequencies s: Scratch = undefined, buffers: std.ArrayList(DeviceBuffer) = .empty, @@ -82,6 +87,16 @@ pub const Model = struct { return positions(context) / kern.page * page_elems * 2 + slot_elems * 2; } + /// What the host's pool plans: a stream's conv states and table row, a token its rows of the ten layers. + pub fn layout(m: *const Model) kv.Layout { + return kv.Layout.ofRows(.{ .kind = .full, .row = kv_width * 2 * 2, .layers = attention_layers }, kern.page, slot_elems * 2 + m.perSlot() * 4, 0); + } + + /// Slots a backend holds: the model's, or (paged) as many as a round takes. + pub fn slotCap(m: *const Model) usize { + return if (m.paged) round_rows else m.slots; + } + /// Decode attention's key chunks a row walks at most, and the blocks that walk them. pub fn chunks(m: *const Model) usize { return m.perSlot(); @@ -105,26 +120,89 @@ pub const Model = struct { return b.ptr; } - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, context: usize, slots: usize) !Model { - var m: Model = .{ .gpa = gpa, .d = d, .w = w, .context = positions(context), .slots = slots }; + /// `slots` streams, each owning a window of pages; paged: one slot's states now, `attach` makes the pages. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, context: usize, slots: usize, paged: bool) !Model { + var m: Model = .{ .gpa = gpa, .d = d, .w = w, .context = positions(context), .slots = if (paged) 1 else slots, .paged = paged }; errdefer m.deinit(); try m.build(s); return m; } /// The device bytes `init` allocates for these sizes, counted by the same path without allocating. - pub fn openBytes(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, context: usize, slots: usize) !usize { - var m: Model = .{ .gpa = gpa, .d = d, .w = w, .context = positions(context), .slots = slots, .planned = 0 }; + pub fn openBytes(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const wts.Weights, context: usize, slots: usize, paged: bool) !usize { + var m: Model = .{ .gpa = gpa, .d = d, .w = w, .context = positions(context), .slots = if (paged) 1 else slots, .paged = paged, .planned = 0 }; defer m.deinit(); try m.build(s); return m.planned.?; } - fn build(m: *Model, s: cuda.Stream) !void { + /// Makes the arena of `pool` pages to lease and the states and tables of `extra + 1` slots (no pages mapped). + pub fn attach(m: *Model, s: cuda.Stream, extra: usize, pool: usize) !void { + if (!m.paged or m.pages != 0 or extra >= round_rows) return error.BadAttach; + m.forget(m.table); + m.forget(m.states); + m.gpa.free(m.ids); + m.gpa.free(m.caps); + m.ids = &.{}; + m.caps = &.{}; + m.slots = extra + 1; + m.pages = pool; + m.arena = try m.alloc(pool * page_elems * 2); + try m.d.check(m.d.api.cuMemsetD8Async(m.arena, 0, pool * page_elems * 2, s.handle), "cuMemsetD8Async"); + try m.makeSlots(s); + try s.synchronize(); + } + + /// Slot `slot`'s pages from table entry `from` on are `ids` (arena page numbers in position order). + pub fn mapPages(m: *Model, s: cuda.Stream, slot: usize, ids: []const u32, from: usize) !void { + const at = try m.note(slot, ids, from); + try m.d.check(m.d.api.cuMemcpyHtoDAsync_v2(m.table + at * 4, ids.ptr, ids.len * 4, s.handle), "cuMemcpyHtoDAsync"); + } + + /// mapPages on the host: the table's copy and the slot's reach; the entry its device copy starts at. + fn note(m: *Model, slot: usize, ids: []const u32, from: usize) !usize { + const per = m.perSlot(); + if (slot >= m.slots or from + ids.len > per) return error.BadChain; + for (ids) |id| if (id >= m.pages) return error.BadChain; + const at = slot * per + from; + @memcpy(m.ids[at..][0..ids.len], ids); + m.caps[slot] = (from + ids.len) * kern.page; + return at; + } + + /// Slot `slot` holds no pages: its table entries stay, no forward may reach them. + pub fn unmapPages(m: *Model, slot: usize) void { + m.caps[slot] = 0; + } + + /// Frees one buffer `alloc` made. + fn forget(m: *Model, ptr: u64) void { + for (m.buffers.items, 0..) |*b, i| if (b.ptr == ptr) { + b.free(); + _ = m.buffers.swapRemove(i); + return; + }; + } + + /// The slots' tables and conv states; a window of pages a slot unless paged (their pages come from leases). + fn makeSlots(m: *Model, s: cuda.Stream) !void { const per = m.perSlot(); - m.arena = try m.alloc(m.slots * per * page_elems * 2); m.table = try m.alloc(m.slots * per * 4); m.states = try m.alloc(m.slots * slot_elems * 2); + if (m.planned != null) return; + m.ids = try m.gpa.alloc(u32, m.slots * per); + m.caps = try m.gpa.alloc(usize, m.slots); + for (m.ids, 0..) |*v, i| v.* = if (m.paged) 0 else @intCast(i); + @memset(m.caps, if (m.paged) 0 else m.context); + try m.d.check(m.d.api.cuMemcpyHtoDAsync_v2(m.table, m.ids.ptr, m.ids.len * 4, s.handle), "cuMemcpyHtoDAsync"); + try (DeviceBuffer{ .d = m.d, .ptr = m.states, .len = m.slots * slot_elems * 2, .borrowed = true }).fill8(0, s.handle); + try s.synchronize(); + } + + fn build(m: *Model, s: cuda.Stream) !void { + if (!m.paged) m.pages = m.slots * m.perSlot(); + if (m.pages > 0) m.arena = try m.alloc(m.pages * page_elems * 2); + try m.makeSlots(s); m.inv = try m.alloc(c.head_dim / 2 * 4); const r = prompt_rows; const h = c.hidden; @@ -163,19 +241,15 @@ pub const Model = struct { .logits = try m.alloc(round_rows * c.vocab * 2), }; if (m.planned != null) return; - const ids = try m.gpa.alloc(i32, m.slots * per); - defer m.gpa.free(ids); - for (ids, 0..) |*v, i| v.* = @intCast(i); - try (DeviceBuffer{ .d = m.d, .ptr = m.table, .len = ids.len * 4, .borrowed = true }).upload(0, std.mem.sliceAsBytes(ids)); const inv = inverseFrequencies(m.w.config.theta); try (DeviceBuffer{ .d = m.d, .ptr = m.inv, .len = inv.len * 4, .borrowed = true }).upload(0, std.mem.sliceAsBytes(&inv)); - try (DeviceBuffer{ .d = m.d, .ptr = m.states, .len = m.slots * slot_elems * 2, .borrowed = true }).fill8(0, s.handle); - try s.synchronize(); } pub fn deinit(m: *Model) void { for (m.buffers.items) |*b| b.free(); m.buffers.deinit(m.gpa); + m.gpa.free(m.ids); + m.gpa.free(m.caps); } /// Attention layer a's key (or value) cache as the kernels take it: its part of page 0. @@ -213,3 +287,51 @@ test "a page holds 512 positions of the ten attention layers' keys and values: 1 try std.testing.expectEqual(@as(f32, 1), inv[0]); try std.testing.expect(@abs(inv[31] - 1.0 / std.math.pow(f64, 1e7, 62.0 / 64.0)) < 1e-12); } + +test "the pool's layout: 20 KiB a token, a stream's conv states and table row fixed, no snapshot slots" { + var m: Model = undefined; + m.context = Model.positions(32768); + const l = m.layout(); + try std.testing.expectEqual(@as(u64, 10 << 20), l.pageBytes()); + try std.testing.expectEqual(@as(u64, 20 << 10), l.token_bytes); + try std.testing.expectEqual(@as(u32, attention_layers), l.shape().full.layers); + try std.testing.expect(l.shape().named); + try std.testing.expectEqual(@as(u64, slot_elems * 2 + 64 * 4), l.fixed_bytes); + // 40 GiB past the weights, 8 streams at 32k, the default 16 GiB cache: a window for the first, the rest pages + const p = try kv.plan(l, .{ .room = 40 << 30, .engine = 0, .lanes = 8, .cache = 16 << 30, .window = 32768 + 16, .engine_paged = true }); + try std.testing.expectEqual(@as(u32, 8), p.lanes); + try std.testing.expectEqual(@as(usize, 0), p.snaps); + try std.testing.expect(p.pages * l.pageBytes() + p.copied + 7 * l.fixed_bytes <= 40 << 30); + try std.testing.expect(p.pages >= l.pages(32768 + 16)); +} + +test "leases map a slot's pages in position order; its reach ends at them; an id past the arena is refused" { + var ids: [8]u32 = @splat(0); + var caps = [_]usize{ 0, 0 }; + var m: Model = undefined; + m.context = 4 * kern.page; + m.slots = 2; + m.pages = 16; + m.ids = &ids; + m.caps = ∩︀ + var pool = try kv.Pool.init(std.testing.allocator, 16, page_elems * 2); + defer pool.deinit(); + var lease: kv.Lease = .{}; + try pool.promise(&lease, 3); + const Rec = struct { + m: *Model, + fn write(ctx: *anyopaque, got: []const u32, from: usize) anyerror!void { + const r: *@This() = @ptrCast(@alignCast(ctx)); + _ = try r.m.note(1, got[from..], from); + } + }; + var rec: Rec = .{ .m = &m }; + try pool.cover(&lease, 3, .{ .ctx = &rec, .write = Rec.write }); + try std.testing.expectEqualSlices(u32, lease.ids.items, ids[4..7]); + try std.testing.expectEqual(@as(usize, 3 * kern.page), caps[1]); + try std.testing.expectEqual(@as(usize, 13), pool.available()); + pool.finish(&lease); + try std.testing.expect(pool.idle() and pool.available() == 16); + try std.testing.expectError(error.BadChain, m.note(0, &.{16}, 0)); + try std.testing.expectError(error.BadChain, m.note(0, &.{ 1, 2, 3, 4, 5 }, 0)); +} diff --git a/zig/src/families/lfm2_moe/cuda_native.zig b/zig/src/families/lfm2_moe/cuda_native.zig index b5699b57953..605e1e92f2e 100644 --- a/zig/src/families/lfm2_moe/cuda_native.zig +++ b/zig/src/families/lfm2_moe/cuda_native.zig @@ -7,6 +7,7 @@ const wts = @import("cuda_weights.zig"); const kern = @import("cuda_kernels.zig"); const mdl = @import("cuda_model.zig"); const be = @import("cuda_backend.zig"); +const kv = @import("core").kv_pool; pub const model_type = "lfm2_moe"; pub const formats: []const []const u8 = &.{"mlx-q4g64"}; @@ -14,6 +15,8 @@ pub const default_context: i64 = 32768; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; pub const snap_lookahead: u32 = 0; +/// A request's last verify window: its pages hold that many rows past its prompt and reply. +pub const window_rows: u32 = be.max_window; pub const explains_open = true; /// The server's reading of the room left after the weights; null if unreadable. @@ -30,6 +33,10 @@ pub const Loaded = struct { ctx: *anyopaque, deinit: *const fn (*anyopaque) void, target: *be.Lfm, + /// The attention caches as pages of the core pool (null: every stream owns a window, made at open). + layout: ?kv.Layout = null, + /// With a layout: the first stream's rows are pages too, a window of them set aside by the plan. + engine_paged: bool = true, }; const Owned = struct { gpa: std.mem.Allocator, w: wts.Weights, k: kern.Kernels, s: cuda.Stream, m: mdl.Model, lb: be.Lfm }; @@ -45,17 +52,37 @@ fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { return n; } +/// TENSORFOLD_LFM2_KV_PAGES=0: every stream owns a window of pages, made at open; else they lease the pool's. +fn pagesOn() bool { + const v = @import("core").profile.get(.TENSORFOLD_LFM2_KV_PAGES) orelse return true; + return !std.mem.eql(u8, v, "0"); +} + +/// The device bytes `n` streams take (paged: the first's states and a round's slot buffers, no pages). const Plan = struct { own: *const Owned, d: *const cuda.Driver, context: usize, + paged: bool, fn bytes(p: Plan, n: usize) !u64 { const o = p.own; - return try mdl.Model.openBytes(o.gpa, p.d, o.s, &o.w, p.context, n) + be.Lfm.openBytes(n); + return try mdl.Model.openBytes(o.gpa, p.d, o.s, &o.w, p.context, n, p.paged) + be.Lfm.openBytes(if (p.paged) be.round_rows else n); } }; +/// The pool: `streams` more slots beside the first and an arena of `n` pages. +pub fn attach(p: *anyopaque, streams: u32, n: usize) !void { + const own: *Owned = @ptrCast(@alignCast(p)); + try own.lb.attach(streams, n); +} + +/// Whether a request's caches could start now (the lane host's admission, on its engine thread). +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const own: *const Owned = @ptrCast(@alignCast(p)); + return own.lb.admits(prompt, max_tokens); +} + /// The attention layers the kernels' page arena holds: the admitted 10 of 40 (conv the rest). fn checkLayers(config: *const cfg.Config) !void { var n: usize = 0; @@ -77,16 +104,17 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer own.w.deinit(); try checkLayers(&own.w.config); const context = @min(mdl.Model.positions(o.context), own.w.config.context); - const plan: Plan = .{ .own = own, .d = ctx.d, .context = context }; + const paged = pagesOn(); + const plan: Plan = .{ .own = own, .d = ctx.d, .context = context, .paged = paged }; const room: u64 = if (o.room) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); - const n = fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { + const n = if (paged) try fitFirst(room, plan) else fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { if (e == error.ParallelPastMemory) { const most = fit(room, o.lanes, false, plan) catch 0; std.log.err("--parallel {d} needs {d:.2} GiB at a {d}-token window and the CUDA memory budget leaves {d:.2} GiB after the weights: {d} stream{s} fit", .{ o.lanes, gib(try plan.bytes(o.lanes)), context, gib(room), most, if (most == 1) "" else "s" }); } return e; }; - own.m = try mdl.Model.init(gpa, ctx.d, own.s, &own.w, context, n); + own.m = try mdl.Model.init(gpa, ctx.d, own.s, &own.w, context, n, paged); errdefer own.m.deinit(); own.lb = try be.Lfm.init(gpa, ctx.d, &own.m, &own.k, own.s); errdefer own.lb.deinit(); @@ -99,9 +127,16 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .ctx = own, .deinit = release, .target = &own.lb, + .layout = if (paged) own.m.layout() else null, }; } +/// Paged: the first stream's states and the scratch must fit; the host plans the pool after. +fn fitFirst(room: u64, plan: anytype) !usize { + if (try plan.bytes(1) > room) return error.NoStreamFits; + return 1; +} + fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } From 5c2da9a68682a4ffc9d2644e37d1bbfa021ae799 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:57:19 +0100 Subject: [PATCH 49/59] lfm2_moe: the prompt cache on CUDA, a kept state the conv states and the pages' rows through its position A state at `at` is the slot's conv states and its keys and values at positions [0, at) of the ten attention layers: one copy a run of consecutive whole pages, then the last page's rows a layer's keys and values. It is copied behind the chunk that ends at the mark and restored into the new stream's leased pages before its next chunk, so a later turn's pass starts at its history. Lookahead 0, as the other headless families. States live in 2 MiB snapshot pages allocated once at startup inside the prompt-cache budget (`snap_ready`), as GLM's: a keep or a restore leases or reads pages and allocates nothing, and a dropped state's pages go back to the pool at once (every copy that reads or writes them is queued on the backend's one stream). The store counts held and spare pages through `snap_charged` / `snap_spare` / `snap_reuses`. --- docs/profiles.md | 3 +- zig/src/core/profile.zig | 2 +- zig/src/families/lfm2_moe/cuda_backend.zig | 50 ++++- zig/src/families/lfm2_moe/cuda_family.zig | 2 + zig/src/families/lfm2_moe/cuda_native.zig | 53 +++++- zig/src/families/lfm2_moe/cuda_snap.zig | 209 +++++++++++++++++++++ zig/src/native/cuda_kv_pool.zig | 15 +- 7 files changed, 324 insertions(+), 10 deletions(-) create mode 100644 zig/src/families/lfm2_moe/cuda_snap.zig diff --git a/docs/profiles.md b/docs/profiles.md index 64f6d5ebbd8..3549677fd7b 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -51,7 +51,8 @@ Coverage includes: with `TENSORFOLD_DORY_KV_PAGES=0` it refuses to load, by both names. With the switch unset, the startup line shows `TENSORFOLD_DORY_KV_PAGES=1 (arithmetic, TF_KV_SHARE)` and kept states carry the same identity as `=1`. - Every CUDA family whose host prompt cache the CUDA host builds (Nemotron, Nemotron Omni, GLM, MiniMax M3, Qwen3.5 - dense/MoE, Flash Next, Kolibri-1, Gemma 4, Spark2.5, Dory): `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS`, exact `1` only. + dense/MoE, Flash Next, Kolibri-1, Gemma 4, Spark2.5, Dory, LFM2.5-24B-A2B): `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS`, + exact `1` only. - Flash Next on CUDA: `TF_FLASHNEXT_KV_PAGES`, `TF_FLASHNEXT_KV_PAGES_ALL`. - Dory on CUDA: `TENSORFOLD_DORY_KV_PAGES`, full-attention caches in pool pages unless it is exactly `0`; unset, every stream's caches are contiguous and made at open. diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index a1cf975eeb0..a38ee629ad4 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -137,7 +137,7 @@ const nemotron: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni" }; const slide_cuda: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "qwen3_5" }; const flash: []const []const u8 = &.{"qwen4_exp"}; /// The CUDA families whose host prompt cache the generic CUDA host builds (cuda_keep_others_test.zig checks the list). -pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory" }; +pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe" }; pub const entries = [_]Entry{ .{ .id = .TF_QWEN_REQUEST_STARTS, .families = qwen, .class = .arithmetic, .syntax = .one, .effect = "Opt into CUDA message-start prompt cuts", .evidence = "#1334; default-off; GB10 six-turn: resumed equals fresh, one reply differs from unset" }, diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig index 5199cdf6a9e..5d2a402df60 100644 --- a/zig/src/families/lfm2_moe/cuda_backend.zig +++ b/zig/src/families/lfm2_moe/cuda_backend.zig @@ -7,6 +7,7 @@ const fwd = @import("cuda_forward.zig"); const mdl = @import("cuda_model.zig"); const kern = @import("cuda_kernels.zig"); const kv = @import("core").kv_pool; +const snap = @import("cuda_snap.zig"); const be = lanes.backend; const Stream = lanes.Stream; @@ -54,6 +55,7 @@ pub const Lfm = struct { slot_bufs: []cuda.DeviceBuffer, // a slot's last-row logits, then its rule: two a slot next: u64 = 0, pool: ?kv.Pool = null, // the pages every slot leases (attach) + snaps: ?snap.Pages = null, // the prompt cache's pages, allocated once inside its budget (snap_ready) /// The device bytes `init` allocates: the token and pick rings, metas, each slot's last row and rule. pub fn openBytes(slots: usize) usize { @@ -97,6 +99,7 @@ pub const Lfm = struct { l.rows.deinit(x.gpa); } if (x.pool) |*p| p.deinit(); + if (x.snaps) |*p| p.deinit(); x.lanes.deinit(x.gpa); for (x.slot_bufs) |*b| b.free(); x.gpa.free(x.slot_bufs); @@ -150,6 +153,30 @@ pub const Lfm = struct { }; } + /// The stream's state at `at` for the prompt cache, copied behind the chunk that ends there. + pub fn saveState(x: *Lfm, owner: ?*anyopaque, at: u32) !*snap.Saved { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + if ((l.fill orelse l.len) != at) return error.NotAtMark; // a state is copied only where the pass stands + return snap.save(x.gpa, try x.snapPages(), x.m, x.s, l.slot, at); + } + + /// The stream's slot made to hold `k`'s state (a restore outside its prompt pass). + pub fn restoreState(x: *Lfm, owner: ?*anyopaque, k: *const snap.Saved) !void { + const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + try snap.restore(try x.snapPages(), x.m, x.s, l.slot, k); + l.len = k.at; + } + + pub fn dropState(x: *Lfm, k: *snap.Saved) void { + snap.drop(x.gpa, &x.snaps.?, k); + } + + fn snapPages(x: *Lfm) !*snap.Pages { + return if (x.snaps) |*p| p else error.NoSnapshotCache; + } + fn freeSlot(x: *const Lfm) ?usize { return std.mem.indexOfScalar(bool, x.free[0..x.m.slots], true); } @@ -210,13 +237,32 @@ pub const Lfm = struct { l.sampled = true; }; s.cached = 0; - if (s.reuse.saved != null) s.reuse_failed = true; // no prompt cache: every pass starts at 0 try x.m.clearSlot(x.s, l.slot); - l.fill = 0; + l.fill = x.resumeAt(s, l, p.len); s.fill_at.store(@intCast(l.fill.?), .monotonic); return l; } + /// The kept state's position, restored into the slot (0: none, or not this prompt's). + fn resumeAt(x: *Lfm, s: *Stream, l: *const Lane, len: usize) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const snap.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= len) { + s.reuse_failed = true; + return 0; + } + const p = x.snapPages() catch { + s.reuse_failed = true; + return 0; + }; + snap.restore(p, x.m, x.s, l.slot, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + /// One chunk from `l.fill` to the next grid line or mark; true once the prompt's last row's logits are written. fn chunk(x: *Lfm, s: *Stream, l: *Lane) !bool { const p = s.prompt(); diff --git a/zig/src/families/lfm2_moe/cuda_family.zig b/zig/src/families/lfm2_moe/cuda_family.zig index a938da0d0eb..50263f9d8af 100644 --- a/zig/src/families/lfm2_moe/cuda_family.zig +++ b/zig/src/families/lfm2_moe/cuda_family.zig @@ -6,6 +6,7 @@ pub const model = @import("cuda_model.zig"); pub const forward = @import("cuda_forward.zig"); pub const backend = @import("cuda_backend.zig"); pub const native = @import("cuda_native.zig"); +pub const snap = @import("cuda_snap.zig"); test { _ = config; @@ -15,4 +16,5 @@ test { _ = forward; _ = backend; _ = native; + _ = snap; } diff --git a/zig/src/families/lfm2_moe/cuda_native.zig b/zig/src/families/lfm2_moe/cuda_native.zig index 605e1e92f2e..ab288466974 100644 --- a/zig/src/families/lfm2_moe/cuda_native.zig +++ b/zig/src/families/lfm2_moe/cuda_native.zig @@ -1,4 +1,4 @@ -//! LFM2.5-24B-A2B (MLX affine 4-bit) behind the native CUDA registry: plain and copy-drafted decoding, no prompt cache. +//! LFM2.5-24B-A2B (MLX affine 4-bit) behind the native CUDA registry: plain and copy-drafted decoding, prompt reuse. const std = @import("std"); const cuda = @import("cuda"); const lanes = @import("lanes"); @@ -7,6 +7,7 @@ const wts = @import("cuda_weights.zig"); const kern = @import("cuda_kernels.zig"); const mdl = @import("cuda_model.zig"); const be = @import("cuda_backend.zig"); +const snap = @import("cuda_snap.zig"); const kv = @import("core").kv_pool; pub const model_type = "lfm2_moe"; @@ -14,6 +15,7 @@ pub const formats: []const []const u8 = &.{"mlx-q4g64"}; pub const default_context: i64 = 32768; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; +/// A kept state is the caches through its position and nothing past it (no draft head reads a token on). pub const snap_lookahead: u32 = 0; /// A request's last verify window: its pages hold that many rows past its prompt and reply. pub const window_rows: u32 = be.max_window; @@ -141,6 +143,49 @@ fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } +fn lfm(ptr: *anyopaque) *be.Lfm { + return @ptrCast(@alignCast(ptr)); +} + +/// Bytes a state at `at` prompt tokens takes: whole snapshot pages. +pub fn snap_bytes(_: *anyopaque, at: u32) u64 { + return snap.bytes(at); +} + +/// The cache's pages, allocated once before any request: the store counts held and spare pages through the hooks below. +pub fn snap_ready(ptr: *anyopaque, budget: u64) !u64 { + const x = lfm(ptr); + if (x.snaps != null) return error.SnapshotCacheMade; + x.snaps = try snap.Pages.init(x.gpa, x.d, budget); + return 0; +} + +pub fn snap_charged(_: *anyopaque, saved: *anyopaque) u64 { + const k: *const snap.Saved = @ptrCast(@alignCast(saved)); + return k.lease.ids.items.len * snap.page; +} + +pub fn snap_spare(ptr: *anyopaque) u64 { + return if (lfm(ptr).snaps) |*p| p.spare() else 0; +} + +pub fn snap_reuses(ptr: *anyopaque, at: u32) bool { + return snap_spare(ptr) >= snap.bytes(at); +} + +/// The prompt pass stands at `at` (a chunk end or a mark): copy the stream's caches there. +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try lfm(ptr).saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return lfm(ptr).restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + lfm(ptr).dropState(@ptrCast(@alignCast(saved))); +} + pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { error.PastContext => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", @@ -182,3 +227,9 @@ test "the admitted layer pattern has the arena's ten attention layers" { config.attention[0] = true; try std.testing.expectError(error.UnsupportedLfmGeometry, checkLayers(&config)); } + +test "the prompt cache's hooks compile against the store's vtable" { + const pc: struct { bytes: *const fn (*anyopaque, u32) u64, save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, drop: *const fn (*anyopaque, *anyopaque) void } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; + try std.testing.expect(@intFromPtr(pc.save) != 0); + try std.testing.expectEqual(snap.bytes(100), snap_bytes(undefined, 100)); +} diff --git a/zig/src/families/lfm2_moe/cuda_snap.zig b/zig/src/families/lfm2_moe/cuda_snap.zig new file mode 100644 index 00000000000..a3a9f41fa61 --- /dev/null +++ b/zig/src/families/lfm2_moe/cuda_snap.zig @@ -0,0 +1,209 @@ +//! A stream's kept state (conv states, K/V [0, at)) in pages allocated once in the prompt-cache budget, as GLM's. +const std = @import("std"); +const cuda = @import("cuda"); +const kv = @import("core").kv_pool; +const mdl = @import("cuda_model.zig"); +const kern = @import("cuda_kernels.zig"); + +/// A kept state: its position and the snapshot pages that hold it, in order. +pub const Saved = struct { at: u32, lease: kv.Lease }; + +const page_bytes = mdl.page_elems * 2; +const row_bytes = mdl.kv_width * 2; +const state_bytes = mdl.slot_elems * 2; + +/// A snapshot page: the unit the budget is cut into. +pub const page: usize = 2 << 20; + +/// Bytes a state at `at` holds: whole snapshot pages. +pub fn bytes(at: usize) u64 { + const n = state_bytes + at * (page_bytes / kern.page); + return (n + page - 1) / page * page; +} + +/// The budget's pages, allocated once; states lease them and give them back. +pub const Pages = struct { + pages: kv.Pool, + arena: ?cuda.DeviceBuffer, + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, budget: u64) !Pages { + const count = std.math.cast(u32, budget / page) orelse return error.SnapshotBudget; + var pages = try kv.Pool.init(gpa, count, page); + errdefer pages.deinit(); + return .{ .pages = pages, .arena = if (count > 0) try cuda.DeviceBuffer.alloc(d, @as(usize, count) * page) else null }; + } + + pub fn deinit(p: *Pages) void { + if (p.arena) |*a| a.free(); + p.pages.deinit(); + } + + /// Bytes of pages no state holds. + pub fn spare(p: *const Pages) u64 { + return p.pages.available() * page; + } + + fn take(p: *Pages, n: usize) !kv.Lease { + if (n == 0 or n > p.pages.available() or p.arena == null) return error.NoSnapshotRoom; + var lease: kv.Lease = .{}; + errdefer p.pages.finish(&lease); + try p.pages.promise(&lease, n); + try p.pages.cover(&lease, n, null); + return lease; + } +}; + +/// `slot`'s state at `at`, region by region: one copy a run of consecutive whole pages, a layer's rows of the last. +fn each(m: *const mdl.Model, slot: usize, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { + if (at > m.caps[slot]) return error.PastPages; + try f(ctx, m.states + slot * state_bytes, 0, state_bytes); + var off: usize = state_bytes; + const ids = m.ids[slot * m.perSlot() ..]; + const whole = at / kern.page; + var q: usize = 0; + while (q < whole) { + var n: usize = 1; + while (q + n < whole and ids[q + n] == ids[q] + n) n += 1; + try f(ctx, m.arena + @as(u64, ids[q]) * page_bytes, off, n * page_bytes); + off += n * page_bytes; + q += n; + } + const rows = at % kern.page; + if (rows == 0) return; + const last = m.arena + @as(u64, ids[whole]) * page_bytes; + for (0..2 * mdl.attention_layers) |i| { // layer a's keys at block 2a, its values at 2a + 1 + try f(ctx, last + i * kern.page * row_bytes, off, rows * row_bytes); + off += rows * row_bytes; + } +} + +/// Region bytes [off, off + len) over a state's pages: (arena offset, region offset, length), a run of consecutive ids. +fn pageRuns(ids: []const u32, off: usize, len: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), held: u64, done: usize, n: usize) anyerror!void) !void { + var done: usize = 0; + while (done < len) { + const at = off + done; + var q = at / page; + var n = @min(len - done, page - at % page); + while (done + n < len and ids[q + 1] == ids[q] + 1) : (q += 1) n = @min(len - done, n + page); + try f(ctx, @as(u64, ids[at / page]) * page + at % page, done, n); + done += n; + } +} + +/// Copies between a slot's region at `dev` and a lease's pages. +const Copy = struct { d: *const cuda.Driver, s: cuda.Stream, arena: u64, dev: u64, out: bool }; + +fn copyRun(c: Copy, held: u64, done: usize, n: usize) anyerror!void { + const src = if (c.out) c.dev + done else c.arena + held; + const dst = if (c.out) c.arena + held else c.dev + done; + try c.d.check(c.d.api.cuMemcpyDtoDAsync_v2(dst, src, n, c.s.handle), "cuMemcpyDtoDAsync"); +} + +const Leased = struct { d: *const cuda.Driver, s: cuda.Stream, arena: u64, ids: []const u32, out: bool }; + +fn copy(c: Leased, dev: u64, off: usize, len: usize) anyerror!void { + try pageRuns(c.ids, off, len, Copy{ .d = c.d, .s = c.s, .arena = c.arena, .dev = dev, .out = c.out }, copyRun); +} + +/// Copy `slot`'s state at `at` into leased pages, queued on `s` behind the chunk that ends there. +pub fn save(gpa: std.mem.Allocator, p: *Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const k = try gpa.create(Saved); + errdefer gpa.destroy(k); + k.* = .{ .at = at, .lease = try p.take(bytes(at) / page) }; + errdefer p.pages.finish(&k.lease); + try each(m, slot, at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = true }, copy); + return k; +} + +/// Make `slot`'s pages and conv states hold `k`'s state, queued on `s` before the next chunk. +pub fn restore(p: *const Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, k: *const Saved) !void { + if (k.at > m.context) return error.PastContext; + try each(m, slot, k.at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = false }, copy); +} + +/// Give a state's pages back: every copy that reads or writes them is queued on the one stream, ahead of any later one. +pub fn drop(gpa: std.mem.Allocator, p: *Pages, k: *Saved) void { + p.pages.finish(&k.lease); + gpa.destroy(k); +} + +const testing = std.testing; + +const Count = struct { + runs: *std.ArrayList([3]usize), + fn add(c: Count, dev: u64, off: usize, len: usize) anyerror!void { + try c.runs.append(testing.allocator, .{ dev, off, len }); + } +}; + +fn fake(ids: []u32, caps: []usize) mdl.Model { + var m: mdl.Model = undefined; + m.context = 4 * kern.page; + m.slots = caps.len; + m.arena = 1 << 40; + m.states = 1 << 36; + m.ids = ids; + m.caps = caps; + return m; +} + +test "a state: the conv states, consecutive whole pages as one copy, the last page's rows a layer's K and V" { + // slot 1 leases pages 7, 8, 3, 9: positions 0..1023 one run, 1024..1535 a page, 1536.. a partial page + var ids = [_]u32{ 0, 0, 0, 0, 7, 8, 3, 9 }; + var caps = [_]usize{ 0, 4 * kern.page }; + const m = fake(&ids, &caps); + const at = 3 * kern.page + 100; + var runs: std.ArrayList([3]usize) = .empty; + defer runs.deinit(testing.allocator); + try each(&m, 1, at, Count{ .runs = &runs }, Count.add); + try testing.expectEqual(@as(usize, 1 + 2 + 20), runs.items.len); + try testing.expectEqual([3]usize{ (1 << 36) + state_bytes, 0, state_bytes }, runs.items[0]); + try testing.expectEqual([3]usize{ (1 << 40) + 7 * page_bytes, state_bytes, 2 * page_bytes }, runs.items[1]); + try testing.expectEqual([3]usize{ (1 << 40) + 3 * page_bytes, state_bytes + 2 * page_bytes, page_bytes }, runs.items[2]); + const v9 = (1 << 40) + 9 * page_bytes + kern.page * row_bytes; // page 9, layer 0's values + try testing.expectEqual([3]usize{ v9, state_bytes + 3 * page_bytes + 100 * row_bytes, 100 * row_bytes }, runs.items[4]); + var total: usize = 0; + for (runs.items) |r| total += r[2]; + try testing.expectEqual(state_bytes + at * 20 * 1024, total); + try testing.expectEqual((total + page - 1) / page * page, bytes(at)); +} + +test "a state on whole pages has no partial copies; one past a slot's pages is refused" { + var ids = [_]u32{ 4, 5, 6, 7 }; + var caps = [_]usize{2 * kern.page}; + const m = fake(&ids, &caps); + var runs: std.ArrayList([3]usize) = .empty; + defer runs.deinit(testing.allocator); + try each(&m, 0, 2 * kern.page, Count{ .runs = &runs }, Count.add); + try testing.expectEqual(@as(usize, 2), runs.items.len); + try testing.expectEqual(@as(usize, 2 * page_bytes), runs.items[1][2]); + try testing.expectError(error.PastPages, each(&m, 0, 2 * kern.page + 1, Count{ .runs = &runs }, Count.add)); +} + +const Run = struct { + out: *std.ArrayList([3]usize), + fn add(r: Run, held: u64, done: usize, n: usize) anyerror!void { + try r.out.append(testing.allocator, .{ held, done, n }); + } +}; + +test "a region over snapshot pages: one copy a run of consecutive ids, split where the ids jump" { + const ids = [_]u32{ 4, 5, 9, 10, 11, 2 }; + var out: std.ArrayList([3]usize) = .empty; + defer out.deinit(testing.allocator); + // bytes [page / 2, 5 page + 10): pages 4-5 (from mid-page), 9-11, then 2 + try pageRuns(&ids, page / 2, 4 * page + page / 2 + 10, Run{ .out = &out }, Run.add); + try testing.expectEqual(@as(usize, 3), out.items.len); + try testing.expectEqual([3]usize{ 4 * page + page / 2, 0, page + page / 2 }, out.items[0]); + try testing.expectEqual([3]usize{ 9 * page, page + page / 2, 3 * page }, out.items[1]); + try testing.expectEqual([3]usize{ 2 * page, 4 * page + page / 2, 10 }, out.items[2]); + out.clearRetainingCapacity(); + try pageRuns(&ids, 3 * page + 7, 100, Run{ .out = &out }, Run.add); // inside one page + try testing.expectEqual([3]usize{ 10 * page + 7, 0, 100 }, out.items[0]); +} + +test "a state's pages: whole snapshot pages, the budget's pages leased and given back" { + try testing.expectEqual(@as(u64, page), bytes(1)); + try testing.expect(bytes(10_000) >= state_bytes + 10_000 * 20 * 1024 and bytes(10_000) % page == 0); +} diff --git a/zig/src/native/cuda_kv_pool.zig b/zig/src/native/cuda_kv_pool.zig index 5f0b16318e7..985f183ae30 100644 --- a/zig/src/native/cuda_kv_pool.zig +++ b/zig/src/native/cuda_kv_pool.zig @@ -575,15 +575,20 @@ test "kv pages: a family that keeps no prompts plans no cache, so its streams ta try std.testing.expect(fits(Promptless, loaded, o, 3 << 29, 8192, 0) and !fits(struct {}, loaded, o, 3 << 29, 8192, 0)); } } -test "kv pages: LFM2-MoE declares neither keeps_no_prompts nor snap_save and plans its default cache as before" { +test "kv pages: LFM2-MoE keeps prompts without snapshot slots: its default cache plans as before, and the store holds what the plan set aside" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var problem: []const u8 = ""; const lfm = @import("lfm2_moe_cuda").native; - try std.testing.expect(!keepsNoPrompts(lfm) and !@hasDecl(lfm, "snap_save") and keepsNoPrompts(Promptless)); + try std.testing.expect(!keepsNoPrompts(lfm) and @hasDecl(lfm, "snap_save") and !@hasDecl(lfm, "snap_slots") and keepsNoPrompts(Promptless)); const l: kv_pool.Layout = .{ .fixed_bytes = 180 << 20, .token_bytes = 13_056, .page_tokens = 512, .snap_bytes = 0 }; const o: api.Open = .{ .dir = "", .model_type = "lfm2_moe", .lanes = 8 }; - // as a family that declares neither: main's default cache, scaled by the room the streams leave - try std.testing.expectEqual(try kv_pool.plan(l, budgetOf(struct {}, l, 3 << 29, o, 8192, false, false, 0, null)), (try plan(lfm, arena.allocator(), l, 3 << 29, o, 8192, &problem, false, false, 0, null)).?); - try std.testing.expectEqual(@as(u64, 0), kept(lfm, .{}, null, o, 40 << 30, 0, 0, false).copied); // no store either way + // as any family that keeps prompts: main's default cache, scaled by the room the streams leave + const p = (try plan(lfm, arena.allocator(), l, 3 << 29, o, 8192, &problem, false, false, 0, null)).?; + try std.testing.expectEqual(try kv_pool.plan(l, budgetOf(struct {}, l, 3 << 29, o, 8192, false, false, 0, null)), p); + // on pages the store holds the plan's budget as pool pages; on fixed pages (TENSORFOLD_LFM2_KV_PAGES=0) the room's + const q = (try plan(lfm, arena.allocator(), l, 40 << 30, o, 8192, &problem, false, false, 0, null)).?; + try std.testing.expect(q.copied + q.kept > 0); + try std.testing.expectEqual(q.copied + q.kept, kept(lfm, .{}, q, o, 40 << 30, 0, 0, false).copied); + try std.testing.expectEqual(budget.cacheBytes(null, 40 << 30, 0), kept(lfm, .{}, null, o, 40 << 30, 0, 0, false).copied); } From aaceda4e08d730c4a306d56abef85200d028cea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:35:40 +0100 Subject: [PATCH 50/59] lfm2_moe: keep a mark's state as the prompt pass goes by, so a keep adds no pass A chat mark inside a prompt chunk ended the chunk there, and every extra prompt pass reads the weights once more: a cold 10k chat turn, whose two marks sit in its last chunk, ran 12 passes instead of 10. Now up to four marks inside a chunk are tapped instead: the conv kernel runs once more on each mark's last row alone, writing the same y and that row's conv states into the model's tap buffer, and the keep copies those states with the K/V rows before the mark. The pass goes on to its grid line; a fifth mark still ends it. The kernel is unchanged. --- zig/src/families/lfm2_moe/cuda_backend.zig | 77 ++++++++++++++++++---- zig/src/families/lfm2_moe/cuda_forward.zig | 10 ++- zig/src/families/lfm2_moe/cuda_model.zig | 4 ++ zig/src/families/lfm2_moe/cuda_snap.zig | 20 +++--- 4 files changed, 88 insertions(+), 23 deletions(-) diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig index 5d2a402df60..2ded108337e 100644 --- a/zig/src/families/lfm2_moe/cuda_backend.zig +++ b/zig/src/families/lfm2_moe/cuda_backend.zig @@ -55,6 +55,7 @@ pub const Lfm = struct { slot_bufs: []cuda.DeviceBuffer, // a slot's last-row logits, then its rule: two a slot next: u64 = 0, pool: ?kv.Pool = null, // the pages every slot leases (attach) + tapped: ?struct { stream: *const Stream, cut: Cut } = null, // the chunk's tapped marks while its hooks run snaps: ?snap.Pages = null, // the prompt cache's pages, allocated once inside its budget (snap_ready) /// The device bytes `init` allocates: the token and pick rings, metas, each slot's last row and rule. @@ -157,8 +158,10 @@ pub const Lfm = struct { pub fn saveState(x: *Lfm, owner: ?*anyopaque, at: u32) !*snap.Saved { const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); const l = x.lanes.getPtr(s) orelse return error.UnknownStream; - if ((l.fill orelse l.len) != at) return error.NotAtMark; // a state is copied only where the pass stands - return snap.save(x.gpa, try x.snapPages(), x.m, x.s, l.slot, at); + const tap: ?usize = if (x.tapped) |t| if (t.stream == s) std.mem.indexOfScalar(usize, t.cut.taps(), at) else null else null; + if (tap == null and (l.fill orelse l.len) != at) return error.NotAtMark; // where the pass stands, or a tap + const conv = if (tap) |j| x.m.s.tap + j * mdl.slot_elems * 2 else x.m.states + l.slot * mdl.slot_elems * 2; + return snap.save(x.gpa, try x.snapPages(), x.m, x.s, l.slot, at, conv); } /// The stream's slot made to hold `k`'s state (a restore outside its prompt pass). @@ -268,20 +271,55 @@ pub const Lfm = struct { const p = s.prompt(); const at = l.fill.?; if (s.isCancelled()) return error.Cancelled; - var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); - for (s.reuse.marks) |mk| if (mk > at and mk < end) { - end = mk; - }; - const done = end == p.len; - try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }}, true, end - at - 1, @intFromBool(done)); + const c = cut(at, p.len, s.reuse.marks); + const done = c.end == p.len; + var rows: [mdl.max_taps]usize = undefined; + for (c.taps(), 0..) |t, j| rows[j] = t - at - 1; + try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..c.end], .taps = rows[0..c.n] }}, true, c.end - at - 1, @intFromBool(done)); if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, cfg.vocab * 2, x.s.handle), "cuMemcpyDtoDAsync"); - s.fill_at.store(@intCast(end), .monotonic); - l.fill = if (done) null else end; + s.fill_at.store(@intCast(c.end), .monotonic); + l.fill = if (done) null else c.end; if (done) l.len = p.len; - if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); + if (s.reuse.hook) |hk| { + x.tapped = .{ .stream = s, .cut = c }; + defer x.tapped = null; + for (c.taps()) |t| hk.at(hk.ptr, s, @intCast(t)); + if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(c.end)) != null) hk.at(hk.ptr, s, @intCast(c.end)); + } return done; } + /// A chunk's end (the grid line, the prompt's end or a mark) and the marks inside it, tapped in order. + const Cut = struct { + end: usize, + at: [mdl.max_taps]usize = undefined, + n: usize = 0, + fn taps(c: *const Cut) []const usize { + return c.at[0..c.n]; + } + }; + + /// The chunk from `at`: up to max_taps marks inside it are tapped, the next one ends it. + fn cut(at: usize, len: usize, marks: []const u32) Cut { + var c: Cut = .{ .end = @min(len, (at / prompt_rows + 1) * prompt_rows) }; + var from = at; + while (true) { // the marks inside in order, the first max_taps tapped + var next: ?usize = null; + for (marks) |mk| if (mk > from and mk < c.end and (next == null or mk < next.?)) { + next = mk; + }; + const mk = next orelse break; + if (c.n == mdl.max_taps) { + c.end = mk; + break; + } + c.at[c.n] = mk; + c.n += 1; + from = mk; + } + return c; + } + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { const x = self(ptr); const l = try x.opening(s); @@ -434,3 +472,20 @@ test "a request holds its prompt, its reply and one verify window in whole pages try std.testing.expectEqual(@as(usize, 2), pagesFor(400, 97)); try std.testing.expectEqual(@as(usize, 65), pagesFor(32768, 0)); } + +test "a chunk taps the marks inside it, up to four, and ends at the next one, the grid line or the prompt's end" { + const cases = [_]struct { at: usize, len: usize, marks: []const u32, end: usize, taps: []const usize }{ + .{ .at = 0, .len = 3000, .marks = &.{}, .end = prompt_rows, .taps = &.{} }, + .{ .at = 0, .len = 3000, .marks = &.{700}, .end = prompt_rows, .taps = &.{700} }, + .{ .at = 0, .len = 3000, .marks = &.{ 900, 300, 2900 }, .end = prompt_rows, .taps = &.{ 300, 900 } }, + .{ .at = 0, .len = 3000, .marks = &.{ 5, 4, 3, 2, 1 }, .end = 5, .taps = &.{ 1, 2, 3, 4 } }, + .{ .at = 9216, .len = 10144, .marks = &.{ 10050, 10140 }, .end = 10144, .taps = &.{ 10050, 10140 } }, + .{ .at = 2048, .len = 2500, .marks = &.{ 2100, 2500 }, .end = 2500, .taps = &.{2100} }, + .{ .at = 700, .len = 3000, .marks = &.{700}, .end = prompt_rows, .taps = &.{} }, + }; + for (cases) |k| { + const c = Lfm.cut(k.at, k.len, k.marks); + try std.testing.expectEqual(k.end, c.end); + try std.testing.expectEqualSlices(usize, k.taps, c.taps()); + } +} diff --git a/zig/src/families/lfm2_moe/cuda_forward.zig b/zig/src/families/lfm2_moe/cuda_forward.zig index 723d2944536..6694da56a73 100644 --- a/zig/src/families/lfm2_moe/cuda_forward.zig +++ b/zig/src/families/lfm2_moe/cuda_forward.zig @@ -11,8 +11,8 @@ const Kernels = kern.Kernels; const Stream = cuda.Stream; const tail: cuda.norms.Tail = .{ .round = true }; // the norms' torch points: bf16(w * bf16(h * inv)) -/// A stream's rows in one forward: its slot, first position, tokens. -pub const Chain = struct { slot: usize, p0: usize, tokens: []const u32 }; +/// A stream's rows in one forward: its slot, first position, tokens; a prompt chunk's tap rows keep their conv states. +pub const Chain = struct { slot: usize, p0: usize, tokens: []const u32, taps: []const usize = &.{} }; const Pass = struct { m: *const Model, @@ -65,6 +65,10 @@ const Pass = struct { // a prompt chunk keeps its last row's state, a round each row's (a window keeps any prefix of its rows) const snap0: usize = if (p.prompt) p.rows - 1 else 0; try p.k.convRows(p.s, x.wide, cv.weight, state, mdl.slot_elems, x.slot, x.off, x.y, snaps, snap0, p.rows); + if (p.prompt) for (p.chains[0].taps, 0..) |r, j| { // the kernel again on row r: the same y, its states in tap j + const tap = x.tap + (j * mdl.slot_elems + index * 2 * c.hidden) * 2; + try p.k.convRows(p.s, x.wide + r * 3 * c.hidden * 2, cv.weight, state, mdl.slot_elems, x.slot + r * 4, x.off + r * 4, x.y + r * c.hidden * 2, tap, 0, 1); + }; try p.sums(x.y, c.hidden); try p.project(cv.out, x.y, x.xs, x.r, p.rows, p.prompt); } @@ -149,6 +153,8 @@ pub fn forward(m: *const Model, k: *const Kernels, s: Stream, chains: []const Ch for (chains) |ch| { if (ch.tokens.len == 0 or ch.slot >= m.slots or ch.p0 + ch.tokens.len > m.context) return error.BadChain; if (ch.p0 + ch.tokens.len > m.caps[ch.slot]) return error.PastPages; + if (ch.taps.len > 0 and (!prompt or ch.taps.len > mdl.max_taps)) return error.BadChain; + for (ch.taps) |r| if (r >= ch.tokens.len) return error.BadChain; rows += ch.tokens.len; } if (rows > @as(usize, if (prompt) mdl.prompt_rows else mdl.round_rows) or (prompt and chains.len != 1)) return error.BadWindow; diff --git a/zig/src/families/lfm2_moe/cuda_model.zig b/zig/src/families/lfm2_moe/cuda_model.zig index 7d4b6364559..c0b487505a9 100644 --- a/zig/src/families/lfm2_moe/cuda_model.zig +++ b/zig/src/families/lfm2_moe/cuda_model.zig @@ -20,6 +20,8 @@ pub const kv_width = c.kv_heads * c.head_dim; pub const page_elems = attention_layers * 2 * kern.page * kv_width; /// Elements a slot's conv states hold: two bx rows a conv layer. pub const slot_elems = conv_layers * 2 * c.hidden; +/// Marks a prompt chunk taps (their conv states kept as the pass goes by); one more ends the chunk. +pub const max_taps = 4; /// Key chunks one attention launch walks in parallel at most (nemotron's chunk_blocks). const chunk_blocks = 64; @@ -52,6 +54,7 @@ pub const Scratch = struct { pm: u64, pl: u64, snaps: u64, // bf16 [conv_layers][round_rows][2][hidden]: each window row's conv state after it + tap: u64, // bf16 [max_taps][conv_layers][2][hidden]: the conv states after a chunk's tapped rows (a slot's layout) logits: u64, // bf16 [round_rows, vocab] }; @@ -238,6 +241,7 @@ pub const Model = struct { .pm = try m.alloc(parts * 4), .pl = try m.alloc(parts * 4), .snaps = try m.alloc(conv_layers * round_rows * 2 * h * 2), + .tap = try m.alloc(max_taps * slot_elems * 2), .logits = try m.alloc(round_rows * c.vocab * 2), }; if (m.planned != null) return; diff --git a/zig/src/families/lfm2_moe/cuda_snap.zig b/zig/src/families/lfm2_moe/cuda_snap.zig index a3a9f41fa61..965546d10df 100644 --- a/zig/src/families/lfm2_moe/cuda_snap.zig +++ b/zig/src/families/lfm2_moe/cuda_snap.zig @@ -53,10 +53,10 @@ pub const Pages = struct { } }; -/// `slot`'s state at `at`, region by region: one copy a run of consecutive whole pages, a layer's rows of the last. -fn each(m: *const mdl.Model, slot: usize, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { +/// `slot`'s state at `at`: conv states (from `conv`), a copy a run of consecutive whole pages, the last's rows a layer. +fn each(m: *const mdl.Model, slot: usize, conv: u64, at: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), dev: u64, off: usize, len: usize) anyerror!void) !void { if (at > m.caps[slot]) return error.PastPages; - try f(ctx, m.states + slot * state_bytes, 0, state_bytes); + try f(ctx, conv, 0, state_bytes); var off: usize = state_bytes; const ids = m.ids[slot * m.perSlot() ..]; const whole = at / kern.page; @@ -105,21 +105,21 @@ fn copy(c: Leased, dev: u64, off: usize, len: usize) anyerror!void { try pageRuns(c.ids, off, len, Copy{ .d = c.d, .s = c.s, .arena = c.arena, .dev = dev, .out = c.out }, copyRun); } -/// Copy `slot`'s state at `at` into leased pages, queued on `s` behind the chunk that ends there. -pub fn save(gpa: std.mem.Allocator, p: *Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, at: u32) !*Saved { +/// `slot`'s state at `at` copied into leased pages behind the chunk that ends there or taps it (conv states at `conv`). +pub fn save(gpa: std.mem.Allocator, p: *Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, at: u32, conv: u64) !*Saved { if (at == 0 or at > m.context) return error.NotAtMark; const k = try gpa.create(Saved); errdefer gpa.destroy(k); k.* = .{ .at = at, .lease = try p.take(bytes(at) / page) }; errdefer p.pages.finish(&k.lease); - try each(m, slot, at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = true }, copy); + try each(m, slot, conv, at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = true }, copy); return k; } /// Make `slot`'s pages and conv states hold `k`'s state, queued on `s` before the next chunk. pub fn restore(p: *const Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, k: *const Saved) !void { if (k.at > m.context) return error.PastContext; - try each(m, slot, k.at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = false }, copy); + try each(m, slot, m.states + slot * state_bytes, k.at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = false }, copy); } /// Give a state's pages back: every copy that reads or writes them is queued on the one stream, ahead of any later one. @@ -156,7 +156,7 @@ test "a state: the conv states, consecutive whole pages as one copy, the last pa const at = 3 * kern.page + 100; var runs: std.ArrayList([3]usize) = .empty; defer runs.deinit(testing.allocator); - try each(&m, 1, at, Count{ .runs = &runs }, Count.add); + try each(&m, 1, m.states + state_bytes, at, Count{ .runs = &runs }, Count.add); try testing.expectEqual(@as(usize, 1 + 2 + 20), runs.items.len); try testing.expectEqual([3]usize{ (1 << 36) + state_bytes, 0, state_bytes }, runs.items[0]); try testing.expectEqual([3]usize{ (1 << 40) + 7 * page_bytes, state_bytes, 2 * page_bytes }, runs.items[1]); @@ -175,10 +175,10 @@ test "a state on whole pages has no partial copies; one past a slot's pages is r const m = fake(&ids, &caps); var runs: std.ArrayList([3]usize) = .empty; defer runs.deinit(testing.allocator); - try each(&m, 0, 2 * kern.page, Count{ .runs = &runs }, Count.add); + try each(&m, 0, m.states, 2 * kern.page, Count{ .runs = &runs }, Count.add); try testing.expectEqual(@as(usize, 2), runs.items.len); try testing.expectEqual(@as(usize, 2 * page_bytes), runs.items[1][2]); - try testing.expectError(error.PastPages, each(&m, 0, 2 * kern.page + 1, Count{ .runs = &runs }, Count.add)); + try testing.expectError(error.PastPages, each(&m, 0, m.states, 2 * kern.page + 1, Count{ .runs = &runs }, Count.add)); } const Run = struct { From 4ab79253229e88bd7c97d72a04fbb2f5a77337a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:35:40 +0100 Subject: [PATCH 51/59] docs: LFM2.5 on CUDA leases pool pages and keeps chat states in the prompt cache --- docs/recipes/lfm2.5-24b-a2b.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/recipes/lfm2.5-24b-a2b.md b/docs/recipes/lfm2.5-24b-a2b.md index 1df62b6c511..2e770c08641 100644 --- a/docs/recipes/lfm2.5-24b-a2b.md +++ b/docs/recipes/lfm2.5-24b-a2b.md @@ -53,7 +53,10 @@ zig-out/native/bin/tensorfold-native serve "$HOME/models/lfm2.5-24b-a2b-4bit" -- ``` The default window is 32,768 tokens (`--context`), and `--parallel` holds up to 128 streams if the memory budget fits -them. Each stream has fixed pages for its keys and values. The family reads MLX affine 4-bit weights in groups of +them. Streams lease 512-position pages of keys and values from one pool as they need them +(`TENSORFOLD_LFM2_KV_PAGES=0` gives each stream fixed pages instead). The prompt cache keeps a chat's state at its +history marks, the conv states and the K/V rows before the mark, in pages allocated once inside its budget +(`--prompt-cache-gib`). The family reads MLX affine 4-bit weights in groups of 64, with the embedding at 4, 6 or 8 bits. The 6- and 8-bit exports are refused by name and stay on Metal. Drafts are the lane core's copy drafts from the prompt's own text; there is no draft head yet. From b809f7a2ebdc6ee7647f9f97d4e9a1025be7be0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:59:21 +0100 Subject: [PATCH 52/59] lfm2: read TENSORFOLD_LFM2_KV_PAGES through the environment table, refuse anything but 0 or 1 --- docs/environment.md | 1 + zig/src/families/lfm2_moe/cuda_native.zig | 10 +++++----- zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 15 +++++++++++++++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 1e48b4dd78b..0fa7c385826 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -30,6 +30,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96 | | `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off ([profiles](profiles.md)) | | `TF_PROMPT_INTERMEDIATE` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` keeps Flash Next's ladder of intermediate prompt-cache checkpoints under a long prompt's history | +| `TENSORFOLD_LFM2_KV_PAGES` | Exactly `0` or `1`, checked when the CUDA backend starts; unset leases pool pages ([profiles](profiles.md)) | | `TF_HEAD_GEOMETRY` | Whole native-size nonnegative geometry count in the head benchmark | | `TF_ROCE_GID_INDEX` | Whole index 0 through 2147483647; unset searches for a RoCE v2 IPv4 GID | | `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/src/families/lfm2_moe/cuda_native.zig b/zig/src/families/lfm2_moe/cuda_native.zig index ab288466974..8ab9ce977e9 100644 --- a/zig/src/families/lfm2_moe/cuda_native.zig +++ b/zig/src/families/lfm2_moe/cuda_native.zig @@ -54,10 +54,10 @@ fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { return n; } -/// TENSORFOLD_LFM2_KV_PAGES=0: every stream owns a window of pages, made at open; else they lease the pool's. -fn pagesOn() bool { - const v = @import("core").profile.get(.TENSORFOLD_LFM2_KV_PAGES) orelse return true; - return !std.mem.eql(u8, v, "0"); +/// TENSORFOLD_LFM2_KV_PAGES=0: every stream owns a window of pages, made at open; unset or 1 leases the pool's. +fn pagesOn() !bool { + const name = "TENSORFOLD_LFM2_KV_PAGES"; + return @import("sys").environment.value(bool, name, @import("profile").lookup(name), true); } /// The device bytes `n` streams take (paged: the first's states and a round's slot buffers, no pages). @@ -106,7 +106,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer own.w.deinit(); try checkLayers(&own.w.config); const context = @min(mdl.Model.positions(o.context), own.w.config.context); - const paged = pagesOn(); + const paged = try pagesOn(); const plan: Plan = .{ .own = own, .d = ctx.d, .context = context, .paged = paged }; const room: u64 = if (o.room) |r| r.read(r.ctx) orelse 0 else std.math.maxInt(u64); const n = if (paged) try fitFirst(room, plan) else fit(room, o.lanes, o.lanes_fixed, plan) catch |e| { diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 67bcb4b6663..f88746ff20e 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -53,6 +53,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_PROMPT_INTERMEDIATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (unset leases pool pages)" }, .{ .name = "TF_ROCE_GID_INDEX", .scope = .cuda, .kind = .u32, .forms = "a whole GID index from 0 to 2147483647" }, .{ .name = "TF_GEMMA4_CHUNK_SOLO", .scope = .gemma4, .kind = .size, .forms = "a solo prompt pass's rows, a multiple of 512 up to 4096" }, .{ .name = "TF_DRAMA_PREFILL_ROWS", .scope = .drama3, .kind = .u32, .trim = " ", .forms = "whole prompt rows a chunk, 1 through 1024 (checked when a Drama 3 checkpoint opens)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index bba3055681a..480a9aee37e 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -71,6 +71,8 @@ const valid = [_]Case{ .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .raw = "1", .n = 1 }, .{ .name = "TF_PROMPT_INTERMEDIATE", .raw = "0", .n = 0 }, .{ .name = "TF_PROMPT_INTERMEDIATE", .raw = "1", .n = 1 }, + .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .raw = "0", .n = 0 }, + .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_ROCE_GID_INDEX", .raw = "2147483647", .n = 2147483647 }, .{ .name = "TF_DRAMA_PREFILL_ROWS", .raw = " 128 ", .n = 128 }, .{ .name = "TF_DRAMA_REFERENCE_CACHE", .raw = "0", .n = 0 }, @@ -255,6 +257,19 @@ test "environment: the keep-others switch is exact 0 or 1, checked when the CUDA try t.expect(try e.value(bool, name, "1", false)); } +test "environment: LFM2's page switch is exact 0 or 1, refused by name, and unset keeps pages on" { + const name = "TENSORFOLD_LFM2_KV_PAGES"; + for ([_][]const u8{ "off", "false", "no", "on", "2", " 0" }) |raw| { + try t.expectError(error.InvalidEnvironment, e.value(bool, name, raw, true)); + const why = (try e.refusal(a, Env{ .name = name, .raw = raw }, .{ .cuda = true })).?; + defer a.free(why); + try t.expect(std.mem.indexOf(u8, why, name) != null); + } + try t.expect(try e.value(bool, name, null, true)); + try t.expect(try e.value(bool, name, "1", true)); + try t.expect(!try e.value(bool, name, "0", true)); +} + test "environment: real settings are finite, keep their lower bound and optional cap, and read as floats" { try t.expectEqual(@as(f64, 3.25), try e.value(f64, "TF_DSV41_GRAPH_FLOOR_GIB", "3.25", 0)); try t.expectEqual(@as(f64, 0), try e.value(f64, "TF_DSV41_GRAPH_FLOOR_GIB", "0", 1)); From 6da2c048aedc1dc845c01ad7e0da6942a70cbb26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:27:58 +0100 Subject: [PATCH 53/59] lfm2: the startup line says the prompt cache is reserved at load --- zig/src/families/lfm2_moe/cuda_native.zig | 3 +++ zig/src/native/cuda_kv_pool.zig | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/zig/src/families/lfm2_moe/cuda_native.zig b/zig/src/families/lfm2_moe/cuda_native.zig index 8ab9ce977e9..76412a86638 100644 --- a/zig/src/families/lfm2_moe/cuda_native.zig +++ b/zig/src/families/lfm2_moe/cuda_native.zig @@ -152,6 +152,9 @@ pub fn snap_bytes(_: *anyopaque, at: u32) u64 { return snap.bytes(at); } +/// The startup line says the prompt cache is reserved at load: `snap_ready` allocates all of it before any request. +pub const snap_reserved = true; + /// The cache's pages, allocated once before any request: the store counts held and spare pages through the hooks below. pub fn snap_ready(ptr: *anyopaque, budget: u64) !u64 { const x = lfm(ptr); diff --git a/zig/src/native/cuda_kv_pool.zig b/zig/src/native/cuda_kv_pool.zig index 985f183ae30..b02d2e47766 100644 --- a/zig/src/native/cuda_kv_pool.zig +++ b/zig/src/native/cuda_kv_pool.zig @@ -256,7 +256,7 @@ pub fn text(comptime F: type, a: Allocator, stream_bytes: u64, l: ?kv_pool.Layou const line = ", a {d:.1} GiB prompt cache in device memory, budgeted as host memory"; return .{ shape, try std.fmt.allocPrint(a, line, .{toGib(k.copied)}) }; } - const cache = if (k.copied == 0) ", no prompt cache" else if (k.host) try std.fmt.allocPrint(a, ", {s}a {d:.1} GiB prompt cache in host memory with {d:.0} MiB of device staging", .{ if (placed) "prompt states on host, the cache doesn't fit on the card: " else "", toGib(k.copied), @as(f64, @floatFromInt(k.snap_bytes)) / (1 << 20) }) else if (comptime @hasDecl(F, "snap_slots")) try std.fmt.allocPrint(a, ", {s}a prompt cache of {d} snapshot slots ({d:.1} GiB) and {d:.1} GiB of copied rows", .{ if (placed) "prompt states on device: " else "", k.snaps, toGib(k.snaps * k.snap_bytes), toGib(k.copied) }) else try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(k.copied)}); + const cache = if (k.copied == 0) ", no prompt cache" else if (k.host) try std.fmt.allocPrint(a, ", {s}a {d:.1} GiB prompt cache in host memory with {d:.0} MiB of device staging", .{ if (placed) "prompt states on host, the cache doesn't fit on the card: " else "", toGib(k.copied), @as(f64, @floatFromInt(k.snap_bytes)) / (1 << 20) }) else if (comptime @hasDecl(F, "snap_slots")) try std.fmt.allocPrint(a, ", {s}a prompt cache of {d} snapshot slots ({d:.1} GiB) and {d:.1} GiB of copied rows", .{ if (placed) "prompt states on device: " else "", k.snaps, toGib(k.snaps * k.snap_bytes), toGib(k.copied) }) else try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache{s}", .{ toGib(k.copied), if (comptime @hasDecl(F, "snap_reserved")) ", reserved at load" else "" }); return .{ shape, cache }; } @@ -575,7 +575,7 @@ test "kv pages: a family that keeps no prompts plans no cache, so its streams ta try std.testing.expect(fits(Promptless, loaded, o, 3 << 29, 8192, 0) and !fits(struct {}, loaded, o, 3 << 29, 8192, 0)); } } -test "kv pages: LFM2-MoE keeps prompts without snapshot slots: its default cache plans as before, and the store holds what the plan set aside" { +test "kv pages: LFM2-MoE keeps prompts without snapshot slots: its default cache plans as before, the store holds what the plan set aside, reserved at load" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var problem: []const u8 = ""; @@ -590,5 +590,10 @@ test "kv pages: LFM2-MoE keeps prompts without snapshot slots: its default cache const q = (try plan(lfm, arena.allocator(), l, 40 << 30, o, 8192, &problem, false, false, 0, null)).?; try std.testing.expect(q.copied + q.kept > 0); try std.testing.expectEqual(q.copied + q.kept, kept(lfm, .{}, q, o, 40 << 30, 0, 0, false).copied); - try std.testing.expectEqual(budget.cacheBytes(null, 40 << 30, 0), kept(lfm, .{}, null, o, 40 << 30, 0, 0, false).copied); + const k = kept(lfm, .{}, null, o, 40 << 30, 0, 0, false); + try std.testing.expectEqual(budget.cacheBytes(null, 40 << 30, 0), k.copied); + // the startup line says the cache is reserved at load; a family without `snap_reserved` doesn't + const want = try std.fmt.allocPrint(arena.allocator(), ", a {d:.1} GiB prompt cache, reserved at load", .{toGib(k.copied)}); + try std.testing.expectEqualStrings(want, (try text(lfm, arena.allocator(), 1 << 30, null, null, false, false, 32768, k, false))[1]); + try std.testing.expectEqualStrings(want[0 .. want.len - ", reserved at load".len], (try text(struct {}, arena.allocator(), 1 << 30, null, null, false, false, 32768, k, false))[1]); } From 65cebea5db60c116d9d20e18aef49aaae34dc02c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:26:34 +0100 Subject: [PATCH 54/59] lfm2_moe: a keep's copies run on their own stream, so a cold turn's first token doesn't wait for them --- zig/src/families/lfm2_moe/cuda_backend.zig | 10 ++ zig/src/families/lfm2_moe/cuda_snap.zig | 191 ++++++++++++++++++++- 2 files changed, 193 insertions(+), 8 deletions(-) diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig index 2ded108337e..eeeeafda600 100644 --- a/zig/src/families/lfm2_moe/cuda_backend.zig +++ b/zig/src/families/lfm2_moe/cuda_backend.zig @@ -176,6 +176,11 @@ pub const Lfm = struct { snap.drop(x.gpa, &x.snaps.?, k); } + /// Before the prompt stream writes a slot's caches: the keeps' copies queued so far land first (a draw needn't). + fn settle(x: *Lfm) !void { + if (x.snaps) |*p| try p.fence(x.s); + } + fn snapPages(x: *Lfm) !*snap.Pages { return if (x.snaps) |*p| p else error.NoSnapshotCache; } @@ -240,6 +245,7 @@ pub const Lfm = struct { l.sampled = true; }; s.cached = 0; + try x.settle(); try x.m.clearSlot(x.s, l.slot); l.fill = x.resumeAt(s, l, p.len); s.fill_at.store(@intCast(l.fill.?), .monotonic); @@ -275,6 +281,7 @@ pub const Lfm = struct { const done = c.end == p.len; var rows: [mdl.max_taps]usize = undefined; for (c.taps(), 0..) |t, j| rows[j] = t - at - 1; + try x.settle(); try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..c.end], .taps = rows[0..c.n] }}, true, c.end - at - 1, @intFromBool(done)); if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, cfg.vocab * 2, x.s.handle), "cuMemcpyDtoDAsync"); s.fill_at.store(@intCast(c.end), .monotonic); @@ -362,6 +369,7 @@ pub const Lfm = struct { const l = x.lanes.getPtr(s) orelse return error.UnknownStream; const t = try x.value(feed); if (position != l.len + 1) return error.PositionMismatch; + try x.settle(); try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{t} }}, false, 0, 1); l.len += 1; const h = x.next; @@ -398,6 +406,7 @@ pub const Lfm = struct { total += l.rows.items.len; } if (total > round_rows) return error.RoundTooWide; + try x.settle(); try fwd.forward(x.m, x.k, x.s, chains, false, 0, total); var at: usize = 0; for (windows, 0..) |w, i| { @@ -431,6 +440,7 @@ pub const Lfm = struct { slots[i] = @intCast(l.slot); rows[i] = @intCast(l.row0 + path.len - 1); // the conv states after the last kept row } + try x.settle(); try fwd.commit(x.m, x.k, x.s, slots[0..windows.len], rows[0..windows.len]); } diff --git a/zig/src/families/lfm2_moe/cuda_snap.zig b/zig/src/families/lfm2_moe/cuda_snap.zig index 965546d10df..605b35ac236 100644 --- a/zig/src/families/lfm2_moe/cuda_snap.zig +++ b/zig/src/families/lfm2_moe/cuda_snap.zig @@ -21,23 +21,77 @@ pub fn bytes(at: usize) u64 { return (n + page - 1) / page * page; } +/// The keeps' own stream: copies start after the prompt pass (`ready`); `main` waits (`done`) before its next write. +pub const Side = struct { + stream: cuda.Stream, + ready: cuda.Event, + done: cuda.Event, + pending: bool = false, // copies queued that the prompt stream has not waited for yet + + pub fn init(d: *const cuda.Driver) !Side { + var st = try cuda.Stream.init(d, true); + errdefer st.deinit(); + var r = try cuda.Event.init(d, false); + errdefer r.deinit(); + return .{ .stream = st, .ready = r, .done = try cuda.Event.init(d, false) }; + } + + pub fn deinit(x: *Side) void { + x.stream.deinit(); // drains the copies first + x.done.deinit(); + x.ready.deinit(); + } + + /// Before a keep's copies: they start after everything queued on `main` so far. + fn begin(x: *Side, main: cuda.Stream) !void { + try x.ready.record(main); + try x.stream.wait(x.ready); + } + + /// After a keep's copies (or some of them): `done` marks them; if it can't, they are drained here. + fn end(x: *Side) void { + x.done.record(x.stream) catch { + x.stream.synchronize() catch std.log.warn("lfm2_moe: a keep's copies did not drain", .{}); + return; + }; + x.pending = true; + } + + /// Before `main` writes what a keep reads or reads what it wrote: wait on the device for the keeps queued so far. + pub fn fence(x: *Side, main: cuda.Stream) !void { + if (!x.pending) return; + try main.wait(x.done); + x.pending = false; + } +}; + /// The budget's pages, allocated once; states lease them and give them back. pub const Pages = struct { pages: kv.Pool, arena: ?cuda.DeviceBuffer, + side: ?Side = null, // the keeps' stream (none without pages) pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, budget: u64) !Pages { const count = std.math.cast(u32, budget / page) orelse return error.SnapshotBudget; var pages = try kv.Pool.init(gpa, count, page); errdefer pages.deinit(); - return .{ .pages = pages, .arena = if (count > 0) try cuda.DeviceBuffer.alloc(d, @as(usize, count) * page) else null }; + if (count == 0) return .{ .pages = pages, .arena = null }; + var arena = try cuda.DeviceBuffer.alloc(d, @as(usize, count) * page); + errdefer arena.free(); + return .{ .pages = pages, .arena = arena, .side = try Side.init(d) }; } pub fn deinit(p: *Pages) void { + if (p.side) |*x| x.deinit(); if (p.arena) |*a| a.free(); p.pages.deinit(); } + /// Before `main` writes a slot's caches or reads snapshot pages: the keeps queued so far land first. + pub fn fence(p: *Pages, main: cuda.Stream) !void { + if (p.side) |*x| try x.fence(main); + } + /// Bytes of pages no state holds. pub fn spare(p: *const Pages) u64 { return p.pages.available() * page; @@ -105,24 +159,28 @@ fn copy(c: Leased, dev: u64, off: usize, len: usize) anyerror!void { try pageRuns(c.ids, off, len, Copy{ .d = c.d, .s = c.s, .arena = c.arena, .dev = dev, .out = c.out }, copyRun); } -/// `slot`'s state at `at` copied into leased pages behind the chunk that ends there or taps it (conv states at `conv`). -pub fn save(gpa: std.mem.Allocator, p: *Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, at: u32, conv: u64) !*Saved { +/// `slot`'s state at `at` (conv states at `conv`) copied on the keeps' stream, after what `main` has queued. +pub fn save(gpa: std.mem.Allocator, p: *Pages, m: *const mdl.Model, main: cuda.Stream, slot: usize, at: u32, conv: u64) !*Saved { if (at == 0 or at > m.context) return error.NotAtMark; + const x = if (p.side) |*x| x else return error.NoSnapshotRoom; const k = try gpa.create(Saved); errdefer gpa.destroy(k); k.* = .{ .at = at, .lease = try p.take(bytes(at) / page) }; errdefer p.pages.finish(&k.lease); - try each(m, slot, conv, at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = true }, copy); + try x.begin(main); + defer x.end(); // copies already queued still read the slot: `main` waits for them as for whole ones + try each(m, slot, conv, at, Leased{ .d = m.d, .s = x.stream, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = true }, copy); return k; } -/// Make `slot`'s pages and conv states hold `k`'s state, queued on `s` before the next chunk. -pub fn restore(p: *const Pages, m: *const mdl.Model, s: cuda.Stream, slot: usize, k: *const Saved) !void { +/// Make `slot`'s pages and conv states hold `k`'s state: queued on `main` before the next chunk, after the keeps. +pub fn restore(p: *Pages, m: *const mdl.Model, main: cuda.Stream, slot: usize, k: *const Saved) !void { if (k.at > m.context) return error.PastContext; - try each(m, slot, m.states + slot * state_bytes, k.at, Leased{ .d = m.d, .s = s, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = false }, copy); + try p.fence(main); + try each(m, slot, m.states + slot * state_bytes, k.at, Leased{ .d = m.d, .s = main, .arena = p.arena.?.ptr, .ids = k.lease.ids.items, .out = false }, copy); } -/// Give a state's pages back: every copy that reads or writes them is queued on the one stream, ahead of any later one. +/// Give a state's pages back: a later keep writes them after what `main` queued before it (a restore reading them). pub fn drop(gpa: std.mem.Allocator, p: *Pages, k: *Saved) void { p.pages.finish(&k.lease); gpa.destroy(k); @@ -207,3 +265,120 @@ test "a state's pages: whole snapshot pages, the budget's pages leased and given try testing.expectEqual(@as(u64, page), bytes(1)); try testing.expect(bytes(10_000) >= state_bytes + 10_000 * 20 * 1024 and bytes(10_000) % page == 0); } + +/// A fake driver's queue log: which stream each copy, record and wait went to, and the sampler's mark. +const Order = struct { + const Op = struct { kind: enum { copy, record, wait, sample }, stream: usize, event: usize = 0 }; + var ops: [128]Op = undefined; + var n: usize = 0; + const main: usize = 1; + const side: usize = 2; + const ready: usize = 3; + const done: usize = 4; + + fn add(op: Op) void { + ops[n] = op; + n += 1; + } + fn id(h: ?*anyopaque) usize { + return @intFromPtr(h); + } + fn dtod(_: u64, _: u64, _: usize, st: @import("cuda").abi.Stream) callconv(.c) @import("cuda").abi.Result { + add(.{ .kind = .copy, .stream = id(st) }); + return 0; + } + fn record(ev: @import("cuda").abi.Event, st: @import("cuda").abi.Stream) callconv(.c) @import("cuda").abi.Result { + add(.{ .kind = .record, .stream = id(st), .event = id(ev) }); + return 0; + } + fn wait(st: @import("cuda").abi.Stream, ev: @import("cuda").abi.Event, _: c_uint) callconv(.c) @import("cuda").abi.Result { + add(.{ .kind = .wait, .stream = id(st), .event = id(ev) }); + return 0; + } + + /// Whether the first token waits for a keep: before the sampler, `main` has a copy or waits for `done`. + fn firstWaits() bool { + for (ops[0..n]) |op| { + if (op.kind == .sample) return false; + if (op.stream == main and (op.kind == .copy or (op.kind == .wait and op.event == done))) return true; + } + return true; // no sampler: nothing to show + } + + /// Whether a restore's copies on `main` (after the sampler) come after `main` waited for every keep's `done`. + fn restoreWaits() bool { + var last_done: ?usize = null; // the last record of `done` on the keeps' stream + var waited: ?usize = null; + var sampled = false; + for (ops[0..n], 0..) |op, i| switch (op.kind) { + .sample => sampled = true, + .record => if (op.event == done) { + last_done = i; + }, + .wait => if (op.stream == main and op.event == done) { + waited = i; + }, + .copy => if (sampled and op.stream == main) return if (last_done) |d| if (waited) |w| w > d else false else true, + }; + return true; + } + + /// Every keep copy on the keeps' stream comes after it waited for `ready`, recorded on `main`. + fn keepAfterPass() bool { + var armed = false; + for (ops[0..n]) |op| switch (op.kind) { + .wait => if (op.stream == side and op.event == ready) { + armed = true; + }, + .copy => if (op.stream == side and !armed) return false, + else => {}, + }; + return true; + } +}; + +test "a keep's copies run beside the first token's draw, after the prompt pass, and a restore waits for them" { + const cu = @import("cuda"); + var d: cu.Driver = undefined; + d.api.cuMemcpyDtoDAsync_v2 = Order.dtod; + d.api.cuEventRecord = Order.record; + d.api.cuStreamWaitEvent = Order.wait; + const main: cu.Stream = .{ .d = &d, .handle = @ptrFromInt(Order.main) }; + var ids = [_]u32{ 4, 5, 6, 7 }; + var caps = [_]usize{2 * kern.page}; + var m = fake(&ids, &caps); + m.d = &d; + var pages: Pages = .{ + .pages = try kv.Pool.init(testing.allocator, 16, page), + .arena = .{ .d = &d, .ptr = 1 << 44, .len = 16 * page, .borrowed = true }, + .side = .{ .stream = .{ .d = &d, .handle = @ptrFromInt(Order.side) }, .ready = .{ .d = &d, .handle = @ptrFromInt(Order.ready) }, .done = .{ .d = &d, .handle = @ptrFromInt(Order.done) } }, + }; + defer pages.pages.deinit(); + // the real order: keep, the sampler, then a restore + Order.n = 0; + const k = try save(testing.allocator, &pages, &m, main, 0, kern.page + 7, m.states); + Order.add(.{ .kind = .sample, .stream = Order.main }); + try restore(&pages, &m, main, 0, k); + try testing.expect(!Order.firstWaits() and Order.restoreWaits() and Order.keepAfterPass()); + try testing.expect(!pages.side.?.pending); + drop(testing.allocator, &pages, k); + // planted: the copies back on `main` ahead of the sampler (as before this change); the check must see the wait + Order.n = 0; + var lease = try pages.take(bytes(kern.page + 7) / page); + defer pages.pages.finish(&lease); + try each(&m, 0, m.states, kern.page + 7, Leased{ .d = &d, .s = main, .arena = 1 << 44, .ids = lease.ids.items, .out = true }, copy); + Order.add(.{ .kind = .sample, .stream = Order.main }); + try testing.expect(Order.firstWaits()); + // planted: a restore without the fence reads the pages while the keeps' copies may still run + Order.n = 0; + const k2 = try save(testing.allocator, &pages, &m, main, 0, kern.page + 7, m.states); + Order.add(.{ .kind = .sample, .stream = Order.main }); + try each(&m, 0, m.states, k2.at, Leased{ .d = &d, .s = main, .arena = 1 << 44, .ids = k2.lease.ids.items, .out = false }, copy); + try testing.expect(!Order.restoreWaits()); + pages.side.?.pending = false; + drop(testing.allocator, &pages, k2); + // planted: the copies on the keeps' stream before it waited for the prompt pass + Order.n = 0; + try each(&m, 0, m.states, kern.page + 7, Leased{ .d = &d, .s = pages.side.?.stream, .arena = 1 << 44, .ids = lease.ids.items, .out = true }, copy); + try testing.expect(!Order.keepAfterPass()); +} From ff2a4c08fbedf9c781744ad08cb74a599f28c441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:50:11 +0100 Subject: [PATCH 55/59] lfm2_moe: every write a keep reads takes its stream from one place, which waits for the keeps A clear, a chunk, a one-row step, a verify round and a commit each queue on the stream fenced() hands back, after the keeps' copies queued so far. A host test reads the backend's writes and fails on one queued on the prompt stream without the wait; each of the five planted that way goes red. --- zig/src/families/lfm2_moe/cuda_backend.zig | 103 ++++++++++++++++++--- 1 file changed, 91 insertions(+), 12 deletions(-) diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig index eeeeafda600..91475497887 100644 --- a/zig/src/families/lfm2_moe/cuda_backend.zig +++ b/zig/src/families/lfm2_moe/cuda_backend.zig @@ -176,9 +176,10 @@ pub const Lfm = struct { snap.drop(x.gpa, &x.snaps.?, k); } - /// Before the prompt stream writes a slot's caches: the keeps' copies queued so far land first (a draw needn't). - fn settle(x: *Lfm) !void { + /// The stream every write to a slot's caches takes, after the keeps so far (a draw needn't); tested below. + fn fenced(x: *Lfm) !cuda.Stream { if (x.snaps) |*p| try p.fence(x.s); + return x.s; } fn snapPages(x: *Lfm) !*snap.Pages { @@ -245,8 +246,7 @@ pub const Lfm = struct { l.sampled = true; }; s.cached = 0; - try x.settle(); - try x.m.clearSlot(x.s, l.slot); + try x.m.clearSlot(try x.fenced(), l.slot); l.fill = x.resumeAt(s, l, p.len); s.fill_at.store(@intCast(l.fill.?), .monotonic); return l; @@ -281,8 +281,7 @@ pub const Lfm = struct { const done = c.end == p.len; var rows: [mdl.max_taps]usize = undefined; for (c.taps(), 0..) |t, j| rows[j] = t - at - 1; - try x.settle(); - try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..c.end], .taps = rows[0..c.n] }}, true, c.end - at - 1, @intFromBool(done)); + try fwd.forward(x.m, x.k, try x.fenced(), &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..c.end], .taps = rows[0..c.n] }}, true, c.end - at - 1, @intFromBool(done)); if (done) try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(l.last, x.m.s.logits, cfg.vocab * 2, x.s.handle), "cuMemcpyDtoDAsync"); s.fill_at.store(@intCast(c.end), .monotonic); l.fill = if (done) null else c.end; @@ -369,8 +368,7 @@ pub const Lfm = struct { const l = x.lanes.getPtr(s) orelse return error.UnknownStream; const t = try x.value(feed); if (position != l.len + 1) return error.PositionMismatch; - try x.settle(); - try fwd.forward(x.m, x.k, x.s, &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{t} }}, false, 0, 1); + try fwd.forward(x.m, x.k, try x.fenced(), &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{t} }}, false, 0, 1); l.len += 1; const h = x.next; try x.drawRows(l, x.m.s.logits, 0, 1, position, x.handle(), 0); @@ -406,8 +404,7 @@ pub const Lfm = struct { total += l.rows.items.len; } if (total > round_rows) return error.RoundTooWide; - try x.settle(); - try fwd.forward(x.m, x.k, x.s, chains, false, 0, total); + try fwd.forward(x.m, x.k, try x.fenced(), chains, false, 0, total); var at: usize = 0; for (windows, 0..) |w, i| { const l = x.lanes.getPtr(w.stream).?; @@ -440,8 +437,7 @@ pub const Lfm = struct { slots[i] = @intCast(l.slot); rows[i] = @intCast(l.row0 + path.len - 1); // the conv states after the last kept row } - try x.settle(); - try fwd.commit(x.m, x.k, x.s, slots[0..windows.len], rows[0..windows.len]); + try fwd.commit(x.m, x.k, try x.fenced(), slots[0..windows.len], rows[0..windows.len]); } /// No draft head: absorbing is a no-op, a request for drafts is refused by name (copy drafts come from the host). @@ -499,3 +495,86 @@ test "a chunk taps the marks inside it, up to four, and ends at the next one, th try std.testing.expectEqualSlices(usize, k.taps, c.taps()); } } + +/// The writes a keep reads, by their call, and which argument is the stream each is queued on. +const Write = struct { call: []const u8, arg: usize }; +const writes = [_]Write{ .{ .call = "fwd.forward(", .arg = 2 }, .{ .call = "fwd.commit(", .arg = 2 }, .{ .call = ".clearSlot(", .arg = 0 } }; + +/// The writes in `code` whose stream isn't `try x.fenced()`; `found` counts every write. +fn unfenced(code: []const u8, found: *usize) usize { + var bad: usize = 0; + for (writes) |w| { + var from: usize = 0; + while (std.mem.indexOfPos(u8, code, from, w.call)) |at| { + from = at + w.call.len; + found.* += 1; + var depth: usize = 0; + var arg: usize = 0; + var start = from; + const stream = for (code[from..], from..) |ch, i| switch (ch) { + '(', '[', '{' => depth += 1, + ')', ']', '}' => if (depth == 0) break code[start..i] else { + depth -= 1; + }, + ',' => if (depth == 0) { + if (arg == w.arg) break code[start..i]; + arg += 1; + start = i + 1; + }, + else => {}, + } else ""; + if (arg != w.arg or !std.mem.eql(u8, std.mem.trim(u8, stream, " \n"), "try x.fenced()")) bad += 1; + } + } + return bad; +} + +test "a clear, a chunk, a one-row step, a verify round and a commit wait for the keeps; one on x.s is red" { + const all = @embedFile("cuda_backend.zig"); + const code = all[0..std.mem.indexOf(u8, all, "\ntest \"").?]; + var found: usize = 0; + try std.testing.expectEqual(@as(usize, 0), unfenced(code, &found)); + try std.testing.expectEqual(@as(usize, 5), found); // a new write names itself here + // planted: each write in turn queued on the prompt stream without the wait + const fence = "try x.fenced()"; + var planted: usize = 0; + var from: usize = 0; + while (std.mem.indexOfPos(u8, code, from, fence)) |at| : (from = at + fence.len) { + const bent = try std.mem.concat(std.testing.allocator, u8, &.{ code[0..at], "x.s", code[at + fence.len ..] }); + defer std.testing.allocator.free(bent); + found = 0; + try std.testing.expectEqual(@as(usize, 1), unfenced(bent, &found)); + planted += 1; + } + try std.testing.expectEqual(@as(usize, 5), planted); +} + +const Waits = struct { + var n: usize = 0; + var on: usize = 0; + var of: usize = 0; + fn wait(st: cuda.abi.Stream, ev: cuda.abi.Event, _: c_uint) callconv(.c) cuda.abi.Result { + n += 1; + on = @intFromPtr(st); + of = @intFromPtr(ev); + return 0; + } +}; + +test "fenced: the prompt stream waits for the keeps' done once a keep is queued, and not again until the next" { + var d: cuda.Driver = undefined; + d.api.cuStreamWaitEvent = Waits.wait; + var x: Lfm = undefined; + x.s = .{ .d = &d, .handle = @ptrFromInt(1) }; + x.snaps = null; + Waits.n = 0; + try std.testing.expectEqual(x.s.handle, (try x.fenced()).handle); // no prompt cache: nothing to wait for + const side: snap.Side = .{ .stream = .{ .d = &d, .handle = @ptrFromInt(2) }, .ready = .{ .d = &d, .handle = @ptrFromInt(3) }, .done = .{ .d = &d, .handle = @ptrFromInt(4) }, .pending = true }; + x.snaps = .{ .pages = try kv.Pool.init(std.testing.allocator, 1, snap.page), .arena = null, .side = side }; + defer x.snaps.?.pages.deinit(); + try std.testing.expectEqual(@as(usize, 0), Waits.n); + try std.testing.expectEqual(x.s.handle, (try x.fenced()).handle); + try std.testing.expect(Waits.n == 1 and Waits.on == 1 and Waits.of == 4); + _ = try x.fenced(); // nothing queued since: no second wait + try std.testing.expectEqual(@as(usize, 1), Waits.n); +} From b4f1bf263c7da8ef0a8980c279d0b31f9acf0ce9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:01:49 +0000 Subject: [PATCH 56/59] changelog: #2989 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41719f2591c..620d7ff40a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- LFM2.5-24B-A2B on CUDA: the five prompt-stream writes whose state a prompt-cache keep copies (a slot clear, a prompt chunk, a one-row step, a verify round and a commit) take their stream from one helper that first waits for the keeps' copies, and a host test fails if a write skips it. Replies are unchanged (#2989, after #1503). Thanks to @jschmied. + - Environment: the Metal Qwen KV paging and slot-resume switches and the slide checks refuse a malformed value by name, and `TF_SLIDE_TAKE_OUT_CHECK` is read once at start with `--slide` (#3018, for #2370). - Metrics: every queued request carries one wait reason decided on the admission path, and DeepSeek-V4.1 names its own (`kv_pool`, `memory_floor`, `prefill_concurrent`). `/metrics` gains `requests_waiting_by_reason`, `request_refusals_total` and `request_failures_total` by code and `restore_fallbacks_total`, and `/v1/load` gains `waiting_by_reason` and `refusals`; replies are unchanged (#3014, for #2135). Thanks to @devopsfortunato for the design. From 23475ef6dfe72e534c83c1ac465077a12d9050b0 Mon Sep 17 00:00:00 2001 From: Ash <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 02:19:15 +0000 Subject: [PATCH 57/59] server: a crash's stale note and graph temporaries are cleared when the server opens their folders --- zig/src/platform/atomic_file.zig | 44 +++++++++++++++++++++++++++ zig/src/server/compact_test.zig | 10 +++--- zig/src/server/private_files_test.zig | 42 +++++++++++++++++++++++++ zig/src/server/server.zig | 3 ++ 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/zig/src/platform/atomic_file.zig b/zig/src/platform/atomic_file.zig index 1150c254673..6353a65a283 100644 --- a/zig/src/platform/atomic_file.zig +++ b/zig/src/platform/atomic_file.zig @@ -78,6 +78,50 @@ pub fn replacePrivate(a: Allocator, path: []const u8, parts: []const []const u8) try commit(a, try stagePrivate(a, path, parts), path); } +/// Clears the `.tmp..` a crash left in `dir` (only `only`'s when given); live writers keep theirs. +pub fn discardStale(io: std.Io, dir: []const u8, only: ?[]const u8) void { + var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return; + defer d.close(io); + var it = d.iterate(); + while (it.next(io) catch null) |entry| { + if (entry.kind != .file) continue; + const staged = stagedBy(entry.name) orelse continue; + if (only) |file| if (!std.mem.eql(u8, staged.file, file)) continue; + const stale = if (platform.windows) blk: { + // no portable way to ask whether a pid lives: a day-old temporary is stale + const cutoff = std.Io.Clock.real.now(io).subDuration(.{ .nanoseconds = 86_400 * std.time.ns_per_s }); + const st = d.statFile(io, entry.name, .{}) catch continue; + break :blk st.mtime.nanoseconds < cutoff.nanoseconds; + } else writerGone(staged.pid); + if (stale) d.deleteFile(io, entry.name) catch {}; + } +} + +/// The file and writer's pid when `name` is exactly `.tmp..`, as `stageAs` prints them. +fn stagedBy(name: []const u8) ?struct { file: []const u8, pid: i32 } { + const at = std.mem.lastIndexOf(u8, name, ".tmp.") orelse return null; + if (at == 0) return null; + const rest = name[at + ".tmp.".len ..]; + const dot = std.mem.indexOfScalar(u8, rest, '.') orelse return null; + if (!decimal(rest[0..dot]) or !decimal(rest[dot + 1 ..])) return null; + const pid = std.fmt.parseInt(i32, rest[0..dot], 10) catch return null; + if (pid <= 0) return null; + return .{ .file = name[0..at], .pid = pid }; +} + +/// Digits as `{d}` prints them: at least one, no sign, separator or leading zero. +fn decimal(text: []const u8) bool { + if (text.len == 0 or (text.len > 1 and text[0] == '0')) return false; + for (text) |ch| if (!std.ascii.isDigit(ch)) return false; + return true; +} + +fn writerGone(pid: i32) bool { + if (platform.windows) return false; // discardStale uses the age fallback there + if (platform.c.kill(pid, @fromBackingInt(@intCast(0))) == 0) return false; + return platform.c.errno(-1) == .SRCH; +} + fn writeAll(fd: platform.c.fd_t, bytes: []const u8) !void { var done: usize = 0; while (done < bytes.len) { diff --git a/zig/src/server/compact_test.zig b/zig/src/server/compact_test.zig index 682e0e35cf5..19692749d5e 100644 --- a/zig/src/server/compact_test.zig +++ b/zig/src/server/compact_test.zig @@ -72,9 +72,9 @@ const Stay = struct { } }; -const Text = struct { +pub const Text = struct { reasoning: bool = false, - fn text(t: *@This()) model_text.Text { + pub fn text(t: *@This()) model_text.Text { return .{ .ctx = t, .vtable = &.{ .encode = encode, .decode = decode, .token_id = tokenId, .token_string = tokenString, .vocab_size = vocabSize, .eos_ids = eosIds, .render = render, .template_source = templateSource } }; } @@ -126,7 +126,7 @@ const Text = struct { } }; -const Eng = struct { +pub const Eng = struct { window: u32, cache: bool = false, prompts: std.ArrayList([]u8) = .empty, @@ -134,7 +134,7 @@ const Eng = struct { early: usize = 0, late: usize = 0, - fn engine(e: *Eng) api.Engine { + pub fn engine(e: *Eng) api.Engine { return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; } @@ -165,7 +165,7 @@ const Eng = struct { } }; -fn freePrompts(e: *Eng) void { +pub fn freePrompts(e: *Eng) void { for (e.prompts.items) |p| gpa.free(p); e.prompts.deinit(gpa); } diff --git a/zig/src/server/private_files_test.zig b/zig/src/server/private_files_test.zig index 67d1c6c8071..093303639b6 100644 --- a/zig/src/server/private_files_test.zig +++ b/zig/src/server/private_files_test.zig @@ -5,6 +5,7 @@ const json = @import("json"); const compact_mem = @import("compact_mem.zig"); const server = @import("server.zig"); const Graph = @import("slide_graph.zig").Graph; +const fakes = @import("compact_test.zig"); const testing = std.testing; const io = testing.io; @@ -95,3 +96,44 @@ test "security: the fact graph is owner-only and is not written through a plante defer again.deinit(); try testing.expectEqual(@as(usize, 1), again.facts.items.len); } + +test "a server open clears a crash's stale temporaries but keeps a live writer's and every other file" { + // the pid check is POSIX's; Windows' day-old fallback would need Dir.setTimestamps, which Zig 0.17 lacks there + if (platform.windows) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "notes"); + try tmp.dir.createDirPath(io, "graphs"); + const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const live = try std.fmt.allocPrint(a, ".tmp.{d}.0", .{platform.c.getpid()}); + // no process has pid 999999999 (Linux's pid_max is at most 2^22, macOS's 99999) + const stale = [_][]const u8{ "notes/k.md.tmp.999999999.0", "notes/k.json.tmp.999999999.12", "graphs/graph.json.tmp.999999999.3" }; + const kept = [_][]const u8{ + "notes/k.md", "notes/k.md.tmp.not-a-pid.0", + "notes/k.md.tmp.+999999999.0", "notes/k.md.tmp.999999999.0.extra", + "notes/k.md.tmp.0999999999.0", "notes/k.md.tmp.999_999_999.0", + "notes/k.md.tmp.0.0", "notes/k.md.tmp.4294967295.0", + "notes/.tmp.999999999.0", + "graphs/other.json.tmp.999999999.0", // another file's, in a folder the graph may share + try std.fmt.allocPrint(a, "notes/k.md{s}", .{live}), + try std.fmt.allocPrint(a, "graphs/graph.json{s}", .{live}), + }; + for (stale ++ kept) |name| try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "x" }); + + var eng: fakes.Eng = .{ .window = 256 }; + defer fakes.freePrompts(&eng); + var text: fakes.Text = .{}; + const srv = try server.Server.init(testing.allocator, io, eng.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .compact_memory = try std.fmt.allocPrint(a, "{s}/notes", .{root}), + .slide_graph = try std.fmt.allocPrint(a, "{s}/graphs/graph.json", .{root}), + }, null); + defer srv.deinit(); + + for (stale) |name| try testing.expectError(error.FileNotFound, tmp.dir.statFile(io, name, .{})); + for (kept) |name| _ = try tmp.dir.statFile(io, name, .{}); +} diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 158ff512eeb..7ad346293b3 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -201,6 +201,9 @@ pub const Server = struct { srv.* = .{ .tool_ids = tool_ids, .gpa = gpa, .io = io, .engine = engine, .info = engine.info(), .text = text, .config = config, .keys = keys, .metrics = .{ .gpa = gpa, .phases = config.phase_metrics }, .load = .init(io), .store = .{ .gpa = gpa }, .arena = .init(gpa), .slide = .init(gpa, io, config.slide_graph), .teacher = .init(gpa) }; srv.config.tool_id_key = null; // its key is zeroed: `tool_ids` is the one copy errdefer srv.deinit(); // a later step's failure stops the keepalive before the caller closes the engine + // a crash between a note's or the graph's write and its rename leaves a temporary behind + if (config.compact_memory) |dir| platform.atomic_file.discardStale(io, dir, null); + if (config.slide_graph) |path| platform.atomic_file.discardStale(io, std.fs.path.dirname(path) orelse ".", std.fs.path.basename(path)); if (srv.info.embeddings != null and srv.info.capability(.text_generation)) return error.InvalidEmbeddingCapabilities; if (srv.info.readouts != null and (srv.info.capability(.text_generation) or srv.info.embeddings != null)) return error.InvalidReadoutCapabilities; if (srv.info.vision) |vision| if (@import("vision_markers.zig").firstUnsafe(text, vision)) |id| { From 5e132f0154f986ad90f279b9cb00de945d333ca4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:06:01 +0000 Subject: [PATCH 58/59] server: the stale-temporary sweep moves to stale_temps.zig, so server.zig stays at 600 lines The same two calls, made at the same point in Server.init. --- zig/src/server/server.zig | 7 ++----- zig/src/server/stale_temps.zig | 10 ++++++++++ 2 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 zig/src/server/stale_temps.zig diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 7ad346293b3..a46505c1fc8 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -78,8 +78,7 @@ pub const Config = struct { silence_mid: bool = false, silence_guard: bool = false, cfg: ?@import("drama_cfg.zig").Options = null, - /// --prompt-seed keeps historical prompt-keyed sampling when a request omits its seed. - prompt_seed: bool = false, + prompt_seed: bool = false, // --prompt-seed: historical prompt-keyed sampling when a request omits its seed /// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere. request_log: ?[]const u8 = null, /// TENSORFOLD_PHASE_METRICS=1: /metrics adds the queue phase's histogram; unset, its families are as before. @@ -201,9 +200,7 @@ pub const Server = struct { srv.* = .{ .tool_ids = tool_ids, .gpa = gpa, .io = io, .engine = engine, .info = engine.info(), .text = text, .config = config, .keys = keys, .metrics = .{ .gpa = gpa, .phases = config.phase_metrics }, .load = .init(io), .store = .{ .gpa = gpa }, .arena = .init(gpa), .slide = .init(gpa, io, config.slide_graph), .teacher = .init(gpa) }; srv.config.tool_id_key = null; // its key is zeroed: `tool_ids` is the one copy errdefer srv.deinit(); // a later step's failure stops the keepalive before the caller closes the engine - // a crash between a note's or the graph's write and its rename leaves a temporary behind - if (config.compact_memory) |dir| platform.atomic_file.discardStale(io, dir, null); - if (config.slide_graph) |path| platform.atomic_file.discardStale(io, std.fs.path.dirname(path) orelse ".", std.fs.path.basename(path)); + @import("stale_temps.zig").discard(io, config); // a crash's temporaries beside the note and the graph if (srv.info.embeddings != null and srv.info.capability(.text_generation)) return error.InvalidEmbeddingCapabilities; if (srv.info.readouts != null and (srv.info.capability(.text_generation) or srv.info.embeddings != null)) return error.InvalidReadoutCapabilities; if (srv.info.vision) |vision| if (@import("vision_markers.zig").firstUnsafe(text, vision)) |id| { diff --git a/zig/src/server/stale_temps.zig b/zig/src/server/stale_temps.zig new file mode 100644 index 00000000000..6a9268fffc3 --- /dev/null +++ b/zig/src/server/stale_temps.zig @@ -0,0 +1,10 @@ +//! A crash between a note's or the graph's write and its rename leaves a temporary: cleared at server open. +const std = @import("std"); +const platform = @import("sys"); +const Config = @import("server.zig").Config; + +/// Each temporary left in the stored note's folder and beside the fact graph, removed. +pub fn discard(io: std.Io, config: Config) void { + if (config.compact_memory) |dir| platform.atomic_file.discardStale(io, dir, null); + if (config.slide_graph) |path| platform.atomic_file.discardStale(io, std.fs.path.dirname(path) orelse ".", std.fs.path.basename(path)); +} From e7e24243d63e232b05d4892df4fa01c9a2d6c70b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:13:10 +0000 Subject: [PATCH 59/59] changelog: #3132 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 620d7ff40a2..607d011c57e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: temporaries a crash left beside notes and the `--slide-graph` file are cleared when the server opens their folders, only the server's own and only when their process is gone (#3132). + - LFM2.5-24B-A2B on CUDA: the five prompt-stream writes whose state a prompt-cache keep copies (a slot clear, a prompt chunk, a one-row step, a verify round and a commit) take their stream from one helper that first waits for the keeps' copies, and a host test fails if a write skips it. Replies are unchanged (#2989, after #1503). Thanks to @jschmied. - Environment: the Metal Qwen KV paging and slot-resume switches and the slide checks refuse a malformed value by name, and `TF_SLIDE_TAKE_OUT_CHECK` is read once at start with `--slide` (#3018, for #2370).