Skip to content

[rl] Spread rollout workers over the hosts of chosen roles - #6113

Draft
felipemello1 wants to merge 1 commit into
felipemello1/verifiers-041/4-bumpfrom
felipemello1/distribute/2-spread-workers
Draft

felipemello1 wants to merge 1 commit into
felipemello1/verifiers-041/4-bumpfrom
felipemello1/distribute/2-spread-workers

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: rollouter.worker_roles picks which hosts run the rollout workers, by the hosts' roles. It 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 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, so no recipe changes behavior. A config field caps the workers on one host.

In a Slurm job with trainer hosts t0, t1, generator hosts g0, g1 and the controller on t0, each role is True, False or None and a host runs workers if at least one of its roles is True and none is False, so the 5 workers go 3, 2 to g0, g1 with generator True and the other roles None, 2, 2, 1 to t1, g0, g1 when controller=False vetoes t0, 2, 1, 1, 1 over every host with trainer and generator True, and all 5 to t0 through this_host() with the default controller=True, while a launcher that runs the controller outside the job adds the controller's machine as an extra host.

# before: one mesh on the controller host
await self._worker_actors.setup_async.call(...)
self._worker_actors.run_group.choose(...)
# after: the hosts that worker_roles picks, one mesh per host, and one handle per worker
worker_roles: RolloutWorkerRoles = field(default_factory=RolloutWorkerRoles)  # Rollouter.Config
await asyncio.gather(*(host_workers.setup_async.call(...) for host_workers in self._workers.by_host))
random.choice(self._workers.by_worker).run_group.call_one(...)

Problem

  1. Every rollout worker runs on the controller host. That host also runs the controller, the generator router and the batcher, and on a launcher's job it can also hold trainer or generator ranks.
  2. The PR below this one sizes the pool from the load: up to 32 workers, ~25 GiB of private memory (SLAKE).
  3. On a multi-host job, the other hosts can't take any of them.
  4. No run has shown the controller host to be the bottleneck yet. This is headroom for when the pool outgrows one host.

Solution

  1. RolloutWorkerRoles (new, rollouter.py) has one bool | None field per role: trainer, generator and controller. Rollouter.Config.worker_roles holds it. No field True raises a ValueError with the values, when the roles are built and again in Controller.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) keeps controller=True, so it adds the generator hosts to the controller's host. With controller=None, the controller's role adds no host. With controller=False, the controller's host runs no workers, even when another True role includes it.
  2. rollout_worker_hosts(host_meshes=, worker_roles=) in provisioning.py gives each host its roles, then keeps the hosts with a True role and no False role, each host once, in job order. Roles that share a host share its mesh, so the hosts are keyed by (mesh, host index). When a False role vetoes every host, it raises a ValueError that lists each host's roles.
  3. The launcher says where the controller runs, because it put the controller there: MonarchLauncher.controller_on_first_trainer_host. Layout.host_meshes and HostMeshes take it as a required argument.
    • Base launcher: False. The controller's host is its own machine, this_host(), outside the job. Its only role is controller.
    • SlurmLauncher: True. The batch script typically runs on the allocation's first node, and Monarch's SlurmJob gives the first nodes to the first mesh, the trainer's. So trainer host 0 also has the controller's role: controller=False keeps workers off it, and trainer=True, controller=True counts it once. Its workers spawn through this_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 in PBS_NODEFILE, and Monarch's PBSJob gives the first nodes, in that order, to the trainer's mesh.
    • No launcher: the workers run on this host, whatever the roles.
  4. MonarchActorSystem.spawn_rollout_workers spawns one CPU proc mesh per host, evenly (5 workers on 3 hosts: 2, 2, 1). RolloutWorkerActor takes first_worker_index, so log ranks stay unique across hosts.
  5. Monarch can't join meshes, so the actor system returns 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.
  6. MonarchActorSystem.Config.max_rollout_workers_per_host (default 128) caps the workers on one host. Setup raises when worker_roles would put more there. The check runs when the workers spawn, not in __post_init__: the number of hosts is known only then.
  7. The Rollouter picks a worker uniformly at random, as choose does on one mesh. choose stays in the call convention (ActorSystem's docstring and the Monarch README). Rollouter.close closes every host's workers at once, under one time limit, and a host whose close raises is logged without cutting the others short. stop_rollout_workers then stops every host's mesh at once and logs a host whose stop fails.
  8. Unchanged: with the default, every worker runs on the controller's host and spawns through this_host(), as on main, so no recipe needs a change. Runs without a launcher spawn no extra process.

Results

Slurm, trainer hosts t0, t1 and generator hosts g0, g1, the controller on t0, 5 workers.
t0's workers spawn through this_host(), the controller's own machine.
Each row names the roles that are not None.
controller=True (default)                         t0: 5
generator=True                                    g0: 3, g1: 2
trainer=True, generator=True, controller=False    t1: 2, g0: 2, g1: 1       every host but the controller's
trainer=True, generator=True                      t0: 2, t1: 1, g0: 1, g1: 1
trainer=True, controller=True                     t0: 3, t1: 2              t0 counts once
generator=True, controller=True                   t0: 2, g0: 2, g1: 1
One host for every role, generator=False, controller=True:   ValueError, generator=False vetoes the only host

The host lists come from test_rollout_worker_hosts (13 cases, fake host meshes), test_rollout_worker_hosts_raises_when_every_host_is_vetoed and test_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 roles True and the controller on trainer host 0. Trainer host 0 counts once and spawns through this_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:

  • Why one field per role? Felipe chose per-role fields after comparing them with an enum of placements and a list of roles.
  • Why three values per role, and not two lists (roles to include, roles to exclude) or placement set on the launcher? All three can write every layout above. This one keeps the class and the field from before. Only the types and the rule change, so the diff is the smallest. Here None means "this role adds or removes no host", not "off". Its cost: for the controller's host only, generator must stay None, because False vetoes the controller's host when it is also a generator host.
  • Who sets a role to False? No recipe yet. trainer=True, generator=True, controller=False keeps the rollout workers off the controller's host, so the controller keeps its CPUs.
  • Why does the launcher say whether the controller is on trainer host 0? It placed the controller, so it knows. Monarch can't tell: a HostMesh has no address, hostname or resources, and the controller's this_host() is a separate Monarch host that never equals a job host.
  • Why key the hosts by (mesh, host index), and not by HostMesh? A HostMesh can'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.
  • Why default to controller=True? It changes nothing. The next PR in this stack sets generator=True by default, together with what each env needs on every host.
  • Why max_rollout_workers_per_host = 128? It catches a pool sized by mistake. Example: rollouter.rollouts_per_worker=1 with 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_getaffinity ignores a CPU quota, and no run has measured how many workers a host with an inference engine tolerates.
  • Why not one mesh and choose? Workers on N hosts are N meshes, and Monarch has no API to join meshes. choose picks within one mesh, so the rollouter picks the worker and calls call_one on it.

NOTE:

  • Not run on a real multi-host job yet. With the default, the workers still run on the controller's machine.
  • Not checked on a real Slurm or PBS cluster: that the batch host is the trainer's first host. It rests on each scheduler running the batch script on the job's first node (typically, for Slurm), and on Monarch's SlurmJob and PBSJob giving the first nodes to the first mesh (monarch/_src/job/slurm.py, pbs.py). If the batch script ran elsewhere, controller=False would veto trainer host 0 instead of the controller's machine, and trainer=True would put trainer host 0's workers on the controller's machine (a speed cost only). The workers of the controller's host still spawn through this_host(), so a service at 127.0.0.1 on the controller's machine stays reachable.
  • An open PR that adds retries to run_group_rollouts edits 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 # TODO in the code):

  • Let extra CPU-only hosts run rollout workers, so the workers take no CPUs from the trainer or the generators. It needs a launcher that requests such hosts.
  • Derive 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, watch generator/inter_token_latency_ms when workers share a host with a generator.
  • The spread test reads each worker's simulated host from a private Monarch env var (HYPERACTOR_PROCESS_NAME). Switch once a public value names ProcessJob hosts, which share one hostname.

Test plan

python -m pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config -q
# 1000 passed, 7 skipped (6 need Verifiers, 1 skipped on main)
# The same command with Verifiers 0.4.1 installed:
# 1104 passed, 1 skipped (skipped on main)

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 that generator=False vetoes), test_rollout_worker_hosts_raises_when_every_host_is_vetoed, test_rollout_worker_hosts_uses_the_default_of_an_unset_role (RolloutWorkerRoles(generator=True) keeps controller=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 with ProcessJob; workers 0 and 1 run on the machine an actor spawned through this_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_host now passes a launcher's hosts, which the default controller=True must not use when the controller runs outside the job. pre-commit and pyrefly check pass.

@felipemello1
felipemello1 added this pull request to stack #6115 November 16, 2026 06:53
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 16, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 27s —— View job


Needs discussion: this adds workers_on_controller_host, which no recipe sets, for a bottleneck that hasn't been seen yet, and it hasn't run on a real multi-host job. 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 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

  1. 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).
  2. Gate: this option has no consumer. .claude/rules/config.md says to "expose only options a verified recipe uses", and no recipe sets workers_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 new ActorSystem parameter, a handle type and about 330 lines of tests for a path nobody has run. The default path changes too (.choose() becomes random.choice + call_one, and stop now 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 internal HYPERACTOR_PROCESS_NAME format; add a TODO or avoid it.
  • tests/rl/unit_tests/cpu/test_shutdown.py:571 -- the spawn and placement tests belong in test_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 in spawn_rollout_workers. #6114 could land on #6112 with that, without the host spreading, on_controller_host, rollout_worker_hosts, first_worker_index or the ProcessJob test.
  • Controller-host assumption. rollout_worker_hosts drops hosts[0], which is trainer host 0. Layout.host_meshes always puts the trainer first, and the TODO about SlurmJob's host order covers the remaining risk. Roles sharing a mesh are deduplicated by id(), which matches Layout.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.py be deleted. #6099 also changes worker setup and stop and will conflict with stop_rollout_workers here. #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.choice uses the global random state. Nothing else in torchtitan/ 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()

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 1641c9f to bb91c5b Compare November 16, 2026 07:26
@felipemello1

Copy link
Copy Markdown
Contributor Author

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

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 -- 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_NAME parse 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. Only test_stop_rollout_workers_stops_the_other_hosts_when_one_fails is still in test_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

  1. 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.
  2. 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 only by_worker built from the one mesh, about 10 lines in spawn_rollout_workers.
Details

I re-checked these at HEAD:

  • rollout_worker_hosts dedups meshes by id(). That matches Layout.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_workers appends 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_workers now logs a failed stop and moves on instead of raising, the same as stop(). Rollouter.close doesn't depend on the old raise.
  • sync_log_step.call(step=step) matches the endpoint sync_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 .choose hits are routing strategies), so removing it from the ActorSystem call 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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from bb91c5b to 8f6ef23 Compare November 16, 2026 14:00
@felipemello1 felipemello1 changed the title [rl] Spread rollout workers over the job's hosts (opt-in) [rl] Spread rollout workers over the job's hosts Nov 16, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: The author decided on the gate: spreading is now the default (8f6ef23), so the option has its consumers.

  • Rollouter.Config.workers_on_controller_host defaults to False: every job host but the controller's, and a one-host job keeps the workers on that host.
  • Recipes whose env needs the controller host keep True, each with a one-line reason: Search-R1 (retriever at 127.0.0.1), SLAKE and Geometry3K (images at a local path). The Verifiers recipes get True from VerifiersRollouter.Config's default and still raise on False.
  • An audit that builds every recipe: 12 keep True, 19 use False; 3 multi-host recipes now spread (AlphabetSort Qwen3-14B, the AlphabetSort Slurm example, the 144-GPU DAPO-Math recipe). The title drops "(opt-in)" and the description is rewritten for the new default.

@claude please review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

  1. 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".
  2. 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, or hf_assets_path being readable on generator hosts. The cheapest check is rl_grpo_qwen3_0_6b_flex_slurm on 2 nodes for 10+ steps. Paste the Rollout 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 in test_rollouter_pool.py.
  • The tests changed only to match the new default. _rollouter_without_datasets sets True explicitly, and test_setup_spawns_worker_pool_on_controller_host passes 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_workers uses dataclasses.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.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Agreed: the new default needs a real multi-host run before it lands. The plan is the check you name: rl_grpo_qwen3_0_6b_flex_slurm on 2 nodes for 10+ steps, once with the default and once with workers_on_controller_host=True, with the Rollout workers per host log line and the step times side by side. It needs a Slurm cluster login from the author, so it is not run yet. The results will be posted here, and the description updated.

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you help me better understand this todo?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +220 to +221
by_host.append(host_workers)
by_worker += [

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

letss add a couple of lines here with intuition on why we would want by host and by worker

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how os num of threads defined? is this a good default?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
num_host_workers = num_workers // len(hosts) + (
host_index < num_workers % len(hosts)
)
if num_host_workers == 0:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets put all the logic on rollout_worker_hosts and not have if/else here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
Comment on lines +236 to +240
for i, mesh in enumerate(meshes):
try:
await mesh.stop()
except Exception:
logger.exception("rollout worker mesh.stop[%d] failed", i)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we have all meshes be called to stop in parallel, instead of sequentially?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/rl/actors/monarch/system.py Outdated
*,
num_workers: int,
num_threads: int,
on_controller_host: bool,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan_recipes/rl/geometry3k.py Outdated
),
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,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 8f6ef23 to da71dbc Compare November 16, 2026 19:21
@felipemello1

Copy link
Copy Markdown
Contributor Author

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:

  • Section banners in functions with clear phases. A comment-only commit is coming in this stack.
  • Spread the Terminal-Bench workers: a separate PR on top of the Verifiers stack that runs the Verifiers env in the rollout worker. It needs each task's files on every host and a sandbox reachable from every host; the design is being planned now.
  • Search-R1 30B-A3B perf keeps controller_host_only until its retriever listens on a routable address (TODO in the recipe).

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

  1. The "Summary (human-written)" section is still empty, and only the author can write it.
  2. 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_slurm check. The ProcessJob test covers cross-mesh calls on one machine. It doesn't cover cross-host networking, or reading hf_assets_path and SLAKE's data dir on generator hosts. Please post that run's Rollout workers per host line 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_worker comment and the divmod split with a worked example are in.
  • rollout_worker_hosts decides every placement, and spawn_rollout_workers has no if/else.
  • controller_host() is its own function.
  • stop_rollout_workers uses gather(..., return_exceptions=True). The coroutine wrapper means a stop() that raises synchronously doesn't stop the others from running.
  • The Geometry3K pin is removed.
  • The num_threads_per_worker TODO is at rollouter.py:127.

Other checks:

  • "all_hosts" with a launcher now spawns the controller host's workers through the trainer mesh's host 0 instead of this_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 == 0 skips 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.

Comment thread torchtitan_recipes/rl/search_r1.py Outdated
Comment on lines +276 to +280
# 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"
),

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

Comment on lines +304 to +309
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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dont assume t0 runs the controller. Say this is an example. This should be using the coding style skill. it isnt.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from da71dbc to e2df498 Compare November 17, 2026 00:09
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. Since your last review: the controller's host is found by hostname in MonarchActorSystem.controller_host_indices (overridable, no trainer needed) instead of assuming trainer host 0; all Search-R1 recipes are pinned once in _search_r1_rollouter_config(); a real 4-host test pins the hostname match. Not done yet: a run on a real multi-host job (the author decides when). The human-written Summary is still empty on purpose.

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 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 with read_hostnames and compares it with socket.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's dataclasses.replace is 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

  1. 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.
  2. 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 of read_hostnames. The ProcessJob test can't check that check, because every simulated host has the same hostname. Before merge, please post the planned 2-node rl_grpo_qwen3_0_6b_flex_slurm run: its Rollout workers per host line, 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_only returns 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 call socket.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_workers is implemented only in MonarchActorSystem and the two test fakes. All of them take the new placement kwarg, and nothing calls .choose() on an actor handle any more.
  • "all_but_controller_host" on a one-host job raises in setup_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_hostnames doesn'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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 8f52216 to 50cb092 Compare November 20, 2026 05:47
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 50cb092 to 3187f3d 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 22s —— View job


Approve, with one item before merging: the rebased 3187f3d has no correctness defects and the default still keeps every worker on the controller's machine. The human-written summary is still empty, and there is one PBS placement suggestion inline. 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: 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

  1. 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 -- PBSLauncher inherits controller_on_first_trainer_host=False, which means "outside the job", but its controller runs on the job's first node. So controller=False silently doesn't keep workers off that node. Check PBSJob'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_host is required in Layout.host_meshes and HostMeshes, and every caller passes it.
    • The duplicate roles test is gone. test_no_worker_role_true_after_build_raises covers the error and the rerun from Controller.Config.__post_init__ (controller.py:468).
    • The RolloutWorkerRoles docstring describes what an unset role does, and test_rollout_worker_hosts_uses_the_default_of_an_unset_role checks it.
  • No leftover callers: nothing outside the tests uses _worker_actors, _rollout_worker_mesh or .choose() on a worker handle. The remaining .choose( hits are routing strategies. spawn_rollout_workers has one implementation (MonarchActorSystem), and every caller passes worker_roles.
  • A spawn that fails partway leaves self._workers as None, so close skips the per-host close and still calls stop_rollout_workers. That stops every mesh appended so far, and test_close_stops_the_workers_of_a_spawn_that_failed_partway covers 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.

Comment on lines +48 to +50
# 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.

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.

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=False still runs workers on the controller's node.
  • trainer=True, controller=True spawns a share through this_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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 3187f3d to 2e0fb04 Compare November 22, 2026 12:45
@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 1m 16s —— View job


Approve, with one item before merging: 2e0fb04 fixes the PBS placement and I found no new defects, but the human-written summary is still empty. One wording suggestion is posted inline. 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: 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

  1. 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 3187f3d is in pbs.py. The PR description already describes the PBS behavior.
  • controller_on_first_trainer_host is still set in one place per launcher: the base class sets False, SlurmLauncher and PBSLauncher set True. _build_actor_system passes it to Layout.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.

Comment on lines +353 to +354
# 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.

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.

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:

Suggested change
# 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reply from claude: Done in c646a1b: the comment now says "On Slurm and PBS", rewrapped to stay within 100 columns.

@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 2e0fb04 to c646a1b Compare November 22, 2026 15:11
@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 51s —— View job


Approve, with one item before merging: c646a1b makes the PBS wording fix and I found no new defects. The human-written summary is still empty. 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: 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

  1. 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 at 2e0fb04 apart from that comment. The rule (a host is kept when it has a True role and no False role) and the this_host() substitution for trainer host 0 are unchanged.
  • spawn_rollout_workers and stop_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 with return_exceptions=True.
  • controller_on_first_trainer_host is set in one place per launcher (base False, Slurm and PBS True) and is required in Layout.host_meshes and HostMeshes.
  • 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.

felipemello1 added a commit that referenced this pull request Nov 23, 2026
## 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.

![On main every recipe starts 4 rollout workers, so each worker runs 16
training rollouts for the batch-invariant CI recipes and 384 for
Terminal-Bench 9B, while this PR starts one worker per 128 training
rollouts in flight (1 and 12 workers) and raises for a group over 128
rollouts.](https://raw.githubusercontent.com/felipemello1/pr_images/81b3f3c5472e7afa521015485beada6a8fb24d0f/torchtitan/6112/columns.png)
<!-- 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]>
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch 5 times, most recently from 1d5e291 to 4c0c749 Compare November 23, 2026 19:57
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from 4c0c749 to 87a1d61 Compare November 23, 2026 20:12
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch 2 times, most recently from 7a8b7e0 to b5da469 Compare November 24, 2026 02:29
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.
@felipemello1
felipemello1 force-pushed the felipemello1/distribute/2-spread-workers branch from b5da469 to 50d58a0 Compare November 24, 2026 02:30

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