Skip to content
E
Educatum

How does FlashAttention optimize self-attention, and what are its hardware trade-offs?

Curated by Educatum AI teamLast updated:
HardwareInference
Direct Answer

Standard self-attention materializes the full N×N attention matrix in slow High Bandwidth Memory (HBM), creating a severe memory-bandwidth bottleneck. FlashAttention restructures attention into an IO-aware tiled kernel that keeps Q, K, and V blocks in fast on-chip SRAM, computes exact attention incrementally via online softmax, and recomputes the attention matrix during backpropagation instead of storing it. This reduces HBM accesses to Θ(N²d²/M) and memory footprint from O(N²) to O(N) without changing the mathematical output.

Standard self-attention is expensive because its time and space complexities scale quadratically with sequence length NN. It materializes the full N×NN \times N attention matrix in High Bandwidth Memory (HBM), which is orders of magnitude slower than on-chip SRAM. FlashAttention (Dao et al., 2022) restructures exact self-attention into an IO-aware tiled kernel that minimizes transfers between slow HBM and fast on-chip SRAM:

  • Concrete GPU Memory Hierarchy (A100 / H100): An NVIDIA A100 (80 GB HBM2e, ~2.0 TB/s) or H100 (80 GB HBM3, ~3.35 TB/s) only provides ~192–228 KB of fast on-chip SRAM / shared memory per SM (~20–30 MB aggregate across all SMs at >19 TB/s effective bandwidth). For N=16kN = 16\text{k} in fp16 across 32 heads, just one N×NN \times N score matrix takes 16 GiB16\text{ GiB}—far larger than SRAM—forcing slow HBM round-trips.
  • Tiling: FlashAttention splits QQ into blocks of size BrB_r and K,VK, V into blocks of size BcB_c so each active tile satisfies the SRAM budget Brd+Bcd+BrBc≲MB_r d + B_c d + B_r B_c \lesssim M (e.g., Bc=⌈M/(4d)⌉B_c = \lceil M / (4d) \rceil, Br=min⁡(⌈M/(4d)⌉,d)B_r = \min(\lceil M / (4d) \rceil, d)), computing exact attention inside SRAM without ever writing the N×NN \times N matrix to HBM.
  • Recomputation: During the backward pass, instead of saving the O(N2)O(N^2) probability matrix from forward, FlashAttention stores only the O(N)O(N) per-row log-sum-exp normalization statistics (m,ℓ)(m, \ell) (plus OO) and recomputes the attention blocks on the fly inside SRAM, trading extra FLOPs for massive HBM bandwidth savings.

Limitations & Caveats

  • Performance gains depend on sequence length NN, head dimension dd, and SRAM capacity MM. For very short sequences, standard unfused kernels or cuBLAS GEMMs can match or beat FlashAttention due to kernel launch overhead.
  • Efficiency peaks when d∈{64,128}d \in \{64, 128\} so Q,K,VQ, K, V tiles fit comfortably in SM shared memory; larger head dimensions shrink tile sizes and reduce arithmetic intensity.

Core Insights & Mathematical Foundations

[Standard Attention HBM Accesses]: Θ(Nd+N2)[FlashAttention HBM Accesses]: Θ ⁣(N2d2M) (for d≤M, where M is SRAM size and d is head dim)[Block Softmax Statistics]: Pblock=exp⁡(Sblock−mblock),lblock=rowsum⁡(Pblock)[Online Softmax (Maximum)]: mnew=max⁡(mold,mblock)[Online Softmax (Exp Sum)]: lnew=lold⋅emold−mnew+lblock⋅emblock−mnew[Rescaled Output]: Onew=lold⋅emold−mnew⋅Oold+emblock−mnew⋅PblockVblocklnew[FlashAttention-3 FP8 Scaling]: uses block-wise FP8 scaling factors and incoherent (Hadamard) processing to suppress outliers\begin{aligned} & \text{[Standard Attention HBM Accesses]: } \Theta(Nd + N^2) \\ & \text{[FlashAttention HBM Accesses]: } \Theta\!\left(\frac{N^2 d^2}{M}\right) \text{ (for } d \le M\text{, where } M \text{ is SRAM size and } d \text{ is head dim)} \\ & \text{[Block Softmax Statistics]: } P_{\text{block}} = \exp(S_{\text{block}} - m_{\text{block}}), \quad l_{\text{block}} = \operatorname{rowsum}(P_{\text{block}}) \\ & \text{[Online Softmax (Maximum)]: } m_{\text{new}} = \max(m_{\text{old}}, m_{\text{block}}) \\ & \text{[Online Softmax (Exp Sum)]: } l_{\text{new}} = l_{\text{old}} \cdot e^{m_{\text{old}} - m_{\text{new}}} + l_{\text{block}} \cdot e^{m_{\text{block}} - m_{\text{new}}} \\ & \text{[Rescaled Output]: } O_{\text{new}} = \frac{l_{\text{old}} \cdot e^{m_{\text{old}} - m_{\text{new}}} \cdot O_{\text{old}} + e^{m_{\text{block}} - m_{\text{new}}} \cdot P_{\text{block}} V_{\text{block}}}{l_{\text{new}}} \\ & \text{[FlashAttention-3 FP8 Scaling]: uses block-wise FP8 scaling factors and incoherent (Hadamard) processing to suppress outliers} \end{aligned}

Follow-up 1: Explain the online softmax technique and how tiling enables FlashAttention.

Standard softmax requires knowing the global maximum (m) and the sum of exponentials (l) of a row before computing probabilities. This creates a global barrier, forcing the model to read the entire row of Query-Key dot products before normalizing.

FlashAttention circumvents this using online softmax (Milakov & Gimelshein, 2018), which tracks running local statistics as it processes blocks. This enables numerically stable streaming computation without materializing the full attention row in HBM.

When a new block is processed, FlashAttention compares the new local maximum with the running maximum and rescales previously accumulated outputs using the exponential difference. This correction ensures mathematical equivalence to standard softmax while enabling block-by-block computation.


⚠️ Limitations & Caveats

  • Accumulating running statistics requires high precision. If tracked in low precision (e.g., fp16/bf16), the exponential sums may overflow or underflow; therefore, these statistics are typically maintained in fp32.

Follow-up 2: How do FlashAttention-2 and FlashAttention-3 address hardware underutilization?

The original FlashAttention suffered from hardware underutilization because it did not fully parallelize across sequence dimensions and spent cycles on non-matmul operations (e.g., softmax updates) on standard CUDA cores. FlashAttention-2 addressed these issues primarily on Ampere-class GPUs (e.g., A100), but did not exploit the new hardware primitives introduced in Hopper-class GPUs (e.g., H100), motivating FlashAttention-3.

  • FlashAttention-2 (Dao, 2023, arXiv:2307.08691): Parallelizes work across the sequence length dimension (Query blocks) rather than primarily over Key/Value blocks. It also reduces the number of rescaling operations in online softmax, improving Tensor Core utilization on Ampere GPUs.
  • FlashAttention-3 (Shah et al., 2024, arXiv:2407.08608): Targets NVIDIA Hopper (e.g., H100). It uses Tensor Memory Accelerator (TMA) to asynchronously move data from HBM to SRAM while Tensor Cores execute matrix multiplications, overlapping compute and memory transfer. It also introduces FP8 support with scaling for stability.

Dimension FlashAttention FlashAttention-2 FlashAttention-3
Computational Cost Moderate (some underutilization) Lower (optimized for Ampere/A100) Lowest (overlaps memory + compute on Hopper/H100)
Data Types bfloat16 / float16 bfloat16 / float16 bfloat16 / float16 / float8 (with scaling)
Known Limitation Limited parallelism Shared memory pressure / bank conflicts Hopper-specific optimizations, limited portability

Hardware Constraints

  • FlashAttention-3 is specialized for Hopper-class GPUs and relies on low-level hardware features (e.g., TMA), making it non-portable to older architectures (e.g., A100) or other accelerators.
  • FP8 introduces quantization noise; stable training requires careful block-wise scaling and Hadamard/incoherent transforms to handle outlier activations.

Tiled Forward Pass & PyTorch Implementation

# Conceptual tiled forward pass (FA-2 order: outer loop over Q blocks, inner over K/V blocks)
for i in range(0, N, B_r):
    Q_i = load_from_hbm(Q[i : i + B_r])          # stays in fast SRAM
    O_i = zeros((B_r, d), fp32)
    m_i = full((B_r, 1), -inf, fp32)
    l_i = zeros((B_r, 1), fp32)

    for j in range(0, N, B_c):
        K_j, V_j = load_from_hbm(K[j : j + B_c], V[j : j + B_c])
        S_ij = (Q_i @ K_j.T) * inv_sqrt_d        # computed in SRAM (B_r x B_c)
        m_new = maximum(m_i, rowmax(S_ij))
        P_tilde = exp(S_ij - m_new)
        alpha = exp(m_i - m_new)
        l_i = alpha * l_i + rowsum(P_tilde)
        O_i = alpha * O_i + P_tilde @ V_j        # unnormalized numerator in fp32
        m_i = m_new

    store_to_hbm(O[i : i + B_r], O_i / l_i)
    store_to_hbm(L[i : i + B_r], m_i + log(l_i)) # logsumexp for backward recompute

In production PyTorch (2.2+), scaled dot-product attention dispatches automatically to FlashAttention kernels when tensors are fp16/bf16 on CUDA with is_causal or supported masks:

import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

# q, k, v: (batch, n_heads, seq_len, head_dim) in bfloat16 on CUDA
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
    out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.