Repository navigation
[RL] Share the core training engine - #4773
Merged
Merged
Conversation
tianyu-l
requested review from
IvanKobzarev,
SherlockNoMad,
aditvenk,
fegin,
sanketpurandare,
wconstab and
wwwjn
as code owners
September 17, 2026 19:47
|
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
approved these changes
Sep 17, 2026
fegin
approved these changes
Sep 17, 2026
aditvenk
approved these changes
Sep 17, 2026
2 tasks
tianyu-l
pushed a commit
that referenced
this pull request
Sep 21, 2026
## Summary Fix four stale paths left after the RL promotion and TrainingEngine split (#4773), plus one leftover llama3 adapter path. - `torchtitan/rl/docs/bitwise_parity.md`: `batch_invariance.py` now lives under `rl/model/`. - `torchtitan/rl/README.md`: `TrainingEngine` lives in `torchtitan.training_engine`, not `torchtitan.trainer`. - `docs/checkpoint.md`: shared checkpoint fields are on `BaseCheckpointManager.Config` in `checkpointer/base.py`. `dcp.py` only adds `async_mode`. - `torchtitan/models/qwen3/state_dict_adapter.py`: llama3's adapter is `models/llama3/state_dict_adapter.py` (no `model/` subdirectory). Docs only. No behavior change. ## Test plan - [ ] Confirmed each replacement path exists on this branch - [ ] Lint / docs checks
This was referenced Sep 22, 2026
aryamazaheri
added a commit
to PanocularAI/torchtitan
that referenced
this pull request
Sep 30, 2026
Controller._start_rollout_producers/_stop_rollout_producers factor the producer pipeline (rollout workers + data input) out of run(), and RolloutGroupWorkBuffer gains pause()/resume(), so panofabric-engine's decentralized_rl windowed loop can drive the consume side itself and keep rollouts from straddling an outer weight merge. Rebased onto upstream a182e53 (torchtitan/experiments/rl -> torchtitan/rl, pytorch#4773). Dropped from this commit versus the 1c7ab80 rebase: - the HF transformers-backend vLLM glue (vllm_wrapper/vllm_registry/ attention): it composed at ModelSpec, which pytorch#4810 deleted, and only served the never-working rl_*_hf* A/B baseline presets. - the global torch._dynamo recompile_limit = 10: a stale copy of code upstream moved into models/gpt_oss in pytorch#3737. - a comment-only hunk in training_sample_builder.py. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
shuhuayu
added a commit
that referenced
this pull request
Nov 10, 2026
Trainer.train() closes the profiler through TrainingEngine.close_profiler(), which always called Profiler.__exit__(None, None, None). Since #4773 replaced the profiler `with` block with start_profiler()/close_profiler(), the OOM exit-snapshot branch from #4580 has been unreachable for the main trainer. close_profiler() now takes the exception that ended training, and train() passes it on failure and nothing on normal exit.
shuhuayu
added a commit
that referenced
this pull request
Nov 11, 2026
Independent PR on `main`. ## Summary (human-written) On main, an OOM during training closes the profiler as if shutdown were clean, so the memory profiler never writes its exit snapshot; passing the exception to the profiler fixes that, which is how I debugged several full-scale Kimi K3 OOMs. ## Why #4580 added an OOM branch to `Profiler.__exit__` that writes an exit memory snapshot when the exception (or anything in its cause chain) is an `OutOfMemoryError`. #4773 then replaced the profiler `with` block in `Trainer.train()` with `engine.start_profiler()` plus `engine.close_profiler()` in a `finally`, and `close_profiler()` always calls `Profiler.__exit__(None, None, None)`. Since then the OOM branch is unreachable for the main trainer. The exception itself still propagates; only the snapshot is lost. ## What changed - `TrainingEngine.close_profiler(exc: BaseException | None = None)` passes `exc` to `Profiler.__exit__`. - `Trainer.train()` replaces its `finally` with `except BaseException as e: close_profiler(e); raise` and `else: close_profiler()`. - `engine.close()` still calls `close_profiler()` with no exception. It only reaches an open profiler when `train()` never started it, so nothing is lost. ## Example ```text train_step raises an OOM (possibly wrapped in a RuntimeError by PP) before: close_profiler() -> Profiler.__exit__(None, None, None); no snapshot after: close_profiler(e) -> Profiler.__exit__(type(e), e, tb); snapshot written once the same exception object still propagates to the caller ``` The exception is passed explicitly rather than read from `sys.exc_info()`, which would also return an exception an outer frame is still handling (e.g. a caller that catches an OOM and retries `train()` would get a bogus snapshot). This matches the `close(exc)` shape in #5871. ## Scope - RL is not covered. `rl/trainer/trainer.py` starts the profiler through the shared engine but closes it from its async `close()` endpoint, which has no training exception to pass, so RL OOMs still get no exit snapshot. - #5871 rewrites `observability/profiler.py` and touches `tests/unit_tests/cpu/test_trainer.py`; whichever lands second needs a rebase. - CUDA-graph stream-lane rendering is not part of this PR; #5526 covers it. ## User-facing changes | Before | After | | --- | --- | | An OOM in `Trainer.train()` writes no exit memory snapshot. | The existing OOM branch writes it once. | ## Numerics None. Only profiler shutdown on a training failure changes. ## Testing `test_train_passes_failure_to_profiler_close` runs the real `Trainer.train`, `TrainingEngine.close_profiler`, and `Profiler.__exit__` with the snapshot writer mocked, for three cases: normal exit (no snapshot), a plain OOM, and an OOM wrapped in a RuntimeError as PP does (snapshot once, and the same exception object is re-raised). All 57 tests in `tests/unit_tests/cpu/test_trainer.py` pass; `pre-commit` passes. Each of these breakages fails the test: `train()` not passing the exception, `close_profiler()` ignoring it, a snapshot on every close, and swallowing the exception after closing. Not verified: writing a real GPU OOM snapshot.
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.
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):
Supersedes #4649, which was accidentally merged into its ghstack base branch instead of
main.