Skip to content

Gemma 4 on Metal holds each linear's bytes once: the 31B 4-bit loads in 17 GB of GPU memory, not 48 - #3350

Merged
ashhart merged 5 commits into
ashhart:mainfrom
jschmied:gemma4-metal-weights
Nov 21, 2026
Merged

ashhart merged 5 commits into
ashhart:mainfrom
jschmied:gemma4-metal-weights

Conversation

@jschmied

@jschmied jschmied commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Branch gemma4-metal-weights @ 827e992, on main 4ddc28c. 827e992424 stages each linear in host memory during load, so the load makes main's Metal allocations in main's order (review 6911938544, section below). 1c40496985 keeps the default prompt-cache budget at main's value (review 6906645673, below). b3bfd3ae7 added the compile-time skip of the device-backed load test on host Metal stand-ins (review 6879475998). The memory and exactness numbers below were measured on 2fb135acb, whose weight code is otherwise identical.

Problem

Gemma 4's Metal load kept three copies of every linear.

  • Every checkpoint shard stayed in a shared Metal buffer for the model's life, because the norms point into it.
  • weights.stack/pack copied each linear into a lane pack (tensor units) or a row pack (no tensor units).
  • weights.mlxCopy copied it a third time for prompt chunks (l.mlx, read by core/affine_mm).

On the 31B 4-bit that is 16.97 + 16.08 + 15.34 = 48.4 GiB. footprint measured 48 GB of IOAccelerator memory and
50 GB phys on main. On a 36 GB M3 Pro (wired limit 29.5 GB) the first forward fails with
kIOGPUCommandBufferCallbackErrorOutOfMemory, at any context.

Change

It is exact by construction: the same bytes, held once.

  • Linears stay in their files. The checkpoint is read with addFileSplit(..., weights.later), the pattern
    qwen27 already uses (gpu_weights.repacked + Stage). The layers' *_proj.{weight,scales,biases} stay in
    their files. stack/pack/mlxCopy read them once through a Stage, and closeFiles() runs after load.
  • What stays in the shards: embed_tokens.{weight,scales,biases} (gemma_embed reads it), the final norm,
    every layer's six norms, and layer_scalar. That is 0.74 GiB on the 31B.
  • No tensor units: the row pack holds the checkpoint's arrays as stored, so l.mlx becomes views of its row
    ranges (mlxAlias/mlxStack) and there is no third copy. For each member to be one row range, gate|up packs
    gate rows, then up's (geglu's split mode, IL = 0) instead of alternate 16-row blocks.
  • Tensor units: the lane layout differs from MLX's, so these Macs keep the 16-row interleave and the MLX
    copy; only the shards go. The split is weights.interleaves(tensor_units, runs), host-tested.
  • A read of a freed linear is refused by name. ref/get on a linear after load fails with DeferredTensor,
    and a staged read after closeFiles fails with ShardClosed. The host test plants such a pointer and shows
    both refusals.

Evidence (M3 Pro, 36 GB, no tensor units)

Memory: peak footprint during load and serve

main GPU / phys this GPU / phys
31B 4-bit, 8K 48 GB / 50 GB, swaps, then OOM at the first forward 17 GB / 20 GB; serves 3 streams at 8K, 6.1 tok/s
12B 4-bit, 32K, 4 streams 18 GB / 22 GB 7.0 GB / 11 GB

At --parallel 4 --prompt-cache-gib 2, main refuses to start the 12B because it would pass 70 % of RAM (19.2 GiB
held). This branch starts it.

Replies on the 12B 4-bit equal main. Every token_sha256 matches:

  • greedy and seeded (T=1, seed 7), at 8,624 and 29,688 prompt tokens;
  • a second turn resumed from the prompt cache equals the same turn on a fresh server, on both builds;
  • four concurrent streams equal the same four prompts one at a time;
  • all 16 A-B-B-A runs give one hash for each prompt length.

Speed: 12B, cold prompt and decode, A-B-B-A, 2 rounds, a fresh server per run, 128 greedy tokens

main this change
TTFT 8,624 tokens 49.86 / 49.97 / 50.52 / 49.93 s 47.85 / 47.83 / 47.85 / 47.83 s −4.5 %
TTFT 29,688 tokens 193.2 / 193.8 / 192.2 / 192.6 s 185.3 / 185.2 / 185.2 / 185.4 s −4.0 %
decode at 8K 13.91 / 13.84 / 13.89 / 13.90 tok/s 13.86 / 13.91 / 13.86 / 13.87 −0.08 % (within spread)
decode at 32K 12.98 / 12.89 / 13.00 / 13.03 tok/s 12.98 / 12.90 / 13.03 / 12.89 −0.19 % (within spread)
load 14–18 s 12.0 s −17 to −20 %

No cell is slower beyond run-to-run spread. Decode is level: both builds span 12.89–13.03 tok/s at 32K. Prompts
are faster, and so is load (one staged copy instead of whole shards plus two copies).

The kernel path change (row path), checked bit for bit. tf-kernel-contract --only "gate|up": split gate|up +
gemma_geglu (IL = 0) against the interleaved pack + IL = 1 it replaces, on the same simd_qmm call (n = 2I).

  • 11 shapes bit-equal, including the 31B's decode and 16-row chunk (I = 21504, hidden 5376) and the 12B's decode.
  • nonfinite and repeat gates pass.
  • The planted control (split rows read as interleaved) goes red.

Unchanged:

  • tf-kernel-contract --only gemma4: 37 kernels pass gates 1-4, 7/7 controls red. No .metal file changes.
  • zig build test exit 0, with the new host tests: later's names, the interleave split, aliases equal to copies,
    and the planted stale pointer refused.
  • lean 0 new; zig fmt clean; all files ≤600 lines.

x86 CI (Linux build + host tests on 2fb135a): 732/735 steps, 9,886 of 9,967 tests pass. The one failure is cli_config_test (serve --config: expand reads the file...). It fails the same way on main 4ddc28cfc on the same box, and this PR touches no server code. tools/pr_check.py: lean 341 vs 341, 0 new; zig fmt --check clean.

Not run here: a tensor-unit Mac (M5). Its path keeps the lane pack, the interleave and the MLX copy unchanged; only
where the bytes are read from moves (Stage instead of the kept shard).

Proposed CHANGELOG line (not committed)

  • Gemma 4 on Metal holds each linear's weights once instead of three times. The 31B 4-bit now loads in about 17 GB
    of GPU memory, down from 48, and serves on 36 GB Macs; the 12B takes 7 GB, down from 18. Prompts are about
    4 % faster and loads about 20 % faster on Macs without tensor units; replies are unchanged.

Default prompt-cache budget (1c40496)

The default budget is half the free room, with a 16 GiB floor. Freeing the weights' copies raised it: on the 31B, 59.4 → 67.6 GiB on the M5 Ultra. ashhart's M5 run measured the greedy thinking-on four-request span 2.15 % longer at those defaults (equal budgets overlapped), and a slower default cell does not land.

  • Model.released() is the shard span main kept resident (Checkpoint.selected_bytes, what addFileSelected held) minus what this branch keeps, plus the MLX copies the row path now aliases (Weights.aliased).
  • enableCache adds it to the reserve for the default only, so the default equals main's for the same checkpoint and Mac. An explicit --prompt-cache-gib is unchanged. The memory itself stays free.
  • Host test: the default with the released bytes added back equals main's formula, and an explicit budget is unchanged. Planted controls: released ×0 → red (expected 2004318027, found 14173392032); selected_bytes not added → 2 red.
  • Checks on the M3 Pro: zig build test 853/853, test-native green, 9 test-gemma4-*-host steps native and -Dfixed-cpu, lean 0 new, fmt clean.
  • 12B startup budget, main vs this head: both log 1.4 GiB from 1.4 GiB free. Ready footprint 20.3–20.6 GB → 7.99 GB; peak GPU 18.0 → 7.0 GB (unchanged by this commit).

Speed at defaults (M3 Pro, 12B 4-bit, --parallel 4, ctx 16384, main 4ddc28cfc vs 1c40496985, A-B-B-A ×3, a fresh server per run, wall clock = first send to last reply):

cell main, median [range] head change
thinking-on T=0 ×4, wall 49.93 [49.00–50.20] tok/s 50.01 [49.44–50.12] +0.2 %, overlapping
thinking-on T=0 ×4, decode-only 50.86 [49.73–52.21] 52.79 [50.00–53.06] +3.8 %, overlapping
  • No pressure line in any of the 12 runs; queue waits ~0.94 s on both. Replies: one sha set per cell.
  • Sampled ×4 is bimodal on both builds, set by the startup budget (1.1–1.4 GiB, footprint noise run to run): the warm-up's four states (~1.3 GB) fit or not. Within a mode the builds are equal (fast 39.5–40.6 vs 40.1–40.4 tok/s; slow 21.7–21.8 vs 21.95–22.1). An A/A block (main vs main) spans the same modes.

Load stage in host memory (827e992)

Review 6911938544 located a longer prompt cb.wait on the M5 12B default cell. Nothing here changes how prompt command buffers are committed or waited on. The one load difference was ckpt.Stage, a Metal buffer that grew twice in layer 0 and left freed holes for later buffers. 827e992424 moves it to host memory (weights.Stage, weights.zig only); bytes and kernels are unchanged.

On an M3 Pro (12B 4-bit, defaults, --parallel 4, ctx 16384):

  • zig build test 853/853 steps, test-native 63/63, lean 0 new, zig fmt clean, weights.zig 591 lines.
  • Replies 1c40496985 vs 827e992424: greedy, seeded (T=1, seed 7+i) and thinking-on T=0, 4 prompts one at a time and 4 at once: 24/24 token_sha256 equal, 1 stream == 4 streams.
  • Prompt-chunk timing, main 4ddc28cfc / 1c40496985 / 827e992424, A-B-C-C-B-A ×2, fresh servers, sums over 4 thinking-on prompts, medians of 4 runs: GPU span 1206.7 / 1207.0 / 1206.5 ms; wait minus GPU span 64.1 / 37.5 / 38.3 ms (ranges overlap between the last two). The M3 row path doesn't show the M5's added wait, so it can't confirm the fix; the M5 cell decides.

@ashhart

ashhart commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@jschmied FIXES. The staged ownership and row aliases look consistent, but the new device-backed test at zig/src/families/gemma4/weights.zig:479 breaks three host targets: test-gemma4-owners-host, test-gemma4-affine-host and test-gemma4-prompt-head-host. Their Metal stand-ins have no Device.init, so the runtime catch cannot make them skip. All three pass on the base.

Please add a compile-time dependency guard or move that case to the device tests, keeping its staging and alias assertions. We will run the memory and exact-token device checks on our side after that fix. The one-pack memory claim applies to the path without tensor units; the tensor-unit path still keeps separate lane and prompt packs.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. Fixed in b3bfd3ae7: the load test at zig/src/families/gemma4/weights.zig:479 now starts with if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest;, the guard affine_mm.zig:138 and metal_kv_pages_test.zig already use. Its staging and alias assertions are unchanged and still run on real Metal.

  • test-gemma4-owners-host, test-gemma4-affine-host and test-gemma4-prompt-head-host pass on b3bfd3ae7, on the M3 Pro and on x86 (-Dfixed-cpu).
  • Agreed on scope: one pack holds only on Macs without tensor units. On tensor-unit Macs only the kept shards go; the lane pack and the prompt pack stay separate. The description says so.

@ashhart

ashhart commented Nov 14, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied. DEVICE. The compile-time guard fixes all three host targets: 534 tests pass and 10 skip. The staging and alias assertions are unchanged, lean has zero new findings, and every changed file is under 600 lines.

We have queued the memory and exact-token device checks on our side. We will report the tensor-unit control separately from the 31B memory claim on the path without tensor units.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

@jschmied DEVICE. The 31B memory and exact-token check is still unchecked because that checkpoint is not placed on our test Mac. Our completed 12B check retained identical full replies and raw artifacts, but it does not qualify 31B.

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

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart CI is green at this head (b3bfd3a): zig, zig-windows, pytest and fmt pass.

For the 31B, the device side is in our receipts (M3 Pro 36 GB, mlx-community/gemma-4-31b-it-4bit): on main the load holds each linear three times (48 GB footprint, swap, then OOM at the first forward); this head loads in 17 GB / 20 GB and serves 3 streams at 8K at 6.1 tok/s. The 31B's decode and 16-row chunk shapes are among the 11 bit-equal kernel shapes. A main-vs-head 31B reply comparison isn't possible on this Mac because main can't run the 31B here; the 12B check you completed is the exactness evidence for the shared path.

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

@jschmied, the 31B check we promised is in, on an M5 Ultra with mlx-community/gemma-4-31b-it-4bit. It keeps all 160 full replies and every 1/16/128-row raw token/logit/top-two artifact identical to main. Loaded Metal allocation falls from 51,958,824,960 to 34,536,587,264 bytes, saving 16.226 GiB.

Several four-stream reply-speed cells are slower. Thinking-on prime factors at temperature 0 falls from 34.738 to 32.887 tok/s, 5.33%, with disjoint ranges; two sampled thinking-off cells lose 4.99% and 4.94%. CI is green, but that concurrent cost needs an answer before calling the check GREEN.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 15, 2026

Copy link
Copy Markdown
Owner

DEVICE. @jschmied, CI is confirmed green, and the 36 GB fit result is useful. Our completed 31B comparison also keeps every measured reply and raw artifact exact while saving 16.226 GiB of Metal allocation.

The concurrent speed question in the preceding result remains open, including the 5.33% prime-factor cell. Please address that cost before landing.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Thanks for the M5 run. The three four-stream cells are a paired loss, so don't land yet. I have not found a cause in this PR's code. Here is what I checked.

Ruled out by reading b3bfd3ae7 against 4ddc28cfc. On tensor units the served path gets the same buffers in the same order:

  • stack/pack still interleave gate|up. interleaves(true, 1) is true, and s.interleaved is glu and count == 1 as on main.
  • packArrays still builds the lane pack from the same host arrays: same device.buffer(..., shared) calls, same regOrder, same order.
  • mlxCopy still makes one aligned shared buffer per member. Only the source moves, from the kept shard to the Stage.
  • The layer loop is unchanged: qkv, o, gate|up, down, then the seven MLX copies. The rows branch (mlxAlias) is never taken when tensorUnits() is true.
  • Residency is unchanged. residency.hold adds checkpoint.shards and weights.owned as before, with the same shared | untracked / shared options. Every pack and copy that was in the set is still in it. Only the 17 GiB of shard bytes leave.
  • Kernels are unchanged: no .metal change, and no runtime get/ref of a linear. That would now fail with DeferredTensor rather than fall back.
  • The only new allocation is the load-time Stage, freed before serving. Unlike Nemotron on Metal without tensor units skips the lane tiles no kernel reads: about 1 GiB less #3375, no struct grew a field and no build step moved.

One served setting does depend on the memory this PR frees: the default prompt-cache budget. enableCache (native/gemma4.zig:175) sizes it from maxWorkingSet - allocated - 8 GiB - streams' caches, as half that room with a 16 GiB floor (cache_fit.defaultBudget). Gemma's snapSave copies a stream's caches on the GPU into new buffers at each kept mark. That copy runs beside the other three streams' decode.

  • If main's room was near zero on your M5, main served with no prompt cache or a small one.
  • With 16.2 GiB more room, this head keeps more states, and copies more of them.

This is a hypothesis, not a measurement: I have no M5.

Could you send or re-run:

  1. The prompt cache: ... GiB from ... GiB free startup line from both builds' runs. If they differ, that is the lead.
  2. The three slower cells (thinking-on prime factors T=0, and the two sampled thinking-off cells) on both builds with the same --prompt-cache-gib, A-B-B-A. Use main's logged value, or 0 for both.

If the loss stays with equal budgets, the cause is something I have not found yet, and I will keep looking.

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Here is a check of the prompt-cache lead from my last comment, run on an M3 Pro (36 GB). It is the row path, not the M5's lane path, so your equal-budget rerun is still the deciding test. Setup: 12B 4-bit, --parallel 4, context 16384, main 4ddc28cfc against b3bfd3ae7, A-B-B-A ×3, a fresh server per run, one warm-up batch.

Default flags. The budgets differ: main logs prompt cache: 1.2 GiB with 19.1 GiB in use after load, and this head logs 12.8 GiB with 7.6 GiB in use.

cell main head change
thinking-on prime factors, T=0, 4 streams 57.78 tok/s 51.57 −10.7 %, nearly disjoint
sampled thinking-off, T=1, 4 streams 24.06 40.31 +68 %

Main hits memory pressure (16 warnings) and stops keeping states. The head keeps a state at each miss and copies it on the GPU beside the other three streams' decode. So the thinking cell loses. The sampled cell gains because the warm-up repeats its prompts, so the head's kept states are reused.

--prompt-cache-gib 0 on both builds. Each logs 0.0 GiB.

cell main head change
thinking-on prime factors, T=0 51.20 tok/s 51.06 −0.3 %, ranges overlap
sampled thinking-off, T=1 17.25 17.80 +3.2 %

Replies: there is one hash set per cell across all 24 runs, and main equals the head.

On this Mac, the loss comes from the default prompt-cache policy getting more room, not from the weights. With equal budgets the builds are level. If your M5 rerun with equal --prompt-cache-gib comes out level too, the remaining question is the policy itself: whether a state should be saved on a miss while other streams are decoding. That is a separate change from this PR. "Don't land yet" stays until your rerun.

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, thank you, that isolates it. The memory saving and exactness hold: 16.2 GiB less loaded Metal allocation on the 31B, with every full reply and the raw logits unchanged. And your M3 Pro tables show where the thinking cell's loss comes from: with --prompt-cache-gib 0 on both builds they are level, so the weights are not the cause.

The loss is still there at default flags, though. This head's default prompt-cache budget grows from 1.2 to 12.8 GiB, and the thinking-on four-stream cell drops 10.7%. A change that makes a default cell slower does not land, even when the cause is another policy. So one of two things has to go first: keep the default budget at main's value in this PR, or change the save-on-miss policy (no kept state saved while other streams are decoding) in its own PR, which we would take on its own measurements.

On our side we will rerun the M5 cells with equal --prompt-cache-gib on both builds and main as a separate control, and run your two cells on an M3 Ultra at both default and equal budgets.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Thanks, understood. A slower default cell doesn't land. I'll take the second route: the save-on-miss policy in its own PR from main. #3350 stays "don't land yet" until that PR lands.

That PR will carry its own measurements:

Your M5 and M3 Ultra reruns will be a useful check on both.

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart A correction to my last two comments: the M3 Pro loss was a measurement artifact, not save-on-miss. So I've put the save-on-miss PR on hold.

What the logs show. The thinking cell's prompts are 37 to 39 tokens, so no state is kept during it on either build: every think request logs kept 0. What does differ is memory pressure.

  • At its 1.2 GiB default budget, main logs a pressure warning before every think cell, then "normal again" 5.1 to 5.7 s into it.
  • Under pressure the lane host admits one more stream only when none is running, so main's four requests queue.
  • Gemma 4 on Metal holds each linear's bytes once: the 31B 4-bit loads in 17 GB of GPU memory, not 48 #3350 logs no pressure line in any of its 6 runs.
  • Our cell divided tokens by tensorfold.seconds, which is decode time from the end of the prefill. It leaves out that queue wait, so it rated main's queued requests too well.

Rerun with wall clock (first send to last reply). M3 Pro, 12B 4-bit, --parallel 4, context 16384, default flags, main 4ddc28cfc against b3bfd3ae7, A-B-B-A ×3, a fresh server per run:

cell metric main, median [range] #3350 change
thinking-on T=0 ×4 wall clock 40.19 [39.82–41.38] tok/s 49.81 [48.90–50.06] +24.0 %, disjoint
thinking-on T=0 ×4 decode-only (old) 51.72 [51.30–52.60] 51.83 [51.38–52.95] +0.2 %
sampled ×4 wall clock 21.10 [16.93–21.33] 40.11 [39.54–40.44] +90 %, disjoint
sampled ×4 decode-only (old) 27.29 [20.80–28.31] 40.49 [39.84–40.92] +48 %

On this Mac, #3350 at default flags is faster, not slower. For your M5 and M3 Ultra reruns, two things would tell us whether the same thing happened there:

  1. Pressure lines: whether main's server log shows "memory pressure" lines during the four-stream cells.
  2. Metric: whether the cell divides by decode seconds or by wall time.

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, our M5 Ultra run agrees with your M3 Pro tables. All 504 full replies match across the parent, this head and main, on the 12B and the 31B, at default, zero and 1 GiB prompt-cache budgets. With equal budgets the parent and head group spans overlap. With default budgets (about 59.4 GiB on the parent and 67.6 GiB on this head for the 31B) the greedy thinking-on four-request span is 2.15% longer, with disjoint ranges.

So the cause is the one you found, and the ask from our last reply stands: keep the default budget at main's value in this PR, or land the save-on-miss policy change on its own first. The memory saving itself is welcome either way.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Thanks for the M5 run. I took your first route: 1c40496985 keeps the default prompt-cache budget at main's value in this PR.

  • The change: enableCache adds the bytes this branch no longer keeps resident back into the reserve when it sizes the default. These are the shard span main held plus the MLX copies the row path now aliases. The default then equals main's for the same checkpoint and Mac. An explicit --prompt-cache-gib is unchanged, and the memory stays free.
  • Tests: a host test pins the default to main's formula, with planted controls red. zig build test 853/853 and test-native pass on the M3 Pro.
  • M3 Pro at defaults, 12B 4-bit, four streams, A-B-B-A ×3 against main 4ddc28cfc:
    • Both builds log 1.4 GiB from 1.4 GiB free.
    • Thinking-on T=0, wall clock: 49.93 → 50.01 tok/s (+0.2 %), ranges overlapping.
    • No pressure line in any run, and replies are one hash set per cell.
    • The sampled cell is bimodal on both builds, depending on whether the warm-up's states fit a budget that varies 1.1 to 1.4 GiB between runs. Within each mode the builds are equal. Main against a second main server shows the same two modes.

The body has the full table. Could you rerun the 31B default cells on the M5 at this head? With the budgets now equal, they should overlap as your equal-budget runs did.

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, the reserve change answers our default-budget request. On an M5 Ultra all 504 full replies match across the 12B and 31B at the default, zero and 1 GiB cache budgets, and the lower loaded memory stays. The 31B default greedy loss is gone: the four-request span goes from 2.1200 to 2.1261 s, with overlapping ranges.

One small default loss remains, on the 12B greedy thinking-on cell: 1.2424 to 1.2472 s (+0.39%), with the two base runs at 1.24235-1.24246 s and the two new runs at 1.24448-1.24999 s. At matched cache budgets of zero and 1 GiB every cell overlaps. We'll rerun that one cell with more runs before deciding; if it holds, it needs a look before this lands.

The native host tests and the local dev-tools build pass; the macOS dev-tools CI job was cancelled at 55 minutes of runner time, not by a test.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, we reran the 12B default greedy thinking-on cell on the M5 Ultra with six fresh servers an arm, first run dropped. The four-request span's median goes from 1.242053 to 1.248117 s (+0.49%), and the new median sits 0.8 ms above base's slowest run, so by our rule it is still a default slowdown. The full ranges now overlap, so it's small, but a default that slows a measured cell can't land.

Everything else holds: all 56 full replies match, cached tokens are zero, no memory-pressure lines appear, and the cache budgets match between arms. We don't know the cause yet. We'll look at where the time goes on our side and post what we find, but if you can see why the default 12B path costs a little more per request, that would settle it fastest.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, here's where the 12B default time goes, as far as we can see. Of the 6.1 ms added across four requests, about 4.7 ms is prompt time. Decode is unchanged: the same 63 shared rounds verifying 264 rows, with the same dispatch counts.

Finer timing points at the CPU waiting longer for the prompt command buffers to complete (the wait in prompt.run, zig/src/families/gemma4/prompt.zig:153), while the GPU spans themselves stay close. Both versions allocate the same 97 GPU buffers a request, keep no prompt states and make no per-request residency commits. With that timing on, the longer wait also shows at explicit 0 and 1 GiB budgets, so it doesn't look like a default-only cache step.

That locates the wait but not its cause, so we don't have a fix to suggest yet. If anything in the change alters how or when the prompt's command buffers are committed or waited on, that's where we'd look first.

  • Synthena (Ash's Agent)

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Thanks, locating it in the prompt's cb.wait narrows it a lot. Short answer: nothing in this PR changes how or when a prompt command buffer is committed or waited on. Against main, 1c40496985 touches core/checkpoint_metal.zig, gemma4/{gemma4,model,weights}.zig and native/gemma4.zig. prompt.zig, forward.zig, kernels.zig, residency.zig, core/affine_mm and every .metal file are unchanged. prompt.run still encodes one serial encoder per chunk, then commit and wait (prompt.zig:150-153).

What the prompt binds on tensor-unit Macs, main against this head:

prompt reads main this head
embed w/s/b (gather), every norm, layer_scalar a Ref into a per-file shard span buffer, shared | untracked a Ref into a per-file kept buffer, shared | untracked (checkpoint_metal.zig:140)
l.mlx (core/affine_mm prompt chunks) mlxCopy, one buffer per member, shared | untracked the same, same order (weights.zig:11)
lane packs, head, scratch unchanged unchanged
residency hold adds every shard and weights.owned, commits once at startup the same (residency.zig:11-12)

On the 12B there are two buffers per side, so each encoder binds the same number of buffers in the same tracking mode. Every one is in the set, which is committed and requested once at load. Nothing new is tracked, and nothing reaches the GPU outside the set.

What does differ, ranked:

  1. Where the load's Metal buffers land. The load stages each linear through ckpt.Stage, a Metal buffer that grows when a larger member comes (checkpoint_metal.zig:286).
    • On the 12B it grows twice in layer 0: 8.4 MiB at q, freed, then 31.6 MiB at gate.
    • The 31.6 MiB buffer stays alive between all the packs and MLX copies and is freed after load.
    • So this head allocates the weights in a different sequence and leaves two freed holes. Buffers made after load (scratch, the streams' caches) can land in them.
    • Main allocates the same buffers back to back. This is the Nemotron on Metal without tensor units skips the lane tiles no kernel reads: about 1 GiB less #3375 pattern: same kernels, different allocation order.
    • Candidate fix 827e992424 on 1c40496985, weights.zig only: the stage moves to host memory (weights.Stage). The load then makes main's Metal allocations in main's order, minus the linears' shard span, with no extra Metal buffer and no hole. Bytes and kernels are unchanged.
  2. The kept pieces' addresses. Main read the embed and norms at the files' odd offsets inside a span of about 5 GiB. Of the 12B's 340 kept tensors, 295 are not 16-byte aligned there. This head packs them 256-byte aligned into a 541 MiB buffer and a 0.3 MiB one. That should not cost, but it is the one thing every prompt chunk reads that sits somewhere new.
  3. Two struct fields from 1c40496985: Checkpoint.selected_bytes and Weights.aliased, both read only at startup. Decode reads Model as much as the prompt does, and you see decode level, so I rank this last.

Ruled out: the budget (you see the wait at 0 and 1 GiB too). Per-request work from this change: released()/reserved() run once in enableCache at startup, and the Stage and the files are gone before the server starts. Hazard tracking: every buffer involved is untracked, on both sides.

Not run yet: the Metal device run of 827e992424 (zig build test, test-native, 12B replies against 1c40496985, prompt-wait timing on the M3 Pro). Our Mac is offline until later today. On the Spark, the three host targets that compile the load pass: test-gemma4-owners-host, test-gemma4-affine-host and test-gemma4-prompt-head-host. zig fmt is clean, and weights.zig is 591 lines.

Once our Mac is back, I'll run those, push 827e992424 here, and ask you to time the 12B default greedy thinking-on cell on it with your prompt-wait timing. If the wait comes back level, it was candidate 1. If it doesn't, candidate 2 is next: I'd test a variant that keeps the kept pieces at their file offsets. Until the cell is level, this PR shouldn't land.

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart 827e992424 is pushed: the load stages each linear in host memory, so its Metal buffers are made in main's order with no freed holes (candidate 1 from my last comment). weights.zig only, same bytes and kernels.

On our M3 Pro it is exact and neutral: suites green, 24/24 replies equal to 1c40496985 (greedy, seeded, thinking-on, 1 and 4 streams), and the prompt chunks' wait minus GPU span is level with 1c40496985 (38.3 vs 37.5 ms over four prompts). The M3's row path doesn't show your added wait, so it can't settle it. Could you time the 12B default greedy thinking-on cell on the M5 Ultra at this head with your prompt-wait timing?

One way to split your number, if it's easy: commit to GPUStartTime vs GPUEndTime to wait return. On the M3 nearly all of the CPU excess is before the GPU starts, so that tells queueing behind another command buffer apart from host-side completion. If the cell isn't level, candidate 2 (kept pieces back at their file offsets) is next. Until it is, this shouldn't land.

@ashhart

ashhart commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@jschmied, the 12B default greedy thinking-on cell is still slower on the M5 Ultra at this head. Six measured fresh servers per arm, after one excluded warm-up, give 1.225519 s on main and 1.236776 s here (+0.92%). Every new run is slower than every main run in this sample. All 84 full replies match exactly, with zero cached tokens and no memory-pressure warning. The previous head is 1.235878 s.

In a separate matched probe run, the four prompt waits total 47.85 versus 55.33 ms before GPU execution, 121.37 versus 121.32 ms on the GPU, and 0.44 versus 0.45 ms after GPU completion. That locates the remaining wait but does not identify its cause. Host staging has not recovered the default cell, so this still waits on that cost.

  • Synthena

@jschmied

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. We couldn't reproduce the M5 cost on our M3 Pro, so here is what it is not, and a probe that would locate it on the M5 in one pair of runs.

All runs: 12B, defaults, 4 thinking-on prompts at once, fresh servers, warm-up excluded, A-B-B-A order. Replies are one sha set in every run. Sums over the 4 prompt chunks, medians of 4 runs per arm:

M3 Pro encode->commit commit->GPUStart GPU span GPUEnd->return
main 4ddc28cfc 0.76 ms 37.69 ms 1206.19 ms 0.55 ms
b3bfd3ae7 0.83 34.52 1206.64 0.51
1c40496985 0.77 32.86 1205.88 0.53
827e992424 (head) 0.81 33.34 1205.76 0.60

The cache budget is pinned to 1 GiB here, the most main accepts on 36 GB, with no pressure warning in any run. Unpinned, main is 44.3 ms and the head 35.0 ms. On the M3 the head waits less before GPU start, not more.

Three candidate causes we checked and ruled out:

  1. Buffers bound per command buffer. The M5 takes the lane path, and there both builds create the same 716 weight buffers in the same order with the same options. Only the two whole-shard buffers differ: main's are 6.7 GB and the head's kept-tensor buffers are 567 MB. A prompt chunk binds 332 distinct weight buffers on both builds, and a decode step 388. We read the lane load on the M3 with tensor units forced on for load only. The extra buffers the row path binds (698 vs 450) don't apply on the M5.
  2. Work queued ahead of a chunk. A per-queue commit log shows only prompt.run and forward.run commits during the cell on both builds. Nothing else runs between a chunk's commit and its GPU start, so the wait is submission latency with the GPU idle.
  3. A larger automatic cache budget doing snapshot saves. Both builds compute the same budget (1.1–1.4 GiB, since 1c40496985 reserves the freed memory), and the cell keeps 0 states with 0 hits on both.

So the ~1.9 ms per prompt before GPU start on the M5 isn't explained by anything we can reach on the M3. If you can spare one more pair on the M5, the patch below (local, env-gated, never committed) splits each chunk the same way and logs every commit on the queue with its caller. Apply it with python3 patch.py <repo root> on a clean tree at 4ddc28cfc or 827e992424, then zig build native, and set TF_G4_CHUNK_TIMES=1 TF_G4_QUEUE_LOG=1. A second run with TF_G4_COUNT=1 adds the buffers bound per chunk; it slows encoding, so keep it separate. The g4chunk, g4cb and g4count lines are all we'd need. They show whether the M5 gap is encode time, something queued ahead, or pure submission latency, and whether the bound bytes or buffer counts differ there.

827e992424 stays the head until that's known. We won't push a guess at a fix that we can't measure.

patch.py (sha256 3a2a5306…f89691)
"""Local, env-gated instrumentation for the #3350 bisect (never committed): per prompt chunk timings and buffer counts."""
import sys, pathlib
root = pathlib.Path(sys.argv[1]) / "zig/src"

def sub(rel, old, new):
    p = root / rel; t = p.read_text()
    assert t.count(old) == 1, (rel, old)
    p.write_text(t.replace(old, new))

# encoder trace: distinct buffers bound (setBuffer/useResource) and bind calls, only while trace_on
sub("metal/command.zig", "const Id = objc.Id;\n", """const Id = objc.Id;
pub var trace_on: bool = false;
pub var trace_calls: usize = 0;
pub var trace_n: usize = 0;
pub var trace_ids: [16384]usize = undefined;
fn traceNote(id: Id) void {
    trace_calls += 1;
    const k = @intFromPtr(id);
    for (trace_ids[0..trace_n]) |x| if (x == k) return;
    if (trace_n < trace_ids.len) { trace_ids[trace_n] = k; trace_n += 1; }
}
""")
sub("metal/command.zig", """    pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void {
""", """    pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void {
        if (trace_on) traceNote(buffer.id);
""")
sub("metal/command.zig", """    pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void {
""", """    pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void {
        if (trace_on) traceNote(buffer.id);
""")
sub("metal/metal.zig", "pub const Queue = @import(\"command.zig\").Queue;\n",
    "pub const Queue = @import(\"command.zig\").Queue;\npub const cmd_trace = @import(\"command.zig\");\n")

# residency set at hold: members and bytes
sub("metal/resident.zig", "            return .{ .held = held, .io = io, .work = work, .scratch = scratch };\n",
    "            std.log.info(\"g4resident name={s} members={d} bytes={d}\", .{ name, held.members.count(), held.bytes });\n"
    "            return .{ .held = held, .io = io, .work = work, .scratch = scratch };\n")

# prompt chunk timings
sub("families/gemma4/prompt.zig", """    const rows = ids.len;
    if (rows == 0 or rows > R) return error.BadChunk;
""", """    const t_enc = mtl.clock.seconds();
    const timed = @import("sys").getenv("TF_G4_CHUNK_TIMES") != null;
    const counted = @import("sys").getenv("TF_G4_COUNT") != null;
    if (counted) { mtl.cmd_trace.trace_on = true; mtl.cmd_trace.trace_calls = 0; mtl.cmd_trace.trace_n = 0; }
    const rows = ids.len;
    if (rows == 0 or rows > R) return error.BadChunk;
""")
sub("families/gemma4/prompt.zig", """    e.end();
    cb.commit();
    cb.wait();
    if (cb.failure()) |msg| {
        std.log.err("gemma4: prompt chunk failed: {s}", .{msg});""", """    e.end();
    const t_commit = mtl.clock.seconds();
    cb.commit();
    cb.wait();
    const t_back = mtl.clock.seconds();
    if (counted) {
        mtl.cmd_trace.trace_on = false;
        std.log.info("g4count rows={d} binds={d} distinct={d}", .{ rows, mtl.cmd_trace.trace_calls, mtl.cmd_trace.trace_n });
    }
    if (timed) std.log.info("g4chunk rows={d} at={d} enc={d:.6} commit={d:.6} gpu_start={d:.6} gpu_end={d:.6} back={d:.6}", .{ rows, p0, t_enc, t_commit, cb.gpuStart(), cb.gpuEnd(), t_back });
    if (cb.failure()) |msg| {
        std.log.err("gemma4: prompt chunk failed: {s}", .{msg});""")

# per-queue commit log (TF_G4_QUEUE_LOG): every commit with clock time, caller address and queue; times once completed
sub("metal/command.zig", "pub var trace_on: bool = false;\n", """pub var trace_on: bool = false;
const qclock = @import("clock.zig");
var qlog_on: ?bool = null;
const QRec = struct { cb: Id, t: f64, ra: usize, q: usize };
var qrecs: [8192]QRec = undefined;
var qn: usize = 0;
var qlock = std.atomic.Value(bool).init(false);
fn qOn() bool {
    if (qlog_on == null) qlog_on = @import("sys").getenv("TF_G4_QUEUE_LOG") != null;
    return qlog_on.?;
}
fn qRecord(cb: Id, ra: usize) void {
    const t = qclock.seconds();
    const q = @intFromPtr(objc.msg(?Id, cb, "commandQueue", .{}));
    while (qlock.swap(true, .acquire)) {}
    defer qlock.store(false, .release);
    if (qn < qrecs.len) {
        qrecs[qn] = .{ .cb = objc.retain(cb), .t = t, .ra = ra, .q = q };
        qn += 1;
    }
}
pub fn qlogFlush() void {
    if (!qOn()) return;
    while (qlock.swap(true, .acquire)) {}
    defer qlock.store(false, .release);
    std.log.info("g4qbase flush={x}", .{@intFromPtr(&qlogFlush)});
    var keep: usize = 0;
    for (qrecs[0..qn]) |r| {
        const st = objc.msg(usize, r.cb, "status", .{});
        if (st >= 4) {
            std.log.info("g4cb q={x} ra={x} commit={d:.6} gpu_start={d:.6} gpu_end={d:.6} st={d}", .{ r.q, r.ra, r.t, objc.msg(f64, r.cb, "GPUStartTime", .{}), objc.msg(f64, r.cb, "GPUEndTime", .{}), st });
            objc.release(r.cb);
        } else {
            qrecs[keep] = r;
            keep += 1;
        }
    }
    qn = keep;
}
""")
sub("metal/command.zig", """    pub fn commit(self: CommandBuffer) void {
""", """    pub noinline fn commit(self: CommandBuffer) void {
        if (qOn()) qRecord(self.id, @returnAddress());
""")
sub("families/gemma4/prompt.zig", "    if (timed) std.log.info(\"g4chunk", "    mtl.cmd_trace.qlogFlush();\n    if (timed) std.log.info(\"g4chunk")
print("patched", root)

@ashhart

ashhart commented Nov 18, 2026

Copy link
Copy Markdown
Owner

Thank you @jschmied for the M3 probes and for moving the staging to host memory. The M3 numbers are level, and nothing in the diff changes how prompt buffers are committed or waited on.

The M5 default cell is still slower at this head: 1.236776 s against 1.225519 s on main, +0.92%, with every new run slower than every main run in that sample. All replies match, so this is only the default cost.

Could you run the instrumented pair on the M5 and send the four log lines? We need to see whether the extra wait is in encoding, queued ahead of the chunk, or after GPU completion. The cell has to come back level before this can land.

  • Synthena

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart We have no M5, only the M3 Pro, so the instrumented pair has to come from your machine. The probe is the one in my 17 Nov comment (#3350 (comment)): apply patch.py to a clean tree at main 4ddc28cfc and at this head 827e992424, run zig build native, and set TF_G4_CHUNK_TIMES=1 TF_G4_QUEUE_LOG=1. Each prompt chunk then logs encode->commit, commit->GPUStart, GPU span and GPUEnd->return, and every commit on the queue with its caller. The patch is local only and never committed.

If you send those four lines for main and this head, I'll read where the +0.92 % sits. If most of it is before GPU start, I'll try candidate 2 next: the kept pieces back at their file offsets. Until the cell is level, this shouldn't land.

@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thank you @jschmied. The host staging and the M3 results are clear, and we agree nothing in the change alters how prompt buffers are committed or waited on.

We are unable to run the M5 default cell here. The instrumented pair is the one in your 17 November comment: apply the local patch to a clean tree at main 4ddc28c and at 827e992, build native, set TF_G4_CHUNK_TIMES=1 and TF_G4_QUEUE_LOG=1, and post the four per-chunk timings and queue lines from both trees. On your M3 Pro, please also confirm the four replies and the prompt-wait split are level. Until an M5 cell comes back level, the default cost is still open.

  • Synthena

@jschmied

Copy link
Copy Markdown
Contributor Author

@ashhart Confirmed on our M3 Pro, from the instrumented pair at main 4ddc28cfc and this head 827e992424 (12B, four thinking-on prompts, A-B-B-A twice, TF_G4_CHUNK_TIMES=1 TF_G4_QUEUE_LOG=1):

  • Replies: one sha set over all 8 runs; the four replies are equal on both trees.
  • Prompt-wait split, summed over the 4 chunks: commit->GPUStart 44.3 ms on main vs 35.0 ms here; GPU span 1208.6 vs 1207.5 ms.
  • Queue: busy-by-others 0.0 ms on every chunk of both builds; only prompt.run and forward.run commit.

So on the M3 the split is level, with no extra wait before GPU start, during it or after it. We have no M5 either, so the default cell stays open until someone with an M5 runs the probe; the patch and steps are in my 17 Nov comment. Until then this shouldn't land.

@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied. The instrumented pair reads level on your machine: the queue is idle of others, the GPU span is equal, and the branch even trims the commit-to-start wait, with every reply equal. That leaves exactly the one open cell: the M5 default prompt pass, which measured about one percent slower at this head.

We will run the device check on our side with your probe on an M5 Ultra and read where the wait sits. Until that cell comes back level, the default cost stays open, as you said.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

The 827e9924 head merged cleanly into 37fa51d23. I hit the same compile errors on main alone and on the merge in test-gemma4-owners-host and test-gemma4-prompt-head-host. The row-projection test helper assumes every struct pipeline has a pointer ID. One test double uses a numeric ID and the other has no ID field.

In scratch, I gave the inert test double a numeric ID and made the test helper handle pointer and integer IDs. This touches only the test helper and test double. On main, the two previously failing targets then passed 380 tests with three skips. On the trial merge, this command passed 757 tests with 13 skips and zero failures on M5 Max with Zig 0.17.0:

zig build test-native test-gemma4-load-parts-host test-gemma4-owners-host test-gemma4-affine-host test-gemma4-prompt-head-host test-gemma4-shared-host compile-gemma4-host -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all

The M5 Ultra default-prompt timing cell remains open.

Igor Lessio - AIFLOW LABS

jschmied and others added 5 commits November 21, 2026 04:37
…in 17 GB of GPU memory, not 48

The load kept every shard in a Metal buffer for the model's life, then copied each linear twice more: a lane or
row pack for decode, and an MLX copy for prompt chunks. On a 36 GB Mac the 31B 4-bit failed its first forward.
- The layers' linears now stay in their files (checkpoint_metal's addFileSplit with weights.later, as qwen27
  does). They are read once through a Stage into the packs, and the files close after load.
- The shards keep only the embed, the norms and the layer scalars.
- Without tensor units the row pack holds the checkpoint's arrays as stored, so l.mlx views its rows in place.
  gate|up packs gate rows, then up's (geglu's split mode), so each member is one row range.
- Tensor-unit Macs keep the lane pack's 16-row interleave and the MLX copy, staged the same way.
A linear read through the checkpoint after load is refused by name (DeferredTensor), and a staged read after
closeFiles by ShardClosed. A host test shows both, and the aliases' bytes equal the copies'.
The kernel contract checks split gate|up + geglu against the interleaved twin's bits, with a planted control.
…ts' Metal stand-ins, which have no Device.init
… packs released, so it stays the size it was

The linears no longer stay resident in their shard span, and the row path aliases the packs instead of copying each
member. That frees about 11.4 GiB on the 12B 4-bit, and the default prompt-cache budget grew into it. A larger default
cache must not make a default cell slower, so the default now counts those bytes as still held:
- Checkpoint.selected_bytes: each file's span from its first selected tensor to its last, what addFileSelected held;
- Weights.aliased: the bytes the per-member copies took, on the row path that no longer makes them;
- Model.released() sums the span past the kept tensors and the aliases, and enableCache adds it to the streams'
  reserve for the default budget only. An explicit --prompt-cache-gib is unchanged, and the memory stays free.
…buffers are made in main's order

The staging buffer was a Metal buffer that grew while the packs and MLX copies were made, so each growth freed one
buffer and allocated another between them, and the freed span was left as a hole after load. Host memory makes the
load's Metal allocations main's sequence with the shard spans left out: kept pieces, then per layer the packs and copies.
@ashhart
ashhart force-pushed the gemma4-metal-weights branch from 827e992 to 3fa5304 Compare November 21, 2026 04:37
@ashhart
ashhart merged commit 3e0a0ce into ashhart:main Nov 21, 2026
2 of 11 checks passed
@ashhart

ashhart commented Nov 21, 2026

Copy link
Copy Markdown
Owner

Thank you @jschmied. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

ashhart added a commit that referenced this pull request Nov 21, 2026
ashhart added a commit to eXsoR65/TensorFold that referenced this pull request Nov 21, 2026
ashhart added a commit that referenced this pull request Nov 21, 2026
ashhart added a commit that referenced this pull request Nov 21, 2026
jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 24, 2026
Since ashhart#3350, gemma4/model.zig reads each shard with addFileSplit(.., "language_model.", weights.later), so the tower is
not held on main; this PR's addShard was only called by its own test. The PR now covers LFM3-VL only.
ashhart pushed a commit to jschmied/TensorFold that referenced this pull request Nov 24, 2026
Since ashhart#3350, gemma4/model.zig reads each shard with addFileSplit(.., "language_model.", weights.later), so the tower is
not held on main; this PR's addShard was only called by its own test. The PR now covers LFM3-VL only.
ashhart pushed a commit that referenced this pull request Nov 24, 2026
Since #3350, gemma4/model.zig reads each shard with addFileSplit(.., "language_model.", weights.later), so the tower is
not held on main; this PR's addShard was only called by its own test. The PR now covers LFM3-VL only.
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