Repository navigation
enable graph trainer + mxfp8 composability - #3558
Conversation
|
ok, this approach works for dense but not moe. Reasoning, current torchao mxp8 moe training integration uses |
307e09a to
1342d69
Compare
1342d69 to
26e84ab
Compare
26e84ab to
5e46b0f
Compare
|
@SherlockNoMad I don't understand why the torch function subclass wouldn't work with non-strict tracer; in fact, it's something that I'd expect to work better than the Dynamo. |
5e46b0f to
0264f86
Compare
|
@tianyu-l on your opinion on adding the |
|
Show evidence that the loss is bitwise equivalent before and after this change? |
for bf16, right? There is no baseline for GraphTrainer + mxfp8 since this PR unbreaks it. |
| return config | ||
|
|
||
|
|
||
| def graph_trainer_deepseek_v3_debugmodel_mxfp8() -> GraphTrainer.Config: |
There was a problem hiding this comment.
All of the mxfp8 variants seem pretty boilerplatey--not sure if there is a way around it though.
There was a problem hiding this comment.
When I think about what low prec research on torchtitan might look at, the boilerplate seems increasingly bad, because there are bunch of different spots where I may want to swap between high and low precision; this _mxfp8 config is ONLY the gmm (now granted, torchtitan popularized this particular recipe, so it's ok for it to be deified in some way), but there are plenty of other ways to "do mxfp8".
There was a problem hiding this comment.
Shouldn't you add tests for these configs? I'm not sure I want to spend GB200x2 CI hours on it, but I would certainly like the no-EP single GPU config to be tested with deterministic loss check.
| EP=1 (``ep_mesh is None``), where it skips the all-to-all and only applies | ||
| the local padded permute. The padding is what the quantized grouped GEMM | ||
| needs; the all-to-all is orthogonal, so EP=1 is supported for single-GPU | ||
| debugging / numerics by running ``permute_and_pad`` with ``ep_degree=1``. |
There was a problem hiding this comment.
The local support is new I guess?
btw, we want to do this regardless of GraphTrainer limitations, for more direct code. The feedback we got overwhelmingly is that subclasses used to override ops are confusing / unintuitive. |
For eager mxfp8 (since it seems like this used to exist). |
makes sense, will add to the PR summary shortly |
This PR also adds the eager config for deepseek mxfp8 as well as mxfp8 + EP=1 support, I'll split that to a separate PR to make it easier to track numerics changes for the graph trainer related changes. |
| # the converter's compile requirement is satisfied. pad_multiple=128 is | ||
| # required by the CuTeDSL quantization kernel on sm_100 (e.g. B200); the | ||
| # default of 32 only suffices on older architectures. |
There was a problem hiding this comment.
wondering how did you do testing?
If you have verified manually, graph trainer also have some e2e unit test, and we should have 2 test cases that uses the mxfp8 configs.
There was a problem hiding this comment.
yeah, let's do that after #3935 lands, we need a clean baseline to add tests
| # Quantize the MoE expert grouped GEMMs to MXFP8 on the base model config | ||
| # before wrapping in the graph_trainer config. to_graph_trainer_config copies | ||
| # the (now MXFP8-swapped) model fields into the graph model class and swaps in | ||
| # graph_trainer's parallelize_fn. graph_trainer always compiles the model, so |
There was a problem hiding this comment.
graph_trainer always compiles the model
That's not the case... GraphTrainer always trace the model, but only regional compiles flex_attn.
I think we also need to mark the quantized region with regional_inductor?
|
|
||
| def graph_trainer_deepseek_v3_debugmodel_mxfp8() -> GraphTrainer.Config: | ||
| base = deepseek_v3_debugmodel() | ||
| # Quantize the MoE expert grouped GEMMs to MXFP8 on the base model config |
There was a problem hiding this comment.
what about the other gemms not in the MoE regions?
|
can you share a tlprase link to the run? I am wondering how it work without compiling? |
The original problem was not tracer not working with torch_function subclass. |
|
I split out mxfp8+eager baseline and mxfp8+ep=1 baselines to this stack: #3935 will rebase this PR on top once they land |
tianyu-l
left a comment
There was a problem hiding this comment.
please address comments before merging
0264f86 to
5b95567
Compare
Migrate NVFP4 from the override mechanism to the converter mechanism (NVFP4LinearConverter), aligning with Float8LinearConverter and the MXFP8LinearConverter direction in PR pytorch#3558: build the quantized module from a config node via model_registry(converters=...) rather than an opt-in override. NVFP4LinearConverter is a pure leaf swap. NVFP4Linear reuses torchao's stateful NVFP4Linear (weight/bias, the _sr_seed / _rht_sign_vector buffers, RHT logic, state-dict handling) and adds only torchtitan's meta-init buffer protocol and a bf16 DTensor<->local TP bridge: parallelize() infers colwise/rowwise from the weight placement and validates the local GEMM dims are divisible by 128; forward() runs the functional op on local shards and returns the colwise/rowwise placement so DTensor performs the reduction in bf16. This drops the override's parent-block sequence-parallel rewrite and fp4-code collectives (the fp4-comm win is marginal for the MoE / low-TP targets NVFP4 addresses; the fp4 compute win is retained). - New: torchtitan/components/quantization/nvfp4.py; exported from the package; has_quantization() updated to recognize NVFP4. - Enablement: llama3_debugmodel_nvfp4 and llama3_8b_nvfp4 in llama3/config_registry.py (fqns=["layers"] converts every in-layer linear and leaves lm_head stock; NVFP4 needs each GEMM dim % 128). - Remove the 738-line override and its 605-line unit test; convert the Blackwell integration entry to the converter flavor; add a CPU targeting test. Validated on GB200 (sm100): 1-GPU and TP=2 debugmodel training both converge over 3 steps with finite grad_norm and clean teardown. Co-Authored-By: Claude Opus 4.8 <[email protected]>
fee585a to
5f506b3
Compare
yes, just updated the test plan with evidence of this for mxfp8 eager, with NGPU1 |
5f506b3 to
9800f8b
Compare
Migrate NVFP4 from the override mechanism to the converter mechanism (NVFP4LinearConverter), aligning with Float8LinearConverter and the MXFP8LinearConverter direction in PR pytorch#3558: build the quantized module from a config node via model_registry(converters=...) rather than an opt-in override. NVFP4LinearConverter is a pure leaf swap. NVFP4Linear reuses torchao's stateful NVFP4Linear (weight/bias, the _sr_seed / _rht_sign_vector buffers, RHT logic, state-dict handling) and adds only torchtitan's meta-init buffer protocol and a bf16 DTensor<->local TP bridge: parallelize() infers colwise/rowwise from the weight placement and validates the local GEMM dims are divisible by 128; forward() runs the functional op on local shards and returns the colwise/rowwise placement so DTensor performs the reduction in bf16. This drops the override's parent-block sequence-parallel rewrite and fp4-code collectives (the fp4-comm win is marginal for the MoE / low-TP targets NVFP4 addresses; the fp4 compute win is retained). - New: torchtitan/components/quantization/nvfp4.py; exported from the package; has_quantization() updated to recognize NVFP4. - Enablement: llama3_debugmodel_nvfp4 and llama3_8b_nvfp4 in llama3/config_registry.py (fqns=["layers"] converts every in-layer linear and leaves lm_head stock; NVFP4 needs each GEMM dim % 128). - Remove the 738-line override and its 605-line unit test; convert the Blackwell integration entry to the converter flavor; add a CPU targeting test. Validated on GB200 (sm100): 1-GPU and TP=2 debugmodel training both converge over 3 steps with finite grad_norm and clean teardown. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Summary: 90% claude (for now) 1. add a config for graph trainer llama3 + mxfp8 2. add a config for graph trainer deepseek debug + mxfp8 3. make 2 work on a machine with 1 gpu by supporting the ep=1 path 4. make 2 actually run mxfp8 grouped_gemm by removing the torchao subclass wrapper and calling the underlying `torch.autograd.Function` directly. This is needed because `GraphTrainer` does not trace `__torch_function__`. Test Plan: ``` // on 1 B200 GPU // graph trainer + dense model + mxfp8 NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_8b_mxfp8 ./run_train.sh // graph trainer + moe debug model + mxfp8 NGPU=1 MODULE=graph_trainer.deepseek_v3 CONFIG=graph_trainer_deepseek_v3_debugmodel_mxfp8 ./run_train.sh ```
9800f8b to
3816164
Compare
Migrate NVFP4 from the override mechanism to the converter mechanism (NVFP4LinearConverter), aligning with Float8LinearConverter and the MXFP8LinearConverter direction in PR pytorch#3558: build the quantized module from a config node via model_registry(converters=...) rather than an opt-in override. NVFP4LinearConverter is a pure leaf swap. NVFP4Linear reuses torchao's stateful NVFP4Linear (weight/bias, the _sr_seed / _rht_sign_vector buffers, RHT logic, state-dict handling) and adds only torchtitan's meta-init buffer protocol and a bf16 DTensor<->local TP bridge: parallelize() infers colwise/rowwise from the weight placement and validates the local GEMM dims are divisible by 128; forward() runs the functional op on local shards and returns the colwise/rowwise placement so DTensor performs the reduction in bf16. This drops the override's parent-block sequence-parallel rewrite and fp4-code collectives (the fp4-comm win is marginal for the MoE / low-TP targets NVFP4 addresses; the fp4 compute win is retained). - New: torchtitan/components/quantization/nvfp4.py; exported from the package; has_quantization() updated to recognize NVFP4. - Enablement: llama3_debugmodel_nvfp4 and llama3_8b_nvfp4 in llama3/config_registry.py (fqns=["layers"] converts every in-layer linear and leaves lm_head stock; NVFP4 needs each GEMM dim % 128). - Remove the 738-line override and its 605-line unit test; convert the Blackwell integration entry to the converter flavor; add a CPU targeting test. Validated on GB200 (sm100): 1-GPU and TP=2 debugmodel training both converge over 3 steps with finite grad_norm and clean teardown. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI failure looks unrelated, landing |
One conflict + one required replay (this sync was not inert): - CONFLICT experiments/torchft/trainer.py: complementary dataloader kwargs (ours: training_steps/global_batch_size/parallel_dims; upstream pytorch#3856: local_batch_size -> dataloader_batch_size). Resolved keeping both. - REPLAY pytorch#3856 'Always Pre-Split Microbatches for PP' onto ezpz/trainer.py: it builds its own dataloader, so it needed the same PP microbatch-size logic or PP would feed full-size batches. Training dataloader only; the validator path keeps local_batch_size (matches upstream). - No replay for pytorch#3558 mxfp8 (SM100+CUDA+compile only -> inapplicable on XPU; adds an opt-in config fn only), kimi_k2_7, other models, or the 8 CI-only commits.
## Summary Add NVFP4 (NVIDIA Blackwell, sm_100+) as a first-class quantization recipe using the **converter** mechanism, alongside `Float8LinearConverter` and `MXFP8LinearConverter` (#3558): the quantized module is built from a config node via `model_registry(converters=...)`, so NVFP4 is selectable through the normal config path and tested in the standard flow. ### What changed - **New** `torchtitan/components/quantization/nvfp4.py`: `NVFP4LinearConverter` (a `Linear.Config` -> `NVFP4Linear.Config` leaf swap, mirroring `MXFP8LinearConverter`) and `NVFP4Linear`. - `NVFP4Linear` **reuses torchao's stateful `NVFP4Linear`** (weight/bias, the `_sr_seed` / `_rht_sign_vector` runtime buffers, RHT logic, state-dict handling) and adds: - torchtitan's meta-init buffer protocol. `_sr_seed` is a **per-rank, non-persistent** stochastic-rounding key (SR is unbiased and no quantized values cross the wire, so distinct seeds per rank are correct; a Philox key needs no checkpointing). `_rht_sign_vector` is drawn per-rank at random but **broadcast to a replicated, persistent** buffer, because the Hadamard basis must match across TP ranks (rowwise TP shards the GEMM contraction dim, and the transform only cancels when both operands share the sign vector). - a **tensor-parallel path on the `spmd_types` backend**. torchao's functional NVFP4 op (`nvfp4_mm_triton`) is an opaque Triton autograd Function that DTensor cannot dispatch on, so TP runs it inside an `spmd.local_map` region (modeled on `RoutedExperts`): the framework converts activations to local shards on entry and re-types the output on exit, and `nvfp4_mm_triton` is registered via `spmd.register_local_autograd_function`. - Mixed-precision NVFP4 with bf16 tail: new `qwen3_8b_nvfp4_mixed` and `lama3_8b_nvfp4_mixed` configs convert only the leading decoder layers to NVFP4 and keep the `last ceil(n_layers * 0.15)` layers and lm_head in bf16. ### Design notes **spmd_types-only TP.** The opaque NVFP4 op needs an explicit local-compute region to type-check under SPMD; the DTensor backend has no way to dispatch it. So TP is supported **only** under `spmd_backend='spmd_types'`, and is validated with `debug.spmd_typechecking` (an eager type checker that confirms the local_map colwise/rowwise output and input-gradient types). FSDP-only / single-GPU runs are unaffected and take torchao's local functional path directly. **bf16 collectives at the block boundary.** The converter keeps the model's stock bf16 TP collectives and quantizes only the GEMM -- it does not move fp4 codes over the wire. Moving fp4 would only help the column-parallel all-gather (the rowwise reduction needs a real sum and stays bf16), scales only with TP degree x sequence length, and is zero at TP=1. For NVFP4's targets -- large-K MoE models trained low-TP / high-EP, where bf16 all-to-all dominates and MoE experts are out of scope here -- the fp4 **compute** win is the prize and is fully retained. Keeping bf16 collectives also lets `NVFP4Linear` stay a leaf swap that composes with FSDP/TP through the standard `sharding_config`. ## Numerical and performance validation Llama 3 8B was trained on C4 dataset for 763 steps (200,015,872 tokens), sequence length 2048, global batch size 128, 4-way FSDP, TP 1. NVFP4, MXFP8, BF16 used the same local batch size of 32 with global accumulation of 1. <details> <summary> Experiment Setup </summary> - GPUs: 4× NVIDIA GB200, 184.3 GiB HBM each (~737 GiB total), sm_100 - OS: Ubuntu 24.04.4 LTS - Driver: NVIDIA 595.84.01 - Python: 3.12.3 - PyTorch: 2.14.0a0+gitd9abf9e - CUDA: 13.3 (nvcc 13.3.73) - OAI Triton: 3.8.0+git43422b04 - TorchAO: 0.18.0+gitcb76f29 for MXFP8 compiled cuda kernels; TOT for NVFP4 and BF16. </details> **Table 1 — Eager Trainer 200M-token run** | Precision | TPS/GPU | Aggregate TPS | TFLOPs/GPU | Peak mem | × BF16 TPS | × BF16 mem | Loss @200M | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | BF16 | 21,919 | 87,676 | 1,057.59 | 174.49 GiB | 1.00× | 1.00× | 1.27381 | | MXFP8 | 28,084 | 112,336 | 1,355.08 | 179.94 GiB (97.6%) | 1.28× | 1.03× | 1.26707 | | **NVFP4** | **31,758** | **127,032** | **1,532.34** | **103.00 GiB** | **1.45×** | **0.59×** | 1.26874 | **Takeaway:** NVFP4 has higher tokens per second (TPS) and lower peak memory usage than MXFP8 and BF16. It delivers ~**1.45× throughput at ~0.59× memory** with matched loss (1.274 vs 1.268) against BF16. MXFP8 is ~1.28 faster than BF16 but gives no memory relief because it saves BF16 activations for backwards pass. NVFP4 beats MXFP8 by **~1.13× on throughput while using only ~0.57× its memory (103 vs 180 GiB, ~77 GiB less)**. NVFP4 saves quantized activations and scale factors for backwards pass, reducing memory pressure. ## Training Loss Convergence **Eager Trainer 200M-token run for NVFP4, MXFP8, BF16** <img width="1440" height="840" alt="image" src="https://github.com/user-attachments/assets/b433c205-731d-4f35-966c-1ec5bf12a159" /> ## AI tools used - Claude Opus 4.8 (1M context) and OAI GPT 5.6 via Codex
Summary:
torch.autograd.Functionwith the mxfp8 logic directly. This is needed becauseGraphTraineruses SimpleFSDP, that uses DTensorized weight, and that does not compose with torchao's previous usage of__torch_function__.An explanation of 3:
Same result in the end, but more direct and no longer depends on
__torch_function__.Test Plan:
Verified the traces manually to see mxfp8 MoE kernels being called in GraphTrainer runs