Skip to content

metal: MLX 8-bit and F16-scaled folders open on Apple Silicon - #1050

Closed
midagedev wants to merge 5 commits into
mainfrom
mac-f16
Closed

midagedev wants to merge 5 commits into
mainfrom
mac-f16

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What and why

The Metal backend opened only MLX folders quantized to 4 bits with BF16 scales (MLX_A4). Many MLX folders hold other
kinds:

  • 8-bit weights: LFM3-1.7B-MLX-8bit; the routers and some layers of mixed DWQ folders such as Qwen3.6-35B-A3B-4bit-DWQ.
  • F16 scales and biases: every mlx-community Llama and Mistral folder.

This adds MLX_A8 on every launch kind MLX_A4 has. It also adds MLX_A4H/MLX_A8H (ids 2006/2007, F16 scale and bias),
and opens a session on all four kinds. A4 and A8 are each one template owner over the scale pair (A4T<Pair>,
A8T<Pair>, Pair = AffineBf16 or AffineF16). Two config keys are now read:

  • a Qwen3.6 folder's rope_parameters.type;
  • a tokenizer's tool_parser_type.

Release notes: Added — Apple Silicon opens MLX 8-bit folders, mixed 4/8-bit (DWQ) folders, and folders with F16 scales.

Code shape

  • No second copy. The BF16 and F16 kinds share one A4 and one A8 owner. Only the scale pair's widen differs.
  • Model code holds only architecture facts.
  • Dead code is gone.
  • No silent failure. These are refused by name:
    • a weight whose two companions differ in dtype, or are F32;
    • a non-finite F16 scale;
    • a 4-bit router, which the open dequantizes on the host;
    • an F16 embedding or head.
  • Comments state what is true now.
  • No relaxed gate.
  • cargo fmt and clippy are clean; the lint count did not go up.

Duplication found or removed: none.

What I ran

All on an M1 Pro (32 GB, macOS 27.0), the second maintainer Mac.

Gates:

  • cargo test -p bloomery-metal --lib: 116 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.
  • model-hf lib: 121 passed. hf: 157 passed.
  • gate_metal_device: PASS. gate_metal_qwen35moe_kernels: PASS on all 6 instances, in 630 s.
  • gate_metal_qwen35moe_kernels --mutants-all: PASS, including three new mutants: half_scale_as_bf16,
    half_bias_as_scale, half_widen_as_bf16.
  • gate_metal_qwen35moe_e2e: PASS on 4 rows.
  • e2e --mutants-all: PASS.
  • just mac-static origin/main: green after tools/hf-arch-check.py learned to read the new or-pattern arm (MlxA4 | MlxA8 | … => None); just check-recipes rc 0.

metal_scan --compare against main 904266c: added=123, removed=0, changed=59. The changed entries are the existing
A4 programs; their names are now the template's (archive +96 B each). On Qwen3.8-27B MLX 4-bit, base and this branch
gave:

  • --logits-hash 32 bit for bit the same (79b3c52ec6067bd4);
  • decode_rest_ms 111.66 / 112.04 (base) and 111.65 / 111.60 (this branch), interleaved.

Real folders (generate_metal):

  • Qwen3.6-35B-A3B-4bit-DWQ (mixed 4/8-bit) opens. Its text is coherent ("The capital of France is Paris, a city
    renowned for …"; a fibonacci body).
    • Greedy on a random-id prompt splits from mlx-lm 0.32.0's at step 2.
    • Teacher-forced over our 12 ids, mlx-lm's own forward picks each of them. At step 2 our pick leads its second
      by 0.25.
    • So the split is mlx-lm's incremental decode at a near-tie.
  • LFM3-1.7B-MLX-8bit opens, and its text is coherent. mlx-lm 0.32.0 does not load lfm3, so there are no
    reference ids.

Hardware

Apple M1 Pro, 32 GB, macOS 27.0.

AI use: written with Claude Code (Sonnet and Opus rounds implemented it; the maintainer's lead session reviewed and ran
the gates).

🤖 Generated with Claude Code

midagedev and others added 5 commits November 1, 2026 02:01
…vec modes, GEMMs, routed pairs, experts, head and embedding — with its kernel-gate clauses and three mutants

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…H), and every MLX affine kind opens a session

Llama and Mistral MLX folders store each group's scale and bias as F16; the Qwen folders store BF16. Two kinds hold the
F16 pair as stored (MLX_A4H 2006, MLX_A8H 2007): gguf's dequant takes the pair type, the planner places a weight by its
companions' dtype (a weight whose scales and biases disagree is refused by name), a plain F16 tensor widens to F32
exactly. On Metal the A4 and A8 decode owners take the pair as a parameter (A4T<Pair>, A8T<Pair>), so the H kinds are
instances on every launch kind A4 and A8 have. The open path (chain sites, the session's launched and projected
sites, the open's checks, model-hf's MLX type maps, the router's host dequant) takes MLX_A8, MLX_A4H and MLX_A8H.
Kernel-gate clauses for the H kinds and mutants half_scale_as_bf16, half_bias_as_scale, half_widen_as_bf16.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…spelling, is read at default

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…serving parses tool calls by the model's family

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added 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 placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels 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: the fixture requantizer hides NaN inputs, and the change adds redundant owners.

Must fix

1. Refuse non-finite values before requantizing

crates/metal/src/bin/gate_metal_qwen35moe_kernels/fixture.rs:307 accepts F32 NaNs through dequant_row. With an F32 embedding fixture, a group containing NaN and zeros becomes scale 0, bias 0 and zero codes. --only a8_embed compares these finite replacement bytes against the oracle's decode; the original NaN is never checked.
Rejecting the input here protects both matrix and expert reads before invalid fixtures become accepted evidence. After dequant_row(...)?; inside this loop, insert:

        if let Some(col) = out.iter().position(|v| !v.is_finite()) {
            return Err(format!("{name}: row {r} column {col} is not finite"));
        }

2. Reuse the existing missing-fixture owner

crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_requant.rs:679 copies crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_a4.rs:615 verbatim. Both decide how a missing MLX fixture fails a clause. R14 requires one owner.
Reuse the already accessible function now, before refusal behavior can diverge. Delete the new with definition and its doc comment; add:

use super::clauses_a4::with;

3. Remove the pass-through plane wrapper

crates/metal/src/bin/gate_metal_qwen35moe_kernels/clauses_experts.rs:183 adds plane_as, which only forwards every argument to Fixture::rows_as. It has two callers and no additional contract.
Removing it now avoids maintaining another name for the same operation. Delete its definition and doc comment. Replace its calls at lines 294 and 297, respectively, with:

                fix.rows_as(quant, "blk.0.ffn_gate_shexp.weight", PAIR_COLS, e.k)
                fix.rows_as(quant, "blk.0.ffn_up_shexp.weight", PAIR_COLS, e.k)

4. Keep one make-command implementation

tools/mlx-fixture.py:1134 duplicates the validation, quantizer creation, make and check sequence at tools/mlx-fixture.py:1123. Only the pair and printed label differ.
Combining these branches now keeps future validation changes in one place. Replace main with:

def main(argv):
    if argv[0:1] == ["--self-test"]:
        self_test()
        return 0
    if (argv[0:1] == ["make"] and len(argv) in (5, 6) and argv[3] == "--config"
            and (len(argv) == 5 or argv[5] == "--f16")):
        fixture, out, config_path = argv[1], argv[2], argv[4]
        for p in (fixture, config_path):
            if not os.path.isfile(p):
                print(f"mlx-fixture: {p}: no such file", file=sys.stderr)
                return EXIT_MISSING
        pair = "f16" if len(argv) == 6 else "bf16"
        quantizer = MlxQuantizer()
        layers = make(fixture, out, config_path, quantizer, pair=pair)
        label = " (f16 pairs)" if pair == "f16" else ""
        print(f"made {out}{label}: layers {[k for _, k in layers]}")
        check(out, fixture, quantizer)
        return 0
    if len(argv) == 3 and argv[0] == "check":
        out, fixture = argv[1], argv[2]
        for p in (out, fixture):
            if not os.path.exists(p):
                print(f"mlx-fixture: {p}: no such path", file=sys.stderr)
                return EXIT_MISSING
        check(out, fixture, MlxQuantizer())
        return 0
    print(USAGE, file=sys.stderr)
    return EXIT_USAGE

Non-blocking

⚠ Reproducible Metal proof: crates/metal/kernels/quant.metal:703 routes the existing A4 calculation through template pair methods. The move/split class requires program equivalence. Attach the scan comparison that establishes equivalence despite renamed entries, both exact commit hashes, and gate/A/B commands with output; the PR currently gives summaries.

Checked

Duplicates: the dryer's copied with pair and both make branches confirmed; both fixes remove code without a new owner. The plane wrapper only forwards arguments.
Silent failure: followed F32 fixture bytes through dequantization, requantization and the embedding oracle. No finite-value check blocks the NaN conversion.
Validation: the Python replacement parses and reduces main from 37 to 28 lines. Both inline replacements target added lines and preserve the method arguments. Device tests were not run here.
Gates: the new A8 band has a dated PIN. None of these findings relies on an escape-catalog exception or ledger lesson.

Card check: needs-gpu. This pull request changes crates/gpu/src/site.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)

N_EXPERTS,
)?,
shared_gate: if_shared(e, || {
plane_as(fix, quant, "blk.0.ffn_gate_shexp.weight", PAIR_COLS, e.k)

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.

Call rows_as directly; plane_as only forwards its arguments.

Suggested change
plane_as(fix, quant, "blk.0.ffn_gate_shexp.weight", PAIR_COLS, e.k)
fix.rows_as(quant, "blk.0.ffn_gate_shexp.weight", PAIR_COLS, e.k)

plane_as(fix, quant, "blk.0.ffn_gate_shexp.weight", PAIR_COLS, e.k)
})?,
shared_up: if_shared(e, || {
plane_as(fix, quant, "blk.0.ffn_up_shexp.weight", PAIR_COLS, e.k)

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.

Call rows_as directly; plane_as only forwards its arguments.

Suggested change
plane_as(fix, quant, "blk.0.ffn_up_shexp.weight", PAIR_COLS, e.k)
fix.rows_as(quant, "blk.0.ffn_up_shexp.weight", PAIR_COLS, e.k)

@midagedev

Copy link
Copy Markdown
Owner Author

Superseded by #1057. That PR holds the same change rebased on main after #1047, with this PR's four review fixes. Force push is not used on this branch.

@midagedev midagedev closed this Oct 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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 placement Placement planning: crates/placement 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