Skip to content

[HIP] [Perf] fused_qknorm_idxrqknorm: early loads, hardware converts, DPP exchanges, xor-atomic V nibbles and a prefill variant - #8472

Merged
junhaha666 merged 13 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/fused-qknorm-idxr-early-loads
Nov 27, 2026

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

  • Change: four commits in one HIP kernel family, fusedQKNormIdxrQKNormKernel of fused_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.
  • Why it is faster: fewer dependent load stages, hardware fp8 / fp4 converts instead of a compare / select chain per element, DPP instead of ds_bpermute, one atomicXor per V word instead of atomicAnd + atomicOr; the prefill variant runs one wave per head with cos/sin shared by token pairs; the raw entry skips pybind marshalling.
  • How much (MI355X gfx950, MiniMax-M3.1 TP4 head set, kernel level): changes 1+2 are -4.6% to -11.9% device time vs main at 8..8192 tokens (torch profiler, median of 200 launches); change 3 saves another 0.5 us (8 rows) to 2.0 us (384 rows); the prefill variant vs the generic kernel at 4096 / 32768 tokens is 26.34 -> 13.60 us / 164.08 -> 73.91 us (graph replay, median); host time per eager call is about 8.8-9.0 us through the raw entry vs 28.8-29.4 us through the old compile_ops wrapper (tables below).
  • End to end: not measured.
  • Stack order: merge this PR first. aiter [FlyDSL] [Perf] MiniMax-M3.1 TP4 decode QKV front as one op: one-launch (1-64 rows) + split-K (65-128 rows) GEMM / norm / RoPE / NVFP4 insert #8607 (QKV front) edits the same Python file and is rebased on top of it after it lands. ATOM does not need a change.

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) fusedQKNormIdxrQKNormKernel of fused_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.

  1. Early operand loads (625fe97a2): issue the row, slot_mapping, position, norm weight and cos/sin loads of a warp together instead of as a s_waitcnt vmcnt chain. Two load stages after the V branch instead of three.
  2. gfx950 hardware converts (408b6fdb7): the NVFP4 quantizer computes the e4m3 scale byte, its decoded value and the e2m1 codes with v_cvt_pk_fp8_f32, v_cvt_f32_fp8 and v_cvt_scalef32_pk_fp4_f32 instead of a compare / select chain per element. The torch reference in the test now states the NaN / infinity semantics.
  3. DPP exchanges, xor-atomic V nibbles, FMA reciprocal (fdec4e4cf): the norm sum, the amax butterfly and the RoPE partner exchange use DPP moves instead of ds_bpermute; the V nibble lands with one atomicXor of (old ^ new) << shift (disjoint bits, xors commute) instead of atomicAnd + atomicOr per word; the two __fdiv_rn(1, x) of nvQuantLane become v_rcp_f32 plus two FMA Newton steps (identical to __fdiv_rn for 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 for rotary_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):

tokens 8 32 64 256 512 4096 8192
change 1 vs main -1.1% -1.6% -1.5% -2.7% -6.6% -1.2% -1.5%
changes 1+2 vs main -10.6% -10.4% -10.6% -11.9% -7.4% -6.5% -4.6%

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

rows A this PR amd-kernels this - amd-kernels
8 4.22 3.73 2.77 +0.96
16 4.37 3.78 2.87 +0.91
64 4.80 4.05 3.39 +0.66
128 5.71 4.67 3.76 +0.91
288 7.01 5.13 4.21 +0.92
384 7.50 5.45 4.41 +1.04
512 8.52 6.23 4.47 +1.76

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

  • Output bytes (kv pages, index pages, q, index q) are identical between all three commits and to the amd-kernels kernel at every row count above.
  • 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 unchanged test_fused_qknorm_idxrqknorm.py (fp8 / mxfp4 / auto, per-token and static scales) pass; the nvfp4 test checks atol=0, rtol=0 against the torch reference including special global scales, padded / skip layouts, seq / scatter / MTP slot patterns.

Review

By hand against the repo review-pr rules 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 of fusedQKNormIdxrQKNormKernel for 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 for 2*tp tokens (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_TOKENS overrides 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):

tokens HIP, changes 1-3 this variant FlyDSL kernel of #8576
8 5.79 5.52 4.50
64 5.71 5.55 4.54
256 6.67 5.50 5.33
384 6.95 5.61 5.49
512 7.14 5.69 5.87
768 8.35 6.28 6.57
1024 10.40 6.84 7.22
2048 14.82 9.35 9.12
4096 26.34 13.60 12.85
8192 47.05 22.10 21.94
16384 85.92 36.66 40.55
32768 164.08 73.91 79.53

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_ops wrapper (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 except mxfp4_reject) exits 0 with 58 clean result rows; op_tests/test_fused_qknorm_nvfp4.py exits 0 with no new crash dump. New op_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 fe8ae8719 and e72ed2d9f):

  • The NVFP4 page stride and base must be 16 B aligned (the V side uses 16 B loads and 64-bit atomics): enforced in C++ (AITER_CHECK) and in the Python raw front; a 4 B-only layout is refused. New REJECT case "page stride 4 B aligned" in op_tests/test_fused_qknorm_nvfp4.py.
  • The prefill variant serves at most 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.
  • The raw front checks qkv.dim() == 2, declines while AITER_REBUILD has not been honoured by the wrapper, and declines for a loaded module without the raw symbol.
  • The prefill test takes a kernel-name receipt (torch profiler) at a fixed size of 2 tokens: the forced-prefill child must launch fusedNvfp4InsertPrefillKernel and the generic child must not.
  • The per-op architecture probe uses the shared 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.py exit 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); after e72ed2d9f: -n 1 8 --seeds 1 --kinds contig passes (4 cases, 0 differ) and a call with AITER_REBUILD=1 goes through the wrapper, which rebuilds module_fused_qknorm_idxrqknorm. The 58-row test_fused_qknorm_idxrqknorm.py run 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

e72ed2d9f

Behavior and intent

Makes the NVFP4 K/V + index-cache insert of fused_qknorm_idxrqknorm cheaper 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 and ds_bpermute for 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.py was 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 bf16 qkv of 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, fp8 index_q_out, fp32 scales, all on the current device. The prefill variant needs 2 <= n <= 419430 tokens (floor from AITER_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 only num_tokens >= 1 and 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

…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]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full 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 8472 --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.

…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]>
ganyi1996ppo pushed a commit to ganyi1996ppo/aiter that referenced this pull request Nov 23, 2026
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]>
@aiter-bot

aiter-bot commented Nov 25, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 6b5f781d0f21 · mode shadow

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

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents unsupported inputs from reaching it?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — validation answer must explicitly state what remains unverified (or say none with a reason)

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

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

Copilot AI balanced review requested due to automatic review settings November 25, 2026 03:51
@ganyi1996ppo ganyi1996ppo changed the title [HIP] [Perf] fused_qknorm_idxrqknorm: issue the row, slot_mapping and norm/rope operand loads up front [HIP] [Perf] fused_qknorm_idxrqknorm: early operand loads, gfx950 hardware converts, DPP exchanges and xor-atomic V nibbles Nov 25, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

A supported 4-byte-aligned page layout can trigger misaligned 64-bit atomics and 16-byte vector loads, requiring alignment-safe fallbacks and padded-page test coverage.

1 open issue

Review effort: Balanced

Comment thread csrc/kernels/fused_qknorm_idxrqknorm.cu Resolved
…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]>
@ganyi1996ppo ganyi1996ppo changed the title [HIP] [Perf] fused_qknorm_idxrqknorm: early operand loads, gfx950 hardware converts, DPP exchanges and xor-atomic V nibbles [HIP] [Perf] fused_qknorm_idxrqknorm: early loads, hardware converts, DPP exchanges, xor-atomic V nibbles and a prefill variant Nov 25, 2026
Copilot AI balanced review requested due to automatic review settings November 25, 2026 06:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Review effort: Balanced

Comment thread aiter/ops/fused_qknorm_idxrqknorm.py Resolved
Comment thread csrc/kernels/fused_qknorm_idxrqknorm.cu Resolved
Comment thread csrc/kernels/fused_qknorm_idxrqknorm.cu Resolved
Comment thread csrc/kernels/fused_qknorm_idxrqknorm.cu Resolved
ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 25, 2026
…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]>
ganyi1996ppo and others added 2 commits November 25, 2026 18:58
… 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]>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 01:26
Copilot AI balanced review requested due to automatic review settings November 26, 2026 09:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Comment thread op_tests/test_fused_qknorm_nvfp4.py Resolved
…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]>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 09:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because an unpublished critical finding indicates that 64-bit slot truncation can corrupt cache data or skip valid slots.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@junhaha666

Copy link
Copy Markdown
Contributor

@ganyi1996ppo The prefill path truncates slot_mapping and index_slot_mapping to 32 bits (fused_qknorm_idxrqknorm.cu:1507,1646), changing the existing slot < 0 skip behavior.

On gfx950 at b182ae9c2, I reproduced this with int64 slots [-4294967295, -4294967294]: the generic kernel leaves both caches unchanged, while the prefill kernel treats them as slots [1, 2], modifying 399 KV-cache bytes and 144 index-cache bytes.

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]>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 03:18
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

@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 slot < 0 behavior in both sites:

  • K / index-K slot load (:1507): the uint4 already loads both 32-bit words of each int64, so slot_t[t] = (hi < 0) ? -1 : lo (no extra loads).
  • V-run detection (:1646): reads the full int64 and forces a = -1 when it is negative, so negative slots neither start nor continue a V run and the slot >= 0 write guard skips them. a stays a 32-bit low word for the DPP exchange, so the valid-slot path is unchanged.

Verified on gfx950: your exact case [-4294967295, -4294967294] now leaves both caches byte-identical to the generic kernel (0 bytes changed), and I added a regression test (test_bigneg_slots_skipped) that asserts prefill == generic on large-magnitude negative slots (incl. -1). The valid-slot fast path is unchanged (prefill-vs-generic grid 114/114 identical, nvfp4 byte-exact test passes). Please re-check when you have a moment.

@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

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 slot_mapping / index_slot_mapping entry (fused_qknorm_idxrqknorm.cu:1507 and :1646), which dropped the sign for negative slots of magnitude >= 2^32 and wrote them as valid slots. Both sites now preserve the generic kernel's slot < 0 skip semantics:

  • :1507: slot_t[t] = (hi < 0) ? -1 : lo using the high word already loaded by the uint4.
  • :1646: the full int64 is read and a is forced to -1 when negative, so negative slots are excluded from V-run detection and the slot >= 0 write guard; a remains a 32-bit low word for the DPP exchange.

Valid (small non-negative) slots are bit-identical to before. New regression test test_bigneg_slots_skipped asserts prefill == generic on large-magnitude negative slots; verified on gfx950 (0 bytes changed on [-4294967295, -4294967294], prefill-vs-generic grid 114/114 identical, nvfp4 byte-exact test passes).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The standalone test entry point omits the large-negative-slot regression, leaving CI unable to detect a reversion of the int64 sign checks.

1 open issue

Review effort: Balanced

junhaha666
junhaha666 previously approved these changes Nov 27, 2026
… 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]>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 03:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

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

@junhaha666
junhaha666 merged commit f70ac7f into ROCm:main Nov 27, 2026
95 of 108 checks passed
ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 27, 2026
…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]>
ganyi1996ppo added a commit to ganyi1996ppo/aiter that referenced this pull request Nov 27, 2026
….py — ROCm#8472 file + qkv-front hook, deferred-front before _nvfp4_raw_front

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ganyi1996ppo added a commit that referenced this pull request Nov 30, 2026
…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]>
lirui927 pushed a commit to lirui927/aiter that referenced this pull request Nov 30, 2026
…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]>
lirui927 pushed a commit to lirui927/aiter that referenced this pull request Nov 30, 2026
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]>
XiaobingSuper pushed a commit to XiaobingSuper/aiter that referenced this pull request Dec 3, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants