FlashAttention
A GPU kernel that computes exact attention block by block in fast on-chip memory, never writing the n×n score matrix out, so memory grows linearly with length and attention runs ~2–4× faster.
Analogy: Totalling a huge ledger page by page in your head, keeping only a running sum, instead of photocopying every page onto your desk first and then adding them up.
How it works
- It is exact attention, not an approximation: same result up to floating-point rounding.
- Attention is bottlenecked by memory traffic, not math: naive kernels write and reread the n×n scores in HBM.
- It splits Q, K and V into tiles that fit in on-chip SRAM and computes everything per tile there.
- An online softmax keeps a running max and sum, rescaling partial results as new K/V tiles stream in.
- Compute stays O(n²); memory and traffic drop, which made 32k–128k contexts practical.
Check yourself
Answer to mark it learned; your answers aren't scored.
A 16k-token fine-tune OOMs on an 80 GB H100, even though the model's attention calls PyTorch SDPA, which should dispatch to FlashAttention. The script loads the model with dtype=torch.float32. What's going on?
Go deeper
Full explanation
FlashAttention is a GPU kernel that computes exact standard Self-attention (same result up to floating-point rounding) much faster and with memory linear in sequence length. It is not an approximation like sparse or linear attention.
The insight is IO-awareness: on modern GPUs attention is bottlenecked by memory traffic, not math. The naive version writes the full n×n score matrix to HBM (the GPU's large, slow memory), reads it back for the softmax, writes the result, and reads it again to multiply by V. At 8k tokens that is ~67M scores per head, per layer.
FlashAttention tiles Q, K and V into blocks that fit in on-chip SRAM (~20 MB on an A100, roughly 10× HBM's bandwidth). For each tile it computes scores, softmax and the weighted sum, using an online softmax: a running max and sum rescale the partial results as new K/V tiles stream in. Only the final output is written back; the n×n matrix never exists in HBM. In training, the backward pass recomputes tiles instead of storing them.
Compute is still O(n²); what drops is memory footprint and traffic, which is what made 32k–128k contexts practical. FA-2 (2023) roughly doubled FA-1's speed with better parallelism; FA-3 (2024) targets Hopper with asynchronous copies and FP8. You rarely call it directly: PyTorch SDPA, vLLM and most serving stacks use it by default.
Code Using FlashAttention in PyTorch and Transformers
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import AutoModelForCausalLM
# 1) Raw kernel: PyTorch SDPA dispatches to a FlashAttention-2 kernel on supported GPUs
q = k = v = torch.randn(1, 32, 16_384, 128, device="cuda", dtype=torch.bfloat16) # (batch, heads, seq, dim)
with sdpa_kernel(SDPBackend.FLASH_ATTENTION): # force it: errors instead of silently falling back
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
# Naive attention would materialize 32 x 16k x 16k scores: ~17 GB in bf16. This never does.
# 2) In a model: request the kernel explicitly
MODEL = "meta-llama/Llama-3.1-8B-Instruct" # any decoder model
model = AutoModelForCausalLM.from_pretrained(
MODEL,
dtype=torch.bfloat16, # flash kernels need fp16/bf16, not fp32
attn_implementation="flash_attention_2", # needs `pip install flash-attn`; "sdpa" is the default
device_map="auto",
)
# 3) Serving: vLLM, SGLang and TensorRT-LLM already pick a flash kernel. Nothing to do.Real example
A team fine-tunes a 7B model (32 layers, 32 heads) on 16k-token contracts. With naive attention, one layer's score matrix is 32 × 16k × 16k × 2 bytes ≈ 17 GB in bf16, and the backward pass needs it kept for every layer: impossible on an 80 GB H100. With FlashAttention the extra state per layer is one softmax statistic per row (~2 MB), so the run fits at batch 1 with gradient checkpointing. Their first attempt still OOMed: the training script loaded the model in fp32, so SDPA quietly fell back to the math path.
Trade-offs +4 · −3
+ You gain
- Exact: no accuracy trade-off, a drop-in replacement for standard attention.
- Attention memory linear in length: ~10× less at 2k tokens and ~20× at 4k (FA-1).
- ~2–4× faster attention, and faster end-to-end training and prefill.
- On by default in PyTorch SDPA, vLLM, SGLang and TensorRT-LLM.
− You pay
- Compute is still O(n²): doubling the context still means ~4× the attention FLOPs.
- Hardware and dtype limits: FA-2 needs Ampere or newer and fp16/bf16; FA-3 targets Hopper.
- Doesn't shrink the KV cache, so long-context decode stays memory-bound.
Use it when
Always, for training and inference on Ampere-or-newer GPUs in fp16/bf16. Verify it is actually active when you fine-tune long-context models or write custom attention.
Avoid it when
Older GPUs (V100, T4) without FA-2 support, fp32 training, or attention variants with masks or biases the kernel doesn't support. And don't expect it to fix quadratic compute or KV-cache size.
Numbers to know 4
- A100: ~20 MB of on-chip SRAM at ~19 TB/s vs 40–80 GB of HBM at ~1.5–2 TB/s.
- FA-1: 3× faster GPT-2 training at 1k tokens; 10–20× attention memory saving at 2k–4k.
- FA-2: ~2× FA-1, reaching 50–73% of A100 peak FLOPs/s.
- FA-3 on H100: 1.5–2× FA-2, up to ~740 TFLOPs/s in FP16 (~75% utilization), ~1.2 PFLOPs/s in FP8.
Common pitfalls 4
- Calling it an approximation in an interview: it is exact attention computed in a different order.
- Silent fallback: fp32 tensors, a custom additive mask or an old GPU send SDPA to the slow math path. Force the backend in a test.
- Assuming it makes long context cheap: 128k-token prefill is still quadratic and still costly.
- Expecting big decode gains: decode is bound by reading the KV cache, which Flash-Decoding and paged kernels address.
Interview questions 2
Answer out loud first, then reveal.
Is FlashAttention an approximation? What exactly does it speed up?Show answer
No, it computes exact softmax attention; outputs match up to floating-point rounding. It speeds up memory traffic, not math. Naive attention writes the n×n score matrix to HBM and reads it back several times, and on GPUs that IO dominates. Tiling into on-chip SRAM with an online softmax means the matrix is never materialized, so memory becomes linear and attention runs 2–4× faster. FLOPs are still quadratic, which is why I still budget prefill cost carefully at 128k.
If every stack already uses FlashAttention, why should an architect care?Show answer
Three reasons. First, it is what makes long context feasible at all, so context-length decisions rest on it. Second, it falls back silently: fp32, a custom mask or a T4 sends you to the slow path, and a fine-tune OOMs at 8k for no obvious reason, so I assert the backend. Third, it helps training and prefill far more than decode, so for chat latency I look at KV-cache size, batching and speculative decoding instead.