Repository navigation
fix(quant): load ModelOpt W4A16_NVFP4 checkpoints in families without a ModelOpt group size - #3026
Conversation
… 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.
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
|
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:
Final fix validation: |
…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
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 asmxfp4. 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_weightsandFusedQKVLinear::from_weights_separate), for every family that loads through them.Type of change
fix— bug fixCause
is_modelopt_nvfp4(src/models/gemma4.rs) requiredquant_algo == "nvfp4".W4A16_NVFP4checkpoints store the same{weight, weight_scale, weight_scale_2}triplets, butload_text_weightsrepacks only when the predicate holds, so theuint8plane[out, in/2]stayed as it was and loaded as a dense weight. The firstmatmulthrows inside MLX.UnifiedLinear::from_weightsandFusedQKVLinear::from_weights_separateinferred the mode withinfer_quantization_mode(has_biases, group_size, bits)from the declared group size. A family whosegroup_size()falls back to 64 therefore gotmxfp4;reconcile_quantization_layoutthen 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_nvfp4acceptsw4a16_nvfp4besidenvfp4. No other algorithm name is added:NVFP4_AWQcarries a pre-quantization scale and is not the same format.infer_plane_quantization_mode(new,mlxcel-corelayers.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.biasesis affine as before, and shapes that reconcile to nothing keep the declared guess so the loader reports that error itself.src/vision/weights.rsalready infers from the effective group size.UnifiedLinear::from_weightsandFusedQKVLinear::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@0bf21b0dbe6dandAnveshGummala/qwen2.5-3b-nvfp4-max-qat_quant@6119bc238f88(model_type: qwen2, ModelOpt 0.47.0,W4A16_NVFP4, group size 16):main, both checkpointsmatmul, exit 134Paris.Paris44The 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):matmul, exit 134, as onmainthe original the original the original …(noise), 96 layout warningsParis.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 on955335a38, treee9bca0dd5809) on a DGX Spark (GB10).cargo fmt --all -- --checkcargo clippy --workspace --all-targets --features cuda -- -D warnings(the Linux spelling of the template's line)cargo build --release --features cudaa_block_float_linear_takes_the_mode_its_packing_impliesandmodelopt_nvfp4_qkv_under_the_default_group_size_loads_as_nvfp4(mlxcel-core),a_w4a16_nvfp4_checkpoint_is_repacked_and_loads_as_nvfp4andother_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 16cargo 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 passed05bbc1ad0, see above)("mxfp4", 16, 4)for("nvfp4", 16, 4)) and the repack test fails. The 0.5B checkpoint prints noise on such a build (run on05bbc1ad0, 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 isnative_env_tests::the_cuda_cache_defaults_reach_mlx, which fails the same way on a cleanmain(order-dependent; test(cuda): make verify-test-cuda fails the cache-default test on every CUDA host since #2876 #2987)ci.ymljobs 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) andxla-compile(cargo check --features cuda,xla-iree --all-targets,cargo check --no-default-features --features xla-diagnostics --all-targets): all passmake verify-python-tooling(219 tests OK), license headers, env-var docs, kernel dtype keys, kernel port dispatch, cross-repo refsmaincargo deny check: not run and not applicable (no manifest, lockfile ordeny.tomlchange)Notes for reviewers
nvfp4(wasmxfp4at 16, which no MLX quantizer produces), and 32 wide declared as 16 loads asmxfp4(wasnvfp4at 32, likewise). MiniCPM-V 4.6, whose MXFP4 planes are stored at 32 under a config default of 64, answers as before.AxionML/Qwen3.5-4B-NVFP4(plainNVFP4) aborts onmainwith the same kind of message for another reason: its loader route does not repack ModelOpt triplets.NVFP4_AWQ,MIXED_PRECISIONand the FP8 algorithms are other formats; a test pins that they are not repacked as NVFP4.uint8plane, which turns the abort of these checkpoints into a load error. This PR makes them load; with both merged the refusal no longer fires forW4A16_NVFP4. The two touch different parts oflayers.rsand do not depend on each other.Checklist
docs/: not needed (no option, flag or documented behaviour changes)// Used by: ...comments: on the new function.envfiles committedImplementation 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.