Skip to content

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

Merged
midagedev merged 16 commits into
mainfrom
mac-lfm3speed
Oct 29, 2026
Merged

midagedev merged 16 commits into
mainfrom
mac-lfm3speed

Conversation

@midagedev

Copy link
Copy Markdown
Owner

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:

  • The A4 dot reads 32-bit words. The head is a logits mat-vec, then a one-threadgroup argmax. That argmax now runs 32 SIMD groups.
  • Every quant's lane loads float4.
  • A sandwich join hands the next launch x·gain and one scale word, so the next launch loads it plain.
  • At up to 16384 live keys, the f16 cache runs a one-pass flash. It writes no partials and folds no ticket.

Prefill:

  • The GEMMs walk weight tiles fastest.
  • They dequantize A4 with one fma a value.
  • They read half activation rows, cast once a pass, through the same range-checked cast.

Open:

  • Weights load on up to eight threads beside the pipeline build.
  • A folder hands out its checked tokenizer instead of building it twice.
  • A host-fed step encodes the next host-fed token while it waits.

All but the one-pass flash keep the bits: --logits-hash is 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

  • No second copy. Each lever is in the owner every Metal model uses: the mat-vec lanes, the join, attention, the GEMM staging, logits_argmax, the arena load and the session.
  • Model code holds only architecture facts. No per-model branch. The --only lfm3 timing cut has a model-tax row with its reason.
  • Dead code is gone. The ticket head handoff and the norm-on-load readers are removed.
  • No silent failure.
    • A half cast past 65504 raises the quantizer site and gives NaN; a clause and a mutant hold it.
    • A non-finite join scale raises NormQuant.
    • A stale parked token is dropped unrun (parked_goes_stale).
  • Comments state what is true now.
  • No relaxed gate. No band moved. The one-pass flash adds a PIN(2026-10-29) derivation showing it fits inside the unchanged one-segment band. Two mutants whose code moved, a4_routed_bias_sign and tensor_range_no_raise, are retargeted to the new owner, with FAIL-first.
  • fmt and clippy clean (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:

  • lib tests: bloomery-metal 115 passed, bloomery-model-hf 118 passed, bloomery-tokenizer 53 passed.
  • gate_metal_device: PASS, including parked_goes_stale.
  • gate_metal_qwen35moe_e2e, rows lfm3 (with the deep pin), qwen35moe, qwen3moe and qwen38d: PASS.
  • e2e --mutants-all: lfm3 3 and qwen35moe 12, each red on its clause.
  • gate_metal_qwen35moe_kernels: PASS on 6 instances.
  • kernel --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.

sitting arms tg128 tok/s (depth ~6) pp512 tok/s pp4096 tok/s
attention, 8 rounds before one-pass → after 135.2 → 139.9 (+3.44 % ±0.84)
mlx-vlm 120.0
GEMM, 6 rounds before GEMM → after 141.0 → 141.4 (+0.36 % ±2.30) 1059.3 → 1225.3 (+15.67 % ±0.21) 957.2 → 1137.5 (+18.85 % ±0.58)
mlx-vlm 119.6 916.1 911.6
argmax, 40 rounds, same binary arms +0.74 % ±0.43
this head vs main, rounds 1–4 main → this 1056.4 → 1225.0 (+15.9 % ±0.3)
  • Main decoded 92.6 tok/s in the deep round's sitting.
  • This head's binary is bit-equal to the GEMM sitting's "after": logits_hash is the same over a 512-id prompt (64 tokens) and 128 decode tokens, and the texts are identical.
  • The last sitting's later rounds ran under load 20–57 from other work on the Mac. Only its first four rounds' pp512 is quoted.
  • The qwen35moe-mlx 4-layer fixture prefills +6.40 % ±0.28 (GEMM sitting).
  • qwen3moe and qwen38d are not timed: the Mac has GGUF fixtures of them only.

AI use: written and checked with Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd

midagedev and others added 14 commits October 29, 2026 20:17
… 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
@github-actions github-actions Bot added documentation Improvements or additions to documentation model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 29, 2026

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

Comment on lines +215 to +220
struct PairWeights {
gate: Vec<u8>,
up: Vec<u8>,
shared_gate: Vec<u8>,
shared_up: Vec<u8>,
}

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.

Reuse the existing PairWeights type so the four weight planes have one definition.

Suggested change
struct PairWeights {
gate: Vec<u8>,
up: Vec<u8>,
shared_gate: Vec<u8>,
shared_up: Vec<u8>,
}
use super::clauses_experts::PairWeights;

@midagedev

Copy link
Copy Markdown
Owner Author

Review fixes:

  1. d506c48: a P1 of f32 projections casts nothing and passes its f32 rows (your code). No supported Metal file has an all-F32 P1 today. A pass gate for that case is not in this PR; it is a tracker item.
  2. a5f325f: the half-rows clause and the hand-on clauses call clauses_rows' same_bits (now pub(super)). The half-rows check now also refuses unequal lengths.
  3. a5f325f: the hand-on clauses use clauses_experts' PairWeights.

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.

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

@midagedev
midagedev enabled auto-merge (rebase) October 29, 2026 16:20
@midagedev
midagedev merged commit 2dadf09 into main Oct 29, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant