Skip to content

[rl] Verifiers: each rollout worker runs its Verifiers env; the env server is gone - #6118

Draft
felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/verifiers-041/3-env-in-worker
Draft

felipemello1 wants to merge 1 commit into
mainfrom
felipemello1/verifiers-041/3-env-in-worker

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: Each rollout worker loads its Verifiers env and runs each episode itself, with env.run_slot. The env server process and its pool are deleted. Verifiers 0.4.1 removes that server, so this unblocks the bump.

Before, a separate Verifiers env server with 16 pool processes ran each of a group's 32 Terminal-Bench episodes and every model call carried its group id in the sampling params, and now the rollout worker (1 of 12, with 32 threads) that gets the group runs all 32 with env.run_slot, registers each trace's session with the group in its generation server (start_session, an unknown session gets 422), and at shutdown cancels its episodes in its new close so their containers are removed, with a 60 s limit, while all 12 workers still run on the controller's host.

Problem

  1. Today every Verifiers episode runs in a separate env server: one process plus its pool, started by VerifiersRollouter.
  2. Each rollout worker sends it tasks over ZMQ with Verifiers' EnvClient.
  3. Verifiers 0.4.1 deletes that server (verifiers.v1.serve).
  4. So TitanRL can't move to 0.4.1 until the episode runs in the worker.

Solution

  1. VerifiersRolloutWorker.Config.environment is the Verifiers env config. Each worker loads it when it is built. The recipe passes the training dataset's taskset config to it; nothing copies it. The worker builds validation tasks with it too, so the validation taskset needs the same task class and task config (a TODO and the README say so).
  2. run_group plans the group with env.slots(task, n=group_size) and runs each slot with env.run_slot.
  3. The group id never leaves our process. Verifiers calls on_trace when it creates each trace, before any model call. The worker then registers the trace's session with its group in its generation server (start_session). The server looks the group up by the X-Session-ID header. A session it doesn't know gets 422. end_session drops it and returns the session's metadata. A call still generating when its session ends (Verifiers gave up on it) leaves nothing behind.
  4. Each worker registers the local taskset alias before it loads the env.
  5. Each worker has a close endpoint. Rollouter.close waits for the running groups (run_group_drain_timeout_s, 30 s). Then it calls the workers' close under one limit (worker_close_timeout_s, 60 s), then stops them. The worker's close cancels the rollouts still running, so their sandboxes stop. Both limits are Rollouter.Config fields and must be positive. A pool whose spawn failed still stops.
  6. Every trace Verifiers mints is released at the router, a retried attempt's included.
  7. Verifiers' named rewards and metrics are logged on turn 0 of every rollout with turns: verifiers/reward/<name> (the raw score) and verifiers/metric/<name>. Validation logs them as validation_verifiers/reward/<name>. The training reward stays Verifiers' weighted sum.
  8. Core: Configurable.Config.to_dict dumps pydantic values, so the to_dict overrides in VerifiersTaskDataset and RenderersConfigAdapter go. The controller's release_session_fn logs a failed release for both workers, plus a release_session_failed trace event. ReleaseSessionFn says it never raises.
  9. Deleted: VerifiersRollouter, VerifiersEnvServer, GROUP_ID_SAMPLING_PARAM, worker_kwargs, connection_timeout_sec.
  10. The Terminal-Bench harness skips its tmux cleanup when the rollout's setup failed (e.g. its sandbox never started).
  11. All of a run's workers share one Verifiers run id. Each worker now runs its own Verifiers env, so without a shared id each worker process would get its own id and its own sandbox-creation limiter (e.g. for Prime sandboxes), and N workers would create sandboxes N times as fast as the limit. VerifiersRolloutWorker.Config.run_id (the launcher's VF_RUN_ID, else a new id, chosen once with the config) is set as VF_RUN_ID by each worker before it loads its env. The limiter keeps its state under ~/.cache/verifiers, so workers on different hosts share it only if that folder is shared. The shared id also lets one label find the run's sandboxes: Docker sandboxes get verifiers.run=<run_id> (only the label, no limiter). Test: test_rollout_worker_sets_the_verifiers_run_id_from_its_config.
  12. Unchanged: the dataset config, the taskset alias ids, generate_fn per group, statuses, the trace converter, the worker count (from rollouts_per_worker: 12 for the 9B recipe, 10 for 35B-A3B).

You may ask: why build the task in the worker? The sample carries only the task's data, as plain JSON. The worker's env gives the task class and its config.
You may ask: why a close endpoint, not Monarch's __cleanup__? Like the trainer's close, the controller calls it before it stops the process.
You may ask: why register the group from on_trace, not send it with each call? It rode the sampling params, which Verifiers forwards but doesn't declare. Now it never leaves our process.
You may ask: no container watchdog? A graceful stop cancels each rollout, and its run_slot removes its own container. Only a killed worker leaves containers behind.

NOTE: one 20-step Terminal-Bench run of an earlier version of this stack: Qwen3.5-27B, 4 GB300 hosts, 16 rollout workers picked at random, remote VM sandboxes. It predates the session map and the least-loaded worker pick (a later PR in this stack). It is close to a 6-step run of an env-server version of these PRs: the same reward within noise, and steps 2-5 took 1,260 s vs 1,313 s in total (single steps vary either way). That env-server run had 86 env-server processes, which its launcher sized; the recipe's default was 16. So this compares the two layouts, not worker counts. Each worker's close took 16-28 s and cancelled 15-86 rollouts. Sandboxes created = terminated (1,355), so none outlived the job. The run predates item 10.

                        this stack                    env server
reward, steps 2-5       0.71 / 0.75 / 0.67 / 0.73     0.67 / 0.73 / 0.66 / 0.75
step time, steps 2-5    189 / 394 / 266 / 411 s       196 / 439 / 412 / 266 s

NOTE: worker_close_timeout_s is 60 s. After it, the workers stop and their remaining sandboxes stay up. Docker is not measured: the build host has no Docker. Estimated load at close, Qwen3.5-9B Terminal-Bench recipe:

rollouts in flight:   (3 + 1) x 12 groups x 32 = 1,536  ->  128 per worker over 12 workers
busiest worker:       `choose` picks any worker, so one can hold more than 4 groups. The least-loaded pick
                      (a later PR in this stack) keeps each worker near 4 groups = 128 rollouts
container removal:    Verifiers runs `docker rm -f` on a thread; 32 threads -> 4 rounds
all workers at once:  up to 12 x 32 = 384 removals run together on one Docker daemon

60 s covers it if one removal takes under ~15 s at that load.
NOTE: each worker now holds its env in memory. In the run above: 1.27 GiB per worker at setup, 2.16 GiB median at the end, about 35 GiB for 16 workers. The env-server processes were never measured, so there is no baseline.
NOTE: sandbox exec transport errors went from 2 in 6,271 rollouts to 70 in 17,504 (0.03% -> 0.40%). Not bisected. One untested guess: each process now runs more rollouts at once, about 64 per rollout worker vs 24 per env-server process.
NOTE: DAPO now scores in each of its 5 rollout workers, and each starts 4 Math-Verify processes: 20 in all, vs 4 with the env server.

Follow up (each one is a TODO in the code)

  • Enable multi-env training: load the env from each sample's config, so one job can mix tasksets. Until then, nothing checks the env's taskset against the dataset's.
  • Drop tasks whose first prompt doesn't fit from the dataset, and detect the overflow by the call's status 400, not its error text.
  • Release a session only after its model calls finish.
  • Raise a typed error when a closed generator is called; then both rollout workers log it without a traceback.
  • Give the rubric the rollout's Verifiers reward directly, not through the last turn. Blocked: it changes RewardFn's input for both workers.
  • Pass the vision processor to the renderer the worker's train client builds.
  • Remove a killed worker's sandboxes, with a cleanup that runs outside the worker.
  • Measure the workers' close with the Docker runtime, and set worker_close_timeout_s from it (TODO in the Terminal-Bench recipe).
  • Share one Math-Verify pool per host.

Test plan

pytest -rs tests/rl/unit_tests/cpu tests/unit_tests/cpu/components/test_renderer.py tests/unit_tests/cpu/config
# Verifiers 0.4.0: 1069 passed, 1 skipped (test_train_loop.py, skipped on main too).
# Without Verifiers: 974 passed, 7 skipped (the Verifiers test files and recipes).

New:

  • test_a_group_runs_end_to_end_in_a_rollout_worker, for training (group 5, 2 rollouts, temperature 1.0) and validation (group -1, 1 rollout, temperature 0.0): real DAPO env, renderer client and generation server, fake generator. Every call reaches generate_fn with its group and temperature, and verifiers/reward/math_verify sits on turn 0. It fails without start_session (every call gets 422). The training group holds rollout_worker/ram_gib and the validation group doesn't: it fails without the flush at the end of VerifiersRolloutWorker.run_group.
  • test_generation_server_refuses_a_session_with_no_group: 422 for a session never started and for one ended (replaces test_generation_server_requires_group_id).
  • test_concurrent_verifiers_groups_keep_their_session_groups: two groups' sessions call one server at once over HTTP.
  • test_a_fresh_worker_process_loads_the_terminal_bench_env: fails without the alias registration (ModuleNotFoundError).
  • test_cleanup_skips_a_rollout_whose_setup_failed: fails without the check (the harness runs tmux kill-server).
  • test_the_close_endpoint_reaches_each_worker_process: real worker processes. Fails without the endpoint (AttributeError: close). It is the only test that fails when close loses its @concurrent_endpoint decorator.
  • test_close_closes_the_workers_then_stops_them: the workers' close runs once before they stop. When it hangs, one timeout warning, and the workers still stop.
  • test_close_stops_the_pool_of_a_spawn_that_failed: fails without the workers is None check in Rollouter.close.
  • test_a_call_that_ends_after_end_session_leaves_nothing_behind: fails without the session check after generate_fn.
  • test_generation_server_answers_422_to_a_bad_request: now with the group from the session.
  • test_close_cancels_running_rollouts_then_stops_serving
  • test_setup_async_builds_the_train_client_and_bypasses_the_proxy: replaces test_verifiers_worker_sends_muse_glimmer_renderer_config.
  • test_rollout_releases_every_session_verifiers_minted: replaces test_rollout_releases_every_trace_session_even_if_one_release_fails.
  • test_release_session_fn_logs_a_failed_release: the failed-release case, now in the controller, with its trace event.

Deleted with the env server: test_setup_spawns_workers_with_the_env_server_address_and_close_stops_the_workers_first, test_env_server_workers_skip_the_trainer_imports.

@felipemello1
felipemello1 added this pull request to stack #6120 November 16, 2026 07:13
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 16, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 59s —— View job


Request changes: running the env in the worker is the right design, but the new worker shutdown that cancels rollouts and removes sandboxes still needs the Terminal-Bench GPU run, and 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: Request changes -- The design is right: Verifiers 0.4.1 removes the env server, and running the env in the worker deletes a process and a pool. But the new shutdown path, where the worker's close cancels rollouts and removes sandboxes within 60 s, hasn't run with Docker. The PR itself says the Terminal-Bench GPU run gates the merge.

What this PR does. Each VerifiersRolloutWorker loads its Verifiers env in __init__. run_group plans the group with env.slots and runs each slot with env.run_slot. This deletes VerifiersRollouter, VerifiersEnvServer and the worker_kwargs plumbing through Rollouter and ActorSystem. In core, Rollouter.close now calls each worker's new close endpoint, with a 60 s limit, before it stops them. Configurable.Config.to_dict dumps pydantic values. The release-failure logging moves into the controller's release_session_fn.

Example.

before: worker --ZMQ EnvClient.run(task_data)--> env server pool proc --> agent --> interception --> worker GenerationServer
        close: stop workers, then terminate the env server process (its containers go with it, or don't)
after:  worker: env.run_slot(slot) --> agent --> interception (same proc) --> GenerationServer
        close: drain groups (30 s) -> workers' close: cancel rollouts, run_slot removes containers (60 s) -> stop workers

Must fix

  1. The "Summary (human-written)" section is empty. The author needs to fill it in; agents don't.
  2. Post the Terminal-Bench GPU run the description promises, with statuses, reward, rollouts in flight per worker, host memory per worker, and how long close took. _WORKER_CLOSE_TIMEOUT_S = 60 is a guess, and a worker whose close overruns leaves its containers running.

Should consider (inline)

  • rollouter.py:255 -- the literal torchtitan_group_id replaces GROUP_ID_SAMPLING_PARAM, but the receiver still reads it through the constant.
  • rollouter.py:88 -- the check that the env's taskset matches the training dataset's taskset is gone. A mismatch within the same task class is now silent.
  • rollouter.py:325 -- several TODOs cover behavior this PR doesn't change (also L194, L304, L465), and "Not done here" narrates history (also verifiers_terminal_bench.py:142).
  • test_shutdown.py:499 -- spawns real Monarch processes to test a one-line endpoint forward. Fold it into the in-process RolloutWorkerActor test.
  • test_rollouter_pool.py:310 -- the "return" case duplicates test_setup_spawns_worker_pool_on_controller_host.

Should consider (body only)

  • Unrelated edits in rollouter.py: the trace_to_rollout_turns docstring rewritten to prefix/delta, Any changed to vf.Episode/vf.Trace annotations, and keyword-only calls to verifiers_rollout_logs/log_failed_rollout. They're small, but one concern per PR.

Questions

  • After the worker's close cancels a group's rollouts, make_scored_group re-raises CancelledError out of the run_group endpoint, whose caller the controller has already cancelled. Does Monarch treat a BaseException from an endpoint as an actor failure, the exit-130 path the docstring warns about? Unverified.
  • choose places groups at random, and Terminal-Bench rollouts are long. Before, Verifiers' pool capped max_concurrent per pool worker. Now one worker can hold 2-3x the average, rendering and running docker cleanup on 32 threads. Does the GPU run show that worker falling behind?
  • Before, connection_timeout_sec=1800 covered a slow env start for Terminal-Bench. Now vf.load_environment runs in each actor's __init__, on 16 workers at once. Is there a Monarch spawn or setup_async timeout that a slow Harbor load could hit?
Details
  • Gate: the problem is real (Verifiers 0.4.1 deletes verifiers.v1.serve). The layer is right: the env belongs in the worker that already owns the GenerationServer. Net LoC is -110.
  • The core changes are small and each one has a consumer:
    • BaseRolloutWorker.close defaults to a no-op.
    • The Rollouter.close ordering is drain, then workers' close, then stop.
    • Configurable.to_dict uses duck-typed model_dump, and the two to_dict overrides it replaces are deleted.
    • The release try/except moves from MessageEnvRolloutWorker into the controller's closure, which is pickled into the worker. The worker still runs it, so behavior is the same.
  • Validation behavior is unchanged: the deleted env server also built validation tasks with the training taskset's task config.
  • Releases on cancel: _run_single_rollout releases each minted session in finally, so a cancelled or failed run_slot still releases its sessions.

Not verified: the Verifiers 0.4.0 slots/run_slot/on_trace API (verifiers isn't installed on this runner), and anything on Docker or GPU. A maintainer still needs to review the core changes (configurable.py, rollout/rollouter.py, controller.py).

max_tokens=sampling.max_tokens,
seed=sampling.seed,
**{GROUP_ID_SAMPLING_PARAM: group_id},
torchtitan_group_id=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 used to be **{GROUP_ID_SAMPLING_PARAM: group_id}. The receiver still reads it through the constant (generation_server.py:224), so the key now has two spellings. If the constant is ever renamed, group_id stops reaching the generator and nothing fails loudly. The change isn't needed for this PR, so I'd revert it and keep the import:

Suggested change
torchtitan_group_id=group_id,
**{GROUP_ID_SAMPLING_PARAM: group_id},

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: Keeping the literal. The author asked to drop the **{...} form on the old version of this PR. A drift fails loudly: the server answers 400 without the group id, and the end-to-end test sends the key.

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.

hmm, this is more confusing, because i am pretty sure that "torchtitan_group_id" is NOT an arg in "vf.SamplingConfig". I prefer what you had before, lets just add a 1 liner explaining why we are using ** to pass kwargs dict

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.

To be honest, i dont understand who is the consumer of this, why we need to pass these kwargs and why this is the best way. It doesnt seem to be robust at all.

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: You're right: torchtitan_group_id is not a declared vf.SamplingConfig field. Verifiers only passed it through.
Instead of restoring the ** with a comment, the group id now never leaves our process. See the next reply.

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: The consumer was our own generation server. It needs each call's group for the vLLM priority, the group's cached policy version and the group's KV release.
Now Verifiers doesn't carry it. When Verifiers creates a trace (on_trace, before any model call), the worker registers trace id -> group id in its generation server. The server finds the group by the X-Session-ID header, and a session it doesn't know gets a 422.

Comment on lines +88 to +90
environment: vf.EnvConfig
"""The Verifiers env each worker loads: its taskset, agent, harness and runtime. Give it
the same taskset object as the training dataset."""

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.

VerifiersRollouter.Config.__post_init__ used to raise if the env's taskset differed from training_dataloader.dataset.verifiers_taskset. Now only this docstring states the rule. Say a user copies a recipe and changes the dataset's taskset to another config of the same class, e.g. a different Harbor dataset, but forgets worker.environment. run_group then builds every task with the wrong taskset's task config and runtime, and nothing raises (CLAUDE.md principle 8: validate contracts whose failure would otherwise be silent).

Two small ways to keep the guarantee without the deleted subclass:

  • Have the recipe helpers build environment.taskset from the dataset config, so there is a single source.
  • Have the sample carry its taskset id, and have run_group raise when it doesn't match self._verifiers_env.config.taskset. Validation samples use a different taskset, so this one needs care.

If neither is worth it before the per-sample-env TODO lands, say in this TODO that the mismatch isn't checked.

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 in 5739e92 with your fallback: the per-sample-env TODO now says nothing checks the env's taskset against the dataset's. A sample carries no taskset id today, so a cheap run-time check isn't possible.

return _MarkerWorker(self.marker_dir)


def test_the_close_endpoint_reaches_each_worker_process(tmp_path):

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 test spawns two real Monarch processes, plus cloudpickle by-value registration, only to check that RolloutWorkerActor.close forwards to self._worker.close(). test_rollout_worker_actor_builds_its_worker_and_inits_its_logger in test_rollouter_pool.py already builds the actor in-process with object.__new__. Two extra lines there would cover the same regression at no process-spawn cost in CPU CI: give it a worker with an AsyncMock close, await actor.close's underlying function, and assert it was awaited. Unless the real-process spawn guards something the in-process check can't, I'd fold it in there (.claude/rules/tests.md: tests must earn their CI cost).

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: Keeping it. With @concurrent_endpoint removed from close, only this test fails across the RL suite: the in-process actor test calls the method directly, so it can't see a missing endpoint.



@pytest.mark.parametrize("close_ends_with", ["return", "hang"])
def test_close_closes_each_worker_then_stops_them(

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.

The "return" case repeats what test_setup_spawns_worker_pool_on_controller_host now asserts (close_calls_at_stop == 1, then stopped). Only "hang" guards something new: the timeout path still stops the workers. I'd drop the parametrize and keep just the hang case.

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: Keeping the "return" row. It is the only test that checks a normal close logs no "still closing after" warning; test_setup_spawns_worker_pool_on_controller_host checks the order, not the warning.

Comment on lines +325 to +327
# TODO: give the rubric the rollout's Verifiers reward directly. It rides on the last
# turn only because `RewardFromVerifiers` reads rewards from turns. Not done here: it
# changes the reward function's input for both workers, which needs its own PR.

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 TODO, and the ones for phase-time metrics (L465), the prompt-overflow detection (L304) and generate_fn in setup_async (L192), describe behavior this PR doesn't change. They read as the PR's follow-up list copied into the code. "Not done here: ... needs its own PR" also narrates the PR's history, which won't make sense once it merges; the same phrase is at verifiers_terminal_bench.py:142. I'd keep the TODOs this change introduces (killed-worker sandboxes, in-flight calls before release, per-sample env, close timeout) and track the rest in an issue. If you keep them, drop the "Not done here" clauses.

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 in 5739e92: the TODOs whose work belongs to other open PRs (generate_fn once at setup, the phase-time metrics) are gone, and main's 2-line set_generate_fn comment is back. The "Not done here" clauses are gone too; T12 and T19 now end with what blocks them. The rest are gaps this change creates or exposes.

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from 4b9fe6f to 5739e92 Compare November 16, 2026 08:38
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Fixes are in 5739e92. On the rest:

  • GPU run: not posted yet. It needs a box with Docker and the author's go; the description keeps it as the gate for merging.
  • (a) CancelledError out of run_group after close: it does not fail the actor. Probed in a real worker: if the caller cancelled first it gets CancelledError; if it still awaits it gets ActorError ... failed with BaseException. Either way the actor still answers, stops cleanly and the process exits 0 (Monarch 0.7.0 concurrent.py:91-99 forwards the error to the caller only).
  • (b) Random choose: the least-loaded placement PR in the rollout-placement stack replaces it; the GPU run logs rollouts in flight per worker.
  • (c) Slow env load: no Monarch timeout fires. With 16 real workers whose __init__ sleeps 100 s, setup_async returns after 109.7 s with no error. One real Terminal-Bench worker build takes 9.6 s here.
  • The type and keyword edits in rollouter.py: they follow the author's review comments on the old version of this change (real types instead of Any, keywords at call sites), in functions this PR rewrites. Kept.

@claude please review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes (again): the code is fixed, but the human-written summary is still empty and the Terminal-Bench run with Docker hasn't been posted. 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 -- The code issues from the last review are resolved, and the new commit adds no new problems. Two gates are still open: the human-written summary is empty, and the Terminal-Bench run with Docker, which the PR names as its merge gate, hasn't been posted.

What this PR does. Each VerifiersRolloutWorker loads its Verifiers env in __init__ and runs each episode with env.run_slot. That deletes VerifiersRollouter, VerifiersEnvServer and the worker_kwargs plumbing. In core, Rollouter.close now calls each worker's new close endpoint, with a 60 s limit, before it stops the workers. Configurable.to_dict dumps pydantic values, and the controller's release_session_fn now owns the logging of a failed release.

Example.

close, before: drain groups (30 s) -> stop workers -> terminate env server (its containers may outlive it)
close, after:  drain groups (30 s) -> workers' close: cancel rollouts, each run_slot removes its container (60 s)
               -> stop workers

Must fix (still open)

  1. The "Summary (human-written)" section is still empty. The author fills it in; agents don't.
  2. Post the Terminal-Bench run: statuses, reward, rollouts in flight per worker, host memory per worker, and how long close took. _WORKER_CLOSE_TIMEOUT_S = 60 is still a guess. If the busiest worker's close overruns it, the leftover containers stay up, and that would change the design, not just the constant.

Resolved since the last review

  • rollouter.py:256 literal torchtitan_group_id: I accept the reply. A missing group id gets a 400, so a drift fails loudly, and the end-to-end test sends the key.
  • The taskset mismatch is now stated in the per-sample-env TODO (rollouter.py:742).
  • TODOs trimmed, and no "Not done here" clauses are left.
  • test_the_close_endpoint_reaches_each_worker_process: kept. I accept that it is the only test that fails when @concurrent_endpoint is dropped.
  • The "return" row in test_close_closes_each_worker_then_stops_them: kept. I accept that it is the only check that a normal close logs no warning.
  • Questions (a)-(c): answered by the probes in the reply. The type and keyword edits are kept, as the author's own earlier review asked for them.
Details
  • I checked that shutdown releases sessions before the router stops. Controller.close closes the generators, then calls rollouter.close(), and only then calls actor_system.stop() (controller.py:631-666). So when a cancelled rollout releases its sessions in its finally block, the router is still up, and the worker's close waits for those releases before the workers stop.
  • GenerationServer.close is a no-op on a server that never started (generation_server.py:141). So a worker whose setup_async failed still closes cleanly.
  • MonarchActorSystem is the only ActorSystem, so deleting **kwargs from spawn_rollout_workers and adding the close endpoint covers every implementation.
  • The no_proxy edit moves here from the deleted env server process. It now runs in each worker process, which is where Verifiers' HTTP client now runs.

Not verified: the Verifiers 0.4.0 slots/run_slot/on_trace API (I couldn't import verifiers on this runner), and anything that needs Docker or a GPU. A maintainer still needs to review the core changes (configurable.py, rollout/rollouter.py, controller.py, actors/).

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from 5739e92 to 6cceb46 Compare November 16, 2026 16:57
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: this stack (top bcc8100) ran 20 Terminal-Bench steps end to end. Speed and reward are close to
the previous stack. Each rollout worker's close took 16-28 s. No sandbox was left running after the job. Findings 1
and 3 are fixed in 6cceb46 (this PR; the stack top is now a5876c7).

Setup:

  • Qwen3.5-27B on 4 hosts with 4 GPUs each. The trainer uses FSDP 2 x TP 2, plus 12 one-GPU vLLM engines.
  • Remote sandboxes, one VM per rollout.
  • 256 rollouts per step (16 tasks x 16), up to 2,048 in flight. 20 steps, no saves.
  • Before = the same setup on the previous stack (an env server with 86 workers of 24 rollouts each). It ran 6 steps.
                                  this stack                       before
step time, steps 2-5              189 / 394 / 266 / 411 s          196 / 439 / 412 / 266 s
reward, steps 2-5                 0.71 / 0.75 / 0.67 / 0.73        0.67 / 0.73 / 0.66 / 0.75
pass rate, all rollouts           65.2% (17,504)                   66.6% (6,271)
model time / agent time           0.75                             0.75
mean of steps 2-20                step 412 s, reward 0.66, status completed 0.965, error 0.034
rollout stops                     finished 96.0%, context overflow 2.27%, harness 0.95%, sandbox 0.57%
rollouts in flight per worker     16 workers; p50 59, p90 104, max 197 (busiest = 1.8x the mean)
RSS per worker                    1.3 GiB at setup, at most 2.5 GiB
close                             each worker 16-28 s (cap 60 s); 752 rollouts cancelled

Findings:

  1. If a sandbox fails to start, the Terminal-Bench harness still runs its cleanup. The runtime.run at
    torchtitan/rl/examples/verifiers/terminal_bench/harness.py:127 then raises AttributeError on the torn-down
    runtime. Verifiers logs the traceback once per rollout (16 here). Fixed in 6cceb46: the cleanup returns early
    when the agent never started (test_cleanup_skips_a_rollout_whose_setup_failed).
  2. Sandbox failures train as ERROR with error_reward. The TODO above rollout_status covers this. Here it was 0.66%
    of rollouts.
  3. At close, every generate call still in flight logs its own traceback. That was 12,612 "generator is closed" errors.
    Fixed in 6cceb46: the generation server logs at most one traceback a minute, with how many failed since the last
    one, and close logs the count left over. A TODO tracks the typed-error fix that replaces this limit.
  4. After the rollouter closed, the process exited 254. The trainer mesh's mesh.stop() (actors/monarch/system.py:268)
    hit Monarch's "cleanup error: deadline has elapsed". The previous stack failed the same way, so this stack did not
    cause it.
  5. Sandbox exec disconnects hit 70 rollouts (0.40%). Before, they hit 2 of 6,271. One untested cause: each worker now
    runs about 64 rollouts at once, not 24.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 46s —— 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 20-step Terminal-Bench run answers the earlier must-fix: worker close took 16-28 s against the 60 s cap, and sandboxes created = terminated (1,355). The two bugs it found are fixed in 6cceb46. The human-written summary is still empty.

What this PR does. Each VerifiersRolloutWorker loads its Verifiers env and runs each episode with env.run_slot, so the env server process and its pool are deleted. Rollouter.close now drains the groups, then calls each worker's close (cancel rollouts, remove their sandboxes) with a 60 s cap, then stops the workers. New in 6cceb46:

  • The generation server logs at most one traceback a minute.
  • The Terminal-Bench harness skips its tmux cleanup when setup failed.

Example.

sandbox never starts -> harness.cleanup
  before: runtime.run("tmux kill-server") on a torn-down runtime -> AttributeError, traceback per rollout
  after:  trace.timing.agent.start is unset -> return
shutdown with 1,500 calls in flight -> generators closed first
  before: 12,612 "generator is closed" tracebacks
  after:  1 traceback/min per worker + "N failed since the last traceback" at close

Must fix

  1. The "Summary (human-written)" section is empty. The author fills it in; agents don't.

Should consider

  • generation_server.py:265-281 -- the once-a-minute limit applies to every failure in a normal run, not just at shutdown. The inline comment has a smaller option.

Questions

  • Sandbox exec transport errors went from 2/6,271 to 70/17,504 rollouts. That gap is larger than noise, and these rollouts train as ERROR with error_reward. Is it the per-process concurrency (about 64 rollouts per worker vs 24 per env-server worker)? One cheap check is a short run with worker_pool_size=32, num_threads_per_worker=16. For a maintainer: is an unexplained 0.4% sandbox error rate acceptable for an example recipe?
Details
  • Earlier must-fix 2 (the Terminal-Bench run): resolved. It covers statuses, reward, rollouts in flight per worker (p50 59, max 197), RSS per worker (at most 2.5 GiB) and close time. It used remote VM sandboxes, and the shipped recipes use vf.DockerConfig. So Docker close time is still the estimate in the description (fits in 60 s if one docker rm -f takes under ~8 s at 512 concurrent). An overrun logs "still closing after" and leaves that worker's containers up. That is visible, not silent.
  • The exit 254 from mesh.stop() (finding 4) also happens on the previous stack, so it is not caused here.
  • The harness fix is a separate bug from the env move, but it is 5 lines plus a test, and the GPU run of this stack surfaced it. Fine to keep here.
  • Unchanged since the last review: every inline thread from the first review is resolved (replies accepted in the second review).

Not verified: that Verifiers 0.4.0 sets trace.timing.agent.start only after setup succeeds, and that Timing() leaves it falsy. Verifiers can't be imported on this runner. Docker shutdown timing is not verified either. A maintainer still needs to review the core changes (configurable.py, rollout/rollouter.py, controller.py, actors/).

Comment on lines +265 to +281
# At shutdown, every call still in flight fails here, because the generators close
# first: thousands of identical tracebacks. So log at most one traceback a minute,
# with how many failed since the last one. Verifiers still logs each failed call, so a
# different error in that minute still shows its message, without a traceback.
# TODO: once a closed generator raises a typed error (see the TODO in
# `MessageEnvRolloutWorker`), skip only its traceback and drop this limit.
now = time.monotonic()
if now - self.last_traceback_time >= 60.0:
logger.exception(
"TorchTitan generation failed for %s (%d more failed since the last traceback)",
request_id,
self.num_failures_without_traceback,
)
self.last_traceback_time = now
self.num_failures_without_traceback = 0
else:
self.num_failures_without_traceback += 1

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.

The limit is meant for shutdown, but it applies to every generation failure for the whole run. Say the router returns 5xx for a few seconds mid-training, and then a different bug raises in the same minute. The first error gets a traceback. The second shows up only as Verifiers' one-line message and a count, so the stack that would locate it is gone. That is a knob that hides a problem (principle 1), and it adds two pieces of state plus a reset in close.

The sibling path has the same shutdown flood: MessageEnvRolloutWorker logs a traceback for every closed-generator failure. It keeps plain logger.exception with a TODO (torchtitan/rl/rollout/rollouter.py:653). I'd do the same here: revert to logger.exception and point the TODO at the typed-error fix, so both workers are fixed in one place. If the shutdown flood is too painful to wait for that fix, keep the limit but start it only after the first closed-generator failure, so failures in a normal run keep their tracebacks. A flag set by the worker's close would come too late: the generators close before Rollouter.close drains, and the flood starts there.

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from 6cceb46 to d993873 Compare November 16, 2026 17:06
Comment thread torchtitan/rl/controller/controller.py Outdated
routing_session_id=routing_session_id
)
except Exception:
# Not fatal: `max_sessions` evicts an unreleased session.

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.

lets make this easier to understand. You are saying that the router LRU would eventually evict this? I wonder if theres a TODO to make this more robust in the router, or if we should use structured logger to save here that this exception occurred, so its easier to identify it.

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: Yes. Once the router holds more than max_sessions, it drops the session it used least recently. The group's release also frees any KV the generator holds for the session. So nothing stays forever, and the router needs no TODO.
Changed: the comment now says this in plain words, and the except also logs a release_session_failed structured-log event.

Comment on lines +57 to +59
elif hasattr(val, "model_dump"):
# A pydantic model: dump its fields as JSON data.
return val.model_dump(mode="json")

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.

was this properly tested?

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: Yes. test_config_to_dict_is_json (core CPU CI) dumps a RenderersConfigAdapter. That class no longer has its own to_dict, so the test runs this branch.
It passes. With the branch removed, it fails with "string indices must be integers".

Comment thread torchtitan/rl/rollout/rollouter.py Outdated
# stop anyway and leave the rest. In a run with 16 rollout workers and remote VM sandboxes, each
# worker's close took 16-28 s for up to 86 running episodes, so 60 s leaves about 2x room.
# TODO: re-check with the Docker runtime, which is not measured yet.
_WORKER_CLOSE_TIMEOUT_S = 60.0

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.

should we somehow have a way to pass these as variables, but have good defaults for them? i dont want to make it hard for people to override those if they want to. Sounds like bad practice.

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.

is this the common pattern we do in titan?

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. Both are now Rollouter.Config fields with defaults: run_group_drain_timeout_s = 30.0 and worker_close_timeout_s = 60.0. Both must be positive.

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: No. Titan usually makes a timeout a config field with a default, e.g. CommConfig.init_timeout_seconds and TokenEnv.Config.step_timeout_s.
The module constant was copied from main's _RUN_GROUP_DRAIN_TIMEOUT_S. Both timeouts are config fields now (see the reply above).

Comment on lines +141 to +146
# TODO: size the pool in the controller from the rollouts in flight and the host's CPUs,
# with a user override. Blocked: it changes how every recipe sizes its workers. 16 is hand-set.
worker_pool_size=16,
# Each worker renders and removes sandboxes on threads. A render waiting for its
# renderer's lock holds a thread, so with too few, waiting renders stall sandbox cleanup.
num_threads_per_worker=32,

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.

for the reader, we do that in another stack #6112

To claude: i remember that in 6112 we sized the worker pool size, but i dont remember us setting any number for threads per worker.

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: Right. The distributed-workers PRs below this one size the pool (rollouts_per_worker) and keep num_threads_per_worker at 4. After the rebase on them, this recipe sets no pool size.
This PR sets 32 threads for Terminal-Bench only. Each worker renders prompts and removes sandboxes on these threads, and a render that waits for its renderer's lock still holds a thread. 32 isn't tuned.

Comment on lines -55 to -61
def to_dict(self) -> dict[str, Any]:
return {
"verifiers_taskset": self.verifiers_taskset.model_dump(mode="json"),
"num_tasks": self.num_tasks,
"seed": self.seed,
"shuffle": self.shuffle,
}

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 dont fully follow why we are making this change. Can you give me a TLDR. Will we still return the same?

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: Yes, it returns the same 4 keys and values.
The shared Configurable.Config.to_dict now dumps any pydantic value with model_dump(mode="json"). This PR adds a second pydantic value to a config (VerifiersRolloutWorker.Config.environment). So the shared code learned it once, instead of a second override.

Comment on lines +282 to +283
# One trace is one agent's run, e.g. the policy's or a simulated user's. A compaction or a
# harness subagent adds a branch to this trace.

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.

Lets do something like this instead:

"""# Every agent should produce a single trainable trace. Multiple retries can yield multiple traces, but only one trainable. Keep only trainable traces"""


Do we log any sort of metrics on retries or why we retried? sounds like we are blind to it.

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: Applied, with one correction: a retry restarts the trace list, so episode.traces holds only the last attempt. Several traces come from several agents, e.g. the policy and a simulated user. The comment says that now.
Retries: Verifiers' episode and agent retries default to 0, and no recipe changes that. If one does, each attempt's errors count in the new verifiers/errors/<type> metric (training groups only).

rollouts_or_errors=rollouts_or_errors, sample=sample, group_id=group_id
)

async def _run_single_rollout(

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.

this function is honestly not easy to read, despite not being very long. I think that this file, in general, could use some text markers, like:

"""# ------- Do X --------"""

We shouldnt abuse it, but i think it would help human review. Lets apply this concept to this stack and #6112 stack

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: Added banners (# ======== Do X ========) only where a function has clear phases: make_scored_group (3), the Verifiers run_group (3), _run_single_rollout (4) and Rollouter.close (2).
In the distributed-workers PRs, the one candidate, spawn_rollout_workers, has two parts that its comments already label, so it has none.

if not turns:
# Verifiers records an overlong first prompt as a failed model call; vLLM, the
# renderer and the generation server all word it "maximum context length".
# TODO: drop tasks whose first prompt doesn't fit from the dataset, and detect the overflow

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.

Suggested change
# TODO: drop tasks whose first prompt doesn't fit from the dataset, and detect the overflow
# TODO: drop from the dataset tasks whose first prompt doesn't fit, and detect the overflow

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: Applied word for word. The TODO's second half is still open: detect the overflow by the call's status 400 instead of its error text.
After the generation-server PR below this one, our server returns 400 only for a prompt that doesn't fit, so we could switch now. That waits for your answer.

Comment on lines 326 to 329
# TODO: give the rubric the rollout's Verifiers reward directly. It rides on the last
# turn only because `RewardFromVerifiers` reads rewards from turns. Blocked: it changes
# `RewardFn`'s input for both workers.
turns[-1].env_rewards[VERIFIERS_REWARD_KEY] = trace.reward

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.

does verifiers always give one reward for the entire rollout? This sounds brittle as is.

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: One training reward per rollout: Verifiers' trace.reward, the weighted sum of the trace's named rewards. Verifiers scores the whole trace, not each turn.
What was brittle is fixed. Each named reward and metric is now logged on turn 0, as verifiers/reward/<name> and verifiers/metric/<name>. And the next PR gives a trace that the env's grader drops (trace.dropped, new in 0.4.1) a new DROPPED status, which isn't trained.

Comment on lines -348 to -349
max_concurrent_rollouts=async_loop.max_active_rollout_groups
* async_loop.num_samples_per_prompt,

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.

why are we deleting this? i am not against it, i just want to understand

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: It sized the deleted env server: each of its 16 pool processes capped its episodes at ceil(max_concurrent_rollouts / 16). Nothing reads it now.
The cap on rollouts in flight now comes from the controller (max_active_rollout_groups x group size), spread over the workers.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review. Since your last review: the group id comes from a session-to-group map in the generation server (start_session/end_session), not a sampling param; the two timeouts are Rollouter.Config fields; Rollouter.close stops partly spawned workers and keeps closing healthy hosts when one host's close fails; rebased on the distributed-workers PRs. The human-written Summary is still empty on purpose.

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, with one item left 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 new commit fixes what the last review and the author's own review raised: the group id no longer goes through an undeclared sampling param, the two timeouts are config fields, and Rollouter.close now handles a partial spawn and a failing host. I found no new correctness problems. The human-written summary is still empty.

What changed since the last review.

  • The generation server keeps a session -> group map. The worker's on_trace callback fills it with start_session, and end_session drops the entry and returns the session's metadata. A call for a session the server doesn't know gets 422.
  • run_group_drain_timeout_s and worker_close_timeout_s are now Rollouter.Config fields, each checked in __post_init__.
  • Rollouter.close calls every host's close inside one gather(return_exceptions=True) under one wait_for, and calls stop_rollout_workers in a finally.
  • The once-a-minute traceback limit is gone. It is back to logger.exception, with a TODO that points at the typed-error fix (this answers my last should-consider).

Example.

on_trace(trace "9f3c")           -> start_session("9f3c", group=7)
POST /generate X-Session-ID 9f3c -> group_ids["9f3c"] == 7 -> generate_fn(group_id=7)
run_slot ends / is cancelled     -> finally: end_session("9f3c") -> release_session_fn("9f3c")
late call for 9f3c               -> before generate: 422; already generating: reply sent, metadata not kept
Rollouter.close                  -> drain (30 s) -> gather(host.close for each host) within 60 s -> finally stop workers

Must fix

  1. The "Summary (human-written)" section is empty. The author fills it in; agents don't. I know it is empty on purpose for now. It still has to be filled in before merge.

Questions

  • DAPO no longer has VerifiersRollouter's placement check, so it now runs on the default worker_placement="all_hosts", and each host's workers load the Math taskset and start their own Math-Verify pool. Has a DAPO run with workers on more than one host happened, e.g. the release GPU script? Terminal-Bench stays on controller_host_only, so only DAPO changes placement here.
Details

What I checked at HEAD (22f6f26):

  • Generation server races:
    • The session check runs after the body's await. Nothing awaits between that check and the request_counts increment, so end_session can't leave a stale count behind.
    • Metadata from a call that finishes after end_session is dropped (generation_server.py:277), so nothing leaks.
    • close clears group_ids.
  • Contract of ReleaseSessionFn ("never raises"):
    • The controller's closure catches and logs the failure and emits release_session_failed.
    • MessageEnvRolloutWorker dropped its own try/except, and the Verifiers worker never had one.
    • test_release_session_fn_logs_a_failed_release covers the failure path.
    • The docstring says a release frees the session's KV. InterGeneratorRouter.release_session does that for a pinned session, and release_groups covers non-sticky routing. So the docstring is accurate.
  • Rollouter.close:
    • After a timeout, wait_for cancels the gather, and the finally still stops the workers.
    • A host that raises is logged per host and doesn't cut the others short.
    • With workers is None (spawn raised) it only stops the workers. TimeoutError is the right exception on Python >= 3.11, which pyproject.toml requires.
  • No stale references to env_server, GROUP_ID_SAMPLING_PARAM, worker_kwargs or connection_timeout_sec remain in the repo.
  • The no-turns ERROR_INFRA path and verifiers/errors/<type> come from the base branch, not this PR.
  • Every inline thread from the earlier reviews is resolved. The author's 19 comments from 2026-11-16 all have replies. Each one changes the code or answers with evidence: config fields for the timeouts, the TODO rewrites, section banners, torchtitan_group_id replaced by the session map.

Not verified: that Verifiers 0.4.0 calls on_trace before a trace's first model call (Verifiers can't be imported on this runner; test_a_group_runs_end_to_end_in_a_rollout_worker claims to cover it). Also not verified: Docker close timing, and anything on GPU. A maintainer still needs to review the core changes (configurable.py, rollout/rollouter.py, rollout/types.py, controller.py, actors/).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: on DAPO across hosts: not run yet. The first multi-host run of the distributed-workers PRs is still pending, and DAPO would spread there for the first time. Each worker builds its own Math taskset and Math-Verify pool, so no state is shared between hosts.

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from 22f6f26 to d22cdae Compare November 17, 2026 04:42
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from d720f5b to 288f17b Compare November 19, 2026 02:10
@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch 2 times, most recently from 103ba49 to ec46bb0 Compare November 20, 2026 02:43
@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from ec46bb0 to cdf494a 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 8s —— View job


Approve, with one item left before merging: the human-written summary is still empty. Since the last review the PR was only rebased on the sampling-params fixes, and I found no new problems. 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 item below before merging. At cdf494a the code is the design I approved at ef03e68, rebased on the new base commit 94c9488 (sampling-params fixes). I found no new problems. The empty human-written summary is still the only item left.

What this PR does. Each VerifiersRolloutWorker loads its Verifiers env. It runs each episode with env.slots and env.run_slot. This deletes the env server, VerifiersRollouter, GROUP_ID_SAMPLING_PARAM and the worker_kwargs plumbing. The generation server looks up each call's group in a session -> group map, which on_trace fills. Rollouter.close does three things: drain the groups, call each worker's close (which cancels its rollouts), then stop the pool. All workers in a run share one Verifiers run id.

Example. How the rebase meets this PR's generation server:

before this PR:  sampling_params {"temperature": 1.0, ..., "torchtitan_group_id": 7}
                 -> server pops the group id, then parses the rest
this PR:         sampling_params {"temperature": 1.0, "top_k": -1, "min_p": 0.0, ...}
                 -> _parse_sampling_config(body["sampling_params"])  (rejects a non-dict and unknown keys)
                 -> group_id = group_ids[X-Session-ID]                (422 if start_session never ran)

Must fix

  1. The "Summary (human-written)" section of the description is empty. The author fills it in; agents don't.
Details

What I checked at cdf494a against origin/felipemello1/verifiers-041/2-server-fixes:

  • The rebase. The new base's _parse_sampling_config checks the type itself (generation_server.py:365). So the PR can drop its own isinstance(sampling_params, dict) check. The base rejects unknown keys, so a stray torchtitan_group_id would now get a 422, not be ignored. Nothing in the PR sends one.
  • Net diff. 29 files, +1143/-978. That is 6 and 5 lines fewer than at ef03e68. Those lines are the overlap with the base commit, not new logic.
  • Unchanged since ef03e68:
    • Rollouter.close: drain, wait_for(workers.close.call()), then finally stop. With workers is None it skips close and still stops the pool.
    • The two timeout config fields and their __post_init__ check.
    • The close endpoint, and ReleaseSessionFn's "never raises" contract with the controller's catch-and-log closure.
    • The session map's checks after both awaits.
    • The named rewards on turn 0, the harness setup-failed check, and VF_RUN_ID set before load_environment.
  • Stale references. None left in the repo: env_server, EnvServer, VerifiersRollouter, GROUP_ID_SAMPLING_PARAM, pop_generation_metadata, connection_timeout_sec, worker_kwargs, _RUN_GROUP_DRAIN_TIMEOUT_S, torchtitan_group_id, setup_env_server_worker.
  • Earlier threads. Every inline thread from the earlier reviews, and from the author's own review, still has a reply that changes the code or gives evidence.

Not verified: the Verifiers 0.4.0 API (slots, run_slot, the on_trace order), because I couldn't import Verifiers on this runner. Also not verified: how long close takes with Docker.

A maintainer still needs to review the core changes: configurable.py, rollout/rollouter.py, rollout/types.py, controller.py and actors/.

@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch 6 times, most recently from f4b1c48 to b01498a Compare November 23, 2026 20:12
@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from b01498a to f7878d3 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 7s —— View job


Approve, with one item left before merging: the human-written summary is still empty. Since the last review the PR was only rebased on 163226b (1 GiB requests, top_k/min_p), and I found no new problems. 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 item below before merging. At f7878d3 the PR matches the design I approved at cdf494a. It is now rebased on base commit 163226b (1 GiB requests, top_k -1/0 and min_p 0.0 accepted), and I found no new problems. The only open item is still the empty human-written summary.

What this PR does. Each VerifiersRolloutWorker loads its Verifiers env and runs each episode with env.slots plus env.run_slot. This deletes the env server, VerifiersRollouter, GROUP_ID_SAMPLING_PARAM and the worker_kwargs plumbing. The generation server finds each call's group through a session -> group map that on_trace fills. Rollouter.close drains the groups, calls each worker's close (which cancels its rollouts), then stops the pool. All of a run's workers share one Verifiers run id.

Example. How a Verifiers 0.4.1-style call reaches the server at this base:

on_trace(trace "9f3c")                -> start_session("9f3c", group=7)
POST /generate X-Session-ID: 9f3c
  sampling_params {"temperature": 1.0, "top_k": -1, "min_p": 0.0, ...}
                                      -> _parse_sampling_config (base: no-op top_k/min_p accepted)
                                      -> group_ids["9f3c"] == 7 -> generate_fn(group_id=7)
run_slot returns / raises / cancelled -> finally: end_session("9f3c") + release_session_fn("9f3c")
late call for an ended session        -> 422 before generating; metadata dropped if already generating

Must fix

  1. The "Summary (human-written)" section of the description is empty. The author fills it in; agents don't.
Details

What I checked at f7878d3 against origin/felipemello1/verifiers-041/2-server-fixes. cdf494a can't be fetched here, so I re-read the whole diff instead of an incremental one.

  • Net diff. 29 files, +1148/-977. That is 5 more added lines and 1 fewer deleted than at cdf494a, which is the overlap with the new base commit. I found no new logic.
  • The rebase. This PR's vf.SamplingConfig sets only temperature, top_p, max_tokens and seed. The top_k/min_p values that Verifiers sends by default are handled by the base's _parse_sampling_config, and the PR no longer adds a group-id key that the base would reject.
  • Core, unchanged since the last review:
    • Rollouter.close: drain, then wait_for(workers.close.call()), then finally stop. With workers is None it skips close.
    • The two timeout fields and their __post_init__ check.
    • BaseRolloutWorker.close, and the close endpoint on RolloutWorkerActor.
    • ReleaseSessionFn's never-raises contract, enforced by the controller's closure. MessageEnvRolloutWorker dropped its own try/except.
    • Configurable.to_dict dumping pydantic values.
  • Worker. Each rollout joins _running_rollouts before run_group's next await, so close sees it. A cancelled rollout's finally still ends and releases its sessions. _run_single_rollout catches Exception, so one failed episode doesn't cancel its TaskGroup siblings.
  • Earlier threads. Every inline thread from the earlier reviews, and from the author's own review, still has a reply that changes the code or gives evidence.

Not verified: the Verifiers 0.4.0 API (slots, run_slot, the on_trace order), because Verifiers can't be imported on this runner. Docker close timing is not verified either.

A maintainer still needs to review the core changes: configurable.py, rollout/rollouter.py, rollout/types.py, controller.py and actors/.

felipemello1 added a commit that referenced this pull request Nov 24, 2026
…ead per 4 rollouts, and gc.freeze (#6174)

## 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:** 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.](https://raw.githubusercontent.com/felipemello1/pr_images/81b3f3c5472e7afa521015485beada6a8fb24d0f/torchtitan/6174/lanes.png)
<!-- pr-image drawn at 65fc2a5 -->

```text
# 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:
```text
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):
```text
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 #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 #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**

```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: 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`).

Co-authored-by: Felipe Mello <[email protected]>
@felipemello1
felipemello1 force-pushed the felipemello1/verifiers-041/3-env-in-worker branch from f7878d3 to 9678b60 Compare November 24, 2026 02:29
Base automatically changed from felipemello1/verifiers-041/2-server-fixes to main November 24, 2026 02:29
…erver is gone

Each rollout worker loads its Verifiers env and runs each episode with
env.run_slot. The env server process and VerifiersRollouter are deleted.
Rollouter.close calls a new per-worker close before it stops the workers;
both close timeouts are Rollouter.Config fields.

The worker registers each trace's session with its rollout group from
on_trace, so the group id no longer rides in the sampling params. Verifiers'
named rewards and metrics are logged on turn 0 as verifiers/reward/<name>
and verifiers/metric/<name>.

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