Repository navigation
[rl] Rollout worker metrics (loop lag, thread-pool lag, RAM), one thread per 4 rollouts, and gc.freeze - #6174
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 2m 37s —— View job Approve, with one item to fix before merging (the human-written summary is empty): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- The executor and GC instrumentation is correct, including job cancellation and shutdown, and the bench supports both default changes. The one must-fix item is the empty human summary.
What this PR does. Each rollout worker's default executor becomes a ThreadPoolExecutor subclass that records two things: how long each asyncio.to_thread job waits for a thread, and how many jobs are running or waiting at once. A gc.callbacks hook times each collection. VmRSS and Pss replace ru_maxrss. Two defaults also change: num_threads_per_worker goes from 4 to 32, and setup ends with GarbageCollector.freeze (a full collection, then gc.freeze()), as the controller already does.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking `podman rm --force`
before: 4 threads, all busy 39-55% of the time; the render waits for a thread, so each
model call gets +4.3 s on average. event_loop_lag_ms reads ~0.5 s (a GC pause),
so no metric shows the thread wait.
after: 32 threads -> +21 ms. A training group now carries
executor_queue_wait_ms (17-34 s with 4 threads, 4-18 ms with 32),
num_executor_jobs_in_flight, gc_pause_ms, rss_gib, pss_gib
Must fix
- PR description -- "Summary (human-written)" is empty. Per CONTRIBUTING, the author writes it.
Should consider
rollout_worker.py:124--RssAnonfrom/proc/self/statusinstead ofPssfromsmaps_rollup: no page-table walk on the loop, and the same name as #5926'srss_anon_gib(inline).rollout_worker.py:70-- the comment reports bench numbers; keep only the reason (inline).rollout_worker.py:102-- the metric guide appears three times (comment, README, config docstrings); point to the README (inline).rollouter.py:124-- thenum_threads_per_workerdocstring is mostly bench results; trim it to the sizing rule plus a README pointer (inline).- Scope: the
gc.freeze()default is independent of the metrics and of the thread-count change. It is fine here becausegc_pause_msis the metric that shows it. If a reviewer wants one concern per PR, it is the piece to split out.
Questions
- Draft #5926 adds per-step
process/rollout_worker/rss_anon_gib(children included) next to this PR's per-grouprss_gib/pss_gib. Is the plan for the per-group memory keys to go away once #5926 lands, or are both meant to stay?
Details
QueueWaitThreadPoolExecutor.submit: the submit time is stored under the lock, so the dict's insertion order matches submit-time order, andnext(iter(...))really is the oldest waiting job. A job cancelled before it starts (asyncio task cancellation,shutdown(cancel_futures=True)) never runsrecord_wait_then_run. Its done callback still pops the key and decrements the count. The basesubmitruns outside our lock, which avoids the_shutdown_lock->self._lockordering deadlock that the comment describes. A job still waiting at a flush is reported in that flush, then again with its full wait in the next one. That is harmless for aMax.GcPause: one start time is enough, since CPython runs one collection at a time under the GIL. The trainer'sGarbageCollector.__init__callsgc.disable(), but the rollout worker only uses the staticfreeze, so automatic collection stays on, which is what you want here.- Tests:
test_executor_queue_wait_counts_a_job_that_has_not_startedcovers the still-waiting path, which the worker test doesn't (there, the waiting job finishes before the flush). Each test guards a different path.
Not verified: GPU runs; the cost of smaps_rollup with 4 KiB pages. A maintainer still needs to review, since this changes the RL rollouter defaults.
| # Reading Pss walks the page tables: ~0.6 ms with 64 KiB pages, more with 4 KiB pages. | ||
| m.Metric( | ||
| "rollout_worker/pss_gib", | ||
| m.Max(_read_proc_kib("/proc/self/smaps_rollup", "Pss") / 2**20), | ||
| ), |
There was a problem hiding this comment.
Should consider: RssAnon from /proc/self/status instead of Pss from smaps_rollup. It covers the same question ("what does this worker really cost on the host") because it leaves out the file-backed shared pages (the .so text that RSS counts in every worker). It is in the same file as VmRSS, so it costs nothing extra on the event loop. smaps_rollup walks the page tables on every training group, and you haven't measured that with 4 KiB pages. It also matches the rss_anon_gib name in draft #5926, so whichever PR lands second has nothing to rename. If you switch, the README entry and the pss_gib assert in test_rollouter_pool.py need the same rename.
| # Reading Pss walks the page tables: ~0.6 ms with 64 KiB pages, more with 4 KiB pages. | |
| m.Metric( | |
| "rollout_worker/pss_gib", | |
| m.Max(_read_proc_kib("/proc/self/smaps_rollup", "Pss") / 2**20), | |
| ), | |
| m.Metric( | |
| "rollout_worker/rss_anon_gib", | |
| m.Max(_read_proc_kib("/proc/self/status", "RssAnon") / 2**20), | |
| ), |
| # Setup objects (e.g. modules and the tokenizer) live until exit. Freeze them so full | ||
| # collections skip them (~1M objects). At rollouts_per_worker=160, the longest collection drops | ||
| # from ~0.45 s to ~0.1 s, and full collections run ~4x as often with the same total pause. Near | ||
| # the event loop's limit (256 per worker at 10x Terminal-Bench's call rate), the total pause | ||
| # grew 30-50%. |
There was a problem hiding this comment.
Should consider: this comment reports a one-off bench (160 per worker, 10x Terminal-Bench, +30-50%). Those numbers belong in the PR description and will go stale. The code only needs the reason for the freeze.
| # Setup objects (e.g. modules and the tokenizer) live until exit. Freeze them so full | |
| # collections skip them (~1M objects). At rollouts_per_worker=160, the longest collection drops | |
| # from ~0.45 s to ~0.1 s, and full collections run ~4x as often with the same total pause. Near | |
| # the event loop's limit (256 per worker at 10x Terminal-Bench's call rate), the total pause | |
| # grew 30-50%. | |
| # Setup objects (e.g. modules and the tokenizer) live until exit. Freeze them so full | |
| # collections skip them (~1M objects) and each one stalls the event loop for less time. |
| # Add this worker's metrics to each training group. The first five cover the time since its | ||
| # previous training group. The two memory metrics are read now. What each shows and when to | ||
| # act: "Rollout worker metrics" in `torchtitan/rl/observability/metrics/README.md`. | ||
| # event_loop_lag_ms: the longest time the event loop couldn't run ready work. | ||
| # event_loop_lag_ms_per_s: ms the loop ran late per second, i.e. how busy the loop is. | ||
| # executor_queue_wait_ms: the longest an executor job (an `asyncio.to_thread` call) waited | ||
| # for a free thread. | ||
| # num_executor_jobs_in_flight: the most executor jobs running or waiting at once. | ||
| # gc_pause_ms: the longest garbage collection. | ||
| # rss_gib: this process's memory now, shared libraries included. | ||
| # pss_gib: the same, with each shared page split among the processes that map it. | ||
| # The controller ignores the metrics of validation groups (negative ids), so what is measured | ||
| # during validation goes with this worker's next training group. |
There was a problem hiding this comment.
Should consider: these per-key descriptions are written out three times in this PR: here, in the README's "Rollout worker metrics" section, and in the Rollouter.Config docstrings. The class docstrings of EventLoopLag, GcPause and QueueWaitThreadPoolExecutor add a fourth. The copies will drift apart. Point to the README and keep only the note that is specific to this code, about validation groups:
| # Add this worker's metrics to each training group. The first five cover the time since its | |
| # previous training group. The two memory metrics are read now. What each shows and when to | |
| # act: "Rollout worker metrics" in `torchtitan/rl/observability/metrics/README.md`. | |
| # event_loop_lag_ms: the longest time the event loop couldn't run ready work. | |
| # event_loop_lag_ms_per_s: ms the loop ran late per second, i.e. how busy the loop is. | |
| # executor_queue_wait_ms: the longest an executor job (an `asyncio.to_thread` call) waited | |
| # for a free thread. | |
| # num_executor_jobs_in_flight: the most executor jobs running or waiting at once. | |
| # gc_pause_ms: the longest garbage collection. | |
| # rss_gib: this process's memory now, shared libraries included. | |
| # pss_gib: the same, with each shared page split among the processes that map it. | |
| # The controller ignores the metrics of validation groups (negative ids), so what is measured | |
| # during validation goes with this worker's next training group. | |
| # Add this worker's metrics to each training group ("Rollout worker metrics" in | |
| # `torchtitan/rl/observability/metrics/README.md`). The controller ignores the metrics of | |
| # validation groups (negative ids), so what is measured during validation goes with this | |
| # worker's next training group. |
| """Threads in each worker process's default thread pool, the pool behind every | ||
| `asyncio.to_thread` call in that process. | ||
|
|
||
| All rollouts in the worker share these threads. A blocking call that takes seconds, e.g. a | ||
| slow sandbox removal, holds its thread until it returns. Threads busy on average = blocking | ||
| calls per second x seconds each. Example: rollouts_per_worker=128, each rollout ending with a | ||
| 10.7 s blocking removal, 0.22 removals per second per worker. 0.22 x 10.7 s = 2.4 threads | ||
| busy on average, and bursts fill more: | ||
| 4 threads: all 4 busy 39-55% of the time. The worker added 4.3 s to each model call | ||
| on average (27 s at p99), waiting for a thread. | ||
| 32 threads: it added 21 ms, the same as with no blocking call (~20 ms). | ||
| Leave ~2x headroom for bursts. The pool starts a thread only when a call finds the others busy. | ||
| Each started thread costs ~4 MiB. | ||
| Too few shows in two metrics: `rollout_worker/executor_queue_wait_ms` reads seconds, well above | ||
| `rollout_worker/gc_pause_ms`, and `rollout_worker/num_executor_jobs_in_flight` reads above this | ||
| value. That count includes the jobs waiting for a thread, so the load needed at most this many | ||
| threads: set the threads to about it, then check that the wait drops to tens of ms.""" |
There was a problem hiding this comment.
Should consider: this docstring is 17 lines, and most of them are the bench (4.3 s / 27 s p99 / 21 ms) and the metric guide, which the README already has. A config docstring should say what the field is and how to pick it: the sizing rule (busy threads = blocking calls/s x seconds each, with ~2x headroom), the fact that threads start lazily at ~4 MiB each, and a pointer to executor_queue_wait_ms / num_executor_jobs_in_flight in the README. The bench numbers can live in the PR description.
acee469 to
032d4ad
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 38s —— View job Approve, with one item to fix before merging (the human-written summary is still empty): review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- The force-push (032d4ad) addresses the earlier review's comment and docstring items. The executor and GC instrumentation is still correct. The only open item is the empty human summary.
What this PR does. It makes each rollout worker's default executor a ThreadPoolExecutor subclass. The subclass records how long each asyncio.to_thread job waits for a thread, and the most jobs running or waiting at once. A gc.callbacks hook times each collection. VmRSS and Pss replace ru_maxrss. Two defaults change: num_threads_per_worker goes from 4 to 32, and setup ends with GarbageCollector.freeze, which the controller already does.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking `podman rm --force`
before: 4 threads. The render waits for a free thread, so each model call gets +4.3 s on average.
event_loop_lag_ms reads ~0.5 s (a GC pause), and no metric shows the thread wait.
after: 32 threads -> +21 ms. Each training group carries executor_queue_wait_ms,
num_executor_jobs_in_flight, gc_pause_ms, rss_gib, pss_gib
Must fix
- PR description: "Summary (human-written)" is still empty. Per CONTRIBUTING, the author writes it.
Questions
- Unchanged from last time: draft #5926 logs
process/rollout_worker/rss_anon_gibeach step. Should the per-grouprss_gib/pss_gibgo away when it lands, or should both stay?
Details
What the earlier review's items look like at 032d4ad:
- Bench numbers in the freeze comment (
rollout_worker.py:70): resolved. The comment now gives the reason and the trade-off from CPython's 25% full-collection threshold. - Per-key guide repeated in the
run_groupcomment: resolved. The comment now lists the keys and points to the README. num_threads_per_workerdocstring full of bench results (rollouter.py:121): resolved. It now gives the sizing rule, the headroom, the lazy thread start, and a README pointer.- Pss vs RssAnon: not adopted. The comment now names the page-table walk cost. That was a should-consider, so I'm not raising it again.
- Splitting
gc.freeze()into its own PR: not split. Still fine, sincegc_pause_msis the metric that shows its effect.
Re-checked at HEAD:
QueueWaitThreadPoolExecutor.submitstores the submit time under our lock, then calls the basesubmitoutside it. That avoids the_shutdown_lock->self._lockordering problem withshutdown(cancel_futures=True).- Insertion order matches submit-time order, and the pool's queue is FIFO. So
next(iter(...))influshis the oldest waiting job. - A job cancelled before it starts never runs
record_wait_then_run(_WorkItem.runreturns atset_running_or_notify_cancel). Its done callback still uncounts it and drops its key.ThreadPoolExecutorhas no_lockattribute of its own, so the subclass's_lockdoesn't shadow anything. GcPauserelies on the GIL for one collection at a time. The rollout worker only calls the staticfreeze, so automatic collection stays on, unlike the trainer, whoseGarbageCollector.__init__callsgc.disable().- No in-repo recipe sets
num_threads_per_worker. The two tests that set it use small values throughSimpleNamespace, so the new default reaches every recipe. - Tests:
test_executor_queue_wait_counts_a_job_that_has_not_startedcovers the still-waiting path inflush. The worker test covers validation-group carry-over and the freeze call.gc.unfreeze()infinallykeeps the freeze from leaking into later tests.
Not verified: GPU runs; the cost of smaps_rollup with 4 KiB pages. A maintainer still needs to review, since this changes the RL rollouter defaults.
2e2bdab to
7bd18c4
Compare
7bd18c4 to
26adc72
Compare
26adc72 to
0a3da66
Compare
0a3da66 to
0388ebd
Compare
0388ebd to
b26fa49
Compare
There was a problem hiding this comment.
Verdict: Request changes -- @tianyu-l's first comment is correct: the metric logic belongs in the framework-free worker, not the Monarch actor. Moving it changes the worker's interface and rewrites the worker test, so it needs another look. The second comment is only partly right: no new check is needed, but the docstring should be clearer.
What this PR does. Each rollout worker adds its event-loop lag, its thread-pool lag, and its RSS and peak RSS to each training group. The controller logs its own loop lag each step. rollouts_per_thread=4 replaces num_threads_per_worker=4, and the worker calls gc.freeze() after setup.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking sandbox removal
before: 4 threads. Renders wait for a free thread (+4.3 s per model call), and no metric shows it
after: ceil(128 / 4) = 32 threads (+21 ms). Each training group carries
rollout_worker/{event_loop_lag_ms, thread_pool_lag_ms, ram_gib, peak_ram_gib}
On @tianyu-l's comments
1. "Put the logic in rollouter.py (BaseRolloutWorker) and keep the Monarch actor a thin wrapper": correct.
design.mdsays: "Service cores are plain, framework-free classes; actor/engine wrappers are thin adapters around them."- At HEAD,
RolloutWorkerActor(rollout_worker.py:52-123) owns logic that has nothing to do with Monarch:- when to start the probes
- the
group_id >= 0rule for validation groups - the
/proc/self/statusparse - the metric keys
- The author's reply doesn't address this comment.
- There is a trap in moving it.
MessageEnvRolloutWorker(rollouter.py:457,503) andVerifiersRolloutWorker(examples/verifiers/rollouter.py:215,250) overridesetup_asyncandrun_group, and neither callssuper(). Logic placed insideBaseRolloutWorker.run_groupwould silently disappear from both. Use concrete methods that subclasses don't override instead:# BaseRolloutWorker (one worker per process, so it can own the process metrics) def start_process_metrics(self) -> None: GarbageCollector.freeze("...") # optional: freeze could also stay in the actor self._event_loop_lag = m.EventLoopLag("rollout_worker") self._thread_pool_lag = m.ThreadPoolLag("rollout_worker") def flush_process_metrics(self) -> list[m.Metric]: ... # today's _flush_metrics body # RolloutWorkerActor await self._worker.setup_async(...); self._worker.start_process_metrics() group = await self._worker.run_group(...) if group_id >= 0: group.metrics += self._worker.flush_process_metrics()
- Side benefit:
test_rollout_worker_reports_its_metrics(test_rollouter_pool.py:101-165) can call these methods on a real worker. It would no longer need to construct the actor withobject.__new__or reach into Monarch's privateendpoint._method.__wrapped__, the point raised in the earlier bot review. - Installing the default executor (
rollout_worker.py:45) can stay in the actor. It is per-process setup and was already there before this PR.
2. "Make sure rollouts_per_thread <= rollouts_per_worker, or even divisible": partly correct.
- The thread count is
ceil(rollouts_per_worker / rollouts_per_thread)(rollouter.py:182). For anyrollouts_per_thread >= 1, which__post_init__already enforces, that gives between 1 thread androllouts_per_workerthreads. No value produces a broken pool. rollouts_per_thread > rollouts_per_workergives 1 thread, which is what the user asked for. Raising here would break a debug run that only lowersrollouts_per_workerto 2, because the defaultrollouts_per_threadis 4.- Divisibility buys nothing. Rounding up only adds threads, so no thread serves more than
rollouts_per_threadrollouts. Requiring it would reject reasonable pairs like 100 / 8. It would also be stricter thanrollouts_per_workeritself, which rounds up the worker count the same way (controller.py:591-604). - What is missing is the "at most" meaning in the docstring (
rollouter.py:118-120). Suggested wording: "At most this many rollouts share one thread: threads = ceil(rollouts_per_worker / rollouts_per_thread), e.g. 128/4 -> 32, 7/4 -> 2, 2/4 -> 1." - If the coupling between the two fields still reads as confusing, the alternative is an absolute
num_threads_per_worker: int = 32. It needs no cross-field rule, but it no longer scales whenrollouts_per_workerchanges, which is the PR's stated reason for the ratio. That trade-off is for a maintainer to decide.
Must fix (missed in the review)
- PR description: "Summary (human-written)" is still empty, as the last three automated reviews noted. Per
CONTRIBUTING.md, the author writes it.
Not verified: GPU runs. A maintainer still needs to review, since this changes the RL rollouter defaults.
04ba8bd to
7066b33
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 58s —— View job Approve, with one item to fix before merging (the human-written summary is still empty). @tianyu-l's comment about the thin actor is now resolved: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- 7066b33 resolves @tianyu-l's first comment: the metric logic now lives in BaseRolloutWorker, and the Monarch actor only calls it. The author answered the second comment and is waiting on @tianyu-l. The one open item is still the empty human summary.
What this PR does. Each rollout worker adds its event-loop lag, its thread-pool lag, and its RSS and peak RSS to each training group. The controller logs its own loop lag each step. rollouts_per_thread=4 replaces num_threads_per_worker=4, so a worker gets ceil(rollouts_per_worker / 4) threads. The worker also calls gc.freeze() after setup.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking sandbox removal
before: 4 threads. Renders wait for a free thread (+4.3 s per model call), and no metric shows it
after: ceil(128 / 4) = 32 threads (+21 ms). Each training group carries
rollout_worker/{event_loop_lag_ms, thread_pool_lag_ms, ram_gib, peak_ram_gib}
RolloutWorkerActor.run_group (rollout_worker.py:85-94):
group = await self._worker.run_group(...)
group.metrics += self._worker.flush_process_metrics(group_id) # [] for validation ids
Must fix
- PR description: "Summary (human-written)" is still empty, as all four earlier automated reviews noted. Per
CONTRIBUTING.md, the author writes it.
Questions
- @tianyu-l: the author asks whether you still want a
rollouts_per_thread <= rollouts_per_workercheck (reply onrollouter.py:126). The docstring atrollouter.py:120-123now lists the rounding cases (128/4 -> 32, 7/4 -> 2, 2/4 -> 1). My view hasn't changed: no pair gives a broken pool, so the check isn't needed.
Details
What changed since the last review, checked at 7066b33:
- Maintainer comment 1 (thin actor): resolved.
BaseRolloutWorker.start_process_metrics/flush_process_metrics(rollouter.py:364-396) own the probe start, the validation-id rule, the/proc/self/statusread, and the metric keys. Subclasses override neither:MessageEnvRolloutWorkerandVerifiersRolloutWorkeronly overridesetup_async/run_group, so the methods reach both stock workers.RolloutWorkerActoris the only host (actors/monarch/system.py:188), so no other adapter misses the calls. The bare annotations inBaseRolloutWorker.__init__(rollouter.py:351-352) only add types, so a subclass that skipssuper().__init__()still works. GarbageCollector.freezestays in the actor (rollout_worker.py:67). That is fine: it is per-process setup, like the executor installed in__init__.group.metrics += ...is safe.RolloutGroup.metricsusesdefault_factory=list, and no worker sets group-level metrics today (RolloutGroup(call sites:rollouter.py:468,484,488,controller.py:1303). So the controller's=->+=(controller.py:1292) only changes behavior for the new worker keys.- On the controller,
EventLoopLagis created after the freeze (controller.py:1047) and closed inrun()'sfinallyafter the gather (controller.py:1166)._trainer_loopis the only reader, and it runs only inside that window. - Still declined, not raised again: the worker test reaches into Monarch's private
endpoint._method.__wrapped__(test_rollouter_pool.py:210-211). Now that the logic is onBaseRolloutWorker, the test could call the two methods directly. The author kept the actor path on purpose, so the test also covers the actor's two calls.
Not verified: GPU runs; the bench numbers in the description. A maintainer still needs to review, since this changes the RL rollouter defaults.
There was a problem hiding this comment.
Why new methods, not code inside setup_async / run_group: MessageEnvRolloutWorker and VerifiersRolloutWorker override both without super(), so code there would silently disappear.
It doesn't convince me. I think we should keep monarch actor a thin wrapper, instead of holding logic that could be universal to any ActorSystem.
- move the logic in
MessageEnvRolloutWorkerhttps://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/rollout/rollouter.py#L377-L398 to base class - put the metrics setup also in base class
- if
VerifiersRolloutWorkerneeds to customize thesetup_async, it can handle the metrics setup by itself, or call into super().
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Agent details
**TLDR:** The Rollouter now starts one rollout worker per
`rollouts_per_worker` (default 128) training rollouts in flight. Before,
every recipe started 4 workers, whatever its load.

<!-- pr-image drawn at c7e5aa4 -->
```python
# before: Rollouter.Config
worker_pool_size: int = 4
# after: Rollouter.Config; the Rollouter sizes its pool from the controller's max_rollouts_in_flight
rollouts_per_worker: int = 128
```
**Problem**
1. `Rollouter.Config.worker_pool_size` sets how many rollout worker
processes start. It defaults to 4, and no recipe changes it.
2. Each worker runs all its rollouts on one event loop.
3. So each worker's load follows the recipe: 16 rollouts per worker for
the batch-invariant CI recipes, 384 for Terminal-Bench 9B.
**Solution**
1. `Rollouter.Config.rollouts_per_worker` (default 128) replaces
`worker_pool_size`.
2. The controller passes `max_rollouts_in_flight` (groups in flight x
group size, a new `AsyncLoopConfig` property) to the Rollouter's
constructor. `Rollouter.setup_async` starts
ceil(`max_rollouts_in_flight` / `rollouts_per_worker`) workers and logs
the count.
3. A group runs on one worker. So a group larger than
`rollouts_per_worker` raises when the config is built: only one worker
per group in flight could run a training group at once, and the others
would sit idle. `num_samples_per_prompt < 1` now raises too; nothing
checked it.
4. Unchanged: one mesh on the controller host, and Monarch's `choose`
picks the worker, at random. So `rollouts_per_worker` is the mean load,
not a cap. A later PR in this stack picks the least-loaded worker.
Also in this PR:
- One TODO on `InterGeneratorRouter.release_groups`, which both
group-level release calls use (training loop and validation): evaluate
if that release is needed, since each rollout already releases its
session. It lists the two things only that release does today.
- The controller's per-group asyncio tasks become `rollout_loop_<i>`, so
"rollout worker" names only the process.
**Results**
```text
recipe max in flight workers: main -> this PR host memory after imports
dapo_math 30B-A3B (x2) 2,560 4 -> 20 ~13.9 GiB
SLAKE 816B 4,096 4 -> 32 ~22 GiB (on one host until #6157)
Terminal-Bench Qwen3.5-9B 1,536 4 -> 12 ~8.5 GiB
Terminal-Bench Qwen3.5-35B-A3B 1,280 4 -> 10 ~7.2 GiB
Search-R1 30B-A3B perf 1,024 4 -> 8 ~5.8 GiB
geometry3k (x2) 512 4 -> 4 ~3.1 GiB
dapo_math 4B, Verifiers 4B (x4) 640 4 -> 5 ~3.8 GiB
alphabet_sort, Search-R1, ... (15) 160-256 4 -> 2 ~1.8 GiB
batch-invariant CI (x3) 64 4 -> 1 ~1.1 GiB
DAPO-Math 816B GB300 64 4 -> 1 ~1.1 GiB
```
Counts: ceil(`async_loop.max_rollouts_in_flight` / 128) of each built
recipe config. Every recipe uses the default 128; worker counts range
from 1 to 32. Memory: one worker holds 1.13 GiB of RAM after its
imports, but ~0.46 GiB of that is shared library pages, loaded once per
host. So a host's workers take ~0.46 GiB once, plus ~0.67 GiB per
worker; the column above adds both. Main's 4 workers take ~3.1 GiB.
Memory used while running comes on top.
You may ask:
- Why 128? A starting point, not a measured optimum. RL libraries run
2-192 rollouts per worker process for sandbox envs and 320-2,560 for
light search agents; math configs have medians of 72 and 256. 128 starts
half the processes that 64 would. #6174, later in this stack, adds the
worker metrics that check it on real runs.
- Why no CPU cap in the count? The Rollouter runs in the controller's
process, so it sees only that host's CPUs, and #6113 spreads the workers
to hosts it can't see. #6113 also caps the workers per host
(`MonarchActorSystem.Config.max_rollout_workers_per_host`).
- Why does the controller pass the load, not a worker count? The
Rollouter owns `rollouts_per_worker`, so it sizes its own pool. The
controller knows the load.
- Why only training rollouts? Validation comes due every `freq` steps,
so workers sized for it would sit idle between validations. Validation
shares the workers, as on main.
- Where does a worker's memory go? torch 578 MiB, Monarch 84,
transformers 22, and ~450 MiB of the `grain` and `datasets` packages.
Those load with the `VisionProcessor` import, which runs
`torchtitan/components/data/__init__.py`; the renderer and
`rl/rollout/data.py` import them too. A TODO at that import says to
check whether a worker needs them.
NOTE:
- Every worker runs on the controller host until #6157 turns on the
generator hosts by default (#6113 adds the switch): SLAKE's 32 workers
take ~22 GiB there. These PRs should land together.
- `VerifiersRollouter.__init__` forwards `max_rollouts_in_flight`.
- Not run on GPUs.
Follow up / TODO (each is a `# TODO` in the code):
- [ ] Place single rollouts on workers, instead of groups, so there is
less idle time as rollouts finish. This needs a new home for group-level
postprocessing.
- [ ] Evaluate if we need the group-level release in
`InterGeneratorRouter.release_groups`.
- [ ] Load the `grain` and `datasets` packages only where they are used,
to save ~450 MiB per rollout worker. First check that a worker doesn't
need them.
- [ ] At 128 rollouts per worker, renders and parses (`TokenEnv`) may
queue on the worker's 4 threads. Measure that wait, then size the pool
from it.
**Test plan**
```bash
python -m pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config -q
# Verifiers 0.4.0: 1003 passed, 1 skipped (test_train_loop.py, skipped on main too).
# Without Verifiers: 946 passed, 7 skipped (the Verifiers test files and recipes).
```
New or changed:
- `test_async_controller.py`:
`test_a_group_larger_than_rollouts_per_worker_raises` (with
`rollouts_per_worker=0` too).
- `test_rollouter_pool.py`:
`test_setup_spawns_worker_pool_on_controller_host`: 20 training rollouts
in flight / 7 per worker -> 3 workers (a floor would give 2).
- `test_shutdown.py`:
`test_controller_builds_rollouter_with_training_rollouts_in_flight`: the
default config's 32 groups in flight x 8 rollouts reach the Rollouter as
256.
`pre-commit` passes. `pyrefly` skips `torchtitan/rl` and `tests`
(`project-excludes` in `pyproject.toml`), so it checks none of this PR's
files.
Co-authored-by: Felipe Mello <[email protected]>
3037758 to
00cf9db
Compare
d74c926 to
644f1d8
Compare
| group_size=group_size, | ||
| sampling=sampling, | ||
| ) | ||
| group.metrics += self._worker.flush_process_metrics(group_id) |
There was a problem hiding this comment.
this is a leftover, which we need to
- move this to Base and Verifiers RolloutWorker's
run_group - revert changes in this file
There was a problem hiding this comment.
Reply from claude: Done in 65fc2a5.
My reply in the other thread crossed with this comment, so its point about the actor keeping the flush no longer holds.
# before: RolloutWorkerActor.run_group
group = await self._worker.run_group(...)
group.metrics += self._worker.flush_process_metrics(group_id)
return group
# after: RolloutWorkerActor.run_group is main's again
return await self._worker.run_group(...)
# after: MessageEnvRolloutWorker.run_group ends with (VerifiersRolloutWorker.run_group the same)
group = await self.make_scored_group(
rollouts=[task.result() for task in tasks], sample=sample, group_id=group_id
)
group.metrics += self.flush_process_metrics(group_id)
return grouprollout_worker.pynow has no diff in this PR. TheBaseRolloutWorker.run_groupdocstring shows these 3 lines.- Tests call the worker directly now, with no actor:
test_rollout_worker_reports_its_metrics, and arollout_worker/ram_gibassert on the realrun_groupintest_rollout_worker.py.
@tianyu-l ready for another look.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 28s —— View job Request changes: @tianyu-l's latest comment, which asks to move |
There was a problem hiding this comment.
Verdict: Request changes -- @tianyu-l's latest comment (rollout_worker.py:84: "move this to Base and Verifiers RolloutWorker's run_group, revert changes in this file") is not done at HEAD 644f1d8. The author's reply argues against it, and the maintainer's change request still stands. The fix is small, but it also rewrites the main worker test, so it needs another look.
What this PR does. Each rollout worker adds its event-loop lag, its thread-pool lag, and its RSS and peak RSS to each training group. The controller logs its own loop lag each step. rollouts_per_thread=4 replaces num_threads_per_worker=4. Since 644f1d8, BaseRolloutWorker.setup_async builds the renderer, calls gc.freeze(), and starts the trackers. VerifiersRolloutWorker does the last two steps itself.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking sandbox removal
before: 4 threads. Renders wait for a free thread (+4.3 s per model call), and no metric shows it
after: ceil(128 / 4) = 32 threads (+21 ms). Each training group carries
rollout_worker/{event_loop_lag_ms, thread_pool_lag_ms, ram_gib, peak_ram_gib}
RolloutWorkerActor.run_group at HEAD (rollout_worker.py:76-85), the one line still in the actor:
group = await self._worker.run_group(...)
group.metrics += self._worker.flush_process_metrics(group_id)
Must fix
- PR description: "Summary (human-written)" is still empty, as every earlier automated review noted. Per
CONTRIBUTING.md, the author writes it. torchtitan/rl/actors/monarch/rollout_worker.py:84-- @tianyu-l's comment is unaddressed. The reply says "run_groupis abstract, so the base class has no place to run code after it". That is true, but it isn't what was asked. The ask matches the pattern this PR already uses forsetup_async: each concrete worker does it itself.- At the end of
MessageEnvRolloutWorker.run_group(rollouter.py:597) andVerifiersRolloutWorker.run_group(examples/verifiers/rollouter.py:288):group = await self.make_scored_group(rollouts=..., sample=sample, group_id=group_id) group.metrics += self.flush_process_metrics(group_id) return group
- Then revert
rollout_worker.py, so the PR leaves it untouched. Note this in theBaseRolloutWorker.run_groupdocstring ("ends withflush_process_metrics"), the same waysetup_async's docstring describes steps 2 and 3. - Test follow-up:
test_rollout_worker_reports_its_metrics(test_rollouter_pool.py:206-275) now goes through the actor endpoint bodies (_method.__wrapped__) to reach the flush. After the move, the actor no longer flushes, so that path tests nothing. Callworker.setup_asyncandworker.flush_process_metrics(group_id)on_LoopBlockingWorkerdirectly. That also removes the Monarch-private access an earlier review raised. Intest_rollout_worker.py:140, assert that the realrun_group'sgroup.metricsholdsrollout_worker/ram_gib. That is a stronger check than callingflush_process_metricsbefore the group, and it guards the new line inMessageEnvRolloutWorker.
- At the end of
Questions
- @tianyu-l: the
rollouts_per_thread <= rollouts_per_workercheck (rollouter.py:127) is still waiting on your answer. The docstring now lists the rounding cases. My view hasn't changed: every pair gives a working pool, so the check isn't needed.
Details
Checked at 644f1d8:
- @tianyu-l's 11-23 comment (move the
MessageEnvRolloutWorker.setup_asynclogic and the metrics setup to the base class, and let Verifiers handle its own): done.BaseRolloutWorker.setup_async(rollouter.py:355-388) builds the renderer, freezes, and starts the trackers.MessageEnvRolloutWorkerinherits it.VerifiersRolloutWorker.setup_asyncends with the freeze andstart_process_metrics()(examples/verifiers/rollouter.py:249-253). The actor'ssetup_asynconly forwards. - With the flush inside
run_group, a group that raises skips the flush. That is the same as today, where the actor's line afterawaitis skipped too, so its lag carries to the worker's next training group. make_scored_groupis the one concrete method both workers end on, so the flush could go there with no subclass edits. That mixes a process metric into scoring, and it would hide the call from a third worker that doesn't use it. The two explicit lines are the clearer option, and they are what the maintainer asked for.self._renderer: Rendererin the basesetup_asyncis safe at runtime:rollouter.pyhasfrom __future__ import annotations, andRendereris aTYPE_CHECKINGimport.- No in-repo file outside tests still names
num_threads_per_worker.
Not verified: GPU runs; the bench numbers in the description. A maintainer still needs to review, since this changes the RL rollouter defaults.
…ead per 4 rollouts, and gc.freeze Each rollout worker adds its metrics to each training group it returns, through BaseRolloutWorker.flush_process_metrics: rollout_worker/event_loop_lag_ms (Max) and _per_s (Mean), rollout_worker/thread_pool_lag_ms (Max) and _per_s (Mean), rollout_worker/ram_gib (VmRSS, now) and rollout_worker/peak_ram_gib (VmHWM, the most since start), from /proc/self/status. BaseRolloutWorker.setup_async (moved from MessageEnvRolloutWorker) builds the renderer, then calls GarbageCollector.freeze (as the controller does) and starts the metrics. VerifiersRolloutWorker ends its own setup_async the same way. MessageEnvRolloutWorker.run_group and VerifiersRolloutWorker.run_group end with flush_process_metrics. The Monarch actor doesn't change. The controller keeps the worker's metrics on the group, and logs its own controller/event_loop_lag_ms and _per_s with each step. EventLoopLag and ThreadPoolLag live in observability/metrics/loop_lag.py. ThreadPoolLag sends an empty call to the default thread pool every 50 ms and records how late a thread starts it. A call that waits 60 s logs a warning. Rollouter.Config.rollouts_per_thread (default 4) replaces num_threads_per_worker (default 4): each worker starts ceil(rollouts_per_worker / rollouts_per_thread) threads, 32 by default.
644f1d8 to
65fc2a5
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 11s —— View job Approve, with one item to fix before merging (the human-written summary is still empty). @tianyu-l's comments about the thin actor are now resolved at 65fc2a5: review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- 65fc2a5 does what @tianyu-l asked on rollout_worker.py: each worker's run_group now flushes the metrics, and the PR no longer touches the Monarch actor. One item is still open: the human-written summary is empty.
What this PR does. Each rollout worker adds four metrics to each training group: its event-loop lag, its thread-pool lag, its RSS, and its peak RSS. The controller logs its own loop lag each step. rollouts_per_thread=4 replaces num_threads_per_worker=4. BaseRolloutWorker.setup_async now builds the renderer, calls gc.freeze(), and starts the trackers. VerifiersRolloutWorker does the last two steps itself.
Example.
rollouts_per_worker=128, each rollout ends with a 10.7 s blocking sandbox removal
before: 4 threads. Renders wait for a free thread (+4.3 s per model call), and no metric shows it
after: ceil(128 / 4) = 32 threads (+21 ms). Each training group carries
rollout_worker/{event_loop_lag_ms, thread_pool_lag_ms, ram_gib, peak_ram_gib}
MessageEnvRolloutWorker.run_group / VerifiersRolloutWorker.run_group (end):
group = await self.make_scored_group(...)
group.metrics += self.flush_process_metrics(group_id) # [] for validation ids
return group
Must fix
- PR description: "Summary (human-written)" is still empty, as every earlier automated review noted. Per
CONTRIBUTING.md, the author writes it.
Questions
- @tianyu-l: your 11-23 change request asked for three things, and all three are done at 65fc2a5 (details below). You may want to dismiss or update it. The
rollouts_per_thread <= rollouts_per_workercheck (rollouter.py:127) is still waiting on your answer. The docstring now lists the rounding cases (128/4 -> 32, 7/4 -> 2, 2/4 -> 1), and every pair gives a working pool.
Details
What I checked at 65fc2a5:
- @tianyu-l's 11-24 comment (move the flush into the Base and Verifiers workers'
run_group, and revertrollout_worker.py): resolved.rollout_worker.pyis no longer in the diff.- The flush now ends
MessageEnvRolloutWorker.run_group(rollouter.py:604) andVerifiersRolloutWorker.run_group(examples/verifiers/rollouter.py:291). - The base
run_groupdocstring shows the pattern (rollouter.py:450-454).
- @tianyu-l's 11-23 comment (move the setup logic into the base class, and let Verifiers handle its own setup): resolved.
BaseRolloutWorker.setup_async(rollouter.py:355-388) builds the renderer, freezes, and starts the trackers.MessageEnvRolloutWorkerinherits it.VerifiersRolloutWorkerends its own setup with the freeze andstart_process_metrics().
- Every
BaseRolloutWorkersubclass is covered.- The in-repo subclasses are
MessageEnvRolloutWorker,VerifiersRolloutWorker, and the test fakes_CustomWorkerand_LoopBlockingWorker. _CustomWorkeroverrides neithersetup_asyncnorrun_group, sotest_rollout_worker.py:192checks the realMessageEnvRolloutWorkerpath end to end.- No other code reads
self._rendererfrom the base class, so moving it there changes nothing.
- The in-repo subclasses are
- The earlier Monarch-private access is gone.
test_rollout_worker_reports_its_metricsnow callssetup_async/run_groupon aBaseRolloutWorkersubclass directly, so it no longer uses_method.__wrapped__.- It still covers the three cases: setup is not counted, a validation group gets no metrics and its waits carry over to the next training group, and the freeze runs.
- A
run_groupthat raises skips the flush. The trackers aren't reset, so that time counts in the worker's next training group. This is the same behavior as when the actor did the flush. - No file outside the tests still names
num_threads_per_worker. The controller's=->+=change (controller.py:1292) is still what lets the worker keys reach the step, andtest_rollout_loop_keeps_the_metrics_a_worker_sent_with_its_groupguards it.
Not verified: GPU runs; the bench numbers in the description. A maintainer still needs to review, since this changes the RL rollouter defaults.
…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: Each rollout worker now adds its metrics to each training group it returns: how late its event loop runs ready work, how late its thread pool starts an
asyncio.to_threadcall, and its RAM (now and peak). The controller logs its own event-loop lag each step. Two worker defaults change with what a CPU bench showed: one thread per 4 rollouts (32 threads at 128 rollouts per worker, was 4), and agc.freeze()at the end of setup.Problem
rollouts_per_worker) on one event loop. Theirasyncio.to_threadcalls (renders, parses, blocking env calls) share 4 threads.Solution
BaseRolloutWorker.setup_asyncbuilds the renderer (moved fromMessageEnvRolloutWorker, which now inherits it), then callsGarbageCollector.freeze(step 7) andstart_process_metrics, which starts the trackers.VerifiersRolloutWorkerends its ownsetup_asyncwith the same two calls: Verifiers builds its own renderer, so it skipssuper().flush_process_metricsreturns the worker's keys for each training group.MessageEnvRolloutWorker.run_groupandVerifiersRolloutWorker.run_groupend by adding them to the group, as the baserun_groupdocstring shows. The controller now adds its rollout metrics to the group's metrics instead of replacing them, so the worker's keys reach the step that trains the group.EventLoopLag(new,rl/observability/metrics/loop_lag.py): a task sleeps 50 ms and records how late it wakes up.ThreadPoolLag(new, same file): every 50 ms it sends an empty call to the default thread pool, and the thread records when it starts. A flush during a wait counts the wait so far. A call that waits 60 s logs a warning, because a stuck pool may stop every group, and with it the metrics.ram_gibandpeak_ram_gib: RSS now and its peak since the worker started, read from/proc/self/status(VmRSS,VmHWM).EventLoopLag("controller")after its setup and logs it with each step.Rollouter.Config.rollouts_per_thread(default 4) replacesnum_threads_per_worker: threads per worker = ceil(rollouts_per_worker/rollouts_per_thread), with no cap. Examples: 7 / 4 -> 2 threads, 2 / 4 -> 1.GarbageCollector.freeze(a full collection, thengc.freeze()), as the controller does.ThreadPoolExecutor. The generator, batcher and trainer get no new metric.Results
A CPU bench: real TitanRL rollout workers with the rest of this stack applied (from #6118, each runs its Verifiers env), replaying recorded Terminal-Bench rollouts against fake generators, 6 workers, 300 s windows, one run each:
Cost of the metrics (CPU probes on a devserver, synthetic loops):
You may ask:
rollouts_per_thread. Both high: the GIL or the loop (pure-Python work on threads, a GC). More threads don't help then.ThreadPoolExecutor, andThreadPoolLagis built likeEventLoopLag. It also sees a pool that never frees: its warning fires while no group returns. Peers: Dropwizard'sInstrumentedExecutorServicetimes each job's queue wait, Micrometer and tokio report queue depth, anyio counts waiting tasks. vLLM and SGLang report no thread-pool wait.run_in_executorand timed on the thread, it read 0.3-3 ms (one run 64 ms).rollouts_per_thread, and not a thread count? The threads a worker needs grow with its rollouts, so the ratio stays right whenrollouts_per_workerchanges. Set 1 for an env with one blocking call per rollout.rollouts_per_thread=1at 128 rollouts per worker. The pool starts a thread only when a call finds the others busy, ~4 MiB each.rollouts_per_threadandrollouts_per_worker? Rounding up gives a working pool for every pair. A<=check would make a debug run withrollouts_per_worker=2also setrollouts_per_thread.flush_process_metricsat the end of itsrun_group?run_groupis abstract, so the base class has no place to run code after it. The Monarch actor only forwards calls, so another actor system gets the keys too.EventLoopLagon the controller? Its thread pool runs at most two calls at once (one dataset read, one validation), so it can't fill. The generator, batcher and trainer hold their loops by design (engine steps, batching, forward and backward), so a loop lag there reads their work.smaps_rolluptook 15-18 ms per read at 24.6 GiB, on the event loop. RSS counts shared libraries in full, so a sum over workers overcounts.VmHWMfor the peak, and notru_maxrss? On a 6.16 kernelru_maxrssread below the RSS (2,034 vs 2,059 MiB while 2 GiB was held), so a dashboard could show a peak under the current value.VmHWMis never belowVmRSS.NOTE:
event_loop_lag_ms_per_sreads ~5-20 ms per second on an idle or light worker (timer rounding),thread_pool_lag_ms_per_s~3-11 (thread wake-up).VmRSScan read low on hosts with many CPUs. Not checked on such a kernel.process/rollout_worker/rss_anon_gibeach step: anonymous memory only, children included. This PR'sram_gibandpeak_ram_gibare RSS, shared libraries included, per training group. Don't compare the two. Whichever lands second keeps one set of names.Test plan
New or changed:
test_metrics.py:test_event_loop_lag_measures_a_blocked_loop(a 0.3 s block reads at least 250 ms in Max and in the per-second Mean, and the next flush starts over).test_thread_pool_lag_counts_a_stuck_pool(one thread held: a flush reads the waiting check's wait so far, at least 200 ms, and the warning logs).test_rollouter_pool.py:test_rollout_worker_reports_its_metricscalls the worker'ssetup_asyncandrun_groupdirectly, with a 1-thread default executor. Setup's 0.3 s hold is not counted. Setup yields first, so trackers started before setup would count it. A validation group that holds the loop, then the thread, for 0.3 s each gets no metrics. The next training group reads both waits (at least 250 ms) and the RAM keys. Setup raises the freeze count. Its fake worker subclassesBaseRolloutWorker, ends itssetup_asyncwithsuper().setup_async(...), given no-op configs (_NO_OP_CONFIG), and ends itsrun_groupwith the flush, as a real worker does.test_setup_spawns_worker_pool_on_controller_host: 7 rollouts per worker / 4 per thread -> 2 threads.test_async_controller.py:test_rollout_loop_keeps_the_metrics_a_worker_sent_with_its_group.test_rollout_worker.py(test_worker_executes_group_without_actor_mesh): the group from the realMessageEnvRolloutWorker.run_groupholdsrollout_worker/ram_gib. Watched failing with the flush line removed from thatrun_group.test_verifiers.py(the worker setup test): aftersetup_async,flush_process_metrics(group_id=0), which raisesAttributeErrorif setup didn't start the trackers. Watched failing withstart_process_metrics()removed from the Verifiers worker.pre-commitpasses.pyreflyskipstorchtitan/rlandtests(project-excludesinpyproject.toml).