Repository navigation
[FlyDSL] NVFP4 sparse PA: prefill kernel (sparse_pa_nvfp4_prefill) - #7826
Conversation
MiniMax-M3.1 sparse paged attention over an NVFP4 KV cache, decode: topk block ids and the request block table in, exact e2m1 x e4m3 products on the f16 MFMA, bf16 out. Exports minimax_m3_sparse_pa_nvfp4_decode. gfx950 only. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
Token-tile Q-outer prefill over the NVFP4 KV page of the decode kernel: each page of the union of a tile's selected blocks is fetched and dequantized once and shared by every row that selected it. Exports minimax_m3_sparse_pa_nvfp4_prefill; the page loader and dequantization move into the shared helper file. Co-Authored-By: Claude <[email protected]>
…able Co-Authored-By: Claude <[email protected]>
…nd test The late_v closure now binds its page buffer and resource as default arguments and the test cases are dict literals; outputs and ISA are unchanged. Co-Authored-By: Claude <[email protected]>
Host-side only; the compiled kernel and its outputs are unchanged (496 output hashes identical). - Key the launcher cache by device and launch through the shared _run_compiled helper, so a second GPU in one process does not reuse the first GPU's compiled handle. - Refuse split counts above MAX_SPLITS (the scratch holds 16 splits per unit). - Refuse non-gfx950 devices and CPU tensors before allocating or compiling. - Validate the raw-pointer operands: all on q's device, dense kv_cache pages at least a full payload wide, one float32 element per global scale, sm_scale finite and positive, q and out below 2 GiB (32-bit byte offsets). - Document that one launch may be in flight per device (shared split scratch). - Test: the mismatch ratio of checkAllclose now fails a case, the gate uses get_gfx_runtime(), and refusals() pins each new refusal by its message. Co-Authored-By: Claude <[email protected]>
… as decode) Host-side only; the compiled kernel and its outputs are unchanged (the 58 prefill output hashes are identical). - Key the launcher cache by device and launch through the shared _run_compiled helper. - Refuse non-gfx950 devices and CPU tensors before allocating or compiling. - Validate the raw-pointer operands: all on q's device, dense kv_cache pages at least a full payload wide, one float32 element per global scale, sm_scale finite and positive, q and out below 2 GiB (32-bit byte offsets). - Test: refusals() now also covers the prefill entry point, by message. Co-Authored-By: Claude <[email protected]>
…skip split scratch when unsplit - Refuse a 2-D seq_lens / 1-D block_table and a block_table with fewer rows than requests (the kernel reads bt[req * stride + blk] from a raw pointer). - Refuse xcds other than 0 or 8: the XCD-aware grid assumes workgroup b runs on XCD b % 8, and any nonzero xcds also drops the cross-XCD partials scope. - Allocate the ~144 MiB split partials/tickets only for launches with splits > 1; an unsplit launch never touches them and gets placeholders. - Test: refusal cases for the above; a NaN err in the perf table now fails the run. Co-Authored-By: Claude <[email protected]>
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
valarLip
left a comment
There was a problem hiding this comment.
⚠️ Action required before merge (5)
- Make the page-union dedup cover every lane, and state the contract for repeated block ids.
minimax_m3_sparse_pa_nvfp4_prefill.py:231loopsrange_constexpr(TOPK * (TQ - 1)), so pairs inside the tile's last row are never compared (and withtq=1nothing is deduped). A block id repeated within one row is counted once in rows 0..TQ-2 and twice in the last row; decode andrun_torchcount it twice. The output therefore depends on the row's position in the tile and onpick_tile. UseTOPK * TQ - 1, document (and test) "ids within a row must be distinct", and add a dup-id case toPREFILL_CASES. Fix the module docstring and the comment at :229 to match. - Use the shared arch / CU helpers instead of a new local probe.
_gfx_arch(prefill.py:449) readsgcnArchName, which.github/instructions/aiter-ops-flydsl.instructions.md:110forbids. Useget_gfx_runtime()/get_cu_num()fromaiter/jit/utils/chip_info.py. - Stop copying the decode host helpers.
_gfx_arch/_unit_scale/_cu_count(prefill.py:449-460) are byte-identical todecode.py:639-650. The k/v scale fallback (prefill.py:538-544vsdecode.py:787-793) and thec = sm_scale*LOG2Echeck are also identical. Move them tominimax_m3_sparse_pa_nvfp4_common.py. - Rebase onto #7825's current head
af14f1c9and mirror its wrapper checks. This branch merged #7825 only up toa74bb9b0. Prefill still lacksblock_table.dim() == 2and a block_table row-count check (prefill.py:~528): a 1-D table passes and its stride 1 is used as the row stride, so pages are looked up wrongly with no error. - Tidy the tile knobs and comments.
- Raise when
roundsis given withouttq(it is silently replaced at :534). - Drop
compile_prefill(q_lds=...):_get_kernelnever passes it. - Merge the back-to-back
if const_expr(not Q_LDS)at :185/:187. - Fix the
pick_tiledocstring: the code tests< 2 * cus, not "one CU's worth". - Fix the
_common.pyheader: decode still uses its own_page_loader/_dq4, not the shared ones.
- Raise when
Not blocking: a separate prefill kernel is justified (Q-outer page-union dataflow vs decode's per-row slot loop), and the op_test has an fp64 oracle, a gfx950 gate and perf numbers. Merge after #7825; the aiter-bot PR self-review section is still unanswered.
Reviewed at f3d1915 (this PR's own commits only; base #7825 is unmerged).
fsx950223
left a comment
There was a problem hiding this comment.
Reviewed exact head f3d1915. All 40 standard prefill oracle cases and four padding checks passed on gfx950 with FlyDSL 0.5.0. Two correctness defects were reproduced: repeated selections produce tile-dependent attention, and a flattened block table is accepted but addressed incorrectly.
[P2] Make repeated-selection semantics independent of the tile size — aiter/ops/flydsl/kernels/minimax_m3_sparse_pa_nvfp4_prefill.py:231
The deduplication loop excludes comparisons within the last row and performs no comparisons when TQ=1. Repeating logical block selections therefore changes their attention weight depending on the tile size and other rows' selections. On gfx950, four rows selecting [0, 0, 3, -1, ...] produced relative L2 error 0.00165 against the existing fp64 oracle with tq=1, but 0.26768 with tq=2 or tq=4; the outputs differed by 0.26765. Define a consistent duplicate-ID contract and enforce it: if selections have set semantics, deduplicate all TOPK*TQ lanes; if multiplicity is supported, preserve each row's multiplicity when consuming shared pages. Add a duplicate-selection regression case.
[P2] Validate block-table rank before passing its row stride — aiter/ops/flydsl/kernels/minimax_m3_sparse_pa_nvfp4_prefill.py:528
Checking only dtype and stride(-1) allows a one-dimensional block_table through. The launcher then passes its stride(0), which is 1, as the request-row stride, so request IDs greater than zero read the wrong page mappings. Flattening the block table from make_case([500, 700], [1, 1], 1, 16, seed=5) was accepted and produced relative L2 error 1.15094 against the correctly shaped table. Require a two-dimensional block table before launch and add a refusal test for flattened tables.
Validation:
- PASS on
local:git -C checkout rev-parse HEAD
Matched f3d1915; remote exact-SHA fetch and HEAD verification also matched in remote-checkout.log. - PASS on
gfx950 / mi355-gpu-34 / fsx950223_pr_review_gfx950:SSH and srun wrapper recorded in validation-record.md, executing run-targeted.sh with flock -w 60 /workspace/gpu.lock timeout 600 and HIP_VISIBLE_DEVICES=2
Exit 0. Verified gfx950 and intended checkout/FlyDSL imports. All 40 prefill oracle cases passed; maximum relative L2 error 0.00166605. targeted.log records both defect reproductions. - PASS on
gfx950 / mi355-gpu-34 / fsx950223_pr_review_gfx950:Same SSH and srun wrapper executing run-padding.sh
Exit 0. Padding rows output zero without changing their neighbor for all four tile configurations; padding.log. - FAIL on
gfx950 / mi355-gpu-34 / fsx950223_pr_review_gfx950:Initial run-gfx950.sh using the container's installed FlyDSL
Exit 1 before kernel execution: required FlyDSL >=0.5.0, installed 0.4.0. Resolved with pinned 0.5.0 in a task-local environment; no global dependency upgrade. - SKIP on
gfx942:GPU correctness execution
The new prefill kernel supports gfx950 only.
Remaining validation:
- Performance sweeps and real model or selector inputs were not tested.
- No same-op base GPU comparison was possible because the prefill operation is newly introduced.
- Detailed commands, scripts, outputs, environment checks, and CI evidence are preserved in this task directory.
Automated Codex review of commit f3d19158434b.
…to sparse_pa_nvfp4_* Requested by fsx950223 (thread on the op test import): the function, the _decode and _common kernel modules, the lazy export in aiter/ops/flydsl/__init__.py and the op test file now carry the model-neutral name. No code change beyond the names. Co-Authored-By: Claude <[email protected]>
…eqs kernel argument - XCD count: get_num_xcds(default=0) inside q's device context replaces the private ctypes _xcd_count (whose except silently returned 0); anything other than 8 keeps the plain grid. CU count: the index scorer's _cu_count, which honours CU_NUM. Arch gate: get_gfx_runtime() instead of reading gcnArchName. - i32_reqs was declared, passed and never read; it held one of the 16 preloaded SGPR argument slots. Co-Authored-By: Claude <[email protected]>
…t checks, tidy comments The shape, dtype, stride, 2 GiB, splits, xcds, scale and sm_scale guards were asserts, which python -O strips in front of a raw-pointer launch. They now go through require(), which raises ValueError (as minimax_m3_index_score_prefill does); q / topk_idx rank, q and topk_idx dtype, and Hq / Hkv divisibility are refused too instead of crashing later. The refusal test accepts ValueError only and gains four cases. Nits: decode_splits_agree docstring says rel-L2 <= 2e-3 rather than "to the bit", the page-layout comment in pack_pages no longer contradicts itself, and the comment on `lim` in the kernel is rewritten. Co-Authored-By: Claude <[email protected]>
… tensors and fx.copy
aiter/ops/flydsl/AGENTS.md: new kernels use FlyDSL buffer tensors and fx.copy, not the
legacy buffer_ops. The page, Q, output and split-partial accesses now go through
ptr_buf_tensor / buf_copy_load / buf_copy_store (the helpers the index scorer uses); the
masked output store sends masked lanes to a dword offset past the buffer end
(OOB_DWORD), which is what buffer_ops' mask did. The ticket atomic uses
fx.llvm.atomic_add (agent scope, monotonic) instead of a hand-built LLVM AtomicRMWOp.
Measured on one MI355X (flydsl 0.5.0):
- 864 output sha256 (16 cases x 6 splits x xcds {auto,0,8} x late_v {auto,off,on}):
identical to the tree before this commit.
- ISA of the ragged_h4 variants (13 compiled kernels): VGPR / SGPR / LDS identical,
every buffer_load / buffer_store / atomic count identical; at most 1 instruction
fewer (an Int32 num_records product replaces an Int64 one). The atomic change alone
gives a byte-identical .s.
- op-test perf table, 14 shapes, median of 5 interleaved runs per tree: time of this
commit over af14f1c, geomean 0.985 in one session (min 0.942, max 1.009) and
1.000 in a second (min 0.991, max 1.012): no slowdown.
Co-Authored-By: Claude <[email protected]>
…l, evidence on the raw ones that stay
aiter/ops/flydsl/AGENTS.md: a raw rocdl / llvm / arith call stays only with a comment
naming the stable API that is missing or slower, backed by ISA or benchmark evidence.
Replaced by the typed API (each measured alone, then together, on one MI355X, flydsl
0.5.0):
- maxf_nn: fx.arith.maxnumf(..., fastmath=nnan) (byte-identical .s for the decode kernel)
- exp2: fx.math.exp2(..., fastmath=afn)
- pk_bf16: Vec(f32x2).to(BFloat16)
- mfma_f16: fx.make_mma_atom(fx.rocdl.MFMA(16, 16, 32, Float16)) + fx.gemm
All four give the same instruction multiset (VGPR / SGPR / LDS identical, 13 kernels) and
864 identical output sha256. Timing, op-test perf table, 14 shapes: each alone within
+-1% of the tree before this commit (5 runs); all four together 1.004 geomean over 10
alternating A/B runs (per-round 0.980 .. 1.016), i.e. not separable from run-to-run noise
on 8 - 20 us kernels, and 1.00 on the >= 100 us shapes.
Kept raw, with the reason at the call:
- permlane32/16_swap (+ llvm.extractvalue): the typed fx.gpu.shuffle_xor gives the same
bits but 22 more instructions (v_cmp_eq / v_cndmask / v_mov), 1249 -> 1271 unsplit.
- cvt_scalef32_pk_f16_fp4 / _fp8: the typed Vec.bitcast(Float4E2M1FN / Float8E4M3FN)
.to(Float16) does not compile ("LLVM Translation failed for operation:
builtin.unrealized_conversion_cast", then a segfault).
- readfirstlane / ballot / readlane / sched_barrier / s_waitcnt: no typed spelling in
FlyDSL 0.5.0 (fx.gpu has only the shuffle family, whose result is a VGPR).
Co-Authored-By: Claude <[email protected]>
Block ids within a row must be distinct (a selector emits every block once); the decode kernel attends once per slot, so a repeated id would be counted twice. ATOM's selector (index_topk.py: top-k over one sort key per block id) never emits a repeat. Co-Authored-By: Claude <[email protected]>
… buffer tensors, ValueError checks) into the prefill branch
…e, state the repeated-id contract The union loop ran over TOPK * (TQ - 1) lanes, so pairs inside the tile's last row were never compared and with tq = 1 nothing was deduplicated: a block id repeated in a row was attended once in rows 0 .. TQ - 2 and twice in the last row, so the output depended on the row's position in the tile and on pick_tile (fsx950223 reproduced rel-L2 0.00165 at tq 1 vs 0.268 at tq 2 / 4 on rows selecting [0, 0, 3, -1, ...]). The loop now covers TOPK * TQ - 1, so a repeated id is attended once for every tile size. Contract (module and function docstrings): ids within a row must be distinct, which ATOM's selector guarantees by construction (top-k over per-block sort keys, one key per block id); prefill attends a repeated id once, decode once per slot. Test: two PREFILL_CASES repeat ids (make_case dup=), checked for every tile against an fp64 oracle with set semantics (run_torch dedup=True). Co-Authored-By: Claude <[email protected]>
…or its wrapper checks, require a 2-D block_table - block_table: a 1-D table passed the stride(-1) check and its stride(0) = 1 became the request-row stride, so request ids > 0 read the wrong pages (fsx950223: a flattened make_case([500, 700], [1, 1], 1, 16, seed=5) table gave rel-L2 1.15). The wrapper now requires a 2-D block_table with at least one row; row_req_id values stay a device value, so they are documented rather than checked. Refusal test: flattened table, for decode and prefill. - Arch gate: get_gfx_runtime() instead of reading gcnArchName; CU count: the index scorer's _cu_count (honours CU_NUM), as decode does. - The unit scale, the k / v scale fallback and check, the c = sm_scale * log2(e) check and the shared operand checks (q / out / kv_cache / topk_idx / block_table dtype, stride, size and device) move to sparse_pa_nvfp4_common.py (unit_scale, host_scales, check_operands); decode and prefill call them instead of carrying byte-identical copies. Prefill's checks are ValueErrors (require), as in decode. - Test: refusals() runs the shared cases against both entry points. Co-Authored-By: Claude <[email protected]>
- rounds without tq is refused (it used to be silently replaced by pick_tile's choice); tq and rounds are validated with ValueError in compile_prefill. - compile_prefill(q_lds=...) is gone: _get_kernel never passed it. - The two back-to-back `if const_expr(not Q_LDS)` blocks are one. - pick_tile's docstring now says what the code tests (< 2 workgroups per CU). - The _common header says which helpers are shared by both kernels and which only prefill uses (decode keeps its own _page_loader / _dq4). Co-Authored-By: Claude <[email protected]>
PRELOAD_HINTS hard-coded amdgpu-kernarg-preload=True, so the global toggle that the other FlyDSL kernels read had no effect here. The count stays 16. Co-Authored-By: Claude <[email protected]>
Docs: topk_idx shape, bf16 -> f16 rounding range, open_page return, why _atomic_add is an llvm atomicrmw. Tests: refusal cases for splits > 1 with rows * Hkv above the limit, a strided topk_idx last dim, a non-contiguous q, rows != reqs * query_len. Co-Authored-By: Claude <[email protected]>
… into the prefill branch Conflicts resolved keeping both sides: - sparse_pa_nvfp4_common.py: one tensor_shim import (AITER_FLYDSL_KERNARG_PRELOAD, buf_copy_load, ptr_buf_tensor). #7825 made decode's _unit_scale refuse its first allocation inside graph capture; on this branch that function lives in _common as unit_scale, so the refusal and its helper (refuse_alloc_in_capture, from decode) moved there too, and decode imports it for _split_buffers. The message says "sparse_pa_nvfp4 call" (shared with prefill) instead of "sparse_pa_nvfp4_decode call". - sparse_pa_nvfp4_decode.py: _unit_scale stays removed (moved to _common on this branch). - op_tests: module docstring takes both edits; #7825's c3 / over setup and its four new refusal cases are added to the shared / decode-only lists; decode() in refusals() passes query_len from the case; the capture tests import unit_scale from _common as _unit_scale. Co-Authored-By: Claude <[email protected]>
The merge d7e110f left #7825's four new refusal cases twice in the shared list (git had already merged them there, I added them again), and two decode-only cases ("rows != reqs * query_len", "splits 2 with rows * Hkv > MAX_SPLIT_ROWS") in the list run on both entry points. Keep strided topk_idx last dim / non-contiguous q in the shared list and the other two in the decode-only list, once each. Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
🔵 Needs a closer look
The new gfx950 attention kernel requires head-matched GPU correctness, graph-replay, and performance validation, but no such report was supplied, GPU tests cannot run here, and measurements are only author-reported.
1 open issue
Review effort: Balanced
|
@valarLip, re-review of 11-15 18:01, point by point. Pushed head is now 0ddf0fd (fast-forward of 23d5a9d): three commits for this review (a2a57d5, 7338bce, 7f04852), a merge of #7825's round 3 (d7e110f, 214e5a0), and a follow-up that removes refusal cases the merge had duplicated (0ddf0fd).
On the merged tree the op test passes (decode 102 and prefill 56 checks, #7825's capture refusals included) and the 4 prefill kernels have the same ISA as before the merge. Not run: CI's ruff 0.16.0 and a per-process foreign-GPU check. |
…nches Two splits > 1 launches on different streams of one device shared one cached partials + tickets buffer and corrupted each other. Add sparse_pa_nvfp4_decode_alloc(device) and an optional workspace= argument (checked for device, dtype, size, contiguity, alignment); the cached per-device buffer stays the default. The explicit alloc is also the graph users' alloc point. The kernel is unchanged. Also: say what a capture needs (scratch before capture, variants eagerly), check the capture state on q's device, state the unchecked device-side contract (seq_lens, page ids, scales) in the docstring, import LOG2E from kernels_common. Co-Authored-By: Claude <[email protected]>
…8/64, more refusals Adds a two-stream case (a workspace per stream, poisoned partials, against the oracle; the shared default scratch is reported as the caller's error), a capture case with the explicit alloc, oracle cases for topk 1, 8 and 64, refusal cases (non-uint8 kv_cache, strided block_table / seq_lens, topk_idx rows < q rows, topk 65, splits > topk, the workspace checks), and drops a dead "+ 0 * j". Co-Authored-By: Claude <[email protected]>
… into the prefill branch Conflicts resolved keeping both sides: - aiter/ops/flydsl/__init__.py: both lazy exports (sparse_pa_nvfp4_decode_alloc and sparse_pa_nvfp4_prefill), in the dict and in __all__. - sparse_pa_nvfp4_common.py: #7825 deleted the LOG2E constant here and imports it from kernels_common; host_scales (which lives here on this branch) now uses that import. refuse_alloc_in_capture (moved here in the previous merge, shared with prefill) takes #7825's reworded message, with "sparse_pa_nvfp4 kernels" instead of "sparse_pa_nvfp4_decode". - sparse_pa_nvfp4_decode.py: DecodeWorkspace, sparse_pa_nvfp4_decode_alloc and the workspace validation come from #7825; its _refuse_alloc_in_capture / _unit_scale stay removed (they live in _common as refuse_alloc_in_capture / unit_scale), and its inline scale / sm_scale checks and LOG2E import stay replaced by host_scales; the placeholders (unit_scale) and the split scratch (workspace or the default) are chosen before the launch. - op_tests: #7825's topk_n cases, splits_of, two_streams and capture tests kept; its refusal cases that apply only to decode (topk 65, splits > topk, strided seq_lens, the workspace cases) are in the decode-only list, the others in the shared list; the two strided-last-dim cases expect this branch's split messages ("block_table must be int32 ..." / "seq_lens must be int32 ...") instead of the joint one; decode() in refusals() also passes workspace. Co-Authored-By: Claude <[email protected]>
The existing case (2**19 + 1 rows) is refused by `<` and `<=` alike, so nothing separated them. Add q of exactly 2**31 bytes (refused, both entry points) and an acceptance neighbour of 2**31 - 4096 bytes for prefill (rows 0 and the last, partial tile checked against the oracle), plus the out dtype / shape refusals. `<` is needed because the masked lanes store to a sentinel dword that is the last dword of `out` at exactly 2 GiB. Co-Authored-By: Claude <[email protected]>
…6-slot limit; padding at every tile position One refusal case per guard the prefill wrapper has (topk_idx slot count, dtype / rank / stride / length / device of row_req_id and row_kv_lens), and the padding-row check now pads rows at position 0, 1 and 3 of a tile (4 rows) beside real rows, at every tile. Co-Authored-By: Claude <[email protected]>
Modelled on capture_scratch: a first call that must allocate the scale placeholder is refused inside a capture; after an eager call or sparse_pa_nvfp4_decode_alloc the capture replays and matches the oracle at every tile. Co-Authored-By: Claude <[email protected]>
|
Round 4, head Open Copilot thread (unaligned views, Merge of #7825 round 4. The 4 prefill kernels' ISA is byte-identical to Tests added (from a local pass of the repo's review-pr skill):
Op test at this head on one MI355X, flydsl 0.5.0: PASSED 0, 182 oracle checks (126 decode + 56 prefill), max rel-L2 1.708e-3. Refusal cases: 29 shared + 18 decode-only + 11 prefill-only. Not run at this head: prefill timing (ISA identical, so not timed), Open question, no code changed. A selected block whose table entry is negative ( @valarLip @valar-cop re-review at |
There was a problem hiding this comment.
🔵 Needs a closer look
The gfx950 attention kernels combine raw-pointer access and complex GPU synchronization without independent head-matched validation, leaving correctness, capture safety, and performance tradeoffs for human review.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
valar-cop
left a comment
There was a problem hiding this comment.
a few small things..
prefill throughput with top-k ids from a real selector?
ci green.
| ("alias_two_blocks", [129], [1], 1, 16, {"alias": True}), | ||
| ("alias_chunk", [3000, 700, 130], [300, 700, 130], 1, 16, {"alias": True}), | ||
| ] | ||
| PREFILL_TQ = ((4, 2), (4, 1), (2, 1), (1, 1)) |
There was a problem hiding this comment.
tq=2, rounds=2 is reachable from the public entry but never run here, and no prefill case has hkv>1 with group=8. add both, or reject rounds=2 with tq=2 in compile_prefill?
There was a problem hiding this comment.
Fixed in f09a52a (+ 663d12c). tq=2, rounds=2 is valid (compile_prefill accepts rounds 1 or 2 when it divides tq; only (1, 2) is refused) and correct: on MI355X all prefill cases at (2, 2) match the fp64 oracle at rel-L2 1.55e-3 .. 1.67e-3, same as the other tiles, and the kernel compiles (1749 instructions, 36864 B LDS). So it is now in PREFILL_TQ and every prefill test runs it. New cases group8_h2 (Hkv 2) and group8_h4 (Hkv 4) cover group 8 with Hkv > 1, and the three untested rounds refusals (1 with 2, 3, 0) are in the prefill refusal list. Mutation checks: skipping the second combine round at (2, 2) fails 15 of 80 sweep rows, all at (2, 2); a hard-coded group of 16 in the Q^T load fails exactly the two new cases. That check first passed unnoticed because torch.empty_like returned the previous call's output; prefill_call now pre-fills NaN (663d12c). Kernel and host code unchanged (ISA of the four existing prefill kernels byte-identical to bc0c2c8).
| out = torch.empty_like(c["q"]) | ||
| g = torch.cuda.CUDAGraph() | ||
| with torch.cuda.graph(g): | ||
| sparse_pa_nvfp4_prefill( |
There was a problem hiding this comment.
both replays pass explicit k_scale/v_scale, so the default placeholder is never read at replay. add a k_scale=1.0, v_scale=1.0 case and capture/replay cold there?
There was a problem hiding this comment.
Fixed in c89d0aa. You are right: both replays passed explicit scales, so the placeholder was never read at replay. New capture_prefill_scales, with k_scale = v_scale = 1.0 and, per tile, four variants (both given, default k, default v, both default): a cold capture is refused in every variant, because host_scales allocates the placeholder on every call, also when both scales are passed (the test pins that); after an eager call each variant replays three times into a NaN-filled output and matches the oracle; in the both-default variant the placeholder is set to 2.0 between two replays: the output goes wrong (rel-L2 5.06), and is right again once restored, so the replay does read it. Mutants: a zero placeholder fails 45 checks, a lazily allocated placeholder fails the 5 cold-capture checks. Side finding, not changed: python floats as k_scale / v_scale give a raw AttributeError from host_scales (the signature says Tensor).
The two-stream test compared each output only by a whole-output rel-L2, which a single localized 25% element error passes. Use check() (rel-L2 plus the componentwise checkAllclose) like the rest of the file; the shared-scratch run stays a diagnostic count. Co-Authored-By: Claude <[email protected]>
…ds per kv head, refusals for bad rounds compile_prefill accepts rounds 2 with tq 2 (rounds must divide tq), so every prefill test now runs that tile too; two group-8 cases with Hkv > 1 are new, and the rounds refusals (1 with 2, 3, 0) are tested. Co-Authored-By: Claude <[email protected]>
The caching allocator returned the previous call's correct output for torch.empty_like, so a prefill tile that wrote nothing passed (a mutant that skips the second combine round at tq 2 went unnoticed). Co-Authored-By: Claude <[email protected]>
A cold capture is refused whatever the scales (the placeholder is allocated on every host_scales call); after an eager call the capture replays and matches the oracle with k and v given, with either or both defaulted, and the default-scale replay reads the placeholder (changed between two replays, the output changes). Co-Authored-By: Claude <[email protected]>
…826-r5 Co-Authored-By: Claude <[email protected]>
|
Round 5, head
Op test on one MI355X, flydsl 0.5.0: PASSED 0, 206 oracle checks (126 decode + 80 prefill, up from 56), refusals 29 shared + 18 decode-only + 14 prefill-only. The 4 existing prefill kernels' ISA is byte-identical to @valarLip @valar-cop re-review at |
There was a problem hiding this comment.
🔵 Needs a closer look
The GPU-specific attention kernel requires human review because source-only inspection cannot verify numerical correctness, graph replay, or latency, and no exact-head gfx950 validation report was supplied.
No open issues 🎉
Review effort: Balanced

Summary
Adds the MiniMax-M3.1 sparse paged-attention prefill kernel over an NVFP4 KV cache (FlyDSL, gfx950 / MI355X only):
sparse_pa_nvfp4_prefill. It builds on the decode PR #7825 (this PR's base ismain, and #7825 is not merged yet, so the diff also carries #7825's commits; merge #7825 first and it shrinks to the prefill part): same page, same selector inputs (topk_idx [Hkv, rows, 16]logical block ids plus the request block table), plus per row its request (row_req_id) and causal key count (row_kv_lens= position + 1), so ragged batches and chunked prefill (q_len < kv_len) need nothing else. NVFP4 is needed because it is M3.1's native fp4 KV format.Perf target not met. Measured median 0.64 PFLOPS over the 37-shape large-prefill head set (rows x Hkv >= 16384, group 16, local top-k model; our target was >= 2 PFLOPS). The f16 MFMA we use (16x16x32) peaked at about 2.27 PFLOPS in our MI355X calibration, and this kernel's dequantization and softmax work is comparable to its MFMA work; our estimate (not a measurement) of the overlap bound is roughly 1.3 to 1.6 PFLOPS, so we did not find a route to 2 PFLOPS with exact 16-bit MFMA on this dataflow. It is on par with vLLM's NVFP4 prefill kernel (which also runs exact f16) and faster than the MXFP4 path. The performance tables below are from an earlier head (0c1cfa7) and were not re-measured at this head. Same card, same harness, interleaved A/B/A/B on 14 of those shapes: this head takes 1.033x the time of 0c1cfa7 (geomean; range 1.011 to 1.073; the two A runs differ by 1.005), the known cost of the review fixes (the later commits leave the prefill ISA unchanged); so read the tables as about 3% optimistic for this head. Two of the 37 headline shapes (batch 16, q_len 8192, Hkv 4, ctx 32768 and 131072) have a q tensor of exactly 2 GiB and are now refused by the
q must be below 2 GiBcheck (added after the tables were measured); the check is needed, not an off-by-one: masked lanes store to a sentinel dword that is the last dword ofoutwhenoutis exactly 2 GiB.Page format and numerics
The KV page is the one of the decode PR (128-token page,
[K side | V side], e2m1 + e4m3 scale per 16, MFMA-lane-ordered scales; the layout is insparse_pa_nvfp4_common.py). It is the vLLM KV page, not the NVFP4 index page of #7813 / #7814. Numerics as decode: exact e2m1 x e4m3 products in f16, f16 Q and P, fp32 softmax / accumulation, bf16 output; no fp8 MFMA. Against an fp64 oracle rel-L2 is 1.6e-3 to 1.7e-3 (bf16 output floor), and against vLLM's prefill kernel (also exact) 0 to 2.5e-4 rel-L2 on the 6 cases compared.What changes (against
main: +3239 / -0 over 5 files, including #7825's 4 files; on top of #7825's head 4e415b6: +1349 / -203 over 5 files)aiter/ops/flydsl/kernels/sparse_pa_nvfp4_prefill.py(+591, new): token-tile Q-outer kernel. One workgroup =TQconsecutive rows x the (<= 16) query heads of one kv head; it walks the union of the pages those rows selected, fetches and dequantizes each page once and runs QK / softmax / PV for every row that selected it (others skip it with a wave-uniform branch). The 4 waves each own 32 keys of every page and are merged through LDS at the end: no atomics, no partial buffers. The tile (1, 2 or 4 rows, 1 or 2 combine rounds) is picked from the grid size bypick_tile(rule measured on MI355X;tq/roundscan be passed and the test runs all four combinations).aiter/ops/flydsl/kernels/sparse_pa_nvfp4_common.py(+221 / -3): the page loader and the K / V dequantization only this kernel uses, plus what both kernels now share:check_operands(host-side refusals),host_scales,unit_scaleandrefuse_alloc_in_capture(the first allocation of the scale placeholder is refused inside graph capture, as [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825 asks of decode),scales_up_to(zeroes the V scales of keys past a limit).aiter/ops/flydsl/kernels/sparse_pa_nvfp4_decode.py(+18 / -103): refactor only: its host checks,_unit_scaleand_scales_up_tomove to_commonand are called from there; [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825'sDecodeWorkspace/sparse_pa_nvfp4_decode_allocare kept. The ISA of its 20 compiled variants is byte-identical to [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's head 3af4025 (compiled without a GPU), and the 1080 decode output hashes of 3af4025 equal the merged tree's.aiter/ops/flydsl/__init__.py(+5): the lazy export.op_tests/test_flydsl_sparse_pa_nvfp4.py(+434 / -97): prefill cases, padding-row check, prefill perf table, the refusal cases shared by both entry points, the exact-2 GiB refusal and its acceptance neighbour, and the prefill graph-capture test ([FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's capture tests run on the merged tree).Left out of this PR on purpose: an opt-in lazy softmax rescale (4 to 10% faster in our runs, default off, but not bit-exact and about 75 extra lines; it can follow separately) and an fp8-MFMA experiment arm (not exact; not wanted for sparse PA).
Repeated block ids: ids within a row should be distinct (read in ATOM's
index_topk.py: a top-k over one key per block, so a row does not repeat an id; not run on a real selector's output), andblock_tablemust be 2-D. Every slot of a row is one attended block, as in decode: the page union shares the loads across rows and tile sizes, a row weights a page by the number of its slots that selected it, and its own block keeps its causal limit even if another slot reaches the same page. A repeated id therefore counts once per slot (decode does the same). The prefill kernel also zeroes the V scales of keys past the rows' positions in the tail page and never reads the block table for a slot that is not valid.Performance (prefill, vs vLLM and MXFP4)
One MI355X, same process, graph replay, medians of 7 interleaved replays, two independent runs (r1/r2). Batch 1 / 4 / 16 requests, each a chunk of q_len rows ending at ctx keys, group 16. Top-k per row = 15 blocks + the tail block under a synthetic "local" model (block 0, 3 local blocks, 11 of a 32-block pool shared by the 128 rows of a tile, tail; neighbouring rows overlap; this is not a real selector output). K/V pool 8 GB. PFLOPS = 4 x 128 x Hq x (keys attended) / time.
vLLMisnvfp4_prefillof our vLLM tree (unmodified).MXFP4= ATOM's emit kernel + aiterpa_decodeplan-free on MXFP4 pages (a different KV quantization, so speed only; unavailable where its output exceeds 2 GiB).Headline set (rows x Hkv >= 16384, 37 shapes): NVFP4 median 0.636 PFLOPS (min 0.572, max 0.661), vLLM median 0.627. Over all 72 shapes, NVFP4 / vLLM time: geomean 0.975, best 0.655, worst 1.078 (batch 16, q_len 8192, ctx 131072, Hkv 2); 19 of 72 shapes are slower than vLLM, 16 of them by 2% or less (about the noise of this harness), the others by 2.05% (batch 16, q 8192, ctx 32768, Hkv 4), 2.2% (batch 16, q 2048, ctx 32768, Hkv 4) and 7.8% (the Hkv 2 shape above). NVFP4 / MXFP4 time over 70 shapes: geomean 0.760, worst 0.996 (two 512-row Hkv 1 shapes are within 1% of it).
All 72 shapes, two runs
Tests
python3 op_tests/test_flydsl_sparse_pa_nvfp4.py [--perf](exits non-zero on any failed check). Same aiter op-test shape as the decode PR. New here: 14 prefill cases (chunked, Hkv 1/2/4, group 8, one-row, block edges, full prompt, fewer than top-k ids, junk ids, repeated ids, ragged batch, a table that maps two logical blocks to one page) x 4 tiles (tq4 / 2 combine rounds, 4 / 1, 2 / 1, 1 / 1) against the fp64 oracle, padding rows (kv length 0) output zeros without disturbing neighbours (checked at every tile, so a padding row also shares a workgroup with its neighbour), and a prefill perf table (us / TFLOPS / TB/s / err) on random top-k, the worst case for page reuse (0.32 to 0.52 PFLOPS there).Checked on this tree (flydsl 0.5.0, gfx950):
sparse_pa_nvfp4_decode) #7825's4e415b6bd9+ three test commits; the kernels did not change; valar-cop's review): (a)tq=2, rounds=2is reachable from the public entry (compile_prefillaccepts rounds in {1, 2} that dividetq; only (1, 2) is refused) and was never run: on the GPU all prefill cases at (2, 2) match the fp64 oracle (rel-L2 1.55e-3 to 1.67e-3), so it is now in the tile list for every prefill test, withgroup8_h2/group8_h4(Hkv 2 and 4, group 8) and three refusal cases for a badrounds(f09a52a0c8). Mutations: skipping the second combine round at (2, 2) fails 15 of the 80 sweep rows, all at (2, 2); a hard-coded group of 16 in the Q^T load fails exactly the two new group-8 cases. My first attempt at that mutation passed unnoticed becausetorch.empty_likereturned the previous call's correct output;prefill_callnow pre-fills the output with NaN (663d12c217). (b) The capture test passed explicit scales at replay, so the default placeholder was never read:capture_prefill_scales(c89d0aa268) runs k_scale = v_scale = 1.0 and four variants per tile (both given, default k, default v, both default): a cold capture is refused in every variant (host_scalesallocates the placeholder on every call), after an eager call each variant replays 3 times into a NaN-filled output and matches the oracle, and poking the placeholder to 2.0 between two replays of the both-default variant makes the output wrong (rel-L2 5.06), so the replay does read it. A zero placeholder fails 45 checks, a lazily allocated one fails the 5 cold-capture checks. Python floats ask_scale/v_scaleraise a rawAttributeErrorinhost_scales(the signature says Tensor); not changed. Op test PASSED 0, 206 oracle checks (126 decode + 80 prefill); the 4 existing prefill kernels' ISA is byte-identical to bc0c2c8 and the new (2, 2) kernel compiles (offline); output hashes not re-compared; CI at this head not checked; prefill timing not run (no kernel change). Not measured: prefill throughput with top-k ids from a real selector (nothing here dumps the selector's block ids). [measured]sparse_pa_nvfp4_decode) #7825's round 4, 3af4025, + three test commits; the kernels did not change): op test PASSED 0; 182 oracle checks (126 decode + 56 prefill; the 24 extra decode checks are [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's five newtopk_ncases), 0 fail, 0 skip, max rel-L2 1.708e-3. New checks: a q of exactly 2 GiB is refused on both entry points and a prefill call at 219 - 1 rows (q and out 231 - 4096 bytes) matches the oracle on its first and last row; the prefill refusal guards that had no case (8 cases: topk slot count,row_req_id/row_kv_lensdtype, rank, stride, length and device); padding rows at tile positions 0, 1 and 3 at all four tiles; prefill under graph capture (cold capture refused, then 24 replay checks and 8 refusal checks after an eager warm-up orsparse_pa_nvfp4_decode_alloc). The 4 prefill kernels' ISA is byte-identical to 0ddf0fd and the 70 prefill output hashes are equal. Not run at this head: prefill timing (ISA identical, not timed),AITER_FLYDSL_KERNARG_PRELOAD=0. [measured]sparse_pa_nvfp4_decode) #7825's round 3, 214e5a0): PASSED 0, 158 oracle checks (102 decode + 56 prefill), all within rel-L2 2.5e-3 (max 1.71e-3), no refusal or capture failure. [measured]sparse_pa_nvfp4_decode) #7825's round-2 head; op test 102 decode + 56 prefill checks PASSED; the five round-2 cases fail on the previous head (illegal memory access with an empty block table, NaN with a 0x7f V scale in the unwritten tail, wrong output with strides reaching 2**31, rel-L2 3.18 for two table entries on one page) and pass now; unaligned operands are refused (contract guard: on gfx950 they gave identical output before). Prefill time over the previous head: geomean 1.027 over 6 shapes (10 alternating runs, 1.003 to 1.038; the V-scale zeroing is about half of it), decode 1.005. [measured][0, 18432]ended in an illegal memory access at every tile; the prologue load now goes through a zero-size buffer when no slot is valid (padding_empty_tablecovers an empty cache for decode and prefill; decode already returned zeros). ISA and output hashes unchanged, prefill time 1.001 of the previous head. [measured]tq2 and 4; the auto tile for 2 rows istq1, which does not); the wrapper's duplicateblock_table.dim() == 2check is dropped (check_operandsrefuses it); two comments fixed. Host code and test only: the ISA of the 19 compiled kernels (15 decode, 4 prefill) is byte-identical to 23d5a9d, 70 prefill + 918 decode output hashes are identical, prefill time 0.998 of the previous head (6 shapes, 10 alternating runs). [measured]sparse_pa_nvfp4_decode) #7825's round 3 (d7e110f): same ISA for all 4 prefill kernels (the prefill kernel sets no compile hints, so the kernarg-preload change does not reach it) and for the 20 decode variants compared with 214e5a0 (compiled without a GPU, default preload on); 70 prefill and 918 decode output hashes identical to the commit before the merge; [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's graph-capture refusals and replays pass. [measured]pa_decodepath: 6 sha256 hashes identical toorigin/main.Not in this PR
The decode kernel (#7825), the NVFP4 KV write kernel, ATOM / vLLM integration. Not verified: a real selector's top-k distribution, real model data, non-gfx950 targets, flydsl versions other than 0.5.0.
PR Self-Review
Reviewed revision
c0757bb
Behavior and intent
Adds
sparse_pa_nvfp4_prefill, a token-tile sparse paged-attention prefill over the NVFP4 KV page of #7825 (NVFP4 is M3.1's native fp4 KV format). Before this there was no NVFP4 sparse prefill in aiter. Block ids within a row should be distinct; a repeated id counts once per slot, as in decode: the page union is keyed by page and own-block flag over allTOPK * TQlanes, and a row weights a page by the number of its slots that selected it, so the result does not depend on the tile size.block_tablemust be 2-D with at least one row. The PR is based onmainand carries #7825's commits until #7825 merges.Validation and unverified scope
MI355X, flydsl 0.5.0, one card:
python3 op_tests/test_flydsl_sparse_pa_nvfp4.py --perfgives PASSED 0, 206 oracle checks (126 decode, 80 prefill), max rel-L2 1.71e-3. CUDA-graph replay, 25 replays: decode (query_len 4, group 8, splits 4, xcds 8) 1.659e-3, prefill (tq 2, group 8) 1.664e-3. Against the previous head 23d5a9d (before the review round) the ISA of all 19 compiled kernels is byte-identical and prefill time is 0.998 (table below); the merge of #7825's round 3 changes no kernel's ISA either. Unverified: a real selector's top-k, non-gfx950, flydsl other than 0.5.0,row_req_idvalues past theblock_tablerows (a device value, not checked), an int32 / float32 operand whose pointer is not 4-byte aligned (torch cannot build one).PR-specific question
Is it acceptable that a block id repeated within a row (out of contract) counts once per slot, as in decode, instead of once per row? A selector never emits one, so only a caller that builds ids by hand can see it; the choice makes prefill equal decode on every input and keeps the result independent of the tile. On the head this PR was first cut from, two rows repeating ids gave different output per tile; the cases
dup_idsanddup_ids_h2(both within tolerance of the per-slot oracle at all 4 tiles) cover it now.Changed op tests
op_tests/test_flydsl_sparse_pa_nvfp4.pygains 16 prefill cases (includinggroup8_h2/group8_h4: Hkv 2 and 4 with 8 heads per kv head) x 5 tiles (tq4 / 2 combine rounds, 4 / 1, 2 / 2, 2 / 1, 1 / 1) against an fp64 oracle (run_torch, which counts a repeated id once per slot), padding rows checked at every tile,padding_empty_tableandpoisoned_tailfor decode and prefill, 29 refusal cases shared by both entry points plus 18 decode-only and 14 prefill-only (three of them for a badrounds) (a q of exactly 2 GiB among them, with a call just below it that must run), padding at tile positions 0, 1 and 3, prefill graph capture (capture_prefill, andcapture_prefill_scaleswith explicit and default scales), and the prefill perf table. #7825'scapture_scratch(first scratch allocation refused inside graph capture, then replays) runs here too. No other test covers this kernel.Evidence
Prefill time, 6 shapes, median of 10 alternating runs per tree (base = 23d5a9d, new = 7f04852):
new/base time: geomean 0.9983, min 0.994, max 1.006 over 6 shapes; runs per arm: 10
Padding-row check on a scratch copy of the kernel in which a row is treated as padding only when the first row of its tile is (a bug that exists only when a padding row shares a workgroup with a neighbour): the old check (auto tile,
tq1) passes, the new one fails attq4 / 2 rounds, 4 / 1 and 2 / 1 and passes at 1 / 1.🤖 Generated with Claude Code