Repository navigation
feat(quant): plumb MXFP4/MXFP8/NVFP4 through compiled MoE path; --q-recipe + --q-mode nvfp4; Gemma4 router fix - #61
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ 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.
…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).
a63cd90 to
6309dfd
Compare
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.
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]>

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:
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 atqwen3_5_moe/persistence.rsandqwen3_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.--q-recipe X --q-mode nvfp4support with strict invariants (bits=4, gs=16) and a recipe whitelist (unsloth,qwen3_5only —mixed_*lack the per-tensor exclusions NVFP4 needs). Newapply_nvfp4_upgrademirrorsapply_mxfp_upgradebut 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.recipe_gs=64when 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.is_router_gateto match Gemma4's.router.proj(Qwen used.mlp.gate); andapply_nvfp4_upgradenow emits an explicit 8-bit affine override for affine-only keys when the inner predicate returnsDefault, instead of letting them fall through to top-levelmode=nvfp4(which the affine-only loader rejects).effective_plq_forunified 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:
Test count
cargo test -p mlx-core --lib convert::tests: 1313 → 1390 (+77 new, including the fullapply_nvfp4_upgradematrix, invariant validators, recipe restriction, and the regression test for the Gemma4 router.proj + affine-only Default fallback).apply_mxfp_upgradetests preserved and passing.Test plan
cargo test -p mlx-core --lib convert::tests— 44 / 44 passcargo clippy -p mlx-core --all-targets -- -D warnings— cleancargo fmt --check— cleanyarn vite fmt+yarn vite lint --type-aware --type-check packages/cli/src/commands/convert.ts— clean🤖 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_dispatchmodule and plumbing per-layer(mode, bits, group_size)overrides fromconfig.jsonthrough loaders and into the compiled C++ runtime via a new quant-info registry (mlx_store_quant_info, cleared withmlx_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-mxfpupgrade flag: adds strict early validation for MXFP/NVFP invariants, restricts--q-mode nvfp4 --q-recipeto supported recipes, upgrades recipe decisions viaapply_mxfp_upgrade/apply_nvfp4_upgrade, and ensures no-recipe quantization returns/persists per-layer overrides while writing an effectivequantization.mode/group_sizetoconfig.json.Improves robustness/perf of quantization by tiling large 3D MoE expert tensors during
mlx_quantizeto 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.