Repository navigation
[HIP] [FlyDSL] [Feature] OPUS bf16 flash-attn: head dim 64 and attention sinks (gfx950) - #5223
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
There was a problem hiding this comment.
🟡 Changes recommended
The new single-seq varlen routing predicate is missing a head-dim consistency check for K (can misroute invalid shapes), and a couple of newly introduced/modified messages/docs are inaccurate or misleading.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR extends the gfx950 OPUS bf16 flash-attention forward path (behind AITER_ENABLE_FMHA_OPUS) to cover additional previously-rejected cases: symmetric head dim D=64, optional per-head attention sinks, and single-sequence varlen routing to the dense OPUS path (including oversized K/V buffer prefix slicing), with new env-gated gfx950 tests.
Changes:
- Enable OPUS symmetric kernel instantiation/dispatch for D in {64, 128}, including corresponding host-side gating.
- Thread optional sink logits through the C++/pybind/Python launch stack and fold the sink into the denominator/LSE in-kernel.
- Route single-sequence varlen calls to the dense path and add tests for D=64, sinks, single-seq routing, and oversized K/V buffers.
File summaries
| File | Description |
|---|---|
| op_tests/test_mha.py | Adds gfx950 OPUS tests for D=64, sink correctness, single-seq varlen routing, and oversized K/V buffer behavior. |
| csrc/py_itfs_cu/fmha_fwd_bf16_opus_kernels.cu | Extends host launcher checks to allow D=64/128 symmetric + wires optional sink pointer into kernel args. |
| csrc/include/torch/fmha_fwd_bf16_opus.h | Extends the C++ API with a trailing optional sink argument. |
| csrc/include/rocm_ops.hpp | Exposes the new optional sink argument via pybind. |
| csrc/include/fmha_fwd_hd128_bf16_opus_kernel.hpp | Implements sink folding into the softmax denominator/LSE in the symmetric kernel store path. |
| csrc/include/fmha_fwd_hd128_bf16_opus_defs.h | Adds ptr_sink to kargs and relaxes traits to support D=64 or D=128 with divisibility static_asserts. |
| csrc/include/fmha_fwd_bf16_opus_launch.h | Adds sink pointer to launch args and dispatches symmetric kernel based on D=64 vs D=128 and causal flag. |
| aiter/ops/mha.py | Updates Python wrapper signature to accept sink, updates OPUS gating for sinks + D=64, and adds single-seq varlen→dense routing. |
Review details
Suppressed comments (1)
aiter/ops/mha.py:3741
- The single-seq varlen router checks q and v head dims match, but does not verify k has the same head dim. If k.shape[-1] != q.shape[-1], this path can still route into the dense call and fail later with a less actionable error (or potentially dispatch incorrectly). Add a k head-dim equality check alongside v.
if q.dim() != 3 or k.dim() != 3 or v.dim() != 3:
return False
if q.shape[-1] != v.shape[-1] or q.shape[-1] not in (64, 128):
return False
- Files reviewed: 8/8 changed files
- Comments generated: 3
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
6580310 to
1cd38c3
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Sink fallback and dtype/layout dispatch issues can produce incorrect routing or runtime failures.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (4)
aiter/ops/mha.py:3162
- The same silent sink loss exists for varlen dispatch: when the symmetric OPUS gate is false (including the default opt-out),
can_impl_fmha_v3_fwd()can still selectfmha_v3_varlen_fwd, whose call has no sink parameter. A D=128 varlen request withsink_ptrtherefore returns attention without the sink. Author must add a sink exclusion to the varlen v3 gate or select a sink-aware fallback, with a test while OPUS is disabled.
ret = ret and (
sink_ptr is None
or (
sink_ptr.dtype == dtypes.fp32
and sink_ptr.shape == (nhead_q,)
aiter/ops/mha.py:3140
- [verified] The multi-sequence symmetric varlen gate repeats the q-only dtype check. For a D=64 call with q bf16 and k/v fp16, all predicates pass and the branch at line 3188 invokes the OPUS wrapper, which rejects the mismatched scalar types instead of reaching the CK fallback. Author must require the packed K/V tensors to be bf16 before selecting this path.
ret = ret and (q.dtype == dtypes.bf16)
aiter/ops/mha.py:2080
- [verified] The new symmetric D=64/128 gate only checks
q.dtypeand never checks the denseoutlayout. With q bf16 and k/v (or out) fp16, or with a supplied out whose last stride is not 1, a valid D=64 shape reaches the OPUS wrapper; its C++ validation requires q/k/v/out to share bf16 and all last strides to be unit (csrc/py_itfs_cu/fmha_fwd_bf16_opus_kernels.cu:135-137,377-380). It raises instead of falling back to CK. Author must gate the symmetric path on K/V/out dtypes andout.stride(-1) == 1.
if hdim_q != hdim_v or hdim_q not in (64, 128):
return False
op_tests/test_mha.py:1295
- [verified] The sink cases only use equal query/key lengths plus
seqlen_kv=0. The zero-key case takes the kernel's early no-KV path, so it does not exercise sink handling after a nonempty causal tile has fully masked the first rows whensq > sk; the PR description claims that coverage. A regression in that branch could return incorrect O/LSE while all current sink tests pass. Author must add a sink case such assq=128, sk=64and run it withcausal=True.
(2, 300, 0, 8, 2), # no keys -> every row attends only the sink
- Files reviewed: 8/8 changed files
- Comments generated: 2
- Review effort level: Lite
|
No activity for 15 days, so this is now labelled |
1cd38c3 to
6f6e4b1
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Critical correctness issues remain in masked-window dispatch and very negative sink handling, along with validation gaps.
4 open findings
Require fully unmasked windows before selecting the group-mode kernel · New Use sink logits when all causal keys are masked · New WhenAITER_ENABLE_FMHA_OPUS=0(or the OPUS gate rejects an asymmetric shape), this sink-enabled… This newly enabledbatch_size > 1branch and the accompanying group-mode tests implement…
3 resolved since last review
🧠 Review effort: Lite
|
No activity for 15 days, so this is now labelled |
6f6e4b1 to
949ae49
Compare
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
There was a problem hiding this comment.
🟡 Changes recommended
The change still has two verified moderate correctness gaps: dense out= is not exposed through the public API, and padded varlen inputs are not rejected as required by the stated contract.
6 open issues
Use sink logits when all causal keys are masked Require fully unmasked windows before selecting the group-mode kernel Public dense API does not expose the out parameter · New Varlen eligibility gate accepts caller-supplied padded lengths · New gfx950 test gate checks build target instead of runtime GPU · New Varlen test gates use build target instead of runtime GPU · New
2 resolved since last review
Review effort: Lite
949ae49 to
fce9e6c
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The new OPUS and varlen test cases are skipped by the standard CI command because they follow a Python benchmark entry point and are not collected with pytest, leaving key dispatch and sink paths unverified.
8 open issues
Use sink logits when all causal keys are masked Require fully unmasked windows before selecting the group-mode kernel Ensure new OPUS tests run in the standard Aiter test job · New Ensure new varlen OPUS tests run in the standard Aiter test job · New Varlen eligibility gate accepts caller-supplied padded lengths Public dense API does not expose the out parameter Varlen test gates use build target instead of runtime GPU gfx950 test gate checks build target instead of runtime GPU
Review effort: Lite
|
@siqiy-cerebras Thanks for the update. I've reviewed fce9e6c and it looks good to me. The only CI failure (Aiter Test shard 0, test_ar_rmsnorm_routing.py) was a main issue that has since been fixed by #8313. Please rebase onto the latest main to trigger a fresh CI run; re-running the old job would reuse the old merge commit and fail again. Once CI passes, I'll approve and merge. |
opus_gqa_traits already derives every tile, LDS and MFMA count from D_TILE_SIZE, and the gqa_d128_kernel body has no literal head-dim constant. What kept D=64 out was the static_assert(D_TILE_SIZE_ == 128) plus the host-side D==128 checks. At D=64 every derived count stays integral: smem_d_rpt 2->1, GEMM0_E_K 8->4, GEMM1_E_N 4->2, k/v_buffer_load_insts 2->1, k_ds_read_insts 16->8, v_ds_read_insts 32->16. Each of those divisibility conditions is now a static_assert, so a future D fails to compile instead of silently dropping work. D=64 keeps the D=128 tile shape (Q=32, KV=64, 8 waves) and gets the batch and group (varlen) instances, causal and non-causal. The sliding-window kernel stays D=128 only: it gains a static_assert, and the launcher, the torch entry and both Python gates refuse a window at D=64, so such a call falls back instead of reaching a kernel that has no instance for it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Siqi Yan <[email protected]>
gpt-oss carries a learned per-head sink logit on every attention layer, and the OPUS gates rejected sink_ptr outright, so its D=64 prefill never reached OPUS. A sink is one extra key that joins the softmax denominator but carries no value: out = (sum_j exp(s_j) v_j) / (sum_j exp(s_j) + exp(sink)) It is folded in once, in store_result, which fixes the O normalization and the LSE together, in batch and group mode alike. Finalization rebases onto M = max(key max, sink) and rescales the online denominator by alpha = exp2(m_row - M), so a dominant sink cannot overflow exp2 and a +inf sink cannot produce inf - inf. alpha is folded into the final reciprocal, so the output accumulator is still scaled exactly once, and when the sink does not dominate alpha is exactly 1. A row with no keys ends with O = 0 and lse = sink. m_row/l_row are base-2 while the sink is a natural-log logit, hence LOG2_E. Plumbing: ptr_sink in opus_gqa_kargs and sink_ptr in fmha_fwd_bf16_opus_args; [H] fp32 contiguous validation in the torch entry; a trailing optional `sink` on the torch declaration, the pybind def, the op stub and its fake, and both public wrappers; the dense and varlen dispatch sites pass sink_ptr. The gates admit a sink when it is [nhead_q] fp32 and contiguous, on the symmetric kernel, and without a window -- the sliding-window kernel does not read it, and the launcher refuses that combination and any asymmetric head dim rather than silently drop the sink. sink_size (the "first N keys are sinks" variant) stays unsupported. Every backward hard-codes sink=None, so a gradient-tracked sink call would get dQ/dK/dV from a different softmax and no d_sink. flash_attn_func and flash_attn_varlen_func, and their autograd Functions, now reject that with NotImplementedError instead. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Siqi Yan <[email protected]>
Dense (op_tests/test_mha.py), through flash_attn_func:
* test_flash_attn_func_opus_d64 -- the D=128 batch matrix one head dim down.
* test_flash_attn_func_opus_sink -- a per-head sink for D in {64, 128}, including
fully-masked causal rows and a no-key case, so "attend only the sink" runs both
inside a block with keys and on the no-keys early exit. O is checked against
attention_ref; the fp32 LSE against logaddexp(no-sink LSE, sink) -- the sharp
check, since the sink lives in the softmax denominator.
* test_flash_attn_func_opus_sink_dominant / _posinf -- the max-rebase: a sink
far above every key score stays finite, and a +inf sink gives O = 0, LSE = +inf.
* test_flash_attn_{,varlen_}func_sink_requires_grad_rejected -- the autograd guard.
Group (op_tests/test_mha_varlen.py), _run_opus_group_case gains a sink:
* test_fmha_fwd_bf16_opus_d64_group -- the D=128 group contract matrix at D=64.
* test_fmha_fwd_bf16_opus_group_sink -- the same matrix with a sink, D in
{64, 128}; empty-KV groups must end at O = 0 and LSE = sink.
* test_flash_attn_varlen_func_opus_dispatch gains positive D=64 rows; the
existing D=64 + window row stays a rejection, now with a reason.
* test_flash_attn_varlen_func_opus_sink_dispatch -- a sink reaches OPUS through
the public entry, except together with a window.
* test_flash_attn_varlen_func_opus_oversized_kv -- one sequence whose K/V buffer
is longer than cu_seqlens_k (vLLM's chunked-context workspace) with a NaN tail
that must never be attended.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Siqi Yan <[email protected]>
…w tests A causal row whose keys are all masked keeps attn_row_max's -1e30 sentinel as its max, so a finite sink below it underflowed to lse = -inf. Rows with l_row == 0 now take lse = sink and O = 0 directly; every other row is unchanged. test_flash_attn_func_opus_sink_below_sentinel covers both no-key paths. The gfx950 gates this PR added use get_gfx_runtime(), which reads the live device rather than GPU_ARCHS. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Siqi Yan <[email protected]>
fce9e6c to
5f2db05
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
Approval should be deferred because the gfx950 HIP kernel, dispatch, and autograd changes lack exact-revision, head-matched GPU validation across the d64, sink, masking, empty-row, and fallback paths, with supplied results coming from an older overlaid install.
No open issues 🎉
8 resolved since last review
Use sink logits when all causal keys are masked Require fully unmasked windows before selecting the group-mode kernel Ensure new varlen OPUS tests run in the standard Aiter test job Ensure new OPUS tests run in the standard Aiter test job Varlen eligibility gate accepts caller-supplied padded lengths Public dense API does not expose the out parameter Varlen test gates use build target instead of runtime GPU gfx950 test gate checks build target instead of runtime GPU
Review effort: Lite
|
Thank you @shay-li77 for reviewing this PR! I've rebase onto the latest main, next would need your approval to run CI workflows :-D |



Summary
Extends the gfx950 OPUS bf16 flash-attention forward (
gqa_d128_kernel) to symmetric head dim 64 and to attention sinks (one learned fp32 logit per query head), in both batch mode and the group/varlen mode added by #7584. Same opt-in as the existing symmetric path:AITER_ENABLE_FMHA_OPUS=1(default0).This PR was rebased onto #7584. #7584's group mode supersedes the group mode and single-sequence varlen router this PR originally carried, so those commits are gone; what remains is d=64 and sinks on top of it.
Motivation
gpt-oss prefill is bf16, d=64 (64 q heads / 8 kv heads), with a learned sink on every attention layer. The OPUS gates rejected both d=64 and any
sink_ptr, so these calls ran on the CK forward. See Performance for what OPUS gives on the same calls.Changes
opus fmha: support symmetric head dim 64 alongside 128).opus_gqa_traitsalready derives every tile, LDS and MFMA count fromD_TILE_SIZE, and the kernel body has no literal head-dim constant; onlystatic_assert(D_TILE_SIZE_ == 128)and the host-sideD == 128checks kept d=64 out. Each divisibility condition the tiling relies on is now astatic_assert. D=64 reuses the D=128 tile shape (Q=32, KV=64, 8 waves) and gets 4 instances (batch/group × causal/non-causal). The sliding-window kernel stays D=128-only: it gains astatic_assert, and the launcher, the torch entry and both Python gates refuse a window at d=64.opus fmha: attention-sink support for the symmetric kernel). The sink is folded in once, instore_result, so O and LSE are both correct in batch and group mode. Finalization rebases ontoM = max(key max, sink)and rescales the denominator byalpha = exp2(m_row - M), so a dominant sink cannot overflowexp2and a+infsink cannot produceinf - inf.alphafolds into the final reciprocal, so the accumulator is still scaled once, andalpha == 1exactly when the sink does not dominate. A row with no unmasked key (no keys at all, or a causal row whose keys are all masked) takes its own branch and ends atO = 0, lse = sink; its row max is only a sentinel, so rebasing onto it would lose a sink below that sentinel. Plumbing:ptr_sinkinopus_gqa_kargs,sink_ptrinfmha_fwd_bf16_opus_args, a trailing optionalsinkon the torch entry, pybind, op stub/fake and both public wrappers. The gates admit a sink only when it is[nhead_q]fp32 contiguous, on the symmetric kernel, without a window; the launcher refuses the other combinations instead of silently dropping the sink.sink=None, so a gradient-tracked sink call would get dQ/dK/dV from a different softmax and no d_sink.flash_attn_func/flash_attn_varlen_func(and their autograd Functions) now raiseNotImplementedErrorfor that case.opus fmha: tests for head dim 64 and attention sinks, plus the review-round commitopus fmha: sink on rows with no unmasked key; runtime arch gate in new tests), described under "Changed op tests".Performance (if applicable)
One gfx950 GPU, bf16, 64 q heads / 8 kv heads, d=64. Measured through the public
flash_attn_func/flash_attn_varlen_funcwithAITER_ENABLE_FMHA_OPUS=0(Before: the default dispatch, which builds and runs the CKmha_fwd/mha_varlen_fwdon these shapes) and=1(After: OPUS). Both arms ran in the same process; a spy on the OPUS entry confirmed it ran only in the After arm. Median of 50 iterations after 10 warmup; causal is bottom-right aligned. Sinks arelinspace(-4, 12)over the heads.With the sink on, OPUS time is within 0.5% of the no-sink run on every shape (the sink is one epilogue term).
The table was measured at
949ae49b3. The review round's only kernel change is the no-key sink branch. I re-timed it in one session against the previous revision's kernel, callingfmha_fwd_bf16_opus_fwd/fmha_fwd_bf16_opus_varlen_fwddirectly at the same eight shapes. Every row matched within 0.1%: for example, dense causal with a sink measured 2192.5 µs before and 2192.4 µs after.Testing
Tested on one gfx950 GPU; details under "Validation and unverified scope".
Documentation
Dependencies
Breaking Changes
flash_attn_func/flash_attn_varlen_functhat tracks gradients now raisesNotImplementedErrorinstead of returning gradients computed without the sink. Inference callers (torch.no_grad()) are unaffected.PR Self-Review
Reviewed revision
5f2db05
Behavior and intent
With
AITER_ENABLE_FMHA_OPUS=1on gfx950, bf16 forward calls withD_QK == D_V == 64, and symmetric calls carryingsink_ptr, now run on the OPUS kernel in batch and group/varlen mode; before, the gates sent them to CK. Everything else dispatches as before. The existing behavior was insufficient because d=64 + sinks is the gpt-oss prefill shape, and OPUS is faster than the CK forward on it (Performance).Validation and unverified scope
fce9e6c6b72d, one MI355X (gfx950):python3 -m pytest -q op_tests/test_mha_varlen.py op_tests/test_mha.py -k "opus or sink_requires_grad". The OPUS tests setAITER_ENABLE_FMHA_OPUS=1per test.test_flash_attn_func_opus_sink_below_sentinelwas also run against the previous revision's kernel (ba741ff50).masked_rows-64andmasked_rows-128fail: all 6144 fully masked rows return lse = -inf.no_keyscases pass, because the no-keys early exit already handled them.python3 -m pytest -q op_tests/test_mha_optional_flydsl.py→ 6 passed. This file is what failed CI on949ae49b3. black 25.11 and ruff 0.16.0 pass.5f2db05aea54is the same four commits asfce9e6c6b72d, rebased onto main044e23329to pick up [Test] test_ar_norm_precedence: give the stand-in should_fly_allreduce_rmsnorm #8313.git range-diffreports every commit as identical, and there were no conflicts. Since then, main has changed only the backward path inaiter/ops/mha.pyand unrelated build entries inrocm_ops.hppandoptCompilerConfig.json. The OPUS sources and tests are unchanged, so the GPU results above still apply. The CPU checks were re-run at5f2db05aea54.aiter/ops/mha.py,aiter/test_mha_common.py,aiter/plugin/__init__.py,csrc/include, the OPUS sources and the two op-test files were overlaid on an older aiter install. The OPUS module was then rebuilt from the overlaid csrc. Two container-local changes were needed:_FLYDSL_AVAILABLEwas forced toFalse, because the installed flydsl predates main's FlyDSL entry points. On gfx950 FlyDSL serves only fp8, so bf16 routing is unaffected.get_gfx_runtimewas aliased toget_gfx, because the install predates it. On that one-GPU machine both return gfx950..github/scripts/aiter_test.shruns both files as scripts (python3 "$file"), and the tests are defined after the__main__sweep. This is also true of main's existing OPUS tests: the Standard Tests logs contain notest_*opus*names. CI does cover the OPUS module build and the script sweeps.PR-specific question
get_gfx() == "gfx950", andfmha_fwd_bf16_opus_launchrefuses any other arch.[nhead_q], contiguous; the gates check it the way the launcher reads it, so a mismatch falls back instead of failing.D_QK == D_Vin {64, 128} selectsgqa_d128_kernel.opus_gqa_traitsstatic_asserts D in {64, 128} plus every divisibility the tiling needs, so another D fails to compile. Windows are D=128-only (static_assertin the SWA kernel). Sinks require a symmetric head dim and no window, because the SWA and d192/v128 kernels don't read them. The existing 2^32 KV byte-extent guard and the GQA divisibility check are unchanged.TORCH_CHECKs them.fmha_fwd_bf16_opus_launchreturns false (window at d=64, sink with a window or an asymmetric head dim) rather than launching a kernel that would ignore the request.Changed op tests
op_tests/test_mha.pytest_flash_attn_func_opus_d64: the d=128 batch matrix at d=64. It is the only coverage of the d=64 batch instances.test_flash_attn_func_opus_sink,_sink_dominant,_sink_posinf: the only coverage of the sink epilogue. They cover normal, dominant and+infsinks, fully-masked causal rows and the no-keys early exit. LSE is checked againstlogaddexp(no-sink LSE, sink).test_flash_attn_func_opus_sink_below_sentinel: a finite sink (-1e31) that sits below the kernel's -1e30 row-max sentinel. It runs on fully masked causal rows inside non-empty KV and on the no-keys exit. It is the only coverage of the no-key sink branch, and itsmasked_rowscases fail on the previous revision.test_flash_attn_{,varlen_}func_sink_requires_grad_rejected: the autograd guard._run_opus_batch_casegains awith_sinkflag instead of a second harness.get_gfx_runtime()(the live device) rather thanget_gfx(). The same applies intest_mha_varlen.py.op_tests/test_mha_varlen.pytest_fmha_fwd_bf16_opus_d64_group: [HIP] [Feature] Add group/varlen and sliding-window support to the hd128 opus forward #7584's group contract matrix at d=64. It is the only coverage of the d=64 group instances.test_fmha_fwd_bf16_opus_group_sink: the same matrix with a sink at d=64/128. Empty-KV groups must end atO = 0, lse = sink._run_opus_group_casegains asinkargument.hdim64_window, still a rejection.test_flash_attn_varlen_func_opus_sink_dispatch: a sink reaches OPUS through the public entry, except with a window.test_flash_attn_varlen_func_opus_oversized_kv: one sequence whose K/V buffer is longer thancu_seqlens_k(as in vLLM's chunked-context workspace), with a NaN tail that must never be attended. No existing test covers an oversized K/V buffer.op_tests/test_mha_optional_flydsl.pyflash_attn_funcandflash_attn_varlen_funcin a namespace with a hand-written list of globals._reject_sink_autogradis a new module global those entries call, so it joins the namespace as a no-op, as_IS_GFX1250_ASM_DEVICEdid in [ASM] [HIP] [FlyDSL] [gfx1250] asm mha fp8 fwd: add D192x128 per-tensor varlen kernel #7375. Without it, the four dispatch tests fail withNameError, which is what failed CI on949ae49b3.🤖 Generated with Claude Code