4.5Long context & FlashAttention
Why attention gets expensive as contexts grow, how FlashAttention computes it exactly without ever writing the N×N matrix to memory, and what else makes million-token windows possible.
The quadratic wall
Self-attention computes a score between every query and every key: for a sequence of tokens, that’s an matrix per head per layer. At 4K tokens it has 16.8 million entries; at 128K tokens, 17 billion. In 16-bit precision, that one matrix would take 34 GB, for a single head of a single layer.
Two separate costs grow with :
- Compute. The score and weighted-sum products cost about FLOPs per head. This can’t be avoided while attention stays exact and full: every pair really is compared.
- Memory traffic. A straightforward implementation materializes the score matrix , writes it to GPU memory, reads it back for the softmax, writes the probabilities , then reads them again to multiply by . Those passes over numbers often take more time than the arithmetic itself.
The second cost turns out to be the one you can eliminate, and doing so made long contexts practical.
A chef has a small, very fast countertop and a huge pantry two floors down. A naive recipe says: chop everything, carry the full tray of chopped vegetables down to the pantry, carry it back up to season it, carry it down again, back up to cook. Most of the evening is spent on stairs.
A smart chef brings up one basket of ingredients at a time, finishes as much as possible on the counter, and keeps a running tally on a sticky note so earlier batches never need revisiting. The countertop is the GPU’s SRAM, the pantry is HBM, the baskets are tiles, and the sticky note is the online softmax’s running max and sum.
Where the time really goes: the memory hierarchy
A GPU has two very different kinds of memory. HBMHBM (high-bandwidth memory)The large main memory stacked next to a GPU (tens of GB, a few TB/s). It is much bigger but much slower than the on-chip SRAM inside each streaming multiprocessor. is the large main memory: the FlashAttention paper cites 40–80 GB at 1.5–2.0 TB/s for an A100. On-chip SRAM is tiny, 192 KB per streaming multiprocessor across 108 of them, but has an estimated bandwidth of around 19 TB/s, about 10× faster.
Matrix multiplication reuses each loaded number many times, so it keeps the arithmetic units busy. The softmax, masking and scaling steps do only a few operations per number, so they are memory-boundMemory-bound (vs compute-bound)A workload is memory-bound when its speed is limited by how fast data can be moved from memory, not by arithmetic. The deciding ratio is arithmetic intensity: FLOPs performed per byte moved.: their speed is set by how fast numbers move to and from HBM. Naive attention interleaves big matrix multiplies with exactly these cheap-but-bandwidth-hungry steps over entries, which is the worst possible combination.
FlashAttention: tile, stream, never materialize
FlashAttentionFlashAttentionAn exact attention algorithm that processes attention in tiles held in fast on-chip memory, avoiding materializing the full attention matrix. (Dao et al., 2022) fuses all of attention into one GPU kernel that keeps the intermediate results on-chip. The algorithm:
- Split into blocks of rows, and , into blocks of rows too.
- Load a block of queries into SRAM. Then stream key/value blocks through, one at a time.
- For each pair, compute the small tile of scores in SRAM, fold it into a running softmax and a running output, and throw the tile away.
- After the last key/value block, normalize the output rows once and write them to HBM.
Step 3 needs a trick, because softmax normalizes over the whole row and we only see a slice of it at a time. That trick is the online softmaxOnline softmaxComputing a softmax in one streaming pass by keeping a running maximum and running sum, and rescaling earlier partial results whenever the maximum grows. It is the trick that lets FlashAttention work tile by tile. (Milakov and Gimelshein, 2018). For each row, keep the largest score seen so far, , and the running sum of exponentials, . When a new tile brings a bigger maximum, multiply everything accumulated so far by to re-express it relative to the new maximum. The final result is identical to the ordinary softmax.
For training, the backward pass needs the attention probabilities again. Instead of storing them, FlashAttention recomputes them tile by tile from , , and the saved per-row and . That costs some extra FLOPs, but avoids reading an matrix, so it’s faster overall. Memory use becomes linear in instead of quadratic.
The traffic model is deliberately simple. Real unfused pipelines make extra passes over the N×N matrix (masking, dropout, separate softmax kernels), and the FlashAttention paper measured 40.3 GB versus 4.4 GB of HBM reads and writes for GPT-2 medium attention (forward and backward).
Things to try:
- Step through the first row of tiles. Watch the table: when a tile contains a larger score than any before, jumps and the rescale factor drops below 1, shrinking the old sum before adding the new terms.
- Compare causal and full. With the causal mask, tiles above the diagonal are skipped entirely: 10 of the 16 tiles remain with 2×2 blocks. Real kernels get close to a 2× saving this way.
- Watch the counters. Naive attention pushes every score through HBM four times. The tiled version moves only , , and .
- Slide the sequence length at real scale. The N×N matrix for one head at 128K tokens is 32 GiB. FlashAttention never allocates it.
The FlashAttention paper measured 40.3 GB versus 4.4 GB of HBM reads and writes for GPT-2 medium attention (forward and backward), with runtime falling from 41.7 ms to 7.3 ms, even though FlashAttention performed slightly more FLOPs because of recomputation.
Cheaper than full attention
FlashAttention makes exact attention fast, but compute is still , and the KV cache still grows linearly. For very long contexts, many models also change what is computed:
- Sliding-window attentionSliding-window attentionAttention in which each token only attends to the most recent W tokens, so cost and KV cache grow linearly rather than quadratically with context length.. Each token attends only to the previous tokens. Mistral 7B used ; because each layer can look tokens back, information can still travel further across layers (the paper notes a theoretical span of about 131K tokens across 32 layers). Gemma models interleave many local sliding-window layers with occasional global ones, which keeps most layers’ KV caches small.
- Sparse attention. Attend to a selected subset of positions: fixed patterns (as in the 2019 Sparse Transformer and Longformer), or learned selection, where a lightweight scorer picks the most relevant earlier tokens for each query. Several recent frontier and open models are reported to use learned sparse attention for long contexts. The details differ by model and are not always published.
- Linear attention and state-space models. Replace the growing cache with a fixed-size recurrent state updated token by token, giving linear time and constant memory per token. Pure versions (Mamba and relatives) tend to be weaker at exact recall from far back, so recent models often use hybrids: mostly linear-attention layers plus a few full-attention layers. See Qwen for an example.
Stretching the window: RoPE scaling
Models are pretrained mostly on shorter sequences, and RoPE encodes position as rotation angles that grow with position. Feed a model positions far beyond what it was trained on and it sees angles it has never encountered, and quality collapses. Context-extension methods rescale those angles:
- Position interpolation (Chen et al., 2023) squeezes the new, longer range of positions into the trained range, for example dividing every position by 4 to go from 4K to 16K, then fine-tunes briefly.
- NTK-aware scaling and YaRN (Peng et al., 2023) scale RoPE’s different frequencies by different amounts: high-frequency dimensions, which encode local order, are left mostly alone, while low-frequency ones are interpolated. YaRN reached long contexts with far less fine-tuning than earlier methods.
In practice, labs combine RoPE scaling with a dedicated long-context stage of continued pretraining on long documents.
Can the model actually use it?
A context window says how many tokens fit, not how well they’re used. The “Lost in the Middle” study (Liu et al., 2023) gave models multi-document question answering and moved the relevant document around. Accuracy was highest when the answer was near the beginning or end of the context and dropped noticeably in the middle, a U-shaped curve.
The popular needle-in-a-haystack test hides one fact in a long filler text and asks for it back. Modern models often score near-perfectly on it, which is why harder suites such as RULER (Hsieh et al., 2024) add multiple needles, tracing and aggregation tasks. RULER found that many models’ effective context, where performance stays high, is much shorter than the advertised window. Treat a model’s context length as an upper bound.
MATH CORNER · optionalOnline softmax, with numbers
For one query row with scores and values , attention computes . Process the scores in blocks, keeping a running max , a running sum and an unnormalized output . For each new block :
Start with , , . At the end, . Subtracting the running max keeps every exponent , so nothing overflows.
Worked example. One row, four keys in two blocks. Scores , scalar values .
| step | rescale | |||
|---|---|---|---|---|
| block 1: scores 1, 3 | 3 | (first block) | ||
| block 2: scores 2, 5 | 5 |
Result: .
Check against the direct computation with all four scores at once: weights , sum ; weighted values ; output . Identical, as promised.
In code
The core of FlashAttention, for one query block, written as plain PyTorch loops. Real kernels do this in SRAM, in parallel over query blocks, heads and batch.
import torch
def flash_attention_block(q, K, V, block=128):
"""q: (Bq, d) one query block; K, V: (N, d). Returns softmax(qK^T/sqrt(d)) V."""
d = q.shape[-1]
m = torch.full((q.shape[0], 1), float("-inf")) # running max per row
l = torch.zeros(q.shape[0], 1) # running sum of exps
o = torch.zeros(q.shape[0], d) # unnormalized output
for j in range(0, K.shape[0], block): # stream K/V blocks
s = q @ K[j:j + block].T / d ** 0.5 # score tile (lives in SRAM)
m_new = torch.maximum(m, s.max(dim=1, keepdim=True).values)
scale = torch.exp(m - m_new) # rescale old accumulators
p = torch.exp(s - m_new)
l = scale * l + p.sum(dim=1, keepdim=True)
o = scale * o + p @ V[j:j + block]
m = m_new
return o / l # normalize once at the end
q, K, V = torch.randn(64, 64), torch.randn(1000, 64), torch.randn(1000, 64)
ref = torch.softmax(q @ K.T / 8, dim=-1) @ V
print(torch.allclose(flash_attention_block(q, K, V), ref, atol=1e-5)) # True
- “FlashAttention approximates attention.” It computes exactly the same result as standard attention, up to floating-point rounding. The speedup comes from moving less data, not from skipping work.
- “FlashAttention reduces the FLOPs of attention.” It slightly increases them (recomputation in the backward pass). It is faster because naive attention is limited by memory traffic, not arithmetic.
- “FlashAttention removes the quadratic cost.” Compute is still ; what drops to linear is the extra memory. Sub-quadratic compute needs different attention patterns (sliding window, sparse, linear).
- “With sliding-window attention a model cannot use anything older than the window.” Each layer can pass information one window further back, so the effective receptive field grows with depth, though recall of distant details is weaker.
- “A 1M-token context window means the model reliably uses 1M tokens.” Evaluations like Lost in the Middle and RULER show performance often degrades well before the advertised limit, especially for information in the middle.
Check your understanding
Q1.What is the main reason FlashAttention is faster than a naive attention implementation?
Q2.During online softmax, the running max for a row goes from 3 to 5 after a new tile. What must happen to the running sum ℓ accumulated so far?
Q3.How does FlashAttention's memory use scale with sequence length N (for fixed head dim)?
Q4.What did the 'Lost in the Middle' study find?
Q5.Why do RoPE-based models need special handling (such as position interpolation or YaRN) to go beyond their training context?
Further reading
- paperFlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — Dao et al., 2022: tiling, online softmax and recomputation.
- paperFlashAttention-2 — Better parallelism and work partitioning.
- paperFlashAttention-3 — Asynchrony and FP8 on Hopper GPUs.
- paperOnline normalizer calculation for softmax — Milakov & Gimelshein, 2018: the running max/sum trick.
- paperLost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023.
- paperYaRN: Efficient Context Window Extension of Large Language Models — Peng et al., 2023: frequency-aware RoPE scaling.