Attention Mechanisms, Part 3: Escaping N² — The Approximation Era

Part 2 ended with the Transformer’s bill: every head in every layer builds an $N \times N$ table of scores. With the few-hundred-token sequences of 2017, that table was small. By 2019 people wanted whole documents, long audio clips, and images flattened into thousands of pixels, and the table had become the thing standing in the way.

Between roughly 2019 and 2021, a wave of papers tried to get around it. They all started from the same observation: in a trained model, most entries of the attention table are close to zero. A token usually puts almost all of its weight on a handful of other tokens. If most of the table is nearly empty, maybe we do not need to compute all of it.

There are only a few ways to act on that idea, and every method in this post picks one of them:

  • Skip entries by a fixed rule. Decide in advance which token pairs are allowed to interact, for example only nearby tokens. (Sparse Transformer, Longformer, BigBird)
  • Skip entries based on content. Find the pairs that are likely to have large scores at runtime and compute only those. (Reformer, Routing Transformer)
  • Shrink the table. Compress the keys and values so there are fewer columns to compare against. (Linformer)
  • Never build the table. Rewrite the softmax so the computation can be reordered and the $N \times N$ matrix never appears. (Performer, Linear Transformer)

The survey by Tay et al. (2020) uses a similar grouping. Below, each pattern is drawn as an attention mask. Lit cells are the scores that actually get computed; dark cells are skipped. Play the row sweep to see which keys a single query reads under each scheme, and move the $N$ slider to see how the cost of each grows.

The attention pattern zoo

How Big the N² Table Really Gets

During inference you can compute attention one row at a time and throw each row away. During training you cannot. The backward pass needs the softmax probabilities, so every head in every layer keeps its full $N \times N$ table in memory until the gradients are computed.

The size is easy to work out: $N^2$ entries, 2 bytes each in fp16. For a BERT-large-sized model (24 layers, 16 heads), one training sequence needs the memory shown below. On the default linear scale, the $N^2$ curve bends sharply past an 80 GB GPU; switch to log–log to inspect all the way to 128k.

Each doubling of $N$ multiplies the cost by four. These numbers cover only the attention probabilities with a batch size of one: no weights, gradients, optimizer state, nor other activations. At 8k, one sequence takes most of an 80 GB A100. At 16k it no longer fits at all. At 32k you would need about ten GPUs just to hold the attention tables.

Context lengths at the time were short. GPT-2 (2019) used 1,024 tokens and GPT-3 (2020) used 2,048. Full documents, source files, genomic sequences, and high-resolution images all needed far more than that, and the chart above shows why nobody could simply turn the length up.

Fixed Patterns: the Sparse Transformer

Child et al. (2019) at OpenAI built the first sparse attention that worked at scale. They looked at the attention maps of trained dense models and saw that most of the weight followed regular patterns: tokens attended to their neighbours, or to positions at regular intervals, as in an image where the pixel directly above is one full row back. If the useful pattern is predictable, you can decide in advance which entries to compute and skip the rest.

They used two patterns, each split across two heads (or two layers) so that together they cover the sequence:

  • Strided. One head attends to the previous $l$ tokens. The other attends to every $l$-th token before that. With $l \approx \sqrt{N}$, any token can reach any earlier token in two hops: first along its own stride, then locally. This suits data with a period, such as images flattened row by row.
  • Fixed. The sequence is cut into blocks. One head attends within the current block. The other attends to a few designated “summary” positions at the end of each block, which every later token can see. This suits text, which has no natural period.

Each query now reads about $2\sqrt{N}$ keys instead of $N$, so the total cost drops from $O(N^2)$ to $O(N\sqrt{N})$. At $N = 8192$ that is roughly 45 times fewer scores. The paper used it to train autoregressive models on 12,288-token sequences of text and image pixels and on raw audio more than 65,000 samples long, when 512 to 1,024 tokens was the norm.

The cost was engineering. A sparsity pattern only saves time if a GPU kernel can skip the missing entries efficiently, and that required custom block-sparse CUDA kernels. They were hard to modify, hard to combine with other tricks, and hard for other labs to reproduce. This problem returns throughout the era: skipping entries is easy to describe and hard to make fast.

The idea still lasted. GPT-3 alternated dense layers with locally banded sparse layers “similar to the Sparse Transformer”, and block-sparse kernels became a standard tool.

Content-Based Patterns: Reformer

A fixed pattern guesses where the large scores will be. But the large scores are, by definition, the pairs where $q_i^\top k_j$ is large. Why not find those pairs directly? Kitaev, Kaiser & Levskaya (2020) did this with locality-sensitive hashing (LSH): a hash function designed so that similar vectors usually get the same hash.

The steps are:

  1. Share queries and keys. Use one projection for both, so one hash describes both roles. With separate queries and keys, a query and its best key could be hashed independently and land in different places.
  2. Hash with a random rotation. Rotate every vector by a random matrix and label it by the direction it ends up closest to. Vectors that point in similar directions, which are the ones with large dot products, usually get the same label, called a bucket.
  3. Sort and chunk. Sort tokens by bucket, cut the sorted sequence into equal chunks, and let each chunk attend to itself and the chunk before it.

The sort costs $O(N \log N)$, which is where Reformer’s headline complexity comes from. The attention itself is linear in $N$ for a fixed chunk size. Because softmax is dominated by its largest scores, attending only within a bucket recovers most of the weight.

Hashing is random, so sometimes a query and its best key fall on opposite sides of a bucket boundary. Reformer reduces this by hashing several times with different rotations and attending within the union of buckets. The visualization below shows one round of hashing, the sort into chunks, and what a second round recovers.

LSH bucketing in Reformer

Reformer also attacked memory in a second way. With reversible layers, borrowed from RevNets, each layer’s input can be recomputed exactly from its output, so the backward pass rebuilds activations instead of storing them. Keep this in mind: recomputing instead of storing is also the central trick of FlashAttention, two years later.

Reformer did not catch on, for two reasons. First, hashing, sorting, and gathering tokens into chunks are irregular operations, and GPUs are fast at large regular matrix multiplications. The lower complexity rarely turned into a lower wall-clock time at the lengths people actually trained on. Second, when a task needs one exact token from far away, a match that hashed into a different bucket cannot be seen at all.

Sliding Windows: Longformer and BigBird

Longformer (Beltagy, Peters & Cohan, 2020) made the simplest bet of the group, and it is the one that lasted.

Each token attends to a window of $w$ nearby tokens. A few task-specific tokens, such as [CLS] for classification or the question tokens in question answering, get global attention: they attend to every token, and every token attends to them. The cost is $O(N \cdot w)$, linear in $N$ for a fixed window.

With $w = 512$, the score table for one head shrinks as follows:

$N$DenseSliding windowReduction
8k134 MB8.4 MB16×
32k2.1 GB33.6 MB64×
128k34.4 GB134 MB256×

The reduction is just $N / w$. The obvious worry is that a token can see only $w$ neighbours. The answer is depth, the same way a stack of small convolutions sees a large patch of an image. In layer 1 a token sees $w$ positions. In layer 2 it sees tokens that have already seen their own $w$ neighbours. After $L$ layers the receptive field is roughly $L \cdot w$: twelve layers with $w = 512$ reach about 6,000 tokens, although no single attention step looks past 512.

BigBird (Zaheer et al., 2020) adds a few random keys per query on top of the window and the global tokens. The random links act as shortcuts, so information can cross the sequence in a few hops. BigBird also proved something the other methods could not: with global tokens, this sparse attention is still a universal approximator of sequence-to-sequence functions and is Turing complete, just like full attention.

Sliding windows are still in production. Mistral 7B uses a 4,096-token window, and the Gemma 2 and Gemma 3 families interleave local window layers with global layers. The reason is that a window is just a dense band around the diagonal, and a dense band breaks cleanly into the regular tiles GPUs are good at. Of all the patterns in this post, it is the one that fits the hardware best.

Low Rank: Linformer

Wang et al. (2020) took a linear-algebra route instead of a sparse one. They measured the attention matrices of trained models and found them close to low rank: most of the information is captured by a small number of directions. If that is true, you do not need all $N$ keys. A compressed summary of them will do.

Linformer learns two matrices $E, F \in \mathbb{R}^{k \times N}$ that mix the $N$ keys and values down to $k$ summary rows before attention:

$$\text{head} = \text{softmax}\left(\frac{Q(EK)^\top}{\sqrt{d_k}}\right)(FV)$$

Each query now compares against $k$ compressed keys instead of $N$ real ones, so the score table is $N \times k$. With $k = 256$, one head at $N = 32\text{k}$ shrinks from 2.1 GB to 16.8 MB.

The problem is in the shapes. $E$ and $F$ have $N$ as one of their dimensions, so the sequence length is fixed when the model is trained. A Linformer trained on 4,096 tokens has no weights for token 4,097. Every other part of the Transformer works at any length; this part does not. Worse, every compressed key is a mix of all positions, including future ones, so there is no simple way to apply a causal mask. That rules out autoregressive language modelling, which was quickly becoming the main use of Transformers. Quality also dropped on retrieval-style tasks, which makes sense: if the method assumes the fine detail of the attention matrix can be thrown away, it will struggle on tasks that depend on that detail.

Kernels: Performer and FAVOR+

The Performer (Choromanski et al., 2021) is the most elegant attempt of the group. Start from what softmax attention computes for one pair of tokens: an unnormalised weight $\exp(q_i^\top k_j)$ (folding the $1/\sqrt{d_k}$ into $q$ and $k$). That function of two vectors is a kernel, and many kernels can be written approximately as an ordinary dot product of transformed vectors. Suppose we find a feature map $\phi$ that turns a $d$-dimensional vector into an $r$-dimensional one with

$$\phi(q)^\top \phi(k) \approx \exp(q^\top k)$$

Then the attention numerator becomes $\phi(Q)\phi(K)^\top V$, a product of three ordinary matrices. Matrix multiplication is associative, so we can choose where the brackets go:

$$\left(\phi(Q)\phi(K)^\top\right)V \quad = \quad \phi(Q)\left(\phi(K)^\top V\right)$$

Both sides give the same numbers, but look at the shapes. $\phi(Q)$ and $\phi(K)$ are $N \times r$, and $V$ is $N \times d$. On the left, $\phi(Q)\phi(K)^\top$ is $N \times N$: the table we were trying to avoid. On the right, $\phi(K)^\top V$ is only $r \times d$, a small summary of all keys and values whose size does not depend on $N$. Each query then reads from that summary. The total cost is $O(Nrd)$, linear in $N$. Nothing is skipped; the $N \times N$ matrix simply never appears.

For one head at $N = 8192$, $r = 256$, $d = 64$, ignoring the cost of computing the features: the dense path takes about $8.6 \times 10^9$ multiply-adds and the reordered path about $2.7 \times 10^8$, roughly 32 times fewer. The ratio is $N / r$, so the reordering only pays off when $N$ is well above $r$. For short sequences, dense attention is cheaper.

The hard part is finding a good $\phi$, and that is what the “+” in FAVOR+ is about. The textbook random-feature map uses sines and cosines, and its estimates can be negative. Attention weights must be positive, and when the softmax normaliser is a sum of noisy terms that can cancel, it can come out close to zero or even negative, and training blows up. Performer uses positive random features, $\phi(x) \propto \exp(w^\top x - \lVert x \rVert^2 / 2)$ for random Gaussian $w$. These are always positive and their dot product equals $\exp(q^\top k)$ on average. It also makes the random directions orthogonal to each other, which reduces the variance further.

import torch

def favor_features(x, w):
    # x: [batch, heads, tokens, d];  w: [d, r] random Gaussian (orthogonalised in FAVOR+)
    x = x / x.size(-1) ** 0.25                 # fold in the 1/sqrt(d) temperature
    proj = x @ w                               # [.., tokens, r]
    sq = (x ** 2).sum(dim=-1, keepdim=True) / 2
    return torch.exp(proj - sq) / w.size(-1) ** 0.5

def linear_attention(q, k, v, phi):
    qp, kp = phi(q), phi(k)                            # [.., tokens, r]
    kv = torch.einsum("bhnr,bhnd->bhrd", kp, v)        # [.., r, d]   N is summed away
    z = kp.sum(dim=-2)                                 # [.., r]      normaliser
    num = torch.einsum("bhnr,bhrd->bhnd", qp, kv)
    den = torch.einsum("bhnr,bhr->bhn", qp, z).unsqueeze(-1)
    return num / den

# w = torch.randn(64, 256)
# out = linear_attention(q, k, v, lambda x: favor_features(x, w))

The causal case is less tidy. With a mask, query $i$ may only use keys $1, \ldots, i$, so instead of one summary $\phi(K)^\top V$ you need a running prefix sum of $\phi(k_j) v_j^\top$, updated one token at a time. That is cheap in theory and awkward to make fast on a GPU. But this running sum, it turns out, is an important idea in its own right.

Honourable Mentions

  • Linear Transformer (Katharopoulos et al., 2020) uses the same reordering with the simpler feature map $\phi(x) = \text{elu}(x) + 1$. Its key observation is that causal linear attention is a recurrent network: the running sum $\sum_j \phi(k_j) v_j^\top$ is an $r \times d$ hidden state, updated once per token. Generating a new token then costs the same at step 10 as at step 10,000. This idea came back in RetNet, gated linear attention, and Mamba-2.
  • Synthesizer (Tay et al., 2020) drops the query-key comparison entirely and learns the attention weights directly, or even fixes them at random. It worked surprisingly well on some tasks, which raised a fair question about how much of attention’s value comes from comparing tokens by content.
  • Routing Transformer (Roy et al., 2020) finds content-based sparsity with online k-means clustering instead of hashing.

Why Most of These Faded

Three reasons, from least to most important.

They did not clearly win on quality. The Long Range Arena benchmark (Tay et al., 2020) was built to compare these methods on six long-context tasks. No efficient variant won across the board, the ranking changed from task to task, and the best average score was barely above the plain Transformer’s. A method that is sometimes worse and rarely much better is hard to adopt.

Lower complexity did not mean faster. An $O(N \log N)$ method with scattered memory reads and poor use of the GPU’s matrix units can lose to an $O(N^2)$ method running near peak speed. At the sequence lengths people actually trained on, several of these methods were slower than the dense attention they replaced, and each one added custom code that had to be maintained as PyTorch and CUDA changed.

The starting assumption was wrong. This is the important one. The whole era assumed that computing the $N \times N$ matrix meant storing it, so the only way to save memory was to compute less of it. In 2022, FlashAttention showed that the storing was a choice about how attention was implemented, not something attention requires. Exact attention could use memory linear in $N$ and also run faster. Once that was true, approximating attention saved little and cost accuracy.

FlashAttention still does $O(N^2)$ arithmetic, though. At very long lengths compute becomes the limit, which is another reason sliding windows, the most hardware-friendly approximation, are still around. The chart below puts all of these methods on the same axes. Turn on the FlashAttention curve to see how far below the others its memory sits.

How attention memory scales with sequence length
MethodCost per headCore ideaDid it last?
Sparse Transformer$O(N\sqrt{N})$fixed strided / block patternsPartly: GPT-3’s banded layers, block-sparse kernels
Reformer$O(N \log N)$LSH buckets + reversible layersNo
Longformer$O(N w)$sliding window + global tokensYes: sliding windows in Mistral, Gemma
BigBird$O(N w)$window + global + randomPartly: the theory is still cited
Linformer$O(N k)$low-rank projection of $K$, $V$No: fixed length, no causal mask
Performer$O(N r d)$random-feature kernel + reorderingPartly: through linear-attention research
Linear Transformer$O(N r d)$feature-map kernel, recurrent decodingYes: as an ancestor of modern linear RNNs

The Bridge: Exact Attention Without the N² Memory

The turning point came from a short paper that proposed no new architecture.

Rabe & Staats (2021), Self-attention Does Not Need $O(n^2)$ Memory, pointed out that the $N \times N$ matrix is a side effect of evaluation order. You do not need a whole row of scores before taking its softmax. You can process the keys in chunks while keeping three running values for each query: the largest score seen so far, the sum of exponentials so far, and the weighted sum of values so far. When a new chunk brings a larger maximum, you rescale what you have already accumulated and carry on. At the end you get exactly the same result as ordinary attention, not an approximation, using $O(\log N)$ memory for a single query and $O(\sqrt{N})$ for self-attention in their practical implementation.

The paper got less attention than the architectures above because it did not make models more capable. What it did was change the question. The problem was never the arithmetic. It was the decision to write the full intermediate matrix to memory.

The next post picks up from there. FlashAttention takes the same streaming softmax, asks what it costs to move data between GPU main memory and the small, fast on-chip memory, and makes exact attention both faster and linear in memory. That made most of this era unnecessary.

References

Discussion