Repository navigation
Conversation
xmfan
force-pushed
the
xmfan/stack/51
branch
from
September 3, 2026 00:15
302fe58 to
0823adc
Compare
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 3, 2026 00:15
7b2af06 to
8428666
Compare
This was referenced Sep 3, 2026
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 3, 2026 01:20
8428666 to
035f24b
Compare
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 3, 2026 06:13
035f24b to
1407993
Compare
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 4, 2026 06:40
1407993 to
5881f82
Compare
xmfan
force-pushed
the
xmfan/stack/51
branch
from
September 4, 2026 06:40
4a0178b to
11efec5
Compare
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 4, 2026 18:31
5881f82 to
534b968
Compare
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Sep 4, 2026
## Why
TorchTitan captures the non-pipeline forward-backward function, but pipeline training still executes every schedule eagerly. The pipeline schedule is a suitable graph boundary once input preprocessing remains outside capture and communication order, process groups, tensor structure, and tensor metadata remain static.
This change applies the same full-forward-backward capture model to pipeline schedules.
## Capture boundary
```text
Eager code
|
+--> load microbatches
+--> move tensors to the device
+--> preprocess model inputs
|
v
CUDA graph boundary
|
+--> pipeline schedule
+--> forward computation
+--> pipeline P2P communication
+--> loss computation
+--> backward computation
+--> detached microbatch-loss reduction
|
v
Eager code
|
+--> gradient clipping
+--> optimizer and scheduler steps
+--> metrics reduction and logging
```
## Change
Split pipeline preprocessing from `_pp_forward_backward_body()` and wrap that schedule body when CUDA graphs are enabled. Use a persistent graph-owned loss sentinel on ranks that do not own the last stage.
Expose the upstream deferred-receive control for looped schedules and configure directed P2P process groups before distributed initialization. CUDA-graph pipeline training requires either explicit per-direction process groups or PyTorch automatic TorchComms groups.
Reject pipeline CUDA graphs with validation because validation reinitializes the shared schedule and invalidates the captured training graph.
## Testing
The unit tests cover configuration validation, directed-group initialization, deferred-receive forwarding, structured pipeline inputs, persistent loss output, and wrapper selection.
- `python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_pipeline_parallel.py tests/unit_tests/cpu/test_integration_test_definitions.py`
- `PYTHONPATH=. python tests/integration_tests/run_tests.py <output> --test_suite features --test_name pp_looped_1f1b_cudagraph --ngpu 4` (10/10 steps)
- Deterministic four-GPU eager-versus-graph comparison with seed 42: bitwise-identical loss and `grad_norm` for all 10 steps
stack-info: PR: pytorch/torchtitan#4435, branch: xmfan/stack/52
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 4, 2026 22:00
534b968 to
2d434c8
Compare
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 4, 2026 22:06
2d434c8 to
ea8ad91
Compare
## Why
TorchTitan captures the non-pipeline forward-backward function, but pipeline training still executes every schedule eagerly. A pipeline schedule with one stage per rank is a suitable graph boundary once input preprocessing remains outside capture and communication order, process groups, tensor structure, and tensor metadata remain static.
This change adds CUDA graph capture for single-stage-per-rank pipeline schedules. Looped schedules remain unsupported here because they require separate directed P2P communicators.
## Capture boundary
```text
Eager code
|
+--> load microbatches
+--> move tensors to the device
+--> preprocess model inputs
|
v
CUDA graph boundary
|
+--> pipeline schedule
+--> forward computation
+--> pipeline P2P communication
+--> loss computation
+--> backward computation
+--> detached microbatch-loss reduction
|
v
Eager code
|
+--> gradient clipping
+--> optimizer and scheduler steps
+--> metrics reduction and logging
```
## Change
Split pipeline preprocessing from `_pp_forward_backward_body()` and select either the pipeline or non-pipeline body through the existing `fwd_bwd_fn` before applying the CUDA graph wrapper. Use a persistent loss sentinel on ranks that do not own the last stage.
Reject looped pipeline schedules until their directed P2P communicator dependency is available, and reject pipeline CUDA graphs with validation because validation reinitializes the shared schedule and invalidates the captured training graph.
## Testing
The unit tests cover configuration validation, structured pipeline inputs, persistent loss output, and wrapper selection.
- `python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_integration_test_definitions.py`
- `PYTHONPATH=. python tests/integration_tests/run_tests.py <output> --test_suite features --test_name pp_1f1b_cudagraph --execution_mode real_pg --ngpu 2 --no-parallel` (10/10 steps)
stack-info: PR: #4435, branch: xmfan/stack/52
xmfan
force-pushed
the
xmfan/stack/52
branch
from
September 4, 2026 23:56
ea8ad91 to
9660d5d
Compare
xmfan
marked this pull request as ready for review
September 4, 2026 23:57
xmfan
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
September 4, 2026 23:57
tianyu-l
approved these changes
Sep 5, 2026
| ngpu=2, | ||
| use_real_pg=True, | ||
| ), | ||
| OverrideDefinitions( |
Contributor
There was a problem hiding this comment.
instead of adding new one, can we just remove the disable-cuda-graph flag in these two existing tests https://github.com/pytorch/torchtitan/blob/main/tests/integration_tests/features.py#L106-L121
| # The returned loss here is local SUM loss / global_valid_tokens | ||
| return loss | ||
|
|
||
| def pp_forward_backward_step( |
Contributor
There was a problem hiding this comment.
This function becomes pretty short now. To reduce surface, can we inline it back to forward_backward_step?
| train_context: dist_utils.SpmdContext | ||
| fwd_bwd_fn: ForwardBackwardFn | ||
| fwd_bwd_fn: Callable[..., torch.Tensor] | ||
| _pp_loss_sentinel: torch.Tensor |
Contributor
There was a problem hiding this comment.
to make it more readable (at the cost of being verbose)
Suggested change
| _pp_loss_sentinel: torch.Tensor | |
| _pp_loss_sentinel_on_non_last_stage: torch.Tensor |
or whatever you'd propose alternatively.
We probably should broadcast loss to every PP rank though. Not a blocker for this PR
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Sep 5, 2026
## Why
TorchTitan captures the non-pipeline forward-backward function, but pipeline training still executes every schedule eagerly. The pipeline schedule is a suitable graph boundary once input preprocessing remains outside capture and communication order, process groups, tensor structure, and tensor metadata remain static.
This change applies the same full-forward-backward capture model to pipeline schedules.
## Capture boundary
```text
Eager code
|
+--> load microbatches
+--> move tensors to the device
+--> preprocess model inputs
|
v
CUDA graph boundary
|
+--> pipeline schedule
+--> forward computation
+--> pipeline P2P communication
+--> loss computation
+--> backward computation
+--> detached microbatch-loss reduction
|
v
Eager code
|
+--> gradient clipping
+--> optimizer and scheduler steps
+--> metrics reduction and logging
```
## Change
Split pipeline preprocessing from `_pp_forward_backward_body()` and wrap that schedule body when CUDA graphs are enabled. Use a persistent graph-owned loss sentinel on ranks that do not own the last stage.
Expose the upstream deferred-receive control for looped schedules and configure directed P2P process groups before distributed initialization. CUDA-graph pipeline training requires either explicit per-direction process groups or PyTorch automatic TorchComms groups.
Reject pipeline CUDA graphs with validation because validation reinitializes the shared schedule and invalidates the captured training graph.
## Testing
The unit tests cover configuration validation, directed-group initialization, deferred-receive forwarding, structured pipeline inputs, persistent loss output, and wrapper selection.
- `python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_pipeline_parallel.py tests/unit_tests/cpu/test_integration_test_definitions.py`
- `PYTHONPATH=. python tests/integration_tests/run_tests.py <output> --test_suite features --test_name pp_looped_1f1b_cudagraph --ngpu 4` (10/10 steps)
- Deterministic four-GPU eager-versus-graph comparison with seed 42: bitwise-identical loss and `grad_norm` for all 10 steps
stack-info: PR: pytorch/torchtitan#4435, branch: xmfan/stack/52
xmfan
marked this pull request as draft
September 5, 2026 10:07
xmfan
marked this pull request as ready for review
September 5, 2026 10:16
tianyu-l
pushed a commit
that referenced
this pull request
Sep 5, 2026
Stacked PRs: * #4485 * #4435 * #4433 * #4432 * __->__#4430 --- --- --- ### [trainer][pp] Release consumed pipeline loss graphs ## Why The pipeline schedule needs autograd-connected per-microbatch losses until backward finishes. At the end of the schedule, PyTorch extends the Trainer-provided `losses` list with those tensors, then clears its internal list. Clearing the schedule's internal list is insufficient because the Trainer's list now owns the same attached tensors. Previously, TorchTitan stacked those attached losses. The resulting reporting loss retained edges to every microbatch graph. Although `train_step()` later detached a value for metrics, its original `loss` variable could keep the attached aggregate alive through optimization and logging. ## Loss ownership and lifetime ### Common pipeline-schedule path ```text PipelineSchedule._internal_losses [loss_mb0*, loss_mb1*, ...] * attached to autograd | | losses.extend(_internal_losses) | _internal_losses.clear() v Trainer-owned losses [loss_mb0*, loss_mb1*, ...] ``` ### Before ```text Trainer-owned attached losses | | torch.stack(...).sum() v reporting loss* | | returned to train_step() v loss.detach() | +--> accumulated_loss | +--> distributed metric reduction | +--> metrics_processor.log(...) ``` The original reporting loss remains attached while it is still referenced, keeping all of the microbatch graphs reachable. ### After ```text Trainer-owned attached losses | +--> detached_losses = [loss.detach(), ...] | +--> losses.clear() | +--> attached losses and their graphs can be released here Detached losses | | torch.stack(...).sum() v reporting loss without grad_fn | +--> train_step accumulation +--> distributed metric reduction +--> metrics_processor.log(...) ``` ## Change Detach each per-microbatch loss at the Trainer ownership boundary, clear the original loss list, and construct the reporting value only from detached tensors. Out-of-place `detach()` is intentional: losses may be views, for which `detach_()` is invalid, and the Trainer should not mutate aliases held by pipeline schedule code. This does not change forward computation, backward gradients, or the reported loss value. It only shortens the lifetime of completed autograd graphs and their associated activations. ## Testing The unit test verifies: - The reported loss value is unchanged. - Backward produces the expected gradients. - The reporting loss has no `grad_fn`. - The Trainer-owned loss list is cleared. - The original losses and activations are immediately reclaimable. Tested with: - `python -m pytest -q tests/unit_tests/cpu/test_trainer.py -k pp_forward_backward_step_releases_consumed_loss_graphs` - Four-GPU `pp_looped_1f1b_cudagraph` integration run, 10/10 steps.
xmfan
added a commit
to xmfan/torchtitan
that referenced
this pull request
Sep 5, 2026
Manually consolidate pytorch#4432, pytorch#4433, and pytorch#4435 with their review follow-ups on main, which already includes the pipeline loss-lifetime fix from pytorch#4430. Support structured CUDA graph inputs, account for gradient accumulation and SDC during warmup, and capture single-stage pipeline schedules while keeping preprocessing outside capture. Require explicit accumulation and SDC schedule arguments as requested in review.
tianyu-l
pushed a commit
that referenced
this pull request
Sep 6, 2026
Enable CUDA graph capture and replay for pipeline schedules with one stage per rank, including GPipe and 1F1B. Capture the forward-backward schedule while keeping input preprocessing and token accounting outside the captured region. This is a manually squashed consolidation of the previous stack and its review follow-ups: - [#4432: Structured CUDA graph inputs](#4432) - [#4433: Warm up two optimizer steps before capture](#4433) - [#4435: Single-stage pipeline CUDA graph capture](#4435) The original PRs were submitted using stack-pr. After losing upstream write access, updating and landing that stack became difficult; this PR replaces those three unmerged PRs with one commit targeting `main` from `xmfan:cudagraph-review-followups`. It builds on the already merged [#4430: Release consumed pipeline loss graphs](#4430). The wrapper handles structured positional and keyword inputs, checks stable input structure and tensor metadata, and copies new tensor values into capture-owned buffers. Warmup invocation counting lives in `wrap_with_cuda_graph` and accounts for gradient accumulation and finite or continuous SDC replay schedules. As requested in review, `gradient_accumulation_steps`, `sdc_num_steps`, and `sdc_num_replays` are required keyword arguments. Two optimizer steps remain a conservative warmup default, allowing an eager step after lazy optimizer state initialization. Pipeline capture reuses a device-resident loss sentinel on non-last stages. Configuration rejects looped schedules and pipeline validation, which reinitializes the shared schedule. The existing real-process-group 1F1B and PP+FSDP integration recipes now enable CUDA graphs and run 10 training steps. Validation: CI TorchFT changes and the separate CPU override-registry fix remain outside this PR's scope.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked PRs:
[cudagraph] Capture pipeline forward-backward steps
Note: this doesn't add looped schedule support yet, that will need the directed p2p communicators (pytorch/pytorch#195760), a reference of adding support is in #4485.
Why
TorchTitan captures the non-pipeline forward-backward function, but pipeline training still executes every schedule eagerly. A pipeline schedule with one stage per rank is a suitable graph boundary once input preprocessing remains outside capture and communication order, process groups, tensor structure, and tensor metadata remain static.
This change adds CUDA graph capture for single-stage-per-rank pipeline schedules. Looped schedules remain unsupported here because they require separate directed P2P communicators.
Capture boundary
Change
Split pipeline preprocessing from
_pp_forward_backward_body()and select either the pipeline or non-pipeline body through the existingfwd_bwd_fnbefore applying the CUDA graph wrapper. Use a persistent loss sentinel on ranks that do not own the last stage.Reject looped pipeline schedules until their directed P2P communicator dependency is available, and reject pipeline CUDA graphs with validation because validation reinitializes the shared schedule and invalidates the captured training graph.
Testing
The unit tests cover configuration validation, structured pipeline inputs, persistent loss output, and wrapper selection.
python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_integration_test_definitions.pyPYTHONPATH=. python tests/integration_tests/run_tests.py <output> --test_suite features --test_name pp_1f1b_cudagraph --execution_mode real_pg --ngpu 2 --no-parallel(10/10 steps)