Skip to content

[Perf] [AMD] qsa: Select blocks with the exact topk_v2 on gfx95 - #50871

Draft
eppaneamd wants to merge 7 commits into
sgl-project:mainfrom
eppaneamd:rocm-qsa-prefill-topk
Draft

eppaneamd wants to merge 7 commits into
sgl-project:mainfrom
eppaneamd:rocm-qsa-prefill-topk

Conversation

@eppaneamd

@eppaneamd eppaneamd commented Nov 17, 2026 •

Copy link
Copy Markdown

Motivation

QSA's block selection picks each row's 512 blocks with fast_topk, which stages at most 4,096 members of a row's threshold bin and drops the rest, so a row with more drops members of its true top 512 (#36807 reports the same overflow in fast_topk_v2). On unpatched main, four rows of 8,192 scores in one threshold bin leave 239 to 263 of each row's 512 selected scores below the true 512th largest in two runs (fast_topk against torch.topk; repro in the details).

This PR picks the blocks on gfx95 with topk_v2 (#47960), which is exact in its default mode, for extend and for decode, target-verify and draft-extend batches. In extend, topk_v2 reads only the order of the scores, so they stay unscaled and the division pass goes away.

On one MI355X, one layer's selection takes 24.6 % less time for a 16,384-token extend chunk on an 83,968-token prefix, and 57.8 % less for a verify step of 60 requests (0.50 ms per decode step).

Most of the extend gain is the division pass, which #48274 removes too; topk_v2 alone saves 4.6 % to 11.0 %.

Related work:

Modifications

  • qsa_indexer.py, select_prefill_tokens, on gfx95 when the request-relative TileLang scoring runs:
    • each row chunk's blocks come from topk_transform_ragged_v2 instead of qsa_fast_topk;
    • the scores come back unscaled (score_scale=1.0);
    • the logits width rounds up to a multiple of 4, the row stride topk_v2's 16-byte loads need;
    • in batch-invariant mode topk_v2 runs deterministic: ties go to the smallest block indices, as qsa_fast_topk breaks them with FlashInfer on CUDA.
  • qsa_indexer.py, select_decode_tokens, on gfx95:
    • the blocks come from topk_transform_paged_v2 without a page table (it writes raw block indices and leaves the scores unmodified) instead of fast_topk;
    • a logits row stride that is not a multiple of 4 keeps fast_topk.
  • mqa.py, tilelang_qsa_mqa_prefill_relative: a score_scale of 1 skips the division.

Scope:

  • extend, decode, target-verify and draft-extend batches of QSA models (qwen4_exp.py) on gfx95;
  • unchanged: other platforms, batch-invariant decode and a block_topk other than 512, which keep their paths in select_decode_tokens;
  • measured on MI355X (gfx950) at the indexer geometry of amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8; GSM8K served with that checkpoint.

Assumptions:

  • A logits row width (stride) that is not a multiple of 4, possible with [Perf] [AMD] qsa: Score decode rows with a grouped Triton kernel on ROCm #50702's unpadded scorer, keeps fast_topk, so that path is unchanged.
  • topk_v2's split path (a batch of at most 16 rows with a long one) keeps one scratch buffer per device, which each launch leaves clean for the next, so two selections must not overlap on one device.
    • No serving mode that overlaps two QSA selections was found: the indexer's second stream (SGLANG_ALT_STREAM=1 on ROCm, in decode graph capture) is joined before each layer's attention; the other modes are in the details.
    • This is from reading the code; no concurrent run was made.

Accuracy Tests

  • This changes gfx95's default selection without a flag. The GSM8K run below checks the new launches end to end, not the selection's exactness:
    • 13 (main) and 14 (this PR) of its 1,319 requests reach 2,052 tokens, the length from which a decode row has more than 512 blocks and its selection stops taking every block;
    • none comes near 4,096 blocks, above which fast_topk can drop members of the top 512 (the longest request is 6,520 tokens).
  • The selection is an exact top 512 in topk_v2's default mode (SGLANG_TOPK_V2_MODE=1). On the benchmark's random scores:
    • decode: in every row longer than 512 blocks, both selections pick a top 512 (checked against torch.topk), and no row's block set differs between them;
    • extend: the two selections differ in 0, 117, 1 and 0 rows of a call, in the order of the extend table below. In an earlier run on the previous image (…-20261115), each of the 120 differing rows of a call was checked against torch.topk:
      • 119 tie at the 512th score (both sets are a top 512 of the scores they rank);
      • in 1, dividing by sqrt(head_dim) merged two distinct scores at the 512th place, so today's set is a top 512 of the divided scores only and this PR's of the undivided ones.
  • New tests in test_qsa_select_rocm.py (MI35x suite), through select_prefill_tokens and select_decode_tokens; the exactness tests fail on main, and the two fast_topk guards (off gfx95, a row stride not a multiple of 4) are checked by mutation (cases and mutations in the details below).
  • On the image below, the QSA test files fail the same tests with and without this PR (20 in test_qsa_indexer, 3 in test_qsa_determinism). Each of ten mutations of the change fails a named test; an eleventh, keeping the division, selects the same blocks and passes.

GSM8K, all 1,319 questions, amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 at TP1 with MTP on one MI355X, on lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117, the same server for both:

Code Strict Flexible n
main (372b35034d, the merge base) 97.19 % (1,282) 96.59 % (1,274) 1,319
This PR (1fbe3b8b2e) 97.19 % (1,282) 96.21 % (1,269) 1,319
  • The runs differ in 12 strict verdicts, 6 each way (exact McNemar p = 1.0), and in 33 flexible ones, 19 correct only on main and 14 only with this PR (p = 0.49). Two runs of the same kernels on this image differ as much: 12 strict verdicts, and 16 of 1,319 responses are word for word the same.
  • With this PR, every extend selection called topk_v2's ragged entry point (7,319 calls) and the captured decode graphs its paged entry point, and nothing called fast_topk; on main, fast_topk ran in both. Every logged decode batch replayed captured graphs.
GSM8K setup
  • Image lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117 (sha256:09b8237296024285e6286ffb54d75c3af6d59342bbbb3558dea56bed86798814, SGLang c67db7c762), one MI355X. Each commit's python/sglang copied over the image's editable install (/sgl-workspace/sglang/python/sglang); the sha256 of every file checked against the commit. The two trees differ only in qsa_indexer.py and mqa.py.
  • Checkpoint amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8, revision bd6e49d9abfe0ce1da53a45593daaee83580035b.
  • Server, both runs:
SGLANG_USE_AITER=1 SGLANG_USE_AITER_UNIFIED_ATTN=1 SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION=1 AITER_GDR_FLYDSL=1 \
ROCM_QUICK_REDUCE_QUANTIZATION=NONE SGLANG_TIMEOUT_KEEP_ALIVE=1800 PYTHONNOUSERSITE=1 \
python3 -m sglang.launch_server --model-path amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 \
  --revision bd6e49d9abfe0ce1da53a45593daaee83580035b \
  --served-model-name amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 \
  --tokenizer-path amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 --trust-remote-code \
  --host 127.0.0.1 --port 30000 --tensor-parallel-size 1 --data-parallel-size 1 --expert-parallel-size 1 \
  --quantization quark --attention-backend aiter --page-size 64 --kv-cache-dtype fp8_e4m3 \
  --mem-fraction-static 0.88 --model-loader-extra-config '{"enable_multithread_load": true}' \
  --chunked-prefill-size 16384 --cuda-graph-backend-prefill breakable \
  --max-running-requests 64 --cuda-graph-max-bs-decode 64 \
  --mamba-ssm-dtype bfloat16 --mamba-radix-cache-strategy extra_buffer_lazy \
  --mamba-track-interval 262144 --max-mamba-cache-size 960 \
  --ple-offload-embedding --json-model-override-args '{"text_config": {"ple_embedding_dtype": "float8_e4m3fn"}}' \
  --speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 --speculative-draft-kv-cache-dtype fp8_e4m3 --enable-linear-replayssm-spec \
  --reasoning-parser qwen3 --default-chat-template-kwargs '{"enable_thinking": false}' \
  --tool-call-parser qwen3_coder --scheduler-recv-interval 10 --stream-interval 50 --tokenizer-worker-num 6 \
  --enable-metrics --enable-cache-report --watchdog-timeout 1200
  • Client: sgl-eval 0.1.3, the GSM8K evaluator of the contribution guide (zero-shot, greedy):
sgl-eval run gsm8k --base-url http://127.0.0.1:30000/v1 --num-examples 1319 --num-threads 64 \
  --chat-template-kwarg enable_thinking=false
  • Strict: sgl-eval's score, the last \boxed{} answer checked against the reference. Flexible: the last number in the response equals the reference (lm-evaluation-harness's GSM8K flexible-extract regex).
  • Request lengths: prompt tokens from the checkpoint's chat template (they sum to the client's 126,917) plus the generated tokens the client recorded.
  • Path: wrappers loaded only in the test harness counted the calls of _exact_block_topk, _exact_decode_block_topk, qsa_fast_topk and fast_topk, during CUDA graph capture and outside it. The extend selection runs outside the captured graph segments, so its calls are counted as served; a replayed decode graph runs no Python, so served decode batches are counted from the server log's batch lines (cuda graph: True).

Speed Tests and Profiling

  • Served end-to-end throughput has not been measured yet.
  • Decode gains with the rows' length: a step of 60 requests under 2,000 tokens, where no row has more than 512 blocks, saves 0.03 ms (−16.6 % per call).
  • The first call builds topk_v2's JIT module, which the extend selection builds too: 9.0 s with an empty cache against 2.2 s for fast_topk's (8 rows of 40,000 scores).

One layer's extend selection (select_prefill_tokens, all row chunks), median µs on one MI355X:

Rows on cached tokens (keys) Today topk_v2, divided scores This PR Change, topk_v2 alone Change, total
16,384 on 83,968 (25,088) 3,467.9 3,090.2 2,617.2 −11.0 % −24.6 %
16,384 on 0 (4,096) 613.8 584.6 491.4 −4.6 % −20.0 %
4,096 on 96,256 (25,088) 964.2 859.6 738.7 −10.8 % −23.3 %
16,384 on 83,973 (25,089) 3,519.8 3,155.0 2,670.1 −10.4 % −24.0 %

One layer's decode selection (select_decode_tokens, 4 verify rows a request, CUDA graph), median µs:

Requests (rows) Mean context (tokens) Today This PR Change Saved per decode step
2 (8) 115,164 39.08 22.56 −41.8 % 0.21 ms
7 (28) 80,420 35.36 17.48 −50.4 % 0.23 ms
45 in a 48-request graph (192) 128,210 64.04 26.32 −58.8 % 0.49 ms
60 (240) 124,838 66.40 27.96 −57.8 % 0.50 ms
60 under 2,000 tokens (240) 1,171 12.32 10.28 −16.6 % 0.03 ms

A decode step selects 13 times: once for each of the 12 full-attention layers of amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 in the verify pass and once for its MTP layer in the draft-extend pass. The last column is 13 times the saving per call, with the draft-extend call timed at the verify shape.

The percentages are medians of the per-repetition ratios. This PR's arm, timed twice in the same loop, lies within −0.2 % to +0.2 % of itself (A/A) in extend and −1.2 % to +1.0 % in decode.

Repro, single-stream check, setup, method, tests and mutations

Repro on unpatched main (lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117, SGLang c67db7c762, one MI355X). The scores lie in [100, 101), one threshold bin of fast_topk, which stages at most 4,096 of its members:

import torch
from sglang.kernels.ops.attention.fast_topk import fast_topk

torch.manual_seed(0)
rows, keys, k = 4, 8192, 512
scores = 100 + torch.rand(rows, keys, device="cuda")  # all in one threshold bin
lengths = torch.full((rows,), keys, dtype=torch.int32, device="cuda")
picked = scores.gather(1, fast_topk(scores, lengths, topk=k, row_starts=None).long())
cut = torch.topk(scores, k).values[:, -1:]  # the 512th largest score
print("selected scores below the 512th largest, per row:", (picked < cut).sum(1).tolist())
selected scores below the 512th largest, per row: [248, 242, 261, 253]

A second run printed [250, 239, 263, 253]; the counts vary a little between runs. The same input through topk_transform_paged_v2, the call this PR makes (also on main), selects no score below the cut:

# The same input through topk_v2's paged entry point, as the change calls it (also on main).
import torch
from sglang.kernels.ops.attention.dsv4.topk import plan_topk_v2, topk_transform_paged_v2

torch.manual_seed(0)
rows, keys, k = 4, 8192, 512
scores = 100 + torch.rand(rows, keys, device="cuda")
lengths = torch.full((rows,), keys, dtype=torch.int32, device="cuda")
out = scores.new_empty((rows, k), dtype=torch.int32)
topk_transform_paged_v2(scores, lengths, None, out, 1, plan_topk_v2(lengths))
picked = scores.gather(1, out.long())
cut = torch.topk(scores, k).values[:, -1:]
print("topk_v2: selected scores below the 512th largest, per row:", (picked < cut).sum(1).tolist())
topk_v2: selected scores below the 512th largest, per row: [0, 0, 0, 0]

Single-stream check of topk_v2's split scratch, from reading the code on this branch (nothing was run concurrently):

  • The selection is called only by QSAIndexer.select_prefill_tokens and select_decode_tokens, from QSAIndexer._forward_impl; the prefill (ragged) entry point does not use the scratch.

  • Qwen4ExpAttentionDecoderLayer.self_attention runs the indexer on alt_stream only while a decode graph is captured, for fewer than 1,024 tokens, and on ROCm only when SGLANG_ALT_STREAM=1 creates the stream. The main stream's work meanwhile (_prepare_qkv_gate) does not select, the layer joins the alt stream before attention, and the next layer forks from the joined stream, so selections run one after another.

  • The speculative worker's plan_stream runs prepare_for_draft_extend (metadata); the draft extend runs on the main stream.

  • Qwen4 PLE models, the checkpoint above included, raise NotImplementedError under two-batch overlap, and batch_overlap/ creates no stream.

  • python/sglang/srt has no prefill/decode multiplexing mode (no pdmux or green-context code); disaggregated prefill and decode are separate servers, each with its own scratch.

  • Image: lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117 (SGLang c67db7c762), with this branch's files applied (each file's sha256 checked against the branch).

  • torch 2.11.0+rocm10.0.0, Triton 3.8.0, one MI355X (gfx950).

  • Benchmark (test/manual/kernels/attention/bench_qsa_select.py):

    • extend: one request of Gaussian, RMS-normed Q and K at the indexer geometry (4 heads, head dim 128, compress ratio 4, 512 blocks); every arm calls select_prefill_tokens: today (the branch other platforms take), topk_v2 with divided scores, this PR, and this PR again (A/A);
    • decode: 4 rows a request (a target-verify step) over random contexts (2 requests: 70,000 to 130,000 tokens; 7: 4,000 to 130,000; 45 and 60: 4,000 to 252,000; 60 short: 400 to 2,000), padded with empty requests to the graph's batch size, over a page table of 4,096 pages of 16 compressed keys (a 262,144-token limit); the scorer runs in its own graph before each timed call, and each arm is select_decode_tokens captured in a CUDA graph: today, this PR, this PR again (A/A), and this PR with the extend entry point (topk_transform_ragged_v2) on the same rows, which is 4 % to 26 % slower than the paged one;
    • a 512 MB write before every call (cold L2), CUDA events around the call, arms interleaved with a rotating start, 31 repetitions;
    • kernels per call recorded per arm; the run fails if an arm launches another arm's top-k, or the division where it should not.
python test/manual/kernels/attention/bench_qsa_select.py --out bench.json
python -m pytest test/registered/kernels/ops/attention/qsa/test_qsa_select_rocm.py

New tests in test_qsa_select_rocm.py:

  • extend: scores in one narrow band, so a row's threshold bin holds about 8,190 members: every row selects exactly its top 512, at 8,192 keys and at 8,190 (a width not a multiple of 4);
  • extend, batch-invariant mode: every score tied, every row selects blocks 0-511;
  • decode: the same narrow band, 4 verify rows of 8,189 to 8,192 keys, with rows of 0, 1, 300, 512 and 513 keys in the batch;
  • decode, CUDA graph capture and replay at 16 and 256 rows: clustered scores, rows from 0 to 65,536 keys, exact results from every replay;
  • guards: fast_topk still runs off gfx95 and on a row stride that is not a multiple of 4.
Mutation Failing test
decode: gfx95 gate dropped (topk_v2 on every platform) test_select_decode_tokens_keeps_fast_topk[not_gfx95]
decode: stride check dropped test_select_decode_tokens_keeps_fast_topk[row_stride_not_a_multiple_of_4]
decode: the logits width passed as every row's length test_select_decode_tokens_exact_on_narrow_band_scores
decode: host synchronization inside the selection test_select_decode_tokens_exact_under_graph_replay (capture fails)
extend: gfx95 back on fast_topk test_select_prefill_tokens_exact_on_narrow_band_scores
extend: batch-invariant mode not passed to topk_v2 test_select_prefill_tokens_ties_go_to_the_smallest_blocks_when_batch_invariant
extend: logits width not rounded up to a multiple of 4 test_select_prefill_tokens_exact_on_narrow_band_scores[8190]
extend: topk_v2 reads past each row's length test_select_prefill_tokens_exact_on_narrow_band_scores
extend: score scale negative (order reversed) test_select_prefill_tokens_exact_on_narrow_band_scores
extend: selected block ids offset by one test_select_prefill_tokens_exact_on_narrow_band_scores
extend: division kept (the same blocks, slower) passes, as expected

Checklist

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ⊘ Skipped -- the PR is a draft; marking it ready starts a new run (AMD: then /rerun-failed-ci).
Latest PR Test (Extra): ⊘ Skipped -- the PR is a draft; marking it ready starts a new run (AMD: then /rerun-failed-ci).
Latest PR Test (AMD ROCm 10): ⚠️ Run #46307622199

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

On gfx95, select_prefill_tokens picks each row chunk's blocks with
topk_v2's ragged entry point instead of fast_topk, which drops members of
an overfull threshold bin (sgl-project#36807). topk_v2 reads only the order of the
scores, so they skip the division by sqrt(head_dim); the logits width
rounds up to the multiple of 4 that topk_v2's loads need. In
batch-invariant mode topk_v2 runs deterministic, giving ties to the
smallest block indices.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
@github-actions github-actions Bot added the amd label Nov 17, 2026
eppaneamd and others added 3 commits November 17, 2026 11:33
The one conflict is the sglang.srt.utils import in qsa_indexer.py: main
added is_npu and the _is_npu constant, this branch added
is_gfx95_supported. Both are kept.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
On gfx95, select_decode_tokens (decode, target-verify and draft-extend
batches) picks each row's blocks with topk_v2's paged entry point, without
a page table, instead of fast_topk, which drops members of an overfull
threshold bin (sgl-project#36807). topk_v2 needs the logits row stride to be a
multiple of 4 for its 16-byte loads; rows with another stride keep
fast_topk. The prefill test and benchmark now cover decode as well and are
renamed to test_qsa_select_rocm.py and bench_qsa_select.py.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
select_decode_tokens leaves the scores of rows that fit k unwritten, which
topk_v2's trivial path, like fast_topk's, never reads. Comment only; no code
change.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
@eppaneamd eppaneamd changed the title [Perf] [AMD] qsa: Select prefill blocks with the exact topk_v2 on gfx95 [Perf] [AMD] qsa: Select blocks with the exact topk_v2 on gfx95 Nov 17, 2026
eppaneamd and others added 2 commits November 17, 2026 22:25
main renamed the CI stages (sgl-project#50874); a test registered under stage-b now
maps to a suite no workflow runs.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
eppaneamd added a commit to eppaneamd/InferenceX that referenced this pull request Nov 18, 2026
Patches 16, 21 and 24 add opt-in kernels, each off unless the recipe sets its SGLANG_AMD_*
variable; c12, c24, c48 and c80 set all eight:
- 16 QSA indexer prefill blocks selected by the exact topk_v2, one pipeline stage on gfx95
  (sgl-project/sglang#50871, #51263)
- 21 QSA decode, verify and draft-extend blocks selected by the exact topk_v2, draft-extend
  rows scored grouped as in verify (sgl-project/sglang#50871, #51242)
- 24 GDN ReplaySSM verify and commit kernels (sgl-project/sglang#51180)

Co-authored-by: Claude <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
maeehart pushed a commit to SemiAnalysisAI/InferenceX that referenced this pull request Nov 24, 2026
…draft head at its shipped precision

Patches 11-16, 21 and 24 add opt-in kernels, each off unless the recipe sets its SGLANG_AMD_*
variable; c12, c24, c48 and c80 set all eight:
- 11 grouped QSA verify scoring (sgl-project/sglang#48625, carries #46631)
- 12-13 FlyDSL QSA sparse prefill (ROCm/aiter#7556 kernels in the image's AITER checkout,
  sgl-project/sglang#51179 wiring)
- 14 MXFP4 MoE intermediate kept 128-aligned at TP 1 (sgl-project/sglang#49852)
- 15 Triton HC prefill path (sgl-project/sglang#50863)
- 16 QSA indexer prefill blocks selected by the exact topk_v2, one pipeline stage on gfx95
  (sgl-project/sglang#50871, #51263)
- 21 QSA decode, verify and draft-extend blocks selected by the exact topk_v2, draft-extend
  rows scored grouped as in verify (sgl-project/sglang#50871, #51242)
- 24 GDN ReplaySSM verify and commit kernels (sgl-project/sglang#51180)

c1 and c2 set SGLANG_AMD_MONO_QWEN38_DRAFT_HEAD_FP8=0, and the recipe drops
default-chat-template-kwargs so the server serves the chat template's default thinking mode.
The setup script uses set -eo pipefail (AGENTS.md Bash: no nounset).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
Signed-off-by: Rony Leppänen <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant