Repository navigation
[rl] SGLang generator: run GDN and KDA prefill inside breakable prefill CUDA graphs - #6415
felipemello1 wants to merge 7 commits into
Conversation
…graphs TorchTitan's SGLang GDN backend implements SGLang's prefill-graph hooks: each breakable prefill graph bucket keeps static tables (request offsets, state slots, prefix-cache snapshot rows), refilled from the batch before each replay, so the GDN extend is captured instead of breaking the graph at every GDN layer. With HiCache, the refresh queues one stream wait for every state layer's load-back. For GDN models the engine caps a prefill batch at 256 requests (SGLang's prefill_max_requests), since every table row costs GPU time in every GDN layer. Draft runners and attention DP keep the eager extend.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 5m 0s —— View job Needs discussion -- review posted. This PR overlaps draft #6200, which targets the same gap with a 5-line change once an upstream SGLang fix lands, so maintainers should decide whether this interim path lands. Separately, one new test class repeats coverage the fp8 class already has. |
There was a problem hiding this comment.
Verdict: Needs discussion -- this adds about 190 lines of breakable-only per-bucket GDN tables, built on private SGLang internals. Draft #6200 targets the same prefill gap with +5 lines plus an upstream SGLang fix (sgl-project/sglang#51225, still open). A maintainer should decide whether this interim path lands.
What this PR does. SGLang's breakable prefill graphs break at every layer whose backend lacks SGLang's prefill-graph hooks, so each GDN layer currently runs eagerly at about 2 ms of host time. This PR implements those hooks on TorchTitanLinearAttnBackend. Each captured bucket gets static tables (offsets, slots, snapshot slots and lengths, conv-history rows), and refresh_prefill_graph_metadata refills them before each replay. track_extend_states and convolve_extend read the tables while a bucket is active. The engine also caps prefill batches at 256 requests for GDN models.
Example. Qwen3.5-0.8B, one 2,048-token prefill in breakable mode:
main: [graph] GDN [graph] GDN [graph] GDN [graph] attn ... 18 eager GDN layers, 47.3 ms
this PR: [graph: GDN GDN GDN] attn [graph: GDN GDN GDN] ... 13.2 ms
bucket of 512 tokens, rows for 160 requests, batch of 2:
cu_seqlens [0, 100, 130, 130, ...]; state_indices [5, 9, -1, ...]
padding rows: empty sequences on slot -1; conv history -> dummy slot 0
output tokens 130.. zeroed (kernels leave them unwritten)
Must fix
- Overlap with #6200 (gate). #6200 is a small change once SGLang can capture linear attention in full prefill graphs. It covers GDN and KDA, and measures 4.5 ms vs 28.6 ms breakable on 0.8B. After it lands,
"full"is the default for GDN models and this PR's tables, the 256-request cap, and the new test file serve a non-default mode. The PR is upfront about this ("a maintainer's call"). The open questions are whether to carry ~590 lines for the interim, and whether the upstream fix is close. Also coordinate with #6318, which rewritestrack_extend_stateswhere the graph branch goes, and #6294 / #6414, which touch the same files. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:648--TestSGLangGDNOutsideBatchInvariantModeduplicatesTestSGLangFp8KVCacheGDNHiCache's coverage of the default-mode captured extend at the cost of another engine build. Drop it, or name the regression only it catches. Dropping it also lets the_OutsideBatchInvariantModemixin fold back into the fp8 class.
Should consider
torchtitan/rl/generator/sglang/engine.py:560-- the 256-request cap also applies under attention DP > 1, wheresupports_prefill_graph_extendis False and no tables exist. Gate it the same way.
Questions
linear_attention.py:269-272rewritesforward_batch.mamba_track_indicesin place with_translate_mamba_indices. Can SGLang callrefresh_prefill_graph_metadatatwice on the same batch, or run the eagerinit_forward_metadataon it after a refresh (for example on a fallback)? Either would translate the indices twice. If the translation isn't idempotent, a request's snapshot silently lands in the wrong slot.- Under
enable_unified_memory, which the engine always sets for linear attention models, is row 0 of the conv pool view really reserved? The unit test builds its ownIdSpacewith an unused row 0. The parity tests would only catch a clash if the request owning that row is decoded afterwards. - Why not enable KDA too? The shared branches are already in the base class. KDA would need
supports_prefill_graph_extendplus the paddingmasked_fill_, and a KDA model breaks the graph at every layer today.
Details
- Overlap search:
gh pr list --searchfor "prefill CUDA graphs linear attention", "GDN", and "linear_attention.py sglang". Found #6200 (full prefill graphs, draft, waits on sgl-project/sglang#51225, OPEN), #6318 (public extra_buffer hooks), #6294 (always fused), #6414 (MTP), #6403. The description already lists these. - Existing counterpart: SGLang's own
GDNPrefillGraphMetadataindexes SGLang's Triton kernels. The description's reason for not reusing it (Attention Gym takes only offsets and slots) holds. - Numerics: in default mode, prefill batches with no snapshot move from warpdrive to fused inside graphs (rel L2 4.2e-3). This is explained, and it follows the existing attention-gym#980 TODO in
paged_gdn. It needs no new TODO, because the graph path picks up warpdrive once #980 lands. - Stale
prefill_graph_metadataafter a replay: onlyinit_forward_metadataclears it, and decode-graph replay doesn't call that.forward_decodedoesn't read the field, though, and the draft runners have their own backends, so I found no path that reads stale tables. refresh_prefill_graph_metadatahas no host sync:sum(extend_seq_lens_cpu)is a host list, and the rest are device copies,torch.whereandclamp(out=).
Not verified: SGLang's hook call order (capture vs replay vs init_forward_metadata) and prefill_max_requests semantics. SGLang's source is not available in this checkout. No GPU runs.
Before merge: fill in the human-written summary.
| class TestSGLangGDNOutsideBatchInvariantMode( | ||
| _OutsideBatchInvariantMode, TestSGLangBitwiseParityGDN | ||
| ): | ||
| """``TestSGLangBitwiseParityGDN`` on one GPU outside batch-invariant mode, where the | ||
| prefill graphs run the GDN extend on the default (chunk) kernels.""" | ||
|
|
||
| config_fn = staticmethod(_qwen3_5_debug_tp1_config) | ||
| # bf16 gives 1e-3 to 2e-3 on this model. | ||
| MAX_MEAN_ABS_DIFF = 0.01 |
There was a problem hiding this comment.
This class duplicates coverage that TestSGLangFp8KVCacheGDNHiCache already has. That class inherits every TestSGLangBitwiseParityGDN test, including the new test_prefill_graphs_capture_gdn_extend. It also runs outside batch-invariant mode, so the graph-captured GDN extend runs on the default chunk kernels with the same 1e-2 tolerance. The only extra this class adds is bf16 KV without HiCache, and neither of those is a GDN prefill-graph path. It still costs a full SGLang engine build in the B200 job: about 37 s of capture plus import time.
Per .claude/rules/tests.md ("don't ... duplicate coverage"; "prefer extending existing coverage"), either drop this class, or name the regression it would catch that the fp8 class misses. If it goes, _OutsideBatchInvariantMode has a single consumer again. Its overrides can then go back into TestSGLangFp8KVCacheGDNHiCache, which also removes the docstring and skip-message churn in this file and the workflow loop change.
There was a problem hiding this comment.
Reply from claude: Fixed in 706c97b: TestSGLangGDNOutsideBatchInvariantMode is gone. TestSGLangFp8KVCacheGDNHiCache keeps its own overrides again, as in the base PR, and the workflow adds only test_sglang_gdn_prefill_graph.py. The capture check moved to the base class (test_prefill_graphs_capture_linear_extend), so the fp8 class still runs it.
| if any(isinstance(layer.attention, GDN.Config) for layer in model.layers): | ||
| # At most 256 requests per prefill batch; SGLang runs the rest in the next | ||
| # prefill step. The GDN prefill graphs keep a table row per request, and each | ||
| # row costs GPU time in every GDN layer: 1,024 rows add about 3 ms to a | ||
| # 2,048-token Qwen3.5-0.8B prefill (13 ms with 256 rows, one GB300). | ||
| server_kwargs["prefill_max_requests"] = 256 |
There was a problem hiding this comment.
The cap's condition (GDN + breakable) doesn't match the condition for capturing the extend (TorchTitanGDNAttnBackend.supports_prefill_graph_extend: not a draft worker, attn_dp_size == 1).
Under attention DP > 1 the GDN extend stays eager and no tables are built, yet prefill batches are still capped at 256 requests. That splits large bursts (e.g. a GRPO group's followers) over extra prefill steps for no benefit, which is a small throughput regression on a path that works today.
Suggest gating it the same way, e.g. and parallelism.data_parallel_degree == 1, with a pointer to supports_prefill_graph_extend so the two conditions stay in sync. Unverified: whether SGLang applies prefill_max_requests per DP rank or globally, which also changes the effective cap at DP > 1.
There was a problem hiding this comment.
Reply from claude: Fixed in 706c97b: the cap now applies only at data_parallel_degree == 1, with a pointer to TorchTitanLinearAttnBackend.supports_prefill_graph_extend, the hook it mirrors. Under attention DP the extend stays eager, and prefill batches are uncapped as on main.
There was a problem hiding this comment.
Reply from claude: In a4febaf (comment only), the TODO at supports_prefill_graph_extend gives the right reason the extend stays eager under attention DP. SGLang replays prefill graphs there only on steps where no DP rank decodes: a decoding rank votes against them for SSM models. So the follow-up needs only an idle rank's made-up request masked, plus a DP 2 test.
…tch-invariant class; cap prefill batches only at attention DP 1
|
Reply from claude: Fixed in 706c97b. I dropped the duplicate class, gated the cap on attention DP 1, and KDA now runs in the graphs too. The overlap with the full-prefill-graphs draft stays a maintainer's call. Two facts on this pin bear on it (below). Duplicate class. Cap under attention DP. The cap now follows the hook's condition: # before
if any(isinstance(layer.attention, GDN.Config) for layer in model.layers):
# after
# Attention DP keeps the linear attention extend eager, with no tables
# (TorchTitanLinearAttnBackend.supports_prefill_graph_extend).
if parallelism.data_parallel_degree == 1 and any(
isinstance(layer.attention, LinearAttention.Config) for layer in model.layers
):KDA. The tables were already shared, so KDA needed only three changes:
The capture check is now Overlap with the full-prefill-graphs draft. On this pin (SGLang 851642ade), that draft can't replace this one as written:
This PR's tables carry the snapshots. A local prototype runs full prefill graphs on them, and its numbers will decide whether it becomes a follow-up PR. Questions.
@claude please review |
|
Claude finished @felipemello1's task in 2m 58s —— View job Approve -- review posted. |
There was a problem hiding this comment.
Verdict: Approve -- 706c97b resolves both must-fix items from my last review. The author's reply also shows that draft #6200 can't replace this PR on the current SGLang pin, nor with its upstream fix.
What this PR does. SGLang's breakable prefill graphs used to break at every GDN and KDA layer, about 2 ms of host time per layer. TorchTitanLinearAttnBackend now implements SGLang's prefill-graph hooks. Each captured bucket gets static tables (offsets, slots, snapshot slots and lengths, conv-history rows), refilled before each replay with device copies only. The GDN and KDA extends zero the bucket's tokens past the batch. At attention DP 1, the engine caps prefill batches at 256 requests for linear attention models.
Example.
Qwen3.5-0.8B, one 2,048-token prefill, breakable:
before: [graph] GDN [graph] GDN [graph] GDN [graph] attn ... 47.3 ms
after: [graph: GDN GDN GDN] attn [graph: GDN GDN GDN] ... 13.2 ms
bucket of 512 tokens, table rows for 160 requests, batch of 2:
cu_seqlens [0, 100, 130, 130, ...] state_indices [5, 9, -1, ...]
untracked/padding rows: conv history -> dummy slot 0; tokens 130.. zeroed
Earlier items
- Overlap with #6200 (gate): resolved. That draft's upstream fix (sgl-project/sglang#51225) refuses
enable_mamba_extra_bufferin full prefill graphs, and the engine always turns it on for GDN and KDA. So #6200 can't replace this PR as written. The author also plans to build full prefill graphs on these same tables. Unverified: the SGLang source lines the author cites. - Duplicate
TestSGLangGDNOutsideBatchInvariantMode: resolved, the class is removed. - Cap under attention DP: resolved.
engine.py:561now gates ondata_parallel_degree == 1, which matchessupports_prefill_graph_extend(attn_dp_size == data_parallel_degree,engine.py:502).prefill_graph_max_seqsreads SGLang'sprefill_max_requests, so 256 has one source. - Questions on double translation, slot 0, and KDA: answered or done.
Should consider
engine.py:142-145: thecuda_graphdocstring for"breakable"doesn't mention the new user-visible 256-request prefill cap for linear attention models. Only the README does. One clause there would save a reader from wondering why a large GRPO burst prefills over several steps.
Details
- Re-reviewed every commit since my last full review (through 706c97b), not only the fix commit.
- KDA:
kda.pyzeroesoutput_1THKatpadding_tokens[None, :, None, None], which matches its[1, T, H, K]output.supports_prefill_graph_extendnow lives on the shared base. - Table capacity: a bucket's
max_seqs = min(num_tokens, prefill_graph_max_seqs). A replayed batch has at most as many requests as tokens, and at mostprefill_max_requests, socu_seqlens[:batch_size].copy_(...)can't overflow while the hook is on. - Stale
prefill_graph_metadataafter a replay: only an eagerinit_forward_metadataclears it. Decode doesn't read it, and every eager extend callsinit_forward_metadatafirst, so no path reads stale tables. - Graph branch of
track_extend_statesvs eager: tracked rows write the same rows and lengths, with the same clamp. Untracked and padding rows write duplicate indices into slot 0, so which write wins there is nondeterministic. That is harmless: padding rows run on slot -1 and skip it. - vLLM counterpart:
vllm/attention/linear_attention.pykeeps its own staticquery_start_loc/state_indicesbuffers for vLLM's builder. The two engines' hook contracts differ, so a shared table type would need a shared metadata contract. No finding. - Overlap search: "prefill graph linear attention" and the changed files. Found #6200, #6403 (vLLM side, no overlap), #6414 and #6318 (same files, already listed in the description), and #6417 (also edits
sglang/engine.pyand the README: a rebase only).
Not verified: SGLang's hook call order and prefill_max_requests semantics (no SGLang source in this checkout; covered by test_prefill_graphs_capture_linear_extend and the bitwise classes on GPU). The GDN classes first run the captured extend at TP 2 in CI.
Before merge: fill in the human-written summary.
…steps where no DP rank decodes
Summary (human-written)
Agent details
TLDR: TorchTitan's SGLang linear attention backends run the GDN and KDA prefill inside SGLang's breakable prefill CUDA graphs. Before, every GDN or KDA layer broke the graph and ran eagerly, at about 2 ms of host time per GDN layer. Qwen3.5-0.8B on one GB300, one 2,048-token prefill: 47.3 -> 13.2 ms (vLLM: 12.7 ms). On a 128-session agent load: 5,960 -> 8,551 output tok/s, +43% (vLLM: 8,926-9,520).
Problem
MambaAttnBackendBase:supports_prefill_graph_extend,init_prefill_graph_metadata,refresh_prefill_graph_metadataandprefill_graph_extend_active.Solution
TorchTitanLinearAttnBackendimplements the hooks with onePrefillGraphMetadataper captured bucket: request offsets, state slots,has_initial_state, prefix-cache snapshot slots and lengths, and conv-history rows.refresh_prefill_graph_metadatarefills them from the batch before each replay, with device copies only (no host sync). Rows past the batch are empty sequences on slot -1, which Attention Gym's kernels skip.prefill_max_requeststo 256: a prefill batch has at most 256 requests, and the tables at most 256 rows.layer_router.wait_for_part(STATE_PART)). The host does not block.Results
+43% (bf16) and +50% (fp8) over main. The harness's run-to-run spread is 3-6% (two runs per engine at bf16). SGLang now makes 0.90-0.96x vLLM's output tok/s at bf16 (was 0.63-0.67x). KV capacity is unchanged: 10.6M tokens at bf16, 21.2M at fp8.
What a table row costs, which sets the 256-request cap. One GDN layer in a graph on one GB300, a 2,048-token bucket with 2 real requests of 1,024 tokens, GPU time, median of 30 replays:
An agent load of 1,024 sessions never put more than 21 requests in one prefill batch (990 prefill steps). A larger burst (a GRPO group's followers, a round of short prompts) is split over prefill steps, all in graphs: at
max_num_seqs600, a leader's 599 followers ran as 256, 256 and 87.Why 256, not SGLang's own default of 128? The speed numbers above were measured with 256-row tables, and 128 would split those bursts twice as often. 128 would save about 0.45 ms per 2,048-token 0.8B prefill and 3.5 ms per 27B prefill.
Capture cost, 74 prefill buckets up to 16,384 tokens (SGLang's capture log; 0.8B fp8: two runs of this PR):
The engine build in the load runs grew more than that: 73.8 -> 81.9 s at bf16, 82.6 -> 114.1 s at fp8. The extra is import time, not this PR. A CPU-only import of the engine module took 36 s and 80 s in two back-to-back runs.
You may ask:
cuda_graph="full"for linear attention models, and it waits on an SGLang PR and a pin bump. This PR changes only"breakable", on the current pin. We also tried full prefill graphs on this PR's tables. They add little over breakable ones, so that prototype is parked on a branch of the author's fork:init_forward_metadata_out_graph, because SGLang's full-graph metadata path refuses the extra_buffer prefix cache (sgl-project/sglang#51225). And it checks TorchTitan's attention backend asfa3in SGLang's unified-memory check, which otherwise turns full prefill graphs off with only a warning (the draft above hits the same check). How the two PRs land together is a maintainer's call.GDNPrefillGraphMetadata)? Its tables index SGLang's Triton kernels (chunk indices, conv blocks). TorchTitan runs the trainer's Attention Gym kernels, which take only offsets and slots. This PR reuses the hook contract, not the tables.meta-pytorch/attention-gym#980). A batch with no snapshot pays for it. Fused takes 1.6-2.0x warpdrive's GPU time per layer in a graph: 0.163 vs 0.092 ms (0.8B, 2,048 tokens), 0.704 vs 0.356 ms (27B, 8,192 tokens), so about +17 ms per 8,192-token prefill over 48 layers. The open draft "GDN/KDA chunk kernels: always fused" makes eager run fused too.prefill_max_requests, SGLang moves the extra requests to the next prefill step instead.NOTE: stacked on "[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward". Its fp8 class (
TestSGLangFp8KVCacheGDNHiCache) is this PR's default-mode check of the captured GDN extend.NOTE: open drafts that touch the same code:
track_extend_states, where this PR adds its graph branch. The SGLang internals this PR reads (listed in the code's TODO on SGLang's extra_buffer hooks) move to those hooks.TorchTitanGDNAttnBackend,convolve_extendand the README. Whichever lands second rebases. MTP and these prefill graphs have not run together; the draft runners keep their eager GDN extend.NOTE: the static pool (KV and GDN states) keeps its size: the graphs take their extra memory from what
gpu_memory_limitleaves for activations. A model near its memory limit has less headroom.NOTE: with HiCache, a prefill that loads states back now waits for the last state layer's copy before its first GDN layer. The eager path waited one layer at a time, overlapping the copy with compute. A prefill with no load-back waits on nothing.
Test plan
tests/rl/unit_tests/gpu/test_sglang_gdn_prefill_graph.py(new, 1 GPU), modeled on SGLang's owntest_gdn_prefill_graph.py: the production backend on test pools. It captures one 512-token bucket with rows for 160 requests, then replays 6 different batches in it: 141 requests in one batch, cached prefixes, tracked and untracked rows, padding rows, and batches without tracking. Each replay is compared with the eager extend of the same batch, on the output and on the whole conv and state pools; only the dummy slot 0 may differ.test_prefill_graphs_capture_linear_extend(new, in the parity tests' base class): during prefill replays, no GDN or KDA layer runs its extend eagerly. It runs in the GDN, GDN HiCache, fp8 and KDA classes, and skips where nothing captures the extend (no linear attention, no breakable graphs, or attention DP).TestSGLangBitwiseParityKDA(1 GPU in CI), with the KDA extend captured: 7 passed, all 21 trainer-vs-SGLang checks bitwise, on one GB300.TestSGLangFp8KVCacheGDNHiCache(fp8 KV, HiCache, extend captured): 8 passed, 2 skipped, mean |logprob diff| per sequence 1.2e-3 to 1.7e-3.TestSGLangBitwiseParityGDNandTestSGLangBitwiseParityGDNHiCachefirst run at TP 2 in CI.pytest tests/rl/unit_tests/cpu: 771 passed, 8 skipped, 2 failed. The 2 fail on main too:test_kv_offload_coordination.py::test_terminal_cleanup_preserves_block_identity, 2 cases.torchtitan/rl/): all hooks pass.