Skip to content

feat(topk): fuse the DSA page-table transform into a cooperative top-k - #5

Merged
xiaobochen-amd merged 1 commit into
mainfrom
topk-transform-main
Aug 28, 2026
Merged

xiaobochen-amd merged 1 commit into
mainfrom
topk-transform-main

Conversation

@jiejingzhangamd

@jiejingzhangamd jiejingzhangamd commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

What

Adds dsa_topk_transform: the DSA indexer's per-row top-k and its page-table transform in a single kernel launch.

sglang currently follows its top-k with a chain of tensor ops to turn the winning positions into physical KV slots — a score gather, two torch.where, the page split, a torch.gather, the recombine and a masked_fill (_topk_transform_512_vectorized). At k=2048 that chain is launch-bound and costs more than the selection it follows (37.9–50.2 us measured).

How

Selection is a cooperative radix-select (csrc/include/coop_topk.cuh): a 12-bit LDS histogram narrows the row, a second pass over the fp16 key refines the threshold bin, and rows whose values collapse into a single coarse key fall back to a rescan.

The page-table mapping runs as a tail pass after the block-wide sync, not inside the scatter emit. That ordering is the whole point: folding the lookup into the emit serialises dependent scattered loads against the row scan and measured 6–16 us worse at batch >= 64.

Long rows take a multi-block split path (coop_mb_*); both paths share the same transform tail.

Numbers

Against sgl_kernel's fast_topk_transform_fused on real GLM-5.2 decode logits (live=100001, page_size=1), batch 1–256: 1.82–2.22x faster, bit-identical output.

Fusing the transform in (vs. two launches) saves a further 1.4–2.2 us per call.

Interface

pageTable = None emits raw positions, making this a plain per-row top-k. rowStarts = None means every row starts at 0 — what decode always wants, and it saves a per-call zeros tensor. pageSize must be a power of two; feeding the indexer's compact page_size=64 table yields the same physical slots as gathering a page_size=1 table without materialising the wide one.

Exposed as a ctypes entry because per-call binding cost is a visible fraction of a 20 us op.

Validation

Built and run on MI355X (gfx950). Selected set matches torch.topk exactly across one-block and row-split paths, short/long/ragged rows, and both page sizes, verified by inverting a deliberately shuffled page table.

Selection is exact except on rows dense enough to collapse into one fp16 coarse key (synthetic clustered data loses 1–3 of 2048); real GLM-5.2 logits are exact. This is a property of the pre-existing coop selection, not of the transform.

Note on the base branch

This targets upstream-sync (= ROCm/aiter 9aa8a6b9) rather than main, so the diff is just the three files. This fork's main is 304 commits behind upstream and 0 ahead, and predates the torch-free aiter_tensor_t / ctypes interface this op is built on, so it cannot host the change as-is. To take just the feature, cherry-pick 39ba9cca.


Note on base. Same change as #2, which was merged into upstream-sync by mistake; this targets main. main predates the detorch migration of module_top_k_per_row, so the port differs from what landed in #2 in three ways:

  • pybind instead of ctypes. Registering any ffi_type="ctypes" entry forces torch_exclude on the whole module (aiter/jit/core.py), and on this base three of the module's four sources still include torch/all.h, so no ctypes entry compiles here at all. This is pre-existing, not something this PR introduces: main's own top_k_per_row_decode_fast and top_k_per_row_prefill_fast fail to build the same way today — calling either on plain main dies with fatal error: 'torch/all.h' file not found. They are simply never called. [module_topk_*] de-torch topk_per_row / topk_plain + externalize workspaces ROCm/aiter#4702 and [detorch] remove vestigial py_itfs_common.h includes (non-CK); top_k_per_row now torch-free ROCm/aiter#4756 are what make the ctypes form buildable.
  • topk_per_row_kernels.cu keeps the torch::Tensor signature style of the two entries beside it and takes the stream from getCurrentHIPStream.
  • The aiter::coop namespace goes above the top_k_per_row_prefill doc comment instead of between that comment and the function it documents.

coop_topk.cuh is byte-identical to #2 and the selection kernel is unchanged.

The ctypes rationale does not survive measurement. #2 justified ctypes as saving per-call binding cost on a ~20 us op. Benchmarked against the ctypes build on the same machine (GLM-5.2 decode logits, live=100001, page_size=1, k=2048, three runs each):

rows ctypes (us) pybind (us)
1 30.01 / 27.13 / 28.22 24.97 / 25.35 / 24.93
8 26.85 / 26.13 / 26.48 26.21 / 26.14 / 26.17
64 39.65 / 40.15 / 39.27 40.08 / 39.45 / 40.07

pybind is never slower, and at batch 1 it is consistently ~3.4 us faster with no overlap between the two sets. The two trees sit on different bases so that batch-1 gap is not purely the binding, but there is no per-call penalty to recover.

Testing. Built and run on this base against a gfx950 MI355X. op_tests/test_dsa_topk_transform.py (added by #3, which stacks on this) passes 13/13, and output is bit-identical to sgl_kernel's fast_topk_transform_fused (mismatch=0) at every measured shape, 1.71–1.92x faster across batch 1–64.

sglang's DSA indexer follows its per-row top-k with a chain of tensor ops to
turn the winning positions into physical KV slots -- a score gather, two
torch.where, the page split, a torch.gather, the recombine and a masked_fill
(_topk_transform_512_vectorized). At k=2048 that chain is launch-bound and
costs more than the selection it follows.

This adds dsa_topk_transform, which does both halves in one launch. Selection
is a cooperative radix-select (csrc/include/coop_topk.cuh): a 12-bit LDS
histogram narrows the row, then a second pass over the fp16 key refines the
threshold bin, with a fallback rescan for rows whose values collapse into one
coarse key. The page-table mapping rides along as a tail pass after the
block-wide sync rather than inside the scatter emit, which keeps the dependent
scattered loads off the hot selection loop -- folding it into the emit measured
6-16us worse at batch >= 64.

Against sgl_kernel's fast_topk_transform_fused on real GLM-5.2 decode logits
(live=100001, page_size=1) this is 1.82-2.22x faster across batch 1-256 with
bit-identical output.

A null pageTable emits raw positions, making this a plain per-row top-k; a null
rowStarts means every row starts at 0, which is what decode wants and saves it
a per-call zeros tensor. Exposed as a ctypes entry because per-call binding
cost is a visible fraction of a 20us op.

Ported onto main, which predates the aiter_tensor_t migration of this file, so
it carries two deltas against the copy merged as #2: topk_per_row_kernels.cu
also needs an explicit aiter_tensor.h include (upstream already had one on the
newer base), and the coop namespace goes above the top_k_per_row_prefill doc
comment rather than between that comment and the function it documents.
@xiaobochen-amd
xiaobochen-amd merged commit e88f48e into main Aug 28, 2026
JohnQin-llm pushed a commit that referenced this pull request Aug 28, 2026
#5)

sglang's DSA indexer follows its per-row top-k with a chain of tensor ops to
turn the winning positions into physical KV slots -- a score gather, two
torch.where, the page split, a torch.gather, the recombine and a masked_fill
(_topk_transform_512_vectorized). At k=2048 that chain is launch-bound and
costs more than the selection it follows.

This adds dsa_topk_transform, which does both halves in one launch. Selection
is a cooperative radix-select (csrc/include/coop_topk.cuh): a 12-bit LDS
histogram narrows the row, then a second pass over the fp16 key refines the
threshold bin, with a fallback rescan for rows whose values collapse into one
coarse key. The page-table mapping rides along as a tail pass after the
block-wide sync rather than inside the scatter emit, which keeps the dependent
scattered loads off the hot selection loop -- folding it into the emit measured
6-16us worse at batch >= 64.

Against sgl_kernel's fast_topk_transform_fused on real GLM-5.2 decode logits
(live=100001, page_size=1) this is 1.82-2.22x faster across batch 1-256 with
bit-identical output.

A null pageTable emits raw positions, making this a plain per-row top-k; a null
rowStarts means every row starts at 0, which is what decode wants and saves it
a per-call zeros tensor. Exposed as a ctypes entry because per-call binding
cost is a visible fraction of a 20us op.

Ported onto main, which predates the aiter_tensor_t migration of this file, so
it carries two deltas against the copy merged as #2: topk_per_row_kernels.cu
also needs an explicit aiter_tensor.h include (upstream already had one on the
newer base), and the coop namespace goes above the top_k_per_row_prefill doc
comment rather than between that comment and the function it documents.

Co-authored-by: jiejingzhangamd <[email protected]>
JohnQin-llm pushed a commit that referenced this pull request Aug 28, 2026
dsa_topk_transform (#5) landed with a ctypes entry, which does not compile on
this base: registering any ffi_type="ctypes" op forces torch_exclude on the
whole module (aiter/jit/core.py), and three of module_top_k_per_row's four
sources still include torch/all.h. Calling aiter.dsa_topk_transform on main
today dies in the JIT build with

    csrc/include/py_itfs_common.h:6:10: fatal error: 'torch/all.h' file not found

The module has been in this state since before #5 -- main's own
top_k_per_row_decode_fast and top_k_per_row_prefill_fast fail identically, they
are just never called, so nothing reached the broken path. #5 added the first
ctypes entry on this module that callers actually use.

This binds the op through pybind instead: a torch::Tensor signature matching
the two entries beside it, the stream from getCurrentHIPStream, a declaration
in topk_per_row.h and an m.def in TOP_K_PER_ROW_PYBIND. The kernel and
coop_topk.cuh are untouched.

The binding costs nothing measurable. Against the ctypes build on the same
MI355X, GLM-5.2 decode logits (live=100001, page_size=1, k=2048), three runs
each:

    rows    ctypes us                pybind us
       1    30.01 / 27.13 / 28.22    24.97 / 25.35 / 24.93
       8    26.85 / 26.13 / 26.48    26.21 / 26.14 / 26.17
      64    39.65 / 40.15 / 39.27    40.08 / 39.45 / 40.07

pybind is never slower and batch 1 is consistently ~3.4us faster with no
overlap between the two sets, so the per-call binding cost #5 cited as the
reason for ctypes is not visible here.

The proper fix is the detorch migration of this module (ROCm#4702, ROCm#4756), after
which the ctypes form builds and this can go back if it ever measures better.

op_tests/test_dsa_topk_transform.py passes 13/13 on gfx950, and output stays
bit-identical to sgl_kernel's fast_topk_transform_fused at every shape.
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.

2 participants