Skip to content

[RL] Share the core training engine - #4773

Merged
tianyu-l merged 1 commit into
mainfrom
tianyu-l/rl-training-engine
Sep 17, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
tianyu-l/rl-training-engine

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

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 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.

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 (oldest at bottom):

Supersedes #4649, which was accidentally merged into its ghstack base branch instead of main.

ghstack-source-id: 67c130b
Pull-Request: #4649
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Sep 17, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 17, 2026
@tianyu-l tianyu-l added ciflow/8gpu ciflow/graph-trainer Run GraphTrainer CI ciflow/real-pg Run the full 8-GPU Real PG integration suite labels Sep 17, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/8gpu.
Currently recognized labels are

  • ciflow/b200
  • ciflow/fake-pg
  • ciflow/h100.8
  • ciflow/real-pg
  • ciflow/rl
  • ciflow/rocm

Please add the new label to .github/pytorch-probot.yml

@pytorch-bot

pytorch-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/b200
  • ciflow/fake-pg
  • ciflow/h100.8
  • ciflow/real-pg
  • ciflow/rl
  • ciflow/rocm

Please add the new label to .github/pytorch-probot.yml

@tianyu-l
tianyu-l merged commit ec953b3 into main Sep 17, 2026
40 checks passed
@tianyu-l
tianyu-l deleted the tianyu-l/rl-training-engine branch September 17, 2026 22:26
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
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.
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/graph-trainer Run GraphTrainer CI ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/8gpu 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.

4 participants