Repository navigation
metal: routed experts' grouped GEMM on a 64-row tile (prompt pass +16–19 % on M4 Pro) - #777
Conversation
…chosen by the run's fragments A tile is 64 weight rows by 64 activation rows (the table cuts a group into tiles of at most 64 slots). Each SIMD group multiplies its own 16 weight rows against every live 8-row activation fragment. The K loop is picked once a tile from ceil(run / 8), so no test runs inside it, and only the live rows are staged. An output's sum order is the K loop's alone, so the outputs are bit-equal to the 32-row tile's. A tile the table cannot write raises the expert-id site and stores nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…t-equal to the 32-row tile The 32-row tile is kept as the oracle. The clause runs both over a 136-row scene whose runs cross every fragment count, 8k and 8k+1, and groups of two and three tiles. Two new mutants are red on it (upper rows read the lower half's; a full last fragment leaves its last row unstaged). Four existing mutants' find texts follow the moved lines with the same defects. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…te table Run lengths follow U rows a pass with an optional skew; the ROUTED variants remove the multiply, the staging or the weight staging one at a time. 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: an accepted skew hangs the timing tool; the new probe also duplicates existing facts.
Must fix
1. Sample distinct experts without rejection
crates/metal/src/bin/metal_gemm_time/routed.rs:135
metal_gemm_time --routed --rows 1 --skew 2000 passes the finite, nonnegative check in mac.rs:451. All weights except rank zero become zero; the loop can never collect eight distinct experts, so no timing is printed.
Fixing the sampler now makes skew sweeps terminate. Replace picks with bounded sampling without replacement, rescaling the remaining weights at each pick:
fn picks(rows: usize, skew: f64, seed: u64) -> Vec<u32> {
let mut rng = Rng::new(seed);
let mut rank: Vec<usize> = (0..EXPERTS).collect();
for i in (1..EXPERTS).rev() {
let j = usize::try_from(rng.next() % (i as u64 + 1))
.expect("shuffle index fits usize");
rank.swap(i, j);
}
let mut ids = Vec::with_capacity(rows * EXPERT_SLOTS);
for _ in 0..rows {
let mut available: Vec<usize> = (0..EXPERTS).collect();
for _ in 0..TOP_K {
let best = available.iter().map(|&e| rank[e]).min()
.expect("unpicked experts remain");
let mut total = 0.0;
let cdf: Vec<f64> = available.iter().map(|&e| {
total += ((best + 1) as f64 / (rank[e] + 1) as f64).powf(skew);
total
}).collect();
let u = (rng.next() >> 11) as f64 / (1u64 << 53) as f64 * total;
let at = cdf.iter().position(|&c| c > u)
.expect("remaining weights have positive mass");
ids.push(u32::try_from(available.swap_remove(at))
.expect("expert id fits u32"));
}
ids.push(u32::try_from(EXPERTS).expect("shared id fits u32"));
}
ids
}2. Reuse the engine's geometry owners
crates/metal/src/bin/metal_gemm_time/routed.rs:49 repeats geometry exported by crates/metal/src/kernels/router.rs:15, crates/metal/src/kernels/experts_geom.rs:11 and crates/metal/src/kernels/routed.rs:36.
The capacity calculation at routed.rs:220 repeats the existing kernels/routed.rs:52 owner. RArm.tile at line 75 is redundant: ship and all five routed variants use height 64. R14 applies.
Reusing these owners now keeps the probe consistent when kernel geometry changes. Delete the six geometry constants, RArm.tile, and its two initializers; update RArm's doc sentence. Replace the existing kernels import with:
use bloomery_metal::kernels::{
EXPERT_K, EXPERT_SLOTS, GEMM_THREADS, Quant,
ROUTED_IDS as TOP_K, ROUTED_ROWS as TILE_ROWS, TABLE_THREADS, route_tiles,
};
use bloomery_metal::kernels::router::{EXPERTS, K as HIDDEN};Make the existing table-thread constant public in kernels/routed.rs and re-export it from kernels/mod.rs:
pub const TABLE_THREADS: usize = 1024;pub use routed::TABLE_THREADS;Replace pass's capacity calculation with:
let max_tiles = route_tiles(slots, EXPERTS);3. Give the hash recurrence one owner
crates/metal/src/bin/metal_gemm_time/routed.rs:374 copies the recurrence in crates/metal/src/bin/metal_gemm_time/mac.rs:789. R14 applies.
Sharing the helper now prevents dense and routed hashes from diverging. Move the existing fnv definition into mac.rs, add fnv to routed.rs's super import, and replace the dense fold with the call below:
fn fnv(h: u64, v: &[f32]) -> u64 {
v.iter().fold(h, |h, w| {
(h ^ u64::from(w.to_bits())).wrapping_mul(0x0000_0100_0000_01B3)
})
}let hash = fnv(0xCBF2_9CE4_8422_2325, &words);Non-blocking
⚠ Attach the geometry evidence: crates/metal/kernels/gemm_routed.metal:278
Shared memory per group grows from 7,680 to 10,240 bytes for f16 and 13,824 to 18,432 for f32 [derived]. The occupancy/geometry class requires resource proof, the owning gate and timed A/B. Add raw Metal gate and A/B output plus the exact model path; the body provides summaries.
Checked
Duplicates: geometry and hash copies confirmed; dryer reported zero pairs.
Complexity: diagnostics flag grouped_launch (37), routed::launch (36), pass (28), run (22); mac::run grows 40→44.
Silent failure: invalid row/skew parses return errors; the sampler's reachable hang is above.
Tests: grouped_oracle checks pair/down outputs against the old tile bit for bit and rejects unwritten sentinels. Its two new mutants alter upper-row addressing and last-row staging; the comparisons detect both.
Gates: no bands moved. Metal execution was not run during validation.
Escape catalog: C1–C4 do not match the retained findings.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
…he engine's geometry A large --skew made the rejection sampler spin forever once only one expert had weight. Each pick now draws from the experts not yet picked, with weights relative to the best remaining one. The probe takes the expert, router and table geometry from the kernels' owners (TABLE_THREADS is now public) and the table capacity from route_tiles; the dense and routed hashes share one fnv. 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:
- Sampling hang: fixed by bounded sampling without replacement and rescaling each remaining distribution.
- Geometry duplication: fixed by reusing engine constants and
route_tiles, and removingRArm.tile. - Hash duplication: fixed by sharing
fnvbetween dense and routed outputs.
Verdict: CLEAN: all earlier must-fix items are resolved, and the new commits introduce no blocking defect.
Checked
Duplicates: 1 relocated function checked (fnv); one recurrence remains. Geometry uses existing owners. Dryer reported 0 pairs.
Complexity: diagnostics flag grouped_launch (37), routed::launch (36), pass (28), routed::run (22), and mac::run (40→44). Their branch growth predates this increment; the capacity-owner substitution and field removals add no branches.
Silent failure: 2 parse-to-Option sites followed into named errors. The new sampler retains a weight of 1 at every pick and removes each selected expert; finite large skews cannot exhaust its probability mass or repeat an id.
Tests: no tests changed in this increment, so no new test mutation check applies.
Gates: no pins or bands moved. All five routed variants retain tile height 64, preserving the capacity calculation.
Performance: this increment changes timing-tool setup and exports; it adds no engine hot-path work.
Escape catalog: C1–C4 do not match this increment.
Notes
Validation was static. 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)
The routed experts' grouped GEMM for the Metal prompt pass, on a 64-row tile. Part of #593.
The expert GEMMs took half of a 2048-row pass on the M4 Pro and ran well below the dense GEMM's rate. The cost was not the weight side: a probe that removed the weight staging moved the time by 5 %. It was the 32-row tile and a liveness test on every fragment inside the K loop.
grouped_oracleholds this against the old tile, kept as an oracle in the gate.metal_gemm_time --routedtimes the grouped GEMM over a synthetic route table.Geometry: threadgroup memory per tile grows from 7,680 to 10,240 bytes (f16 operands) and from 13,824 to 18,432 (f32); 128 threads as before. The timed A/B below is the evidence for the occupancy change.
Gates (M1 Pro, fixture), rc 0:
just lab-metal(112 kernel mutants, each red on its clause; two new ones red ongrouped_oracle),just lab-metal-e2e(9 mutants,q_*unchanged),mac-metal-lint,check-unsafe,check-comments,check-recipes,cargo fmt --check.M4 Pro 48 GB, Qwen3.6-35B-A3B MLX 4-bit, development-loop numbers (not public). Ops timed one command buffer at a time (
--pass-times U, first pass):Real prompts, interleaved in one sitting, arm order rotated:
mlx-lm in the same sitting: pp512 940.8 tok/s, pp4096 1038.2 tok/s. Decode control (
--prompt "The capital of France is" -n 64), at the start and end: base 102.1 / 100.2, this 100.2 / 100.6 tok/s. Decode does not run the grouped GEMM.Evidence: base
generate_metalat a3353a0 (main after #773), this branch at 66867dc31 (the rebase moved no file undercrates/metal); macOS 27.0.1, Apple M4 Pro 48 GB;generate_metal --prompt "$(cat p.txt)" -n 8 --ctx 8192withBLOOMERY_REF_MODELset, release build, one process per run; prompts are README text; model fileQwen3.6-35B-A3B-mlx4-00001-of-00001.gguf(the MLX 4-bit weights as one GGUF split). Load (vm.loadavg, 1 min) was 3.0–5.1 during the runs.The kernel and the gate were written with a Claude Code round and reviewed by the maintainer.
🤖 Generated with Claude Code
https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ