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 2 commits into
ashhart:mainfrom
jschmied:metal-weights-shared
Open

jschmied wants to merge 2 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 @ c4e0bc9 on main 99d23848c (rebased from a9ec9da now that #3350 has landed; #3350's commits are main's, only this PR's two remain): 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.

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.

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

…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.
@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

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants