Repository navigation
feat(topk): fuse the DSA page-table transform into a cooperative top-k - #5
Merged
Merged
Conversation
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, atorch.gather, the recombine and amasked_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'sfast_topk_transform_fusedon 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 = Noneemits raw positions, making this a plain per-row top-k.rowStarts = Nonemeans every row starts at 0 — what decode always wants, and it saves a per-call zeros tensor.pageSizemust 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.topkexactly 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/aiter9aa8a6b9) rather thanmain, so the diff is just the three files. This fork'smainis 304 commits behind upstream and 0 ahead, and predates the torch-freeaiter_tensor_t/ ctypes interface this op is built on, so it cannot host the change as-is. To take just the feature, cherry-pick39ba9cca.Note on base. Same change as #2, which was merged into
upstream-syncby mistake; this targetsmain.mainpredates the detorch migration ofmodule_top_k_per_row, so the port differs from what landed in #2 in three ways:ffi_type="ctypes"entry forcestorch_excludeon the whole module (aiter/jit/core.py), and on this base three of the module's four sources still includetorch/all.h, so no ctypes entry compiles here at all. This is pre-existing, not something this PR introduces:main's owntop_k_per_row_decode_fastandtop_k_per_row_prefill_fastfail to build the same way today — calling either on plainmaindies withfatal 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.cukeeps thetorch::Tensorsignature style of the two entries beside it and takes the stream fromgetCurrentHIPStream.aiter::coopnamespace goes above thetop_k_per_row_prefilldoc comment instead of between that comment and the function it documents.coop_topk.cuhis 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):
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
gfx950MI355X.op_tests/test_dsa_topk_transform.py(added by #3, which stacks on this) passes 13/13, and output is bit-identical tosgl_kernel'sfast_topk_transform_fused(mismatch=0) at every measured shape, 1.71–1.92x faster across batch 1–64.