Repository navigation
[rl] Monarch: with RDMA, run the batcher on the last trainer host - #6283
felipemello1 wants to merge 8 commits into
Conversation
3891c2c to
0b57de8
Compare
|
Reply from claude: @claude please review |
|
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 |
There was a problem hiding this comment.
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
- 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. torchtitan/rl/actors/monarch/system.py:191-195-- the move adds a cross-host transfer of each rollout group on the awaitedadd_grouppath. 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 theram_metricshelper are a separate concern; split them out and coordinate with #5926 and #5492 (inline).torchtitan/rl/actors/monarch/batcher.py:80--get_hostnameexists 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_hostalready 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_hostwith one trainer host returnshost_meshes.trainer's slice, whilerollout_worker_hostsdeliberately usesthis_host()for the controller's host (the batch script may not run on t0). With PBS (controller_on_first_trainer_host=False, TODO inlauncher/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.
| host = ( | ||
| this_host() | ||
| if config.rdma_min_tensor_bytes is None | ||
| else batcher_host(host_meshes=self._host_meshes) | ||
| ) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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")]) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
4ddd995 to
b971255
Compare
bb3a6f5 to
ad0a195
Compare
…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.
ad0a195 to
2c08487
Compare
Summary (human-written)
Agent details
TLDR: With RDMA microbatches (
Batcher.Config.rdma_min_tensor_bytesset) 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.Problem
MonarchActorSystem.provisionspawns the batcher's process onthis_host(), the controller's host. WithSlurmLauncher, that is typically trainer host 0, which also runs the controller and the generator router.maybe_release_oldest_batch).forward_backward, one in the controller'straining_batch_queue(maxsize=1), and one waiting to enter it.rl_dapo_qwen3_30b_a3b_math_8kpacks 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.rdma_min_tensor_bytestoday, and the one launch recipe has one trainer host. So no public run changes yet.Solution
spawn_batchernow starts the batcher's process itself, asspawn_rollout_workersdoes: it is the only method that getsBatcher.Config.provisionnow reserves the trainer, the generators and the router.this_host(), as before. With RDMA, it isprovisioning.batcher_host: the last trainer host, orthis_host()without a launcher.controller_on_first_trainer_host) or outside the job, so the last of 2+ trainer hosts is never its host.spawn_batcherlogs "The batcher runs on host ", from a newBatcherActor.get_hostnameendpoint.batcher/ram_gibandbatcher/peak_ram_gib(VmRSS and VmHWM). The newm.ram_metrics(role)reads them from/proc/self/status.BaseRolloutWorker.flush_process_metricsuses it too, with its keys unchanged.spawn_cpu_procsis gone: the router, the batcher and the rollout workers all callHostMesh.spawn_procs.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_batchstill compares the actor's batch with an in-process one at rtol=atol=0.You may ask:
add_groupreturns 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.rollout_worker/ram_gibandpeak_ram_gib, from the same function. Shared libraries count in full, which is small next to a batch at scale.NOTE:
batcher/ram_gib.spawn_batchernow waits for the batcher's constructor, to read its host. A constructor error now shows up there, not at the firstadd_group.SlurmLauncherorPBSLauncherthat is the controller's machine, as before. With a launcher whose controller runs outside the job, the batcher moves to trainer host 0.spawn_batcherlines. 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 beforehost.spawn_procs.m.ram_metricsor replace it.Test plan
test_rollouter_pool.py:test_batcher_host_is_the_last_trainer_host(3 trainer hosts -> t2, 1 -> t0, no launcher ->this_host()).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).test_batcher_actor_returns_the_in_process_batchchecksget_hostnameand the two RAM keys on a real actor.batcher_hostalways returningthis_host()fails 2 placement cases; spawning without the RDMA check fails[by_value];batcher_host(host_meshes=None)fails[rdma].pre-commitpasses.