Skip to content

[pipelining] Treat any module with FSDP2's stage methods as sharded data parallel - #205659

Draft
anshul-si wants to merge 1 commit into
gh/anshul-si/148/basefrom
gh/anshul-si/148/head
Draft

anshul-si wants to merge 1 commit into
gh/anshul-si/148/basefrom
gh/anshul-si/148/head

Conversation

@anshul-si

@anshul-si anshul-si commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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 module
from 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.pipelining
today means patching FSDPModule in 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 and
schedules call: set_manual_backward_finalization,
set_requires_gradient_sync, set_reshard_after_backward,
finalize_backward(async_op=...), unshard(async_op=...) and reshard.
_is_sharded_data_parallel(module) replaces the 14 checks in stage.py and
schedules.py. FSDPModule has all six methods, so FSDP2 stages behave as
before. The check calls issubclass on the module's type, which caches its
result 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
isinstance with a runtime protocol, which isn't cached.

_validate_deferred_gradient_reduction still checks for FSDPModule only: it
reads FSDP2's communication context, which only FSDP2 stages can share. The
unshard and gradient reduction handles are typed as a small _Waitable
protocol, since only wait() is called on them.

Test Plan:

  • New TestShardedDataParallelStageModule in
    test/distributed/pipelining/test_schedule.py. Its module has the six
    methods without being an FSDPModule, and records its calls.
    • _PipelineScheduleRuntime runs the lowered Interleaved1F1B and ZBV plans
      for two stages on one rank. Each stage's module gets
      unshard(async_op=True) before its compute, then the gradient reduction
      calls at REDUCE_GRAD and WAIT_REDUCE_GRAD, and every handle is waited on.
    • A RESHARD action calls reshard().
    • A module with only some of the methods is left alone.
    • perform_reduce_grad on 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) and test_stage.py (23
    passed, 10 skipped) pass on CPU. test_schedule_multiproc.py's FSDP2 test
    needs 4 GPUs and wasn't run.
  • End to end with torchtitan's FlexShard backend, with torchtitan and
    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. The
    schedule calls unshard(async_op=True), finalize_backward(async_op=True),
    set_manual_backward_finalization and reshard() on FlexShard's stage
    modules.
  • lintrunner (FLAKE8, RUFF, PYFMT, CODESPELL, DOCSTRING_LINTER and others) is
    clean on the changed files. pyrefly 0.58.0 reports no new errors in them.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🔗 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 Jobs

As of commit d1ddae3 with merge base a66bab0 (image):

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.

@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Nov 19, 2026
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant