Skip to content

[DSV4] Fix silent KV corruption when speculative draft tokens > 4 - #33872

Closed
Deleter-D wants to merge 1 commit into
sgl-project:mainfrom
Deleter-D:fix_dsv4_compress_hard_code
Closed

Deleter-D wants to merge 1 commit into
sgl-project:mainfrom
Deleter-D:fix_dsv4_compress_hard_code

Conversation

@Deleter-D

@Deleter-D Deleter-D commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

On a DSV4 speculative verify batch, the compress write-plan (plan_w from plan_compress_prefill) is built from the optimistic seq_len = prefix_len + num_draft_tokens, but after verification the sequence tail rolls back to prefix_len + accept_len. Every token that ends up committed must therefore still be resident in the compress-state ring, whatever the accept length turns out to be — otherwise a later compression window reads a stale ring slot.

c_plan.cuh hard-coded that write pad at kMaxMTPDraftTokens = 4:

constexpr int32_t kMaxMTPDraftTokens = 4;
const auto mtp_pad = std::min(ring_size - compress_ratio, kMaxMTPDraftTokens);

So with speculative_num_draft_tokens > 4 the plan under-writes the ring: the tokens between seq_len - 4 and seq_len - num_draft_tokens never get persisted. This fails silently — no illegal memory access, no NaN, no assertion. The compressed state is simply computed from stale slots, which shows up only as a quiet accuracy regression. The host path was additionally missing the pad entirely (it used first_w_pos = last_c_pos - ...with no min against seq_len - pad).

Modifications

Kernel (python/sglang/kernels/jit/csrc/deepseek_v4/c_plan.cuh)

  • Replaced the mtp_pad constant with a real num_draft_tokens parameter on plan_compress_prefill and on Prefill0Params. The per-request pad is now min(extend_len, num_draft_tokens), and first_w_pos = min(last_c_pos - (is_overlap ? cr : 0), seq_len - pad). Clamping by extend_len keeps a captured cuda graph valid when the real per-step draft count is below the bound it was captured with.
  • Applied the same rule on all three planner paths that were out of sync: the GPU plan_compress_prefill_kernel0 (both its branches) and the C++ host loop.
  • Added two RuntimeChecks so an unserviceable configuration fails loudly instead of silently corrupting: num_draft_tokens >= 0, and the ring-capacity bound num_draft_tokens <= ring_size - window_size + 2 (a compression at p reads [p - window_size + 1, p]; ring slots alias every ring_size positions, so a write at w clobbers w - ring_size). The message points at get_compress_state_ring_size(compress_ratio, is_speculative=True), which is the usual root cause.

Plumbing (num_draft_tokens threaded from backend down to the planner)

  • CompressorPrefillPlan.generate and create_paged_compressor_data take num_draft_tokens: int = 0 and forward it.
  • DeepseekV4AttnBackend gains self.compress_verify_write_pad = self.speculative_num_draft_tokens or 0 (an always-int view of a field that is
    None when not speculating) and passes it on the verify / cuda-graph-replay metadata paths. DeepseekV4HipRadixBackend gets the same wiring.
  • Default of 0 means plain prefill and all non-speculative paths keep their exact previous write set.

Tests

  • New test/registered/kernels/ops/attention/test_deepseek_v4_compress_plan_draft_pad.py (base-b-kernel-unit / 1-gpu-large, ~60s). Details below.
  • python/sglang/test/kits/attention_unittest/attention_methods/dsv4_attention.py: the mock runner previously always set speculative_algorithm=None, so PoolConfigurator.is_speculative was False and speculative cases allocated the non-speculative ring sizes (8 / 128) — the mock could not represent the configuration where this bug lives. It now derives "EAGLE" from speculative_num_draft_tokens. swa_page_size also changed from DSV4_SWA_WINDOW (128) to case.page_size (256), because the planner requires swa_page_size % ring_size == 0 and the speculative c128 ring is 256.

Accuracy Tests

The bug is a silent-corruption class, so the guard is at the plan level rather than an end-to-end score. New kernel test, 7 cases, all passing:

  • test_c4_ring_residency / test_c128_ring_residency — for every num_draft_tokens in {1..5, max_d-1, max_d} crossed with every residue of seq_len % compress_ratio, assert plan_w covers all of [prefix_len, seq_len). This is the sufficient condition: if each step writes its whole extend range, then by induction the next compression window is resident whatever the accept length. Reverting the min(..., seq_len - pad) clamp turns these red for D > 4.
  • test_c4_window_covered_over_decode_chain / test_c128_window_covered_over_decode_chain — replay a verify chain at the worst accept length (a = 1) across 2·cr+4 steps, accumulate what each step writes, and at every compression point assert the full window_size it reads is already resident. Catches errors the per-step invariant would miss.
  • test_cpu_and_gpu_planner_agree — the invariants above run on the host-loop plan; this pins plan_compress_prefill_kernel0's plan to it, so the fix has to hold on both paths (the pre-fix code diverged between them).
  • test_plain_prefill_unaffected — num_draft_tokens=0 reproduces the exact non-speculative write set (including the swa-page-boundary clause for c4), i.e. no regression for non-speculative serving.
  • test_over_capacity_raises — ring_size - window_size + 3 draft tokens must raise, not silently truncate.

Existing DSV4 suites are unaffected: test_c4_v2.py / test_c128_v2.py only do fp64 numeric parity with a plan as input, and no existing test anywhere used num_draft_tokens != 0, which is exactly how the bug escaped.

Speed Tests and Profiling

No performance impact expected or measured. The change swaps a compile-time constant for a kernel parameter inside the planner's index arithmetic; no extra memory traffic, no new kernel launches, no change to the compress kernels themselves. On a speculative verify batch the plan writes more rows than before (that is the fix), bounded by num_draft_tokens per request.

Checklist

  • Format your code according to the Format code with
    pre-commit
    .
  • Add unit tests according to the Run and add unit
    tests
    .
  • Update documentation according to Write documentations.
    — no user-facing behavior or flag change; rationale is documented in the c_plan.cuh doc comment and the test module docstring.
  • Provide accuracy and speed benchmark results according to Test the accuracy and [Benchmark the speed (https://docs.sglang.io/developer_guide/contribution_guide.html#benchmark-the-speed).
  • Follow the SGLang code style guidance.

CI States

Latest PR Test (Base): ❌ Run #31103363292
Latest PR Test (Extra): ❌ Run #31103362936

@Deleter-D

Deleter-D commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

This change may resolve the #33800. However, due to the ring size limitation, draft_tokens may still need to be limited to 10 or fewer.

@Deleter-D

Copy link
Copy Markdown
Contributor Author

@merrymercy @Fridge003 Hi, could you please help trigger the CI? Thank you!

Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 8, 2026
…project#32035 sgl-project#33656 sgl-project#32183 sgl-project#33145)

Applied PRs (latest from GitHub):
  sgl-project#33288  Indexer logits OOM fix
  sgl-project#30393  HiCache packed/sidecar draft caches
  sgl-project#31170  DPA prefix_affinity load balancing
  sgl-project#33795  DSpark compact ragged-verify CUDA graph JIT race
  sgl-project#32467  C128 plan-kernel warp barrier
  sgl-project#33865  DSpark x prefill CP unblock
  sgl-project#30371  SWA state pool sizing (storage page)
  sgl-project#33358  FlashMLA norm-rope K-tokens-per-block ILP
  sgl-project#33872  num_draft_tokens clamp + extend_len==0 skip (supersede sgl-project#32183)
  sgl-project#34002  Sidecar backup vacuously-successful fix (replaces sgl-project#33656, with tests)
  sgl-project#33862  Reclaim redundant host mirrors after storage backup
  sgl-project#31315  Avoid repeated Mooncake gets after stale hits
  sgl-project#32327  Q8KV8 sparse MLA prefill backend (flashmla_sparse_q8)
  sgl-project#31668  Fix sidecar pool life-time (use-after-free on prefetch abort)
  sgl-project#31195  TP0 verify-token-budget broadcast (adapted to get_schedule() API)

Dropped (per user request or superseded):
  sgl-project#32771  IndexCache C4 top-k reuse — has bug
  sgl-project#32035  DSpark C128 online compressor — has bug
  sgl-project#33656  Superseded by sgl-project#34002 (same fix + unit tests)
  sgl-project#32183  Superseded by sgl-project#33872 (included in supersede PR)
  sgl-project#33145  Base f01f706 already has superior reasoning-effort profile system

Conflicts resolved:
  sgl-project#31195: adapted to base get_schedule().disable_overlap_schedule API
  sgl-project#32327: path remapped jit_kernel/ -> kernels/jit/ and kernels/ops/attention/
  sgl-project#31668: applied cleanly on top of sgl-project#30393+sgl-project#34002+sgl-project#33862 modifications
@apejcic

apejcic commented Aug 8, 2026

Copy link
Copy Markdown

Independent confirmation of this mechanism on B300 (sm_103a) — hardware
you noted you couldn't test. DeepSeek-V4-Flash-0731 + DSPARK, tp=1,
fp8_e4m3 KV, opaque-id echo replay (n=200, conc=12, cold boot per arm).
Baseline corruption scales monotonically with num_draft_tokens - 4,
exactly as the under-persistence model predicts: ndt=4 → 0%, ndt=6 →
41.5%/43.0% (two boots), ndt=7 → 56.5%, ndt=8 → 75.0%; no-spec → 0%.

With your patch applied (applies clean on current main): ndt=6 → 0/200 on
two independent cold boots plus 0/600 on a third, ndt=7 → 0/200, ndt=8 →
0/200 — the ladder flattens to no-spec parity (0/1400 patched requests
total). The new RuntimeCheck never fired (ndt 6/8 ≤ c4 bound 10,
silent pass as designed). JIT side note: the content-hash cache rebuilt
c_plan.cuh automatically on first patched boot (new build dir
...compress_plan_f15ff9b00d5175ba__arch_10.3a__tvmffi_0.1.11, old one
retained), and the new .so carries the new check string — clean
rebuild/reload story for JIT sources.

For the record: this also confirms #34021 is a distinct defect. It cannot
fire in this configuration (TileLang mHC path is on, and tp=1 has no
symmetric pool) and leaves the corruption above untouched; your planner
fix is the one that resolves it here.

Happy to contribute the full repro protocol (offline replay script +
server flags). Strong +1 for merge; glad to help with review iterations.

Comment on lines 108 to 120
SGL_DEVICE uint32_t warp_inclusive_sum(uint32_t lane_id, uint32_t val) {
static_assert(device::kWarpThreads == 32);
#pragma unroll
for (uint32_t offset = 1; offset < 32; offset *= 2) {
#ifndef USE_ROCM
uint32_t n = __shfl_up_sync(device::kFullMask, val, offset);
#else
uint32_t n = __shfl_up(val, offset, 32);
#endif
if (lane_id >= offset) val += n;
}
return val;
}

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.

maybe reuse warp::inclusive_sum


const int32_t last_c_pos = (sl / cr) * cr;
const int32_t first_w_pos = min(last_c_pos - (is_overlap ? cr : 0), sl - params.mtp_pad);
const int32_t pad = min(static_cast<int32_t>(E), params.num_draft_tokens);

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.

Why do we need this min here?

ShangmingCai added a commit that referenced this pull request Aug 9, 2026
…raft tokens > 4

Cherry-pick of upstream #33872 (open, head aece477).
Threads runtime num_draft_tokens through the DSV4 compress write-plan
instead of the hardcoded kMaxMTPDraftTokens=4, so the compression ring
buffer persists enough KV state when speculative draft tokens exceed 4.
c_plan.cuh is JIT-compiled at runtime, so this needs no kernel rebuild.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@hnyls2002 hnyls2002 closed this Aug 9, 2026
Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 10, 2026
…l-project#32035 ref sgl-project#33872)

Ports the extend_len==0 idle/padded-request guard from the dsv4-merge sgl-project#33872 enhanced port (95d4b84) onto the upstream sgl-project#33872 fix, preventing RuntimeCheck(0<extend_len) regression in compact ragged verify.
ShangmingCai added a commit that referenced this pull request Aug 10, 2026
…raft tokens > 4

Cherry-pick of upstream #34189 (merged, squash 4a5d7d3).
Replaces the earlier open-PR #33872 attempt: instead of threading
num_draft_tokens through the backend/compressor, the compress write-pad
is reframed as a property of the ring (ring_size - window_size + 2) in
c_plan.cuh, with startup validation (_assert_ring_serves_draft_tokens in
pool_configurator.py) that rejects over-configured draft counts.
c_plan.cuh is JIT-compiled at runtime, so this needs no kernel rebuild.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants