Skip to content

[Pipeline] Support outer gradient accumulation - #196641

Closed
fegin wants to merge 9 commits into
gh/fegin/363/basefrom
gh/fegin/363/head
Closed

fegin wants to merge 9 commits into
gh/fegin/363/basefrom
gh/fegin/363/head

Conversation

@fegin

@fegin fegin commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Add a finalize_gradients step option so callers can keep FSDP accumulation open across complete pipeline schedules.

Use the public FSDP finalizer.

FSDP finalization reshards parameters, but the pipeline runtime kept the stage marked as unsharded. Track stages retained across calls separately and update the runtime state when reduction reshards a stage. This preserves the duplicate-unshard checks without forcing another all-gather between deferred steps.

Keep the option scoped to FSDP. DDP and non-FSDP stages keep their existing reduction and scaling behavior.

Test Plan:

python3 test/distributed/pipelining/test_schedule.py
python3 test/distributed/test_composability.py -k test_pp_fsdp_outer_gradient_accumulation
python3 test/distributed/test_composability.py -k test_pp_fsdp_unshard_reshard_runtime
python3 test/distributed/test_composability.py -k test_pp_ddp
UV_NO_CONFIG=1 lintrunner -a

This commit was authored with assistance from Codex.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196641

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (4 Unrelated Failures)

As of commit 6c64dee with merge base 5c7687f (image):

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Sep 10, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 16, 2026
Add a finalize_gradients step option so callers can keep FSDP accumulation open across complete pipeline schedules.

Use the public FSDP finalizer.

FSDP finalization reshards parameters, but the pipeline runtime kept the stage marked as unsharded. Track stages retained across calls separately and update the runtime state when reduction reshards a stage. This preserves the duplicate-unshard checks without forcing another all-gather between deferred steps.

Keep the option scoped to FSDP. DDP and non-FSDP stages keep their existing reduction and scaling behavior.

Test Plan:

```
python3 test/distributed/pipelining/test_schedule.py
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_outer_gradient_accumulation
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_unshard_reshard_runtime
```

```
python3 test/distributed/test_composability.py -k test_pp_ddp
```

```
UV_NO_CONFIG=1 lintrunner -a
```

This commit was authored with assistance from Codex.

ghstack-source-id: d723137
Pull-Request: #196641
@fegin
fegin marked this pull request as ready for review September 16, 2026 22:27
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 17, 2026
Add a finalize_gradients step option so callers can keep FSDP accumulation open across complete pipeline schedules.

Use the public FSDP finalizer.

FSDP finalization reshards parameters, but the pipeline runtime kept the stage marked as unsharded. Track stages retained across calls separately and update the runtime state when reduction reshards a stage. This preserves the duplicate-unshard checks without forcing another all-gather between deferred steps.

Keep the option scoped to FSDP. DDP and non-FSDP stages keep their existing reduction and scaling behavior.

Test Plan:

```
python3 test/distributed/pipelining/test_schedule.py
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_outer_gradient_accumulation
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_unshard_reshard_runtime
```

```
python3 test/distributed/test_composability.py -k test_pp_ddp
```

```
UV_NO_CONFIG=1 lintrunner -a
```

This commit was authored with assistance from Codex.

ghstack-source-id: 7d78749
Pull-Request: #196641
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 18, 2026
Add a finalize_gradients step option so callers can keep FSDP accumulation open across complete pipeline schedules.

Use the public FSDP finalizer.

FSDP finalization reshards parameters, but the pipeline runtime kept the stage marked as unsharded. Track stages retained across calls separately and update the runtime state when reduction reshards a stage. This preserves the duplicate-unshard checks without forcing another all-gather between deferred steps.

Keep the option scoped to FSDP. DDP and non-FSDP stages keep their existing reduction and scaling behavior.

Test Plan:

```
python3 test/distributed/pipelining/test_schedule.py
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_outer_gradient_accumulation
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_unshard_reshard_runtime
```

```
python3 test/distributed/test_composability.py -k test_pp_ddp
```

```
UV_NO_CONFIG=1 lintrunner -a
```

This commit was authored with assistance from Codex.

ghstack-source-id: d407cdf
Pull-Request: #196641
fegin added a commit that referenced this pull request Sep 18, 2026
Add a finalize_gradients step option so callers can keep FSDP accumulation open across complete pipeline schedules.

Use the public FSDP finalizer.

FSDP finalization reshards parameters, but the pipeline runtime kept the stage marked as unsharded. Track stages retained across calls separately and update the runtime state when reduction reshards a stage. This preserves the duplicate-unshard checks without forcing another all-gather between deferred steps.

Keep the option scoped to FSDP. DDP and non-FSDP stages keep their existing reduction and scaling behavior.

Test Plan:

```
python3 test/distributed/pipelining/test_schedule.py
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_outer_gradient_accumulation
```

```
python3 test/distributed/test_composability.py -k test_pp_fsdp_unshard_reshard_runtime
```

```
python3 test/distributed/test_composability.py -k test_pp_ddp
```

```
UV_NO_CONFIG=1 lintrunner -a
```

This commit was authored with assistance from Codex.

ghstack-source-id: d407cdf
Pull-Request: #196641
self._update_losses(self._stage, losses)

self._stage.perform_reduce_grad(self._n_microbatches if self.scale_grads else 1)
if self._finalize_gradients or not isinstance(self._stage.submod, FSDPModule):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you know this better, why we need

not isinstance(self._stage.submod, FSDPModule):

which reduce_grad path would FSDPModule take?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a comment, there are still other stage, like DDP.

@SherlockNoMad SherlockNoMad left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approve to unblock.

as discussed offline, such case should be supported by a pluggable PP IR.

The original motivation of the PR is to support following case:
It ooms to run 1F1B with microbatch size of 32 due to staged activation memory, but it can run with microbatch size of 4. So it does 8 rounds of "outer gradient accumulation", with "inner PP 1F1B of microbatch size of 4".

The same effect can be achieved by a customized PP IR, which unrolls the "1F1B mb4 by 8 times".

cc @tianyu-l @sanketpurandare

sanketpurandare

This comment was marked as resolved.

@sanketpurandare sanketpurandare left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks correct to me for eager stuff

[ghstack-poisoned]
[ghstack-poisoned]
@fegin

fegin commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 22, 2026
@fegin

fegin commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 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.

Details for Dev Infra team Raised by workflow job

@fegin

fegin commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorch-auto-revert

Copy link
Copy Markdown

@pytorchbot revert -m "Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable" -c autorevert

This PR is attributed to have caused regression in:

Note: This revert was accelerated by the AI advisor: AI advisor: related (confidence=0.99)

Please investigate and fix the issues.
@claude Can you please read this revert comment, follow the links and read the errors, to then give a brief diagnostics on the cause of the error? If you judge the error to be legitimate reason for a revert, please provide brief guidance on how the author could fix it.

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Claude finished @pytorch-auto-revert[bot]'s task in 37s —— View job


Revert diagnosis: legitimate

  • Read revert comment and fetched the failing job log
  • Identified root cause
  • Proposed fix

Cause. lintrunner-noclang-all fails with a real RUFF F821 in the code this PR added:

>>> Lint for test/distributed/test_composability.py:
  Error (RUFF) F821
    Undefined name `TEST_WITH_ROCM`.
        388  |    @skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "Test requires 4+ GPUs")
        389  |    def test_pp_fsdp_outer_gradient_accumulation(self):
    >>> 390  |        if TEST_WITH_ROCM:
        391  |            return

test/distributed/test_composability.py:390 references TEST_WITH_ROCM, but the file's common_utils import (lines 30-35) only brings in instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if. So it's not just a lint nit — the test would raise NameError the moment it runs anywhere.

This is a lint-only job (no test signal involved), it is 100% attributable to lines added by this PR, and the whole lint workflow returned RC=1 — so the autorevert is correct.

Fix. Either import the flag:

from torch.testing._internal.common_utils import (
    instantiate_parametrized_tests,
    parametrize,
    run_tests,
    skip_but_pass_in_sandcastle_if,
    TEST_WITH_ROCM,
)

or, preferably, drop the manual early-return (which silently reports the test as passing) and use the standard decorator instead:

from torch.testing._internal.common_utils import skipIfRocm

@skipIfRocm
@skip_if_lt_x_gpu(4)
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "Test requires 4+ GPUs")
def test_pp_fsdp_outer_gradient_accumulation(self):

Then re-verify with lintrunner -m origin/main (or UV_NO_CONFIG=1 lintrunner -a) before re-landing. Note the PR's stated test plan already lists lintrunner -a; it likely ran before the ROCm guard was added in a later amend, so it's worth re-running on final HEAD.

Fix this →

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

pytorchmergebot added a commit that referenced this pull request Sep 22, 2026
This reverts commit affe288.

Reverted #196641 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](#196641 (comment)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@fegin your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Sep 22, 2026
[ghstack-poisoned]
@fegin

fegin commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

fegin added a commit to pytorch/torchtitan that referenced this pull request Sep 29, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4662
* #4661
* #4660
* #4659
* __->__ #4658

----
**Conflict with #4649, need
to discuss how to incorporate with
#4649
**Depend on pytorch/pytorch#196640 and
pytorch/pytorch#196641

- Add `parallelism.fsdp_defer_gradient_reduction` to reduce gradients
after the final backward of a gradient accumulation group.
- Replay the whole optimizer step during SDC checks.
- Use the public FSDP and pipeline finalization APIs.
@github-actions
github-actions Bot deleted the gh/fegin/363/head branch November 30, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: pipelining Pipeline Parallelism release notes: distributed (pipeline) release notes category Reverted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants