Skip to content

[Fix] attention: correct NVFP4 speculative workspace mapping - #43356

Open
LingZ315 wants to merge 5 commits into
sgl-project:mainfrom
LingZ315:lz/fix-nvfp4-spec-graph-safe-refresh
Open

LingZ315 wants to merge 5 commits into
sgl-project:mainfrom
LingZ315:lz/fix-nvfp4-spec-graph-safe-refresh

Conversation

@LingZ315

@LingZ315 LingZ315 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

SM120 speculative verification and draft extension need an NVFP4-to-FP8 workspace with the correct physical KV slots and sequence lengths. Reusing prompt-prefill metadata during speculative replay can select the wrong cached rows. Applying global scales again after workspace dequantization also changes attention outputs.

Modifications

  • Write cached prefixes and current K/V into their physical workspace slots, using GPU-resident speculative lengths and write locations. Ordinary prefill uses the same physical mapping.
  • Apply global K/V scales once and account for each pool's full workspace and private draft buffers, including implicit MTP drafts.
  • Require --disable-cuda-graph-padding for SM120 Qwen3_5ForConditionalGeneration + NEXTN + NVFP4 decode graphs. Exact captured batch sizes use graphs; uncaptured sizes retain eager fallback.
  • Use eight CTAs per SM for speculative workspace dequantization on SM120 rows containing 512 elements. Kernel arithmetic, four warps per CTA and other launch geometries remain unchanged.

Packed payload/scale transport is in the separate HiCache companion PR.

Current-main refresh (2026-11-22)

Merged main 4916e5a56ab0e2c90d9065cd6116091a79f28f55 into the existing branch; refreshed head: 1e06d0262d98302a0911f8d36a37b550168c1e8f. This preserves the previous PR history.

Adapted the speculative path to IterationIds and window write locations, updated dtype resolution to quant_config, and reconciled private-draft workspace sizing with main's DCP accounting. Added DCP regression coverage and updated fixtures to the current layer-router APIs.

Fresh validation on two RTX 5090 GPUs, TP2, Qwen3.8-27B ModelOpt NVFP4 with integrated MTP, NEXTN 5/1/6, FlashInfer 0.7.4, sglang-kernel 0.4.11:

  • CPU: 476 tests and 317 subtests passed. One MuseSpark full-pipeline test was deselected after its two failing Blackwell subtests reproduced on unchanged main in this SM120 environment (TRTLLM FMHAv2 prefill ... does not support fp8_e4m3 KV cache).
  • GPU kernel/Graph tests: 6 passed. Repository-pinned pre-commit passed on all 11 changed files.
  • Fixed-batch Graph/eager comparison: 42/42 request pairs have identical output token IDs, covering C1/C4/C8/C13/C16, 384 input tokens and 128 generated tokens, with the same startup seed. C13 is not captured and exercises eager fallback.
  • Asynchronous stress: each arm completed 74/74 requests, all with 128 output tokens, including mixed lengths, C13/C16, 27K/50K/141K C1 and 27K shared-prefix C4/C8/C16. Logs explicitly show 16 simultaneous decode requests with CUDA Graph enabled.

Both arms used a 196608-token pool, chunk 8192, page 64, Mamba state pool 96, no HiCache or FR-Spec, and custom all-reduce disabled. Mamba pool 64 capped actual concurrency at 12 with this five-slot-per-request setup; the C16 validation uses 96. Decode Graph capture sizes are 1/2/4/8/16 with padding disabled.

This refresh does not implement native packed-FP4 verify: speculative verification still dequantizes cached prefixes into the workspace. The eight-CTA optimization remains restricted to 512-element rows; this model's TP1 geometry has 1024-element rows and retains the previous launch geometry. No fresh speedup claim is made for RTX PRO 6000 TP1.

Historical Accuracy Tests

Based on a99c7d050fae, tested with Qwen3.8-27B ModelOpt NVFP4 weights on two RTX 5090 GPUs (SM120), TP2:

  • Standalone core, 11 files, HiCache OFF: 413 CPU tests and 207 subtests; 88 Graph/eager request pairs with exact output and speculative-metadata agreement. Cases include mixed lengths/order, shared-prefix replay, C13/C16, four approximately 50K inputs and one 131,072-token input.
  • Combined core + HiCache: 72 attention checks; 6 GPU kernel/Graph checks and 5 host-plan checks; 8 L2 Graph/eager request pairs.
  • Combined finite quality set: NVFP4 19/24, FP8 19/24, zero new errors. Both fail the same five items: T8192K5, T8192K7, T25000K5, T25000K7, T32000K5. Each performance point's ten measured batches also has stable output IDs within each path.

CPU rerun:

python -m pytest -q \
  test/registered/unit/layers/attention/test_flashinfer_nvfp4_speculative.py \
  test/registered/unit/layers/attention/test_flashinfer_nvfp4_workspace.py \
  test/registered/unit/model_executor/test_pool_configurator.py \
  test/registered/unit/server_args/test_server_args.py

Kernel reproducer: python -m pytest -q test/registered/kernels/ops/quantization/test_nvfp4_kv_cache.py.

These results do not establish native packed-FP4 attention, SM100, RTX PRO 6000 TP1, 141K decode performance, or the complete reasoning/tool/vision/needle quality suite.

Historical Speed Tests and Profiling

The following measures the combined core + HiCache candidate, with HiCache ON. A=NVFP4 KV + FP8 workspace; B=FP8 KV. Both use the same NVFP4 weights, trtllm_mha decode backend (FP8 uses XQA), page 64, TP2, NEXTN 3/1/4, fixed pool 196608, chunk 8192, Mamba 96 and decode Graph sizes 1–16 with padding disabled. Runtime: FlashInfer 0.7.2, sglang-kernel 0.4.10, PyTorch 2.14.1+cu130.

Complete A1/B1/B2/A2: one warmup plus five measured batches per point per launch, 128 output tokens per request. Throughputs below are pooled medians of ten measured batches per path; ratios are the geometric mean of the two launch-pair ratios, calculated separately.

Input / prefix / concurrency Request-window tokens/s A / B Paired A/B Decode tokens/s A / B Paired decode A/B
25K / shared / C1 187.43 / 177.85 1.0573 266.89 / 243.21 1.0994
25K / shared / C4 603.91 / 598.74 1.0110 863.96 / 818.96 1.0592
25K / shared / C16 1004.99 / 1140.58 0.8809 1744.24 / 2041.18 0.8516
50K / shared / C4 398.19 / 444.95 0.9012 706.38 / 809.45 0.8723
25K / unique / C4 574.15 / 650.26 0.8832 805.77 / 923.64 0.8741

Request time runs from HTTP open to receipt of [DONE], including TTFT, transport, stream parsing and in-loop raw writes; flush/seed, memory checkpoints and post-stream validation are excluded. Decode throughput excludes each request's first SSE event and is client-observed, not pure GPU time. Both launch pairs agree in direction at every point. Request throughput is 5.7%/1.1% higher at shared 25K C1/C4 and 9.9–11.9% lower at the other points. TTFT p90 is also higher for A at shared 25K C4 (608 vs 236 ms) and shared 50K C4 (1051 vs 588 ms). Two pairs do not establish statistical significance or isolate a kernel's contribution.

At the fixed pool size, ready-state known KV/scales/workspace storage per rank is 2.169 vs 3.189 GiB (31.99% lower); total PyTorch allocated memory is 19.985 vs 21.031 GiB (4.97% lower), and reserved memory is 20.512 vs 21.559 GiB. These quantities were identical across both ranks and both launches of each path; they are not whole-device memory or per-request peaks.

Automatic token-pool capacity, separately measured at memory fraction 0.9 with the same Graph/Mamba settings, is 782,592 vs 565,568 tokens (+38.37%). Each path completed one 25K request. This does not establish full-pool stability or a larger single-request context limit.

Checklist

The repository-pinned pre-commit stage passed on all 11 changed files in a disposable checkout of this exact core patch; the hooks left source unchanged.


CI States

Latest PR Test (Base): ⊘ Skipped -- add the run-ci label to run CI tests.
Latest PR Test (Extra): ⊘ Skipped -- add the run-ci label to run CI tests.
Latest PR Test (AMD ROCm 10): ⊘ Skipped -- add the run-ci label to run CI tests.

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@AppNetDeveloper

Copy link
Copy Markdown

@LingZ315 thanks for the quick refresh! As promised, results from our setup. Short version: it works on SM120 RTX PRO 6000 in real production traffic (served our live traffic for ~1 h, 0 errors, 0 tracebacks), quality unchanged, big decode win at long context.

Setup: 1× RTX PRO 6000 Blackwell Workstation (SM120, 96 GB), TP1, RadixArk/Qwen3.8-27B-NVFP4 (modelopt mixed) with integrated MTP (EAGLE 3/1/4), this PR at 9f285aa, torch 2.14.1+cu130, FlashInfer 0.7.0.post1, sglang-kernel 0.4.9. Flags: --kv-cache-dtype nvfp4 --prefill-kv-cache-dequant-dtype fp8_e4m3 --attention-backend flashinfer (decode auto-switched to trtllm_mha, page_size forced to 64) --enable-linear-replayssm-spec --disable-prefill-cuda-graph --chunked-prefill-size 16384 --prefill-decode-interval 1 --max-mamba-cache-size 250 --max-running-requests 50 --mem-fraction-static 0.90, no HiCache (per #36121).
Baseline = our production: v0.5.21, --kv-cache-dtype fp8_e4m3 + HiCache ratio 3, same model/MTP/flags.

Correctness (our agent harness, temperature 0.6): tool calls 12/12 (medium) + 12/12 (xhigh), vision 4/4 (skewed invoice OCR, UI screenshot, chart), needle-in-~32k-tokens 4/4. CUDA graphs on, MTP accept length 2.97 vs 3.02 baseline.

KV capacity: 990,208 tokens vs 715,591 with FP8 (+38%) at the same mem fraction; 1,075,760 with --page-size 16 --mem-fraction-static 0.92.

Long-context decode (~84k-token unique prompt, 400 output tokens, measured while serving live traffic):

v0.5.21 FP8 KV + HiCache this PR, NVFP4 KV
1 request: TTFT / decode 14.4 s / 64.2 tok/s 13.6 s / 102.4 tok/s (+60%)
4 concurrent: TTFT / decode 35.2 s / 25.8 tok/s 34.8 s / 22.5 tok/s

Live traffic, warm cache (our agent workload, 25–60k-token contexts):

  • Chunked-prefill throughput +17% (6,349 vs 5,449 tok/s per 16k chunk), probably main vs 0.5.21 rather than this PR.
  • Per-request decode at mid-length contexts (25–30k) ~10% lower than baseline (121 vs 134 tok/s at 1–2 running, 97 vs 111 at 3–5); end-to-end median at our gateway +7% (110 vs 103 tok/s).
  • Prefix-cache hit rate 80% vs 86%: we lose HiCache ([Bugfix] Fail fast when hierarchical cache is enabled with FP4 KV cache dtype #36121) and page_size 64 (forced by trtllm_mha) coarsens prefix reuse.

Notes:

  1. First requests after start trigger JIT compilation (ptxas/Triton) that blocks the scheduler: /health failed for ~2 min and our gateway marked the backend down. A warm-up at startup (or compiling during graph capture) would avoid that.
  2. The decode win grows with context length, the mid-context regression is small; together with [Bugfix] Fail fast when hierarchical cache is enabled with FP4 KV cache dtype #36121 (HiCache scale buffers) this would be a clear upgrade for us.

Thanks again, happy to re-test follow-ups.

@AppNetDeveloper

Copy link
Copy Markdown

Follow-up with HiCache back on: #43356 + #43240 (HiCache FP4 host-pool fix, validated in #43240 (comment)), same SM120 setup, --hicache-ratio 3, page_size 64, mem 0.90. Served production for ~40 min, 0 errors, MTP accept 2.88, quality checks unchanged — so the PR itself is solid on SM120.

Throughput, live agent traffic with warm cache (most contexts 25–35k tokens), vs our v0.5.21 FP8 KV + FlashInfer + HiCache baseline at similar load:

baseline #43356 + #43240
per-request decode, 1–2 running ~134 tok/s 106 tok/s
per-request decode, 3–5 running ~111 tok/s 82 tok/s
prefix-cache hit 86% 77%
end-to-end median at our gateway 103–118 tok/s 86 tok/s

So on SM120 the NVFP4 path wins clearly only at long context (+60% decode at ~84k, earlier comment) and loses ~20–25% at mid-length contexts. Our guess is the mandatory trtllm_mha (XQA) decode for NVFP4 on SM120 plus page_size 64 (lower prefix reuse), not your workspace kernel. We're back on FP8 KV for now and will re-test when the SM120 NVFP4 decode path or page-size constraint changes. Thanks again!

@chengye75-star

Copy link
Copy Markdown

@AppNetDeveloper your data is exactly why we shipped #43471 last night — same SM120 platform, same Qwen3.8-27B-NVFP4 + MTP stack. It may change the tradeoff you backed away from.

To be precise about what it does not touch: your mid-length decode regression (~134→106 tok/s at 1–2 running) is on the trtllm_mha/XQA decode path + page-64 reuse, and #43471 doesn't move decode kernels — your conclusion holds there. What #43471 removes is the FP8 dequant workspace from the prefill path entirely: NVFP4 prefill now goes through FlashInfer's native packed-FP4 paged prefill (run(..., kv_cache_sf=...), kernel-side tile dequant), so the per-chunk gather→bf16→fp8 re-dequant of the whole cached prefix is gone — along with its two structural taxes:

  • Transient memory: on our 2× RTX 5060 Ti 16 GB (TP2) rig, a ~45K-token cold prefix OOM-killed the scheduler in production via dequantize_prev_kv temporaries under the workspace route. With [Refactor] Native NVFP4 prefill via FlashInfer kv_cache_sf: retire the FP8 dequant workspace (O(n^2) + OOM fix; tvm-ffi fake-Segfault note) #43471, back-to-back cold 45K/100K/150K prefill rounds run with GPU memory flat to the MiB across all rounds (no per-layer spikes at all).
  • Fixed + per-token pool cost: dq_k/dq_v were allocated per pool-row (~146 MiB/rank) and charged 1024 B/token into compute_cell_size. Both vanish → cell size 10816→9792 B/token, i.e. +10.5% same-budget pool capacity, and boot headroom rose 0.88→2.6 GB/rank at our 180K config, which let us raise both pool and mamba-slot budget.

Reference numbers (same rig, native-FP4 prefill, greedy, cold disjoint prefixes — full A/B vs the workspace route running as I type; these are the absolute values):

metric 2×5060 Ti 16GB TP2 (chunk 2048)
45K cold prefill TTFT 12.4 s
100K cold 35.5 s
150K cold in-flight (180K pool, usage ~0.83)
decode (NEXTN 2/1/3 MTP) 70–90 tok/s single-stream, accept 2.1–3.0, HiCache kernel+#43240 battery green

Notes for a trial on your rig:

If the decode side is what keeps you on FP8 KV, one data point worth having on your radar: on SM120 the decode loss looks like an XQA/page-size property of the NVFP4 route, not of the KV format's arithmetic — if FP8-KV decode at page 64 ≈ page 16 on your harness, the mid-length story may be fixable independently of this.

@AppNetDeveloper

Copy link
Copy Markdown

@chengye75-star @LingZ315 thanks for the pointer to #43471. We tried it on the same SM120 setup. Short version: native NVFP4 prefill + MTP verify is correct but crashes under CUDA graphs at bs=16, and on SM120 there is currently no graph-safe native verify path.

Tree: #43356 @ 9f285aa + #43240 (HiCache FP4 host pool) + #43471 @ 4eae8ca cherry-picked. There was one conflict in FlashInferAttnBackend.forward_extend. We put the prefill_uses_native_fp4 branch first and kept #43356's speculative/regular dequant-workspace branches as the elif. That means that, with native prefill on, target verify and draft extend also read the packed pool through run(..., kv_cache_sf=...).
Setup: 1× RTX PRO 6000 (SM120), TP1, Qwen3.8-27B NVFP4 (ThinkingCap A4 checkpoint, hybrid GDN), EAGLE 3/1/4, speculative_attention_mode=prefill (default on SM120), --kv-cache-dtype nvfp4 --prefill-kv-cache-dequant-dtype fp8_e4m3, HiCache ratio 3, page 64, mem 0.90, SGLANG_NVFP4_NATIVE_PREFILL=1.

What works

  • KV pool 1,187,136 tokens vs 709,511 with FP8 KV at the same mem fraction (+67%). With [Fix] attention: correct NVFP4 speculative workspace mapping #43356 alone we had ~990k, so the freed workspace shows up as expected.
  • Without decode CUDA graphs (--cuda-graph-backend-decode disabled): no errors, and our harness all passes (reasoning 16/16, tool calls 24/24, vision 4/4, needle 4/4). MTP accept len matches FP8 KV: 3.15 vs 3.16 at 1–4 running, 2.49 vs 2.52 at 10–19. So the numerics of the native verify path look right.

What breaks (decode CUDA graphs on)
Fine at low concurrency (accept 3.15 at 1–4 running). On a 16-concurrent decode burst, the scheduler died after ~6 s:

eagle_worker_v2.verify -> run_eagle_verify -> eagle_prepare_for_verify
-> decode_cuda_graph_runner.load_batch -> hybrid_attn_backend.init_forward_metadata_out_graph
-> flashinfer_backend.init_forward_metadata_out_graph -> indices_updater_prefill.update
-> wrapper_paged.begin_forward/plan -> _compute_page_mask_indptr: mask_indptr[0] = 0
torch.AcceleratorError: CUDA error: an illegal memory access was encountered

The error is async, so the faulting kernel is probably the previous graph replay of target verify through the native kv_cache_sf route, not plan() itself. Our guess: something the native route reads at replay isn't graph-stable for the bs=16 graph. Candidates are the wrapper attributes injected by _set_paged_forward_attrs at capture time, or plan buffers sized for the dequant-workspace route. Same tree, same traffic, graphs off → clean.

--speculative-attention-mode decode (verify on trtllm_mha) does not start on SM120

Capture cuda graph failed: shape '[1187200, 4, 256]' is invalid for input of size 607846400

The trtllm verify path views the packed FP4 pool (head_dim // 2) as unpacked. As kv_cache_hook says, native trtllm verify is SM100-only today.

Why this matters on SM120: the only graph-safe verify path today is #43356's speculative dequant workspace. It re-dequantizes every running request's whole cached prefix into FP8 on every verify step. We suspect that is behind the −20–25% mid-context (25–35k) decode we reported earlier. A graph-safe native verify (#43471's route) would likely remove it and keep the +67% capacity.

FP8 KV baseline on the same box for reference (unique prefixes, 400 output tokens, per-request decode): ~27k: 124.5 tok/s c1 / 57.8 c4 / 37.2 c8 · ~50k: 105.0 c1 / 24.1 c8 · ~141k: 83.5 c1 / 22.3 c4. Happy to run a fix on this rig and report the same table for NVFP4.

chengye75-star added a commit to chengye75-star/sglang that referenced this pull request Oct 15, 2026
…ack to the workspace path

CUDA-graph replay of the native kv_cache_sf path is only proven stable for
plain prompt-prefill. Target-verify / draft-extend now fall back to the
dequant workspace route (graph-safe via sgl-project#43356) unless the operator opts
in via SGLANG_NVFP4_NATIVE_SPEC=1 (small capture lists only).
Also plans speculative prefill wrappers with float8_e4m3fn when downgraded.
@chengye75-star

Copy link
Copy Markdown

@AppNetDeveloper your bs=16 crash report was exactly the evidence we needed — thank you. Confirmed: the gap is in our PR, not in your merge. #43471's native branch as written covers forward_extend unconditionally, so with your (correct) conflict resolution your speculative forwards went native — and graph-stability of the native kv_cache_sf path had only ever been exercised at bs≤2 (our rig captures [1,2] only). Your async-error reading and both suspects are spot on.

Fix pushed to the PR branch (feat/nvfp4-native-prefill, commit 00f2216):

  • The native FP4 route is now guarded to plain prompt-prefill only. Target verify / draft extend (v2) are downgraded to the dequant-workspace branch — i.e. on your tree, [Fix] attention: correct NVFP4 speculative workspace mapping #43356's graph-safe speculative workspace path takes over exactly as before the cherry-pick.
  • Plan dtype follows the downgrade: when a speculative wrapper is planned with spec_info present while native prefill is on, kv_data_type is passed as float8_e4m3fn instead of the packed uint8 — a static dtype here was very plausibly the IMA you saw (fp8 workspace tensors planned as packed bytes, or vice versa, at capture vs replay).
  • Pool accounting is untouched, so the +67% capacity (no per-row workspace, 9792 B/token) stays regardless of the guard.
  • An operator opt-in SGLANG_NVFP4_NATIVE_SPEC=1 exists for rigs whose decode-graph capture list is provably small (ours: [1,2], where native verify runs at accept 2.9–3.0 with the full HiCache battery green). Default is off; on the bare PR base the fallback branch needs [Fix] attention: correct NVFP4 speculative workspace mapping #43356's speculative workspace — we say that plainly in the docstring rather than pretend bare-main spec is supported.

What we ask you to re-test on the PRO 6000 (we can't reach bs=16 on 16 GB×2 — your rig is the only bs=16 evidence that matters):

  1. [Fix] attention: correct NVFP4 speculative workspace mapping #43356 @ 9f285aa + fix(hicache): square NVFP4 host-pool geometry + page-granular block-scale transport #43240 + refreshed [Refactor] Native NVFP4 prefill via FlashInfer kv_cache_sf: retire the FP8 dequant workspace (O(n^2) + OOM fix; tvm-ffi fake-Segfault note) #43471 (take the branch head, re-resolve the one forward_extend conflict — the guard is inside the native branch condition, your native-first ordering should now drop spec onto your [Fix] attention: correct NVFP4 speculative workspace mapping #43356 elif automatically), decode CUDA graphs enabled, burst at the same 16-concurrency that killed the scheduler in ~6 s.
  2. Same quality set (reasoning/tool/vision/needle) and accept at 1–4 and 10–19 running, to confirm the downgrade is numerically free (workspace route was your passing baseline in the first report).
  3. If it comes back clean, the same decode table you posted for FP8 KV (27k/50k/141k, c1/c4/c8) — that turns the guard into a full tradeoff picture for the maintainers: native cold-prefill + OOM fix + pool gain, spec verify on the graph-safe workspace until a graph-stable native verify lands.

On that last point we agree with your framing: a genuinely graph-safe native verify (stable plan buffers across replays at captured shapes) is the real prize, and your plan()-vs-replay analysis in the crash note is the right starting map. We're working it; when we have a candidate we would very much like your harness on it.

Reference, same-PR guard build on our SM120 TP2 rig just now: decode 90.4 (counting) / 76.9 (short) / 70.5 (creative), cold prefill 45K/100K at 12.2/34.9 s, memory flat — bit-for-bit the same as ungarded native, as expected for a guard that only moves speculative forwards.

Refresh against a99c7d0, preserve physical slots and global scales,
account for independent draft workspaces, reject unsafe graph padding,
and bound SM120 speculative DQ launch workers to eight CTAs per SM.

Core source validated independently with HiCache disabled.
@LingZ315 LingZ315 changed the title fix: make FlashInfer NVFP4 speculative decoding graph-safe [Fix] attention: correct NVFP4 speculative workspace mapping Oct 25, 2026
@LingZ315

Copy link
Copy Markdown
Contributor Author

@merrymercy could you please run /tag-and-rerun-ci extra for the current head (c4ca4dff3cb8) to enable Base + Extra CI?

This branch now includes upstream main 5ef99013ac3e. The workspace fix and the existing static-grid launch configuration are retained. Local CPU validation passed: 413 tests + 207 subtests for this PR, and 443 tests + 207 subtests combined with #46452. The repository-pinned pre-commit checks also passed.

The earlier GPU/model and benchmark results in the PR descriptions apply to the documented a99c7d0-based validation snapshot; they have not been rerun on these new heads. If GitHub requires approval for fork workflows, could you approve those as well?

detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…mily + S-EXT1 + riders + S-RACE + LLGUARD/ENVREG), S-EXT1 and S-RACE items CLOSED, entry-256's raw-env deviation and LL-vs-PCIe-IPC collision warning both marked CLOSED with the BOOT_DELTA (h') needle in landing terms, sgl-project#35617 left as the sole FAM-A7 survivor, sgl-project#44732 re-pointed to the operator's merge-sgl-project#5 answer, and the KV-ROUTE DECISION RECORD added (HOLD NVFP4-KV until armed PCIe-IPC is measured post-merge; preferred-if-ever sequence merge -> sgl-project#43356-delta -> sgl-project#46452 NOT sgl-project#43240 -> optional sgl-project#43471 -> fork BUILD-A QSA FP4 reads (template sgl-project#38724) -> BUILD-B L3 scale sidecar -> one GPU window; sgl-project#46141 template, sgl-project#44462 NEXT, MXFP4 declined, entry-247 re-sync watch-string modelopt_e4m3_k32)
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
…m re-plant, flashinfer_backend 175/208/233 re-plants + spec-workspace pool pair, trtllm_mha fail-loud, qsa folds, dsv4 wrapper redirect -- entries 54,57,64,102,120,166,175,176,178,192,194,200,203,208,210,213,233,241,125,118,184

gdn_backend.py (54/120/203): THE FULL fork delta RE-PLANTED onto the
  post-merge structure (the merge took upstream's file and the saved hunks
  were the loss): extend-side circular replayssm fold (metadata wiring +
  once-per-forward fold before _prefill_gates), the lossless-verify (u,k,g)
  tuple plumbing through target_verify (buffer kwargs + recurrent-fallback
  _lossless arm + the EAGLE-tree assert), _assert_lossless_verify_kernel
  (the FlashInfer verify kernel swallows **kwargs -- silent zero-ring class,
  fail here instead), and the SGLANG_GDN_REPLAYSSM_VERIFY_NUM_STAGES pin.
  Every supporting seam (spec_utils fold pair re-homed by B4-4 onto
  mamba_pool, TritonGDNKernel u/k/g params, pool-side buffers) verified
  live; hybrid_linear's accept-side twin survived.
flashinfer_backend.py (175/178/192/194/208/233): marker file with THREE
  confirmed losses re-planted -- (a) entry-233 sgl-project#45092 wrapper REUSE on both
  per-bs dicts (the double-capture wrong-output class is ACTIVE on this
  stack: graph_variants capture the same bs twice; merge restored the
  unconditional overwrite); (b) entry-208 sgl-project#43524 None-if-workspace scale
  arms on both forward_extend consumers (the merged pool DOES global-scale
  in dequantize_prev_kv -- unconditional k_scale_float double-scales);
  (c) entry-175 sgl-project#43356 speculative workspace: forward_extend mode split +
  eager draft-extend paged branch + pool methods (MHATokenToKVPool main +
  HybridLinearKVPool + SWA wrapper delegations; the quant-method seam
  dequantize_speculative_prefix_to_workspace arrived in-range and the pool
  accessor + backend wiring are OUR half). B3-8's 'no caller' dedupe was
  WRONG-DIRECTION: the callers are this route and its test.
  VERIFIED-PRESENT: entry-194 spec_kv_index_token_blocks at :2576,
  KVWriteLoc.for_layer x3, is_draft_extend_v2 x3; the 39-hunk saved delta
  is mostly re-sited fork content (access-kind refactor upstream itself
  landed in-range).
hybrid_linear_attn_backend.py (102/176/203): upstream-side patch dry-run
  proves ALREADY-FOLDED at the merge (36/36 hunks previously-applied);
  side-state getattr pair rides memory_pool's compat properties (:1721-34).
trtllm_mha_backend.py (64/178): entry-64 layers_mapping arm ABSORBED by
  layer_router (the merged pool routes full/SWA + waits there); entry-178
  SM120-FP8-KV fail-loud construction guard RE-PLANTED (FMHAv2 e4m3 raise
  class returns otherwise).
qsa folds (15/118/125/166/184/200/210/212/213): metadata VERIFIED-
  SUPERSEDED (the merged pack-kernel + sharded + CP-subset path is beyond
  the window delta); qsa_indexer folded (project_qk ensure_cos_sin_cache
  param -- the CP caller as merged TypeErrors without it -- + the guarded
  out-of-capture sizing safety net at both sites); sparse_attn folded the
  SLOT_INDICES int64 overflow guard (comment-hunk superseded by the fork's
  KV_IS_FP8 form); qwen_sparse_attn_backend folded the CP K/V side-stream
  PREFETCH MACHINERY (prefetch_cp_kv/_gather_cp_kv/_cp_kv_pending +
  leak-guard + join + release-ordering -- qwen4_exp.py:2614 CALLS
  prefetch_cp_kv so as merged the CP path AttributeErrors), the sync-free
  slot-table prefix reads, the device-built cu_k and max_q pass-through,
  and upstream's in-place paged-prefill fast path WITH a fork FP8 guard
  (our scaled stores need the descale pack loop; unscaled pools take the
  fast path exactly as upstream intends).
deepseek_v4.py (57/176): shared-experts symbols verified present; raw
  'from deep_gemm import' restored by the merge RE-REDIRECTED to the
  guarded wrapper (mega_moe sibling). glm5_next.py (176): upstream-side
  fold verified fully PRESENT (stale marker).

Battery ACTUALS (CVD=9, prod venv, PYTHONPATH=python, import sglang OK):
  test_flashinfer_nvfp4_speculative: 6F -> **6P** (re-anchored: iteration-
  ids plan seam, kv_layers store seam, dispatch_reason/ragged_verify_layout
  stub fields; all entry-175 beliefs PRESERVED, none weakened)
  test_qsa_cp_unit: 50F -> **65P/0F** across the pair
  gdn/replayssm CPU surface (extend_fold + verify_ple_commit + stages +
  prefill_graph): 5P/2S (stages honest-CUDA-skip)
  ruff F821+E9 + format: clean on all 14 files touched
  KNOWN CARRY: test_mega_moe_deepgemm_api 1F is the DOCUMENTED mega_moe
  class (pre-existing at b3207c7 with and without the B5-3 redirect;
  mxfp4.py's in-range wrapper import vs the test's deep_gemm fake) -> B2
  marker at :905 covers the test-side re-anchor.
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
… C closure -- the post-merge port queue is now decided

ARRIVAL SCAN (git log 12dc623..2a6c204 --grep) + LIVE gh STATE +
head-sha comparison for EVERY deferred item. Verdicts:
  RELEASED-BY-MERGE: sgl-project#42689 (@ 7a632cf in-range -- the SECTION-B
    cherry is now redundant; behavior note rides the restart).
  CLOSED (C-items whose PRs arrived and whose integration this stack
    performed): C1 (the dedicated merge week WAS merge sgl-project#5; all eight
    precursor PRs in-range), C2 (sgl-project#44993/sgl-project#44994 -- B5), C3 (sgl-project#45232/
    sgl-project#45236/sgl-project#45334 -- B2), C4 (sgl-project#45238/sgl-project#45241/sgl-project#45242 -- B3), C5 (sgl-project#44912/
    sgl-project#44913 -- arrived; entry-230 canary re-planted as its guard),
    C9 (sgl-project#39727 -- verified OPT-IN, no purge; BOOT_DELTA anti-needle),
    C0a (arrival shas already recorded at entry 310 -- Section C now
    carries NO open code-integration items: C6/C10 retain only their
    explicitly-named docs/boot-measurement remainders, re-stated).
  STILL-OPEN: sgl-project#44342 (head unchanged; auto-merge comfort LOST to
    #46970x), sgl-project#46153/sgl-project#37106/sgl-project#32479/sgl-project#45391 (gh CONFLICTING -- stale
    bases, rebase before any port), sgl-project#41624/sgl-project#42525/sgl-project#42660/sgl-project#44462/sgl-project#35617
    (open, heads unchanged), sgl-project#46191/sgl-project#39845-class (watch-list, none in
    range).
  HOLD STANDS (operator decision, binding): sgl-project#43356/sgl-project#46452/sgl-project#43240/
    sgl-project#43471 KV route -- step-1 'MERGE sgl-project#5 lands first' is NOW MET; the
    sequence may be re-visited ONLY with the post-merge PCIe-IPC
    measurement at an operator sitting. sgl-project#44732: the 'one purge if done
    WITH the merge' premise LAPSED when merge sgl-project#5 completed without it
    -- later execution costs the SAME single purge once; no penalty,
    no haste. Recorded for the operator, not decided by B6.
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…NSUS ZERO (39/39)

- pool_configurator FP4 draft pricing RE-PLANTED (entry-175 sgl-project#43356, never
  landed upstream -- verified absent at eb73a50): _compute_eagle_fp4_draft_
  cell_size + the FP4 arm in the non-DSA draft branch, folded onto upstream's
  in-window DCP-aware else (the draft's heads stay unreplicated; dcp only
  scales the DSA-indexer term, unreachable in this branch, so the fork's
  2-arg _compute_cell_size call is byte-equivalent here). copy import restored.
- decode_cuda_graph_runner: _init_model_hooks() call RE-PLANTED (entry-61
  boot-integrity class -- the def + the _replay_prepare_hook consumer survived
  the merge, only the call was dropped, so every real DecodeCudaGraphRunner
  build would AttributeError on replay; the fork-only method is NOT upstream
  -- git-verified: no call at eb73a50, no def at base 2a6c204).
- eager_runner region@326/367 ADOPTED (_execute_extend_cp + the inline
  group-sharing predicate == fork's runner_owns_cp_boundary, byte-equivalent;
  sgl-project#44994 (299a75a) is an in-window ancestor so upstream owns the shape now;
  the cp_extend module stays live for base_runner's forward_context path).
- memory_pool grafted lossless-verify tuple VERIFIED (check gate, u/k/g
  supersession, configurator supply, gdn_backend consumer -- all present;
  marker replaced with the verification note).
- layer_list make_layers empty_cache hunk VERIFIED re-homed (code + rationale
  already at the new home; marker downgraded to a plain comment).

Targeted: 223P/0F/193sub (dcp_logical+load_inquirer+page_invariants+
init_req+prefill_adder+page_interleave).
Gates: ruff repo ruleset + format; registration trio rc=0.
@AppNetDeveloper

Copy link
Copy Markdown

Thanks @chengye75-star, and sorry for the slow reply. We haven't re-run the bs=16 test on the 00f2216 guard yet, and here is why, plus everything we've learned on the same SM120 box since.

On the guard (00f2216)

Our reason for going back to FP8 KV was the mid-context decode loss (−20–25% at 25–35k). On SM120, MTP verify runs through the prefill path (speculative_attention_mode=prefill), and with #43356 it re-dequantizes the whole cached prefix of every running request into the FP8 workspace on every verify step. The guard sends verify back to exactly that path. So we expect it to fix the bs=16 crash and keep the +67% KV, but leave the decode tradeoff where it was. A graph-safe native verify is what would change our decision.

We also noticed @LingZ315's refresh of #43356 (bc63670553): the fix for the wrong cached rows during speculative replay (we had the earlier head serving live traffic for ~1 h on Oct 9; our checks passed, but good to know) and 8 CTAs/SM for the SM120 workspace dequant. That second change hits our bottleneck directly, so it's worth measuring.

We'll re-run the full table (bs=16 burst with decode graphs on, the same quality set, 27k/50k/141k c1/c4/c8, MTP accept at 1–4 and 10–19 running) as soon as either (a) a graph-safe native verify candidate exists, or (b) #43356 with the 8-CTA dequant is rebased on current main. We now run main in production, so (b) drops straight into our tree.

What changed on our side

  • Production is SGLang main (nightly 08f10090c7, sglang-kernel 0.4.11, FlashInfer 0.7.4) since Nov 20. Before that, 0.5.23 from Nov 9. Same box: 1× RTX PRO 6000 Blackwell (SM120, 96 GB), TP1, Qwen3.8-27B NVFP4 (ThinkingCap A4 checkpoint, hybrid GDN), integrated MTP with 5 speculative steps + FR-Spec, FP8 KV (~1.14M tokens) + HiCache. Quality set 44/44 on main. With real traffic and a clean start, main ≈ 0.5.23 for us.
  • An earlier main vs 0.5.23 A/B (Nov 14: c1 −10%, c24 −23% per request) turned out to be confounded by host memory, not main. See the next point.
HiCache + container memory: the 1/3-throughput trap
  • Our container has a cgroup memory.max of 279 GB. A full HiCache (252 GB pinned) put it at ~96%. A few minutes after start, the kernel went into constant reclaim/compaction: throughput dropped to ~1/3, and two gloo_tcp_loop threads sat at 30–47% CPU. Halving HiCache (--hicache-ratio 1, ~150/279 GB) was stable under real traffic (70–142 tok/s per request, ~470 tok/s total at ~5.7 concurrent). Rule of thumb: size HiCache from the cgroup limit, not from the machine's RAM.
  • After killing a server, the old scheduler stays a zombie for 1–3 min while it releases ~250 GB of pinned host memory. Starting a new server before that finishes gives the same ~1/3 symptom (HiCache reservation >10 min, high gloo CPU). We now wait for clean memory before every launch.
  • Separately (Nov 2, 0.5.22, --hicache-ratio 4): after ~1 day 18 h uptime, the scheduler was pinned at 100% CPU with the GPU at ~10%, giving 10× slower decode. A restart fixed it. We couldn't profile it in the container; pinned HiCache memory is our main suspect (possibly related to [Fix] hicache: mlock pinned host buffers so page aging never scans them #47543).
Hybrid (GDN/mamba) HiCache: host hits need their own mamba-state budget
SM120 small-M kernels (decode at 1–16 concurrent)

A decode trace at c1 / ~45k context showed the step bound by GEMMs that run at ~50% of memory bandwidth (FP8 10.6 ms, NVFP4 7.7 ms out of a 30.7 ms step; attention only 0.86 ms). Microbenchmarks with the real shapes in CUDA graphs:

  • FP8 per-token (compressed-tensors), M=4–16: default quant+CUTLASS ≈ 46% of BW. Tuned triton_scaled_mm (BLOCK_M 16, N 32, K 256, 4 warps, 4 stages) ≈ 87%, via the existing JSON config mechanism (8 shapes; CUTLASS again from M≥24). --fp8-gemm-backend doesn't affect this path.
  • NVFP4 W4A4: CUTLASS 50–70%. The KDA qwen3x NVFP4 SM120 kernel already in SGLang reaches 85–89%, but _SUPPORTED_SHAPES blocks it for the 27B's gate_up (5120→34816) and down (17408→5120). We widened the allowlist for M≤16.
  • FR-Spec with an FP8 lm_head OOMed: SGLang stores the FP8 weight transposed [5120, 248320], and the hot-token slice cut along K. Fix in our PR [Fix] speculative: FR-Spec (--speculative-token-map) with a quantized (FP8) target lm_head #44277. For an NVFP4 lm_head with interleaved scales (weight_scale_interleaved), the slice needs the modelopt scale un-swizzle/re-swizzle. We have a CPU-tested patch.
  • Together (FR-Spec with a 40k hot list built from our own traffic, 99.8% coverage, + KDA + FP8 JSONs): 45k c1 98.5 → 131.7 tok/s (+34%), c4 45.9 → 52.1 (+13.5%), no memory or quality cost.
  • Also tried, no gain: --enable-torch-compile (bs≤8) and the FlashInfer GDN prefill backend. bf16 mamba-SSM + FlashInfer GDN decode gives +18% KV at equal speed.
Scheduler ceilings at higher concurrency
  • At ~20 concurrent, the scheduler (a single Python thread) is already at ~100% CPU while throughput is still healthy (~800–865 tok/s total). Above that, more concurrency doesn't add throughput.
  • With FP8 KV, the KV cache fills at ~28 concurrent agent requests (~3.5% KV each even with shared prefixes); from there it evicts and slows down. This is the regime where NVFP4 KV capacity would pay off, if decode didn't regress.
  • sglang:cache_hit_rate is an instantaneous gauge (it reads 0.0 between batches). The real hit rate (~82–86% for us) comes from the cached_tokens_total / prompt_tokens_total counters.
Two serving-side gotchas (not NVFP4-specific)
  • qwen3_coder tool-call streaming: non-text parameters are only emitted when they close. A long list/JSON argument produced >45 s without a single chunk, and our client's stall guard took it for a hung stream. We now emit a whitespace keepalive every ~400 chars while a non-text parameter is open; the parsed JSON is identical.
  • Reasoning + prefix cache: a text response's content comes back with a leading \n\n, and the chat template adds another \n\n after </think>. Re-sending it verbatim loses the cache for the whole previous answer; lstrip("\n") keeps it.

Happy to test either candidate on this rig and post the same table. Thanks again to both of you.

Copy link
Copy Markdown
Contributor Author

Updated this PR to work with the latest main. The new head is 1e06d0262, ready for your retest.

This branch has not been deployed

No deployments
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.

3 participants