Skip to content

metal: the prefill attention fills its MMA rows with real (position, head) pairs and rescales elementwise - #1107

Merged
midagedev merged 2 commits into
mainfrom
macpp
Nov 1, 2026
Merged

midagedev merged 2 commits into
mainfrom
macpp

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What

The Metal prefill attention (attn_prefill_f16) puts real rows in every MMA fragment row.

Before this change, a fragment held one position's query heads, padded to 8 rows. At 4 query heads per key head (Llama-3, Qwen3 dense, LFM3), half of each score and value product ran on zero rows. Now a key head's rows are (position, query head) pairs, numbered position by position. A threadgroup takes 32 consecutive rows, and each SIMD group holds 8 of them.

The rescale is now each row's own factor multiplied into its values, not a product with a diagonal fragment. A query that is not finite makes only its own row NaN.

Why

Decomposition of Llama-3.1-8B prefill at P=4096 on an M1 Pro, against mlx-lm 0.32.0 f16:

  • the total gap was 3.13 s;
  • 2.59 s of it was this attention: ours 3.89 s, mlx 1.29 s;
  • the GEMMs were tied at 4.03 TF.

Results

Second Mac (M1 Pro, 16-core GPU). generate_metal prompt tok/s, base vs new, interleaved, 4–5 rounds, 95 % intervals:

model pp4096 pp512
Llama-3.1-8B 223.14 → 255.46 (+14.48 % ± 0.11) +2.27 % ± 0.07
Qwen3-8B 217.66 → 252.76 (+16.13 % ± 0.04) +2.51 % ± 0.07
LFM3-1.7B 1134.06 → 1217.56 (+7.36 % ± 0.13) +1.86 % ± 0.13
Qwen3.8-27B 74.70 → 76.10 (+1.87 %) +0.29 % ± 0.10
Qwen3-Coder-30B-A3B 400.88 → 427.00 (+6.52 % ± 0.08) +0.77 % ± 0.10

Attention probe, Llama shape, P=4096: 121.4 → 48.6 ms. For reference, mlx-lm f16 does Llama pp4096 at 269.08 tok/s on the same Mac. These are development-loop numbers: no timing lease, and the load was recorded at ≤ 3.

Checks

  • metal_scan --compare: the only changed entry on all 7 instances is attn_prefill_f16.
  • Kernel gate: PASS on 7 instances. --mutants-all: every mutant is red on its clause.
    • New mutants: the row mapping (position, head), the SIMD group's first row's causal limit (prefill, window and prologue rows), the block's last row, and the per-row NaN.
    • prefill_pad_rows_stored is retired with a PIN line: there are no padded rows left to store.
  • New clause assertion: a query that is not finite makes only its own row NaN. It is red on the old kernel.
  • lab-metal-e2e: all 6 rows PASS, with their mutants.
  • decode = prefill: equal for Llama and Coder at D=1024 and 4096.
  • Base and new generate equal ids on 5 models.

Lead re-run on the rebased commit (second Mac, one chain, rc 0):

  • cargo test -p bloomery-metal --lib: 123 passed. The one test skipped is the known cached-checkpoint test.
  • gate_metal_device: PASS.
  • gate_metal_qwen35moe_kernels: PASS on 7 instances. --mutants-all: 235/104/25/42/42/21/4, each red on its clause.
  • just lab-metal-e2e: PASS on 6 rows, checked by row name (qwen35moe, qwen3moe, qwen38d, lfm3, llama, qwen3). Each row's --mutants-all is PASS.
  • just mac-static origin/main: rc 0. check-model-tax: ok, with and without --base.

🤖 Generated with Claude Code

…y head) pairs, and a row rescales its own accumulators

A prefill fragment held one position's query heads padded to eight rows, so at four query heads a key head half of
every score and value product was zero rows. A key head's rows are now its query heads at every position of the
chunk, numbered position by position; a threadgroup takes 32 consecutive rows and a SIMD group the 8 of one fragment.
The causal mask and the window are the lane's row's, and a query that is not finite makes NaN its own row only. The
rescale is the row's factor on its two values a fragment instead of a diagonal fragment product.

The probes: metal_gemm_time times the prefill's half-row GEMM (h16), and metal_rows_time no longer indexes past the
query buffer at P >= 1024 on a host with no gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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 new h16 probe reports the wrong pipeline and output traffic, and duplicates the GEMM dispatch.

Must fix

1. Inspect the pipeline the h16 arm actually runs

crates/metal/src/bin/metal_gemm_time/mac.rs:654
--arm h16 --pipelines inspects gemm_*_store_f16. The timed arm uses GemmX::F16, which selects gemm_*_store_h16. The printed kernel name and resource limit describe another program.
Kind A: --arm h16 --pipelines reaches the wrong lookup and prints its metadata.
Cost: Correct this before these resource reports guide geometry changes.
Replace the added match arm:

Arm::Half => (device.library(), format!("gemm_{}_store_h16", quant.name())),

2. Count four bytes for each h16 output

crates/metal/src/bin/metal_gemm_time/mac.rs:1044
The new elem = 2 also feeds r * n * elem at line 1049. This arm writes f32 output, so gbps omits 2 * R * N bytes per dispatch [derived].
Kind A: timing h16 reaches the shared byte calculation and prints understated bandwidth.
Cost: Fix the byte count before probe results enter performance comparisons.
Replace the issued calculation:

let out_elem_bytes = if matches!(arm, Arm::Mlx(_)) { elem } else { 4 };
let issued = bytes + (n / tile) * r * k * elem + r * n * out_elem_bytes;

3. Keep one GEMM dispatch setup

crates/metal/src/bin/metal_gemm_time/mac.rs:898 repeats crates/metal/src/bin/metal_gemm_time/mac.rs:868: the same timing loop, shape, weights, output, fault and error handling. Select the library, input representation and operand once, then share the setup (R14).
Kind B: merge the copied setup mechanically; the replacement below is shorter and adds no helper.
Cost: Merge the arms now so future dispatch fixes have one owner. This removes a copied block without adding a helper.
Replace both arms with:

Arm::Engine(_) | Arm::Tensor(_, _) | Arm::Half => {
    let (kernels, operand) = match arm {
        Arm::Engine(o) => (ctx.kernels, o),
        Arm::Tensor(o, relaxed) => (&libs.tensor(ctx.device, relaxed)?.1, o),
        Arm::Half => (ctx.kernels, Operand::F16),
        _ => unreachable!("the arm uses Kernels::gemm"),
    };
    time_dispatches(ctx, pool.copies, dispatches, |encoder, copy| {
        let x = match arm {
            Arm::Half => GemmX::F16 {
                x: x_h16.as_ref().expect("the half arm's activation rows")
                    .window(Elems(0), Elems(r * k)).map_err(why)?,
                stride: k,
            },
            _ => GemmX::F32 {
                x: x_f32.window(Elems(0), Elems(r * k)).map_err(why)?,
                stride: k,
            },
        };
        kernels.gemm(encoder, GemmParams {
            quant, rows: n, cols: k, acts: r,
            weights: pool.window(copy, 0)?, x,
            y: y.window_mut(Elems(0), Elems(r * n)).map_err(why)?,
            y_stride: n, mode: GemmMode::Store, operand, fault,
            layer: LAYER_NONE,
        }).map_err(|e| format!("the dispatch did not encode: {e}"))
    })?
}

Non-blocking

⚠ Supply the geometry and timing proof: crates/metal/kernels/attention.metal:1683
At GQA=4, flash threadgroups per key head fall from ceil(P/4) to ceil(P/8) [derived]. This is the occupancy/geometry class. The PR reports gate passes but labels its timing results unleased. Supply the resource derivation, owning/e2e gate output and admissible A/B with both hashes, model paths and commands/output.

Checked

Pipeline selection traced through GemmPipelines::of; f32 output confirmed in GemmParams and the h16 kernel entry.
Both dispatch arms and the smaller consolidation inspected. The inline suggestion targets an added line.
The parser issue is confirmed at base line 474, unchanged by the diff; no open issue title duplicates it.
The geometry count follows the old four-position blocks and new 32-row blocks. Escape catalog C1–C4 do not match the retained findings.

Notes

Metal gates require Apple Silicon/macOS and were not run here.

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

Filed outside this PR: #1108

for quant in [Quant::Q4K, Quant::Q6K, Quant::A4] {
let (library, name): (&Library, String) = match arm {
Arm::Engine(o) => (device.library(), engine_kernel(quant, o)),
Arm::Half => (device.library(), engine_kernel(quant, Operand::F16)),

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.

The h16 arm dispatches gemm_*_store_h16; inspect that pipeline for its thread limit.

Suggested change
Arm::Half => (device.library(), engine_kernel(quant, Operand::F16)),
Arm::Half => (device.library(), format!("gemm_{}_store_h16", quant.name())),

…bytes, and shares the engine arms' dispatch

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@midagedev

Copy link
Copy Markdown
Owner Author

Fixed in a8c80eb, probe only:

  1. --arm h16 --pipelines now names gemm_*_store_h16. Second Mac output: q4k max_threads 768, q6k 640, a4 640.
  2. The output bytes are 4 per value for the engine arms. MLX keeps its own element size.
  3. The engine, tensor and h16 arms now share one dispatch setup.
    Check: a4 14336:4096:2048 h16 is 59.635 ms (4.03 TF), the same as before the fix. just mac-metal-lint: 0 warnings.

@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:

Verdict: CLEAN: The three earlier must-fix items are resolved; no must-fix finding remains in this incremental review.

Checked

Duplicates: 0 new functions, types or constants. The repeated GEMM setup is removed.
Complexity: existing arm-selection branches in one now share one GEMM dispatch.
Silent failure: library, input-window and GEMM errors propagate. The h16 buffer expectation is guarded by its construction.
Behavior: engine/tensor inputs remain f32; h16 inputs remain f16. MLX retains its own output width.
Tests: no tests added or changed; mutation check not applicable.
Gates: no pins or clauses changed in this increment.
Escape catalog: C1–C4 do not match.

Notes

Metal execution requires Apple Silicon/macOS; no Metal build or gate was run here.

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

@midagedev
midagedev merged commit 384a1be into main Nov 1, 2026
7 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