Repository navigation
[FlyDSL] Single-Launch Dynamic Decode TopK - #6329
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
valarLip
left a comment
There was a problem hiding this comment.
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_basefor packed rows andnext_n); - the
rows == 0early 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:
- Capture with a fresh
indices. - Before the first
graph.replay(), make an eager call with the sameindices. - That call sees counters from the graph pool that were never zeroed.
arrived == active_parts - 1either never holds (no merge, final indices unwritten) or holds early (merge over incomplete partials).- 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_valuesis described as gating "at run time" (repeated in decode), but it is a Python bool, andconst_expr(...) and ...makes it compile-time. A caller passing a runtimefx.Booleanwould fail tracing.- The body docstring says rows no longer than k get an identity copy when
row_labelsis 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.
Co-authored-by: Cursor <[email protected]>
valarLip
left a comment
There was a problem hiding this comment.
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.pypassestopk_indices[:num_decode_tokens, :topk_tokens];glm5_next/indexer.pyallocatestorch.emptyper call;paged_scoring.pypassesselected[span];dcp_ops.pydoes the same;- aiter's own
topk_selectallocates 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 - 1never holds: the merge never runs, the row's indices keep theirtorch.emptycontents, 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), andtorch.cuda.graphcaptures every graph on the same class-level side stream. Graphs A and B captured on one persistentindicestherefore share a workspace. Thetorch.zeroswas 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_cudagraphand SGLang'sbreakable_cuda_graphcallcapture_begindirectly 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 iteratingreversed(_EAGER_WORKSPACES)while another pops or inserts raiseOrderedDict 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), withclear_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
indicesalive, 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_elementsis 65536, soparts == 1for 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_partsreturns 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_000comment 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 theparts == 1one-block path._FLYDSL_TOPK_DECODE_GATESwas 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.
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
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.
#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.
#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.
…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.
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.
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.
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
seq_lens.1/2/4/8/16active parts.Last-Arriver Final Merge
next_n, and mixed short/long rows.Test Plan
Host+device CUDAGraph tests use the production
top_k_per_row_decodeinterface. Inputs remain fixed. After eager and CUDAGraph warmup, CPU wall-clock timing measures onegraph.replay()followed by stream synchronization; results are the median of 31 runs.Performance coverage:
Correctness coverage:
next_nTest Results
gfx950
Selected unstable host+device CUDAGraph results:
Stable host+device CUDAGraph results for the same cases:
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:The public Stable dispatch gate is
width >= 131072 && rows <= 16: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