Repository navigation
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
483c783 to
213c33e
Compare
jcaraban
left a comment
There was a problem hiding this comment.
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 andcausalwould then be capabilities of that path rather than a separatemha_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_funcrouting inaiter/ops/mha.pyto 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 reservedptr_qseq_paddingslot and inferring split mode fromout.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.
|
@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:
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. |
The new binaries are kv_tile=64 What the THD object adds that #7939's does not cover:
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). |
WAITING ON AUTHORPR Self-ReviewRevision 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
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
jcaraban
left a comment
There was a problem hiding this comment.
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:
- GPU memory fault with valid arguments.
kv_splits=5on a 1536-token causal document faults for 6/1 and 12/2 heads;kv_splits=4is 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_FAULTmax_seqlenabove the longest document now gives wrong output (3 of 87 calls) or a fault (6 of 87). Details inline.- 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.
There was a problem hiding this comment.
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=5fault is gone: the same 174-call scan (single causal documents, exact and overstatedmax_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_seqlenoverstated 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
_gfx950suffix 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.
…-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]>
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]>
f523493 to
40caeca
Compare
Summary
Two gfx950 kernels for attention over whole documents in THD: Q/K/V
[total, H, 256]delimited by onecu_seqlens, anyHq % 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,mask0/1, both declaringkv_range, and apair_splitcolumn 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_thdlauncher with an explicitkv_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 Tritonlse_mergekernel.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.op_tests/test_mha_v4.py, timing inop_tests/op_benchmarks/hip/bench_mha_v4_thd.py.Not in this PR: routing
flash_attn_varlen_functo 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
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"):mha_v4(06729c3 against b3511b6) does not change device time: geomean ratio 1.001.Testing
Documentation
aiter/ops/mha_v4.mddescribes the THD mode.Dependencies
Breaking Changes
None.
mha_v4gains three optional keyword arguments.PR Self-Review
Reviewed revision
e707d43
Behavior and intent
mha_v4gains THD operands: withcu_seqlensandmax_seqlenit attends over each document of a concatenated pack, with an optional causal mask, on two new gfx950 BF16 hd256 kernels. Until nowmha_v4took 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, andpython3 op_tests/test_mha_v4_sparse.py: 609 ran, 5 skipped, 0 failed (CI, on the merge with main).kv_splits2 to 6, 4 to 12 Q tiles,max_seqlenexact and overstated by 512) and 600 random packs (1 to 5 documents, both masks, 1 to 9 slices,max_seqlenoverstated 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 whattest_mha_v4_bf16_hd256_thd_causal_slice_layoutsnow covers.max_seqlentwo tiles short, slices left unmerged and a document left unwritten in the 4 GiB pack.Unverified: MI350X was not run. Only a 256-CU device was run, so the
kv_splits + 1layout against another CU count rests on the kernel readingcu_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=...), andfind_configselects them by arch (gfx950), all-BF16 formats, head dimension 256, mode 3 and themaskcolumn fromcausal. Every other lookup passesmask=0and its own mode, as before, so no existing call can land on them.Before launching,
mha_v4refuses other formats, BSHD operands,block_maskandseqlens_k;find_configraises 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, thecu_seqlensdtype and layout, theoutand LSE layouts againstkv_splits, and that a row sliced bykv_splitsdeclareskv_range. Only a row declaringpair_splitgets the CU count and the larger grid. The contents ofcu_seqlensstay the caller's contract, since checking them would synchronize every launch;max_seqlenmay 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 overstatedmax_seqlen, a pack whose operands each pass 4 GiB, compile parity, and the callsmha_v4and the launcher refuse. A disassembly gate checks that the row declaringpair_splitloads the CU count. No existing test reaches mode 3 rows, a causal mask orcu_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.