Skip to content

[rl] SGLang generator: abort a request whose logprob turns NaN or -inf - #6418

Draft
felipemello1 wants to merge 4 commits into
mainfrom
felipemello1/sgl203/s3-abort-non-finite-logprobs
Draft

felipemello1 wants to merge 4 commits into
mainfrom
felipemello1/sgl203/s3-abort-non-finite-logprobs

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: SGLangEngine aborts 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 to max_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)".

On main, a request with NaN logits decodes 200 garbage tokens, and a -inf logprob is clamped to a finite -3.39e38 that enters the loss. This PR checks each 50-token increment against finfo(bfloat16).min and aborts the request, which returns finish reason abort and no tokens.

Problem

  1. Main drops non-finite generator logprobs from the loss (trainer/losses/dapo.py, effective_loss_mask; trainer/batcher.py, target_mask).
  2. SGLang clamps a -inf logprob to its dtype's min (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.
  3. SGLang lets a NaN logprob through: its NaN checks (SGLANG_SANITIZE_NAN_LOGITS, SGLANG_ENABLE_NAN_LOGITS_CHECK) are off by default.
  4. With NaN logits at top_p 1, SGLang's sampler takes the argmax of NaN probabilities and keeps going, with no error: in the probe below it sampled 50 tokens from NaN logits before this PR's abort stopped it.

Solution

  1. _OutputCollector checks 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.
  2. A flagged request that is still running goes on a list. step() aborts it with scheduler.abort_request(AbortReq(rid=...)) after the event loop iteration.
  3. SGLang's abort matches every request id that starts with the given one (AbortReq.matches). So a flagged request waits while another admitted request's id extends it, as in .../request=1 and .../request=10 of one Verifiers session.
  4. When SGLang finishes the flagged request, the collector returns it with finish reason "abort" and no tokens or logprobs, whichever way SGLang finishes it (an abort, or its last increment).
  5. One WARNING per abort, on attention TP rank 0, prefixed with the generator's name. Every TP rank samples the same tokens, so all ranks abort the same requests.
  6. Healthy requests take the same path as before.

NOTE: the check sees a request every SGLANG_FORCE_STREAM_INTERVAL tokens (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: SamplingConfig allows only top_p 1. With SGLang's default Gumbel sampling, top_p 1 never calls torch.multinomial, which asserts on NaN probabilities. SGLang calls it for top_p < 1, for top_k, or with SGLANG_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's Req.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__ and step().

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 with max_tokens 200 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.
  • Ran both on one GB300 through a 1-GPU subclass of 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=10 returns "abort". Their home, the 2-GPU Varlen class at TP 2 (real Qwen3-0.6B), first runs in CI.
  • Real NaN logits, once (a one-off probe, not in the PR): Qwen3.5-0.8B, breakable graphs, one 300-token prompt, max_tokens 200. 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.
  • pre-commit on the changed files (pyrefly excludes torchtitan/rl/): all hooks pass.

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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 27, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, 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 -- 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 return FinishedRequest, 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 setting to_finish on the admitted Req replace AbortReq and 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) renames send_output to receive, 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 _admitted set and aborts the same requests in the same order. Under attention DP, each DP rank's scheduler aborts only its own requests. The existing has_unfinished_requests / _finished logic 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 AbortReq branch, 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=1 and .../request=10 can both be in flight.
  • Cost. One Python comparison per logprob per increment, next to the existing extend. Negligible.
  • param_dtype is Literal["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.

Comment on lines +488 to +491
finished = {}
while self.engine.has_unfinished_requests():
for result in self.engine.step():
finished[result.request_id] = result

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 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:

Suggested change
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

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 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

Comment on lines +428 to +429
torch.finfo(torch.bfloat16).min,
torch.finfo(torch.float32).min,

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 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.

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

Comment on lines +898 to +910
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

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.

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.

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: 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:

  1. 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. Setting to_finish on its Req would leave it queued.
  2. finishes a running request with req.request_finish(FINISH_ABORT()), not a bare to_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.

@felipemello1

felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Reply from claude: All three suggestions are in dfb71cb, plus a TODO at _LOGPROB_FLOOR in 95554ee. The two test changes are applied, and a comment now says why the public abort path stays. Details are in the threads.

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 torchtitan/rl/generator/, so each engine keeps only its early abort. The TODO at _LOGPROB_FLOOR (95554ee) says so.

@claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 -- 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 the AbortReq branch, 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_finish question: the author says abort_request also removes a retracted request from the waiting queue and calls request_finish (SGLang 851642ade, managers/scheduler.py:6058-6076). A bare to_finish would leave a retracted request queued, so the public path and its prefix wait stay. The comment at engine.py:735 records why.
  • Defining the "abort, no tokens" rule once for both engines: done as a TODO at engine.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..dfb71cb on the two PR files (+5/-7) and re-read _OutputCollector at HEAD. The early-finish branch in _receive_tokens pops _admitted and _non_finite the same way the AbortReq branch does. take_requests_to_abort skips 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.

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