Skip to content

metal: prompt call fixed costs (one buffer per layer, checkpoints copied once) - #779

Merged
midagedev merged 5 commits into
mainfrom
mac-passfix
Oct 24, 2026
Merged

midagedev merged 5 commits into
mainfrom
mac-passfix

Conversation

@midagedev

@midagedev midagedev commented Oct 24, 2026 •

Copy link
Copy Markdown
Owner

Fixed costs of a Metal prompt call. Part of #593.

A contributor's two-point fit showed about 100 ms of fixed cost per prompt call on the M3 and M5 Ultra, and chat turn 2 (a few short calls) took about 60 % of turn 1's time.

  • A checkpoint copied 73.7 MB of delta state twice (pages → Vec → slot), and a cut copied it back twice. Each now copies once, straight between the shared pages and the slot: 24.7 → 1.3 ms a checkpoint.
  • An unprofiled pass was one command buffer per op, about 200 a pass. It now commits one buffer per layer, each opened at the stream's token boundary and not waited, and settles the last one once. A layer bounds how long one buffer runs, so a long pass on a small chip stays clear of the GPU's command-buffer timeout. One buffer per pass measured the same within 1 ms. The profiled pass (--pass-times) keeps a buffer per op.
  • --pass-times takes several sizes and prints pass_wall beside the summed op times. The server prints one line per prompt call (positions, ids, ms).

Gate q_layers (e2e): a 100-id pass commits one buffer per layer and waits once, and its pick, logits row, states, rings and cache rows equal the profiled pass's bit for bit. FAIL-first: one buffer per op (22), one buffer for the pass (1), and a layer buffer without the boundary wait (other picks) are each red.

Gates (M1 Pro, fixture), each rc 0 at the head after the review fixes: cargo fmt --all --check, check-unsafe, check-comments, just check-recipes, just mac-metal-lint, just lab-metal, just lab-metal-e2e. Output lines:

clause q_layers: PASS (a pass of 100 ids is 4 command buffers (one a layer) and one wait, and leaves the pick, logits row, states, rings and cache rows of the profiled pass's 22 buffers bit for bit)
gate_metal_qwen35moe_e2e: PASS
gate_metal_qwen35moe_e2e --mutants-all: PASS (9 mutants, each red on its clause)
gate_metal_qwen35moe_kernels --mutants-all: PASS (112 mutants, each red on its clause)

An earlier run of just check-recipes on this Mac was red only in its two Python self-tests, from main's tools/bloomery/reach_cache.py under Python 3.14 (marshal.dumps(code, 2) raises on a slice constant); the run at the head was green. Not touched here.

M4 Pro 48 GB, Qwen3.6-35B-A3B MLX 4-bit, development-loop numbers (not public). Interleaved, arm order rotated:

base one buffer + single copies per-layer buffers
checkpoint (ms) 24.7 / 25.6 1.26 / 1.41 —
pass wall, 9 rows (ms) 75.5 / 62.9 62.3 / 62.0 61.4 / 61.3
pass wall, 2048 rows (ms) — 1825.1 / 1826.8 1826.2 / 1825.5
873 ids, prompt tok/s 933.7 / 942.9 971.8 / 957.6 957.0
7985 ids, prompt tok/s 989.6 / 986.6 1000.9 / 1000.6 1000.3 / 998.0 / 999.1

Chat through bloomery-serve-metal -c 8192, turn 2 (26 new ids, three calls: 5, 16 and 4 ids): base 104.5 / 125.4 / 86.9 ms, after 51.9 / 81.5 / 43.7 ms. Decode control (--prompt "The capital of France is" -n 64): 103.2 / 100.3 / 102.3 / 101.9 tok/s across the sittings.

Evidence: base = main with #777's tile (daf73ee); the one-buffer arm at 36becf462 and the per-layer arm at the tree of this branch's head (the commits were regrouped by file after the measurement, the tree unchanged). macOS 27.0.1, Apple M4 Pro 48 GB; model file Qwen3.6-35B-A3B-mlx4-00001-of-00001.gguf; generate_metal --prompt "$(cat p.txt)" -n 8 --ctx 8192 and --pass-times 9,64,2048, release build, one process per run. Load (vm.loadavg, 1 min) 2.4–5.7.

What is left of the fixed cost on a short pass is named in the measurement: the expert weights read once (the floor), the dense GEMM's 64-row tile padding on a few rows (about 29 ms at 9–64 rows), and the first call of a process (about 90 ms, the rows arena's first open).

The code and gates were written with Claude Code rounds and reviewed by the maintainer.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ

midagedev and others added 3 commits October 25, 2026 02:21
… checkpoints and cuts copy once

An unprofiled pass was a command buffer an op, about 200 a pass. It now
commits a buffer at each layer change (the embed rides with the first
layer, the head with the last), each opened at the stream's token boundary
and not waited, and settles the last one. A layer bounds a buffer's run
time, so a long pass on a small chip stays clear of the GPU's
command-buffer timeout. A refusal before the first commit commits nothing;
one after waits the committed layers out. The profiled pass keeps a buffer
an op (PassProfiler). TokenRecording holds a recording and its open token
encoder across the walk's calls, and the stream counts its committed
buffers (StepStats::submits).

A checkpoint copies each delta layer's state lane and ring from the shared
pages straight into its slot, and a cut copies a slot straight back into
the stores, each once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…nd one wait, bit-equal to the profiled pass

FAIL-first: a buffer an op (22 buffers), one buffer for the pass (1) and
a layer buffer without the token-boundary wait (other picks) are each red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: The encoder accessor permits committing an open encoder, and new owners leave duplicate implementations.

Must fix

1. Keep each encoder inside its recording

crates/metal/src/stream.rs:213 Open two recordings with stream.begin()?.open_token_encoder()?, then call std::mem::swap(a.encoder(), b.encoder()). Now a.finish() ends b's encoder and returns a's recording. stream.submit(recording) commits a's buffer while its encoder remains open in b. Metal rejects that commit.
Restrict this API before callers depend on the escaping mutable reference. Replace the accessor with:

pub fn encoder<R>(
    &mut self,
    f: impl for<'e> FnOnce(&mut ComputeEncoder<'e>) -> R,
) -> R {
    f(&mut self.encoder)
}

Replace PassLayers::one with:

fn one(
    &mut self,
    layer: Option<usize>,
    f: impl FnOnce(&mut MetalOps<'_, '_>) -> Result<(), SessionError>,
) -> Result<(), SessionError> {
    let open = self.buffers.at(layer)?;
    open.encoder(|encoder| {
        f(&mut MetalOps::rows(
            encoder,
            self.arena,
            RowsCtx { arena: self.rows },
            self.kernels,
            self.from,
            self.head,
        ))
    })
}

2. Share concurrent encoder construction (R14)

crates/metal/src/encode.rs:179 repeats crates/metal/src/encode.rs:168: both select the same concurrent Metal encoder through the same factory. Only the returned lifetime differs.
Reuse the constructor now so a factory change has one owner. Replace the borrowing wrapper with:

pub(crate) fn concurrent(
    buffer: &ProtocolObject<dyn MTLCommandBuffer>,
) -> Result<ComputeEncoder<'_>, DeviceError> {
    Self::concurrent_detached(buffer)
}

3. Use the median owner in the existing timing loop (R14)

crates/metal/src/bin/generate_metal.rs:630 duplicates the sort and middle-element selection at crates/metal/src/bin/generate_metal.rs:577 in the same binary.
Complete the conversion now so median selection has one owner. Replace lines 577–578 with:

let med = median(&mut t);

4. Use EncodeCount's new addition owner (R14)

crates/metal/src/encode.rs:151 repeats the fieldwise addition at crates/metal/src/arch/qwen3moe/session.rs:1823. The same triplets occur in Tracer::one at session.rs:1567 and Profiler::one at session.rs:1912.
Convert all three triplets now so a new count field cannot leave these callers behind. Replace each triplet with:

self.count += c;

Non-blocking

⚠ Attach reproducible Metal validation: crates/metal/src/arch/qwen3moe/session.rs:1758 changes prompt command-buffer submissions from one per op to one per layer. The PR reports successful gates and interleaved timings but omits captured gate output. Attach the commands and gate output tied to the tested base and head.

Checked

Duplicates: both concurrent constructors, both median implementations and all three count accumulators confirmed. Items 2–4 reuse existing owners and remove code.
Tests: q_layers asserts one submission per layer and one wait, then compares results with the profiled pass. Retaining one buffer across all layers fails its submit-count assertion.
Gates: the unsafe-ratchet increase has a dated PIN and reason.
Escape catalog: C1–C4 do not match these findings. No ledger lessons are in force.

Notes

Static validation only; Metal gates were not run here.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

midagedev and others added 2 commits October 25, 2026 03:11
…rrent constructor; EncodeCount adds in one place

The encoder reaches the caller's closure at a lifetime of its own, so it
cannot leave the call or trade places with another pair's, and a pair's
finish always ends its own encoder. concurrent is concurrent_detached
with the borrow, and the three count triplets use EncodeCount's +=.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

    1. Fixed: stream.rs:215 scopes encoder access through a higher-ranked callback, blocking the reported swap.
    1. Fixed: encode.rs:168 reuses the concurrent constructor and retains the borrowing return lifetime.
    1. Fixed: generate_metal.rs:577 uses the existing median owner.
    1. Fixed: all three count accumulators use EncodeCount::add_assign.
  • Earlier validation question answered: the PR now includes head gate commands, M1 Pro identification, and gate and mutant output.

Verdict: CLEAN: All four earlier must-fix items are resolved, and the new commits introduce no proven defect.

Checked

Duplicates: 0 new items; changed implementations reuse existing owners.
Complexity: the incremental edits add no branches.
Silent failure: 0 new sites. Callback errors propagate unchanged.
Tests: no tests changed. Existing q_layers rejects per-op and whole-pass buffering through its submission-count assertion; state comparisons check ordering. The PR reports these mutants red.
Gates: no pins or thresholds changed in this increment.
Performance: the incremental edits add no allocations, command buffers, copies, locks, or floating-point reduction changes.
Adversarial checks: encoder exchange is blocked by the callback lifetime; constructor borrowing remains enforced; median inputs contain three samples and retain the same selection rule.
Escape catalog: C1–C4 do not match the new commits.

Notes

Static review only. Metal gates were not run here; they require Apple Silicon and macOS.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev
midagedev merged commit e294ea7 into main Oct 24, 2026
8 checks passed
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.

1 participant