Repository navigation
[HIP] [Perf] fused_qknorm_idxrqknorm: early loads, hardware converts, DPP exchanges, xor-atomic V nibbles and a prefill variant - #8472
Conversation
…ope operand loads up front In fusedQKNormIdxrQKNormKernel the loads of one warp's work were a chain: slot_mapping, then the row and position behind the V branch, then the norm weight (folded into the norm's predicated region, so it waited right after issuing), then cos/sin. Load the row and slot_mapping before the V branch (V uses both), and issue the position, norm weight and cos/sin loads together past it, none behind a condition and none converted until used. The arithmetic is unchanged. Co-Authored-By: Claude <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
…4 converts nvQuantLane's e4m3 scale byte, its decode and the e2m1 codes were integer / compare chains. On gfx950 use v_cvt_pk_fp8_f32, v_cvt_f32_fp8 and v_cvt_scalef32_pk_fp4_f32 (scale 1) for the same values; the integer routines stay as the other arches' path. Both exact reciprocals (__fdiv_rn) are kept. The bytes are unchanged: exhaustive over all 2^32 fp32 inputs for the e2m1 codes and over [0, 448] for the e4m3 byte, with a NaN mapped to the zero of its sign as the integer code does. The op test now runs NaN, infinity, signed zero, subnormal, scale-tie and random-bit-pattern V rows and extreme global scales against a reference that states those semantics. Co-Authored-By: Claude <[email protected]>
New doc (this branch had none). Documents what the branch is (origin/main + PRs ROCm#8465/ROCm#8472/ROCm#8473, confirmed a strict superset of the production container's baked-in aiter commit b9e08da, 114 commits ahead with zero divergence), the known prior gap this closes (the production recipe's container bakes aiter into its image, so this branch's code was never actually exercised by a real server run before this pass), and the real wired e2e verification performed this pass: a fresh clone wired via a PYTHONPATH prepend ahead of the image's baked-in copy, confirmed from a live server process's own log, ran a full 900s c1 AgentX point with zero errors. Also notes a real gotcha hit this pass (the composable_kernel git submodule needs --recursive) and that amd_kernels elimination is a separate, not-yet-completed effort on the ATOM side, not this branch. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…V nibbles, FMA reciprocal NVFP4 decode insert (gfx950): replace the ds_bpermute shuffles of the norm / amax butterflies and the RoPE partner exchange by DPP moves and v_permlane16_swap, land the V nibble with one xor per word (two 64-bit atomics per lane instead of four and + or pairs), and compute the two exact reciprocals of the quantizer with v_rcp_f32 plus two FMA Newton steps. Bit-identical output. Technique credit: amd-kernels norm_rope_nvfp4_insert. Co-Authored-By: Claude <[email protected]>
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
There was a problem hiding this comment.
🔵 Needs a closer look
Maintainer confirmation is needed because the compiler-dependent GPU optimization lacks independent correctness and performance validation, particularly on the untested gfx942 target.
No open issues 🎉
What changed in this PR
This PR reorganizes global-memory loads in Aiter’s fused Q/K RMSNorm, RoPE, and cache-insert HIP kernel to reduce serialized memory waits without changing the public API or intended numerical results.
Changes:
- Load row data and slot mappings before the V branch, reusing row data for NVFP4 and MXFP4 V stores.
- Separate norm-weight and RoPE operand loading from computation, retaining operands in their storage type until use.
- Clamp unused RoPE indices so lanes outside the rotated dimensions can load valid operands unconditionally.
| File | Description |
|---|---|
csrc/kernels/fused_qknorm_idxrqknorm.cu |
Reorders operand loads and reuses row data to reduce memory-load serialization. |
Review effort: Balanced
…th for the MiniMax-M3 TP4 head set One HIP kernel family, two variants selected by token count: the existing one-warp-per-(token, head) kernel stays for decode-sized / non-matching calls, and a wave64-per-head prefill variant (2 or 4 token pairs per wave, scalar position/slot loads, shared cos/sin, V runs with full-octet fast path, buffer loads, non-temporal stores) is used for 16q/1kv/1index, head_dim 128, rotary 64, bf16, gfx950. Falls back automatically to the generic path. A raw-pointer pybind entry plus a Python gate cuts host time per call. Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical issues permit incorrect tensor indexing, misaligned memory operations, and 32-bit address overflow, while regression tests can pass without exercising the prefill kernel.
7 open issues
Require rank-2 QKV input in the raw gate · New Preserve alignment-safe accesses for 4-byte-aligned cache layouts · New Bound prefill descriptor extents and row offsets · New Enforce alignment for vector loads and 64-bit atomics Let input-construction failures fail the regression test · New Assert that forced-prefill tests launch the prefill kernel · New Reuse the shared GPU architecture detection helper · New
Review effort: Balanced
…ort reorder from the QKV front branch The QKV front kernels import only the device helpers of the FlyDSL NVFP4 insert, not the insert kernels. Keep those helpers (qkv_front_common.py) and remove the rest: the decode and prefill FlyDSL insert kernels, their test, and the FlyDSL route inside fused_qknorm_idxrqknorm (the NVFP4 insert stays the HIP kernel of ROCm#8472). Only the deferred QKV front hook remains in fused_qknorm_idxrqknorm.py. bench_models.py goes back to main (an import reorder only). Co-Authored-By: Claude <[email protected]>
… and prefill The raw entry no longer takes prefill only: fused_qknorm_nvfp4_raw serves every token count and the launcher picks the prefill variant from the token floor and the generic kernel below it, so the Python front has no token floor and decode shares the 8.8 us host path (28.9 us through the marshalled entry). The test compares the raw entry against the marshalled one at 1..8192 tokens under both floors and clears the remaining ruff findings. Co-Authored-By: Claude <[email protected]>
… prefill extent cap, raw front rank check, kernel-name dispatch receipt in the prefill test, shared arch probe) Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
The test fails with the supported AITER_REBUILD=1 setting because it asserts raw-entry availability before a valid public-op call rebuilds the module in the parent process.
1 open issue
2 resolved since last review
Review effort: Balanced
…aw front test_compile_fullgraph() asserted _nvfp4_raw_front(*args) is True directly, without ever calling the public op in this process first. Under AITER_REBUILD=1, the raw front's own rebuild gate declines until the marshalled wrapper has rebuilt the module (jit_core.rebuilded_list), and test_reject()'s rebuild runs in child subprocesses, so the parent's list is still empty when this assertion ran -- it failed before the compile check. Reproduced: running the pre-fix test under AITER_REBUILD=1 raises AssertionError at this line. Fixed by calling aiter.fused_qknorm_idxrqknorm once (the same shape) before probing the raw front directly, the same way a real caller reaches it. Verified on gfx950 (node 034): fails on the original code under AITER_REBUILD=1, passes with the fix under both AITER_REBUILD=0 and AITER_REBUILD=1. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
@ganyi1996ppo The prefill path truncates On gfx950 at Please preserve the int64 slot semantics in both the K/index-K writes and V-run detection, so negative slots remain skipped. |
…VFP4 prefill insert The prefill kernel read only the low 32-bit word of each int64 slot_mapping / index_slot_mapping entry, dropping the sign carried by the high word. A negative int64 slot with magnitude >= 2^32 (e.g. -4294967295 = 0xFFFFFFFF00000001, low word 1) was treated as a valid positive slot and written, whereas the generic kernel keys off the full int64 (slot < 0 -> skip). Reported by junhaha666: slots [-4294967295, -4294967294] left the caches unchanged under the generic kernel but wrote 399 KV-cache bytes + 144 index-cache bytes under the prefill kernel. Fix, in fusedNvfp4InsertPrefillKernel: - K / index-K slot load: the uint4 already loads both 32-bit words of each int64 (pp.x/pp.z low, pp.y/pp.w high, previously only pinned by an asm and discarded). Now slot_t[t] = (hi < 0) ? -1 : lo, so a negative int64 is skipped exactly as the generic kernel does. No extra loads; the discarded-word asm is removed. - V-run detection: read the full int64 (slot_mapping[widx]) and force a to -1 when it is negative; a stays a 32-bit low word for the DPP run-length exchange and readlane, so negative slots neither start nor continue a V run and the slot >= 0 write guard skips them. Valid (small non-negative) slots are bit-identical to before. Added a regression test (test_bigneg_slots_skipped) that runs the generic and prefill kernels on large-magnitude negative slots including [-4294967295, -4294967294] and asserts byte-identical caches and zero bytes written for all-padding patterns. Verified on gfx950: the regression test passes (prefill == generic, 0 bytes); the prefill-vs-generic grid is 114/114 identical and the nvfp4 byte-exact test passes, so the valid-slot fast path is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@junhaha666 Thanks for the catch and the clean repro. Fixed in 7fc6961. The prefill insert now reads the full int64 slot and skips it when negative (the sign lives in the high word), matching the generic kernel's
Verified on gfx950: your exact case |
|
Re: the Copilot review "🔵 Needs a closer look" — 64-bit slot truncation (can corrupt cache data or skip valid slots): Fixed in 7fc6961. The NVFP4 prefill insert previously read only the low 32-bit word of each int64
Valid (small non-negative) slots are bit-identical to before. New regression test |
… script entry The standalone __main__ path ran main() but never test_bigneg_slots_skipped(), so the large-magnitude-negative-slot check was only reached under pytest, not when the file is run as a script (Copilot review, ROCm#8472). Invoke it from the entry point too, guarded to the top-level invocation (the --child/--bigneg-child workers must not re-spawn the comparison) and to gfx950, matching main()'s gate. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
🔵 Needs a closer look
Human assessment is needed because the alignment guard omits two output pointers, allowing sliced output views that violate the prefill kernel’s store-alignment requirements.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
…index_q_fp8_out) Copilot overview (ROCm#8472): launchNvfp4Prefill's pfPtrAligned8 guard covered only the input pointers (q_norm_w, k_norm_w, iq_norm_w, ik_norm_w, cos_sin_cache), but the prefill kernel also does aligned vectorized stores to its outputs: q_out with uint2 (8 B) non-temporal stores and index_q_fp8_out with int (4 B) stores. Both are caller-provided (std::optional<aiter_tensor_t>, taken by data_ptr()), so a sliced output view with an odd storage_offset would break those stores exactly like a sliced input breaks the loads. Extend the same decline-to-generic guard to the outputs: pfPtrAligned8(q_out) and a new pfPtrAligned4(index_q_fp8_out) for its 4 B store width. The fast path stays bit-identical for aligned outputs; a misaligned output now falls back to the generic kernel (which produces correct results) instead of storing misaligned. Extend test_fused_qknorm_nvfp4_prefill.py with a misaligned_out case (q sliced to 2 B, iq to 1 B) asserting the forced-prefill child matches the generic child byte-for-byte at the dispatch-probe and larger token counts. Co-Authored-By: Claude Opus 4.8 <[email protected]>
….py — ROCm#8472 file + qkv-front hook, deferred-front before _nvfp4_raw_front Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ch (1-64 rows) + split-K (65-128 rows) GEMM / norm / RoPE / NVFP4 insert (#8607) * [FlyDSL] [Perf] fused_qknorm_idxrqknorm: FlyDSL NVFP4 insert for MiniMax-M3 TP4 prefill Same bytes as the HIP kernel, 1.6-3.0x faster on device and 3.5x less host time per call for calls of at least 1024 tokens (nvfp4 K/V/index-K, 16/1/1 heads, rotary 64, gfx950). Ported from amd-kernels. AITER_FUSED_QKNORM_NVFP4_FLYDSL=0 keeps the HIP kernel. Co-Authored-By: Claude <[email protected]> * [FlyDSL] mxfp8 activation quantizer for the decode GEMM tiers: (16, 16) code layout + shuffled E8M0 scales gfx950 FlyDSL quantizer: bf16 [M, K] -> fp8 e4m3 codes in the weight's (16, 16) preshuffled layout (rows padded to the row tile, padding rows zero) plus E8M0 scales in AITER's shuffled layout, or row-major codes. One launch, a workgroup per 32-row x 256-K tile. Prerequisite of the one-launch QKV front chain (next PR): that kernel reads exactly these codes. Technique source: amd-kernels gemm/mxfp8_common/mxfp8_quant.py and the scale/convert helpers of mxfp8_gemm_decode.py (ported, no import). op_tests/test_flydsl_mxfp8_quant_shuffled.py compares codes and scales byte for byte against a torch reference of the Triton MXFP8 rule (60 shape/magnitude cases). Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Perf] one-launch MiniMax-M3.1 QKV front chain for 17-64 decode rows (TP4) QKV MXFP8 GEMM (deferred split-3) + q/k/index-q/index-k RMSNorm + partial RoPE + NVFP4 K/V/index-K page inserts in ONE launch: 240 five-wave workgroups, a head's 12 workgroups publish sc1 slabs and bump an epoch counter, the last roles reduce and insert eight rows each. Replaces the three launches of the public decode path (quantize, GEMM, fused_qknorm_idxrqknorm) for 17-64 rows. Host wrapper qkv_chain_cooperative_insert keeps counters per device/stream or HIP capture id. Technique source: amd-kernels attention/mxfp8_qkv_norm_rope_nvfp4_insert_n2560_k6144_rot64_p128 (kernel_cooperative.py, host.py) and the decode GEMM primitives of mxfp8_gemm_decode.py (ported, no import). Helpers come from the FlyDSL NVFP4 insert of #8576, activation codes from the quantizer of the previous commit. Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Perf] split-3 decode MXFP8 GEMM (fp32 K-third slabs) for 65-128 rows, MiniMax-M3.1 TP4 QKV One-wave workgroups over RT 16-row x NI 16-column tiles of one K third, both operands in the (16, 16) preshuffled layout, W / A blocks issued ahead of the scaled MFMAs, odd-RT A scale re-pairing; writes the fp32 slabs a fused reduce-insert reads. Bit-identical to the amd-kernels decode GEMM at 65..128 rows; graph replay 8.1-9.1 us vs 9.7-11.7 us for the public GEMM. Technique source: amd-kernels gemm/mxfp8_common/mxfp8_gemm_decode.py (ported, no import). Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Perf] split-3 reduce + norm / RoPE + NVFP4 insert, QKV chain for 65-128 decode rows (TP4) Sums the three fp32 K-third slabs, rounds to bf16 and runs the norm / RoPE / NVFP4 K, V, index-K insert arithmetic of fused_qknorm_idxr_nvfp4_insert in one launch (V in workgroups of its own through LDS); qkv_chain_insert serves 17-128 rows (one launch to 64 rows, GEMM + reduce-insert above). Bit-identical to the amd-kernels chain at 65..128 rows; graph replay 13.7-16.3 us vs 16.9-20.0 us for quantize + public GEMM + fused_qknorm_idxrqknorm. Technique source: amd-kernels attention/mxfp8_qkv_norm_rope_nvfp4_insert_n2560_k6144_rot64_p128 (reduce_insert.py, packing.py). Co-Authored-By: Claude <[email protected]> * [FlyDSL] mxfp8 quantizer review fixes: bf16/contiguous input check, per-device compiled handle + x.device stream, whole-tile rule for rpw>2, op test entry point Co-Authored-By: Claude <[email protected]> * [FlyDSL] qkv chain review fixes: operand validation (devices, dtypes, extents), per-device handle + stream, stricter page checks, op test entry point Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Perf] QKV front tier chosen by a tuned table: gemm_a8w8_qkv_front + deferred fused epilogue in fused_qknorm_idxrqknorm The MXFP8 QKV projection of a decode layer is one interface (gemm_a8w8_qkv_front); a tuned row (a8w8_mxfp8_qkv_front_tuned_gemm.csv, kernelId qkvfront) picks plain / one-launch chain (17-64 rows) / split-3 chain (65-128 rows). A fused tier only quantizes in the projection and runs GEMM + norm + RoPE + NVFP4 insert inside the fused_qknorm_idxrqknorm call on the same tensor. Whole-front tuner: op_tests/tune_gemm_a8w8_qkv_front.py. Co-Authored-By: Claude <[email protected]> * [FlyDSL] qkv chain: row-major activation mode (a_row) for the one-launch tier and the front, to measure (16, 16) vs plain A Co-Authored-By: Claude <[email protected]> * [FlyDSL] qkv front on row-major A only: drop the (16, 16) activation layout, the shuffled quantizer and code_rows; retune the one-launch lookahead; regenerate the tier rows Co-Authored-By: Claude <[email protected]> * [FlyDSL] qkv front: split-K factor ks as a tuning config (1/2/3/4/6) through the kernel, the reduce-insert and the tuned rows; tuner enumerates ks x tile; #8610's row-major split kernel merged in Co-Authored-By: Claude <[email protected]> * drop the shuffled-A split-K op test (replaced by test_gemm_a8w8_qkv_front.py row-major split cases) Co-Authored-By: Claude <[email protected]> * [FlyDSL] QKV front as one op: static tier by row count (17-64 one-launch, 65-128 split-K, ks a kernel parameter), no tuned table / tuner / config family; hand-off failure modes documented and checked; quantizer guard-byte and fused-vs-unfused bitwise tests Co-Authored-By: Claude <[email protected]> * [FlyDSL] one-launch QKV front serves 1-16 rows too (RT=1 tile; no structural limit found), window 1-128 Co-Authored-By: Claude <[email protected]> * [FlyDSL] drop the closed #8576 FlyDSL insert and an unrelated import reorder from the QKV front branch The QKV front kernels import only the device helpers of the FlyDSL NVFP4 insert, not the insert kernels. Keep those helpers (qkv_front_common.py) and remove the rest: the decode and prefill FlyDSL insert kernels, their test, and the FlyDSL route inside fused_qknorm_idxrqknorm (the NVFP4 insert stays the HIP kernel of #8472). Only the deferred QKV front hook remains in fused_qknorm_idxrqknorm.py. bench_models.py goes back to main (an import reorder only). Co-Authored-By: Claude <[email protected]> * [FlyDSL] QKV front review fixes: operand validation as exceptions, op-boundary shape / head checks, device-keyed split launches - asserts that validated caller operands (shapes, dtypes, devices, strides, ranges, ks) are ValueError now, so python -O keeps them; one _validate shared by the one-launch and split tiers (the split tier had fewer checks) - the head set (16 / 1 / 1, rotary 64) and N 2560 / K 6144 are checked with a message naming the supported shape, at gemm_a8w8_qkv_front and at both chain entries; ks outside (1, 2, 3, 4, 6) is rejected - the split GEMM and the reduce-insert launches key the compiled handle by device and run under the operand's device and stream (a handle reused on another device does not launch) Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Build] AOT prebuild of the QKV front kernels aiter.aot.flydsl.qkv_front replays qkv_chain_insert on FakeTensors over 1-128 rows, bisected where the tile or tier switches, so the one-launch kernels (16 / 32 / 48 / 64 rows), the split-K GEMM tiles and the reduce-insert are in the prebuilt cache; registered in AOT_MODULES and the AOT README. Co-Authored-By: Claude <[email protected]> * [FlyDSL] QKV front: drop stale skips (not-in-this-tree) and tuned-table wording from tests and comments Co-Authored-By: Claude <[email protected]> * [FlyDSL] [Build] dry_run: the Event stand-in accepts record / synchronize The QKV front's counter pool records and waits on a cuda Event on first use; under the AOT dry run the stand-in had neither method, so the replay of qkv_chain_insert failed with AttributeError. Co-Authored-By: Claude <[email protected]> * [FlyDSL] QKV front: document the slot_mapping run contract (consecutive slots per octet, no gapped or split-octet runs) Co-Authored-By: Claude <[email protected]> * [FlyDSL] qkv front _validate: require f32 k/v scales and non-overlapping uint8 KV pages Harden the operand checks the raw-pointer launch depends on (Copilot review, PR #8607): - k_scale / v_scale: the kernels read the scalar via _gptr(..., T.f32, 4), so require float32 with numel() >= 1; a 1-element bf16 scalar previously passed but would be a 2-byte read reinterpreted as f32. - kv_cache / index_cache: require uint8 and stride(0) >= full page footprint (2*128*72 / 128*72). The kernels index pages by slot>>7, so an expanded or overlapping page layout (e.g. stride(0)==0) would let distinct slots alias the same page. dtype uint8 is now also enforced. Co-Authored-By: Claude Opus 4.8 <[email protected]> * op_tests: consolidate gemm_a8w8_qkv_front tests into test_flydsl_qkv_chain.py (remove standalone file) All chain and gemm_a8w8_qkv_front correctness cases are retained verbatim in the single file; no coverage change (7 test functions / 257 parametrized cases before and after). Shared `needs_gfx950` mark and `NB` constant deduplicated; the standalone file is removed. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude <[email protected]>
…he row layout (gfx950, gfx1250) kv_cache_dtype="nvfp4" with byte k_scale / v_scale planes (uint8 or float8_e4m3fn) writes K (normed, roped) and V straight into the NVFP4 row layout of MiniMax-M3's sparse pool and of the FlyDSL paged decode: per (page, kv head) an e2m1 payload [128, 64] and E4M3 scales [128, 8], no global scale. With it, index_cache_dtype="nvfp4" and the new index_scale argument write the index key in the same layout and the same pass: payload [pages, 128, 64], scales [pages, 128, 8], addressed by index_slot_mapping. ATOM staged these rows in BF16 and quantized them in three more launches per sparse layer. - The scale dtype picks the layout. fp32 [1] k_scale / v_scale keep the page layout of ROCm#7824, still gfx950-only; byte planes select the row layout, on gfx950 and gfx1250. The wrapper uses this only for its arch check; the C++ host checks own every other rule. - The row layout runs the generic kernel at every token count. The prefill variant and the raw-pointer entry of ROCm#8472 are the page layout's: their V runs, K scale order and single page stride are that format's, and the variant is compiled for gfx950 only. The launcher reaches it under kNvfp4, which the row layout does not set. Neither Python fast path (the raw front, the deferred QKV front of ROCm#8607) takes a call with index_scale, so a page-layout call that passes it is refused (by the C++ checks, or by the deferred front itself) instead of having it dropped. - With the row-layout K/V the index cache is "auto", fp8 or NVFP4 rows (index_scale). An mxfp4 or page-layout nvfp4 index cache is refused (each would be its own set of kernels). - scale = e4m3(amax / 6) (RNE, saturating at 448), codes = e2m1(x * (1 / scale)) half to even, sign included, in IEEE arithmetic: the rule of ATOM's Triton NVFP4 stores (kv_nvfp4_store, index_fp4_store), so the bytes match them on finite rows. The scale byte and the magnitudes come from nvQuantLane with a unit global scale (the page layout's quantizer, on gfx950 its hardware converts): amax * float32(1/6) rounds to the e4m3 byte of amax / 6 for every bf16 and fp16 amax. The sign is the row layout's own: none for a NaN, a zero or any element of a zero-scale group, read from x's bits because this file is built with fp32 denormals flushed and x * (1 / scale) can be one. The store is storeNvfp4IndexRow with a kRows flag. - Token rows are contiguous inside a (page, head); the base and the page and head strides of every plane are free, each plane on its own. The 16-bit payload store (nvStoreRowData, which the page layout shares) assumes no alignment and compiles to the same code as before; the host refuses a plane in which two (page, head)s share bytes. - Kernel: template flags kNvRows and kNvIndexRows (default false) and one trailing NvRows argument: the K and V scale-plane strides, and the index rows' scale plane and page strides. 16 new kernels. The existing ones keep their instructions and resources; only the implicit-kernarg offset moves, by the argument's 56 B. The prefill kernels are unchanged. op_tests/test_fused_qknorm_nvfp4.py: test_nvfp4_rows checks the K/V and index rows byte for byte against "auto" + a torch reference of the rule, on strided fields of one pre-filled pool: also with odd payload bases and odd page and head strides, with every plane on its own strides and the two scale planes of different byte dtypes, and in the call shape of the prefill variant (16 q / 1 kv / 1 index heads, bf16, e4m3 index_q_out). The rows include zero-scale blocks of either sign, elements whose x * (1 / scale) is an fp32 denormal, NaN and infinities. test_rows_reject covers the host refusals, the wrapper's arch gate per scale dtype and the deferred front's refusal; test_reject gains the page-layout call of the raw front's shape with index_scale. stress_qkv's largest magnitude is now the dtype's (3e38 does not fit fp16). Co-Authored-By: Claude Fable 5.2 <[email protected]>
main brings ROCm#8472 (NVFP4 prefill kernel, raw NVFP4 entry, gfx950 lane exchanges and converts in the generic kernel) and ROCm#8607 (deferred QKV front in the wrapper). Conflicts, resolved mechanically: - csrc/include/rocm_ops.hpp: both sides (qkv_partials / check_only arguments of fused_qknorm_idxrqknorm, main's fused_qknorm_nvfp4_raw binding). - csrc/kernels/fused_qknorm_idxrqknorm.cu - includes: the union. - norm / rope helpers: both sets, each written out in full. main's xorLane, warpSum32, NormRopeOperands, loadNormWeights, loadRopeOperands and normAndRope (the prefill kernel uses all but the two loaders) next to this branch's shflXor, warpReduceSum / warpReduceMax, NormRopeInputs, loadCosSin, rotateElems, ropeElems and normAndRope. The two normAndRope differ in the operand type. - fusedQKNormIdxrQKNormKernel: this branch's body, plus one line: the NVFP4 V store passes the lane's loaded row, which main's storeNvfp4VToken now takes. - the prefill kernel, its launcher, fused_qknorm_nvfp4_raw and the NVFP4 store helpers are main's, untouched. The host entry, the launcher, the header, the wrapper and the tests merged without conflict. At this commit the generic kernel does not yet use main's helpers: off gfx12 its lane exchanges are ds_bpermute again, and its packed loads still assume 8 B aligned norm weights and cos/sin, which main's prefill launcher hands to it unaligned. The wrapper's two new fronts (deferred QKV front, raw NVFP4 front) return before check_only and qkv_partials are looked at. The following commits fix these. Device assembly (CPU compile, JIT flags): on gfx1250 1152 of the 1160 generic instances and reduceQkvPartialsKernel are identical to 0af322d's; the 8 NVFP4 instances take main's store helpers. The prefill kernel is identical to main's on gfx1250, gfx950 and gfx942. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…he row layout (gfx950, gfx1250) kv_cache_dtype="nvfp4" with byte k_scale / v_scale planes (uint8 or float8_e4m3fn) writes K (normed, roped) and V straight into the NVFP4 row layout of MiniMax-M3's sparse pool and of the FlyDSL paged decode: per (page, kv head) an e2m1 payload [128, 64] and E4M3 scales [128, 8], no global scale. With it, index_cache_dtype="nvfp4" and the new index_scale argument write the index key in the same layout and the same pass: payload [pages, 128, 64], scales [pages, 128, 8], addressed by index_slot_mapping. ATOM staged these rows in BF16 and quantized them in three more launches per sparse layer. - The scale dtype picks the layout. fp32 [1] k_scale / v_scale keep the page layout of ROCm#7824, still gfx950-only; byte planes select the row layout, on gfx950 and gfx1250. The wrapper uses this only for its arch check; the C++ host checks own every other rule. - The row layout runs the generic kernel at every token count. The prefill variant and the raw-pointer entry of ROCm#8472 are the page layout's: their V runs, K scale order and single page stride are that format's, and the variant is compiled for gfx950 only. The launcher reaches it under kNvfp4, which the row layout does not set. Neither Python fast path (the raw front, the deferred QKV front of ROCm#8607) takes a call with index_scale, so a page-layout call that passes it is refused (by the C++ checks, or by the deferred front itself) instead of having it dropped. - With the row-layout K/V the index cache is "auto", fp8 or NVFP4 rows (index_scale). An mxfp4 or page-layout nvfp4 index cache is refused (each would be its own set of kernels). - scale = e4m3(amax / 6) (RNE, saturating at 448), codes = e2m1(x * (1 / scale)) half to even, sign included, in IEEE arithmetic: the rule of ATOM's Triton NVFP4 stores (kv_nvfp4_store, index_fp4_store), so the bytes match them on finite rows. The scale byte and the magnitudes come from nvQuantLane with a unit global scale (the page layout's quantizer, on gfx950 its hardware converts): amax * float32(1/6) rounds to the e4m3 byte of amax / 6 for every bf16 and fp16 amax. The sign is the row layout's own: none for a NaN, a zero or any element of a zero-scale group, read from x's bits because this file is built with fp32 denormals flushed and x * (1 / scale) can be one. The store is storeNvfp4IndexRow with a kRows flag. - Token rows are contiguous inside a (page, head); the base and the page and head strides of every plane are free, each plane on its own. The 16-bit payload store (nvStoreRowData, which the page layout shares) assumes no alignment and compiles to the same code as before; the host refuses a plane in which two (page, head)s share bytes. - Kernel: template flags kNvRows and kNvIndexRows (default false) and one trailing NvRows argument: the K and V scale-plane strides, and the index rows' scale plane and page strides. 16 new kernels. The existing ones keep their instructions and resources; only the implicit-kernarg offset moves, by the argument's 56 B. The prefill kernels are unchanged. op_tests/test_fused_qknorm_nvfp4.py: test_nvfp4_rows checks the K/V and index rows byte for byte against "auto" + a torch reference of the rule, on strided fields of one pre-filled pool: also with odd payload bases and odd page and head strides, with every plane on its own strides and the two scale planes of different byte dtypes, and in the call shape of the prefill variant (16 q / 1 kv / 1 index heads, bf16, e4m3 index_q_out). The rows include zero-scale blocks of either sign, elements whose x * (1 / scale) is an fp32 denormal, NaN and infinities. test_rows_reject covers the host refusals, the wrapper's arch gate per scale dtype and the deferred front's refusal; test_reject gains the page-layout call of the raw front's shape with index_scale. stress_qkv's largest magnitude is now the dtype's (3e38 does not fit fp16). Co-Authored-By: Claude Fable 5.2 <[email protected]>



At a glance
fusedQKNormIdxrQKNormKerneloffused_qknorm_idxrqknorm(fused Q/K RMSNorm + RoPE + NVFP4 KV / index-cache insert): early operand loads, gfx950 hardware converts, DPP exchanges with xor-atomic V nibbles and an FMA reciprocal, and a prefill variant, all behind one raw-pointer NVFP4 entry.ds_bpermute, oneatomicXorper V word instead ofatomicAnd+atomicOr; the prefill variant runs one wave per head with cos/sin shared by token pairs; the raw entry skips pybind marshalling.compile_opswrapper (tables below).Summary
Four changes to the HIP kernel (the first three bit-identical latency changes, the fourth a new prefill variant of the same kernel family)
fusedQKNormIdxrQKNormKerneloffused_qknorm_idxrqknorm(fused Q/K RMSNorm + RoPE + NVFP4 KV / index-cache insert, MiniMax-M3.1 TP4 decode and small-token calls). They were four stacked or related PRs (#8472, #8473, #8580 and the FlyDSL kernel of #8576) for one op; they are one PR now, as four commits, with one HIP kernel family and one dispatch.625fe97a2): issue the row,slot_mapping, position, norm weight and cos/sin loads of a warp together instead of as as_waitcnt vmcntchain. Two load stages after the V branch instead of three.408b6fdb7): the NVFP4 quantizer computes the e4m3 scale byte, its decoded value and the e2m1 codes withv_cvt_pk_fp8_f32,v_cvt_f32_fp8andv_cvt_scalef32_pk_fp4_f32instead of a compare / select chain per element. The torch reference in the test now states the NaN / infinity semantics.fdec4e4cf): the norm sum, the amax butterfly and the RoPE partner exchange use DPP moves instead ofds_bpermute; the V nibble lands with oneatomicXorof(old ^ new) << shift(disjoint bits, xors commute) instead ofatomicAnd+atomicOrper word; the two__fdiv_rn(1, x)ofnvQuantLanebecomev_rcp_f32plus two FMA Newton steps (identical to__fdiv_rnfor every positive normal fp32, exhaustive on MI355X; outside [2^-100, 2^100] and for 0 / inf / nan it falls back).All gfx950-specific changes are gated on
__gfx950__; other arches compile to the previous code. The DPP rope partner is used forrotary_dim == 64; other rotary dims keep__shfl.Results (MI355X gfx950, MiniMax-M3.1 TP4 head set: 16 q, 1 kv, 1 index head, head_dim 128, rotary 64, bf16)
Device-side kernel time of the NVFP4 insert, torch profiler, median of 200 launches, rotated inputs, alternating runs on one GPU, us (from the three original PRs):
Graph replay of 64 distinct inserts, event timing, median of 4 alternating rounds in one lease, us per call (A = changes 1+2, this = all three, amd-kernels =
norm_rope_nvfp4_insert_d128_rot64_p128):Change 3 alone saves 0.5 us at 8 rows to 2.0 us at 384 rows. No end-to-end model run was done. At 1024 tokens and above the TP4 head set is served by the FlyDSL kernel of #8576, so those sizes are not the target of this PR.
Known gap, stated on purpose
This kernel does not reach the amd-kernels kernel: it is still about +1.0 us per call slower at decode row counts, about 60 sparse layers x 1.0-1.1 us = 0.06-0.07 ms per decode step (0.2-0.3% of a 28.95 ms G64 step). That gap was reviewed and accepted by the owner.
Tried and not included: pinning kernel arguments in SGPRs (no change, 3.78 vs 3.77 us at M=8); a V "run writer" without atomics (slower below about 200 rows).
Correctness
python op_tests/test_fused_qknorm_nvfp4.py -t 1 7 8 16 64 300 --perf_tokens 8(1260 byte-for-byte checks) and the unchangedtest_fused_qknorm_idxrqknorm.py(fp8 / mxfp4 / auto, per-token and static scales) pass; the nvfp4 test checksatol=0, rtol=0against the torch reference including special global scales, padded / skip layouts, seq / scatter / MTP slot patterns.Review
By hand against the repo
review-prrules on each commit when it was a separate PR; no open findings.4. Prefill variant of the same kernel family (replaces the FlyDSL kernel of #8576)
A second,
constexpr-selected variant offusedQKNormIdxrQKNormKernelfor the MiniMax-M3 TP4 head set (16 q / 1 kv / 1 index heads, head_dim 128, rotary 64, bf16, NVFP4 K/V + NVFP4 index cache, gfx950): one wave64 per head for2*tptokens (2 token pairs per wave below 3072 tokens, 4 from 3072), scalar position / slot / scale loads, cos/sin shared by two token pairs, V octets written by the first token of a run (runs are found on the device from consecutive rows with consecutive slots, so the contract stays "slots are distinct": a run that covers a whole octet is stored plainly, a shorter run xors in only its own nibbles, scattered / MTP / decode-shaped calls degrade to one-token runs), hardware bf16 / fp8 packs, and a branch-free full-octet V quantization with an exact fallback. The measured crossover is at 2 tokens, so the dispatch floor is 2 (AITER_FUSED_QKNORM_NVFP4_PREFILL_MIN_TOKENSoverrides it); every call that does not match the head set / dtypes / contract runs the unchanged generic path. Design source: the FlyDSL kernel of #8576 (itself ported from amd-kernels, credited in the source; no import).Device time per call, us (MI355X gfx950, graph replay of 8 rotated input copies, median; HIP #8472 head = changes 1-3 only):
It is never slower than the HIP kernel without it, and within 3% of the FlyDSL kernel at 384-2048 and 8192-32768 tokens (faster at 512, 768, 1024, 16384, 32768); 6% slower at 4096 and 3% at 256. At 8-128 tokens it is about 1 us (~20%) slower than the FlyDSL kernel, but the FlyDSL kernel was only dispatched from 1024 tokens, so there the comparison is with the unchanged HIP kernel, which it beats. Some of the small-token rows (8-128 tokens) were measured before the full-octet V fast path was added, so they are conservative.
Host time per eager call (2000 calls, median of 2 runs): about 8.7 us for the new path through a raw-pointer entry, 8.3 us for the FlyDSL kernel, 28.5 us for the existing
compile_opswrapper (aiter's pybind marshalling costs about 1.7 us per tensor). The raw-pointer entry takes plain integers after a short Python-side gate; the C++ entry itself only checks num_tokens and the device arch (dtypes/shapes/strides/alignment/devices are validated solely by the Python gate, not re-checked in C++, so a call that bypasses that gate is unsafe); it matters for eager prefill steps and makes no difference under CUDA graphs. Kernel resources: 69 VGPR / 96 SGPR / 0 LDS / 0 scratch, occupancy 7 (the small kernel: 28 VGPR, occupancy 8); hipcc compile time of the translation unit +0.4 s (23.2 s -> 23.6 s).Verification: byte-for-byte against the generic kernel in 528 cases (token counts 2 ... 32768 incl. odd counts and the 6143 / 6145 tile boundary; slot patterns: contiguous, aligned, multi-request, -1 tail / middle, sparse, scattered, MTP, shared-octet runs, reversed, gap-2, random chunks) and against the FlyDSL kernel in the 220 cases inside its contract: 0 differ.
op_tests/test_fused_qknorm_idxrqknorm.py(all modes exceptmxfp4_reject) exits 0 with 58 clean result rows;op_tests/test_fused_qknorm_nvfp4.pyexits 0 with no new crash dump. Newop_tests/test_fused_qknorm_nvfp4_prefill.py(+298 lines).Supersedes #8473, #8580 and #8576 (closed in favour of this PR).
Review-fix update (head
e72ed2d9f)Changes after the review comments (all in the commits
fe8ae8719ande72ed2d9f):AITER_CHECK) and in the Python raw front; a 4 B-only layout is refused. New REJECT case "page stride 4 B aligned" inop_tests/test_fused_qknorm_nvfp4.py.kPfMaxTokens = INT32_MAX / (kPfRow * 2)= 419430 tokens (32-bit buffer extent); above that the generic kernel (64-bit row addresses) runs. Covered by two extra cases (419430 / 419431) in the prefill test.qkv.dim() == 2, declines whileAITER_REBUILDhas not been honoured by the wrapper, and declines for a loaded module without the raw symbol.fusedNvfp4InsertPrefillKerneland the generic child must not.get_gpu_arch().Re-verified on gfx950 (node overlay of this branch's diff on an older aiter image, touched JIT module rebuilt):
test_fused_qknorm_nvfp4.pyexit 0 (includes the new REJECT case and padded variants);test_fused_qknorm_nvfp4_prefill.py: raw vs marshalled 0 differ in both children and 506 cases compared, 0 differ (the 264-case grid plus the two 419430 / 419431 cases); aftere72ed2d9f:-n 1 8 --seeds 1 --kinds contigpasses (4 cases, 0 differ) and a call withAITER_REBUILD=1goes through the wrapper, which rebuildsmodule_fused_qknorm_idxrqknorm. The 58-rowtest_fused_qknorm_idxrqknorm.pyrun quoted above was not repeated after the review fixes.Reproduce:
python3 op_tests/test_fused_qknorm_nvfp4.py,python3 op_tests/test_fused_qknorm_nvfp4_prefill.py,python3 op_tests/test_fused_qknorm_idxrqknorm.py.PR Self-Review
Reviewed revision
e72ed2d9fBehavior and intent
Makes the NVFP4 K/V + index-cache insert of
fused_qknorm_idxrqknormcheaper for the MiniMax-M3 TP4 head set on gfx950 (decode-sized and prefill-sized token counts), with byte-identical outputs. The existing kernel waited on a chain of dependent loads, used compare / select chains for the NVFP4 converts andds_bpermutefor lane exchanges, and had no prefill-shaped variant.Validation and unverified scope
Commands and results are in the sections above and in the review-fix update (gfx950 MI355X): byte-for-byte test vs the torch reference at
atol=0, rtol=0, 506 prefill-vs-generic cases with 0 differences, kernel-name receipt, raw vs marshalled entry. Not verified: no end-to-end model run; other arches are only compile-checked (every gfx950-specific change is behind__gfx950__);test_fused_qknorm_idxrqknorm.pywas not re-run after the review fixes.PR-specific question
Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
gfx950 only (
get_gpu_arch()in C++,get_gfx_runtime()in the Python raw front). The raw front takes a call only for bf16qkvof shape[n, 2560](16 q / 1 kv / 1 index heads, head_dim 128, rotary 64), contiguous bf16 norm weights and cos/sin cache, int64 positions / slot mappings, uint8 NVFP4 pages with a 16 B aligned stride and base, fp8index_q_out, fp32 scales, all on the current device. The prefill variant needs 2 <= n <= 419430 tokens (floor fromAITER_FUSED_QKNORM_NVFP4_PREFILL_MIN_TOKENS, cap from the 32-bit buffer extent). Anything else declines to the unchanged generic path. The C++ entry itself re-checks onlynum_tokens >= 1and the device arch (AITER_CHECK); every other part of the contract above is validated solely by the Python gate, not re-checked in C++.Changed op tests
op_tests/test_fused_qknorm_nvfp4.py: byte-exact check of the NVFP4 insert against the torch reference (special scales, padded / skip layouts, seq / scatter / MTP slot patterns); extended with the REJECT case for a 4 B-aligned page stride. It is the canonical test of this op, so the case belongs here.op_tests/test_fused_qknorm_nvfp4_prefill.py: new: runs each case in two child processes (prefill forced on / off through the dispatch-floor variable) and compares digests of every output between the prefill variant, the generic kernel, the raw entry and the marshalled entry, plus the 419430 / 419431 boundary and the kernel-name receipt. The canonical test cannot force a dispatch floor per process, so it cannot show that the prefill kernel ran or that it matches the generic one.🤖 Generated with Claude Code