Repository navigation
[rl] Rollout workers get generate_fn and release_session_fn once, at setup; the rollouter closes each worker before it stops them - #6099
Conversation
|
Reply from claude: @claude please review |
|
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. |
There was a problem hiding this comment.
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
- 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, thoughReleaseSessionFnnow 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 wholegather, so a different worker's failed close goes unlogged and the hung worker isn't named. Useasyncio.waitlike the drain step just above (inline). -
torchtitan/rl/rollout/rollouter.py:757-- theclose()contract ("the second call must return at once") doesn't cover two cases that can happen:__cleanup__callscloseon a worker whosesetup_asyncnever ran or failed.- After the 60 s timeout,
__cleanup__callsclosewhile 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:MessageEnvRolloutWorkerhas nothing to close. The endpoint,__cleanup__,_WORKER_CLOSE_TIMEOUT_Sand 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_rolloutnow awaitsrelease_session_fnwith 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.timeoutneeds Python 3.11+.pyproject.tomlrequires>=3.11, andtoken_env.pyalready uses it.- The tests assign
worker._generate_fndirectly so they don't have to callsetup_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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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_resultsdoesn'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.
There was a problem hiding this comment.
Reply from claude: Fixed: closing the workers uses asyncio.wait, like the drain step above it.
862ebd5 to
cae7807
Compare
ab51e2b to
92754eb
Compare
|
Reply from claude: answers to the points in the review that have no inline thread.
Removed, with the failure half of its test (now
Done. The
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
92754eb to
71def52
Compare
| @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() |
There was a problem hiding this comment.
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 | ||
| """ |
There was a problem hiding this comment.
i think we can delete everything after "and return at once when nothing is."
Summary (human-written)
Before we would pass to every group the
generate_fnandrelease_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'sclosebefore it stops the processes.Stack (15 PRs, bottom first; merging a PR also merges every PR below it; this PR in bold)
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
generate_fnand onerelease_session_fnand passes the same two with every group.__cleanup__after 3 s and fails the job: the controller exits 130.Solution
BaseRolloutWorker.setup_asynctakes both functions, documented in itsArgs;run_grouploses them.BaseRolloutWorker.close()frees whatsetup_asyncstarted. 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.closeas an endpoint.Rollouter.closedrains, calls each worker'sclose, then stops the processes.__cleanup__calls the sameclose, 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 afinallyanyway.release_sessionlogs a failed release and returns: the router evicts a session nobody released, so a failure isn't fatal.Results
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 warningstest_spawn_rollout_workers_returns_one_handle_per_workercloses 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).