Skip to content

[FlyDSL] gfx1201 (RDNA4) FlyDSL BF16 attention optimizations & FP8 attention implementation - #4188

Merged
coderfeli merged 50 commits into
ROCm:mainfrom
pds-amd:feat/flydsl-flash-attn-gfx1201-v9
Nov 2, 2026
Merged

coderfeli merged 50 commits into
ROCm:mainfrom
pds-amd:feat/flydsl-flash-attn-gfx1201-v9

Conversation

@pds-amd

@pds-amd pds-amd commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Diffusion attention is a significant RDNA4 (gfx1201) workload. This PR
modernizes the native FlyDSL flash-attention path and adds a native per-tensor
FP8 attention path for the same device.

What changed

BF16/F16 attention

  • Moves the gfx1201 implementation into kernels/fmha_gfx1201/ and keeps the
    public entry point as flydsl_flash_attn_func.
  • Supports BSHD inputs, independent non-causal Q/KV sequence lengths, exact
    tail masking for padded KV tiles, causal self-attention, BF16, and F16.
  • Adds validated softmax_scale, out, and optional launch-stream arguments.
  • Selects tiles from the shape and rejects launch configurations exceeding the
    gfx1201 LDS or buffer-index limits.

FP8 attention and quantization

  • Adds an FP8 E4M3 attention consumer with BF16 output. It takes
    pre-quantized BSHD Q/K/V plus one-element FP32 device descales.
  • Adds flydsl_fp8_quant, a native gfx1201-only BF16 Q/K/V producer. It
    performs per-tensor quantization and optionally applies an in-register FWHT
    to Q and K before quantization.
  • The native producer is intentionally not a general backend dispatcher:
    unsupported devices or input contracts fail with ValueError rather than
    silently selecting Triton or torch.
  • The FP8 consumer uses typed FlyDSL buffer views, copies, layouts, math, and
    WMMA APIs. The remaining low-level operations are confined to packed FP8
    conversion and packed-LDS boundaries. On pinned FlyDSL 0.3.4.1, the tested
    typed alternatives either do not lower or do not yet validate correctly.

Validation

The new gfx1201 coverage uses the repository’s canonical, architecture-dispatching
test entry points and executable aiter-op-test flow.

python op_tests/test_flydsl_fmha.py
python op_tests/test_flydsl_fp8_quant.py
python op_tests/op_benchmarks/flydsl/bench_fmha_gfx1201.py

The tests cover public API validation, BF16/F16 and FP8 numerical correctness,
causal and non-causal paths, cross-attention, KV tail masking, output-buffer
reuse, launch-stream behavior, the quantizer's fused-D64 and generic paths,
and its zero/input-device contracts.

The comparative benchmark covers Flux (1536 and 4096), Wan (8192 and 32768),
and SD3.5 (2048, D64). Each candidate is checked against an FP32 SDPA
reference.

@pds-amd
pds-amd requested a review from a team July 10, 2026 14:51
@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 4188 --add-label <label>

@pds-amd pds-amd changed the title gfx1201 (RDNA4) FlyDSL BD16 attention optimizations & FP8 attention implementation gfx1201 (RDNA4) FlyDSL BF16 attention optimizations & FP8 attention implementation Jul 11, 2026
@zufayu
zufayu requested a review from amd-ruitang3 July 13, 2026 01:37
@pds-amd
pds-amd force-pushed the feat/flydsl-flash-attn-gfx1201-v9 branch from e769109 to 0a94750 Compare July 22, 2026 11:10
Copilot AI lite review requested due to automatic review settings August 3, 2026 07:13
@pds-amd
pds-amd force-pushed the feat/flydsl-flash-attn-gfx1201-v9 branch from 0a94750 to 17c3853 Compare August 3, 2026 07:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR advances the gfx1201 (RDNA4) FlyDSL flash-attention stack by (1) improving the existing bf16/f16 path with shape-driven tiling plus broader sequence-length handling (including cross-attention and tail-masked padding), and (2) adding a new per-tensor FP8 (e4m3) attention path with a FlyDSL rotate+quantize producer.

Changes:

  • Add per-tensor FP8 attention (consumer kernel) and a fully-FlyDSL 2-pass per-tensor FP8 quantization kernel (with optional Hadamard/FWHT rotation for Q/K).
  • Update the bf16/f16 gfx1201 flash-attention kernel to support cross-attention and non-causal tail masking, plus shape-driven (BLOCK_M, BLOCK_N) selection via the Python wrapper.
  • Add/extend correctness + perf tests covering cross-attention, unaligned non-causal lengths, FP8 producer invariants, and perf benchmarking vs SDPA-FLASH.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
op_tests/test_flydsl_fmha.py New perf sweep/benchmark driver comparing SDPA-FLASH vs FlyDSL bf16 and FP8 paths, with correctness cross-checks.
op_tests/flydsl_tests/test_flydsl_fmha.py Expanded pytest correctness coverage for cross-attn, tail-masked padding, FP8 paths, and new wrapper extras (softmax_scale, out=).
aiter/ops/flydsl/kernels/fp8_quant_gfx1201.py New fully-FlyDSL per-tensor FP8 quantization (+ optional FWHT rotation) producer kernel (2-pass amax + scale).
aiter/ops/flydsl/kernels/flash_attn_func_gfx1201.py bf16/f16 kernel updates: cross-attn addressing, tail-mask support, and new seq-length args/plumbing.
aiter/ops/flydsl/kernels/flash_attn_func_fp8_gfx1201.py New FP8-input flash-attention consumer kernel (bf16 output) with per-tensor scales and tail-mask/cross-attn support.
aiter/ops/flydsl/fmha_kernels.py Public API updates: flydsl_flash_attn_func extras (softmax_scale/out/fp8 descales), dispatch to bf16 vs fp8 kernels, and new flydsl_fp8_quant producer.
aiter/ops/flydsl/init.py Export flydsl_fp8_quant alongside existing FlyDSL public APIs when FlyDSL is available.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
@pds-amd

pds-amd commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

@amd-ruitang3 a friendly nudge on this review.

@amd-ruitang3
amd-ruitang3 requested a review from coderfeli August 17, 2026 08:23
@coderfeli

Copy link
Copy Markdown
Collaborator

And use flydsl kernel clean up skill to clean the kernel code.

@coderfeli coderfeli left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

use flydsl kernel clean up skill to clean the kernel code.

Copilot AI review requested due to automatic review settings August 24, 2026 09:38
@pds-amd
pds-amd force-pushed the feat/flydsl-flash-attn-gfx1201-v9 branch from fa7d294 to b465df6 Compare August 24, 2026 09:38
@github-actions github-actions Bot changed the title gfx1201 (RDNA4) FlyDSL BF16 attention optimizations & FP8 attention implementation [FlyDSL] gfx1201 (RDNA4) FlyDSL BF16 attention optimizations & FP8 attention implementation Aug 24, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Copilot AI review requested due to automatic review settings August 24, 2026 10:09
@pds-amd
pds-amd force-pushed the feat/flydsl-flash-attn-gfx1201-v9 branch from b465df6 to ce6a916 Compare August 24, 2026 10:09
@pds-amd

pds-amd commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

use flydsl kernel clean up skill to clean the kernel code.

@coderfeli I applied the FlyDSL kernel cleanup guidance and rebased onto current main.

I kept typed LDS access in the BF16 and FP8 kernels as documented gfx1201 performance exceptions: the corresponding SharedAllocator pointer lowerings were over 2x and 3.7-5.1x slower, respectively, with FlyDSL 0.2.4. Both sites have PERF(gfx1201) comments. Validation on a 2x gfx1201 pod passes all 39 correctness tests, and the five-shape latency sweep matches or improves the previously reported performance within run-to-run variance.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved
Copilot AI review requested due to automatic review settings August 24, 2026 10:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Suppressed comments (3)

Previously missed (3) — in code that hasn't changed since the last review.

aiter/ops/flydsl/fmha_kernels.py:226

  • The docstring claims all backends keep rotated Q/K off HBM, but the torch fallback materializes the rotated tensors via torch.matmul (so it does round-trip through memory). This is a documentation/expectation mismatch for users comparing producer backends.
    the fused Triton passes; ``"torch"`` runs the reference. All three keep rotated
    Q/K off HBM (2 reads + 0.5 write). The FlyDSL path requires bf16 inputs,

aiter/ops/flydsl/kernels/flash_attn_func_gfx1201.py:6

  • This module docstring states BLOCK_N is fixed at 32, but this kernel is now built with a variable (BLOCK_M, BLOCK_N) selected by _pick_tiles (e.g., BLOCK_N can be 64). Updating the doc avoids misleading profiling/perf interpretations.
1. BLOCK_N=32 (reduced tile, fewer iterations, better occupancy).

aiter/ops/flydsl/kernels/flash_attn_func_fp8_gfx1201.py:14

  • The docstring describes BLOCK_N as fixed at 32, but build_flash_attn_func_module now accepts block_n and the wrapper can select BLOCK_N=64 for some shapes. Clarifying this helps keep the kernel documentation consistent with actual dispatch behavior.
1. BLOCK_N=32: fewer KV iterations and better occupancy than wider tiles.

Copilot AI review requested due to automatic review settings August 24, 2026 10:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pds-amd

pds-amd commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Overall please follow aiter/FlyDSL authoring guidelines and aiter-op-test for testing. This PR needs quite a bit of refactoring.

@samremes Thank you for the thorough review.

I went through each thread and refactored the implementation against the pinned FlyDSL 0.3.4.1 API, following the aiter/FlyDSL authoring and aiter-op-test patterns.

The remaining low-level operations are limited to the packed FP8 conversion and packed LDS boundaries. I used typed FlyDSL views, copies, layouts, math, and WMMA APIs everywhere else. I documented the specific 0.3.4.1 limitation and validation results next to each remaining boundary, and added detail in the individual thread responses.

I also ran a paired before/after benchmark on the same GPU. The material deltas are below; all numerical checks passed.

FlyDSL path Model / shape Before this refactor (µs) Current (µs) Change
BF16 Flux, 1536, D128 308.454 317.666 +3.0%
BF16 Flux, 4096, D128 2058.610 2173.490 +5.6%
BF16 Wan, 8192, D128 4082.140 4194.560 +2.8%
FP8, including quantization Flux, 1536, D128 338.010 372.914 +10.3%
FP8, including quantization Flux, 4096, D128 1872.550 1946.900 +4.0%
FP8, including quantization Wan, 8192, D128 3457.200 3526.860 +2.0%
FP8, including quantization Wan, 32768, D128 50970.900 54034.900 +6.0%
FP8, pre-quantized inputs Flux, 1536, D128 242.840 259.907 +7.0%
FP8, pre-quantized inputs Flux, 4096, D128 1521.950 1591.980 +4.6%
FP8, pre-quantized inputs Wan, 8192, D128 2981.090 3073.360 +3.1%

Please let me know if there is a preferred FlyDSL pattern for either remaining packed boundary.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Unresolved correctness, API contract, and test coverage issues remain, including BF16 tail-mask type compatibility and FP8 backend/scale validation.

Review effort: Lite
Findings: 1 High severity · 3 Medium severity

Open (4)

Comment thread aiter/ops/flydsl/fp8_quant.py Resolved
Comment thread op_tests/test_flydsl_fmha_gfx1201.py Resolved
Comment thread op_tests/test_flydsl_fp8_quant.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Critical kernel type and test failures, plus an incomplete FP8 dispatch contract, remain unresolved.

Review effort: Lite
Findings: 2 High severity · 3 Medium severity · 1 Low severity

Open (6)

Comment thread op_tests/test_flydsl_fmha_gfx1201.py Resolved
Comment thread aiter/ops/flydsl/fmha_kernels.py Resolved

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

Looks a lot better already. Some ideas for further simplicifation, not sure if all are feasible.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Critical kernel construction issues and missing input-contract and CI timing fixes remain.

Review effort: Lite
Findings: 2 High severity

Open (2)
Resolved since last review (6)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Add FILE_TIMES entry for the new test script

op_tests/​test_flydsl_fp8_quant.py:199

This new top-level test_*.py is discovered by split_tests.sh and executed directly by aiter_test.sh, but it has no FILE_TIMES entry. The sharder therefore assigns the 15-second fallback (.github/scripts/split_tests.sh:390-398) to a script that performs compilation, a two-stream contract check, and three benchmark sweeps, which can substantially underestimate shard load and create imbalanced CI shards. Please add a realistic timing entry for this test in split_tests.sh.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Address the quantizer’s oversized-buffer safety issue and the mixed-width tail-mask comparison.

Review effort: Lite
Findings: 1 High severity

Open (1)
Resolved since last review (2)

Comment thread aiter/ops/flydsl/fp8_quant.py Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Critical and moderate correctness, tracing, and test-coverage issues remain unresolved.

Review effort: Lite
Findings: 2 High severity

Open (2)
Resolved since last review (1)

Comment thread op_tests/test_flydsl_fmha.py Resolved
@pds-amd

pds-amd commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@samremes Thanks again for the helpful comments! I have reworked this PR against the pinned FlyDSL 0.3.4.1 API and responded on each thread.

The few remaining low-level operations are confined to packed-FP8/LDS boundaries where the equivalent typed representation does not currently compile or produced incorrect results in validation. I documented those boundaries and the attempted alternatives in the relevant code/comments.

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

Tested on R9700 (gfx1201) at 2aa286c with ROCm 7.2.3, torch 2.10, and FlyDSL 0.4.0 and 0.3.4.1. The three commands listed in the description pass. Checked against an fp32 math reference, these are correct: BF16/F16 tail masking, causal, cross-attn, large Wan shapes (up to [1,75600,40,128]), and out/stream handling. BF16 runs 1.07–1.10x faster than main on Wan14B and SD3.5 D64, and is about even on Flux and Wan1.3B.

Please fix before merge

  1. flydsl_fp8_quant silently corrupts data above 4 GiB. _validate_quant_dword_offsets limits the dword index to Int32, but the buffer voffset is in bytes, so it wraps once numel > 2^31. The scale comes out correct; the quantized values are read from the wrapped address.
    q = torch.ones(1,266240,64,128, dtype=torch.bfloat16, device='cuda'); q[:, -8192:] = 100
    k = v = torch.randn(1,128,64,128, dtype=torch.bfloat16, device='cuda')
    q8,_,_,sq,_,_ = flydsl_fp8_quant(q, k, v, rotation=False)
    print(sq.item(), q8[0,-1].float().unique())  # 0.2232, tensor([4.5]) -- expected 448
  2. BF16 regression vs main. The numel <= INT32_MAX check in fmha_kernels.py (~L145-156) also applies to BF16, and its message says "FP8 buffer-index". bf16 [16,32768,32,128] runs correctly on main and raises ValueError here.
  3. FP8: P is converted to e4m3 without scaling (flash_attn_func_fp8.py ~L287-298). Any p below ~2^-10 flushes to 0, but l still accumulates the fp32 p, so the result depends on where the row max lands. Repro: Q = e1; K row 0 = 0 and the other 4095 rows = -7.5·e1; V = 1; all descales and softmax_scale = 1. Output is 0.3066, expected 1.0. Moving the zero row to the end gives 0.996. On random inputs this shows up as about ±2% scale error per row. Suggested fix: scale P before the conversion and fold the inverse scale into inv_l, and/or accumulate l from the quantized P.
  4. Tests only assert cosine similarity, which does not change when a whole row is scaled, so neither (3) nor the BF16 bias below can be caught. Please add a max-abs check against an fp32 math reference, plus a V = ones -> output == 1.0 probe.

Minor

  • FP8 with q_descale = 0 produces an all-NaN output. Descales passed with BF16 inputs are silently ignored.
  • Needs a rebase: it conflicts with main in aiter/ops/flydsl/__init__.py and fmha_gfx1201/flash_attn_func.py. The description says FlyDSL 0.3.4.1, but requirements pin 0.4.0. The tests need tabulate, which is not in requirements.
  • VGPR spills: BF16/F16 at D=256, and FP8 at D=512 (710). Results are still correct.
  • flydsl_fp8_quant raises IndexError instead of ValueError on 2D input.
  • Pre-existing, also on main: BF16 truncates P to bf16 (flash_attn_func.py ~L302-311) while l uses the fp32 p, so V = ones gives 0.99609375. The F16 path uses RNE and gives exactly 1.0.

…ttn-gfx1201-v9

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

# Conflicts:
#	aiter/ops/flydsl/__init__.py
#	aiter/ops/flydsl/kernels/fmha_gfx1201/flash_attn_func.py
@pds-amd

pds-amd commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@vivienfanghuagood

Thanks for the detailed review.

I checked your finding and validated the fixes on gfx1201.

Addressed:

  • Corrected FP8 quantizer validation to enforce the V# byte-extent limit.
  • Restricted flattened Int32 limits to the FP8 path; large BF16/F16 batches remain valid.
  • Preserved ranked fx.Tensor launch arguments, allowing the tested 2³¹-element BF16 case without reverting to raw pointers.
  • Fixed FP8 softmax probability scaling and zero Q/K descale handling.
  • Reject BF16/F16 descales instead of silently ignoring them.
  • Added explicit 4D BSHD validation.
  • Added max-absolute-error and V=ones normalization regressions through both pytest and the standard op-test runner.
  • I also merged current ROCm/aiter:main; the PR is conflict-free and reports mergeable.

@vivienfanghuagood

Copy link
Copy Markdown
Contributor

Re-tested 30c1590 on R9700 (FlyDSL 0.4.0 and 0.3.4.1). The other fixes are confirmed, and there is no perf regression. Thanks!

One thing remains: FP8 P/l mismatch on long sequences. P is now scaled by 2^8 before the cvt, but l still sums the fp32 p, so probabilities that flush or round in e4m3 still bias the output. Repro: Q = e1 (D=64); K row 0 = 0, all other rows K[...,0] = -12 / -13; V = 1; descales and softmax_scale = 1. Expected output is 1.0; measured:

N -12 -13
32768 1.039 0.930
75600 1.078 0.855

Accumulating l from the dequantized P would make the numerator and denominator consistent. The current probe (N=4096, atol 2e-2) doesn't cover this case.

…ttn-gfx1201-v9

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

# Conflicts:
#	aiter/ops/flydsl/fmha_kernels.py
@pds-amd

pds-amd commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@vivienfanghuagood Thanks!

The original implementation followed a pattern also used by other FP8 attention kernels in AITER. I updated this path so the softmax denominator accumulates the same E4M3-quantized probabilities consumed by WMMA.

I also added long-sequence regression coverage for the reported cases.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants