From 3dcbbc18c607af6875ad58aacb9d60942ea727bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:25:20 +0100 Subject: [PATCH 01/23] cuda: the parked-page reading logs at debug level The start-up line naming the free pages on the per-CPU lists printed only when 0.25 GiB or more happened to sit there, so start-up output changed with the box's memory state (#2127). The pool still counts them; only the line moves to debug. --- zig/src/native/cuda_family_memory.zig | 2 +- zig/src/native/cuda_family_memory_test.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/native/cuda_family_memory.zig b/zig/src/native/cuda_family_memory.zig index 569af1948b4..5f5a5b712cd 100644 --- a/zig/src/native/cuda_family_memory.zig +++ b/zig/src/native/cuda_family_memory.zig @@ -63,7 +63,7 @@ pub fn weights(comptime F: type, a: Allocator, io: std.Io, o: api.Open, problem: /// Logs, from 0.25 GiB, the free pages on the per-CPU lists that a pool's reading counted. pub fn noteParked(p: budget.Pool, what: []const u8) void { const line = "{s} counts the {d:.2} GiB free on the per-CPU page lists beyond their resting level (MemAvailable does not)"; - if (p.parked >= 1 << 28) std.log.info(line, .{ what, toGib(p.parked) }); + if (p.parked >= 1 << 28) std.log.debug(line, .{ what, toGib(p.parked) }); // debug: varies run to run } pub fn room(comptime F: type, ptr: *anyopaque, local: u64) !u64 { diff --git a/zig/src/native/cuda_family_memory_test.zig b/zig/src/native/cuda_family_memory_test.zig index 4e48552e230..a57a505eb30 100644 --- a/zig/src/native/cuda_family_memory_test.zig +++ b/zig/src/native/cuda_family_memory_test.zig @@ -114,7 +114,7 @@ test "a Linux unified pool counts the free pages parked on the per-CPU lists, at try t.expectEqual(@as(usize, 0), Fake.zone_probes); } -test "the pool names the parked share it counted, for the start-up log line" { +test "the pool names the parked share it counted, for the debug log line" { var driver: cuda.Driver = undefined; driver.api.cuDeviceGetAttribute = Fake.attribute; driver.api.cuMemGetInfo_v2 = Fake.memInfo; From a807dfe36a31f7660081fe1ba66f426dec95cb4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:46:04 +0100 Subject: [PATCH 02/23] changelog: leave the released 1.2.2 entry as it was (#2164) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8c0cbfe29..7136d47a74f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -888,7 +888,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - On Ryzen AI Max (RDNA 3.5) GPUs, one- and two-row decode launches use narrower stream tiles, so Qwen3.6-35B-A3B chat decodes about 18% faster with drafts on, and Qwen3.8-27B about 5% faster, with the same tokens (#1855). Thanks to @AbrahamCete. -- Flash Next on RDNA 3.5 iGPUs (gfx1150 to gfx1153) fills prompts in 4,096-row chunks by default on one GPU, falling back to 1,024 when the larger chunk would admit fewer streams. Tokens are unchanged. The larger chunk's scratch holds about 4.6 GiB more device memory; `--policy prefill_step=1024` gives it back (#1651, fixes #1649). Thanks to @gilby. +- Flash Next on RDNA 3.5 iGPUs (gfx1150 to gfx1153) fills prompts in 4,096-row chunks by default on one GPU, falling back to 1,024 when the larger chunk would admit fewer streams. Tokens are unchanged (#1651, fixes #1649). Thanks to @gilby. - CUDA's Qwen DFlash2 drafters must declare sliding attention on every layer (`use_sliding_window` and one `sliding_attention` per layer), which the kernels run, so a drafter declaring a full-attention layer is refused before loading instead of running through the sliding ring (#1946, part of #1863). Thanks to @garvrao80. From 9ca1fe3b352cba45cff107789afb205ee3ae2a74 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:39:10 +0000 Subject: [PATCH 03/23] changelog: #2164's line from lines/2164.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7136d47a74f..b729241480b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: the start-up note about pages parked on the kernel's per-CPU lists logs at debug level, so whether it shows no longer depends on the box's memory state; the budget still counts those pages (#2164, follow-up to #2127). Thanks to @jschmied. + - CUDA: the families' sampled rule comes from one function, `cuda.sample.ruleFor`, in place of seven copies (MiniMax M3's hand-filled `Rule` included); a host test checks each old form byte for byte over 25,480 settings, and the fatbins are unchanged (#2680, #2460 item 3). Thanks to @jschmied. - Tests: the dense serving and gradient-serving pins follow three sources main changed (the DSpine draft kernels, Flash Next's shared RMS helpers with the same SASS, and its disk-state keys), so `test-qwen-serving-host` and `test-gradient-serving` pass on main again (#2738, refs #2031). @@ -888,7 +890,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - On Ryzen AI Max (RDNA 3.5) GPUs, one- and two-row decode launches use narrower stream tiles, so Qwen3.6-35B-A3B chat decodes about 18% faster with drafts on, and Qwen3.8-27B about 5% faster, with the same tokens (#1855). Thanks to @AbrahamCete. -- Flash Next on RDNA 3.5 iGPUs (gfx1150 to gfx1153) fills prompts in 4,096-row chunks by default on one GPU, falling back to 1,024 when the larger chunk would admit fewer streams. Tokens are unchanged (#1651, fixes #1649). Thanks to @gilby. - CUDA's Qwen DFlash2 drafters must declare sliding attention on every layer (`use_sliding_window` and one `sliding_attention` per layer), which the kernels run, so a drafter declaring a full-attention layer is refused before loading instead of running through the sliding ring (#1946, part of #1863). Thanks to @garvrao80. From 7c16585c326960c4995a62e60378289db3d851f6 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:00:14 +0000 Subject: [PATCH 04/23] feat(cuda): prompt attention at two query heads a block dots.mocr (12 heads over 2 of 128), GLM-OCR (16 over 8 of 128) and Nemotron Parse (16 over 8 of 64) have groups the existing prompt instances cannot split, so pattn_kernel gains HPC 2 instances at head dims 128 and 64. Each layout, and paged decode at head 128, gets a contract entry with a planted control, the new launches and the merge_segs launch get records for five SMs, and the paged-attention contract's geometry test runs on the host. Existing kernels keep their SASS: the wide segs path's control switch folds away. --- zig/build/cuda_row_contracts.zig | 2 +- zig/kernels/cuda/contract_controls_set.cu | 1 + zig/kernels/cuda/contract_dense_controls.cuh | 44 ++++++++++++++ zig/kernels/cuda/paged_attn_segs.cuh | 4 +- zig/kernels/cuda/prefill_attention.cu | 8 +++ .../core/contract/dense_attention_records.zig | 16 ++++++ zig/src/core/contract/paging_pending.zig | 1 + zig/src/core/contract/registry_joins.zig | 3 +- zig/tests/cuda/contract_paged_attn.zig | 57 ++++++++++++++++++- 9 files changed, 130 insertions(+), 6 deletions(-) create mode 100644 zig/kernels/cuda/contract_dense_controls.cuh create mode 100644 zig/src/core/contract/dense_attention_records.zig diff --git a/zig/build/cuda_row_contracts.zig b/zig/build/cuda_row_contracts.zig index 42a25a5e7d6..f4192da3771 100644 --- a/zig/build/cuda_row_contracts.zig +++ b/zig/build/cuda_row_contracts.zig @@ -12,7 +12,7 @@ pub fn host(b: *std.Build, target: std.Build.ResolvedTarget, cuda: *std.Build.Mo step.dependOn(&radio_run.step); const stress = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_group_stress_host.zig"), .target = target, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); b.step("test-group-sums-stress-host", "Actual group-sum stress inputs distinguish reduced sums at every seed").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = stress })).step); - for ([_][]const u8{ "contract_norms_tail.zig", "contract_l2.zig", "contract_act_round.zig", "contract_embed.zig", "contract_qk_round.zig", "contract_window_rows.zig", "contract_hc_mix.zig", "contract_qk_l2.zig", "contract_act_l2.zig", "shared_rows_abi_host.zig" }) |name| { + for ([_][]const u8{ "contract_norms_tail.zig", "contract_l2.zig", "contract_act_round.zig", "contract_embed.zig", "contract_qk_round.zig", "contract_window_rows.zig", "contract_hc_mix.zig", "contract_qk_l2.zig", "contract_act_l2.zig", "contract_paged_attn.zig", "shared_rows_abi_host.zig" }) |name| { const m = b.createModule(.{ .root_source_file = b.path(b.pathJoin(&.{ "zig/tests/cuda", name })), .target = target, diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index ef7312fd864..e4608a5b9f7 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -2,3 +2,4 @@ #include "contract_controls.cu" #include "contract_js_controls.cuh" +#include "contract_dense_controls.cuh" diff --git a/zig/kernels/cuda/contract_dense_controls.cuh b/zig/kernels/cuda/contract_dense_controls.cuh new file mode 100644 index 00000000000..b2780f96962 --- /dev/null +++ b/zig/kernels/cuda/contract_dense_controls.cuh @@ -0,0 +1,44 @@ +// Planted controls for the dense decoders' prompt rows: pattn at two heads a block, values from the next lane's dims. + +// Included by contract_controls_set.cu after contract_controls.cu, whose PATTN_VLANE fault and headers it reuses. + +namespace tf_prefill_attention { +extern "C" __global__ void __launch_bounds__(256, 1) tf_ctl_pattn_128_hpc2(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc, + const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, + int W, int H, int HK, int G, float scale, const int* __restrict__ PT, long long PS) { + constexpr int D = 128, WARPS = 8, HPC = 2, NS = 8; + constexpr bool causal = true; + constexpr int skip = 0; + constexpr bool P256 = false, HPAGED = false, F8 = false, HM = false, IDS = false; + constexpr int CAP = 0, PTOK = 1, PN = 0; + const float *ks = nullptr, *vs = nullptr; + const int HO = H; + auto first_row = [] { return blockIdx.x * 16 * (WARPS / HPC); }; +#include "prefill_attention_rows.cuh" +} + +extern "C" __global__ void __launch_bounds__(256, 1) tf_ctl_pattn_64_hpc2(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc, + const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, + int W, int H, int HK, int G, float scale, const int* __restrict__ PT, long long PS) { + constexpr int D = 64, WARPS = 8, HPC = 2, NS = 8; + constexpr bool causal = true; + constexpr int skip = 0; + constexpr bool P256 = false, HPAGED = false, F8 = false, HM = false, IDS = false; + constexpr int CAP = 0, PTOK = 1, PN = 0; + const float *ks = nullptr, *vs = nullptr; + const int HO = H; + auto first_row = [] { return blockIdx.x * 16 * (WARPS / HPC); }; +#include "prefill_attention_rows.cuh" +} +} // namespace tf_prefill_attention + +// Paged decode at head 128 (Nemotron's segs body), one planted fault: values from the neighbouring lane's dims. +namespace tf_ctl_paged { +#define SEG_HD 128 +#define SEG_KW (128 / 2 + 2) +#define SEG_WIDE 1 +#define SEG_VLANE 1 +#define SEG_CHUNK tf_ctl_nemo_attn_chunk_segs +#define SEG_MERGE tf_ctl_nemo_attn_merge_segs +#include "paged_attn_segs.cuh" +} // namespace tf_ctl_paged diff --git a/zig/kernels/cuda/paged_attn_segs.cuh b/zig/kernels/cuda/paged_attn_segs.cuh index 5a18303cb40..6ff3f1919c7 100644 --- a/zig/kernels/cuda/paged_attn_segs.cuh +++ b/zig/kernels/cuda/paged_attn_segs.cuh @@ -2,7 +2,7 @@ #define SEG_E (SEG_WIDE ? 8 : 4) #ifndef SEG_VLANE -#define SEG_VLANE 0 // 1 in contract_controls.cu only: the narrow form reads its values from the neighbouring lane's dims +#define SEG_VLANE 0 // 1 in the planted controls only: values from the neighbouring lane's dims #endif extern "C" __global__ void __launch_bounds__(256) SEG_CHUNK(const AttnSegs sg, const __nv_bfloat16* __restrict__ QKV, @@ -79,7 +79,7 @@ extern "C" __global__ void __launch_bounds__(256) SEG_CHUNK(const AttnSegs sg, c for (int j = 0; j < TILE; ++j) { const float p = ps[g][j]; #if SEG_WIDE - const uint4 v = *reinterpret_cast(&vw[j][4 * jj]); + const uint4 v = *reinterpret_cast(&vw[j][4 * (jj ^ SEG_VLANE)]); const uint32_t vv[4] = {v.x, v.y, v.z, v.w}; #pragma unroll for (int e = 0; e < 4; ++e) { diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index bc2d36eac09..1c6e0f073df 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -318,6 +318,14 @@ template __global__ void tf_prefill_attention::pattn_kernel<128, 8, 8, 8>(const template __global__ void tf_prefill_attention::pattn_kernel<64, 8, 4, 8>(const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, int, int, int, float, const int* __restrict__, long long); +// Head dim 128, eight warps, two query heads a block, eight staging slots (dense OCR decoders: 2 or 6 heads a KV head). +template __global__ void tf_prefill_attention::pattn_kernel<128, 8, 2, 8>(const __nv_bfloat16* __restrict__, + const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, int, + int, int, float, const int* __restrict__, long long); +// Head dim 64, eight warps, two query heads a block, eight staging slots (dense OCR decoders: 2 heads a KV head). +template __global__ void tf_prefill_attention::pattn_kernel<64, 8, 2, 8>(const __nv_bfloat16* __restrict__, + const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, int, + int, int, float, const int* __restrict__, long long); // Head dim 64, eight warps, four query heads a block, eight staging slots (LFM2's 4 heads a KV head, causal or trees). template __global__ void tf_prefill_attention::tree_kernel<64, 8, 4, 8>(const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, const int* __restrict__, int, int, int, int, int, float); diff --git a/zig/src/core/contract/dense_attention_records.zig b/zig/src/core/contract/dense_attention_records.zig new file mode 100644 index 00000000000..7e743949a35 --- /dev/null +++ b/zig/src/core/contract/dense_attention_records.zig @@ -0,0 +1,16 @@ +//! The dense OCR decoders' prompt rows: pattn_kernel at two query heads a block, head 128 and 64, every SM (nvcc 13.0). +const std = @import("std"); +const registry = @import("registry.zig"); +const R = registry.CudaRecord; + +const hpc2_128 = "_ZN20tf_prefill_attention12pattn_kernelILi128ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifPKix"; +const hpc2_64 = "_ZN20tf_prefill_attention12pattn_kernelILi64ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifPKix"; + +pub const cuda = [_]R{ + .{ .launch = .{ .name = "dense pattn128 hpc2", .image = "prefill_attention", .symbol = hpc2_128, .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "dense pattn64 hpc2", .image = "prefill_attention", .symbol = hpc2_64, .threads = 256, .dynamic = 32768, .opt_in = true }, .usage = .{ .{ .regs = 148, .static = 0, .bound = 256 }, .{ .regs = 148, .static = 0, .bound = 256 }, .{ .regs = 148, .static = 0, .bound = 256 }, .{ .regs = 164, .static = 0, .bound = 256 }, .{ .regs = 164, .static = 0, .bound = 256 } } }, +}; + +test "dense attention records: every launch fits every SM by its measured record" { + for (cuda) |r| try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); +} diff --git a/zig/src/core/contract/paging_pending.zig b/zig/src/core/contract/paging_pending.zig index a9cadf1048c..d1749611d4c 100644 --- a/zig/src/core/contract/paging_pending.zig +++ b/zig/src/core/contract/paging_pending.zig @@ -8,6 +8,7 @@ pub const extra = [_]R{ .{ .launch = .{ .name = "paging tf_nemo_attn_chunk", .image = "nemotron_attention", .symbol = "tf_nemo_attn_chunk", .threads = 256 }, .usage = .{ .{ .regs = 76, .static = 45568, .bound = 256 }, .{ .regs = 91, .static = 45568, .bound = 256 }, .{ .regs = 91, .static = 45568, .bound = 256 }, .{ .regs = 118, .static = 45568, .bound = 256 }, .{ .regs = 118, .static = 45568, .bound = 256 } } }, .{ .launch = .{ .name = "paging tf_nemo_attn_chunk_pf", .image = "nemotron_attention", .symbol = "tf_nemo_attn_chunk_pf", .threads = 256 }, .usage = .{ .{ .regs = 128, .static = 45568, .bound = 256 }, .{ .regs = 128, .static = 45568, .bound = 256 }, .{ .regs = 128, .static = 45568, .bound = 256 }, .{ .regs = 128, .static = 45568, .bound = 256 }, .{ .regs = 128, .static = 45568, .bound = 256 } } }, .{ .launch = .{ .name = "paging tf_nemo_attn_chunk_segs", .image = "nemotron_attention", .symbol = "tf_nemo_attn_chunk_segs", .threads = 256 }, .usage = .{ .{ .regs = 78, .static = 45568, .bound = 256 }, .{ .regs = 97, .static = 45568, .bound = 256 }, .{ .regs = 97, .static = 45568, .bound = 256 }, .{ .regs = 120, .static = 45568, .bound = 256 }, .{ .regs = 120, .static = 45568, .bound = 256 } } }, + .{ .launch = .{ .name = "paging tf_nemo_attn_merge_segs", .image = "nemotron_attention", .symbol = "tf_nemo_attn_merge_segs", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 35, .static = 8192, .bound = 256 }, .{ .regs = 37, .static = 8192, .bound = 256 } } }, .{ .launch = .{ .name = "paging pattn128", .image = "prefill_attention", .symbol = "_ZN20tf_prefill_attention12pattn_kernelILi128ELi8ELi8ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifPKix", .threads = 256, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 206, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 } } }, }; test "paging records: every paging launch fits every SM by its measured record" { diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 7b19de3d6b9..e3f0e8ccc23 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -19,7 +19,8 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("moss_image_cuda_records.zig").cuda ++ @import("exl3_dense_records.zig").cuda ++ @import("exl3_finish_records.zig").cuda ++ - @import("lfm2_moe_cuda_records.zig").cuda; + @import("lfm2_moe_cuda_records.zig").cuda ++ + @import("dense_attention_records.zig").cuda; pub const nvcc_132_after = @import("registry_learning.zig").cuda_132 ++ @import("paging_pending.zig").cuda_132 ++ @import("lfm2_moe_cuda_records.zig").cuda_132 ++ diff --git a/zig/tests/cuda/contract_paged_attn.zig b/zig/tests/cuda/contract_paged_attn.zig index ff5fceaa19e..e45641cc54f 100644 --- a/zig/tests/cuda/contract_paged_attn.zig +++ b/zig/tests/cuda/contract_paged_attn.zig @@ -36,6 +36,46 @@ pub const cfgs = [_]Cfg{ .{ .name = "control: paged decode at head 64 reading its values from the neighbouring lane's dims", .h = 32, .hk = 8, .d = 64, .form = .{ .decode = .{ .chunk = "tf_ctl_paged_attn_chunk_segs_64", .merge = "tf_paged_attn_merge_segs_64" } }, .control = true, .served = &decode_served }, .{ .name = "cuda paged prompt pattn_kernel<64, 8, 4, 8>, 32/8 heads of 64, 512-key pages", .h = 32, .hk = 8, .d = 64, .form = prompt64, .served = &prompt_served }, .{ .name = "control: paged prompt rows at head 64 reading their values from the neighbouring 8 dims", .h = 32, .hk = 8, .d = 64, .form = .{ .prompt = .{ .sym = "tf_ctl_pattn_64", .rows = 32, .smem = 8 * 32 * 8 * 16 } }, .control = true, .served = &prompt_served }, +} ++ dense.cfgs; + +/// The dense OCR decoders' layouts: two query heads a block at head 128 (groups 6 and 2) and 64 (group 2). +const dense = struct { + const hpc2_128 = "_ZN20tf_prefill_attention12pattn_kernelILi128ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifPKix"; + const hpc2_64 = "_ZN20tf_prefill_attention12pattn_kernelILi64ELi8ELi2ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifPKix"; + const p128: Form = .{ .prompt = .{ .sym = hpc2_128, .rows = 64, .smem = 8 * 32 * 16 * 16 } }; + const p64: Form = .{ .prompt = .{ .sym = hpc2_64, .rows = 64, .smem = 8 * 32 * 8 * 16 } }; + const c128: Form = .{ .prompt = .{ .sym = "tf_ctl_pattn_128_hpc2", .rows = 64, .smem = 8 * 32 * 16 * 16 } }; + const c64: Form = .{ .prompt = .{ .sym = "tf_ctl_pattn_64_hpc2", .rows = 64, .smem = 8 * 32 * 8 * 16 } }; + const d128: Form = .{ .decode = .{ .chunk = "tf_nemo_attn_chunk_segs", .merge = "tf_nemo_attn_merge_segs" } }; + const dctl: Form = .{ .decode = .{ .chunk = "tf_ctl_nemo_attn_chunk_segs", .merge = "tf_nemo_attn_merge_segs" } }; + + /// The file's prompt and decode shapes at `h` query heads, and one whole 1024-row prompt chunk from key 0. + fn prompt(comptime h: usize) [4]c.Shape { + return .{ .{ .rows = 256, .n = h, .k = 0 }, .{ .rows = 64, .n = h, .k = 3000 }, .{ .rows = 100, .n = h, .k = 500 }, .{ .rows = 1024, .n = h, .k = 0 } }; + } + fn decode(comptime h: usize) [4]c.Shape { + return .{ .{ .rows = 1, .n = h, .k = 3000 }, .{ .rows = 16, .n = h, .k = 1500 }, .{ .rows = 128, .n = h, .k = 700 }, .{ .rows = 8, .n = h, .k = 4000 } }; + } + const prompt12 = prompt(12); + const prompt16 = prompt(16); + const decode12 = decode(12); + const decode16 = decode(16); + + const cfgs = [_]Cfg{ + // dots.mocr: 12 query heads over 2 KV heads of 128 + .{ .name = "cuda paged prompt pattn_kernel<128, 8, 2, 8>, 12/2 heads of 128, 512-key pages", .h = 12, .hk = 2, .d = 128, .form = p128, .served = &prompt12 }, + .{ .name = "control: paged prompt rows at head 128, two heads a block, 12/2, values from the neighbouring 8 dims", .h = 12, .hk = 2, .d = 128, .form = c128, .control = true, .served = &prompt12 }, + .{ .name = "cuda paged decode tf_nemo_attn_chunk_segs + tf_nemo_attn_merge_segs, 12/2 heads of 128, 512-key pages", .h = 12, .hk = 2, .d = 128, .form = d128, .served = &decode12 }, + .{ .name = "control: paged decode at head 128, 12/2, values from the neighbouring lane's dims", .h = 12, .hk = 2, .d = 128, .form = dctl, .control = true, .served = &decode12 }, + // GLM-OCR: 16 query heads over 8 KV heads of 128 + .{ .name = "cuda paged prompt pattn_kernel<128, 8, 2, 8>, 16/8 heads of 128, 512-key pages", .h = 16, .hk = 8, .d = 128, .form = p128, .served = &prompt16 }, + .{ .name = "control: paged prompt rows at head 128, two heads a block, 16/8, values from the neighbouring 8 dims", .h = 16, .hk = 8, .d = 128, .form = c128, .control = true, .served = &prompt16 }, + .{ .name = "cuda paged decode tf_nemo_attn_chunk_segs + tf_nemo_attn_merge_segs, 16/8 heads of 128, 512-key pages", .h = 16, .hk = 8, .d = 128, .form = d128, .served = &decode16 }, + .{ .name = "control: paged decode at head 128, 16/8, values from the neighbouring lane's dims", .h = 16, .hk = 8, .d = 128, .form = dctl, .control = true, .served = &decode16 }, + // Nemotron Parse: 16 query heads over 8 KV heads of 64 + .{ .name = "cuda paged prompt pattn_kernel<64, 8, 2, 8>, 16/8 heads of 64, 512-key pages", .h = 16, .hk = 8, .d = 64, .form = p64, .served = &prompt16 }, + .{ .name = "control: paged prompt rows at head 64, two heads a block, 16/8, values from the neighbouring 8 dims", .h = 16, .hk = 8, .d = 64, .form = c64, .control = true, .served = &prompt16 }, + }; }; /// Gates 1 and 3 run attention_ref's bound: decode weights are fp32 through fast exp, prompt P enters the mma as bf16. @@ -337,8 +377,21 @@ pub const Set = struct { } }; -test "the paged forms' geometry: 4 query heads a KV head, AttnSegs as nemotron_attention.cu pads it" { +test "the paged forms' geometry: whole groups a block, groups the decode kernels take, AttnSegs as nemotron_attention.cu pads it" { try std.testing.expectEqual(@as(usize, 304), @sizeOf(AttnSegs)); - for (cfgs) |f| try std.testing.expectEqual(@as(usize, 4), f.h / f.hk); try std.testing.expectEqual(@as(usize, 32), prompt64.prompt.rows); + for (cfgs) |f| { + const group = f.h / f.hk; + try std.testing.expectEqual(f.h, group * f.hk); + for (f.served) |s| try std.testing.expectEqual(f.h, s.n); + switch (f.form) { + .prompt => |p| { // a block's query heads, 16 rows a warp over eight warps, divide the group + const hpc = 16 * 8 / p.rows; + try std.testing.expect(hpc == 1 or hpc == 2 or hpc == 4 or hpc == 8); + try std.testing.expectEqual(@as(usize, 0), group % hpc); + try std.testing.expectEqual(@as(u32, @intCast(8 * 32 * ((f.d / 8 + 7) / 8 * 8) * 16)), p.smem); + }, + .decode => try std.testing.expect(group <= 16), // paged_attn.cuh's GMAX + } + } } From 39061aa9f86dfe5af3a84588c6ab011b354a4b8c Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:16:13 +0000 Subject: [PATCH 05/23] docs(changelog): the two-heads-a-block prompt attention The changelog gains the line for #2609: the new pattn_kernel instances for the three OCR decoders' head layouts, their contract entries and records, and that no served kernel's code changes. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b729241480b..57eb0ad118d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Living Weights on Nemotron (`--slide`): a lesson's pocket goes only into the layers whose subject rows carry it and that pass the full verifier, and the neurons it needs are shrunk to what passes; a rejected shrink restores the exact rows and count. A correction overturns a shipped answer with an explicit additive fit and checked deletion of the original, and one that depends on an earlier pocket is refused by fact before fitting. Pretrained weights and kernels are unchanged, and serving without `--slide` is unchanged. `TF_SLIDE_POCKET_DUMP` is read through the environment table: blank means no dump, and a path with a control character is refused at startup (#2025, part of #1968). - Server: `--unix-socket PATH` serves on a new owner-only Unix socket instead of TCP, so a local client reaches the server without its requests crossing a network interface. It refuses an existing path, a parent directory others can write to (unless sticky) and the TCP-only flags, checks each peer's user, and is refused on Windows (#2389). Thanks to @kotevcode. +- CUDA kernels: `pattn_kernel` gains instances at two query heads a block for head dims 128 and 64, the prompt attention that dots.mocr (12 heads over 2), GLM-OCR (16 over 8) and Nemotron Parse (16 over 8) need on CUDA, with contract entries, planted controls and records for five SMs; paged decode at head 128 gets contract entries at those layouts and `tf_nemo_attn_merge_segs` its record. No served kernel's code changes (#2609, part of #1927). Thanks to @laudney. - CUDA EXL3 experts: a second finish kernel clamps silu's output, `min(silu(g), L) · clip(u, −L, L)` (Ling-3.1's order), when a layer asks for it. Every other format, and bf16 or SwiGLU-OAI activations, refuse it before launch, and existing EXL3 models are unchanged (#2336). Thanks to @ajensenwaud. From de825ffb3d50ec97249445a683715942f9aea65b Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:54:33 +0000 Subject: [PATCH 06/23] fix(contract): merge_segs records for nvcc 13.2 and 13.3 tf_nemo_attn_merge_segs compiles to fewer registers under later compilers: nvcc 13.2 gives sm_121 35 where 13.0 gives 37, and 13.3 gives sm_120 and sm_121 34 each. Each release's set now carries its own usage, so trees built by those compilers check against their own records; both prompt attention instances compile alike on all three. --- zig/src/core/contract/paging_pending.zig | 8 +++++++- zig/src/core/contract/registry_joins.zig | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/zig/src/core/contract/paging_pending.zig b/zig/src/core/contract/paging_pending.zig index d1749611d4c..0c4a26e66c9 100644 --- a/zig/src/core/contract/paging_pending.zig +++ b/zig/src/core/contract/paging_pending.zig @@ -15,7 +15,13 @@ test "paging records: every paging launch fits every SM by its measured record" for (extra) |r| try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); } -/// The paging launch nvcc 13.2 compiles differently, from every SM's image. +/// The paging launches nvcc 13.2 compiles differently, from every SM's image. pub const cuda_132 = [_]@import("registry.zig").Override{ .{ .name = "paging tf_nemo_attn_chunk_segs", .usage = .{ .{ .regs = 78, .static = 45568, .bound = 256 }, .{ .regs = 97, .static = 45568, .bound = 256 }, .{ .regs = 97, .static = 45568, .bound = 256 }, .{ .regs = 118, .static = 45568, .bound = 256 }, .{ .regs = 118, .static = 45568, .bound = 256 } } }, + .{ .name = "paging tf_nemo_attn_merge_segs", .usage = .{ .{ .regs = 32, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 35, .static = 8192, .bound = 256 }, .{ .regs = 35, .static = 8192, .bound = 256 } } }, +}; + +/// The paging launch nvcc 13.3 compiles differently from 13.2, from every SM's image. +pub const cuda_133 = [_]@import("registry.zig").Override{ + .{ .name = "paging tf_nemo_attn_merge_segs", .usage = .{ .{ .regs = 32, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 39, .static = 8192, .bound = 256 }, .{ .regs = 34, .static = 8192, .bound = 256 }, .{ .regs = 34, .static = 8192, .bound = 256 } } }, }; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index e3f0e8ccc23..3b629408490 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -35,7 +35,8 @@ pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++ @import("glm_cuda_records.zig").cuda_133 ++ @import("nvcc_133_records.zig").cuda_133 ++ @import("minimax_cuda_records.zig").cuda_133 ++ - @import("nvfp4_experts32_records.zig").cuda_133; + @import("nvfp4_experts32_records.zig").cuda_133 ++ + @import("paging_pending.zig").cuda_133; pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("cuda_lane_pending.zig").records ++ @import("weight_only_records.zig").cuda ++ From b92c0e7976d86a0ebbda29ed5b73a5a8f88cc0d6 Mon Sep 17 00:00:00 2001 From: Anders Jensen-Waud Date: Fri, 6 Nov 2026 07:45:17 +1100 Subject: [PATCH 07/23] cuda kda: refuse a model's KDA shape other than the kernels' before launch kda.geometry(key_dim, value_dim, conv_taps) returns error.KdaGeometry unless the model's heads are the kernels' 128 keys and 128 values and its conv window has kda.cuh's 4 taps, so a family calls it at load, before any allocation or launch (#874's review: unsupported head widths and tap counts refused up front). kda.taps names TAPS beside dk and dv. No kernel or launch changes; GLM's bytes are untouched. Part of #850, stacked on #2142. --- zig/src/cuda/kda.zig | 7 +++++++ zig/src/cuda/kda_test.zig | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/zig/src/cuda/kda.zig b/zig/src/cuda/kda.zig index 3ea9a872762..374413014b5 100644 --- a/zig/src/cuda/kda.zig +++ b/zig/src/cuda/kda.zig @@ -5,9 +5,16 @@ const cuda = @import("root.zig"); pub const dk = 128; pub const dv = 128; +/// The conv window's taps (kda.cuh TAPS): three kept rows and the current one. +pub const taps = 4; /// Windows of this many rows or more (prefill chunks) take the three-kernel chain (kda.WIDE_ROWS). pub const wide_rows = 64; +/// A model's KDA shape against the one the kernels are built for, refused before anything is allocated or launched. +pub fn geometry(key_dim: usize, value_dim: usize, conv_taps: usize) error{KdaGeometry}!void { + if (key_dim != dk or value_dim != dv or conv_taps != taps) return error.KdaGeometry; +} + /// glm_kda.cu's entries. pub const Kernels = struct { chain: cuda.Function, diff --git a/zig/src/cuda/kda_test.zig b/zig/src/cuda/kda_test.zig index d36b0c96156..c316bca4cc6 100644 --- a/zig/src/cuda/kda_test.zig +++ b/zig/src/cuda/kda_test.zig @@ -120,3 +120,9 @@ test "shared KDA: malformed geometry refuses before the driver is touched" { try std.testing.expectError(error.KdaShape, kda.replayLayers(&ks, stream, undefined, 1, 1, 0)); try std.testing.expectEqual(@as(usize, 0), Capture.count); } + +test "shared KDA: a model's head widths and conv taps other than the kernels' are refused" { + try kda.geometry(128, 128, 4); + for ([_][3]usize{ .{ 64, 128, 4 }, .{ 128, 64, 4 }, .{ 256, 256, 4 }, .{ 128, 128, 3 }, .{ 128, 128, 5 }, .{ 0, 0, 0 } }) |g| + try std.testing.expectError(error.KdaGeometry, kda.geometry(g[0], g[1], g[2])); +} From 4b0adc910e957d1db4d5f2ac9ebc7c92c2700e7b Mon Sep 17 00:00:00 2001 From: Anders Jensen-Waud Date: Sun, 8 Nov 2026 10:36:27 +1100 Subject: [PATCH 08/23] cuda kda: review: dk, dv and taps held to kda.cuh's DK, DV and TAPS by a host test zig/kda_header_host.zig builds kda.cuh's constant line from kda.dk, kda.dv and kda.taps and requires it in the header, so a kernel change to any of them fails test-kda-host until kda.zig and its geometry refusal follow. dk and dv name kda.cuh's DK and DV. With TAPS set to 5 in kda.cuh alone, the new test fails and the 19 shared KDA tests still pass. --- zig/build/glm_family_host.zig | 7 ++++++- zig/kda_header_host.zig | 8 ++++++++ zig/src/cuda/kda.zig | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 zig/kda_header_host.zig diff --git a/zig/build/glm_family_host.zig b/zig/build/glm_family_host.zig index 90e9b79a08e..4b8b92b8d59 100644 --- a/zig/build/glm_family_host.zig +++ b/zig/build/glm_family_host.zig @@ -21,7 +21,12 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, glm: *std.Build.Module, mod const warm_run = b.addRunArtifact(b.addTest(.{ .root_module = warm, .filters = &.{"GLM warm peers:"} })); b.step("test-glm-warm-peers-host", "Selected GLM warm-up peers and NCCL posting failures without devices").dependOn(&warm_run.step); step.dependOn(&warm_run.step); - b.step("test-kda-host", "Shared KDA launch ABI against its frozen predecessor, without CUDA execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"shared KDA:"} })).step); + const kda = b.step("test-kda-host", "Shared KDA launch ABI against its frozen predecessor, without CUDA execution"); + kda.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"shared KDA:"} })).step); + const kda_header = b.createModule(.{ .root_source_file = b.path("zig/kda_header_host.zig"), .target = host, .optimize = .debug, .imports = &.{.{ .name = "cuda", .module = cuda }} }); + const kda_header_run = b.addRunArtifact(b.addTest(.{ .root_module = kda_header })); + kda.dependOn(&kda_header_run.step); + step.dependOn(&kda_header_run.step); const startup = b.createModule(.{ .root_source_file = b.path("zig/src/families/glm/cuda_start_test.zig"), .target = host, .optimize = .debug }); const startup_run = b.addRunArtifact(b.addTest(.{ .root_module = startup })); b.step("test-glm-startup-host", "Page refusals propagate through rank liveness before engine construction").dependOn(&startup_run.step); diff --git a/zig/kda_header_host.zig b/zig/kda_header_host.zig new file mode 100644 index 00000000000..d54ae8ed411 --- /dev/null +++ b/zig/kda_header_host.zig @@ -0,0 +1,8 @@ +//! Shared KDA's widths in Zig against kda.cuh's, so a kernel change cannot leave kda.geometry's refusal behind. +const std = @import("std"); +const kda = @import("cuda").kda; + +test "shared KDA: kda.zig's dk, dv and taps are kda.cuh's DK, DV and TAPS" { + const line = std.fmt.comptimePrint("constexpr int DK = {d}, DV = {d}, TAPS = {d};", .{ kda.dk, kda.dv, kda.taps }); + try std.testing.expect(std.mem.indexOf(u8, @embedFile("kernels/cuda/common/kda.cuh"), line) != null); +} diff --git a/zig/src/cuda/kda.zig b/zig/src/cuda/kda.zig index 374413014b5..8592962f054 100644 --- a/zig/src/cuda/kda.zig +++ b/zig/src/cuda/kda.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("root.zig"); +/// Key and value channels a head (kda.cuh DK, DV); zig/kda_header_host.zig holds these and taps to the header. pub const dk = 128; pub const dv = 128; /// The conv window's taps (kda.cuh TAPS): three kept rows and the current one. From cd30646ca82889b298330f04a8c52697f9aeb012 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:39:14 +0000 Subject: [PATCH 09/23] changelog: #2338 under Unreleased --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57eb0ad118d..2fef174fe1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CUDA: a model whose KDA heads or conv window differ from the kernels' (128 keys, 128 values, 4 taps) is refused at load with `KdaGeometry`, before anything is allocated or launched, and a host test ties those numbers to `kda.cuh` (#2338, refs #850). Thanks to @ajensenwaud. + + - CUDA: the start-up note about pages parked on the kernel's per-CPU lists logs at debug level, so whether it shows no longer depends on the box's memory state; the budget still counts those pages (#2164, follow-up to #2127). Thanks to @jschmied. - CUDA: the families' sampled rule comes from one function, `cuda.sample.ruleFor`, in place of seven copies (MiniMax M3's hand-filled `Rule` included); a host test checks each old form byte for byte over 25,480 settings, and the fatbins are unchanged (#2680, #2460 item 3). Thanks to @jschmied. From 91fd1c84994e08469a4ceee93b345018f8947e3c Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:50:42 -0800 Subject: [PATCH 10/23] fabric/tp: in-process ranks on one GPU, so tests can run more ranks than devices NCCL refuses two ranks on one device, and host.zig's in-process ranks read host memory, so no test could run three ranks' exchanges on one GPU. tp.device keeps host.zig's rendezvous (Group.enter and meet, now public) and moves bytes with device copies. Each call syncs its caller's stream and returns with its copies done, so a capturing stream is refused. Its exchange and send/recv are pairwise, with a count per slot: the rank without a partner at an odd world goes on to the next collective, and a recv never takes a previous post. tf-tp-test device runs gpu_checks' collectives and send/recv on 2, 3 and 4 in-process ranks of one GPU against the rank-order reference (Ctx.rank_order), without graphs. --- zig/src/fabric/tp/collective.zig | 2 +- zig/src/fabric/tp/device.zig | 312 ++++++++++++++++++++++++++++ zig/src/fabric/tp/device_test.zig | 151 ++++++++++++++ zig/src/fabric/tp/gpu_checks.zig | 4 +- zig/src/fabric/tp/gpu_cli.zig | 19 +- zig/src/fabric/tp/gpu_main.zig | 40 +++- zig/src/fabric/tp/host.zig | 31 +-- zig/src/fabric/tp/host_test.zig | 24 +-- zig/src/fabric/tp/portable_test.zig | 1 + zig/src/fabric/tp/tp.zig | 2 + 10 files changed, 548 insertions(+), 38 deletions(-) create mode 100644 zig/src/fabric/tp/device.zig create mode 100644 zig/src/fabric/tp/device_test.zig diff --git a/zig/src/fabric/tp/collective.zig b/zig/src/fabric/tp/collective.zig index 60eefd11ab8..3feb0db6f7d 100644 --- a/zig/src/fabric/tp/collective.zig +++ b/zig/src/fabric/tp/collective.zig @@ -30,7 +30,7 @@ pub const DType = enum(u8) { pub const Op = enum(u8) { sum, max, min }; /// Which implementation is behind a `Collective` (logs, bench labels). -pub const Kind = enum { nccl, mailbox, hybrid, roce, host }; +pub const Kind = enum { nccl, mailbox, hybrid, roce, host, device }; pub const Collective = struct { ptr: *anyopaque, diff --git a/zig/src/fabric/tp/device.zig b/zig/src/fabric/tp/device.zig new file mode 100644 index 00000000000..6eff6202edc --- /dev/null +++ b/zig/src/fabric/tp/device.zig @@ -0,0 +1,312 @@ +//! In-process ranks on one GPU, for tests (NCCL refuses two ranks on a device): host.zig's rendezvous, device copies. +const std = @import("std"); +const cuda = @import("cuda"); +const collective = @import("collective.zig"); +const host = @import("host.zig"); +const reference = @import("reference.zig"); +const DevicePtr = collective.DevicePtr; +const Stream = collective.Stream; +const DType = collective.DType; +const Op = collective.Op; +const Error = collective.Error; + +pub const max_ranks = host.max_ranks; + +/// One-way messages from one rank to another. Each count has one writer, so a receiver never reads an old post. +const Slot = struct { + buf: DevicePtr = 0, + bytes: usize = 0, + posted: std.atomic.Value(u64) = .init(0), + taken: std.atomic.Value(u64) = .init(0), +}; + +pub const Group = struct { + base: host.Group, + d: *const cuda.Driver, + gpa: std.mem.Allocator, + /// Each rank's `all_gather_v` lengths, read back from the device before it posts. + lens: [max_ranks][max_ranks]i32 = @splat(@splat(0)), + /// Each rank's `varFits(16)`, for `varAgreed`. + fits: [max_ranks]bool = @splat(false), + slots: [max_ranks][max_ranks]Slot = @splat(@splat(.{})), + + pub fn init(d: *const cuda.Driver, gpa: std.mem.Allocator, world: u32) Group { + return .{ .base = host.Group.init(world), .d = d, .gpa = gpa }; + } + + pub fn rank(g: *Group, r: u32) Rank { + std.debug.assert(r < g.base.world); + return .{ .group = g, .me = r }; + } +}; + +/// Each call syncs its caller's stream and returns with its copies done: not stream-ordered, and never captured. +pub const Rank = struct { + group: *Group, + me: u32, + /// `varAgreed`'s answer, once this communicator agreed. + var_agreed: ?bool = null, + + pub fn iface(self: *Rank) collective.Collective { + return .{ .ptr = self, .vtable = &vtable }; + } + + const vtable: collective.Collective.VTable = .{ + .kind = .device, + .rank = rankOf, + .world = worldOf, + .all_reduce = allReduce, + .all_gather = allGather, + .exchange = exchange, + .send = send, + .recv = recv, + .barrier = barrier, + .check = check, + .abort = abort, + .all_gather_v = allGatherV, + .var_fits = varFits, + .var_agreed = varAgreed, + }; + + fn self_(ptr: *anyopaque) *Rank { + return @ptrCast(@alignCast(ptr)); + } + + fn rankOf(ptr: *anyopaque) u32 { + return self_(ptr).me; + } + + fn worldOf(ptr: *anyopaque) u32 { + return self_(ptr).group.base.world; + } + + /// A driver call; a failure aborts every rank, so none waits for this one. + fn call(self: *Rank, res: cuda.abi.Result, what: []const u8) Error!void { + self.group.d.check(res, what) catch { + abort(self); + return error.BackendFailed; + }; + } + + /// The caller's earlier work on `stream` is done, so its buffers hold what it wrote. A capturing stream is refused. + fn ready(self: *Rank, stream: Stream) Error!void { + const d = self.group.d; + var status: cuda.abi.CaptureStatus = .none; + try self.call(d.api.cuStreamIsCapturing(stream, &status), "cuStreamIsCapturing"); + if (status != .none) return error.Unsupported; + try self.finish(stream); + } + + fn finish(self: *Rank, stream: Stream) Error!void { + try self.call(self.group.d.api.cuStreamSynchronize(stream), "cuStreamSynchronize"); + } + + fn copy(self: *Rank, dst: DevicePtr, src: DevicePtr, n: usize, stream: Stream) Error!void { + if (n == 0 or dst == src) return; + try self.call(self.group.d.api.cuMemcpyDtoDAsync_v2(dst, src, n, stream), "cuMemcpyDtoDAsync"); + } + + fn download(self: *Rank, dst: []u8, src: DevicePtr, stream: Stream) Error!void { + if (dst.len == 0) return; + try self.call(self.group.d.api.cuMemcpyDtoHAsync_v2(@ptrCast(dst.ptr), src, dst.len, stream), "cuMemcpyDtoHAsync"); + } + + fn upload(self: *Rank, dst: DevicePtr, src: []const u8, stream: Stream) Error!void { + if (src.len == 0) return; + try self.call(self.group.d.api.cuMemcpyHtoDAsync_v2(dst, @ptrCast(src.ptr), src.len, stream), "cuMemcpyHtoDAsync"); + } + + /// Every rank's input read back and reduced on the host in rank order (`reference.reduce`), then written out. + fn allReduce(ptr: *anyopaque, s: DevicePtr, r: DevicePtr, count: usize, t: DType, op: Op, stream: Stream) Error!void { + const self = self_(ptr); + const g = self.group; + const w = g.base.world; + try self.ready(stream); + try g.base.enter(self.me, .{ .call = .all_reduce, .send = s, .recv = r, .count = count, .t = t, .op = op }); + const n = count * t.size(); + const buf = g.gpa.alloc(u8, n * (w + 1)) catch { + abort(self); + return error.BackendFailed; + }; + defer g.gpa.free(buf); + var ins: [max_ranks][]const u8 = undefined; + for (0..w) |i| { + ins[i] = buf[i * n ..][0..n]; + try self.download(buf[i * n ..][0..n], g.base.posts[i].send, stream); + } + try self.finish(stream); + const out = buf[w * n ..][0..n]; + if (n > 0) reference.reduce(out, ins[0..w], t, op); + // the output may alias an input: every rank has read them all before any rank writes + try g.base.meet(); + try self.upload(r, out, stream); + try self.finish(stream); + try g.base.meet(); + } + + fn allGather(ptr: *anyopaque, s: DevicePtr, r: DevicePtr, count: usize, t: DType, stream: Stream) Error!void { + const self = self_(ptr); + const g = self.group; + try self.ready(stream); + try g.base.enter(self.me, .{ .call = .all_gather, .send = s, .recv = r, .count = count, .t = t }); + const n = count * t.size(); + for (0..g.base.world) |i| try self.copy(r + i * n, g.base.posts[i].send, n, stream); + try self.finish(stream); + try g.base.meet(); + } + + /// Copies only each rank's lens[r] bytes (`var_refuse` ranks take whole strides); unequal lengths are refused. + fn allGatherV(ptr: *anyopaque, s: DevicePtr, r: DevicePtr, stride: usize, lens: DevicePtr, t: DType, stream: Stream) Error!void { + const self = self_(ptr); + const g = self.group; + const w = g.base.world; + try self.ready(stream); + try self.download(std.mem.sliceAsBytes(g.lens[self.me][0..w]), lens, stream); + try self.finish(stream); + try g.base.enter(self.me, .{ .call = .all_gather_v, .send = s, .recv = r, .count = stride, .t = t, .lens = lens }); + const n = stride * t.size(); + const mine = g.lens[self.me][0..w]; + for (0..w) |i| if (!std.mem.eql(i32, mine, g.lens[i][0..w])) { + abort(self); + return error.Invalid; + }; + const whole = g.base.var_refuse & (@as(u32, 1) << @intCast(self.me)) != 0; + for (0..w) |i| { + if (mine[i] < 0 or mine[i] > n) { + abort(self); + return error.Invalid; + } + const len: usize = if (whole) n else @intCast(mine[i]); + try self.copy(r + i * n, g.base.posts[i].send, len, stream); + } + try self.finish(stream); + try g.base.meet(); + } + + fn varFits(ptr: *anyopaque, bytes: usize) bool { + const self = self_(ptr); + return bytes > 0 and self.group.base.var_refuse & (@as(u32, 1) << @intCast(self.me)) == 0; + } + + /// Every rank's `varFits(16)` met once, then the kept answer. + fn varAgreed(ptr: *anyopaque) Error!bool { + const self = self_(ptr); + if (self.var_agreed) |v| return v; + const g = self.group; + g.fits[self.me] = varFits(ptr, 16); + try g.base.enter(self.me, .{ .call = .barrier }); + var all = true; + for (g.fits[0..g.base.world]) |f| all = all and f; + try g.base.meet(); + self.var_agreed = all; + return all; + } + + /// Posts `buf` for `peer` without waiting; `delivered` waits until the peer has copied it. + fn post(self: *Rank, buf: DevicePtr, n: usize, peer: u32) u64 { + const slot = &self.group.slots[self.me][peer]; + slot.buf = buf; + slot.bytes = n; + const k = slot.posted.load(.monotonic) + 1; + slot.posted.store(k, .release); + return k; + } + + fn delivered(self: *Rank, peer: u32, k: u64) Error!void { + const slot = &self.group.slots[self.me][peer]; + try waitFor(self.group, &slot.taken, k); + } + + /// Waits for `peer`'s next post to this rank and copies it into `buf`, finished on return. + fn take(self: *Rank, buf: DevicePtr, n: usize, peer: u32, stream: Stream) Error!void { + const slot = &self.group.slots[peer][self.me]; + const k = slot.taken.load(.monotonic) + 1; + try waitFor(self.group, &slot.posted, k); + if (slot.bytes != n) { + abort(self); + return error.Invalid; + } + try self.copy(buf, slot.buf, n, stream); + try self.finish(stream); + slot.taken.store(k, .release); + } + + fn waitFor(g: *Group, count: *std.atomic.Value(u64), want: u64) Error!void { + const t0 = host.now(); + while (count.load(.acquire) < want) { + if (g.base.aborted.load(.acquire)) return error.Aborted; + if (host.now() - t0 > g.base.timeout_ns) return error.Timeout; + std.Thread.yield() catch {}; + } + } + + /// Two ranks trade without the others, as NCCL's pairs do: the last rank of an odd world can sit out. + fn exchange(ptr: *anyopaque, s: DevicePtr, r: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const self = self_(ptr); + try collective.checkPeer(self.me, self.group.base.world, peer); + if (self.group.base.aborted.load(.acquire)) return error.Aborted; + try self.ready(stream); + const n = count * t.size(); + const k = self.post(s, n, peer); + try self.take(r, n, peer, stream); + try self.delivered(peer, k); + } + + fn send(ptr: *anyopaque, buf: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const self = self_(ptr); + try collective.checkPeer(self.me, self.group.base.world, peer); + if (self.group.base.aborted.load(.acquire)) return error.Aborted; + try self.ready(stream); + try self.delivered(peer, self.post(buf, count * t.size(), peer)); + } + + fn recv(ptr: *anyopaque, buf: DevicePtr, count: usize, t: DType, peer: u32, stream: Stream) Error!void { + const self = self_(ptr); + try collective.checkPeer(self.me, self.group.base.world, peer); + if (self.group.base.aborted.load(.acquire)) return error.Aborted; + try self.ready(stream); + try self.take(buf, count * t.size(), peer, stream); + } + + fn barrier(ptr: *anyopaque) Error!void { + const self = self_(ptr); + try self.group.base.enter(self.me, .{ .call = .barrier }); + try self.group.base.meet(); + } + + fn check(ptr: *anyopaque) Error!void { + if (self_(ptr).group.base.aborted.load(.acquire)) return error.Aborted; + } + + fn abort(ptr: *anyopaque) void { + self_(ptr).group.base.aborted.store(true, .release); + } +}; + +/// Runs `body(rank_collective, rank, ctx)` on `world` threads with `context` current; returns any rank's first error. +pub fn run(context: *const cuda.Context, gpa: std.mem.Allocator, world: u32, opts: host.Options, ctx: anytype, comptime body: fn (collective.Collective, u32, @TypeOf(ctx)) anyerror!void) !void { + var group = Group.init(context.d, gpa, world); + group.base.var_refuse = opts.var_refuse; + var ranks: [max_ranks]Rank = undefined; + var errs: [max_ranks]?anyerror = @splat(null); + var threads: [max_ranks]std.Thread = undefined; + const Wrap = struct { + fn go(r: *Rank, cx: *const cuda.Context, c: @TypeOf(ctx), e: *?anyerror) void { + cx.makeCurrent() catch |err| { + e.* = err; + r.group.base.aborted.store(true, .release); + return; + }; + body(r.iface(), r.me, c) catch |err| { + e.* = err; + r.group.base.aborted.store(true, .release); + }; + } + }; + for (0..world) |i| { + ranks[i] = group.rank(@intCast(i)); + threads[i] = try std.Thread.spawn(.{}, Wrap.go, .{ &ranks[i], context, ctx, &errs[i] }); + } + for (threads[0..world]) |t| t.join(); + for (errs[0..world]) |e| if (e) |err| return err; +} diff --git a/zig/src/fabric/tp/device_test.zig b/zig/src/fabric/tp/device_test.zig new file mode 100644 index 00000000000..26d62234ee1 --- /dev/null +++ b/zig/src/fabric/tp/device_test.zig @@ -0,0 +1,151 @@ +//! The `Collective` contract on in-process ranks of one device, over a fake driver whose copies move host memory. +const std = @import("std"); +const cuda = @import("cuda"); +const collective = @import("collective.zig"); +const device = @import("device.zig"); +const contract = @import("host_test.zig"); +const Collective = collective.Collective; +const abi = cuda.abi; + +fn addr(b: []u8) collective.DevicePtr { + return @intFromPtr(b.ptr); +} + +const Fake = struct { + var capturing: bool = false; + + fn bytes(p: usize, n: usize) []u8 { + return @as([*]u8, @ptrFromInt(p))[0..n]; + } + fn dtod(dst: abi.DevicePtr, src: abi.DevicePtr, n: usize, _: abi.Stream) callconv(.c) abi.Result { + @memcpy(bytes(dst, n), bytes(src, n)); + return abi.success; + } + fn dtoh(dst: ?*anyopaque, src: abi.DevicePtr, n: usize, _: abi.Stream) callconv(.c) abi.Result { + @memcpy(bytes(@intFromPtr(dst), n), bytes(src, n)); + return abi.success; + } + fn htod(dst: abi.DevicePtr, src: ?*const anyopaque, n: usize, _: abi.Stream) callconv(.c) abi.Result { + @memcpy(bytes(dst, n), bytes(@intFromPtr(src), n)); + return abi.success; + } + fn sync(_: abi.Stream) callconv(.c) abi.Result { + return abi.success; + } + fn isCapturing(_: abi.Stream, status: *abi.CaptureStatus) callconv(.c) abi.Result { + status.* = if (capturing) .active else .none; + return abi.success; + } + fn setCurrent(_: abi.Context) callconv(.c) abi.Result { + return abi.success; + } + + fn driver() cuda.Driver { + var d: cuda.Driver = undefined; + d.api.cuMemcpyDtoDAsync_v2 = dtod; + d.api.cuMemcpyDtoHAsync_v2 = dtoh; + d.api.cuMemcpyHtoDAsync_v2 = htod; + d.api.cuStreamSynchronize = sync; + d.api.cuStreamIsCapturing = isCapturing; + d.api.cuCtxSetCurrent = setCurrent; + return d; + } +}; + +fn context(d: *const cuda.Driver) cuda.Context { + return .{ .d = d, .device = 0, .handle = null }; +} + +test "every call on two, three and four ranks of one device equals the reference" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 3, 4 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, contract.Calls.go); +} + +test "exchange, send and recv between two ranks of one device, and in pairs of four" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 4 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, contract.Pairwise.go); +} + +const OddPairs = struct { + fn go(c: Collective, rank: u32, _: void) !void { + var mine: [64]u8 = @splat(@intCast(rank + 1)); + var got: [64]u8 = @splat(0); + // the last rank of an odd world has no partner and goes straight on, as the GPU checks pair ranks + const peer = rank ^ 1; + if (peer < c.world()) { + try c.exchange(addr(&mine), addr(&got), 64, .u8, peer, null); + try std.testing.expectEqualSlices(u8, &@as([64]u8, @splat(@intCast(peer + 1))), &got); + } + var all: [64 * device.max_ranks]u8 = undefined; + try c.allGather(addr(&mine), addr(&all), 64, .u8, null); + for (0..c.world()) |r| try std.testing.expectEqualSlices(u8, &@as([64]u8, @splat(@intCast(r + 1))), all[r * 64 ..][0..64]); + } +}; + +test "pairs at an odd world: the rank without a partner meets the others at the next collective" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 3, 5 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, OddPairs.go); +} + +const BackToBack = struct { + fn go(c: Collective, rank: u32, _: void) !void { + if (rank > 1) return; + for (0..200) |k| { + var sent: [8]u8 = @splat(@truncate(k)); + if (rank == 0) { + try c.send(addr(&sent), 8, .u8, 1, null); + } else { + var got: [8]u8 = @splat(0xff); + try c.recv(addr(&got), 8, .u8, 0, null); + try std.testing.expectEqualSlices(u8, &sent, &got); + } + } + } +}; + +test "back-to-back sends: each recv takes the next post, never the previous one" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 3 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, BackToBack.go); +} + +test "a desynchronised call or lengths that differ are refused on every rank" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 3 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, contract.Desync.go); + try device.run(&cx, std.testing.allocator, 2, .{}, {}, contract.VarDesync.go); +} + +test "abort frees a rank of one device waiting in a collective" { + var d = Fake.driver(); + const cx = context(&d); + try device.run(&cx, std.testing.allocator, 2, .{}, {}, contract.Aborts.go); +} + +test "a variable-length all-gather on one device moves each rank's length, and the ranks agree once" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 3 }) |w| { + try device.run(&cx, std.testing.allocator, w, .{}, @as(u32, 0), contract.VarGather.go); + try device.run(&cx, std.testing.allocator, w, .{ .var_refuse = 2 }, @as(u32, 2), contract.VarGather.go); + } +} + +const Capture = struct { + fn go(c: Collective, _: u32, _: void) !void { + var a: [16]u8 = @splat(0); + var b: [32]u8 = undefined; + try std.testing.expectError(error.Unsupported, c.allGather(addr(&a), addr(&b), 16, .u8, null)); + } +}; + +test "a capturing stream is refused before any rank waits" { + var d = Fake.driver(); + const cx = context(&d); + Fake.capturing = true; + defer Fake.capturing = false; + try device.run(&cx, std.testing.allocator, 2, .{}, {}, Capture.go); +} diff --git a/zig/src/fabric/tp/gpu_checks.zig b/zig/src/fabric/tp/gpu_checks.zig index 825dee6c24d..0c327d34f7a 100644 --- a/zig/src/fabric/tp/gpu_checks.zig +++ b/zig/src/fabric/tp/gpu_checks.zig @@ -25,6 +25,8 @@ pub const Ctx = struct { omit_p2p: bool = false, omitted: u32 = 0, baseline: ?Collective = null, + /// The communicator under test sums in rank order (`reference.reduce`'s order), so the reference is its answer. + rank_order: bool = false, oracle: cuda.DeviceBuffer, pub fn init(d: *const cuda.Driver, gpa: std.mem.Allocator, rank: u32, world: u32, max_bytes: usize) !Ctx { @@ -82,7 +84,7 @@ pub const Ctx = struct { /// Above two ranks, the actual NCCL result is the reference, with the same in-place geometry. fn sumReference(c: *Ctx, n: usize, t: DType, offset: ?usize, input: cuda.abi.DevicePtr) !void { - if (c.world == 2 or t == .u8 or t == .i32 or t == .i64) return; + if (c.world == 2 or c.rank_order or t == .u8 or t == .i32 or t == .i64) return; const slow = c.baseline orelse return error.MissingNcclReference; const out = c.oracle.ptr + (offset orelse 0); if (offset) |skew| try c.oracle.uploadAsync(skew, c.mine(n), c.stream.handle); diff --git a/zig/src/fabric/tp/gpu_cli.zig b/zig/src/fabric/tp/gpu_cli.zig index dc576fc03bd..5ea2cec41ea 100644 --- a/zig/src/fabric/tp/gpu_cli.zig +++ b/zig/src/fabric/tp/gpu_cli.zig @@ -1,19 +1,20 @@ //! Validate the runner's command before opening a driver, bootstrap or fate channel. const std = @import("std"); -pub const usage = "usage: tf-tp-test suite | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | hca | kernel\n"; +pub const usage = "usage: tf-tp-test suite | device | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | hca | kernel\n"; pub const Mode = enum { fatal, kill, transport }; pub const Failure = struct { victim: u32, mode: Mode, n: u32 = 50, hold: ?u32 = null }; -pub const Command = union(enum) { suite, failfast: Failure, @"roce-host", hca, kernel }; +pub const Command = union(enum) { suite, device, failfast: Failure, @"roce-host", hca, kernel }; pub fn parse(args: []const []const u8) error{InvalidArguments}!Command { if (args.len == 0) return error.InvalidArguments; const tag = std.meta.stringToEnum(std.meta.Tag(Command), args[0]) orelse return error.InvalidArguments; switch (tag) { - .suite, .@"roce-host", .hca, .kernel => { + .suite, .device, .@"roce-host", .hca, .kernel => { if (args.len != 1) return error.InvalidArguments; return switch (tag) { .suite => .suite, + .device => .device, .@"roce-host" => .@"roce-host", .hca => .hca, .kernel => .kernel, @@ -40,11 +41,11 @@ fn number(s: []const u8) error{InvalidArguments}!u32 { // Also executed against the Linux entry point with an invalid environment, before any CUDA work. pub const invalid = [_][]const []const u8{ - &.{}, &.{"UNKNOWN"}, &.{ "suite", "extra" }, &.{ "kernel", "extra" }, - &.{ "hca", "extra" }, &.{ "roce-host", "extra" }, &.{"failfast"}, &.{ "failfast", "0" }, - &.{ "failfast", "0", "typo" }, &.{ "failfast", "bad", "fatal" }, &.{ "failfast", "-1", "kill" }, &.{ "failfast", "4294967296", "fatal" }, - &.{ "failfast", "0", "fatal", "50" }, &.{ "failfast", "0", "kill", "50" }, &.{ "failfast", "0", "transport", "bad" }, &.{ "failfast", "0", "transport", "50", "bad" }, - &.{ "failfast", "0", "transport", "50", "0", "extra" }, + &.{}, &.{"UNKNOWN"}, &.{ "suite", "extra" }, &.{ "kernel", "extra" }, + &.{ "device", "extra" }, &.{ "hca", "extra" }, &.{ "roce-host", "extra" }, &.{"failfast"}, + &.{ "failfast", "0" }, &.{ "failfast", "0", "typo" }, &.{ "failfast", "bad", "fatal" }, &.{ "failfast", "-1", "kill" }, + &.{ "failfast", "4294967296", "fatal" }, &.{ "failfast", "0", "fatal", "50" }, &.{ "failfast", "0", "kill", "50" }, &.{ "failfast", "0", "transport", "bad" }, + &.{ "failfast", "0", "transport", "50", "bad" }, &.{ "failfast", "0", "transport", "50", "0", "extra" }, }; test "invalid commands are refused before resources open" { @@ -52,7 +53,7 @@ test "invalid commands are refused before resources open" { } test "documented commands and failfast defaults" { - inline for (.{ "suite", "roce-host", "hca", "kernel" }) |name| { + inline for (.{ "suite", "device", "roce-host", "hca", "kernel" }) |name| { try std.testing.expectEqualStrings(name, @tagName(try parse(&.{name}))); } inline for (.{ Mode.fatal, Mode.kill, Mode.transport }) |mode| { diff --git a/zig/src/fabric/tp/gpu_main.zig b/zig/src/fabric/tp/gpu_main.zig index 353b9d59a64..33417a045f8 100644 --- a/zig/src/fabric/tp/gpu_main.zig +++ b/zig/src/fabric/tp/gpu_main.zig @@ -1,4 +1,4 @@ -//! `tf-tp-test suite | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | hca | kernel`: one rank. +//! `tf-tp-test suite | device | failfast RANK fatal|kill|transport [N [HOLD_S]] | roce-host | hca | kernel` const std = @import("std"); const cuda = @import("cuda"); const tp = @import("tp"); @@ -23,6 +23,7 @@ pub fn main(init: std.process.Init) !u8 { const cfg = try tp.Config.fromEnv(); if (command == .@"roce-host") return @import("roce_host.zig").run(cfg, init.gpa); if (command == .hca) return hca(cfg, init.io); + if (command == .device) return device(cfg); if (command == .failfast and (!cfg.failfast or command.failfast.hold != null) and !hostOnlyAllowed(cfg)) { std.debug.print("REFUSED: failfast with TF_TP_FAILFAST=0 or a hold is host-only: TF_TP_ALLOW_HOST_ONLY=1 and no RDMA wire\n", .{}); return 2; @@ -124,6 +125,43 @@ fn suite(s: *tp.Session, d: *const cuda.Driver, gpa: std.mem.Allocator, cfg: tp. return if (c.failures == 0) 0 else 1; } +/// `device`: every collective on 2, 3 and 4 in-process ranks of one GPU (`TF_TP_DEVICE`), against the reference. +fn device(cfg: tp.Config) !u8 { + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, @intCast(cfg.device)); + defer ctx.deinit(); + var name_buf: [128]u8 = undefined; + std.debug.print("INFO in-process ranks on {s} (sm_{d})\n", .{ try ctx.name(&name_buf), try ctx.capability() }); + var run: DeviceRun = .{ .d = &driver }; + for ([_]u32{ 2, 3, 4 }) |w| tp.device.run(&ctx, std.heap.smp_allocator, w, .{}, &run, DeviceRun.rank) catch |e| { + std.debug.print("FAIL world {d}: {t}\n", .{ w, e }); + _ = run.failures.fetchAdd(1, .monotonic); + }; + const passes = run.passes.load(.monotonic); + const failures = run.failures.load(.monotonic); + std.debug.print("SUMMARY in-process ranks: {d} passed, {d} failed\n", .{ passes, failures }); + return if (failures == 0 and passes > 0) 0 else 1; +} + +const DeviceRun = struct { + d: *const cuda.Driver, + passes: std.atomic.Value(u32) = .init(0), + failures: std.atomic.Value(u32) = .init(0), + + fn rank(comm: tp.Collective, r: u32, run: *DeviceRun) !void { + var c = try checks.Ctx.init(run.d, std.heap.smp_allocator, r, comm.world(), max_bytes); + defer c.deinit(); + c.rank_order = true; + const sizes = [_]usize{ 6, 1000, 4096, 65536, 256 * 1024, 256 * 1024 + 16, 1 << 20, 4 << 20 }; + for (sizes, 0..) |n, i| try c.collectives(comm, "device", n, 100 * i); + try c.pointToPoint(comm, "device", 64 * 1024, 7); + try comm.barrier(); + _ = run.passes.fetchAdd(c.passes, .monotonic); + _ = run.failures.fetchAdd(c.failures, .monotonic); + } +}; + /// The failed-transport check's host-only forms (fail-fast off, a hold): TF_TP_ALLOW_HOST_ONLY=1 and no RDMA wire. fn hostOnlyAllowed(cfg: tp.Config) bool { const flag = std.mem.eql(u8, std.mem.span(std.c.getenv("TF_TP_ALLOW_HOST_ONLY") orelse ""), "1"); diff --git a/zig/src/fabric/tp/host.zig b/zig/src/fabric/tp/host.zig index 051daea5379..a3b9b53d782 100644 --- a/zig/src/fabric/tp/host.zig +++ b/zig/src/fabric/tp/host.zig @@ -9,9 +9,9 @@ const Error = collective.Error; pub const max_ranks = 8; -const Call = enum(u8) { none, all_reduce, all_gather, all_gather_v, exchange, barrier }; +pub const Call = enum(u8) { none, all_reduce, all_gather, all_gather_v, exchange, barrier }; -const Post = struct { call: Call = .none, send: DevicePtr = 0, recv: DevicePtr = 0, count: usize = 0, t: DType = .u8, op: Op = .sum, peer: u32 = 0, lens: DevicePtr = 0 }; +pub const Post = struct { call: Call = .none, send: DevicePtr = 0, recv: DevicePtr = 0, count: usize = 0, t: DType = .u8, op: Op = .sum, peer: u32 = 0, lens: DevicePtr = 0 }; /// One-way message slot from rank `src` to rank `dst` (send / recv). const Slot = struct { buf: std.atomic.Value(DevicePtr) = .init(0), bytes: usize = 0, taken: std.atomic.Value(bool) = .init(false) }; @@ -38,8 +38,20 @@ pub const Group = struct { return .{ .group = g, .me = r }; } + /// Posts rank `me`'s call, waits for all, and refuses calls that do not match rank 0's. + pub fn enter(g: *Group, me: u32, p: Post) Error!void { + if (g.aborted.load(.acquire)) return error.Aborted; + g.posts[me] = p; + try g.meet(); + const r0 = g.posts[0]; + if (r0.call != p.call or r0.count != p.count or r0.t != p.t or r0.op != p.op) { + g.aborted.store(true, .release); + return error.Invalid; + } + } + /// Sense-reversing barrier over every rank; `error.Aborted` once any rank aborts. - fn meet(g: *Group) Error!void { + pub fn meet(g: *Group) Error!void { const gen = g.generation.load(.acquire); if (g.arrived.fetchAdd(1, .acq_rel) + 1 == g.world) { g.arrived.store(0, .release); @@ -56,7 +68,7 @@ pub const Group = struct { } }; -fn now() u64 { +pub fn now() u64 { var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.MONOTONIC, &ts); return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); @@ -106,17 +118,8 @@ pub const Rank = struct { return self_(ptr).group.world; } - /// Posts this rank's call, waits for all, and refuses calls that do not match rank 0's. fn enter(self: *Rank, p: Post) Error!void { - const g = self.group; - if (g.aborted.load(.acquire)) return error.Aborted; - g.posts[self.me] = p; - try g.meet(); - const r0 = g.posts[0]; - if (r0.call != p.call or r0.count != p.count or r0.t != p.t or r0.op != p.op) { - abort(self); - return error.Invalid; - } + return self.group.enter(self.me, p); } fn allReduce(ptr: *anyopaque, s: DevicePtr, r: DevicePtr, count: usize, t: DType, op: Op, _: collective.Stream) Error!void { diff --git a/zig/src/fabric/tp/host_test.zig b/zig/src/fabric/tp/host_test.zig index 311b5e11de6..9601355a3a6 100644 --- a/zig/src/fabric/tp/host_test.zig +++ b/zig/src/fabric/tp/host_test.zig @@ -12,8 +12,8 @@ fn addr(b: []u8) collective.DevicePtr { const n = 96; -const Calls = struct { - fn go(c: Collective, rank: u32, _: void) !void { +pub const Calls = struct { + pub fn go(c: Collective, rank: u32, _: void) !void { const world = c.world(); inline for (.{ DType.f32, DType.bf16, DType.i32, DType.f16 }) |t| { const bytes = n * t.size(); @@ -49,8 +49,8 @@ test "every call on two, three and four in-process ranks equals the reference" { try host.run(4, {}, Calls.go); } -const Pairwise = struct { - fn go(c: Collective, rank: u32, _: void) !void { +pub const Pairwise = struct { + pub fn go(c: Collective, rank: u32, _: void) !void { var mine: [64]u8 = @splat(@intCast(rank + 1)); var got: [64]u8 = undefined; // pairs (0, 1), (2, 3), ...: two ranks trade, as the GPU checks pair them at any even world @@ -74,8 +74,8 @@ test "exchange, send and recv between two ranks, and in pairs of four" { try host.run(4, {}, Pairwise.go); } -const Desync = struct { - fn go(c: Collective, rank: u32, _: void) !void { +pub const Desync = struct { + pub fn go(c: Collective, rank: u32, _: void) !void { var a: [64]u8 = @splat(0); var b: [128]u8 = undefined; // the ranks disagree on the count: both see it instead of hanging @@ -88,8 +88,8 @@ test "a desynchronised call is refused on every rank" { try host.run(2, {}, Desync.go); } -const Aborts = struct { - fn go(c: Collective, rank: u32, _: void) !void { +pub const Aborts = struct { + pub fn go(c: Collective, rank: u32, _: void) !void { var a: [16]u8 = @splat(0); var b: [32]u8 = undefined; if (rank == 1) { @@ -108,8 +108,8 @@ test "abort frees a rank waiting in a collective" { try host.run(2, {}, Aborts.go); } -const VarGather = struct { - fn go(c: Collective, rank: u32, refuse: u32) !void { +pub const VarGather = struct { + pub fn go(c: Collective, rank: u32, refuse: u32) !void { const world = c.world(); const stride = 200; const whole = refuse & (@as(u32, 1) << @intCast(rank)) != 0; @@ -142,8 +142,8 @@ test "a variable-length all-gather moves each rank's length, and the ranks agree } } -const VarDesync = struct { - fn go(c: Collective, rank: u32, _: void) !void { +pub const VarDesync = struct { + pub fn go(c: Collective, rank: u32, _: void) !void { var a: [64]u8 = @splat(0); var b: [128]u8 = undefined; const lens = [2]i32{ 8, if (rank == 0) 8 else 16 }; diff --git a/zig/src/fabric/tp/portable_test.zig b/zig/src/fabric/tp/portable_test.zig index f1f9adf3e5a..bfd9b8a459a 100644 --- a/zig/src/fabric/tp/portable_test.zig +++ b/zig/src/fabric/tp/portable_test.zig @@ -4,6 +4,7 @@ test { _ = @import("reference.zig"); _ = @import("config.zig"); _ = @import("host_test.zig"); + _ = @import("device_test.zig"); _ = @import("roce_guard.zig"); _ = @import("bootstrap.zig"); _ = @import("fate_test.zig"); diff --git a/zig/src/fabric/tp/tp.zig b/zig/src/fabric/tp/tp.zig index 9893b7f8a4f..c316ad18fd8 100644 --- a/zig/src/fabric/tp/tp.zig +++ b/zig/src/fabric/tp/tp.zig @@ -10,6 +10,7 @@ pub const sock = @import("sock.zig"); pub const bootstrap = @import("bootstrap.zig"); pub const fate = @import("fate.zig"); pub const host = @import("host.zig"); +pub const device = @import("device.zig"); pub const nccl = @import("nccl.zig"); pub const mailbox = @import("mailbox.zig"); pub const hybrid = @import("hybrid.zig"); @@ -242,6 +243,7 @@ test { _ = @import("roce_post_test.zig"); _ = @import("roce_inflight_test.zig"); _ = @import("host_test.zig"); + _ = @import("device_test.zig"); _ = @import("fate_test.zig"); _ = @import("fate_lifetime_test.zig"); } From 7dd2000ae666805365b0324f7f7abf9bd146c59c Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:54:31 -0800 Subject: [PATCH 11/23] deepseek_v41: uneven sampling and dense split KV tests at three ranks The uneven sampling tests ran at two and four ranks; three ranks split their 1,280-token vocabulary 512/384/384, as the real one splits 337/337/336 blocks. The dense row-mode and capped union split KV test was fixed at two ranks; it now takes the world from the communicator and runs at two and three, with a pool of 32 pages a rank so three ranks divide it (world 2 keeps its 64). --- zig/src/families/deepseek_v41/kv/split_test.zig | 17 +++++++++-------- zig/src/families/deepseek_v41/sampling_test.zig | 8 ++++---- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/zig/src/families/deepseek_v41/kv/split_test.zig b/zig/src/families/deepseek_v41/kv/split_test.zig index 53232f162d5..c471ee566dc 100644 --- a/zig/src/families/deepseek_v41/kv/split_test.zig +++ b/zig/src/families/deepseek_v41/kv/split_test.zig @@ -1,4 +1,4 @@ -//! Split KV's exchange on two in-process ranks: every row read after the exchange equals the replicated pool's. +//! Split KV's exchange on in-process ranks: every row read after the exchange equals the replicated pool's. const std = @import("std"); const testing = std.testing; @@ -20,7 +20,8 @@ const Ctx = struct { seed: u64 }; fn rank(comm: tp.Collective, me: u32, ctx: *const Ctx) anyerror!void { const gpa = testing.allocator; - var pool = try sessions.Pool.init(gpa, .{ .families = &fams, .page = page }, 64 * page, 2, me); + const W = comm.world(); + var pool = try sessions.Pool.init(gpa, .{ .families = &fams, .page = page }, W * 32 * page, W, me); defer pool.deinit(); var host = try sessions.HostPool.init(gpa, &pool); defer host.deinit(); @@ -60,9 +61,9 @@ fn rank(comm: tp.Collective, me: u32, ctx: *const Ctx) anyerror!void { t.* = if (rnd.uintLessThan(u32, 8) == 0) -1 else @intCast(rnd.uintLessThan(u32, rows)); } var send: [R * K * rb]u8 = undefined; - var recv: [2 * R * K * rb]u8 = undefined; + var recv: [tp.host.max_ranks * R * K * rb]u8 = undefined; var tok: [R * K]i32 = undefined; - try x.dense(.{ .sel = @intFromPtr(&sel), .rows = R, .k = K, .table = @intFromPtr(&tables), .pts = pts, .rslot = @intFromPtr(&rslot), .psh = psh, .base = base, .row_bytes = rb, .world = 2, .send = @intFromPtr(&send), .tok = @intFromPtr(&tok) }, @intFromPtr(&recv), null); + try x.dense(.{ .sel = @intFromPtr(&sel), .rows = R, .k = K, .table = @intFromPtr(&tables), .pts = pts, .rslot = @intFromPtr(&rslot), .psh = psh, .base = base, .row_bytes = rb, .world = W, .send = @intFromPtr(&send), .tok = @intFromPtr(&tok) }, @intFromPtr(&recv), null); for (sel, tok, 0..) |t, o, i| { if (t < 0) { try testing.expectEqual(@as(i32, -1), o); @@ -83,12 +84,12 @@ fn rank(comm: tp.Collective, me: u32, ctx: *const Ctx) anyerror!void { for (blocks.items) |*b| b.deinit(gpa); blocks.deinit(gpa); } - try split.planUnion(gpa, .{ .sel = &useg, .k = K, .table = &table2, .psh = psh, .world = 2, .rank = me, .row_bytes = rb, .cap = 3 * 120 * rb }, &blocks); + try split.planUnion(gpa, .{ .sel = &useg, .k = K, .table = &table2, .psh = psh, .world = W, .rank = me, .row_bytes = rb, .cap = 3 * 120 * rb }, &blocks); try testing.expect(blocks.items.len > 1); for (blocks.items) |blk| { const s2 = try gpa.alloc(u8, blk.m * rb); defer gpa.free(s2); - const r2 = try gpa.alloc(u8, 2 * blk.m * rb); + const r2 = try gpa.alloc(u8, W * blk.m * rb); defer gpa.free(r2); try x.unionBlock(base, rb, @intFromPtr(blk.phys.ptr), blk.m, @intFromPtr(s2.ptr), @intFromPtr(r2.ptr), null); for (useg[blk.a * K .. blk.b * K], blk.tokens) |t, o| { @@ -99,8 +100,8 @@ fn rank(comm: tp.Collective, me: u32, ctx: *const Ctx) anyerror!void { } } -test "split == replicated: dense row-mode and capped union exchanges on two ranks" { - for ([_]u64{ 1, 2, 3 }) |seed| try tp.host.run(2, &Ctx{ .seed = seed }, rank); +test "split == replicated: dense row-mode and capped union exchanges on two and three ranks" { + for ([_]u32{ 2, 3 }) |w| for ([_]u64{ 1, 2, 3 }) |seed| try tp.host.run(w, &Ctx{ .seed = seed }, rank); } // -- packed (TF_DSV41_KV_SPLIT_COMPACT): packed == dense == replicated behind every token, on 2 and 3 ranks --------- diff --git a/zig/src/families/deepseek_v41/sampling_test.zig b/zig/src/families/deepseek_v41/sampling_test.zig index 4a24ac50a7b..cb4c1c61a5c 100644 --- a/zig/src/families/deepseek_v41/sampling_test.zig +++ b/zig/src/families/deepseek_v41/sampling_test.zig @@ -7,7 +7,7 @@ const json = @import("json"); const serve = @import("dsv41_serve"); const pipe = @import("sampling_pipe.zig"); -test "world four: uneven candidate and whole-row sampling match one rank" { +test "two, three and four ranks: uneven candidate and whole-row sampling match one rank" { const vocab = 1280; const n = 4; const a = testing.allocator; @@ -29,7 +29,7 @@ test "world four: uneven candidate and whole-row sampling match one rank" { var expected_whole: [1]usize = undefined; var one: Case = .{ .logits = logits, .world = 1, .uneven = true, .rows = n, .sampling = sampling, .nucleus = 64, .positions = &positions, .got = &expected, .whole = &expected_whole }; try run(&one); - for ([_]u32{ 2, 4 }) |world| { + for ([_]u32{ 2, 3, 4 }) |world| { var got: [n]u32 = undefined; var whole: [1]usize = undefined; var split: Case = .{ .logits = logits, .world = world, .uneven = true, .rows = n, .sampling = sampling, .nucleus = 64, .positions = &positions, .got = &got, .whole = &whole }; @@ -266,7 +266,7 @@ test "vs_choose's mirror == the pipeline's picks over top_k x top_p x min_p x te const SegSpec = struct { row0: u32, n: u32, s: pipe.Sampling, positions: []const u64 }; -test "world four: batched uneven sampling keeps segment offsets and global ids" { +test "two, three and four ranks: batched uneven sampling keeps segment offsets and global ids" { const vocab = 1280; const rows = 4; const a = testing.allocator; @@ -281,7 +281,7 @@ test "world four: batched uneven sampling keeps segment offsets and global ids" var expected: [rows]u32 = undefined; var one: Multi = .{ .logits = logits, .world = 1, .uneven = true, .rows = rows, .segs = &segs, .batched = false, .got = &expected }; try tp.host.run(1, &one, multiBody); - for ([_]u32{ 2, 4 }) |world| { + for ([_]u32{ 2, 3, 4 }) |world| { var got: [rows]u32 = undefined; var mirror: [rows]i64 = @splat(-2); var split: Multi = .{ .logits = logits, .world = world, .uneven = true, .rows = rows, .segs = &segs, .batched = true, .got = &got, .mirror = &mirror }; From 4f3bf63ab55db7f1d5d9346280a59e6acce761b1 Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:30:18 -0800 Subject: [PATCH 12/23] deepseek_v41: the GPU runner over the real images, and the exchanges at three ranks tf-dsv41-test was only built as a compile check over synthetic images, so its GPU commands had no build that ran them. `zig build dsv41-test` installs it for the host over the family images from -Ddsv41-nvcc or -Ddsv41-fatbins, without the runtime's own images (its commands launch none). The runner also imports tp. `tf-dsv41-test exchanges` runs the family's exchanges at worlds 1 to 4 as threads on one GPU (tp.device), each rank's bytes compared: - embedSend, allGather and embedSum with uneven vocabulary shares (4/3/3 blocks at world 3): every id's row x4 on every rank; - Engram's gatherCols: each rank's columns in rank order; - mhc_cuda's boundary (5 rows) and mhc_pf's site (20 rows) over gathered partials: worlds 2 to 4 give world 1's bytes on every output when world 1 holds the partials' exact sum (sixteenths below 16, so every fp32 sum is exact). --- zig/build/dsv41_cuda.zig | 23 +- zig/tests/cuda/deepseek_v41/exchanges.zig | 309 ++++++++++++++++++++++ zig/tests/cuda/dsv41_main.zig | 3 + 3 files changed, 329 insertions(+), 6 deletions(-) create mode 100644 zig/tests/cuda/deepseek_v41/exchanges.zig diff --git a/zig/build/dsv41_cuda.zig b/zig/build/dsv41_cuda.zig index 95b777dc153..fd4d225a057 100644 --- a/zig/build/dsv41_cuda.zig +++ b/zig/build/dsv41_cuda.zig @@ -38,7 +38,7 @@ pub fn assemble(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b return m; } pub fn steps(b: *std.Build) void { - _ = @import("dsv41_images.zig").images(b, b.option([]const u8, "dsv41-nvcc", "Optional family nvcc compiler"), b.option([]const u8, "dsv41-fatbins", "Optional complete family prebuilt image directory")); + const real = @import("dsv41_images.zig").images(b, b.option([]const u8, "dsv41-nvcc", "Optional family nvcc compiler"), b.option([]const u8, "dsv41-fatbins", "Optional complete family prebuilt image directory")); _ = @import("dsv41_images.zig").module(b, b.graph.host, .Debug, runtime(b, b.graph.host, false), null); const check_target = b.resolveTargetQuery(.{ .cpu_arch = b.graph.host.result.cpu.arch, .os_tag = .linux, .abi = .gnu }); const heads_check = b.addExecutable(.{ .name = "tf-dsv41-prefill-heads", .root_module = module(b, check_target, "prefill_heads_check.zig", false) }); @@ -87,13 +87,24 @@ pub fn steps(b: *std.Build) void { const output = record.captureStdOut(.{}); b.step("emit-dsv41-catalog", "Record symbol resolution without CUDA device work").dependOn(&b.addInstallFile(output, "dsv41-launches.txt").step); const runner_base = module(b, target, "cuda_test.zig", true); - const runner = b.addExecutable(.{ .name = "tf-dsv41-test", .root_module = b.createModule(.{ + const runner = b.addExecutable(.{ .name = "tf-dsv41-test", .root_module = runnerModule(b, target, runner_base.import_table.get("cuda").?, runner_base.import_table.get("dsv41_kernels").?) }); + _ = runner.getEmittedBin(); + b.step("compile-dsv41-runner", "Emit the supplied device fixture runner with nonexecuted synthetic images").dependOn(&runner.step); + const gpu = b.step("dsv41-test", "Install tf-dsv41-test for this host over the family images (-Ddsv41-nvcc or -Ddsv41-fatbins)"); + const im = real orelse return gpu.dependOn(&b.addFail("dsv41-test needs -Ddsv41-nvcc=PATH or -Ddsv41-fatbins=DIR").step); + // the family's images only: the runner's commands launch no runtime kernels + const cuda = runtime(b, b.graph.host, false); + const dk = @import("dsv41_images.zig").module(b, b.graph.host, .Debug, cuda, im); + gpu.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = "tf-dsv41-test", .root_module = runnerModule(b, b.graph.host, cuda, dk) }), .{}).step); +} + +/// tests/cuda/dsv41_main.zig over the runtime `cuda` and the kernel module `dk`, with `tp` for the exchanges. +fn runnerModule(b: *std.Build, target: std.Build.ResolvedTarget, cuda: *std.Build.Module, dk: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/dsv41_main.zig"), .target = target, .optimize = .Debug, .link_libc = true, - .imports = &.{ .{ .name = "cuda", .module = runner_base.import_table.get("cuda").? }, .{ .name = "dsv41_kernels", .module = runner_base.import_table.get("dsv41_kernels").? } }, - }) }); - _ = runner.getEmittedBin(); - b.step("compile-dsv41-runner", "Emit the supplied device fixture runner with nonexecuted synthetic images").dependOn(&runner.step); + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "dsv41_kernels", .module = dk }, .{ .name = "tp", .module = @import("tp.zig").module(b, target, .Debug, cuda) } }, + }); } diff --git a/zig/tests/cuda/deepseek_v41/exchanges.zig b/zig/tests/cuda/deepseek_v41/exchanges.zig new file mode 100644 index 00000000000..3f323f2e4ef --- /dev/null +++ b/zig/tests/cuda/deepseek_v41/exchanges.zig @@ -0,0 +1,309 @@ +//! `tf-dsv41-test exchanges`: the family's exchanges at worlds 1 to 4 as threads on one GPU (tp.device), bit for bit. + +const std = @import("std"); +const cuda = @import("cuda"); +const dsv41 = @import("dsv41_kernels"); +const tp = @import("tp"); +const check = @import("../check.zig"); + +const Gpu = check.Gpu; +const Collective = tp.Collective; +const max = tp.device.max_ranks; + +const D = 5120; // config.zig's hidden +const vocab = 1280; // ten 128-row blocks: 4/3/3 at world 3 +const n = 7; +const worlds = [_]u32{ 1, 2, 3, 4 }; + +/// partition.zig's `share`: whole 128-row blocks, one more to each of the first ranks. +fn share(rank: usize, world: usize) [2]usize { + const blocks = vocab / 128; + const base = blocks / world; + const extra = blocks % world; + return .{ (rank * base + @min(rank, extra)) * 128, (base + @intFromBool(rank < extra)) * 128 }; +} + +fn bf16(f: f32) u16 { + const u: u32 = @bitCast(f); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +/// Finite values in [-amp, amp], never +-0 (embed_sum's +0 from the other ranks would flip a -0). +fn fill(rnd: std.Random, out: []u16, amp: f32) void { + for (out) |*v| { + v.* = bf16((rnd.float(f32) * 2 - 1) * amp); + if (v.* & 0x7fff == 0) v.* = 0x3f80; + } +} + +fn fillF32(rnd: std.Random, out: []f32, lo: f32, hi: f32) void { + for (out) |*v| v.* = lo + rnd.float(f32) * (hi - lo); +} + +fn bytes(s: anytype) []const u8 { + return std.mem.sliceAsBytes(s); +} + +/// One device buffer per input, freed together. +const Bufs = struct { + d: *const cuda.Driver, + list: [24]cuda.DeviceBuffer = undefined, + len: usize = 0, + + fn keep(b: *Bufs, buf: cuda.DeviceBuffer) cuda.DeviceBuffer { + b.list[b.len] = buf; + b.len += 1; + return buf; + } + fn up(b: *Bufs, host: []const u8) !u64 { + return b.keep(try cuda.DeviceBuffer.fromHost(b.d, host)).ptr; + } + fn zeros(b: *Bufs, len: usize) !cuda.DeviceBuffer { + const buf = b.keep(try cuda.DeviceBuffer.alloc(b.d, @max(len, 4))); + try buf.fill8(0, null); + return buf; + } + fn deinit(b: *Bufs) void { + for (b.list[0..b.len]) |*x| x.free(); + } +}; + +const Embed = struct { + gpu: Gpu, + k: *const dsv41.Kernels, + table: []const u16, + ids: []const i64, + got: [max][]u8, + + fn go(c: Collective, rank: u32, e: *Embed) anyerror!void { + const W = c.world(); + const part = share(rank, W); + var stream = try cuda.Stream.init(e.gpu.d, false); + defer stream.deinit(); + var b: Bufs = .{ .d = e.gpu.d }; + defer b.deinit(); + const tab = try b.up(bytes(e.table[part[0] * D ..][0 .. part[1] * D])); + const ids = try b.up(bytes(e.ids)); + const rows = (try b.zeros(n * D * 2)).ptr; + const recv = (try b.zeros(W * n * D * 2)).ptr; + const out = try b.zeros(n * 4 * D * 2); + const o = e.k.others(stream); + try o.embedSend(ids, n, tab, @intCast(part[0]), part[1], D, rows); + try c.allGather(rows, recv, n * D, .bf16, stream.handle); + try o.embedSum(recv, W, n, D, out.ptr); + try stream.synchronize(); + try out.download(0, e.got[rank]); + } +}; + +/// Embedding rows from uneven vocabulary shares, gathered and summed: every rank holds each id's row x4. +fn embed(gpu: Gpu, k: *const dsv41.Kernels, rnd: std.Random) !void { + const table = try gpu.gpa.alloc(u16, vocab * D); + defer gpu.gpa.free(table); + fill(rnd, table, 2.0); + // both ends of every world's shares, and two at random + const ids = [n]i64{ 0, 511, 512, 895, 896, @intCast(rnd.uintLessThan(u32, vocab)), vocab - 1 }; + const want = try gpu.gpa.alloc(u16, n * 4 * D); + defer gpu.gpa.free(want); + for (ids, 0..) |id, i| for (0..4) |s| @memcpy(want[(i * 4 + s) * D ..][0..D], table[@as(usize, @intCast(id)) * D ..][0..D]); + var e: Embed = .{ .gpu = gpu, .k = k, .table = table, .ids = &ids, .got = undefined }; + const store = try gpu.gpa.alloc(u8, max * n * 4 * D * 2); + defer gpu.gpa.free(store); + for (&e.got, 0..) |*g, r| g.* = store[r * n * 4 * D * 2 ..][0 .. n * 4 * D * 2]; + var what: [64]u8 = undefined; + for (worlds) |w| { + try tp.device.run(gpu.ctx, std.heap.smp_allocator, w, .{}, &e, Embed.go); + for (0..w) |r| try check.sameBytes(try std.fmt.bufPrint(&what, "embed world {d} rank {d}", .{ w, r }), e.got[r], bytes(want)); + } + check.pass("BITEXACT exchanges embed: {d} ids over vocab {d} at worlds 1-4 (4/3/3 at 3) == each id's row x4", .{ n, vocab }); +} + +const Cols = struct { + gpu: Gpu, + k: *const dsv41.Kernels, + cols: usize, + send: []const u16, // rank r's [n, cols] at r * n * cols + got: [max][]u8, + + fn go(c: Collective, rank: u32, e: *Cols) anyerror!void { + const W = c.world(); + var stream = try cuda.Stream.init(e.gpu.d, false); + defer stream.deinit(); + var b: Bufs = .{ .d = e.gpu.d }; + defer b.deinit(); + const send = try b.up(bytes(e.send[rank * n * e.cols ..][0 .. n * e.cols])); + const recv = (try b.zeros(W * n * e.cols * 2)).ptr; + const out = try b.zeros(n * W * e.cols * 2); + try c.allGather(send, recv, n * e.cols, .bf16, stream.handle); + try e.k.others(stream).gatherCols(recv, W, n, e.cols, out.ptr); + try stream.synchronize(); + try out.download(0, e.got[rank][0..out.len]); + } +}; + +/// Engram's row exchange: each rank's columns gathered, then laid side by side in rank order. +fn cols(gpu: Gpu, k: *const dsv41.Kernels, rnd: std.Random) !void { + const cw = 8 * 64; // eight heads of a 64-wide share each + const send = try gpu.gpa.alloc(u16, max * n * cw); + defer gpu.gpa.free(send); + fill(rnd, send, 4.0); + var e: Cols = .{ .gpu = gpu, .k = k, .cols = cw, .send = send, .got = undefined }; + const store = try gpu.gpa.alloc(u8, max * 4 * n * cw * 2); + defer gpu.gpa.free(store); + for (&e.got, 0..) |*g, r| g.* = store[r * 4 * n * cw * 2 ..][0 .. 4 * n * cw * 2]; + const want = try gpu.gpa.alloc(u16, 4 * n * cw); + defer gpu.gpa.free(want); + var what: [64]u8 = undefined; + for (worlds) |w| { + for (0..n) |i| for (0..w) |q| @memcpy(want[(i * w + q) * cw ..][0..cw], send[(q * n + i) * cw ..][0..cw]); + try tp.device.run(gpu.ctx, std.heap.smp_allocator, w, .{}, &e, Cols.go); + const len = w * n * cw * 2; + for (0..w) |r| try check.sameBytes(try std.fmt.bufPrint(&what, "engram cols world {d} rank {d}", .{ w, r }), e.got[r][0..len], bytes(want)[0..len]); + } + check.pass("BITEXACT exchanges engram: {d} rows of {d} columns a rank at worlds 1-4 == the rank-order layout", .{ n, cw }); +} + +/// One mHC site over gathered partials: `pf` mhc_pf's site (PFDEC, past 16 rows), else mhc_cuda's boundary. +const Fold = struct { + gpu: Gpu, + k: *const dsv41.Kernels, + pf: bool, + R: usize, + x: []const u16, // [R, 4 D] streams + parts: [max][]const u16, // rank r's [R, D] partial at this world + fnw: []const u16, // [24, 4 D] + base: []const f32, + scale: []const f32, + nw: []const f32, + coef: []const f32, // pre [R, 4], post [R, 4], comb [R, 16] + got: [max][]u8, + + fn go(c: Collective, rank: u32, e: *Fold) anyerror!void { + const W = c.world(); + const R = e.R; + var stream = try cuda.Stream.init(e.gpu.d, false); + defer stream.deinit(); + var b: Bufs = .{ .d = e.gpu.d }; + defer b.deinit(); + const x = try b.up(bytes(e.x)); + const send = try b.up(bytes(e.parts[rank])); + const recv = (try b.zeros(W * R * D * 2)).ptr; + const coef = try b.up(bytes(e.coef)); + const outs = [_]cuda.DeviceBuffer{ + try b.zeros(R * 4 * D * 2), // new streams + try b.zeros(R * 4 * 40 * 32 * 4), // partials + try b.zeros(R * D * 2), // collapsed row + try b.zeros(R * D * 2), // normed input (boundary) + try b.zeros(R * 24 * 4), // next coefficients (boundary) + }; + try c.allGather(send, recv, R * D, .bf16, stream.handle); + const o = e.k.others(stream); + if (e.pf) { + try o.mhcSite(.{ .x = x, .xs = 4 * D, .xout = outs[0].ptr, .g = recv, .gr = @intCast(R * D), .world = @intCast(W), .gbf16 = 1, .post = coef + R * 16, .comb = coef + R * 32, .pre = coef, .@"fn" = try b.up(bytes(e.fnw)), .part = outs[1].ptr, .c = outs[2].ptr, .R = @intCast(R) }, 0, false, false); + } else { + const nc = outs[4].ptr; + try o.mhcBoundary(.{ + .x = x, + .xs = 4 * D, + .xout = outs[0].ptr, + .g = recv, + .gr = @intCast(R * D), + .world = @intCast(W), + .gbf16 = 1, + .post = coef + R * 16, + .comb = coef + R * 32, + .pre = coef, + .@"fn" = try b.up(bytes(e.fnw)), + .base = try b.up(bytes(e.base)), + .scale = try b.up(bytes(e.scale)), + .part = outs[1].ptr, + .c = outs[2].ptr, + .nw = try b.up(bytes(e.nw)), + .out = outs[3].ptr, + .opre = nc, + .opost = nc + R * 16, + .ocomb = nc + R * 32, + .cnt = (try b.zeros(256)).ptr, + .R = @intCast(R), + .eps = 1e-6, + .hc_eps = 1e-6, + .post_alpha = 2.0, + .iters = 20, + }, 0, false); + } + try stream.synchronize(); + var at: usize = 0; + for (outs) |buf| { + try buf.download(0, e.got[rank][at..][0..buf.len]); + at += buf.len; + } + } + + fn outBytes(R: usize) usize { + return R * 4 * D * 2 + R * 4 * 40 * 32 * 4 + 2 * R * D * 2 + R * 24 * 4; + } +}; + +/// Worlds 2-4 against world 1 holding the sum: partials in sixteenths below 16 keep every rank-order fp32 sum exact. +fn fold(gpu: Gpu, k: *const dsv41.Kernels, rnd: std.Random, pf: bool, R: usize) !void { + const gpa = gpu.gpa; + const x = try gpa.alloc(u16, R * 4 * D); + defer gpa.free(x); + fill(rnd, x, 1.0); + const fnw = try gpa.alloc(u16, 24 * 4 * D); + defer gpa.free(fnw); + fill(rnd, fnw, 0.02); + var base: [24]f32 = undefined; + fillF32(rnd, &base, -0.5, 0.5); + var scale: [3]f32 = undefined; + fillF32(rnd, &scale, 0.5, 1.5); + const nw = try gpa.alloc(f32, D); + defer gpa.free(nw); + fillF32(rnd, nw, 0.8, 1.2); + const coef = try gpa.alloc(f32, R * 24); + defer gpa.free(coef); + fillF32(rnd, coef, 0.0, 0.5); + // sums in [-96, 96] sixteenths; ranks before the last [-32, 32], the last the rest + const sum = try gpa.alloc(i32, R * D); + defer gpa.free(sum); + for (sum) |*s| s.* = rnd.intRangeAtMost(i32, -96, 96); + const parts = try gpa.alloc(u16, max * R * D); + defer gpa.free(parts); + const len = Fold.outBytes(R); + const want = try gpa.alloc(u8, len); + defer gpa.free(want); + const store = try gpa.alloc(u8, max * len); + defer gpa.free(store); + var e: Fold = .{ .gpu = gpu, .k = k, .pf = pf, .R = R, .x = x, .parts = undefined, .fnw = fnw, .base = &base, .scale = &scale, .nw = nw, .coef = coef, .got = undefined }; + for (&e.got, 0..) |*g, r| g.* = store[r * len ..][0..len]; + var what: [64]u8 = undefined; + const name = if (pf) "mhc_pf site" else "mhc boundary"; + for ([_]u32{ 1, 1, 2, 3, 4 }, 0..) |w, round| { + for (0..R * D) |i| { + var left = sum[i]; + for (0..w) |r| { + const v = if (r + 1 == w) left else rnd.intRangeAtMost(i32, -32, 32); + left -= v; + parts[r * R * D + i] = bf16(@as(f32, @floatFromInt(v)) / 16.0); + } + } + for (&e.parts, 0..) |*p, r| p.* = parts[r * R * D ..][0 .. R * D]; + try tp.device.run(gpu.ctx, std.heap.smp_allocator, w, .{}, &e, Fold.go); + // the first round is the reference; the second shows the kernel repeats its bytes + if (round == 0) { + @memcpy(want, e.got[0]); + continue; + } + for (0..w) |r| try check.sameBytes(try std.fmt.bufPrint(&what, "{s} R {d} world {d} rank {d}", .{ name, R, w, r }), e.got[r], want); + } + check.pass("BITEXACT exchanges {s}: R {d}, partials of worlds 2-4 == world 1 holding their exact sum, every output", .{ name, R }); +} + +pub fn run(gpu: Gpu, k: *const dsv41.Kernels) !void { + var prng = std.Random.DefaultPrng.init(2270); + const rnd = prng.random(); + try embed(gpu, k, rnd); + try cols(gpu, k, rnd); + try fold(gpu, k, rnd, false, 5); + try fold(gpu, k, rnd, true, 20); +} diff --git a/zig/tests/cuda/dsv41_main.zig b/zig/tests/cuda/dsv41_main.zig index ba994a7810b..4bb0771c1e0 100644 --- a/zig/tests/cuda/dsv41_main.zig +++ b/zig/tests/cuda/dsv41_main.zig @@ -8,6 +8,7 @@ const experts = @import("deepseek_v41/experts.zig"); const replay_case = @import("deepseek_v41/replay.zig"); const kvglue = @import("deepseek_v41/kv_glue.zig"); const kvsplit = @import("deepseek_v41/kvsplit.zig"); +const exchanges = @import("deepseek_v41/exchanges.zig"); const mhcdec = @import("deepseek_v41/mhcdec.zig"); const mhc_probe = @import("deepseek_v41/mhc_probe.zig"); const mhc_alloc = @import("deepseek_v41/mhc_alloc_bench.zig"); @@ -26,6 +27,7 @@ const usage = \\ replay one recorded Python extension call (dsv41_capture.py) re-issued and compared, storage by storage \\ kvglue fused KV RMS/SWA store against the reference Triton bytes \\ kvsplit split KV's exchange copies against kv/split.zig's host reference (no fixture) + \\ exchanges embedding, Engram and mHC exchanges at worlds 1-4 as threads on this GPU (no fixture) \\ mhc-probe [windows] the 16-row mHC boundary under cache states, buffer layouts and a cross-stream dependency \\ x3gm3-bench [rows,..] [reps] x3gm v3 against v2 at the served prefill shapes: bits and time (synthetic data) \\ x3ld-epi [rows,..] [reps] TF_DSV41_X3LD_EPI: fused x3ld + epilogues against the four launches (bits, time) @@ -82,6 +84,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { return; } if (std.mem.eql(u8, cmd, "kvsplit")) return kvsplit.run(gpu, &k); + if (std.mem.eql(u8, cmd, "exchanges")) return exchanges.run(gpu, &k); if (std.mem.eql(u8, cmd, "kvglue")) return kvglue.run(gpu, &k, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "mhc-probe")) return mhc_probe.run(gpu, &k, if (rest.len > 0) rest[0] else null); if (std.mem.eql(u8, cmd, "mhc-alloc")) return mhc_alloc.run(gpu, &k, if (rest.len > 0) rest[0] else null); From 31474bb458e0a19faffb93986c22a2b76d82c249 Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:31:56 -0800 Subject: [PATCH 13/23] deepseek_v41: the lockstep test at two and three ranks Its pair read the other rank's vote as 1 - me, so it ran at two ranks only. The ranks now wait for every rank's vote; at three, rank 0's failed request is not done on any rank, and the last rank's transport fault reaches both others as a failed vote. --- zig/src/families/deepseek_v41/lockstep.zig | 72 ++++++++++++---------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/zig/src/families/deepseek_v41/lockstep.zig b/zig/src/families/deepseek_v41/lockstep.zig index 68e98594653..e5289c0b3e1 100644 --- a/zig/src/families/deepseek_v41/lockstep.zig +++ b/zig/src/families/deepseek_v41/lockstep.zig @@ -31,16 +31,17 @@ pub fn agreed(agree: ?Agree, result: anyerror!void, what: []const u8, rank: u32) return ok; } -// -- host test: two ranks on threads, the agreement an in-process AND ----------------------------------------------- +// -- host test: ranks on threads, the agreement an in-process AND --------------------------------------------------- -const Pair = struct { - /// each round's two votes: 0 not yet, 1 ok, 2 not - votes: [8][2]std.atomic.Value(u8) = @splat(.{ .init(0), .init(0) }), - ranks: [2]Rank = undefined, +const Ranks = struct { + /// each round's votes: 0 not yet, 1 ok, 2 not + votes: [8][4]std.atomic.Value(u8) = @splat(@splat(.init(0))), + ranks: [4]Rank = undefined, + world: u32, - const Rank = struct { p: *Pair, me: u32, round: u32 = 0 }; + const Rank = struct { p: *Ranks, me: u32, round: u32 = 0 }; - fn agree(p: *Pair, me: u32) Agree { + fn agree(p: *Ranks, me: u32) Agree { p.ranks[me] = .{ .p = p, .me = me, .round = p.ranks[me].round }; return .{ .ctx = &p.ranks[me], .all = all }; } @@ -49,19 +50,22 @@ const Pair = struct { const k: *Rank = @ptrCast(@alignCast(ctx)); const r = k.round; k.round += 1; - const other = &k.p.votes[r][1 - k.me]; k.p.votes[r][k.me].store(if (ok) 1 else 2, .release); - var spins: u64 = 0; - while (other.load(.acquire) == 0) : (spins += 1) { - if (spins > 1 << 32) return error.Timeout; // a rank that never votes: the test fails, not hangs - std.atomic.spinLoopHint(); + var every = ok; + for (k.p.votes[r][0..k.p.world]) |*v| { + var spins: u64 = 0; + while (v.load(.acquire) == 0) : (spins += 1) { + if (spins > 1 << 32) return error.Timeout; // a rank that never votes: the test fails, not hangs + std.atomic.spinLoopHint(); + } + every = every and v.load(.acquire) == 1; } - return ok and other.load(.acquire) == 1; + return every; } }; -/// One rank's requests: the first fails on rank 0 (a NotInRam), the second goes through on both. -fn runRank(p: *Pair, me: u32, got: *[3]bool, err: *?anyerror) void { +/// One rank's requests: the first fails on rank 0 (a NotInRam), the second goes through on all, the last rank faults. +fn runRank(p: *Ranks, me: u32, got: *[3]bool, err: *?anyerror) void { const first: anyerror!void = if (me == 0) error.NotInRam else {}; got[0] = agreed(p.agree(me), first, "restore", me) catch |e| { err.* = e; @@ -72,29 +76,33 @@ fn runRank(p: *Pair, me: u32, got: *[3]bool, err: *?anyerror) void { return; }; // a transport fault is not a request's: it is returned (the rank's fail-fast), after its own vote - const peer: anyerror!void = if (me == 1) error.PeerFailed else {}; + const last = me + 1 == p.world; + const peer: anyerror!void = if (last) error.PeerFailed else {}; got[2] = agreed(p.agree(me), peer, "restore", me) catch |e| { err.* = e; - if (me == 1) _ = Pair.all(&p.ranks[me], false) catch {}; + if (last) _ = Ranks.all(&p.ranks[me], false) catch {}; return; }; } -test "lockstep: rank 0's failed request is not done on both ranks, and the next request runs on both" { - var p: Pair = .{}; - for (&p.ranks, 0..) |*k, i| k.* = .{ .p = &p, .me = @intCast(i) }; - var got: [2][3]bool = .{ .{ true, false, true }, .{ true, false, true } }; - var errs: [2]?anyerror = .{ null, null }; - const t0 = try std.Thread.spawn(.{}, runRank, .{ &p, 0, &got[0], &errs[0] }); - const t1 = try std.Thread.spawn(.{}, runRank, .{ &p, 1, &got[1], &errs[1] }); - t0.join(); - t1.join(); - for (got) |g| { - try std.testing.expect(!g[0]); // the failed request: not done on either rank - try std.testing.expect(g[1]); // the next: done on both +test "lockstep: rank 0's failed request is not done on two or three ranks, and the next request runs on all" { + for ([_]u32{ 2, 3 }) |w| { + var p: Ranks = .{ .world = w }; + for (&p.ranks, 0..) |*k, i| k.* = .{ .p = &p, .me = @intCast(i) }; + var got: [4][3]bool = @splat(.{ true, false, true }); + var errs: [4]?anyerror = @splat(null); + var threads: [4]std.Thread = undefined; + for (0..w) |i| threads[i] = try std.Thread.spawn(.{}, runRank, .{ &p, @as(u32, @intCast(i)), &got[i], &errs[i] }); + for (threads[0..w]) |t| t.join(); + for (got[0..w]) |g| { + try std.testing.expect(!g[0]); // the failed request: not done on any rank + try std.testing.expect(g[1]); // the next: done on all + } + for (0..w - 1) |i| { + try std.testing.expect(!got[i][2]); // the others hear the fault as a failed vote + try std.testing.expectEqual(@as(?anyerror, null), errs[i]); + } + try std.testing.expectEqual(@as(?anyerror, error.PeerFailed), errs[w - 1]); } - try std.testing.expect(!got[0][2]); // rank 0 hears the fault as a failed vote - try std.testing.expectEqual(@as(?anyerror, error.PeerFailed), errs[1]); - try std.testing.expectEqual(@as(?anyerror, null), errs[0]); try std.testing.expect(isFatal(error.CudaFailed) and !isFatal(error.NotInRam) and !isFatal(error.PoolExhausted)); } From 5f524d4b9d0077522203f6f388a538f36736bac7 Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:03:44 -0800 Subject: [PATCH 14/23] fabric/tp: device.run joins its ranks when a spawn fails, and a size mismatch is tested A failed spawn returned while the ranks already running still used run's group. They are now aborted and joined first. A recv of another size than its send is refused with Invalid, and the sender waiting on it is freed with Aborted. --- zig/src/fabric/tp/device.zig | 7 ++++++- zig/src/fabric/tp/device_test.zig | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/zig/src/fabric/tp/device.zig b/zig/src/fabric/tp/device.zig index 6eff6202edc..a6c5b01cc22 100644 --- a/zig/src/fabric/tp/device.zig +++ b/zig/src/fabric/tp/device.zig @@ -305,7 +305,12 @@ pub fn run(context: *const cuda.Context, gpa: std.mem.Allocator, world: u32, opt }; for (0..world) |i| { ranks[i] = group.rank(@intCast(i)); - threads[i] = try std.Thread.spawn(.{}, Wrap.go, .{ &ranks[i], context, ctx, &errs[i] }); + threads[i] = std.Thread.spawn(.{}, Wrap.go, .{ &ranks[i], context, ctx, &errs[i] }) catch |err| { + // the ranks already running hold this frame's group: stop them and wait before returning + group.base.aborted.store(true, .release); + for (threads[0..i]) |t| t.join(); + return err; + }; } for (threads[0..world]) |t| t.join(); for (errs[0..world]) |e| if (e) |err| return err; diff --git a/zig/src/fabric/tp/device_test.zig b/zig/src/fabric/tp/device_test.zig index 26d62234ee1..00b9edb339a 100644 --- a/zig/src/fabric/tp/device_test.zig +++ b/zig/src/fabric/tp/device_test.zig @@ -134,6 +134,20 @@ test "a variable-length all-gather on one device moves each rank's length, and t } } +const Sizes = struct { + fn go(c: Collective, rank: u32, _: void) !void { + var a: [16]u8 = @splat(1); + if (rank == 0) return std.testing.expectError(error.Aborted, c.send(addr(&a), 8, .u8, 1, null)); + if (rank == 1) return std.testing.expectError(error.Invalid, c.recv(addr(&a), 16, .u8, 0, null)); + } +}; + +test "a recv of another size than its send is refused, and the waiting sender is freed" { + var d = Fake.driver(); + const cx = context(&d); + for ([_]u32{ 2, 3 }) |w| try device.run(&cx, std.testing.allocator, w, .{}, {}, Sizes.go); +} + const Capture = struct { fn go(c: Collective, _: u32, _: void) !void { var a: [16]u8 = @splat(0); From d9270b4dacf9185b9c383f0dd27c5106e60b29d3 Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:03:44 -0800 Subject: [PATCH 15/23] deepseek_v41: the embedding check takes every share edge at worlds 2, 3 and 4 The ids pinned world 3's edges only; the others were covered by chance. The fold comment now says why the sums are exact, and the buffer list asserts its bound. --- zig/tests/cuda/deepseek_v41/exchanges.zig | 29 +++++++++++++---------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/zig/tests/cuda/deepseek_v41/exchanges.zig b/zig/tests/cuda/deepseek_v41/exchanges.zig index 3f323f2e4ef..9d2cb6b4be9 100644 --- a/zig/tests/cuda/deepseek_v41/exchanges.zig +++ b/zig/tests/cuda/deepseek_v41/exchanges.zig @@ -13,6 +13,9 @@ const max = tp.device.max_ranks; const D = 5120; // config.zig's hidden const vocab = 1280; // ten 128-row blocks: 4/3/3 at world 3 const n = 7; +// every share edge at worlds 2, 3 and 4 (640; 512, 896; 384, 768, 1024), both ends, and one at random +const edges = [_]i64{ 0, 383, 384, 511, 512, 639, 640, 767, 768, 895, 896, 1023, 1024, vocab - 1 }; +const ne = edges.len + 1; const worlds = [_]u32{ 1, 2, 3, 4 }; /// partition.zig's `share`: whole 128-row blocks, one more to each of the first ranks. @@ -51,6 +54,7 @@ const Bufs = struct { len: usize = 0, fn keep(b: *Bufs, buf: cuda.DeviceBuffer) cuda.DeviceBuffer { + std.debug.assert(b.len < b.list.len); b.list[b.len] = buf; b.len += 1; return buf; @@ -84,13 +88,13 @@ const Embed = struct { defer b.deinit(); const tab = try b.up(bytes(e.table[part[0] * D ..][0 .. part[1] * D])); const ids = try b.up(bytes(e.ids)); - const rows = (try b.zeros(n * D * 2)).ptr; - const recv = (try b.zeros(W * n * D * 2)).ptr; - const out = try b.zeros(n * 4 * D * 2); + const rows = (try b.zeros(ne * D * 2)).ptr; + const recv = (try b.zeros(W * ne * D * 2)).ptr; + const out = try b.zeros(ne * 4 * D * 2); const o = e.k.others(stream); - try o.embedSend(ids, n, tab, @intCast(part[0]), part[1], D, rows); - try c.allGather(rows, recv, n * D, .bf16, stream.handle); - try o.embedSum(recv, W, n, D, out.ptr); + try o.embedSend(ids, ne, tab, @intCast(part[0]), part[1], D, rows); + try c.allGather(rows, recv, ne * D, .bf16, stream.handle); + try o.embedSum(recv, W, ne, D, out.ptr); try stream.synchronize(); try out.download(0, e.got[rank]); } @@ -101,21 +105,20 @@ fn embed(gpu: Gpu, k: *const dsv41.Kernels, rnd: std.Random) !void { const table = try gpu.gpa.alloc(u16, vocab * D); defer gpu.gpa.free(table); fill(rnd, table, 2.0); - // both ends of every world's shares, and two at random - const ids = [n]i64{ 0, 511, 512, 895, 896, @intCast(rnd.uintLessThan(u32, vocab)), vocab - 1 }; - const want = try gpu.gpa.alloc(u16, n * 4 * D); + const ids = edges ++ [_]i64{@intCast(rnd.uintLessThan(u32, vocab))}; + const want = try gpu.gpa.alloc(u16, ne * 4 * D); defer gpu.gpa.free(want); for (ids, 0..) |id, i| for (0..4) |s| @memcpy(want[(i * 4 + s) * D ..][0..D], table[@as(usize, @intCast(id)) * D ..][0..D]); var e: Embed = .{ .gpu = gpu, .k = k, .table = table, .ids = &ids, .got = undefined }; - const store = try gpu.gpa.alloc(u8, max * n * 4 * D * 2); + const store = try gpu.gpa.alloc(u8, max * ne * 4 * D * 2); defer gpu.gpa.free(store); - for (&e.got, 0..) |*g, r| g.* = store[r * n * 4 * D * 2 ..][0 .. n * 4 * D * 2]; + for (&e.got, 0..) |*g, r| g.* = store[r * ne * 4 * D * 2 ..][0 .. ne * 4 * D * 2]; var what: [64]u8 = undefined; for (worlds) |w| { try tp.device.run(gpu.ctx, std.heap.smp_allocator, w, .{}, &e, Embed.go); for (0..w) |r| try check.sameBytes(try std.fmt.bufPrint(&what, "embed world {d} rank {d}", .{ w, r }), e.got[r], bytes(want)); } - check.pass("BITEXACT exchanges embed: {d} ids over vocab {d} at worlds 1-4 (4/3/3 at 3) == each id's row x4", .{ n, vocab }); + check.pass("BITEXACT exchanges embed: {d} ids, every share edge, over vocab {d} at worlds 1-4 (4/3/3 at 3) == each row x4", .{ ne, vocab }); } const Cols = struct { @@ -244,7 +247,7 @@ const Fold = struct { } }; -/// Worlds 2-4 against world 1 holding the sum: partials in sixteenths below 16 keep every rank-order fp32 sum exact. +/// Worlds 2-4 against world 1 holding the sum: multiples of 1/16 under 16 in size are exact in bf16 and in fp32 sums. fn fold(gpu: Gpu, k: *const dsv41.Kernels, rnd: std.Random, pf: bool, R: usize) !void { const gpa = gpu.gpa; const x = try gpa.alloc(u16, R * 4 * D); From 128b1f59363c13a661058f83bb186ed9f8262f0b Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:55:40 -0700 Subject: [PATCH 16/23] deepseek_v41: the exchanges check splits the vocabulary with the family's partition.zig tf-dsv41-test now imports partition.zig through dsv41_shared, so the embedding check follows production's share instead of a copy of it. --- zig/build/dsv41_cuda.zig | 5 +++-- zig/tests/cuda/deepseek_v41/exchanges.zig | 15 ++++----------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/zig/build/dsv41_cuda.zig b/zig/build/dsv41_cuda.zig index fd4d225a057..f3b86a5500c 100644 --- a/zig/build/dsv41_cuda.zig +++ b/zig/build/dsv41_cuda.zig @@ -98,13 +98,14 @@ pub fn steps(b: *std.Build) void { gpu.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = "tf-dsv41-test", .root_module = runnerModule(b, b.graph.host, cuda, dk) }), .{}).step); } -/// tests/cuda/dsv41_main.zig over the runtime `cuda` and the kernel module `dk`, with `tp` for the exchanges. +/// tests/cuda/dsv41_main.zig over the runtime `cuda` and the kernel module `dk`, with `tp` for the exchanges and the +/// family's `partition.zig`, so the exchanges split the vocabulary as production does. fn runnerModule(b: *std.Build, target: std.Build.ResolvedTarget, cuda: *std.Build.Module, dk: *std.Build.Module) *std.Build.Module { return b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/dsv41_main.zig"), .target = target, .optimize = .Debug, .link_libc = true, - .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "dsv41_kernels", .module = dk }, .{ .name = "tp", .module = @import("tp.zig").module(b, target, .Debug, cuda) } }, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "dsv41_kernels", .module = dk }, .{ .name = "tp", .module = @import("tp.zig").module(b, target, .Debug, cuda) }, .{ .name = "dsv41_partition", .module = shared.module(b, target, "partition.zig") } }, }); } diff --git a/zig/tests/cuda/deepseek_v41/exchanges.zig b/zig/tests/cuda/deepseek_v41/exchanges.zig index 9d2cb6b4be9..8a2dc293e15 100644 --- a/zig/tests/cuda/deepseek_v41/exchanges.zig +++ b/zig/tests/cuda/deepseek_v41/exchanges.zig @@ -4,6 +4,7 @@ const std = @import("std"); const cuda = @import("cuda"); const dsv41 = @import("dsv41_kernels"); const tp = @import("tp"); +const partition = @import("dsv41_partition"); const check = @import("../check.zig"); const Gpu = check.Gpu; @@ -18,14 +19,6 @@ const edges = [_]i64{ 0, 383, 384, 511, 512, 639, 640, 767, 768, 895, 896, 1023, const ne = edges.len + 1; const worlds = [_]u32{ 1, 2, 3, 4 }; -/// partition.zig's `share`: whole 128-row blocks, one more to each of the first ranks. -fn share(rank: usize, world: usize) [2]usize { - const blocks = vocab / 128; - const base = blocks / world; - const extra = blocks % world; - return .{ (rank * base + @min(rank, extra)) * 128, (base + @intFromBool(rank < extra)) * 128 }; -} - fn bf16(f: f32) u16 { const u: u32 = @bitCast(f); return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); @@ -81,18 +74,18 @@ const Embed = struct { fn go(c: Collective, rank: u32, e: *Embed) anyerror!void { const W = c.world(); - const part = share(rank, W); + const part = try partition.share(vocab, rank, W); var stream = try cuda.Stream.init(e.gpu.d, false); defer stream.deinit(); var b: Bufs = .{ .d = e.gpu.d }; defer b.deinit(); - const tab = try b.up(bytes(e.table[part[0] * D ..][0 .. part[1] * D])); + const tab = try b.up(bytes(e.table[part.lo * D ..][0 .. part.len * D])); const ids = try b.up(bytes(e.ids)); const rows = (try b.zeros(ne * D * 2)).ptr; const recv = (try b.zeros(W * ne * D * 2)).ptr; const out = try b.zeros(ne * 4 * D * 2); const o = e.k.others(stream); - try o.embedSend(ids, ne, tab, @intCast(part[0]), part[1], D, rows); + try o.embedSend(ids, ne, tab, @intCast(part.lo), part.len, D, rows); try c.allGather(rows, recv, ne * D, .bf16, stream.handle); try o.embedSum(recv, W, ne, D, out.ptr); try stream.synchronize(); From 1b4d21c1e6caa8da38bcf8d189f44eac1ac1842c Mon Sep 17 00:00:00 2001 From: Christopher Maher <7034124+Defilan@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:08:15 -0700 Subject: [PATCH 17/23] deepseek_v41: the embed check takes its edge ids from partition.share The ids were constants for a vocabulary of 1280. They now come from share(vocab, r, W).lo - 1 and .lo at worlds 2 to 4, so the check stays on the edges if share changes. Same 14 ids today. The runner module's doc comment is one line, which clears the lean check's new multi-line comment. --- zig/build/dsv41_cuda.zig | 3 +-- zig/tests/cuda/deepseek_v41/exchanges.zig | 13 ++++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/zig/build/dsv41_cuda.zig b/zig/build/dsv41_cuda.zig index f3b86a5500c..6b64f7d380e 100644 --- a/zig/build/dsv41_cuda.zig +++ b/zig/build/dsv41_cuda.zig @@ -98,8 +98,7 @@ pub fn steps(b: *std.Build) void { gpu.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = "tf-dsv41-test", .root_module = runnerModule(b, b.graph.host, cuda, dk) }), .{}).step); } -/// tests/cuda/dsv41_main.zig over the runtime `cuda` and the kernel module `dk`, with `tp` for the exchanges and the -/// family's `partition.zig`, so the exchanges split the vocabulary as production does. +/// tests/cuda/dsv41_main.zig over `cuda` and `dk`, plus `tp` and the family's `partition.zig` for the exchanges. fn runnerModule(b: *std.Build, target: std.Build.ResolvedTarget, cuda: *std.Build.Module, dk: *std.Build.Module) *std.Build.Module { return b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/dsv41_main.zig"), diff --git a/zig/tests/cuda/deepseek_v41/exchanges.zig b/zig/tests/cuda/deepseek_v41/exchanges.zig index 8a2dc293e15..c62c2330fe6 100644 --- a/zig/tests/cuda/deepseek_v41/exchanges.zig +++ b/zig/tests/cuda/deepseek_v41/exchanges.zig @@ -14,9 +14,16 @@ const max = tp.device.max_ranks; const D = 5120; // config.zig's hidden const vocab = 1280; // ten 128-row blocks: 4/3/3 at world 3 const n = 7; -// every share edge at worlds 2, 3 and 4 (640; 512, 896; 384, 768, 1024), both ends, and one at random -const edges = [_]i64{ 0, 383, 384, 511, 512, 639, 640, 767, 768, 895, 896, 1023, 1024, vocab - 1 }; -const ne = edges.len + 1; +/// The vocabulary's ends and both sides of every share edge at worlds 2 to 4, where `partition.share` puts them. +const edges = edges: { + var ids: []const i64 = &.{ 0, vocab - 1 }; + for (worlds[1..]) |w| for (1..w) |r| { + const lo: i64 = (partition.share(vocab, r, w) catch unreachable).lo; + ids = ids ++ &[_]i64{ lo - 1, lo }; + }; + break :edges ids[0..ids.len].*; +}; +const ne = edges.len + 1; // and one id at random const worlds = [_]u32{ 1, 2, 3, 4 }; fn bf16(f: f32) u16 { From 12251a5a41dc3b5f7aadf8a3fb614a1df10d2004 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:39:17 +0000 Subject: [PATCH 18/23] changelog: #2491 under Unreleased --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fef174fe1b..d4ccd565cb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Tests: `tp.device` runs N tensor-parallel ranks as threads on one GPU with device copies, so DeepSeek-V4.1's exchanges are now tested at a world of 3 (uneven sampling, dense split KV and lockstep), and `zig build dsv41-test` builds `tf-dsv41-test` over the family's own kernel images (#2491, refs #2270). Thanks to @Defilan. + + - CUDA: a model whose KDA heads or conv window differ from the kernels' (128 keys, 128 values, 4 taps) is refused at load with `KdaGeometry`, before anything is allocated or launched, and a host test ties those numbers to `kda.cuh` (#2338, refs #850). Thanks to @ajensenwaud. From cd4432ebac959d97a8b507077f0dcd50bd373aa2 Mon Sep 17 00:00:00 2001 From: mrv777 Date: Sat, 7 Nov 2026 19:44:18 -0600 Subject: [PATCH 19/23] qwen draw: a sampled row's top-k skips 32-logit blocks that cannot beat the k-th candidate The bounded top-k behind every sampled Qwen row (Metal 27B verify, and the Qwen 3.5/3.6 CUDA engine through the shared draw) walked all 248,320 logits one at a time. A 32-word block whose largest key is at or below the k-th selected key holds no candidate, so the scalar walk over it inserts nothing; it is now skipped with one vector compare. Every word is still checked for non-finite values, including in skipped blocks. The selection is equal to the scalar walk: a host test compares both over 400 random rows (ties, both zeros, masks, tails, NaN and -inf), and a second plants -inf in a skipped block. Planted controls (skip one key too eagerly; check finiteness after the skip) both fail. --- CHANGELOG.md | 1 + zig/build/qwen35_cache_host.zig | 2 +- zig/src/families/qwen3_5/draw_topk.zig | 110 ++++++++++++++++++++++--- 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ccd565cb1..38b7543bda1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -212,6 +212,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - HIP on gfx12 under `--policy matrix=on`: the WMMA dense tile's big block takes 64-deep K steps over swizzled LDS rows, its barrier orders LDS only, and the block thresholds are tuned again, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.694 s instead of 0.720 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.946 s instead of 0.974 s on a Radeon AI PRO R9700. The kernel contract checks the new block byte for byte against a frozen copy of the old one (#2280, part of #2245). Thanks to @laudney. +- Qwen3.8-27B on Metal (and the Qwen 3.5/3.6 CUDA engine, which shares the draw): a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. CUDA is not measured. - Fabric: a pipeline stage's boot and round loop is one driver, generic over an engine binding, so a CUDA, Metal or XPU stage writes only its binding; nothing uses it yet. A stop that a middle stage receives now passes on instead of closing the ring (#2241, part of #2005). Thanks to @jschmied. - KV pool: a family's pool group is sized by its bytes a row over its layers, and a paged CUDA load prints a line of each group's rows a page and padding (the window rows and state outside or beside the pool too), apart from the unchanged startup line; every family stays one group, so nothing else changes (#2532, part of #2444). Thanks to @jschmied. diff --git a/zig/build/qwen35_cache_host.zig b/zig/build/qwen35_cache_host.zig index 7fb19c706e5..da84b7f27fa 100644 --- a/zig/build/qwen35_cache_host.zig +++ b/zig/build/qwen35_cache_host.zig @@ -15,7 +15,7 @@ pub fn tests(b: *std.Build) void { .imports = &.{ .{ .name = "metal", .module = fake }, .{ .name = "lanes", .module = lanes }, .{ .name = "kernel_sources", .module = sources } }, }); b.step("test-qwen35-cache-host", "Qwen2B retained bytes, paged images and resumed host-reference tokens").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"Qwen retained:"} })).step); - const pure = &.{ "admit the affine 2B", "admit untied heads", "text_config parses", "a top-level config", "the geometry refuses", "the Python loader's refusals", "candidate selection preserves", "a masked draw", "a stream's cache bytes" }; + const pure = &.{ "admit the affine 2B", "admit untied heads", "text_config parses", "a top-level config", "the geometry refuses", "the Python loader's refusals", "candidate selection preserves", "a masked draw", "bounded BF16 keys", "the blocked selection", "a non-finite word inside", "a stream's cache bytes" }; b.step("test-qwen35-metal-host", "Qwen2B geometry, keyed draws and state sizing on the CPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = pure })).step); } diff --git a/zig/src/families/qwen3_5/draw_topk.zig b/zig/src/families/qwen3_5/draw_topk.zig index f0bb59ad72d..3a10ae1d87a 100644 --- a/zig/src/families/qwen3_5/draw_topk.zig +++ b/zig/src/families/qwen3_5/draw_topk.zig @@ -8,27 +8,55 @@ fn key(word: u16) u16 { if (word & 0x7fff == 0) return 0x8000; return word ^ (if (word & 0x8000 == 0) @as(u16, 0x8000) else @as(u16, 0xffff)); } +/// Words a block: one vector compare skips 32 logits that cannot enter a full selection. +const block = 32; +const Block = @Vector(block, u16); + +/// `key` over a block of words. +fn keys(words: Block) Block { + const negative = words & @as(Block, @splat(0x8000)) != @as(Block, @splat(0)); + const flipped = words ^ @select(u16, negative, @as(Block, @splat(0xffff)), @as(Block, @splat(0x8000))); + return @select(u16, words & @as(Block, @splat(0x7fff)) == @as(Block, @splat(0)), @as(Block, @splat(0x8000)), flipped); +} + +/// Inserts a finite allowed word that beats the k-th key, after equal keys so ties keep id order. +inline fn consider(selected: *[capacity]Entry, filled: *usize, k: usize, word: u16, id: usize, mask: []const u32) void { + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) return; + const rank = key(word); + if (filled.* == k and rank <= selected[k - 1].key) return; + var at = @min(filled.*, k - 1); + while (at > 0 and rank > selected[at - 1].key) : (at -= 1) selected[at] = selected[at - 1]; + selected[at] = .{ .key = rank, .word = word, .id = id }; + filled.* = @min(filled.* + 1, k); +} + fn value(word: u16) f64 { return @as(f32, @bitCast(@as(u32, word) << 16)); } +/// The k best allowed words of a finite row, ordered by key then id; a block that can't beat the k-th key is skipped. +fn select(logits: []const u16, k: usize, mask: []const u32, selected: *[capacity]Entry) error{NonfiniteQwenLogits}!usize { + var filled: usize = 0; + var at: usize = 0; + while (at + block <= logits.len) : (at += block) { + const row: Block = logits[at..][0..block].*; + if (@reduce(.Or, row & @as(Block, @splat(0x7f80)) == @as(Block, @splat(0x7f80)))) return error.NonfiniteQwenLogits; + if (filled == k and @reduce(.Max, keys(row)) <= selected[k - 1].key) continue; + for (logits[at..][0..block], at..) |word, id| consider(selected, &filled, k, word, id, mask); + } + for (logits[at..], at..) |word, id| { + if (word & 0x7f80 == 0x7f80) return error.NonfiniteQwenLogits; + consider(selected, &filled, k, word, id, mask); + } + return filled; +} + /// Null retains the general draw for unbounded or larger top-k and greedy requests. pub fn draw(logits: []const u16, sampling: lanes.Sampling, position: u64, mask: []const u32) !?u32 { if (sampling.temperature <= 0 or sampling.top_k == 0 or sampling.top_k > capacity) return null; - const k: usize = sampling.top_k; var selected: [capacity]Entry = undefined; - var filled: usize = 0; - for (logits, 0..) |word, id| { - // Validate the whole row, including masked tokens and candidates below the cut. - if (word & 0x7f80 == 0x7f80) return error.NonfiniteQwenLogits; - if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; - const rank = key(word); - if (filled == k and rank <= selected[k - 1].key) continue; - var at = @min(filled, k - 1); - while (at > 0 and rank > selected[at - 1].key) : (at -= 1) selected[at] = selected[at - 1]; - selected[at] = .{ .key = rank, .word = word, .id = id }; - filled = @min(filled + 1, k); - } + // Validate the whole row, including masked tokens and candidates below the cut. + const filled = try select(logits, sampling.top_k, mask, &selected); if (filled == 0) return error.NoAllowedQwenToken; var candidates: [capacity]lanes.sampling.Candidate = undefined; for (candidates[0..filled], selected[0..filled]) |*out, entry| out.* = .{ .value = value(entry.word), .id = entry.id }; @@ -49,3 +77,59 @@ test "bounded BF16 keys preserve numeric order over every finite word and both z } } } + +/// The scalar walk `select` replaces: every word validated, then inserted after its equal keys. +fn selectScalar(logits: []const u16, k: usize, mask: []const u32, selected: *[capacity]Entry) !usize { + var filled: usize = 0; + for (logits, 0..) |word, id| { + if (word & 0x7f80 == 0x7f80) return error.NonfiniteQwenLogits; + consider(selected, &filled, k, word, id, mask); + } + return filled; +} + +test "the blocked selection equals the scalar walk over ties, zeros, masks, tails and non-finite words" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(0x5eed); + const r = prng.random(); + const words = try gpa.alloc(u16, 4099); + defer gpa.free(words); + var mask: [(4099 + 31) / 32]u32 = undefined; + for (0..400) |case| { + const n = 1 + r.uintLessThan(usize, words.len); + const narrow = case % 2 == 1; // eight adjacent words: k-th keys and block maxima often differ by one + for (words[0..n]) |*w| w.* = if (narrow) 0x3f80 + r.uintLessThan(u16, 8) else switch (r.uintLessThan(u8, 8)) { + 0 => 0, // +0 and -0 share a key + 1 => 0x8000, + 2 => 0x4000 | r.uintLessThan(u16, 4), // a few tied values + else => r.int(u16) & ~@as(u16, 0x0080), // never all-ones exponents here + }; + if (case % 3 == 0) for (0..n / 64 + 1) |_| { // big values late in the row, so early blocks are full and later skipped + words[n - 1 - r.uintLessThan(usize, @min(n, 64))] = 0x4700; + }; + const masked = case % 4 == 1; + for (&mask) |*m| m.* = r.int(u32); + const m: []const u32 = if (masked) mask[0 .. (n + 31) / 32] else &.{}; + if (case % 5 == 2) words[r.uintLessThan(usize, n)] = if (case % 2 == 0) 0x7fc0 else 0xff80; // NaN or -inf + const k = 1 + r.uintLessThan(usize, capacity); + var a: [capacity]Entry = undefined; + var b: [capacity]Entry = undefined; + const want = selectScalar(words[0..n], k, m, &a); + const got = select(words[0..n], k, m, &b); + if (want) |filled| { + try std.testing.expectEqual(filled, try got); + for (a[0..filled], b[0..filled]) |x, y| { + try std.testing.expectEqual(x.id, y.id); + try std.testing.expectEqual(x.word, y.word); + } + } else |err| try std.testing.expectError(err, got); + } +} + +test "a non-finite word inside a block the selection skips is still refused" { + var words: [96]u16 = @splat(0x3f80); // 1.0 + for (words[0..32]) |*w| w.* = 0x4000; // 2.0 fills k = 4 in the first block + words[70] = 0xff80; // -inf in the third block, whose largest key is below the selection's + var selected: [capacity]Entry = undefined; + try std.testing.expectError(error.NonfiniteQwenLogits, select(&words, 4, &.{}, &selected)); +} From 91cb5493104463c9208e96e66b752527cd372880 Mon Sep 17 00:00:00 2001 From: mrv777 Date: Sat, 7 Nov 2026 20:37:14 -0600 Subject: [PATCH 20/23] changelog: the sampled top-k line names #2507 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b7543bda1..45195a0e34e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -213,6 +213,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - HIP on gfx12 under `--policy matrix=on`: the WMMA dense tile's big block takes 64-deep K steps over swizzled LDS rows, its barrier orders LDS only, and the block thresholds are tuned again, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.694 s instead of 0.720 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.946 s instead of 0.974 s on a Radeon AI PRO R9700. The kernel contract checks the new block byte for byte against a frozen copy of the old one (#2280, part of #2245). Thanks to @laudney. - Qwen3.8-27B on Metal (and the Qwen 3.5/3.6 CUDA engine, which shares the draw): a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. CUDA is not measured. +- Qwen3.8-27B on Metal (and the Qwen 3.5/3.6 CUDA engine, which shares the draw): a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. CUDA is not measured (#2507). - Fabric: a pipeline stage's boot and round loop is one driver, generic over an engine binding, so a CUDA, Metal or XPU stage writes only its binding; nothing uses it yet. A stop that a middle stage receives now passes on instead of closing the ring (#2241, part of #2005). Thanks to @jschmied. - KV pool: a family's pool group is sized by its bytes a row over its layers, and a paged CUDA load prints a line of each group's rows a page and padding (the window rows and state outside or beside the pool too), apart from the unchanged startup line; every family stays one group, so nothing else changes (#2532, part of #2444). Thanks to @jschmied. From cc2fc9d61af6e1cdd3a7c01d79f380fa5800f29c Mon Sep 17 00:00:00 2001 From: mrv777 Date: Sun, 8 Nov 2026 03:13:26 -0600 Subject: [PATCH 21/23] changelog: the top-k line says which CUDA draws reach the host (#2507) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45195a0e34e..8775537f212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -233,6 +233,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: the Qwen4 and Dory RoPE word-table host tests print their tables only when a comparison fails, naming the first wrong word; a passing run writes nothing to stderr (#2519, refs #1852). - Tests: thirteen host checks that no CI job ran build and pass again on main (`test-cluster-loader-host`, `test-exl3-prompt-host`, `test-gemma4-affine-host`, `test-gradient-serving`, `test-metal-residency-owners-host`, `test-qwen-serving-host`, `test-qwen27-prompt-rows-host`, `test-qwen35-draft-frame-host`, `test-qwen35-draft-trees-host`, `test-qwen35-frame-invalidation-host`, `test-qwen35-live-host`, `test-qwen35-shared-host` and `compile-qwen35-rounds-host`). Their fixtures and build wiring follow the engine's current imports and fields. The prompt-rows and shared-cache tests expect blank values as unset, #2527's floor message and the overlaid log and before block. The source pins take main's reviewed bytes, each naming its commit. No engine code changes (#2550). +- Qwen3.8-27B on Metal: a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. The Qwen 3.5/3.6 CUDA engine shares this host draw for each first token and for grammar-masked windows; its unmasked sampled verify rows draw on the GPU. CUDA is not measured (#2507). Thanks to @mrv777. - Nemotron on Macs: a non-finite value in a masked key no longer reaches prompt attention's output; finite prompts run the same kernels as before, and prefill is level (#2322, part of #1009). From 4c22964fef1b625f778808dd534784c43b1cb090 Mon Sep 17 00:00:00 2001 From: mrv777 Date: Sun, 8 Nov 2026 09:12:13 -0600 Subject: [PATCH 22/23] changelog: the top-k line back under Unreleased (#2507) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8775537f212..eb7de697e04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -183,6 +183,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: the image page says how the native server finds libjpeg-turbo 3.1.4.1 for JPEG input: why the release is pinned, the search order and file names on macOS, Linux and Windows, `TENSORFOLD_LIBTURBOJPEG`, and what each startup warning means (#2590, refs #2581). - Internal: a shared CUDA MLA image (`mla.cu`, `cuda.mla`) for a 512-wide latent with 64 roped columns and 128-wide heads, on GLM's MLA chunk bodies, which move from `glm_glue_attn.cuh` to `common/mla.cuh` and which GLM instantiates at its old widths (its SASS is identical on all five SMs). Its seven launches are under the kernel contract with a planted control each, and `test-mla-twins-host` keeps its absorb, expand and per-rank merge GLM's kernels token for token. No family calls it yet (#2335, refs #850). Thanks to @ajensenwaud. +- Qwen3.8-27B on Metal: a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. The Qwen 3.5/3.6 CUDA engine shares this host draw for each first token and for grammar-masked windows; its unmasked sampled verify rows draw on the GPU. CUDA is not measured (#2507). Thanks to @mrv777. ## 1.2.5 From c879aabe6de9902bda0c3f3f59f86371cbcf9a52 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:39:20 +0000 Subject: [PATCH 23/23] changelog: #2507's line from lines/2507.txt in place of its own --- CHANGELOG.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb7de697e04..0be88ddb0ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.8-27B on Metal: a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. The Qwen 3.5/3.6 CUDA engine shares this host draw for each first token and for grammar-masked windows; its unmasked sampled verify rows draw on the GPU. CUDA is not measured (#2507). Thanks to @mrv777. - Tests: `tp.device` runs N tensor-parallel ranks as threads on one GPU with device copies, so DeepSeek-V4.1's exchanges are now tested at a world of 3 (uneven sampling, dense split KV and lockstep), and `zig build dsv41-test` builds `tf-dsv41-test` over the family's own kernel images (#2491, refs #2270). Thanks to @Defilan. - - CUDA: a model whose KDA heads or conv window differ from the kernels' (128 keys, 128 values, 4 taps) is refused at load with `KdaGeometry`, before anything is allocated or launched, and a host test ties those numbers to `kda.cuh` (#2338, refs #850). Thanks to @ajensenwaud. - - CUDA: the start-up note about pages parked on the kernel's per-CPU lists logs at debug level, so whether it shows no longer depends on the box's memory state; the budget still counts those pages (#2164, follow-up to #2127). Thanks to @jschmied. - CUDA: the families' sampled rule comes from one function, `cuda.sample.ruleFor`, in place of seven copies (MiniMax M3's hand-filled `Rule` included); a host test checks each old form byte for byte over 25,480 settings, and the fatbins are unchanged (#2680, #2460 item 3). Thanks to @jschmied. @@ -183,7 +182,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: the image page says how the native server finds libjpeg-turbo 3.1.4.1 for JPEG input: why the release is pinned, the search order and file names on macOS, Linux and Windows, `TENSORFOLD_LIBTURBOJPEG`, and what each startup warning means (#2590, refs #2581). - Internal: a shared CUDA MLA image (`mla.cu`, `cuda.mla`) for a 512-wide latent with 64 roped columns and 128-wide heads, on GLM's MLA chunk bodies, which move from `glm_glue_attn.cuh` to `common/mla.cuh` and which GLM instantiates at its old widths (its SASS is identical on all five SMs). Its seven launches are under the kernel contract with a planted control each, and `test-mla-twins-host` keeps its absorb, expand and per-rank merge GLM's kernels token for token. No family calls it yet (#2335, refs #850). Thanks to @ajensenwaud. -- Qwen3.8-27B on Metal: a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. The Qwen 3.5/3.6 CUDA engine shares this host draw for each first token and for grammar-masked windows; its unmasked sampled verify rows draw on the GPU. CUDA is not measured (#2507). Thanks to @mrv777. ## 1.2.5 @@ -213,8 +211,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - HIP on gfx12 under `--policy matrix=on`: the WMMA dense tile's big block takes 64-deep K steps over swizzled LDS rows, its barrier orders LDS only, and the block thresholds are tuned again, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.694 s instead of 0.720 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.946 s instead of 0.974 s on a Radeon AI PRO R9700. The kernel contract checks the new block byte for byte against a frozen copy of the old one (#2280, part of #2245). Thanks to @laudney. -- Qwen3.8-27B on Metal (and the Qwen 3.5/3.6 CUDA engine, which shares the draw): a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. CUDA is not measured. -- Qwen3.8-27B on Metal (and the Qwen 3.5/3.6 CUDA engine, which shares the draw): a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. CUDA is not measured (#2507). - Fabric: a pipeline stage's boot and round loop is one driver, generic over an engine binding, so a CUDA, Metal or XPU stage writes only its binding; nothing uses it yet. A stop that a middle stage receives now passes on instead of closing the ring (#2241, part of #2005). Thanks to @jschmied. - KV pool: a family's pool group is sized by its bytes a row over its layers, and a paged CUDA load prints a line of each group's rows a page and padding (the window rows and state outside or beside the pool too), apart from the unchanged startup line; every family stays one group, so nothing else changes (#2532, part of #2444). Thanks to @jschmied. @@ -234,7 +230,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: the Qwen4 and Dory RoPE word-table host tests print their tables only when a comparison fails, naming the first wrong word; a passing run writes nothing to stderr (#2519, refs #1852). - Tests: thirteen host checks that no CI job ran build and pass again on main (`test-cluster-loader-host`, `test-exl3-prompt-host`, `test-gemma4-affine-host`, `test-gradient-serving`, `test-metal-residency-owners-host`, `test-qwen-serving-host`, `test-qwen27-prompt-rows-host`, `test-qwen35-draft-frame-host`, `test-qwen35-draft-trees-host`, `test-qwen35-frame-invalidation-host`, `test-qwen35-live-host`, `test-qwen35-shared-host` and `compile-qwen35-rounds-host`). Their fixtures and build wiring follow the engine's current imports and fields. The prompt-rows and shared-cache tests expect blank values as unset, #2527's floor message and the overlaid log and before block. The source pins take main's reviewed bytes, each naming its commit. No engine code changes (#2550). -- Qwen3.8-27B on Metal: a sampled row's top-k skips 32 logits at a time that cannot beat the k-th candidate, still refusing any non-finite logit, with the same candidates and replies. On an M5 Ultra with Qwen3.8-27B MLX 4-bit and its DFlash2 drafter, sampled verify rounds take 1.6 ms less and sampled decode is 6% faster; greedy is unchanged. The Qwen 3.5/3.6 CUDA engine shares this host draw for each first token and for grammar-masked windows; its unmasked sampled verify rows draw on the GPU. CUDA is not measured (#2507). Thanks to @mrv777. - Nemotron on Macs: a non-finite value in a masked key no longer reaches prompt attention's output; finite prompts run the same kernels as before, and prefill is level (#2322, part of #1009).