Skip to content

🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints - #50245

Open
ArthurZucker wants to merge 50 commits into
mainfrom
mixed-nvfp4-fp8-plan
Open

ArthurZucker wants to merge 50 commits into
mainfrom
mixed-nvfp4-fp8-plan

Conversation

@ArthurZucker

@ArthurZucker ArthurZucker commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

🤗 Transformers CI

TLDR: we refactor the AutoQuantizer to support a quantization_plan. This defines a mapping: { checkpoint_layer_name: quantizer}.

Based on this, the hf_quantizer's job is to:

  1. update the weight conversion operations to also run on the quantization weights
  2. make sure all weights are dequantized or deserialized or quantized using conversion ops before / after the ones that are already running
  3. make sure all of this follows the quantization_plan -> a single quantizer per layer.

This requires a few changes to standardize load_operations per quantization method, and ensure dequantized or deserialized or quantized are all standard WeightConversionOperations.

Also introduces NVFP4Experts(nn.Module) which is fairly long but standard w.r.t fp8.

Supersedes #49818 and #49658 (mixing quantization methods per module); overlaps #49779 and #49851 for pre-quantized NVFP4.
Related issues: #38253, #48371, #44292, #46772. Needs huggingface/kernels-community#1291 for fp8 experts.

@HuggingFaceDocBuilderDev

HuggingFaceDocBuilderDev commented Nov 2, 2026 •

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
@ArthurZucker
ArthurZucker force-pushed the compressed-tensors-dequantize-on-load branch from bc6733c to 7cf9e8a Compare November 4, 2026 08:40
Base automatically changed from compressed-tensors-dequantize-on-load to main November 5, 2026 02:51
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/core_model_loading.py Resolved
@ArthurZucker

Copy link
Copy Markdown
Collaborator Author

run-slow: deepseek_v4, ministral3, mistral4, aqlm_integration, bitnet_integration, eetq_integration, finegrained_fp8, higgs, metal, mxfp4, nvfp4, sinq

@IlyasMoutawwakil IlyasMoutawwakil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

did a first pass ! awesome work ! can't wait for it to be merged !

i think we can generalize the custom schema -> quant plan conversion through a schema readers (dict or registry). right now i can think of four cases for it (modelopt, dsv4/dsv4.1, m3.1) and compressed-tensors (at least for moes since CT are only gonna be adding linear kernels).

the docs need some rework and to not reinforce the mistakes in finegrained-fp8.

Comment thread docs/source/en/quantization/overview.md Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved

@vasqu vasqu 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.

Releasing my first round as well, my focus were the 2 core files you mentioned. I'll make another pass going through the other stuff

Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/quantizers/base.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved

@vasqu vasqu 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.

2nd round, going over all other things

Comment thread docs/source/en/quantization/overview.md Resolved
Comment thread src/transformers/core_model_loading.py Resolved
Comment thread src/transformers/core_model_loading.py Resolved
Comment thread src/transformers/core_model_loading.py Resolved
@ArthurZucker ArthurZucker changed the title [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints Nov 12, 2026
@vasqu

vasqu commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator

Can we clean up the string comments -> docstrings + a bit spacing for readability.

Last note: not sure but I would advertise nvfp4 as severly limited on top of the doc

@IlyasMoutawwakil

Copy link
Copy Markdown
Member

pushed 2baa90f for the docstrings / spacing / nvfp4 note:

  • last two single-quoted docstrings are proper """ now, didn't find other string comments
  • some breathing room in the denser bits (from_plan, replace_modules, quantized_modules, nvfp4 linear/experts, mxfp4 grouped forward, nvfp4 validate_environment)
  • warning at the top of the nvfp4 doc: blackwell only, no tp, no offload, no saving/training, experts only from pre-quantized checkpoints
  • also fixed the nvfp4 ep test on 2 gpus (it forced gloo with cuda tensors + had some cpu/cuda device mismatches)

one correction to #50670's description: test_qkv_chunk_rope_permute_with_fp8_quantization fails on main too, so it's not a regression from this pr, the test is just outdated (fake quantizer)

Comment thread docs/source/en/quantization/nvfp4.md Resolved
…ints

Load per-layer quantized checkpoints (ModelOpt MIXED_PRECISION, DeepSeek-V4's
FP8 + MXFP4 experts) as a plan of {module pattern: quantizer}. Quantize and
dequantize become load operations, so each layer loads with its own format.
Comment thread src/transformers/quantizers/auto.py Resolved
Comment thread src/transformers/quantizers/auto.py Resolved
`conversion_mapping.py` carries the same scoping/bake edits as #51501 in a
different generation (it also still has `seen_identifiers`), so keep main's
version here and leave that refactor to its PR: no duplication between the two.

The restore brings back `test_child_with_same_model_type_as_root_is_skipped`,
which #51501 removes; the dedup it tests is still present on this branch.

`core_model_loading.py` is untouched: its added lines are all quantizer
plumbing (`update_weight_transform`, `rename_layer`, `tensor_idx`, the
`Concatenate` stack) that the plan needs, none of it in #51501.
`compile_matcher` glued the pattern into `.*(?:{name})\.`, so a plan entry
`experts` also named `shared_experts` (DeepSeek, GLM, Kimi...) and an unescaped
`.` let `layers.1` name `layersa1`.

Escape the literal part of the pattern, keep `*` as the only wildcard, and
require a module boundary before the name too (`(?<![^.])`), which keeps
`p` matching `P` under any prefix. The `*` fallback stays a plain `.*`.

Regression test: `{"experts": q, "layers.1": q, "*": q}` leaves
`shared_experts` on `*`, and `layers.1` doesn't name `layersa1` or `layers.11`.
@tarekziade

Copy link
Copy Markdown
Collaborator

I ran this PR's head (71e492e1c8) against its merge base (1097d1570e) on our benchmark boxes (RTX PRO 4500 Blackwell, sm_120, kernels 0.18.2 on both sides), loading a few real quantized checkpoints. Two problems on the PR side:

1. gpt-oss-20b (MXFP4) loads with its experts randomly initialized

No error is raised. The load report shows the MXFP4 expert tensors are not consumed and the dequantized parameters are created empty:

GptOssForCausalLM LOAD REPORT from: openai/gpt-oss-20b
Key                                                   | Status
------------------------------------------------------+-----------
model.layers.{0...23}.mlp.experts.gate_up_proj_blocks | UNEXPECTED
model.layers.{0...23}.mlp.experts.down_proj_blocks    | UNEXPECTED
model.layers.{0...23}.mlp.experts.down_proj           | MISSING
model.layers.{0...23}.mlp.experts.gate_up_proj        | MISSING

The model then fails during generate. The same checkpoint loads cleanly on the merge base, with no load report and 12.8 GiB on the GPU.

2. A modelopt NVFP4 checkpoint crashes in map_module_to_quantizer

  File "src/transformers/quantizers/auto.py", line 600, in preprocess_model
    self.map_module_to_quantizer(model)
  File "src/transformers/quantizers/auto.py", line 429, in map_module_to_quantizer
    converters = [t for t in transforms if isinstance(t, WeightConverter)]
TypeError: 'NoneType' object is not iterable

With nvidia/Qwen3-8B-NVFP4 (quant_method: modelopt, NVFP4). The merge base rejects it with "Unknown quantization type, got modelopt". If modelopt NVFP4 isn't meant to be supported here, a clear error would be better than this TypeError.

Repro (one GPU, either checkpoint):

import torch
from transformers import AutoModelForCausalLM

AutoModelForCausalLM.from_pretrained(
    "openai/gpt-oss-20b",  # or "nvidia/Qwen3-8B-NVFP4" with attn_implementation="sdpa"
    attn_implementation="eager",
    dtype=torch.bfloat16,
    device_map="cuda",
)

No regression on fine-grained FP8 (6 paired rounds each, head vs base):

checkpoint e2e decode 95% CI weights
Qwen/Qwen3-1.7B-FP8 +0.11% [-1.07, +1.31] identical (1.94 GB, stays FP8)
Qwen/Qwen3-8B-FP8 +0.21% [-0.66, +1.10] identical (9.0 GB)

Load RSS is +0.3 to +0.75% on the PR side, which is significant but below 1%.

`update_weight_conversions` rewrote every `.weight` converter with one `names`
list built from each dequantizing format, so a layer whose format does not
dequantize also got the scales folded into its weight: its group resolved to a
source pattern (`.experts.*.w2.weight`) and loading died on
`AttributeError: MixtralForCausalLM has no attribute ''`.

`weight_converter` replaces `update_weight_transform` and does it per param,
where the module (hence the format) is known:

    model converter, dequantize    its sources also collect the serialized companions, so one
                                   load op reads the weight and its scale together
    model converter, no dequantize its sources, the load op after the model's ops
    on the fly                     a quantize op, sets `quantization_operation`
    no quantizer                   unchanged

so `update_weight_conversions` only renames a plan written in the checkpoint's
module names and adds each format's own converters (a serialized companion is
one of them). Op order is stated once: a dequantize reads the scales before
the model's ops, a deserialize unpacks the merged tensor after them.
A plan held its per-pattern configs in a bare dict, so `quantization_config.quant_method` (read by the
`save_pretrained` "not serializable" error, by `trainer_utils`, and by anything dispatching on a saved
checkpoint like vLLM or SGLang) blew up with `AttributeError: 'dict' object has no attribute
'quant_method'`.

`MixQuantizationConfig` keeps the patterns under `plan` and answers `quant_method = "mix"`, with the
dict-ish accessors the plan's own code and tests use (`__getitem__`, `__iter__`, `keys`, `items`, `get`),
and `to_dict()` produces `{"quant_method": "mix", "plan": {...}}`, so a saved plan is self-describing.

A single-format model keeps its format's config untouched. Loading a saved plan back is left to
`AUTO_QUANTIZER_MAPPING["mix"]` (TODO in the class), which mixed checkpoints cannot exercise yet.
A plan is written against a checkpoint's module names, so an entry that names
nothing in this model (`layers.99.mlp.experts`) is a typo, and the modules it
was meant for silently keep the format of `*`. That is the wrong thing to keep
silent with on-the-fly quantization.

No second walk of `named_modules`: `get_quantizer` already resolves every key
and module during the load, so it records the pattern it answered with, and
`postprocess_model` reports the ones nothing resolved to (the `*` fallback
always matches, so it is never reported).
`expert_dtype: fp4` (`quant_method: fp8` + FP4 experts) had no path here: the
experts allocated FP8 storage, so V4-Flash/Pro checkpoints could not load.

This is main's code, restored — it was dropped in the cleanup commits:

    FineGrainedFP8Config        `expert_dtype: "fp8" | "fp4"`, validated
    _alloc_expert_proj          `weight_k_div`, FP4 packs two e2m1 values per byte
    FP8Experts                  FP4 storage: int8 weights, K halved, per-row SF at gran_k=32
    Fp8Dequantize               `_unpack_fp4` before applying the scale grid
    quantized_module            passes `expert_dtype` to the experts class only
    DeepseekV4Config            fold a top-level `expert_dtype` into `quantization_config`, as V4.1 ships it

Main carries no test for it, so this restores the code as it was, not new behaviour.
It mixed `FineGrainedFP8Config` with `BitsAndBytesConfig(load_in_4bit=True)`, which raises: a plan can only
mix formats that swap their own modules (`quantized_module`), and bnb doesn't.

Use a ModelOpt mixed-precision plan instead (fp8 with fp4/mxfp4 experts) and say the restriction out loud.
`preprocess_model` runs before the files are read, so it passes no converters to
`map_module_to_quantizer`. For a plan read out of a checkpoint's config (ModelOpt
`quant_algo`, `schema_readers`), `checkpoint_names` is still true, and the rename
branch then iterated `None`:

    TypeError: 'NoneType' object is not iterable        every ModelOpt checkpoint

Skip the rename when there are no converters: the loader renames the plan with
the model's, see `update_weight_conversions`. Renaming to an empty dict would
have wiped the plan instead of crashing, so this is not just a None guard.

Also `_assign_is_quantized` → `assign_is_quantized`: `auto.py` imports it, a
function used across modules should not be private.
- `overview.md`: the most used path first. A stored plan (or a per-layer checkpoint's own scheme) needs no
  `quantization_config`, then the loading attributes that change it, then writing a plan yourself with a real
  model (FP8 attention + MXFP4 experts).
- `nvfp4.md`: "no tensor parallelism" read as "no distributed at all". Tensor parallelism is rejected, expert
  parallelism does shard NVFP4 experts; say both.
Two ways exist: `quantized_module` builds the module on meta (one shared pass, the only one a plan can mix),
and `MODULES_TO_PATCH_FOR_QUANTIZATION` patches an existing class before loading. Say which one is legacy and
where it should go.
`preprocess_model` looped over the plan's quantizers to set `is_quantized` and
`quantization_method`, so a mixed plan ended up advertising whichever format came
last (`trainer_utils` reads that attribute). The plan's own config says `"mix"`,
a single-format plan keeps that format's.

The per-quantizer preparations stay in the loop: each only touches the modules
its own patterns name, so their order does not matter.
The guard read as arbitrary without the list: bitsandbytes, AWQ, torchao and
compressed-tensors swap modules themselves instead of declaring `quantized_module`,
so a plan cannot hand them only their own modules.
`load_eetq_kernels` did the hub download + dynamic import directly, so `torch.compile`
traced into it and a missing `kernels` package surfaced as an opaque error.

Mirror finegrained-fp8: the load is an `@allow_in_graph` function (one opaque node,
no return value) that fills a module global, checks `is_kernels_available()`, and
names the missing kernel symbols. The shared helper for both can come later.
`activation_scheme="none"` dequantizes the weight on every forward because there is
no W8A16 kernel yet. Correct, but say what would remove it.
A module is only swapped to FP8 when the plan says it is FP8, so a weight still in
full precision means the checkpoint did not quantize it (`ignore`, a partially
quantized export). The forward silently ran it in full precision.

Detect it once, after loading, in the format's post-load hook: name it and count
it instead of hiding it in a hot path.
The post-load check walked `named_modules()` a second time. The swap pass already
visits every module, so `quantized_module` records them and the hook only looks at
those.
It is there for the scale copies `weight_converter` builds, whose tensors are not
always a block grid. Not a new style for scales: the fix would be to stop
translating a mapping's ops onto its scales, which is out of scope here.
    1. scoped rename: the quantizer renames to our standard names
    2. unscoped rename: all renaming

The FIXME between them described the prefix fallback; say what it does.
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: deepseek_v4, ministral3, mistral4, aqlm_integration, bitnet_integration, eetq_integration, finegrained_fp8, higgs, hqq, metal, mxfp4, nvfp4, sinq

When a user passes a plan to narrow a pre-quantized checkpoint,
unmatched modules now get dequantize=True instead of flipping
pre_quantized=False (which tried to quantize already-fp8 weights).
Also fixes silent weight_scale_inv loading.

This branch has not been deployed

No deployments
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.

6 participants