Skip to content

fix(qwen3.5): allow non-affine (nvfp4/mxfp8) quantized lm_head + MTP fc via LinearProj - #85

Merged
Brooooooklyn merged 3 commits into
mainfrom
worktree-fix-quantized-head-linearproj
Jul 5, 2026
Merged

Brooooooklyn merged 3 commits into
mainfrom
worktree-fix-quantized-head-linearproj

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The qwen3.5 dense lm_head and MTP fc could only load an affine quantized head. Linear::load_quantized / Linear::forward (crates/mlx-core/src/nn/linear.rs) hardcode c"affine" (dequant + mlx_quantized_matmul mode) and require biases. A micro-scaled head (nvfp4 / mxfp8 — scales only, no biases) crashed at load:

Biases must be provided for affine quantization

This is an unfinished early path (commit 08354f84, PR #32, when affine was the only mode). It forced NVIDIA-NVFP4 → MLX transcodes to fall back to an affine-int4 lm_head instead of keeping the intended per-layer bit allocation.

Fix

Migrate the qwen3.5 dense lm_head and both MTP fc fields (dense + moe) from Linear / Option<Linear> onto the mode-aware LinearProj (quantized_linear.rs) and install them via the existing try_build_ql dispatch on plq.mode — exactly as gemma4 and qwen3_5_moe already do for their heads. Linear::load_quantized is left untouched (other families still use it).

                       old (affine-only)            new (mode-aware)
lm_head / mtp.fc  ──▶  Linear::load_quantized  ──▶  LinearProj  ─┬─ bf16    → Standard(Linear)
                       (c"affine", needs biases)                 ├─ affine  → Quantized("affine")
                                                                 ├─ mxfp8   → Quantized("mxfp8")   ← was a crash
                                                                 └─ nvfp4   → Quantized("nvfp4")   ← was a crash
  • Task 1 d08372b6 — dense lm_head: Option<Linear> → Option<LinearProj>; install in persistence.rs; threaded through every model.rs + paged_forward.rs forward call site.
  • Task 2 96e3e450 — MTP fc: Linear → LinearProj in models/qwen3_5/mtp.rs and models/qwen3_5_moe/mtp.rs; removed a stale "falls through to set_weight" comment.
  • Tidy 293482fb — two cosmetic follow-ups from the final review (literal "affine" test assertion; "quantized" debug label).

No checkpoint or convert change — this removes a loader constraint only. Existing checkpoints keep bf16/affine heads unchanged.

Behavior preservation

  • bf16 head/fc → LinearProj::Standard → identical input.matmul(weight_t) (heads are bias-free).
  • affine head/fc → LinearProj::Quantized mode "affine" → identical mlx_quantized_matmul(x, weight, scales, biases, true, gs, bits, "affine") operands.
  • tied-embeddings path unchanged (lm_head is None when tied).

Validation

3 new install-type unit tests assert the mode dispatch (affine → Quantized("affine"), mxfp8 → Quantized("mxfp8"), bf16 → Standard) for the dense head and both MTP fc. cargo clippy -D warnings + cargo fmt clean.

E2E runtime (a hand-built qwen3.5-9B checkpoint with an mxfp8 lm_head — scales, no biases):

Head mode Result
bf16 (0.8b tied, 9B-bf16) ✅ coherent — unchanged path
affine (9B-unsloth) ✅ coherent — behavior preserved
mxfp8 (9B-mxfp8head) ✅ loads (was a crash) + generates correct text — the fix

The authoritative GPU parity suite (qwen3_5_paged_vs_flat_parity, qwen3_5_session) runs in CI.

🤖 Generated with Claude Code


Note

Medium Risk
Touches core inference and weight-loading paths for lm_head and MTP fc; behavior is intended to be parity-preserving for bf16/affine, with new support for mxfp8/nvfp4.

Overview
Fixes quantized checkpoint loading for dense lm_head and MTP fc (dense + MoE): those layers no longer go through affine-only Linear::load_quantized, which failed on mxfp8/nvfp4 heads missing affine biases.

They now use LinearProj with the same try_build_ql path as other projections, so affine, mxfp8, mxfp4, and nvfp4 install correctly; bf16 stays LinearProj::Standard. set_weight calls take a name label (e.g. "lm_head", "mtp.fc"). Forward/prefill/paged paths only change types to Option<LinearProj>; tied embeddings still leave lm_head as None.

Tests cover install dispatch for dense lm_head (mxfp8, affine, bf16, tied) and both MTP fc modules.

Reviewed by Cursor Bugbot for commit 293482f. Bugbot is set up for automated code reviews on this repo. Configure here.

Brooooooklyn and others added 3 commits July 5, 2026 01:22
The dense qwen3.5 `lm_head` was `Option<Linear>`, whose `load_quantized`
hardcodes affine dequant — an nvfp4/mxfp8/mxfp4/sym8 head crashed at load
("Biases must be provided for affine quantization"). Move it to
`Option<LinearProj>` and install through the per-layer-mode `try_build_ql`
dispatch, mirroring the gemma4 / qwen3_5_moe heads.

- `Qwen35Inner::lm_head`: `Option<Linear>` → `Option<LinearProj>`; untied
  construction wraps `LinearProj::Standard(Linear)`.
- Install site (`apply_weights_inner`): dispatch on `plq.mode` via
  `try_build_ql` + `set_quantized`, bf16 falls to `LinearProj::Standard`.
  The outer `Some(head)` guard preserves the tied path (head stays `None`).
- Thread `&Option<LinearProj>` + `head.forward(...)` through every forward
  call site in model.rs and paged_forward.rs; `set_weight` now names the head.

Behavior preserved: bf16 head → Standard (same dense matmul); affine head →
Quantized mode "affine" (same `mlx_quantized_matmul` operands as the old
`Linear::forward`). `Linear::load_quantized`/`forward` untouched (other
families still use them). Scoped to qwen3.5 dense.

New unit test `dense_lm_head_installs_mode_aware_linearproj` asserts mxfp8 and
affine heads install as `LinearProj::Quantized` (correct mode), bf16 as
`LinearProj::Standard`, and a tied config leaves the head `None`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The dense and moe MTP `fc` projections were `nn::Linear`, whose
`load_quantized` hardcodes affine dequant — an mxfp8/mxfp4/nvfp4 fc
crashed at load ("Biases must be provided for affine quantization") or
dequantized wrong. Move both `fc` fields to `LinearProj` and install
through the per-layer-mode `try_build_ql` dispatch each module already
uses for its attention/MLP projections, mirroring the Task 1 dense
lm_head migration (d08372b).

- `Qwen3_5MTPModule::fc` and `Qwen3_5MoeMTPModule::fc`: `Linear` ->
  `LinearProj`; ctor wraps `LinearProj::Standard(Linear::new(...))`.
- fc install: dispatch on `plq.mode` via `try_build_ql` + `set_quantized`,
  bf16 falls to `set_weight` (stays `Standard`). Dropped the old
  `self.fc.load_quantized(...)` affine-only path and the stale comment
  claiming non-affine fc weights fall through to `set_weight` (they hit
  the affine load instead — the bug).
- `has_quantized_weights` / `get_parameters` unchanged: `LinearProj`
  exposes the same `is_quantized` / `get_weight` API as `Linear`.

Behavior preserved: bf16 fc -> Standard (same dense matmul); affine fc ->
Quantized mode "affine" (same `mlx_quantized_matmul` operands, same
group_size/bits/biases). Our checkpoints keep the MTP fc bf16, so no
numeric change. `Linear::load_quantized`/`forward` untouched.

New unit test `mtp_fc_installs_mode_aware_linearproj` in both MTP modules
asserts a mxfp8 and an affine fc install as `LinearProj::Quantized` (right
mode) and a bf16 fc as `LinearProj::Standard`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ation

- persistence.rs install test: assert the affine head keeps mode "affine"
  against a string literal instead of the DEFAULT_QUANT_MODE constant, so the
  check is constant-rename independent (drops the now-unused import).
- qwen3_5/mtp.rs apply_weights debug log: label a quantized fc "quantized"
  instead of "affine-quantized" — the fc can now load in mxfp8/mxfp4/nvfp4,
  and the exact mode is already logged separately as default_quant_mode.

Both are cosmetic follow-ups from the final whole-branch review (no behavior
change); the 3 install tests + fmt stay green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 12ead166-9d20-4c1d-ba76-76c9f4c732d7

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-fix-quantized-head-linearproj

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cursor

cursor Bot commented Jul 5, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_8d77ce20-1a56-48af-befb-a6cbf76a1b6a)

@Brooooooklyn
Brooooooklyn merged commit 4e350f7 into main Jul 5, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the worktree-fix-quantized-head-linearproj branch July 5, 2026 10:57
Brooooooklyn added a commit that referenced this pull request Jul 8, 2026
…t recipe)

Ports NVIDIA modelopt's w4a16_nvfp4-fp8_attn-kv_fp8_cast PTQ recipe with MXFP4
substituted for NVFP4. Data-free: MLX's mlx_quantize(mxfp4) reproduces modelopt's
dynamic uncalibrated weight quantization exactly, and modelopt's calibration only
sets FP8 activation amax (mlx-node keeps activations/KV bf16), so no imatrix or
calibration data is needed. Covers dense qwen3_5 and MoE qwen3_5_moe.

Per-layer map: FFN gate/up/down (dense + MoE switch_mlp experts + shared_expert)
and lm_head -> mxfp4 4/32; self_attn q/k/v/o + GDN in_proj_qkv/z/out_proj ->
mxfp8 8/32; GDN in_proj_a/b -> affine 8/64 (T=0 MTP<->AR bit-exactness);
router gates -> affine 8/64 (mxfp8 destroys top-K routing); embeddings, norms,
conv1d, A_log/dt_bias, vision, MTP, in_proj_ba -> bf16.

Recipe emits Custom{mxfp4/mxfp8} directly (no --q-mxfp wrapper); runs under
top-level --q-mode affine. Rejects --imatrix-path/--q-mxfp/explicit --q-bits!=4/
--q-group-size!=32. Also adds video_preprocessor_config.json to the aux copy list
and de-stales the is_affine_only_key lm_head doc (mode-aware LinearProj post-#85).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

1 participant