Skip to content

[cudagraph] Capture optimizer updates separately - #4660

Merged
fegin merged 37 commits into
mainfrom
gh/fegin/174/head
Sep 30, 2026
Merged

fegin merged 37 commits into
mainfrom
gh/fegin/174/head

Conversation

@fegin

@fegin fegin commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Conflict with #4649

Keep forward-backward and optimizer updates in separate CUDA graphs while sharing graph-owned gradients. Capture clipping, finite checks, and fused Adam updates, while keeping checkpoint waits and LR scheduling eager.

Architecture Change:

Introduce Optimization that encapsulate EMA, gradient clipping, gradient finite check and optimizer step.

Naming comes from the Codex's suggestion:

Closest related frameworks: PyTorch lightning uses _AutomaticOptimization and Megatron-Core uses MegatronOptimizer, both encapsulate more than just Optitimizer.step(). Learner is a bit confusing because Ray RLlib uses Learner for the entire post-training model, loss, gradients, ...

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 17, 2026
Keep forward-backward and optimizer updates in separate CUDA graphs while sharing graph-owned gradients. Capture clipping, finite checks, and fused Adam updates, while keeping checkpoint waits and LR scheduling eager.

ghstack-source-id: dbb1e03
Pull-Request: #4660
@fegin
fegin marked this pull request as ready for review September 17, 2026 08:26
@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]
fegin added a commit that referenced this pull request Sep 18, 2026
Keep forward-backward and optimizer updates in separate CUDA graphs while sharing graph-owned gradients. Capture clipping, finite checks, and fused Adam updates, while keeping checkpoint waits and LR scheduling eager.

ghstack-source-id: 0e60a26
Pull-Request: #4660
Comment thread torchtitan/config/configs.py Resolved
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 22, 2026
Keep forward-backward and optimizer updates in separate CUDA graphs while sharing graph-owned gradients. Capture clipping, finite checks, and fused Adam updates, while keeping checkpoint waits and LR scheduling eager.

ghstack-source-id: 3149fc1
Pull-Request: #4660
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin requested a review from felipemello1 as a code owner September 24, 2026 08:12
fegin added a commit that referenced this pull request Sep 28, 2026
Add an Optimization component that owns the optimizer, LR scheduler, EMA, gradient clipping, finite checks, and optional CUDA graph capture. Keep scheduler and EMA updates outside the captured device update.

Nest all optimization configuration under optimization and rename the component package from optimizer to optimization.

Test Plan:

```
taskset -c 0-382 pytest -q tests/unit_tests/cpu/test_optimization.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_optimizer_param_groups.py tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_torchft_trainer.py torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -x
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-fsdp --test_suite features --test_name fsdp_optimizer_cuda_graph --ngpu 2 --execution_mode real_pg --no-parallel
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-pp --test_suite features --test_name fsdp_pp_optimizer_cuda_graph --ngpu 4 --execution_mode real_pg --no-parallel
taskset -c 0-382 env NGPU=2 MODULE=torchtitan_recipes.tests.features CONFIG=muse_glimmer_debugmodel_fsdp2_optimizer_cuda_graph ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-foreach --optimization.optimizer.implementation foreach
taskset -c 0-382 env NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-graph-trainer --training.steps 3 --training.disable_cuda_graphs
```

ghstack-source-id: fa3a99c
Pull-Request: #4660
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 28, 2026
Add an Optimization component that owns the optimizer, LR scheduler, EMA, gradient clipping, finite checks, and optional CUDA graph capture. Keep scheduler and EMA updates outside the captured device update.

Nest all optimization configuration under optimization and rename the component package from optimizer to optimization.

Test Plan:

```
taskset -c 0-382 pytest -q tests/unit_tests/cpu/test_optimization.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_optimizer_param_groups.py tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_torchft_trainer.py torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -x
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-fsdp --test_suite features --test_name fsdp_optimizer_cuda_graph --ngpu 2 --execution_mode real_pg --no-parallel
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-pp --test_suite features --test_name fsdp_pp_optimizer_cuda_graph --ngpu 4 --execution_mode real_pg --no-parallel
taskset -c 0-382 env NGPU=2 MODULE=torchtitan_recipes.tests.features CONFIG=muse_glimmer_debugmodel_fsdp2_optimizer_cuda_graph ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-foreach --optimization.optimizer.implementation foreach
taskset -c 0-382 env NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-graph-trainer --training.steps 3 --training.disable_cuda_graphs
```

ghstack-source-id: fa3a99c
Pull-Request: #4660
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 28, 2026
Add an Optimization component that owns the optimizer, LR scheduler, EMA, gradient clipping, finite checks, and optional CUDA graph capture. Keep scheduler and EMA updates outside the captured device update.

Nest all optimization configuration under optimization and rename the component package from optimizer to optimization.

Test Plan:

```
taskset -c 0-382 pytest -q tests/unit_tests/cpu/test_optimization.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_optimizer_param_groups.py tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_torchft_trainer.py torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -x
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-fsdp --test_suite features --test_name fsdp_optimizer_cuda_graph --ngpu 2 --execution_mode real_pg --no-parallel
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-pp --test_suite features --test_name fsdp_pp_optimizer_cuda_graph --ngpu 4 --execution_mode real_pg --no-parallel
taskset -c 0-382 env NGPU=2 MODULE=torchtitan_recipes.tests.features CONFIG=muse_glimmer_debugmodel_fsdp2_optimizer_cuda_graph ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-foreach --optimization.optimizer.implementation foreach
taskset -c 0-382 env NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-graph-trainer --training.steps 3 --training.disable_cuda_graphs
```

ghstack-source-id: 3b87c4d
Pull-Request: #4660
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Sep 28, 2026
Add an Optimization component that owns the optimizer, LR scheduler, EMA, gradient clipping, finite checks, and optional CUDA graph capture. Keep scheduler and EMA updates outside the captured device update.

Nest all optimization configuration under optimization and rename the component package from optimizer to optimization.

Test Plan:

```
taskset -c 0-382 pytest -q tests/unit_tests/cpu/test_optimization.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_optimizer_param_groups.py tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_torchft_trainer.py torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -x
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-fsdp --test_suite features --test_name fsdp_optimizer_cuda_graph --ngpu 2 --execution_mode real_pg --no-parallel
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-pp --test_suite features --test_name fsdp_pp_optimizer_cuda_graph --ngpu 4 --execution_mode real_pg --no-parallel
taskset -c 0-382 env NGPU=2 MODULE=torchtitan_recipes.tests.features CONFIG=muse_glimmer_debugmodel_fsdp2_optimizer_cuda_graph ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-foreach --optimization.optimizer.implementation foreach
taskset -c 0-382 env NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-graph-trainer --training.steps 3 --training.disable_cuda_graphs
```

ghstack-source-id: 5bf7f60
Pull-Request: #4660
"""Clear gradients owned by the optimizers."""
self.optimizers.zero_grad(set_to_none=set_to_none)

def step(self, loss: torch.Tensor, *, current_step: int) -> torch.Tensor:

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.

why would we put loss instead of loss_is_finite in the method input? as that seems the only information we need here

@fegin fegin Sep 30, 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.

We move loss_is_finite calculation into step(). I think this is more self-contained:

Validating the input, which is loss, then performing update based on the loss.

  - validate loss;
  - clip and validate gradients;
  - update parameters;
  - advance scheduler and EMA.

Can move it back to training engine if you think that is a more appropriate place.

fegin added a commit that referenced this pull request Sep 29, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4662
* #4661
* #4660
* #4659
* __->__ #4658

----
**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]
fegin added a commit that referenced this pull request Sep 29, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4662
* #4661
* #4660
* __->__ #4659

----

- Clear parameter gradients to None in Trainer and FaultTolerantTrainer.
- Keep capture-created gradient buffers alive and restore them after
replay.
- Require capture and replay to start without pending gradients.


**Why this state can reduce memory use:**

1. ``set_to_none=True`` without ``CUDAGraphGradientState`` fails after
the
       first capture.
       Autograd allocates a gradient during capture and assigns it to
``param.grad``. The next ``zero_grad`` clears that Python reference.
CUDA graph replay runs the captured GPU work, but it does not repeat the
``param.grad`` assignment. The optimizer then sees ``param.grad is
None``
       and skips the parameter update.

2. ``set_to_none=False`` avoids that failure, but eager warmup allocates
the
gradient before capture, outside the CUDA graph memory pool. Capture
only
records writes into that existing gradient buffer. Its lifetime overlaps
       the complete forward-backward graph::

time forward backward optimizer
gradient [===============================================]
           forward temp   [==========]
           backward temp                       [=========]

The graph allocator cannot reuse the gradient storage for these
temporary
       tensors because their lifetimes overlap.

3. With ``CUDAGraphGradientState``, ``set_to_none=True`` leaves
gradients
absent when capture starts. Autograd allocates them from the CUDA graph
memory pool during backward, after many forward tensors have expired::

time forward backward optimizer
           forward temp   [==========]
gradient [=========================]
shared block [forward temp] [gradient ]

During capture, the CUDA graph pool may reuse storage released by
forward
tensors for later gradients. This state then keeps those gradient
tensors
alive and restores each ``param.grad`` reference after replay. This
makes
       ``set_to_none=True`` safe.
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 29, 2026
Add an Optimization component that owns the optimizer, LR scheduler, EMA, gradient clipping, finite checks, and optional CUDA graph capture. Keep scheduler and EMA updates outside the captured device update.

Nest all optimization configuration under optimization and rename the component package from optimizer to optimization.

Test Plan:

```
taskset -c 0-382 pytest -q tests/unit_tests/cpu/test_optimization.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/test_invalid_loss.py tests/unit_tests/cpu/test_optimizer_param_groups.py tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_torchft_trainer.py torchtitan/experiments/torchft/tests/test_torchft_checkpoint.py -x
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-fsdp --test_suite features --test_name fsdp_optimizer_cuda_graph --ngpu 2 --execution_mode real_pg --no-parallel
taskset -c 0-382 python -m tests.integration_tests.run_tests /tmp/torchtitan-optimization-refactor-pp --test_suite features --test_name fsdp_pp_optimizer_cuda_graph --ngpu 4 --execution_mode real_pg --no-parallel
taskset -c 0-382 env NGPU=2 MODULE=torchtitan_recipes.tests.features CONFIG=muse_glimmer_debugmodel_fsdp2_optimizer_cuda_graph ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-foreach --optimization.optimizer.implementation foreach
taskset -c 0-382 env NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh --dump_folder /tmp/torchtitan-optimization-refactor-graph-trainer --training.steps 3 --training.disable_cuda_graphs
```

ghstack-source-id: ab650d0
Pull-Request: pytorch/torchtitan#4660
[ghstack-poisoned]
[ghstack-poisoned]
Comment thread tests/integration_tests/features.py Outdated
Comment on lines +136 to +137
ngpu=2,
logical_world_size=4,

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 real pg is used -- is this legit?

if it works should we change the entire CI, but not this PR?

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.

okay, let's not do this in this PR.

Comment thread torchtitan/models/flux/README.md Resolved
Comment thread run_train.sh Resolved
@fegin
fegin requested a review from tianyu-l September 30, 2026 02:45
[ghstack-poisoned]
[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/174/base to main September 30, 2026 04:54
@fegin
fegin merged commit 2164881 into main Sep 30, 2026
34 of 35 checks passed
meta-codesync Bot pushed a commit to meta-pytorch/flex_shard that referenced this pull request Oct 8, 2026
…anges

Summary:
Recent TorchTitan syncs changed several APIs that `experiments/fb/flex_shard` depends on, so `flex_shard_tests` now fails at import time (`unittest` `loadTestsFromName` ImportError). This diff moves the fb FlexShard code to the new APIs, fixes the EP>1 DistMuon break from #4419, and ports the Qwen3 recipe.

- pytorch/torchtitan#4904 (optimizer config refactor): `build_dist_muon(...)` is replaced by the `DistMuon(...)` class, which takes the same arguments. `comm_free_adapter.build_local_dist_muon` now constructs `DistMuon` directly.
- pytorch/torchtitan#4660 (`components.optimizer` -> `components.optim`, `Trainer.Config.optim`):
  - Imports now come from `torchtitan.components.optim`.
  - DSV3 Muon configs set `config.optim.optimizer`.
  - `FlexShardDistMuonOptimizers` accepts the new `enable_cuda_graph` kwarg. It raises if the flag is set, the same way upstream `OptimizersContainer` rejects optimizers that can't be captured.
  - `_log_optimizer` now takes a pattern string.
- pytorch/torchtitan#4617: `ParallelismConfig` now lives in `torchtitan.config.parallelism`.
- pytorch/torchtitan#4905:
  - `ParallelDims` is now `ParallelismContext`, and the `parallel_dims=` kwarg is now `parallelism_context=`.
  - `get_spmd_context(...)` is replaced by `parallelism_context.activate_spmd()`.
  - The `efsdp` mesh axis is now `edp_shard`. This also covers the `partition_rank_axis_name` passed to the DistMuon bucket planner.
  - Tests build the context with `ParallelismContext.from_config(config, DistributedTopology(world_size=...))`.
- pytorch/torchtitan#4840: `BlockShard(block_size=R)` is now `BlockShard(block_sizes=(R,))`.
- pytorch/torchtitan#4878: the DSV3 `model_registry` now requires `enable_sp`. The FlexShard wrapper passes `enable_sp=False`. FlexShard rejects TP, and `False` keeps the shared-expert `w2` as a plain `Linear`, as it was before #4878.
- pytorch/torchtitan#4419 (EP without DTensor): `Module._parallelize` now leaves EP-sharded routed experts as plain local `nn.Parameter` shards. It records their layouts in each module's `_sharding_config` instead of returning DTensors. With EP>1, DistMuon failed with "Partitioned block parameters must be DTensors", and `dtensor_to_global_layout` no longer found anything to declare.
  - flex_shard `dist_muon/placement.py` and `storage_layout.py` now read the FlexShard `GlobalLayout` contract (`get_global_layout`) instead of DTensor placements. `get_dim0_block_partitions` no longer takes `partition_axis_name`.
  - The new `experiments/fb/flex_shard/spmd_layouts.py` `declare_spmd_global_layouts(model, mesh)` collects `_sharding_config.state_shardings` and declares them through `spmd_types_to_global_layout`. The DSV3 recipes and tests call it where they used to call `dtensor_to_global_layout`.
- EP>1 configs now need `training.disable_cuda_graphs`: upstream config validation rejects CUDA graphs with the all-to-all token dispatcher. `flex_shard_deepseek_v3_debug_muon` sets EP=2 after construction, so it skipped that check and would fail when launched from the CLI. It now disables CUDA graphs, as upstream EP configs do.
- Qwen3 recipe port. It was broken before these syncs, by `protocols.model_spec`, `FusedQKVLinear`, `components.metrics`, `tools.logging`, `default_adamw` and `set_spmd_backend`.
  - It follows the DSV3 pattern: `FlexShardQwen3Model(Qwen3Model)` with `Config.muon_pattern`, and `parallelize()` runs `parallelize_qwen3_muon` under `activate_spmd()`.
  - Configs are rebuilt on the current `Trainer.Config` fields with the same hyperparameters.
  - Q/K/V BlockShard plans use the fused `QKVLinear.wqkv`: one `head_dim`-row matrix per Q/K/V head.
  - `parallelize_qwen3_muon` uses `dp_shard`, always calls `_parallelize` (as DSV3 does), and declares the EP layouts.
- DSV3 `test_debug_muon_train_step` now disables autograd multithreading, as upstream `init_distributed` does. The SPMD mesh is thread-local, and FSDPTest skips `init_distributed`. So selective-AC recompute ran on an autograd device thread with no mesh set, the MoE token dispatch skipped EP there, and backward failed in `torch._grouped_mm` with "matrix batch sizes have to match". The upstream Trainer is not affected: the DSV3 debug model with EP=2 + SAC trains normally.

The `comm_free_adapter` change is the same as the one in D122391176, the auto-generated Test Blame fix. This diff also covers the other breakages in fb/flex_shard.

The DistMuon tests (DSV3 `test_shard0_owned_mixed` and `test_debug_muon_train_step`, and Qwen3 `test_debug_muon_train_step`) now get past every API break. They still fail on the fused `w13` weights, which the next diff (D122443668) fixes.

Reviewed By: weifengpy

Differential Revision: D122692766

Pull Request resolved: #50
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