Repository navigation
[rl] Split the generator into service, engine loop, dispatcher and engine; add GenerationEngine - #5317
Conversation
f6c9e20 to
1444fd1
Compare
pzhan9
left a comment
There was a problem hiding this comment.
overall lgtm. But it is really hard to go through the details due to the massive code movements. It will be nice to break down code movements to their own commits, so it is easier for human to review.
felipemello1
left a comment
There was a problem hiding this comment.
-
this is pretty hard to eval, could ask the agent to have two runs: one in main and one in this branch? maybe do alphabet sort for multiturn and dapo math to see results going up. Each should take ~10min. For dapo-math you will need 50 steps. Alphabet sort, 10 steps will do. Ask it to compare vllm logs.
-
I would ask the agetn to double check that everything is verbatim
-
Nit: We should have a follow up PR to rewrite comments/docstrings and make it more structural, with diagrams, etc, and non-verbose.
1444fd1 to
9b51163
Compare
… transfer consistently (#5316) ## 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 #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 (#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.
caa93a5 to
d82973d
Compare
|
investigation from claude: Thanks @felipemello1! I checked both points against the full stack: this PR plus #5391 on top ( 1. Runs on main vs this stack Both use the real recipes on the same host (GB300), with one change made identically on both commits: only 2 GPUs were free, so each run used a TP=1 trainer and one TP=1 generator (model configs rebuilt for that layout). Everything else is the recipe as checked in. Alphabet sort (
DAPO math (
The async loop is not deterministic, so per-step values differ; the curves track each other. Earlier, a 2-GPU deterministic run (batch-invariant, on-policy, random-init Qwen3 debug model) was bitwise identical to main on every training metric (loss, grad norm, rewards, entropy, trainer-vs-generator logprobs, policy age); only time-to-first-token latency differed. vLLM logs. After normalizing actor names, progress bars and throughput samples, every engine line matches: the full
Two more startup + step-0 validation runs per commit, alternating main and this stack, all matched this stack's numbers exactly: 9.42 GiB consumed, 1,733,680 KV cache tokens, 0.133 validation, and identical vLLM engine lines. 2. Verbatim check For every function and method in the old files, I compared
No changes were needed. I'll do 3 (restructuring the comments and docstrings) as a follow-up PR. |
wwwjn
left a comment
There was a problem hiding this comment.
The experiment looks good to me, it has some randomness in dataloading order and generator generation order, but seems the new version is not constantly bad
…gine; add GenerationEngine generator.py mixed three concerns: vLLM engine calls, request dispatch and fan-in across DP replicas, and the engine-loop thread. Split them so each reads on its own and an inference engine other than vLLM has one place to plug in: - generator/generator.py: VLLMGenerator, the service -- config, setup and endpoints (1860 -> 457 lines). - generator/engine_loop.py: EngineThread (the engine thread and its event loop) and EngineLoop (queue, decide -> broadcast -> apply, load coalescing, policy version and per-group cache-salt pins). - generator/dispatcher.py: RequestDispatcher, now fed engine-agnostic FinishedRequests. Rank 0 builds each Completion from the fanned-in results, so peers no longer send a Completion with a placeholder min_policy_version. - generator/types.py: SamplingConfig, EngineRequest, FinishedRequest, RequestMetricsInputs; no vLLM import. - generator/vllm/engine.py: VLLMEngine holds every vLLM call (EngineArgs, render + add_request, step, SamplingParams, metrics inputs, KV reset, model state dict load, shutdown). - generator/vllm/config.py: VLLMCudaGraphConfig. No config or behavior change. SamplingConfig, VLLMCudaGraphConfig and add_extra_vllm_engine_args move with their code; every caller is updated. --- Decouple the generator service from vLLM: - VLLMGenerator -> Generator, VLLMGeneratorActor -> GeneratorActor. - generator/engine.py: GenerationEngine, 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, data-parallel layout), with the build arguments every engine accepts. - VLLMEngine implements it. vLLM-only settings move from Generator.Config to VLLMEngine.Config, selected by the new Generator.Config.engine (default VLLMEngine.Config()): cuda_graph, extra_vllm_engine_args -> extra_engine_args, vllm_stat_logger -> stat_logger. vLLM setup, EngineArgs and the stat logger become private VLLMEngine methods, and the engine is built from its config on the engine loop thread. - Engine-agnostic settings stay on Generator.Config (model_dtype, gpu_memory_limit, max_num_batched_tokens, checkpointer, dist_moe_runtime, debug) and are passed to the engine's build. - EngineThread -> EngineLoopThread. generator.py no longer imports vLLM; the default engine config is imported lazily. Recipes and tests move to generator.engine.cuda_graph; only Python configs change (the CLI has no per-field overrides). --- actors/monarch/README.md lists the adapters and the Monarch use that still lives outside the package (provisioning in train.py, spawning in the controller and rollouter, and InterGeneratorRouter as an Actor), with the planned path to confine it there. Linked from the RL README.
d82973d to
89f1698
Compare
…or Monarch (#5391) Stacked on #5317. ## Why The controller, the rollouter, the trainer, the batcher and `train.py` used Monarch directly: `train.py` provisioned the GPU proc meshes; the controller spawned the router and batcher processes, set up torch elastic, spawned every actor, sliced the trainer by DP rank and stopped the meshes; the rollouter spawned and stopped its worker pool; the batcher and the trainer exchanged `MonarchRDMAMicrobatch`es. Running the RL loop on another actor framework (e.g. Ray) would mean editing all of them. This PR puts actor placement behind an interface selected by config, the way `Generator.Config.engine` selects the inference engine (#5317). ## What changed - **`actors/system.py`: `ActorSystem`**, framework-agnostic. It provisions processes, spawns each service, initializes TorchStore (storage on the trainer's processes, plus every trainer and generator actor's client), stops the processes, and shuts its client down. The name follows Akka/Pekko's actor system (see its docstring). Its docstring also defines the call convention its handles follow: `.call()` with `.get(rank)` on the result, `.call_one()`, `.choose()`, `.stream()`, `.broadcast()` (Monarch's endpoint calls; another framework wraps its handles to provide them). - `spawn_trainer(config, dp_degree=...)` returns a **`TrainerHandle`**: all-ranks, rank-0 and per-DP-rank handles. The actor system slices the trainer by DP rank and checks the `(dp, cp, tp)` layout with `get_dp_rank`, so the controller no longer slices meshes. - `spawn_generator_router(router_config, generator_config=...)` spawns the generators and the router over them, and returns only the router: the controller reaches the generators through the router. - `spawn_batcher`, `spawn_rollout_workers` / `stop_rollout_workers`. - **`Controller.Config.actor_system`** selects the implementation; the default `MonarchActorSystem.Config()` is imported lazily. `Controller.setup_async(actor_system=...)` also accepts one the launcher built, e.g. a `MonarchActorSystem` on hosts it allocated (`host_meshes`, `generator_env` constructor arguments), so launchers that bring their own hosts keep working. `train.py` only builds, runs and closes the controller, then calls the actor system's `shutdown()`. - **`actors/monarch/system.py`: `MonarchActorSystem`.** `actors/monarch/provisioning.py` takes `train.py`'s proc mesh provisioning (`PerHostProvisioner`, `HostMeshes`, `spawn_proc_mesh`, the spawn bootstraps) plus `spawn_cpu_procs` and the client `shutdown`. - **`actors/monarch/router.py`: `InterGeneratorRouterActor`**, the endpoints and the singleton check. `InterGeneratorRouter` is now a plain class with public async methods, like `Trainer` and `Generator`. - **RDMA microbatches (separate commit).** `MonarchRDMAMicrobatch` moves to `actors/monarch/rdma_microbatch.py`. The batcher and the trainer use an `RDMAMicrobatch` protocol (`read`, `drop`, the batch/DP rank/microbatch indices) in `trainer/rdma_microbatch.py`, next to `RDMAMicrobatchPrefetcher`; `BatcherActor` injects `MonarchRDMAMicrobatch.register` into `Batcher`. - **Fix:** `VerifiersRollouter.setup_async` takes `actor_system` (unused: rollouts run in the Verifiers EnvServer), plus a test that its signature matches `Rollouter.setup_async`. After this PR no module outside `actors/monarch/` imports Monarch, except the controller's lazy default config. `actors/monarch/README.md` describes the package and the call convention that remains outside it. ## Behavior - Processes and actors are created in the same order as before: GPU meshes, router and batcher processes, torch elastic, trainer, generators, router, batcher, rollout workers, TorchStore. The trainer's DP-rank layout check now runs right after the trainer spawns instead of after TorchStore init. Teardown order is unchanged. - `ts.initialize(mesh=trainer_mesh)` and the per-actor TorchStore client setup move into `ActorSystem.initialize_torchstore()` (with a TODO to move it to a model state dict transport). - A batcher with `rdma_min_tensor_bytes` set but no registration raises `ValueError`. ## Testing - RL CPU unit tests: 497 passed, 8 skipped. The Verifiers tests (skipped without `verifiers`) pass with `verifiers==0.3.1`: 37 passed, 1 skipped. New tests cover provisioning order and launcher host meshes, trainer DP-rank grouping and the layout check, teardown order with the batcher, and the Batcher's missing-registration error. - `pre-commit run` on the changed files: clean. - GPU A/B against main (`dc9ea005e`), GB300, Qwen3 debug model with random init and a deterministic varying reward, 6 steps: - on-policy, batch-invariant, 1 trainer GPU + 1 generator GPU: all non-timing metrics bitwise identical (only time-to-first-token differs); - same, with a DP=2 trainer and `rdma_min_tensor_bytes=1024` (3 GPUs, per-DP-rank columns over RDMA): bitwise identical; - async (`target_offpolicy_steps=3`): finishes all steps on both. Both then hit the same teardown error on main and here (the rollout worker mesh stops while a router reply is in flight).
Stacked on #5316.
Why
torchtitan/rl/generator/generator.py(1860 lines) mixed three concerns in one class,VLLMGenerator:EngineArgs,render_cmpl+add_request,step,SamplingParams,RequestOutputparsing, prefix-cache reset, teardown);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
GenerationEnginewithout touching the generator, the engine loop or the dispatcher.What changed
Generator split
generator/generator.pyGenerator(wasVLLMGenerator), the service: config, setup and endpointsgenerator/engine_loop.pyEngineLoopThread(the thread and event loop the engine lives on) andEngineLoop(queue, decide -> broadcast -> apply, load coalescing, policy version, per-group cache-salt pins)generator/dispatcher.pyRequestDispatcherand the rank-0 completion metricsgenerator/types.pySamplingConfig,EngineRequest,FinishedRequest,RequestMetricsInputsgenerator/engine.pyGenerationEngine, the engine interfacegenerator/vllm/engine.pyVLLMEngine, holding every vLLM callgenerator/vllm/config.pyVLLMCudaGraphConfigThe dispatcher now receives engine-agnostic
FinishedRequests instead of vLLMRequestOutputs, and rank 0 builds eachCompletion. Peer replicas used to send aCompletionwith a placeholdermin_policy_versionthat rank 0 overwrote; they now send theirFinishedRequests 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.VLLMEngineimplements it. vLLM setup,EngineArgsand the stat logger are privateVLLMEnginemethods, and the engine is built from its config on the engine loop thread.generator/vllm/imports vLLM;generator.pyimports the default engine config lazily.Monarch README
actors/monarch/README.mdlists the Monarch adapters and the Monarch use that still lives outside them (provisioning intrain.py, spawning in the controller and rollouter,InterGeneratorRouteras anActor, and the RDMA microbatch), with the planned path to confine it toactors/monarch/.User-facing changes
VLLMGenerator->Generator,VLLMGeneratorActor->GeneratorActor.vLLM-only settings move from
Generator.ConfigtoVLLMEngine.Config, selected by the newGenerator.Config.engine(defaultVLLMEngine.Config()):generator.cuda_graphgenerator.engine.cuda_graphgenerator.extra_vllm_engine_argsgenerator.engine.extra_engine_argsgenerator.vllm_stat_loggergenerator.engine.stat_loggergenerator.session_kv_holdergenerator.engine.session_kv_holderEngine-agnostic settings stay on
Generator.Configand 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--overridetargets override functions, not config paths.SamplingConfigmoves totorchtitan.rl.generator.types,VLLMCudaGraphConfigtotorchtitan.rl.generator.vllm.config, andadd_extra_vllm_engine_argstotorchtitan.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:
register_to_vllm, the model runner env var, the batch-invariant logprob patch) now runs on the engine loop thread inside the engine build, afterset_batch_invarianceand the determinism flags. vLLM reads neither at import time.RequestOutput->FinishedRequestconversion happens inVLLMEngine.stepon 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).generate'sstop_token_idsassert runs before the closed/not-started guard (error path only).SessionReleaseMessage, applied on every rank in the next decision; vLLM priority scheduling ([rl][easy] vLLM priority scheduling: serve rollout groups in the order they started #5257) passesgroup_idas the priority and rank 0'sarrival_timeto every rank, as on main. Becausesession_kv_holderis vLLM-only, its check againstreset_kv_cache_on_model_state_dict_loadnow fails when the engine is built rather than whenGenerator.Configis constructed.Testing
dc9ea005e).test_engine_loop.pydrivesEngineLoopdirectly with a fake engine;VLLMEngine's admission, salting, rejection, step, shutdown and KV-reset tests use a fakeLLMEngine; the engine kwargs test buildsVLLMEnginethroughConfig.build(...)with vLLM mocked; thegenerateendpoint and the DP fan-in's min/max versions have their own tests.pre-commit run --all-files: clean for the changed files (see [rl] Organize torchtitan/rl into role packages; name model state dict transfer consistently #5316 for the unrelated localkda.pypyrefly errors).target_offpolicy_steps=3): within main's own run-to-run variation.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.