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
6 changes: 6 additions & 0 deletions zig/src/families/glm/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ pub const Engine = struct {
std.log.err("glm: {d:.1} GB of weights and {d:.1} GB of caches pass this Mac's {d:.1} GB load limit ({s}); load a layer subset or the expert-parallel pair, or set GLM_LOAD_LIMIT_GB (past 70% of RAM a load risks a watchdog panic)", .{ @as(f64, @floatFromInt(plan_bytes)) / 1e9, @as(f64, @floatFromInt(e.arena.bytes)) / 1e9, @as(f64, @floatFromInt(limit)) / 1e9, e.limit.source() });
return error.OverMemoryLimit;
}
{ // the load needs the memory a cached copy of the checkpoint holds: the paced reads wait for free pages (#583)
const dropped_at = std.c.mach_absolute_time();
if (wts.dropCached(gpa, dir)) |cached| {
if (cached > 0) std.log.info("glm: dropped {d:.1} GiB of the checkpoint from the file cache before the load ({d:.2} s)", .{ @as(f64, @floatFromInt(cached)) / (1 << 30), @as(f64, @floatFromInt(std.c.mach_absolute_time() - dropped_at)) / 24e6 });
} else |err| std.log.warn("glm: could not drop the checkpoint's cached pages ({s}); the load reads beside them", .{@errorName(err)});
}
e.w = try wts.load(gpa, e.device, dir, &e.c, 16, false);
errdefer {
e.w.deinit();
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm/glm.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ test {
_ = @import("../../core/copy_index.zig");
_ = @import("attn_check.zig");
_ = @import("load_plan.zig");
_ = weights;
_ = mirror;
}
71 changes: 71 additions & 0 deletions zig/src/families/glm/weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,77 @@ fn runCopies(l: *Loader, threads: usize) !void {
if (tx.failed.load(.acquire)) return error.TransformFailed;
}

extern "c" fn msync(addr: *anyopaque, len: usize, flags: c_int) c_int;
extern "c" fn mincore(addr: *const anyopaque, len: usize, vec: [*]u8) c_int;
const MS_INVALIDATE = 2; // macOS sys/mman.h

/// Each shard's pages that an earlier download or read left in the file cache, dropped: the copies read with
/// F_NOCACHE, which keeps them out of the cache but evicts nothing already there, and macOS keeps clean file pages
/// while it compresses freshly filled buffers (#583). msync(MS_INVALIDATE) over a read-only shared mapping, no root.
/// The bytes that were cached.
pub fn dropCached(gpa: std.mem.Allocator, dir: []const u8) !u64 {
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const a = arena_state.allocator();
const index = try mtl.MappedFile.open(try std.fmt.allocPrintSentinel(a, "{s}/model.safetensors.index.json", .{dir}, 0));
defer index.deinit();
const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, index.bytes[0..index.size], .{ .allocate = .alloc_always });
var files: std.StringArrayHashMapUnmanaged(void) = .empty;
var it = doc.object.get("weight_map").?.object.iterator();
while (it.next()) |kv| try files.put(a, kv.value_ptr.string, {});
const page: usize = std.heap.pageSize();
var cached: u64 = 0;
for (files.keys()) |name| {
const fd = std.c.open(try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ dir, name }, 0), .{ .ACCMODE = .RDONLY });
if (fd < 0) return error.OpenFailed;
defer _ = std.c.close(fd);
const end = std.c.lseek(fd, 0, std.c.SEEK.END);
if (end <= 0) continue;
const len: usize = @intCast(end);
const map = std.c.mmap(null, len, .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0);
if (map == std.c.MAP_FAILED) return error.MapFailed;
defer _ = std.c.munmap(@alignCast(map), len);
const vec = try a.alloc(u8, (len + page - 1) / page);
if (mincore(map, len, vec.ptr) == 0) for (vec) |v| {
cached += @as(u64, v & 1) * page;
};
if (msync(map, len, MS_INVALIDATE) != 0) return error.InvalidateFailed;
}
return cached;
}

test "a checkpoint's cached pages are dropped, and counted once" {
const gpa = std.testing.allocator;
var name_buf: [64]u8 = undefined;
const dir = try std.fmt.bufPrintSentinel(&name_buf, "/tmp/tf-drop-cached-{d}", .{std.c.getpid()}, 0);
_ = std.c.mkdir(dir, 0o700);
defer _ = std.c.rmdir(dir);
var path_buf: [128]u8 = undefined;
const index = try std.fmt.bufPrintSentinel(&path_buf, "{s}/model.safetensors.index.json", .{dir}, 0);
const text = "{\"weight_map\": {\"a\": \"s.safetensors\", \"b\": \"s.safetensors\"}}";
var shard_buf: [128]u8 = undefined;
const shard = try std.fmt.bufPrintSentinel(&shard_buf, "{s}/s.safetensors", .{dir}, 0);
for ([_][:0]const u8{ index, shard }, [_][]const u8{ text, "" }) |file, body| {
const fd = std.c.open(file, .{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600));
try std.testing.expect(fd >= 0);
defer _ = std.c.close(fd);
if (body.len > 0) {
_ = std.c.write(fd, body.ptr, body.len);
continue;
}
const data = try gpa.alloc(u8, 4 << 20);
defer gpa.free(data);
@memset(data, 7);
try std.testing.expectEqual(@as(isize, @intCast(data.len)), std.c.write(fd, data.ptr, data.len));
_ = std.c.fsync(fd);
_ = std.c.pread(fd, data.ptr, data.len, 0); // read through the file cache
}
defer _ = std.c.unlink(index);
defer _ = std.c.unlink(shard);
try std.testing.expect(try dropCached(gpa, dir) > 0);
try std.testing.expectEqual(@as(u64, 0), try dropCached(gpa, dir));
}

/// The first `c.run` layers, the MTP layer (when stored) and the head; `dry`: check names, dtypes and shapes, read nothing.
pub fn load(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8, c: *const cfg.Config, threads: usize, dry: bool) !*Weights {
var arena_state = std.heap.ArenaAllocator.init(gpa);
Expand Down
Loading