Skip to content

[pipelining] Register post-metadata-inference cleanup - #199884

Closed
sanketpurandare wants to merge 1 commit into
mainfrom
codex/post-metadata-inference-cleanup
Closed

sanketpurandare wants to merge 1 commit into
mainfrom
codex/post-metadata-inference-cleanup

Conversation

@sanketpurandare

Copy link
Copy Markdown
Contributor

I reviewed this AI-assisted change and its validation. It is relevant because pipeline metadata inference can execute user code whose runtime state is not owned by PipelineStage.

This PR was prepared with assistance from Codex.

Summary

Add a removable callback registration to pipeline schedules for cleanup that must run after dynamic metadata inference.

PipelineStage already restores its module buffers, releases inference tensors, reshards FSDP parameters, and clears gradients. External runtimes can own additional state that is not reachable through the stage module. Registered callbacks run after all stage-owned cleanup completes.

Callbacks:

  • run only when dynamic metadata inference executes;
  • run from the existing cleanup path after stage cleanup;
  • do not run for constructor-provided static metadata;
  • can be removed through RemovableHandle.

This intentionally does not introduce a general pipeline lifecycle framework or callback arguments.

Test plan

  • python test/distributed/pipelining/test_schedule.py ScheduleTest (51 passed)
  • spin quicklint (passed)

Pipeline metadata inference can leave state in runtimes external to stage
modules. Add a minimal removable callback registration on the schedule and
invoke callbacks after dynamic metadata inference and stage-owned cleanup.
Static metadata initialization does not invoke the callbacks.

This change was authored with assistance from Codex.

Test Plan:

```
python test/distributed/pipelining/test_schedule.py ScheduleTest
spin quicklint
```
@pytorch-bot

pytorch-bot Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 74919b8 with merge base a8df8b3 (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 6, 2026
@sanketpurandare
sanketpurandare requested a review from fegin October 6, 2026 05:25
@fegin fegin added the module: pipelining Pipeline Parallelism label Oct 6, 2026
@sanketpurandare sanketpurandare added topic: not user facing topic category ciflow/trunk Trigger trunk jobs on your pull request labels Oct 6, 2026
@sanketpurandare

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

sanketpurandare added a commit to pytorch/torchtitan that referenced this pull request Oct 8, 2026
## Summary

Dynamic pipeline metadata inference executes representative model
forwards before the first training step. Dist-MoE owns activation state
outside the stage module, so PipelineStage's module and FSDP cleanup
cannot release that state.

Register `DistMoeRuntime.context.reset` through PyTorch's
post-metadata-inference cleanup API. The runtime owns the returned
handle and removes it during constructor rollback and normal teardown.

This replaces the validation-only private schedule monkeypatch. It does
not change pipeline schedules, activation-slot coloring, Dist-MoE
kernels, or static-metadata execution.

## Dependency

Depends on pytorch/pytorch#199884. Keep this PR in draft until that API
lands, then rebase on the corresponding PyTorch baseline and rerun the
gates below.

## Test plan

- `python -m pytest -q tests/unit_tests/cpu/test_dist_moe.py` (38
passed)
- Focused Pyrefly on `torchtitan/models/common/dist_moe/runtime.py` (0
errors)
- All non-Pyrefly pre-commit hooks passed; project-wide Pyrefly reports
an unrelated existing multimedia `video.py` error
- A two-rank PP/CP MXFP8 Dist-MoE configuration completed 10 full
CUDA-graph training steps with finite loss and gradients and no metadata
monkeypatch
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
I reviewed this AI-assisted change and its validation. It is relevant because pipeline metadata inference can execute user code whose runtime state is not owned by PipelineStage.

> This PR was prepared with assistance from Codex.
>
> ## Summary
>
> Add a removable callback registration to pipeline schedules for cleanup that must run after dynamic metadata inference.
>
> PipelineStage already restores its module buffers, releases inference tensors, reshards FSDP parameters, and clears gradients. External runtimes can own additional state that is not reachable through the stage module. Registered callbacks run after all stage-owned cleanup completes.
>
> Callbacks:
> - run only when dynamic metadata inference executes;
> - run from the existing cleanup path after stage cleanup;
> - do not run for constructor-provided static metadata;
> - can be removed through `RemovableHandle`.
>
> This intentionally does not introduce a general pipeline lifecycle framework or callback arguments.
>
> ## Test plan
>
> - `python test/distributed/pipelining/test_schedule.py ScheduleTest` (51 passed)
> - `spin quicklint` (passed)

Pull Request resolved: pytorch#199884
Approved by: https://github.com/fegin
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 module: pipelining Pipeline Parallelism topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants