Skip to content

[FlyDSL] [gfx1250] FMHA prefill: support v_hdim 256 - #6897

Merged
coderfeli merged 1 commit into
mainfrom
vigokhal/flydsl-fmha-gfx1250-vhdim256
Oct 26, 2026
Merged

coderfeli merged 1 commit into
mainfrom
vigokhal/flydsl-fmha-gfx1250-vhdim256

Conversation

@vgokhale

@vgokhale vgokhale commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The gfx1250 m32x8 FMHA prefill kernel declines v_hdim 256. The Qwen3.5 / Qwen3-Next full-attention layers use qk_hdim = v_hdim = 256. Add support to the kernel to support this model.

Change

  • Add 256 to SUPPORTED_V_HDIM.
  • At BLOCK_M 256 (2 Q tiles per wave), the O epilogue tile does not fit its LDS staging chunk when v_hdim is 256. supported_num_q_tiles / _pick_num_q_tiles now check that the O tile fits for the requested v_hdim, so v_hdim 256 runs at BLOCK_M 128.
  • The routers in fmha_kernels.py pass v_hdim to supports_gqa_ratio.
  • test_mha_flydsl.py adds the (256, 256) and (128, 256) pairs.

Results (gfx1250, FlyDSL 0.4.0)

python op_tests/test_mha_flydsl.py -s 256,256: 829/829 checks pass.

Qwen-style GQA with ragged lengths and sq != sk, 256/256 checks pass:
-l thd -s 256,256 -c 1 -b 1 3 8 -nh 4 16 -nhkv 1 2 -sq 1 17 300 2048 -sk 300 2048 5000 --rand-seqlens 3

flash_attn_varlen_func, bf16, causal, qk = v = 256. Times in µs, TFLOPS in parentheses:

heads q/kv seqlen × batch time (µs) TFLOP/s max diff
4/1 1024 × 1 17.1 126 0.016
4/1 4096 × 1 52.8 651 0.016
4/1 8192 × 1 114.3 1203 0.016
4/1 1024 × 8 21.0 819 0.016
4/1 2048 × 16 101.3 1356 0.016
16/2 1024 × 1 18.1 476 0.016
16/2 4096 × 1 80.6 1704 0.016
16/2 8192 × 1 297.5 1848 0.016
16/2 1024 × 8 61.5 1118 0.016
16/2 2048 × 16 360.0 1527 0.016

Qwen3.5-35B-A3B-MXFP4 in ATOM, TP4, lm_eval GSM8K 3-shot at 64 concurrent requests:

prefill attention flexible strict
FlyDSL , two runs 0.8643 / 0.8666 0.8560 / 0.8560

Overlaps #6702, which also touches fmha_fwd_prefill_a16w16_m32x8.py and fmha_kernels.py; whichever lands second needs a small rebase.

Allow v_hdim 256 in the m32x8 prefill kernel (qk_hdim 256 / v_hdim 256 is
the Qwen3.5 / Qwen3-Next full-attention shape).

At BLOCK_M 256 the O epilogue tile does not fit its LDS staging chunk, so
the Q tile choice now checks the O fit for the requested v_hdim and
v_hdim 256 runs at BLOCK_M 128.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vgokhale
vgokhale requested a review from a team October 24, 2026 02:26
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6897 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@coderfeli

Copy link
Copy Markdown
Collaborator

@ruanjm

@coderfeli
coderfeli merged commit 31729e8 into main Oct 26, 2026
56 checks passed
@coderfeli
coderfeli deleted the vigokhal/flydsl-fmha-gfx1250-vhdim256 branch October 26, 2026 02:44
ruanjm added a commit that referenced this pull request Oct 26, 2026
Brings in 121 commits of main, including #6897 (v_hdim 256 for the gfx1250
m32x8 prefill kernel).

Resolution: the only conflict was in fmha_kernels.py, where both sides changed
the two forward dispatchers. This branch moved the gfx1250 eligibility check
out of the router and into the kernels' own support gates
(flash_attn_a16w16_m32x8_supported / flash_attn_a8w8_m32x8_supported), while
main still had the inline gate and added v_hdim to its supports_gqa_ratio
call. Kept this branch's structure -- main's block is the pre-refactor form of
code that now lives in the gates.

That resolution dropped main's new v_hdim argument, so the a16w16 gate now
passes v_hdim to supports_gqa_ratio itself. Without it the gate would claim
support for a (gqa, v_hdim) pair that no Q-tile choice can serve, and
_pick_num_q_tiles would raise on max() of an empty sequence.

a16w16 and test_mha_flydsl.py auto-merged; v_hdim 256 verified working after
the merge (bf16, thd, 256/256, causal).

Co-Authored-By: Claude Opus 5 <[email protected]>
ruanjm added a commit that referenced this pull request Oct 26, 2026
Mirrors #6897, which added v_hdim 256 to the a16w16 sibling, so the 8-bit
kernel serves the same (qk_hdim, v_hdim) grid as the 16-bit one. The test's
SUPPORTED_D_QK_V already lists (256, 256) and (128, 256) for both.

As in a16w16, v_hdim 256 runs at BLOCK_M 128 only: the BLOCK_M 256 O tile does
not fit its LDS staging chunk. That limit is not hardcoded -- supported_num_q_tiles
now filters its choices through _o_fits, which builds the O manager for the
requested v_hdim and reads the answer off its own LDS clearance assert. a8w8
probes with O_DTYPE, since its O is bf16 whatever the input type is.

The gate and both host entries now pass v_hdim down, so an unservable
(gqa, v_hdim) pair is declined rather than reaching _pick_num_q_tiles and
raising on max() of an empty sequence.

Verified on gfx1250 that a8w8 and a16w16 agree on the tile choice for every
gqa ratio in 1..48 at v_hdim 128 and 256. Numerics at v_hdim 256:
(256,256) bf8 455/1048576 elements outside 1e-2 (max 0.0258), (128,256) mixed
fp8/bf8 477 (0.0268) on thd and bshd with LSE, gqa 4 880/2097152 (0.0325) --
the usual 8-bit quantization level. The d128 shapes are byte-identical to
their pre-merge numbers.

Also correct two docstrings that still described this kernel as bf16/fp16.

Co-Authored-By: Claude Opus 5 <[email protected]>
coderfeli pushed a commit that referenced this pull request Oct 27, 2026
* FMHA gfx1250: rename the fwd routers and attention stages, split Contents

flydsl_flash_attn_{varlen,batch}_func -> _fwd, matching the existing
flydsl_flash_attn_varlen_bwd sibling, and the four attention stages to
_attention_{prologue,epilogue,core_one_kv_tile,core_multi_kv_tiles} so
the shared prefix groups them. 55 references across 7 files, three of
them other test modules.

The managers' Contents block now describes each of the nine managers on
its own line instead of one paragraph covering them together.

Pure renaming and prose: un-renaming reproduces the previous AST exactly
in all six code files, and the managers file is AST-identical ignoring
docstrings.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: share the Q/K/V manager construction between the cores

Both attention cores built the same nine managers inline, 34 duplicated
lines differing only by a local alias. Extract _build_managers().

Only this part is shareable: _attention_prologue also issues the
pipeline-fill copies and lays out the N_KV_PP ring, while the one-tile
core deliberately keeps its tile in slot 0 with Q in slot 1, which is
what lets it run on a single barrier. Manager construction emits no IR,
so the multi-tile, one-KV-tile and GQA cores are all byte-identical.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA flydsl: dispatch the fwd routers on gfxip first

Both routers tried the gfx950 fp8 gate and then the gfx1250 gate, so
arch was buried inside each. Switch on get_gfx() first and run only the
gate for that arch; an fp8 request on gfx1250 no longer walks the fp8
checks to reach the same answer.

Move the gfx1250 gate into the kernel as flash_attn_m32x8_supported,
matching flydsl_flash_attn_fp8_supported: metadata only, no allocation
or launch. It takes a "varlen"/"batch" mode, accepted and ignored since
one gate serves both today. Import the three gfx1250 entry points under
_gfx1250 names. The gate's terms are unchanged from the two inline
expressions it replaces.

Both routers resolve out the same way: allocate from v_hdim when it is
None, validate it otherwise. Sizing from V is the point -- the old
torch.empty_like(q[..., :v_hdim]) clamped and wrote past a narrow
buffer at qk_hdim < v_hdim.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: rename the buffer managers off the b16-only name

fp8/bf8 staging will share these managers with bf16, so the module name
should not claim a width. Pure rename plus the three references in the
a16w16 kernel.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: add the a8w8 kernel as a copy of a16w16

Starting point for fp8/bf8 support. A sibling rather than making the
a16w16 kernel dtype-parameterised: the ring, the V transpose load and
the WMMA shape all change for 8-bit, and a sibling keeps the tuned
bf16 ISA provably untouched while those land.

Identical to a16w16 apart from names: a16w16 -> a8w8 throughout, which
covers both kn_* kernel names so the JIT cannot collide, plus the four
entry points. It therefore still traces bf16 today -- every later fp8
change shows up as a diff against a known-good baseline.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: teach the a8w8 kernel the 8-bit WMMA

WMMA_K_B8 = 64: 16x16x64 contracts twice as deep as the bf16 16x16x32
for the same 8 VGPRs per operand, HW-probed
(v_wmma_f32_16x16x64_fp8_fp8 v[8:15], v[0:7], v[0:7]).

_wmma now dispatches on operand dtype. 8-bit goes through a four-way
table over FP8(E4M3FN)/BF8(E5M2) for A and B, which the hardware mixes
freely; the intrinsics reject float vectors, so fragments are bitcast to
v8 i32 first. The 16-bit path is unchanged.

Only the dispatch is wired: the tiling still uses WMMA_K = 32, so this
kernel continues to trace bf16 until the fragment plan follows.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: make the shared buffer managers width-aware

The managers hard-coded bf16: 2 bytes per element, a 32-deep WMMA
contraction and 8 elements per b128 chunk. Derive all three from the
element dtype so the a8w8 kernel can drive the same code at 1 byte,
a 64-deep contraction and 16 elements per chunk.

The LDS side of the async band descriptor keeps a fixed 16-byte chunk
stride -- a b128 write is 16 bytes at any element width; only the
global-memory address and the hdim immediate scale.

a16w16 ISA is byte-identical on the multi-tile d128/d192 and
one-KV-tile cores.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: give the LDS->VGPR ring a per-fragment load width

_ring_drive assumed every WMMA fragment is two ds_loads. That holds
wherever one load covers half a 32-byte operand (b128), but 8-bit V
has no tr8_b128 -- ds_load_tr8_b64 covers a quarter, so a V fragment
is four loads while K stays at two. A single stream now mixes both.

The two phase loops collapse into one driven by a running issued
cursor: the wait is issued - end-of-this-fragment, which reproduces
the old num_prefetch-2 in steady state and the old drain ramp once
the cursor saturates. The managers own the width (K 2, V 2 or 4) so
the fragment counts, the head carry clamp and the V->K boundary in
_vk_emit all read it from one place.

a16w16 ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: teach the K/V LDS plans the 8-bit operand layout

A WMMA AB operand is two groups of 16 B per lane, group g holding K
elements [2*KPack*g + KPack*h, +KPack) for lane half h, with KPack =
16/elem_bytes -- 8 at bf16, 16 at fp8. CK's gfx125 traits give the
same split (16x16x32 KPackPerGroup 8, 16x16x64 KPackPerGroup 16), and
it reproduces the layout the shipped bf16 V plan already implies.

K reads a group with one b128 either way, so it stays at two loads and
only its group stride changes (16 -> 32 elements). V reads through the
transpose crossbar, which delivers 8 elements per load, so at 8-bit a
group costs two tr8_b64 and a fragment four, and the lane row base
becomes KPack*(lane//16) instead of a fixed 8.

Pads come from a bank sweep validated against the shipped 16-bit
config: K 16 B at both widths, V 16 elements. The V pad assumes
tr8_b64 is serviced 16 lanes/cycle like b128; at 32 lanes/cycle no row
pad is conflict-free and V would need a swizzle. Noted at the constant.

16-bit ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: drive the gemm ring from the manager's V load width

The fused PV+QK gemm built every fragment from exactly two ds_loads.
Fragments are now assembled by an N-way _concat -- nested shufflevector,
which the allocator coalesces into adjacent registers for free, the
same way the two-part concat already does -- and the V width comes from
v_mgr.loads_per_frag at each call site rather than a literal 2.

The head prefetch pins its burst in whole fragments for the same
reason, so at 8-bit it pins groups of four rather than splitting a V
fragment across the scheduler's reordering.

16-bit ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: make the Q B-fragments width-aware

Q already read the two groups the B operand wants: lane l takes chunks
{l//16, l//16 + 2} of a 64-byte row, which is 2*KPack*g + KPack*h for
g in {0,1}, and the V1 XOR swizzle works on 16 B chunks, so its byte
geometry is identical at either width. Only two things assumed 16-bit:
the fragment concat was fixed at 16 elements, and V2 stepped to the
second group by _WMMA_M elements rather than a flat 32 bytes.

16-bit ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: order V by P's kv layout, widen the PV B operand

PV sums over kv, so any kv permutation is legal as long as P and V
agree -- and P's is not free: it falls out of the QK accumulator, where
lane half h holds kv 8h+0..7 of each 16-row frag. V follows that rather
than its logical k, which means it keeps the 16-bit addressing at every
width: lane row base 8h, one 8-element transpose load per 16 kv rows,
four of them at 8-bit stepping {0,16,32,48}. K and Q are unaffected --
they read their logical k directly and agree with each other.

This also removes the pad caveat. With rows 0-15 contiguous in a fetch,
V's 16-element pad is conflict-free at both LDS service widths, so
tr8_b64's lanes/cycle no longer matters.

The PV B operand now takes num_kv_frags//num_contract_tiles softmax
tiles instead of a hardcoded pair -- four at 8-bit.

16-bit ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: give the a8w8 kernel its P and O types

elem_dtype drove Q, K, V, P and O alike, which only works while they
are all the same width. In the 8-bit kernel it now means the Q/K/V
input type only: P is pinned to bf8, whose wider exponent suits the
[0,1] softmax range better than fp8's extra mantissa bit, and the O
accumulator and store stay bf16.

At fp8 a KV split costs 9216 B for each of K and V, against 17408 and
18432 at bf16 -- the 16-element pads and 1-byte rows.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: build the a8w8 kernel end to end

First compiling 8-bit path. Five things stood between the plumbing and
a build, none of them cosmetic:

- num_contract_tiles read the module WMMA_K (32) while the managers use
  wmma_k (64 at 8-bit), so the ring asked for twice the V loads the
  plan held.
- 8-bit element vectors do not legalize as LDS load result types.
- .to() emits arith.truncf, which has no lowering pattern for an f8
  result, so f32->bf8 goes through cvt_scalef32_pk8_bf8_f32 -- which
  also converts all 8 elements in one instruction.
- An f8-typed vector feeding a shuffle leaves an unlegalizable cast
  behind, so 8-bit fragments stay i32 from ds_load to wmma and _wmma
  takes its operand element types as arguments.
- pick_n_block's wide-n_block cap is a 16-bit capacity proxy. At 8-bit
  n_block 64 is invalid outright: a contraction tile is 64 kv deep and
  each LDS split must hold whole tiles.

The kernel is 8-bit only, so the 16-bit branches it inherited from the
copy are gone; the width conditionals in the shared managers stay.

fp8 d128 ISA: 384 VGPR, 0 spills, 128 wmma_16x16x64_fp8_fp8 (QK) + 128
fp8_bf8 (PV), 276 ds_load_tr8_b64, 136 ds_load_b128, 65 pk8 converts,
and zero v_perm/v_mov -- the four-part fragment concat is as free as
the two-part one. Builds at fp8 and bf8 across d64/128/192/256.

Q cannot carry the softmax scale at 8-bit, so it is disabled and
results are NOT yet numerically correct; S must be scaled after the QK
gemm instead.

16-bit ISA byte-identical on multi-tile d128/d192, gqa 32/4 and the
one-KV-tile core.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: scale S in softmax for the a8w8 kernel

8-bit Q cannot carry softmax_scale*LOG2E -- there is no f8 multiply --
so softmax puts S into log2 units itself. Folded in before the mask so
masked lanes stay -inf and the max/sum trees see log2 units throughout;
the sink seed is unaffected, since it carries LOG2E only at either
width, exactly as when Q held the scale.

Costs 128 packed multiplies and pushes d128 to 449 VGPR (still 0
spill), 6159 instructions against 5461. The multiply does not contract
because the scaled S has two consumers, the max tree and the s - m
before exp2. Since c > 0, max(c*s) == c*max(s), so a later pass can
leave S unscaled through mask and max, scale only the row max into the
running one, and let exp2(fma(s, c, -m)) contract into v_pk_fma_f32.
Deferred: it touches the pass that produces P, where the open PV defect
would be indistinguishable from a restructure bug.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: fix V's 8-bit transpose fetch (tr8_b64 crossbar)

ds_load_tr8_b64 and ds_load_tr16_b128 do not share a crossbar, despite
SP3 §9.6.16/§9.6.17 wording them identically. tr16_b128 transposes over
eight consecutive lanes; tr8_b64 takes byte L%8 from the strided set
{b..b+3, b+8..b+11}, b = (L//16)*16 + ((L//8)%2)*4 -- HW-probed.

V assumed the consecutive form, so every lane straddled columns L%8 and
L%8+8 and the sum over kv blended them. The 8-bit fetch formula becomes
lane_kv = (l//16)*8 + ((l%16)//8)*4 + l%4 and lane_d = ((l//4)%2)*8,
which lands lane l on column l%16 with 8 consecutive rows -- the same
output shape tr16_b128 gives, so nothing downstream changes: the kv
permutation agreeing with P, the {0,16,32,48} row offsets, the 4-way
concat and the 16-element pad all stand (the pad is still 1-way at both
LDS service widths under the new addresses).

fp8 d128: full attention relative error 0.96 -> 0.048, which is the fp8
V and bf8 P quantization; with P uniform, where P is exact, absolute
error 0.0504 -> 0.000114; the d mapping is now the exact identity.

16-bit ISA byte-identical on multi-tile d128.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: fold the a8w8 softmax scale into the exp argument

The scale was applied to S in pass 1, which gave it two consumers --
the max tree and the s - m before exp2 -- so nothing could contract and
it cost a standalone packed multiply per element.

S now stays raw through mask and max tree, and only the row max is
scaled before it folds into the running one: one multiply per row
instead of 8*num_kv_frags. Valid because the scale is positive, so
max(c*S) == c*max(S). The exp argument becomes fma(S, c, -m), whose
single consumer lets it contract. The fma keeps fsub_inf's no-ninf
rule, and -inf*c + finite is still -inf.

fp8 d128: 450 -> 388 VGPR (0 spill either way, and below the 384 from
before the scale existed), 6169 -> 5767 instructions. v_pk_mul_f32
448 -> 322 and v_pk_add_f32 180 -> 50, the multiplies and their
subtracts both absorbed. Note the contraction is mostly SCALAR
v_fma_f32 (394) rather than packed (74): an fma needs all three
operands register-aligned where the two-operand forms did not, so the
scalar-op count is roughly flat and the gain is instruction count and
register pressure.

Numerics unchanged: full attention relative error 0.0480 and uniform-P
absolute error 0.000114, both identical to before the restructure.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: drop the a8w8 softmax's unscaled path

Both call sites pass s_scale and it is never None -- 8-bit Q cannot
carry the scale, so softmax always applies it. Make the argument
required and delete the branch, which also leaves fsub_inf dead: its
no-ninf rule now lives on fma_inf, the only consumer of it.

fp8 ISA byte-identical, so this is purely dead code.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: test and bench the 8-bit path

test_mha_flydsl.py takes Q and KV dtypes as 'q' or 'q,kv' (V follows
K), so -d bf8,bf8 and -d bf16 both work. The default adds the matched
8-bit pairs, bf8+bf8 and fp8+fp8; mixed pairs parse but the backend
decides. Each requested pair is put to the kernel's own support gate
up front and declined ones are logged and dropped, rather than failing
mid-sweep -- the gate's dtype clause is hdim-independent, so one served
hdim stands in for all and the axis stays exactly filterable.

8-bit has no randn or fill_, so inputs draw in fp32 and round, scaled
to stay inside range; the reference runs on the dequantized tensors,
which is what the kernel sees; and tolerances widen to rtol 1e-1 /
atol 2e-2, since bf8 P alone carries 2 mantissa bits.

bench_mha_fwd.py gets -d bf16|bf8 applied to whichever cases are
selected, so case ids are unchanged. Its dispatch spy was also stale:
it looked up pre-alias entry names and so could not have fired since
the router was restructured, and there are two kernel families now --
it watches both aliases and reports the dtype in the header.

Case 10 at bf8: 1.088ms / 2021 TFLOPS against 1.764ms / 1246 at bf16.

Verified: thd bf8 and fp8 (causal, and fp8 with LSE -- the first runs
of the -inf path through fma_inf), bshd bf8, and bf16 unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA bench: fp16/fp8 dtypes and bf8 twin cases

-d now covers bf16, fp16, bf8 and fp8, and defaults to None rather than
bf16 so it overrides what a case carries instead of silently replacing
it. The case table gains a bf8 twin of every entry, appended after the
table is built so existing ids never move -- case 10 is the standing
perf reference and stays where it is, with its bf8 twin at 90.

Case 10: 1.805ms / 1218 TFLOPS at bf16, 1.084ms / 2030 at bf8.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: rename the a16w16 support gate

flash_attn_m32x8_supported -> flash_attn_a16w16_m32x8_supported, so the
16-bit gate names its dtype family the way the 8-bit sibling
(flash_attn_a8w8_m32x8_supported) already does.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: allow mixed 8-bit Q and KV dtypes

Q and KV were forced to the same 8-bit type by a single elem_dtype/dtype_str
threaded through the kernel. Split it into q_dtype/kv_dtype (device) and
q_dtype_str/kv_dtype_str (host): QManager takes q_dtype, the K/V managers take
kv_dtype, and the QK wmma becomes a_dtype=kv_dtype, b_dtype=q_dtype.

The wmma side needed nothing new. _wmma already took per-operand element types
and the mixed wmma_f32_16x16x64_{fp8_bf8,bf8_fp8} variants were already in
_B8_WMMA, because PV has always run mixed: V is the input type while P is
always bf8. Both operands are one byte, so LDS layouts, swizzles, the ring and
n_block are unchanged.

The support gate now accepts any 8-bit Q against any 8-bit KV; K and V must
still agree with each other, since both ride kv_dtype. The a16w16 sibling keeps
requiring k.dtype == q.dtype -- 16-bit cannot mix.

Both launch-cache keys carry both dtype strings, so a mixed build cannot alias
a matched one.

Also drop a dead elem_dtype parameter from the epilogue and
_zero_fill_attention, and fix an assert message that had been copied from the
16-bit sibling and still said "Expected bf16 or fp16".

Verified on gfx1250, 512x512 d128 causal: matched fp8 is unchanged at
233/524288 elements outside 1e-2 (max abs delta 0.0260981619); fp8 Q with bf8
KV lands at 243 (0.0275), between matched fp8 and matched bf8 (255, 0.0280).
All four pairs run in one process produce four distinct results identical to
their isolated runs.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA test: -dq/-dkv, fixed tolerance, drop redundant upcast

Three cleanups to test_mha_flydsl.py:

Replace the _str2dtype_pair spec with separate -dq/--dtype-q and
-dkv/--dtype-kv lists. Each takes plain dtype names; the dtype axis is their
product, filtered by the backend gate, so a pair the kernel declines is
skipped with a log line instead of failing mid-run. -dkv defaults to -dq. The
defaults resolve to the same four matched pairs as before, and mixed 8-bit is
now expressible: -dq fp8 -dkv bf8.

Drop the dynamic _tols helper and compare everything at a flat
rtol=atol=1e-2. The 8-bit quantization error is real and is now visible rather
than absorbed by a widened bound: a few hundred of 524288 elements fall
outside it on an 8-bit case.

Stop pre-converting q/k/v to fp32 before calling the torch references. Both
run_torch_varlen and run_torch_batch already upcast internally, so they
accepted 8-bit inputs all along and the caller-side conversion was dead.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA flydsl: dispatch on the live GPU, not the build target

Both forward dispatchers selected the architecture with get_gfx(), which
follows the GPU_ARCHS build-target setting rather than the GPU actually
running. On gfx950 hardware built with GPU_ARCHS='gfx950;gfx1250', an FP8
request took the gfx1250 branch instead of the gfx950 backend.

Use get_gfx_runtime(), which chip_info documents as the helper for runtime
dispatch decisions, and rename the local to gfxip.

The CPU dispatch contract test mocked chip_info.get_gfx; it now patches
get_gfx_runtime. That mock is load-bearing -- patching the old helper fails 6
of its 16 cases.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: decline 8-bit requests carrying descales

Both gfx1250 8-bit routes accepted q_descale, k_descale and v_descale but
neither their support gates nor their kernel calls consumed them, so
v_descale=2 was treated as 1 and the call returned plausible but wrongly
scaled attention with no error.

Decline instead: return None before allocating the output when the request is
8-bit and any descale is non-None, so the caller falls through to a backend
that honours them. The a16w16 route is unaffected.

Verified on gfx1250: no descale is served, any one of the three is declined,
all three are declined, and bf16 with a descale is still served.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA bench/test: count 8-bit input and 16-bit output bytes apart

Both bandwidth helpers applied one element size to Q, K, V and O. The 8-bit
cases read 1-byte inputs but still write a bf16 O, so neither figure was
right.

_fwd_bytes() in the benchmark charged every tensor 2 bytes, inflating reported
TB/s by 60% when the four tensors have equal element counts and LSE is off
(8N bytes counted against 5N actual). _nbytes() in the test applied
q.element_size() to O as well, understating TB/s by 20% in the same shape
(4N counted against 5N).

Give both helpers a separate output element size and update their callers.
LSE accounting is unchanged at four bytes per element.

Measured on case 90 (bf8): TB/s 0.48 -> 0.38. The 16-bit cases are unaffected.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: support v_hdim 256 in the a8w8 kernel

Mirrors #6897, which added v_hdim 256 to the a16w16 sibling, so the 8-bit
kernel serves the same (qk_hdim, v_hdim) grid as the 16-bit one. The test's
SUPPORTED_D_QK_V already lists (256, 256) and (128, 256) for both.

As in a16w16, v_hdim 256 runs at BLOCK_M 128 only: the BLOCK_M 256 O tile does
not fit its LDS staging chunk. That limit is not hardcoded -- supported_num_q_tiles
now filters its choices through _o_fits, which builds the O manager for the
requested v_hdim and reads the answer off its own LDS clearance assert. a8w8
probes with O_DTYPE, since its O is bf16 whatever the input type is.

The gate and both host entries now pass v_hdim down, so an unservable
(gqa, v_hdim) pair is declined rather than reaching _pick_num_q_tiles and
raising on max() of an empty sequence.

Verified on gfx1250 that a8w8 and a16w16 agree on the tile choice for every
gqa ratio in 1..48 at v_hdim 128 and 256. Numerics at v_hdim 256:
(256,256) bf8 455/1048576 elements outside 1e-2 (max 0.0258), (128,256) mixed
fp8/bf8 477 (0.0268) on thd and bshd with LSE, gqa 4 880/2097152 (0.0325) --
the usual 8-bit quantization level. The d128 shapes are byte-identical to
their pre-merge numbers.

Also correct two docstrings that still described this kernel as bf16/fp16.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: type softmax P as fp8, not bf8

The PV gemm's B operand is UNNORMALIZED exp(S - m), whose row max is exactly
1.0 -- flash attention defers the 1/l to the O epilogue. In that regime e4m3's
extra mantissa bit is worth more than e5m2's exponent range: the sum is
dominated by terms near 1.0, and the terms that fall under e4m3's subnormal
floor are negligible against a denominator that is already >= 1.

The old rationale ("its [0,1] range wants the wider exponent") holds for a
NORMALIZED P, where values cluster near 1/seqlen and e5m2's range is
load-bearing. That is not what this gemm is fed.

Elements outside the test's flat 1e-2, thd causal, bf8 in, bf8 -> fp8:

  512^2   d128        255 (max 0.0280) -> 0, the case now passes outright
  4096^2  d128        203 (max 0.0225) -> 2 (max 0.0194)
  8192^2  d128        252 (max 0.0294) -> 1 (max 0.0116)
  512^2   d256/256    455 (max 0.0258) -> 3 (max 0.0145)

The margin widens with sequence length rather than eroding, which is the axis
where e4m3's floor would have bitten if anywhere. bshd with GQA 4, LSE and a
sink: 29 of 1048576, LSE unaffected.

Free: same operand width, so the change is a cvt and wmma opcode swap. Case 90
median 1282.6 us against 1267.1 us for bf8 over three runs each, inside this
box's ~2% noise.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: decline strided views and invalid softmax scales

Two ways a request could reach the m32x8 kernels and come back wrong.

Non-unit last stride. The Q/K/V TDM descriptors are built from the seq and
head strides only -- no hdim stride is passed, so the kernels assume the last
dimension is contiguous. A view whose last stride is not 1 but which still has
some unit-stride axis, e.g. a [B,S,D,H] tensor permuted to [B,S,H,D], is
accepted by FlyDSL's layout check and then addresses the wrong elements. A
view with NO unit-stride axis raises instead, which is why this went unnoticed.
Measured on a permuted bf16 [1,128,8,64]: 0.139 max delta against the same
data made contiguous.

Non-positive or non-finite softmax_scale. Logits are masked to -inf before the
scale is applied, so a zero scale turns a masked tail into NaN (0 * -inf) and a
negative one flips its sign. A one-token [1,1,1,64] fp8 input returns all-NaN
at scale 0.0 and at -1.0.

Both are now declined before the output is allocated, so the caller falls
through to a backend that handles them.

The guards cover the a16w16 path as well as a8w8. The reviewer scoped this to
the 8-bit routes, but the 16-bit kernel passes no hdim stride either, and
calling it directly with a permuted view reproduces the same 0.139 delta -- the
hole predates the 8-bit work and the two share the branch. Declining sends
those requests to CK, which serves them correctly.

Verified both dtypes: permuted views and scale in {0, -1, inf, nan} are
declined; contiguous inputs and scale 0.125 are still served.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA test: do not cross-check 8-bit against Triton

_call_varlen_triton passes no descales, but Triton's 8-bit kernel loads all
three scale pointers unconditionally, so `-k flydsl triton` on an fp8/bf8 case
died inside the Triton kernel even at d128/128; asymmetric hdims trip its own
head-dimension assertion first.

Skip the Triton candidate for 8-bit cases, alongside the existing sink and
sliding-window exclusions. 16-bit cases still cross-check against Triton.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA flydsl: name the gfx1250 aliases by dtype family first

Rename the gfx1250 aliases in fmha_kernels.py so the dtype family leads:
flash_attn_*_gfx1250_a8w8 -> flash_attn_*_a8w8_gfx1250, and the bare 16-bit
names gain a16w16 (flash_attn_batch_gfx1250 -> flash_attn_batch_a16w16_gfx1250).
The _GFX1250_A8W8_* constants are swapped to match.

The order matters: flash_attn_batch_gfx1250 is a prefix of
flash_attn_batch_gfx1250_a8w8, so the swaps run before the a16w16 insertions.

bench_mha_fwd.py's dispatch spy builds these names with f-strings rather than
importing them, so it needs updating in step; a grep for the literal names does
not find it. Its assert that the spy fired is what catches this.

Rename only. The reflowed ternaries are black's response to the longer names.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: decline BSHD views whose batch stride is implicit

The BSHD kernels take no batch stride: they address batch b at
b * seq_len * stride_seq. A view whose own batch stride differs from that
product -- [S,B,H,D] storage permuted to [B,S,H,D], say -- reads the wrong rows
or off the end. A contiguous [64,2,8,64] permuted to [2,64,8,64] has stride(0)
512 against the assumed 65536, one past a 65536-element buffer: the call was
served and returned NaN.

This is distinct from the unit-last-stride guard, which does not catch it --
the permuted view has stride(-1) == 1.

Decline q/k/v and a caller-provided out whose layout does not match, so the
request falls through to CK rather than raising; CK serves these correctly.
Batch 1 is exempt, since it never forms a nonzero batch offset and requiring
the identity there would decline valid single-batch views.

Covers a16w16 as well as a8w8: neither BSHD entry passes a batch stride, so the
hole predates the 8-bit work and the two share the dispatch branch.

Verified on both dtypes -- permuted inputs and a bad out buffer declined,
contiguous and batch-1 still served.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: cap the rescale threshold to P's dtype range

Deferred rescale keeps m stale while the row max stays within
RESCALE_THRESHOLD natural logits, so P = exp(S - m_stale) reaches
exp(RESCALE_THRESHOLD). At 8.0 that is exp(8) ~= 2981, which fit bf8's 57344
max but not e4m3's 448 once P was retyped to fp8. Overflow converts to NaN
while the denominator keeps summing the exact f32 values.

Two consecutive KV tiles with scaled maxima 0 and 7.07 -- inside the 8.0
threshold, so no rescale fires -- returned NaN where fp32 gives 0.9992.

Derive the cap from P_DTYPE rather than writing a constant:

  RESCALE_THRESHOLD = min(8.0, log(finfo(P_DTYPE).max) - 0.1)

which is 6.0048 for e4m3 (max P 405.4, inside 448) and leaves bf8 at 8.0. A
literal 6.0 would fix today's bug and silently wait to break the next time P is
retyped, which is precisely how this one arrived.

Verified at logit gaps 5.66 / 7.07 / 8.49 / 11.3, all now matching fp32 to fp8
quantization error. Accuracy unchanged: 512^2 still 2/3/1/0 elements outside
1e-2 across the four dtype pairs, 8192^2 still 1 of 8388608 at max 0.0116.
Perf unchanged: case 90 median 1292.7 us against 1282.6 us at threshold 8,
inside this box's noise.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: decline sinks with a non-unit stride

_load_sink_logit reads the per-head sink as ptr_sink + q_head_idx, and no sink
stride is passed to either kernel, so the load assumes the tensor is
contiguous. A strided sink -- [0, 10, 1, 20][::2], meaning [0, 1] -- would be
read as [0, 10], corrupting the softmax denominator and the LSE.

In practice a 1-D strided sink does not reach the load: FlyDSL's layout check
rejects a tensor with no unit-stride axis, so it raises from inside the JIT
rather than returning wrong numbers. That is still a poor failure for a request
another backend can serve, and it depends on an invariant of the layout checker
rather than on anything this code enforces.

Decline it in both dispatchers so the request falls through to CK. Covers
a16w16 as well as a8w8: it indexes the sink identically and passes no stride
either, and the two share the dispatch branch.

Verified on both dtypes and both layouts: strided sinks declined, contiguous
sinks and the no-sink path still served, and the sink correctness sweep
unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: share the m32x8 helpers between the two kernels

The 16-bit and 8-bit prefill kernels are deliberate siblings, so most of each
file is dtype-specific -- but 19 small helpers were byte-identical: lane/wave
indexing, LDS allocation and barriers, fragment packing, the LDS->VGPR ring,
the reduction tree and the scheduling hint. Move them to fmha_utils.py,
alongside the buffer managers that were already shared.

Sharing is gated on the whole dependency closure matching, not on matching
source text -- a function can read identically and still reach a definition
that differs. Five more that look identical stay put for now:
supported_num_q_tiles, supports_gqa_ratio and _pick_num_q_tiles reach _o_fits,
which probes the O manager with a different element type per kernel, and
_packed_tile_indices and _wg_kv_span reach _m_tile_idx. The module docstring
records that so the exclusion is not mistaken for an oversight.

NUM_WAVES and WMMA_M move too rather than being copied: only _block_m needs
them, and a per-kernel copy could drift from the shared helper that reads it.

Generated code is byte-identical before and after -- same hash over all cached
artifacts across four kernel builds -- so this changes neither behaviour nor
performance.

Co-Authored-By: Claude Opus 5 <[email protected]>

* FMHA gfx1250: share the O staging and tile-fit helpers too

The five helpers held back in the previous commit differed only in how they
spelled the same value, so unify the spelling and share them: _o_manager,
_o_fits, supported_num_q_tiles, supports_gqa_ratio and _pick_num_q_tiles, plus
_m_tile_idx, _packed_tile_indices and _wg_kv_span.

  - _o_fits probed the O manager as _DTYPE_MAP[DEFAULT_DTYPE] on one side and
    O_DTYPE on the other. Both are fx.BFloat16 -- the same object -- because O
    stages through LDS as a 2-byte element in both siblings and the staging
    size depends only on that width.
  - _o_manager differed only in whether elem_dtype had a default. It is now
    required, and a8w8's one call site passes it explicitly.
  - _m_tile_idx wrote `- 1` against `- fx.Int32(1)`.

DTYPE_MAP and TORCH_DTYPE_MAP are merged and moved, so a dtype name means the
same thing in both kernels. That needs care: the maps were also serving as the
VALIDATOR (`assert dtype_str in _DTYPE_MAP`, `q.dtype in
_TORCH_DTYPE_MAP.values()`), and a merged map would have let the 16-bit kernel
accept "fp8" and build a kernel reading its inputs at the wrong width, with
nothing downstream to catch it. Each kernel now validates against its own
SUPPORTED_DTYPES; verified a16w16 still rejects "fp8" and a8w8 still rejects
"bf16". The docstring says why, since gating on `in DTYPE_MAP` is the natural
thing to write next.

No identical-text duplication remains between the two kernels.

Generated code is byte-identical to before the whole refactor -- same hash over
all cached artifacts across four kernel builds -- which is also what settles the
two spelling unifications above.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
yuychang added a commit to yuychang/aiter that referenced this pull request Oct 27, 2026
- Resolve fmha_kernels.py onto main's split flydsl_flash_attn_varlen_fwd/_batch_fwd dispatch (ROCm#6702, ROCm#6897)
- Keep the PR's _fp8_gfx950_reject_reason gate and cu_seqlens checks on main's gfx950 FP8 varlen branch
- Move the bf16 descale decline into main's gfx1250 branches: both gfx1250 kernels now decline any q/k/v_descale
- Rename the remaining flydsl_flash_attn_varlen_func references in mha.py and the tests to flydsl_flash_attn_varlen_fwd
- Point the gfx1250 descale-decline test at get_gfx_runtime and stub the kernel entries; it also covers the batch path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants