Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceFlashAttention & Memory Efficiency
HardInference Optimization10 min read

FlashAttention & Memory Efficiency

At batch 8, 32 heads, and 8,192 tokens, FP16 scores need 32 GiB. FlashAttention computes the same attention without storing that matrix.

On this page

Every prompt in causal attends to itself and every earlier token. Materializing the full square score S=QK⊤/dS = QK^{\top}/\sqrt{d} quadruples memory every time sequence length doubles: at batch 8, 32 heads, and 8,192 tokens, one score matrix claims 32 GiB before counting probabilities, weights, or activations.

computes the exact same dense attention without storing SS or the probability matrix PP in .[1] Keeping active tiles in fast on-chip and streaming keys and values past them with 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, 8×32×81922×2=32 GiB8 \times 32 \times 8192^2 \times 2 = 32\text{ GiB} (34.36 GB34.36\text{ GB}). PyTorch's math fallback keeps FP32 intermediates, doubling that to 64 GiB.[2] An unfused four-pass baseline writes SS, reads SS for , writes PP, and reads PP for PVPV, moving 128 GiB of intermediate traffic across HBM per layer.

score-matrix-size.py
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")
Output
one FP16 score matrix: 32.00 GiB | 4-pass traffic: 128.00 GiB

GPUs 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 n×nn \times n matrices off chip.

Three-tier GPU memory hierarchy showing host CPU DRAM, H100 SXM HBM (80 GB, 3.35 TB/s), and SM-local shared memory (228 KiB/SM, 227 KiB max per block, shared with L1) beside a separate 256 KiB/SM register file. Below, a proportional 144 KiB working-set bar partitions Q (16 KiB), K (16 KiB), V (16 KiB), output O (32 KiB), and FP32 score tile S (64 KiB).
A Br=Bc=128B_r = B_c = 128, d=64d = 64 attention tile needs 144 KiB across shared memory and registers (three 128×64128 \times 64 FP16 Q/K/V tiles = 48 KiB, one 128×64128 \times 64 FP32 output accumulator = 32 KiB, and one 128×128128 \times 128 FP32 score tile = 64 KiB), fitting on chip instead of bouncing 128 GiB through HBM.

Tiling and online softmax

FlashAttention fuses attention into one SRAM-tiled pass: load a QQ tile on chip, stream K,VK, V tiles past it, update running row softmax statistics, and discard every SijS_{ij} and PijP_{ij} tile immediately.

A 3 by 3 causal stencil contains 9 allocated score slots and 6 valid pairs. For a separate batch 8, 32-head, 8,192-token example, one full FP16 score or probability array is 32 GiB. Four directional transfers total 128 GiB of logical intermediates. The tiled path keeps Q and row state on chip, streams K/V tiles in, discards temporary score and probability tiles, and writes O plus an 8 MiB FP32 LSE array.
Materialized attention shuttles 128 GiB of intermediates through HBM; FlashAttention discards tiles on chip and writes only OO plus an 8 MiB FP32 LSE vector.

How online softmax stays exact

Because later key tiles can raise a row's maximum mm, safe softmax rescales previous sums using esj−mnew=emold−mnewesj−molde^{s_j - m_{\text{new}}} = e^{m_{\text{old}} - m_{\text{new}}} e^{s_j - m_{\text{old}}}:

mnew=max⁡(mold,mtile),ℓnew=emold−mnewℓold+ℓtile,Nnew=emold−mnewNold+Ntilem_{\text{new}} = \max(m_{\text{old}}, m_{\text{tile}}), \qquad \ell_{\text{new}} = e^{m_{\text{old}} - m_{\text{new}}} \ell_{\text{old}} + \ell_{\text{tile}}, \qquad N_{\text{new}} = e^{m_{\text{old}} - m_{\text{new}}} N_{\text{old}} + N_{\text{tile}}

Split scores [1.0, 2.0, 3.0] and values [10, 20, 40] into Block A [1.0, 2.0] (mA=2m_A = 2, ℓA≈1.368\ell_A \approx 1.368, NA≈23.679N_A \approx 23.679) and Block B [3.0]. When Block B moves the max to 33, multiply both ℓA\ell_A and NAN_A by α=e2−3≈0.368\alpha = e^{2-3} \approx 0.368, add Block B (11 and 4040), and divide once at the end: O=48.711/1.503≈32.4045O = 48.711 / 1.503 \approx 32.4045, matching dense softmax. FlashAttention-2 keeps NN unnormalized across the inner loop and divides by ℓfinal\ell_{\text{final}} once before storing OO, removing FA1's per-step division.[1][5]

Rescaling both ℓA\ell_A and NAN_A by α=e2−3\alpha = e^{2-3} aligns Block A to Block B's maximum before merging, yielding exact output 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:

flash-attention-sketch.py
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):
Output
block sizes 1, 3, 20: outputs, gradients, and empty row match SDPA

Backward pass: recompute from LSE

Standard backward saves the 32 GiB probability matrix PP (64 GiB write+read) to evaluate dV=P⊤dOdV = P^{\top} dO, dP=dO V⊤dP = dO\,V^{\top}, dS=P⊙(dP−D)dS = P \odot (dP - D) with scalar row correction Di=dOi⋅OiD_i = dO_i \cdot O_i, dQ=dS K/ddQ = dS\,K/\sqrt{d}, and dK=dS⊤Q/ddK = dS^{\top} Q/\sqrt{d}.[1] FlashAttention saves only one FP32 log-sum-exp scalar per query row, Li=mi+log⁡ℓiL_i = m_i + \log \ell_i (8 MiB vs. 32 GiB, a 4,096x auxiliary reduction), and recomputes local Pij=exp⁡(Sij−Li)P_{ij} = \exp(S_{ij} - L_i) in SRAM during backward.

The materializing backward path saves and rereads one 32 GiB FP16 probability matrix, 64 GiB total logical transfers; FlashAttention saves an 8 MiB FP32 LSE row vector and reconstructs local tiles. For the article’s seeded CPU check, query row 1 and key 0 have score S_10 = -0.385025137 and LSE L_1 = 2.434266205, giving P_10 = exp(S_10 - L_1) = 0.059648198. A 5 by 7 mask shows row 0 fully masked and rows 1 through 4 admitting 4, 5, 6, and 7 keys. The reconstructed probabilities combine with dP and row correction D to form dS, which gives dQ and dK; P and dO independently give dV = P^T dO.
Recomputing SijS_{ij} and Pij=exp⁡(Sij−Li)P_{ij} = \exp(S_{ij} - L_i) on chip trades extra Tensor Core FLOPs to avoid 64 GiB of HBM traffic.

Complexity and causal tile skipping

In the two-level SRAM model (capacity MM scalar elements, d≤M≤ndd \le M \le nd):[1]

PropertyMaterialized baselineFlashAttention
Auxiliary memoryO(n2)O(n^2) for SS and PPO(n)O(n) for row LSE
FLOPsO(n2d)O(n^2 d)O(n2d)O(n^2 d) (exact dense attention; extra backward recompute)
HBM reads/writesΘ(nd+n2)\Theta(nd + n^2)Θ(n2d2/M)\Theta(n^2 d^2 / M)

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 j>ij > i 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).

A labeled 4 by 4 tile schedule shows six fully allowed past pairs, four diagonal pairs, and six future pairs skipped. A diagonal tile applies a lower-triangular element mask, setting its upper triangle to negative infinity before softmax.
In an aligned 4x4 grid, 10 tile pairs run and 6 future pairs (37.5%) skip completely.

Evolution across GPU generations: FA1 to FA4

GenerationHardware focusKey scheduling shiftReported peak
FA1 (2022)[1]Ampere (A100)SRAM tiling + online softmax; K/V outer loop15% 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 forward740 TFLOPs/s FP16; ~1.2 PFLOPs/s FP8
FA4 (2026)[8]Blackwell (B200) & HopperSoftware-emulated exp, conditional rescaling, TMEM, 2-CTA backward, CuTe-DSL1,613 TFLOPs/s BF16 on B200 (71% peak)

FA2 flipped FA1's outer loop to pin QQ tiles and unnormalized NN 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]

Two aligned lanes show producer and consumer states across a shared overlap window. Slot B starts free; while the consumer uses ready slot A for tile t, TMA copies tile t+1 into B. A copy-complete barrier marks B ready. The consumer applies the softmax update after the dependent matrix result arrives, then releases A so the producer can refill it. Overlap depends on independent work, synchronization, and available resources.
FA3 warp specialization overlaps producer TMA copies with consumer WGMMA/softmax across circular buffer slots.

Prefill vs. decode and paged KV kernels

Training and long-prompt prefill expose quadratic scores (33.56M33.56\text{M} 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.

With an 8,192-key span, prefill has 8,192 causal query rows and 33,558,528 valid query-key pairs per head. One decode step has a single query row and 8,192 valid keys. Their exact pair-count ratio is 4,096.5; the full square contains 67,108,864 possible slots, and the ratio does not measure speed. A separate map sends eight logical allocator pages of 16 tokens each to scattered physical blocks. One 128-token kernel read spans all eight pages. The flash-attn paged interface separately requires page sizes divisible by 256.
Prefill scores 4,096.5x more causal pairs per head than one decode step; paged decode kernels follow block tables across scattered physical pages.

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]

SurfaceInstall & importHardware target
PyTorch SDPAF.scaled_dot_product_attention[2]Auto-dispatches Flash, Mem-Efficient, or Math backend
FlashAttention-2pip install flash-attn --no-build-isolation -> from flash_attn import flash_attn_funcAmpere, Ada, Hopper (CUDA 12.0+); AMD ROCm (CK / AIter Triton)
FlashAttention-3Build hopper/ -> from flash_attn_3 import flash_attn_interfaceHopper H100 / H800 (CUDA 12.3+)
FlashAttention-4pip install flash-attn-4 -> from flash_attn.cute import flash_attn_funcHopper & 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!

cached-query-alignment.py
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}")
Output
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.5

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

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A materializing baseline has batch 2, 12 heads, and 4,096 tokens in FP16 with one write and read each of S and P. What are one score matrix, four-pass traffic, and FP32 LSE?
2.Merge online softmax states Block A (m=4, ell=2, N=10) and Block B (m=5, ell=1, N=-3) at reference m=5 (exp(-1) approx 0.367879).
3.An attention row has scores [0, ln(3)], values [4, 12], no dropout, and upstream gradient dO = 2. What are D, dS, and dV?
4.One causal tile covers Q 32..47 and K 25..32. Separately, a 5x5 square aligned grid runs causal attention. How is the single tile handled, and how many 5x5 pairs run vs. skip?
5.During eval decode, one query at position 2 attends over 5 cache slots (0..2 valid, zero scores, values [64, 24, 32, 100, 100]). Which PyTorch SDPA output and arguments are right?

5 questions remaining.

References

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

Dao, T., Fu, D. Y., Ermon, S., Rudra, A., Ré, C. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.14135

torch.nn.functional.scaled_dot_product_attention

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html

NVIDIA Hopper Tuning Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/hopper-tuning-guide/index.html

H100 GPU

NVIDIA · 2026

https://www.nvidia.com/en-us/data-center/h100/

FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning.

Dao, T. · 2023 · ICLR 2024

https://arxiv.org/abs/2307.08691

FlashAttention

Dao-AILab · 2026

https://github.com/Dao-AILab/flash-attention

FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision.

Shah, J., Bikshandi, G., Zhang, Y., Thakkar, V., Ramani, P., & Dao, T. · 2024

https://arxiv.org/abs/2407.08608

FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling

Ted Zadouri, Markus Hoehnerbach, Jay Shah, Timmy Liu, Vijay Thakkar, Tri Dao · 2026 · arXiv

https://arxiv.org/abs/2603.05451

Transformers: Attention Backends

Hugging Face · 2026

https://huggingface.co/docs/transformers/en/attention_interface

torch.backends.cuda: SDPA backend eligibility

PyTorch · 2026

https://docs.pytorch.org/docs/stable/backends.html

Accelerating PyTorch 2 Transformers with torch.compile and scaled_dot_product_attention

PyTorch Contributors · 2026

https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.