Skip to content

[MHA] Route flash_attn_varlen_func gfx950 hd256 BF16 THD forward to mha_v4 - #8704

Merged
valarLip merged 14 commits into
mainfrom
fmha-v3-fwd-thd-hd256
Dec 3, 2026
Merged

valarLip merged 14 commits into
mainfrom
fmha-v3-fwd-thd-hd256

Conversation

@JohnNikolay84

@JohnNikolay84 JohnNikolay84 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

aiter.flash_attn_varlen_func now runs the gfx950 BF16 hd256 forward of packed self-attention on
mha_v4's THD kernels (#8067), for MHA and GQA, causal or not. Training (forward + backward)
through flash_attn_varlen_func gets these kernels; the backward is unchanged. The PR adds no
kernel, launcher or manifest: it is a dispatch in _flash_attn_varlen_forward to mha_v4.

Forward pass on MI355X, compared with what flash_attn_varlen_func runs today:

  • GQA (24/4, 12/2, 6/1), which used to fall back to CK: 1.8-2.6x faster (up to 3.2x with opt-in KV
    splits).
  • MHA, which used to run on the v3 hd256 group kernels: about 1.6x faster.

Motivation

We need these kernels to train with aiter.flash_attn_varlen_func (forward + backward).

They exist in mha_v4 (#8067), but mha_v4 is forward-only and has no autograd/backward
integration, so they could not be used for training. #8067 left routing from
flash_attn_varlen_func to a follow-up that is tested through that entry point, backward included.

Today, flash_attn_varlen_func sends gfx950 BF16 hd256 calls to:

  • the v3 group kernels fwd_hd256_bf16_group.co / fwd_hd256_bf16_causal_group.co, but only when
    nhead_q == nhead_k, because they index K/V by the Q head;
  • CK for every GQA shape.

FlashAttnVarlenFunc.backward only needs the forward's output and LSE, and mha_v4 returns both
in the layout the v3 path returns, so the existing backward consumes them as is. The forward is
routed to mha_v4 itself rather than to a copy of its kernels and launcher in v3, so there is one
set of code objects and one launcher to keep correct (review feedback).

Changes

_flash_attn_varlen_forward gains a branch, ahead of v3 and CK, that calls
mha_v4(..., cu_seqlens=, max_seqlen=, causal=, return_lse=, out=, kv_splits=) when
can_impl_fmha_v4_thd() holds: gfx950, BF16, head dims 256/256, nhead_q % nhead_k == 0, Q and K
passing the same cu_seqlens tensor (checked by pointer, so no device sync and safe under graph
capture), no window other than causal, and none of dropout, bias, ALiBi, soft cap, sink, descales,
padded cu_seqlens, block_table, min_seqlen_q or return_softmax. mha_v4 needs Triton; it is
imported lazily, and without it calls keep their current path. Every other call keeps its current
path too, including a separate cu_seqlens_k tensor with equal contents (v3 group kernels for MHA,
CK for GQA). AITER_FMHA_V4_THD=0 restores the previous routing. KV splits are off by default and
opt-in through AITER_FMHA_V4_THD_KV_SPLITS (auto or a count, clamped to what mha_v4 takes),
because auto ranged from 0.58x to 1.47x of one slice on MI355X.

Tests: generate_qkv now shares one cu_seqlens tensor for QKV-packed inputs (-i QKVPACKED), and
op_tests/test_mha_varlen.py gets test_flash_attn_varlen_func_thd_hd256, which also runs from
__main__ as CI runs the file. The file's seq-padding benchmark skips GQA ratios that don't divide
its 8 heads, which crashed every -gr 6 run. .github/scripts/flash_attention/test.sh deselects
the two alibi=True variants of the dropout/causal/head-dim-128 case that aborts in the Triton
backward kernel (bwd_kernel_fused_causal, LLVM miscompile), as it already does for the
alibi=False variants, and on RDNA3 skips the dropout/causal/head-dim-32 case without alibi, which
fails its output check there. Both are Triton-backend failures that do not go through this code.

Performance (if applicable)

All numbers come from op_tests/test_mha_varlen.py at 10d3c4e on MI355X (gfx950, 256 CUs). The
test times aiter.flash_attn_varlen_func with run_perftest; fwd_us / fwd_tflops are from its
summary table (profiler device time). -i QKVPACKED gives whole documents with one cu_seqlens
tensor for Q and K. "Before" is the same command with AITER_FMHA_V4_THD=0.

GQA, one causal document per pack, hd256 BF16 (the shapes of the #8067 table):

AITER_LOG_MORE=1 python3 op_tests/test_mha_varlen.py -b 1 -nh <24|12|6> -s N,N -d_qk_v 256,256 \
    -dt bf16 -gr 6 -c True -l False -det False -i QKVPACKED
Hardware Workload/configuration Before (CK) After Change
MI355X 24/4 heads, 4K 487 TFLOPS (423.0 us) 1082 TFLOPS (190.5 us) 2.22x
MI355X 24/4 heads, 8K 559 TFLOPS (1475.4 us) 1206 TFLOPS (683.6 us) 2.16x
MI355X 24/4 heads, 16K 577 TFLOPS (5717.8 us) 1356 TFLOPS (2432.9 us) 2.35x
MI355X 24/4 heads, 32K (*) 546 TFLOPS (24158 us) 1370 TFLOPS (9629 us) 2.51x
MI355X 12/2 heads, 4K 396 TFLOPS (260.4 us) 713 TFLOPS (144.5 us) 1.80x
MI355X 12/2 heads, 8K 484 TFLOPS (851.6 us) 1208 TFLOPS (341.3 us) 2.50x
MI355X 12/2 heads, 16K 545 TFLOPS (3026.4 us) 1255 TFLOPS (1314.7 us) 2.30x
MI355X 12/2 heads, 32K 554 TFLOPS (11906.5 us) 1370 TFLOPS (4816.2 us) 2.47x
MI355X 6/1 heads, 4K 199 TFLOPS (259.5 us) 360 TFLOPS (143.4 us) 1.81x
MI355X 6/1 heads, 8K 400 TFLOPS (514.9 us) 783 TFLOPS (263.2 us) 1.96x
MI355X 6/1 heads, 16K 485 TFLOPS (1700.7 us) 1259 TFLOPS (655.0 us) 2.60x
MI355X 6/1 heads, 32K 544 TFLOPS (6069.2 us) 1275 TFLOPS (2587.6 us) 2.35x

(*) 24/4 heads at 32K: the test's FP32 torch reference runs out of memory after the timing, so
there is no summary row. That row uses the AITER_LOG_MORE=1 profiler kernel time, in both columns.

Opt-in KV splits (AITER_FMHA_V4_THD_KV_SPLITS=auto added to the same command) on the shapes where
auto splits:

Hardware Workload/configuration Before (CK) After, one slice After, auto splits Change vs CK
MI355X 6/1 heads, 4K 259.5 us 143.4 us 81.1 us (635 TFLOPS) 3.20x
MI355X 6/1 heads, 8K 514.9 us 263.2 us 203.9 us (1011 TFLOPS) 2.53x
MI355X 12/2 heads, 4K 260.4 us 144.5 us 126.7 us (814 TFLOPS) 2.06x

MHA, 2 documents, 24 heads, hd256 BF16:

AITER_LOG_MORE=1 python3 op_tests/test_mha_varlen.py -b 2 -nh 24 -s N,N -d_qk_v 256,256 \
    -dt bf16 -gr 1 -c <False|True> -l False -det False -i QKVPACKED
Hardware Workload/configuration Before (v3 group) After Change
MI355X non-causal, 2 x 4096 821 TFLOPS (1005.1 us) 1314 TFLOPS (627.7 us) 1.60x
MI355X non-causal, 2 x 4000 791 TFLOPS (993.7 us) 1279 TFLOPS (614.9 us) 1.62x
MI355X causal, 2 x 4096 644 TFLOPS (639.9 us) 1040 TFLOPS (396.4 us) 1.61x
MI355X causal, 2 x 4000 620 TFLOPS (634.7 us) 1016 TFLOPS (387.2 us) 1.64x

Backward time is unchanged: the same backward kernels run in both columns
(fmha_bwd_hd256_odo_bf16_group, fmha_bwd_fused_dkdv_dq_hd256_bf16_[non]causal_varlen).

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X (not applicable: gfx950-only kernels)
  • Tested on MI300X (not applicable: gfx950-only kernels; other GPUs keep their path)
  • Tested on MI355X (gfx950)

Documentation

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

The flash_attn_varlen_func docstring describes the fast path, the one-cu_seqlens requirement,
AITER_FMHA_V4_THD=0 and AITER_FMHA_V4_THD_KV_SPLITS.

Dependencies

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

The new path uses Triton through mha_v4 (lse_merge, arch_info). It is imported lazily; without
Triton, calls take the existing path.

Breaking Changes

None. Qualifying gfx950 BF16 hd256 varlen forward calls now run a different kernel by default. Its
output error against an FP32 reference is lower than the previous kernel's (see below).
AITER_FMHA_V4_THD=0 restores the previous routing.

PR Self-Review

Reviewed revision

5df4536

Behavior and intent

aiter.flash_attn_varlen_func on gfx950 with BF16 hd256 Q/K/V runs the forward of packed
self-attention (Q and K sharing one cu_seqlens tensor, no padding) on mha_v4's THD kernels,
MHA and GQA, causal or not. Before this change, MHA calls used the slower v3 group kernels and GQA
calls fell back to CK, and the THD kernels could not be used for training because mha_v4 has no
backward. The backward path is unchanged and consumes the output and LSE mha_v4 returns. The PR
adds no kernel and no launcher: mha_v4's code objects and launcher are the only copy.

Validation and unverified scope

Hardware: MI355X (gfx950, 256 CUs), ROCm 7.2, PyTorch 2.13, Triton 3.9. All runs at 10d3c4e;
5df4536 has the same aiter/ code, rebased on main, plus the test.sh deselects.

CI at 5df4536 passed, including the MI35X standard tests, which run op_tests/test_mha_varlen.py
as a script (its -d_qk_v sweep and the THD cases from __main__), and both Flash Attention
Triton jobs.

op_tests/test_mha_varlen.py:

  • python3 -m pytest op_tests/test_mha_varlen.py -k thd_hd256: 5 passed (one-slice MHA and GQA,
    causal and not, and a 2-slice case that checks _lse_merge_kernel runs).
  • Every performance command above passed the test's forward and backward checks against its torch
    reference, except 24/4 heads at 32K, where the reference ran out of memory. The profiler showed
    fmha_fwd_hd256_bf16_varlen[_causal] in every "after" run and _lse_merge_kernel only in the
    auto runs.

An ad-hoc script calls aiter.flash_attn_varlen_func with return_lse=True against an FP32
per-document reference (FP32 autograd for gradients) and checks the launched kernels: 60/60 pass.

  • One slice (default): heads 16/16, 24/4, 12/2, 6/1 and 32/8; ragged packs with 0, 1, 255, 256 and
    257-token documents and documents up to 8192 tokens; packed (strided) QKV; causal and
    non-causal; backward for 16/16, 24/4 and 6/1.
  • KV splits: forced 2, 3 and 4 slices for 6/1, 12/2 and 24/4, causal and non-causal, over packs
    whose 0- and 1-token documents leave slices without keys for some rows; auto; backward with 4
    slices and with auto.
  • Stays off this path: a separate cu_seqlens_k tensor with equal contents (MHA: v3 group kernel;
    GQA: CK), forward and backward; per-document Q and K lengths that differ while totals and maxima
    match; AITER_FMHA_V4_THD=0.

Errors on the mha_v4 rows: max |O error| <= 0.0104 on the forward packs (previous kernel: 0.0132)
and <= 0.0154 on the backward packs; max |LSE error| < 1e-5 (previous kernel: 0.0042); max
dQ/dK/dV relative error <= 0.0061.

Packs over 4 GiB (16/16 heads, Q/K/V/O each 4.07 GiB, 535 documents): the default (one slice)
passes. With KV splits requested, mha_v4 raises per-slice output stride ... does not fit the 32-bit kernarg slot instead of computing: its split resolver does not drop to one slice when the
FP32 partials pass 4 GiB. That is opt-in only and a mha_v4 limit.

Unverified:

  • MI350X was not rerun at this revision.
  • Host overhead: a call through mha_v4() costs a few microseconds more on the host than the
    previous C++ path; the times above include it.
  • Direct C++ callers of fmha_v3_varlen_fwd / mha_fwd() do not reach these kernels; only
    flash_attn_varlen_func routes to them.
  • When FlyDSL is installed, it can take inference (no-grad) calls before this path.
  • The existing hd256 varlen backward kernels return wrong gradients for packs over 4 GiB. That
    predates this PR and needs a separate fix in those kernels.

PR-specific question

Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant
prevents unsupported inputs from reaching it?

The mha_v4 branch of _flash_attn_varlen_forward is taken only when can_impl_fmha_v4_thd()
holds:

  • Architecture: gfx950 (get_gfx() == "gfx950").
  • Dtype: BF16 Q/K/V and output; no descales. FP16 and FP8 never take it.
  • Shape: head dims 256/256; varlen (THD) with max_seqlen_q == max_seqlen_k > 0 and equal
    Q/K/V token counts; nhead_q % nhead_k == 0, any ratio; Q and K pass the same cu_seqlens
    tensor (same data_ptr, shape, int32, contiguous), so every document has the same Q and K
    length.
  • Mask: none, or causal without a window (window_size_left == -1, right -1 or 0).
  • Excluded inputs: padded cu_seqlens, block_table, dropout, bias/ALiBi, soft cap, sink,
    min_seqlen_q, return_softmax, zero_tensors, an out of another shape/dtype/device.
  • Environment: AITER_FMHA_V4_THD not 0, and mha_v4 importable (Triton installed).

Invariant: one cu_seqlens array for Q and K is the only host-visible proof that every document has
the same Q and K length; equal totals and maxima are not enough (CI's test_mha_varlen.py inputs
hit exactly that). The gate checks tensor identity, not contents, so it never syncs with the
device. Inside mha_v4, the THD launcher checks the tensors again (TORCH_CHECK on ranks, dtypes,
devices, head counts, unit-stride head dim, and every byte stride fitting its 32-bit kernarg slot)
and raises rather than computing a wrong result. A call that fails the gate keeps its current
path.

Changed op tests

aiter/test_mha_common.py: generate_qkv(..., qkvpacked=True) returns one cu_seqlens tensor for
Q and K, as packed self-attention callers pass it. Before, it built two equal tensors, so
-i QKVPACKED never reached this path.

op_tests/test_mha_varlen.py:

  • New test_flash_attn_varlen_func_thd_hd256 (gfx950 only; skipped without Triton or with
    AITER_FMHA_V4_THD=0): three ragged documents, 12 heads, d=256 BF16, GQA ratios 1 and 6, causal
    and non-causal, plus one 2-slice KV-split case. It asserts the THD kernel launched and that
    _lse_merge_kernel launched only when splitting, and checks forward and backward against the
    file's torch reference with its tolerances. CI runs this file as a script, so __main__ also
    runs these cases when -d_qk_v includes 256,256 and -dt includes bf16. No existing test
    reaches this path: the default sweep gives Q and K different lengths.
  • __main__ skips the seq-padding benchmark when its fixed SEQ_PADDING_NHEADS = 8 is not
    divisible by -gr (for example -gr 6), instead of failing its assert and losing the summary
    table of the main test. That benchmark always passes padded cu_seqlens, which this path does
    not take, so skipping it loses no coverage of this change.

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

@JohnNikolay84
JohnNikolay84 marked this pull request as ready for review November 25, 2026 18:43
@JohnNikolay84
JohnNikolay84 requested a review from a team November 25, 2026 18:43
@github-actions github-actions Bot changed the title fmha hd256 bf16 in mha_v3 [ASM] [HIP] fmha hd256 bf16 in mha_v3 Nov 25, 2026
@aiter-bot

aiter-bot commented Nov 25, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 5df453694419 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

`aiter.flash_attn_varlen_func` on gfx950 with BF16 hd256 Q/K/V runs the forward of packed
self-attention (Q and K sharing one `cu_seqlens` tensor, no padding) on `mha_v4`'s THD kernels,
MHA and GQA, causal or not. Before this change, MHA calls used the slower v3 group kernels and GQA
calls fell back to CK, and the THD kernels could not be used for training because `mha_v4` has no
backward. The backward path is unchanged and consumes the output and LSE `mha_v4` returns. The PR
adds no kernel and no launcher: `mha_v4`'s code objects and launcher are the only copy.

Validation and unverified scope

Hardware: MI355X (gfx950, 256 CUs), ROCm 7.2, PyTorch 2.13, Triton 3.9. All runs at 10d3c4e2;
5df45369 has the same `aiter/` code, rebased on main, plus the `test.sh` deselects.

CI at 5df45369 passed, including the MI35X standard tests, which run `op_tests/test_mha_varlen.py`
as a script (its `-d_qk_v` sweep and the THD cases from `__main__`), and both Flash Attention
Triton jobs.

`op_tests/test_mha_varlen.py`:

- `python3 -m pytest op_tests/test_mha_varlen.py -k thd_hd256`: 5 passed (one-slice MHA and GQA,
  causal and not, and a 2-slice case that checks `_lse_merge_kernel` runs).
- Every performance command above passed the test's forward and backward checks against its torch
  reference, except 24/4 heads at 32K, where the reference ran out of memory. The profiler showed
  `fmha_fwd_hd256_bf16_varlen[_causal]` in every "after" run and `_lse_merge_kernel` only in the
  `auto` runs.

An ad-hoc script calls `aiter.flash_attn_varlen_func` with `return_lse=True` against an FP32
per-document reference (FP32 autograd for gradients) and checks the launched kernels: 60/60 pass.

- One slice (default): heads 16/16, 24/4, 12/2, 6/1 and 32/8; ragged packs with 0, 1, 255, 256 and
  257-token documents and documents up to 8192 tokens; packed (strided) QKV; causal and
  non-causal; backward for 16/16, 24/4 and 6/1.
- KV splits: forced 2, 3 and 4 slices for 6/1, 12/2 and 24/4, causal and non-causal, over packs
  whose 0- and 1-token documents leave slices without keys for some rows; `auto`; backward with 4
  slices and with `auto`.
- Stays off this path: a separate `cu_seqlens_k` tensor with equal contents (MHA: v3 group kernel;
  GQA: CK), forward and backward; per-document Q and K lengths that differ while totals and maxima
  match; `AITER_FMHA_V4_THD=0`.

Errors on the `mha_v4` rows: max |O error| <= 0.0104 on the forward packs (previous kernel: 0.0132)
and <= 0.0154 on the backward packs; max |LSE error| < 1e-5 (previous kernel: 0.0042); max
dQ/dK/dV relative error <= 0.0061.

Packs over 4 GiB (16/16 heads, Q/K/V/O each 4.07 GiB, 535 documents): the default (one slice)
passes. With KV splits requested, `mha_v4` raises `per-slice output stride ... does not fit the
32-bit kernarg slot` instead of computing: its split resolver does not drop to one slice when the
FP32 partials pass 4 GiB. That is opt-in only and a `mha_v4` limit.

Unverified:

- MI350X was not rerun at this revision.
- Host overhead: a call through `mha_v4()` costs a few microseconds more on the host than the
  previous C++ path; the times above include it.
- Direct C++ callers of `fmha_v3_varlen_fwd` / `mha_fwd()` do not reach these kernels; only
  `flash_attn_varlen_func` routes to them.
- When FlyDSL is installed, it can take inference (no-grad) calls before this path.
- The existing hd256 varlen backward kernels return wrong gradients for packs over 4 GiB. That
  predates this PR and needs a separate fix in those kernels.

PR-specific question

**Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant
prevents unsupported inputs from reaching it?**

The `mha_v4` branch of `_flash_attn_varlen_forward` is taken only when `can_impl_fmha_v4_thd()`
holds:

- **Architecture:** gfx950 (`get_gfx() == "gfx950"`).
- **Dtype:** BF16 Q/K/V and output; no descales. FP16 and FP8 never take it.
- **Shape:** head dims 256/256; varlen (THD) with `max_seqlen_q == max_seqlen_k > 0` and equal
  Q/K/V token counts; `nhead_q % nhead_k == 0`, any ratio; Q and K pass the same `cu_seqlens`
  tensor (same `data_ptr`, shape, int32, contiguous), so every document has the same Q and K
  length.
- **Mask:** none, or causal without a window (`window_size_left == -1`, right -1 or 0).
- **Excluded inputs:** padded `cu_seqlens`, `block_table`, dropout, bias/ALiBi, soft cap, sink,
  `min_seqlen_q`, `return_softmax`, `zero_tensors`, an `out` of another shape/dtype/device.
- **Environment:** `AITER_FMHA_V4_THD` not `0`, and `mha_v4` importable (Triton installed).

Invariant: one `cu_seqlens` array for Q and K is the only host-visible proof that every document has
the same Q and K length; equal totals and maxima are not enough (CI's `test_mha_varlen.py` inputs
hit exactly that). The gate checks tensor identity, not contents, so it never syncs with the
device. Inside `mha_v4`, the THD launcher checks the tensors again (`TORCH_CHECK` on ranks, dtypes,
devices, head counts, unit-stride head dim, and every byte stride fitting its 32-bit kernarg slot)
and raises rather than computing a wrong result. A call that fails the gate keeps its current
path.

Changed op tests

`aiter/test_mha_common.py`: `generate_qkv(..., qkvpacked=True)` returns one `cu_seqlens` tensor for
Q and K, as packed self-attention callers pass it. Before, it built two equal tensors, so
`-i QKVPACKED` never reached this path.

`op_tests/test_mha_varlen.py`:

- New `test_flash_attn_varlen_func_thd_hd256` (gfx950 only; skipped without Triton or with
  `AITER_FMHA_V4_THD=0`): three ragged documents, 12 heads, d=256 BF16, GQA ratios 1 and 6, causal
  and non-causal, plus one 2-slice KV-split case. It asserts the THD kernel launched and that
  `_lse_merge_kernel` launched only when splitting, and checks forward and backward against the
  file's torch reference with its tolerances. CI runs this file as a script, so `__main__` also
  runs these cases when `-d_qk_v` includes `256,256` and `-dt` includes `bf16`. No existing test
  reaches this path: the default sweep gives Q and K different lengths.
- `__main__` skips the seq-padding benchmark when its fixed `SEQ_PADDING_NHEADS = 8` is not
  divisible by `-gr` (for example `-gr 6`), instead of failing its assert and losing the summary
  table of the main test. That benchmark always passes padded `cu_seqlens`, which this path does
  not take, so skipping it loses no coverage of this change.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • PASS — Aiter Test Gate: passed

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

@slippedJim

Copy link
Copy Markdown
Contributor

@aiter-bot review

@JohnNikolay84
JohnNikolay84 force-pushed the fmha-v3-fwd-thd-hd256 branch 3 times, most recently from 9bddfbf to 12f6a94 Compare November 27, 2026 10:54
@JohnNikolay84

Copy link
Copy Markdown
Contributor Author

FA failures look like an issue on main related to triton kernel, not asm

@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. Getting the THD kernels behind flash_attn_varlen_func is exactly the follow-up #8067 left open, and the numbers are great 👌 I also like the gate: requiring one cu_seqlens tensor for Q and K avoids a sync, and the new test goes through backward.

My concern is with how the kernel gets there. As far as I can tell this PR doesn't route to the v4 kernel, it adds a second copy of it inside v3:

  • fwd_hd256_bf16_varlen.co and fwd_hd256_bf16_varlen_causal.co under hsa/gfx950/fmha_v3_fwd/ are byte-identical to the ones in fmha_v4_fwd/ (same git blobs).
  • init_fmha_fwd_v3_thd_args and the THD branch of fmha_fwd_v3 repeat fmha_v4_fwd_thd: the kernarg fill, the KV-split descriptor at 0x1E0 (here through the ptr_qseq_padding slot), the grid sizing and the pair_extra rule.
  • The v4 manifest carries kv_range and pair_split for these rows and the v4 launcher reads them. Here they turn into "mode 3" and "causal" in code.
  • fmha_fwd_v3_thd_kv_splits re-implements _resolve_thd_kv_splits from mha_v4.py in C++.
  • thd_kv_split_merge_kernel is a second LSE merge next to lse_merge.

This worries me for this kernel in particular because its launch contract is tight and we already got it wrong once. In #8067 the launcher sized the grid from max_seqlen while the kernel decided per document, which gave GPU memory faults and a few wrong outputs that the test suite didn't catch. Fixing it meant rebuilding both objects, changing the launcher and adding a manifest column, all together. With two copies of the objects and two launchers, nothing makes the next rebuild update both. The coverage is uneven too: test_mha_v4.py has nine THD test functions (the slice layouts from that fault, packs past 4 GiB, the check that pair-split rows load cu_budget), all on the v4 copy, while the v3 copy gets five cases, one of them with slices. And the v4 launcher is changing right now (#8684, #8801).

The alternative I have in mind is a Python dispatch. _flash_attn_varlen_forward already selects other backends that way before it reaches v3 and CK (the OPUS varlen kernels, the gfx1250 ASM path), so one more branch behind your is_fmha_v3_thd_bf16_hd256() gate could call the v4 launcher:

  • mha_v4(..., cu_seqlens=..., max_seqlen=..., causal=..., return_lse=True) returns the BF16 output and an FP32 [heads, total] LSE, the layout fmha_v3_varlen_fwd returns, so FlashAttnVarlenFunc and the backward wouldn't change.
  • The first revision of #8067 had this routing in about 50 lines of mha.py (213c33e). We only took it out so it could come back tested through this entry point, backward included.
  • Your own measurement has the two entry points running these kernels within 1% of each other, so the copy isn't buying speed.
  • The PR would shrink to mha.py and the tests: no second set of objects, and no changes to mha_fwd.cu, mha_fwd.h, asm_mha_varlen_fwd.cu or the v3 CSV.

So my main question: what was the reason for copying the kernels and their launcher into v3 instead of dispatching to mha_v4 from Python? The one thing I can see the copy buying is that direct C++ callers of fmha_v3_varlen_fwd / mha_fwd() reach the kernel too, but only when they pass the same offsets array for Q and K. Is there such a caller, or another constraint I'm missing (the lazy import of mha_v4, its JIT module, something on the training side)? If there is one, could we at least keep a single copy of the objects and a single launcher that both entry points call?

Two smaller things:

  • KV splits are chosen by AITER_FMHA_V3_FWD_THD_KV_SPLITS, a process-wide setting for what mha_v4 takes per call (kv_splits=). With the Python dispatch the same variable could simply feed that argument.
  • Agreed on the red Flash Attention check: it aborts in the Triton test_flash_attn_output at head dim 128, which doesn't go through this code.

To be clear about what I checked: this is from reading the diff at 12f6a94, I haven't run it on a GPU. Reading it, I didn't find a correctness problem in the new path itself; the Python and C++ gates agree on the cases I traced (causal and window handling, padded lengths, GQA). My concern is the duplication, not the behavior.

@JohnNikolay84

Copy link
Copy Markdown
Contributor Author

Added a WA for FA integration ( removed 2 tests )

The two removed tests are the alibi=True variants (kvpacked True and False) of the one configuration that crashes: dropout 0.17, 2048×2048, head dim 128, causal, MHA. Its alibi=False variants were already skipped for the same Triton bug.

@JohnNikolay84

Copy link
Copy Markdown
Contributor Author

@jcaraban as the description says, running this through flash_attn_varlen_func for training is tricky, because v4 has no support for bwd kernel whatsoever.

@jcaraban

Copy link
Copy Markdown
Contributor

Thanks John. I think we mean two different things here, so let me separate them.

You're right that mha_v4 has no backward and no autograd wrapper, so nobody can train by calling mha_v4 directly. That isn't what I'm proposing. flash_attn_varlen_func stays the entry point and FlashAttnVarlenFunc stays the autograd function. Only the forward launch inside _flash_attn_varlen_forward would go to the v4 launcher, instead of to a second copy of that launcher in mha_fwd.cu.

That works because the backward doesn't depend on which launcher ran the forward:

  • FlashAttnVarlenFunc.backward hands _flash_attn_varlen_backward the saved Q, K, V, output, LSE and cu_seqlens, and that function picks its kernel from arch, head dim, dtype and mask.
  • This PR doesn't add or change a backward kernel either. It pairs the THD forward with the existing hd256 backward through the saved output and LSE; the description says "the backward path is unchanged and consumes the LSE written by the new forward".
  • _flash_attn_varlen_forward already does this for other kernels. The gfx1250 ASM forward is its own launcher and JIT module, and the OPUS varlen forward has no backward of its own. The gfx1250 branch even notes "FlashAttnVarlenFunc needs return_lse for backward".

To be sure, I tried it on an MI355X. On top of b7fab68 I added one branch to _flash_attn_varlen_forward, behind your is_fmha_v3_thd_bf16_hd256() gate, that calls mha_v4(..., cu_seqlens=..., return_lse=True) (code at the end). Then I ran flash_attn_varlen_func forward and backward through both routes on the same inputs:

  • One slice, 7 cases (MHA 12/12, GQA 12/2, 24/4 and 6/1, causal and not, documents of 31 to 4096 tokens): output, LSE, dQ, dK and dV are bit-identical between the two routes. Both launch the same forward kernel (fmha_fwd_hd256_bf16_varlen[_causal]) and the same backward kernels (fmha_bwd_hd256_odo_bf16_group and fmha_bwd_fused_dkdv_dq_hd256_bf16_[non]causal_varlen).
  • Two slices (6/1 causal, 12/2 non-causal): the routes differ slightly (max |O| difference 0.0005, gradients up to 0.004), because lse_merge and thd_kv_split_merge_kernel are different code. Their errors against an FP32 autograd reference are the same to three digits.
  • Your test_flash_attn_varlen_func_thd_hd256: 5 passed as the PR ships it. Through the v4 route the four one-slice cases pass unchanged. The 2-slice case fails only the assertion on the merge kernel's name; with lse_merge as the expected name it passes its forward and backward checks.

The Python route has two costs, so they're on the table:

  • Host overhead: the forward call took 5 to 9 us longer through mha_v4() (97.7 vs 106.4 us for MHA 12/12 over 2057 tokens, 191.6 vs 196.8 us for GQA 6/1 causal at 4K). Backward time was the same within 1%. I haven't tried to trim it.
  • mha_v4.py imports Triton at module level (for lse_merge and arch_info), so the branch needs Triton installed. mha.py already imports Triton modules lazily in other places.

So, is there something else that needs the kernels and their launcher inside v3? If it is a direct C++ caller of fmha_v3_varlen_fwd / mha_fwd(), or one of the two costs above, could we still keep one copy of the objects and one launcher that both entry points share? Two copies have to be kept in step by hand, and that is the part I'd like to avoid.

The branch I tested (inserted before elif can_impl_fmha_v3_fwd():; the env var only switches routes for the comparison)
    elif (
        os.environ.get("AITER_THD_ROUTE") == "v4"
        and is_fmha_v3_thd_bf16_hd256()
        and k.dtype == dtypes.bf16
        and v.dtype == dtypes.bf16
        and nhead_q % nhead_k == 0
        and dropout_p == 0.0
        and logits_soft_cap == 0.0
        and bias is None
        and alibi_slopes is None
        and sink_size == 0
        and sink_ptr is None
        and q_descale is None
        and k_descale is None
        and v_descale is None
        and not return_softmax
    ):
        from .mha_v4 import AttentionFormat, mha_v4

        thd_splits = os.environ.get("AITER_FMHA_V3_FWD_THD_KV_SPLITS", "1")
        out, softmax_lse = mha_v4(
            q,
            k,
            v,
            AttentionFormat.BF16,
            AttentionFormat.BF16,
            AttentionFormat.BF16,
            softmax_scale=float(softmax_scale),
            out=out,
            return_lse=True,
            kv_splits=thd_splits if thd_splits == "auto" else int(thd_splits),
            cu_seqlens=cu_seqlens_q,
            max_seqlen=int(max_seqlen_q),
            causal=bool(causal) or window_size_right == 0,
        )
        S_dmask = torch.empty((0,), dtype=torch.float32, device=q.device)
        rng_state = torch.empty((2,), dtype=torch.int64, device=q.device)

@github-actions github-actions Bot changed the title [ASM] [HIP] [CI] fmha hd256 bf16 in mha_v3 [CI] fmha hd256 bf16 in mha_v3 Nov 29, 2026
@JohnNikolay84 JohnNikolay84 changed the title [CI] fmha hd256 bf16 in mha_v3 [MHA] Route flash_attn_varlen_func gfx950 hd256 BF16 THD forward to mha_v4 Nov 30, 2026
@JohnNikolay84

Copy link
Copy Markdown
Contributor Author

Thanks @jcaraban , agreed. The PR now dispatches to mha_v4 from _flash_attn_varlen_forward, as you suggested: no copied .co files, no second launcher or merge kernel, no v3 CSV or C++ changes. The KV-split variable feeds mha_v4's kv_splits=. The description has updated MI355X numbers through flash_attn_varlen_func.

@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! here my empty approval (づ ᴗ _ᴗ)づ🎁

@JohnNikolay84

Copy link
Copy Markdown
Contributor Author

@slippedJim could you approve the PR? This kernel is needed for a customer to support training ( fwd + bwd).

@valarLip
valarLip merged commit d9a0a30 into main Dec 3, 2026
78 checks passed
@valarLip
valarLip deleted the fmha-v3-fwd-thd-hd256 branch December 3, 2026 02:00
AndreasKaratzas added a commit that referenced this pull request Dec 3, 2026
Conflict in op_tests/test_mha_varlen.py: keep main's SEQ_PADDING_NHEADS
next to the PR's EXPANDED_LAYOUTS and expanded-inputs test.

Main's #8704 routes gfx950 hd256 BF16 self-attention to mha_v4's THD rows,
which misread a token stride of 0 the same way the v3/OPUS kernels do
(expanded q/k/v: out off by up to 3.3, no error). Add the same token
stride check to can_impl_fmha_v4_thd so such inputs go to CK, and run the
expanded-inputs test at hd256 too, with one cu_seqlens tensor so it takes
the v4 route.

Co-authored-by: Claude <[email protected]>
Signed-off-by: Andreas Karatzas <[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.

5 participants