Skip to content

metal: Qwen2 MLX folders (q/k/v bias, raw NEOX, groups 5–7 at head 128 and 7 at head 64) and tied heads open - #1131

Merged
midagedev merged 3 commits into
mainfrom
metal-qwen2-tied
Nov 2, 2026
Merged

midagedev merged 3 commits into
mainfrom
metal-qwen2-tied

Conversation

@midagedev

@midagedev midagedev commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Metal에서 Qwen2/Qwen2.5-Coder MLX 폴더(q/k/v bias)와 tied head 모델(Qwen3-4B-2507 등)이 열리고, mlx-lm과 같은 토큰을 냅니다.

What and why

Several mlx-community dense folders were refused on Metal or had no e2e row:

  • Qwen2.5-Coder-7B was refused for its attention group (28 query heads over 4 key heads = group 7).
  • Qwen2's q, k and v projections carry a bias.
  • Qwen3-4B-Instruct-2507 and Qwen3-0.6B tie the head to the embedding (no lm_head).

This change adds four things:

  • Bias. The q, k and v bias is added in f32 after P1 (kernels/bias.metal).
  • Raw-NEOX prologue. It serves a NEOX layer with no head norm.
  • New attention instances. The attention rows serve head 128 at groups 5, 6 and 7, and head 64 at group 7.
  • Tied head. A folder with no lm_head reads its head from the embedding.

tools/mlx-logits.py had two problems:

  • floatize dropped a Linear's own bias, so a Qwen2 pin was dumped without its biases. This is fixed.
  • A new simulate subcommand runs the rounding rule against a pin. It gives the qwen2 row its band. The summed rule overstates the band for Qwen2, because its k bias makes the q·k product large in layer 0 (1.1 against a cap of 0.15). The simulated rule's worst is 1.96e-2, so the band is 0.02.

Release notes: Added — Metal opens Qwen2 / Qwen2.5-Coder MLX folders and MLX folders with a tied head (Qwen3-4B-Instruct-2507, Qwen3-0.6B).

Code shape

  • No second copy. Qwen2 maps through the Llama map's owner as data (bias, NEOX pairs, no head norm). The raw-NEOX arm is one more Prologue variant of the shared attention body.
  • Model code holds only architecture facts.
  • Dead code is gone.
  • No silent failure.
    • A head norm over NORM pairs stays a compile error.
    • A bias row of the wrong width is refused by name. Mutant H3 checks this: it is red on bias_rows.
    • Norm rows that are not whole float4s are refused by name. Mutant H1 checks this: it is red on rows_refusals.
  • Comments state what is true now.
  • No relaxed gate.
    • The qwen2 band is derived by simulation (PIN(2026-11-02), with the derivation in row.rs). It is not fitted.
    • The lab-metal bounds were raised with a dated reason: 14 instances now take 1185 s and 5461 s on an M1 Pro.
  • fmt and clippy clean; lint ratchet 0.

Duplication found or removed: none.

What I ran

Second Mac (M1 Pro, 16-core GPU, macOS 26), on the merged tree before the rebase. crates/metal is unchanged by the rebase.

  • gate_metal_qwen35moe_kernels: PASS on 14 instances in 1185 s.
  • --mutants-all: PASS, all 780 mutants red on their own clause, in 5461 s. Per instance: 239/105/25/42/42/21/4/38/42/48/42/42/42/48.
  • lab-metal-e2e: 8 rows PASS (qwen35moe, qwen3moe, qwen38d, lfm3, llama, qwen3, qwen3t, qwen2), in 1047 s.
    • qwen2 m_logits: max |logit| difference 1.687e-2 at step 1, band 0.02.
    • Every row's --mutants-all is PASS. bias_skipped is red on the qwen2 row: step 0 picked 20415, the pin's argmax is 48298.
  • One-off host mutants: H1 is red on rows_refusals, H3 is red on bias_rows.
  • --plan: Qwen2.5-Coder-7B, Qwen3-4B-2507, Qwen3.5-4B, Qwen3-0.6B, Llama-3.2-1B and Qwen2.5-0.5B all print plan: opens.
  • Greedy ids of the full folders against mlx-lm 0.32.0: Qwen2.5-Coder-7B-Instruct 16/16 EQUAL, Qwen3.5-4B 16/16 EQUAL.
  • just remote-static 7394839c9: ok, 1908 s.

Box, fixture tier, before the rebase:

  • narrow-scan: the 4 scan bins are identical (--no-jit), which narrows 158 gates to 93.
  • gate-batch --tier fixture --ledger: 106 items, red 2. Both reds are pre-existing on main:
    • gate-gpu-qwen38-twocard is red the same way on base 7394839.
    • gate-gpu-qwen4exp-nvfp4-cut ended rc 66: the box has no fixture file for it.
  • 35 items are deferred to the real tier, and 6 need an env variable the batch does not set.

After the rebase onto 0272f6e:

  • narrow-scan: the 4 bins are identical (--no-jit).
  • gate-batch --tier fixture --ledger: 107 items, red 11. None of the reds comes from this PR:
    • gate-ops (a_hybrid_trunk_prices_its_attention_planes_in_the_cache_format, 8745492 vs 8695808) is red the same way on base 0272f6e.
    • gate-qwen4exp-meta (qwen36_q8_bp_on_two_3090s), gate-gpu-qwen35moe-e2e and its 2 variants, and 5 gate-gpu-qwen35moe-leg variants are red on stale recorded budgets and byte pins. These are the Qwen3.5 GDN plan bytes that 1b28971 moved; model: the qwen35moe trunk and two-3090 plan pins count each GDN layer's carry and lane stamp #1134 re-pins them. This PR does not touch the qwen35moe plan or place code.
    • Run directly at BLOOMERY_TIER=fixture, just gate-gpu-qwen35moe-e2e gives identical results on base and head. gate_qwen35moe_e2e is PASS on both. The generate_qwen3moe hw test is red on both, because it refuses BLOOMERY_CARD_BUDGET, which the fixture tier sets.
    • gate-gpu-qwen4exp-nvfp4-cut has no fixture set on the box, as before.
  • Second Mac: just remote-static origin/main is ok (1388 s). cargo test -p bloomery-metal --lib: 130 passed. The 1 failure is a_cached_checkpoint_repo_is_its_folder_with_nothing_fetched, which depends on the machine's HF cache, as in metal: the prefill attention fills its MMA rows with real (position, head) pairs and rescales elementwise #1107.

Review fixes (fe030c8) were rerun on the second Mac:

  • gate_metal_qwen35moe_kernels: PASS on 14 instances in 888 s.
  • --mutants-all [lfm3_attn]: PASS, 21 mutants.
  • lab-metal-e2e: PASS on 8 rows, with every d_count group and dispatch count unchanged (35/35/31/171/31/31/31/35). qwen2 m_logits is 1.687e-2 against a band of 0.02. Each row's mutants are red.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CjHkkntc2L1xRN21xB39mj

midagedev and others added 2 commits November 2, 2026 17:10
…simulate runs the rounding rule against a pin

floatize built every QuantizedLinear as nn.Linear(bias=False), so a dump of Qwen2 lost its q, k and v biases.
simulate runs the dump's model in f32 with each projection's and the head's input and the stored keys and values
rounded to f16, and prints max |sim - pin| per step: the band of an e2e row whose summed rule overstates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CjHkkntc2L1xRN21xB39mj
…s open on Metal — q, k and v biases, the raw NEOX prologue, head-128 groups 5 to 7 and head-64 group 7

A dense Llama-map folder whose attention carries q, k and v biases (Qwen2, Qwen2.5-Coder) adds them in f32 after P1;
a NEOX layer with no head norm runs the raw-NEOX prologue; the attention rows serve head 128 at groups 5, 6 and 7 and
head 64 at group 7; a folder with no lm_head reads its head from the embedding. The e2e gate gains the qwen3t row
(Qwen3-4B-Instruct-2507, tied head) and the qwen2 row (Qwen2.5-Coder-7B-Instruct, band from the simulated rounding
rule), the kernel gate the bias rows and the new attention instances with their mutants, and lab-metal's bounds follow
the fourteen instances' walls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CjHkkntc2L1xRN21xB39mj
@github-actions github-actions Bot added documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Nov 2, 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: Three duplicate implementations, missing timeout PIN attribution, and a false router-refusal comment need correction.

Must fix

1. Reuse the P1 dispatcher for every mixer

crates/metal/src/arch/qwen3moe/ops.rs:599 duplicates crates/metal/src/arch/qwen3moe/ops.rs:1120 and conv_in at line 1188 (R14). All three select the same step/rows P1 operation.
Reuse the existing owner to remove both copies. Replace the two trait methods:

fn delta_in(&mut self, l: LayerCtx<'_>, _: &DeltaPlan) -> Result<(), SessionError> {
    self.attn_p1(l)
}
fn conv_in(&mut self, l: LayerCtx<'_>, _: &ShortConvPlan) -> Result<(), SessionError> {
    self.attn_p1(l)
}

2. Extend the existing fixture unpacker

crates/model-hf/src/arch/llama/mod.rs:1538 copies crates/model-hf/src/arch/llama/mod.rs:1228, including metadata removal and U32 shape expansion; only the filter differs (R14).
Keep one fixture reader. Delete unpacked_with_biases, use unpacked at its four calls, update the weight-only doc, and replace the existing definition:

fn unpacked(mut fixture: Json) -> Vec<(String, Vec<usize>)> {
    fixture.as_object_mut().unwrap().remove("__metadata__");
    entries(&fixture)
        .into_iter()
        .filter(|(name, _, _)| name.ends_with(".weight") || name.ends_with(".bias"))
        .map(|(name, dtype, mut shape)| {
            if dtype == safetensors::Dtype::U32 {
                *shape.last_mut().unwrap() *= 8;
            }
            (name, shape)
        })
        .collect()
}

3. Use one prologue-to-oracle mapping

crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_window.rs:589 repeats the variant mapping and invalid-prologue error in crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_attention.rs:400 (R14). Only the optional-gain check belongs here.
Delegate to remove the second mapping. Remove the norm_rope, rope_norm_pairs and rope_neox imports and replace:

fn prologue(
    attn: &AttnGeom,
    x: &[f32],
    gain: &Option<Vec<f32>>,
    eps: f32,
    rope: &[f32],
) -> Result<Vec<f32>, String> {
    if attn.prologue().is_some() && attn.qk_norm != gain.is_some() {
        return Err("the scene's gains do not match the instance's head norm".to_string());
    }
    super::clauses_attention::prologue_of(attn, x, gain.as_deref().unwrap_or(&[]), eps, rope)
}

4. Attribute the raised timeout limits with PIN

justfile:97 explains the raised limits but lacks the required PIN(YYYY-MM-DD): marker from CONTRIBUTING.md.
Add the marker to complete this gate change's attribution. Replace that line:

# PIN(2026-11-02): on an M1 Pro (16-core GPU) at fourteen instances the gate took 1185 s and the mutants step (780 mutants)

5. Remove the obsolete dense-router refusal claim

crates/metal/src/instance.rs:1751 says widths 896, 1536 and 3584 fail router validation. The new router_geom::k uses UNLAUNCHED_K for every dense FFN, independently of its hidden width.
Remove the obsolete restriction before it guides another test. Replace lines 1752–1753 with:

    /// compiles at; a dense FFN's unlaunched router uses `UNLAUNCHED_K`.

Optimization headroom

  • G, per-launch and per-sync fixed cost: crates/metal/src/arch/qwen3moe/ops.rs:609, measure folding the bias add into P1's stores. For full 28-layer Qwen2.5-Coder-7B decode, this removes 28 launches and 28 × (3584 + 512 + 512) × 8 = 1,032,192 activation bytes per token [derived].

Checked

Duplicates: three repeated facts confirmed; all proposed reuses remove code. Dryer identifies the P1 pairs.
Complexity: no complexity-based finding remains to validate.
Silent failure: the proposed prologue delegation preserves both named refusals.
Tests: replacements checked statically; existing Llama and Qwen3 fixtures contain no .bias entries, so widening unpacked preserves those inputs. Tests were not run during validation.
Gates: timeout bounds rise from 900/1800 s to 1800/8400 s; item 4 supplies the missing PIN marker.
Escape catalog: C1–C4 do not match these findings.

Notes

Hardware gates were not run here. The PR reports Mac runs before the rebase; head reruns remain pending. The required NVIDIA gate command/output and card evidence are absent.

Card check: needs-gpu. This pull request changes crates/gpu/src/arch/qwen3moe/body.rs, crates/gpu/src/arch/qwen3moe/dispatch.rs, crates/gpu/src/arch/qwen3moe/plan.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

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

Comment thread justfile Outdated
# selects it. The mutants step runs every registered instance's mutants in one process under one bound; 2026-10-27 it
# took 945 s on an M1 Pro (16-core GPU) at two instances and 220 mutants, over the 900 s default, so it runs at 1800.
# selects it. The gate and its mutants step each run every registered instance in one process under one bound;
# 2026-11-02 on an M1 Pro (16-core GPU) at fourteen instances the gate took 1185 s and the mutants step (780 mutants)

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.

The raised gate limits need the PIN marker required by CONTRIBUTING.md.

Suggested change
# 2026-11-02 on an M1 Pro (16-core GPU) at fourteen instances the gate took 1185 s and the mutants step (780 mutants)
# PIN(2026-11-02): on an M1 Pro (16-core GPU) at fourteen instances the gate took 1185 s and the mutants step (780 mutants)

Comment thread crates/metal/src/instance.rs Outdated
Comment on lines +1752 to +1753
/// takes (a multiple of 1024); the files' own (896, 1536, 3584) are the
/// router's refusal, which this test does not pin.

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.

Dense FFNs now use UNLAUNCHED_K for the unused router, so the stated hidden-width refusal no longer exists.

Suggested change
/// takes (a multiple of 1024); the files' own (896, 1536, 3584) are the
/// router's refusal, which this test does not pin.
/// compiles at; a dense FFN's unlaunched router uses `UNLAUNCHED_K`.

…ure unpacker keeps biases, the window clauses map a prologue through prologue_of, the lab-metal bounds carry their PIN

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CjHkkntc2L1xRN21xB39mj

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

  • Fixed 1: delta_in and conv_in reuse the existing attn_p1 dispatcher.
  • Fixed 2: unpacked_with_biases is removed; its callers use the extended unpacked.
  • Fixed 3: the window oracle delegates to prologue_of and preserves gain validation.
  • Fixed 4: the timeout attribution includes PIN(2026-11-02):.
  • Fixed 5: the dense-router comment describes UNLAUNCHED_K correctly.

Verdict: CLEAN: The incremental changes preserve behavior and resolve all five previous must-fix findings.

Checked

Duplicates: no new definitions. The two P1 dispatchers and window oracle reuse existing owners; the duplicate fixture helper is removed.
Complexity: the dispatcher and oracle changes remove repeated branches.
Silent failure: 1 added fallback followed. The empty gain slice is unread on raw prologues; missing required gains and invalid prologues return named errors.
Tests: static mutation analysis of crates/model-hf/src/arch/llama/mod.rs:143: making qkv_bias false makes the Qwen2 mapping test fail. Fixture checks confirmed no biases in the existing Llama/Qwen3 inputs and all 84 Qwen2 biases. An eight-case model check preserved every prologue/gain dispatch and error result.
Gates: no threshold changes in this increment; the previously requested timeout PIN is present.
Performance: both P1 delegations call the same step and row methods as before and add no allocation, copy or launch.
Escape catalog: C1–C4 do not match the incremental changes.

Notes

Rust tests and hardware gates were not run here. The PR reports Metal reruns after the fixes. NVIDIA evidence remains incomplete: no nvidia-smi line or commit-paired gate command output.

Card check: needs-gpu. This pull request changes crates/gpu/src/arch/qwen3moe/body.rs, crates/gpu/src/arch/qwen3moe/dispatch.rs, crates/gpu/src/arch/qwen3moe/plan.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

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

@midagedev
midagedev merged commit 0f7e6b1 into main Nov 2, 2026
8 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 gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card 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