Skip to content

[GraphTrainer][AutoDev] Enable cudagraph in aot_fx_trace mode - #2868

Merged
SherlockNoMad merged 8 commits into
mainfrom
graph_trainer/enable-cudagraph
Apr 9, 2026
Merged

SherlockNoMad merged 8 commits into
mainfrom
graph_trainer/enable-cudagraph

Conversation

@SherlockNoMad

Copy link
Copy Markdown
Contributor

Summary

  • Integrates cudagraph_pass into apply_default_graph_passes so the aot_fx_trace compile path wraps the traced fwd+bwd graph with CUDAGraphWrapper.
  • Parameters and buffers are identified as static inputs (stable tensor addresses across training steps) to avoid redundant copies during cudagraph replay.
  • Improves cudagraph_pass to accept static_input_indices directly, as an alternative to the is_forward flag used by the AOT path.

Test plan

  • Existing bitwise deterministic test (test_bitwise_deterministic.py) now exercises cudagraph in the aot_fx_trace path — verifies bitwise identical losses/gradients vs eager for both Llama3 and DeepSeek-v3.
  • Existing numerics tests (test_llama3_aot_fx_trace_vs_eager, test_dsv3_aot_fx_trace_vs_eager) verify cudagraph-wrapped aot_fx_trace matches eager FSDP2.
  • Integration tests updated: aot_fx_trace tests now reflect cudagraph usage and skip ROCm (cudagraph not supported there).
  • AOT mode cudagraph tests remain unchanged and continue to pass.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 7, 2026
@SherlockNoMad SherlockNoMad changed the title [GraphTrainer] Enable cudagraph in aot_fx_trace mode [GraphTrainer][AutoDev] Enable cudagraph in aot_fx_trace mode Apr 7, 2026
SherlockNoMad added a commit that referenced this pull request Apr 7, 2026
…ypes

The aot_fx_trace joint graph can have float-valued inputs (e.g.
global_valid_tokens scaling factor). Add float to the supported input
types so that CUDAGraphWrapper does not reject these inputs during
recording.

Spun off from PR #2868 review feedback.
SherlockNoMad added a commit that referenced this pull request Apr 7, 2026
## Summary

- Add `float` to the supported input types in
`CUDAGraphWrapper._check_input_types`
- The aot_fx_trace joint graph can produce float-valued inputs (e.g.
`global_valid_tokens` scaling factor), which previously caused a
`ValueError` during CUDA graph recording
- Float inputs are treated as static constants baked into the graph at
recording time (they are not in `_input_indices_to_copy`, so they won't
be updated on replay)

## Context

Spun off from [PR
#2868](#2868) review feedback.
The original error was:
```
ValueError: args must be tensor, integer (for dynamic shapes), Generator (for random number generator), or opaque object, but found <class 'float'> with value 65536.0 at index 117
```

## Test plan

- [x] `pre-commit run --all-files` passes (all hooks green)
- [x] `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
-x` — 12/12 passed
- [x] `pytest
torchtitan/experiments/graph_trainer/tests/test_precompile.py -x` —
24/24 passed
Apply cudagraph_pass inside apply_default_graph_passes so the
aot_fx_trace compile path wraps the traced fwd+bwd graph with
CUDAGraphWrapper. Parameters and buffers are identified as static
inputs (stable tensor addresses across training steps) to avoid
redundant copies during cudagraph replay.

Changes:
- Improve cudagraph_pass to accept static_input_indices directly as
  an alternative to the is_forward flag (used by the AOT path).
- Integrate cudagraph_pass into apply_default_graph_passes.
- Compute static input indices from TracedResult metadata in the
  trainer.
- Update integration test descriptions and add skip_rocm_test=True
  for aot_fx_trace tests (cudagraph is not supported on ROCm).
…tead of static_input_indices

Address review feedback: since the joint fwd+bwd graph is traced as a
forward graph, we can use is_forward=True to let get_static_input_indices
infer the static inputs automatically, rather than computing them
manually in trainer.py.
…rgs, and DSv3 compat

Three fixes to make cudagraph work in the aot_fx_trace compile path:

1. Compute static_input_indices from TracedResult metadata instead of
   relying on TracingContext (which is unavailable under make_fx).
   Parameters and buffers are identified as static inputs by counting
   their unwrapped plain tensors from input_subclass_layouts.

2. Accept float in CUDAGraphWrapper._check_input_types. The DSv3
   traced graph includes float graph inputs (e.g. global_valid_tokens)
   which are already excluded from copy-on-replay.

3. Auto-skip cudagraph when the graph contains CUDA-to-CPU device
   transfers (e.g. MoE load-balancing counters in DSv3) that are
   incompatible with CUDA graph capture.
…, fix docstring

- Add TracedResult.num_static_inputs property to compute the number of
  leading graph inputs with stable tensor addresses (params/buffers),
  accounting for subclass unwrapping.

- Split apply_default_graph_passes into two APIs:
  - construct_default_graph_passes(traced_result) builds the pass list
    with per-pass config bound via functools.partial
  - apply_default_graph_passes(gm, example_inputs, passes) is a generic
    pass runner with no pass-specific parameters

- Fix _has_cuda_to_cpu_transfers docstring to clarify that pin_memory is
  not checked (conservative check).

- Update .claude/CLAUDE.md: per-pass config must be bound during pass
  construction, not threaded through the generic apply function.
… apply_graph_passes

- Move _has_cuda_to_cpu_transfers from passes.py to cudagraph.py as a
  public function (has_cuda_to_cpu_transfers), colocated with other
  cudagraph utilities.

- Rename apply_default_graph_passes to apply_graph_passes since it now
  takes an explicit pass list and is a generic runner.
@SherlockNoMad
SherlockNoMad force-pushed the graph_trainer/enable-cudagraph branch from e7ad873 to 2936e96 Compare April 8, 2026 20:07
@SherlockNoMad
SherlockNoMad marked this pull request as ready for review April 8, 2026 20:08

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

Added integration test failed.

Failed test flavor: aot_fx_trace llama3 FSDP+TP+FlexAttn+cudagraph.

Comment on lines +28 to +29
if TYPE_CHECKING:
from torchtitan.experiments.graph_trainer.make_fx_tracer import TracedResult

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.

Why do you need TYPE_CHECKING here? what's wrong with import TracedResult

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.

AutoDev: Already addressed in commit 0391c7b — replaced TYPE_CHECKING guard with a direct import of TracedResult at the top of passes.py.

ngpu=8,
),
# === aot_fx_trace mode tests ===
# Note: aot_fx_trace applies cudagraph by default, so skip_rocm_test=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.

When newly added tests pass, we can remove corresponding cudagraph tests using the deprecated AOT mode.

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.

doesn't replace AOT yet.

…Result import, fix FlexAttn test

- Merge has_cuda_to_cpu_transfers and has_flex_attention into a single
  is_cudagraph_compatible() function with logger.warning for skip reasons
- Check specifically for flex_attention/flex_attention_backward HOPs
  (not all HigherOrderOperators) with TODO to remove once regional_inductor
  is applied before cudagraph
- Replace TYPE_CHECKING conditional import of TracedResult with direct import
- Fix aot_fx_trace FlexAttn integration test: remove "+cudagraph" from name
  and skip_rocm_test since cudagraph is auto-skipped for FlexAttn graphs
# cudagraph should be the last pass.
from torchtitan.experiments.graph_trainer.cudagraph import is_cudagraph_compatible

if is_cudagraph_compatible(traced_result.gm):

@SherlockNoMad SherlockNoMad Apr 8, 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.

cc @yiming0416

llama3 is currently incompatible with cudagraph, since we haven't enable regional inductor for flex.

But I do want to land this so that this becomes the compatibility checking gate for future optimizations.

All passes must be compatible with cudagraph, since it's the single most important optimization.

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.

Do you mean dsv3 is incompatible?

Why is regional inductor for flex attention a pre-requisite for 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.

when flex attention is uncompiled, it uses the math backend, which has a copy with unpined memory, thus breaking cudagraph.

flex_attn is only compatible with cudagraph when it's compiled into triton kernel.

@yiming0416

Copy link
Copy Markdown
Contributor

This time test_bitwise_determinism failed in CI.

I though we have rules for agents to always make sure bitwise test pass before pushing new code?

Replace the general device-mismatch check with specific op-level checks:
- aten.copy_ / aten._to_copy with cross-device tensors (MoE load-balancing)
- aten._grouped_mm with CPU tensor inputs (MoE routing indices)

This fixes the CI failure where _grouped_mm with CPU routing indices
triggered "Cannot copy between CPU and CUDA tensors during CUDA graph
capture" on nightly PyTorch.
…patible

The previous check only flagged aten._grouped_mm when its FX graph inputs
were visibly on CPU. However, _grouped_mm can perform internal CPU↔CUDA
copies (e.g. workspace allocation) that are invisible in graph metadata,
causing "Cannot copy between CPU and CUDA tensors during CUDA graph
capture" at runtime even when all visible inputs are on CUDA.

Fix: reject any graph containing _grouped_mm unconditionally, so DSv3
MoE gracefully falls back to the non-cudagraph path.
@SherlockNoMad

Copy link
Copy Markdown
Contributor Author

AutoDev: Fixed CI failure — TestDSv3BitwiseDeterministic::test_aot_fx_trace_vs_eager was crashing with:

RuntimeError: Cannot copy between CPU and CUDA tensors during CUDA graph capture unless the CPU tensor is pinned.

Root cause: is_cudagraph_compatible only flagged aten._grouped_mm when its FX graph inputs were visibly on CPU. But DSv3's _grouped_mm performs internal CPU↔CUDA copies (workspace allocation) that aren't visible in the graph metadata — all inputs appear on CUDA, yet the op still fails during capture.

Fix: Reject any graph containing aten._grouped_mm unconditionally (commit 9c4b394). DSv3 now gracefully skips cudagraph and runs the non-cudagraph path.

Also replied to the TYPE_CHECKING review comment — already addressed in commit 0391c7b.

@yiming0416
yiming0416 self-requested a review April 9, 2026 00:43
@SherlockNoMad
SherlockNoMad merged commit d98fa54 into main Apr 9, 2026
16 of 25 checks passed
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…rch#2876)

## Summary

- Add `float` to the supported input types in
`CUDAGraphWrapper._check_input_types`
- The aot_fx_trace joint graph can produce float-valued inputs (e.g.
`global_valid_tokens` scaling factor), which previously caused a
`ValueError` during CUDA graph recording
- Float inputs are treated as static constants baked into the graph at
recording time (they are not in `_input_indices_to_copy`, so they won't
be updated on replay)

## Context

Spun off from [PR
pytorch#2868](pytorch#2868) review feedback.
The original error was:
```
ValueError: args must be tensor, integer (for dynamic shapes), Generator (for random number generator), or opaque object, but found <class 'float'> with value 65536.0 at index 117
```

## Test plan

- [x] `pre-commit run --all-files` passes (all hooks green)
- [x] `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
-x` — 12/12 passed
- [x] `pytest
torchtitan/experiments/graph_trainer/tests/test_precompile.py -x` —
24/24 passed
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…h#2868)

## Summary

- Integrates `cudagraph_pass` into `apply_default_graph_passes` so the
`aot_fx_trace` compile path wraps the traced fwd+bwd graph with
`CUDAGraphWrapper`.
- Parameters and buffers are identified as static inputs (stable tensor
addresses across training steps) to avoid redundant copies during
cudagraph replay.
- Improves `cudagraph_pass` to accept `static_input_indices` directly,
as an alternative to the `is_forward` flag used by the AOT path.

## Test plan

- [ ] Existing bitwise deterministic test
(`test_bitwise_deterministic.py`) now exercises cudagraph in the
aot_fx_trace path — verifies bitwise identical losses/gradients vs eager
for both Llama3 and DeepSeek-v3.
- [ ] Existing numerics tests (`test_llama3_aot_fx_trace_vs_eager`,
`test_dsv3_aot_fx_trace_vs_eager`) verify cudagraph-wrapped aot_fx_trace
matches eager FSDP2.
- [ ] Integration tests updated: `aot_fx_trace` tests now reflect
cudagraph usage and skip ROCm (cudagraph not supported there).
- [ ] AOT mode cudagraph tests remain unchanged and continue to pass.
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Apr 14, 2026
…rch#2876)

## Summary

- Add `float` to the supported input types in
`CUDAGraphWrapper._check_input_types`
- The aot_fx_trace joint graph can produce float-valued inputs (e.g.
`global_valid_tokens` scaling factor), which previously caused a
`ValueError` during CUDA graph recording
- Float inputs are treated as static constants baked into the graph at
recording time (they are not in `_input_indices_to_copy`, so they won't
be updated on replay)

## Context

Spun off from [PR
pytorch#2868](pytorch#2868) review feedback.
The original error was:
```
ValueError: args must be tensor, integer (for dynamic shapes), Generator (for random number generator), or opaque object, but found <class 'float'> with value 65536.0 at index 117
```

## Test plan

- [x] `pre-commit run --all-files` passes (all hooks green)
- [x] `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
-x` — 12/12 passed
- [x] `pytest
torchtitan/experiments/graph_trainer/tests/test_precompile.py -x` —
24/24 passed
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Apr 14, 2026
…h#2868)

## Summary

- Integrates `cudagraph_pass` into `apply_default_graph_passes` so the
`aot_fx_trace` compile path wraps the traced fwd+bwd graph with
`CUDAGraphWrapper`.
- Parameters and buffers are identified as static inputs (stable tensor
addresses across training steps) to avoid redundant copies during
cudagraph replay.
- Improves `cudagraph_pass` to accept `static_input_indices` directly,
as an alternative to the `is_forward` flag used by the AOT path.

## Test plan

- [ ] Existing bitwise deterministic test
(`test_bitwise_deterministic.py`) now exercises cudagraph in the
aot_fx_trace path — verifies bitwise identical losses/gradients vs eager
for both Llama3 and DeepSeek-v3.
- [ ] Existing numerics tests (`test_llama3_aot_fx_trace_vs_eager`,
`test_dsv3_aot_fx_trace_vs_eager`) verify cudagraph-wrapped aot_fx_trace
matches eager FSDP2.
- [ ] Integration tests updated: `aot_fx_trace` tests now reflect
cudagraph usage and skip ROCm (cudagraph not supported there).
- [ ] AOT mode cudagraph tests remain unchanged and continue to pass.
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…rch#2876)

## Summary

- Add `float` to the supported input types in
`CUDAGraphWrapper._check_input_types`
- The aot_fx_trace joint graph can produce float-valued inputs (e.g.
`global_valid_tokens` scaling factor), which previously caused a
`ValueError` during CUDA graph recording
- Float inputs are treated as static constants baked into the graph at
recording time (they are not in `_input_indices_to_copy`, so they won't
be updated on replay)

## Context

Spun off from [PR
pytorch#2868](pytorch#2868) review feedback.
The original error was:
```
ValueError: args must be tensor, integer (for dynamic shapes), Generator (for random number generator), or opaque object, but found <class 'float'> with value 65536.0 at index 117
```

## Test plan

- [x] `pre-commit run --all-files` passes (all hooks green)
- [x] `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
-x` — 12/12 passed
- [x] `pytest
torchtitan/experiments/graph_trainer/tests/test_precompile.py -x` —
24/24 passed
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…h#2868)

## Summary

- Integrates `cudagraph_pass` into `apply_default_graph_passes` so the
`aot_fx_trace` compile path wraps the traced fwd+bwd graph with
`CUDAGraphWrapper`.
- Parameters and buffers are identified as static inputs (stable tensor
addresses across training steps) to avoid redundant copies during
cudagraph replay.
- Improves `cudagraph_pass` to accept `static_input_indices` directly,
as an alternative to the `is_forward` flag used by the AOT path.

## Test plan

- [ ] Existing bitwise deterministic test
(`test_bitwise_deterministic.py`) now exercises cudagraph in the
aot_fx_trace path — verifies bitwise identical losses/gradients vs eager
for both Llama3 and DeepSeek-v3.
- [ ] Existing numerics tests (`test_llama3_aot_fx_trace_vs_eager`,
`test_dsv3_aot_fx_trace_vs_eager`) verify cudagraph-wrapped aot_fx_trace
matches eager FSDP2.
- [ ] Integration tests updated: `aot_fx_trace` tests now reflect
cudagraph usage and skip ROCm (cudagraph not supported there).
- [ ] AOT mode cudagraph tests remain unchanged and continue to pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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