Repository navigation
[trainer][pp] Release consumed pipeline loss graphs - #4430
Conversation
0beb68b to
e314315
Compare
85b5c7e to
ac20b45
Compare
e314315 to
4366ec2
Compare
4366ec2 to
e60eb52
Compare
da62423 to
c584ac0
Compare
e60eb52 to
4abc557
Compare
| assert losses is not None | ||
| return torch.sum(torch.stack(losses)).to(self.device) | ||
| # Backward has consumed these losses. Report through detached views, | ||
| # then release the original tensors and their autograd graphs. |
There was a problem hiding this comment.
noob question: what's the net benefit of releasing autograd graphs -- is it for memory overhead reduction?
I saw you mentioned
Four-GPU pp_looped_1f1b_cudagraph integration run, 10/10 steps.
Does it mean 1f1b can run with cudagraph? If so should we remove some disable-cuda-graph flag in CI?
There was a problem hiding this comment.
what's the net benefit of releasing autograd graphs
There's 1 reason because of PP di/dw, 1 generic reason for custom autograd functions, and 1 reason because of cudagraphs. And they compound on each other and make the situation worse:
1- For di/dw: retain_graph=False is the default option for .backward() and autograd.grad(), but it only clears the saved activations that the autograd engine passes through. When we implement di/dw with this API, we do something like autograd.grad(inputs=inputs, retain_graph=True) and then autograd.grad(inputs=weights, retain_graph=False). This means that the saved activations for nodes only on the path of di but not on the path of dw will not be freed until all tensors this autograd graph (usually loss tensor, or other tensors held on for logging) go out of scope cc @soulitzer. This detach and clear makes this memory freed at the end of the schedule step instead of the end of train_step.
Here's some potentially held activations according to Fable:
- Attention core: SDPA/FlexAttention saves q, k, v, the attention output, and logsumexp for its backward — all B×H×L×D-scale tensors, and the QK^T/softmax internals if it's an unfused implementation. SDPA has no parameters; dW for the QKV/output projections only needs the projections' own saved inputs.
- RoPE application: saved inputs/cos/sin for the rotation backward.
- SwiGLU internals: the SiLU node saves its input (w1(x)), and the elementwise mul saves both operands (silu(w1(x)) and w3(x)). The w1/w2/w3 matmul nodes themselves are on the weight path and get freed; the glue between them isn't.
- MoE routing: router softmax/top-k saves, the gather/scatter index tensors, the combine-weighted sums.
- On the loss-owning stage: the cross-entropy node's saved log-softmax (L×V) — one of the single largest saves in the graph — is parameter-free, so it's pass-1-only. (The lm_head matmul's saved hidden states, by contrast, are needed for its dW and get freed.)
2- Only the tensors on ctx.save_for_backward are freed at the end of a autograd call with retain_graph=False, a custom autograd function that does some ctx.x = tensor is only freed once the autograd graph goes out of scope.
3- Cudagraphs (problem after #4435). Our cudagraph implementations maintain their own private memory pools, and any tensor that escapes the cudagraph always needs to exist in the pool (so that CG can write to that address every replay). If you instead capture the losses.clear and sum
BEFORE PR
torch.cuda.graph capture of _pp_forward_backward_body
|
+--> pp_schedule.step()
| losses = [loss_mb0*, loss_mb1*, ...] * attached
|
+--> return torch.sum(torch.stack(losses)) # attached aggregate
|
v
capture ends -- liveness snapshot taken here
alive at capture end:
reporting loss*
grad_fn: SumBackward -> StackBackward
-> loss_mb0.grad_fn subgraph -> retained dI-only saves
-> loss_mb1.grad_fn subgraph -> retained dI-only saves
-> ...
AFTER PR
torch.cuda.graph capture of _pp_forward_backward_body
|
+--> pp_schedule.step()
| losses = [loss_mb0*, loss_mb1*, ...]
|
+--> detached_losses = [l.detach() for l in losses]
+--> losses.clear()
| last roots into the microbatch graphs die HERE,
| still inside capture -> allocator recycles their
| blocks within the pool during capture itself
|
+--> return torch.sum(torch.stack(detached_losses)) # grad_fn=None
|
v
capture ends
alive at capture end:
one detached reporting tensor (the graph's designated output)
Does it mean 1f1b can run with cudagraph? If so should we remove some disable-cuda-graph flag in CI?
The tests were ran on the whole stack, so only in the later pr that lands pp + cg
There was a problem hiding this comment.
Very cool, thanks for explaining!
## 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.
stack-info: PR: #4430, branch: xmfan/stack/47
4abc557 to
d4a9868
Compare
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.
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.
Stacked PRs:
[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
losseslist 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 originallossvariable could keep the attached aggregate alive through optimization and logging.Loss ownership and lifetime
Common pipeline-schedule path
Before
The original reporting loss remains attached while it is still referenced, keeping all of the microbatch graphs reachable.
After
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 whichdetach_()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:
grad_fn.Tested with:
python -m pytest -q tests/unit_tests/cpu/test_trainer.py -k pp_forward_backward_step_releases_consumed_loss_graphspp_looped_1f1b_cudagraphintegration run, 10/10 steps.