Skip to content

Metal: MLX 4-bit (affine) qwen35moe files decode on Apple Silicon - #757

Merged
midagedev merged 26 commits into
mainfrom
mac-mlx-a4
Oct 24, 2026
Merged

midagedev merged 26 commits into
mainfrom
mac-mlx-a4

Conversation

@midagedev

Copy link
Copy Markdown
Owner

What and why

Mac port (#593): the Metal backend reads MLX's affine 4-bit format, so a Qwen3.6 MLX checkpoint converted to a GGUF split (MLX_A4 weights, MLX_A8 router) opens and decodes on the Metal device.

  • gguf gains the MLX_A4 and MLX_A8 block types: groups of 64 codes, then a BF16 scale and a BF16 bias (w = s·q + b). gguf owns their block bytes and value counts; every other reader takes them from its row.
  • hf and model-hf read an MLX checkpoint folder into the qwen35moe map (Family::Qwen36 beside Qwen38, with Qwen3.8's MTP draft kept). tools/mlx-fixture.py writes the qwen35moe fixture as an MLX folder for the gates.
  • Metal: one decode owner per quant (kernels/quant.metal). The mat-vec, pair, fold and head bodies are generic over it, and struct A4 joins Q4_K and Q6_K. A SIMD group owns four rows. Kernels::with_geometry refuses a row count the library's source does not define.
  • chain: SiteTy::MlxA4 sits outside the card kernel table (BACKEND_SITES). The qwen35moe reader takes a backend's site lists as data (read::Sites35). The card passes its lists as before, and the card's site code refuses MlxA4 by name. Metal passes session::SITES, one LAUNCHED list held equal to the arena's quant set by a test.

Release notes: Added — Metal: MLX 4-bit (affine, group 64) qwen35moe files open and decode on Apple Silicon.

Code shape

  • No second copy. gguf is the one owner of block bytes and value counts. The Metal kernels take the dequant from one quant owner.
  • Model code holds only architecture facts. The MLX map is per-family data in model-hf's tables.
  • Dead code is gone.
  • No silent failure. A partial A4 group, an MLX type a backend does not launch, and a geometry the library was not built with are named errors.
  • Comments state what is true now.
  • No relaxed gate.
  • cargo fmt and cargo clippy are clean; the lint count did not go up.

Duplication found or removed: three local ggml_type helpers in the Metal gates became Quant::ggml(); the five copies of Metal's site list became one LAUNCHED.

What I ran

On an M1 Pro (development evidence):

  • just lab-metal: gate_metal_qwen35moe_kernels --mutants-all: PASS (63 mutants, each red on its clause), including the A4 clauses (mat-vec, pair, fold, head, embed) against the f64 oracle.
  • just lab-metal-e2e: clause m_mlx: PASS (the MLX split opens, every typed site MLX_A4, and generates), --mutants-all: PASS (4 mutants).
  • just mac-metal-lint, just mac-lint, just mac-fmt-check, cargo test -p bloomery-chain -p bloomery-placement -p bloomery-model-hf -p bloomery-serve, tools/check-{unsafe,comments,model-tax,arch}.sh: all rc 0.
  • New checks, run FAIL-first: the launched_sites_are_the_arena_quants test fails with MlxA4 dropped from LAUNCHED; the nrows clause fails with the geometry refusal removed.

Box gates (fixture tier, the list just affected derives) follow in a comment.

Not yet: a real MLX checkpoint's decode measured beside mlx-lm on the same Mac.

AI use: written with Claude Code; the lead session reviewed every round's diff and re-ran the gates.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ

@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 24, 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 empty fixture index passes; duplicate and unused owners remain.

Must fix

1. Reject missing fixture tensors (A)

mlx-fixture.py:610 With valid config and GGUF, weight_map: {} skips the tensor loop, prints check: 0 tensors, and returns CLI status 0. An empty checkpoint is certified. Reject missing tensors before using gate evidence. After entries:

    expected = set(entries)
    for name, (_, kind, _) in entries.items():
        if kind == "quant":
            stem = name.removesuffix(".weight")
            expected.update((f"{stem}.scales", f"{stem}.biases"))
    if set(weight_map) != expected:
        raise Refusal(EXIT_REFUSED,
                      f"tensor index: missing {expected - set(weight_map)}, "
                      f"extra {set(weight_map) - expected}")

2. Reuse quant metadata (B, R14)

clauses_matvec.rs:545 copies matvec.rs:38. Delete ty; replace its call:

        let bytes = fixture.rows(name, quant.ggml(), cols, rows)?;

fixture.rs:160 repeats GgmlType::blck_size's counts:

fn values_per_block(ty: GgmlType) -> Result<usize, String> {
    let n = match ty {
        GgmlType::Q4_K | GgmlType::Q6_K | GgmlType::MLX_A4 => ty.blck_size(),
        _ => None,
    };
    n.and_then(|n| usize::try_from(n).ok())
        .ok_or_else(|| format!("{ty:?} is not a mat-vec type"))
}

One map avoids later drift.

3. Reuse gate owners (B, R14)

clauses_a4.rs:389 duplicates clauses_norm.rs:301. Make the original pub(super); delete the copy and import:

use super::clauses_norm::head_partials;

Its a4_embed at line 599 copies clauses_embed.rs:109, already supporting A4:

pub fn a4_embed(h: &Harness<'_>, fix: &Fixture) -> Clause {
    if fix.table("token_embd.weight", HEAD_K)?.2 != gguf::quant::GgmlType::MLX_A4 {
        return Err("token_embd.weight is not MLX_A4".into());
    }
    super::clauses_embed::embed(h, fix)
}

mlx.rs:28 also copies target.rs:51. Make the original pub(super); delete the new struct/impl and import:

use super::target::Quiet;

These copies otherwise drift.

4. Share the fixture scanner (B, R14)

mlx.rs:53 copies mac.rs:414. Both ignore I/O errors and can select an incomplete listing. Share this in refset::fixture, including first_shard_in:

pub fn first_shard_at(at: &str) -> Result<String, RefError> {
    let error = |e| RefError::missing(at, format!("cannot list {at}: {e}"));
    let mut found = Vec::new();
    for entry in std::fs::read_dir(at).map_err(error)? {
        let name = entry.map_err(error)?.file_name();
        let name = name.to_str().ok_or_else(|| RefError::missing(at, "non-UTF-8 filename"))?;
        if is_first_shard(name) {
            found.push(name.to_owned());
        }
    }
    match found.as_slice() {
        [one] => Ok(format!("{at}/{one}")),
        _ => Err(RefError::missing(at, format!("expected one first shard: {found:?}"))),
    }
}

In both resolvers, after let at:

    refset::fixture::first_shard_at(&at)
        .map(PathBuf::from).map_err(|e| e.to_string())

One owner prevents drift.

5. Delete the dead decoder (B)

mlx-fixture.py:83 is unused. Delete:

-def f16_bits_to_f32(bits):
-    """Little-endian f16 bits widened to f32 (exact), as half_to_f32 does."""
-    return np.ascontiguousarray(bits, dtype="<u2").astype(np.float32)

Non-blocking

⚠ Geometry evidence: geometry.rs:9 doubles accumulators and halves threadgroups (2048 → 1024 at 8192 rows, two SIMD groups [derived]). Attach the geometry prediction and timed A/B output on the contributor's Mac.

Checked

Duplicates: quant metadata, head partials, embedding checks, sinks and fixture scans confirmed.
Complexity: no finding rests on complexity alone.
Silent failure: empty indexes skip checks; both new scans discard directory-entry errors.
Tests: static validation only; no hardware gates rerun.
Gates: geometry prediction and timed A/B absent from the PR body. No finding depends on escape catalog C1–C4.

Card check: needs-gpu. This pull request changes crates/gpu/src/arch/qwen3moe/body35.rs, 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)

("blk.2.attn_qkv.weight", Quant::Q6K, 2048, 8192),
("blk.2.ffn_down_shexp.weight", Quant::Q6K, 512, 2048),
] {
let bytes = fixture.rows(name, ty(quant), cols, rows)?;

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.

Quant::ggml already owns this type mapping; delete the duplicate ty helper.

Suggested change
let bytes = fixture.rows(name, ty(quant), cols, rows)?;
let bytes = fixture.rows(name, quant.ggml(), cols, rows)?;

midagedev and others added 22 commits October 24, 2026 09:50
…the probe sweeps

The Q4_K/Q6_K mat-vec, the seg and headnorm launches, the experts' pair and
fold, and the output head take 2, 4 or 8 rows a SIMD group; four is the
landed count. `Kernels::with_geometry` carries the rows, the mat-vec
SIMD-group count and the router's, and every launch follows it; the probe's
`--geometry` compiles the shipped source with the counts replaced. A new
`nrows` clause holds the bits equal at four and two rows a SIMD group, and the
fold clause covers a row tail a threadgroup does not divide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…ad bodies generic over it

quant.metal holds the Q4_K and Q6_K owners: the block, the lane map and its
registers, the blocks a lane walks, the input load in its plain, norm and
route forms, and one block's dot (Q4_K also the gated delta net's two-halves
form). matvec_rows, the pair, the fold and the head's argmax are templates
over the owner; every entry is an explicit instantiation under its old host
name, so no launcher changes. Every launch's output words, the fault word
included, equal the previous source's bit for bit on 57 launch pairs (a
scratch harness through the runtime compiler); the kernels gate's clauses are
unrelaxed and its mutants re-pinned to the shared text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…4 and 2005

dequant_row decodes s*q + b in f32 (the product is exact, so one rounding), pinned bit for bit
against mx.quantize/mx.dequantize output; check_mlx_affine refuses a non-finite BF16 scale or
bias, or a scale whose top code leaves f32, before any value is written. No card and no host
matmul read them yet: both refuse by name.

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

config.json's quantization block (affine, group 64, 4 or 8 bits, per-module overrides) places
each .weight with its .scales and .biases as one tensor; another mode, group or width, a
divergent quantization_config copy, or a weight without its companions is refused by name.
Tested over the real mlx-community Qwen3.6-35B-A3B 4bit config and shard headers.

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

mx.quantize over the fixture's dequantized tensors in mlx-community's names and layout, then a
check: the f32 decode equals mx.dequantize bit for bit and every value lies within the
quantizer's band of the GGUF value. Its self-test runs without mlx. hf.py's type mirror gains
2004 and 2005.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…e and bias as MLX_A4/MLX_A8 blocks

Byte moves only; every block passes check_mlx_affine or the tensor is refused by name. The
pre-stacked switch_mlp experts go through the same interleave with ggml dims [K, R, E]. Pinned
against real mx.quantize output; a part read of an MLX weight is refused by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
One map with a Family: Qwen3.6's prefix, its pre-stacked switch_mlp experts, the explicit
layer_types list, the vision tower left out by prefix. The value heads arrive in HF's grouped
order and are regrouped to the file's tiled order as for Qwen3.8; the norms MLX's convert already
folded take no +1; the conv's [c, k, 1] is squeezed first. Tested over the real config and headers
and the fixture folder's headers against the GGUF fixture's tensor list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…ouped, the norms unchanged

The folder now matches the real mlx-community layout the map reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…dia markers)

mlx-community's Qwen3.6 folder writes `backend`, `is_local`, `processor_class`,
the processor's media markers by name and `TokenizersBackend` as the class.
The markers are added tokens of tokenizer.json, which serving matches as
written; the rest name where and how HF loaded the folder. Each key has its
schema row, so a value outside it is still refused by name.

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

`prepare` reads tokenizer.json, so a fixture folder without it does not
convert. `make` now refuses, before it writes anything, a config whose
folder has no tokenizer.json, and copies tokenizer.json, tokenizer_config.json,
chat_template.jinja and generation_config.json when present; `check` prints
their sha256 with the shards'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TG5hgJqn38MRwLefZHyHCJ
…he geometry note without measured numbers, the head call's alignment, the MLX fixture's maker in its error

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q5zTV27LbaVZFTjnkdmTjJ
…) and the reader's sites.<field> lists, resolved through Sites35::CARD; a field CARD does not name is refused by name

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

@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, five must-fix items and geometry evidence remain open.

Verdict: MUST_FIX: empty checkpoints pass; duplicate and unused owners remain.

Must fix

1. Reject missing tensors (A)

Still open: mlx-fixture.py:610. With valid config and GGUF, weight_map: {} skips all tensor checks, prints check: 0 tensors, and the CLI returns 0. Reject missing tensors before trusting fixtures. After entries:

    expected = set(entries)
    for name, (_, kind, _) in entries.items():
        if kind == "quant":
            stem = name.removesuffix(".weight")
            expected.update((f"{stem}.scales", f"{stem}.biases"))
    if set(weight_map) != expected:
        raise Refusal(EXIT_REFUSED,
                      f"tensor index: missing {expected - set(weight_map)}, "
                      f"extra {set(weight_map) - expected}")

2. Reuse quant metadata (B, R14)

Still open: clauses_matvec.rs:545 copies matvec.rs:37. Delete ty; replace its call:

        let bytes = fixture.rows(name, quant.ggml(), cols, rows)?;

fixture.rs:160 repeats blck_size's counts. Reuse prevents drift:

fn values_per_block(ty: GgmlType) -> Result<usize, String> {
    let n = match ty {
        GgmlType::Q4_K | GgmlType::Q6_K | GgmlType::MLX_A4 => ty.blck_size(),
        _ => None,
    };
    n.and_then(|n| usize::try_from(n).ok())
        .ok_or_else(|| format!("{ty:?} is not a mat-vec type"))
}

3. Reuse gate owners (B, R14)

Still open: clauses_a4.rs:389 copies clauses_norm.rs:301. Make the original pub(super), delete the copy and import:

use super::clauses_norm::head_partials;

Its a4_embed at line 599 copies clauses_embed.rs:109, which supports A4. Replace:

pub fn a4_embed(h: &Harness<'_>, fix: &Fixture) -> Clause {
    if fix.table("token_embd.weight", HEAD_K)?.2 != gguf::quant::GgmlType::MLX_A4 {
        return Err("token_embd.weight is not MLX_A4".into());
    }
    super::clauses_embed::embed(h, fix)
}

mlx.rs:28 copies target.rs:51. Make the original pub(super), delete the new struct/impl and import:

use super::target::Quiet;

Reuse prevents gate drift.

4. Share fixture scanning (B, R14)

Still open: mlx.rs:53 copies mac.rs:414. Both discard entry errors. Extract refset::fixture::first_shard_in's listing and reuse it in all three paths:

pub fn first_shard_at(at: &str) -> Result<String, RefError> {
    let error = |e| RefError::missing(at, format!("cannot list {at}: {e}"));
    let mut found = Vec::new();
    for entry in std::fs::read_dir(at).map_err(error)? {
        let name = entry.map_err(error)?.file_name();
        let name = name.to_str().ok_or_else(|| RefError::missing(at, "non-UTF-8 filename"))?;
        if is_first_shard(name) {
            found.push(name.to_owned());
        }
    }
    match found.as_slice() {
        [one] => Ok(format!("{at}/{one}")),
        _ => Err(RefError::missing(at, format!("expected one first shard: {found:?}"))),
    }
}

In both Metal resolvers, after let at:

    refset::fixture::first_shard_at(&at)
        .map(PathBuf::from).map_err(|e| e.to_string())

One owner prevents drift.

5. Delete the dead decoder (B)

Still open: mlx-fixture.py:83 has no callers. Delete it:

-def f16_bits_to_f32(bits):
-    """Little-endian f16 bits widened to f32 (exact), as half_to_f32 does."""
-    return np.ascontiguousarray(bits, dtype="<u2").astype(np.float32)

Non-blocking

⚠ Geometry evidence, still open: geometry.rs:9 doubles accumulators and halves threadgroups (2048 → 1024 at 8192 rows, two SIMD groups [derived]). Attach the geometry prediction and timed A/B output on the contributor's Mac.

Checked

Duplicates: all cited copies confirmed; findings carried from the previous review.
Complexity: no finding rests on complexity alone.
Silent failure: empty indexes bypass checks; both Metal scans discard entry errors.
Validation: source and AST checks; no runtime tests rerun.
Gates: no pins moved; no escape or ledger pattern matched.

Card check: needs-gpu. This pull request changes crates/gpu/src/arch/qwen3moe/body35.rs, 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)

@github-actions github-actions Bot added the host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset label Oct 24, 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.

Since the last review:

  • Missing tensors: fixed; the checker requires the complete index.
  • Quant metadata: fixed; callers reuse Quant and GGUF metadata.
  • Gate owners: fixed; partials, embedding checks and Quiet are shared.
  • Fixture scanning: fixed; both Metal gates use the refset resolver, which propagates entry errors.
  • Dead decoder: fixed; the unused function is deleted.

Verdict: CLEAN: all five previous must-fix items are resolved, and the new commits introduce no blocking defect.

Checked

Duplicates: 6 new items checked; none duplicated. All 15 displayed dryer pairs read; none concerns an added definition in this increment.
Complexity: crapper's flagged functions are from earlier commits; this increment adds no complexity to those functions.
Silent failure: 7 paths followed: two quant refusals, directory/entry/UTF-8 errors, ambiguous shard counts and index mismatch. Callers receive named errors.
Tests: 7 in-memory cases pass for the source-derived index guard; deleting mlx-fixture.py:612 makes 6 fail. The added self-test rejects one missing entry and an empty index.
Tests: dropping A4 from Quant::ALL fails the site-set assertion; dropping token faults fails the shared embedding clause; removing the geometry refusal fails nrows (source checks).
Gates: no pins or coverage removed; the shared embedding clause preserves the deleted copy's assertions.
Escape catalog: no patterns matched.

Notes

Metal gates and the full filesystem self-test were not run here. The supplied PR text lacks the complete NVIDIA gate evidence required by CONTRIBUTING.md.

Card check: needs-gpu. This pull request changes crates/gpu/src/arch/qwen3moe/body35.rs, 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)

@midagedev

Copy link
Copy Markdown
Owner Author

Box evidence for 6530ba9 (the maintainer's workstation, RTX 3090 + RTX A6000, fixture tier). The list is just affected origin/main (235 recipes), run by tools/gate-batch.sh --tier fixture --ledger:

DONE total=235 red=21 tier=fixture skipped=11 wall=2649s laneA=2311s laneB=2292s laneX=337s deferred=208 real_only=49 no_fixture=5 real_file=37 needs_env=2 deferred_list=/Users/hckim/.cache/bloomery/m

All 21 reds are main's state, not this PR's. Each was rerun from a main tree and gave the same result:

  • stale fixture budgets (gate-fixture-budget, 11 glm5next gates, solar2-twocard);
  • a model file missing on the box (gate-tokenizer);
  • gate-qwen4exp-meta, gate-gpu-qwen4exp-mtp, gate-gpu-qwen38-serve, gate-ds41-load, gate-flint-meta;
  • gate-gpu-qwen35moe-leg@q35iq3s6 (logits rel 1.102e-1, the same value on main);
  • gate-ptx-spill (main's scan values).

just narrow (--no-jit scans of the covering bin set) shows every ptx-scan identical: no kernel moved.

The Mac gates are in the description: just lab-metal (63 mutants), just lab-metal-e2e (m_mlx, 4 mutants).

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 host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset 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