Skip to content

[PP] Overlap FSDP gradient reduction waits - #4661

Merged
fegin merged 23 commits into
mainfrom
gh/fegin/175/head
Oct 2, 2026
Merged

fegin merged 23 commits into
mainfrom
gh/fegin/175/head

Conversation

@fegin

@fegin fegin commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Allow multi-stage pipeline schedules to overlap an FSDP gradient reduction wait with the next local stage backward. Single-stage schedules cannot place work between reduction and wait, so they reject the option.

This uses the defer_reduce_grad_wait API from PyTorch PR, pytorch/pytorch#196963.

This PR also changes TorchTitan's CI to use PyTorch cu132 as we no longer have cu130 wheel.

[ghstack-poisoned]
[ghstack-poisoned]

@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.

We should just make this a default option and not add a config?

fegin added a commit 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.
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit 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

----

- Clear parameter gradients to None in Trainer and FaultTolerantTrainer.
- Keep capture-created gradient buffers alive and restore them after
replay.
- Require capture and replay to start without pending gradients.


**Why this state can reduce memory use:**

1. ``set_to_none=True`` without ``CUDAGraphGradientState`` fails after
the
       first capture.
       Autograd allocates a gradient during capture and assigns it to
``param.grad``. The next ``zero_grad`` clears that Python reference.
CUDA graph replay runs the captured GPU work, but it does not repeat the
``param.grad`` assignment. The optimizer then sees ``param.grad is
None``
       and skips the parameter update.

2. ``set_to_none=False`` avoids that failure, but eager warmup allocates
the
gradient before capture, outside the CUDA graph memory pool. Capture
only
records writes into that existing gradient buffer. Its lifetime overlaps
       the complete forward-backward graph::

time forward backward optimizer
gradient [===============================================]
           forward temp   [==========]
           backward temp                       [=========]

The graph allocator cannot reuse the gradient storage for these
temporary
       tensors because their lifetimes overlap.

3. With ``CUDAGraphGradientState``, ``set_to_none=True`` leaves
gradients
absent when capture starts. Autograd allocates them from the CUDA graph
memory pool during backward, after many forward tensors have expired::

time forward backward optimizer
           forward temp   [==========]
gradient [=========================]
shared block [forward temp] [gradient ]

During capture, the CUDA graph pool may reuse storage released by
forward
tensors for later gradients. This state then keeps those gradient
tensors
alive and restores each ``param.grad`` reference after replay. This
makes
       ``set_to_none=True`` safe.
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin marked this pull request as ready for review September 29, 2026 17:52
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 29, 2026
@fegin fegin changed the title [pp] Expose deferred FSDP gradient reduction waits [pp] Overlap FSDP gradient reduction waits Sep 29, 2026
@fegin fegin changed the title [pp] Overlap FSDP gradient reduction waits [PP] Overlap FSDP gradient reduction waits Sep 29, 2026
Comment thread torchtitan_recipes/tests/features.py Resolved
Comment on lines +394 to +396
"defer_reduce_grad_wait": any(
isinstance(stage.submod, FSDPModule) for stage in stages
),

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.

In titan we always enable fspd wrapping. Would this be still needed because, sometimes the stage.submod could be a submodule of a FSDPModule? sounds unlikely.

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.

GraphTrainer also uses this function but doesn't have FSDPModule. However, we can use backward_requires_autograd to simplify the code. Rewrite this.

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

**Conflict with #4649

Keep forward-backward and optimizer updates in separate CUDA graphs
while sharing graph-owned gradients. Capture clipping, finite checks,
and fused Adam updates, while keeping checkpoint waits and LR scheduling
eager.


**Architecture Change:**

Introduce `Optimization` that encapsulate EMA, gradient clipping,
gradient finite check and optimizer step.

Naming comes from the Codex's suggestion:

Closest related frameworks: PyTorch lightning uses
`_AutomaticOptimization` and Megatron-Core uses `MegatronOptimizer`,
both encapsulate more than just `Optitimizer.step()`. `Learner` is a bit
confusing because Ray RLlib uses `Learner` for the entire post-training
model, loss, gradients, ...
Comment thread torchtitan_recipes/tests/features.py Resolved
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
fegin added 3 commits October 1, 2026 19:23
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/175/base to main October 2, 2026 06:56
@fegin
fegin merged commit 8812ee1 into main Oct 2, 2026
fegin added a commit that referenced this pull request Oct 2, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #4662
* #4661

**Summary**
Expose the maximum number of pending pipeline send batches. The PyTorch
schedule inserts explicit waits and releases sent outputs while autograd
keeps the backward edges.

Unit tests cover forwarding and validation. A deterministic FSDP 2 x PP
2 integration case covers the budget with deferred gradient-reduction
waits.

This PR depends on pytorch/pytorch#196727
shuhuayu added a commit that referenced this pull request Oct 8, 2026
## Summary

- Mirror the FSDP setup in the upstream PipelineStage forward path.
- Enable manual backward finalization before the Kimi K3
attention-residual stage runs its model forward.
- Fix the Kimi K3 PP B200 test regression exposed after deferred FSDP
gradient reduction was adopted in
#4661.

## Why

AttnResPipelineStage overrides forward_one_chunk. The override omitted
the FSDP manual-finalization setup now performed by the PyTorch base
implementation. Runtime pipeline schedules later call finalize_backward
and fail with:

FSDP finalize_backward requires manual backward finalization. Call
set_manual_backward_finalization(True) before forward

The resulting test regression was reproduced by the
kimi_k3_fsdp2_tp2_ep2_pp2_vpp4 B200 lane in
https://github.com/pytorch/torchtitan/actions/runs/37123140508/job/111203042475.

## Test plan

- The existing 8-GPU kimi_k3_fsdp2_tp2_ep2_pp2_vpp4 B200 regression test
passed with rc=0 in
https://github.com/pytorch/torchtitan/actions/runs/37738225414.
- The overall B200 workflow remains red because five unrelated lanes
failed: kimi_k3_mm, kimi_k3_mm_muon, mxfp8_linear_fsdp,
dist_moe_eager_fsdp_ep_cudagraph, and
dist_moe_eager_fsdp_ep_pp_cudagraph.
- Changed-file formatting, flake8, pydoclint, codespell, and link hooks
passed.
shuhuayu added a commit that referenced this pull request Nov 24, 2026
## Summary (human-written)

udpate b200 ci to cu132.

## Why

The B200 workflows install the latest PyTorch nightly without a pin,
from the
`cu130` index. PyTorch stopped publishing cu130 nightlies on 2026-11-03
(pytorch/pytorch#203260). The newest wheel on that index is
`torch==2.16.0.dev20261102+cu130`, so every B200 run since then has
tested a
three-week-old PyTorch:

| Index | Newest torch nightly (checked 2026-11-23) |
| --- | --- |
| `nightly/cu130` (B200 today) | `2.16.0.dev20261102` |
| `nightly/cu132` (other CUDA lanes) | `2.16.0.dev20261123` |

**Example.** pytorch/pytorch#205562, the fix for the cuDNN varlen
backward
wrong-dQ bug (pytorch/pytorch#205493), landed on 2026-11-19. It never
reaches
B200 CI, and `kimi_k3_dist_moe_fsdp_ep_cp` in #5684 keeps crashing with
`cuDNN SDPA ... illegal memory access`.

The other CUDA lanes moved to cu132 in #4661. The two B200 workflows
were not
updated.

## What changed

- `integration_test_b200.yaml` and
`integration_test_b200_graph_trainer.yaml`
  install torch, torchvision and torchao from `nightly/cu132` instead of
  `nightly/cu130`.
- The container image stays
`nvidia/cuda:13.0.3-cudnn-devel-ubuntu22.04`. The
  torch wheels ship their own CUDA runtime and cuDNN as `nvidia-*` pip
  packages.
- The torchao pin (`0.19.0.dev20261103`) is published on cu132, so
  `.github/requirements-torchao.txt` is unchanged.

## Testing

The B200 and B200 graph-trainer workflows run on this PR through the
`ciflow/b200` label. The run log should show
`torch==2.16.0.dev2026112x+cu132`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants