Standard multi-head self-attention in the Transformer architecture exhibits quadratic time and memory complexity with respect to sequence length . While the computational complexity is widely cited, the primary performance bottleneck in production hardware is not arithmetic throughput, but memory access overhead. On modern GPU architectures such as NVIDIA A100 and H100, tensor processing cores execute matrix multiplications at teraflop and petaflop scales, but memory bandwidth between High Bandwidth Memory (HBM) and on-chip SRAM remains the binding constraint.
Standard implementations of self-attention materialize the intermediate attention score matrix and the subsequent softmax probability matrix in HBM. This causes excessive read and write traffic, reducing hardware utilization to a fraction of theoretical peak compute.
FlashAttention, introduced by Tri Dao et al. (2022), addresses this bottleneck through an IO-aware algorithm that computes exact attention without materializing the intermediate matrices in global GPU memory. By leveraging online softmax normalization, SRAM block tiling, and selective activation recomputation in the backward pass, FlashAttention reduces memory accesses from quadratic to sub-quadratic , where is SRAM capacity and is head dimension. The resulting mechanism achieves 2x to 4x wall-clock speedups over standard attention while retaining exact mathematical equivalence. Subsequent iterations, including FlashAttention-2 and FlashAttention-3, further optimized work partitioning, warp-level scheduling, asynchronous memory transfers, and low-precision floating-point formats.
1. The Hardware Bottleneck: GPU Memory Hierarchies and Rooflines
To understand why standard attention scales poorly, one must evaluate the physical memory hierarchy of modern computing accelerators.
+-----------------------------------------------------------------------+
| GPU Global Memory (HBM3 / HBM2e) |
| Capacity: 40 GB - 141 GB | Bandwidth: 1.5 TB/s - 4.8 TB/s |
+-----------------------------------------------------------------------+
|
| High Latency / Limited Bandwidth
v
+-----------------------------------------------------------------------+
| Streaming Multiprocessor (SM) On-Chip SRAM (Shared Memory / L1 Cache) |
| Capacity: 192 KB - 228 KB per SM | Bandwidth: ~19 TB/s aggregate |
+-----------------------------------------------------------------------+
|
| Low Latency / Extremely High Bandwidth
v
+-----------------------------------------------------------------------+
| Tensor Cores / Compute Registers |
| Arithmetic Throughput: 312 TFLOPS (A100 FP16) - 1,979 TFLOPS (H100) |
+-----------------------------------------------------------------------+Memory Hierarchy Characteristics
A modern GPU divides memory into distinct tiers:
- High Bandwidth Memory (HBM): Main device memory. It provides high capacity (for example, 80 GB on an A100 SXM4 or 141 GB on an H100 SXM5) but relatively constrained bandwidth (2.0 TB/s on A100; 3.35 TB/s on H100).
- On-Chip Shared Memory / L1 Cache (SRAM): Located directly on each Streaming Multiprocessor (SM). An A100 contains 108 SMs with 192 KB of configurable shared memory per SM (approx. 20 MB total on-chip), delivering roughly 19 TB/s of aggregate bandwidth.
- Register Files: The fastest memory, coupled directly to execution pipelines.
The Roofline Model and Arithmetic Intensity
Under the Roofline Model, an operation's attainable performance (FLOP/s) is bounded by:
where arithmetic intensity is defined as:
For an NVIDIA A100 GPU running FP16 Tensor Core math:
- Peak Compute: 312 TFLOPS ( FLOP/s)
- Peak Memory Bandwidth: 2.0 TB/s ( B/s)
- Machine Balance / Threshold Intensity:
Any kernel with an arithmetic intensity below 156 FLOPs/byte on an A100 is memory-bandwidth bound.
Standard Self-Attention Memory Flow
Given input representations for queries , keys , and values in (for sequence length and head dimension ), the standard attention computation follows:
In standard PyTorch implementations:
- Load and from HBM, compute , and write of size back to HBM.
- Load from HBM, compute , and write of size back to HBM.
- Load and from HBM, compute , and write of size back to HBM.
For sequence length and :
- Total FLOPs: FLOPs.
- HBM Data Transferred (FP16): Loading and storing and ( bytes) plus loading and storing ( bytes). The terms require MB of HBM traffic.
- Arithmetic Intensity:
Because , standard attention operates deep in the memory-bound regime. Most GPU execution cycles are spent stalling while waiting for DRAM transfers.
2. The Online Softmax Formulation
The key obstacle to computing attention entirely inside fast SRAM is the softmax operator. Given a vector , the standard three-pass softmax requires global reduction:
Computing and requires full visibility of all elements before any single output probability can be normalized. In naive block-based execution, this would necessitate writing intermediate scores to HBM between passes.

Derivation of the Incremental Online Normalizer
FlashAttention adopts the online softmax formulation established by Milakov and Gimelshein (2018) and Rabe and Staats (2021).
Suppose a row vector is partitioned into two contiguous blocks and , such that .
For block 1:
- Local maximum:
- Local unnormalized sum:
When block 2 is loaded:
- Block maximum:
- Block unnormalized sum:
The combined global maximum across both blocks is:
To combine the partition sums and , they must be rescaled to the unified baseline :
General Recurrence for Arbitrary Sequence Blocks
For a sequence partitioned into blocks , the online recurrence maintains running statistics at step :
with base initializations and .
Output Vector Update and Rescaling
The attention output for a single query row is .
Let be the unnormalized accumulator for the first blocks scaled to max :
When the -th block of keys and values is processed:
- Compute local dot products:
- Find local block maximum:
- Update running maximum:
- Compute unnormalized exponents for current block:
- Rescale previous accumulator and add new contribution:
- Update normalizer:
After iterating through all blocks, the exact attention output vector is obtained by a single element-wise division:
This recurrence produces the exact same numerical result as standard softmax attention, without ever storing the full score matrix.
3. FlashAttention Forward Algorithm and Tiling
The FlashAttention forward pass coordinates this online formulation across matrices loaded in SRAM-sized tiles.
+-----------------------------------------------------------------------------------+
| FlashAttention Forward Tiling Schema |
+-----------------------------------------------------------------------------------+
Query Blocks (Outer/Inner Loop): Tile size Br x d
Key/Value Blocks: Tile size Bc x d
K_1 K_2 K_3 ... K_Tc
+----------+----------+----------+ +----------+
| Bc x d | Bc x d | Bc x d | | Bc x d |
+----------+----------+----------+ +----------+
Q_1| Tile S_11 Tile S_12 Tile S_13 Tile S_1Tc | -> O_1 (Br x d)
Q_2| Tile S_21 Tile S_22 Tile S_23 Tile S_2Tc | -> O_2 (Br x d)
Q_3| Tile S_31 Tile S_32 Tile S_33 Tile S_3Tc | -> O_3 (Br x d)
...|
Q_Tr| Tile S_r1 Tile S_r2 Tile S_r3 Tile S_rTc | -> O_Tr (Br x d)
Each SM loads Q_i into SRAM, then streams K_j, V_j blocks, updating
running statistics (m_i, l_i) and accumulator O_i purely within SRAM.Tile Size Selection
Given on-chip SRAM capacity (bytes), block dimensions (rows of ) and (columns of ) are bounded by:
Typically, block sizes are configured as such that , local score tile , and output accumulator fit simultaneously in shared memory.
Step-by-Step Forward Pass Procedure
Input: Q, K, V in HBM (size N x d), SRAM capacity M.
Initialize: O = 0 in HBM (N x d), l = 0 in HBM (N), m = -inf in HBM (N).
Set tile dimensions: Bc = ceil(M / (4d)), Br = min(ceil(M / (4d)), d).
Divide Q into Tr = ceil(N / Br) blocks: Q_1, ..., Q_Tr.
Divide K, V into Tc = ceil(N / Bc) blocks: K_1, ..., K_Tc and V_1, ..., V_Tc.
For j = 1 to Tc:
1. Load K_j, V_j from HBM into SRAM.
For i = 1 to Tr:
a. Load Q_i, O_i, l_i, m_i from HBM into SRAM.
b. Compute S_ij = (Q_i K_j^T) / sqrt(d) in SRAM (size Br x Bc).
c. Compute m_tilde_ij = rowmax(S_ij) in SRAM (size Br).
d. Compute P_tilde_ij = exp(S_ij - m_tilde_ij) in SRAM (size Br x Bc).
e. Compute l_tilde_ij = rowsum(P_tilde_ij) in SRAM (size Br).
f. Compute new running max:
m_i^new = max(m_i, m_tilde_ij)
g. Compute new running normalizer:
l_i^new = exp(m_i - m_i^new) * l_i + exp(m_tilde_ij - m_i^new) * l_tilde_ij
h. Update output tile in SRAM:
O_i = diag(exp(m_i - m_i^new)) * O_i + exp(m_tilde_ij - m_i^new) * (P_tilde_ij * V_j)
i. Write m_i = m_i^new, l_i = l_i^new, and O_i back to HBM.
Final normalization: For each row i, compute O_i = diag(l_i)^(-1) * O_i in HBM.4. Backward Pass and Selective Activation Recomputation
In standard backpropagation through attention, the forward pass must cache the entire attention probability matrix in HBM so the backward pass can compute:
This caching requirement enforces an memory footprint per attention head, causing out-of-memory (OOM) errors during long-sequence training.
Standard Attention Backward Pass:
Forward: Store P (N x N) in HBM -> Memory: O(N^2)
Backward: Load P (N x N) from HBM -> IO: O(N^2)
FlashAttention Backward Pass:
Forward: Store only m, l in HBM (size N) -> Memory: O(N)
Backward: Load Q_i, K_j from HBM, recompute S_ij and P_ij in SRAM on the fly -> IO: O(N^2 d^2 / M)Recomputing Attention in SRAM
FlashAttention eliminates the memory footprint by discarding after the forward pass. Instead, it only writes the normalization statistics to HBM, which scales linearly as .
During the backward pass:
- Block tiles and upstream gradient are loaded into SRAM.
- The score tile is recomputed directly in SRAM.
- Using cached values and , the exact softmax probabilities are reconstructed:
- Gradients are computed entirely in SRAM and accumulated into HBM.
Gradient Derivation with Recomputed Statistics
Let . The gradient with respect to pre-softmax score matrix tile simplifies to:
By calculating prior to the inner loop over blocks, the kernel computes in SRAM without extra global memory transactions.
Recomputation Trade-Off Analysis
Although recomputing in the backward pass adds FLOPs (a 33% increase in backward FLOP count), it completely removes memory reads from HBM. Because the attention backward pass on GPUs is heavily memory-bound, eliminating HBM reads results in a net wall-clock speedup of 2x or more despite the extra arithmetic operations.
5. Algorithmic Evolution: FlashAttention-1, 2, and 3
The FlashAttention methodology has undergone three major architectural revisions to match evolving GPU hardware capabilities.
| Feature | FlashAttention-1 (2022) | FlashAttention-2 (2023) | FlashAttention-3 (2024) | | :--- | :--- | :--- | :--- | | Primary Target | NVIDIA Ampere (A100) | NVIDIA Ampere / Ada | NVIDIA Hopper (H100/H200) | | Outer Loop Dimension | blocks | blocks | blocks | | SM Parallelization | Batch, Heads | Batch, Heads, SeqLen () | Batch, Heads, SeqLen () | | SRAM Accumulator | Unscaled rescaled per step | Scaled by normalizer at end | Scaled by normalizer at end | | Hardware Specialization| Standard Tensor Cores | Optimized Warp Partitioning | TMA + WGMMA + FP8 Tensor Cores | | Asynchrony Model | Synchronous compute/load | Synchronous compute/load | Asynchronous ping-pong pipeline | | FP16 Peak Utilization | 30% - 40% on A100 | 50% - 73% on A100 | Up to 85% on H100 (840 TFLOPS) |
FlashAttention-2: Inverted Loops and Sequence Parallelism
FlashAttention-2 identified several hardware inefficiencies in the original algorithm:
- Loop Inversion: FlashAttention-1 placed blocks in the outer loop and blocks in the inner loop to save memory writes. However, this required frequent shared memory updates for . FlashAttention-2 moves to the outer loop and to the inner loop. An SM loads once into registers and streams across it, keeping in registers until fully computed.
- Parallelization Across Sequence Length: When batch size number of heads is small (e.g., during long-context single-batch inference or multi-query attention), FlashAttention-1 underutilized GPU SMs. FlashAttention-2 parallelizes across the sequence length dimension of , ensuring all SMs remain saturated even for batch size 1.
- Warp-Level Matrix Partitioning: In FlashAttention-1, warps within a thread block shared intermediate matrix multiplications, requiring synchronizations (
__syncthreads()). FlashAttention-2 splits across warps so each warp computes local GEMMs without cross-warp synchronization during the and steps.
FlashAttention-3: Hopper Architecture and Asynchronous Pipelining
FlashAttention-3 targets the NVIDIA Hopper (H100) architecture, which introduced structural hardware primitives:
- Tensor Memory Accelerator (TMA): A hardware engine that transfers multi-dimensional tensor blocks between global memory (HBM) and shared memory (SRAM) asynchronously without consuming SM instruction issues or register files.
- Warp-Group Matrix Multiply and Accumulate (WGMMA): Instructions executed by a collective of four warps (128 threads) operating directly on shared memory matrices without register staging.
- Warp Specialization: FlashAttention-3 partitions threads in a thread block into dedicated producer warps (issuing TMA loads) and consumer warps (executing WGMMA instructions), eliminating pipeline bubbles through circular shared-memory buffers.
- Interleaved Softmax and Matmul: Hopper Tensor Cores and vector ALUs operate asynchronously. FlashAttention-3 overlaps the softmax exponentiation of block on the ALU with the matrix multiplication on the Tensor Cores.
- Low-Precision FP8 Attention with Incoherent Processing: FP8 quantization introduces numerical instability in attention due to large outlier activations. FlashAttention-3 applies randomized Hadamard transformations () to spread activation energy across dimensions, preventing underflow/overflow in 8-bit formats and reaching 1.3 PFLOPS on H100.
6. Theoretical IO Complexity Bounds
The primary theoretical contribution of IO-aware attention is bounding memory access volume relative to SRAM size .
Let be sequence length, be head dimension, and be SRAM capacity in elements, with .
Standard Attention IO Complexity
Standard attention writes and reads intermediate matrices to HBM:
For long sequences where , IO complexity is dominated by .
FlashAttention IO Complexity
In FlashAttention, is split into blocks and into blocks, with .
- Number of block pairs: .
- Data loaded per block pair: .
- Total HBM memory accesses:
Lower Bound Optimality
Dao et al. proved via the Hong-Kung pebbling game that for any algorithm computing exact attention with SRAM of size , the minimum number of HBM accesses is:
FlashAttention asymptotically matches this theoretical lower bound. The reduction factor in memory traffic relative to standard attention is:
For typical parameters ( elements, ), , explaining the massive empirical reduction in DRAM traffic.
7. Systems Impact and Production Implementations
The development of IO-aware attention fundamentally reshaped modern LLM architectures, serving systems, and context window economics.
+-----------------------------------------------------------------------------------+
| Production Serving and Training Stack Integration |
+-----------------------------------------------------------------------------------+
| Large Language Models: Llama 3, DeepSeek-V3, Claude, GPT-4, Mistral |
+-----------------------------------------------------------------------------------+
| Distributed Frameworks: Megatron-LM, DeepSpeed, PyTorch FSDP |
+-----------------------------------------------------------------------------------+
| Serving Engines: vLLM, SGLang, TensorRT-LLM, TGI |
+-----------------------------------------------------------------------------------+
| Core Kernels: FlashAttention-2/3, FlashDecoding, PyTorch SDPA, CUTLASS |
+-----------------------------------------------------------------------------------+Context Length Scaling
Prior to FlashAttention, standard model context windows were constrained to 2,048 or 4,096 tokens (e.g., original GPT-3 and OPT). Storing the attention matrix for across 32 layers and 32 heads in 16-bit precision would require:
This rendered full-context training impossible without extreme tensor model parallelism. By reducing activation memory from to (storing only ), FlashAttention made 32K, 128K, and 1M+ context windows computationally tractable on standard GPU clusters.
FlashDecoding for Inference Prefill and Generation
During LLM autoregressive generation (decode phase), the query sequence length is , while the key-value sequence length grows with context history. Because , standard FlashAttention parallelization over cannot utilize multiple SMs.
To address this, Flash-Decoding introduces parallelization across the sequence dimension:
- The KV cache is split into chunks.
- Each chunk computes partial attention outputs and running statistics in parallel across separate SMs using online softmax.
- A final reduction kernel combines the partial outputs using the online softmax combination equations:
This achieves near-constant generation latency as context length scales up to 64K tokens, eliminating the generation bottleneck in production inference engines like vLLM and SGLang.
Sources
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Dao et al., NeurIPS 2022)
- FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (Dao, ICLR 2024)
- FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (Shah et al., NeurIPS 2024)
- Online Normalizer Calculation for Softmax (Milakov & Gimelshein, 2018)
- Self-attention Does Not Need Memory (Rabe & Staats, 2021)
- Attention Is All You Need (Vaswani et al., NeurIPS 2017)
- Roofline: An Insightful Visual Performance Model for Floating-Point Programs on Multicore Architectures (Williams et al., CACM 2009)
- Flash-Decoding for Fast Generation with Long Contexts (Dao et al., Stanford CRFM 2023)



