Skip to content
Open
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
100 commits
Select commit Hold shift + click to select a range
ead67d3
[Cute,Fwd,Sm120] Disable use_tma_O in SM80 base class
jganbar May 11, 2026
bc67a9c
[Cute,Fwd,Sm120] Use universal smem-store atom for SM80 MMA layout
jganbar May 11, 2026
c0250ca
[Cute,Fwd,Sm120] Default pack_gqa=False on consumer Blackwell
jganbar May 11, 2026
e595c95
Add SM120 TMA forward kernel with warp specialization
blake-snc Mar 14, 2026
a6b9896
Fix arch override and add SMEM fallback in SM120 TMA forward
blake-snc Apr 2, 2026
bf10b6d
Move `stream` to end of FlashAttentionForwardSm120Tma.__call__
blake-snc Apr 18, 2026
b7be538
Add SM80/SM120 block-sparse forward attention support
blake-snc Mar 25, 2026
3cd8cb6
Use get_total_block_count utility for block-sparse early exit check
blake-snc Mar 25, 2026
59cf537
Include sm_110 in Blackwell-family arch gating (follow-up to #2572) (…
Johnsonms May 26, 2026
6c4f74f
Use is_family_of for sm_90 and sm_103 arch checks (#2589)
Johnsonms May 26, 2026
59f01d6
Bump AITER submodule to commit 3b2e6f4 (#2540)
sstamenk May 27, 2026
0bbb25a
Clamp kv_stage to avoid SMEM overflow for small head_dims on SM100 (#…
Johnsonms May 28, 2026
c200609
[Fwd,Sm100] fix: decode↔prefill exp2 emulation consistency (#2595)
Luosuu May 28, 2026
eaf806d
replace deprecated apis (#2602)
brandon-yujie-sun May 29, 2026
f82d0dc
Bump nvidia-cutlass-dsl to >=4.5.2 and quack-kernels to >=0.5.0 (#2605)
Johnsonms May 30, 2026
6dba037
[CuTe,Fwd,Sm100] refactor mla sm100 forward and add page table (#2558)
jayhshah Jun 1, 2026
c184200
ci: bump Jimver/cuda-toolkit to v0.2.35 for CUDA 13.2 support (#2617)
ko3n1g Jun 2, 2026
b02b07e
[ROCm] Bump Triton to >=3.6.0 and aiter submodule (#2614)
micmelesse Jun 2, 2026
fefa96a
[Triton] Fix graph capture issues and env var (#2620)
micmelesse Jun 3, 2026
d80a771
[CuTe,Bwd,Sm100] allow 2cta with score mod and mask mod in bwd (#2557)
reubenconducts Jun 3, 2026
22a7223
[CuTe] Fix lint failures (#2625)
drisspg Jun 4, 2026
766ed20
[CuTe] Fix lint failure in flash_bwd_sm100.py (#2627)
Johnsonms Jun 4, 2026
12f0ce1
fix: add weights_only=True to all torch.load call sites (#2622)
aryanputta Jun 5, 2026
98688fd
use correction warps if not tma store; remove outdated packgqa guard …
jayhshah Jun 5, 2026
bc58abc
Add aux-scalars to interface to enable dynamic ints and floats in exp…
drisspg Jun 6, 2026
fbf4f9d
sm120: forward kernel — tile/scheduler tuning, SplitKV, paged-KV, pac…
thad0ctor Jun 8, 2026
8163761
sm120: backward — SM80-base extensions, postprocess, pack-GQA M-split…
thad0ctor Jun 8, 2026
71d5f97
sm120: masking, block-sparse, paged-KV, varlen, pack-GQA support + co…
thad0ctor Jun 8, 2026
89d78ff
sm120: dispatch, per-shape tile selection, fp8-decode routing
thad0ctor Jun 8, 2026
3190fa4
sm120: fp8 (e4m3/e5m2) KV-cache decode kernel
thad0ctor Jun 8, 2026
4279d5c
sm120: tests (forward/backward/varlen/local/paged-KV/decode/fp8) + ar…
thad0ctor Jun 8, 2026
08129f8
sm120: document support, usage, and known limitations (README)
thad0ctor Jun 8, 2026
cb23d13
Merge remote-tracking branch 'origin/main' into sm120-conflict-assess
thad0ctor Jun 9, 2026
5933648
sm120: address CodeRabbit review (seqlen seqused guard, fp8 test mem,…
thad0ctor Jun 9, 2026
fc1f20c
sm120: skip mask_mod-backward aux-scalars test on cc12 (documented li…
thad0ctor Jun 9, 2026
b1dbdfb
fix(sm120): drain prologue cp.async before dK/dV epilogue to kill zer…
thad0ctor Jun 9, 2026
6121d6a
fix: build and select cu13.2 prebuilt wheels (#2618)
ko3n1g Jun 9, 2026
7bc5df5
fix(sm120): coerce tensor max_seqlen to host int in varlen backward u…
thad0ctor Jun 9, 2026
e87110e
fix(sm120): make FA4 cute entry points opaque to torch.compile
thad0ctor Jun 9, 2026
fb02fc8
ci(fa4): enforce cutlass-dsl/quack dep floors and rebake cu130 image …
Johnsonms Jun 10, 2026
c410ecf
sm120: add FLASH_ATTENTION_SM120_BWD_CFG backward config override hook
thad0ctor Jun 10, 2026
1944c3a
sm120: consume FLASH_ATTENTION_SM120_BWD_SKIP_FULL_CAUSAL_MASK env ov…
thad0ctor Jun 10, 2026
6c3e045
sm120: use 64x128 backward tile for head_dim <= 64 (+8.8% geomean)
thad0ctor Jun 10, 2026
3406adb
sm120: AtomLayoutNdKV=2 for head_dim 128 backward (+1.1% median)
thad0ctor Jun 10, 2026
bda31e1
sm120: default causal mask-skip for D256 qpkv4 B2 S2048 backward (+6.2%)
thad0ctor Jun 10, 2026
e2b84bd
sm120 bwd: repair dead Mma_dKV_is_RS register-resident P/dS path
thad0ctor Jun 10, 2026
5c02393
sm120: dispatch RS (register-resident P/dS) config for dense D<=64 S>…
thad0ctor Jun 10, 2026
ca456ab
sm120: D256 qpkv2 B1 S2048 nonpack split2 (+4.8%) and qpkv4 Hq32/Hkv8…
thad0ctor Jun 10, 2026
44918b5
Merge branch 'sm120-rs-agent' into sm120-squashed
thad0ctor Jun 10, 2026
fc8cbad
Fix SM100 FP8 fwd with cutlass-dsl >=4.5.2 (MmaF8F6F4Op) (#2640)
Johnsonms Jun 10, 2026
98ed878
test(sm120): gate on cc[0]==12 so sm_121 (DGX Spark) runs the suite
thad0ctor Jun 15, 2026
96ca9c0
fix(sm120): raise NotImplementedError for over-cap backward head dims…
thad0ctor Jun 15, 2026
7052e21
[cute] Fix int32 overflow in SM100 LPT tile scheduler for long contex…
sryap Jun 16, 2026
cbbab83
[Fwd,Sm100] Tune FP8 causal hd128 ex2_emu_freq (8 vs inherited 16) (#…
Johnsonms Jun 16, 2026
d16e381
Make q_subtile_factor default to identity (#2660)
drisspg Jun 17, 2026
bdda748
fix(hd256/sm100): make q/k/v contiguous before dedicated hd256 kernel…
yunweili3 Jun 19, 2026
940cd96
[Cute,Bwd,Sm100] add sparse MLA (Deepseek v4) backward kernels (#2621)
jayhshah Jun 20, 2026
6a94f8b
fix: sync callers with new _flash_attn_fwd 4-tuple return signature (…
hhy3 Jun 24, 2026
82d6441
Fix compatibility issues with CuTe DSL 4.6.0+ (#2648)
anakinxc Jun 25, 2026
c56ba0f
Pass tmem scalar fields as .ptr to TmemAllocator on SM100 (#2679)
pashu-cohere Jun 26, 2026
ddfec5d
Add FLASHATTENTION_DISABLE_SPLIT_ALIGNMENT (#2680)
janeyx99 Jun 26, 2026
6f644f9
ci: rebake cu130 image for cutlass-dsl 4.6.0.dev0 floor (#2684)
Johnsonms Jun 27, 2026
0046957
Update FA4 cute quack compatibility (#2676)
Luosuu Jun 27, 2026
5ed0361
ci: install cutlass-dsl/quack at runtime to decouple from the baked i…
Johnsonms Jun 28, 2026
890f238
[Cute,Bwd,Sm100] Assume 16B stride divisibility for LSE/dPsum bulk-co…
Johnsonms Jun 29, 2026
46b2ae3
fix(hd256/sm100): forward reads actual input strides, drop .contiguou…
oattia Jun 29, 2026
e79261e
ci: run MLA backward cases so CI exercises flash_bwd_mla_sm100.py (#2…
Johnsonms Jun 29, 2026
73c992c
Parallelize splitkv alignment templated kernels, remove flag (#2683)
janeyx99 Jun 30, 2026
002cce0
[FA3] uv installation support (#2458)
bbuschkaemper Jul 3, 2026
1f7ce2f
[AMD ROCm] Enable RDNA backward and adopt CK unified workspace (#2675)
rocking5566 Jul 6, 2026
6e646e0
Fix CuTe SM120 compile-time argument handling (#2671)
yinli-systems Jul 7, 2026
5835c73
[NVIDIA][CuTe,Fwd,sm120] Implement Pack-GQA on SM120 (+ graceful Spli…
johnnynunez Jul 7, 2026
af04967
ad tcgen.ld.red support to sm103a arch (#2696)
drisspg Jul 11, 2026
2ee8023
[CuTe, Bwd] Fix backward compile key churn due to pickling, max_seqle…
michaelxu-msft Jul 11, 2026
0816ef1
hopper/setup.py: harden tarfile extraction against path traversal and…
aryanputta Jul 12, 2026
2402cb0
Enable 2CTA for SM100 block-sparse backward (#2661)
drisspg Jul 14, 2026
77aacb6
Add paged-KV block_table bounds check in mha_fwd_kvcache (#2711)
yunweili3 Jul 16, 2026
2c18385
Merge origin/main into sm120-squashed
thad0ctor Jul 17, 2026
467749e
fix(sm120): drop stray positional 'local' in SM80/SM120 backward ctor…
thad0ctor Jul 17, 2026
2b32b86
fix(sm120): let decode auto-split engage SplitKV instead of asserting
thad0ctor Jul 17, 2026
2409214
[CuTe, SM100] Fix FP8 e4m3 accuracy: make max_offset dtype-aware to a…
yunweili3 Jul 19, 2026
b54df16
[CuTe, Flex] Allow score mod use in varlen backward (#2547)
reubenconducts Jul 23, 2026
00756db
Expand FLASHATTENTION_DISABLE_DROPOUT to not bring in unneeded header…
janeyx99 Jul 24, 2026
14c3779
add linearize scheduling to combine kernel for full cudagraph (#2692)
liangel-02 Jul 27, 2026
849f660
Numeric tweaks to fp8 (#2731)
drisspg Jul 28, 2026
c75d019
Remove SM100 Functions from Hopper (#2746)
ankutalev Jul 29, 2026
c46b814
[CuTe,Sm100] Varlen Dynamic Persistent scheduler and metadata (#2559)
reubenconducts Aug 2, 2026
df61ab6
[AI] Add doc on debug methodology (#2753)
jayhshah Aug 3, 2026
4a948e9
[ROCm] Fix CK varlen_fwd binding argument mismatch (#2742)
hyoon1 Aug 4, 2026
c68c592
[CuTe, SM100] Sparse MLA bwd: don't scatter dK/dV at -1 sentinel indi…
abcdabcd987 Aug 4, 2026
4460ebb
[CuTe,Bwd,Sm90] Fix: wait for bwd_preprocess on the block-sparse path…
Fugoes Aug 5, 2026
5579b12
[Cute, bwd, sm90/100/110] Support learnable sink in backward (#2706)
Aug 5, 2026
7a08d7a
[CuTe, FA4] Preserve first-tile flag during scheduler reconstruction …
dongxiao92 Aug 6, 2026
d7e4dba
Fix duplicated word in layer norm comment (#2744)
cupkk Aug 6, 2026
3fa8105
[CuTe, SM100] Fix deadlock in varlen + block-sparse + SplitKV forward…
JiaxuanBai Aug 6, 2026
1cc7ff6
[CuTe, Fwd] Stabilize tensor max_seqlen compile key (#2762)
eamonn-zh Aug 7, 2026
69e1bcb
[CuTe] Fix forward dynamic-shape correctness (#2745)
drisspg Aug 7, 2026
a369df7
Fix CLC fuzz scheduler expectations (#2766)
JiaxuanBai Aug 9, 2026
4cabd92
Merge origin/main into sm120-squashed (PR #2634)
thad0ctor Aug 10, 2026
baabf5a
Keep SM120 sink backward working without touching _flash_attn_bwd
thad0ctor Aug 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ jobs:

- name: Install CUDA ${{ inputs.cuda-version }}
if: ${{ inputs.cuda-version != 'cpu' }}
uses: Jimver/cuda-toolkit@v0.2.30
uses: Jimver/cuda-toolkit@v0.2.35

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
curl -s https://api.github.com/repos/Jimver/cuda-toolkit/git/ref/tags/v0.2.35 | jq -r '.object.sha'

Repository: thad0ctor/flash-attention

Length of output: 110


🏁 Script executed:

#!/bin/bash
set -euo pipefail
ls -la .github/workflows || true
sed -n '60,95p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 2336


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '60,95p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 1799


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '70,90p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 961


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '70,90p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 961


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '70,90p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 961


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '70,90p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 961


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '70,90p' .github/workflows/_build.yml
rg -n "Jimver/cuda-toolkit@" .github/workflows/_build.yml

Repository: thad0ctor/flash-attention

Length of output: 961


Pin Jimver/cuda-toolkit to an immutable commit SHA.

.github/workflows/_build.yml uses the mutable tag Jimver/cuda-toolkit@v0.2.35; resolve it to its commit SHA 3d45d157f327c09c04b50ee6ccdea2d9d017ec76 to prevent tag retargeting.

🔒 Proposed fix
-        uses: Jimver/cuda-toolkit@v0.2.35
+        uses: Jimver/cuda-toolkit@3d45d157f327c09c04b50ee6ccdea2d9d017ec76
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
uses: Jimver/cuda-toolkit@v0.2.35
uses: Jimver/cuda-toolkit@3d45d157f327c09c04b50ee6ccdea2d9d017ec76
🧰 Tools
🪛 zizmor (1.25.2)

[error] 80-80: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/_build.yml at line 80, Replace the mutable tag reference
in the workflow step that currently reads "uses: Jimver/cuda-toolkit@v0.2.35"
with the immutable commit SHA to prevent tag retargeting; update the uses line
to "uses: Jimver/cuda-toolkit@3d45d157f327c09c04b50ee6ccdea2d9d017ec76" so the
action is pinned to the specified commit SHA.

Source: Linters/SAST tools

id: cuda-toolkit
with:
cuda: ${{ inputs.cuda-version }}
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ permissions:

env:
CI_WORK_DIR: ${{ vars.CI_WORK_DIR || format('/scratch/user/{0}', github.actor) }}
FA4_TEST_FILTER: "1024-1024-128-True-0-0.0-False-False-False-mha-dtype0 or 1024-1024-128-False-0-0.0-False-False-False-mha-dtype0"
FA4_TEST_FILTER: >-
1024-1024-128-True-0-0.0-False-False-False-mha-dtype0
or 1024-1024-128-False-0-0.0-False-False-False-mha-dtype0
or test_flash_attn_ex2_emu_decode_prefill_consistency

jobs:
lint:
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pip install flash-attn-4
pip install -e "flash_attn/cute[dev]"
```

Dependencies: `nvidia-cutlass-dsl>=4.4.1`, `torch`, `einops`, `apache-tvm-ffi`, `quack-kernels>=0.4.0`.
Dependencies: `nvidia-cutlass-dsl>=4.5.2`, `torch`, `einops`, `apache-tvm-ffi`, `quack-kernels>=0.5.0`.

## Running Tests

Expand Down
108 changes: 108 additions & 0 deletions benchmarks/benchmark_mla_paged_kv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Copyright (c) 2025, Johnsonms.

# We recommend locking GPU clocks before running the benchmark to ensure consistent results.
# This can be done using the following commands (2619 MHz is the max clock for B200):
# sudo nvidia-smi -i 0 -pm 1
# sudo nvidia-smi -i 0 --lock-gpu-clocks 2619,2619
# See more here: https://github.com/triton-lang/triton/blob/d9f10ebdc5da53f73eb852fde73d8d7d80b679d1/python/triton/testing.py#L487

import time
import torch

from triton.testing import do_bench

from flash_attn.cute.interface import flash_attn_varlen_func


device = "cuda"
dtype = torch.bfloat16
seqlen_q = 1
nheads_q = 128
nheads_kv = 1 # MQA-128
headdim = 64
headdim_v = 512
causal = True

batch_size = 128
page_sizes = [None, 16, 64, 128] # None = non-paged baseline

torch.manual_seed(0)

print(f"\nMLA paged KV, nheads_q = {nheads_q}, nheads_kv = {nheads_kv}, headdim = {headdim}, headdim_v = {headdim_v}, causal = {causal}")

for seqlen in [s * 1024 for s in [1, 2, 4, 8, 16, 32, 64]]:
# Varlen format: (total_tokens, nheads, hdim)
total_q = batch_size * seqlen_q
total_k = batch_size * seqlen

try:
q = torch.randn(total_q, nheads_q, headdim, dtype=dtype, device=device)
k = torch.randn(total_k, nheads_kv, headdim, dtype=dtype, device=device)
v = torch.randn(total_k, nheads_kv, headdim_v, dtype=dtype, device=device)
qv = torch.randn(total_q, nheads_q, headdim_v, dtype=dtype, device=device)
except torch.OutOfMemoryError:
continue

cu_seqlens_q = torch.arange(0, total_q + seqlen_q, seqlen_q, dtype=torch.int32, device=device)
cu_seqlens_k = torch.arange(0, total_k + seqlen, seqlen, dtype=torch.int32, device=device)

# Mem I/O: KV read + Q/QV read + O write
total_seqlen = seqlen * batch_size
mem_io = (
total_seqlen * nheads_kv * (headdim + headdim_v) * 2 # K + V read
+ q.numel() * 2 + qv.numel() * 2 # Q + QV read
+ total_q * nheads_q * headdim_v * 2 # O write
)
# FLOPs: QK^T + PV (with qv, PV uses headdim_v)
flops = seqlen_q * total_seqlen * nheads_q * (headdim + headdim_v * 2) * 2

for page_size in page_sizes:
if page_size is None:
# Non-paged baseline
fn = lambda: flash_attn_varlen_func( # noqa: E731
q, k, v, qv=qv,
cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=seqlen_q, max_seqlen_k=seqlen,
causal=causal,
)
label = "non-paged"
else:
# Create paged KV
num_pages_per_seq = (seqlen + page_size - 1) // page_size
total_pages = num_pages_per_seq * batch_size
k_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim, device=device, dtype=dtype)
v_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim_v, device=device, dtype=dtype)
page_table = torch.zeros(batch_size, num_pages_per_seq, dtype=torch.int32, device=device)
for b in range(batch_size):
for p in range(num_pages_per_seq):
page_idx = b * num_pages_per_seq + p
start = p * page_size
end = min(start + page_size, seqlen)
k_offset = b * seqlen
if start < seqlen:
k_paged[page_idx, :end - start] = k[k_offset + start:k_offset + end]
v_paged[page_idx, :end - start] = v[k_offset + start:k_offset + end]
page_table[b, p] = page_idx
seqused_k = torch.full((batch_size,), seqlen, dtype=torch.int32, device=device)
Comment on lines +73 to +86

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Handle OOM in the paged-KV allocation path as well.

Lines 73-86 can still OOM and terminate the whole run, while the non-paged allocations already skip gracefully.

🛠️ Proposed fix
         else:
             # Create paged KV
-            num_pages_per_seq = (seqlen + page_size - 1) // page_size
-            total_pages = num_pages_per_seq * batch_size
-            k_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim, device=device, dtype=dtype)
-            v_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim_v, device=device, dtype=dtype)
-            page_table = torch.zeros(batch_size, num_pages_per_seq, dtype=torch.int32, device=device)
+            try:
+                num_pages_per_seq = (seqlen + page_size - 1) // page_size
+                total_pages = num_pages_per_seq * batch_size
+                k_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim, device=device, dtype=dtype)
+                v_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim_v, device=device, dtype=dtype)
+                page_table = torch.zeros(batch_size, num_pages_per_seq, dtype=torch.int32, device=device)
+            except torch.OutOfMemoryError:
+                print(f"Skipping paged-{page_size} at seqlen={seqlen}: OOM")
+                continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
k_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim, device=device, dtype=dtype)
v_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim_v, device=device, dtype=dtype)
page_table = torch.zeros(batch_size, num_pages_per_seq, dtype=torch.int32, device=device)
for b in range(batch_size):
for p in range(num_pages_per_seq):
page_idx = b * num_pages_per_seq + p
start = p * page_size
end = min(start + page_size, seqlen)
k_offset = b * seqlen
if start < seqlen:
k_paged[page_idx, :end - start] = k[k_offset + start:k_offset + end]
v_paged[page_idx, :end - start] = v[k_offset + start:k_offset + end]
page_table[b, p] = page_idx
seqused_k = torch.full((batch_size,), seqlen, dtype=torch.int32, device=device)
# Create paged KV
try:
num_pages_per_seq = (seqlen + page_size - 1) // page_size
total_pages = num_pages_per_seq * batch_size
k_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim, device=device, dtype=dtype)
v_paged = torch.zeros(total_pages, page_size, nheads_kv, headdim_v, device=device, dtype=dtype)
page_table = torch.zeros(batch_size, num_pages_per_seq, dtype=torch.int32, device=device)
except torch.OutOfMemoryError:
print(f"Skipping paged-{page_size} at seqlen={seqlen}: OOM")
continue
for b in range(batch_size):
for p in range(num_pages_per_seq):
page_idx = b * num_pages_per_seq + p
start = p * page_size
end = min(start + page_size, seqlen)
k_offset = b * seqlen
if start < seqlen:
k_paged[page_idx, :end - start] = k[k_offset + start:k_offset + end]
v_paged[page_idx, :end - start] = v[k_offset + start:k_offset + end]
page_table[b, p] = page_idx
seqused_k = torch.full((batch_size,), seqlen, dtype=torch.int32, device=device)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@benchmarks/benchmark_mla_paged_kv.py` around lines 73 - 86, The paged-KV
allocation and initialization (k_paged, v_paged, page_table and seqused_k) can
OOM; wrap that whole allocation+fill block in a try/except that catches
torch.cuda.OutOfMemoryError or RuntimeError, call torch.cuda.empty_cache() and
log/print a concise warning, then skip this benchmark iteration (e.g., set a
local skip flag or continue the outer loop) exactly like the non-paged path
does; ensure you reference and protect the symbols k_paged, v_paged, page_table
and seqused_k so they are not used after a failed allocation.


fn = lambda kp=k_paged, vp=v_paged, pt=page_table, su=seqused_k: flash_attn_varlen_func( # noqa: E731
q, kp, vp, qv=qv,
cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=None,
max_seqlen_q=seqlen_q, max_seqlen_k=None,
seqused_k=su, page_table=pt,
causal=causal,
)
path = "TMA" if page_size == 128 else "cp.async"
label = f"paged-{page_size} ({path})"

fn() # warmup / compile
time.sleep(1) # avoid power throttling
t = do_bench(fn, warmup=5, rep=20)
print(
f"Seqlen = {seqlen}, {label}: {t * 1e3:.1f} us, "
f"{mem_io * 1e-9 / (t * 1e-3):.0f} GB/s, "
f"{flops * 1e-12 / (t * 1e-3):.0f} TFLOPS/s"
)

print(f"Arithmetic intensity: {flops / mem_io:.1f}")
print()
39 changes: 39 additions & 0 deletions flash_attn/cute/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,45 @@ from flash_attn.cute import flash_attn_func, flash_attn_varlen_func
out = flash_attn_func(q, k, v, causal=True)
```

## Consumer Blackwell (sm_120 / RTX PRO 6000, RTX 50-series)

FA4 runs on consumer Blackwell (compute capability 12.x), which exposes SM80-class
`mma.sync` tensor cores (no WGMMA/tcgen05/TMEM). Dispatch and tile selection are
auto-tuned for this arch; no environment variables are required for normal use.

**Supported:** forward and backward for dense, causal, and local/sliding-window
attention; MHA / GQA / MQA; variable-length (`flash_attn_varlen_func`); paged-KV;
block sparsity; `score_mod` / `mask_mod`; learnable sink. Head dims 64/96/128/192/256.

**fp8 KV-cache decode (e4m3/e5m2):** for decode (`seqlen_q == 1`) with a quantized
K/V cache and a bf16/fp16 query, pass fp8 `k`/`v` plus per-`(batch, kv_head)` fp32
`k_descale`/`v_descale`. This auto-routes to a memory-efficient GEMV decode kernel
(no env var needed) and is ~1.6–1.9× faster than bf16 at GQA ratios ≤ 4 while halving
KV-cache bandwidth. Accuracy is within ~2e-3 of an fp8-quantized reference.

**Environment flags:**
- `FLASH_ATTENTION_SM120_DECODE_KERNEL=1` — opt into the experimental **bf16** GEMV
decode kernel for `seqlen_q == 1` (the fp8 decode path above is always on when fp8
K/V is supplied). Off by default.
- `FLASH_ATTENTION_ARCH` — override the detected compute capability (testing/compile).

**Known performance floors vs FA2 on sm_120** (hardware-bound, not bugs):
- Causal *MHA* (`qhead_per_kvhead == 1`) at `seqlen ≥ 8192` is ~0.95× FA2 — a register/
occupancy wall (255 regs/thread → 1 CTA/SM). GQA (the common case) is at parity or faster.
- fp8 KV-cache decode regresses below bf16 at GQA ratio ≥ 8 (the GEMV loop becomes
compute-bound); it still halves KV memory, so it remains the only fp8-cache path.
- Backward is at ~parity with FA2; fp8 is forward/decode-only (no fp8 backward).

**Feature limitations on sm_120:**
- `learnable_sink` is incompatible with SplitKV (each split would double-count the sink
in the combine step), so SplitKV is disabled when a sink is present — attention runs
in a single split (correct, but without the decode SplitKV speedup).
- Negative-offset sliding windows (`window_size` with a negative bound, e.g. `(None, -X)`
or `(-X, None)`) are forward-only: the backward raises `NotImplementedError` (its
dK/dV are incorrect for these offset windows). Non-negative windows are fully supported.
- Deterministic backward (`deterministic=True`) is not supported (the SM80-base backward
lacks the dQ-semaphore path).

## Development

```sh
Expand Down
118 changes: 114 additions & 4 deletions flash_attn/cute/block_sparse_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
"""
Block-sparse runtime utilities for CUTE DSL kernels.

Expand All @@ -18,6 +19,7 @@
from flash_attn.cute.block_sparsity import BlockSparseTensors
from flash_attn.cute.named_barrier import NamedBarrierBwd
from flash_attn.cute.seqlen_info import SeqlenInfoQK
from flash_attn.cute.utils import AuxData


@cute.jit
Expand Down Expand Up @@ -705,6 +707,114 @@ def produce_block_sparse_loads_sm100(
return kv_producer_state, q_producer_phase


@cute.jit
def run_block_sparse_mainloop_sm80(
blocksparse_tensors: BlockSparseTensors,
batch_idx,
head_idx,
m_block,
mma_one_n_block,
mask_fn,
mask_mod,
fastdiv_mods,
qhead_per_kvhead: cutlass.Constexpr[int] = 1,
q_subtile_factor: cutlass.Constexpr[int] = 1,
):
"""Block-sparse mainloop iteration for SM80/SM120.

NOTE: This implementation hard-codes the non-varlen 4D indexing pattern
(lines below this docstring access blocksparse_tensors with 3D indices into
batch/head/m_block_sparse). Varlen + block-sparse on SM80/SM120 would
require routing through get_curr_blocksparse_tensors(...) (which handles
both 2D varlen and 4D non-varlen layouts) and threading seqlen_info into
this function. The SM120 dispatcher in interface.py currently does not
support varlen + block-sparse together, so this is intentionally narrow;
if you lift that restriction, update this function accordingly.

Processes mask blocks first (applying mask_mod), then full blocks (seqlen masking only).
The first full block always receives seqlen masking regardless of whether mask blocks
preceded it, since full blocks may be at higher n positions than mask blocks.

Mirrors the non-intra-wg-overlap path of consume_block_sparse_loads for SM90/SM100.

Args:
mma_one_n_block: callable with signature
(n_block, mask_fn, is_first_n_block) -> None
mask_fn: partial of mask.apply_mask with batch/head/m_block/thr_mma already bound.
Called as mask_fn(acc_S, n_block=n, mask_mod=..., mask_seqlen=...,
fastdiv_mods=...)
mask_mod: the user mask_mod constexpr (None → no mask_mod application)
fastdiv_mods: fast-division helpers when mask_mod is not None

Returns:
processed_any: True if at least one block was processed.
"""
# SM80/SM120 only need the first 4 fields; trailing fields are SM100/backward-only.
mask_block_cnt, mask_block_idx, full_block_cnt, full_block_idx, *_ = blocksparse_tensors

m_block_sparse = sparse_tensor_m_block(m_block, qhead_per_kvhead, q_subtile_factor)

curr_mask_block_cnt = mask_block_cnt[batch_idx, head_idx, m_block_sparse]
curr_mask_block_idx = mask_block_idx[batch_idx, head_idx, m_block_sparse, None]

if const_expr(full_block_cnt is not None):
curr_full_block_cnt = full_block_cnt[batch_idx, head_idx, m_block_sparse]
curr_full_block_idx = full_block_idx[batch_idx, head_idx, m_block_sparse, None]
else:
curr_full_block_cnt = Int32(0)
curr_full_block_idx = None

processed_any = curr_mask_block_cnt + curr_full_block_cnt > 0

# Process mask blocks: first gets is_first=True and seqlen masking; rest get is_first=False.
if curr_mask_block_cnt > 0:
n_block = curr_mask_block_idx[curr_mask_block_cnt - 1]
mma_one_n_block(
n_block=n_block,
mask_fn=partial(
mask_fn,
mask_mod=mask_mod,
mask_seqlen=True,
fastdiv_mods=fastdiv_mods if const_expr(mask_mod is not None) else None,
),
is_first_n_block=True,
)
for i in cutlass.range(1, curr_mask_block_cnt):
n_block = curr_mask_block_idx[curr_mask_block_cnt - 1 - i]
mma_one_n_block(
n_block=n_block,
mask_fn=partial(mask_fn, mask_mod=mask_mod, mask_seqlen=False),
is_first_n_block=False,
)

# Process full blocks: first full block always gets seqlen masking (it may be at the
# highest n position even when mask blocks were present). No mask_mod applied.
if const_expr(full_block_cnt is not None):
if curr_full_block_cnt > 0:
n_block = curr_full_block_idx[curr_full_block_cnt - 1]
if curr_mask_block_cnt == 0:
mma_one_n_block(
n_block=n_block,
mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=True),
is_first_n_block=True,
)
else:
mma_one_n_block(
n_block=n_block,
mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=True),
is_first_n_block=False,
)
for j in cutlass.range(1, curr_full_block_cnt):
n_block = curr_full_block_idx[curr_full_block_cnt - 1 - j]
mma_one_n_block(
n_block=n_block,
mask_fn=partial(mask_fn, mask_mod=None, mask_seqlen=False),
is_first_n_block=False,
)

return processed_any


@cute.jit
def get_total_block_count(
blocksparse_tensors: BlockSparseTensors,
Expand Down Expand Up @@ -754,7 +864,7 @@ def handle_block_sparse_empty_tile_correction_sm100(
sScale: cute.Tensor,
stats: list,
correction_epilogue: Callable,
thr_mma_pv: cute.core.ThrMma,
thr_mma_pv: cute.ThrMma,
tOtO: cute.Tensor,
sO: cute.Tensor,
pipeline_sm_stats: cutlass.pipeline.PipelineAsync,
Expand Down Expand Up @@ -1363,7 +1473,7 @@ def consume_block_sparse_mma_bwd_sm90(
score_mod_bwd_fn=None,
subtile_factor: cutlass.Constexpr = 1,
m_block_max: int = 0,
aux_tensors=None,
aux_data: AuxData = AuxData(),
fastdiv_mods=(None, None),
):
"""SM90 backward block sparse MMA consumption with separate partial/full loops.
Expand Down Expand Up @@ -1396,7 +1506,7 @@ def consume_block_sparse_mma_bwd_sm90(
mask_causal=is_causal,
mask_local=is_local,
mask_mod=mask_mod,
aux_tensors=aux_tensors,
aux_data=aux_data,
fastdiv_mods=fastdiv_mods,
)

Expand All @@ -1409,7 +1519,7 @@ def consume_block_sparse_mma_bwd_sm90(
mask_seqlen=True,
mask_causal=is_causal,
mask_local=is_local,
aux_tensors=aux_tensors,
aux_data=aux_data,
fastdiv_mods=fastdiv_mods,
)

Expand Down
Loading