Skip to content

[cudagraph] Support non-deferred gradient accumulation - #5050

Merged
sanketpurandare merged 1 commit into
mainfrom
sanket/cudagraph-nondeferred-ga
Oct 4, 2026
Merged

sanketpurandare merged 1 commit into
mainfrom
sanket/cudagraph-nondeferred-ga

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

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. _CUDAGraphGradientState records those tensors after capture and restores each param.grad reference 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

  • Focused unit test exercises two accumulation groups with fsdp_defer_gradient_reduction=False.
  • Real two-GPU FSDP run completed two eager warmups, CUDA-graph capture, replay, optimizer updates, and clean process-group teardown with finite loss and gradient norms.
  • A full DP64/TP4/EP64, GA16 logical-topology validation completed ten steps with whole-step capture/replay and finite training state.
  • Repository formatting, AST, whitespace, license, flake8, pydoclint, codespell, and link checks pass. Pyrefly reports two unrelated errors already present on main in 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

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 4, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label 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."
)

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.

@fegin I forgot, why did we have this limitation?

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.

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

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.

It was tested with @fegin 's fix pytorch/pytorch#199677. So @fegin land the pytorch fix first

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.

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

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
sanketpurandare force-pushed the sanket/cudagraph-nondeferred-ga branch from 44fee5e to 0ed651f Compare October 4, 2026 21:55
@sanketpurandare
sanketpurandare merged commit 52f603d into main Oct 4, 2026
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>
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 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.

3 participants