Skip to content

metal: the tensor-op GEMMs read the f16 operand's rows as half rows cast once a pass, as the simdgroup GEMMs do - #1187

Merged
midagedev merged 2 commits into
midagedev:mainfrom
yulmucoffee:metal-gemm-tiles
Nov 9, 2026
Merged

midagedev merged 2 commits into
midagedev:mainfrom
yulmucoffee:metal-gemm-tiles

Conversation

@yulmucoffee

Copy link
Copy Markdown
Contributor

What and why

The tensor-op GEMMs (gemm_tensor.metal, the path a GPU with matrix units takes) now read the f16 operand's activations as half rows, cast once a pass, as the simdgroup GEMMs have since 15211d1f2. Until now that path had no half-row entry, so every weight tile loaded the f32 rows as scalars and range-checked each value while staging. The tile and its sum order do not change, so the output bits are the same as before. On an M5 Pro the A4 GEMM goes from 15.7 to 23.4 TFLOPS at the 27B's 17408 × 5120 shape (2,048 rows), and the prompt rate of Qwen3.8-27B at P = 512 goes up 40 %. It comes out of the variant search you asked for in #593. The readings of every variant I tried are in a comment there.

Release notes: Changed — prompt processing on Macs whose GPU has matrix units (M5) is about 30–40 % faster (Qwen3.8-27B 4-bit: 275 → 384 tok/s at P = 512 on an M5 Pro).

Two commits:

  • metal_gemm_time: --tensor-src …. --src compiles its file at Metal 3.2, so it cannot take a tensor-op program. --tensor-src takes the same NAME:ROWS:ACTS:THREADS:ORDER:PATH and compiles at Metal 4. --dump-tensor-source writes the starting text, and a source arm's NAME_h16 runs gemm_<quant>_store_h16 over half rows. This is how I tried the variants.
  • metal: the tensor-op GEMMs read the f16 operand's rows as half rows …:
    • gemm_tensor.metal gets the _h16 entries gemm.metal has (store, resid, seg store, seg resid, for every weight type). tensor_tile and its two kernels take the activation type X, as gemm.metal's do, and the staging picks gemm_stage_x's half overload.
    • GemmPipelines takes the half-row entries on either path, so gemm_x casts the f16 operand's rows once on the tensor-op path too. gemm_takes_half, takes_half and the tensor-op refusal go, and so does GemmPipelines::new's path argument.
    • The gate runs gemm_half_rows on the tensor-op kernels as tensor_gemm_half_rows (both rows), and the requantized types' tensor_gemm_{a8,a4h,a8h}_half_rows. The mutant tensor_h16_stage turns tensor_gemm_half_rows red. check_cast now checks the rows against the operand, not the path.
    • metal_gemm_time gets the arm tensorh16.

Code shape

  • No second copy. The half-row staging is gemm_shared.metal's gemm_stage_x overload and the cast is gemm_x, both shared with the simdgroup path. The tensor tile is templated on the row type instead of copied.
  • Model code holds only architecture facts. No model code changed.
  • Dead code is gone. gemm_takes_half, GemmPipelines::takes_half, the Option around the half pipelines, the "no half-row entry" refusal and the path argument it needed.
  • No silent failure. The cast's range check is the staging's: an activation past the half range or NaN raises the quantizer's site and makes its row NaN (tensor_gemm_half_rows checks it).
  • Comments state what is true now. tools/check-comments.sh: ok.
  • No relaxed gate. No band moved. The new clauses ask for the f32-row entries' bits, exactly.
  • cargo fmt and cargo clippy are clean on what I touched (just mac-metal-lint rc 0, just mac-fmt-check rc 0).

Duplication found or removed: none.

What I ran

All on the Mac below. Base is main at 004a23b7d, this branch is two commits on it.

  • FAIL-first. With the mutant tensor_h16_stage (the tensor tile stages a half row's four runs pairwise swapped), tensor_gemm_half_rows is red on both rows:

    clause tensor_gemm_half_rows: FAIL (blk.0.attn_qkv.weight 8192x2048 r9 Store x stride 2048[0] is -1.7075713 (0xbfda91b2), expected -0.12075682 (0xbdf74f5a))   [qwen35moe_a3b]
    clause tensor_gemm_half_rows: FAIL (blk.0.attn_q.weight 4096x2048 r9 Store x stride 2048[0] is -0.24136068 (0xbe772741), expected 1.6244254 (0x3fcfed2c))   [qwen3moe_a3b]
    
  • just lab-metal. On this branch alone, the only red clauses are the three shader-validation ones that metal gates: the shader validation reader counts macOS 26.5's report form, and has one owner #1180 fixes: row_tail_reads once, and gemm_a4_store twice ("shader validation reported nothing for the control"). The recipe stops there, before --mutants-all. Every other clause passes, the five new ones among them:

    clause tensor_gemm_half_rows: PASS (6 dense A4 cases at both epilogues and the segmented group, the half rows' bits the f32 rows' (tensor path); the range fault and NaN rows through the cast)   [qwen35moe_a3b, qwen3moe_a3b]
    clause tensor_gemm_a8_half_rows / a4h / a8h: PASS (6 dense … cases …, the half rows' bits the f32 rows' (tensor path); …)   [qwen35moe_a3b]
    

    On this branch with metal gates: the shader validation reader counts macOS 26.5's report form, and has one owner #1180's commit picked on top (a scratch tree, not this PR), just lab-metal ends rc 0 after 42 minutes:

    gate_metal_device: PASS
    gate_metal_qwen35moe_kernels: PASS (14 instances)
    gate_metal_qwen35moe_kernels --mutants-all [<each of the 14 instances>]: PASS (… mutants, each red on its clause)
    mutant tensor_h16_stage [qwen35moe_a3b]: red on tensor_gemm_half_rows
    mutant tensor_h16_stage [qwen3moe_a3b]: red on tensor_gemm_half_rows
    

    That is 421 clause lines PASS and 2 SKIP (metallib_equals_source, no Metal Toolchain). 816 mutants turn their clause red.

  • The output bits. metal_gemm_time --hash, the last dispatch's output, tensor16 (f32 rows) against tensorh16 (half rows): the same hash for a4, q4k and q6k at 17408×5120×512, 1000×5120×100 and 5120×17408×64.

  • The GEMM (metal_gemm_time --quant a4 --shape N:K:R --arm tensor16 --arm tensorh16, TFLOPS, median of 5 rounds, arm order rotated each round):

    N × K × rows tensor16 (main's) tensorh16 (this) ratio
    17408 × 5120 × 2048 15.65 23.36 1.49
    5120 × 17408 × 2048 13.78 21.76 1.58
    10240 × 5120 × 2048 15.61 23.29 1.49
    17408 × 5120 × 512 15.56 23.14 1.49
  • End to end. generate_metal -m <folder> --tokens <P ids from random.Random(P)> -n 128 --ctx C --ignore-eos, one process a run, one unscored round, then 5 rounds with the builds alternating. The difference is (half / main − 1), with its 95 % interval from Welch's t:

    model, P main tok/s this tok/s difference
    Qwen3.8-27B prompt, 512 (--ctx 2048) 274.6 383.9 +39.8 % ± 3.5
    Qwen3.8-27B decode, 512 18.38 18.32 −0.3 % ± 0.9
    Qwen3-4B prompt, 512 1738.9 2462.9 +41.6 % ± 3.7
    Qwen3-4B prompt, 4096 1357.4 1751.3 +29.0 % ± 2.2
    Qwen3-4B decode, 512 / 4096 106.16 / 88.24 106.12 / 88.06 −0.0 % ± 0.4 / −0.2 % ± 0.3

    Every run of each model and P printed the same text as main's first run (12 of 12 each). The 27B ran at --ctx 2048. At --ctx 8192 both builds are refused here since a37bf902a: the load asks 17978213808 bytes of the driver and the device's free bytes are 17170104320; a cache of 2048 rows fits. So I have no P = 4096 row for it.

  • mlx-lm in the same session, for scale (mlx_lm.benchmark -p P -g 128 -n 5, mlx-lm 0.32.2 on mlx 0.32.4): Qwen3.8-27B prompt 380.0 ± 12.5 at 512, Qwen3-4B 2392.6 ± 30.6 at 512 and 2213.4 ± 20.5 at 4096.

  • Not run: just mac-static's lint and combos stop with 69 here (no ~/opt/bloomery-mac-env.sh: no CUDA headers or Linux sysroot). The change is in crates/metal, which the Linux build does not compile.

Hardware (if the change is for a machine)

Apple M5 Pro (16-core GPU), 24 GB (hw.memsize 25769803776), Mac17,9, macOS 26.5.1 (25F80), on AC power, other apps closed during the timed runs. gemm: architecture=applegpu_g17s metal4=true matrix-units=true engine-path=tensor. Rust 1.99.1, no Metal Toolchain (metal-lib: path=source). Builds: generate_metal sha256 6cbf576ce8148c29… (main) and 2a1fc13c1477b3af… (this). Models: mlx-community/Qwen3.8-27B-4bit at 10c35caa, and mlx-community/Qwen3-4B-Instruct-2507-4bit (model.safetensors sha256 2a73c6c2…). These are development-loop numbers, taken with no timing lease.

🤖 Generated with Claude Code

yulmucoffee and others added 2 commits November 9, 2026 10:25
… source arm's NAME_h16 reads half rows

`--src` compiles its file at Metal 3.2, so a variant of gemm_tensor.metal could not be tried through it.
`--tensor-src` takes the same NAME:ROWS:ACTS:THREADS:ORDER:PATH and compiles at Metal 4, as the tensor-op
program is; `--dump-tensor-source PATH` writes that program's text as the starting point. A source arm's
`NAME_h16` runs the file's `gemm_<quant>_store_h16` over the `Half` arm's rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ast once a pass, as the simdgroup GEMMs do

gemm_tensor.metal gets the h16 entries gemm.metal has (store, resid, seg store, seg resid for every weight
type): the tile is the f16 entry's with the activation rows half, staged as they are, so a weight tile no
longer loads and range-checks the f32 rows itself. GemmPipelines takes the half-row entries on either path,
so gemm_x casts the f16 operand's rows once on the tensor-op path too; gemm_takes_half and the tensor-op
refusal go. The output bits are the f32-row entries' (the cast is the staging's checked cast).

The gate runs gemm_half_rows on the tensor-op kernels (tensor_gemm_half_rows, and the requantized types'
tensor_gemm_{a8,a4h,a8h}_half_rows), caught by the mutant tensor_h16_stage. metal_gemm_time gets the arm
tensorh16.

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: CLEAN: the tensor-op GEMMs now read the f16 operand's rows through the same shared half-row staging and cast the simdgroup path already has, the per-path branch and its dead code go, and a new bit-equality clause with a proven-red mutant pins the change on every gate row.

Checked

  • Duplicates: 7 new items checked (_h16 entries, the X template parameter, TensorHalf, SourceHalf, --tensor-src, tensor_h16_stage, check_cast); none duplicated — the staging and the cast stay gemm_shared.metal's gemm_stage_x half overload and gemm_cast_rows, one owner for both paths (gemm_tensor.metal:209); tensor_h16_stage edits the tensor program's text while the simdgroup table's equal-looking edit targets the other program, so neither is a copy.
  • Complexity: metal_gemm_time's one and Arm::parse grow by match arms (even growth); GemmPipelines::new shrinks (the path argument, the Option and takes_half go with it).
  • Silent failure: 1 site followed (mac.rs x_h16 .expect, a tool-side panic on a set-up bug); the range check stays gemm_half4, one owner, and the new clause checks the fault site and the NaN row through the cast on the tensor path too.
  • Tests: tensor_gemm_half_rows compares Rows::Cast bits with Rows::F32 on the tensor kernels, dense, residual-strided and segmented; planting tensor_h16_stage (half4 runs pairwise swapped in the tensor program's staging) turns it red — FAIL-first output for both rows is in the PR body, and the mutant's find text is occurrence-count-checked.
  • Gates: no band or pin moved; the removed tensor-path refusal left no orphan refusal test (grepped); on the tensor path the clause got stronger (a real bits comparison replaces the old "f32 rows handed back" case).
  • Performance: the tensor prefill path gains one cast launch and acts·cols·6 bytes per projection (gemm_x); the change class asks for a timed A/B and the body carries it on the contributor's card (prompt +40 %, decode −0.3 % ± 0.9, same output text 12/12).
  • Escape catalog: no script under tools/ touched; C1–C4 do not match.

Optimization headroom

  • E, less work: gemm_tensor.metal:413 — the routed tile still stages its f32 activation rows per weight tile (16 scalar loads and 4 range checks a chunk, the float overload) while the dense tiles now read cast half rows; casting the pass's rows once before the grouped GEMMs would drop that per-tile check work from the MoE prefill.

Notes

  • dryer and crapper did not run (both ModuleNotFoundError), so their checks were done by hand: no duplicate pair read, complexity read by eye.

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

@midagedev

Copy link
Copy Markdown
Owner

@yulmucoffee Thank you for this, and sorry for the slow replies on your PRs. The variant search in #593 and the readings you posted there are very helpful.

It is in the same test tree as #1180, running just lab-metal on an M4 Pro now. An M4 has no matrix units, so this Mac checks that the other paths keep their bits; your M5 Pro numbers are the evidence for the tensor-op path itself.

(Written by an AI coding agent.)

@midagedev
midagedev merged commit 2f560a7 into midagedev:main Nov 9, 2026
7 checks passed
midagedev added a commit to yulmucoffee/bloomery that referenced this pull request Nov 9, 2026
@midagedev

Copy link
Copy Markdown
Owner

Merged as 2f560a7. lab-metal ran green on an M1 Pro (macOS 27.0.1) with #1180 merged on top: every clause PASS, each mutant red on its clause. The tensor path itself rests on your M5 Pro evidence (an M1 has no matrix units). Thank you.

(Written by an AI coding agent.)

@yulmucoffee
yulmucoffee deleted the metal-gemm-tiles branch November 16, 2026 08:44
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.

2 participants