Skip to content

[rl] SGLang generator: run GDN and KDA prefill inside breakable prefill CUDA graphs - #6415

Draft
felipemello1 wants to merge 7 commits into
felipemello1/sgl203/s1-fp8-kv-cachefrom
felipemello1/sgl203/s2-gdn-prefill-graphs
Draft

felipemello1 wants to merge 7 commits into
felipemello1/sgl203/s1-fp8-kv-cachefrom
felipemello1/sgl203/s2-gdn-prefill-graphs

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Before this PR, every GDN layer breaks the breakable prefill graph and runs eagerly, about 2 ms of host time each, so a 2,048-token Qwen3.5-0.8B prefill takes 47.3 ms. This PR runs the GDN layers inside the graph segments, on tables refilled before each replay, so it takes 13.2 ms.

Problem

  1. SGLang's breakable prefill graphs capture the model in segments and run each attention layer eagerly in between. A linear attention layer breaks the graph too, unless its backend implements SGLang's prefill-graph hooks on MambaAttnBackendBase: supports_prefill_graph_extend, init_prefill_graph_metadata, refresh_prefill_graph_metadata and prefill_graph_extend_active.
  2. TorchTitan's GDN and KDA backends have none of them, so every GDN or KDA layer of every prefill step runs eagerly. One 2,048-token prefill (no profiler, one GB300):
    • Qwen3.5-0.8B (18 GDN layers): 47.3 ms wall for 6.9 ms of GPU work. 36.0 ms of it is host time inside the GDN layers (2.0 ms each).
    • Qwen3.5-27B (48 GDN layers): 108.3 ms wall for 74.2 ms of GPU work. 90.9 ms of it is host time inside the GDN layers (1.9 ms each).
  3. On the 128-session 0.8B agent load, prefill steps take 53% of SGLang's step time, and SGLang reaches 0.63-0.67x vLLM's output tok/s.

Solution

  1. Tables. TorchTitanLinearAttnBackend implements the hooks with one PrefillGraphMetadata per captured bucket: request offsets, state slots, has_initial_state, prefix-cache snapshot slots and lengths, and conv-history rows. refresh_prefill_graph_metadata refills 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.
  2. Fixed shapes. In the graph, every row copies its conv history. Untracked and padding rows copy into SGLang's dummy slot 0: a torch index write would wrap -1 to the pool's last slot, a real one. The GDN and KDA extends zero the tokens past the batch, which the kernels leave unwritten.
  3. Request cap. Every table row costs GPU time in every GDN or KDA layer, even when empty (see Results). So in breakable mode, for linear attention models at attention DP 1, the engine sets SGLang's prefill_max_requests to 256: a prefill batch has at most 256 requests, and the tables at most 256 rows.
  4. HiCache. SGLang waits for a layer's states to load back from host memory only in Python, when the layer reads them. A captured layer can't, so the refresh queues one stream wait for all state layers (layer_router.wait_for_part(STATE_PART)). The host does not block.
  5. Unchanged. Decode and SGLang's draft runners (MTP) keep their current path. Under attention DP > 1 the GDN and KDA extends stay eager, with no cap, and a TODO: no test class captures the extend at attention DP. There, SGLang replays prefill graphs only on steps where no DP rank decodes.

Results

Numerics, Qwen3.5 debug model (random weights), trainer vs SGLang logprobs, one GB300 at TP 1:
batch-invariant mode, GDN HiCache class            bitwise: 26 checks, 0 differ
batch-invariant mode, KDA class (Kimi K3 debug)     bitwise: 21 checks, 0 differ
default mode, fp8 KV + HiCache (GDN)                mean |logprob diff| per sequence 1.2e-3 to 1.7e-3 (bound 1e-2)
default mode, bf16 KV (GDN, a local class)          mean |logprob diff| per sequence 0.9e-3 to 1.6e-3 (bound 1e-2, three runs)
default mode, a prefill batch with no snapshot      the graph runs the fused chunk kernel, where main ran warpdrive:
                                                    rel L2 4.2e-3 between the two (one layer, 0.8B and 27B shapes)
Qwen3.5-0.8B, one GB300, cuda_graph "breakable", max_num_seqs 256, max_num_batched_tokens 16,384,
128 closed-loop agent sessions (4,000-token shared first prompt, 100-800 output tokens per turn,
200-3,000 tool tokens, 12k-40k tokens per session), 60 s warmup + 120 s window, one run per arm:
                     out tok/s   prefill step                share of step time   decode step   TTFT p50
main, bf16 KV        5,960       49.5 ms, 2,168 tokens avg   53%                  4.77 ms       90 ms
this PR, bf16 KV     8,551       12.2 ms, 2,026 tokens avg   21%                  4.69 ms       19 ms
main, fp8 KV         6,443       50.7 ms, 2,218 tokens avg   58%                  3.97 ms       93 ms
this PR, fp8 KV      9,638       11.9 ms, 2,027 tokens avg   23%                  4.03 ms       19 ms
vLLM on the same load: 8,926 and 9,520 (bf16 KV, two runs), 9,395 (fp8 KV).
one 2,048-token prefill per request (max_tokens 1), mean of 10, no profiler, one GB300:
                 main                                          this PR
Qwen3.5-0.8B     47.3 ms (36.0 ms host time in 18 GDN breaks)  13.2 ms, no GDN break    vLLM FULL graphs: 12.7 ms
Qwen3.5-27B      108.3 ms (90.9 ms in 48 GDN breaks)           86.0 ms, no GDN break    main's GPU work: 74.2 ms

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

table rows   Qwen3.5-0.8B: one layer, x 18 layers   Qwen3.5-27B: one layer, x 48 layers
128          0.202 ms, 3.6 ms                       0.373 ms, 17.9 ms
256          0.227 ms, 4.1 ms                       0.446 ms, 21.4 ms
1,024        0.391 ms, 7.0 ms                       0.903 ms, 43.4 ms

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_seqs 600, 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):

                                     main      this PR
prefill capture, 0.8B bf16           32 s      37-38 s
prefill capture, 0.8B fp8            31 s      44-46 s
prefill capture, 27B bf16            62 s      74 s
graph memory held after capture      0.8B: +1.05 GB, 27B: +1.33 GB

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:

  • How does this relate to the open draft "[rl] SGLang generator: full prefill CUDA graphs for linear attention (GDN, KDA) models"? That PR adds 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:
    full vs breakable prefill graphs, both on this PR's tables, one GB300, one run per arm:
    load                                   out tok/s       prefill share (breakable)    engine build
    Qwen3.5-0.8B, 128 sessions (2 pairs)   +3.2%, +2.6%    21%                          +25-28 s
    Qwen3.5-27B, 54 sessions               +0.9%           4%                           +22 s
    
    Full graphs remove only the attention layers' breaks, so they help only where prefill is a large share of the step. The prototype needed two workarounds on this pin. It overrides 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 as fa3 in 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.
  • Why not reuse SGLang's own GDN prefill graph (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.
  • Why does the graph always run the fused chunk kernel? Every replay may take a prefix-cache snapshot, so the tables always pass snapshot slots, and warpdrive can't write snapshots yet (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.
  • Why cap the prefill batch, not only the tables? SGLang runs a batch with more requests than the tables fully eager, with no graph at all: 71.5 ms per 2,048-token 0.8B prefill, slower than main's 47.3 ms. With 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:

  • "use SGLang's public extra_buffer hooks for GDN and KDA" rewrites 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.
  • "GDN/KDA chunk kernels: always fused" (above).
  • "[rl] SGLang generator: MTP speculative decoding for Qwen3.5" edits TorchTitanGDNAttnBackend, convolve_extend and 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_limit leaves 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 own test_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.
    • Bitwise in batch-invariant mode, and outside it for batches with snapshots (the fused kernel on both sides). Within rel L2 1e-2 for batches without snapshots (graph fused, eager warpdrive).
    • 2 passed (default, batch-invariant) on one GB300.
    • It fails if untracked rows copy their conv history to -1 (the conv pool differs), or if the padding tokens are not zeroed.
  • 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.
  • The bf16 row of the numerics block is a local run of the GDN tests outside batch-invariant mode (not added: the fp8 class covers the same captured path).
  • On one GB300 (this box has one GPU), at TP 1: the batch-invariant GDN HiCache class, which runs every test of the GDN class plus the host load-back test, with the GDN extend captured: 10 passed (9 plus a local check that the cap is 256), all 26 trainer-vs-SGLang checks bitwise. TestSGLangFp8KVCacheGDNHiCache (fp8 KV, HiCache, extend captured): 8 passed, 2 skipped, mean |logprob diff| per sequence 1.2e-3 to 1.7e-3. TestSGLangBitwiseParityGDN and TestSGLangBitwiseParityGDNHiCache first run at TP 2 in CI.
  • CI: the B200 RL job's SGLang step runs the new test file.
  • 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.
  • pre-commit on the changed files (pyrefly excludes torchtitan/rl/): all hooks pass.

…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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 27, 2026
@felipemello1
felipemello1 added this pull request to stack #6416 November 27, 2026 20:56
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

  1. 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 rewrites track_extend_states where the graph branch goes, and #6294 / #6414, which touch the same files.
  2. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:648 -- TestSGLangGDNOutsideBatchInvariantMode duplicates TestSGLangFp8KVCacheGDNHiCache'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 _OutsideBatchInvariantMode mixin 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, where supports_prefill_graph_extend is False and no tables exist. Gate it the same way.

Questions

  • linear_attention.py:269-272 rewrites forward_batch.mamba_track_indices in place with _translate_mamba_indices. Can SGLang call refresh_prefill_graph_metadata twice on the same batch, or run the eager init_forward_metadata on 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 own IdSpace with 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_extend plus the padding masked_fill_, and a KDA model breaks the graph at every layer today.
Details
  • Overlap search: gh pr list --search for "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 GDNPrefillGraphMetadata indexes 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_metadata after a replay: only init_forward_metadata clears it, and decode-graph replay doesn't call that. forward_decode doesn'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_metadata has no host sync: sum(extend_seq_lens_cpu) is a host list, and the rest are device copies, torch.where and clamp(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.

Comment on lines +648 to +656
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

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

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

Comment on lines +560 to +565
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

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

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

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: 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
@felipemello1 felipemello1 changed the title [rl] SGLang generator: run GDN prefill inside breakable prefill CUDA graphs [rl] SGLang generator: run GDN and KDA prefill inside breakable prefill CUDA graphs Nov 27, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

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. TestSGLangGDNOutsideBatchInvariantMode is gone. The test file is the base PR's again, plus one test. The workflow adds only the new kernel test file.

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:

  1. supports_prefill_graph_extend moved from the GDN backend to TorchTitanLinearAttnBackend.
  2. The KDA extend zeroes padding_tokens, as GDN does.
  3. The cap covers KDA models.

The capture check is now test_prefill_graphs_capture_linear_extend, in the base class. It runs in every GDN and KDA class, and skips where nothing captures the extend.

Overlap with the full-prefill-graphs draft. On this pin (SGLang 851642ade), that draft can't replace this one as written:

  1. [Fix] cuda_graph: Capture full prefill CUDA graphs of linear attention backends on static forward metadata sgl-project/sglang#51225 refuses the extra_buffer prefix cache in full prefill graphs. Its _init_full_cg_prefill_metadata raises when enable_mamba_extra_buffer is on. The engine turns it on for GDN and KDA (registry.py, support_mamba_cache_extra_buffer=True; mamba_track_interval=64).
  2. SGLang turns the FULL prefill backend off under enable_unified_memory unless the attention backend is named fa3 or fa4 (arg_groups/kv_cache_hook.py:643-672). The engine sets unified memory for every linear attention model. So today cuda_graph="full" for these models prefills eagerly, with only a warning.

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.

  • Double translation.
    • SGLang runs each prefill either as a graph replay or eagerly, never both (model_executor/model_runner.py:2090-2120).
    • A breakable replay calls the refresh once (prefill_cuda_graph_runner.py:1411).
    • SGLang's eager metadata translates mamba_track_indices in place the same way, once per forward (hybrid_linear_attn_backend.py:220-223).
    • Under unified memory the translation maps virtual ids to physical slots, so it is not idempotent. Both paths keep the once-per-forward rule.
  • Slot 0 under unified memory. It is reserved.
    • "Padded rows carry req-pool row 0, which maps to the reserved mamba padding slot 0 in both the static and the unified pool" (hybrid_linear_attn_backend.py:209-210).
    • The unified allocator's size excludes it (mem_cache/unified_memory_pool.py:46).
    • The HiCache classes run on unified memory (test_runs_on_unified_memory) and stay bitwise.

@claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 58s —— View job


Approve -- review posted.

@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 -- 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_buffer in 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:561 now gates on data_parallel_degree == 1, which matches supports_prefill_graph_extend (attn_dp_size == data_parallel_degree, engine.py:502). prefill_graph_max_seqs reads SGLang's prefill_max_requests, so 256 has one source.
  • Questions on double translation, slot 0, and KDA: answered or done.

Should consider

  • engine.py:142-145: the cuda_graph docstring 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.py zeroes output_1THK at padding_tokens[None, :, None, None], which matches its [1, T, H, K] output. supports_prefill_graph_extend now 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 most prefill_max_requests, so cu_seqlens[:batch_size].copy_(...) can't overflow while the hook is on.
  • Stale prefill_graph_metadata after a replay: only an eager init_forward_metadata clears it. Decode doesn't read it, and every eager extend calls init_forward_metadata first, so no path reads stale tables.
  • Graph branch of track_extend_states vs 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.py keeps its own static query_start_loc/state_indices buffers 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.py and 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant