Skip to content

Add NVFP4GroupedLinearConverter to support MoE quantization - #4821

Merged
syed-ahmed merged 14 commits into
pytorch:mainfrom
rdspring1:nvfp4_moe_converter
Oct 7, 2026
Merged

syed-ahmed merged 14 commits into
pytorch:mainfrom
rdspring1:nvfp4_moe_converter

Conversation

@rdspring1

@rdspring1 rdspring1 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Adds NVFP4 support for MoE routed experts to DeepSeek-V3, registers the debug, 16B, and 671B recipes, and validates the 671B recipe against the MLCommons DeepSeek-V3 benchmark task on 64 GB300 GPUs.

NVFP4GroupedLinearConverter quantizes the grouped-MM expert GEMMs while preserving the logical grouped-MM offsets, so the routed experts join the dense linears already covered by NVFP4LinearConverter. The 671B recipe pairs NVFP4 on the FFN and all 61 layers' routed experts with MXFP8 on the 1D attention path.

rdspring1 and others added 3 commits September 21, 2026 11:49
MXFP8Linear installs _LinearShardedTensorWithMXFP8Compute as its
nn.Parameter. The subclass exposes __tensor_flatten__, but DCP never
consults it: with no __get_tensor_shard__ hook, the checkpoint records the
parameter as a byte stream and pickles the wrapper object rather than the
plain high-precision shard it holds in _tensor. The read then fails, since
torch.load runs under weights_only=True:

    _pickle.UnpicklingError: Weights only load failed.
    WeightsUnpickler error: Unsupported global: GLOBAL
      torchtitan.quantization.mxfp8.tensor._LinearShardedTensorWithMXFP8Compute
      was not an allowed global by default

Saving succeeds, so this surfaces only on resume. Any MXFP8 run that
resumes from a DCP checkpoint is affected. pytorch#4203 added both the class and
the parameter wrap.

_ShardedFSDPTensor already documents itself as "the nn.Parameter the
optimizer updates and the checkpoint stores", and quantized operands are
rebuilt per unshard by _build_operands, never checkpointed. So _tensor is
the shard DCP should persist: high-precision data, byte-identical to what
an unconverted model writes, and loadable by a model built without the
converter.

The test asserts the saved entry is a TensorStorageMetadata instead of
asserting only a successful round trip. A BYTE_IO entry round trips fine
while the safe globals are registered and fails in a fresh process, so a
round-trip-only test does not see this bug.

Verified on 2 nodes: save at step 2, resume at step 6. Also verified at
671B on 16 nodes, where the MXFP8 attention arm resumed with no
UnpicklingError.

Co-Authored-By: Claude Opus 5 <[email protected]>
Add a cached NVFP4 GroupedExperts implementation and config converter that
preserve logical grouped-MM offsets and reuse TorchAO's default backend
behavior.

Register the three DeepSeek V3 NVFP4 recipes for debug, 16B, and 671B with
mixed MXFP8 attention, while keeping the 16B dense layer in BF16.

Reject configurations the NVFP4 grouped GEMMs cannot serve: pad_multiple
must be a positive multiple of 128, and every targeted GroupedExperts must
have dim and hidden_dim divisible by 128. Both checks run over all targets
before any config is rewritten, so a rejected model config is left
unmutated.

deepseek_v3_671b_nvfp4_mixed inherits disable_cuda_graphs = True from
deepseek_v3_671b and does not override it. With capture enabled, an FSDP
all-gather failed at step 2 of two 16-node runs, followed by
cudaErrorStreamCaptureInvalidated. With capture disabled, training and
validation completed and the step-1 loss was consistent across runs.
deepseek_v3_16b_nvfp4 does enable capture and completed 50 steps on two
nodes.

Extend focused CPU coverage for conversion, dispatch padding, exact module
selection, dropped recipe names, and the two new validation rules.

Validation: tests/unit_tests/cpu/test_quantization.py passes; ufmt passes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Records the three-arm convergence campaign on 64 GB300 GPUs: steps to the
3.60 validation target, per-GPU throughput, and peak memory, with the
parallelism, data, and converter details and the single-seed caveat stated
alongside.

Co-Authored-By: Claude Opus 5 <[email protected]>
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 21, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 21, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

…keys

63c4e9f (pytorch#4808) renamed NVFP4Linear.forward's positional argument:

    -        def forward(self, x: torch.Tensor) -> torch.Tensor:
    +        def forward(self, input: torch.Tensor) -> torch.Tensor:

but left NVFP4Linear.Config.build keying its in_src_shardings and
in_dst_shardings entries "x". Module._maybe_wrap_with_local_region resolves
those keys through inspect.signature(type(self).forward), so the rename
silently invalidated them:

    AssertionError: NVFP4Linear: local_spmd is set but in_dst_shardings is
    missing entries for: ['input']

The same commit made the mismatch reachable. It gave feed_forward w13 a
stacked_colwise_config(), which sets local_spmd, where the previous
colwise_config() did not; _maybe_wrap_with_local_region returns the forward
unchanged when local_spmd is false. Either half alone is inert, so the
assertion appears only from pytorch#4808 onward, on every rank at construction, for
any recipe converting FFN linears.

Float8Linear.forward was renamed by the same commit and MXFP8Linear.forward
already took `input`; neither declares input shardings, so neither is
affected.

Co-Authored-By: Claude Opus 5 <[email protected]>
@tianyu-l

Copy link
Copy Markdown
Contributor

need to rebase after #4820

also would appreciate if you could wait after #4539 lands

A streaming run could not resume from its own DCP checkpoint. Loading
step-210 of a 16-node DeepSeek-V3 run failed on all 64 ranks before step 1:

    RuntimeError: Missing key in checkpoint state_dict: dataloader.dp_rank_0.
    parent_state.parent.parent_window_start_state.hf.examples_iterable.
    previous_state.

GrainDataLoader.state_dict returned the iterator state as the nested dict
Grain builds by recursing through the dataset graph, and DCP gives every
leaf of a nested dict its own storage key. The leaves are not stable: at the
bottom sits a Hugging Face streaming cursor whose state_dict grows and drops
entries such as examples_iterable.previous_state depending on where in the
shard iteration stopped. Save and load at different positions therefore
produce different key sets, and DCP requires every in-memory key to exist in
the checkpoint.

Pickle the iterator state to one bytes value per rank. The key set is then
fixed for the life of the run, so a checkpoint written at any cursor
position loads at any other. bytes is a builtin, so DCP's weights_only=True
read accepts it.

The payload is opaque to checkpoint inspection, and it embeds whatever the
source library placed in its state, so a mismatched datasets version now
fails at unpickling; load_state_dict catches that and says so rather than
surfacing a bare UnpicklingError.

The state version goes to 2. A version-1 checkpoint raises the existing
unsupported-version error instead of being misread.

test_c4_resumption could not have caught this: it round trips state_dict to
load_state_dict in process, where the nested dict is a live object and never
meets DCP. The new test saves through dcp.save, asserts the storage metadata
holds exactly one entry per rank, and loads that checkpoint into a dataloader
sitting at a different cursor position.

Co-Authored-By: Claude Opus 5 <[email protected]>
rdspring1 and others added 6 commits September 30, 2026 18:49
Three cleanups to the DeepSeek-V3 NVFP4 configs, no numerics change intended.

Derive the convertible FFN submodules from the model instead of picking a
literal per config. NVFP4 rejects any Linear whose in_features or out_features
is not a multiple of 128, in NVFP4Linear.Config.__post_init__. DeepSeek-V3 16B's
dense FFN is 10944 wide, so both its Linears are rejected -- w13 on out_features,
w2 on in_features -- while 671B (18432) and the debugmodel (1024) are clean.
That exclusion was encoded as _NVFP4_FFN_SUBMODULES_NO_DENSE, chosen by hand at
one of three call sites with the reason recorded nowhere. nvfp4_ffn_submodules()
reads it off the dense width, so a new flavor gets the right answer without a
reviewer knowing the dim.

Rename _NVFP4_BLOCK to _NVFP4_GEMM_ALIGNMENT and move it to utils.py. 128 is a
torchao Triton kernel tiling requirement; NVFP4's own block is the 16-element
microscaling block that appears in the same file as BlockWise1x16. The old name
named the wrong one. utils.py has no torchao dependency, so the config registry
can import the constant and the helper even when the torchao-backed NVFP4Linear
import fails -- otherwise a torchao mismatch turns a shape decision into an
ImportError.

Lift bf16_tail_fraction to a first parameter on the debugmodel and 671B configs;
16B already had it. Its denominator stays all decoder layers, quantizable or
not, so "the last X% of layers stay BF16" is readable off the model without
knowing which layers are eligible.

Rename deepseek_v3_671b_nvfp4_mixed to deepseek_v3_671b_nvfp4, and its
GraphTrainer wrapper with it. The suffix was accurate when it was introduced:
the 671B config was then the only one mixing NVFP4 with MXFP8 attention. 16B
gained the same MXFP8 attention converter in "DSV3 NVFP4: F0L0 everywhere, and
make the 16B config a scale-down of 671B", after which every NVFP4 config is
mixed and the suffix distinguished nothing. The eager and GraphTrainer
registries now mirror each other 1:1.

test_deepseek_nvfp4_recipes_preserve_quantization_and_routing already
parametrizes all six recipes; it follows the rename, and its special-case
_nvfp4_mixed strip collapses into the existing _nvfp4 strip.

Co-Authored-By: Claude Opus 5 <[email protected]>
# Conflicts:
#	tests/unit_tests/cpu/test_quantization.py
#	torchtitan/config/transform/quantization.py
#	torchtitan/quantization/utils.py
#	torchtitan_recipes/tests/models/deepseek_v3.py
)


def deepseek_v3_671b_nvfp4(

@anijain2305 anijain2305 Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  • Is attention projs running on mxfp8 intentional? From the README and the chart, it seems like yes. Do you have some evidence of bad accuracy with nvfp4 attention projs, if yes, consider adding it to the README.
  • Perhaps change the name of the test to have mxfp8 as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is attention projs running on mxfp8 intentional?

Yes, it is intentional.

Do you have some evidence of bad accuracy with nvfp4 attention projs?

Internal teams recommended bf16 or mxfp8 for the attention linear projections. No apple-to-apples evidence for the run in the README.

Perhaps change the name of the test to have mxfp8 as well?

Changed suffix from _nvfp4 to _nvfp4_ffn_mxfp8_attn for all dsv3 recipes.

| --- | ---: | ---: | ---: | ---: |
| MXFP8 attention | 42 | 734.83 | 2,614 | 226.08 GiB (81.73%) |
| BF16 (control) | 43 | 618.06 | 2,198 | 227.26 GiB (82.16%) |
| NVFP4 F0L0 + MXFP8 attention | 46 | 825.10 | 2,935 | 220.02 GiB (79.54%) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What does F0L0 stand for? Can you add a line describing it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

F0L0 means none of the FFN layers from layer 0 forward are converted to bf16 nor any layers backward from the last layer. Essentially, all the FFN layers are in NVFP4. For stability, a common knob is to leave some of the first and last layers in network in BF16. See Appendix E.2. Layer sensitivity and Figure 9 from Pretraining Large Language Models with NVFP4

@anijain2305 anijain2305 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks pretty good. Have a couple of comments.

@rdspring1 rdspring1 changed the title Add NVFP4GroupedExpertsConverter to support MoE quantization Add NVFP4GroupedLinearConverter to support MoE quantization Oct 6, 2026
)


def deepseek_v3_671b_nvfp4_ffn_mxfp8_attn(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this corresponding to the run in the picture assets/images/dsv3_671b_mlperf_nvfp4_vs_mxfp8_vs_bf16.png?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes.

@syed-ahmed

syed-ahmed commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

The CI failures don't seem related to this PR (all fail at attn_gym/linear/gdn/bwd/triton/chunk_gdn_bwd*). Merging based on that.

@syed-ahmed
syed-ahmed merged commit 4b1f9ce into pytorch:main Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants