Repository navigation
Conversation
0ec4d5a to
f6b1b4a
Compare
e90f5d2 to
70717aa
Compare
…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).
4c20187 to
9c04738
Compare
9c04738 to
4feec06
Compare
4feec06 to
3377d75
Compare
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP both ranks hold loss L of 8 tokens -> report L/2 so the DP x CP sum is L dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. The reported loss and sum metrics are divided by the CP degree, because every CP rank holds the loss of all CP tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the DeepSeek V3 and V4 `_apply_fsdp` overrides. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` for a CP-sharded lm_head, and rejects TP, PP, weight tying, and SPMD typechecking with CP vocab parallelism. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - No unit test covers the CP loss scaling, the hidden-state gradient reduce-scatter, or the DP-only FSDP reduction; the integration entry runs them end to end. - With CP vocab parallelism, the trainer's `max_loss` is the CP group's mean loss only when the CP ranks hold the same number of valid tokens. - Only `apply_fsdp_to_decoder` users get the DP-only placement. graph_trainer's simple FSDP does not read the CP placement and is not supported with CP vocab parallelism. - SPMD typechecking is rejected; the loss path uses untyped funcol collectives. stack-info: PR: pytorch/torchtitan#6134, branch: fegin/stack/41
099f62c to
de9eb08
Compare
29f9c53 to
2ed594a
Compare
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.
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP both ranks hold loss L of 8 tokens -> report L/2 so the DP x CP sum is L dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. The reported loss and sum metrics are divided by the CP degree, because every CP rank holds the loss of all CP tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the DeepSeek V3 and V4 `_apply_fsdp` overrides. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` for a CP-sharded lm_head, and rejects TP, PP, weight tying, and SPMD typechecking with CP vocab parallelism. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - No unit test covers the CP loss scaling, the hidden-state gradient reduce-scatter, or the DP-only FSDP reduction; the integration entry runs them end to end. - With CP vocab parallelism, the trainer's `max_loss` is the CP group's mean loss only when the CP ranks hold the same number of valid tokens. - Only `apply_fsdp_to_decoder` users get the DP-only placement. graph_trainer's simple FSDP does not read the CP placement and is not supported with CP vocab parallelism. - SPMD typechecking is rejected; the loss path uses untyped funcol collectives. stack-info: PR: #6134, branch: fegin/stack/41
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP both ranks hold loss L of 8 tokens -> report L/2 so the DP x CP sum is L dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. The reported loss and sum metrics are divided by the CP degree, because every CP rank holds the loss of all CP tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the DeepSeek V3 and V4 `_apply_fsdp` overrides. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` for a CP-sharded lm_head, and rejects TP, PP, weight tying, and SPMD typechecking with CP vocab parallelism. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - No unit test covers the CP loss scaling, the hidden-state gradient reduce-scatter, or the DP-only FSDP reduction; the integration entry runs them end to end. - With CP vocab parallelism, the trainer's `max_loss` is the CP group's mean loss only when the CP ranks hold the same number of valid tokens. - Only `apply_fsdp_to_decoder` users get the DP-only placement. graph_trainer's simple FSDP does not read the CP placement and is not supported with CP vocab parallelism. - SPMD typechecking is rejected; the loss path uses untyped funcol collectives. stack-info: PR: #6134, branch: fegin/stack/41
|
@claude review my PR |
There was a problem hiding this comment.
Verdict: Request changes -- the design is sound and the memory and throughput gains are measured, but global_max_loss reports a wrong value under CP vocab parallelism, and no test guards the new loss and gradient scaling.
What this PR does. With CP, each CP rank can now own a V/cp slice of the token embedding and lm_head, the way TP shards the vocab. The embedding all-gathers token IDs over CP, looks up its own vocab slice, and reduce-scatters the result. ChunkedLossWrapper all-gathers hidden states and labels over CP and runs vocab-parallel CE over the CP group. It reports loss / cp and reduce-scatters the hidden-state gradient. FSDP shards and reduces those two weights over DP only. The final norm gets its own FSDP unit, so fsdp_partial_backwards now restores the outer groups' grad_dtype.
Example. DP1 x CP2, 4 local tokens per rank, rank0 has 4 valid labels, rank1 has 2:
main: rank0 avg = L0/4, rank1 avg = L1/2; global_max_loss = max(L0/4, L1/2)
this PR: both ranks hold L0+L1; accumulated_loss = (L0+L1)/(2*6)
trainer: local_avg = accumulated * 6 / local_count
rank0 -> (L0+L1)/8, rank1 -> (L0+L1)/4 -> max = (L0+L1)/4
(neither a per-rank mean nor the CP-group mean (L0+L1)/6)
global_avg_loss stays correct: sum = (L0+L1)/6.
Must fix
torchtitan/components/loss.py:1035--global_max_lossis wrong when the CP ranks have different valid-token counts. Fix: report this rank's own-token loss instead of/ cp_size(inline).tests/integration_tests/features.py:1055-- nothing catches a break in the CP loss scaling, the hidden-gradient reduce-scatter, or the DP-only FSDP reduction. Add a 2-rank gloo comparison against a full-vocab reference intest_chunked_loss_fsdp.py(inline).
Should consider
torchtitan/distributed/fsdp.py:477-- #6253 (open, JavaZeroo) also splits[norm, lm_head]into separate FSDP units, for all chunked-loss training. Once split, every chunk backward runs FSDP's root final callback. That is the reason this PR needs thegrad_dtyperestore, and #6253 doesn't include it. Coordinate: land the split and the restore together, then keep only the DP-only mesh choice here. #6454 and #5946 also rewritefsdp_lifecycle.py.torchtitan/components/loss.py:767-- usespmd.redistribute, as the embedding does, instead of two funcol helpers (inline).torchtitan/components/loss.py:849-- reads the private_sharding_configfromloss.pyandfsdp.py, and thevocab_on_cpattribute should be private (inline).torchtitan/config/validation.py:298-- checkglobal_vocab_sizeat config time (inline).- The PR says graph_trainer's simple FSDP is unsupported, but nothing raises. Embedding-only CP vocab doesn't need
ChunkedLossWrapper, so it passes validation, and simple FSDP would then reduce a CP-sharded weight over DP x CP. AValueErrorin graph_trainer's config validation would make that explicit (unverified how simple FSDP behaves).
Details
Gate. The problem is real: full-vocab weights and fp32 gradients sit on every CP rank at peak memory. The fix is in the right layer (sharding configs, the loss wrapper, FSDP placement). The value is measured on 64 GB300 GPUs: -11.3 GiB peak, +1.9% tps. No PyTorch dependency is added. The grad_dtype workaround has a TODO linking pytorch/pytorch#203176.
Why the grad_dtype restore is needed only with a split head. With the grouped [norm, lm_head] unit, calling only lm_head in the loss never completes the group's forward. No pre-backward hook is registered on the logits, so inner backwards don't run the root final callback. With lm_head as its own unit, each chunk forward completes the group, and each chunk backward resets every group's grad_dtype. So main is not affected, and this belongs in this PR (or with #6253).
Gradient correctness, by reasoning. The lm_head slice gradient on each CP rank is d(L_group/N_global)/dW_r. Summing it over DP gives the full gradient, because FSDP gradient division is disabled and the loss is normalized by the global token count. The hidden-gradient partials over vocab slices, reduce-scattered over CP, give the local dh. The norm still reduces over DP x CP. The eval path (Validator reuses engine.loss_fn) also gets /cp, and its later sum over the loss mesh is correct.
Overlap search. vocab parallel, ChunkedLossWrapper, fsdp_lifecycle grad_dtype. Found #6253 (norm/head split), #6454 and #5946 (fsdp_lifecycle.py), and #5707 (chunked loss only on loss tokens, which would also touch the CP gather).
Not verified: GPU runs and DCP resume (taken from the description); graph_trainer's behavior with a CP-sharded embedding.
A maintainer still needs to review: the PR touches core (loss.py, fsdp.py, fsdp_lifecycle.py, validation.py).
| cp_size = cp_group.size() | ||
| total_loss = total_loss / cp_size |
There was a problem hiding this comment.
Must fix. After this division loss_metrics/global_max_loss gives a wrong number whenever the CP ranks hold different numbers of valid tokens. That happens with any IGNORE_INDEX labels (document ends, padding). trainer.py:453 computes accumulated_loss * global_count / local_count. Here accumulated_loss is L_group / (cp * N_global), so the trainer reports L_group / (cp * local_count). That is neither this rank's mean (what main reports) nor the CP group's mean. Nothing raises; the code comment only describes the problem.
Per-microbatch reweighting can't fix this exactly under gradient accumulation, because the trainer's local_count is summed over the whole step. A fix that keeps main's meaning: report this rank's own-token loss. Compute per-token CE (reduction="none") on the gathered chunk, .sum() it for the chunk backward, and add only the entries in [cp_rank * T, (cp_rank + 1) * T) into total_loss. Then total_loss matches main with no / cp_size, and global_avg_loss and global_max_loss keep their meaning. The /mean metrics can keep the / cp_size scaling. If you would rather not do this, the PR needs to say why the changed meaning of global_max_loss is acceptable.
| IntegrationTestDefinition( | ||
| configs=[llama3_debugmodel_fsdp2_cp2], | ||
| test_descr="FSDP+CP", | ||
| configs=[llama3_debugmodel_fsdp2_cp2_vocab], |
There was a problem hiding this comment.
Must fix. This entry only checks that training runs. The three invariants this PR adds can break without any error: the / cp_size loss scaling, the reduce-scatter of the hidden-state gradient, and the DP-only FSDP reduction of the CP-sharded weights. If you drop the scaling, or shard the lm_head over (dp_shard, cp), this still passes. The PR's "Known issues" says no test covers them.
The cheapest guard is a 2-rank gloo case in tests/unit_tests/cpu/components/test_chunked_loss_fsdp.py, which already has the DTensorTestBase harness. Use a CP group of 2 with a vocab-sharded lm_head. Compare the summed loss, the hidden-state gradient, and the full lm_head gradient (concatenated over CP) against a 1-rank full-vocab reference on the same tokens. That is about 40 lines and needs no GPU.
| def _cp_all_gather(tensor: torch.Tensor, group: dist.ProcessGroup) -> torch.Tensor: | ||
| return funcol.wait_tensor( | ||
| funcol.all_gather_tensor(tensor.contiguous(), gather_dim=0, group=group) | ||
| ) | ||
|
|
||
|
|
||
| def _cp_reduce_scatter(tensor: torch.Tensor, group: dist.ProcessGroup) -> torch.Tensor: | ||
| return funcol.wait_tensor( | ||
| funcol.reduce_scatter_tensor(tensor, "sum", scatter_dim=0, group=group) | ||
| ) | ||
|
|
There was a problem hiding this comment.
Should consider: the embedding does the same CP all-gather and reduce-scatter with spmd.redistribute(..., src=spmd.S(0), dst=spmd.R) and src=spmd.P, dst=spmd.S(0) (embedding.py:764-772). Here the PR adds two single-purpose funcol wrappers for the same operations. Calling spmd.redistribute inline at both call sites deletes these helpers, gives one way to do it, and leaves less to change for the typechecking TODO in validation.py.
| self.vocab_on_cp = isinstance(lm_head, Module) and vocab_sharded_on_cp( | ||
| lm_head._sharding_config |
There was a problem hiding this comment.
Should consider: Module._sharding_config is private. Until now only module.py itself and the HF/vLLM adapters (which set it) touch it. This PR reads it from loss.py here and from fsdp.py:446,479. Either add a public read-only accessor on Module, or have vocab_sharded_on_cp take the module so the private read lives next to the class. Also, vocab_on_cp is only used inside this class, so name it _vocab_on_cp.
| if lm_head_on_cp and not ( | ||
| isinstance(loss, ChunkedLossWrapper.Config) | ||
| and isinstance(loss.loss_fn, CrossEntropyLoss.Config) | ||
| ): | ||
| raise ValueError( | ||
| "An lm_head with CP-sharded vocab requires ChunkedLossWrapper with " | ||
| "CrossEntropyLoss." | ||
| ) |
There was a problem hiding this comment.
Should consider: without global_vocab_size, the CP path only raises at the first loss call (cross_entropy_loss, "global_vocab_size is required..."). This check already reads the inner loss config, so it can also catch that at config time:
| if lm_head_on_cp and not ( | |
| isinstance(loss, ChunkedLossWrapper.Config) | |
| and isinstance(loss.loss_fn, CrossEntropyLoss.Config) | |
| ): | |
| raise ValueError( | |
| "An lm_head with CP-sharded vocab requires ChunkedLossWrapper with " | |
| "CrossEntropyLoss." | |
| ) | |
| if lm_head_on_cp and not ( | |
| isinstance(loss, ChunkedLossWrapper.Config) | |
| and isinstance(loss.loss_fn, CrossEntropyLoss.Config) | |
| and loss.loss_fn.global_vocab_size is not None | |
| ): | |
| raise ValueError( | |
| "An lm_head with CP-sharded vocab requires ChunkedLossWrapper with " | |
| "CrossEntropyLoss and global_vocab_size set." | |
| ) |
…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).
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP both ranks hold loss L of 8 tokens -> report L/2 so the DP x CP sum is L dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. The reported loss and sum metrics are divided by the CP degree, because every CP rank holds the loss of all CP tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the DeepSeek V3 and V4 `_apply_fsdp` overrides. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` for a CP-sharded lm_head, and rejects TP, PP, weight tying, and SPMD typechecking with CP vocab parallelism. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - No unit test covers the CP loss scaling, the hidden-state gradient reduce-scatter, or the DP-only FSDP reduction; the integration entry runs them end to end. - With CP vocab parallelism, the trainer's `max_loss` is the CP group's mean loss only when the CP ranks hold the same number of valid tokens. - Only `apply_fsdp_to_decoder` users get the DP-only placement. graph_trainer's simple FSDP does not read the CP placement and is not supported with CP vocab parallelism. - SPMD typechecking is rejected; the loss path uses untyped funcol collectives. stack-info: PR: #6134, branch: fegin/stack/41
#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).
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP backward on the loss of all 8 tokens; each rank reports the loss of its own 4 dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. Each chunk backward uses the loss of all gathered tokens, so every vocab slice gets its full gradient. The reported loss and metrics sum only this rank's own tokens, so `global_avg_loss`, `global_max_loss`, `ce_loss/mean`, and `z_loss/mean` mean the same as without CP vocab parallelism, also when the CP ranks hold different numbers of valid tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `CrossEntropyLoss` takes `reduction="none"` to return the loss and metrics per token, with or without z-loss. `cross_entropy_and_logsumexp` takes the same `reduction`; the vocab-parallel kernel already returned per-token values. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the DeepSeek V3 and V4 `_apply_fsdp` overrides. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` and `global_vocab_size` for a CP-sharded lm_head, and rejects TP, PP, and weight tying with CP vocab parallelism. GraphTrainer rejects CP vocab parallelism: its SimpleFSDP would reduce the CP-sharded weights over DP x CP. - `Module.sharding_config` is a public read-only property, so `fsdp.py` and `loss.py` do not read the private `_sharding_config`. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. llama3 debug model, CP2 with CP vocab on 2 GPUs, seed 42, deterministic, 10 steps, against the previous version of this PR: grad_norm is bitwise equal at every step, so the gradients are unchanged. `global_avg_loss` differs in the last bits (summation order). `global_max_loss` changes: it now matches the same config without CP vocab (4.06188 vs 4.06188 at step 1, within 1e-4 later), while the previous version reported 4.058. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP and runs with SPMD typechecking on. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - `test_chunked_loss_fsdp.py`, 2-rank gloo, CP2 with a vocab-sharded lm_head, with and without z-loss, ranks with different valid-token counts: each rank's loss, the hidden-state gradient, and the lm_head gradient slice match a full-vocab reference. It fails with the previous `loss / cp` reporting. - `test_fsdp.py`: `apply_fsdp_to_decoder` shards the CP-sharded embedding and lm_head over DP only, and the norm over DP x CP. It fails if the lm_head gets the DP x CP config. - SPMD typechecking, 2 GPUs, Ulysses CP2 with CP vocab, 10 steps: loss, max loss, and grad_norm are bitwise equal with typechecking on and off. With the vocab embedding lookup outside `spmd.local_map`, the typed FSDP2 x CP2 run fails. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - Only `apply_fsdp_to_decoder` users get the DP-only placement. GraphTrainer raises for CP vocab parallelism. stack-info: PR: #6134, branch: fegin/stack/41
|
[CLAUDE on behalf of fegin] @claude re-review this PR |
There was a problem hiding this comment.
Verdict: Approve -- both earlier must-fix items are resolved and I found no new must-fix problems. This approval lifts my earlier REQUEST_CHANGES.
What this PR does. With CP, each CP rank can now own a V/cp slice of the token embedding and lm_head. The embedding all-gathers token IDs over CP, looks up its slice, and reduce-scatters the output. ChunkedLossWrapper all-gathers hidden states and labels over CP and runs per-token vocab-parallel CE over the CP group. It backpropagates the loss of all gathered tokens but reports only this rank's own tokens, then reduce-scatters the hidden-state gradient. FSDP reduces the two CP-sharded weights over DP only.
Example. DP1 x CP2, 4 local tokens per rank; rank0 has 4 valid labels, rank1 has 2:
previous rev: both ranks report (L0+L1)/(2*6); max_loss = (L0+L1)/4 (wrong)
HEAD: chunk backward uses sum over all 8 tokens / 6
rank0 reports L0/6, rank1 reports L1/6
global_avg_loss = (L0+L1)/6, global_max_loss = max(L0/4, L1/2) (same as without CP vocab)
Earlier must-fix items
loss.pyglobal_max_lossunder uneven valid-token counts: resolved. The wrapper now reports own-token sums (reduction="none"plus theown_token_chunksmask), with no/ cp_size.- No guard for CP loss scaling, hidden-gradient reduce-scatter, or DP-only reduction: resolved.
TestChunkedLossCPVocabParallelcompares against a full-vocab reference with uneven valid-token counts, with and without z-loss.test_apply_fsdp_to_decoder_reduces_cp_sharded_vocab_over_dp_onlychecks the FSDP axes.
Earlier should-consider items: the inline spmd.redistribute calls, the public Module.sharding_config, _vocab_on_cp, the global_vocab_size check at config time, and the GraphTrainer ValueError are all done. Still open: coordination with #6253 (open), which splits [norm, lm_head] without the grad_dtype restore. Whichever lands second must keep the restore in fsdp_lifecycle.py.
Should consider
- The description says the DP-only placement covers "the DeepSeek V3 and V4
_apply_fsdpoverrides". Neither model has one. The path they take isMTPDecoder._apply_fsdp(torchtitan/models/common/mtp.py:144), which delegates toDecoder._apply_fsdp. Reword it.
Questions
torchtitan/distributed/fsdp.py:666: with explicit prefetching (EP > 1 orunshard_in_current_stream, which includes the Muse Spark recipe), the lm_head backward prefetch now fires in the first chunk backward.is_last_backward=Falsekeeps that prefetch, so the last block stays unsharded through every remaining loss chunk. The measured step-1 peak already includes this. Did you compare it against prefetching the last block frommodel.norm, which now runs its backward in the outer backward?
Details
Re-checked at HEAD. resolve_fsdp_mesh keeps replicate, so replace(dp_mesh_dims, shard="dp_shard") gives HSDP and DDP+CP (dp_shard=1) the same DP-only placement. Every in-tree decoder _apply_fsdp (MTP, multimodal, qwen3_8_flash_next) ends in apply_fsdp_to_decoder. The no-grad and frozen-decoder paths return own-token total_loss, and the head gets its full slice gradient from chunk_loss.sum(). The own-token masking sums every metric. That is right for the /mean keys CrossEntropyLoss emits, and validation requires CrossEntropyLoss. No added line has a hidden sync or non-ASCII text.
Overlap search. vocab parallel, fsdp_lifecycle, ChunkedLossWrapper. Found: #6253 (norm/head split); #6454 and #5946 (fsdp_lifecycle.py); #5707 (lm_head only on loss tokens, which would need to select loss tokens after the CP gather); #6014 and #6011 (FlexShard TP/CP and chunked loss). When FlexShard storage lands, it will need the same DP-only placement, or it must reject CP vocab.
Not verified: GPU runs, DCP resume, and the 64-GPU numbers (taken from the description).
A maintainer still needs to review: the PR touches core (loss.py, fsdp.py, fsdp_lifecycle.py, validation.py, module.py).
Before merge: fill in the human-written summary.
## Summary (human-written) Why CP uses more memory than TP? The main reason is the `lm_head`. For each layer, FSDP2 gathers the full weights and in the backward also calculates the full gradients. This memory is usually not a problem as long as we turn on `reshard_after_forward`. But for `lm_head`, which happens at the memory usage peak, these fully-gathered tensors become extra memory usage on top of the accumulated memory usage. With TP or vocabulary parallelism, the vocabulary dimension is sharded. So the fully-gathered tensors (weights and gradients) are TP-degree smaller. On the other hand, CP doesn't shard on any of the weight dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming CP degree is 8 and TP degree is also 8). This PR introduces a new way to do CP by doing vocabulary parallelism over CP dimension for embedding and lm_head, and turns it on in the Muse Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less at the step-1 peak) but also improves the performance (+1.9%), as we only need to all-gather 1/CP-degree of the weight. ## Why With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size. **Example.** CP2, 4 local tokens per rank, vocab 8: ```text embedding: rank0 rows 0..3, rank1 rows 4..7 all-gather ids -> both see t0..t7; look up own rows; reduce-scatter -> [4, D] local loss: all-gather h -> [8, D]; logits [8, V/2]; vocab-parallel CE over CP backward on the loss of all 8 tokens; each rank reports the loss of its own 4 dh [8, D] partial -> reduce-scatter -> [4, D] ``` ## What changed - `cp_vocab_parallel_token_embedding_sharding_config`: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back. `VocabParallelEmbedding.forward` runs these collectives when its sharding config shards the weight over CP; the TP path is unchanged. - `cp_vocab_parallel_lm_head_sharding_config`: `ChunkedLossWrapper` reads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. Each chunk backward uses the loss of all gathered tokens, so every vocab slice gets its full gradient. The reported loss and metrics sum only this rank's own tokens, so `global_avg_loss`, `global_max_loss`, `ce_loss/mean`, and `z_loss/mean` mean the same as without CP vocab parallelism, also when the CP ranks hold different numbers of valid tokens. `loss_inputs` are not gathered, because the required `CrossEntropyLoss` ignores them. - `CrossEntropyLoss` takes `reduction="none"` to return the loss and metrics per token, with or without z-loss. `cross_entropy_and_logsumexp` takes the same `reduction`; the vocab-parallel kernel already returned per-token values. - `apply_fsdp_to_decoder` shards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the MTP, multimodal, and Qwen3.8 Flash-Next `_apply_fsdp` overrides, which all end in it. The final norm gets its own FSDP unit. - Config validation requires `ChunkedLossWrapper` with `CrossEntropyLoss` and `global_vocab_size` for a CP-sharded lm_head, and rejects TP, PP, and weight tying with CP vocab parallelism. GraphTrainer rejects CP vocab parallelism: its SimpleFSDP would reduce the CP-sharded weights over DP x CP. - `Module.sharding_config` is a public read-only property, so `fsdp.py` and `loss.py` do not read the private `_sharding_config`. - `apply_fsdp_to_decoder` raises if a CP-sharded `tok_embeddings` holds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight. - The Muse Spark 64-GPU recipe (`_muse_spark_816b_dist_moe_bf16_spmd_64`) uses both sharding configs. - `fsdp_partial_backwards` restores the `grad_dtype` of the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer's `grad_dtype` to fp32. The layers' weight gradients would then be written and copied in fp32. ## Numerics The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%. llama3 debug model, CP2 with CP vocab on 2 GPUs, seed 42, deterministic, 10 steps, against the previous version of this PR: grad_norm is bitwise equal at every step, so the gradients are unchanged. `global_avg_loss` differs in the last bits (summation order). `global_max_loss` changes: it now matches the same config without CP vocab (4.06188 vs 4.06188 at step 1, within 1e-4 later), while the previous version reported 4.058. ## Performance Additional collectives over CP per microbatch: - Embedding forward: all-gather of the token IDs and reduce-scatter of the output. Embedding backward: all-gather of the output gradient. - Loss: all-gather of the hidden states and the labels, the vocab-parallel cross-entropy all-reduces (max, sum of exp, target logit) for each loss chunk, and reduce-scatter of the hidden-state gradient. Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch. Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks): - 64 real GB300 GPUs: 2,178.8 -> 2,219.2 tps (+1.9%), 257.81 / 268.66 -> 246.55 / 254.40 GiB. - Logical 64-GPU FakePG run (rank 0): 3,654.7 -> 3,662.9 tps, 257.81 / 268.66 -> 246.55 / 254.40 GiB. The `grad_dtype` restore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise. ## Testing - Integration test: the `fsdp+cp` entry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP and runs with SPMD typechecking on. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects. - CPU: config validation, FSDP, loss, common model, DeepSeek V3/V4, and Muse Spark recipe tests. - DCP save and resume, llama3 debug model, DP2 x CP2 with CP vocab, seed 42, deterministic, checkpoint at step 5: steps 6-10 are bitwise equal to the uninterrupted run (resuming without the optimizer state differs from step 7). The checkpoint stores the embedding and lm_head weights and moments with the global [vocab, dim] shape; the vocab is split over CP first and each CP slice over DP. - `test_chunked_loss_fsdp.py` checks that the chunk backwards keep the decoder's `grad_dtype` with bf16 mixed precision and a separate lm_head unit. It fails without the restore. - `test_chunked_loss_fsdp.py`, 2-rank gloo, CP2 with a vocab-sharded lm_head, with and without z-loss, ranks with different valid-token counts: each rank's loss, the hidden-state gradient, and the lm_head gradient slice match a full-vocab reference. It fails with the previous `loss / cp` reporting. - `test_fsdp.py`: `apply_fsdp_to_decoder` shards the CP-sharded embedding and lm_head over DP only, and the norm over DP x CP. It fails if the lm_head gets the DP x CP config. - SPMD typechecking, 2 GPUs, Ulysses CP2 with CP vocab, 10 steps: loss, max loss, and grad_norm are bitwise equal with typechecking on and off. With the vocab embedding lookup outside `spmd.local_map`, the typed FSDP2 x CP2 run fails. - The 64-GPU fake recipe builds and passes validation. ## Known issues / follow-ups - Only `apply_fsdp_to_decoder` users get the DP-only placement. GraphTrainer raises for CP vocab parallelism. stack-info: PR: #6134, branch: fegin/stack/41
Stacked PRs:
[cp] Shard the token embedding and lm_head vocab over CP
Summary (human-written)
Why CP uses more memory than TP? The main reason is the
lm_head. Foreach layer, FSDP2 gathers the full weights and in the backward also
calculates the full gradients. This memory is usually not a problem as
long as we turn on
reshard_after_forward. But forlm_head, whichhappens at the memory usage peak, these fully-gathered tensors become
extra memory usage on top of the accumulated memory usage.
With TP or vocabulary parallelism, the vocabulary dimension is sharded.
So the fully-gathered tensors (weights and gradients) are TP-degree
smaller. On the other hand, CP doesn't shard on any of the weight
dimension. So for the lm_head, CP uses ~8x more memory than TP (assuming
CP degree is 8 and TP degree is also 8).
This PR introduces a new way to do CP by doing vocabulary parallelism
over CP dimension for embedding and lm_head, and turns it on in the Muse
Spark 64-GPU recipe. This not only reduces the memory usage (11.3 GiB less
at the step-1 peak) but also improves the performance (+1.9%), as we only
need to all-gather 1/CP-degree of the weight.
Why
With CP, every CP rank all-gathers the full-vocab token embedding and lm_head weights and builds their full fp32 gradients plus the FSDP reduce-scatter copies. For a 202K x 8K vocab this is about 15 GiB of transient memory per rank (in the Muse Spark 64-GPU recipe, an 11.3 GiB drop in step-1 peak allocated memory and 14.3 GiB in reserved memory). Sharding the vocab over CP, as TP already does, makes these 1/cp the size.
Example. CP2, 4 local tokens per rank, vocab 8:
What changed
cp_vocab_parallel_token_embedding_sharding_config: the weight is sharded over CP. Token IDs are all-gathered over CP, each rank looks up its vocab slice, and the CP-partial output is reduce-scattered back.VocabParallelEmbedding.forwardruns these collectives when its sharding config shards the weight over CP; the TP path is unchanged.cp_vocab_parallel_lm_head_sharding_config:ChunkedLossWrapperreads the lm_head's sharding config, so the lm_head layout alone turns this on. The wrapper all-gathers hidden states and labels over CP, runs the vocab-parallel CE with the CP group, and reduce-scatters the hidden-state gradient. Each chunk backward uses the loss of all gathered tokens, so every vocab slice gets its full gradient. The reported loss and metrics sum only this rank's own tokens, soglobal_avg_loss,global_max_loss,ce_loss/mean, andz_loss/meanmean the same as without CP vocab parallelism, also when the CP ranks hold different numbers of valid tokens.loss_inputsare not gathered, because the requiredCrossEntropyLossignores them.CrossEntropyLosstakesreduction="none"to return the loss and metrics per token, with or without z-loss.cross_entropy_and_logsumexptakes the samereduction; the vocab-parallel kernel already returned per-token values.apply_fsdp_to_decodershards a CP-sharded embedding or lm_head over DP only, since each CP rank computes the full gradient of its vocab slice. It reads this from the modules' sharding configs, so every model that calls it gets the same placement, including the MTP, multimodal, and Qwen3.8 Flash-Next_apply_fsdpoverrides, which all end in it. The final norm gets its own FSDP unit.ChunkedLossWrapperwithCrossEntropyLossandglobal_vocab_sizefor a CP-sharded lm_head, and rejects TP, PP, and weight tying with CP vocab parallelism. GraphTrainer rejects CP vocab parallelism: its SimpleFSDP would reduce the CP-sharded weights over DP x CP.Module.sharding_configis a public read-only property, sofsdp.pyandloss.pydo not read the private_sharding_config.apply_fsdp_to_decoderraises if a CP-shardedtok_embeddingsholds a parameter other than an embedding weight, since FSDP would reduce it over DP only. This needs the built module: Muse Spark's embedding norm config exists but has no weight._muse_spark_816b_dist_moe_bf16_spmd_64) uses both sharding configs.fsdp_partial_backwardsrestores thegrad_dtypeof the FSDP groups outside the lm_head after the chunk backwards. With the lm_head as its own FSDP unit, each chunk backward runs FSDP's root final callback, which resets every layer'sgrad_dtypeto fp32. The layers' weight gradients would then be written and copied in fp32.Numerics
The embedding and lm_head gradients are reduced over DP only, and the loss sums vocab-parallel partial results over CP, so the reduction order changes. llama3 debug model, CP2 on 2 GPUs, seed 42, deterministic, 10 steps, against the same config without CP vocab: step-1 loss and grad_norm match; later losses differ by at most 1.3e-4 and grad_norm by at most 3e-4. Muse Spark debug model, DP2 x CP2 on 4 GPUs, loaded from one seed checkpoint: step-1 loss is identical and grad_norm differs by 7e-5 relative; over 30 steps loss stays within 0.3%.
llama3 debug model, CP2 with CP vocab on 2 GPUs, seed 42, deterministic, 10 steps, against the previous version of this PR: grad_norm is bitwise equal at every step, so the gradients are unchanged.
global_avg_lossdiffers in the last bits (summation order).global_max_losschanges: it now matches the same config without CP vocab (4.06188 vs 4.06188 at step 1, within 1e-4 later), while the previous version reported 4.058.Performance
Additional collectives over CP per microbatch:
Extra activation memory: the loss holds the CP-gathered hidden states and a CP-gathered hidden-state gradient accumulator, about 2 x cp x local tokens x dim elements per microbatch.
Muse Spark 64-GPU recipe, 100 steps from random init on c4_test, tps over steps 71-90, step-1 peak allocated / reserved (max over ranks):
The
grad_dtyperestore alone, FakePG with the same recipe: 3,495 -> 3,663 tps (+4.8%), with the layer backward 431 ms faster per step. Loss and grad_norm match within run-to-run noise.Testing
fsdp+cpentry (llama3 debug model, FSDP2 x CP2, 4 GPUs) now shards the vocab over CP and runs with SPMD typechecking on. It is an end-to-end run without a loss golden. The CP configs with goldens use TP or PP, which CP vocab parallelism rejects.test_chunked_loss_fsdp.pychecks that the chunk backwards keep the decoder'sgrad_dtypewith bf16 mixed precision and a separate lm_head unit. It fails without the restore.test_chunked_loss_fsdp.py, 2-rank gloo, CP2 with a vocab-sharded lm_head, with and without z-loss, ranks with different valid-token counts: each rank's loss, the hidden-state gradient, and the lm_head gradient slice match a full-vocab reference. It fails with the previousloss / cpreporting.test_fsdp.py:apply_fsdp_to_decodershards the CP-sharded embedding and lm_head over DP only, and the norm over DP x CP. It fails if the lm_head gets the DP x CP config.spmd.local_map, the typed FSDP2 x CP2 run fails.Known issues / follow-ups
apply_fsdp_to_decoderusers get the DP-only placement. GraphTrainer raises for CP vocab parallelism.