Skip to content

[FlyDSL] Single-Launch Dynamic Decode TopK - #6329

Merged
valarLip merged 13 commits into
mainfrom
lirui/1009
Oct 14, 2026
Merged

valarLip merged 13 commits into
mainfrom
lirui/1009

Conversation

@lirui927

@lirui927 lirui927 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Single-Launch Dynamic Decode TopK

Motivation

PR #5011 introduced Multi-CTA Radix-Select TopK for long sequences, but its execution configuration is determined primarily by the physical buffer width. With wide padded buffers or mixed decode workloads, rows with short effective lengths may still execute multiple kernels designed for long rows, incurring substantial fixed launch and phase-coordination overhead.

This PR implements a single-launch dynamic Decode TopK. The kernel selects each row's parallelism from its effective length on the device: one CTA writes short-row results directly, while long rows are split across multiple CTAs that compute local TopK results. The last arriving CTA performs the final merge within the same kernel.

Technical Details

Dynamic Local TopK

  • The kernel computes each row's effective length from seq_lens.
  • Long rows dynamically select 1/2/4/8/16 active parts.
  • Unstable mode targets approximately 32K elements per part; Stable mode targets approximately 64K elements per part.
  • One CTA independently computes local TopK for each active part.
  • Rows requiring only one part write final indices/values directly without writing the partial workspace.
  • Inactive CTAs exit immediately.

Last-Arriver Final Merge

Each active CTA computes local TopK
→ writes partial candidates
→ performs an agent release fence
→ performs an atomic arrival
→ non-last CTAs exit
→ the last arriving CTA performs an agent acquire fence
→ final merge completes in the same kernel
  • CTAs never spin-wait for one another, and the grid does not require all CTAs to be resident simultaneously, avoiding grid-residency deadlocks.
  • The last arriving CTA resets the arrival counter to zero for the next invocation or Graph replay.
  • Local selection and merge reuse the same one-block radix selector and LDS allocation.
  • Candidate positions map directly back to original global IDs, so no additional remap kernel is required.
  • The implementation supports stable/unstable output, indices-only/values output, next_n, and mixed short/long rows.

Test Plan

Host+device CUDAGraph tests use the production top_k_per_row_decode interface. Inputs remain fixed. After eager and CUDAGraph warmup, CPU wall-clock timing measures one graph.replay() followed by stream synchronization; results are the median of 31 runs.

Performance coverage:

  • All-short: wide padded buffers with effective lengths of 4K/16K/20K/48K and row counts from 1 to 32.
  • Mixed: 25%/50%/80% long rows with physical widths of 512K/1M.
  • All-long: 128K, 256K, 512K, and 1M with row counts from 1 to 32.

Correctness coverage:

  • stable/unstable
  • indices-only/values
  • next_n
  • equal-score ties
  • workspace rearm
  • CUDAGraph replay
  • concurrent multi-Graph and multi-stream execution

Test Results

gfx950

Selected unstable host+device CUDAGraph results:

Case Shape / Effective Length HIP one-block Original multi-kernel Current single-kernel
All-short rows=1, width=1M, length=512 22.41 us 29.35 us 19.54 us
All-short rows=1, width=1M, length=16K 30.45 us 41.81 us 31.12 us
All-short rows=2, width=1M, length=20K 31.67 us 44.58 us 31.75 us
All-short rows=16, width=1M, length=4K 26.91 us 51.04 us 26.03 us
All-short rows=32, width=1M, length=48K 45.43 us 46.31 us 42.76 us
Mixed, 80% long rows=20, width=512K, 16×512K + 4×4K 199.56 us 70.88 us 66.79 us
Mixed, 50% long rows=16, width=512K, 8×512K + 8×4K 197.16 us 61.77 us 66.11 us
Mixed, 50% long rows=16, width=1M, 8×1M + 8×4K 364.63 us 79.59 us 77.40 us
Mixed, 25% long rows=16, width=1M, 4×1M + 12×4K 302.86 us 77.24 us 74.43 us
Mixed, 20% long rows=20, width=512K, 4×512K + 16×4K 164.68 us 60.00 us 64.25 us
All-long rows=1, width=128K 64.87 us 45.04 us 47.81 us
All-long rows=4, width=128K 64.49 us 45.55 us 47.61 us
All-long rows=32, width=128K 74.31 us 46.56 us 51.28 us
All-long rows=4, width=256K 115.23 us 47.20 us 53.87 us
All-long rows=16, width=256K 115.95 us 48.56 us 56.67 us
All-long rows=16, width=512K 197.35 us 66.65 us 69.01 us
All-long rows=32, width=512K 223.55 us 84.24 us 71.10 us
All-long rows=16, width=1M 403.02 us 91.23 us 81.73 us
  • All-short: compared with HIP one-block, the 16K case regresses by approximately 2%, the 20K case is roughly equal, and the other cases improve by approximately 1.03x–1.15x. Compared with the original multi-kernel implementation, all cases improve by approximately 1.08x–1.96x.
  • Mixed: approximately 2.56x–4.71x faster than HIP one-block. Compared with the original multi-kernel implementation, the 80%-long and 1M cases improve by approximately 1.03x–1.06x, while the 512K 50%- and 20%-long cases regress by approximately 7%.
  • All-long: approximately 1.35x–4.93x faster than HIP one-block. Compared with the original multi-kernel implementation, 128K regresses by approximately 5%–10%, 256K by approximately 14%–17%, and rows=16 at 512K by approximately 4%; rows=32 at 512K and rows=16 at 1M improve by approximately 1.18x and 1.12x.

Stable host+device CUDAGraph results for the same cases:

Case Shape / Effective Length HIP one-block Original multi-kernel Current single-kernel
All-short rows=2, width=1M, length=20K 45.61 us 47.86 us 37.68 us
All-short rows=16, width=1M, length=4K 29.24 us 51.54 us 25.32 us
All-short rows=1, width=1M, length=16K 40.96 us 46.54 us 34.65 us
All-short rows=32, width=1M, length=48K 57.35 us 50.10 us 43.60 us
Mixed, 80% long rows=20, width=512K, 16×512K + 4×4K 212.96 us 83.43 us 72.50 us
Mixed, 20% long rows=20, width=512K, 4×512K + 16×4K 176.89 us 68.37 us 67.22 us
Mixed, 50% long rows=16, width=512K, 8×512K + 8×4K 209.24 us 63.75 us 68.27 us
Mixed, 50% long rows=16, width=1M, 8×1M + 8×4K 378.67 us 87.37 us 86.70 us
Mixed, 25% long rows=16, width=1M, 4×1M + 12×4K 375.73 us 85.51 us 83.93 us
All-long rows=4, width=128K 75.34 us 50.99 us 55.06 us
All-long rows=16, width=512K 210.55 us 72.13 us 72.74 us
All-long rows=16, width=1M 420.58 us 95.83 us 93.32 us
All-long rows=1, width=128K 76.08 us 49.96 us 53.79 us
All-long rows=4, width=256K 110.79 us 52.28 us 59.59 us
All-long rows=16, width=256K 127.94 us 52.66 us 61.52 us
All-long rows=32, width=128K 86.92 us 51.01 us 57.60 us
All-long rows=32, width=512K 237.11 us 93.11 us 80.78 us
  • Stable all-short: approximately 1.15x–1.32x faster than HIP one-block and 1.15x–2.04x faster than the original multi-kernel implementation.
  • Stable mixed: approximately 2.63x–4.48x faster than HIP one-block. Compared with the original multi-kernel implementation, the 80%-long case improves by approximately 1.15x, the 1M and 20%-long cases are roughly equal to 2% faster, and the 512K 50%-long case regresses by approximately 7%.
  • Stable all-long: approximately 1.37x–4.51x faster than HIP one-block. Compared with the original multi-kernel implementation, 128K regresses by approximately 8%–13%, 256K by approximately 14%–17%, and rows=16 at 512K is roughly equal; rows=32 at 512K and rows=16 at 1M improve by approximately 1.15x and 1.03x.

Correctness, counter rearm, CUDAGraph replay, concurrent multi-Graph, and concurrent multi-stream tests pass.

gfx942

The public Unstable dispatch gate is width >= 524288 && rows <= 32:

Case Shape / Effective Length HIP one-block Original multi-kernel Current single-kernel
All-short rows=1, width=1M, length=16K 43.96 us 55.27 us 41.54 us
All-short rows=2, width=1M, length=20K 43.86 us 58.99 us 44.60 us
All-short rows=16, width=1M, length=4K 32.38 us 103.85 us 32.98 us
All-short rows=32, width=1M, length=48K 64.83 us 107.36 us 60.32 us
Mixed, 80% long rows=20, width=512K, 16×512K + 4×4K 343.76 us 147.48 us 124.27 us
Mixed, 50% long rows=16, width=512K, 8×512K + 8×4K 326.42 us 149.39 us 121.83 us
Mixed, 50% long rows=16, width=1M, 8×1M + 8×4K 632.33 us 212.34 us 174.84 us
Mixed, 25% long rows=16, width=1M, 4×1M + 12×4K 603.18 us 210.69 us 170.47 us
Mixed, 20% long rows=20, width=512K, 4×512K + 16×4K 323.59 us 103.99 us 119.87 us
All-long rows=16, width=512K 345.41 us 151.76 us 124.13 us
All-long rows=32, width=512K 345.47 us 214.06 us 172.16 us
All-long rows=16, width=1M 634.16 us 214.53 us 176.15 us
  • All-short: rows=1 and rows=32 improve over HIP one-block by approximately 1.06x and 1.07x; rows=2 at length 20K regresses by approximately 6%, and rows=16 at length 4K by approximately 2%. Compared with the original multi-kernel implementation, all cases improve by approximately 1.32x–3.15x.
  • Mixed: approximately 2.68x–3.62x faster than HIP one-block. Compared with the original multi-kernel implementation, most cases improve by approximately 1.19x–1.24x, while the 512K 20%-long case regresses by approximately 15%.
  • All-long: approximately 2.01x–3.60x faster than HIP one-block and 1.22x–1.24x faster than the original multi-kernel implementation.

The public Stable dispatch gate is width >= 131072 && rows <= 16:

Case Shape / Effective Length HIP one-block Original multi-kernel Current single-kernel
All-short rows=1, width=1M, length=16K 59.11 us 61.75 us 48.71 us
All-short rows=2, width=1M, length=20K 61.60 us 62.41 us 52.33 us
All-short rows=16, width=1M, length=4K 35.91 us 123.60 us 32.01 us
Mixed, 50% long rows=16, width=512K, 8×512K + 8×4K 351.23 us 184.15 us 126.64 us
Mixed, 50% long rows=16, width=1M, 8×1M + 8×4K 663.74 us 267.36 us 187.37 us
Mixed, 25% long rows=16, width=1M, 4×1M + 12×4K 636.53 us 267.81 us 183.62 us
All-long rows=1, width=128K 117.26 us 68.76 us 82.17 us
All-long rows=4, width=128K 118.10 us 67.97 us 82.98 us
All-long rows=4, width=256K 205.50 us 73.40 us 93.35 us
All-long rows=16, width=256K 208.37 us 123.84 us 96.80 us
All-long rows=16, width=512K 369.38 us 184.35 us 129.96 us
All-long rows=16, width=1M 664.73 us 269.32 us 190.09 us
  • Stable all-short: approximately 1.12x–1.21x faster than HIP one-block and 1.19x–3.86x faster than the original multi-kernel implementation.
  • Stable mixed: approximately 2.77x–3.54x faster than HIP one-block and 1.43x–1.46x faster than the original multi-kernel implementation.
  • Stable all-long: approximately 1.42x–3.50x faster than HIP one-block. Compared with the original multi-kernel implementation, rows=16 at 256K, 512K, and 1M improve by approximately 1.28x–1.42x; 128K regresses by approximately 20%–22%, and rows=4 at 256K by approximately 27%.

Correctness passes for all three paths.

Overall Conclusion

The current single-kernel implementation preserves dynamic per-row partitioning and avoids cross-CTA waiting. This change primarily targets all-short rows in wide padded buffers: all-short workloads improve over both HIP one-block and the original multi-kernel implementation, while most mixed workloads match or outperform the original multi-kernel path. A small number of long-row cases regress, but performance remains substantially better than HIP one-block.

Submission Checklist

@github-actions

github-actions Bot commented Oct 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 (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:multi-gpu 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 6329 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

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 stop the title rewrites; labels stay in sync either way.

@lirui927 lirui927 changed the title perf(flydsl): fuse variable-length decode topk [FlyDSL] Single-Launch Dynamic Decode TopK Oct 9, 2026
@lirui927
lirui927 marked this pull request as ready for review October 9, 2026 15:45
@lirui927
lirui927 requested a review from a team October 9, 2026 15:45
@github-actions github-actions Bot added the FlyDSL label Oct 9, 2026
@zufayu
zufayu requested a review from yadaish October 10, 2026 01:38
@lirui927
lirui927 requested a review from valarLip October 10, 2026 03:17

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. Folding decode top-k into a single launch removes the multi-launch overhead, and the core protocol looks right to me on gfx942/gfx950. Specifically:

  • the last-arriver sequence: store drain, barrier, release fence, agent-scope atomic, rearm by subtracting active_parts, then acquire;
  • the part/merge offsets (part*k, merge_len, index_base for packed rows and next_n);
  • the rows == 0 early return.

The removed public helpers (clear_topk_per_row_decode_workspace_cache, topk_per_row_decode_chunks, …) have no remaining callers in aiter, ATOM, sglang or vllm.

This review comes from reading the code; I have not run it on a GPU. The comments fall into four groups below, each with a concrete example. Inline comments point at the lines.

1. Architecture coverage changed with the kernel

gfx1250 no longer builds. arrive() calls rocdl.s_waitcnt(vmcnt=0). FlyDSL's s_waitcnt dispatches only for gfx942/gfx950, gfx11xx and gfx120x, and raises s_waitcnt is not supported on target arch for anything else (flydsl/expr/rocdl/universal.py). topk_select still lists gfx1250 in _SUPPORTED_GFX and adds "decode" without an arch check.

Example: on gfx1250, topk_select(x[16, 262144] fp32, k=2048) picks decode, and building the kernel raises. The old multi-launch kernel had no s_waitcnt and ran there. A gfx12 encoding alone would not be enough either, because vmcnt does not count stores on gfx12 (stores use storecnt). The drain-before-release step would then not guarantee the partials are visible before the last arriver merges them. Until the drain is arch-aware, gating decode off gfx1250 would keep the old behavior.

gfx942 now runs the one-block selector body. The one-block entry point deliberately excludes gfx942 (_FLYDSL_TOPK_ONE_BLOCK_ARCHES = ("gfx950", "gfx1250")). Decode now inlines the same body there through the gfx942 gates and topk_select. Example: stable, width ≥ 131072 on gfx942 runs it with _LONG_RADIX_DEFAULT and about 45 KB of LDS, so one 1024-thread CTA fits per CU. The PR reports correctness on gfx942, but this body has had no tuning there, and any wave64 or LDS-specific issue in it now reaches production decode.

2. Workspace lifetime

The workspace is cached on the indices object (setattr), keyed by (rows, columns).

Capture first, then eager, reads uninitialized counters. The docstring says capture without warmup is valid. In that case the torch.zeros for the counters is only recorded into the graph, and the zero-fill runs at replay. The cached workspace is visible to eager calls right away. Example:

  1. Capture with a fresh indices.
  2. Before the first graph.replay(), make an eager call with the same indices.
  3. That call sees counters from the graph pool that were never zeroed.
  4. arrived == active_parts - 1 either never holds (no merge, final indices unwritten) or holds early (merge over incomplete partials).
  5. The counter may also never return to zero, which affects every later replay.

Zeroing outside capture (or with an eager memset before capture), or keying the cache so that eager calls never see a capture-time allocation, would close this.

New views get a new workspace every call. ATOM passes topk_indices[:num_decode_tokens, :topk_tokens] (deepseek_v2.py), which is a new tensor object every step, and topk_select allocates indices with torch.empty per call. In eager steps every call therefore allocates the partial buffers again. That is rows × parts·k int32 plus fp32, about 8 MB at rows=32, parts=16, k=2048, plus a counter memset launch. The removed process-level cache, keyed by device, stream and shape, avoided both. Graph replay reuses the captured view, so it is unaffected. When parts == 1 (e.g. gfx950 stable at width 100000), the partial buffers are never read at all, yet they are still allocated and the counters zeroed each time.

3. Performance

Dispatch gates were not re-tuned for one CTA per short row. Stable rows under 2×65536 elements (unstable: under 65536) are not split, so each runs on a single 1024-thread CTA. The gates that route these widths here were fitted to the old multi-CTA kernel.

Example: the gfx950 stable gates send widths 32768–131072 with up to 32 rows here, and _DECODE_GATE_AMORTISED sends width ≥ 8192 with k ≥ 1024. At 4 rows × 100000 stable that is 4 CTAs doing a one-block select, which the one-block kernel could take directly. The PR's tables show 128K/256K stable on gfx942 13–20% slower than the old kernel, and 32K–128K is not measured. A sweep over that range would show where the gates should move.

Value writes add a dependent global load. With write_values=True, the scatter, compact and emit loops now reload input_row[col] with a buffer load (lines 359, 367, 762, 769, 1071) instead of rebuilding the value from the key held in a register. That adds one global load per emitted element on every one-block path, prefill included.

The selector body is inlined three times per kernel. run_one_block_body (more than 1000 lines) is emitted for the direct-row branch, the part branch and the merge trip. That roughly triples code size and compile time for each of the k × stable × write_values × packed specializations, and the larger instruction footprint can cost i-cache misses. The direct and part branches differ only in output views and index_base, so they could share one call.

4. Tests and docs

The split/merge tests cannot see a wrong stable tie-break across parts. compare_topk_results accepts any index set whose differing values are allclose, and under stable it only checks that indices ascend. test_flydsl_decode_split_reuse uses randn data, so ties at part boundaries almost never occur.

Example: if the merge kept a tied element from part 1 over an equal-valued, lower-index element from part 0, the output would still ascend and the values would match, so the test would pass. But stable promises the lowest-index tie-break that topk_select relies on for tie="low" and deterministic. A case with many equal values straddling a part boundary, checked against torch.topk on (value, -index), would catch it.

Two docstrings disagree with the code.

  • write_row_values is described as gating "at run time" (repeated in decode), but it is a Python bool, and const_expr(...) and ... makes it compile-time. A caller passing a runtime fx.Boolean would fail tracing.
  • The body docstring says rows no longer than k get an identity copy when row_labels is set, but the copy is skipped for labelled rows (around line 1360). A caller relying on the documented behavior gets no output written for such rows.

Comment thread op_tests/test_topk_per_row.py Resolved

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I re-reviewed a84d95b. The split/merge itself checks out on GPU:

  • stable at k = 512/1024/2048/4096 picks the lowest index for ties across parts, and the returned values are correct;
  • the second selector pass in a CTA re-initialises LDS behind a barrier;
  • every part is longer than k, so the merge never reads unwritten partials.

The blocker is the new workspace management. Please switch it back to the ownership model the base branch used. The reasons and the details follow.

1. Workspace: please restore the base model

What goes wrong now

Under capture, _get_workspace pops a matching eager workspace out of _EAGER_WORKSPACES. That memory comes from the normal caching allocator, not the graph pool. The only thing keeping it alive afterwards is a setattr on the indices Python object. When indices is a temporary, it is collected right after capture and the memory goes back to the allocator. The graph still writes partials and counters through the raw pointers on every replay.

Every ATOM caller passes a temporary indices:

  • deepseek_v2.py passes topk_indices[:num_decode_tokens, :topk_tokens];
  • glm5_next/indexer.py allocates torch.empty per call;
  • paged_scoring.py passes selected[span];
  • dcp_ops.py does the same;
  • aiter's own topk_select allocates per call.

model_runner runs an eager warmup at the same batch size before capture, so the claim branch is always taken.

I reproduced this on MI355X following that pattern: eager warmup, then capture with a fresh out[:rows] slice, then ordinary eager allocations, then replay. Output:

eager pool keys before capture: [(device(type='cuda', index=0), 0, 16, 32768)]
eager pool keys after capture: []
victim tensors aliasing graph workspace: 3
replay 0: topk_correct=True victim_corrupted=[True, False, True]
replay 1: topk_correct=False victim_corrupted=[True, False, True]
replay 2: topk_correct=False victim_corrupted=[True, False, True]

Unrelated tensors get overwritten, and once the counter has been clobbered the top-k itself is wrong from the second replay on.

Three more problems come from the same design:

  • The counter cannot recover once it is wrong. The arrival protocol needs counter == 0 at launch, but the counter is zeroed only when it is allocated. If it starts at G ≥ active_parts, arrived == active_parts - 1 never holds: the merge never runs, the row's indices keep their torch.empty contents, and a downstream KV gather goes out of bounds. If 0 < G < active_parts, every launch merges before the partials are complete.
  • Graphs share counters that only one of them zeroes. The graph key is (stream_id, rows, columns), and torch.cuda.graph captures every graph on the same class-level side stream. Graphs A and B captured on one persistent indices therefore share a workspace. The torch.zeros was recorded only in A, so if B replays first its counters are uninitialised. I confirmed the shared key on GPU; that run happened to get zeroed memory.
  • The claim checks neither the stream nor any lock. It relies on "capture starts after a device synchronize". vLLM's breakable_cudagraph and SGLang's breakable_cuda_graph call capture_begin directly without a sync, and run eager segments between capture segments. They can claim a workspace an eager kernel on another stream is still using. Concurrent callers iterating reversed(_EAGER_WORKSPACES) while another pops or inserts raise OrderedDict mutated during iteration.

There is also no longer any way to release the eager pool, because clear_topk_per_row_decode_workspace_cache was removed. Up to 16 entries of rows × parts·k × 8 bytes stay alive. They are allocated after the KV-cache memory profiling, so they come out of the budget the profiler already handed to the KV cache.

What the base did

  • Eager calls use a process-level lru_cache(maxsize=16) keyed by (device, stream_id, shapes), with clear_topk_per_row_decode_workspace_cache() to release it.
  • Under capture every call allocates fresh storage from the graph pool. It never comes from, or goes into, the eager cache, so its lifetime is the graph's and has nothing to do with indices.
  • The kernel re-initialises its state on every launch, so the workspace never depends on what a previous launch left behind.

For this kernel the third point means the counters must be reset per launch, either in the kernel or with a reset that runs every launch; a zero-fill recorded during capture replays each time. With all three restored, every issue above goes away. The test that holds every indices in buffers (section 2) should then gain a case with a temporary out[:rows] captured after warmup, followed by eager allocations and replays.

2. Tests

  • The graph test holds every indices alive, including the "capture without warmup" part, so it cannot see the use-after-free above. Please add the pattern from the repro.
  • The graph calls the op three times on the same logits and indices, and only the last output is checked. If the second or third call read partials left by the previous one (counter not rearmed, missing fence), the stale partials are identical to the fresh ones, so the error stays hidden. Varying the inputs between the calls, or checking each output, would catch it.
  • The stable + write_values merge path has no test coverage. The main sweep stops at ctx 128000, and stable's part_elements is 65536, so parts == 1 for every stable case. The production split gates (gfx950 stable (131072, 200000, 48), (200000, None, 64), gfx942 (131072, None, 16)) and the merge's value write-back never run in CI.
  • The cross-part tie test cannot tell the two possible rules apart. It uses all-ones input over two parts, where "lowest global index" and "first position in the merge buffer" give the same answer, so a merge that breaks ties by position would still pass. A case where the tied winner comes from a later part, or where part 0 has fewer than k tied elements, would distinguish them.

3. Dispatch and performance

These were raised last time and still apply:

  • topk_per_row_decode_parts returns 1 for stable widths below 131072 (unstable: below 65536), so the whole row runs on one 1024-thread CTA. The gfx950 stable gates (32768, 65535, 16) and (65536, 131072, 32) still send these shapes here. At rows=4, width=100000 that is 4 CTAs on 256 CUs, each scanning 100k elements serially. The 32K–128K range has no benchmark.
  • The _ONE_WORKGROUP_MAX_ROW_WIDTH = 20_000 comment still describes it as the crossover to a split kernel. That value was measured against the old multi-kernel; above 20000 most rows now take the parts == 1 one-block path. _FLYDSL_TOPK_DECODE_GATES was not re-tuned either.
  • run_one_block_body (about 1300 lines) is still inlined three times: direct, part and merge. Direct and part differ only in the output base and whether values are written, so selecting an integer offset at run time would allow one call.

New: topk_per_row.py calls torch.cuda.get_device_properties(...).multi_processor_count on every call. aiter.jit.utils.chip_info.get_cu_num() is cached and honours CU_NUM. With CU_NUM set (partitioning, limited CUs), parts is currently computed from a different CU count than the rest of aiter's dispatch uses.

Correction to my previous review

I said a labelled row no longer than k gets no output written. In the decode paths, labelled rows are parts (each longer than k) or merge rows (parts·k long), so that case does not occur. Only the docstring is inaccurate there; it is not a correctness issue.

Comment thread op_tests/test_topk_per_row_stable.py Resolved
Comment thread aiter/ops/flydsl/topk/topk_per_row.py Resolved
Comment thread aiter/ops/flydsl/topk/topk_per_row.py Resolved
@lirui927
lirui927 requested a review from valarLip October 10, 2026 11:09
@lirui927
lirui927 requested a review from valarLip October 12, 2026 01:55
valarLip
valarLip previously approved these changes Oct 13, 2026
valarLip
valarLip previously approved these changes Oct 14, 2026
@valarLip
valarLip merged commit a1e5a46 into main Oct 14, 2026
@valarLip
valarLip deleted the lirui/1009 branch October 14, 2026 10:44
JH-Leon-KIM-AMD added a commit that referenced this pull request Oct 16, 2026
Brings in #6329's single-launch decode kernel, which is what the chunked
backend now runs above width 20000. Conflicts:

- topk_per_row.py: the split workspace cache moved into the kernel module, so
  clear_topk_per_row_decode_workspace_cache() calls it there and also drops
  the adaptive control buffers. The chunked path calls main's
  launch_topk_per_row_decode().
- topk.py: takes main's chip_info import, which adds get_gfx and
  get_gfx_runtime.
- test_topk_per_row.py: keeps the adaptive sections and main's split-reuse and
  ragged decode tests, inside the --sections parser.
JH-Leon-KIM-AMD added a commit that referenced this pull request Oct 16, 2026
#6329's single-launch kernel is faster than the chunked one these bands were
fitted against, so the old entries took cells where it now wins. The gfx942
80 and 228 CU and gfx950 256 CU entries are re-fitted on the same rule, with
the fallback taken per cell as the kernel the gate would actually run there.
The gfx942 304 CU entry is unchanged: no MI300X node could be reserved, so it
is re-measured in a follow-up.

| card | cells behind main, old -> new (diagonal / padded) | worst cell taken, new | #6329's 36 cases, geomean / worst |
|---|---|---|---|
| gfx942, 80 CU | 22 / 17 -> 0 / 0 | 1.06x | 1.16x / 0.99x |
| gfx942, 228 CU | 11 / 5 -> 0 / 0 | 1.09x | 1.21x / 0.99x |
| gfx950, 256 CU | 22 / 11 -> 0 / 0 | 1.08x | 1.12x / 0.99x |

1000 diagonal and 900 padded cells per card (k 256-4096, width 4K-1M, rows
1-512, both emit modes), graph replay, median of 3 repeats, FlyDSL 0.3.4.1;
#6329's cases with max_row_len set to the longest live row. test_topk_per_row,
test_topk_per_row_stable and test_topk_select pass on all three cards.
JH-Leon-KIM-AMD added a commit that referenced this pull request Oct 16, 2026
#6329 replaced the chunked decode kernel with a single-launch one, so the
gate's answer becomes `BACKEND_SINGLE = "single"` and the comments that named
the old kernel follow. `BACKEND_CHUNKED` had no users outside topk.py, and
every non-adaptive answer already reached the single-launch kernel, so no
call routes differently.
JH-Leon-KIM-AMD added a commit that referenced this pull request Oct 22, 2026
…6329's kernel

The 304 CU entry was left fitted against the chunked kernel when the other
three were re-fitted, since no MI300X node was free. It is now fitted on
the same rule, so it stops taking cells where #6329's single-launch kernel
wins. The stable test's comment names that kernel too.

| slice | admitted, old -> new | behind main, old -> new | worst cell taken, new |
|---|---|---|---|
| diagonal | 361 -> 386 | 10 -> 0 | 1.08x |
| padded, max_row_len = live | 288 -> 345 | 3 -> 0 | 1.08x |
| padded, max_row_len = 1M | 657 -> 369 | 113 -> 58 | 0.51x |

1000 diagonal and 1000 padded cells (k 256-4096, width 4K-1M, rows 1-512,
both emit modes), graph replay, median of 3 repeats, FlyDSL 0.3.4.1.
test_topk_per_row, test_topk_per_row_stable and test_topk_select pass on
gfx942 304 CU.
JH-Leon-KIM-AMD added a commit that referenced this pull request Oct 23, 2026
The decode gate is a table of measured numbers, so the script that measures
them belongs beside it. This times the adaptive, single-launch, FlyDSL
one-block and C++ one-block kernels on the same inputs, names the kernel
main's dispatch picks for each cell, and checks every result against
torch.topk. Slices cover full rows, padded rows (uniform, mixed, spread) and
the cases #6329 published; timer 1 decides, timer 2 is #6329's method.

On MI355X (gfx950, 256 CU) timer 1 matches the harness the existing gate
numbers came from: median ratio 1.000-1.002 per kernel over 200 cells, run
to run within 0.4%. The one-block and single-launch kernels in stable mode
run up to 2.16x slower on some random draws while adaptive moves by 2%, so
each cell runs on three seeds by default.
JH-Leon-KIM-AMD added a commit that referenced this pull request Nov 10, 2026
The B slice replays #6329's published cases and ignored --rows, so
--slice B --rows 4 still ran all 35 of them. --rows now defaults to
None: given, it filters B as it does the A slices; omitted, the A
slices take ROWS and B keeps every published case, the 20-row ones that
ROWS does not list included.

--list: the default run stays at 3875 cells (B 35), --slice B --rows 4
gives 4.
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.

3 participants