AI
Flash Attention: How It Makes Transformers Faster
Flash attention explained: how tiling and on-chip memory make exact attention faster and leaner, what changed in versions 2 to 4, and how to use it.
Flash attention is a faster way for a GPU to compute the attention step in a transformer, without changing the result. Standard attention builds a huge table of scores between every pair of tokens and writes it to the GPU's main memory, then reads it back. Flash attention instead works through the calculation in small tiles that fit in the GPU's tiny, very fast on-chip memory, so that table is never stored in full. The answer is mathematically the same (it's "exact" attention, not an approximation), but it moves far less data, runs several times faster on long sequences and uses memory that grows linearly with length instead of quadratically.
Introduced by Tri Dao and colleagues in 2022, FlashAttention is now built into PyTorch, Hugging Face Transformers, vLLM, llama.cpp and Ollama. This guide explains why standard attention is slow, how flash attention works step by step, what changed in versions 2, 3 and 4, how it compares with PyTorch's SDPA and with paged attention, and how to turn it on.
Flash Attention at a Glance
| Version | Year | Main idea | Hardware focus | Reported result |
|---|---|---|---|---|
| FlashAttention | 2022 | IO-aware tiling: keep attention blocks in on-chip SRAM | NVIDIA Ampere-era GPUs | 15% faster end-to-end BERT-large training than the MLPerf 1.1 record, 3x faster GPT-2 training at 1K tokens |
| FlashAttention-2 | 2023 | Better work partitioning across thread blocks and warps, fewer non-matmul operations | Ampere, Ada, Hopper | About 2x faster than v1; 50–73% of A100 peak; up to 225 TFLOPs/s per A100 in GPT training |
| FlashAttention-3 | 2024 | Asynchrony with Tensor Cores and TMA, FP8 support | Hopper (H100, H800) | 1.5–2.0x faster than v2 on H100; up to 740 TFLOPs/s in FP16, close to 1.2 PFLOPs/s in FP8 |
| FlashAttention-4 | After v3 | Written in NVIDIA's CuTe DSL | Hopper and Blackwell (H100, B200) | Distributed as the separate flash-attn-4 package |
Sources: the FlashAttention, FlashAttention-2 and FlashAttention-3 papers on arXiv, and the official repository README.
Why Standard Attention Is Slow
Attention compares every token with every other token. For a sequence of N tokens, each attention head computes an N × N matrix of scores, applies softmax to each row, then multiplies by the values. Our explainer on the attention mechanism covers the maths in plain terms.
The problem isn't only the amount of arithmetic. It's where the data lives. A GPU has two very different kinds of memory:
- HBM (high-bandwidth memory): tens of gigabytes, but every read and write takes time. See our guide to HBM memory.
- On-chip SRAM: only a few hundred kilobytes per processing unit, but far faster to access.
A straightforward attention implementation writes the full score matrix to HBM, reads it back for softmax, writes the result and reads it again for the final multiplication. At 8,192 tokens, one head's score matrix has 67 million entries, about 128 MiB in 16-bit precision. With 32 heads, that's around 4 GiB per layer for one sequence, moved back and forth through HBM. The GPU spends much of its time waiting on memory, not computing.
The FlashAttention paper's key insight was that attention should be IO-aware: designed around reads and writes between memory levels, not just around the number of operations.
How Flash Attention Works
Flash attention fuses the whole attention computation into a single GPU kernel built on three techniques.
1. Tiling. Queries, keys and values are split into blocks small enough to fit in SRAM. The kernel loads one block of queries, then loops over blocks of keys and values. For each pair it computes the partial scores, applies softmax and accumulates the output, all on-chip. Only the final output goes back to HBM.
2. Online softmax. Softmax normally needs the whole row of scores, because it divides by their sum. Flash attention keeps a running maximum and running sum for each row and rescales the partial results as each new block arrives. When the last block is done, the output is exactly what full softmax would have produced.
3. Recomputation in the backward pass. Training needs the attention matrix again to compute gradients. Instead of storing it, flash attention stores only small per-row statistics and recomputes the needed blocks during the backward pass. That's more arithmetic but far less memory traffic, and on modern GPUs the trade pays off.
The results:
- Memory: linear in sequence length instead of quadratic, because the N × N matrix is never materialised.
- Speed: far fewer HBM reads and writes, so wall-clock time drops even though some computation is repeated.
- Exactness: the output matches standard attention, up to normal floating-point differences.
What flash attention doesn't change is the number of attention operations, which still grows with the square of the sequence length. It makes that work far more efficient; it doesn't make it disappear.
What Is Flash Attention 2?
What is Flash Attention 2? It's the 2023 rewrite of the original kernel that roughly doubled its speed. The authors found that version 1 reached only 25–40% of the GPU's theoretical throughput, because work wasn't split well across the GPU's thread blocks and warps. FlashAttention-2:
- reduced non-matrix-multiply operations, which are slow on Tensor Core GPUs,
- parallelised a single head's computation across more thread blocks, keeping the GPU busy even with small batches,
- split work within each block across warps so they share less memory.
The paper reports about 2x speedup over version 1 and 50–73% of an A100's theoretical maximum. It also reports end-to-end training of GPT-style models at up to 225 TFLOPs/s per A100, 72% model FLOPs utilisation. FlashAttention-2 also added support for larger head dimensions, and it's the version most libraries mean when they say "flash attention".
FlashAttention-3 targets NVIDIA's Hopper GPUs. It overlaps data movement with computation using Hopper's asynchronous features, interleaves matrix multiplications with softmax, and adds FP8 support. The authors report 1.5–2.0x speedups over version 2 on H100, and 2.6x lower numerical error than a baseline FP8 attention.
FlashAttention-4 is written in NVIDIA's CuTe DSL and optimised for Hopper and Blackwell GPUs such as the H100 and B200. It ships as its own package.
Flash Attention vs SDPA
Flash attention vs SDPA is a common question in PyTorch code, but it's not either-or. torch.nn.functional.scaled_dot_product_attention (SDPA) is PyTorch's built-in attention function. Behind it, PyTorch can dispatch to several backends:
| SDPA backend | What it is |
|---|---|
FLASH_ATTENTION | A flash attention kernel built into PyTorch |
EFFICIENT_ATTENTION | A memory-efficient attention kernel, also tiled |
CUDNN_ATTENTION | NVIDIA's cuDNN fused attention |
MATH | The plain reference implementation |
PyTorch picks the best available backend for your GPU, data type and inputs. You can force or restrict it with a context manager:
import torch
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend
q = torch.randn(1, 32, 4096, 128, device="cuda", dtype=torch.bfloat16)
k = torch.randn(1, 32, 4096, 128, device="cuda", dtype=torch.bfloat16)
v = torch.randn(1, 32, 4096, 128, device="cuda", dtype=torch.bfloat16)
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)The separate flash-attn package from the FlashAttention authors usually gets new features and GPU generations first. In Hugging Face Transformers, you choose between them with attn_implementation: "sdpa" uses PyTorch's function, while "flash_attention_2" uses the flash-attn package.
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.2-1B",
dtype="bfloat16",
attn_implementation="flash_attention_2",
)For most users, SDPA is the easy default: no extra install and it already uses flash-style kernels where possible. Install flash-attn when you need its newest features, specific head sizes or the best speed on supported GPUs.
Flash Attention vs Paged Attention
Flash attention vs paged attention compares two techniques that solve different problems, and serving systems use both together:
| Flash attention | Paged attention | |
|---|---|---|
| Problem solved | Slow, memory-hungry attention computation | Wasted and fragmented KV cache memory when serving many requests |
| Where it acts | Inside the attention kernel | In how the KV cache is laid out in GPU memory |
| Main benefit | Faster training and prefill, lower activation memory | More concurrent requests per GPU, cache sharing across requests |
| Introduced by | Dao et al., 2022 | vLLM team, 2023 |
Paged attention splits each request's key-value cache into fixed-size blocks, like pages in an operating system, so memory isn't reserved in large contiguous chunks. Flash attention makes the arithmetic over those keys and values fast. Engines like vLLM combine paged memory management with flash attention kernels, and Hugging Face Transformers offers paged versions of its attention backends too.
How to Install Flash Attention
Here's how to install flash attention for the main versions, following the official repository:
- FlashAttention-2:
pip install flash-attn --no-build-isolation. It requires a CUDA toolkit or ROCm toolkit, PyTorch, and thepackaging,psutilandninjaPython packages. Building from source is slow and memory-hungry; the README suggests limiting parallel jobs, for exampleMAX_JOBS=4 pip install flash-attn --no-build-isolation, on machines with limited RAM. - Supported GPUs: Ampere, Ada and Hopper (A100, RTX 3090, RTX 4090, H100), with FP16 and BF16. Turing GPUs (T4, RTX 2080) are covered by a separate community repository with a subset of features.
- AMD: a ROCm version of FlashAttention-2 with Composable Kernel and Triton backends, for ROCm 6.0 and later.
- FlashAttention-3: a beta for H100 and H800 GPUs with CUDA 12.3 or later, built from the
hopperfolder of the repository. - FlashAttention-4:
pip install flash-attn-4.
You often don't need to install anything:
- PyTorch SDPA includes flash attention kernels.
- llama.cpp has a
-fa/--flash-attnoption (on, off or auto). - Ollama uses flash attention automatically when the backend supports it. You can force it with
OLLAMA_FLASH_ATTENTION=1, and it must be on to use a quantized KV cache.
Limits and Common Mistakes
- Expecting it to shrink the KV cache. Flash attention cuts the memory used during the attention computation. It doesn't reduce the key-value cache stored during generation; that needs grouped-query attention, paging or cache quantization.
- Expecting big gains on short sequences. The benefit grows with sequence length. For short prompts, attention is a small share of total time.
- Unsupported hardware or data types. Older GPUs, FP32 or unusual head sizes can silently fall back to slower kernels. Check which backend actually ran.
- Custom attention masks. Some arbitrary masks and attention variants aren't supported by every flash kernel. Causal masks, sliding windows and common patterns usually are.
- Mismatched builds. A
flash-attnwheel built for a different PyTorch or CUDA version fails to import or crashes. Match versions, or rely on SDPA. - Assuming it's approximate. It isn't. If outputs differ noticeably from standard attention, look for a bug or precision issue, not "flash attention error".
FAQ
Is flash attention an approximation?
No. Flash attention computes exact attention. It reorders the computation and keeps intermediate results in fast on-chip memory, so the output matches standard attention apart from tiny floating-point differences.
Does flash attention help inference or only training?
Both. It speeds up training and the prefill step of inference, where long prompts are processed at once. During token-by-token decoding, memory bandwidth for reading the KV cache usually dominates, and specialised decode kernels matter more.
Does flash attention work on consumer GPUs?
Yes, on supported architectures. FlashAttention-2 supports NVIDIA Ampere and Ada cards such as the RTX 3090 and RTX 4090. Tools like llama.cpp and Ollama can use flash attention on many consumer GPUs and Apple silicon through their own kernels.
Do I need flash attention if I use PyTorch SDPA?
Often not. SDPA already dispatches to a flash attention backend when your GPU and inputs support it. The separate package is useful for newer features and the fastest kernels on supported hardware.
Who created FlashAttention?
Tri Dao and colleagues introduced FlashAttention in 2022, and Tri Dao wrote FlashAttention-2. FlashAttention-3 was a collaboration led by Jay Shah with Tri Dao and co-authors from industry, including NVIDIA and Meta.