Skip to content

[Pipeline] Defer FSDP gradient reduction waits - #196725

Closed
fegin wants to merge 5 commits into
gh/fegin/365/basefrom
gh/fegin/365/head
Closed

fegin wants to merge 5 commits into
gh/fegin/365/basefrom
gh/fegin/365/head

Conversation

@fegin

@fegin fegin commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Split pipeline FSDP gradient reduction into explicit start and wait actions.

REDUCE_GRAD starts asynchronous FSDP gradient finalization and stores its public GradientReductionHandle. WAIT_REDUCE_GRAD waits for that handle and completes gradient scaling. Every reduction has exactly one matching wait, and each pipeline rank may have at most one pending reduction.

By default, the wait remains adjacent to its reduction, preserving existing behavior. With defer_reduce_grad_wait=True, schedule lowering moves only the wait to immediately before the next local reduction or to the end of the schedule. The reduction remains at its existing causal point, allowing its communication to overlap with the next local stage's backward computation.

For pre-lowered compute-comms schedules, the action stream is the source of truth. Their REDUCE_GRAD and WAIT_REDUCE_GRAD ordering is validated regardless of the constructor option.

Non-final outer gradient-accumulation steps skip both actions. Deferred waits reject FSDP stages that share a communication context because another stage cannot safely use that context while a reduction is pending.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 33ea317 with merge base f239880 (image):
💚 Looks good so far! There are no failures yet. 💚

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

[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin marked this pull request as ready for review September 24, 2026 08:55
stage.start_gradient_reduction()
else:
grad_scale_factor = self._n_microbatches if self.scale_grads else 1
stage.perform_reduce_grad(grad_scale_factor)

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.

IIUC, perform_reduce_grad is CPU blocking. it would wait for reduce_grad to complete, preventing other backward compute to proceed.

Even if we don't have outer gradient accumulation, we want the the async reduce grad.

I think we should make Async ReduceGrad the default behavior.

Comment thread torch/distributed/pipelining/stage.py 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.

I think the cleanest contract is for every lowered REDUCE_GRAD to have exactly one later WAIT_REDUCE_GRAD; defer_reduce_grad_wait should control only where that wait is placed. With the option disabled, lowering should emit REDUCE_GRAD, WAIT_REDUCE_GRAD adjacently. With it enabled, lowering should move the wait after the intervening compute, immediately before the next local REDUCE_GRAD, with the final wait at the end of the step. This makes the action stream the single source of truth: REDUCE_GRAD always starts asynchronous FSDP finalization, and WAIT_REDUCE_GRAD always waits, releases retained reduction buffers, restores manual-finalization state, and scales the completed sharded gradients. A pre-lowered compute_comms schedule would therefore need no hidden constructor flag to interpret the same actions; construction should instead validate one ordered wait per reduction, no duplicates or dangling waits, and the documented pending-reduction bound. Outer gradient-accumulation steps can keep both actions as runtime no-ops when finalize_gradients=False, preserving static topology. I also suggest separating async completion from memory policy: finalize_backward(async_op=True) should respect the configured reduce-scatter input-buffer cap, while the pipeline integration may raise that cap explicitly only when deferred overlap is enabled. Otherwise the adjacent/default form silently changes peak memory and copy-in/reduce-scatter overlap. Tests should reuse the existing schedule-lowering and PP/FSDP composability coverage to prove immediate versus deferred placement, pre-lowered action semantics without an out-of-band flag, the chosen one-pending-reduction invariant, gradient equivalence, and unchanged default memory policy.

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

fegin commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

The new version addresses the reviews.

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

LGTM! Please update the PR description with a more elaborate summary

@fegin

fegin commented Sep 29, 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 29, 2026
@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

pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
Store a GradientEdge for each releasable, grad-requiring pipeline output so backward does not require the original tensor object. Track one pending batched send per output slot. When an existing schedule wait completes that send, release the send operations and the stage's output reference.

Keep unsupported output types, DDP, custom split backward, and last-stage outputs on their tensor-backed ownership paths. Forward-only schedules do not create unused GradientEdges.

**This PR does not change when sends are issued. This PR releases send and stage ownership after the send completes, using the matching backward as the causal retirement point.**

Test Plan:

```

python test/distributed/pipelining/test_backward.py

python test/distributed/pipelining/test_stage.py OutputSlotReleaseTest

```

Authored with assistance from Codex.
Pull Request resolved: #196963
Approved by: https://github.com/SherlockNoMad
ghstack dependencies: #196640, #196724, #196725
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
## Summary

Add `WAIT_SEND_F` and `WAIT_SEND_B` as first-class pipeline schedule actions.

Each send now has an explicit matching wait. The runtime keeps the P2P operations, work handles, source tensors, and optional output-release callback alive until that wait executes.

## Motivation
Pipeline sends are nonblocking. Their work handles and source tensors must remain alive until communication completes.

Implicit end-of-step waits cannot express earlier ownership release and are unsuitable for static CUDA graph capture. Explicit actions make send lifetime part of the schedule.

This PR is stacked on #196963, which lets forward output ownership be released without breaking backward autograd connectivity.

## Design

For generated schedules:

  - Insert one wait for every send.
  - Place a forward-send wait after the matching backward action when available.
  - Place backward-send waits and unmatched forward-send waits at schedule end.

  For pre-lowered `compute_comms` schedules:

  - Require one ordered wait for every send.
  - Reject duplicate sends, missing waits, and waits without a pending send.

  At runtime:

  - Track each send by direction, stage, and microbatch.
  - Retire a send only when its explicit wait executes.
  - Release forward output ownership after the forward send completes.
  - Drain pending sends only when action execution fails.
  - Do not poll for communication completion.

  The schedule simulator also understands send-wait dependencies and requires he peer receive to be posted before a wait can complete.

  This PR does not enforce an outstanding-send count. A later PR can move these explicit waits earlier to satisfy a memory budget.

Pull Request resolved: #196726
Approved by: https://github.com/SherlockNoMad, https://github.com/sanketpurandare
ghstack dependencies: #196640, #196724, #196725, #196963
pytorchmergebot pushed a commit that referenced this pull request Sep 30, 2026
## Summary

Add an optional `max_outstanding_sends` limit to runtime pipeline schedules. The schedule moves existing send waits earlier to keep pending forward and backward sends within the per-rank limit.

Waits move only when dependency analysis proves the placement cannot create a cycle. Unsafe limits raise an actionable error. The default behavior remains unchanged.

Pull Request resolved: #196727
Approved by: https://github.com/sanketpurandare
ghstack dependencies: #196640, #196724, #196725, #196963, #196726
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
## Summary

Add an optional `max_outstanding_sends` limit to runtime pipeline schedules. The schedule moves existing send waits earlier to keep pending forward and backward sends within the per-rank limit.

Waits move only when dependency analysis proves the placement cannot create a cycle. Unsafe limits raise an actionable error. The default behavior remains unchanged.

Pull Request resolved: pytorch#196727
Approved by: https://github.com/sanketpurandare
ghstack dependencies: pytorch#196640, pytorch#196724, pytorch#196725, pytorch#196963, pytorch#196726
@github-actions
github-actions Bot deleted the gh/fegin/365/head branch December 2, 2026 01:58
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 ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: distributed (pipeline) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants