Repository navigation
[AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode - #40
Conversation
9c004f1 to
9dfb8cc
Compare
Adapt the paged sparse GQA kernel and token-based split-K scheduling from ROCm/ATOM#2311 to SGLang token-slot caches and MTP query metadata. Keep legacy as the default and provide an explicit pr2311 opt-in with compatibility fallback. Add gfx942 correctness, masking, layout, dispatch and graph-replay coverage. No ATOM dependency or AITER source change.
9dfb8cc to
4b5faf7
Compare
|
|
||
| metadata = self._resolve_metadata(forward_batch) | ||
| topk_indices = topk_indices.to(torch.int32).contiguous() | ||
| if self._sparse_impl == "pr2311" and is_hip(): |
There was a problem hiding this comment.
Why using PR id to trigger the attention path ?
There was a problem hiding this comment.
The PR replaces QSA attention with _qsa_sparse_paged_gqa_kernel. Not sure if there are better QSA attention implementations.
If this PR can be merged, I'll remove this condition.
Remove SGLANG_QSA_SPARSE_IMPL and automatically select direct paged GQA for compatible gfx942 BF16 QSA decode and MTP verification inputs. Retain HIP-only lazy imports and compatibility fallback. The attention kernel, split-K scheduling, and reduction code are unchanged. Validate TP2 on MI308X with MTP off/on at concurrency 1, 4, and 32, including mixed lengths, logprobs, and traces on both TP ranks. All 117 kernel/regression tests and eight validation checks pass. Across 16 formal performance runs (512 requests), QPS differs by less than 0.33% from the original manually enabled implementation rerun under matched conditions. MTP c4 mean TTFT decreases 12.740%, while mean TPOT increases 2.961%; this is not an across-the-board latency improvement. GSM8K scores are 1279/1319 without MTP and 1280/1319 with MTP, each one question below the corresponding current legacy control (-0.0758 pp). All 5276 evaluation requests succeed. Against the historical PR40 manually enabled runs, each new score is two questions lower; those cross-date comparisons do not isolate the effect of automatic dispatch. Signed-off-by: madhang <[email protected]>
57da161 to
5be1aac
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The experimental path is dispatched by default because the documented opt-in selector is neither defined nor checked.
1 open finding
What changed in this PR
Adds an intended opt-in ROCm paged GQA sparse-attention path for faster Qwen3.8 decode.
Changes:
- Adds a gfx942 BF16 Triton paged GQA kernel with split-K reduction.
- Integrates direct token-slot dispatch and workspace reuse.
- Adds AMD correctness, fallback, MTP, and graph-replay coverage.
| File | Description |
|---|---|
qwen_sparse_attn_backend.py |
Integrates paged GQA dispatch. |
qsa/sparse_attn_decode.py |
Implements the Triton kernel and reduction wrapper. |
test_qsa_sparse_paged_gqa.py |
Adds AMD kernel and dispatch tests. |
test_qsa.py |
Verifies non-HIP import behavior. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
|
||
| metadata = self._resolve_metadata(forward_batch) | ||
| topk_indices = topk_indices.to(torch.int32).contiguous() | ||
| if is_hip(): |
| and q.shape[1] > 0 | ||
| and q.shape[1] % k_cache.shape[1] == 0 | ||
| and q.shape[1] // k_cache.shape[1] <= 32 | ||
| and _device_info(q.device)[0] == "gfx942" |
There was a problem hiding this comment.
Maybe we can remove the condition of device check?
There was a problem hiding this comment.
I think the condition q.shape[1] // k_cache.shape[1] <= 32 is unnecessary. I will add another pr to update it.
There was a problem hiding this comment.
Make sense. It's not necessary.
ebc1afd
into
apinge:qwen38-flash-next-amd-current-fix-install
* [AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode (#40) * [AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode Adapt the paged sparse GQA kernel and token-based split-K scheduling from ROCm/ATOM#2311 to SGLang token-slot caches and MTP query metadata. Keep legacy as the default and provide an explicit pr2311 opt-in with compatibility fallback. Add gfx942 correctness, masking, layout, dispatch and graph-replay coverage. No ATOM dependency or AITER source change. * [AMD] Enable automatic QSA paged GQA dispatch Remove SGLANG_QSA_SPARSE_IMPL and automatically select direct paged GQA for compatible gfx942 BF16 QSA decode and MTP verification inputs. Retain HIP-only lazy imports and compatibility fallback. The attention kernel, split-K scheduling, and reduction code are unchanged. Validate TP2 on MI308X with MTP off/on at concurrency 1, 4, and 32, including mixed lengths, logprobs, and traces on both TP ranks. All 117 kernel/regression tests and eight validation checks pass. Across 16 formal performance runs (512 requests), QPS differs by less than 0.33% from the original manually enabled implementation rerun under matched conditions. MTP c4 mean TTFT decreases 12.740%, while mean TPOT increases 2.961%; this is not an across-the-board latency improvement. GSM8K scores are 1279/1319 without MTP and 1280/1319 with MTP, each one question below the corresponding current legacy control (-0.0758 pp). All 5276 evaluation requests succeed. Against the historical PR40 manually enabled runs, each new score is two questions lower; those cross-date comparisons do not isolate the effect of automatic dispatch. Signed-off-by: madhang <[email protected]> --------- Signed-off-by: madhang <[email protected]> Co-authored-by: root <root> (cherry picked from commit ebc1afd) * test(qsa): place paged decode tests in the attention kernel suite --------- Signed-off-by: madhang <[email protected]> Co-authored-by: madhang <[email protected]>

Motivation
Qwen sparse decode currently gathers selected K/V into a compact buffer before running attention. On the tested Qwen3.8-Flash-Next TP2 workload, the complete sparse-attention path takes 2.290 ms per decode step across 12 QSA layers.
ROCm/ATOM#2311 improves paged sparse GQA through token-based split-K sizing and launch configurations adapted to grid occupancy. This PR adapts that kernel and scheduling to SGLang so decode and MTP verification can load selected K/V directly from token-slot caches.
The new path is opt-in:
SGLANG_QSA_SPARSE_IMPL=pr2311. The default remainslegacybecause the measurements include TTFT/tail regressions and an unresolved MTP GSM8K decrease.Modifications
Technical details
b97551f1d03a47027d286a5846a63a888acad237, retaining MIT/AMD attribution and the upstream AITER credit. There is no ATOM dependency or AITER source change.[physical_token_slot, kv_head, head_dim]K/V as one-token pages. Use the realreq_to_token_pool.req_to_tokentable and per-query request-pool rows; CUDA-graph dummy tables are not used. This view does not change the server's allocator page-size setting..cgK/V loads, empty-partition early return and head subgroups for large GQA groups. TP2 has 12 Q heads per KV head and does not need head subgroup splitting.Only four files change (786 insertions). The implementation is identical to the version used for the measurements below.
Accuracy Tests
Environment: Qwen3.8-Flash-Next-PTPC-FP8, TP2 on MI308X/gfx942. Each row compares the two sparse-attention implementations within the same MTP mode.
Protocol: all 1,319 original GSM8K test questions; five examples from train IDs 0–4; model chat template with
enable_thinking=Falseandadd_generation_prompt=True; temperature 0, top_p 1, sampling seed 2311, max_new_tokens 4096, normal EOS, client concurrency 16. No test answers are used as few-shot examples. All 5,276 requests succeeded; truncations remain in the denominator.Primary scoring extracts the last signed numeric answer after
####, falling back to the last signed number, then compares normalized Decimal values. The original unsigned-integer and strict-####scores are also retained. Every first-pass correctness-discordant item has the same judgment under primary and original scoring, so the A/B delta is not caused by that scoring change.Without MTP, 5 questions changed correct→wrong and 7 wrong→correct. With MTP, 8 changed correct→wrong and 5 wrong→correct. The observed MTP decrease is 3 questions / 0.2274 percentage points; this is not an accuracy-equivalence claim.
Two repeats of the selected discordant subsets showed within-implementation correctness variation: non-MTP legacy 10/12 and 7/12, PR2311 6/12 and 8/12; MTP legacy 5/13 and 8/13, PR2311 5/13 and 6/13. These subsets have different batch composition and do not replace the full-set scores. The cause remains unresolved; no second full-set A/B or pre-agreed non-inferiority margin is available.
The benchmark container used a frozen standalone client because the old evaluation entrypoint had a stale tokenizer/port, test-answer few-shot leakage and unsigned answer parsing. Example full-set invocations:
These are recorded benchmark-environment paths, not new package entrypoints. The controlled launcher supplies the matching state file, mode and port (7081 without MTP; 7082 with MTP). The PR2311 runs use the same clients/protocol with the implementation switched and separate output labels. Reproduction requires a fresh output root; the complete report records all server/client commands and the frozen protocol hash.
Run the following validation from the prepared checkout in the frozen ROCm environment. The final run also used
SGLANG_USE_AITER=1,AITER_MOE_PADDING_SIZE=64and the step-6 private tuning environment recorded in the complete report. Select an available device before reproducing.Kernel validation against an FP32 reference uses
atol=0.003, rtol=0.02for BF16 scaling/probability/output rounding. The new suite passed 39 tests on each of two GPUs; existing QSA/MTP/addressing regressions passed 67 tests. On the final PR tree, the combined suites were rerun: 106 passed.HIP_VISIBLE_DEVICES=4 CUDA_VISIBLE_DEVICES=4 PYTHONPATH="$PWD/python" \ python3 -m pytest \ test/registered/kernels/test_qsa_sparse_paged_gqa.py \ test/registered/kernels/test_qsa.py \ test/registered/kernels/test_qsa_mtp_shared_indexer.py \ test/registered/unit/mem_cache/test_qsa_compressed_addressing.py -qSpeed Tests and Profiling
Test results
MI308X (gfx942, 80 CU) ×2, TP2, Qwen3.8-Flash-Next-PTPC-FP8. Each configuration uses 32 requests, 12,000 input / 350 output tokens, random-range-ratio 1.0, seed 42, temperature 0, ignore_eos enabled and profiler off. Server seed 2311, chunked prefill 16384, max running requests 32, decode graph max batch 32, radix cache disabled and GR-read FlyDSL enabled.
MTP uses EAGLE, 3 speculative steps, topk 1, 4 draft tokens. These are legacy-versus-PR2311 comparisons within each MTP mode; the two modes were measured on different days/device pairs and are not a controlled measurement of the benefit of turning MTP on.
Values are legacy → PR2311 (relative change), averaged over both formal runs per configuration. QPS is higher-is-better; TTFT and TPOT are lower-is-better.
Observed regressions are retained:
The MTP TTFT cause has not been isolated. The throughput and mean-TPOT improvements do not establish an improvement in every metric. Higher-concurrency end-to-end tests (8/16/32) have not been run.
Both modes used A1→B1→B2→A2 order and separate c1/c4 warmups; c1/c4 order alternated by round. Non-MTP B1/B2 shared one service, retaining the script’s one-request warmup before every client run; MTP used four independent service launches. There were 256 successful formal requests per mode. Reported percentile summaries average per-round percentiles; they are not pooled request percentiles.
Server and client commands
Run from the selected SGLang checkout; use an available GPU pair. The example below is the non-MTP setup; switch
SGLANG_QSA_SPARSE_IMPLbetweenlegacyandpr2311across fresh services.For the recorded MTP performance setup, retain the common exports above and use this complete server command in a fresh service. GPU4/5 were the historical pair; check availability first. The tuning exports select the frozen step-5 inputs before startup:
Omit speculative flags to disable MTP; do not pass the string
NONE. The requested mem fraction is 0.95; the server's effective value was 0.8075.Client, run once at each concurrency with the same service configuration:
The above expands the original
run_pure_text_bench.shwith explicit port/concurrency overrides. Each fresh service also receives 4-request warmups at c1 and c4 before the formal rounds. These are recorded container commands; use fresh log/output directories. To reproduce the earlier non-MTP setup in the current shared environment, select the same frozen tuning inputs before startup as well, since the shared directory subsequently gained an additional CSV.Dependencies: torch
2.12.0+rocm7.2.4.gitcf5ea6e.post2, Triton3.7.0+amd.rocm7.2.0.git89002410, AITER4752a40867fe71d42d3a2ff595d2450226b5d6ca, FlyDSL0.3.2, transformers5.12.1. MTP and GSM8K runs explicitly selected private copies of the original 15 BF16 tuning CSVs viaAITER_CONFIG_GEMM_BF16andAITER_OPUS_TUNED_CSV_GLOB, excluding a later untracked shared tuning CSV. The complete report includes these exact environment values.Non-MTP profile4
Original profile4: c4, 12 requests, 12,000 input / 5 output tokens. Graph kernels were matched through
hipGraphLaunchcorrelation IDs; stable decode steps were compared across both TP ranks. Times below sum 12 QSA layers per step and average ranks.The new path includes its split-K reduction. The baseline includes its K/V preparation/compaction. These are SGLang before/after measurements, not ATOM's original tuning numbers. KV-store time increased 11.82% and one TP1 MoE kernel increased 2.71%; these increases are included in the full-graph result. Profiled client timing includes trace export and is not used for the end-to-end table. No MTP trace was collected.
Checklist
Base-branch compatibility
Prepared directly on
apinge/sglang:qwen38-flash-next-amd-current-fix-installatc9ef753c67be67f4e6d284575f22483cfd9afe2c. The local commit's parent is exactly this HEAD. The exported patch passedgit apply --check, and an independent checkout of the target HEAD successfully rangit merge --ff-only perf/qsa-sparse-paged-gqa-mi308x-prwith an identical final tree. The final source hashes match those used for the historical performance and accuracy runs.This records conflict-free compatibility with the target as checked at
2026-09-30T08:20:05.676798+00:00; remote CI and review are pending. The default remains legacy while the MTP TTFT and accuracy differences are investigated.