Skip to content

🚨 NVFP4: MoE experts and ModelOpt exports on finegrained-kernels - #49851

Open
IlyasMoutawwakil wants to merge 21 commits into
mainfrom
nvfp4-experts
Open

IlyasMoutawwakil wants to merge 21 commits into
mainfrom
nvfp4-experts

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

Reworks NVFP4 on kernels-community/finegrained-kernels. It adds MoE experts, ModelOpt exports and saving.

  • NVFP4Linear and the new NVFP4Experts run on finegrained-kernels. The nvfp4-gemm kernel is removed.

  • NVFP4Experts has grouped_mm and batched_mm implementations. Eager is the reference.

  • Layout ops come from the quantizer's get_param_ops:

    • the packed FP4 int8 view;
    • the gate|up interleave;
    • the SM100 scale swizzle.

    Each op is reversed on save. Scale parameters are declared row-major. On Blackwell, the swizzle op turns this rank's scales into the 5-D layout the kernels read, when they fit it. A warning says when they don't.

  • get_load_operations returns two ops. deserialize applies the layout ops. dequantize handles FP8, block FP8, MXFP8, and NVFP4 under dequantize=True.

  • A fused post-expert norm runs in the kernel for the norm classes the integration maps (Muse Spark).

  • NVFP4Experts supports a clamped SwiGLU, from the config's swiglu_alpha and swiglu_limit.

  • AUTO_QUANTIZATION_CONFIG_READERS maps a quant_method to a reader. read_modelopt turns a ModelOpt export into an NVFP4Config.

  • read_mxfp8 does the same for an MXFP8 checkpoint whose moe_quant_algo is NVFP4. Its experts load in NVFP4. Its other MXFP8 layers load dequantized. A plain MXFP8 checkpoint still goes to FineGrainedFP8Config.

  • FP8 layers of a ModelOpt MIXED_PRECISION export load dequantized, with a warning. Their scales load into a slot the plan replicates, and each rank dequantizes its shard after loading.

  • NVFP4Config gains these options:

    • quantized_layers: how each checkpoint module loads, "nvfp4", "nvfp4_weight_only", "dequantize" or None. A key is a module name or a pattern. The readers translate their formats into these values.
    • activation_format: "bf16" for weight-only;
    • dequantize: load dequantized. A load falls back to it without a supported device;
    • checkpoint_format: "modelopt" or "nvfp4-pack-quantized". The second names the packed weight weight_packed and ships reciprocal globals.
  • Experts shard under expert parallelism (masked, ep_size == tp_size), where each rank holds whole experts, and under tensor parallelism alone, where each rank holds a slice of every expert. Nothing changes in core.

  • save_pretrained works. Experts keep their checkpoint's layout, and scales follow their weights. is_serializable is a method, as save_pretrained calls it.

Workarounds for current loader limits

NVFP4 holds its tensors in the layout the kernels read: packed FP4 bytes viewed as int8, gate|up rows interleaved, and scales swizzled on SM100. Loading must produce that layout, and saving must undo it. Main's loader gets in the way in four places. Each workaround stays inside the NVFP4 quantizer and integration.

1. Finding the module when saving

  • On main: a save first renames each key to its checkpoint name, then runs the converters' reverse ops. So the reverse ops only see checkpoint names. For Mixtral that's block_sparse_moe.experts.0.w1.weight, while the module lives at mlp.experts.
  • NVFP4 needs: to undo a tensor's layout, the reverse op must know which module holds it, e.g. whether the experts' scales are swizzled. A checkpoint name doesn't lead to that module.
  • Right fix: run the reverse ops on the model's names, then rename. The stack's weight-loading PR does this.
  • For now: on save, NVFP4Deserialize maps the checkpoint name back through the model's renames to find the module. The ModelOpt renames (weight_scale → weight_scale_inv, …) can't be undone this way, so a save writes the modules' own tensor names. A reload reads them as they are.

2. Saving the scales of a model quantized on the fly

  • On main: after loading, the loader keeps only the converters that matched a key in the checkpoint. A full-precision checkpoint has no scales, so the converters that would merge or split scales never match and are dropped.
  • NVFP4 needs: those converters at save time. Without them, a per-expert model like Mixtral saves its weights per expert but its scales fused.
  • Right fix: keep a quantizer's companion converters for saving, or let the quantizer rebuild them. The stack's machinery PR rebuilds them for every block-scaled quantizer.
  • For now: after an on-the-fly load, the quantizer rebuilds its conversions for the save, with update_weight_conversions(..., for_save=True).

3. Saving tensors that aren't a converter's target

  • On main: a converter's reverse only matches its target key. The deserialize converter [weight, weight_scale_inv] -> weight reverses weight, so weight_scale_inv goes to disk as it's held.
  • NVFP4 needs: every tensor whose layout changed at load to be reversed at save. That includes dense scales, which are swizzled, and fused expert stacks, which are interleaved and swizzled.
  • Right fix: a reverse that covers all of a converter's sources.
  • For now: each such parameter gets a converter of its own. It comes first, since the first matching converter wins.

4. Dequantizing FP8 layers under tensor parallelism

  • On main: a converter's sources are all sharded with its target's placement. The loader builds one DtensorShardOperation from the target parameter and slices every source with it while reading. A TP plan entry can only change that for a parameter.

  • NVFP4 needs: ModelOpt's mixed exports ship some layers in FP8, which load dequantized into a plain nn.Linear. The natural path is a converter [weight, weight_scale_inv] -> weight with a dequantize op, as with FP8's dequantize=True on main. Under TP, the scale is then sliced with the weight's placement, which is wrong for two ModelOpt layouts:

    • a per-tensor scale (FP8) is 0-dim, so there is nothing to slice and the shard op fails;
    • a block grid (FP8_PB_WO) can ship as [N/128, 1, K/128, 1], with a size-1 axis after each blocked dim. A rowwise split, e.g. o_proj, slices dim 1 instead of the K blocks in dim 2.

    The scale should simply be replicated. But it isn't a parameter of the nn.Linear, so no plan entry can say so. The split itself isn't ours to change either: the model's plan makes o_proj rowwise because attention needs it.

  • Right fix: let a plan give a converter source its own placement, e.g. replicate a scale. The dequantize could then stay a normal conversion op.

  • For now: each FP8 layer gets a temporary weight_scale_inv parameter, only so the plan can mark it replicate. The weight's converter no longer sees the scale, so each rank dequantizes its weight shard after loading, with the matching slice of the grid. Then the parameter is dropped, and the layer leaves quantized_layers, so a save describes it as bf16.

Swizzled scales need no workaround. Scale parameters are declared in the checkpoint's row-major shape, so tensor and expert parallelism slice them with main's code. The swizzle op then works on this rank's scales. Experts need one extra rule: a swizzled gate_up writes the activations for down in the swizzled layout, which only a swizzled down reads. So gate_up swizzles only when down does. Each module answers this in swizzles_scales, from the shape of the scales it loads. One side effect: under tensor and expert parallelism, a scale's DTensor still reports the declared row-major shape.

This PR changes nothing in core.

Questions for maintainers

  • Point 1: is running the reverse ops before the renames, as in the stack's weight-loading PR, the right order on save?
  • Point 2: should the loader keep a quantizer's companion converters for saving, or is a quantizer hook better?
  • Points 3 and 4: should converters reverse all their sources, and should plans be able to name converter sources? Together those would remove the per-parameter converters and the temporary FP8 scale parameter.

Breaking changes

  • replace_with_nvfp4_linear is now replace_with_nvfp4.
  • On-the-fly NVFP4 uses the new kernels, so outputs change slightly.

Checks

All on B200.

Real ModelOpt exports. These are public checkpoints from the Hub. "vs bf16" compares the logits with the unquantized base model. "vs dequantized" compares them with the same checkpoint loaded with dequantize=True.

Checkpoint Model Layers W4A4 vs bf16 W4A4 vs dequantized
nvidia/Qwen3-8B-NVFP4 dense NVFP4 0.972 0.989
nvidia/Qwen3-30B-A3B-NVFP4 MoE, 128 experts NVFP4 - 0.993
nvidia/Muse-Glimmer-30B-NVFP4 dense W4A16_NVFP4 + FP8 - 1.000 (weight-only)

Greedy generations:

  • nvidia/Qwen3-30B-A3B-NVFP4 (MoE), prompt "The capital of France is Paris. The capital of Germany is":

    Berlin. The capital of Italy is Rome. The capital of Spain is Madrid. The capital of Portugal

  • nvidia/Muse-Glimmer-30B-NVFP4 (dense, weight-only NVFP4 and FP8 layers), chat prompt "What is the capital of France? Answer in one sentence.":

    We need answer in one sentence. Probably "The capital of France is Paris

Synthetic and tiny models. A random Mixtral is saved as a ModelOpt export, with NVFP4 per-expert experts, NVFP4, weight-only NVFP4, block and per-tensor FP8 attention, and a weight-only NVFP4 lm_head. It is compared with its dequantized reference.

Check Cosine
Synthetic ModelOpt Mixtral, eager / grouped_mm / batched_mm ≥ 0.995
Same, DistributedConfig(tp_size=2, ep_size=2) 0.999
Same, DistributedConfig(tp_size=2) 0.999
Tiny Muse Spark (fused experts, post-expert norm) vs its bf16 reference 0.993
Synthetic MXFP8 Mixtral with nvfp4-pack-quantized experts ≥ 0.995

save_pretrained then from_pretrained gives identical logits for these:

  • the ModelOpt Mixtral;
  • an on-the-fly Mixtral;
  • the MXFP8 Mixtral;
  • tiny Muse Spark;
  • Muse Glimmer.

Dense scale swizzle vs row-major: 1.15x at 4096x4096, M=16, and 1.32x at 12288x4096, M=2048.

Related: #49756 builds a GB10 path on the removed kernel.

  • Tests (tests/quantization/nvfp4)
  • Docs (docs/source/en/quantization/nvfp4.md)

🤖 Generated with Claude Code

- NVFP4 linears and experts run on kernels-community/finegrained-kernels.
- Experts get their own grouped and batched implementations.
- A config reader turns a ModelOpt export into an NVFP4Config.
- FP8 layers of a ModelOpt mixed-precision export load dequantized.
- NVFP4Config gains activation_format and dequantize.

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.

IlyasMoutawwakil and others added 13 commits October 22, 2026 04:49
- A save writes the modules' own names with row-major scales, stacked gate|up rows and uint8 packed bytes.
- Per-expert scales and globals split back like their weights, on-the-fly loads included.
- is_serializable is a method, as save_pretrained calls it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- get_load_operations returns a deserialize op (layout) and a dequantize op (FP8, NVFP4 under dequantize=True).
- get_param_ops gives each param its layout ops: packed int8 view, gate|up interleave, scale swizzle. Each
  reverses on save, so saving is the reversed conversions.
- Per-param converters load fused stacks and dense scales, and an on-the-fly load rebuilds them for saving.
- Dense scales swizzle on load, and stay row-major under tensor parallelism.
- A ModelOpt MIXED_PRECISION export's own module list replaces the default skips, so its NVFP4 lm_head loads.
- The shard op keeps per-expert slices of swizzled stacks and loads per-tensor scalars whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Name the dense-scale flag by its cause, tensor_parallel, and keep experts swizzled.
- Drop the ModelOpt renames before a save by matching modelopt_renames(), with no stored state.
- Quantize on the current accelerator, so XPU works too.
- Drop the postprocess_model override the base already covers.
- Document saving, and the dense scale swizzle.

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

- Swizzled scales are 5-D parameters that the swizzle op fills at load and reverses on save.
- sharding_utils keeps main's code except the stack's per-expert rule: a source with fewer dims than the param is a
  slice of axis 0.
- FP8 layers that load dequantized get a scale slot the plan replicates, and dequantize after loading on each shard.
  They then leave quantized_layers, so a save describes them as bf16.
- The deserialize op maps checkpoint names through the model's renames only on save.
- Drop the post-load shape check, the "nvfp4" activation_format alias and the reader's None fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Scale params are declared in the checkpoint's row-major shape, so TP and EP slice them with main's code.
- One swizzle op turns each local shard into the 5-D layout when it tiles, and reverses it on save. The kernels read
  the layout from the shape.
- sharding_utils is back to main.

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

- `read_mxfp8` routes an MXFP8 checkpoint with `moe_quant_algo: NVFP4` to NVFP4. Experts load NVFP4, other MXFP8 layers load dequantized.
- `quantized_layers` values say how a module loads: nvfp4, nvfp4_weight_only, dequantize or None. Keys can be patterns.
- `checkpoint_format="nvfp4-pack-quantized"`: `weight_packed` rename and reciprocal globals.
- FP8 dequantize infers its block from the scale shape.
- `NVFP4Experts` supports a clamped SwiGLU.

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

Tensor parallelism alone dropped the experts' plan, so every rank loaded every expert. Each scale grid now follows its
weight's split, and a split grid stays row-major. Expert parallelism still holds whole, swizzled experts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- `swizzles_scales` on each module decides from the shape of the scales being loaded. Down swizzles when its scales
  fit. gate_up also needs down to swizzle, as a swizzled gate_up writes swizzled activations for down.
- Tensor-parallel expert slices now swizzle too.
- A one-time warning says when Blackwell scales load row-major.
- `_fits_swizzled_layout` replaces `_tiles_swizzled`, with its rules spelled out.
- Assign `_weight_conversions` through `setattr`, which the type checker accepts.

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

- `serialized_names` lists the expert stacks, and the globals a dequantized load folds in. Core then builds the fused
  stack converters, collects the globals for dequantizing merges, and gives the scales their weight's plan style.
- Every converter ends with `NVFP4Deserialize`, so a fused dense gate|up linear gets its layout ops too.
- The model's renames are read once, when loading starts, instead of on every saved tensor.
- The Muse Spark test also loads its fused stacks dequantized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The kernels read row-strided activations now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A converter pattern only ends at a name boundary. A bare `down_proj` stack also claimed a dense MLP's
`down_proj.weight`, so a model with both failed to load.

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

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

Thanks a lot ! In general, try to simplify stuff if possible and not put too much docstring if it is not needed / ambiguous for the reader. Left a bunch of comments !

Comment thread docs/source/en/quantization/nvfp4.md Outdated
Comment on lines +52 to +56
A `MIXED_PRECISION` export may quantize some layers to FP8, block FP8 or MXFP8, for example its attention. Those layers
load dequantized to the model dtype, and a warning says so.

An MXFP8 checkpoint with `"moe_quant_algo": "NVFP4"` also loads with NVFP4. Its experts load in NVFP4, in the
`nvfp4-pack-quantized` format. Its other MXFP8 layers load dequantized.

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.

Not very clear, maybe we shouldn't put it in the doc ?

Comment thread docs/source/en/quantization/nvfp4.md Outdated
## Quantize while loading

Pass [`NVFP4Config`] to quantize a full-precision checkpoint as it loads. The linears and MoE experts are quantized.
MoE routers stay in the model dtype. Use `modules_to_not_convert` to keep other modules in their original precision.

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.

it's fine not specifying that the router is not quantized, we do the same for lm_head.

Comment thread docs/source/en/quantization/nvfp4.md Outdated
Comment on lines +73 to +74
quantization_config=NVFP4Config(modules_to_not_convert=["lm_head"]),
)

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.

Remove this, modules_to_not_convert=["lm_head"]. this is usually added by default when quantizing on the fly in get_modules_to_not_convert.

Comment thread docs/source/en/quantization/nvfp4.md Outdated
## MoE experts

Pick the experts' kernels with `experts_implementation`: `"grouped_mm"` or `"batched_mm"` run the fused MoE chain, and
`"eager"` runs one call per expert. On Blackwell GPUs, scales load swizzled into the layout the scaled MMA reads.

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.

let's keep it simple, we can remove the mention of the swizzling.

Suggested change
`"eager"` runs one call per expert. On Blackwell GPUs, scales load swizzled into the layout the scaled MMA reads.
`"eager"` runs one call per expert.

Comment on lines +88 to 92
```py
from transformers.distributed import DistributedConfig

distributed_config = DistributedConfig(tp_size=8, ep_size=8)
```

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.

Have a better snippet here, it is hard for the user what to do.

Comment on lines +2080 to +2081
quantized_layers (`dict[str, str | None]`, *optional*):
How checkpoint modules load: `"nvfp4"`, `"nvfp4_weight_only"`, `"dequantize"`, or `None` to stay

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.

change name please

Comment on lines +2084 to +2085
activation_format (`str`, *optional*):
`None` quantizes the activations to NVFP4 too. `"bf16"` keeps them in the model dtype (weight-only).

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.

is the "bf16" a legacy thing ? it is not very clear from "bf16" that we keep them in the model dtype. Can we use another term ? weight_only was nice but it can only be a boolean.

Comment on lines +2123 to +2124
def get_loading_attributes(self):
return {"activation_format": self.activation_format, "dequantize": self.dequantize}

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.

will we always have the input_scale ? because then it might not make sense to update activation_format to None.

Comment on lines 221 to +232
class NVFP4ConfigTest(unittest.TestCase):
def test_config_uses_quantization_method_enum(self):
config = NVFP4Config(modules_to_not_convert=["lm_head"])

def test_a_modelopt_export_reads_its_formats_and_skip_list(self):
shipped = {
"quant_method": "modelopt",
"quant_algo": "MIXED_PRECISION",
"quantized_layers": {
"layers.0.experts": {"quant_algo": "NVFP4"},
"layers.0.attention.wq": {"quant_algo": "FP8_PB_WO"},
},
"exclude_modules": ["lm_head"],
# some exports write the list as its string
"modules_to_not_convert": "['model.layers.0.mlp.gate']",

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.

For the config, we should probably directly test with a modelopt model config on the hub !

Comment thread tests/quantization/nvfp4/test_nvfp4.py Outdated
Comment on lines +440 to +465
@require_kernels
@require_torch_accelerator
@_requires_fp8_triton
class NVFP4LoadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.directory = tempfile.TemporaryDirectory()
reference = _modelopt_checkpoint(cls.directory.name).to(torch_device)
cls.ids = torch.randint(0, 512, (2, 24), device=torch_device)
cls.expected = cls._logits(reference)

@classmethod
def tearDownClass(cls):
cls.directory.cleanup()

@classmethod
def _logits(cls, model):
with torch.no_grad():
return model(cls.ids).logits.float()

def _load(self, path, **kwargs):
return AutoModelForCausalLM.from_pretrained(path, dtype=torch.bfloat16, device_map=torch_device, **kwargs)

@parameterized.expand(["eager", "grouped_mm", "batched_mm"])
def test_a_modelopt_checkpoint_matches_its_dequantized_model(self, implementation):
model, info = self._load(self.directory.name, experts_implementation=implementation, output_loading_info=True)

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.

We should have a class dedicated to modelops checkpoints to make sure that we are able to load them as expected + run.

Then we should also have a class to check that the integration works when we quantize on the fly and so on.

I feel like it is clearer if we split them.

Then can you try to update the test name to something shorter ? Make sure that the test run fast also.

For model opt, is there a tiny model on the hub that we can use also ? Otherwise, it should be fine with creating one ourselves. I know how troublesome it is to get those.

Comment thread src/transformers/quantizers/auto.py Outdated
Comment on lines +183 to +185
reader = AUTO_QUANTIZATION_CONFIG_READERS.get(quant_method)
if reader is not None and (config := reader(quantization_config_dict)) is not None:
return config

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.

maybe something converter would make more sense than reader ? even for AUTO_QUANTIZATION_CONFIG_READERS . Also, does can this even be None ? (config := reader(quantization_config_dict)). Maybe we should warn the user that the quant config is not supported bc of missing features probably and that they create an issue on the hub to have it fixed ?

Cyrilvallez and others added 6 commits October 28, 2026 16:19
`update_weight_conversions` ends each converter with the op of the load: quantize, deserialize or dequantize.
The quantize op's reverse serializes on save. NVFP4 no longer uses core's separate quantize step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Docs and docstrings say only what is needed.
- `weight_only` replaces `activation_format="bf16"`, and `quant_plan` replaces `quantized_layers`.
- The ModelOpt and MXFP8 schemas convert through `convert_modelopt_schema` and `convert_mxfp8_schema`.
- Quantizing on the fly runs in torch, with no kernel.
- `NVFP4Dequantize` no longer inherits from `Fp8Dequantize`.
- MoE routers stay in full precision through `get_keys_to_not_convert`.
- The expert stacks' names start at a name boundary, so a shared expert's projections no longer load as stacks.
- An unquantized expert stack loads and saves under its own name.
- The tests split into ModelOpt and on-the-fly classes, with real Hub schemas and tiny Hub models.

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: nvfp4

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.

5 participants