Repository navigation
[RL] Share the core training engine - #4649
Conversation
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
wwwjn
left a comment
There was a problem hiding this comment.
Thanks for the discussion, both rl and pretrain train.py and trainer.py looks very clean now
| self.ntokens_seen += ( | ||
| self.config.training.num_tokens_per_microbatch_per_dp_rank | ||
| // self.parallel_dims.cp | ||
| ) |
There was a problem hiding this comment.
We use labels.numel() before, they should be identical. But can we add a comment here why this is a preferred way? Is it because of Flux?
There was a problem hiding this comment.
Yes, Flux is the primary reason. For regular language-model batches, labels.numel() matches, but model preprocessing can change the target shape or structure (for example, Flux latent targets and MTP label tuples). The configured logical input-token count is the model-independent accounting/throughput contract, with division by CP for the rank-local count. I added this explanation in #4773.
| @@ -969,46 +401,10 @@ def fwd_bwd() -> torch.Tensor: | |||
| else: | |||
| accumulated_loss.add_(detached_loss) | |||
There was a problem hiding this comment.
Why is the gradient accumulation loop not in TrainingEngine? With CUDAGraph, we will have to move this part as a function and I think TrainingEngine is the right place to do so. You don't have to do this in this PR, but I want to understand is there any hard limit that you don't move this loop into TrainingEngine.
There was a problem hiding this comment.
No particular reason, I think it was mostly because cudagraph boundary thing. I agree that we probably can replace engine's forward_backward_microbatch with a function that does all grad accum steps, as the interface to core and RL trainers.
felipemello1
left a comment
There was a problem hiding this comment.
lgtm
How are you going to test this? Integration/unit tests only? should we have a main vs this PR sanity check?
|
Can you change the PR summary? It is out-dated. |
Yes I will. I merged first. |
|
well merged into wrong branch |
## Human's note: This is pure refactor, and there is **NO NUMERICS CHANGE**. I personally think it's enough for reviewer to read the note I wrote below, and check the code changes that sounds interesting / problematic to you. **Core changes** 1. extracted `TrainingEngine` into `torchtitan/training_engine.py`, shared by core eager trainer and RL trainer. See API below. - supervised trainer specific: tokenizer, dataloader, `create_seed_checkpoint`, metrics - for metrics, they were done differently due to historical reasons. Now they share a common function `compute_training_performance_metrics()`. I think the two trainer may be unified regarding metrics, but I'll leave it out to future work (cc @felipemello1) - RL trainer specific - weight sync / torchstore `push_state_dict`, receiving whole batch of data instead of building on the fly - the following are shared with generator, thus owned by RL controller, including `compile_config`, `dump_folder`, `model_spec`, `hf_assets_path` - FLUX trainer still inherits core Trainer, and is greatly simplified, by moving image encoder processing into recently introduced `model.preprocess_inputs` - GraphTrainer now has its own `GraphTrainingEngine(TrainingEngine)`, which has compatible interface to potentially be used as an RL trainer backend, but it is not tested (cc @SherlockNoMad @aditvenk) - `FaultTolerantTrainingEngine` inherits `TrainingEngine`, but `FaultTolerantTrainer` does not inherit core `Trainer` because it anyway has to rewrite most things. 2. `torchtitan/experiments/rl/` is graduated to `torchtitan/rl/` - added @felipemello1 @wwwjn @pzhan9 @tianyu-l as codeowners (can be revisited later) - reorganized files under the torchtitan/rl/ folder. Put a section in torchtitan/rl/README.md to explain the new file layout. - Regarding RL trainer and generator, I put non-monarch-actor "real" definitions under `torchtitan/rl/`, and put thin monarch actor inheritance under `torchtitan/rl/distributed/actors/`. The idea is that **trainer and generator could be adopted by others independently without monarch**. (cc @pzhan9) - RL `RolloutWorkerActor` keeps composition with `RolloutWorker`, instead of inheritance, because users might inherit `RolloutWorker` and change its behavior. - `InterGeneratorRouter` is still a monarch actor only class, because it's not just an endpoint. It uses monarch APIs to call other actors. - linter is still excluded because the unsettled dependency story -- would like to worry later **`TrainingEngine` public APIs** ``` class TrainingEngine( Configurable, torch.distributed.checkpoint.stateful.Stateful, ): def __init__( config, *, model_config, max_num_documents, output_dir, ) -> None def initialize( model_spec, *, compile_config, sd_adapter, dataloader=None, create_seed_checkpoint=False, ) -> None def prepare_step( global_valid_tokens, *, num_accumulation_steps=1, ) -> torch.Tensor def forward_backward_microbatch( *, microbatch_group, global_valid_tokens, accumulation_index=0, ) -> torch.Tensor def optimizer_step() -> torch.Tensor def load_checkpoint() -> bool def save_checkpoint(*, last_step=False) -> bool def start_profiler() -> None def step_profiler() -> None def close_profiler() -> None def state_dict() -> dict[str, Any] def load_state_dict(state_dict) -> None def close() -> None ``` **Other changes** **supervised training** - renamed `batch` to `microbatch`, whenever appropriate. - for each spmd gradient accumulation step, PP has multiple microbatches -- it is now consistently named as a `microbatch_group` to be non-ambiguous - removed "batch" mesh, because it's a duplicate to "dp" mesh - rename lowercase `cudagraph` to `cuda_graph`, whenever appropriate. - `wrap_with_cuda_graph` no longer assumes each optimizer step has fixed number of microbatches, because RL training doesn't satisfy this condition - changing from `Checkpointer.Config` having `enable` field to `checkpointer: Checkpointer.Config | None` style **RL** - RL trainer is renamed from `PolicyTrainer` to `Trainer`, under torchtitan/rl/trainer.py - RL trainer now should share core capability like cudagraph, sdc_replay, garbage collection, profiling, HSDP optimization, etc. And hard to miss one in the future. - RL trainer cudagraph not enabled / tested yet; PP is not enabled due to torchstore issue (cc @wwwjn) - Per RL example trivial rollouters are removed; as a replacement, a `config_registry` file now hosts a simple shared rollouter config such as `_alphabet_sort_rollouter_config()` and `_dapo_math_rollouter_config()`, so all configs don't have to redefine them. - RL losses now require `global_valid_tokens` to be device tensor to be cudagraphable - RL now does not accept DP > 1 unless EP is used, in which it is required EP == DP * TP. Otherwise, it is recommended to use `num_generators > 1` ------------------------------------------------------- ### Summary by agent: Core and RL trainers had independently accumulated the same distributed model lifecycle and per-microbatch execution logic. That duplication made features such as CUDA graphs, SDC replay, profiling, GC, checkpointing, and HSDP accumulation easy to support in one workflow but miss in the other. This introduces a configurable `TrainingEngine` composed by workflow-specific trainers, moves shared model initialization and forward/backward behavior into it, and makes Flux use the same execution path. It also graduates TitanRL to `torchtitan.rl`, gives standalone trainer/generator services thin Monarch actor adapters, clarifies microbatch contracts, and keeps RL CI optional while triggering it for shared files that can affect RL. Existing RL recipes retain eager trainer execution and dynamic varlen metadata to preserve their established numerics; CUDA graphs are available as an explicit shared-config opt-in. Numerics: deterministic H100 Flux runs were bitwise identical before and after for all recorded losses and grad norms. Deterministic H100 RL comparisons against `origin/main` were also bitwise identical for trainer TP=2 and TP=4, including generator TP=1, TP=2, and TP=4 coverage. Validation: `pre-commit run --all-files`; `pytest tests/unit_tests/cpu -x` (1107 passed, 2 skipped); `pytest tests/rl -x` (415 passed, 23 skipped). Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * __->__ #4649 * #4648 Supersedes #4649, which was accidentally merged into its ghstack base branch instead of `main`.
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.
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4662 * #4661 * __->__ #4660 **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, ...
Human's note:
This is pure refactor, and there is NO NUMERICS CHANGE. I personally think it's enough for reviewer to read the note I wrote below, and check the code changes that sounds interesting / problematic to you.
Core changes
extracted
TrainingEngineintotorchtitan/training_engine.py, shared by core eager trainer and RL trainer. See API below.create_seed_checkpoint, metricscompute_training_performance_metrics(). I think the two trainer may be unified regarding metrics, but I'll leave it out to future work (cc @felipemello1)push_state_dict, receiving whole batch of data instead of building on the flycompile_config,dump_folder,model_spec,hf_assets_pathmodel.preprocess_inputsGraphTrainingEngine(TrainingEngine), which has compatible interface to potentially be used as an RL trainer backend, but it is not tested (cc @SherlockNoMad @aditvenk)FaultTolerantTrainingEngineinheritsTrainingEngine, butFaultTolerantTrainerdoes not inherit coreTrainerbecause it anyway has to rewrite most things.torchtitan/experiments/rl/is graduated totorchtitan/rl/torchtitan/rl/, and put thin monarch actor inheritance undertorchtitan/rl/distributed/actors/. The idea is that trainer and generator could be adopted by others independently without monarch. (cc @pzhan9)RolloutWorkerActorkeeps composition withRolloutWorker, instead of inheritance, because users might inheritRolloutWorkerand change its behavior.InterGeneratorRouteris still a monarch actor only class, because it's not just an endpoint. It uses monarch APIs to call other actors.TrainingEnginepublic APIsOther changes
supervised training
batchtomicrobatch, whenever appropriate.microbatch_groupto be non-ambiguouscudagraphtocuda_graph, whenever appropriate.wrap_with_cuda_graphno longer assumes each optimizer step has fixed number of microbatches, because RL training doesn't satisfy this conditionCheckpointer.Confighavingenablefield tocheckpointer: Checkpointer.Config | NonestyleRL
PolicyTrainertoTrainer, under torchtitan/rl/trainer.pyconfig_registryfile now hosts a simple shared rollouter config such as_alphabet_sort_rollouter_config()and_dapo_math_rollouter_config(), so all configs don't have to redefine them.global_valid_tokensto be device tensor to be cudagraphablenum_generators > 1Summary by agent:
Core and RL trainers had independently accumulated the same distributed model lifecycle and per-microbatch execution logic. That duplication made features such as CUDA graphs, SDC replay, profiling, GC, checkpointing, and HSDP accumulation easy to support in one workflow but miss in the other.
This introduces a configurable
TrainingEnginecomposed by workflow-specific trainers, moves shared model initialization and forward/backward behavior into it, and makes Flux use the same execution path. It also graduates TitanRL totorchtitan.rl, gives standalone trainer/generator services thin Monarch actor adapters, clarifies microbatch contracts, and keeps RL CI optional while triggering it for shared files that can affect RL.Existing RL recipes retain eager trainer execution and dynamic varlen metadata to preserve their established numerics; CUDA graphs are available as an explicit shared-config opt-in.
Numerics: deterministic H100 Flux runs were bitwise identical before and after for all recorded losses and grad norms. Deterministic H100 RL comparisons against
origin/mainwere also bitwise identical for trainer TP=2 and TP=4, including generator TP=1, TP=2, and TP=4 coverage.Validation:
pre-commit run --all-files;pytest tests/unit_tests/cpu -x(1107 passed, 2 skipped);pytest tests/rl -x(415 passed, 23 skipped).Stack from ghstack (oldest at bottom):