Skip to content

[FlyDSL] Add flydsl radix topk one block kernel - #5363

Merged
lirui927 merged 57 commits into
mainfrom
lirui/flydsl_topk_gfx1250
Sep 18, 2026
Merged

lirui927 merged 57 commits into
mainfrom
lirui/flydsl_topk_gfx1250

Conversation

@lirui927

@lirui927 lirui927 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

This PR adds a FlyDSL one-block radix per-row TopK kernel and wires it into the default dispatch on gfx950, and gfx1250, replacing the HIP one-block path in those cases.

Goals:

  • Prefill (variable-length rows described by row_starts / row_ends) and decode (seq_lens / next_n) share the same kernel.
  • Support any positive integer k, optional values output, and deterministic stable mode.
  • Keep short-row semantics: when a row has fewer than k live elements, pad indices with -1 and values with -inf.
  • Replace only the HIP one-block coverage. Existing multi-block paths and other fallbacks stay unchanged, which limits the risk of turning this on by default.

Implementation

One-block radix TopK

New file: aiter/ops/flydsl/kernels/topk/radix_topk_one_block.py.

  • One workgroup per row.
  • Short rows (physical width <= 4096) cache sorted keys in LDS. Long rows use a radix histogram plus candidate compaction, and fall back to a global-memory rescan if candidates overflow LDS.
  • If row_len <= k, skip radix selection and copy/pad the output directly.
  • gfx1250 uses wave32; gfx950 use wave64.
  • Block size depends on short-row width and row count: 256 threads for short rows with rows <= 256, otherwise 1024.
  • Stable output is sorted by index ascending (smaller index wins ties). Values always stay aligned with the corresponding indices.

Dispatch

  • Prefill: on the non-multi-block branch, try FlyDSL one-block first; fall back to HIP if _is_flydsl_radix_topk_one_block_supported returns false.
  • Decode: insert the same FlyDSL one-block attempt before the existing path.
  • Supported arches are _FLYDSL_TOPK_ONE_BLOCK_ARCHES = ("gfx950", "gfx1250").
  • Dispatch reads only physical logits.shape[1] and the row count, not device-side row bounds, so it is CUDAGraph-safe.
  • This PR does not change the existing topk_use_mulblocks multi-block path or per-arch HIP fallbacks.
  • New prefill kill-switch; decode reuses the existing one:
AITER_DISABLE_FLYDSL_TOPK_PREFILL=1   # added in this PR
AITER_DISABLE_FLYDSL_TOPK_DECODE=1    # existing

Layout cleanup

TopK files are grouped into their own subpackages. In this PR these moves are renames only:

  • aiter/ops/flydsl/kernels/topk/ — six kernel modules.
  • aiter/ops/flydsl/topk/ — three launch wrappers.

Optimizations for concentrated value distributions

Real logits often span a narrow range, so radix bins on float bits collapse onto a few buckets. That causes atomic contention on the first-pass histogram, and more first-pass survivors than the LDS candidate buffer can hold. This PR addresses both:

  • Wider first radix digit. A finer first pass cuts both surviving candidates and the number of lanes hitting the same bin. At the same LDS cost, this is cheaper than replicating a coarser first pass. Later digits keep the same bin counts, so the candidate buffer is unaffected.
  • Grow the candidate buffer from leftover LDS. If candidates overflow the buffer, pass 3 and the final emit rescan the full row in global memory (2 global passes become 4). More concentrated distributions hit this more often. The candidate buffer now takes the remaining LDS budget instead of a fixed 4096 entries.
  • Scatter pass-1 atomics by lane. Histogram replicas are chosen by lane, not by wave: when one bin owns most of a row, a whole wave no longer serializes onto one address. Wave-index replicas only split waves that were already concurrent, which does not help.
  • In-wave reduction for same-bin vectors. If the four keys from one vector load share the same first-pass digit, ballot-merge the counts in the wave and issue a single atomic add. More concentrated data means neighboring elements share a bin more often.

These changes affect performance only; output semantics are unchanged.

Correctness

op_tests/test_topk_per_row.py now calls the one-block kernel directly (bypassing dispatch). On supported arches, each prefill shape also runs the four stable × write_values combinations, so dispatch changes cannot hide a kernel regression.

Coverage:

  • Prefill and decode.
  • Full rows, padded rows, and non-zero row starts.
  • next_n=1 and MTP decode.
  • Stable and unstable.
  • Indices-only and indices+values.
  • Random inputs and several degrees of value ties.
  • Workspace reuse and CUDAGraph replay.

How to test

python -m op_tests.test_topk_per_row
python -m op_tests.test_topk_per_row_stable

Performance

Method

  • Latency after CUDAGraph capture: 3 warmups, 5 alternating HIP / FlyDSL rounds, median. Both HIP and FlyDSL use one-block.
  • Full rows, padding, and uneven logits (narrow, single-peak, few discrete values).
  • M (rows): 1, 2, 16, 32, 52, 64, 128, 512, 1024, 4096, 16384.
  • N (width): 128, 4096, 4097, 16384, 32768, 65536, 98304, 131072, 164401, 200000.
  • K: 128, 512, 2048, 4096.

GFX1250

Conclusion: default FlyDSL one-block is faster overall, with no systematic regression.
775 cases, geomean 1.41×; 731 faster, 44 slower.

Scenario n Geomean speedup Faster
All 775 1.41× 731/775
Prefill 377 1.40× 355/377
Decode 398 1.42× 376/398
Uneven distribution 214 1.36× 210/214

Representative points (k=2048, stable+values, full rows):

rows × width Prefill Decode
1 × 4096 1.78× 1.82×
16 × 65536 1.51× 1.37×
64 × 65536 1.51× 1.48×
128 × 131072 1.40× 1.38×
16384 × 4096 2.51× 2.78×
16384 × 200000 1.18× 1.29×

Of the 44 slower cases, 42 differ by at most 5 µs; the median relative regression is 3.3%. The remaining 2 cases regress by 6.6%–6.9%.

GFX950

Conclusion: default FlyDSL one-block is faster overall, with no systematic regression.
775 cases, geomean 1.44×; 741 faster, 34 slower (worst about 0.88×, ~5.5 µs slower).

Scenario n Geomean speedup Faster
All 775 1.44× 741/775
Prefill 377 1.44× 360/377
Decode 398 1.44× 381/398
Uneven distribution 214 1.40× 195/214

Representative points (k=2048, stable+values, full rows):

rows × width Prefill Decode
1 × 4096 1.65× 1.75×
16 × 65536 1.68× 1.49×
64 × 65536 1.67× 1.69×
128 × 131072 1.68× 1.73×
16384 × 4096 2.30× 2.35×
16384 × 200000 1.52× 1.53×

Slower cases are mostly large batches that also write values; most are only a few percent slower, typically about 5 µs.

Checklist

@github-actions

github-actions Bot commented Sep 9, 2026

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

@lirui927
lirui927 marked this pull request as ready for review September 9, 2026 13:27
@lirui927
lirui927 requested a review from a team September 9, 2026 13:27
@github-actions github-actions Bot added the FlyDSL label Sep 9, 2026
@zufayu
zufayu requested a review from coderfeli September 10, 2026 02:39
@lirui927
lirui927 force-pushed the lirui/flydsl_topk_gfx1250 branch from 9c21608 to b431360 Compare September 10, 2026 02:44
@lirui927 lirui927 changed the title [FlyDSL] Add gfx1250 radix topk one block [FlyDSL] Add radix topk one block Sep 10, 2026
@lirui927
lirui927 marked this pull request as draft September 10, 2026 08:30
@lirui927
lirui927 marked this pull request as ready for review September 10, 2026 14:59
@lirui927 lirui927 changed the title [FlyDSL] Add radix topk one block [FlyDSL] Add radix topk one block and refactor FlyDSL TopK dispatch Sep 10, 2026
@lirui927 lirui927 changed the title [FlyDSL] Add radix topk one block and refactor FlyDSL TopK dispatch [FlyDSL] Add flydsl radix topk one block kernel and refactor flydsl topk dispatch Sep 10, 2026
lirui927 and others added 16 commits September 14, 2026 22:29
The six TopK kernel modules were loose in kernels/ alongside unrelated
families. Move them into kernels/topk/ and update the five importers.

Co-Authored-By: Claude Opus 5 <[email protected]>
@lirui927
lirui927 force-pushed the lirui/flydsl_topk_gfx1250 branch from 3bb05d9 to 2628565 Compare September 15, 2026 07:50
Mirrors the kernels/topk/ grouping: the three TopK launch wrappers move
out of flydsl/ into flydsl/topk/, and the ten importers follow.

Co-Authored-By: Claude Opus 5 <[email protected]>
@lirui927
lirui927 marked this pull request as ready for review September 15, 2026 11:17
lirui927 and others added 9 commits September 15, 2026 19:18
Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	aiter/ops/flydsl/topk/topk_per_row_argmax.py
#	aiter/ops/flydsl/topk/topk_per_row_small_k.py
#	aiter/ops/topk_select.py
None of this changes what the kernel selects.

- stable_stage_capacity was an alias for stable_sort_capacity.
- The candidate column array is written and read only under
  `not stable or stable_sort_enabled`, so the other configuration no longer
  pays for it: the entry size drops to the key alone, which doubles the
  candidate buffer at stable k > 2048 (9458 -> 18917 on gfx950, 16106 ->
  32213 on gfx1250) and pushes back the global rescan.
- merge_histograms folded a lone replica into itself, costing a pass over
  the bins plus a barrier on every row of the gfx950/gfx1250 long path.
- accumulate_prefix_histogram re-tested a bound its callers already hold,
  and the column it took for that test is now unused.
- choose_threshold took the one metadata slot and the one scan storage that
  all six call sites pass.
- write_direct_scalar is only reached at k <= block_threads, so its outer
  loop always ran once.
- The decode row bounds are _row_length, already imported here.
- The three radix levels have to cover the whole key; say so where the
  table is read, and name the LDS budget by its table rather than by the
  one architecture that first had an entry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The inline transform matched _f32_to_ord bit for bit except that it left
NaN alone, so a negative NaN sorted below -inf instead of above +inf. Which
selector serves a call is a shape decision -- inside top_k_per_row_decode,
a shape in the _FLYDSL_TOPK_DECODE_GATES bands goes to the multi-block
kernel and a shape outside them lands here -- so the same row answered
differently depending on a choice the caller never made. That is the case
ord_signed_f32 exists to rule out, and it folds -0.0 onto +0.0 as well, so
the stable contract's smallest-index tie-break now holds for signed zeros.

On a row carrying both NaN signs the one-block kernel now selects the same
columns as the multi-block kernel and as torch.topk.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
get_gfx() honours GPU_ARCHS, which is what build-time codegen wants and the
opposite of what this dispatch wants: the arch chooses the wave size, the
LDS budget and the radix widths, so a GPU_ARCHS that names another card
builds a kernel the device cannot match -- get_warp_size spells out that a
wrong wave size silently drops the upper lanes' work. The multi-block
launcher next door already reads the device. With GPU_ARCHS=gfx1250 on a
gfx950 the one-block path picked wave32 and a 158K budget; it now picks
gfx950 and wave64.

Also drop the stable argument the predicate discarded and the row_starts
branch its only caller cannot reach.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both sweeps recorded all_close into the summary table and nothing read it
back, so a kernel that selected the wrong columns printed False in a
markdown row and still exited 0. Assert on the column instead, with the
table as the message.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
One flag gated both sweeps, so widening it for the one-block prefill kernel
also started driving the multi-block decode kernel on gfx1250 -- an arch
_FLYDSL_TOPK_DECODE_GATES has no entry for, so production never dispatches
it there. Ask each path for its own list instead of keeping a third copy in
the test, and the two sweeps stop moving together.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The one-block kernel measured no clear win on gfx942, and it has no
_ONE_BLOCK_LDS_BUDGET_BYTES entry, so its candidate buffer sits at the 4096
compact floor and overflows into the four-pass global rescan far sooner
than on the two arches that do. Prefill and decode there fall back to HIP
the way they did before this PR; the sweeps follow the list on their own.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@coderfeli

Copy link
Copy Markdown
Collaborator

LGTM

@lirui927
lirui927 merged commit 87cf2f5 into main Sep 18, 2026
52 of 56 checks passed
@lirui927
lirui927 deleted the lirui/flydsl_topk_gfx1250 branch September 18, 2026 07:12
JH-Leon-KIM-AMD added a commit that referenced this pull request Sep 20, 2026
The table is keyed by (arch, CU count) and had one entry, so MI355X kept the
upstream path. This adds its entry, fitted from its own 1000-cell sweep rather
than reused from the other card: the two share no number, and the shape of the
result differs because the fallback does. gfx950 is in
_FLYDSL_TOPK_ONE_BLOCK_ARCHES, so a declined cell here runs #5363's FlyDSL port,
which wins 554 of the 1000 cells outright and is a much harder baseline than the
C++ kernel gfx942 falls back to.

Measured on MI355X (gfx950, 256 CU) over 1000 cells covering k 256..4096, width
4K..1M and 1..512 rows, in the same three passes as gfx942. Scoring every cell
rather than the ones the gate takes, and picking each declined cell's baseline
out of upstream's own arch-keyed chunked gate, the table returns 1.133x geomean
with no cell behind, at slack 1.00. Loosening slack to 1.10 does not raise that
number at all on this card and puts 87 cells more than 3% behind, so 1.00 stands
for a sharper reason here than it did there.

k=256 carries the result: _FLYDSL_TOPK_DECODE_KS stops at 512, so upstream never
runs its chunked path there and all 200 of those cells fall back to the port.
Over the 67 the table takes it is 2.077x, against 1.28x to 1.31x for every other
k group. Run without the table the kernel is 0.896x of the per-cell oracle with
349 cells more than 10% off the best, so the result is the gate's, not the
kernel's.

The routing check runs both sides of all 91 band edges of this entry on the card
and confirms the kernel the table names is the one that launches, 91/91.

Co-Authored-By: Claude Opus 5 <[email protected]>
JH-Leon-KIM-AMD added a commit that referenced this pull request Sep 20, 2026
The table is keyed by (arch, CU count) and had one entry, so MI355X kept the
upstream path. This adds its entry, fitted from its own 1000-cell sweep rather
than reused from the other card: the two share no number, and the shape of the
result differs because the fallback does. gfx950 is in
_FLYDSL_TOPK_ONE_BLOCK_ARCHES, so a declined cell here runs #5363's FlyDSL port,
which wins 554 of the 1000 cells outright and is a much harder baseline than the
C++ kernel gfx942 falls back to.

Measured on MI355X (gfx950, 256 CU) over 1000 cells covering k 256..4096, width
4K..1M and 1..512 rows, in the same three passes as gfx942. Scoring every cell
rather than the ones the gate takes, and picking each declined cell's baseline
out of upstream's own arch-keyed chunked gate, the table returns 1.133x geomean
with no cell behind, at slack 1.00. Loosening slack to 1.10 does not raise that
number at all on this card and puts 87 cells more than 3% behind, so 1.00 stands
for a sharper reason here than it did there.

k=256 carries the result: _FLYDSL_TOPK_DECODE_KS stops at 512, so upstream never
runs its chunked path there and all 200 of those cells fall back to the port.
Over the 67 the table takes it is 2.077x, against 1.28x to 1.31x for every other
k group. Run without the table the kernel is 0.896x of the per-cell oracle with
349 cells more than 10% off the best, so the result is the gate's, not the
kernel's.

The routing check runs both sides of all 91 band edges of this entry on the card
and confirms the kernel the table names is the one that launches, 91/91.

Co-Authored-By: Claude Opus 5 <[email protected]>
JH-Leon-KIM-AMD added a commit that referenced this pull request Sep 20, 2026
The table is keyed by (arch, CU count) and had one entry, so MI355X kept the
upstream path. This adds its entry, fitted from its own 1000-cell sweep rather
than reused from the other card: the two share no number, and the shape of the
result differs because the fallback does. gfx950 is in
_FLYDSL_TOPK_ONE_BLOCK_ARCHES, so a declined cell here runs #5363's FlyDSL port,
which wins 554 of the 1000 cells outright and is a much harder baseline than the
C++ kernel gfx942 falls back to.

Measured on MI355X (gfx950, 256 CU) over 1000 cells covering k 256..4096, width
4K..1M and 1..512 rows, in the same three passes as gfx942. Scoring every cell
rather than the ones the gate takes, and picking each declined cell's baseline
out of upstream's own arch-keyed chunked gate, the table returns 1.133x geomean
with no cell behind, at slack 1.00. Loosening slack to 1.10 does not raise that
number at all on this card and puts 87 cells more than 3% behind, so 1.00 stands
for a sharper reason here than it did there.

k=256 carries the result: _FLYDSL_TOPK_DECODE_KS stops at 512, so upstream never
runs its chunked path there and all 200 of those cells fall back to the port.
Over the 67 the table takes it is 2.077x, against 1.28x to 1.31x for every other
k group. Run without the table the kernel is 0.896x of the per-cell oracle with
349 cells more than 10% off the best, so the result is the gate's, not the
kernel's.

The routing check runs both sides of all 91 band edges of this entry on the card
and confirms the kernel the table names is the one that launches, 91/91.
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.

5 participants