Repository navigation
Centralize model config transforms - #4648
Merged
Merged
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
tianyu-l
commented
Sep 14, 2026
| Converters may return a replacement root config when the transform needs | ||
| to wrap the model config itself. | ||
|
|
||
| TODO: Replace this legacy interface with ``ModelConfigTransform``. |
tianyu-l
commented
Sep 14, 2026
| This package may import other `torchtitan` packages. Those packages must not | ||
| import this package. Recipes import and apply transforms. | ||
|
|
||
| Model registry functions temporarily violate this direction while they accept |
wwwjn
approved these changes
Sep 14, 2026
fegin
approved these changes
Sep 14, 2026
tianyu-l
added a commit
that referenced
this pull request
Sep 17, 2026
## 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): __init__( config, *, model_config, max_num_documents, output_dir, ) initialize_distributed_runtime() initialize_model(model_spec, *, compile_config, create_seed_checkpoint=False) initialize_optimizer(model_spec) initialize_checkpointer(*, dataloader, sd_adapter) initialize_forward_backward() prepare_step(global_valid_tokens, *, step) forward_backward_microbatch( *, microbatch_group, global_valid_tokens, loss_kwargs=None, accumulation_index=0, num_accumulation_steps=1, ) optimizer_step() complete_step(*, last_step=False) load_checkpoint() save_checkpoint(*, last_step=False) start_profiler() close() state_dict() load_state_dict(state_dict) ``` **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
tianyu-l
added a commit
that referenced
this pull request
Sep 17, 2026
## 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`.
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.
Model transforms had accumulated in model- and RL-specific locations even though they are reusable configuration-time operations. Centralizing them gives every model spec one consistent way to compose quantization, LoRA, batch-invariance, and linear-casting transforms.
This moves the generic converters under
torchtitan.config.transform, introduces a small converter interface, and updates all model registrations and tests to use it. The change is intentionally behavior-preserving.Validation:
pre-commit run --all-files;pytest tests/unit_tests/cpu -x(1107 passed, 2 skipped, run on the full stack).Stack from ghstack (oldest at bottom):