Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
28 changes: 28 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions zig/build/contract_shard_host.zig
Original file line number Diff line number Diff line change
@@ -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);
}
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
69 changes: 46 additions & 23 deletions zig/tests/cuda/contract_after.zig
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
}
}
39 changes: 28 additions & 11 deletions zig/tests/cuda/contract_back_suites.zig
Original file line number Diff line number Diff line change
@@ -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";
68 changes: 68 additions & 0 deletions zig/tests/cuda/contract_children.zig
Original file line number Diff line number Diff line change
@@ -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;
}
59 changes: 59 additions & 0 deletions zig/tests/cuda/contract_children_host.zig
Original file line number Diff line number Diff line change
@@ -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);
}
3 changes: 2 additions & 1 deletion zig/tests/cuda/contract_compile.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading