Skip to content

[ASM] [HIP] [CI] [gfx942] Optimize long-context FMHA with split-KV - #5592

Open
amd-yashagar wants to merge 1 commit into
mainfrom
feat/gfx942-fmha-hd192-split-asm
Open

amd-yashagar wants to merge 1 commit into
mainfrom
feat/gfx942-fmha-hd192-split-asm

Conversation

@amd-yashagar

@amd-yashagar amd-yashagar commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Kimi-K3 packed-varlen prefill (BF16, D_QK=192, D_V=128) is long-K bound on the gfx942 ASM kernel. This PR improves utilization for small Q grids without changing the public flash_attn_varlen_func API.

Technical Details

  • Add a split-KV ASM producer and HIP output/LSE combine.
  • Add num_splits to fmha_v3_varlen_fwd: 0 is auto, 1 is unsplit, and 2–8 force a split count.
  • Auto selects split-3 for compatible gfx942 inputs when Sk >= 8192 and ceil(Sq/128) * H <= floor(4 * CU / 3). Other calls remain unsplit.
  • The combine respects cu_seqlens_q, preserving output rows outside the active interval. The producer handles ragged and empty K using cu_seqlens_k, without a host sync.

Test Plan

  • Run the split-KV correctness suite on MI300X and MI325X.
  • Compare base and head operator timings across split-selected and unsplit shapes.

Test Result

The full split-KV suite passed on MI300X and MI325X at head b52b5fa1a. Forward comparisons passed across 32 shapes on each GPU. Backward dq/dk/dv passed against an FP32 CPU reference for 129x8192x4 and 4096x42700x12.

Base e48c06d89 versus head b52b5fa1a, BF16, batch 1, noncausal, preallocated out=:

GPU Ticket shape: 4096x42700x12 20 split-selected shapes 12 unsplit shapes
MI300X 3.523 → 3.354 ms 1.016×–2.769× faster Bitwise-equal output; head/base latency 0.996–1.002
MI325X 2.758 → 2.303 ms 1.067×–2.808× faster Bitwise-equal output; head/base latency 0.999–1.007

Each matrix used three rounds of 30 samples per side, with base/head order alternated. Samples were collected in separate processes.

MI300A, MI250X and end-to-end model accuracy were not tested.

Submission Checklist

PR Self-Review

Reviewed revision

b52b5fa1acbf223107c4df15cad690099fa1d20d

Behavior and intent

Improve long-K, small-Q-grid attention with split-KV while leaving unsupported calls on the existing unsplit producer. Lower-level callers can explicitly select unsplit with num_splits=1.

Validation and unverified scope

The current head passed correctness and performance checks on MI300X and MI325X. MI300A, MI250X and end-to-end model accuracy remain unverified.

PR-specific question

The split path requires gfx942 excluding MI308, BF16, batch 1, equal Q/KV heads, D_QK=192/D_V=128, and noncausal attention without unsupported options. Device-side cumulative lengths bound the producer and combine without a host sync.

Changed op tests

op_tests/test_fmha_gfx942_asm_splitkv.py covers split counts, auto boundaries, forward and backward accuracy, output preservation, sequence tails, graph/compile and address limits.

@amd-yashagar
amd-yashagar requested review from a team and a lite review from Copilot September 16, 2026 14:02
@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; main branch always runs both MI35X and MI300X
multigpu 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: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
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 5592 --add-label <label>

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 opt this PR out.

@github-actions github-actions Bot changed the title [ASM][gfx942] Optimize long-context FMHA with split-KV [ASM] [HIP] [JIT] [gfx942] Optimize long-context FMHA with split-KV Sep 16, 2026

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.

🔵 Needs a closer look

Two moderate review findings remain unresolved.

Pull request overview

Adds gfx942 split-KV BF16 FMHA for long-context varlen attention while preserving the public API.

Changes:

  • Adds split-KV ASM dispatch and HIP LSE combination.
  • Registers internal operations, interfaces, manifests, and JIT sources.
  • Adds correctness tests and performance benchmarks.

Review findings:

  • Moderate (1 vote): asm_mha_varlen_fwd.cu selects split-3 for seqlen_k 8161–8191 despite the documented 8192 threshold; align the contract and add boundary coverage.
  • Moderate (1 vote): The forced split path rejects max_seqlen_k == 0 before empty-K handling; handle empty K first or skip the partition check.
File summaries
File Summary
op_tests/test_fmha_gfx942_asm_splitkv.py Tests split-KV correctness, dispatch, LSE, graphs, and compilation.
op_tests/op_benchmarks/bench_fmha_gfx942_asm_splitkv.py Benchmarks unsplit versus split-KV execution.
hsa/gfx942/fmha_v3_fwd/fmha_splitkv.csv Registers split-KV code-object metadata.
csrc/py_itfs_cu/asm_mha_varlen_fwd.cu Implements split-KV selection and dispatch.
csrc/kernels/fmha_fwd_v3_splitkv_combine.cu Combines partial outputs and LSE values.
csrc/include/torch/mha_v3_varlen_fwd.h Declares the internal split-KV operation.
csrc/include/rocm_ops.hpp Registers the internal operation.
csrc/include/mha_fwd.h Declares split-KV interfaces and constants.
csrc/cpp_itfs/mha_fwd.cu Launches the split-KV ASM kernel.
aiter/ops/mha.py Registers Python and fake-tensor bindings.
aiter/jit/optCompilerConfig.json Adds the combine kernel to JIT builds.
Review details

Suppressed comments (2)

csrc/py_itfs_cu/asm_mha_varlen_fwd.cu:29

  • [verified] For seqlen_k values 8161–8191, this ceil expression produces 256 and auto-selects split-3, even though the PR contract says the gate begins at Sk >= 8192 and the comment describes a floor of 256 tiles. The added boundary test only covers 8160, so this earlier split of a partial tile is untested and contradicts the documented heuristic. Author must align the implementation and contract by using an explicit 8192 boundary (or revise the stated threshold) and add both sides of it.
    const int kv_tiles = (seqlen_k + kHd192SplitKvTile - 1) / kHd192SplitKvTile;
    if(kv_tiles < kHd192SplitKvAutoMinKvTiles)

csrc/py_itfs_cu/asm_mha_varlen_fwd.cu:503

  • When the internal forced path is called with max_seqlen_k == 0, this check runs before the existing empty-K branch below. Both tile counts are zero, so it raises instead of returning the zero output/LSE that the unsplit path supports. Skip this partition check for empty K (or handle the empty case before selecting split-KV).
    if(use_hd192_splitkv)
  • Files reviewed: 11/12 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI review requested due to automatic review settings September 16, 2026 14:17

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

Kernel status validation and fake-output dtype handling must be corrected before approval.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

aiter/ops/mha.py:1170

  • [verified] This new fake delegates to gen_fmha_v3_varlen_fwd_fake_tensor, whose return_dropout_randval=False branch creates the empty third output with default float32; the real C++ implementation creates that empty p tensor with q.options() (BF16) at csrc/py_itfs_cu/asm_mha_varlen_fwd.cu:457. torch.compile can therefore infer the wrong dtype for this new op, and the current test does not inspect the third or fourth outputs. Author must make the fake p dtype match the real op (preferably in the shared fake) and validate all four outputs.
    return gen_fmha_v3_varlen_fwd_fake_tensor(
  • Files reviewed: 11/12 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment thread csrc/py_itfs_cu/asm_mha_varlen_fwd.cu Resolved
Copilot AI review requested due to automatic review settings September 16, 2026 14:51
@amd-yashagar
amd-yashagar force-pushed the feat/gfx942-fmha-hd192-split-asm branch 2 times, most recently from 29694f8 to 33d07c2 Compare September 16, 2026 14:59

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.

🔵 Needs a closer look

Low-level ASM, HIP combination, and dispatch changes require final human review.

Review details
  • Files reviewed: 11/12 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Copilot AI review requested due to automatic review settings September 16, 2026 15:01

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.

🔵 Needs a closer look

Unresolved fake-tensor dtype and benchmark validation issues require human review.

Review details

Suppressed comments (3)

aiter/ops/mha.py:1174

  • The internal op's fake reuses gen_fmha_v3_varlen_fwd_fake_tensor, whose empty p tensor defaults to float32, but the real C++ implementation creates p with q.options() (BF16 for this split-KV path). torch.compile therefore sees a different dtype for the third return value and can fail or propagate an invalid graph when that value is consumed. Make the fake return an empty p with dtype=q.dtype (or correct the shared fake helper) and add an assertion covering all four outputs.
    return gen_fmha_v3_varlen_fwd_fake_tensor(
        q,
        k,
        v,
        cu_seqlens_q,

op_tests/op_benchmarks/bench_fmha_gfx942_asm_splitkv.py:92

  • This gate can pass invalid output: if either kernel returns NaN/Inf, cosine_difference becomes NaN and NaN >= 1e-4 is false; if both outputs have zero norm, the denominator is also zero. Check finiteness and require a finite, positive denominator before accepting the comparison, otherwise the benchmark can report timings for a broken kernel.
    cosine_difference = 1.0 - 2.0 * (
        reference.double() * actual.double()
    ).sum().item() / (
        reference.double().square().sum().item() + actual.double().square().sum().item()
    )

op_tests/test_fmha_gfx942_asm_splitkv.py:146

  • The description reports 26/26 tests passed, but this file defines 27 collected cases: 1 single case, 8 boundary cases, 7 split-count cases, 3 dispatch cases, and 8 additional single-case tests. Please correct the reported result or explain which case was not run so the validation claim is reproducible.
@pytest.mark.parametrize("num_splits", range(2, 9))
def test_splitkv_counts(num_splits):
    sq, sk, h = 129, 2048, 4
    q, k, v, cu_q, cu_k = _make_packed(sq, sk, h, seed=100 + num_splits)
  • Files reviewed: 11/12 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@zufayu
zufayu requested a review from amd-ruitang3 September 17, 2026 01:11
Copilot AI review requested due to automatic review settings September 22, 2026 08:43

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.

Copilot review overview

🟡 Changes recommended

The reviewed tests and benchmark need MI308 capability guards, and auto-selection coverage needs a deterministic dispatch assertion.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 Medium severity

Open (2)

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.

Copilot review overview

🔵 Needs a closer look

Unresolved moderate test-validation gaps affect split-KV graph, non-LSE correctness, and mismatch detection.

Review effort: Lite
Findings: None

Resolved since last review (2)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Default tests omit non-LSE correctness coverage

op_tests/​test_fmha_gfx942_asm_splitkv.py:359

[verified] The default CLI runs only --lse 1, while the production default is return_lse=False; that path passes nullptr to the new combine kernel and is not compared with the independent CPU reference for non-empty K. The benchmark's split-vs-unsplit cosine check cannot catch a shared error. Author must add a non-LSE correctness case to the default test matrix.

Copilot AI review requested due to automatic review settings September 23, 2026 09:06
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 3, 2026
Copilot AI lite review requested due to automatic review settings November 3, 2026 16:18

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.

🔵 Needs a closer look

An active moderate-severity issue causes NaN combined outputs and LSE for supported zero-length ragged K inputs, so the change requires a corrective fix.

4 open issues

Review effort: Lite

Copilot AI lite review requested due to automatic review settings November 10, 2026 15:07

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.

Copilot wasn't able to review any files in this pull request. Check if the Files changed in this pull request are included in default exclusions.

Still open (4)

@shay-li77

Copy link
Copy Markdown
Contributor

Needs changes. Finding 1: when cu_seqlens_q[1] < total_q, the split-KV combine writes uninitialized partials into the caller's out= rows past cu_seqlens_q[1]; pass cu_seqlens_q to the combine and skip those rows. Auto split-3 now replaces the unsplit kernel for existing gfx942 calls (finding 2), so please also provide base-vs-head operator timings on the current head across the Sk>=8192 / Sq-up-to-2xCU range, a backward dq/dk/dv accuracy check on split-selected shapes, and forward accuracy results on MI300X; finding 3 asks for the test's arch gate to use get_gfx_runtime().

Findings

  1. major csrc/py_itfs_cu/asm_mha_varlen_fwd.cu:581 — The gate checks max_seqlen_q == total_q but not cu_seqlens_q. With cu_seqlens_q = [0, n], n < total_q, the combine still reads all total_q rows of the torch::empty o_parts/lse_parts and writes garbage into the caller's out= rows >= n, which the unsplit path left untouched. Pass cu_seqlens_q to the combine and skip those rows.
  2. major csrc/py_itfs_cu/asm_mha_varlen_fwd.cu:508 — Auto split-3 now replaces the unsplit kernel for existing flash_attn_varlen_func calls (gfx942 bf16 192x128, Sk>=8192), with no way back. Still missing: base-vs-head timings on the current head beyond 4096x42700 (incl. Sk near 8192 and Sq near the 2xCU bound), a backward/grad check, and accuracy on MI300X/MI300A.
  3. minor op_tests/test_fmha_gfx942_asm_splitkv.py:505 — main() gates on get_gfx(), which follows GPU_ARCHS. With a multi-arch build such as 'gfx950;gfx942' on an MI355X it returns gfx942, so the forced-split cases run and raise. Use get_gfx_runtime() for this gate.

Evidence requested

  • Base-vs-head operator timings measured on the current head (GPU model, ROCm version, base commit, sample count) for several shapes the auto gate now captures, e.g. Sk=8192/16K/42.7K/128K with Sq from 129 up to the q_tiles*H≈2xCU bound, listing any shape that gets slower. (The only number predates the current head and covers one shape, while the auto split now applies to the whole Sk>=8192 range.)
  • A backward accuracy check through flash_attn_varlen_func on a split-selected shape (e.g. 129x8192x4 and 4096x42700x12), comparing dq/dk/dv against a reference. (Under autograd, the CK varlen backward consumes the out and LSE produced by split-KV, and the author states backward is unverified.)
  • The forward accuracy run of op_tests/test_fmha_gfx942_asm_splitkv.py on MI300X (and MI300A if available), not only MI325X. (The C++ gate admits every gfx942 SKU except MI308, so all of them now take the new default.)

@shay-li77

Copy link
Copy Markdown
Contributor

@amd-yashagar

@amd-yashagar

Copy link
Copy Markdown
Contributor Author

@shay-li77 Thank you for the review, addressing the changes now. The review notification got buried in other emails. Sorry for the delay.

@amd-yashagar
amd-yashagar force-pushed the feat/gfx942-fmha-hd192-split-asm branch from 24eb312 to 797156c Compare November 25, 2026 08:37
Copilot AI lite review requested due to automatic review settings November 25, 2026 08:37
@github-actions github-actions Bot changed the title [ASM] [HIP] [JIT] [gfx942] Optimize long-context FMHA with split-KV [ASM] [HIP] [CI] [gfx942] Optimize long-context FMHA with split-KV Nov 25, 2026
@github-actions github-actions Bot added the CI label Nov 25, 2026
@amd-yashagar
amd-yashagar force-pushed the feat/gfx942-fmha-hd192-split-asm branch from 797156c to caf7ef8 Compare November 25, 2026 08:39

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

The auto-selection threshold contradicts the documented contract and leaves the stated MI325X shape unsplit, so the selector, tests, and PR description must be aligned.

5 open issues

Review effort: Lite

Comment on lines +28 to +31
const int q_wgs =
((seqlen_q + kFmhaHd192SplitKvQTile - 1) / kFmhaHd192SplitKvQTile) * nhead;
if(q_wgs > static_cast<int>(4 * get_num_cu_func() / 3))
return 1;
Copilot AI lite review requested due to automatic review settings November 25, 2026 08:42

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.

🔵 Needs a closer look

The selector contradicts the documented auto-selection contract for workloads between 4CU/3 and 2CU, and the implementation, tests, and PR description need to be reconciled with a boundary test.

5 open issues

Review effort: Lite

@amd-yashagar
amd-yashagar force-pushed the feat/gfx942-fmha-hd192-split-asm branch from caf7ef8 to fc6fbf7 Compare November 25, 2026 08:50
Copilot AI lite review requested due to automatic review settings November 25, 2026 08:50

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.

🔵 Needs a closer look

The implementation and test use a stricter 4CU/3 auto-mode cutoff than the PR description’s stated 2CU contract, so the dispatch behavior or documentation must be aligned.

5 open issues

Review effort: Lite

Long-KV packed-varlen attention with D_QK=192 / D_V=128 underfills
gfx942 when the Q grid is small. Add an ASM split-KV producer plus an
LSE combine kernel behind fmha_v3_varlen_fwd(num_splits=...):
0 = auto, 1 = unsplit, 2-8 = forced split.

Auto picks split-3 for gfx942 (not MI308) BF16, batch 1, non-causal,
no dropout/bias/SWA/padded cu_seqlens, Sk >= 8192 and
Q_tiles * heads <= 4 * CU / 3. Everything else stays on the existing
kernel; a forced split on an unsupported input raises.

The kernel clamps splits to cu_seqlens_k and the combine leaves rows
outside cu_seqlens_q untouched, so no host sync is needed and the path
is CUDA-graph safe. Inputs whose Q/K/V or partial-plane byte spans
exceed 32-bit offsets fall back to unsplit (auto) or raise (forced).
@amd-yashagar
amd-yashagar force-pushed the feat/gfx942-fmha-hd192-split-asm branch from fc6fbf7 to b52b5fa Compare November 25, 2026 10:02
Copilot AI lite review requested due to automatic review settings November 25, 2026 10:02

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

The implementation still has an unresolved dispatch-threshold mismatch with the stated contract and can issue an invalid zero-grid split launch for valid empty-query inputs.

6 open issues

Review effort: Lite

Comment on lines +517 to +519
num_splits = select_hd192_splitkv_num_splits(
num_splits, splitkv_compatible, max_seqlen_q, num_heads, max_seqlen_k);
const bool use_hd192_splitkv = num_splits > 1;
@amd-yashagar

Copy link
Copy Markdown
Contributor Author

@shay-li77

Thanks for the review. The requested fixes and current-head validation are complete.

  1. Q rows outside the logical interval: The combine receives cu_seqlens_q and skips rows outside the active interval, preserving caller-provided out= and LSE rows. Tests cover short, offset, and empty Q intervals.

  2. Auto-selection and performance: The gfx942 gate is now ceil(Sq/128) * H <= floor(4 * CU / 3). On the current head b52b5fa1a, all 20 split-selected shapes were faster on both MI300X and MI325X. For the ticket shape (Sq=4096, Sk=42700, H=12), latency was 3.523 → 3.354 ms on MI300X and 2.758 → 2.303 ms on MI325X.

    The 12 shapes just above the gate remained unsplit and produced bitwise-identical output to base. Measured head/base latency ratios were 0.996–1.002 on MI300X and 0.999–1.007 on MI325X. On MI325X, the largest median slowdown was 0.67% (Sq=6400, Sk=16384, H=12); timings used separate processes and are not paired.

    flash_attn_varlen_func continues to auto-select and has no per-call opt-out. The lower-level fmha_v3_varlen_fwd(num_splits=1) still selects the unsplit path.

  3. Backward and forward accuracy: The full split-KV suite passed on both GPUs at b52b5fa1a. Backward dq/dk/dv checks against an FP32 CPU reference passed for 129x8192x4 and 4096x42700x12; the worst relative L2 was 0.002368. The 32-shape forward matrices passed at atol/rtol 0.02; maximum relative L2 was 0.003196 on MI300X and 0.003192 on MI325X. MI300A was not available.

  4. Architecture gate: The test now uses get_gfx_runtime() rather than the build-target architecture.

@shay-li77

Copy link
Copy Markdown
Contributor

@amd-yashagar Thanks, this addresses the earlier review: the combine now skips rows outside cu_seqlens_q, the selection data on MI300X/MI325X covers what I asked for, and the test uses get_gfx_runtime(). Two of Copilot's points from its last review are still open on b52b5fa:

  1. With an empty Q (q.size(0) == 0, so q_wgs == 0) and max_seqlen_k >= 8192, select_hd192_splitkv_num_splits still returns split-3. Please fall back to the unsplit path when q_wgs == 0, so an empty call behaves as it does on main.
  2. The PR description still says auto selection allows Q_tiles * heads <= 2 * CU, but the code uses floor(4 * CU / 3). Please update the description to match.

Main also requires every review conversation to be resolved before merge. Six are still open, four of which you've already answered, so please resolve them once these are done. Then I'll approve and merge.

This branch has not been deployed

No deployments
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.

5 participants