Repository navigation
[rl] Rollouts that fail outside the policy are recorded, not trained (1/4) - #6116
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 5m 43s —— View job Approve -- please write the empty human-written summary before merging; a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The fix is in the right layer and is shared by both workers. A group with no raise and no cut-short completion trains as it does on main. A maintainer still needs to review, since this touches core RL code (rollouter.py, training_sample_builder.py).
What this PR does. A sibling that raises, or whose completion the generator aborted, becomes ERROR_INFRA. It stays in the group for logs but is never scored. The other siblings are scored and centered among themselves. TrainingSampleBuilder now drops only rollouts with reward None, instead of the whole group. Both workers now gather with return_exceptions=True and call one shared BaseRolloutWorker.make_scored_group. On main, MessageEnvRolloutWorker gathered without it, so the envs were closed while siblings could still be generating. max_rollout_tokens is now required, so an overlong prompt ends as TRUNCATED_PROMPT_TOO_LONG instead of a generator raise that would now count as infra.
Example.
group of 3; generate raises for rollout 0; rubric gives rollouts 1, 2 rewards 2, 3
main (MessageEnv): rollout 0 = ERROR, no turns -> "untrainable" filter drops all 3
main (Verifiers): run_group raises -> controller drops the group (rollout/group_failures)
this PR: rollout 0 = ERROR_INFRA, reward/advantage None, logs["error"] = "ConnectionError(...)"
rollouts 1, 2: advantages -0.5, +0.5, trained
Must fix
- The "Summary (human-written)" section is empty. Please write it yourself (2-5 sentences: the problem, why this approach, and what you checked).
Should consider
torchtitan/rl/rollout/rollouter.py:597-- the worker repeatsTokenEnv's finish-reason check. Key the log off the returnedERROR_INFRAstatus and keep the constant private.torchtitan/rl/rollout/token_env.py:275-- this TODO is #6098. Landing #6098 first means a policy-caused re-render crash never turns into an unpenalizedERROR_INFRAdrop.torchtitan/rl/rollout/rubric.py:61--RubricOutput.reward: float | Nonehas no in-repo producer yet. Move it to the stack PR that uses it, or name the user.
Questions
- An exception in a user's
MessageEnv.stepor renderer now silently means "don't train", where on main it meant "train witherror_reward". That makes a policy-triggerable env bug invisible to the loss; onlyrollout/status_rate/error_infrashows it. Is that metric enough, or should a recipe alert or fail when the rate stays high? (Not a request for a knob in this PR.)
Details
- Numerics on the no-failure path. I traced the following:
- When every rollout is scored,
make_scored_grouppasses the same rollouts toscore_groupand the advantage estimator as main does. is_zero_stdreduces to main's check when every rollout is scored.asyncio.timeout(None)replaces thetimeout is Nonebranch and behaves the same.- In the CI recipes,
max_rollout_tokens=seq_lenreplaces_configure_ci'smax_context_length. I traced these to the same value, including the kimi_k3 and 0.6b batch-invariant rebuilds and the tp4_ep4 rebuild. - Production alphabet_sort and geometry3k recipes go from no cap to
seq_len, which their short prompts shouldn't hit.
- When every rollout is scored,
- Callers audited. Every
MessageEnvRolloutWorker.Config/TokenEnv.Configin recipes and tests now setsmax_rollout_tokens.ERROR_ABORThas no remaining references.KeepExtremeRewardsFilteralready skips reward None, and withkeep_errorsit recordsERROR_INFRA, sinceis_error()includes it. Validation (group_size=1) leavesERROR_INFRAout ofvalidation_reward, as the PR's NOTE says. - Cancellation.
make_scored_groupre-raises aCancelledErrorfound in the gather results. Outer cancellation still propagates throughgather. - Python version.
asyncio.timeoutandTimeout.expired()need Python 3.11, whichpyproject.tomlalready requires.
Not verified: that vLLM actually emits finish_reason="error" (e.g. on a failed KV load) in the pinned version; no GPU runs.
| if completion.finish_reason in CUT_SHORT_FINISH_REASONS: | ||
| logs["error"] = ( | ||
| f"the generator cut response {completion.request_id} short " | ||
| f"(finish_reason={completion.finish_reason})" | ||
| ) |
There was a problem hiding this comment.
The worker repeats TokenEnv.step's finish-reason check, so the cut-short rule now lives in two places and CUT_SHORT_FINISH_REASONS has to be imported across modules. If a third finish reason gets added to the set later, both places have to change together, and a custom TokenEnv that returns ERROR_INFRA for some other reason never gets a logs["error"].
Smaller fix: read the status TokenEnv already returned, and keep the constant module-private (_CUT_SHORT_FINISH_REASONS) in token_env.py:
| if completion.finish_reason in CUT_SHORT_FINISH_REASONS: | |
| logs["error"] = ( | |
| f"the generator cut response {completion.request_id} short " | |
| f"(finish_reason={completion.finish_reason})" | |
| ) | |
| if next_env_step.status is RolloutStatus.ERROR_INFRA: | |
| logs["error"] = ( | |
| f"the generator cut response {completion.request_id} short " | |
| f"(finish_reason={completion.finish_reason})" | |
| ) |
There was a problem hiding this comment.
Reply from claude: Fixed in 9708524: the worker keys the log off next_env_step.status is RolloutStatus.ERROR_INFRA, with neutral text ("the env step returned ERROR_INFRA for response ... (finish_reason=...)"), and the set is now the private _CUT_SHORT_FINISH_REASONS in token_env.py.
| # TODO: convert `parsed.tool_calls` to the dicts `Message.tool_calls` holds: on a full | ||
| # re-render, Qwen3's and GPT-OSS's renderers raise on them, and the rollout ends ERROR_INFRA | ||
| # though the policy made the call. A separate fix, with its own renderer tests. |
There was a problem hiding this comment.
#6098 (open) already fixes this: it stores parsed.tool_calls as ToolCall dicts, so the full re-render stops raising. Link it in the TODO.
The order these two land in matters. On main, this renderer crash makes the rollout ERROR, which trains with error_reward. With only this PR, the crash becomes ERROR_INFRA: the rollout is dropped and the policy is never penalized for the tool call that triggered it. Landing #6098 first (or below this PR in the stack) means that window never opens, and this TODO plus the PR's NOTE can be deleted.
There was a problem hiding this comment.
Reply from claude: Agreed: the open TokenEnv PR that stores tool calls as ToolCall dicts fixes this TODO. Landing it first is the author's call; I flagged it. The TODO stays until then.
|
|
||
| reward: float | ||
| """Final scalar reward for this rollout; assigned to `Rollout.reward`.""" | ||
| reward: float | None |
There was a problem hiding this comment.
No in-repo score_group returns reward=None. Rubric._score_single_rollout always returns a float, so the only producer is the test override in test_rollout_worker.py. ERROR_INFRA is left out by the status check before scoring, not by this field.
If the consumer is a later PR in the stack (#5986?), consider moving this widening, the "rubric" test case and the make_scored_group reward-None branch there. Otherwise, name the in-repo user in the PR description.
There was a problem hiding this comment.
Reply from claude: Fixed in 9708524: nothing in this stack returns a rubric reward of None, so the RubricOutput.reward widening, its test case and the reward-None filter in make_scored_group are reverted; rubric.py matches main. rollout/unscored_rate went with it, since it now always equals rollout/status_rate/error_infra.
adb7171 to
9708524
Compare
|
Claude finished @felipemello1's task in 1m 1s —— View job Approve -- the earlier findings are fixed in 9708524, but please write the empty human-written summary before merging. A maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I checked 9708524 and the earlier findings are fixed. The one item left is the empty human-written summary. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py).
Earlier findings at HEAD
rollouter.py:795, duplicated finish-reason check: resolved. The worker now checks fornext_env_step.status is RolloutStatus.ERROR_INFRA, andtoken_env.py:843keeps_CUT_SHORT_FINISH_REASONSprivate.rubric.py,RubricOutput.reward: float | Nonehad no producer: resolved.rubric.pyis no longer in the diff.make_scored_groupnow filters only onis_trainable(), androllout/unscored_rateis gone. The only rollouts with reward None areERROR_INFRAones. The remaining readers ofRollout.rewardall skip None:compute_rollout_metrics,build_from_groupand the recorder.token_env.py:275, link the TODO to #6098: still open. #6098 is still open againstmain. The author replied that landing it first is their call. I have no new comment on this.- The question about alerting on
error_infra: answered.rollout/status_rate/error_infrais logged for both training and validation, and alerting would be a follow-up.
Must fix
- The "Summary (human-written)" section of the description is still only the template comment. Please write it yourself: 2-5 sentences on the problem, why this approach, and what you checked.
The fix commit adds no new problems. The numerics, callsite and cancellation analysis from the previous review still holds at HEAD.
Not verified: that vLLM at the pinned version actually emits finish_reason="error". No GPU runs were done.
| # return_exceptions: every sibling ends before the controller frees the group's KV | ||
| # cache. A sibling still generating would hold it again, and nothing would free it. |
There was a problem hiding this comment.
i dont see why we need this "group kv cache". My understand about the logic (please correct me if i am wrong) is that every kv cache is associated with a list[rollout_ids].
if len(rollout_ids)>1, we dont release that kv cache.
If every id associated with that kv cache is released, then we dont need the kv cache anymore
In this situation, i dont see why we would need a group level kv cache. Is my understanding wrong? if so, would it make sense to refactor how we hold the cache?
There was a problem hiding this comment.
Reply from claude: Your model is right for the KV blocks: vLLM counts each block's users and frees it at 0.
The group release does two things a rollout's release can't. It drops the policy version the group's prompts are cached under: only the controller knows when the last rollout of a group is done. And under non-sticky routing, it frees held KV that release_session can't find.
So it stays. The TODO "evaluate if we need this group-level release" at InterGeneratorRouter.release_groups keeps your question open. The comment is now 3 plain steps in BaseRolloutWorker.run_group.
| # TODO: for a rollout that Verifiers didn't finish cleanly, mark its infra failures `ERROR_INFRA`, | ||
| # so they aren't trained. Today a failed model call, sandbox or scoring step is ERROR and trains | ||
| # with `error_reward`. Needs Verifiers' error fields sorted into policy and infra failures. |
There was a problem hiding this comment.
do we fix this in this stack?
There was a problem hiding this comment.
Reply from claude: Yes, in this PR. A rollout that fails outside the policy now ends ERROR_INFRA: recorded, not trained. Examples: a sandbox or tunnel error, a setup timeout, or a rollout with no turn.
HarnessError, TaskError and a context overflow still train with error_reward, because the policy can cause them. The full table is in VerifiersRolloutWorker.rollout_status.
| ).to_string(include_turn=False) | ||
| turns: list[RolloutTurn] = [] | ||
| status = RolloutStatus.ERROR | ||
| logs: dict[str, Any] = {} |
There was a problem hiding this comment.
do we have a "logs" equivalent for verifiers? is the mental model the same?
There was a problem hiding this comment.
Reply from claude: Yes, the same model. Both workers fill Rollout.logs, a free-form dict. The rollout recorder saves it, and training never reads it.
The native worker writes only {"error": ...}, on failure. The Verifiers worker always writes the trace id, the task, the stop condition, each error with its traceback, and the phase times.
9708524 to
564ffe6
Compare
|
Reply from claude: @claude please review. Since your last review: this PR now sits on the distributed-workers PRs (same native stack); a rollout with no turn and any failure outside the policy end ERROR_INFRA (not trained); HarnessError and TaskError still train as ERROR; new |
|
Claude finished @felipemello1's task in 3m 1s —— View job Approve -- no new problems at 564ffe6. Please write the human-written summary before merging, and a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems in the rebased commit 564ffe6: the Verifiers status table, the no-turn rule and the 400/422 split agree with each other and with their tests. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py, types.py).
What changed since the last review.
VerifiersRolloutWorker.rollout_statusnow decides who failed fromtrace.last_error. HarnessError, TaskError and ProviderError 400 stayERROR. A setup timeout, any other error, or a failure elsewhere in the episode isERROR_INFRA.- A Verifiers rollout with no turn is now always
ERROR_INFRA. - The generation server answers 400 only for an overlong prompt and 422 for every other bad request.
verifiers/errors/<type>counts are added togroup.metrics.
Example.
Verifiers group of 3 (rewards from the trace; error_reward=0)
r0: trace ok, 5 turns, reward 1.0
r1: trace failed, last_error=SandboxError, 2 turns
r2: trace failed, last_error=HarnessError, 3 turns
base: r1, r2 = ERROR -> both scored with error_reward; advantages +0.67, -0.33, -0.33
PR: r1 = ERROR_INFRA, reward/advantage None, kept for logs
r0, r2 scored and centered on their own mean: advantages +0.5, -0.5
metrics: verifiers/errors/SandboxError=1, verifiers/errors/HarnessError=1
Must fix
- The "Summary (human-written)" section is still only the template placeholder. You said this is on purpose for now. Before merging, please write it yourself in 2-5 sentences: the problem, why this approach, and what you checked.
Details
- No-turn rule. On base, a no-turn rollout was forced to
ERROR, so theelse: turns[-1].env_rewards[...]branch never ran. Now it is forced toERROR_INFRA, which is stillis_error(), so that branch still can't hit an emptyturns. After the rule the status is alwaysERROR_INFRA, so"marking %s", status.namein the first-prompt warning always printsERROR_INFRA. That is harmless. - 400 vs 422. The overlong-prompt check now runs after the body is validated. A malformed body therefore gets 422 before its length is looked at, and no 400 is left for any cause except a prompt that is too long. That keeps the
ProviderError 400 -> ERRORrow safe from config mistakes. - Callsites at HEAD after the rebase. Every
TokenEnv.Config/MessageEnvRolloutWorker.Configin recipes, tests and docs setsmax_rollout_tokens. That includes search_r1, dapo_math (3 sites), slake, geometry3k and alphabet_sort (prod and CI). Therl_grpo_qwen3_6_27b_varlen_perfrebuild picks up that recipe'sseq_len.ERROR_ABORT/error_aborthas no references left. - Builder. With
drop_zero_std_reward_groups, a group of N > 1 left with one scored rollout is dropped as zero-std. Without that option, it trains with advantage 0. Both match the new comment. - Earlier open item. #6098 (tool calls stored as
ToolCalldicts) is still open againstmain. The TODO attoken_env.py:279stays until it lands, as you said.
Not verified: that Verifiers 0.4.0's Trace exposes last_error, and its Error exposes status_code, as rollout_status reads them. The status tests use SimpleNamespace traces, and I couldn't import Verifiers here. If either attribute were missing, every failed trace would raise inside _run_single_rollout and quietly become ERROR_INFRA. Also not verified: that vLLM at the pinned version emits finish_reason="error". No GPU runs were done.
|
Reply from claude: on your unverified item: both attributes exist in Verifiers 0.4.0 and 0.4.1. |
564ffe6 to
efa4efd
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 38s —— View job Approve -- no new problems at efa4efd. Please write the human-written summary before merging, and a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I re-read the full diff at efa4efd and found no new problems. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py, types.py).
The last automated review was at 564ffe6, which this checkout doesn't have, so I couldn't diff the two commits. I reviewed the full diff against felipemello1/distribute/3-least-loaded instead. It matches the PR description and the behavior approved last time.
Example (native worker).
group of 4; env.init() raises for rollout 1; rubric gives rollouts 0, 2, 3 rewards 1, 0, 0
base: rollout 1 = ERROR with no turns -> the builder's "untrainable" check drops all 4
PR: rollout 1 = ERROR_INFRA, logs["error"] = repr(error), reward/advantage None
rollouts 0, 2, 3 are scored and centered on their own mean; the builder trains those 3
Must fix
- The "Summary (human-written)" section is still only the template placeholder. Please write it yourself before merging: 2-5 sentences on the problem, why this approach, and what you checked.
Details
- Earlier unverified item. The last review couldn't confirm that
Trace.last_errorandProviderError.status_codeexist in Verifiers. You citedverifiers/v1/trace.py:658(0.4.0) andverifiers/v1/errors.py:40-42, which answers it. I still couldn't import Verifiers here to confirm it myself. - Raises inside
VerifiersRolloutWorker._run_single_rollout. A wrong trainable-trace count (ValueError) or a non-VerifiersTaskSample(TypeError) now ends each rollout asERROR_INFRA, logged at error level bymake_scored_group. On base,run_groupre-raised and the controller dropped the group. Either way nothing trains, so no numerics change. verifiers/errors/<type>. Each rollout runs its own episode (_verifiers_env_client.runis called once per rollout), so countingverifiers_episode.errorstogether with the trainable trace's errors counts each error once.- Abort path. None of the in-repo generators abort in-flight requests on weight sync. Only SGLang's admission rejections and engine aborts emit
finish_reason="abort". So movingabortfrom a trainedERROR_ABORTto an untrainedERROR_INFRAdoesn't drop rollouts on the normal async path. - The numerics, callsite, and cancellation analysis from the earlier reviews still holds at this HEAD. The no-failure path passes the same rollouts to
score_groupand the advantage estimator as base, and everyTokenEnv.Configsetsmax_rollout_tokens. - #6098 (the TODO at
token_env.py:278) is still open. You said earlier that the landing order is your call.
Not verified: Verifiers attribute names (Verifiers isn't importable here). vLLM emitting finish_reason="error" at the pinned version. No GPU runs.
efa4efd to
c717efb
Compare
|
Reply from claude: @claude please review. The stack was reordered (6112 -> 6116 -> 6117 -> 6118 -> 6119 -> 6113 -> 6157 -> 6114), and 6113 now picks hosts with one flag per role ( |
9aa831c to
4f6de89
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 25s —— View job Approve -- no new problems at 4f6de89; please write the human-written summary before merging (one small docstring fix is inline), and a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. I found no new problems at 4f6de89. The diff (9 files, +564/-99) is the native-worker change I approved at 9aa831c, with main's builder checks applied to the trainable rollouts. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py, types.py, token_env.py).
This checkout doesn't contain 9aa831c, so I couldn't diff the two commits. I re-read the full diff against felipemello1/distribute/1-pool-size instead.
Example (native worker).
group of 4; generate raises on turn 0 of rollout 0; rubric gives rollouts 1-3 rewards 1, 0, 0
base: rollout 0 = ERROR, no turns -> num_groups_dropped_untrainable drops all 4
PR: rollout 0 = ERROR_INFRA, reward/advantage None, logs["errors"] = [{type, message, traceback}]
rollouts 1-3 are centered on their own mean (+0.67, -0.33, -0.33) and trained
rollout/status_rate/error_infra = 0.25, rollout/errors/ConnectionError = 1
Must fix
- The "Summary (human-written)" section is still only the template placeholder. Please write it yourself: 2-5 sentences on the problem, why this approach, and what you checked.
Should consider
torchtitan/rl/rollout/types.py:427-- theRollout.logsdocstring says the dict has theerror_entryshape. Onlylogs["errors"]holdserror_entrydicts. A one-line docstring fix is inline.
Details
- No-failure path. When every rollout is trainable,
rollouts_to_trainis the whole group. The no-completion group drop,is_zero_std, the per-rollout loop and theadvantagestats then all reduce to base.make_scored_grouppasses the same rollouts toscore_groupand the advantage estimator, andasyncio.timeout(None)matches the oldtimeout is Nonebranch. - Cut-short completions.
TokenEnv.stepreturnsERROR_INFRAbefore parsing, so anabort/errorfinish can't becomeERROR_PARSE. The partial turn is still appended, for the recorder, but it is never trained. An empty completion takes the same path, so the builder's no-completion group drop no longer fires for the native worker. - Error entries. The
finish_reason_*/empty_completion/ step-timeout entries have no"traceback".log_failed_rolloutreads it with.get, so they don't raise aKeyError.env.init()outputs default toerrors=[]. - Tests. The two builder tests fail on base: an
ERROR_INFRArollout with no turn hits base's group drop, and base'spstdevover one reward is 0 only through the full-group path. The worker test runs the realrun_group->make_scored_grouppath. - Still open from before. #6098 (the TODO at
token_env.py:285). You said the landing order is your call.
Not verified: whether vLLM at the pinned version emits finish_reason="error". No CPU or GPU tests were run here.
| """Rollouter-specific debug record, with `error_entry` shape, e.g. why the rollout failed. | ||
| Saved with the rollout by `RolloutSampleRecorder`; not used for training.""" |
There was a problem hiding this comment.
The docstring says logs has the error_entry shape. It doesn't. logs is a free-form dict, and only logs["errors"] is a list of error_entry-shaped dicts. The Verifiers worker writes other keys next to it (trace id, task, phase times), and log_failed_rollout prints those keys separately. compute_rollout_metrics and log_failed_rollout both rely on the "errors" key, so the docstring should name it:
| """Rollouter-specific debug record, with `error_entry` shape, e.g. why the rollout failed. | |
| Saved with the rollout by `RolloutSampleRecorder`; not used for training.""" | |
| """Rollouter-specific debug record, e.g. why the rollout failed. `logs["errors"]`, if set, is a | |
| list of `error_entry` dicts, counted in `<prefix>/errors/<type>`. Saved with the rollout by | |
| `RolloutSampleRecorder`; not used for training.""" |
There was a problem hiding this comment.
Reply from claude: Fixed in 655f61f: the docstring is your text.
4f6de89 to
655f61f
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 37s —— View job Approve -- 655f61f fixes the last open item and adds no new problems. Please write the human-written summary before merging; a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 655f61f fixes the last open item (the Rollout.logs docstring), and I found no new problems. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py, types.py, token_env.py).
Earlier findings at HEAD
types.py:427, theRollout.logsdocstring: resolved. It now says that onlylogs["errors"]holdserror_entrydicts, and that they are counted in<prefix>/errors/<type>.
Example (native worker, unchanged).
group of 4; generate raises on turn 0 of rollout 0; rubric gives rollouts 1-3 rewards 1, 0, 0
base: rollout 0 = ERROR, no turns -> num_groups_dropped_untrainable drops all 4
PR: rollout 0 = ERROR_INFRA, reward/advantage None, logs["errors"] = [{type, message, traceback}]
rollouts 1-3 are centered on their own mean (+0.67, -0.33, -0.33) and trained
rollout/status_rate/error_infra = 0.25, rollout/errors/ConnectionError = 1
Must fix
- The "Summary (human-written)" section is still only the template placeholder. Please write it yourself: 2-5 sentences on the problem, why this approach, and what you checked.
Should consider
- Description, NOTE "until the Verifiers PR (3/3)": the stack is 4 PRs, and the other NOTEs say 3/4.
Details
- Since 4f6de89. This checkout doesn't contain 4f6de89, so I re-read the full diff against
felipemello1/distribute/1-pool-size(9 files, +565/-99). The only change from what I approved is the one-line docstring. - No-failure path. When every rollout is trainable,
rollouts_to_trainis the whole group, so the builder's checks andmake_scored_groupreduce to base. - Still open from before. #6098 is the TODO at
token_env.py:285. You said the landing order is your call.
Not verified: whether vLLM at the pinned version emits finish_reason="error". No CPU or GPU tests were run here.
655f61f to
c2f7464
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 41s —— View job Approve -- no new problems at c2f7464. Please write the human-written summary before merging; a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems at c2f7464. A maintainer still needs to review it, because it touches core RL code (rollouter.py, training_sample_builder.py, types.py, token_env.py).
Since the last review (655f61f). This checkout doesn't contain 655f61f, so I re-read the full diff against felipemello1/distribute/1-pool-size (9 files, +565/-99, the same size as before). The code matches what I approved, including the Rollout.logs docstring fix. The description's NOTE now says "Verifiers PR (3/4)", which fixes the 3/3 vs 3/4 mismatch I pointed out.
Example (native worker, unchanged).
group of 4; generate raises on turn 0 of rollout 0; rubric gives rollouts 1-3 rewards 1, 0, 0
base: rollout 0 = ERROR, no turns -> num_groups_dropped_untrainable drops all 4
PR: rollout 0 = ERROR_INFRA, reward/advantage None, logs["errors"] = [{type, message, traceback}]
rollouts 1-3 are centered on their own mean (+0.67, -0.33, -0.33) and trained
rollout/status_rate/error_infra = 0.25, rollout/errors/ConnectionError = 1
Must fix
- The "Summary (human-written)" section is still only the template placeholder. Please write it yourself: 2-5 sentences on the problem, why this approach, and what you checked.
Details
- No-failure path. When every rollout is trainable,
rollouts_to_trainis the whole group. The builder's no-completion drop,is_zero_std, the per-rollout loop and theadvantagestats then reduce to base, andmake_scored_grouppasses the same rollouts toscore_groupand the advantage estimator. - All untrainable. For a group of 1,
is_zero_stdis False andpstdevis never called on an empty list. For a group of 2 or more, the group counts as zero-std. - Still open from before. #6098 is the TODO at
token_env.py:285. You said the landing order is your call.
Not verified: whether vLLM at the pinned version emits finish_reason="error". No CPU or GPU tests were run here.
| # TODO: a group left with 10 of 16 rollouts gives its prompt about 10/16 of a full group's | ||
| # weight, since the loss averages over tokens. Reweight them, or make the trainer count the | ||
| # rollouts it trains. Not done yet: either one changes the loss of every recipe. |
There was a problem hiding this comment.
Didn't get this part.
- In the past, number of rollouts per training batch was invariant -> now it's variant. This has the advantage of not dropping trainable signals, but has the disadvantage of changing training dynamics. Is this common practice by other libraries?
- Even on main, the number of tokens change all the time, and one reward signal is scattered evenly onto all tokens, whose count is already variant. Changing the number of rollouts / rewards doesn't seem to affect this fact. What's the principle here?
There was a problem hiding this comment.
Reply from claude: You're right on the second point, so the TODO is gone (191455d).
- Principle: a rollout trains only if its reward says something about the policy. One that failed outside it (sandbox down, generator unreachable) is left out, and its siblings are centered on their own mean. Main trained it as ERROR, with
error_rewardor the rubric's score. - Weight is the loss's job, and the loss is a token mean (
dapo.py, divided by the global loss-token count). A prompt already weighs its share of the batch's trained tokens, which moves every step with completion length. 10 of 16 rollouts left weighs like 16 shorter ones, so reweighting only this case would single out one cause. - Rollouts per batch already vary on main: a later empty turn drops one rollout (torchtitan/rl/trainer/training_sample_builder.py:193-200). Samples per batch vary too: branching splits a rollout into several samples, and a sample with no loss token is dropped.
- Peers, one rollout failed outside the policy:
- drop it, train the rest:
- prime-rl skips errored traces (src/prime_rl/orchestrator/algo/base.py:12-25) and centers the rest on their own mean (src/prime_rl/orchestrator/algo/grpo.py:66-112).
- AReaL, by default (
drop_incomplete_group=False): areal/infra/remote_inf_engine.py:246-271. - verl's V1 sampler: a failed prompt's usable rows still train (verl/trainer/ppo/v1/replay_buffer.py:333-344).
- drop the whole group:
- SkyRL: skyrl/integration/harbor/harbor_generator.py:75-125.
- AReaL with
drop_incomplete_group=True.
- zero its loss, keep reward 0 in the group mean:
- drop it, train the rest:
- Dropping the group keeps the count fixed but loses the siblings: at 1% failures and groups of 32, 27% of groups.
- If we want every group to weigh the same, prime-rl's
loss_aggregation="prompt"(packages/prime-rl-configs/src/prime_rl/configs/algorithm.py:201) does it in the loss, for every cause at once.
| self._training_dataloader.load_state_dict(state_dict) | ||
|
|
||
|
|
||
| def log_failed_rollout(rollout: Rollout) -> None: |
There was a problem hiding this comment.
should this be private util function
There was a problem hiding this comment.
Reply from claude: I'd keep it public. Main already has a public log_failed_rollout in the Verifiers example (torchtitan/rl/examples/verifiers/rollouter.py:546), which its test imports. #6183 (3/4) replaces that one with an import of this one, so both workers log failures the same way. The repo rule is not to import another module's _private names, so a private name here would turn public two PRs later. It is also the helper a custom BaseRolloutWorker calls at the end of each rollout, as both stock workers do. No change (still public at 191455d).
| def is_truncated(self) -> bool: | ||
| return self.value in _TRUNCATED | ||
| return self in ( | ||
| RolloutStatus.TRUNCATED_LENGTH, | ||
| RolloutStatus.TRUNCATED_PROMPT_TOO_LONG, | ||
| RolloutStatus.TRUNCATED_MAX_TURNS, | ||
| ) |
There was a problem hiding this comment.
just to make sure -- these are still trainable, right?
There was a problem hiding this comment.
Reply from claude: Yes. is_trainable() (types.py:247-250) is False only for ERROR_INFRA here. Later PRs add FIRST_PROMPT_TOO_LONG (2/4) and ERROR_UNKNOWN (3/4), and DROPPED (the Verifiers 0.4.1 PR), and none of them is a TRUNCATED_* status. TRUNCATED_LENGTH, TRUNCATED_MAX_TURNS and TRUNCATED_PROMPT_TOO_LONG are scored and trained as on main. After the rebase onto main, the rubric also subtracts truncation_penalty from them when it is set. Line 237 ends is_truncated, whose set is unchanged: it only moved from a module-level frozenset into the method. No change (same lines at 191455d).
|
@claude review my review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. I checked @tianyu-l's three comments against the code at HEAD. They are all right: the first points to a TODO that should be deleted, and the other two need small answers or edits. They don't uncover any new correctness problem. A maintainer still needs to review the core RL changes.
On @tianyu-l's comments
training_sample_builder.py:157, the number of rollouts per batch: correct on both points.- Rollouts per batch. On base this count is fixed in practice. The Batcher fires after
num_prompts_per_train_steptrainable groups (batcher.py:228-233), and each of those groups trains all of its rollouts. The only exceptions on base are the rare drops for an empty completion or no valid tokens. With this PR, a group trains only its trainable rollouts, so the count can now vary. - What base does instead. Base doesn't keep that signal. In the native worker, a rollout that raised became
ERRORand trained witherror_rewardor the rubric's score. If it had no turn at all, base dropped the whole group. - Precedent. DAPO's "overlong filtering" also masks single samples out of the loss while their siblings train (DAPO paper, Sec. 3.4). I couldn't check other libraries' code from here.
- The principle. The loss is a token mean:
dapo.py:128divides byglobal_loss_token_counts. A prompt's weight is already its share of the batch's trained tokens, and that share changes every step with completion length. Dropping rollouts is one more source of the same variance, not a new one. So the TODO's "reweight" idea would treat this one cause differently from all the others. Delete the TODO and the matching follow-up bullet in the description. Details are inline.
- Rollouts per batch. On base this count is fixed in practice. The Batcher fires after
rollouter.py:286, makelog_failed_rolloutprivate: partly correct. In this PR, nothing outsiderollouter.pycalls it, so the CLAUDE.md naming rule says it should be private. But #6183 (3/4) imports it intoexamples/verifiers/rollouter.pyandtest_verifiers.py, and CLAUDE.md also forbids importing another module's_privatenames. Since the two PRs land together, keeping it public is fine. @felipemello1, please say so in the thread.types.py:237, are theTRUNCATED_*statuses still trainable: yes.is_trainable()(types.py:247-250) is False only forERROR_INFRA. All threeTRUNCATED_*statuses are still scored, and they gettruncation_rewardif it is set (rubric.py:133), the same as on base.ERROR,ERROR_PARSEandERROR_TIMEOUTstill train too.
Must fix
- The "Summary (human-written)" section is still only the template placeholder. @felipemello1, please write it yourself.
torchtitan/rl/trainer/training_sample_builder.py:155-157-- delete the reweight TODO (item 1 above, inline).- Reply to @tianyu-l's three threads.
Not verified: any RL library's code other than torchtitan's.
| # TODO: a group left with 10 of 16 rollouts gives its prompt about 10/16 of a full group's | ||
| # weight, since the loss averages over tokens. Reweight them, or make the trainer count the | ||
| # rollouts it trains. Not done yet: either one changes the loss of every recipe. |
There was a problem hiding this comment.
Following up on @tianyu-l's question above: this TODO describes how a token-mean loss always behaves, and nothing here is broken. dapo.py:128 divides the summed loss by global_loss_token_counts. So every trained token gets the same weight, and a prompt's weight is its share of the batch's trained tokens. That share already changes from group to group with completion length, branching, and the per-rollout drops that are on base too (num_rollouts_dropped_empty_completion, num_samples_dropped_no_valid_tokens). A group that trains 10 of its 16 rollouts is the same as a group whose completions are shorter. "Reweight them" would make this one cause of variance behave differently from all the others.
I'd delete the TODO, and also the matching "Reweight a group that lost rollouts" follow-up in the description:
| # TODO: a group left with 10 of 16 rollouts gives its prompt about 10/16 of a full group's | |
| # weight, since the loss averages over tokens. Reweight them, or make the trainer count the | |
| # rollouts it trains. Not done yet: either one changes the loss of every recipe. |
There was a problem hiding this comment.
Reply from claude: Done in 191455d: the TODO is deleted. The reasoning is in the reply to Tianyu's comment on the same line.
c2f7464 to
191455d
Compare
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 48s —— View job Approve -- 191455d deletes the reweight TODO and adds no new problems, and the replies to @tianyu-l's three threads match the code. Please write the human-written summary before merging; a maintainer still needs to review the core RL changes. Review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems at 191455d. It deletes the reweight TODO, which @tianyu-l and I asked for, and the replies to all three of @tianyu-l's threads match the code. A maintainer still needs to review, because this touches core RL code (rollouter.py, training_sample_builder.py, types.py, token_env.py).
Earlier findings at HEAD
training_sample_builder.py:153, the reweight TODO: resolved. It is deleted, and the matching follow-up bullet is gone from the description. In its place, the description explains why a token-mean loss already weights prompts unevenly.- @tianyu-l,
rollouter.py:300, shouldlog_failed_rolloutbe private: answered. It stays public because #6183 imports it, and the repo rule forbids importing another module's_privatenames. Nothing else in this PR calls it. - @tianyu-l,
types.py:237, areTRUNCATED_*still trainable: answered, correct.is_trainable()(types.py:247-250) is False only forERROR_INFRA. After the rebase, the rubric still subtractstruncation_penaltyfrom truncated rollouts (rubric.py:158-160), as on main.
Example (native worker, unchanged).
group of 4; generate raises on turn 0 of rollout 0; rubric gives rollouts 1-3 rewards 1, 0, 0
base: rollout 0 = ERROR, no turns -> num_groups_dropped_untrainable drops all 4
PR: rollout 0 = ERROR_INFRA, reward/advantage None, logs["errors"] = [{type, message, traceback}]
rollouts 1-3 are centered on their own mean (+0.67, -0.33, -0.33) and trained
rollout/status_rate/error_infra = 0.25, rollout/errors/ConnectionError = 1
Must fix
- The "Summary (human-written)" section is still only the template placeholder. @felipemello1, please write it yourself: 2-5 sentences on the problem, why this approach, and what you checked.
Details
- What I re-read. This checkout doesn't contain c2f7464, so I re-read the full diff against
felipemello1/distribute/1-pool-size(9 files, +562/-99). It is the change I approved before, minus the 3-line TODO. - Rebase onto main's
truncation_penalty._score_single_rolloutruns only on trainable rollouts (make_scored_group), soERROR_INFRAnever gets a penalty orerror_reward.ERROR,ERROR_PARSEandERROR_TIMEOUTstill geterror_rewardif it is set, as on main. - Stale references.
ERROR_ABORT,error_abort, the oldlogs["error"]key and the module-level_TRUNCATED/_ERRORsets have no references left in the repo. - No-failure path. When every rollout is trainable,
rollouts_to_trainis the whole group, so the builder's checks andmake_scored_groupreduce to base. - Still open from before. #6098 is the TODO at
token_env.py:285. You said the landing order is your call.
Not verified: whether vLLM at the pinned version emits finish_reason="error". I ran no CPU or GPU tests here.
191455d to
106b507
Compare
…a prompt too long (3/4) (#6183) <!-- Reviewers need to be convinced, not just informed. Delete sections you don't need. Agents: follow .claude/skills/pr-description/SKILL.md. Never fill in the Summary. --> ## 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:** `VerifiersRolloutWorker` maps each trace to who failed, by error type and status code, never by message text. It uses the native worker's mechanism: `_run_single_rollout` always returns a `Rollout` and logs a failure once, and `make_scored_group` scores only trainable rollouts.  <!-- pr-image drawn at 2784265 --> ```text Verifiers trace, checked in this order status trained first model call got a 400 (prompt >= max_rollout_tokens) FIRST_PROMPT_TOO_LONG no no turn (e.g. the sandbox didn't start) ERROR_INFRA no a deadline passed (agent, finalize, scoring) ERROR_TIMEOUT yes, with error_reward ok, but its episode failed (e.g. a judge's trace) ERROR_INFRA no ended on a 400 on a later model call TRUNCATED_PROMPT_TOO_LONG yes failed, last error HarnessError or TaskError ERROR yes, with error_reward failed, any other error ERROR_INFRA no (e.g. SandboxError, a 502) ok COMPLETED yes hit max_turns TRUNCATED_MAX_TURNS yes a completion hit max_tokens, or a Verifiers token budget TRUNCATED_LENGTH yes (max_input_tokens, max_output_tokens, max_total_tokens) truncated for another reason (e.g. compaction_failed) ERROR_UNKNOWN no then: any trainable status above, but no trainable token ERROR_INFRA no ``` **Problem** 1. The Verifiers worker marks any failed trace `ERROR`, and a trace with no turn `ERROR`. 2. `ERROR` trains. Many of these failures aren't the policy's: a `SandboxError`, a 502, a sandbox that never started. 3. It finds an overlong first prompt by matching "maximum context length" in an error message. And the generation server answers 400 to a missing header or a malformed body too, so a 400 can't mean "prompt too long". 4. In a 20-step Terminal-Bench run, 116 of 17,504 rollouts (0.66%) failed outside the policy. Main marked each one `ERROR` (Results below). **Solution** 1. `rollout_status` follows the table. A new error type defaults to "not trained". Verifiers' token budgets stay `TRUNCATED_LENGTH`, like a completion that hit `max_tokens`. Any other truncation, e.g. `compaction_failed`, is now `ERROR_UNKNOWN` and doesn't train. 2. A trace with model calls but no trainable token has no turn. It becomes `ERROR_INFRA`, unless its status is already untrainable, with a `no_trainable_token` entry in `Rollout.logs["errors"]`. So it never trains, and its 0.0 never enters the group mean. 3. `_run_single_rollout` catches into `ERROR_INFRA` and calls the generic `log_failed_rollout`. Verifiers' own log helper is deleted. `run_group` uses an `asyncio.TaskGroup` and `make_scored_group`. 4. The generation server answers 400 only for a prompt with no room for an output token. A missing header or a malformed body gets 422, so a config mistake can't look like a prompt that's too long. 5. The `BaseRolloutWorker.score_group` and `run_group` docstrings no longer say where rewards and advantages are set. 6. A rollout with no turn no longer drops its group: #6116 makes the builder skip untrainable rollouts before its group drop, and this PR makes the rollout untrainable. **Results** ```text 20-step Terminal-Bench run, Qwen3.5-27B, 17,504 rollouts, stop reasons from its logs: ERROR_INFRA: 100 SandboxError + 16 setup_timeout = 116 (0.66%) still train: 398 prompt too long (after a turn: TRUNCATED_PROMPT_TOO_LONG), 167 HarnessError (ERROR) the 600 error rollouts the recorder kept, by turns: no turn: 17 SandboxError, 16 setup_timeout (on main each was scored ERROR and its whole group was dropped) with turns: 368 prompt too long, 137 HarnessError, 62 SandboxError ``` Among the recorded error rollouts, no HarnessError or prompt-too-long one had zero turns, so the no-turn rule changed none of them. You may ask: why do `HarnessError` and `TaskError` train? In an earlier 50-step Terminal-Bench run, 73 of 106 harness errors were the agent's own `pkill -f` killing its harness. A `TaskError` can mean the agent broke the box its grader runs in. You may ask: why list the policy's errors, not the infra ones? A new Verifiers error type then defaults to "not trained". NOTE: `ERROR` and `ERROR_TIMEOUT` still train at `error_reward` (0.0 in both Verifiers recipes). To leave them out of training, add them to the tuple in `RolloutStatus.is_trainable`. A TODO above `RolloutStatus` marks making this configurable. New W&B keys: `rollout/status_rate/error_unknown`, `rollout/errors/no_trainable_token`. **Follow up** - [ ] Tell policy-caused failures from infra ones inside `HarnessError`, `TaskError` and the deadlines. Blocked: Verifiers' error types say where a rollout broke, not who caused it. - [ ] Allow more than one trainable trace per episode, which happens in e.g. Verifiers' `best_of_n` env (n attempts per episode). **Test plan:** both suites (Verifiers 0.4.0: 1045 passed, 1 skipped; without Verifiers: 961 passed, 7 skipped). New: `test_rollout_status_says_who_failed` (one case per table row; 23 cases), `test_a_rollout_with_no_turn_never_trains_and_each_failure_is_logged` (5 cases; `no_trainable_token` checks Solution 2 and its log entry), `test_a_rollout_whose_verifiers_call_raises_is_error_infra_and_logged`, `test_a_rollout_that_raises_fails_its_group_after_its_siblings_stop`, `test_generation_server_answers_422_to_a_bad_request`; `test_generation_server_requires_group_id` now expects 422. `pre-commit` passes. `pyrefly` skips `torchtitan/rl` and `tests` (`project-excludes` in `pyproject.toml`), so it checks none of this PR's files. Co-authored-by: Felipe Mello <[email protected]>
Summary (human-written)
Agent details
TLDR: A rollout's status now says who failed, and only the policy's failures train. In the native worker, a rollout that fails outside the policy (
ERROR_INFRA: an exception, or a completion the generator cut short or returned empty) stays in its group, counted by metrics, with its errors inRollout.logs. It is never scored or trained. The rest of the group trains, centered on its own mean. Such a rollout with no completion token no longer drops its group. First of 4: TokenEnv's first prompt, the Verifiers worker and the builder's per-rollout drops follow.Problem
MessageEnvRolloutWorker._run_single_rolloutmarks any exceptionERROR.TokenEnvmarks an aborted completionERROR_ABORT.ERRORreads as the policy's fault: the rubric scores it (or gives iterror_reward, if set), and it enters the group mean.build_from_groupdrops the whole group if any rollout has no completion token. In a 20-step Terminal-Bench run, 33 of the 600 error rollouts the recorder kept had no turn (17SandboxError, 16 setup timeouts). Each one dropped its whole group.Solution
RolloutStatus.is_trainable()is False forERROR_INFRA._run_single_rolloutalways returns aRollout. An exception becomesERROR_INFRA, with its type, message and traceback inRollout.logs["errors"]. A failed rollout is logged once, bylog_failed_rollout.make_scored_grouponly scores and centers the trainable rollouts.run_groupruns the rollouts in anasyncio.TaskGroup: a raise past_run_single_rolloutis a bug, and it cancels the siblings before the group fails.TrainingSampleBuilder.build_from_groupskips a rollout whose status doesn't train, then runs main's checks on the rest. A group of 2 or more with fewer than 2 scored rollouts counts as zero-std, e.g. 3 of 4 areERROR_INFRAand the one left has advantage 0.TokenEnv: a completion cut short (finish reasonabortorerror) or with no tokens isERROR_INFRA. Its failures go toTokenEnvOutput.errors. Only the step deadline isERROR_TIMEOUT.ERROR_ABORTis deleted.rollout/status_rate/<status>for every terminal status, androllout/errors/<type>andvalidation/errors/<type>per error inRollout.logs["errors"].ERROR_INFRA(item 5), so the builder skips it, and its siblings train.drop_zero_std_reward_groupsand the loss are as on main.rollout_reward/group_zero_std_fracand the zero-std drop read the rewards of the trainable rollouts. The per-rollout drops and their metrics are in the builder PR (4/4).ERROR_INFRAbefore the Verifiers PR (3/4), so the builder sees all its rollouts, as on main: a rollout with no turn still drops its group. It only gains the metrics of item 6.You may ask: why set the status in
_run_single_rollout, not inmake_scored_group? One place sets a rollout's status and logs its failure. Scoring only reads statuses.You may ask: can users add a status? Not yet: a
StrEnumwith members can't be subclassed. A TODO sits aboveRolloutStatus.You may ask: why not reweight a group that lost rollouts? The loss is a token mean, so a prompt already weighs its share of the batch's trained tokens, which changes every step with completion length. A group that trains 10 of its 16 rollouts weighs like a group with shorter completions.
NOTE: validation now leaves untrainable rollouts out of
validation_reward.NOTE: a tool call in the history can make
TokenEnv's full re-render raise. That rollout isERROR_INFRA, though the policy caused it. It's a renderer bug on main; a TODO marks it.NOTE: a reward function that raises (e.g. a judge that is down) still fails its whole group. A TODO in
make_scored_groupmarks it.NOTE: until the Verifiers PR (3/4), the Verifiers worker keeps its own
log_failed_rolloutand its main behavior.NOTE: Lands with #6182 and #6183: until #6183, a Verifiers rollout with no turn still drops its group, as on main. Until #6182, a native rollout whose first prompt doesn't fit is still scored as
TRUNCATED_PROMPT_TOO_LONG.NOTE:
ERRORandERROR_TIMEOUTstill train: the rubric scores them, or gives themerror_rewardif set (0.0 in every recipe that sets it). To leave them out of training, add them to the tuple inRolloutStatus.is_trainable. A TODO aboveRolloutStatusmarks making this configurable.Follow up (each one is a TODO in the code)
rollout/types.py.ERRORandERROR_TIMEOUTout of training.make_scored_group, e.g. a length penalty; the advantage estimator and the group filters become some of them.Rollout.rewardper token, e.g. to give each turn of a multi-turn rollout its own reward.parsed.tool_callsto the dictsMessage.tool_callsholds, so the full re-render doesn't raise.RolloutError) in their ownerrorsfield onRolloutandTokenEnvOutput, next to a free-formlogs.Test plan
pre-commitpasses.pyreflyskipstorchtitan/rlandtests(project-excludesinpyproject.toml), so it checks none of this PR's files.New tests, each failing without its change:
test_a_failed_rollout_is_kept_logged_once_and_left_out_of_the_advantage(generate call raises, aborted generation)test_a_response_that_fails_to_parse_is_error_parse_unless_the_generator_cut_it_shorttest_only_the_step_deadline_is_error_timeouttest_build_from_group_skips_an_unscored_rollout_but_trains_its_siblings(ERROR_INFRAwith no turn, and after a turn)test_build_from_group_drops_a_group_left_with_one_scored_rollout(num_groups_dropped_zero_std)test_compute_rollout_metrics_records_a_rate_per_statustest_compute_rollout_metrics_counts_each_error_type