Skip to content

[HIP] [Perf] fused_qknorm_idxrqknorm: DPP lane exchanges, xor-atomic V nibbles, FMA reciprocal (stacked on #8473) - #8580

Closed
ganyi1996ppo wants to merge 3 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/fused-qknorm-idxr-dpp-xor-v
Closed

ganyi1996ppo wants to merge 3 commits into
ROCm:mainfrom
ganyi1996ppo:ganyi/fused-qknorm-idxr-dpp-xor-v

Conversation

@ganyi1996ppo

@ganyi1996ppo ganyi1996ppo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stacked on #8473 (which is stacked on #8472): the first two commits of this branch are those PRs, review the top commit only; the diff shrinks as they land.

fused_qknorm_idxrqknorm, NVFP4 insert (gfx950, MiniMax-M3 decode rows 8..512): remove the remaining serial latency of the kernel with three changes, all bit-identical.

  • Lane exchanges: the norm sum, the amax butterfly (4-lane groups) and the RoPE partner exchange used __shfl_xor / __shfl, i.e. ds_bpermute (an LDS round trip each). On gfx950 xor-1/2/4/8 are DPP moves (quad_perm, row_shr/row_shl, row_ror:8) and xor-16 is v_permlane16_swap (inline asm: the two-result builtin is folded to one register by the compiler; s_nop 1 around it). Same lane map, same summation order as warpReduceSum (16, 8, 4, 2, 1).
  • V nibble: the V store landed a token's nibble with atomicAnd + atomicOr per word (8 atomics per lane). The token's nibble is written by that token only, so one atomicXor of (old ^ new) << shift lands it without touching the other tokens' nibbles of the octet (disjoint bits, xors commute): two 64-bit atomics per lane. old is a plain uint4 load issued before the quantization, only its own nibble is used.
  • Reciprocals: the two __fdiv_rn(1, x) of nvQuantLane (about 25 instructions each with denormal-mode switching) become v_rcp_f32 plus two FMA Newton steps (rcpRN). Identical to __fdiv_rn(1, d) for every positive normal fp32 (all 2^31 patterns, exhaustive on MI355X, 0 mismatches); outside [2^-100, 2^100] and for 0 / inf / nan it falls back to __fdiv_rn.

All three are gated on __gfx950__; every other arch compiles to the previous code. The DPP rope partner is used for rotary_dim == 64 (partner == lane ^ 8), other rotary dims keep __shfl.

Motivation / known regression (stated on purpose)

The point is to run the MiniMax-M3.1 TP4 decode on aiter alone (no amd-kernels norm_rope_nvfp4_insert). This kernel does not reach the amd-kernels one: it is still about +1.0 us per call slower (table below), which is about 60 sparse layers x 1.0-1.1 us = 0.06-0.07 ms per decode step, about 0.2-0.3% of a 28.95 ms G64 step. That regression was reviewed and accepted by the owner in exchange for dropping the amd-kernels dependency. Public ATOM already calls aiter.fused_qknorm_idxrqknorm for this insert (atom/model_ops/attention_mha.py), so no ATOM change is needed; this PR only makes that call faster.

Tried and not included: reordering / pinning the kernel arguments in SGPRs (the serial s_load chain), no change (3.78 vs 3.77 us at M=8); a V "run writer" without atomics, slower below about 200 rows.

Results (MI355X, gfx950, ROCm 7.2.4; graph replay of 64 distinct inserts, event timing, us per call)

Each cell is the median of 4 alternating rounds (A, B, C order repeated twice in one lease on one GPU). A = #8473 head, this PR = A + top commit, amd-kernels = norm_rope_nvfp4_insert_d128_rot64_p128. TP4 head set (16 q, 1 kv, 1 index head, head_dim 128, rotary 64), bf16, random qkv x3, scattered positions.

rows #8473 (A) this PR amd-kernels this PR - 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
1024 13.3 10.2 6.05 +4.2
4096 32.6 25.6 13.3 +12.3

(1024 rows and above are prefill chunks; >= 1024 tokens go to the FlyDSL kernel of #8576 on the TP4 head set.) Versus #8473 the top commit saves 0.5 us at 8 rows to 2.0 us at 384 rows.

Correctness

  • Output bytes (kv pages, index pages, q, index q) are identical to the amd-kernels kernel and to [HIP] [Perf] fused_qknorm_idxrqknorm: nvfp4 quantizer on the gfx950 fp8 / fp4 converts (stacked on #8472) #8473 at every row count above (bit-identical: True in all 18 comparisons per arm).
  • op_tests/test_fused_qknorm_nvfp4.py (unchanged): 912 checks pass (atol=0, rtol=0 against the torch reference incl. special global scales, padded / skip layouts, seq / scatter / MTP slot patterns, refusals), exit 0; same on [HIP] [Perf] fused_qknorm_idxrqknorm: nvfp4 quantizer on the gfx950 fp8 / fp4 converts (stacked on #8472) #8473 for comparison. This covers the MXFP4 / fp8 modes that share normAndRope.
  • Reciprocal: exhaustive over the 2^31 positive normal fp32 patterns (standalone harness, not committed), 0 mismatches vs __fdiv_rn(1, x).
  • Assumption stated in the code: a slot is written once per call (the xor lands the nibble delta against the old value; a duplicated slot within one call would leave an unspecified value in that one nibble, as the and/or version left an unspecified one of the two).
  • Not run: gfx942 / gfx1250 (their code path is the previous one, selected at compile time).

Reproduce: ARMS=ak,ai MS=8,16,64,128,288,384,512,1024,4096 python3 mb.py style harness (graph of 64 inserts, event timing) on one idle MI355X; python3 op_tests/test_fused_qknorm_nvfp4.py.

Review

Run by hand through the repo's review-pr skill (triage rules A1 A4 B2 C1 C2 D1 D8 P1-P3 P5 P6): no sibling variant carries a changed line, no guard removed; A4 (shared normAndRope / quantizer code executed by every mode): covered by the unchanged op test above plus bit-compare vs the previous kernel; D1: the xor depends on the old word but only on its own nibble (stale or uninitialized pages are fine); P6: measured base vs head back to back on one GPU (table above). Findings fixed before opening: DPP and rcpRN first gated on __GFX9__ / ungated, now gfx950 only since only gfx950 was tested; rope DPP restricted to rotary_dim == 64; kernel-argument pinning and a QKDBG debug hook from the experiments removed.

Technique credit: amd-kernels norm_rope_nvfp4_insert (DPP / permlane exchanges, run-wise V write idea).

🤖 Generated with Claude Code

ganyi1996ppo and others added 3 commits November 22, 2026 21:06
…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]>
…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]>
…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]>
@ganyi1996ppo
ganyi1996ppo requested review from a team and a balanced review from Copilot November 24, 2026 14:05
@github-actions github-actions Bot added the HIP label Nov 24, 2026
@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 8580 --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.

@aiter-bot

aiter-bot commented Nov 24, 2026 •

Copy link
Copy Markdown

DRAFT — evaluation paused

PR Self-Review

Revision fdec4e4cfccf · mode shadow

This pull request is a draft, so readiness evaluation is paused and no verdict applies. Evaluation resumes when it is marked ready for review and the required CI completes.

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

Accepted 4-byte-aligned cache layouts can reach wide loads and atomics that require stricter alignment, causing undefined behavior without a 32-bit fallback.

1 open issue
What changed in this PR

This PR reduces latency in aiter’s HIP fused Q/K normalization, RoPE, and NVFP4 cache-insert kernel for gfx950 decode workloads. It builds on #8472 and #8473, aiming to preserve output bytes while reducing instruction and memory-access costs.

Changes:

  • Replaces selected lane shuffles with faster gfx950 lane-exchange instructions.
  • Combines V-cache nibble updates into two 64-bit XOR atomics per lane.
  • Uses a refined reciprocal fast path with division fallback for exceptional values.
File Description
op_tests/​test_fused_qknorm_nvfp4.py Inherited from #8473: expands special-value reference behavior and extreme-scale coverage.
csrc/​kernels/​fused_qknorm_idxrqknorm.cu Adds lane-exchange, V-write, and reciprocal optimizations atop the stacked kernel changes.
aiter/​ops/​fused_qknorm_idxrqknorm.py Comment-only changes inherited from #8473 clarify positive scales and hardware rounding.

Review effort: Balanced

Comment on lines +644 to +661
const uint4 old = *reinterpret_cast<const uint4*>(words); // in flight during the quantization
float v[kElemsPerLane];
loadElems(row, v);
uint32_t packed;
const uint32_t sb = nvQuantLane(v, gs, packed);
// The nibble of token `pos` is written by this token only (a slot is written once per call), so
// one xor of (old ^ new) << shift per word lands it without disturbing the other tokens'
// nibbles of the octet (they flip disjoint bits, and xors commute): two 64-bit atomics per lane
// instead of 4 x (and + or). `old` is a plain load issued before the quantization; only its own
// nibble is used, and no other token changes that nibble.
const uint32_t d0 = ((((old.x >> shift) ^ (packed >> 0)) & 0xFu) << shift);
const uint32_t d1 = ((((old.y >> shift) ^ (packed >> 4)) & 0xFu) << shift);
const uint32_t d2 = ((((old.z >> shift) ^ (packed >> 8)) & 0xFu) << shift);
const uint32_t d3 = ((((old.w >> shift) ^ (packed >> 12)) & 0xFu) << shift);
using u64 = unsigned long long;
u64* w64 = reinterpret_cast<u64*>(words);
atomicXor(w64, static_cast<u64>(d0) | (static_cast<u64>(d1) << 32));
atomicXor(w64 + 1, static_cast<u64>(d2) | (static_cast<u64>(d3) << 32));
@ganyi1996ppo

Copy link
Copy Markdown
Contributor Author

Merged into #8472 (same kernel, now three commits on one branch). Closing in favour of #8472.

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