Skip to content

[pipelining] Skip in-place detach of view stage outputs in stage_backward_input - #200199

Closed
anijain2305 wants to merge 2 commits into
gh/anijain2305/1350/basefrom
gh/anijain2305/1350/head
Closed

anijain2305 wants to merge 2 commits into
gh/anijain2305/1350/basefrom
gh/anijain2305/1350/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

stage_backward_input frees output-side graph state by calling
stage_output.detach_() on every stage output after computing input
gradients. That raises "Can't detach views in-place" when a stage output is a
view, e.g. the output of an identity autograd.Function. Activation
checkpointing libraries return such views at their checkpoint boundary
(torch_remat does), so a pipeline stage that ends in a checkpointed block
fails under every schedule that splits input and weight backward (zero
bubble, ZBV, CSV schedules with I/W actions):

RuntimeError: Failed to run stage backward input: ...
RuntimeError: Can't detach views in-place. Use detach() instead.

Skip the in-place detach for views. It is only a memory optimization: a
view's graph is freed when the last reference to the output goes away. For
outputs released after send that is right away; outputs the stage retains
(e.g. DTensor, DDP-wrapped submodules, last-stage outputs) are kept until the
weight backward, so their input-only graph lives until then.

Test plan: new test_stage_backward_input_with_view_output runs the split
input/weight backward on a stage whose output comes from an identity
autograd.Function and checks input and weight gradients against a plain
backward. It fails without the fix with the error above.

python test/distributed/pipelining/test_backward.py

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 3306b18 with merge base 2eb7361 (image):
💚 Looks good so far! There are no failures yet. 💚

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 Oct 7, 2026
@anijain2305
anijain2305 marked this pull request as ready for review October 7, 2026 22:41
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review the PR

@claude

claude Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 1m 36s —— View job


The fix is correct and follows the existing last-stage precedent at stage.py:1366-1368, but the new code comment overstates when a view output's graph gets freed.

PR Review: #200199

Summary

This PR skips the in-place detach_() on stage outputs that are views in stage_backward_input, so stages whose output comes from an identity autograd.Function (for example a torch_remat checkpoint boundary) work with split I/W schedules. No REVIEW.md applies. The only problem is the comment that explains the change.

Code Quality

  • torch/distributed/pipelining/_backward.py:281-284: the comment says a view's graph "is released once the stage drops its reference to the output". For outputs the stage does not release after send, that reference is held much longer than the comment implies. Not-releasable outputs include tensor subclasses such as DTensor, DDP-wrapped submodules, and last-stage outputs (see _output_slot_is_releasable, stage.py:702-714).
    • For these outputs, backward_one_chunk keeps the live tensor in bwd_kwargs["stage_output"] (stage.py:1332-1335 only replaces GradientEdge roots with None). It then stores that tensor in self.backward_state[bwd_chunk_id] (stage.py:1338-1343) until backward_weight_one_chunk runs.
    • So in ZB/ZBV schedules, the input-only part of a view output's graph stays alive until the deferred W step. For non-view outputs, detach_() frees it right after the I step.
    • For plain-tensor outputs released after send, the backward roots are already GradientEdges and this branch never runs, so the common case is unaffected.
    • Fix: reword the comment to say the graph is freed when the last reference to the output goes away, which for retained outputs is after weight backward. Don't null those tensors out in stage.py:1332: DDP's prepare_for_backward reads bwd_kwargs["stage_output"] (stage.py:1117-1123).

Recommendation

Approve once the comment is reworded. The fix is minimal and has a direct regression test. I couldn't run the test in this environment because the shell command wasn't approved.

[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 7, 2026
…ward_input

`stage_backward_input` frees output-side graph state by calling
`stage_output.detach_()` on every stage output after computing input
gradients. That raises "Can't detach views in-place" when a stage output is a
view, e.g. the output of an identity `autograd.Function`. Activation
checkpointing libraries return such views at their checkpoint boundary
(torch_remat does), so a pipeline stage that ends in a checkpointed block
fails under every schedule that splits input and weight backward (zero
bubble, ZBV, CSV schedules with I/W actions):

```text
RuntimeError: Failed to run stage backward input: ...
RuntimeError: Can't detach views in-place. Use detach() instead.
```

Skip the in-place detach for views. It is only a memory optimization: a
view's graph is freed when the last reference to the output goes away. For
outputs released after send that is right away; outputs the stage retains
(e.g. DTensor, DDP-wrapped submodules, last-stage outputs) are kept until the
weight backward, so their input-only graph lives until then.

Test plan: new `test_stage_backward_input_with_view_output` runs the split
input/weight backward on a stage whose output comes from an identity
`autograd.Function` and checks input and weight gradients against a plain
backward. It fails without the fix with the error above.

    python test/distributed/pipelining/test_backward.py

ghstack-source-id: ac7401b
Pull-Request: #200199
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review the PR

@claude

claude Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 42s —— View job


I found no issues: the reworded comment fixes the one point from the earlier review, and the fix and regression test look correct.

PR Review: #200199

Summary

stage_backward_input no longer calls in-place detach_() on stage outputs that are views, such as the output of an identity autograd.Function at a checkpoint boundary, so split I/W schedules now work for these stages. No REVIEW.md applies.

  • The guard at torch/distributed/pipelining/_backward.py:287 matches the existing last-stage guard at torch/distributed/pipelining/stage.py:1367-1368.
  • The new comment at _backward.py:281-285 now says that a retained view output keeps its graph alive until the weight backward. That was the only point raised in the earlier review.
  • test_stage_backward_input_with_view_output is a direct regression test. It follows the device-generic pattern of the tests around it and checks both input and weight gradients against a plain backward.

Recommendation

Approve. I didn't run the test because the shell command needed approval in this environment.

@anijain2305 anijain2305 added the topic: not user facing topic category label Oct 8, 2026
@anijain2305

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 Oct 8, 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

cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ward_input (pytorch#200199)

`stage_backward_input` frees output-side graph state by calling
`stage_output.detach_()` on every stage output after computing input
gradients. That raises "Can't detach views in-place" when a stage output is a
view, e.g. the output of an identity `autograd.Function`. Activation
checkpointing libraries return such views at their checkpoint boundary
(torch_remat does), so a pipeline stage that ends in a checkpointed block
fails under every schedule that splits input and weight backward (zero
bubble, ZBV, CSV schedules with I/W actions):

```text
RuntimeError: Failed to run stage backward input: ...
RuntimeError: Can't detach views in-place. Use detach() instead.
```

Skip the in-place detach for views. It is only a memory optimization: a
view's graph is freed when the last reference to the output goes away. For
outputs released after send that is right away; outputs the stage retains
(e.g. DTensor, DDP-wrapped submodules, last-stage outputs) are kept until the
weight backward, so their input-only graph lives until then.

Test plan: new `test_stage_backward_input_with_view_output` runs the split
input/weight backward on a stage whose output comes from an identity
`autograd.Function` and checks input and weight gradients against a plain
backward. It fails without the fix with the error above.

    python test/distributed/pipelining/test_backward.py
Pull Request resolved: pytorch#200199
Approved by: https://github.com/sanketpurandare
acisseJZhong added a commit to pytorch/torchtitan that referenced this pull request Oct 22, 2026
TorchTitan `release/0.4` uses pipelining behavior missing from the
inspected PyTorch 2.15 RC: core PP rejects `loss_kwarg_mbs`, Dist-MoE PP
cannot register metadata cleanup, and ZeroBubble with release-pinned
remat fails when split backward detaches a view in place. This adds an
automatically applied compatibility shim for those three upstream fixes.

### PyTorch PRs backported

| Upstream PR | Author | Required behavior |
| --- | --- | --- |
| pytorch/pytorch#199884 | Sanket Purandare |
Register post-metadata-inference cleanup callbacks, used by Titan's
Dist-MoE PP integration and forwarded by GraphTrainer. |
| pytorch/pytorch#200238 | Jiani Wang | Support
per-microbatch `loss_kwarg_mbs`, already passed by core Titan PP
training. |
| pytorch/pytorch#200199 | Animesh Jain | Skip
in-place detach of view stage outputs during split input/weight
backward, needed by ZeroBubble with activation rematerialization. |

The corresponding upstream commits are
`f722f226bbcebd522c6fec3bc463b21df273cb7e`,
`9a2d9d7b6434e9aa4e048aa8d1b76939e5fe9962`, and
`b7442f6915a1d95412d7fab784e554053746b08d`.

### Behavior and compatibility boundary

- The packaged shim runs during `import torchtitan`, before training
constructs pipeline schedules. Users do not need to call a patch
function manually.
- It replaces the affected Python functions in the current process,
preserves schedule class identities, and updates the backward alias used
by `stage.py`. Installed PyTorch files are not modified.
- The tested wheel is `torch==2.15.0+cu130`, source commit
`dd1fefe31baf1bc8efbab6dc5291eebfb948b7bf`. The version gate accepts the
public version `2.15.0`; other public versions are left untouched.
- Missing-feature checks and exact before/after function-source
fingerprints bound the backports to the reviewed implementations. All
replacements are prepared before publication; an unsupported source
layout raises an explicit error without partially patching the modules.
Later RCs, the final wheel, and partial cherry-pick combinations need
revalidation.
- Set `TORCHTITAN_DISABLE_TORCH_COMPAT=1` before import in a fresh
process to disable the shim for diagnosis.

### Validation

- 66 CPU tests passed: 13 new compatibility regressions and 53 existing
PP tests. Coverage includes five schedules, microbatch loss values and
gradients, cleanup lifecycle, split-backward view outputs, invalid
inputs, and import gates/atomicity.
- Original RC core PP training reproduces the `loss_kwarg_mbs` failure.
With only the two API backports, ZeroBubble + Full remat reproduces
`Can't detach views in-place`.
- Two-H100 Llama3 training: 1F1B completed three steps; ZeroBubble +
Full remat completed four, including CUDA Graph replay. With seed 42 and
deterministic algorithms enabled, recorded loss and grad norm exactly
matched an independent application of the upstream source diffs for each
recipe.
- Selected GraphTrainer runner tests: 13 passed, plus 6 subtests. WGrad
fusion: 24 passed, plus 13 subtests. GraphTrainer Llama3 FSDP2 completed
four steps in both regional and full Inductor modes; these additional
runs are smoke tests, not numerical-equivalence checks.
- Built and installed the `0.4.0rc1` wheel with `--no-deps` into a
separate directory, then imported it outside the checkout. Automatic
activation, idempotence, class identity, backward alias binding, and
unchanged on-disk Torch hashes passed.
- `pre-commit run --all-files`: formatting/style checks passed; global
Pyrefly remains failing in files outside this diff (61 diagnostics with
the shared development environment; 38 when pointed at the RC overlay).
Unrelated automatic edits were restored. Static type checking does not
observe the runtime-added PyTorch API.

This remains a draft pending release-wheel revalidation and the full
release CI matrix, including B200/Dist-MoE. No additional compiler or
performance backports are included.
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 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants