Repository navigation
[Triton/Gluon] MHAv4 split-KV - #6560
Conversation
A dense launch runs one work-group per (batch, head, 256-row query tile), so a short sequence with few heads leaves most CUs idle: [1, 4352, 3, 128] fills 51 of MI355X's 256. mha_v4(kv_splits=n) folds n equal key ranges into the batch of one launch, Q repeated as a stride-0 view and K/V cut as views, then merges the partials by their LSE in a new Triton kernel (lse_merge). Operands are quantized before the split, so per-tensor scales and the LSE bias stay global and cancel in the merge. kv_splits="auto" takes the largest n that keeps the grid in one wave, divides Sk and leaves ranges of at least 512 keys (mha_v4_kv_splits); a grid that already fills the GPU gets 1. Supported for BF16, BF16/FP8, INT8/FP8 and FP8/FP8 on gfx950, without block_mask or seqlens_k; the MX recipes pack K/V in tiles no key range can be cut from. Explicit counts outside that raise, "auto" falls back to the unsplit call. The default stays 1. At [1, 4352, 3, 128] under HIP graphs, BF16 goes from 74 to 36 us, BF16/FP8 from 63 to 37 us and FP8 from 132 to 121 us, with the same error against FP32 attention. At 32 heads auto picks 1 and costs nothing; any split there is slower. Eager calls to the launch custom ops now run their bodies directly and keep the op for torch.compile. A mutating custom op's Python dispatch cost ~55 us per call, most of the host time of a launch; BF16 mha_v4 drops from 72 to 15 us of host time. Also fix _restore_k_mean_in_lse under GQA: it applied a K-head mean to Q heads, so return_lse failed for any quantized K with fewer KV heads. Signed-off-by: Niko Säkkinen <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
kv_splits merges its key ranges by their LSE, so where it may split is where MHA v4 exports one. "auto" asked for gfx950 by name instead; it now asks the LSE gate for the call's Q and V formats, which admits the same four per-tensor recipes on gfx950 as before. An arch whose LSE is validated later gets auto with it, without another arch check here. An explicit count crashed with a TypeError: _resolve_kv_splits called _check_lse_capable() without its operands. It now passes Q and V, so a count on an arch or recipe without LSE raises the gate's NotImplementedError. mha_v4_kv_splits sizes the split from the device's own CU count, so each SKU and partition mode gets its own: [1, 4096, 1, 8192] splits 16 ways on MI300X and MI355X, 8 on MI300A and 4 on MI308X. A test pins that, and another checks auto and the explicit count against a refused LSE gate. Signed-off-by: Niko Säkkinen <[email protected]>
kv_splits needed a count that divides the key length, so a prime or odd Sk could not split at all and "auto" settled for a smaller divisor: [1, 4352, 3] on 256 CUs fits 5 ranges in one wave but took 4. Range i now starts at key i * (Sk // n) and spans Sk // n + Sk % n keys, so the ranges overlap by the remainder and the last one ends at Sk. A per-range seqlens_k cuts every other range back to Sk // n, so each key is attended once. The fold stays a view when B is 1 or n divides Sk. Otherwise K and V are copied once, as Q already is for B > 1. An even split passes no seqlens_k and runs as before. This needs a dense row that takes per-batch key lengths: BF16 and BF16/FP8 on gfx950. mha_v4_kv_splits gains ragged=False, which auto sets for those operands. INT8/FP8 and FP8/FP8 still need a divisor and raise a ValueError saying so. A count above the key length now raises too. _varlen_capable is split out of _check_varlen_capable so auto can ask without raising. Also drop the comment about the gfx942 code objects from _lse_unsupported. The tests cover a fold that reproduces every key once and is a view only when it should be, the ragged heuristic, and uneven counts (splits=3, and a B=2 GQA shape with Sk=1001) in the unsplit-accuracy test. Signed-off-by: Niko Sakkinen <[email protected]>
hellozhuo-amd
left a comment
There was a problem hiding this comment.
Thanks for the split-KV work; on gfx950 the speedup reproduces, but 3 new tests fail (compile parity x2, block-mask shape) and there's an int32 overflow risk in the merge kernel, so please see the inline comments.
Signed-off-by: Niko Säkkinen <[email protected]> # Conflicts: # aiter/ops/mha_v4.py # op_tests/test_mha_v4.py
_fold_key_ranges built the overlapping key ranges with as_strided, whose storage_offset() Dynamo cannot trace, so kv_splits broke a fullgraph compile. unfold gives the same view without it. test_mha_v4_kv_splits_auto_leaves_unsupported_calls_unsplit built its block mask for a 256x64 tile; the gfx950 BF16 sparse row is 256x128. Signed-off-by: Niko Säkkinen <[email protected]>
Main extended seqlens_k to the FP8/FP8 and INT8/FP8 rows, so on gfx950 every recipe kv_splits accepts can now end its last key range short, and a count no longer has to divide the key length. - Correct the docstring, which still limited the remainder to BF16 and BF16/FP8. - Cover the divisor requirement with a row whose per-batch key lengths are patched away, since no gfx950 kv_splits recipe hits it any more; drop the FP8 case that expected the error. - Bound the split LSE error relative to the unsplit one. Splitting moves it by noise on the order of the recipe's own quantization error: under 0.001 nats for BF16, but up to 0.036 for FP8 Q/K against an unsplit error of ~0.55, on even splits as well as uneven ones. Signed-off-by: Niko Säkkinen <[email protected]>
Derive the key-tile count from mha_v4_kv_tile(), as the other sparse tests do, rather than restating gfx950's 256x128 geometry. Signed-off-by: Niko Säkkinen <[email protected]>
The merge reached split i at i * stride_po_b, which Triton computes in the stride's 32 bits, so it faulted once (splits - 1) * S * H * D passed 2^31. The row offset rows * stride_po_s overflowed the same way within a single partial once S * H * D passed 2^31, even with one split. Make the batch, head and row offsets 64-bit and reach each split by stepping the pointers. Speed and output are unchanged. Add a test at both sizes that puts all weight on the last split, so the merge must return it exactly. Signed-off-by: Niko Säkkinen <[email protected]>
Since main let all four split-capable recipes take per-batch key lengths, auto took the largest count that fits one wave and let the last range take the remainder: 5 at [1, 4352, 3, 128], where 4 divides the keys. A remainder builds seqlens_k with two kernels per call (~3 us replayed, ~14 us of host time), and past batch 1 the key ranges stop being a view, so K and V are copied: [2, 4352, 2] ran 86 us at 3 splits against 70 us unsplit. Take the largest dividing count that fits, and fall back to a remainder only at batch 1 when no count divides. Across batch-1 shapes on MI355X a divisor above half the fit was faster replayed and eager; below half, replayed BF16 gained up to 17 us from the extra splits, while eager calls and replayed FP8 still favoured the divisor. At [1, 4352, 3, 128] auto now replays in 41 us instead of 46 us for BF16. Document that auto minimizes device time and is meant for graph-replayed or compiled callers: a split adds ~35 us of host time per eager call. Signed-off-by: Niko Säkkinen <[email protected]>
The tile was a literal 32 x 4 with no record of how it was chosen. Move it into configs/gfx950/triton/attention/lse_merge/DEFAULT.json, read through get_tuned_kernel_config, so a sweep can see and change it. Swept BLOCK_M 8/16/32/64/128 x num_warps 1/2/4/8 on MI355X with graph replay, over the kv_splits shapes of mha_v4 ([1, 4352, 3] at 2/4/8 splits, [1, 8192, 3] at 2, [1, 3586, 1] at 7, [1, 5000, 2] at 5, [2, 4352, 1] at 4) and [1, 16384, 8] at 4, each with and without the merged LSE. 16 x 4 was within 1.7% of each shape's best on average and 32 x 4 8% behind, up to 27% at [1, 3586, 1] x 7 (2.55 -> 2.01 us). Other archs keep 32 x 4 as the fallback until measured. Signed-off-by: Niko Säkkinen <[email protected]>
mha_v4 gives every key range real keys, so the merge's guards for a range without any (LSE -inf) were never run. Test the merge against a torch reference with a range empty for every row, rows empty in only some ranges, and rows empty in all of them, which must merge to a 0 output and LSE -inf rather than NaN. Dropping either guard, on the max or on the total weight, makes it fail. Signed-off-by: Niko Säkkinen <[email protected]>
Zero partials divide evenly into any batch, so splits came out 0 and the merge silently wrote a 0 output and LSE -inf. Raise ValueError instead. mha_v4 only merges with kv_splits >= 2, so this only reaches direct callers. Signed-off-by: Niko Säkkinen <[email protected]>
|
are you enforcing a max upper-bound to |
kv_splits="auto" already leaves every range at least 512 keys, but an explicit count was only checked against the key length, so it could cut ranges down to a single key. That stays accurate: on MI355X even 3-4 keys per range match the unsplit call. But a range shorter than a KV tile still costs a whole tile, so those splits only add work-groups and merge traffic. Q [1, 1000, 3, 128] over 1024 BF16 keys takes 25 us unsplit, 28-31 us at 4-16 splits, 40 us at 64 and 128 us at 256. The merge also unrolls over the split count, and its cold compile grows from 2.2 s at 64 splits to 13.4 s at 128; kv_splits=1024 had not finished compiling after two minutes. Reject explicit counts above key_length // mha_v4_kv_tile(), so every range holds at least one KV tile, test the bound and its inclusive edge, and document it. Signed-off-by: Niko Säkkinen <[email protected]>
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
Good catch. |
benchmark_mha_v4 only timed the unsplit path, so the kv_splits table in the PR description could not be regenerated. Add kv_splits and timing parameters, with --kv-splits (ints or "auto") and --timing (profiler|graph|eager) in main(): - graph: median of 100 replays of a HIP graph holding 10 calls - eager: median of 50 samples of 20 calls, issue to synchronize, plus the time to issue them alone as "host us" Split counts other than 1 time only the recipes that split, and "auto" records the count it picked. Calls write into a preallocated out. The profiler timing stays the default. Signed-off-by: Niko Säkkinen <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Empty partial ranges can still contaminate merged outputs with NaNs, and the runtime capability check uses build-time architecture information instead of the live GPU.
4 open issues
What changed in this PR
This PR adds optional split-KV execution to MHA v4 to improve GPU use for short sequences with few heads. It merges partial attention results by log-sum-exp and keeps the default execution unsplit.
Changes:
- Adds explicit and automatic split counts, capability checks, and key-range folding.
- Adds a Triton merge kernel with gfx950 tuning and bypasses custom-op dispatch for eager launches.
- Extends correctness tests and graph/eager benchmarks for split-KV execution.
| File | Description |
|---|---|
op_tests/test_mha_v4.py |
Adds split-KV tests and benchmark options. |
aiter/ops/triton/configs/gfx950/triton/attention/lse_merge/DEFAULT.json |
Adds gfx950 merge launch settings. |
aiter/ops/triton/attention/utils.py |
Adds the public merge wrapper and config lookup. |
aiter/ops/triton/_triton_kernels/attention/lse_merge.py |
Implements weighted partial-output merging with 64-bit offsets. |
aiter/ops/mha_v4.py |
Integrates split selection, range folding, merging, and eager launch dispatch. |
Review effort: Balanced
_varlen_capable used get_gfx(), which follows GPU_ARCHS, while the launcher dispatches on the live device. Use get_gfx_runtime() instead, behind a torch_compile_guard op, the same way get_gfx() hides its rocminfo probe: called directly, it makes torch.compile(fullgraph=True) fail on the subprocess. The new test reports a different build arch and checks that the gate still follows the GPU, eagerly and under fullgraph compile. Signed-off-by: Niko Säkkinen <[email protected]>
A range with LSE -inf for a row weighs exp(-inf - max) = 0, but the merge still loaded its partial output and multiplied it in, so a NaN or Inf there turned the merged row into NaN (0 * NaN = NaN). Mask the value load to rows the range reached. The empty-range test now fills every empty row's partial output with 1e4, NaN or Inf; the NaN and Inf cases fail without the mask. Signed-off-by: Niko Säkkinen <[email protected]>
aiter/ops/triton/README.md asks for a unit test under op_tests/triton_tests/ and a bench_<op>.py for each Triton wrapper. lse_merge only had tests in the standalone mha_v4 script. - op_tests/triton_tests/attention/test_lse_merge.py: compare with a torch merge over shapes, head dims, output dtypes and with and without the merged LSE; strided views; empty ranges with NaN and Inf partials; offsets past 2^31 elements; and each rejected argument. The three direct lse_merge tests move here from test_mha_v4.py. - op_tests/op_benchmarks/triton/bench_lse_merge.py: CUDA-graph timing over rotating buffers through do_bench_aiter_triton, on the shapes kv_splits="auto" makes or one --shape, with and without the LSE. Signed-off-by: Niko Säkkinen <[email protected]>
arch_info.get_arch() caches the live device's arch at import, so Dynamo reads it as a constant. That makes the torch_compile_guard op around get_gfx_runtime()'s rocminfo probe unnecessary. It still ignores GPU_ARCHS, which is what the gate needs. Signed-off-by: Niko Säkkinen <[email protected]>
Signed-off-by: Niko Säkkinen <[email protected]>
Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit.
Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it.
…-KV (#962) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * fix(mha-v4): regroup batched packed keys without a graph break A batch of several packed sequences is scattered back into a padded [batch, max_k] buffer before the MHA v4 launch. The row and slot of each packed key came from repeat_interleave over the lengths, whose output shape depends on their values, so torch.compile split the graph at this call in every transformer block. Search the cumulative boundaries instead: the output has the shape of the packed rows and the indices are the same, empty sequences included. Qwen-Image-Edit with batched true CFG on AITER_BF16 (8x MI355X, 2048x2048, measured on top of #962, where that backend is the default): 104 graph breaks and 41 recompiles go to 0, and a step batch goes from 12.14 s to 9.88 s.
…#966) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it.
) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(flux2): default FLUX.2-dev to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits on gfx950, FLUX.2-dev defaults to AITER_BF16 with kv_splits auto, except under PipeFusion, whose pipeline was not measured. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence.
…KV (#968) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(minimax-h3): default MiniMax-H3 to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits on gfx950, the base MiniMax-H3 runner defaults to AITER_BF16 with kv_splits auto. Its subclasses (FastH3, Turbo, VDN, Ref2VA) keep their own defaults since they were not measured, and so does --use_hybrid_attn_schedule, which refuses a set --attention_backend. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence.
* perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(flux): default FLUX.1-dev to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits on gfx950, FLUX.1-dev defaults to AITER_BF16 with kv_splits auto, except under PipeFusion, which runs FLUX.1 in FP16. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence.
…it-KV (#972) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(flux2-klein): default FLUX.2-klein to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits on gfx950, FLUX.2-klein-9B and -4B default to AITER_BF16 with kv_splits auto, except under PipeFusion, which runs them in FP16. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence.
* perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(z-image): default Z-Image to AITER MHA v4 BF16 with split-KV
…#977) * perf(aiter): compute FAv3 rows past the last full wave split-K The AITER FAv3 hd128 bf16 forward on gfx942/gfx950 gives each CU one 256-row query tile. Qwen-Image-Edit at Ulysses 8 launches 258 tiles on the 256-CU MI355X, so a second wave of 2 tiles costs as much as the first. Run the rows past the last full wave against K slices as varlen segments over all CUs and merge them by log-sum-exp. * perf(qwen): default Qwen-Image(-Edit) to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, Qwen-Image and Qwen-Image-Edit default to AITER_BF16. Edit uses a fixed 4-way split, because the joint edit sequence leaves too few query tiles for the split auto picks; Qwen-Image uses auto. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. Replaces the FAv3 last-wave split from the previous commit. * fix(config): keep an explicit --mha_v4_kv_splits 1 over the model default --mha_v4_kv_splits defaulted to 1, so the runner could not tell an explicit 1 from an omitted flag and replaced it with the model's split count. The flag now defaults to unset; the model default fills it in, and the runtime config resolves what is still unset to 1. * fix(qwen): only default to split-KV MHA v4 on gfx950 AITER exports the MHA v4 LSE, and so accepts kv_splits > 1, only on gfx950; on gfx942 AITER_BF16 is available but an explicit split count raises. Gate the Qwen default on gfx950 so MI300-series GPUs keep the global default. The test now drives the real arch check and patches only Qwen's split-KV gate. * perf(qwen): default Qwen-Image-Edit to MHA v4 kv_splits auto Needs ROCm/aiter#7942: its auto picks Edit's split from a wave-rounding cost model and runs the split in one op, so torch.compile neither breaks the graph nor recompiles across Edit's two CFG sequence lengths. With it, auto matches the fixed 4 on Edit 2048 (8x MI355X: 11.07 vs 11.10 s); without it, auto leaves Edit unsplit. * perf(flux): default FLUX.1-Kontext to AITER MHA v4 BF16 with split-KV Where AITER's mha_v4 takes kv_splits (ROCm/aiter#6560) on gfx950, FLUX.1-Kontext-dev defaults to AITER_BF16 with kv_splits auto. At 1024x1024 with Ulysses 8 each rank attends 3 heads over ~8.7k tokens, too few query tiles to fill the GPU, which the split fills. An explicit --attention_backend or --mha_v4_kv_splits keeps precedence. prefer_mha_v4 moves from the Qwen runner to base_model so both use it. * perf(qwen): default Qwen-Image-2.1 to AITER MHA v4 BF16 with split-KV * fix(config): defer torch import in attention output codecs


MHAv4: split short sequences over the keys with
kv_splitsMotivation
A dense
mha_v4launch runs one work-group per (batch, head, 256-row query tile). A short sequence with few heads therefore leaves most of the GPU idle:[B, S, H, D][1, 4352, 3, 128][1, 4352, 8, 128][1, 4352, 32, 128]Shapes like these (a few heads per rank after tensor or sequence parallelism, a few thousand tokens) are common in low-resolution image diffusion inference. This PR lets the kernel spread one such call over the keys as well as over the queries, and then merge the partial results by their log-sum-exp (LSE).
This PR also makes eager
mha_v4calls skip the Python dispatch of the launch custom ops, which was most of the host time of a small launch.What changes
mha_v4(..., kv_splits=1 | n | "auto"), default1(unchanged behaviour):The K/V sequence is cut into
nkey ranges, which are folded into the batch dimension of a single launch:_repeat_queries): a stride-0 view when B is 1, a copy otherwise._fold_key_ranges. Withstep = Sk // n, rangeistarts at keyi * stepand spansstep + Sk % nkeys, so the ranges overlap by the remainder and the last one ends atSk. WhenndividesSkthe ranges are equal. Otherwise a per-rangeseqlens_k(_key_range_lengths) cuts every other range back tostep, and each key is attended once.ndividesSk. An uneven split with B > 1 copies K and V once.The kernel writes
npartial outputs and partial LSEs. A new Triton kernel then merges them by LSE intoout(and intolsewhenreturn_lse=True).Operands are quantized before the split. Per-tensor scales and the K-mean LSE bias therefore stay global and cancel in the merge.
kv_splits="auto"calls the new public helpermha_v4_kv_splits(batch, query_length, query_heads, key_length, device=None, *, ragged=False). It picks the largestnthat:_MHA_V4_MIN_KV_SPLIT_TOKENS);Sk. Only when no such divisor exists, at B = 1 and withragged=True, does it take the largestnthat fits and let the last range take the remainder."auto"passesragged=Truefor operands whose dense row takes per-batch key lengths (all four supported recipes on gfx950). A divisor is preferred because a remainder costs two extra kernels per call to buildseqlens_k, and with B > 1 also a K/V copy, which costs more than the extra splits gain (see Performance). For example,[1, 4352, 3]on 256 CUs splits 4 ways: 5 would fit, but 4 divides 4352.A grid that already fills the GPU gets
1, so"auto"never splits a full grid. It minimizes device time and is meant for HIP-graph-replayed ortorch.compiled callers; eager callers should read the eager numbers under Performance. The CU count is the device's own (multi_processor_count), so each SKU and partition mode sizes its own split. For example,[1, 4096, 1, 8192]splits 16 ways on MI300X and MI355X, 8 ways on MI300A and 4 ways on MI308X.Whether a dense row takes per-batch key lengths (
_varlen_capable) is decided on the live GPU arch (get_gfx_runtime()), the arch the launcher dispatches on, not onGPU_ARCHS. The probe sits behind atorch_compile_guardop, so it stays traceable underfullgraph=True.New Triton kernel:
lse_mergeaiter/ops/triton/_triton_kernels/attention/lse_merge.pycontains_lse_merge_kernel. Its offsets are 64-bit, so partials past 2^31 elements (many splits of a long sequence, or a single large partial) are addressed correctly.aiter/ops/triton/attention/utils.pyaddslse_merge(partial_out, partial_lse, out, lse=None). It rejects partials that hold no key range.mha_v4it is wrapped as the custom opaiter::mha_v4_merge_kv_splits(with a fake implementation), sokv_splitsworks undertorch.compile.configs/gfx950/triton/attention/lse_merge/DEFAULT.jsonthroughget_tuned_kernel_config().op_tests/triton_tests/attention/test_lse_merge.py. Benchmark:op_tests/op_benchmarks/triton/bench_lse_merge.py.Eager calls bypass custom-op dispatch (
_launch_op)_launch_op(name)decorator. It registers the op as before, but an eager call runs the Python body directly; undertorch.compilethe registered op is still used.Fix:
_restore_k_mean_in_lseunder GQAreturn_lse=Truefailed for any quantized K with fewer KV heads than Q heads. It now appliesrepeat_interleaveover the head groups first.Benchmark:
benchmark_mha_v4inop_tests/test_mha_v4.pykv_splitsandtimingparameters, with--kv-splits(ints or"auto") and--timing profiler|graph|eagerinmain().graphandeagerare the methodology under Performance.profilerstays the default, so the CI output only gains the two columns."auto", the table also shows the count that"auto"picked.Constraints
kv_splitsfollows the LSE gate: gfx950 today. Elsewhere"auto"resolves to 1 and an explicit count raisesNotImplementedError.Sk // mha_v4_kv_tile()(128-key tiles on gfx950). A larger count raisesValueError. A shorter range still costs a whole tile, and the merge unrolls over the count, so its compile time grows steeply with it.Skneeds a dense row that takes per-batch key lengths (_varlen_capable). On gfx950 all four recipes have one; a row without it needs a divisor and raisesValueErrorotherwise.n × B × Sq × H × Dpartial outputs in the output dtype, plusn × B × H × SqFP32 LSE. With B > 1, Q is copiedntimes, and an uneven split also copies K and V once.Performance (gfx950)
Setup:
b5078fc49a(merge base); head = this branch.out.Methodology:
Reproduce:
benchmark_mha_v4gives the head columns for one shape. The file then runs its full check suite.The benchmark on main has no
--kv-splitsor--timing. Its column was measured with the same timing loops at the merge base. A rerun at14c39dd7a4gave BF16 69.4 / 40.6 / 40.6 µs under graph replay atkv_splits1 / 4 /"auto", and 70 / 50 / 53 µs eager.[1, 4352, 3, 128]: 51 work-groups on 256 CUs;"auto"picks 4.kv_splits=1"auto"kv_splits=1"auto"Other shapes: graph replay / eager e2e.
"auto")kv_splits=1"auto"[1, 8192, 3, 128](2)[1, 4352, 32, 128](1)Notes:
torch.compile(_launch_op).seqlens_k."auto"is meant for graph-replayed or compiled callers, andkv_splitsdefaults to 1, so eager callers are unaffected unless they opt in.[2, 4352, 2]: 86 µs at 3 splits against 70 µs unsplit), so"auto"only takes a remainder at B = 1.lse_merge, which adds one compare per loaded row. They were not timed again after it.Testing
op_tests/test_mha_v4.py(end to end, throughmha_v4):test_mha_v4_kv_splits_match_the_unsplit_call(gfx950): 4 recipes ×kv_splits ∈ {2, 3, 4}× (B=1 MHASq=1000, Sk=1024, H=3; B=2 GQASq=333, Sk=768, 4 Q / 2 KV heads; the same GQA shape withSk=1001). Keys escalate along the sequence so ranges carry very different softmax mass. Output and LSE error against FP32 attention stay within 1.1× of the unsplit call's (plus 1e-3 relative output error and 0.02 nats of LSE, the noise floor of splitting), and thereturn_lse=Falseoutput equals thereturn_lse=Trueone bit for bit.test_mha_v4_kv_splits_auto_fills_one_wave: the heuristic at 256 CUs fills one wave, dividesSk, keeps ranges ≥ 512 keys, and returns 1 for full grids and primeSk. Withragged=Trueit still prefers a divisor (4 ways forSk=4352). It takes a remainder only at B = 1 when no divisor exists (5 ways for the primeSk=4349), and returns 1 for thatSkat B = 2.test_mha_v4_kv_splits_fold_every_key_once: for B ∈ {1, 2} with even and uneven counts, the folded ranges cut to their lengths concatenate back to K exactly. The fold is a view only when B is 1 or the count dividesSk.test_mha_v4_kv_splits_rejects_what_it_cannot_split(gfx950): zero, non-int, a count aboveSk, a range shorter than a KV tile,block_mask,seqlens_k, MXFP4 and FP8/MXFP6 each raise the expected error.test_mha_v4_kv_splits_allow_one_kv_tile_per_range(gfx950): exactly one KV tile per range still runs and matches the unsplit call.test_mha_v4_kv_splits_need_a_divisor_without_per_batch_key_lengths(gfx950): with_varlen_capablepatched off, a non-divisor count raisesValueErrorand a divisor still runs.test_mha_v4_kv_splits_auto_follows_the_cu_count: the same shape at 304 / 256 / 228 / 80 CUs splits 16 / 16 / 8 / 4 ways.test_mha_v4_kv_splits_follow_the_lse_gate: where the LSE gate refuses (arch patched to gfx942),"auto"resolves to 1 and an explicit count raisesNotImplementedError.test_mha_v4_kv_splits_auto_leaves_unsupported_calls_unsplit(gfx950): MXFP4 andblock_maskcalls with"auto"equal the plain call bit for bit.test_mha_v4_kv_splits_compile_parity(gfx950): BF16 and FP8 withkv_splits=4give identicaloutandlseeager and undertorch.compile(fullgraph=True).test_mha_v4_varlen_gate_follows_the_live_gpu_not_gpu_archs(gfx950): withget_gfx()reporting gfx942,_varlen_capablestill follows the gfx950 GPU, eager and undertorch.compile(fullgraph=True).op_tests/triton_tests/attention/test_lse_merge.py(pytest, through the publiclse_mergewrapper):test_lse_merge_matches_reference: a torch merge over 6 shapes (one range, a one-row sequence, partial tiles, up to 7 ranges, B up to 3) × head dims 64/128 × BF16/FP16/FP32 output × with and without the merged LSE.test_lse_merge_reads_and_writes_strided_views: inputs and outputs with only a contiguous last dimension. Nothing outside the output views is written.test_lse_merge_skips_empty_ranges: a range empty for every row, rows empty in some ranges, and rows empty in all ranges. The empty partials are filled with 1e4, NaN or Inf. Rows reached by no range merge to 0 output and -inf LSE, with no NaN.test_lse_merge_addresses_past_2_31_elements(needs ~10 GiB free): 5 splits of[65536, 64, 128]and one partial of[147456, 128, 128], both past 2^31 elements, return the last split exactly.test_lse_merge_rejects_malformed_arguments: no key range, partials that don't fold into the batch, wrongpartial_lseorlseshapes, a non-contiguous last dimension and a head dimension that is not a power of two each raiseValueError.op_tests/op_benchmarks/triton/bench_lse_merge.pytimes the merge withdo_bench_aiter_triton(CUDA graph, rotating buffers), with and without the merged LSE. It runs on the shapeskv_splits="auto"makes, or on one--shape BATCH SEQUENCE HEADS SPLITS, with--metric time|bandwidthand--dtype bf16|fp16|fp32.PR Self-Review
Reviewed revision
eb27c3173d8f4dacc66bb6686a486ea4343241abBehavior and intent
A dense MHA v4 launch runs one work-group per (batch, head, 256-row query tile). A short sequence with few heads therefore leaves most CUs idle:
[1, 4352, 3]fills 51 of MI355X's 256. Before this PR the only way to use the rest of the GPU was a different kernel.This PR adds
mha_v4(..., kv_splits=1 | N | "auto"):The keys are split into N ranges, which are folded into the batch of a single launch. The partial outputs are then merged by their LSE in a new Triton kernel,
lse_merge.Operands are quantized once, before the split. Per-tensor scales therefore stay global, and the LSE bias is the same in every range, so it cancels in the merge.
kv_splitsis supported for BF16, BF16/FP8, INT8/FP8 and FP8/FP8, wherever the LSE gate admits them (gfx950 today), and not withblock_maskorseqlens_k."auto"(mha_v4_kv_splits()) picks the largest count that:Where splitting is unsupported,
"auto"returns 1.If the count doesn't divide the key length, the last range takes the remainder. This uses per-batch key lengths, so operands without them need a count that divides the key length. That capability (
_varlen_capable) is checked on the live GPU arch, the arch the launcher dispatches on.An explicit count is bounded by
key_length // mha_v4_kv_tile(), so every range holds at least one KV tile. A shorter range still costs a whole tile, and the merge unrolls over the count, so its compile time grows steeply.In the merge, a range with LSE -inf for a row carries no weight, and its partial output is not loaded. NaN or Inf there therefore cannot poison the merged row.
Default behavior is unchanged:
kv_splits=1takes the existing path and never callslse_merge.One change affects existing calls: the launch custom ops (
mha_v4_fwd_launch,mha_v4_fwd_sparse_launch, and the MXFP4 and MXFP6 launchers) are now wrapped by_launch_op. Eager calls run the launcher directly instead of going throughtorch.librarydispatch, which cost about 55 µs of host time per call. Undertorch.compilethe same custom op is still used.Validation and unverified scope
Validated on MI355X (gfx950) at this revision. Build: torch 2.13.0+git3369fa2, HIP 7.16.26323, ROCm 10.1.0, Triton 3.8.0, Python 3.12.3. JIT modules were rebuilt from this branch.
python op_tests/test_mha_v4.py(as CI runs it): 275 checks run, 0 failed, 0 skipped. This includes the 60 cases this PR adds and the existingmha_v4compile-parity tests, which exercise the_launch_opchange undertorch.compile.pytest op_tests/triton_tests/attention/test_lse_merge.py: 87 passed, including both past-2^31 cases. Without the empty-range mask, its NaN and Inf cases fail.python op_tests/op_benchmarks/triton/bench_lse_merge.pyruns with the default shapes, with--shapeand with--metric bandwidth. It was run on a shared GPU, so its times are not quoted.Explicit counts past one tile per range, Q
[1, 1000, 3, 128]over 1024 BF16 keys, eager:lse_mergecompile: 0.55 s at 32 splits, 2.2 s at 64 and 13.4 s at 128.kv_splits=1024had not finished compiling after 2 minutes.These measurements motivated the explicit-count bound.
Formatting and lint:
black --check(stable, as in CI) andruff check0.16.0 pass on the changed Python files.Unverified:
kv_splitsis disabled there by the LSE gate:"auto"returns 1 and an explicit count raises. On gfx942 onlytest_lse_merge.py(no arch gate) and the CPU-sidemha_v4tests would run."auto"for MI300X, MI300A, MI308X and MI355X is tested only by mocking the CU count. CPX/partition modes were not run.kv_splitscompile parity covers BF16 and FP8/FP8 only. BF16/FP8 and INT8/FP8 undertorch.compileare not tested.test_mha_v4_kv_splits_compile_parityfail once in a full run on their gfx950 setup. The existingtest_mha_v4_raw_compile_parity[FP8,FP8]fails there too, also on main, and an unsplit FP8 call mismatched once in 5. I did not reproduce it: three full runs and 80 isolated repeats were clean, including runs with NaN-filled freed memory. The test is unchanged.native_fp8_format, the KV-tile manifest, the LSE gate and_check_varlen_capablestill useget_gfx(), which followsGPU_ARCHS. These predate this PR and are left for a follow-up.mha_v4docstring;lse_mergeBLOCK_M×num_warpssweep behind the gfx950 config;tl.range) would remove this; it is left as a follow-up.PR-specific question
Which exact workload keys consume these configuration changes, and what evidence shows that unrelated shapes keep their previous selection?
The only configuration change is a new file,
aiter/ops/triton/configs/gfx950/triton/attention/lse_merge/DEFAULT.json, with one entry:_lse_merge_kernel: {BLOCK_M: 16, num_warps: 4}.get_tuned_kernel_config("attention", "LSE_MERGE", "_lse_merge_kernel", ...)in_lse_merge_config(). Its only caller islse_merge(). Inaiter, the only caller of that ismha_v4when it resolves tokv_splits > 1. The new test and benchmark call it too.kv_splits > 1call on gfx950 uses it. The file is resolved once per process. Other architectures have no entry and get the fallbackBLOCK_M=32, num_warps=4.get_tuned_kernel_config()requires that fallback, and it must launch on every arch. It logs a warning when it is used.LSE_MERGEis a new config family and_lse_merge_kernelis a new kernel, so no existing workload had a previous selection to change.grep -rn "LSE_MERGE\|lse_merge" aiterfinds no other consumer.kv_splits=1never reacheslse_merge.mha_v4checks in the 275-check run still pass.BLOCK_M8–128 ×num_warps1–8 over themha_v4kv_splitsshapes, 16 × 4 came within 2% of each shape's best on average. The fallback was 8% behind it.Changed op tests
The PR changes three files under
op_tests/. It modifies or removes no existing test. No test on main callskv_splits,mha_v4_kv_splitsorlse_merge, so each test below is the only coverage of its behavior.op_tests/test_mha_v4.pyadds 11 tests (60 cases on gfx950). They run end to end throughmha_v4. They are not redundant withtest_lse_merge.py, which tests only the merge: these cover the key-range fold, the"auto"heuristic, the gates and the compile path.test_mha_v4_kv_splits_match_the_unsplit_call(36 cases: 4 recipes × 2/3/4 splits × batch 1, batch 2 GQA, and batch 2 with a remainder): the end-to-end accuracy check. It compares split output and LSE with full-precision attention and with the unsplit call.test_mha_v4_kv_splits_auto_fills_one_wave:"auto"grows the grid to one wave and no further, and prefers a divisor.test_mha_v4_kv_splits_auto_follows_the_cu_count(4 cases: 304/256/228/80 CUs):"auto"sizes the split by the device's own CU count.test_mha_v4_kv_splits_fold_every_key_once(4 cases): the range fold covers every key exactly once, and only an uneven batched fold copies.test_mha_v4_kv_splits_follow_the_lse_gate: where the LSE gate refuses,"auto"is 1 and an explicit count raises.test_mha_v4_kv_splits_auto_leaves_unsupported_calls_unsplit:"auto"falls back to the plain call for sparse, varlen and MX recipes, instead of raising.test_mha_v4_kv_splits_rejects_what_it_cannot_split(8 cases): each error path raises the intended exception. The cases are zero, a non-int, more than the keys, shorter than a tile,block_mask,seqlens_k, MXFP4 and FP8/MXFP6.test_mha_v4_kv_splits_allow_one_kv_tile_per_range: the tile bound is inclusive; exactly one tile per range still runs and matches.test_mha_v4_kv_splits_need_a_divisor_without_per_batch_key_lengths: an operand row without per-batch key lengths rejects a remainder.test_mha_v4_kv_splits_compile_parity(2 cases: BF16, FP8): split calls undertorch.compilematch eager.test_mha_v4_varlen_gate_follows_the_live_gpu_not_gpu_archs: the per-batch key-length gate follows the live GPU, notGPU_ARCHS, also underfullgraph=True. It fails if the gate usesget_gfx().The file also changes
benchmark_mha_v4, which is not a check. It gainskv_splitsandtimingparameters (--kv-splits,--timing profiler|graph|eager), so the Performance tables can be regenerated. With the defaults it times what it timed before. The other benchmarks don't cover this:bench_sage.pyhas nokv_splitsand times only withdo_bench, without graph-replay or eager host timing.op_tests/triton_tests/attention/test_lse_merge.pyis new (87 cases). It is the pytest unit test thataiter/ops/triton/README.md(rule 16) requires for the Triton wrapper. It calls the publiclse_mergedirectly. That reaches inputsmha_v4never produces: empty ranges, NaN or Inf partials, strided outputs, FP16/FP32 outputs, head dim 64 and malformed arguments. Earlier revisions of this PR had the direct merge tests intest_mha_v4.py. They moved here, so nothing is tested twice.test_lse_merge_matches_reference(72 cases): merged output and LSE against a torch merge, over shapes, head dims, output dtypes and the optional LSE.test_lse_merge_reads_and_writes_strided_views: strided inputs and outputs, and no writes outside the output views.test_lse_merge_skips_empty_ranges(6 cases: 1e4/NaN/Inf fill × with and without LSE): an LSE of -inf carries no weight whatever its partial holds, and an all-empty row gives 0, not NaN. The NaN and Inf cases fail without the empty-range mask.test_lse_merge_addresses_past_2_31_elements(2 cases, needs ~10 GiB free): the 64-bit offsets, both when the splits pass 2^31 elements and when a single partial does.test_lse_merge_rejects_malformed_arguments(6 cases): each rejected argument raisesValueError, including zero partials, which would otherwise merge to a silent 0.op_tests/op_benchmarks/triton/bench_lse_merge.pyis new. It is a benchmark, not a check. It is thebench_<op>.pythataiter/ops/triton/README.md(rule 17) requires.lse_merge. It times withdo_bench_aiter_triton(CUDA-graph replay over rotating buffers), with and without the merged LSE.kv_splits="auto"makes on MI355X, and one large explicit split. Alternatively one--shape BATCH SEQUENCE HEADS SPLITS.--head-dim,--dtype bf16|fp16|fp32and--metric time|bandwidth.benchmark_mha_v4times the whole split call, where the merge is 2–4 µs of about 40 µs. No other benchmark launcheslse_merge. This file isolates the merge, which is what a sweep of its gfx950 tile config (BLOCK_M,num_warps) needs.--shapeand with--metric bandwidthon MI355X. The GPU was shared, so its times are not quoted.