Skip to content

[Triton/Gluon] [FlyDSL] [CI] fp8 unified attention for gfx950 - #4676

Merged
azaidy merged 158 commits into
mainfrom
jograner/flydsl-unified-attention-SILOTIGER-877
Nov 30, 2026
Merged

azaidy merged 158 commits into
mainfrom
jograner/flydsl-unified-attention-SILOTIGER-877

Conversation

@johannes-graner

@johannes-graner johannes-graner commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Qwen3-VL MLPerf inference on MI355X (gfx950) runs fp8 unified attention on a paged KV cache. The Triton/Gluon kernel upcasts the fp8 KV cache before the QK GEMM, so it does not use the fp8 MFMA path, and main has no non-causal path at all. This PR adds a FlyDSL backend behind one public entry, aiter.ops.unified_attention.unified_attention(), with a host-only router that picks the kernel per call. The Triton entry under aiter.ops.triton is unmodified.

Technical Details

  • Scope: one public unified_attention entry plus a router in aiter/ops/flydsl/unified_attention_kernels.py. FlyDSL fmha_gfx950 serves causal batches with no 1-token rows and all non-causal batches. With backend=None, causal decode-only calls and causal batches that may contain a 1-token row go to main's Triton/Gluon kernel. backend="flydsl" forces FlyDSL, including causal decode (raises when it declines); "triton" and "gluon" bypass it.
  • Why the split: the router sees only host-side shapes. The batch bound q.shape[0] > (B-1)*max_seqlen_q + 1 detects that no 1-token row can exist; it is a performance proxy (BN64 pads 1-token rows to full tiles), not a correctness limit. FlyDSL pa_decode loses cold uniform decode to main (geomean 1.39x under the 512 MB-flush method), and no host-side quantity separates the skew batches where it wins. Later unification changes only the two router conditions.
  • Prefill: main's fmha_gfx950 builder gains paged KV (linear and shuffled layouts), f16 output, and a packed BN64 body for D128 with GQA group 4, 8 or 16. It adds a compact grid, scalar page ids via s_buffer_load, max-free fast loop, nsm carry, staged non-temporal O epilogue (with an explicit LDS drain before the K/V ring is reused). Static index maps (Q/O row bases, staged O read/store, scan lane/chunk) use layouts.
  • Decode routing: backend=None causal decode goes to Triton/Gluon. Forced backend="flydsl" decode and all non-causal decode run on the fmha kernel as 1-token rows. AITER_UNIFIED_ATTN_PA_DECODE=1 routes auto causal decode to FlyDSL. The variable is parsed once, in _pa_decode_env().
  • Dormant pa_decode route: FlyDSL pa_decode (fp8 Q) would serve shuffled-cache decode only when pa_decode.SUPPORTS_FP8_QUERY is set. FP8-query support for pa_decode is a separate PR, so the flag is False here and the route, its workspace cache and their checks ship disabled; the checks skip with a logged reason. Decode that pa_decode declines falls through to the fmha kernel.
  • Limits: gfx950 only; float8_e4m3fn Q/KV with bf16 or f16 output. Sinks, softcap and fp32 output fall back to Gluon/Triton. Explicit backend="flydsl" calls that cannot run raise.
  • AOT: aiter/aot/flydsl/unified_attention.py is an AOT_MODULES replay module: it replays the public op on fake tensors, so the router picks each key (336 jobs, 112 each for G16, G8, G4, over batch_chunks buckets 1-32; --check supported). Decode on the fmha kernel reuses the prefill keys.
  • Batch limits: causal calls with B >= 512 decline (Triton serves them under backend=None; forced "flydsl" raises RuntimeError). Non-causal calls with B >= 2048 raise ValueError (no fallback exists).
  • FLYDSL_RUNTIME_RUN_ONLY: only the pa_decode branch is blocked. fmha decode runs from the AOT artifacts for Hkv=4 with G4, G8 or G16; other head configurations decline (Triton under backend=None, RuntimeError when forced).
  • FlyDSL API stability, audited against 0.5.0 (the pin on main): the deprecated fx.get is replaced by coord[i].unpack(). The remaining raw rocdl/llvm ops (permlane32_swap, ballot, readfirstlane, rcp, sched_barrier, cvt_pkrtz, intr_expect, inline asm anchors) stay, each with a comment: 0.5.0 has no stable equivalent (for example shuffle_xor returns one value and costs 5-6% prefill) and main's FlyDSL kernels already use the same ops.
  • Workspace cache (dormant with the pa_decode route): one grow-only power-of-two allocation per device, stream and head geometry; captured calls never allocate.
  • Triton-only arguments are forwarded to the Triton kernel and routed there.
  • bn64 O-stage LDS reuse is declared as two fx.unions.
  • op_tests/test_flydsl_fmha.py runs its pytest suite under CI.
  • Built and tested against FlyDSL 0.5.0.

Test Plan

gfx950, idle GPU, ENABLE_CK=0 FLYDSL_RUNTIME_ENABLE_CACHE=0:

python3 op_tests/test_unified_attention.py
python3 op_tests/test_flydsl_fmha.py
python3 -m pytest op_tests/test_flydsl_fmha.py
python3 -m pytest op_tests/test_flydsl_pa_decode.py   # main's file, unchanged by this PR
  • op_tests/test_unified_attention.py: the paged and packed coverage. End to end through the public entry, both KV layouts; routing spies that assert which backend ran (check_decode_routing, including RUN_ONLY and the env variable); batch limits 511/512 (causal) and 2047/2048 (non-causal) and batch_chunks bucket crossings; a uniform-capture / ragged-replay graph test; paged-addressing pools above 2^31 bytes. The pa_decode graph and workspace-growth checks are dormant and skip with a reason.
  • op_tests/test_flydsl_fmha.py: prefill builder cases (dense, varlen, LSE, split-K, f16 output) plus test_fp8_packed_bn64_late_logit_spike, which drives packed BN64 (G16) through flydsl_unified_attention into the softmax max-rebase and inf-recompute branches.
  • Sweep: 228 prefill shapes against a torch oracle (run at ec1f92d9f7), plus AOT of every job.
  • Performance: paired same-GPU A/B through the public entry against origin/main (HEAD and main back to back per shape, 512 MB L2/MALL flush, 3 rotated-order repeats, median of medians).

Test Result

At 458f11382e on gfx950: test_unified_attention.py PASS (all groups); test_flydsl_fmha.py 306 passed / 22 skipped; AOT 336 ok / 0 failed. Not re-run at this head: main's unchanged test_flydsl_pa_decode.py (504 passed / 0 failed / 38 skipped at ec1f92d9f7) and the 228-shape sweep (184 served by FlyDSL, 0 NaN, 44 declines at ec1f92d9f7).

Timed at 706fa4ef1a against main 07766baeae: paired same-GPU A/B, 512 MB cache flush between calls, 3 rotated repeats; per-cell run-to-run spread median 2.2% (prefill) / 2.9% (decode).

Hardware Workload Before (main) After Change
MI355X causal prefill, 114 cells (2 layouts x G4/8/16 x 19 shapes) Triton/Gluon FlyDSL fmha geomean 0.773 time ratio (per layout x G 0.761-0.789; worst cell 0.880)
MI355X non-causal prefill not supported FlyDSL fmha new
MI355X decode after routing, 35 uniform + 6 skew cells Triton/Gluon Triton/Gluon parity: uniform 0.999, skew 1.001 (worst 1.024)

Time ratio is new/main; below 1 is faster. Details in the vault issue doc.

Submission Checklist

PR Self-Review

Reviewed revision

b6ab8cb

Behavior and intent

Adds a FlyDSL backend behind unified_attention() for gfx950. The fmha_gfx950 kernel serves causal batches with no 1-token rows and all non-causal batches, which main cannot run. With backend=None, causal decode-only and possibly-mixed causal batches stay on main's Triton/Gluon kernel because FlyDSL pa_decode loses cold uniform decode and the router sees only shapes; the pa_decode route ships disabled. A non-causal call that FlyDSL declines now raises ValueError before the Triton fallback (the Triton entry's assert causal is also a ValueError), so it no longer depends on assert surviving python -O.

Validation and unverified scope

On gfx950 at the head, python3 op_tests/test_unified_attention.py PASS, pytest op_tests/test_flydsl_fmha.py 306 passed / 22 skipped, AOT 336 ok / 0 failed. Timed at the head against main, prefill is 0.773x main's time and decode is at parity. Unverified: main's pytest op_tests/test_flydsl_pa_decode.py and the 228-shape sweep at the head, the dormant pa_decode route, execution on gfx942, gfx1201 and gfx1250, the setup.py PREBUILD_KERNELS path, and large-batch non-causal performance.

At b6ab8cb (includes the merge of origin/main 4122ef5) on gfx950 with ENABLE_CK=0: FLYDSL_RUNTIME_ENABLE_CACHE=0 python3 op_tests/test_flydsl_fmha.py pytest 306 passed / 22 skipped and the gfx950 fp8 sweep PASS; python3 op_tests/test_unified_attention.py PASS, including the new check_noncausal_decline under normal and python -O; a bf16-then-fp16 sweep with the runtime cache enabled (fresh cache dir) PASS with a distinct f16 AOT key (out_dtype is now in the bind_aot key in _build_fp8). Unverified: a populated PREBUILD_KERNELS AOT cache replay, the prebuild replay covers only the bf16 launcher (f16 is not prebuilt), and gfx942 was not run.

PR-specific question

What permissions and untrusted-input boundary does this CI change have, and can fork PR code or text reach a privileged execution path?

The only .github/ change is one added row in .github/split-test-times/aiter.tsv (op_tests/test_unified_attention.py, 33), which is static timing data used to schedule the new script in CI test splitting. No workflow, script or permission is touched, and no PR-controlled text is read by any privileged step through this change.

Changed op tests

  • op_tests/test_flydsl_fmha.py: adds prefill builder cases with f16 output and test_fp8_packed_bn64_late_logit_spike (packed BN64, G16, through flydsl_unified_attention, a late logit spike that reaches the softmax max-rebase and inf-recompute branches, causal and non-causal, both layouts, with an empty sequence); main's cases are retained. Its __main__ now runs the pytest suite so CI executes these tests. These fail before this PR because the builder had no f16-output or packed BN64 path. Paged and packed routing coverage is in op_tests/test_unified_attention.py, not here.
  • op_tests/test_unified_attention.py: new. It drives unified_attention end to end, so router decisions (backend asserted by spies in check_decode_routing), fallback, batch limits, bucket crossings, a uniform-capture / ragged-replay graph test, both KV layouts and pools above the 2^31 byte view limit are covered. The fmha test never reaches the router and the Triton tests do not exercise the FlyDSL backend. It also checks that Triton-only arguments are routed to Triton, and check_noncausal_decline forces a FlyDSL decline of a non-causal call and asserts ValueError with Triton never invoked, including under a python -O subprocess; it fails before the fix under -O because the stripped assert let the call reach Triton. It extends the existing routing checks, no new file.

johannes-graner and others added 19 commits August 11, 2026 07:18
flydsl.kernels is not shipped in the wheel, so these sources have to be
vendored rather than imported. Copies flash_attn_fp8_gfx950.py plus the
fp8-reachable subset of flash_attn_utils.py: 56 of 153 top-level symbols,
1807 lines of 5535, computed as the transitive AST closure of the kernel's
imports. The bf16 Dualwave* hierarchy is absent and nothing leaks in.

dtype_to_elem_type is defined locally instead of reusing the shared vendored
copy under kernels/: that one predates fp8 and returns MLIR T.* types, while
these kernels need fx types for Vec.make_type.

Verified: imports from outside the repo root, and the dense fp8 control
reproduces the reference kernel exactly (maxerr 5.770e-02, cos 0.999766).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Upstream derives bn128 as (num_kv_splits <= 1) and (not varlen), which
conflates two unrelated things: bn128 selects a pipeline shape (6-deep K
prefetch ring, Q in registers, DMA V staging, packed-i32x8 direct PV), and
none of that depends on how Q is packed or whether the KV range is split.
Measured evidence: forcing FP8_PV_DIRECT true under varlen makes the kernel
build and compute real attention (cos 0.96), moving the split-K failure to
an unrelated workspace fault.

bn128 is now a factory parameter defaulting to None, which reproduces
upstream's expression exactly -- verified across all six (splits, varlen)
combinations. Callers opt in rather than inherit a silent change, because
the deep ring has only ever been measured dense and the shallow fp8 path is
unexercised.

BN128 was already in cache_tag, so the variants do not collide in the
compile cache; confirmed by test. No regression: all 7 shapes still
bit-identical to upstream.

The builder still rejects fp8+varlen ahead of traits construction, so this
is not yet reachable end-to-end -- that guard goes with the q_tok_base work.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The fp8 context never had compute_active_guard. The grid is sized
ceil(max_seqlen_q / BLOCK_M) in y for every batch entry, so under varlen the
excess blocks of each shorter sequence ran with q_start past their own end
and wrote into the next packed sequence's rows. bf16 skips them via
`q_start < seqlen_q_v`; fp8 computed seqlen_q_v and used it only for
delta_i32.

Earlier diagnosis in the vault said the body failed to apply q_tok_base to Q
addressing. That was wrong -- q_gmem_elem_offset already includes it. The
row-256 boundary came from unguarded out-of-range blocks, not bad
addressing.

Adds compute_active_guard/init_active_guard mirroring bf16, wraps the body
in the same @flyc.jit predicate, and lifts the builder's fp8+varlen
rejection. fp8 now pins bn128=True regardless of varlen, since the shallow
path still has no working PV dispatch.

7 ragged cases pass with zero bad rows, including one where every sequence
is far below BLOCK_M. Dense unchanged: still bit-identical to upstream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Last of the three fp8 rejections. KV is addressed through a block table
instead of contiguously; page size is structurally BLOCK_N (64), matching
the target workload's BLOCK_SIZE_64 cache.

Paged builds a fresh page-bounded descriptor per tile rather than walking
one whole-tensor descriptor with a soffset, so three things had to change
beyond copying the bf16 path:

- page_byte_stride uses ELEM_BYTES, not upstream's BF16_BYTES, and the page
  view is i8-typed to match the dense fp8 descriptors. Buffer offsets are
  scaled by the view's element width, so the bf16 constant would place every
  page but the first at twice its offset.
- kv_gmem_elem_offset drops the batch token base under paging. Dense fp8
  carries it in the voffset because its descriptor spans the whole tensor;
  inside a one-page descriptor it would push every batch above 0 past
  num_records and silently read zeros.
- Two of the three V staging paths fold the tile term into the voffset
  rather than the soffset, so it is removed there rather than zeroed in a
  slot they do not use.

The BN128 ring prefetches up to four tiles past the live range. Dense
absorbs that via num_records, but paged cannot: the page id selects the
descriptor base before any bound applies, so an unstaged block-table slot
sends the DMA outside the pool. page_id_for_tile clamps to the last staged
tile; those tiles are masked by the epilogue regardless.

Dense and varlen stay bit-identical to upstream. Paged verified over 14
cases including multi-batch, unaligned, non-causal, single-page, and
paged+varlen (the production prefill configuration), plus a permutation
invariance check that catches a kernel reading the pool by position.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Store per-partial max/sum and O, then combine 2+ partials. The combine
rescales m_row into shared combine units before reduction.
Two planned small-M optimisations, both of which the measurements killed.

prefetch_bound="clamp" bounds the ring's forward prefetch by clamping the
tile index rather than branching, so the loop stays one basic block and the
sched_group_barrier schedule is untouched. It removes a fixed 4-tile
overshoot worth 1.29x KV traffic at M=1384. It changes nothing at any
measured shape: the kernel is latency-bound, not bandwidth-bound, so the
overshoot was already absorbed by ring slack. Kept because it is free and
strictly less wasteful, with a comment saying not to expect a win. A
destructive-control run confirmed the flag reaches the emitted kernel.

The short-KV prologue trim was dropped before implementation: the prologue
stages exactly the 4 tiles that the minimum two loop iterations consume
(2 iterations x 2 tiles/iteration), so there was nothing to trim. The plan
assumed an over-fetch that does not exist.

What the fixed cost actually is, measured by holding the grid constant and
sweeping KV length: 13.9 us per launch, 59% of runtime at 4 tiles/WG and 4%
at 128. Splitting it further gives ~6.4 us per dispatch wave that does not
scale with KV -- the 32 KB Q stage, the 32 KB Q->VGPR re-read, and three
full-CTA barriers. That is 27% of M=1384 and 2% of M=32768, and it predicts
the measured curve within 4%. Removing it means restructuring the Q path,
which is past the scope agreed for this pass.

block_m is deliberately not exposed. It is bound by block_m = num_waves * 32
with rows_per_wave pinned by the MFMA tile, so halving it halves wave
occupancy, and 2 workgroups/CU is unreachable at any block_m because the KV
ring alone is 96.8 KB of an 80 KB half-budget.

Dense stays bit-identical to upstream; paged and split-K gates green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
_pv_fp8_direct emits D_CHUNKS=4 mutually independent MFMAs back to back --
each accumulates a different v_o[dc], and their operand prep is pure
bitcasts the compiler hoists, so nothing lands between them. A
sched_group_barrier alternating 1 MFMA with 4 VALU spreads them.

Measured +0.5% at M=32768 over three runs each, with the on and off ranges
not overlapping (1706.6/1704.8/1705.9 against 1695.9/1697.1/1700.5). Small
but real. M=1384 shows +1.0% mean with overlapping ranges, so unresolvable.
No shape regresses.

Two things this established that matter more than the 0.5%:

The clustering is NOT shape-specific. Identical 90% MFMA stall and the same
7 back-to-back pairs across three distinct compiled kernels (causal
paged+varlen M=1384 and M=8192, non-causal dense M=2048), because D_CHUNKS
is HEAD_DIM // D_CHUNK = 4 for every configuration the builder accepts. So
this is not overfitting to one shape.

And back-to-back issue was a symptom, not the cause. Spreading three of the
MFMAs cut their individual latency 38% (21,090 -> 13,136 cycles) but left
stall at 90%. They are waiting on the shared p_fp8 operand chain, not on
matrix-pipe issue pressure. That bounds what any further scheduling work can
recover and redirects it at the dependency structure instead.

Group id matters: the first attempt used group 14, which nothing else
references, and was silently dropped with the emitted schedule byte-identical
to baseline. Group 13 is what the loop epilogue uses. Adding ds_read to the
interleave made the cadence worse (back-to-back 4 -> 6) and was dropped.

Opt-in, default off; dense stays bit-identical and all three gates pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The prologue stages seven KV tiles, but the first loop iteration reads only
K1, V0, V1 -- the first three issued. vmcnt retires in order, so vmcnt(4)
covers exactly those and leaves the four prefetch tiles in flight; they are
not read until later iterations, each preceded by the loop's own full drain.
The paired lgkmcnt(0) is required for the barrier: with VDMA off, V staging
ends in an LDS store that vmcnt does not cover.

Vendors waitcnt_vm_n from upstream flash_attn_utils.py, which the fp8 AST
closure never pulled in because this kernel only ever called the full drain.
The bf16 sibling uses it 12 times.

Medians improve ~1-2% at the trace shapes and are flat at M=32768, but ranges
overlap at 9 repeats, so this is not a demonstrated win -- it is kept because
the narrower wait is strictly more correct about what it is waiting for. The
first prologue drain is NOT narrowable: load_k(t0) is issued before Q's
chunks, so in-order vmcnt retirement means waiting for Q implies waiting for
K0 anyway, and Q is read immediately after the barrier.

All 42 gate cases pass; dense stays bit-identical to upstream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Memory and compute clusters strictly alternating, one barrier each, mirroring
the bf16 sibling. This is step 1 of 3 and is a REGRESSION on its own: 8-15%
slower (11885 / 260.0 / 49.7 us at M=32768 / 4023 / 1384 against 10342 /
234.6 / 46.2). Expected -- seven added barriers buy nothing until the wave
stagger has the granularity to exploit them. Kept as a checkpoint so the
stagger's contribution can be measured separately.

Two bf16 mechanisms are deliberately not ported, because fp8 cannot represent
them: the half-computed P carried across the back edge, and the rescale of an
already-cast P between PV steps. Both need a P surviving an ext/scale/trunc
round trip, and e4m3 has 3 mantissa bits. So the merged max stays (both score
sets live at C3) and _subtile_tail stays barrier-free.

Intermediate boundaries wait lgkmcnt(0) only, leaving the prefetch DMAs in
flight; only the back edge drains. Verified in the compiled IR: 7 lgkm
boundaries + 1 drain. No barrier is placed inside lazy_correct_o's scf.if,
which is ballot-gated and can diverge per wave.

All 42 gate cases pass; dense stays bit-identical to upstream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Factors M as BLOCK_Q query positions x GQA_GROUP_SIZE heads instead of
BLOCK_M positions x 1 head, mirroring Triton unified_attention's
`query_pos = q_block_local_idx * BLOCK_Q + offs_m // num_queries_per_kv`.
grid.x becomes num_kv_heads (64 -> 4 at GQA 16:1).

This is what lets one launch batch both phases: at Sq=1 a single token
fills the tile because the tile's width is heads, and at Sq=4023 the same
tile holds BLOCK_Q positions. Previously 1 of 256 M rows carried work at
decode, and 16 workgroups per GQA group each re-streamed the same KV.

Measured on MI355X, legacy -> packed, fp8 paged+varlen causal:

  4023+7x1 ctx16k   2072 -> 1809 us   1.15x
  2821+7x1 ctx16k   1707 -> 1215 us   1.40x
  1384+8x1 ctx16k   1288 ->  713 us   1.81x
  decode b=8        639  ->  302 us   2.11x
  decode b=64       5004 ->  425 us  11.78x
  prefill M=4023    1218 -> 1232 us   0.99x

Against Triton the mixed batch flips from losing to winning: 0.60-0.97x
becomes 1.04-1.11x, with prefill unchanged at 1.08x.

Three bugs fixed along the way, each with its own signature:
- the XCD swizzle linearised (x, y) with NUM_HEADS_Q while the grid
  launched NUM_HEADS_KV, dropping every head above num_kv_heads
- the causal block-reversal recomputed q_start in BLOCK_M units,
  so only q_block_idx 0 landed correctly
- init_tile_bounds bounded the causal KV extent by BLOCK_M rather than
  BLOCK_Q, over-running the tile count by the group size

Off by default (gqa_pack_m=False); the legacy path stays bit-identical to
upstream. gqa_pack_m with num_kv_splits > 1 is refused: the split-K
workspace is indexed by a scalar q_head_idx that does not exist when the
head varies per M row.

Also parameterises num_waves/block_m and adds a num_prefetch_k probe knob,
and puts BLOCK_M/NUM_WAVES/BLOCK_SIZE in the JIT cache key so tile-shape
variants cannot alias to one compiled binary.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
rocprofv3 kernel trace gives 137.0 KB LDS per workgroup against 160 KB
per CU, so two workgroups would need a 41% cut and zeroing the Q tile
outright still leaves 105 KB.

Also corrects a misreading: the vt array is typed bf16 but sized in fp8
bytes under BN128, so it already holds raw fp8 at the theoretical
minimum. There is no bf16 V staging to reclaim.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Route the vendored gfx950 fp8 flash-attention kernel through the public
unified_attention() entry point that vLLM and SGLang import, via a
return-None opt-in adapter (aiter/ops/flydsl/unified_attention_kernels.py)
rather than a libtype tuned CSV or a new environment variable. softmax_scale
is injected by pre-scaling q_descale, so no kernel edit is needed. The adapter
gates on the exact served configuration (head_dim, dtype, paged, varlen) and
returns None otherwise, falling through to Triton.

The adapter's support gate also carries the non-causal / fp16-output / sinks
relaxations from the shape-widening work committed separately; they ride in
this file because it is a single new module and git has no baseline to split
them against.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extend the gfx950 fp8 dual-wave kernel's shape coverage. None of these
changes touches the 8-cluster main-loop schedule; all are gate, init,
epilogue, output-store, and validation only. The default bf16-output causal
use_sinks=False path stays bit-identical to upstream.

- Non-causal: the builder already supported it; the restriction was only the
  adapter gate (committed separately). Paged+varlen+non-causal now tested.
- fp16 output: a distinct out_dtype_str selects cvt_pkrtz vs cvt_pk_bf16_f32
  at the output store sites only; the internal bf16 P-pack is untouched and
  the split-K partial dtype follows the output dtype.
- Attention sinks: seed m_row from a per-head fp32 sink with factor
  sink*log2e/c_logit_scale (c_logit_scale already folds in log2e), gathered
  per-M-row under GQA packing, with a sink term in the epilogue denominator.
  Split-K + sinks is refused at build time: the combine pass has no sink input
  and would count exp(sink) once per split. The adapter never builds split-K,
  so the served path is fully covered.

Bug fix: dtype_str is validated but the traits factory is fp8-only, so
build(dtype_str="bf16") silently built fp8. Validation now rejects non-fp8.
cross_seqlen and dualwave_swp_debug_lazy_counts are dropped from the cache tag
(set but never read; they were multiplying identical compiled variants).

All three gates pass with the flydsl cache cleared: vendored dense
bit-identical + varlen + fp16 + sinks + split-K-sinks refusal, paged 18/18,
split-K 14/14, every case zero bad rows under its applicable criterion.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The GQA-packed decode path could not use split-K: the partial store indexed
the workspace by a scalar q_head_idx, absent under packing where the head
varies per M row. Make store_splitk_partial_o and store_empty_split key on the
per-M-row q_head_row (identical to q_head_idx when unpacked, so byte-identical
there); the combine kernel was already head-generic. Lift the build refusal.

Not auto-enabled: the default still yields unpacked for num_kv_splits > 1, so
packed+split-K only occurs when a caller passes gqa_pack_m=True. GQA_PACK_M and
NUM_KV_SPLITS both key the JIT cache, so this cannot alias the unpacked binary.

Decode-only ITL, GQA 16:1, vs packed single-pass: 2.3x-5.3x faster at splits 4-8,
beating Triton unified_attention at ctx=4096 (24us vs 56.6us). 36/36 packed
split-K cases correct (0 bad rows); existing unpacked split-K, dense, varlen,
paged gates all unchanged. No hot-loop code touched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Wire the packed+split-K decode path into unified_attention() so it is selected
automatically, and extend it to ragged (unequal-length) decode batches.

Kernel: lift the varlen+split-K build refusal. The per-segment KV range was
already per-sequence (init_tile_bounds reads seqlen_kv_v, which under varlen is
cu_seqlens_kv[b+1]-cu_seqlens_kv[b]); the only gap was compute_active_guard
dropping the per-sequence q-range check under split-K, so a short sequence's
excess q-blocks wrote into the next packed sequence. AND the two predicates
under varlen+splitK; byte-identical otherwise.

Dispatch: select split-K only when max_seqlen_q == 1 (all-decode), max_seqlen_k
> 512, num_2d_prgms < 256 (machine underfilled), and no sinks. Split count is
the largest power of 2 with num_2d*splits <= 256, capped at 8 (b=7/8 -> 8,
b=9 -> 4, matching the measured winners). The all-decode gate keeps every
prefill and mixed batch on single-pass: the split-K combine workspace is
dense-in-q and cannot serve unequal query lengths, so ragged-q batches must not
route here. Verified: no unequal-q batch is ever dispatched to split-K.

Decode-only end-to-end: b=8 ctx=4096 40.5us (was ~78, beats Triton 56.4us at
1.39x), b=8 ctx=16384 60.7us (was ~289, ~parity). Prefill/chunked/mixed
geomeans unchanged (1.135/1.094/1.057x). Ragged split-K correct (18 cases,
0 bad rows); all standing gates pass, dense bit-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The split-K combine wrote O at batch_idx*seq_len, correct only when every
sequence has max_seqlen_q query rows -- so the dispatch gated split-K on
all-decode (max_seqlen_q == 1). Rebase the combine's O write on cu_seqlens_q
under varlen: sequence batch_idx's rows start at cu_seqlens_q[batch_idx], with
num_records bounded to its own query length (which also guards the padding
combine rows past a short sequence). The workspace stays dense (seq_len q-slots
per batch, filled at local q_row), so the format is unchanged and the all-decode
path is byte-identical (cu=[0,1,2,...] collapses both terms to the old formula).

Drop the max_seqlen_q == 1 gate condition. num_2d_prgms is now the packed
per-sequence workgroup count, num_kv_heads * sum_i ceil(query_len_i / BLOCK_Q),
so a low-chunk mix that underfills the machine routes to split-K while a
high-chunk mix (long prefill) fills it and stays single-pass. This costs one
host sync per dispatch on cu_seqlens_q, gated behind max_seqlen_k > 512; the
gate genuinely depends on per-sequence q-block counts so the read is
unavoidable without a caller-supplied count (noted for future).

Low-chunk mixed (chunk=128 + 8 decodes) now 1.35x vs single-pass at ctx=16384;
high-chunk mixed and prefill unchanged. New correctness gate 12/12, 0 bad rows;
all existing gates pass, all-decode split-K byte-identical, dense bit-identical.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The split-K gate needs num_2d_prgms = num_kv_heads * sum_i ceil(qlen_i/BLOCK_Q),
whose per-sequence lengths live on cu_seqlens_q (device); reading them with
.item() put a ~29us host sync on the dispatch critical path -- 48-121% of kernel
time on the shallow decode shapes split-K is meant to win. Decide the branch from
host-side scalars wherever the exact sum cannot change the outcome (mirrors
Triton's own dispatch, which avoids the same read):

- all-decode (max_seqlen_q==1): each qlen is 1, so the sum is exactly num_seqs.
- otherwise a host lower bound max(num_seqs, ceil(total_q/BLOCK_Q)) is provably
  <= the exact sum; when num_kv_heads*lower_bound >= target the machine is full
  and single-pass is correct without the read (prefill, high-chunk mix).
- only a low-chunk mix that underfills the machine still reads cu_seqlens_q, and
  only there does the exact sum change the split count.

Every dispatch decision is identical to the exact-sum form (verified old-vs-new
across the full table and end-to-end through unified_attention()). Sync cost on
the no-read paths falls 29.4us -> ~0.07us. All gates pass, no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The regression gates for the fp8 gfx950 unified-attention work lived only in the
issue's investigation scripts, so aiter itself carried the shipped code without
the tests that prove it correct. Port the six shipped-feature gates into
op_tests/flydsl_tests/ as pytest tests: packed+split-K decode (36 equal + 18
ragged), low-chunk mixed split-K (12), paged (19), unpacked split-K (14),
chunked cross-prefill (5), and the vendored dense/varlen/fp16/sinks gate (26 + 1
OOM skip).

Idiomatic to the existing flydsl_tests: SPDX header, repo-relative import,
get_gfx_runtime + is_flydsl_available skip marks (skip, not fail, off gfx950),
parametrized cases, shared ref_paged_attn where it applies (paged, cross-prefill)
and self-contained fp32/upstream references where it does not (dense contiguous
KV, sinks, fp16, bit-identical-to-upstream). Thresholds preserved exactly,
including the sinks combined abs+rel bad-row rule and the dense bit-identical
check. The upstream bit-identical comparison needs the FlyDSL reference checkout;
it reads FLYDSL_REF_CHECKOUT (default ~/projects/flydsl) and skips cleanly if
absent. All pass on gfx950 with the same case counts as the originals.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Move the dispatch hook into the public unified_attention entry point,
tighten the adapter support gate, trim dev-history from kernel comments,
and expand the end-to-end tests.
@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:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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 4676 --add-label <label>

@github-actions github-actions Bot 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.

Remaining comments which cannot be posted as a review comment to avoid GitHub Rate Limit

ruff

⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E731)

mk = lambda n: torch.randn(b, S, n, d, generator=g, device=DEV, # noqa: E731


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from aiter.ops.flydsl.utils import is_flydsl_available # noqa: E402


⚠️ [ruff] <I001> reported by reviewdog 🐶
Import block is un-sorted or un-formatted

from aiter.ops.flydsl.kernels.flash_attn_fp8_gfx950 import (
build_flash_attn_dualwave_swp_fp8_module as build,
)
from aiter.ops.flydsl.kernels.flash_attn_dualwave_common import (
dualwave_splitk_workspace_elems as ws_elems,
)


⚠️ [ruff] <RUF059> reported by reviewdog 🐶
Unpacked variable b is never used


⚠️ [ruff] <RUF059> reported by reviewdog 🐶
Unpacked variable sq is never used


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from aiter.ops.flydsl.utils import is_flydsl_available # noqa: E402


⚠️ [ruff] <I001> reported by reviewdog 🐶
Import block is un-sorted or un-formatted

from aiter.ops.flydsl.kernels.flash_attn_fp8_gfx950 import (
build_flash_attn_dualwave_swp_fp8_module as build,
)
from aiter.ops.flydsl.kernels.flash_attn_dualwave_common import (
dualwave_splitk_workspace_elems as ws_elems,
)


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from aiter.ops.flydsl.utils import is_flydsl_available # noqa: E402


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E731)

mk = lambda n: torch.randn(b, s, n, d, generator=g, device=DEV, # noqa: E731


⚠️ [ruff] <RUF059> reported by reviewdog 🐶
Unpacked variable b is never used


⚠️ [ruff] <RUF059> reported by reviewdog 🐶
Unpacked variable b is never used


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E731)

mk = lambda n: torch.randn(total, n, d, generator=g, device=DEV, # noqa: E731


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

import aiter.ops.triton.attention.unified_attention as ua # noqa: E402


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from aiter.ops.flydsl.utils import is_flydsl_available # noqa: E402


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from op_tests.flydsl_tests.test_flydsl_unified_attention import _build # noqa: E402


⚠️ [ruff] <RUF100> reported by reviewdog 🐶
Unused noqa directive (non-enabled: E402)

from op_tests.triton_tests.attention.test_unified_attention import ( # noqa: E402


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

kwargs = dict(
q=q, k=k, v=v, out=out,
cu_seqlens_q=cu_q, max_seqlen_q=max(query_lens),
seqused_k=seqused_k, max_seqlen_k=max(kv_lens),
softmax_scale=SCALE, causal=True, window_size=(-1, -1),
block_table=bt, softcap=0,
q_descale=q_ds, k_descale=k_ds, v_descale=v_ds,
)


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

kwargs = dict(
q=q, k=k, v=v, out=out,
cu_seqlens_q=cu_q, max_seqlen_q=max(query_lens),
seqused_k=seqused_k, max_seqlen_k=max(kv_lens),
softmax_scale=SCALE, causal=True, window_size=(-1, -1),
block_table=bt, softcap=0,
q_descale=q_ds, k_descale=k_ds, v_descale=v_ds,
)


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"softcap": dict(softcap=30.0),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"sliding_window": dict(window_size=(256, 0)),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"alibi_slopes": dict(alibi_slopes=torch.ones(64, device="cuda", dtype=torch.float32)),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"output_scale": dict(output_scale=torch.ones(1, device="cuda", dtype=torch.float32)),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

base = dict(
q=q, k=k, v=v, out=out, cu_seqlens_q=cu_q, seqused_k=seqused_k,
max_seqlen_k=256, causal=True, window_size=(-1, -1), block_table=bt,
softcap=0, q_descale=q_ds, k_descale=k_ds, v_descale=v_ds,
num_kv_heads=4, block_size=PAGE, num_queries_per_kv=16, num_seqs=1,
q_scales=None, alibi_slopes=None, output_scale=None, qq_bias=None,
sinks=None, shuffled_kv_cache=False, skip_reduce=False,
)


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

base = dict(
q=q, k=k, v=v, out=out, cu_seqlens_q=cu_q, seqused_k=seqused_k,
max_seqlen_k=256, causal=True, window_size=(-1, -1), block_table=bt,
softcap=0, q_descale=q_ds, k_descale=k_ds, v_descale=v_ds,
num_kv_heads=4, block_size=PAGE, num_queries_per_kv=16, num_seqs=1,
q_scales=None, alibi_slopes=None, output_scale=None, qq_bias=None,
sinks=None, shuffled_kv_cache=False, skip_reduce=False,
)

Bring the PR's files to the two style gates CI enforces
(.github/workflows/pre-checks.yaml): psf/black@stable and ruff 0.16.0.

- black: reformat all touched files (the kernel files are new in this PR,
  so this is PR code only).
- ruff: drop unused `# noqa` directives for rules not in ruff's default set
  (E402/E731/E741/E722/BLE001), sort imports, remove unused imports, rewrite
  dict() calls as literals, and underscore-prefix unused unpacked test vars.
- Remove dead locals flagged by F841: the redundant `PAGED` local (traits.PAGED
  is read directly), the unused `bn128`/`bn128_pf` flags, and the unused
  smem_v_* tile-stride chain (the V buffer is sized from smem_k_tile_elems).
- Add the repo-conventional `# noqa: B008` to the fx.Stream(None) default arg.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@johannes-graner
johannes-graner force-pushed the jograner/flydsl-unified-attention-SILOTIGER-877 branch from 51c4bbd to 7fdcd6f Compare August 11, 2026 08:35
johannes-graner and others added 7 commits August 11, 2026 11:32
- Vendoring claims: "vendored from FlyDSL" -> "adapted and extended from
  FlyDSL" in both kernel files; note the fp8 paged/varlen/split-K/sinks
  machinery is aiter-owned and not upstream-tracked, and drop the stale
  extracted-line counts (the file has since grown well past them).
- fp8 build-mode comment: rewrite the past-tense "was rejected / now works"
  dev-history to present-tense current behavior.
- Qualify the dangling "bf16 sibling" references to name the upstream file
  (FlyDSL kernels/attention/flash_attn_gfx950.py); there is no in-tree sibling.
- Drop A/B and commit-hash references; drop the model-specific KV-cap claim
  (the kernel is not model-specific); drop the ATT latency-percent number.
- Reword the C1 VGPR comment and simplify the varlen active-guard comment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- _supported (U156): split the ~90-line AND-chain into named sub-predicates
  (_dispatch_mode_ok / _page_geometry_ok / _dtypes_ok / _descales_ok /
  _geometry_ok / _no_unsupported_features / _sinks_ok), each with a short
  docstring, mirroring the existing _strides_ok. Same predicates, same
  short-circuit order; signature unchanged (tests call it directly).
- Guards (F77): head_dim/dtype/out_dtype builder-arg guards now raise
  ValueError (house convention; matches test_flydsl_fmha). Arch guard stays
  RuntimeError (hardware capability).
- Prefetch index (F399): inline the identity _pf_tile; move its rationale to
  the (deliberately unclamped) pf_a/pf_b site.
- Launch defaults (F827): factor the default-filling and arg tuple shared by
  _launch and _compile into _normalize_launch_args, removing ~30 lines of
  hand-synced duplication.

Verified on gfx950 (cache cleared): test_unified_attention_flydsl 23 passed;
test_vendored_fp8_attention 19 passed/1 OOM-skip; test_fp8_splitk +
test_packed_splitk_decode 68 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Hoist the byte-identical copy-pasted helpers across the 8 fp8-attention test
files into op_tests/flydsl_tests/_common.py (underscore-prefixed, not collected):
- q8: the per-tensor fp8 e4m3 quantizer (7 copies). Kept hand-rolled -- aiter's
  per_tensor_quant omits the clamp(min=1e-4) scale floor and diverges on
  near-zero tensors.
- assert_attn_close: the bad-rows/max-err/cosine numeric gate (8 copies),
  parameterized so every call site keeps its exact tolerances.
- build wrappers (6 copies) and the dense fp32 reference (2 copies).

Deliberately left per-file: the page-pool/block-table builders and the
ragged/mixed/sinks reference variants (they differ by layout, so unifying would
risk changing what each test exercises) and the routing-specific helpers.

Behavior-preserving: 167 passed, 1 skipped (OOM ref) -- identical to baseline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
>8 k-splits verified correct on gfx950 (16 and 32 splits, causal and
non-causal, bad_rows==0, cosine >0.9996 vs fp32 reference). The cap of 8 is a
performance-measurement bound, not a correctness limit -- reword to say so and
drop the stale "prototype" framing (here and in the _get_kernel docstring).
_MAX_SEGMENTS stays 8 pending perf tuning of larger counts.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Benchmark (issue scripts u74_splits_*.py) shows the optimal auto-dispatch split
count is ctx-dependent: 8 under-splits long-context small-batch decode by up to
~4x (b=1 ctx=131072: 291.9us @8 vs 79.6us @64), while >16 regresses short
contexts because _split_count keys on machine fill, not KV depth. 16 is the
no-regression default that captures most of the long-context win.

Since split-K selection cannot be tuned perfectly from shape alone (cf. CK),
expose the cap as AITER_UNIFIED_ATTN_MAX_KV_SPLITS rather than guessing from
ctx: default 16, raise for long-context workloads. All split counts verified
correct to 128. The public unified_attention() signature is frozen (vLLM/SGLang
import it), so an env var is the only pass-through available.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…V_SPLITS

README had no home for runtime tuning knobs (only build-time vars inline). Add a
section documenting the split-K cap override; future tuning env vars go here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment/docstring-only pass, no code changes:
- Rewrapped a handful of over-88-char comment lines in the two kernel
  files (flash_attn_dualwave_common.py) that black leaves unwrapped;
  ISA/MFMA/scheduling rationale in those files was left untouched.
- Deduped the near-verbatim `~/.flydsl/cache` JIT-cache caveat that was
  repeated in 5 test-file module docstrings (test_fp8_paged,
  test_fp8_cross_prefill, test_fp8_splitk, test_packed_splitk_mixed,
  test_packed_splitk_decode): canonical text now lives once in
  _common.py's module docstring, each test file points at it with a
  one-line pointer.
- Compressed the long module docstring and dispatch-tier comment block
  in unified_attention_kernels.py (the adapter) and the verbose
  docstrings in test_unified_attention_flydsl.py and
  test_flydsl_unified_attention.py to their load-bearing "why", cutting
  restatement and worked-example narration while keeping every
  correctness rationale.
- Dropped a dated "calibrated 2026-08-07 sweep" dev-log comment,
  keeping the resulting threshold and the reasoning behind it.

Validated with py_compile, ruff, black --check, and
op_tests/test_unified_attention_flydsl.py (23 passed).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
AOT list covers GQA groups 16/8/4 (288 jobs).
Non-causal enrolls bc16/32 (336 jobs); causal stays at bc<=8 and declines
to Triton above it. Non-causal B>2047 raises ValueError (no fallback; the
scan spills above 32 chunks).
…ed-attention-SILOTIGER-877

# Conflicts:
#	aiter/ops/flydsl/kernels/pa_decode/context.py
#	aiter/ops/flydsl/kernels/pa_decode_kernel.py
#	aiter/ops/flydsl/pa_decode.py
#	aiter/ops/flydsl/pa_decode_tuning.py
#	op_tests/test_flydsl_pa_decode.py
Paired A/B showed FlyDSL pa_decode slower than the gfx950 Gluon kernel on
33/35 uniform decode cells. No sync-free host quantity separates the skew
batches where it wins, so auto decode goes to Triton/Gluon. backend="flydsl"
or AITER_UNIFIED_ATTN_PA_DECODE=1 keeps pa_decode reachable; non-causal
decode stays on FlyDSL.
Raise NotImplementedError before the NHD traits assertion is reached; add
test_pa_decode_nhd_fp8_query_rejected.
… on a capability flag

Restore pa_decode kernel, wrapper, tuning and tests to main. The router enables
the pa_decode decode route only when pa_decode sets SUPPORTS_FP8_QUERY; without
it, non-causal and forced decode run on the fmha kernel.
They hard-code local paths and import modules outside the tree; kept locally untracked.
- Staged epilogue waits vmcnt(0) before overwriting the K/V ring, so an
  empty segment's tile-0 LDS DMA is drained explicitly.
- One _load_elem wrapper holds the raw copy_atom_call_ssa with its reason;
  one _load_scalar_f32 replaces the duplicated descale loaders.
- Staged O read/store map and the scan lane/chunk map use layouts.
- Record why the compact grid has no XCD remap; drop investigation labels.
- Packed BN64 test with a late logit spike reaching the max-P rebase and
  the inf recompute, causal/non-causal, linear/shuffled, with an empty
  sequence.
…ests

Decode that pa_decode declines now falls through to the fmha kernel once
SUPPORTS_FP8_QUERY is set, and FLYDSL_RUNTIME_RUN_ONLY declines only decode
without an AOT artifact (the packed Hkv=4 keys are prebuilt). The
AITER_UNIFIED_ATTN_PA_DECODE parse lives in one helper.

Unified-attention AOT is an AOT_MODULES replay of the public op instead of a
hand-wired fake-tensor pass; it still enrolls 336 jobs.

op_tests assert which backend ran, add G2, batch-chunk bucket and B limit
cases, empty q-sequences, and a uniform-capture / ragged-replay graph check;
the dormant pa_decode checks skip with an explicit reason.
…ed-attention-SILOTIGER-877

# Conflicts:
#	.github/split-test-times/aiter.tsv
Comment thread aiter/ops/unified_attention.py Resolved
Comment thread op_tests/test_flydsl_fmha.py Resolved
johannes-graner and others added 5 commits November 19, 2026 14:18
…riton

Add equal_seqlen_q, attn_work, force_fp8_pv_on_fp4_kv_cache, output_gate and output_rows to the wrapper and forward them to Triton. FlyDSL does not implement the last three, so auto routing falls back to Triton and backend="flydsl" raises.
The staged epilogue reused the kv/vt LDS through a raw pointer from lds.kv. Declare the reuse as a union of {kv, vt} and the O-stage array so the overlay and its size are part of the storage type. LDS size and output are unchanged.
CI runs op_tests as scripts, so the pytest functions never ran. Run them first, as the other FlyDSL op_tests do, and only run the benchmark sweep if they pass.
A single union gave kv and vt one LDS symbol, which dropped their alias scopes; the waitcnt pass then serialised ring-buffer reads behind the K/V DMAs (+13% on bn64). Overlay each half of the O stage on its own ring buffer instead, so kv and vt stay distinct LDS objects. Output is bit-identical.

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

Confirmed a silent correctness bug in the new public entry: optimized Python allows declined non-causal calls to execute the causal-only Triton fallback. Reviewed revision 296876d. Direct gfx950 kernel validation remains unavailable.

[P2] Reject non-causal calls unconditionally before Triton fallback — aiter/ops/unified_attention.py:196

When FlyDSL declines a non-causal call, this entry forwards causal=False to Triton, whose only rejection is assert causal. Under python -O or PYTHONOPTIMIZE, that assertion disappears and the fallback can silently apply causal masking. Reproduced on gfx942 with two BF16 query rows, zero Q/K, two valid KV tokens, and V values 1 and 3: automatic routing returned [1.0, 2.0], while non-causal attention requires [2.0, 2.0]. Add an unconditional exception before this fallback whenever causal is false, and cover the declined route under optimized Python.

Validation:

  • PASS on local: git -C exact-checkout rev-parse HEAD
    Matched 296876d; remote isolated source also matched. All changed Python files passed AST parsing.
  • PASS on hjbog-srdc-39.amd.com / sixifang_dev / gfx942: flock -w 30 /tmp/codex-pr-review-4676-296876d3/gpu.lock timeout 120 ../venv/bin/python ../fallback_repro.py
    Exit 0: normal Python rejected the non-causal fallback with 'Only causal attention is supported'. Verified gfx942, idle GPU 0, FlyDSL 0.5.0 from the isolated virtual environment, and imports from the exact checkout.
  • FAIL on hjbog-srdc-39.amd.com / sixifang_dev / gfx942: flock -w 30 /tmp/codex-pr-review-4676-296876d3/gpu.lock timeout 120 ../venv/bin/python -O ../fallback_repro.py
    Exit 1: observed non-causal output [1.0, 2.0] instead of [2.0, 2.0]. The reproduction raised RuntimeError after checking the values. Log: fallback-gfx942-final.log.
  • PASS on hjbog-srdc-39.amd.com / sixifang_dev / gfx942: flock -w 30 /tmp/codex-pr-review-4676-296876d3/gpu.lock timeout 120 ../venv/bin/python ../causal_smoke.py
    Exit 0: causal control returned the expected [1.0, 2.0]. Log: causal-smoke-gfx942.log.
  • SKIP on dzm-mi355-gpu34-dev / gfx950: ssh -o BatchMode=yes -o ConnectTimeout=10 -o RemoteCommand=none -o RequestTTY=no -o ControlMaster=no -o ControlPath=none dzm-mi355-gpu34-dev "squeue -h -u zhiming_ding_qle -o '%i|%N|%t'"
    Allocation discovery failed with exit 255: connection to aac16.amd.com port 22 timed out. No gfx950 tests executed. Log: allocation.log.

Remaining validation:

  • The new gfx950 paged MFMA kernel, AOT execution, and performance were not tested directly by this review.
  • Read-only CI logs confirmed test_flydsl_fmha.py completed with 306 passed and 22 skipped; these are CI results, not reviewer-run tests.
  • No base GPU comparison was performed because the new public module is absent from the supplied base. Detailed commands, environment setup, and logs are preserved in validation-notes.txt and this task directory.

Automated Codex review of commit 296876d3f583.

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

LGTM

…he Triton fallback

Triton only rejected non-causal via assert, stripped under python -O, so a
declined non-causal call silently ran causally. Raise ValueError
unconditionally in the wrapper and in the Triton entry; test it normally and
in a -O subprocess.
…ed-attention-SILOTIGER-877

# Conflicts:
#	.github/split-test-times/aiter.tsv
#	aiter/aot/flydsl/README.md
The merge of main (#8600 AOT binding) left _build_fp8's out_dtype out of
the bind_aot key, so bf16 and f16 launchers shared one cached kernel and the
f16 call ran the bf16 epilogue.
@johannes-graner

Copy link
Copy Markdown
Contributor Author

Fixed in 9fc5251. aiter/ops/unified_attention.py now raises ValueError before the Triton fallback whenever FlyDSL declined a non-causal call, and the Triton entry's assert causal is an explicit ValueError so direct callers are also safe under python -O. op_tests/test_unified_attention.py adds check_noncausal_decline, which forces the FlyDSL decline, asserts the error and that Triton is never invoked, and re-runs itself under python -O. Validated on gfx950: test_unified_attention.py PASS, test_flydsl_fmha.py 306 passed / 22 skipped.

@johannes-graner

Copy link
Copy Markdown
Contributor Author

@fsx950223 I believe your change request is addressed now.

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

LGTM!

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.

9 participants