Skip to content

Transpose add - #5

Merged
valarLip merged 6 commits into
mainfrom
transpose_add
Dec 4, 2024
Merged

valarLip merged 6 commits into
mainfrom
transpose_add

Conversation

@fangche123

Copy link
Copy Markdown
Contributor

No description provided.

@valarLip
valarLip merged commit 8db72fc into main Dec 4, 2024
amd-youchen added a commit to amd-youchen/aiter that referenced this pull request Dec 3, 2025
valarLip added a commit that referenced this pull request Mar 18, 2026
valarLip added a commit that referenced this pull request Jul 27, 2026
…igs (#4397)

* [dev] Pr/a8w4 situv2 (#4)

* add Situv2 activation for a8w4 MoE stage1

* refactor(flydsl): scope situv2 helpers and fix lint

Move situ beta compile-time constants into situ_elem/situ_up_elem; apply
ruff/black fixes on the a8w4 situv2 test module.

* feat(moe): integrate SiTUv2 into fused_moe API, split-K, tuner/prebuild

* test(moe): add SiTUv2 host-ref + a4w4/a8w4 stage1 test (adapted to Situv2 naming)

Complements MHYang's aiter/ops/flydsl/test_flydsl_moe_a8w4.py by adding a
host-only (no-GPU) SiTUv2 reference sweep plus a4w4 stage1 coverage in
addition to a8w4. Adapted to this branch's API: ActivationType.Situv2 enum
and situ_beta / situ_linear_beta parameters on torch_moe_stage1 and
flydsl_moe_stage1.

Co-authored-by: Cursor <[email protected]>

* test(moe): add SiTUv2 default cases + --beta/--linear-beta to test_moe_2stage (Situv2 naming)

Co-authored-by: Cursor <[email protected]>

* test: consolidate a8w4 SiTUv2 vec4 cases into op_tests/flydsl_tests.

Move pytest tile/gate_mode sweep from aiter/ops/flydsl/test_flydsl_moe_a8w4.py
into test_flydsl_moe_situv2.py and remove the misplaced test file.

* style: black-format silu_and_mul_fq.py for CI pre-checks.

---------

Co-authored-by: MHYang <[email protected]>
Co-authored-by: Clement Lin <[email protected]>
Co-authored-by: Cursor <[email protected]>

* [dev] Pr/fix k dimension (#5)

* add Situv2 activation for a8w4 MoE stage1

* refactor(flydsl): scope situv2 helpers and fix lint

Move situ beta compile-time constants into situ_elem/situ_up_elem; apply
ruff/black fixes on the a8w4 situv2 test module.

* feat(moe): integrate SiTUv2 into fused_moe API, split-K, tuner/prebuild

* test(moe): add SiTUv2 host-ref + a4w4/a8w4 stage1 test (adapted to Situv2 naming)

Complements MHYang's aiter/ops/flydsl/test_flydsl_moe_a8w4.py by adding a
host-only (no-GPU) SiTUv2 reference sweep plus a4w4 stage1 coverage in
addition to a8w4. Adapted to this branch's API: ActivationType.Situv2 enum
and situ_beta / situ_linear_beta parameters on torch_moe_stage1 and
flydsl_moe_stage1.

Co-authored-by: Cursor <[email protected]>

* test(moe): add SiTUv2 default cases + --beta/--linear-beta to test_moe_2stage (Situv2 naming)

Co-authored-by: Cursor <[email protected]>

* test: consolidate a8w4 SiTUv2 vec4 cases into op_tests/flydsl_tests.

Move pytest tile/gate_mode sweep from aiter/ops/flydsl/test_flydsl_moe_a8w4.py
into test_flydsl_moe_situv2.py and remove the misplaced test file.

* style: black-format silu_and_mul_fq.py for CI pre-checks.

* Fix GUI shuffle_scale k_pad for non-256-aligned MoE K and auto stage2 tile_k.

Pad w2/w1 GUI e8m0 scales to k_groups multiple of 8 (DSV4 inter=640), unify
stage2 tile_k selection in flydsl_moe_stage2 and fused_moe, and add staged
a8w4 regression tests across inter/model K sweeps.

* test: integrate a8w4 K-dimension regressions into existing test suites.

Move shuffle pad coverage into test_quant_mxfp4 and FlyDSL GUI stage2/e2e
into test_flydsl_moe_a8w4; drop standalone op_tests files for repo convention.

* test: move flydsl a8w4 GUI regressions to op_tests/flydsl_tests.

Relocate test_flydsl_moe_a8w4 under op_tests/flydsl_tests and align with
pytest conventions used by other FlyDSL op tests.

---------

Co-authored-by: MHYang <[email protected]>
Co-authored-by: Clement Lin <[email protected]>
Co-authored-by: Cursor <[email protected]>

* [dev] Feat/flydsl moe a16wfp4 (#6)

* add Situv2 activation for a8w4 MoE stage1

* refactor(flydsl): scope situv2 helpers and fix lint

Move situ beta compile-time constants into situ_elem/situ_up_elem; apply
ruff/black fixes on the a8w4 situv2 test module.

* feat(moe): integrate SiTUv2 into fused_moe API, split-K, tuner/prebuild

* test(moe): add SiTUv2 host-ref + a4w4/a8w4 stage1 test (adapted to Situv2 naming)

Complements MHYang's aiter/ops/flydsl/test_flydsl_moe_a8w4.py by adding a
host-only (no-GPU) SiTUv2 reference sweep plus a4w4 stage1 coverage in
addition to a8w4. Adapted to this branch's API: ActivationType.Situv2 enum
and situ_beta / situ_linear_beta parameters on torch_moe_stage1 and
flydsl_moe_stage1.

Co-authored-by: Cursor <[email protected]>

* test(moe): add SiTUv2 default cases + --beta/--linear-beta to test_moe_2stage (Situv2 naming)

Co-authored-by: Cursor <[email protected]>

* test: consolidate a8w4 SiTUv2 vec4 cases into op_tests/flydsl_tests.

Move pytest tile/gate_mode sweep from aiter/ops/flydsl/test_flydsl_moe_a8w4.py
into test_flydsl_moe_situv2.py and remove the misplaced test file.

* style: black-format silu_and_mul_fq.py for CI pre-checks.

* Fix GUI shuffle_scale k_pad for non-256-aligned MoE K and auto stage2 tile_k.

Pad w2/w1 GUI e8m0 scales to k_groups multiple of 8 (DSV4 inter=640), unify
stage2 tile_k selection in flydsl_moe_stage2 and fused_moe, and add staged
a8w4 regression tests across inter/model K sweeps.

* test: integrate a8w4 K-dimension regressions into existing test suites.

Move shuffle pad coverage into test_quant_mxfp4 and FlyDSL GUI stage2/e2e
into test_flydsl_moe_a8w4; drop standalone op_tests files for repo convention.

* test: move flydsl a8w4 GUI regressions to op_tests/flydsl_tests.

Relocate test_flydsl_moe_a8w4 under op_tests/flydsl_tests and align with
pytest conventions used by other FlyDSL op tests.

* Add FlyDSL MoE a16wfp4 (bf16 x mxfp4) kernels on gfx950.

Port a16w4 stage1/stage2 into mixed_moe_gemm_2stage as dedicated _a16w4
builders while keeping HEAD fp8/fp4 compile paths unchanged. Wire dispatch
in moe_kernels and add op_tests/flydsl_tests regression for stage1, stage2,
and e2e against torch_moe references.

* Fix ruff/black lint issues in a16wfp4 PR files.

Remove unused _fly imports, move lds_space/types imports to module top,
add noqa for test sys.path bootstrap, and apply black formatting.

* Remove dead duplicate waves_per_eu None checks in a16w4 stage2.

The parameter defaults to int and callers always pass an int after dispatch.

* Fix a16w4 stage2: skip second compute when total_tiles==1.

The CK-style ping-pong pipeline assumed total_tiles>=2.  When
inter_dim==tile_k (e.g. inter_dim=256, tile_k=256) total_tiles=1,
the HEAD pre-fetched an out-of-bounds A tile into lds_ping, and the
TAIL then computed with that garbage data, producing cos~0.71 vs
reference.

Fix: const_expr(total_tiles==1) guard in the TAIL block--skip the
second compute_tile and the ping-buffer load entirely.

Also tighten test _check_result: add cosine+rel_L2 as primary gate
(cos>0.999) so future stage2 bugs cannot be masked by atol=1.0 on
small-magnitude outputs.

* Add pipeline guards for a16w4 stage1 total_tiles==1 and odd-tile validation.

The stage1 ping-pong pipeline has the same total_tiles>=2 assumption
as stage2.  Add:
- total_tiles==1 guard in stage1 TAIL (same pattern as stage2 fix)
- Validation: reject odd total_tiles and K < tile_k at compile time
  for both stage1 and stage2 a16w4 paths

These configs cannot occur with real LLM shapes (model_dim and
inter_dim are always multiples of 256), but the guards prevent
silent corruption on contrived inputs.

* Add SiTUv2 activation to a16w4 (bf16 x mxfp4) stage1.

Port the SiTUv2 activation from pr/a8w4-situv2 into the a16w4 stage1
kernel (both direct and cshuffle epilogues):
  situ_g   = beta * tanh(gate/beta) * sigmoid(gate)
  up_scaled = linear_beta * tanh(up/linear_beta)
with gate/up clamped to <=7 / [-7,7] before activation, matching the
a8w4 situv2 numerics exactly.

Thread situ_beta/situ_linear_beta through compile_flydsl_moe_stage1 and
flydsl_moe_stage1; the per-beta cache tag keeps distinct binaries.

Verified vs an inline torch SiTUv2 reference (mxfp4 dequant GEMM +
clamp + situv2): cos>=0.99996 across beta in {(1,1),(0.5,2),(1.5,0.8)},
shapes (512/256, 3072/256), tile_n {128,256}. silu/swiglu unchanged.

* Strip dead generic pipeline from a16w4 stage1 kernel (~2260 lines).

compile_mixed_moe_gemm1_a16w4 was created by copying the generic fp8/fp4
builder and gating with is_a16w4_stage1.  The live a16w4 path is fully
contained in `if const_expr(is_a16w4_stage1): ... return`; everything
after that return was an unreachable copy of the generic f8f6f4 kernel
body (referenced generic-only vars like _lds_tid_offset_pong / _pipe_*
that are never defined on the a16w4 path -- proven dead since a16w4
tests pass without them).

Remove the dead generic kernel body, the generic-only setup blocks
(postlude pipeline schedule, not-is_a16w4 guards), and the now-unused
setup vars.  Purely dead-code deletion: a16w4 stage1/stage2/e2e/situv2
+ a4w4 all still pass with identical cosine.

* Strip dead generic pipeline from a16w4 stage2 kernel (~1140 lines).

Same shape as the stage1 cleanup: compile_mixed_moe_gemm2_a16w4's live
a16w4 path is fully contained in `if const_expr(is_a16w4): ... return`
inside _moe_gemm2_then_body; everything after that return was an
unreachable copy of the generic f8f6f4 stage2 body (f8f6f4 MFMA,
generic-only scale layouts). Proven dead: a16w4 stage2/e2e/situv2 +
a4w4 all pass unchanged after removal.

Remove the dead body plus the now-unused generic setup vars
(pack_N/pack_K, cbsz/blgp, generic scale layouts, sx_rsrc sentinel,
etc.). Purely dead-code deletion.

* feat(moe): route a16w4 (bf16 x mxfp4) SiTUv2 through fused_moe

Wire the mixed_moe a16w4 kernel into the fused_moe 2-stage path for SiTUv2:
get_2stage_cfgs now matches bf16/fp16 x fp4 when activation is SiTUv2 (which
uniquely identifies the a16w4 kernel, so GPT-OSS / legacy bf16-Swiglu keep
their CK-Tile routing), maps _a_type to bf16/fp16, and infers q_dtype_a=bf16
for SiTUv2+separated so the activation stays bf16 (no fp4 quant). The stage1/
stage2 activation-quant gates also accept SiTUv2.

Tests: a16w4 SiTUv2 via fused_moe (cos=1.0 vs torch ref) and an a8w4 SiTUv2
inter=640 vec4 case exercising the fix-k non-256 K-tiling.

* feat(moe): support non-256 inter_dim for a16w4 (a8w4 parity)

Bring the FlyDSL a16w4 (bf16 x mxfp4) MoE kernels to a8w4 parity so
inter_dim need not be a multiple of 256 (e.g. DSV4 inter=640, and
arbitrary values like 384 via inter_dim_pad), across stage1/stage2/E2E.

Kernel (mixed_moe_gemm_2stage.py):
- stage2: allow inter_dim % tile_k == 0 (drop even-only rule), add
  odd_k_tiles 1-tile tail path, 256-pad scale reads (#3476).
- stage1: same odd_k_tiles K-loop + 256-padded w1 scale layout; fix gx
  launch grid (tile2_pad + full-N when inter_dim_pad > 0).

Caller (moe_kernels.py):
- pick/resolve_flydsl_stage1_tile_n: use tile_n=128 when inter%256!=0
  (fixes stage1 error on cols 0..inter%256 under tile_n=256).
- zero-init stage1 out when inter_dim_pad > 0.

Tests (test_flydsl_moe_a16wfp4.py):
- non-256 regressions (256/384/640) for stage1/stage2/E2E + pick_* tests.
- _generate_a16wfp4_data gains activation/situ_beta/situ_linear_beta.
- --perf sweep mode (correctness + latency/TFLOPs).

* test(moe): fold situv2 tests into dtype files, drop standalone situv2 file

Consolidate test_flydsl_moe_situv2.py into the per-dtype test files (matching
how test_flydsl_moe_a16wfp4.py already embeds its situv2 tests):

- test_flydsl_moe_a8w4.py: add the a8w4 SiTUv2 vec4 stage1 sweep + the
  host-only situv2 reference test; reuse the file's existing _check_close
  helper (fp32 cast for the bf16-ref vs f16-out case). Add shuffle_weight /
  e8m0_shuffle imports.
- Delete test_flydsl_moe_situv2.py. Its broken-under-pytest a4w4/a8w4
  main()-runner is dropped; a8w4 situv2 is now real parametrized coverage.

a16wfp4 situv2 tests already lived in their dtype file and are unchanged.

* fix conflict

* add timing args

---------

Co-authored-by: MHYang <[email protected]>
Co-authored-by: Clement Lin <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: mh <mh@local>

* fix(moe): a8w4 non-256 inter_dim stage1 tile_n + situv2 E2E regression tests

Squashed fix + tests (PR#3 commits 50729303, 2f33bd40, 1f0c6485, 46e3e056).

flydsl_moe_stage1 only downgraded tile_n (256->128) for non-256-aligned
inter_dim on a16w4 (bf16 x mxfp4); a8w4 (fp8 x mxfp4) kept tile_n=256, which
in separated gate_mode over-runs the gate/up (N) axis for non-256 inter_dim:
~30% wrong E2E output or GPU memfault at inter=384/640. Extend the resolve to
a8w4 (b_dtype fp4/mxfp4, a_dtype in {bf16,fp8}); a4w4 untouched. Callers keep
passing tile_n=256; the kernel resolves internally.

Tests (numeric vs torch reference, no-pad path, 128-multiple inter_dim):
- test_flydsl_e2e_a8w4_situv2 (separated, the production/customer path)
- test_flydsl_e2e_a16wfp4_situv2 (separated + interleave)
- test_flydsl_e2e_a8w4_gui extended to inter=256/384/640 (interleave, swiglu)

Verified on gfx950 (full rebuild): a8w4 20 / a16wfp4 27 / a4w4 4 passed;
ruff + black clean.

* refactor(moe): observable non-256 tile downgrade + a8w4 interleave situv2 E2E

Squashed (PR#3 c827ddbb + d381aae7).

- resolve_flydsl_stage1_tile_n / resolve_flydsl_stage2_tile_k: keep the silent
  auto-downgrade of a non-dividing tile (256->128) for non-256 inter_dim, but
  make it observable -- full docstrings noting tile=256 is NOT tunable for such
  shapes, plus a one-time (deduped) logger.warning on override.
- test_flydsl_e2e_a8w4_situv2: enable interleave (a16w4-style shuffle_weight_a16w4
  recipe) alongside separated, over 128-multiple inter_dim. Verified all
  activations (silu/swiglu/situv2) x both gate_modes x non-256 give E2E 0.0000.

* Add interleave_gate_up_rows + moe_shuffle_weight to ops/shuffle.py

Needed by atom-k3 (rocm/atom HEAD imports them from aiter.ops.shuffle);
ported verbatim from aiter main. Keeps the single aiter-k3 branch usable
by vllm-k3, sglang-k3 and atom-k3.

* [kimi-K3] extend conv2d support to gfx1250

* [Kimi-K3] pin _MIN_FLYDSL_VERSION to 0.2.2 (K3 MoE kernels need loc= API removed in 0.2.4)

* [Kimi-K3] fix MoE A16W4 for flydsl 0.2.4 and bump _MIN_FLYDSL_VERSION

flydsl 0.2.4 removed the loc= parameter from rocdl._split_mfma_operands.
The A16W4 BF16 K32 MFMA helper in mixed_moe_gemm_2stage.py called it as
_split_mfma(operands, loc=loc), which raises TypeError under 0.2.4.

Drop loc= from both (identical) helper sites; _split_mfma_operands only
unwraps operand Values and reads int flags, so it never needed loc. The
loc/ip are still threaded to the real op builder (_mfma_k32_raw), so
location tracking is preserved.

Bump _MIN_FLYDSL_VERSION to 0.2.4 and drop the now-stale 0.2.2 pin note.

Verified on gfx950 with flydsl 0.2.4 via test_flydsl_moe_a16wfp4.py
(stage1, stage2, e2e all pass, cos>=0.99999).

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

* [Kimi-K3] add fmoe tuned config

* [Kimi-K3] add bf16 dense GEMM tuned config

* [Kimi-K3] extend a16w4 fmoe tuned config inter_dim=384

* fix(kimi-k3): support A4W4 SiTUv2 on gfx950 and gfx1250

Keep Kimi-K3 SiTUv2 on the A4W4 FlyDSL path, add gfx1250 grouped-MoE activation and stability support, preserve ATOM's legacy A4W4 call, and cover the gfx1250 path with focused tests.

Co-authored-by: Cursor <[email protected]>

* [Kimi-K3] fix flydsl aot build failed

* Gluon reduce guard

* add a8w4 fmoe tune config

* Enable a8w4 SiTUv2 MoE via AITER_SITUV2_A8W4

Signed-off-by: Hongxia Yang <[email protected]>

* Support row-strided inputs in grouped TopK

* chore(gfx1250): drop CK enable patch — not needed for Kimi-K3

patches/ck_gfx1250_enable.patch only served to build native CK kernels
(quant/cache/rmsnorm/moe/sample/custom_all_reduce) on gfx1250. Verified that
with ENABLE_CK=0 (no patch, triton/hip fallbacks) Kimi-K3 serves correctly on
gfx1250 x4 (tp4): full gsm8k 1319 = 0.956 flexible/strict, vs 0.9613 with the
patched native-CK path — within stderr (+/-0.0056). Dropping the patch keeps
cleanup/k3-minimal minimal for merge into k3-for-amd; gfx1250 runs ENABLE_CK=0
(cost: ~13% decode vs native CK, no accuracy loss).

* chore(gfx1250): drop unified_attention Gluon guard — K3 doesn't use it

Kimi-K3 runs full-attn via MLAAttention (MLA-latent) and KDA via fla, so it never
dispatches to unified_attention (verified 0 calls across a full gsm8k run). The
non-power-of-two head_size / Gluon-reduce guards were added for K3's old
MHA-via-unified_attention path, which ATOM has now removed. Reverting
unified_attention.py to k3-for-amd keeps cleanup/k3-minimal focused on what K3
actually needs. Full gsm8k 1319 with this + the dropped CK patch = 0.955.

* Support row-strided inputs in grouped TopK opt-sort

* rm test_flydsl_moe_situv2.py: SiTUv2 coverage lives in test_flydsl_moe_a8w4.py

Per PR #6 review: the SiTUv2 stage1 variants (a4w4/a8w4) are already covered
by test_flydsl_moe_a8w4.py (cases were migrated there), so drop the
standalone file.

* test: fold row-strided biased_grouped_topk case into test_moeTopkSoftmax.py

Per PR review: stride is a simple feature — extend the existing
test_biased_grouped_topk with a dense-vs-strided equality check
(gating_output copied into a padded, non-contiguous row-strided view)
instead of a dedicated test file. Removes
op_tests/test_biased_grouped_topk_strided.py.

Verified on gfx950: topk_ids/topk_weights [dense vs strided] pass.

* test: simplify strided coverage — make gating_output itself row-strided

Instead of a separate dense-vs-strided check block, create gating_output
as a non-contiguous row-strided view (slice of a padded backing buffer) so
the existing biased_grouped_topk_hip checks exercise the strided path
directly. moe_fused_gate still gets a dense copy (it does not accept
strided input). The randn stream is kept identical to the dense layout so
later tests in the file see the same random inputs.

Verified on gfx950: full file run, zero failures.

* test: add K3 row-strided biased_grouped_topk case in main

Per review discussion: keep test_biased_grouped_topk's dense default
unchanged; the function now accepts an optional gating_output, and main
gains one case passing the K3 fused MoE-front router layout — logits as a
non-contiguous row-strided slice of the fused [gate_up|experts|routed]
buffer (896 experts, topk=16). The dedicated strided test file stays
removed.

Verified on gfx950: full file run, zero failures (err_aiter = 0).

* style: apply black formatting to gfx1250 flydsl files

Match the repo's pre-checks CI (black via psf/black@stable, ruff check):
reformat grouped_moe_gfx1250.py, gemm_mxscale_gfx1250.py and
moe_grouped_gemm_mxscale_gfx1250.py. Ruff reports no issues on the
branch. No functional change.

* add gfx1250 bf16 tuned config

* [Kimi-K3] fix ruff findings reported by the CI style check

The pre-checks ruff job installs ruff unpinned (`pip3 install ruff`) and the
repo carries no ruff config, so the enforced rule set follows ruff's defaults.
ruff 0.16.0 widened those defaults well beyond E4/E7/E9/F, which is what this
branch tripped over. Fix the 41 findings reviewdog flagged inside the PR diff:

- silu_and_mul_fq.py (B023): bind the per-iteration SSA values as default args
  in _fmin / _sigmoid_s / _situv2_elem. The closures are deliberately redefined
  per unrolled iter_idx because the arith.constant ops must be emitted at the
  current insertion point, so hoisting them out of the loop is not an option.
- moe_kernels.py: narrow the logger-import guard to ImportError (BLE001) and
  switch the flagged annotations to PEP 604 / builtin generics (UP006, UP045).
- flydsl moe tests + test_moe_2stage.py: sort the import blocks (I001), drop
  the now-unused `# noqa: E402` markers (RUF100), rewrite dict() calls as
  literals (C408), and mark the sweep-runner blanket catches with an explicit
  `# noqa: BLE001` plus the reason they are intentional.

Only findings inside the PR diff are addressed; pre-existing findings elsewhere
in the same files are left alone. black --check stays clean.

* [Kimi-K3] fix the second batch of ruff findings from the CI style check

reviewdog only posts a bounded number of results per run, so resolving the
first 41 findings surfaced a second batch of 27 that were in the PR diff all
along. Same root cause (unpinned ruff + no repo ruff config, 0.16.0 defaults).

- fused_moe.py / grouped_moe_gfx1250.py / moe_grouped_gemm_mxscale_gfx1250.py
  (UP045): PEP 604 annotations. Converted whole parameter runs rather than the
  individual flagged lines, because fixing one line pulls its neighbours into
  the diff hunk and the findings cascade.
- mfma_preshuffle_pipeline.py: drop the quotes from the ir.Value/ir.Type
  annotations (UP037) and sort __all__ (RUF022).
- mixed_moe_gemm_2stage.py: sort the import blocks (I001), functools.cache for
  the maxsize=None caches (UP033), inline the directly-called lambda in
  out_mlir (PLC3002), merge the nested bf16-atomics guard (SIM102), and
  underscore-prefix the unpacked values that are never read (RUF059) -- the
  decode calls are kept since they emit IR.

All rewrites are behaviour-preserving; black --check stays clean and the import
name sets are unchanged. Findings outside the PR diff are still left alone.

---------

Signed-off-by: Hongxia Yang <[email protected]>
Co-authored-by: billishyahao <[email protected]>
Co-authored-by: MHYang <[email protected]>
Co-authored-by: Clement Lin <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: billishyahao <[email protected]>
Co-authored-by: mh <mh@local>
Co-authored-by: Dewei Wang <[email protected]>
Co-authored-by: Felix Li <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Felix Li <[email protected]>
Co-authored-by: XiaobingSuper <[email protected]>
Co-authored-by: root <[email protected]>
Co-authored-by: Hongxia Yang <[email protected]>
Co-authored-by: RolaoDenthu <[email protected]>
Co-authored-by: zejunchen-zejun <[email protected]>
Co-authored-by: Lingpeng Jin <[email protected]>
johannes-graner added a commit that referenced this pull request Aug 27, 2026
…iew #5)

Express the Q/O-row, split-K workspace, and flat->(n_kv,d) shuffled/linear KV
decompositions via FlyDSL layout algebra instead of raw //,% arithmetic, on the
static-shape within-tile ownership sites the authoring skill prescribes it for.
Semantics-preserving: crd2idx/idx2crd recomputed bit-for-bit against the prior
formulas, Int64 coords pinned at every 64-bit (2 GB KV-pool/workspace) site to
avoid Int32 overflow. Hardware/ABI-bound maps stay raw (per-page BufferDesc
rebasing, measured MFMA-operand lane maps, the bank-conflict rotation). Full
flydsl attention suite 129 passed / 1 skip, identical per-file to baseline;
reviewed opus/high, approved.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
azaidy pushed a commit that referenced this pull request Nov 30, 2026
* Vendor the gfx950 fp8 attention kernel from FlyDSL v0.3.0

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]>

* Make the BN128 pipeline shape selectable independently of varlen/split-K

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]>

* Add the missing active guard; fp8 varlen now correct

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]>

* Add paged KV to the fp8 attention kernel

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]>

* Add fp8 split-K to the attention kernel

Store per-partial max/sum and O, then combine 2+ partials. The combine
rescales m_row into shared combine units before reduction.

* Add an opt-in prefetch bound; record why small-M tuning stopped here

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]>

* Spread the PV MFMA cluster with a scheduling hint

_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]>

* Narrow the second prologue drain to lgkmcnt(0) + vmcnt(4)

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]>

* Decompose the fp8 main loop into 8 clusters

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]>

* Pack the GQA group into M so one kernel serves prefill and decode

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]>

* Record the measured LDS ceiling: 2 WG/CU is unreachable

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]>

* Wire FlyDSL fp8 unified attention into the public dispatch path

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]>

* Widen fp8 unified attention: non-causal, fp16 output, sinks

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]>

* Enable packed-M + split-K decode (the Triton-3d analog)

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]>

* Auto-dispatch split-K on decode-only batches

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]>

* Extend split-K dispatch to low-chunk mixed batches

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]>

* Drop the ~29us dispatch host sync on the common paths

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]>

* Add fp8 unified-attention correctness gates to op_tests

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]>

* Apply code-review fixes

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.

* Format with black and clear ruff findings

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]>

* Address review batch 2: comment/doc fixes

- 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]>

* Address review batch 2: code refactors (behavior-preserving)

- _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]>

* Address review batch 2 (G1): dedupe test helpers into _common.py

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]>

* Address review batch 2 (U74): reword split-count cap comment

>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]>

* Raise split-count cap to 16, env-configurable

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]>

* docs: add Environment variables section with AITER_UNIFIED_ATTN_MAX_KV_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]>

* Compress verbose comments across the PR

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]>

* Fix int32 KV overflow and two Copilot review findings

Pass K/V to the fp8 kernel as a rank-2 [num_blocks, page_row] view instead
of a flat reshape(-1). FlyDSL's C-ABI codec packs every memref shape dim as
signed int32 (only strides may be int64), so a flattened KV pool of >= 2**31
elements (e.g. num_blocks=32768, block_size=64, 8 kv-heads, head_dim=128 fp8
= exactly 2**31 bytes) overflowed the shape field and raised struct.error at
launch, crashing the upstream test_triton_unified_attn on gfx950. The kernel
only takes K/V's base pointer (paged rebases per page, dense num_records is a
scalar), so the shape is unused -- keeping num_blocks as its own int32 dim
removes the overflow with no addressing or perf change.

Guard the gfx950 FlyDSL import in unified_attention() with try/except
ImportError: the adapter's is_flydsl_available() gate can only run after the
module imports, so without FlyDSL installed the import itself raised instead
of falling back to Triton.

Derive the split-K fill target from q.device at call time (@cache keyed on
device index) instead of once at import from the then-current device, which
mis-selected split-K in multi-GPU processes.

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

* WIP: shuffled 5D fp8 KV-cache support for FlyDSL unified attention (SILOTIGER-877)

Local checkpoint (not pushed, pending PR review). Implements shuffled-cache
support across the unified attention dispatch:
- K-side vectorized load (address-only, no sigma) in load_k
- V-side coalesced token-major staging (_stage_v_fp8_coalesced) + transpose-in-
  read, behind _V_LDS_COALESCED (scatter fallback retained)
- KV_VECTORIZED/KV_VEC_SIZE traits + cache_tag; kv_cache_layout builder param
- _dispatch_mode_ok accepts shuffled; _strides_ok requires flag<->5D agreement;
  stride_kv_n descriptor sizing fixed for 5D
- op_tests updated for the gate/signature changes

Correctness: 24/24 shuffled+linear matrix, standing suites 19/19, 26/26, 23/23.
Perf vs Triton-shuffled: prefill ~1.06x, decode 1.24-1.50x, total attention
+12.6% on the test-trace composition; mixed regime is a net loss (dispatch-split
is the planned next step). Full record in the vault issue
shuffled-cache-support-investigation.md.

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

* WIP: mixed-batch dispatch split for unified attention

Partition a clean two-block mixed batch (prefill seqs contiguous, decode
seqs contiguous) and route each half to its own recursive
flydsl_unified_attention call: prefill -> single-pass 2d, decode -> split-K
3d. Both halves are zero-copy view slices of q/out (descales are scalar and
shared, so nothing is gathered); the two calls write disjoint output rows in
place. Interleaved or pure batches decline to the single call (unchanged).

Fixes the mixed-batch loss where one num_kv_splits is picked for the whole
launch: at deep decode context the single call denied the decodes split-K,
so the split flips small-chunk/deep-ctx 0.63x->1.15x vs Triton and
large-chunk/deep-ctx 0.96x->1.02-1.07x. Correctness validated on 8 mixed
shapes (torch ref cos>0.999, split-vs-single parity ~1.0); standing matrix
24/24.

Ungated: at shallow decode context (4096) the two-launch overhead makes the
split a ~5-9% net loss vs single-call, so a decode-context-depth gate is
still TODO (crossover between ctx=4096 and 16384, needs a finer sweep).
AITER_UA_DISPATCH_SPLIT=0 disables.

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

* Gate mixed-batch dispatch split on decode-context depth; drop env var

Take the split only when the decode half's max KV depth >= _SPLIT_MIN_DECODE_KV
(6144). Below that the decode half's split-K does not amortize the split's
two-launch + partition overhead, so the ungated split regressed vs the single
call (chunk=256 was 0.87x at ctx=4096). Threshold from a gfx950 ctx sweep at
chunks 256/512/4023: the crossover is chunk-independent and lands in (5632,
6144]; at/above 6144 every sampled chunk wins (1.01-1.93x over single-call).

_partition_mixed now also returns the decode-half max KV; the guard adds a
cheap host-scalar pre-check (max_seqlen_k >= threshold) so shallow batches skip
the device partition entirely, and checks the exact decode depth only when a
deep decode is possible. Removes the AITER_UA_DISPATCH_SPLIT env var and
_dispatch_split_enabled -- behavior is now fully determined by input shape,
matching this module's no-dispatch-env-var stance.

Validated on gfx950: gate fires at ctx>=6144 and declines below across chunks
256/512/4023; 15/15 correct vs torch ref; standing matrix 24/24. Known residual:
a large-chunk + shallow-decode mixed batch passes the max_seqlen_k pre-check on
the prefill's depth, pays the partition probe, then declines -- a ~3-10% cost in
that narrow regime (no host scalar isolates decode depth without the probe).

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

* Memoize dispatch-split declines to remove the residual probe cost

A large-chunk + shallow-decode mixed batch satisfies the host-scalar
pre-check (max_seqlen_k reflects the deep prefill KV) but declines the split
on the true, shallow decode depth -- paying _partition_mixed's ~29us device
sync only to decline. That batch recurs identically on every decoder layer,
so the probe was re-paid per layer (the ~3-10% residual on that regime).

Memoize declined signatures on a host-only key (the two metadata data_ptrs
plus shape scalars); a later identical batch skips the probe and goes
straight to the single call. Only declines are memoized -- a decline falls
through to the single unified call, correct for any composition, so a stale
hit costs at most a missed split, never wrong output; a take re-slices on
the probed split_point and must re-probe, so takes are never memoized.
Recorded only for the clean two-block shallow-decode case, so the taken
split's ephemeral sliced sub-batches don't pollute the memo. Bounded LRU.

Validated on gfx950: scripts/test_dispatch_split_memo.py -- residual probes
once over 4 identical calls (was 4), take re-probes every call, no
cross-signature contamination, output bit-identical to a fresh probe and
correct vs torch ref. Standing gates unperturbed: stage4 matrix all-pass
(shuffled+linear), split-K 0 bad rows, pytest 42 passed.

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

* Cede underfilled mixed-shallow batches to Triton (return None)

The mixed small-chunk shallow-decode regime loses 0.4-0.6x to Triton: FlyDSL
builds one BLOCK_M=256 tile and launches a dense grid, so a small-chunk mix
leaves the machine underfilled (real WGs < CU count; resident waves 20.2 vs
53.3 at a filling chunk). Root cause is dispatch-level underfill, not the
shuffled-V transpose (refuted by flat LDS-wait across chunk sizes). A finer
FlyDSL tile does not recover it -- num_waves=4 doubles WGs but halves per-CU
SIMD utilization (dualwave stagger), a wash even on a perfect build; the
num_waves=8 V-staging weld and the const_expr-only tile shape make it a second
JIT binary regardless.

So cede exactly that regime to Triton, which tiles finer (BLOCK_M 128/16) to
fill the machine. Gate on the already-computed underfill signal
(num_2d_prgms < target_num_prgms) at zero added sync: return None for a mixed
single-call batch (max_seqlen_q > 1 and num_seqs > 1). Excludes all-decode
(won via split-K) and single-seq prefill (won), which also underfill but are
not losses; deep-decode mixed already took the dispatch split upstream. The
signal separates measured losses (num_2d 60-156) from fills (>=284) cleanly at
the 256-CU boundary.

Validated on gfx950: scripts/test_dispatch_underfill_fallback.py -- the loss
regime routes to Triton, all-decode/single-seq/deep-mixed/high-chunk-mixed all
stay on FlyDSL, every output correct vs torch ref. Standing gates unperturbed:
stage4 matrix all-pass, split-K 0 bad rows, decline-memo pass, pytest 42
passed.

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

* Apply code-review-3 fixes: split-prefill cede, dead V-staging removal, comment trim

Address the three actioned findings from code-review-3 (SILOTIGER-877).

Correctness (Must-fix 1): the mixed-batch dispatch split discarded the prefill
sub-call's return, so a prefill half that underfilled and returned None left its
output rows unwritten -- the split has no Triton fall-through, only the external
caller does. _sub now returns the call result and the parent cedes the whole
batch to Triton (return None) when the prefill half declines. Prefill is issued
first and the halves write disjoint rows, so a decline means nothing was written
and decode has not run; the decode half (max_q == 1) never declines, so one
check suffices.

Dead code (Should-fix 3): remove the byte-scatter V-staging A/B variant and the
dead non-DMA V store path from flash_attn_dualwave_common.py (net -192 lines):
_stage_v_fp8_scatter, the orphaned _V_LDS_TOKEN_SWAP table, the _V_LDS_COALESCED
toggle, the _stage_v_fp8_vectorized dispatcher, and the dead _stage_v_fp8_block
body. load_v calls _stage_v_fp8_block_dma directly and its vectorized branch
calls _stage_v_fp8_coalesced directly. The VDMA trait (a JIT-key member) and the
live 4D-linear tr8 reader are unchanged.

Comments (Should-fix 4): strip vault-internal stage/status/investigation
narration and trim verbosity across the three files, keeping the layout-spec,
addressing/OOB, and tier-selection rationale.

The fix-1 path has no committed test yet; validated statically (py_compile,
grep, wiring inspection) and behaviorally via the shuffled benchmark run
(shallow-mixed served=NO). Performance unchanged.

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

* Widen 0-dim scalar fp8 descales to [1] in the FlyDSL attention adapter

vLLM passes per-tensor q/k/v descales as 0-dim scalar tensors (shape ()).
FlyDSL's from_dlpack rejects those -- a scalar has no stride-1 axis to
auto-mark layout-dynamic -- so the kernel launch raised RuntimeError. Normalize
to a 1-element 1-D view before the dispatch gate, the mixed-batch recursion, and
the kernel see them. reshape on a 0-dim tensor is a view, numel is unchanged so
_descales_ok still passes, and _scaled_q_descale's elementwise multiply stays
shape-correct. None and already-1-D descales pass through untouched.

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

* Cede the losing high-batch/deep-context pure-decode region to Triton

Pure-decode FlyDSL is prefill-tuned: for GQA decode (query_len=1, 16:1) a
BLOCK_M=256 tile has 16 live M-rows, and the wasted per-tile compute is exposed
at 1 WG/CU (the 97 KB BLOCK_N-based LDS ring pins occupancy). Above a fixed
KV-read-volume quantum this loses ~2x to Triton and split-K does not recover it
(monotonic-worse at full fill). A gfx950 A/B grid (SILOTIGER-877) places the
boundary cleanly: every winning cell has num_seqs*max_seqlen_k <= 65536, every
losing cell >= 98304.

Return None (-> Triton) for top-level pure decode above _DECODE_CEDE_WORK=65536,
guarded on max_seqlen_k > 1280 so the always-winning shallow region stays on
FlyDSL regardless of batch. Scoped to the top-level entry via _from_split: the
mixed-batch split's _sub closure drops the decode sub-call's return value on a
"never declines" invariant, so a decode half reached through the split must not
cede (would silently leave output rows unwritten). Adds regression tests for
both the cede threshold and the mixed-split invariant.

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

* Add FlyDSL fp8 decode-specialized kernel (BLOCK_M=16 GQA-group, gfx950)

Decode-specialized attention kernel for the SILOTIGER-877 ceded region
(high-batch/deep-context decode the prefill-tuned body loses to Triton).

- BLOCK_M=16 GQA-group MFMA (mfma_16x16x32_f8), native fp8, per-tensor
  descale folded as scalars; QK C-output -> PV operand via register-side
  ds_bpermute repack (no LDS round-trip).
- Multi-wave cooperative workgroup: N waves split the KV loop, on-chip
  LDS LSE combine; async global->LDS DMA (buffer_load...lds); register
  V-prefetch (5D-shuffled V is already in operand order).
- Paged 5D-shuffled + linear cache, varlen, causal, bf16/fp16 output.

Verified stable checkpoint: correctness 14/14 (all-1s/distinct/random x
linear/shuffled x bf16/fp16, 0 bad rows, cos>0.99) on a cold cache, and
b=64 at-or-above Triton (1.15x ctx=4096, 1.01x ctx=16384).

WIP before Stage 3 split-KV; not yet wired into the unified_attention
dispatch.

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

* Add fill-aware split-KV to FlyDSL fp8 decode kernel

Fills the underfilled low-batch / deep-context decode regime the
single-pass (Stage 2) path lost to Triton, by adding an inter-workgroup
KV split on top of the multi-wave cooperative workgroup.

- Split S on grid.z: each (batch, kv-head, split) workgroup runs its KV
  sub-range with the NW=8 cooperative waves + intra-workgroup LDS combine
  and writes an unnormalized partial (m, l, O) to a global workspace.
- A separate decode combine kernel LSE-merges the S partials (global max
  -> rescale by exp2(m_s - m_global) -> sum -> /l). Plain global-memory
  reduction (CDNA4 has no workgroup clusters). Shared split-K combine
  helper left untouched; prefill stays bit-identical.
- Host S-plan: S = clamp(ceil(256 / (batch*H_kv)), 1, s_max, npages)
  (b8->8, b16->4, b32->2, b64->1). S=1 keeps the Stage-2 direct path,
  so b=64 is byte-unchanged. Measured optimum is 1 WG/CU fill.

Verified cold-cache: correctness 162 PASS / 0 FAIL (split-K sweep
S in {1,2,4,8}, distinct-mode cross-split combine, b=64 unregressed,
linear/shuffled x bf16/f16, isolation bit-identical). Performance:
6/8 grid cells >= Triton (b8/ctx16384 0.32->1.09x, b16/ctx16384
0.40->0.96x, b32/ctx16384 0.62->0.94x; b=64 1.15x/1.01x unchanged);
two residuals (b16/b32 at ctx16384, 0.94-0.96x) within ~5%.

WIP before Stage 4: not yet wired into the unified_attention dispatch.

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

* Integrate FlyDSL fp8 decode kernel into unified_attention dispatch

Wire the decode-specialized kernel (Stages 0-3) into the public
unified_attention() entry point and make it production-pool-safe.

- Centralized decode dispatch: one _decode_dispatch_action gate returns
  route / cede / legacy, with named tunable thresholds
  (_DECODE_CEDE_MIN_SEQS=9, _MAX_SEQS=48, _MIN_KV=8192) and an
  AITER_DECODE_KERNEL toggle, all in one place for retuning. Decode
  (query_len=1, GQA-16:1 fp8, no sinks/window/softcap) routes to the new
  kernel; a conservative mid-batch x deep-context band
  (9<=num_seqs<=48 AND max_seqlen_k>=8192) cedes to Triton; else legacy.
  from_split never cedes -- a split-reached decode half must always serve
  (the split discards sub-call returns).
- Per-page buffer rebasing (prefill's _make_page_view) for the K DMA and
  the V operand load, so the 2 GB production KV pool (65536 blocks) no
  longer overflows the int32 memref shape and faults. K/V are now plain
  pointers; any pool size works. Compute core unchanged.
- _get_decode_kernel lru_cache + the builder cache_tag keep the decode
  JIT binary from aliasing the prefill body or a different split count.
- Prefill/mixed/chunked untouched (branch gated on max_seqlen_q==1);
  prefill is bit-identical with the flag off.

Certified cold-cache: test_stage4_matrix ALL PASSED (24 shuffled+linear
cases); pytest test_unified_attention_flydsl + test_fp8_paged 44 passed,
0 failed, 0 skipped; decode correctness 209 PASS / 0 FAIL incl. 48
production-pool (2 GB) cases; live A/B through unified_attention() 6/8
grid cells >= Triton (b=64 1.05-1.21x), ~79-81% of the asm bandwidth
ceiling. Narrows the former decode cede (which ceded a region the new
kernel now wins) to only the measured mid-batch/deep-context loss band.

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

* Tidy fp8 decode kernel and dispatch: docstring, assert, dead code, comments

Post-review cleanup, no compute change (decode correctness bit-identical,
209/209 cold-cache).

- _route_decode_kernel docstring: describe the actual per-page BufferDesc
  rebasing instead of the false flat page_id*PAGE_REGION addressing claim.
- Assert K/V contiguity on the decode route (callers relied on it implicitly).
- Remove dead MAXFP8 constant and the inert KBUFS(=1)/cur_bufoff double-buffer
  scaffolding (every use was a x1 no-op or a plain alias of wave_kv).
- Note that causal rides the decode cache tag only for uniformity (it is
  constant at query_len=1).
- Strip internal ticket/phase/vault references from shipping code and error
  messages; keep the technical content and the generalization markers.
- Reword the packed+split-K note in the prefill body to name its true live
  consumers (single-seq GQA-prefill underfill split-K and non-16:1 GQA decode).

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

* Document linear vs shuffled decode KV layout tradeoff

Comment-only. The shuffled layout has V pre-transposed (direct global read, no
LDS V tile); the linear layout transpose-scatters V into LDS per page, which is
slower. Record that shuffled is the production/performance layout and linear is
the correctness/reference layout, and that vectorizing the linear V transpose is
deferred unless production is confirmed to serve a linear KV cache at scale.

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

* Consolidate FlyDSL attention correctness tests; drop decode dev script

Replace the standalone 209-case decode sweep with one parametrized correctness
test through the public flydsl_unified_attention() entry, validated against the
existing fp32 ref_paged_attn.

- test_correctness_all_modes: prefill/decode/mixed x {bf16,f16}, plus the three
  regression guards carried over from the removed sweep -- the 5D shuffled
  layout, a 2 GB production pool (65536 blocks, exercising per-page BufferDesc
  rebasing at high page ids), and a split-K-triggering ragged decode batch.
  For shuffled/padded cases the reference runs on the linear 4D pool while the
  kernel consumes a shuffled view of the SAME data, so one reference validates
  both layouts.
- Remove the subsumed per-axis sweeps (prefill context depth, decode batch,
  mixed); consolidate the softmax-scale tests; reduce gqa_ratios to 16:1 + 1:1.
- git rm scripts/test_stage1_decode.py (nothing under scripts/ ships).

Pre-existing paged/split-K/packed/cross/vendored suites and the routing gates
in test_unified_attention_flydsl.py are untouched.

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

* Dedup decode s_waitcnt helper; correct softmax-reduce sharing note

- Replace the byte-identical _waitcnt_vm_n copy in the decode kernel with an
  import of waitcnt_vm_n from flash_attn_dualwave_common (identical encoding:
  0xF / 0x3F70 / 0x3 / <<14). Decode-only change; prefill is untouched.
- Correct the softmax-reduce comment: decode's shuffle_xor{16,32} reduction over
  four lane-groups is NOT a rows_per_wave parameterization of the prefill body's
  _reduction_pair (32 in-register slots + one permlane32_swap over the 32-lane
  halves). Different input shape, primitive, and depth, so it stays decode-local
  rather than a shared helper. The deeper V-staging / split-K combine de-welding
  candidates remain deferred (high prefill-bit-identity risk, low ROI).

Decode/prefill/mixed correctness unchanged (20/20 cold-cache).

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

* Strip stale stage/ticket narration and dangling refs from decode files

Final comment sweep for the decode changeset: remove surviving SILOTIGER-877 /
Stage-4 narration and references to non-shipping dev-scratch files
(scripts/stage0_probe_*, scripts/test_stage1_decode.py, test_stage4_matrix.py)
from the decode kernel and test files. Comment/docstring only; no code change.

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

* Adapt fp8 wide MFMA call to FlyDSL 0.3.1 list-operand signature

FlyDSL 0.3.1 added a Python wrapper shadowing the raw ODS
mfma_scale_f32_32x32x64_f8f6f4 op: the signature became
(result_type, operands_list) returning .result, replacing the raw
10-positional-arg builder. Bundle the operands into a list and drop the
trailing .result, matching upstream flydsl flash_attn_utils.py.

Fixes 'takes 2 positional arguments but 10 were given' at kernel trace
time. Verified: test_flydsl_unified_attention.py 20 passed on gfx950.

* Modernize fp8 unified-attention kernels per flydsl-kernel-code-cleanup

Behavior-preserving cleanup of the gfx950 fp8 unified-attention kernels:
migrate fx.Index to explicit fx.Int32/fx.Int64 (Int64 for address, offset,
stride, workspace, and split/page indices; Int32 for bounded counters), drop
redundant ArithValue wraps, replace raw arith.cmpi/arith.constant with the fx
surface, and remove a dead import plus two unused dispatch parameters (intent
moved to docstrings).

Verified against the fp8 attention correctness suite on gfx950: 123 passed,
1 known-OOM skip, 0 failed.

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

* Tighten fp8 unified-attention tests per flydsl-kernel-testing

Hold the added FlyDSL fp8-attention tests to the correctness-test bar:
remove the source-grep test (test_q_descale_has_no_other_consumer), whose
invariant is already checked behaviorally by test_softmax_scale_actually_
changes_output; move the routing test into op_tests/flydsl_tests/ as
test_unified_attention_routing.py, where the oracle-correctness contract
applies, fixing its sys.path depth; and collapse the packed split-K decode
Cartesian product to distinct boundaries only (batch 7/8/9 -> a single
non-power-of-two 9, and drop the redundant even-split ctx/split axes),
keeping the ragged sweep that exercises real partial/empty fill regimes.

Full suite green on gfx950: 123 passed, 1 known-OOM skip, 0 failed.

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

* Address PR #4676 review: non-causal cede, empty-KV guard, env/device hardening

- Serve non-causal on FlyDSL instead of ceding into the causal-only Triton fallback; make the Triton guard a real raise so -O cannot strip it into a wrong-mask run
- Guard the decode epilogue den==0 (empty KV) in both the direct-store and split-K combine paths, matching the prefill _safe_l_inv pattern
- Parse AITER_DECODE_KERNEL defensively (bad value -> default) and document it in the README; key decode dummy/workspace tensors on q.device; check the mixed-split decode sub-call None return

Add regression tests in flydsl_tests: non-causal service inside the perf-cede bands (spied to confirm FlyDSL, not Triton), empty-KV finite output across both divide paths, defensive env parse, and shuffled-5D large-page-id coverage.

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

* Refactor static-shape index maps to make_layout/crd2idx (PR #4676 review #5)

Express the Q/O-row, split-K workspace, and flat->(n_kv,d) shuffled/linear KV
decompositions via FlyDSL layout algebra instead of raw //,% arithmetic, on the
static-shape within-tile ownership sites the authoring skill prescribes it for.
Semantics-preserving: crd2idx/idx2crd recomputed bit-for-bit against the prior
formulas, Int64 coords pinned at every 64-bit (2 GB KV-pool/workspace) site to
avoid Int32 overflow. Hardware/ABI-bound maps stay raw (per-page BufferDesc
rebasing, measured MFMA-operand lane maps, the bank-conflict rotation). Full
flydsl attention suite 129 passed / 1 skip, identical per-file to baseline;
reviewed opus/high, approved.

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

* Add FlyDSL unified-attention to AOT prebuild

Enroll the gfx950 fp8 unified-attention kernel family into aiter's
ahead-of-time build. The family has no tuning CSV, so it emits a fixed
80-variant cross-product (48 prefill + 32 decode) for the (64,4,128)
GQA-16 production config: causal, out dtype, shuffled/linear KV cache,
kv-splits, and prefill sinks. Each variant compiles compile-only under
FakeTensorMode via the runtime adapter's _get_kernel/_get_decode_kernel,
so AOT binaries key identically to dispatch lookups. A None-sentinel
guard in collect_aot_jobs lets a CSV-less family source jobs from
parse_csv directly.

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

* Address PR #4676 Copilot review: clarify MAX_KV_SPLITS scope, fix AOT type hints

- README: AITER_UNIFIED_ATTN_MAX_KV_SPLITS caps only the general/prefill-body
  _split_count path, not the decode-specialized kernel's plan_num_kv_splits.
- collect_aot_jobs: type csv_paths/parse_csv as str | None to match the
  None-sentinel contract for non-CSV families (DEFAULT_CSVS = [None]).

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

* Address PR #4676 Copilot review 2: dead branch, test assertion, mislabeled tests

- common.py: remove the unreachable second `elif OpKind.GROUPED_MOE` stub
  (the earlier branch imports the real grouped_moe.compile_one_config).
- test_vendored_fp8_attention: assert output finiteness on the largest shape
  before skipping (was executing the kernel with no assertion).
- test_unified_attention_routing: drop the over-defensive host-only
  env-parse test and correct the "no GPU needed" section headers -- the
  remaining predicate/cede tests build cuda tensors / launch the kernel and
  legitimately sit under the gfx950 arch skip.

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

* Sort imports in flydsl attention tests (ruff I001)

reduce.py CI pins ruff 0.16.0 whose default rules include I001 import
sorting; local 0.15.20 does not raise it. Reorder the six test import
blocks to satisfy the CI-pinned ruff.

* Fix FlyDSL unified-attention dispatch gates

C5: derive KV-cache layout from tensor rank so a 5D cache with the
default shuffled_kv_cache=False reaches the FlyDSL hook instead of
raising in the 4D unpack.
C4: reject padded block-table views (stride(0) must equal row width)
so a compacting reshape cannot desync from block_table_stride.
C2: require window_size==(-1,-1); decline right-bounded windows that
the kernel would silently ignore on a non-causal call.

* Relocate FlyDSL routing test to collected top-level op_tests

The aiter CI shard scans op_tests with find -maxdepth 1, so the nested
flydsl_tests/ file never ran in CI. Move it to top-level op_tests/ and
add a __main__ guard that self-invokes pytest, so the existing
python3 <file> runner executes it; the gfx950 skipif keeps it a clean
skip on the gfx942 shard. Repo-root sys.path insert fixes helper
imports under script-mode execution.

* Fix stale aiter.ops.flydsl.utils imports in flydsl_tests

utils.py was deleted by the main merge; is_flydsl_available now lives in
unified_attention_kernels. Repoint the six FlyDSL correctness tests so they
no longer ModuleNotFoundError at collection before their skip gates run.

* Confine FlyDSL unified-attention to full-chip gfx950; harden fallbacks

- Gate the FlyDSL adapter on actual per-device CU count: MI350P is gfx950
  with half the CUs, so decline (cede to Triton) below full chip rather
  than run a kernel whose decode planner assumes 256 CUs.
- Replace the -O-strippable `assert causal` Triton-fallback guard with an
  unconditional NotImplementedError.
- Pass the decode-half KV maximum through _partition_mixed instead of the
  global max_seqlen_k.
- Update/extend routing regression tests accordingly.

* docs: move unified-attention env vars out of main README

Move the AITER_UNIFIED_ATTN_MAX_KV_SPLITS and AITER_DECODE_KERNEL runtime
knobs from the top-level README into aiter/aot/flydsl/README.md, per PR
#4676 review (env vars do not belong on the main README).

* fix: resolve FlyDSL unified-attention arch per q.device

Select and build the FlyDSL fp8 unified_attention backend from the
tensor device architecture rather than an import-time/process-global
cache. Resolve gfx950 + full-chip CU count from q.device properties,
share one per-device result across explicit and automatic backend
selection, and enter the q.device context before the kernel builder
lookup so a gfx950 closure cannot be built for a gfx942 tensor.

PR #4676 review (per-device architecture resolution).

* test: consolidate unified-attention tests into one op-test file

Single top-level op_tests/test_unified_attention.py in AITER op-test
style (no pytest): prefill, decode, mixed, cross-attention mask, split-K
combine, paged permutation-invariance, backend-routing gate, and an AOT
cache-hit check, all vs an independent fp32 paged-attention oracle with
checkAllclose. PR #4676 review.

* test: remove unified-attention tests superseded by consolidation

Delete the routing pytest file and seven nested flydsl_tests modules
(plus _common.py); their coverage moved into the single top-level
op_tests/test_unified_attention.py. PR #4676 review.

* docs: document unified-attention runtime env vars in code, not markdown

Remove the runtime env-var table from aiter/aot/flydsl/README.md (that
file is for build-time AOT vars, and aiter documents runtime knobs
inline in code by convention) and make the AITER_DECODE_KERNEL helper
docstring self-sufficient. PR #4676 review.

* fix: address Copilot review on unified-attention

- guard optional FlyDSL import in the capability probe so backend="triton"
  and automatic dispatch fall through to Triton when FlyDSL is absent
- assert decode split count >= 1, mirroring the prefill builder, so a
  non-positive count is rejected instead of launching a zero-dim grid
- thread the configured KV-split cap (_MAX_SEGMENTS) into the decode
  planner so the documented default of 16 and the env override take
  effect on the decode path; add 16 to the AOT _DECODE_SPLITS prebuild set
- correct the AOT README: no --csv for the fixed unified-attention family,
  its hardcoded gfx950 target, and its missing command entry

* refactor: split unified-attention entry point into backend router

Address Sami's review: route through a neutral aiter/ops/unified_attention.py
that delegates to FlyDSL or Triton/Gluon, with the real FlyDSL entry at
aiter/ops/flydsl/unified_attention.py. Revert the Triton entry point to its
pre-PR state so no Triton source changes ship. Reuse the shared
is_flydsl_available helper. Relax the gfx950 gate to the arch alone and thread
the real device CU count into the decode split planner so fewer-CU parts
(MI350P) work. Make PR comments terse.

* [FlyDSL] Unified-attention benchmarks and decode-only prototype revert

- bench scripts: gluon baseline, triton-anchored calibration, ceded shapes
- CUDA-graph kernel-only decode benchmark
- decode-only dispatch change and its revert

* [FlyDSL] Prototype fp8 prefill variants and benchmarks

- fix fallback comparator after gfx950 Gluon default
- stage shuffled fp8 V into LDS, four-wave double-buffered prefill
- conventional prefill defaults, graph replay and marked-eager profiling

* [FlyDSL] Route unified-attention decode to pa_decode with fp8 Q

- prequantized FP8 queries in paged decode
- resident-workgroup-wave partitioning and VGPR occupancy guard
- remove custom FlyDSL decode kernel

* [FlyDSL] Add fmha_gfx950 ISA-identity gate and extract forward body

- ISA-identity gate script with serial reverify and flaky-job handling
- extract forward body for reuse (ISA-identical)

* [FlyDSL] Add paged, shuffled and f16 support to fmha_gfx950

- paged/shuffled/f16 traits and validation
- OUT_F16 store, linear paged KV, shuffled K and V

* [FlyDSL] Route unified-attention prefill through the main FMHA builder

- sinks declined in the gate; routing of underfilled causal prefill
- packed/conventional BN64 body variants, full-width shuffled V reader
- BN64 denominator reduction and V transpose fixes (reverts and reapplies collapsed)
- remove dual-wave fp8 prefill kernel; untrack local bench scripts

* [FlyDSL] Harden unified-attention routing and support gate

- exact-shape validation, decode-route split of mixed batches
- softmax_scale and i32 overflow guards
- normalize shuffled_kv_cache once; drop router empty-context repair
- host-sync-free mixed causal routing; AOT README decode JIT note

* [FlyDSL] Consolidate unified-attention tests

- share paged attention oracle and per_tensor_quant
- delete paged FMHA pytest suite, drop routing-gate tests

* [FlyDSL] Refactor and fix FlyDSL unified-attention kernels

- fix FMHA kv_page_div tail-tile underflow
- narrow import guard, drop unused fp8 builder surface
- per-device _num_cu, pa_decode-owned scratch
- share shuffled V reader and FMHA body context

* [FlyDSL] Harden validation, share KV shuffle, restructure fmha test

- validation hardening and oracle attribution
- shared KV shuffle, dead state removal, stale comment cleanup
- test_flydsl_fmha.py as benchmark sweep; all-zero rows as cosine matches

* Decline CPU inputs and rank-invalid V caches, document unified_attention

CPU q now declines to the fallback before any CUDA device is selected.
_shapes_ok validates V rank before indexing its shape. Add the
unified_attention docstring and a split_tests timing entry for the
unified attention test.

* Set measured CI weights for unified attention and FlyDSL FMHA tests

* Address FMHA review: license headers, const_expr, shared K helper

Add SPDX headers to unified_attention entrypoints (C48, C64). Compute
q_start once, gate on const_expr, share the shuffled-K address helper,
and justify unstable API uses (C50-C62). Refresh the decode work plan
once per captured graph. Restore pre-existing FMHA pytest cases (C65).

* Use stable FMHA barriers and bf16 packing, drop dead epilogue wait

Switch rocdl.s_barrier to fx.gpu.barrier with equivalent gfx950 ISA
(C49), pack bf16 through Vec.from_elements while keeping exact f16 RTZ
(C55), and remove an unused paged epilogue wait and barrier (C53).

* Tighten attention test gates and cover large-view and group-2 cases

Gate outputs by measured dtype bounds, cover explicit 256-row FMHA
tiles and group-2 GQA, and exercise page-local views beyond the signed
int32 byte limit.

* Skip dead BN64 prefetch, mask pa_decode V tail, refresh planner per call

Skip the dead last-iteration prefetch in the conventional BN64 body
(C51). Mask invalid V tail payload before PV in pa_decode and reduce
its register pressure. Record the planner refresh for every captured
call.

* Unify FlyDSL attention test harnesses and clarify docs

Inline FMHA contract tests into test_flydsl_fmha.py and unify the
pa_decode harness (match main). Clarify comments, AOT docs and the
unified attention contract; drop redundant sinks forwarding and
workspace key fields; simplify the paged addressing test.

* Use layout algebra in fmha_gfx950, keep raw lane swap with justification

Derive K/V operand ownership from the MFMA atom, use fx.Int64 block
indices (C56) and idx2crd for packed GQA rows (C58). shuffle_xor for
the lane exchange measured slower (C54), so the raw op stays with a
justification comment.

* Warn once when captured FlyDSL decode declines to Triton

* Migrate FlyDSL kernels to 0.4 APIs

* Fall back to Triton when FlyDSL is not installed

The backend router import…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants