Skip to content
LearnAI

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.

⏱ 14 minAdvanced

The quadratic wall

Self-attention computes a score between every query and every key: for a sequence of NN tokens, that’s an N×NN \times N 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 N2N^2:

  • Compute. The score and weighted-sum products cost about 4N2d4N^2 d 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 S=QK⊤S = QK^\top, writes it to GPU memory, reads it back for the softmax, writes the probabilities PP, then reads them again to multiply by VV. Those passes over N2N^2 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.

ANALOGY· A tiny countertop and a pantry downstairs

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 N2N^2 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:

  1. Split QQ into blocks of rows, and KK, VV into blocks of rows too.
  2. Load a block of queries into SRAM. Then stream key/value blocks through, one at a time.
  3. For each pair, compute the small tile of scores Sij=QiKj⊤S_{ij} = Q_i K_j^\top in SRAM, fold it into a running softmax and a running output, and throw the tile away.
  4. 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, mm, and the running sum of exponentials, ℓ\ell. When a new tile brings a bigger maximum, multiply everything accumulated so far by emold−mnewe^{m_{\text{old}} - m_{\text{new}}} 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 QQ, KK, VV and the saved per-row mm and ℓ\ell. That costs some extra FLOPs, but avoids reading an N2N^2 matrix, so it’s faster overall. Memory use becomes linear in NN instead of quadratic.

INTERACTIVEFlashAttention tiling
Block size
Mask
keys / values (streamed in blocks) →queries (outer loop) →K/V1Q1K/V2Q2K/V3Q3K/V4Q41.9·······0.11.2······0.31.80.1·····2.50.22.72.1····1.9-1.0-1.00.92.5···1.31.3-0.70.51.12.4··1.01.32.12.41.70.51.8·0.92.92.51.91.72.82.1-0.8SRAM (on-chip, tiny, fast)Q blockK blockV blockS tile 2×2, never leaves SRAMrunning m, ℓ per rowO accumulator (rescaled)Press Next: the first query block and key/value block are loaded into SRAM.
1/11
N×N scores through HBM (naive)
0
write S, read S, write P, read P
N×N scores through HBM (tiled)
0
S and P live only in SRAM
Q / K,V block loads (tiled)
0 / 0
elements, toy head dim 4
O written (tiled)
0
once per query block
At real scale (one head, BF16, head dim 128, 128-row query blocks)
N×N matrix (S or P)
2.00 GiB
per head, per sequence: naive must store it
HBM traffic, naive
8.03 GiB
4N² + 4Nd elements
HBM traffic, tiled
4.02 GiB
2Nd + 2N²d/B_r · 2.0× less

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).

An 8×8 matrix of attention scores processed tile by tile. The query block stays in SRAM while key/value blocks stream past; each tile updates the running max m and sum ℓ for its rows (table below). With the causal mask, tiles entirely in the future are skipped. Counters compare HBM traffic with a naive implementation.

Things to try:

  1. Step through the first row of tiles. Watch the table: when a tile contains a larger score than any before, mm jumps and the rescale factor drops below 1, shrinking the old sum before adding the new terms.
  2. 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.
  3. Watch the counters. Naive attention pushes every score through HBM four times. The tiled version moves only QQ, KK, VV and OO.
  4. 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 O(N2)O(N^2), 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 WW tokens. Mistral 7B used W=4096W = 4096; because each layer can look WW 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 s1,…,sNs_1, \dots, s_N and values v1,…,vNv_1, \dots, v_N, attention computes o=∑jesj∑keskvjo = \sum_j \frac{e^{s_j}}{\sum_k e^{s_k}} v_j. Process the scores in blocks, keeping a running max mm, a running sum ℓ\ell and an unnormalized output o~\tilde{o}. For each new block BB:

mnew=max⁡(m, max⁡j∈Bsj)ℓnew=em−mnew ℓ+∑j∈Besj−mnewo~new=em−mnew o~+∑j∈Besj−mnew vj\begin{aligned} m_{\text{new}} &= \max\big(m,\ \max_{j \in B} s_j\big) \\ \ell_{\text{new}} &= e^{m - m_{\text{new}}}\,\ell + \sum_{j \in B} e^{s_j - m_{\text{new}}} \\ \tilde{o}_{\text{new}} &= e^{m - m_{\text{new}}}\,\tilde{o} + \sum_{j \in B} e^{s_j - m_{\text{new}}}\, v_j \end{aligned}

Start with m=−∞m = -\infty, ℓ=0\ell = 0, o~=0\tilde{o} = 0. At the end, o=o~/ℓo = \tilde{o} / \ell. Subtracting the running max keeps every exponent ≤0\le 0, so nothing overflows.

Worked example. One row, four keys in two blocks. Scores (1,3∣2,5)(1, 3 \mid 2, 5), scalar values (10,20∣30,40)(10, 20 \mid 30, 40).

stepmmrescale emold−mnewe^{m_{\text{old}}-m_{\text{new}}}ℓ\ello~\tilde{o}
block 1: scores 1, 33(first block)e−2+e0=1.1353e^{-2} + e^{0} = 1.13530.1353⋅10+1⋅20=21.3530.1353 \cdot 10 + 1 \cdot 20 = 21.353
block 2: scores 2, 55e3−5=0.1353e^{3-5} = 0.13531.1353⋅0.1353+e−3+e0=1.20341.1353 \cdot 0.1353 + e^{-3} + e^{0} = 1.203421.353⋅0.1353+0.0498⋅30+40=44.38321.353 \cdot 0.1353 + 0.0498 \cdot 30 + 40 = 44.383

Result: o=44.383/1.2034=36.88o = 44.383 / 1.2034 = 36.88.

Check against the direct computation with all four scores at once: weights ∝(e−4,e−2,e−3,e0)=(0.0183,0.1353,0.0498,1)\propto (e^{-4}, e^{-2}, e^{-3}, e^{0}) = (0.0183, 0.1353, 0.0498, 1), sum 1.20341.2034; weighted values 0.183+2.707+1.494+40=44.3830.183 + 2.707 + 1.494 + 40 = 44.383; output 36.8836.88. 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
COMMON MISCONCEPTIONS
  • “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 O(N2)O(N^2); 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

0/5 answered
  1. Q1.What is the main reason FlashAttention is faster than a naive attention implementation?

  2. 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?

  3. Q3.How does FlashAttention's memory use scale with sequence length N (for fixed head dim)?

  4. Q4.What did the 'Lost in the Middle' study find?

  5. Q5.Why do RoPE-based models need special handling (such as position interpolation or YaRN) to go beyond their training context?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.