diff --git a/CHANGELOG.md b/CHANGELOG.md index 488902b266e..24f2e7d857f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Core: Drama 3's `torch.save` reader moves to `core/torch_pth.zig` (its zip container to `core/torch_zip.zig`) and its WAV code to `core/wav.zig`; the reader also opens a root of nested state dicts, naming tensors by their keys joined with `/` (`openNested`), and returns a tensor's stored bytes at a given dtype and shape (`readRaw`), with host tests; Drama 3's generated and served audio stays byte-identical on Metal (#3719, for #3615). Thanks to @BobClawblaw. + - Qwen 3.5/3.6/3.8 on HIP: a prompt chunk before the last stops its last layer after the keys and values, and the final chunk runs that layer only over the rows that are read, through the shared prompt-tail rule CUDA and Metal use (#2845, for #2829). - Qwen3.8-27B on Metal: on a prompt's last chunk, the last layer's q projection, o projection, MLP and final norm run only over the 128-row block that holds the row the head reads, while every row still writes its keys, values and recurrent state; a chunk whose last layer has another reader (drafter taps, images, MoE, a tensor-parallel pair, the ANE share) runs every row as before, and a new `test-qwen27-prompt-tail` step checks the block byte for byte against an every-row pass (#2826, refs #2165). Thanks to @GumbiiDigital. @@ -117,6 +119,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA: with `TF_FLASHNEXT_KV_PAGES` on Linux, the Flash Next page pool no longer takes its whole arena at load: its 256 MiB pieces are mapped as streams first reach them, and a helper thread maps the next ones between requests, so at 262,144 x 3 on a GB10 about 14 GiB more stays free after load (MemAvailable 40.8-41.6 GiB against 26.5-27.0). Replies are unchanged; without `TF_FLASHNEXT_KV_PAGES`, and on other systems, nothing changes (#3066). Thanks to @Arminova. ## 1.3.0 +- CUDA lanes: a one-stream reply keeps the draft depth it priced until another depth wins by 5% on the expected tokens a millisecond, and a probe one draft deeper is verified instead of being trimmed by the lone window's own prices; one noisy round no longer leaves a reply at one draft for the rest of it (#3468). - CLI: `tensorfold models` lists the chat checkpoints from the supported-models guide that fit this machine, largest first, with the memory each needs, a quality score from TensorFold Web's quality suite (receipts in `docs/receipts/quality-suite`) and a rough one-stream speed (measured on this chip, or estimated from another chip by memory bandwidth); `--all` adds the rest, `--json` adds `machine` and `catalog` to schema 1, and the cached checkpoints follow as before (#3483). diff --git a/zig/build/drama3_metal.zig b/zig/build/drama3_metal.zig index a74e0270166..6d33787f647 100644 --- a/zig/build/drama3_metal.zig +++ b/zig/build/drama3_metal.zig @@ -4,7 +4,7 @@ const std = @import("std"); const dir = "zig/kernels/metal/drama3"; const sources = [_][]const u8{ "dense.metal", "gdn.metal", "attn.metal", "moe.metal", "nvfp4.metal", "guidance.metal", "sample.metal", "codec.metal" }; -/// Drama in the Metal engines: its `core` is the engine's safetensors, the server's tokenizer and frame_rounds. +/// Drama in the Metal engines: its `core` is the engine's safetensors, torch_pth and wav, the tokenizer, frame_rounds. pub fn addNative(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, native: *std.Build.Module, metal_std: []const u8) void { const tokenizer = native.import_table.get("tokenizer") orelse tok: { const t = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); @@ -12,7 +12,7 @@ pub fn addNative(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. break :tok t; }; const rounds = b.createModule(.{ .root_source_file = b.path("zig/src/core/frame_rounds.zig"), .target = target, .optimize = optimize }); - const shim = b.addWriteFiles().add("drama3_core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\n"); + const shim = b.addWriteFiles().add("drama3_core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\npub const torch_pth = @import(\"tensorfold\").torch_pth;\npub const wav = @import(\"tensorfold\").wav;\n"); const core = b.createModule(.{ .root_source_file = shim, .target = target, .optimize = optimize, .imports = &.{ .{ .name = "tensorfold", .module = native.import_table.get("tensorfold").? }, .{ .name = "tokenizer", .module = tokenizer }, diff --git a/zig/build/residency_host.zig b/zig/build/residency_host.zig index c7ef5114504..1bf0fcc1a59 100644 --- a/zig/build/residency_host.zig +++ b/zig/build/residency_host.zig @@ -30,7 +30,7 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M const bytes = b.createModule(.{ .root_source_file = b.addWriteFiles().add("residency-drama-empty.zig", "pub const bytes: []const u8 = &.{};\n") }); const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = b.graph.host, .link_libc = true }); const rounds = b.createModule(.{ .root_source_file = b.path("zig/src/core/frame_rounds.zig"), .target = b.graph.host }); - const shim = b.addWriteFiles().add("residency-drama-core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\n"); + const shim = b.addWriteFiles().add("residency-drama-core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\npub const torch_pth = @import(\"tensorfold\").torch_pth;\npub const wav = @import(\"tensorfold\").wav;\n"); const core = b.createModule(.{ .root_source_file = shim, .target = b.graph.host, .imports = &.{ .{ .name = "tensorfold", .module = engine }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "frame_rounds", .module = rounds } } }); const drama = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/drama3_metal.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "drama3_metallib", .module = bytes } } }); host.addImport("core", core); diff --git a/zig/build/slide_host.zig b/zig/build/slide_host.zig index 82fc265c2e6..9a08f109a46 100644 --- a/zig/build/slide_host.zig +++ b/zig/build/slide_host.zig @@ -12,7 +12,7 @@ pub fn metal(b: *std.Build, m: anytype) void { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .link_libc = true }); const rounds = b.createModule(.{ .root_source_file = b.path("zig/src/core/frame_rounds.zig"), .target = target }); const files = b.addWriteFiles(); - const core = b.createModule(.{ .root_source_file = files.add("slide-drama-core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\n"), .target = target, .imports = &.{ .{ .name = "tensorfold", .module = m.engine }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "frame_rounds", .module = rounds } } }); + const core = b.createModule(.{ .root_source_file = files.add("slide-drama-core.zig", "pub const safetensors = @import(\"tensorfold\").safetensors;\npub const tokenizer = @import(\"tokenizer\");\npub const frame_rounds = @import(\"frame_rounds\");\npub const torch_pth = @import(\"tensorfold\").torch_pth;\npub const wav = @import(\"tensorfold\").wav;\n"), .target = target, .imports = &.{ .{ .name = "tensorfold", .module = m.engine }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "frame_rounds", .module = rounds } } }); const bytes = b.createModule(.{ .root_source_file = files.add("slide-inert-metallib.zig", "pub const bytes: []const u8 = &.{};\n") }); native.addImport("kimi_k3", @import("metal_targets.zig").kimiModule(b, target, .Debug, m.metal, m.engine, m.lanes)); native.addImport("kimi_metallib", bytes); diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 5792d1d96c1..b6eeeaf861e 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -13,6 +13,8 @@ const copy_price = @import("copy_price.zig"); pub const State = struct { p: []f64, rounds: u64 = 0, + last: ?i64 = null, // the depth this rule last chose: another must beat it by depth_margin + probe: ?i64 = null, // a probe's depth for the next round (a lone window keeps it) plain: ?u64 = null, wait: ?u64 = null, ms: ?Table = null, // plain_guard: the stream's own round times @@ -173,18 +175,33 @@ pub const Rule = struct { const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else 3; return @max(1, @min(most, want)); } - var best = (try r.bestRows(who, p, most, false)).rows; - const st = &who.state.*.?; + const st = try r.state(who); + var best = (try r.bestRows(who, p, most, false, st.last)).rows; st.rounds += 1; - if (best == 0) return @intFromBool(r.probePlain(st)); + if (best == 0) { + st.last = null; // plain holds no depth: the next drafted depth is chosen fresh + st.probe = null; + return @intFromBool(r.probePlain(st)); + } st.plain = 0; st.wait = r.k.depth_probe_every; - if (best < most and st.rounds % r.k.depth_probe_every == 0) best += 1; + st.last = best; + st.probe = null; + if (best < most and st.rounds % r.k.depth_probe_every == 0) { + best += 1; + st.probe = best; + } return best; } - /// The rows with the most expected tokens a ms (0: plain) and the best of one or more, from each row's chance. - fn bestRows(r: *Rule, who: Who, chances: []const f64, most: i64, comptime copy: bool) !struct { rows: i64, drafted: i64 } { + /// The stream's estimate state, allocated from its prior on first use. + fn state(r: *Rule, who: Who) !*State { + _ = try r.rates(who); + return &who.state.*.?; + } + + /// The rows with the most expected tokens a ms (0: plain); `hold` stays unless another beats it by depth_margin. + fn bestRows(r: *Rule, who: Who, chances: []const f64, most: i64, comptime copy: bool, hold: ?i64) !struct { rows: i64, drafted: i64 } { var best: i64 = 1; var best_rate: f64 = -1.0; if (copy or r.plain_guard) { @@ -197,6 +214,7 @@ pub const Rule = struct { } var drafted: i64 = 1; var drafted_rate: f64 = -1.0; + var held_rate: f64 = -1.0; var expected: f64 = 1.0; var run: f64 = 1.0; var d: i64 = 1; @@ -205,15 +223,21 @@ pub const Rule = struct { const at: usize = @intCast(d - 1); run *= if (at < chances.len) chances[at] else chances[chances.len - 1]; expected += run; - if (expected / cost > best_rate) { + const rate = expected / cost; + if (hold != null and d == hold.?) held_rate = rate; + if (rate > best_rate) { best = d; - best_rate = expected / cost; + best_rate = rate; } - if (expected / cost > drafted_rate) { + if (rate > drafted_rate) { drafted = d; - drafted_rate = expected / cost; + drafted_rate = rate; } } + // a noisy round must not flip a held depth: another wins it only by depth_margin + if (hold) |h| { + if (best != 0 and h >= 1 and h <= most and h != best and held_rate >= 0.0 and best_rate < held_rate * r.k.depth_margin) best = h; + } return .{ .rows = best, .drafted = drafted }; } @@ -236,7 +260,7 @@ pub const Rule = struct { pub fn copyRows(r: *Rule, who: Who, chances: []const f64, rows: i64, take: bool) !i64 { if (rows <= 0 or !r.copy_guard or r.family_costs.empty()) return rows; if ((try copy_price.plain(r, who)) == null) return rows; - const best = try r.bestRows(who, chances, rows, true); + const best = try r.bestRows(who, chances, rows, true, null); const st = &who.state.*.?; if (best.rows > 0) { if (take) { diff --git a/zig/src/core/lanes/depth_constants.zig b/zig/src/core/lanes/depth_constants.zig index ef87f217175..45cd577b14b 100644 --- a/zig/src/core/lanes/depth_constants.zig +++ b/zig/src/core/lanes/depth_constants.zig @@ -8,6 +8,7 @@ pub const Constants = struct { depth_probe_every: u64 = 8, // rounds between probes one depth deeper cost_rate: f64 = 0.2, // weight of the newest round in a depth's measured time plain_margin: f64 = 1.05, // a drafted depth must beat plain rounds' tokens a ms by this much + depth_margin: f64 = 1.05, // another depth must beat the one a stream holds by this much: a round's estimate is noisy plain_wait_most: u64 = 128, // plain rounds between probes at most draft_slack: i64 = 2, // drafts a stream offers past what its last shared round granted it grant_slack: i64 = 1, // granted depths: drafts past a grant that verified every draft the stream held diff --git a/zig/src/core/lanes/depth_noise_test.zig b/zig/src/core/lanes/depth_noise_test.zig new file mode 100644 index 00000000000..aae183e9bd3 --- /dev/null +++ b/zig/src/core/lanes/depth_noise_test.zig @@ -0,0 +1,67 @@ +//! The depth rule against a round's noise, and the probe a lone window must keep for it to recover. +const std = @import("std"); +const depth = @import("depth.zig"); +const win = @import("windows.zig"); +const Stream = @import("stream.zig").Stream; +const Table = @import("table.zig").Table; +const t = std.testing; + +fn rule(gpa: std.mem.Allocator, family: *const Table, shared: *const Table, most: u32, prior: []const f64) !depth.Rule { + return .{ .gpa = gpa, .prior = prior, .most_drafts = most, .family_costs = family, .shared_costs = shared, .mtp_step_ms = 0.5, .plain_guard = true, .node_probabilities = false, .batch_rows = 8 }; +} + +test "depth: a noisy round does not take a stream off the depth it holds" { + const gpa = t.allocator; + var family: Table = .{}; + defer family.deinit(gpa); + for ([_]f64{ 16, 20, 24 }, 1..) |ms, rows| try family.put(gpa, @intCast(rows), ms); // forward ms by rows + const shared: Table = .{}; + var r = try rule(gpa, &family, &shared, 2, &.{ 0.72, 0.54 }); + defer r.deinit(); + var st: ?depth.State = null; + defer if (st) |*s| s.deinit(gpa); + const who: depth.Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; + try r.observeCost(1, 18.1, false, who); + try r.observeCost(2, 20.8, false, who); + try t.expectEqual(@as(i64, 2), try r.depth(who)); // 1.72/18.1 against 2.1088/20.8: two drafts lead + // a round inflated by the probe that followed it: two drafts now trail one, but by less than the margin + for (0..12) |_| try r.observeCost(2, 22.65, false, who); + try t.expectEqual(@as(i64, 2), try r.depth(who)); + // a depth that keeps losing by more than the margin still gives way + try r.observeCost(2, 30.0, false, who); + try t.expectEqual(@as(i64, 1), try r.depth(who)); +} + +test "depth: a probe asks one draft past the depth a stream holds" { + const gpa = t.allocator; + var family: Table = .{}; + defer family.deinit(gpa); + for ([_]f64{ 16, 20, 24, 30 }, 1..) |ms, rows| try family.put(gpa, @intCast(rows), ms); + const shared: Table = .{}; + var r = try rule(gpa, &family, &shared, 3, &.{ 0.72, 0.54, 0.5 }); + defer r.deinit(); + var st: ?depth.State = null; + defer if (st) |*s| s.deinit(gpa); + const who: depth.Who = .{ .state = &st, .draft_room = 100, .finished = false, .forced = false }; + try r.observeCost(1, 18.1, false, who); + try r.observeCost(2, 20.8, false, who); + try r.observeCost(3, 25.0, false, who); + for (1..8) |_| try t.expectEqual(@as(i64, 2), try r.depth(who)); + try t.expectEqual(@as(i64, 3), try r.depth(who)); // every eighth round probes one deeper + try t.expectEqual(@as(?i64, 3), st.?.probe); +} + +test "windows: a lone window keeps the probe a depth rule asked for" { + var s: Stream = undefined; + const probed: win.Plan = .{ .stream = &s, .position = 0, .kind = .head, .held = 2, .probe_rows = 2 }; + var counts = [_]u32{1}; + win.keepProbe(&probed, &counts); + try t.expectEqual(@as(u32, 2), counts[0]); + counts[0] = 3; + win.keepProbe(&probed, &counts); // an allocator already deeper than the probe keeps its own choice + try t.expectEqual(@as(u32, 3), counts[0]); + const priced: win.Plan = .{ .stream = &s, .position = 0, .kind = .head, .held = 2 }; + counts[0] = 1; + win.keepProbe(&priced, &counts); + try t.expectEqual(@as(u32, 1), counts[0]); +} diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 3f7ebcd6e05..5dd92e910b6 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -84,6 +84,7 @@ test { _ = @import("grammar_parallel_test.zig"); _ = @import("pricing_test.zig"); _ = @import("depth_probe_test.zig"); + _ = @import("depth_noise_test.zig"); _ = @import("proposal_external_test.zig"); _ = @import("lone_costs_test.zig"); _ = @import("depth_floor_test.zig"); diff --git a/zig/src/core/lanes/lone_copy_price_test.zig b/zig/src/core/lanes/lone_copy_price_test.zig index 66353440da0..e7acd461178 100644 --- a/zig/src/core/lanes/lone_copy_price_test.zig +++ b/zig/src/core/lanes/lone_copy_price_test.zig @@ -207,7 +207,7 @@ fn digest(got: Run) [5]u64 { return .{ got.rounds, got.drafted, got.accepted, got.copies[0] + got.copies[1], got.copy_rows }; } -/// Values from main e7e24243d, before lone copies were priced (the same configurations, clocks and copier). +/// Values from main e7e24243d, before lone copies were priced; re-pinned where the depth margin holds a depth (#3468). fn pinned(expected: [5]u64, got: Run) !void { try std.testing.expectEqual(expected, digest(got)); } @@ -215,14 +215,14 @@ fn pinned(expected: [5]u64, got: Run) !void { test "lone copy price: head windows without a copy proposed keep main's depths" { var silent = hip(true); silent.copy_drafts = false; // no copy is ever proposed - try pinned(.{ 40, 82, 55, 0, 0 }, try run(silent, long_context, .{}, 1, 96)); - try pinned(.{ 39, 138, 56, 0, 0 }, try run(silent, short_context, .{}, 1, 96)); + try pinned(.{ 40, 84, 55, 0, 0 }, try run(silent, long_context, .{}, 1, 96)); + try pinned(.{ 39, 139, 56, 0, 0 }, try run(silent, short_context, .{}, 1, 96)); } test "lone copy price: root copies and GLM's own copy rates stay as on main" { var root = hip(true); root.root_copies = true; - try pinned(.{ 52, 424, 43, 26, 365 }, try run(root, long_context, .{}, 1, 96)); + try pinned(.{ 52, 423, 43, 26, 366 }, try run(root, long_context, .{}, 1, 96)); var glm = root; // lanes/../glm/cuda_copy_policy.zig: root and context copies priced by each stream's own rate glm.context_copies = true; glm.own_copy_rates = true; @@ -458,7 +458,7 @@ test "lone copy price: kept copy prices need two timed copies on a lone stream, } test "lone copy price: engines that leave copies unpriced decide two requests in a row as before" { - // e5478c4ab: the trail of two requests in a row on one engine, hashed, where the copy gate is off + // e5478c4ab: two requests in a row on one engine, hashed, copy gate off; re-pinned for the depth margin (#3468) var tile = hip(true); tile.lone_cost_tile = 2; // CUDA's lone window prices, which keep their own calibration (lanes/lone_costs.zig) var head = hip(true); @@ -466,8 +466,8 @@ test "lone copy price: engines that leave copies unpriced decide two requests in var copies = hip(false); copies.copy_guard = false; const cases = [_]struct { m: cfgs.Model, expected: [2]u64 }{ - .{ .m = tile, .expected = .{ 14840352178686162370, 75 } }, - .{ .m = head, .expected = .{ 12942564931587194512, 69 } }, + .{ .m = tile, .expected = .{ 14952552964951112534, 75 } }, + .{ .m = head, .expected = .{ 2990995193398607308, 69 } }, .{ .m = copies, .expected = .{ 14652143946053147409, 62 } }, }; for (cases) |c| { diff --git a/zig/src/core/lanes/windows.zig b/zig/src/core/lanes/windows.zig index c2ff650a4df..7d8bced68be 100644 --- a/zig/src/core/lanes/windows.zig +++ b/zig/src/core/lanes/windows.zig @@ -30,6 +30,7 @@ pub const Plan = struct { parents: ?[]const i32 = null, // a tree's drafts' parents branch_from: u32 = 0, // the first row of suffix-match branches (0: none; lanes/fill.zig) cost_probe_rows: ?u32 = null, // an unseen width selected for calibration, confirmed by a matching completed round + probe_rows: ?u32 = null, // a depth probe's rows this round: a lone window keeps them context_copy: bool = false, // branch_from names a copied continuation appended to the head copy_trusted: bool = true, // the copy is priced from cfg.copy_rate's prior (trustedCopy), else from short_rate's deferred_copy: []const u32 = &.{}, // a full priced head may free room for this continuation @@ -112,6 +113,11 @@ pub fn plan(e: *Engine, s: *Stream, copied: ?Copy) !Plan { } } if (!p.context_copy and e.cfg.fill_lanes > 0 and s.drafts and p.kind != .forced and (p.parents == null or p.lanes != null)) try fillLanes(e, s, &p); + // a depth probe asked one draft past the priced width: this round verifies it, so its estimate can move + if (s.depth) |*st| if (st.probe) |rows| { + p.probe_rows = @intCast(@min(rows, @as(i64, @intCast(p.count())))); + st.probe = null; + }; try trail.event(e, &.{ f("ev", trail.str("plan")), f("stream", trail.str(s.id)), f("kind", trail.str(@tagName(p.kind))), f("n", trail.int(p.count())), f("tree", .{ .bool = p.parents != null }) }); return p; } @@ -317,6 +323,8 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { plans[0].stream.cost_probe_trial = lone_costs.trial(plans[0].stream, probs[0], count + 1); } if (live) { + // a depth probe asks one draft past the priced width: keep it, or the acceptance it explores never moves + keepProbe(&plans[0], counts); var expected: f64 = 1; for (probs[0][0..counts[0]]) |chance| expected += chance; const ms = own.get(1 + @as(i64, counts[0])); @@ -356,6 +364,13 @@ pub fn allocate(e: *Engine, plans: []Plan) !void { try trail.event(e, &.{ f("ev", trail.str("alloc")), f("plans", .{ .list = rows }) }); } +/// A depth probe asks one draft past the priced width: this round verifies it, so its estimate can move. +pub fn keepProbe(p: *const Plan, counts: []u32) void { + if (p.probe_rows) |rows| { + if (rows > counts[0]) counts[0] = rows; + } +} + /// A family's row policy decides each head window's drafts (lanes/trim.zig); other windows run whole. fn trimmed(e: *Engine, plans: []Plan, t: trim.Trim) !void { const a = e.arena.allocator(); diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index caac0deebd9..57fb3e598a4 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -25,6 +25,8 @@ pub const CopyIndex = @import("copy_index.zig").CopyIndex; pub const recurrent_workspace = @import("recurrent_workspace.zig"); pub const tokenizer = @import("tokenizer"); // a module of its own, so the native server shares it pub const proposal_rows = @import("proposal_rows.zig"); +pub const torch_pth = @import("torch_pth.zig"); // torch.save archives read without Python: Drama 3's codec +pub const wav = @import("wav.zig"); // reference clips in, speech out pub const proposal_vocab = @import("proposal_vocab.zig"); pub const ids_json = @import("ids_json.zig"); pub const affine4_host = @import("affine4_host.zig"); @@ -73,6 +75,8 @@ pub const kv_prompts = @import("kv_prompts.zig"); pub const state_walk = @import("state_walk.zig"); test { + _ = torch_pth; + _ = wav; _ = startup_receipt; _ = benchmark_group; _ = dspine; diff --git a/zig/src/families/drama3/codec_pth.zig b/zig/src/core/torch_pth.zig similarity index 80% rename from zig/src/families/drama3/codec_pth.zig rename to zig/src/core/torch_pth.zig index 98850ed820d..204aa5b1c56 100644 --- a/zig/src/families/drama3/codec_pth.zig +++ b/zig/src/core/torch_pth.zig @@ -1,4 +1,4 @@ -//! codec.pth read without Python: the zip's stored members and a pickle VM limited to weights_only's allow-list. +//! torch.save checkpoints read without Python: stored zip members and a pickle VM limited to weights_only's allow-list. const std = @import("std"); const Allocator = std.mem.Allocator; @@ -36,7 +36,10 @@ pub const Tensor = struct { stride: []const u64, }; -const Member = struct { local: u64, size: u64, crc: u32 }; +const zip = @import("torch_zip.zig"); +const Member = zip.Member; +const readMember = zip.readMember; +const readDirectory = zip.readDirectory; pub const Archive = struct { arena: std.heap.ArenaAllocator, @@ -48,6 +51,15 @@ pub const Archive = struct { prefix: []const u8, pub fn open(gpa: Allocator, io: std.Io, path: []const u8) !Archive { + return openAs(gpa, io, path, false); + } + + /// A root dict nesting state dicts beside plain values: tensors are named by their keys joined with '/'. + pub fn openNested(gpa: Allocator, io: std.Io, path: []const u8) !Archive { + return openAs(gpa, io, path, true); + } + + fn openAs(gpa: Allocator, io: std.Io, path: []const u8, nested: bool) !Archive { var arena = std.heap.ArenaAllocator.init(gpa); errdefer arena.deinit(); const a = arena.allocator(); @@ -74,7 +86,7 @@ pub const Archive = struct { if (pm.size > 64 << 20) return error.BadArchive; const pickle = try a.alloc(u8, @intCast(pm.size)); try readMember(io, file, pm, pickle); - const tensors = try unpickle(a, pickle); + const tensors = try unpickle(a, pickle, nested); return .{ .arena = arena, .io = io, .file = file, .members = members, .tensors = tensors, .prefix = prefix }; } @@ -91,6 +103,36 @@ pub const Archive = struct { }; } + /// name's elements as stored (row-major bytes, caller frees): dtype and shape as given, the member CRC-checked. + pub fn readRaw(self: *const Archive, gpa: Allocator, name: []const u8, dtype: DType, shape: []const u64) ![]u8 { + const t = try self.tensor(name); + if (t.dtype != dtype) return error.UnexpectedDType; + if (!std.mem.eql(u64, t.shape, shape)) { + std.log.err("tensor {s} has shape {any}, expected {any}", .{ name, t.shape, shape }); + return error.ShapeMismatch; + } + var numel: u64 = 1; + var i = t.shape.len; + while (i > 0) { + i -= 1; + if (t.shape[i] != 1 and t.stride[i] != numel) return error.NonContiguousTensor; + numel *= t.shape[i]; + } + if (t.offset > t.storage_numel or numel > t.storage_numel - t.offset) return error.BadArchive; + const width = elementBytes(dtype); + const key = try std.fmt.allocPrint(gpa, "{s}data/{s}", .{ self.prefix, t.storage }); + defer gpa.free(key); + const m = self.members.get(key) orelse return error.MissingStorage; + if (m.size != std.math.mul(u64, t.storage_numel, width) catch return error.BadArchive) return error.BadArchive; + const all = try gpa.alloc(u8, @intCast(m.size)); + errdefer gpa.free(all); + try readMember(self.io, self.file, m, all); + if (t.offset == 0 and numel == t.storage_numel) return all; + const out = try gpa.dupe(u8, all[@intCast(t.offset * width)..][0..@intCast(numel * width)]); + gpa.free(all); + return out; + } + /// name's float32 elements row-major (caller frees), its shape and its storage member's CRC-32 checked. pub fn readF32(self: *const Archive, gpa: Allocator, name: []const u8, shape: []const u64) ![]f32 { const t = try self.tensor(name); @@ -124,108 +166,6 @@ pub const Archive = struct { } }; -fn readU16(b: []const u8, at: usize) u16 { - return std.mem.readInt(u16, b[at..][0..2], .little); -} - -fn readU32(b: []const u8, at: usize) u32 { - return std.mem.readInt(u32, b[at..][0..4], .little); -} - -fn readU64(b: []const u8, at: usize) u64 { - return std.mem.readInt(u64, b[at..][0..8], .little); -} - -/// A stored member's bytes into `out` (exactly its size), CRC-checked. -fn readMember(io: std.Io, file: std.Io.File, m: Member, out: []u8) !void { - if (out.len != m.size) return error.BadArchive; - var head: [30]u8 = undefined; - if (try file.readPositionalAll(io, &head, m.local) != head.len) return error.ShortRead; - if (readU32(&head, 0) != 0x04034b50) return error.BadArchive; - const data: u64 = m.local + @as(u64, head.len) + @as(u64, readU16(&head, 26)) + @as(u64, readU16(&head, 28)); - if (try file.readPositionalAll(io, out, data) != out.len) return error.ShortRead; - if (std.hash.Crc32.hash(out) != m.crc) return error.ChecksumMismatch; -} - -/// The central directory: every member stored (method 0), zip64 records honoured. -fn readDirectory(a: Allocator, io: std.Io, file: std.Io.File) !std.StringHashMapUnmanaged(Member) { - const size = try file.length(io); - if (size < 22) return error.BadArchive; - const tail_len: usize = @intCast(@min(size, 22 + 0xFFFF)); - const tail = try a.alloc(u8, tail_len); - if (try file.readPositionalAll(io, tail, size - @as(u64, tail_len)) != tail_len) return error.ShortRead; - var at: usize = tail_len - 22; - while (readU32(tail, at) != 0x06054b50) { - if (at == 0) return error.BadArchive; - at -= 1; - } - var count: u64 = readU16(tail, at + 10); - var cd_size: u64 = readU32(tail, at + 12); - var cd_off: u64 = readU32(tail, at + 16); - if (count == 0xFFFF or cd_size == 0xFFFFFFFF or cd_off == 0xFFFFFFFF) { - if (at < 20 or readU32(tail, at - 20) != 0x07064b50) return error.BadArchive; - var rec: [56]u8 = undefined; - if (try file.readPositionalAll(io, &rec, readU64(tail, at - 20 + 8)) != rec.len) return error.ShortRead; - if (readU32(&rec, 0) != 0x06064b50) return error.BadArchive; - count = readU64(&rec, 32); - cd_size = readU64(&rec, 40); - cd_off = readU64(&rec, 48); - } - if (cd_size > 64 << 20 or cd_off > size or cd_size > size - cd_off) return error.BadArchive; - const cd = try a.alloc(u8, @intCast(cd_size)); - if (try file.readPositionalAll(io, cd, cd_off) != cd.len) return error.ShortRead; - var members: std.StringHashMapUnmanaged(Member) = .empty; - var p: usize = 0; - var n: u64 = 0; - while (n < count) : (n += 1) { - if (cd.len - p < 46 or readU32(cd, p) != 0x02014b50) return error.BadArchive; - const method = readU16(cd, p + 10); - const crc = readU32(cd, p + 16); - var csize: u64 = readU32(cd, p + 20); - var usize_: u64 = readU32(cd, p + 24); - const nlen: usize = readU16(cd, p + 28); - const xlen: usize = readU16(cd, p + 30); - const clen: usize = readU16(cd, p + 32); - var local: u64 = readU32(cd, p + 42); - if (cd.len - p - 46 < nlen + xlen + clen) return error.BadArchive; - const name = cd[p + 46 ..][0..nlen]; - var x = p + 46 + nlen; - const xend = x + xlen; - while (xend - x >= 4) { - const id = readU16(cd, x); - const len: usize = readU16(cd, x + 2); - if (xend - x - 4 < len) return error.BadArchive; - if (id == 0x0001) { - var f = x + 4; - const fend = f + len; - if (usize_ == 0xFFFFFFFF) { - if (fend - f < 8) return error.BadArchive; - usize_ = readU64(cd, f); - f += 8; - } - if (csize == 0xFFFFFFFF) { - if (fend - f < 8) return error.BadArchive; - csize = readU64(cd, f); - f += 8; - } - if (local == 0xFFFFFFFF) { - if (fend - f < 8) return error.BadArchive; - local = readU64(cd, f); - } - } - x += 4 + len; - } - if (method != 0 or csize != usize_) { - std.log.err("codec.pth member {s} is compressed; torch.save stores members", .{name}); - return error.CompressedMember; - } - if (local > size or usize_ > size - local) return error.BadArchive; - try members.put(a, name, .{ .local = local, .size = usize_, .crc = crc }); - p += 46 + nlen + xlen + clen; - } - return members; -} - const GlobalRef = union(enum) { ordered_dict, rebuild_tensor_v2, storage_type: DType }; const Storage = struct { dtype: DType, key: []const u8, numel: u64 }; @@ -244,7 +184,9 @@ const Value = union(enum) { none, boolean: bool, int: i64, + float: f64, str: []const u8, + list: *std.ArrayList(Value), tuple: []const Value, dict: *Dict, global: GlobalRef, @@ -376,8 +318,26 @@ fn reduce(a: Allocator, f: Value, args: Value) !Value { } } +/// A nested root's tensors into `out` under `prefix`; plain values (numbers, strings, lists) are not weights. +fn collect(a: Allocator, out: *std.StringHashMapUnmanaged(Tensor), prefix: []const u8, d: *const Dict, depth: usize) !void { + if (depth > 8) return error.BadPickle; + for (d.keys.items, d.values.items) |k, v| { + if (k != .str) continue; + const name = if (prefix.len == 0) k.str else try std.mem.concat(a, u8, &.{ prefix, "/", k.str }); + switch (v) { + .tensor => |t| { + const gop = try out.getOrPut(a, name); + if (gop.found_existing) return error.BadPickle; + gop.value_ptr.* = t.*; + }, + .dict => |sub| try collect(a, out, name, sub, depth + 1), + else => {}, + } + } +} + /// The state dict's tensors by name. Unknown opcodes and globals are refused, never run. -fn unpickle(a: Allocator, data: []const u8) !std.StringHashMapUnmanaged(Tensor) { +fn unpickle(a: Allocator, data: []const u8, nested: bool) !std.StringHashMapUnmanaged(Tensor) { var stack: std.ArrayList(Value) = .empty; var marks: std.ArrayList(usize) = .empty; var memo: std.AutoHashMapUnmanaged(u32, Value) = .empty; @@ -430,6 +390,23 @@ fn unpickle(a: Allocator, data: []const u8) !std.StringHashMapUnmanaged(Tensor) try stack.append(a, .{ .int = v }); }, 'N' => try stack.append(a, .none), + 'G' => try stack.append(a, .{ .float = @bitCast(std.mem.readInt(u64, (try r.bytes(8))[0..8], .big)) }), // BINFLOAT + ']' => { // EMPTY_LIST + const l = try a.create(std.ArrayList(Value)); + l.* = .empty; + try stack.append(a, .{ .list = l }); + }, + 'a' => { // APPEND + const v = try pop(&stack); + if (stack.items.len == 0 or stack.items[stack.items.len - 1] != .list) return error.BadPickle; + try stack.items[stack.items.len - 1].list.append(a, v); + }, + 'e' => { // APPENDS + const at = marks.pop() orelse return error.BadPickle; + if (at == 0 or at > stack.items.len or stack.items[at - 1] != .list) return error.BadPickle; + try stack.items[at - 1].list.appendSlice(a, stack.items[at..]); + stack.shrinkRetainingCapacity(at); + }, 0x88 => try stack.append(a, .{ .boolean = true }), // NEWTRUE 0x89 => try stack.append(a, .{ .boolean = false }), // NEWFALSE 'q', 'r' => { // BINPUT, LONG_BINPUT @@ -478,6 +455,10 @@ fn unpickle(a: Allocator, data: []const u8) !std.StringHashMapUnmanaged(Tensor) else => return error.BadPickle, }; var out: std.StringHashMapUnmanaged(Tensor) = .empty; + if (nested) { + try collect(a, &out, "", root, 0); + return out; + } for (root.keys.items, root.values.items) |k, v| { if (k != .str or v != .tensor) return error.BadPickle; const gop = try out.getOrPut(a, k.str); @@ -524,7 +505,7 @@ test "the state-dict VM reads torch.save's tensor records and their views" { }; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - const tensors = try unpickle(arena.allocator(), &fixture); + const tensors = try unpickle(arena.allocator(), &fixture, false); try std.testing.expectEqual(@as(u32, 3), tensors.count()); const w = tensors.get("a.weight").?; try std.testing.expectEqual(DType.f32, w.dtype); @@ -549,7 +530,7 @@ test "the state-dict VM refuses globals outside the allow-list" { const evil = "\x80\x02cos\nsystem\n."; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - try std.testing.expectError(error.ForbiddenGlobal, unpickle(arena.allocator(), evil)); + try std.testing.expectError(error.ForbiddenGlobal, unpickle(arena.allocator(), evil, false)); } /// A float32 storage of 2^62 + 1 elements (an 8-byte LONG1 count): `numel * 4` wraps to the 4 bytes its member holds. @@ -571,3 +552,7 @@ fn readWrapped() !void { test "a storage whose byte count wraps past 2^64 is refused, not sized by the wrapped count" { try std.testing.expectEqual(@import("sys").isolate.Outcome.passed, try @import("sys").isolate.run(readWrapped, .{})); } + +test { + _ = @import("torch_pth_test.zig"); +} diff --git a/zig/src/core/torch_pth_test.zig b/zig/src/core/torch_pth_test.zig new file mode 100644 index 00000000000..0d7611b5359 --- /dev/null +++ b/zig/src/core/torch_pth_test.zig @@ -0,0 +1,370 @@ +//! torch_pth's nested roots and raw reads on archives built here: names, plain values, views, refusals and damage. + +const std = @import("std"); +const pth = @import("torch_pth.zig"); +const Archive = pth.Archive; + +/// A torch.save pickle, written opcode by opcode (protocol 2, as torch.save writes it). +const Pickle = struct { + b: std.ArrayList(u8) = .empty, + + fn op(p: *Pickle, bytes: []const u8) void { + p.b.appendSlice(std.testing.allocator, bytes) catch @panic("oom"); + } + + fn str(p: *Pickle, s: []const u8) void { + p.op("X"); + var n: [4]u8 = undefined; + std.mem.writeInt(u32, &n, @intCast(s.len), .little); + p.op(&n); + p.op(s); + } + + fn int(p: *Pickle, v: u16) void { + if (v < 256) p.op(&.{ 'K', @intCast(v) }) else p.op(&.{ 'M', @truncate(v), @intCast(v >> 8) }); + } + + fn ints(p: *Pickle, vs: []const u16) void { + p.op("("); + for (vs) |v| p.int(v); + p.op("t"); + } + + /// An OrderedDict, its items and the `_metadata` attribute torch's state dicts carry (BUILD). + fn stateDictOpen(p: *Pickle) void { + p.op("ccollections\nOrderedDict\n)R("); + } + + fn stateDictClose(p: *Pickle) void { + p.op("u}"); + p.str("_metadata"); + p.op("ccollections\nOrderedDict\n)R"); + p.str(""); + p.op("}"); + p.str("version"); + p.int(1); + p.op("sssb"); + } + + /// _rebuild_tensor_v2((storage, Type, key, "cpu", numel), offset, shape, stride, False, OrderedDict()). + fn tensor(p: *Pickle, storage: []const u8, key: []const u8, numel: u16, offset: u16, shape: []const u16, stride: []const u16) void { + p.op("ctorch._utils\n_rebuild_tensor_v2\n(("); + p.str("storage"); + p.op("ctorch\n"); + p.op(storage); + p.op("\n"); + p.str(key); + p.str("cpu"); + p.int(numel); + p.op("tQ"); + p.int(offset); + p.ints(shape); + p.ints(stride); + p.op("\x89ccollections\nOrderedDict\n)RtR"); + } + + fn done(p: *Pickle) []const u8 { + p.op("."); + return p.b.items; + } + + fn deinit(p: *Pickle) void { + p.b.deinit(std.testing.allocator); + } +}; + +const Entry = struct { name: []const u8, data: []const u8, method: u16 = 0, crc: ?u32 = null }; + +fn put16(l: *std.ArrayList(u8), v: u16) void { + var b: [2]u8 = undefined; + std.mem.writeInt(u16, &b, v, .little); + l.appendSlice(std.testing.allocator, &b) catch @panic("oom"); +} + +fn put32(l: *std.ArrayList(u8), v: u32) void { + var b: [4]u8 = undefined; + std.mem.writeInt(u32, &b, v, .little); + l.appendSlice(std.testing.allocator, &b) catch @panic("oom"); +} + +/// A zip of stored members (local headers, central directory, end record), as torch.save lays it out. +fn zipBytes(entries: []const Entry) []u8 { + const a = std.testing.allocator; + var out: std.ArrayList(u8) = .empty; + var cd: std.ArrayList(u8) = .empty; + defer cd.deinit(a); + for (entries) |e| { + const crc = e.crc orelse std.hash.Crc32.hash(e.data); + const local: u32 = @intCast(out.items.len); + for ([_]*std.ArrayList(u8){ &out, &cd }, 0..) |l, central| { + put32(l, if (central == 0) 0x04034b50 else 0x02014b50); + if (central == 1) put16(l, 20); + for ([_]u16{ 20, 0, e.method, 0, 0 }) |v| put16(l, v); + for ([_]u32{ crc, @intCast(e.data.len), @intCast(e.data.len) }) |v| put32(l, v); + put16(l, @intCast(e.name.len)); + put16(l, 0); + if (central == 1) { + for ([_]u16{ 0, 0, 0 }) |v| put16(l, v); + put32(l, 0); + put32(l, local); + } + l.appendSlice(a, e.name) catch @panic("oom"); + } + out.appendSlice(a, e.data) catch @panic("oom"); + } + const cd_off: u32 = @intCast(out.items.len); + out.appendSlice(a, cd.items) catch @panic("oom"); + put32(&out, 0x06054b50); + for ([_]u16{ 0, 0, @intCast(entries.len), @intCast(entries.len) }) |v| put16(&out, v); + put32(&out, @intCast(cd.items.len)); + put32(&out, cd_off); + put16(&out, 0); + return out.toOwnedSlice(a) catch @panic("oom"); +} + +const Fixture = struct { + tmp: std.testing.TmpDir, + path: []u8, + + fn init(bytes: []const u8) !Fixture { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + errdefer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "model.pth", .data = bytes }); + const dir = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator); + defer std.testing.allocator.free(dir); + return .{ .tmp = tmp, .path = try std.fs.path.join(std.testing.allocator, &.{ dir, "model.pth" }) }; + } + + fn deinit(f: *Fixture) void { + std.testing.allocator.free(f.path); + f.tmp.cleanup(); + } +}; + +/// Ten float32 values 0..9 and six bf16 words, as the storages "0" and "1". +fn storages() [2][]const u8 { + const S = struct { + const f32s: [40]u8 = blk: { + var b: [40]u8 = undefined; + for (0..10) |i| std.mem.writeInt(u32, b[i * 4 ..][0..4], @bitCast(@as(f32, @floatFromInt(i))), .little); + break :blk b; + }; + const bf16s = [12]u8{ 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0 }; + }; + return .{ &S.f32s, &S.bf16s }; +} + +/// A state dict under "model", a tensor two dicts down under "ema", and plain values beside them. +fn nestedPickle(p: *Pickle) []const u8 { + p.op("\x80\x02}("); + p.str("model"); + p.stateDictOpen(); + p.str("enc.w"); + p.tensor("FloatStorage", "0", 10, 4, &.{ 2, 3 }, &.{ 3, 1 }); + p.str("enc.b"); + p.tensor("FloatStorage", "0", 10, 0, &.{2}, &.{1}); + p.stateDictClose(); + p.str("ema"); + p.op("}("); + p.str("inner"); + p.op("}("); + p.str("b"); + p.tensor("BFloat16Storage", "1", 6, 2, &.{ 2, 2 }, &.{ 2, 1 }); + p.op("u"); + p.op("u"); + p.str("step"); + p.int(7); + p.str("config"); + p.op("}("); + p.str("name"); + p.str("x"); + p.str("layers"); + p.op("](K\x01K\x02e"); + p.op("u"); + p.str("lr"); + p.op("G\x3f\xe0\x00\x00\x00\x00\x00\x00"); + p.op("u"); + return p.done(); +} + +fn nestedArchive(pickle: []const u8) []u8 { + const s = storages(); + return zipBytes(&.{ + .{ .name = "ckpt/data.pkl", .data = pickle }, + .{ .name = "ckpt/byteorder", .data = "little" }, + .{ .name = "ckpt/data/0", .data = s[0] }, + .{ .name = "ckpt/data/1", .data = s[1] }, + .{ .name = "ckpt/version", .data = "3\n" }, + }); +} + +test "openNested names a nested root's tensors by their joined keys and skips plain values and metadata" { + const gpa = std.testing.allocator; + var p: Pickle = .{}; + defer p.deinit(); + const bytes = nestedArchive(nestedPickle(&p)); + defer gpa.free(bytes); + var f = try Fixture.init(bytes); + defer f.deinit(); + var arc = try Archive.openNested(gpa, std.testing.io, f.path); + defer arc.close(); + try std.testing.expectEqual(@as(u32, 3), arc.tensors.count()); + try std.testing.expectEqualStrings("ckpt/", arc.prefix); + const w = try arc.tensor("model/enc.w"); + try std.testing.expectEqual(pth.DType.f32, w.dtype); + try std.testing.expectEqualSlices(u64, &.{ 2, 3 }, w.shape); + try std.testing.expectEqual(@as(u64, 4), w.offset); + try std.testing.expectEqual(pth.DType.bf16, (try arc.tensor("ema/inner/b")).dtype); + for ([_][]const u8{ "step", "config/name", "config/layers", "lr", "model/_metadata", "model", "ema/inner" }) |name| + try std.testing.expect(arc.tensors.get(name) == null); +} + +test "readRaw returns a view's own elements: offset slices of a shared storage, at each width" { + const gpa = std.testing.allocator; + var p: Pickle = .{}; + defer p.deinit(); + const bytes = nestedArchive(nestedPickle(&p)); + defer gpa.free(bytes); + var f = try Fixture.init(bytes); + defer f.deinit(); + var arc = try Archive.openNested(gpa, std.testing.io, f.path); + defer arc.close(); + const s = storages(); + const w = try arc.readRaw(gpa, "model/enc.w", .f32, &.{ 2, 3 }); + defer gpa.free(w); + try std.testing.expectEqualSlices(u8, s[0][16..40], w); + const b = try arc.readRaw(gpa, "model/enc.b", .f32, &.{2}); + defer gpa.free(b); + try std.testing.expectEqualSlices(u8, s[0][0..8], b); + const h = try arc.readRaw(gpa, "ema/inner/b", .bf16, &.{ 2, 2 }); + defer gpa.free(h); + try std.testing.expectEqualSlices(u8, s[1][4..12], h); + try std.testing.expectError(error.UnexpectedDType, arc.readRaw(gpa, "ema/inner/b", .f16, &.{ 2, 2 })); +} + +test "readRaw refuses a view past its storage, a strided view and a storage of the wrong size" { + const gpa = std.testing.allocator; + var p: Pickle = .{}; + defer p.deinit(); + p.op("\x80\x02}("); + p.str("past"); + p.tensor("FloatStorage", "0", 10, 5, &.{ 2, 3 }, &.{ 3, 1 }); + p.str("strided"); + p.tensor("FloatStorage", "0", 10, 0, &.{ 2, 3 }, &.{ 1, 2 }); + p.str("short"); + p.tensor("FloatStorage", "0", 11, 0, &.{2}, &.{1}); + p.str("missing"); + p.tensor("FloatStorage", "9", 2, 0, &.{2}, &.{1}); + p.op("u"); + const s = storages(); + const bytes = zipBytes(&.{ .{ .name = "ckpt/data.pkl", .data = p.done() }, .{ .name = "ckpt/data/0", .data = s[0] } }); + defer gpa.free(bytes); + var f = try Fixture.init(bytes); + defer f.deinit(); + var arc = try Archive.open(gpa, std.testing.io, f.path); + defer arc.close(); + try std.testing.expectError(error.BadArchive, arc.readRaw(gpa, "past", .f32, &.{ 2, 3 })); + try std.testing.expectError(error.NonContiguousTensor, arc.readRaw(gpa, "strided", .f32, &.{ 2, 3 })); + try std.testing.expectError(error.BadArchive, arc.readRaw(gpa, "short", .f32, &.{2})); + try std.testing.expectError(error.MissingStorage, arc.readRaw(gpa, "missing", .f32, &.{2})); +} + +test "open refuses a nested root in flat mode; openNested refuses a name reached twice and roots past eight levels" { + const gpa = std.testing.allocator; + var p: Pickle = .{}; + defer p.deinit(); + const nested = nestedArchive(nestedPickle(&p)); + defer gpa.free(nested); + var f = try Fixture.init(nested); + defer f.deinit(); + try std.testing.expectError(error.BadPickle, Archive.open(gpa, std.testing.io, f.path)); + + var twice: Pickle = .{}; + defer twice.deinit(); + twice.op("\x80\x02}("); + twice.str("a/b"); + twice.tensor("FloatStorage", "0", 10, 0, &.{2}, &.{1}); + twice.str("a"); + twice.op("}("); + twice.str("b"); + twice.tensor("FloatStorage", "0", 10, 0, &.{2}, &.{1}); + twice.op("uu"); + const dup = nestedArchive(twice.done()); + defer gpa.free(dup); + var g = try Fixture.init(dup); + defer g.deinit(); + try std.testing.expectError(error.BadPickle, Archive.openNested(gpa, std.testing.io, g.path)); + + var deep: Pickle = .{}; + defer deep.deinit(); + deep.op("\x80\x02"); + for (0..10) |_| { + deep.op("}("); + deep.str("d"); + } + deep.tensor("FloatStorage", "0", 10, 0, &.{2}, &.{1}); + for (0..10) |_| deep.op("u"); + const deep_bytes = nestedArchive(deep.done()); + defer gpa.free(deep_bytes); + var h = try Fixture.init(deep_bytes); + defer h.deinit(); + try std.testing.expectError(error.BadPickle, Archive.openNested(gpa, std.testing.io, h.path)); +} + +fn expectOpenError(expected: anyerror, bytes: []const u8) !void { + var f = try Fixture.init(bytes); + defer f.deinit(); + try std.testing.expectError(expected, Archive.openNested(std.testing.allocator, std.testing.io, f.path)); +} + +test "damaged archives are refused: CRC mismatches, truncation, missing or doubled pickles, big-endian, bad pickles" { + const gpa = std.testing.allocator; + var p: Pickle = .{}; + defer p.deinit(); + const pickle = nestedPickle(&p); + const s = storages(); + + // a storage byte changed after its CRC was written: the open succeeds, the read refuses + const good = nestedArchive(pickle); + defer gpa.free(good); + const flipped = try gpa.dupe(u8, good); + defer gpa.free(flipped); + const at = std.mem.indexOf(u8, flipped, s[0]).?; + flipped[at + 20] ^= 0x01; + var f = try Fixture.init(flipped); + defer f.deinit(); + var arc = try Archive.openNested(gpa, std.testing.io, f.path); + defer arc.close(); + try std.testing.expectError(error.ChecksumMismatch, arc.readRaw(gpa, "model/enc.w", .f32, &.{ 2, 3 })); + + const bad_crc = zipBytes(&.{.{ .name = "ckpt/data.pkl", .data = pickle, .crc = 0 }}); + defer gpa.free(bad_crc); + try expectOpenError(error.ChecksumMismatch, bad_crc); + + try expectOpenError(error.BadArchive, good[0 .. good.len - 22]); // no end record + try expectOpenError(error.BadArchive, good[0..10]); + + const none = zipBytes(&.{.{ .name = "ckpt/data/0", .data = s[0] }}); + defer gpa.free(none); + try expectOpenError(error.BadArchive, none); + + const two = zipBytes(&.{ .{ .name = "a/data.pkl", .data = pickle }, .{ .name = "b/data.pkl", .data = pickle } }); + defer gpa.free(two); + try expectOpenError(error.BadArchive, two); + + const big = zipBytes(&.{ .{ .name = "ckpt/data.pkl", .data = pickle }, .{ .name = "ckpt/byteorder", .data = "big" } }); + defer gpa.free(big); + try expectOpenError(error.BigEndianArchive, big); + + const cut = zipBytes(&.{.{ .name = "ckpt/data.pkl", .data = pickle[0 .. pickle.len - 1] }}); // no STOP + defer gpa.free(cut); + try expectOpenError(error.BadPickle, cut); + + // a storage member whose local header is said to lie past the end of the file + const far = try gpa.dupe(u8, good); + defer gpa.free(far); + const name = std.mem.lastIndexOf(u8, far, "ckpt/data/0").?; // its central directory entry's name + std.mem.writeInt(u32, far[name - 4 ..][0..4], 1 << 30, .little); + try expectOpenError(error.BadArchive, far); +} diff --git a/zig/src/core/torch_zip.zig b/zig/src/core/torch_zip.zig new file mode 100644 index 00000000000..3a29f2aac9a --- /dev/null +++ b/zig/src/core/torch_zip.zig @@ -0,0 +1,108 @@ +//! A torch.save archive's zip container: the central directory and its stored members, CRC-checked. + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const Member = struct { local: u64, size: u64, crc: u32 }; + +pub fn readU16(b: []const u8, at: usize) u16 { + return std.mem.readInt(u16, b[at..][0..2], .little); +} + +pub fn readU32(b: []const u8, at: usize) u32 { + return std.mem.readInt(u32, b[at..][0..4], .little); +} + +pub fn readU64(b: []const u8, at: usize) u64 { + return std.mem.readInt(u64, b[at..][0..8], .little); +} + +/// A stored member's bytes into `out` (exactly its size), CRC-checked. +pub fn readMember(io: std.Io, file: std.Io.File, m: Member, out: []u8) !void { + if (out.len != m.size) return error.BadArchive; + var head: [30]u8 = undefined; + if (try file.readPositionalAll(io, &head, m.local) != head.len) return error.ShortRead; + if (readU32(&head, 0) != 0x04034b50) return error.BadArchive; + const data: u64 = m.local + @as(u64, head.len) + @as(u64, readU16(&head, 26)) + @as(u64, readU16(&head, 28)); + if (try file.readPositionalAll(io, out, data) != out.len) return error.ShortRead; + if (std.hash.Crc32.hash(out) != m.crc) return error.ChecksumMismatch; +} + +/// The central directory: every member stored (method 0), zip64 records honoured. +pub fn readDirectory(a: Allocator, io: std.Io, file: std.Io.File) !std.StringHashMapUnmanaged(Member) { + const size = try file.length(io); + if (size < 22) return error.BadArchive; + const tail_len: usize = @intCast(@min(size, 22 + 0xFFFF)); + const tail = try a.alloc(u8, tail_len); + if (try file.readPositionalAll(io, tail, size - @as(u64, tail_len)) != tail_len) return error.ShortRead; + var at: usize = tail_len - 22; + while (readU32(tail, at) != 0x06054b50) { + if (at == 0) return error.BadArchive; + at -= 1; + } + var count: u64 = readU16(tail, at + 10); + var cd_size: u64 = readU32(tail, at + 12); + var cd_off: u64 = readU32(tail, at + 16); + if (count == 0xFFFF or cd_size == 0xFFFFFFFF or cd_off == 0xFFFFFFFF) { + if (at < 20 or readU32(tail, at - 20) != 0x07064b50) return error.BadArchive; + var rec: [56]u8 = undefined; + if (try file.readPositionalAll(io, &rec, readU64(tail, at - 20 + 8)) != rec.len) return error.ShortRead; + if (readU32(&rec, 0) != 0x06064b50) return error.BadArchive; + count = readU64(&rec, 32); + cd_size = readU64(&rec, 40); + cd_off = readU64(&rec, 48); + } + if (cd_size > 64 << 20 or cd_off > size or cd_size > size - cd_off) return error.BadArchive; + const cd = try a.alloc(u8, @intCast(cd_size)); + if (try file.readPositionalAll(io, cd, cd_off) != cd.len) return error.ShortRead; + var members: std.StringHashMapUnmanaged(Member) = .empty; + var p: usize = 0; + var n: u64 = 0; + while (n < count) : (n += 1) { + if (cd.len - p < 46 or readU32(cd, p) != 0x02014b50) return error.BadArchive; + const method = readU16(cd, p + 10); + const crc = readU32(cd, p + 16); + var csize: u64 = readU32(cd, p + 20); + var usize_: u64 = readU32(cd, p + 24); + const nlen: usize = readU16(cd, p + 28); + const xlen: usize = readU16(cd, p + 30); + const clen: usize = readU16(cd, p + 32); + var local: u64 = readU32(cd, p + 42); + if (cd.len - p - 46 < nlen + xlen + clen) return error.BadArchive; + const name = cd[p + 46 ..][0..nlen]; + var x = p + 46 + nlen; + const xend = x + xlen; + while (xend - x >= 4) { + const id = readU16(cd, x); + const len: usize = readU16(cd, x + 2); + if (xend - x - 4 < len) return error.BadArchive; + if (id == 0x0001) { + var f = x + 4; + const fend = f + len; + if (usize_ == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + usize_ = readU64(cd, f); + f += 8; + } + if (csize == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + csize = readU64(cd, f); + f += 8; + } + if (local == 0xFFFFFFFF) { + if (fend - f < 8) return error.BadArchive; + local = readU64(cd, f); + } + } + x += 4 + len; + } + if (method != 0 or csize != usize_) { + std.log.err("codec.pth member {s} is compressed; torch.save stores members", .{name}); + return error.CompressedMember; + } + if (local > size or usize_ > size - local) return error.BadArchive; + try members.put(a, name, .{ .local = local, .size = usize_, .crc = crc }); + p += 46 + nlen + xlen + clen; + } + return members; +} diff --git a/zig/src/families/drama3/wav.zig b/zig/src/core/wav.zig similarity index 100% rename from zig/src/families/drama3/wav.zig rename to zig/src/core/wav.zig diff --git a/zig/src/families/drama3/codec_load.zig b/zig/src/families/drama3/codec_load.zig index b636fbed1ea..c4f90b1a55d 100644 --- a/zig/src/families/drama3/codec_load.zig +++ b/zig/src/families/drama3/codec_load.zig @@ -1,7 +1,7 @@ //! One FP32 codec schema for prepared safetensors and the restricted native PTH reader. const std = @import("std"); const core = @import("core"); -const pth = @import("codec_pth.zig"); +const pth = @import("core").torch_pth; const mapping = @import("codec_map.zig"); const schema = @import("codec_schema.zig"); diff --git a/zig/src/families/drama3/codec_map.zig b/zig/src/families/drama3/codec_map.zig index d1a46a19766..5b9e1ef4851 100644 --- a/zig/src/families/drama3/codec_map.zig +++ b/zig/src/families/drama3/codec_map.zig @@ -1,6 +1,6 @@ //! The codec's tensors in native FP32 layouts, read from codec.pth; no FP16 decoder image is reused. const std = @import("std"); -const pth = @import("codec_pth.zig"); +const pth = @import("core").torch_pth; const A = std.mem.Allocator; const Reader = struct { diff --git a/zig/src/families/drama3/cuda/tts.zig b/zig/src/families/drama3/cuda/tts.zig index 6e511f9d42e..1769a333e02 100644 --- a/zig/src/families/drama3/cuda/tts.zig +++ b/zig/src/families/drama3/cuda/tts.zig @@ -4,7 +4,7 @@ const model = @import("../model.zig"); const cuda = @import("cuda"); const eng = @import("engine.zig"); const codec_ = @import("codec.zig"); -const wav = @import("../wav.zig"); +const wav = @import("core").wav; const cfg = @import("../config.zig"); const kern = @import("kernels.zig"); const completion = @import("../completion.zig"); diff --git a/zig/src/families/drama3/drama3.zig b/zig/src/families/drama3/drama3.zig index d929cb5b4af..91f22076e09 100644 --- a/zig/src/families/drama3/drama3.zig +++ b/zig/src/families/drama3/drama3.zig @@ -13,7 +13,7 @@ pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); pub const prompt = @import("prompt.zig"); pub const codec = @import("cuda/codec.zig"); -pub const wav = @import("wav.zig"); +pub const wav = @import("core").wav; pub const tts = @import("cuda/tts.zig"); pub const common = @import("common.zig"); pub const shards = @import("shards.zig"); @@ -36,7 +36,6 @@ test { _ = @import("codec_schema.zig"); _ = @import("cuda/stager.zig"); _ = @import("cuda/reference_rows.zig"); - _ = @import("codec_pth.zig"); _ = prompt; _ = wav; } diff --git a/zig/src/families/drama3/drama3_metal.zig b/zig/src/families/drama3/drama3_metal.zig index 444f17d7cd4..489ad30e00d 100644 --- a/zig/src/families/drama3/drama3_metal.zig +++ b/zig/src/families/drama3/drama3_metal.zig @@ -8,7 +8,7 @@ pub const codec_load = @import("codec_load.zig"); pub const replay = @import("replay.zig").Replay(@This()); pub const config = @import("config.zig"); pub const prompt = @import("prompt.zig"); -pub const wav = @import("wav.zig"); +pub const wav = @import("core").wav; pub const common = @import("common.zig"); pub const shards = @import("shards.zig"); pub const gpu = @import("metal/gpu.zig"); @@ -36,7 +36,6 @@ test { _ = reference_cache; _ = @import("codec_map.zig"); _ = @import("codec_schema.zig"); - _ = @import("codec_pth.zig"); _ = prompt; _ = wav; _ = kernels; diff --git a/zig/src/families/drama3/metal/tts.zig b/zig/src/families/drama3/metal/tts.zig index 014deea9d70..d9f64e09e59 100644 --- a/zig/src/families/drama3/metal/tts.zig +++ b/zig/src/families/drama3/metal/tts.zig @@ -3,7 +3,7 @@ const std = @import("std"); const model = @import("../model.zig"); const cfg = @import("../config.zig"); const common = @import("../common.zig"); -const wav = @import("../wav.zig"); +const wav = @import("core").wav; const gpu = @import("gpu.zig"); const eng = @import("engine.zig"); const codec_ = @import("codec.zig"); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index fb9f1b525cf..6da355cfc0b 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -4,6 +4,9 @@ const std = @import("std"); pub const startup_receipt = @import("profile").startup_receipt; pub const benchmark_group = @import("core/benchmark_group.zig"); pub const safetensors = @import("core/safetensors.zig"); +/// torch.save archives and WAV files: Drama 3's codec and clips, through its `core` shim. +pub const torch_pth = @import("core/torch_pth.zig"); +pub const wav = @import("core/wav.zig"); pub const gguf = @import("core/gguf.zig"); pub const Checkpoint = checkpoint_host.Checkpoint; pub const checkpoint_host = @import("core/checkpoint.zig");