Skip to content

feat(quant): plumb MXFP4/MXFP8/NVFP4 through compiled MoE path; --q-recipe + --q-mode nvfp4; Gemma4 router fix - #61

Merged
Brooooooklyn merged 2 commits into
mainfrom
worktree-q-mxfp-toggle
May 16, 2026
Merged

Brooooooklyn merged 2 commits into
mainfrom
worktree-q-mxfp-toggle

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR closes the long-standing gap where MXFP4 / MXFP8 / NVFP4 conversions silently bypassed the fast compiled C++ MoE forward path, and adds proper recipe + NVFP4 support so non-affine modes can use the Unsloth Dynamic strategy. Concretely:

  • Plumb a Rust → C++ quant-info registry (g_quant_info, mlx_store_quant_info) so the compiled MoE forward path knows the per-projection mode/bits/gs at dispatch time. Drops the legacy MXFP-mode bypass at qwen3_5_moe/persistence.rs and qwen3_5/persistence.rs:746, routing all three FP modes through the fast path. Verified on Qwen3.6-35B-A3B: MXFP8 39.8 → 48.4 tok/s, NVFP4 reaches 59.1 tok/s under the recipe, all generations coherent.
  • Add --q-recipe X --q-mode nvfp4 support with strict invariants (bits=4, gs=16) and a recipe whitelist (unsloth, qwen3_5 only — mixed_* lack the per-tensor exclusions NVFP4 needs). New apply_nvfp4_upgrade mirrors apply_mxfp_upgrade but for nvfp4 (gs=16), keeps router gates / affine-only loaders intact. Validators relaxed in TS CLI, Rust safetensors path, and Rust GGUF path; identical error wording across the three.
  • Two follow-up bug fixes found while sweeping all Qwen3.6-27B / 35B-A3B / Gemma-4-26B-A4B-IT variants end-to-end:
    • recipe_gs=64 when global mode is nvfp4 — the user-facing gs=16 was being passed into the recipe predicate and the recipe's affine 6-bit AWQ projections rejected gs=16 at quantize time.
    • Widened is_router_gate to match Gemma4's .router.proj (Qwen used .mlp.gate); and apply_nvfp4_upgrade now emits an explicit 8-bit affine override for affine-only keys when the inner predicate returns Default, instead of letting them fall through to top-level mode=nvfp4 (which the affine-only loader rejects).
  • effective_plq_for unified resolver with embedding/embed_tokens alias handling (caught by Codex review). Centralizes per-layer mode lookup across Qwen3.5 / Qwen3.5-MoE / Gemma4.

End-to-end verification

Converted and benched (best-of-T2–T4 on M3 Max 128GB) the full lineup. All coherent across 4-turn capitals chat, no fallback warnings:

Model Coverage Notes
Qwen3.6-35B-A3B Q2–Q8 + MXFP4/MXFP8/NVFP4 NVFP4 redone with recipe (252 overrides vs 80 uniform), 59.1 tok/s
Qwen3.6-27B Q2–Q8 + MXFP4/MXFP8/NVFP4 27B NVFP4 also redone with recipe, 14.9 tok/s
Gemma-4-26B-A4B-IT Q3–Q8 + MXFP4/MXFP8/NVFP4 8 variants live on HF; Q2 skipped (4B-active is below 2-bit redundancy floor)

Test count

  • cargo test -p mlx-core --lib convert::tests: 1313 → 1390 (+77 new, including the full apply_nvfp4_upgrade matrix, invariant validators, recipe restriction, and the regression test for the Gemma4 router.proj + affine-only Default fallback).
  • All pre-existing apply_mxfp_upgrade tests preserved and passing.

Test plan

  • cargo test -p mlx-core --lib convert::tests — 44 / 44 pass
  • cargo clippy -p mlx-core --all-targets -- -D warnings — clean
  • cargo fmt --check — clean
  • yarn vite fmt + yarn vite lint --type-aware --type-check packages/cli/src/commands/convert.ts — clean
  • End-to-end convert + load + 4-turn coherence smoke for all 25 variants (9 × Qwen 35B-A3B + 9 × Qwen 27B + 8 × Gemma-4-26B-A4B-IT, less Q2 for Gemma4)
  • HuggingFace uploads + README updates for all 25 model repos

🤖 Generated with Claude Code


Note

High Risk
High risk because it changes quantization invariants/metadata, model loading dispatch, and adds new Rust↔C++ FFI state (mlx_store_quant_info) that affects the compiled inference path for quantized models.

Overview
Enables per-projection quantization mode dispatch across Qwen3.5 (dense + MoE) and Gemma4 by introducing a shared quant_dispatch module and plumbing per-layer (mode, bits, group_size) overrides from config.json through loaders and into the compiled C++ runtime via a new quant-info registry (mlx_store_quant_info, cleared with mlx_clear_weights). This removes reliance on heuristics like “uint8 scales implies MXFP8” and allows mixed-mode checkpoints (affine/MXFP4/MXFP8/NVFP4) to take the compiled forward path.

Extends conversion to support NVFP4 + recipes and an orthogonal --q-mxfp upgrade flag: adds strict early validation for MXFP/NVFP invariants, restricts --q-mode nvfp4 --q-recipe to supported recipes, upgrades recipe decisions via apply_mxfp_upgrade/apply_nvfp4_upgrade, and ensures no-recipe quantization returns/persists per-layer overrides while writing an effective quantization.mode/group_size to config.json.

Improves robustness/perf of quantization by tiling large 3D MoE expert tensors during mlx_quantize to avoid Metal GPU watchdog timeouts, and hardens “affine-only” tensor handling (e.g. lm_head, embed_tokens, router.proj, embedding_projection) to prevent silent mis-dequantization under FP modes; Gemma4 also synthesizes fused MoE expert override keys so per-layer overrides still apply after load-time tensor fusion.

Reviewed by Cursor Bugbot for commit 62d72d6. Bugbot is set up for automated code reviews on this repo. Configure here.

@coderabbitai

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a9e83f96-17b1-435e-922f-5525c3e11d90

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-q-mxfp-toggle

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit a63cd90. Configure here.

Comment thread crates/mlx-core/src/convert.rs Resolved
…cipes

Adds full mixed-mode quantization plumbing across convert, persistence,
inference, and the compiled C++ MoE forward path.

Conversion (crates/mlx-core/src/convert.rs, utils/gguf.rs, cli/src/commands/convert.ts)
- New --q-mxfp flag: orthogonal post-transform that upgrades affine
  decisions emitted by any recipe to mxfp8 (8-bit) / mxfp4 (4-bit).
- New --q-mode nvfp4 + apply_nvfp4_upgrade: NVFP4 micro-block
  (bits=4, group_size=16) variant with strict invariants. Restricted
  to unsloth/qwen3_5 recipes (only recipes with NVFP4-safe tensor-class
  exclusions; mixed_* lack skip lists for linear_attn.out_proj etc.).
- is_affine_only_key helper: lm_head, router.proj, embed_tokens*,
  embedding_projection are excluded from MXFP/NVFP upgrades — those
  loaders are affine-only and would silently mis-dequantize FP weights.
- Router gates (mlp.gate, shared_expert_gate, .router.proj) forced to
  8-bit affine under FP modes; matches Python mlx-lm quant_predicate.
- validate_nvfp4_invariants / validate_nvfp4_recipe helpers; recipe
  predicates pass recipe_gs=64 under --q-mode nvfp4 (affine-legal).
- MoE expert quantize tiled along axis 0 in 32-expert chunks to avoid
  Metal GPU watchdog (5s command-buffer limit) on 256-expert stacks.

Inference loaders (qwen3_5 / qwen3_5_moe / gemma4 quantized_linear + persistence)
- PerLayerQuant struct + PerLayerMode::{Affine, Mxfp8, Mxfp4, Nvfp4}.
- try_build_mxfp4_quantized_linear / try_build_mxfp4_quantized_switch_linear,
  same for nvfp4. Per-layer parser reads mode from per-layer JSON.
- Dispatch by plq.mode in try_build_ql closures; alias `embedding`
  to `embed_tokens` in MoE PLQ resolver.
- Gemma4: honor per-layer bits/group_size in vision projection load,
  guard MXFP embedding only when quantized.

Compiled MoE forward (mlx-sys quant-info registry)
- Per-projection quant-info registry scaffolding (scalable to MXFP4/8 + NVFP4).
- linear_proj, switch_linear_fwd, MoE init dispatch made registry-aware
  with heuristic fallback; paged-init detect_quant lambdas mirror.
- detect_layer_quant / detect_router_gate_quant helpers extracted.
- Dense Qwen3.5 quant-info plumbed; MXFP-mode bypass dropped — all
  MoE now routes through the fast compiled C++ path.

Tests
- apply_mxfp_upgrade unit tests (per match arm: Skip, Default with
  bits ∈ {3,4,5,6,8}, Custom 4/8 promotion, affine-only key exclusions
  for lm_head / router.proj / embed_tokens / embedding_projection).
- effective_plq_for resolver tests.

End-to-end verification: 27B dense, 35B-A3B MoE, Gemma-4-26B-A4B-IT MoE
all converted, benched, and uploaded across 8–9 variants each (affine
Q3–Q8, MXFP4, MXFP8, NVFP4).
@Brooooooklyn
Brooooooklyn force-pushed the worktree-q-mxfp-toggle branch from a63cd90 to 6309dfd Compare May 16, 2026 03:14
The guard at quantize_with_optional_tiling that detects "first chunk
returned no biases but a later chunk returned some" was dead: it tested
`!has_biases && !bias_chunks.is_empty()`, but `bias_chunks` is only
pushed right after `has_biases = true` (~3 lines below), so
`!bias_chunks.is_empty()` always implies `has_biases`, making the
combined condition unreachable.

Use `packed_chunks.len() > 1` instead — `packed_chunks` is pushed
unconditionally at the top of every iteration, so `len > 1` is the
honest signal that at least one prior chunk has already been processed
without producing biases.

Reported by Cursor Bugbot on PR #61 commit a63cd90.
@Brooooooklyn
Brooooooklyn merged commit 434bfbf into main May 16, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the worktree-q-mxfp-toggle branch May 16, 2026 03:56
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Post-rebase fixes required to land the MTP branch cleanly on the
advanced origin/main (#61-#64: lfm2 MoE, E37 prefill opt, drain-on-write
convert). All conflicts during the 84-commit replay were resolved within
their commits; these are the cross-cutting reconciliations:

- convert.rs: origin/main #63 changed `save_safetensors` to drain its
  argument (`&mut`, drain-on-write). The MTP sidecar + split-drafter
  writers borrow their tensor maps immutably and the sidecar reuses its
  map afterward (its `is_empty()` gates config metadata), so drain a
  small clone instead of the original.
- qwen3_5/model.rs: origin/main's E37/E38 last-token prefill slice
  (`forward_with_optional_last_slice`) auto-merged into the SHARED
  `forward_pre_norm_inner`, but that primitive must return the full
  per-position hidden for the MTP prompt-hidden path
  (`chunked_prefill_with_hidden_with_size` re-slices it by chunk
  length). Restored the tested plain-`forward` loop. E37's main win
  (lm_head matmul reduction) is still applied by
  `project_last_logits_from_pre_norm_hidden`; only the negligible eager
  last-layer-MLP slice (E38) is dropped. Kept origin/main's chunk_async
  toggle + our parameterized chunk_size in chunked_prefill.
- lfm2 integration tests (origin/main #64): added the MTP ChatConfig
  fields (enable_mtp/mtp_depth/mtp_adaptive_depth: None) that our branch
  introduced and the new lfm2 test literals lacked.

Verified: build OK; mlx-core 1654 pass / 3 pre-existing Metal-f32 env
failures (sources byte-identical to origin/main); paged-attn OK; clippy
-D warnings clean; fmt clean; typecheck OK; TS 1260 pass / 6 missing
gitignored-GSM8K-fixture failures (present in main checkout).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant