Skip to content

[rl] generator: SGLang full prefill CUDA graphs - #5853

Merged
tianyu-l merged 3 commits into
sglang-7-kdafrom
sglang-8-full-prefill-graphs
Nov 10, 2026
Merged

tianyu-l merged 3 commits into
sglang-7-kdafrom
sglang-8-full-prefill-graphs

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Stacked on #5819 (SGLang KDA).

Summary (human-written)

Why

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

breakable prefill graphs: prefill step 14.7 ms (p50)
  aten::_flash_attention_forward   214 us CPU per call, one per layer
  torch_attn::_varlen_attn_out      51 us CPU per call
full prefill graphs:      prefill step  4.3 ms (p50)

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 new cuda_graph="full" mode, now the default, captures prefill batches as SGLang's full CUDA graphs, with max_num_seqs request 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_config joins the server args extra_server_args cannot set.
  • Tests: the parity base class runs "full"; the GDN and KDA classes set "breakable".
  • sglang/README.md: the CUDA graphs section and the support table.
  • Review fixes (fb2c483): test_prefill_replays_cuda_graphs counts the prefill
    graph 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

Before After
default cuda_graph="breakable": breakable prefill graphs default cuda_graph="full": full prefill graphs
GDN/KDA models with the default raise ValueError: set cuda_graph="breakable"
extra_server_args may set cuda_graph_config raises ValueError (TorchTitan sets it)

Numerics

Batch-invariant mode stays bitwise identical to the trainer.

Check Hardware Result
All 7 test_sglang_bitwise_parity.py classes. 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 graphs 4x GB300 passed, max delta 0
Batch-invariant Qwen3-0.6B TP 1, 32 greedy requests (64-281 prompt tokens, 64 output tokens), one admitted every 3 steps: full vs breakable prefill graphs 1x GB300 identical tokens, bitwise-identical logprobs

Performance

Qwen3-0.6B, generator TP 2, 2x GB300, perf mode, temperature 1, fixed-length outputs. Local benchmark through the same GenerationEngine calls; one process per configuration, run one after another on the same GPUs; three repeats each (ranges).

Workload Breakable prefill graphs Full prefill graphs vLLM
Stream: one request (300 in / 150 out) admitted every step, 256 requests: wall 5.09-5.35 s 1.98-2.02 s 2.10-2.20 s
Stream: request latency p50 / p90 2.86-2.97 / 4.62-4.85 s 1.30-1.34 / 1.84-1.88 s 0.90-0.93 / 1.00-1.01 s
Prefill: 512 requests, 1536 in / 128 out 2.68-3.08 s 2.51-2.53 s
Prefill: 256 requests, 100 in / 64 out 0.40-0.41 s 0.37-0.39 s
GRPO 16 prompts x 8 samples (1024 in, 256 out) 1.03-1.22 s 1.01-1.13 s
GRPO 64 prompts x 8 samples (128 in, 256 out) 2.13-2.17 s 2.06-2.19 s
GRPO 16 x 8, siblings admitted after the head's prefill (cached prefix) 0.97-1.04 s 0.96-0.99 s
Decode: 256 requests, 128 in / 512 out 2.03-2.05 s (first repeat: 6.38 s) 2.01-2.05 s

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_sort with generator TP 2 + trainer TP 2 (4x GB300, 10 steps, RL environment): trainer
tokens/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.
  • CI: the B200 SGLang step ([rl] generator: SGLang generation engine #5812), run 42015552173, before the split into "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.
  • Benchmarks and E2E runs as above.
  • No new test: the parity classes cover both prefill graph modes ("full" in the base class, "breakable" in the GDN and KDA classes).

Known issues / follow-ups

  • Mixing a prefill chunk into the running decodes (SGLang's 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.
  • After several workloads in one engine, the stream workload's decode steps slow from 3.4 ms to 8.4 ms with either prefill graph backend; not investigated yet.

@tianyu-l
tianyu-l added this pull request to stack #5813 November 5, 2026 07:43
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@tianyu-l

tianyu-l commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 41s —— View job


Approve -- please address the items before merging (fill in the human-written summary, add an upstream issue link to the new TODO): 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 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

  1. The PR description's "Summary (human-written)" section is empty. The author needs to fill it in.
  2. 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_prefill is 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 with max_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_graph Literal'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_attention is the same check _init_event_loop already 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.forward assumes SGLang zero-fills the padded part of out_cache_loc in 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.

Comment on lines +337 to +338
# TODO: SGLang's hybrid linear attention backend fails to capture full
# prefill graphs (IndexError in its graph metadata).

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

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

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch 2 times, most recently from 0f10311 to 12f6d43 Compare November 5, 2026 08:16
@tianyu-l

tianyu-l commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 48s —— View job


Approve -- please fill in the human-written summary before merging: 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 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_ARGS comment now says "sets or overrides" and explains why cuda_graph_backend_prefill is 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.

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from 12f6d43 to ed656ee Compare November 5, 2026 10:52
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from ed656ee to cc5ae8b Compare November 6, 2026 20:33
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from cc5ae8b to 50e3afe Compare November 7, 2026 20:23
@tianyu-l
tianyu-l marked this pull request as ready for review November 8, 2026 09:05
@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 09:05
Comment on lines +338 to +352
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}

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.

This is hard to read -- why don't we

  • let self.config.cuda_graph be "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.

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

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch 2 times, most recently from 3438039 to ee7d89b Compare November 8, 2026 12:32
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from 165db29 to d517822 Compare November 9, 2026 05:02
@tianyu-l

tianyu-l commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. The description is updated for your must-fix items (file paths and design now match the code); the stack is also rebased onto latest main.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 50s —— View job


Approve -- please fill in the human-written summary before merging: 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 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 new ValueError for 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. "under decode, breakable and full CUDA 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.

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from d517822 to d302331 Compare November 9, 2026 05:06
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch 2 times, most recently from 65c5cd5 to 85380a1 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 85380a182.

Breakable prefill graphs run attention eagerly between graph segments, about 7-8 ms of CPU per prefill step for 28 layers (p50 14.7 ms); the new default full prefill graphs include attention (p50 4.3 ms).

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

No test proves a full prefill graph replayed. Also, a cheap first split of the decode slowdown.

  1. Inline comment: no test proves a full prefill graph replayed (test:103).
  2. 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:

  1. Profile one slow step. Is the extra 5 ms on the CPU or on the GPU?
  2. Call flush_cache while 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.
  3. Then record each slow step's execution mode.
  4. 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"

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

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:

  1. Wrap the full prefill backend's replay (prefill_cuda_graph_runner.py:2323).
  2. Count the calls.
  3. 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).

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

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from 85380a1 to 9d10c1c Compare November 10, 2026 05:35
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from 9d10c1c to faa9371 Compare November 10, 2026 06:24
@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] On the automated review body:

  • The replay test is added (faa9371). The README line now names the graph modes.
  • The decode slowdown (3.4 -> 8.4 ms after several workloads in one engine) happens with either prefill graph backend, so this PR did not introduce it. It is tracked as a follow-up. The suggested first split (profile one slow step; flush_cache while idle and re-run) is the plan.

@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from faa9371 to 650ef20 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-8-full-prefill-graphs branch from 650ef20 to fb2c483 Compare November 10, 2026 06:52
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.

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.

incomplete sentence?

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] Yes, fixed in 67bfb8c: "Linear attention (GDN, KDA) models need this mode for prefill graphs, since "full" raises for them."

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

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.

worth making this comment more clear? this explains why we set "full_prefill_max_req": max_num_seqs

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 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).
@tianyu-l
tianyu-l force-pushed the sglang-8-full-prefill-graphs branch from fb2c483 to 67bfb8c Compare November 10, 2026 19:38
@tianyu-l
tianyu-l merged commit 71d78ae into main Nov 10, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
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.
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.

3 participants