Skip to content

Add global scale for nvfp4 quantized MoEs - #1844

Merged
michalk8 merged 8 commits into
mainfrom
global-scale-nvfp4
Oct 7, 2026
Merged

michalk8 merged 8 commits into
mainfrom
global-scale-nvfp4

Conversation

@nastya236

@nastya236 nastya236 commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Follow up of ml-explore/mlx#4458 that adds global scale to gather_qmm with nvfp4 weights.
[should be merged after mlx pr]

Tested with mlx-community/Qwen3.6-35B-A3B-nvfp4:

mlx_lm.chat --model mlx-community/Qwen3.6-35B-A3B-nvfp4 --max-tokens 1024

Input: What is the highest mountain? Be brief.
Output:
Here's a thinking process:

  1. Analyze User Input:
  • Question: "What is the highest mountain?"
  • Constraints: "Be brief."
  • Key requirement: Direct, concise answer without elaboration or reasoning.
  1. Identify Core Fact:
  • The highest mountain above sea level is Mount Everest.
  • Height: 8,848.86 meters (29,031.7 feet) above sea level.
  1. Apply Constraints:
  • "Be brief." → Keep it to one short sentence or just the name.
  1. Formulate Response:
  • "Mount Everest." (or "Mount Everest, 8,848.86 meters above sea level.")
  1. Final Check:
  • Matches fact? Yes.
  • Brief? Yes.
  • No extra thinking/reasoning? Yes.
  • Ready. Output: "Mount Everest."✅

Mount Everest.

@nastya236 nastya236 changed the title global scale for nvfp4 moes Add global scale for nvfp4 quantized MoEs Sep 4, 2026
@gabe-l-hart

gabe-l-hart commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

This branch was proposed as a fix for the underflow issues I'm seeing with Granite in #1836 (both dense and moe). I tested it out, but it doesn't seem to fix the issue for either model, and the MoE path raises a stack trace: #1836 (comment)

@nastya236
nastya236 requested a review from michalk8 October 6, 2026 22:46
Comment thread mlx_lm/models/switch_layers.py Resolved
Comment thread mlx_lm/models/switch_layers.py Resolved

@michalk8 michalk8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Minor comments, otherwise LGTM!

Comment thread mlx_lm/models/switch_layers.py Resolved
Comment thread mlx_lm/models/switch_layers.py Resolved
Comment thread mlx_lm/models/switch_layers.py Resolved
Comment thread tests/test_models.py Resolved
Comment thread mlx_lm/utils.py Resolved

@michalk8 michalk8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM, thank you!

@michalk8
michalk8 merged commit 3696eb2 into main Oct 7, 2026
2 checks passed
@michalk8
michalk8 deleted the global-scale-nvfp4 branch October 7, 2026 15:49
inureyes added a commit to lablup/mlxcel that referenced this pull request Oct 17, 2026
…2441)

## Summary

mlx-lm's `quantize_model(..., mode="nvfp4", global_scale=True)` (ml-explore/mlx-lm#1844) writes `max|w[e]|` per expert as `{switch layer}.global_scale` and flags the layer with `"global_scale": true`; MLX's `gather_qmm` dequantizes with `global_scale / (448 * 6)`. mlxcel read the same key as the compressed-tensors output multiplier, so such an export would decode with every routed expert 2688 times too large. This PR keeps the two scales apart, threads the native one through `gather_qmm`, and extends ModelOpt NVFP4 expert loading beyond Gemma 4.

### Part 1: MLX-native per-expert global scale

- FFI: `gather_qmm` gains a nullable `global_scale: *const MlxArray` (Rust decl, `mlx_cxx_bridge.h`, `mlx_cxx_bridge.cpp`); every existing caller passes null. A test-only `quantize_weights_with_global_scale` wraps `mlx::core::quantize(..., global_scale)`.
- `SwitchLinear::Quantized` now has `inv_global_scale` (the post-matmul multiplier, from the in-process `{prefix}.inv_global_scale` key) and `native_global_scale` (handed to `gather_qmm`). `quantized_parts` returns `None` when either is present, so the fused paths fall back to `forward`; `SwitchGLU::forward_with_expert_scales` passes through `forward_indexed` and gets the native scale too.
- The flag comes from the config, not the key. `apply_native_global_scale_flags` (called by `load_text_weights` and by every Gemma 4 loader through `sanitize_gemma4_nvfp4_weights`) reads the `quantization` / `quantization_config` entries (top level and `text_config`) and moves each flagged `{path}.global_scale` to `{path}.native_global_scale`. A flag without its tensor fails there, and so does a flag on a layer whose weight is not a `[num_experts, out, in]` stack (its scale would otherwise be renamed and never read); a `.global_scale` left at a switch prefix (never flagged) fails in `SwitchLinear` with the prefix named; a checkpoint that ships `native_global_scale` itself is refused. I chose this over adding a parameter to `from_weights_with_mode` because about 55 family files construct `SwitchLinear` / `SwitchGLU`; the decision is still made from the per-layer config entry, once, before any family sanitizer renames keys. Loaders that do not go through these funnels (other VLM paths) see the bare key; it fails the load wherever it sits at a shared `SwitchLinear` prefix, but a loader that renames expert keys by suffix can leave it orphaned (see Not done here).
- Load-time validation of the native scale against MLX's preconditions: `nvfp4` mode, one f32 entry per expert of a `[E, out, in]` stack, a Metal or CUDA GPU stream. Each failure is a load error naming the prefix and backend, never a mid-generation throw.
- Laguna's in-process expert sidecar is renamed to `inv_global_scale` (`laguna_sanitize.rs`, `laguna.rs` detection, tests). Laguna's dense shared-expert `[1]` `.global_scale` keeps its name: it feeds `UnifiedLinear`, and dense global scales are out of scope.
- Two fixes needed for any mlx-lm nvfp4 MoE export to load at all: `SwitchLinear::from_weights` (the shared loader, which declares no mode) infers bias-free block-float planes with uint8 scales from the shapes (nvfp4 / mxfp4 / mxfp8 by words-per-group) instead of declaring them affine and refusing them; and the quantized embedding lookup in the bridge stops requesting a uint8 output dtype for block-float tables, which aborted the first lookup (`[dequantize] Only real floating types are supported but output dtype == uint8`).

### Part 2: ModelOpt NVFP4 experts outside Gemma 4

- `load_text_weights` runs `normalize_nvfp4_keys` + `repack_nvfp4_weights_to_quantized` for any text checkpoint declaring ModelOpt NVFP4 in `quantization_config` (top level or `text_config`) or in `hf_quant_config.json`. Detection reuses Gemma 4's `is_modelopt_nvfp4`, lifted to a module-level `pub(crate)` fn; the `hf_quant_config.json` shape is rewritten into the `config.json` shape before it is checked. `quant_method` and the producer name match case-insensitively.
- The repack decodes F8_E4M3 block scales that MLX's own safetensors loader returns as raw uint8 bytes (the Gemma 4 loader already decoded them; a numeric cast would read the bytes as 0..255).
- New shared helper `stack_expert_leaf` plus `EXPERT_PLANE_LEAVES` in `switch_layers.rs`; the DeepSeek-V3, Mistral 4 and PhiMoE stacking loops and the generic per-expert stacker use it, so the repack's per-expert `weight_scale_2` sidecar becomes a `[num_experts]` `inv_global_scale` vector in the same pass as weight/scales/biases.
- PhiMoE and Mistral 4 read the 16-wide block size from `quantization_config` (`modelopt_nvfp4_group_size`). DeepSeek-V3's own expert path is affine-only; it now refuses a block-float plane by name instead of reporting a missing `.biases` key.
- Families with their own `weight` / `scales` / `biases` stacking loop that load through the shared `SwitchLinear` (OLMoE, dots1, Solar Open, LFM2, Cohere2-MoE, ...) would stack a ModelOpt plane's codes and block scales and drop its `weight_scale_2`. `SwitchLinear` now refuses a bias-free uint8-scale plane with no multiplier while per-expert `.global_scale` sidecars remain under its MoE block, naming the leftover key, so those checkpoints fail to load instead of decoding wrong.
- gpt-oss's own `ExpertLinear` calls `gather_qmm` with no tensor scale, so it refuses a plane carrying `.native_global_scale` or a bare `.global_scale`.
- `docs/supported-models.md` documents both formats.

Also added: `scripts/mlx_lm_logit_trace.py`, an mlx-lm reference tracer in the `examples/logit_trace` TSV format, reusing the tokenizer and chunk plan from `scripts/laguna_oracle_trace.py`.

## Verification

All on the GB10 CUDA host (sm_121), `--profile test-fast --features cuda`. MLX at the pin supports `gather_qmm(..., global_scale)` for nvfp4 on CUDA (overlay `quantized.cpp`, ml-explore/mlx#4507 plumbing; qmv and qmm_naive apply it, qmm_sm80 and the grouped-GEMM path decline it), confirmed first with a Python probe on mlx 0.32.4 and then by the Rust tests below. Metal is left to the Metal nightly. Checkpoint paths are under `~/models_archive/mlx` because `~/models` was remapped on the host during the run.

- New tests, all run on CUDA: `switch_layers::global_scale_tests` (native path against `x @ dequantize(w[e]).T * gs/2688`, unsorted and sorted layouts, plus a relative-L2 check against the float weights; flag stripped fails to load; flag without tensor fails; reserved key refused; nvfp4 / shape / exclusivity checks; ModelOpt sidecar stacking and application; partial sidecar refused), `sanitize_tests::load_text_weights_repacks_modelopt_nvfp4_for_non_gemma_families` (config.json and hf_quant_config.json detection, E4M3 bytes preserved), `load_text_weights_resolves_flagged_native_global_scales`, `load_text_weights_leaves_undeclared_triplets_alone`, and per-family stacking tests in `phimoe`, `mistral4`, `deepseek_v3`.
- Revert checks. With part 1 reverted (native scale applied as the old post-multiplier, bare key accepted, flags ignored): `native_global_scale_matches_dense_dequantized_reference`, `global_scale_without_the_config_flag_fails_to_load`, `config_flag_without_global_scale_tensor_is_a_load_error`, `native_global_scale_needs_nvfp4_and_one_entry_per_expert` and `load_text_weights_resolves_flagged_native_global_scales` fail. Without the gpt-oss guard, `gpt_oss_expert_linear_refuses_a_per_expert_global_scale` fails; without the unstacked-sidecar guard, `a_plane_whose_family_left_the_modelopt_sidecars_unstacked_is_refused` fails. With part 2 reverted (no sidecar leaf, no F8 decode): the PhiMoE, Mistral 4, DeepSeek-V3 stacking tests, `per_expert_sidecars_stack_into_the_output_multiplier`, `a_partial_per_expert_sidecar_is_refused` and `load_text_weights_repacks_modelopt_nvfp4_for_non_gemma_families` fail.
- Module suites (`--test-threads=1`): switch_layers, laguna, sanitize, phimoe, mistral4, deepseek_v3, deepseek, gemma4, olmoe, qwen3_moe, inkling, kimi_k3, deepseek_v4, gpt_oss, glm4_moe, step3p5, nemotron_h, hunyuan, llama4, exaone, ernie, qwen3_next all pass. `cargo clippy --profile test-fast --features cuda --lib --tests -- -D warnings`, `cargo check -p mlxcel-core --lib --tests`, `cargo fmt --check` and the five contract checks pass.

### Real checkpoints

- Laguna regression, `~/models_archive/mlx/laguna-xs-2.1-nvfp4` (`poolside/Laguna-XS-2.1-NVFP4`), now on `inv_global_scale`: `MLXCEL_SDPA_DETERMINISTIC=1 mlxcel generate -m <dir> -p "Explain how mixture-of-experts routing works in two paragraphs." -n 64 --temp 0 --show-reasoning` is token-identical to `main` (8744c87, built in the same worktree before the change; main's self-parity checked first).
- ModelOpt path that already worked, `~/models_archive/mlx/gemma-4-31b-it-nvfp4`: same command, token-identical to `main`.
- Real mlx-lm export, `~/models_archive/mlx/olmoe-1b-7b-0924-nvfp4-gs`. Recipe: `allenai/OLMoE-1B-7B-0924` (HF bf16; its config lacks `rms_norm_eps`, so `1e-5`, the transformers default, was added for mlx-lm), loaded with `mlx_lm.utils.load(..., lazy=True)`, floats cast to bf16, `quantize_model(model, config, None, None, mode="nvfp4", global_scale=True)`, `save(...)`. mlx-lm 0.32.2 (mlx 0.32.4, `mlx-cuda-13` wheel) already carries the `global_scale` path, so it was used instead of a `ba8a08f` checkout; 48 switch layers carry the flag. `main` refuses it at load (`quantization.mode is "affine" but the checkpoint ships no .biases plane`). This branch: `mlxcel generate -m <dir> -p "The capital of France is Paris. The capital of Germany is" -n 40 --temp 0` gives "Berlin. The capital of the United Kingdom is London. The capital of the United States is Washington, D.C." (mlx-lm greedy: "Berlin. The capital of Italy is Rome. ..."). With the config flags stripped it fails to load naming `model.layers.0.mlp.switch_mlp.gate_proj`.
- Teacher-forced logit trace on that export, corpus `docs/architecture.md`, `256 4 8 0` (width 256, 4 chunks, top-8), reference `scripts/mlx_lm_logit_trace.py` (mlx-lm 0.32.2 on CUDA), compared with `scripts/compare_logit_traces.py`:
  - fixed arm: 0 of 396 decided positions disagree (gap >= 2), 19 of 1024 overall, all at reference gaps under 0.5; perplexity 20.15 vs 20.13.
  - native scale replaced by the old post-multiply: 396 of 396 decided positions disagree (1024 of 1024 overall); greedy output is garbage ("ByrPLAYpackavelorschKK Television...").
- ModelOpt non-Gemma: no ModelOpt NVFP4 MoE checkpoint of DeepSeek-V3, Mistral 4 or PhiMoE is published at a size this host fits (`mistralai/Mistral-Small-4-119B-2603-NVFP4` is in Mistral's consolidated format), so the synthetic triplet tests above cover the stacking. I also tried `nvidia/Qwen3-30B-A3B-NVFP4` (`~/models_archive/hf-src/Qwen3-30B-A3B-NVFP4`): the 18624 triplets now repack and the experts stack, but the model still aborts in the dense fused QKV projection (`FusedQKVLinear` hardcodes affine and has no global-scale path), which is outside this issue; `main` aborts on the same checkpoint with a matmul shape error.

## Not done here

- Dense fused QKV with NVFP4 + `weight_scale_2` (blocks Qwen3-MoE ModelOpt checkpoints).
- VLM loaders other than Gemma 4 do not resolve the flag. An mlx-vlm export with per-expert global scales (Neywa-Labs/mlx-vlm#2437) fails to load where the bare key reaches a shared `SwitchLinear` prefix, but the Gemma 4 unified loader's `split_fused_moe_key` (`src/loading/vlm_gemma_unified.rs`) splits only `.weight` / `.scales` / `.biases` of a fused `experts.gate_up_proj` and would leave a `.global_scale` orphaned. That is pre-existing and in a loading file outside this issue.
- A security review comment on this PR lists LOW follow-ups (load-time key scan cost, flag resolution only in the text and Gemma 4 funnels, DeepSeek v1's private loader treating a bias-free quantized plane as unquantized, which predates this PR).
- Re-measured after review: Laguna XS 2.1 greedy is still token-identical to `main`, and the OLMoE export's greedy output is unchanged.

Closes #2351
@Sofille65 Sofille65 mentioned this pull request Oct 20, 2026
michalk8 pushed a commit that referenced this pull request Oct 20, 2026
QuantizedSwitchLinear passes global_scale to mx.gather_qmm since #1844.
That keyword first shipped in mlx 0.32.3, so with mlx 0.32.2 every
quantized MoE fails with a TypeError on the first forward.
Nottlespike pushed a commit to RESMP-DEV/mlx-lm that referenced this pull request Oct 21, 2026
QuantizedSwitchLinear passes global_scale to mx.gather_qmm since ml-explore#1844.
That keyword first shipped in mlx 0.32.3, so with mlx 0.32.2 every
quantized MoE fails with a TypeError on the first forward.
jundot pushed a commit to jundot/omlx that referenced this pull request Oct 24, 2026
KRAFTON publishes Raon-1 mini's MLX architecture (RDA/MLA hybrid, mHC
residual streams, NVFP4 MoE) as a custom module next to the weights
(config.json "model_file": "raon_mlx_model.py"), which mlx-lm only imports
under trust_remote_code. oMLX also could not load it with trust on: the
pinned mlx-lm predates per-expert NVFP4 global scales.

- Vendor a reviewed copy of the module (KRAFTON/Raon-1-mini-preview-mlx
  @ c558ec0f, verbatim) as mlx_lm.models.raon1_mini, registered by the
  pre-load dispatch for model_type == "raon1_mini".
- For that exact model_file name, the load_config wrapper drops
  model_file so mlx-lm resolves the vendored class by model_type, and the
  remote-code gate passes. Any other model_file still needs the toggle.
- switch_compat backports the switch-layer half of ml-explore/mlx-lm#1844
  for this module: QuantizedSwitchLinear carries global_scale into
  mx.gather_qmm, and NVFP4 to_quantized keeps one per expert (the loader
  never flags Raon's merged gate_up). It is a no-op once the pin includes
  #1844.

Tests build a tiny NVFP4 checkpoint with per-expert global scales and no
model file on disk, load it strictly, and match prefill and cached decode
against a float model with the dequantized experts.


Claude-Session: https://claude.ai/code/session_01GWdPoMqLRWaCVjCtmzYp2S

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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.

3 participants