Repository navigation
Conversation
[ghstack-poisoned]
This was referenced Nov 19, 2026
Draft
anshul-si
added a commit
that referenced
this pull request
Nov 25, 2026
…ackend.Config() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardBackend.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `flex_shard_partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `flex_shard_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `flex_shard_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardBackend.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardBackend.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `flex_shard_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `fsdp_backend=FlexShardBackend.Config()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `flex_shard_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 751f488 Pull-Request: #6243
anshul-si
added a commit
that referenced
this pull request
Nov 25, 2026
…ackend.Config() Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardBackend.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `flex_shard_partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `flex_shard_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `flex_shard_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardBackend.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardBackend.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `flex_shard_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `fsdp_backend=FlexShardBackend.Config()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `flex_shard_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 751f488 Pull-Request: #6243
anshul-si
added a commit
that referenced
this pull request
Nov 30, 2026
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardConfig.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `FlexShardConfig._partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardConfig.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardConfig.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `storage=FlexShardConfig()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 78fc5a7 Pull-Request: #6243
anshul-si
added a commit
that referenced
this pull request
Nov 30, 2026
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR, the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description `FlexShardConfig.validate_model` rejects `pipeline_parallel_degree > 1`. Deleting the rejection alone would train differently from FSDP2: - **Pipeline schedules don't recognize FlexShard stages.** PyTorch's pipeline stages and schedules treat a stage module as data parallel only if it is an `FSDPModule`. They would never unshard a FlexShard stage ahead of its compute, defer its gradient reduction across microbatches, or finalize it at the end of the step. - **The chunked loss reduce-scatters every microbatch.** On the last stage, `FlexShardConfig._partial_backwards` turned `lm_head`'s bucket's gradient sync on for the last chunk of each microbatch, while the schedule keeps sync off until the end of the step. With the schedules fixed, Llama 3 debug under 1F1B at `pp=2, dp_shard=2` (8 microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4, and its loss leaves FSDP2's at step 6. - **ZBV loses the final norm's grad.** After the chunks, `_partial_backwards` resharded `lm_head`'s bucket, which also holds the final norm. A zero-bubble schedule's input pass then takes the sharded `norm.weight`, so its weight pass never computes that grad: with the other fixes, Llama 3 debug under ZBV at `pp=2` on 2 GPUs has a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2. - **Grads accumulate in bf16 across microbatches.** With bf16 parameters, FlexShard sums the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32. The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates a DTensor. - **PyTorch:** pytorch/pytorch#205659, "[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel" (not merged yet). Pipeline stages and schedules check for the six methods they call, which FlexShard modules have, instead of for `FSDPModule`. - **flex_shard** (not merged yet): - "Sum the grads of a module called more than once per backward as FSDP2 does", the fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync backwards in fp32. - "Run the end-of-backward pass for no-sync buckets under manual backward finalization, as FSDP2 does" does the same for the embedding. - "Add requires_gradient_sync and manual_backward_finalization getters to bucket storages". - **This PR:** - `_partial_backwards` reads the caller's gradient sync and whether backward finalization is manual through those getters. Under manual finalization, i.e. a pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after the chunks, as FSDP2's `fsdp_partial_backwards` leaves reductions and parameter residency to the schedule. Otherwise the last chunk takes the caller's setting, and the caller's settings are restored instead of set to True. That's no change today: validation rejects deferred gradient reduction, so sync is on outside. - `FlexShardConfig.validate_model` no longer rejects pipeline parallelism. It rejects it with a PyTorch whose pipelining lacks pytorch/pytorch#205659, which would neither defer nor finalize FlexShard's reductions (a TODO to drop the check once torchtitan's minimum PyTorch has it). `FlexShardConfig.validate_trainer` rejects `checkpointer.initial_load_in_hf` with pipeline parallelism: `load_hf_into_local_shards` groups and broadcasts over all ranks, which assumes every rank holds the same keys, and pipeline stages don't (a TODO, and a note at that assumption). - Accelerator graphs with pipeline parallelism stay allowed: they match FSDP2 bitwise (below). - The TODO on deferred gradient reduction now says what's left there: FSDP2's `fsdp_partial_backwards` leaves the last chunk's reduction to the outer backward when earlier microbatches kept grads. - `FLEX_SHARD_FSDP.md` lists pipeline parallelism as supported (with a PyTorch that has pytorch/pytorch#205659), replaces its rejection with the Hugging Face load's, and lists the new integration test. Before this lands, torchtitan's CI pin of flex_shard (`.github/scripts/install_flex_shard.sh`, `d6bb546`) has to move to a commit with the three flex_shard changes, and CI's PyTorch nightly has to include pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism with FlexShard. The new pin is needed without pipeline parallelism too: `_partial_backwards` now reads the getters for every chunked loss. **Tests.** - `test_config_validation.py` gains `test_flex_shard_pipeline_parallelism`: FlexShard with `pipeline_parallel_degree=2` is accepted when pipelining recognizes FlexShard modules and rejected when it doesn't (pytorch/pytorch#205659's helper removed), and a Hugging Face load with pipeline parallelism is rejected. The file passes (26). - `deepseek_v3_flex_shard+cp+pp+ep` in the models suite is a Real PG FlexShard twin of `deepseek_v3_fsdp+cp+pp+ep` (DeepSeek V3 debug, `dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`, 8 GPUs), as the integration-tests PR's twins are: the same config with `storage=FlexShardConfig()`, checked bitwise against the FSDP2 entry's golden, from the same seed checkpoint (`deepseek_v3_debugmodel`). ROCm skips it (`hardware_skips/skipped_tests.toml`), and release validation's `--exclude` list gains it. `test_integration_test_definitions.py` and `test_context_parallel_validation.py` pass (52 passed, 40 subtests). - No GPU unit parity test: `_check_matches_fsdp2` builds models with `model.parallelize` and runs its own microbatch loop, while a pipeline schedule owns the step, the loss and the reductions, so a pipeline case would need a second harness around `model.pipeline`. The twin and the runs below check pipeline parallelism end to end. - With the three flex_shard changes, `test_matches_fsdp2_with_tied_weights_and_chunked_loss` and `test_matches_fsdp2_with_tensor_parallelism`, whose chunked losses go through `_partial_backwards` without pipeline parallelism, pass on 2 GB200 GPUs with `world_size` set to 2. - flake8 and ufmt pass on the changed files. **FlexShard matches FSDP2.** All runs use torch with pytorch/pytorch#205659, flex_shard with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4 isn't installed on the test machine) and the recipes' `ChunkedLossWrapper`. Both backends load the same seed checkpoint, made without pipeline parallelism on one GPU. - On 2 GB200 GPUs at `pp=2`, `scripts/loss_compare.py --assert-equal --metrics loss,grad_norm` over 20 steps reports equal loss and grad norm at every step (step-20 loss and grad norm): | Config | Step 20 | | --- | --- | | Llama 3 debug, 1F1B | 3.11325 / 0.7644 | | Llama 3 debug, Interleaved1F1B | 3.11325 / 0.7644 | | Llama 3 debug, ZBV | 3.11323 / 0.7642 | | DeepSeek V3 debug, 1F1B | 3.13358 / 0.5802 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.11325 / 0.7644 | The graphs run records the forward-backward graph on both backends. At `dp_shard=1` no reduce-scatter runs, which the runs below add. - On 4 GB300 GPUs at `pp=2, dp_shard=2` (MAST), one training per backend for 20 steps, TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise identical at every step, and so is the load-balance loss for DeepSeek V3: | Config | Step 20 | | --- | --- | | Llama 3 debug, Interleaved1F1B | 3.14708 / 0.7182 | | DeepSeek V3 debug, `ep=2`, 1F1B | 3.18157 / 0.5915 | | DeepSeek V3 debug, `ep=2`, ZBV | 3.18201 / 0.6053 | | Llama 3 debug, Interleaved1F1B, accelerator graphs on | 3.14708 / 0.7182 | On 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (`dp_shard=2, cp=2, pp=2`, Interleaved1F1B, `ep=4`) are bitwise identical in the same scalars over 20 steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks pytorch/pytorch#205659. Its pipelining files are those of the PR's base, so the jobs loaded the PR's three changed files (`torch/distributed/pipelining/_utils.py`, `stage.py` and `schedules.py`) in their place through an import hook in `sitecustomize`, checked at startup. - The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in validation and the twin's definition were added. Their FlexShard and pipeline code is this commit's. - ZBV needs workarounds on both backends, so it's out of scope here: functorch's `donated_buffer=False`, since compiled flex attention's backward donates buffers that the split backward's `retain_graph` needs; full activation remat for Llama 3; and no remat for DeepSeek V3, whose default remat unpacks a saved input twice in the split backward and whose full remat's MoE routing placeholder fails. **FSDP2 is unchanged.** FSDP2's code doesn't change. `scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>` with FSDP2 on Llama 3 debug at `pp=2`, Interleaved1F1B, the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20 loss 3.13296, grad norm 0.7869). **Not covered:** deferred gradient reduction, with or without pipeline parallelism (it needs flex_shard's equivalent of FSDP2's `set_is_last_backward`); Hugging Face loads with pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan rejects for both backends. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 78fc5a7 Pull-Request: #6243
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.
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the checkpointing PR,
the Hugging Face load PR, the tensor- and context-parallelism PR, the DeepSeek V3 PR,
the accelerator-graphs PR, the integration-tests-and-docs PR, the EMA PR, the DistMuon
PR, the DeepSeek V3 DistMuon recipe PR and the DeepSeek V3 MTP PR.
Summary (human-written)
Description
FlexShardConfig.validate_modelrejectspipeline_parallel_degree > 1. Deleting therejection alone would train differently from FSDP2:
schedules treat a stage module as data parallel only if it is an
FSDPModule. Theywould never unshard a FlexShard stage ahead of its compute, defer its gradient
reduction across microbatches, or finalize it at the end of the step.
FlexShardConfig._partial_backwardsturnedlm_head's bucket's gradient sync on forthe last chunk of each microbatch, while the schedule keeps sync off until the end of
the step. With the schedules fixed, Llama 3 debug under 1F1B at
pp=2, dp_shard=2(8microbatches) runs 12 reduce-scatters per step on the last stage instead of FSDP2's 4,
and its loss leaves FSDP2's at step 6.
_partial_backwardsresharded
lm_head's bucket, which also holds the final norm. A zero-bubbleschedule's input pass then takes the sharded
norm.weight, so its weight pass nevercomputes that grad: with the other fixes, Llama 3 debug under ZBV at
pp=2on 2 GPUshas a step-1 grad norm of 1.4159 with FlexShard and 1.4189 with FSDP2.
the grads of no-sync backwards in bf16, where FSDP2 sums them in fp32.
The fixes are in three repositories. As in #5842, nothing on the FlexShard path creates
a DTensor.
methods as sharded data parallel" (not merged yet). Pipeline stages and schedules
check for the six methods they call, which FlexShard modules have, instead of for
FSDPModule.fix the DeepSeek V3 MTP PR needs, also sums the Linear weights' grads across no-sync
backwards in fp32.
finalization, as FSDP2 does" does the same for the embedding.
storages".
_partial_backwardsreads the caller's gradient sync and whether backwardfinalization is manual through those getters. Under manual finalization, i.e. a
pipeline schedule, every chunk keeps its grads and the bucket stays unsharded after
the chunks, as FSDP2's
fsdp_partial_backwardsleaves reductions and parameterresidency to the schedule. Otherwise the last chunk takes the caller's setting, and
the caller's settings are restored instead of set to True. That's no change today:
validation rejects deferred gradient reduction, so sync is on outside.
FlexShardConfig.validate_modelno longer rejects pipeline parallelism. It rejectsit with a PyTorch whose pipelining lacks [pipelining] Treat any module with FSDP2's stage methods as sharded data parallel pytorch#205659, which would neither
defer nor finalize FlexShard's reductions (a TODO to drop the check once
torchtitan's minimum PyTorch has it).
FlexShardConfig.validate_trainerrejectscheckpointer.initial_load_in_hfwith pipeline parallelism:load_hf_into_local_shardsgroups and broadcasts over all ranks, which assumesevery rank holds the same keys, and pipeline stages don't (a TODO, and a note at
that assumption).
(below).
fsdp_partial_backwardsleaves the last chunk's reduction to the outer backwardwhen earlier microbatches kept grads.
FLEX_SHARD_FSDP.mdlists pipeline parallelism as supported (with a PyTorch thathas [pipelining] Treat any module with FSDP2's stage methods as sharded data parallel pytorch#205659), replaces its rejection with the Hugging Face load's,
and lists the new integration test.
Before this lands, torchtitan's CI pin of flex_shard
(
.github/scripts/install_flex_shard.sh,d6bb546) has to move to a commit with thethree flex_shard changes, and CI's PyTorch nightly has to include
pytorch/pytorch#205659. Without that PyTorch, validation rejects pipeline parallelism
with FlexShard. The new pin is needed without pipeline parallelism too:
_partial_backwardsnow reads the getters for every chunked loss.Tests.
test_config_validation.pygainstest_flex_shard_pipeline_parallelism: FlexShardwith
pipeline_parallel_degree=2is accepted when pipelining recognizes FlexShardmodules and rejected when it doesn't ([pipelining] Treat any module with FSDP2's stage methods as sharded data parallel pytorch#205659's helper removed), and a
Hugging Face load with pipeline parallelism is rejected. The file passes (26).
deepseek_v3_flex_shard+cp+pp+epin the models suite is a Real PG FlexShard twin ofdeepseek_v3_fsdp+cp+pp+ep(DeepSeek V3 debug,dp_shard=2, cp=2, pp=2,Interleaved1F1B,
ep=4, 8 GPUs), as the integration-tests PR's twins are: the sameconfig with
storage=FlexShardConfig(), checked bitwise against theFSDP2 entry's golden, from the same seed checkpoint (
deepseek_v3_debugmodel). ROCmskips it (
hardware_skips/skipped_tests.toml), and release validation's--excludelist gains it.
test_integration_test_definitions.pyandtest_context_parallel_validation.pypass (52 passed, 40 subtests)._check_matches_fsdp2builds models withmodel.parallelizeand runs its own microbatch loop, while a pipeline schedule owns the step, the loss
and the reductions, so a pipeline case would need a second harness around
model.pipeline. The twin and the runs below check pipeline parallelism end to end.test_matches_fsdp2_with_tied_weights_and_chunked_lossandtest_matches_fsdp2_with_tensor_parallelism, whose chunked losses go through_partial_backwardswithout pipeline parallelism, pass on 2 GB200 GPUs withworld_sizeset to 2.FlexShard matches FSDP2. All runs use torch with pytorch/pytorch#205659, flex_shard
with the three changes, seed 42, deterministic, 8 microbatches, flex attention (FA4
isn't installed on the test machine) and the recipes'
ChunkedLossWrapper. Bothbackends load the same seed checkpoint, made without pipeline parallelism on one GPU.
On 2 GB200 GPUs at
pp=2,scripts/loss_compare.py --assert-equal --metrics loss,grad_normover 20 steps reports equal loss and grad norm at every step (step-20loss and grad norm):
The graphs run records the forward-backward graph on both backends. At
dp_shard=1no reduce-scatter runs, which the runs below add.
On 4 GB300 GPUs at
pp=2, dp_shard=2(MAST), one training per backend for 20 steps,TensorBoard scalars compared exactly: loss, max loss and grad norm are bitwise
identical at every step, and so is the load-balance loss for DeepSeek V3:
ep=2, 1F1Bep=2, ZBVOn 8 GB300 GPUs, the twin's config and its FSDP2 counterpart (
dp_shard=2, cp=2, pp=2, Interleaved1F1B,ep=4) are bitwise identical in the same scalars over 20steps (step-20 loss 3.18164, grad norm 0.6002). MAST's PyTorch build lacks
[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel pytorch#205659. Its pipelining files are those of the PR's base, so the jobs
loaded the PR's three changed files (
torch/distributed/pipelining/_utils.py,stage.pyandschedules.py) in their place through an import hook insitecustomize, checked at startup.The 2-GPU runs and the 4-GPU runs without graphs started before the PyTorch check in
validation and the twin's definition were added. Their FlexShard and pipeline code is
this commit's.
ZBV needs workarounds on both backends, so it's out of scope here: functorch's
donated_buffer=False, since compiled flex attention's backward donates buffers thatthe split backward's
retain_graphneeds; full activation remat for Llama 3; and noremat for DeepSeek V3, whose default remat unpacks a saved input twice in the split
backward and whose full remat's MoE routing placeholder fails.
FSDP2 is unchanged. FSDP2's code doesn't change.
scripts/loss_compare.py <the DeepSeek V3 MTP PR> <this PR>with FSDP2 on Llama 3 debug atpp=2, Interleaved1F1B,the chunked loss, 20 steps, without a seed checkpoint (both start from seed 42 with the
same parallelism), 2 GB200 GPUs, reports equal loss and grad norm at every step (step-20
loss 3.13296, grad norm 0.7869).
Not covered: deferred gradient reduction, with or without pipeline parallelism (it
needs flex_shard's equivalent of FSDP2's
set_is_last_backward); Hugging Face loadswith pipeline parallelism; and MTP layers with pipeline parallelism, which torchtitan
rejects for both backends.
Co-authored-by: Wei Feng [email protected]