Skip to content

[HIP] [FlyDSL] [Feature] OPUS bf16 flash-attn: head dim 64 and attention sinks (gfx950) - #5223

Merged
shay-li77 merged 4 commits into
ROCm:mainfrom
siqiy-cerebras:opus-d64-sym-sinks-varlen
Nov 22, 2026
Merged

shay-li77 merged 4 commits into
ROCm:mainfrom
siqiy-cerebras:opus-d64-sym-sinks-varlen

Conversation

@siqiy-cerebras

@siqiy-cerebras siqiy-cerebras commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

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 (default 0).

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

  • d=64 (opus fmha: support symmetric head dim 64 alongside 128). opus_gqa_traits already derives every tile, LDS and MFMA count from D_TILE_SIZE, and the kernel body has no literal head-dim constant; only static_assert(D_TILE_SIZE_ == 128) and the host-side D == 128 checks kept d=64 out. Each divisibility condition the tiling relies on is now a static_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 a static_assert, and the launcher, the torch entry and both Python gates refuse a window at d=64.
  • Sinks (opus fmha: attention-sink support for the symmetric kernel). The sink is folded in once, in store_result, so O and LSE are both correct in batch and group mode. Finalization rebases onto M = max(key max, sink) and rescales the denominator by alpha = exp2(m_row - M), so a dominant sink cannot overflow exp2 and a +inf sink cannot produce inf - inf. alpha folds into the final reciprocal, so the accumulator is still scaled once, and alpha == 1 exactly 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 at O = 0, lse = sink; its row max is only a sentinel, so rebasing onto it would lose a sink below that sentinel. Plumbing: ptr_sink in opus_gqa_kargs, sink_ptr in fmha_fwd_bf16_opus_args, a trailing optional sink on 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 + autograd. Every backward passes 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 raise NotImplementedError for that case.
  • Tests (opus fmha: tests for head dim 64 and attention sinks, plus the review-round commit opus 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_func with AITER_ENABLE_FMHA_OPUS=0 (Before: the default dispatch, which builds and runs the CK mha_fwd / mha_varlen_fwd on 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 are linspace(-4, 12) over the heads.

Hardware Workload/configuration Before After Change
1× gfx950 dense b1, sq 4096 / sk 32768, causal 2940.5 µs 2243.0 µs 1.31×
1× gfx950 dense b1, sq 4096 / sk 32768, causal, sink 2779.8 µs 2252.7 µs 1.23×
1× gfx950 dense b1, sq 4096 / sk 32768, non-causal 2983.8 µs 2354.9 µs 1.27×
1× gfx950 dense b1, sq 4096 / sk 32768, non-causal, sink 2980.7 µs 2361.7 µs 1.26×
1× gfx950 varlen 4 × (sq 2048 / sk 8192), causal 1342.2 µs 1125.3 µs 1.19×
1× gfx950 varlen 4 × (sq 2048 / sk 8192), causal, sink 1290.9 µs 1126.8 µs 1.15×
1× gfx950 varlen 4 × (sq 2048 / sk 8192), non-causal 1493.9 µs 1209.7 µs 1.23×
1× gfx950 varlen 4 × (sq 2048 / sk 8192), non-causal, sink 1489.2 µs 1215.5 µs 1.23×

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, calling fmha_fwd_bf16_opus_fwd / fmha_fwd_bf16_opus_varlen_fwd directly 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

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X — not applicable: the OPUS kernels are gfx950-only and the gates require gfx950
  • Tested on MI300X — not applicable, same reason

Tested on one gfx950 GPU; details under "Validation and unverified scope".

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

  • New C++ parameters are trailing optionals, so callers are source-compatible; the mangled symbol changes, so the JIT module rebuilds.
  • A sink-enabled call through flash_attn_func / flash_attn_varlen_func that tracks gradients now raises NotImplementedError instead 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=1 on gfx950, bf16 forward calls with D_QK == D_V == 64, and symmetric calls carrying sink_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

  • Op tests at 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 set AITER_ENABLE_FMHA_OPUS=1 per test.
  • Negative control: test_flash_attn_func_opus_sink_below_sentinel was also run against the previous revision's kernel (ba741ff50).
    • masked_rows-64 and masked_rows-128 fail: all 6144 fully masked rows return lse = -inf.
    • The two no_keys cases pass, because the no-keys early exit already handled them.
  • CPU: python3 -m pytest -q op_tests/test_mha_optional_flydsl.py → 6 passed. This file is what failed CI on 949ae49b3. black 25.11 and ruff 0.16.0 pass.
  • Rebase: 5f2db05aea54 is the same four commits as fce9e6c6b72d, rebased onto main 044e23329 to pick up [Test] test_ar_norm_precedence: give the stand-in should_fly_allreduce_rmsnorm #8313. git range-diff reports every commit as identical, and there were no conflicts. Since then, main has changed only the backward path in aiter/ops/mha.py and unrelated build entries in rocm_ops.hpp and optCompilerConfig.json. The OPUS sources and tests are unchanged, so the GPU results above still apply. The CPU checks were re-run at 5f2db05aea54.
  • How it was run: this branch's 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_AVAILABLE was forced to False, because the installed flydsl predates main's FlyDSL entry points. On gfx950 FlyDSL serves only fp8, so bf16 routing is unaffected.
    • get_gfx_runtime was aliased to get_gfx, because the install predates it. On that one-GPU machine both return gfx950.
  • Codegen: register counts come from the JIT-built module's code-object notes. They are unchanged from the previous revision, with no spills: d=128 VGPR 248/249 (occupancy 2), d=64 VGPR 166/167 (occupancy 3), SWA 253.
  • Unverified:
    • CI does not run any of these OPUS pytest functions. .github/scripts/aiter_test.sh runs 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 no test_*opus* names. CI does cover the OPUS module build and the script sweeps.
    • No model-level accuracy eval.
    • No end-to-end serving number on this revision.
    • MI250X/MI300X: not applicable.

PR-specific question

  • Architecture: gfx950 only. Both Python gates require get_gfx() == "gfx950", and fmha_fwd_bf16_opus_launch refuses any other arch.
  • Dtype: bf16 q/k/v/out (gate + torch entry). A sink must be fp32, [nhead_q], contiguous; the gates check it the way the launcher reads it, so a mismatch falls back instead of failing.
  • Shape: D_QK == D_V in {64, 128} selects gqa_d128_kernel. opus_gqa_traits static_asserts D in {64, 128} plus every divisibility the tiling needs, so another D fails to compile. Windows are D=128-only (static_assert in 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.
  • Invariant: three layers agree. The Python gates decline unsupported combinations, so the call falls back with correct output. The torch entry TORCH_CHECKs them. fmha_fwd_bf16_opus_launch returns 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.py
    • test_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 +inf sinks, fully-masked causal rows and the no-keys early exit. LSE is checked against logaddexp(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 its masked_rows cases fail on the previous revision.
    • test_flash_attn_{,varlen_}func_sink_requires_grad_rejected: the autograd guard.
    • _run_opus_batch_case gains a with_sink flag instead of a second harness.
    • The gfx950 gates this PR adds call get_gfx_runtime() (the live device) rather than get_gfx(). The same applies in test_mha_varlen.py.
  • op_tests/test_mha_varlen.py
    • test_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 at O = 0, lse = sink. _run_opus_group_case gains a sink argument.
    • The varlen dispatch table gains two positive d=64 rows. The existing d=64 row becomes 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 than cu_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.py

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Sep 3, 2026

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 5223 --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.

@siqiy-cerebras
siqiy-cerebras marked this pull request as ready for review September 3, 2026 15:54
@siqiy-cerebras
siqiy-cerebras requested review from a team and a lite review from Copilot September 3, 2026 15:54
@github-actions github-actions Bot changed the title [Feature] OPUS bf16 flash-attn: head dim 64, attention sinks, single-seq varlen routing (gfx950) [HIP] [Feature] OPUS bf16 flash-attn: head dim 64, attention sinks, single-seq varlen routing (gfx950) Sep 3, 2026
@github-actions github-actions Bot added the HIP label Sep 3, 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.

🟡 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.

Comment thread aiter/ops/mha.py Resolved
Comment thread op_tests/test_mha.py Resolved
@zufayu
zufayu requested a review from amd-ruitang3 September 4, 2026 23:44
Copilot AI review requested due to automatic review settings September 12, 2026 14:37
@siqiy-cerebras
siqiy-cerebras force-pushed the opus-d64-sym-sinks-varlen branch from 6580310 to 1cd38c3 Compare September 12, 2026 14:37

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

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 select fmha_v3_varlen_fwd, whose call has no sink parameter. A D=128 varlen request with sink_ptr therefore 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.dtype and never checks the dense out layout. 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 and out.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 when sq > 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 as sq=128, sk=64 and run it with causal=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

Comment thread aiter/ops/mha.py Resolved
Comment thread aiter/ops/mha.py Resolved
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 7, 2026
@zufayu
zufayu requested review from shay-li77 and removed request for amd-ruitang3 October 9, 2026 05:47
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Oct 10, 2026
Copilot AI lite review requested due to automatic review settings October 10, 2026 21:09
@siqiy-cerebras
siqiy-cerebras force-pushed the opus-d64-sym-sinks-varlen branch from 1cd38c3 to 6f6e4b1 Compare October 10, 2026 21:09

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.

Comment thread aiter/ops/mha.py Resolved
@github-actions

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Oct 26, 2026
@siqiy-cerebras
siqiy-cerebras force-pushed the opus-d64-sym-sinks-varlen branch from 6f6e4b1 to 949ae49 Compare November 15, 2026 04:53
Copilot AI lite review requested due to automatic review settings November 15, 2026 04:53
@aiter-bot

aiter-bot commented Nov 15, 2026 •

Copy link
Copy Markdown

READY FOR HUMAN REVIEW

PR Self-Review

Revision 5f2db05aea54 · 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

With `AITER_ENABLE_FMHA_OPUS=1` on gfx950, bf16 forward calls with `D_QK == D_V == 64`, and symmetric calls carrying `sink_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

- **Op tests** at `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 set `AITER_ENABLE_FMHA_OPUS=1` per test.
  - Result: **402 passed, 3 skipped**. That is varlen 247 passed and 3 skipped, plus mha 155 passed.
  - The 3 skips are #7584's windowed Q-pad cases, which skip themselves when non-causal.
  - This covers all existing OPUS tests (d=128 batch, group, SWA and Q-pad; d=192/v128; varlen dispatch) plus the new ones.
- **Negative control:** `test_flash_attn_func_opus_sink_below_sentinel` was also run against the previous revision's kernel (`ba741ff50`).
  - `masked_rows-64` and `masked_rows-128` fail: all 6144 fully masked rows return lse = -inf.
  - The two `no_keys` cases pass, because the no-keys early exit already handled them.
- **CPU:** `python3 -m pytest -q op_tests/test_mha_optional_flydsl.py` → 6 passed. This file is what failed CI on `949ae49b3`. black 25.11 and ruff 0.16.0 pass.
- **Rebase:** `5f2db05aea54` is the same four commits as `fce9e6c6b72d`, rebased onto main `044e23329` to pick up #8313. `git range-diff` reports every commit as identical, and there were no conflicts. Since then, main has changed only the backward path in `aiter/ops/mha.py` and unrelated build entries in `rocm_ops.hpp` and `optCompilerConfig.json`. The OPUS sources and tests are unchanged, so the GPU results above still apply. The CPU checks were re-run at `5f2db05aea54`.
- **How it was run:** this branch's `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_AVAILABLE` was forced to `False`, because the installed flydsl predates main's FlyDSL entry points. On gfx950 FlyDSL serves only fp8, so bf16 routing is unaffected.
  - `get_gfx_runtime` was aliased to `get_gfx`, because the install predates it. On that one-GPU machine both return gfx950.
- **Codegen:** register counts come from the JIT-built module's code-object notes. They are unchanged from the previous revision, with no spills: d=128 VGPR 248/249 (occupancy 2), d=64 VGPR 166/167 (occupancy 3), SWA 253.
- **Unverified:**
  - CI does not run any of these OPUS pytest functions. `.github/scripts/aiter_test.sh` runs 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 no `test_*opus*` names. CI does cover the OPUS module build and the script sweeps.
  - No model-level accuracy eval.
  - No end-to-end serving number on this revision.
  - MI250X/MI300X: not applicable.

PR-specific question

- **Architecture:** gfx950 only. Both Python gates require `get_gfx() == "gfx950"`, and `fmha_fwd_bf16_opus_launch` refuses any other arch.
- **Dtype:** bf16 q/k/v/out (gate + torch entry). A sink must be fp32, `[nhead_q]`, contiguous; the gates check it the way the launcher reads it, so a mismatch falls back instead of failing.
- **Shape:** `D_QK == D_V` in {64, 128} selects `gqa_d128_kernel`. `opus_gqa_traits` `static_assert`s D in {64, 128} plus every divisibility the tiling needs, so another D fails to compile. Windows are D=128-only (`static_assert` in 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.
- **Invariant:** three layers agree. The Python gates decline unsupported combinations, so the call falls back with correct output. The torch entry `TORCH_CHECK`s them. `fmha_fwd_bf16_opus_launch` returns 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.py`**
  - `test_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 `+inf` sinks, fully-masked causal rows and the no-keys early exit. LSE is checked against `logaddexp(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 its `masked_rows` cases fail on the previous revision.
  - `test_flash_attn_{,varlen_}func_sink_requires_grad_rejected`: the autograd guard.
  - `_run_opus_batch_case` gains a `with_sink` flag instead of a second harness.
  - The gfx950 gates this PR adds call `get_gfx_runtime()` (the live device) rather than `get_gfx()`. The same applies in `test_mha_varlen.py`.
- **`op_tests/test_mha_varlen.py`**
  - `test_fmha_fwd_bf16_opus_d64_group`: #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 at `O = 0, lse = sink`. `_run_opus_group_case` gains a `sink` argument.
  - The varlen dispatch table gains two positive d=64 rows. The existing d=64 row becomes `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 than `cu_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.py`**
  - Its harness runs `flash_attn_func` and `flash_attn_varlen_func` in a namespace with a hand-written list of globals. `_reject_sink_autograd` is a new module global those entries call, so it joins the namespace as a no-op, as `_IS_GFX1250_ASM_DEVICE` did in #7375. Without it, the four dispatch tests fail with `NameError`, which is what failed CI on `949ae49b3`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply

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.

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.

Comment thread aiter/ops/mha.py Resolved
Comment thread aiter/ops/mha.py Resolved
Comment thread op_tests/test_mha.py Resolved
Comment thread op_tests/test_mha_varlen.py Resolved
@siqiy-cerebras siqiy-cerebras changed the title [HIP] [Feature] OPUS bf16 flash-attn: head dim 64, attention sinks, single-seq varlen routing (gfx950) [HIP] [Feature] OPUS bf16 flash-attn: head dim 64 and attention sinks (gfx950) Nov 15, 2026
@github-actions github-actions Bot removed the stale The PR hasn't been updated in 2 weeks label Nov 16, 2026
@siqiy-cerebras
siqiy-cerebras force-pushed the opus-d64-sym-sinks-varlen branch from 949ae49 to fce9e6c Compare November 19, 2026 17:36
Copilot AI lite review requested due to automatic review settings November 19, 2026 17:36
@github-actions github-actions Bot changed the title [HIP] [Feature] OPUS bf16 flash-attn: head dim 64 and attention sinks (gfx950) [HIP] [FlyDSL] [Feature] OPUS bf16 flash-attn: head dim 64 and attention sinks (gfx950) Nov 19, 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.

Comment thread op_tests/test_mha.py Resolved
Comment thread op_tests/test_mha_varlen.py Resolved
@shay-li77

Copy link
Copy Markdown
Contributor

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

siqiy-cerebras and others added 4 commits November 20, 2026 11:37
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]>
@siqiy-cerebras
siqiy-cerebras force-pushed the opus-d64-sym-sinks-varlen branch from fce9e6c to 5f2db05 Compare November 20, 2026 19:41
Copilot AI lite review requested due to automatic review settings November 20, 2026 19:41

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

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

Review effort: Lite

@siqiy-cerebras

Copy link
Copy Markdown
Contributor Author

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

@shay-li77
shay-li77 merged commit 35c23e6 into ROCm:main Nov 22, 2026
75 of 76 checks passed
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.

4 participants