Skip to content

metal: Qwen3.8-27B decode — the plain residual hands on the normed stream, and the dense down is a residual mat-vec - #1047

Merged
midagedev merged 4 commits into
mainfrom
mac-d27dec
Oct 31, 2026
Merged

midagedev merged 4 commits into
mainfrom
mac-d27dec

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What and why

Qwen3.8-27B's Metal decode spent its step on two serial costs a plain residual does not need: the next reader's norm,
recomputed from the stream, and the dense FFN's down projection through the routed fold. Now a plain residual hands
the normed stream on through new <q>_norm_next entries (the hand-on group), and a dense FFN's down adds into the
stream as the residual mat-vec. Bits are unchanged on three models.

Release notes: Changed — Qwen3.8-27B decodes about 20 % faster on Apple Silicon (MLX 4-bit, M1 Pro).

Code shape

  • No second copy. The hand-on is Arena::hands_on for every plain residual. The down is the existing mat-vec
    residual mode.
  • Model code holds only architecture facts.
  • Dead code is gone.
  • No silent failure. Kernels::norm_next refuses a shape it has no entry for, by name.
  • Comments state what is true now.
  • No relaxed gate. Two scratch pins in check.rs carry PIN(2026-10-30) with their byte derivation.
    dense_weight_half is re-aimed at the residual mat-vec's add: the dense down's launch moved there, so the old
    fold edit no longer reached it.
  • 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. Every timed row was taken at 1-minute load ≤ 4.

  • 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).
  • gate_metal_qwen35moe_kernels --mutants-all: PASS on every instance (qwen35moe_a3b 220, qwen3moe_a3b 98, gdn48 24,
    gqa6 34, gqa4 34). The new plain hand-on clauses and their mutants are included.
  • gate_metal_qwen35moe_e2e: PASS on 4 rows.
  • e2e --mutants-all: PASS (qwen35moe 12, qwen38d 3, lfm3 3).
  • metal_scan --compare against the base, on lfm3_attn and qwen35moe_a3b: added=5 (*_norm_next), changed=0,
    same=242.
  • --logits-hash 32 is equal to the base on qwen38-27b-mlx4, LFM3-1.7B and Qwen3.6-35B-A3B.
  • just mac-static origin/main: green except lint, whose one warning came from main's qdot (fixed on main in 0305ba7).
    Every tools/check-*.sh is green after the rebase.

Decode step, ms (decode_rest_ms, ours run 2 of --repeat 2). mlx-lm 0.32.0 ran in the same sitting:

model depth base this PR mlx-lm
Qwen3.8-27B MLX 4-bit 16 111.6 89.4 91.3
Qwen3.8-27B MLX 4-bit 4096 118.6 96.2 92.5
Qwen3.6-35B-A3B MLX 4-bit 16 17.42 15.58 —
LFM3-1.7B 16 7.15 7.13 —

At depth 4096 the remaining gap is the gqa256 flash: 40 GB/s at 4096 keys, 6.6 ms a step. That is a separate change
(the flash at depth).

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

midagedev and others added 3 commits November 1, 2026 01:46
…nse FFN's down adds into the stream as a mat-vec

On a layer without a sandwich, a hand-on group after each half's out projection writes the new stream times the next
launch's norm gain and the norm's scale (`<q>_norm_next`), and the reader runs its scaled entry instead of norming on
load; a dense FFN under a plain residual sends its down through the residual mat-vec, not the fold. Every float sum
is the same, so the logits hash of 32 steps equals the base's on Qwen3.8-27B, Qwen3.6-35B-A3B and LFM3-1.7B, and
metal_scan --compare reads 5 entries added and 0 changed.

Decode on the second M1 Pro (32 GB), 4 interleaved rounds, ours run 2 of --repeat 2, mlx-lm 0.32.0:
Qwen3.8-27B MLX 4-bit, depth 16: 111.6 -> 89.4 ms a token (-20.0 %; mlx-lm 91.3); depth 4096: 118.6 -> 96.2 ms (mlx-lm
92.5). Qwen3.6-35B-A3B: 17.42 -> 15.58 ms (-10.5 %). LFM3-1.7B: 7.15 -> 7.13 ms (unchanged).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the dense down's launch under a plain residual

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo label Oct 31, 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: Dense-down launch setup is duplicated, and the new probe describes an obsolete session path.

Must fix

1. Reuse the existing output selector for the dense down

ops.rs:737 repeats dense_down_store:705: the weights, dimensions, input window and launch are identical. Only the output and mode differ; half_out already owns that decision. This is kind B, R14.
Keeping both makes every launch-shape change require two edits. Consolidating now removes two wrappers.
Delete dense_down_add and dense_down_store. Replace experts_down below, and update its doc link to refer to the existing half_out function.

pub(super) fn experts_down(&mut self, l: LayerCtx<'_>) -> Result<(), SessionError> {
    match (&l.plan.ffn.route, &l.plan.residual) {
        (FfnRoute::Router { .. }, ResidualPlan::Plain) => {
            return self.experts_fold(l.layer);
        }
        (FfnRoute::Router { .. }, ResidualPlan::Sandwich(_)) => {
            return Err(routed_sandwich(l.layer));
        }
        (FfnRoute::Dense, _) => {}
    }
    let Arena {
        layers,
        h,
        x,
        join,
        hidden,
        geom,
        ..
    } = &mut *self.arena;
    let f = &layers[l.layer].ffn;
    let (out, mode) = half_out(l, x, join, *hidden)?;
    self.kernels.matvec(
        self.enc,
        MatvecParams {
            quant: f.down_quant,
            rows: *hidden,
            cols: geom.experts.k,
            weights: all(&f.down)?,
            x: h.window(Elems(0), Elems(geom.experts.k))?,
            y: out,
            mode,
        },
    )?;
    self.close();
    Ok(())
}

2. Describe the probe's current session path

d27.rs:19 calls the fold the plain dense session's launch. experts_down now selects the residual mat-vec for that path. This is a misleading comment, kind B.
Correcting it now prevents using the comparison row as the engine baseline. Replace lines 19–20 with:

//!   at its one slot for comparison, and through `matvec` with
//!   `Mode::Residual`, the session's launch: the same sums with no per-block

Non-blocking

⚠ Attach reproducible Metal evidence: ops.rs:994 adds two dispatches per qualifying plain-residual layer per decode token, a launch-count change. The body gives gate and timing summaries without both hashes or complete commands/output. Attach those, the exact checkpoint, and the gate, mutant and base/head timing output from the stated M1 Pro so the comparison can be reproduced.

Checked

Duplicates: confirmed the dense-down copy and the existing half_out selector; dryer reported 0 candidate pairs.
Complexity: diagnostics flag new run_rows and norm_next functions and growth in timing, accounting and gate code.
Silent failure: norm_next checks quantization, nonzero whole-block input, epsilon, buffer lengths and alignment before dispatch.
Tests: the inline replacement targets added lines and is valid Rust documentation. Hardware mutation results were not independently verified.
Gates: two scratch pins carry dated byte derivations. The dense residual mutant targets m_logits through the residual mat-vec.
Escape catalog: no C1–C4 pattern in the cited hunks. No ledger lessons are in force.

Notes

Static review only. No builds or hardware tests ran here. Metal execution requires Apple Silicon/macOS.

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

Comment on lines +19 to +20
//! at its one slot, what a plain-residual dense session launches, and
//! through `matvec` with `Mode::Residual`, the same sums with no per-block

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.

Plain dense sessions dispatch the residual mat-vec; the fold row is a comparison.

Suggested change
//! at its one slot, what a plain-residual dense session launches, and
//! through `matvec` with `Mode::Residual`, the same sums with no per-block
//! at its one slot for comparison, and through `matvec` with
//! `Mode::Residual`, the session's launch: the same sums with no per-block

…ks; the probe names the residual mat-vec as the session's launch

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

Copy link
Copy Markdown
Owner Author

Both must-fix items are applied in 2bb9b34.

  1. experts_down launches the dense down once, into the output half_out picks. dense_down_add and dense_down_store are gone.
  2. The probe comment in d27.rs now names the residual mat-vec as the session's launch.

Re-run on the M1 Pro after the change: gate_metal_qwen35moe_e2e PASS on 4 rows; --mutants-all PASS (qwen35moe 12, qwen38d 3, lfm3 3; dense_weight_half red on m_logits). just mac-metal-lint clean. Every tools/check-*.sh green.

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

  • Must-fix 1 fixed: experts_down reuses half_out; both dense-down wrappers are removed.
  • Must-fix 2 fixed: the probe identifies the residual mat-vec as the session's launch.

Verdict: CLEAN: Both earlier must-fix items are resolved, and the consolidation preserves all four routing and residual cases.

Checked

Duplicates: the two dense-down wrappers are replaced by one path through the existing half_out.
Complexity: experts_down keeps routed cases in a match and shares the dense dispatch.
Silent failure: 2 refusal paths followed. Routed sandwiches and missing join buffers return named errors before dispatch; no default is added.
Behavior: dense plain writes the residual stream; dense sandwich stores into the join buffer; routed plain retains its fold. Each successful down path retains one closing call.
Tests: none added or changed, so no new mutation check applies. Hardware tests were not run here.
Gates: no pins, thresholds or cases changed in this increment.
Escape catalog: no C1–C4 pattern matches. No ledger lessons are in force.

Notes

Static incremental review only. Metal execution requires Apple Silicon/macOS.

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

@midagedev
midagedev merged commit b94bbd1 into main Oct 31, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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