Skip to content

metal: the decode flash at depth — register walk, 16 segments, a fold by SIMD shuffle - #1060

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

midagedev merged 2 commits into
mainfrom
macflash

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What and why

At depth, the Metal decode flash spent about 412 µs a layer at Qwen3.8-27B's shape (4096 keys). Three costs:

  • a precise exp ran twice a key a lane, so the ALU was the bound;
  • the one pass ran up to 16384 keys with a threadgroup per query head, so the grid was small;
  • 16 KB of static threadgroup memory limited residency.

Now the segmented walk reads K/V rows straight into registers, a key a lane, with one exp a lane a 16-key tile. The
one pass ends at 512 keys, and past it the keys split into 16 segments. The fold takes a head a SIMD group and a
segment slot a lane, and passes the factors by simd_shuffle, not threadgroup memory. So the geometry no longer caps
the query-head count: Qwen3-32B's 64 heads are no longer refused. The kernel takes 204 µs a layer at that shape.

The attention probe (metal_attention_time) gains MLX's sdpa_vector kernels as a reference arm (MIT, listed in
THIRD_PARTY_NOTICES.md; the probe only).

Release notes: Changed — Apple Silicon decode at long contexts is faster: Qwen3-Coder-30B-A3B at 16K keys 38 % less
step time, Qwen3.8-27B at 4K keys equal to mlx-lm.

Code shape

  • No second copy. The walk and the fold are the flash's one owner. The one-pass and attn_norm_rope* text is
    unchanged.
  • Model code holds only architecture facts.
  • Dead code is gone. The tile staging and the threadgroup factors are removed.
  • No silent failure. A NaN partial still poisons its head's output by name (the fold's refused path).
  • Comments state what is true now.
  • No relaxed gate. Two geometry refusals are removed because the shapes are now held: 3 key heads, and more
    than 62 query heads. A lib test asserts holds() for 24/3 and 128/16. The refusal table loses that one case
    (15 → 14). Kernel mutants: 6 are re-aimed at the new walk and fold, and 2 are new (attn_tile_score_lane,
    attn_tile_weight_shuffle). The kept e2e mutant merge_first_segment is re-aimed at the fold's segment read.
  • cargo fmt and clippy are clean; the lint count did not go up.

Duplication found or removed: none.

What I ran

On an M1 Pro (32 GB, macOS 27.0), the second maintainer Mac.

Change class: float sum order (the walk's and the fold's order moved). Judged by the e2e logits band and
decode = prefill.

  • cargo test -p bloomery-metal --lib: 115 passed. One test fails the same way on main and is skipped:
    model_arg::tests::a_cached_checkpoint_repo_is_its_folder_with_nothing_fetched.
  • gate_metal_device: PASS. gate_metal_qwen35moe_kernels: PASS (6 instances).
  • Kernel --mutants-all: PASS (qwen35moe_a3b 222, qwen3moe_a3b 98, gdn48 24, gqa6 34, gqa4 34, lfm3_attn 20).
  • gate_metal_qwen35moe_e2e: PASS on 4 rows. e2e --mutants-all: PASS. merge_first_segment stays kept: the gate's
    sessions hold one segment.
  • decode = prefill: EQUAL on Qwen3.8-27B and Qwen3.6-35B-A3B at depth 512, 4096 and 16384.
  • metal_scan --compare, on each of the 6 instances: changed=4, same=243.
    • The intended three: gqa256_flash_f16, gqa256_flash_q8, gqa256_flash_f16_rows.
    • The fourth, attn_norm_rope_rows, has unchanged source. It shares the rewritten F16Cache definition. Its
      clauses (attn_rows_v0, prefill) pass.
  • On the rebased head ae47641: lib 115 passed, the kernel gate PASS (6 instances), e2e PASS on 4 rows, e2e
    --mutants-all PASS. just mac-static origin/main: ok.

Decode step, ms (decode_rest_ms, run 2 of --repeat 2): base and this branch interleaved, 4 rounds. The interval is
the paired 95 % interval.

model keys base this PR effect
Qwen3.8-27B MLX 4-bit 16 89.47 89.44 −0.03 % ±0.58
Qwen3.8-27B MLX 4-bit 4096 96.49 92.40 −4.23 % ±0.75
Qwen3.6-35B-A3B 4-bit 4096 17.77 16.91 −4.87 % ±0.63
Qwen3.6-35B-A3B 4-bit 16384 (3 rounds) 23.62 19.94 −15.56 % ±0.58
Qwen3-Coder-30B-A3B 4-bit 4096 26.57 24.31 −8.48 % ±0.60
Qwen3-Coder-30B-A3B 4-bit 16384 75.63 47.05 −37.79 % ±0.06
LFM3-1.7B MLX 4-bit 4096 8.42 7.91 −6.03 % ±0.17

mlx-lm 0.32.0 in the same sitting: 27B at 4096 keys, 92.42 ms.

The remaining kernel gap to MLX's two-pass kernel at 4096 keys is about 80 µs a layer:

  • about 50 µs is the fold, read serially in the dispatch's last threadgroup;
  • about 50 µs is the walk, with no bound unit found yet.

That is a separate change.

Hardware

Apple M1 Pro, 32 GB, macOS 27.0.

AI use: written with Claude Code (an Opus round implemented it; the maintainer's lead session reviewed and ran the
gates).

🤖 Generated with Claude Code

…lits into 16 segments, and folds every head's factors by SIMD shuffle

The segmented walk reads its K/V rows straight into registers, a key a lane, with one exp a lane a 16-key tile; the
tile staging and the threadgroup factors are gone. The fold takes a head a SIMD group and a segment slot a lane, so
the geometry caps no query-head count (Qwen3-32B's 64 heads open). The one pass ends at 512 keys. The attention
probe gains MLX's sdpa_vector as its reference arm.

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 fold hides invalid values, and reference arms run with unsupported geometry and racing scratch writes.

Must fix

1. Preserve invalid values when a live segment's factor underflows

crates/metal/kernels/attention.metal:946 At 1024 keys and 16 segments, an f16 value NaN in a segment with maximum −200 produces a NaN value partial but finite maximum and weight sum. Other segments with maximum 0 make its f32 factor zero. This branch skips the NaN and returns finite output without a fault.
Cost: keep the failure visible before this fold becomes the reference for further optimization.
Replace the skip with the empty-segment test, and update the fold comment accordingly:

if (simd_shuffle(ls[r], ushort(c)) == 0.0f) {
    continue;
}

2. Remove the unsupported 16-block MLX timing arm

crates/metal/src/bin/metal_attention_time/mac.rs:1633 always adds the new segment cap, 16. crates/metal/src/bin/metal_attention_time/mlx.rs:392 uses blocks / 32 in all three fold loops, so this arm reads no partials and writes zeros. The self-check uses 64 blocks and passes; timings still report success.
Cost: remove the false reference before its timings guide another kernel change.
Replace lines 1633–1637 with the supported MLX rule, and remove the cap comparison from this function's doc comment:

let block_counts = [mlx::blocks_g13s(keys, QUERY_HEADS / KV_HEADS)];

3. Give each scratch address one writer

crates/metal/src/bin/metal_attention_time/mlx.rs:324 The base, exact, contiguous and chunk arms instantiate pad_n = 1. Every thread then writes its query-head maximum to pad[0] concurrently. The reference arms execute a threadgroup data race.
Cost: remove undefined behavior before using these arms to validate or compare kernels.
Replace the store:

if (simd_gid * BD + simd_lid < pad_n)
    pad[simd_gid * BD + simd_lid] = max_score;

4. Delete the unused cache tile fields

crates/metal/kernels/attention.metal:531 The rewritten walk removes every read of tile_k and tile_v; only two null assignments remain. These fields are dead elements under the fewest-elements rule.
Cost: remove them while the cache layout is already changing.
Apply:

--- a/crates/metal/kernels/attention.metal
+++ b/crates/metal/kernels/attention.metal
@@ -531,3 +530,0 @@
-    // Unread: the walk reads the cache rows alone. The rows append names them.
-    threadgroup attn_lane_word *tile_k;
-    threadgroup attn_lane_word *tile_v;
@@ -1156,2 +1152,0 @@
-    cache.tile_k = nullptr;
-    cache.tile_v = nullptr;

5. Retain a dated reason for the removed refusals

crates/metal/src/kernels/geom.rs:355 removes the three-key-head refusal case and its PIN. The divisor and factor-memory guards also disappear from attention_geom::holds. The replacement assertions explain the new geometry, but neither location records the required dated removal reason.
Cost: record why coverage changed while the removal and its evidence are together.
Add this immediately before the case table:

// PIN(2026-10-31): lane-held fold factors remove the divisor and shared-memory limits; attention_geom tests accept 24/3 and 128/16.

Non-blocking

⚠ Attach reproducible performance evidence: crates/metal/kernels/attention.metal:718 changes float sum order and occupancy. The body reports gates and interleaved A/B results, but omits exact model paths, both timed commit hashes, and commands with output. Attach those records under CONTRIBUTING's evidence contract.

Checked

Duplicates: dryer reports 0 candidate pairs. The cache tile fields have no readers.
Complexity: diagnostics report mlx_setup (new, 23), encode_pass1 (new, 21), timed (29→43), self_check (22→26), and parse (25→27).
Silent failure: followed the f16 store, value accumulation, partial write and fold; also the MLX block selection and fold. Both retain the failure paths above.
Tests: mlx_setup checks 1024 keys with 64 blocks, so it misses the 16-block failure. Geometry assertions now accept 24/3 and 128/16. No mutation tests were run here.
Gates: the geometry refusal case and guards disappear without a dated removal reason.
Escapes: none of the four catalog patterns matches the retained findings.

Notes

Metal gates were not run here. Static arithmetic checks reproduced the NaN suppression, zero fold iterations at 16 blocks, and scratch-address collisions.

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

Comment thread crates/metal/kernels/attention.metal Outdated
for (uint r = 0u; r < ATTN_FOLD_ROUNDS; ++r) {
for (uint c = 0u; c < 32u && 32u * r + c < args.segments; ++c) {
float f = simd_shuffle(factors[r], ushort(c));
if (f == 0.0f) {

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.

A zero factor can be underflow for a live segment with NaN values; skip only a segment with no weight.

Suggested change
if (f == 0.0f) {
if (simd_shuffle(ls[r], ushort(c)) == 0.0f) {

Comment on lines +1633 to +1637
let rule = mlx::blocks_g13s(keys, QUERY_HEADS / KV_HEADS);
let mut block_counts = vec![rule];
if rule != bloomery_metal::kernels::SEGMENT_CAP {
block_counts.push(bloomery_metal::kernels::SEGMENT_CAP);
}

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 MLX fold processes blocks in groups of 32; the 16-block cap arm writes zeros. Keep the supported MLX counts.

Suggested change
let rule = mlx::blocks_g13s(keys, QUERY_HEADS / KV_HEADS);
let mut block_counts = vec![rule];
if rule != bloomery_metal::kernels::SEGMENT_CAP {
block_counts.push(bloomery_metal::kernels::SEGMENT_CAP);
}
let block_counts = [mlx::blocks_g13s(keys, QUERY_HEADS / KV_HEADS)];

}
}

pad[(simd_gid * BD + simd_lid) % pad_n] = max_score;

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.

With pad_n=1, all threads race on pad[0]. Give each stored address one writer.

Suggested change
pad[(simd_gid * BD + simd_lid) % pad_n] = max_score;
if (simd_gid * BD + simd_lid < pad_n)
pad[simd_gid * BD + simd_lid] = max_score;

… segment's NaN reaches its head; the MLX timing arms run the supported block count with one writer per scratch address; the cache's unread tile fields go

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

Copy link
Copy Markdown
Owner Author

Review answered in 8f33ea6:

  1. The fold skips a segment only when its weight sum is 0 (simd_shuffle(ls[r], c) == 0). A live segment whose factor underflows is still added: 0 × finite adds an exact 0, 0 × NaN gives NaN. New kernel clause attn_fold_nan: 1024 keys in 16 segments, segment 1 scored ~203 under the others, one V row NaN; every output of key head 0 must be NaN. Mutant attn_fold_underflow_skipped restores the factor test.
  2. The MLX timing arm runs only mlx::blocks_g13s; the 16-block arm is gone.
  3. The MLX scratch store has one writer per address.
  4. tile_k/tile_v deleted.
  5. PIN(2026-10-31) line names the removed refusals and the tests that accept 24/3 and 128/16.

Gates on the second M1 Pro (macOS 26.2), this tree:

  • lib: 115 passed, 0 failed (1 filtered: a known main failure).
  • gate_metal_qwen35moe_kernels: PASS (6 instances); attn_fold_nan PASS on the 4 instances with an f16 flash.
  • --mutants-all: PASS on all 6 (223/99/24/35/35/20); attn_fold_underflow_skipped red on attn_fold_nan on all 4.
  • gate_metal_qwen35moe_e2e: PASS, 4 rows; --mutants-all PASS (qwen35moe 12, qwen38d 3, lfm3 3).

@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: live segments preserve NaN when their factors underflow.
  2. Fixed: MLX timing uses only supported block counts.
  3. Fixed: scratch addresses have one writer.
  4. Fixed: unused cache tile fields are removed.
  5. Fixed: removed geometry refusals have a dated reason.
  6. Performance evidence: still open (crates/metal/kernels/attention.metal:945).

Verdict: CLEAN: All five earlier must-fix items are fixed, and no new must-fix defect remains.

Non-blocking

⚠ Attach reproducible hardware evidence: crates/metal/kernels/attention.metal:945 changes the decode fold. Attach exact model paths, both timed commit hashes, commands with output, and the new underflow mutant's failing run. The body's gate summary names the earlier ae47641. These records keep subsequent kernel decisions tied to verified results.

Checked

Duplicates: 6 new definitions checked; segment_span matches private, test-only span_mirror, whose reuse would add API. Dryer reports 0 pairs.
Complexity: new attn_fold_nan is 16, from scene setup and fail-fast validation. Flagged mlx_setup (23), encode_pass1 (21), timed (43), self_check (26), and parse (27) are unchanged in this increment.
Silent failure: 3 paths followed. Live NaN remains NaN, empty segments are skipped, and MLX launch errors set the failure result.
Tests: restoring the factor-zero skip at attention.metal:945 makes attn_fold_nan reject finite output. Static arithmetic reproduced this mutation; scratch indices are unique and in bounds, and selected MLX block counts are multiples of 32.
Gates: the removed refusals now have PIN(2026-10-31) and a reason; no band is relaxed.
Escapes: none of C1–C4 matches the incremental diff.

Notes

Metal gates and GPU timing were not run here. Current-head gate output and FAIL-first evidence are absent from the supplied PR body.

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

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