Repository navigation
[cudagraph] Remove the unsynchronized empty_cache() before accelerator graph capture - #6131
Conversation
…tor graph capture
## Summary (human-written)
There is a race condition if users do not call a sync after step() and
call empty_cache() before the next step().
For the current TorchTitan main, we do call sync in the end of each
iteration to gather the log. However, if we change the logging to async,
this race condition will be exposed.
The race condition happens like this:
```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
AdamW reading those grads is queued on the default stream
step 3: zero_grad(set_to_none=True) frees the grads on the host
-> the blocks return to the reduce-scatter stream's free pool
empty_cache() unmaps free blocks of expandable segments, after
syncing only the reduce-scatter stream
-> the queued AdamW reads unmapped memory: illegal memory access
```
This PR fixes the issue by removing the wrapper's empty_cache(). The graph
capture context (torch.cuda.graph / torch.accelerator.Graph) already calls
synchronize() and then empty_cache() when it starts, so the extra call is
not needed and the race is gone.
## Why
`AcceleratorGraphWrapper` calls `torch.accelerator.empty_cache()` right before it captures a graph, without a sync. If the host runs ahead of the device, this can unmap memory that a queued kernel still reads:
```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
AdamW reading those grads is queued on the default stream
step 3: zero_grad(set_to_none=True) frees the grads on the host
-> the blocks return to the reduce-scatter stream's free pool
empty_cache() unmaps free blocks of expandable segments, after
syncing only the reduce-scatter stream
-> the queued AdamW reads unmapped memory: illegal memory access
```
On main, a blocking host-to-device copy of the token counts in `Trainer.train_step` waits for the previous optimizer step before `zero_grad`, so the host never gets this far ahead. "[trainer] Log training metrics without waiting for the device", later in this stack, removes that copy and exposes the crash: llama3 debug model, FSDP2 on 2 GPUs, `expandable_segments:True` (set by `run_train.sh`), crashes in step 2-3 with varlen, flex, and CP2.
The call is not needed. The capture context that runs right after it, `torch.cuda.graph` or `torch.accelerator.Graph`, already calls `synchronize()` and then `empty_cache()` in `__enter__`.
## What changed
- Remove the wrapper's `empty_cache()` and its `before_empty_cache` / `after_empty_cache` memory logs. The capture context releases the same cache, after a device sync.
- `ACCELERATOR_GRAPH.md` says the capture context empties the cache.
- `test_preparation_runs_only_before_first_capture` (renamed) expects no `empty_cache()` call from the wrapper.
The underlying gap is in PyTorch. FSDP2 orders the reuse of gradient blocks with stream events, which covers normal allocations but not `empty_cache()`. The expandable-segment unmap waits only for the stream that allocated the block, while a plain `cudaFree` syncs the device. A single-GPU repro without torchtitan crashes with expandable segments, and passes with a `record_stream` before the free or a sync before `empty_cache()`. The optimizer's first-step `empty_cache()` already syncs first (#5019). The other call runs at startup.
## Testing
- With the host running ahead ("[trainer] Log training metrics without waiting for the device"), llama3 debug model on 2 GPUs, `log_freq=10`, 20 steps: with the wrapper's unsynchronized call, varlen, flex, and CP2 each crash 3 of 3 runs; with it removed all pass 3 of 3. A GPU coredump puts the fault in the fused AdamW kernel, on gradients in segments owned by FSDP2's reduce-scatter stream.
- On another 4-GPU host the debug model does not get far enough ahead to crash. With an ~80 ms GPU sleep added before each AdamW step, the wrapper's unsynchronized call crashes 8 of 9 runs (varlen, flex, CP2) and this change passes 9 of 9.
- Losses and grad_norm match a `CUDA_LAUNCH_BLOCKING=1` run of the same config (varlen with `debug.deterministic=True`).
This change was written with an AI assistant (Claude).
stack-info: PR: #6131, branch: fegin/stack/38
e402323 to
acfa162
Compare
|
@claude review this PR |
There was a problem hiding this comment.
Verdict: Approve -- the removed empty_cache() duplicates work the capture context already does after a device sync, so deleting it fixes the race and removes code. A maintainer still needs to review, since this touches torchtitan/distributed/.
What this PR does. Before its first capture, AcceleratorGraphWrapper.__call__ called torch.accelerator.empty_cache() with no sync, with debug memory logs on either side. The PR deletes those three lines. The next call, accelerator_graph_manager.capture() (accelerator_graph.py:288-316), enters torch.cuda.graph(...) or torch.accelerator.Graph(...), and that context already runs synchronize() and then empty_cache() in __enter__. The memory release stays the same; only the unsynchronized call goes away.
Example. FSDP2, expandable_segments:True, with the host running ahead of the device (later in this stack):
before: zero_grad frees grads -> wrapper empty_cache() unmaps the free
expandable-segment blocks (syncs only the RS stream)
-> queued AdamW on the default stream reads unmapped memory -> IMA
after: zero_grad frees grads -> torch.cuda.graph.__enter__:
synchronize() -> empty_cache() -> capture; no in-flight kernel
can still be using the released blocks
Questions
- The description puts the root cause in PyTorch: the expandable-segment unmap in
empty_cache()waits only on the allocating stream, while FSDP2 orders reuse with events. Is there an upstream issue for this? If so, consider linking it next to the existing sync-before-empty_cache()comment attorchtitan/components/optim/optim.py:160, so that the next person who adds an unsynchronizedempty_cache()sees why it is unsafe. This can go in a follow-up; it shouldn't block this PR.
Details
- Necessity: on
mainthe race is hidden by the blocking H2D token-count copy inTrainer.train_step, so this PR is a prerequisite for the async-logging PR later in the stack. It is a valid change on its own merits too, because the call was redundant. - Other
empty_cache()callers in core:optim.py:170syncs first when the device is initialized (when it isn't, no device work can be in flight).observability/metrics.py:66runs at startup, before any training-step work. - The non-CUDA path (
with self.stream, graph:) enters the stream context before the graph, so the graph's sync and cache release happen before capture starts, the same as on CUDA. - Test: the
torch.accelerator.empty_cachepatch intest_preparation_runs_only_before_first_capturestays, and the test now fails if the wrapper callsempty_cache()again. That is the regression it guards.torch.cuda.graphis mocked, so the test does not check the capture context's own release, which is fine. - Debug logs: dropping
before_empty_cache/after_empty_cacheleavesafter_captureas the onlylog_memoryboundary. Nothing else in the repo reads those boundary names.
Not verified: that torch.accelerator.Graph.__enter__ (non-CUDA backends) syncs and empties the cache the way torch.cuda.graph.__enter__ does. I couldn't inspect the installed torch in this environment. The GPU crash and pass counts in the description were not reproduced here.
Stacked PRs:
[cudagraph] Remove the unsynchronized empty_cache() before accelerator graph capture
Summary (human-written)
There is a race condition if users do not call a sync after step() and
call empty_cache() before the next step().
For the current TorchTitan main, we do call sync in the end of each
iteration to gather the log. However, if we change the logging to async,
this race condition will be exposed.
The race condition happens like this:
This PR fixes the issue by removing the wrapper's empty_cache(). The graph
capture context (torch.cuda.graph / torch.accelerator.Graph) already calls
synchronize() and then empty_cache() when it starts, so the extra call is
not needed and the race is gone.
Why
AcceleratorGraphWrappercallstorch.accelerator.empty_cache()right before it captures a graph, without a sync. If the host runs ahead of the device, this can unmap memory that a queued kernel still reads:On main, a blocking host-to-device copy of the token counts in
Trainer.train_stepwaits for the previous optimizer step beforezero_grad, so the host never gets this far ahead. "[trainer] Log training metrics without waiting for the device", later in this stack, removes that copy and exposes the crash: llama3 debug model, FSDP2 on 2 GPUs,expandable_segments:True(set byrun_train.sh), crashes in step 2-3 with varlen, flex, and CP2.The call is not needed. The capture context that runs right after it,
torch.cuda.graphortorch.accelerator.Graph, already callssynchronize()and thenempty_cache()in__enter__.What changed
empty_cache()and itsbefore_empty_cache/after_empty_cachememory logs. The capture context releases the same cache, after a device sync.ACCELERATOR_GRAPH.mdsays the capture context empties the cache.test_preparation_runs_only_before_first_capture(renamed) expects noempty_cache()call from the wrapper.The underlying gap is in PyTorch. FSDP2 orders the reuse of gradient blocks with stream events, which covers normal allocations but not
empty_cache(). The expandable-segment unmap waits only for the stream that allocated the block, while a plaincudaFreesyncs the device. A single-GPU repro without torchtitan crashes with expandable segments, and passes with arecord_streambefore the free or a sync beforeempty_cache(). The optimizer's first-stepempty_cache()already syncs first (#5019). The other call runs at startup.Testing
log_freq=10, 20 steps: with the wrapper's unsynchronized call, varlen, flex, and CP2 each crash 3 of 3 runs; with it removed all pass 3 of 3. A GPU coredump puts the fault in the fused AdamW kernel, on gradients in segments owned by FSDP2's reduce-scatter stream.CUDA_LAUNCH_BLOCKING=1run of the same config (varlen withdebug.deterministic=True).This change was written with an AI assistant (Claude).