diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml index 0631782c06b..c0f19ccefdb 100644 --- a/.github/workflows/app.yml +++ b/.github/workflows/app.yml @@ -137,6 +137,8 @@ jobs: name: tensorfold-linux-appimage path: app/release/linux/*.AppImage if-no-files-found: error + # ~230 MB a run: kept 3 days, not GitHub's 90 (2,069 copies, 475 GB of Actions storage by 12 Nov) + retention-days: 3 mobile: runs-on: ubuntu-24.04 diff --git a/.github/workflows/no-gpu.yml b/.github/workflows/no-gpu.yml index 6403551b15f..4e1338f66b3 100644 --- a/.github/workflows/no-gpu.yml +++ b/.github/workflows/no-gpu.yml @@ -59,7 +59,7 @@ jobs: "$RUNNER_TEMP/pytest/bin/python" -m pytest -q -p no:cacheprovider zig: runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 60 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: @@ -125,10 +125,26 @@ jobs: exit 0 fi python3 -m unittest discover -s tools/zig -p zig_cache_restat_test.py -v - # zig build test is the host unit tests. No GPU. The Python suite is not this check. - # A unit test that hangs fails by name after 10 minutes instead of holding the runner until the job's limit. - - name: zig build test - run: zig build -Dfixed-cpu test --test-timeout 10m + - name: Host test graph regressions + shell: bash + env: + BASE_REF: ${{ github.base_ref }} + PUSH_BASE: ${{ github.event.before }} + run: | + if [ -n "$BASE_REF" ]; then + base=$(git merge-base HEAD "origin/$BASE_REF" 2> /dev/null || true) + else + base=$(git rev-parse --verify "$PUSH_BASE^{commit}" 2> /dev/null || true) + fi + if [ -n "$base" ] && git diff --quiet "$base" HEAD -- \ + build.zig zig/build/host_tests.zig tools/zig/host_tests_test.py; then + echo "Host test graph inputs are unchanged." + exit 0 + fi + python3 -m unittest discover -s tools/zig -p host_tests_test.py -v + # Keep per-test timeouts while allowing the DeepSeek AOT enumeration to finish on hosted runners. + - name: zig build test-host + run: zig build -Dfixed-cpu test-host --test-timeout 20m # The kernel contract's limits gate: every registered launch against M1-M5 and sm_80/86/89/120/121, controls red. - name: zig build test-kernel-contract run: zig build -Dfixed-cpu test-kernel-contract diff --git a/CHANGELOG.md b/CHANGELOG.md index d785a94f97b..80df7e5b72d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- CI: the app workflow keeps its Linux AppImage artifact for 3 days instead of GitHub's default 90 (#2966). + +- CI: the Linux no-GPU job runs `zig build test-host`, which collects the named host tests and compile checks apart from nine reviewed exclusions (the optional xgrammar steps, the release-path check, the two large-state timing commands, which stay available for explicit runs, and four fixture and source-pin checks held back under #2031); the build graph refuses empty checks, stale exclusions and aliases that bring excluded work back (#2095, part of #2031). Thanks to @garvrao80. + +- Tests: the TCP bootstrap's three-rank gather test and the multi-rank RoCE vote test join every rank they started before returning, so a failed spawn or check no longer leaves threads writing to a finished test's frame (#2963). Thanks to @Defilan. + +- GLM-5.3-Flash on CUDA: a tensor-parallel abort reaches the ranks' communicator from the engine's start, once, and a start-up failure after an abort no longer destroys the communicator again; serving and replies are unchanged (#2918, part of #2560). Thanks to @laudney. + +- Metal: MiniMax-M3, Spark2.5 and Llama take their NaN-aware bf16 argmax from one shared source; the compiled code is unchanged (#2949, part of #2251). Thanks to @jschmied. + - Metal: the image towers of GLM, Step-5, Gemma 4 and Qwen share one source for bf16 rounding, threadgroup sum and max, row softmax and LayerNorm statistics; the compiled code is unchanged (#2948, part of #2251). Thanks to @jschmied. - Tests: the dashboard page's test runs on every OS, so Linux CI covers it, and no longer expects a paged prefix cache tile the page never had; `zig build test` passes on Macs again (#2946). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c6d09d598f5..277cbabb292 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,6 +41,15 @@ zig build test-cuda-host This subset does not replace the complete `test` suite. +Native Linux no-GPU CI runs `zig build -Dfixed-cpu test-host --test-timeout 20m`. +It includes `test` and every configured `test-*` and `check-*` step, including compile-only checks. +New named checks join automatically, even when a build module registers them last. +The reviewed exclusions in `zig/build/host_tests.zig` cover the optional xgrammar tests, +the separately scheduled `check-release-paths` gate, manual large-state timing commands, and temporary failures tracked in #2031. +An empty named check, a stale exclusion, or an alias that brings excluded work back into the aggregate fails it. +When a fix lands, remove its temporary exclusion and the matching fixture entry in `tools/zig/host_tests_test.py`. +This aggregate is only registered for native Linux; other hosts keep their existing `test` and device steps. + HIP is an explicit build opt-in. Add `-Dhip=true` to enable its host tests and named HIP targets: ```sh diff --git a/build.zig b/build.zig index 357e4a098a6..1a05edb0cdb 100644 --- a/build.zig +++ b/build.zig @@ -77,6 +77,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/dsv41_draft.zig").steps(b); @import("zig/build/dsv41_assets.zig").steps(b); const target = b.standardTargetOptions(.{}); + defer @import("zig/build/host_tests.zig").wire(b, target); @import("zig/build/copy_source.zig").steps(b); @import("zig/build/checkpoint_io_host.zig").steps(b, target); if (target.result.os.tag == .macos) @import("zig/build/masked_values.zig").steps(b, target, .ReleaseSafe); diff --git a/tools/zig/host_tests_test.py b/tools/zig/host_tests_test.py new file mode 100644 index 00000000000..a728cdc76a9 --- /dev/null +++ b/tools/zig/host_tests_test.py @@ -0,0 +1,101 @@ +"""Real Zig build graphs must include new host checks and keep reviewed external requirements outside CI.""" +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +POLICY = ROOT / "zig/build/host_tests.zig" +EXCLUDED = ( + "test-grammar-budget", + "test-grammar-tools", + "check-release-paths", + "test-startup-states-timing", + "test-imprint-ops-timing", + "test-metal-residency-owners-host", + "test-qwen35-draft-frame-host", + "test-qwen35-frame-invalidation-host", + "test-gradient-serving", +) + + +@unittest.skipUnless(sys.platform.startswith("linux"), "test-host is a native Linux CI aggregate") +class HostTestGraphTests(unittest.TestCase): + def setUp(self): + self.zig = os.environ.get("ZIG") or shutil.which("zig") + if not self.zig: + self.skipTest("no Zig compiler found (set ZIG, or put zig on PATH)") + temporary = tempfile.TemporaryDirectory(prefix="tensorfold-host-graph-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + shutil.copyfile(POLICY, self.root / "host_tests.zig") + + def build(self, extra="", omit=None, args=None): + excluded = "\n".join( + f' b.step("{name}", "external requirement").dependOn(&b.addFail("external gate ran").step);' + for name in EXCLUDED if name != omit + ) + source = '''const std = @import("std"); +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + defer @import("host_tests.zig").wire(b, target); +''' + excluded + "\n" + extra + "\n}\n" + (self.root / "build.zig").write_text(source) + return subprocess.run([self.zig, "build", *(args or ["test-host", "--summary", "all"])], + cwd=self.root, capture_output=True, text=True, timeout=120) + + def assert_failed_with(self, result, message): + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(message, result.stdout + result.stderr) + + def test_new_named_host_test_is_included_after_the_collector_is_declared(self): + result = self.build(' b.step("test-new-host", "new host test").dependOn(&b.addFail("new host test reached").step);') + self.assert_failed_with(result, "new host test reached") + + def test_existing_unnamed_unit_tests_are_preserved(self): + result = self.build(' b.step("test", "existing units").dependOn(&b.addFail("existing units reached").step);') + self.assert_failed_with(result, "existing units reached") + + def test_new_compile_only_check_is_included(self): + (self.root / "broken.zig").write_text('comptime { @compileError("new compile check reached"); }\n') + result = self.build(''' const check = b.addObject(.{ .name = "compile-only", .root_module = b.createModule(.{ + .root_source_file = b.path("broken.zig"), .target = target, + }) }); + b.step("check-new-host", "compile only").dependOn(&check.step);''') + self.assert_failed_with(result, "new compile check reached") + + def test_reviewed_external_requirements_are_not_executed(self): + result = self.build() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn("external gate ran", result.stdout + result.stderr) + + def test_alias_to_an_excluded_check_is_rejected(self): + result = self.build(''' b.step("test-alias", "alias").dependOn(&b.top_level_steps.get("test-grammar-budget").?.step);''') + self.assert_failed_with(result, "test-host reaches excluded test-grammar-budget") + self.assertNotIn("external gate ran", result.stdout + result.stderr) + + def test_direct_alias_to_an_excluded_action_is_rejected(self): + result = self.build(''' const external = b.top_level_steps.get("test-grammar-tools").?; + b.step("test-action-alias", "alias").dependOn(external.step.dependencies.items[0]);''') + self.assert_failed_with(result, "test-host reaches excluded test-grammar-tools") + self.assertNotIn("external gate ran", result.stdout + result.stderr) + + def test_empty_named_check_is_rejected(self): + result = self.build(' _ = b.step("test-empty", "accidentally disconnected");') + self.assert_failed_with(result, "named check test-empty has no build steps") + + def test_removed_external_step_requires_review_of_its_exclusion(self): + result = self.build(omit="test-grammar-tools") + self.assert_failed_with(result, "stale exclusion test-grammar-tools") + + def test_cross_target_does_not_acquire_a_native_host_aggregate(self): + result = self.build(args=["--help", "-Dtarget=x86_64-windows-gnu"]) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertNotIn("test-host", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/zig/build/host_tests.zig b/zig/build/host_tests.zig new file mode 100644 index 00000000000..ed6e7b1a4eb --- /dev/null +++ b/zig/build/host_tests.zig @@ -0,0 +1,73 @@ +//! Native Linux CI collects named host tests and compile checks after every build module has registered its steps. +const std = @import("std"); +const Step = std.Build.Step; +const Set = std.AutoHashMapUnmanaged(*Step, void); + +const Exclusion = struct { name: []const u8, reason: []const u8 }; +const exclusions = [_]Exclusion{ + .{ .name = "test-grammar-budget", .reason = "Requires the optional xgrammar checkout and -Dxgrammar=DIR" }, + .{ .name = "test-grammar-tools", .reason = "Requires the optional xgrammar checkout and -Dxgrammar=DIR" }, + .{ .name = "check-release-paths", .reason = "The release-paths CI job checks the separately built release server" }, + .{ .name = "test-startup-states-timing", .reason = "Manual disk startup timing seeds up to 100,000 states" }, + .{ .name = "test-imprint-ops-timing", .reason = "Manual Imprint timing seeds up to 100,000 learned states" }, + .{ .name = "test-metal-residency-owners-host", .reason = "red on main, #2031 (Qwen27 recording fixture leaves Runner.kv unset)" }, + .{ .name = "test-qwen35-draft-frame-host", .reason = "red on main, #2031 (recording fixture leaves seg_fn uninitialized)" }, + .{ .name = "test-qwen35-frame-invalidation-host", .reason = "red on main, #2031 (same recording fixture as test-qwen35-draft-frame-host)" }, + .{ .name = "test-gradient-serving", .reason = "red on main, #2031 (Flash Next hyper-connection source pin drifted)" }, +}; + +pub fn wire(b: *std.Build, target: std.Build.ResolvedTarget) void { + const host = b.graph.host.result; + if (host.os.tag != .linux or target.result.os.tag != host.os.tag or + target.result.cpu.arch != host.cpu.arch or target.result.abi != host.abi) return; + + const all = b.step("test-host", "Native Linux host tests and compile checks with reviewed exclusions"); + var rejected: std.ArrayList(*Step) = .empty; + for (b.top_level_steps.values()) |top| { + const name = top.step.name; + if (&top.step == all or !isCheck(name) or exclusion(name) != null) continue; + if (top.step.dependencies.items.len == 0) + reject(b, &rejected, b.fmt("test-host: named check {s} has no build steps", .{name})); + all.dependOn(&top.step); + } + + var included: Set = .empty; + collect(b.allocator, all, &included); + for (exclusions) |entry| { + const top = b.top_level_steps.get(entry.name) orelse { + reject(b, &rejected, b.fmt("test-host: stale exclusion {s}: {s}", .{ entry.name, entry.reason })); + continue; + }; + var visited: Set = .empty; + if (includedBoundary(b.allocator, &top.step, &included, &visited)) + reject(b, &rejected, b.fmt("test-host reaches excluded {s}: {s}", .{ entry.name, entry.reason })); + } + if (rejected.items.len != 0) all.dependencies = rejected; +} + +fn reject(b: *std.Build, rejected: *std.ArrayList(*Step), message: []const u8) void { + rejected.append(b.allocator, &b.addFail(message).step) catch @panic("OOM"); +} + +fn isCheck(name: []const u8) bool { + return std.mem.eql(u8, name, "test") or std.mem.startsWith(u8, name, "test-") or + std.mem.startsWith(u8, name, "check-"); +} + +fn exclusion(name: []const u8) ?Exclusion { + for (exclusions) |entry| if (std.mem.eql(u8, name, entry.name)) return entry; + return null; +} + +fn collect(a: std.mem.Allocator, root: *Step, seen: *Set) void { + if ((seen.getOrPut(a, root) catch @panic("OOM")).found_existing) return; + for (root.dependencies.items) |dep| collect(a, dep, seen); +} + +fn includedBoundary(a: std.mem.Allocator, root: *Step, included: *const Set, seen: *Set) bool { + if ((seen.getOrPut(a, root) catch @panic("OOM")).found_existing) return false; + if (included.contains(root)) return true; + if (root.tag != .top_level) return false; + for (root.dependencies.items) |dep| if (includedBoundary(a, dep, included, seen)) return true; + return false; +} diff --git a/zig/kernels/metal/core/bf16_argmax.metal b/zig/kernels/metal/core/bf16_argmax.metal new file mode 100644 index 00000000000..83cc0b90570 --- /dev/null +++ b/zig/kernels/metal/core/bf16_argmax.metal @@ -0,0 +1,41 @@ +// The greedy draw for decode glue: a bf16 logits row's argmax, NaN first, ties to the lower id (MLX argmax). +#include +using namespace metal; + +// The better of two (value, id) candidates: NaN first (lower id among NaNs), then the larger value, then the lower id. +inline bool tf_bf16_argmax_better(float a, uint ia, float b, uint ib) { + if (isnan(a)) return !isnan(b) || ia < ib; + if (isnan(b)) return false; + return a > b || (a == b && ia < ib); +} + +// Kernel NAME: logits [vocab] bf16 to its argmax in ids[0], one threadgroup of 1024. +#define TF_BF16_ARGMAX(NAME) \ + [[kernel]] void NAME(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], \ + constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { \ + threadgroup float vals[32]; \ + threadgroup uint idxs[32]; \ + float best = -INFINITY; \ + uint at = 0xffffffffu; \ + for (uint i = t; i < vocab; i += 1024) { \ + const float v = float(logits[i]); \ + if (tf_bf16_argmax_better(v, i, best, at)) { best = v; at = i; } \ + } \ + for (ushort d = 16; d > 0; d >>= 1) { \ + const float ov = simd_shuffle_xor(best, d); \ + const uint oi = simd_shuffle_xor(at, d); \ + if (tf_bf16_argmax_better(ov, oi, best, at)) { best = ov; at = oi; } \ + } \ + if (lane == 0) { vals[sg] = best; idxs[sg] = at; } \ + threadgroup_barrier(mem_flags::mem_threadgroup); \ + if (sg != 0) return; \ + best = vals[lane]; \ + at = idxs[lane]; \ + for (ushort d = 16; d > 0; d >>= 1) { \ + const float ov = simd_shuffle_xor(best, d); \ + const uint oi = simd_shuffle_xor(at, d); \ + if (tf_bf16_argmax_better(ov, oi, best, at)) { best = ov; at = oi; } \ + } \ + if (lane == 0) ids[0] = at; \ + } diff --git a/zig/kernels/metal/llama/glue.metal b/zig/kernels/metal/llama/glue.metal index 33311408352..55a8bac131e 100644 --- a/zig/kernels/metal/llama/glue.metal +++ b/zig/kernels/metal/llama/glue.metal @@ -230,41 +230,8 @@ struct ll_vec_args { uint rows, pos, heads, groups, blocks, chunk, first; float for (uint j = 0; j < PER; ++j) O[(row * a.heads + head) * DH + PER * sg + j] = bfloat(acc[j]); } -inline bool ll_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw (nemotron_glue's tf_argmax_bf16): a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void ll_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (ll_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (ll_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (ll_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(ll_argmax) // The bf16 linear rows ll_matvec_1 to ll_matvec_32 (core/bf16_matvec.metal). TF_BF16_MATVECS(ll) diff --git a/zig/kernels/metal/minimax_m3/glue.metal b/zig/kernels/metal/minimax_m3/glue.metal index ccdd1bd8594..0b798224edd 100644 --- a/zig/kernels/metal/minimax_m3/glue.metal +++ b/zig/kernels/metal/minimax_m3/glue.metal @@ -528,41 +528,8 @@ struct mm_vec_args { uint rows, pos, heads, groups, topk; float scale; uint sel, *(device bfloat4*)(O + (row * a.heads + head) * 128 + 4 * lane) = bfloat4(acc); } -inline bool mm_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw: a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void mm_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (mm_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (mm_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(mm_argmax) // bf16 rows into fp32 ones (n values): an image's rows over their placeholders' embeddings, the tower's pre-norm out. diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 5c28fc732fc..90556bce078 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -188,7 +188,7 @@ pub const core_simd_qmm_bits = @embedFile("core/simd_qmm_bits.metal"); /// Step-5's glue at StepFun's rounding points: embed, norms, q/k rotation, gate, SwiGLU, residual adds. pub const step5_glue = @embedFile("step5/glue.metal"); /// MiniMax-M3's glue at transformers' rounding points: norms, rotation, SwiGLU-OAI, router, indexer, decode attention. -pub const minimax_m3_glue = @embedFile("minimax_m3/glue.metal"); +pub const minimax_m3_glue = @embedFile("core/bf16_argmax.metal") ++ @embedFile("minimax_m3/glue.metal"); /// MiniMax-M3's prompt attention on the tensor units over each row's kept index blocks. pub const minimax_m3_attention_nax = @embedFile("minimax_m3/attention_nax.metal"); /// MiniMax-M3's DSpark drafter (norms, q/k into its context rings, block attention, the Markov chain) and the taps. @@ -210,13 +210,13 @@ pub const step5_attend_nax = @embedFile("step5/attend_nax.metal"); /// Step-5's image tower (perception encoder, downsampler convs, projector) on gemm_nax's tensor-unit GEMMs. pub const step5_vision = vision_glue ++ @embedFile("step5/vision.metal"); /// Spark2.5's glue at its PyTorch rounding points: embed, fp32 residual adds and norms, rope, head gate, exact GELU. -pub const spark25_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("spark25/glue.metal"); +pub const spark25_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("spark25/glue.metal"); /// Spark2.5's prompt attention on the tensor units (gemma4's prompt kernel; nax.h inlined at load). pub const spark25_attention_nax = @embedFile("spark25/attention_nax.metal"); /// Spark2.5's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). pub const spark25_gemm = gemm_nax ++ @embedFile("spark25/gemm.metal"); /// Llama's glue at HF's rounding points: embed, a bf16 residual and its norm, rope with bf16 cos and sin, SiLU. -pub const llama_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("llama/glue.metal"); +pub const llama_glue = @embedFile("core/bf16_matvec.metal") ++ @embedFile("core/bf16_argmax.metal") ++ @embedFile("llama/glue.metal"); /// Llama's prompt attention on the tensor units (gemma4's prompt kernel, every key; nax.h inlined at load). pub const llama_attention_nax = @embedFile("llama/attention_nax.metal"); /// Llama's bf16 prompt projections on gemm_nax's tensor-unit GEMM (nax.h inlined at load). diff --git a/zig/kernels/metal/spark25/glue.metal b/zig/kernels/metal/spark25/glue.metal index 9508cbb7b57..ecc49dc0f60 100644 --- a/zig/kernels/metal/spark25/glue.metal +++ b/zig/kernels/metal/spark25/glue.metal @@ -232,41 +232,8 @@ struct sp_vec_args { uint rows, pos, heads, groups, ring, window, blocks, chunk, for (uint j = 0; j < PER; ++j) O[(row * a.heads + head) * DH + PER * sg + j] = bfloat(acc[j]); } -inline bool sp_better(float a, uint ia, float b, uint ib) { - if (isnan(a)) return !isnan(b) || ia < ib; - if (isnan(b)) return false; - return a > b || (a == b && ia < ib); -} - -// The greedy draw (nemotron_glue's tf_argmax_bf16): a bf16 logits row's argmax, ties to the lower id, into ids[0]. -[[kernel]] void sp_argmax(const device bfloat* logits [[buffer(0)]], device uint* ids [[buffer(1)]], - constant uint& vocab [[buffer(2)]], uint t [[thread_position_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float vals[32]; - threadgroup uint idxs[32]; - float best = -INFINITY; - uint at = 0xffffffffu; - for (uint i = t; i < vocab; i += 1024) { - const float v = float(logits[i]); - if (sp_better(v, i, best, at)) { best = v; at = i; } - } - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (sp_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) { vals[sg] = best; idxs[sg] = at; } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg != 0) return; - best = vals[lane]; - at = idxs[lane]; - for (ushort d = 16; d > 0; d >>= 1) { - const float ov = simd_shuffle_xor(best, d); - const uint oi = simd_shuffle_xor(at, d); - if (sp_better(ov, oi, best, at)) { best = ov; at = oi; } - } - if (lane == 0) ids[0] = at; -} +// The greedy draw: a bf16 logits row's argmax into ids[0] (core/bf16_argmax.metal). +TF_BF16_ARGMAX(sp_argmax) // Row r of residual R = bf16 embedding row ids[r] (the release's table, [vocab, width]), held in fp32. [[kernel]] void sp_embed_bf16(const device uint* ids [[buffer(0)]], const device bfloat* E [[buffer(1)]], diff --git a/zig/src/cuda/tp_group.zig b/zig/src/cuda/tp_group.zig index cbe26f5b167..147b046ee56 100644 --- a/zig/src/cuda/tp_group.zig +++ b/zig/src/cuda/tp_group.zig @@ -61,7 +61,8 @@ pub const Group = struct { g.multi = null; } - fn destroyComm(g: *Group) void { + /// Once only, and never after an abort: an owner's unwind and its abort share `aborted`. + pub fn destroyComm(g: *Group) void { if (!g.aborted.swap(true, .acq_rel)) _ = g.lib.api.ncclCommDestroy(g.comm); } diff --git a/zig/src/fabric/tp/bootstrap.zig b/zig/src/fabric/tp/bootstrap.zig index 84eb13d0160..1f133f09ccd 100644 --- a/zig/src/fabric/tp/bootstrap.zig +++ b/zig/src/fabric/tp/bootstrap.zig @@ -222,7 +222,13 @@ test "three ranks gather in rank order and agree" { var outs: [3][3][32]u8 = undefined; var errs: [3]?anyerror = @splat(null); var threads: [2]std.Thread = undefined; - for (0..2) |i| threads[i] = try std.Thread.spawn(.{}, testRank, .{ Config{ .world = 3, .rank = @intCast(i + 1), .link_port = l.port, .connect_timeout_ns = 5 * std.time.ns_per_s }, &outs[i + 1], &errs[i + 1] }); + var started: usize = 0; + // the ranks write to this frame: every return first joins the started ones (their deadlines bound it) + defer for (threads[0..started]) |t| t.join(); + for (0..2) |i| { + threads[i] = try std.Thread.spawn(.{}, testRank, .{ Config{ .world = 3, .rank = @intCast(i + 1), .link_port = l.port, .connect_timeout_ns = 5 * std.time.ns_per_s }, &outs[i + 1], &errs[i + 1] }); + started = i + 1; + } var b = try Bootstrap.acceptOn(l.fd, 3, 5 * std.time.ns_per_s); defer b.close(); var id: [32]u8 = undefined; @@ -232,6 +238,7 @@ test "three ranks gather in rank order and agree" { const all = try b.allGather(&.{0}, &buf, &blobs); try b.agree("same", "settings"); for (threads) |t| t.join(); + started = 0; // joined above, so a failed check below does not join them again for (errs) |e| try std.testing.expect(e == null); try std.testing.expectEqual(@as(usize, 3), all.len); try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2 }, all[2]); diff --git a/zig/src/fabric/tp/group.zig b/zig/src/fabric/tp/group.zig index 409eaeefc09..ea8cb04d34f 100644 --- a/zig/src/fabric/tp/group.zig +++ b/zig/src/fabric/tp/group.zig @@ -16,6 +16,8 @@ pub const Backend = struct { world: u32, /// The family's group once it is up (serving): gathers then take its size rule. Null: plain NCCL calls. group: ?*cuda.tp_group.Group = null, + /// The group that owns `comm` from the start (aborts go through it); null: the caller owns it and aborts it. + owner: ?*cuda.tp_group.Group = null, aborted: std.atomic.Value(bool) = .init(false), /// The underlying error of the calling thread's last failed call (`Error` is a fixed set; the family reads this). last: ?anyerror = null, @@ -122,11 +124,11 @@ pub const Backend = struct { }; } - /// Any thread; only the first acts. The group aborts; with none, only later calls stop (T1: the mesh owns comms). + /// Any thread; only the first acts. The owner (or the routing group) aborts; with neither, only later calls stop. fn abort(ptr: *anyopaque) void { const b = of(ptr); if (b.aborted.swap(true, .acq_rel)) return; - if (b.group) |g| g.abort(); + if (b.owner orelse b.group) |g| g.abort(); } }; @@ -146,6 +148,7 @@ const Fake = struct { var wired: struct { s: cuda.abi.Stream, mine: DevicePtr, all: DevicePtr, bytes: usize } = undefined; var abort_inside: ?*Backend = null; // a fake NCCL call that another thread aborts while it is pending var aborts: usize = 0; + var destroys: usize = 0; var fail = false; fn allGather(s: DevicePtr, r: DevicePtr, count: usize, t: cuda.nccl.DataType, _: cuda.nccl.Comm, st: coll.Stream) callconv(.c) cuda.nccl.Result { gathers[n] = .{ .s = s, .r = r, .count = count, .t = t, .st = st }; @@ -160,6 +163,10 @@ const Fake = struct { aborts += 1; return 0; } + fn commDestroy(_: cuda.nccl.Comm) callconv(.c) cuda.nccl.Result { + destroys += 1; + return 0; + } fn fits(_: *anyopaque, bytes: usize) bool { return bytes <= 4096; } @@ -175,6 +182,7 @@ const Fake = struct { n = 0; multi = 0; aborts = 0; + destroys = 0; fail = false; abort_inside = null; } @@ -287,3 +295,24 @@ test "a call another thread aborts while it is pending ends as Aborted, not as a // the group's own failed call after its abort: Aborted, not NCCL's error (lib.check's fatal stop outside tests) try testing.expectError(error.Aborted, g.allGather(.{ .d = undefined, .handle = test_stream }, 0x100, 0x200, 16)); } + +test "with an owner and no routing group, abort aborts the owner's communicator once and its destroy then does nothing" { + Fake.reset(); + const lib = fakeLib(); + var owner: cuda.tp_group.Group = .{ .lib = fakeLib(), .comm = null, .rank = 0, .world = 2 }; + owner.lib.api.ncclCommDestroy = Fake.commDestroy; + var b: Backend = .{ .d = undefined, .lib = &lib, .comm = null, .rank = 0, .world = 2, .owner = &owner }; + const c = b.collective(); + c.abort(); + c.abort(); + try testing.expectEqual(@as(usize, 1), Fake.aborts); + owner.destroyComm(); + try testing.expectEqual(@as(usize, 0), Fake.destroys); + try testing.expectError(error.Aborted, c.allGather(0x100, 0x200, 4, .f32, test_stream)); + // the routing group installed later is the same group: one abort still + Fake.reset(); + var g: cuda.tp_group.Group = .{ .lib = fakeLib(), .comm = null, .rank = 0, .world = 2 }; + var bg: Backend = .{ .d = undefined, .lib = &lib, .comm = null, .rank = 0, .world = 2, .owner = &g, .group = &g }; + bg.collective().abort(); + try testing.expectEqual(@as(usize, 1), Fake.aborts); +} diff --git a/zig/src/fabric/tp/roce_multi_session.zig b/zig/src/fabric/tp/roce_multi_session.zig index 4072e836a3a..51b2969b450 100644 --- a/zig/src/fabric/tp/roce_multi_session.zig +++ b/zig/src/fabric/tp/roce_multi_session.zig @@ -125,9 +125,16 @@ test "multirank probe: one rank's mismatch leaves every rank without the wire; m defer sock.close(l.fd); var v: Vote = .{ .port = l.port, .lfd = l.fd, .odd = odd }; var t: [2]std.Thread = undefined; - for (&t, 1..) |*x, me| x.* = try std.Thread.spawn(.{}, Vote.rank, .{ &v, @as(u32, @intCast(me)) }); + var started: usize = 0; + // the ranks use this frame's vote: a failed spawn first joins the started ones (their deadlines bound it) + defer for (t[0..started]) |x| x.join(); + for (&t, 1..) |*x, me| { + x.* = try std.Thread.spawn(.{}, Vote.rank, .{ &v, @as(u32, @intCast(me)) }); + started = me; + } v.rank(0); for (t) |x| x.join(); + started = 0; // joined above, so a failed check below does not join them again for (v.errs) |e| try std.testing.expectEqual(@as(?anyerror, null), e); for (v.kept) |k| try std.testing.expectEqual(odd == null, k); } diff --git a/zig/src/families/glm/cuda_engine.zig b/zig/src/families/glm/cuda_engine.zig index 431535318ba..3cc2adec230 100644 --- a/zig/src/families/glm/cuda_engine.zig +++ b/zig/src/families/glm/cuda_engine.zig @@ -149,7 +149,7 @@ pub const Engine = struct { const share = try shard.Share.of(&c, tg.rank, tg.world); const backend = try gpa.create(tp.group.Backend); errdefer gpa.destroy(backend); - backend.* = .{ .d = d, .lib = lib, .comm = comm, .rank = tg.rank, .world = tg.world }; + backend.* = .{ .d = d, .lib = lib, .comm = comm, .rank = tg.rank, .world = tg.world, .owner = o.owner }; const kb = @import("cuda_kda_block.zig"); kb.pad_to = if (o.settings.kda_pad) kb.padWidth(c.kda_heads, world) else 0; // read once: rowWidth reads only this const spans = try gpa.alloc(shard.Span, world); diff --git a/zig/src/families/glm/cuda_engine_types.zig b/zig/src/families/glm/cuda_engine_types.zig index 98fa0b6c365..280f12aa2a6 100644 --- a/zig/src/families/glm/cuda_engine_types.zig +++ b/zig/src/families/glm/cuda_engine_types.zig @@ -45,4 +45,5 @@ pub const Options = struct { settings: ranks.Settings, vision: ?images_mod.Limits = null, // --vision's limits (null: off): every rank must hold the rows rank 0 sends drafter: bool = false, // DFlash2 loads after rank agreement + owner: ?*cuda.tp_group.Group = null, // the communicator's owner, which the backend aborts (null: the caller's own) }; diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index 4a1f5cd1a5c..5522d5bd889 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -272,14 +272,14 @@ fn openRank(a: StartArgs, set: ranks.Settings) !Loaded { } else id.internal = try cuda.tp_watch.takeId(io); // rank 0's, over this rank's line const comm = try cuda.startup_log.init(io, &lib, id, p.rank, p.world); own.group = .{ .lib = lib, .comm = comm, .rank = p.rank, .world = p.world }; - errdefer _ = own.group.lib.api.ncclCommDestroy(own.group.comm); + errdefer own.group.destroyComm(); // guarded: after an abort it destroys nothing cuda.p2p_report.beforePeers(&diag, .{ .lib = &own.group.lib, .comm = comm, .later = true }); own.progress.enter(.peer_warmup); if (p.world > 1) try @import("cuda_warm_peers.zig").warm(io, ctx.d, &own.group, .of(set.split, set.ring), &diag); cuda.p2p_report.afterInit(&diag, .{ .lib = &own.group.lib, .comm = comm, .d = ctx.d, .later = true }); const cap = capacity(o.context); own.progress.enter(.weights); - own.e = try engine.Engine.init(gpa, io, ctx.d, ctx, dir, &own.group.lib, own.group.comm, p.rank, p.world, .{ .capacity = cap, .mtp = o.drafts, .settings = set, .vision = o.vision, .drafter = o.drafter != null }); + own.e = try engine.Engine.init(gpa, io, ctx.d, ctx, dir, &own.group.lib, own.group.comm, p.rank, p.world, .{ .capacity = cap, .mtp = o.drafts, .settings = set, .vision = o.vision, .drafter = o.drafter != null, .owner = &own.group }); errdefer own.e.deinit(); if (o.vision) |lim| { // before the rooms: the tower's bytes count against rank 0's var problem: []const u8 = ""; diff --git a/zig/tests/contract/metal_minimax_glue.zig b/zig/tests/contract/metal_minimax_glue.zig index 9ffc8165abd..1ea2b1f6b3c 100644 --- a/zig/tests/contract/metal_minimax_glue.zig +++ b/zig/tests/contract/metal_minimax_glue.zig @@ -422,7 +422,7 @@ pub const Copy = struct { // --- mm_argmax: the greedy draw over a bf16 logits row, ties to the lower id --------------------------------------- -/// mm_better: NaN beats any number (the lower id among NaNs), else the larger value, ties to the lower id. +/// tf_bf16_argmax_better (core/bf16_argmax.metal): NaN first (lower id among NaNs), then larger, ties to the lower id. fn better(v: f32, i: usize, best: f32, at: usize) bool { if (std.math.isNan(v)) return !std.math.isNan(best) or i < at; if (std.math.isNan(best)) return false; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 3d3c09e7466..58fad54fe20 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -110,7 +110,7 @@ zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d578 zig/src/cuda/sample.zig 5d374b5cd2108fd90b383cfec0a63bdce038eef8c380289495e5b9d080c590f2 raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged) zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125db2199fa6 raw commits e9bf05ffd, ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/tp_group.zig cc353741ff13422e24f5c5434af189c81663e70eaf831afd6ec1e468c8204d25 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally) +zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw zig/src/cuda/vit.zig 72c4301251f50d0f25907f0d8ad03a943281b234c506a455e413627a3ffe09c0 raw