Repository navigation
[rl] generator: SGLang reuses a rollout group's prompt KV - #5918
Conversation
|
@claude review |
|
Claude finished @tianyu-l's task in 3m 19s —— View job Approve -- please address the items below before merging (one must-fix: requests held for a leader that SGLang aborts are never released). See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. This works around a real, measured SGLang gap (tracked upstream with a TODO) with about 45 lines of logic. The one must-fix is a one-line change to the release condition so held requests can't hang. A maintainer still needs to review.
What this PR does. add_requests keeps the first queued request for each (cache salt, prompt) in SGLang's waiting queue. It takes later requests with the same key out of the queue and holds them. step() puts them back with ReqList.join once the first request has prefilled, so they hit its prompt KV in the radix cache. Linear-attention models skip all of this.
Example.
add_requests([g7/s0..s15]) (same prompt, same salt)
before: one prefill batch computes 16 x 1024 prompt tokens (0% cached)
after: waiting queue = [g7/s0], held = [g7/s1..s15]
step(): prefill s0 -> its KV is cached -> join s1..s15
next prefill: s1..s15 each recompute only the last page (93.7% cached)
Must fix
torchtitan/rl/generator/sglang/engine.py:561-- held requests are released only if the leader prefilled or got afinished_reason. A leader that SGLang drops through itsAbortReqpath (which_OutputCollector.send_outputalready handles) leaves its followers held forever, sohas_unfinished_requests()never turns False. Release when the collector no longer tracks the leader. Which SGLang paths trigger this is unverified; details inline.
Should consider
torchtitan/rl/generator/sglang/engine.py:500-- addreq.priorityto the key, so a validation or older-group request is never held behind a newer group's leader that SGLang hasn't scheduled yet.torchtitan/rl/generator/sglang/README.md:77-- note in the support-table row that linear attention models don't get the reuse.
Details
- Gate: the problem is real (measured: 0% / 59% cached before, 93.7% after). The fix sits at the engine adapter, which is the layer that owns SGLang scheduling here. The upstream issue is linked in a TODO. vLLM gets this behavior natively, so this isn't a one-sided design. The alternatives (
lpm, dropping priority scheduling, a warmup request per group) are covered in the description. - I checked these edge cases and found no other problems:
- Overlap scheduling: followers are released one iteration later, after
pop_and_process. - Chunked prefill: the leader's
output_idsappear only after its last chunk. load_model_state_dictwith reset: held requests own no KV, so flushing is safe. A leader prefilled in the in-flight batch releases its followers on the nextstep(), after the flush. They then recompute the prompt, which costs some speed but is correct.- TP determinism: leaders are picked in waiting-queue order, which is the same on every rank.
- Overlap scheduling: followers are released one iteration later, after
- Test: extending
test_trainer_vs_sglang_decodeinstead of adding a new test is the right call. The negative check in the description shows the assertion fails without holding.
Not verified: which pinned-SGLang paths drop a waiting request through AbortReq without setting finished_reason; the ReqList.join semantics.
| # prompt's KV; queue the requests held for it (see add_requests). | ||
| released = [] | ||
| for key, (leader, followers) in list(self._awaiting_prefill.items()): | ||
| if leader.output_ids or leader.finished(): |
There was a problem hiding this comment.
This release condition only covers a leader that prefilled (output_ids) or got a finished_reason (finished()). SGLang has a third way to drop a request: _OutputCollector.send_output handles an AbortReq sent for a request that leaves the waiting queue without ever being scheduled. On that path nothing sets req.finished_reason. So if a leader leaves SGLang that way, its followers stay in _awaiting_prefill forever. has_unfinished_requests() then returns True forever, and the engine loop (and _generate in the test) spins. Which SGLang paths can trigger this (waiting-queue timeout, max_queued_requests set through extra_server_args, ...) is unverified. But the collector's AbortReq branch exists because SGLang reports some aborts that way.
Smallest fix: release when the collector no longer tracks the leader. It drops a request from _admitted on every finish and abort:
| if leader.output_ids or leader.finished(): | |
| if leader.output_ids or leader.rid not in self._outputs._admitted: |
(or give _OutputCollector a small is_admitted(rid) method rather than reading its _admitted.)
There was a problem hiding this comment.
Checked against the pinned SGLang: every path that drops a queued or prefilling request sets req.finished_reason before it sends the AbortReq, so leader.finished() already covers it.
- Waiting-queue aborts (
SGLANG_REQ_WAITING_TIMEOUT, client aborts):abort_request->_abort_waiting->request_retirer.abort_queued, which callsreq.finish_outside_step(...)first. - Queue full (
max_queued_requests), for both the incoming request and an evicted lower-priority one:_abort_unavailable->abort_queued, same. - A chunked prefill aborted mid-prefill:
prepare_abort->finish_outside_step.
Only two paths send AbortReq without it:
- Retract's "unresumable" abort in
pause_generation, which applies only to aninput_embedsrequest that has already sent output. The engine never buildsinput_embedsrequests, and a leader with output has already released its followers. - dLLM validation, which rejects a request before it enters the waiting queue, so it never becomes a leader.
So I kept the condition. Reading _OutputCollector._admitted would tie the release to a private field of the collector to cover a case that can't happen here.
| held = set() | ||
| # In admission order, so every TP rank picks the same leaders. | ||
| for req in queued.values(): | ||
| key = (req.cache_salt, tuple(req.origin_input_ids)) |
There was a problem hiding this comment.
The key doesn't include priority, so a request can be held behind a lower-priority leader. Example: reset_kv_cache_on_model_state_dict_load=True (salt None) or the same min_policy_version. Group 9's request for prompt P is admitted and is still waiting behind groups 0..8. Then a validation request (priority -1) or a group-2 request for the same P arrives. It is held until group 9's leader gets scheduled, even though SGLang would have run it first and it can preempt. That breaks the "groups still run oldest first" claim in the README. Within one rollout group, priorities are always equal, so adding req.priority to the key costs nothing for the intended case:
| key = (req.cache_salt, tuple(req.origin_input_ids)) | |
| key = (req.priority, req.cache_salt, tuple(req.origin_input_ids)) |
(and update the _awaiting_prefill type annotation and its comment.)
There was a problem hiding this comment.
Done: the key is now (priority, cache salt, prompt). The parity test now puts its two equal prompts in one rollout group (_generate gives equal prompts one group_id), as a rollout group's samples are.
| | Tensor parallelism | Supported; outside batch-invariant mode, the model's TP all-reduces run on SGLang's TP all-reduce (custom all-reduce) instead of NCCL | | ||
| | CUDA graphs (decode and prefill), overlap scheduling, chunked prefill | Supported | | ||
| | Priority scheduling by rollout group | Supported | | ||
| | Prompt KV reuse within a rollout group | Supported; see below | |
There was a problem hiding this comment.
This row reads as supported for every model, but GDN/KDA models don't hold requests and reuse 0% of the shared prompt. Say so in the table, so someone scanning it doesn't expect reuse for Qwen3.5 or Kimi K3:
| | Prompt KV reuse within a rollout group | Supported; see below | | |
| | Prompt KV reuse within a rollout group | Supported for softmax attention; not for linear attention (GDN, KDA), see below | |
|
@claude review again |
|
Claude finished @tianyu-l's task in 46s —— View job Approve: all earlier items are resolved and the new commit introduces no new problems. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- every item from the earlier review is resolved, and the new commit introduces no new problems. A maintainer still needs to review.
Earlier items
- Must fix, held requests never released after a leader abort (
engine.py:562): resolved by the author's analysis. In the pinned SGLang, every path that drops a waiting or prefilling request callsfinish_outside_stepbefore sendingAbortReq, soleader.finished()covers it. The two exceptions (an unresumable retract of aninput_embedsrequest, and dLLM validation) can't affect a leader here. Keeping the condition is the right call. - Priority in the hold key (
engine.py:501): fixed. The key is now(priority, cache_salt, prompt), and the annotation and comment are updated. - README support-table row: fixed. It now names linear attention (GDN, KDA) as not reusing the prompt.
New commit (222bc8d)
_generatesetsgroup_id=prompt_ids.index(ids), so the two equal prompts intest_trainer_vs_sglang_decodeshare one priority and still exercise holding. Nothing else is affected: no other test passes duplicate prompts. The shared prompt (prompt_ids[0][::-1]) is not cached bytest_sglang_decode_batch_invariance, which runs first by name order, so thenum_cached_tokens > 0check comes only from holding.
Not verified: the pinned-SGLang abort paths (traced by the author; SGLang isn't installed in this checkout) and the GPU parity runs.
222bc8d to
6e88949
Compare
6e88949 to
acc2670
Compare
acc2670 to
7bb5cf1
Compare
5b0262a to
d0075d2
Compare
d0075d2 to
05d15f2
Compare
ebde368 to
ff8ac26
Compare
8b22d36 to
b9d9709
Compare
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
Held requests are in none of SGLang's request lists, so SGLang code that walks those lists skips them.
Held followers = later requests that share a prompt with an admitted leader. This PR keeps them out of SGLang's waiting queue until the leader's prefill is processed.
- Inline comment: held followers bypass
max_queued_requests(engine.py:522).
The general issue
- Held requests are in none of SGLang's request lists.
- But SGLang assumes "every live request is in exactly one list" (request_list.py:44-45 at the pinned SGLang commit).
- So SGLang code that walks those lists skips them:
- the queue limit,
- priority eviction,
- abort-mode pause,
- queue metrics.
| held.add(req.rid) | ||
| else: | ||
| self._awaiting_prefill[key] = (req, []) | ||
| self._scheduler.waiting_queue.take(lambda req: req.rid in held) |
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
Held followers bypass SGLang's max_queued_requests limit.
Problem
- Held followers leave the waiting queue.
_abort_on_queued_limitcheckslen(waiting_queue)only (scheduler.py:3759-3793 at the pinned SGLang commit).- So SGLang's
max_queued_requestsstops counting held followers. - Releasing them later (
waiting_queue.joinat line 598) runs no admission check.
Example with max_queued_requests=2
- Admit leader L and follower F. F is held.
- L starts its prefill and leaves the queue.
- X and Y are admitted, since the queue looks empty.
- When L's prefill ends, F joins.
- The queue now holds X, Y and F: 3 requests, over the limit of 2.
Smallest fix
The option is unset by default. Raise at build when max_queued_requests is set and prompts are held.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Agreed. max_queued_requests (unset by default) is now rejected in extra_server_args (7ad04d5). Of the other list walkers:
- priority eviction runs only inside that same limit;
- the engine pauses with
retractonly, neverabort; - the engine reports its own queue metrics.
A comment names the one other reachable case,SGLANG_REQ_WAITING_TIMEOUT(off by default).
b9d9709 to
f066c31
Compare
f066c31 to
7ad04d5
Compare
7ad04d5 to
4129d96
Compare
4129d96 to
9c6b1c2
Compare
|
Reply from claude: nit on the TODO in # TODO(https://github.com/sgl-project/sglang/issues/48963): SGLang could share
# a prompt's KV among requests in one prefill batch, as vLLM's prefix cache
# does; then drop the holding. The same hold inside SGLang's scheduler
# (https://github.com/sgl-project/sglang/pull/49147) would also let us drop it. |
| # Per (priority, cache salt, prompt) whose first admitted request awaits its | ||
| # prefill: that request, and the later requests with that key, held out of | ||
| # SGLang's waiting queue until then (see add_requests). The priority keeps a | ||
| # request from waiting on a newer group's request that SGLang runs later. | ||
| # SGLang's code that walks its request lists does not see held requests: | ||
| # e.g. its SGLANG_REQ_WAITING_TIMEOUT (off by default) never times them out. |
There was a problem hiding this comment.
i found this a bit hard to follow. Can you ask the agent to reword. I think that other comments added in this PR could benefit from a bit of rewording as well.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Reworded in 3691b4d. This comment now names the leader (the first request with a key, in SGLang's waiting queue) and its followers (held outside it), and says what step() does with them. The add_requests docstring, the step() comments, the max_queued_requests and linear-attention notes, the README's "Rollout groups" section and the test comments are reworded the same way.
SGLang inserts a request's KV into its radix cache only after the request's prefill, so the samples of a rollout group admitted in one prefill batch each computed the shared prompt (SGLang's in-batch prefix caching only reorders the waiting queue under the lpm policy, which priority scheduling excludes). - engine.py: add_requests holds a request whose prompt and cache salt match an admitted request still awaiting its prefill out of SGLang's waiting queue; step() queues it once that prefill's results are processed (first token appended, prompt KV cached), keeping its priority and wait queue entry time. SGLang's own parallel sampling (n > 1) prefills the prompt first for the same reason. Linear attention models do not hold requests: without the extra_buffer strategy, SGLang snapshots their states only at the end of a cached prefix, so a same-prompt request reuses nothing. - README.md: documents it, with measurements. - test_sglang_bitwise_parity.py: test_trainer_vs_sglang_decode's last two requests share a fresh prompt; the second must report cached tokens and still match the trainer bitwise. Qwen3-4B, TP 1, GB300, 8 prompts x 16 samples admitted at once: cached share of prompt tokens 0% -> 93.7% (1K prompts, TTFT p50 0.46 s -> 0.10 s) and 59% -> 93.7% (4K prompts, 0.73 s -> 0.25 s).
Address review: a request with the same prompt but an older group (or validation) no longer waits for a newer group's leader; the parity test puts its equal prompts in one rollout group. README notes linear attention models get no reuse.
- extra_server_args cannot set max_queued_requests: SGLang's queue limit counts its waiting queue only, which held requests are not in. - Comment that SGLang's list-walking code (e.g. SGLANG_REQ_WAITING_TIMEOUT) does not see held requests.
9c6b1c2 to
3691b4d
Compare
|
[From Claude (AI agent), on behalf of @tianyu-l] Done in 3691b4d: the TODO now links sgl-project/sglang#49147 as well, with your wording. |
…ed dispatcher checks (#5959) Stacked on #5918. Addresses the DeepEP / HybridEP question on #5815. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> Integrate sglang with deepep and hybrided ## Why `SGLangEngine` accepts only the all-to-all token dispatcher and Dist-MoE, so an MoE generator configured with DeepEP or HybridEP (as `search_r1`'s vLLM generator uses DeepEP) cannot run on SGLang. `VLLMEngine` accepts them, but checks nothing: a dispatcher config the engine cannot run fails mid-capture or mid-generation with a low-level error. **Example.** ```python generator = Generator.Config( parallelism=InferenceParallelismConfig(tensor_parallel_degree=2, expert_parallel_degree=2), engine=SGLangEngine.Config(), # default cuda_graph="full" ) # model's dispatcher: DeepEPTokenDispatcher(cuda_graph_compatible=True, num_max_tokens_per_rank=N) # before: ValueError "the SGLang engine supports the all-to-all token dispatcher and Dist-MoE only" # after: runs, under CUDA graphs # Either engine, num_max_tokens_per_rank=4096 for an 8195-token-per-rank step bound: # before: AssertionError mid-generation "DeepEP current token count 5120 exceeds the preallocated capacity of 4096" # after: ValueError at build "num_max_tokens_per_rank=4096 is below the 8195 tokens an EP rank can get in one engine step" ``` ## What changed - `generator/model.py` (engine-agnostic): two checks both engines call. - `validate_ep_token_dispatchers`, at engine build: - a dispatcher that reads its split sizes on the host (all-to-all, DeepEP without `cuda_graph_compatible`, HybridEP without `non_blocking_capacity_factor`) raises under CUDA graphs; - DeepEP's deterministic dispatch (`DebugConfig.deterministic`) raises under CUDA graphs: DeepEP sorts the received tokens with data-dependent shapes (`ElasticBuffer.deterministic_sort`); - HybridEP needs an EP degree divisible by 4: a step can have any token count, and HybridEP's TMA loads need a rank's tokens times the ranks in its node, in 4-byte words, to fill 16-byte rows (EP 2 with 3 tokens per rank raised "TMA 16B alignment error" while SGLang captured a decode graph); - a HybridEP `non_blocking_capacity_factor` below 1.0 raises: HybridEP drops the tokens past its capacity without an error, which changes the sampled tokens. - `validate_ep_token_dispatcher_capacity`, in the model wrappers: a DeepEP/HybridEP `num_max_tokens_per_rank` below a step's tokens per EP rank raises. SGLang's bound is `chunked_prefill_size + max_running_requests`, vLLM's `max_num_batched_tokens`, each padded to a multiple of TP and split over TP. - `sglang/engine.py`: its dispatcher loop is replaced by the shared check, so it accepts DeepEP and HybridEP. - `vllm/engine.py`, `vllm/model_wrapper.py`: call the shared checks. - `sglang/README.md`: the MoE section, including where to get DeepEP and HybridEP builds (the install scripts in `.github/scripts/` and `.ci/docker/common/`). | Generator dispatcher | SGLang before | vLLM before | Both after | | --- | --- | --- | --- | | DeepEP `cuda_graph_compatible` / HybridEP `non_blocking_capacity_factor`, CUDA graphs | ValueError | runs | runs | | Host-synced dispatcher, CUDA graphs | ValueError | fails at capture ("Cannot copy between CPU and CUDA tensors during CUDA graph capture") | ValueError at build | | DeepEP + `DebugConfig.deterministic` + CUDA graphs | ValueError | fails at capture (same DeepEP code; not run on vLLM) | ValueError at build | | HybridEP, EP degree not divisible by 4 | ValueError | TMA alignment error on small steps (expected; not run on vLLM) | ValueError at build | | HybridEP `non_blocking_capacity_factor` < 1.0 | ValueError | drops tokens silently | ValueError at build | | `num_max_tokens_per_rank` too small | ValueError (DeepEP/HybridEP unsupported) | assert at the first large step | ValueError at build | Every existing RL recipe whose generator uses EP passes the new checks (built on CPU and checked: the `alphabet_sort`, `dapo_math`, `search_r1` and test `alphabet_sort` recipes; `verifiers_terminal_bench` already turns generator CUDA graphs off). - Review fixes (19d9f98): the shared validator notes that Dist-MoE experts have no token dispatcher; the CUDA-graph server-args comment names the DeepEP / HybridEP capacity check, which assumes SGLang's default capture sizes. Explicit capture sizes and graph-mode keys in `extra_server_args` are rejected since #5812. ## Numerics No change for configurations that ran before. DeepEP and HybridEP results on SGLang match the trainer bitwise when the trainer uses the same dispatcher (below). ## Testing Locally on GB300, Qwen3 MoE debug model (`TestSGLangBitwiseParityMoEEP`'s config with the dispatcher swapped). DeepEP v2 at the pin in `.github/scripts/install_deepep_v2.sh` and HybridEP at the pin in `.ci/docker/common/install_deepep.sh`, built against torch's NCCL 2.32.3: | Run | Result | | --- | --- | | DeepEP on trainer and generator, TP 2 / EP 2, batch-invariant, `cuda_graph="none"` | all 4 parity tests pass bitwise on both ranks | | DeepEP, `cuda_graph="full"`, `DebugConfig.deterministic=False` | graphs capture, generation runs, decode batch invariance passes | | HybridEP on trainer and generator, TP 4 / EP 4, `cuda_graph="full"` | decode batch invariance and 2 trainer-vs-SGLang tests pass bitwise on all 4 ranks; the 4th test fails in the test's own trainer forward (HybridEP on a 150-token sequence, outside the generator) | | Generator-only DeepEP or HybridEP (trainer all-to-all) | decode batch invariance passes; trainer vs SGLang differs (max ~6e-3): the dispatchers combine expert outputs in different orders | | DeepEP deterministic + `cuda_graph="full"`; `num_max_tokens_per_rank=4096`; HybridEP with EP 2; HybridEP factor 0.5 | each raises the new ValueError at build | - `pytest tests/rl/unit_tests/cpu`: 568 passed, 7 skipped. - No new CI test: the RL B200 job installs neither DeepEP nor HybridEP, and the SGLang venv's own DeepEP wheel asserts on an NCCL version mismatch with torch. ## Known issues / follow-ups - DeepEP's deterministic dispatch cannot run in CUDA graphs (DeepEP limitation, deepseek-ai/DeepEP#820). - The trainer's HybridEP dispatch raises TMA alignment errors for token counts per rank that miss the alignment (small test sequences); training microbatches are packed to aligned sizes. - A CI job for DeepEP / HybridEP generators needs DeepEP builds in the RL and SGLang environments.

Stacked on #5853 (SGLang full prefill CUDA graphs).
Summary (human-written)
vllm automatically share prefix cache among grouped requests; sglang doesn't support that so this is a workaround -- send one request first, and others later so they can share the first request's prefix cache.
Why
A GRPO rollout group is N samples of one prompt, admitted together. vLLM caches a request's KV blocks when it allocates them, so the samples prefilled in one batch share the prompt. SGLang adds a request's KV to its radix cache only after that request's prefill result is processed. So every sample admitted in the same prefill batch recomputes the whole prompt. SGLang's in-batch prefix caching only reorders the waiting queue under the
lpmpolicy, and priority scheduling (SGLangEnginesets priority = group id, so older groups finish first) allows onlyfcfs/lof. On DAPO, SGLang served 34% of prompt tokens from cache, against 85% for vLLM.Example. One group of 16 samples, 1K-token prompt, all admitted in one
add_requests:What changed
sglang/engine.py:add_requestsadmits the first request for each (priority, cache salt, prompt) as usual. It takes later requests with the same key out of SGLang's waiting queue and holds them. Within a rollout group the priority is the same; keying on it keeps an older group's request from waiting on a newer group's leader.step()puts the held requests back in the queue once the first request's prefill result is processed (first token appended, prompt KV cached). It usesReqList.join, so they keep their priority and wait-queue entry time, and groups still run oldest first.has_unfinished_requestscounts held requests.TokenizerManager) prefills the prompt first for the same reason.extra_bufferstrategy, SGLang snapshots linear attention states only at the end of a cached prefix. A request with the same prompt must recompute the last token, so it needs the state one token earlier and reuses nothing (measured: 0% cached either way). Holding would only delay it.sglang/README.md: new "Rollout groups" section and a row in the support table.test_sglang_bitwise_parity.py:test_trainer_vs_sglang_decodenow ends its batch with two requests that share a prompt (one rollout group:_generategives equal prompts onegroup_id), and checks that the second one reads cached tokens (softmax-attention classes). The test still asserts the bitwise trainer parity of both requests.extra_server_argscannot setmax_queued_requests,since SGLang's limit counts only its waiting queue, which held requests are not
in; a comment notes that SGLang's other list walkers (e.g.
SGLANG_REQ_WAITING_TIMEOUT) do not see held requests either.Alternatives considered
lpmpolicy: priority scheduling excludes it, and its in-batch caching only deprioritizes duplicates in the queue; they still share a batch whenever the prefill budget fits them.max_new_tokens=0first (SGLang's n > 1 approach): adds one request per group and a round trip through the engine. Holding gives the same cache reuse inside onestep()loop.Performance
Qwen3-4B-Base, TP 1, 1x GB300, perf mode, 8 prompts x 16 samples admitted at once, 256 output tokens, temperature 1. Three repeats each; values are the median (spread at most 0.05 s).
93.7% is the most a request can reuse: each sample recomputes its last prompt page.
Numerics
Batch-invariant mode stays bitwise identical to the trainer: held requests run the same kernels and only start later.
test_sglang_bitwise_parity.pyVarlen, MoE EP, sliding window, Dist-MoE, MLA, KDAnum_cached_tokens > 0as intendedTesting
PREFETCHpath, whose output depends on the batch composition; Recurrent delta-rule scan: same output bits for every launch config meta-pytorch/attention-gym#704 fixes it.Known issues / follow-ups