Repository navigation
[rl] Size the rollout worker pool from rollouts_per_worker - #6112
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 2m 26s —— View job Approve -- please address the items before merging (a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The worker count now follows the load, so recipes no longer start a fixed 4 workers. What's left are small local edits. A maintainer still needs to review, since this touches controller.py.
What this PR does. Rollouter.Config.worker_pool_size (a fixed count, default 4) is replaced by rollouts_per_worker (default 64). The new Controller.Config.num_rollout_workers property computes ceil(max_active_rollout_groups * num_samples_per_prompt / rollouts_per_worker) and passes it to Rollouter.setup_async(num_workers=...). A whole group runs on one worker, so a group larger than rollouts_per_worker raises at config time. dapo_math 30B-A3B and slake override the ratio to cap the number of processes on their host.
Example.
P=32, S=3 -> 128 groups in flight, group size 8 = 1024 rollouts
main: 4 workers, 256 rollouts each
this PR: ceil(1024 / 64) = 16 workers, 64 each
group size 128, defaults -> ValueError at config build (main: it ran on 4 workers)
I checked all callers: VerifiersRollouter is the only Rollouter subclass and it forwards num_workers. No references to worker_pool_size are left. Rollout seeds are set per sample, not per worker, so the worker count does not change numerics.
Must fix
- The PR description's "Summary (human-written)" section is empty. The author needs to fill it in before merge.
torchtitan_recipes/rl/dapo_math.py:535-- the knob is set afterController.Configis built, so both new checks are skipped. Set it where the rollouter config is built (inline).torchtitan/rl/controller/controller.py:916,:1268-- therelease_groupsTODOs are unrelated to pool sizing, and the code doesn't say why the release can't go yet. Drop them, or state the reason in the code (inline).
Should consider
tests/rl/unit_tests/cpu/test_async_controller.py:84-- the round-up test only re-checks a one-lineceil. Keep the raise test (inline).
Questions
- Both overrides are written as absolute counts ("256 starts 10 workers", "1024 starts 4 workers"). In both cases the real limit is the memory of one host, not the load per worker. A ratio drifts with the recipe's other settings. For example, slake's builder takes
target_offpolicy_steps: at 15 it would start 8 workers on the controller host, not 4. Is a ratio the right knob for these two recipes, or should they be left as accepted exceptions? - The CI recipes, the RL loss guard, and the 816B GB300 dapo_math recipe drop from 4 workers to 1.
_collect_validation_rolloutsgathers every validation sample at once, so all of them, plus scoring (up to 4 Math-Verify processes per worker for dapo_math), now land on a single event loop. Was validation or step time checked on any of these?
Not verified: runtime or step-time effect of the new worker counts (no GPU run, per the PR).
| # 256 starts 10 workers. The default 64 would start 40, on the one host that also runs the trainer and | ||
| # the generator. Each worker takes ~1.15 GiB after imports, plus up to 4 Math-Verify processes. | ||
| config.rollouter.rollouts_per_worker = 256 |
There was a problem hiding this comment.
This sets the field after Controller.Config is built, so neither of the two checks this PR adds runs on it: Rollouter.Config.__post_init__ (rollouts_per_worker >= 1) and the group-size check in Controller.Config.__post_init__. Today it's harmless (16 <= 256), but this recipe is now the one in-repo example of setting the knob, and anyone who copies it skips both checks. config.md also says to build a config complete instead of patching it afterwards.
Set it where the rollouter is built (line 442), e.g.
rollouter=dataclasses.replace(
_dapo_math_rollouter_config(...),
rollouts_per_worker=256, # <- comment moves here
),or give _dapo_math_rollouter_config a rollouts_per_worker kwarg. Then delete lines 533-535.
There was a problem hiding this comment.
Reply from claude: Fixed in d963cd9: rollouts_per_worker=256 is now set where the rollouter config is built (dataclasses.replace(_dapo_math_rollouter_config(...), rollouts_per_worker=256)), so both checks run. slake already sets it inside its own Rollouter.Config(...).
| return_exceptions=True, | ||
| ) | ||
| # Drop the generators' pinned cache salts and held KV for these groups. | ||
| # TODO: evaluate how to remove this group-level release. |
There was a problem hiding this comment.
This TODO, and the one at line 1268, have nothing to do with sizing the worker pool. That makes them a second concern in this PR. They also don't say why the release can't go yet. The reason (each group's prefix-cache salt stays pinned until release_groups, and without sticky routing only release_groups frees held KV) is only in the PR description. Either drop both TODOs from this PR, or, if they stay, put that reason in the code:
| # TODO: evaluate how to remove this group-level release. | |
| # TODO: remove this group-level release once a rollout's cache salt and held KV can be freed | |
| # without it (needs sticky routing). |
There was a problem hiding this comment.
Reply from claude: Keeping both TODOs word for word: the PR author asked for exactly this TODO, in this PR. It marks an open question to evaluate, not a fix that is known to be safe.
There was a problem hiding this comment.
Lets add a bit more info here.
| # TODO: evaluate how to remove this group-level release. | |
| # TODO: evaluate if we need this group-level release, since we already release | |
| # at the end of every rollout. |
There was a problem hiding this comment.
Reply from claude: moved, with your text, to InterGeneratorRouter.release_groups, which both callers use. I added
why it can't simply go: it also drops each group's pinned cache salt, which the per-rollout release doesn't, and it
frees held KV under non-sticky routing.
| def test_num_rollout_workers_rounds_up_training_rollouts_over_rollouts_per_worker() -> ( | ||
| None | ||
| ): | ||
| # 20 groups of 8: 160 rollouts in flight / 64 per worker = 2.5 | ||
| config = _controller_config_with_groups(num_groups=20, group_size=8) | ||
| assert config.num_rollout_workers == 3 |
There was a problem hiding this comment.
This test re-checks a one-line math.ceil that the property's docstring table already spells out. It guards no invariant that could break silently (tests.md: don't assert what the config computes from values the test just set). Consider dropping it and keeping only the raise test, which does guard a user-facing contract.
There was a problem hiding this comment.
Reply from claude: Keeping it. The property is the one formula this PR adds, and a floor instead of the ceil would start too few workers while still passing the raise test.
5f8f2e6 to
d963cd9
Compare
|
Reply from claude: Answers to the two questions, then the fixes are in d963cd9.
@claude please review |
|
Claude finished @felipemello1's task in 45s —— View job Approve -- please address the items before merging (only the empty human-written summary is left; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The dapo_math fix landed, and the replies settle the other earlier items. The one thing left is the empty human-written summary. A maintainer still needs to review, since this touches controller.py.
What changed since the last review (d963cd9).
- dapo_math 30B-A3B: fixed.
torchtitan_recipes/rl/dapo_math.py:443now setsrollouts_per_worker=256throughdataclasses.replace(_dapo_math_rollouter_config(...), ...). Both new checks run on it:Rollouter.Config.__post_init__reruns onreplace, andController.Config.__post_init__sees the final value._dapo_math_rollouter_configreturns a plainRollouter.Configwhose__post_init__only validates, so rerunning it is safe. release_groupsTODOs (controller.py:916,:1268): the author kept them on purpose. I'm dropping this item. If you touch those lines again, a short reason in the comment (salts stay pinned, and without sticky routing onlyrelease_groupsfrees held KV) would tell a reader why the release can't go yet.- Round-up test: the author kept it because a floor-vs-ceil bug would pass the raise test. That's a fair reason; dropped.
- Questions: answered. slake drifts with
target_offpolicy_steps(8 workers at 15), dapo_math 30B-A3B is pinned at 10, and the 4 -> 1 recipes peak at 84 rollouts on one worker. Whether slake and dapo_math should cap a worker count instead of a ratio is left to the maintainer.
Example.
32 groups in flight x 8 = 256 rollouts / 64 -> 4 workers (main: 4)
48 x 32 = 1536 / 64 -> 24 workers (main: 4)
group size 128, rollouts_per_worker=64 -> ValueError at config build
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author needs to fill it in before merge (CLAUDE.md, PR expectations #2).
Not verified: step time and validation time with the new worker counts (no GPU run, per the PR).
|
|
||
| @property | ||
| def num_rollout_workers(self) -> int: | ||
| """Training rollouts in flight / `rollouter.rollouts_per_worker`, rounded up. Validation |
There was a problem hiding this comment.
| """Training rollouts in flight / `rollouter.rollouts_per_worker`, rounded up. Validation | |
| """Max training rollouts in flight / `rollouter.rollouts_per_worker`, rounded up. Validation |
Lets make sure we are talking about max inflight, since the actual inflight is variable
There was a problem hiding this comment.
Reply from claude: done. The docstring now starts "Max training rollouts in flight / rollouter.rollouts_per_worker,
rounded up", and its example uses the new default, 128.
| return_exceptions=True, | ||
| ) | ||
| # Drop the generators' pinned cache salts and held KV for these groups. | ||
| # TODO: evaluate how to remove this group-level release. |
There was a problem hiding this comment.
Lets add a bit more info here.
| # TODO: evaluate how to remove this group-level release. | |
| # TODO: evaluate if we need this group-level release, since we already release | |
| # at the end of every rollout. |
|
|
||
| max_num_seqs = config.max_num_seqs_per_generator_dp_rank | ||
| logger.info("max_num_seqs=%d per generator DP rank", max_num_seqs) | ||
| num_rollout_workers = config.num_rollout_workers |
There was a problem hiding this comment.
this is odd. Is this calling the property num_rollout_workers?
Also,
- do we have checks about number of cpus available? like good heuristics?
- I also think that our default should be 128 rollouts per worker. Do we have good reason pick 64? Do we have metrics that can help us capture if this is too litle/too much?
There was a problem hiding this comment.
Reply from claude:
- Yes, a property on
Controller.Config, likemax_num_seqs_per_generator_dp_rankright above it. - CPUs: no cap. At 128, our recipes start 1 to 32 workers. With the next PR, that is at most 20 on one host
(dapo_math 30B-A3B, a one-host recipe), and SLAKE's 32 go 4 per host. The real limits are memory and CPU next to
the inference engine. The controller also can't see other hosts' CPUs. A per-host cap is a TODO at the spread code. - 128: it's 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. So 64 and 128 both fit. 128
starts half the processes. None of those numbers measures our workload, so the metrics below are the check. - Metrics:
rollout_worker/event_loop_lag_ms(the worst lag in the step) says the workers are behind.
rollout_worker/peak_rss_gibsays what each one costs. The third PR of this stack adds
rollout_worker/rollouts_in_flight_maxvs_mean.
| release_session_fn = self._make_release_session_fn() | ||
|
|
||
| # One rollout worker per active buffer slot: lets generation fill every active slot, | ||
| # One rollout loop per active buffer slot: lets generation fill every active slot, |
There was a problem hiding this comment.
is "per buffer slot" the right way of doing it? Sounds like more than necessary. I guess i have to revise the logic here. Maybe the initial idea was one per worker? but now we will distribute and even route, so i am not sure if this logic is proper. Maybe it is, i just want some clarification.
Also, what does "Active" mean here? seems like a bad word choice
There was a problem hiding this comment.
Reply from claude: the count is right. A rollout loop is an asyncio task in the controller, not a process; it waits on
one group while a worker runs it. Example: dapo_math 30B-A3B admits 160 groups of 16. At 128 per worker, that's 20
worker processes. One loop per worker would start only 20 groups at a time, an eighth of the budget. "Active" is the
buffer's word: a group counts from admission until it's trained (work_buffer.py:57-82). The old task name
rollout_worker_{i} was the confusing part; it's rollout_loop_{i} now, and the comment says what a loop is.
Renaming max_active_rollout_groups touches 26 lines in 7 files, so I left it for a separate PR if you want it.
| metrics=[m.Metric("rollout/group_failures", m.Sum(1.0))], | ||
| ) | ||
| # The group makes no more generation calls, so its cache salts can go. | ||
| # TODO: evaluate how to remove this group-level release. |
There was a problem hiding this comment.
i am pretty sure i commented on such todo already. Is this repeated?
There was a problem hiding this comment.
Reply from claude: yes, it was at both callers, validation and training. It's now one TODO, on the method both call
(InterGeneratorRouter.release_groups).
| """Training rollouts in flight per rollout worker, on average; sets the worker count | ||
| (`Controller.Config.num_rollout_workers`). Higher starts fewer processes, but more rollouts | ||
| share each worker's one event loop. At 64, 32 groups of 8 run on 4 workers.""" |
There was a problem hiding this comment.
| """Training rollouts in flight per rollout worker, on average; sets the worker count | |
| (`Controller.Config.num_rollout_workers`). Higher starts fewer processes, but more rollouts | |
| share each worker's one event loop. At 64, 32 groups of 8 run on 4 workers.""" | |
| """Used to estimate the `Controller.Config.num_rollout_workers` based on the number | |
| max inflight rollouts. E.g. num_workers = min(max_inflight/rollouts_per_worker, num_cpus_available). |
Lets do something like this. Please revise. Feel free to improve this docstring with minor nits.
There was a problem hiding this comment.
Reply from claude: took the formula and an example. I left out the CPU term: the controller only sees its own host's
CPUs, the workers now spread to hosts it can't see, and at 128 we start at most 32 workers, over 8 hosts. A per-host
cap is a TODO at the spread code. More on the controller.py:784 thread.
| if self.rollouts_per_worker < 1: | ||
| raise ValueError( | ||
| "worker_pool_size must be at least 1, got " | ||
| f"{self.worker_pool_size}" | ||
| "rollouts_per_worker must be at least 1, got " | ||
| f"{self.rollouts_per_worker}" | ||
| ) |
There was a problem hiding this comment.
this seems useless. Shouldnt the check be self.rollouts_per_worker < groupsize?
Actually, what happens if group size >self.rollouts_per_worker? shouldnt this just be a warning, i.e. we are processing more than expected, but things still run, or does it truly break anything?
I guess we should still raise anyway
There was a problem hiding this comment.
Reply from claude: the group check exists, in Controller.Config.__post_init__, because the group size lives in
async_loop. It already raises for any rollouts_per_worker below 1: every group has 1 or more rollouts (I added
that check too, nothing enforced it), so I deleted the < 1 one. What breaks: nothing crashes, but workers sit idle.
4 groups of 256 at 128 per worker start ceil(1,024 / 128) = 8 workers, and only 4 can ever be busy. So it raises, and
the message says why.
| rollouter=dataclasses.replace( | ||
| _dapo_math_rollouter_config( | ||
| validation_dataset=AIME2025Dataset.Config(), | ||
| token_env=TokenEnv.Config( | ||
| max_rollout_tokens=max_total_tokens, | ||
| max_num_turns=1, | ||
| ), | ||
| ), | ||
| # 256 starts 10 workers. The default 64 would start 40, on the one host that also runs the | ||
| # trainer and the generator. Each worker takes ~1.15 GiB after imports, plus up to 4 | ||
| # Math-Verify processes. | ||
| rollouts_per_worker=256, |
There was a problem hiding this comment.
i said in another comment by thoughts about using 128 per worker. Lets not make this change here.
"Each worker takes ~1.15 GiB after imports" do you know why? is it the pyotch import? can we do anything about it?
"plus up to 4
# Math-Verify processes." should we worry about this?
Whats the point of having 40 independent workers that inmports pytorch 40 times? This creates these bubbles that some workers are busier than others. Is there a more efficient way of doing this "pool" of workers without paying the 1.15GB 40x?
There was a problem hiding this comment.
Reply from claude: removed; 30B-A3B now starts 20 workers at the default 128, not 40.
- Memory: the "1.15" is 1,155 MiB of RSS (1.13 GiB). ~0.46 GiB of it is shared library pages, mapped once per host, so each extra worker costs
~0.7 GiB. By import: torch 578 MiB, transformers 22, Monarch 84, and ~450 MiB of grain and datasets. Those load
with theVisionProcessorimport, which runstorchtitan/components/data/__init__.py; the renderer and
rl/rollout/data.pyimport them too. - What we can do: lazy imports could save up to ~450 MiB per worker without touching torch. I left a TODO at the
VisionProcessorimport; it's a follow-up PR. Whether the worker needs those modules is not checked yet. - Math-Verify: no worry. Each scorer is a ~73 MiB
python -Iprocess, started on first use, at most 4 per worker. - 40 workers: 128 halves the count. Fewer, fatter processes is the common choice. The busy-worker bubbles are what
the third PR's least-loaded pick is for.
| # 1024 starts 4 workers at the default target_offpolicy_steps=7. The default 64 would | ||
| # start 64, ~1.15 GiB each after imports, all on the controller host: each worker opens | ||
| # its images by a local path. | ||
| rollouts_per_worker=1024, |
There was a problem hiding this comment.
nah, this is bad. Sounds like we have to understand if
- 64 rollouts per worker is too low.
- If it isnt, then 1024 will lag, right? We dont want to lag, specially for images processing, if any.
- If it is, then we should increase our default
- We can reduce this 1.15GB cost per worker
There was a problem hiding this comment.
Reply from claude: removed. 1) 128 is the new default: a starting point inside what RL libraries run, not a measured
optimum. 1024 would have put 4,096 rollouts on 4 workers. Each rollout renders its image on the worker's 4-thread
pool, so renders would have waited for a thread. The lag metric doesn't see that wait; a render-time span would (TODO
at num_threads_per_worker). 2) Lazy imports, a follow-up, cut up to ~450 MiB per worker. SLAKE now runs 32
workers, 4 per host with the next PR. The Slurm launcher already requires the dataset on every node.
d963cd9 to
7f2c312
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 50s —— View job Approve -- please address the items before merging (only the empty human-written summary blocks; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The author's replies settle the earlier review threads. The one blocking item left is the empty human-written summary. This touches controller.py, so a maintainer still needs to review.
What this PR does. Rollouter.Config.worker_pool_size (fixed at 4) is replaced by rollouts_per_worker (default 128). Controller.Config.num_rollout_workers is ceil(max_active_rollout_groups * num_samples_per_prompt / rollouts_per_worker), and it is passed to Rollouter.setup_async(num_workers=...). A whole group runs on one worker, so a group larger than rollouts_per_worker raises at config time. Each worker appends rollout_worker/event_loop_lag_ms (Max, reset at sync_log_step) and rollout_worker/peak_rss_gib to every group it returns. The controller now uses += to add its rollout metrics, so the worker metrics survive.
Example.
8 groups x 8 = 64 in flight / 128 -> 1 worker (main: 4)
48 x 32 = 1536 / 128 -> 12 workers (main: 4)
group size 256, defaults -> ValueError at config build
Changes since the last review. The dapo_math and slake overrides are gone, and every recipe uses the default 128. The TODO moved to InterGeneratorRouter.release_groups, with the reason it can't simply go. The num_samples_per_prompt >= 1 check is new. I checked at HEAD: VerifiersRollouter forwards num_workers, no worker_pool_size references remain, and validation drops group.metrics as before (controller.py:917-935). So the worker metrics reach W&B only through training groups, as the description says.
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author needs to fill it in before merge.
Should consider
tests/rl/unit_tests/cpu/test_rollouter_pool.py:103-- the real-process test costs ~15-20 s of CPU CI for an observability metric. It can run in-process like the test above it (inline).torchtitan/rl/actors/monarch/rollout_worker.py:116--peak_rss_giboverlaps the memory metrics in open #5926 from the same actor. Pick one (inline).
Questions
- At this PR alone, dapo_math 30B-A3B runs 20 workers and SLAKE 32, all on the controller host: ~13.9 GiB and ~22 GiB, against ~3.1 GiB on main. The description says this PR and #6113 should land together. Will they merge together, or should this one wait for #6113?
Not verified: that Monarch calls RolloutWorkerActor.__cleanup__ on stop (I couldn't inspect the installed Monarch). Also not verified: step time and validation time at the new worker counts (no GPU run).
| return _LoopBlockingWorker() | ||
|
|
||
|
|
||
| def test_rollout_worker_reports_its_event_loop_lag() -> None: |
There was a problem hiding this comment.
This test spawns a real Monarch process and ships the module by value with cloudpickle. The PR says that adds ~15-20 s to the CPU job, and all it guards is an observability metric. The lag tracker doesn't need a separate process. test_rollout_worker_actor_builds_its_worker_and_inits_its_logger above already runs RolloutWorkerActor.__init__ in-process inside asyncio.run, and that starts _track_event_loop_lag on the same loop. So the same check can run in under a second:
async def run() -> float:
actor = object.__new__(RolloutWorkerActor)
RolloutWorkerActor.__init__(actor, worker_config=SimpleNamespace(build=lambda: None),
worker_kwargs={}, num_threads=1, structured_logger_init_fn=None)
await asyncio.sleep(0) # let the lag task start its sleep
time.sleep(0.3) # block the loop
await asyncio.sleep(0.15)
return actor._max_event_loop_lag_s
assert asyncio.run(run()) >= 0.15That also drops _LoopBlockingWorker, its config, and the cloudpickle/this_host imports. The 6-line append in run_group would lose its test, and I think that's an acceptable loss.
| "rollout_worker/event_loop_lag_ms", | ||
| m.Max(1000 * self._max_event_loop_lag_s), | ||
| ), | ||
| m.Metric("rollout_worker/peak_rss_gib", m.Max(peak_rss_gib)), |
There was a problem hiding this comment.
#5926, also open and by the same author, adds process/rollout_worker/rss_anon_gib/{sum,max} and host_mem_available_gib from this same actor. If both land, the same process gets two memory metrics with different semantics: peak RSS here, which counts shared pages, and anonymous RSS there. Please pick one. If #5926 is still the plan, drop peak_rss_gib here and keep only the lag metric. If it isn't, close #5926 or rebase it onto this metric.
| # The worst event-loop lag in this step; `sync_log_step` starts it over. | ||
| self._max_event_loop_lag_s = 0.0 | ||
| self._event_loop_lag_task = asyncio.get_running_loop().create_task( | ||
| self._track_event_loop_lag() | ||
| ) | ||
|
|
||
| async def _track_event_loop_lag(self) -> None: | ||
| """Measure how late a 0.1 s sleep wakes up. A busy loop runs other rollouts' code first: | ||
| woken after 0.35 s -> lag 0.25 s.""" | ||
| loop = asyncio.get_running_loop() | ||
| while True: | ||
| start = loop.time() | ||
| await asyncio.sleep(_EVENT_LOOP_CHECK_INTERVAL_S) | ||
| lag_s = loop.time() - start - _EVENT_LOOP_CHECK_INTERVAL_S | ||
| self._max_event_loop_lag_s = max(self._max_event_loop_lag_s, lag_s) |
There was a problem hiding this comment.
i am not against having it here, but it seems like a decent utility that could be used in other places as well. I think we have a draft pr doing that already.
There was a problem hiding this comment.
Reply from claude: done in a2d425f. The tracker is now a shared EventLoopLag in torchtitan/rl/observability/metrics/loop_lag.py, with the same module, class name and API as your event-loop-lag draft (controller, batcher, generation server), so that draft can drop its copy. The worker builds it in one line.
| # For sizing `rollouts_per_worker`: lag means too many rollouts per worker, memory too many | ||
| # workers. Peak RSS counts shared library pages in every worker, so a sum over workers is an | ||
| # upper bound. `ru_maxrss` is in KiB on Linux. |
There was a problem hiding this comment.
this is not human friendly. Write it better.
There was a problem hiding this comment.
Maybe something like:
# Compute lag and memory metrics per group.
# peak_rss_gib measures XYZ.
# Lag is the bla bla bla.
also is there a better name for "peak_rss_gib"? rss is not an obvious name.
There was a problem hiding this comment.
Reply from claude: rewritten in your shape (a2d425f):
# Add this worker's lag and memory metrics to each training group.
# event_loop_lag_ms: how late this worker's event loop ran ready work, since its previous
# training group. Max: the longest delay. Sum: all delays of 100 ms or more, added up.
# peak_memory_gib: the most RAM this process has held at once, shared libraries included.
# The controller ignores the metrics of validation groups (negative ids), so lag measured during
# validation goes with this worker's next training group.There was a problem hiding this comment.
Reply from claude: renamed to rollout_worker/peak_memory_gib (variable and metric key). The comment above says what it measures.
| # TODO: place single rollouts on workers, so a group can span several; that removes this check. | ||
| # Today a group runs whole on one worker, which scores it and computes its advantages. |
There was a problem hiding this comment.
| # TODO: place single rollouts on workers, so a group can span several; that removes this check. | |
| # Today a group runs whole on one worker, which scores it and computes its advantages. | |
| # TODO: place single rollouts on workers, instead of groups | |
| # so we can have less idle time as rollouts finish. This would require | |
| # rethinking where group-level postprocessing runs. |
There was a problem hiding this comment.
Reply from claude: applied your TODO text word for word.
| f"async_loop.num_samples_per_prompt={group_size} is over " | ||
| f"rollouter.rollouts_per_worker={self.rollouter.rollouts_per_worker}: a group runs whole " | ||
| "on one worker, so workers beyond the groups in flight would sit idle during training. " | ||
| "Raise rollouts_per_worker or lower num_samples_per_prompt." | ||
| ) |
There was a problem hiding this comment.
this is poorly written. Write plainly.
There was a problem hiding this comment.
Reply from claude: rewritten (a2d425f). With 4 groups of 256 and rollouts_per_worker=128 it now reads: "async_loop.num_samples_per_prompt (256) must be at most rollouter.rollouts_per_worker (128). Each group runs on one worker, so at most 4 workers can run a training group at once, and the extra workers would sit idle. Raise rollouts_per_worker or lower num_samples_per_prompt." It also raises this ValueError for rollouts_per_worker=0 (before, the message itself divided by zero).
| Higher starts fewer processes (~0.7 GiB of private memory each after imports), and more | ||
| rollouts share each worker's event loop; `rollout_worker/event_loop_lag_ms` shows a worker | ||
| falling behind. `Controller.Config` checks that a group fits on one worker.""" |
There was a problem hiding this comment.
| Higher starts fewer processes (~0.7 GiB of private memory each after imports), and more | |
| rollouts share each worker's event loop; `rollout_worker/event_loop_lag_ms` shows a worker | |
| falling behind. `Controller.Config` checks that a group fits on one worker.""" | |
| Higher starts fewer processes (~0.7 GiB of private memory each after imports), and more | |
| rollouts share each worker's event loop; `rollout_worker/event_loop_lag_ms` metric shows a worker | |
| falling behind. `Controller.Config` checks that a group fits on one worker.""" |
There was a problem hiding this comment.
Reply from claude: applied your docstring text word for word.
| # TODO: at 128 rollouts per worker, renders and parses (`TokenEnv`) may queue on these threads, | ||
| # and the event-loop lag doesn't show that wait. A span around the render would. |
There was a problem hiding this comment.
is there a way to have it captured by the event loop lag?
| # TODO: at 128 rollouts per worker, renders and parses (`TokenEnv`) may queue on these threads, | |
| # and the event-loop lag doesn't show that wait. A span around the render would. | |
| # TODO: at 128 rollouts per worker, renders and parses (`TokenEnv`) may queue on these threads, | |
| # and the event-loop lag metric doesn't show that wait. A span around the render would. |
There was a problem hiding this comment.
Reply from claude: applied your TODO text word for word. To your question: no. When a render waits for one of the worker's threads, the event loop isn't held: it keeps running other rollouts, so the lag task wakes up on time. To see that wait, time how long each asyncio.to_thread call waits for a free thread, or add a span around the render (your TODO).
7f2c312 to
a2d425f
Compare
|
Reply from claude: @claude please review. Since your last review: the lag test now runs in-process ( |
|
Claude finished @felipemello1's task in 1m 23s —— View job Approve -- please address the items before merging (still blocking: the empty human-written summary; still open: the #5926 memory-metric overlap; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new commit takes the maintainer's review threads and the earlier automated items, and I found no new correctness problems. The empty human-written summary still blocks merge. Because this touches controller.py, a maintainer still needs to review.
What changed since the last review (a2d425f).
- Lag test: fixed.
test_rollouter_pool.py:93now runs in-process, with no Monarch process and nocloudpickle. It still covers the validation-vs-training split. - The tracker is now the shared
EventLoopLag(rl/observability/metrics/loop_lag.py), which emits Max plus a Sum of delays of 100 ms or more. The worker flushes it only for training groups (group_id >= 0). I checked at HEAD: validation ids count down from -1 (controller.py:654), and_collect_validation_rolloutsreads onlygroup.rollouts(controller.py:930-945). So lag measured during validation goes to the next training group, as the comment says. peak_rss_gibis renamed topeak_memory_gib. The comments, the TODOs and the group-size error message are rewritten as the author asked.- The controller now uses
group.metrics += ...(controller.py:1260), andRolloutGroup.metricsusesdefault_factory=list, so no list is shared between groups.
Example.
training group 0 returns from worker 0 after a 0.3 s render held its loop
-> group.metrics += [event_loop_lag_ms Max(~300), Sum(~300), peak_memory_gib Max(1.1)]
-> controller += rollout/* metrics -> W&B at the step that trains group 0
validation group -1 on the same worker -> no worker metrics; its lag goes to the next training group
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Still open from the last review
rollout_worker.py:99: this PR'srollout_worker/peak_memory_giboverlaps the memory metrics that #5926 (still open) adds from the same actor (process/rollout_worker/rss_anon_gib). Nobody has replied on that thread. Please decide which one stays before both land.
Questions
- Will this PR merge together with #6113? Until #6113 lands, all workers run on the controller host: dapo_math 30B-A3B starts 20 and SLAKE 32 (~13.9 / ~22 GiB).
Not verified: I couldn't run the tests or inspect the installed Monarch, so I haven't checked that RolloutWorkerActor.run_group._method.__wrapped__ (a private Monarch attribute, used in the test) exists in the pinned version. Also not verified: step time and validation time at the new worker counts (no GPU run).
| ) | ||
| # Add this worker's lag and memory metrics to each training group. | ||
| # event_loop_lag_ms: how late this worker's event loop ran ready work, since its previous | ||
| # training group. Max: the longest delay. Sum: all delays of 100 ms or more, added up. |
There was a problem hiding this comment.
why 100ms? I dont think we should this sort of detail in comments about other functions, otherwise if they change, the comment becomes stale. Its better to leave details to the function where it belongs.
There was a problem hiding this comment.
Reply from claude: agreed, done in c749040. The comment above the worker metrics (rollout_worker.py:90-95) now says what each metric measures, one line each, and nothing about how EventLoopLag computes it. On 100 ms: that threshold only kept small delays out of the old Sum. The lag is now logged as ms late per second (see the loop_lag.py thread). A rate needs no threshold, so threshold_s is gone.
|
|
||
| from torchtitan.components.tokenizer import HuggingFaceTokenizer | ||
| from torchtitan.observability import structured_logger as sl | ||
| from torchtitan.rl.observability import metrics as m |
There was a problem hiding this comment.
i dont think we need the "as m".
There was a problem hiding this comment.
Reply from claude: I kept it to match the rest of RL. The RL modules that log these metrics on main import metrics as m (controller.py:131, rollout/types.py:16, trainer/batcher.py:32, ...), and so does the metrics README (observability/metrics/README.md:27). If you'd rather import the names, I'll switch this file to from torchtitan.rl.observability.metrics import EventLoopLag, Max, Metric.
| if group_id >= 0: | ||
| # `ru_maxrss` is in KiB on Linux. | ||
| peak_memory_gib = ( | ||
| resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20 |
There was a problem hiding this comment.
where/when is this resource reset? or it isnt/shouldnt?
There was a problem hiding this comment.
Reply from claude: it isn't reset, and doesn't need to be. ru_maxrss is the peak since the process started, so the metric answers "how much memory does a worker need". The comment now says "Nothing resets it" (rollout_worker.py:97 in c749040). A per-step peak would need a reset through /proc/self/clear_refs, which also resets it for every other tool that reads it. Your #5926 logs each worker's memory every step (process/rollout_worker/rss_anon_gib) and edits the same files. Whichever lands second rebases.
| f"async_loop.num_samples_per_prompt ({group_size}) must be at most " | ||
| f"rollouter.rollouts_per_worker ({rollouts_per_worker}). Each group runs on one " | ||
| f"worker, so at most {self.async_loop.max_active_rollout_groups} workers can run " | ||
| "a training group at once, and the extra workers would sit idle. Raise " | ||
| "rollouts_per_worker or lower num_samples_per_prompt." | ||
| ) |
There was a problem hiding this comment.
raise ValueError(
f"async_loop.num_samples_per_prompt ({group_size}) is larger than "
f"rollouter.rollouts_per_worker ({rollouts_per_worker}). Please raise "
"rollouter.rollouts_per_worker or lower async_loop.num_samples_per_prompt."
)
There was a problem hiding this comment.
Reply from claude: done in c749040, your text word for word (controller.py:434-438). The test matches it in both cases: a group of 256 with 128 per worker, and a group of 8 with 0 (test_async_controller.py:96-102).
| (`verifiers_env_server.serve.pool`), the env server runs its rollouts in its pool workers. So 4 | ||
| rollout workers and a pool of 8 add 4 + 1 + 8 processes to the controller, not 4 x 8. The env server |
There was a problem hiding this comment.
I am a but confused here. What work does the worker do and the envserver do? It sounds like most of it is done by the envserver?
the rollout worker scales with number of rollouts. How about the envserver?
having a separate pool for envserver seems wasteful. Is this the best design?
There was a problem hiding this comment.
Reply from claude: on main, the work splits like this (the README's steps 1-10):
- The env server runs the Verifiers env. It starts each agent in its runtime (a process or a Docker container), hosts the server the agent sends its chat requests to, and grades the rollout (steps 2-4, 8-9).
- The rollout worker drives generation. Its
GenerationServerturns each chat request into agenerate_fncall (steps 5-7). Then it turns the traces into TitanRL rollout turns, scores the group and computes advantages (step 10). - The rollout workers scale with rollouts in flight (this PR). The env server is one process, plus a pool whose size is fixed in config (
verifiers_env_server.serve.pool).
You're right that a second pool is wasteful. #6118 deletes the env server: each rollout worker runs its own Verifiers env, so the rollout workers are the only pool, and they scale with rollouts. Its README then counts "the controller and the rollout workers", and says "Each worker loads the env and runs its episodes". In this PR, the README change is down to the worker-count sentence (examples/verifiers/README.md:71-72).
| self._reset() | ||
| return [ | ||
| Metric(self._key, Max(1000 * max_lag_s)), | ||
| Metric(self._key, Sum(1000 * total_lag_s)), |
There was a problem hiding this comment.
if we are doing this across workers. Should we log the sum, but compute the mean across workers?
There was a problem hiding this comment.
Reply from claude: yes, done in c749040. Before, the step logged the Sum over every group of every worker, so it grew with the worker count: 12 workers, each 1 s late, read 12,000 ms. A plain mean over groups would weigh a worker by how many groups it returned (up to 16 per step at 128 rollouts per worker and groups of 8). So each flush now logs its late ms as a Mean whose count is the seconds it covers (loop_lag.py:63-64). Across workers, that reduces to ms late per second, averaged over workers: rollout_worker/event_loop_lag_ms_per_s/mean.
Example: worker A is 1,980 ms late in 10 s, and worker B 0 ms. The step logs (1980 + 0) / (10 + 10) = 99 ms per s. The Max stays: the longest single delay on any worker.
| worker_pool_size: int = 4 | ||
| """CPU rollout worker processes to spawn on the controller host.""" | ||
| rollouts_per_worker: int = 128 | ||
| """Sets how many rollout worker processes start, from the max training rollouts in flight: |
There was a problem hiding this comment.
lets trim this docstring a bit. too long.
There was a problem hiding this comment.
Reply from claude: trimmed to the sizing rule and one example (rollouter.py:111-117 in c749040). Your text from the last round stays word for word, minus its last sentence ("Controller.Config checks that a group fits on one worker"): by your rule on rollout_worker.py:88, that detail lives in the check.
a2d425f to
c749040
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 25s —— View job Approve -- please address the items before merging (still blocking: the empty human-written summary; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The latest push (c749040) answers the maintainer's threads from 02:06 and 02:40, and I found no new correctness problems. The empty human-written summary still blocks merge. This touches controller.py, so a maintainer still needs to review.
What changed since the last review.
- Lag as a rate:
EventLoopLag.flush(loop_lag.py:638-647) now returns aMaxand aMean(total_ms, count=elapsed_s)under<role>/event_loop_lag_ms_per_s, andthreshold_sis gone. I checkedMean.reduce(types.py:149-154): it issum(value) / sum(count). Each flush on a worker covers its own stretch of time, with no overlap, so the step reads time-weighted ms late per second across groups and workers, as the description says. The idle floor (~20 wakes/s, each slightly late) sits in that rate. The description reports it as ~4 ms/s. - The tracker now starts at the end of
RolloutWorkerActor.setup_async(rollout_worker.py:69), so the tokenizer build isn't counted. The Rollouter raises on a second setup, and the controller awaits setup before anyrun_group, so the attribute that is only declared in__init__is always set before it's read. - The worker comment no longer describes how
EventLoopLagworks inside. It also saysru_maxrssis never reset. The group-size error uses the maintainer's text. Therollouts_per_workerdocstring is trimmed. - #5926 overlap: the author answered ("whichever lands second rebases"), and both PRs are theirs. Dropped.
Example.
worker A: 10 s since its last training group, one 2 s hold -> Max 1980, Mean(1980, count=10)
worker B: 10 s, idle -> Max ~0, Mean(~40, count=10)
step logs: event_loop_lag_ms/max = 1980
event_loop_lag_ms_per_s/mean = (1980 + 40) / 20 = ~101
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Questions
- The description says this PR and #6113 should land together, because until then dapo_math 30B-A3B (20 workers) and SLAKE (32) run all their workers on the controller host. Will they merge as a pair?
Not verified: I couldn't run Python here, so I couldn't confirm that RolloutWorkerActor.run_group._method.__wrapped__ (a private Monarch attribute; this test is its only user in the repo) exists in the pinned Monarch. Step time and validation time at the new worker counts are not measured (no GPU run).
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. HEAD (0cd97c8) is back to the reviewed c749040 design, plus the maintainer's wording. Both must-fix items from the last review are resolved, and I found no new correctness problems. The empty human-written summary still blocks merge. This touches controller.py, so a maintainer still needs to review.
What this PR does. Rollouter.Config.worker_pool_size (fixed at 4) is replaced by rollouts_per_worker (default 128). The controller starts ceil(max_active_rollout_groups * num_samples_per_prompt / rollouts_per_worker) workers. A group larger than rollouts_per_worker raises at config time. Each training group a worker returns gets rollout_worker/event_loop_lag_ms (Max), event_loop_lag_ms_per_s (a Mean weighted by time), and peak_memory_gib.
Example.
8 groups x 8 = 64 in flight / 128 -> 1 worker (main: 4)
48 x 32 = 1536 / 128 -> 12 workers (main: 4)
group size 256, defaults -> ValueError: "num_samples_per_prompt (256) is larger than rollouter.rollouts_per_worker (128) ..."
Since the last review (4a3d9db -> 0cd97c8).
- 32-thread default: resolved.
num_threads_per_workeris 4 again (rollouter.py:692). The new default, the extra metrics andgc.freeze()moved to #6174. - Repeated metric definitions: resolved. The long comment is gone, and
run_grouplists only the two metrics it adds. - The group-size error now uses the maintainer's text (
controller.py:423-427), and the test matches it.
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Should consider
torchtitan/rl/actors/monarch/rollout_worker.py:90-94-- the rewritten comment is ambiguous about which groups have negative ids, and it drops why validation is skipped (inline, with a suggestion).torchtitan/rl/controller/controller.py:1190,:1527-- drive-by docstring reformats (inline).
Not verified: I couldn't run Python here. So RolloutWorkerActor.run_group._method.__wrapped__, the private Monarch attribute the lag test uses, is still unchecked against the pinned Monarch. Step time at the new worker counts hasn't been measured either (no GPU run).
| # =========== Log worker metrics =========== | ||
| # lag measured during validation goes with this worker's next training group (group_id<0) | ||
| if group_id >= 0: | ||
| # peak_memory_gib: the most RAM this process has held since it started, shared libraries included. | ||
| # `ru_maxrss` is in KiB on Linux. Nothing resets it. |
There was a problem hiding this comment.
The rewrite reads as if group_id<0 marks the training group, and it drops the reason validation is skipped: the controller throws away validation groups' metrics. Without that, a reader can't tell why the if exists. Line 93 also has a double space after #. (Unrelated: line 80 adds a blank line at the start of the body.)
| # =========== Log worker metrics =========== | |
| # lag measured during validation goes with this worker's next training group (group_id<0) | |
| if group_id >= 0: | |
| # peak_memory_gib: the most RAM this process has held since it started, shared libraries included. | |
| # `ru_maxrss` is in KiB on Linux. Nothing resets it. | |
| # =========== Log worker metrics =========== | |
| # Validation groups (group_id < 0) get none: the controller drops their metrics, so lag | |
| # measured during validation goes with this worker's next training group. | |
| if group_id >= 0: | |
| # peak_memory_gib: the most RAM this process has held since it started, shared libraries | |
| # included. `ru_maxrss` is in KiB on Linux. Nothing resets it. |
There was a problem hiding this comment.
Reply from claude: Fixed in cb0a09a: the comment now uses your text, so it says the controller drops validation groups' metrics. The double space after # and the blank first line of run_group's body are gone too.
| `validate_after_training`, and log it. run() calls it after cancelling the running ones. | ||
| """ |
There was a problem hiding this comment.
This change, and the same one at lines 1527-1528, moves a closing """ onto its own line in docstrings this PR doesn't otherwise touch. On main each is one line, so this is a drive-by reformat (one concern per PR). Revert both, unless pre-commit now asks for it.
| `validate_after_training`, and log it. run() calls it after cancelling the running ones. | |
| """ | |
| `validate_after_training`, and log it. run() calls it after cancelling the running ones.""" |
There was a problem hiding this comment.
Reply from claude: Fixed in cb0a09a: both docstrings (_maybe_validate_after_training and _start_push_model_state_dict) close on one line again, as on main. pre-commit passes on the file.
0cd97c8 to
cb0a09a
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 56s —— View job Approve -- please address the items before merging (still blocking: the empty human-written summary; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. HEAD (cb0a09a) resolves both should-consider items from the last review, and I found no new correctness problems. The empty human-written summary still blocks merge. This touches controller.py, so a maintainer still needs to review.
Since the last review (0cd97c8 -> cb0a09a).
- Worker-metrics comment: resolved.
rollout_worker.py:89-91now says validation groups (group_id < 0) get no metrics because the controller drops them. The double space and the blank first line of the body are gone. - Drive-by docstring reformats: resolved.
_maybe_validate_after_trainingand_start_push_model_state_dictno longer appear in the diff.
Example.
8 groups x 8 = 64 in flight / 128 -> 1 worker (main: 4)
20 x 16 = 320 / 128 -> 3 workers (main: 4)
group size 256, defaults -> ValueError: "async_loop.num_samples_per_prompt (256) is larger than rollouter.rollouts_per_worker (128) ..."
At HEAD I checked that no worker_pool_size references are left, that math is imported in controller.py, and that VerifiersRollouter.setup_async forwards num_workers.
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Should consider
torchtitan/rl/rollout/rollouter.py:20andtorchtitan/rl/actors/monarch/rollout_worker.py:21-- each deletes a blank line between imports that this PR doesn't otherwise change. That's a drive-by. Restore both, unless pre-commit asks for the change.torchtitan/rl/examples/verifiers/README.md:530-- the reflow leaves a short line ("the env server runs") with the rest of the sentence on the next line. Rewrap the paragraph.
Not verified: I couldn't run Python here. So RolloutWorkerActor.run_group._method.__wrapped__ (a private Monarch attribute, used by the lag test) is still unchecked against the pinned Monarch. Step time at the new worker counts hasn't been measured (no GPU run).
cb0a09a to
cd3ec9a
Compare
|
Claude finished @felipemello1's task in 40s —— View job Approve -- please address the items before merging (still blocking: the empty human-written summary; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. HEAD (cd3ec9a) resolves both should-consider items from the last review, and the new commit adds no new problems. The empty human-written summary still blocks merge. This touches controller.py, so a maintainer still needs to review.
Since the last review (cb0a09a -> cd3ec9a).
- Drive-by import blank lines: resolved.
rollouter.pyandrollout_worker.pykeep the blank line between therendererandtokenizerimports, as on main. Neither file's import hunk now changes anything except the new imports. - README reflow: resolved.
examples/verifiers/README.md:71-77is rewrapped evenly, and the text is unchanged apart from the worker-count sentence.
Example.
8 groups x 8 = 64 in flight / 128 -> 1 worker (main: 4)
20 x 16 = 320 / 128 -> 3 workers (main: 4)
group size 256, defaults -> ValueError at config build
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Not verified: I couldn't run Python here, so I haven't checked RolloutWorkerActor.run_group._method.__wrapped__ (the private Monarch attribute the lag test uses) against the pinned Monarch. Step time at the new worker counts hasn't been measured (no GPU run).
cd3ec9a to
c5e8ad2
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 7s —— View job Approve -- please address the item before merging (still blocking: the empty human-written summary; a maintainer still needs to review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. HEAD (c5e8ad2, now one squashed commit) is only the pool-sizing change, and I found no correctness problems in it. The empty human-written summary still blocks merge. This touches controller.py, so a maintainer still needs to review.
Since the last review (cd3ec9a -> c5e8ad2). The worker metrics are gone from this PR: EventLoopLag (loop_lag.py), rollout_worker/event_loop_lag_ms*, peak_memory_gib, the lag test, and the controller's group.metrics += change. #6174 now carries them. What's left: the rollouts_per_worker knob, the num_rollout_workers property, the group-size and num_samples_per_prompt >= 1 checks, the rollout_loop_<i> rename, the import TODO in rollout_worker.py, and the release_groups TODO. The release_groups TODO now lists what only that call does. I checked both items at HEAD. EngineLoop.release_groups pops _group_min_policy_versions (engine_loop.py:224-225). release_session frees held KV only when a pin exists (inter_generator.py:241-244).
Example.
8 groups x 8 = 64 in flight / 128 -> 1 worker (main: 4)
20 x 16 = 320 / 128 -> 3 workers (main: 4)
group size 256, defaults -> ValueError at config build
rollouts_per_worker=0 -> same ValueError (every group has >= 1 rollout), no ZeroDivisionError
At HEAD I also checked these. No worker_pool_size references are left, recipes and docs included. math is imported in controller.py. Every Rollouter.setup_async caller passes num_workers: the controller, VerifiersRollouter, and both tests. The Rollouter.Config < 1 check was dropped, but the group-size check in Controller.Config.__post_init__ still covers it.
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in before merge (CLAUDE.md, PR expectations #2).
Should consider
- The PR description says #6174 is "later in this stack". #6174's base is
felipemello1/infra-errors/4-rollout-filter, not a branch above this PR. Until #6174 lands, nothing reports whether 128 rollouts per worker is too many. If #6174 is in a different stack, please say so in the description.
Not verified: I couldn't run the tests here. Step time at the new worker counts hasn't been measured (no GPU run, per the PR).
|
Reply from claude: on "#6174 is later in this stack": it is. Both PRs are in native stack 6205, bottom to top: #6112, #6116, #6182, #6183, #6204, #6174. |
| if group_size > rollouts_per_worker: | ||
| raise ValueError( | ||
| f"async_loop.num_samples_per_prompt ({group_size}) is larger than " | ||
| f"rollouter.rollouts_per_worker ({rollouts_per_worker}). Please raise " | ||
| "rollouter.rollouts_per_worker or lower async_loop.num_samples_per_prompt." | ||
| ) |
There was a problem hiding this comment.
IIUC this is to make sure any worker won't get more rollouts than rollouts_per_worker. Even with this constraint, it still depends on the self._worker_actors.run_group.choose() behavior at https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/rollout/rollouter.py#L256, which I'm not sure if the constraint would be respected, without knowing how choose works. Could you confirm?
There was a problem hiding this comment.
Reply from claude: Confirmed: it doesn't. In torchmonarch 0.8.0, each choose call picks one actor uniformly at random and ignores load (endpoint.rs). So rollouts_per_worker sizes the pool as a mean load, not a cap.
This check only makes sure that one group fits in one worker. Without the check, 4 groups of 256 at 128 per worker would start ceil(1024 / 128) = 8 workers. A worker that gets a group holds 256, and at least 4 workers sit idle. With the check, random choose can still put two allowed groups on one worker: 4 groups of 128 start 4 workers, and if two groups land on the same worker, it holds 256 while another worker sits idle.
With #6114 (least-loaded pick), and while no validation group is in flight, a worker holds at most ceil(R / S) x S training rollouts (R = rollouts_per_worker, S = group size). That is R when S divides R, as in every recipe (S = 2, 8, 16 or 32). This counts whole groups until they return, as #6114's gauges do. Validation groups count toward a worker's load too, so while a validation runs, a worker's training load can go past R.
So no hard cap in this PR. The docstring now says "on average" and "Not a cap" (c7e5aa4).
|
|
||
| await self._rollouter.setup_async( | ||
| actor_system=actor_system, | ||
| num_workers=num_rollout_workers, |
There was a problem hiding this comment.
this is violating encapsulation:
- controller has to look into details of rollouter to get
rollouts_per_workerconfig - to calculate a
num_rollout_workersconfig, to feed back intorollouts_per_worker - and
rollouts_per_workeris not directly used in construction of rollout worker
What I think we should do instead
- send something like
num_rolloutsto the constructor of rollouter
There was a problem hiding this comment.
Reply from claude: Agreed, done in c7e5aa4. The controller now passes the load to the rollouter's constructor, and the rollouter sizes its own pool:
# Controller.__init__
self._rollouter = config.rollouter.build(max_rollouts_in_flight=config.async_loop.max_rollouts_in_flight)
# Rollouter.setup_async
num_workers = math.ceil(self._max_rollouts_in_flight / self._config.rollouts_per_worker)
- Name:
max_rollouts_in_flightrather thannum_rollouts, since it is the most training rollouts in flight at once (groups in flight x group size), not a count per step or per run. It is a newAsyncLoopConfigproperty, whichmax_num_seqs_per_generator_dp_ranknow uses too. - Gone:
Controller.Config.num_rollout_workers, the controller's log line (the rollouter logs the count), andsetup_async(num_workers=...). - Kept in
Controller.Config.__post_init__: the check that a group fits inrollouts_per_worker. It compares two sibling configs at config time, and the config loader reruns only the root__post_init__after recipe edits and overrides (config/loader.py:54-56). - [rl] Spread rollout workers over the hosts of chosen roles #6113, [rl] Send each rollout group to the worker with the fewest rollouts in flight #6114 and [rl] Rollout worker metrics (loop lag, thread-pool lag, RAM), one thread per 4 rollouts, and gc.freeze #6174 need no source change for this. [rl] Spread rollout workers over the hosts of chosen roles #6113's test helper sets the rollouts in flight instead of
num_workers=.
|
@claude review my review |
There was a problem hiding this comment.
Verdict: Request changes -- both of @tianyu-l's comments hold. rollouts_per_worker is an average that choose doesn't enforce, and the controller computes a number from a knob that the Rollouter owns but never reads.
What this PR does. It replaces the fixed worker_pool_size=4 with rollouts_per_worker=128. The controller starts ceil(max_active_rollout_groups * num_samples_per_prompt / rollouts_per_worker) workers and passes that count to Rollouter.setup_async(num_workers=...).
Example.
dapo_math 30B-A3B: 160 groups x 16 = 2560 in flight / 128 -> 20 workers
mean load per worker: 128 rollouts
choose picks a worker without looking at load (random):
busiest worker ~1.98x the mean, i.e. ~250 rollouts (#6114's placement simulation)
Terminal-Bench 9B, 48 x 32 on 12 workers: ~2.36x, i.e. ~300 on the busiest worker
On tianyu-l's comments
1. controller.py:435, "does choose respect the constraint?" The concern is correct. The reading of the check is partly off.
choosedoes not respect it.rollouter.py:256callsself._worker_actors.run_group.choose(...). Peractors/system.py:71, that means "on any one actor of the handle", and nothing in torchtitan tracks load per worker. As far as I know, Monarch'schoosepicks a rank without looking at load. The author's own #6114 says the pick is random today ("Each group goes to a worker picked at random") and replaces it withLeastLoadedRoutingStrategy. Even with that, its simulation puts the busiest worker at 1.6-1.9x the mean. So no worker is kept at or underrollouts_per_worker, in this PR or after #6114.- The check doesn't try to cap the load either. With group size
S>rollouts_per_workerR, the formula starts more workers than there are groups in flight (ceil(G*S/R) > G), so some workers can never get a group. The check only stops that over-count. - Fix: document the knob as what it is, a sizing ratio. For example, at
rollouter.py:111-113:"""Sizes the pool: ceil(max training rollouts in flight / rollouts_per_worker) workers. This is the mean load per worker, not a cap: a worker can hold more, since groups are placed without regard to load (see #6114)."""If a hard cap is what's wanted, it needs a placement change (#6114 plus a limit), not this check.
2. controller.py:850, encapsulation. Correct. rollouts_per_worker sits on Rollouter.Config, but Rollouter never reads it (grep: only controller.py and the test do). The controller reaches into the rollouter's config, does the division, and passes the result back. That breaks config.md's "each component owns its config". The precedent the author cited, max_num_seqs_per_generator_dp_rank, isn't the same case: the generator has no knob that only the controller reads. The fix is to send the load, not the count. I'd call it max_rollouts_in_flight, the name controller.py:570 already uses. A bare num_rollouts is ambiguous (per step? total?).
# rollouter.py
async def setup_async(self, *, actor_system, max_rollouts_in_flight: int, ...):
num_workers = math.ceil(max_rollouts_in_flight / self._config.rollouts_per_worker)
logger.info("%d rollout workers (rollouts_per_worker=%d)", num_workers, self._config.rollouts_per_worker)
...spawn_rollout_workers(self._config.worker, num_workers=num_workers, ...)
# controller.py
await self._rollouter.setup_async(actor_system=actor_system,
max_rollouts_in_flight=async_loop.max_active_rollout_groups * async_loop.num_samples_per_prompt, ...)This deletes the Controller.Config.num_rollout_workers property (controller.py:589-605) and the controller's log (:795-800). The rollouts_per_worker >= 1 check goes back to Rollouter.Config.__post_init__, its owner. The group-size check can stay in Controller.Config.__post_init__, because it relates two sibling configs. VerifiersRollouter.setup_async and both tests forward the new argument. The round-up test moves to the rollouter, or goes away.
Must fix (missed)
- The "Summary (human-written)" section of the PR description is still empty. The author has to write it.
Not verified: Monarch isn't installed in this runner, so I couldn't read the pinned version's choose implementation. The claim that it ignores load rests on #6114's description.
Rollouter.Config.rollouts_per_worker (default 128) replaces worker_pool_size. The controller passes the max training rollouts in flight to the Rollouter's constructor. The Rollouter starts ceil(max training rollouts in flight / rollouts_per_worker) workers, and a group larger than rollouts_per_worker raises.
c5e8ad2 to
c7e5aa4
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 19s —— View job Approve -- please address the item before merging (both of tianyu-l's comments are resolved at c7e5aa4; the human-written summary is still empty and blocks merge; tianyu-l still needs to re-review): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. HEAD (c7e5aa4) fixes both of @tianyu-l's comments, and I found no new correctness problems. The human-written summary is still empty, and that blocks merge. tianyu-l's request for changes stays in place until they re-review, and this touches controller.py, so a maintainer still needs to review.
What this PR does. It replaces the fixed Rollouter.Config.worker_pool_size=4 with rollouts_per_worker=128. The controller passes async_loop.max_rollouts_in_flight (groups in flight x group size) to the Rollouter's constructor. Rollouter.setup_async then starts ceil(max_rollouts_in_flight / rollouts_per_worker) workers and logs the count. A group larger than rollouts_per_worker raises when the config is built.
Example.
dapo_math 30B-A3B: 160 groups x 16 = 2560 in flight -> Rollouter(max_rollouts_in_flight=2560)
setup_async: ceil(2560 / 128) = 20 workers (main: 4)
batch-invariant CI: 8 x 8 = 64 -> 1 worker (main: 4)
group size 256, or rollouts_per_worker=0 -> ValueError in Controller.Config.__post_init__
tianyu-l's comments at HEAD.
controller.py:465, "doeschooserespect the limit?": resolved. Therollouts_per_workerdocstring (rollouter.py:112-115) now says it is an average and "Not a cap", because validation rollouts come on top and groups can land unevenly. The check only makes sure that one group fits on one worker. The author's reply links the Monarch 0.8.0 source, which shows thatchoosepicks an actor at random.controller.py:850, encapsulation: resolved. The Rollouter now reads its own knob and does the division itself (rollouter.py:183-191). The controller passes only the load (controller.py:636-638).Controller.Config.num_rollout_workers, the controller's log line, andsetup_async(num_workers=...)are gone. The group-size check stays in the root config. That is justified: it compares two sibling configs, and the loader reruns only the root__post_init__after recipe edits (config/loader.py:54-56).
At HEAD I also checked these:
- Every caller passes the new argument: the controller,
VerifiersRollouter.__init__, theRollouterdocstring example, and the tests that build one (test_alphabet_sort, plus theobject.__new__stubs intest_rollouter_poolandtest_verifiers). - No
worker_pool_sizeornum_rollout_workersreferences are left anywhere. max_num_seqs_per_generator_dp_ranknow uses the newmax_rollouts_in_flightproperty and computes the same value as before.
Must fix
- The "Summary (human-written)" section of the PR description is still empty. The author has to write it (CLAUDE.md, PR expectations #2).
Not verified: I didn't run the tests. Step time at the new worker counts hasn't been measured (no GPU run, per the PR).
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
Summary (human-written)
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.Problem
Rollouter.Config.worker_pool_sizesets how many rollout worker processes start. It defaults to 4, and no recipe changes it.Solution
Rollouter.Config.rollouts_per_worker(default 128) replacesworker_pool_size.max_rollouts_in_flight(groups in flight x group size, a newAsyncLoopConfigproperty) to the Rollouter's constructor.Rollouter.setup_asyncstarts ceil(max_rollouts_in_flight/rollouts_per_worker) workers and logs the count.rollouts_per_workerraises 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 < 1now raises too; nothing checked it.choosepicks the worker, at random. Sorollouts_per_workeris the mean load, not a cap. A later PR in this stack picks the least-loaded worker.Also in this PR:
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.rollout_loop_<i>, so "rollout worker" names only the process.Results
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:
MonarchActorSystem.Config.max_rollout_workers_per_host).rollouts_per_worker, so it sizes its own pool. The controller knows the load.freqsteps, so workers sized for it would sit idle between validations. Validation shares the workers, as on main.grainanddatasetspackages. Those load with theVisionProcessorimport, which runstorchtitan/components/data/__init__.py; the renderer andrl/rollout/data.pyimport them too. A TODO at that import says to check whether a worker needs them.NOTE:
VerifiersRollouter.__init__forwardsmax_rollouts_in_flight.Follow up / TODO (each is a
# TODOin the code):InterGeneratorRouter.release_groups.grainanddatasetspackages only where they are used, to save ~450 MiB per rollout worker. First check that a worker doesn't need them.TokenEnv) may queue on the worker's 4 threads. Measure that wait, then size the pool from it.Test plan
New or changed:
test_async_controller.py:test_a_group_larger_than_rollouts_per_worker_raises(withrollouts_per_worker=0too).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-commitpasses.pyreflyskipstorchtitan/rlandtests(project-excludesinpyproject.toml), so it checks none of this PR's files.