Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Graph cache: a capture is freed until the map holds it, the keep floo…
…r stays under the max, a max of 0 is eager

- A capture whose agreement throws, or whose insert runs out of memory, no longer leaks its executable: the map's
  slot is reserved before the capture, and the executable is owned here until the insert, which cannot fail.
- A host map that cannot grow counts as no room in the existing room vote, so every rank declines that miss together.
- `min_keep` is clamped to `max`, so under the memory floor the cap never rises above the configured max. A max of 0
  runs every step eagerly, with no collective.
- A cap lowered to 0 under the floor goes back to max once every rank has room, instead of staying eager for good.
- Hits make no collective: with `Agree` set, keys, settings and fingerprint changes must already match on every rank.
  The docs now say so: the fingerprint changes at the same step on every rank, and `fingerprintOf` is for one rank.

Co-authored-by: Jonathan Regan-Beasley <197533392+jregan-beasley-smc@users.noreply.github.com>
  • Loading branch information
jayleaton committed Oct 15, 2026
commit 5826f89bd31ce0f4d875051b61dec78cfd764ae7
31 changes: 20 additions & 11 deletions zig/src/cuda/graph_cache.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub const Body = struct {
run: *const fn (ctx: *anyopaque, stream: Stream) anyerror!void,
};

/// Every rank's verdict AND-ed, so ranks capture, evict and fall back at the same steps; never called in a capture.
/// Every rank's verdict AND-ed on a miss (hits never call it), so ranks capture, evict and fall back together.
pub const Agree = struct {
ctx: *anyopaque,
all: *const fn (ctx: *anyopaque, ok: bool) anyerror!bool,
Expand Down Expand Up @@ -53,7 +53,9 @@ pub fn Cache(comptime Key: type) type {
stats: struct { replayed: u64 = 0, captured: u64 = 0, eager: u64 = 0, evicted: u64 = 0, dropped: u64 = 0, floor_hits: u64 = 0 } = .{},

pub fn init(gpa: std.mem.Allocator, engine: Engine, settings: Settings) Self {
return .{ .gpa = gpa, .engine = engine, .settings = settings, .cap = settings.max };
var s = settings;
s.min_keep = @min(s.min_keep, s.max); // the floor never holds more than the configured max
return .{ .gpa = gpa, .engine = engine, .settings = s, .cap = s.max };
}

pub fn deinit(c: *Self) void {
Expand Down Expand Up @@ -98,9 +100,9 @@ pub fn Cache(comptime Key: type) type {
return .eager;
}

/// One step: the key's graph launched, captured first on a miss; a new `fingerprint` drops every graph first.
/// One step: the key's graph, captured first on a miss; a new `fingerprint` (same step on all ranks) drops all.
pub fn run(c: *Self, key: Key, stream: Stream, fingerprint: u64, body: Body) !Outcome {
if (!c.settings.on or c.failed) return c.eager(stream, body);
if (!c.settings.on or c.failed or c.settings.max == 0) return c.eager(stream, body);
if (c.fingerprint != null and c.fingerprint.? != fingerprint) c.dropAll();
c.fingerprint = fingerprint;
c.tick += 1;
Expand All @@ -110,9 +112,10 @@ pub fn Cache(comptime Key: type) type {
c.stats.replayed += 1;
return .replayed;
}
// a miss: room on every rank, else shed the least recent quarter and lower the cap (once below it, eager)
const room_here = if (c.room) |f| f() else true;
if (!try c.agreed(room_here and c.cap > 0)) {
// a miss: room on every rank (a host map that cannot grow is none), else shed a quarter and lower the cap
const reserved = if (c.entries.ensureUnusedCapacity(c.gpa, 1)) |_| true else |_| false;
const room_here = reserved and (if (c.room) |f| f() else true);
if (!try c.agreed(room_here)) {
if (c.settings.hold) {
if (!quiet and c.stats.floor_hits == 0) std.log.warn("graph cache: under the memory floor on {s} rank: this key eager, {d} graphs held (hold)", .{ if (room_here) "another" else "this", c.entries.count() });
c.stats.floor_hits += 1;
Expand All @@ -123,7 +126,7 @@ pub fn Cache(comptime Key: type) type {
for (0..drop) |_| if (c.entries.count() > c.settings.min_keep) c.evictOldest();
}
const was = c.cap;
c.cap = @intCast(@max(c.entries.count(), c.settings.min_keep));
c.cap = @intCast(@max(c.entries.count(), c.settings.min_keep)); // min_keep <= max (init)
c.stats.floor_hits += 1;
if (!quiet and c.cap != was) std.log.warn("graph cache: under the memory floor on {s} rank: cap {d} -> {d} ({d} held, {d} evicted, {d} eager so far)", .{ if (room_here) "another" else "this", was, c.cap, c.entries.count(), c.stats.evicted, c.stats.eager + 1 });
return c.eager(stream, body);
Expand All @@ -138,13 +141,15 @@ pub fn Cache(comptime Key: type) type {
if (!quiet) std.log.warn("graph capture failed: {s} (key {any}, {d} graphs held)", .{ @errorName(err), key, c.entries.count() });
break :blk null;
};
var owned = exec; // freed here until the map holds it, so a failed agreement cannot leak it
defer if (owned) |x| c.engine.free(c.engine.ctx, x);
if (!try c.agreed(exec != null)) {
if (exec) |x| c.engine.free(c.engine.ctx, x);
c.failed = true;
c.dropAll();
return c.eager(stream, body);
}
try c.entries.put(c.gpa, key, .{ .exec = exec.?, .used = c.tick });
c.entries.putAssumeCapacityNoClobber(key, .{ .exec = exec.?, .used = c.tick });
owned = null;
try c.engine.launch(c.engine.ctx, exec.?, stream);
c.stats.captured += 1;
return .captured;
Expand Down Expand Up @@ -196,7 +201,7 @@ pub const CudaEngine = struct {
}
};

/// FNV-1a over the addresses a body captures (buffer bases, sizes): the fingerprint `run` compares.
/// FNV-1a over the addresses a body captures (buffer bases, sizes): the fingerprint `run` compares, on one rank only.
pub fn fingerprintOf(words: []const u64) u64 {
var h: u64 = 0xcbf29ce484222325;
for (words) |w| {
Expand Down Expand Up @@ -390,3 +395,7 @@ test "graph cache: off runs every step eagerly" {
test "graph cache: fingerprint" {
try std.testing.expect(fingerprintOf(&.{ 1, 2 }) != fingerprintOf(&.{ 2, 1 }));
}

test {
_ = @import("graph_cache_regression_test.zig");
}
181 changes: 181 additions & 0 deletions zig/src/cuda/graph_cache_regression_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//! Failure ownership, rank verdict counts and bounded-cap regressions for the graph cache.

const std = @import("std");
const cache = @import("graph_cache.zig");
const Stream = @import("stream.zig").Stream;
const no_stream: Stream = .{ .d = undefined, .handle = null };
const expect = std.testing.expect;
const equal = std.testing.expectEqual;

const Engine = struct {
captures: usize = 0,
live: usize = 0,
launches: usize = 0,
bodies: usize = 0,
handles: [32]u8 = undefined,

fn engine(e: *Engine) cache.Engine {
return .{ .ctx = e, .capture = capture, .launch = launch, .free = free };
}
fn capture(p: *anyopaque, _: Stream, _: cache.Body) !*anyopaque {
const e: *Engine = @ptrCast(@alignCast(p));
e.captures += 1;
e.live += 1;
return &e.handles[e.captures % e.handles.len];
}
fn launch(p: *anyopaque, _: *anyopaque, _: Stream) !void {
const e: *Engine = @ptrCast(@alignCast(p));
e.launches += 1;
}
fn free(p: *anyopaque, _: *anyopaque) void {
const e: *Engine = @ptrCast(@alignCast(p));
std.debug.assert(e.live > 0);
e.live -= 1;
}
fn body(e: *Engine) cache.Body {
return .{ .ctx = e, .run = run };
}
fn run(p: *anyopaque, _: Stream) !void {
const e: *Engine = @ptrCast(@alignCast(p));
e.bodies += 1;
}
};

const Peer = struct {
verdicts: []const bool,
at: usize = 0,
throw_at: ?usize = null,
fn agree(p: *Peer) cache.Agree {
return .{ .ctx = p, .all = all };
}
fn all(ctx: *anyopaque, ok: bool) !bool {
const p: *Peer = @ptrCast(@alignCast(ctx));
const at = p.at;
p.at += 1;
if (p.throw_at == at) return error.CollectiveFailed;
if (at >= p.verdicts.len) return error.UnexpectedCollective;
return ok and p.verdicts[at];
}
};

test "graph cache regression: capture agreement throw frees the not-yet-inserted executable" {
var e: Engine = .{};
// per miss: room, then the capture's verdict
var p: Peer = .{ .verdicts = &.{ true, true }, .throw_at = 1 };
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{});
defer c.deinit();
c.agree = p.agree();
try std.testing.expectError(error.CollectiveFailed, c.run(1, no_stream, 7, e.body()));
try equal(@as(usize, 1), e.captures);
try equal(@as(usize, 0), e.live);
try equal(@as(usize, 0), c.count());
try equal(@as(usize, 2), p.at);
}

test "graph cache regression: local map OOM declines before any capture and can recover" {
var e: Engine = .{};
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
var c = cache.Cache(u32).init(failing.allocator(), e.engine(), .{});
defer c.deinit();
try equal(cache.Outcome.eager, try c.run(1, no_stream, 7, e.body()));
try expect(failing.has_induced_failure);
try equal(@as(usize, 0), e.captures);
try equal(@as(usize, 0), e.live);
try expect(!c.failed);
failing.fail_index = std.math.maxInt(usize);
try equal(cache.Outcome.captured, try c.run(1, no_stream, 7, e.body()));
try equal(@as(usize, 1), e.live);
}

test "graph cache regression: peer map OOM makes a locally prepared rank eager before capture" {
var e: Engine = .{};
var p: Peer = .{ .verdicts = &.{false} };
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{});
defer c.deinit();
c.agree = p.agree();
try equal(cache.Outcome.eager, try c.run(1, no_stream, 7, e.body()));
try equal(@as(usize, 1), p.at);
try equal(@as(usize, 0), e.captures);
try equal(@as(usize, 1), e.bodies);
}

test "graph cache regression: local OOM still contributes the room verdict" {
var e: Engine = .{};
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
var p: Peer = .{ .verdicts = &.{true} };
var c = cache.Cache(u32).init(failing.allocator(), e.engine(), .{});
defer c.deinit();
c.agree = p.agree();
try equal(cache.Outcome.eager, try c.run(1, no_stream, 7, e.body()));
try equal(@as(usize, 1), p.at);
try equal(@as(usize, 0), e.captures);
}

test "graph cache regression: hits make no collective; a fingerprint change shared by every rank recaptures" {
var e: Engine = .{};
var p: Peer = .{ .verdicts = &.{ true, true, true, true, true, true } };
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{});
defer c.deinit();
c.agree = p.agree();
_ = try c.run(1, no_stream, 7, e.body());
_ = try c.run(2, no_stream, 7, e.body());
try equal(@as(usize, 4), p.at);
for (0..4) |_| try equal(cache.Outcome.replayed, try c.run(1, no_stream, 7, e.body()));
try equal(@as(usize, 4), p.at);
// a new layout generation on every rank: both graphs go, the next miss agrees twice as any other
try equal(cache.Outcome.captured, try c.run(1, no_stream, 8, e.body()));
try equal(@as(usize, 6), p.at);
try equal(@as(u64, 2), c.stats.dropped);
try equal(@as(usize, 1), c.count());
try equal(@as(usize, 1), e.live);
}

var room = true;
fn available() bool {
return room;
}

test "graph cache regression: zero maximum remains eager across pressure recovery, with no collective" {
var e: Engine = .{};
var p: Peer = .{ .verdicts = &.{} };
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{ .max = 0 });
defer c.deinit();
c.room = available;
c.agree = p.agree();
for ([_]bool{ false, true, false, true }) |ok| {
room = ok;
try equal(cache.Outcome.eager, try c.run(1, no_stream, 7, e.body()));
try equal(@as(u32, 0), c.cap);
try equal(@as(usize, 0), c.count());
}
try equal(@as(usize, 0), e.captures);
try equal(@as(usize, 0), p.at);
}

test "graph cache regression: default floor cannot enlarge a two-entry maximum" {
var e: Engine = .{};
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{ .max = 2 });
defer c.deinit();
c.room = available;
try equal(@as(u32, 2), c.settings.min_keep);
room = false;
_ = try c.run(1, no_stream, 7, e.body());
room = true;
for (0..8) |key| {
_ = try c.run(@intCast(key), no_stream, 7, e.body());
try expect(c.count() <= 2 and c.cap <= 2 and e.live <= 2);
}
}

test "graph cache regression: zero keep floor recovers after reducing the cap to zero" {
var e: Engine = .{};
var c = cache.Cache(u32).init(std.testing.allocator, e.engine(), .{ .max = 2, .min_keep = 0 });
defer c.deinit();
c.room = available;
room = false;
try equal(cache.Outcome.eager, try c.run(1, no_stream, 7, e.body()));
try equal(@as(u32, 0), c.cap);
room = true;
try equal(cache.Outcome.captured, try c.run(1, no_stream, 7, e.body()));
try equal(@as(u32, 2), c.cap);
}