You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Adds the MiniMax-M3.1 sparse paged-attention decode kernel over an NVFP4 KV cache (FlyDSL, gfx950 / MI355X only): sparse_pa_nvfp4_decode. It takes what the index selector emits, topk_idx [Hkv, rows, 16] logical 128-token block ids (-1 padded, any order) plus the request block table, so no sparse block table is built between the selector and the kernel. The prefill kernel is a follow-up PR stacked on this one.
Why NVFP4 and not the MXFP4 pa_decode tile. NVFP4 does not use the MXFP4 pa_decode tile because that tile feeds K's e2m1 codes to the scaled MFMA with one e8m0 (power-of-two) scale per 32 dims, widens V to bf16, handles only query_length 1 and reads separate data and scale views of shape [pages, kv_heads, 128, 64] / [.., 128, 4], while MiniMax-M3.1's native KV page is NVFP4: one buffer with an e4m3 scale per 16 dims (not a power of two, so it cannot be expressed as an e8m0 scale without changing the values) plus a global fp32 scale, so this kernel forms the exact e2m1 x e4m3 products in f16 and runs a plain f16 MFMA.
Perf target not met. Measured cold (8 GB pool) median 5.28 TB/s over the 13-shape decode head set (our target was 6 TB/s; only 512 rows x Hkv 4 reaches 6.05). The 256-row Hkv 1 shapes (one workgroup per CU) are at 4.4-4.6 TB/s. Against the MXFP4 path and the vLLM NVFP4 kernel it is faster (tables below), but it is below the bandwidth we wanted.
Page format
One page = 128 tokens, 2 * Hkv * 9216 B: [K side | V side], a side = Hkv x 8192 B e2m1 codes (low nibble = even element) then Hkv x 1024 B e4m3 scales, one scale per 16 elements. Same conventions as the NVFP4 index pages of #7813 / #7814 (128-token pages, e2m1 low nibble first, e4m3 scale per 16, no per-tensor scale in the page; the global fp32 k / v scales are separate [1] tensors). It is not the index page: this is the vLLM KV page, whose K scales and V data / scales are stored in MFMA-lane order so each lane loads its operands with a few wide loads. The exact byte offsets are in the docstring of sparse_pa_nvfp4_common.py, and the test builds pages from token-major codes with its own writer, so a layout mistake cannot cancel against the kernel. There is no NVFP4 KV write kernel in this PR.
Numerics
K and V = e2m1 x e4m3 scale, which f16 holds exactly (at most 6 significant bits), so nothing is rounded before the MFMA: 16-bit MFMA (v_mfma_f32_16x16x32_f16), Q and P in f16, scores / softmax / accumulation fp32, bf16 output. f16 rather than bf16 because it measured faster. No fp8 MFMA. Q bf16 -> f16 is exact except |q| > 65504 or < 6e-8.
Against an fp64 oracle on the same pages: rel-L2 1.6e-3 to 1.7e-3 (the bf16 output rounding floor), 96 checks. vLLM's NVFP4 decode kernel rounds K to e4m3, so its error against the same oracle is 3.6e-2 to 4.4e-2 in our runs (mine-vs-vllm 3.6e-2 to 4.4e-2 rel-L2, 9 cases) and the two are not expected to agree bit for bit.
What changes (+2093 / -0, 4 files, 20 commits including the review rounds)
aiter/ops/flydsl/kernels/sparse_pa_nvfp4_decode.py (+984): the kernel and sparse_pa_nvfp4_decode(q, kv_cache, topk_idx, block_table, seq_lens, sm_scale, out, k_scale, v_scale, query_len). One workgroup = one query row x the (<= 16) query heads of one kv head x a share of the row's top-k slots; lane = top-k slot (one ballot gives the valid set); splits are a static partition of the slots merged in split order by the last workgroup to arrive (deterministic, no host sync, graph-capturable; scratch allocated on first use, so warm up before capture; one launch in flight per device, the scratch is shared). The split count, the XCD-aware grid (only when splits > 1) and trailing V loads (late_v, when 1.5 to 4 workgroups share a CU) are chosen per launch by rules measured on MI355X; each can be overridden and the test checks they agree bitwise. K data loads are non-temporal, V stays cacheable.
aiter/ops/flydsl/kernels/sparse_pa_nvfp4_common.py (+191): page layout, MFMA mapping, conversion and softmax helpers.
aiter/ops/flydsl/__init__.py (+10): the lazy exports of sparse_pa_nvfp4_decode and sparse_pa_nvfp4_decode_alloc.
op_tests/test_flydsl_sparse_pa_nvfp4.py (+908): see Tests.
No csrc, no tuned CSV (aiter-config-shape does not apply).
Left out of this PR on purpose: page-ring depths above 1 (measured slower, -5 to -15% at >= 2 workgroups per CU) and a cacheable-K option (streaming K is faster); both existed in the development branch.
Performance (decode)
One MI355X, same process, graph replay of 8 launches (about 2 us graph-node floor included), medians of 15 interleaved replays, two independent runs shown as r1/r2 where the cell has two numbers. ctx 32768 for every row; top-k = 15 random earlier blocks + the row's tail block (synthetic, not a real selector output); 4 input variants cycled; K/V pool 8 GB with random page ids (little cache reuse; the first-iteration numbers of the op test are warmer). TB/s = valid selected page-heads x 18432 B / time (MXFP4: x 17408 B). MXFP4 is the existing path: ATOM's Triton emit kernel (top-k -> page-folded block table) plus aiter pa_decode on the MXFP4 pages with e4m3 Q, planned; it is a different KV quantization, so this is a speed comparison, not a numerics one. vLLM is nvfp4_sparse_decode of our vLLM tree (models/minimax_m3/amd/ops, unmodified); it only supports 16 heads per KV head.
Head set (the 4 TP head layouts at 256 / 512 rows, plus MTP q_len 4 / 8):
rows
q_len
Hkv
group
NVFP4 us
NVFP4 TB/s
MXFP4 emit+pa us
MXFP4 TB/s
vLLM NVFP4 us
NVFP4/MXFP4 time
NVFP4/vLLM time
256
1
4
16
56.7/56.5
5.32/5.35
63.4/63.5
4.50/4.49
92.8/92.9
0.892
0.610
256
1
2
16
29.9/29.8
5.05/5.06
35.0/35.0
4.07/4.08
49.0/49.1
0.854
0.609
256
1
1
16
16.4/16.3
4.59/4.64
23.7/23.9
3.00/2.99
25.1/24.7
0.687
0.658
256
1
1
8
17.0/17.1
4.44/4.40
22.6/23.1
3.15/3.09
unsupported (g8)
0.748
nan
512
1
4
16
99.9/99.8
6.05/6.05
112.8/112.1
5.06/5.09
183.0/181.8
0.888
0.547
512
1
2
16
54.6/55.0
5.53/5.49
60.5/60.3
4.71/4.73
91.7/92.8
0.907
0.594
512
1
1
16
28.7/28.5
5.27/5.29
35.2/35.2
4.05/4.06
47.0/47.9
0.813
0.603
512
1
1
8
29.3/29.8
5.15/5.08
35.2/34.6
4.05/4.12
unsupported (g8)
0.846
nan
256
4
4
16
52.4/52.5
5.76/5.76
58.6/58.5
4.87/4.87
94.6/91.9
0.896
0.563
256
8
4
16
51.9/51.9
5.82/5.81
55.7/56.0
5.12/5.10
91.8/93.0
0.930
0.562
256
4
1
8
16.8/16.9
4.49/4.47
22.4/22.1
3.19/3.22
unsupported (g8)
0.759
nan
256
8
1
8
16.7/17.0
4.53/4.44
21.8/21.8
3.26/3.28
unsupported (g8)
0.772
nan
512
4
4
16
104.0/103.4
5.81/5.84
108.7/107.7
5.25/5.30
178.5/180.0
0.958
0.579
median NVFP4 TB/s 5.281 (min 4.42, max 6.05); NVFP4/MXFP4 time: geomean 0.839, worst 0.958; NVFP4/vLLM time: geomean 0.591, worst 0.658, over 9 shapes
Small shapes (1 to 128 rows, MTP), one run
rows
q_len
Hkv
group
NVFP4 us
NVFP4 TB/s
MXFP4 emit+pa us
MXFP4 TB/s
vLLM NVFP4 us
NVFP4/MXFP4 time
NVFP4/vLLM time
1
1
4
16
8.5
0.14
10.1
0.11
10.2
0.837
0.831
1
1
1
16
8.3
0.04
9.8
0.03
9.3
0.849
0.898
1
1
1
8
8.1
0.04
9.8
0.03
unsupported (g8)
0.829
nan
4
1
4
16
9.5
0.50
11.1
0.40
11.6
0.861
0.820
4
1
1
16
8.6
0.14
10.2
0.11
9.7
0.839
0.878
4
1
1
8
8.6
0.14
10.1
0.11
unsupported (g8)
0.845
nan
16
1
4
16
11.2
1.68
14.7
1.21
13.0
0.764
0.863
16
1
1
16
9.6
0.49
11.1
0.40
11.1
0.865
0.867
16
1
1
8
9.4
0.50
10.5
0.42
unsupported (g8)
0.893
nan
64
1
4
16
16.7
4.53
23.7
3.01
25.1
0.705
0.665
64
1
1
16
11.4
1.66
14.8
1.21
13.7
0.768
0.832
64
1
1
8
11.3
1.68
14.5
1.23
unsupported (g8)
0.775
nan
128
1
4
16
29.6
5.10
35.2
4.05
48.3
0.841
0.613
128
1
1
16
13.3
2.84
17.7
2.02
17.3
0.753
0.767
128
1
1
8
13.5
2.80
16.9
2.10
unsupported (g8)
0.795
nan
8
8
4
16
10.0
0.94
12.0
0.74
51.5
0.834
0.194
32
4
4
16
13.5
2.80
17.7
2.02
17.3
0.763
0.780
32
8
4
16
13.4
2.82
17.9
1.99
29.5
0.747
0.453
64
4
4
16
16.5
4.57
23.5
3.04
25.4
0.704
0.650
median NVFP4 TB/s 1.663 (min 0.04, max 5.10); NVFP4/MXFP4 time: geomean 0.802, worst 0.893; NVFP4/vLLM time: geomean 0.681, worst 0.898, over 14 shapes
Shapes where NVFP4 is slower than the MXFP4 path: none in either table (worst 0.958 of its time). Shapes slower than vLLM: none.
Tests
python3 op_tests/test_flydsl_sparse_pa_nvfp4.py [--perf] (about 30 s with --perf; exits non-zero on any failed check). Aiter op-test shape: no pytest, @benchmark + run_perftest + checkAllclose, markdown tables (us / TFLOPS / TB/s / err vs the oracle on the first rows), get_gfx_runtime() gating in main(). fp64 torch oracle built from the token-major codes. Matrix: 16 cases (ragged, Hkv 1/2/4, group 8/16, one-token rows, block edges, fewer than top-k ids, tail only, junk ids, orderings, MTP 4/8, batches 40 / 130) x 6 split counts against the oracle; every split count vs one workgroup (fp32 merge order differs, so rel-L2 <= 2e-3, not bitwise); XCD-aware vs plain grid and late_v on/off bitwise; padding rows output zeros and do not disturb neighbours.
Checked on this tree (flydsl 0.5.0, gfx950):
op test: PASSED, 96 oracle checks, max rel-L2 1.7e-3; perf table err 1.3e-3 to 1.4e-3.
Outputs are byte-identical to the development branch this was cut from (496 sha256 hashes: all cases x splits x xcds x late_v, plus 16 auto-selected perf shapes); compiled ISA is identical for the three variants compared.
The existing MXFP4 pa_decode path: 6 sha256 hashes identical to origin/main (this PR touches no existing code beyond the lazy-export table).
Copilot round 2 (d83ef9e): a padding-only call with an empty block table (padding_empty_table: it ended in an illegal memory access before); a NaN V scale (0x7f) in the unwritten tail of the last page (poisoned_tail: NaN in all 12 poisoned launches before; the fix zeroes those scales in the tail branch only, +26 instructions there, decode time geomean 0.998 over 14 shapes); refusals for topk_idx / block_table views whose 32-bit element offsets reach 2**31 (outputs were wrong by 1.55 to 1.81 before) and for operands that are not 4-byte aligned. Op test 96 oracle checks PASSED; CUDA-graph replay rel-L2 1.659e-3. [measured]
Review round 3 (7e52695, d6ee6c4, 214e5a0): the first scratch allocation of _unit_scale and _split_buffers is refused inside a CUDA graph capture (a capture would record the fill instead of running it; with stale memory under the tickets an eager call after a capture-only gave rel-L2 1.054e-2 against the oracle, correct is 1.668e-3; the new capture_scratch case fails 6 checks on the old code); PRELOAD_HINTS honours AITER_FLYDSL_KERNARG_PRELOAD (preload length 14 unset, 0 with =0; with the variable unset the ISA of all 20 decode variants is byte-identical to d83ef9e); doc fixes; four new refusal cases (the code already refused them). Op test at 214e5a0: 117 oracle checks (one is the poisoned-ticket check, which must fail) and 28 refusal cases, plus the capture cases. Decode time new/base geomean 0.991 over 4 alternating runs, which is noise (the ISA is identical). ATOM's capture loop runs an eager warm-up forward with the same shapes before each recording, so the first call is never inside a capture there (read, not run).
Review round 4 (94fb41b: sparse_pa_nvfp4_decode_alloc(device) and an optional workspace= argument, validated for device, dtype, size, contiguity and alignment, with the per-device cached buffer kept as the default; the warm-up wording now says what a first call needs (the scale placeholder is allocated by every call, the split scratch only by splits > 1, so call sparse_pa_nvfp4_decode_alloc before capture or make one eager call that needs it); _unit_scale / _split_buffers now run inside torch.cuda.device(q.device); the device-side contract (seq_lens[r] <= block_table.shape[1] * 128, page ids in [0, kv_cache.shape[0])) is documented, not checked, because a check needs a device sync; LOG2E imported from kernels_common.py. 3af4025: the tests). On one MI355X (gfx950): the full op test passes 120 correctness rows and 42 refusal cases, up from 96 and 28 (new: topk 1, 8 and 64 at every split count up to topk, a two-streams case, a capture that uses the explicit alloc, seven workspace checks and more refusals); two graphs of 64 split launches on two streams with no sync in between gave 263 of 384 wrong outputs in one run and 114 of 384 in another on the shared default scratch (a race, so it varies) and 0 of 384 with one workspace per stream; the 25-replay graph check gives rel-L2 1.659e-3. The final ISA of 56 decode variants (topk 8, 16, 64) is byte-identical to 214e5a0 (compiled without a GPU). A first call of a not-yet-loaded variant (splits, topk, xcds, late_v) inside a capture worked on gfx950 with FlyDSL 0.5.0 (correct replay), so it is not refused; the docstring says so and asks callers to call each variant once eagerly, because some other FlyDSL ops refuse it. The performance table was timed on an intermediate head and not re-timed on this one (new/base geomean 0.992).
Review round 5 (4e415b6, Copilot): the concurrent per-stream-workspace test (two_streams) now checks each of its 384 outputs with the file's check() (componentwise checkAllclose plus the fp64 rel-L2 check) instead of a whole-output norm only; the shared-scratch run (a caller error) keeps the whole-norm predicate and stays diagnostic-only. Test file only, kernels untouched. On the GPU the op test passes (PASSED 0); a 0.0813 error injected into one output of the per-stream run makes the new check fail (bad = 3). On this data the old predicate would also have failed there: the reference peaks at 2.69, so the componentwise tolerance is about 0.054 and any single-element error that fails it already pushes the whole norm over its tolerance; I could not find an error the old predicate passes and the new one fails, so this aligns the predicate with the rest of the file rather than catching more here. [measured]
black clean; ruff check clean on the added files (a first push had two B023 and two C408 findings, fixed in the third commit with outputs, hashes and ISA re-checked unchanged).
Not in this PR
Two decode launches that split a row (splits > 1) and use the same workspace must not overlap: by default the workspace is one per device, so on several streams of one device each stream needs its own workspace=sparse_pa_nvfp4_decode_alloc(device); sharing one is the caller's error and corrupts the results silently (documented in the wrapper, not enforced). ATOM does not pass a workspace yet (not run with it). The prefill kernel (next PR), the NVFP4 KV write kernel, ATOM / vLLM integration. Not verified: behaviour on a real selector's top-k distribution or on real model data; non-gfx950 targets; flydsl versions other than 0.5.0.
PR Self-Review
Reviewed revision
4e415b6 (head after review round 5: a test-only commit on top of 3af4025; the full sha is the PR head)
Behavior and intent
Adds sparse_pa_nvfp4_decode, sparse paged-attention decode over an NVFP4 KV cache that reads the selector's topk_idx and the block table directly. Before this there was no NVFP4 sparse decode in aiter. K and V are exact in f16, so nothing is rounded before the 16-bit MFMA. The wrapper raises ValueError for operands it cannot read (arch, device, shape, dtype, stride, 2 GiB, splits, xcds, scales, sm_scale), which python -O does not strip. Block ids within a row must be distinct; a repeat counts twice.
Validation and unverified scope
MI355X, flydsl 0.5.0, one card: python3 op_tests/test_flydsl_sparse_pa_nvfp4.py --perf gives PASSED 0, 96 oracle checks, max rel-L2 1.70e-3. CUDA-graph replay (query_len 4, group 8, splits 4, xcds 8, 25 replays): rel-L2 1.659e-3. 864 output hashes are identical to af14f1c. Decode time over af14f1c: geomean 1.0035 over 14 shapes (10 alternating runs); 1.00 at 50 us and above. Unverified: a real selector's top-k, non-gfx950, flydsl other than 0.5.0, several streams or devices.
PR-specific question
Every check fails before this PR (the op does not exist). The refusal cases raise AssertionError on af14f1c, so they fail the ValueError-only test.
Changed op tests
op_tests/test_flydsl_sparse_pa_nvfp4.py is the only test of this kernel: 16 cases x 6 split counts against an fp64 oracle built from the token-major codes, split / XCD-grid / late_v agreement, padding rows, 18 refusal cases. The MXFP4 pa_decode tests use another page format and kernel.
Evidence
Decode time, --perf table, median of 10 alternating runs per tree (before = af14f1c):
rows
q_len
Hkv
group
ctx
before us
after us
after/before
1
1
1
16
32768
8.10
8.15
1.006
1
1
4
16
32768
8.50
8.68
1.021
8
1
1
16
32768
9.18
9.32
1.015
8
1
4
16
32768
10.28
10.42
1.014
64
1
1
16
32768
11.68
11.65
0.997
64
1
4
16
32768
19.55
19.63
1.004
256
1
1
16
32768
19.75
19.78
1.001
256
1
4
16
32768
52.70
52.58
0.998
512
1
1
16
32768
30.17
30.45
1.009
512
1
4
16
32768
103.55
103.43
0.999
32
4
1
16
32768
10.06
10.16
1.010
32
4
4
16
32768
16.00
15.34
0.958
64
8
1
16
32768
11.49
11.57
1.006
64
8
4
16
32768
19.05
19.26
1.011
after/before time: geomean 1.0035, min 0.958, max 1.021 over 14 shapes; runs per arm: 10
Raw ops: maxf_nn, exp2, pk_bf16 and mfma_f16 use the typed FlyDSL API (same instruction multiset, same hashes). permlane swap (typed shuffle_xor: 22 more instructions), the e2m1 / e4m3 converts (typed conversion does not compile) and the wave primitives stay raw, each with its reason at the call.
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]>
ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm
vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all
All standard extended tests (excludes ci:atom_full)
Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 7825 --add-label <label>
One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.
PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.
Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.
…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]>
Adds MiniMax-M3 NVFP4 sparse paged-attention decode for gfx950, consuming selector block IDs directly without constructing an intermediate sparse block table. Prefill and KV-cache writing remain out of scope.
Changes:
Implements split-workgroup decode with deterministic merging and launch heuristics.
Adds shared NVFP4 page-layout and numerical helpers, plus a lazy public export.
Adds fp64-reference correctness checks and synthetic performance sweeps. Reported bandwidth is below the 6 TB/s target.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Critical shared-scratch races and device-blind compiled-handle caching can corrupt results or leave outputs unwritten, while validation gaps and ineffective test checks remain unresolved.
The wrapper accepts sm_scale=0 or a zero k_scale, but multiplying masked scores (-inf) by that scale produces NaNs in the probabilities and empty-wave maxima. Even a one-token row therefore fails to return that token's V. Preserve masked maxima as -inf and masked probabilities as zero independently of scaling, so zero scale gives uniform attention over valid keys without reading device scales on the host.
The wrapper accepts Q/output tensors beyond the kernel's 32-bit buffer byte-offset range: for Q shaped [262145, 64, 128], row 262144 starts at byte 2^32 and its offset wraps to zero. The output store at line 432 has the same issue, so later rows can overwrite earlier results. Reject unsupported extents before launch—a conservative limit below 2 GiB also keeps masked-store sentinel offsets out of range—or rebase both resources with 64-bit row addresses.
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]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Insufficient block-table validation permits out-of-bounds reads, while unsupported XCD overrides can break the cross-XCD coherence required for split merges.
A separately allocated block_table shaped [1, 6] passes these guards for two requests, but request 1 then reads bt[6 + blk] beyond the allocation. Require a 2-D table with at least one row per request and a 1-D seq_lens before passing their raw pointers. Add a refusal case for a shortened table.
An explicit xcds=1 bypasses the supported eight-XCD topology: with one row and splits=2, blocks 0 and 1 land on different XCDs under the documented dispatch mapping. Because any nonzero xcds sets PART_SCOPE=0, those splits lose the cross-XCD coherence policy needed for their merge. Restrict overrides to 0 or 8 before compilation and add a refusal case.
Avoid allocating split workspace for unsplit launches
This allocates and permanently caches the full split workspace even when splits == 1, although the single-workgroup specialization never accesses it. The partial buffer alone is 1025 * 16 * 64 * 36 * 4 = 151,142,400 bytes (about 144 MiB), including for the default unsplit 512-row/Hkv=4 launch. Allocate it only for split launches and pass unused pointer/size placeholders for the single-workgroup specialization to avoid this unnecessary per-device memory reservation.
A NaN error is not counted as a failure: NaN > REL_L2_TOL is false. The perf path only computes rel_l2() and does not use the finite-output check in check(), so a perf-only shape that produces NaNs can still leave the script printing PASSED and exiting zero. Count any error that does not satisfy err <= REL_L2_TOL as a failure, or reuse check() for these outputs.
The reason will be displayed to describe this comment to others. Learn more.
Not renamed in this push. Which name should it have? The comment names none.
Evidence for the current one: it follows the in-tree convention for this model's FlyDSL ops on main (minimax_m3_index_score*.py kernels and test_flydsl_minimax_m3_index_score*.py tests). The name carries the three things that differ from existing kernels: the model's sparse-selector interface (topk_idx + block table), the NVFP4 page layout, and decode vs prefill.
Cost of renaming: minimax_m3_sparse_pa_nvfp4_decode is the lazy export in aiter/ops/flydsl/__init__.py, the common module's name, and the name in the stacked prefill PR #7826, and the index scorer in #7813 shares the prefix. I would rename them together after you pick the target name. Tell me the name and I will do it in the next round.
The reason will be displayed to describe this comment to others. Learn more.
Renamed earlier in the stack (sparse_pa_nvfp4_*, ae17f83): the kernel and file names no longer carry the model name; the op test is op_tests/test_flydsl_sparse_pa_nvfp4.py. Nothing changed on this in the latest round.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed exact head a74bb9b, the complete merge-base diff, kernel helpers, callers, tests, and existing feedback. No concrete blocking defect was found within the documented API constraints. Validation remains incomplete: the configured gfx950 host had no idle GPU on either availability check, and its container has FlyDSL 0.4.0 rather than the pinned 0.5.0. The correctness suite and split/grid/load-variant checks need an idle MI355X with the pinned dependency before approval.
Validation:
PASS on local: git -C checkout rev-parse HEAD
Exit 0; HEAD is a74bb9b in an isolated checkout.
PASS on local: git diff --check against merge-base 342aa1dc1971480955ac6ebd504c237e668d75b4; Python ast.parse on all four changed Python files
Both checks exited 0. These checks do not validate GPU compilation or execution.
PASS on dzm-mi355-gpu34-dev / allocation 9581 / fsx950223_pr_review_gfx950: Container probes using torch.cuda.get_device_properties, flydsl.__version__, and rocm-smi --showuse --showmemuse
Verified gfx950 on all eight devices and FlyDSL 0.4.0. Initial utilization was 97–100%; recheck was 62–98%, with 89–90% VRAM allocated. Logs are preserved in environment.log and environment-recheck.log.
SKIP on gfx950: timeout 300 python3 op_tests/test_flydsl_minimax_m3_sparse_pa_nvfp4.py
Not launched because no idle GPU was available. The container also lacks the pinned FlyDSL 0.5.0. Exact-SHA GPU correctness and launch-variant validation remain pending.
SKIP on gfx942: NVFP4 sparse PA decode correctness suite
The new kernel explicitly supports gfx950 only; gfx942 execution would not validate its supported target.
Remaining validation:
Successful GitHub CI statuses were inspected, but usable logs establishing execution of this specific NVFP4 suite were unavailable; CI was not counted as GPU correctness evidence.
Concurrent launches on multiple streams are explicitly unsupported by the shared per-device workspace contract.
Detailed evidence and pending validation are preserved in validation-notes.txt and the task directory logs.
…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]>
block_table / seq_lens shape (decode.py ~770): refused unless seq_lens is 1-D, block_table is 2-D and has at least one row per request. Refusal tests: shortened table, 2-D seq_lens.
xcds override (~783): refused unless 0 or 8 (the grid assumes workgroup b runs on XCD b % 8, and any nonzero value also drops the cross-XCD partials scope). Refusal test: xcds=1.
Split scratch for unsplit launches (~786): the ~144 MiB partials/tickets are now allocated only when splits > 1; an unsplit launch passes placeholders (the kernel touches them only under SPLITS > 1). Measured: first unsplit launch allocates 0.0005 MiB (head a74bb9b: 144.1 MiB); a split launch still allocates 144.1 MiB.
NaN in the perf path (test ~537): the perf failure count is now ~(err <= tol), so a NaN err fails the run.
32-bit byte offsets: assert q.numel() * q.element_size() < 2**31 (out is asserted to have q's shape), refusal test "q over 2 GiB".
sm_scale == 0: refused (c > 0 assert, refusal tests for 0 and NaN).
k_scale == 0: not handled, by contract. The docstring says k_scale / v_scale are positive, a device value not checked on the host (reading it would sync). Measured: k_scale = 0 returns NaN for every output element (4096 of 4096 in a 2-row case). A zero global scale is not a value the quantizer produces; if you want a kernel-side guard I can add one, at a cost I have not measured.
GPU validation of af14f1c (MI355X gfx950, flydsl 0.5.0, one idle card, op_tests/test_flydsl_minimax_m3_sparse_pa_nvfp4.py --perf): PASSED 0, 96/96 oracle checks ok (max rel-L2 1.7e-3), all refusal cases refused with their own message, perf table err 1.4e-3 or below. Split / XCD-grid / late_v agreement checks passed. Against a74bb9b on the same card, outputs are bit-identical over 288 launches (every case x split count x xcds in {default, 0, 8}). Not re-measured: the graph-replay TB/s tables in the description (the kernel is unchanged; only host-side asserts and the allocation changed).
The reason will be displayed to describe this comment to others. Learn more.
⚠️ Action required before merge (5)
Apply fsx950223's rename (still open). He named the target, sparse_pa_nvfp4_decode (thread on op_tests/test_flydsl_minimax_m3_sparse_pa_nvfp4.py:32), after af14f1c was pushed. Rename the function, the _decode/_common modules, the lazy export in aiter/ops/flydsl/__init__.py and the test file together, then rebase #7826 on the result.
Port the kernel's memory ops off legacy buffer_ops.aiter/ops/flydsl/AGENTS.md:32 says new kernels use FlyDSL buffer tensors and fx.copy. This PR uses buffer_ops.create_buffer_resource_from_addr / buffer_load / buffer_store throughout minimax_m3_sparse_pa_nvfp4_decode.py (112-141, 272-280, 429-443, 490); the sibling minimax_m3_index_score.py:778 already uses fx.copy. AGENTS.md:34 also asks for a comment naming the missing stable API on each raw rocdl/llvm/arith call that stays (_common.py:84-168, decode _atomic_add). If an op has to stay raw for performance, cite the ISA or timing evidence in that comment.
Reuse chip_info instead of a private HIP query._xcd_count (decode.py:665-680) re-implements chip_info._query_num_xccs / get_num_xcds (chip_info.py:687, 745) with its own ctypes call, and its except silently returns 0, so the XCD grid is turned off without any log. _cu_count (decode.py:643) ignores CU_NUM, but the sibling minimax_m3_index_score.py:339 honours it. Call get_num_xcds(default=0) inside the device context, and use the sibling's _cu_count.
Drop the dead i32_reqs kernel argument. It is declared at decode.py:196/585, passed at 603/829 and never read in the kernel body, so it uses one of the 16 preloaded SGPR argument slots for nothing.
Raise ValueError for public input checks, not assert. The arch and device checks already raise (decode.py:739-744), but the shape, dtype, stride, 2 GiB, splits, xcds, scale and sm_scale guards (753-804) are asserts, and python -O strips them in front of a raw-pointer launch. minimax_m3_index_score_prefill.py:1569+ raises ValueError. Update the refusal tests (test:398) to match.
Nits: decode_splits_agree docstring says "to the bit" but the check is rel-L2 <= 2e-3 (test:297); the layout comment at test:93 contradicts itself; the comment at decode.py:271 is garbled; the self-review "Reviewed revision" still says a74bb9b (aiter-bot FAIL, shadow mode).
CI is green, and the new op test ran on MI35X (shard 3/8, PASSED 0, 57 s). The design is justified: NVFP4 is the native KV format, its e4m3/16 scales cannot use the scaled MFMA of the MXFP4 pa_decode tile, and it reads topk_idx directly. It is 0.84x the time of the MXFP4 emit+pa path (geomean).
Re-reviewed at af14f1c. Already fixed: device-keyed cache, splits <= 16, gfx950 gate, operand/device/stride checks, block_table/seq_lens shape, xcds in {0,8}, no split scratch when unsplit, NaN counted in perf, get_gfx_runtime() test gate, mismatch ratio gates the test.
The reason will be displayed to describe this comment to others. Learn more.
⚠️ Action required before merge (3)
Refuse the first scratch allocation inside graph capture instead of only documenting "warm up before capture"._split_buffers (sparse_pa_nvfp4_decode.py:673-682) and _unit_scale (:668-670) are functools.cached and allocate on the first call. If that first call happens during capture (for example, a warm-up that only ran unsplit shapes, then capture of a small batch that picks splits > 1), the torch.zeros / torch.ones fill is recorded into that graph and never executed. Eager calls and other graphs that run before that graph replays then read uninitialised tickets and scales. Add require(not torch.cuda.is_current_stream_capturing(), ...) on the allocating path, or expose an explicit alloc like minimax_m3_index_score_alloc. A caller-provided workspace would also close Copilot's open thread on overlapping streams (r4539177793), which is still unresolved.
Honour the global kernarg-preload toggle.PRELOAD_HINTS (sparse_pa_nvfp4_common.py:54-59) hard-codes "amdgpu-kernarg-preload": True, so AITER_FLYDSL_KERNARG_PRELOAD=0 (tensor_shim.py:28, read by 22 other FlyDSL kernels) has no effect here. Use AITER_FLYDSL_KERNARG_PRELOAD and keep the count at 16.
Fix the remaining doc and AGENTS.md nits.
decode.py:6 says topk_idx [Hkv, rows, 16]. The code takes [Hkv, >= rows, topk] with topk in [1, 64].
common.py:144 says bf16x8_to_f16 is "exact unless |x| > 65504". f16 subnormals also round, and tiny values flush to zero (the description states < 6e-8 correctly).
_page_loader's docstring (decode.py:92) says open_page returns "the buffer resource". It returns three buffer tensors.
_atomic_add (decode.py:81-88) is a raw fx.llvm.atomic_add with no comment naming the missing typed API (AGENTS.md "Raw ops").
The refusal list has no cases for splits > 1 with rows * Hkv > 1024, a strided topk_idx last dim, a non-contiguous q, or rows != reqs * query_len.
CI at d83ef9e is green, and test_flydsl_sparse_pa_nvfp4.py ran on MI35X (shard 1/8, passed, 61 s). The NVFP4 premise holds: M3.1's native KV format is NVFP4, and the e4m3/16 scales cannot use the MXFP4 pa_decode tile. Please also state that reason in the description.
Re-reviewed at d83ef9e (full diff). Already fixed: rename to sparse_pa_nvfp4_* (ae17f83), FlyDSL buffer tensors / fx.copy instead of buffer_ops, with a reason on each remaining raw op (44317ca, 48d4dff), get_num_xcds(default=0) + _cu_count instead of a private ctypes query, dead i32_reqs removed (b1babd3), ValueError via require() everywhere + refusal tests (a5460a2), all nits from af14f1c. Copilot round 2 fixed too: empty block table for padding (51e655d), NaN V scale in the unwritten tail (07fb5d0), i32 offset bound (0834fb8), 4-byte alignment (d83ef9e).
…inside graph capture
The split scratch and the scale placeholder are cached per device and allocated
(and zero-filled) on the first call. Inside a capture the fill is recorded, not
run, so eager calls and other graphs read uninitialised tickets and scales.
The first call on a device during capture is now refused.
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]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because an omitted critical finding identifies a missing block-table bounds check that permits out-of-bounds raw loads despite passing wrapper validation.
The reason will be displayed to describe this comment to others. Learn more.
⚠️ Action required before merge (4)
Close Copilot's multi-stream thread (r4539177793) with a caller-owned workspace, not only a docstring. Two splits > 1 launches on different streams of one device still share _split_buffers (sparse_pa_nvfp4_decode.py:687-698, ~150 MiB, process-lifetime), and they silently corrupt each other's tickets and partials. Export a sparse_pa_nvfp4_decode_alloc(device) (same pattern as minimax_m3_index_score_alloc, __init__.py:159) and take an optional workspace= argument. Keep the cached buffer only as the default. That also gives graph users an explicit alloc point.
Update the PR description. It still says topk_idx [Hkv, rows, 16], "+1549, 4 files, 4 commits" and "Reviewed revision d83ef9e". It also has a stray "## PR Self-Review` section with the block below." line. Add the NVFP4 reason that r25 asked for: M3.1's native KV format is NVFP4, and the external benchmark rules reject non-native fp4 caches.
Say what the warm-up actually needs.:677, :690 and :758 say "one eager call (same shapes)". The scratch does not depend on shape. Every call allocates the scale placeholder, and only splits > 1 allocates the split scratch. So the warm-up needs one eager call with splits > 1 on that device, as your own capture_scratch "warm for splits 1" case shows. Also move _unit_scale(dev) / _split_buffers(dev) (:864-866) inside the with torch.cuda.device(q.device) block at :881, so is_current_stream_capturing() checks q's device and not whichever device is current.
Small nits (credit: Copilot's head review for the first one):
State the unchecked device-side contract in the docstring: seq_lens[r] <= block_table.shape[1] * 128, and page ids < kv_cache.shape[0]. The kernel reads bt[req, blk] for any blk <= pos // 128.
Import LOG2E from kernels_common.py:18 instead of redefining it at sparse_pa_nvfp4_common.py:50.
Drop the dead + 0 * j at test_flydsl_sparse_pa_nvfp4.py:70.
Add refusal cases for a non-uint8 kv_cache, a strided block_table / seq_lens last dim, and topk_idx.shape[1] < rows.
CI: lint, OPUS and Triton checks pass at 214e5a0. The "Aiter Test" run (43752555672) has been stuck in build_aiter_wheels (3.12) since 11-15 19:30. So test_flydsl_sparse_pa_nvfp4.py, including the new capture_scratch, has not run on MI35X at head. Please re-trigger it.
Re-reviewed at 214e5a0 (full diff). Already fixed: a first allocation inside graph capture is now refused (_refuse_alloc_in_capture, 7e52695), with a capture/replay/poisoned-ticket test. AITER_FLYDSL_KERNARG_PRELOAD is honoured (d6ee6c4). Doc nits fixed: topk shape, bf16->f16 range, open_page return, _atomic_add reason. Refusal cases added for splits>1 over 1024 units, strided topk, non-contiguous q and rows != reqs*query_len (214e5a0).
@valarLip, re-review of 11-15 17:56, point by point. Pushed head is now 214e5a0 (three commits on d83ef9e, fast-forward). The description is updated to match, including why NVFP4 cannot use the MXFP4 pa_decode tile.
Scratch allocation inside graph capture: fixed in 7e52695. The first call on a device inside a capture now raises ValueError for both _unit_scale and _split_buffers; it is checked only on a cache miss, so the kernel and the hot path are unchanged. I took your first option (no explicit alloc function). Evidence: on d83ef9e a first splits=4 call inside torch.cuda.graph was not refused, and with stale memory under the tickets an eager call afterwards gave rel-L2 1.054e-2 against the fp64 oracle (correct is 1.668e-3). The new case capture_scratch refuses three cold captures (splits 4 cold; splits 4 after a warm-up that only ran unsplit shapes, your scenario; splits 1 cold), then checks warm-up, capture, replays and an eager call against the oracle; it fails 6 checks on the old code. ATOM's capture loop runs an eager warm-up forward with the same shapes before each recording, so the first call is never inside a capture there; that is from reading the code, I did not run ATOM with this aiter. The overlapping-streams thread from Copilot is not closed by this: see my reply in that thread.
AITER_FLYDSL_KERNARG_PRELOAD ignored: fixed in d6ee6c4. PRELOAD_HINTS takes the value from tensor_shim, and the count stays 16. Compiled without a GPU, the final ISA has .amdhsa_user_sgpr_kernarg_preload_length 14 with the variable unset and 0 with AITER_FLYDSL_KERNARG_PRELOAD=0. With the variable unset, the ISA of all 20 decode variants is byte-identical to d83ef9e. [FlyDSL] NVFP4 sparse PA: prefill kernel (sparse_pa_nvfp4_prefill) #7826's prefill kernel sets no compile hints, so it is untouched.
Docs and AGENTS.md nits: fixed in 214e5a0. topk_idx is [Hkv, rows, topk] with topk 1 to 64; bf16x8_to_f16 is exact for 2^-14 <= |x| < 2^16, rounds to multiples of 2^-24 below that (|x| <= 2^-25 gives 0) and gives inf above, checked over every finite bf16 value; open_page returns three buffer tensors; _atomic_add now has a comment (FlyDSL's llvm.atomicrmw helper; UniversalAtomicAdd and BufferAtomicAdd are copy atoms that return no old value, which the merge ticket needs). The four missing refusal cases are added (splits=2 with rows x Hkv = 1026, a strided topk_idx last dim, a non-contiguous q, rows != reqs * query_len); the code already refused all four, so there is no code change.
The op test at 214e5a0 has 117 oracle checks (one is the poisoned-ticket check, which must fail) and 28 refusal cases, plus the capture cases; decode time new/base is 0.991 over 4 alternating runs, which is noise since the ISA is identical. Not run: ATOM end to end, CI's ruff 0.16.0, and a per-process foreign-GPU check on the card.
… 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]>
…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]>
@valarLip, re-review of 11-15 20:59, point by point. Pushed head is now 3af4025 (fast-forward of 214e5a0): 94fb41b (library) and 3af4025 (tests). The description is updated to match. About CI: we do not re-run workflows ourselves; this push starts a new Aiter Test run, which should replace the run that was stuck in build_aiter_wheels at 214e5a0.
Caller-owned workspace for the multi-stream thread: done in 94fb41b. sparse_pa_nvfp4_decode_alloc(device) is exported (same pattern as minimax_m3_index_score_alloc) and sparse_pa_nvfp4_decode takes an optional workspace=; the cached per-device buffer stays the default. A workspace is checked for device, dtype, size, contiguity and alignment; not sharing one between concurrent launches is the caller's job and the docstring says so. The kernel is unchanged: the final ISA of 56 decode variants (topk 8/16/64, all splits, xcds, late_v) is byte-identical to 214e5a0, compiled without a GPU. On one MI355X, two graphs of 64 split launches replayed on two streams with no sync in between gave 263 of 384 wrong outputs in one run and 114 of 384 in another on the shared default scratch (a race, so it varies), and 0 of 384 with one workspace per stream. New cases: two_streams, and a capture that uses the explicit alloc (the default scratch is never allocated). ATOM does not pass a workspace yet; I did not run ATOM with it.
Description: updated: topk_idx [Hkv, rows, topk], the diff stat (+2093 / -0 over 4 files, 20 commits), the stray heading line gone, the NVFP4 reason (M3.1's native KV format is NVFP4, and the e4m3 scale per 16 dims cannot be expressed as the e8m0 scale of the MXFP4 tile), "Reviewed revision" 3af4025, and the multi-stream paragraph now describes the workspace.
What the warm-up needs: you are right that the scratch does not depend on shape: every call allocates the scale placeholder, only splits > 1 allocates the split scratch. The messages and the docstring now say: call sparse_pa_nvfp4_decode_alloc before capture, or make one eager call that needs the scratch. _unit_scale / _split_buffers now run inside the with torch.cuda.device(q.device) block, so the capture check looks at q's device. One more thing our own review asked for, which I did not ship: a refusal of a first call of a not-yet-loaded variant (splits, topk, xcds, late_v) inside a capture, because it would JIT-compile and load a module there. I measured it on gfx950 with FlyDSL 0.5.0 and it works, both for a variant compiled earlier and for one never compiled (correct replay); so there is no refusal, and the docstring says it worked in that test but still asks callers to call each variant once eagerly, since some other FlyDSL ops refuse it.
Nits: the device-side contract (seq_lens[r] <= block_table.shape[1] * 128, page ids in [0, kv_cache.shape[0])) is in the docstring and not checked in the wrapper, because checking it needs a device sync, which a capture cannot do; a kernel-side mask would change the ISA and add work to every launch, say so if you want that instead. LOG2E is imported from kernels_common.py and the copy is deleted (both literals give the same float32). The dead + 0 * j is gone. New refusal cases: non-uint8 kv_cache, strided block_table and seq_lens last dim, topk_idx.shape[1] < rows, topk 65, splits > topk, and seven workspace checks (42 refusal cases, was 28); the code already refused all of them, so there is no wrapper change.
Also added: oracle cases for topk 1, 8 and 64 at every split count up to topk (only 16 was tested). The full op test passes on gfx950: 120 correctness rows, 42 refusal cases, graph replay rel-L2 1.659e-3. Not run: ATOM with workspace=, CI's ruff version, and the performance table at this head (it was timed on an intermediate head, new/base geomean 0.992).
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The concurrent-workspace test uses only a whole-output norm, allowing localized corruption to pass; it should reuse check() for componentwise validation.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed exact head 3af4025 and the complete four-file merge-base diff. No blocking correctness defect found. On gfx950 with pinned FlyDSL 0.5.0, the full correctness suite passed, and an additional componentwise check passed for concurrent launches using separate workspaces.
Validation:
PASS on local and dzm-mi355-gpu34-dev: git rev-parse HEAD; git diff --exit-code
Both isolated source trees matched 3af4025 with no tracked changes. Remote verification is preserved in remote-sha-verified.log.
PASS on dzm-mi355-gpu34-dev / allocation 9589 / fsx950223_pr_review_gfx950 / GPU 6: flock -w 60 /workspace/gpu.lock timeout 600 /workspace/codex-pr-review-7825-20261116/venv/bin/python op_tests/test_flydsl_sparse_pa_nvfp4.py
Exit 0, PASSED 0. All 120 oracle rows passed; maximum rel-L2 0.00170805. Padding, poisoned-tail, refusal, launch-variant, capture, and separate-workspace concurrency checks passed. Architecture and intended imports were verified. Logs: gpu950-test-pinned.log and validation-commands.json.
PASS on dzm-mi355-gpu34-dev / allocation 9589 / fsx950223_pr_review_gfx950 / GPU 6: flock -w 60 /workspace/gpu.lock timeout 120 /workspace/codex-pr-review-7825-20261116/venv/bin/python - < concurrent_check.py
Exit 0. All 32 concurrent graph outputs using one workspace per stream passed componentwise checkAllclose and the fp64 relative-L2 check; maximum rel-L2 0.00163127. Log: gpu950-concurrent-componentwise.log.
SKIP on hjbog-srdc-39.amd.com / sixifang_dev: docker exec sixifang_dev python3 -c 'import torch,flydsl; print(torch.cuda.get_device_properties(0).gcnArchName); print(flydsl.__version__)'
Environment probe succeeded and reported gfx942 with FlyDSL 0.4.0. Kernel execution was skipped because this operation supports gfx950 only.
Remaining validation:
Validation used synthetic NVFP4 pages; real selector output and model integration were not exercised.
Performance tables were not independently remeasured. The existing base has no equivalent NVFP4 operation for a direct regression comparison.
Overlapping split launches must use separate workspaces. The suite reproduced corruption when sharing the default scratch, consistent with the documented caller contract.
The initial isolated-environment attempt lacked torch and pandas; its log is preserved. Dependencies were subsequently resolved within the isolated virtual environment, and validation passed.
… 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 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]>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The gfx950 kernel’s cross-workgroup ticketing and XCD-local coherence require exact-head GPU validation of numerical correctness, graph replay, concurrency, and performance, which is unavailable in this review environment.
Round 5, head 4e415b6bd9 (a test-only commit on top of 3af40255eb; kernels untouched). The PR body is updated.
Copilot, concurrent-workspace test (op_tests/test_flydsl_sparse_pa_nvfp4.py:745): fixed, see the reply in the thread. The per-stream-workspace outputs go through check(). I could not construct an error that the old whole-norm predicate passed and check() rejected on this data (the reference peaks at 2.69, so the componentwise tolerance is about 0.054), so this aligns the predicate rather than catching more; the 0.0813-error injection makes the new check fail.
Copilot, first thread (isolate scratch across overlapping launches): unchanged, answered earlier. Overlapping split launches need a workspace each (sparse_pa_nvfp4_decode_alloc), which the test pins.
fsx950223's review (approve at 3af40255eb): the componentwise concurrent check passed on a separate GPU, which is the same property the new test pins.
Not run at this head: perf (no kernel change), CI's ruff 0.16.0 (ruff 0.17.3 and black clean). The red evaluate on the push is a Self-Review run that was cancelled; the run after my body edit succeeded.
…7826)
* [FlyDSL] NVFP4 sparse PA: decode kernel
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]>
* Test: NVFP4 sparse PA decode vs an fp64 oracle (aiter op_test style)
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA: prefill kernel
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]>
* Test: NVFP4 sparse PA prefill vs an fp64 oracle, padding rows, perf table
Co-Authored-By: Claude <[email protected]>
* Fix ruff findings (B023, C408) in the NVFP4 sparse PA decode kernel and 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]>
* [FlyDSL] NVFP4 sparse PA decode: harden the host wrapper (review fixes)
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]>
* [FlyDSL] NVFP4 sparse PA prefill: harden the host wrapper (same fixes 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]>
* [FlyDSL] NVFP4 sparse PA decode: validate block_table/seq_lens/xcds, 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]>
* [FlyDSL] NVFP4 sparse PA decode: rename minimax_m3_sparse_pa_nvfp4_* 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]>
* [FlyDSL] NVFP4 sparse PA decode: reuse chip_info, drop the dead i32_reqs 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]>
* [FlyDSL] NVFP4 sparse PA decode: raise ValueError for the public input 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]>
* [FlyDSL] NVFP4 sparse PA decode: port the memory ops to FlyDSL buffer 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]>
* [FlyDSL] NVFP4 sparse PA decode: typed FlyDSL ops where they are equal, 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]>
* [FlyDSL] NVFP4 sparse PA decode: state the repeated-block-id contract
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]>
* [FlyDSL] NVFP4 sparse PA prefill: dedup the page union over every lane, 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]>
* [FlyDSL] NVFP4 sparse PA prefill: share the decode host helpers, mirror 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]>
* [FlyDSL] NVFP4 sparse PA prefill: tidy the tile knobs and comments
- 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]>
* [FlyDSL] NVFP4 sparse PA prefill: port the memory ops to FlyDSL buffer tensors, as decode
Same rule and same helpers as the decode kernel (aiter/ops/flydsl/AGENTS.md): the page
loader in the _common file, Q and the output go through ptr_buf_tensor / buf_copy_load /
buf_copy_store; the masked output store uses OOB_DWORD. Comment on the raw wave
primitives, as in decode.
Measured on one MI355X (flydsl 0.5.0):
- 60 prefill output sha256 (12 cases x 4 tiles + auto tile): identical to the tree
before this commit; the 50 of them that exist in the PR's original head (f3d1915)
are identical too, so the dedup fix changes nothing for distinct ids.
- op-test prefill perf table, 6 shapes, median of 5 interleaved runs per tree: time of
this branch over f3d1915 geomean 0.999 (min 0.983, max 1.013).
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA decode: a slot that is not valid never reads the block table
A padding-only call (seq_lens 0, every top-k slot -1) with a block table that has no
columns passed validation but still read bt[0] through the raw pointer: column zero was
selected, the load was not suppressed. An invalid lane now loads the first request length
instead (discarded), so the table is not touched. Regression case: padding_empty_table.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA decode: zero the V scales of the keys past the row position
Masking P does not help when an unwritten tail key carries a NaN V scale (e4m3 0x7f):
0 * NaN is NaN in the PV MFMA. In the tail block the scale bytes of the keys past the
row limit are zeroed before dequantization (only in the branch that already masks the
tail). Regression case: poisoned_tail (NaN scale bytes in the unwritten tail of the last page).
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA decode: refuse topk_idx / block_table views whose 32-bit element offsets overflow
The kernel computes head x stride, row x stride and request x stride in i32. A legal view
with a large stride wrapped to a negative offset. The wrapper now refuses views whose
largest element offset reaches 2**31 (no kernel change, so no ISA change).
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA decode: refuse operands that are not 4-byte aligned
Q, out and the pages are accessed through dword buffer tensors that declare 4-byte
alignment. check the base addresses of q, out and kv_cache and the page stride; padded
pages with an aligned stride are still accepted.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill: keep every logical block of a row when a table maps several to one page
The page union deduplicated physical pages, so with block_table [[0, 0]], ids [0, 1] and
row_kv_lens 129 the shared page got the tail mask and the row attended 1 token, not 129.
A lane's union key is now 2 * page + (1 if the slot is the row's own block): the own block
keeps its causal limit and the other blocks of the same page are unmasked (the page is
loaded once per key). A row weights a page by the number of its slots that selected it, so
two full blocks on one page count twice. This makes prefill agree with decode on every
input: a repeated block id now counts once per slot in prefill too (it was attended once,
a tile-independent but decode-different result for an out-of-contract input), and the
round-1 'dedup' oracle option is gone.
The same change stops an invalid slot from reading the block table (the prefill analogue
of the decode padding-row finding): such a lane loads the request id instead.
Regression cases: alias_two_blocks (the block_table [[p, p]] case), alias_chunk, and the
padding-only call with an empty block table.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill: zero the V scales of the keys past the rows' positions
Same finding as decode: P is masked past a row's limit, but a NaN V scale (e4m3 0x7f) in
the unwritten tail of the last page still gives 0 * NaN in the PV MFMA. The scale bytes of
the keys past the largest limit of the rows that reach the tail page are zeroed (the keys
between the rows' limits are written, and masked per row). scales_up_to moves to the
_common file and the decode kernel imports it. Regression: poisoned_tail runs prefill.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill: a padding-only call does not read a page
The prologue loaded the first union page unconditionally. With no valid slot (row_kv_lens 0,
every slot -1) it still read page 0, which does not exist when kv_cache is [0, page]: an
illegal memory access. The load now goes through a zero-size buffer when the union is
empty (as the decode kernel does for an invalid page). padding_empty_table covers an empty
KV cache as well as an empty table, for decode and prefill; two more alignment refusal
cases (cache base +2 bytes).
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill test: run the padding-row check at every tile
For 2 rows the auto tile is tq 1, where a padding row never shares a workgroup with
its neighbour. Loop over PREFILL_TQ and compare row 1 to the fp64 oracle as well.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill: drop the duplicate block_table dim check
check_operands already refuses a block_table that is not 2-D; the wrapper keeps only
the non-empty check, with its own message.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA prefill: fix two misplaced or untrue comments
The "causal limit" comment now sits above the lim code, not the Q buffer setup; the
perf test no longer claims neighbouring rows do not overlap (random top-k does overlap).
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA decode: refuse the first scratch allocation inside graph capture
The split scratch and the scale placeholder are cached per device and allocated
(and zero-filled) on the first call. Inside a capture the fill is recorded, not
run, so eager calls and other graphs read uninitialised tickets and scales.
The first call on a device during capture is now refused.
Co-Authored-By: Claude <[email protected]>
* [FlyDSL] NVFP4 sparse PA: honour AITER_FLYDSL_KERNARG_PRELOAD
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]>
* [FlyDSL] NVFP4 sparse PA decode: doc fixes and refusal tests
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]>
* op_tests: remove refusal cases duplicated by the #7825 merge
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]>
* [FlyDSL] NVFP4 sparse PA decode: caller-owned workspace for split launches
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]>
* [FlyDSL] NVFP4 sparse PA decode test: workspace, two streams, topk 1/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]>
* op_tests: refuse q of exactly 2 GiB, and run a call just below it
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]>
* op_tests: prefill refusal cases for row_req_id, row_kv_lens and the 16-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]>
* op_tests: prefill under graph capture
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]>
* op test: check every per-stream-workspace output with check()
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]>
* op_tests: prefill at tq 2 with 2 combine rounds, Hkv 2 / 4 with 8 heads 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]>
* op_tests: prefill_call pre-fills the output with NaN
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]>
* op_tests: prefill capture with explicit and default scales
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]>
---------
Co-authored-by: Claude <[email protected]>
Closing as landed: this PR's content is already on main. #7826 (sparse PA prefill) was stacked on this branch, so its head c0757bb110 contained all of this PR's commits (4e415b6bd9 is an ancestor of it), and the squash merge 8f574bdf51 brought in sparse_pa_nvfp4_common.py, sparse_pa_nvfp4_decode.py and op_tests/test_flydsl_sparse_pa_nvfp4.py together with the prefill kernel. Because it was squashed, git no longer recognises this branch's commits as merged, hence the add/add conflict. Resolving it against main would leave an empty diff.
The one review thread still open here was answered earlier; if anything in it needs a follow-up it will go into a new PR on top of main.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds the MiniMax-M3.1 sparse paged-attention decode kernel over an NVFP4 KV cache (FlyDSL, gfx950 / MI355X only):
sparse_pa_nvfp4_decode. It takes what the index selector emits,topk_idx [Hkv, rows, 16]logical 128-token block ids (-1 padded, any order) plus the request block table, so no sparse block table is built between the selector and the kernel. The prefill kernel is a follow-up PR stacked on this one.Why NVFP4 and not the MXFP4
pa_decodetile. NVFP4 does not use the MXFP4pa_decodetile because that tile feeds K's e2m1 codes to the scaled MFMA with one e8m0 (power-of-two) scale per 32 dims, widens V to bf16, handles onlyquery_length1 and reads separate data and scale views of shape[pages, kv_heads, 128, 64]/[.., 128, 4], while MiniMax-M3.1's native KV page is NVFP4: one buffer with an e4m3 scale per 16 dims (not a power of two, so it cannot be expressed as an e8m0 scale without changing the values) plus a global fp32 scale, so this kernel forms the exact e2m1 x e4m3 products in f16 and runs a plain f16 MFMA.Perf target not met. Measured cold (8 GB pool) median 5.28 TB/s over the 13-shape decode head set (our target was 6 TB/s; only 512 rows x Hkv 4 reaches 6.05). The 256-row Hkv 1 shapes (one workgroup per CU) are at 4.4-4.6 TB/s. Against the MXFP4 path and the vLLM NVFP4 kernel it is faster (tables below), but it is below the bandwidth we wanted.
Page format
One page = 128 tokens,
2 * Hkv * 9216B:[K side | V side], a side =Hkv x 8192 Be2m1 codes (low nibble = even element) thenHkv x 1024 Be4m3 scales, one scale per 16 elements. Same conventions as the NVFP4 index pages of #7813 / #7814 (128-token pages, e2m1 low nibble first, e4m3 scale per 16, no per-tensor scale in the page; the global fp32 k / v scales are separate[1]tensors). It is not the index page: this is the vLLM KV page, whose K scales and V data / scales are stored in MFMA-lane order so each lane loads its operands with a few wide loads. The exact byte offsets are in the docstring ofsparse_pa_nvfp4_common.py, and the test builds pages from token-major codes with its own writer, so a layout mistake cannot cancel against the kernel. There is no NVFP4 KV write kernel in this PR.Numerics
K and V = e2m1 x e4m3 scale, which f16 holds exactly (at most 6 significant bits), so nothing is rounded before the MFMA: 16-bit MFMA (
v_mfma_f32_16x16x32_f16), Q and P in f16, scores / softmax / accumulation fp32, bf16 output. f16 rather than bf16 because it measured faster. No fp8 MFMA. Q bf16 -> f16 is exact except |q| > 65504 or < 6e-8.Against an fp64 oracle on the same pages: rel-L2 1.6e-3 to 1.7e-3 (the bf16 output rounding floor), 96 checks. vLLM's NVFP4 decode kernel rounds K to e4m3, so its error against the same oracle is 3.6e-2 to 4.4e-2 in our runs (
mine-vs-vllm3.6e-2 to 4.4e-2 rel-L2, 9 cases) and the two are not expected to agree bit for bit.What changes (+2093 / -0, 4 files, 20 commits including the review rounds)
aiter/ops/flydsl/kernels/sparse_pa_nvfp4_decode.py(+984): the kernel andsparse_pa_nvfp4_decode(q, kv_cache, topk_idx, block_table, seq_lens, sm_scale, out, k_scale, v_scale, query_len). One workgroup = one query row x the (<= 16) query heads of one kv head x a share of the row's top-k slots; lane = top-k slot (one ballot gives the valid set); splits are a static partition of the slots merged in split order by the last workgroup to arrive (deterministic, no host sync, graph-capturable; scratch allocated on first use, so warm up before capture; one launch in flight per device, the scratch is shared). The split count, the XCD-aware grid (only when splits > 1) and trailing V loads (late_v, when 1.5 to 4 workgroups share a CU) are chosen per launch by rules measured on MI355X; each can be overridden and the test checks they agree bitwise. K data loads are non-temporal, V stays cacheable.aiter/ops/flydsl/kernels/sparse_pa_nvfp4_common.py(+191): page layout, MFMA mapping, conversion and softmax helpers.aiter/ops/flydsl/__init__.py(+10): the lazy exports ofsparse_pa_nvfp4_decodeandsparse_pa_nvfp4_decode_alloc.op_tests/test_flydsl_sparse_pa_nvfp4.py(+908): see Tests.No csrc, no tuned CSV (
aiter-config-shapedoes not apply).Left out of this PR on purpose: page-ring depths above 1 (measured slower, -5 to -15% at >= 2 workgroups per CU) and a cacheable-K option (streaming K is faster); both existed in the development branch.
Performance (decode)
One MI355X, same process, graph replay of 8 launches (about 2 us graph-node floor included), medians of 15 interleaved replays, two independent runs shown as r1/r2 where the cell has two numbers. ctx 32768 for every row; top-k = 15 random earlier blocks + the row's tail block (synthetic, not a real selector output); 4 input variants cycled; K/V pool 8 GB with random page ids (little cache reuse; the first-iteration numbers of the op test are warmer). TB/s = valid selected page-heads x 18432 B / time (MXFP4: x 17408 B).
MXFP4is the existing path: ATOM's Triton emit kernel (top-k -> page-folded block table) plus aiterpa_decodeon the MXFP4 pages with e4m3 Q, planned; it is a different KV quantization, so this is a speed comparison, not a numerics one.vLLMisnvfp4_sparse_decodeof our vLLM tree (models/minimax_m3/amd/ops, unmodified); it only supports 16 heads per KV head.Head set (the 4 TP head layouts at 256 / 512 rows, plus MTP q_len 4 / 8):
median NVFP4 TB/s 5.281 (min 4.42, max 6.05); NVFP4/MXFP4 time: geomean 0.839, worst 0.958; NVFP4/vLLM time: geomean 0.591, worst 0.658, over 9 shapes
Small shapes (1 to 128 rows, MTP), one run
median NVFP4 TB/s 1.663 (min 0.04, max 5.10); NVFP4/MXFP4 time: geomean 0.802, worst 0.893; NVFP4/vLLM time: geomean 0.681, worst 0.898, over 14 shapes
Shapes where NVFP4 is slower than the MXFP4 path: none in either table (worst 0.958 of its time). Shapes slower than vLLM: none.
Tests
python3 op_tests/test_flydsl_sparse_pa_nvfp4.py [--perf](about 30 s with--perf; exits non-zero on any failed check). Aiter op-test shape: no pytest,@benchmark+run_perftest+checkAllclose, markdown tables (us / TFLOPS / TB/s / err vs the oracle on the first rows),get_gfx_runtime()gating inmain(). fp64 torch oracle built from the token-major codes. Matrix: 16 cases (ragged, Hkv 1/2/4, group 8/16, one-token rows, block edges, fewer than top-k ids, tail only, junk ids, orderings, MTP 4/8, batches 40 / 130) x 6 split counts against the oracle; every split count vs one workgroup (fp32 merge order differs, so rel-L2 <= 2e-3, not bitwise); XCD-aware vs plain grid andlate_von/off bitwise; padding rows output zeros and do not disturb neighbours.Checked on this tree (flydsl 0.5.0, gfx950):
err1.3e-3 to 1.4e-3.xcdsxlate_v, plus 16 auto-selected perf shapes); compiled ISA is identical for the three variants compared.pa_decodepath: 6 sha256 hashes identical toorigin/main(this PR touches no existing code beyond the lazy-export table).padding_empty_table: it ended in an illegal memory access before); a NaN V scale (0x7f) in the unwritten tail of the last page (poisoned_tail: NaN in all 12 poisoned launches before; the fix zeroes those scales in the tail branch only, +26 instructions there, decode time geomean 0.998 over 14 shapes); refusals fortopk_idx/block_tableviews whose 32-bit element offsets reach 2**31 (outputs were wrong by 1.55 to 1.81 before) and for operands that are not 4-byte aligned. Op test 96 oracle checks PASSED; CUDA-graph replay rel-L2 1.659e-3. [measured]_unit_scaleand_split_buffersis refused inside a CUDA graph capture (a capture would record the fill instead of running it; with stale memory under the tickets an eager call after a capture-only gave rel-L2 1.054e-2 against the oracle, correct is 1.668e-3; the newcapture_scratchcase fails 6 checks on the old code);PRELOAD_HINTShonoursAITER_FLYDSL_KERNARG_PRELOAD(preload length 14 unset, 0 with=0; with the variable unset the ISA of all 20 decode variants is byte-identical to d83ef9e); doc fixes; four new refusal cases (the code already refused them). Op test at 214e5a0: 117 oracle checks (one is the poisoned-ticket check, which must fail) and 28 refusal cases, plus the capture cases. Decode time new/base geomean 0.991 over 4 alternating runs, which is noise (the ISA is identical). ATOM's capture loop runs an eager warm-up forward with the same shapes before each recording, so the first call is never inside a capture there (read, not run).sparse_pa_nvfp4_decode_alloc(device)and an optionalworkspace=argument, validated for device, dtype, size, contiguity and alignment, with the per-device cached buffer kept as the default; the warm-up wording now says what a first call needs (the scale placeholder is allocated by every call, the split scratch only bysplits > 1, so callsparse_pa_nvfp4_decode_allocbefore capture or make one eager call that needs it);_unit_scale/_split_buffersnow run insidetorch.cuda.device(q.device); the device-side contract (seq_lens[r] <= block_table.shape[1] * 128, page ids in[0, kv_cache.shape[0])) is documented, not checked, because a check needs a device sync;LOG2Eimported fromkernels_common.py. 3af4025: the tests). On one MI355X (gfx950): the full op test passes 120 correctness rows and 42 refusal cases, up from 96 and 28 (new:topk1, 8 and 64 at every split count up totopk, a two-streams case, a capture that uses the explicit alloc, seven workspace checks and more refusals); two graphs of 64 split launches on two streams with no sync in between gave 263 of 384 wrong outputs in one run and 114 of 384 in another on the shared default scratch (a race, so it varies) and 0 of 384 with one workspace per stream; the 25-replay graph check gives rel-L2 1.659e-3. The final ISA of 56 decode variants (topk8, 16, 64) is byte-identical to 214e5a0 (compiled without a GPU). A first call of a not-yet-loaded variant(splits, topk, xcds, late_v)inside a capture worked on gfx950 with FlyDSL 0.5.0 (correct replay), so it is not refused; the docstring says so and asks callers to call each variant once eagerly, because some other FlyDSL ops refuse it. The performance table was timed on an intermediate head and not re-timed on this one (new/base geomean 0.992).two_streams) now checks each of its 384 outputs with the file'scheck()(componentwisecheckAllcloseplus the fp64 rel-L2 check) instead of a whole-output norm only; the shared-scratch run (a caller error) keeps the whole-norm predicate and stays diagnostic-only. Test file only, kernels untouched. On the GPU the op test passes (PASSED 0); a 0.0813 error injected into one output of the per-stream run makes the new check fail (bad = 3). On this data the old predicate would also have failed there: the reference peaks at 2.69, so the componentwise tolerance is about 0.054 and any single-element error that fails it already pushes the whole norm over its tolerance; I could not find an error the old predicate passes and the new one fails, so this aligns the predicate with the rest of the file rather than catching more here. [measured]blackclean;ruff checkclean on the added files (a first push had two B023 and two C408 findings, fixed in the third commit with outputs, hashes and ISA re-checked unchanged).Not in this PR
Two decode launches that split a row (
splits > 1) and use the same workspace must not overlap: by default the workspace is one per device, so on several streams of one device each stream needs its ownworkspace=sparse_pa_nvfp4_decode_alloc(device); sharing one is the caller's error and corrupts the results silently (documented in the wrapper, not enforced). ATOM does not pass a workspace yet (not run with it). The prefill kernel (next PR), the NVFP4 KV write kernel, ATOM / vLLM integration. Not verified: behaviour on a real selector's top-k distribution or on real model data; non-gfx950 targets; flydsl versions other than 0.5.0.PR Self-Review
Reviewed revision
4e415b6 (head after review round 5: a test-only commit on top of 3af4025; the full sha is the PR head)
Behavior and intent
Adds
sparse_pa_nvfp4_decode, sparse paged-attention decode over an NVFP4 KV cache that reads the selector'stopk_idxand the block table directly. Before this there was no NVFP4 sparse decode in aiter. K and V are exact in f16, so nothing is rounded before the 16-bit MFMA. The wrapper raisesValueErrorfor operands it cannot read (arch, device, shape, dtype, stride, 2 GiB,splits,xcds, scales,sm_scale), whichpython -Odoes not strip. Block ids within a row must be distinct; a repeat counts twice.Validation and unverified scope
MI355X, flydsl 0.5.0, one card:
python3 op_tests/test_flydsl_sparse_pa_nvfp4.py --perfgives PASSED 0, 96 oracle checks, max rel-L2 1.70e-3. CUDA-graph replay (query_len 4, group 8, splits 4, xcds 8, 25 replays): rel-L2 1.659e-3. 864 output hashes are identical to af14f1c. Decode time over af14f1c: geomean 1.0035 over 14 shapes (10 alternating runs); 1.00 at 50 us and above. Unverified: a real selector's top-k, non-gfx950, flydsl other than 0.5.0, several streams or devices.PR-specific question
Every check fails before this PR (the op does not exist). The refusal cases raise
AssertionErroron af14f1c, so they fail theValueError-only test.Changed op tests
op_tests/test_flydsl_sparse_pa_nvfp4.pyis the only test of this kernel: 16 cases x 6 split counts against an fp64 oracle built from the token-major codes, split / XCD-grid /late_vagreement, padding rows, 18 refusal cases. The MXFP4pa_decodetests use another page format and kernel.Evidence
Decode time,
--perftable, median of 10 alternating runs per tree (before = af14f1c):after/before time: geomean 1.0035, min 0.958, max 1.021 over 14 shapes; runs per arm: 10
Raw ops: maxf_nn, exp2, pk_bf16 and mfma_f16 use the typed FlyDSL API (same instruction multiset, same hashes). permlane swap (typed shuffle_xor: 22 more instructions), the e2m1 / e4m3 converts (typed conversion does not compile) and the wave primitives stay raw, each with its reason at the call.
🤖 Generated with Claude Code