Skip to content

fix(quant): load ModelOpt W4A16_NVFP4 checkpoints in families without a ModelOpt group size - #3026

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/modelopt-nvfp4-plane-mode
Nov 15, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/modelopt-nvfp4-plane-mode

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A ModelOpt checkpoint with quant_algo: W4A16_NVFP4 (NVFP4 weights, activations left at 16 bit) aborted at its first forward pass. The name was not recognized as the NVFP4 triplet format, so nothing was repacked; and once it is recognized, a family without a ModelOpt group size (Llama, and through it Qwen2.5) still decoded the planes as mxfp4. Both are closed here: the name is accepted, and the loader infers a block-float mode from the group size the shapes give.

Related issues

Closes #3024.

#2444 closed the second half for Qwen3, Qwen3-MoE, PhiMoE and Mistral 4 by giving each family a ModelOpt group size. This PR closes it in the two loaders those accessors feed (UnifiedLinear::from_weights and FusedQKVLinear::from_weights_separate), for every family that loads through them.

Type of change

  • fix — bug fix

Cause

  1. is_modelopt_nvfp4 (src/models/gemma4.rs) required quant_algo == "nvfp4". W4A16_NVFP4 checkpoints store the same {weight, weight_scale, weight_scale_2} triplets, but load_text_weights repacks only when the predicate holds, so the uint8 plane [out, in/2] stayed as it was and loaded as a dense weight. The first matmul throws inside MLX.
  2. UnifiedLinear::from_weights and FusedQKVLinear::from_weights_separate inferred the mode with infer_quantization_mode(has_biases, group_size, bits) from the declared group size. A family whose group_size() falls back to 64 therefore got mxfp4; reconcile_quantization_layout then corrected the group size to 16 from the shapes and kept the mode, and the E4M3 block scales were decoded as MXFP4 exponents.

Change

  • is_modelopt_nvfp4 accepts w4a16_nvfp4 beside nvfp4. No other algorithm name is added: NVFP4_AWQ carries a pre-quantization scale and is not the same format.
  • infer_plane_quantization_mode (new, mlxcel-core layers.rs): for a plane without .biases, reconcile the layout against the shapes first and infer the mode from the group size that gives. At the 4 bits these planes declare, 16 wide is NVFP4 and 32 wide is MXFP4, whatever group size was declared. A plane with .biases is affine as before, and shapes that reconcile to nothing keep the declared guess so the loader reports that error itself. src/vision/weights.rs already infers from the effective group size.
  • Used by UnifiedLinear::from_weights and FusedQKVLinear::from_weights_separate. Loaders that pass an explicit mode (from_weights_with_mode) are untouched.

Before / after

GB10 (sm_121, CUDA 13.0), release builds of 955335a38 (main, the base of this branch) and of this PR, generate -n 48 --temp 0, MLXCEL_SDPA_DETERMINISTIC=1.

AnveshGummala/qwen2.5-0.5b-nvfp4-max-quant @ 0bf21b0dbe6d and AnveshGummala/qwen2.5-3b-nvfp4-max-qat_quant @ 6119bc238f88 (model_type: qwen2, ModelOpt 0.47.0, W4A16_NVFP4, group size 16):

Prompt main, both checkpoints This PR, 0.5B This PR, 3B
What is the capital of France? Answer in one word. abort in matmul, exit 134 Paris. Paris
What is 2 + 2? Answer with just the number. abort, exit 134 4 4
Write one sentence about the sea. abort, exit 134 The vast and boundless ocean stretches across the Earth, teeming with life and containing vast amounts of water, creating a vast expanse of blue and white. The sea is a vast and mysterious body of water that covers most of the Earth's surface.

Each half alone, first prompt on the 0.5B checkpoint (test-fast builds with one half reverted; these two builds were made from the previous revision of this branch, 05bbc1ad0, which differs from this commit in two doc comments only):

Build Result
the name not accepted abort in matmul, exit 134, as on main
the name accepted, mode inferred from the declared group size the original the original the original … (noise), 96 layout warnings
both (this PR) Paris.

Checkpoints that load today give the same output for the first prompt (200 tokens) as on main, one of each quantization kind at hand: Qwen3.5-0.8B nvfp4, mxfp4 and mxfp8 (native MLX block-float), Qwen3-1.7B-MLX-MXFP4, MiniCPM-V 4.6 (MXFP4 at group 32 under a default of 64), Qwen3-0.6B-4bit, SmolLM3-3B-4bit, gemma-3-270m-it-4bit, gemma-3-4b-it-4bit, Qwen3-VL-4B-Instruct-4bit. Two of them, Qwen3.5-0.8B-mxfp8 and Qwen3-0.6B-4bit, spend all 200 tokens reasoning, so for those the comparison was repeated with --show-reasoning: the reasoning text is identical too.

Test plan

Run on this PR's commit (ffd56be29, one commit on 955335a38, tree e9bca0dd5809) on a DGX Spark (GB10).

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --features cuda -- -D warnings (the Linux spelling of the template's line)
  • cargo build --release --features cuda
  • The four new tests by name: a_block_float_linear_takes_the_mode_its_packing_implies and modelopt_nvfp4_qkv_under_the_default_group_size_loads_as_nvfp4 (mlxcel-core), a_w4a16_nvfp4_checkpoint_is_repacked_and_loads_as_nvfp4 and other_modelopt_algorithms_are_not_repacked_as_nvfp4: pass. The core tests compare the output bytes of a plane loaded under the default 64 with the same plane loaded under its true 16
  • cargo test -p mlxcel-core --profile test-fast --features cuda --lib layers::: 108 passed; cargo test --profile test-fast --features cuda --lib -- models::sanitize modelopt nvfp4 mxfp4 quantiz models::llama3 models::qwen3 models::gemma4 vision::weights: 636 passed
  • Negative control 1, the name not accepted: the repack test fails ("weight_scale was not repacked"). The 0.5B checkpoint aborts on such a build (run on 05bbc1ad0, see above)
  • Negative control 2, the mode from the declared group size: both core tests fail (("mxfp4", 16, 4) for ("nvfp4", 16, 4)) and the repack test fails. The 0.5B checkpoint prints noise on such a build (run on 05bbc1ad0, see above)
  • make verify-test-cuda (cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 186 of 187 test binaries pass (15497 tests passed, 1 failed, 496 ignored), the four new tests among them. The one failure is native_env_tests::the_cuda_cache_defaults_reach_mlx, which fails the same way on a clean main (order-dependent; test(cuda): make verify-test-cuda fails the cache-default test on every CUDA host since #2876 #2987)
  • The self-hosted ci.yml jobs a pull request from a fork does not get, run by hand: clippy (cargo clippy -p mlxcel --lib --tests -- -D warnings, default features), cpu-link (cargo test -p mlxcel-core --profile test-fast --lib --no-run, then the two new core tests on that CPU build) and xla-compile (cargo check --features cuda,xla-iree --all-targets, cargo check --no-default-features --features xla-diagnostics --all-targets): all pass
  • make verify-python-tooling (219 tests OK), license headers, env-var docs, kernel dtype keys, kernel port dispatch, cross-repo refs
  • Validated with real checkpoints: the tables above
  • Traced per "Judging a change that moves the numbers": the layout of a plane moves only where its shapes contradict the declared group size (see the notes); ten checkpoints across affine, MXFP4, MXFP8 and native NVFP4 answer word for word as on main
  • cargo deny check: not run and not applicable (no manifest, lockfile or deny.toml change)
  • Metal: not built or run here. The NVFP4 and MXFP4 halves of the core test and the repack test skip where the backend has no native kernel for the mode

Notes for reviewers

  • Llama/Qwen2.5 ModelOpt metadata. Hardening adds the same ModelOpt group-size accessor used by Qwen3 to the Llama config reader. A declared NVFP4 or W4A16_NVFP4 config now supplies group size 16, eliminating the default-64 layout mismatch described in the original measurement. Explicit MLX quantization settings retain priority. Other families still benefit from the shape-derived mode fallback; their metadata warnings are outside this Llama/Qwen2.5 correction.
  • What can move. Only a bias-free 4-bit plane whose shapes give another group size than the declared one: 16 wide declared wider now loads as nvfp4 (was mxfp4 at 16, which no MLX quantizer produces), and 32 wide declared as 16 loads as mxfp4 (was nvfp4 at 32, likewise). MiniCPM-V 4.6, whose MXFP4 planes are stored at 32 under a config default of 64, answers as before.
  • Not covered. AxionML/Qwen3.5-4B-NVFP4 (plain NVFP4) aborts on main with the same kind of message for another reason: its loader route does not repack ModelOpt triplets. NVFP4_AWQ, MIXED_PRECISION and the FP8 algorithms are other formats; a test pins that they are not repacked as NVFP4.
  • Relation to fix(core): reject packed uint8 weights in dense linear loaders #3019. That PR makes the dense loaders refuse an unconverted uint8 plane, which turns the abort of these checkpoints into a load error. This PR makes them load; with both merged the refusal no longer fires for W4A16_NVFP4. The two touch different parts of layers.rs and do not depend on each other.
  • Not run: Metal and ROCm.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/: not needed (no option, flag or documented behaviour changes)
  • Updated // Used by: ... comments: on the new function
  • No secrets, credentials, or .env files committed

Implementation hardening

The original issue #3024 also requires the Llama/Qwen2.5 ModelOpt group-size warning to disappear. The config now retains ModelOpt metadata and resolves its recognized NVFP4 group size before the default of 64. Regression coverage checks both accepted aliases, case normalization, explicit MLX settings taking priority, rejection of other algorithms, and the unchanged default.

… a ModelOpt group size

A ModelOpt export whose `quant_algo` is `W4A16_NVFP4` (NVFP4 weights,
unquantized activations) stores the same `{weight, weight_scale,
weight_scale_2}` triplets as `NVFP4`. `is_modelopt_nvfp4` accepted only the
latter, so nothing was repacked and the packed bytes reached a dense matmul,
which throws inside MLX and ends the process:

    [matmul] Last dimension of first input with shape (1,41,896) must match
    second to last dimension of second input with shape (448,1152).

Recognizing the name is not enough for a family whose config reader knows
only the mlx-lm `quantization` block (Llama, and with it Qwen2.5): it
declares its default group size of 64 for every plane, the mode is inferred
from that as `mxfp4`, and the layout reconciliation then corrects the group
size to 16 from the shapes but keeps the mode. `UnifiedLinear::from_weights`
and `FusedQKVLinear::from_weights_separate` now infer a block-float mode from
the group size the shapes give, as the vision weight loader already does.
@inureyes inureyes added arch:dense Dense transformer decoder area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:models Model architectures, weights, loading, metadata modeltype:text Text-only language model priority:high High priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions labels Nov 15, 2026
Read recognized NVFP4 metadata before falling back to group size 64 so Qwen2.5 projections do not emit avoidable layout mismatch warnings. Preserve explicit MLX settings and cover aliases, unsupported algorithms, and missing metadata.

Refs lablup#3024, lablup#3026
@inureyes

Copy link
Copy Markdown
Member

Implementation hardening for #3026.

Reviewed #3024: shape-derived block-float inference and the W4A16_NVFP4 alias correctly cover linear and separate-QKV loaders. Found and fixed the remaining acceptance gap: Llama/Qwen2.5 still declared group size 64, producing metadata warnings. The config now retains ModelOpt metadata and uses the shared group-size accessor while preserving explicit MLX settings. No additional security or hot-path performance defect was found.

Validation: The existing native NVFP4/MXFP4 tests passed in the CUDA core suite; repacking tests passed in the combined CUDA root suite. New config regression coverage checks aliases, case handling, explicit-setting priority, other algorithms, and absent metadata. Real-checkpoint throughput was not re-run.

Combined validation: cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1 completed with 15,611 passed, 3 failed, and 498 ignored. The three failures are the XLA bundled-golden comparisons; all three also fail on unmodified main at f0088c9 (the stateful decode emitter from #3048 differs from the bundled fixtures). They are not introduced by this PR. Python tooling passed 238 tests.

cargo clippy --workspace --profile test-fast --all-targets --features cuda -- -D warnings passed after updating all Llama config fixtures for the new metadata field. Formatting and kernel dtype-key checks passed.

Final fix validation: cargo test --workspace --profile test-fast --features cuda --lib modelopt_nvfp4_declares_the_effective_llama_group_size passed. The resulting CUDA test binary also passed all 75 selected Llama, headless Llama, bidirectional Llama, and Helium regressions under gpu-lock. The fix is commit 527591a.

@inureyes
inureyes merged commit 6f20b79 into lablup:main Nov 15, 2026
33 checks passed
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 15, 2026
inureyes pushed a commit that referenced this pull request Nov 15, 2026
…3030)

## Summary

A ModelOpt NVFP4 export of Qwen3.5 that includes the vision tower (`AxionML/Qwen3.5-4B-NVFP4`) aborted at its first forward pass: the Qwen3.5 VLM loader never repacked ModelOpt's `{weight, weight_scale, weight_scale_2}` triplets, so the packed bytes reached the text model as dense weights. The loader now runs the same repack the text-only loaders use.

## Related issues

Closes #3029.

Stacked on #3026 (the fix for #3024): the first commit of this branch is that PR, and only the second commit is new. The repack makes the checkpoint load; #3026 is what makes the repacked planes decode as NVFP4 for a family whose config has no ModelOpt group size, which Qwen3.5 is.

## Type of change

- [x] `fix` — bug fix

## Cause

`load_qwen3_5_vlm_with_variant` (`src/loading/vlm_qwen.rs`) reads the checkpoint itself (`load_vlm_weights_common`), converts FP8 layouts, splits the map into text and vision weights and builds the model. The ModelOpt repack (`sanitize_modelopt_nvfp4_weights`, #2351) is called from `load_text_weights`, which the text-only loaders use and this route does not.

## Change

- **`split_qwen3_5_vlm_weights`** (new, `vlm_qwen.rs`): the loader's existing key split, moved into a function, followed by the ModelOpt repack of the text weights when `is_modelopt_nvfp4_text_checkpoint` holds for the config (or for `hf_quant_config.json`, as on the text-only route). It runs after the split, so the keys carry the text model's own names; the vision tower, which ModelOpt leaves unquantized, has no triplets and is untouched.
- `sanitize_modelopt_nvfp4_weights` and `is_modelopt_nvfp4_text_checkpoint` (`src/models/sanitize.rs`) become `pub(crate)` and are re-exported from `models`.
- `src/loading/vlm_qwen35_modelopt_tests.rs` (new): `a_modelopt_nvfp4_checkpoint_is_repacked_on_the_vlm_route`, `the_vlm_route_repacks_only_what_the_config_declares` (no declaration, ModelOpt `FP8`, another `quant_method`), `the_vlm_route_reads_the_modelopt_sidecar_file`.

## Before / after

GB10 (sm_121, CUDA 13.0), release builds, `generate -n 600 --temp 0`, `MLXCEL_SDPA_DETERMINISTIC=1`, `AxionML/Qwen3.5-4B-NVFP4` @ `4521f321`. "#3026 only" is the release build of that PR's commit.

| Prompt | `main` (`955335a38`) | #3026 only | This PR |
|---|---|---|---|
| What is the capital of France? Answer in one word. | abort in `matmul`, exit 134 | abort, exit 134 | `Paris` (157 tokens with the reasoning) |
| What is 2 + 2? Answer with just the number. | abort, exit 134 | abort, exit 134 | `4` (152 tokens) |
| `--image tests/fixtures/test_image_shapes.png`, "What shapes are in this image? Answer in one short sentence." | abort, exit 134 | not run | `This image features a red square, a blue circle, and a green triangle.` (233 tokens) |
| Write one sentence about the sea. | abort, exit 134 | abort, exit 134 | no answer within 600 tokens: the model is still weighing drafts in its reasoning channel, which reads coherently with `--show-reasoning` |

The repack call alone, on `955335a38` without #3026 (a test-fast build): the checkpoint loads and prints `1. 1. 2. 2. 3. 3. …`. Both halves are needed.

A second checkpoint, run after this PR was opened, with the build of tree `b7389ccdd4a7`: `AxionML/Qwen3.5-9B-NVFP4` @ `97aef923` aborts on `main` in the same way (`(1,22,4096)` against `(2048,8192)`, exit 134) and on this PR answers `Paris` (157 tokens), `4` (173 tokens) and, with the image, `A red square, a blue circle, and a green triangle.` (167 tokens).

The MoE export `AxionML/Qwen3.5-35B-A3B-NVFP4` @ `75f5a9d9` aborts on `main` too (exit 134). On this PR it stops at load with `Error: Failed to load Qwen3.5 text model: Missing biases: model.layers.0.mlp.switch_mlp.gate_proj` (exit 1): its triplets are repacked, but the expert layers of this family load affine planes only. That is the limit named in the notes below, now measured.

Twelve checkpoints that load on the #3026 build give the same output for the first prompt (300 tokens) on this PR as on that build, and the eleven of them that load on `main` the same as on `main`: Qwen3.5-0.8B 4bit, bf16, nvfp4, mxfp4 and `-decision`, Qwen3-VL-4B-Instruct-4bit, gemma-3-4b-it-4bit, gemma-4-e2b-it-4bit, SmolLM3-3B-4bit, Qwen3-1.7B-MLX-MXFP4, MiniCPM-V 4.6, and the ModelOpt Qwen2.5-0.5B of #3024 (the one that aborts on `main`). With the image, Qwen3.5-0.8B-bf16 and Qwen3-VL-4B-Instruct-4bit answer the same on `main` and on this PR.

## Test plan

Run on a DGX Spark (GB10). The full run below was made on tree `b7389ccdd4a7`. This PR's commit (`0778248fb`, the second commit of the branch; tree `d87d5a63801c`) differs from it by two doc comments in `src/models/sanitize.rs`; on that final tree the format check, the three new tests, and both clippy runs were repeated.

- [x] `cargo fmt --all -- --check`
- [x] `cargo clippy --workspace --all-targets --features cuda -- -D warnings` (the Linux spelling of the template's line)
- [x] `cargo build --release --features cuda`
- [x] The three new tests by name: pass
- [x] `cargo test --profile test-fast --features cuda --lib -- --test-threads=1 loading:: models::sanitize modelopt nvfp4 models::qwen3_5`: 547 passed
- [x] Negative control, the repack not called on this route: the first and the third new test fail, the second (nothing declared, nothing repacked) passes
- [x] `make verify-test-cuda` (`cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1`): 186 of 187 test binaries pass (15500 tests passed, 1 failed, 496 ignored), the three new tests among them. The one failure is `native_env_tests::the_cuda_cache_defaults_reach_mlx`, which fails the same way on a clean `main` (order-dependent; #2987)
- [x] The self-hosted `ci.yml` jobs a pull request from a fork does not get, run by hand: `clippy` (`cargo clippy -p mlxcel --lib --tests -- -D warnings`, default features), the three new tests on that CPU build, and `xla-compile` (`cargo check --features cuda,xla-iree --all-targets`, `cargo check --no-default-features --features xla-diagnostics --all-targets`): all pass
- [x] `make verify-python-tooling` (219 tests OK), license headers, env-var docs, kernel dtype keys, kernel port dispatch, cross-repo refs
- [x] Validated with a real checkpoint, text and image: the table above
- [ ] `cargo deny check`: not run and not applicable (no manifest, lockfile or `deny.toml` change)
- [ ] Metal and ROCm: not built or run here

## Notes for reviewers

- **The "quantized layout does not match declared metadata" warnings remain** (248 on this checkpoint), as for the Llama-family checkpoints in #3026: the config still declares the default group size and the loader reconciles it from the shapes.
- **Activations.** The export also quantizes activations (`input_scale`); mlxcel runs the weights only, as it does for the other ModelOpt NVFP4 checkpoints it loads. The repack removes those tensors.
- **No reference comparison.** I did not compare the outputs with another runtime; the evidence is that the answers are right and the reasoning text is coherent, where `main` cannot run the checkpoint at all.
- **Not covered: the MoE variant.** `load_qwen3_5_moe_vlm` goes through the same function, so its triplets are repacked too, but its experts still do not load (`SwitchLinear` there is affine-only and the per-expert `global_scale` is not stacked); see the measured load error above. The text-only route has the same limit.
- **Not covered: other VLM routes.** Qwen2-VL, Qwen2.5-VL, Qwen3-VL, the GLM loaders, Gemma 3 and the other loaders that read their checkpoint through `load_vlm_weights_common` still do not repack ModelOpt triplets. This PR closes the gap for the Qwen3.5 route only, the one I had a checkpoint for.
- **Not covered.** A text-only Qwen3.5 ModelOpt export goes through `load_text_weights` and is already repacked there; I had no such checkpoint to run.
- **`--surgery` ordering.** On this route a surgery transform runs when the checkpoint is read, before the split and therefore before the repack; on the text-only route it runs after. `main` could not run such a checkpoint at all, so nothing existing changes.

## Checklist

- [x] PR title uses a Conventional Commits prefix
- [x] One logical change per PR
- [ ] Updated `docs/`: not needed (no option, flag or documented behaviour changes)
- [x] Updated `// Used by: ...` comments: on the new function and on the two functions it now calls
- [x] No secrets, credentials, or `.env` files committed
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:dense Dense transformer decoder area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:models Model architectures, weights, loading, metadata modeltype:text Text-only language model priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(quant): load ModelOpt W4A16_NVFP4 checkpoints in text families without a ModelOpt group size

2 participants