Repository navigation
[rl] generator: SGLang full prefill CUDA graphs - #5853
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. This is a small change local to the SGLang engine. It is backed by measured gains on small-prefill workloads and by passing bitwise parity tests. Before merging it needs the human-written summary and an upstream link on the new TODO.
What this PR does. With cuda_graph="decode_and_prefill", SGLang now captures prefill batches as full CUDA graphs, so attention is inside the graph too. Before, it used breakable graphs, which run attention eagerly between graph segments. The number of request slots per graph is set to max_num_seqs, so a prefill batch always fits in a graph and never runs eagerly. Models with linear attention (GDN, KDA) keep breakable graphs. cuda_graph_config is now one of the server args that extra_server_args cannot set.
Example. Qwen3-0.6B, 28 layers, one 300-token prefill while other requests decode:
before: prefill_graphs = {backend: breakable}
-> 28 eager attention calls at ~0.27 ms CPU each -> ~14.7 ms step
after: prefill_graphs = {backend: full, full_prefill_max_req: max_num_seqs}
-> one graph replay -> ~4.3 ms step
Qwen3.5 / Kimi K3 (LinearAttention layers): still breakable, unchanged
Must fix
- The PR description's "Summary (human-written)" section is empty. The author needs to fill it in.
torchtitan/rl/generator/sglang/engine.py:337-- the workaround TODO for the SGLang linear-attention capture failure has no upstream issue link (see inline comment).
Should consider
torchtitan/rl/generator/sglang/engine.py:92--cuda_graph_backend_prefillis still in_TORCHTITAN_SERVER_ARGS, but the engine no longer sets it (see inline comment).
Questions
- With
full_prefill_max_req = max_num_seqs, how do graph memory and capture time grow withmax_num_seqs? The 0.77 GB figure is for 256 slots. Does a run with e.g. 1024 slots still use less memory than breakable graphs?
Details
- Gate. The problem is real and measured: small prefills are CPU-bound on eager attention dispatch. The fix uses an existing SGLang option at the layer that owns it. No new knob is added; the existing
cuda_graphLiteral's default now does more. GDN/KDA models fall back to breakable graphs, but that is chosen per model architecture and documented in the docstring and README. It is not a silent fallback on a user-requested config. - Callsites.
has_linear_attentionis the same check_init_event_loopalready used, now computed once.linear_attention.py:83(the stale-buffer note for breakable graphs) is still accurate, because linear-attention models still use breakable graphs. README line 122 ("Dist-MoE runs under both kinds of CUDA graphs") still holds: the PR reports Dist-MoE parity under full prefill graphs. - Dist-MoE under full graphs.
_DecoderBody.forwardassumes SGLang zero-fills the padded part ofout_cache_locin graph buffers, and that the per-call token count is fixed at capture. Both now need to hold for full prefill graphs as well. The PR's Dist-MoE parity result says they do. I couldn't check this independently. - Tests. The existing parity classes already run with
"decode_and_prefill", so they now exercise full graphs for non-linear models and breakable graphs for GDN/KDA. No new test is needed.
Not verified: the SGLang cuda_graph_config schema (backend, full_prefill_max_req) and the GPU parity and perf results. SGLang isn't installed here and there are no GPUs.
| # TODO: SGLang's hybrid linear attention backend fails to capture full | ||
| # prefill graphs (IndexError in its graph metadata). |
There was a problem hiding this comment.
This TODO needs an upstream issue link. It works around a gap in SGLang (its hybrid linear attention backend fails to capture full prefill graphs), and every other SGLang TODO in this file links its sglang issue. Without one, nobody can tell when GDN/KDA models can drop the breakable path. Please file the IndexError with SGLang and write # TODO(https://github.com/sgl-project/sglang/issues/<N>): ....
| "disable_cuda_graph", | ||
| "disable_prefill_cuda_graph", | ||
| "cuda_graph_backend_prefill", | ||
| "cuda_graph_config", |
There was a problem hiding this comment.
The engine no longer sets cuda_graph_backend_prefill (line 92), but it stays in this set, whose comment (line 75) says these are the args "SGLangEngine sets itself". If SGLang treats it as a flat alias of cuda_graph_config["prefill"]["backend"], keeping it blocked is correct. In that case, change the comment to say "sets or overrides", so the set doesn't look out of date. If it isn't an alias, remove it from the set. Unverified: SGLang isn't installed in this checkout, so I couldn't check how ServerArgs resolves the two.
0f10311 to
12f6d43
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The amended commit fixes both code items from the earlier review. The only thing left is the human-written summary.
What this PR does. With cuda_graph="decode_and_prefill", prefill batches are now captured as SGLang's full CUDA graphs, so attention is inside the graph, with max_num_seqs request slots per graph. Models with linear attention (GDN, KDA) keep breakable graphs. cuda_graph_config is now one of the server args that extra_server_args cannot set.
Example. Qwen3-0.6B, one 300-token prefill while other requests decode:
before: cuda_graph_backend_prefill="breakable"
-> 28 eager attention calls (~0.27 ms CPU each) -> ~14.7 ms step
after: cuda_graph_config={"prefill": {"backend": "full", "full_prefill_max_req": max_num_seqs}}
-> one graph replay -> ~4.3 ms step
GDN/KDA models: cuda_graph_config={"prefill": {"backend": "breakable"}}
Since the last review
- Resolved:
engine.py:338-- the linear-attention TODO now links sgl-project/sglang#48593. - Resolved:
engine.py:75-- the_TORCHTITAN_SERVER_ARGScomment now says "sets or overrides" and explains whycuda_graph_backend_prefillis still blocked. - Answered: the description now gives memory and capture time at
max_num_seqs=512(0.94 GB, 36 s), which is still under breakable graphs' 1.02 GB. - Still open: the "Summary (human-written)" section of the description is empty. The author needs to fill it in.
No new problems in the amended commit.
Not verified: the SGLang cuda_graph_config schema, and the GPU parity and perf results. SGLang isn't installed here and there are no GPUs.
12f6d43 to
ed656ee
Compare
ed656ee to
cc5ae8b
Compare
cc5ae8b to
50e3afe
Compare
| if self.config.cuda_graph == "decode_and_prefill": | ||
| server_kwargs["cuda_graph_backend_prefill"] = "breakable" | ||
| if has_linear_attention: | ||
| # TODO(https://github.com/sgl-project/sglang/issues/48593): SGLang's | ||
| # hybrid linear attention backend fails to capture full prefill graphs. | ||
| prefill_graphs = {"backend": "breakable"} | ||
| else: | ||
| # Full graphs also capture attention, whose eager CPU cost otherwise | ||
| # dominates small prefills. A request slot per running request, so | ||
| # no prefill batch has too many requests for the graphs (it would run | ||
| # eagerly). | ||
| prefill_graphs = { | ||
| "backend": "full", | ||
| "full_prefill_max_req": max_num_seqs, | ||
| } | ||
| server_kwargs["cuda_graph_config"] = {"prefill": prefill_graphs} |
There was a problem hiding this comment.
This is hard to read -- why don't we
- let
self.config.cuda_graphbe"full"when we really mean it's "full" - let linear attention error out when full is chosen
But sure, I'd like to respect whatever sglang convention is.
There was a problem hiding this comment.
[Reply from Claude (AI agent), on behalf of the PR author]
Done: cuda_graph: Literal["none", "decode", "breakable", "full"] = "full". "full" raises at engine build for GDN/KDA models (TODO linking sgl-project/sglang#48593); they set "breakable", as the GDN and KDA parity classes now do. The names follow SGLang's prefill graph backends (breakable, full).
3438039 to
ee7d89b
Compare
165db29 to
d517822
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The description now matches the code. The code has not changed since my last approval, and the rebase doesn't touch this PR's three files. The human-written summary is still empty.
Example.
cuda_graph="full" (default)
Qwen3 -> cuda_graph_config={"prefill": {"backend": "full", "full_prefill_max_req": max_num_seqs}}
Qwen3.5 -> ValueError: set SGLangEngine.Config.cuda_graph to 'breakable'
cuda_graph="breakable" -> cuda_graph_config={"prefill": {"backend": "breakable"}}
cuda_graph="decode" / "none" -> disable_prefill_cuda_graph=True
Since the last review
- Resolved: "What changed" and "User-facing changes" now describe the
"breakable"/"full"split. The before/after table now shows the default moving from"breakable"to"full"and the newValueErrorfor GDN/KDA. - Resolved: Numerics and Testing now say which mode each class runs. They also say the CI run predates the split and that the B200 job reruns at the current head.
- Still open: "Summary (human-written)" is empty. The author has to write it.
- Still open (should consider):
torchtitan/rl/generator/sglang/README.md:118-- "Dist-MoE ... runs under both kinds of CUDA graphs" is now ambiguous, since there are three graph modes. Name the ones the parity runs cover, e.g. "underdecode,breakableandfullCUDA graphs".
No new problems at HEAD (d517822). The earlier fixes still hold: the upstream TODO link at engine.py:190 and the _TORCHTITAN_SERVER_ARGS comment at engine.py:76. In-repo SGLang callsites: the rl_grpo_qwen3_0_6b_varlen_sglang recipe (Qwen3, gets "full") and the parity tests. No recipe runs SGLang with a GDN/KDA model.
Not verified: SGLang's cuda_graph_config schema and the GPU parity results at the current head. SGLang isn't installed here and there are no GPUs.
d517822 to
d302331
Compare
65c5cd5 to
85380a1
Compare
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
No test proves a full prefill graph replayed. Also, a cheap first split of the decode slowdown.
- Inline comment: no test proves a full prefill graph replayed (test:103).
- The "both kinds of CUDA graphs" README line (claude[bot], 2026-11-09) is still open.
The decode slowdown
From the PR body: "decode steps slow from 3.4 ms to 8.4 ms" after several workloads in one engine.
Why it matters: an RL generator runs one engine for hours. So this can cost more than a one-off.
A cheap first split:
- Profile one slow step. Is the extra 5 ms on the CPU or on the GPU?
- Call
flush_cachewhile idle, and re-run. (It returns False if requests are pending.)- If the step drops back to 3.4 ms, the cause is some state the flush resets: the radix tree, the request and KV allocators, or the device allocator cache (scheduler.py:5867-5894 at the pinned SGLang commit).
- A drop back to 3.4 ms does not rule out graphs either. The flush also changes the re-run's prefill mix and frees the device cache.
- Then record each slow step's execution mode.
- Check the suspects one at a time. Examples: radix tree size, free-slot fragmentation from 1-token pages.
| sync_weights_from_trainer = False | ||
| # CUDA graphs SGLang captures (SGLangEngine.Config.cuda_graph). | ||
| cuda_graph = "breakable" | ||
| cuda_graph = "full" |
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
No test checks that a full prefill graph actually replayed.
Problem
- If every prefill fell back to eager, all parity classes would still pass.
- Then the new default,
cuda_graph="full", would be untested. - SGLang declines full replay for several reasons (prefill_cuda_graph_runner.py:1497-1532 at the pinned SGLang commit). For example:
- a cached-prefix topology outside the capture,
- too much bucket padding.
Our vLLM test records the execution mode and asserts FULL ran (test_generator_dp_cudagraph.py:110-117, 186-188).
Smallest fix
In the existing workload:
- Wrap the full prefill backend's
replay(prefill_cuda_graph_runner.py:2323). - Count the calls.
- Assert at least one call for the "full" classes.
Wrapping can_run_graph is not enough. The model runner still goes eager when token_indices_to_pool is set (model_runner.py:2090-2117).
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Added test_prefill_replays_cuda_graphs in faa9371. For classes with breakable or full prefill graphs, it counts the prefill graph backend's replay calls (inside execute, so after SGLang's eager fallbacks) over a prefill of new prompts and asserts at least one.
85380a1 to
9d10c1c
Compare
9d10c1c to
faa9371
Compare
|
[From Claude (AI agent), on behalf of @tianyu-l] On the automated review body:
|
faa9371 to
650ef20
Compare
650ef20 to
fb2c483
Compare
| Without them, prefill is bound by the eager model's CPU overhead. | ||
| - ``"breakable"``: ``"decode"``, plus SGLang's breakable graphs for prefill | ||
| batches, which run attention eagerly between graph segments, at a CPU cost | ||
| per layer in every prefill step. For linear attention (GDN, KDA) models. |
| # Full graphs also capture attention, whose eager CPU cost otherwise | ||
| # dominates small prefills. A request slot per running request, so no | ||
| # prefill batch has too many requests for the graphs (it would run | ||
| # eagerly). |
There was a problem hiding this comment.
worth making this comment more clear? this explains why we set "full_prefill_max_req": max_num_seqs
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Reworded in 67bfb8c: SGLang runs a prefill batch eagerly if it has more requests than full_prefill_max_req. A prefill batch has at most max_num_seqs requests (SGLang's max_running_requests), so with that many slots every prefill batch runs in a graph.
Capture prefill batches as SGLang's full CUDA graphs, with a request slot per running request, instead of breakable ones, which run attention eagerly between graph segments. Linear attention models keep breakable graphs.
- Test: with breakable or full prefill CUDA graphs, a prefill of new prompts replays a graph; every other test would also pass with eager prefill. - README: Dist-MoE runs under decode graphs and breakable or full prefill graphs (it said both kinds, from when there were two).
fb2c483 to
67bfb8c
Compare
Stacked on #5853 (SGLang full prefill CUDA graphs). ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> 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 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 - GPU parity classes above. The GDN class fails with attn-gym 0.0.18 on this PR, on its base, and on main. The cause is the recurrent kernel's `PREFETCH` path, whose output depends on the batch composition; meta-pytorch/attention-gym#704 fixes it. - CPU RL unit tests: 566 passed, 7 skipped. ## Known issues / follow-ups - Drop holding once sgl-project/sglang#48963 lands.

Stacked on #5819 (SGLang KDA).
Summary (human-written)
Why
SGLangEnginecaptures prefill batches as SGLang's breakable CUDA graphs: the model runs in graph segments, and attention runs eagerly between them. Each eager attention call costs about 0.27 ms of CPU time (FlashAttention 4's host-side dispatch plus the varlen wrapper), so every prefill step pays about 7-8 ms of CPU time for Qwen3-0.6B's 28 layers, however few tokens it has. When requests arrive while others decode (multi-turn and agentic rollouts), most steps are small prefills, and this CPU time dominates them.Example. Qwen3-0.6B, TP 1, one request (300 prompt tokens) admitted every step while earlier ones decode (stream workload below), per-step profile:
SGLang's full prefill CUDA graphs capture the whole forward, attention included, one graph per token-count bucket with a fixed number of request slots. By default SGLang sizes the slots to
chunked_prefill_size // 512(32 at the default 16K); a prefill batch with more requests runs eagerly, which made many-short-prompt prefill slower than breakable graphs (0.51 s vs 0.39 s for 256 prompts of 100 tokens).What changed
sglang/engine.py: a newcuda_graph="full"mode, now the default, captures prefill batches as SGLang's full CUDA graphs, withmax_num_seqsrequest slots, so no prefill batch has too many requests for them."breakable"(the old default) stays for models with linear attention (GDN, KDA): SGLang's hybrid linear attention backend fails to capture full prefill graphs (TODO in code), so"full"raises for them at engine build instead of falling back.cuda_graph_configjoins the server argsextra_server_argscannot set."full"; the GDN and KDA classes set"breakable".sglang/README.md: the CUDA graphs section and the support table.test_prefill_replays_cuda_graphscounts the prefillgraph backend's replays for classes with breakable or full prefill graphs and
asserts at least one, since every other test would also pass with eager prefill;
the README names the graph modes Dist-MoE runs under.
User-facing changes
cuda_graph="breakable": breakable prefill graphscuda_graph="full": full prefill graphsValueError: setcuda_graph="breakable"extra_server_argsmay setcuda_graph_configValueError(TorchTitan sets it)Numerics
Batch-invariant mode stays bitwise identical to the trainer.
test_sglang_bitwise_parity.pyclasses. Varlen, sliding window, MLA and Dist-MoE capture full prefill graphs; GDN and KDA run"breakable"; MoE EP and MLA at EP 2 run without graphsPerformance
Qwen3-0.6B, generator TP 2, 2x GB300, perf mode, temperature 1, fixed-length outputs. Local benchmark through the same
GenerationEnginecalls; one process per configuration, run one after another on the same GPUs; three repeats each (ranges).Prefill graph memory: 0.77 GB (full, 256 slots) vs 1.02 GB (breakable). Prefill graph capture: 28 s vs 31 s. At max_num_seqs=512 (the controller's cap): 0.94 GB and 36 s, with the stream workload at 2.14-2.17 s. The first decode repeat with breakable graphs includes attention kernel compilation, which the full-graph run did not show.
End to end,
alphabet_sortwith generator TP 2 + trainer TP 2 (4x GB300, 10 steps, RL environment): trainertokens/s over steps 3-9 is 1684 with full prefill graphs and 1651 for vLLM (one run each, same session). Earlier
SGLang runs with breakable graphs gave 1632, 1758 and 1763, so this workload does not separate the engines.
Testing
test_sglang_bitwise_parity.py, all 7 classes, and the batch-invariant check above."breakable"and"full": all 7 classes passed (4 tests each, every rank); the step took 9 minutes. The split changes which mode each class selects, not what a mode captures; the B200 job reruns them at the current head."full"in the base class,"breakable"in the GDN and KDA classes).Known issues / follow-ups
enable_mixed_chunk) is gated off in SGLang when requests return logprobs. With a local SGLang patch that lifts the gate, mixed steps take 7.6 ms (p50), about a prefill step plus a decode step. On the stream workload that brings latency p50 / p90 to 1.04-1.14 / 1.19-1.25 s, but wall time rises to 2.35-2.54 s.