Skip to content

[cudagraph] Warm up two optimizer steps before capture - #4433

Closed
xmfan wants to merge 1 commit into
xmfan/stack/49from
xmfan/stack/50
Closed

xmfan wants to merge 1 commit into
xmfan/stack/49from
xmfan/stack/50

Conversation

@xmfan

@xmfan xmfan commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[cudagraph] Warm up two optimizer steps before capture

Why

Only the forward-backward callable is captured; the optimizer runs eagerly. Warmup gives the forward-backward path an opportunity to perform lazy initialization before capture and lets the first optimizer step initialize its state. The Trainer zeroes existing gradients in place when CUDA graphs are enabled, preserving their storage for replay.

Two full optimizer steps are a conservative default: the second exercises an eager forward-backward invocation after the first optimizer update. One full optimizer step may be sufficient. We have not established a failure that requires a second step, and a fixed warmup count does not guarantee that every configuration has completed all lazy initialization.

One forward-backward invocation is also not one optimizer step: gradient accumulation runs several invocations per step, and scheduled SDC replay re-executes checked invocations.

Capture timing

Optimizer step 1
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> lazy optimizer-state allocation

Optimizer step 2
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> another eager step after the first optimizer update

Optimizer step 3
    +--> capture the next forward/backward invocation
    +--> replay thereafter

The warmup count is measured in wrapped forward-backward invocations:

2 * gradient_accumulation_steps
+ checked_warmup_steps * sdc_num_replays

Change

Add a num_warmup_iterations option to CUDAGraphWrapper, validated in its constructor. The wrapper counts eager forward-backward invocations before capture. The default training policy allows two complete optimizer steps, including gradient accumulation and additional SDC replay calls, before capture starts.

Testing

The tests cover explicit and invalid warmup counts, gradient accumulation, finite and continuous SDC schedules, and forwarding the configured count into the graph wrapper.

  • python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py
  • python -m tests.integration_tests.run_tests <output> --test_suite features --test_name sdc_replay_cudagraph --execution_mode real_pg --ngpu 1 --no-parallel (capture begins on step 3)
  • Full stack: four-GPU pp_looped_1f1b_cudagraph integration, eager steps 1-2, capture on step 3, replay through step 10

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 3, 2026
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 3, 2026 01:20
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 3, 2026 01:21
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 3, 2026 06:13
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 3, 2026 06:14
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 4, 2026 18:31
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 4, 2026 18:31
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 4, 2026
## Why

One eager forward-backward invocation is not enough to establish steady-state training storage. Optimizers may allocate state lazily during their first `step()`, and gradient accumulation may invoke forward-backward several times before one optimizer step.

Capturing before those allocations stabilize can leave persistent allocations outside the graph pool or record a non-steady-state memory layout.

## Capture timing

```text
Optimizer step 1
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> lazy optimizer-state allocation

Optimizer step 2
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> steady-state allocator behavior

Optimizer step 3
    +--> capture the next forward/backward invocation
    +--> replay thereafter
```

The warmup count is measured in wrapped forward-backward invocations:

```text
2 * gradient_accumulation_steps
+ checked_warmup_steps * sdc_num_replays
```

## Change

Add a validated `num_warmup_iterations` option to `CUDAGraphWrapper` and its convenience wrapper. The Trainer computes the number of invocations performed during the first two optimizer steps, including additional executions made by scheduled SDC replay.

Capture therefore begins only after optimizer state, gradients, and allocator behavior have reached their steady-state layout.

## Testing

The tests cover explicit and invalid warmup counts, gradient accumulation, finite and continuous SDC schedules, and forwarding the configured count into the graph wrapper.

- `python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py`
- `python -m tests.integration_tests.run_tests <output> --test_suite features --test_name sdc_replay_cudagraph --execution_mode real_pg --ngpu 1 --no-parallel` (capture begins on step 3)
- Full stack: four-GPU `pp_looped_1f1b_cudagraph` integration, eager steps 1-2, capture on step 3, replay through step 10

stack-info: PR: pytorch/torchtitan#4433, branch: xmfan/stack/50
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 4, 2026 20:52
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 4, 2026 20:52
Comment thread torchtitan/trainer.py

def _num_cuda_graph_warmup_iterations(self) -> int:
num_warmup_steps = 2
num_iterations = num_warmup_steps * self.gradient_accumulation_steps

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.

This is a bit awkward. So we can't wrap train step (lots of non-cudagraphable stuff), and must wrap the inner fwd bwd function. So when we want to warm up a number of train steps, we have to compute the number of cudagraph wrapped skips

@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 4, 2026 22:00
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 4, 2026 22:00
## Why

Only the forward-backward callable is captured; the optimizer always runs eagerly. Warmup is still required because capture permanently freezes device addresses and the graph memory pool, and the first training steps change both:

- The captured backward writes into `param.grad` at baked-in addresses. With CUDA graphs enabled the Trainer zeroes gradients in place (`set_to_none=False`), so gradient buffers are allocated once, by the first eager backward. Capturing earlier would allocate them inside the capture as graph-pool storage that the eager optimizer then reads behind the graph's back.

- The optimizer allocates its state lazily during its first `step()`. Every tensor alive when capture ends becomes a permanent resident of the private graph pool, so long-lived global allocations (optimizer state, gradients, cuBLAS and NCCL workspaces) must exist before the pool is carved out. Capturing earlier records an allocator layout that never recurs and fragments the pool against the later persistent allocations.

- First iterations perform one-time lazy initialization (cuBLAS workspace allocation and algorithm selection, NCCL communicator setup, autograd engine startup) that is forbidden during stream capture. PyTorch's graph APIs bake in side-stream warmup for the same reason: `make_graphed_callables` defaults to 3 warmup iterations and the DDP recipe recommends 11.

One optimizer step is not enough: step 1 performs the one-time allocations above, so the steady-state per-step cycle (gradients accumulated then zeroed in place, optimizer state updated in place) only starts repeating from step 2. Running two full steps eagerly and capturing on step 3 guarantees the recorded invocation matches every subsequent step.

One forward-backward invocation is also not one optimizer step: gradient accumulation runs several invocations per step, and scheduled SDC replay re-executes checked invocations.

## Capture timing

```text
Optimizer step 1
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> lazy optimizer-state allocation

Optimizer step 2
    +--> gradient-accumulation forward/backward calls
    +--> scheduled SDC replay calls
    +--> steady-state allocator behavior

Optimizer step 3
    +--> capture the next forward/backward invocation
    +--> replay thereafter
```

The warmup count is measured in wrapped forward-backward invocations:

```text
2 * gradient_accumulation_steps
+ checked_warmup_steps * sdc_num_replays
```

## Change

Add a `num_warmup_iterations` option to `CUDAGraphWrapper`, validated in its constructor, and thread it through `wrap_with_cuda_graph`. The Trainer computes the number of invocations performed during the first two optimizer steps, including additional executions made by scheduled SDC replay.

Capture therefore begins only after optimizer state, gradients, and allocator behavior have reached their steady-state layout.

## Testing

The tests cover explicit and invalid warmup counts, gradient accumulation, finite and continuous SDC schedules, and forwarding the configured count into the graph wrapper.

- `python -m pytest -q tests/unit_tests/cpu/test_cudagraph.py tests/unit_tests/cpu/test_trainer.py`
- `python -m tests.integration_tests.run_tests <output> --test_suite features --test_name sdc_replay_cudagraph --execution_mode real_pg --ngpu 1 --no-parallel` (capture begins on step 3)
- Full stack: four-GPU `pp_looped_1f1b_cudagraph` integration, eager steps 1-2, capture on step 3, replay through step 10

stack-info: PR: #4433, branch: xmfan/stack/50
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 4, 2026 22:06
@xmfan xmfan changed the title [do-not-review] [cudagraph] Warm up two optimizer steps before capture [cudagraph] Warm up two optimizer steps before capture Sep 4, 2026
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 4, 2026 22:06
@xmfan
xmfan marked this pull request as ready for review September 4, 2026 22:15
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 4, 2026 23:56
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 4, 2026 23:56
Comment thread torchtitan/trainer.py
f"(warmup {config.lr_scheduler.warmup_steps})"
)

def _num_cuda_graph_warmup_iterations(self) -> int:

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.

I'd prefer this happens inside cudagraph.py. E.g. we can send gradient_accumulation_steps, sdc_config.num_steps, and sdc_config.num_replays into wrap_with_cuda_graph.

Comment thread torchtitan/trainer.py
return torch.tensor([-1.0], device=self.device)

def train_step(self, data_iterator: Iterator[TrainerBatch]):
self.optimizers.zero_grad(set_to_none=self.config.training.disable_cuda_graphs)

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.

regarding

The captured backward writes into param.grad at baked-in addresses. With CUDA graphs enabled the Trainer zeroes gradients in place (set_to_none=False), so gradient buffers are allocated once, by the first eager backward. Capturing earlier would allocate them inside the capture as graph-pool storage that the eager optimizer then reads behind the graph's back.

Due to memory concerns, I think we'll need to apply @BoyuanFeng 's trick to not allocating cudagraph buffer for FSDP-sharded gradients. But yeah we probably still need warmup for other reasons.

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.

Comment thread torchtitan/trainer.py
)

def _num_cuda_graph_warmup_iterations(self) -> int:
num_warmup_steps = 2

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.

One optimizer step is not enough: step 1 performs the one-time allocations above, so the steady-state per-step cycle (gradients accumulated then zeroed in place, optimizer state updated in place) only starts repeating from step 2. Running two full steps eagerly and capturing on step 3 guarantees the recorded invocation matches every subsequent step.

I might have missed something -- why warming up 2 steps instead of just 1, i.e. what makes step 2 and step 3 different?

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.

1 step warmup can be sufficient, but it's implementation dependent, and I'm not sure if @sanketpurandare actually hit an issue there.

In theory, you could have lazy state that initializes only the step after optimizer states are initializes, and changes the memory allocation pattern. But if there's none, 1 step should be fine.

@xmfan
xmfan marked this pull request as draft September 5, 2026 10:07
@xmfan
xmfan changed the base branch from xmfan/stack/49 to main September 5, 2026 10:07
@xmfan
xmfan changed the base branch from main to xmfan/stack/49 September 5, 2026 10:15
@xmfan
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.
@xmfan xmfan closed this Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants