Repository navigation
metal: faster decode and prefill in the common owners (LFM3-1.7B on an M1 Pro: decode 92.6 → ~140, pp512 1059 → 1225 tok/s) - #972
Conversation
…cuts of the A4 row loop and the head Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
… 32-bit words, and the head is a logits mat-vec then a one-threadgroup argmax The same bits in fewer, wider loads; a launch refuses A4 weights off a 4-byte boundary by name. The head's ticket handoff (one fence and atomic a threadgroup) goes: logits_argmax reduces the stored logits with the same packed key, the lower row on ties, the logit site raised for a non-finite logit. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…float4 The same values in the same order; a mat-vec, segment, pair, head or headnorm launch refuses an input or gain window off a 16-byte boundary by name. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
… gain and one scale word, so P1, the gate-up and the head load it plain The join already reads the whole stream; the readers no longer recompute its RMS in every threadgroup. A reader multiplies its dot by the scale where the norm-on-load did, so the bits are the same. A plain residual takes none of it. The kernel gate's handon clauses hold the readers' bits, the NaN and overflow cases and the refusals. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…its, so a bit-identical change is proved by one compare Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…p a query head, so a short-depth decode and rows launch write no partial Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…, copied, instead of building it from the keys again Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…ipeline build, and a host-fed step encodes the next host-fed token while it waits Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…float4 quads Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…h one fma a value, and read their activations as half rows cast once a pass Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…yer cut against mlx-lm Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
… the code the GEMMs now stage through (dequant16's bias, gemm_half4's raise) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
There was a problem hiding this comment.
Verdict: MUST_FIX: An unused half cast can poison supported F32 prefill, and the new gates duplicate existing owners.
Must fix
1. Skip the half cast when P1 has only F32 projections
crates/metal/src/arch/qwen3moe/ops/rows.rs:191 runs gemm_x before checking the projections' types. The checker admits F32 P1 projections, whose branch reads the original F32 rows. On the simdgroup path, an all-F32 P1 with a finite normalized value above 65504 raises QuantColumn from the unused cast; Session::pass_with returns Fault and poisons the session. A residual row of ones, gain 65536 and epsilon 1e-5 produce about 65535.67 in f32 [derived].
Fix this before valid model files acquire this failure. Replace the added let x block with:
let x = if p1.parts.iter().any(|part| part.quant != Quant::F32) {
self.kernels.gemm_x(
self.enc,
GemmXParams {
x: rows.xn.window(Elems(0), Elems(m * *hidden))?,
x_stride: *hidden,
cols: *hidden,
acts: m,
operand: PASS_OPERAND,
half: &mut rows.xh,
fault: &faults[slot],
layer: layer_word(l),
},
)?
} else {
crate::kernels::GemmX::F32 {
x: rows.xn.window(Elems(0), Elems(m * *hidden))?,
stride: *hidden,
}
};Add a pass gate with all-F32 P1 and finite activations above the half range. Restoring the unconditional cast must make it fail.
2. Reuse the existing bit-comparison checker (R14)
crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_handon.rs:343 and the closure at crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_gemm.rs:1255 repeat crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_rows.rs:342. The new closure also accepts a matching prefix of unequal-length slices.
Reuse the checker now so bit-identity checks have one implementation. Make the existing definition visible with this complete replacement:
pub(super) fn same_bits(what: &str, got: &[f32], want: &[f32]) -> Result<(), String> {
if got.len() != want.len() {
return Err(format!("{what}: {} words, not {}", got.len(), want.len()));
}
match got.iter().zip(want).position(|(g, w)| g.to_bits() != w.to_bits()) {
None => Ok(()),
Some(i) => Err(format!(
"{what}[{i}] is {:?} ({:#010x}), expected {:?} ({:#010x})",
got[i], got[i].to_bits(), want[i], want[i].to_bits()
)),
}
}Delete hand-on's copy and add:
use super::clauses_rows::same_bits;Replace the GEMM closure with:
let same = |what: &str, want: &[f32], got: &[f32]| {
super::clauses_rows::same_bits(what, got, want)
};3. Reuse the existing pair-weight type (R14)
crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_handon.rs:215 duplicates the four fields and purpose of crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_experts.rs:128.
Remove the second type now so a weight-plane change needs one definition. Delete the new struct and import the existing type; the local constructor can remain:
use super::clauses_experts::PairWeights;Non-blocking
⚠ Attach the measurement evidence: crates/metal/kernels/attention.metal:1366 changes the attention sum order; the head changes launch count and occupancy. The body supplies summaries without both commit hashes or the commands and output. Attach the owning gate runs and timed A/B on the named Mac, including the exact model file and hardware/runtime identification. This makes the claimed gains reproducible before the common paths spread to more models.
Checked
Duplicates: both existing owners and the added copies confirmed. Each proposed reuse removes elements.
Complexity: no finding rests on a complexity score.
Silent failure: followed the cast's fault through pass_with to session poisoning.
Tests: the all-F32 P1 regression needs a pass gate that fails when the unconditional cast is restored.
Gates: the measurement-evidence request remains advisory.
Escape catalog: none of the cited findings matches C1–C4.
Notes
Metal compilation and hardware gates were not run during validation.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| struct PairWeights { | ||
| gate: Vec<u8>, | ||
| up: Vec<u8>, | ||
| shared_gate: Vec<u8>, | ||
| shared_up: Vec<u8>, | ||
| } |
There was a problem hiding this comment.
Reuse the existing PairWeights type so the four weight planes have one definition.
| struct PairWeights { | |
| gate: Vec<u8>, | |
| up: Vec<u8>, | |
| shared_gate: Vec<u8>, | |
| shared_up: Vec<u8>, | |
| } | |
| use super::clauses_experts::PairWeights; |
…alf rows Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
…' same_bits and clauses_experts' PairWeights Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
|
Review fixes:
Evidence: the PR body's sittings ran on the lead Mac (M1 Pro 32 GB, macOS 27.0.1, LiquidAI/LFM3-1.7B-MLX-4bit), with interleaved arms in one sitting each. The gate runs are listed under "What I ran"; the fixed head's gates are running now. |
There was a problem hiding this comment.
Since the last review:
- #1: the all-F32 cast failure is fixed. Its requested regression gate is still missing; see below.
- #2: fixed. Both bit-comparison copies now use
clauses_rows::same_bits. - #3: fixed. Hand-on clauses now use
clauses_experts::PairWeights.
Verdict: CLEAN: The incremental changes resolve the three blocking code findings and introduce no proven blocking defect.
Non-blocking
⚠ Add the all-F32 regression gate: crates/metal/src/arch/qwen3moe/ops/rows.rs:193 skips the unused cast, but no test exercises this branch with values above the half range.
Add a pass case with all-F32 P1, finite normalized values above 65504, and bounded projection outputs. Assert success; restoring the unconditional gemm_x call must make it fail. This prevents the same failure from returning.
Checked
Duplicates: 0 new named definitions. The bit comparisons reuse clauses_rows::same_bits; hand-on reuses clauses_experts::PairWeights. The dryer candidates are outside this increment's added lines.
Complexity: gemm_half_rows delegates its comparison; rows_p1 adds one quant-type guard. The other crapper targets are unchanged by this increment.
Silent failure: invalid norms still fault through pass_with; mixed-quant P1 retains the checked half cast. Other projection sites refuse F32.
Tests: gemm_half_rows checks cast-output bits and quantized range faults. It does not exercise the all-F32 P1 bypass or catch restoration of the unconditional cast.
Gates: no pins, thresholds or gate cases moved in this increment.
Escape catalog: no C1–C4 patterns matched.
Notes
Metal compilation and hardware gates were not run; these paths require macOS.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
What and why
This PR makes Metal decode and prefill faster, measured on LFM3-1.7B. Every change sits in a common Metal owner, so every Metal model's programs take it.
Decode:
Prefill:
Open:
All but the one-pass flash keep the bits:
--logits-hashis equal across them. The one-pass flash moves the attention sum order only, inside every unchanged band.Release notes: Changed — Metal decodes and prefills faster: LFM3-1.7B MLX 4-bit on an M1 Pro decodes 92.6 → about 140 tok/s, and prefills pp512 1059 → 1225 and pp4096 957 → 1138 tok/s.
Code shape
logits_argmax, the arena load and the session.--only lfm3timing cut has amodel-taxrow with its reason.parked_goes_stale).PIN(2026-10-29)derivation showing it fits inside the unchanged one-segment band. Two mutants whose code moved,a4_routed_bias_signandtensor_range_no_raise, are retargeted to the new owner, with FAIL-first.bloomery-metal, all targets, pipeline-scan and encode-trace): 0 warnings.Duplication found or removed: none.
What I ran
On a second Mac (M-series, macOS 27), at the pre-rebase head and again after the rebase:
bloomery-metal115 passed,bloomery-model-hf118 passed,bloomery-tokenizer53 passed.gate_metal_device: PASS, includingparked_goes_stale.gate_metal_qwen35moe_e2e, rows lfm3 (with the deep pin), qwen35moe, qwen3moe and qwen38d: PASS.--mutants-all: lfm3 3 and qwen35moe 12, each red on its clause.gate_metal_qwen35moe_kernels: PASS on 6 instances.--mutants-all: lfm3_attn 20, gdn48 24, gqa6 34 and gqa4 34 pass. qwen35moe_a3b and qwen3moe_a3b pass except the two retargeted mutants above.just remote-static origin/main: green.Hardware
Lead Mac: Apple M1 Pro 32 GB, macOS 27.0.1. LFM3-1.7B-MLX-4bit, its folder as downloaded. mlx-vlm 0.7.11 on mlx 0.32.4. Arms interleaved in one sitting each, order rotated, 95 % interval on the paired difference. These are development-loop numbers: the Mac has no timing runner.
logits_hashis the same over a 512-id prompt (64 tokens) and 128 decode tokens, and the texts are identical.AI use: written and checked with Claude Code.
🤖 Generated with Claude Code
https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd