Skip to content

[GLM-5.3-Flash] Capture the KDA extend in breakable prefill CUDA graphs - #41105

Merged
BBuf merged 5 commits into
sgl-project:mainfrom
yuan-luo:glm53-kda-extend-graph
Oct 9, 2026
Merged

BBuf merged 5 commits into
sgl-project:mainfrom
yuan-luo:glm53-kda-extend-graph

Conversation

@yuan-luo

@yuan-luo yuan-luo commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

GLM-5.3-Flash (glm5_next) interleaves 34 KDA linear-attention layers with 11 DSA layers. Prefill CUDA graphs are auto-disabled for KDA models, and --cuda-graph-backend-prefill breakable (BCG) opts back in, but BCG breaks the graph at every linear-attention layer: the whole KDA extend runs eagerly on each replay, about sixteen Triton launches per layer plus their Python and the host syncs in prepare_chunk_indices.

From profiling the eager prefill is CPU launch-bound, not GPU-bound. A prefill step issues about 2300 kernel launches, and with the profiler on it costs about 300 ms of CPU whether it carries 1K or 16K tokens; without the profiler a single 1K-token prompt still waits 152 ms for its first token. BCG halves the launches to 1182 per step, yet a 4K-token step still spends 116 ms on the CPU (with the profiler on), and the KDA chain with its glue is more than 60% of what is left.

The KDA extend cannot simply be recorded: its launch grids and index tables come from host-side lengths that change on every replay of a bucket.

  • prepare_chunk_indices builds the (sequence, chunk) table with .tolist(); it and prepare_chunk_offsets are tensor_cached on the tensor object, so inside a capture they would hand back capture-time tables without recording anything.
  • causal_conv1d_fn sizes its grid from seq_lens_cpu, and the delta-rule state kernel launches one program per sequence.
  • The prefix-cache track path selects rows with host lists or nonzero and scatters with data-dependent shapes.

Design

image

The KDA extend now runs inside the graph on static tables, and BCG breaks only at the DSA layers.

  • For each token bucket T, capture allocates tables at the bucket's bounds: max_seqs = min(T, SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS) (128), max_chunks = cdiv(T, 64) + max_seqs and max_conv_blocks = cdiv(T, 8) + max_seqs. The captured kernels launch fixed grids over these bounds.
  • Before each replay, KDAPrefillGraphMetadata.fill rebuilds the tables from the batch's CPU lengths in numpy and ships them in one pinned asynchronous host-to-device copy; slots and prefix flags come from device gathers. Nothing synchronizes.
  • Padded rows cost nothing. Padded sequences are empty in cu_seqlens, padded chunk rows point past their sequence and return on an i_t * BT >= T guard, padded conv blocks and state slots carry PAD_SLOT_ID, and rows past the batch's tokens are zeroed so the MoE and the collectives see finite values.
  • Prefix-cache snapshots become a per-row table (none, final state, chunk-boundary state, conv window start, destination slot) read by two small Triton kernels, instead of host-selected scatters.
  • The hybrid backend follows the runner's existing captured-metadata contract for BCG (init_forward_metadata_for_breakable_cuda_graph_capture / prepare_forward_metadata_for_breakable_cuda_graph_replay, as DeepSeek-V4 already does). DSA keeps its eager metadata init. RadixLinearAttention skips the eager break when the backend runs the extend in the graph.
  • The path is active only under a breakable prefill backend, with the Triton KDA extend kernel and without fused-accept verify staging. A batch with more sequences than the cap runs eagerly through can_run_prefill_cuda_graph. SGLANG_DISABLE_KDA_PREFILL_GRAPH_EXTEND=1 restores the per-layer break.

Modifications

  • layers/attention/linear/kda_prefill_graph.py (new): per-bucket tables, their refresh, the track plan, and kda_extend_in_graph, the forward extend on those tables.
  • kernels/ops/attention/fla/kda_prefill_graph_track.py (new): the conv-window and SSM-state snapshot kernels over per-row modes.
  • kernels/ops/attention/fla/kda.py: out-of-range early return in the gate cumsum, recompute_w_u and chunk output kernels; chunk_kda accepts precomputed chunk_indices / chunk_offsets.
  • kernels/ops/attention/fla/chunk_delta_h.py: accepts chunk_offsets instead of deriving it through tensor_cache.
  • kernels/ops/mamba/causal_conv1d_triton.py: optional (sequence, block) table that sets the grid instead of seq_lens_cpu.
  • layers/attention/linear/kda_backend.py: capability checks, table capture and refresh, and the dispatch to the graph path.
  • layers/attention/hybrid_linear_attn_backend.py, base_attn_backend.py, layers/radix_linear_attention.py: the captured-metadata contract, the replay gate and the break decision.
  • environ.py: SGLANG_DISABLE_KDA_PREFILL_GRAPH_EXTEND, SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS.
  • test/registered/kernels/ops/attention/test_kda_prefill_graph.py (new).

Accuracy

test_kda_prefill_graph.py captures one bucket and replays it for five batches of different shapes, against the production eager forward_extend on cloned pools. The batches cover several sequences, cached prefixes, padding, chunk-aligned and unaligned prefix-cache snapshots, and no tracking. Every replay matches bit for bit on the output, the conv and SSM pools and the track slots, and no other pool slot changes.

The existing KDA, GDN, causal_conv1d, mamba2, radix linear attention and hybrid backend tests pass on B300 (13 files).

End to end, the natural-language greedy probes produce exactly the text of main's BCG, and GSM8K (200 questions, greedy) scores within one question of eager prefill:

Config GSM8K
eager prefill (cookbook default) 98.5%
main, BCG 98.5%
this PR, BCG 98.5%
this PR, BCG, 16K chunks 98.5%

Performance

8x B300, GLM-5.3-Flash, cookbook B300 FP8 recipe (TP8, TRT-LLM DSA, FP8 KV, flashinfer_trtllm MoE), random-ids, all servers on one box and one tree, no profiler:

Metric eager (default) main, BCG this PR, BCG this PR, BCG, 16K chunks
TTFT, 1 x 1K tokens 152 ms 47 ms 37 ms 39 ms
TTFT, 1 x 4K tokens 177 ms 152 ms 113 ms 95 ms
TTFT, 1 x 16K tokens 495 ms 419 ms 384 ms 333 ms
c64 1024/256 median TTFT 968 ms 767 ms 696 ms 708 ms
c64 1024/256 output tok/s 4291 4167 4268 4477
bs64 decode median ITL 9.69 ms 9.63 ms 9.62 ms 9.70 ms

With the profiler on, a 4093-token prefill step goes from 1182 eager launches and 116 ms of CPU under main's BCG to 439 launches and 42 ms, and the GPU now finishes 33-35 ms after the last launch: the step is GPU-bound. Prefill graph capture takes 85 s instead of 165 s.

"16K chunks" adds --chunked-prefill-size 16384 --cuda-graph-max-bs-prefill 16384 --mem-fraction-static 0.78. GLM-5 defaults BCG prefill to 4096-token chunks, so 16K buckets alone never replay; the 16K buckets cost about 22 GB more graph memory per GPU.


CI States

Latest PR Test (Base): ⏳ Run #37721340383
Latest PR Test (Extra): ✅ Run #37721340093
Latest PR Test (AMD ROCm 10): ❌ Run #37721340434

track_state: Optional[torch.Tensor] = None,
track_chunk_idx: Optional[torch.Tensor] = None,
beta_is_raw: bool = False,
chunk_indices: Optional[torch.Tensor] = None,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Helion wrapper still has the old signature, so test_public_signatures_match_triton now fails (kwargs != chunk_indices at index 17): CI.

Please sync the wrapper or update the contract test if these args are intentionally Triton-only.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comment, I synced the wrapper rather than relaxing the contract test.

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

Just need to address one blocker, the 128-seq cap is only checked at forward time, so DP ranks can split and hang

Comment on lines +557 to +560
# Graph-safe varlen: padded chunk_indices rows point past their sequence
# (see kda_prefill_graph.py); they must not compute or write anything.
if i_t * BT >= T:
return

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.

Seems already boundary-checked below, so just an early exit? (Also at L805-L808 and L986-L989)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is an early exit.

Comment on lines +573 to +576
track=(
get_exec().mamba.enable_mamba_extra_buffer
and not get_memory().disable_radix_cache
),

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.

enable_mamba_extra_buffer seems to already imply this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enable_mamba_extra_buffer is derived from mamba_extra_buffer_of, I dropped the second check.

Comment on lines +557 to +562
def can_run_prefill_graph_extend(self, forward_batch: ForwardBatch) -> bool:
return (
forward_batch.extend_seq_lens_cpu is not None
and len(forward_batch.extend_seq_lens_cpu) == forward_batch.batch_size
and forward_batch.batch_size <= envs.SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS.get()
)

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 cap isn't in the DP prefill-graph vote, so ranks can split: DPA + BCG + --enable-mixed-chunk hangs once one rank's mixed batch passes 128

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same root cause as the blocker above, fixed.

cache_indices = self._prefill_graph_cache_indices(forward_batch)
meta = KDAPrefillGraphMetadata.allocate(
num_tokens=forward_batch.positions.shape[0],
max_seqs_cap=envs.SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS.get(),

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.

Read the cap once in __init__? L561 reads it every prefill step

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed and KDAAttnBackend.__init__ reads it once into prefill_graph_max_seqs.

@yuan-luo

yuan-luo commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Just need to address one blocker, the 128-seq cap is only checked at forward time, so DP ranks can split and hang

Thanks for the comment. It is a good catch, I fixed it by moving the cap into can_replay_locally.

@yuan-luo
yuan-luo force-pushed the glm53-kda-extend-graph branch 2 times, most recently from 0e54824 to 50dd61e Compare October 7, 2026 11:48
@yuan-luo
yuan-luo requested a review from hnyls2002 as a code owner October 7, 2026 11:48
@yuan-luo

yuan-luo commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@mmangkad I addressed the comments, PTAL.

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

LGTM, thanks

luoyuan.luo added 5 commits October 8, 2026 11:08
Breakable prefill CUDA graphs broke the graph at every KDA layer, because
the extend sizes its launch grids and index tables from host-side lengths
that change on each replay of a bucket. Capture the Triton KDA extend on
per-bucket static tables sized by the bucket's bounds, rebuild them from the
batch's CPU lengths before each replay (one async host-to-device copy, no
sync), and launch fixed grids whose padded rows return immediately.
Prefix-cache snapshots use per-row tables and two small Triton kernels.

The hybrid backend adopts the runner's captured-metadata contract for
breakable prefill graphs. Batches with more sequences than
SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS run eagerly, and
SGLANG_DISABLE_KDA_PREFILL_GRAPH_EXTEND restores the per-layer break.
The Triton chunk_kda gained chunk_indices / chunk_offsets for the CUDA-graph
captured KDA extend, which broke the Helion wrapper's signature contract
(test_public_signatures_match_triton). Take the same two arguments in the
Helion wrapper, use them in place of prepare_chunk_indices /
prepare_chunk_offsets when given, and forward them on the single-token Triton
fallback. Omitting them keeps the previous behavior.

The graph-captured extend stays Triton-only: Helion's state kernel has no
guard for the -1 state slot of padded rows. Say so where the backend gates it.
… vote

The KDA prefill graph's per-bucket tables hold at most
SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS sequences, but the cap was checked only at
forward time (HybridLinearAttnBackend.can_run_prefill_cuda_graph), after the
dp-attention ranks had voted to replay. A rank over the cap then ran eagerly
while the other ranks replayed the graph, and their collectives diverged.

The backend now declares the bound at init
(AttentionBackend.prefill_cuda_graph_max_batch_size), and the prefill runner
checks it in can_replay_locally, which feeds both the schedule-time vote and
the forward. The forward-time hook and the capture-time fallback it needed
are removed.

Reword the early-exit comments on padded chunk rows in the KDA kernels: the
stores below are already masked, so the exit only skips wasted work.
KDAAttnBackend reads SGLANG_KDA_PREFILL_GRAPH_MAX_SEQS once in __init__
(prefill_graph_max_seqs); the hybrid backend and the per-bucket table
allocation use that value. The track-table predicate is just
enable_mamba_extra_buffer, which already requires the radix cache.

The dp-vote regression test also covers mixed batches (--enable-mixed-chunk),
whose decode rows count against the bound too.
…nner

Unit tests build PrefillCudaGraphRunner with __new__ and set only the
fields can_replay_locally reads, so the new _captured_attn_metadata_max_bs
raised AttributeError there (test_cp_strategy_unit). Give it a class-level
None, like _backend_can_run_prefill_cuda_graph, so such runners keep the
unbounded behavior.
@yuan-luo
yuan-luo force-pushed the glm53-kda-extend-graph branch from 4f1b602 to 1ae80c9 Compare October 8, 2026 03:08
@mmangkad mmangkad changed the title [GLM-5.3] Capture the KDA extend in breakable prefill CUDA graphs [GLM-5.3-Flash] Capture the KDA extend in breakable prefill CUDA graphs Oct 8, 2026
@BBuf
BBuf merged commit 9a1aeac into sgl-project:main Oct 9, 2026
445 of 571 checks passed
mingfeima pushed a commit that referenced this pull request Oct 10, 2026
ormandj added a commit to ormandj/sglang that referenced this pull request Oct 11, 2026
Main's KDA extend forwards precomputed chunk_indices/chunk_offsets (sgl-project#41105). They index the whole extend, so a blocked call over a slice must not receive them; each block call derives its own from its cu_seqlens.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jit-kernel run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants