Repository navigation
[rl] SGLang generator: abort a request whose logprob turns NaN or -inf - #6418
felipemello1 wants to merge 4 commits into
Conversation
SGLang lets a NaN logprob through and clamps -inf to its dtype's min. The engine now aborts such a request while it runs and returns it with finish reason abort and no tokens, so no such logprob reaches the trainer.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 4m 56s —— View job Approve, see the review. |
There was a problem hiding this comment.
Verdict: Approve -- the problem is real on main, the generator owns it, and the change stays inside SGLangEngine's output collector. The items below are suggestions; none blocks the merge.
What this PR does. _OutputCollector flags a request when a logprob in an increment is NaN or <= finfo(bf16).min. That floor also catches SGLang's clamped -inf, which main's isfinite masks in dapo.py:114 / batcher.py:968 let through. step() then aborts the flagged request in SGLang. It waits first if another admitted id extends the flagged one, because SGLang's abort matches ids by prefix. The request comes back as finish_reason="abort" with no tokens. Downstream already handles that: TokenEnv maps "abort" to ERROR_INFRA (token_env.py:237), and the Verifiers server rejects any finish reason other than stop/length (generation_server.py:267).
Example.
request "s/request=1", NaN logits from token 5, max_tokens 200
main: decodes 200 garbage tokens, NaN logprobs; the trainer masks them; the env reads the garbage as the reply
this PR: 1st increment (token 50) flagged -> abort_request -> ~1 more decode step
-> FinishedRequest(token_ids=[], finish_reason="abort") -> rollout marked ERROR_INFRA
"s/request=10" also running -> request=1 waits (keeps decoding) until request=10 finishes
Should consider
tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:491-- the dict hides a request that finishes twice. Assert unique ids (suggestion inline).tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:429-- the float32-min subtest repeats the bfloat16-min branch.- When the vLLM half lands, define the "non-finite logprob -> abort, no tokens" rule once in
torchtitan/rl/generator/(the floor and the check), not once per engine. Both engines returnFinishedRequest, so the final-result mapping could live in one place, with each engine adding only its early abort.
Questions
torchtitan/rl/generator/sglang/engine.py:898-910-- could settingto_finishon the admittedReqreplaceAbortReqand remove the prefix wait? (inline)
Details
- Overlapping work. Searched "SGLang generator", "NaN logprob" and "sglang/engine.py". #6379 (top-k logprobs) and the log-padding PR touch
_OutputCollector, as the description says. #6018 (output_sink) renamessend_outputtoreceive, which is a trivial rebase. Nothing supersedes this PR. - TP/DP. Logits are all-gathered before the logprobs are computed, so every TP rank sees the same values and the same
_admittedset and aborts the same requests in the same order. Under attention DP, each DP rank's scheduler aborts only its own requests. The existinghas_unfinished_requests/_finishedlogic already assumes every rank receives the outputs. - Retraction and reset-on-load. A flagged request that is retracted to the waiting queue is aborted from there and comes back through the
AbortReqbranch, which clears the tokens. A request that finishes before it is aborted is dropped from_requests_to_abort, because it is no longer in_non_finite. - Prefix collisions are reachable. Verifiers runs a session's requests concurrently (
generation_server.py:241), so.../request=1and.../request=10can both be in flight. - Cost. One Python comparison per logprob per increment, next to the existing
extend. Negligible. param_dtypeisLiteral["bfloat16", "float32"](config/configs.py:115). So the fp16 clamp (-65504), which would pass the floor, can't occur.
Not verified: SGLang's abort_request, AbortReq.matches and logprob clamping (SGLang's source wasn't available here). These rest on the author's GB300 run, and the TP 2 Varlen run is still pending in CI.
Before merge: fill in the human-written summary.
| finished = {} | ||
| while self.engine.has_unfinished_requests(): | ||
| for result in self.engine.step(): | ||
| finished[result.request_id] = result |
There was a problem hiding this comment.
This is the first in-repo caller of scheduler.abort_request on a running request, and the collector has two ways to finish an aborted request: the AbortReq branch of send_output and the abort-reason increment in _receive_tokens. If SGLang reported the abort both ways, step() would return the request twice and the dispatcher's _rank0_outstanding_generations.pop(...) would raise a KeyError on the second one. Because the dict here overwrites duplicates, the test can't catch that. One line fixes it:
| finished = {} | |
| while self.engine.has_unfinished_requests(): | |
| for result in self.engine.step(): | |
| finished[result.request_id] = result | |
| finished = {} | |
| while self.engine.has_unfinished_requests(): | |
| for result in self.engine.step(): | |
| self.assertNotIn(result.request_id, finished) | |
| finished[result.request_id] = result |
There was a problem hiding this comment.
Reply from claude: Fixed in dfb71cb: the loop now asserts that no request finishes twice before it stores the result.
for result in self.engine.step():
self.assertNotIn(result.request_id, finished)
finished[result.request_id] = result| torch.finfo(torch.bfloat16).min, | ||
| torch.finfo(torch.float32).min, |
There was a problem hiding this comment.
The float32-min subtest covers the same branch as the bfloat16-min one. Both fail logprob > _LOGPROB_FLOOR, and bfloat16's min is the boundary case (== the floor). Each subtest is another 200-token generation on the 2-GPU Varlen class. Consider keeping just NaN and torch.finfo(torch.bfloat16).min.
There was a problem hiding this comment.
Reply from claude: Fixed in dfb71cb: the poisons are NaN and torch.finfo(torch.bfloat16).min. float32's min fails the same logprob > _LOGPROB_FLOOR check, and bfloat16's min is the value closest to the floor.
# NaN, and bfloat16's min: of the values SGLang clamps a -inf logprob to (with
# bfloat16 or float32 logits), the one nearest the floor.
for poison in (float("nan"), torch.finfo(torch.bfloat16).min):| to_abort, waiting = [], [] | ||
| for request_id in self._requests_to_abort: | ||
| # Finished meanwhile: the collector already returned it. | ||
| if request_id not in self._non_finite: | ||
| continue | ||
|
|
||
| extended = any( | ||
| other != request_id and other.startswith(request_id) | ||
| for other in self._admitted | ||
| ) | ||
| (waiting if extended else to_abort).append(request_id) | ||
| self._requests_to_abort = waiting | ||
| return to_abort |
There was a problem hiding this comment.
Question (unverified, I couldn't read SGLang's source here): the prefix wait exists only because AbortReq matches ids by prefix. The collector already holds each admitted request's Req (self._admitted[rid][0]), and add_requests already depends on SGLang reporting a Req whose to_finish is a FINISH_ABORT. If abort_request does nothing more than set req.to_finish = FINISH_ABORT(...) for a running request, then setting it on that one Req would abort exactly that request. That would delete the waiting list and the extension scan (~15 lines), and test_abort_spares_request_whose_id_extends_the_aborted_one with them. It would also stop a flagged request from decoding to max_tokens while it waits. Does abort_request do more than that for a running request (e.g. under overlap scheduling or for retracted requests)? If it does, a one-line comment saying why the public abort path is needed would help.
There was a problem hiding this comment.
Reply from claude: abort_request does more than finish the Req, so I kept the public path and added the one-line reason in dfb71cb.
At the pinned SGLang (851642ade), Scheduler.abort_request:
- drops matching requests from every request list, the waiting queue included (
managers/scheduler.py:6058-6059). That is how a flagged request that was retracted back to the waiting queue gets aborted. Settingto_finishon itsReqwould leave it queued. - finishes a running request with
req.request_finish(FINISH_ABORT()), not a bareto_finish(:6062-6076).
# SGLang runs one more decode step for an aborted request, then finishes it.
# abort_request also drops a retracted request from SGLang's waiting queues.
for request_id in self._output_collector.take_requests_to_abort():
scheduler.abort_request(AbortReq(rid=request_id))The prefix wait stays: it comes from AbortReq.matches, which that path uses.
…'s min; why the public abort path
|
Reply from claude: All three suggestions are in dfb71cb, plus a TODO at On "define the non-finite rule once when the vLLM half lands": agreed. The vLLM half is still a draft on the author's fork. Whichever lands second can move the floor and the "abort, no tokens" mapping into @claude please review |
|
Claude finished @felipemello1's task in 46s —— View job Approve: all three earlier items are fixed in dfb71cb, and nothing new came up. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- dfb71cb resolves all three items from the last review, and nothing new turned up. The merge commit (ce7a2d3) doesn't touch either file in this PR.
What this PR does. _OutputCollector flags a request when a logprob in an increment fails logprob > finfo(bf16).min, which catches NaN and SGLang's clamped -inf. step() aborts the flagged request through scheduler.abort_request. If another admitted request's id extends the flagged one, the abort waits, because AbortReq matches ids by prefix. The request then comes back as finish_reason="abort" with no tokens or logprobs.
Example.
"s/request=1": NaN logits from token 5, max_tokens 200
main: decodes 200 garbage tokens; the env reads them as the reply
this PR: flagged at its first increment (token 50) -> abort_request
-> FinishedRequest(token_ids=[], finish_reason="abort") -> TokenEnv: ERROR_INFRA
Resolved since the last review
- Duplicate finishes: the test loop now runs
assertNotIn(result.request_id, finished)before it stores each result, so a request reported twice (once by theAbortReqbranch, once by the abort-reason increment) fails the test. - The redundant float32-min subtest is gone. The poisons are now NaN and bfloat16's min, the boundary value.
- The
to_finishquestion: the author saysabort_requestalso removes a retracted request from the waiting queue and callsrequest_finish(SGLang 851642ade,managers/scheduler.py:6058-6076). A bareto_finishwould leave a retracted request queued, so the public path and its prefix wait stay. The comment atengine.py:735records why. - Defining the "abort, no tokens" rule once for both engines: done as a
TODOatengine.py:79, to be resolved by whichever of the SGLang and vLLM halves lands second. That fits, since the vLLM half is still a draft on the author's fork.
Details
- Re-reviewed
git diff c7a8664..dfb71cbon the two PR files (+5/-7) and re-read_OutputCollectorat HEAD. The early-finish branch in_receive_tokenspops_admittedand_non_finitethe same way theAbortReqbranch does.take_requests_to_abortskips ids that already finished, so a request can't be both aborted and finished. - Overlap search is unchanged from the last review: #6379 (top-k logprobs), the log-padding PR and #6018 (output_sink) touch
_OutputCollector. The description already names the rebase conflicts. Nothing supersedes this PR.
Not verified: the SGLang behavior behind the abort path (abort_request dropping waiting requests, AbortReq.matches, the logprob clamp). SGLang's source isn't in this checkout, so these rest on the author's citations and their GB300 run. The 2-GPU Varlen run at TP 2 is still pending in CI. This PR changes only RL generator code; a maintainer still needs to review it.
Before merge: fill in the human-written summary.
Summary (human-written)
Agent details
TLDR:
SGLangEngineaborts a running request once one of its sampled tokens has a NaN or -inf logprob, and returns it with finish reason "abort" and no tokens. Main's trainer drops NaN logprobs from the loss, but two cases get past it: SGLang turns a -inf logprob into a finite number, and a request with NaN logits decodes garbage up tomax_tokens, which a multi-turn env reads as the policy's reply. This is the SGLang side of the vLLM engine's NaN abort, a draft on the author's fork: "[rl] vLLM generator: abort a request whose summed logprob turns NaN or -inf (1/3)".Problem
trainer/losses/dapo.py,effective_loss_mask;trainer/batcher.py,target_mask).OutputLogprobProcessor.compute_logprobs): -3.4028e38 with float32 logits, -3.3895e38 with bfloat16 ones. That value is finite, so it passes main's masks and enters the loss at the clamped log-ratio.SGLANG_SANITIZE_NAN_LOGITS,SGLANG_ENABLE_NAN_LOGITS_CHECK) are off by default.Solution
_OutputCollectorchecks each increment of logprobs that SGLang sends:logprob > finfo(bfloat16).min. NaN fails every comparison, and both clamped values sit at or below that floor.step()aborts it withscheduler.abort_request(AbortReq(rid=...))after the event loop iteration.AbortReq.matches). So a flagged request waits while another admitted request's id extends it, as in.../request=1and.../request=10of one Verifiers session.NOTE: the check sees a request every
SGLANG_FORCE_STREAM_INTERVALtokens (50 by default), when SGLang sends an increment. So a request runs up to ~50 tokens past the NaN before it stops. The vLLM engine checks every step.NOTE:
SamplingConfigallows only top_p 1. With SGLang's default Gumbel sampling, top_p 1 never callstorch.multinomial, which asserts on NaN probabilities. SGLang calls it for top_p < 1, for top_k, or withSGLANG_OPT_USE_GUMBEL_SAMPLE=0.NOTE: the aborted turn's KV stays in SGLang's radix cache, under the session, until
release_sessions. Its prompt was cached at prefill, so a retry of the same call reuses that prompt's KV: if the NaN came from a bad cached prefix, the retry can hit it again. Its reply can't be reused: the rollout gets no tokens, so no later prompt contains the reply. So this PR doesn't set SGLang'sReq.skip_radix_cache_insert, which would keep the reply out of the cache. The vLLM series uncaches the aborted turn's blocks (its session KV holder and CPU offload connector).NOTE: not tested at TP > 1 or DP > 1 (one GPU here). The new test first runs at TP 2 in CI, in the Varlen class.
NOTE: this PR conflicts with "[rl] SGLang generator: top-k logprobs for score centering" in
_OutputCollector: that PR moves each request's partial tokens and logprobs into a_PartialRequest. Whichever lands second rebases. It merges cleanly with "[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward". It also conflicts with "[rl] SGLang generator: log the CUDA graph padding share and HiCache-loaded prompt tokens" in_OutputCollector.__init__andstep().Test plan
TestSGLangBitwiseParityVarlen.test_aborts_request_with_non_finite_logprob(new), once per poison value: NaN and bfloat16's min. Of SGLang's two clamped -inf values (bfloat16's and float32's min), bfloat16's is the one nearest the floor. It also checks that no request finishes twice. It sends two prompts withmax_tokens200 and poisons the first increment of one request. The poisoned request returns "abort" with no tokens, after fewer than 100 tokens were sent. The other request is not aborted and has tokens.TestSGLangBitwiseParityVarlen.test_abort_spares_request_whose_id_extends_the_aborted_one(new): the same with ids.../request=1(poisoned) and.../request=10(healthy). The healthy one is not aborted; the poisoned one returns "abort" with no tokens.TestSGLangBitwiseParityKDA(random debug weights; this box has one GPU), with the KDA class's own tests: 8 passed. After the last change, the two abort tests again: 2 passed, 2 subtests passed (81 s). Log: "generator: aborting request .../request=1 after 50 generated tokens: a logprob is not finite (NaN or -inf)". With the prefix guard removed (extended = False), the second test fails: the healthy.../request=10returns "abort". Their home, the 2-GPU Varlen class at TP 2 (real Qwen3-0.6B), first runs in CI.max_tokens200. A device flag in the logits wrap (captured by the graphs) turns every logit to NaN after the 5th engine step. At temperature 1 and at temperature 0 the request returns "abort" with 0 tokens after 53 engine steps (one increment of 50 tokens). A healthy request right after each case runs all 200 tokens.pytest tests/rl/unit_tests/cpu: 771 passed, 8 skipped, 2 failed. The 2 fail on main too:test_kv_offload_coordination.py::test_terminal_cleanup_preserves_block_identity, 2 cases.torchtitan/rl/): all hooks pass.