Skip to content

[rl] Rollout worker metrics (loop lag, thread-pool lag, RAM), one thread per 4 rollouts, and gc.freeze - #6174

Merged
felipemello1 merged 1 commit into
mainfrom
felipemello1/worker-metrics/1-executor-gc-memory
Nov 24, 2026
Merged

felipemello1 merged 1 commit into
mainfrom
felipemello1/worker-metrics/1-executor-gc-memory

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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_thread call, 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 a gc.freeze() at the end of setup.

With each worker running its Verifiers env, 10.7 s sandbox removals hold all 4 threads before this PR and a render waits (4.3 s added per model call), while this PR's 32 threads start it at once (21 ms), gc.freeze() cuts each full collection from 408-461 ms to 72-120 ms, and new keys show the thread-pool lag, the event-loop lag of the workers and the controller, and each worker's RAM now and at peak.

# before: Rollouter.Config
num_threads_per_worker: int = 4
# after: threads per worker = ceil(rollouts_per_worker / rollouts_per_thread) = 128 / 4 = 32
rollouts_per_thread: int = 4
# new keys, in each training group's metrics
rollout_worker/event_loop_lag_ms, rollout_worker/thread_pool_lag_ms   (Max, and a _per_s Mean for each)
rollout_worker/ram_gib, rollout_worker/peak_ram_gib
# new keys, in each step's metrics
controller/event_loop_lag_ms, controller/event_loop_lag_ms_per_s

Problem

  1. A rollout worker runs about 128 rollouts (rollouts_per_worker) on one event loop. Their asyncio.to_thread calls (renders, parses, blocking env calls) share 4 threads.
  2. No metric shows when the loop or the threads fall behind. Blocking calls that hold every thread leave the loop free, so a loop-lag metric would not show that wait.
  3. On a CPU bench (below), one 10.7 s blocking call per rollout keeps all 4 threads busy 39-55% of the time. The worker then adds 4.3 s to each model call on average, while renders wait for a thread.
  4. A full garbage collection rescans the ~1M objects that imports and setup built: 408-461 ms per collection at 160 rollouts per worker.

Solution

  1. BaseRolloutWorker.setup_async builds the renderer (moved from MessageEnvRolloutWorker, which now inherits it), then calls GarbageCollector.freeze (step 7) and start_process_metrics, which starts the trackers. VerifiersRolloutWorker ends its own setup_async with the same two calls: Verifiers builds its own renderer, so it skips super(). flush_process_metrics returns the worker's keys for each training group. MessageEnvRolloutWorker.run_group and VerifiersRolloutWorker.run_group end by adding them to the group, as the base run_group docstring 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.
  2. EventLoopLag (new, rl/observability/metrics/loop_lag.py): a task sleeps 50 ms and records how late it wakes up.
  3. 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.
  4. ram_gib and peak_ram_gib: RSS now and its peak since the worker started, read from /proc/self/status (VmRSS, VmHWM).
  5. The controller starts an EventLoopLag("controller") after its setup and logs it with each step.
  6. Rollouter.Config.rollouts_per_thread (default 4) replaces num_threads_per_worker: threads per worker = ceil(rollouts_per_worker / rollouts_per_thread), with no cap. Examples: 7 / 4 -> 2 threads, 2 / 4 -> 1.
  7. At the end of setup, each worker calls GarbageCollector.freeze (a full collection, then gc.freeze()), as the controller does.
  8. Unchanged: the worker uses Python's plain 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:

128 rollouts per worker, one 10.7 s blocking removal per rollout
                        model call, added mean / p50 / p99   longest wait for a thread, per worker
  4 threads             4.3 s / 1.2 s / 26.7 s               17-34 s
  32 threads            21 ms / 19 ms / 44 ms                4-18 ms

160 rollouts per worker, no blocking call
full garbage collections, all 6 workers     count   each              total    worst stall
  without gc.freeze()                       4       408-461 ms        1.7 s    421-452 ms
  with gc.freeze()                          18      72-120 ms         1.6 s    81-119 ms

Cost of the metrics (CPU probes on a devserver, synthetic loops):

one ThreadPoolLag check            123-137 us of event-loop CPU, 20 checks per second
one EventLoopLag wake              39-47 us of CPU, 20 per second
RSS read (/proc/self/status)       28-33 us, flat from 0.6 to 24.6 GiB
throughput, probe off/on           440.9 / 440.5 turns/s (1 thread), 423.2 / 422.9 (32 threads), with an earlier, costlier draft of the probe

You may ask:

  • How do I read the two lags? High thread-pool lag with low loop lag: too few threads, so lower rollouts_per_thread. Both high: the GIL or the loop (pure-Python work on threads, a GC). More threads don't help then.
  • Why a probe, and not a timed executor? The worker keeps Python's plain ThreadPoolExecutor, and ThreadPoolLag is built like EventLoopLag. It also sees a pool that never frees: its warning fires while no group returns. Peers: Dropwizard's InstrumentedExecutorService times each job's queue wait, Micrometer and tokio report queue depth, anyio counts waiting tasks. vLLM and SGLang report no thread-pool wait.
  • Why does the thread read the start time? A check sent from the loop would add the loop's own delay: on a probe with 128 rollouts and 0.3% of turns holding the loop 100 ms, a free pool read up to 185 ms. Sent with run_in_executor and timed on the thread, it read 0.3-3 ms (one run 64 ms).
  • Why rollouts_per_thread, and not a thread count? The threads a worker needs grow with its rollouts, so the ratio stays right when rollouts_per_worker changes. Set 1 for an env with one blocking call per rollout.
  • Why no cap? A cap of 32 would block rollouts_per_thread=1 at 128 rollouts per worker. The pool starts a thread only when a call finds the others busy, ~4 MiB each.
  • Why no check between rollouts_per_thread and rollouts_per_worker? Rounding up gives a working pool for every pair. A <= check would make a debug run with rollouts_per_worker=2 also set rollouts_per_thread.
  • Why does each worker call flush_process_metrics at the end of its run_group? run_group is 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.
  • Why only EventLoopLag on 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.
  • Why RSS, and not private memory? RSS reads in 28-33 us at any heap size. smaps_rollup took 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.
  • Why VmHWM for the peak, and not ru_maxrss? On a 6.16 kernel ru_maxrss read 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. VmHWM is never below VmRSS.

NOTE:

  • For Verifiers recipes, the env runs in the env server until [rl] Verifiers: each rollout worker runs its Verifiers env; the env server is gone #6118 moves it into each worker. Until then, these metrics don't see its renders and sandbox calls.
  • A group's worker metrics land on the step that trains it. What a worker measures during validation goes with its next training group.
  • Healthy floors: event_loop_lag_ms_per_s reads ~5-20 ms per second on an idle or light worker (timer rounding), thread_pool_lag_ms_per_s ~3-11 (thread wake-up).
  • On Linux 6.2-6.15 kernels without commit 82241a83cd15, VmRSS can read low on hosts with many CPUs. Not checked on such a kernel.
  • Both lag tasks run on the loop they watch, so a loop that hangs for good shows nothing.
  • Draft [rl] Rollout workers, the router and the controller report their CPU and memory each step #5926 logs process/rollout_worker/rss_anon_gib each step: anonymous memory only, children included. This PR's ram_gib and peak_ram_gib are RSS, shared libraries included, per training group. Don't compare the two. Whichever lands second keeps one set of names.
  • Not run on GPUs.

Test plan

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: 1053 passed, 1 skipped (test_train_loop.py, skipped on main too).
# Without Verifiers: 969 passed, 7 skipped (the Verifiers test files and recipes).

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_metrics calls the worker's setup_async and run_group directly, 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 subclasses BaseRolloutWorker, ends its setup_async with super().setup_async(...), given no-op configs (_NO_OP_CONFIG), and ends its run_group with 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 real MessageEnvRolloutWorker.run_group holds rollout_worker/ram_gib. Watched failing with the flush line removed from that run_group.
  • test_verifiers.py (the worker setup test): after setup_async, flush_process_metrics(group_id=0), which raises AttributeError if setup didn't start the trackers. Watched failing with start_process_metrics() removed from the Verifiers worker.

pre-commit passes. pyrefly skips torchtitan/rl and tests (project-excludes in pyproject.toml).

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

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the 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

  1. PR description -- "Summary (human-written)" is empty. Per CONTRIBUTING, the author writes it.

Should consider

  • rollout_worker.py:124 -- RssAnon from /proc/self/status instead of Pss from smaps_rollup: no page-table walk on the loop, and the same name as #5926's rss_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 -- the num_threads_per_worker docstring 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 because gc_pause_ms is 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-group rss_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, and next(iter(...)) really is the oldest waiting job. A job cancelled before it starts (asyncio task cancellation, shutdown(cancel_futures=True)) never runs record_wait_then_run. Its done callback still pops the key and decrements the count. The base submit runs outside our lock, which avoids the _shutdown_lock -> self._lock ordering 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 a Max.
  • GcPause: one start time is enough, since CPython runs one collection at a time under the GIL. The trainer's GarbageCollector.__init__ calls gc.disable(), but the rollout worker only uses the static freeze, so automatic collection stays on, which is what you want here.
  • Tests: test_executor_queue_wait_counts_a_job_that_has_not_started covers 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.

Comment on lines +124 to +128
# 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),
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Suggested change
# 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),
),

Comment on lines +70 to +74
# 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%.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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

Comment on lines 102 to 114
# 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

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

Comment thread torchtitan/rl/rollout/rollouter.py Outdated
Comment on lines +124 to +140
"""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."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@felipemello1
felipemello1 removed this pull request from stack #6175 November 18, 2026 15:42
@felipemello1
felipemello1 changed the base branch from felipemello1/verifiers-041/1-infra-errors to felipemello1/infra-errors/4-drop-rollout-not-group November 18, 2026 15:42
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from acee469 to 032d4ad Compare November 18, 2026 15:42
@felipemello1
felipemello1 added this pull request to stack #6185 November 18, 2026 15:43
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the 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

  1. 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_gib each step. Should the per-group rss_gib/pss_gib go 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_group comment: resolved. The comment now lists the keys and points to the README.
  • num_threads_per_worker docstring 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, since gc_pause_ms is the metric that shows its effect.

Re-checked at HEAD:

  • QueueWaitThreadPoolExecutor.submit stores the submit time under our lock, then calls the base submit outside it. That avoids the _shutdown_lock -> self._lock ordering problem with shutdown(cancel_futures=True).
  • Insertion order matches submit-time order, and the pool's queue is FIFO. So next(iter(...)) in flush is the oldest waiting job.
  • A job cancelled before it starts never runs record_wait_then_run (_WorkItem.run returns at set_running_or_notify_cancel). Its done callback still uncounts it and drops its key. ThreadPoolExecutor has no _lock attribute of its own, so the subclass's _lock doesn't shadow anything.
  • GcPause relies on the GIL for one collection at a time. The rollout worker only calls the static freeze, so automatic collection stays on, unlike the trainer, whose GarbageCollector.__init__ calls gc.disable().
  • No in-repo recipe sets num_threads_per_worker. The two tests that set it use small values through SimpleNamespace, so the new default reaches every recipe.
  • Tests: test_executor_queue_wait_counts_a_job_that_has_not_started covers the still-waiting path in flush. The worker test covers validation-group carry-over and the freeze call. gc.unfreeze() in finally keeps 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.

@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch 2 times, most recently from 2e2bdab to 7bd18c4 Compare November 18, 2026 19:52
@felipemello1
felipemello1 removed this pull request from stack #6185 November 18, 2026 20:42
@felipemello1
felipemello1 changed the base branch from felipemello1/infra-errors/4-drop-rollout-not-group to felipemello1/infra-errors/3-verifiers-status November 18, 2026 20:43
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 7bd18c4 to 26adc72 Compare November 18, 2026 20:43
@felipemello1
felipemello1 added this pull request to stack #6190 November 18, 2026 20:43
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 26adc72 to 0a3da66 Compare November 18, 2026 21:57
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 0a3da66 to 0388ebd Compare November 19, 2026 00:34
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 0388ebd to b26fa49 Compare November 19, 2026 01:49
@felipemello1
felipemello1 removed this pull request from stack #6190 November 19, 2026 01:49
@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 7s —— View job


Request changes: tianyu-l's first comment is correct (move the metric logic into BaseRolloutWorker), and the second is only partly right (no new check needed, just a clearer docstring). See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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.md says: "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 >= 0 rule for validation groups
    • the /proc/self/status parse
    • the metric keys
  • The author's reply doesn't address this comment.
  • There is a trap in moving it. MessageEnvRolloutWorker (rollouter.py:457,503) and VerifiersRolloutWorker (examples/verifiers/rollouter.py:215,250) override setup_async and run_group, and neither calls super(). Logic placed inside BaseRolloutWorker.run_group would 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 with object.__new__ or reach into Monarch's private endpoint._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 any rollouts_per_thread >= 1, which __post_init__ already enforces, that gives between 1 thread and rollouts_per_worker threads. No value produces a broken pool.
  • rollouts_per_thread > rollouts_per_worker gives 1 thread, which is what the user asked for. Raising here would break a debug run that only lowers rollouts_per_worker to 2, because the default rollouts_per_thread is 4.
  • Divisibility buys nothing. Rounding up only adds threads, so no thread serves more than rollouts_per_thread rollouts. Requiring it would reject reasonable pairs like 100 / 8. It would also be stricter than rollouts_per_worker itself, 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 when rollouts_per_worker changes, 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)

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

@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 04ba8bd to 7066b33 Compare November 22, 2026 09:03
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the 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

  1. 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_worker check (reply on rollouter.py:126). The docstring at rollouter.py:120-123 now 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/status read, and the metric keys. Subclasses override neither: MessageEnvRolloutWorker and VerifiersRolloutWorker only override setup_async / run_group, so the methods reach both stock workers. RolloutWorkerActor is the only host (actors/monarch/system.py:188), so no other adapter misses the calls. The bare annotations in BaseRolloutWorker.__init__ (rollouter.py:351-352) only add types, so a subclass that skips super().__init__() still works.
  • GarbageCollector.freeze stays 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.metrics uses default_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, EventLoopLag is created after the freeze (controller.py:1047) and closed in run()'s finally after the gather (controller.py:1166). _trainer_loop is 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 on BaseRolloutWorker, 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

felipemello1 added a commit that referenced this pull request Nov 23, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Agent details

**TLDR:** The Rollouter now starts one rollout worker per
`rollouts_per_worker` (default 128) training rollouts in flight. Before,
every recipe started 4 workers, whatever its load.

![On main every recipe starts 4 rollout workers, so each worker runs 16
training rollouts for the batch-invariant CI recipes and 384 for
Terminal-Bench 9B, while this PR starts one worker per 128 training
rollouts in flight (1 and 12 workers) and raises for a group over 128
rollouts.](https://raw.githubusercontent.com/felipemello1/pr_images/81b3f3c5472e7afa521015485beada6a8fb24d0f/torchtitan/6112/columns.png)
<!-- pr-image drawn at c7e5aa4 -->

```python
# before: Rollouter.Config
worker_pool_size: int = 4
# after: Rollouter.Config; the Rollouter sizes its pool from the controller's max_rollouts_in_flight
rollouts_per_worker: int = 128
```

**Problem**
1. `Rollouter.Config.worker_pool_size` sets how many rollout worker
processes start. It defaults to 4, and no recipe changes it.
2. Each worker runs all its rollouts on one event loop.
3. So each worker's load follows the recipe: 16 rollouts per worker for
the batch-invariant CI recipes, 384 for Terminal-Bench 9B.

**Solution**
1. `Rollouter.Config.rollouts_per_worker` (default 128) replaces
`worker_pool_size`.
2. The controller passes `max_rollouts_in_flight` (groups in flight x
group size, a new `AsyncLoopConfig` property) to the Rollouter's
constructor. `Rollouter.setup_async` starts
ceil(`max_rollouts_in_flight` / `rollouts_per_worker`) workers and logs
the count.
3. A group runs on one worker. So a group larger than
`rollouts_per_worker` raises when the config is built: only one worker
per group in flight could run a training group at once, and the others
would sit idle. `num_samples_per_prompt < 1` now raises too; nothing
checked it.
4. Unchanged: one mesh on the controller host, and Monarch's `choose`
picks the worker, at random. So `rollouts_per_worker` is the mean load,
not a cap. A later PR in this stack picks the least-loaded worker.

Also in this PR:
- One TODO on `InterGeneratorRouter.release_groups`, which both
group-level release calls use (training loop and validation): evaluate
if that release is needed, since each rollout already releases its
session. It lists the two things only that release does today.
- The controller's per-group asyncio tasks become `rollout_loop_<i>`, so
"rollout worker" names only the process.

**Results**

```text
recipe                          max in flight   workers: main -> this PR   host memory after imports
dapo_math 30B-A3B (x2)                  2,560   4 -> 20                    ~13.9 GiB
SLAKE 816B                              4,096   4 -> 32                    ~22 GiB (on one host until #6157)
Terminal-Bench Qwen3.5-9B               1,536   4 -> 12                    ~8.5 GiB
Terminal-Bench Qwen3.5-35B-A3B          1,280   4 -> 10                    ~7.2 GiB
Search-R1 30B-A3B perf                  1,024   4 -> 8                     ~5.8 GiB
geometry3k (x2)                           512   4 -> 4                     ~3.1 GiB
dapo_math 4B, Verifiers 4B (x4)           640   4 -> 5                     ~3.8 GiB
alphabet_sort, Search-R1, ... (15)    160-256   4 -> 2                     ~1.8 GiB
batch-invariant CI (x3)                    64   4 -> 1                     ~1.1 GiB
DAPO-Math 816B GB300                       64   4 -> 1                     ~1.1 GiB
```

Counts: ceil(`async_loop.max_rollouts_in_flight` / 128) of each built
recipe config. Every recipe uses the default 128; worker counts range
from 1 to 32. Memory: one worker holds 1.13 GiB of RAM after its
imports, but ~0.46 GiB of that is shared library pages, loaded once per
host. So a host's workers take ~0.46 GiB once, plus ~0.67 GiB per
worker; the column above adds both. Main's 4 workers take ~3.1 GiB.
Memory used while running comes on top.

You may ask:
- Why 128? A starting point, not a measured optimum. RL libraries run
2-192 rollouts per worker process for sandbox envs and 320-2,560 for
light search agents; math configs have medians of 72 and 256. 128 starts
half the processes that 64 would. #6174, later in this stack, adds the
worker metrics that check it on real runs.
- Why no CPU cap in the count? The Rollouter runs in the controller's
process, so it sees only that host's CPUs, and #6113 spreads the workers
to hosts it can't see. #6113 also caps the workers per host
(`MonarchActorSystem.Config.max_rollout_workers_per_host`).
- Why does the controller pass the load, not a worker count? The
Rollouter owns `rollouts_per_worker`, so it sizes its own pool. The
controller knows the load.
- Why only training rollouts? Validation comes due every `freq` steps,
so workers sized for it would sit idle between validations. Validation
shares the workers, as on main.
- Where does a worker's memory go? torch 578 MiB, Monarch 84,
transformers 22, and ~450 MiB of the `grain` and `datasets` packages.
Those load with the `VisionProcessor` import, which runs
`torchtitan/components/data/__init__.py`; the renderer and
`rl/rollout/data.py` import them too. A TODO at that import says to
check whether a worker needs them.

NOTE:
- Every worker runs on the controller host until #6157 turns on the
generator hosts by default (#6113 adds the switch): SLAKE's 32 workers
take ~22 GiB there. These PRs should land together.
- `VerifiersRollouter.__init__` forwards `max_rollouts_in_flight`.
- Not run on GPUs.

Follow up / TODO (each is a `# TODO` in the code):
- [ ] Place single rollouts on workers, instead of groups, so there is
less idle time as rollouts finish. This needs a new home for group-level
postprocessing.
- [ ] Evaluate if we need the group-level release in
`InterGeneratorRouter.release_groups`.
- [ ] Load the `grain` and `datasets` packages only where they are used,
to save ~450 MiB per rollout worker. First check that a worker doesn't
need them.
- [ ] At 128 rollouts per worker, renders and parses (`TokenEnv`) may
queue on the worker's 4 threads. Measure that wait, then size the pool
from it.

**Test plan**

```bash
python -m pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config -q
# Verifiers 0.4.0: 1003 passed, 1 skipped (test_train_loop.py, skipped on main too).
# Without Verifiers: 946 passed, 7 skipped (the Verifiers test files and recipes).
```

New or changed:
- `test_async_controller.py`:
`test_a_group_larger_than_rollouts_per_worker_raises` (with
`rollouts_per_worker=0` too).
- `test_rollouter_pool.py`:
`test_setup_spawns_worker_pool_on_controller_host`: 20 training rollouts
in flight / 7 per worker -> 3 workers (a floor would give 2).
- `test_shutdown.py`:
`test_controller_builds_rollouter_with_training_rollouts_in_flight`: the
default config's 32 groups in flight x 8 rollouts reach the Rollouter as
256.

`pre-commit` passes. `pyrefly` skips `torchtitan/rl` and `tests`
(`project-excludes` in `pyproject.toml`), so it checks none of this PR's
files.

Co-authored-by: Felipe Mello <[email protected]>
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch 4 times, most recently from 3037758 to 00cf9db Compare November 23, 2026 19:57
Base automatically changed from felipemello1/infra-errors/4-rollout-filter to main November 23, 2026 19:57
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch 2 times, most recently from d74c926 to 644f1d8 Compare November 23, 2026 20:12
group_size=group_size,
sampling=sampling,
)
group.metrics += self._worker.flush_process_metrics(group_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this is a leftover, which we need to

  • move this to Base and Verifiers RolloutWorker's run_group
  • revert changes in this file

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: 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 group
  • rollout_worker.py now has no diff in this PR. The BaseRolloutWorker.run_group docstring shows these 3 lines.
  • Tests call the worker directly now, with no actor: test_rollout_worker_reports_its_metrics, and a rollout_worker/ram_gib assert on the real run_group in test_rollout_worker.py.

@tianyu-l ready for another look.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 28s —— View job


Request changes: @tianyu-l's latest comment, which asks to move flush_process_metrics into the workers' run_group and revert the actor file, isn't done at 644f1d8, and the human-written summary is still empty. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. PR description: "Summary (human-written)" is still empty, as every earlier automated review noted. Per CONTRIBUTING.md, the author writes it.
  2. torchtitan/rl/actors/monarch/rollout_worker.py:84 -- @tianyu-l's comment is unaddressed. The reply says "run_group is 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 for setup_async: each concrete worker does it itself.
    • At the end of MessageEnvRolloutWorker.run_group (rollouter.py:597) and VerifiersRolloutWorker.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 the BaseRolloutWorker.run_group docstring ("ends with flush_process_metrics"), the same way setup_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. Call worker.setup_async and worker.flush_process_metrics(group_id) on _LoopBlockingWorker directly. That also removes the Monarch-private access an earlier review raised. In test_rollout_worker.py:140, assert that the real run_group's group.metrics holds rollout_worker/ram_gib. That is a stronger check than calling flush_process_metrics before the group, and it guards the new line in MessageEnvRolloutWorker.

Questions

  • @tianyu-l: the rollouts_per_thread <= rollouts_per_worker check (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_async logic 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. MessageEnvRolloutWorker inherits it. VerifiersRolloutWorker.setup_async ends with the freeze and start_process_metrics() (examples/verifiers/rollouter.py:249-253). The actor's setup_async only 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 after await is skipped too, so its lag carries to the worker's next training group.
  • make_scored_group is 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: Renderer in the base setup_async is safe at runtime: rollouter.py has from __future__ import annotations, and Renderer is a TYPE_CHECKING import.
  • 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.
@felipemello1
felipemello1 force-pushed the felipemello1/worker-metrics/1-executor-gc-memory branch from 644f1d8 to 65fc2a5 Compare November 24, 2026 02:15
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the 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

  1. 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_worker check (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 revert rollout_worker.py): resolved.
    • rollout_worker.py is no longer in the diff.
    • The flush now ends MessageEnvRolloutWorker.run_group (rollouter.py:604) and VerifiersRolloutWorker.run_group (examples/verifiers/rollouter.py:291).
    • The base run_group docstring 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.
    • MessageEnvRolloutWorker inherits it.
    • VerifiersRolloutWorker ends its own setup with the freeze and start_process_metrics().
  • Every BaseRolloutWorker subclass is covered.
    • The in-repo subclasses are MessageEnvRolloutWorker, VerifiersRolloutWorker, and the test fakes _CustomWorker and _LoopBlockingWorker.
    • _CustomWorker overrides neither setup_async nor run_group, so test_rollout_worker.py:192 checks the real MessageEnvRolloutWorker path end to end.
    • No other code reads self._renderer from the base class, so moving it there changes nothing.
  • The earlier Monarch-private access is gone.
    • test_rollout_worker_reports_its_metrics now calls setup_async / run_group on a BaseRolloutWorker subclass 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_group that 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, and test_rollout_loop_keeps_the_metrics_a_worker_sent_with_its_group guards it.

Not verified: GPU runs; the bench numbers in the description. A maintainer still needs to review, since this changes the RL rollouter defaults.

@felipemello1
felipemello1 merged commit 40009c0 into main Nov 24, 2026
27 of 28 checks passed
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants