Repository navigation
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/205659
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 2 Cancelled JobsAs of commit d1ddae3 with merge base a66bab0 ( NEW FAILURE - The following job has failed:
CANCELLED JOBS - The following jobs were cancelled. Please retry:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
anshul-si
added a commit
to pytorch/torchtitan
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
to pytorch/torchtitan
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
to pytorch/torchtitan
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
to pytorch/torchtitan
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):
Pipeline stages and schedules recognize a data parallel stage module only by
its class, with
isinstance(module, FSDPModule)in 14 places. A stage modulefrom another library that shards its parameters the same way and has the same
methods, such as FlexShard (meta-pytorch/flex_shard), is treated as a plain
module: the schedule never unshards it ahead of its stage's compute, never
defers its gradient reduction across microbatches, and never finalizes it at
the end of the step. Using such a module with
torch.distributed.pipeliningtoday means patching
FSDPModulein the stage and schedules modules.This PR checks for the methods instead. A new private runtime-checkable
protocol,
_ShardedDataParallelModule, lists the six methods that stages andschedules call:
set_manual_backward_finalization,set_requires_gradient_sync,set_reshard_after_backward,finalize_backward(async_op=...),unshard(async_op=...)andreshard._is_sharded_data_parallel(module)replaces the 14 checks instage.pyandschedules.py.FSDPModulehas all six methods, so FSDP2 stages behave asbefore. The check calls
issubclasson the module's type, which caches itsresult per class, so checking every submodule of a stage on each UNSHARD and
RESHARD action stays cheap: about 0.4 us per module, against 2.7 us for
isinstancewith a runtime protocol, which isn't cached._validate_deferred_gradient_reductionstill checks forFSDPModuleonly: itreads FSDP2's communication context, which only FSDP2 stages can share. The
unshard and gradient reduction handles are typed as a small
_Waitableprotocol, since only
wait()is called on them.Test Plan:
TestShardedDataParallelStageModuleintest/distributed/pipelining/test_schedule.py. Its module has the sixmethods without being an
FSDPModule, and records its calls._PipelineScheduleRuntimeruns the lowered Interleaved1F1B and ZBV plansfor two stages on one rank. Each stage's module gets
unshard(async_op=True)before its compute, then the gradient reductioncalls at REDUCE_GRAD and WAIT_REDUCE_GRAD, and every handle is waited on.
reshard().perform_reduce_gradon a stage finalizes the module's gradients.With the old
isinstance(..., FSDPModule)checks, 4 of the 5 tests fail.test_schedule.py(164 passed, 194 subtests) andtest_stage.py(23passed, 10 skipped) pass on CPU.
test_schedule_multiproc.py's FSDP2 testneeds 4 GPUs and wasn't run.
flex_shard fixes that aren't merged yet (2 GPUs, pipeline parallelism 2,
Interleaved1F1B, Llama 3 debug model, chunked loss, 20 steps): loss and grad
norm are bitwise identical to FSDP2's, without patching
FSDPModule. Theschedule calls
unshard(async_op=True),finalize_backward(async_op=True),set_manual_backward_finalizationandreshard()on FlexShard's stagemodules.
clean on the changed files. pyrefly 0.58.0 reports no new errors in them.