On this page
Every prompt token in causal prefill attends to itself and every earlier token. Materializing the full square score matrix quadruples memory every time sequence length doubles: at batch 8, 32 heads, and 8,192 tokens, one FP16 score matrix claims 32 GiB before counting probabilities, weights, or activations.
FlashAttention computes the exact same dense attention without storing or the probability matrix in HBM.[1] Keeping active tiles in fast on-chip SRAM and streaming keys and values past them with online softmax cuts auxiliary storage from quadratic to linear and eliminates the HBM round-trips that stall standard attention.
The memory wall
At batch 8, 32 heads, and 8,192 tokens in FP16, (). PyTorch's SDPA math fallback keeps FP32 intermediates, doubling that to 64 GiB.[2] An unfused four-pass baseline writes , reads for softmax, writes , and reads for , moving 128 GiB of intermediate traffic across HBM per layer.
score_bytes = 8 * 32 * 8192 * 8192 * 2
print(f"one FP16 score matrix: {score_bytes / 1024**3:.2f} GiB | 4-pass traffic: {4 * score_bytes / 1024**3:.2f} GiB")one FP16 score matrix: 32.00 GiB | 4-pass traffic: 128.00 GiBGPUs separate tiny on-chip SRAM from off-die HBM: on H100 SXM, each SM has 228 KiB shared memory (max 227 KiB/block) plus a 256 KiB register file, while HBM holds 80 GB at 3.35 TB/s.[3][4] Low-intensity elementwise ops like softmax sit pinned to the HBM bandwidth ceiling whenever they bounce matrices off chip.

Tiling and online softmax
FlashAttention fuses attention into one SRAM-tiled pass: load a tile on chip, stream tiles past it, update running row softmax statistics, and discard every and tile immediately.

How online softmax stays exact
Because later key tiles can raise a row's maximum , safe softmax rescales previous sums using :
Split scores [1.0, 2.0, 3.0] and values [10, 20, 40] into Block A [1.0, 2.0] (, , ) and Block B [3.0]. When Block B moves the max to , multiply both and by , add Block B ( and ), and divide once at the end: , matching dense softmax. FlashAttention-2 keeps unnormalized across the inner loop and divides by once before storing , removing FA1's per-step division.[1][5]
32.404513.Verify the Q-outer tiled recurrence (handling unequal lengths, remainder tiles, and an all-masked row that returns zero[6]) and its autograd gradients against PyTorch SDPA:
import math, torch
import torch.nn.functional as F
torch.set_num_threads(1)
def tiled_attention(q, k, v, allowed, block_size):
nq, d = q.shape
nk = k.shape[0]
out = []
for i in range(0, nq, block_size):
qi = q[i:i + block_size]
m = torch.full((len(qi), 1), -torch.inf, dtype=q.dtype)
l = torch.zeros_like(m)
num = torch.zeros((len(qi), v.shape[1]), dtype=q.dtype)
for j in range(0, nk, block_size):
s = (qi @ k[j:j + block_size].T / math.sqrt(d)).masked_fill(
~allowed[i:i + len(qi), j:j + block_size], -torch.inf
)
new_m = torch.maximum(m, s.amax(dim=1, keepdim=True))
ref = torch.where(torch.isfinite(new_m), new_m, 0.0) # Avoid -inf - (-inf).
scale = torch.exp(m - ref)
w = torch.exp(s - ref)
num = scale * num + w @ v[j:j + block_size]
l = scale * l + w.sum(dim=1, keepdim=True)
m = new_m
out.append(num / torch.where(l > 0, l, 1.0))
return torch.cat(out)
torch.manual_seed(7)
q = torch.randn(5, 4, dtype=torch.float64, requires_grad=True)
k = torch.randn(7, 4, dtype=torch.float64, requires_grad=True)
v = torch.randn(7, 3, dtype=torch.float64, requires_grad=True)
allowed = torch.arange(7)[None, :] <= (torch.arange(5) + 2)[:, None]
allowed[0] = False # Fully masked row -> zero output.
expected = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed, dropout_p=0.0)
ref_grads = torch.autograd.grad(expected.square().sum(), (q, k, v))
for bs in (1, 3, 20): got = tiled_attention(q, k, v, allowed, bs)
torch.testing.assert_close(got, expected, atol=1e-12, rtol=1e-12)
for g, rg in zip(torch.autograd.grad(got.square().sum(), (q, k, v)), ref_grads):
torch.testing.assert_close(g, rg, atol=1e-11, rtol=1e-11)
print("block sizes 1, 3, 20: outputs, gradients, and empty row match SDPA")block sizes 1, 3, 20: outputs, gradients, and empty row match SDPABackward pass: recompute from LSE
Standard backward saves the 32 GiB probability matrix (64 GiB write+read) to evaluate , , with scalar row correction , , and .[1] FlashAttention saves only one FP32 log-sum-exp scalar per query row, (8 MiB vs. 32 GiB, a 4,096x auxiliary reduction), and recomputes local in SRAM during backward.

Complexity and causal tile skipping
In the two-level SRAM model (capacity scalar elements, ):[1]
| Property | Materialized baseline | FlashAttention |
|---|---|---|
| Auxiliary memory | for and | for row LSE |
| FLOPs | (exact dense attention; extra backward recompute) | |
| HBM reads/writes |
Scaling sequence length from 4K to 16K grows materialized FP16 score storage 16x (from 8 GiB to 128 GiB), while FP32 LSE grows just 4x (from 4 MiB to 16 MiB).
For causal attention, FlashAttention skips materialized masks by classifying tile pairs from absolute token ranges: skip strictly future tiles (key_start > query_end, cutting ~50% of work as grid size grows), run past tiles unmasked (key_end <= query_start), and mask boundary tiles locally in SRAM. Always compare position ranges rather than tile indices when query and key tile widths differ (for example, 64-wide K tile 2 covering 128..191 still overlaps 128-wide Q tile 1 covering 128..255).

Evolution across GPU generations: FA1 to FA4
| Generation | Hardware focus | Key scheduling shift | Reported peak |
|---|---|---|---|
| FA1 (2022)[1] | Ampere (A100) | SRAM tiling + online softmax; K/V outer loop | 15% faster BERT-large (512 seq) |
| FA2 (2023)[5] | Ampere (A100) | Q-resident outer loop, split-Q warps, unnormalized numerator | ~2x FA1; 230 TFLOPs/s FP16 |
| FA3 (2024)[7] | Hopper (H100) | TMA async copy, WGMMA, warp specialization, FP8 forward | 740 TFLOPs/s FP16; ~1.2 PFLOPs/s FP8 |
| FA4 (2026)[8] | Blackwell (B200) & Hopper | Software-emulated exp, conditional rescaling, TMEM, 2-CTA backward, CuTe-DSL | 1,613 TFLOPs/s BF16 on B200 (71% peak) |
FA2 flipped FA1's outer loop to pin tiles and unnormalized on chip (eliminating FA1's intermediate HBM writes) and switched from split-K to split-Q warps so each warp owns disjoint query rows with no cross-warp output reduction.[5] FA3 split Hopper warps into TMA producers and WGMMA/softmax consumers over circular shared buffers.[7] FA4 tackles Blackwell's faster Tensor Cores vs. slower special-function units with emulated exponentials, conditional rescaling (reusing the old reference max when a tile's max barely grows), TMEM accumulators, and Python-embedded CuTe-DSL.[8]

Prefill vs. decode and paged KV kernels
Training and long-prompt prefill expose quadratic scores ( valid causal pairs per head at 8K context), whereas single-token decode scores just 8,192 cached keys (a 4,096.5x ratio) and is KV-bandwidth-bound. Production engines layer PagedAttention's block table under paged tiled kernels like flash_attn_with_kvcache (forward-only, requiring page sizes divisible by 256 in FA2[6]) or FlashInfer, and use flash_attn_varlen_func with int32 cu_seqlens for packed variable-length batches.

Practical surfaces, layouts, and the Causal 2.1 gotcha
FA2, FA3, and FA4 ship as separate wheels and import paths, not one auto-upgrading package:[6]
| Surface | Install & import | Hardware target |
|---|---|---|
| PyTorch SDPA | F.scaled_dot_product_attention[2] | Auto-dispatches Flash, Mem-Efficient, or Math backend |
| FlashAttention-2 | pip install flash-attn --no-build-isolation -> from flash_attn import flash_attn_func | Ampere, Ada, Hopper (CUDA 12.0+); AMD ROCm (CK / AIter Triton) |
| FlashAttention-3 | Build hopper/ -> from flash_attn_3 import flash_attn_interface | Hopper H100 / H800 (CUDA 12.3+) |
| FlashAttention-4 | pip install flash-attn-4 -> from flash_attn.cute import flash_attn_func | Hopper & Blackwell via CuTe-DSL |
Prefer PyTorch SDPA (or HF attn_implementation="flash_attention_2" / "flash_attention_3"[9]) unless you need FA3/FA4, paged KV, or varlen APIs. Watch three interface traps: (1) flash_attn_func uses (B, S, H, D) while SDPA uses (B, H, S, D), (2) FA2 returns out (return_attn_probs=True allocates a quadratic debug buffer!) while FA4 returns (out, lse), and (3) FA2 groups GQA query heads contiguously ([0,0,0,1,1,1], never interleaved).
Bottom-right (FA 2.1+) vs. upper-left (SDPA) causal alignment
During cached decode or chunked prefill (seqlen_q < seqlen_k), new queries sit at the end of the sequence. Starting in FlashAttention 2.1, causal=True aligns the diagonal to the bottom-right (k <= q + seqlen_k - seqlen_q).[6] By contrast, PyTorch SDPA (is_causal=True) aligns to the upper-left (k <= q), blinding a single decode query to every cached key after index 0!
import numpy as np, torch
import torch.nn.functional as F
torch.set_num_threads(1)
qi, ki = np.arange(2)[:, None], np.arange(5)[None, :]
print("SDPA/FA2.0 top-left: ", (ki <= qi).astype(int).tolist())
print("FA2.1+ bottom-right: ", (ki <= qi + 5 - 2).astype(int).tolist())
q = torch.zeros(1, 1, 1, 2, dtype=torch.float64)
k = torch.zeros(1, 1, 4, 2, dtype=torch.float64)
v = torch.tensor([10.0, 20.0, 40.0, 80.0], dtype=torch.float64).reshape(1, 1, 4, 1)
wrong = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0).item()
right = F.scaled_dot_product_attention(q, k, v, is_causal=False, dropout_p=0.0).item()
assert wrong == 10.0 and right == 37.5
print(f"SDPA decode is_causal=True (wrong): {wrong:.1f} | all-valid cache: {right:.1f}")SDPA/FA2.0 top-left: [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0]]
FA2.1+ bottom-right: [[1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]
SDPA decode is_causal=True (wrong): 10.0 | all-valid cache: 37.5Always probe dispatch on CUDA with can_use_flash_attention and sdpa_kernel(SDPBackend.FLASH_ATTENTION) before timing with CUDA events, and never catch an OOM as "backend ineligible" (falling back to math allocates more memory).[10][11]