You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
MiniMax-M3 index-score kernels in FlyDSL (decode + prefill)
Two new FlyDSL kernels that compute the M3 indexer's block scores — the [heads, tokens, blocks] tensor the sparse selector picks top-k from. One for
decode, one for prefill, both reading the paged index cache directly.
Against aiter's pa_sparse_block_score_{decode,prefill} they are 1.04–1.65x
on prefill, at or above parity on decode for the ragged batches a server
actually sends, and they cover the shape M3 runs — 4 index heads, which
aiter has no build for — which that one cannot. gfx950, fp8 row-major cache,
bf16 Q: one shape each, deliberately — an earlier revision carried a
dtype/layout matrix, the maintainer declined to review at that size, and about
2 300 lines were deleted rather than defended.
Supported configuration — one shape each, deliberately
arch
gfx950 only
index cache
fp8, row-major, contiguous pages
Q
bf16
context parallelism
decode only (cp_world / cp_rank). The prefill entry point takes no CP arguments and indexes the whole block range, so a CP caller must shard before calling it
What the 2 300-line deletion removed, and what it does not mean
An earlier revision of this PR carried a dtype/layout matrix: fp8 or bf16
cache, fp8 or bf16 Q, row-major or shuffled pages, gfx942 and
gfx950. The maintainer declined to review at that size, so every arm that M3
does not run was deleted — about 2 300 lines — and the entry points now reject
what they no longer implement instead of advertising it. If one of those arms
is wanted back, it is a revert of a deletion, not new work.
Two notes on what that deletion means:
gfx942 is gone, not broken. It built and the fp8 flavour was arch-selected
(e4m3fnuz vs e4m3fn), but no gfx942 part was ever available to run it, so
the support was never more than "it compiles". Removing it is the honest end
of that, not a regression.
Decode does not use an fp8 MFMA, and that is the contract, not an
oversight. ATOM scores the two phases at deliberately opposite precision: index_topk.py:447 (prefill) does tl.dot(q.to(k.dtype), k), rounding Q down
to fp8, while :1046 (decode) does tl.dot(k.to(q.dtype), q), lifting K to
Q's precision, with a source comment saying the phases are meant to differ.
Converting decode to fp8 would change every score and therefore which blocks
the top-k selector picks.
Performance
MI355X (gfx950), FlyDSL 0.3.4.1, one GPU, measured for this revision. Every
number below is a median with p90/p10 reported; the decode arms are captured
into a CUDA graph because at these shapes the Python wrapper is an order of
magnitude more than the kernel and an eager loop times Python, not the GPU.
err is 0 at rtol=0, atol=0 — bit-exact against aiter, not a tolerance
pass. aiter is both the baseline and the judge here.
2 245 TFLOPS is 46% of the 4.93 PF/s MFMA ceiling measured on this part.
Cross-checked against rocprofv3 --kernel-trace on the same points — 1.04x,
1.32x, 1.69x, 1.33x — so the sweep's wall clock and the kernel durations agree
to within a few percent here. Prefill kernels are long enough that the launch
floor does not distort them, which is not true of the decode table below.
Prefill on a mixed batch
The grid is sized by max_query_len, so a short request in a batch with a long
one gets tiles it cannot fill. Those tiles now retire at the page-range guard
instead of walking the request's causal window first (see the review fixes
below). Measured old-vs-new, alternating arms, p90/p10 ≤ 1.06:
batch
old us
new us
(q 8192, prefix 0) + (q 1, prefix 131 071)
172.2
134.0
1.28x
(q 4096, prefix 0) + 3 × (q 1, prefix 65 535)
121.2
112.0
1.08x
uniform b1 q4096 ctx128K
93.0
94.0
neutral
uniform b4 q1024 ctx16K
45.2
45.0
neutral
Decode — against aiter, on the shapes aiter can build
Real decode batches are ragged, and that is the regime the selector is tuned
for: with the spread map on, a ragged batch is 3–8% faster than with it off,
measured across every geometry the selector can reach.
The table below is the opposite case. Every row uses equal-length requests at a
power-of-two context, which puts the page count at exactly 4 x CU — 32
requests x 32 blocks and 1 request x 1024 blocks are both 1024 pages on a
256-CU part. That is the one shape where the spread map has no uneven last
round to flatten, so it shows only its overhead, and it is where the 0.85–0.96x
rows come from. They are a property of these batches, not of the kernel.
Kernel durations from rocprofv3 --kernel-trace, not wall clock:
B
heads
ctx
aiter us
FlyDSL us
speedup
2
1
4 096
4.24
3.12
1.36x
2
2
4 096
4.32
3.08
1.40x
2
1
32 768
4.76
4.16
1.14x
2
2
32 768
4.40
3.60
1.22x
32
1
4 096
5.40
5.60
0.96x
32
2
4 096
4.64
5.44
0.85x
128
1
8 192
20.84
21.56
0.97x
128
2
8 192
21.04
21.64
0.97x
Medians over three rounds. The 4-5 us rows move by a few percent between runs
even on an idle node, so read them as "about 1.35x" and "about 0.9x", not to
the second decimal; the 21 us rows are stable to ~1%.
The 128-request rows are fixed in this PR: the served depth ladder defaulted to
4 pages per wave past the tabled batches, which is right only once a request is
long enough to keep its own CTAs busy, and sizing it by the context instead
moves ctx 8K from 0.91-0.93x to parity. Contexts past max_block 256 take the
path they took before.
The work map is hoisted out of the timed region in both arms, which is how
production calls it: it is built once per step and reused by every layer.
Scores differ from aiter by 2.7e-05 to 7.6e-05 — that is the precision contract
above (ours lifts K to bf16, aiter uses an fp8 MFMA), not a tolerance failure.
The ragged/uniform crosstab, and why the selector cannot condition on it
Chasing the 0.85-0.96x rows with every geometry the selector can reach,
measured in one process with the arm order rotated so no arm keeps a fixed
cache state:
batch shape
spread on (picked)
spread off
uniform, aligned (this table)
7.64 us
6.96 us
spread costs 10%
ragged, same bounds
6.88 us
7.08 us
spread wins 3%
ragged, ctx 8 192
9.00 us
9.72 us
spread wins 8%
Real decode batches are ragged, so the selector's choice is the right one and
this is left alone. It also cannot be conditioned: geometry sizes from the
BOUNDS only, never from seq_lens contents, so that a captured graph replays —
and raggedness is exactly what decides the sign. Worth stating plainly because
the table above cannot show it: on the batches a server actually sends, these
rows are wins.
Two earlier revisions of this section reported different numbers, both
superseded:
Parity (0.95-1.02x) from a CUDA-graph wall-clock harness. That was a
measurement artifact: the harness carried a ~10 us constant floor that both
arms paid equally, which compresses every ratio toward 1.00. The kernel trace
is the honest instrument here, and it says something quite different in both
directions.
The 128-request rows as 0.91-0.93x, described as a standing property to be
fixed elsewhere. They are fixed here, by the depth change described above.
Decode at the shape M3 actually runs
M3 uses 4 index heads. pa_sparse_block_score_decode has no build for num_idx_heads=4; it raises rather than running:
S, H
aiter
1, 1
builds
1, 2
builds
1, 4
no build
4, 4 / 8, 4 / 16, 4
no build
So for M3 decode this is not a speedup over aiter, it is the only option.
Correctness
271 passed, 2 skipped on gfx950, one test file.
Prefill is judged bit-exact against pa_sparse_block_score_prefill over
the reachable geometry arms, plus mixed query lengths, strided caches, padded
chunk axes and malformed-tensor rejection.
Decode is judged against an oracle transcribed from the operator contract
rather than from the kernel, so it cannot inherit the implementation's
assumptions.
Every geometry arm must agree bit for bit with every other. These are the
same arithmetic in different geometries, not different approximations of it.
Exhaustiveness tests assert that every geometry the selector can reach has an
arm, so narrowing the selector cannot silently drop coverage.
Review fixes in this PR
Sixteen findings reproduced and fixed, two refuted with measurements. Every
fix is host-side, and that is measured rather than asserted: md5 of the device
ELF pulled out of a cold compile (FLYDSL_DUMP_IR=1, the gpu.binary blob,
one runtime cache per arm). All 38 code objects this suite builds are
byte-identical at this PR's head and at the head of the previous review round,
the decode, decode-under-CP and prefill arms production selects among them.
The check is calibrated rather than assumed: changing one device-side constant
in the decode builder moves 31 of the 38 hashes and leaves exactly the 7
prefill objects alone, so it tracks codegen and localises it.
The earlier rounds were checked the same way, on the objects production selects
rather than on all 38. Recorded there: the one decode object that moved is the
page-loop depth change described above, which selects a different kernel rather
than emitting a different one; prefill's moved with the earlier staging fixes,
at 120 VGPRs and 41 SGPRs with no spills, so occupancy is unchanged.
The first refutation is the residual runs list in the prefill page loop. LDS_TRIP is PPW if PPW % 2 == 0 else 2 * PPW, always a multiple of PPW,
so runs is empty at the end of every trip; the short tail is already
predicated by store_run's base + len(runs) <= blk_hi.
The second is the spread map's row-budget clamp, reported as silently dropping pages at B=1, max_block=1100, 1028 pages on a 304-CU part. It does the opposite: a
thin row carries a span, not a page, so the 275 rows cover 1028 pages exactly
(base = 1028 // 275 = 3, extra = 203, 275 * 3 + 203 = 1028). Remove the
clamp and thin becomes 303 against 276 available rows, 27 rows are truncated
and 81 pages go unscored. The report did find a real gap in the test, though:
its cu parametrisation was only reaching random.Random, so all three arms
ran at this part's own CU count. The count is forced now.
The sixteen findings, each reproduced before being changed
finding
what it actually was
work_map_size vs build_work_map
read different CU counts under CU_NUM — 64 rows vs 128, buffer refused
legacy-map rescue
only knew waves_per_tok, so every spread geometry raised "expected exact grid slice" (1024 rows vs 1028). Now deleted: S/H change the geometry, so the map sizes with them or not at all
optional S/H
geometry, work_map_size, work_map_capacity and build_work_map defaulted them; nothing in-tree or in ATOM ever omitted them, and a map built without them is indexed with the wrong stride
duplicated _cu_count
the prefill scorer carried its own, memoised, which froze the CU_NUM read — the divergence the first row fixes. It now imports decode's; the warm path calls it zero times
index_score_supported
returned True for calls score_flydsl then rejected, and advertised block_table/seq_lens as optional while refusing both. Both are required now
prefill idx_q strides
overlap was checked, 16-byte alignment was not
prefill sm_scale
the page max is taken before the scale, so a negative one returns the wrong block
dead prefill tiles
walked the full causal window before storing nothing
prefill cache alignment
an outer stride of 16385 fp8 elements cleared a page but left every page after the first unaligned; decode already refused it
alloc_score (both)
handed back torch.empty, and the kernels store only each row's causal window -- 25% of the prefill buffer at q256/ctx256, 31% of decode's on a ragged batch, reaching the top-k selector as arbitrary memory. -inf now
two arch probes
prefill queried the driver before checking the device type, so a CPU-only runner got RuntimeError: No HIP GPUs are available; one _validate_arch now, which removed the copy and the bug together
trailing empty request
staged Q from one row past idx_q
requires_gfx950
seven tests would fail rather than skip on a CPU runner
make_prefill_case(heads)
sized the score buffer by heads while Q kept one head
prefill launch bounds
max_query_len/max_seq_len were checked for being positive but not for fitting the i32 token arithmetic they feed, and max_seq_len sizes alloc_score, so an absurd bound allocated before anything rejected it. Both are bounded by 0x7FFFFFFF - (PAGE - 1) now, before max_block is derived
spread-map invariant test (ours, found while reproducing the spread-clamp report)
parametrised the CU count but passed it only to random.Random, and get_cu_num caches its first read, so all three arms ran at this part's count. Forced now, and the 304-CU case from the report is the first one it builds
What is in the diff
Five files, +5044/-1: two new kernels, their one test file, the lazy exports,
and 16 lines of tensor_shim.py.
tensor_shim.py gains a cache_modifier pass-through on buf_copy_atom plus a
check on unit_bytes; it is the only shared file touched, and every existing
caller keeps its behaviour. cache_modifier is deliberately not
range-checked there: its width is architecture-dependent, and capping it at 2
bits broke five gfx1250 mxfp8 GEMM kernels, which pass CPOL_DEV (0x10).
The exports are lazy, so nothing in this repo dispatches to these kernels yet —
the consumer is ATOM, and that integration is a separate change.
Not in scope
ATOM integration and the vLLM PR.
A producer-side shuffled index cache. It was implemented and then reverted:
the scorers read the row-major cache, and the shuffled layout was worth ~5% on
prefill, which did not justify a second addressing mode in fused_qknorm_idxrqknorm.
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 5626 --add-label <label>
PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.
The reason will be displayed to describe this comment to others. Learn more.
Note
Copilot was unable to run its full agentic suite in this review.
Pull request overview
Adds a new FlyDSL implementation of the MiniMax-M3 decode index-score kernel along with a correctness oracle, a hardware lane-mapping probe, and a benchmarking harness.
…e GPU gate
Two review findings from PR #5626.
block_table validation checked the row count and both strides but never the
column count, so a table paired with a larger max_block was accepted and the
kernel read past its end. Reject shape[1] < max_block.
Under context parallelism that bound is necessary but not sufficient: the
table is indexed by the global block `p * cp_world + cp_rank`, so a rank with
a non-empty shard needs columns past its own local bound, and how far past
depends on seq_lens -- which a metadata-only predicate never reads. The width
of a CP table therefore stays the caller contract the validator already
documents; the comment now says so at the site. The one case decidable here
is the empty shard, which the kernel already handles by clamping its
speculative load to column 0, and which test_empty_cp_shard_narrow_table
covers -- so the check cannot be tightened to the global span without
dropping a supported configuration.
_GPU_TESTS was missing five tests that allocate device tensors
(test_chunk_map_kernel_matches_reference, test_spread_map_kernel_matches_
reference, test_spread_scores, test_spread_graph_replay,
test_auto_token_legacy_map). They assert host-side properties, which is
presumably why they were left out, but they still build their inputs on the
device, so on a non-gfx950 host they errored instead of skipping.
393 passed, 2 skipped on gfx950.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This test is not covered by requires_gfx950 but passes torch.device("cuda") to prefill_geometry, which calls torch.cuda.get_device_properties through _cu_count. On CPU or a non-gfx950 runner, collection succeeds but this test executes and fails instead of being skipped, so the documented architecture gating is incomplete.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. I re-checked everything against 58c5f7ac. Several things from the earlier version are now fixed:
block_table, cu_seqlens_q, seq_lens and prefix_lens layouts are validated;
the cache must have contiguous pages;
the prefill scorer and its allocator are exported;
non-positive launch bounds are rejected.
A few gaps remain, below, each with an example. Inline comments point at the lines.
1. Prefill: Q strides must also be 16-byte aligned
The new check (idx_q.stride(2) == 1 and idx_q.stride(1) >= HEAD_DIM) rules out overlapping heads, but not misaligned ones. q_fp8_at turns the bf16 element offset into a dword offset with off >> 1 and then does a vector load. An odd row or head stride is therefore truncated by one element, and the load is unaligned.
Example: idx_q = buf[..., :128] with buf of shape [T, H, 129] (bf16). stride(1) = 129 passes the check. Head 1 starts at element 129, the kernel reads from element 128 (one feature early), and the scores are silently wrong.
The decode scorer already states the right contract, in _validate_metadata:
ift.stride(2) !=1orany(st*t.element_size() %16forstint.stride()[:2]):
raiseValueError(f"{name}: rows and heads/pages must be 16-byte aligned")
Applying the same check to prefill's idx_q would close this.
2. Prefill: query tiles past q_len still walk the whole context
hi_tok is clamped only by seq_len (prefill.py:526-527). A tile with q_base >= q_len therefore loads and MFMAs every page of its causal window, then stores nothing. Triton returns early on BLOCK_SIZE_Q * pid_q >= q_len. The grid is sized by max_query_len, so in a mixed batch the short requests pay for the long one.
Example with tile_q = 128: request A has q = 8192, prefix = 0, and request B has q = 1, prefix = 131071. B's 64 query tiles each walk about 1024 pages, 64× B's real work, and they dominate the launch.
The same clamp also reads out of range. Out-of-range rows are redirected to row 0 of the request (q = (q < q_len).select(q, 0)). For a trailing empty request, cu[b] == cu[b+1] == total_q, so that row is total_q, one past the end of idx_q. That faults if idx_q ends its allocation.
An early exit for q_base >= q_len (before the page loop) fixes both.
3. Decode: work-map helpers and the entry point disagree
Legacy maps no longer match. The work_map_size docstring says "Omitting S/H keeps the legacy unsplit map, which score_flydsl accepts with the matching geometry". But the spread geometry adds one row per request, and the legacy rescue in _validate_metadata only covers waves_per_tok > 1. With the CU count pinned to 256, at this head:
batch, max_block, S, H
legacy map rows
rows score_flydsl expects
4, 1024, 4, 1
1024
1028
1, 1024, 4, 1
256
257
4, 1024, 1, 1
1024
1028
32, 1024, 4, 1
2048
2048 (OK)
So a caller following the docstring gets "expected exact grid slice" for the first three. Either the rescue needs to cover the spread case, or the docstring should require S/H.
CU count comes from two places._cu_count(None) returns get_cu_num(), which honours the CU_NUM environment variable. _cu_count(device) returns torch's multi_processor_count. work_map_size/work_map_capacity default to device=None, and the docstring does not say to pass a device. build_work_map and _make_map resolve with seq_lens.device. Example: with CU_NUM=64 (common when tuning) on a 256-CU part and S=1, H=1, batch=1, max_block=128, work_map_size gives 64 rows and build_work_map gives 128. A buffer sized by the former is rejected by the latter ("expected packed [at least 128, 2]"). Using one source for both (and passing the device through) avoids the split.
The support predicate can say yes to a call that fails.index_score_supported documents itself as sharing the entry point's validation. But _validate_metadata skips block_table/seq_lens when they are None, which is the predicate's default, and the predicate takes no sm_scale. A dispatcher that asks minimax_m3_index_score_flydsl_supported(q, cache, S, H, mb), gets True and routes to FlyDSL then sees score_flydsl raise "block_table and seq_lens are required", or reject the scale. Making those arguments required in the predicate, or validating them there too, keeps the two in step.
4. Shared code between the two scorers
Export is fixed, but prefill still has no *_supported predicate. ATOM-side dispatch can only find out by calling it and catching the error.
Prefill imports nothing from the decode module, so these exist twice:
LOG2E, _CTA_OVERSUBSCRIBE, _cu_count, _CACHE/_get, alloc_score, load_k16, and the arch probe.
The copies have already diverged: prefill's _cu_count is memoised with @cache (its comment measured the uncached query at 1.7× a 22 µs kernel), while decode's is not, and decode calls it on every launch. Validation diverged the same way: the alignment check in section 1 exists only in decode. A small shared helper module for the host-side pieces would keep fixes like these in one place.
`max_query_len` and `max_seq_len` size the grid and nothing downstream
re-checked them. `max_query_len=0` launched an empty query grid and
returned silently -- the worst outcome, since the caller gets a buffer of
sentinels and no signal that it asked for nothing. `max_seq_len=0`
reached `hipModuleLaunchKernel` as a zero dimension and surfaced as
`hipErrorInvalidValue`, which names no argument.
The decode scorer already rejects its equivalents (`max_block`, `S`, `H`);
this states the same contract for prefill, `heads` included.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A rename regex during the test merge rewrote the word inside the skip
string too, so the prefill perf sweep pointed at
`test_flydsl_minimax_m3_index_score_prefill.py` -- which no longer
exists. Both sweeps now name the file that does.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Seven things the review found, each verified against the code before being
changed and none of them cosmetic:
**The two map-sizing entry points could disagree.** `work_map_size` has no
tensor and resolves its geometry with `device=None`, which reads `CU_NUM`;
`build_work_map` resolves from `seq_lens.device`, which reads torch. With
`CU_NUM=64` on a 256-CU part one said 64 rows and the other 128, and the
buffer the first sized was refused by the second. `CU_NUM` now wins on both
paths and on the spread builder's own apportionment, so there is one count.
**The legacy-map rescue only knew about the wave split.** A map from the
two-argument `build_work_map` has unsplit geometry, and the rescue that
honours it open-coded `waves_per_tok`. S/H can change `spread` instead:
`work_map_size(4, 1024)` is 1024 rows where S=4,H=1 wants 1028, one spare row
per request, and the scorer raised "expected exact grid slice" on a map it had
just been told how to read. It now asks `geometry` for the legacy shape.
**`index_score_supported` did not answer for the entry point.**
`_validate_metadata` skips `block_table`/`seq_lens` when they are None and
never sees the scale, so the predicate returned True for calls `score_flydsl`
then rejected -- a dispatcher that trusted it took a raise instead of a
fallback.
**Prefill ruled out overlapping Q rows but not misaligned ones.** `q_fp8_at`
turns a bf16 element offset into a dword offset and vector-loads it, so an odd
or 2-mod-16 head stride reads off its boundary: `buf[T, H, 129][..., :128]`
passes the overlap check and still starts head 1 at element 128. Decode's
16-byte check is now stated here too.
**Prefill accepted any `sm_scale`.** The epilogue takes each page's max and
only then multiplies, so a negative scale returns `max(dot) * scale` rather
than `max(dot * scale)` -- a different block, silently. Decode already refused
these.
**A tile past its request's last query row walked the whole causal window.**
The grid is sized by `max_query_len`, so in a mixed batch -- (q 8192, prefix 0)
next to (q 1, prefix 131071) -- the short request still got 64 tiles, each
scanning about 1024 pages to store nothing. `q_base < q_len` joins the
page-range guard, which costs nothing on a uniform batch and is 1.28x on that
mixed one. It is on the guard rather than clamping `hi_tok` because the clamp
form cost 2-3% at b4/q1024/ctx16K.
**A trailing empty request read one row past `idx_q`.** Its tiles still stage
Q, and the `q < q_len` clamp addressed `seq_start + 0`, which for the last
request is `total_q`; the buffer view's num_records is the view maximum, not
the tensor, so nothing caught it. The correction folds into the staging origin,
which is CTA-uniform, instead of clamping each staged row.
Seven tests unmarked with `requires_gfx950` reach `get_cu_num` or a device
query and would fail rather than skip on a CPU runner; the ones that monkeypatch
the CU count are left alone, since they are genuinely CPU-safe. `heads` now
builds the Q it promises in `make_prefill_case` -- sizing the score buffer by it
while Q kept one head made every head sweep a shape rejection.
Not changed: the reviewer's residual-`runs` report is a false positive.
`LDS_TRIP` is `PPW if PPW % 2 == 0 else 2 * PPW`, always a multiple of PPW, so
`runs` is empty at the end of every trip, and the short tail is already
predicated by `store_run`'s `base + len(runs) <= blk_hi`.
Decode's two code objects are byte-identical to before this commit -- every
decode change is host-side. Prefill's moved, as intended, at 120 VGPRs and 41
SGPRs with no spills, so occupancy is unchanged. 263 passed, 3 skipped.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The served depth ladder defaults to 4 pages per wave past the tabled batches,
and that number was measured at one context. It does not carry. Swept at
batch 128 over max_block 32 to 1024 with `rocprofv3 --kernel-trace`, depth 4
gives up 5-19% across max_block 48-128 -- which includes ctx 8K, where this
kernel was 0.91-0.93x against `pa_sparse_block_score_decode`. Depth 2 there
measures 1.06-1.09x over depth 4 on six independent shapes (H 1, 2 and 4,
batch 24 through 256), and the aiter comparison moves to 0.98-1.01x.
Bounded at max_block 256 rather than written as a formula. The curve is not
monotone -- 192 and 256 want 1, 512 and 1024 want 4 again -- so a formula
fitted through it would be fitting noise, and above 256 the old ladder is
still the best of the three depths measured. Contexts past that take exactly
the path they take today.
The rule stops at 2, never 1, which also keeps `spread` where it is: it is
gated on `pages_per_wave == 1`, so a rule reaching 1 would have switched 60
configurations onto the spread work map as a side effect. Enumerating the
selector over the whole envelope confirms `pages_per_wave` is the only field
that changes, on 215 of 660 configurations.
Measurement notes, since two earlier readings of this were wrong. Wall clock
cannot resolve these kernels: a CUDA-graph harness carried a ~10 us constant
floor that both arms paid equally and reported every shape as parity, hiding
a 1.4x win at small batch and a 0.86x loss at large. The numbers above are
kernel durations from the trace. Each sweep brackets itself with the same
control configuration at both ends -- 21.56 and 21.12 us here -- and reports
p90/p10 per configuration, so a neighbour arriving mid-sweep shows up in the
data rather than in a guess about the node.
The code objects are unchanged: this moves which kernel is selected, not how
any of them is generated.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The comments had become a lab notebook. Whole blocks were tables of our own
measurements -- VGPR counts against microseconds, per-configuration ratios,
lists of ablations that did not move anything -- which tell a reader nothing
about what the code does and are the first thing to go stale. Comments and
docstrings were 28% of these three files.
What is kept is the shape of each decision and every trap that fails
silently: the even FEAT_TILES_PER_WAVE the 32x32 pairing needs, the even
k_lds trip the two page buffers need, Q living in page buffer 1, the 16-byte
Q stride, the order-preserving scale, the aliasing rule on `out`, the k-axis
permutation the two scorers must agree on. Those are the ones where getting
it wrong produces wrong scores rather than a crash, so they earn their lines.
Three things that were not just verbose but wrong, left behind when the
unreachable arms were deleted:
* the prefill module docstring named five symbols that no longer exist
(`convert_k`, `fp8_mfma`, `k_operand`, `trip_pages`, `_ns_off`) and
described the fp8-Q and bf16-widening paths as if they were still there.
* a comment in the tests explained the shuffled cache layout's cache
policy. That layout was reverted.
* the prefill section header told the reader to run
`op_tests/test_flydsl_minimax_m3_index_score_prefill.py`, which the merge
into this file deleted.
`force_arch` goes with them: it forced gfx942 onto a gfx950 device and had no
callers left once gfx942 support was removed.
No behaviour change. The two kernel modules parse to identical ASTs once
docstrings are stripped, and all three production code objects are
byte-identical to the previous commit's.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`_validate_metadata` read `torch.cuda.get_device_properties(idx_q.device)` to
get the arch before it had established that the tensor was on a GPU at all.
On a machine with one, a CPU tensor makes that call raise something
`index_score_supported` catches, so it returned False and nothing looked
wrong. On a machine without one it is `RuntimeError: No HIP GPUs are
available`, raised straight through a predicate whose own docstring says
"metadata only: no device reads" -- and a dispatcher is allowed to call it
anywhere.
`test_metadata_rejects_cpu` is the proof: a test whose entire subject is
rejecting CPU tensors could not run on a CPU-only machine. Checking
`device.type` first makes the CPU case the plain rejection it always should
have been.
`test_every_lazy_export_resolves` needed the gfx950 marker instead of a fix.
It touches no kernel, but resolving every lazy name imports modules outside
M3 whose own import queries the arch, so the GPU requirement is real and
belongs in the marker rather than in a workaround here.
The whole file now behaves on a CPU runner: 39 passed, 227 skipped, nothing
failed. It was 3 failed before. Code objects are unchanged -- this is host
side only.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The comment on the decode depth rule implied the deeper default above
max_block 256 was the better choice there. It is not better; it stopped
mattering. Swept to max_block 8192 -- ctx 1M -- with the real selector and
three source variants, depths 1, 2 and 4 land within 2% of each other at every
batch from 32 to 128, and the direction flips between batches.
The reason is in the bytes. At those shapes the kernel reads 5.7-6.0 TB/s
against this part's measured 6.3-6.4 TB/s ceiling, so it is at the roof and
the per-wave loop shape has nothing left to win. Which also retires the
argument this rule was originally bounded on: the regression at max_block
1024 that made me keep the deeper default does not generalise upward, because
nothing does up there.
Keeping 4 above the bound, since that is what shipped and 2 measures the same.
What changes is that the comment now says why, and says it from measurement
rather than from an extrapolation past the last point swept.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Four findings held, each checked against the code before being changed.
**The prefill launcher cache was not keyed on the device.** `_run_compiled`
memoises the compiled handle on the launcher object, so two gfx950 devices
sharing one launcher would run the first device's handle on the second. The
decode scorer already keys this way and has `test_noncurrent_device`; prefill
now does too.
**A cache whose pages overlap was accepted.** The page checks covered the rows
inside a page and said nothing about the distance between pages, but
`page_buffer` advances by `stride(0)` -- so `(1, 128, 1)` passed and made every
page overlap the one before it, scoring the wrong pages with no error.
**A Q view whose rows overlap was accepted.** The head stride was bounded and
the row stride was not, so `[rows, 2, 128]` strided `(128, 128, 1)` passed
while row 1 aliased head 1 of row 0. Both now use the extent check the decode
path uses.
**A comment in the decode validator still offered an fp8 Q** two lines above
the check that accepts bfloat16 only.
One finding is NOT a defect and nothing changed for it: the prefill MFMA atom
is `MFMA_Scale` with its scale operands left at the atom default, which the
report says must be an explicit UE8M0 identity or every score is wrong. Both
reachable prefill geometries were compiled and disassembled: they emit
`v_mfma_f32_32x32x64_f8f6f4` and `v_mfma_f32_16x16x128_f8f6f4`, the UNSCALED
encodings, and no `v_mfma_scale*` instruction appears in any of the three
production code objects. The bit-exact agreement with aiter says the same
thing independently.
The last finding asks for the ragged arrays' contents to be validated --
`cu_seqlens_q` monotonic and ending at `total_q`, `seq_lens` within
`max_seq_len`. Those are device reads. The grid is sized from the bounds
precisely so that it survives a cudagraph replay, and a validator that read
the lengths would stall every launch and make the grid depend on data that
can change between replays. The decode scorer states this as a caller
contract; the prefill entry point now states the same one explicitly instead
of leaving it implied.
Also restores four words in the test file that a rename regex had rewritten
inside prose, including a docstring that described "a flat run_prefill of 16 B
chunks".
265 passed, 4 skipped on gfx950; 39 passed, 230 skipped with no GPU visible.
Code objects unchanged.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
[verified] --batch uses nargs="*", so an explicitly empty --batch is represented by [] and the CLI documentation/tests treat that as selecting no work. args.batch or [1] converts that explicit empty selection back into batch 1 for the prefill sweep, unexpectedly launching benchmarks. Author must distinguish None (default) from [] here.
`geometry`, `work_map_size`, `work_map_capacity` and `build_work_map` took
S and H as optional, and `_validate_metadata` carried a rescue path for a
map built without them. Nothing in-tree or in ATOM ever called them that
way, so the rescue was an untested branch guarding a caller that does not
exist -- and S/H change the geometry, so a map built without them is a map
the kernel indexes with the wrong stride. They are required now and the
rescue is gone. `index_score_supported` likewise advertised `block_table`
and `seq_lens` as optional while refusing both; a caller that omits one
now finds out at the call, not from a False it has to interpret.
The two scorers had also grown a second copy of `_cu_count` and of the
row/head stride rule. Prefill now imports both from decode. Its copy was
memoised, which froze the `CU_NUM` read -- the exact divergence decode's
own docstring says must not happen -- and bought nothing: the `_auto_*`
helpers that ask for the count are themselves memoised, so the warm path
calls it zero times (measured: 0.385 us per `geometry`, 0 calls).
All three production code objects are bit-identical.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Only positivity is checked here, but these bounds become Int32 launch arguments and max_seq_len is converted to block indices that are multiplied by 128 in the kernel. Values above the signed-32-bit causal range can therefore wrap dimensions/addresses instead of being rejected. Apply the same INT32_MAX - 127 upper bound used by the decode-side arithmetic before deriving max_block.
…t code
Three gaps the reviewers found, each reproduced before being changed:
- The prefill cache check cleared a whole page but never a 16-byte
boundary. `ptr_buf_tensor` declares 16-byte alignment and the copy atom
moves 16 B at a time, so an outer stride of 16385 fp8 elements left every
page after the first unaligned -- in bounds, so only the alignment rule
catches it. Decode already refused it; prefill now runs the same
`_validate_rows`.
- Both `alloc_score`s handed back `torch.empty`. The kernels store only the
pages inside a row's window, so at prefill q256/ctx256 a quarter of the
buffer, and on a ragged decode batch a third of it, was never written. The
top-k selector downstream reads those slots and can pick a block that does
not exist. They are -inf now; a caller passing `out` owes it the same.
- The two arch probes are one `_validate_arch`. That removes the copy and
fixes prefill with it: it queried the driver before checking the device
type, so on a runner with no card it raised `RuntimeError: No HIP GPUs are
available` where decode returns a rejection. `LOG2E` is imported rather
than redefined.
What is left with a shared name -- `_get`, `alloc_score`, `geometry`,
`kernel_name`, `feature_tiles` -- has genuinely different bodies per kernel;
merging them would mean a parameterised helper, which is more code, not less.
All three production code objects stay byte-identical.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…p at the CU count it was questioned at
`max_query_len`/`max_seq_len` were checked for being positive but not for
fitting the i32 token arithmetic they feed; `max_seq_len` also sizes
`alloc_score`, so an absurd bound allocated before anything rejected it.
Decode already states this contract as "causal token address exceeds int32".
The spread-map invariant test parametrised `cu` but only used it as a random
seed -- `get_cu_num` caches its first read, so every arm ran at this part's
own count. It now forces the count the way `test_prefill_reads_the_same_cu_override`
does, and leads with the 304-CU case reported as dropping pages: 1028 pages
against a 276-row budget, covered exactly by the rows' spans.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
MiniMax-M3 index-score kernels in FlyDSL (decode + prefill)
Two new FlyDSL kernels that compute the M3 indexer's block scores — the
[heads, tokens, blocks]tensor the sparse selector picks top-k from. One fordecode, one for prefill, both reading the paged index cache directly.
Against aiter's
pa_sparse_block_score_{decode,prefill}they are 1.04–1.65xon prefill, at or above parity on decode for the ragged batches a server
actually sends, and they cover the shape M3 runs — 4 index heads, which
aiter has no build for — which that one cannot. gfx950, fp8 row-major cache,
bf16 Q: one shape each, deliberately — an earlier revision carried a
dtype/layout matrix, the maintainer declined to review at that size, and about
2 300 lines were deleted rather than defended.
Supported configuration — one shape each, deliberately
cp_world/cp_rank). The prefill entry point takes no CP arguments and indexes the whole block range, so a CP caller must shard before calling itWhat the 2 300-line deletion removed, and what it does not mean
An earlier revision of this PR carried a dtype/layout matrix: fp8 or bf16
cache, fp8 or bf16 Q, row-major or shuffled pages, gfx942 and
gfx950. The maintainer declined to review at that size, so every arm that M3
does not run was deleted — about 2 300 lines — and the entry points now reject
what they no longer implement instead of advertising it. If one of those arms
is wanted back, it is a revert of a deletion, not new work.
Two notes on what that deletion means:
(
e4m3fnuzvse4m3fn), but no gfx942 part was ever available to run it, sothe support was never more than "it compiles". Removing it is the honest end
of that, not a regression.
oversight. ATOM scores the two phases at deliberately opposite precision:
index_topk.py:447(prefill) doestl.dot(q.to(k.dtype), k), rounding Q downto fp8, while
:1046(decode) doestl.dot(k.to(q.dtype), q), lifting K toQ's precision, with a source comment saying the phases are meant to differ.
Converting decode to fp8 would change every score and therefore which blocks
the top-k selector picks.
Performance
MI355X (gfx950), FlyDSL 0.3.4.1, one GPU, measured for this revision. Every
number below is a median with p90/p10 reported; the decode arms are captured
into a CUDA graph because at these shapes the Python wrapper is an order of
magnitude more than the kernel and an eager loop times Python, not the GPU.
Prefill — reproducible from this PR
batch 1, q_len 4096, fp8 cache, 1 index head:
erris 0 atrtol=0, atol=0— bit-exact against aiter, not a tolerancepass. aiter is both the baseline and the judge here.
2 245 TFLOPS is 46% of the 4.93 PF/s MFMA ceiling measured on this part.
Cross-checked against
rocprofv3 --kernel-traceon the same points — 1.04x,1.32x, 1.69x, 1.33x — so the sweep's wall clock and the kernel durations agree
to within a few percent here. Prefill kernels are long enough that the launch
floor does not distort them, which is not true of the decode table below.
Prefill on a mixed batch
The grid is sized by
max_query_len, so a short request in a batch with a longone gets tiles it cannot fill. Those tiles now retire at the page-range guard
instead of walking the request's causal window first (see the review fixes
below). Measured old-vs-new, alternating arms, p90/p10 ≤ 1.06:
Decode — against aiter, on the shapes aiter can build
Real decode batches are ragged, and that is the regime the selector is tuned
for: with the spread map on, a ragged batch is 3–8% faster than with it off,
measured across every geometry the selector can reach.
The table below is the opposite case. Every row uses equal-length requests at a
power-of-two context, which puts the page count at exactly
4 x CU— 32requests x 32 blocks and 1 request x 1024 blocks are both 1024 pages on a
256-CU part. That is the one shape where the spread map has no uneven last
round to flatten, so it shows only its overhead, and it is where the 0.85–0.96x
rows come from. They are a property of these batches, not of the kernel.
Kernel durations from
rocprofv3 --kernel-trace, not wall clock:Medians over three rounds. The 4-5 us rows move by a few percent between runs
even on an idle node, so read them as "about 1.35x" and "about 0.9x", not to
the second decimal; the 21 us rows are stable to ~1%.
The 128-request rows are fixed in this PR: the served depth ladder defaulted to
4 pages per wave past the tabled batches, which is right only once a request is
long enough to keep its own CTAs busy, and sizing it by the context instead
moves ctx 8K from 0.91-0.93x to parity. Contexts past max_block 256 take the
path they took before.
The work map is hoisted out of the timed region in both arms, which is how
production calls it: it is built once per step and reused by every layer.
Scores differ from aiter by 2.7e-05 to 7.6e-05 — that is the precision contract
above (ours lifts K to bf16, aiter uses an fp8 MFMA), not a tolerance failure.
The ragged/uniform crosstab, and why the selector cannot condition on it
Chasing the 0.85-0.96x rows with every geometry the selector can reach,
measured in one process with the arm order rotated so no arm keeps a fixed
cache state:
Real decode batches are ragged, so the selector's choice is the right one and
this is left alone. It also cannot be conditioned:
geometrysizes from theBOUNDS only, never from
seq_lenscontents, so that a captured graph replays —and raggedness is exactly what decides the sign. Worth stating plainly because
the table above cannot show it: on the batches a server actually sends, these
rows are wins.
Two earlier revisions of this section reported different numbers, both
superseded:
measurement artifact: the harness carried a ~10 us constant floor that both
arms paid equally, which compresses every ratio toward 1.00. The kernel trace
is the honest instrument here, and it says something quite different in both
directions.
fixed elsewhere. They are fixed here, by the depth change described above.
Decode at the shape M3 actually runs
M3 uses 4 index heads.
pa_sparse_block_score_decodehas no build fornum_idx_heads=4; it raises rather than running:So for M3 decode this is not a speedup over aiter, it is the only option.
Correctness
pa_sparse_block_score_prefilloverthe reachable geometry arms, plus mixed query lengths, strided caches, padded
chunk axes and malformed-tensor rejection.
rather than from the kernel, so it cannot inherit the implementation's
assumptions.
same arithmetic in different geometries, not different approximations of it.
arm, so narrowing the selector cannot silently drop coverage.
Review fixes in this PR
Sixteen findings reproduced and fixed, two refuted with measurements. Every
fix is host-side, and that is measured rather than asserted: md5 of the device
ELF pulled out of a cold compile (
FLYDSL_DUMP_IR=1, thegpu.binaryblob,one runtime cache per arm). All 38 code objects this suite builds are
byte-identical at this PR's head and at the head of the previous review round,
the decode, decode-under-CP and prefill arms production selects among them.
The check is calibrated rather than assumed: changing one device-side constant
in the decode builder moves 31 of the 38 hashes and leaves exactly the 7
prefill objects alone, so it tracks codegen and localises it.
The earlier rounds were checked the same way, on the objects production selects
rather than on all 38. Recorded there: the one decode object that moved is the
page-loop depth change described above, which selects a different kernel rather
than emitting a different one; prefill's moved with the earlier staging fixes,
at 120 VGPRs and 41 SGPRs with no spills, so occupancy is unchanged.
The first refutation is the residual
runslist in the prefill page loop.LDS_TRIPisPPW if PPW % 2 == 0 else 2 * PPW, always a multiple ofPPW,so
runsis empty at the end of every trip; the short tail is alreadypredicated by
store_run'sbase + len(runs) <= blk_hi.The second is the spread map's row-budget clamp, reported as silently dropping pages at
B=1,max_block=1100, 1028 pages on a 304-CU part. It does the opposite: athin row carries a span, not a page, so the 275 rows cover 1028 pages exactly
(
base = 1028 // 275 = 3,extra = 203,275 * 3 + 203 = 1028). Remove theclamp and
thinbecomes 303 against 276 available rows, 27 rows are truncatedand 81 pages go unscored. The report did find a real gap in the test, though:
its
cuparametrisation was only reachingrandom.Random, so all three armsran at this part's own CU count. The count is forced now.
The sixteen findings, each reproduced before being changed
work_map_sizevsbuild_work_mapCU_NUM— 64 rows vs 128, buffer refusedwaves_per_tok, so everyspreadgeometry raised "expected exact grid slice" (1024 rows vs 1028). Now deleted: S/H change the geometry, so the map sizes with them or not at allS/Hgeometry,work_map_size,work_map_capacityandbuild_work_mapdefaulted them; nothing in-tree or in ATOM ever omitted them, and a map built without them is indexed with the wrong stride_cu_countCU_NUMread — the divergence the first row fixes. It now imports decode's; the warm path calls it zero timesindex_score_supportedscore_flydslthen rejected, and advertisedblock_table/seq_lensas optional while refusing both. Both are required nowidx_qstridessm_scalealloc_score(both)torch.empty, and the kernels store only each row's causal window -- 25% of the prefill buffer at q256/ctx256, 31% of decode's on a ragged batch, reaching the top-k selector as arbitrary memory. -inf nowRuntimeError: No HIP GPUs are available; one_validate_archnow, which removed the copy and the bug togetheridx_qrequires_gfx950make_prefill_case(heads)headswhile Q kept one headmax_query_len/max_seq_lenwere checked for being positive but not for fitting the i32 token arithmetic they feed, andmax_seq_lensizesalloc_score, so an absurd bound allocated before anything rejected it. Both are bounded by0x7FFFFFFF - (PAGE - 1)now, beforemax_blockis derivedrandom.Random, andget_cu_numcaches its first read, so all three arms ran at this part's count. Forced now, and the 304-CU case from the report is the first one it buildsWhat is in the diff
Five files,
+5044/-1: two new kernels, their one test file, the lazy exports,and 16 lines of
tensor_shim.py.diffstat
tensor_shim.pygains acache_modifierpass-through onbuf_copy_atomplus acheck on
unit_bytes; it is the only shared file touched, and every existingcaller keeps its behaviour.
cache_modifieris deliberately notrange-checked there: its width is architecture-dependent, and capping it at 2
bits broke five gfx1250 mxfp8 GEMM kernels, which pass
CPOL_DEV(0x10).The exports are lazy, so nothing in this repo dispatches to these kernels yet —
the consumer is ATOM, and that integration is a separate change.
Not in scope
the scorers read the row-major cache, and the shuffled layout was worth ~5% on
prefill, which did not justify a second addressing mode in
fused_qknorm_idxrqknorm.