Skip to content

[rl] generator: SGLang reuses a rollout group's prompt KV - #5918

Merged
tianyu-l merged 4 commits into
sglang-8-full-prefill-graphsfrom
sglang-9-stagger-shared-prompts
Nov 10, 2026
Merged

tianyu-l merged 4 commits into
sglang-8-full-prefill-graphsfrom
sglang-9-stagger-shared-prompts

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

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 lpm policy, and priority scheduling (SGLangEngine sets priority = group id, so older groups finish first) allows only fcfs/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:

before: prefill batch = g7/s0 .. g7/s15       16 x 1024 prompt tokens computed
after:  add_requests -> waiting queue: g7/s0   held: g7/s1 .. g7/s15
        step(): prefill g7/s0, its prompt KV enters the radix cache, release s1..s15
        next prefill: g7/s1 .. g7/s15          each computes only the last token (page)

What changed

  • sglang/engine.py:
    • add_requests admits 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 uses ReqList.join, so they keep their priority and wait-queue entry time, and groups still run oldest first.
    • has_unfinished_requests counts held requests.
    • SGLang's own n > 1 sampling (TokenizerManager) prefills the prompt first for the same reason.
    • TODO linking [Feature] Share a prompt's KV among requests admitted in the same prefill batch sgl-project/sglang#48963 (share in-flight prefixes within a prefill batch); once that lands, holding can be dropped.
  • Models with linear attention (GDN, KDA) don't hold requests. Without the extra_buffer strategy, 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_decode now ends its batch with two requests that share a prompt (one rollout group: _generate gives equal prompts one group_id), and checks that the second one reads cached tokens (softmax-attention classes). The test still asserts the bitwise trainer parity of both requests.
  • Review fix (9c6b1c2): extra_server_args cannot set max_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

  • lpm policy: 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.
  • Dropping priority scheduling: brings back off-policy samples from late groups, and doesn't fix the cache.
  • Sending each prompt as a warmup request with max_new_tokens=0 first (SGLang's n > 1 approach): adds one request per group and a round trip through the engine. Holding gives the same cache reuse inside one step() 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).

Prompt length Metric SGLang before SGLang after vLLM
1K prompt tokens from cache 0% 93.7% 82.0%
1K TTFT p50 / max 0.46 / 0.74 s 0.10 / 0.11 s 0.12 / 0.21 s
1K wall 2.37 s 1.75 s 1.75 s
4K prompt tokens from cache 59.0% 93.7% 90.8%
4K TTFT p50 / max 0.73 / 1.38 s 0.25 / 0.26 s 0.28 / 0.54 s
4K wall 4.54 s 3.43 s 2.96 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.

Check Hardware Result
test_sglang_bitwise_parity.py Varlen, MoE EP, sliding window, Dist-MoE, MLA, KDA 4x GB300 passed
GDN class with attn-gym 0.0.17 4x GB300 passed (8/8)
Same test with holding disabled (negative check) 4x GB300 fails num_cached_tokens > 0 as intended

Testing

Known issues / follow-ups

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

  1. torchtitan/rl/generator/sglang/engine.py:561 -- held requests are released only if the leader prefilled or got a finished_reason. A leader that SGLang drops through its AbortReq path (which _OutputCollector.send_output already handles) leaves its followers held forever, so has_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 -- add req.priority to 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_ids appear only after its last chunk.
    • load_model_state_dict with reset: held requests own no KV, so flushing is safe. A leader prefilled in the in-flight batch releases its followers on the next step(), 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.
  • Test: extending test_trainer_vs_sglang_decode instead 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():

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

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

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.

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 calls req.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 an input_embeds request that has already sent output. The engine never builds input_embeds requests, 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))

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

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

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.

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 |

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

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

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.

Done.

@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 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 calls finish_outside_step before sending AbortReq, so leader.finished() covers it. The two exceptions (an unresumable retract of an input_embeds request, 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)

  • _generate sets group_id=prompt_ids.index(ids), so the two equal prompts in test_trainer_vs_sglang_decode share 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 by test_sglang_decode_batch_invariance, which runs first by name order, so the num_cached_tokens > 0 check 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.

@tianyu-l
tianyu-l added this pull request to stack #5813 November 7, 2026 03:01
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from 222bc8d to 6e88949 Compare November 7, 2026 20:23
@tianyu-l
tianyu-l marked this pull request as ready for review November 8, 2026 11:12
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 8, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 8, 2026 11:13
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from 6e88949 to acc2670 Compare November 8, 2026 11:50
@tianyu-l tianyu-l added the ciflow/b200 Trigger B200 CI label Nov 8, 2026
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from acc2670 to 7bb5cf1 Compare November 8, 2026 12:32
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch 2 times, most recently from 5b0262a to d0075d2 Compare November 8, 2026 21:47
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from d0075d2 to 05d15f2 Compare November 8, 2026 21:55
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from ebde368 to ff8ac26 Compare November 9, 2026 05:02
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch 3 times, most recently from 8b22d36 to b9d9709 Compare November 9, 2026 07:22
@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at b9d970929.

Before, all 16 samples of a rollout group prefill the same 1024-token prompt in one batch; now the first sample goes alone and the other 15 are held, then read all but the last prompt token from SGLang's radix cache (1K prompts: 0% to 93.7% from cache).

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

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.

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

@felipemello1 felipemello1 Nov 10, 2026 •

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.

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_limit checks len(waiting_queue) only (scheduler.py:3759-3793 at the pinned SGLang commit).
  • So SGLang's max_queued_requests stops counting held followers.
  • Releasing them later (waiting_queue.join at line 598) runs no admission check.

Example with max_queued_requests=2

  1. Admit leader L and follower F. F is held.
  2. L starts its prefill and leaves the queue.
  3. X and Y are admitted, since the queue looks empty.
  4. When L's prefill ends, F joins.
  5. 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.

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.

[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 retract only, never abort;
  • the engine reports its own queue metrics.
    A comment names the one other reachable case, SGLANG_REQ_WAITING_TIMEOUT (off by default).

@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from b9d9709 to f066c31 Compare November 10, 2026 05:35
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from f066c31 to 7ad04d5 Compare November 10, 2026 06:24
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from 7ad04d5 to 4129d96 Compare November 10, 2026 06:41
@tianyu-l
tianyu-l removed this pull request from stack #5964 November 10, 2026 06:41
@tianyu-l
tianyu-l added this pull request to stack #6002 November 10, 2026 06:41
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from 4129d96 to 9c6b1c2 Compare November 10, 2026 06:52
@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: nit on the TODO in torchtitan/rl/generator/sglang/engine.py (lines 325-327 at 9c6b1c2). sgl-project/sglang#49147 adds this same hold inside SGLang's scheduler (open, not reviewed by SGLang maintainers yet). Could the TODO link it too, so a reader knows which upstream change lets us delete the hold? For example:

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

Comment on lines +319 to +324
# 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.

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.

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.

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.

[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.
@tianyu-l
tianyu-l force-pushed the sglang-9-stagger-shared-prompts branch from 9c6b1c2 to 3691b4d Compare November 10, 2026 19:38
@tianyu-l

Copy link
Copy Markdown
Contributor Author

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

@tianyu-l
tianyu-l merged commit ad06f8c into main Nov 10, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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