Skip to content

[rl] Monarch: with RDMA, run the batcher on the last trainer host - #6283

Draft
felipemello1 wants to merge 8 commits into
felipemello1/distribute/3-least-loadedfrom
felipemello1/distribute/4-batcher-host
Draft

felipemello1 wants to merge 8 commits into
felipemello1/distribute/3-least-loadedfrom
felipemello1/distribute/4-batcher-host

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: With RDMA microbatches (Batcher.Config.rdma_min_tensor_bytes set) and 2+ trainer hosts, the batcher's process now runs on the last trainer host instead of the controller's host. With RDMA, the batcher holds each packed batch until every trainer rank has read it, so those batches now sit next to the trainer ranks that read them. Without RDMA (the default), nothing moves. Each batch also reports the batcher's RAM.

                          trainer host 0 (controller, router)        last trainer host
without RDMA              batcher, returns each batch to the controller    -                    unchanged
with RDMA, before         batcher + up to 3 packed batches                 -
with RDMA, this PR        -                                                batcher + up to 3 packed batches
# before: provision() spawned the batcher's process on the controller's host
self._batcher_mesh = spawn_cpu_procs(1)
# after: spawn_batcher() picks the host from the batcher's config
host = (
    this_host()
    if config.rdma_min_tensor_bytes is None
    else batcher_host(host_meshes=self._host_meshes)
)
self._batcher_mesh = host.spawn_procs(per_host={"cpus": 1})

Problem

  1. MonarchActorSystem.provision spawns the batcher's process on this_host(), the controller's host. With SlurmLauncher, that is typically trainer host 0, which also runs the controller and the generator router.
  2. With RDMA, the batcher keeps each packed batch registered until every trainer rank has read it (maybe_release_oldest_batch).
  3. That is up to 3 batches at once: one in forward_backward, one in the controller's training_batch_queue (maxsize=1), and one waiting to enter it.
  4. Size at public recipe scale: rl_dapo_qwen3_30b_a3b_math_8k packs at most 32 prompts x 16 samples x 10,240 tokens = 5.2M tokens. At 38 bytes per token, that is about 0.19 GiB per batch, 0.56 GiB for 3. It grows with the tokens per batch and with every per-token field a batch carries.
  5. When it happens: no public recipe sets rdma_min_tensor_bytes today, and the one launch recipe has one trainer host. So no public run changes yet.

Solution

  1. spawn_batcher now starts the batcher's process itself, as spawn_rollout_workers does: it is the only method that gets Batcher.Config. provision now reserves the trainer, the generators and the router.
  2. Without RDMA, the host is this_host(), as before. With RDMA, it is provisioning.batcher_host: the last trainer host, or this_host() without a launcher.
  3. The controller runs on trainer host 0 (controller_on_first_trainer_host) or outside the job, so the last of 2+ trainer hosts is never its host.
  4. spawn_batcher logs "The batcher runs on host ", from a new BatcherActor.get_hostname endpoint.
  5. Each batch's metrics gain batcher/ram_gib and batcher/peak_ram_gib (VmRSS and VmHWM). The new m.ram_metrics(role) reads them from /proc/self/status. BaseRolloutWorker.flush_process_metrics uses it too, with its keys unchanged.
  6. spawn_cpu_procs is gone: the router, the batcher and the rollout workers all call HostMesh.spawn_procs.
  7. Unchanged: the batcher still registers and drops its own RDMA buffers on its own host, as Monarch's drop requires. Trainer ranks read them as before.

Results

Training batches: unchanged. The same code builds and packs them; only the host of its process changes. test_batcher_actor_returns_the_in_process_batch still compares the actor's batch with an in-process one at rtol=atol=0.

CPU probe (not committed): Monarch ProcessJob, where each "host" is a local process.
batcher_host + spawn_procs, then an actor in the new process reports its host.
trainer hosts   batcher process
3               trainer host 2
2               trainer host 1
1               trainer host 0

You may ask:

  • Why only with RDMA? Without it, add_group returns each batch to the controller, which holds it. A move would free nothing on the controller's host and add a cross-host copy of each batch.
  • Why the last trainer host, not a config field? The last of 2+ trainer hosts is never the controller's, and its trainer ranks read the batches.
  • Why VmRSS, not anonymous memory? It matches the rollout workers' rollout_worker/ram_gib and peak_ram_gib, from the same function. Shared libraries count in full, which is small next to a batch at scale.

NOTE:

  • Not run on GPUs or on 2+ hosts. The first run with RDMA and 2+ trainer hosts should log "The batcher runs on host " with a name other than the controller's, and show batcher/ram_gib.
  • spawn_batcher now waits for the batcher's constructor, to read its host. A constructor error now shows up there, not at the first add_group.
  • On a trainer host, the batcher gets that host's environment (the launcher's job-wide settings, as the trainer ranks do), not the controller's shell.
  • With RDMA and one trainer host, the batcher starts through the launcher's mesh for trainer host 0. With SlurmLauncher or PBSLauncher that is the controller's machine, as before. With a launcher whose controller runs outside the job, the batcher moves to trainer host 0.
  • An approved open PR makes RDMA the default and edits the same spawn_batcher lines. Once it lands, the batcher leaves the controller's host by default when there are 2+ trainer hosts. Whichever PR lands second rebases and keeps that PR's RDMA backend check before host.spawn_procs.
  • Two open drafts add per-process memory metrics from anonymous memory, under other keys. When they rebase, they should use m.ram_metrics or replace it.

Test plan

python -m pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config -q
# 1008 passed, 7 skipped (6 need Verifiers, 1 skipped on main)
# The same command with Verifiers 0.4.1 installed:
# 1115 passed, 1 skipped (skipped on main)
  • New in test_rollouter_pool.py: test_batcher_host_is_the_last_trainer_host (3 trainer hosts -> t2, 1 -> t0, no launcher -> this_host()).
  • New in test_shutdown.py: test_spawn_batcher_leaves_the_controller_host_only_with_rdma (without RDMA -> this_host(); with RDMA -> batcher_host, called with the actor system's host meshes).
  • Changed: the provision-order test expects only the router's CPU process. test_batcher_actor_returns_the_in_process_batch checks get_hostname and the two RAM keys on a real actor.
  • Each new test was watched failing: batcher_host always returning this_host() fails 2 placement cases; spawning without the RDMA check fails [by_value]; batcher_host(host_meshes=None) fails [rdma].
  • pre-commit passes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@felipemello1
felipemello1 added this pull request to stack #6205 November 20, 2026 05:50
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/4-batcher-host branch from 3891c2c to 0b57de8 Compare November 22, 2026 09:03
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 32s —— View job


Needs discussion: the PR frees about 0.56 GiB for a config no recipe uses, adds a cross-host hop to every add_group, and overlaps the #6301-#6303 data-plane redesign. See the review.

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

Verdict: Needs discussion -- the memory this frees is small, no recipe exercises it today, and the move adds a cross-host hop to every add_group. Meanwhile the open data-plane stack (#6301-#6303) changes what the batcher holds, which makes its placement close to irrelevant.

What this PR does. With Batcher.Config.rdma_min_tensor_bytes set and a launcher, spawn_batcher spawns the batcher's process on the last trainer host instead of this_host(). Without RDMA nothing changes. The batcher spawn moves from provision to spawn_batcher, spawn_cpu_procs is deleted, a get_hostname endpoint feeds one log line, and each batch gains batcher/ram_gib and batcher/peak_ram_gib through a new shared m.ram_metrics.

Example. SlurmLauncher, trainer hosts [t0, t1], RDMA on, controller on t0:

before: controller(t0) --add_group(group)--> batcher(t0)    holds <=3 batches on t0
        trainer ranks on t0, t1 RDMA-read from t0
after:  controller(t0) --add_group(group)--> batcher(t1)    holds <=3 batches on t1
        trainer ranks on t0, t1 RDMA-read from t1

At rl_dapo_qwen3_30b_a3b_math_8k scale this moves about 0.56 GiB from t0 to t1, and each group now crosses the network once more before it is packed.

Must fix

  1. Problem not shown, and overlaps an in-flight redesign. The description says no public recipe sets RDMA, the one launch recipe has one trainer host, and the saving is about 0.56 GiB. The controller's host already runs the group buffer and up to 128 rollout workers at about 0.8 GiB each (max_rollout_workers_per_host). Without a measured memory problem on t0, the PR adds about +129 net LoC for a hypothetical config. The wwwjn stack is also redesigning this exact path: #6302 splits the batcher into plan and bytes, and in #6303 "the batcher now returns only the step's plan", so trainer DP leaders pack their own microbatches and the batcher holds no packed tensors. Once that lands, the batcher's host no longer decides where batches sit, and moving it only adds latency. Please agree with @wwwjn on which path owns batch memory before landing this, or show a run where t0's RAM is the actual limit.
  2. torchtitan/rl/actors/monarch/system.py:191-195 -- the move adds a cross-host transfer of each rollout group on the awaited add_group path. The PR's own argument against moving the by-value batcher applies here too, and #6303 measures this hop at up to 2.33 s (inline).

Should consider

  • torchtitan/rl/actors/monarch/batcher.py:71 -- the RAM metric and the ram_metrics helper are a separate concern; split them out and coordinate with #5926 and #5492 (inline).
  • torchtitan/rl/actors/monarch/batcher.py:80 -- get_hostname exists only for a log line; log from the actor's __init__ instead (inline).
  • tests/rl/unit_tests/cpu/test_shutdown.py:668 -- a fully mocked test of a two-way conditional; test_batcher_host_is_the_last_trainer_host already covers host selection (inline).

Questions

  • If the goal is to keep the controller's host light, is the batcher the biggest consumer there? The group buffer holds the same per-token arrays before they reach the batcher, and #6303 reports controller RSS of 7.84 GB with score centering, mostly from pickling those arrays through the controller.
Details
  • batcher_host with one trainer host returns host_meshes.trainer's slice, while rollout_worker_hosts deliberately uses this_host() for the controller's host (the batch script may not run on t0). With PBS (controller_on_first_trainer_host=False, TODO in launcher/pbs.py:48) and one trainer host, the batcher therefore moves from the controller's machine to t0. That is harmless but differs from how the rollout workers handle the same case.
  • If this lands before #5413 (RDMA by default), every multi-host run moves the batcher, so the add_group latency point becomes the default path.

Not verified: the cross-host add_group cost at public recipe scale (no 2+ host run), and whether Monarch forwards actor logs to the controller by default.

Comment on lines +191 to +195
host = (
this_host()
if config.rdma_min_tensor_bytes is None
else batcher_host(host_meshes=self._host_meshes)
)

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.

With RDMA, every add_group now sends its rollout group from the controller (trainer host 0) to the last trainer host. Before this PR that hop stayed on one host. _batcher_loop awaits each call (controller.py:1354-1358), so the cross-host transfer is on the path that feeds training_batch_queue.

The description gives "would add a cross-host copy of each batch" as the reason not to move the batcher without RDMA. The same argument applies here, because the groups going into the batcher hold the same per-token arrays as the packed batches coming out. #6303 measures this hop already: add_group takes up to 2.33 s with score centering at 4K completions, about 17 MB per group.

Please either measure batcher_add_group before and after with 2+ trainer hosts, or keep the batcher on this_host() until the data-plane stack decides where the bytes go (see the review body).


@endpoint
async def get_hostname(self) -> str:
return socket.gethostname()

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 only use of this endpoint is one startup log line, and because of it spawn_batcher now waits for the constructor. A smaller option: log socket.gethostname() from _BatcherActorEndpoints.__init__, which already calls init_logger(). That removes the endpoint, the await in spawn_batcher, and the get_hostname fakes in the tests (_cpu_host, and the hostname assertion in test_batcher_actor.py). Unverified: whether Monarch forwards actor stdout to the controller by default in these launchers.

batch, has_samples = super().add_group(rollout_group=rollout_group)
if batch is not None:
# This process's RAM, logged with the step this batch trains.
batch = replace(batch, metrics=[*batch.metrics, *m.ram_metrics("batcher")])

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.

batcher/ram_gib / peak_ram_gib, and moving ram_metrics out of rollouter.py into a shared helper, are observability changes that don't depend on where the batcher runs. Under "one concern per PR" they belong in their own PR, and that PR should be coordinated with #5926 and #5492, which add per-process memory metrics under other keys. Putting them in a separate PR also lets this metric land even if the placement change doesn't.

[(None, "this host"), (1024, "the batcher's host in host_meshes")],
ids=["by_value", "rdma"],
)
def test_spawn_batcher_leaves_the_controller_host_only_with_rdma(

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.

Everything here is mocked: this_host, batcher_host, the proc mesh and the actor. The test only checks which branch of a two-way conditional in spawn_batcher runs, which is the "repeat mock calls" pattern that .claude/rules/tests.md asks us to avoid. test_batcher_host_is_the_last_trainer_host already covers the actual host selection. Suggest deleting this test along with the _cpu_host helper, or keeping only the provision-order test's use of _cpu_host.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/4-batcher-host branch 2 times, most recently from 4ddd995 to b971255 Compare November 22, 2026 15:11
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/4-batcher-host branch 6 times, most recently from bb3a6f5 to ad0a195 Compare November 23, 2026 20:12
Felipe Mello added 8 commits November 23, 2026 17:56
…ead per 4 rollouts, and gc.freeze

Each rollout worker adds its metrics to each training group it returns, through
BaseRolloutWorker.flush_process_metrics: rollout_worker/event_loop_lag_ms (Max) and _per_s (Mean),
rollout_worker/thread_pool_lag_ms (Max) and _per_s (Mean), rollout_worker/ram_gib (VmRSS, now) and
rollout_worker/peak_ram_gib (VmHWM, the most since start), from /proc/self/status.
BaseRolloutWorker.setup_async (moved from MessageEnvRolloutWorker) builds the renderer, then calls
GarbageCollector.freeze (as the controller does) and starts the metrics. VerifiersRolloutWorker ends
its own setup_async the same way. MessageEnvRolloutWorker.run_group and
VerifiersRolloutWorker.run_group end with flush_process_metrics. The Monarch actor doesn't change.
The controller keeps the worker's metrics on the group, and logs its own
controller/event_loop_lag_ms and _per_s with each step.

EventLoopLag and ThreadPoolLag live in observability/metrics/loop_lag.py. ThreadPoolLag sends an
empty call to the default thread pool every 50 ms and records how late a thread starts it. A call
that waits 60 s logs a warning.

Rollouter.Config.rollouts_per_thread (default 4) replaces num_threads_per_worker (default 4): each
worker starts ceil(rollouts_per_worker / rollouts_per_thread) threads, 32 by default.
…0 and min_p 0.0

The server reads request bodies up to 1 GiB (aiohttp's default is 1 MiB). It
accepts the sampling params that filter nothing: top_k -1 or 0 and min_p 0.0.
Verifiers 0.4.1 sends top_k=-1 and min_p=0.0 on every call. Other values raise.
…erver is gone

Each rollout worker loads its Verifiers env and runs each episode with
env.run_slot. The env server process and VerifiersRollouter are deleted.
Rollouter.close calls a new per-worker close before it stops the workers;
both close timeouts are Rollouter.Config fields.

The worker registers each trace's session with its rollout group from
on_trace, so the group id no longer rides in the sampling params. Verifiers'
named rewards and metrics are logged on turn 0 as verifiers/reward/<name>
and verifiers/metric/<name>.
Pins Verifiers 0.4.1 and renderers 0.2.0, which move together. Main's httpx
pin stays: renderers 0.2.0 still imports httpx without declaring it, so its
TODO no longer names a version. The trace converter reads 0.4.1's numpy
arrays without copying them to lists (split_prompt takes arrays), checks
each node's logprob count, and skips a branch Verifiers marks untrainable;
the Terminal-Bench recipe and harness follow what 0.4.1 deleted (HarborEnv,
Runtime.run_program); the generation server replies with packed float32
logprobs. A trace the env's judge dropped becomes the new DROPPED status:
not trained, not an error.
Rollouter.Config.worker_roles (RolloutWorkerRoles) has one field per role: trainer, generator and
controller. Each is True (add the hosts with this role), False (never use a host with this role) or
None (no opinion). A host runs rollout workers if at least one of its roles is True and none is
False, and a host with several roles counts once. The workers spread evenly over those hosts. The
default, controller=True with the others None, keeps every worker on the controller's host, as
before. RolloutWorkerRoles raises when no role is True. Controller.Config checks that again,
because the config loader reruns only its __post_init__. rollout_worker_hosts raises when a False
role vetoes every host that a True role picked.

The launcher says where the controller runs: MonarchLauncher.controller_on_first_trainer_host, False
by default. SlurmLauncher and PBSLauncher set True: their batch script runs on the job's first node
(typically, for Slurm), and SlurmJob and PBSJob give the first nodes to the trainer mesh. With True,
trainer host 0 also has the controller's role, so trainer=True, generator=True, controller=False
runs workers on every host but the controller's. The controller's host always spawns its workers
through this_host(), the controller's own machine, as before. With False, that machine is outside
the job and its only role is the controller's. Without a launcher, the workers run on this host.

MonarchActorSystem.Config.max_rollout_workers_per_host (128) caps the workers on one host. Each
host's workers get their own proc mesh. spawn_rollout_workers returns a RolloutWorkersHandle
(by_host, by_worker), and the meshes stop in parallel. The Rollouter calls setup_async,
sync_log_step and close on each host's workers, and sends each group to one worker picked at random.
A host whose close raises doesn't cut the other hosts' close short.
Rollout workers now run on the generators' hosts by default:
RolloutWorkerRoles defaults to generator=True, the others None. Whatever a
worker reads by path must then sit at the same path on every such host: in
a shared folder (a filesystem mounted at the same path on every host)
first, or in a copy on each host as the last fallback.

- RLDataset.Config.paths_on_every_host: the paths a dataset's samples point
  at (none by default). SLAKE names its data dir, Geometry3K its image dir,
  a Verifiers Harbor taskset its cache dir. Rollouter.setup_async passes the
  training dataset's paths to each rollout worker actor. The actor checks them
  (check_paths_exist_on_this_host in rollout/data.py) before it builds the
  worker, so a host without one fails the job at start, with the path and the
  host. RolloutWorkerActor now builds its worker in setup_async, so a build
  error reaches the controller as an endpoint error. Its close skips a worker
  that setup_async never built.
- Each rollout worker process starts with OMP_NUM_THREADS=1 unless its
  host's env sets it (apply_rollout_worker_env_defaults, the spawn's
  bootstrap), so that if worker code runs torch or numpy math, it uses 1
  thread instead of one per CPU.
- The two ERROR_INFRA log lines in rollout/rollouter.py and the Verifiers
  worker's failed-rollout line name the worker's host.
- VerifiersRolloutWorker.setup_async runs `docker version` once when the
  env's agents run in Docker. A host without a usable daemon fails the job
  at start, and the error names the host. It waits at most 60 s.
- Terminal-Bench: a worker builds each task as TerminalTask, which raises
  when the task's tests/ is missing on the worker's host (unless the task's
  separate verifier image carries its own tests). The group fails before
  any sandbox starts, instead of training as a TaskError.
- Search-R1 keeps its workers on the controller's host
  (generator=None, controller=True): its retriever listens on 127.0.0.1.
- The Verifiers worker's renderer_multiplex docstring says what it limits:
  the model calls in flight that share one renderer. A rollout counts from
  rendering its prompt until the model's reply arrives, not while its tools
  run. A renderer loaded past the limit stays until the worker exits.
- Docs: "Rollout workers on more than one host" in the RL README, "More
  than one host" in the Terminal-Bench README, and pointers to it from the
  Search-R1 README, the SLAKE and Geometry3K recipes and the Monarch README.
…n flight

The Rollouter keeps one _RolloutWorkerLoad (a RoutingCandidate) per worker and picks with
LeastLoadedRoutingStrategy: the lowest count of rollouts in flight, the one chosen longest ago on a
tie. The count rises by the group size once the call is sent and drops when the call ends.
Rollouter.metrics() adds rollout_worker/num_rollouts_in_flight_max and _mean to each step's metrics.

The RL README's "Rollout workers on more than one host" says why a host whose groups fail at once
gets most new groups.
With RDMA microbatches (Batcher.Config.rdma_min_tensor_bytes set), the batcher holds each packed
batch until every trainer rank has read it: up to 3 at once (one in forward_backward, one in the
controller's training_batch_queue, one waiting to enter it). MonarchActorSystem.spawn_batcher now
starts the batcher's process on the last trainer host (provisioning.batcher_host). The controller
runs on trainer host 0 (SlurmLauncher) or outside the job, so with 2+ trainer hosts those batches
stay off the controller's host. Without RDMA, each batch goes back to the controller, so the batcher
stays on the controller's host, as before.

spawn_batcher starts the batcher's process itself, as spawn_rollout_workers does, because only it
gets the Batcher.Config. provision now reserves the trainer, the generators and the router.
spawn_cpu_procs is gone: the router and the batcher call HostMesh.spawn_procs directly.
spawn_batcher logs the batcher's host (BatcherActor.get_hostname).

Each batch's metrics gain batcher/ram_gib and batcher/peak_ram_gib (VmRSS and VmHWM). The new
metrics.ram_metrics(role) reads them from /proc/self/status for the batcher and the rollout workers,
whose rollout_worker/ram_gib and peak_ram_gib keep their names.
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/4-batcher-host branch from ad0a195 to 2c08487 Compare November 24, 2026 02:15

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant