Repository navigation
[MTP] Cut spec-v2 host-seam overhead in hybrid-linear MTP decode - #32219
Merged
Merged
Conversation
yuan-luo
requested review from
BBuf,
DarkSharpness,
Fridge003,
HaiShaw,
HydraQYH,
Qiaolin-Yu,
Ying1123,
celve,
hanming-lu,
hebiao064,
hnyls2002,
ispobock,
merrymercy and
yizhang2077
as code owners
July 23, 2026 13:50
Contributor
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
yuan-luo
force-pushed
the
mtp_decode_perf_opt
branch
from
July 23, 2026 14:01
80e424d to
f231f4e
Compare
JustinTong0323
left a comment
Collaborator
There was a problem hiding this comment.
Found one correctness issue in the plan-stream hybrid-linear verification path.
Collaborator
|
/rerun-failed-ci |
BBuf
approved these changes
Jul 28, 2026
BBuf
reviewed
Jul 28, 2026
added 3 commits
July 28, 2026 11:19
KDAAttnBackend never declared needs_cpu_seq_lens and inherited the base-class True, forcing FutureMap.resolve_seq_lens_cpu onto the blocking path: a per-step fwd_prepare_d2h_stream.synchronize() that stalls the scheduler ~0.5 ms (median 485 us over 30 traced steps, B200 bs=1 MTP) waiting for the previous verify to finish on GPU and publish new_seq_lens, zeroing the spec-v2 host run-ahead. KDA metadata never reads the spec-v2 seq_lens_cpu mirror: replay padding comes from forward_batch.num_padding, and the replayssm track-flush mask paths are gated `not is_kda`. GDNAttnBackend and Mamba2AttnBackend already run the same base-class metadata code with needs_cpu_seq_lens = False; this brings KDA into the same GPU-only contract. With the full-attn siblings (trtllm_mla / fa3 / flashmla / triton) all False, the OR over spec-v2 backends now stays False for KDA hybrids (e.g. Kimi-Linear MTP) and the per-step stream sync disappears entirely.
The hybrid wrapper never overrode the get/update_verify_buffers_to_fill_after_draft hooks, so every hybrid-linear MTP model (GDN / KDA) hit the base [None, None]: the draft stage could not write the tree mask / positions straight into the full-attn child's captured verify buffers and instead allocated a fresh custom_mask every step -- sized bs * max_context_len once the GPU-only seq_lens path (needs_cpu_seq_lens=False) nulls seq_lens_sum. - get: delegate to the full-attn child (the linear side consumes no mask); the draft stage now writes into the captured verify buffers and the per-step mask allocation disappears. - update: forward to both children. MambaAttnBackendBase gets an explicit no-op (mamba plan-time metadata -- state slot indices, per-bs static query_start_loc -- is draft-output independent); children without an implementation keep the fail-loud NotImplementedError, so an unvetted plan-stream combination fails loudly instead of silently reading stale buffers. The update site only fires under SGLANG_ENABLE_OVERLAP_PLAN_STREAM (default off).
eagle_prepare_for_verify extends every row by exactly draft_token_num tokens, yet went through the generic assign_extend_cache_locs kernel: the host eagerly materialized `seq_lens + draft_token_num` (a fresh tensor + one dispatch per step on the bs=1 MTP inter-phase seam) and the kernel re-derived per-row output offsets with O(bs) cross-row prefix-sum loads. Add assign_extend_cache_locs_uniform: the end offset is computed in the kernel (start + draft_token_num) and the output offset is a direct pid * draft_token_num. NPU / CPU fall back to the end_offset-tensor reference path, unchanged. The non-uniform call site (move_accept_tokens: seq_lens + num_correct_drafts + 1) keeps the reference kernel.
added 3 commits
July 28, 2026 11:19
_replay_metadata refreshed state_indices_list through a chain of dispatched aten ops on the bs=1 MTP host critical path: zero padded req_pool_indices rows, mamba mapping gather, v2p translate, -1 padding sentinel, copy_ into the static buffer (5 dispatches on the static pool, more on the unified pool). _fused_state_indices_kernel does the gather + sentinel + store in a single triton launch, preserving the reference chain's side effect of zeroing padded req_pool_indices rows (captured kernels gather with them; dropping the zeroing would be a delayed illegal memory access). Gated to CUDA + the static hybrid pool whose v2p translate is the identity, and to replayssm off; the unified pool's allocator translate is not a flat table gather, so those configs keep the reference chain.
Drives the fused single-launch replay-prep path and the reference aten chain on guard-padded buffers across a bs x num_padding matrix (non-power-of-two sizes exercise the BS_UPPER masking) and asserts bit-identical results: state indices incl. the -1 padding sentinels, the req_pool_indices zeroing side effect (captured kernels gather with that buffer; a missed zeroing is a delayed illegal memory access, not a visible diff), and untouched guard tails past total_bs. Also covers non-injective mappings (requests sharing a mamba slot).
yuan-luo
force-pushed
the
mtp_decode_perf_opt
branch
from
July 28, 2026 03:19
536a444 to
ee7b6e2
Compare
yuan-luo
force-pushed
the
mtp_decode_perf_opt
branch
from
July 28, 2026 03:31
ee7b6e2 to
b908e69
Compare
saturn-acc
pushed a commit
to saturn-acc/sglang
that referenced
this pull request
Aug 16, 2026
…-project#32219) Co-authored-by: luoyuan.luo <[email protected]>
Atituiset
pushed a commit
to Atituiset/sglang
that referenced
this pull request
Sep 10, 2026
…-project#32219) Co-authored-by: luoyuan.luo <[email protected]>
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 24, 2026
…es for mamba graph replay Upstream d9cf7b0 (v0.5.20), only the part that reaches the 27B. MambaAttnBackendBase._replay_metadata refreshes the captured state_indices_list before every decode / target-verify graph replay; on the 27B's D group that is the DFLASH verify graph every step. The reference chain (index-put of padded req rows, mapping gather, identity translate, -1 fill, copy) is 4 launches of host overhead in the bs=1 seam; the fused Triton kernel does it in one, bit-identically, including the padded-row zeroing of the static req_pool_indices buffer. Ported: srt/layers/attention/mamba/mamba_state_indices_triton.py (fork path next to mamba_state_scatter_triton, not kernels/ops/mamba) and the fast path in _replay_metadata. Adapted: eligibility is asked per replay (_fused_state_indices_ok) instead of cached at init, so a pool rebinding cannot leave a stale answer, and it also requires get_mamba_indices to be the base flat gather (the kernel reads req_index_to_mamba_index_mapping directly). Unified pool (non-identity v2p translate), ReplaySSM (its cursor refresh reads the gathered ids) and non-CUDA devices keep the reference chain. Not ported (not applicable to DFLASH on this line): - update_verify_buffers_to_fill_after_draft: tree verify (topk > 1) only; - KDA needs_cpu_seq_lens: no KDA model here; - eagle_utils assign_extend_cache_locs_uniform_func: EAGLE prepare_for_verify; DFLASH computes its verify cache locs in its own Triton prepare_block. Tests (CPU, incg cgroup): test/registered/unit/layers/attention/test_fused_replay_state_indices_32219.py - the production kernel under TRITON_INTERPRET vs the reference chain over a bs x num_padding matrix (8 sizes incl. non-powers of two, 2 seeds): state indices, returned view, req_pool_indices side effect, guard tails -- all bit-identical; - eligibility: static hybrid pool on CUDA -> fast path; unified translate, overridden gather, ReplaySSM, CPU device, foreign pool -> reference chain. 3 passed. Mutant (padded-row zeroing removed): bit-identity test red. Metal: test/registered/attention/unittests/gdn/test_triton.py (cuda-graph decode + verify cases) needs a GPU.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 26, 2026
…-prefill-graph(-split/-tiny/-max-prefix), --p-deep-split-from Picks der 27B-Linie in Reihenfolge (alle Schalter Default aus, P-Env/argv ohne Flag byte-gleich): upstream-Ports bac77bc (sgl-project#37657) eb6d7d6 (sgl-project#34184) dc9fbf9 (sgl-project#32219 Teil) als Voraussetzung des Prefill-Graphen; 5fd4e77 5d8612b 02e218f d24a17d 6b24aa6 3e093fe (P-Host-Overlap, #PGAP, P-NOSYNC); d32ddcb fb7ea2b 37ea1db 3e6ce57 (P-Prefill-Graph); 735db6a (+ 4e03821 als reine Verschiebung durch die Auflösung erledigt) f49f2fd 51e39d4 dc128e3 18639ea. Konfliktauflösungen: - scheduler_pp_mixin: NF H49 PP-HOST-PERIOD und 27B P-HOST-OVERLAP komponiert (die im Inventar genannte Doppel-Instrumentierung): H49 note_launch/note_no_batch/note_sync bleiben, der d2h-Wait steht zusätzlich im #PGAP-Span, deferred publish + Lead-Bound nach dem Launch wie 27B. Beide Instrumente getrennt schaltbar (H49-Env / --p-host-overlap). - unified_radix_cache: Chunk-Publish unter H2-sync_trace UND #PGAP-Span. - launcher common_flags: p_chunked_prefill_tokens() = Graph-Bucket oder P_CHUNKED_PREFILL_TOKENS (NF-Env, Default = Konstante; 27B byte-gleich). - argv_p: NF p_micro_batch_flags + 27B p_prefill_graph_flags() vor extra/H25-Strip. - solve_p_cut: prefill_graph_pool_mib neben NF sgl-project#114 activation_reserve. - --d-replayssm-spec der 27B-Hunks nicht doppelt registriert (NF-Form bleibt). Tests (test27b.sh): 20 portierte Testdateien 204 passed, 2 skipped; test_weg2_vision_prefill_graph_seam_0924 nicht gelaufen (Boot aktiv, incg-Schlange), nachzufahren. dup_defs_gate: 0 neu.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
With MTP (NEXTN) speculative decoding under spec-v2 overlap scheduling, each decode step consists of three CUDA graphs:
Between the graphs live eager "seams": accept sampling, cache-slot assignment, attention-metadata rebuild, next-step draft input preparation. At low concurrency (bs=1 to small batches) these seams, host-side Python dispatch and per-step synchronization the GPU cannot overlap, become GPU idle time.
Host run-ahead, and what pins it
sglang's
event_loop_overlapis designed so that while the GPU executes step N, the host is already assembling and enqueuing step N+1; the host stays off the critical path iff host loop time < GPU step time. TheFutureMapkeeps cross-step data (next tokens, new_seq_lens, draft seeds) GPU-resident, relayed by pool index between graphs, so the host can launch the next step without ever seeing accept results, launch-queue depth grows to ~1 full step of run-ahead:Several per-step host costs, however, still pin the host to the GPU's progress and shrink that run-ahead back toward lockstep:
KDAAttnBackendnever declaredneeds_cpu_seq_lens, inheriting the base-classTrue, which forcesFutureMap.resolve_seq_lens_cpuonto the blocking path (fwd_prepare_d2h_stream.synchronize()every step). In bs=1 MTP traces of a KDA-hybrid model this stall measured ~0.5 ms/step median — the host waits for the previous verify to finish on GPU, zeroing run-ahead. GDN / Mamba2 / ShortConv siblings already declareFalseand run the same base-class metadata code.HybridLinearAttnBackendnever forwardedget/update_verify_buffers_to_fill_after_draft, so every hybrid-linear MTP model takes the[None, None]fallback: the draft stage cannot write the tree mask / positions straight into the full-attn child's captured verify buffers and instead allocates a freshcustom_maskeach step — sizedbs * max_context_lenonce the GPU-only seq_lens path nullsseq_lens_sum.eagle_prepare_for_verifyextends every row by exactlydraft_token_numtokens, yet materializedseq_lens + draft_token_numon the host (a fresh tensor + a dispatch per step) for the generic cache-locs kernel, which then re-derived per-row output offsets with O(bs) cross-row prefix-sum loads._replay_metadatarefreshedstate_indices_listvia separate aten ops (zero paddedreq_pool_indicesrows → mapping gather → v2p translate →-1padding sentinel →copy_into the static buffer) on every mamba-backend CUDA-graph replay.The host seam is a serial chain — single-point savings do not add up: remove A and the CPU immediately hits B. What ultimately hides the host is the combination plus the overlap scheduling itself, not any single item. The latency payoff therefore lands as a bundle; each fix is nonetheless independently correct and independently revertible.
Effects
Before PR, GPU bubbles between draft_extend/draft/target_verify are significant:

After PR, GPU bubbles between these tree APIs are almost gone:

Whole picture before PR, no overlap, CUDA graph launch is sync:

After PR, the verify CUDA graph launch can be overlapped in the next draft_extend:

Provenance
These items were developed and measured in a bs=1 MTP decode optimization campaign on a KDA-hybrid MoE model (4× B200, TP4, NEXTN speculative decoding), whose end state reached ~90% GPU busy per step with the host fully hidden behind the GPU — the per-item trace measurements quoted in this PR (the ~0.5 ms/step D2H stall) come from that campaign. This PR upstreams the model-agnostic host-seam subset; every item passed the campaign's correctness gate (byte-exact 256-token greedy output + accept length invariance) before it stayed.
Modifications
One commit per item, bit-identical by construction (scheduling / fusion only — no numerical path changes):
Opt KDA backend out of the per-step seq_lens_cpu D2H sync—KDAAttnBackenddeclaresneeds_cpu_seq_lens = False, matching GDN/Mamba2/ShortConv. Safety: the sharedMambaAttnBackendBasemetadata never reads the spec-v2 CPU mirror for KDA — replay padding always comes fromforward_batch.num_padding, and the replayssm track-flush mask reads arenot is_kda-gated. With the full-attn siblings (trtllm_mla / fa3 / flashmla / triton) alreadyFalse, the OR over spec-v2 backends can now stayFalsefor KDA hybrids and the per-step stream sync disappears.Forward verify-buffer hooks through HybridLinearAttnBackend—getdelegates to the full-attn child (the linear side consumes no mask); the draft stage now writes directly into the captured verify buffers and the per-step mask allocation disappears.updateforwards to both children with an explicit no-op onMambaAttnBackendBase(mamba plan-time metadata is draft-output independent); children without an implementation keep the fail-loudNotImplementedError, so an unvetted plan-stream combination fails loudly instead of silently reading stale buffers.Fuse the uniform verify-prep cache-locs end offsets into the kernel— newassign_extend_cache_locs_uniform: end offset computed in-kernel (start + draft_token_num), output offset a directpid * draft_token_num. NPU / CPU fall back to the end_offset-tensor reference path unchanged; the non-uniform call site (move_accept_tokens) keeps the reference kernel.Fuse the mamba replay-prep state-indices chain into one launch—_fused_state_indices_kerneldoes the gather + sentinel + store in a single triton launch, preserving the reference chain's side effect of zeroing paddedreq_pool_indicesrows (captured kernels gather with that buffer). Gated to CUDA + the static hybrid pool whose v2p translate is the identity + replayssm off; unified-pool / replayssm configs keep the reference chain.Add bit-exact reference test for _fused_state_indices_kernel— see Accuracy Tests.Compatibility: no API / flag changes; NPU, CPU, unified-memory pool, and replayssm behavior unchanged (explicit gates / fallbacks); plan-stream fail-loud contract preserved.
Accuracy Tests
test/registered/attention/unittests/hybrid_linear/test_fused_state_indices_kernel.py: fused kernel vs the reference aten chain on guard-padded buffers, bs ∈ {1, 2, 7, 32, 33} × num_padding sweep × 3 seeds + a non-injective-mapping case — asserts bit-identical state indices (incl.-1sentinels), thereq_pool_indiceszeroing side effect, and untouched guard tails (out-of-range write protection forBS_UPPER > bs). Result on H20-3e: 2 tests, 45 subtests, all pass (8.8s).b98a577f), H20-3e, tp=4 (greedy, 8 fixed prompts, 256 tokens each,ignore_eos):Qwen3.5-35B-A3B+ NEXTN MTP (--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4) — a GDN-hybrid spec-v2 config exercising items 2-4: output text byte-identical; per-promptspec_verify_ctidentical (113/91/71/83/84/83/85/80) — acceptance behavior unchanged.Kimi-Linear-48B-A3B-Instructplain CUDA-graph decode — a KDA config exercising item 4's fused replay path: output byte-identical.Speed Tests and Profiling
These changes remove host-side work whose payoff is latency at low concurrency and compounds with sibling optimizations (serial chain):
decide_needs_cpu_seq_lens) for all other configs.bs * max_context_lenbool-mask allocation for every hybrid-linear MTP model.Byte-identical outputs above double as the no-regression evidence. A bundle-level TPOT A/B on Blackwell for the KDA-hybrid MTP target is part of the follow-up series and will be reported there.
This is one part of hybrid-linear model optimazations, with which GPU utils increase from 67% to 95% in MTP.
Checklist
CI States
Latest PR Test (Base): 🚫 Run #30326134766
Latest PR Test (Extra): ✅ Run #30889987619