Skip to content

[FlyDSL] [FMHA] Paged-KV forward prefill - #7553

Merged
coderfeli merged 46 commits into
mainfrom
jruan/gfx1250_fdsl_fmha_paged
Nov 11, 2026
Merged

coderfeli merged 46 commits into
mainfrom
jruan/gfx1250_fdsl_fmha_paged

Conversation

@ruanjm

@ruanjm ruanjm commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

FMHA gfx1250: paged-KV forward prefill

1. Introduction

This PR adds paged-KV support to the gfx1250 FlyDSL m32x8 FMHA forward-prefill kernels. Until now the kernels served only contiguous K/V -- thd (varlen, sliced by cu_seqlens) and bshd (uniform [B, S, H, D]) -- and both dispatch gates explicitly declined block_table, so every page-indexed request fell through to CK. AITER already exposes the equivalent operation through mha_batch_prefill_func, but that is CK-only and its ck_tile pipeline skips every non-gfx9 target, so on gfx1250 there was no paged prefill path at all. This PR closes that gap for prefix caching and chunked prefill.

The KV pool is read with the TDM gather descriptor rather than a second loader: K/V are gathered by token row instead of page row, so [num_blocks, page_size, H, D] is addressed as a token-indexed [num_blocks * page_size, H, D] view and one loader covers every page size. Paging is injected into the existing core through a kv_policy seam, so the paged and contiguous paths share one traced body rather than forking it; the contiguous policy compiles to the same code as before.

2. What this PR adds

New public entry points:

  • mha_paged_fwd_prefill (aiter/ops/mha.py) -- paged forward prefill, routing to the FlyDSL gfx1250 kernel when it can serve the configuration and falling back to mha_batch_prefill_func (CK) otherwise. A separate entry rather than a hook inside mha_batch_prefill_func, because that one has no backend fan-out and its signature carries CK-only options (kv_block_descale, logits_soft_cap, the vLLM 2-D block_table) the FlyDSL path does not implement.
  • flydsl_flash_attn_paged_fwd (aiter/ops/flydsl/fmha_kernels.py) -- the FlyDSL dispatcher. Returns None to fall through, never raises.
  • flash_attn_paged_m32x8 (a16w16) and flash_attn_paged_a8w8_m32x8 (a8w8) -- the per-kernel host entries.

Supported inputs on the paged path:

  • Page pool layouts [num_blocks, page_size, nheads_k, hdim] and [num_blocks, nheads_k, hdim] (page size 1), with any power-of-two page_size; page size is compile-time, so one build serves one page size.
  • qk_hdim in 64/128/192/256 and v_hdim in 64/128/256.
  • bf16 and fp16 (a16w16), plus fp8/bf8 including mixed q/kv 8-bit (a8w8), with optional per-tensor fp32 q/k/v descales on the 8-bit path.
  • Causal and non-causal, sliding window, attention sink, LSE output, and any GQA ratio the contiguous path already supports.
  • Ragged batches, including sequences whose last page is partially filled and batches with zero-length sequences.

Deliberate screens -- each of these falls through to CK rather than running with a silently wrong result: 5-D vectorized pools, the vLLM 2-D block_table, non-contiguous page pools, non-power-of-two page sizes, num_blocks * page_size >= 2**31, per-tensor descales on the 16-bit path, logits_soft_cap, and metadata tensors that are not 1-D unit-stride int32 on Q's device.

3. Performance

All numbers below were measured on a gfx1250 A0A0 engineering sample (AMD Eng Sample: 100-000001863-03). On A0 silicon the ASM FMHA paths are gated off, so the THD baseline is the FlyDSL contiguous kernel itself -- this is a paged-vs-contiguous comparison inside one kernel family, not a comparison against an ASM reference.

Common to both tables: bf16, qk_hdim = v_hdim = 128, causal, no LSE, no sink, full attention window, 5 warmup and 20 timed iterations per point. THD and all four page sizes for a given shape are measured back to back in one process, so clock drift between arms cannot masquerade as a page-size effect.

3.1 Cost of paging, against the THD kernel at the same shape

TFLOPS with random normal inputs. delta is the paged kernel against THD at that shape.

Hq/Hkv seqlen B THD page=1 delta page=16 delta page=64 delta page=1024 delta
1/1 16384 1 382 321 -16.0% 386 +0.9% 401 +4.9% 398 +4.0%
1/1 16384 2 574 533 -7.1% 554 -3.5% 576 +0.4% 579 +1.0%
1/1 16384 4 803 812 +1.1% 796 -0.9% 803 -0.1% 810 +0.8%
1/1 32768 1 654 566 -13.4% 620 -5.3% 653 -0.2% 662 +1.3%
1/1 32768 2 867 890 +2.6% 884 +2.0% 897 +3.4% 871 +0.5%
1/1 32768 4 1047 1052 +0.5% 1048 +0.1% 1052 +0.5% 1055 +0.8%
1/1 65536 1 957 944 -1.4% 942 -1.5% 953 -0.4% 951 -0.7%
1/1 65536 2 1299 1326 +2.0% 1278 -1.6% 1285 -1.1% 1289 -0.8%
1/1 65536 4 1329 1337 +0.6% 1310 -1.5% 1317 -0.9% 1321 -0.6%
1/1 131072 1 1346 1355 +0.7% 1330 -1.2% 1340 -0.5% 1339 -0.6%
1/1 131072 2 1356 1371 +1.0% 1339 -1.3% 1347 -0.7% 1351 -0.4%
1/1 131072 4 1361 1378 +1.3% 1344 -1.3% 1354 -0.5% 1358 -0.2%
4/1 16384 1 807 808 +0.2% 802 -0.6% 804 -0.3% 812 +0.6%
4/1 16384 2 1109 1143 +3.1% 1130 +1.9% 1136 +2.4% 1150 +3.7%
4/1 16384 4 1199 1195 -0.4% 1189 -0.8% 1202 +0.2% 1194 -0.5%
4/1 32768 1 1274 1267 -0.5% 1260 -1.1% 1272 -0.2% 1266 -0.7%
4/1 32768 2 1288 1313 +1.9% 1280 -0.6% 1278 -0.8% 1281 -0.6%
4/1 32768 4 1315 1322 +0.6% 1304 -0.8% 1310 -0.4% 1309 -0.5%
4/1 65536 1 1342 1343 +0.1% 1320 -1.6% 1333 -0.7% 1332 -0.7%
4/1 65536 2 1352 1360 +0.6% 1336 -1.1% 1341 -0.7% 1341 -0.8%
4/1 65536 4 1354 1367 +1.0% 1341 -1.0% 1351 -0.2% 1351 -0.2%
4/1 131072 1 1367 1378 +0.8% 1350 -1.2% 1361 -0.4% 1361 -0.4%
4/1 131072 2 1371 1383 +0.9% 1354 -1.2% 1365 -0.4% 1366 -0.4%
4/1 131072 4 1372 1383 +0.8% 1355 -1.2% 1366 -0.4% 1361 -0.8%
16/2 16384 1 1183 1187 +0.3% 1171 -1.0% 1175 -0.7% 1189 +0.4%
16/2 16384 2 1267 1236 -2.4% 1237 -2.3% 1250 -1.3% 1259 -0.6%
16/2 16384 4 1286 1276 -0.8% 1270 -1.3% 1275 -0.9% 1281 -0.4%
16/2 32768 1 1229 1314 +6.9% 1305 +6.1% 1320 +7.4% 1315 +6.9%
16/2 32768 2 1328 1336 +0.6% 1313 -1.1% 1322 -0.4% 1323 -0.4%
16/2 32768 4 1335 1343 +0.6% 1320 -1.1% 1330 -0.4% 1332 -0.2%
16/2 65536 1 1357 1366 +0.6% 1341 -1.2% 1351 -0.5% 1351 -0.5%
16/2 65536 2 1360 1370 +0.7% 1344 -1.2% 1356 -0.3% 1355 -0.4%
16/2 65536 4 1360 1372 +0.9% 1346 -1.1% 1358 -0.2% 1358 -0.2%
16/2 131072 1 1372 1385 +1.0% 1357 -1.0% 1367 -0.3% 1366 -0.4%
16/2 131072 2 1372 1384 +0.9% 1357 -1.0% 1367 -0.3% 1368 -0.3%
16/2 131072 4 1373 1385 +0.9% 1357 -1.1% 1367 -0.4% 1367 -0.4%

3.2 Peak throughput per page size

page size median vs THD worst best peak TFLOPS (random) at peak TFLOPS (fix-init 0.25) at
1 +0.7% -16.0% +6.9% 1385 16/2 sq=131072 B=1 2769 16/2 sq=131072 B=4
16 -1.1% -5.3% +6.1% 1357 16/2 sq=131072 B=2 2699 16/2 sq=131072 B=1
64 -0.4% -1.3% +7.4% 1367 16/2 sq=131072 B=2 2724 16/2 sq=131072 B=4
1024 -0.4% -0.8% +6.9% 1368 16/2 sq=131072 B=2 2725 16/2 sq=131072 B=4

3.3 Effect on the contiguous THD and BSHD kernels

Several commits here touch the shared non-paged path -- the per-fragment ring tap, spreading each wave's TDM issues through the body, dropping four scheduling fences, and moving the TDM copies to the tiled atom -- so the contiguous kernels were measured against origin/main as well.

This PR is about 2% faster on both layouts. Rows marked * changed sign between repetitions and are not claimed as a gain: both are small or grid-starved shapes where the run-to-run spread exceeds the difference being measured.

layout B Hq/Hkv seqlen main this PR delta per-rep
thd 4 8/8 16384 1119 1150 +2.7% +2.7 +2.9 +1.9
thd 4 8/8 65536 1326 1352 +2.0% +2.0 +2.1 +2.1
thd 1 4/1 131071 1346 1371 +1.8% +1.9 +1.8 +1.9
thd 1 16/4 4095 539 550 +2.1% * -0.1 +1.7 +3.2
thd 2 16/2 32768 1310 1336 +2.0% +2.1 +1.9 +2.0
bshd 1 8/8 32769 1174 1195 +1.8% +3.8 +1.6 +0.9
bshd 2 32/8 8192 1084 1096 +1.1% +1.9 +0.9 +1.1
bshd 1 8/8 16384 901 923 +2.4% +2.8 +2.2 +2.6
bshd 4 8/8 8192 161 164 +1.8% * -2.8 +2.4 +1.8
bshd 2 8/8 65536 1321 1348 +2.1% +2.4 +2.2 +1.9

ruanjm added 30 commits October 27, 2026 08:51
All four TDM sites in fmha_buffer_managers now build their descriptor with
cdna5.make_tiled_tdm_atom + tdm_partition instead of make_tdm_atom +
copy_atom_call: QManager16bV2's Q load, both of OManager16bV2's O stores
(2-D at gqa 1, 3-D otherwise), and _tdm_load_views' K/V band loads.

Padding and strides now come out of the layouts. pad_interval/pad_amount are
gone -- the tiled atom reads the padded row stride from smem_layout -- and so
are the explicit strides=[...] lists, since the global view carries the real
strides. The O store keeps its existing trick of declaring the pad as data and
letting the global extent drop it via OOB; verified numerically that the tiled
store writes columns 0..v_hdim-1 and nothing in the pad.

_tdm_load_views is pure and hands tuples to TdmCopyDescriptor.async_load, so
the partition moved into the builder; the tuples now carry already-partitioned
tensors and async_load issues fx.copy.

Its num_warps default (_DEFAULT_NUM_WAVES = 8) is removed. Every caller passes
1 -- the tile is split across waves by _warp_band, so a wave copies its own
band alone -- and the >1 path has never been exercised. Leaving an untested 8
as the default is worse here than requiring the argument, because
tdm_partition addresses past the tile when the warp coord does not match
num_warps.

4536 -> 4492 instructions, VGPR flat at 315, no spills, same TDM issue counts.
Numerics bit-identical. Perf is neutral: case 10 -0.8% and case 90 -0.9% on
medians over 5-6 runs per arm at random init, ranges overlapping -- inside this
box's noise. The ISA delta is purely scalar: on case 90's kernel SALU drops
1745 -> 1706 and s_delay_alu 160 -> 155, while VALU (3593), ds_ (428), s_wait
(277) and v_wmma (256) are unchanged.
_drain_barrier wrapped a single _copy_fence(*_kv_drain,
num_dscnt=_num_head_carry) call behind a zero-arg closure, used twice per
kernel. Both captured values are already in scope at the call sites, and
_copy_fence(*_kv_drain) is called inline at two other places in the same
file, so the closure was not buying encapsulation.

Call it directly at both sites in each kernel and drop the closure.

ISA is byte-identical for all three affected kernels (a16w16 at bf16 and
bf8, a8w8 at bf8), so this changes neither behaviour nor performance.
Body start reads V(start-1) from logical slot 0 and multiplies it by a zero
carried P, so the value is dead -- but it must be FINITE, because 0*NaN is NaN
and that poisons the O accumulator for the rest of the kernel. The prologue was
guaranteeing finiteness by issuing a second TDM copy of V(start) into the slot.

Zero the slot in LDS instead. Same guarantee, no global traffic: the dummy was
re-fetching a whole V slot (36 KB at bf16 d128/n_block 128, two TDM issues
because the V descriptor spans both LDS split halves). The zeroing sits in Q's
global-load shadow between load_q_to_vgpr_part1 and part2, where the KV
prologue copies already are, and touches only V[2] -- Q time-shares physical
slot 1 and the low 17 KB of slot 2's K chunks, not its V chunks.

The zeroing lives in fmha_utils._zero_slot(base, size, num_splits, split_stride,
tid), shared by both kernels. Whole rounds share one address and use ds_store's
immediate offset; the partial round wraps surplus lanes with tid % rem rather
than branching, since the callers are module level and a runtime if would need
its own @flyc.jit. Re-zeroing is idempotent, and wrapping keeps the LDS conflict
2-way instead of one address per wave. An earlier clamp-everything version cost
26 extra instructions and forfeited the immediate offsets.

WAVE_SIZE and BLOCK_SIZE move to fmha_utils alongside NUM_WAVES so the helper
and its callers cannot disagree about the thread count.

Confirmed the hazard is real before changing it: with slot 0 poisoned with bf16
NaN, removing the dummy outright gives all-NaN output, and keeping it passes.
Without the poison it still corrupts 2.2% of elements from whatever the
previous workgroup left in LDS -- intermittent and load-dependent. Fast-math
does not fold 0*NaN to 0.

case 10 kernel: 7040 -> 7048 instructions, TDM loads 8 -> 6, SGPR 70 -> 68,
VGPR flat at 480, no spills. Perf -0.87% median over 5 runs per arm at random
init, ranges overlapping -- neutral to marginally better.
Serve a page-indexed K/V cache, so prefix-caching and chunked-prefill callers
stop falling through to CK. a16w16 only; the a8w8 sibling follows later.

The pool is read as a token-indexed table: pages are contiguous, so token row
page_indices[p] * page_size + off addresses any page size with one loader, and
stride(-3) is the per-token stride. page_size is compile-time; 1, 16 and 1024
all work without a dispatch fork.

How it fits in:

- _ContiguousKVPolicy / _PagedKVPolicy: a tile index becomes a K/V descriptor
  in exactly three places, so they move behind one object the prologue builds.
  Paged keeps positions sequence-relative (row_base 0) and the page table
  supplies the pool row, leaving softmax masking and the slot rotation alone.
  The contiguous path emits byte-identical ISA.
- _TdmGatherTransport + KManager16bPaged / VManager16bPaged: a third transport
  mixed in front of the V1 managers, so the whole LDS read side is inherited.
  pad_interval = hdim, pad_amount = pad_elems reproduces the existing padded
  LDS layout exactly.
- fmha_utils.s_buffer_load: arbitrary-size uniform load, cut into the 1/4/8/16
  widths the scalar path accepts.

Dead rows gather an in-range, finite sentinel -- the sequence's first token.
Gather defines OOB only for non-decreasing indices (ISA 4.10.3.2) and a page
table is permuted, so an OOB sentinel is undefined here; pool row 0 is not
usable either, since its page may never have been written and a NaN reaches O
through P == 0 under fast math.

Interior tiles are fully valid, so one scalar test skips the per-row select
chain and only the tail tile pays: 175.3 -> 167.3 us at page_size=1 and
166.5 -> 162.7 us at page_size=16 (B=4 H=8/8 d=128 sq=sk=4096 causal).

Correctness is the paged result against the same kernel run on the dense KV the
page table spells out -- bitwise equality, across page_size 1/4/16/64/1024,
hdim 64/128, GQA 1-4x, causal and not, 3-D and 4-D pools, ragged tails, and
with every unreferenced page filled with NaN.

Declined at the gate (falls through to CK): hdim 192, which would split K into
two gather segments while a 128 V stays at one, so the halves would declare
different tensorcnt; the vLLM 2-D block_table; logits_soft_cap; descales.

Also here: drop the dead num_waves parameter from the K/V managers (written,
never read, and 8 misdescribes a path whose producer count is 4), and rename
the padded row fields to padded_row_elems / padded_row_bytes, leaving
OManager16bV1._row_bytes alone since it is XOR-swizzled rather than padded.

No functional change to the dense path: a16w16 and a8w8 ISA are byte-identical
to HEAD across thd/bshd, causal, sliding-window, return_lse, the one-KV-tile
core and hdim 192; bf16 32/32 rows at error 0, fp8 16/16 clean.
Sweeps the FlyDSL paged kernel over page_size 1/16/1024, batch, seqlen, GQA
ratio and causal, against an fp32 torch reference, and reports us / TFLOPS /
TB-s / err per shape. 72/72 rows at err 0.

The page table is a random permutation, so a kernel that assumes pages are laid
out sequentially fails rather than passes quietly, and the pool carries
unreferenced pages so a gather that strays outside the page list shows up.

No CK candidate: mha_batch_prefill does not compile on gfx1250. Its tile
distributions static_assert on wave64 ("slice size can't evenly divide input
sizes", sequence<32,32,32>), so there is no in-tree paged-prefill baseline to
compare against on this arch.
Paged becomes a third value on the existing --layout axis rather than its own
file, with a -p/--page-size sweep beside it. It reuses the file's own
run_torch_varlen reference, _flops and _nbytes, so the paged rows are computed
and scored exactly like the thd ones -- the page table is just gathered into
dense K/V first.

The table stays separate, as the other two layouts do: the arg signature
differs, so forcing one table would scatter NaN columns.

8-bit dtypes and hdim 192 are filtered out of the paged sweep, matching what
the gate declines.
30 paged cases (5 shapes x page_size 1/16/1024 x hdim 128/64), appended after
the bf8 twins so every existing id keeps its number -- case 10 stays the
standing perf reference.

The page table is permuted, as in the correctness test, so a kernel that
assumes pages are sequential shows up here too. The dispatch spy watches
flash_attn_paged_a16w16_gfx1250, so a fall-through is a hard error rather than
perf for some other backend; paged has no a8w8 sibling, so only the a16w16
entry is listed.

a16w16 and pow2 hdim only: the gather loader has no 8-bit sibling, and 192
would split K into two gather segments against a single-segment V, leaving the
halves disagreeing on tensorcnt.

Measured on the paged analogue of case 10 (B=4 H=8/8 d=128 sq=sk=4096 causal,
fixed init): page 1 158.5 us, page 16 150.3 us, page 1024 147.3 us.
15 cases (5 shapes x page_size 1/16/1024) appended after the existing paged
block, so ids 160-189 and case 10 all keep their numbers.

Shapes: 16k causal multi-batch (the paged analogue of case 10), 64k and odd
~2^17 MQA long context, short q into a long cache, and a decode-shaped q=1
into a long cache. The last two are the shapes prefix caching actually
produces, and neither existed in the dense list.

d128 only, and narrower heads on the longest rows, so the pool stays
affordable: at page_size 1 a 2^17 sequence is ~131k blocks.

Spot-checked at page 16 (fixed init): 16k B=4 1036 us / 2123 TFLOPS, 64k MQA
1569 us / 2803 TFLOPS, 2^17 MQA 6214 us / 2831 TFLOPS, short-q 897/65537
574 us, decode q=1 366 us. The most memory-hungry row (page 1 at 2^17, ~131k
blocks) runs at 6478 us.
The paged cases differ only by page_size across three id blocks, which --list
did not print, so the listing could not tell them apart.
The paged sweep listed lse as an axis but never checked it: it asked the
reference for return_lse=False and dropped out[1], so lse=True rows changed the
kernel variant and verified nothing extra. It now unpacks the reference LSE and
compares per request, asserting the same fp32 [nheads_q, total_q] convention
the thd path does.

sink and window were worse: the gate does not decline either on the paged path
and the entry forwards both, so they were reachable but untested. Both are now
swept, matching the thd axes.

96 rows across causal/lse/sink at page_size 1/16/1024 and 36 more with ragged
per-request seqlens (so kv_indptr has non-uniform strides and page_base varies
per request), all at err 0. Sliding window (256,256) checked separately, also 0.
Paged prefill had no reachable entry for the FlyDSL kernel: mha_batch_prefill_func
is the only paged entry in mha.py and it has no backend fan-out at all, going
straight to CK -- which does not compile on gfx1250 (its tile distributions
static_assert on wave64).

A new entry rather than a hook inside mha_batch_prefill_func, whose signature
carries CK-only options the FlyDSL path does not implement: kv_block_descale,
logits_soft_cap and the vLLM 2-D block_table. Hooking there would have meant
screening those out at a call site whose contract is CK's.

Takes FlyDSL when the gate accepts, and falls back to mha_batch_prefill_func
otherwise, so the entry is portable rather than gfx1250-only. The fallback
needs max_seqlen_q/k, which are optional on the FlyDSL path, so a caller that
omits them and then falls through gets a ValueError rather than a TypeError
from deeper in.

Verified: bitwise-equal to the same kernel on the dense KV the page table
spells out, across page_size 1/16/64/1024 with permuted tables and NaN-filled
unreferenced pages, with a spy confirming the FlyDSL entry actually fired
rather than a silent CK fallback; return_lse yields [nheads_q, total_q] fp32;
hdim 192 and fp8 both fall through to CK as intended.
test_mha_flydsl_{varlen,batch,paged} -> test_flydsl_mha_fwd_*, so the function
names follow the file after the earlier git mv. The @benchmark decorator logs
these, so the names appear in the run output too.
The paged gate declined qk_hdim 192 on the theory that K splitting into two
pow2 gather segments against a single-segment V would leave the halves
declaring different tensorcnt. That was wrong and untested: the prologue assert
compares drain DEPTHS, and _kv_drain_depths collapses any positive count to 0,
so K=8 and V=4 both yield (0, -1) and it passes. Each half's tensor_wait uses
its own count, which is what it should do.

192 also encodes cleanly: its two segments need pad_interval 64 and 32 dwords
(both powers of two) and pad_amount 36 and 68 dwords, inside the 7-bit field.
Every hdim in SUPPORTED_QK_HDIM encodes, so the paged-specific allow-list was
redundant and is removed rather than widened.

Verified bitwise-equal to the same kernel on the dense KV the page table spells
out, at page_size 1/16/1024 with permuted tables and NaN-filled unreferenced
pages, plus a sweep over hdim 192/128, 128/128 and 64/64 (36 rows, err 0) and a
ragged-seqlen GQA 4x run with sink and LSE.
…e enough

A page contributes page_size CONSECUTIVE pool rows, so once a page covers at
least gather_rows of the band, one plain 2-D TDM per page costs no more issues
than a gather and usually far fewer: num_rows/page_size against
num_rows/gather_rows. At n_block 128 that takes a band from 4 gather issues to
2 at page_size 16 and to 1 from page_size 32 up; the whole kernel goes from 21
tensor_load to 6 at page_size 1024.

It also drops the index expansion and the sentinel for those page sizes: the
plain path passes `valid` as the global extent, so out-of-range rows are
hardware zero-filled, which is finite by construction rather than by choosing a
written row.

Threshold is page_size >= gather_rows, not m_block/num_active_waves/4. The two
agree at n_block 128 (both 8), but at n_block 64 -- hdim 192 and 256 -- the
latter gives 4, and at page_size 4 a band is 16 rows, so plain would be 4
issues against the gather's 2. The gather should keep those.

Correctness: bitwise-equal to the same kernel on the dense KV the page table
spells out, at page_size 1/4/8/16/64/1024 with permuted tables and NaN-filled
unreferenced pages, plus 15 sweep rows over hdim 128/192/256 x page_size
1/4/8/16/1024 at err 0.

Perf is NEUTRAL so far: 161.7 -> 161.2 us at page 1024 and 163.3 -> 164.2 us at
page 16 (B=4 d128 sq=sk=4096), and within noise at sq 512 and 1024. The 100-140
cycle stall the trace shows on a gather's 4th issue is evidently covered by
other work in these shapes; this lands for the issue-count reduction and the
simpler OOB story, not for a measured win.
The descriptor BUILD consumes the page indices, and the build is hoisted above
the drain so its address math overlaps, so loading them in the same body put
s_wait_kmcnt directly on that dependency: the thread trace showed the
s_buffer_load and its wait adjacent, with the TDM loader consuming the result
immediately.

Load them a body earlier instead and carry them across the back edge, so a
body builds its descriptor from indices that have been in flight for a whole
iteration. The prologue keeps a direct load for its own start descriptor --
there is no earlier body to have carried that one.

Carried only while there are few: one SGPR each, so page_size >= 8 needs at
most 4 while page_size 1 would need 32 against ~106 architected. The threshold
lines up with the plain-TDM path, so every page size that builds a plain
descriptor carries, and the gather sizes keep the inline load.

case 201 (paged, 64k causal MQA, page_size 1024): 1539.6-1559.1 -> 1513.5-1518.6 us,
about -2%. case 195 (page 16) 1015.1 -> 996.6 us. case 190 (page 1, carry off)
1067.0 -> 1070.7 us, unchanged as expected. SGPR 70, no spills.

Correctness: 32 sweep rows over page_size 1/8/16/1024 x hdim 128/192 at err 0,
and bitwise-equal to the dense path under NaN poisoning on both sides of the
carry threshold. Dense ISA unchanged.
_build_paged assumed every sequence owns at least one page, so a curated
sk=0 shape reached torch.cat with an empty list and the whole paged sweep
died before running a single case. Give those sequences an empty slice and
a zero last_page_len, which is what the kernel's num_pages > 0 guard
already assumes.
…body

Two reorders of the leading half, both reaching past what sched_barrier
can express.

The page index load is split out of prepare() into advance(), issued after
the gemm, and anchored at the end of softmax main so its s_wait_kmcnt lands
~450 instructions later instead of ~120. sched_barrier alone is not enough:
the load's only consumer is the loop-carried PHI, so MachineSink moves it to
the latch before the scheduler runs and the ISA comes out byte-identical.
The wait binds to the first use, so _keepalive_sgpr -- the uniform twin of
_keepalive, emitting no instruction -- is what decides where it goes.
Anchoring after _softmax_phase() returns puts the use past the rescale
branch and collapses the distance back to zero, so it has to sit inside.

LO's P then crosses the back edge as f32 and narrows at the top of the next
body, which puts the loop's exit test between the producing softmax and the
v_cvt_pk_bf16_f32 run. That half costs 480 -> 501 VGPR with no spills and
is worth -1.75% on thd long context by itself, where no index staging runs
at all.

Long context, median of 3: thd 131071 -1.72%, thd 64k -1.76%,
paged 64k -1.65% at page 1024 and -1.10% at page 16.
…ot be carried

page_size 1 needs one index per row, so a band wants 32 of them -- far past
what _MAX_CARRIED_PAGE_INDICES allows against a 106-SGPR cap that the config
already sits on with 4 spills. Those indices therefore load in-body and the
descriptor build consumes them immediately: LO issued the load just ahead of
the P narrowing and HI right after s_barrier_wait, each leaving 10-15
instructions before s_wait_kmcnt.

Nothing placed earlier helps while the consumer stays put, since the wait
binds to the first use. So move the consumer instead: on this path only,
prefetch_desc.async_load() goes at the end of the half's gemm/softmax
stretch, and the ring head plus ring body become the cover.

Gated on kv_policy.inline_indices, false for every carried and contiguous
config -- case 201's ISA is byte-identical across this commit.

Case 191 (paged 64k, page 1), median of 3: 3234.9 -> 3115.9 us, -3.68%,
and -6.20% against the pre-staging baseline. VGPR 500 and SGPR spills 4,
both unchanged.
…ces cannot be carried"

This reverts commit 6f050a4.

The commit is kept on jruan/gfx1250_fmha_paged_late_issue_test rather than
deleted: it is 3.76% faster on untraced wall clock at case 191 (3130.4 vs
3248.7 us, 10/10 paired, holding at both random and fixed init), so it is not
a dead end. But its stated mechanism was wrong -- it gave the index load no
cover at all (load -> kmcnt went 15 instructions to 14) and merely cut the TDM
window from 1354 instructions to 620, which is the s_wait_tensorcnt cost the
thread trace shows.

Measured per cycle it is the worse kernel: 3.642 cycles per instruction against
carrying's 3.443. Two explanations were tested and refuted -- a frequency
effect (it clocks 2.5% LOWER at equal power, ~2140 W, this kernel being
power-capped near 1 GHz against a 2400 MHz peak) and thread-trace overhead
(ATT costs 0.6% over counters alone). Why it wins on wall clock while losing
per cycle is unresolved.

Carrying the indices at every page size, which this makes room for, lands next.
_MAX_CARRIED_PAGE_INDICES was 4 on the reasoning that each carried index costs
an SGPR, which ruled out page_size 1 (32 per band) against a 106-SGPR cap the
config already sits on. The reasoning does not hold: a band's indices die as
soon as its descriptor is built, so carrying them widens an existing live range
across the back edge rather than adding a new one. Measured at 32, the cost is
8 extra spills, all v_writelane into VGPR lanes with no scratch traffic.

What it buys, at page_size 1: the lagging half's index load moves from just
after s_barrier_wait to a full body ahead -- load at 1291, the pvqk gemm at
1503..1977, s_wait_kmcnt at 2021 -- so the whole gemm covers it, and the TDM
issue does not move. The leading half keeps its existing anchor.

Thread trace, case 191, two slots x four sequential waves: 3.443 cycles per
instruction against 4's 3.642, -5.47%, improved on all eight waves and
concentrated (-10%) in each slot's first wave. 4.55% fewer cycles on ~1% more
instructions.

Correctness: 48/48 at err 0 across page 1/16/1024 x hdim 128/256 x causal x lse.

Note this does NOT win on untraced wall clock -- see the test branch
jruan/gfx1250_fmha_paged_late_issue_test, which is 3.76% faster there while
measuring worse per cycle. That contradiction is unresolved; this branch
optimises what the trace measures.
With the limit at 32 and a band holding at most num_rows = n_block / 4 <= 32
indices, _carry was true for every config the gate admits, so the flag and the
four branches on it were dead weight. Remove the constant, fold the reason
carrying is affordable into the num_state_slots comment, and drop the tile_idx
argument that indices() stopped using once it always reads the carried set.

Emitted ISA is byte-identical for case 191 (page 1, 32 indices per band) and
case 201 (page 1024, 1), so this is a pure refactor.
Each sched_barrier(0) in the compute core was removed on its own and judged
against the emitted ISA first, then against an interleaved A/B -- both arms in
one run, since the box drifts ~10% between sessions and only within-session
comparisons mean anything here. Sampled cases: thd 16384, thd 65536,
paged 65536 at page 1/16/1024.

Removed:

  - ahead of the lagging half's ring head. The index SMEM loads and the head
    were in separate scheduling regions, so the loads sat stranded in front of
    the ds_read burst; without the fence the scheduler walks them into it.
    -0.13%..-0.43% across five cases, same sign on all of them.
  - ahead of the leading half's ring head. The mirror of the above, and the
    comment there already said the two were meant to match. Perf neutral
    (+/-0.16%, mixed signs); it goes for symmetry, not speed.
  - before the leading half's gemm, and after the lagging half's ring head.
    Both byte-identical: 0 diff lines, registers unchanged, and the whole
    s_wait_dscnt histogram preserved including the ring's 220 x 0x12. The
    scheduler keeps the head out of the WMMA stream without being told, so the
    comment crediting a barrier with preventing the wmma<-ds_load bubble went
    with them.

Measured and KEPT, so they are not stale:

  - between advance() and softmax in the leading half. Holds the index load
    early; removing it shortens load -> s_wait_kmcnt from 371 to 306 and from
    936 to 834 instructions, and costs +0.84% at page_size 1 -- the only
    config that loads 32 indices per band.
  - between the P keepalive and the drain. +0.04..+0.20%, every sampled case
    worse.
  - the pair inside _phase_barrier. The largest reordering of the set at 1474
    lines, and a loss: +0.80% paged page 1024, +0.61% thd d256, five of six
    cases worse.

Correctness, run on the two removals that changed the ISA: paged 24/24 and
thd+bshd 16/16 at err 0, no hang.
Adds a tap(i) hook to _ring_drive, called after each fragment's refill and
before its wmma, plus async_load_one(index) on the buffer descriptors so a
batch can be issued one copy at a time. Mechanism only: no caller passes a
tap, so the hook never fires.

Emitted ISA is byte-identical to HEAD on three configs that cover every path
through the ring -- paged gather (case 191), paged plain-TDM (201) and thd
(10), 0 diff lines each -- so there is no performance question to answer for
this commit.

This exists because a sched_group_barrier pipeline cannot do the job. TDM is
group-addressable (isLDSDMA is true for anything setting TENSOR_CNT, so mask
0x800 matches tensor_load_to_lds, and DS_READ does not, keeping it separable
from ds_load_tr16) -- but _ring_drive brackets every fragment in
sched_barrier(0), so the gemm is dozens of tiny scheduling regions and a
pipeline can never move a TDM issue past a wmma. Converting those fences to
group barriers is not an option either: _waitn's hand-computed s_wait_dscnt is
only correct if exactly the expected loads are outstanding at that
instruction, and sched_group_barrier is advisory where sched_barrier is not.
Issuing from inside the ring sidesteps all of it.
A wave on the gather path issues one TDM per 8 rows of its band -- four at
page_size 1 -- and they all went out as one clump ahead of the work. Both
halves now thread them through what follows, by different mechanisms, because
only one of the two can be asked nicely.

Leading half: the copies are issued from inside the ring via _ring_drive's tap,
at fragments 0, 1, 2 and 6, giving TDM, 2 ds_load, 2 wmma per tapped fragment.
This cannot be a sched_group_barrier pipeline. _ring_drive brackets every
fragment in sched_barrier(0) and _pv_qk_gemm brackets itself in s_setprio, both
of which SIInstrInfo::isSchedulingBoundary treats as region boundaries, so the
gemm is dozens of tiny regions and no pipeline can move a TDM past a wmma.
Converting those fences is not an option either: _waitn's hand-computed
s_wait_dscnt is only correct if exactly the expected loads are outstanding at
that instruction, and sched_group_barrier is advisory where sched_barrier is
not. Source placement needs nothing from the scheduler.

Lagging half: a sched_group_barrier pipeline, TDM / 8 VALU / TDM / 8 VALU /
TDM / 40 VALU / TDM through softmax's max tree. Advisory is fine here -- no
hand-computed wait depth rides on the order -- and softmax is one unbroken
region, so the groups bind. Emitted ISA matches the request exactly.

Both are gated at 2 copies, each for a measured reason:
  - the tap, because moving a lone TDM past the gemm's s_setprio costs
    +0.3..+0.6% on the configs that have only one;
  - the pipeline, because a single group is NOT inert -- any
    SCHED_GROUP_BARRIER hands its region to IGroupLP, which then schedules it
    bottom-up, moving 4400 lines of ISA and costing ~0.5%.
Below the gate both paths emit exactly what they did before: ISA is
byte-identical for paged page_size 1024 and for thd.

Interleaved A/B, median of 3, one session: paged 64k -1.71% at page_size 1
(4 issues) and -0.55% at 16 (2 issues). The four single-issue cases in the same
run compile byte-identical, so their spread -- -0.05%..+0.20% -- is the noise
floor, putting both gains well clear of it.

Side effect worth knowing: the lagging half's s_wait_xcnt is gone. It guarded a
real WAR hazard -- the second s_buffer_load_b512's destination block holding the
first's live soffset -- and reallocation under the interleave dissolved the
overlap. That stall was 38 cyc x 1024 hits, 0.74% of the trace, and four direct
attempts to remove it had failed. SGPR spills 12 -> 8, VGPR 500 -> 508, no VGPR
spills.

Correctness: paged 48/48 across page_size 1/16/1024 x hdim 128/256 x causal x
lse, thd+bshd 16/16, all at err 0.
PagedSpec, _ContiguousKVPolicy and _PagedKVPolicy describe where a tile's rows
come from, not what they contain, so they are dtype-agnostic and the a8w8 core
will want the same ones. They depended on nothing beyond fx and s_buffer_load,
which already lives here.

Pure move: emitted ISA is byte-identical on paged gather (case 191), paged
plain-TDM (201) and thd (10), so no measurement applies. fmha_utils goes
594 -> 737 lines, which is still well short of wanting its own module.
The a8w8 core still read tile positions through the prologue's raw tile_row0 /
kv_valid closures and added kv_start by hand, which is the shape a16w16 had
before paging. Route it through _ContiguousKVPolicy instead: the prologue
publishes one policy object, the core reads positions off it, and
_get_kv_desc gains the page_indices argument plus the policy's desc_kwargs.

Contiguous only -- no paging yet. Emitted ISA is byte-identical on a8w8 d128
(case 90) and d192 (case 110), which is the property that matters: the seam
costs nothing where it is not used.

This is the prerequisite for a8w8 paging. The gather loader layer underneath
is already shared and already element-width aware -- verified separately at
elem_bytes=1 across hdim 64/128/256 x 16/32 rows x identity/permuted indices,
all byte-exact against the padded LDS layout the 8-bit readers expect.
Adds the layout="paged" device entry to the a8w8 builder, mirroring a16w16:
kv_len derived from the page count and the last page's fill, positions kept
sequence-relative with the page table supplying the pool row, PagedSpec handed
to the prologue, and the paged K/V managers selected there. page_size joins the
compile key and forces the multi-tile core.

The gather loader underneath needed no changes -- it is shared and already
element-width aware, verified at elem_bytes=1 across hdim 64/128/256 x 16/32
rows x identity/permuted indices, all byte-exact.

thd and bshd pass paged=None and come out byte-identical on a8w8 d128 (case 90)
and d192 (case 110), so the plumbing costs nothing where it is unused.

Host plumbing, tests and correctness are not here yet: nothing can reach this
entry until _ensure_paged_kernel and the dispatch gate land, so it is dead code
for the moment.
Completes the a8w8 paged path: the carried page indices join the core's loop
state, the prologue's start descriptors go through the policy, and the host
side gains _ensure_paged_kernel and flash_attn_paged_a8w8_m32x8.
_paged_layout_ok moves to fmha_utils since it only inspects shapes, strides and
metadata dtypes -- nothing about the K/V element type -- so both kernels share
it.

Verified against the strongest reference available: the paged kernel versus the
SAME kernel on the dense KV its page table spells out, which shares arithmetic
order and tile schedule, so a paging bug cannot hide behind a tolerance. Five
shapes, all BITWISE identical, with every unreferenced pool page NaN-poisoned
and every output finite -- page_size 1 (the 4-issue gather path), 16, 64 and
256, GQA 1x/2x/4x, causal and non-causal, and sk not divisible by page_size.

thd and bshd are byte-identical on a8w8 d128 (case 90) and d192 (case 110).

Two port bugs worth noting, both silent: the a16w16 entry allocates O as
q.dtype, which for 8-bit must be TORCH_O_DTYPE instead (bf16) or the output
comes back fp8 and NaN; and the paged core_kwargs briefly carried both
"paged": None and "paged": PagedSpec(...), where Python takes the later key and
the source says two contradictory things.

Not yet here: bench cases, the op test, and the mha.py route.
flydsl_flash_attn_paged_fwd dropped its "a8w8 paged is a later phase" bail and
now picks the family the way the varlen router does: 8-bit to the a8w8 sibling
with bf16 output, everything else to a16w16 with output following the input.
The a8w8 supported() gate learns "paged" mode and the kv_* arguments, and stops
rejecting block_table outright so the paged screens can run.

bench_mha_fwd gains 45 a8w8 paged cases at ids 205..249, appended after the
existing blocks so no id moves -- the bf8 duplication above runs before the
paged blocks exist, so those were bf16 only. The paged candidate list now
watches both families, which is what makes the bench assert the a8w8 entry
actually fired rather than silently falling through.

Case 205 (a8w8 paged, page_size 1, 4k causal) runs at 87.6 us / 392 TFLOPS,
and the five-shape bitwise check against the dense equivalent still passes
through the router path. a16w16 paged (case 201) is unaffected.
@ruanjm
ruanjm force-pushed the jruan/gfx1250_fdsl_fmha_paged branch from 7ae9f6a to 20a0469 Compare November 10, 2026 03:24
@github-actions github-actions Bot changed the title [Triton/Gluon] [ASM] [HIP] [FMHA] Paged-KV forward prefill [FlyDSL] [FMHA] Paged-KV forward prefill Nov 10, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Automatic kernel selection can pass incompatible sorted metadata to NO_SORT kernels, while skipped review jobs can corrupt the duration median used for queue admission.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 10, 2026 03:30

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

Paged metadata inference and sink-shape validation can cause runtime failures, while numerical tests do not enforce correctness and public-entry routing and fallback remain untested.

2 open issues

Review effort: Balanced

Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Comment thread aiter/ops/mha.py Resolved

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

Reviewed exact commit 20a0469. Confirmed a host-side failure when inferring KV sequence lengths from oversized preallocated metadata. GPU kernel correctness remains unvalidated: the changed kernels require gfx1250, and the gfx950 import attempt was blocked by an older FlyDSL installation.

[P2] Restrict sequence-length inference to the active batch — aiter/ops/flydsl/fmha_kernels.py:934

The metadata gate explicitly accepts oversized preallocated buffers, but this calculation uses their full lengths. For two active requests, qo_indptr=[0,2,4], kv_indptr=[0,1,2,2], and kv_last_page_lens=[2,2] pass the gate. Omitting max_seqlen_k then adds three page counts to two last-page lengths and raises RuntimeError before launch, instead of serving the request. This was reproduced with the exact dispatch function and an intercepted launcher; exact-sized metadata and explicit maxima pass. Slice kv_indptr to _batch+1 and kv_last_page_lens to _batch before computing the maximum.

Validation:

  • PASS on local: git -C source rev-parse HEAD
    Verified 20a0469 in the isolated checkout.
  • PASS on local: python3 -m compileall -q source/aiter/ops/flydsl/fmha_kernels.py source/aiter/ops/flydsl/kernels/fmha_gfx1250 source/aiter/ops/mha.py source/op_tests/test_flydsl_mha_fwd.py
    Exit 0; syntax.log retained.
  • SKIP on gfx950 / fsx950223_pr_review_gfx950: srun --overlap --jobid=9561 --ntasks=1 --cpus-per-task=1 podman exec -i fsx950223_pr_review_gfx950; flock -w 30 /workspace/gpu.lock timeout 90 env ROCR_VISIBLE_DEVICES=0 PYTHONPATH=/workspace/codex-pr-review-7553-20261111/head FLYDSL_CACHE_DIR=/workspace/codex-pr-review-7553-20261111/cache TORCH_EXTENSIONS_DIR=/workspace/codex-pr-review-7553-20261111/cache/torch python3 /workspace/codex-pr-review-7553-20261111/targeted.py
    Architecture verified as gfx950 inside the container; remote HEAD verified. Exit 1 during checkout import: FlyDSL >=0.5.0 required, installed version 0.4.0. No GPU kernel test executed. See targeted-gfx950.log.
  • PASS on gfx950 container, CPU only: srun --overlap --jobid=9561 --ntasks=1 --cpus-per-task=1 podman exec -i fsx950223_pr_review_gfx950 timeout 30 python3 /workspace/codex-pr-review-7553-20261111/inference_repro.py
    Exit 0. Host-only AST reproduction of the exact dispatcher, with support predicate and launcher stubbed, reproduced the tensor-size mismatch (3 versus 2). Exact-sized metadata and explicit maxima passed. See inference-repro.log.
  • PASS on gfx942 / sixifang_dev: docker exec sixifang_dev python3 -c "import torch; print(torch.__version__); print([(i,torch.cuda.get_device_properties(i).gcnArchName) for i in range(torch.cuda.device_count())])"
    Exit 0; all visible devices reported gfx942. This environment cannot validate the gfx1250 kernels. See gfx942-probe.log.

Remaining validation:

  • Neither configured host provides gfx1250; paged gather correctness, numerical accuracy, synchronization, and shared contiguous-path performance require validation on that target.
  • The host-only reproduction validates the reported inference failure, not GPU execution.
  • Available CI metadata includes successful MI35X standard tests, but no gfx1250 execution evidence was obtained.
  • Detailed commands and logs are preserved in this task directory, including validation-notes.txt.

Automated Codex review of commit 20a046966f0c.

The paged dispatch gate accepts oversized preallocated kv_indptr and
kv_last_page_lens on purpose, but the max_seqlen_k fallback consumed their
full lengths. With two active requests and buffers sized for three, the page
counts and the last-page lengths disagree in shape and the broadcast raises
before launch, so a servable request fails whenever max_seqlen_k is omitted.

Slice kv_indptr to _batch + 1 and kv_last_page_lens to _batch. max_seqlen_q
needs no slice: _batch is derived from qo_indptr, so its difference is exact.
Downstream is unaffected either way, since flash_attn_paged_m32x8 takes the
batch from qo_indptr and passes both buffers as raw pointers.
@ruanjm
ruanjm requested review from fsx950223 and a balanced review from Copilot November 11, 2026 02:26
@ruanjm

ruanjm commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Reviewed exact commit 20a0469. Confirmed a host-side failure when inferring KV sequence lengths from oversized preallocated metadata. GPU kernel correctness remains unvalidated: the changed kernels require gfx1250, and the gfx950 import attempt was blocked by an older FlyDSL installation.

[P2] Restrict sequence-length inference to the active batch — aiter/ops/flydsl/fmha_kernels.py:934

The metadata gate explicitly accepts oversized preallocated buffers, but this calculation uses their full lengths. For two active requests, qo_indptr=[0,2,4], kv_indptr=[0,1,2,2], and kv_last_page_lens=[2,2] pass the gate. Omitting max_seqlen_k then adds three page counts to two last-page lengths and raises RuntimeError before launch, instead of serving the request. This was reproduced with the exact dispatch function and an intercepted launcher; exact-sized metadata and explicit maxima pass. Slice kv_indptr to _batch+1 and kv_last_page_lens to _batch before computing the maximum.

fixed

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

Both kernel dispatch gates accept unsupported sink shapes such as (8, 1), causing host-entry assertion failures instead of fallback; the (num_q,) shape checks must be restored alongside the device checks.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@coderfeli coderfeli left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@zufayu zufayu assigned fsx950223 and unassigned coderfeli Nov 11, 2026
@zufayu
zufayu requested a review from coderfeli November 11, 2026 06:56
@coderfeli
coderfeli merged commit 3b15efe into main Nov 11, 2026
@coderfeli
coderfeli deleted the jruan/gfx1250_fdsl_fmha_paged branch November 11, 2026 07:00
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.

5 participants