Skip to content

[cudagraph] Capture gradient accumulation in one CUDA graph - #4658

Merged
fegin merged 22 commits into
mainfrom
gh/fegin/172/head
Sep 29, 2026
Merged

fegin merged 22 commits into
mainfrom
gh/fegin/172/head

Conversation

@fegin

@fegin fegin commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


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.

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 14, 2026
@fegin fegin changed the title [trainer] Capture gradient accumulation in one CUDA graph [cudagraph] Capture gradient accumulation in one CUDA graph Sep 14, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin marked this pull request as ready for review September 17, 2026 08:25
@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]
Comment thread torchtitan/training_engine.py Outdated
Comment on lines +397 to +401
self._defer_fsdp_gradient_reduction = (
self.parallel_dims.fsdp_enabled
and self.num_accumulation_steps > 1
and not self.config.training.disable_cuda_graphs
)

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.

not totally convinced that we should defer when the 3 conditions are satisfied -- e.g. when cudagraph is disabled (e.g. on a hardware that doesn't support cudagraph), one still enjoy the benefit of reduced comm overhead, wgrad accumulation, etc.

Maybe we can make it a parallelism.fsdp_xxx flag -- xxx could be defer_gradient_reduction

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.

The very first version actually includes one and you suggested that we should assume CUDAGraph is always enabled for this use case. If you prefer, I can add it back.

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.

let me see if I can clarify

  • during offline discussion I was saying "if you enable cudagraph capture, the only mode we support is to defer" -- the reason is that cudagraph itself is advanced & has extra memory overhead, and you probably should have good hardware to run
  • here I'm saying "if you disable cudagraph, you can choose to defer or not to defer" -- point is that the memory overhead (defer) vs. comm & no-fusion overhead (not defer) is a real tradeoff for anyone not using cudagraph.

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.

I think when gradient accumulation is used, people are memory hungry cudagraph or not. So the original design doesn't separate the two. But let's do what you propose for now. If there are use cases, we can extend the support, it is not hard.

Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Outdated
if self.sdc_replayer is not None and accumulation_index == 0:
loss = self.sdc_replayer.run_fwd_bwd(
forward_backward, step=self.num_completed_steps + 1
def _gradient_accumulation_body(

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.

given that from outside it makes more sense to call forward_backward as the training_engine interface, should we

  • call "gradient_accumulation" forward_backward
  • call forward_backward_microbatch / microbatches or forward_backward_step -- I prefer the former so "microbatch(es)" is always explicit; otherwise it's all grad accumulation steps.

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.

Please check if we both agree on the new naming.

[ghstack-poisoned]
[ghstack-poisoned]

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

overall looks great -- had a couple of final questions on logic, and some nits on naming & UX

Comment thread torchtitan/training_engine.py Outdated
return loss

def _pp_forward_backward_body(
def _pp_forward_backward_microbatches(

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.

Suggested change
def _pp_forward_backward_microbatches(
def _pp_forward_backward_microbatch_group(

so that we only use microbatch / microbatch_group / microbatch_groups, not microbatches

Comment thread torchtitan/training_engine.py Outdated
if self.config.training.disable_cuda_graphs:
return

cuda_graph_forward_backward = partial(

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.

Suggested change
cuda_graph_forward_backward = partial(
eager_forward_backward_fn = partial(

Comment thread torchtitan/training_engine.py Outdated
defer_fsdp_gradient_reduction = (
defer_fsdp_gradient_reduction
and self.parallel_dims.fsdp_enabled
and len(microbatch_groups) > 1

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.

don't need this special handling?

Comment thread torchtitan/training_engine.py Outdated
)
return arg_mbs, kwarg_mbs, target_mbs

def _forward_backward_microbatch_groups(

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.

Suggested change
def _forward_backward_microbatch_groups(
def _forward_backward_body(

which

  • more or less matches the public facing forward_backward()
  • save some word, as we never needed to define a function xxx_microbatch_groups
  • more readable as "_body" is what cudagraph captures

Comment thread torchtitan/training_engine.py Outdated

defer_fsdp_gradient_reduction = (
defer_fsdp_gradient_reduction
and self.parallel_dims.fsdp_enabled

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.

somehow feel this is not needed as well, as

  • we apply fully_shard even when dp=cp=1
  • it should be no op

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.

uh, right, we always apply fsdp.

Comment thread torchtitan/training_engine.py Outdated
labels=target_mbs,
loss_kwargs={"global_valid_tokens": global_valid_tokens},
)
run_microbatch_groups = partial(

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 would avoid defining this at all.

if sdc_replay:
  self.sdc_replayer.run_fwd_bwd(partial(), ...)
else:
  result = self._run_forward_backward(preprocessed_microbatch_groups, global_valid_tokens)

Comment thread torchtitan/training_engine.py Outdated

cuda_graph_forward_backward = partial(
self._forward_backward_microbatch_groups,
defer_fsdp_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.

raise value error here if user didn't set it to True

Comment thread torchtitan/training_engine.py Outdated
"""Select eager or CUDA graph execution for gradient accumulation."""

self._run_gradient_accumulation = self._gradient_accumulation_body
if self.config.training.disable_cuda_graphs:

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 think we need that check as well. The point is that

  • on a hardware that doesn't support cudagraph, even if by default disable_cudagraph is false, the code could still run without attempting to capture cudagraph

defer_fsdp_gradient_reduction
and self.config.parallelism.fsdp_reshard_after_forward != "never"
):
raise ValueError(

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.

can happen in post_init of ParallelismConfig, if my earlier suggestion is taken? Not clear why cudagraph makes the difference to error out here.

Actually -- why would cudagraph requires defer + never RAF to be the same? Can I simultaneously

  • enable cudagraph
  • reshard after forward, and always all-gather again
  • but don't reduce-scatter gradient (aka defer)

@fegin fegin Sep 23, 2026 •

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.

Actually -- why would cudagraph requires defer + never RAF to be the same? Can I simultaneously

enable cudagraph
reshard after forward, and always all-gather again
but don't reduce-scatter gradient (aka defer)

This is okay, but I feel that contradict to the argument that with CUDAGraph, we always do defer because that means users have good hardwares. If users have good, why would they ever want to do reshard after forward ?

I don't mind removing the restriction but would like to understand the rationale of why cudagraph enablement makes this special choice.

I would first move the check to post_init but if we later decide to support RAF, I will remove it from the final version.

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.

a point that maybe minor or not minor:
repeating all-gather (RAF) won't change numerics or lose grad fusion opportunity, but sync gradients across microbatches will -- which may make RAF more favorable when you are really in need for some more memory to trade

Comment thread torchtitan/training_engine.py Outdated
fsdp_root.set_is_last_backward(is_last)
fsdp_root.set_reshard_after_backward(is_last)
fsdp_root.set_requires_gradient_sync(is_last)
elif self.parallel_dims.dp_replicate_enabled:

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.

this condition should be outside "if PP else non-PP" -- it matters for PP as well

[ghstack-poisoned]

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

looks great! some final comments

Comment thread torchtitan/training_engine.py Outdated
is_last_accumulation_step = accumulation_index == num_accumulation_steps - 1

if (
not defer_fsdp_gradient_reduction

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.

Is this condition saying

  • if defer, then we don't need special treatment for HSDP -- as anyway it'll only incur all-reduce at the final accumulation step

I think it's fine, but I also believe it works well if we don't have this line, for simplicity?

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.

maybe we should change one of them to SAF="never" as it'd be used to give the best perf

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/172/base to main September 28, 2026 17:23
@fegin
fegin changed the base branch from main to gh/fegin/172/base September 28, 2026 17:24
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/172/base to main September 28, 2026 23:00
@fegin
fegin changed the base branch from main to gh/fegin/172/base September 28, 2026 23:01
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/172/base to main September 29, 2026 07:21
@fegin
fegin merged commit a182e53 into main Sep 29, 2026
39 of 46 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