Skip to content

fix(core): reject packed uint8 weights in dense linear loaders - #3019

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/reject-packed-bitlinear-as-dense
Nov 14, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/reject-packed-bitlinear-as-dense

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

A linear layer whose weight is uint8 with a .weight_scale beside it (a BitLinear/ternary export such as the Falcon3 1.58-bit Llama checkpoints, or FP8 / ModelOpt NVFP4 planes that a model's loader did not convert) has no .scales plane, so the dense loaders took the packed bytes for a dense matrix. The load succeeded and the first forward pass threw inside MLX, ending the process with SIGABRT. The dense loaders now refuse that layout at load time with an error that names the tensor.

Related issues

Closes #3018.

Type of change

  • fix — bug fix

Cause

FusedQKVLinear::from_weights_separate_with_mode (src/lib/mlxcel-core/src/layers.rs) treats a projection as quantized only when .scales exists; otherwise it concatenates the q/k/v weights as dense. Linear::from_weights, which is also the dense fallback of UnifiedLinear, accepts any .weight. Neither looks at the dtype, so uint8 rows that pack several logical rows each went straight into matmul and the attention reshape.

Change

  • reject_packed_bitlinear_as_dense (new, private): a uint8 weight with a {prefix}.weight_scale key is an error naming the tensor.
  • Called from Linear::from_weights and, for each of the three planes, from the dense branch of the separate-QKV loader (which builds its Linear directly).
  • Not changed: quantized planes (they have .scales and never reach these calls), float weights that happen to carry a weight_scale key, and the dedicated BitNet model, whose BitLinear loader does not use these paths.
  • This does not add inference support for any of these layouts.
  • src/lib/mlxcel-core/src/layers_packed_weight_tests.rs (new): packed_bitlinear_is_refused_by_single_and_preconcatenated_loaders, packed_bitlinear_is_refused_in_each_separate_qkv_plane (the packed plane as q, as k and as v), and float_planes_with_a_scale_sidecar_keep_the_dense_path (f32, f16 and bf16 planes with the sidecar still load).

Before / after

GB10 (sm_121, CUDA 13.0), release builds of 955335a38 (main, the base of this branch) and of this PR, generate -n 32 --temp 0 -p "What is the capital of France? Answer in one word.".

Checkpoint main This PR
mlx-community/Falcon3-1B-Instruct-1.58bit-4bit @ 22afc218dcbc exit 134, [reshape] Cannot reshape array of size 23552 into shape (1,23,8,256). exit 1, Error: Unsupported packed weight: model.layers.0.self_attn.q_proj.weight is uint8 with model.layers.0.self_attn.q_proj.weight_scale; this dense linear loader cannot decode it. …
AnveshGummala/qwen2.5-0.5b-nvfp4-max-quant @ 0bf21b0dbe6d (ModelOpt W4A16_NVFP4, not repacked on main) exit 134, [matmul] Last dimension of first input with shape (1,41,896) must match … exit 1, the same error for model.layers.0.self_attn.q_proj.weight
AxionML/Qwen3.5-4B-NVFP4 @ 4521f321 (ModelOpt NVFP4 on a loader route that does not repack it) exit 134, [matmul] Last dimension of first input with shape (1,22,2560) must match … exit 1, Error: Failed to load Qwen3.5 text model: Unsupported packed weight: model.layers.0.linear_attn.in_proj_qkv.weight is uint8 with …

Three checkpoints that load today answer Paris with the same output on both builds: bitnet-b1.58-2B-4T-4bit (the dedicated BitNet loader), Qwen2.5-0.5B-Instruct-4bit and Falcon3-1B-Instruct-3bit.

Test plan

Run on this PR's commit (443b59829, one commit on 955335a38, tree cd7f872dacd5) 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
  • cargo test -p mlxcel-core --profile test-fast --features cuda --lib packed_weight_tests: 3 passed
  • Negative control: with the two refusal calls made no-ops (the helper kept), the two refusal tests fail and the float control passes; restored, 3 pass
  • cargo test --profile test-fast --features cuda --lib models::bitnet: 6 passed
  • make verify-test-cuda (cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 186 of 187 test binaries pass (15496 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; 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 with 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
  • 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 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. The check is on dtype and key names, before any backend call

Notes for reviewers

  • What changes for a user. A checkpoint in one of these layouts now fails to load with a message, where it used to load and abort on the first token. Nothing that produced output before is refused: on main these bytes reach matmul as a dense uint8 matrix.
  • The message does not say which layout it is. The same key pair is a BitLinear export, an FP8 one, or an unconverted ModelOpt NVFP4 one; the text lists the three.
  • Other dense entry points are not covered. MultiLinear's regular arm, Embedding::from_weights and the models that build a Linear with Linear::new from a raw tensor do not go through Linear::from_weights. None of the three checkpoints above reaches them; they could get the same check separately.
  • The ModelOpt W4A16_NVFP4 checkpoint in the second row is made to load, not just refused, by a separate change I will propose; with both in place the refusal no longer fires for it.
  • Implemented and validated with AI assistance (Claude) driving the GB10 host. Every number above comes from the logs of those runs.

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 and on Linear::from_weights
  • No secrets, credentials, or .env files committed

A linear layer whose weight is uint8 and which carries a singular
`weight_scale` (a BitLinear/ternary export such as the Falcon3 1.58-bit
Llama checkpoints) has no `.scales` plane, so the dense fallback took the
packed rows for a dense matrix. The load succeeded and the first attention
reshape aborted the process.

Refuse that layout at load time with an error that names the tensor, in
`Linear::from_weights` and for each plane of the separate-QKV loader. The
dedicated BitNet loader does not use these paths and is unchanged. This
does not add inference support for such checkpoints.
@inureyes

Copy link
Copy Markdown
Member

Thanks for the careful write-up and the negative control, @Jaeyeong-CHOI. Maintainer review on Apple Silicon (M3 Ultra, Metal):

  • Purpose fit: the refusal covers both dense entry points named in fix(core): reject packed uint8 weights in dense linear loaders instead of aborting #3018 (Linear::from_weights, which UnifiedLinear falls back to, and each plane of the separate-QKV loader). Quantized planes never reach it, and the NVFP4 sanitize path drops weight_scale when it repacks, so checkpoints that load today are unaffected.
  • Security and performance: load-time key lookup and dtype read only, no forward-path cost.
  • Merged main into the branch (no conflicts). No code changes were needed.

Validation on Metal:

  • cargo test -p mlxcel-core --lib packed_weight_tests: 3 passed
  • cargo clippy --lib --tests -- -D warnings: clean
  • cargo build --release and a qwen3.5-4b-4bit generate smoke run: unchanged output

The other dense entry points you listed (MultiLinear, Embedding::from_weights, direct Linear::new) can take the same check in a follow-up if a checkpoint reaches them.

@inureyes
inureyes merged commit 836ada4 into lablup:main Nov 14, 2026
31 checks passed
@inureyes inureyes added the status:done Completed label Nov 14, 2026
inureyes pushed a commit that referenced this pull request Nov 15, 2026
… a ModelOpt group size (#3026)

## 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

- [x] `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).

- [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 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
- [x] `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
- [x] 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)
- [x] 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)
- [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 (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; #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), `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
- [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 real checkpoints: the tables above
- [x] 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 #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

- [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
- [x] 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.
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers modeltype:text Text-only language model arch:dense Dense transformer decoder labels Nov 30, 2026
@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 modeltype:text Text-only language model priority:medium Medium 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(core): reject packed uint8 weights in dense linear loaders instead of aborting

2 participants