Skip to content

[cudagraph] Remove the unsynchronized empty_cache() before accelerator graph capture - #6131

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/38
Nov 17, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/38

Conversation

@fegin

@fegin fegin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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:

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:

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).

…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
@fegin

fegin commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@fegin fegin changed the title [distributed] Remove the unsynchronized empty_cache() before accelerator graph capture [cudagraph] Remove the unsynchronized empty_cache() before accelerator graph capture Nov 16, 2026
@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 1m 39s —— View job


Approve: the removed empty_cache() duplicated the sync-then-release that the capture context already does, so deleting it fixes the race. Review

@claude claude Bot left a comment

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.

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 at torchtitan/components/optim/optim.py:160, so that the next person who adds an unsynchronized empty_cache() sees why it is unsafe. This can go in a follow-up; it shouldn't block this PR.
Details
  • Necessity: on main the race is hidden by the blocking H2D token-count copy in Trainer.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:170 syncs first when the device is initialized (when it isn't, no device work can be in flight). observability/metrics.py:66 runs 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_cache patch in test_preparation_runs_only_before_first_capture stays, and the test now fails if the wrapper calls empty_cache() again. That is the regression it guards. torch.cuda.graph is mocked, so the test does not check the capture context's own release, which is fine.
  • Debug logs: dropping before_empty_cache/after_empty_cache leaves after_capture as the only log_memory boundary. 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.

@fegin
fegin marked this pull request as ready for review November 16, 2026 22:24
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 16, 2026
@fegin
fegin merged commit d83f56a into main Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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