You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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=:
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.
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-actionsBot
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
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.
[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.
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).
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.
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,
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.
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.
[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.
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.
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
majorcsrc/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.
majorcsrc/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.
minorop_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.)
github-actionsBot
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
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.
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.
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.
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).
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.
Thanks for the review. The requested fixes and current-head validation are complete.
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.
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.
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.
Architecture gate: The test now uses get_gfx_runtime() rather than the build-target architecture.
@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:
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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_funcAPI.Technical Details
num_splitstofmha_v3_varlen_fwd:0is auto,1is unsplit, and2–8force a split count.Sk >= 8192andceil(Sq/128) * H <= floor(4 * CU / 3). Other calls remain unsplit.cu_seqlens_q, preserving output rows outside the active interval. The producer handles ragged and empty K usingcu_seqlens_k, without a host sync.Test Plan
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 for129x8192x4and4096x42700x12.Base
e48c06d89versus headb52b5fa1a, BF16, batch 1, noncausal, preallocatedout=: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
b52b5fa1acbf223107c4df15cad690099fa1d20dBehavior 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.