Skip to content

[Triton/Gluon] MHAv4 split-KV - #6560

Merged
jcaraban merged 20 commits into
ROCm:mainfrom
nsakkine:mha_v4-kv-splits
Nov 4, 2026
Merged

jcaraban merged 20 commits into
ROCm:mainfrom
nsakkine:mha_v4-kv-splits

Conversation

@nsakkine

@nsakkine nsakkine commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

MHAv4: split short sequences over the keys with kv_splits

Motivation

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 of the GPU idle:

shape [B, S, H, D] work-groups MI355X (256 CUs) MI300X (304 CUs)
[1, 4352, 3, 128] 51 20% 17%
[1, 4352, 8, 128] 136 53% 45%
[1, 4352, 32, 128] 544 > 1 wave > 1 wave

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_v4 calls 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"), default 1 (unchanged behaviour):

  • The K/V sequence is cut into n key ranges, which are folded into the batch dimension of a single launch:

    • Q is repeated across the ranges (_repeat_queries): a stride-0 view when B is 1, a copy otherwise.
    • K and V are folded by _fold_key_ranges. With step = Sk // n, range i starts at key i * step and spans step + Sk % n keys, so the ranges overlap by the remainder and the last one ends at Sk. When n divides Sk the ranges are equal. Otherwise a per-range seqlens_k (_key_range_lengths) cuts every other range back to step, and each key is attended once.
    • The fold is a view when B is 1 or n divides Sk. An uneven split with B > 1 copies K and V once.
  • The kernel writes n partial outputs and partial LSEs. A new Triton kernel then merges them by LSE into out (and into lse when return_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 helper mha_v4_kv_splits(batch, query_length, query_heads, key_length, device=None, *, ragged=False). It picks the largest n that:

    • still fits the grid in one wave on the device;
    • leaves every range at least 512 keys (_MHA_V4_MIN_KV_SPLIT_TOKENS);
    • divides Sk. Only when no such divisor exists, at B = 1 and with ragged=True, does it take the largest n that fits and let the last range take the remainder. "auto" passes ragged=True for 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 build seqlens_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 or torch.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 on GPU_ARCHS. The probe sits behind a torch_compile_guard op, so it stays traceable under fullgraph=True.

New Triton kernel: lse_merge

  • aiter/ops/triton/_triton_kernels/attention/lse_merge.py contains _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.
  • A range with LSE -inf for a row carries no weight, and the kernel does not load its partial output. NaN or Inf in an empty range therefore cannot reach the merged row (0 × NaN would be NaN). A row that no range reaches merges to a 0 output and LSE -inf.
  • aiter/ops/triton/attention/utils.py adds lse_merge(partial_out, partial_lse, out, lse=None). It rejects partials that hold no key range.
  • In mha_v4 it is wrapped as the custom op aiter::mha_v4_merge_kv_splits (with a fake implementation), so kv_splits works under torch.compile.
  • The tile comes from configs/gfx950/triton/attention/lse_merge/DEFAULT.json through get_tuned_kernel_config().
  • Tests: 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)

  • The launch custom ops are now declared through a small _launch_op(name) decorator. It registers the op as before, but an eager call runs the Python body directly; under torch.compile the registered op is still used.
  • A mutating custom op's Python dispatch costs about 55 µs per call, which was most of the host time of a small launch.

Fix: _restore_k_mean_in_lse under GQA

  • It applied a per-K-head mean to Q heads, so return_lse=True failed for any quantized K with fewer KV heads than Q heads. It now applies repeat_interleave over the head groups first.

Benchmark: benchmark_mha_v4 in op_tests/test_mha_v4.py

  • New kv_splits and timing parameters, with --kv-splits (ints or "auto") and --timing profiler|graph|eager in main(). graph and eager are the methodology under Performance. profiler stays the default, so the CI output only gains the two columns.
  • A count other than 1 times only the four recipes that split. With "auto", the table also shows the count that "auto" picked.

Constraints

  • Architecture: the ranges are merged by their LSE, so kv_splits follows the LSE gate: gfx950 today. Elsewhere "auto" resolves to 1 and an explicit count raises NotImplementedError.
  • Recipes: BF16, BF16/FP8, INT8/FP8 and FP8/FP8. The MX recipes (MXFP4/MXFP6) pack K/V in tiles that a key range can't be cut out of, so they aren't supported.
  • Explicit counts: each range must hold at least one KV tile, so the count is at most Sk // mha_v4_kv_tile() (128-key tiles on gfx950). A larger count raises ValueError. A shorter range still costs a whole tile, and the merge unrolls over the count, so its compile time grows steeply with it.
  • Uneven counts: a count that doesn't divide Sk needs 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 raises ValueError otherwise.
  • Memory: a split call allocates n × B × Sq × H × D partial outputs in the output dtype, plus n × B × H × Sq FP32 LSE. With B > 1, Q is copied n times, and an uneven split also copies K and V once.

Performance (gfx950)

Setup:

  • MI355X (256 CUs), exclusive GPU, torch 2.13.
  • main = b5078fc49a (merge base); head = this branch.
  • Times are the median µs per call, with BF16 inputs, Sq = Sk, D = 128 and a preallocated out.

Methodology:

  • Graph: 100 replays of a HIP graph holding 10 back-to-back calls. p10 to p90 is within 3.7 µs on every row.
  • Eager: 50 samples of 20 back-to-back calls. "Host" is the time to issue a call; "e2e" runs from issue to synchronize.

Reproduce: benchmark_mha_v4 gives the head columns for one shape. The file then runs its full check suite.

python op_tests/test_mha_v4.py --sequence-q 4352 --sequence-k 4352 --heads 3 --kv-splits 1 2 4 5 8 auto --timing graph eager

The benchmark on main has no --kv-splits or --timing. Its column was measured with the same timing loops at the merge base. A rerun at 14c39dd7a4 gave BF16 69.4 / 40.6 / 40.6 µs under graph replay at kv_splits 1 / 4 / "auto", and 70 / 50 / 53 µs eager.

[1, 4352, 3, 128]: 51 work-groups on 256 CUs; "auto" picks 4.

graph replay main kv_splits=1 2 4 5 8 "auto"
BF16 69.6 69.9 43.9 40.8 46.0 50.4 41.2
BF16/FP8 60.9 61.0 43.2 40.2 44.7 49.6 40.0
INT8/FP8 124.0 123.5 111.3 108.9 112.1 118.9 109.5
FP8/FP8 132.3 131.9 121.7 122.0 126.4 133.0 122.7
eager e2e (host) main kv_splits=1 2 4 5 8 "auto"
BF16 87 (83) 70 (14) 49 (48) 49 (47) 62 (61) 52 (48) 54 (52)
BF16/FP8 132 (130) 64 (60) 101 (99) 100 (99) 116 (115) 101 (99) 104 (104)
INT8/FP8 318 (316) 236 (233) 286 (285) 287 (286) 303 (302) 286 (285) 293 (292)
FP8/FP8 379 (377) 289 (287) 346 (345) 345 (344) 368 (367) 346 (345) 354 (353)

Other shapes: graph replay / eager e2e.

shape ("auto") recipe main kv_splits=1 "auto"
[1, 8192, 3, 128] (2) BF16 127.3 / 131 127.9 / 129 113.3 / 115
FP8/FP8 165.0 / 380 167.6 / 295 160.2 / 358
[1, 4352, 32, 128] (1) BF16 353.3 / 358 353.6 / 356 354.9 / 356
FP8/FP8 367.9 / 391 366.6 / 379 366.3 / 379

Notes:

  • Head is cheaper than main on the eager host even unsplit, because its launchers skip the custom-op dispatch outside torch.compile (_launch_op).
  • A split adds about 35 µs of host time per call, mostly the Triton merge launch. A count that leaves a remainder adds about 14 µs more to build seqlens_k.
  • These eager calls are limited by host time, so splitting only pays eagerly for BF16; the quantized recipes get slower. "auto" is meant for graph-replayed or compiled callers, and kv_splits defaults to 1, so eager callers are unaffected unless they opt in.
  • Divisor vs remainder: across batch-1 shapes on MI355X, a divisor above half the fit was faster both replayed and eager. Below half, replayed BF16 gained up to 17 µs from the extra splits of a remainder, while eager calls and replayed FP8 still favoured the divisor. With B > 1 a remainder copies K and V and was slower than not splitting ([2, 4352, 2]: 86 µs at 3 splits against 70 µs unsplit), so "auto" only takes a remainder at B = 1.
  • The tables predate the empty-range mask in 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, through mha_v4):

  • test_mha_v4_kv_splits_match_the_unsplit_call (gfx950): 4 recipes × kv_splits ∈ {2, 3, 4} × (B=1 MHA Sq=1000, Sk=1024, H=3; B=2 GQA Sq=333, Sk=768, 4 Q / 2 KV heads; the same GQA shape with Sk=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 the return_lse=False output equals the return_lse=True one bit for bit.
  • test_mha_v4_kv_splits_auto_fills_one_wave: the heuristic at 256 CUs fills one wave, divides Sk, keeps ranges ≥ 512 keys, and returns 1 for full grids and prime Sk. With ragged=True it still prefers a divisor (4 ways for Sk=4352). It takes a remainder only at B = 1 when no divisor exists (5 ways for the prime Sk=4349), and returns 1 for that Sk at 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 divides Sk.
  • test_mha_v4_kv_splits_rejects_what_it_cannot_split (gfx950): zero, non-int, a count above Sk, 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_capable patched off, a non-divisor count raises ValueError and 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 raises NotImplementedError.
  • test_mha_v4_kv_splits_auto_leaves_unsupported_calls_unsplit (gfx950): MXFP4 and block_mask calls with "auto" equal the plain call bit for bit.
  • test_mha_v4_kv_splits_compile_parity (gfx950): BF16 and FP8 with kv_splits=4 give identical out and lse eager and under torch.compile(fullgraph=True).
  • test_mha_v4_varlen_gate_follows_the_live_gpu_not_gpu_archs (gfx950): with get_gfx() reporting gfx942, _varlen_capable still follows the gfx950 GPU, eager and under torch.compile(fullgraph=True).

op_tests/triton_tests/attention/test_lse_merge.py (pytest, through the public lse_merge wrapper):

  • 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, wrong partial_lse or lse shapes, a non-contiguous last dimension and a head dimension that is not a power of two each raise ValueError.

op_tests/op_benchmarks/triton/bench_lse_merge.py times the merge with do_bench_aiter_triton (CUDA graph, rotating buffers), with and without the merged LSE. It runs on the shapes kv_splits="auto" makes, or on one --shape BATCH SEQUENCE HEADS SPLITS, with --metric time|bandwidth and --dtype bf16|fp16|fp32.

PR Self-Review

Reviewed revision

eb27c3173d8f4dacc66bb6686a486ea4343241ab

Behavior 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_splits is supported for BF16, BF16/FP8, INT8/FP8 and FP8/FP8, wherever the LSE gate admits them (gfx950 today), and not with block_mask or seqlens_k.

    • The MX recipes are excluded because their packed K/V tiles and padded block scales can't be cut into row ranges.
  • "auto" (mha_v4_kv_splits()) picks the largest count that:

    • fits the grid in one wave of this device's CU count;
    • leaves at least 512 keys per range;
    • preferably divides the key length.

    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=1 takes the existing path and never calls lse_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 through torch.library dispatch, which cost about 55 µs of host time per call. Under torch.compile the 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 existing mha_v4 compile-parity tests, which exercise the _launch_op change under torch.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.py runs with the default shapes, with --shape and 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:

    • Accuracy matched the unsplit call even at 3–4 keys per range, for BF16 and INT8/FP8, with and without a remainder.
    • Time: 25 µs unsplit, 28–31 µs at 4–16 splits, 40 µs at 64 and 128 µs at 256.
    • Cold lse_merge compile: 0.55 s at 32 splits, 2.2 s at 64 and 13.4 s at 128. kv_splits=1024 had not finished compiling after 2 minutes.

    These measurements motivated the explicit-count bound.

  • Formatting and lint: black --check (stable, as in CI) and ruff check 0.16.0 pass on the changed Python files.

Unverified:

  • gfx942: not run at this revision. kv_splits is disabled there by the LSE gate: "auto" returns 1 and an explicit count raises. On gfx942 only test_lse_merge.py (no arch gate) and the CPU-side mha_v4 tests would run.
  • Other CU counts: "auto" for MI300X, MI300A, MI308X and MI355X is tested only by mocking the CU count. CPX/partition modes were not run.
  • Compile coverage: kv_splits compile parity covers BF16 and FP8/FP8 only. BF16/FP8 and INT8/FP8 under torch.compile are not tested.
  • FP8 compile parity on another setup: a reviewer saw the FP8 case of test_mha_v4_kv_splits_compile_parity fail once in a full run on their gfx950 setup. The existing test_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.
  • Other arch checks: native_fp8_format, the KV-tile manifest, the LSE gate and _check_varlen_capable still use get_gfx(), which follows GPU_ARCHS. These predate this PR and are left for a follow-up.
  • Earlier measurements not repeated at this revision:
    • the eager versus HIP-graph-replayed timings in the mha_v4 docstring;
    • the lse_merge BLOCK_M × num_warps sweep behind the gfx950 config;
    • the Performance tables, after the empty-range mask.
  • Large explicit counts on long sequences: the bound still allows, for example, 256 splits at 32k keys, whose cold merge compile is well over 13 s. Making the merge loop a runtime loop (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}.

  • Who reads it: get_tuned_kernel_config("attention", "LSE_MERGE", "_lse_merge_kernel", ...) in _lse_merge_config(). Its only caller is lse_merge(). In aiter, the only caller of that is mha_v4 when it resolves to kv_splits > 1. The new test and benchmark call it too.
  • Shape keys: none. The entry is per device, not per shape, so every kv_splits > 1 call on gfx950 uses it. The file is resolved once per process. Other architectures have no entry and get the fallback BLOCK_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.
  • Why unrelated shapes are unaffected:
    • LSE_MERGE is a new config family and _lse_merge_kernel is a new kernel, so no existing workload had a previous selection to change. grep -rn "LSE_MERGE\|lse_merge" aiter finds no other consumer.
    • The default kv_splits=1 never reaches lse_merge.
    • The existing mha_v4 checks in the 275-check run still pass.
  • Why 16 × 4: in my earlier MI355X sweep of BLOCK_M 8–128 × num_warps 1–8 over the mha_v4 kv_splits shapes, 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 calls kv_splits, mha_v4_kv_splits or lse_merge, so each test below is the only coverage of its behavior.

op_tests/test_mha_v4.py adds 11 tests (60 cases on gfx950). They run end to end through mha_v4. They are not redundant with test_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 under torch.compile match eager.
  • test_mha_v4_varlen_gate_follows_the_live_gpu_not_gpu_archs: the per-batch key-length gate follows the live GPU, not GPU_ARCHS, also under fullgraph=True. It fails if the gate uses get_gfx().

The file also changes benchmark_mha_v4, which is not a check. It gains kv_splits and timing parameters (--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.py has no kv_splits and times only with do_bench, without graph-replay or eager host timing.

op_tests/triton_tests/attention/test_lse_merge.py is new (87 cases). It is the pytest unit test that aiter/ops/triton/README.md (rule 16) requires for the Triton wrapper. It calls the public lse_merge directly. That reaches inputs mha_v4 never 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 in test_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 raises ValueError, including zero partials, which would otherwise merge to a silent 0.

op_tests/op_benchmarks/triton/bench_lse_merge.py is new. It is a benchmark, not a check. It is the bench_<op>.py that aiter/ops/triton/README.md (rule 17) requires.

  • What it covers: the merge kernel alone, through the public lse_merge. It times with do_bench_aiter_triton (CUDA-graph replay over rotating buffers), with and without the merged LSE.
  • Shapes: by default, those that kv_splits="auto" makes on MI355X, and one large explicit split. Alternatively one --shape BATCH SEQUENCE HEADS SPLITS.
  • Options: --head-dim, --dtype bf16|fp16|fp32 and --metric time|bandwidth.
  • Why it is not redundant: benchmark_mha_v4 times the whole split call, where the merge is 2–4 µs of about 40 µs. No other benchmark launches lse_merge. This file isolates the merge, which is what a sweep of its gfx950 tile config (BLOCK_M, num_warps) needs.
  • Validation: it ran with the default shapes, with --shape and with --metric bandwidth on MI355X. The GPU was shared, so its times are not quoted.

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]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
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 gfx1201 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 6560 --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.

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
hellozhuo-amd self-requested a review October 26, 2026 08:38

@hellozhuo-amd hellozhuo-amd 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 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.

Comment thread aiter/ops/mha_v4.py Resolved
Comment thread op_tests/test_mha_v4.py Resolved
Comment thread aiter/ops/mha_v4.py Resolved
Comment thread aiter/ops/triton/attention/utils.py Resolved
Comment thread aiter/ops/triton/attention/utils.py Resolved
Comment thread aiter/ops/triton/attention/utils.py Resolved
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]>
@jcaraban

Copy link
Copy Markdown
Contributor

are you enforcing a max upper-bound to kv_splits? something like kv_splits <= seqlen / KV-tile

Comment thread aiter/ops/mha_v4.py Resolved
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]>
@aiter-bot

aiter-bot commented Oct 30, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

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

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_splits` is supported for BF16, BF16/FP8, INT8/FP8 and FP8/FP8, wherever the LSE gate admits them (gfx950 today), and not with `block_mask` or `seqlens_k`.
  - The MX recipes are excluded because their packed K/V tiles and padded block scales can't be cut into row ranges.
- `"auto"` (`mha_v4_kv_splits()`) picks the largest count that:
  - fits the grid in one wave of this device's CU count;
  - leaves at least 512 keys per range;
  - preferably divides the key length.

  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=1` takes the existing path and never calls `lse_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 through `torch.library` dispatch, which cost about 55 µs of host time per call. Under `torch.compile` the 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 existing `mha_v4` compile-parity tests, which exercise the `_launch_op` change under `torch.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.py` runs with the default shapes, with `--shape` and 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:
  - Accuracy matched the unsplit call even at 3–4 keys per range, for BF16 and INT8/FP8, with and without a remainder.
  - Time: 25 µs unsplit, 28–31 µs at 4–16 splits, 40 µs at 64 and 128 µs at 256.
  - Cold `lse_merge` compile: 0.55 s at 32 splits, 2.2 s at 64 and 13.4 s at 128. `kv_splits=1024` had not finished compiling after 2 minutes.

  These measurements motivated the explicit-count bound.
- Formatting and lint: `black --check` (`stable`, as in CI) and `ruff check` 0.16.0 pass on the changed Python files.

Unverified:
- **gfx942:** not run at this revision. `kv_splits` is disabled there by the LSE gate: `"auto"` returns 1 and an explicit count raises. On gfx942 only `test_lse_merge.py` (no arch gate) and the CPU-side `mha_v4` tests would run.
- **Other CU counts:** `"auto"` for MI300X, MI300A, MI308X and MI355X is tested only by mocking the CU count. CPX/partition modes were not run.
- **Compile coverage:** `kv_splits` compile parity covers BF16 and FP8/FP8 only. BF16/FP8 and INT8/FP8 under `torch.compile` are not tested.
- **FP8 compile parity on another setup:** a reviewer saw the FP8 case of `test_mha_v4_kv_splits_compile_parity` fail once in a full run on their gfx950 setup. The existing `test_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.
- **Other arch checks:** `native_fp8_format`, the KV-tile manifest, the LSE gate and `_check_varlen_capable` still use `get_gfx()`, which follows `GPU_ARCHS`. These predate this PR and are left for a follow-up.
- **Earlier measurements not repeated at this revision:**
  - the eager versus HIP-graph-replayed timings in the `mha_v4` docstring;
  - the `lse_merge` `BLOCK_M` × `num_warps` sweep behind the gfx950 config;
  - the Performance tables, after the empty-range mask.
- **Large explicit counts on long sequences:** the bound still allows, for example, 256 splits at 32k keys, whose cold merge compile is well over 13 s. Making the merge loop a runtime loop (`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}`.
- **Who reads it:** `get_tuned_kernel_config("attention", "LSE_MERGE", "_lse_merge_kernel", ...)` in `_lse_merge_config()`. Its only caller is `lse_merge()`. In `aiter`, the only caller of that is `mha_v4` when it resolves to `kv_splits > 1`. The new test and benchmark call it too.
- **Shape keys:** none. The entry is per device, not per shape, so every `kv_splits > 1` call on gfx950 uses it. The file is resolved once per process. Other architectures have no entry and get the fallback `BLOCK_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.
- **Why unrelated shapes are unaffected:**
  - `LSE_MERGE` is a new config family and `_lse_merge_kernel` is a new kernel, so no existing workload had a previous selection to change. `grep -rn "LSE_MERGE\|lse_merge" aiter` finds no other consumer.
  - The default `kv_splits=1` never reaches `lse_merge`.
  - The existing `mha_v4` checks in the 275-check run still pass.
- **Why 16 × 4:** in my earlier MI355X sweep of `BLOCK_M` 8–128 × `num_warps` 1–8 over the `mha_v4` `kv_splits` shapes, 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 calls `kv_splits`, `mha_v4_kv_splits` or `lse_merge`, so each test below is the only coverage of its behavior.

**`op_tests/test_mha_v4.py`** adds 11 tests (60 cases on gfx950). They run end to end through `mha_v4`. They are not redundant with `test_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 under `torch.compile` match eager.
- `test_mha_v4_varlen_gate_follows_the_live_gpu_not_gpu_archs`: the per-batch key-length gate follows the live GPU, not `GPU_ARCHS`, also under `fullgraph=True`. It fails if the gate uses `get_gfx()`.

The file also changes `benchmark_mha_v4`, which is not a check. It gains `kv_splits` and `timing` parameters (`--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.py` has no `kv_splits` and times only with `do_bench`, without graph-replay or eager host timing.

**`op_tests/triton_tests/attention/test_lse_merge.py`** is new (87 cases). It is the pytest unit test that `aiter/ops/triton/README.md` (rule 16) requires for the Triton wrapper. It calls the public `lse_merge` directly. That reaches inputs `mha_v4` never 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 in `test_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 raises `ValueError`, including zero partials, which would o

[truncated in readiness report; see the PR description for the full answer]

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.

@nsakkine

Copy link
Copy Markdown
Collaborator Author

are you enforcing a max upper-bound to kv_splits? something like kv_splits <= seqlen / KV-tile

Good catch. kv_splits="auto" was already bounded: it requires at least 512 keys per range (4 KV tiles on gfx950), so it stays well under seqlen / KV-tile. Explicit counts were only checked against kv_splits <= key_length. Explicit counts are now bounded too: kv_splits must be at most key_length // mha_v4_kv_tile(), so every key range holds at least one full KV tile. Larger counts raise ValueError, and there are tests for a sub-tile count and for the inclusive edge (exactly one tile per range).

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]>
hellozhuo-amd
hellozhuo-amd previously approved these changes Oct 30, 2026

@hellozhuo-amd hellozhuo-amd 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.

LGTM

@nsakkine
nsakkine marked this pull request as ready for review October 30, 2026 08:45
@nsakkine
nsakkine requested a review from a team October 30, 2026 08:45
@github-actions github-actions Bot changed the title MHAv4 split-KV [Triton/Gluon] MHAv4 split-KV Oct 30, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot October 30, 2026 09:33

Copilot AI 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.

🟡 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

Comment thread aiter/ops/mha_v4.py Resolved
Comment thread aiter/ops/triton/attention/utils.py Resolved
Comment thread aiter/ops/triton/attention/utils.py Resolved
_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]>
@zufayu
zufayu requested review from a team and Dewei-Wang-sh November 2, 2026 01:25
Comment thread aiter/ops/mha_v4.py Resolved
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]>

@leonling-ll leonling-ll 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.

LGTM

@jcaraban
jcaraban merged commit 8eb9119 into ROCm:main Nov 4, 2026
jcaraban added a commit to jcaraban/xDiT that referenced this pull request Nov 13, 2026
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.
jcaraban added a commit to jcaraban/xDiT that referenced this pull request Nov 13, 2026
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.
avjves pushed a commit to xdit-project/xDiT that referenced this pull request Nov 24, 2026
…-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.
jcaraban added a commit to xdit-project/xDiT that referenced this pull request Nov 24, 2026
…#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.
jcaraban added a commit to xdit-project/xDiT that referenced this pull request Nov 24, 2026
)

* 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.
jcaraban added a commit to xdit-project/xDiT that referenced this pull request Nov 24, 2026
…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.
jcaraban added a commit to xdit-project/xDiT that referenced this pull request Nov 24, 2026
* 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.
avjves pushed a commit to xdit-project/xDiT that referenced this pull request Nov 25, 2026
…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.
avjves pushed a commit to xdit-project/xDiT that referenced this pull request Nov 25, 2026
* 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
jcaraban added a commit to xdit-project/xDiT that referenced this pull request Nov 25, 2026
…#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants