Repository navigation
🚨 NVFP4: MoE experts and ModelOpt exports on finegrained-kernels - #49851
IlyasMoutawwakil wants to merge 21 commits into
Conversation
- 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>
|
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. |
- 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
left a comment
There was a problem hiding this comment.
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 !
| 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. |
There was a problem hiding this comment.
Not very clear, maybe we shouldn't put it in the doc ?
| ## 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. |
There was a problem hiding this comment.
it's fine not specifying that the router is not quantized, we do the same for lm_head.
| quantization_config=NVFP4Config(modules_to_not_convert=["lm_head"]), | ||
| ) |
There was a problem hiding this comment.
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.
| ## 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. |
There was a problem hiding this comment.
let's keep it simple, we can remove the mention of the swizzling.
| `"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. |
| ```py | ||
| from transformers.distributed import DistributedConfig | ||
|
|
||
| distributed_config = DistributedConfig(tp_size=8, ep_size=8) | ||
| ``` |
There was a problem hiding this comment.
Have a better snippet here, it is hard for the user what to do.
| quantized_layers (`dict[str, str | None]`, *optional*): | ||
| How checkpoint modules load: `"nvfp4"`, `"nvfp4_weight_only"`, `"dequantize"`, or `None` to stay |
| activation_format (`str`, *optional*): | ||
| `None` quantizes the activations to NVFP4 too. `"bf16"` keeps them in the model dtype (weight-only). |
There was a problem hiding this comment.
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.
| def get_loading_attributes(self): | ||
| return {"activation_format": self.activation_format, "dequantize": self.dequantize} |
There was a problem hiding this comment.
will we always have the input_scale ? because then it might not make sense to update activation_format to None.
| 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']", |
There was a problem hiding this comment.
For the config, we should probably directly test with a modelopt model config on the hub !
| @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) |
There was a problem hiding this comment.
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.
| reader = AUTO_QUANTIZATION_CONFIG_READERS.get(quant_method) | ||
| if reader is not None and (config := reader(quantization_config_dict)) is not None: | ||
| return config |
There was a problem hiding this comment.
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 ?
`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>
|
[For maintainers] Suggested jobs to run (before merge) run-slow: nvfp4 |
What does this PR do?
Reworks NVFP4 on
kernels-community/finegrained-kernels. It adds MoE experts, ModelOpt exports and saving.NVFP4Linearand the newNVFP4Expertsrun on finegrained-kernels. Thenvfp4-gemmkernel is removed.NVFP4Expertshasgrouped_mmandbatched_mmimplementations. Eager is the reference.Layout ops come from the quantizer's
get_param_ops: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_operationsreturns two ops.deserializeapplies the layout ops.dequantizehandles FP8, block FP8, MXFP8, and NVFP4 underdequantize=True.A fused post-expert norm runs in the kernel for the norm classes the integration maps (Muse Spark).
NVFP4Expertssupports a clamped SwiGLU, from the config'sswiglu_alphaandswiglu_limit.AUTO_QUANTIZATION_CONFIG_READERSmaps aquant_methodto a reader.read_modeloptturns a ModelOpt export into anNVFP4Config.read_mxfp8does the same for an MXFP8 checkpoint whosemoe_quant_algoisNVFP4. Its experts load in NVFP4. Its other MXFP8 layers load dequantized. A plain MXFP8 checkpoint still goes toFineGrainedFP8Config.FP8 layers of a ModelOpt
MIXED_PRECISIONexport load dequantized, with a warning. Their scales load into a slot the plan replicates, and each rank dequantizes its shard after loading.NVFP4Configgains these options:quantized_layers: how each checkpoint module loads,"nvfp4","nvfp4_weight_only","dequantize"orNone. 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 weightweight_packedand 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_pretrainedworks. Experts keep their checkpoint's layout, and scales follow their weights.is_serializableis a method, assave_pretrainedcalls 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
block_sparse_moe.experts.0.w1.weight, while the module lives atmlp.experts.NVFP4Deserializemaps 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
update_weight_conversions(..., for_save=True).3. Saving tensors that aren't a converter's target
[weight, weight_scale_inv] -> weightreversesweight, soweight_scale_invgoes to disk as it's held.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
DtensorShardOperationfrom 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] -> weightwith a dequantize op, as with FP8'sdequantize=Trueon main. Under TP, the scale is then sliced with the weight's placement, which is wrong for two ModelOpt layouts:FP8) is 0-dim, so there is nothing to slice and the shard op fails;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 makeso_projrowwise 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_invparameter, only so the plan can mark itreplicate. 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 leavesquantized_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
Breaking changes
replace_with_nvfp4_linearis nowreplace_with_nvfp4.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.nvidia/Qwen3-8B-NVFP4nvidia/Qwen3-30B-A3B-NVFP4nvidia/Muse-Glimmer-30B-NVFP4W4A16_NVFP4+ FP8Greedy generations:
nvidia/Qwen3-30B-A3B-NVFP4(MoE), prompt"The capital of France is Paris. The capital of Germany is":nvidia/Muse-Glimmer-30B-NVFP4(dense, weight-only NVFP4 and FP8 layers), chat prompt"What is the capital of France? Answer in one sentence.":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.grouped_mm/batched_mmDistributedConfig(tp_size=2, ep_size=2)DistributedConfig(tp_size=2)nvfp4-pack-quantizedexpertssave_pretrainedthenfrom_pretrainedgives identical logits for these: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/quantization/nvfp4)docs/source/en/quantization/nvfp4.md)🤖 Generated with Claude Code