Skip to content

[FlyDSL] NVFP4 sparse PA: prefill kernel (sparse_pa_nvfp4_prefill) - #7826

Merged
valarLip merged 48 commits into
mainfrom
ganyi/nvfp4-sparse-pa-prefill-pr
Nov 16, 2026
Merged

valarLip merged 48 commits into
mainfrom
ganyi/nvfp4-sparse-pa-prefill-pr

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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 is main, 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 GiB check (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 of out when out is 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 in sparse_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 = TQ consecutive 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 by pick_tile (rule measured on MI355X; tq / rounds can 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_scale and refuse_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_scale and _scales_up_to move to _common and are called from there; [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's DecodeWorkspace / sparse_pa_nvfp4_decode_alloc are 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), and block_table must 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. vLLM is nvfp4_prefill of our vLLM tree (unmodified). MXFP4 = ATOM's emit kernel + aiter pa_decode plan-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
batch q_len ctx Hkv rows NVFP4 us NVFP4 PFLOPS vLLM us MXFP4 emit+pa us headline
1 512 4096 1 512 25/26 0.275/0.270 38/39 27/27
1 512 4096 2 512 38/37 0.370/0.371 41/41 46/45
1 512 4096 4 512 60/61 0.459/0.458 61/60 81/80
1 512 32768 1 512 28/28 0.299/0.294 42/43 28/28
1 512 32768 2 512 42/43 0.395/0.392 46/46 48/48
1 512 32768 4 512 68/70 0.487/0.476 69/70 86/87
1 512 131072 1 512 28/28 0.301/0.298 42/43 28/28
1 512 131072 2 512 42/42 0.394/0.392 47/47 48/48
1 512 131072 4 512 69/70 0.486/0.476 68/70 86/88
1 2048 4096 1 2048 55/57 0.424/0.415 56/56 74/76
1 2048 4096 2 2048 101/100 0.465/0.466 101/101 135/134
1 2048 4096 4 2048 190/184 0.491/0.507 188/186 259/247
1 2048 32768 1 2048 68/67 0.492/0.497 68/68 85/86
1 2048 32768 2 2048 126/124 0.529/0.536 125/122 161/156
1 2048 32768 4 2048 236/232 0.565/0.574 235/232 310/304
1 2048 131072 1 2048 68/68 0.489/0.491 68/68 86/86
1 2048 131072 2 2048 126/124 0.530/0.535 126/126 163/159
1 2048 131072 4 2048 235/238 0.566/0.559 234/240 307/309
1 8192 32768 1 8192 235/230 0.566/0.578 235/230 305/299
1 8192 32768 2 8192 437/436 0.610/0.611 437/434 579/572 y
1 8192 32768 4 8192 805/808 0.662/0.659 813/814 1084/1099 y
1 8192 131072 1 8192 231/239 0.577/0.558 234/243 304/316
1 8192 131072 2 8192 439/444 0.606/0.600 443/440 583/582 y
1 8192 131072 4 8192 821/856 0.649/0.623 850/898 1120/1180 y
4 512 4096 1 2048 57/58 0.485/0.476 58/59 78/79
4 512 4096 2 2048 106/108 0.523/0.516 106/109 147/150
4 512 4096 4 2048 199/200 0.558/0.554 198/199 269/273
4 512 32768 1 2048 67/64 0.499/0.517 67/66 85/82
4 512 32768 2 2048 127/123 0.526/0.540 127/124 164/158
4 512 32768 4 2048 238/233 0.560/0.572 236/233 309/305
4 512 131072 1 2048 69/66 0.484/0.502 68/66 86/84
4 512 131072 2 2048 125/122 0.531/0.544 126/124 162/158
4 512 131072 4 2048 228/225 0.583/0.593 229/224 299/294
4 2048 4096 1 8192 170/173 0.550/0.540 171/174 232/235
4 2048 4096 2 8192 315/315 0.593/0.593 314/316 450/451 y
4 2048 4096 4 8192 602/601 0.620/0.621 603/603 881/879 y
4 2048 32768 1 8192 213/219 0.625/0.609 213/218 281/285
4 2048 32768 2 8192 414/414 0.643/0.643 413/417 560/568 y
4 2048 32768 4 8192 808/810 0.660/0.658 823/821 1106/1103 y
4 2048 131072 1 8192 226/221 0.589/0.604 229/224 297/291
4 2048 131072 2 8192 422/430 0.631/0.619 417/427 562/578 y
4 2048 131072 4 8192 826/848 0.645/0.629 833/869 1120/1164 y
4 8192 32768 1 32768 807/808 0.660/0.659 805/827 1088/1101 y
4 8192 32768 2 32768 1627/1616 0.655/0.659 1644/1662 2212/2202 y
4 8192 32768 4 32768 3235/3330 0.659/0.640 3226/3355 4339/4760 y
4 8192 131072 1 32768 824/834 0.646/0.639 838/861 1130/1147 y
4 8192 131072 2 32768 1663/1744 0.640/0.611 1690/1740 2263/2410 y
4 8192 131072 4 32768 3330/3358 0.640/0.635 3383/3395 4408/4473 y
16 512 4096 1 8192 190/195 0.585/0.570 191/196 261/268
16 512 4096 2 8192 360/359 0.617/0.618 365/361 506/503 y
16 512 4096 4 8192 694/703 0.640/0.632 700/711 989/1000 y
16 512 32768 1 8192 223/223 0.596/0.598 224/223 294/295
16 512 32768 2 8192 428/426 0.622/0.626 431/425 572/572 y
16 512 32768 4 8192 817/837 0.652/0.636 839/843 1116/1142 y
16 512 131072 1 8192 225/227 0.592/0.586 227/229 297/299
16 512 131072 2 8192 429/424 0.620/0.628 431/430 584/588 y
16 512 131072 4 8192 838/837 0.636/0.637 854/864 1150/1142 y
16 2048 4096 1 32768 609/603 0.613/0.619 609/609 892/887 y
16 2048 4096 2 32768 1187/1202 0.629/0.621 1181/1235 1758/1765 y
16 2048 4096 4 32768 2358/2372 0.633/0.629 2346/2406 3523/3520 y
16 2048 32768 1 32768 813/827 0.655/0.644 829/849 1102/1133 y
16 2048 32768 2 32768 1625/1617 0.656/0.659 1666/1658 2238/2212 y
16 2048 32768 4 32768 3278/3655 0.650/0.583 3350/3438 4377/4422 y
16 2048 131072 1 32768 839/834 0.635/0.639 844/847 1127/1165 y
16 2048 131072 2 32768 1674/1667 0.636/0.639 1696/1715 2286/2309 y
16 2048 131072 4 32768 3345/3330 0.637/0.640 3438/3453 4479/4457 y
16 8192 32768 1 131072 3236/3270 0.659/0.652 3236/3284 4362/4351 y
16 8192 32768 2 131072 6509/6696 0.655/0.636 6461/6673 8674/8812 y
16 8192 32768 4 131072 12828/13487 0.664/0.632 12833/12954 n/a (output > 2 GiB) y
16 8192 131072 1 131072 3403/3627 0.626/0.587 3496/3512 4559/4521 y
16 8192 131072 2 131072 7533/7373 0.566/0.578 6916/6916 8883/8902 y
16 8192 131072 4 131072 14141/14008 0.603/0.608 14101/14042 n/a (output > 2 GiB) y

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 (tq 4 / 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):

  • Round 5 (head c0757bb = bc0c2c8 + a merge of [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's 4e415b6bd9 + three test commits; the kernels did not change; valar-cop's review): (a) tq=2, rounds=2 is reachable from the public entry (compile_prefill accepts rounds in {1, 2} that divide tq; 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, with group8_h2 / group8_h4 (Hkv 2 and 4, group 8) and three refusal cases for a bad rounds (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 because torch.empty_like returned the previous call's correct output; prefill_call now 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_scales allocates 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 as k_scale / v_scale raise a raw AttributeError in host_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]
  • Round 4 (head bc0c2c8 = 0ddf0fd + a merge of [FlyDSL] NVFP4 sparse PA: decode kernel (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 new topk_n cases), 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_lens dtype, 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 or sparse_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]
  • op test at 0ddf0fd (the head; includes [FlyDSL] NVFP4 sparse PA: decode kernel (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]
  • Copilot round 2 (48d9dc4): on top of [FlyDSL] NVFP4 sparse PA: decode kernel (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]
  • Copilot round 3 (23d5a9d): a padding-only call with an empty KV cache [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_table covers 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]
  • valarLip review of 11-15 (a2a57d5, 7338bce, 7f04852): the prefill padding-row check now runs at every tile (a padding row shares a workgroup with its neighbour at tq 2 and 4; the auto tile for 2 rows is tq 1, which does not); the wrapper's duplicate block_table.dim() == 2 check is dropped (check_operands refuses 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]
  • Merge of [FlyDSL] NVFP4 sparse PA: decode kernel (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]
  • The existing MXFP4 pa_decode path: 6 sha256 hashes identical to origin/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 all TOPK * TQ lanes, 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_table must be 2-D with at least one row. The PR is based on main and 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 --perf gives 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_id values past the block_table rows (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_ids and dup_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.py gains 16 prefill cases (including group8_h2 / group8_h4: Hkv 2 and 4 with 8 heads per kv head) x 5 tiles (tq 4 / 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_table and poisoned_tail for decode and prefill, 29 refusal cases shared by both entry points plus 18 decode-only and 14 prefill-only (three of them for a bad rounds) (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, and capture_prefill_scales with explicit and default scales), and the prefill perf table. #7825's capture_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):

key base us new us new/base
512 / 1 / 16 / 4096 26.91 26.92 1.000
512 / 4 / 16 / 4096 70.98 70.75 0.997
2048 / 1 / 16 / 32768 85.80 85.25 0.994
2048 / 4 / 16 / 32768 312.30 311.02 0.996
8192 / 1 / 16 / 32768 312.48 314.31 1.006
8192 / 4 / 16 / 32768 1144.16 1141.18 0.997

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, tq 1) passes, the new one fails at tq 4 / 2 rounds, 4 / 1 and 2 / 1 and passes at 1 / 1.

🤖 Generated with Claude Code

ganyi1996ppo and others added 9 commits November 11, 2026 08:12
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]>
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]>
…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]>
@ganyi1996ppo
ganyi1996ppo changed the base branch from ganyi/nvfp4-sparse-pa-decode-pr to main November 13, 2026 07:18
@ganyi1996ppo
ganyi1996ppo requested a review from a team November 13, 2026 07:18
@aiter-bot

aiter-bot commented Nov 13, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision c0757bb11040 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

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 all `TOPK * TQ` lanes, 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_table` must be 2-D with at least one row. The PR is based on `main` and 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 --perf` gives 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 23d5a9d6c6 (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_id` values past the `block_table` rows (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_ids` and `dup_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.py` gains 16 prefill cases (including `group8_h2` / `group8_h4`: Hkv 2 and 4 with 8 heads per kv head) x 5 tiles (`tq` 4 / 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_table` and `poisoned_tail` for decode and prefill, 29 refusal cases shared by both entry points plus 18 decode-only and 14 prefill-only (three of them for a bad `rounds`) (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`, and `capture_prefill_scales` with explicit and default scales), and the prefill perf table. #7825's `capture_scratch` (first scratch allocation refused inside graph capture, then replays) runs here too. No other test covers this kernel.

<details><summary>Evidence</summary>

Prefill time, 6 shapes, median of 10 alternating runs per tree (base = 23d5a9d6c6, new = 7f048524b7):

| key | base us | new us | new/base |
|---|---|---|---|
| 512 / 1 / 16 / 4096 | 26.91 | 26.92 | 1.000 |
| 512 / 4 / 16 / 4096 | 70.98 | 70.75 | 0.997 |
| 2048 / 1 / 16 / 32768 | 85.80 | 85.25 | 0.994 |
| 2048 / 4 / 16 / 32768 | 312.30 | 311.02 | 0.996 |
| 8192 / 1 / 16 / 32768 | 312.48 | 314.31 | 1.006 |
| 8192 / 4 / 16 / 32768 | 1144.16 | 1141.18 | 0.997 |

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, `tq` 1) passes, the new one fails at `tq` 4 / 2 rounds, 4 / 1 and 2 / 1 and passes at 1 / 1.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (5)

  1. Make the page-union dedup cover every lane, and state the contract for repeated block ids. minimax_m3_sparse_pa_nvfp4_prefill.py:231 loops range_constexpr(TOPK * (TQ - 1)), so pairs inside the tile's last row are never compared (and with tq=1 nothing is deduped). A block id repeated within one row is counted once in rows 0..TQ-2 and twice in the last row; decode and run_torch count it twice. The output therefore depends on the row's position in the tile and on pick_tile. Use TOPK * TQ - 1, document (and test) "ids within a row must be distinct", and add a dup-id case to PREFILL_CASES. Fix the module docstring and the comment at :229 to match.
  2. Use the shared arch / CU helpers instead of a new local probe. _gfx_arch (prefill.py:449) reads gcnArchName, which .github/instructions/aiter-ops-flydsl.instructions.md:110 forbids. Use get_gfx_runtime() / get_cu_num() from aiter/jit/utils/chip_info.py.
  3. Stop copying the decode host helpers. _gfx_arch / _unit_scale / _cu_count (prefill.py:449-460) are byte-identical to decode.py:639-650. The k/v scale fallback (prefill.py:538-544 vs decode.py:787-793) and the c = sm_scale*LOG2E check are also identical. Move them to minimax_m3_sparse_pa_nvfp4_common.py.
  4. Rebase onto #7825's current head af14f1c9 and mirror its wrapper checks. This branch merged #7825 only up to a74bb9b0. Prefill still lacks block_table.dim() == 2 and 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.
  5. Tidy the tile knobs and comments.
    • Raise when rounds is given without tq (it is silently replaced at :534).
    • Drop compile_prefill(q_lds=...): _get_kernel never passes it.
    • Merge the back-to-back if const_expr(not Q_LDS) at :185/:187.
    • Fix the pick_tile docstring: the code tests < 2 * cus, not "one CU's worth".
    • Fix the _common.py header: decode still uses its own _page_loader / _dq4, not the shared ones.

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 fsx950223 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

ganyi1996ppo and others added 10 commits November 15, 2026 03:57
…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]>
ganyi1996ppo and others added 4 commits November 15, 2026 13:24
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]>
Copilot AI balanced review requested due to automatic review settings November 15, 2026 22:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 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

@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

@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).

  1. Description and self-review out of date: fixed in the PR body, rewritten against the code at 0ddf0fd. A repeated id counts once per slot; the base is main; the stats and counts are recomputed (against main +2801 / -0 over 5 files because the diff carries [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's commits; on top of [FlyDSL] NVFP4 sparse PA: decode kernel (sparse_pa_nvfp4_decode) #7825's head 214e5a0 +1101 / -153 over 5 files, the decode file being the refactor into _common); 14 prefill cases and 158 oracle checks (102 decode + 56 prefill), counted from a run; the stray heading line is gone; it says why NVFP4 (M3.1's native fp4 KV format). One thing I did not change: the performance tables are from an earlier head (0c1cfa7) and I did not re-measure them. A same-harness interleaved A/B on 14 of their shapes puts this head at 1.033x the time of that commit (geomean, range 1.011 to 1.073, A-to-A drift 1.005), the known cost of the review fixes, so the body says the tables read about 3% optimistic. Two of the 37 headline shapes (batch 16, q_len 8192, Hkv 4) have a q of exactly 2 GiB and are now refused by the q must be below 2 GiB check, which was added after the tables; the body says so. The check is needed: masked lanes store to a sentinel dword that is the last dword of out when out is exactly 2 GiB (on a scratch copy with <=, group 8 corrupted that dword in 5 of 5 runs).
  2. Padding-row check at every tile: fixed in a2a57d5. You are right: for 2 rows pick_tile returns tq 1, so a padding row never shared a workgroup with its neighbour. padding_rows now loops over PREFILL_TQ and checks that row 0 is zero, row 1 is bit-equal to the unpadded call at the same tile, and row 1 is within tolerance of run_torch. On a scratch copy of the kernel where a row counts as padding only if the first row of its tile does, the old check passed and the new one fails at three of the four tiles (it passes at tq 1, where nothing is shared). A second mutant that drops the kv_l > 0 term is caught by neither version, because that term is redundant.
  3. Duplicate block_table.dim() == 2 check: fixed in 7338bce. check_operands already refuses a non-2-D table, so the wrapper keeps only the non-empty check with its own message; the empty block_table refusal case expects that message now. The other refusal cases (23 shared by both entry points, 7 decode-only, 3 prefill-only) pass, including flattened block_table. The ISA of all 19 compiled kernels is byte-identical to 23d5a9d, and 70 prefill and 918 decode output hashes are identical.
  4. Two comments: fixed in 7f04852. The "causal limit" comment now sits on the loop that builds lim, and the test_prefill_perf docstring says neighbouring rows overlap only by chance instead of claiming there is no overlap. Comments and a docstring only; the ISA is unchanged.

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.

ganyi1996ppo and others added 6 commits November 15, 2026 18:52
…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]>
Copilot AI balanced review requested due to automatic review settings November 16, 2026 01:09
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Round 4, head bc0c2c8360 (fast-forward of 0ddf0fd818: a merge of #7825's round 4 3af40255eb, then three test-only commits; no kernel changed). The PR body is updated to this head.

Open Copilot thread (unaligned views, check_operands). Already answered in the thread: the alignment guard is in. Nothing new this round.

Merge of #7825 round 4. The 4 prefill kernels' ISA is byte-identical to 0ddf0fd818, the 20 decode variants are byte-identical to 3af40255eb (compiled without a GPU), and 70 prefill and 1080 decode output hashes are equal. LOG2E now comes from kernels_common because #7825 removed it from _common.

Tests added (from a local pass of the repo's review-pr skill):

  1. A q of exactly 2 GiB had no test (< vs <= passed alike). 1d789201c3 adds a refusal case on both entry points plus a prefill call at 2**19 - 1 rows that must run (first and last row match the oracle). On a scratch copy with the check relaxed to <=, the old tests pass and the new one fails.
  2. Prefill refusals with no case, and padding only at tile position 0. 623d50af04 adds one case per row-array guard (topk slot count, row_req_id / row_kv_lens dtype, rank, stride, length, device) and pads rows 0, 1 and 3 of a 4-row tile at every tile.
  3. No prefill graph-capture test. bc0c2c8360 adds capture_prefill: a cold capture is refused ("scale placeholder"), after an eager call or sparse_pa_nvfp4_decode_alloc it replays and matches the oracle at all four tiles. host_scales allocates the 4-byte placeholder on every call; left as it is (the message tells the caller to warm up).

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), AITER_FLYDSL_KERNARG_PRELOAD=0.

Open question, no code changed. A selected block whose table entry is negative ([[1, -1, 0]], kv_len 129): decode attends page 0, prefill drops the slot (9.3e-2 rel-L2 apart). It is outside the contract (decode's docstring requires valid page ids); should prefill's docstring say so too, or should the two agree on one behaviour?

@valarLip @valar-cop re-review at bc0c2c8360 (merge of #7825 round 4 + test-only commits).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 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 valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

a few small things..

prefill throughput with top-k ids from a real selector?

ci green.

Comment thread op_tests/test_flydsl_sparse_pa_nvfp4.py Outdated
("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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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).

ganyi1996ppo and others added 5 commits November 15, 2026 19:47
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]>
Copilot AI balanced review requested due to automatic review settings November 16, 2026 02:00
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Round 5, head c0757bb110 (fast-forward of bc0c2c8360: a merge of #7825's round 5 4e415b6bd9, then three test-only commits; the kernels did not change). The PR body is updated.

  • valar-cop, tq=2, rounds=2 / Hkv > 1 with group 8 (op_tests/test_flydsl_sparse_pa_nvfp4.py:341): fixed in f09a52a0c8 and 663d12c217, details in the thread. The combination is valid and matches the oracle on the GPU, so it is tested rather than refused.
  • valar-cop, default placeholder at replay (op_tests/test_flydsl_sparse_pa_nvfp4.py:948): fixed in c89d0aa268, details in the thread.
  • valar-cop, prefill throughput with top-k ids from a real selector: not measured. Nothing in the tooling here dumps the selector's block ids, and the perf cases use random scores, so I do not have a number to give.
  • Copilot (review at bc0c2c836): no open issues.

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 bc0c2c8360 (offline compile) and the new (2, 2) kernel compiles; output hashes were not re-compared. Not run at this head: prefill timing (no kernel change), CI's ruff 0.16.0. The PR Self-Review run on the push succeeded; the one started by my body edit was cancelled (it shows as a red evaluate), and I did not re-run it.

@valarLip @valar-cop re-review at c0757bb110 (merge of #7825 round 5 + test-only commits).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 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

@valarLip
valarLip merged commit 8f574bd into main Nov 16, 2026
@valarLip
valarLip deleted the ganyi/nvfp4-sparse-pa-prefill-pr branch November 16, 2026 05:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants