Repository navigation
Conversation
fegin
force-pushed
the
fegin/stack/41
branch
from
November 16, 2026 22:18
0ec4d5a to
f6b1b4a
Compare
fegin
force-pushed
the
fegin/stack/42
branch
from
November 16, 2026 22:18
9420287 to
76b0325
Compare
This was referenced Nov 16, 2026
fegin
added a commit
that referenced
this pull request
Nov 17, 2026
…r graph capture (#6131) Stacked PRs: * #6136 * #6135 * #6134 * #6133 * #6132 * #5882 * #5881 * __->__#6131 --- --- --- ### [cudagraph] Remove the unsynchronized empty_cache() before accelerator graph capture ## Summary (human-written) There is a race condition if users do not call a sync after step() and call empty_cache() before the next step(). For the current TorchTitan main, we do call sync in the end of each iteration to gather the log. However, if we change the logging to async, this race condition will be exposed. The race condition happens like this: ```text step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream AdamW reading those grads is queued on the default stream step 3: zero_grad(set_to_none=True) frees the grads on the host -> the blocks return to the reduce-scatter stream's free pool empty_cache() unmaps free blocks of expandable segments, after syncing only the reduce-scatter stream -> the queued AdamW reads unmapped memory: illegal memory access ``` This PR fixes the issue by removing the wrapper's empty_cache(). The graph capture context (torch.cuda.graph / torch.accelerator.Graph) already calls synchronize() and then empty_cache() when it starts, so the extra call is not needed and the race is gone. ## Why `AcceleratorGraphWrapper` calls `torch.accelerator.empty_cache()` right before it captures a graph, without a sync. If the host runs ahead of the device, this can unmap memory that a queued kernel still reads: ```text step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream AdamW reading those grads is queued on the default stream step 3: zero_grad(set_to_none=True) frees the grads on the host -> the blocks return to the reduce-scatter stream's free pool empty_cache() unmaps free blocks of expandable segments, after syncing only the reduce-scatter stream -> the queued AdamW reads unmapped memory: illegal memory access ``` On main, a blocking host-to-device copy of the token counts in `Trainer.train_step` waits for the previous optimizer step before `zero_grad`, so the host never gets this far ahead. "[trainer] Log training metrics without waiting for the device", later in this stack, removes that copy and exposes the crash: llama3 debug model, FSDP2 on 2 GPUs, `expandable_segments:True` (set by `run_train.sh`), crashes in step 2-3 with varlen, flex, and CP2. The call is not needed. The capture context that runs right after it, `torch.cuda.graph` or `torch.accelerator.Graph`, already calls `synchronize()` and then `empty_cache()` in `__enter__`. ## What changed - Remove the wrapper's `empty_cache()` and its `before_empty_cache` / `after_empty_cache` memory logs. The capture context releases the same cache, after a device sync. - `ACCELERATOR_GRAPH.md` says the capture context empties the cache. - `test_preparation_runs_only_before_first_capture` (renamed) expects no `empty_cache()` call from the wrapper. The underlying gap is in PyTorch. FSDP2 orders the reuse of gradient blocks with stream events, which covers normal allocations but not `empty_cache()`. The expandable-segment unmap waits only for the stream that allocated the block, while a plain `cudaFree` syncs the device. A single-GPU repro without torchtitan crashes with expandable segments, and passes with a `record_stream` before the free or a sync before `empty_cache()`. The optimizer's first-step `empty_cache()` already syncs first (#5019). The other call runs at startup. ## Testing - With the host running ahead ("[trainer] Log training metrics without waiting for the device"), llama3 debug model on 2 GPUs, `log_freq=10`, 20 steps: with the wrapper's unsynchronized call, varlen, flex, and CP2 each crash 3 of 3 runs; with it removed all pass 3 of 3. A GPU coredump puts the fault in the fused AdamW kernel, on gradients in segments owned by FSDP2's reduce-scatter stream. - On another 4-GPU host the debug model does not get far enough ahead to crash. With an ~80 ms GPU sleep added before each AdamW step, the wrapper's unsynchronized call crashes 8 of 9 runs (varlen, flex, CP2) and this change passes 9 of 9. - Losses and grad_norm match a `CUDA_LAUNCH_BLOCKING=1` run of the same config (varlen with `debug.deterministic=True`). This change was written with an AI assistant (Claude).
fegin
force-pushed
the
fegin/stack/42
branch
2 times, most recently
from
November 18, 2026 08:47
4f3edc0 to
424363a
Compare
fegin
force-pushed
the
fegin/stack/42
branch
from
November 19, 2026 21:13
424363a to
bff3244
Compare
This was referenced Nov 19, 2026
fegin
force-pushed
the
fegin/stack/42
branch
from
November 20, 2026 00:20
bff3244 to
9689e41
Compare
fegin
force-pushed
the
fegin/stack/42
branch
from
November 20, 2026 18:02
9689e41 to
9abff8a
Compare
fegin
requested review from
acisseJZhong,
felipemello1,
shuhuayu and
wwwjn
as code owners
November 30, 2026 22:55
fegin
force-pushed
the
fegin/stack/42
branch
from
November 30, 2026 23:00
d51288d to
c6a325f
Compare
fegin
force-pushed
the
fegin/stack/41
branch
from
November 30, 2026 23:00
29f9c53 to
2ed594a
Compare
fegin
marked this pull request as draft
November 30, 2026 23:07
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
Stacked PRs: * #6252 * #5746 * #6135 * #6134 * #6133 * #6132 * __->__#5882 * #5881 (landed) --- --- --- ### [muse_spark] Add a 64-GPU Dist-MoE recipe with varlen attention ## Summary (human-written) With the CPU-offloading optimizer, we can run Muse Spark with 64 GPUs. This PR adds a recipe to demonstrate it. ## Why The Dist-MoE scale recipes run only on 256 or 512 GPUs, and they use FlexAttention only. #5706 added `attn_backend` to `muse_spark_816b_a42b` and listed three blockers for varlen in these recipes: their loader sets no `max_num_documents`, varlen K/V all-gather is untested on Muse, and `use_flex_flash_attention` raises on non-flex layers. This change removes those blockers and adds a 64-GPU recipe. It covers the #5706 follow-up "Varlen K/V all-gather CP for the Dist-MoE scale recipes". **Example.** ```text before: muse_spark_816b_a42b_dist_moe_bf16_spmd_256 / _512 only, FlexAttention after: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 (and _64_fake): Muse Spark 816B, BF16 Dist-MoE, DP8 / CP8 (K/V all-gather) / EP64, TP1, 32K sequence length, global batch 64, varlen attention with max_num_documents=128, Adam moments in pinned host memory ``` ## What changed **Recipe helpers** - `_muse_spark_816b_dist_moe_bf16_spmd` takes `attn_backend: Literal["flex", "varlen"]` and `max_num_documents`. It passes `attn_backend` to `muse_spark_816b_a42b`. - It sets the data loader's `max_num_documents` before `_with_dist_moe` enables CUDA graphs, because `Trainer.Config` validation checks varlen against CUDA graphs. - The FakePG data loader keeps `max_num_documents`. It replaces only the dataset and shuffle fields of the data loader config. - The K/V all-gather CP transform also maps `VarlenInnerAttention` and `SlidingWindowVarlenInnerAttention`. - Flex-Flash block-mask tuning applies only with FlexAttention. **New recipes** - `muse_spark_816b_a42b_dist_moe_bf16_spmd_64` and `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake`. Remat also saves all attention regions (`attention.*`). - The 64-GPU recipe sets `fsdp_reshard_after_forward = "default"` instead of the helper's `"always"`. With PP off, only the last [norm, lm_head] FSDP unit changes: it stays unsharded after forward, so the loss does not all-gather the 3 GiB lm_head weight again. - `max_num_documents=128` is one slot per 256 tokens. The packer never drops documents: a row that reaches the cap ends early and is padded, and the rest of the document starts the next row. On C4 with the Muse Spark tokenizer (600 rows on each of 8 DP ranks), documents average 460 tokens. 64 slots pad 10.7% of the tokens, and 80% of the rows reach the cap. 128 slots pad none. - The data loader and AdamW configs are updated with `dataclasses.replace`, so their `__post_init__` checks run (`max_num_documents > 0`; `moment_cpu_offload_fraction > 0` needs `fused=True` and rejects accelerators other than CUDA, including ROCm). **README** (`torchtitan/models/muse_spark/README.md`) - Context parallelism: varlen attention supports both Ulysses and K/V all-gather. - CP load balancing: head-tail works with K/V all-gather varlen. - K/V all-gather CP needs tokens per microbatch divisible by the CP degree, or by 2 x the CP degree with head-tail. The query block size rule applies only with FlexAttention. - Varlen attention with CUDA graphs requires `dataloader.max_num_documents`. Without it, set `training.disable_accelerator_graphs`. - A table lists the Dist-MoE scale recipes. ## Numerics The 256- and 512-GPU and UltraData recipe configs are unchanged (0 field diffs). ## Testing - `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake` (NGPU=64, NUMA-bound) runs and fits on one GPU of the fake-PG layout for 10 steps. - Varlen K/V all-gather also runs with head-tail load balancing on the same layout. - Muse Spark recipe and model CPU unit tests. - Both 64-GPU recipes build and pass `Trainer.Config` validation. - `test_fake_scale_recipe_tokenizer[muse_spark_816b_a42b_dist_moe_bf16_spmd_64_fake]` builds the 64-GPU fake recipe. It catches a broken build, including a varlen layer type that the K/V all-gather CP map misses (the build raises "No CP inner attention configured"). ## Known issues / follow-ups - The real recipe ran on 64 GPUs for 20 steps at an earlier rebase of this stack, with the same save regions, real routing, and `max_num_documents=64`. Peak memory was 267.4 GiB (trainer) and 272.7 GiB (NVML) of 276.6 GiB, so only about 4 GiB is free. tps was about 2% higher than with the default save regions (1,716 vs 1,683). - On 64 real GPUs with the same setup, `fsdp_reshard_after_forward = "default"` lowered peak memory by 1.9 GiB (265.5 vs 267.4 GiB trainer, 270.8 vs 272.7 GiB NVML), and tps did not change (1,725 vs 1,716). The 256- and 512-GPU recipes keep `"always"`. - `max_num_documents=128` was run on 64 real GPUs only with the whole recipe stack, which also shards the vocab over CP and frees memory. There, peak allocated memory was the same as with 64 slots. It is not run at this commit alone, where only about 4 GiB is free. - tps counts padding tokens, and padding rows skip the routed experts. So 128 slots lower the reported tps but raise the real tokens trained per second. - `test_debug_recipe_tokenizer[muse_spark_debugmodel_mm]` also fails on main.
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
…variant
## Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
## Why
**Save more outputs.** The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
**MXFP8.** The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
**Example.**
```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 only
save regions = attention.inner_attention, feed_forward.routed_experts.dist_moe, attention.*
after: save regions = ... + feed_forward.pooler.*, feed_forward.unpooler.*, feed_forward.router.*
muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64: same DP8/CP8/EP64 layout and save regions
routed experts -> MXFP8DistMoeRoutedExperts, BlockScaledConfig(fast_math=True)
attention.*, feed_forward.pooler/unpooler -> MXFP8Linear
inner attention and lm_head stay BF16
checkpoint folder muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64
```
## What changed
**Save regions**
- The 64-GPU recipes also save `feed_forward.pooler.*`, `feed_forward.unpooler.*`, and `feed_forward.router.*`. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.
**MXFP8 variant**
- `_muse_spark_816b_dist_moe_bf16_spmd` is renamed to `_muse_spark_816b_dist_moe_spmd` and takes `expert_precision`. With `"mxfp8"`, the routed experts use MXFP8 Dist-MoE, and an `MXFP8LinearTransform` quantizes the attention and compressed-MoE (pooler/unpooler) projections, as in `muse_spark_debugmodel_dist_moe_mxfp8`.
- `_with_dist_moe` passes `BlockScaledConfig(fast_math=True)` for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.
- A comment on the 64-GPU recipe's TP1 records why MXFP8 recipes avoid TP.
- The MXFP8 linear policy moves from the test recipes into `torchtitan_recipes/models/muse_spark.py`, so both recipes share it (mechanical).
- The checkpoint folder name includes the expert precision.
- New recipes: `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64` and `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake`.
- The README recipe table lists the MXFP8 recipe.
## Numerics
- Saving instead of recomputing gives the same values. Muse Spark debug model with Dist-MoE, DP2 x CP2 x EP4 on 4 GPUs, vocab over CP, seed 42, deterministic, CUDA graphs, 10 steps: loss and grad_norm are bitwise equal with and without the three regions (step 10: 5.082653522491455 / 1.653401494026184). The log shows the pooler, unpooler, and router gate linears switch from recompute to saved.
- BF16 vs MXFP8, 100 real steps: loss at steps 1 / 50 / 100 is 12.2323 / 3.8930 / 2.9158 vs 12.2316 / 3.8928 / 2.9195. No long loss comparison was run.
- `fast_math=True` vs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.
## Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.
- Save regions (BF16): 2,219.2 -> 2,245.5 tps (+1.2%), 246.55 / 254.40 -> 252.41 / 260.40 GiB. NVML peak 260.01 -> 266.01 GiB.
- BF16 -> MXFP8 (both with the new save regions): 2,245.5 -> 2,525.3 tps (+12.5%), 252.41 / 260.40 -> 259.05 / 266.44 GiB. NVML peak 266.01 -> 272.66 GiB. Of this, `fast_math=True` alone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).
- Logical 64-GPU FakePG run (rank 0): save regions 3,662.9 -> 3,746.1 tps (+2.3%); BF16 -> MXFP8 3,746.1 -> 4,165.3 tps (+11.2%).
The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
## Testing
- `test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projections` builds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.
- `pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark` (with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.
## Known issues / follow-ups
- Needs dist_moe at or after meta-pytorch/dist_moe@b76e0e0 ("Fix MXFP8 callback postprocess with padded routes"). Before it, the padded-row zeroing that Muse uses raises in the MXFP8 expert postprocess. CI installs dist_moe from main, which includes the fix.
- The lm_head stays BF16. `MuseSparkLMHead` has an fp32 output, an output multiplier, and a tanh soft cap, and `MXFP8LinearTransform` only converts plain `Linear` configs.
- The Dist-MoE MXFP8 scratch could share memory by buffer lifetime, as the BF16 formula does, which would return about 5.6 GiB. That change belongs in Dist-MoE.
stack-info: PR: #6135, branch: fegin/stack/42
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
…variant
## Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
## Why
**Save more outputs.** The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
**MXFP8.** The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
**Example.**
```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 only
save regions = attention.inner_attention, feed_forward.routed_experts.dist_moe, attention.*
after: save regions = ... + feed_forward.pooler.*, feed_forward.unpooler.*, feed_forward.router.*
muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64: same DP8/CP8/EP64 layout and save regions
routed experts -> MXFP8DistMoeRoutedExperts, BlockScaledConfig(fast_math=True)
attention.*, feed_forward.pooler/unpooler -> MXFP8Linear
inner attention and lm_head stay BF16
checkpoint folder muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64
```
## What changed
**Save regions**
- The 64-GPU recipes also save `feed_forward.pooler.*`, `feed_forward.unpooler.*`, and `feed_forward.router.*`. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.
**MXFP8 variant**
- `_muse_spark_816b_dist_moe_bf16_spmd` is renamed to `_muse_spark_816b_dist_moe_spmd` and takes `expert_precision`. With `"mxfp8"`, the routed experts use MXFP8 Dist-MoE, and an `MXFP8LinearTransform` quantizes the attention and compressed-MoE (pooler/unpooler) projections, as in `muse_spark_debugmodel_dist_moe_mxfp8`.
- `_with_dist_moe` passes `BlockScaledConfig(fast_math=True)` for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.
- A comment on the 64-GPU recipe's TP1 records why MXFP8 recipes avoid TP.
- The MXFP8 linear policy moves from the test recipes into `torchtitan_recipes/models/muse_spark.py`, so both recipes share it (mechanical).
- The checkpoint folder name includes the expert precision.
- New recipes: `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64` and `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake`.
- The README recipe table lists the MXFP8 recipe.
## Numerics
- Saving instead of recomputing gives the same values. Muse Spark debug model with Dist-MoE, DP2 x CP2 x EP4 on 4 GPUs, vocab over CP, seed 42, deterministic, CUDA graphs, 10 steps: loss and grad_norm are bitwise equal with and without the three regions (step 10: 5.082653522491455 / 1.653401494026184). The log shows the pooler, unpooler, and router gate linears switch from recompute to saved.
- BF16 vs MXFP8, 100 real steps: loss at steps 1 / 50 / 100 is 12.2323 / 3.8930 / 2.9158 vs 12.2316 / 3.8928 / 2.9195. No long loss comparison was run.
- `fast_math=True` vs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.
## Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.
- Save regions (BF16): 2,219.2 -> 2,245.5 tps (+1.2%), 246.55 / 254.40 -> 252.41 / 260.40 GiB. NVML peak 260.01 -> 266.01 GiB.
- BF16 -> MXFP8 (both with the new save regions): 2,245.5 -> 2,525.3 tps (+12.5%), 252.41 / 260.40 -> 259.05 / 266.44 GiB. NVML peak 266.01 -> 272.66 GiB. Of this, `fast_math=True` alone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).
- Logical 64-GPU FakePG run (rank 0): save regions 3,662.9 -> 3,746.1 tps (+2.3%); BF16 -> MXFP8 3,746.1 -> 4,165.3 tps (+11.2%).
The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
## Testing
- `test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projections` builds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.
- `pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark` (with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.
## Known issues / follow-ups
- Needs dist_moe at or after meta-pytorch/dist_moe@b76e0e0 ("Fix MXFP8 callback postprocess with padded routes"). Before it, the padded-row zeroing that Muse uses raises in the MXFP8 expert postprocess. CI installs dist_moe from main, which includes the fix.
- The lm_head stays BF16. `MuseSparkLMHead` has an fp32 output, an output multiplier, and a tanh soft cap, and `MXFP8LinearTransform` only converts plain `Linear` configs.
- The Dist-MoE MXFP8 scratch could share memory by buffer lifetime, as the BF16 formula does, which would return about 5.6 GiB. That change belongs in Dist-MoE.
stack-info: PR: #6135, branch: fegin/stack/42
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
…6132) Stacked PRs: * #6252 * #5746 * #6135 * #6134 * #6133 * #6468 * __->__#6132 * #5882 (landed) * #5881 (landed) --- --- --- ### [trainer][perf] Log training metrics without waiting for the device ## Summary (human-written) TorchTitan's logging currently waits for the device. But it can actually be overlapped with the next step. Right now we have to adjust the logging frequency to avoid logging being the bottleneck. This is very annoying. With this PR, we can set logging frequency to 1 which is very useful when the cluster resource is busy and we don't have luxury to run many iterations. Follows the design of #2728 and fixes some issues. ## Why Each logged step reads its metrics right after `optim_step()`. The first read, `int(global_main_loss_token_count)`, and the `.item()` calls after it wait until the device finishes the optimizer update. Only then does the host fetch, preprocess, and copy the next step's inputs, so the device sits idle before the next step's first kernel or CUDA graph. With `log_freq=1` this happens every step. Blocking host-to-device copies wait for the update too: the global token count before the next forward, and the token and FLOP counts that the logged reductions create with `torch.tensor(..., device=...)`. ```text before: optim_step | .item() waits for the update | fetch, preprocess, H2D | device idle | forward after: optim_step | queue metric copies | fetch, preprocess, H2D, queue forward | print the previous step ``` #2728 deferred the same reads by one step. It was closed without merging: the review asked to wait for #4202 (distributed tensor logging), so metrics could handle device and host values together. #4202 is still open, and it adds per-tensor statistics; it does not remove these per-step reads. This change is small and self-contained, so it can land now and move onto #4202's mechanism when that lands. ## What changed - `MetricsProcessor.log_async` takes the logged values as tensors or floats. It starts a non-blocking host copy of each tensor and returns. `flush()` waits for those copies and emits the metrics. `log()` is `log_async()` plus `flush()`, so other callers keep their behavior. - The global token count, and the token and FLOP counts reduced for logging, are copied to the device with `non_blocking=True`. A blocking copy from pageable memory waits for the previous optimizer update. - `Trainer.train_step` calls `log_async` and flushes the previous logged step after queuing its own forward and backward. `train()` also flushes before validation and when training ends, so log lines keep their order. - The throughput window ends when the device reaches the `log_async` call. It is timed with device events recorded at `reset()` and at `log_async`. A checkpoint saved after the step is not in its window, as before. Validation throughput is timed with the same events. Runs without an accelerator (`torch.accelerator.is_available()` is false) use the host clock. Token count, data loading time, and peak memory are read at `log_async`, so data the next step fetches before the flush is not counted. - The logged reductions keep their results on the device: `dist_sum_tensor`, a new `dist_max_tensor`, and `dist_mean_tensor` (renamed from `dist_mean` to match the other two). `collect_aux_loss_metrics` returns device scalars, divided in float64 as before, and the RL trainer converts them where it needs floats. - The `global_valid_tokens` trace record is passed to `log_async` apart from the metrics and emitted at the flush. `log_trace_scalar` takes optional `step` and `relative_step`, so the record keeps the step it belongs to. Its step tags come from the step that flushes it. ## User-facing changes | | Before | After | |---|---|---| | Training log line of step N | printed during step N | printed during step N+1, after its work is queued | | `dist_mean` | returns a float | renamed `dist_mean_tensor`, returns a device tensor | | `collect_aux_loss_metrics` | returns floats | returns device scalars | The order of log lines (training before validation of the same step), metric keys, and values are unchanged. ## Numerics / performance Loss and grad_norm are unchanged; only when they are read changes. llama3 debug model, 2 GPUs, seed 42, deterministic, 12 steps with `log_freq=5`, validation, and a checkpoint at step 10: loss, grad_norm, and validation loss match the parent commit at every logged step. Peak reserved memory of step 1 is 0.89 GiB vs 0.78 GiB on the parent; later steps match (0.80 GiB). Freed blocks used by other streams go back to the allocator later when the host runs ahead. 64 real GB300 GPUs, `muse_spark_816b_a42b_dist_moe_bf16_spmd_64` (DP8/CP8/EP64, 32K, pinned-host Adam moments, log_freq=1), 100 steps from random init: 2,122.2 -> 2,158.7 tps over steps 71-90 (+1.7%). Step-1 peak allocated memory is unchanged (257.82 GiB). FakePG run of the same recipe (`_fake`), one GPU, NUMA-bound, arms alternated on the same GPU, median tps of steps 5-10 (log_freq=1) or the steps 11-20 window (log_freq=10), relative to the parent commit: | | log_freq=1 | log_freq=10 | |---|---|---| | parent | 1.000 | 1.000 | | this commit | 1.028, 1.029, 1.027 | 1.009, 1.009 | Logging every step costs the parent 1.8%; this commit removes that cost. Host wall time per step agrees with the event-timed tps (-2.9%). Peak memory is unchanged. Copying each value separately costs at most 0.1% compared with one stacked copy. An earlier version without the non-blocking count copies gave no gain at log_freq=1. With `debug.seed=42`, losses match the parent within the parent's own run-to-run noise on this recipe. ## Testing - `test_async_log_uses_the_window_at_log_time`: data fetched before the flush must not count in the logged step's throughput window, and the emitted values must match the logged tensors. The deferred trace record must carry the logged step and relative step. The loss is (1,)-shaped, like the loss on PP ranks without the last stage, while grad_norm is 0-dim. - `test_trainer_accumulates_reused_accelerator_graph_losses` checks the values passed to `log_async` and that each step flushes. - `pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 244 passed, 1 skipped, with GPUs visible and with `CUDA_VISIBLE_DEVICES=` (no accelerator). - llama3 debug model, 2 GPUs, seed 42, deterministic: loss and grad_norm in TensorBoard are bitwise equal to the parent commit at every logged step for FSDP 2 with 20 steps at `log_freq=1` and `log_freq=10`, and for PP 2 with 1F1B (`llama3_debugmodel_pp2_1f1b`) with 10 steps at `log_freq=1`. The PP run checks that the rank without the last stage can log its (1,)-shaped loss sentinel. - `test_trainer_keeps_scheduled_eval_during_warmup`: its fake trainer gets a `metrics_processor`, since `train()` flushes before validation. ## Known issues / follow-ups - An error raised after a step is logged but before the flush, for example an NCCL timeout, loses that step's log line. - #4202 (distributed tensor logging) is a separate mechanism for per-tensor statistics; it does not remove these reads. This change was written with an AI assistant (Claude).
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
…variant
## Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
## Why
**Save more outputs.** The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
**MXFP8.** The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
**Example.**
```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 only
save regions = attention.inner_attention, feed_forward.routed_experts.dist_moe, attention.*
after: save regions = ... + feed_forward.pooler.*, feed_forward.unpooler.*, feed_forward.router.*
muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64: same DP8/CP8/EP64 layout and save regions
routed experts -> MXFP8DistMoeRoutedExperts, BlockScaledConfig(fast_math=True)
attention.*, feed_forward.pooler/unpooler -> MXFP8Linear
inner attention and lm_head stay BF16
checkpoint folder muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64
```
## What changed
**Save regions**
- The 64-GPU recipes also save `feed_forward.pooler.*`, `feed_forward.unpooler.*`, and `feed_forward.router.*`. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.
**MXFP8 variant**
- `_muse_spark_816b_dist_moe_bf16_spmd` is renamed to `_muse_spark_816b_dist_moe_spmd` and takes `expert_precision`. With `"mxfp8"`, the routed experts use MXFP8 Dist-MoE, and an `MXFP8LinearTransform` quantizes the attention and compressed-MoE (pooler/unpooler) projections, as in `muse_spark_debugmodel_dist_moe_mxfp8`.
- `_with_dist_moe` passes `BlockScaledConfig(fast_math=True)` for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.
- A comment on the 64-GPU recipe's TP1 records why MXFP8 recipes avoid TP.
- The MXFP8 linear policy moves from the test recipes into `torchtitan_recipes/models/muse_spark.py`, so both recipes share it (mechanical).
- The checkpoint folder name includes the expert precision.
- New recipes: `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64` and `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake`.
- The README recipe table lists the MXFP8 recipe.
## Numerics
- Saving instead of recomputing gives the same values. Muse Spark debug model with Dist-MoE, DP2 x CP2 x EP4 on 4 GPUs, vocab over CP, seed 42, deterministic, CUDA graphs, 10 steps: loss and grad_norm are bitwise equal with and without the three regions (step 10: 5.082653522491455 / 1.653401494026184). The log shows the pooler, unpooler, and router gate linears switch from recompute to saved.
- BF16 vs MXFP8, 100 real steps: loss at steps 1 / 50 / 100 is 12.2323 / 3.8930 / 2.9158 vs 12.2316 / 3.8928 / 2.9195. No long loss comparison was run.
- `fast_math=True` vs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.
## Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.
- Save regions (BF16): 2,219.2 -> 2,245.5 tps (+1.2%), 246.55 / 254.40 -> 252.41 / 260.40 GiB. NVML peak 260.01 -> 266.01 GiB.
- BF16 -> MXFP8 (both with the new save regions): 2,245.5 -> 2,525.3 tps (+12.5%), 252.41 / 260.40 -> 259.05 / 266.44 GiB. NVML peak 266.01 -> 272.66 GiB. Of this, `fast_math=True` alone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).
- Logical 64-GPU FakePG run (rank 0): save regions 3,662.9 -> 3,746.1 tps (+2.3%); BF16 -> MXFP8 3,746.1 -> 4,165.3 tps (+11.2%).
The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
## Testing
- `test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projections` builds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.
- `pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark` (with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.
## Known issues / follow-ups
- Needs dist_moe at or after meta-pytorch/dist_moe@b76e0e0 ("Fix MXFP8 callback postprocess with padded routes"). Before it, the padded-row zeroing that Muse uses raises in the MXFP8 expert postprocess. CI installs dist_moe from main, which includes the fix.
- The lm_head stays BF16. `MuseSparkLMHead` has an fp32 output, an output multiplier, and a tanh soft cap, and `MXFP8LinearTransform` only converts plain `Linear` configs.
- The Dist-MoE MXFP8 scratch could share memory by buffer lifetime, as the BF16 formula does, which would return about 5.6 GiB. That change belongs in Dist-MoE.
stack-info: PR: #6135, branch: fegin/stack/42
fegin
added a commit
that referenced
this pull request
Dec 1, 2026
#6468) Stacked PRs: * #6252 * #5746 * #6135 * #6134 * #6133 * __->__#6468 * #6132 (landed) * #5882 (landed) * #5881 (landed) --- --- --- ### [torchft] Log training metrics without waiting for the device ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why #6132 makes the core trainer log through `MetricsProcessor.log_async`. The torchft trainer has its own `train_step` and still calls the blocking `MetricsProcessor.log()` with floats read by `dist_sum`, `dist_max`, and `.item()`. It is the only caller of `log()`, and the only reason `log_async` accepts floats for the loss and grad_norm. Moving it to `log_async` leaves one logging API with tensor-only loss and grad_norm. The speedup for torchft is small: `TorchFTOptim` already waits for the device every step (`step_is_finite.item()`), and so does `should_commit()`. The main value is the API cleanup. ## What changed - `FaultTolerantTrainer.train_step` reduces the logged values with `dist_sum_tensor` and `dist_max_tensor` (with `ft_pg`, as before), keeps grad_norm and the loss on the device, and calls `log_async`. It flushes the previous logged step after the next step's data is on the device and before `forward_backward`. The core trainer flushes after `forward_backward`, but here `zero_grad` in `forward_backward` starts the next quorum, which may reconfigure `ft_pg`, so the previous step's logging all-reduces on `ft_pg` must finish first, as they did before this change. - `train()` flushes before validation and when training ends, so log lines keep their order. - Host-to-device copies of the token counts and FLOPs use `non_blocking=True`, as in the core trainer. - `MetricsProcessor.log()` is deleted. `log_async` takes `global_avg_loss`, `global_max_loss`, and `grad_norm` as tensors only. `num_flops` stays `float | torch.Tensor`, because the trainers pass a Python float when DP is off. ## User-facing changes | | Before | After | |---|---|---| | torchft training log line of step N | printed during step N | printed during step N+1, before its forward | | `MetricsProcessor.log()` | blocking log | deleted; use `log_async()` and `flush()` | ## Numerics / performance Loss and grad_norm are unchanged; only when they are read changes. The divisions by the replica count are the same, applied to tensors instead of floats. ## Testing - `test_ft_averages_logged_loss_and_flops_by_active_replica_count` mocks the tensor reductions, and checks the values passed to `log_async`, that the logged sums go through `ft_pg`, and that the step flushes before `forward_backward`. - `pytest torchtitan/experiments/torchft/tests/test_torchft_trainer.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability tests/unit_tests/cpu/components/test_invalid_loss.py tests/unit_tests/cpu/components/test_validator.py tests/unit_tests/cpu/models/common/test_aux_loss.py`: 256 passed, 1 skipped. - Not run: the 8-GPU torchft integration test (torchft is not installable here). CI runs it. This change was written with an AI assistant (Claude).
fegin
added a commit
that referenced
this pull request
Dec 2, 2026
…variant
## Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
## Why
**Save more outputs.** The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
**MXFP8.** The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
**Example.**
```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 only
save regions = attention.inner_attention, feed_forward.routed_experts.dist_moe, attention.*
after: save regions = ... + feed_forward.pooler.*, feed_forward.unpooler.*, feed_forward.router.*
muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64: same DP8/CP8/EP64 layout and save regions
routed experts -> MXFP8DistMoeRoutedExperts, BlockScaledConfig(fast_math=True)
attention.*, feed_forward.pooler/unpooler -> MXFP8Linear
inner attention and lm_head stay BF16
checkpoint folder muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64
```
## What changed
**Save regions**
- The 64-GPU recipes also save `feed_forward.pooler.*`, `feed_forward.unpooler.*`, and `feed_forward.router.*`. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.
**MXFP8 variant**
- `_muse_spark_816b_dist_moe_bf16_spmd` is renamed to `_muse_spark_816b_dist_moe_spmd` and takes `expert_precision`. With `"mxfp8"`, the routed experts use MXFP8 Dist-MoE, and an `MXFP8LinearTransform` quantizes the attention and compressed-MoE (pooler/unpooler) projections, as in `muse_spark_debugmodel_dist_moe_mxfp8`.
- `_with_dist_moe` passes `BlockScaledConfig(fast_math=True)` for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.
- A comment on the 64-GPU recipe's TP1 records why MXFP8 recipes avoid TP.
- The MXFP8 linear policy moves from the test recipes into `torchtitan_recipes/models/muse_spark.py`, so both recipes share it (mechanical).
- The checkpoint folder name includes the expert precision.
- New recipes: `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64` and `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake`.
- The README recipe table lists the MXFP8 recipe.
## Numerics
- Saving instead of recomputing gives the same values. Muse Spark debug model with Dist-MoE, DP2 x CP2 x EP4 on 4 GPUs, vocab over CP, seed 42, deterministic, CUDA graphs, 10 steps: loss and grad_norm are bitwise equal with and without the three regions (step 10: 5.082653522491455 / 1.653401494026184). The log shows the pooler, unpooler, and router gate linears switch from recompute to saved.
- BF16 vs MXFP8, 100 real steps: loss at steps 1 / 50 / 100 is 12.2323 / 3.8930 / 2.9158 vs 12.2316 / 3.8928 / 2.9195. No long loss comparison was run.
- `fast_math=True` vs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.
## Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.
- Save regions (BF16): 2,219.2 -> 2,245.5 tps (+1.2%), 246.55 / 254.40 -> 252.41 / 260.40 GiB. NVML peak 260.01 -> 266.01 GiB.
- BF16 -> MXFP8 (both with the new save regions): 2,245.5 -> 2,525.3 tps (+12.5%), 252.41 / 260.40 -> 259.05 / 266.44 GiB. NVML peak 266.01 -> 272.66 GiB. Of this, `fast_math=True` alone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).
- Logical 64-GPU FakePG run (rank 0): save regions 3,662.9 -> 3,746.1 tps (+2.3%); BF16 -> MXFP8 3,746.1 -> 4,165.3 tps (+11.2%).
The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
## Testing
- `test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projections` builds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.
- `pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark` (with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.
## Known issues / follow-ups
- Needs dist_moe at or after meta-pytorch/dist_moe@b76e0e0 ("Fix MXFP8 callback postprocess with padded routes"). Before it, the padded-row zeroing that Muse uses raises in the MXFP8 expert postprocess. CI installs dist_moe from main, which includes the fix.
- The lm_head stays BF16. `MuseSparkLMHead` has an fp32 output, an output multiplier, and a tanh soft cap, and `MXFP8LinearTransform` only converts plain `Linear` configs.
- The Dist-MoE MXFP8 scratch could share memory by buffer lifetime, as the BF16 formula does, which would return about 5.6 GiB. That change belongs in Dist-MoE.
stack-info: PR: #6135, branch: fegin/stack/42
…variant
## Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
## Why
**Save more outputs.** The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
**MXFP8.** The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
**Example.**
```text
before: muse_spark_816b_a42b_dist_moe_bf16_spmd_64 only
save regions = attention.inner_attention, feed_forward.routed_experts.dist_moe, attention.*
after: save regions = ... + feed_forward.pooler.*, feed_forward.unpooler.*, feed_forward.router.*
muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64: same DP8/CP8/EP64 layout and save regions
routed experts -> MXFP8DistMoeRoutedExperts, BlockScaledConfig(fast_math=True)
attention.*, feed_forward.pooler/unpooler -> MXFP8Linear
inner attention and lm_head stay BF16
checkpoint folder muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64
```
## What changed
**Save regions**
- The 64-GPU recipes also save `feed_forward.pooler.*`, `feed_forward.unpooler.*`, and `feed_forward.router.*`. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.
**MXFP8 variant**
- `_muse_spark_816b_dist_moe_bf16_spmd` is renamed to `_muse_spark_816b_dist_moe_spmd` and takes `expert_precision`. With `"mxfp8"`, the routed experts use MXFP8 Dist-MoE, and an `MXFP8LinearTransform` quantizes the attention and compressed-MoE (pooler/unpooler) projections, as in `muse_spark_debugmodel_dist_moe_mxfp8`.
- `_with_dist_moe` passes `BlockScaledConfig(fast_math=True)` for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.
- A comment on the 64-GPU recipe's TP1 records why MXFP8 recipes avoid TP.
- The MXFP8 linear policy moves from the test recipes into `torchtitan_recipes/models/muse_spark.py`, so both recipes share it (mechanical).
- The checkpoint folder name includes the expert precision.
- New recipes: `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64` and `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake`.
- The README recipe table lists the MXFP8 recipe.
## Numerics
- Saving instead of recomputing gives the same values. Muse Spark debug model with Dist-MoE, DP2 x CP2 x EP4 on 4 GPUs, vocab over CP, seed 42, deterministic, CUDA graphs, 10 steps: loss and grad_norm are bitwise equal with and without the three regions (step 10: 5.082653522491455 / 1.653401494026184). The log shows the pooler, unpooler, and router gate linears switch from recompute to saved.
- BF16 vs MXFP8, 100 real steps: loss at steps 1 / 50 / 100 is 12.2323 / 3.8930 / 2.9158 vs 12.2316 / 3.8928 / 2.9195. No long loss comparison was run.
- `fast_math=True` vs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.
## Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.
- Save regions (BF16): 2,219.2 -> 2,245.5 tps (+1.2%), 246.55 / 254.40 -> 252.41 / 260.40 GiB. NVML peak 260.01 -> 266.01 GiB.
- BF16 -> MXFP8 (both with the new save regions): 2,245.5 -> 2,525.3 tps (+12.5%), 252.41 / 260.40 -> 259.05 / 266.44 GiB. NVML peak 266.01 -> 272.66 GiB. Of this, `fast_math=True` alone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).
- Logical 64-GPU FakePG run (rank 0): save regions 3,662.9 -> 3,746.1 tps (+2.3%); BF16 -> MXFP8 3,746.1 -> 4,165.3 tps (+11.2%).
The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
## Testing
- `test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projections` builds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.
- `pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark` (with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.
## Known issues / follow-ups
- Needs dist_moe at or after meta-pytorch/dist_moe@b76e0e0 ("Fix MXFP8 callback postprocess with padded routes"). Before it, the padded-row zeroing that Muse uses raises in the MXFP8 expert postprocess. CI installs dist_moe from main, which includes the fix.
- The lm_head stays BF16. `MuseSparkLMHead` has an fp32 output, an output multiplier, and a tanh soft cap, and `MXFP8LinearTransform` only converts plain `Linear` configs.
- The Dist-MoE MXFP8 scratch could share memory by buffer lifetime, as the BF16 formula does, which would return about 5.6 GiB. That change belongs in Dist-MoE.
stack-info: PR: #6135, branch: fegin/stack/42
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked PRs:
[muse_spark] Save more outputs in the 64-GPU recipe and add an MXFP8 variant
Summary (human-written)
As the title says, with vocab over CP, we can perform less remat thanks to
the memory saving (+1.2%).
We also add an MXFP8 variant of this recipe. Since the recipe uses TP1,
MXFP8 doesn't expose any TP communication, and it gives +12.5% over BF16.
Why
Save more outputs. The 64-GPU recipe recomputes everything outside attention and the Dist-MoE experts in backward, including the compressed-MoE projections (pooler, unpooler) and the router gate. Sharding the vocab over CP (the parent commit) frees about 11 GiB at the step-1 peak, so the recipe can keep these outputs and skip their recompute.
MXFP8. The 816B scale recipes are BF16 only. The comment gave two reasons: inner attention and the LM head stay BF16, and TorchTitan has no asynchronous MXFP8 TP path, so MXFP8 with TP exposes TP communication. The 64-GPU recipe uses TP1, so the TP reason does not apply. Dist-MoE and the Muse debug recipe already support MXFP8.
Example.
What changed
Save regions
feed_forward.pooler.*,feed_forward.unpooler.*, andfeed_forward.router.*. The router pattern matches the gate linear inside the router; the router's top-k and aux loss are still recomputed.MXFP8 variant
_muse_spark_816b_dist_moe_bf16_spmdis renamed to_muse_spark_816b_dist_moe_spmdand takesexpert_precision. With"mxfp8", the routed experts use MXFP8 Dist-MoE, and anMXFP8LinearTransformquantizes the attention and compressed-MoE (pooler/unpooler) projections, as inmuse_spark_debugmodel_dist_moe_mxfp8._with_dist_moepassesBlockScaledConfig(fast_math=True)for MXFP8, as the DeepSeek-V3 MXFP8 Dist-MoE recipe does. The staged pipeline's fused clamped-SwiGLU (in the W2 combine and in backward) then uses an approximate exp and reciprocal in the sigmoid. This also applies to the MXFP8 debug recipe.torchtitan_recipes/models/muse_spark.py, so both recipes share it (mechanical).muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64andmuse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_fake.Numerics
fast_math=Truevs exact SwiGLU (A/B of the flag), 100 real steps: the loss difference has mean +0.00000 over all steps and max abs 0.0073 (0.24%, step 80), with no consistent sign.Performance
64 real GB300 GPUs, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks). Each step was measured separately, with the same harness. These runs used
max_num_documents=64. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.fast_math=Truealone is about +3% (A/B of the flag: +2.9% real, +2.5% FakePG, memory unchanged).The MXFP8 +6.6 GiB comes from Dist-MoE buffers allocated once at init, not from training memory. The MXFP8 backward scratch is 53.65 GiB vs 48.00 GiB for BF16, because the block-scaled size formula adds its buffers without overlapping them by lifetime. The activation slots are 63.04 vs 62.00 GiB, from the scale bytes and the 128-row expert padding. Saved activations and unshard buffers are the same within 0.1 GiB at the peak.
Testing
test_dist_moe_64_mxfp8_recipe_quantizes_experts_and_projectionsbuilds the MXFP8 fake recipe and checks the expert and projection config types and the fast-math flag. It catches FQN patterns that stop matching and the policy being dropped. It needs dist_moe, so it runs in the B200 lane, which installs dist_moe; this commit adds it to that lane's pytest list.pytest tests/unit_tests/cpu/recipes tests/unit_tests/cpu/models/muse_spark(with dist_moe installed): 77 passed, 13 skipped (Fused MLA needs CUDA), 3 xfailed. Both 64-GPU fake recipes build and pass validation.Known issues / follow-ups
MuseSparkLMHeadhas an fp32 output, an output multiplier, and a tanh soft cap, andMXFP8LinearTransformonly converts plainLinearconfigs.