Skip to content

[Feat] hisparse: host KV tier for the QSA (Qwen4) sparse-attention backend - #46191

Open
JUNQINGV587 wants to merge 5 commits into
sgl-project:mainfrom
JUNQINGV587:qsa-hisparse
Open

JUNQINGV587 wants to merge 5 commits into
sgl-project:mainfrom
JUNQINGV587:qsa-hisparse

Conversation

@JUNQINGV587

@JUNQINGV587 JUNQINGV587 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Qwen3.8-Flash-Next has a 262K native context and ~24 KiB/token of KV (12 full-attention layers, GQA 2:1, 256 head dim, bf16). On 2xL20 (47.45 GiB/card) the weights are 44.75 GB/card, which leaves a device KV pool of 47,232 tokens measured from the server's own log line. A single 262K request cannot be admitted at all, and the admission path rejects it in 1.5 s.

HiSparse already provides exactly the machinery needed (pinned host mirror + on-demand fetch + CUDA-graph-safe custom ops), but it is tied to the MHA backends and is explicitly rejected for qwen4_exp by validate_hisparse().

What this PR does

Wire the existing HiSparse two-tier cache to the QSA backend:

  1. mem_cache/hisparse_hook.py: allow the QSA backend through validate_hisparse().
  2. mem_cache/qsa_kv_pool.py: add a HiSparse-aware QSA pool whose device side is a bounded window of the logical sequence and whose host side is a pinned mirror; register it so the scheduler's capacity accounting sees it.
  3. Address translation: the four KV read points and the single write gate in the QSA kernels now map logical -> device slot indices and fall back to the host mirror on a miss.
  4. managers/coordinator.py + kv_cache_configurator.py: call the HiSparse coordinator and multiply logical_token_capacity() by host_to_device_ratio (without this, admission still uses the device window and rejects long requests).

A later commit makes the host write capture-safe: the original code did an unpinned device->host copy inside set_kv_buffer, which raises Cannot copy between CPU and CUDA tensors during CUDA graph capture unless the CPU tensor is pinned. The host write is now a Triton kernel that scatters straight into the pinned mirror, with a fixed-shape fast path when resident_tokens >= logical_size.

Result (2xL20, TP=2, bf16 KV, CUDA graph on)

--enable-hisparse --hisparse-config '{"host_to_device_ratio": 4}' --max-total-tokens 196608:

item before after
admitted per request 47,226 tok 262,144 tok
3 concurrent requests n/a 3 x 258,231 tok
decode, 3 streams n/a 54.06 / 53.99 / 53.99 t/s (162-165 agg)
decode, 1 stream @258K n/a 85.74 t/s (94.93 at 32K)
VRAM 44.75 GB/card 44.5 / 49.1 GB
host pinned n/a 9.0 GiB/rank

Decode speed with the graph off is 8.3 t/s, so CUDA graph capture must stay enabled; the host tier is only reached on a window miss.

Limits / notes for reviewers

  • Only the QSA backend is wired; MHA/MLA keep their existing paths.
  • The indexer key cache must stay device-resident (it is read on every decode step to pick the top-k blocks); only K/V are tiered.
  • --max-total-tokens is the device window. Setting it to the full logical size (786,432) silently clamps to 399,360 and then allocates a 73 GiB host mirror, which the OOM killer takes. The ratio must be set via --hisparse-config instead.
  • Host-tier read costs ~2.2 ms/token at 262K in the measured configuration.

Testing

  • Kernel-level: test_kernels.py (gather/scatter equivalence, host-vs-device read) and test_fused.py pass.
  • End-to-end: three concurrent 258,231-token requests admitted and decoded on 2xL20, Xid 0 across the run. Two 8K prompts compare equal to the non-HiSparse path within the machine's own run-to-run logit spread (this box does not reproduce greedy ids between runs of the identical binary, so the check is on logits, not ids).
  • compileall clean.

CI States

Latest PR Test (Base): ❌ Run #40107835921
Latest PR Test (Extra): ❌ Run #40107835926
Latest PR Test (AMD ROCm 10): ❌ Run #40107835853

Qwen4 QSA keeps its 12-layer bf16 K/V in 12,288 B/token and a device-resident
indexer. Wire the existing HiSparse allocator to a QSA host tier instead of
the MLA 576 B layout:

- validate_hisparse: allow Qwen4 QSA, require bf16/auto KV and skip the DSA
  backend whitelist (QSA has its own sparse backend).
- HiSparseQSATokenToKVPool: pinned host K/V for the logical id space, write
  through on every store, device copy only for resident slots, indexer sized
  for the logical capacity (compressed_slot = full_slot // ratio).
- HiSparseMHAMainPool as the full-attention pool; allocator gains a
  host-tier-only mode (logical pages only, no device pages).
- fused_kv / pack_qsa_prefill_kv / compact kernels: resolve logical -> device
  slot with a resident window; non-resident rows read the pinned host copy.
- pool_configurator: indexer cell cost scales with host_to_device_ratio.
- model_runner/scheduler: QSA has no HiSparseCoordinator; keep size_full for
  scheduling capacity without starting the DSA coordinator.

(cherry picked from commit b43c888)
… create

QSA forces scheduler.enable_hisparse=False and skips
maybe_init_hisparse_coordinator (allowed P0 degradation), but the
prefill result path guards on the global get_memory().enable_hisparse,
which stays True because the HiSparse KV pool selection keys off it.
Result: AttributeError: 'NoneType' object has no attribute
'admit_request_into_staging' on the first prefill, killing the server.

Guard both coordinator calls on the coordinator actually existing.

(cherry picked from commit 3853328)
logical_token_capacity() ignored host_to_device_ratio, so with
--enable-hisparse the admission cap (max_req_input_len) came out as the
device window: ratio=2/device 4608 refused an 8152-token prompt with
'Input length (8152 tokens) exceeds the maximum allowed length (4602
tokens)'.  Scale by the ratio for QSA only; DSA sizes its own capacity.

(cherry picked from commit 475c869)
Writing the pinned host mirror used to do three things that CUDA graph
capture forbids: an unpinned device->host copy, a host-side boolean check,
and a variable-length gather. Replace them with one fixed-shape Triton
scatter that writes the host mirror and, only for slots inside the
resident window, the device tier. When every slot is resident the Python
side skips the launch entirely.
@github-actions

This comment has been minimized.

@JUNQINGV587 JUNQINGV587 changed the title HiSparse: host KV tier for the QSA (Qwen4) sparse-attention backend [Feat] hisparse: host KV tier for the QSA (Qwen4) sparse-attention backend Oct 24, 2026
@JUNQINGV587

Copy link
Copy Markdown
Contributor Author

What this does

Adds a host-side KV tier to the QSA (Qwen4 sparse-attention) backend: when the device window is full, blocks migrate to a pinned host buffer instead of being dropped, and come back on demand.

Validation

2x L20 48 GiB (SM89), TP=2, Qwen3.8-Flash-Next NVFP4, --context-length 262144, radix cache off.

  • 3 requests x 258,231 prompt tokens = 774,693 tokens in flight, KV pool 786,432 slots (device window 196,608 x ratio 4, host tier 9.0 GiB/rank)
  • prefill 173.6 s for the three requests (~4,460 tok/s aggregate); decode 162.2 tok/s aggregate (54.1 / 54.0 / 54.0 per stream at 258K), 54.4 tok/s at a 128K window
  • VRAM 44.6 / 44.3 GiB per card; startup ~690 s; single-stream 258K = 85.7 tok/s

One caveat worth stating up front: this stack is not bitwise reproducible request-to-request (on main either), so we validated perf plus token-id equality on a fixed probe set, not bitwise KV equality.

The test matrix is skipped on this PR because it needs the run-ci label -- happy to add a targeted unit test for the qsa mem-cache wiring if you can point me at the right place.

@JUNQINGV587

Copy link
Copy Markdown
Contributor Author

Validation on real hardware (SM89, 2× L20)

Ran this branch (plus a local merge of main at 6563312) on the box it was written for:
2× L20 48 GB (SM89), TP=2, PCIe Gen3 x16, no NVLink, Qwen3.8-Flash-Next NVFP4 (W4A16 Marlin MoE),
262,144 context, HiSparse host_to_device_ratio=4 (9.0 GiB pinned host KV tier per rank).

Numbers from /metrics + a streaming probe (no synthetic kernels):

case result
258K-token prompt, single stream TTFT 57.2 s, 85.8 tok/s decode
3 × 258K concurrent 162.4 tok/s aggregate, 54.1 tok/s per stream, max TTFT 175 s
KV pool after startup 786,432 logical tokens (device window 196,608)
GPU memory resident 44.7 / 48 GiB per card
dmesg Xid delta across the runs 0

Same runs with the opt-in prefill CUDA graph (--cuda-graph-bs-prefill) OOM while capturing the
12,288 bucket on this card, so all numbers above are with the default --disable-prefill-cuda-graph.
That is a VRAM headroom limit on 48 GB cards, not a regression from this PR.

Thanks again for the review.

detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…amilies' blocks deleted), sgl-project#38355 moved to Section R as MISDIAGNOSED (C11 entry closed, five-leg citation), sgl-project#33029 moved to Section R as NOT-NEEDED, S-RACE tripwire queued post-merge, sgl-project#46191 ring-decision cross-reference updated
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 Oct 30, 2026
…gl-project#44462(317)/sgl-project#44342-trunk(318) in both the FAM-A3b block and the B6 re-triage verdicts; 10 dated corrections (mergeable flips: sgl-project#46191 REAL -> WATCH-HIGH with the re-derive-vs-QSA_RING_GROUPS=2 instruction, sgl-project#39845 DISPUTED as UNKNOWN-not-true plus the general 'UNKNOWN is no signal' rule; sgl-project#44344 -> SECTION R DOA with the entry-268 unconditional-clear subsumption citation and the mergeable-is-a-trap note; sgl-project#42525 target path moved fla->linear; sgl-project#45520 STILL OPEN -> re-apply rule ARMED FOR MERGE sgl-project#6; b12x-package archived claim DISPUTED with the frozen cutlass-dsl==4.8.0 pin risk standing; sgl-project#46153+sgl-project#41624 gated as ONE QAD bundle; sgl-project#37106 PARKED on eroded motivation with named revive conditions; sgl-project#32479 gated behind the PCIe-IPC measurement and DE-COUPLED from sgl-project#45391; sgl-project#44462's NEXT note spent); NEW S-item S-B12XDENSE filed

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.

1 participant