Skip to content

[Pipeline] Release forward outputs after sends complete - #196963

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

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

Conversation

@fegin

@fegin fegin commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Sep 14, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 9ed97d3 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]
@fegin
fegin marked this pull request as ready for review September 24, 2026 08:56
@SherlockNoMad

Copy link
Copy Markdown
Contributor

One clarification worth having is "
“Released” here means the pipeline drops its reference. The underlying storage is reclaimed only if neither autograd nor aliases nor user code still needs it."

Comment thread torch/distributed/pipelining/stage.py Outdated
Comment on lines +772 to +773
# One lease covers the slot's batched sends.
state.pending_consumers[idx] += 1

@SherlockNoMad SherlockNoMad Sep 24, 2026 •

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.

It doesn't seem to have a case where there are more consumers.

do it really need a counter for pending consumer?

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.

Sol: • Your reading is correct: in current built-in schedules, the counter only follows 0 → 1 → 0.

It is incremented once per output slot, outside the destination loop. All destination sends are then waited together before one release call. Thus it counts send batches, not consumers.

A boolean such as send_pending would better express the actual invariant. A second get_fwd_send_ops() call should probably be rejected as a duplicate rather than supported through reference counting.

A counter would only be justified if multiple independently retired send batches for the same output were intentionally supported—which this implementation does not currently do.

def _output_slot_is_releasable(self, output: Any) -> tuple[bool, str]:
"""Return whether an output may be released after sending."""
if self.is_last:
return False, "last-stage output"

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.

last-stage output usually contains loss, and needs to be returned to trainer loop.

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.

Yes, the last stage intentionally keeps its output tensor. The schedule may return it to the caller or pass it to the loss function. _output_slot_is_releasable() therefore marks last-stage outputs as not releasable.

"""Inputs and outputs retained for a forward chunk's sends and backward."""

output_grad_edges: tuple[GradientEdge | None, ...]
input_values: list[torch.Tensor]

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.

› does gradient Edge idea also work for input_values of a stage?

• Technically yes: GradientEdge can represent both autograd outputs and differentiation inputs.

Conceptually:

out_edge = get_gradient_edge(stage_output)
in_edge = get_gradient_edge(stage_input)

(dinput,) = torch.autograd.grad(
out_edge,
in_edge,
grad_outputs=(doutput,),
)

But it is not a drop-in change for this PR. input_values currently serve additional purposes:

  • They identify which inputs require gradients.
  • Full backward reads each input’s .grad and clears it.
  • First-stage inputs may be user tensors whose .grad must be populated.
  • Split weight backward may still depend on input values; autograd retains them when mathematically necessary.

Using input edges would require returning gradients directly from autograd.grad rather than relying on .grad, while preserving user-input, hook, DTensor, and split-backward semantics.

So the same optimization is potentially applicable to non-first-stage received activations, but it needs a separate design. The output case is simpler because, after sending, the pipeline only needs a backward root— not the output tensor interface itself.

Comment thread torch/distributed/pipelining/stage.py Resolved
fegin added a commit that referenced this pull request Sep 28, 2026
Store a GradientEdge for each releasable pipeline output so backward does not require the original tensor object. Track live output leases separately and release an output after every send consumer retires.

Keep unsupported output types, DDP, custom split backward, last-stage outputs, and forward-only graphs on their existing ownership paths.

Test Plan:

```
taskset -c 0-382 python3 test/distributed/pipelining/test_backward.py
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule.py
taskset -c 0-382 python3 test/distributed/pipelining/test_stage.py
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule_multiproc.py -k test_eval_inference_mode
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule_multiproc.py -k test_forward_only
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule_multiproc.py -k test_v_shape_schedules
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule_multiproc.py -k test_custom_function_callback
taskset -c 0-382 python3 test/distributed/pipelining/test_schedule_multiproc.py -k test_non_symmetric_stage_ids
taskset -c 0-382 env UV_NO_CONFIG=1 lintrunner -a
```

Authored with assistance from Codex.

ghstack-source-id: a59cac4
Pull-Request: #196963
[ghstack-poisoned]
@fegin fegin changed the title [Pipeline] Release sent outputs through autograd edges [Pipeline] Release forward outputs after sends complete Sep 29, 2026
[ghstack-poisoned]
@fegin

fegin commented Sep 30, 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 30, 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

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-noble-rocm-py3.11-mi350 / test (distributed, 1, 3, amd-dpx-linux.rocm.gpu.gfx950.2)

Details for Dev Infra team Raised by workflow job

[ghstack-poisoned]
@fegin

fegin commented Sep 30, 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

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
fegin added a commit to pytorch/torchtitan 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

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.
pytorchmergebot pushed a commit that referenced this pull request Oct 5, 2026
…t_before_backward (#199624)

`StageTest::test_schedule_releases_output_before_backward` (both `ScheduleGPipe` and `Schedule1F1B`), added in #196963, has failed deterministically on MI300 (`periodic-rocm-mi300`, distributed, 4 GPUs) since it landed. It passes on CUDA (T4 x4) and MI350 at the same commits.

```
test_stage.py, line 917, in test_schedule_releases_output_before_backward
Mismatched elements: 111494 / 262144 (42.5%)
Greatest absolute difference: 0.011597447097301483 at index (34, 452) (up to 4e-05 allowed)
Greatest relative difference: 347.6016540527344 at index (485, 506) (up to 1e-05 allowed)
```

Example job: https://github.com/pytorch/pytorch/actions/runs/36972654380/job/110734361600

## Root cause

The test checks pipeline gradients against a reference that does one full-batch forward and backward pass (M=256). The schedule runs 8 microbatches (M=32). If the backend picks GEMM kernels for M=32 and M=256 that round differently, a pre-activation near zero can land on the other side of the ReLU. That barely changes the forward output, but it switches the gradient for that unit on or off, so many gradient elements move well past `rtol=1e-5, atol=4e-5`.

I checked this on a single GPU using the same model, shapes, and loss. A 1-ulp nudge to the microbatched forward pass caused one ReLU flip in 1 of 10 seeds. That flip shifted 34.8% of the `layers.0.net1.weight` gradient elements past the test's tolerance (max abs diff 1.9e-3), while the forward outputs still matched under `assert_close`'s default tolerances. Without a flip, the two paths agreed to about 1e-6. `test_manual`, which compares chunked and full-batch forward outputs at default tolerances, passes in the same MI300 job, so the forward data is not corrupted. Only the ReLU gradients differ.

## Fix

Run the reference forward and backward pass over the same microbatches as the schedule. The reference then uses the same GEMM shapes as the stages and matches them bit for bit, so the test still checks for gradient corruption from the early output release without depending on how different batch sizes round. Tolerances are unchanged.

## Testing

- 4x MI210 (gfx90a): the 2 `test_schedule_releases_output_before_backward` variants and all 8 `StageTest` tests pass with this change. The original test also passes on gfx90a, so the MI300 failure could not be reproduced there.
- Single GPU: the microbatched reference and the microbatched run produce bit-identical gradients.
- MI300 confirmation needs `ciflow/periodic-rocm-mi300`.

This PR was authored with the help of an AI assistant.

Pull Request resolved: #199624
Approved by: https://github.com/jeffdaily
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
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…t_before_backward (pytorch#199624)

`StageTest::test_schedule_releases_output_before_backward` (both `ScheduleGPipe` and `Schedule1F1B`), added in pytorch#196963, has failed deterministically on MI300 (`periodic-rocm-mi300`, distributed, 4 GPUs) since it landed. It passes on CUDA (T4 x4) and MI350 at the same commits.

```
test_stage.py, line 917, in test_schedule_releases_output_before_backward
Mismatched elements: 111494 / 262144 (42.5%)
Greatest absolute difference: 0.011597447097301483 at index (34, 452) (up to 4e-05 allowed)
Greatest relative difference: 347.6016540527344 at index (485, 506) (up to 1e-05 allowed)
```

Example job: https://github.com/pytorch/pytorch/actions/runs/36972654380/job/110734361600

## Root cause

The test checks pipeline gradients against a reference that does one full-batch forward and backward pass (M=256). The schedule runs 8 microbatches (M=32). If the backend picks GEMM kernels for M=32 and M=256 that round differently, a pre-activation near zero can land on the other side of the ReLU. That barely changes the forward output, but it switches the gradient for that unit on or off, so many gradient elements move well past `rtol=1e-5, atol=4e-5`.

I checked this on a single GPU using the same model, shapes, and loss. A 1-ulp nudge to the microbatched forward pass caused one ReLU flip in 1 of 10 seeds. That flip shifted 34.8% of the `layers.0.net1.weight` gradient elements past the test's tolerance (max abs diff 1.9e-3), while the forward outputs still matched under `assert_close`'s default tolerances. Without a flip, the two paths agreed to about 1e-6. `test_manual`, which compares chunked and full-batch forward outputs at default tolerances, passes in the same MI300 job, so the forward data is not corrupted. Only the ReLU gradients differ.

## Fix

Run the reference forward and backward pass over the same microbatches as the schedule. The reference then uses the same GEMM shapes as the stages and matches them bit for bit, so the test still checks for gradient corruption from the early output release without depending on how different batch sizes round. Tolerances are unchanged.

## Testing

- 4x MI210 (gfx90a): the 2 `test_schedule_releases_output_before_backward` variants and all 8 `StageTest` tests pass with this change. The original test also passes on gfx90a, so the MI300 failure could not be reproduced there.
- Single GPU: the microbatched reference and the microbatched run produce bit-identical gradients.
- MI300 confirmation needs `ciflow/periodic-rocm-mi300`.

This PR was authored with the help of an AI assistant.

Pull Request resolved: pytorch#199624
Approved by: https://github.com/jeffdaily
atalman pushed a commit that referenced this pull request Oct 19, 2026
…t_before_backward (#201197)

[Pipeline] Use microbatched reference in test_schedule_releases_output_before_backward (#199624)

`StageTest::test_schedule_releases_output_before_backward` (both `ScheduleGPipe` and `Schedule1F1B`), added in #196963, has failed deterministically on MI300 (`periodic-rocm-mi300`, distributed, 4 GPUs) since it landed. It passes on CUDA (T4 x4) and MI350 at the same commits.

```
test_stage.py, line 917, in test_schedule_releases_output_before_backward
Mismatched elements: 111494 / 262144 (42.5%)
Greatest absolute difference: 0.011597447097301483 at index (34, 452) (up to 4e-05 allowed)
Greatest relative difference: 347.6016540527344 at index (485, 506) (up to 1e-05 allowed)
```

Example job: https://github.com/pytorch/pytorch/actions/runs/36972654380/job/110734361600

## Root cause

The test checks pipeline gradients against a reference that does one full-batch forward and backward pass (M=256). The schedule runs 8 microbatches (M=32). If the backend picks GEMM kernels for M=32 and M=256 that round differently, a pre-activation near zero can land on the other side of the ReLU. That barely changes the forward output, but it switches the gradient for that unit on or off, so many gradient elements move well past `rtol=1e-5, atol=4e-5`.

I checked this on a single GPU using the same model, shapes, and loss. A 1-ulp nudge to the microbatched forward pass caused one ReLU flip in 1 of 10 seeds. That flip shifted 34.8% of the `layers.0.net1.weight` gradient elements past the test's tolerance (max abs diff 1.9e-3), while the forward outputs still matched under `assert_close`'s default tolerances. Without a flip, the two paths agreed to about 1e-6. `test_manual`, which compares chunked and full-batch forward outputs at default tolerances, passes in the same MI300 job, so the forward data is not corrupted. Only the ReLU gradients differ.

## Fix

Run the reference forward and backward pass over the same microbatches as the schedule. The reference then uses the same GEMM shapes as the stages and matches them bit for bit, so the test still checks for gradient corruption from the early output release without depending on how different batch sizes round. Tolerances are unchanged.

## Testing

- 4x MI210 (gfx90a): the 2 `test_schedule_releases_output_before_backward` variants and all 8 `StageTest` tests pass with this change. The original test also passes on gfx90a, so the MI300 failure could not be reproduced there.
- Single GPU: the microbatched reference and the microbatched run produce bit-identical gradients.
- MI300 confirmation needs `ciflow/periodic-rocm-mi300`.

This PR was authored with the help of an AI assistant.

Pull Request resolved: #199624
Approved by: https://github.com/jeffdaily

(cherry picked from commit 630d63a)

Co-authored-by: pablo-garay <[email protected]>
@github-actions
github-actions Bot deleted the gh/fegin/368/head branch December 2, 2026 01:59
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.

3 participants