Repository navigation
[cudagraph] Support non-deferred gradient accumulation - #5050
Merged
Merged
Conversation
sanketpurandare
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
October 4, 2026 20:53
tianyu-l
reviewed
Oct 4, 2026
Comment on lines
-475
to
-482
| if ( | ||
| len(microbatch_groups) > 1 | ||
| and not self.config.parallelism.fsdp_defer_gradient_reduction | ||
| ): | ||
| raise ValueError( | ||
| "CUDA graph gradient accumulation requires " | ||
| "parallelism.fsdp_defer_gradient_reduction=True." | ||
| ) |
Contributor
There was a problem hiding this comment.
@fegin I forgot, why did we have this limitation?
Contributor
Author
There was a problem hiding this comment.
No idea, it works perfectly. We were worried that cudagraphs might produce sharded grads which need to alive throughout, but it is fine for the sharded grads to be alive throughout. No memory regression, unified cudagraph logic
Contributor
Author
There was a problem hiding this comment.
It was tested with @fegin 's fix pytorch/pytorch#199677. So @fegin land the pytorch fix first
Contributor
There was a problem hiding this comment.
@tianyu-l In my mind this check was added after the first draft version after some discussions. But since you stamped the PR, I might misunderstand the discussion.
tianyu-l
approved these changes
Oct 4, 2026
Whole-step CUDA graphs already capture the complete outer accumulation loop. The forward/backward graph wrapper records the capture-created parameter gradients and restores their Python param.grad references after every replay, so per-microbatch FSDP reduction does not require a separate graph or deferred reduction. Remove the stale validation wrapper and pass the existing forward/backward callable directly to the CUDA-graph wrapper. Update the focused unit test to prove that two accumulation groups execute with fsdp_defer_gradient_reduction=False. Test: python -m pytest -q tests/unit_tests/cpu/test_trainer.py -k cuda_graph_accumulation_supports_eager_gradient_reduction
sanketpurandare
force-pushed
the
sanket/cudagraph-nondeferred-ga
branch
from
October 4, 2026 21:55
44fee5e to
0ed651f
Compare
sanketpurandare
added a commit
that referenced
this pull request
Oct 4, 2026
## Motivation The Dist-MoE annex supports two post-expert policies: typed fused descriptors and eager callables. TorchTitan currently accepts only `RMSNormPostprocess`, preventing a model-owned learned postprocess module from using the annex eager path while retaining normal module, optimizer, FSDP, checkpoint, hook, and autograd ownership. ## Design Allow `to_dist_moe_postprocess()` to return either `dist_moe.RMSNormPostprocess` or any callable. TorchTitan forwards the exact returned object to `dist_moe.ExecutionOptions`; it does not execute, wrap, copy, or reinterpret the callback. Returning the module itself therefore preserves `nn.Module.__call__`, forward hooks, parameters in the state dict, and ordinary input/parameter gradients. The existing invalid-result check remains strict: objects that are neither the typed descriptor nor callable fail at the TorchTitan integration boundary. Annex marks callable policies as eager, so this does not claim arbitrary-callback make_fx or GraphTrainer support. ## Verification - Focused callback test proves exact object identity and eager-policy selection. - A registered module forward hook executes exactly once. - Input and learned-parameter gradients are produced through ordinary autograd. - The learned parameter remains in the module state dict. - Invalid factory output raises the actionable integration error. - Common Dist-MoE plus stacked CUDA-graph selection: 32 passed, 37 deselected. - Repository formatting, AST, whitespace, license, flake8, pydoclint, codespell, and link checks pass. Pyrefly reports the same two unrelated `main` errors described in the lower PR. This PR is the upper layer of the native GitHub stack and is based on #5050. --- <sub>Stack created with <a href="https://github.com/github/gh-stack">GitHub Stacks CLI</a></sub>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
TorchTitan captures the complete forward/backward accumulation loop as one CUDA graph. The existing wrapper nevertheless rejects more than one outer accumulation group unless FSDP gradient reduction is deferred. That restriction predates whole-step capture and prevents valid configurations that reduce and accumulate sharded gradients after every microbatch.
Design
Pass the existing forward/backward callable directly to
wrap_fwd_bwd_with_cuda_graph.zero_grad(set_to_none=True)clears Python gradient references before invocation. During capture, the first microbatch creates graph-owned parameter gradients and later microbatches accumulate into them._CUDAGraphGradientStaterecords those tensors after capture and restores eachparam.gradreference after replay, since CUDA replay does not repeat Python assignment.This changes no eager behavior, collective count, reduction dtype, or FSDP reduction timing. It removes only the stale deferred-reduction validation wrapper.
Verification
fsdp_defer_gradient_reduction=False.mainin activation checkpointing and multimedia video typing.The Dist-MoE scale composition used for validation also requires the pending PyTorch FSDP stream-ownership fix in pytorch/pytorch#199677.
Stack created with GitHub Stacks CLI