Skip to content
Open
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
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ pub fn build(b: *std.Build) void {
@import("zig/build/metal_prompt_sources.zig").steps(b, budget_mods.metal, budget_mods.engine, test_step);
@import("zig/build/fsr.zig").deviceSteps(b, budget_mods.metal, budget_mods.engine, budget_mods.sources);
b.step("test-shared-head-cost-metal-host", "Metal family head-cost grants without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = budget_mods.engine, .filters = &.{"shared head costs:"} })).step);
b.step("test-spark25-budget-metal-host", "Spark2.5's Metal load budget: shards, stacks and scratch against the limit, no device").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = budget_mods.engine, .filters = &.{"spark metal budget:"} })).step);
@import("zig/build/flashnext_budget.zig").compileHost(b, budget_mods.metal, budget_mods.engine, budget_mods.lanes);
@import("zig/build/residency_host.zig").compileHost(b, budget_mods.metal, budget_mods.engine, budget_mods.lanes);
@import("zig/build/dsv41_metal.zig").steps(b, budget_mods.metal, budget_mods.sources, test_step);
Expand Down
3 changes: 3 additions & 0 deletions zig/build/gemma4_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub fn tests(b: *std.Build, sources: *std.Build.Module) *std.Build.Step {
b.step("test-gemma4-load-parts-host", "Production late constructor with faulting GPU boundary").dependOn(&parts.step);
const owner_fake = b.createModule(.{ .root_source_file = b.path("zig/gemma4_inert_metal.zig"), .target = b.graph.host });
const owners = b.createModule(.{ .root_source_file = b.path("zig/gemma4_owners_test.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = owner_fake }, .{ .name = "kernel_sources", .module = sources } } });
owners.addImport("core", owners); // checkpoint_metal.zig reaches its shard file cache through `core`
const owner_run = b.addRunArtifact(b.addTest(.{ .root_module = owners }));
owner_run.has_side_effects = true;
b.step("test-gemma4-owners-host", "Actual Gemma ownership boundaries without a GPU").dependOn(&owner_run.step);
Expand All @@ -23,12 +24,14 @@ pub fn tests(b: *std.Build, sources: *std.Build.Module) *std.Build.Step {
b.step("test-gemma4-config", "Real Gemma parser fixtures without GPU dependencies").dependOn(&config_run.step);
const fake = b.createModule(.{ .root_source_file = b.path("zig/gemma4_recording_metal.zig"), .target = b.graph.host });
const root = b.createModule(.{ .root_source_file = b.path("zig/gemma4_shared_affine_test.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = fake }, .{ .name = "kernel_sources", .module = sources } } });
root.addImport("core", root); // checkpoint_metal.zig reaches its shard file cache through `core`
const filter = b.option([]const u8, "gemma4-host-filter", "One portable shared affine regression");
const run = b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = if (filter) |f| &.{f} else &.{} }));
run.has_side_effects = true;
b.step("test-gemma4-affine-host", "Record actual shared dispatch without devices or shader compilation").dependOn(&run.step);
const head_fake = b.createModule(.{ .root_source_file = b.path("zig/gemma4_head_metal.zig"), .target = b.graph.host });
const head_root = b.createModule(.{ .root_source_file = b.path("zig/gemma4_head_test.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = head_fake }, .{ .name = "kernel_sources", .module = sources } } });
head_root.addImport("core", head_root); // checkpoint_metal.zig reaches its shard file cache through `core`
const head_run = b.addRunArtifact(b.addTest(.{ .root_module = head_root }));
head_run.has_side_effects = true;
b.step("test-gemma4-prompt-head-host", "Last prompt-row and decode projection bindings against synthetic layer logits").dependOn(&head_run.step);
Expand Down
3 changes: 3 additions & 0 deletions zig/gemma4_head_test.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Production prompt/decode bindings, evaluated by a CPU oracle; this does not emulate Metal reduction precision.
const std = @import("std");
const mtl = @import("metal");
/// checkpoint_metal.zig's `core`: gemma4/weights.zig's `later` pulls that file's tests in.
pub const safetensors = @import("src/core/safetensors.zig");
pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig");
const weights = @import("src/families/gemma4/weights.zig");
const prompt = @import("src/families/gemma4/prompt.zig");
const cfg = @import("src/families/gemma4/config.zig");
Expand Down
3 changes: 3 additions & 0 deletions zig/gemma4_owners_test.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! The production packed loader's publication boundary with a recording allocator and inert Metal.
const std = @import("std");
const mtl = @import("metal");
/// checkpoint_metal.zig's `core`: gemma4/weights.zig's `later` pulls that file's tests in.
pub const safetensors = @import("src/core/safetensors.zig");
pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig");
const weights = @import("src/families/gemma4/weights.zig");
const cfg = @import("src/families/gemma4/config.zig");
test "packed pair second publication failure releases every buffer once" {
Expand Down
3 changes: 3 additions & 0 deletions zig/gemma4_shared_affine_test.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Actual shared encoders against independent release ABI and launch constants, with inert Metal recording.
const std = @import("std");
const mtl = @import("metal");
/// checkpoint_metal.zig's `core`: gemma4/weights.zig's `later` pulls that file's tests in.
pub const safetensors = @import("src/core/safetensors.zig");
pub const checkpoint_file_cache = @import("src/core/checkpoint_file_cache.zig");
const am = @import("src/core/affine_mm.zig");
const lane = @import("src/core/lane_projection.zig");
const ks = @import("kernel_sources");
Expand Down
41 changes: 41 additions & 0 deletions zig/src/core/checkpoint_metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,15 @@ pub const Checkpoint = struct {
};
}

/// A tensor's dtype, shape and size, kept in a shard or left in its file.
pub fn describe(self: *const Checkpoint, name: []const u8) !Deferred {
if (self.tensors.get(name)) |t| return .{ .file = 0, .at = 0, .bytes = t.bytes, .dtype = t.dtype, .shape = t.shape, .rank = t.rank };
return self.deferred.get(name) orelse {
std.log.err("checkpoint has no tensor {s}", .{name});
return error.MissingTensor;
};
}

pub fn has(self: *const Checkpoint, name: []const u8) bool {
return self.tensors.contains(name) or self.deferred.contains(name);
}
Expand Down Expand Up @@ -271,6 +280,30 @@ pub const Checkpoint = struct {
}
};

/// A `Later` for the layers' linears whose module name ends in one of `modules`: their weight, scales and biases.
pub fn laterModules(comptime modules: []const []const u8) Later {
return struct {
fn pick(name: []const u8, _: usize) bool {
const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;
const leaf = name[dot + 1 ..];
const linear = std.mem.eql(u8, leaf, "weight") or std.mem.eql(u8, leaf, "scales") or std.mem.eql(u8, leaf, "biases");
if (!linear or std.mem.indexOf(u8, name, ".layers.") == null) return false;
inline for (modules) |m| if (std.mem.endsWith(u8, name[0..dot], m)) return true;
return false;
}
}.pick;
}

/// A checkpoint read through a Stage (anything that takes `get(name)`): kept tensors in place, deferred ones staged.
pub const Staged = struct {
c: *const Checkpoint,
stage: *Stage,

pub fn get(s: Staged, name: []const u8) !Tensor {
return s.stage.read(s.c, name);
}
};

/// A repack's source: deferred tensors read into one reused shared buffer, each view valid until `reset`.
pub const Stage = struct {
device: mtl.Device,
Expand Down Expand Up @@ -372,6 +405,7 @@ fn fixture(gpa: std.mem.Allocator, tmp: *std.testing.TmpDir) ![:0]u8 {
}

test "full and selected checkpoint views retain data, ownership and relative offsets" {
if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; // a host Metal stand-in has no device
const device = mtl.Device.init() catch return error.SkipZigTest;
defer device.deinit();
const gpa = std.testing.allocator;
Expand Down Expand Up @@ -403,6 +437,7 @@ test "a split checkpoint keeps later tensors in the file, packs the rest, and st
const log_level = std.testing.log_level;
std.testing.log_level = .err;
defer std.testing.log_level = log_level;
if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; // a host Metal stand-in has no device
const device = mtl.Device.init() catch return error.SkipZigTest;
defer device.deinit();
const gpa = std.testing.allocator;
Expand Down Expand Up @@ -466,6 +501,12 @@ test "a span longer than one pread may ask for is read whole" {
try std.testing.expectError(error.ShortRead, readAll(fd, dest[0..2], len - 1));
}

test "laterModules picks the named layer linears' three tensors and nothing else" {
const later = laterModules(&.{ "_proj", ".mixer.in" });
for ([_][]const u8{ "model.layers.3.self_attn.q_proj.weight", "model.layers.0.mlp.down_proj.biases", "x.layers.1.mixer.in.scales" }) |n| try std.testing.expect(later(n, 2));
for ([_][]const u8{ "model.embed_tokens.weight", "model.layers.3.input_layernorm.weight", "model.layers.3.self_attn.q_proj", "lm_head.weight", "model.layers.2.mixer.in_norm.weight" }) |n| try std.testing.expect(!later(n, 2));
}

test {
_ = file_cache;
}
34 changes: 10 additions & 24 deletions zig/src/families/gemma4/weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -130,27 +130,13 @@ pub const Weights = struct {
}
};

/// Tensors left in their files at load (checkpoint_metal's `later`): the layers' linears, read once through a Stage.
pub fn later(name: []const u8, _: usize) bool {
const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false;
const leaf = name[dot + 1 ..];
const linear = std.mem.eql(u8, leaf, "weight") or std.mem.eql(u8, leaf, "scales") or std.mem.eql(u8, leaf, "biases");
return linear and std.mem.indexOf(u8, name, ".layers.") != null and std.mem.endsWith(u8, name[0..dot], "_proj");
}
/// Tensors left in their files at load: the layers' linears (any `*_proj`), read once through a Stage.
pub const later = ckpt.laterModules(&.{"_proj"});

/// The load's reader: kept tensors where they are, the linears staged from their files.
/// The load's reader: kept tensors where they are, the linears staged in host memory (not ckpt.Staged's buffer).
const Src = struct {
c: *const ckpt.Checkpoint,
stage: *Stage,

/// A tensor's dtype and shape, kept or in its file.
fn meta(r: Src, name: []const u8) !ckpt.Deferred {
if (r.c.tensors.get(name)) |t| return .{ .file = 0, .at = 0, .bytes = t.bytes, .dtype = t.dtype, .shape = t.shape, .rank = t.rank };
return r.c.deferred.get(name) orelse {
std.log.err("checkpoint has no tensor {s}", .{name});
return error.MissingTensor;
};
}
};

/// The linears' staging in host memory, not a Metal buffer: load makes its Metal buffers in main's order, no holes.
Expand Down Expand Up @@ -243,8 +229,8 @@ fn mlxCopy(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.Array
fn copyBytes(r: Src, prefix: []const u8, member: []const u8) !u64 {
var buf: [3][160]u8 = undefined;
const ns = try names3(&buf, prefix, member);
const sb_at = std.mem.alignForward(usize, (try r.meta(ns[0])).bytes, 256);
return sb_at + std.mem.alignForward(usize, (try r.meta(ns[1])).bytes, 256) + (try r.meta(ns[2])).bytes;
const sb_at = std.mem.alignForward(usize, (try r.c.describe(ns[0])).bytes, 256);
return sb_at + std.mem.alignForward(usize, (try r.c.describe(ns[1])).bytes, 256) + (try r.c.describe(ns[2])).bytes;
}

/// A member's rows of a row-path pack as core/affine_mm reads it: the same bytes, no copy (no tensor units).
Expand All @@ -265,7 +251,7 @@ fn mlxStack(r: Src, s: *const Stack, prefix: []const u8, members: []const []cons
run += 1;
row = 0;
}
const n = (try r.meta((try names3(&buf, prefix, m))[0])).shape[0];
const n = (try r.c.describe((try names3(&buf, prefix, m))[0])).shape[0];
o.* = mlxAlias(s.runs[run], row, n);
row += n;
}
Expand All @@ -275,9 +261,9 @@ fn mlxStack(r: Src, s: *const Stack, prefix: []const u8, members: []const []cons
fn storedK(r: Src, prefix: []const u8, member: []const u8, width: cfg.widths.Width) !usize {
var buf: [3][160]u8 = undefined;
const ns = try names3(&buf, prefix, member);
const w = try r.meta(ns[0]);
const s = try r.meta(ns[1]);
const b = try r.meta(ns[2]);
const w = try r.c.describe(ns[0]);
const s = try r.c.describe(ns[1]);
const b = try r.c.describe(ns[2]);
const ok = w.dtype == .u32 and w.rank == 2 and s.rank == 2 and b.rank == 2 and s.dtype == .bf16 and b.dtype == .bf16 and
s.shape[0] == w.shape[0] and b.shape[0] == w.shape[0] and s.shape[1] == b.shape[1] and
w.bytes == w.shape[0] * w.shape[1] * 4 and s.bytes == s.shape[0] * s.shape[1] * 2 and b.bytes == s.bytes;
Expand All @@ -302,7 +288,7 @@ fn pack(gpa: std.mem.Allocator, device: mtl.Device, r: Src, owned: *std.ArrayLis
for (members) |m| {
const mk = try storedK(r, prefix, m, width);
if (k != 0 and k != mk) return error.BadGemmaWeight;
n += (try r.meta((try names3(&buf, prefix, m))[0])).shape[0];
n += (try r.c.describe((try names3(&buf, prefix, m))[0])).shape[0];
k = mk;
}
const row_words = k * width.bits / 32;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/spark25/metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ test {
_ = state;
_ = budget;
_ = snapshot;
_ = weights;
}
35 changes: 33 additions & 2 deletions zig/src/families/spark25/metal_budget.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,25 @@ pub const default_share = 0.75;
pub const margin: u64 = 2 << 30;

/// Bytes for caches: `ram` times the share (or SPARK_LOAD_LIMIT_GB's GB, at most the GPU's working set), less the rest.
pub fn caches(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 {
pub fn caches(ram: u64, working_set: u64, text: ?[]const u8, kept: u64) error{BadLoadLimit}!u64 {
var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * default_share);
const t = std.mem.trim(u8, text orelse "", " \t");
if (t.len > 0) {
const gb = std.fmt.parseFloat(f64, t) catch return error.BadLoadLimit;
if (!std.math.isFinite(gb) or gb <= 0) return error.BadLoadLimit;
limit = @min(@as(u64, @intFromFloat(gb * 1e9)), @min(ram, working_set));
}
return if (limit > resident + margin) limit - resident - margin else 0;
return if (limit > kept + margin) limit - kept - margin else 0;
}

/// What a loaded `model` keeps resident besides caches: its shards, its stacked matrices and the windows' scratch.
pub fn resident(model: anytype) u64 {
return model.checkpoint.residentBytes() + model.weights.stacked_bytes + scratch;
}

/// The decode window's and the prompt chunk's buffers.
pub const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows);

/// The longest context one stream's caches fit in `bytes`, at most `most`.
pub fn longest(bytes: u64, most: usize) usize {
if (st.cacheBytes(1) > bytes) return 0;
Expand All @@ -39,3 +47,26 @@ test "spark metal budget: a share of RAM less the weights, a set limit capped at
try std.testing.expectError(error.BadLoadLimit, caches(256 * gib, 240 * gib, "lots", 6 * gib));
try std.testing.expectEqual(@as(usize, 4096), longest(st.cacheBytes(4096), 1 << 20));
}

test "spark metal budget: the stacked matrices count as resident, so a load limit they push over leaves no caches" {
const gib: u64 = 1 << 30;
const Fake = struct {
checkpoint: struct {
bytes: usize,
pub fn residentBytes(c: @This()) usize {
return c.bytes;
}
},
weights: struct { stacked_bytes: u64 },
};
const m: Fake = .{ .checkpoint = .{ .bytes = 1 * gib }, .weights = .{ .stacked_bytes = gib / 2 } };
try std.testing.expectEqual(@as(u64, 1 * gib + gib / 2 + scratch), resident(m));
const old = m.checkpoint.residentBytes() + scratch; // the accounting before: the shards and scratch only
try std.testing.expectEqual(try caches(32 * gib, 24 * gib, null, old) - gib / 2, try caches(32 * gib, 24 * gib, null, resident(m)));
// a limit with room for the shards, scratch and one token's caches, but not for the stacks as well
const room = old + margin + st.cacheBytes(1) + gib / 8;
const text = try std.fmt.allocPrint(std.testing.allocator, "{d}", .{@as(f64, @floatFromInt(room)) / 1e9});
defer std.testing.allocator.free(text);
try std.testing.expect(longest(try caches(32 * gib, 24 * gib, text, old), 1 << 20) > 0);
try std.testing.expectEqual(@as(usize, 0), longest(try caches(32 * gib, 24 * gib, text, resident(m)), 1 << 20));
}
4 changes: 3 additions & 1 deletion zig/src/families/spark25/metal_model.zig
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ pub const Model = struct {
errdefer m.checkpoint.deinit();
const files = try shards.shardFiles(gpa, io, dir);
defer shards.freeShardFiles(gpa, files);
for (files) |path| try m.checkpoint.addFile(m.device, path, "");
// the stacked members stay in their files, read once into the stacks: the shards keep what is read in place
for (files) |path| try m.checkpoint.addFileSplit(m.device, path, "", null, weights.later);
m.weights = try weights.load(gpa, m.device, &m.checkpoint, &m.config);
m.checkpoint.closeFiles();
errdefer m.weights.deinit(gpa);
{
const lib = try mtl.Library.fromSource(m.device, ks.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise });
Expand Down
Loading
Loading