Skip to content

Spark2.5 on Metal holds its stacked matrices once: spark-x2.6 loads at its size on disk, not 1.6x - #3379

Open
jschmied wants to merge 5 commits into
ashhart:mainfrom
jschmied:metal-weights-shared
Open

jschmied wants to merge 5 commits into
ashhart:mainfrom
jschmied:metal-weights-shared

Conversation

@jschmied

@jschmied jschmied commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Branch metal-weights-shared @ 47b7303 on main 33e716462 (ashhart's rebase c9a2a50 plus one CI fix: Gemma 4's host test roots give checkpoint_metal.zig its core): it moves #3350's
pattern into core and puts Gemma 4 and Spark2.5 on it.

Problem

Spark2.5's Metal load (metal_model.zig:60, addFile) kept every shard resident for the model's life. Then
metal_weights.stacked() copied q_k_v_proj+g_proj and gate_proj+up_proj into new buffers, and nothing
read the originals again. Measured on main with footprint, peak GPU memory against the safetensors bytes on disk:
1.58x for spark-x2.6-4b (bf16) and 1.69x for spark-x2.6-4b-4bit.

Change

Core (core/checkpoint_metal.zig), shared:

  • laterModules(comptime modules): a Later predicate for the layers' linears whose module name ends in one of
    modules, matching their weight, scales and biases.
  • Checkpoint.describe(name): dtype, shape and size of a tensor, kept or deferred. This was Gemma's private Src.meta.
  • Staged: a checkpoint read through a Stage. It is anything with get(name), so the existing duck-typed
    readers (mlx_affine.read, Spark's dense) take staged tensors unchanged.

Gemma 4 (no behaviour change): weights.later = laterModules(&.{"_proj"}), and Src = Staged. The 12B's
replies equal #3350's in every case below, at the same 7.0 GB of GPU memory.

Spark2.5 (family-only):

  • later = laterModules(.q_k_v_proj, .g_proj, .gate_proj, .up_proj) and addFileSplit(..., later).
  • Each stack reserves its members in a Stage and reads them through Staged; stacked() copies them once, then the
    stage resets. closeFiles() runs after load.
  • out_proj, down_proj, the embedding/tied head and the norms stay in the shards, read in place as before.
  • A host test pins which names are deferred.
  • The stacks' bytes are summed where each buffer is made (Weights.stacked_bytes), and the cache budget counts them
    as resident: budget.resident = shards + stacks + scratch. The load line names all three.

Evidence (M3 Pro 36 GB, no tensor units; base = #3350's head on main 4ddc28c)

Memory (peak footprint GPU / phys, load and a 200-token request):

checkpoint on disk base this ratio
spark-x2.6-4b (bf16) 8.22 GB 13 GB / 13 GB 8.24 GB / 8.71 GB 1.58 -> 1.00
spark-x2.6-4b-4bit 2.31 GB 3.92 GB / 4.39 GB 2.60 GB / 3.07 GB 1.69 -> 1.13

Replies equal base (token_sha256) on both checkpoints:

  • greedy and seeded (T=1, seed 7) at 8,406 and 28,645 prompt tokens;
  • a second turn resumed from the prompt cache equals the same turn on a fresh server;
  • 4 concurrent streams equal 1 at a time;
  • every A-B-B-A run gives one hash per prompt length.

Speed, A-B-B-A, 2 rounds, a fresh server per run, 128 greedy tokens:

base this change
bf16 TTFT 8K 16.50/16.49/16.51/16.50 s 16.49/16.51/16.50/16.50 0.00 %
bf16 decode 8K 15.26/15.53/15.57/15.55 tok/s 15.38/15.61/15.59/15.54 +0.35 %
bf16 TTFT 28.6K 66.44/66.42/66.44/66.48 s 66.57/66.39/66.38/66.37 -0.03 %
bf16 decode 28.6K 14.23/14.26/14.29/14.11 14.26/14.29/14.28/14.20 +0.24 %
4-bit TTFT 8K 18.77/18.78/18.78/18.79 s 18.79/18.77/18.77/18.76 -0.04 %
4-bit decode 8K 44.90/45.49/45.31/45.31 45.51/45.45/45.53/45.02 +0.28 %
4-bit TTFT 28.6K 74.26/74.15/74.27/74.24 s 74.28/74.13/74.19/74.42 +0.03 %
4-bit decode 28.6K 35.89/35.49/35.75/35.75 35.53/35.82/35.37/35.51 -0.46 %
load 6.0-8.0 s 6.0-8.0 s level

Settled: the cell is level on a quiet machine (6 more A-B-B-A rounds on this head: paired median +0.02 %, 5 of 12 slower, spread 0.4 tok/s; see the comment below). On the busy machine it read as slower: 4-bit decode at 28.6K. Over 6 A-B-B-A rounds (12 pairs), the paired median is -0.44 % (mean -0.59 %), with 7 of 12 pairs slower and one reply hash throughout. Paired deltas: -1.02 +0.93 -1.07 -0.68 -0.92 +0.12 -2.23 +0.63 -3.84 +1.13 -0.21 +0.10 %. The pairs show a position effect: (A1,B1) is slower 6 of 6, and (B2,A2) is faster 5 of 6.

Isolation: the stacked buffers are allocated as before (device.buffer). The only thing that moves is the in-place tensors' offsets (256-aligned in the packed buffer instead of file offsets). A variant with identical code but every tensor loaded in place, A-B-B-A against this head (4 rounds), is level on means (35.23 vs 35.19 tok/s, -0.1 %; paired median -0.67 %, 5 of 8), within this Mac's +/-6 % single-run spread. We found no mechanism. The quiet-machine rerun is in the comments. If you run your device check, this cell is the one to look at.

Checks:

  • zig build test exit 0, including the new laterModules and Spark later host tests.
  • lean 0 new; zig fmt clean; all files 600 lines or fewer. No kernel changes.

Core vs family

  • core: laterModules, Checkpoint.describe, Staged
  • gemma4: uses them (refactor)
  • spark25: later, reserve, staged stacking, closeFiles

Flint has the same pattern (stacked() of qkv and gate|up) but is not changed here: there is no Flint checkpoint
that fits a 36 GB Mac to verify it on. It waits for a tester.

x86 CI (Linux, -Dfixed-cpu full set on 03e5d75): 732/735 steps, 9,887 of 9,967 tests pass. The one failure is cli_config_test, the same as on main on that box (see #3350). tools/pr_check.py: lean 341 vs 341, 0 new.

No refusal test: nothing new is refused. Speed and memory are measured against #3350's head (main plus #3350), not against main alone: this PR stacks on it.

Proposed CHANGELOG line

  • Spark2.5 on Metal keeps one copy of its stacked attention and MLP matrices. spark-x2.6-4b now needs about its
    size on disk in GPU memory (8.2 GB, down from 13). Replies and speed are unchanged.

47b7303 (CI fix, Synthena 12-03): zig/zig-b failed at checkpoint_metal.zig:6:28: no module named 'core' in test-gemma4-owners-host, -affine-host and -prompt-head-host: Gemma's later now calls checkpoint_metal.laterModules, which pulls that file's tests (and its core reference) into those roots. Each root now re-exports safetensors and checkpoint_file_cache and is its own core, as the residency owners root does. x86 targeted on b546bab57 (47b7303 changes only three build-file comments): 73/73 steps, 898/930 tests (32 skipped), check-native-cuda-host compile-cuda-tests 21/21, pr_check/fmt/lean 0 new. aarch64-macos -Dcpu=apple_m1 cross-build of tf-spark-run compiles; only the link stops (no macOS SDK here). No device run this round (our Mac is offline).

64508cc (review fix, ashhart 11-28): the stacked buffers left the shards, so residentBytes() stopped counting them and the budget handed their memory to the caches. metal_weights.stacked() now adds each stack buffer's size to Weights.stacked_bytes; metal_budget.resident(model) = shards + stacks + scratch, and native/spark25.zig passes it to caches(). No new allocation; no Gemma 4 file changes, so its numbers stay as they were. New step test-spark25-budget-metal-host. Mac (M3 Pro, -Dcpu=apple_m1, native md5 78cd070b, old c4e0bc9 f53a061b):

  • host test metal_budget.zig "the stacked matrices count as resident...": 61/61 with test-spark25-host. Planted control (old accounting, + stacked_bytes dropped): red at metal_budget.zig:63, expected 2021077184, found 1484206272.
  • load line, spark-x2.6-4b-4bit, --context 4096, default limit: c4e0bc9 23.7 GiB for caches; 64508cc resident 2.726 GB (shards 0.932, stacks 1.384, scratch 0.410), 22.5 GiB for caches (1.29 GiB less = the stacks).
  • SPARK_LOAD_LIMIT_GB=4.181484 (shards + scratch + 2 GiB margin + half the stacks): c4e0bc9 loads with 0.6 GiB of caches; 64508cc refuses the load ("--context 4096: this Mac's Spark2.5 caches fit 0 tokens under its load limit").
  • x86 (Linux, full set) on 64508cc: -Dfixed-cpu test-host, test, golden, kernel-contract, security, fuzz, release paths: 2314/2314 steps, 22598 tests pass (166 skipped); check-native-cuda-host compile-cuda-tests 17/17; pr_check, fmt, lean 0 new.

c4e0bc9 (rebase onto main 99d2384 after #3350 landed): only this PR's two commits remain; range-diff = against a9ec9da's pair except gemma4/weights.zig, where #3350 landed its own host-memory Stage: Gemma's Src stays on that local Stage and the three sizing calls read r.c.describe(...) (the resolution AIFlowML described). Mac (M3 Pro, -Dcpu=apple_m1): native build ok; focused steps (staged copies, gemma4 load-parts/shared/contract, checkpoint consumers/identity, step5, test-spark25-host) 241/241 tests; tf-kernel-contract 'metal gemma4 gate|up split rows' 1 pass, wrong-layout control red. Memory, main 99d2384 -> c4e0bc9 (peak, load + 200-token request): BF16 spark-x2.6-4b (8.22 GB on disk) GPU 13.0 -> 8.237 GB, 4-bit (2.31 GB) GPU 3.92 -> 2.603 GB, the same as the rows above. The one red step, test-gemma4-owners-host, is main's own: core/row_projection.zig:209/:212 (3bb1cef, #3854) needs a pointer id that the Gemma inert-Metal fake does not have; it fails the same on main 99d2384. GB10 Linux on c4e0bc9: test-host-ci-linux-{fast,host,compile}, zig rc=0.

a9ec9da (CI fix): the Linux zig job failed to compile core/checkpoint_metal.zig's two device tests (:397, :427) against the host-stub Metal modules that _ = weights; now pulls in (Device has no init there). Both tests now open with if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest;, the guard gemma4/weights.zig's load test already uses. No other change; the speed and memory rows above are on 03e5d75 and the served path is the same code. GitHub CI on a9ec9da: zig, zig-windows, pytest, fmt pass. x86 full set on a9ec9da: the only failure is cli_config_test, as on main on that box. Mac suite 853/853 steps.

@jschmied

Copy link
Copy Markdown
Contributor Author

The quiet-machine rerun of the one open cell, 4-bit decode at 28.6K, is in. It's level, so the -0.44 % in the description was noise from a busy machine.

Same head 03e5d7538 against main 4ddc28cfc (the description's base), on the same M3 Pro, 01:00-01:33 with nothing else running. The 1-minute load average was 0.98-2.41, logged per run. 6 A-B-B-A rounds, a fresh server per run, 128 greedy tokens, prompt 28,645 tokens.

round A B B A
20 35.81 35.85 35.85 35.84
21 35.82 35.81 35.86 35.84
22 35.63 35.47 35.68 35.68
23 35.76 35.68 35.59 35.68
24 35.67 35.74 35.76 35.73
25 35.72 35.81 35.83 35.85
  • Decode: paired median +0.02 %, PR slower in 5 of 12 pairs. Means 35.750 (main) vs 35.744 tok/s (-0.02 %).
  • TTFT: paired median +0.003 %, 74.07-74.18 s in both arms.
  • Tokens: token_sha256 9a1ca4ef9503869b in all 24 runs.
  • Run-to-run spread: 0.4 tok/s, against about ±6 % on the busy machine, where the earlier pairs also showed the position effect.

No cell is slower now, so I'm withdrawing the description's "shouldn't land until it is settled". I'll update the description to match.

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

DEVICE. @jschmied, the ownership and stage-reset paths look sound. Native builds, all four Spark runtime libraries and the two new selector cases pass, with no new lean findings.

We will run the device check on our side with the same checkpoint: full reply and raw-logit equality for both stored formats, plus loaded allocation, checkpoint residency and peak footprint measured separately. The reported memory saving still needs that receipt. Green zig, zig-windows, pytest and fmt CI at this head is also needed before landing.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart CI is green on a9ec9da (zig, zig-windows, pytest, fmt). The Linux zig job failed because _ = weights; pulled core/checkpoint_metal.zig's two device tests into the host-stub builds, where the Metal Device has no init. Both tests now skip there with the same comptime guard gemma4/weights.zig uses; nothing else changed, so the served path is the code your device check will run. Body updated to the new head.

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

@jschmied DEVICE. The Spark load-memory and exact-token check is still unchecked because its checkpoint is not placed on our test Mac. The new head only adds the two host Metal stand-in guards; it leaves the device test bodies unchanged.

The PR’s zig, zig-windows, pytest and fmt results at this head are also unknown in the supplied evidence.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

@jschmied, to settle the note above: CI is green at this head (zig, zig-windows, pytest and fmt), and the new commits only add the two host Metal stand-in guards, so the device code is the version you measured. The Spark x2.6 checkpoints are gated where we fetch from, so we can't rerun the load on our Mac. Your receipts carry the device side: peak GPU memory on main was 1.58x (bf16) and 1.69x (4-bit) the checkpoint's size on disk, this head loads at its size on disk, and replies are equal. This is stacked on #3350, so it lands right after #3350 does.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied. LAND after #3350. The full layout contract and runner registration are now reviewed, including the wrong-layout control and byte comparison with the interleaved path. The ownership paths look sound. The accepted device receipts and green CI still apply; the BF16 memory result is about 8.2 GB, while the 4-bit result is about 1.13 times its disk size.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

I ran the staged-load tests and test-spark25-host at a9ec9da55 on M5 Max with Zig 0.17.0. The filtered build passed 72 tests. On a Linux Metal stand-in I also selected the three checkpoint cases directly: the two guarded device cases skipped, and the laterModules case passed.

The branch trial-merges into 124052c97 by itself. Applying #3350's current 827e99242 first exposes one conflict in gemma4/weights.zig. Taking const Src = ckpt.Staged gives a type error because #3350 now uses its own host-memory Stage, while ckpt.Staged takes the shared Metal-buffer stage. In a scratch merge I kept Gemma's Src pointed at its local Stage and changed the three sizing calls from r.meta(...) to r.c.describe(...). The native build and 66 focused tests then passed on the combined tree.

On both the PR head and the resolved stack, zig build tf-kernel-contract -Dcpu=apple_m1 and ./zig-out/bin/tf-kernel-contract --only 'metal gemma4 gate|up split rows' --no-limits gave 11 bit-equal shapes and caught the wrong-layout control. This run used synthetic inputs.

Igor Lessio - AIFLOW LABS

@jschmied
jschmied force-pushed the metal-weights-shared branch from a9ec9da to c4e0bc9 Compare November 21, 2026 07:25
@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart #3350 is on main, so this PR is rebased onto main 99d23848c. The new head is c4e0bc9ce, with only this PR's two commits left.

The body names the new head.

@AIFlowML

Copy link
Copy Markdown
Contributor

I checked the rebased c4e0bc9ce on main 2ce240cf0, which contains the landed #3350. #3379 merges cleanly, and adding #3420 at 25466d5da also merges cleanly. Adding #4435 at f953d4f23 has one conflict in core/checkpoint_metal.zig: both branches append a test at the same location. Keeping both tests resolves it with no manual production-code changes.

On M5 Max (macOS 27.2, Zig 0.17.0), test-spark25-host test-gemma4-load-parts-host test-lfm3-host test-step5-host plus a scratch filter on the existing staged-checkpoint, text-only shard and sparse-read fixtures completed 72/72 steps with all 135 tests passing. tf-kernel-contract --only 'gemma4 gate|up split rows' passed the kernel, caught the wrong-layout control, and reported zero limit problems.

This checks the current loader changes together. Full-checkpoint memory numbers are from the author’s measurements.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied for reducing Spark2.5's resident checkpoint copies and sharing the checkpoint helpers with Gemma 4.

I found one memory-accounting issue. The new persistent stacked-weight buffers are no longer included in checkpoint resident bytes, but the cache-budget calculation still counts only checkpoint bytes plus scratch. It therefore gives the cache memory already occupied by the stacked weights, allowing both the default budget and an explicit load limit to be exceeded. Please include every persistent stacked-weight buffer in the resident-memory total used for that budget.

The tensor copies preserve the stored bytes and their ownership looks sound; this finding is limited to the missing memory accounting.

  • Synthena

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Fixed in 64508cc0e: the stacked buffers now count as resident in the cache budget. Not rebased.

  • Change: stacked() adds each stack buffer's size to Weights.stacked_bytes once, where the buffer is made.
    budget.resident(model) is shards + stacks + scratch, and the Spark2.5 load passes it to caches(). No new
    allocations. No Gemma 4 file changed, so its numbers are unchanged.
  • Host test (metal_budget.zig, step test-spark25-budget-metal-host): checks that resident counts the stacks,
    that the default budget drops by exactly their size, and that a limit with room for shards + scratch + one token,
    but not the stacks, leaves no caches. The planted old accounting goes red at metal_budget.zig:63
    (expected 2021077184, found 1484206272).
  • Mac (M3 Pro), spark-x2.6-4b-4bit, --context 4096:
    • default limit: 23.7 -> 22.5 GiB for caches. The new load line reads resident 2.726 GB (shards 0.932, stacks 1.384, scratch 0.410).
    • SPARK_LOAD_LIMIT_GB=4.181484 (half the stacks over): c4e0bc9 loads with 0.6 GiB of caches, the new head
      refuses with "caches fit 0 tokens under its load limit".
  • x86 full set: -Dfixed-cpu test-host, test, golden, kernel-contract, security, fuzz, release paths: 2314/2314 steps, 22598 tests pass (166 skipped); check-native-cuda-host compile-cuda-tests 17/17; pr_check, fmt, lean 0 new.

The body names the new head.

@ashhart
ashhart force-pushed the metal-weights-shared branch from 64508cc to c9a2a50 Compare November 30, 2026 11:49
@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Thanks for the memory-accounting fix, which closes the review's one issue.

Decision: ready for our review and device run, which is ours - an M3/M4-class Mac with Spark2.5, checking the memory ratios (1.00x bf16, 1.13x 4-bit against disk) and the load-line accounting against your posted M3 Pro numbers. The run is ours, not yours. Your host test (metal_budget.zig) covers the accounting, and the planted old accounting goes red as it should.

The not-rebased state and the changelog line are ours too.

  • Synthena

@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Performance receipt required (kind:perf)

Moves the deferred-load pattern into core checkpoint_metal and applies it to Spark2.5's Metal path so stacked matrices are read once from shards instead of duplicating resident buffers, cutting peak GPU memory from 1.58x/1.69x to ~1.0x/1.13x of checkpoint size on disk.

  • Failing CI check(s): zig, zig-b.
  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [BLOCKER] zig/src/families/spark25/metal_weights.zig: The affine stack's byte accounting adds b_at (the offset where biases start) plus totalgroups2, but the buffer also holds the scales region between weights and biases; the sum appears to undercount the actual buffer size (weights + scales + biases), so the cache budget under-reserves memory and the load line understates stacks. Suggested fix: Compute the buffer's true size (e.g. the offset after biases, or w_at + s_at + b_at regions as allocated) and add that to stacked_bytes; add a host test asserting stacked_bytes equals the sum of the appended buffer lengths.
  • [WARNING] zig/src/families/spark25/metal_model.zig: closeFiles() is called unconditionally after weights.load, but if load fails mid-way the errdefer path may leave file descriptors open or, worse, close files while deferred tensors are still referenced by an in-flight Stage; the ordering with errdefer m.weights.deinit(gpa) is not shown to be safe on the error path. Suggested fix: Confirm closeFiles() is safe when weights.load returns an error (deferred tensors must not be read afterwards), or move it behind a success-only path / tie it to the checkpoint's own deinit.
  • [WARNING] zig/src/core/checkpoint_metal.zig: describe() returns file=0/at=0 for kept tensors, which is fine for metadata-only callers, but any caller that treats the returned Deferred as a readable file location for a kept tensor would read from offset 0 of file 0; the API does not distinguish 'kept' from 'deferred' in the returned struct. Suggested fix: Document that describe() is metadata-only, or add a kept flag to Deferred so callers cannot mistake a kept tensor for a file-backed one.
  • Synthena

@jschmied

jschmied commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

New head 47b730389: your rebase c9a2a50f4 plus one commit that fixes the red zig and zig-b jobs. Not rebased.

CI (run 46412884663): the failure is ours. All four failed steps (test-gemma4-owners-host, -affine-host, -prompt-head-host in zig; owners in zig-b) stop at checkpoint_metal.zig:6:28: no module named 'core'. Gemma's later (gemma4/weights.zig:134) now calls checkpoint_metal.laterModules, so weights.zig's later: test pulls checkpoint_metal.zig into those three host roots. That brings in its tests, and its test { _ = file_cache; } reaches core, which these roots never had. In 47b730389 each of the three roots re-exports safetensors and checkpoint_file_cache and is its own core (zig/build/gemma4_host.zig), like the residency owners root does. x86 (-Dfixed-cpu, targeted, on b546bab57, which differs only in three build-file comments): 20 targeted steps incl. the three Gemma roots and test-spark25-host, 73/73 steps, 898 of 930 tests pass (32 skipped); check-native-cuda-host compile-cuda-tests 21/21; pr_check, fmt, lean 0 new.

[BLOCKER] affine stack bytes: I checked it, and the count is right. metal_weights.zig:132-134 places the scales at s_at, after the words, and the biases at b_at = alignForward(s_at + total*groups*2, 256), after the scales. The buffer is b_at + total*groups*2 bytes (:134), and :148 adds the same expression. b_at already includes the words and the scales region, so stacked_bytes is exactly the allocated length.

[WARNING] closeFiles() after a failed load: weights.load is a try (metal_model.zig:62). If it fails, :63 never runs. The errdefer m.checkpoint.deinit() from :57 runs instead, and deinit calls closeFiles (checkpoint_metal.zig:268-269), which sets every fd to -1 (:198-204), so each fd is closed once. The Stage belongs to load (metal_weights.zig:181-182, defer stage.deinit()), so none is still alive by the time :63 runs. A deferred read after the close returns error.ShardClosed (checkpoint_metal.zig:184), not bytes from offset 0.

[WARNING] describe() with file 0/at 0 for kept tensors: it only returns metadata. Its only callers are Gemma's sizing and shape checks (gemma4/weights.zig:232-233, 254, 264-266, 291), and they read bytes, shape, dtype and rank. Nothing reads a file through it. Checkpoint.read (:180-185) and Stage.read (:329-330) look the name up in deferred again. A kept name is either refused there (MissingTensor) or, in Stage.read, served from the shard. No change.

Mac: our Mac is offline, so this round has no device run. It is the aarch64-macos -Dcpu=apple_m1 cross-build of tf-spark-run (Zig analysis and codegen clean; only the link stops, on the missing macOS SDK frameworks) plus the host tests above. The device check stays with your Mac run, as you planned on 12-02.

Receipt: the claim is resident memory at load, not speed. tools/perf_receipt.py can't run Metal on this box, and the memory ratios are what your M3/M4 device run checks.

@ashhart ashhart added synthena:needs-ash Needs owner decision and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Needs maintainer review (kind:perf)

Moves the deferred-load pattern into core checkpoint_metal and applies it to Spark2.5's Metal path so stacked matrices are read once from shards instead of duplicating resident buffers, cutting peak GPU memory from 1.58x/1.69x to ~1.0x/1.13x of checkpoint size on disk.

  • Failing CI check(s): verify.

Findings:

  • [WARNING] zig/src/families/spark25/metal_model.zig: closeFiles() runs unconditionally after load, but if weights.load returns an error the errdefer path may leave shard file descriptors open or close files while a Stage still references deferred tensors; the error-path ordering is not shown to be safe. Suggested fix: Confirm closeFiles() is safe when weights.load fails (no deferred tensor is read afterwards), or move it behind a success-only path and tie it to the errdefer cleanup.
  • [WARNING] zig/src/core/checkpoint_metal.zig: describe() returns a Deferred with file=0/at=0 for kept tensors, which is only valid because callers use it for metadata only; if any future caller treats it as a readable location it will read from the wrong place. Suggested fix: Document that describe() is metadata-only (file/at are placeholders) or return a dedicated metadata type so it cannot be mistaken for a readable location.
  • Synthena

@jschmied

jschmied commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

This re-review is on the same head, 47b730389, and came 16 minutes after my reply above. That reply already answers both warnings. No change.

  • closeFiles() after a failed weights.load: :63 runs only if load succeeds, because load is a try (metal_model.zig:62). If load fails, the errdefer m.checkpoint.deinit() from :57 closes the files (checkpoint_metal.zig:268-269). closeFiles sets each fd to -1 (:198-204), so calling it again from a later errdefer does nothing. The only Stage is local to load (metal_weights.zig:181-182, defer stage.deinit()), so it is gone before either close. A read after the close returns error.ShardClosed (checkpoint_metal.zig:183-184, tested at :479). Gemma's load test checks exactly that (gemma4/weights.zig:575-576).
  • describe() placeholders: callers only read its metadata (gemma4/weights.zig:232-233, 254, 264-266, 291). Reads look the name up in deferred again (checkpoint_metal.zig:180-185).
  • Red verify: the job wants a tf-receipt-v1 JSON for the kind:perf label. The claim is Metal resident memory at load, which tools/perf_receipt.py can't measure on this box. The body's M3 Pro rows (BF16 13.0 -> 8.237 GB, 4-bit 3.92 -> 2.603 GB) and your planned M3/M4 run cover it.

@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thanks, @jschmied. The byte accounting is right — the bias offset already includes the words and the scales region, so the stacked total is the allocated length — and the two warnings are answered: the close runs only on success with the error path closing through the checkpoint's own deinit and every descriptor set to −1, and the describe call is metadata-only with its callers reading the shape fields, never a file location. The CI failure was the build roots missing the module, fixed in the three host roots.

The claim is resident memory at load, so the receipt gate does not apply the way a speed claim's does; the memory ratios are what the device run checks. That run is ours as planned — the load ratios measured against resident memory on the M3 and M4 — and we will post the results here.

  • Synthena

jschmied and others added 5 commits December 5, 2026 07:21
…rs Gemma 4 now shares

Spark2.5's load kept every shard resident and copied q_k_v_proj+g_proj and gate_proj+up_proj into stacks, so
spark-x2.6 took 1.6x its size on disk.
- core/checkpoint_metal.zig gains laterModules (a Later for the layers' linears by module name),
  Checkpoint.describe (a kept or deferred tensor's dtype and shape) and Staged (a checkpoint read through a Stage,
  for any reader that takes get(name)).
- Gemma 4's load uses laterModules and describe, with no change in behaviour; it keeps its own host-memory
  Stage (ashhart#3350), so Staged serves Spark2.5.
- Spark2.5 leaves the stacked members in their files, stages them for stacked(), and closes the files after load.
  out, down, the embedding and the norms stay in place. spark-x2.6-4b now takes 8.2 GB of GPU memory, not 13.
…st targets' Metal stand-ins

Gemma 4's and Spark2.5's test blocks now reach weights.zig, which uses checkpoint_metal, so the host-stub test
modules (gemma4_recording_metal, gemma4_inert_metal, gemma4_head_metal) compiled its device tests against a Device
with no init. They take the same comptime guard gemma4/weights.zig's load test has.
…sident

The stacked q|k|v|gate and gate|up buffers moved out of the shards, so checkpoint residentBytes no longer
held them, and the cache budget (shards plus scratch) handed their memory to the caches: both the default
share and SPARK_LOAD_LIMIT_GB could be exceeded. Weights now sums each stack's bytes where its buffer is
made, budget.resident adds them, and the load line names shards, stacks and scratch.
gemma4/weights.zig's `later` now calls checkpoint_metal's laterModules, so the owners, affine and
prompt-head host roots compile that file's tests, whose file_cache reference reaches `core`.
Each root re-exports safetensors and checkpoint_file_cache and is its own `core`, as residency's owners root does.
@ashhart
ashhart force-pushed the metal-weights-shared branch from 47b7303 to 8a452ca Compare December 5, 2026 07:25

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:perf Classified by Synthena as performance improvement synthena:needs-ash Needs owner decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants