Repository navigation
[Feat] QSA: Add cache sharding for Qwen3.8 hybrid models - #43527
shiyang814-cpu wants to merge 19 commits into
Conversation
1e06478 to
0c69e62
Compare
a588d40 to
d8a5294
Compare
|
🚀 |
|
[BBuf Review Agent] Could you post main vs this head with the default |
|
@PikachuHyA, Thanks for the benchmark. The primary goal of this work is to reduce QSA cache memory usage and increase effective cache capacity, rather than improve performance. |
Thanks for the suggestion. I reran the requested comparisons on the same 8x H20 setup with TP8/EP8 and
All requests completed successfully. The c=128 and 128K decode results are effectively flat and do not show a default-path decode regression. I treat the c=1 TTFT difference as noise-sensitive rather than as a speedup claim.
GSM8K used all 1,314 examples. LongBench-v2 used the same historical evaluator and settings: 120 loaded rows, 10K–200K context filtering, temperature 0.6, top-p 0.95, and max output 16,384. With the current tokenizer, 85 rows passed the context filter and contributed to the score. Both accuracy changes are within the resolution of these evaluation sizes, so the updated sharded path remains consistent with the previous results. |
|
[BBuf Review Agent] @shiyang814-cpu The shard-1 numbers look good at c=1 and c=128, including the 128K decode run. The shard-4 accuracy reruns on |
|
[sglang-bot Review Agent] Could you split it below 3000 changed lines (now 3006)? |
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
| @@ -1105,10 +1345,12 @@ def _capture_cuda_graph_metadata( | |||
| req_pool_indices=self._graph_row_req_pool_indices[:metadata_rows], | |||
| is_cuda_graph=True, | |||
| graph_write_locs=self._graph_write_locs[:metadata_rows], | |||
| write_owner_mask=self._graph_write_owner_mask[:metadata_rows], | |||
There was a problem hiding this comment.
[sglang-bot Review Agent] At length 68 with compression ratio 4, XPU and NPU graph replay refresh the write location but leave this mask all false. The indexer drops the completed key. Could we copy boundary into the mask and check the stored key across two replays?
There was a problem hiding this comment.
Fixed: the fallback now updateswrite_owner_mask in place on every replay. Boundary and non-boundary replay checks passed.
There was a problem hiding this comment.
[sglang-bot Review Agent] The replay fallback now copies boundary into write_owner_mask in place, so a length-68 row is marked for writing at ratio 4 and a non-boundary row is cleared.
|
|
||
| needs = [len(reqs) for reqs in new_page_reqs] | ||
| available = self.class_free_page_counts() | ||
| if any(need > available[c] for c, need in enumerate(needs)): |
There was a problem hiding this comment.
[sglang-bot Review Agent] With one free page on each of four owners, two requests can both need owner 0's next page. The scheduler admits both, then this returns None and decode raises OOM. Could the retraction check use the same per-owner demand as allocation?
There was a problem hiding this comment.
Fixed: the capacity gate now checks per-owner page demand using request allocation targets and rotation bases. Eviction and retraction checks passed.
There was a problem hiding this comment.
[sglang-bot Review Agent] ScheduleBatch.check_decode_mem now passes the requests to the allocator, which sums page demand by owner. If both requests need owner 0 and only one page is free there after eviction, the gate rejects the batch before alloc_decode.
| """Request tokens a pool of `max_total_num_tokens` per-rank rows holds.""" | ||
| if isinstance(allocator, PageInterleavePoolAllocator): | ||
| return allocator.size |
There was a problem hiding this comment.
[sglang-bot Review Agent] For two 16,384-token shards this already returns 32,768, and PrefillBootstrapQueue doubles it again. A 32,704-token ignore-EOS prompt passes bootstrap and can sit in the queue forever with radix disabled. Could we remove the second widening?
There was a problem hiding this comment.
Fixed: bootstrap now useseffective_logical_max_total_num_tokens directly, without applying shard widening again.
There was a problem hiding this comment.
[sglang-bot Review Agent] PrefillBootstrapQueue now passes effective_logical_max_total_num_tokens directly to max_bootstrap_input_len. The helper uses the shard count only to reserve one page per shard.
| from sglang.test.ci.ci_register import register_cuda_ci | ||
| from sglang.test.test_utils import find_available_port | ||
|
|
||
| register_cuda_ci(est_time=30, stage="base-b-kernel-unit", runner_config="4-gpu-b200") |
There was a problem hiding this comment.
[sglang-bot Review Agent] This file has no __main__ entrypoint, so collect_tests raises before it can select any suite. Once that is fixed, the B200 registration still skips the SM90-only test. Could we add the pytest entrypoint and register it on four H100s?
There was a problem hiding this comment.
Fixed: restored the executable pytest entrypoint and switched to the existing four-GPU H100 runner. The eager/CUDA Graph pipeline passed on four H20 GPUs.
There was a problem hiding this comment.
[sglang-bot Review Agent] The pytest entrypoint is there, but test/run_suite.py still calls validate_all_suites before filtering, and it rejects extra-b-kernel-unit-test-4-gpu-h100. Could you change stage to "extra-b" at line 16 so this selects extra-b-test-4-gpu-h100?
| for enabled, feature in unsupported: | ||
| if enabled: | ||
| raise ValueError(f"QSA cache sharding does not support {feature}") | ||
| if ep_size < 1 or moe_dp_size < 1 or tp_size % (ep_size * moe_dp_size): |
There was a problem hiding this comment.
[sglang-bot Review Agent] TP8 with attention DP2 and EP8 reaches this check with tp_size=4, so it rejects a valid eight-rank expert group even when shard size 2 fits the KV replica group. Could we validate EP against the full TP width?
There was a problem hiding this comment.
Fixed: EP topology validation now uses the full TP size; KV replica validation still uses attention TP size. The reported configuration passes validation.
There was a problem hiding this comment.
[sglang-bot Review Agent] The parallel hook now passes cfg.tp_size to the EP check and the derived attention TP width to the KV replica check. That lets EP8 use the full TP8 group with attention DP2.
| raise StopIteration | ||
|
|
||
| monkeypatch.setattr(qsa_indexer_module, "qsa_mqa_decode", fake_decode) | ||
| indexer = SimpleNamespace(block_topk=512, distributed_topk_group=object()) |
There was a problem hiding this comment.
[sglang-bot Review Agent] On CUDA this raises AttributeError while evaluating self.index_n_heads, before fake_decode can check min_scored_len. Could we give the fixture the query head count?
There was a problem hiding this comment.
Fixed: added the missingindex_n_heads fixture field and includedwrite_owner_mask in the existing metadata comparison. The CUDA regression passed.
There was a problem hiding this comment.
[sglang-bot Review Agent] index_n_heads=1 was added to a different fixture at line 597. Could you add it to the SimpleNamespace at test_qsa.py:669 too? QSAIndexer.select_decode_tokens reads it before calling fake_decode.
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
| ) | ||
| destinations = tl.cumsum(owned.to(tl.int32), axis=0) - 1 | ||
| output_mask = offsets < compact_width | ||
| tl.store(compact_ptr + row * compact_width + offsets, -1, mask=output_mask) |
There was a problem hiding this comment.
[sglang-bot Review Agent] With shard size 4, one warp can clear a slot to -1 after another warp has put a valid KV ID there. Attention then skips that token. Could we fill only the suffix starting at the owned count?
| from sglang.test.ci.ci_register import register_cuda_ci | ||
| from sglang.test.test_utils import find_available_port | ||
|
|
||
| register_cuda_ci(est_time=30, stage="extra-b-kernel-unit", runner_config="4-gpu-h100") |
There was a problem hiding this comment.
[sglang-bot Review Agent] This registers extra-b-kernel-unit-test-4-gpu-h100, which makes validate_all_suites raise before it selects any tests. Could we use stage="extra-b" for the existing four-H100 lane?
| compressed, buffer, metadata.graph_write_locs, owner_mask | ||
| ) | ||
| else: | ||
| local_locs = metadata.graph_write_locs[owner_mask].long() |
There was a problem hiding this comment.
[sglang-bot Review Agent] On XPU the mask selects zero rows at capture and one row when a request reaches length 68. Boolean indexing makes the temporary’s shape depend on that device value inside torch.xpu.graph. Could we keep the store fixed-width and predicate each row?
| self, *, num_tokens: int, tree_cache, requests=None, spec_algorithm=None | ||
| ) -> bool: | ||
| self.evict_to_free_tokens(tree_cache, num_tokens) | ||
| if self.available_size() < num_tokens: |
There was a problem hiding this comment.
[sglang-bot Review Agent] With free pages [0, 1, 1, 1], a decode that needs one page on owner 1 gets retracted because available_size() is zero. Could we check the requested owners before applying the minimum-owner floor?
| block_indices = qsa_fast_topk( | ||
| logits, row_starts, compressed_lengths, topk=self.block_topk | ||
| ) | ||
| block_indices = QSAIndexer._maybe_merge_distributed_topk( |
There was a problem hiding this comment.
[sglang-bot Review Agent] With 511 larger scores and two blocks tied for the last slot on one owner, local fast_topk can discard the smaller ID before the global merge sees it. Could we apply the logical-ID tie break during local selection too?
| and qsa_sharding_runtime is not None | ||
| and qsa_sharding_runtime.enabled | ||
| ): | ||
| token_to_kv_pool_allocator = PageInterleavePoolAllocator( |
There was a problem hiding this comment.
[sglang-bot Review Agent] With shard size 4 and post-capture KV sizing enabled, startup reaches PageInterleavePoolAllocator.resize() and raises NotImplementedError. Could we gate QSA sharding in post_capture_kv_sizing_planned too?
| raise StopIteration | ||
|
|
||
| monkeypatch.setattr(qsa_indexer_module, "qsa_mqa_decode", fake_decode) | ||
| indexer = SimpleNamespace(block_topk=512, distributed_topk_group=object()) |
There was a problem hiding this comment.
[sglang-bot Review Agent] On CUDA this still raises AttributeError on self.index_n_heads before fake_decode can check min_scored_len. Could we set index_n_heads=1 on the fixture to match the query?
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
Still open from my last review:
- Local truncation can discard the global tie winner (
python/sglang/srt/layers/attention/qsa/qsa_indexer.py:781)
| # Fixed-width updates preserve masked destinations, including real | ||
| # slot zero. Serial rows avoid collisions with inactive safe slots. | ||
| local_locs = metadata.graph_write_locs.long() | ||
| for row in range(compressed.shape[0]): |
There was a problem hiding this comment.
[sglang-bot Review Agent] At batch size 128, NPU graph replay reads and writes 128 rows in sequence per QSA layer, even on steps with no completed group. Could we batch the masked store or show base/head NPU replay timings and streaming throughput, TTFT and ITL at concurrency 1 and 128?
sglang-bot
left a comment
There was a problem hiding this comment.
[sglang-bot Review Agent] A few things to fix before this can go in.
Still open from my last review:
- Local truncation can discard the global tie winner (
python/sglang/srt/layers/attention/qsa/qsa_indexer.py:781)
| keys, cache = compressed.to(buffer.dtype).contiguous(), buffer | ||
| if buffer.dtype == torch.float8_e4m3fn: | ||
| keys, cache = keys.view(torch.int8), cache.view(torch.int8) | ||
| inactive = -1 - torch.arange(keys.shape[0], device=keys.device) |
There was a problem hiding this comment.
[sglang-bot Review Agent] At batch size 1, every QSA layer rebuilds the same slot IDs and casts them back to int32 before the store. Could we prepare those slots once per replay, or show base/head NPU replay timings and streaming throughput, TTFT and ITL at concurrency 1 and 128?
There was a problem hiding this comment.
Both issues are addressed in the current head. Distributed prefill/decode now apply deterministic SMALL tie-breaking before local truncation, validated with 384 real MQA cutoff cases and 4/8-H20 eager/CUDA Graph tests. Slot IDs are prepared once per replay and reused across layers through the same int32 buffer; batch-1/128 FP16/BF16/FP8 contract tests pass. NPU hardware timings remain unmeasured.
There was a problem hiding this comment.
[sglang-bot Review Agent] cedb2af3 fixes the NPU slot issue: each layer now reads the int32 buffer prepared once per replay. On ROCm, QSAIndexer.select_decode_tokens still reaches fast_topk at qsa/kernel.py:71 because the SMALL branch excludes HIP. Could that path keep the smaller logical ID at the 512th-slot tie before merging?
There was a problem hiding this comment.
Thanks! I've added an explicit HIP rejection during startup: QSA cache sharding currently requires NVIDIA CUDA, so ROCm cannot enter the distributed top-k path. The default unsharded ROCm path is unchanged. H20 cutoff tests and 4/8-GPU eager/CUDA Graph regressions pass.
There was a problem hiding this comment.
[sglang-bot Review Agent] 4a419ac0 rejects QSA cache sharding at startup when torch.version.hip is set, so ROCm can’t reach the distributed top-k cutoff.
Rebase the validated cache-sharding feature state onto the latest upstream main while preserving owner-local attention and distributed candidate merge behavior.
Preserve graph-safe shard ownership and widening semantics while removing unused owner packing and consolidating redundant transport tests.
Inline the owner attention pipeline and replace redundant test matrices with focused multi-GPU coverage so the change remains reviewable without affecting measured performance.
Send cache-sharded QSA writes through the pool ownership mapping and exclude sharded layouts from the incompatible fused decode path.
Keep the local fast top-k path while forcing initialized scores whenever rank-local candidates participate in a global merge.
Consolidate sharding setup and regression fixtures so the PR remains below the 3,000-line review threshold without changing runtime behavior.
Add the pytest script entry required by the CI registry so partitioned suites execute the four-GPU regression instead of failing during collection.
Preserve the ServerArgs positional ABI, classify the experimental CLI flag, and align CP, routed-pool, fused-KV, and XPU indexer fixtures with the production cache-sharding contract so CI suites exercise the intended paths.
Make owner compaction stores disjoint and preserve deterministic local cutoff ties before distributed candidate pruning. Check and reclaim decode capacity against the actual rotated owner demand. Keep fallback graph writes fixed-shape, disable post-capture KV sizing for QSA sharding, repair the decode fixture and register the four-GPU test in the existing extra-b H100 suite. Preserve the original CP store path and remove redundant candidate and pool setup code. Validation: 528 QSA tests, 345 adjacent tests, 36 temporary regressions, and 238 subtests passed. Four- and eight-H20 candidate/owner attention pipelines passed in eager and CUDA Graph modes. The real CI registry and executor passed; isolated compaction memcheck reported zero errors. XPU/NPU fallback was checked with CPU dispatch simulation, not hardware.
Use one ATB cache store per replay batch with unique negative slots for inactive rows. Preserve real slot zero and copy FP8 cache bytes through int8 views. Keep CUDA and reference dispatch unchanged. Simplify equivalent ownership and candidate mapping expressions to keep the complete PR below the 3000-line review limit. Validation: 538 QSA tests, 361 adjacent tests, 250 subtests, 384 real MQA cutoff cases, and four/eight-H20 eager and full CUDA Graph pipelines pass. All PR hooks and CI registry checks pass. Device memcheck reports no memory errors with CUDA API probe reporting disabled. The NPU store contract passes batch-1/128 dispatch simulation for FP16/BF16/FP8. NPU hardware, native graph replay and performance have not been tested.
Prepare unique negative inactive slots in shared graph metadata, including cold capture, and reuse its fixed int32 storage in every layer's native cache store. Remove per-layer slot construction and conversion while preserving valid slot zero and FP8 byte views. Validation: batch-1/128 FP16/BF16/FP8 replay-slot contract tests, 714 targeted regressions, 384 real H20 MQA cutoff cases, and four/eight-GPU eager and CUDA Graph pipelines pass. Qwen3.8-Flash-Next-FP8 serves C128 and 128K contexts; shard1/shard4 each score 63/64 on the GSM8K subset. NPU native graph replay and performance remain untested.
Plan prefill chunks from group-wide key counts before handling empty owners. Avoid unsharded history-position allocation and use parallel page metadata, including multi-step draft replay. Gate diagnostic mask construction with SGLANG_QSA_DEBUG_BOUNDS while retaining invalid-slot checks in debug mode.
Summary
This PR adds owner-based QSA cache sharding for Qwen3.8 hybrid models, partitioning raw K/V history and compressed index keys within each KV-head replica group.
Upstream KVShard already supports sharded raw K/V storage for Qwen3.8. This PR adds a separate execution mode that also shards compressed history: each rank scores its local keys, merges candidates into a global Top-K, and computes sparse attention against owner-local K/V.
The implementation reuses page-interleave placement and allocation, with deterministic logical-ID tie-breaking, FP32 output/LSE merging, and shared fixed-address communication buffers for CUDA Graph replay. Pending compression rings, GDN/PLE states, and MoE placement retain their existing layouts.
Prefill performance
Measured at
4a419ac0beon one 8×H20 host withQwen3.8-Flash-Next-FP8, TP8/EP8. Shard1 and shard4 used identical code, environment, and server settings.Each point is the median of three independent single-request benchmarks: random token IDs, one output token, concurrency 1, seed 42, temperature 0, and no client warmup. The reported session followed an initial measurement session and reversed the context-length order.
Logical KV capacity increased from 2,287,616 to 8,615,936 tokens, approximately 3.77×, at the same memory fraction. This compares shard4 with shard1; it does not measure incremental capacity over upstream CP + KVShard, physical GPU memory reduction, or an increase in the model context-length limit.
These results evaluate prefill and supersede the earlier performance table. They do not establish sustained decode throughput or long-context answer quality.
Accuracy and default-path regression
The November 24 follow-up reported the following shard4 results at
a9835ad68f:LongBench-v2 loaded 120 examples; 85 passed the 10K–200K context filter. It used temperature 0.6, top-p 0.95, and a maximum output of 16,384 tokens.
The same follow-up compared base
dacaf1d713with heada9835ad68f, using shard1 and streaming. C128 output throughput was effectively unchanged, and the 128K-input decode run showed no material regression. These are historical revision-specific results, not measurements of the latest rebased head.Usage
The following command reproduces the configuration used for the prefill measurements:
With TP8 and two KV heads, shard4 creates groups
[0,1,2,3]and[4,5,6,7]. Each group owns one partitioned history for its KV head; history is not globally deduplicated across the two groups.Compatibility
Sharding defaults to disabled (
--qsa-cache-sharding-size 1). Enabling it currently requires NVIDIA CUDA and a shard size that divides the attention KV-head replica group.This implementation rejects combinations with:
These are current implementation limits.
CI States
Latest PR Test (Base): ⊘ Skipped in Run #47064259070 -- its commit has no run-ci approval, or the run predates the labels; a maintainer's⚠️ Run #47064262558
/approve-ciapproves this commit and reruns it, or/rerun-failed-cireruns an approved one.Latest PR Test (Extra): ⊘ Skipped -- add the
run-ci-nv-extralabel to opt in.Latest PR Test (AMD ROCm 10):
Tip
Base CI only covers the core cases, and its workload may not exercise your change. Use
/rerun-testto run the tests your change touches, or copy this prompt for an agent: