Repository navigation
metal: prompt call fixed costs (one buffer per layer, checkpoints copied once) - #779
Conversation
… 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
…per prompt call Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
There was a problem hiding this comment.
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)
…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
There was a problem hiding this comment.
Since the last review:
-
- Fixed: stream.rs:215 scopes encoder access through a higher-ranked callback, blocking the reported swap.
-
- Fixed: encode.rs:168 reuses the concurrent constructor and retains the borrowing return lifetime.
-
- Fixed: generate_metal.rs:577 uses the existing median owner.
-
- Fixed: all three count accumulators use
EncodeCount::add_assign.
- Fixed: all three count accumulators use
- 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)
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.
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.--pass-times) keeps a buffer per op.--pass-timestakes several sizes and printspass_wallbeside 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:An earlier run of
just check-recipeson this Mac was red only in its two Python self-tests, from main'stools/bloomery/reach_cache.pyunder 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:
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 8192and--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