Skip to content

[rl] Rollout workers get generate_fn and release_session_fn once, at setup; the rollouter closes each worker before it stops them - #6099

Draft
felipemello1 wants to merge 1 commit into
felipemello1/rollout-placement/1-worker-handlesfrom
felipemello1/rollout-workers/1-setup-and-close
Draft

felipemello1 wants to merge 1 commit into
felipemello1/rollout-placement/1-worker-handlesfrom
felipemello1/rollout-workers/1-setup-and-close

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Before we would pass to every group the generate_fn and release_session_fn. This is unnecessary. We can set it once per worker instead and simplify the call and avoid resetting it every time.

Agent details

TLDR: A rollout worker gets its two generator functions once, in setup_async, instead of with every group. At shutdown, the rollouter calls each worker's close before it stops the processes.

main:     setup_async(tokenizer, renderer, ...);   run_group(generate_fn, release_session_fn, sample, ...)
this PR:  setup_async(generate_fn, release_session_fn, tokenizer, renderer, ...);   run_group(sample, ...)
shutdown: drain the run_group calls -> worker.close() on each, through an endpoint -> stop_rollout_workers()
          each close that raises or runs past 60 s -> logged by worker; stop_rollout_workers() still runs

Stack (15 PRs, bottom first; merging a PR also merges every PR below it; this PR in bold)

# PR What
1 Run Verifiers groups in rollout workers Verifiers groups run in rollout workers; the env server stays
2 Rollouts that fail outside the policy are recorded, not trained a failed rollout no longer drops its group
3 Rollouter: least-loaded placement; the controller sizes the pool from rollouts_per_worker least-loaded placement; the pool size follows the rollouts in flight
4 Rollout workers get generate_fn and release_session_fn once, at setup; the rollouter closes each worker before it stops them generator functions at setup; workers close before they stop
5 Verifiers: each example is an installed package; its name is the taskset id taskset ids are package names
6 Verifiers: each rollout worker runs its Verifiers envs; the env server is gone the env runs in the worker (Verifiers 0.4.0)
7 Verifiers: the generation server keeps one session per trace sessions; 1 GiB requests; the renderer refuses overlong prompts
8 Verifiers 0.4.1 and renderers 0.2.0 both pins move
9 Verifiers: only a rollout that Verifiers finished cleanly trains the failure rule
10 Verifiers README: terms, concurrency and sandboxes README only: terms, concurrency, sandboxes
11 Verifiers: time each rollout's sandbox start, setup, agent, model, finalize and scoring per-phase time metrics
12 Terminal-Bench: terminal_bench_env_config takes the package that exports the taskset a package argument for launchers outside the repo
13 Spread rollout workers over the job's hosts opt-in: rollout workers on the other hosts
14 Terminal-Bench: run each task in its image's WORKDIR and grade with task.toml timeouts Terminal-Bench task fixes
15 Rollout workers, the router and the controller report their CPU and memory each step per-role CPU and memory metrics

Alone on main, not in this stack: "Validation reads each prompt at most once; ValidationConfig.steps defaults to -1" and "Terminal-Bench 35B-A3B recipe: Dist-MoE in both roles, FULL CUDA graph generators, DAPO loss".

Problem

  1. The controller builds one generate_fn and one release_session_fn and passes the same two with every group.
  2. A worker that serves them over HTTP must swap its server's function on every group.
  3. A worker that owns sandboxes needs seconds to stop them at shutdown.
  4. Monarch cancels an actor's __cleanup__ after 3 s and fails the job: the controller exits 130.

Solution

  1. BaseRolloutWorker.setup_async takes both functions, documented in its Args; run_group loses them.
  2. BaseRolloutWorker.close() frees what setup_async started. It frees only what is still up, and returns at once when nothing is: a close can come twice, before setup ends, or during another close.
  3. The worker actor exposes close as an endpoint. Rollouter.close drains, calls each worker's close, then stops the processes. __cleanup__ calls the same close, for a worker the rollouter didn't close (an error). Each worker's close that raises, or still runs after 60 s (_WORKER_CLOSE_TIMEOUT_S), is logged with the worker's index, and the processes stop in a finally anyway.
  4. The controller's release_session logs a failed release and returns: the router evicts a session nobody released, so a failure isn't fatal.
  5. The Verifiers worker (PR 1) takes both functions at setup and sets its server's function once. It has nothing to close: its env client and server stop with its process, as before.
  6. Unchanged: what each function does. The MessageEnv worker has nothing to close.

Results

one actor whose close takes N s, stopped two ways (CPU, real Monarch)
stop() alone, N = 0, 1, 2 s           exit 0
stop() alone, N = 5 s                 exit 130: "cleanup error: deadline has elapsed"
close endpoint, then stop(), N = 5 s  exit 0, in 7.5 s

NOTE: BC-breaking for custom rollout workers: both functions now arrive in setup_async.

TODOs in this PR: none.

Test plan

pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config
# 972 passed, 1 skipped, 14 warnings

test_spawn_rollout_workers_returns_one_handle_per_worker closes 2 of 5 real Monarch workers by endpoint, then stops all 5; each worker closes. New: test_each_worker_close_that_fails_or_hangs_is_logged_and_the_workers_still_stop (one worker hangs, another raises; both are logged).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 15, 2026
@felipemello1
felipemello1 added this pull request to stack #6101 November 15, 2026 08:43
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 20s —— View job


Approve, with items to address before merging -- see the review. A maintainer still needs to 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 controller now hands both functions to the workers once, and shutdown closes each worker before it stops them. The change is local to RL and doesn't touch numerics. This touches RL core (Rollouter, Controller), so a maintainer still needs to review.

What this PR does. generate_fn and release_session_fn now go into BaseRolloutWorker.setup_async (and Rollouter.setup_async), not into every run_group call. Workers get a close() method, and the Monarch actor exposes it as an endpoint. Rollouter.close now runs three steps: drain the in-flight calls, call each worker's close (60 s timeout, failures logged), then stop_rollout_workers() in a finally. __cleanup__ calls close again as a backstop. Catching a failed session release moves from the worker into the controller's release_session closure.

Example.

before: controller.run -> _rollout_loop(generate_fn, release_session_fn)
          -> rollouter.run_group_rollouts(generate_fn, release_session_fn, sample, ...)
          -> worker.run_group(generate_fn, release_session_fn, ...)   # both fns pickled with every group
        VerifiersRollouter: set_generate_fn(generate_fn) on every group
after:  controller.setup_async -> rollouter.setup_async(generate_fn, release_session_fn, ...)  # once
        _rollout_loop -> run_group_rollouts(sample, ...) -> worker.run_group(sample, ...)
shutdown: drain -> worker.close.call_one() x N (<= 60 s) -> stop_rollout_workers()

Must fix

  1. The PR description: "Summary (human-written)" is empty. The author needs to fill it in.

Should consider

  • torchtitan/rl/examples/verifiers/rollouter.py:342 -- a second try/except around release is still here, though ReleaseSessionFn now says the fn never raises. Delete it and its test (inline).

  • torchtitan/rl/rollout/rollouter.py:244 -- when one close hangs, the timeout cancels the whole gather, so a different worker's failed close goes unlogged and the hung worker isn't named. Use asyncio.wait like the drain step just above (inline).

  • torchtitan/rl/rollout/rollouter.py:757 -- the close() contract ("the second call must return at once") doesn't cover two cases that can happen:

    • __cleanup__ calls close on a worker whose setup_async never ran or failed.
    • After the 60 s timeout, __cleanup__ calls close while the first call is still running.

    Say both are allowed, so the Verifiers worker coming in #5 handles them.

Questions

  • In this PR, nothing in the repo overrides close: MessageEnvRolloutWorker has nothing to close. The endpoint, __cleanup__, _WORKER_CLOSE_TIMEOUT_S and the new tests are for the sandbox-owning worker that arrives in #5. That's fine if the stack lands together. If #3 might merge without #5, should the close half move into #5?
Details
  • Ordering: the controller assigns generator_router (controller.py:829) before it calls _rollouter.setup_async (:858). So the closures built once at setup capture the live router, just as the per-loop closures did before.
  • Release robustness: MessageEnvRolloutWorker._run_single_rollout now awaits release_session_fn with no try/except (rollouter.py:699). A custom fn that raises would now fail a rollout that had finished. The only in-repo fn catches its own errors, and the Protocol docstring now states that rule, so this is fine as a contract. It's why the Verifiers copy should go.
  • asyncio.timeout needs Python 3.11+. pyproject.toml requires >=3.11, and token_env.py already uses it.
  • The tests assign worker._generate_fn directly so they don't have to call setup_async. That's acceptable in unit tests.

Not verified: the Monarch __cleanup__ 3 s deadline and the exit-130 behavior. I'm relying on the measurements in the PR description.

Comment thread torchtitan/rl/rollout/rollouter.py Outdated
Comment on lines +244 to +259
try:
async with asyncio.timeout(_WORKER_CLOSE_TIMEOUT_S):
close_results = await asyncio.gather(
*(worker.close.call_one() for worker in workers),
return_exceptions=True,
)
for worker_index, result in enumerate(close_results):
if isinstance(result, BaseException):
logger.error(
"Rollout worker %d close failed", worker_index, exc_info=result
)
except TimeoutError:
logger.error(
"Rollout worker closes still running after %.0f s; stopping the workers",
_WORKER_CLOSE_TIMEOUT_S,
)

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.

If one worker's close hangs, asyncio.timeout cancels the whole gather. Two things are lost:

  • The log doesn't say which worker hung.
  • A different worker's close that raised is never logged, because the loop over close_results doesn't run.

The drain step just above (lines 233-243) already handles the same situation with asyncio.wait(..., timeout=...). Using that here too would make the two steps match, and you could log every failed or still-running worker by index, for about the same LoC:

close_calls = [asyncio.ensure_future(w.close.call_one()) for w in workers]
try:
    if close_calls:
        await asyncio.wait(close_calls, timeout=_WORKER_CLOSE_TIMEOUT_S)
    for worker_index, call in enumerate(close_calls):
        if not call.done():
            logger.error("Rollout worker %d close still running after %.0f s", worker_index, _WORKER_CLOSE_TIMEOUT_S)
            call.cancel()
        elif call.exception() is not None:
            logger.error("Rollout worker %d close failed", worker_index, exc_info=call.exception())
finally:
    if actor_system is not None:
        await actor_system.stop_rollout_workers()

If you make this change, update the hangs case in test_a_worker_close_that_fails_is_logged_and_the_workers_still_stop to check the new message.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Fixed: closing the workers uses asyncio.wait, like the drain step above it.

@felipemello1
felipemello1 removed this pull request from stack #6101 November 15, 2026 21:43
@felipemello1
felipemello1 force-pushed the felipemello1/rollout-placement/1-worker-handles branch from 862ebd5 to cae7807 Compare November 15, 2026 21:43
@felipemello1
felipemello1 force-pushed the felipemello1/rollout-workers/1-setup-and-close branch from ab51e2b to 92754eb Compare November 15, 2026 21:43
@felipemello1
felipemello1 added this pull request to stack #6109 November 15, 2026 21:44
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: answers to the points in the review that have no inline thread.

the review bot (review): torchtitan/rl/examples/verifiers/rollouter.py:342 -- a second try/except around release is still here, though ReleaseSessionFn now says the fn never raises. Delete it and its test (inline).

Removed, with the failure half of its test (now test_rollout_releases_every_trace_session). "Verifiers: each rollout worker runs its Verifiers envs; the env server is gone" rewrites this file and has no second try/except.

the review bot (review): torchtitan/rl/rollout/rollouter.py:757 -- the close() contract ("the second call must return at once") doesn't cover two cases that can happen

Done. The close() docstring now says: free only what is still up, and return at once when nothing is. It lists the three ways a close comes: twice (the rollouter's close, then the actor's __cleanup__), before setup ends (setup_async never ran, raised, or is still running), and during another close (__cleanup__ after the rollouter's close timed out). The Verifiers worker in "Verifiers: each rollout worker runs its Verifiers envs; the env server is gone" handles all three: each step stops only what is still up. Its new test parks a first close while it stops an env, and checks that a second close returns within 1 s.

the review bot (review): In this PR, nothing in the repo overrides close: MessageEnvRolloutWorker has nothing to close. ... should the close half move ...?

Kept here on purpose. This PR sets the worker's lifecycle both ways: the functions once at setup, and a close before the stop. Its user, the Verifiers worker, is two PRs up this stack. If the stack stopped below that PR, the close half would have no user, and it would move up then.

…setup; the rollouter closes each worker before it stops them
@felipemello1
felipemello1 force-pushed the felipemello1/rollout-workers/1-setup-and-close branch from 92754eb to 71def52 Compare November 15, 2026 22:19
Comment on lines +85 to +94
@concurrent_endpoint
async def close(self) -> None:
"""The Rollouter calls this before it stops the worker: a slow close (e.g. stopping
sandboxes) can't run in `__cleanup__`, which Monarch cancels after 3 s."""
await self._worker.close()

async def __cleanup__(self, exc: Exception | None) -> None:
"""Monarch runs this when the actor stops; a killed process skips it. It closes a worker
the Rollouter didn't, e.g. after an error."""
await self._worker.close()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i am ok with leaving both, but the docstring doesnt make convincing why we need both and why they should be the same. I dont think we do it for other actors, do we? i.e. have both close and cleanup

twice the Rollouter's close, then the actor's `__cleanup__`
before setup ends `setup_async` never ran, raised, or is still running
during another close `__cleanup__` after the Rollouter's close timed out
"""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i think we can delete everything after "and return at once when nothing is."

@felipemello1
felipemello1 marked this pull request as ready for review November 15, 2026 23:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 15, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 15, 2026 23:12
@felipemello1
felipemello1 marked this pull request as draft November 16, 2026 01:19
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 16, 2026
@felipemello1
felipemello1 removed this pull request from stack #6109 November 16, 2026 06:52

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant