Repository navigation
[cudagraph] Capture optimizer updates separately - #4660
Merged
Merged
Conversation
[ghstack-poisoned]
This was referenced Sep 14, 2026
[ghstack-poisoned]
fegin
marked this pull request as ready for review
September 17, 2026 08:26
fegin
requested review from
IvanKobzarev,
SherlockNoMad,
aditvenk,
sanketpurandare,
tianyu-l,
wconstab and
wwwjn
as code owners
September 17, 2026 08:26
[ghstack-poisoned]
tianyu-l
reviewed
Sep 20, 2026
[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]
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]
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]
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
tianyu-l
reviewed
Sep 29, 2026
| """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: |
Contributor
There was a problem hiding this comment.
why would we put loss instead of loss_is_finite in the method input? as that seems the only information we need here
Contributor
Author
There was a problem hiding this comment.
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]
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]
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]
tianyu-l
approved these changes
Sep 30, 2026
Comment on lines
+136
to
+137
| ngpu=2, | ||
| logical_world_size=4, |
Contributor
There was a problem hiding this comment.
when real pg is used -- is this legit?
if it works should we change the entire CI, but not this PR?
Contributor
Author
There was a problem hiding this comment.
okay, let's not do this in this PR.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
Optimizationthat encapsulate EMA, gradient clipping, gradient finite check and optimizer step.Naming comes from the Codex's suggestion:
Closest related frameworks: PyTorch lightning uses
_AutomaticOptimizationand Megatron-Core usesMegatronOptimizer, both encapsulate more than justOptitimizer.step().Learneris a bit confusing because Ray RLlib usesLearnerfor the entire post-training model, loss, gradients, ...