Repository navigation
🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints - #50245
ArthurZucker wants to merge 50 commits into
Conversation
…ix and name boundaries to #50245
|
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: |
bc6733c to
7cf9e8a
Compare
|
run-slow: deepseek_v4, ministral3, mistral4, aqlm_integration, bitnet_integration, eetq_integration, finegrained_fp8, higgs, metal, mxfp4, nvfp4, sinq |
IlyasMoutawwakil
left a comment
There was a problem hiding this comment.
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.
vasqu
left a comment
There was a problem hiding this comment.
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
vasqu
left a comment
There was a problem hiding this comment.
2nd round, going over all other things
|
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 |
|
pushed 2baa90f for the docstrings / spacing / nvfp4 note:
one correction to #50670's description: |
…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.
`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`.
|
I ran this PR's head ( 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: The model then fails during 2. A modelopt NVFP4 checkpoint crashes in With 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):
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.
|
[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.
TLDR: we refactor the
AutoQuantizerto support aquantization_plan. This defines a mapping:{ checkpoint_layer_name: quantizer}.Based on this, the
hf_quantizer's job is to:dequantizedordeserializedorquantizedusing conversion ops before / after the ones that are already runningquantization_plan-> a single quantizer per layer.This requires a few changes to standardize
load_operationsper quantization method, and ensuredequantizedordeserializedorquantizedare all standardWeightConversionOperations.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.