Repository navigation
[rl] Spread rollout workers over the hosts of chosen roles - #6113
felipemello1 wants to merge 1 commit into
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 3m 27s —— View job Needs discussion: this adds |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code is sound, but it adds a knob that no recipe sets, for a bottleneck the description says hasn't been seen yet, and it hasn't run on a real multi-host job.
What this PR does. It adds Rollouter.Config.workers_on_controller_host (default True). Setting it to False makes MonarchActorSystem.spawn_rollout_workers spawn one CPU proc mesh on each job host except trainer host 0, splitting the workers as evenly as it can. spawn_rollout_workers now returns a RolloutWorkersHandle(by_host, by_worker), and the Rollouter dispatches each group with random.choice(by_worker).run_group.call_one(...) instead of .choose(). RolloutWorkerActor offsets its log rank by first_worker_index, and the Verifiers config raises when the knob is False.
Example.
Slurm: trainer mesh [t0, t1], generators [g0], [g1]; 5 workers
rollout_worker_hosts -> [t1, g0, g1]
True (default): t0: 5 (same as before)
False: t1: 2, g0: 2, g1: 1 log ranks 0-1, 2-3, 4
Packed 1-node job (all roles on node_0), False -> hosts[1:] is empty -> this_host(): 5
Must fix
- The "Summary (human-written)" section is empty. Only the author can write it. It should say why this should land before a run needs it (see 2).
- Gate: this option has no consumer.
.claude/rules/config.mdsays to "expose only options a verified recipe uses", and no recipe setsworkers_on_controller_host=False. The description itself says "No run has shown the controller host to be the bottleneck yet" and "Not run on a real multi-host job". So the PR adds a bool, a newActorSystemparameter, a handle type and about 330 lines of tests for a path nobody has run. The default path changes too (.choose()becomesrandom.choice+call_one, andstopnow logs failures instead of raising). Please either name the run or recipe that needs spreading (e.g. Terminal-Bench 9B's 24 workers saturating t0, with measurements), or hold this PR until one exists. A maintainer should decide whether to land opt-in headroom ahead of a measured need.
Should consider
tests/rl/unit_tests/cpu/test_shutdown.py:531-- the test depends on Monarch's internalHYPERACTOR_PROCESS_NAMEformat; add a TODO or avoid it.tests/rl/unit_tests/cpu/test_shutdown.py:571-- the spawn and placement tests belong intest_rollouter_pool.py, not the shutdown tests.
Details
- Smaller alternative if this is held. #6114 (least-loaded dispatch) is stacked on this PR, but it only needs
by_worker. On one mesh, that is[mesh.flatten("rank").slice(rank=r) for r in range(num_workers)], about 10 lines inspawn_rollout_workers. #6114 could land on #6112 with that, without the host spreading,on_controller_host,rollout_worker_hosts,first_worker_indexor the ProcessJob test. - Controller-host assumption.
rollout_worker_hostsdropshosts[0], which is trainer host 0.Layout.host_meshesalways puts the trainer first, and the TODO about SlurmJob's host order covers the remaining risk. Roles sharing a mesh are deduplicated byid(), which matchesLayout.host_meshes, where roles that share a mesh share one object. So it works for both the packed and the per-role layouts. - Overlapping work. #5899 removes the Verifiers env server, which would let the new check in
examples/verifiers/rollouter.pybe deleted. #6099 also changes worker setup and stop and will conflict withstop_rollout_workershere. #5925 is the closed predecessor; it also set True explicitly in the Search-R1 and Terminal-Bench recipes. This PR leaves that to the TODO, which is fine while the default is True. random.choiceuses the globalrandomstate. Nothing else intorchtitan/draws from it (I checked), and #6114 replaces it anyway.- No change to training numerics: placement only decides which process runs a group.
Not verified: Monarch's .choose() semantics (whether uniform random matches it), and any real multi-host behavior.
| def _simulated_host() -> str: | ||
| """The host this process runs on, as `ProcessJob` names it, e.g. "trainer_1".""" | ||
| # e.g. "anon-0 @ trainer_1" | ||
| return os.environ["HYPERACTOR_PROCESS_NAME"].split("@")[-1].strip() |
There was a problem hiding this comment.
This parses HYPERACTOR_PROCESS_NAME ("anon-0 @ trainer_1"), which is an undocumented Monarch internal. If Monarch changes the format, test_rollout_workers_spread_over_the_hosts_of_a_job breaks and the failure won't point at anything in torchtitan. If there's no public way to get a proc's host, add a TODO saying this depends on a private Monarch detail (CLAUDE.md principle 3). Alternatively, have the worker report socket.gethostname() plus the proc mesh it was spawned on. ProcessJob hosts all share one hostname, though, so the env var may really be the only option here.
There was a problem hiding this comment.
Reply from claude: Fixed in bb91c5b: a one-line # TODO: at the parse says the env var is private, and that the simulated ProcessJob hosts share one hostname.
| return _SpreadWorker(self.marker_dir) | ||
|
|
||
|
|
||
| def test_rollout_workers_spread_over_the_hosts_of_a_job(tmp_path, monkeypatch): |
There was a problem hiding this comment.
This test covers spawning (placement, log ranks, cross-mesh calls), not shutdown. test_rollouter_pool.py already holds the rollout worker spawn tests, so it fits better there. The same goes for test_rollout_worker_hosts_are_every_host_but_trainer_host_0, unless the plan is to grow test_shutdown.py into the provisioning test file (_FakeHostMesh already lives here). Only test_stop_rollout_workers_stops_the_other_hosts_when_one_fails belongs in this file.
There was a problem hiding this comment.
Reply from claude: Fixed in bb91c5b: the host-list test and the real-Monarch spread test moved to test_rollouter_pool.py. Only the stop test stays in test_shutdown.py.
1641c9f to
bb91c5b
Compare
|
Reply from claude: The two test items are fixed in bb91c5b. On the gate: spreading the workers is one of the goals the author set for this stack, so the PR stays opt-in as is, with the TODO at the field saying when a recipe flips it. Whether it lands before a recipe needs it is for the author and a maintainer; the smaller alternative you describe is noted for the author. @claude please review |
|
Claude finished @felipemello1's task in 1m 20s —— View job Needs discussion: both test comments are fixed and I found no new problems. A maintainer still has to decide whether to land the opt-in option, and the human-written summary is still empty. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- bb91c5b fixes both test comments and I found no new defects. The remaining questions are for the author and a maintainer: whether to land an option no recipe sets yet, and the empty human-written summary.
What changed since the last review.
- The
HYPERACTOR_PROCESS_NAMEparse now has a TODO saying it relies on a private Monarch env var. Resolved. - The host-list test and the real-Monarch spread test moved to
test_rollouter_pool.py. Onlytest_stop_rollout_workers_stops_the_other_hosts_when_one_failsis still intest_shutdown.py. Resolved.
Example.
Slurm: trainer mesh [t0, t1], generators [g0], [g1]; 5 workers
True (default): t0: 5 (same as before)
False: t1: 2, g0: 2, g1: 1 log ranks 0-1, 2-3, 4
Packed 1-node job, False -> hosts[1:] is empty -> this_host(): 5
Must fix
- The PR description still has an empty "Summary (human-written)" section. Only the author can fill it in. It should say why this should land before a run needs it.
- Gate, still open: no recipe sets
workers_on_controller_host=False, and the description says no run has shown the controller host to be the bottleneck. The author's reply defers that to a maintainer, which is the right call. A maintainer should decide either to land opt-in headroom ahead of a measured need, or to hold this PR. If it's held, #6114 can land on #6112 with onlyby_workerbuilt from the one mesh, about 10 lines inspawn_rollout_workers.
Details
I re-checked these at HEAD:
rollout_worker_hostsdedups meshes byid(). That matchesLayout.host_meshes(launcher/base.py:86), where roles that share a mesh get the same object. So the packed layout and the per-role layout both drop exactly trainer host 0.- The real
flatten("hosts").slice(hosts=i)path runs in the ProcessJob test, against real Monarch host meshes. spawn_rollout_workersappends each proc mesh before it spawns actors on it, so a later host that fails to spawn still gets its earlier meshes stopped. Hosts that get no workers are skipped (num_workers < len(hosts)).stop_rollout_workersnow logs a failed stop and moves on instead of raising, the same asstop().Rollouter.closedoesn't depend on the old raise.sync_log_step.call(step=step)matches the endpointsync_log_step(self, step: int)(rollout_worker.py:86).- The Verifiers check runs in
VerifiersRollouter.Config.__post_init__, after the base__post_init__, so a bad config fails when it is built. - Nothing calls
.choose()on an actor handle any more (the remaining.choosehits are routing strategies), so removing it from theActorSystemcall convention is consistent. - No change to training numerics: placement only decides which process runs a group.
Not verified: whether random.choice matches Monarch's .choose() selection (I couldn't read the Monarch source here), and any behavior on a real multi-host job.
bb91c5b to
8f6ef23
Compare
|
Reply from claude: The author decided on the gate: spreading is now the default (8f6ef23), so the option has its consumers.
@claude please review |
|
Claude finished @felipemello1's task in 2m 15s —— View job Needs discussion: spreading the workers is now the default, but no real multi-host job has run with it yet, and the human-written summary is still empty. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- with False as the default, the option now has consumers, but every multi-host run now places its workers differently, with no measured bottleneck and no real multi-host run behind the change. A maintainer has to accept that before this lands.
What changed since the last review. Rollouter.Config.workers_on_controller_host now defaults to False (rollouter.py:121). Search-R1, SLAKE and Geometry3K set True in their recipes, and VerifiersRollouter.Config overrides the default to True and still raises on False. I checked the audit against the code. The only env-side 127.0.0.1 uses are Search-R1's search_url and the Verifiers env/generation servers, and the only local image paths are SLAKE and Geometry3K. So the in-repo recipes that need the controller host are all covered. One-host jobs and runs without a launcher behave as before: hosts[1:] or [this_host()], and with no launcher the spawn is the same as the old spawn_cpu_procs(num_workers).
Example.
rl_grpo_qwen3_0_6b_flex_slurm (2 nodes): node 0 = trainer, node 1 = generator_0..3
before / True: node 0: all workers (with controller, router, batcher, 4 trainer ranks)
after (default): node 1: all workers (with 4 vLLM generators)
144-GPU DAPO-Math: workers split over every host but trainer host 0
Must fix
- The "Summary (human-written)" section is still empty. Only the author can write it. With the new default, it should say why every multi-host run should move its workers now, when the description says "No run has shown the controller host to be the bottleneck yet".
- The new default has not run on a real multi-host job. The description says "The first multi-host run of an AlphabetSort or DAPO-Math recipe is also the first with spread workers". Before the opt-in flip, only people who chose False hit this path. Now every multi-host user does, and the ProcessJob test can't check cross-host pickling of
generate_fn, cross-host networking, orhf_assets_pathbeing readable on generator hosts. The cheapest check isrl_grpo_qwen3_0_6b_flex_slurmon 2 nodes for 10+ steps. Paste theRollout workers per host: [...]log line and the step logs (or throughput) next to a True run. If that run isn't possible before merge, a maintainer has to decide between landing with False unverified and keeping True as the default until it runs.
Details
- Earlier items still resolved at HEAD: the TODO for the private
HYPERACTOR_PROCESS_NAME, and the spawn tests now intest_rollouter_pool.py. - The tests changed only to match the new default.
_rollouter_without_datasetssets True explicitly, andtest_setup_spawns_worker_pool_on_controller_hostpasses a launcher's hosts, so it checks that True ignores them. - The Verifiers subclass overrides the field with a default of True and checks it after
Rollouter.Config.__post_init__.test_verifiers_rollouter_rejects_spread_workersusesdataclasses.replace, which reruns__post_init__, so that test does run the check. - The CPU cost moves rather than disappears: in the 2-node example, the workers now share node 1 with four vLLM processes instead of sharing node 0 with the trainer. Which placement is better depends on the load. That is part of why a run is needed (item 2), not a defect in the code.
- Out-of-repo envs that call a 127.0.0.1 service or read local files will now fail on multi-host jobs with a connection or file error from a remote worker. The field's docstring says when to set True, so the failure is loud, not silent.
- No change to training numerics: placement only decides which process runs a group.
Not verified: any real multi-host behavior, and whether random.choice matches Monarch's .choose() selection.
|
Reply from claude: Agreed: the new default needs a real multi-host run before it lands. The plan is the check you name: |
| for rank in range(num_host_workers) | ||
| ] | ||
| # TODO: log each worker's hostname too, so a controller off trainer host 0 shows up. | ||
| # It needs a hostname endpoint and one gather at setup. |
There was a problem hiding this comment.
can you help me better understand this todo?
There was a problem hiding this comment.
Reply from claude: it was a check on one guess, "trainer host 0 runs the controller": the log showed counts per host,
not names. Two things make it moot. controller_host() now holds that guess in one place; under "all_hosts" a
wrong guess only changes which host gets an extra worker last. And every structured-log record already carries
host_name and the worker's unique rank (structured_logger/jsonl_handler.py:93, :97), so the worker-to-host map
is in the logs. I removed the TODO.
| by_host.append(host_workers) | ||
| by_worker += [ |
There was a problem hiding this comment.
letss add a couple of lines here with intuition on why we would want by host and by worker
There was a problem hiding this comment.
Reply from claude: done:
# Two views of the same workers:
# by_host[i] every worker on host i, one `.call()` for all of them (setup, log step)
# by_worker[j] worker j alone, for `.call_one()`: the rollouter sends each group to one worker| RolloutWorkerActor, | ||
| worker_config=config, | ||
| worker_kwargs=kwargs, | ||
| num_threads=num_threads, |
There was a problem hiding this comment.
how os num of threads defined? is this a good default?
There was a problem hiding this comment.
Reply from claude: Rollouter.Config.num_threads_per_worker, default 4. It sizes each worker's default thread pool,
the one behind asyncio.to_thread. In a worker, that pool runs the renders, prompt builds and parses in TokenEnv
(token_env.py:197-365); Math-Verify has its own pool. Not measured. At 128 rollouts per worker, renders may queue on
4 threads, and the lag metric doesn't show that wait. I left it at 4 with a TODO: a span around the render would show
the wait.
| num_host_workers = num_workers // len(hosts) + ( | ||
| host_index < num_workers % len(hosts) | ||
| ) | ||
| if num_host_workers == 0: |
There was a problem hiding this comment.
the second part is not intuitive. Please make it easier to understand. You could break it down into two parts, give a numerical example to make it easier to the reader.
There was a problem hiding this comment.
Reply from claude: done:
# Split the workers evenly; the first hosts take one extra each until none are left.
# 5 workers on 3 hosts: 5 // 3 = 1 each, and 5 % 3 = 2 extra -> [2, 2, 1].
min_workers_per_host, num_extra_workers = divmod(num_workers, len(hosts))| [this_host()] | ||
| if on_controller_host | ||
| else rollout_worker_hosts(host_meshes=self._host_meshes) | ||
| ) |
There was a problem hiding this comment.
lets put all the logic on rollout_worker_hosts and not have if/else here
There was a problem hiding this comment.
Reply from claude: done. spawn_rollout_workers calls rollout_worker_hosts(host_meshes=..., placement=...), and
nothing else decides hosts.
| return this_host().spawn_procs(per_host={"cpus": num_procs}) | ||
|
|
||
|
|
||
| def rollout_worker_hosts(*, host_meshes: HostMeshes | None) -> list[HostMesh]: |
There was a problem hiding this comment.
I believe we should make the default to evenly distribute across all hosts, and have a flag to exclude controller host, default as False.
As we do runs, we can compare peak host memory, and see if theres a good reason to change this default.
There was a problem hiding this comment.
Reply from claude: done. rollouter.worker_placement defaults to "all_hosts", evenly, with the controller's host
last, so extra workers go elsewhere first. "all_but_controller_host" is the flag you asked for. A third value,
"controller_host_only", keeps Terminal-Bench and Search-R1's 2-host perf recipe on the controller host, because
their envs need it. One field can't hold the contradiction two booleans can (both True). For the comparison: W&B
already logs the controller host's memory (System tab, memory %), and each worker logs rollout_worker/peak_rss_gib
and rollout_worker/event_loop_lag_ms.
| for i, mesh in enumerate(meshes): | ||
| try: | ||
| await mesh.stop() | ||
| except Exception: | ||
| logger.exception("rollout worker mesh.stop[%d] failed", i) |
There was a problem hiding this comment.
could we have all meshes be called to stop in parallel, instead of sequentially?
There was a problem hiding this comment.
Reply from claude: done for the rollout worker meshes, with a test where every stop must start before any finishes
(a one-by-one loop times out). MonarchActorSystem.stop() (router, batcher, trainer, generators) is main's code and
stays as it is.
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class RolloutWorkersHandle: |
There was a problem hiding this comment.
i wonder if we are missing a better abstraction for workers across hosts, like we had services in forge. Is this a common pattern in titan now? i think we do something similar for batcher -> trainer?
There was a problem hiding this comment.
Reply from claude: a services layer brings its own placement and restart rules: a replica takes the controller host
or whole hosts, an error restarts the replica, and load is counted in calls. Our workers need none of that. Titan's
pattern is a handle the actor system returns, grouped the way callers need: TrainerHandle(all_ranks, rank0, by_dp_rank), and RolloutWorkersHandle(by_host, by_worker) has the same shape. Batcher -> trainer is a fixed slice,
not a pick: DP rank i always trains column i. For the pick, the third PR of this stack now uses
LeastLoadedRoutingStrategy, the class the generator router and the DP-rank router use to place new sessions (the
sticky strategy's fallback). So titan has one way to pick the least loaded target.
| *, | ||
| num_workers: int, | ||
| num_threads: int, | ||
| on_controller_host: bool, |
There was a problem hiding this comment.
can we ahve some independent function that defines what "controller host" is? today we put it on first node of trainer. But say someone wanted to put it on on its own node. I would like that, if they changed it, we didnt have to change the logic here either.
There was a problem hiding this comment.
Reply from claude: done. controller_host(host_meshes=...) in provisioning.py names the controller's host (trainer
host 0 today, and its docstring says it's a guess). It is used to exclude the controller's host, and to put it last
under "all_hosts", where a wrong guess only changes which host gets an extra worker last. "controller_host_only"
uses this_host(), which is the controller's machine by definition. If the controller moves to another job host,
only controller_host() changes. If it gets a node outside the job, its return type and rollout_worker_hosts
change, both in provisioning.py; spawn_rollout_workers doesn't.
| ), | ||
| rollouter=Rollouter.Config( | ||
| # Each worker opens its images by a local path, which may exist only on the controller host. | ||
| workers_on_controller_host=True, |
There was a problem hiding this comment.
we dont need this. You are putting it here because its single node, right? lets make the change i mentioned to always distribute equally. If we have a single node, naturally it will be in the controller host.
There was a problem hiding this comment.
Reply from claude: right, removed. Geometry3K runs on one host, so its workers land there anyway. The only recipe line
left is Search-R1 30B-A3B perf. It takes 2 hosts, and a worker on the second host would reach no retriever: _search
returns an empty result with a warning (search_r1/env.py:91-95), so the run would train on empty searches without
failing. The Search-R1 README now says so for multi-host runs.
8f6ef23 to
da71dbc
Compare
|
Reply from claude: @claude please review. The code at this head answers the maintainer review (replies are in each thread). Follow-up work, not in this push:
|
|
Claude finished @felipemello1's task in 2m 29s —— View job Needs discussion: the code answers every review thread and has no correctness defects. The new default still needs a real multi-host run, the human-written summary is empty, and one Search-R1 placement suggestion is posted inline. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code at HEAD answers every review thread and I found no correctness defects. Two things are still open: the new default has not run on a real multi-host job, and the human-written summary is empty.
What this PR does. It adds Rollouter.Config.worker_placement, which defaults to "all_hosts". rollout_worker_hosts (provisioning.py:314) puts the controller's host last, so it gets a worker only after every other host has one, and controller_host() holds the "trainer host 0" guess. spawn_rollout_workers splits the workers with divmod, spawns one CPU proc mesh per host, and returns RolloutWorkersHandle(by_host, by_worker). Each group goes to random.choice(by_worker), and the hosts are stopped concurrently. The Verifiers rollouter defaults to "controller_host_only" and raises on any other value. Search-R1 perf pins it as well.
Example.
trainer [t0, t1], generators [g0], [g1]; 5 workers
all_hosts: t1: 2, g0: 1, g1: 1, t0: 1 (log ranks 0-1, 2, 3, 4)
all_but_controller_host: t1: 2, g0: 2, g1: 1
controller_host_only: this_host(): 5 (same as before)
1-node launcher job, all_hosts -> trainer mesh host 0 (same machine as before)
Must fix
- The "Summary (human-written)" section is still empty, and only the author can write it.
- The new default still hasn't run on a real multi-host job: the description's NOTE says so, and your earlier reply plans the 2-node
rl_grpo_qwen3_0_6b_flex_slurmcheck. The ProcessJob test covers cross-mesh calls on one machine. It doesn't cover cross-host networking, or readinghf_assets_pathand SLAKE's data dir on generator hosts. Please post that run'sRollout workers per hostline and its step times. If it can't run before merge, a maintainer has to accept landing the default unverified.
Should consider
torchtitan_recipes/rl/search_r1.py:276-- only the perf recipe is pinned. A multi-host run of the other Search-R1 recipes trains on empty searches without failing. Pin the placement once in_search_r1_rollouter_config()(inline).
Details
I checked the maintainer threads at HEAD:
- The hostname TODO is removed.
- The
by_host/by_workercomment and thedivmodsplit with a worked example are in. rollout_worker_hostsdecides every placement, andspawn_rollout_workershas no if/else.controller_host()is its own function.stop_rollout_workersusesgather(..., return_exceptions=True). The coroutine wrapper means astop()that raises synchronously doesn't stop the others from running.- The Geometry3K pin is removed.
- The
num_threads_per_workerTODO is atrollouter.py:127.
Other checks:
"all_hosts"with a launcher now spawns the controller host's workers through the trainer mesh's host 0 instead ofthis_host(). On Slurm that is the same machine, and the env is the same because of--export=ALL(launcher/slurm.py:59-64).- With fewer workers than hosts, the controller host gets none, because it comes last and
num_host_workers == 0skips it. That is the intended behavior. - The SLAKE docstring claim holds: the Slurm launcher already requires recipe paths to resolve on every node.
- No change to training numerics: placement only decides which process runs a group.
Not verified: real multi-host behavior, and whether random.choice matches Monarch's .choose() selection.
| # The retriever listens on the controller host's 127.0.0.1 (README "Local dense retrieval server"). | ||
| # TODO: start it on a routable address and set `message_env.search_url` to it; then drop this. | ||
| rollouter=dataclasses.replace( | ||
| _search_r1_rollouter_config(), worker_placement="controller_host_only" | ||
| ), |
There was a problem hiding this comment.
The host requirement comes from the env's default search_url (http://127.0.0.1:8000/retrieve, search_r1/env.py:127), not from this recipe's size. But only the perf recipe pins it. If someone runs the 1.7B, 8B or Muse Glimmer recipe on two hosts with --override (or copies one of them), the workers on the other host get "" from _search with a warning per request (env.py:91-95). The run then trains on empty searches and doesn't fail, which is the silent failure that CLAUDE.md principle 8 rules out. The README note only helps someone who reads it first.
Smallest fix: set worker_placement="controller_host_only" once in _search_r1_rollouter_config() (search_r1.py:72), keep the TODO there, and drop this dataclasses.replace. One-host runs behave the same, and this is a net reduction of about 3 lines. This differs from the Geometry3K case you removed: a misplaced worker there fails loudly with a file error, while this one fails silently.
| A guess: the Slurm launcher runs the controller on the allocation's first node | ||
| (`launcher/slurm.py`), and trainer host 0 is that node when Monarch keeps the allocation's order. | ||
| """ | ||
| # TODO: match the controller's hostname instead, so a launcher that runs the controller on | ||
| # another host (or orders hosts differently) needs no change here. | ||
| return host_meshes.trainer, 0 |
There was a problem hiding this comment.
this is bad. It shouldnt be a guess. Can we make it intentionally this and call it every time, and people can replace it if they want to?
There was a problem hiding this comment.
Maybe a question is: what if there isnt a trainer? You need to think about it. This is too messy. The requirement is:
- We have some function that defines where the controller lives
- We can accurately retrieve it, instead of guess
There was a problem hiding this comment.
Reply from claude: done in e2df498. The guess is gone. MonarchActorSystem.controller_host_indices(hosts) is the one place that says where the controller runs, it's called on every launch, and a subclass can override it. By default it reads each job host's hostname (provisioning.read_hostnames, one small process per host, ~3.5 s once per launch) and compares it with the controller's own. If no host matches, it logs the controller's hostname and the job's hostnames.
There was a problem hiding this comment.
Reply from claude: it never looks at the trainer now. It takes the flat list of job hosts, so the controller can run on a trainer host, a generator host, or outside the job (then no host matches, and "all_hosts" has no host to put last). Tests cover the controller on a generator host and outside the job, and a real 4-host test (hosts simulated on one machine) checks the hostname match itself.
| ) -> list[HostMesh]: | ||
| """The hosts to spread the rollout workers over, one single-host mesh each. | ||
|
|
||
| A job with trainer hosts [t0, t1] and generator hosts [g0, g1]; t0 runs the controller: |
There was a problem hiding this comment.
dont assume t0 runs the controller. Say this is an example. This should be using the coding style skill. it isnt.
There was a problem hiding this comment.
Reply from claude: fixed. The docstring now opens: "Example: trainer hosts [t0, t1], generator hosts [g0, g1], and the controller runs on t1 (it can run on any host, or outside the job)". I also walked every other comment, docstring and name in 6112-6114 with code-style, and 3 fresh reviewers then checked them.
da71dbc to
e2df498
Compare
|
Reply from claude: @claude please review. Since your last review: the controller's host is found by hostname in |
|
Claude finished @felipemello1's task in 1m 50s —— View job Needs discussion: the hostname lookup and the Search-R1 pin fix the last review's points, and I found no new defects. The new default still hasn't run on a real multi-host job, and the human-written summary is still empty. See the review. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the hostname lookup and the Search-R1 pin fix the last review's points, and I found no new defects. Two things are still open from before: the new default hasn't run on a real multi-host job, and the human-written summary is empty.
What changed since the last review.
- Felipe asked that the controller's host be found for real, not guessed. That is resolved.
MonarchActorSystem.controller_host_indices(system.py:317) reads each job host's hostname withread_hostnamesand compares it withsocket.gethostname(). It's called on every launcher run except"controller_host_only", and a subclass can override it.rollout_worker_hosts(provisioning.py:303) now takes a flat list of hosts and never looks at the trainer, so it handles the controller on a generator host or outside the job. - The Search-R1 pin is resolved.
worker_placement="controller_host_only"is now set once in_search_r1_rollouter_config()(search_r1.py:74), and the perf recipe'sdataclasses.replaceis gone. - The ProcessJob test now runs the real
controller_host_indices. All the simulated hosts have the same hostname, so"all_but_controller_host"raising "leaves no host" there shows that the hostname match ran.
Example.
trainer [n0, n1], generators [n2], [n3]; controller on n1 (hostname match -> [1]); 5 workers
all_hosts: n0: 2, n2: 1, n3: 1, n1: 1 (n1 goes last)
all_but_controller_host: n0: 2, n2: 2, n3: 1
controller_host_only: this_host(): 5 (no probe, same as before)
controller on a login node (no match): all_hosts keeps the job order, one info log line
Must fix
- The "Summary (human-written)" section is still empty. Only the author can write it, and it has to be there before merge, even though it is empty on purpose for now.
- Still open: the new
"all_hosts"default hasn't run on a real multi-host job. That run would also be the first real cross-host check ofread_hostnames. The ProcessJob test can't check that check, because every simulated host has the same hostname. Before merge, please post the planned 2-noderl_grpo_qwen3_0_6b_flex_slurmrun: itsRollout workers per hostline, and the step times next to a"controller_host_only"run. Otherwise a maintainer has to accept landing the default unverified.
Details
Checked at HEAD:
controller_host_onlyreturns before the probe, so recipes pinned to it (Search-R1, Verifiers) and runs without a launcher spawn no extra process.- On Slurm the controller runs on the allocation's first node (
launcher/slurm.py:55-57). Both sides callsocket.gethostname(), so they use the same form (short name or FQDN) and the match holds. - If no host matches,
"all_but_controller_host"uses every host. The controller is then treated as outside the job. The docstring and the description cover the case of a controller in a container on a job host. spawn_rollout_workersis implemented only inMonarchActorSystemand the two test fakes. All of them take the newplacementkwarg, and nothing calls.choose()on an actor handle any more."all_but_controller_host"on a one-host job raises insetup_async, after the trainer, generators and batcher have spawned (controller.py:846). It can't fail earlier, because the config doesn't know whether a launcher will pass hosts. The case is rare and the error is clear, so I'm noting it and not listing it as a finding.- If one host's probe fails,
read_hostnamesdoesn't stop the other probe processes. Setup fails anyway, and job teardown cleans them up. - No change to training numerics: placement only decides which process runs a group.
Not verified: any real multi-host behavior, including the hostname match on separate machines.
8f52216 to
50cb092
Compare
50cb092 to
3187f3d
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 2m 22s —— View job Approve, with one item before merging: the rebased |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 3187f3d is the same change as 7e3a755, rebased again, and I found no correctness defects in the full diff. With the default (controller=True), every rollout worker still runs on the controller's machine, as on the base branch. This changes the ActorSystem interface, so a maintainer still needs to review.
What this PR does. It adds Rollouter.Config.worker_roles, which is a RolloutWorkerRoles(trainer, generator, controller). Each role is True, False or None. rollout_worker_hosts (provisioning.py:309) gives each job host its roles, keyed by (id(mesh), host index). It keeps a host when one of its roles is True and none is False. The controller's host always spawns through this_host(). spawn_rollout_workers splits the workers with divmod, caps them at max_rollout_workers_per_host (128), and returns RolloutWorkersHandle(by_host, by_worker). Each group goes to random.choice(by_worker).run_group.call_one(...).
Example (Slurm: trainer [t0, t1], generators [g0], [g1], controller on t0, 5 workers).
RolloutWorkerRoles() this_host(): 5 same as the base branch
RolloutWorkerRoles(generator=True) this_host(): 2, g0: 2, g1: 1
trainer=True, generator=True, controller=False t1: 2, g0: 2, g1: 1
no launcher, any roles this_host(): 5
PBS, trainer=True, generator=True, controller=False t0 (controller's node) still gets workers -- see inline
Must fix
- Still open: the "Summary (human-written)" section of the description is empty. Only the author can write it.
Should consider
torchtitan/rl/actors/monarch/launcher/pbs.py:48--PBSLauncherinheritscontroller_on_first_trainer_host=False, which means "outside the job", but its controller runs on the job's first node. Socontroller=Falsesilently doesn't keep workers off that node. CheckPBSJob's node order and set True, or keep the TODO (inline).
Details, checked at 3187f3d
- Earlier fixes still hold after the rebase:
controller_on_first_trainer_hostis required inLayout.host_meshesandHostMeshes, and every caller passes it.- The duplicate roles test is gone.
test_no_worker_role_true_after_build_raisescovers the error and the rerun fromController.Config.__post_init__(controller.py:468). - The
RolloutWorkerRolesdocstring describes what an unset role does, andtest_rollout_worker_hosts_uses_the_default_of_an_unset_rolechecks it.
- No leftover callers: nothing outside the tests uses
_worker_actors,_rollout_worker_meshor.choose()on a worker handle. The remaining.choose(hits are routing strategies.spawn_rollout_workershas one implementation (MonarchActorSystem), and every caller passesworker_roles. - A spawn that fails partway leaves
self._workersas None, socloseskips the per-hostcloseand still callsstop_rollout_workers. That stops every mesh appended so far, andtest_close_stops_the_workers_of_a_spawn_that_failed_partwaycovers it. - No recipe sets
worker_roles, so every in-repo run keeps the default. The real multi-host check belongs to #6157, which changes the default. - No change to training numerics: placement only decides which process runs a group.
Not verified: the node order of Monarch's SlurmJob and PBSJob, and any real multi-host behavior. Neither affects the default.
| # TODO: set `controller_on_first_trainer_host = True` once checked that PBSJob gives the job's | ||
| # first node (where the controller runs) to the trainer mesh, as SlurmJob does. Until then, | ||
| # `rollouter.worker_roles.controller=False` may still put rollout workers on the controller's node. |
There was a problem hiding this comment.
This class's own docstring says the controller runs as the batch script on the job's first node, so it is on a job host. The inherited False means "outside the job's hosts" (launcher/base.py:157-160), and on PBS that is wrong. Two role sets then place workers wrongly and raise nothing:
trainer=True, generator=True, controller=Falsestill runs workers on the controller's node.trainer=True, controller=Truespawns a share throughthis_host()and another share on trainer host 0, the same machine, so that node runs two shares.
The TODO is honest about it, and the default is unaffected. Still, CLAUDE.md principle 8 prefers an error over a silent wrong placement. Smallest fix: check Monarch's PBSJob node order (the same check you made for SlurmJob in monarch/_src/job/). If it matches, set controller_on_first_trainer_host = True here and drop the TODO. If you can't check it now, keep the TODO. The PR description already lists this as a follow-up.
There was a problem hiding this comment.
Reply from claude: Checked in torchmonarch 0.8.0: inside the job, PBSJob._state gives the first PBS_NODEFILE hosts, in order, to the first mesh, the trainer's (monarch/_src/job/pbs.py:297-323, _pbs_batch.py:49-61), as SlurmJob does. So PBSLauncher.controller_on_first_trainer_host = True, and the TODO is gone (2e0fb04). Not run on a real PBS cluster: it rests on PBS running the batch script on the first PBS_NODEFILE host, which the PR body notes.
3187f3d to
2e0fb04
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 16s —— View job Approve, with one item before merging: |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 2e0fb04 resolves the PBS placement point from the last review, and I found no new defects. With the default (controller=True), every rollout worker still runs on the controller's machine, as on the base branch. This changes the ActorSystem interface, so a maintainer still needs to review.
What changed since the last review. PBSLauncher now sets controller_on_first_trainer_host = True (launcher/pbs.py:51), and a comment gives the reason: PBS runs the batch script on the first PBS_NODEFILE host, and PBSJob gives the first nodes to the first mesh, which is the trainer's (MonarchLauncher._layout puts it first). The TODO is gone. On PBS, controller=False now keeps workers off the controller's node, and trainer=True, controller=True counts that node once. Both launchers now behave the same. Only the base launcher, whose controller runs outside the job, keeps False.
Example (PBS or Slurm: trainer [t0, t1], generators [g0], [g1], controller on t0, 5 workers).
RolloutWorkerRoles() this_host(): 5 same as the base branch
trainer=True, generator=True, controller=False t1: 2, g0: 2, g1: 1 PBS before this commit: t0 also got workers
trainer=True, controller=True this_host(): 3, t1: 2 PBS before: t0 ran two shares
Must fix
- Still open: the "Summary (human-written)" section of the description is empty. Only the author can write it.
Should consider
torchtitan/rl/actors/monarch/provisioning.py:353-- the comment says "On Slurm", but PBS takes this branch now too (inline).
Details, checked at 2e0fb04
- The only change since
3187f3dis inpbs.py. The PR description already describes the PBS behavior. controller_on_first_trainer_hostis still set in one place per launcher: the base class sets False,SlurmLauncherandPBSLauncherset True._build_actor_systempasses it toLayout.host_meshes(launcher/base.py:295), where it is required.- No recipe sets
worker_roles, so every in-repo run keeps the default. The real multi-host check belongs to #6157, which changes the default. - No change to training numerics: placement only decides which process runs a group.
Not verified: the node order of Monarch's PBSJob and SlurmJob (Monarch's source isn't installed in this checkout), and any real multi-host behavior. Neither affects the default.
| # Spawn through `this_host()`, the controller's own machine. On Slurm, the batch script that | ||
| # starts the controller typically runs on trainer host 0, so both are the same machine. |
There was a problem hiding this comment.
Now that PBSLauncher sets controller_on_first_trainer_host = True too, "On Slurm" names only one of the two launchers that reach this branch. A reader could take it to mean PBS doesn't. This is a wording fix only:
| # Spawn through `this_host()`, the controller's own machine. On Slurm, the batch script that | |
| # starts the controller typically runs on trainer host 0, so both are the same machine. | |
| # Spawn through `this_host()`, the controller's own machine. On Slurm and PBS, the batch | |
| # script that starts the controller typically runs on trainer host 0, so both are the same machine. |
There was a problem hiding this comment.
Reply from claude: Done in c646a1b: the comment now says "On Slurm and PBS", rewrapped to stay within 100 columns.
2e0fb04 to
c646a1b
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 51s —— View job Approve, with one item before merging: |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. c646a1b makes the wording fix suggested in the last review, and I found no new defects. With the default (controller=True), every rollout worker still runs on the controller's machine, as on the base branch. This changes the ActorSystem interface, so a maintainer still needs to review.
What changed since the last review. One comment in rollout_worker_hosts (provisioning.py:353-354) now says "On Slurm and PBS". It used to say only "On Slurm", and both launchers set controller_on_first_trainer_host = True (launcher/slurm.py:72, launcher/pbs.py:51). Resolved. No code changed.
Example (Slurm or PBS: trainer [t0, t1], generators [g0], [g1], controller on t0, 5 workers).
RolloutWorkerRoles() this_host(): 5 same as the base branch
RolloutWorkerRoles(generator=True) this_host(): 2, g0: 2, g1: 1
trainer=True, generator=True, controller=False t1: 2, g0: 2, g1: 1
no launcher, any roles this_host(): 5
Must fix
- Still open: the "Summary (human-written)" section of the description is empty. Only the author can write it.
Details, checked at c646a1b
rollout_worker_hosts(provisioning.py:309-376) is the same as at2e0fb04apart from that comment. The rule (a host is kept when it has a True role and no False role) and thethis_host()substitution for trainer host 0 are unchanged.spawn_rollout_workersandstop_rollout_workers(system.py:192-269) are unchanged. The cap check runs before anything spawns. Each mesh is saved before its actors spawn, and the stops run concurrently withreturn_exceptions=True.controller_on_first_trainer_hostis set in one place per launcher (base False, Slurm and PBS True) and is required inLayout.host_meshesandHostMeshes.- No recipe sets
worker_roles, so every in-repo run keeps the default. The real multi-host check belongs to #6157, which changes the default. - No change to training numerics: placement only decides which process runs a group.
Not verified: the node order of Monarch's SlurmJob and PBSJob, and any real multi-host behavior. Neither affects the default.
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Agent details
**TLDR:** The Rollouter now starts one rollout worker per
`rollouts_per_worker` (default 128) training rollouts in flight. Before,
every recipe started 4 workers, whatever its load.

<!-- pr-image drawn at c7e5aa4 -->
```python
# before: Rollouter.Config
worker_pool_size: int = 4
# after: Rollouter.Config; the Rollouter sizes its pool from the controller's max_rollouts_in_flight
rollouts_per_worker: int = 128
```
**Problem**
1. `Rollouter.Config.worker_pool_size` sets how many rollout worker
processes start. It defaults to 4, and no recipe changes it.
2. Each worker runs all its rollouts on one event loop.
3. So each worker's load follows the recipe: 16 rollouts per worker for
the batch-invariant CI recipes, 384 for Terminal-Bench 9B.
**Solution**
1. `Rollouter.Config.rollouts_per_worker` (default 128) replaces
`worker_pool_size`.
2. The controller passes `max_rollouts_in_flight` (groups in flight x
group size, a new `AsyncLoopConfig` property) to the Rollouter's
constructor. `Rollouter.setup_async` starts
ceil(`max_rollouts_in_flight` / `rollouts_per_worker`) workers and logs
the count.
3. A group runs on one worker. So a group larger than
`rollouts_per_worker` raises when the config is built: only one worker
per group in flight could run a training group at once, and the others
would sit idle. `num_samples_per_prompt < 1` now raises too; nothing
checked it.
4. Unchanged: one mesh on the controller host, and Monarch's `choose`
picks the worker, at random. So `rollouts_per_worker` is the mean load,
not a cap. A later PR in this stack picks the least-loaded worker.
Also in this PR:
- One TODO on `InterGeneratorRouter.release_groups`, which both
group-level release calls use (training loop and validation): evaluate
if that release is needed, since each rollout already releases its
session. It lists the two things only that release does today.
- The controller's per-group asyncio tasks become `rollout_loop_<i>`, so
"rollout worker" names only the process.
**Results**
```text
recipe max in flight workers: main -> this PR host memory after imports
dapo_math 30B-A3B (x2) 2,560 4 -> 20 ~13.9 GiB
SLAKE 816B 4,096 4 -> 32 ~22 GiB (on one host until #6157)
Terminal-Bench Qwen3.5-9B 1,536 4 -> 12 ~8.5 GiB
Terminal-Bench Qwen3.5-35B-A3B 1,280 4 -> 10 ~7.2 GiB
Search-R1 30B-A3B perf 1,024 4 -> 8 ~5.8 GiB
geometry3k (x2) 512 4 -> 4 ~3.1 GiB
dapo_math 4B, Verifiers 4B (x4) 640 4 -> 5 ~3.8 GiB
alphabet_sort, Search-R1, ... (15) 160-256 4 -> 2 ~1.8 GiB
batch-invariant CI (x3) 64 4 -> 1 ~1.1 GiB
DAPO-Math 816B GB300 64 4 -> 1 ~1.1 GiB
```
Counts: ceil(`async_loop.max_rollouts_in_flight` / 128) of each built
recipe config. Every recipe uses the default 128; worker counts range
from 1 to 32. Memory: one worker holds 1.13 GiB of RAM after its
imports, but ~0.46 GiB of that is shared library pages, loaded once per
host. So a host's workers take ~0.46 GiB once, plus ~0.67 GiB per
worker; the column above adds both. Main's 4 workers take ~3.1 GiB.
Memory used while running comes on top.
You may ask:
- Why 128? A starting point, not a measured optimum. RL libraries run
2-192 rollouts per worker process for sandbox envs and 320-2,560 for
light search agents; math configs have medians of 72 and 256. 128 starts
half the processes that 64 would. #6174, later in this stack, adds the
worker metrics that check it on real runs.
- Why no CPU cap in the count? The Rollouter runs in the controller's
process, so it sees only that host's CPUs, and #6113 spreads the workers
to hosts it can't see. #6113 also caps the workers per host
(`MonarchActorSystem.Config.max_rollout_workers_per_host`).
- Why does the controller pass the load, not a worker count? The
Rollouter owns `rollouts_per_worker`, so it sizes its own pool. The
controller knows the load.
- Why only training rollouts? Validation comes due every `freq` steps,
so workers sized for it would sit idle between validations. Validation
shares the workers, as on main.
- Where does a worker's memory go? torch 578 MiB, Monarch 84,
transformers 22, and ~450 MiB of the `grain` and `datasets` packages.
Those load with the `VisionProcessor` import, which runs
`torchtitan/components/data/__init__.py`; the renderer and
`rl/rollout/data.py` import them too. A TODO at that import says to
check whether a worker needs them.
NOTE:
- Every worker runs on the controller host until #6157 turns on the
generator hosts by default (#6113 adds the switch): SLAKE's 32 workers
take ~22 GiB there. These PRs should land together.
- `VerifiersRollouter.__init__` forwards `max_rollouts_in_flight`.
- Not run on GPUs.
Follow up / TODO (each is a `# TODO` in the code):
- [ ] Place single rollouts on workers, instead of groups, so there is
less idle time as rollouts finish. This needs a new home for group-level
postprocessing.
- [ ] Evaluate if we need the group-level release in
`InterGeneratorRouter.release_groups`.
- [ ] Load the `grain` and `datasets` packages only where they are used,
to save ~450 MiB per rollout worker. First check that a worker doesn't
need them.
- [ ] At 128 rollouts per worker, renders and parses (`TokenEnv`) may
queue on the worker's 4 threads. Measure that wait, then size the pool
from it.
**Test plan**
```bash
python -m pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config -q
# Verifiers 0.4.0: 1003 passed, 1 skipped (test_train_loop.py, skipped on main too).
# Without Verifiers: 946 passed, 7 skipped (the Verifiers test files and recipes).
```
New or changed:
- `test_async_controller.py`:
`test_a_group_larger_than_rollouts_per_worker_raises` (with
`rollouts_per_worker=0` too).
- `test_rollouter_pool.py`:
`test_setup_spawns_worker_pool_on_controller_host`: 20 training rollouts
in flight / 7 per worker -> 3 workers (a floor would give 2).
- `test_shutdown.py`:
`test_controller_builds_rollouter_with_training_rollouts_in_flight`: the
default config's 32 groups in flight x 8 rollouts reach the Rollouter as
256.
`pre-commit` passes. `pyrefly` skips `torchtitan/rl` and `tests`
(`project-excludes` in `pyproject.toml`), so it checks none of this PR's
files.
Co-authored-by: Felipe Mello <[email protected]>
1d5e291 to
4c0c749
Compare
4c0c749 to
87a1d61
Compare
7a8b7e0 to
b5da469
Compare
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.
b5da469 to
50d58a0
Compare
Summary (human-written)
Agent details
TLDR:
rollouter.worker_rolespicks which hosts run the rollout workers, by the hosts' roles. It has one field per role:trainer,generatorandcontroller. Each isTrue(add the hosts with this role),False(never use a host with this role) orNone(no opinion). A host runs workers if at least one of its roles isTrueand none isFalse, and a host with several roles counts once. The workers spread evenly over those hosts. The default,controller=Truewith the othersNone, keeps every worker on the controller's host, so no recipe changes behavior. A config field caps the workers on one host.Problem
Solution
RolloutWorkerRoles(new,rollouter.py) has onebool | Nonefield per role:trainer,generatorandcontroller.Rollouter.Config.worker_rolesholds it. No fieldTrueraises aValueErrorwith the values, when the roles are built and again inController.Config.__post_init__(the config loader reruns only that one after a recipe edits the config). A role you don't set keeps its default:RolloutWorkerRoles(generator=True)keepscontroller=True, so it adds the generator hosts to the controller's host. Withcontroller=None, the controller's role adds no host. Withcontroller=False, the controller's host runs no workers, even when another True role includes it.rollout_worker_hosts(host_meshes=, worker_roles=)inprovisioning.pygives each host its roles, then keeps the hosts with aTruerole and noFalserole, each host once, in job order. Roles that share a host share its mesh, so the hosts are keyed by (mesh, host index). When aFalserole vetoes every host, it raises aValueErrorthat lists each host's roles.MonarchLauncher.controller_on_first_trainer_host.Layout.host_meshesandHostMeshestake it as a required argument.this_host(), outside the job. Its only role iscontroller.SlurmLauncher: True. The batch script typically runs on the allocation's first node, and Monarch'sSlurmJobgives the first nodes to the first mesh, the trainer's. So trainer host 0 also has the controller's role:controller=Falsekeeps workers off it, andtrainer=True, controller=Truecounts it once. Its workers spawn throughthis_host(), the controller's own machine, as on main.PBSLauncher: True, for the same reason. PBS runs the batch script on the job's first node, the first host inPBS_NODEFILE, and Monarch'sPBSJobgives the first nodes, in that order, to the trainer's mesh.MonarchActorSystem.spawn_rollout_workersspawns one CPU proc mesh per host, evenly (5 workers on 3 hosts: 2, 2, 1).RolloutWorkerActortakesfirst_worker_index, so log ranks stay unique across hosts.RolloutWorkersHandle:by_host: each host's actor mesh, for one.call()to all its workers (setup, log step, close);by_worker: one slice per worker, for.call_one()to one worker.This is
TrainerHandle's shape: the actor system slices, and callers don't.MonarchActorSystem.Config.max_rollout_workers_per_host(default 128) caps the workers on one host. Setup raises whenworker_roleswould put more there. The check runs when the workers spawn, not in__post_init__: the number of hosts is known only then.choosedoes on one mesh.choosestays in the call convention (ActorSystem's docstring and the Monarch README).Rollouter.closecloses every host's workers at once, under one time limit, and a host whosecloseraises is logged without cutting the others short.stop_rollout_workersthen stops every host's mesh at once and logs a host whose stop fails.this_host(), as on main, so no recipe needs a change. Runs without a launcher spawn no extra process.Results
The host lists come from
test_rollout_worker_hosts(13 cases, fake host meshes),test_rollout_worker_hosts_raises_when_every_host_is_vetoedandtest_rollout_worker_hosts_uses_the_default_of_an_unset_role, and the counts from the even split. A CPU test runs real Monarch processes on a 4-host job simulated on one machine (ProcessJob), with all three rolesTrueand the controller on trainer host 0. Trainer host 0 counts once and spawns throughthis_host(), and the 5 workers go 2, 1, 1, 1: log ranks 0, 1 on the test's own machine (where the controller runs), 2 on trainer_1, 3 on generator_0_0 and 4 on generator_1_0. Each worker's group called an actor on the controller's host and got its reply. That is a cross-mesh call, the path a cross-host call takes.You may ask:
Nonemeans "this role adds or removes no host", not "off". Its cost: for the controller's host only,generatormust stayNone, becauseFalsevetoes the controller's host when it is also a generator host.False? No recipe yet.trainer=True, generator=True, controller=Falsekeeps the rollout workers off the controller's host, so the controller keeps its CPUs.HostMeshhas no address, hostname or resources, and the controller'sthis_host()is a separate Monarch host that never equals a job host.HostMesh? AHostMeshcan't be a dict key. Two slices of one host compare equal with==, but that call blocks the event loop, and Monarch warns that it can deadlock.controller=True? It changes nothing. The next PR in this stack setsgenerator=Trueby default, together with what each env needs on every host.max_rollout_workers_per_host = 128? It catches a pool sized by mistake. Example:rollouter.rollouts_per_worker=1with 256 training rollouts in flight asks for 256 workers. Each holds ~0.8 GiB of private memory after setup, so 128 on one host take ~100 GiB. No recipe starts more than 32 workers. It isn't derived from the CPU count yet: Monarch has no CPU query before spawning,os.sched_getaffinityignores a CPU quota, and no run has measured how many workers a host with an inference engine tolerates.choose? Workers on N hosts are N meshes, and Monarch has no API to join meshes.choosepicks within one mesh, so the rollouter picks the worker and callscall_oneon it.NOTE:
SlurmJobandPBSJobgiving the first nodes to the first mesh (monarch/_src/job/slurm.py,pbs.py). If the batch script ran elsewhere,controller=Falsewould veto trainer host 0 instead of the controller's machine, andtrainer=Truewould put trainer host 0's workers on the controller's machine (a speed cost only). The workers of the controller's host still spawn throughthis_host(), so a service at 127.0.0.1 on the controller's machine stays reachable.run_group_rolloutsedits the same lines. Whichever lands second rebases, and a retry must count the group on the worker it retries on.Follow up / TODO (each is a
# TODOin the code):max_rollout_workers_per_host's default from each host's CPU count, so it fits each machine. It needs the launcher to report each host's cores (Slurm:SLURM_JOB_CPUS_PER_NODE): Monarch has no CPU query before spawning. Until then, watchgenerator/inter_token_latency_mswhen workers share a host with a generator.HYPERACTOR_PROCESS_NAME). Switch once a public value namesProcessJobhosts, which share one hostname.Test plan
New:
test_rollout_worker_hosts(13 cases: no launcher; one host for every role; a generator on the trainer's node; 6 role sets with the controller on trainer host 0, the 4 layouts among them; 3 with the controller outside the job; a host shared by the trainer and a generator thatgenerator=Falsevetoes),test_rollout_worker_hosts_raises_when_every_host_is_vetoed,test_rollout_worker_hosts_uses_the_default_of_an_unset_role(RolloutWorkerRoles(generator=True)keepscontroller=True:["this_host", "g0", "g1"]),test_no_worker_role_true_after_build_raises,test_close_closes_the_workers_on_every_host_then_stops_them(one time limit for all hosts),test_one_host_failing_to_close_doesnt_cut_the_other_hosts_short,test_close_stops_the_workers_of_a_spawn_that_failed_partway,test_rollout_workers_spread_over_the_hosts_of_a_job(real Monarch processes, hosts simulated withProcessJob; workers 0 and 1 run on the machine an actor spawned throughthis_host()reports),test_setup_raises_when_one_host_would_run_too_many_rollout_workers,test_setup_and_sync_log_step_reach_the_workers_on_every_host,test_stop_rollout_workers_stops_every_host_at_once_when_one_fails(each stop waits until all have started, so a one-by-one loop times out; host 0's stop raises when called).test_setup_spawns_worker_pool_on_controller_hostnow passes a launcher's hosts, which the defaultcontroller=Truemust not use when the controller runs outside the job.pre-commitandpyrefly checkpass.