Repository navigation
[rl] Organize torchtitan/rl into role packages; name model state dict transfer consistently - #5316
Merged
Merged
Conversation
tianyu-l
requested review from
fegin,
felipemello1,
pzhan9,
wconstab and
wwwjn
as code owners
October 12, 2026 10:08
wwwjn
approved these changes
Oct 13, 2026
Contributor
There was a problem hiding this comment.
hmm what's the motivation / consideration to rename weight sync to be model state dict sync? To align with pretraining?
Contributor
Author
There was a problem hiding this comment.
yeah that's not a good name, either, although I wanted to avoid "weight sync" (do you not sync "bias"?) -- let me think more
Contributor
Author
There was a problem hiding this comment.
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
force-pushed
the
rl-folder-restructure
branch
from
October 14, 2026 08:21
2ad7d6e to
e34c572
Compare
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.
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.
Why
torchtitan/rl/was grouped by technical layer (components/,distributed/,model/,observability/,losses/) next to flatcontroller.py,trainer.pyandgenerator.py. Code for one service ended up spread over several of these folders: the generator alone spannedgenerator.py,distributed/parallelism.py,model/vllm_*.pyandobservability/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_dictterms 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)
controller/controller.py,work_buffer.py,metrics.py,WINDOWED_FIFO.mdcontroller.py,components/work_buffer.py,observability/controller.pytrainer/trainer.py,batcher.py,training_sample_builder.py,controller_state.py,losses/trainer.py,components/*,components/checkpointer.py,losses/generator/generator.py,parallelism.pygenerator.py,distributed/parallelism.pygenerator/vllm/model_wrapper.py,registry.py,worker.py,stat_logger.py, attention / GDN / KDA adapters,batch_invariance.pymodel/*,observability/vllm.pyrollout/data.py,recorder.pycomponents/data.py,observability/rollout_recorder.pyrouting/distributed/routing/actors/monarch/torch_elastic.pydistributed/monarch_actors/,distributed/torch_elastic.py_env.py_runtime.pycomponents/checkpointer.pybecomestrainer/controller_state.pybecause it only holds the controller state that the trainer checkpoints (MirroredState, the state keys). The new package__init__.pyfiles re-export nothing, so importing a light module (e.g.generator.parallelism) never pulls in vLLM or Monarch.Names (commit 2)
pull_model_state_dict(version)load_model_state_dict(version)ModelStateDictPullMessage,LoopAction.PULL_MODEL_STATE_DICT,LoopDecision.pull_versionModelStateDictLoadMessage,LoopAction.LOAD_MODEL_STATE_DICT,LoopDecision.load_versionVLLMGenerator.Config.reset_kv_cache_on_weight_syncreset_kv_cache_on_model_state_dict_loadThe trainer pushes, the router pulls (prefetch on every generator, then load), and the generator loads. The trainer's
push_model_state_dict, the router'spull_model_state_dictand the generator'sprefetch_model_state_dictkeep their names. Metric keys (timing/weight_sync/*) are unchanged so existing dashboards keep working.Push and pull scheduled in the trainer loop (commit 4)
WeightSyncManageronly 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 ofController._trainer_loop's scheduling, so it is inlined:_trainer_loopkeepspush_task/pull_taskand 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_dictand_pull_model_state_dict_and_release_groupswrap the actor calls.WEIGHT_SYNC.mdfolds into the_trainer_loopdocstring andTrainer.push_model_state_dict(why staging can overlap forward/backward);test_weight_sync.pybecomestest_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
torchtitan.rl.controller.Controller->torchtitan.rl.controller.controller.Controllerandtorchtitan.rl.distributed.monarch_actors->torchtitan.rl.actors.monarch. Every in-repo caller is updated.reset_kv_cache_on_weight_syncis renamed toreset_kv_cache_on_model_state_dict_load(recipes updated).torchtitan.rl.distributed.weight_sync.WeightSyncManageris removed (its scheduling is now inController._trainer_loop).Testing
pre-commit run --all-files: clean for the changed files. Locally, pyrefly also reports 2 errors intorchtitan/models/common/attention/kda.py, which this PR does not touch; they come from an older localattn_gymwithout theautotuneargument that [kimi] Make KDA L2Norm numerics deterministic #5358 uses.torchtitanimport and dotted string reference (e.g.mock.patchtargets) resolves to an existing module and symbol, checked statically. Everytorchtitan.rlmodule imports.torchtitan_recipes/rlandtorchtitan_recipes/tests/rlbuilds, except a hardware-gated MXFP8 recipe.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-levelexclude: 'build'is an unanchored regex, so it skips every path containing "build" and never formatted that file.