diff --git a/build.zig b/build.zig index 58ef8764a7e..5884badfe66 100644 --- a/build.zig +++ b/build.zig @@ -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); diff --git a/zig/build/gemma4_host.zig b/zig/build/gemma4_host.zig index 6cabe7496a7..e07432321f7 100644 --- a/zig/build/gemma4_host.zig +++ b/zig/build/gemma4_host.zig @@ -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); @@ -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); diff --git a/zig/gemma4_head_test.zig b/zig/gemma4_head_test.zig index 5e16c5716ee..754789a2c9a 100644 --- a/zig/gemma4_head_test.zig +++ b/zig/gemma4_head_test.zig @@ -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"); diff --git a/zig/gemma4_owners_test.zig b/zig/gemma4_owners_test.zig index 3583bb96ee1..e31f04c07c4 100644 --- a/zig/gemma4_owners_test.zig +++ b/zig/gemma4_owners_test.zig @@ -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" { diff --git a/zig/gemma4_shared_affine_test.zig b/zig/gemma4_shared_affine_test.zig index a2d4e96e35f..6a5d2324cfd 100644 --- a/zig/gemma4_shared_affine_test.zig +++ b/zig/gemma4_shared_affine_test.zig @@ -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"); diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index 635365c47d4..e078155b08c 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -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); } @@ -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, @@ -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; @@ -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; @@ -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; } diff --git a/zig/src/families/gemma4/weights.zig b/zig/src/families/gemma4/weights.zig index 0854ea0171a..ee525ac7183 100644 --- a/zig/src/families/gemma4/weights.zig +++ b/zig/src/families/gemma4/weights.zig @@ -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. @@ -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). @@ -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; } @@ -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; @@ -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; diff --git a/zig/src/families/spark25/metal.zig b/zig/src/families/spark25/metal.zig index 033c7c19c2d..e5a9245db8f 100644 --- a/zig/src/families/spark25/metal.zig +++ b/zig/src/families/spark25/metal.zig @@ -14,4 +14,5 @@ test { _ = state; _ = budget; _ = snapshot; + _ = weights; } diff --git a/zig/src/families/spark25/metal_budget.zig b/zig/src/families/spark25/metal_budget.zig index 34ddfc053bf..7340c0c92b0 100644 --- a/zig/src/families/spark25/metal_budget.zig +++ b/zig/src/families/spark25/metal_budget.zig @@ -8,7 +8,7 @@ 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) { @@ -16,9 +16,17 @@ pub fn caches(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) erro 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; @@ -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)); +} diff --git a/zig/src/families/spark25/metal_model.zig b/zig/src/families/spark25/metal_model.zig index babe441c9bb..848093bfd06 100644 --- a/zig/src/families/spark25/metal_model.zig +++ b/zig/src/families/spark25/metal_model.zig @@ -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 }); diff --git a/zig/src/families/spark25/metal_weights.zig b/zig/src/families/spark25/metal_weights.zig index 4dd686479a7..69a35352287 100644 --- a/zig/src/families/spark25/metal_weights.zig +++ b/zig/src/families/spark25/metal_weights.zig @@ -51,6 +51,8 @@ pub const Weights = struct { layers: []Layer, /// The stacked matrices' own buffers (copies of the checkpoint's). stacked: std.ArrayList(mtl.Buffer) = .empty, + /// Their bytes, which the shards no longer hold: part of what a load keeps resident. + stacked_bytes: u64 = 0, pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { gpa.free(w.layers); @@ -80,12 +82,12 @@ fn norm(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8) !Tensor } /// An affine [n, k] matrix at the checkpoint's one width, groups of 64, through the core MLX affine reader. -fn affine(c: *const ck.Checkpoint, bits: u8, base: []const u8, n: usize, k: usize) !Linear { +fn affine(c: anytype, bits: u8, base: []const u8, n: usize, k: usize) !Linear { return .{ .affine = try rows.affine(try mlx_affine.read(c, base, .{ .n = n, .k = k, .bits = bits, .group = cfg.group })) }; } /// The release's bf16 [n, k] matrix in place: k whole 256s for the GEMM's steps, 16-byte aligned for the row kernel. -fn dense(c: *const ck.Checkpoint, base: []const u8, n: usize, k: usize) !Linear { +fn dense(c: anytype, base: []const u8, n: usize, k: usize) !Linear { var b2: [256]u8 = undefined; const w = try c.get(try name(&b2, base, ".weight")); try require(w, .bf16, &.{ n, k }); @@ -94,7 +96,7 @@ fn dense(c: *const ck.Checkpoint, base: []const u8, n: usize, k: usize) !Linear } /// `base`'s matrix in the checkpoint's format. -fn linear(c: *const ck.Checkpoint, bits: u8, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Linear { +fn linear(c: anytype, bits: u8, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Linear { var buf: [256]u8 = undefined; const base = try name(&buf, prefix, suffix); return if (bits == cfg.bf16) dense(c, base, n, k) else affine(c, bits, base, n, k); @@ -121,6 +123,7 @@ fn stacked(gpa: std.mem.Allocator, device: mtl.Device, w: *Weights, parts: []con row += d.n; } try w.stacked.append(gpa, buf); + w.stacked_bytes += n * k * 2; return .{ .bf16 = .{ .buf = buf, .off = 0, .n = n, .k = k } }; }, .affine => |first| { @@ -142,6 +145,7 @@ fn stacked(gpa: std.mem.Allocator, device: mtl.Device, w: *Weights, parts: []con row += a.n; } try w.stacked.append(gpa, buf); + w.stacked_bytes += b_at + total * groups * 2; const out = rows.Weights{ .w = buf, .w_off = 0, .scales = buf, .s_off = s_at, .biases = buf, .b_off = b_at, .n = total, .k = k, .group = first.group, .bits = first.bits }; try out.validate(); return .{ .affine = out }; @@ -149,6 +153,22 @@ fn stacked(gpa: std.mem.Allocator, device: mtl.Device, w: *Weights, parts: []con } } +/// The stacked members, left in their files at load: the stacks below read them once, through a Stage. +pub const later = ck.laterModules(&.{ ".q_k_v_proj", ".g_proj", ".gate_proj", ".up_proj" }); + +/// Room in `stage` for the modules `suffixes` under `prefix`: a bf16 weight, or an affine weight, scales and biases. +fn reserve(stage: *ck.Stage, c: *const ck.Checkpoint, bits: u8, prefix: []const u8, suffixes: []const []const u8) !void { + var bufs: [4][3][256]u8 = undefined; + var names: [12][]const u8 = undefined; + var n: usize = 0; + for (suffixes, 0..) |sfx, i| for ([_][]const u8{ ".weight", ".scales", ".biases" }, 0..) |leaf, j| { + if (j > 0 and bits == cfg.bf16) continue; + names[n] = try std.fmt.bufPrint(&bufs[i][j], "{s}{s}{s}", .{ prefix, sfx, leaf }); + n += 1; + }; + try stage.reserve(c, names[0..n]); +} + pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ck.Checkpoint, f: *const cfg.Config) !Weights { const h = geo.hidden; const b = f.bits; @@ -158,6 +178,9 @@ pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ck.Checkpoint, .layers = try gpa.alloc(Layer, geo.layers), }; errdefer w.deinit(gpa); + var stage = ck.Stage{ .device = device }; + defer stage.deinit(); + const sc: ck.Staged = .{ .c = c, .stage = &stage }; for (w.layers, 0..) |*l, i| { var pb: [64]u8 = undefined; const p = try std.fmt.bufPrint(&pb, "model.layers.{d}.", .{i}); @@ -165,17 +188,28 @@ pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ck.Checkpoint, const a = try name(&ab, p, "self_attn"); var mb: [96]u8 = undefined; const m = try name(&mb, p, "mlp"); - const qkv = try linear(c, b, a, ".q_k_v_proj", geo.queryWidth() + 2 * geo.kvWidth(), h); - const gates = try linear(c, b, a, ".g_proj", geo.query_heads, h); + try reserve(&stage, c, b, a, &.{ ".q_k_v_proj", ".g_proj" }); + const qkv = try linear(sc, b, a, ".q_k_v_proj", geo.queryWidth() + 2 * geo.kvWidth(), h); + const gates = try linear(sc, b, a, ".g_proj", geo.query_heads, h); + const qkvg = try stacked(gpa, device, &w, &.{ qkv, gates }, st.qkvg_rows); + stage.reset(); + try reserve(&stage, c, b, m, &.{ ".gate_proj", ".up_proj" }); + const gu = try stacked(gpa, device, &w, &.{ try linear(sc, b, m, ".gate_proj", geo.intermediate, h), try linear(sc, b, m, ".up_proj", geo.intermediate, h) }, 2 * geo.intermediate); + stage.reset(); l.* = .{ .input_norm = try norm(c, p, "input_layernorm.weight"), .post_norm = try norm(c, p, "post_attention_layernorm.weight"), - .attn = .{ .qkvg = try stacked(gpa, device, &w, &.{ qkv, gates }, st.qkvg_rows), .out = try linear(c, b, a, ".out_proj", h, geo.queryWidth()) }, - .mlp = .{ - .gu = try stacked(gpa, device, &w, &.{ try linear(c, b, m, ".gate_proj", geo.intermediate, h), try linear(c, b, m, ".up_proj", geo.intermediate, h) }, 2 * geo.intermediate), - .down = try linear(c, b, m, ".down_proj", h, geo.intermediate), - }, + .attn = .{ .qkvg = qkvg, .out = try linear(c, b, a, ".out_proj", h, geo.queryWidth()) }, + .mlp = .{ .gu = gu, .down = try linear(c, b, m, ".down_proj", h, geo.intermediate) }, }; } return w; } + +test "later: the stacked members stay in their files; out, down, the embedding and the norms stay in the shards" { + const p = "model.layers.7."; + for ([_][]const u8{ p ++ "self_attn.q_k_v_proj.weight", p ++ "self_attn.q_k_v_proj.scales", p ++ "self_attn.g_proj.biases", p ++ "mlp.gate_proj.weight", p ++ "mlp.up_proj.scales" }) |n| + try std.testing.expect(later(n, 2)); + for ([_][]const u8{ p ++ "self_attn.out_proj.weight", p ++ "mlp.down_proj.weight", "model.embedding.weight", p ++ "input_layernorm.weight", "model.norm.weight" }) |n| + try std.testing.expect(!later(n, 2)); +} diff --git a/zig/src/native/spark25.zig b/zig/src/native/spark25.zig index 0d1e7cbae54..1ac154310da 100644 --- a/zig/src/native/spark25.zig +++ b/zig/src/native/spark25.zig @@ -51,9 +51,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope var len: usize = @sizeOf(u64); if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; const text: ?[]const u8 = if (std.c.getenv("SPARK_LOAD_LIMIT_GB")) |v| std.mem.span(v) else null; - // the decode window's and the prompt chunk's buffers - const scratch: u64 = fl.state.scratchBytes(fl.state.batch_rows) + fl.state.scratchBytes(fl.state.prompt_rows); - const budget = fl.budget.caches(ram, model.device.maxWorkingSet(), text, model.checkpoint.residentBytes() + scratch) catch { + const budget = fl.budget.caches(ram, model.device.maxWorkingSet(), text, fl.budget.resident(model)) catch { model.deinit(); problem.* = "SPARK_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM"; return null; @@ -65,7 +63,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer return null; } - std.log.info("spark2_5: {d:.1} GiB for caches, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); + const held: [3]f64 = .{ @floatFromInt(model.checkpoint.residentBytes()), @floatFromInt(model.weights.stacked_bytes), @floatFromInt(fl.budget.scratch) }; + std.log.info("spark2_5: resident {d:.3} GB (shards {d:.3}, stacks {d:.3}, scratch {d:.3}), {d:.1} GiB for caches, context up to {d} tokens", .{ (held[0] + held[1] + held[2]) / 1e9, held[0] / 1e9, held[1] / 1e9, held[2] / 1e9, @as(f64, @floatFromInt(budget)) / (1 << 30), window }); const h = try gpa.create(Host); errdefer gpa.destroy(h); h.gpa = gpa;