diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8c0cbfe29..0be88ddb0ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ 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. @@ -67,6 +74,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. @@ -888,7 +896,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. 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. - 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. 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/build/dsv41_cuda.zig b/zig/build/dsv41_cuda.zig index 95b777dc153..6b64f7d380e 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 `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"), .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) }, .{ .name = "dsv41_partition", .module = shared.module(b, target, "partition.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/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/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/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..0c4a26e66c9 100644 --- a/zig/src/core/contract/paging_pending.zig +++ b/zig/src/core/contract/paging_pending.zig @@ -8,13 +8,20 @@ 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" { 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 7b19de3d6b9..3b629408490 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 ++ @@ -34,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 ++ diff --git a/zig/src/cuda/kda.zig b/zig/src/cuda/kda.zig index 3ea9a872762..8592962f054 100644 --- a/zig/src/cuda/kda.zig +++ b/zig/src/cuda/kda.zig @@ -3,11 +3,19 @@ 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. +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])); +} 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..a6c5b01cc22 --- /dev/null +++ b/zig/src/fabric/tp/device.zig @@ -0,0 +1,317 @@ +//! 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] = 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 new file mode 100644 index 00000000000..00b9edb339a --- /dev/null +++ b/zig/src/fabric/tp/device_test.zig @@ -0,0 +1,165 @@ +//! 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 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); + 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"); } 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/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)); } 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 }; 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)); +} 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; 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 + } + } } diff --git a/zig/tests/cuda/deepseek_v41/exchanges.zig b/zig/tests/cuda/deepseek_v41/exchanges.zig new file mode 100644 index 00000000000..c62c2330fe6 --- /dev/null +++ b/zig/tests/cuda/deepseek_v41/exchanges.zig @@ -0,0 +1,312 @@ +//! `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 partition = @import("dsv41_partition"); +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; +/// 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 { + 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 { + std.debug.assert(b.len < b.list.len); + 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 = 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.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.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(); + 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); + 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 * ne * 4 * D * 2); + defer gpu.gpa.free(store); + 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, every share edge, over vocab {d} at worlds 1-4 (4/3/3 at 3) == each row x4", .{ ne, 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: 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); + 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);