Skip to content

[rl] Organize torchtitan/rl into role packages; name model state dict transfer consistently - #5316

Merged
tianyu-l merged 4 commits into
mainfrom
rl-folder-restructure
Oct 14, 2026
Merged

tianyu-l merged 4 commits into
mainfrom
rl-folder-restructure

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Why

torchtitan/rl/ was grouped by technical layer (components/, distributed/, model/, observability/, losses/) next to flat controller.py, trainer.py and generator.py. Code for one service ended up spread over several of these folders: the generator alone spanned generator.py, distributed/parallelism.py, model/vllm_*.py and observability/vllm.py. That left no obvious place for a second inference engine (e.g. SGLang next to vLLM) or a second actor framework (e.g. Ray next to Monarch).

This PR regroups the package by role, so each service's code sits together and engine- or framework-specific code sits in its own subpackage. It also replaces the informal "weight sync" with the push / pull / load model_state_dict terms the RL code already uses elsewhere. No behavior changes.

This prepares for splitting generator.py (engine calls vs. request dispatch vs. engine-loop thread) in the next PR of the stack.

What changed

Layout (commit 1: moves plus import and path updates only)

Package Contents Moved from
controller/ controller.py, work_buffer.py, metrics.py, WINDOWED_FIFO.md controller.py, components/work_buffer.py, observability/controller.py
trainer/ trainer.py, batcher.py, training_sample_builder.py, controller_state.py, losses/ trainer.py, components/*, components/checkpointer.py, losses/
generator/ generator.py, parallelism.py generator.py, distributed/parallelism.py
generator/vllm/ model_wrapper.py, registry.py, worker.py, stat_logger.py, attention / GDN / KDA adapters, batch_invariance.py model/*, observability/vllm.py
rollout/ adds data.py, recorder.py components/data.py, observability/rollout_recorder.py
routing/ inter-/intra-generator routing distributed/routing/
actors/monarch/ Monarch actor wrappers, torch_elastic.py distributed/monarch_actors/, distributed/torch_elastic.py
_env.py process environment defaults _runtime.py

components/checkpointer.py becomes trainer/controller_state.py because it only holds the controller state that the trainer checkpoints (MirroredState, the state keys). The new package __init__.py files re-export nothing, so importing a light module (e.g. generator.parallelism) never pulls in vLLM or Monarch.

Names (commit 2)

Before After
generator pull_model_state_dict(version) load_model_state_dict(version)
ModelStateDictPullMessage, LoopAction.PULL_MODEL_STATE_DICT, LoopDecision.pull_version ModelStateDictLoadMessage, LoopAction.LOAD_MODEL_STATE_DICT, LoopDecision.load_version
VLLMGenerator.Config.reset_kv_cache_on_weight_sync reset_kv_cache_on_model_state_dict_load
"weight sync" in docs and comments "model state dict sync" (the whole handoff) or push / pull / load

The trainer pushes, the router pulls (prefetch on every generator, then load), and the generator loads. The trainer's push_model_state_dict, the router's pull_model_state_dict and the generator's prefetch_model_state_dict keep their names. Metric keys (timing/weight_sync/*) are unchanged so existing dashboards keep working.

Push and pull scheduled in the trainer loop (commit 4)

WeightSyncManager only held the trainer loop's two in-flight tasks (the trainer's push and the generators' pull of the previous step's policy) plus the group-buffer release that keeps new rollouts born fresh. It was a piece of Controller._trainer_loop's scheduling, so it is inlined:

  • _trainer_loop keeps push_task / pull_task and awaits each next to the operation it protects: push N-1 before optimizer step N, pull N-1 before push N.
  • Controller._push_model_state_dict and _pull_model_state_dict_and_release_groups wrap the actor calls.
  • WEIGHT_SYNC.md folds into the _trainer_loop docstring and Trainer.push_model_state_dict (why staging can overlap forward/backward); test_weight_sync.py becomes test_trainer_loop.py, which drives the real loop with fake actors.

The actor calls and awaits run in the same order as before; trace spans and metric keys are unchanged.

User-facing changes

  • RL import paths change, e.g. torchtitan.rl.controller.Controller -> torchtitan.rl.controller.controller.Controller and torchtitan.rl.distributed.monarch_actors -> torchtitan.rl.actors.monarch. Every in-repo caller is updated.
  • reset_kv_cache_on_weight_sync is renamed to reset_kv_cache_on_model_state_dict_load (recipes updated).
  • torchtitan.rl.distributed.weight_sync.WeightSyncManager is removed (its scheduling is now in Controller._trainer_loop).

Testing

  • pre-commit run --all-files: clean for the changed files. Locally, pyrefly also reports 2 errors in torchtitan/models/common/attention/kda.py, which this PR does not touch; they come from an older local attn_gym without the autotune argument that [kimi] Make KDA L2Norm numerics deterministic #5358 uses.
  • RL CPU unit tests pass on every commit of the stack (441 passed on this PR's head, none failed).
  • Every absolute torchtitan import and dotted string reference (e.g. mock.patch targets) resolves to an existing module and symbol, checked statically. Every torchtitan.rl module imports.
  • Every RL recipe in torchtitan_recipes/rl and torchtitan_recipes/tests/rl builds, except a hardware-gated MXFP8 recipe.
  • GPU A/B against main (2x GB300, Qwen3 debug model with random init and a deterministic varying reward, so every step changes the weights the generator loads), run on this stack's head ([rl] Split the generator into service, engine loop, dispatcher and engine; add GenerationEngine #5317):
    • on-policy, batch-invariant: all 65 non-timing metrics (loss, grad norm, rewards, entropy, trainer-vs-generator logprob diffs, policy age, rollout lengths) are bitwise identical to main, and the stack is bitwise identical run to run;
    • async (target_offpolicy_steps=3): differs from main by the same amount main differs from itself (which rollouts finish first depends on timing).

Also included: a separate one-line fix for a malformed call in tests/unit_tests/cpu/models/test_build_model_config.py. pre-commit's top-level exclude: 'build' is an unanchored regex, so it skips every path containing "build" and never formatted that file.

@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 12, 2026
@tianyu-l tianyu-l changed the title rl folder restructure [rl] Organize torchtitan/rl into role packages; name model state dict transfer consistently Oct 12, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
@tianyu-l
tianyu-l added this pull request to stack #5318 October 12, 2026 10:29

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.

hmm what's the motivation / consideration to rename weight sync to be model state dict sync? To align with pretraining?

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.

yeah that's not a good name, either, although I wanted to avoid "weight sync" (do you not sync "bias"?) -- let me think more

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.

I removed such concept entirely, merged into controller logic as it belongs to there anyway.

Group RL modules by the service they belong to, so each role's code
lives together and later backends have an obvious home:

- controller/: the async loop, work buffer, model state dict sync, metrics
- trainer/: trainer service, batching, sample building, losses, and the
  controller state the trainer checkpoints
- generator/: generator service and inference parallelism;
  generator/vllm/ holds the vLLM engine integration and model adapters
- rollout/: adds data loading and the rollout recorder
- routing/: inter- and intra-generator routing
- actors/monarch/: Monarch actor wrappers and torch-elastic setup
- _runtime.py -> _env.py

Pure moves plus import and path updates; no behavior change.
pre-commit's top-level exclude: 'build' regex skips every path containing
'build', so this file was never formatted.
Use push/pull/load model_state_dict throughout instead of the informal
"weight sync":

- WeightSyncManager -> ModelStateDictSync (Controller._model_state_dict_sync)
- the generator applies a version with load_model_state_dict; its queue
  message, loop action and decision field follow (ModelStateDictLoadMessage,
  LoopAction.LOAD_MODEL_STATE_DICT, LoopDecision.load_version)
- VLLMGenerator.Config.reset_kv_cache_on_weight_sync ->
  reset_kv_cache_on_model_state_dict_load
- test_weight_sync.py -> test_model_state_dict_sync.py

The trainer's push_model_state_dict, the router's pull_model_state_dict
(prefetch + load on every generator) and the generator's
prefetch_model_state_dict keep their names. Metric keys are unchanged so
existing dashboards keep working.
ModelStateDictSync (formerly WeightSyncManager) only held the trainer
loop's two in-flight tasks: the trainer's push and the generators' pull
of the previous step's policy, plus the group-buffer release that keeps
new rollouts born fresh. It was a piece of Controller._trainer_loop's
scheduling, used nowhere else, so inline it:

- _trainer_loop keeps push_task / pull_task locals and awaits each next to
  the operation it protects: the push before the optimizer step, the pull
  before the next push.
- Controller._push_model_state_dict and
  _pull_model_state_dict_and_release_groups wrap the actor calls, named
  after the endpoints they call.
- MODEL_STATE_DICT_SYNC.md folds into the _trainer_loop docstring and the
  Trainer.push_model_state_dict docstring (why staging can overlap
  forward/backward).
- test_model_state_dict_sync.py becomes test_trainer_loop.py, which drives
  the real loop with fake actors and checks the same ordering.

Metric keys, trace spans and behavior are unchanged.
@tianyu-l
tianyu-l force-pushed the rl-folder-restructure branch from 2ad7d6e to e34c572 Compare October 14, 2026 08:21
@tianyu-l
tianyu-l merged commit 7db578e into main Oct 14, 2026
@tianyu-l
tianyu-l deleted the rl-folder-restructure branch October 14, 2026 09:34
tianyu-l added a commit that referenced this pull request Oct 17, 2026
…gine; add GenerationEngine (#5317)

Stacked on #5316.

## Why

`torchtitan/rl/generator/generator.py` (1860 lines) mixed three concerns
in one class, `VLLMGenerator`:

- calls into vLLM (`EngineArgs`, `render_cmpl` + `add_request`, `step`,
`SamplingParams`, `RequestOutput` parsing, prefix-cache reset,
teardown);
- request dispatch across data-parallel replicas and fan-in of results
to rank 0;
- the engine thread and its SPMD loop (queue, rank 0's decision,
broadcast, step bursts, load coalescing).

That makes each part hard to read in isolation and ties the generator to
vLLM. This PR splits the file along those lines and puts the inference
engine behind an interface, so a second engine (e.g. SGLang) can be
added as another `GenerationEngine` without touching the generator, the
engine loop or the dispatcher.

## What changed

**Generator split**

| File | Contents |
| --- | --- |
| `generator/generator.py` | `Generator` (was `VLLMGenerator`), the
service: config, setup and endpoints |
| `generator/engine_loop.py` | `EngineLoopThread` (the thread and event
loop the engine lives on) and `EngineLoop` (queue, decide -> broadcast
-> apply, load coalescing, policy version, per-group cache-salt pins) |
| `generator/dispatcher.py` | `RequestDispatcher` and the rank-0
completion metrics |
| `generator/types.py` | `SamplingConfig`, `EngineRequest`,
`FinishedRequest`, `RequestMetricsInputs` |
| `generator/engine.py` | `GenerationEngine`, the engine interface |
| `generator/vllm/engine.py` | `VLLMEngine`, holding every vLLM call |
| `generator/vllm/config.py` | `VLLMCudaGraphConfig` |

The dispatcher now receives engine-agnostic `FinishedRequest`s instead
of vLLM `RequestOutput`s, and rank 0 builds each `Completion`. Peer
replicas used to send a `Completion` with a placeholder
`min_policy_version` that rank 0 overwrote; they now send their
`FinishedRequest`s plus the policy version installed when those
finished.

**Engine interface**

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- `GenerationEngine` (`generator/engine.py`) is the interface the engine
loop and the generator call: `add_requests`, `step`,
`has_unfinished_requests`, `load_prefetched_model_state_dict`,
`shutdown`, `prefetched_model_state_dict`, and the data-parallel layout.
Its docstring lists the build arguments every engine accepts.
- `VLLMEngine` implements it. vLLM setup, `EngineArgs` and the stat
logger are private `VLLMEngine` methods, and the engine is built from
its config on the engine loop thread.
- Only `generator/vllm/` imports vLLM; `generator.py` imports the
default engine config lazily.

**Monarch README**

`actors/monarch/README.md` lists the Monarch adapters and the Monarch
use that still lives outside them (provisioning in `train.py`, spawning
in the controller and rollouter, `InterGeneratorRouter` as an `Actor`,
and the RDMA microbatch), with the planned path to confine it to
`actors/monarch/`.

## User-facing changes

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- vLLM-only settings move from `Generator.Config` to
`VLLMEngine.Config`, selected by the new `Generator.Config.engine`
(default `VLLMEngine.Config()`):

  | Before | After |
  | --- | --- |
  | `generator.cuda_graph` | `generator.engine.cuda_graph` |
| `generator.extra_vllm_engine_args` |
`generator.engine.extra_engine_args` |
  | `generator.vllm_stat_logger` | `generator.engine.stat_logger` |
| `generator.session_kv_holder` | `generator.engine.session_kv_holder` |

Engine-agnostic settings stay on `Generator.Config` and are passed to
the engine's build: `model_dtype`, `gpu_memory_limit`,
`max_num_batched_tokens`, `checkpointer`, `dist_moe_runtime`, `debug`.
Every recipe and test is updated. Only Python configs change: the CLI
has no per-field overrides, and `--override` targets override functions,
not config paths.
- `SamplingConfig` moves to `torchtitan.rl.generator.types`,
`VLLMCudaGraphConfig` to `torchtitan.rl.generator.vllm.config`, and
`add_extra_vllm_engine_args` to `torchtitan.rl.generator.vllm.engine`;
every caller is updated.

## Execution order

The per-iteration sequence is unchanged: decide, broadcast, stamp
versions, admit, step burst, fan-in, load. The differences:

- The engine's process-wide setup (`register_to_vllm`, the model runner
env var, the batch-invariant logprob patch) now runs on the engine loop
thread inside the engine build, after `set_batch_invariance` and the
determinism flags. vLLM reads neither at import time.
- `RequestOutput` -> `FinishedRequest` conversion happens in
`VLLMEngine.step` on every rank, not only TP rank 0 (a small list copy
on the other ranks; the n=1 check now fires on every rank instead of
only rank 0).
- A model state dict load sets the policy version after the optional
prefix-cache reset rather than before; both run synchronously on the
engine loop thread, and nothing reads the version in between.
- `generate`'s `stop_token_ids` assert runs before the
closed/not-started guard (error path only).
- Session KV release (#5220) runs through the engine loop as a
`SessionReleaseMessage`, applied on every rank in the next decision;
vLLM priority scheduling (#5257) passes `group_id` as the priority and
rank 0's `arrival_time` to every rank, as on main. Because
`session_kv_holder` is vLLM-only, its check against
`reset_kv_cache_on_model_state_dict_load` now fails when the engine is
built rather than when `Generator.Config` is constructed.

## Testing

- RL CPU unit tests: 492 passed, 8 skipped (rebased on `dc9ea005e`).
`test_engine_loop.py` drives `EngineLoop` directly with a fake engine;
`VLLMEngine`'s admission, salting, rejection, step, shutdown and
KV-reset tests use a fake `LLMEngine`; the engine kwargs test builds
`VLLMEngine` through `Config.build(...)` with vLLM mocked; the
`generate` endpoint and the DP fan-in's min/max versions have their own
tests.
- `pre-commit run --all-files`: clean for the changed files (see #5316
for the unrelated local `kda.py` pyrefly errors).
- Every RL recipe builds, except a hardware-gated MXFP8 recipe.
- GPU A/B against main (2x GB300, Qwen3 debug model with random init and
a deterministic varying reward):
- on-policy, batch-invariant: all 65 non-timing metrics are bitwise
identical to main, and identical run to run;
- async (`target_offpolicy_steps=3`): within main's own run-to-run
variation.
- After the rebase onto `dc9ea005e`, CI's multi-GPU RL suites pass
locally under torchrun: bitwise parity Varlen 3/3, Flex 3/3, Qwen3.5
4/4, and the 4-GPU uneven decode test 1/1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

2 participants