Skip to content

[rl] Split the generator into service, engine loop, dispatcher and engine; add GenerationEngine - #5317

Merged
tianyu-l merged 1 commit into
mainfrom
rl-generator-split
Oct 17, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
rl-generator-split

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

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 FinishedRequests instead of vLLM RequestOutputs, 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 FinishedRequests 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 ([rl] hold each multi-turn session's KV between its turns (5/5) #5220) runs through the engine loop as a 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) 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 [rl] Organize torchtitan/rl into role packages; name model state dict transfer consistently #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.

@tianyu-l
tianyu-l added this pull request to stack #5318 October 12, 2026 10:29
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels 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 the ciflow/b200 Trigger B200 CI label Oct 12, 2026

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

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

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

  2. I would ask the agetn to double check that everything is verbatim

  3. Nit: We should have a follow up PR to rewrite comments/docstrings and make it more structural, with diagrams, etc, and non-verbose.

@tianyu-l tianyu-l changed the title [rl] Split the generator into service, engine loop, dispatch and vLLM engine [rl] Split the generator into service, engine loop, dispatcher and engine; add GenerationEngine Oct 14, 2026
Base automatically changed from rl-folder-restructure to main October 14, 2026 09:33
tianyu-l added a commit that referenced this pull request Oct 14, 2026
… 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.
@tianyu-l
tianyu-l force-pushed the rl-generator-split branch 2 times, most recently from caa93a5 to d82973d Compare October 14, 2026 09:47
@tianyu-l

tianyu-l commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

investigation from claude:
(note that one limitation is that I only got 2 GPUs available on my server)


Thanks @felipemello1! I checked both points against the full stack: this PR plus #5391 on top (15b4d8702), compared with main (7db578e15, which includes #5316).

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 (rl_grpo_qwen3_0_6b_varlen, Qwen3-0.6B, multi-turn, 10 steps, target_offpolicy_steps=3):

main this stack
validation reward, step 0 -> 10 0.179 -> 0.301 0.179 -> 0.286
rollout reward, mean of steps 1-10 0.288 0.286
policy age per step 0,1,2,3,3,3,3,3,3,3 0,1,2,3,3,3,3,3,3,3
wall time 234 s 231 s

DAPO math (rl_dapo_qwen3_4b_math_8k, Qwen3-4B-Base, 50 steps):

main this stack
rollout reward, mean of steps 1-10 / 21-30 / 41-50 0.180 / 0.249 / 0.238 0.184 / 0.240 / 0.241
response length, same windows 1032 / 1260 / 1408 1036 / 1285 / 1549
grad norm, same windows 0.169 / 0.137 / 0.128 0.167 / 0.138 / 0.125
AIME validation reward, step 0 -> 50 0.167 -> 0.133 0.133 -> 0.133
wall time 1189 s 1197 s

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 Initializing a V1 LLM engine ... with config: line, KV cache size, CUDA graph capture, model loading memory, and warnings. Neither branch logged an error. The DAPO pair first differed in two places, and both came from noise in that first main run:

  • KV cache size: 1,733,824 vs 1,733,680 tokens (20 MiB more non-torch memory at startup on this stack).
  • AIME step-0 validation: 5/30 vs 4/30 problems (greedy, but 8K-token answers decoded in one batch without batch invariance, plus Math-Verify timeouts that score zero).

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 ast.unparse of its body (formatting-insensitive, docstrings removed) with its new home. I also diffed comment lines. Code that moved without a matching function name (the EngineArgs block, the request admission loop) was compared as statement blocks after variable renames.

  • Identical: 23 functions in the generator split, 10 in the provisioning move, 10 in the router split, and 36 in the controller and rollouter. The EngineArgs block (now VLLMEngine._build_engine_args) and the admission loop (now VLLMEngine.add_requests) are also identical apart from variable renames.
  • The rest differ only in the intended ways:
    • renames (VLLMGenerator -> Generator, _RequestMetricsInputs -> RequestMetricsInputs, the extra_engine_args field);
    • delegation to the engine, the engine loop and the actor system;
    • peers fanning in FinishedRequests plus the policy version, with rank 0 building each Completion from the same values;
    • ServiceHandle replacing the flatten("rank").slice(rank=0) calls;
    • the router's private methods made public;
    • num_generators read from config instead of the mesh count.
  • Visible but behavior-neutral: the log line "vLLM rejected request" is now "Engine rejected request", the trace span vllm_init is now engine_init, and the engine thread is named engine-loop instead of vllm-engine.
  • Dropped comments are either reworded in their new location or described the old placeholder-min_policy_version fan-in, which no longer exists.

No changes were needed. I'll do 3 (restructuring the comments and docstrings) as a follow-up PR.

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

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.
@tianyu-l
tianyu-l merged commit 3c7c147 into main Oct 17, 2026
@tianyu-l
tianyu-l deleted the rl-generator-split branch October 17, 2026 23:48
tianyu-l added a commit that referenced this pull request Oct 18, 2026
…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).
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.

4 participants