Skip to content

[FlyDSL] feat(topk): per-row top-k across five selectors behind one entry - #5499

Merged
valarLip merged 8 commits into
mainfrom
perf/topk-select-per-row-selectors
Sep 14, 2026
Merged

valarLip merged 8 commits into
mainfrom
perf/topk-select-per-row-selectors

Conversation

@valarLip

@valarLip valarLip commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

What

aiter has four per-row top-k selectors, each fastest in a different corner and
none able to cover the whole domain. This puts them behind one entry,
aiter.topk_select, that picks between them by shape — and adds the fifth, a
k=1 reduction, because at k=1 all four were building machinery the answer does
not need.

serves
argmax k=1, as a reduction: the row split across as many workgroups as it takes to fill the part
small_k one chunk per lane, so k ≤ wave. Short rows and tiny k
plain the existing C++/ASM radix selector. Scales with rows, so it owns the wide-M middle
decode grid-wide radix. Few rows at very wide rows, and all of k=4096
stream one workgroup per row, reading the row once. New. Owns the rest

Parameter names, order and return shape follow deep_select.topk so code
written against DeepSelect ports across. Where this cannot honour DeepSelect's
behaviour it raises rather than diverging silently; the four defaults that
differ are listed on topk_select itself.

Which selector serves

topk_select_backend is fitted to a 232-cell sweep — M 1..16384, N 2048..1M,
k 16..4096 — by measured time, not by rule of thumb. Among backends within 1.4x
of the fastest it prefers the one whose answer is a function of the row alone,
which costs a mean 1.063x and lands a deterministic backend on 200 of the 232
cells. Every backend was checked against torch in a poisoned buffer before being
timed, in interleaved rounds, because one reading of this domain runs 1.42x off
another.

deterministic=True promises the set of selected columns is a function of the
row alone; tie='low'/'high' promise a direction among equal scores and cost
more. plain is the only backend excluded by deterministic — measured, it
selects a different set of tied columns from one call to the next.

k=1

The dispatcher used to send every k=1 call to small_k, whose rule had no width
term, having been fitted only at k=16. It ran 12x behind plain at 1024 rows of
262144.

topk_per_row_argmax splits a row across workgroups instead. That is the point
of the shape: one workgroup per row leaves a 50-row call using a fifth of the
GPU, which is the ceiling torch.argmax is stuck at too.

n=129280, k=1, through the entry, against torch's own reduction (interleaved,
median of 9; every row verified equal to torch.argmax):

rows 1 16 64 256 512 1024
ours 5.77 7.09 10.28 25.73 43.83 97.48 µs
torch.argmax 29.25 30.10 34.88 41.43 57.20 96.66 µs
gain 5.1x 4.2x 3.4x 1.6x 1.3x 1.0x

The two converge at 1024 rows, where both reach 5.4 TB/s and the rows fill the
part without help. Elsewhere: 20.4x at one row of 262144, 12.7x at 1024 rows of
262144. Against the backend that used to be picked, 2.8x–12.7x over the same
range.

The split count is fitted to a 34-cell sweep against the best count measured at
each cell (mean 1.015x, worst 1.087x), and the block width was swept jointly
with it — they are coupled, and 256 turned out to be the best single width.

Correctness found on the way

Three real faults, each with the measurement that caught it in its commit
message:

  • The streaming selector's window was not vector-aligned. absorb took an
    element's column from base but its address from base // vec, so every key
    after the window paired with a column base % vec away from its own. This was
    every k whose capacity was not a whole number of vectors, not a corner: at 64
    rows of 32768, k=1 gave 56 wrong rows of 64, k=2/3/5/6/7 gave 64, and k=4/8/12/16
    were clean. The soak missed it because every shape in it used a k that is a
    multiple of four; five unaligned ones are now in it.
  • The argmax fold read one partial per thread, so splits > block_threads
    silently dropped the rest. The split rule does reach past the block — 512
    splits against a 256-thread block at one row of 1M.
  • topk_select and the small-k wrapper disagreed on the wave width, one
    asking get_gfx() (which honours GPU_ARCHS) and the other the live device,
    so a cross-targeting build picked a backend for a machine it was not running on.

Test plan

  • op_tests/test_topk_select.py — every backend that serves a shape is timed
    beside the entry, so the dispatch can be read off the table rather than
    trusted; exact against torch (rtol=0 atol=0) on all 222 cells.
  • Invariants a value comparison cannot reach: values pair with indices under
    every ordering flag, end= bounds the answer, output_idx_offset shifts
    only live indices, sorted orders the indices even when the values are
    dropped. All three of these were once silently wrong.
  • op_tests/test_flydsl_topk_per_row_small_k.py.
  • Streaming soak: 97 configs across block widths 256/512/1024 and two seeds,
    including 1024x262144 at k=1, 3 and 513.
  • argmax: 240 (block, splits) combinations exact against torch.argmax,
    plus an 80-case sweep of the small-k selector against torch.topk
    (widths 256..32768, k 1..32, rows 1..1024, ragged row lengths) and the
    NaN / ±0.0 / ±inf row.
  • black clean.

Measured on MI355X (gfx950), ROCm 7.2.

Known gaps

  • The small_k dispatch rule still has no width term for k=2..32. k=1 no longer
    reaches it, so the 12x is not reachable, but that band is unmeasured.
  • The split rule for argmax leaves about 1.3% against a per-cell oracle; the
    rest needs a per-cell block choice, and three forms of one were tried and were
    all worse than holding the width flat.

🤖 Generated with Claude Code

`topk_select` picks between aiter's four per-row selectors, none of which
covers the whole domain. Two of them are new here:

  small_k  narrows to k chunks instead of sorting: partition the row into
           C >= k chunks, rank them by maximum, and the true top-k lives in
           the top-k chunks. A chunk is one lane's share, so the selection is
           a ballot -- no barrier, and the chunk maxima never leave registers.
           Fastest thing on the card below k=32, over rows 1..16384.
  stream   one workgroup per row, reading the row once, three radix passes
           over the 32-bit key. Owns the narrow rows and the large-M end of
           the wide ones.

The dispatch is fitted to a 232-cell sweep (M 1..16384, N 2048..1M,
k 16..4096, to 64 GiB) by `topk_fit_policy.py`, against a preference rather
than the stopwatch alone: among backends within 1.4x of the fastest it takes
the one whose answer is a function of the row. That costs a mean 1.063x and
lands a deterministic backend on 200 of the 232 cells; the rules it replaces
lost a mean 1.181x and a worst 4.18x.

The interface follows `deep_select.topk` so code ports across, and raises
rather than diverging silently where it cannot honour DeepSelect's behaviour
(int64 indices, the 2147483647 pad, bf16 input, NaN abort).

Also here:

* `kernel_signature` renders build parameters into a kernel-name suffix, so
  two builds that differ only in an omitted parameter stop emitting the same
  symbol -- indistinguishable in a profile and in a disassembly dump.
* The decode selector's buffer descriptors are built over the row, not the
  whole tensor: `num_records` is a 32-bit byte count, so at 4 GiB it wrapped
  to zero and every load returned zero, with nothing raised.
* Host cost on the serving path: the selectors are 7-10us of device time
  behind what was 47us of Python. Everything shape-derived is now resolved
  once per geometry (`@lru_cache` on scalars, the house pattern), which puts
  the entry at 21.7us.
…l scalars

Review follow-ups on the four-selector entry.

Correctness:
* `wave_size_of(device_index)` in tensor_shim is now the single source, read
  from the live GPU. `topk_select` asked `get_warp_size(get_gfx())`, which
  honours GPU_ARCHS, while the small_k wrapper asked the device -- so a build
  cross-targeting another arch picked a backend for a machine it was not
  running on, then built it for the one it was.

Host cost (gfx950, 64x8192, k=16, 2000 calls):
* `return_value=True` 48.7 -> 28.8us. The gather built a scalar tensor per call
  for `torch.where`'s fill; `gather` + `masked_fill_` drops an H2D, an
  allocation and a kernel. `idx.long().clamp_min_(0)` drops one more [rows, k].
* The backend decision is memoized as one step (`_choose`) instead of a set
  build, an intersection and a rule chain per call: 0.07us. Indices-only path
  7.8 -> 7.5us. The tables it reads are constants, so the one test that
  withholds a backend clears the cache around its patch.

Shape:
* `topk_per_row_radix_stream_serves()` mirrors small_k's predicate, so
  `_available` no longer builds a module to ask whether one can be built. The
  LDS budget search behind both is `_resolve_lds`; the build's dead
  `soft_trigger` pre-assignment went with it.
* `_reject_unsupported` takes keyword-only arguments -- nine positional
  parameters aligned by order at the one call site. `_dispatch` loses an
  unused `width`.
…ards

The row read is latency-bound, not bandwidth-bound (k=1 over 32768 columns
runs 4.1 TB/s where the other two selectors reach 5.8), so what it spends per
element and per register is what it costs.

* The column tile is gone. Thread t's slot (v, j) is column `tid * _VEC +
  (v * block_threads * _VEC + j)`, and the bracket is a compile-time constant,
  so the columns were `elems_per_thread` registers holding one add -- 32 of the
  64 register tile at the widest bound. Step 3 recomputes them; its liveness
  test `cols[slot] >= 0` becomes the same `col < row_len`.
* `in_row` is dropped from the liveness test: a column past this thread's
  vectors is at least `n_max`, which already bounds `row_len`.
* The address no longer tests it either. The descriptor is built over one row,
  so `num_records` already clamps a read past the end to zero -- the select was
  software redoing the V#'s job, per vector, and made the address data-dependent.
* The running maximum splits into one accumulator per vector lane, chaining a
  v_max per vector rather than per element. Only where a thread holds more than
  one vector: at exactly one it shortens nothing, costs the fold, and measured
  7% slower before the guard went in.

Median-of-7 device time, gfx950, k=16:

    width x rows       before     after
    1024  x   64      3.88us    3.62us
    1024  x 1024      4.14us    3.74us
    8192  x   64      6.10us    4.89us
    8192  x 1024      7.59us    7.56us
    32768 x   64      7.28us    7.14us
    32768 x 1024     32.79us   31.63us

80-case sweep against torch (widths 256..32768, k 1..32, rows 1..1024, ragged
row lengths) exact; the NaN / +-0.0 / +-inf row unchanged; op_tests clean.
…ngly

At k=1 and k=2 it returns wrong rows in bulk -- 55 of 64 and 63 of 64 at 32768
gaussian columns -- and the dispatcher reached it: k=2 over a 1M-wide row at
256 rows or more picked it, and every row of the answer was wrong end to end.
A row narrow enough to fit one tile group is right at every k, so it is the
re-select path; k>=4 is clean at every width tried.

Declined in `topk_per_row_radix_stream_serves` rather than left to ship while
the cause is open. Those shapes now fall to decode and are exact. The cause
stays open: this kernel's own notes record that the last fault here survived a
ballot, an ordered load, wait states, LDS padding, four rewrites of the prefix
and both cross-lane primitives before the register pressure turned out to be
it, so a guess costs more than it saves.
At k=1 the selectors build machinery the answer does not need: the small-k one
ranks chunks to bound a survivor set, where the top-1 chunk is just the chunk
holding the maximum; the radix ones walk the key space for a threshold that is
the answer. The dispatcher sent every k=1 call to small_k -- the rule had no
width term, having been fitted only to k=16 -- and it ran 12x behind `plain` at
1024 rows of 262144.

`topk_per_row_argmax` is the reduction instead, and it splits a row across as
many workgroups as it takes to fill the part. That is the point: one workgroup
per row leaves a 50-row call using a fifth of the GPU, which is the ceiling
`torch.argmax` is stuck at too.

n=129280, k=1, through the entry, against torch's own reduction (interleaved,
median of 9; every row verified equal to `torch.argmax`):

    rows      1     16     64    256    512   1024
    ours   5.77   7.09  10.28  25.73  43.83  97.48 us
    torch 29.25  30.10  34.88  41.43  57.20  96.66 us
    gain   5.1x   4.2x   3.4x   1.6x   1.3x   1.0x

Against the backend that used to be picked: 2.8x-5.1x over the same range. The
two converge at 1024 rows, where both reach 5.4 TB/s and the rows fill the part
without help. Elsewhere: 20.4x at one row of 262144, 12.7x at 1024 rows of
262144.

The split count is fitted to a 34-cell sweep against the best count measured at
each cell -- mean 1.015x, worst 1.087x. It is three interacting constants; the
one that is not obvious is the short-row guard, without which a 1024-row call
over a 32768-wide row (decode against a vocabulary) splits four ways and loses
13% where one split is already at 6.05 TB/s.

Ties go to the smallest column, matching `torch.argmax` and the order decode and
the streaming selector already promise, so `tie='low'` can be served by it too.
NaN outranks +inf as everywhere else here, which is why `ord_signed_f32` moved
to `kernels_common` rather than being copied: the dispatcher picks by shape, so
a row holding a NaN must not answer differently for a choice the caller did not
make.

Also reformats two files this branch had left non-black-clean.
…ecline

Root cause of the wrong rows, and it was never about k<=2.

`absorb` takes an element's column from its own `base` but its address from
`base // vec`. `base` is where the streaming loop starts, which is the window,
which is `capacity` on any row wider than it. `capacity = k + soft_trigger(k) +
unroll * tile`; the last two terms are multiples of `vec`, so whenever
`capacity % vec` was non-zero the loop read column `(base // vec) * vec + i` and
labelled it `base + i` -- every key after the window paired with a column
`base % vec` away from its own.

So the broken set was every k whose capacity was not a whole number of vectors,
not the two I happened to test. Measured at 64 rows of 32768, wrong rows out of
64: k=1 56, k=2 64, k=3 64, k=5 64, k=6 64, k=7 64; k=4, 8, 12, 16 clean. The
prediction matched on all ten. A row narrower than the window never enters the
loop, which is why one tile group was always right.

Fixed where it starts: the window rounds down to a whole number of vectors.
Rounding down rather than up keeps it inside the buffer, and it costs at most
three columns of a window that is thousands wide.

`topk_per_row_radix_stream_serves` goes back to `k >= 1`. The decline added in
145ca9c50a was both too narrow -- k=5, 6, 7 were still dispatched and still
wrong -- and no longer needed.

The soak missed this for the same reason I did: every shape in it used a k that
is a multiple of four. Five unaligned ones are now in it. 97 configs across
block widths 256/512/1024 and two seeds, all exact, including 1024x262144 at
k=1, 3 and 513.
The fold kernel gave each thread exactly one partial and dropped the rest:

    in_range = tid < Int32(splits)
    slot = in_range.select(tid, zero)

so `splits > block_threads` silently lost the partials past the block, and the
answer was whatever the first `block_threads` slices held. I had written that
more splits than threads "never happens". It does: the split rule asks for
`vectors // 512` at one or two rows, which passes 256 once the row is wider than
524288 columns -- `m=1, n=1048576` shipped at 512 splits against a 256-thread
block, and was wrong.

Found by a sweep over (block width, split count) that was measuring something
else. Every one of its 34 wrong cells had `splits > block_threads` and none of
the others did.

A thread now folds every `block_threads`-th partial, so no split count can
violate the kernel's contract again -- which matters because the rule that picks
it is fitted, and a refit must not be able to reintroduce this. Slots ascend
within a thread, so its columns do too, and a strict `>` keeps the earliest of a
tie exactly as the slice path does.

240 (block, splits) combinations across six shapes are exact, including every
one that was wrong before; so are the shapes the shipped rule actually reaches
past the block, up to 1024 splits at one row of 2097152.

Also records why the block fold is an LDS tree rather than the usual wave
`shuffle_xor`: the barriers are not what it costs, measured -- a wider block
adds a fold step and still wins where the fold is heaviest.
`_BLOCK_THREADS = 256` was picked by hand. Swept jointly with the split rule --
64/128/256/512 against every split count on the same 34 cells -- because the two
are coupled: a narrower block absorbs less of a slice, which is what the split
rule decides, so one cannot be refitted without the other.

256 turns out to be the best single width. Against a per-cell (block, split)
oracle, holding one block and taking the best split per cell costs mean 1.043x
at 256, 1.046x at 128, 1.064x at 512 and 1.080x at 64. The shipped
configuration -- 256 plus the fitted split rule -- sits at 1.056x, so about 1.3%
is left in the split rule and the remainder needs a per-cell block choice. Three
forms of a block rule were tried against the sweep and every one was worse than
holding it flat, which is what coupling predicts: they reused a split rule
fitted at 256.

Left as it is, and the reasoning is in the file so the next person does not
repeat the sweep to reach the same answer.
@valarLip
valarLip requested a review from a team September 14, 2026 11:33
@github-actions github-actions Bot changed the title feat(topk): per-row top-k across five selectors behind one entry [FlyDSL] feat(topk): per-row top-k across five selectors behind one entry Sep 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5499 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

@valarLip
valarLip merged commit d81eb48 into main Sep 14, 2026
52 of 55 checks passed
@valarLip
valarLip deleted the perf/topk-select-per-row-selectors branch September 14, 2026 14:19
sammysun0711 pushed a commit to sammysun0711/aiter that referenced this pull request Sep 16, 2026
…ntry (ROCm#5499)

* feat(topk): per-row top-k across four selectors behind one entry

`topk_select` picks between aiter's four per-row selectors, none of which
covers the whole domain. Two of them are new here:

  small_k  narrows to k chunks instead of sorting: partition the row into
           C >= k chunks, rank them by maximum, and the true top-k lives in
           the top-k chunks. A chunk is one lane's share, so the selection is
           a ballot -- no barrier, and the chunk maxima never leave registers.
           Fastest thing on the card below k=32, over rows 1..16384.
  stream   one workgroup per row, reading the row once, three radix passes
           over the 32-bit key. Owns the narrow rows and the large-M end of
           the wide ones.

The dispatch is fitted to a 232-cell sweep (M 1..16384, N 2048..1M,
k 16..4096, to 64 GiB) by `topk_fit_policy.py`, against a preference rather
than the stopwatch alone: among backends within 1.4x of the fastest it takes
the one whose answer is a function of the row. That costs a mean 1.063x and
lands a deterministic backend on 200 of the 232 cells; the rules it replaces
lost a mean 1.181x and a worst 4.18x.

The interface follows `deep_select.topk` so code ports across, and raises
rather than diverging silently where it cannot honour DeepSelect's behaviour
(int64 indices, the 2147483647 pad, bf16 input, NaN abort).

Also here:

* `kernel_signature` renders build parameters into a kernel-name suffix, so
  two builds that differ only in an omitted parameter stop emitting the same
  symbol -- indistinguishable in a profile and in a disassembly dump.
* The decode selector's buffer descriptors are built over the row, not the
  whole tensor: `num_records` is a 32-bit byte count, so at 4 GiB it wrapped
  to zero and every load returned zero, with nothing raised.
* Host cost on the serving path: the selectors are 7-10us of device time
  behind what was 47us of Python. Everything shape-derived is now resolved
  once per geometry (`@lru_cache` on scalars, the house pattern), which puts
  the entry at 21.7us.

* refactor(topk): one wave-size source, one dispatch lookup, no per-call scalars

Review follow-ups on the four-selector entry.

Correctness:
* `wave_size_of(device_index)` in tensor_shim is now the single source, read
  from the live GPU. `topk_select` asked `get_warp_size(get_gfx())`, which
  honours GPU_ARCHS, while the small_k wrapper asked the device -- so a build
  cross-targeting another arch picked a backend for a machine it was not
  running on, then built it for the one it was.

Host cost (gfx950, 64x8192, k=16, 2000 calls):
* `return_value=True` 48.7 -> 28.8us. The gather built a scalar tensor per call
  for `torch.where`'s fill; `gather` + `masked_fill_` drops an H2D, an
  allocation and a kernel. `idx.long().clamp_min_(0)` drops one more [rows, k].
* The backend decision is memoized as one step (`_choose`) instead of a set
  build, an intersection and a rule chain per call: 0.07us. Indices-only path
  7.8 -> 7.5us. The tables it reads are constants, so the one test that
  withholds a backend clears the cache around its patch.

Shape:
* `topk_per_row_radix_stream_serves()` mirrors small_k's predicate, so
  `_available` no longer builds a module to ask whether one can be built. The
  LDS budget search behind both is `_resolve_lds`; the build's dead
  `soft_trigger` pre-assignment went with it.
* `_reject_unsupported` takes keyword-only arguments -- nine positional
  parameters aligned by order at the one call site. `_dispatch` loses an
  unused `width`.

* perf(topk): small_k drops half its register tile and the redundant guards

The row read is latency-bound, not bandwidth-bound (k=1 over 32768 columns
runs 4.1 TB/s where the other two selectors reach 5.8), so what it spends per
element and per register is what it costs.

* The column tile is gone. Thread t's slot (v, j) is column `tid * _VEC +
  (v * block_threads * _VEC + j)`, and the bracket is a compile-time constant,
  so the columns were `elems_per_thread` registers holding one add -- 32 of the
  64 register tile at the widest bound. Step 3 recomputes them; its liveness
  test `cols[slot] >= 0` becomes the same `col < row_len`.
* `in_row` is dropped from the liveness test: a column past this thread's
  vectors is at least `n_max`, which already bounds `row_len`.
* The address no longer tests it either. The descriptor is built over one row,
  so `num_records` already clamps a read past the end to zero -- the select was
  software redoing the V#'s job, per vector, and made the address data-dependent.
* The running maximum splits into one accumulator per vector lane, chaining a
  v_max per vector rather than per element. Only where a thread holds more than
  one vector: at exactly one it shortens nothing, costs the fold, and measured
  7% slower before the guard went in.

Median-of-7 device time, gfx950, k=16:

    width x rows       before     after
    1024  x   64      3.88us    3.62us
    1024  x 1024      4.14us    3.74us
    8192  x   64      6.10us    4.89us
    8192  x 1024      7.59us    7.56us
    32768 x   64      7.28us    7.14us
    32768 x 1024     32.79us   31.63us

80-case sweep against torch (widths 256..32768, k 1..32, rows 1..1024, ragged
row lengths) exact; the NaN / +-0.0 / +-inf row unchanged; op_tests clean.

* fix(topk): the streaming selector declines k<=2, which it answers wrongly

At k=1 and k=2 it returns wrong rows in bulk -- 55 of 64 and 63 of 64 at 32768
gaussian columns -- and the dispatcher reached it: k=2 over a 1M-wide row at
256 rows or more picked it, and every row of the answer was wrong end to end.
A row narrow enough to fit one tile group is right at every k, so it is the
re-select path; k>=4 is clean at every width tried.

Declined in `topk_per_row_radix_stream_serves` rather than left to ship while
the cause is open. Those shapes now fall to decode and are exact. The cause
stays open: this kernel's own notes record that the last fault here survived a
ballot, an ordered load, wait states, LDS padding, four rewrites of the prefix
and both cross-lane primitives before the register pressure turned out to be
it, so a guess costs more than it saves.

* perf(topk): k=1 gets a split-row argmax instead of a selector

At k=1 the selectors build machinery the answer does not need: the small-k one
ranks chunks to bound a survivor set, where the top-1 chunk is just the chunk
holding the maximum; the radix ones walk the key space for a threshold that is
the answer. The dispatcher sent every k=1 call to small_k -- the rule had no
width term, having been fitted only to k=16 -- and it ran 12x behind `plain` at
1024 rows of 262144.

`topk_per_row_argmax` is the reduction instead, and it splits a row across as
many workgroups as it takes to fill the part. That is the point: one workgroup
per row leaves a 50-row call using a fifth of the GPU, which is the ceiling
`torch.argmax` is stuck at too.

n=129280, k=1, through the entry, against torch's own reduction (interleaved,
median of 9; every row verified equal to `torch.argmax`):

    rows      1     16     64    256    512   1024
    ours   5.77   7.09  10.28  25.73  43.83  97.48 us
    torch 29.25  30.10  34.88  41.43  57.20  96.66 us
    gain   5.1x   4.2x   3.4x   1.6x   1.3x   1.0x

Against the backend that used to be picked: 2.8x-5.1x over the same range. The
two converge at 1024 rows, where both reach 5.4 TB/s and the rows fill the part
without help. Elsewhere: 20.4x at one row of 262144, 12.7x at 1024 rows of
262144.

The split count is fitted to a 34-cell sweep against the best count measured at
each cell -- mean 1.015x, worst 1.087x. It is three interacting constants; the
one that is not obvious is the short-row guard, without which a 1024-row call
over a 32768-wide row (decode against a vocabulary) splits four ways and loses
13% where one split is already at 6.05 TB/s.

Ties go to the smallest column, matching `torch.argmax` and the order decode and
the streaming selector already promise, so `tie='low'` can be served by it too.
NaN outranks +inf as everywhere else here, which is why `ord_signed_f32` moved
to `kernels_common` rather than being copied: the dispatcher picks by shape, so
a row holding a NaN must not answer differently for a choice the caller did not
make.

Also reformats two files this branch had left non-black-clean.

* fix(topk): align the streaming selector's window, and drop the k<=2 decline

Root cause of the wrong rows, and it was never about k<=2.

`absorb` takes an element's column from its own `base` but its address from
`base // vec`. `base` is where the streaming loop starts, which is the window,
which is `capacity` on any row wider than it. `capacity = k + soft_trigger(k) +
unroll * tile`; the last two terms are multiples of `vec`, so whenever
`capacity % vec` was non-zero the loop read column `(base // vec) * vec + i` and
labelled it `base + i` -- every key after the window paired with a column
`base % vec` away from its own.

So the broken set was every k whose capacity was not a whole number of vectors,
not the two I happened to test. Measured at 64 rows of 32768, wrong rows out of
64: k=1 56, k=2 64, k=3 64, k=5 64, k=6 64, k=7 64; k=4, 8, 12, 16 clean. The
prediction matched on all ten. A row narrower than the window never enters the
loop, which is why one tile group was always right.

Fixed where it starts: the window rounds down to a whole number of vectors.
Rounding down rather than up keeps it inside the buffer, and it costs at most
three columns of a window that is thousands wide.

`topk_per_row_radix_stream_serves` goes back to `k >= 1`. The decline added in
145ca9c50a was both too narrow -- k=5, 6, 7 were still dispatched and still
wrong -- and no longer needed.

The soak missed this for the same reason I did: every shape in it used a k that
is a multiple of four. Five unaligned ones are now in it. 97 configs across
block widths 256/512/1024 and two seeds, all exact, including 1024x262144 at
k=1, 3 and 513.

* fix(topk): the argmax fold reads every partial, not one per thread

The fold kernel gave each thread exactly one partial and dropped the rest:

    in_range = tid < Int32(splits)
    slot = in_range.select(tid, zero)

so `splits > block_threads` silently lost the partials past the block, and the
answer was whatever the first `block_threads` slices held. I had written that
more splits than threads "never happens". It does: the split rule asks for
`vectors // 512` at one or two rows, which passes 256 once the row is wider than
524288 columns -- `m=1, n=1048576` shipped at 512 splits against a 256-thread
block, and was wrong.

Found by a sweep over (block width, split count) that was measuring something
else. Every one of its 34 wrong cells had `splits > block_threads` and none of
the others did.

A thread now folds every `block_threads`-th partial, so no split count can
violate the kernel's contract again -- which matters because the rule that picks
it is fitted, and a refit must not be able to reintroduce this. Slots ascend
within a thread, so its columns do too, and a strict `>` keeps the earliest of a
tie exactly as the slice path does.

240 (block, splits) combinations across six shapes are exact, including every
one that was wrong before; so are the shapes the shipped rule actually reaches
past the block, up to 1024 splits at one row of 2097152.

Also records why the block fold is an LDS tree rather than the usual wave
`shuffle_xor`: the barriers are not what it costs, measured -- a wider block
adds a fold step and still wins where the fold is heaviest.

* docs(topk): record that the argmax block width was swept, not guessed

`_BLOCK_THREADS = 256` was picked by hand. Swept jointly with the split rule --
64/128/256/512 against every split count on the same 34 cells -- because the two
are coupled: a narrower block absorbs less of a slice, which is what the split
rule decides, so one cannot be refitted without the other.

256 turns out to be the best single width. Against a per-cell (block, split)
oracle, holding one block and taking the best split per cell costs mean 1.043x
at 256, 1.046x at 128, 1.064x at 512 and 1.080x at 64. The shipped
configuration -- 256 plus the fitted split rule -- sits at 1.056x, so about 1.3%
is left in the split rule and the remainder needs a per-cell block choice. Three
forms of a block rule were tried against the sweep and every one was worse than
holding it flat, which is what coupling predicts: they reused a split rule
fitted at 256.

Left as it is, and the reasoning is in the file so the next person does not
repeat the sweep to reach the same answer.

Signed-off-by: Xiake Sun <[email protected]>
xysheng-AMD added a commit to ZhangDanyang-AMD/Lumen-RL that referenced this pull request Sep 21, 2026
…r main

ATOM 8b6d6139 -> 0795f0eae2d6, which is PR #2267 ('blank a capture's cache
write targets, and keep the KV pool size across a wake') as squash-merged on
main. Both rollout fixes this line was carrying out of tree are upstream now.

That pin forces aiter forward. atom/model_ops/sampler.py imports topk_select
from aiter at module scope and it does not exist before ROCm/aiter#5499, so the
old lumen/moe base (ROCm/aiter main at f2f8ed9b2) cannot load the rollout at
all -- embed_head, rejection_sampler and model_runner_ext fail the same way.
lumen/moe is therefore rebased onto ROCm/aiter main 6a9a005b7, with the damage
from the #5149 revert undone where upstream has not already re-landed it: 148
files plus arch_info.is_cdna4, all absent from 6a9a005b7, restored at their
pre-revert content. The five SonicMoE commits replay byte-identically and the
composable_kernel gitlink is unchanged.

Validated on image 260921 (the 260917 image re-layered, not rebuilt): examples
5, 4 and 9 all exit 0 with zero errors and --check PASS, k3_kl within +2.6% /
+27.9% / -0.7% of the existing references. Example 9's sleep path is balanced
at 48 releases and 48 resumes with no negative KV budget, no memory access
fault and no NaN grad_norm -- the three symptoms #2267 fixed.

The rebased aiter branch is not pushed; see the warning in versions.env.

Co-authored-by: Cursor <[email protected]>
RElbers pushed a commit that referenced this pull request Sep 25, 2026
…ntry (#5499)

* feat(topk): per-row top-k across four selectors behind one entry

`topk_select` picks between aiter's four per-row selectors, none of which
covers the whole domain. Two of them are new here:

  small_k  narrows to k chunks instead of sorting: partition the row into
           C >= k chunks, rank them by maximum, and the true top-k lives in
           the top-k chunks. A chunk is one lane's share, so the selection is
           a ballot -- no barrier, and the chunk maxima never leave registers.
           Fastest thing on the card below k=32, over rows 1..16384.
  stream   one workgroup per row, reading the row once, three radix passes
           over the 32-bit key. Owns the narrow rows and the large-M end of
           the wide ones.

The dispatch is fitted to a 232-cell sweep (M 1..16384, N 2048..1M,
k 16..4096, to 64 GiB) by `topk_fit_policy.py`, against a preference rather
than the stopwatch alone: among backends within 1.4x of the fastest it takes
the one whose answer is a function of the row. That costs a mean 1.063x and
lands a deterministic backend on 200 of the 232 cells; the rules it replaces
lost a mean 1.181x and a worst 4.18x.

The interface follows `deep_select.topk` so code ports across, and raises
rather than diverging silently where it cannot honour DeepSelect's behaviour
(int64 indices, the 2147483647 pad, bf16 input, NaN abort).

Also here:

* `kernel_signature` renders build parameters into a kernel-name suffix, so
  two builds that differ only in an omitted parameter stop emitting the same
  symbol -- indistinguishable in a profile and in a disassembly dump.
* The decode selector's buffer descriptors are built over the row, not the
  whole tensor: `num_records` is a 32-bit byte count, so at 4 GiB it wrapped
  to zero and every load returned zero, with nothing raised.
* Host cost on the serving path: the selectors are 7-10us of device time
  behind what was 47us of Python. Everything shape-derived is now resolved
  once per geometry (`@lru_cache` on scalars, the house pattern), which puts
  the entry at 21.7us.

* refactor(topk): one wave-size source, one dispatch lookup, no per-call scalars

Review follow-ups on the four-selector entry.

Correctness:
* `wave_size_of(device_index)` in tensor_shim is now the single source, read
  from the live GPU. `topk_select` asked `get_warp_size(get_gfx())`, which
  honours GPU_ARCHS, while the small_k wrapper asked the device -- so a build
  cross-targeting another arch picked a backend for a machine it was not
  running on, then built it for the one it was.

Host cost (gfx950, 64x8192, k=16, 2000 calls):
* `return_value=True` 48.7 -> 28.8us. The gather built a scalar tensor per call
  for `torch.where`'s fill; `gather` + `masked_fill_` drops an H2D, an
  allocation and a kernel. `idx.long().clamp_min_(0)` drops one more [rows, k].
* The backend decision is memoized as one step (`_choose`) instead of a set
  build, an intersection and a rule chain per call: 0.07us. Indices-only path
  7.8 -> 7.5us. The tables it reads are constants, so the one test that
  withholds a backend clears the cache around its patch.

Shape:
* `topk_per_row_radix_stream_serves()` mirrors small_k's predicate, so
  `_available` no longer builds a module to ask whether one can be built. The
  LDS budget search behind both is `_resolve_lds`; the build's dead
  `soft_trigger` pre-assignment went with it.
* `_reject_unsupported` takes keyword-only arguments -- nine positional
  parameters aligned by order at the one call site. `_dispatch` loses an
  unused `width`.

* perf(topk): small_k drops half its register tile and the redundant guards

The row read is latency-bound, not bandwidth-bound (k=1 over 32768 columns
runs 4.1 TB/s where the other two selectors reach 5.8), so what it spends per
element and per register is what it costs.

* The column tile is gone. Thread t's slot (v, j) is column `tid * _VEC +
  (v * block_threads * _VEC + j)`, and the bracket is a compile-time constant,
  so the columns were `elems_per_thread` registers holding one add -- 32 of the
  64 register tile at the widest bound. Step 3 recomputes them; its liveness
  test `cols[slot] >= 0` becomes the same `col < row_len`.
* `in_row` is dropped from the liveness test: a column past this thread's
  vectors is at least `n_max`, which already bounds `row_len`.
* The address no longer tests it either. The descriptor is built over one row,
  so `num_records` already clamps a read past the end to zero -- the select was
  software redoing the V#'s job, per vector, and made the address data-dependent.
* The running maximum splits into one accumulator per vector lane, chaining a
  v_max per vector rather than per element. Only where a thread holds more than
  one vector: at exactly one it shortens nothing, costs the fold, and measured
  7% slower before the guard went in.

Median-of-7 device time, gfx950, k=16:

    width x rows       before     after
    1024  x   64      3.88us    3.62us
    1024  x 1024      4.14us    3.74us
    8192  x   64      6.10us    4.89us
    8192  x 1024      7.59us    7.56us
    32768 x   64      7.28us    7.14us
    32768 x 1024     32.79us   31.63us

80-case sweep against torch (widths 256..32768, k 1..32, rows 1..1024, ragged
row lengths) exact; the NaN / +-0.0 / +-inf row unchanged; op_tests clean.

* fix(topk): the streaming selector declines k<=2, which it answers wrongly

At k=1 and k=2 it returns wrong rows in bulk -- 55 of 64 and 63 of 64 at 32768
gaussian columns -- and the dispatcher reached it: k=2 over a 1M-wide row at
256 rows or more picked it, and every row of the answer was wrong end to end.
A row narrow enough to fit one tile group is right at every k, so it is the
re-select path; k>=4 is clean at every width tried.

Declined in `topk_per_row_radix_stream_serves` rather than left to ship while
the cause is open. Those shapes now fall to decode and are exact. The cause
stays open: this kernel's own notes record that the last fault here survived a
ballot, an ordered load, wait states, LDS padding, four rewrites of the prefix
and both cross-lane primitives before the register pressure turned out to be
it, so a guess costs more than it saves.

* perf(topk): k=1 gets a split-row argmax instead of a selector

At k=1 the selectors build machinery the answer does not need: the small-k one
ranks chunks to bound a survivor set, where the top-1 chunk is just the chunk
holding the maximum; the radix ones walk the key space for a threshold that is
the answer. The dispatcher sent every k=1 call to small_k -- the rule had no
width term, having been fitted only to k=16 -- and it ran 12x behind `plain` at
1024 rows of 262144.

`topk_per_row_argmax` is the reduction instead, and it splits a row across as
many workgroups as it takes to fill the part. That is the point: one workgroup
per row leaves a 50-row call using a fifth of the GPU, which is the ceiling
`torch.argmax` is stuck at too.

n=129280, k=1, through the entry, against torch's own reduction (interleaved,
median of 9; every row verified equal to `torch.argmax`):

    rows      1     16     64    256    512   1024
    ours   5.77   7.09  10.28  25.73  43.83  97.48 us
    torch 29.25  30.10  34.88  41.43  57.20  96.66 us
    gain   5.1x   4.2x   3.4x   1.6x   1.3x   1.0x

Against the backend that used to be picked: 2.8x-5.1x over the same range. The
two converge at 1024 rows, where both reach 5.4 TB/s and the rows fill the part
without help. Elsewhere: 20.4x at one row of 262144, 12.7x at 1024 rows of
262144.

The split count is fitted to a 34-cell sweep against the best count measured at
each cell -- mean 1.015x, worst 1.087x. It is three interacting constants; the
one that is not obvious is the short-row guard, without which a 1024-row call
over a 32768-wide row (decode against a vocabulary) splits four ways and loses
13% where one split is already at 6.05 TB/s.

Ties go to the smallest column, matching `torch.argmax` and the order decode and
the streaming selector already promise, so `tie='low'` can be served by it too.
NaN outranks +inf as everywhere else here, which is why `ord_signed_f32` moved
to `kernels_common` rather than being copied: the dispatcher picks by shape, so
a row holding a NaN must not answer differently for a choice the caller did not
make.

Also reformats two files this branch had left non-black-clean.

* fix(topk): align the streaming selector's window, and drop the k<=2 decline

Root cause of the wrong rows, and it was never about k<=2.

`absorb` takes an element's column from its own `base` but its address from
`base // vec`. `base` is where the streaming loop starts, which is the window,
which is `capacity` on any row wider than it. `capacity = k + soft_trigger(k) +
unroll * tile`; the last two terms are multiples of `vec`, so whenever
`capacity % vec` was non-zero the loop read column `(base // vec) * vec + i` and
labelled it `base + i` -- every key after the window paired with a column
`base % vec` away from its own.

So the broken set was every k whose capacity was not a whole number of vectors,
not the two I happened to test. Measured at 64 rows of 32768, wrong rows out of
64: k=1 56, k=2 64, k=3 64, k=5 64, k=6 64, k=7 64; k=4, 8, 12, 16 clean. The
prediction matched on all ten. A row narrower than the window never enters the
loop, which is why one tile group was always right.

Fixed where it starts: the window rounds down to a whole number of vectors.
Rounding down rather than up keeps it inside the buffer, and it costs at most
three columns of a window that is thousands wide.

`topk_per_row_radix_stream_serves` goes back to `k >= 1`. The decline added in
145ca9c50a was both too narrow -- k=5, 6, 7 were still dispatched and still
wrong -- and no longer needed.

The soak missed this for the same reason I did: every shape in it used a k that
is a multiple of four. Five unaligned ones are now in it. 97 configs across
block widths 256/512/1024 and two seeds, all exact, including 1024x262144 at
k=1, 3 and 513.

* fix(topk): the argmax fold reads every partial, not one per thread

The fold kernel gave each thread exactly one partial and dropped the rest:

    in_range = tid < Int32(splits)
    slot = in_range.select(tid, zero)

so `splits > block_threads` silently lost the partials past the block, and the
answer was whatever the first `block_threads` slices held. I had written that
more splits than threads "never happens". It does: the split rule asks for
`vectors // 512` at one or two rows, which passes 256 once the row is wider than
524288 columns -- `m=1, n=1048576` shipped at 512 splits against a 256-thread
block, and was wrong.

Found by a sweep over (block width, split count) that was measuring something
else. Every one of its 34 wrong cells had `splits > block_threads` and none of
the others did.

A thread now folds every `block_threads`-th partial, so no split count can
violate the kernel's contract again -- which matters because the rule that picks
it is fitted, and a refit must not be able to reintroduce this. Slots ascend
within a thread, so its columns do too, and a strict `>` keeps the earliest of a
tie exactly as the slice path does.

240 (block, splits) combinations across six shapes are exact, including every
one that was wrong before; so are the shapes the shipped rule actually reaches
past the block, up to 1024 splits at one row of 2097152.

Also records why the block fold is an LDS tree rather than the usual wave
`shuffle_xor`: the barriers are not what it costs, measured -- a wider block
adds a fold step and still wins where the fold is heaviest.

* docs(topk): record that the argmax block width was swept, not guessed

`_BLOCK_THREADS = 256` was picked by hand. Swept jointly with the split rule --
64/128/256/512 against every split count on the same 34 cells -- because the two
are coupled: a narrower block absorbs less of a slice, which is what the split
rule decides, so one cannot be refitted without the other.

256 turns out to be the best single width. Against a per-cell (block, split)
oracle, holding one block and taking the best split per cell costs mean 1.043x
at 256, 1.046x at 128, 1.064x at 512 and 1.080x at 64. The shipped
configuration -- 256 plus the fitted split rule -- sits at 1.056x, so about 1.3%
is left in the split rule and the remainder needs a per-cell block choice. Three
forms of a block rule were tried against the sweep and every one was worse than
holding it flat, which is what coupling predicts: they reused a split rule
fitted at 256.

Left as it is, and the reasoning is in the file so the next person does not
repeat the sweep to reach the same answer.
RElbers pushed a commit that referenced this pull request Sep 25, 2026
…ntry (#5499)

* feat(topk): per-row top-k across four selectors behind one entry

`topk_select` picks between aiter's four per-row selectors, none of which
covers the whole domain. Two of them are new here:

  small_k  narrows to k chunks instead of sorting: partition the row into
           C >= k chunks, rank them by maximum, and the true top-k lives in
           the top-k chunks. A chunk is one lane's share, so the selection is
           a ballot -- no barrier, and the chunk maxima never leave registers.
           Fastest thing on the card below k=32, over rows 1..16384.
  stream   one workgroup per row, reading the row once, three radix passes
           over the 32-bit key. Owns the narrow rows and the large-M end of
           the wide ones.

The dispatch is fitted to a 232-cell sweep (M 1..16384, N 2048..1M,
k 16..4096, to 64 GiB) by `topk_fit_policy.py`, against a preference rather
than the stopwatch alone: among backends within 1.4x of the fastest it takes
the one whose answer is a function of the row. That costs a mean 1.063x and
lands a deterministic backend on 200 of the 232 cells; the rules it replaces
lost a mean 1.181x and a worst 4.18x.

The interface follows `deep_select.topk` so code ports across, and raises
rather than diverging silently where it cannot honour DeepSelect's behaviour
(int64 indices, the 2147483647 pad, bf16 input, NaN abort).

Also here:

* `kernel_signature` renders build parameters into a kernel-name suffix, so
  two builds that differ only in an omitted parameter stop emitting the same
  symbol -- indistinguishable in a profile and in a disassembly dump.
* The decode selector's buffer descriptors are built over the row, not the
  whole tensor: `num_records` is a 32-bit byte count, so at 4 GiB it wrapped
  to zero and every load returned zero, with nothing raised.
* Host cost on the serving path: the selectors are 7-10us of device time
  behind what was 47us of Python. Everything shape-derived is now resolved
  once per geometry (`@lru_cache` on scalars, the house pattern), which puts
  the entry at 21.7us.

* refactor(topk): one wave-size source, one dispatch lookup, no per-call scalars

Review follow-ups on the four-selector entry.

Correctness:
* `wave_size_of(device_index)` in tensor_shim is now the single source, read
  from the live GPU. `topk_select` asked `get_warp_size(get_gfx())`, which
  honours GPU_ARCHS, while the small_k wrapper asked the device -- so a build
  cross-targeting another arch picked a backend for a machine it was not
  running on, then built it for the one it was.

Host cost (gfx950, 64x8192, k=16, 2000 calls):
* `return_value=True` 48.7 -> 28.8us. The gather built a scalar tensor per call
  for `torch.where`'s fill; `gather` + `masked_fill_` drops an H2D, an
  allocation and a kernel. `idx.long().clamp_min_(0)` drops one more [rows, k].
* The backend decision is memoized as one step (`_choose`) instead of a set
  build, an intersection and a rule chain per call: 0.07us. Indices-only path
  7.8 -> 7.5us. The tables it reads are constants, so the one test that
  withholds a backend clears the cache around its patch.

Shape:
* `topk_per_row_radix_stream_serves()` mirrors small_k's predicate, so
  `_available` no longer builds a module to ask whether one can be built. The
  LDS budget search behind both is `_resolve_lds`; the build's dead
  `soft_trigger` pre-assignment went with it.
* `_reject_unsupported` takes keyword-only arguments -- nine positional
  parameters aligned by order at the one call site. `_dispatch` loses an
  unused `width`.

* perf(topk): small_k drops half its register tile and the redundant guards

The row read is latency-bound, not bandwidth-bound (k=1 over 32768 columns
runs 4.1 TB/s where the other two selectors reach 5.8), so what it spends per
element and per register is what it costs.

* The column tile is gone. Thread t's slot (v, j) is column `tid * _VEC +
  (v * block_threads * _VEC + j)`, and the bracket is a compile-time constant,
  so the columns were `elems_per_thread` registers holding one add -- 32 of the
  64 register tile at the widest bound. Step 3 recomputes them; its liveness
  test `cols[slot] >= 0` becomes the same `col < row_len`.
* `in_row` is dropped from the liveness test: a column past this thread's
  vectors is at least `n_max`, which already bounds `row_len`.
* The address no longer tests it either. The descriptor is built over one row,
  so `num_records` already clamps a read past the end to zero -- the select was
  software redoing the V#'s job, per vector, and made the address data-dependent.
* The running maximum splits into one accumulator per vector lane, chaining a
  v_max per vector rather than per element. Only where a thread holds more than
  one vector: at exactly one it shortens nothing, costs the fold, and measured
  7% slower before the guard went in.

Median-of-7 device time, gfx950, k=16:

    width x rows       before     after
    1024  x   64      3.88us    3.62us
    1024  x 1024      4.14us    3.74us
    8192  x   64      6.10us    4.89us
    8192  x 1024      7.59us    7.56us
    32768 x   64      7.28us    7.14us
    32768 x 1024     32.79us   31.63us

80-case sweep against torch (widths 256..32768, k 1..32, rows 1..1024, ragged
row lengths) exact; the NaN / +-0.0 / +-inf row unchanged; op_tests clean.

* fix(topk): the streaming selector declines k<=2, which it answers wrongly

At k=1 and k=2 it returns wrong rows in bulk -- 55 of 64 and 63 of 64 at 32768
gaussian columns -- and the dispatcher reached it: k=2 over a 1M-wide row at
256 rows or more picked it, and every row of the answer was wrong end to end.
A row narrow enough to fit one tile group is right at every k, so it is the
re-select path; k>=4 is clean at every width tried.

Declined in `topk_per_row_radix_stream_serves` rather than left to ship while
the cause is open. Those shapes now fall to decode and are exact. The cause
stays open: this kernel's own notes record that the last fault here survived a
ballot, an ordered load, wait states, LDS padding, four rewrites of the prefix
and both cross-lane primitives before the register pressure turned out to be
it, so a guess costs more than it saves.

* perf(topk): k=1 gets a split-row argmax instead of a selector

At k=1 the selectors build machinery the answer does not need: the small-k one
ranks chunks to bound a survivor set, where the top-1 chunk is just the chunk
holding the maximum; the radix ones walk the key space for a threshold that is
the answer. The dispatcher sent every k=1 call to small_k -- the rule had no
width term, having been fitted only to k=16 -- and it ran 12x behind `plain` at
1024 rows of 262144.

`topk_per_row_argmax` is the reduction instead, and it splits a row across as
many workgroups as it takes to fill the part. That is the point: one workgroup
per row leaves a 50-row call using a fifth of the GPU, which is the ceiling
`torch.argmax` is stuck at too.

n=129280, k=1, through the entry, against torch's own reduction (interleaved,
median of 9; every row verified equal to `torch.argmax`):

    rows      1     16     64    256    512   1024
    ours   5.77   7.09  10.28  25.73  43.83  97.48 us
    torch 29.25  30.10  34.88  41.43  57.20  96.66 us
    gain   5.1x   4.2x   3.4x   1.6x   1.3x   1.0x

Against the backend that used to be picked: 2.8x-5.1x over the same range. The
two converge at 1024 rows, where both reach 5.4 TB/s and the rows fill the part
without help. Elsewhere: 20.4x at one row of 262144, 12.7x at 1024 rows of
262144.

The split count is fitted to a 34-cell sweep against the best count measured at
each cell -- mean 1.015x, worst 1.087x. It is three interacting constants; the
one that is not obvious is the short-row guard, without which a 1024-row call
over a 32768-wide row (decode against a vocabulary) splits four ways and loses
13% where one split is already at 6.05 TB/s.

Ties go to the smallest column, matching `torch.argmax` and the order decode and
the streaming selector already promise, so `tie='low'` can be served by it too.
NaN outranks +inf as everywhere else here, which is why `ord_signed_f32` moved
to `kernels_common` rather than being copied: the dispatcher picks by shape, so
a row holding a NaN must not answer differently for a choice the caller did not
make.

Also reformats two files this branch had left non-black-clean.

* fix(topk): align the streaming selector's window, and drop the k<=2 decline

Root cause of the wrong rows, and it was never about k<=2.

`absorb` takes an element's column from its own `base` but its address from
`base // vec`. `base` is where the streaming loop starts, which is the window,
which is `capacity` on any row wider than it. `capacity = k + soft_trigger(k) +
unroll * tile`; the last two terms are multiples of `vec`, so whenever
`capacity % vec` was non-zero the loop read column `(base // vec) * vec + i` and
labelled it `base + i` -- every key after the window paired with a column
`base % vec` away from its own.

So the broken set was every k whose capacity was not a whole number of vectors,
not the two I happened to test. Measured at 64 rows of 32768, wrong rows out of
64: k=1 56, k=2 64, k=3 64, k=5 64, k=6 64, k=7 64; k=4, 8, 12, 16 clean. The
prediction matched on all ten. A row narrower than the window never enters the
loop, which is why one tile group was always right.

Fixed where it starts: the window rounds down to a whole number of vectors.
Rounding down rather than up keeps it inside the buffer, and it costs at most
three columns of a window that is thousands wide.

`topk_per_row_radix_stream_serves` goes back to `k >= 1`. The decline added in
145ca9c50a was both too narrow -- k=5, 6, 7 were still dispatched and still
wrong -- and no longer needed.

The soak missed this for the same reason I did: every shape in it used a k that
is a multiple of four. Five unaligned ones are now in it. 97 configs across
block widths 256/512/1024 and two seeds, all exact, including 1024x262144 at
k=1, 3 and 513.

* fix(topk): the argmax fold reads every partial, not one per thread

The fold kernel gave each thread exactly one partial and dropped the rest:

    in_range = tid < Int32(splits)
    slot = in_range.select(tid, zero)

so `splits > block_threads` silently lost the partials past the block, and the
answer was whatever the first `block_threads` slices held. I had written that
more splits than threads "never happens". It does: the split rule asks for
`vectors // 512` at one or two rows, which passes 256 once the row is wider than
524288 columns -- `m=1, n=1048576` shipped at 512 splits against a 256-thread
block, and was wrong.

Found by a sweep over (block width, split count) that was measuring something
else. Every one of its 34 wrong cells had `splits > block_threads` and none of
the others did.

A thread now folds every `block_threads`-th partial, so no split count can
violate the kernel's contract again -- which matters because the rule that picks
it is fitted, and a refit must not be able to reintroduce this. Slots ascend
within a thread, so its columns do too, and a strict `>` keeps the earliest of a
tie exactly as the slice path does.

240 (block, splits) combinations across six shapes are exact, including every
one that was wrong before; so are the shapes the shipped rule actually reaches
past the block, up to 1024 splits at one row of 2097152.

Also records why the block fold is an LDS tree rather than the usual wave
`shuffle_xor`: the barriers are not what it costs, measured -- a wider block
adds a fold step and still wins where the fold is heaviest.

* docs(topk): record that the argmax block width was swept, not guessed

`_BLOCK_THREADS = 256` was picked by hand. Swept jointly with the split rule --
64/128/256/512 against every split count on the same 34 cells -- because the two
are coupled: a narrower block absorbs less of a slice, which is what the split
rule decides, so one cannot be refitted without the other.

256 turns out to be the best single width. Against a per-cell (block, split)
oracle, holding one block and taking the best split per cell costs mean 1.043x
at 256, 1.046x at 128, 1.064x at 512 and 1.080x at 64. The shipped
configuration -- 256 plus the fitted split rule -- sits at 1.056x, so about 1.3%
is left in the split rule and the remainder needs a per-cell block choice. Three
forms of a block rule were tried against the sweep and every one was worse than
holding it flat, which is what coupling predicts: they reused a split rule
fitted at 256.

Left as it is, and the reasoning is in the file so the next person does not
repeat the sweep to reach the same answer.
ClementLinCF added a commit to AFDEAPAC/aiter that referenced this pull request Oct 2, 2026
topk_select checks the shape and dtype of `input`, `end` and `output_idx`,
and of their strides only that `input` has unit inner stride; but several
backends read or write dense rows:

- plain read a row-strided input -- a column slice of a wider tensor, for
  one -- as dense rows and returned a wrong top-k, on every kernel family
  (register, wide first digit, 512-thread, LDS tail with and without the
  sampled stage, generic radix, block sort), uniform and ragged.  The call
  sites pass stride0 = -1, which the C++ side reads as "rows width apart",
  and its uniform form takes no row pitch at all; only the ranged form
  reads row r at r * stride0.
- plain, argmax and sampled wrote dense rows into a row-strided
  output_idx, and decode refused it.
- every backend read a strided `end` as dense, and decode refused it.

argmax, small_k, the streaming selector (all its forms), decode and sampled
already read a row-strided input correctly.

The public topk_plain wrapper now takes the layout from the tensor: in the
ranged form, which also sizes its launch and scratch by stride0, a row with
unit inner stride and a pitch at least the width is read in place, with
stride0 taken from the tensor when left at -1; every other non-dense
input is handed over densely.  The entry hands every backend a dense
`end`, and, when `output_idx` is not dense, a dense result that it copies
into `output_idx` at the end, as it already does for a reordered result.
A contiguous tensor takes exactly the path it took before; the kernels are
unchanged (the device code is byte-identical).  The cost falls only on the
layouts that were wrong: one copy of the input for a strided uniform plain
call, of the row ends for a strided `end`, and of the result for a
strided output_idx.  Passing the pitch to every kernel instead would change
the machine code of every plain kernel for a layout the uniform form does
not otherwise see.

The bug came with topk_select itself (d81eb48, ROCm#5499); the "-1 means
rows width apart" default dates from 1532816 (ROCm#1578).

Tests: test_topk_select.py gains test_strided_layouts (12 routes x 4
layouts: strided input, strided input with ragged rows, strided output_idx
with guard columns, strided end), and test_topk_plain.py gains
test_strided_rows (padded and broadcast rows through both forms, stride0
left at -1 and given).  Before this change the first fails 39 of its 48
cases and the second ends the process with SIGFPE (the ranged form given a
broadcast tensor's own stride 0); after it both pass.
jhinpan pushed a commit to sgl-project/sgl-amd-mono that referenced this pull request Nov 17, 2026
…experts on the FP4 MFMA, NextN draft included) (#123)

## Motivation

`amd/GLM-5.2-MXFP4` shares GLM-5.3's architecture
(`GlmMoeDsaForCausalLM`, NextN draft `GlmMoeDsaForCausalLMNextN`), and
the glm53 monokernel already has an MXFP4 expert path (`expert_mxfp4`,
`atom_experts`, `native_fp4_mfma`). This PR brings GLM-5.2 FP4 on MI355X
onto the glm53 monokernels: the spec takes the Quark checkpoint (MXFP4
routed experts, bf16 for every other linear), the weights are read or
copied into the kernel's layouts, and the NextN draft runs on the
monokernel too.

At TP8 with MTP3, decode TPOT at concurrency 1 drops from 3.21 ms
(current recipe) to 1.86 ms at 64K context. In AgentX, c1 P90
interactivity rises 52% and throughput per GPU 37% over the current
MI355X recipe, which puts c1 interactivity at 128% of B300.

## Accuracy Tests

TP8 / EP1, MI355X, `amd/GLM-5.2-MXFP4`, fp8_e4m3 KV, MTP3
(`--speculative-num-steps 3 --speculative-eagle-topk 1
--speculative-num-draft-tokens 4`), real acceptance, monokernels on and
off on the same server build.

GSM8K, 400 questions:

| | Accuracy | Accept length |
|---|---|---|
| `--enable-amd-monokernel` | 0.963 | 3.27 |
| off | 0.935 | 3.27 |

Check mode (`SGLANG_AMD_MONO_CHECK`), monokernel against SGLang's
forward on the same steps: target layer outputs at median cosine 0.9987,
LM-head top-1 agreeing on every step, and draft tokens identical in 878
of 882 over a longer run on SGLang `af633e1759` (the other 4 are
near-ties, top-2 logit gap 0.125). The only bound violations are
`dense.excess.rel` on layers 0 to 2 (up to 0.37 against 0.11) and
`draft.eh.rel` (up to 0.0043 against 0.0014). Both come from the bf16
linears the monokernel runs as block FP8 while SGLang's reference stays
bf16; the bounds were set for the FP8 checkpoint, where both sides read
the same weights. GSM8K shows no loss.

## Speed Tests and Profiling

Decode TPOT in ms, TP8, input 65536 / output 8192, synthetic acceptance
at the GLM-5.2 golden lengths (`SGLANG_SIMULATE_ACC_LEN` 3.61 for MTP5,
2.99 for MTP3):

| Setting | c1 | c2 | c4 |
|---|---|---|---|
| off, MTP5 (current recipe) | 3.21 | 3.49 | 4.11 |
| off, MTP3 | 3.45 | 3.80 | 4.20 |
| on, MTP3 (this PR) | **1.86** | **2.81** | 4.25 |

A verify step has requests × (steps + 1) rows and the widths are 2 / 4 /
8, so with MTP3 the target launch covers c1 and c2; at c4 (16 rows) the
target runs SGLang's forward and the draft stays on the monokernel. MTP3
suits the monokernel better than MTP5, whose 6-row verify fits only at
c1 and whose longer accept length does not pay for the extra rows and
draft steps.

AgentX (agentic-coding trace) on the InferenceX GLM-5.2 FP4 MI355X
SGLang recipe, TP8 / EP1 / no DCP, one hour per point. Baseline is the
current recipe (MTP5, monokernel off); this PR runs MTP3 with the
monokernel.

| Conc | | P90 interactivity (tok/s/user) | Throughput / GPU (tok/s) |
P90 TTFT (s) | P90 E2E (s) |
|---|---|---|---|---|---|
| 1 | baseline | 277.008 | 2436.195 | -- | -- |
| 1 | this PR | 420.650 (+51.9%) | 3326.175 (+36.5%) | 0.914 | 11.038 |
| 2 | baseline | 242.718 | 2615.466 | -- | -- |
| 2 | this PR | 334.320 (+37.7%) | 3376.088 (+29.1%) | 0.712 | 10.275 |
| 4 | baseline | 229.358 | 3817.032 | -- | -- |
| 4 | this PR | 266.491 (+16.2%) | 4478.177 (+17.3%) | 0.727 | 10.071 |

Against the published B300 GLM-5.2 FP4 SGLang result, c1 goes from 84.5%
to 128.3% in interactivity and from 66.7% to 91.1% in throughput; c4
from 83.0% to 96.5% and from 79.6% to 93.4%. The final commit on `main`,
rerun at c1 on the stack below, measured 447.480 / 3323.738 (0.874 s P90
TTFT, 10.839 s P90 E2E), in line with the table.

c4 needs sgl-project/sglang#48773: without it, top-k v2 on ROCm picks
wrong indices on split-launch short rows (a regression from
sgl-project/sglang#47960) and the server crashes about 30 minutes into
the trace. With it, every point runs the full hour with no request
errors.

Tested against:
- Accuracy, TPOT and the AgentX table: the SGLang ROCm 7.2 nightly
`lmsysorg/sglang-rocm:v0.5.23-rocm720-mi35x-20261105` (SGLang
`1305b1830a`, AITER `285579b6`, FlyDSL 0.4.0, sgl-amd-mono `e52803f`)
with this PR and sgl-project/sglang#48773 applied.
- The c1 rerun: this PR on sgl-amd-mono `b9f40eb` (`main`), SGLang
`af633e1759`, AITER `acf8fdf93`, FlyDSL 0.4.2. That AITER predates
ROCm/aiter#5499 (`kernel_signature`), so the run carried a local
fallback in `common/epoch.py`; it is not part of this PR and the
nightly's AITER does not need it.

## Checklist

- [x] `pre-commit run` passes on the changed files.
- [x] Tests under `test/` cover the change. `test_glm53_spec.py`,
`test_glm53_draft.py` and `test_glm53_select.py`: 238 passed. Full
`test/unit`: 10 failed / 603 passed, against 10 failed / 593 passed on
`main` (`b9f40eb`); the 10 are the same pre-existing failures in
`test_contract.py` and the kimi_k3 / kimi_k31 forward-drift tests.
- [x] The SGLang commit or PR this was tested against is named above.
- [x] Accuracy and speed results are attached.
- [ ] A new model adds one line to `.github/CODEOWNERS`. Not applicable:
GLM-5.2 is served by the existing glm53 package.
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