Skip to content

Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism and weight-only, generate - #50670

Merged
IlyasMoutawwakil merged 16 commits into
mixed-nvfp4-fp8-planfrom
mixed-plan-fixes
Nov 12, 2026
Merged

IlyasMoutawwakil merged 16 commits into
mixed-nvfp4-fp8-planfrom
mixed-plan-fixes

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Fixes on top of #50245, targeting its branch so the diff shows only them.

Changes

  • bitsandbytes loads again. QuantizationPlanHfQuantizer inherited HfQuantizer.param_needs_quantization (always False), so it never reached the wrapped quantizer's override. The shape check in set_param_for_module then reported every packed bnb weight as mismatched, and on-the-fly 4-bit loading raised Reinit due to size mismatch - ckpt: [2048, 1] vs model: [64, 64]. The plan now asks the quantizer of the param's own pattern, which is also the right answer in a mixed plan. It is the only HfQuantizer method that a quantizer overrides, that the loading code calls on the plan, and that the plan didn't override.

  • NVFP4 under parallelism: expert parallelism shards the experts, tensor parallelism is refused again. 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 set every NVFP4 layer to "replicate", which kept the packed weights whole on every rank, not just the scales.

    • NVFP4Experts registers parameters instead of buffers, so the EP styles shard them along the expert axis. The swizzled scales are swizzled per expert, so they shard as stored. The plan gives _sf its weight's style; the other scales already follow their weight through the serialized names.
    • Both experts forwards skip the routes expert parallelism marks for other ranks (ids past num_experts). The grouped one clamps them for the scale lookups and zeroes their rows, which the GEMM leaves unwritten.
    • A per-expert checkpoint slice can have fewer dims than its parameter (DtensorShardOperation), e.g. the 0-dim per-expert weight_scale_2 merged into (num_experts, 2). This is the same change as Experts and TP: per-instance experts flags, load-time-only experts, scalars and per-expert scales in TP and EP #49775.
    • Tensor parallelism of NVFP4 layers raises, as on main: a tensor-parallel run refuses NVFP4 linears, and NVFP4 experts without expert parallelism to shard them. So with tp_size > 1, only the experts may be NVFP4. The device_map error message and the docs say so.
  • NVFP4 experts decode with generate on GPU. generate switches grouped_mm to batched_mm while decoding, which NVFP4's experts interface didn't register: KeyError. There is no batched NVFP4 GEMM, so batched_mm runs the grouped one.

  • Weight-only NVFP4 runs as saved. ModelOpt's W4A16_NVFP4 (e.g. the experts and lm_head of nvidia/Qwen3.6-35B-A3B-NVFP4) loaded with the W4A4 config, which quantizes activations to FP4 beyond single-token decoding. It now loads with NVFP4Config(weight_only=True): the layers keep their packed weights and dequantize them in each forward, in pure PyTorch, so activations stay in full precision. Weight-only modules hold the same tensors as W4A4 ones and load the same way (the swizzled scales' shape is plain arithmetic now, not a kernel call): only the forward differs. Weight-only experts run eager, since the grouped implementations quantize activations. They check it in the grouped forward: use_experts_implementation patches the class in place, so once one W4A4 NVFP4Experts is built, every NVFP4Experts in the process dispatches through the interface.

  • NVFP4 fixes from running on B200 GPUs:

    • ModelOpt linears load their static input_scale, which the empty placeholder dropped.
    • torch's grouped NVFP4 GEMM gets the per-operand global scales it requires (ones, the global scales scale the output).
    • The grouped experts forward handles bf16 routing weights.
    • A pre-quantized checkpoint can span several devices with a device_map. Only quantizing while loading packs on one device, and every device must be Blackwell.
  • The ModelOpt reader warns that kv_cache_quant_algo is dropped.

  • The plan drops its __class__, __reduce__ and __getattr__ overrides.

    • Nothing checks a loaded model's quantizer class, and __reduce__ only existed to undo __class__ when copying and pickling.
    • __getattr__ forwarded unknown attributes to a single quantizer. Only GGUF's read_header and get_state_dict in from_pretrained used it: they now call hf_quantizer.quantizer. The load ops that read their quantizer's attributes (torchao's metadata, compressed-tensors' compressor) are built by their own quantizer, never by the plan.
  • The type checker passes again: 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245 added three errors, and this PR one.

    • FP8 and MXFP4 set _hf_quantized_needs_local_tp when swapping, as before, told to the type checker.
    • The plan's module swap no longer writes source_cls, which only bitsandbytes reads, on the modules its own replacement tags.
    • NVFP4 reads ep_size from a distributed config that may be absent.

Checked, not changed

  • A mixed plan falls back to HfQuantizer's dequantize, get_state_dict_and_metadata and get_new_dtype. No mixable format needs them today:
    • get_new_dtype is only overridden by GGUF.
    • _dequantize (model.dequantize() after loading) only by bitsandbytes and HIGGS. FP8, MXFP4 and NVFP4 dequantize at load time instead.
    • get_state_dict_and_metadata only by torchao and MXFP4, where it converts GPT-OSS's experts, which load with a single config.
  • model.quantization_method is the last member's on a mixed model. Every reader compares it with bitsandbytes, HQQ, Quark or GPTQ, none of which can be mixed.

Open questions, not changed here

  • A saved plan has no top-level quant_method. Older versions raise on such a quantization_config instead of skipping it.
  • mxfp8 still loads through FineGrainedFP8HfQuantizer, and ModelOpt MXFP8 maps to FP8.
  • Only quantizers implementing quantized_module can be mixed in a plan, so bitsandbytes can't.
  • tests/utils/test_core_model_loading.py::test_qkv_chunk_rope_permute_with_fp8_quantization fails on 🚨 [quantization] per-layer quantization plan: mixed NVFP4 + FP8 checkpoints #50245, before and after merging main. Beyond its fake quantizer being outdated, it shows a behaviour change. One converter splits qkv_proj into q_proj, k_proj and v_proj, and only q_proj is quantized. main quantizes per target param (Weight loading: conversion ops declare many-to-many support, and four small loader fixes #49773), while the plan's update_weight_transform sets the quantize op for the whole converter, so k_proj and v_proj are quantized too.

Tests

Test Result
tests/quantization/test_quantization_plan.py 13 passed, 2 skipped (GPU). The new param_needs_quantization test fails without the fix
tests/quantization/nvfp4/test_nvfp4.py 17 passed, including:
- test_load's Qwen3.5-MoE with W4A16_NVFP4 experts, now checked to stay packed and match the dequantized experts' forward
- test_forward, which runs batched_mm like grouped_mm
- the EP plan and TP refusal tests
- test_expert_parallelism on 2 CPU ranks (gloo, tp_size=ep_size=2), for W4A4 and weight-only experts: each rank holds its half of every expert tensor, swizzled scales included, and the logits match one process's through the eager and grouped experts. The W4A4 GEMMs run on the test's fake kernel, which computes from the dequantized operands, and leaves rows past the last group NaN as the real one leaves them unwritten. Dropping either forward's handling of other ranks' routes fails it
tests/quantization, tests/expert_parallel, tests/tensor_parallel, tests/utils/test_distributed_sharding_utils.py pass on CPU
tiny Mistral4 (hf-internal-testing/tiny-random-Mistral4-fp8-nvfp4) with its NVFP4 shared experts weight-only packed uint8 weights, no missing or unexpected keys, logits identical to the fully dequantized load
tiny Llama with bnb on an A100: 4-bit and 8-bit on the fly, then a 4-bit save and pre-quantized reload loads with no mismatched keys, and the reload matches the logits; 4-bit on #50245 raises
tests/quantization/ggml/test_ggml.py, Qwen2.5-0.5B Q6_K (RUN_SLOW=1) passed, with its expected generation

🤖 Generated with Claude Code

IlyasMoutawwakil and others added 4 commits November 12, 2026 18:07
The plan inherited HfQuantizer's default (False), so the shape check reported every bitsandbytes weight mismatched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ing the layers

Replicating kept the packed weights whole on every rank, not just the scales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…that KV cache quantization is dropped

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Nothing checks a loaded model's quantizer class: the plan is the quantizer, a single one reached through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@HuggingFaceDocBuilderDev

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:

…on full precision activations

ModelOpt's W4A16_NVFP4 loaded with the W4A4 config, which quantizes activations. NVFP4Config(weight_only=True) keeps the
weights packed and dequantizes them in each forward, in pure PyTorch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism, ModelOpt warnings Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism, weight-only NVFP4 Nov 12, 2026
IlyasMoutawwakil and others added 3 commits November 12, 2026 18:31
…er explicitly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the grouped GEMM

- NVFP4Experts registers parameters, which the EP styles shard along the expert axis; the plan gives the swizzled
  scales their weight's style. Tensor parallelism of NVFP4 layers still raises, unless they are kept whole.
- Both experts forwards skip the routes expert parallelism marks for other ranks.
- A per-expert slice can have fewer dims than its parameter, e.g. a 0-dim per-expert scale (as in #49775).
- generate switches grouped_mm to batched_mm while decoding: NVFP4 runs the grouped GEMM for it.
- Weight-only experts run eager whatever the experts class wrapping, which use_experts_implementation does in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism, weight-only NVFP4 Quantization plan fixes: bitsandbytes loading, NVFP4 parallelism and weight-only, generate Nov 12, 2026
IlyasMoutawwakil and others added 3 commits November 12, 2026 19:14
…both implementations

The fake grouped GEMM leaves rows past the last group NaN like the real one leaves them unwritten, so the test
catches a forward that doesn't zero other ranks' routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The plan inspection duplicated how the plans resolve. Tensor parallelism of NVFP4 layers isn't supported, so a
tensor-parallel run refuses NVFP4 linears, and NVFP4 experts without expert parallelism to shard them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The FP8 and MXFP4 modules declare their local tensor-parallel forward as a class attribute instead of each instance.
- The plan's module swap no longer writes `source_cls`, which only bitsandbytes reads, on modules it swaps itself.
- NVFP4 reads `ep_size` like `tp_size`, from a distributed config that may be absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

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

run-slow: finegrained_fp8, mxfp4, nvfp4

Comment thread docs/source/en/quantization/nvfp4.md Outdated

- One CUDA device per process: a multi-device `device_map` is rejected. With tensor parallelism, NVFP4 layers are not
sharded (their scales have no sharding plan yet): every rank holds them whole, the other layers shard as usual.
- One CUDA device per process: a multi-device `device_map` is rejected. Expert parallelism shards NVFP4 experts, but

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.

💀

@IlyasMoutawwakil IlyasMoutawwakil Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

i verified on b200, pre quantized work too, so i relaxed the condition

return None if this rank does not own that slice, else slice inner dims only. Surviving slices are
stacked by the converter into this rank's local [n_local, in, out] shard. A list can fill several params
of the same axis-0 size back to back (e.g. text then vision experts as in ernie), so `tensor_idx` wraps around it.
A slice can have fewer dims than `[in, out]`, e.g. a 0-dim per-expert scale.

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.

maybe just side not beside the conditional instead of docstring?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done

Comment thread src/transformers/integrations/nvfp4.py Outdated


def _frozen(*shape, dtype: torch.dtype) -> nn.Parameter:
"An uninitialized parameter loading quantized data, so without gradients"

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.

proper docstring pls, ig this is fucked across the pr?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done, all the single-quoted ones in the files this pr touches are proper docstrings now

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.

I feel like the og PR or maybe we even need a whole repo cleanup but obv not on you

Comment thread src/transformers/integrations/nvfp4.py Outdated
@@ -391,11 +425,16 @@ def reverse_op(self) -> ConversionOps:
return _IdentityOp()

def _dequantize(self, packed, scales, scale_2):

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.

lol why do we still have this here then? lets keep only 1?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done, the op calls dequantize_nvfp4 directly

self.in_features = in_features
self.out_features = out_features
# Weight-only (W4A16): the weight is dequantized in each forward, no kernel nor activation scale
self.weight_only = weight_only

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.

could we at least dequant once only?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

dequantizing once is what dequantize=True already does: weight-only exists to keep the 4-bit weights in memory, so it dequantizes per forward. caching the dense weight would cost the same memory as dequantize=True

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

normally this would be done with a weight only kernel but we don't have it here and torch also doesn't have it so we do dequant + bf16

new_module = quantizer.quantized_module(name, module)
if new_module is None:
continue
new_module.source_cls = type(module)

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.

same why removed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

nothing reads it on these swaps: only bnb reads source_cls, on the modules its own replace tags, and bnb doesn't go through quantized_module. it was a dead write, which also failed ty

)
else:
return None
new_module._hf_quantized_needs_local_tp = True

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.

id rather have this tbh

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

back as it was, with a ty ignore

Comment on lines +103 to +104
if (getattr(distributed_config, "tp_size", None) or 1) == 1:
return

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.

should this not be validated before somewhere?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

validate_environment runs before the model is built, so it can't see which modules are nvfp4 yet. update_parallel_plan is the first place with both the swapped modules and the distributed config

Comment thread tests/quantization/nvfp4/test_nvfp4.py Outdated


@is_expert_parallel_test
@unittest.skipUnless(is_torch_available(), "test requires PyTorch")

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.

require torch?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done

run_distributed(world_size=2, backend="gloo")(_expert_parallelism_shards_each_expert)(tmp, weight_only)


@unittest.skipUnless(is_torch_available(), "test requires PyTorch")

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.

oh why is it this..

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

that's how run_distributed is used in tests/expert_parallel: it wraps a top-level worker so it pickles to the ranks. cleaned up the rest though, it's parameterized over weight-only now instead of mutating the config in a loop

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.

oh no it was more meant for skipUnless(is_torch_available(), "test requires PyTorch") which doesnt use our helpers

IlyasMoutawwakil and others added 5 commits November 12, 2026 10:40
A pre-quantized NVFP4Linear declared an empty input_scale placeholder, while ModelOpt saves a scalar,
so loading any W4A4 checkpoint with quantized linears (e.g. nvidia/Qwen3-30B-A3B-NVFP4's attention)
failed on a size mismatch. The placeholder now holds one value for pre-quantized loads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
F.scaled_grouped_mm has no NVFP4 implementation for block scales alone ("No gemm implementation was
found" on B200, torch 2.12 and 2.13): it takes [BlockWise1x16, TensorWise] per operand. The global
scales are ones, as they are applied to the output. The fake GEMM in the tests now refuses the old call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The grouped forward scattered its rows into a float32 buffer without a cast: with a bf16 model's
bf16 routing weights the rows stay bf16 and index_put fails on the dtype mismatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only quantizing on the fly needs one device (it packs every weight on quantization_device). A
pre-quantized checkpoint now loads across several GPUs, each checked for Blackwell. On B200,
nvidia/Qwen3-30B-A3B-NVFP4 split over 2 GPUs matches the one-GPU load exactly (logits and greedy
tokens, eager and grouped_mm); the hub kernel runs on its inputs' device, not the current one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- NVFP4 modules always carry the swizzled scales, whose shape is plain arithmetic: weight-only modules hold the same
  tensors as W4A4 ones, the deserialization is the same, and only the forward differs.
- Only one NVFP4 dequantization, `dequantize_nvfp4`.
- The local tensor-parallel flag is set when the modules are swapped again, the type checker told to ignore it.
- Triple-quoted docstrings, the per-expert slice note next to its check, more blank lines.
- The NVFP4 EP test is parameterized and requires torch; the docs list multi-device loading of pre-quantized checkpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil
IlyasMoutawwakil marked this pull request as ready for review November 12, 2026 19:00
@IlyasMoutawwakil
IlyasMoutawwakil merged commit bb5fc01 into mixed-nvfp4-fp8-plan Nov 12, 2026
152 checks passed
@IlyasMoutawwakil
IlyasMoutawwakil deleted the mixed-plan-fixes branch November 12, 2026 19:00
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.

3 participants