Repository navigation
[FlyDSL] [JIT] Adaptive decode Top-K kernel, dispatched by one measured gate - #5677
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
26ce561 to
627ba6c
Compare
The decode path now has four candidate kernels and no single one wins the shape space: across 1000 measured cells on gfx942 the FlyDSL one-block port takes 469 and this kernel takes 512. So the kernel lands behind a table of measured row intervals per (arch, CU count, emit, k, width), and both entry points call the one decision function rather than deciding again further down, which is what keeps them from disagreeing. An (arch, CU count) pair the table does not name keeps today's behaviour exactly. Measured on MI308X (gfx942, 80 CU) over 1000 cells covering k 256..4096, width 4K..1M and 1..512 rows, in three passes: a light pass over the grid, the full protocol over every contested cell, and six repeats on the band edges. Scoring every cell rather than the ones the gate takes, and scoring each declined cell against the kernel that actually runs on that card, the table returns 1.341x geomean where declines run the C++ kernel and 1.196x where they run the port. No cell is behind upstream under either fallback, which is what fitting the intervals at slack 1.00 buys.
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.
eafd41e to
00f068e
Compare
…nches The existing tests all read the host rules: the band table's shape, the k-group expansion, the early-stop default, and that both entry points defer to one decision function. None of them can show that the kernel the table names is the kernel that runs, because that is settled at the launch site. This adds a GPU-gated test that patches the three launch sites and, for both sides of every band edge in the shipped table, asserts the gate agrees with the table, the launch agrees with the gate, and the indices written select the right values. Values rather than indices: a row this long carries ties, and either index of a tied pair is a correct answer. The cells are derived from the table, not written out, so re-fitting the table re-aims the test instead of leaving a stale list that passes by testing nothing. A declined cell is expected to launch the FlyDSL port on the one-block arches and the HIP kernel elsewhere, which is why the expected launch is computed from the arch rather than from the gate. It skips without a device and on a card the table does not name. A cell is capped at 64M elements so a unit test does not ask a shared card for the widest band's tallest row count. Verified on gfx950 at 256 CU: 84 cells, 25 passed.
CI's Check Code Style with Black failed on both: the gfx950 band tuples were written one line per k group and the test's call sites were wrapped by hand. No values changed -- the parsed table is identical before and after.
4624082 to
9e06383
Compare
The bands were fitted on one condition -- the adaptive kernel is no slower
than the best of the four measured kernels. That is what makes "no cell goes
backwards" true, but it also admits cells whose margin over the kernel that
runs today is 1.00x to 1.05x, which is inside run-to-run noise. Claiming
those is claiming more than the measurement supports.
So a cell is now taken only when both hold, against the two different
baselines the two questions need:
adaptive / best of the four <= 1.00 nothing regresses
kernel that runs today / adaptive >= 1.05 the win is real
Both device entries are re-fitted under the pair. gfx942 is unchanged at
1.341x, losing 3 of 433 cells: its fallback is the HIP kernel, which loses
every cell, so everything it took already cleared the floor. gfx950 goes
1.133x -> 1.126x over 284 rather than 358 cells, and the slowest cell the
table takes goes 1.002x -> 1.061x.
Routing re-verified against the new edges: 126/126 on MI308X, 85/85 on
MI355X.
A decode buffer is allocated once at the model's maximum context, so its physical width says what a row could hold and `seq_lens` says what it does. `seq_lens` is device-resident, and the adaptive path picks its kernel on the host, before the launch -- `tier_mode`, `blocks_per_row`, `parts`, `compact` and `needs_workspace_zero` are all decided there. So the host had only the width to go on, and a short row in a wide buffer was built as if it were a long one. A 1M buffer can never say "short", which costs that row the single-workgroup tier outright. The other decode arms do not have this problem, and the measurement shows why: hold the live length fixed, widen the buffer to 1048576, and the HIP one-block kernel and the FlyDSL port both come back at 1.00 on both cards. They read `seq_lens` on the GPU and specialise nothing, so a wider buffer is memory nobody touches. Ours came back at 1.21 and 1.20 -- near-identical on cards 3.2x apart in CU count, which is the shape of a host-side constant rather than a hardware effect. Add `max_row_len` to the decode entry points. It is the longest live row in this call, not the model's maximum context -- `max_seq_len` elsewhere in this repo means the latter, which is the width we already have. Both the band lookup and `decode_adaptive_config` take `min(width, max_row_len)` through one helper, so the gate and the config cannot disagree about which length a cell was admitted on. It is a guarantee, not a hint. `tier_mode` is compiled in, so a bound below the longest live row does not merely give up performance, it launches a kernel that stops short of those rows and returns wrong indices. It cannot be checked here: reading `seqLens` would sync, and this path may be inside a graph capture. `None` keeps today's behaviour exactly, so no existing caller changes. Scored over the padded shapes the shipped table admits, against the best of the other three arms: MI355X goes from 32 losing cells and 1.14x geomean to 1 and 1.34x, MI308X from 157 losing and 0.96x -- a net regression in the shape production actually has -- to none and 1.36x. The band table is unchanged and needs no refit; it was fitted on the diagonal, where the width is the live length, so it was always keyed on the right quantity and was only being looked up with the wrong one. Nine op tests cover the bound, including a ragged batch whose longest row sits exactly on it, compared by selected value against the same call made without a bound.
Both cards were measured on the full grid -- 1000 diagonal cells and the production slice, 0 incorrect -- and until now the gate declined them outright, since it declines any key it does not hold. That is safe the way an unplugged card is fast. The entries are fitted on the diagonal and on the production slice together, a cell needing to clear both of the table's conditions on each. Fitting on the diagonal alone, which is how the two existing entries were produced, does not transfer to these cards: it admits 18 cells that lose at the live length on 304 CU, worst 0.84x. Requiring both empties that column. 228 CU: 315 cells admitted, 0 losing, 1.42x geomean 304 CU: 288 cells admitted, 0 losing, 1.36x geomean against 211 admitted with 1-2 losing if those cards simply borrowed the gfx950 256 CU entry. Purely additive: those keys matched nothing before. The fit was validated by refitting the existing 80 CU entry from its own data, which reproduces its backbone and scores 369 admitted / 0 losing against the shipped 366 / 0.
`max_row_len=None` returned upstream before the chunked bands were read, so a caller that states no bound -- which is every caller today -- lost the chunked kernel upstream routes it to. On a 1M buffer at k=4096 that is 859us against 73us, and it reproduces on all four measured cards. The two tables read different lengths and now say so. The adaptive bands take the caller's bound, because that kernel is configured from it, and decline when it is absent; the chunked bands keep reading the physical width they were fitted on. An unbounded call therefore routes exactly where it routes without this argument, and a bound moves only the one kernel it sizes.
The host only branches on `adaptive`; every other answer falls through to the width branch, so an `upstream` answer still launches the chunked pair. The docstring claimed a direct caller could not reach a kernel the gate would not have picked, which holds for the adaptive kernel alone. Docstring only; no kernel selection changes.
…inputs The 80 CU and 256 CU entries were fitted on the diagonal alone and before the 1.05x floor existed, so the table's own comment described a standard two of its four entries had never been held to. Refitting them with the current fitter is strictly additive: 80 CU takes 430 -> 433 diagonal and 366 -> 369 padded cells, 256 CU takes 284 -> 311 and 211 -> 238, and the one 0.95x padded cell on gfx950 is gone. No cell regresses and none falls under the floor on either card. The table comment loses the measurement narrative and the two counts that the refit had already made stale; the constraint a reader needs stays. Tests: both GPU cells now run twice, once on planted logits whose top k sit at known strided positions inside each row's live length and once on random ones, so an indexing mistake fails against a known answer rather than against a sample. The card is read with the same helpers the gate uses, so a test cannot check one table row while the call under it takes another. Drops the signature assertion, which the GPU test already covers by observing the launch.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The new tests do not execute in CI, and descriptor sizing can produce invalid reads for supported strided tensors.
Get a fresh assessment by requesting another Copilot review.
Review effort: Balanced
Findings: 1
Open (5)
What changed in this PR
Adds a measured, CU-aware adaptive FlyDSL decode Top-K kernel and dispatches eligible bounded rows through it.
Changes:
- Implements adaptive short, persistent, compact, and ordered kernel paths.
- Adds
max_row_lenand centralized backend selection. - Adds dispatch and GPU correctness tests.
| File | Description |
|---|---|
aiter/ops/topk.py |
Adds adaptive routing and public bound support. |
aiter/ops/topk_select.py |
Threads the bound through decode selection. |
aiter/ops/flydsl/topk/topk_per_row.py |
Configures and launches the adaptive kernel. |
aiter/ops/flydsl/kernels/topk/topk_per_row_decode_adaptive.py |
Implements the adaptive GPU kernel. |
op_tests/test_topk_per_row_decode_adaptive.py |
Adds routing and correctness coverage. |
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
The logits descriptor covered rows * stride0 from the tensor base, which is the tensor's extent only when stride0 == width. The host accepts any inner-contiguous view, so an overlapping view (stride0 < width) read the tail of its last rows as out-of-range zeros, and a broadcast view (stride0 == 0) got a zero-byte bound and read every row as zeros; a padded view (stride0 > width) declared storage past its last element. Each row now builds its own descriptor, based at the row and sized to its live length, as the other decode kernels do. The base is 64-bit, so a tensor past 4 GiB stays addressable. The new test fails on the old kernel for the overlapping and broadcast views, on all four band-edge cells it picks, and passes after. Timing on gfx950 at 256 CU, k=2048, both emit modes, rows 1/32/512, widths 4K/64K/1M plus a 1M buffer at live 8K and 128K, 30 cells, graph replay, 2 reps x 3: after/before geomean 1.000, range 0.980-1.029, every result correct. gfx942 was not re-measured.
The gate chose a band by CU count and the launcher sized the kernel's grid by CU count, but each read it separately and neither honoured `CU_NUM`. The two agreed only because both read the device; teaching one of them the override would have admitted a band fitted for one grid and built another. Both now ask `_decode_cu_count`, which lets `CU_NUM` lower the count but not raise it past the device: a row's parts spin on each other, so a grid sized for CUs the card does not have cannot keep them co-resident. The count stays per device rather than `get_cu_num()`'s one value per process. Without `CU_NUM` the count and every launch are unchanged. Both new tests fail on the previous code -- `CU_NUM=80` was ignored, and the launcher read its own count -- and need no device.
CI runs each top-level op_tests file as `python3 <file>`. This file held only pytest functions and no entry point, so CI imported it, defined the tests and exited 0 without running any of them. It now hands itself to `pytest.main`, and a failing test fails the file. Under `python3 <file>` all 44 tests run and pass, none skipped, on gfx942 at 304 and 80 CU and on gfx950 at 256 CU with flydsl 0.3.4.1.
The launch test compared selected values only, which accepts either member of a tie, and its inputs held almost no ties. So nothing checked the stable contract -- smallest index on a tie, output ascending -- on the adaptive kernel, and the stable test never reaches it because it passes no `max_row_len`. Each stable band-edge cell now also runs a tied input and its indices must equal the contract's answer exactly. With stable calls served by the unstable kernel, the tied pass fails all 47 stable cells on gfx942 at 304 CU; planted and random inputs caught 14, only where the swap also changed routing. The file passes on gfx942 at 304 and 80 CU and on gfx950 at 256 CU.
The file was a pytest module, which the aiter-op-test convention does not use. The host checks on the config, the band table, the CU count and max_row_len are now plain check functions under unittest.mock, still 39 cases, reported in their own table. The three on-card tests become one @benchmark sweep over this card's band edges, crossed with stable, three input kinds and five logits layouts (contiguous, padded, overlapping, broadcast, ragged). Each cell runs the bounded call and the unbounded one, which declines the adaptive kernel, checks routing and the result against a torch reference, and times both; a stable call now compares indices on every input, not only tied ones. TB/s is reported and TFLOPS is not, since Top-K does no arithmetic. Every cell passes with zero error and matching routing: 1655 cells on gfx942 at 304 CU (286 s), 1980 at 80 CU (291 s), 845 on gfx950 at 256 CU with flydsl 0.3.4.1 (162 s). Serving stable calls with the unstable kernel fails every cell it touches and the file exits non-zero.
Review asked for a small bounded-decode case in the existing family file rather than a second script, driving only the public API. The separate file goes. test_topk_per_row.py gains a max_row_len pass-through and a bounded decode case: ragged seq_lens in a buffer 4x the bound, the longest row on it, planted logits whose padding outranks every live value so a read past a row is caught, compared with torch.topk over the live part. It records the backend decode_backend_for_call picks instead of spying on the launch, and is skipped on a card with no adaptive bands. Its host asserts, run for every card the table carries, are that the bands are well formed, that the fixed shapes stay adaptive, and that an unmeasured CU count and a None bound both keep the pre-adaptive answer. The stable tie-break moves to test_topk_per_row_stable.py, which now passes max_row_len on a 131072-wide decode so its bit-faithful smallest-index reference covers the adaptive kernel at every tie level. Both files pass on gfx942 at 304 CU and at 80 CU, and on gfx950 at 256 CU with flydsl 0.3.4.1; all 12 bounded cells route to the adaptive kernel on each. Serving a bounded stable call with the unordered emit fails the stable file, and handing the kernel lengths past the bound fails the bounded case in both modes.
…e kernel Review pointed at two things that cost length without carrying a constraint. The adaptive and chunked gates had twin interval matchers differing only in a row minimum; one four-field matcher remains, and the chunked gate's three-field table is passed through it with a row minimum of one, so that table is unchanged. The host-side rule section of the adaptive kernel module carried the fitting history of its constants; those comments and docstrings now keep only what a caller or editor could break (grid order and co-residency, the floor the width table was fitted on, caps of at least two, the short-tier rule staying apart from the dispatcher's). The module's code is unchanged: its AST with docstrings removed is identical. The matcher gives the old answer on all 57,600 (width, rows) cases of the chunked tables. Across 144 decode cells on gfx942 at 304 CU, the backend and the output indices are identical before and after, and the time ratio is 0.999 geomean over four alternating runs (adaptive 1.000). Both topk per-row test files pass at their defaults on gfx942 at 304 and 80 CU, and on gfx950 at 256 CU with flydsl 0.3.4.1.
Comments and docstrings added by the adaptive decode path now describe what the code does and the constraint behind it, without the optimisation history, measured ratios or references to replaced code. The FLYDSL_TOPK_COMPACT_ES alias existed only for old A/B scripts and is removed; FLYDSL_TOPK_ADAPTIVE_ES is the one switch. Apart from early_stop_default(), each file's AST without docstrings is unchanged. test_topk_per_row.py and test_topk_per_row_stable.py pass with default args on gfx942 304 CU, gfx942 80 CU and gfx950 256 CU, the 12 bounded cells routing to adaptive on each. A/B against the parent on gfx942 80 CU, 144 decode cells, four rounds with alternating order: identical outputs, geomean 1.000, every cell within 0.993-1.007.
…checks The concurrent-replay test and test_decode_validated_once compared an unstable call's sorted indices with torch's, which fails when the k-th and (k+1)-th values are equal. Both now compare through compare_topk_results, as 98987e9 did for the scratch tests; stable checks stay index-exact. test_topk_per_row passes on MI350X (gfx950, 256 CU).
…aptive table holds Since the refits 4 x 131072 reaches the adaptive kernel only on 304 CU, so on the card PR CI runs the stable heavy-tie check exercised the single-launch kernel instead. 1 x 524288 is in every adaptive table for k 256 to 4096, and the check now asserts the gate picks adaptive whenever the card and k are in it. On MI350X (gfx950, 256 CU) the old shape trips the assert for k 512, 1024 and 2048, the new one passes, and test_topk_per_row_stable.py passes.
A grid below the part count makes the running workgroups take the missing parts, the concurrent replay test also runs with stable=True, and a hang in the adaptive section dumps a traceback after 900 s. Exact on MI350X (gfx950, 256 CU); the section takes 162 s cold.
A2-A4 also run at buffer widths 32K and 64K, without the A2 lengths that do not fit, and slice R puts one full row among 4K rows (rows 8-512, W 128K-1M), so a card can be refit from this harness alone. The cells are exactly the 4680 the gfx950 and gfx942 refits ran.
It was never fitted with the bound at the buffer width, which capture callers pass. Until it is, 304 CU routes as on main: the single-launch gate or the one-block kernel.
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved adaptive-path defects can launch on the wrong GPU, accept invalid row_starts tensors, and truncate large row strides, risking unwritten outputs, incorrect results, or invalid memory accesses.
9 open issues
Run adaptive planning and execution on the logits device · New Preserve or reject row pitches beyond int32 range · New Validate row_starts on both public entry points · New Verify adaptive routing for regular and packed decode calls · New Test adaptive -1 padding for empty and short rows · New Order input initialization before decode stream reads · New Release the old scratch tensor before testing cache reuse · New Select architecture cases using the runtime GPU · New Reuse the shared CUDA graph capture helper · New
Review effort: Max
stride0 reached the adaptive kernel as int32, so a row pitch of 2**31 elements or more faulted with an illegal memory access; the gfx950 gate admits such a view (unstable 2 x 8192, k 512). The single-launch kernel addresses rows through the tensor layout and was already exact there. The adaptive kernel now takes stride0 as int64. Packed row_starts was checked for dtype and shape on the public path only, and not at all on the `validated` route into single or adaptive: a CPU row_starts returned wrong indices without an error. It is now checked in _decode_with_backend for dtype, shape, contiguity and device whether or not the call was validated. main's packed path had the same gap on the single-launch kernel. A call whose tensors are on a GPU other than the current one now plans, builds and launches the adaptive kernel with that GPU current. The capture id comes from graph_alloc instead of a second binding. Tests: the decode gate test selects cases by the runtime arch, as the gate does, so a 'gfx942;gfx950' build on gfx942 no longer fails it; the scratch tests order input setup before the side stream reads it, and drop their reference to the first buffer so growing can release it; the bound test covers top_k_per_row_decode, strided and packed. New: rows of length 0, 5, k-1 and k padded with -1, a 2**31 pitch, and rejected row_starts. The two-GPU test adds tensors on the non-current GPU. Measured with FlyDSL 0.5.0. The whole test file passes on banff-ccs-aus-g07-05 (gfx942, 64 CU) and smci355-ccs-aus-n03-05 (gfx950, 256 CU); on the gfx942 card the adaptive section also with gfx942 80 CU bands lent to it. On gfx950, at d23b7fd, the two-GPU test fails with GPU 1's tensors and GPU 0 current, and the 2**31 pitch through top_k_per_row_decode faults; both pass here.
The adaptive bands sat at the widths they were measured on, and the gate looked the caller's bound up as given, so a bound one element off a measured width (any max(seqLens), or 163840) never reached the adaptive kernel. The gate now looks the bound up at the next measured width, and the config is built there, capped at the buffer. Below 4096 it declines; past 1M the 1M bands apply. A band now speaks for every bound that rounds to it, so the gfx942 228-CU and gfx950 256-CU entries are refit on a sweep that adds bound = W at 4096-20000 and 512K and bounds off the grid: no admitted cell is behind main on MI300A, MI355X or MI350X. The earlier entries already lost at bound = W on those widths (gfx950: 349 of 4615 cells, worst 0.59x). gfx942 80-CU is not refit, as no such card was free; its bands at 20000 and below and at 512K are dropped. test_decode_bound_rounds_up checks the rounding against every band; the stable 524288 check and the ragged cells follow the bands a card carries. Co-authored-by: Cursor <[email protected]>
The tables are fitted on buffers off the grid (49152, 98304, 163840, 600000) and on bounds past 1M, which the bench could not generate: --widths only filtered the fixed lists and --bound took width or live. --widths now replaces a slice's widths (B still filters its own), --live replaces A2's live lengths, and --bound also takes a number. With no new option the cells are the same as before.
…them Since d14c61f a band speaks for every bound that rounds up to its width, but the bands were fitted at the width itself. Main's kernel can change in between: on MI355X below 131072 it runs the one-block kernel, not the single-launch one the 131072 band was measured against, so a 98304 buffer at 8 rows ran at 0.87x of main. Each band is now kept only where the adaptive kernel is not behind main's kernel at any measured live length on every buffer that rounds to it, with mixed-length rows checked on the buffers between widths. Measured shapes admitted fall from 387 to 238 on gfx950/256, 924 to 842 on gfx942/228 and 568 to 507 on gfx942/80, none behind main (was 75, 33 and 24). Bounds equal to the buffer only, as under graph capture. The bounded next_n=2 test skips the one band, gfx942/228 at 1M, too narrow for a two-row sequence.



Adaptive decode Top-K kernel, dispatched by one measured gate
The decode path now has four candidate kernels and no single one wins the shape space, so this adds the kernel behind a table of measured row intervals keyed by
(arch, CU count, emit, k, width). An(arch, CU count)pair the table does not name keeps today's behaviour exactly.How the dispatch works
Two public entry points reach the decode path, and they do not share a call chain:
topk_select()routes itsdecodearm straight into the FlyDSL host and never passes throughtop_k_per_row_decode(). So the gate sits in both, and both ask one function rather than deciding for themselves, which is what keeps them from disagreeing about a shape.The gate never names the fallback kernel itself: it answers "not ours" and upstream's existing dispatch picks, which is the port on gfx950 and gfx1250 and the HIP/C++ kernel elsewhere. That is also why a caller wanting values never reaches the adaptive kernel, which emits indices only. Only
top_k_per_row_decode()has that dispatch below it. Intopk_select()the decode arm is already chosen, so "not ours" leaves the single-launch kernel.max_row_len, and what a caller has to passA decode buffer is allocated once at the model's maximum context and a call fills whatever part of it the requests need.
seq_lensis device-resident, so the host cannot read it without a sync, and the adaptive kernel picks its tier, part count and workspace on the host before launch. Given only the buffer, it builds a short row as if it were a full one.So the new argument states the longest live row in the batch. A serving stack that assembles the batch already has it -- it is
max(seqLens). No caller in aiter passes it yet, so nothing reaches the new kernel until a stack opts in. The tables below declare it.seq_lensentry, so a bound below the longest live row stays correct and only runs a smaller config; a bound above it costs the win, not the answer.Nonedeclines the adaptive kernel and nothing else. The single-launch bands keep reading the physical width they were fitted on, so a call that passes nothing routes exactly where it routes today.A bound above a row costs that row less than it used to. Under compaction, a row shorter than
compact_minreads its own row instead of filling and re-reading the candidate buffer. Up to 32 rowscompact_minis 10240 per cooperating part, capped so that a row as long as the bound still compacts; past 32 rows it stays atshort_max + 1. A row as long as the bound therefore runs as before: on gfx950 the diagonal slice moved by a geomean of 0.9993 over 1000 cells, and the three cells more than 3% slower are in a shape the gate declines. On gfx942 this change was A/B-tested with the adaptive arm over all 3,875 cells: on MI308X (80 CU) the 489 gated cells re-timed at a geomean of about 1.00 (worst 0.92x, still 1.5-4.6x ahead of main's kernel); on MI300A (228 CU) the 1,903 gated cells average 1.021, too noisy to read per cell. The bands were kept.The kernel keeps its cross-workgroup counters and histograms in a control buffer, and the last workgroup out of each row zeroes that row again. Eager launches share one per device and stream. A graph capture takes its own from the graph's pool, zeroed by the graph on every replay, and drops its stream's eager buffers; it needs no warm-up.
Results
Refit for the rounded bound. The gate looks a bound up at the next measured width, so a band speaks for every buffer that rounds up to it, and main's kernel can differ between two widths. A band is kept only where the adaptive kernel is not behind main's kernel at every live length, on every buffer that rounds to it, on every card that reads the entry. Swept on this head with FlyDSL 0.5.0 and bound = buffer, as under graph capture: every measured width and 20 buffers between them, on both sides of main's thresholds (6144 to 786432), each against main's kernel at that buffer, at live lengths 4096, 8192, 12288, 16384, 24576, 32768, 49152, W/4, W/2 and full; then rows of mixed length on the buffers between widths (25, 50 or 80 % of rows full and the rest 4096, random lengths, one full row among 4096s). Cells within 0.90-1.03x were re-timed with 3 seeds x 2 rounds. Rows are measured at powers of two; a band keeps the rows between two only when both win. The earlier refit's slices keep the 1.05x rule and are re-scored through the new entries. t1, the graph timer below; each cell is cells taken, geomean over them, worst cell, and no taken cell is behind main:
MI308X has only the last two sweeps on this head, and MI300A's past-1M run was not kept. The entries this replaces were behind main on the same between-width sweep, mostly where main's kernel changes inside a rounding interval and at 512K and 1M with live 32768, which the earlier sweeps had not measured. The refit only removes bands; one more MI308X band (unordered k4096, 32768 at 128-512 rows) is dropped because mixed-length rows ran 0.98x there on the re-time. Shapes are (emit, k, rows, buffer) on the between-width sweep:
MI300X was not refit: no such card was available. The tables below predate this refit.
"Cells taken" counts grid cells. For a bound a stack would pass, the share is lower. Over 2000 bounds log-uniform in [32K, 1M], 1 to 512 rows and a 1M buffer (the gate alone, on the host):
On gfx950, stable k256 stays declined: at every width, some bound = width cell with a short live row is behind main (0.43x to 0.99x on the two cards), while a tight bound wins up to 6.55x at 1 to 8 rows. The gate cannot tell the two apart.
Every cell is scored, not only the ones the gate takes. A band takes a cell when the kernel is no slower than the best of the four and at least 1.05x faster than what runs there today; a smaller margin is noise. Every entry had to satisfy that on both slices below, so a cell that only clears it on the diagonal is not in the table. Nothing is behind on either slice.
A ratio is today's kernel over this PR's, so a declined cell is 1.00x by construction and the geomean covers every cell. Each card's own grid and per-cell winners are below.
Protocol: all four arms are timed the same way on every cell, in one session per card, under graph replay (16 copies x 30 iterations x 3); a cell's number is the median of 3 repeats, with the arm order rotated between blocks. The upstream FlyDSL arm is main's, #6329 included. Measured with FlyDSL 0.3.4.1; main now pins 0.5.0, which these numbers have not been re-taken on. The per-row compaction above was A/B'd on 0.4.0, adaptive arm only.
On the diagonal, where the buffer is exactly full.
On padded buffers, a 1048576 buffer holding a shorter live row with
max_row_lenset to that length, which is what production allocates and what a serving stack would pass. Same table, looked up at the bound.Every entry is added by this PR. MI300X (gfx942, 304 CU) has no entry until it is refit with the bound at the buffer width. Cards with no entry are untouched.
The bound is what makes the second table look like the first. Holding the live length fixed and widening the buffer to 1048576 should be free, and for the kernels that read
seq_lenson the device it is; the adaptive kernel pays for it on the host unless it is told. Median of the padded cell over the diagonal cell of the same live length, over the 900 cells where the two differ:radix_topk_one_block, the HIP/C++ kernelmax_row_len#6329's own cases: its 18 shapes at k 2048 in both emit modes, mixed batches included, timed its way (one graph replay plus a sync, median of 31, median of 3 rounds) with
max_row_lenset to the longest live row. Ratio is main's routing over this PR's.MI308X -- gfx942, 80 CU
1000 cells on the diagonal and 900 padded, every combination of:
Per k and emit mode, over the cells of each.
paddedholds the same live length inside a 1048576 buffer withmax_row_lenset to it; every table after this one is the diagonal.Geomean on the diagonal over every k and both emit modes at each shape.
--is a shape the gate declines everywhere, which runs exactly what it runs today.Measured winner per cell on the diagonal.
radix_topk_one_block, the HIP/C++ kernelMI300A -- gfx942, 228 CU
1000 cells on the diagonal and 900 padded, every combination of:
Per k and emit mode, over the cells of each.
paddedholds the same live length inside a 1048576 buffer withmax_row_lenset to it; every table after this one is the diagonal.Geomean on the diagonal over every k and both emit modes at each shape.
--is a shape the gate declines everywhere, which runs exactly what it runs today.Measured winner per cell on the diagonal.
radix_topk_one_block, the HIP/C++ kernelMI350X -- gfx950, 256 CU
1000 cells on the diagonal and 900 padded, every combination of:
Per k and emit mode, over the cells of each.
paddedholds the same live length inside a 1048576 buffer withmax_row_lenset to it; every table after this one is the diagonal.Geomean on the diagonal over every k and both emit modes at each shape.
--is a shape the gate declines everywhere, which runs exactly what it runs today.Measured winner per cell on the diagonal.
radix_topk_one_block, the HIP/C++ kernelVerification
op_tests/test_topk_per_row.py(every section, main's decode and split-reuse tests included),test_topk_per_row_stable.pypass on MI355X, MI350X, MI300A and MI308X at the head;test_topk_select.pypassed on the revisions listed under PR Self-Review.next_n=2, with the launch itself checked at both entry points.seq_lensentry past the width; a bound below the live rows; NaN ranking; stable early stop; and the candidate-buffer builds no band corner reaches, with rows either side of the short-row limit in one launch.op_tests/op_benchmarks/flydsl/bench_topk_per_row_decode.pytimes all four arms on seeded inputs and checks each againsttorch.topkafter the eager call and every replay.torch.topkover each row's live slice: 5700 cells over 3 cards, no incorrect result. On the 2700 padded cells everything past the live length held a poison value, so a read pastseq_lenswould have come back as a wrong answer rather than a plausible one.What is still open
max_row_lenat the buffer width the gate reads the widest band whatever the batch holds. On all four cards the refit above keeps that from costing time: no taken bound = buffer cell is behind main.max(seqLens)would give, is covered by the bound = live slice.max_row_len, is left to a follow-up PR.PR Self-Review
Reviewed revision
5a53b29
Behavior and intent
Decode top-k gains a fourth kernel, the adaptive one, chosen by
decode_backend_for_call()from a table of measured row intervals keyed by(arch, CU count, emit, k, width). No single existing decode kernel wins across the shape space (see Results), so a fixed rule leaves time on the table. The bound is looked up at the next measured width, so any bound reaches the bands that cover it. The adaptive kernel is reached only when the caller passesmax_row_len, the card is in the table and only indices are asked for; every other call routes exactly as it does today, and no result changes, only which kernel produces it.Validation and unverified scope
At
5a53b29f1, FlyDSL 0.5.0, torch 2.10,HIP_VISIBLE_DEVICES=0:python op_tests/test_topk_per_row.py(every section)python op_tests/test_topk_per_row_stable.py5a53b29f1changes the gate's tables and comments and one test;test_topk_select.pyand the plugin tests were not re-run on it.Earlier revisions, same three topk tests unless noted:
d14c61fbftest_topk_per_row.pyandtest_topk_per_row_stable.pypassd23b7fd384d63ae596, andd23b7fd38changes only the gate tablec5600a7test_flydsl_herd.py32 passed, 40 skipped, andtest_moe_topk_gating.py3a3262ae4test_topk_select.pylogs oneFULL-ROWS GRAPH FAILED(thestreamarm does not take n=32768 k=512 on gfx942) and exits 0, as before the refit518eb05cb98987e97dFULL-ROWS GRAPH FAILEDline, exit 04bd49dafftest_topk_per_row.pypass, forced-takeover test included71f1a2c7dHSA_STATUS_ERROR_INVALID_PACKET_FORMAT)Before the merge, the same tests and the benchmark sweeps ran on MI308X, MI300A and MI350X, as in Verification above: 5700 cells against
torch.topk, no incorrect result.Unverified: gfx1250 and MI300X (no table entry, so neither takes the adaptive path); a bound below the buffer on the buffers between widths; CI runners without a device skip the routing test; the per-GPU adaptive launcher has not run on a node with two GPUs.
PR-specific question
No dependency is added; the FlyDSL pin moved to 0.5.0 on main, not here. No C++/HIP source changes, so the AITER JIT modules build as before. The adaptive kernel is FlyDSL, compiled on first use into
FLYDSL_RUNTIME_CACHE_DIR.aiter/jit/utils/chip_info.pygainsget_cu_num_device(), a runtime per-device CU count that honoursCU_NUM;get_build_targets()is unchanged.top_k_per_row_decode()gainsmax_row_len, so its plugin route (#7874) moves to version 2 andtests/plugin_contracts.jsonrecords the new signature; version 1 is not superseded, since a provider written for it would be handed an argument it does not take.c5600a7, a full run from an emptyFLYDSL_RUNTIME_CACHE_DIRwrote 394 files.python op_tests/test_topk_per_row.py --sections adaptiveon that directory passed in 25 s with no file written.Changed op tests
op_tests/test_topk_per_row.py: adds theadaptivesection. It checks the gate's rules on a synthetic table and on every card's bands, the launch at both entry points, mixed-CU nodes, the control buffer staying zero after every launch and replay (an unwarmed capture included), aseq_lensentry past the width, a bound below the live rows, NaN ranking and stable NaN ties, stable early stop, the candidate-buffer build, a grid smaller than the part count, and concurrent replays in both emit modes. A 900 sfaulthandlerdump around the section turns a hang into a traceback.test_decode_bound_rounds_upchecks the rounding: a bound off the grid takes the next measured width and is configured there, never past the buffer; below 4096 it declines, past 1M the 1M band; every carried band admits the bounds that round to it. The ragged cells skip a batch that no band of the k group takes, and thenext_n=2cells skip a band too narrow for one two-row sequence. No other test reaches the adaptive kernel ordecode_backend_for_call().op_tests/test_topk_per_row_stable.py: adds 524288 withmax_row_len=524288for each k and tie level, at the fewest rows the card's band admits there, and asserts that it reaches the adaptive kernel wherever the card's table has such a band. It is the stable tie-breaking check that reaches that kernel; the existing shapes pass no bound and never reach it.op_tests/op_benchmarks/flydsl/bench_topk_per_row_decode.py: new. It times the four arms (adaptive, single, oneblock, hip) on the A1-A4, R (ragged) and B slices, padded widths from 32K, and checks each againsttorch.topkafter the eager call and every replay. The band table was fitted from its output; no existing benchmark compares the decode arms cell by cell, which is what re-fitting the table on a new card needs.--widths,--liveand--bound(width,liveor a number) re-create any buffer, live length and bound, the refit's included.