Skip to content

[ASM] [HIP] Mha v4: gfx950 hd256 mxfp4/6 kernels with per-batch seqlens_k - #7173

Merged
JohnNikolay84 merged 17 commits into
mainfrom
mha4_hd256_mxfp4
Nov 3, 2026
Merged

JohnNikolay84 merged 17 commits into
mainfrom
mha4_hd256_mxfp4

Conversation

@jcaraban

@jcaraban jcaraban commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds gfx950 hd256 MXFP4 and MXFP6 attention to MHA v4, with per-batch seqlens_k, LSE and fullgraph-compatible producers.

Motivation

Ideogram 4 uses 256-wide heads, which previously had no MHA v4 object. MXFP4 minimizes register pressure; MXFP6 offers higher accuracy and retains the 256x64 tile by sharing the V operand ring with K registers.

Changes

  • Adds fwd_hd256_mxfp4.co, fwd_hd256_mxfp6.co and manifest rows; other recipes remain hd128-only.
  • Packs hd256 K/V directly from [b, s, 2h, 128] views, avoiding an intermediate permutation. MXFP6 reuses the hd128 K and FP6-P V HIP packers with head_split=2; the default 1 preserves hd128 output.
  • Adds custom-op Q/K/V producers for fullgraph tracing.
  • Shares the (Q/K, V) head-dim gate between mha_v4 and mha_v4_packed, and selects MX producers through mha_v4_mx_producers. Sparse and mixed-format hd256 requests raise ValueError before quantization rather than failing in find_config.

Performance

Measured on 1x MI355X. Kernel measurements use stacked #7174 for hd256 producer routing. In the model comparison, only the attention backend changes; FP4 GEMMs and torch compilation are enabled in both arms.

Workload/configuration Before After Change
bench_sage --kernel mha4_mxfp4 --d 256 --dv 256, peak over swept shapes No hd256 object 5000 TFLOPS New row
bench_sage --kernel mha4_mxfp6 --d 256 --dv 256 --b 1 --hq 5 --hk 5 --sq 65536 --sk 65536 No hd256 object 4321 TFLOPS kernel; 4047 TFLOPS --e2e New row
hd256 MXFP6 K+V packing, b1 h18 s16384 538 us: hd128 pack + permutation 154 us: head_split=2 -71%
Ideogram 4 (ideogram-ai/ideogram-4-fp8), 2048x2048, 48 steps, --use_fp4_gemms --use_torch_compile; SDPA vs AITER_MXFP4 46.89 s 18.73 s -60%

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

Documentation

  • Docstrings updated
  • User guide updated: mha_v4.md covers hd256, the MXFP6 record layout and script-mode testing.

Dependencies

  • No new third-party dependencies added

Breaking Changes

None. Rows and producers are additive; head_split defaults to the existing behavior. Unsupported head dimensions now raise ValueError before quantization instead of a launcher error.

PR Self-Review

Reviewed revision

3994ef3e9

Behavior and intent

The new rows enable quantized attention for 256-wide heads without changing existing recipes. Dispatch accepts dense all-MXFP4 or all-MXFP6 hd256 inputs and rejects unsupported combinations explicitly.

Validation and unverified scope

On gfx950 (MI355X):

  • e5a2dd8ed: python3 op_tests/test_mha_v4.py ran 235 checks, 0 skipped, 7 failed. All failures are test_mha_v4_mxfp8_{q,k}_matches_unfused_pipeline: their Triton MXFP8 reference fails to compile with local Triton 3.5.1, identically on base. At 2605a277b, the suite ran 230 checks with 0 skipped and 0 failed.
  • e5a2dd8ed: python3 op_tests/test_mha_v4_sparse.py ran 160 checks, 1 skipped, 0 failed.
  • 3994ef3e9: python3 op_tests/test_mha_v4.py --head-dim 128 256 benchmarks both hd256 MXFP6 and MXFP4, reporting err 0 at sk 1024 and 4096. Checks: 235 ran, with the same 7 MXFP8 failures.
  • MXFP6 hd256 packing matches permuted hd128 output bitwise on five ragged shapes; hd128 output matches the base module byte-for-byte on the same shapes. MXFP6 hd256 cosine against fp64 attention is approximately 0.998, matching hd128 in the same harness; repeated launches are bitwise identical.
  • Model E2E: xdit --model ideogram-ai/ideogram-4-fp8 --use_torch_compile --use_fp4_gemms --attention_backend AITER_MXFP4 --height 2048 --width 2048 took 18.73 s. LoadKernel: _ZN5aiter28fmha_fwd_hd256_mxfp4_gfx950E confirms the only FMHA object loaded. This result is from 2605a277b, not rerun for the MXFP6 addition at e5a2dd8ed; the MXFP4 object and producers are unchanged there.

Unverified: no hd256 MXFP6 model E2E or MI250X/MI300X run. The new kernels and their checks are gfx950-only, so those GPUs exercise none of this path.

PR-specific question

Dispatch and ABI: gfx950 manifest rows select dense hd256 all-MXFP4 or all-MXFP6 inputs; the shared Python gate rejects other combinations. Both objects use the existing v4 kernarg layout, including seqlens_k at 0x1C0. No field is added, moved or resized; existing objects remain loadable without host changes.

Binary provenance: both objects under hsa/gfx950/fmha_v4_fwd/ are generated by PyISA from the internal kernel repository, as with existing hsa/ objects. Sources are asm/fmha_sage_fwd/gfx950/mi350_fmha_hd256_mxfp4.py (at the revision adding per-batch seqlens_k) and asm/fmha_sage_fwd/gfx950/mi350_fmha_hd256_mxfp6.py; generator sources are not public. Both use 0 AGPR, 90 SGPR and 512-thread workgroups.

Object Bytes MD5 VGPR LDS bytes
fwd_hd256_mxfp4.co 48568 e8c085fcff95bcc4022b10e0f0e42bfa 256 53248
fwd_hd256_mxfp6.co 52296 f9b6e170d4c8285b37ee5d5e490f02fb 244 75776

Changed op tests

Only op_tests/test_mha_v4.py changes:

  • benchmark_mha_v4: includes both hd256 MXFP6 and MXFP4 in the --head-dim benchmark, previously MXFP4-only.
  • test_mha_v4_mx_hd256_matches_attention: checks both formats against torch attention across shapes.
  • test_mha_v4_mxfp4_hd256_gqa_matches_repeated_kv: checks unequal-head mapping, which equal-head dense tests cannot detect.
  • test_mha_v4_rejects_non_mx_head_dim_256, test_mha_v4_rejects_mixed_mxfp6_head_dim_256, test_mha_v4_rejects_sparse_head_dim_256: require unsupported hd256 combinations to raise; each fails with the head-dim gate stubbed out.
  • test_mha_v4_mx_hd256_seqlens_k_matches_truncated_kv: compares both formats bitwise against physically truncated K/V. MXFP4's approximately 0.978 cosine against torch is too loose to detect this bug.
  • test_mha_v4_mx_hd256_lse_tracks_hd128: checks both formats' LSE epilogues; _LSE_CAPABLE_QV has no head-dim key and output tests never read LSE.
  • test_mha_v4_lse_capable_rows_load_the_lse_kernarg: verifies every claimed object's LSE kernarg load; rejects a pre-LSE object, mirroring the existing varlen guard.
  • test_mha_v4_mx_hd256_compile_parity: exercises fullgraph tracing and the first hd256 out= coverage for both formats.
  • test_mha_v4_quantized_tolerates_k_common_mode / test_mha_v4_lse_survives_k_common_mode: add hd256 MXFP4/MXFP6 with nonzero K means, unlike the other randn checks whose smoothing gate stays closed. Swapping mean halves fails both MXFP4 checks: output error ratio 16.7 and LSE +86 nats, versus limits 1.5 and +0.5.

@jcaraban
jcaraban requested a review from a team October 29, 2026 19:53
@github-actions

This comment was marked as spam.

@github-actions github-actions Bot changed the title Mha v4: gfx950 hd256 MXFP4 kernel with per-batch seqlens_k [Triton/Gluon] [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 kernel with per-batch seqlens_k Oct 29, 2026
@aiter-bot

aiter-bot commented Oct 29, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision f92f1bb5fca7 · 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

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

@github-actions github-actions Bot changed the title [Triton/Gluon] [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 kernel with per-batch seqlens_k [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 kernel with per-batch seqlens_k Oct 29, 2026
@jcaraban
jcaraban added this pull request to stack #7175 October 29, 2026 20:29
@zufayu
zufayu requested a review from shay-li77 October 30, 2026 01:25
@jcaraban

Copy link
Copy Markdown
Contributor Author

@shay-li77 the failed job is unrelated to this PR, please let me know how to proceed

@jcaraban jcaraban changed the title [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 kernel with per-batch seqlens_k [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 and MXFP6 kernels with per-batch seqlens_k Nov 2, 2026
@jcaraban jcaraban changed the title [ASM] [HIP] Mha v4: gfx950 hd256 MXFP4 and MXFP6 kernels with per-batch seqlens_k [ASM] [HIP] Mha v4: gfx950 hd256 mxfp4/6 kernels with per-batch seqlens_k Nov 2, 2026
JohnNikolay84
JohnNikolay84 previously approved these changes Nov 2, 2026
First head dim past 128 in this family. The ASM kernel halves the KV tile to 64
because the O accumulator doubles to 128 VGPRs and a 512-thread workgroup caps
arch+acc at 256.

No new HIP quantizers: the hd256 producers run the existing hd128 ones on a
[b, s, 2h, 128] view and permute, because every hd256 layout is a permutation of
the hd128 one -- both tile the same 16-byte lane slots, 128 tokens by 4 chunks
against 64 by 8. Verified byte-exact for Q/K/V data and scales. The Hadamard is
then block-diagonal over the two halves, still orthogonal, so Q.K^T is unchanged.

The head dim becomes data rather than a constant. V is the only operand carrying
it in its last axis, so it names the dim and everything else derives: the packed
Q/K width scales the hd128 row linearly, mxfp4_k_view/mxfp4_v_view read it off
the descale shape (one E8M0 per 32 elements), and the launcher threads
shapes.head_dim into find_config and the kernarg. hd128 behaviour is unchanged
by construction -- every derived value evaluates to its old constant there.

Note for anyone extending this: the MXFP4 producers tile 128 tokens whatever KV
tile the kernel runs, so the K backing stride and the V scale image follow the
PRODUCER, not cfg.ts_kv.

gfx950, b=1 h=5, kernel-only through mha_v4_packed, against hd128 MXFP4:
  s=4096   1693 vs 1498 TFLOP/s  (+13.0%)
  s=8192   3652 vs 3082 TFLOP/s  (+18.5%)
  s=16384  3573 vs 3278 TFLOP/s  (+9.0%)
Cosine against bf16 attention 0.980 at hd256 vs 0.979 at hd128 on identical
inputs. test_mha_v4 covers aligned, partial-KV, multi-head and GQA shapes plus
the non-MXFP4 rejection; benchmark_mha_v4 gains a --head-dim sweep axis.

Sparse is not supported at hd256 and find_config reports that rather than
falling back to an hd128 object.

Signed-off-by: jcaraban <[email protected]>
The three hd256 producers allocate buffers larger than their logical extent:
the Q and K scale images carry the gather padding the kernel's speculative
tile read needs, and the V data buffer carries the half-row overhang that
mxfp4_v_view's last element reaches into. As plain functions they inlined
into a compiled graph, which then shrank each allocation to what the traced
code reads, and the kernel gathered past the end:

  MX V descale needs 148480 mapped bytes so the kernel's speculative tile
  gather stays in bounds, but only 147456 are backed

Eager was unaffected at every shape, so this only showed up under
--use_torch_compile. Wrapping them as custom ops restores the graph boundary
their hd128 counterparts already have. Each gets a register_fake that
reproduces the padding; _mxfp4_v_hd256_sizes is shared by the real op and its
fake so the two cannot drift. Verified against the real ops under
FakeTensorMode on shape, dtype and untyped_storage().nbytes() across seven
shapes including ragged sequence lengths.

Also split the hd128/hd256 BSHD validation messages so a contiguous d=256
input no longer reports a contiguity error.

bench_sage: dispatch the MXFP4 producer trio on head dim so --d 256 works,
and add an aiter_fp8 kernel so the hd256 FP8 path is benchmarkable alongside
it. Recipes that are hd128-only now SKIP with a reason under --kernel all.

Ideogram-4 at 2048x2048, 48 steps, one MI350: 19.45s with the hd256 MXFP4
attention backend against 25.74s for hd256 FP8.

Signed-off-by: jcaraban <[email protected]>
hd256 reused the hd128 packers on a [b, s, 2h, 128] view and then permuted the
result into the tile order its code object reads. That permute was a second
full pass over K and V, and it had grown to cost about as much as the pack
itself: at b1 h18 s16384, K was 0.056ms of pack behind 0.064ms of permute and
V 0.072ms behind 0.076ms.

The packers now take `head_split`, which splits the head axis into
(heads / head_split, head_split) and places the inner index inside the tile
axis. hd128 passes 1 and is bit-identical to before; hd256 runs as 2h
half-heads and passes 2, so the producers allocate and pack straight into the
final layout with no permute.

The ordering is not a plain (tile, half) nesting, which is worth stating
because it is easy to assume and silently wrong. Inside the 16KB two-tile
group the order is (token_half, half, channel), so the token half sits
OUTSIDE the head half and each kernel rebuilds its own within-group offset
rather than scaling one head_tile index. K's scale needs no remap at all: it
is row-major over (batch, token, head', block) and hd128's image is already
hd256's under a reshape. V's scale shares V's data anchor and does.

Two out/scale numel checks in quantize_v_mxfp4_impl relax from == to >=: the
hd256 caller owns a longer buffer carrying its own gather slack, and the
kernel only ever writes inside the exact region.

Verified bit-identical to the permute path on eight shapes including ragged
sequence lengths, and fake-vs-real metadata still matches on shape, dtype and
untyped_storage().nbytes(). K+V producer time drops 42% at s=1024 and 57% at
s=65536. Ideogram-4 2048x2048, 48 steps, one MI350: 19.45s -> 18.75s for a
byte-identical image.

bench_sage: drop aiter_fp8 from --kernel all; select it explicitly.

Signed-off-by: jcaraban <[email protected]>
_VARLEN_CAPABLE_QV is keyed on (q_format, v_format) alone, so (MXFP4, MXFP4) already claimed
varlen support and the hd256 object inherited that claim the moment its manifest row landed,
while it never read the kernarg. Rebuilt with the hd128 mechanism: the pointer parks in s58,
which the dense path leaves unused, and the override is emitted after every base address --
kv_seq_len also strides the MX scale slices, so shrinking it earlier relocates each batch's
scale base and leaves batch 0 right and batches 1+ wrong.

hd256's scale geometry is its own: the host V-scale image is 1024 bytes per 128-token tile,
not hd128's 512. init_Kscale_srd sets num_records rather than a base, so it correctly runs
after the override with the per-batch length.

Dense gains 9 instructions, sparse assembly is unchanged, 256 VGPR / 90 SGPR as before.
Every batch is bitwise identical to the same kernel on physically truncated K/V across five
shapes; the pre-fix object falls to 0.286 cosine on the same comparison.
The varlen-object guard searched the disassembly for the literal, which also appears as an
ordinary VALU immediate: fwd_hd256_mxfp4.co carried v_add_u32 v242, 0x1c0, v68 and passed
while never reading the kernarg at all. That is the exact substitution the check exists to
catch, so it was reporting all rows clean with one of them silently ignoring seqlens_k.

Verified by pointing the tightened guard at the pre-fix object, which it now names.
_LSE_CAPABLE_QV is keyed on (q_format, v_format) with no head-dim term, so adding the hd256 MXFP4
row made return_lse reachable on an object whose epilogue had never been compared against anything.
It is correct today; nothing held it there.

Bounds the relative error absolutely and against hd128. The absolute bound separates a real LSE
from a buffer that was never written; the hd128 comparison is what a constant cannot do, since the
residual is MXFP4 quantization rather than the epilogue.

Fault injection confirms both legs: zeros, 1e4 and NaN are each caught whether they are applied to
hd256 alone or to both head dims.
_LSE_CAPABLE_QV has the same hole the varlen gate had: keyed on (q_format, v_format) alone, so a
pair that gains a second object inherits the claim without being rebuilt. O never reads LSE, so
every output test keeps passing while the returned LSE is whatever the buffer held. Only the
emitted object can refute it.

Matched on the kernarg load rather than a bare literal, which is what let an object slip through
the varlen gate. Calibrated against the pre-LSE build of fwd_hd128_fp8 from 910e740: it reads
neither 0x40 nor 0x100, and swapping it in makes this check fail.

All 11 currently claimed dense rows pass.
This branch made the hd256 producers custom ops so the path could be traced, and nothing exercised
that. hd256 reaches its quantizers through a separate trio rather than a head-dim argument, so the
hd128 parity checks cover none of it.

Also the first hd256 coverage of out=, which the existing parity tests already assert aliasing for.

Replacing one producer with an untraceable callable makes the check fail, so it is testing the
schemas rather than just running the kernel twice.
… point

Scope said head dimension 128 only. Adds the hd256 row's limits (MXFP4, dense, GFX950) and its
V buffer sizing. Also replaces `pytest op_tests/test_mha_v4.py`: the file has run as a script
since its pytest dependency was dropped, and CI invokes it that way.
hd256 feeds K and its mean through a [B, S, 2H, 128] half-head view, and every hd256 check used
randn K, where the smoothing gate stays closed and the mean is zero. A misaligned mean would pass
all of them. Both common-mode checks now take a head_dim and gain an MXFP4 hd256 row; they drive
the public API, so they keep their meaning when the hd256 tile geometry changes.

hd256 margins match hd128's: output ratio 1.000 (limit 1.5), LSE drift +0.108 nats (limit +0.5).
Swapping the mean halves fails both rows (ratio 16.7, +86 nats), as does dropping the mean
(ratio 12.0, +66 nats).
Dense all-MXFP6 row at head dim 256: 256Q x 64KV tile in 244 VGPRs, with the
V operand ring sharing registers with the two K operand banks. Each 64-token
K record (13,312 B) carries its K-scale tail. Its FP6-P block scale rounds the
block max before taking the exponent, so a max that rounds to 8 no longer
saturates at 7.5.

The hd128 MXFP6 K and FP6-P V packers take head_split=2 and write the hd256
records straight from a [b, s, 2h, 128] view. hd128 output is unchanged, and
hd256 is bit-identical to permuting the hd128 records on five ragged shapes.
K+V pack at b1 h18 s16384: 154 us vs 538 us for pack-then-permute.

LSE and per-batch key lengths are enabled and checked like hd256 MXFP4.
b1 h5 s65536 on MI355X: 4321 TFLOPS (hd256 MXFP4 5043, hd128 MXFP6 ~4000);
cosine vs fp64 attention ~0.998.

Signed-off-by: jcaraban <[email protected]>
Head-dim support was decided in three places with three different rules: the
raw input check, a recipe-kind test in mha_v4, and a Q-format test in
mha_v4_packed that let unsupported V formats through to find_config. One
_check_head_dim over (Q/K format, V format) pairs now serves both entry
points, and rejects sparse at hd256 up front since no hd256 sparse row exists.

The MXFP4 and MXFP6 raw paths pick their (Q, K, FP6-P V) quantizers from
mha_v4_mx_producers instead of per-branch head-dim switches; it is public so
benchmarks select the same producers. The MXFP6 launcher derives the head dim
from Q's FP6 packed width, since an MXFP4 V arrives as a flat buffer.

test_mha_v4: 235 ran, 7 failed (the MXFP8 unfused-pipeline checks, which fail
the same way on the base tree under Triton 3.5.1); sparse: 160 ran, 0 failed.
Each head-dim rejection check fails with _check_head_dim stubbed out.

Signed-off-by: jcaraban <[email protected]>
--head-dim 256 kept only the mxfp4 recipe, so the hd256 MXFP6 row was never benchmarked.
At sk 1024/4096 both hd256 rows pass with err 0.

Signed-off-by: jcaraban <[email protected]>
Both formats bit-exact vs repeated KV on gfx950; a wrong head mapping
(repeat vs repeat_interleave) breaks equality (max diff 0.77).
ROCm 7.2 allocates v_cvt_scalef32_2xpk16_fp6_f32's result over its source tuple; in the fused
MXFP6 K packer that corrupted byte 3 of every 16-byte C0 chunk (CI's 32 FP6 failures). An
early-clobber inline-asm wrapper keeps them disjoint. With the CI compiler: sparse 160/0 failed,
dense FP6 0 failed; unfixed reproduces CI's 5 + 27 failures.
@JohnNikolay84
JohnNikolay84 self-requested a review November 3, 2026 11:56
@JohnNikolay84
JohnNikolay84 merged commit 6a4fa17 into main Nov 3, 2026
@JohnNikolay84
JohnNikolay84 deleted the mha4_hd256_mxfp4 branch November 3, 2026 11:57
jcaraban added a commit that referenced this pull request Nov 4, 2026
…oducers (#7174)

Routes bench_sage to the hd256 MXFP4/MXFP6 producers from #7173 and adds an aiter_fp8 comparator using FMHA v3 per-tensor FP8.

Signed-off-by: jcaraban <[email protected]>
jcaraban added a commit that referenced this pull request Nov 16, 2026
Adds the gfx950 hd256 MXFP8 recipe next to hd256 MXFP4/MXFP6 (#7173). Also regenerates all three hd256 objects (MXFP4, MXFP6, MXFP8), with the same symbols and kernargs and fewer registers. MXFP4 also rounds the FP6 P block max into the next binade before taking its E8M0 exponent, so a max with a bf16 mantissa >= 120/128 no longer saturates E2M3. MXFP6 and MXFP8 output is bitwise unchanged.
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
…ns_k (ROCm#7173)

* mha_v4: add the gfx950 hd256 MXFP4 kernel

First head dim past 128 in this family. The ASM kernel halves the KV tile to 64
because the O accumulator doubles to 128 VGPRs and a 512-thread workgroup caps
arch+acc at 256.

No new HIP quantizers: the hd256 producers run the existing hd128 ones on a
[b, s, 2h, 128] view and permute, because every hd256 layout is a permutation of
the hd128 one -- both tile the same 16-byte lane slots, 128 tokens by 4 chunks
against 64 by 8. Verified byte-exact for Q/K/V data and scales. The Hadamard is
then block-diagonal over the two halves, still orthogonal, so Q.K^T is unchanged.

The head dim becomes data rather than a constant. V is the only operand carrying
it in its last axis, so it names the dim and everything else derives: the packed
Q/K width scales the hd128 row linearly, mxfp4_k_view/mxfp4_v_view read it off
the descale shape (one E8M0 per 32 elements), and the launcher threads
shapes.head_dim into find_config and the kernarg. hd128 behaviour is unchanged
by construction -- every derived value evaluates to its old constant there.

Note for anyone extending this: the MXFP4 producers tile 128 tokens whatever KV
tile the kernel runs, so the K backing stride and the V scale image follow the
PRODUCER, not cfg.ts_kv.

gfx950, b=1 h=5, kernel-only through mha_v4_packed, against hd128 MXFP4:
  s=4096   1693 vs 1498 TFLOP/s  (+13.0%)
  s=8192   3652 vs 3082 TFLOP/s  (+18.5%)
  s=16384  3573 vs 3278 TFLOP/s  (+9.0%)
Cosine against bf16 attention 0.980 at hd256 vs 0.979 at hd128 on identical
inputs. test_mha_v4 covers aligned, partial-KV, multi-head and GQA shapes plus
the non-MXFP4 rejection; benchmark_mha_v4 gains a --head-dim sweep axis.

Sparse is not supported at hd256 and find_config reports that rather than
falling back to an hd128 object.

Signed-off-by: jcaraban <[email protected]>

* mha_v4: make the hd256 MXFP4 producers custom ops

The three hd256 producers allocate buffers larger than their logical extent:
the Q and K scale images carry the gather padding the kernel's speculative
tile read needs, and the V data buffer carries the half-row overhang that
mxfp4_v_view's last element reaches into. As plain functions they inlined
into a compiled graph, which then shrank each allocation to what the traced
code reads, and the kernel gathered past the end:

  MX V descale needs 148480 mapped bytes so the kernel's speculative tile
  gather stays in bounds, but only 147456 are backed

Eager was unaffected at every shape, so this only showed up under
--use_torch_compile. Wrapping them as custom ops restores the graph boundary
their hd128 counterparts already have. Each gets a register_fake that
reproduces the padding; _mxfp4_v_hd256_sizes is shared by the real op and its
fake so the two cannot drift. Verified against the real ops under
FakeTensorMode on shape, dtype and untyped_storage().nbytes() across seven
shapes including ragged sequence lengths.

Also split the hd128/hd256 BSHD validation messages so a contiguous d=256
input no longer reports a contiguity error.

bench_sage: dispatch the MXFP4 producer trio on head dim so --d 256 works,
and add an aiter_fp8 kernel so the hd256 FP8 path is benchmarkable alongside
it. Recipes that are hd128-only now SKIP with a reason under --kernel all.

Ideogram-4 at 2048x2048, 48 steps, one MI350: 19.45s with the hd256 MXFP4
attention backend against 25.74s for hd256 FP8.

Signed-off-by: jcaraban <[email protected]>

* mha_v4: pack the hd256 MXFP4 K and V operands directly

hd256 reused the hd128 packers on a [b, s, 2h, 128] view and then permuted the
result into the tile order its code object reads. That permute was a second
full pass over K and V, and it had grown to cost about as much as the pack
itself: at b1 h18 s16384, K was 0.056ms of pack behind 0.064ms of permute and
V 0.072ms behind 0.076ms.

The packers now take `head_split`, which splits the head axis into
(heads / head_split, head_split) and places the inner index inside the tile
axis. hd128 passes 1 and is bit-identical to before; hd256 runs as 2h
half-heads and passes 2, so the producers allocate and pack straight into the
final layout with no permute.

The ordering is not a plain (tile, half) nesting, which is worth stating
because it is easy to assume and silently wrong. Inside the 16KB two-tile
group the order is (token_half, half, channel), so the token half sits
OUTSIDE the head half and each kernel rebuilds its own within-group offset
rather than scaling one head_tile index. K's scale needs no remap at all: it
is row-major over (batch, token, head', block) and hd128's image is already
hd256's under a reshape. V's scale shares V's data anchor and does.

Two out/scale numel checks in quantize_v_mxfp4_impl relax from == to >=: the
hd256 caller owns a longer buffer carrying its own gather slack, and the
kernel only ever writes inside the exact region.

Verified bit-identical to the permute path on eight shapes including ragged
sequence lengths, and fake-vs-real metadata still matches on shape, dtype and
untyped_storage().nbytes(). K+V producer time drops 42% at s=1024 and 57% at
s=65536. Ideogram-4 2048x2048, 48 steps, one MI350: 19.45s -> 18.75s for a
byte-identical image.

bench_sage: drop aiter_fp8 from --kernel all; select it explicitly.

Signed-off-by: jcaraban <[email protected]>

* mha_v4: per-batch seqlens_k on the gfx950 hd256 MXFP4 row

_VARLEN_CAPABLE_QV is keyed on (q_format, v_format) alone, so (MXFP4, MXFP4) already claimed
varlen support and the hd256 object inherited that claim the moment its manifest row landed,
while it never read the kernarg. Rebuilt with the hd128 mechanism: the pointer parks in s58,
which the dense path leaves unused, and the override is emitted after every base address --
kv_seq_len also strides the MX scale slices, so shrinking it earlier relocates each batch's
scale base and leaves batch 0 right and batches 1+ wrong.

hd256's scale geometry is its own: the host V-scale image is 1024 bytes per 128-token tile,
not hd128's 512. init_Kscale_srd sets num_records rather than a base, so it correctly runs
after the override with the per-batch length.

Dense gains 9 instructions, sparse assembly is unchanged, 256 VGPR / 90 SGPR as before.
Every batch is bitwise identical to the same kernel on physically truncated K/V across five
shapes; the pre-fix object falls to 0.286 cosine on the same comparison.

* test_mha_v4: match the seqlens_k kernarg load, not a bare 0x1c0

The varlen-object guard searched the disassembly for the literal, which also appears as an
ordinary VALU immediate: fwd_hd256_mxfp4.co carried v_add_u32 v242, 0x1c0, v68 and passed
while never reading the kernarg at all. That is the exact substitution the check exists to
catch, so it was reporting all rows clean with one of them silently ignoring seqlens_k.

Verified by pointing the tightened guard at the pre-fix object, which it now names.

* test_mha_v4: compare the hd256 MXFP4 LSE against torch

_LSE_CAPABLE_QV is keyed on (q_format, v_format) with no head-dim term, so adding the hd256 MXFP4
row made return_lse reachable on an object whose epilogue had never been compared against anything.
It is correct today; nothing held it there.

Bounds the relative error absolutely and against hd128. The absolute bound separates a real LSE
from a buffer that was never written; the hd128 comparison is what a constant cannot do, since the
residual is MXFP4 quantization rather than the epilogue.

Fault injection confirms both legs: zeros, 1e4 and NaN are each caught whether they are applied to
hd256 alone or to both head dims.

* test_mha_v4: check the LSE-capable rows really read the LSE kernarg

_LSE_CAPABLE_QV has the same hole the varlen gate had: keyed on (q_format, v_format) alone, so a
pair that gains a second object inherits the claim without being rebuilt. O never reads LSE, so
every output test keeps passing while the returned LSE is whatever the buffer held. Only the
emitted object can refute it.

Matched on the kernarg load rather than a bare literal, which is what let an object slip through
the varlen gate. Calibrated against the pre-LSE build of fwd_hd128_fp8 from 910e740: it reads
neither 0x40 nor 0x100, and swapping it in makes this check fail.

All 11 currently claimed dense rows pass.

* test_mha_v4: trace the hd256 MXFP4 path under fullgraph

This branch made the hd256 producers custom ops so the path could be traced, and nothing exercised
that. hd256 reaches its quantizers through a separate trio rather than a head-dim argument, so the
hd128 parity checks cover none of it.

Also the first hd256 coverage of out=, which the existing parity tests already assert aliasing for.

Replacing one producer with an untraceable callable makes the check fail, so it is testing the
schemas rather than just running the kernel twice.

* mha_v4.md: document head dimension 256 and the script-mode test entry point

Scope said head dimension 128 only. Adds the hd256 row's limits (MXFP4, dense, GFX950) and its
V buffer sizing. Also replaces `pytest op_tests/test_mha_v4.py`: the file has run as a script
since its pytest dependency was dropped, and CI invokes it that way.

* test_mha_v4: run the K common-mode checks at head dimension 256

hd256 feeds K and its mean through a [B, S, 2H, 128] half-head view, and every hd256 check used
randn K, where the smoothing gate stays closed and the mean is zero. A misaligned mean would pass
all of them. Both common-mode checks now take a head_dim and gain an MXFP4 hd256 row; they drive
the public API, so they keep their meaning when the hd256 tile geometry changes.

hd256 margins match hd128's: output ratio 1.000 (limit 1.5), LSE drift +0.108 nats (limit +0.5).
Swapping the mean halves fails both rows (ratio 16.7, +86 nats), as does dropping the mean
(ratio 12.0, +66 nats).

* mha_v4: add the gfx950 hd256 MXFP6 kernel

Dense all-MXFP6 row at head dim 256: 256Q x 64KV tile in 244 VGPRs, with the
V operand ring sharing registers with the two K operand banks. Each 64-token
K record (13,312 B) carries its K-scale tail. Its FP6-P block scale rounds the
block max before taking the exponent, so a max that rounds to 8 no longer
saturates at 7.5.

The hd128 MXFP6 K and FP6-P V packers take head_split=2 and write the hd256
records straight from a [b, s, 2h, 128] view. hd128 output is unchanged, and
hd256 is bit-identical to permuting the hd128 records on five ragged shapes.
K+V pack at b1 h18 s16384: 154 us vs 538 us for pack-then-permute.

LSE and per-batch key lengths are enabled and checked like hd256 MXFP4.
b1 h5 s65536 on MI355X: 4321 TFLOPS (hd256 MXFP4 5043, hd128 MXFP6 ~4000);
cosine vs fp64 attention ~0.998.

Signed-off-by: jcaraban <[email protected]>

* mha_v4: one head-dim gate and one MX producer table

Head-dim support was decided in three places with three different rules: the
raw input check, a recipe-kind test in mha_v4, and a Q-format test in
mha_v4_packed that let unsupported V formats through to find_config. One
_check_head_dim over (Q/K format, V format) pairs now serves both entry
points, and rejects sparse at hd256 up front since no hd256 sparse row exists.

The MXFP4 and MXFP6 raw paths pick their (Q, K, FP6-P V) quantizers from
mha_v4_mx_producers instead of per-branch head-dim switches; it is public so
benchmarks select the same producers. The MXFP6 launcher derives the head dim
from Q's FP6 packed width, since an MXFP4 V arrives as a flat buffer.

test_mha_v4: 235 ran, 7 failed (the MXFP8 unfused-pipeline checks, which fail
the same way on the base tree under Triton 3.5.1); sparse: 160 ran, 0 failed.
Each head-dim rejection check fails with _check_head_dim stubbed out.

Signed-off-by: jcaraban <[email protected]>

* test_mha_v4: benchmark hd256 MXFP6 alongside MXFP4

--head-dim 256 kept only the mxfp4 recipe, so the hd256 MXFP6 row was never benchmarked.
At sk 1024/4096 both hd256 rows pass with err 0.

Signed-off-by: jcaraban <[email protected]>

* test(mha_v4): run hd256 GQA repeated-KV check for MXFP4 and MXFP6

Both formats bit-exact vs repeated KV on gfx950; a wrong head mapping
(repeat vs repeat_interleave) breaks equality (max diff 0.77).

* mha_v4: temporarily disable FP6 Q/K recipes

* mha_v4_quant: keep the FP6 pack destination clear of its sources

ROCm 7.2 allocates v_cvt_scalef32_2xpk16_fp6_f32's result over its source tuple; in the fused
MXFP6 K packer that corrupted byte 3 of every 16-byte C0 chunk (CI's 32 FP6 failures). An
early-clobber inline-asm wrapper keeps them disjoint. With the CI compiler: sparse 160/0 failed,
dense FP6 0 failed; unfixed reproduces CI's 5 + 27 failures.

* Revert "mha_v4: temporarily disable FP6 Q/K recipes"

This reverts commit e326892.

---------

Signed-off-by: jcaraban <[email protected]>
echen4096 added a commit to echen4096/aiter that referenced this pull request Nov 20, 2026
…OCm#3)

Summary:

## Summary

`cvt_scalef32_2xpk16_fp6` in `csrc/kernels/mha_v4_quant.cu` now spells its vector types with two aliases, `f32x16_t` and `u32x6_t`, instead of writing `__attribute__((ext_vector_type(N)))` in its signature and body. The types and the generated code are unchanged.

## Motivation

Since ROCm#7173, `mha_v4_quant.cu` doesn't compile with the ROCm 7.0 compiler (AMD clang 20). That compiler accepts `ext_vector_type` only on a typedef or alias, so it rejects the attribute on the function's return type, its parameters and its local variable:

```
error: 'ext_vector_type' attribute only applies to typedefs
```

Newer clang accepts both forms. With the aliases, the file compiles with ROCm 7.0 as well as newer compilers. The rest of the file already declares its vector types with `using`.

## Changes

- Add `f32x16_t` and `u32x6_t` in the `__gfx950__` block and use them in `cvt_scalef32_2xpk16_fp6`.

## Testing

- Built `mha_v4_quant.cu` for gfx950 with the ROCm 7.0 compiler. It failed with the error above before this change and compiles with it.
- The types and the inline assembly are the same.

Test Plan: Built AITER for MI350 (gfx950) with the ROCm 7.0 HIP compiler and `mha_v4_quant.cu` included: it failed with "'ext_vector_type' attribute only applies to typedefs" before this change and compiles with it.

Differential Revision: D133345530
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants