Skip to content

[rl] Verifiers: top-k logprobs for score centering - #6380

Open
tianyu-l wants to merge 1 commit into
sglang-topk-logprobsfrom
verifiers-topk-logprobs
Open

tianyu-l wants to merge 1 commit into
sglang-topk-logprobsfrom
verifiers-topk-logprobs

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

Score centering (#6378) needs the generator's top-k logprobs for every trained token. With the Verifiers rollouter, tokens reach the trainer through Verifiers' traces, and Verifiers keeps only each completion's token ids and sampled-token logprobs (TurnTokens): an OpenAI top_logprobs field in the response is dropped. So today score centering raises for Verifiers rollouts.

Example. A two-turn Verifiers rollout with score centering (k = 2):

turn 1: prompt 5 tokens, completion [12, 13]   -> generator top-k [[12, 5], [13, 6]]
turn 2: prompt 9 tokens, completion [14]       -> generator top-k [[14, 7]]
before: ValueError "Verifiers rollouts do not carry the generator's top-k logprobs yet"
after:  RolloutTurn 1 gets rows [[12, 5], [13, 6]], RolloutTurn 2 gets [[14, 7]]

What changed

(The approach and most of the code are from #5760.)

  • GenerationServer records each generation's top-k rows in the rollout's VerifiersGenerationMetadata, which already carries the policy versions and metrics Verifiers drops, keyed by (prompt length, completion token ids). A second generation with the same key and the same rows (a seeded retry) is accepted; one with different rows returns HTTP 500, since the rows could not be told apart.
  • run_group opens its group on the generation server and closes it when the group's rollouts end. A request joins its group's sessions before it generates, so closing drops the metadata and request counts of every session the traces didn't pop: a retried attempt, a run that raised, a request that failed or was still generating. A closed group's late request answers 409 and records nothing: once a rollout raises, the env server may keep running its cancelled siblings. Before, such metadata stayed until close(); with top-k rows (8 * k bytes per token) that would grow rollout-worker memory.
  • VerifiersRolloutWorker sends num_topk_logprobs with the sampling params (the server requires it, so a missing value can't silently return no rows), and trace_to_rollout_turns attaches to each trained node the rows of the generation with its prompt length and sampled tokens, sliced per trainable span; a node with no matching generation raises.
  • Removes [rl] Score centering: generator top-k logprobs and ScoreCentering for PolicyGradientLoss #6378's temporary raise for Verifiers rollouts.

Alternatives considered

  • Return the rows in the OpenAI top_logprobs field: Verifiers 0.4 drops it; carrying them in its trace needs an upstream Verifiers change.
  • Key by generation order within the session: breaks when Verifiers retries or branches.
  • Key by the full prompt tokens (would allow two equal completions): needs a Verifiers run to check that each trace's prompt tokens equal the request's (TODO in the code).

Testing

  • tests/rl/unit_tests/cpu/test_verifiers.py (with verifiers==0.4.0): 68 passed. New cases from [rl] Score centering: generator top-k logprobs + ScoreCenteringLoss #5760: rows recorded per generation and attached per node and trainable span across turns, the missing-generation error, and the required num_topk_logprobs sampling param. New here: a seeded retry with equal rows is accepted while different rows get 500, closing the group drops a session no trace popped and refuses its late request (409), and a group whose rollout raised still closes.
  • pytest tests/rl/unit_tests/cpu: see the stack's earlier PRs; this PR touches only the Verifiers example.

Known issues / follow-ups

Stacked on #6379. Next: DPPO score centering (#6384). Co-authored with @felipemello1 (Co-authored-by trailer), whose #5760 implemented this.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 11s —— View job


Request changes: top-k rows leak in sessions that are never popped, and seeded retries hit the duplicate-key 500. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- top-k rows now ride on per-session metadata that leaks for retried or failed Verifiers runs, so rollout-worker memory grows without bound under score centering.

What this PR does. Verifiers drops OpenAI top_logprobs, so the generation server keeps each generation's top-k rows in VerifiersGenerationMetadata, keyed by (prompt length, completion token ids). trace_to_rollout_turns finds each trained node's rows by that same key (the position of the first masked token, plus the masked tokens) and slices them for each trainable span. A missing key raises. A duplicate key on the server returns 500. The rollouter now forwards num_topk_logprobs, and the server requires it.

Example.

request 1: prompt len 5, completion [12, 13] -> server stores (5, (12, 13)) -> rows R1
request 2: prompt len 9, completion [14]     -> server stores (9, (14,))    -> rows R2
trace node A: mask starts at offset 5, masked tokens [12, 13] -> R1
trace node B: mask starts at offset 9, masked tokens [14]     -> R2
before: ValueError for any Verifiers rollout with num_topk_logprobs > 0
after:  turns carry R1 and R2; a node with no matching key raises

Must fix

  1. torchtitan/rl/examples/verifiers/rollouter.py:332 -- sessions that are never popped (a retried attempt, or a run that raises) now each keep 8 * k bytes per generated token until close(). Drop each group's leftover sessions when run_group exits (inline).
  2. torchtitan/rl/examples/verifiers/generation_server.py:294 -- with a seed, a retried request has the same key every time and gets 500 every time; before this PR the retry succeeded. Reject only when the rows differ, which also removes the dict copy (inline).

Should consider

  • PR description: "attached per node and span across turns and branches" is broader than the new tests. They cover one branch with one span per node. The row = sum(node.mask[:start]) offset for a second span within one node, and the skip for a node already trained in an earlier branch, are untested. Reword the description, or add a second span and a second branch to _two_turn_trace (no new test needed).
Details
  • The key logic only goes wrong loudly. Suppose the trace's prompt length differs from the request's, or a node's mask leaves out a token the generator produced. Then no key matches and trace_to_rollout_turns raises. If gap tokens in a mask were not generated at all (inserted by Verifiers), the masked-token key and the row offset both match the generator's completion. I found no path where it silently attaches the wrong rows.
  • Leak size: at k=128, rows are 1 KiB per token. Before this PR, leaked metadata was versions plus folded metrics, independent of length.
  • Duplicate check with equal rows: attaching either row set is correct whatever the prompts were, so the only ambiguous case is equal key with different rows.

Not verified: how Verifiers 0.4 retries after an HTTP 500 or a client timeout (I couldn't inspect the installed package). A maintainer still needs to review.

Comment on lines +332 to +335
# TODO: an attempt Verifiers retried has no trace here, so its held KV waits for the
# group's release. The generation server could record each rollout's session ids and
# release those too.
# release those too. Its metadata, with any top-k rows, also stays until `close()`, as
# does every session of a `run` that raises (no trace ids then).

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's leak gets much bigger with this PR. Before, a session nobody popped held its policy versions and folded metrics, a few hundred bytes. Now it also holds every generation's top-k rows: 8 * k bytes per token, so 1 KiB per token at k=128. A Verifiers attempt that was retried, or a run that raises (harness error, timeout, context overflow), never pops its sessions. One failed 64k-token agentic rollout then keeps ~64 MiB in the rollout worker until close(). In a long run with a steady error rate, worker memory keeps growing until it OOMs.

Smallest fix: the server already gets group_id on every request, so it can record session_ids_by_group[group_id]. Then run_group drops whatever is left for that group in a finally once the TaskGroup exits, since every successful rollout has popped its own traces by then. That also gives the existing KV-release TODO the session list it needs.

Comment on lines +294 to +306
key = (len(prompt_token_ids), tuple(completion.token_ids))
if key in topk_by_generation:
return web.json_response(
{
"error": f"session {session_id}: two generations share prompt length "
f"{key[0]} and completion tokens, so their top-k rows can't be told apart"
},
status=500,
)
topk_by_generation = {
**topk_by_generation,
key: (completion.topk_token_ids, completion.topk_logprobs),
}

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.

With a seed, this rejects a retry that would be harmless. run_group gives every generation in a rollout the same seed (sampling.seed + rollout_id, rollouter.py:280). Say Verifiers retries a request whose first attempt reached the server, for example after a client timeout. The retry has the same prompt and the same seed, so it gets the same completion and the same key. The server returns 500 and Verifiers retries again, and it fails the same way every time. The rollout ends as ERROR_INFRA, where before this PR the retry succeeded.

The ambiguity only matters when the rows differ. If two generations have the same key and the same rows, attaching either one is correct, whatever their prompts were. So reject only when the rows differ, and mutate the dict in place (the old metadata object is replaced right below anyway):

            key = (len(prompt_token_ids), tuple(completion.token_ids))
            rows = (completion.topk_token_ids, completion.topk_logprobs)
            existing = topk_by_generation.get(key)
            if existing is not None and not all(map(np.array_equal, existing, rows)):
                return web.json_response(...)  # as now
            topk_by_generation[key] = rows

This also makes the TODO in trace_to_rollout_turns less pressing.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 33s —— View job


Approve (both earlier must-fix items are resolved; two small items remain): see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. Both earlier must-fix items are fixed at HEAD (60d7034). The only new items are a documentation gap and one unverified edge case.

What changed since the last review.

seeded retry, same key, same rows      -> before: 500 every time; now: 200 (rows kept)
same key, different rows               -> still 500
retried attempt / run that raises      -> before: metadata + rows held until close();
                                          now: run_group's `finally` drops the group's sessions

Earlier findings

  1. Resolved: rollouter.py:291 -- run_group now calls drop_group_sessions(group_id) in a finally, and the server records session_ids_by_group. test_generation_server_records_topk_per_generation covers the success path ("retried-attempt" is dropped). The extended TaskGroup test covers the failure path.
  2. Resolved: generation_server.py:327 -- a duplicate key is rejected only when the rows differ, and the dict is updated in place. The test checks the seeded retry (200) and the different-rows case (500).
  3. Resolved (should-consider): the description no longer says "and branches".

Must fix

  1. generation_server.py:57 -- the new glibc TODO reports ~4.5 KiB held per in-flight token at k=128 (4.5x the rows). Neither the PR description nor losses/README.md mentions it. Add it to "Known issues" and next to the README's transport-cost line (inline).

Should consider

  • rollouter.py:291 -- unverified: a generation request that arrives after the drop (a cancelled sibling whose env-server run keeps going) puts the group back in session_ids_by_group. Nothing drops it again before close() (inline).

Not verified: I couldn't run test_verifiers.py in this environment, and Verifiers 0.4's server-side cancellation behavior is unchecked. A maintainer still needs to review.

]
finally:
# Every finished rollout popped its traces' sessions; drop what is left.
self._generation_server.drop_group_sessions(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.

Unverified: on the failure path, a request can reach the server after this drop. When one rollout raises, the TaskGroup cancels its siblings' run calls. If the Verifiers env server keeps running a cancelled rollout, or a generation is still in flight, _handle_generate_request later calls session_ids_by_group.setdefault(group_id, ...) again. No later drop_group_sessions call clears that group, so its rows stay until close(). Aiohttp does not cancel handlers when the client disconnects (the default since 3.8).

It is much smaller than the leak this PR fixed, but if the env server does keep running cancelled rollouts, one way to close it is for the server to ignore requests for groups that were already dropped. If Verifiers cancels server-side, a one-line comment here saying so is enough.

Comment on lines +57 to +58
# TODO: glibc keeps freed top-k arrays: at k=128 a rollout worker held ~4.5 KiB per in-flight token (rows: 1 KiB).
# Setting M_MMAP_THRESHOLD to 256 KiB in rollout workers fixed it in a CPU repro; not yet checked in a run.

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 is new since the last review and it reports a real memory cost: ~4.5 KiB per in-flight token held at k=128, which is 4.5x the 1 KiB of rows. The PR description doesn't mention it, and neither does the "Transport costs 8 * k bytes per generated token" line in losses/README.md. Please add it to "Known issues / follow-ups" so a reviewer can weigh it, and note it next to that README line, since a user sizing k from the README would underestimate rollout-worker memory.

@tianyu-l
tianyu-l force-pushed the verifiers-topk-logprobs branch from 60d7034 to 3abdbbb Compare November 25, 2026 07:13
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 17s —— View job


Approve (every earlier item is fixed; one small README suggestion remains): see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- every item from the last review is fixed at HEAD (3abdbbb), and the new open/close group logic adds no must-fix problems.

What changed since the last review. drop_group_sessions is now an open_group / close_group pair. The server refuses requests for a group that isn't open (409), and it checks twice: before generating, and again after generating, in case the group closed while the request ran.

Example.

run_group(group 7):  open_group(7)
  rollout 0 raises -> TaskGroup cancels rollout 1, but the env server keeps running it
  finally:           close_group(7) drops every session no trace popped
  rollout 1's next request -> before: recorded again, kept until close()
                              now:    409, nothing recorded
  a request already generating when close_group ran -> 409 after generating, nothing recorded

Earlier findings

  1. Resolved: the glibc memory cost is now under "Known issues" in the description and next to the transport-cost line in losses/README.md.
  2. Resolved (should-consider): requests that arrive after the group is dropped are refused at generation_server.py:367 and :378. test_generation_server_records_topk_per_generation covers the before-generation path (late-sibling -> 409).

Should consider

  • torchtitan/rl/examples/verifiers/README.md:62 (not in the diff) -- step 7 says the GenerationServer "keeps the call's policy version and generator metrics: the trace has no field for them". It now also keeps each generation's top-k rows (when num_topk_logprobs > 0) until the group closes. Add "and top-k rows" so the walkthrough matches the code.
Details
  • open_group resets session_ids_by_group[group_id], so it assumes no two concurrent groups on one worker share an id. That already holds: training ids are dataset indices, validation ids count down from -1 (controller.py:681), and release_groups relies on the same assumption. If ids ever did collide, the failure is loud (409s, failed rollouts), not silent.
  • On the after-generation 409 path, and on the existing 500/502 paths, request_counts[session_id] was already incremented. The session isn't added to the group's set, so close_group doesn't pop that counter. It is one int per affected session until close(), which is negligible.

Not verified: I didn't run test_verifiers.py. A maintainer still needs to review.

@tianyu-l
tianyu-l force-pushed the verifiers-topk-logprobs branch from 3abdbbb to 3a9eb1e Compare November 25, 2026 07:43
@tianyu-l
tianyu-l marked this pull request as ready for review November 25, 2026 07:55
@tianyu-l

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 28s —— View job


Approve (no correctness problems at 8f21ee5; the empty human-written summary still needs filling in): see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. At HEAD (8f21ee5) I found no correctness problems. The remaining items are a description gap and one doc line.

What this PR does. Verifiers drops OpenAI top_logprobs, so the GenerationServer keeps each generation's top-k rows in VerifiersGenerationMetadata, keyed by (prompt length, completion token ids). trace_to_rollout_turns looks up each trained node by the same key and slices the rows for each trainable span. run_group opens its group on the server and closes it in a finally. Closing drops every session no trace popped, and requests that arrive after the group closed get 409. The server now requires num_topk_logprobs in the sampling params.

Example.

prompt [10]         -> completion [11]      server stores (1, (11,))    -> R1
prompt [10, 11, 12] -> completion [13, 14]  server stores (3, (13, 14)) -> R2
node 1: mask [F, T] at offset 0    -> key (1, (11,))    -> turn 1 rows R1
node 2: mask [F, T, T] at offset 2 -> key (3, (13, 14)) -> turn 2 rows R2
seeded retry, same key, same rows  -> 200, rows kept
same key, different rows           -> 500
before: ValueError for any Verifiers rollout with num_topk_logprobs > 0

Must fix

  1. PR description -- "Summary (human-written)" is empty. Per CONTRIBUTING.md and .claude/CLAUDE.md, the author writes that section; please fill it in before merging.

Should consider

  • torchtitan/rl/examples/verifiers/README.md:62 (not in the diff, still open from the last review) -- step 7 says the GenerationServer "keeps the call's policy version and generator metrics". It now also keeps the top-k rows when num_topk_logprobs > 0, until the trace pops them or the group closes. Add "and top-k rows" so the walkthrough matches the code.
Details
  • Row slicing is exact. The key requires a node's masked tokens to equal the generator's completion tokens. So row = sum(node.mask[:start]) indexes the generator's rows one to one, even when one node has several spans.
  • A node trained in an earlier branch has its mask zeroed before any(mask), so it gets no lookup and no rows.
  • No silent path: if num_topk_logprobs > 0 but a turn carries no rows (say, a generator returned topk_token_ids=None), batcher.py:1012 raises on the row-count mismatch.
  • num_topk_logprobs reaches the server the same way as torchtitan_group_id: through VerifiersSamplingConfig into sampling_params. The existing 422/503 tests that skip open_group fail before the group check, so they are unaffected.

Not verified: I didn't run test_verifiers.py (this needs verifiers==0.4.0). A maintainer still needs to review.

@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: image

Verifiers rollouts used to reach the batcher with 0 top-k rows and stop the run, and now the generation server keeps the rows under a key of prompt length and completion ids, each trace node rebuilds the same key, and rows no trace took are dropped when the group ends.

@tianyu-l
tianyu-l force-pushed the verifiers-topk-logprobs branch from 26af3f4 to d641ad1 Compare November 26, 2026 04:08

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/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants