Skip to content

[RL] Share the core training engine - #4649

Merged
tianyu-l merged 13 commits into
gh/tianyu-l/31/basefrom
gh/tianyu-l/31/head
Sep 17, 2026
Merged

tianyu-l merged 13 commits into
gh/tianyu-l/31/basefrom
gh/tianyu-l/31/head

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Sep 14, 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):
  __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 (oldest at bottom):

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 14, 2026
@tianyu-l tianyu-l changed the title [RL] share the core training engine [RL] Share the core training engine Sep 14, 2026
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: 5318290
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: 6c2814b
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: a4ccebc
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: 2acf6be
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: 6073e3d
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: d26c60a
Pull-Request: #4649
tianyu-l added a commit that referenced this pull request Sep 14, 2026
ghstack-source-id: 301db16
Pull-Request: #4649
@tianyu-l tianyu-l added ciflow/8gpu ciflow/real-pg Run the full 8-GPU Real PG integration suite labels Sep 14, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/real-pg.
Currently recognized labels are

  • ciflow/b200
  • ciflow/h100.8
  • ciflow/rl

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

@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026

Copy link
Copy Markdown

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

  • ciflow/b200
  • ciflow/h100.8
  • ciflow/rl

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

@tianyu-l tianyu-l added the ciflow/graph-trainer Run GraphTrainer CI label Sep 14, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 14, 2026

Copy link
Copy Markdown

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

  • ciflow/b200
  • ciflow/h100.8
  • ciflow/rl

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

Comment thread torchtitan/components/data/types.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: c56fa1a
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 83f3611
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 8b4db0b
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 54103c9
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: b2d46ef
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: e41d911
Pull-Request: #4649
[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: b2cc61a
Pull-Request: #4649

@wwwjn wwwjn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the discussion, both rl and pretrain train.py and trainer.py looks very clean now

[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 8ccc8d9
Pull-Request: #4649
self.ntokens_seen += (
self.config.training.num_tokens_per_microbatch_per_dp_rank
// self.parallel_dims.cp
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed in #4773

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/trainer.py
Comment on lines 390 to 402
@@ -969,46 +401,10 @@ def fwd_bwd() -> torch.Tensor:
else:
accumulated_loss.add_(detached_loss)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

[ghstack-poisoned]
tianyu-l added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 67c130b
Pull-Request: #4649

@felipemello1 felipemello1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

How are you going to test this? Integration/unit tests only? should we have a main vs this PR sanity check?

@fegin

fegin commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Can you change the PR summary? It is out-dated.

@tianyu-l
tianyu-l merged commit 0e54b05 into gh/tianyu-l/31/base Sep 17, 2026
29 checks passed
@tianyu-l

Copy link
Copy Markdown
Contributor Author

Can you change the PR summary? It is out-dated.

Yes I will. I merged first.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

well merged into wrong branch

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`.
@tianyu-l
tianyu-l deleted the gh/tianyu-l/31/head branch September 17, 2026 22:37
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.
fegin added a commit that referenced this pull request Sep 30, 2026
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, ...
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.

6 participants