Skip to content

[AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode - #40

Merged
apinge merged 2 commits into
apinge:qwen38-flash-next-amd-current-fix-installfrom
madhang:perf/qsa-sparse-paged-gqa-mi308x-pr
Oct 12, 2026
Merged

apinge merged 2 commits into
apinge:qwen38-flash-next-amd-current-fix-installfrom
madhang:perf/qsa-sparse-paged-gqa-mi308x-pr

Conversation

@madhang

@madhang madhang commented Sep 30, 2026 •

Copy link
Copy Markdown

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 remains legacy because the measurements include TTFT/tail regressions and an unresolved MTP GSM8K decrease.

Modifications

Technical details

  • Add a SGLang-local Triton paged GQA kernel adapted from ATOM commit b97551f1d03a47027d286a5846a63a888acad237, retaining MIT/AMD attribution and the upstream AITER credit. There is no ATOM dependency or AITER source change.
  • View SGLang [physical_token_slot, kv_head, head_dim] K/V as one-token pages. Use the real req_to_token_pool.req_to_token table 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.
  • Pass each query's visible sequence length, including flattened MTP verify rows. Mask future positions, invalid request/physical-slot indices, padded selections and ragged head subgroups; return zero for empty attention rows.
  • Size split-K using query-token count, not request count. Keep the source's three occupancy tiers, .cg K/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.
  • Reuse FP32 partial-output/max/sum workspace by device, shape, split count and stream; retain the buffers for graph replay. Use the already-installed AITER reduction helper.
  • Add explicit dispatch and compatibility checks for ROCm gfx942, BF16, head_dim 128/256 and supported GQA layouts. Unsupported layouts use legacy. Ordinary prefill and the default path are retained.
  • Add AMD CI-registered coverage for reference correctness, invalid and empty rows, strides, MTP metadata, real-table dispatch, fallback and graph replay with refreshed inputs/workspace.

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.

MTP Legacy PR2311 New − legacy
Off 1279/1319 (96.9674%) 1281/1319 (97.1190%) +2 questions, +0.1516 percentage points
On 1285/1319 (97.4223%) 1282/1319 (97.1948%) -3 questions, -0.2274 percentage points

Protocol: all 1,319 original GSM8K test questions; five examples from train IDs 0–4; model chat template with enable_thinking=False and add_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:

python3 /opt/qsa_pr2311_ab/20260930_step6_gsm8k/scripts/qsa_pr2311_step6_client.py \
  --output /opt/qsa_pr2311_ab/20260930_step6_gsm8k/legacy_nomtp/full \
  --split test --parallel 16

python3 /opt/qsa_pr2311_ab/20260930_step6_gsm8k/scripts/qsa_pr2311_step6_mtp_client.py \
  --output /opt/qsa_pr2311_ab/20260930_step6_gsm8k/legacy_mtp/full \
  --split test --parallel 16

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=64 and 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.02 for 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 -q

Speed 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.

MTP Concurrency QPS (req/s) Mean TTFT (ms) Mean TPOT (ms/token)
Off 1 0.1738 → 0.1965 (+13.063%) 1009.7754 → 1005.3395 (-0.439%) 13.5908 → 11.6987 (-13.922%)
Off 4 0.3807 → 0.4144 (+8.850%) 3714.2223 → 3569.8875 (-3.886%) 19.4632 → 17.4150 (-10.523%)
On 1 0.2484 → 0.2611 (+5.147%) 1077.7904 → 1078.3204 (+0.049%) 8.4460 → 7.8807 (-6.693%)
On 4 0.4654 → 0.4756 (+2.192%) 1560.5777 → 1769.7904 (+13.406%) 19.4265 → 18.3902 (-5.334%)

Observed regressions are retained:

  • MTP c4 mean TTFT +13.41% and P90 TTFT +44.27%; both PR2311 rounds were worse than both legacy rounds for these metrics. P95/P99 E2E also increased by about 0.94%/1.28%.
  • MTP c1 P99 TPOT +3.06%, P99 E2E +2.41%, P99 TTFT +0.79%; round directions were inconsistent.
  • Non-MTP c1 P95/P99 TTFT increased about 0.014%/0.442%. Additional tail/variability increases are recorded in the complete report.

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_IMPL between legacy and pr2311 across fresh services.

export PYTHONPATH="$PWD/python"
export HIP_VISIBLE_DEVICES=2,3
export CUDA_VISIBLE_DEVICES=2,3
export SGLANG_USE_AITER=1
export SGLANG_GR_READ_FLYDSL=1
export AITER_MOE_PADDING_SIZE=64
export SGLANG_QSA_SPARSE_IMPL=pr2311

sglang serve \
  --model-path /models/Qwen3.8-Flash-Next-PTPC-FP8 \
  --served-model-name Qwen/Qwen3.8-Flash-Next-PTPC-FP8 \
  --host 127.0.0.1 \
  --port 7081 \
  --tp-size 2 \
  --attention-backend aiter \
  --moe-runner-backend aiter \
  --kv-cache-dtype auto \
  --chunked-prefill-size 16384 \
  --watchdog-timeout 1200 \
  --disable-radix-cache \
  --mem-fraction-static 0.95 \
  --max-running-requests 32 \
  --cuda-graph-max-bs-decode 32 \
  --no-ple-offload-embedding \
  --random-seed 2311

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:

export HIP_VISIBLE_DEVICES=4,5
export CUDA_VISIBLE_DEVICES=4,5
export AITER_CONFIG_GEMM_BF16=/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/merged/bf16_tuned_gemm.csv
export AITER_OPUS_TUNED_CSV_GLOB=/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/qwen3_5_397b_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/minimax_m3_eagle_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/llama405B_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/qwen32B_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/kimik3_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/gptoss_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/glm47_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/dsv3_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/kimik2_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/dsv4_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/glm5_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/llama70B_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/qwen3_8b_bf16_tuned_gemm.csv:/opt/qsa_pr2311_ab/20260930_step5_mtp/frozen-config/kimi_bf16_tuned_gemm.csv

sglang serve \
  --model-path /models/Qwen3.8-Flash-Next-PTPC-FP8 \
  --served-model-name Qwen/Qwen3.8-Flash-Next-PTPC-FP8 \
  --host 127.0.0.1 \
  --port 7081 \
  --tp-size 2 \
  --attention-backend aiter \
  --moe-runner-backend aiter \
  --kv-cache-dtype auto \
  --chunked-prefill-size 16384 \
  --watchdog-timeout 1200 \
  --disable-radix-cache \
  --mem-fraction-static 0.95 \
  --max-running-requests 32 \
  --cuda-graph-max-bs-decode 32 \
  --no-ple-offload-embedding \
  --random-seed 2311 \
  --speculative-algorithm EAGLE \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4

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:

QSA_CONCURRENCY=1  # Repeat with 4.
python3 -m sglang.bench_serving \
  --backend sglang \
  --model /models/Qwen3.8-Flash-Next-PTPC-FP8 \
  --dataset-name random --host 127.0.0.1 --port 7081 \
  --num-prompts 32 --random-input 12000 --random-output 350 \
  --random-range-ratio 1.0 --max-concurrency "$QSA_CONCURRENCY"

The above expands the original run_pure_text_bench.sh with 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, Triton 3.7.0+amd.rocm7.2.0.git89002410, AITER 4752a40867fe71d42d3a2ff595d2450226b5d6ca, FlyDSL 0.3.2, transformers 5.12.1. MTP and GSM8K runs explicitly selected private copies of the original 15 BF16 tuning CSVs via AITER_CONFIG_GEMM_BF16 and AITER_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 hipGraphLaunch correlation IDs; stable decode steps were compared across both TP ranks. Times below sum 12 QSA layers per step and average ranks.

Measurement Legacy PR2311 Change
Complete sparse path, including preparation/reduction 2.290 ms 0.284 ms −87.58%
Full decode GPU graph 20.245 ms 18.199 ms −10.11%

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

  • Retain legacy as the default and provide an explicit opt-in/fallback.
  • Add AMD CI-registered kernel, metadata, fallback and graph tests.
  • Provide full-set GSM8K results with and without MTP, including regressions.
  • Provide c1/c4 performance and non-MTP profile results.
  • Pass Black, isort, configured Ruff rules, registered-test checks and diff checks on the final tree.
  • Document the switch and source attribution in code and provide a complete integration/test report.
  • Run remote CI and obtain maintainer review after publishing.

Base-branch compatibility

Prepared directly on apinge/sglang:qwen38-flash-next-amd-current-fix-install at c9ef753c67be67f4e6d284575f22483cfd9afe2c. The local commit's parent is exactly this HEAD. The exported patch passed git apply --check, and an independent checkout of the target HEAD successfully ran git merge --ff-only perf/qsa-sparse-paged-gqa-mi308x-pr with 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.

@apinge
apinge force-pushed the perf/qsa-sparse-paged-gqa-mi308x-pr branch 2 times, most recently from 9c004f1 to 9dfb8cc Compare September 30, 2026 10:43
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.
@apinge
apinge force-pushed the perf/qsa-sparse-paged-gqa-mi308x-pr branch from 9dfb8cc to 4b5faf7 Compare September 30, 2026 10:46

metadata = self._resolve_metadata(forward_batch)
topk_indices = topk_indices.to(torch.int32).contiguous()
if self._sparse_impl == "pr2311" and is_hip():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why using PR id to trigger the attention path ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@madhang madhang changed the title [AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode [AMD] Enable automatic QSA paged GQA dispatch Oct 9, 2026
@madhang madhang changed the title [AMD] Enable automatic QSA paged GQA dispatch [AMD] Add opt-in paged GQA sparse attention for Qwen3.8 decode Oct 9, 2026
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]>
@madhang
madhang force-pushed the perf/qsa-sparse-paged-gqa-mi308x-pr branch from 57da161 to 5be1aac Compare October 9, 2026 15:40
@yicyang
yicyang requested a balanced review from Copilot October 10, 2026 02:25

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can remove the condition of device check?

@apinge apinge Oct 12, 2026 •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the condition q.shape[1] // k_cache.shape[1] <= 32 is unnecessary. I will add another pr to update it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sense. It's not necessary.

@apinge
apinge merged commit ebc1afd into apinge:qwen38-flash-next-amd-current-fix-install Oct 12, 2026
77 of 88 checks passed
sammysun0711 pushed a commit that referenced this pull request Nov 9, 2026
* [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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants