Repository navigation
[unified memory] Support DSPARK speculative decoding + fix two NaN root causes (page hand-out zeroing, CuTe int32 slot-stride wrap) - #33974
Conversation
Port of the kimi-k3 fork's stage-5 dspark-x-unified enablement (fork
e60b491f4 + 8734883f6) onto main:
- server_args: relax the unified-memory spec gate to chain DSPARK
(topk in {None, 1}); everything else stays blocked.
- trtllm_mla: extend the capture-stable DENSE write-loc fill from
is_decode_or_idle to target_verify, and route the forward_extend
KV write through it (loc_is_dense) when set.
- mamba scatter kernels: replace the blanket dst.is_contiguous()
asserts with the kernels' true contract (arbitrary layer/slot
strides, contiguous trailing entry dims) so the unified pool's
envelope-strided views pass; kernels already index through real
int64-promoted strides.
- update_mamba_state_after_mtp_verify: translate the ScheduleBatch-side
(virtual) mamba_track_indices to physical at a single point
(identity on static pools).
- draft pool: size by the shared unified allocator's virtual-id space
(size_full, page-aligned up), not max_total_num_tokens - the draft
is direct-indexed by virtual ids; keep the draft pool on the plain
contiguous layout (page-major is a target-pool choice).
- lazy compaction: forced OFF under speculative decoding - DSPARK
rewrites batch.out_cache_loc in the verify executor after
set_inflight_forward registered the write-set, so the in-flight WAR
protection would not cover verify-window writes.
Co-Authored-By: Claude Fable 5 <[email protected]>
…(deterministic repro switch) Port of fork 2a897e571. Fills the unified pool with bf16-NaN bit patterns at boot instead of zeros. Any consumer that arithmetically touches never-written bytes (masked page tails, padded lanes) then fails deterministically on every boot instead of depending on what the freed GPU heap happened to contain. Debug-only, env-gated. Co-Authored-By: Claude Fable 5 <[email protected]>
…asked-tail reads) Port of fork 35ae95561. The trtllm-gen MLA attention kernel reads the whole page and masks the rows beyond seq_len ARITHMETICALLY - NaN (and exp-overflow-huge) bit patterns in the never-written tail rows of a request's last partial page leak straight into the attention output. The unified pool zeroes its raw buffer only at boot; page recycling during the run re-exposes historical bytes, making corruption a boot-level lottery. Speculative decoding amplifies exposure: every verify window lands on a fresh page at the sequence tail. Fix: every page leaves the allocator zeroed (fresh or recycled), on the schedule stream, ordered before the consuming forward by the run_batch wait_stream fence. MLA-dense pools only (kernel_page_multiplier > 1). The SGLANG_DEBUG_POISON_POOL harness is the acceptance switch: a poison boot must now score identically to a clean boot. Co-Authored-By: Claude Fable 5 <[email protected]>
…ltiplies
The DSPARK KDA verify kernel (nv_cutedsl fast path) compiles with STATIC
tensor layouts: every state-pool stride is a compile-time constant. Each
per-slot stride individually fits int32 - the unified memory pool's
envelope-strided KDA views carry slot strides of ~14M (fp32 ssm) / ~28M
(bf16 conv) elements - so the constant folds into 32-bit arithmetic and
slot * stride silently wraps mod 2^32 once slot ids exceed ~153 (conv) /
~306 (ssm). Wrapped reads land inside other slots' bytes: silent state
corruption on a clean boot (K3 GSM8K 0.120, fake accept-rate bursts with
a random draft), all-NaN under SGLANG_DEBUG_POISON_POOL, or an illegal
access when the wrap flies off the allocation.
Static contiguous pools never reach the wrap point (slot stride ~197K
elements), which is why this only fired under --enable-unified-memory,
and only under load (fresh boots hand out low slot ids). Kimi-Linear
never engages this kernel (KDA head dims != 128 fail the contract), which
is why K3 alone showed it.
Sentinel (offline replay of a dumped in-system call, bs=24): before -
slots<=75 bit-exact, 100-150 illegal access, >=155 silent divergence on
every output and intermediate; after - bit-exact for every slot range in
{3-26, 100-150, 155-200, 330-360, 400-470} x {zero, NaN} pool-gap fills.
Co-Authored-By: Claude Fable 5 <[email protected]>
…the verify window Reverts the eager-compaction forcing from the DSPARK enablement commit, which was based on a misread of the registration order. Verified on the actual code path: - scheduler.py calls allocator.set_inflight_forward(forward_done, batch.out_cache_loc) AFTER model_worker.forward_batch_generation() returns; - the DSPARK verify executor rebinds ScheduleBatch.out_cache_loc to the verify-window locs inside that call (dspark_verify.py, both compact and non-compact paths) and never restores it (only seq_lens_cpu/seq_lens_sum have backup-restore); - so _flush's _materialize_inflight_write_set() translates exactly the verify-window virtual locs and the write-race classification covers spec verify writes the same way it covers decode writes. The event-gated freed-page reuse (_drain_pending_reuse) also orders the alloc-time page zeroing after the in-flight forward, so the two fixes compose under lazy mode as designed. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d05fa7d1c2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if isinstance( | ||
| token_to_kv_pool_allocator, UnifiedMambaTokenToKVPoolAllocator | ||
| ): |
There was a problem hiding this comment.
Size unified-SWA draft pools for virtual IDs
When DSPARK is used with a unified hybrid-SWA target, the shared allocator is a UnifiedSWATokenToKVPoolAllocator, so this check is skipped and the draft KV pool remains sized to max_total_num_tokens. The SWA allocator's full side nevertheless issues virtual IDs from its larger full_attn_allocator.max_slots space; after sufficient allocation/free churn, those IDs exceed the direct-indexed draft pool and cause out-of-bounds KV writes. Either handle the unified-SWA allocator here too or reject DSPARK for unified-SWA models.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch — real. No unified-SWA target is validated with a spec draft, so rather than wiring sizing for a lane with zero coverage, 9cc89e6ac0 makes it fail loudly: a DSPARK draft against a UnifiedSWATokenToKVPoolAllocator now raises at pool construction instead of silently sizing the draft pool to max_total_num_tokens.
| self._zero_pages_on_alloc = kernel_page_multiplier > 1 and hasattr( | ||
| kvcache, "zero_physical_pages" | ||
| ) |
There was a problem hiding this comment.
Zero unified MLA pages when the shard owns one layer
When a pipeline/tensor shard owns exactly one full-attention MLA layer, full_kernel_page_multiplier is 1 even though the pool is still UnifiedMLATokenToKVPool and remains vulnerable to the same NaN-unsafe partial-page reads. This predicate therefore disables hand-out zeroing for that configuration, allowing poisoned fresh pages or stale recycled tails to corrupt attention outputs. Detect the unified MLA pool via zero_physical_pages rather than requiring the multiplier to exceed 1.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed — the kernel_page_multiplier > 1 predicate misses the one-full-attn-layer shard (the same edge unified_mem_hooks documents for its own detection). 9cc89e6ac0 keys the enable purely on the pool type (hasattr(kvcache, "zero_physical_pages"), defined only by UnifiedMLATokenToKVPool). No behavior change on the validated lanes (K3 multiplier=24, Kimi-Linear=7).
…able Two P1s from the automated review, both real: - kv_cache_configurator: a DSPARK draft against a unified hybrid-SWA target (UnifiedSWATokenToKVPoolAllocator) skipped the virtual-space sizing silently - the SWA composite's full side issues virtual ids from the whole virtual space too, so the draft pool would write out of bounds at high ids. No unified-SWA target is validated with spec; fail loudly instead of sizing wrong. - multi_ended_allocator: keying hand-out zeroing on kernel_page_multiplier > 1 disables it for a shard owning exactly ONE full-attention MLA layer (multiplier 1, pool still UnifiedMLA and still NaN-unsafe on partial-page tails - the same edge unified_mem_hooks documents). Key on the pool type instead (hasattr zero_physical_pages). No behavior change on the validated lanes (K3 multiplier=24, Kimi-Linear=7). Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9cc89e6ac0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| @@ -258,7 +259,20 @@ def __init__( | |||
| self._raw = torch.empty( | |||
| total_bytes + view_tail_pad_bytes, dtype=torch.uint8, device=device | |||
| ) | |||
There was a problem hiding this comment.
[suggestion] SGLANG_DEBUG_POISON_POOL is read via os.environ.get(...) instead of an EnvBool on sglang.srt.environ.Envs. Project env-var conventions require all new sglang-owned SGLANG_* knobs to be registered and accessed through envs.SGLANG_....get() so overrides/tests work and the catalog stays complete. This also forces an ad-hoc import os solely for that read.
Suggestion: Add SGLANG_DEBUG_POISON_POOL = EnvBool(False) under the existing DEBUG section in environ.py, then gate the poison path with envs.SGLANG_DEBUG_POISON_POOL.get(). Drop the local import os if nothing else needs it.
There was a problem hiding this comment.
Done in 0f594845ac: SGLANG_DEBUG_POISON_POOL = EnvBool(False) registered in environ.py (DEBUG section), read via envs.SGLANG_DEBUG_POISON_POOL.get(), ad-hoc import os dropped.
| # kernel_page_multiplier > 1: a shard owning exactly one full-attention | ||
| # MLA layer has multiplier 1 yet reads the same NaN-unsafe partial | ||
| # pages (same edge unified_mem_hooks documents for its detection). | ||
| self._zero_pages_on_alloc = hasattr(kvcache, "zero_physical_pages") |
There was a problem hiding this comment.
[suggestion] _zero_pages_on_alloc = hasattr(kvcache, "zero_physical_pages") is defensive duck-typing on an optional method. Project rules discourage hasattr/getattr for this pattern (it hides missing APIs and weakens type checking). The set of kvcache types that define the hook is known (UnifiedMLATokenToKVPool only today).
Suggestion: Prefer an explicit type check (isinstance(kvcache, UnifiedMLATokenToKVPool)) or a tiny optional protocol / base no-op zero_physical_pages on the pool types MultiEndedAllocator actually receives, then call it unconditionally (or gate on a bool set from the concrete type at construction).
There was a problem hiding this comment.
Done in 0f594845ac: isinstance(kvcache, UnifiedMLATokenToKVPool) (the import direction multi_ended_allocator → unified_memory_pool already exists).
| return conv_views, temporal | ||
|
|
||
|
|
||
| class TestScatterDstLayoutContract(unittest.TestCase): |
There was a problem hiding this comment.
[suggestion] The new tests correctly guard the envelope-strided scatter layout contract (a real DSPARK+unified regression path). They do not pin either claimed NaN root cause: (a) page hand-out zeroing of partial-page tails under an arithmetically masked MLA read, or (b) CuTe int32 slot * stride wrap once slot ids exceed the documented thresholds. Under the unit-test admission rules, those fixes are exactly the kind of "bug regression / derived property" cases that benefit from a small deterministic guard (the poison-pool path is already half of the harness).
Suggestion: Add focused unit tests, e.g. (1) allocate physical pages into a poison-filled UnifiedMLA envelope and assert tail rows read as 0 after hand-out; (2) a pure-math or host-side check that the KDA indexing path multiplies slot·stride in int64 for a stride in the ~14M–28M range at slot ids past the wrap point (or a kernel smoke if CuTe tests already exist). Even one of the two would materially reduce silent-reg risk.
There was a problem hiding this comment.
Added in 0f594845ac, both verified to bite:
test_unified_handout_zeroing(CUDA): fresh + recycled page hand-out over a NaN-poisoned pool must read zero, while untouched pages must stay poisoned (keeps the assert non-vacuous); plus a regression pin that zeroing stays enabled for akernel_page_multiplier == 1single-layer shard.test_kda_decode_mtp_slot_stride(SM100 + cutlass, self-skipping): envelope-strided ssm+conv replicas with a non-pow2 slot stride crossing 2^31 elements at slot 8 must match a contiguous pool bitwise. Verified to FAIL (illegal access) on the pre-fix kernel and pass on the fixed one. Two construction subtleties are documented in the test: a pow2 stride lowers to shifts and dodges the 32-bit imul entirely, and the wrap bites through the conv direct-index path — strided ssm alone passes even pre-fix.
… root-cause unit tests
- server_args: under unified+DSPARK, restrict BOTH attention roles to
spec-verify-audited backends {triton, trtllm_mla, cutedsl_mla,
tokenspeed_mla}. flashinfer's speculative branches consume
spec_info.kv_indices / generate_attn_arg_prefill() raw (VIRTUAL ids,
no translate_kv_loc_dense - see FlashInferMLAIndicesUpdater{Decode,
Prefill}), and fa3 has no verify dense-loc fill; verify routes to
either role depending on --speculative-attention-mode, so both roles
are gated. (P1: untranslated flashinfer MLA spec path.)
- environ: SGLANG_DEBUG_POISON_POOL registered as EnvBool per the env
conventions; unified_memory_pool reads envs.*.get() and drops the
ad-hoc os import.
- multi_ended_allocator: zeroing enable keyed on
isinstance(kvcache, UnifiedMLATokenToKVPool) instead of hasattr
duck-typing (import direction already exists).
- tests pinning both NaN root causes:
- test_unified_handout_zeroing (CUDA): fresh + recycled page hand-out
over a poisoned pool must read zero; untouched pages stay poisoned
(non-vacuous); regression pin for the multiplier==1 single-layer
shard.
- test_kda_decode_mtp_slot_stride (SM100 + cutlass, self-skipping):
envelope-strided ssm+conv replicas with a NON-pow2 slot stride
crossing 2^31 elements at slot 8 must match a contiguous pool
bitwise. Verified to FAIL (illegal access) on the pre-fix kernel
and pass on the fixed one. Two construction pitfalls documented:
pow2 strides lower to shifts and dodge the 32-bit imul; the wrap
bites through the conv direct-index path, so strided ssm alone
passes even pre-fix.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
/tag-and-rerun-ci |
Drop review-oriented commentary (change justifications, validation numbers, finding provenance) from the code comments added in this PR; keep only the constraints the next reader needs (layout contracts, virtual/dense id semantics, the int64 stride-fold hazard, stream ordering). Co-Authored-By: Claude Fable 5 <[email protected]>
873472a to
2f0ed6a
Compare
zero_physical_pages used a uint8 advanced-index fill (env[pages.to(long)] = 0), which routes through TensorIterator element-wise indexing: ~376 GB/s plateau and ~178 us of host submit time per call. Replace with a Triton kernel over the int64-viewed pool (the MLA page envelope is always 8-byte aligned), grid = (pages, word blocks). GB300 kernel-level comparison, K3 geometry (1.69 MiB envelopes, 12808-page pool), median of 30: | pages | u8-index fill | int64-view fill | index_fill_ | triton | |---|---|---|---|---| | 1 | 79 us (22 GB/s) | 54 us (33) | 22 us (81) | 19 us (94) | | 32 | 209 us (271) | 62 us (911) | 119 us (476)| 19 us (2925) | | 256 | 1251 us (362) | 192 us (2357) | 851 us (532)| 73 us (6198) | | 1024 | 4823 us (376) | 641 us (2828) | 3357 us (540)| 256 us (7093)| Host submit @32 pages: 178 us -> 9.4 us. The scattered Triton kernel also beats torch's CONTIGUOUS memset path at equal bytes (4.0 TB/s plateau) and sits at ~89% of HBM peak, so a dedicated CUDA kernel has no meaningful headroom left. BLOCK 1024/2048/8192 indistinguishable. Co-Authored-By: Claude Fable 5 <[email protected]>
…ot causes (page hand-out zeroing, CuTe int32 slot-stride wrap) (sgl-project#33974)
…ot causes (page hand-out zeroing, CuTe int32 slot-stride wrap) (sgl-project#33974)
…ot causes (page hand-out zeroing, CuTe int32 slot-stride wrap) (sgl-project#33974)
trtllm_mha's fmha_v2 prefill (SM90/SM120) loads K and V a whole page at a time and masks the positions past a request's length only in the scores: the P.V product still multiplies their V rows by a zero probability, and 0 * NaN is NaN. XQA decode does the same with an fp8 KV cache on SM90; its bf16 kernel zero-fills those rows instead. The pool must therefore hand out pages whose unwritten rows read as finite values, which a static pool's zero-initialized buffer guarantees. The unified pool handed MHA pages out as they were, and under a mamba hybrid those bytes may last have held the mamba sub-pool's fp32 recurrent state, of which roughly 1 in 256 halves read as a bf16 Inf/NaN. MLA pools already zero on hand-out for the same reason (#33974); MHA pools did not. Seen as Qwen3.5-9B on trtllm_mha at --mem-fraction-static 0.30: unified GSM8K 0.487 / 0.495 against 0.900 / 0.895 (graphs off / on), with about 42% of requests generating to max_tokens. At 0.8 the two sub-pools never reuse each other's bytes, and the scores match. UnifiedMHATokenToKVPool gains zero_physical_pages over the byte-0 envelope view its move_kv_cache uses; the allocator zeroes MHA pages as it does MLA ones, including the tri-pool's float middle (FloatMultiEndedAllocator overrides the hand-out step, so it calls the zeroing itself); zero_pages gains the pure-torch CPU path copy_pages already has, since CPU code now reaches it through MHA pools. Tests: test_unified_handout_zeroing.py runs its fresh/recycled and pool-type cases on an MHA + mamba pool (TestUnifiedMHAHandoutZeroing), and the sliding-window side of a mamba + SWA tri-pool (TestTriPoolSWAHandoutZeroing). With the CUDA skip lifted on CPU, all three fail before this change (every handed-out element is NaN) and pass after. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> (cherry picked from commit 4e5f47f)
Motivation
--enable-unified-memorycurrently hard-blocks speculative decoding (server_args.py:assert self.speculative_algorithm is None). This PR wires chain DSPARK through the unified pool and fixes the two real NaN/corruption root causes found while validating it end to end on Kimi-K3 (TP8, 2x4 GB300) and Kimi-Linear-48B (TP1 x8 B300-class). Other speculative algorithms (EAGLE / tree / DFLASH / NGRAM) remain blocked pending their own virtual-vs-dense loc audits.Modifications
Five commits, reviewable independently:
unified-memory: wire DSPARK chain speculative decodingserver_args.py: relax the unified gate tospeculative_algorithm in (None, "DSPARK"), chain only (speculative_eagle_topk in (None, 1)).trtllm_mla_backend.py: extend the capture-stable DENSE write-loc fill fromis_decode_or_idle()tois_target_verify(), and route theforward_extendKV write through it (loc_is_dense=True) when set — the verify graph must not capture a translate allocation (same class as the decode path that already exists).mamba_state_scatter_triton.py: replace the blanketdst.is_contiguous()asserts with the kernels' true contract (arbitrary layer/slot strides — already consumed via real int64-promoted strides — with contiguous trailing entry dims), so the unified pool's envelope-strided conv/temporal views pass. CPU layout-contract tests + a CUDA envelope-dst end-to-end test added.hybrid_linear_attn_backend.py:update_mamba_state_after_mtp_verifytranslates the ScheduleBatch-side (VIRTUAL)mamba_track_indicesto physical at a single point (identity on static pools) — using them raw silently mis-addresses within bounds on the unified pool.kv_cache_configurator.py: size the DSPARK draft pool by the shared unified allocator's virtual-id space (size_full, page-aligned up) instead ofmax_total_num_tokens— the draft pool is direct-indexed by virtual ids which range over the whole virtual space; keep the draft pool on the plain contiguous layout (page-major is a target-pool layout choice).debug(unified): SGLANG_DEBUG_POISON_POOL— env-gated: fill the pool with bf16-NaN bit patterns at boot instead of zeros. Turns the "does freed GPU heap happen to contain NaN patterns" boot lottery into a deterministic switch; kept as the permanent regression harness for the class of bug below (zero default overhead).fix(unified): zero page envelopes on allocator hand-out— root cause 1. The trtllm-gen MLA kernel reads whole pages and masks rows beyondseq_lenarithmetically (NaN-unsafe); the unified pool zeroes its raw buffer only at boot, so page recycling re-exposes historical bytes and NaN in a request's last partial page tail leaks into the attention output. Speculative decoding amplifies exposure (every verify window lands on a fresh page at the sequence tail). Static pools are safe by construction (torch.zeros+ only finite KV ever written); this gives the shared pool the same guarantee at the alloc boundary. Cost: one contiguous page-envelope memset per handed-out page on the schedule stream — benched at zero (below).fix(kda_decode_mtp): promote slot ids to int64 before state-stride multiplies— root cause 2, and the reason this presented as a "weird" load-dependent heisenbug. The DSPARK KDA verify kernel (nv_cutedslfast path) compiles with STATIC CuTe layouts: state-pool strides are compile-time constants. On the unified pool the envelope-strided KDA state views carry slot strides of ~14M (fp32 ssm) / ~28M (bf16 conv) elements; each constant individually fits int32, so it folds into 32-bit arithmetic andslot * stridesilently wraps mod 2^32 once slot ids exceed ~153 (conv) / ~306 (ssm) — reads land inside other slots' bytes (silent state corruption on a CLEAN boot: GSM8K 0.120, fake accept-rate bursts) or fly off the allocation (illegal access). Static contiguous pools never reach the wrap point (slot stride ~197K elements); Kimi-Linear never engages this kernel (head dims fail the 128 contract → triton fallback); cold boots hand out low slot ids — which is exactly why it was unified-only, K3-only, and load-only. Proven with an offline replay sentinel (dump one real in-system call; rebuild states contiguous vs faithful strided replicas with zero/NaN gap fill; sweep slot magnitudes): before — slots ≤75 bit-exact, 100–150 illegal access, ≥155 silent divergence; after — bit-exact everywhere.unified+spec: keep lazy compaction ON— reverts an over-conservative eager forcing from an earlier draft of commit 1 after verifying the actual ordering: the scheduler registers the in-flight write-set (set_inflight_forward(forward_done, batch.out_cache_loc)) AFTERforward_batch_generation()returns, and the DSPARK verify executor has by then reboundScheduleBatch.out_cache_locto the verify-window locs (never restored) — so lazy compaction's write-race classification covers verify writes exactly like decode writes, and the event-gated freed-page reuse orders the hand-out zeroing (commit 3) after the in-flight forward.Accuracy
GSM8K 200q (
sglang.test.few_shot_gsm8k), Kimi-K3 TP8 2-node GB300, marlin MoE, trtllm_mla, verify graph captured:--disable-radix-cache, 500q, lazy-compaction stats onPoison acceptance criterion: a poisoned boot must score identically to a clean boot — it does (0.985/0.990 both). Kimi-Linear-48B TP1: unified+DSPARK poisoned 0.910 = clean 0.905 = static twin 0.910.
Performance (fix cost = zero)
sglang.benchmark.one_batch_server, isl 8192 / osl 1024, bs sweep, 2 reps per arm, K3 TP8:Limitations / follow-ups
moves=0in the stats run); its correctness rests on the verified write-set ordering (commit 5) plus poison acceptance. A fragmenting long-generation stress is a good follow-up before enabling this in latency-critical production lanes.🤖 Generated with Claude Code
CI States
Latest PR Test (Base): ❌ Run #31373943471
Latest PR Test (Extra): ❌ Run #31373943208