Skip to content

[cudagraph] Reuse graph-owned parameter gradients - #4659

Merged
fegin merged 30 commits into
mainfrom
gh/fegin/173/head
Sep 29, 2026
Merged

fegin merged 30 commits into
mainfrom
gh/fegin/173/head

Conversation

@fegin

@fegin fegin commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


  • Clear parameter gradients to None in Trainer and FaultTolerantTrainer.
  • Keep capture-created gradient buffers alive and restore them after replay.
  • Require capture and replay to start without pending gradients.

Why this state can reduce memory use:

1. ``set_to_none=True`` without ``CUDAGraphGradientState`` fails after the
   first capture.
   Autograd allocates a gradient during capture and assigns it to
   ``param.grad``. The next ``zero_grad`` clears that Python reference.
   CUDA graph replay runs the captured GPU work, but it does not repeat the
   ``param.grad`` assignment. The optimizer then sees ``param.grad is None``
   and skips the parameter update.

2. ``set_to_none=False`` avoids that failure, but eager warmup allocates the
   gradient before capture, outside the CUDA graph memory pool. Capture only
   records writes into that existing gradient buffer. Its lifetime overlaps
   the complete forward-backward graph::

       time           forward             backward          optimizer
       gradient       [===============================================]
       forward temp   [==========]
       backward temp                       [=========]

   The graph allocator cannot reuse the gradient storage for these temporary
   tensors because their lifetimes overlap.

3. With ``CUDAGraphGradientState``, ``set_to_none=True`` leaves gradients
   absent when capture starts. Autograd allocates them from the CUDA graph
   memory pool during backward, after many forward tensors have expired::

       time           forward             backward          optimizer
       forward temp   [==========]
       gradient                            [=========================]
       shared block   [forward temp]       [gradient                 ]

   During capture, the CUDA graph pool may reuse storage released by forward
   tensors for later gradients. This state then keeps those gradient tensors
   alive and restores each ``param.grad`` reference after replay. This makes
   ``set_to_none=True`` safe.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin marked this pull request as ready for review September 17, 2026 08:26
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 17, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/distributed/cuda_graph.py Outdated
tensor_input_indices: Sequence[int] | None = None,
*,
num_warmup_iterations: int,
gradient_state: CUDAGraphGradientState | None = None,

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.

would it ever be None?

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.

yes, this wrapper is also used by optimizer which doesn't have the gradient_state.

Comment thread torchtitan/distributed/cuda_graph.py Outdated
Comment on lines +130 to +131
self.parameters = tuple(unique_parameters)
self._gradients: tuple[

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.

naming seems not consistent

[ghstack-poisoned]
[ghstack-poisoned]
Comment thread torchtitan/distributed/cuda_graph.py Outdated
def wrap_with_cuda_graph(
fn: Callable[..., Any],
*,
gradient_state: CUDAGraphGradientState | None = None,

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 don't feel particularly safe, when something not fwd-bwd can call this function, with this field exposed. But doesn't seem to be worth blocking on this.

[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin requested a review from IvanKobzarev as a code owner September 25, 2026 19:48
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 29, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4662
* #4661
* #4660
* #4659
* __->__ #4658

----
**Conflict with #4649, need
to discuss how to incorporate with
#4649
**Depend on pytorch/pytorch#196640 and
pytorch/pytorch#196641

- Add `parallelism.fsdp_defer_gradient_reduction` to reduce gradients
after the final backward of a gradient accumulation group.
- Replay the whole optimizer step during SDC checks.
- Use the public FSDP and pipeline finalization APIs.
@fegin
fegin changed the base branch from gh/fegin/173/base to main September 29, 2026 07:56
@fegin
fegin changed the base branch from main to gh/fegin/173/base September 29, 2026 07:58
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/173/base to main September 29, 2026 08:00
@fegin
fegin changed the base branch from main to gh/fegin/173/base September 29, 2026 08:10
@fegin
fegin changed the base branch from gh/fegin/173/base to main September 29, 2026 15:01
@fegin
fegin merged commit 8653613 into main Sep 29, 2026
26 of 27 checks passed
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