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

- `tensorfold device` fits a Qwen4 pack by the bytes it holds in GPU memory, so the Qwen4-35B-A3B TFQ packs read as fitting on a 64 GB Mac (#6477)

- Validate qk-pack source tensor shapes before packing so malformed checkpoints fail with InvalidCheckpoint instead of reading out of bounds (#6131).

- XPU: the published Qwen4-35B-A3B FP8 config is part of the host checks, and the checkpoint check lives in its own file (#6372).
Expand Down
42 changes: 40 additions & 2 deletions zig/src/cli/info.zig
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ pub fn runStart(a: Allocator, io: std.Io, out: *std.Io.Writer, env: ?*const std.
return 1;
};
const flash_metal = @import("builtin").os.tag == .macos and std.mem.eql(u8, model_type, "qwen4_exp");
const weights = if (flash_metal) try @import("flashnext_memory").weightBytes(checkpoint, a, io, dir) else try hub.sizeOf(a, io, dir);
const on_disk = if (flash_metal) try @import("flashnext_memory").weightBytes(checkpoint, a, io, dir) else try hub.sizeOf(a, io, dir);
// Qwen4 reads its PLE lookup tables from the mapped files: price only what it holds in GPU memory.
const weights = if (flash_metal) on_disk else try @import("resident.zig").residentBytes(a, io, dir, model_type, on_disk);
const details = hub.configDetails(a, io, dir);
defer if (details.modelopt_formats) |formats| {
for (formats) |format| a.free(format);
Expand All @@ -94,7 +96,10 @@ pub fn runStart(a: Allocator, io: std.Io, out: *std.Io.Writer, env: ?*const std.
if (hub.configInt(a, io, dir, "max_position_embeddings")) |context| {
try out.print("context: {d}\n", .{context});
}
try out.print("weights: {d:.2} GiB ({d} bytes)\n", .{ @as(f64, @floatFromInt(weights)) / GiB, weights });
if (weights < on_disk) {
try out.print("weights: {d:.2} GiB ({d} bytes) in GPU memory\n", .{ gib(weights), weights });
try out.print("on disk: {d:.2} GiB ({d} bytes); its PLE lookup tables ({d} bytes) stay on disk, read in place\n", .{ gib(on_disk), on_disk, on_disk - weights });
} else try out.print("weights: {d:.2} GiB ({d} bytes)\n", .{ @as(f64, @floatFromInt(weights)) / GiB, weights });
if (flash_metal) {
const memory = @import("flashnext_memory");
const inventory = try memory.weights_plan.read(core.Checkpoint, core.quant.mlx, a, io, dir);
Expand Down Expand Up @@ -188,6 +193,39 @@ test "info prints family, format, context, weights and floor for a cached checkp
try std.testing.expect(has(refused.written(), "no registered Zig family serves model_type gemma3n"));
}

test "info names a Qwen4 pack's GPU-resident bytes and leaves other families' lines whole" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const io = std.testing.io;
if (hub.family("qwen4") == null or hub.family("qwen4_text") == null) return error.SkipZigTest;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const dir = try tmp.dir.realPathFileAlloc(io, ".", a);
const shard = @import("resident.zig").shard;
const pre = "model.language_model.layers.1.ple.ple_embedding.";
try shard(a, io, tmp.dir, "model-00001-of-00002.safetensors", &.{ .{ pre ++ "ngram_embedding.shard_0.weight", 4096 }, .{ pre ++ "ngram_embedding.shard_1.weight", 2048 } });
try shard(a, io, tmp.dir, "model-00002-of-00002.safetensors", &.{ .{ "model.language_model.embed_tokens.weight", 512 }, .{ pre ++ "ngram_heads_offsets", 16 } });
for ([_][]const u8{ "qwen4", "qwen4_text" }) |model_type| {
try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{model_type}) });
const total = try hub.sizeOf(a, io, dir);
const held = total - 6144;
var out: std.Io.Writer.Allocating = .init(a);
try std.testing.expectEqual(@as(u8, 0), try run(a, io, &out.writer, null, null, dir));
try std.testing.expect(has(out.written(), try std.fmt.allocPrint(a, "weights: 0.00 GiB ({d} bytes) in GPU memory\n", .{held})));
try std.testing.expect(has(out.written(), try std.fmt.allocPrint(a, "on disk: 0.00 GiB ({d} bytes); its PLE lookup tables (6144 bytes) stay on disk, read in place\n", .{total})));
try std.testing.expect(has(out.written(), try std.fmt.allocPrint(a, "memory floor: {d:.2} GiB", .{gib(held + runtime_margin)})));
}
// Another family with the same tensor names keeps its whole snapshot and its one weights line.
if (hub.family("nemotron_h") == null) return;
try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"nemotron_h\"}" });
const total = try hub.sizeOf(a, io, dir);
var out: std.Io.Writer.Allocating = .init(a);
try std.testing.expectEqual(@as(u8, 0), try run(a, io, &out.writer, null, null, dir));
try std.testing.expect(has(out.written(), try std.fmt.allocPrint(a, "weights: 0.00 GiB ({d} bytes)\nmemory floor: {d:.2} GiB", .{ total, gib(total + runtime_margin) })));
try std.testing.expect(std.mem.indexOf(u8, out.written(), "on disk:") == null);
}

fn has(text: []const u8, needle: []const u8) bool {
if (std.mem.indexOf(u8, text, needle) != null) return true;
std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, text });
Expand Down
11 changes: 8 additions & 3 deletions zig/src/cli/models.zig
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,17 @@ fn find(a: Allocator, io: std.Io, root: []const u8) !?[]const Found {
return found.items;
}

/// A checkpoint `models` lists, with its snapshot's size, for `tensorfold device`'s fit against this machine.
pub const OnDisk = struct { repo: []const u8, family: []const u8, model_type: []const u8, bytes: u64 };
/// A listed checkpoint, its snapshot's size and the part its engine holds in GPU memory, for `tensorfold device`.
pub const OnDisk = struct { repo: []const u8, family: []const u8, model_type: []const u8, bytes: u64, resident: u64 };

pub fn onDisk(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, override: ?[]const u8) ![]const OnDisk {
const found = (try find(a, io, try hub.cacheDir(a, env, override))) orelse return &.{};
const out = try a.alloc(OnDisk, found.len);
for (out, found) |*o, f| o.* = .{ .repo = f.listed.repo, .family = f.listed.family, .model_type = f.listed.model_type, .bytes = try hub.sizeOf(a, io, f.snapshot) };
for (out, found) |*o, f| {
const bytes = try hub.sizeOf(a, io, f.snapshot);
const resident = try @import("resident.zig").residentBytes(a, io, f.snapshot, f.listed.model_type, bytes);
o.* = .{ .repo = f.listed.repo, .family = f.listed.family, .model_type = f.listed.model_type, .bytes = bytes, .resident = resident };
}
return out;
}

Expand Down Expand Up @@ -525,6 +529,7 @@ test "onDisk sizes the checkpoints models lists, and an absent cache has none" {
try std.testing.expectEqualStrings("Org/Flash", found[0].repo);
try std.testing.expectEqualStrings("qwen4_exp", found[0].model_type);
try std.testing.expect(found[0].bytes > 0); // its config.json
try std.testing.expectEqual(found[0].bytes, found[0].resident); // no mapped tables: the whole size
try std.testing.expectEqual(@as(usize, 0), (try onDisk(a, io, null, try std.fs.path.join(a, &.{ root, "missing" }))).len);
}

Expand Down
80 changes: 80 additions & 0 deletions zig/src/cli/resident.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//! A checkpoint's bytes the engine holds in GPU memory: its files, less the lookup tables it reads in place.
const std = @import("std");
const Allocator = std.mem.Allocator;
const st = @import("core").safetensors;

/// Families whose per-layer n-gram tables stay memory-mapped (qwen4 device_weights `take` skips every table role).
const mapped_families = [_][]const u8{ "qwen4", "qwen4_text" };
const ngram_table = ".ple.ple_embedding.ngram_embedding.";

/// The bytes of `dir`'s safetensors tensors that `model_type`'s engine leaves in their files; 0 for other families.
pub fn mappedBytes(a: Allocator, io: std.Io, dir: []const u8, model_type: []const u8) !u64 {
for (mapped_families) |f| {
if (std.mem.eql(u8, f, model_type)) break;
} else return 0;
var d = std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return 0;
defer d.close(io);
var total: u64 = 0;
var it = d.iterate();
while (try it.next(io)) |entry| {
if (entry.name[0] == '.' or !std.mem.endsWith(u8, entry.name, ".safetensors")) continue;
if (entry.kind != .file and entry.kind != .sym_link) continue;
const path = try std.fs.path.join(a, &.{ dir, entry.name });
defer a.free(path);
var meta = st.Metadata.read(a, io, path) catch continue;
defer meta.deinit();
var names = meta.names.iterator();
while (names.next()) |n| if (std.mem.indexOf(u8, n.key_ptr.*, ngram_table) != null) {
total += n.value_ptr.end - n.value_ptr.begin;
};
}
return total;
}

/// `on_disk` (the snapshot's size) less the tables left mapped: what `tensorfold device` compares with the budget.
pub fn residentBytes(a: Allocator, io: std.Io, dir: []const u8, model_type: []const u8, on_disk: u64) !u64 {
return on_disk -| try mappedBytes(a, io, dir, model_type);
}

/// Test fixture: writes `name`, a BF16 safetensors file holding `tensors` (name, byte length) as zeros.
pub fn shard(a: Allocator, io: std.Io, dir: std.Io.Dir, name: []const u8, tensors: []const struct { []const u8, usize }) !void {
var header: std.Io.Writer.Allocating = .init(a);
defer header.deinit();
try header.writer.writeByte('{');
var at: usize = 0;
for (tensors, 0..) |t, i| {
try header.writer.print("{s}\"{s}\":{{\"dtype\":\"BF16\",\"shape\":[{d}],\"data_offsets\":[{d},{d}]}}", .{ if (i > 0) "," else "", t[0], t[1] / 2, at, at + t[1] });
at += t[1];
}
try header.writer.writeByte('}');
const text = header.written();
const bytes = try a.alloc(u8, 8 + text.len + at);
defer a.free(bytes);
std.mem.writeInt(u64, bytes[0..8], text.len, .little);
@memcpy(bytes[8..][0..text.len], text);
@memset(bytes[8 + text.len ..], 0);
try dir.writeFile(io, .{ .sub_path = name, .data = bytes });
}

test "resident bytes: a Qwen4 pack's mapped PLE n-gram shards leave the budget, everything else stays" {
const a = std.testing.allocator;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
defer a.free(dir);
const pre = "model.language_model.layers.1.ple.ple_embedding.";
try shard(a, io, tmp.dir, "model-00001-of-00003.safetensors", &.{ .{ pre ++ "ngram_embedding.shard_0.weight", 4096 }, .{ pre ++ "ngram_embedding.shard_1.weight", 2048 } });
try shard(a, io, tmp.dir, "nonmoe-00001-of-00003.safetensors", &.{ .{ "model.language_model.embed_tokens.weight", 512 }, .{ pre ++ "ngram_heads_offsets", 16 }, .{ "model.language_model.layers.1.ple.key_proj.weight", 256 } });
try tmp.dir.writeFile(io, .{ .sub_path = "experts.tffp6", .data = "not a safetensors file" });
try tmp.dir.writeFile(io, .{ .sub_path = ".hidden.safetensors", .data = "skipped" });
try std.testing.expectEqual(@as(u64, 6144), try mappedBytes(a, io, dir, "qwen4"));
try std.testing.expectEqual(@as(u64, 6144), try mappedBytes(a, io, dir, "qwen4_text"));
try std.testing.expectEqual(@as(u64, 10000 - 6144), try residentBytes(a, io, dir, "qwen4", 10000));
// Other families keep their whole size, even with the same tensor names.
try std.testing.expectEqual(@as(u64, 0), try mappedBytes(a, io, dir, "qwen4_exp"));
try std.testing.expectEqual(@as(u64, 10000), try residentBytes(a, io, dir, "nemotron_h", 10000));
// A missing folder holds nothing mapped, and the subtraction cannot wrap.
try std.testing.expectEqual(@as(u64, 0), try mappedBytes(a, io, "missing-snapshot-dir", "qwen4"));
try std.testing.expectEqual(@as(u64, 0), try residentBytes(a, io, dir, "qwen4", 100));
}
1 change: 1 addition & 0 deletions zig/src/cli/tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
test {
_ = @import("hub.zig");
_ = @import("models.zig");
_ = @import("resident.zig");
_ = @import("catalog.zig");
_ = @import("info.zig");
_ = @import("info_hexagon.zig");
Expand Down
8 changes: 5 additions & 3 deletions zig/src/server/device/report.zig
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ pub fn full(w: *Writer, doc: profile.Doc, s: Support, version: []const u8, fits:
} else try w.print("Not supported by tensorfold-native {s}: {s}\n", .{ version, s.reason });
try w.writeAll(if (fits.len > 0) "Models on disk:\n" else "Models on disk: none in the Hugging Face cache that this build serves\n");
for (fits) |f| {
try w.print(" {s}: {s} ({s}), {d:.1} GiB: ", .{ f.repo, f.title, f.model_type, gibs(f.bytes) });
try w.print(" {s}: {s} ({s}), {d:.1} GiB", .{ f.repo, f.title, f.model_type, gibs(f.bytes) });
if (f.resident) |held| if (held < f.bytes) try w.print(" ({d:.1} GiB in GPU memory; its lookup tables stay on disk)", .{gibs(held)});
try w.writeAll(": ");
try w.writeAll(switch (f.verdict) {
.fits => "fits\n",
.too_large => "larger than the memory for weights\n",
Expand All @@ -90,8 +92,8 @@ pub fn full(w: *Writer, doc: profile.Doc, s: Support, version: []const u8, fits:
try w.print("Profile: ~/.tensorfold/device.json, {s} scan at {s}; rescanned when the hardware or this binary changes, or with --rescan\n", .{ @tagName(doc.scan), doc.scanned_at });
}

/// One checkpoint on disk and whether it serves here.
pub const Fit = struct { repo: []const u8, title: []const u8, model_type: []const u8, bytes: u64, verdict: support.Verdict };
/// One checkpoint on disk, the bytes its engine holds in GPU memory when fewer, and whether it serves here.
pub const Fit = struct { repo: []const u8, title: []const u8, model_type: []const u8, bytes: u64, resident: ?u64 = null, verdict: support.Verdict };

pub fn backendName(b: []const u8) []const u8 {
const names = [_][2][]const u8{ .{ "metal", "Metal" }, .{ "cuda", "CUDA" }, .{ "hip", "HIP" }, .{ "xpu", "XPU" }, .{ "vulkan", "Vulkan" } };
Expand Down
17 changes: 17 additions & 0 deletions zig/src/server/device/report_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ const cuda: support.Offer = .{ .version = "test", .backends = &.{"cuda"}, .famil
.{ .model_type = "minimax_m3_vl", .formats = &.{"mlx-q3g64"} },
}, .kernel_sms = &support.release_sms };

test "device report: a checkpoint whose lookup tables stay on disk shows the bytes held in GPU memory" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const got = try scan.current(a, t.io, null, try parse.macos(a, "aarch64", fx.m5_pro_64), .{ .version = "test", .offer = metal }, "2026-11-13T01:22:01Z", false, true);
const fits = [_]report.Fit{
.{ .repo = "Org/Pack", .title = "Qwen4", .model_type = "qwen4", .bytes = 6081 * ((1 << 30) / 100), .resident = 2505 * ((1 << 30) / 100), .verdict = .fits },
.{ .repo = "Org/Same", .title = "Nemotron 3.5 Lightning", .model_type = "nemotron_h", .bytes = 17 << 30, .resident = 17 << 30, .verdict = .fits },
};
var out: std.Io.Writer.Allocating = .init(a);
try report.full(&out.writer, got.doc, got.support, "test", &fits);
const text = out.written();
try t.expect(std.mem.indexOf(u8, text, " Org/Pack: Qwen4 (qwen4), 60.8 GiB (25.0 GiB in GPU memory; its lookup tables stay on disk): fits\n") != null);
try t.expect(std.mem.indexOf(u8, text, " Org/Same: Nemotron 3.5 Lightning (nemotron_h), 17.0 GiB: fits\n") != null);
try t.expect(std.mem.indexOf(u8, text, " Memory for model weights: 42.8 GiB") != null);
}

test "device report: a known zero weight budget is printed as a size" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
Expand Down
2 changes: 1 addition & 1 deletion zig/src/server/device/support.zig
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ pub fn refusal(a: Allocator, s: Support, model_type: []const u8) !?[]const u8 {

pub const Verdict = enum { fits, too_large, not_here, not_served };

/// A checkpoint of `model_type` with `bytes` on disk: served by this build, its family runs here, it fits the budget.
/// A `model_type` checkpoint holding `bytes` in GPU memory: served by this build, runs here, fits the budget.
pub fn fit(s: Support, families: []const Family, model_type: []const u8, bytes: u64) Verdict {
if (!has(families, model_type)) return .not_served;
if (s.backend == null) return .not_here;
Expand Down
18 changes: 18 additions & 0 deletions zig/src/server/device/support_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,24 @@ test "device support: a checkpoint on disk fits, is too large, does not run here
try t.expectEqual(support.Verdict.not_served, support.fit(s, &metal_families, "deepseek_v4", 17 << 30));
}

test "device support: a Qwen4 TFQ pack fits a 64 GB Mac by its resident bytes, not its size on disk" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const s = try support.derive(a, try parse.macos(a, "aarch64", fx.m5_pro_64), metal);
// 70% of 64 GiB, less the 2 GiB reserve: 42.8 GiB.
try t.expectEqual(@as(u64, 68719476736 / 100 * 70 - (2 << 30)), s.budget);
const families = [_]support.Family{.{ .model_type = "qwen4", .formats = &.{"bf16"} }};
const centi: u64 = (1 << 30) / 100;
// Micro, Pro, Ultra: 45.61 GiB safetensors plus 7.69, 15.20, 17.08 GiB experts; the PLE table is 35.76 GiB.
for ([_]u64{ 769, 1520, 1708 }) |experts| {
const on_disk = (4561 + experts) * centi;
const resident = on_disk - 3576 * centi;
try t.expectEqual(support.Verdict.too_large, support.fit(s, &families, "qwen4", on_disk));
try t.expectEqual(support.Verdict.fits, support.fit(s, &families, "qwen4", resident));
}
}

test "device support: a reserve that exhausts known memory leaves no room for nonempty weights" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
Expand Down
11 changes: 11 additions & 0 deletions zig/src/server/device/test_fixtures.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ pub const m1_max_wired =
\\iogpu.wired_limit_mb: 28672
;

/// A 64 GB M5 Pro with the default GPU wired limit (built to match the recorded Macs' keys).
pub const m5_pro_64 =
\\machdep.cpu.brand_string: Apple M5 Pro
\\kern.osproductversion: 27.0.1
\\hw.memsize: 68719476736
\\hw.ncpu: 15
\\hw.perflevel0.logicalcpu: 5
\\hw.perflevel1.logicalcpu: 10
\\iogpu.wired_limit_mb: 0
;

/// An Intel Mac: no perflevel keys, no iogpu key.
pub const intel_mac =
\\machdep.cpu.brand_string: Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Expand Down
3 changes: 2 additions & 1 deletion zig/src/server/device_cli.zig
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ pub fn main(init: std.process.Init, args: []const [:0]const u8) !u8 {
.title = d.family,
.model_type = d.model_type,
.bytes = d.bytes,
.verdict = support.fit(got.support, bin.offer.families, d.model_type, d.bytes),
.resident = d.resident,
.verdict = support.fit(got.support, bin.offer.families, d.model_type, d.resident),
});
var out: std.Io.Writer.Allocating = .init(a);
if (json) {
Expand Down
Loading