Repository navigation
Add CUDA graph capture to the core Trainer - #3559
Conversation
stack-info: PR: #3559, branch: xmfan/stack/35
|
|
||
| def _step(inp, lab, gvt, *extra_flat): | ||
| with train_context(): | ||
| pred = model(inp, **extra_inputs, **extra_kwargs) |
There was a problem hiding this comment.
is this cudagraphing eager parallellisms as well, say FSDP2?
There was a problem hiding this comment.
yeah it does, everything that model.forward + loss.backward() runs (single cudagraph for whole model, not piecewise cudagraphs). I had issues with FSDP + AC, which is why the examples I tried here are using AC=none
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
stack-info: PR: #3559, branch: xmfan/stack/35
Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. stack-info: PR: #3559, branch: xmfan/stack/35
Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. stack-info: PR: #3559, branch: xmfan/stack/35
Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. stack-info: PR: #3559, branch: xmfan/stack/35
Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. stack-info: PR: #3559, branch: xmfan/stack/35
| return inputs, labels, extra_kwargs | ||
|
|
||
| @sl.log_trace_span("fwd_bwd") | ||
| def forward_backward_step( |
There was a problem hiding this comment.
There're too many fwd bwd functions in this class. I would propose this high-level idea:
- only having one for non-pp, and one for pp -- we don't need a central
forward_backward_stepthat calls if-else within - set
fwd_bwd_fnto one of (1) non-pp (2) pp (3) cudagraph wrapped non-pp - call
fwd_bwd_fninstead offorward_backward_steporpp_forward_backward_step
Please let me know if anything doesn't make sense.
There was a problem hiding this comment.
You can't cudagraph these things currently in forward_backward_step:
- inputs/extra_kwargs prep + attention-mask update
- ntokens_seen logging
- CP sharding and DTensor/SPMD input preparation
- raw dictionary/list handling
Which is why only the "body" is cudagraphed.
set fwd_bwd_fn to one of (1) non-pp (2) pp (3) cudagraph wrapped non-pp
This is a bit weird, we'd then have (4) cudagraph wrapped pp. cudagraph is just a feature to apply on top of any of the existing branches.
pp/non-pp have different pre-processing and post-processing, we'd be hiding the forward_backward_step branching into preprocess/postprocess branches:
- Preprocessing: same hook, but non-PP prepares one microbatch while PP prepares lists of microbatches for the pipeline schedule.
- Execution/postprocessing:
- Non-PP directly runs model, loss, and backward().
- PP delegates to the schedule, aggregates losses on the last stage, and returns a sentinel elsewhere.
- CUDA graphs retain non-PP semantics but manage static inputs and clone the replayed loss.
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
Stacked PRs: * #3559 * __->__#4099 --- --- --- Keep global valid token counts on device Represent global valid token counts consistently as device scalar tensors across training, validation, pipeline parallelism, and graph tracing. Logging may still add back the sync, but intermediates no longer sync. This is needed for cudagraphs as the value of global valid token counts changes each iteration and needs to be part of the graph. Test Plan: - pytest -q tests/unit_tests/test_distributed_utils.py tests/unit_tests/test_loss.py torchtitan/experiments/graph_trainer/tests/test_chunked_loss.py - pyrefly check tests/unit_tests/test_distributed_utils.py torchtitan/distributed/utils.py torchtitan/trainer.py torchtitan/components/loss.py torchtitan/components/validate.py torchtitan/models/flux/trainer.py - 1x H100, Llama 3 debug model, seed 42, 10 deterministic steps: parent and tensor-scalar runs matched raw TensorBoard loss and grad norm bitwise at all 10 steps. Both runs completed and flushed metrics before the existing native process-teardown abort.
| @@ -752,8 +801,17 @@ def forward_backward_step( | |||
| inputs, labels, extra_kwargs = self.post_dataloading_process(input_dict, labels) | |||
There was a problem hiding this comment.
The current code looks clear enough, but I'm not sure how it'd work with future changes like #4116. Could you help review?
I also wonder what if we put the current post_dataloading_process inside model code, including attention mask generation, and CP sharding, would it break cudagraph?
There was a problem hiding this comment.
I also wonder what if we put the current post_dataloading_process inside model code, including attention mask generation, and CP sharding, would it break cudagraph?
It will break.
| Whether to apply CPU offloading of parameters, gradients, and optimizer states in FSDP | ||
| """ | ||
|
|
||
| enable_cuda_graphs: bool = False |
There was a problem hiding this comment.
Could you enable cudagraph in CI wherever we can? IIUC multimodal and PP (and some EP backend) don't work, but others should?
There was a problem hiding this comment.
After seeing the list in CI where we enabled cudagraph, I feel we should keep it by default on and only disable on the ones that doesn't support cudagraph. Then it'd be quite visible what are things we need to work on.
Maybe we should rename this flag to disable_cuda_graphs: bool = False.
|
I suggest that we land this PR to enable CUDAGraph. We need some discussion on post-processing refactor to make it work with CUDAGraph. cc., @jinsooihm |
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
| if test_flavor.enable_cuda_graphs and gpu_arch_type == "cuda": | ||
| # Tyro requires global options to precede union subcommands such as | ||
| # activation-checkpoint:selective. | ||
| cmd += " --training.enable_cuda_graphs" |
There was a problem hiding this comment.
I think it's better if we directly use --training.enable_cuda_graphs in the tests, and make wrap_with_cuda_graph no-op when it's not cuda. This will avoid the introduction of test_flavor.enable_cuda_graphs and make it robust against other hardware like rocm.
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
tianyu-l
left a comment
There was a problem hiding this comment.
looks great, thank you!
| Whether to apply CPU offloading of parameters, gradients, and optimizer states in FSDP | ||
| """ | ||
|
|
||
| enable_cuda_graphs: bool = False |
There was a problem hiding this comment.
After seeing the list in CI where we enabled cudagraph, I feel we should keep it by default on and only disable on the ones that doesn't support cudagraph. Then it'd be quite visible what are things we need to work on.
Maybe we should rename this flag to disable_cuda_graphs: bool = False.
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
|
Disabled cudagraph configs:
|
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
|
Do you know what happens to varlen attention? @liangel-02 used to work to enable full cudagraph for inference (prefill + decode), so I feel it should be cudagraphable for training. |
Known limitations: - Pipeline parallelism primarily needs a different capture boundary rather than different model semantics: capture each stage forward/backward action with its static microbatch state while leaving the Python schedule and P2P handoff eager, instead of capturing the current combined forward+loss+backward callable. - Any captured path that synchronizes with the CPU is unsupported. This includes blocking AllToAll expert parallelism; CUDA graph EP currently requires nonblocking HybridEP or MinimalAsyncEP. - FSDP reshard_after_forward=always is unsupported. Its all-gather work uses hidden FSDP streams, and capture can encounter a dependency on an event produced by uncaptured work, resulting in CUDA_ERROR_STREAM_CAPTURE_ISOLATION. The default and never policies work. Test Plan: - Llama 3 debug model, 1 GPU, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. - DeepSeek v3 debug model, 1 GPU, balanced MoE routing, 10 deterministic steps: eager and CUDA graph TensorBoard loss and grad norm were exactly equal at every step. This GB300 SM103 build required a temporary bmm test shim because native torch._grouped_mm fails to launch; the shim is not included in this commit. - 8x H100, seed 42, 10 deterministic steps: compared raw TensorBoard float32 loss and grad norm values with CUDA graphs disabled and enabled. All 60 scalar pairs matched bitwise (maximum absolute difference 0): - Llama 3 70B, FSDP=4 + TP=2, BF16 training state. - DeepSeek v3 16B HybridEP, FSDP=4 + EP=2 + TP=2, FP32 training state. - DeepSeek v3 16B HybridEP, FSDP=8 + EP=2, FP32 training state. Llama FP32 OOMed while allocating Adam state on 96 GiB H100s, so both Llama runs used BF16. DeepSeek used a temporary CUDA 12.8/API compatibility shim for the host HybridEP checkout; the shim is not included in this commit. The non-graph runs flushed all metrics before worker teardown aborts; CUDA graph runs exited cleanly. stack-info: PR: #3559, branch: xmfan/stack/35
| --baseline-options="--parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4" \ | ||
| --test-options="--parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4" \ | ||
| --baseline-options="--parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --training.disable_cuda_graphs" \ | ||
| --test-options="--parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --training.disable_cuda_graphs" \ |
There was a problem hiding this comment.
@tianyu-l lmk if you have suggestions on how to handle this cleanly. disable_cuda_graphs lives on each model config, but some default configs are trivially valid w/ cg e.g. EP=1. A common pattern is to override the config with ep degree, in which case cg may or may not be supported.
There was a problem hiding this comment.
It looks fine to add this flag everywhere EP (with non-cudagraphable backend) is used. Can revisit later.
The VarlenMetadata needs to be migrated to holding tensors and copied in each iteration, there's also a sync to remove: |
Stacked PRs:
Add eager CUDA graph capture to the core Trainer
Known limitations
No warmup needed
Numerics already match without warmup iteration.
1st iteration: record
2nd+ iteration: replay
Copy-in
Some tensors need to be copied each iteration due to the dataloader's sequence packing. For DSV3 16B these are:
Test Plan
Profile w/ CG: https://interncache-all.fbcdn.net/manifold/perfetto-artifacts/tree/ui/index.html#!/?url=https://interncache-all.fbcdn.net/manifold/perfetto_internal_traces/tree/shared_trace/xmfan_9ba1b77a-f72b-4e7d-b7ad-716941df298c_rank0_trace.json.gz
can see the cg launch from cpu thread

Next steps
There still remains some sync (loss accumulation) after the optimizer to eliminate in the trainer, to be removed soon.
PP uses a different fwd bwd entrypoint.
Disabled cudagraph configs: