Skip to content

[ASM] [HIP] fmha_v4: gfx950 BF16 hd256 THD forward (cu_seqlens), causal and non-causal - #8067

Merged
kaiyang-1 merged 9 commits into
mainfrom
fmha_bf16
Nov 19, 2026
Merged

kaiyang-1 merged 9 commits into
mainfrom
fmha_bf16

Conversation

@JohnNikolay84

@JohnNikolay84 JohnNikolay84 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two gfx950 kernels for attention over whole documents in THD: Q/K/V [total, H, 256] delimited by one cu_seqlens, any Hq % Hkv == 0 (24/4, 12/2, 6/1, MHA), 64-bit addressing, LSE [Hq, total]. Causal work-groups own Q tile i and its mirror n-1-i.

  • fmha_v4_fwd.csv: new mode 3 (THD) rows, mask 0/1, both declaring kv_range, and a pair_split column that the causal row declares.
  • mha_v4(..., cu_seqlens=, max_seqlen=, causal=) runs them through the recipe, head-dimension and LSE checks of the dense path. All-BF16 operands, head dimension 256.
  • fmha_v4_fwd_thd launcher with an explicit kv_splits: each work-group cuts its key walk into that many slices (named kernarg fields), written as FP32 partials and merged by LSE with the Triton lse_merge kernel. kv_splits="auto" takes up to 4 slices when the grid leaves CUs idle. On the causal row, 2 to 5 slices run a pair of Q tiles on one more work-group than slices when that fits the device's CU count, which the launcher passes to the kernel.
  • Checks in op_tests/test_mha_v4.py, timing in op_tests/op_benchmarks/hip/bench_mha_v4_thd.py.

Not in this PR: routing flash_attn_varlen_func to these kernels. That code is in 213c33e for an opt-in follow-up.

Performance (if applicable)

Speedup is now 2.26–3.73× over CK

Heads Pack asm TFLOPS Current AITER (CK) TFLOPS Speedup
24/4 4K 972 405 2.40×
24/4 8K 1119 494 2.26×
24/4 16K 1404 529 2.65×
24/4 32K 1369 548 2.50×
12/2 4K (split ×2) 758 314 2.41×
12/2 8K 1052 425 2.48×
12/2 16K 1199 509 2.36×
12/2 32K 1379 537 2.57×
6/1 4K (split ×4) 608 163 3.73×
6/1 8K (split ×2) 899 321 2.81×
6/1 16K 1160 446 2.60×
6/1 32K 1230 516 2.38×

Two A/Bs on one MI355X GPU over 15 causal shapes (24/4, 12/2 and 6/1 at 4K to 32K and a 300+4K pack, kv_splits="auto"):

  • The move into mha_v4 (06729c3 against b3511b6) does not change device time: geomean ratio 1.001.
  • The rework since the original kernels (daf067c against e707d43: 64-key kernels, extra work-groups, cap of 4 slices) is 11% faster in geomean, 3% to 19% per shape.

Testing

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

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

aiter/ops/mha_v4.md describes the THD mode.

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

None. mha_v4 gains three optional keyword arguments.

PR Self-Review

Reviewed revision

e707d43

Behavior and intent

mha_v4 gains THD operands: with cu_seqlens and max_seqlen it attends over each document of a concatenated pack, with an optional causal mask, on two new gfx950 BF16 hd256 kernels. Until now mha_v4 took only BSHD batches without a causal mask, and packed documents at head dimension 256 ran on the v3 kernels (MHA) or CK (GQA).

Existing calls keep their behavior: the new arguments default to off, and the dense, sorted-sparse and Sol-Attn launchers only moved their kernel cache and launch into one shared helper, which also refuses a grid that does not fit the launch ABI.

Validation and unverified scope

On MI355X at e707d43:

  • python3 op_tests/test_mha_v4.py: 425 ran, 0 skipped, 0 failed, and python3 op_tests/test_mha_v4_sparse.py: 609 ran, 5 skipped, 0 failed (CI, on the merge with main).
  • A scan outside the suite, each call checked against float32 attention: 174 single causal documents (heads 6/1, 12/2 and 24/4, kv_splits 2 to 6, 4 to 12 Q tiles, max_seqlen exact and overstated by 512) and 600 random packs (1 to 5 documents, both masks, 1 to 9 slices, max_seqlen overstated by up to 2048). All pass, with worst-row relative O error 0.0036 and LSE error 2e-6. At b15b18f the first scan hit 8 GPU memory faults and 3 wrong outputs, which is what test_mha_v4_bf16_hd256_thd_causal_slice_layouts now covers.
  • Known-bad controls all fail the THD check (run at b3511b6, whose check is the one used here): a flipped mask, documents merged into one, one output row off by 5%, one LSE entry off by 0.005, max_seqlen two tiles short, slices left unmerged and a document left unwritten in the 4 GiB pack.
  • The timing A/Bs under Performance.

Unverified: MI350X was not run. Only a 256-CU device was run, so the kv_splits + 1 layout against another CU count rests on the kernel reading cu_budget, which the suite checks by disassembly. MI250X and MI300X have no THD row, so the call is refused there, which was not run either. The two code objects were checked through their manifest rows, the suite's disassembly gates and the numerical checks, not by reading the kernels. The speedup table is the author's measurement.

PR-specific question

The THD rows are reached only through mha_v4(..., cu_seqlens=...), and find_config selects them by arch (gfx950), all-BF16 formats, head dimension 256, mode 3 and the mask column from causal. Every other lookup passes mask=0 and its own mode, as before, so no existing call can land on them.

Before launching, mha_v4 refuses other formats, BSHD operands, block_mask and seqlens_k; find_config raises where no row exists (gfx942, head dimension 128); and the launcher checks dtype, device, unit-stride head dimension, that Q, K and V hold the same tokens, that query heads are a multiple of KV heads, the cu_seqlens dtype and layout, the out and LSE layouts against kv_splits, and that a row sliced by kv_splits declares kv_range. Only a row declaring pair_split gets the CU count and the larger grid. The contents of cu_seqlens stay the caller's contract, since checking them would synchronize every launch; max_seqlen may overstate the longest document, which then only costs work-groups that exit at once.

Changed op tests

  • op_tests/test_mha_v4.py: THD checks next to the hd256 BF16 ones, with their float32 reference and tolerance judged on the worst row of each document. They cover both masks, GQA 24/4, 12/2, 6/1 and MHA, ragged packs, explicit and automatic KV slices, the causal slice layouts under an exact and an overstated max_seqlen, a pack whose operands each pass 4 GiB, compile parity, and the calls mha_v4 and the launcher refuse. A disassembly gate checks that the row declaring pair_split loads the CU count. No existing test reaches mode 3 rows, a causal mask or cu_seqlens.
  • op_tests/op_benchmarks/hip/bench_mha_v4_thd.py: times the THD call per pack, mask and slice count. It is a benchmark, not run by CI, and replaces the timing half of the standalone script this PR first added.

@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 8067 --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.

@jcaraban jcaraban 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.

Thanks John, the packed-document kernels look like a clear win for GQA. Before this goes further, I'd like to restructure it so it builds on what mha_v4 already has instead of growing a second path next to it. Details are inline; the short version:

  • Stack this on #7939, which adds BF16 hd256 to mha_v4 (recipe set, manifest row, validation, tests). Packed documents and causal would then be capabilities of that path rather than a separate mha_v4_varlen_fwd.
  • Let the automatic split for the causal pair grid come from #7942's cost model instead of a third heuristic.
  • Move the flash_attn_varlen_func routing in aiter/ops/mha.py to its own follow-up PR, opt-in at first and tested through that entry point, including the backward path.
  • Give the split arguments named kernarg fields and a manifest capability column (as Sol-Attn does with kv_range) instead of writing into the reserved ptr_qseq_padding slot and inferring split mode from out.dim().

One question: what does a second hd256 BF16 kernel (KV tile 32) buy over adding packed documents and causal masking to #7939's object? Non-causal packing with equal lengths is what #7939 already covers through seqlens_k, and a same-shape timing comparison would help decide whether we want two kernels. I reviewed the two objects only through their manifest rows and the launcher, not the kernels themselves.

The description still has the template sections empty (self-review, test checkboxes), and the speedup table doesn't say which paths "Current AITER" measures. I added a banner about the merge order at the top of the description; feel free to adjust it.

Comment thread aiter/ops/mha.py Resolved
Comment thread aiter/ops/mha.py Resolved
Comment thread aiter/ops/mha.py Resolved
Comment thread aiter/ops/mha_v4.py Resolved
Comment thread aiter/ops/mha_v4.py Resolved
Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
Comment thread hsa/gfx950/fmha_v4_fwd/fmha_v4_fwd.csv Resolved
Comment thread op_tests/test_mha_v4_varlen.py Resolved
@jcaraban jcaraban changed the title [ASM] [HIP] fmha_v4: gfx950 BF16 hd256 varlen forward, causal and non… [ASM] [HIP] fmha_v4: gfx950 BF16 hd256 THD forward (cu_seqlens), causal and non-causal Nov 17, 2026
@jcaraban

Copy link
Copy Markdown
Contributor

@JohnNikolay84 I pushed the restructure from my review onto this branch, as a merge of main plus separate commits (no history rewrite), and updated the title and description to match:

  • 6a05e76 merges main and keeps [ASM] Mha v4: gfx950 hd256 BF16 kernel #7939's dense hd256 BF16 row next to yours.
  • e7233a2 takes the flash_attn_varlen_func routing out. It stays in 213c33e for an opt-in follow-up.
  • b9d629c folds the entry point into mha_v4(..., cu_seqlens=, max_seqlen=, causal=) and gives the launcher an explicit kv_splits, named kernarg fields and the kv_range capability.
  • b3511b6 moves the checks into test_mha_v4.py and the timing into op_tests/op_benchmarks/hip/bench_mha_v4_thd.py.

The kernels are untouched, and a same-GPU A/B on MI355X shows no change in device time (numbers in the description). The inline threads say what changed where, including two suggestions I withdrew.

Left for you:

If you disagree with any of it, each change is its own commit and easy to revert.

@JohnNikolay84

JohnNikolay84 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

One question: what does a second hd256 BF16 kernel (KV tile 32) buy over adding packed documents and causal masking to #7939's object? Non-causal packing with equal lengths is what #7939 already covers through seqlens_k, and a same-shape timing comparison would help decide whether we want two kernels. I reviewed the two objects only through their manifest rows and the launcher, not the kernels themselves.

The new binaries are kv_tile=64

What the THD object adds that #7939's does not cover:

  1. Causal masking. [ASM] Mha v4: gfx950 hd256 BF16 kernel #7939 has no causal row. The THD causal object pairs Q tile i with n-1-i, so every work-group does n+1 tile-units, and the 4 diagonal 64-key tiles are masked. This is the main use case (GQA prefill, 24/4, 12/2, 6/1): 2.19–3.21x over CK mha_varlen_fwd at 4K–32K.
  2. Non-power-of-two GQA. The THD object maps head h to h / gqa by integer division; dense mha_v4 refuses 24/4.
  3. Ragged packs without padding. Documents are delimited by cu_seqlens in one [total, H, 256] buffer, so Q rows past a document's end are neither allocated nor computed. That gives the 1.09–1.18x above, before counting the padding copy the dense path needs.
  4. Packs past 4 GiB. Addressing is 64-bit, so packs over 4 GiB are covered by test_mha_v4_bf16_hd256_thd_addresses_documents_past_4gib; dense populate_dense_kernarg needs a 32-bit batch stride.
  5. In-launch KV slices with FP32 partials. Merged error stays below CK's at 1–4 slices, where BF16 partials were ~7% above. For causal 2–5 slices a pair runs on S+1 work-groups. 6/1 4K causal: 141 to 83 µs.

On the other hands:

What #7939's object covers that THD does not. seqlens_k with Sq != Sk, i.e. partial-KV or prefix batches. THD requires whole documents (Q, K and V share total_tokens).

@jcaraban
jcaraban marked this pull request as ready for review November 17, 2026 21:20
@jcaraban
jcaraban requested a review from a team November 17, 2026 21:20
@aiter-bot

aiter-bot commented Nov 17, 2026 •

Copy link
Copy Markdown

WAITING ON AUTHOR

PR Self-Review

Revision 40caeca35fe4 · 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.

@jcaraban jcaraban 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.

I scanned b15b18f on MI355X: one causal document per call, heads 6/1, 12/2 and 24/4, kv_splits 2 to 6, 4 to 12 Q tiles, each with max_seqlen exact and overstated by 512 (174 calls). daf067c passes all of them. b15b18f does not:

  1. GPU memory fault with valid arguments. kv_splits=5 on a 1536-token causal document faults for 6/1 and 12/2 heads; kv_splits=4 is fine there. "auto" is capped at 4 and cannot reach it, but an explicit 5 is accepted:
import torch
from aiter.ops.mha_v4 import AttentionFormat, mha_v4

q = torch.randn((1536, 12, 256), device="cuda", dtype=torch.bfloat16)
k = torch.randn((1536, 2, 256), device="cuda", dtype=torch.bfloat16)
v = torch.randn_like(k)
cu_seqlens = torch.tensor([0, 1536], device="cuda", dtype=torch.int32)
mha_v4(q, k, v, *(AttentionFormat.BF16,) * 3, cu_seqlens=cu_seqlens, max_seqlen=1536,
       causal=True, kv_splits=5, return_lse=True)
torch.cuda.synchronize()  # HSA_STATUS_ERROR_MEMORY_FAULT
  1. max_seqlen above the longest document now gives wrong output (3 of 87 calls) or a fault (6 of 87). Details inline.
  2. Black fails, which fails the test gate. Inline.

The first one should be fixed before this merges. test_mha_v4.py still passes (416 ran, 0 failed) because it has no case for 1 or 2; I can add them if that helps. Sliced accuracy itself is fine: worst-row relative O error 0.003 and LSE error 2e-6 at 1 to 9 slices, both masks.

The description still describes daf067c: the reviewed revision, the accuracy numbers and the A/B are from before the new kernels.

Comment thread csrc/py_itfs_cu/asm_mha_v4_fwd.cu Resolved
Comment thread op_tests/test_mha_v4.py Resolved
jcaraban
jcaraban previously approved these changes Nov 18, 2026

@jcaraban jcaraban 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.

Approving at e707d43: it fixes the three findings of my last review, so this replaces my request for changes. I also updated the description to this head.

Verified on MI355X:

  • The kv_splits=5 fault is gone: the same 174-call scan (single causal documents, exact and overstated max_seqlen) now passes every call, where b15b18f hit 8 faults and 3 wrong outputs.
  • A wider scan of 600 random packs (1 to 5 documents, both masks, 1 to 9 slices, max_seqlen overstated by up to 2048) passes too: worst-row relative O error 0.0036, LSE error 2e-6.
  • Against the original kernels (daf067c against e707d43, both built and timed in one session on the same GPU, old/new/new/old), the causal path is 11% faster in geomean over 15 shapes (3% to 19% per shape). That is the whole rework since then, end to end with kv_splits="auto": the 64-key kernels, the extra work-groups and the cap of 4 slices. I did not time b15b18f on its own.

Observations, none blocking:

  • Only a 256-CU device was run. The launcher now takes the CU count from the device, and the suite checks that the kernel loads it, but MI350X and other CU counts are untested.
  • The suite alone did not catch the earlier fault; the scans above did. They are worth re-running whenever these kernels are rebuilt.
  • The two THD symbols lack the _gfx950 suffix the other objects carry; fine to fix at the next rebuild.
  • The two red CI shards (test_flydsl_hgemm.py, test_flydsl_allreduce_rank_agreement.py) fail in tests this PR does not touch; I re-ran them.

JohnNikolay84 and others added 9 commits November 18, 2026 23:19
…-causal

Two asm kernels for packed whole-document attention: Q/K/V [total, H, 256] delimited by one
cu_seqlens, any Hq % Hkv (24/4, 12/2, 6/1, MHA), 64-bit addressing, LSE [Hq, total_q]. Causal workgroups own
Q tile i and its mirror n-1-i.

- fmha_v4_fwd.csv: new mode 3 (varlen) rows, mask 0/1.
- fmha_v4_fwd_varlen launcher; a 4-D out splits each workgroup's KV range (split args in the
  ptr_qseq_padding slot), merged by LSE with the Triton lse_merge kernel.
- mha_v4_varlen_fwd with an automatic split count when the grid leaves CUs idle.
- _flash_attn_varlen_forward routes gfx950 BF16 hd256 calls with one cu_seqlens, equal Q/K
  lengths and no window, sink, dropout, bias, soft cap, paging or padding to these kernels;
  AITER_DISABLE_FMHA_V4_HD256=1 restores the previous path.
- op_tests/test_mha_v4_varlen.py: fp32 reference checks for both masks.

MI355X GPU time vs the previous path: 1.5-2.9x over CK for GQA, 1.2-2.0x over the v3 asm
kernels for MHA.

Co-authored-by: Cursor <[email protected]>
The routing sent every gfx950 BF16 hd256 varlen call that passed its gate
to the new kernels by default, training included, with no test through
that entry point. This PR keeps to the v4 op. The routing is in 213c33e
for a follow-up that is opt-in and tested through flash_attn_varlen_func,
backward included.
mha_v4 takes cu_seqlens, max_seqlen and causal instead of a second public
entry point, so the recipe, head dimension and LSE checks are the dense
path's. "THD" names the layout: "varlen" already means per-batch
seqlens_k in this module.

- The launcher takes kv_splits as an argument rather than reading it off
  the rank of out, and refuses slices on a row that does not declare
  kv_range, which both mode 3 rows now do.
- The slice count and strides are named kernarg fields with their offsets
  asserted, not a memcpy into the reserved slot.
- The LSE goes through set_lse_kernarg, and every launcher through one
  launch helper that also checks the grid fits the launch ABI.
- The automatic slice count keeps its measured one-wave rule as a private
  resolver next to the dense one; an explicit count keeps a 256-key tile
  per slice.
- op_tests/test_mha_v4_varlen.py called the removed entry point; its
  checks and timing follow in the next commit.
The checks sit next to the hd256 BF16 ones and share their float32
reference and tolerance, judged on the worst row of each document: both
masks, GQA 24/4, 12/2, 6/1 and MHA, ragged packs, explicit and automatic
KV slices, a pack whose operands each pass 4 GiB, compile parity and the
calls mha_v4 and the launcher refuse.

The timing table moves to op_tests/op_benchmarks/hip/bench_mha_v4_thd.py,
so CI no longer times packs on every run.
…artials

The two THD objects now walk keys in 64-token tiles (manifest ts_kv 32 -> 64).
KV slices write FP32 partials: BF16 ones cost ~7% rel L2 against CK once
merged, FP32 keeps the merged error below CK's at any slice count.

A causal launch of 2-5 slices runs a pair on kv_splits + 1 work-groups when
its document has 4+ Q tiles and nhead_q * pairs * (kv_splits + 1) <= 256; the
launcher sizes x for it. "auto" caps at 4 slices.

MI355X, causal, against CK mha_varlen_fwd: 2.19-3.21x over 24/4, 12/2 and 6/1
at 4K-32K (6/1 4K: 642 vs 200 TFLOPS at 4 slices). test_mha_v4.py: 416 ran,
0 failed.

Co-authored-by: Cursor <[email protected]>
The THD grid is (pairs or Q tiles of the longest document, Hq, documents) and
the dispatcher deals work-groups to XCDs by linear id, x fastest. When the
pair count is a multiple of 8, pair p of every document lands on XCD p % 8,
so short documents load the low XCDs and the launch waits on the busiest one.

Unsplit launches now decode l = x + G * y with the document's own pair count
P as (head l / P, pair l % P): a document's P * Hq live work-groups are the
first ids of its z slice, and a head's pairs stay adjacent, so K/V reuse in
each XCD's L2 is unchanged. G is derived from max_seqlen, so the host and the
kernel arguments are unchanged; split launches keep their decode.

MI355X, causal, kv_splits=1: ragged pack B (10 documents of 1-12K tokens)
1.12-1.20x over 24/4, 16/2, 32/2, 64/8 and 6/1, random ragged packs up to
1.26x; equal-length and single-document packs within noise. O and LSE are
bitwise identical to the previous objects on 220 timing cases (kv_splits 1-4
and auto) and on packs with 0/1/255/256/257-token documents.
test_mha_v4.py: 425 ran, 0 failed.

Co-authored-by: Cursor <[email protected]>
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