Repository navigation
[GLM-5.3-Flash] Capture the KDA extend in breakable prefill CUDA graphs - #41105
Conversation
00bb25c to
578dfdd
Compare
| track_state: Optional[torch.Tensor] = None, | ||
| track_chunk_idx: Optional[torch.Tensor] = None, | ||
| beta_is_raw: bool = False, | ||
| chunk_indices: Optional[torch.Tensor] = None, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Thanks for the comment, I synced the wrapper rather than relaxing the contract test.
mmangkad
left a comment
There was a problem hiding this comment.
Just need to address one blocker, the 128-seq cap is only checked at forward time, so DP ranks can split and hang
| # 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 |
There was a problem hiding this comment.
Seems already boundary-checked below, so just an early exit? (Also at L805-L808 and L986-L989)
There was a problem hiding this comment.
Yes, it is an early exit.
| track=( | ||
| get_exec().mamba.enable_mamba_extra_buffer | ||
| and not get_memory().disable_radix_cache | ||
| ), |
There was a problem hiding this comment.
enable_mamba_extra_buffer seems to already imply this
There was a problem hiding this comment.
enable_mamba_extra_buffer is derived from mamba_extra_buffer_of, I dropped the second check.
| 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() | ||
| ) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
Read the cap once in __init__? L561 reads it every prefill step
There was a problem hiding this comment.
Fixed and KDAAttnBackend.__init__ reads it once into prefill_graph_max_seqs.
Thanks for the comment. It is a good catch, I fixed it by moving the cap into can_replay_locally. |
0e54824 to
50dd61e
Compare
|
@mmangkad I addressed the comments, PTAL. |
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.
4f1b602 to
1ae80c9
Compare
…nt4 test tp_group) (#43334)
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.
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 inprepare_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_indicesbuilds the (sequence, chunk) table with.tolist(); it andprepare_chunk_offsetsaretensor_cached on the tensor object, so inside a capture they would hand back capture-time tables without recording anything.causal_conv1d_fnsizes its grid fromseq_lens_cpu, and the delta-rule state kernel launches one program per sequence.nonzeroand scatters with data-dependent shapes.Design
The KDA extend now runs inside the graph on static tables, and BCG breaks only at the DSA layers.
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_seqsandmax_conv_blocks = cdiv(T, 8) + max_seqs. The captured kernels launch fixed grids over these bounds.KDAPrefillGraphMetadata.fillrebuilds 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.cu_seqlens, padded chunk rows point past their sequence and return on ani_t * BT >= Tguard, padded conv blocks and state slots carryPAD_SLOT_ID, and rows past the batch's tokens are zeroed so the MoE and the collectives see finite values.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.RadixLinearAttentionskips the eager break when the backend runs the extend in the graph.can_run_prefill_cuda_graph.SGLANG_DISABLE_KDA_PREFILL_GRAPH_EXTEND=1restores the per-layer break.Modifications
layers/attention/linear/kda_prefill_graph.py(new): per-bucket tables, their refresh, the track plan, andkda_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_uand chunk output kernels;chunk_kdaaccepts precomputedchunk_indices/chunk_offsets.kernels/ops/attention/fla/chunk_delta_h.py: acceptschunk_offsetsinstead of deriving it throughtensor_cache.kernels/ops/mamba/causal_conv1d_triton.py: optional (sequence, block) table that sets the grid instead ofseq_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.pycaptures one bucket and replays it for five batches of different shapes, against the production eagerforward_extendon 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:
Performance
8x B300, GLM-5.3-Flash, cookbook B300 FP8 recipe (TP8, TRT-LLM DSA, FP8 KV,
flashinfer_trtllmMoE), random-ids, all servers on one box and one tree, no profiler: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