Repository navigation
metal: batched prompt prefill for Qwen3.6-35B-A3B - #773
Conversation
gdn_rows runs the gated delta step over a chunk of rows in one launch, its row body shared with the decode's gdn_step; the state is read from the lane_at word and written once to lane_to, and gdn_ring_rows commits the conv ring after the chunk. attn_norm_rope_rows and gqa256_flash_f16_rows run the decode's norm, rope and flash per row at its absolute position (causal), and norm_rows the decode norm per row. Each row is bit-equal to the decode kernels; the launchers refuse each bad shape by name. New clauses in clauses_rows.rs, nine new mutants. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…erands) gemm.metal multiplies a chunk of activation rows by a quantized weight in steel-style 64x64 tiles with simdgroup matrix products and f32 accumulation; each quant's dequant16 owner in quant.metal decodes its weights, the edge store is bounded, an optional residual is added in the epilogue, a segmented form serves the routed experts, and a non-finite or past-half-range activation raises quant_column with its row NaN. metal_gemm_time times it one command buffer at a time (an Apple M4 Pro stamps a queued buffer's GPU start while the previous one runs), beside a probe-only port of MLX's affine_qmm_t as the reference arm. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
Target::prompt cuts the prompt with call_batches: up to 8 rows step as before, longer spans run Session::pass over chunks of U rows. A pass runs the GEMMs over the chunk, the router's selection over rows (route_pick shared with the decode), a GPU route table, the routed experts as grouped GEMMs (gemm_routed.metal), the shared expert dense, and the combine in the decode's order; the head runs on the last row only and the fault word is read once at the end. RowsArena opens on the first pass. New kernel clauses (route, grouped GEMM, combine, headnorm rows) and e2e clauses (short prompts bit-equal to steps, layer-0 state band, chunk-size invariance, store ratio against ik's sets, free-run, fault), each with its mutants. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…ttention delta_rows now runs three kernels: a row-by-key-head parallel prep (conv taps, SiLU, decay, beta, gate) through the same inline functions as the decode step, the state recurrence sequential over rows, and a post pass; the rows stay bit-equal to stepped gdn_step, which keeps its fused form. attn_prefill_f16 runs a tile of query rows against the f16 cache with GQA sharing, a causal limit by absolute position, an f32 online softmax and simdgroup matrix products; it is held to a derived band against the decode flash, and a non-finite input raises its site with the row NaN. metal_rows_time times both one command buffer at a time. The batched pass takes both: the delta rows read the prep scratch the rows arena holds, and the pass's attention is one attn_prefill_f16 launch per layer in place of the v0 rows. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…a gap Without a set the driver wires a buffer at the first command buffer that binds it and lets the wiring lapse when no submitted buffer names it for a while. The first prompt of a process paid the wiring of every weight, and the first decode step after a long pass re-wired the early layers. The session now registers every buffer it allocates into the stream's set, the open waits for the set's request, and a submit renews the request when the last is older than 250 ms. The r_resident clause holds the set's bytes to the allocations and the renewal count. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
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: one doc comment in generate_metal.rs now describes the wrong function; I found no behavior bug in the host path I read.
Must fix
1. step_times_run lost its doc; pass_times_run carries two docs
generate_metal.rs:515-527 The new pass_times_run was inserted between the step_times_run doc block and its fn. Lines 515-520 (the step_times lines, "three depths") now document pass_times_run. step_times_run at line 598 has no doc. A reader of pass_times_run is told it prints step-clock phases for three modes. Fixing it now costs two moved lines; later the wrong text gets copied.
Fix: move lines 515-520 to sit directly above fn step_times_run, and leave 521-526 as the only doc of pass_times_run:
/// The `step_times` lines: `n` tokens in each mode past the run —
/// host-fed and chain greedy, ahead on one id throughout, so every token
/// ahead is kept — the step clock's phases averaged a mode and printed
/// as one line, then the count. The lines are development-loop numbers,
/// like the summary's: the three runs sit at three depths, a mode's
/// attention reading a few keys more than the mode before it.
fn step_times_run(s: &mut Session, n: usize, id: u32) -> Result<(), String> {Non-blocking
⚠ A pass can fail after its first ops are committed: attention.rs:788 builds attn_prefill_f16 lazily, at the first attention layer (layer 3). Each op of a pass is already submitted on its own buffer (session.rs PassOps::one), so layers 0-2 have advanced the delta state and ring. If the pipeline build fails, pass returns Err with the position unmoved and the session not poisoned; the next call on the session reads advanced state. bloomery_serve_metal exits on this error, a library caller does not. Direction: build the pipeline before the first op of the first pass, so a refusal leaves nothing committed.
⚠ A failed rows-arena open leaves its buffers registered: session.rs:976 RowsArena::open registers each buffer as it allocates (residency.rs:167); nothing in the crate calls removeAllocation. If a later buffer fails (y is the largest), rows stays None, the earlier buffers stay in the set, and the retry allocates again. Direction: register the arena's buffers after the open succeeds.
⚠ Probe weight: metal_gemm_time and metal_rows_time add about 2,300 lines, a vendored MLX kernel and a licence entry. No recipe, gate or doc names them (the same holds for metal_attention_time). Say in the PR body which decision they serve after this PR, or drop them (fewest elements).
Optimization headroom
- G. Per-launch and per-sync fixed cost: session.rs:1623
PassOps::onebegins, ends and submits one signalled command buffer per op: about 5 ops × 40 layers, so about 200 buffers and 200 signals per pass, also for a 9-row pass. The ops already end withmemory_barrier, so one buffer per pass with the same barriers would cut that to 1. Onlypass_profileneeds the split.
Checked
- Duplicates: 20 new items checked by Grep. Dryer pairs read:
clauses_gemm.rs:464-607(sameCasetable shape, different tensors), themainstubs of the probe bins,refuseinrows.rs(per-file helper with its ownWHAT, asarena.rsandsession.rshave). None is a duplicate of one owner. - Complexity:
delta_rows(67),gemm_routed(53),attention_rows/attention_prefill,check_chunk,check_rowsare new host launch wrappers whose branches are shape refusals, not logic growth. The probe functions (attn_arms,one) are timing tools. No split asked. - Silent failure: 6 sites followed (
gemm.rs:364unwrap_or(0)is behind the empty-segments refusal at line 292; thelet _ =sites insession.rsare on error paths that return the first error).Target::promptbatching, thePassOut::Lastlogits row and the lane parity (lane_of(from)tolane_of(to)) hold against the step path. - Tests: kernel mutants and clauses were not run; I did not read the clause bodies. No new FAIL-first evidence for
attn_prefill_f16is in the PR text beyond "every kernel mutant red". - Gates: no band, tolerance or lint level moved. New
PIN(2026-10-24)lines on new constants and theunsafe-ratchetimpl are dated and give a reason.unsafe: one newimpl Send, with a SAFETY line. - Escape catalog: no shell code in the diff, no match.
Notes
- The speed table (M4 Pro, 760-855 prompt tok/s) has conditions but not the
CONTRIBUTING.mdevidence list (commit hashes, commands with output). The PR also changes the decode submit path (keep_residentper submit, a wired residency set) and gives one decode control, 101.3 tok/s, with no base-commit number. Please add the base figure at the same depth.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
…; the prefill pipeline is built before a pass commits An Alloc now stages its buffers, and Staged::commit adds them to the set, so a rows arena that fails part way leaves the set as it was. A pass builds attn_prefill_f16's pipeline before its first op is committed, and attention_prefill fetches it before it encodes, so a refused build leaves nothing of the pass on the device. generate_metal's step_times doc sits on step_times_run again. 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:
- Must-fix 1 fixed: the step documentation now precedes its function at crates/metal/src/bin/generate_metal.rs:592.
- Pipeline-build warning fixed: crates/metal/src/arch/qwen3moe/session.rs:984 prepares the pipeline before submitting pass operations.
- Failed-arena warning fixed: crates/metal/src/arch/qwen3moe/session.rs:977 stages buffers and registers them only after allocation succeeds.
- Probe-purpose warning answered: the PR body names routed-expert tile fill and command-buffer consolidation as the probes' next uses.
Verdict: CLEAN: the earlier must-fix is resolved, and no must-fix defect survives review of the new commits.
Non-blocking
⚠ Refusal paths lack regression coverage: residency.rs:194 changes allocation rollback, and session.rs:984 prepares the pipeline before pass operations. The residency clause only exercises successful opens. Extend the Metal gate to force a later allocation failure and a prefill-pipeline build failure; assert unchanged residency counts or model state, respectively, and exercise recovery. The checks should reject eager registration and delayed preparation. Adding them now preserves the new failure contracts.
Checked
- Duplicates: 4 new items checked by Grep; none duplicates an existing owner. No dryer pair covers an incremental addition; prior pair outcomes stand.
- Complexity: crapper's pass_with (26) and attention_prefill (34) change preparation order without adding branches. Its other reports concern functions unchanged since the previous review.
- Silent failure: 3 error paths followed: main-arena allocation, rows-arena allocation, and pipeline compilation. Errors propagate; uncommitted staging drops its retained buffers.
- Tests: no tests changed. Mutation inspection found no refusal-path assertion against eager registration or delayed preparation; no hardware tests were run.
- Gates: no threshold, tolerance, lint level, or test moved.
- Performance: prefill preparation reuses OnceLock; staging allocates only during arena opens. No new per-token allocation, launch, copy, or synchronization.
- Escape catalog: no matching pattern; no shell changes.
Notes
The PR now supplies base decode figures and measurement conditions. Please attach the raw gate output and complete A/B commands with output for the evidence requested previously. Validation here was static.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
Batched prompt prefill for the Metal engine (Qwen3.6-35B-A3B). Part of #593.
A prompt longer than 8 ids now runs as batched passes, one per ubatch (the CUDA engine's rule), instead of one decode step per id.
norm_rows.attn_prefill_f16: a flash attention over a tile of query rows against the f16 cache.Session::pass;Target::promptcuts the prompt withcall_batches. Prompts of 8 ids or less keep the step path.Gates (M1 Pro, fixture):
just lab-metal(every kernel mutant red on its clause),just lab-metal-e2e(prompt ≤ 8 ids bit-equal to steps, state band, chunk-size invariance, reference distance, free run,r_resident),mac-metal-lint,check-unsafe,check-comments,check-recipes.M4 Pro 48 GB, Qwen3.6-35B-A3B MLX 4-bit, development-loop numbers (not public):
The step path (before this change) ran the 873-id prompt at 84–112 tok/s in two contended runs. mlx-lm 0.32 on the same machine, same sitting: pp512 943 tok/s, pp4096 1038 tok/s.
Decode control (
--prompt "The capital of France is" -n 64), interleaved, arm order rotated, 3 rounds each: base (main 8d91214) 103.1 / 102.3 / 101.4, this PR 103.2 / 101.0 / 100.3 tok/s. Mean −0.7 %, inside the noise of 3 rounds on a laptop in use.Evidence: measured at d5b3261 (the review fixes after it touch only the opens and the pass's first op); macOS 27.0.1, Apple M4 Pro 48 GB; model
Qwen3.6-35B-A3BMLX 4-bit as one GGUF split;generate_metal --prompt "$(cat p.txt)" -n 8 --ctx 8192withBLOOMERY_REF_MODELset, release build, one process per run; prompts are README text of 873, 4160 and 7985 ids. Load (vm.loadavg, 1 min) was 2.3–5.9 during the runs.Two probe bins time kernels one command buffer at a time:
metal_gemm_time(its reference arm is MLX'sqmm_t, soTHIRD_PARTY_NOTICES.mdgains MLX's licence) andmetal_rows_time. They serve the next prefill levers: the routed experts' tile fill, and one command buffer per pass instead of one per op.The kernels and host code were written with Claude Code rounds and reviewed by the maintainer.
🤖 Generated with Claude Code
https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ