Repository navigation
[AMD] [GLM5] Skip DSA decode indexer when kv_len <= index_topk (dense k-only fast path) - #31324
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a dense-decode optimization for DSA models, allowing the indexer's logits computation to be skipped (k-only path) during decode when the sequence length is within the top-k threshold. This is supported in both eager mode and via a dual-graph CUDA graph capture mechanism. The review feedback highlights opportunities to improve robustness by using the central envs registry instead of direct os.environ.get calls (ensuring proper boolean parsing) and adding .numel() > 0 checks to prevent RuntimeErrors when calling .max() on empty sequence length tensors.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| # M2a "static" fallback (no dual-variant capture active): enable | ||
| # k-only only when the deployment guarantees every request's | ||
| # kv_len<=index_topk (e.g. i1k/o1k). WRONG for mixed >2K traffic. | ||
| import os | ||
|
|
||
| return os.environ.get("SGLANG_DSA_DECODE_DENSE_GRAPH", "0") == "1" |
There was a problem hiding this comment.
Using os.environ.get directly bypasses the envs configuration registry. More importantly, os.environ.get(..., "0") == "1" only evaluates to True if the environment variable is exactly "1". If a user sets SGLANG_DSA_DECODE_DENSE_GRAPH=True or SGLANG_DSA_DECODE_DENSE_GRAPH=true, this check will evaluate to False. Using envs.SGLANG_DSA_DECODE_DENSE_GRAPH.get() correctly utilizes the central environment variable registry and its boolean parsing logic.
| # M2a "static" fallback (no dual-variant capture active): enable | |
| # k-only only when the deployment guarantees every request's | |
| # kv_len<=index_topk (e.g. i1k/o1k). WRONG for mixed >2K traffic. | |
| import os | |
| return os.environ.get("SGLANG_DSA_DECODE_DENSE_GRAPH", "0") == "1" | |
| # M2a "static" fallback (no dual-variant capture active): enable | |
| # k-only only when the deployment guarantees every request's | |
| # kv_len<=index_topk (e.g. i1k/o1k). WRONG for mixed >2K traffic. | |
| return envs.SGLANG_DSA_DECODE_DENSE_GRAPH.get() |
There was a problem hiding this comment.
Done — switched to envs.SGLANG_DSA_DECODE_DENSE_GRAPH.get() in commit 474270e so it goes through the EnvBool parser (accepts true/1/yes).
| if forward_batch.forward_mode.is_decode_or_idle() and layer_id == 0: | ||
| import os | ||
|
|
||
| if os.environ.get("SGLANG_KONLY_DEBUG", "0") == "1": | ||
| logger.info( | ||
| "[KONLY] decode k-only fired (skip-indexer): num_tok=%d", | ||
| x_meta.shape[0], | ||
| ) |
There was a problem hiding this comment.
Using os.environ.get directly bypasses the envs configuration registry. More importantly, os.environ.get(..., "0") == "1" only evaluates to True if the environment variable is exactly "1". If a user sets SGLANG_KONLY_DEBUG=True or SGLANG_KONLY_DEBUG=true, this check will evaluate to False. Using envs.SGLANG_KONLY_DEBUG.get() correctly utilizes the central environment variable registry and its boolean parsing logic.
if forward_batch.forward_mode.is_decode_or_idle() and layer_id == 0:
if envs.SGLANG_KONLY_DEBUG.get():
logger.info(
"[KONLY] decode k-only fired (skip-indexer): num_tok=%d",
x_meta.shape[0],
)There was a problem hiding this comment.
Done — switched to envs.SGLANG_KONLY_DEBUG.get() in commit 474270e, same EnvBool parsing.
| if fb.seq_lens_cpu is not None: | ||
| max_kv_len = int(fb.seq_lens_cpu.max().item()) | ||
| elif fb.seq_lens is not None: | ||
| max_kv_len = int(fb.seq_lens.max().item()) | ||
| else: | ||
| return False | ||
| return max_kv_len <= self.index_topk |
There was a problem hiding this comment.
If fb.seq_lens_cpu or fb.seq_lens is empty (i.e., has 0 elements), calling .max() on it will raise a RuntimeError. Adding a .numel() > 0 check ensures robustness against empty batches.
| if fb.seq_lens_cpu is not None: | |
| max_kv_len = int(fb.seq_lens_cpu.max().item()) | |
| elif fb.seq_lens is not None: | |
| max_kv_len = int(fb.seq_lens.max().item()) | |
| else: | |
| return False | |
| return max_kv_len <= self.index_topk | |
| if fb.seq_lens_cpu is not None and fb.seq_lens_cpu.numel() > 0: | |
| max_kv_len = int(fb.seq_lens_cpu.max().item()) | |
| elif fb.seq_lens is not None and fb.seq_lens.numel() > 0: | |
| max_kv_len = int(fb.seq_lens.max().item()) | |
| else: | |
| return False | |
| return max_kv_len <= self.index_topk |
There was a problem hiding this comment.
Done in 27bd826 — added .numel() > 0 checks to both the seq_lens_cpu and seq_lens branches before .max(), consistent with the existing empty-batch guard elsewhere in this file.
…ger) When kv_len <= index_topk the DSA top-k selects all valid positions, so the indexer logits GEMM + paged_mqa_logits + top-k are pure waste. Route decode through the existing _forward_cuda_k_only path (dummy-logits topk_transform -> correct physical page-slot indices), instead of the spike's arange() identity synthesis which was wrong under SGLANG_DSA_FUSE_TOPK (indices are physical slots, not logical positions) -> GSM8K 0.02. - _should_skip_logits_computation: allow is_decode_or_idle() with the same max_kv_len <= index_topk test; gated off during cuda-graph capture (the captured branch would be frozen and replay wrong for kv_len>index_topk). - _forward_cuda_k_only: relax the extend-only assert to also accept decode. Eager-mode only for now (Milestone 1: correctness). Cuda-graph dense/sparse variant + can_run_graph gating is Milestone 2.
…a-graph decode k-only (kv_len<=index_topk deployments)
…t dispatch Capture two decode graph variants per bs bucket -- "dense" (k-only, skip-indexer) and "sparse" (full indexer) -- and select which to replay on the host from max_kv_len vs index_topk. Correct for mixed/arbitrary context length under cuda graph (>2K routes to sparse, <=2K to dense), never falling back to eager. - capture_mode.py: add _capture_dsa_variant signal (mirrors lora variant) - dsa_indexer.py: _should_skip_logits_computation capture branch honors the variant (dense->skip, sparse->full); M2a static env kept as fallback - shape_key.py: add dsa_variant to ShapeKey (composes with lora variant_label) - decode_cuda_graph_runner.py: capture dense+sparse per bs; _resolve_dsa_variant dispatches on host seq_lens_cpu (no d2h); env-gated dispatch debug log - environ.py: register SGLANG_DSA_DECODE_DUAL_GRAPH / _DENSE_GRAPH / KONLY_DEBUG Validated (GLM-5.2-MXFP4 TP4 MI355X, index_topk=2048): GSM8K under graph 0.950; long >2K needle recall correct; i1k dense -3~5% TPOT; i8k no regression; dual capture ~55s (~2x), no OOM.
d8c3c81 to
0c41aca
Compare
SGLANG_DSA_DECODE_DENSE_GRAPH and SGLANG_KONLY_DEBUG are declared as EnvBool (accepts true/1/yes/y), but dsa_indexer.py read them with os.environ.get(...) == "1", so common forms like SGLANG_DSA_DECODE_DENSE_GRAPH=true silently no-op'd. Use envs.<FLAG>.get() for both so behavior matches the EnvBool declaration and the rest of the codebase's env conventions. Co-authored-by: Cursor <[email protected]>
…ner (--mtp) EAGLEDraftCudaGraphRunner subclasses DecodeCudaGraphRunner and reuses its capture(), but does not run DecodeCudaGraphRunner.__init__ (so it never sets dsa_dual_graph) and overrides capture_one_shape with a signature that has no dsa_variant. Under --mtp this raised AttributeError: 'EAGLEDraftCudaGraphRunner' object has no attribute 'dsa_dual_graph' at cuda-graph capture. Guard the dual-graph checks with getattr(..., False) and, for the None variant, call capture_one_shape without the extra dsa_variant arg so the narrower draft override still works. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]> # Conflicts: # python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py
Add .numel() > 0 checks before calling .max() on seq_lens_cpu / seq_lens in _should_skip_logits_computation, so an empty batch cannot raise a RuntimeError. Consistent with the existing numel guard elsewhere in this file. Addresses review feedback on the extend and eager-decode gates.
clintg6
left a comment
There was a problem hiding this comment.
@Jacob0226 Tested on MI355X with GLM-5.2-MXFP4 (TP8, 1024 ISL / 1024 OSL). The dual-graph dispatch works correctly. Benchmark results showed around 3% uplift in Total token throughput. With that said, I have a number of recommendations to improve the PR.
Remove SGLANG_KONLY_DEBUG
This appears to be a leftover debug flag. It's only used to gate a single logger.info call in _forward_cuda_k_only, so it shouldn't ship in production. Remove it from environ.py and the associated logging block in dsa_indexer.py.
Remove SGLANG_DSA_DECODE_DUAL_GRAPH and auto-enable for DSA models
Since DSA models already expose index_topk in their HF config, users shouldn't need to enable this manually. Auto-detect DSA models instead:
# Instead of:
self.dsa_dual_graph = envs.SGLANG_DSA_DECODE_DUAL_GRAPH.get()
# Use:
self.dsa_dual_graph = self.dsa_index_topk is not NoneRemove SGLANG_DSA_DECODE_DENSE_GRAPH
This forces dense decode by unconditionally bypassing the indexer, making it another debug/testing override and is unnecessary.
|
/rerun-failed-ci |
|
/rerun-failed-ci |
|
@amd-bot ci-status |
CI Status for PR #31324Merge verdict: ⛔ Do not merge on green alone. PR CI is incomplete (AMD downstream fast-fail skipped) and this PR's core changed code is not exercised by any PR-CI test. All 4 executed failures are pre-existing/infra issues unrelated to this DSA decode change — but "0 related failures" here does not mean the PR is verified. The new k-only / dual-graph decode path is AMD-only + DSA-model-gated, and nothing in PR CI loads a DSA model on AMD. Caution Two coverage gaps, both blocking verification:
Before merge: run a DSA model (GLM-5.2 / DeepSeek-V3.2) decode on AMD MI300 to actually exercise Changed files: Executed CI failure attribution: AMD: 1 executed failure (0 related) · NPU: 2 (0 related) · MLX: 1 (0 related). No jobs pending. (11 AMD downstream jobs skipped by fast-fail — counted as a completeness gap above, not as failures.) AMD Executed Failures
Other Executed Failures
Cascade/aggregator failures collapsed (not independent): Details / what to do before merge
Generated by amd-bot using Claude Code CLI |
|
/rerun-failed-ci |
|
@amd-bot ci-status |
CI Status for PR #31324Merge verdict: No blocking PR-caused failures — all 3 executed test failures are in code paths this PR does not touch (AMD allreduce-fusion mock, NPU MiniMax perf, NVIDIA NIXL RDMA infra). But do not merge on "green" alone: this PR's entire value — the DSA decode skip-indexer fast path for GLM5/DeepSeek-V3.2 on AMD — is exercised only by Caution This PR's changed code is not exercised by any PR-CI test. The DSA decode-indexer fast path in Changed files: Executed CI failure attribution: AMD: 1 failure (0 related) · Others: 2 root failures (0 related) — NPU perf2/4/16 are fast-fail cascades of NPU perf8; B200 shard cancelled (infra); all AMD Executed Failures
Other Executed Failures
Details / what to do before merge
Generated by amd-bot using Claude Code CLI |
|
CI green, final update to comment 903fe7d |
… k-only fast path) (sgl-project#31324) Co-authored-by: Thomas Wang <[email protected]> Co-authored-by: HaiShaw <[email protected]>
Summary
kv_len <= index_topkthe top-k selects all valid positions, so the indexer's logits GEMM +paged_mqa_logits+ top-k selection is wasted work. Add a k-only fast path that skips the indexer, stores the K cache, and generates the identity index directly ([0, 1, ..., kv_len-1, -1, ...]), feeding the same sparse-MLA decode attention kernel.max_kv_lenvsindex_topkat replay. This is correct for mixed lengths — any request withkv_len > index_topkin the batch falls back to the sparse graph.index_topkin their HF config, the dual-graph is turned on automatically wheneverindex_topkis present (dsa_dual_graph = dsa_index_topk is not None); non-DSA models and other archs are unaffected. Eager decode takes the same fast path per-step when safe. (NoSGLANG_DSA_DECODE_*/SGLANG_KONLY_DEBUGenvironment variables — an earlier revision gated this behind opt-in/debug flags; those were removed per review.)Changes
_forward_cuda_k_only): skip logits/top-k, store K cache; for MLA generate the identity index; extended to DECODE (eager + graph)max_kv_lenvsindex_topk; auto-enabled for DSA models viadsa_index_topkScope
GLM-5.2 DSA decode on gfx950 (MI355X). Auto-enabled for DSA models; correct for mixed lengths (long context stays on the sparse indexer path). Other archs / hardware unaffected.
Test plan
Accuracy (GSM8K, MI355X TP4, GLM-5.2-MXFP4):
Within margin of error.
Performance (MI355X TP4, GLM-5.2-MXFP4, docker
rocm/sgl-dev:v0.5.15.post1-rocm720-mi35x-20260714, tilelang DSA backend): token throughput per GPU (tok/s/gpu, higher better) and median TPOT (ms, lower better), dense-decode OFF vs ON (this PR). Isolated effect — same build/backend, only this PR's commits added, everything else identical.Only i1024 / o1024 is shown: this optimization applies when
kv_len <= index_topk(2048). At i8192 every decode step haskv_len > 2048, so it stays on the sparse path and is unchanged.Token throughput per GPU improves ~2.4–5.2% and TPOT drops ~2.3–5.1% at i1k, from skipping the wasted indexer when the sparse top-k would select all positions anyway. The gain is largest at low concurrency and converges to ~2.4% at conc 64. (Δ is the isolated dense-decode effect — same build/backend, feature off vs on — not a full-stack-vs-stock comparison.)
CI States
Latest PR Test (Base): ⏳ Run #31978978932
Latest PR Test (Extra): ❌ Run #31978978765