Repository navigation
Gemma 4 on Metal holds each linear's bytes once: the 31B 4-bit loads in 17 GB of GPU memory, not 48 - #3350
Conversation
|
@jschmied FIXES. The staged ownership and row aliases look consistent, but the new device-backed test at 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.
|
|
Thanks @ashhart. Fixed in
|
|
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.
|
|
@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.
|
|
@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, |
|
@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.
|
|
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.
|
|
@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
One served setting does depend on the memory this PR frees: the default prompt-cache budget.
This is a hypothesis, not a measurement: I have no M5. Could you send or re-run:
If the loss stays with equal budgets, the cause is something I have not found yet, and I will keep looking. |
|
@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, Default flags. The budgets differ: main logs
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.
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 |
|
@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 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
|
|
@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. |
|
@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
Rerun with wall clock (first send to last reply). M3 Pro, 12B 4-bit,
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:
|
|
@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.
|
|
@ashhart Thanks for the M5 run. I took your first route:
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. |
|
@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.
|
|
@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.
|
|
@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 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.
|
|
@ashhart Thanks, locating it in the prompt's What the prompt binds on tensor-unit Macs, main against this head:
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:
Ruled out: the budget (you see the wait at 0 and 1 GiB too). Per-request work from this change: Not run yet: the Metal device run of Once our Mac is back, I'll run those, push |
|
@ashhart On our M3 Pro it is exact and neutral: suites green, 24/24 replies equal to One way to split your number, if it's easy: commit to |
|
@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.
|
|
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:
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:
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
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) |
|
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.
|
|
@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 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. |
|
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.
|
|
@ashhart Confirmed on our M3 Pro, from the instrumented pair at main
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. |
|
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.
|
|
The 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 allThe M5 Ultra default-prompt timing cell remains open. Igor Lessio - AIFLOW LABS |
…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.
827e992 to
3fa5304
Compare
|
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. |
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.
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.
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.
Branch
gemma4-metal-weights@ 827e992, on main 4ddc28c.827e992424stages each linear in host memory during load, so the load makes main's Metal allocations in main's order (review 6911938544, section below).1c40496985keeps the default prompt-cache budget at main's value (review 6906645673, below).b3bfd3ae7added 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 on2fb135acb, whose weight code is otherwise identical.Problem
Gemma 4's Metal load kept three copies of every linear.
weights.stack/packcopied each linear into a lane pack (tensor units) or a row pack (no tensor units).weights.mlxCopycopied 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.
footprintmeasured 48 GB of IOAccelerator memory and50 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.
addFileSplit(..., weights.later), the patternqwen27 already uses (
gpu_weights.repacked+Stage). The layers'*_proj.{weight,scales,biases}stay intheir files.
stack/pack/mlxCopyread them once through aStage, andcloseFiles()runs after load.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.l.mlxbecomes views of its rowranges (
mlxAlias/mlxStack) and there is no third copy. For each member to be one row range, gate|up packsgate rows, then up's (geglu's split mode,
IL = 0) instead of alternate 16-row blocks.copy; only the shards go. The split is
weights.interleaves(tensor_units, runs), host-tested.ref/geton a linear after load fails withDeferredTensor,and a staged read after
closeFilesfails withShardClosed. The host test plants such a pointer and showsboth refusals.
Evidence (M3 Pro, 36 GB, no tensor units)
Memory: peak
footprintduring load and serveAt
--parallel 4 --prompt-cache-gib 2, main refuses to start the 12B because it would pass 70 % of RAM (19.2 GiBheld). This branch starts it.
Replies on the 12B 4-bit equal main. Every
token_sha256matches:Speed: 12B, cold prompt and decode, A-B-B-A, 2 rounds, a fresh server per run, 128 greedy tokens
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 = 1it replaces, on the same simd_qmm call (n = 2I).Unchanged:
tf-kernel-contract --only gemma4: 37 kernels pass gates 1-4, 7/7 controls red. No.metalfile changes.zig build testexit 0, with the new host tests:later's names, the interleave split, aliases equal to copies,and the planted stale pointer refused.
zig fmtclean; 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 main4ddc28cfcon the same box, and this PR touches no server code.tools/pr_check.py: lean 341 vs 341, 0 new;zig fmt --checkclean.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)
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, whataddFileSelectedheld) minus what this branch keeps, plus the MLX copies the row path now aliases (Weights.aliased).enableCacheadds it to the reserve for the default only, so the default equals main's for the same checkpoint and Mac. An explicit--prompt-cache-gibis unchanged. The memory itself stays free.expected 2004318027, found 14173392032);selected_bytesnot added → 2 red.zig build test853/853,test-nativegreen, 9test-gemma4-*-hoststeps native and-Dfixed-cpu, lean 0 new, fmt clean.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, main4ddc28cfcvs1c40496985, A-B-B-A ×3, a fresh server per run, wall clock = first send to last reply):Load stage in host memory (827e992)
Review 6911938544 located a longer prompt
cb.waiton the M5 12B default cell. Nothing here changes how prompt command buffers are committed or waited on. The one load difference wasckpt.Stage, a Metal buffer that grew twice in layer 0 and left freed holes for later buffers.827e992424moves 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 test853/853 steps,test-native63/63, lean 0 new,zig fmtclean, weights.zig 591 lines.1c40496985vs827e992424: greedy, seeded (T=1, seed 7+i) and thinking-on T=0, 4 prompts one at a time and 4 at once: 24/24token_sha256equal, 1 stream == 4 streams.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.