Repository navigation
feat(qsa): Support pyhip qsa indexer for prefill/decode, sparse gqa for prefill - #43
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The pinned PyHIP revision lacks the QSA modules imported by the runtime and AMD test.
1 open finding
What changed in this PR
Adds optional PyHIP QSA acceleration for gfx942 prefill/decode and improves sparse prefill handling.
Changes:
- Adds PyHIP QSA attention/indexer integration and validation.
- Expands QSA pending rings and optimizes packed prefill K/V gathering.
- Fixes fast-top-k overflow handling with AMD coverage.
| File | Description |
|---|---|
test/registered/kernels/test_qsa.py |
Tests verify-window ring compression. |
test/registered/kernels/test_pyhip_qsa.py |
Tests PyHIP attention, indexer, and graphs. |
test/registered/kernels/ops/elementwise/test_fast_topk.py |
Tests top-k overflow on AMD. |
scripts/launch_qwen38_flash_next_fp8_mi308x_pure_tp1.sh |
Updates model and PyHIP settings. |
scripts/launch_qwen38_flash_next_fp8_mi308x_pure_tp_4_or_8_or_2.sh |
Enables PyHIP QSA for multi-TP launches. |
python/sglang/test/qsa_validation.py |
Adds numerical validation utilities. |
python/sglang/srt/mem_cache/qsa_kv_pool.py |
Enlarges per-request QSA rings. |
python/sglang/srt/layers/attention/qwen_sparse_attn_backend.py |
Integrates PyHIP sparse prefill attention. |
python/sglang/srt/layers/attention/qsa/qsa_indexer.py |
Dispatches supported frames to PyHIP. |
python/sglang/srt/layers/attention/qsa/pyhip_backend.py |
Implements PyHIP adapters. |
python/sglang/srt/layers/attention/qsa/metadata.py |
Adds expanded ring addressing. |
python/sglang/srt/layers/attention/qsa/graph_metadata.py |
Updates graph ring metadata. |
python/sglang/srt/environ.py |
Defines PyHIP QSA environment flags. |
python/sglang/kernels/jit/csrc/elementwise/fast_topk.cuh |
Adds full-row overflow fallback. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| ) | ||
| self._rope_axis_map_cache = None | ||
| self._pyhip_indexer = None | ||
| if is_hip() and envs.SGLANG_USE_PYHIP_QSA.get(): |
There was a problem hiding this comment.
Shall we add device check here ?
There was a problem hiding this comment.
There is unnecessary to double check the device in PyHIPIndexer's __init__ . Because there is a check _supports_frame in sglang/python/sglang/srt/layers/attention/qsa/pyhip_backend.py.
| if not self._supports_frame( | ||
| indexer=indexer, hidden=hidden, positions=positions | ||
| ): |
There was a problem hiding this comment.
what happened if not self._supports_frame is True, forward return None, but pyhip QSA backend does not do anything?
There was a problem hiding this comment.
Should we update this PyHIPIndexer static method _supports_frame to can_use_for_forward? Move condition check in python/sglang/srt/layers/attention/qsa/qsa_indexer.py line 616:
if hidden_states.is_cuda and self._pyhip_indexer is not None:
output = self._pyhip_indexer.forward(
indexer=self,
hidden=hidden_states,
positions=positions,
logical=logical_positions,
batch=forward_batch,
metadata=indexer_metadata,
state_slots=state_slots,
)
if output is not None:
return output
So that we could have a proper fallback if pyhip index not supported.
There was a problem hiding this comment.
That makes some sense, but function-wise, it works as a fallback. can_use_for_forward is the first function in self._pyhip_indexer.forward if it returns None, the indexer can run the original sglang functions.
QSAIndexer.forward_cuda()
└─ self._pyhip_indexer.forward(...)
└─ PyHIPIndexer.can_use_for_forward(...)
├─ False → return None
├─ EXTEND → _prefill() → runtime.prefill_indexer(...)
├─ graph DECODE / TARGET_VERIFY
│ → _decode() → runtime.decode_indexer(...)
└─ other mode → return None
QSAIndexer.forward_cuda()
└─ output is None
→ origin sglang project_qk / compress / MQA / top-k
There was a problem hiding this comment.
I've added qsa indexer support for decode eager mode(c9d2ef4), and left MTP draft verify (not in cuda graph) and MTP draft extend for follow-up PRs.
Co-authored-by: Ethan Yang <[email protected]>
d14f81d
into
qwen38-flash-next-amd-current-fix-install
…or prefill (#43) * add pyhip qsa support * enable pyhip for mtp verify * fix error overwriting for ring buffer * align new indexer interface * remove potential sync in qsa * cache packed QSA KV slots per forward * update scripts * update mtp method * update pyhip version * clean qsa attn conditions * rename condition function * rename indexer support * support qsa indexer in decode eager mode * rename ring to ring_slots * fix ring slots * Apply suggestion from @yicyang Co-authored-by: Ethan Yang <[email protected]> --------- Co-authored-by: Luo Cheng <[email protected]> Co-authored-by: Ethan Yang <[email protected]> (cherry picked from commit d14f81d)
…#90) * feat(qsa): Support pyhip qsa indexer for prefill/decode, sparse gqa for prefill (#43) * add pyhip qsa support * enable pyhip for mtp verify * fix error overwriting for ring buffer * align new indexer interface * remove potential sync in qsa * cache packed QSA KV slots per forward * update scripts * update mtp method * update pyhip version * clean qsa attn conditions * rename condition function * rename indexer support * support qsa indexer in decode eager mode * rename ring to ring_slots * fix ring slots * Apply suggestion from @yicyang Co-authored-by: Ethan Yang <[email protected]> --------- Co-authored-by: Luo Cheng <[email protected]> Co-authored-by: Ethan Yang <[email protected]> (cherry picked from commit d14f81d) * feat(qsa):Extend QSA prefill to support 1M context (#81) * feat(qsa): read K/V in place and allow 1M-context decode in PyHIP QSA - Prefixed chunk prefill: PyHIP attention reads the layer's K/V pool in place through the packed slot table (kv_slots) instead of gathering the full-context K/V with index_select; pools PyHIP cannot read in place keep the gather path. - Graph/eager decode: the PyHIP indexer accepts compressed page tables up to the runtime's MAX_COMPRESSED_KEYS (262144 keys, a 1M-token context) instead of 65536, bounded by the 32-bit offsets of its FP32 logits. - Tests: in-place reads match the gather fallback, and graph decode with a 1M-context page table still runs PyHIP. Co-authored-by: Copilot <[email protected]> (cherry picked from commit 0a10105) * fix(qsa): accept YaRN MRoPE in the PyHIP QSA indexer The 1M-context launch overrides RoPE to YaRN, which get_rope builds as YaRNScalingMRotaryEmbedding. PyHIPIndexer.create matched MRotaryEmbedding by exact type, so it returned None and the native indexer silently ran (TP2, ~1M-token prompt: TTFT 229 s vs 87 s with PyHIP). YaRN only rescales the cos/sin cache that the PyHIP prep reads; its lookup and MRoPE axis composition are MRotaryEmbedding's. The new test builds the RoPE through get_rope with the launch-style YaRN parameters and checks that PyHIP is selected and matches native bit for bit in prefill, graph decode and verify. Co-authored-by: Copilot <[email protected]> (cherry picked from commit 010b0e2) * feat(qsa): split long PyHIP QSA prefill indexer rows across attention-TP ranks The PyHIP prefill indexer is replicated on every TP rank; at 1M context its last chunk costs 45.3 ms per layer. With SGLANG_OPT_PYHIP_QSA_SPLIT_INDEXER=1 (off by default), a chunk of at least 2048 rows averaging at least 32768 compressed keys per row is cut into equal contiguous shares: each attention-TP rank selects its share with prefill_indexer(row_range, out) into a shared [tp * share, 2051] frame, and an in-place all_gather_into_tensor completes it. The thresholds come from MI308X measurements (indexer ~1.06e-5 us per row and key, TP2 all-gather ~0.087 us per row) with about a 2x margin. Validated on TP2 with YaRN at --context-length 1000000: SGLANG_TEST_PYHIP_QSA=1 passes with the split on (including a 999648-token request), and TTFT changes by +0.1% / -1.3% / -5.0% / -11.5% at 131k / 262k / 524k / 1M inputs (1M: 86.1 s -> 76.2 s); the decode path is unchanged. Needs pyhip with prefill_indexer(row_range, out). Co-authored-by: Copilot <[email protected]> (cherry picked from commit b1abbb0) * add 1m script * fix(qsa): bound Torch decode fallback key workspace Gather and score compressed keys in page-aligned chunks with a 256 MiB FP32 K budget. Preserve FP32 scoring, full logits, masking and capture-static shapes without materializing all per-query keys at once. Handle empty batches/capacity and truncated or padded output lengths. * feat(qsa): log actual indexer backend dispatch Add the opt-in SGLANG_LOG_QSA_INDEXER_BACKEND diagnostic flag. Log the selected PyHIP, Torch or TileLang path after the indexer returns, with layer, forward mode and query row count. Deduplicate by layer instance, mode and backend. Keep logging disabled by default and avoid import hooks or GPU synchronization. * update scripts * update test * Update default model path in argument parser Co-authored-by: Copilot Autofix powered by AI <[email protected]> * test(qsa): cover chunked decode reference workspace Lower the FP32 key budget to force multiple page chunks and compare against a dense reference. Cover reordered pages, different context lengths, partial-page truncation, padded output and empty inputs. Add a 1M-capacity CUDA Graph workspace bound and replay checks with changed query, cache, page-table and length inputs. * Change TestQsaDecodeWorkspace base class Refactor TestQsaDecodeWorkspace to inherit from CustomTestCase. Co-authored-by: Copilot Autofix powered by AI <[email protected]> * revert(qsa): drop chunked Torch decode fallback and workspace tests Revert the chunked reference implementation and its dedicated workspace regressions. Keep the PyHIP 1M/YaRN/TP-split integration and actual backend dispatch logging unchanged. Reverts 14c5729, 7edc822, and e255acb. * update script * test(qsa): validate graph selection beyond 65536 compressed keys Compare real compressed lengths of 66049 and 250001 against an independent Torch reference, with reordered pages, masked tail keys, and changing lengths during CUDA graph replay. * chore(scripts): remove redundant long-context request helpers Use the built-in serving benchmark with token-ID prompts, zero client warmups, and an explicit cache flush for long-context reproduction. Validated a cold 1000000-token input and 350-token output on TP2 with YaRN. * build(rocm): pin PyHIP to merged QSA API revision --------- Co-authored-by: Luo Cheng <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]> (cherry picked from commit 286cd46) * fix(qsa): adapt backports to qwen4 v0.5.21 interfaces * chore(scripts): move Qwen3.8 1M launcher to evaluation * docs: add Qwen3.8 TP1 and 1M launch examples --------- Co-authored-by: Luo Cheng <[email protected]> Co-authored-by: Ethan Yang <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>

Motivation
This PR is based on tingqli/pyhip#57 . This PR introduces qsa indexer optimization for prefill/decode and sparse gqa optimization for prefill.
MTP draft extend and eager verify(no cuda graph verify) still use original sglang indexer. A follow-up PR will fix it.
Co-authored-by: Cheng Luo [email protected]
Modifications
pyhip.ops.qsa.flydsl.attentionseesrc/pyhip/ops/qsa/flydsl/readme.mdin pyhippyhip.ops.qsa.flydsl.indexer.prefill_indexerandpyhip.ops.qsa.flydsl.indexer.decode_indexeras qsa indexer..tolist()fence and move slot mapping into metadata.Accuracy Tests
TP2
TP2+MTP
TP4
TP4 MTP
Speed Tests and Profiling
All following profile and testing were run on TP2 without MTP.
E2E
Before
After
prefill indexer + sparse gqa
before
indexer



others
gqa
after
indexer

data prepare+other


gqa(union+sparse)
decode indexer
before
after
Checklist
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ci