diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b978738db7..4395a96ba73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Tests: the CUDA kernel-contract runner takes opt-in `--jobs N` and `--shard I/N`; four jobs run the served suites in 1:11:50 against 3:17:59 one at a time, with identical summaries (#3093). Thanks to @BlivionIaG. + - Tests: the lane host explore test's replay holds under load: once every request sent has ended, the test thread sends the next only once a whole engine turn has run after the one that ended the last (turns counted through the host's activity scope), so each send meets no prompt visit and lands at the same point on every run (#5386, fixes #5367). - Vulkan on Apple silicon: submits batch dispatches into one command buffer per batch instead of one submission per dispatch, with hazard-tracked barriers between conflicting dispatches and one barrier owed to the previous submission at the next batch's start; the same logits, 2% to 20% less run time on a 13-inch M1 and a 16-inch M1 Max (#2038, part of #1420). Thanks to @joshuaswarren. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index df58aa74570..532c8b06672 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -101,6 +101,34 @@ On sm_110, some 48 KiB dynamic shared-memory kernels carry another 1 KiB of stat Only their sm_110 audit uses the opt-in limit already raised by their loaders (`allowDynamicShared`). For a mixed release and sm_110 set, each planted control must go red on each target separately. +`tf-cuda-test kernel-contract` alone is the full serial run in one process. Two opt-in modes change that, each apart +from the other, and they compose: + +- Filter: `tf-cuda-test kernel-contract WORD...` runs the kernels, controls and launches whose name holds a WORD. It + skips the standalone suites and the offline limits audit, and marks its `SUMMARY` `(filtered)`. +- Parallel: `tf-cuda-test kernel-contract --jobs N` (N from 1 to 16) starts N child processes of the same binary, + each a shard `K/N`: every N-th kernel, control, standalone suite and launch record, on the visible GPUs in turn. + The shares are equal in count; a kernel's cost is not known when they are cut, so one shard can finish before + another. It prints the children's logs and one merged `SUMMARY`, and exits 1 if any child crashed or printed no + `TALLY` line, or the merged counts show a problem. N never rises by itself. + A process is planned for 28 GiB of host memory for a full run and 8 GiB when WORDs filter it, and 7 GiB of GPU + memory. The run is refused when N processes do not fit the host's available memory (`MemAvailable` in + `/proc/meminfo`, so Linux only), or when `ceil(N / GPUs)` processes do not fit the smallest GPU's total memory + (not its free memory); several processes share a GPU only when they fit. On an integrated GPU, which shares the + host's memory, N times both plans must fit the host's available memory and no GPU total is checked. GPUs that + differ in compute capability, multiprocessor count or name are refused, since registration reads those to pick + kernel configurations and their shards would not list the same kernels. + A shard stops when the process that started it does (`PR_SET_PDEATHSIG`), SIGINT and SIGTERM sent to that process + are forwarded to its shards, and once one shard fails to finish the others are stopped. + `--shard K/N [--device D]` runs one shard alone and prints its `TALLY` line (the machine-readable counts the + parent merges) in place of a `SUMMARY`; `--device` goes with `--shard` only, and so does `--parent PID`, which + the `--jobs` process passes so that a shard refuses to run once that process is gone. + With words the filter applies first and each shard takes its share of what is left. + `kernel-contract --help` prints these options. + The standalone suites of a full run are the entries of `list` in `contract_back_suites.zig` and of `served` in + `contract_after.zig`; the serial run and every shard read that one table, so a new suite is listed in one of them + and a suite called from anywhere else runs in neither. + On an AMD machine, run `zig build hip-kernel-contract -Dhip-arch=ARCH -Dhipcc=...` on a GPU of that chip (the controls are built with the kernels). For the limits of every served chip, `zig build hip-kernel-contract-limits -Dhipcc=...` compiles every kernel group and the controls for gfx1030, gfx1100, gfx1151 and gfx1201 and checks each diff --git a/zig/build/contract_shard_host.zig b/zig/build/contract_shard_host.zig new file mode 100644 index 00000000000..ed91e97bc8e --- /dev/null +++ b/zig/build/contract_shard_host.zig @@ -0,0 +1,23 @@ +//! Host tests of kernel-contract's sharded run: the partition, options, tally merge and shard processes, no GPU code. +const std = @import("std"); + +pub fn host(b: *std.Build, core: *std.Build.Module, all: *std.Build.Step) void { + const run = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_shard_host.zig"), + .target = b.graph.host, + .optimize = .debug, + .imports = &.{.{ .name = "core", .module = core }}, + }) })); + const step = b.step("test-contract-shard-host", "kernel-contract --jobs and --shard: partition, options, merge and shard processes without a GPU"); + step.dependOn(&run.step); + all.dependOn(&run.step); + if (b.graph.host.result.os.tag == .windows) return; // the shard processes are POSIX + const processes = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/cuda/contract_children_host.zig"), + .target = b.graph.host, + .optimize = .debug, + }) })); + processes.has_side_effects = true; + step.dependOn(&processes.step); + all.dependOn(&processes.step); +} diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 97573f8fd0c..f1ec4d84dc5 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -300,6 +300,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st for ([_]*std.Build.Module{ mods.nemotron, mods.qwen35, flashnextModule(b, host, .debug, cuda, mods.core, mods.lanes, mods.qwen_vision, mods.api) }) |m| skip_drafts.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"zero grant:"} })).step); @import("qmmf_prompt_host.zig").steps(b, cuda, mods.core, step); @import("qwen_contract.zig").host(b, mods.core, step); + @import("contract_shard_host.zig").host(b, mods.core, step); @import("qwen_vision_weights_host.zig").host(b, mods.core, step); @import("inc4_host.zig").round(b, cuda, mods.core); @import("inc4_host.zig").rows(b, cuda, mods.core); diff --git a/zig/tests/cuda/contract_after.zig b/zig/tests/cuda/contract_after.zig index a3bc28ec216..3d8f9838b7e 100644 --- a/zig/tests/cuda/contract_after.zig +++ b/zig/tests/cuda/contract_after.zig @@ -1,24 +1,18 @@ -//! kernel-contract's words (`only`): the kernels so named, and the suites that run after the gates on a full run. +//! kernel-contract's gates over its words and shard, and the suites that run after them on a full run. const std = @import("std"); const g = @import("core").contract.gates; const check = @import("check.zig"); +const shard = @import("contract_shard.zig"); +const back = @import("contract_back_suites.zig"); /// Whether `only` names kernels to keep: without plain words (none, or only `-word`s) the run is a full one. pub fn filtered(only: []const []const u8) bool { - for (only) |w| if (!std.mem.startsWith(u8, w, "-")) return true; - return false; + return shard.hasPositive(only); } /// Whether `name` holds no `-word` and, when plain words are given, one of them. pub fn wanted(name: []const u8, only: []const []const u8) bool { - var named = !filtered(only); - for (only) |w| { - const minus = std.mem.startsWith(u8, w, "-"); - const hit = std.mem.indexOf(u8, name, if (minus) w[1..] else w) != null; - if (minus and hit) return false; - named = named or hit; - } - return named; + return shard.wanted(name, only); } /// Keeps the kernels `wanted` keeps; empty keeps every one. @@ -31,16 +25,45 @@ pub fn keep(kernels: *std.ArrayList(g.Kernel), only: []const []const u8) void { kernels.shrinkRetainingCapacity(kept); } -/// The served, paged, pending, learning, lane and SwiGLU pair suites of a full run, and int4's skipped slot. -pub fn suites(gpu: check.Gpu) !void { - try @import("tfq3_tests.zig").run(gpu); - try @import("contract_qwen_served.zig").run(gpu); - try @import("contract_qwen_pages.zig").run(gpu); - try @import("contract_qwen_shared_prefix.zig").run(gpu, &.{}); - try @import("contract_qwen_pending.zig").run(gpu); - try @import("contract_qwen_learning.zig").numerical(gpu); - try @import("contract_fn_lanes.zig").run(gpu); - try @import("contract_prompt_swiglu.zig").run(gpu); - // int4's gates are registrations (the filter selects them); its plan's skipped slot is not one - try @import("contract_int4_run.zig").skippedAlone(gpu); +/// Dumps if asked, then gates 1-4 on `opt`'s share of the kernels; `t0` is the clock at the first gate. +pub fn gates(gpu: check.Gpu, kernels: *std.ArrayList(g.Kernel), opt: shard.Options, t0: *i96, listed: *usize) !g.Tally { + var t: g.Tally = .{}; + try @import("contract_dump.zig").run(gpu.gpa, kernels.items); + t0.* = check.now(gpu.io); + keep(kernels, opt.words); + listed.* = shard.keep(g.Kernel, kernels, &.{}, opt.effectiveShard()); + try g.runAll(gpu.gpa, kernels.items, 0x6b63, &t); + return t; +} + +fn sharedPrefix(gpu: check.Gpu) !void { + return @import("contract_qwen_shared_prefix.zig").run(gpu, &.{}); +} + +/// The served, paged, pending, learning, lane, TFQ3, SwiGLU and int4 skipped suites of a full run. +const served = [_]back.Suite{ + back.entry("tfq3", @import("tfq3_tests.zig").run), + back.entry("qwen-served", @import("contract_qwen_served.zig").run), + back.entry("qwen-pages", @import("contract_qwen_pages.zig").run), + back.entry("qwen-shared-prefix", sharedPrefix), + back.entry("qwen-pending", @import("contract_qwen_pending.zig").run), + back.entry("qwen-learning", @import("contract_qwen_learning.zig").numerical), + back.entry("fn-lanes", @import("contract_fn_lanes.zig").run), + back.entry("prompt-swiglu", @import("contract_prompt_swiglu.zig").run), + back.entry("int4-skipped", @import("contract_int4_run.zig").skippedAlone), +}; + +pub const Part = enum { back, after }; + +/// The suites of a full run in order, the gradient ones first; `sh` runs those whose index it owns. +pub fn suites(gpu: check.Gpu, part: Part, sh: shard.Shard, coverage: *shard.Coverage) !void { + const all = back.list ++ served; + const from: usize = if (part == .back) 0 else back.list.len; + const to: usize = if (part == .back) back.list.len else all.len; + coverage.of += to - from; + for (all[from..to], from..) |s, i| { + if (!sh.owns(i)) continue; + try s.run(gpu); + coverage.ran += 1; + } } diff --git a/zig/tests/cuda/contract_back_suites.zig b/zig/tests/cuda/contract_back_suites.zig index b8872258c99..f7191739f54 100644 --- a/zig/tests/cuda/contract_back_suites.zig +++ b/zig/tests/cuda/contract_back_suites.zig @@ -1,14 +1,31 @@ //! The gradient component suites the kernel contract runs after gates 1-4: FP64 and finite-difference checks. const check = @import("check.zig"); -const std = @import("std"); - -pub fn run(gpu: check.Gpu) !void { - try @import("gdn_back_tests.zig").run(gpu); - try @import("q4_back_tests.zig").run(gpu); - try @import("moe_back_tests.zig").run(gpu); - try @import("attn_back_tests.zig").run(gpu); - try @import("fn_hc_back_tests.zig").run(gpu); - try @import("fn_moe_back_tests.zig").run(gpu); - try @import("fn_pocket_tests.zig").run(gpu, 0); - std.debug.print("PASS gradient component suites (FP64 and finite-difference checks); resource receipts still required\n", .{}); + +/// A standalone suite of the full run: its name and its entry, which owns the device while it runs. +pub const Suite = struct { name: []const u8, run: *const fn (check.Gpu) anyerror!void }; + +/// A suite of any error set as a `Suite` entry. +pub fn entry(comptime name: []const u8, comptime f: anytype) Suite { + return .{ .name = name, .run = &struct { + fn call(gpu: check.Gpu) anyerror!void { + return f(gpu); + } + }.call }; +} + +fn pocket(gpu: check.Gpu) !void { + return @import("fn_pocket_tests.zig").run(gpu, 0); } + +pub const list = [_]Suite{ + entry("gdn-back", @import("gdn_back_tests.zig").run), + entry("q4-back", @import("q4_back_tests.zig").run), + entry("moe-back", @import("moe_back_tests.zig").run), + entry("attn-back", @import("attn_back_tests.zig").run), + entry("fn-hc-back", @import("fn_hc_back_tests.zig").run), + entry("fn-moe-back", @import("fn_moe_back_tests.zig").run), + entry("fn-pocket", pocket), +}; + +/// The line after all of `list` has passed. +pub const passed = "PASS gradient component suites (FP64 and finite-difference checks); resource receipts still required\n"; diff --git a/zig/tests/cuda/contract_children.zig b/zig/tests/cuda/contract_children.zig new file mode 100644 index 00000000000..930df298175 --- /dev/null +++ b/zig/tests/cuda/contract_children.zig @@ -0,0 +1,68 @@ +//! The shards a `kernel-contract --jobs` process starts and the process they must not outlive. +const std = @import("std"); +const builtin = @import("builtin"); + +/// Most shards at once; `contract_shard.max_jobs` may not exceed it. +pub const capacity = 16; + +var pids: [capacity]std.atomic.Value(i32) = @splat(.init(0)); +var stopped: [capacity]std.atomic.Value(bool) = @splat(.init(false)); +var stopping = std.atomic.Value(bool).init(false); + +/// Records shard `slot`'s process so a stop reaches it. +pub fn register(slot: usize, pid: std.posix.pid_t) void { + pids[slot].store(pid, .seq_cst); +} + +pub fn forget(slot: usize) void { + pids[slot].store(0, .seq_cst); +} + +/// Whether a stop signalled shard `slot`, as against the shard ending by itself. +pub fn wasStopped(slot: usize) bool { + return stopped[slot].load(.seq_cst); +} + +pub fn isStopping() bool { + return stopping.load(.seq_cst); +} + +/// Signals every registered shard but `except`; true for the first stop of the run, which should say why. +pub fn stopAll(except: ?usize, sig: std.posix.SIG) bool { + const first = !stopping.swap(true, .seq_cst); + for (&pids, 0..) |*slot, i| { + if (except == i) continue; + const pid = slot.load(.seq_cst); + if (pid <= 0) continue; + stopped[i].store(true, .seq_cst); + std.posix.kill(pid, sig) catch {}; + } + return first; +} + +fn onSignal(sig: std.posix.SIG) callconv(.c) void { + _ = stopAll(null, sig); +} + +/// SIGINT and SIGTERM sent to this process stop its shards too. +pub fn forwardSignals() void { + const act: std.posix.Sigaction = .{ .handler = .{ .handler = onSignal }, .mask = std.posix.sigemptyset(), .flags = 0 }; + std.posix.sigaction(.INT, &act, null); + std.posix.sigaction(.TERM, &act, null); +} + +/// This process's id, for its shards to hold it to. +pub fn selfPid() std.posix.pid_t { + return if (builtin.os.tag == .linux) std.os.linux.getpid() else 0; +} + +pub const ParentError = error{ ParentGone, ParentWatchFailed, ParentWatchNeedsLinux }; + +/// A shard's side: die with SIGKILL when the process that started it does, and refuse if that is already not `parent`. +pub fn followParent(parent: std.posix.pid_t) ParentError!void { + if (builtin.os.tag != .linux) return error.ParentWatchNeedsLinux; + const linux = std.os.linux; + const set = linux.prctl(@backingInt(linux.PR.SET_PDEATHSIG), @backingInt(linux.SIG.KILL), 0, 0, 0); + if (linux.errno(set) != .SUCCESS) return error.ParentWatchFailed; + if (linux.getppid() != parent) return error.ParentGone; +} diff --git a/zig/tests/cuda/contract_children_host.zig b/zig/tests/cuda/contract_children_host.zig new file mode 100644 index 00000000000..245fa11b86c --- /dev/null +++ b/zig/tests/cuda/contract_children_host.zig @@ -0,0 +1,59 @@ +//! kernel-contract's shard processes without a GPU: stopping them, forwarding signals and following the parent. +const std = @import("std"); +const builtin = @import("builtin"); +const t = std.testing; +const children = @import("contract_children.zig"); + +fn sleeper() !std.process.Child { + return std.process.spawn(t.io, .{ .argv = &.{ "/bin/sleep", "60" }, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore }); +} + +fn killedBy(child: *std.process.Child, sig: std.posix.SIG) !void { + const term = try child.wait(t.io); + try t.expect(term == .signal); + try t.expectEqual(sig, term.signal); +} + +test "shard children: a stop reaches every registered shard but the exception, and only the first says why" { + var kept = try sleeper(); + defer kept.kill(t.io); + var gone = try sleeper(); + defer gone.kill(t.io); + children.register(2, kept.id.?); + children.register(3, gone.id.?); + defer children.forget(2); + defer children.forget(3); + const already = children.isStopping(); + try t.expectEqual(!already, children.stopAll(2, .TERM)); + try killedBy(&gone, .TERM); + children.forget(3); + try t.expect(children.wasStopped(3)); + try t.expect(!children.wasStopped(2)); + try t.expect(!children.stopAll(2, .TERM)); + try t.expect(children.isStopping()); +} + +test "shard children: SIGTERM sent to the parent is forwarded to its shards" { + var child = try sleeper(); + defer child.kill(t.io); + children.register(0, child.id.?); + defer children.forget(0); + children.forwardSignals(); + defer { + const default: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0 }; + std.posix.sigaction(.TERM, &default, null); + std.posix.sigaction(.INT, &default, null); + } + try std.posix.raise(.TERM); + try killedBy(&child, .TERM); +} + +test "shard children: a shard follows the parent that started it, and refuses another" { + if (builtin.os.tag != .linux) return error.SkipZigTest; + const parent = std.os.linux.getppid(); + try children.followParent(parent); + try t.expectError(error.ParentGone, children.followParent(parent + 1)); + var armed: c_int = 0; + try t.expectEqual(@as(usize, 0), std.os.linux.prctl(@backingInt(std.os.linux.PR.GET_PDEATHSIG), @intFromPtr(&armed), 0, 0, 0)); + try t.expectEqual(@as(c_int, @backingInt(std.os.linux.SIG.KILL)), armed); +} diff --git a/zig/tests/cuda/contract_compile.zig b/zig/tests/cuda/contract_compile.zig index f306eb5547e..e46677de5ec 100644 --- a/zig/tests/cuda/contract_compile.zig +++ b/zig/tests/cuda/contract_compile.zig @@ -4,6 +4,7 @@ const check = @import("check.zig"); const limits = @import("contract_limits.zig"); export fn tf_compile_contract_consumers(gpu: *const check.Gpu, dir: [*:0]const u8) c_int { limits.fatbins(gpu.*, std.mem.span(dir)) catch return 1; - const problems = limits.live(gpu.*, &.{}) catch return 1; + var coverage: @import("contract_shard.zig").Coverage = .{}; + const problems = limits.live(gpu.*, &.{}, .{}, &coverage) catch return 1; return if (problems == 0) 0 else 1; } diff --git a/zig/tests/cuda/contract_finish.zig b/zig/tests/cuda/contract_finish.zig index ef068dd87d4..c7baa1f63aa 100644 --- a/zig/tests/cuda/contract_finish.zig +++ b/zig/tests/cuda/contract_finish.zig @@ -3,14 +3,27 @@ const std = @import("std"); const check = @import("check.zig"); const g = @import("core").contract.gates; const live = @import("contract_limits.zig").live; +const after = @import("contract_after.zig"); +const shard = @import("contract_shard.zig"); -pub fn run(gpu: check.Gpu, only: []const []const u8, t: g.Tally, t0: i96) !void { - const full = !@import("contract_after.zig").filtered(only); - if (full) try @import("contract_back_suites.zig").run(gpu); +/// `listed`: the kernels and controls the words named, of which `t` is this shard's share. +pub fn run(gpu: check.Gpu, opt: shard.Options, t: g.Tally, listed: usize, t0: i96) !void { + const sh = opt.effectiveShard(); + const full = !after.filtered(opt.words); + var suites: shard.Coverage = .{}; + if (full) try after.suites(gpu, .back, sh, &suites); + if (shard.printsGradientPass(if (opt.shard == null) .serial else .shard, !full)) std.debug.print("{s}", .{@import("contract_back_suites.zig").passed}); const t1 = check.now(gpu.io); - if (full) try @import("contract_after.zig").suites(gpu); - const lim = try live(gpu, only); + if (full) try after.suites(gpu, .after, sh, &suites); + var records: shard.Coverage = .{}; + const lim = try live(gpu, opt.words, sh, &records); const t2 = check.now(gpu.io); - std.debug.print("{s}SUMMARY {d} kernels: {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed; {d} limit problems; gates {d} ms, limits {d} ms\n", .{ if (only.len > 0) "(filtered) " else "", t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, lim, @divTrunc(t1 - t0, std.time.ns_per_ms), @divTrunc(t2 - t1, std.time.ns_per_ms) }); - try check.expect(t.problems() + lim == 0, "kernel-contract: {d} gate failures, {d} controls missed, {d} limit problems", .{ t.failed, t.missed, lim }); + const gates_ms: u64 = @intCast(@divTrunc(t1 - t0, std.time.ns_per_ms)); + const limits_ms: u64 = @intCast(@divTrunc(t2 - t1, std.time.ns_per_ms)); + const sum: shard.Summary = .{ .filtered = opt.words.len > 0, .tally = t, .limits = lim, .gates_ms = gates_ms, .limits_ms = limits_ms }; + if (opt.shard) |s| { + const report: shard.Report = .{ .shard = s, .listed = listed, .tally = t, .limits = lim, .suites = suites, .records = records, .gates_ms = gates_ms, .limits_ms = limits_ms }; + std.debug.print("{f}\n", .{report}); + } else std.debug.print("{f}\n", .{sum}); + try check.expect(sum.problems() == 0, "kernel-contract: {d} gate failures, {d} controls missed, {d} limit problems", .{ t.failed, t.missed, lim }); } diff --git a/zig/tests/cuda/contract_jobs.zig b/zig/tests/cuda/contract_jobs.zig new file mode 100644 index 00000000000..ee366fbde85 --- /dev/null +++ b/zig/tests/cuda/contract_jobs.zig @@ -0,0 +1,210 @@ +//! kernel-contract's opt-in parallel run: `--jobs N` starts N shards of this binary and prints one merged SUMMARY. +const std = @import("std"); +const cuda = @import("cuda"); +const shard = @import("contract_shard.zig"); +const dump = @import("byte_dump.zig"); +const children = @import("contract_children.zig"); +const after = @import("contract_after.zig"); + +/// The options of a `kernel-contract` command line, or null when `args` is another command's or does not parse. +fn options(a: std.mem.Allocator, args: []const [:0]const u8) ?shard.Options { + if (args.len < 2 or !std.mem.eql(u8, args[1], "kernel-contract")) return null; + return shard.parse(a, args[2..]) catch null; +} + +/// The visible GPU a `kernel-contract` shard runs on; 0 for every other command. +pub fn device(a: std.mem.Allocator, args: []const [:0]const u8) c_int { + const opt = options(a, args) orelse return 0; + defer opt.deinit(a); + return opt.device; +} + +/// Before any GPU context: `--help`, a refused command line or `--jobs` ends the process with its exit code; else null. +pub fn parent(init: std.process.Init, driver: *const cuda.Driver, args: []const [:0]const u8) !?u8 { + if (args.len < 2 or !std.mem.eql(u8, args[1], "kernel-contract")) return null; + for (args[2..]) |arg| if (std.mem.eql(u8, arg, "--help")) { + std.debug.print("{s}", .{shard.help}); + return 0; + }; + var culprit: shard.Culprit = .{}; + const opt = shard.parseNamed(init.gpa, args[2..], &culprit) catch |err| { + std.debug.print("FAIL kernel-contract: {f}: {t} ({s})\n{s}", .{ culprit, err, shard.hint(err), shard.help }); + return 2; + }; + defer opt.deinit(init.gpa); + // the child processes compile on POSIX targets only; elsewhere their options are refused, never ignored + if (comptime !shard.posix_processes) { + if (opt.processOption()) |name| { + std.debug.print("FAIL kernel-contract: {s}: child processes need a POSIX host, so run without it (NoProcesses)\n", .{name}); + return 2; + } + } else if (opt.parent) |pid| children.followParent(pid) catch |err| { + std.debug.print("FAIL kernel-contract: --parent {d}: {t}, so this shard stops rather than run on\n", .{ pid, err }); + return 2; + }; + const gpus = std.math.cast(u32, try driver.deviceCount()) orelse 0; + if (opt.shard != null and opt.device >= gpus) { + std.debug.print("FAIL kernel-contract: --device {d}: only {d} GPUs (NoSuchDevice)\n", .{ opt.device, gpus }); + return 2; + } + // without POSIX processes a --jobs was refused above, so this process runs alone + return if (comptime shard.posix_processes) parallel(init, driver, opt, gpus) else null; +} + +/// `--jobs`: the shards' child processes and their merged SUMMARY; null without `--jobs`. +fn parallel(init: std.process.Init, driver: *const cuda.Driver, opt: shard.Options, gpus: u32) !?u8 { + const jobs = opt.jobs orelse return null; + if (dump.active()) { + std.debug.print("FAIL kernel-contract: --jobs {d}: TF_CUDA_DUMP=1 would write every record {d} times (DumpWithJobs)\n", .{ jobs, jobs }); + return 2; + } + fit(init.io, driver, jobs, after.filtered(opt.words), gpus) catch return 2; + return try run(init, opt, jobs, gpus); +} + +/// Whether `jobs` processes fit the GPUs they would use and the host; a refusal is printed with what it compared. +fn fit(io: std.Io, driver: *const cuda.Driver, jobs: u32, filtered: bool, gpus: u32) !void { + var seen: [shard.max_jobs]shard.Gpu = undefined; + var m: shard.Machine = .{ .gpus = gpus, .gpu_mib = std.math.maxInt(u64), .host_mib = 0 }; + const used: u8 = @intCast(@min(gpus, jobs)); + var at: u8 = 0; + while (at < used) : (at += 1) { + const ordinal: c_int = at; + var dev: cuda.abi.Device = 0; + try driver.check(driver.api.cuDeviceGet(&dev, ordinal), "cuDeviceGet"); + seen[at] = .{ .sm = try driver.capability(ordinal), .multiprocessors = 0 }; + var count: c_int = 0; + try driver.check(driver.api.cuDeviceGetAttribute(&count, .multiprocessor_count, dev), "cuDeviceGetAttribute"); + seen[at].multiprocessors = std.math.cast(u32, count) orelse 0; + try driver.check(driver.api.cuDeviceGetName(&seen[at].name, seen[at].name.len - 1, dev), "cuDeviceGetName"); + var bytes: usize = 0; + try driver.check(driver.api.cuDeviceTotalMem_v2(&bytes, dev), "cuDeviceTotalMem"); + m.gpu_mib = @min(m.gpu_mib, bytes >> 20); + var shared: c_int = 0; + try driver.check(driver.api.cuDeviceGetAttribute(&shared, .integrated, dev), "cuDeviceGetAttribute"); + m.integrated = m.integrated or shared != 0; + } + if (shard.firstMixed(seen[0..used])) |mix| { + var line: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + shard.writeMix(&w, seen[0..used], mix) catch {}; + std.debug.print("FAIL kernel-contract: --jobs {d}: {s}, so their shards would not list the same kernels (MixedGpus: {t})\n", .{ jobs, w.buffered(), mix.field }); + return error.MixedGpus; + } + var buf: [8192]u8 = undefined; + const text = std.Io.Dir.cwd().readFile(io, "/proc/meminfo", &buf) catch |err| { + std.debug.print("FAIL kernel-contract: --jobs {d}: cannot read /proc/meminfo, which --jobs needs (Linux only): {t}\n", .{ jobs, err }); + return err; + }; + m.host_mib = shard.memAvailableMib(text) orelse { + std.debug.print("FAIL kernel-contract: --jobs {d}: /proc/meminfo has no MemAvailable line (UnreadableMeminfo)\n", .{jobs}); + return error.UnreadableMeminfo; + }; + shard.afford(jobs, filtered, m) catch |err| { + const host = if (filtered) shard.host_mib_filtered else shard.host_mib_full; + std.debug.print("FAIL kernel-contract: --jobs {d}: {t} (each process is planned for {d} GiB of host and {d} GiB of GPU memory; {d} GiB of host memory is available, {d} GPUs have {d} GiB in total{s})\n", .{ jobs, err, host >> 10, shard.device_mib_per_process >> 10, m.host_mib >> 10, m.gpus, m.gpu_mib >> 10, if (m.integrated) ", sharing the host's" else "" }); + return err; + }; +} + +/// One child: its command, what it printed that the parent reads, and how it ended. +const Job = struct { + io: std.Io, + slot: usize, + jobs: u32, + argv: []const []const u8, + report: ?shard.Report = null, + exit_code: ?u8 = null, + term: ?std.process.Child.Term = null, + failure: ?anyerror = null, + + fn finished(job: *const Job) bool { + return job.failure == null and shard.accepted(job.exit_code, job.report); + } + + fn watch(job: *Job) void { + job.drive() catch |err| { + job.failure = err; + }; + if (!job.finished() and children.stopAll(job.slot, .TERM)) + std.debug.print("FAIL kernel-contract: shard {d}/{d} did not finish, so the other shards are stopped\n", .{ job.slot, job.jobs }); + } + + /// Prints each line the child writes, whatever its length, and keeps its TALLY line. + const Lines = struct { + job: *Job, + + pub fn line(l: Lines, text: []const u8, cut: bool) !void { + if (cut) std.debug.print("{s} [line cut at {d} bytes]\n", .{ text, text.len }) else std.debug.print("{s}\n", .{text}); + if (!std.mem.startsWith(u8, text, "TALLY ")) return; + if (cut) return error.BadTally; + l.job.report = try shard.Report.parseLine(text); + } + }; + + fn drive(job: *Job) !void { + var child = try std.process.spawn(job.io, .{ .argv = job.argv, .stdin = .ignore, .stderr = .pipe }); + defer child.kill(job.io); + children.register(job.slot, child.id.?); + defer children.forget(job.slot); + if (children.isStopping()) std.posix.kill(child.id.?, .TERM) catch {}; + var buf: [1 << 16]u8 = undefined; + var reader = child.stderr.?.readerStreaming(job.io, &buf); + try shard.eachLine(&reader.interface, Lines{ .job = job }); + const term = try child.wait(job.io); + children.forget(job.slot); + job.term = term; + if (term == .exited) job.exit_code = term.exited; + } +}; + +fn run(init: std.process.Init, opt: shard.Options, jobs: u32, gpus: u32) !u8 { + const a = init.arena.allocator(); + const exe = try std.process.executablePathAlloc(init.io, a); + const me = try std.fmt.allocPrint(a, "{d}", .{children.selfPid()}); + var all: [shard.max_jobs]Job = undefined; + for (all[0..jobs], 0..) |*job, k| { + var argv: std.ArrayList([]const u8) = .empty; + try argv.appendSlice(a, &.{ exe, "kernel-contract", "--shard", try std.fmt.allocPrint(a, "{d}/{d}", .{ k, jobs }), "--device", try std.fmt.allocPrint(a, "{d}", .{k % gpus}), "--parent", me }); + try argv.appendSlice(a, opt.words); + job.* = .{ .io = init.io, .slot = k, .jobs = jobs, .argv = argv.items }; + } + children.forwardSignals(); + var threads: [shard.max_jobs]?std.Thread = @splat(null); + for (all[0..jobs], threads[0..jobs]) |*job, *thread| thread.* = std.Thread.spawn(.{}, Job.watch, .{job}) catch |err| { + job.failure = err; + _ = children.stopAll(job.slot, .TERM); + continue; + }; + std.debug.print("kernel-contract: {d} shards over {d} GPUs\n", .{ jobs, gpus }); + for (threads[0..jobs]) |t| if (t) |thread| thread.join(); + var reports: [shard.max_jobs]shard.Report = undefined; + var unfinished: usize = 0; + for (all[0..jobs], 0..) |job, k| { + if (job.finished()) { + reports[k] = job.report.?; + continue; + } + unfinished += 1; + if (job.failure) |err| { + std.debug.print("FAIL kernel-contract: shard {d}/{d}: {t}\n", .{ k, jobs, err }); + } else if (children.wasStopped(k) and job.term != null and job.term.? == .signal) { + std.debug.print("kernel-contract: shard {d}/{d} was stopped: {f}\n", .{ k, jobs, job.term.? }); + } else if (job.term) |term| { + std.debug.print("FAIL kernel-contract: shard {d}/{d} did not finish: {f}, {s} its TALLY line\n", .{ k, jobs, term, if (job.report == null) "without" else "with" }); + } + } + if (unfinished > 0) { + std.debug.print("FAIL kernel-contract: {d} of {d} shards did not finish, so there is no merged SUMMARY\n", .{ unfinished, jobs }); + return 1; + } + const sum = shard.merge(reports[0..jobs], opt.words.len > 0) catch |err| { + std.debug.print("FAIL kernel-contract: the shards do not add up: {t}\n", .{err}); + return 1; + }; + if (shard.printsGradientPass(.parent, after.filtered(opt.words))) std.debug.print("{s}", .{@import("contract_back_suites.zig").passed}); + std.debug.print("{f}\n", .{sum}); + if (sum.problems() == 0) return 0; + std.debug.print("FAIL kernel-contract: {d} gate failures, {d} controls missed, {d} limit problems\n", .{ sum.tally.failed, sum.tally.missed, sum.limits }); + return 1; +} diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index ef3df27bc7c..93663765a4b 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const core = @import("core"); const options = @import("contract_options"); const check = @import("check.zig"); +const shard = @import("contract_shard.zig"); const contract = core.contract; const limits = contract.limits; @@ -57,13 +58,14 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { return error.UnknownContractImage; } -/// Gate 5 on this GPU, each record against the loaded function; plain words in `only` pick launches, `-word`s keep all. -pub fn live(gpu: check.Gpu, only: []const []const u8) !usize { +/// Gate 5 on this GPU, each record of `sh`'s share against its loaded function; plain words pick, `-word`s keep all. +pub fn live(gpu: check.Gpu, only: []const []const u8, sh: shard.Shard, coverage: *shard.Coverage) !usize { const after = @import("contract_after.zig"); const full = !after.filtered(only); var n: usize = 0; - if (full) n = try registry.checkCuda(gpu.gpa, ®istry.all_cuda, false); - if (full) std.debug.print("{s} limits: {d} registered CUDA launches against sm_80/86/89/120/121, {d} problems\n", .{ if (n == 0) "PASS" else "FAIL", registry.all_cuda.len, n }); + const audits = full and sh.index == 0; + if (audits) n = try registry.checkCuda(gpu.gpa, ®istry.all_cuda, false); + if (audits) std.debug.print("{s} limits: {d} registered CUDA launches against sm_80/86/89/120/121, {d} problems\n", .{ if (n == 0) "PASS" else "FAIL", registry.all_cuda.len, n }); const sm: u32 = @intCast(try gpu.ctx.capability()); const t = limits.target(sm) orelse { std.debug.print("N/A limits live: sm_{d} is not a target the records cover\n", .{sm}); @@ -76,15 +78,18 @@ pub fn live(gpu: check.Gpu, only: []const []const u8) !usize { .{ "most shared bytes a block (opt-in)", .max_shared_memory_per_block_optin, t.smem_optin }, .{ "threads a block", .max_threads_per_block, t.threads }, }; - for (dev) |d| { + if (sh.index == 0) for (dev) |d| { const got: u32 = @intCast(try gpu.ctx.attribute(d[1])); if (got != d[2]) n += 1; std.debug.print("{s} limits live sm_{d} {s}: the driver says {d}, the table {d}\n", .{ if (got == d[2]) "PASS" else "FAIL", sm, d[0], got, d[2] }); - } + }; var said: ?limits.Nvcc = null; for (registry.all_cuda ++ registry.cuda_controls) |r| { const control = std.mem.startsWith(u8, r.launch.name, "control"); if (!full and !after.wanted(r.launch.name, only)) continue; + coverage.of += 1; + if (!sh.owns(coverage.of - 1)) continue; + coverage.ran += 1; if (!control and t.sm < r.launch.min_sm) continue; if (!control and at != null and registry.targetDecision(r, t, r.usage[at.?]) != .applicable) continue; const bytes = image(r.launch.image) catch |err| { diff --git a/zig/tests/cuda/contract_shard.zig b/zig/tests/cuda/contract_shard.zig new file mode 100644 index 00000000000..720dc86ee17 --- /dev/null +++ b/zig/tests/cuda/contract_shard.zig @@ -0,0 +1,436 @@ +//! kernel-contract's opt-in sharded run: its options, a shard's share, the tally a shard reports and their merge. +const std = @import("std"); +const gates = @import("core").contract.gates; + +/// Most child processes `--jobs` starts. +pub const max_jobs: u32 = 16; +/// Memory one process is planned for (the host's by whether words filter the run); `--jobs` refuses what won't fit. +pub const host_mib_full: u64 = 28 * 1024; +pub const host_mib_filtered: u64 = 8 * 1024; +pub const device_mib_per_process: u64 = 7 * 1024; + +/// One slice of a run: the items whose index modulo `count` is `index`. +pub const Shard = struct { + index: u32 = 0, + count: u32 = 1, + + pub fn owns(s: Shard, i: usize) bool { + return i % s.count == s.index; + } + + /// `K/N` with K < N, N > 0, both plain decimal digits. + pub fn parse(text: []const u8) error{InvalidShard}!Shard { + const slash = std.mem.indexOfScalar(u8, text, '/') orelse return error.InvalidShard; + const index = number(u32, text[0..slash]) orelse return error.InvalidShard; + const count = number(u32, text[slash + 1 ..]) orelse return error.InvalidShard; + if (count == 0 or index >= count) return error.InvalidShard; + return .{ .index = index, .count = count }; + } +}; + +fn number(comptime T: type, text: []const u8) ?T { + if (text.len == 0) return null; + for (text) |c| if (c < '0' or c > '9') return null; + return std.fmt.parseUnsigned(T, text, 10) catch null; +} + +/// Whether this target has the processes `--jobs` and `--parent` use: POSIX, where a pid is an integer (not Windows). +pub const posix_processes = @typeInfo(std.posix.pid_t) == .int; + +pub const Options = struct { + /// Name filter: the kernels, controls and launches whose name holds one of these. + words: []const []const u8, + shard: ?Shard = null, + /// Child processes to run (`--jobs`); null runs in this process. + jobs: ?u32 = null, + /// The visible GPU a shard runs on (`--device`). + device: u8 = 0, + /// The `--jobs` process that started this shard (`--parent`). + parent: ?u31 = null, + + pub fn effectiveShard(o: Options) Shard { + return o.shard orelse .{}; + } + + /// The option that starts or follows a child process (`--jobs`, `--parent`); null when this process runs alone. + pub fn processOption(o: Options) ?[]const u8 { + if (o.jobs != null) return "--jobs"; + if (o.parent != null) return "--parent"; + return null; + } + + pub fn deinit(o: Options, a: std.mem.Allocator) void { + a.free(o.words); + } +}; + +pub const ParseError = error{ InvalidShard, InvalidJobs, InvalidDevice, DuplicateOption, ShardWithJobs, DeviceWithoutShard, ParentWithoutShard, InvalidParent, UnknownOption, MissingValue } || std.mem.Allocator.Error; + +/// The option and value a refused command line names. +pub const Culprit = struct { + option: []const u8 = "", + value: []const u8 = "", + + pub fn format(c: Culprit, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.writeAll(c.option); + if (c.value.len > 0) try w.print(" {s}", .{c.value}); + } +}; + +/// What the refused option needs, for the line that names it. +pub fn hint(err: ParseError) []const u8 { + return switch (err) { + error.InvalidShard => "K/N with K below N", + error.InvalidJobs => std.fmt.comptimePrint("1 to {d}", .{max_jobs}), + error.InvalidDevice => "a GPU number, 0 to 255", + error.DuplicateOption => "at most once", + error.ShardWithJobs => "--jobs makes the shards", + error.DeviceWithoutShard => "--device goes with --shard", + error.InvalidParent => "a process id", + error.ParentWithoutShard => "--parent goes with --shard", + error.UnknownOption => "options are --jobs, --shard, --device, --parent and --help", + error.MissingValue => "the option needs a value", + error.OutOfMemory => "out of memory", + }; +} + +/// `kernel-contract`'s arguments: name words and, each once at most, `--jobs`, `--shard`, `--device` and `--parent`. +pub fn parse(a: std.mem.Allocator, args: []const [:0]const u8) ParseError!Options { + var culprit: Culprit = .{}; + return parseNamed(a, args, &culprit); +} + +/// `parse`, naming in `culprit` the option and value it refuses. +pub fn parseNamed(a: std.mem.Allocator, args: []const [:0]const u8, culprit: *Culprit) ParseError!Options { + var words: std.ArrayList([]const u8) = .empty; + errdefer words.deinit(a); + var o: Options = .{ .words = &.{} }; + var device_text: ?[]const u8 = null; + var parent_text: ?[]const u8 = null; + var i: usize = 0; + while (i < args.len) : (i += 1) { + const arg: []const u8 = args[i]; + if (!std.mem.startsWith(u8, arg, "--")) { + try words.append(a, arg); + continue; + } + culprit.* = .{ .option = arg }; + const is_jobs = std.mem.eql(u8, arg, "--jobs"); + const is_shard = std.mem.eql(u8, arg, "--shard"); + const is_device = std.mem.eql(u8, arg, "--device"); + const is_parent = std.mem.eql(u8, arg, "--parent"); + if (!is_jobs and !is_shard and !is_device and !is_parent) return error.UnknownOption; + i += 1; + if (i == args.len) return error.MissingValue; + culprit.value = args[i]; + if (is_jobs) { + if (o.jobs != null) return error.DuplicateOption; + const n = number(u32, args[i]) orelse return error.InvalidJobs; + if (n == 0 or n > max_jobs) return error.InvalidJobs; + o.jobs = n; + } else if (is_shard) { + if (o.shard != null) return error.DuplicateOption; + o.shard = try Shard.parse(args[i]); + } else if (is_parent) { + if (parent_text != null) return error.DuplicateOption; + o.parent = number(u31, args[i]) orelse return error.InvalidParent; + parent_text = args[i]; + } else { + if (device_text != null) return error.DuplicateOption; + o.device = number(u8, args[i]) orelse return error.InvalidDevice; + device_text = args[i]; + } + } + if (o.jobs != null and o.shard != null) { + culprit.* = .{ .option = "--shard", .value = "with --jobs" }; + return error.ShardWithJobs; + } + if (device_text) |text| if (o.shard == null) { + culprit.* = .{ .option = "--device", .value = text }; + return error.DeviceWithoutShard; + }; + if (parent_text) |text| if (o.shard == null) { + culprit.* = .{ .option = "--parent", .value = text }; + return error.ParentWithoutShard; + }; + o.words = try words.toOwnedSlice(a); + return o; +} + +/// Whether `only` names any positive word; empty or `-word`-only runs all standalone suites. +pub fn hasPositive(only: []const []const u8) bool { + for (only) |w| if (!std.mem.startsWith(u8, w, "-")) return true; + return false; +} + +/// Whether `name` holds no `-word` and, when positive words are given, at least one of them. +pub fn wanted(name: []const u8, only: []const []const u8) bool { + var named = !hasPositive(only); + for (only) |w| { + const minus = std.mem.startsWith(u8, w, "-"); + const hit = std.mem.indexOf(u8, name, if (minus) w[1..] else w) != null; + if (minus and hit) return false; + named = named or hit; + } + return named; +} + +/// Keeps the items named by `only`'s words (empty: all), then `sh`'s share of those; returns how many the words kept. +pub fn keep(comptime T: type, items: *std.ArrayList(T), only: []const []const u8, sh: Shard) usize { + var kept: usize = 0; + for (items.items) |item| { + if (!wanted(item.spec.name, only)) continue; + items.items[kept] = item; + kept += 1; + } + var mine: usize = 0; + for (items.items[0..kept], 0..) |item, i| { + if (!sh.owns(i)) continue; + items.items[mine] = item; + mine += 1; + } + items.shrinkRetainingCapacity(mine); + return kept; +} + +/// How many of a list's items a shard ran and how many the list holds. +pub const Coverage = struct { ran: u64 = 0, of: u64 = 0 }; + +/// What one shard did: the tally of its kernels and controls, its limit problems and what it ran of each list. +pub const Report = struct { + shard: Shard, + /// Kernels and controls named by the words, before sharding. + listed: u64, + tally: gates.Tally, + limits: u64, + suites: Coverage, + records: Coverage, + gates_ms: u64, + limits_ms: u64, + + pub fn problems(r: Report) u64 { + return r.tally.problems() + r.limits; + } + + const names = [_][]const u8{ "listed", "kernels", "passed", "failed", "known", "controls", "caught", "missed", "limits", "suites", "of_suites", "records", "of_records", "gates_ms", "limits_ms" }; + + fn values(r: Report) [names.len]u64 { + const t = r.tally; + return .{ r.listed, t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, r.limits, r.suites.ran, r.suites.of, r.records.ran, r.records.of, r.gates_ms, r.limits_ms }; + } + + /// The machine-readable line a shard prints and the parent parses; the human SUMMARY is never parsed. + pub fn format(r: Report, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.print("TALLY shard={d}/{d}", .{ r.shard.index, r.shard.count }); + inline for (names, r.values()) |name, v| try w.print(" {s}={d}", .{ name, v }); + } + + pub fn parseLine(line: []const u8) error{BadTally}!Report { + var it = std.mem.splitScalar(u8, line, ' '); + if (!std.mem.eql(u8, it.next().?, "TALLY")) return error.BadTally; + const head = it.next() orelse return error.BadTally; + if (!std.mem.startsWith(u8, head, "shard=")) return error.BadTally; + const shard = Shard.parse(head["shard=".len..]) catch return error.BadTally; + var v: [names.len]u64 = undefined; + inline for (names, &v) |name, *x| { + const field = it.next() orelse return error.BadTally; + if (!std.mem.startsWith(u8, field, name ++ "=")) return error.BadTally; + x.* = number(u64, field[name.len + 1 ..]) orelse return error.BadTally; + } + if (it.next() != null) return error.BadTally; + return .{ + .shard = shard, + .listed = v[0], + .tally = .{ .kernels = v[1], .passed = v[2], .failed = v[3], .known = v[4], .controls = v[5], .caught = v[6], .missed = v[7] }, + .limits = v[8], + .suites = .{ .ran = v[9], .of = v[10] }, + .records = .{ .ran = v[11], .of = v[12] }, + .gates_ms = v[13], + .limits_ms = v[14], + }; + } +}; + +/// The run's totals as its one SUMMARY line states them. +pub const Summary = struct { + filtered: bool, + tally: gates.Tally, + limits: u64, + gates_ms: u64, + limits_ms: u64, + + pub fn problems(s: Summary) u64 { + return s.tally.problems() + s.limits; + } + + pub fn format(s: Summary, w: *std.Io.Writer) std.Io.Writer.Error!void { + const t = s.tally; + try w.print("{s}SUMMARY {d} kernels: {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed; {d} limit problems; gates {d} ms, limits {d} ms", .{ + if (s.filtered) "(filtered) " else "", t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, s.limits, s.gates_ms, s.limits_ms, + }); + } +}; + +pub const MergeError = error{ NoShards, ShardCount, ShardRepeated, ShardMissing, ListDisagrees, KernelsNotOnce, SuitesNotOnce, RecordsNotOnce }; + +/// One summary from every shard's report: counts add, times are the slowest's, and each list must have run once. +pub fn merge(reports: []const Report, filtered: bool) MergeError!Summary { + if (reports.len == 0) return error.NoShards; + const first = reports[0]; + if (first.shard.count != reports.len) return error.ShardMissing; + var sum: Summary = .{ .filtered = filtered, .tally = .{}, .limits = 0, .gates_ms = 0, .limits_ms = 0 }; + var ran: u64 = 0; + var suites: u64 = 0; + var records: u64 = 0; + for (reports, 0..) |r, i| { + if (r.shard.count != first.shard.count) return error.ShardCount; + for (reports[0..i]) |before| if (before.shard.index == r.shard.index) return error.ShardRepeated; + if (r.listed != first.listed or r.suites.of != first.suites.of or r.records.of != first.records.of) return error.ListDisagrees; + sum.tally.kernels += r.tally.kernels; + sum.tally.passed += r.tally.passed; + sum.tally.failed += r.tally.failed; + sum.tally.known += r.tally.known; + sum.tally.controls += r.tally.controls; + sum.tally.caught += r.tally.caught; + sum.tally.missed += r.tally.missed; + sum.limits += r.limits; + sum.gates_ms = @max(sum.gates_ms, r.gates_ms); + sum.limits_ms = @max(sum.limits_ms, r.limits_ms); + ran += r.tally.kernels + r.tally.controls; + suites += r.suites.ran; + records += r.records.ran; + } + if (ran != first.listed) return error.KernelsNotOnce; + if (suites != first.suites.of) return error.SuitesNotOnce; + if (records != first.records.of) return error.RecordsNotOnce; + return sum; +} + +/// A shard's outcome is accepted only with its TALLY line, and an exit of 0 or an exit of 1 that its problems explain. +pub fn accepted(exit_code: ?u8, report: ?Report) bool { + const r = report orelse return false; + const code = exit_code orelse return false; + return code == 0 or (code == 1 and r.problems() > 0); +} + +pub const Refusal = error{ NoGpu, DeviceMemory, HostMemory }; + +/// The machine `--jobs` would run on: its GPUs, the smallest's total memory, the host's available memory. +pub const Machine = struct { + gpus: u32, + gpu_mib: u64, + host_mib: u64, + /// A GPU shares the host's memory, so a process's host and GPU plans draw on the same pool. + integrated: bool = false, +}; + +/// Whether `jobs` processes of a full or `filtered` run fit `m`: `ceil(jobs / gpus)` on a GPU, all on the host. +pub fn afford(jobs: u32, filtered: bool, m: Machine) Refusal!void { + if (m.gpus == 0) return error.NoGpu; + const host = if (filtered) host_mib_filtered else host_mib_full; + if (m.integrated) { + if (jobs * (host + device_mib_per_process) > m.host_mib) return error.HostMemory; + return; + } + const per_gpu = (jobs + m.gpus - 1) / m.gpus; + if (per_gpu * device_mib_per_process > m.gpu_mib) return error.DeviceMemory; + if (jobs * host > m.host_mib) return error.HostMemory; +} + +/// What a registration reads of a GPU to choose its kernels' configurations. +pub const Gpu = struct { + sm: u32, + multiprocessors: u32, + name: [96]u8 = @splat(0), + + pub fn named(sm: u32, multiprocessors: u32, name: []const u8) Gpu { + var g: Gpu = .{ .sm = sm, .multiprocessors = multiprocessors }; + @memcpy(g.name[0..@min(name.len, g.name.len - 1)], name[0..@min(name.len, g.name.len - 1)]); + return g; + } + + pub fn nameText(g: *const Gpu) []const u8 { + return std.mem.sliceTo(&g.name, 0); + } +}; + +pub const Field = enum { compute_capability, multiprocessors, name }; + +pub const Mix = struct { gpu: usize, field: Field }; + +/// The first GPU that differs from GPU 0 in compute capability, multiprocessor count or name, and in which. +pub fn firstMixed(gpus: []const Gpu) ?Mix { + for (gpus[@min(1, gpus.len)..], 1..) |g, i| { + if (g.sm != gpus[0].sm) return .{ .gpu = i, .field = .compute_capability }; + if (g.multiprocessors != gpus[0].multiprocessors) return .{ .gpu = i, .field = .multiprocessors }; + if (!std.mem.eql(u8, g.nameText(), gpus[0].nameText())) return .{ .gpu = i, .field = .name }; + } + return null; +} + +/// The pair `firstMixed` found, each GPU with the value that differs. +pub fn writeMix(w: *std.Io.Writer, gpus: []const Gpu, m: Mix) std.Io.Writer.Error!void { + const first = &gpus[0]; + const other = &gpus[m.gpu]; + switch (m.field) { + .compute_capability => try w.print("GPU 0 is sm_{d} and GPU {d} is sm_{d}", .{ first.sm, m.gpu, other.sm }), + .multiprocessors => try w.print("GPU 0 has {d} multiprocessors and GPU {d} has {d}", .{ first.multiprocessors, m.gpu, other.multiprocessors }), + .name => try w.print("GPU 0 is a {s} and GPU {d} is a {s}", .{ first.nameText(), m.gpu, other.nameText() }), + } +} + +/// Who prints the gradient suites' PASS line: the serial run or the `--jobs` parent, never a shard; not when filtered. +pub const Role = enum { serial, parent, shard }; + +pub fn printsGradientPass(role: Role, filtered: bool) bool { + return !filtered and role != .shard; +} + +/// Hands `sink.line(text, cut)` each line of `r`; one longer than the buffer comes cut, the lines after it whole. +pub fn eachLine(r: *std.Io.Reader, sink: anytype) !void { + while (true) { + const line = r.takeDelimiter('\n') catch |err| switch (err) { + error.StreamTooLong => { + try sink.line(r.buffered(), true); + r.tossBuffered(); + _ = r.discardDelimiterInclusive('\n') catch |e| switch (e) { + error.EndOfStream => return, + else => return e, + }; + continue; + }, + else => |e| return e, + } orelse return; + try sink.line(line, false); + } +} + +/// `/proc/meminfo`'s MemAvailable in MiB. +pub fn memAvailableMib(meminfo: []const u8) ?u64 { + var lines = std.mem.tokenizeScalar(u8, meminfo, '\n'); + while (lines.next()) |line| { + const key = "MemAvailable:"; + if (!std.mem.startsWith(u8, line, key)) continue; + var words = std.mem.tokenizeScalar(u8, line[key.len..], ' '); + const kib = number(u64, words.next() orelse return null) orelse return null; + if (!std.mem.eql(u8, words.next() orelse return null, "kB")) return null; + return kib / 1024; + } + return null; +} + +pub const help = std.fmt.comptimePrint( + \\usage: tf-cuda-test kernel-contract [WORD...] [--jobs N | --shard K/N [--device D]] + \\ (no option) the full serial run in this process + \\ WORD... only the kernels, controls and launches whose name holds a WORD (no suites, no offline audit) + \\ -WORD... every kernel and control but those whose name holds WORD; the suites, audit and launches all run + \\ --jobs N opt-in: N child processes (1 to {d}), one shard each, GPUs round-robin, one merged SUMMARY; + \\ a process is planned for {d} GiB of host memory ({d} GiB with WORDs) and {d} GiB of GPU memory; + \\ refused where N processes do not fit the host's available memory (Linux: /proc/meminfo) or the GPU's + \\ total memory, or where the GPUs differ in compute capability + \\ --shard K/N opt-in: share K of N of the kernels, suites and launches, then a TALLY line in place of a SUMMARY + \\ --device D the visible GPU a --shard process runs on + \\ --parent PID the --jobs process that started a --shard process; the shard stops with it + \\Words and --jobs or --shard compose: the words filter first, then the shard slices what is left. + \\ +, .{ max_jobs, host_mib_full / 1024, host_mib_filtered / 1024, device_mib_per_process / 1024 }); diff --git a/zig/tests/cuda/contract_shard_host.zig b/zig/tests/cuda/contract_shard_host.zig new file mode 100644 index 00000000000..6526b25a5fa --- /dev/null +++ b/zig/tests/cuda/contract_shard_host.zig @@ -0,0 +1,421 @@ +//! kernel-contract's sharded run without a GPU: the partition, the options, the tally line and the merge. +const std = @import("std"); +const t = std.testing; +const shard = @import("contract_shard.zig"); +const gates = @import("core").contract.gates; + +fn args(comptime words: []const [:0]const u8) []const [:0]const u8 { + return words; +} + +test "shard partition: every index belongs to exactly one shard, in shares within one of each other" { + for (1..70) |count| for ([_]usize{ 0, 1, 2, 7, 63, 64, 65, 1000, 4096 }) |n| { + var owned: [70]usize = @splat(0); + for (0..n) |i| { + var owners: usize = 0; + for (0..count) |k| { + const s: shard.Shard = .{ .index = @intCast(k), .count = @intCast(count) }; + if (s.owns(i)) { + owners += 1; + owned[k] += 1; + } + } + try t.expectEqual(@as(usize, 1), owners); + } + for (owned[0..count]) |share| try t.expect(share == n / count or share == n / count + 1); + }; +} + +const Named = struct { spec: struct { name: []const u8 } }; + +fn tally(list: []const Named) gates.Tally { + var sum: gates.Tally = .{}; + for (list) |k| { + if (std.mem.startsWith(u8, k.spec.name, "control")) { + sum.controls += 1; + sum.caught += 1; + } else { + sum.kernels += 1; + if (k.spec.name.len % 7 == 0) sum.failed += 1 else sum.passed += 1; + } + } + return sum; +} + +test "shard keep: the words filter first, the shards run each named kernel and control once, and their tallies add up" { + var names: [200][]const u8 = undefined; + var buf: [200][16]u8 = undefined; + for (&names, &buf, 0..) |*name, *b, i| name.* = std.fmt.bufPrint(b, "{s} {d}", .{ if (i % 5 == 0) "control" else if (i % 3 == 0) "lane" else "norm", i }) catch unreachable; + for ([_][]const []const u8{ &.{}, &.{"lane"}, &.{ "lane", "control" }, &.{"absent"} }) |words| { + var serial: std.ArrayList(Named) = .empty; + defer serial.deinit(t.allocator); + for (names) |name| try serial.append(t.allocator, .{ .spec = .{ .name = name } }); + const listed = shard.keep(Named, &serial, words, .{}); + try t.expectEqual(serial.items.len, listed); + for ([_]u32{ 1, 2, 3, 4 }) |count| { + var reports: [4]shard.Report = undefined; + var seen: usize = 0; + for (0..count) |k| { + var mine: std.ArrayList(Named) = .empty; + defer mine.deinit(t.allocator); + for (names) |name| try mine.append(t.allocator, .{ .spec = .{ .name = name } }); + const kept = shard.keep(Named, &mine, words, .{ .index = @intCast(k), .count = count }); + try t.expectEqual(listed, kept); + if (words.len > 0) for (mine.items) |item| { + var named = false; + for (words) |w| named = named or std.mem.indexOf(u8, item.spec.name, w) != null; + try t.expect(named); + }; + seen += mine.items.len; + reports[k] = .{ .shard = .{ .index = @intCast(k), .count = count }, .listed = kept, .tally = tally(mine.items), .limits = 0, .suites = .{}, .records = .{}, .gates_ms = 1, .limits_ms = 1 }; + } + try t.expectEqual(listed, seen); + const merged = try shard.merge(reports[0..count], words.len > 0); + const want = tally(serial.items); + try t.expectEqual(want, merged.tally); + } + } +} + +test "shard options: words, flags and their refusals by name" { + const a = t.allocator; + const ok = try shard.parse(a, args(&.{ "lane", "--shard", "1/4", "--device", "1", "norm" })); + defer ok.deinit(a); + try t.expectEqual(@as(usize, 2), ok.words.len); + try t.expectEqualStrings("norm", ok.words[1]); + try t.expectEqual(shard.Shard{ .index = 1, .count = 4 }, ok.shard.?); + try t.expectEqual(@as(u8, 1), ok.device); + const child = try shard.parse(a, args(&.{ "--shard", "0/2", "--parent", "4242" })); + defer child.deinit(a); + try t.expectEqual(@as(?u31, 4242), child.parent); + const jobs = try shard.parse(a, args(&.{ "--jobs", "16" })); + defer jobs.deinit(a); + try t.expectEqual(@as(?u32, 16), jobs.jobs); + try t.expect(jobs.shard == null); + const bad = [_]struct { []const [:0]const u8, anyerror }{ + .{ args(&.{ "--shard", "4/4" }), error.InvalidShard }, + .{ args(&.{ "--shard", "0/0" }), error.InvalidShard }, + .{ args(&.{ "--shard", "1" }), error.InvalidShard }, + .{ args(&.{ "--shard", "-1/2" }), error.InvalidShard }, + .{ args(&.{ "--shard", "1/+2" }), error.InvalidShard }, + .{ args(&.{ "--shard", "a/b" }), error.InvalidShard }, + .{ args(&.{ "--jobs", "0" }), error.InvalidJobs }, + .{ args(&.{ "--jobs", "17" }), error.InvalidJobs }, + .{ args(&.{ "--jobs", "two" }), error.InvalidJobs }, + .{ args(&.{ "--jobs", "1_0" }), error.InvalidJobs }, + .{ args(&.{ "--shard", "0/2", "--device", "x" }), error.InvalidDevice }, + .{ args(&.{ "--shard", "0/2", "--device", "256" }), error.InvalidDevice }, + .{ args(&.{ "--parent", "4242" }), error.ParentWithoutShard }, + .{ args(&.{ "--jobs", "2", "--parent", "4242" }), error.ParentWithoutShard }, + .{ args(&.{ "--shard", "0/2", "--parent", "-1" }), error.InvalidParent }, + .{ args(&.{ "--shard", "0/2", "--parent", "4242", "--parent", "4243" }), error.DuplicateOption }, + .{ args(&.{ "--device", "1" }), error.DeviceWithoutShard }, + .{ args(&.{ "--jobs", "2", "--device", "0" }), error.DeviceWithoutShard }, + .{ args(&.{ "--shard", "0/2", "--device", "0", "--device", "1" }), error.DuplicateOption }, + .{ args(&.{ "--jobs", "2", "--shard", "0/2" }), error.ShardWithJobs }, + .{ args(&.{ "--jobs", "2", "--jobs", "2" }), error.DuplicateOption }, + .{ args(&.{ "--shard", "0/2", "--shard", "1/2" }), error.DuplicateOption }, + .{ args(&.{"--jobs"}), error.MissingValue }, + .{ args(&.{"--parallel"}), error.UnknownOption }, + }; + for (bad) |case| try t.expectError(case[1], shard.parse(a, case[0])); +} + +test "shard options: --jobs and --parent name the child processes a target without POSIX refuses; --shard runs alone" { + const a = t.allocator; + const cases = [_]struct { []const [:0]const u8, ?[]const u8 }{ + .{ args(&.{ "--jobs", "2" }), "--jobs" }, + .{ args(&.{ "--shard", "0/2", "--parent", "4242" }), "--parent" }, + .{ args(&.{ "--shard", "1/2", "--device", "1" }), null }, + .{ args(&.{"lane"}), null }, + }; + for (cases) |case| { + const o = try shard.parse(a, case[0]); + defer o.deinit(a); + if (case[1]) |name| try t.expectEqualStrings(name, o.processOption().?) else try t.expect(o.processOption() == null); + } + try t.expectEqual(@import("builtin").os.tag != .windows, shard.posix_processes); +} + +test "shard options: a refusal names the option and value, and what it needs" { + const a = t.allocator; + const cases = [_]struct { []const [:0]const u8, anyerror, []const u8, []const u8 }{ + .{ args(&.{ "norm", "--jobs", "17" }), error.InvalidJobs, "--jobs 17", "1 to 16" }, + .{ args(&.{ "--shard", "3/3" }), error.InvalidShard, "--shard 3/3", "K/N with K below N" }, + .{ args(&.{ "--parallel", "2" }), error.UnknownOption, "--parallel", "options are --jobs, --shard, --device, --parent and --help" }, + .{ args(&.{ "--device", "1" }), error.DeviceWithoutShard, "--device 1", "--device goes with --shard" }, + .{ args(&.{ "--jobs", "2", "--shard", "0/2" }), error.ShardWithJobs, "--shard with --jobs", "--jobs makes the shards" }, + .{ args(&.{"--shard"}), error.MissingValue, "--shard", "the option needs a value" }, + .{ args(&.{ "--parent", "7" }), error.ParentWithoutShard, "--parent 7", "--parent goes with --shard" }, + }; + for (cases) |case| { + var culprit: shard.Culprit = .{}; + try t.expectError(case[1], shard.parseNamed(a, case[0], &culprit)); + var buf: [128]u8 = undefined; + try t.expectEqualStrings(case[2], try std.fmt.bufPrint(&buf, "{f}", .{culprit})); + try t.expectEqualStrings(case[3], shard.hint(@as(shard.ParseError, @errorCast(case[1])))); + } +} + +const sample: shard.Report = .{ + .shard = .{ .index = 2, .count = 4 }, + .listed = 1000, + .tally = .{ .kernels = 300, .passed = 280, .failed = 10, .known = 10, .controls = 100, .caught = 90, .missed = 10 }, + .limits = 4, + .suites = .{ .ran = 3, .of = 12 }, + .records = .{ .ran = 200, .of = 1000 }, + .gates_ms = 1_000_000, + .limits_ms = 200_000, +}; + +test "shard tally line: formats and parses back to the same report, and refuses other lines" { + var buf: [512]u8 = undefined; + const line = try std.fmt.bufPrint(&buf, "{f}", .{sample}); + try t.expectEqualStrings("TALLY shard=2/4 listed=1000 kernels=300 passed=280 failed=10 known=10 controls=100 caught=90 missed=10 limits=4 suites=3 of_suites=12 records=200 of_records=1000 gates_ms=1000000 limits_ms=200000", line); + try t.expectEqual(sample, try shard.Report.parseLine(line)); + var damaged: [512]u8 = undefined; + var extended: [512]u8 = undefined; + const bad = [_][]const u8{ + "", + "SUMMARY 1 kernels", + "TALLY", + "TALLY shard=2/4", + "TALLY shard=4/4 listed=1", + try std.fmt.bufPrint(&damaged, "{s}x", .{line[0 .. line.len - 1]}), + try std.fmt.bufPrint(&extended, "{s} extra=1", .{line}), + "TALLY shard=2/4 kernels=300 listed=1000", + }; + for (bad) |text| try t.expectError(error.BadTally, shard.Report.parseLine(text)); +} + +fn part(index: u32, count: u32, listed: u64, kernels: usize, controls: usize) shard.Report { + var r = sample; + r.shard = .{ .index = index, .count = count }; + r.listed = listed; + r.tally = .{ .kernels = kernels, .passed = kernels, .controls = controls, .caught = controls }; + r.limits = 0; + r.suites = .{ .ran = 1, .of = 2 }; + r.records = .{ .ran = 5, .of = 10 }; + return r; +} + +test "shard merge: counts add, times are the slowest shard's, and a list not run exactly once is refused" { + const merged = try shard.merge(&.{ part(0, 2, 10, 3, 2), part(1, 2, 10, 4, 1) }, false); + try t.expectEqual(@as(usize, 7), merged.tally.kernels); + try t.expectEqual(@as(usize, 7), merged.tally.passed); + try t.expectEqual(@as(usize, 3), merged.tally.controls); + try t.expectEqual(@as(u64, 1_000_000), merged.gates_ms); + try t.expectEqual(@as(u64, 0), merged.problems()); + var buf: [256]u8 = undefined; + try t.expectEqualStrings( + "SUMMARY 7 kernels: 7 pass gates 1-4, 0 fail, 0 known findings; 3 controls: 3 red as planted, 0 missed; 0 limit problems; gates 1000000 ms, limits 200000 ms", + try std.fmt.bufPrint(&buf, "{f}", .{merged}), + ); + try t.expectError(error.NoShards, shard.merge(&.{}, false)); + try t.expectError(error.ShardMissing, shard.merge(&.{part(0, 2, 10, 5, 5)}, false)); + try t.expectError(error.ShardRepeated, shard.merge(&.{ part(0, 2, 10, 5, 0), part(0, 2, 10, 5, 0) }, false)); + try t.expectError(error.ShardCount, shard.merge(&.{ part(0, 2, 10, 5, 0), part(1, 3, 10, 5, 0) }, false)); + try t.expectError(error.ListDisagrees, shard.merge(&.{ part(0, 2, 10, 5, 0), part(1, 2, 11, 5, 0) }, false)); + try t.expectError(error.KernelsNotOnce, shard.merge(&.{ part(0, 2, 10, 5, 0), part(1, 2, 10, 4, 0) }, false)); + var twice = part(1, 2, 10, 5, 0); + twice.suites.ran = 2; + try t.expectError(error.SuitesNotOnce, shard.merge(&.{ part(0, 2, 10, 5, 0), twice }, false)); + var records = part(1, 2, 10, 5, 0); + records.records.ran = 4; + try t.expectError(error.RecordsNotOnce, shard.merge(&.{ part(0, 2, 10, 5, 0), records }, false)); +} + +test "shard merge: a failed gate or a missed control in any shard fails the run" { + var failing = part(1, 2, 10, 5, 0); + failing.tally.failed = 1; + failing.tally.passed = 4; + try t.expectEqual(@as(u64, 1), (try shard.merge(&.{ part(0, 2, 10, 5, 0), failing }, false)).problems()); + var missed = part(1, 2, 10, 5, 0); + missed.tally.missed = 1; + try t.expectEqual(@as(u64, 1), (try shard.merge(&.{ part(0, 2, 10, 5, 0), missed }, false)).problems()); + var limit = part(1, 2, 10, 5, 0); + limit.limits = 2; + try t.expectEqual(@as(u64, 2), (try shard.merge(&.{ part(0, 2, 10, 5, 0), limit }, false)).problems()); +} + +test "shard accepted: a crash, a missing tally or an unexplained exit fails the shard" { + const clean = part(0, 2, 10, 5, 0); + var failing = clean; + failing.tally.failed = 1; + try t.expect(shard.accepted(0, clean)); + try t.expect(shard.accepted(1, failing)); + try t.expect(!shard.accepted(1, clean)); + try t.expect(!shard.accepted(0, null)); + try t.expect(!shard.accepted(1, null)); + try t.expect(!shard.accepted(null, clean)); + try t.expect(!shard.accepted(137, failing)); +} + +const gib: u64 = 1024; + +fn machine(gpus: u32, gpu_gib: u64, host_gib: u64, integrated: bool) shard.Machine { + return .{ .gpus = gpus, .gpu_mib = gpu_gib * gib, .host_mib = host_gib * gib, .integrated = integrated }; +} + +test "shard afford: a GPU or the host that cannot hold the processes refuses them" { + try shard.afford(4, false, machine(2, 16, 200, false)); + try shard.afford(2, false, machine(1, 16, 200, false)); + try shard.afford(1, false, machine(1, 8, 40, false)); + try t.expectError(error.DeviceMemory, shard.afford(3, false, machine(1, 16, 200, false))); + try t.expectError(error.DeviceMemory, shard.afford(1, false, machine(1, 4, 200, false))); + try t.expectError(error.HostMemory, shard.afford(4, false, machine(2, 16, 100, false))); + try t.expectError(error.NoGpu, shard.afford(1, false, machine(0, 16, 200, false))); +} + +test "shard afford: a filtered run plans less host memory, and processes per GPU round up" { + try shard.afford(16, true, machine(2, 56, 128, false)); + try t.expectError(error.HostMemory, shard.afford(16, true, machine(2, 56, 127, false))); + try t.expectError(error.HostMemory, shard.afford(5, false, machine(5, 16, 100, false))); + try shard.afford(4, true, machine(4, 16, 100, false)); + try t.expectError(error.DeviceMemory, shard.afford(16, true, machine(2, 48, 200, false))); + try t.expectError(error.DeviceMemory, shard.afford(5, true, machine(2, 20, 200, false))); + try shard.afford(5, true, machine(2, 21, 200, false)); +} + +test "shard afford: an integrated GPU draws on the host's memory, so both plans add and no GPU total is checked" { + // 4 full processes plan 4 x (28 + 7) GiB of the one pool; the GPU's own total is not a limit + try shard.afford(4, false, machine(1, 1, 140, true)); + try t.expectError(error.HostMemory, shard.afford(4, false, machine(1, 1, 139, true))); + try shard.afford(8, true, machine(1, 1, 120, true)); + try t.expectError(error.HostMemory, shard.afford(8, true, machine(1, 1, 119, true))); + // 3 full processes plan 3 x 35 = 105 GiB: 114 GiB admits them and refuses a 4th, 104 GiB refuses them + try shard.afford(3, false, machine(1, 1, 114, true)); + try t.expectError(error.HostMemory, shard.afford(4, false, machine(1, 1, 114, true))); + try shard.afford(3, false, machine(1, 1, 105, true)); + try t.expectError(error.HostMemory, shard.afford(3, false, machine(1, 1, 104, true))); + try t.expectError(error.NoGpu, shard.afford(1, true, machine(0, 1, 120, true))); +} + +fn gpuList(comptime specs: []const struct { u32, u32, []const u8 }) [specs.len]shard.Gpu { + var out: [specs.len]shard.Gpu = undefined; + for (specs, &out) |spec, *g| g.* = .named(spec[0], spec[1], spec[2]); + return out; +} + +fn mixText(list: []const shard.Gpu) ![]const u8 { + const mix = shard.firstMixed(list) orelse return "same"; + var buf: [200]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try shard.writeMix(&w, list, mix); + return t.allocator.dupe(u8, w.buffered()); +} + +test "shard mixed GPUs: the first that differs from GPU 0 in capability, multiprocessors or name, with both values" { + try t.expectEqual(@as(?shard.Mix, null), shard.firstMixed(&.{})); + const same = gpuList(&.{ .{ 120, 36, "RTX 5060 Ti" }, .{ 120, 36, "RTX 5060 Ti" } }); + try t.expectEqual(@as(?shard.Mix, null), shard.firstMixed(&same)); + const sm = gpuList(&.{ .{ 120, 36, "A" }, .{ 120, 36, "A" }, .{ 121, 36, "A" } }); + const sm_text = try mixText(&sm); + defer t.allocator.free(sm_text); + try t.expectEqualStrings("GPU 0 is sm_120 and GPU 2 is sm_121", sm_text); + const count = gpuList(&.{ .{ 120, 36, "A" }, .{ 120, 70, "A" } }); + try t.expectEqual(shard.Mix{ .gpu = 1, .field = .multiprocessors }, shard.firstMixed(&count).?); + const count_text = try mixText(&count); + defer t.allocator.free(count_text); + try t.expectEqualStrings("GPU 0 has 36 multiprocessors and GPU 1 has 70", count_text); + const name = gpuList(&.{ .{ 120, 36, "RTX 5060 Ti" }, .{ 120, 36, "RTX 5070" } }); + try t.expectEqual(shard.Mix{ .gpu = 1, .field = .name }, shard.firstMixed(&name).?); + const name_text = try mixText(&name); + defer t.allocator.free(name_text); + try t.expectEqualStrings("GPU 0 is a RTX 5060 Ti and GPU 1 is a RTX 5070", name_text); +} + +test "shard meminfo: MemAvailable in MiB, and nothing from other text" { + const text = "MemTotal: 263640884 kB\nMemFree: 1048576 kB\nMemAvailable: 209715200 kB\nBuffers: 1 kB\n"; + try t.expectEqual(@as(?u64, 204800), shard.memAvailableMib(text)); + try t.expectEqual(@as(?u64, null), shard.memAvailableMib("MemTotal: 1 kB\n")); + try t.expectEqual(@as(?u64, null), shard.memAvailableMib("MemAvailable: lots kB\n")); + try t.expectEqual(@as(?u64, null), shard.memAvailableMib("MemAvailable: 5 MB\n")); +} + +test "shard help: states the cap, both host plans, the GPU plan and every option" { + for ([_][]const u8{ "1 to 16", "28 GiB", "8 GiB with WORDs", "7 GiB", "--jobs N", "--shard K/N", "--device D", "/proc/meminfo" }) |needle| + try t.expect(std.mem.indexOf(u8, shard.help, needle) != null); +} + +test "shard pass line: the process that prints the gradient PASS line is one, and none when filtered" { + const runs = [_][]const shard.Role{ &.{.serial}, &.{ .parent, .shard }, &.{ .parent, .shard, .shard, .shard } }; + for (runs) |roles| for ([_]bool{ false, true }) |filtered| { + var printers: usize = 0; + for (roles) |role| printers += @intFromBool(shard.printsGradientPass(role, filtered)); + try t.expectEqual(@as(usize, if (filtered) 0 else 1), printers); + }; +} + +const Collect = struct { + lines: *std.ArrayList([]u8), + cuts: *std.ArrayList(bool), + + pub fn line(c: Collect, text: []const u8, cut: bool) !void { + try c.lines.append(t.allocator, try t.allocator.dupe(u8, text)); + try c.cuts.append(t.allocator, cut); + } +}; + +test "shard lines: a line longer than the buffer is cut and the lines after it still arrive whole" { + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + const line = "TALLY shard=0/1 listed=1 kernels=1 passed=1"; + const long: [100]u8 = @splat('x'); + const mid: [60]u8 = @splat('y'); + const text = try std.fmt.allocPrint(t.allocator, "first\n{s}\n{s}\n{s}\nlast", .{ long, line, mid }); + defer t.allocator.free(text); + try tmp.dir.writeFile(t.io, .{ .sub_path = "log", .data = text }); + const file = try tmp.dir.openFile(t.io, "log", .{}); + defer file.close(t.io); + var buf: [48]u8 = undefined; + var reader = file.readerStreaming(t.io, &buf); + var lines: std.ArrayList([]u8) = .empty; + var cuts: std.ArrayList(bool) = .empty; + defer { + for (lines.items) |l| t.allocator.free(l); + lines.deinit(t.allocator); + cuts.deinit(t.allocator); + } + try shard.eachLine(&reader.interface, Collect{ .lines = &lines, .cuts = &cuts }); + try t.expectEqual(@as(usize, 5), lines.items.len); + try t.expectEqualStrings("first", lines.items[0]); + try t.expectEqual(@as(usize, 48), lines.items[1].len); + try t.expect(cuts.items[1]); + try t.expectEqualStrings(line, lines.items[2]); + try t.expect(!cuts.items[2]); + try t.expect(cuts.items[3]); + try t.expectEqual(@as(usize, 48), lines.items[3].len); + try t.expectEqualStrings("last", lines.items[4]); + try t.expect(!cuts.items[4]); +} + +test "shard filters: negative-only runs keep non-excluded items and keep the filtered summary marker" { + const names = [_][]const u8{ "lane a", "lane control", "norm b", "norm control" }; + try t.expect(!shard.hasPositive(&.{})); + try t.expect(!shard.hasPositive(&.{"-control"})); + try t.expect(shard.hasPositive(&.{ "-control", "lane" })); + try t.expect(shard.wanted("lane a", &.{"-control"})); + try t.expect(!shard.wanted("lane control", &.{"-control"})); + try t.expect(shard.wanted("lane a", &.{ "lane", "-control" })); + try t.expect(!shard.wanted("norm b", &.{ "lane", "-control" })); + + var list: std.ArrayList(Named) = .empty; + defer list.deinit(t.allocator); + for (names) |name| try list.append(t.allocator, .{ .spec = .{ .name = name } }); + const neg = [_][]const u8{"-control"}; + const kept = shard.keep(Named, &list, &neg, .{}); + try t.expectEqual(@as(usize, 2), kept); + try t.expectEqualStrings("lane a", list.items[0].spec.name); + try t.expectEqualStrings("norm b", list.items[1].spec.name); + + const reports = [_]shard.Report{ + .{ .shard = .{ .index = 0, .count = 2 }, .listed = 2, .tally = .{ .kernels = 1, .passed = 1 }, .limits = 0, .suites = .{ .ran = 4, .of = 7 }, .records = .{ .ran = 1, .of = 2 }, .gates_ms = 2, .limits_ms = 1 }, + .{ .shard = .{ .index = 1, .count = 2 }, .listed = 2, .tally = .{ .kernels = 1, .passed = 1 }, .limits = 0, .suites = .{ .ran = 3, .of = 7 }, .records = .{ .ran = 1, .of = 2 }, .gates_ms = 3, .limits_ms = 1 }, + }; + const sum = try shard.merge(&reports, neg.len > 0); + try t.expect(sum.filtered); + var buf: [256]u8 = undefined; + const text = try std.fmt.bufPrint(&buf, "{f}", .{sum}); + try t.expect(std.mem.startsWith(u8, text, "(filtered) SUMMARY 2 kernels:")); +} diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index db7988b3a03..eed4fc860c6 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -67,15 +67,18 @@ const images = struct { pub const controls align(16) = @embedFile("fatbin_contract_controls").*; }; -/// Gates 1-4 on every registered CUDA kernel and each control at its own gate, then gate 5; `only`: contract_after.zig. -pub fn run(gpu: check.Gpu, only: []const []const u8) !void { +/// Gates 1-4 on every registered CUDA kernel and each control at its own gate, then gate 5; `args`: contract_shard.zig. +pub fn run(gpu: check.Gpu, args: []const [:0]const u8) !void { + const opt = try @import("contract_shard.zig").parse(gpu.gpa, args); + defer opt.deinit(gpu.gpa); var t0: i96 = undefined; - const t = try registered(gpu, only, &t0); - try @import("contract_finish.zig").run(gpu, only, t, t0); + var listed: usize = undefined; + const t = try registered(gpu, opt, &t0, &listed); + try @import("contract_finish.zig").run(gpu, opt, t, listed, t0); } // The registered owners and modules end here, before the standalone suites allocate their working sets. -fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { +fn registered(gpu: check.Gpu, opt: @import("contract_shard.zig").Options, t0: *i96, listed: *usize) !g.Tally { const a = gpu.gpa; if (!kk.available) return error.BuiltWithoutKernels; if (!options.controls) { @@ -561,10 +564,5 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { // int4's gates are family registrations, so `kernel-contract int4` selects them; the skipped-slot check is not one const int4 = try @import("contract_int4_run.zig").Set.init(gpu, s, a, &kernels); defer int4.deinit(); - var t: g.Tally = .{}; - try @import("contract_dump.zig").run(a, kernels.items); - t0.* = check.now(gpu.io); - @import("contract_after.zig").keep(&kernels, only); - try g.runAll(a, kernels.items, 0x6b63, &t); - return t; + return @import("contract_after.zig").gates(gpu, &kernels, opt, t0, listed); } diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index f7070dda3e5..3e04868900f 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -125,7 +125,8 @@ pub fn main(init: std.process.Init) !u8 { } var driver = try cuda.Driver.open(); defer driver.close(); - var ctx = try cuda.Context.init(&driver, 0); + if (try @import("contract_jobs.zig").parent(init, &driver, args)) |code| return code; + var ctx = try cuda.Context.init(&driver, @import("contract_jobs.zig").device(init.gpa, args)); defer ctx.deinit(); const gpu: check.Gpu = .{ .d = &driver, .ctx = &ctx, .gpa = init.gpa, .io = init.io }; const cmd = args[1]; diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index b380e3106a9..36ead81743b 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -144,7 +144,7 @@ pub const usage = \\ qwen35-tp-cut PACK [STEP] the 27B's EXL3 weights cut for two ranks at the whole plan: each rank's columns, one run's bytes \\ exl3-prompt-k6 [DIR|none] [BASE] EXL3 prompt kernels at 3 and 4 bits, GLM's shapes: runSlots, FP64, row bytes, time; DIR adds a real layer, BASE (an earlier exl3_experts fatbin) its 4-bit bytes \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time - \\ kernel-contract [WORD...] the contract's gates, each planted control red (-Dnvcc); WORDs: kernels named so, -WORDs: all but those + \\ kernel-contract [WORD...] [--jobs N | --shard K/N [--device D]] the contract's gates, each planted control red (-Dnvcc); WORDs: kernels named so, -WORDs: all but those; --help \\ qmm-prefill-many-contract the GB10 bit-exact multi-projection prompt launch against separate launches \\ qmm-prefill-tile22-contract the GB10 large-prompt 2x2 tile against the default tile \\ qmmf-prompt BF16 K32 prompt staging: parent K64 bytes at current Flash Next shapes