Skip to content

[CuTe, SM90] hdim256 backward: C++ FA3 dQ path and 2-CTA DSMEM dS exchange (373 → 530 TFLOP/s) - #1

Open
SuperGoodGame wants to merge 7 commits into
fa2878/sm90-hd256-bwdfrom
fa2878/pr2
Open

SuperGoodGame wants to merge 7 commits into
fa2878/sm90-hd256-bwdfrom
fa2878/pr2

Conversation

@SuperGoodGame

Copy link
Copy Markdown
Owner

Summary

Follow-up to Dao-AILab#2888 (which fixed the swapped postprocess layout and moved hdim 256 to a 2-stage 64x48 config, 302 → 373 TFLOP/s). This PR takes the CuTe SM90 backward at head_dim 256 to C++ FA3 parity and beyond, in two independently useful commits:

  1. C++ FA3's hdim256 dQ path (BwdConfig.dQacc_use_TMA=False). No smem staging of dQ: the MMA warp groups reduce the dQ accumulator straight into dQaccum with red.global.add.v4.f32, partitioned by the same R2S tiled copy as the smem path, so the gmem layout and the postprocess are unchanged. dQ is computed in two hdim halves into the same registers (C++ Slice_dQKV_Mma; with two accumulators ptxas hoists the second WGMMA above the atomics and dV spills at tile_n=80). The freed 64 KB is what lets the C++ tile (64x80, 2-stage Q) fit. 373 → 471 TFLOP/s, C++ FA3 is 483 on the same GPU.
  2. FA4's 2-CTA dS exchange, on Hopper via DSMEM (BwdConfig.cluster_size=2). With the atomics compiled out the 1-CTA kernel runs at 747 TFLOP/s, so what remains is the fp32 reduce traffic into dQaccum (S² · d · 4 B / tile_n per head; a single SM sustains only ~30 GB/s of red.add). The two CTAs of a cluster take KV blocks n and n^1 of one head, walk the union of their m-block ranges in lockstep and exchange their dS tiles through distributed shared memory (cp.async.bulk.shared::cluster, mbarrier full/empty handshake with remote arrive/expect_tx). CTA r then computes dQ[:, 128r:128r+128] = dS_own @ K_own[:, half] + dS_peer @ K_peer[:, half] (K = 2·tile_n) and reduces only its half: half the atomics and half the dQ registers at the same tile_n. Splitting by head-dim halves rather than query rows (FA4's Blackwell variant) needs only the peer's K half (20 KB) in smem, which is what makes 64x80 fit exactly (232,448 B). Q and dO are TMA-multicast to the pair. Odd block counts use a "ghost" partner that participates in every barrier with fully masked columns (dS = 0), flushes its dQ half, and skips the dK/dV epilogue. 471 → 530 TFLOP/s.

The pair's fixed cost only pays off once the m-block loop is long enough, so _tile_size_bwd_sm90 selects the 2-CTA kernel for seqlen_q >= 2048 (max_seqlen_q for varlen) and keeps the 1-CTA 64x80 config below (measured crossover, table below). Deterministic and block-sparse backward keep the semaphore-ordered smem-staged path, matching the C++ restriction Deterministic && kHeadDim < 256. Forward and hdim ≤ 192 are untouched.

New surface: two BwdConfig fields (dQacc_use_TMA, cluster_size) and two FlashAttentionBackwardSm90 constructor arguments of the same names, both selected in _tile_size_bwd_sm90 (which gains deterministic and seqlen_q keyword arguments). No public API change.

Results

H20Z (H200 silicon, 132 SMs, 227 KB smem; CUDA 12.8, torch 2.10, nvidia-cutlass-dsl 4.7.1), bf16, backward:

main Dao-AILab#2888 commit 1 (1-CTA) commit 2 (2-CTA) C++ FA3
dense S=16384 H=16 D=256 36.5 ms · 302 29.5 ms · 373 23.3 ms · 471 20.8 ms · 530 22.8 ms · 483
dense causal S=16384 17.2 ms · 320 14.8 ms · 370 11.9 ms · 464 10.5 ms · 522 473
varlen S=86000 H=32 (Dao-AILab#2878) 1931 ms · 314 1672 ms · 362 1314 ms · 461 1250 ms · 485 —
varlen causal S=86000 H=32 — 790 ms · 383 659 ms · 460 568 ms · 534 —
dense S=65536 H=16 567 ms · 310 480 ms · 367 383 ms · 459 364 ms · 483 —

2-CTA vs 1-CTA (same 64x80 tile, H=16, ms ratio; bench/crossover_*.log):

seqlen 512 1024 2048 4096 8192 16384
dense 1.02 1.03 0.91 0.91 0.92 0.83
causal 1.02 1.02 0.95 0.92 0.93 0.88
local (1024,1024) 1.00 0.97 0.90 0.89 0.89 0.91
local (256,0) 1.02 1.01 1.00 1.00 1.00 1.01

Correctness

  • Max error vs an fp32 reference is unchanged from main on every path (S=2048: dq/dk/dv 1.33e-3 / 1.16e-3 / 9.14e-4 non-causal, 1.20e-2 / 1.21e-2 / 1.58e-2 causal). dQ stays fp32-accumulated; only the reduction order changes, as in the C++ kernel.
  • Checked vs the fp32 reference on both the 1-CTA and the 2-CTA kernel: dense, causal, GQA 16/4 and 16/2, MQA, local (200,0)/(100,50)/(256,0)/(1024,1024), softcap, deterministic (bitwise-identical repeat, MHA and GQA; smem path), hdim_v=128, hdim 200/224/240 (MHA and GQA, per kv head), odd n-block counts (ghost CTA), ragged S=1000, S=4096, varlen S=86000.
  • Varlen with the 2-CTA kernel, per batch vs the fp32 reference (bench/varlen_gqa_cluster.py): GQA/MQA/MHA with batches of 0, 1, odd and many KV blocks, causal and not, identical errors to the 1-CTA kernel (this caught a padded-offset mismatch between the kernel and the dK/dV accumulator layout during review; fixed in commit 2).
  • tests/cute/test_flash_attn.py::test_flash_attn_output d=256 subset (1152 ids, mha/mqa/gqa × causal × local × softcap × deterministic × sink): 720 passed, 432 skipped, 0 failed. test_flash_attn_varlen_output d=256 random sample (320 ids): 196 passed, 124 skipped, 0 failed. test_flash_attn_sm90_hdim_padding*: 150 passed.
  • ruff check / ruff format --check (0.11.13) clean on flash_bwd_sm90.py.

Related: Dao-AILab#2878, Dao-AILab#2888.

@SuperGoodGame

Copy link
Copy Markdown
Owner Author

@codex review

catwinee and others added 7 commits September 14, 2026 14:03
…gues (Dao-AILab#2807)

* [CuTe] Optimize SM100 HD256 varlen epilogues

Preserve aligned vector stores for packed forward outputs and use tail-safe TMA stores for complete dQ tiles.

* [CuTe] Bound SM100 HD256 varlen grids by max seqlen

Avoid total-token-by-batch over-launch in forward and backward, following the analysis and reproducer reported by @horakka5 in Dao-AILab#2521.

* Use flat varlen scheduling for SM100 HD256 without host maxima

* Preserve supported HD256 output strides across varlen schedulers

* Clean up varlen regression test lint

---------

Co-authored-by: drisspg <drisspguessous@gmail.com>
…config (Dao-AILab#2888)

* [CuTe, SM90] bwd: fix the swapped dK/dV postprocess layout and the GQA dV accumulator rounding

make_trivial_tiled_mma takes the WGMMA atom shape, so its M mode must be 64.
FlashAttentionBackwardPostprocess reversed the whole (tile / atom_layout)
tiler for swap_ab, which asks for M = hdim / num_wg: every SM90 config with
dKV_swapAB fails in the GQA/MQA postprocess with "expects the M-mode to be
64, but got 192" (hdim in (128, 192] on main, cf. Dao-AILab#2087) and dQ_swapAB cannot
be used above hdim 128. Build the tiled MMA the way the mainloop does,
(64, tile / atom_layout on N); the accumulator register layout is unchanged.

The GQA dV accumulator was allocated with a fixed 32-element head-dim
rounding while the kernel and the postprocess use hdim_multiple_of (64 with
dKV_swapAB), so head_dim_v in {160, 200, 208, 224} wrote and read past each
(batch, kv head) region. Round dv_accum like dk_accum.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* [CuTe, SM90] bwd hdim256: 64x48 tile with a 2-stage Q pipeline and dKV_swapAB

The hdim 256 config was the only SM90 backward config with num_stages_Q=1,
so the Q/dO TMA loads and the WGMMAs were serialized every m-block: 302
TFLOP/s dense at S=16k on H200 while hdim 128 is at parity with C++ FA3
(Dao-AILab#2878). The C++ tile (64x80, 2-stage Q) does not fit next to the 64 KB
smem dQaccum staging buffer; 64x48 with dKV_swapAB is the largest tile
that does. Same config for MHA, GQA and MQA (the postprocess fix in the
previous commit is what makes the swapped layout usable for GQA), and
tile_hdim rounds to 64, so head_dim in (192, 256) no longer crashes the
DSL compiler. Block-sparse backward keeps the previous tile because it
derives its KV block size from n_block_size.

H200, bf16, S=16384 H=16 D=256: 302 -> 373 TFLOP/s dense, 320 -> 371
causal; varlen S=86000 H=32: 1931 -> 1706 ms. Max error vs an fp32
reference unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* [CuTe, SM90] tests: cover head_dim in (192, 256) and GQA in the hdim padding tests

Extend the SM90 backward padding regression to head_dim 200/224/240 (which
crashed the DSL compiler before the previous commits) and add a GQA variant
(head_dim 160/192/224 with 2 kv heads), which exercises the swapped-layout
dK/dV postprocess and the rounded fp32 accumulators.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
…2776)

* [CuTe, Bwd] Handle empty attention workloads

* Verify empty backward skips kernel compilation
…ILab#2775)

* Fix PackGQA predicates for padded head dimensions

Co-authored-by: thad0ctor <robert.gilbreth@gmail.com>

* Test PackGQA across padded head dimensions

* [CuTe] Skip unsupported Blackwell PackGQA test dimensions

---------

Co-authored-by: thad0ctor <robert.gilbreth@gmail.com>
Co-authored-by: Driss Guessous <32754868+drisspg@users.noreply.github.com>
…4) + 64x80 tile

Port the C++ FA3 hdim256 dQ path (dQacc_use_TMA=false, Slice_dQKV_Mma) to
the DSL kernel: with dQacc_use_TMA=False the 64 KB smem dQaccum buffer and
warp 1's cp.async.bulk reduce loop are gone; the MMA warp groups reduce the
dQ accumulator straight into dQaccum with red.global.add.v4.f32, partitioned
by the same R2S tiled copy so the gmem layout (and the postprocess) do not
change. dQ^T is computed in two 128-row hdim halves (dQ_swapAB, one 64-row
WGMMA atom per WG each) into the same 32 registers: half 0 is flushed while
dK and half 1 run on the tensor cores. Reusing the registers matters: with
two accumulators ptxas hoists the second WGMMA above the atomics, both halves
are live and dV spills at tile_n=80.

The freed smem allows the C++ tile: 64x80, Q_stage=2, PdS_stage=2,
dKV_swapAB, dQ_swapAB (197 KB + 20 KB). Deterministic backward keeps the
semaphore-ordered smem-staged path (64x48, Q_stage=2), the same restriction
as C++ (Deterministic && kHeadDim < 256); block-sparse keeps its tile.

H200 (H20Z), bf16, B=1 S=16384 H=16 D=256, backward:
  64x48 Q2 (smem)   29.5 ms  373 TF/s   (causal 14.8 ms, 370)
  this commit       23.3 ms  471 TF/s   (causal 11.9 ms, 464)
  C++ FA3           22.8 ms  483 TF/s   (causal 473)
Max error vs the fp32 reference unchanged on every checked path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
… Hopper) + Q/dO multicast

hdim 256 backward is bound by the fp32 red.add traffic into dQaccum
(S^2 * d * 4 B / tile_n per head): with the atomics compiled out the 64x80
kernel runs at 747 TF/s on H200, with them at 471. Port FA4's Blackwell
2-CTA dS exchange to Hopper (cluster_size=2 in FlashAttentionBackwardSm90):

- The two CTAs of a (2,1,1) cluster take KV blocks n and n^1 of one head and
  walk the union of their m-block ranges in lockstep (blocks outside a CTA's
  own causal/local range are fully masked and contribute zeros).
- After the dS R2S, MMA thread 0 bulk-copies the dS tile into the peer's
  sdS_xchg (cp.async.bulk.shared::cluster, mbarrier full/empty handshake
  with remote arrive/expect_tx). CTA r then computes
  dQ[:, 128r:128r+128] = dS_own @ K_own[:, half] + dS_peer @ K_peer[:, half]
  (dQ_swapAB, one 64x64 WGMMA atom per WG; the peer's K half is TMA-loaded
  once per tile) and red.adds its 32 KB half: half the atomics and half the
  dQ registers of the 1-CTA kernel at the same tile_n.
- Q and dO are TMA-multicast to the pair (each CTA loads half a tile;
  PipelineTmaAsync in multicast-signaling mode), halving their L2 reads.
- Odd n-block counts: the scheduler's padded CTA is a full ghost
  participant (its columns are all masked so its dS is 0; it still computes
  and flushes its hdim half of the valid block's dQ) that skips the dK/dV
  epilogue, so pipeline arrival counts stay static.
- The exchange mbarriers live with the other small members so the buffers
  fill smem to exactly 227 KB at 64x80 (Q2 dO1 PdS1, 1 exchange stage).
- The pair's fixed cost only pays off once the m-block loop is long enough:
  measured on H200 the 2-CTA kernel is 9-17% faster at seqlen_q >= 2048
  (dense, causal, wide local windows) and 2-3% slower at seqlen_q <= 1024,
  so _tile_size_bwd_sm90 selects it for seqlen_q >= 2048 (max_seqlen_q for
  varlen) and keeps the 1-CTA 64x80 config below.

H200 (H20Z), bf16, S=16384 H=16 D=256 backward: 23.3 ms / 471 TF/s (previous
commit) -> 20.8 ms / 530 TF/s (causal 11.9 -> 10.5 ms, 464 -> 522 TF/s);
C++ FA3 22.8 ms / 483. Varlen S=86000 H=32 (Dao-AILab#2878): 1314 -> 1248 ms. Max
error vs the fp32 reference unchanged on every checked path (dense, causal,
GQA, local, softcap, hdim_v 128, hdim 200/224, ragged S=1000 with a ghost
CTA). Deterministic and block-sparse keep the smem-staged path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ax_seqlen_k

The parity fix-up on the n-block count is equivalent to rounding straight to
n_block_size * cluster_size, and rounding does not branch: max_seqlen_k may be
a device tensor (or a fake tensor in the FakeTensorMode compile pass), where
the Python `if` synced or raised DataDependentOutputException. The SM100 2-CTA
backward has the same issue; the SM90 cluster config added here reaches it from
the varlen path.
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.

3 participants