KnowML

Attention & Transformers

Follow one sentence through a Transformer: how the word "it" finds the word it refers to, how that search becomes a single matrix equation, and why doing it for every word at once gets expensive as the text gets longer.

⏱ 36 min readAssumes: dot products & softmax (01), RNN/seq2seq bottleneck (07)
Start reading

Here's a sentence: "The animal didn't cross the street because it was too tired." When you read it, you know without thinking that "it" means the animal and not the street, because a street can't be tired. Ask a language model what was tired and it'll give the same answer, so somewhere inside it, the model has connected "it" to "animal", a word several positions earlier.

That's a bit harder than it sounds, because a model doesn't see words. It sees a list of vectors, one for each token (a word or a piece of a word), and each layer of the model updates every vector in the list. For the model to know what "it" refers to, the vector at the position of "it" has to pick up some information from the vector at the position of "animal". So the question is how information gets from one position in the list to another.

Before 2017, the usual answer was a recurrent network (chapter 07). It reads the words one at a time and carries a single memory vector along, updating it at every word, so whatever "animal" contributes has to survive every update between it and "it". And the further apart two words are, the more of that tends to get lost on the way. This chapter is about the idea that replaced it, attention, which lets each position look directly at every other position and decide how much to take from each one. We'll follow our sentence through it with one question in mind: how does "it" decide where to look? It turns out to be a weighted average, and most of the chapter is about making that average learnable, and then about what it costs when every word does it at once.

01How one word looks at the others

A lookup that doesn't need an exact match

Start with a kind of lookup you already use. A Python dictionary stores pairs of keys and values, and d["cat"] finds the key that matches "cat" exactly and hands back its value. Every other entry is ignored, and if no key matches, you get an error.

Our word "it" needs something looser. It isn't looking for one exact word. It's looking for whichever word is most likely to be the thing it refers to, and it might well do better taking a little from several words. So imagine a different kind of lookup. You give it a description of what you're looking for, it compares that description with every key and gives each one a score for how well it matches, and it hands back a mix of all the values, in which the better-matching values make up a bigger share.

That's attention, and each piece of it has a name. What "it" sends out, the description, is called its query. Every word offers a key, the thing the query gets compared against, and a value, which is what it hands over if it's chosen. All three are vectors. To compare a query with a key, attention uses the dot product from chapter 01: multiply the two vectors number by number and add up the results. Two vectors that point in a similar direction give a large dot product, and two that point in unrelated directions give one near zero.

Turning scores into weights

The dot products give one score per word, but a list of scores isn't yet a recipe for mixing. Scores can be negative, and they don't add up to anything in particular. We want weights that are all positive and add up to one, so the result is a proper average.

That's the job of the softmax function. It raises e to the power of each score, which makes every number positive and widens the gap between big and small scores, and then it divides each result by their total so that they add up to one. A score that's clearly higher than the others ends up with most of the weight, but no word ends up with exactly zero.

So attention, for one word, takes three steps. It scores the query against every key with a dot product, turns the scores into weights with a softmax, and adds up the values, each multiplied by its weight. What comes out is a new vector for "it" that blends every word's value, tilted toward the words that matched best.

Trying it on three words

Let's do this with numbers small enough to check by hand. Take three words, "cat", "mat" and "it", and give each one a key with only two numbers in it. The first number says how animal-like the word is and the second says how object-like it is, so "cat" gets [1, 0], "mat" gets [0, 1], and "it", which could be either, gets [0.5, 0.5]. To keep things simple, each word's value is the same as its key. For the query of "it" we'll use [2, 0.5], which mostly asks for something animal-like. These numbers are picked by hand to make the point. In a real model they're learned, as we'll see in section 2.

Below, the code runs the three steps. K @ q takes the dot product of the query with every key at once, the line after it is the softmax, and w @ V is the weighted sum of the values. It also divides the scores by np.sqrt(2). Ignore that for now, because section 3 is about exactly why it's there.

Try it Attention on three words, with numbers you can check by hand
import numpy as np

words = ["cat", "mat", "it"]
K = np.array([[1.0, 0.0],        # "cat": an animal
              [0.0, 1.0],        # "mat": an object
              [0.5, 0.5]])       # "it": not sure yet
V = K.copy()                     # here each value is just its key
q = np.array([2.0, 0.5])         # what "it" is looking for: animal-like

scores = K @ q / np.sqrt(2)      # how well each word matches the query
w = np.exp(scores) / np.exp(scores).sum()   # softmax: weights sum to 1
out = w @ V                      # a weighted average of the values

for word, s, weight in zip(words, scores, w):
    print(f"{word:>4}: score {s:5.2f}  weight {weight:5.2f}")
print("new vector for 'it':", np.round(out, 2))
It prints a score of 1.41 for cat, 0.35 for mat and 0.88 for it itself. The softmax turns those into weights of 0.52, 0.18 and 0.30, which add up to 1, and the new vector for it comes out as [0.67 0.33].

Read the output one line at a time. "cat" scores highest, so it gets just over half the weight. "mat" gets the least. And "it" scored itself too and kept 0.30 of the weight, because a word is always one of the words it can look at. Its vector started out as [0.5, 0.5] and has moved to [0.67, 0.33], toward the animal direction. Nothing in the code says that "it" means "cat". Our query and keys made "cat" the best match, and the average did the rest. (Jay Alammar's The Illustrated Transformer walks through the same idea with pictures, and it's probably the best next read if pictures help you more than equations.)

Why mix all the values instead of taking the best one?

Taking only the best-matching word would be a yes-or-no decision, and a model can't learn well through one. Training works by nudging the model's numbers a little and checking whether the output gets a little better (that's what the gradient from chapter 01 measures). If the lookup picks a single winner, a small nudge to the scores usually changes nothing at all, and once in a while it makes the answer jump to a different word, so there's no smooth signal to follow. A weighted average changes smoothly when the scores change, so every nudge has a small effect the model can learn from. That's why attention is often described as a soft, differentiable lookup.

In the example we wrote the query and the keys ourselves. A real model has to produce them from the words, and it has to do so for every word in the sentence, not only for "it".

02Every word at once

Where queries, keys and values come from

When a sentence enters a model, each token is replaced by its embedding, a vector of a few hundred or a few thousand numbers that the model learned during training. In the original Transformer each embedding has 512 numbers, and that width is called . The embedding for "it" is a single vector, but attention needs three things from it: a query, a key and a value.

It makes them by multiplying the embedding by three different weight matrices, which are learned along with everything else in the model. Multiplying a vector by a matrix gives a new vector, a reshaped view of the original, so a word's query, key and value are three different views of the same embedding.

Why does a word need three different vectors?

Because the three jobs ask different things of it. When "it" goes looking, it's looking for an animal, but "it" isn't an animal itself, so the vector it searches with (its query) shouldn't be the same as the vector that other words find it by (its key). And what a word is matched on doesn't have to be what it passes on once it's matched, so the value gets its own matrix as well. With three matrices, training can shape each view separately. In section 1 we skipped this and set each value equal to its key, which is fine for a toy but leaves a real model less to work with.

Here's one query going through the three steps against four words. Watch how four scores become four weights that add up to one, and how those weights decide how much of each value ends up in the output.

Scaled dot-product attention — one query attending over four keys/values
Q this token K1 K2 K3 K4 0.09 0.62 0.21 0.08 softmax V1 V2 V3 V4 Z output
The query is compared with four keys, and the softmax turns the four scores into weights that add up to 1 (here 0.09, 0.62, 0.21 and 0.08). The same weights then mix the values V1 to V4 into the output Z. The second word gets most of the weight, so its value makes up most of the output. In a real layer every word does this at the same time, each with its own query.

Writing it as matrices

Every word in the sentence goes through the same steps, and the work for one word doesn't depend on the result for any other, so all of it can happen at the same time. Stack the queries of all the words into a matrix , one row per word, and do the same with the keys to get and with the values to get . Then a single matrix multiplication, , computes every word's score against every other word, and the whole of attention fits on one line. This is the equation from the 2017 paper "Attention Is All You Need":

Each part of it is a step you've already seen:

  • Q, K, V matrices with one row per token. Row i holds token i's query, key or value, made by multiplying its embedding by the matching weight matrix. Their width is .
  • QKᵀ a square grid of scores, with one row and one column per token. The number in row i, column j is the dot product of token i's query with token j's key.
  • √d_k a scaling factor, the square root of the query and key width. Section 3 explains why it's needed.
  • softmax applied to each row separately, so that each token's scores become weights adding up to 1.
  • · V multiplies the weights by the values, which gives each token a weighted average of every token's value.

Notice what happens to the shape. A sentence of n tokens goes in as n vectors and comes out as n vectors. Attention changes what's inside each vector by mixing in information from other positions, but it never changes how many vectors there are.

Not looking ahead

There's one complication. A model like GPT is trained to predict the next word: given "The animal didn't cross the", it should guess "street". If the position of "the" could attend to the word after it, it would see the answer. So when attention is used to predict the next token, each position is only allowed to look at itself and the positions before it. This is called causal attention.

Doing it takes one small change. Before the softmax, every score where a token would be looking at a later token is replaced with . Since the softmax raises e to the power of each score, and e to the power of minus infinity is zero, those positions get a weight of exactly zero and contribute nothing. If you drew the grid, the blanked-out scores would form a triangle in the top-right corner of the grid, above the diagonal.

Models like BERT, which read a whole sentence at once to understand it and don't predict the next word, leave the mask off, so every position sees every other one. That's the main difference between the two halves of the original Transformer: the encoder has no mask and the decoder has one. BERT is built from encoder blocks and GPT from decoder blocks.

Next, we'll run the full equation on four tokens with random queries, keys and values, with the mask applied. np.triu(..., k=1) marks the triangle of positions above the diagonal, and the line after it sets those scores to -inf. Subtracting each row's largest score before taking the exponent doesn't change what the softmax returns; it only stops large scores from overflowing. Before you run it, think about the first row. Token 0 isn't allowed to look at anything after itself, so what's left for it to attend to?

Try it Run scaled dot-product attention by hand, mask and all
import numpy as np
rng = np.random.default_rng(0)

T, d_k = 4, 8                    # 4 tokens, 8-dim queries and keys
Q = rng.normal(size=(T, d_k))
K = rng.normal(size=(T, d_k))
V = rng.normal(size=(T, 3))      # values need not share d_k

scores = Q @ K.T / np.sqrt(d_k)  # (T, T): everyone against everyone
future = np.triu(np.ones((T, T), dtype=bool), k=1)
scores[future] = -np.inf         # token t may not read past t

m = scores.max(axis=1, keepdims=True)
W = np.exp(scores - m)
W /= W.sum(axis=1, keepdims=True)     # softmax, one row at a time
Z = W @ V

print("Q", Q.shape, "K.T", K.T.shape, "scores", scores.shape)
print("W", W.shape, "V", V.shape, "Z", Z.shape, "\n")
print(np.round(scores, 2), "\n")
print(np.round(W, 3))
print("row sums:", W.sum(axis=1))
print("Z[0] is exactly V[0]:", np.allclose(Z[0], V[0]))
Every row of W adds up to 1. The first row has a weight of 1.000 on token 0 and zero everywhere else, so Z[0] is exactly V[0]. The last row is the only one that sees all four tokens, with weights 0.102, 0.031, 0.684 and 0.183. scores has shape (4, 4) while V has shape (4, 3).

Token 0 can only attend to itself. Its row of weights is 1.000 followed by zeros, so its output is its own value, unchanged, and in a causal model that's true in every layer: the first token never gets any context from the rest of the text. Only the last row can see all four tokens, and most of its weight, 0.684, goes to token 2, because that's where its largest score, 1.4, is. Look at the shapes as well. The grid of scores is 4 by 4, one row and one column per token, while the values are 4 by 3. Its size depends only on how many tokens there are, and that will matter a lot in section 6.

If you ran this same code at the sizes a real model uses, it would stop learning. Section 3 is about why, and about two other things the plain equation can't do.

03Making it work at real sizes

Scores that grow with the width

In our toy example the queries and keys had two numbers each. In a real model they usually have 64 or 128. A dot product adds up one product for each number, so a wider vector means more terms added together, and the total tends to land further from zero. When the scores spread out like that, the softmax gives nearly all of the weight to the largest score and almost none to the others.

That might seem harmless, since the output is still a weighted average, but it breaks training. When one weight is close to 1 and the rest are close to 0, small changes to the scores hardly change the weights at all, so the gradient that's meant to tell the model how to adjust its queries and keys is close to zero. In practice, the model stops learning where to look.

Dividing the scores fixes it: divide them by , the square root of the query and key width, before the softmax. But why the square root, and not itself or some other number? It comes out of a short calculation about how spread out the dot product of two random vectors is:

Derivation Why , and not or any other constant

"Keeps the variance stable" is the usual hand-wave. It is a three-line calculation, and doing it tells you exactly why the exponent is one half. Follow the original paper and assume the components of and are independent, with mean 0 and variance 1. That assumption is what the whole argument rests on.

  1. Setting up: the raw score for one query against one key is a sum of products. The question is how that sum behaves as grows.
  2. Why the factorisation is legal: independence lets the expectation of a product split into a product of expectations. Both are zero by assumption, so every term is mean-zero and the whole score is centred at 0. The score does not drift as dimension grows. Only its spread does.
  3. Why : variance is , and the mean is zero, so the second moment equals the variance. That is the small step that makes this collapse so cleanly, and it only works because the components are centred.
  4. Why the variances simply add: variance of a sum equals the sum of variances only when the terms are uncorrelated, which independence across gives us. Drop that assumption and this line fails. So the score's standard deviation is : it grows with the square root of head dimension, not with the dimension itself.
  5. Why this exact constant: dividing a random variable by divides its variance by . To cancel a variance of you need , so . Dividing by would over-correct and crush the scores toward zero; dividing by anything else leaves a dimension-dependent scale. There is exactly one right answer.
The scaling exists to protect the softmax, not the dot product. Softmax is shift-invariant but not scale-invariant: multiply every logit by 10 and the output collapses toward one-hot, where the Jacobian is nearly zero in every direction. A model in that regime stops learning, because no gradient survives the backward pass. So is a variance-control trick whose real purpose is keeping softmax inside the range where it still has a usable slope. Change the assumption at the top and the constant changes with it. This is one of the rare interview answers where you can derive the number rather than recall it.

Let's check both halves of that argument in code. Its first part takes 200,000 dot products of random vectors at three widths and prints how spread out they are (their variance), before and after dividing by . Its second part takes one query and six keys of width 512 and runs the softmax on the raw scores and on the scaled ones.

Try it Watch the variance grow with d_k, and the softmax collapse
import numpy as np
rng = np.random.default_rng(0)

def dots(d_k, n=200_000):        # n independent q.k scores
    q = rng.normal(size=(n, d_k))
    k = rng.normal(size=(n, d_k))
    return (q * k).sum(1)

for d_k in (8, 64, 512):
    s = dots(d_k)
    print(f"d_k={d_k:4d}  var(q.k)={s.var():7.1f}"
          f"   var after /sqrt(d_k)={s.var()/d_k:.2f}")

def softmax(x):
    e = np.exp(x - x.max())
    return e / e.sum()

d_k = 512                        # one query against six keys
s = rng.normal(size=(6, d_k)) @ rng.normal(size=d_k)
p_raw, p_sc = softmax(s), softmax(s / np.sqrt(d_k))
print("\nraw scores:      ", np.round(s, 1))
print("unscaled softmax:", np.round(p_raw, 4))
print("scaled softmax:  ", np.round(p_sc, 4))
print(f"smallest weight: {p_raw.min():.1e} unscaled,"
      f" {p_sc.min():.1e} scaled")
The variance of the raw dot products comes out at 8.0, 63.8 and 510.9 for widths 8, 64 and 512, and after dividing by it is 1.00 each time. At width 512 the raw scores run from -70.6 to 25.6, and the unscaled softmax gives the weakest key a weight of 1.6e-42. The scaled softmax gives weights from 0.0056 to 0.3959.

In the first part the variance grows with the width and comes out almost exactly equal to it, and dividing by brings it back to 1 every time, as the derivation said it would. And the second part shows why that matters. Without scaling, the weakest key gets a weight of about 10-42, which is zero for any practical purpose, and no gradient will get through it. With scaling, the same six keys get weights between about 0.006 and 0.4, so there's still a clear favourite, but every key keeps some weight and can still be learned.

Multi-head attention

A single attention layer gives each word one set of weights, so it can only express one idea of which words are relevant. Our sentence has several things going on at once, though. "it" needs to find "animal", the verb "was" goes with its subject, and some words mostly care about their immediate neighbours. With one set of weights, all of that has to be averaged together.

Multi-head attention runs several smaller attention operations side by side, each with its own query, key and value matrices, and each one is called a head. Each head can learn its own idea of relevance. One head might learn to track subject-verb agreement, another which noun a pronoun refers to, and another the local word order.

Adding heads doesn't make the model any bigger. With and 8 heads, each head works with vectors of width , so the eight heads together do about the same amount of work as one head of width 512. At the end, their outputs are joined back into one vector of width 512 and multiplied by one more weight matrix, :

Splitting a vector into heads doesn't take any computation at all, and that's easy to check. Below, we make a matrix for five tokens of width 12, splits it into three heads of width 4, and checks whether the split copied anything. view reads the same memory with a different shape, and transpose swaps two dimensions so that the heads come first.

Try it Split one tensor into heads and confirm nothing was computed
import torch
torch.manual_seed(0)

T, d_model, H = 5, 12, 3         # 5 tokens, 3 heads of width 4
d_h = d_model // H
x = torch.randn(T, d_model)      # one projection's output, e.g. Q

heads = x.view(T, H, d_h).transpose(0, 1)   # (H, T, d_h)
print("x", tuple(x.shape), "-> heads", tuple(heads.shape))

# No arithmetic happened: the heads share x's memory.
print("same storage:", heads.data_ptr() == x.data_ptr())
print("head 1, token 0:", [round(v, 3) for v in heads[1, 0].tolist()])
print("x[0, 4:8]      :", [round(v, 3) for v in x[0, 4:8].tolist()])

# Each head gets its own (T, T) attention map, for the same FLOPs.
A = torch.softmax(heads @ heads.transpose(-2, -1) / d_h**0.5, -1)
print("attention maps:", tuple(A.shape))

back = heads.transpose(0, 1).reshape(T, d_model)   # the Concat step
assert torch.equal(back, x)
print("concat recovers x bit-for-bit:", torch.equal(back, x))
same storage prints True, so the three heads share memory with x. Head 1's vector for token 0 is 0.849, 0.692, -0.316, -2.115, the same four numbers as x[0, 4:8]. The attention weights have shape (3, 5, 5), one 5 by 5 grid per head, and joining the heads back together gives exactly x.

So the heads are another way of reading the same numbers: head 1's part of token 0 is numbers 4 to 7 of token 0's row. What the split buys is the shape of the attention weights, three separate 5-by-5 grids, one for each head, where a single head would have produced one. Joining the heads back together, the Concat in the equation, is the same reshape run backwards.

Multiple attention heads each producing their own Q, K, V projections
Reference figureEach head gets its own learned Q/K/V projection matrices, run in parallel on the same input. Source: Jay Alammar, The Illustrated Transformer.

Positional information

There's a problem we haven't mentioned yet. Look back at the attention equation and ask what it knows about word order. Scores come from dot products between queries and keys, and nothing in a dot product depends on where a word sits in the sentence. Without a causal mask, if you shuffled the words of our sentence and fed them in, every word would get the same output vector as before, only in the shuffled order. To attention on its own, "the dog bit the man" and "the man bit the dog" contain the same information. This property is called being permutation-invariant.

So position has to be added in some other way. There are two common approaches:

  • Sinusoidal position encodings, used in the original paper, add a fixed vector to each token's embedding. That vector is built from sine and cosine waves of different frequencies, one frequency per dimension, so every position gets its own pattern.
  • Rotary position embedding (RoPE), the usual choice in recent models, rotates each query and key vector by an angle that depends on its position.

RoPE has a useful side effect. Once the query at position and the key at position have both been rotated, their dot product depends on the distance between them, , and not on where each one sits. A model using RoPE learns about relative distances ("three words back") instead of absolute positions ("position 41"), and that helps it cope with texts longer than the ones it was trained on, better than sinusoidal or learned absolute positions do.

We now have a working attention layer. A model is made of many of them stacked on top of each other, and stacking needs a little more structure around each one.

04From a layer to a Transformer

Attention moves information between positions, but on its own it can only combine what's already there, because its output is a weighted average of value vectors. So each attention layer is followed by a small feed-forward network: two weight matrices with a nonlinearity between them, applied to each position's vector separately. Attention moves information between words, and the feed-forward network works on what each word now holds.

Two more pieces make deep stacks trainable. A residual connection adds a layer's output to its input, so the layer computes a change to the vector and doesn't replace it. A normalisation layer rescales each vector before it goes into attention or the feed-forward network, which keeps the numbers in a steady range as they pass through many layers. Attention, a feed-forward network, two residual connections and two normalisations make up one Transformer block, and a model is that block repeated, anywhere from 12 times in a small model to 96 or more in a large one.

One pre-norm transformer block — residual stream flowing bottom to top
Input embedding + position LayerNorm Multi-Head Self-Attention + residual add LayerNorm Feed-Forward (2 linear + GELU) + residual add ↑ to next block / output head
Follow the dashed line up the middle. It carries each token's vector from the bottom of the block to the top. Attention and the feed-forward network each read from it, compute something, and add their result back onto it without ever replacing it. That's what lets a stack of 96 blocks train at all: the gradient can flow straight down the line to the earliest layers, for the same reason it does in a ResNet (chapter 04).

Through all of these blocks, one shape stays the same. If you follow a batch of text through a GPT-style model:

  • it goes in as token ids, with shape (batch, seq_len);
  • after the embedding table it's (batch, seq_len, d_model), one vector per token;
  • every block takes in and puts out that same (batch, seq_len, d_model);
  • at the end, the LM head (language-model head), one last matrix, turns each vector into vocab_size scores, one for every token in the vocabulary, which gives a prediction for the next token at every position.

The original paper drew two stacks of blocks side by side, an encoder that reads the input sentence and a decoder that writes the output, which suited the translation task it was built for. Each decoder block has one extra attention layer, called cross-attention, where the queries come from the decoder and the keys and values come from the encoder's output. That's how each word being written can look back at the sentence being translated, a bit like a translator glancing back at the original.

The Transformer encoder-decoder stack — N encoder blocks feeding N decoder blocks
Reference figureThe full encoder-decoder Transformer stack. Source: Jay Alammar, The Illustrated Transformer.

Most models since have kept only one of the two stacks: BERT the encoder, and GPT and most chat models the decoder. Which brings us to why this design replaced recurrent networks so quickly.

05Why it replaced recurrent networks

Before attention there were two common ways to read a sequence. A recurrent network (an RNN or LSTM) reads one token at a time and carries a memory vector forward. A convolutional network (a CNN) looks at a small window of neighbouring tokens in each layer, and stacks layers to see further. Think about our sentence: how many steps does information need to get from "animal" to "it" in each design? In a recurrent network it's one step for every word in between. In a convolutional network it's however many layers it takes for the windows to reach. In attention it's one step, whatever the distance, because every position looks at every other one directly.

That number of steps, the path length, is one of two things that decide how well a design trains at scale. The other is how much of the work can run at the same time. Here's how the three designs compare:

RNN / LSTMCNN (dilated)Self-Attention
Parallelizable across sequenceNo, step needs step Yes, within a layerYes, fully
Max path length, token →
Compute per layer
Handles long-range dependencyDegrades, gradients vanish over distanceBetter, needs deep stacks or large dilationDirectly, in one step

The path length is the main win. In a recurrent network, information from token 1 has to survive updates to reach token , and during training the gradient has to travel back through all of them, shrinking as it goes. That's the vanishing gradient problem from chapter 07, and it's why recurrent networks struggle to connect words that are far apart. In attention, any two tokens are one dot product apart. Attention also wins on parallelism: a recurrent network can't start on token until it has finished token , but attention works on every position at once, which suits a GPU well.

Now look at the third row of the table, because that's the price. Every token is scored against every other token, so the work in each layer grows with the square of the sequence length, where a recurrent network's grows in proportion to the length. In effect the Transformer swaps a hard training problem, getting gradients across long distances, for an engineering problem, doing a lot of arithmetic. Engineering problems are easier to solve with more hardware, and so far the trade has paid off.

Historically it happened in two steps. In 2014, sequence-to-sequence models for translation squeezed the whole input sentence into one fixed-size vector, and long sentences came out badly. In 2015, Bahdanau and colleagues added attention to a recurrent translation model, so the decoder could look back at every word of the input. In 2017, Vaswani and colleagues, in "Attention Is All You Need", removed the recurrence entirely and kept only attention plus position information. BERT and GPT followed in 2018, ViT showed in 2020 that the same block works on patches of an image, and by 2023 the Transformer was the default design for text, vision and audio, and increasingly for robotics.

That quadratic cost didn't go away, though. It's where most of the engineering around Transformers goes, and it's the subject of the last section.

06What it costs

The grid grows with the square of the length

For a sequence of tokens, attention builds the grid of scores we saw in section 2, in every head of every layer. Computing it takes time proportional to , and storing it the straightforward way takes memory proportional to . Double the length of the text and that work roughly quadruples. A great deal of the engineering in large language models comes back to this one fact, enough that chapter 23 (Efficient AI & Systems) is about it.

Probably the best-known fix, FlashAttention, doesn't reduce the arithmetic at all, since the same scores still get computed. What it avoids is writing the full grid out to the GPU's main memory. It works through the grid in small tiles that fit in the GPU's fast on-chip memory and computes the softmax tile by tile. On modern GPUs, moving data to and from main memory is usually slower than the arithmetic, so the same maths finishes much sooner.

The KV cache

Generating text adds a second cost. A model writes its reply one token at a time, and every new token has to attend to every token before it, so it needs their keys and values. Recomputing all of them for every new token would mean redoing nearly the same work again and again, so instead they're computed once and kept. This store is called the KV cache, and it grows with every token in the conversation.

For a model with 8 billion parameters, the cache takes about 128 KB per token, and at long context lengths that adds up to more memory than the model's weights:

KV cache growth — linear in tokens, and that is quite bad enough
4.9 GB — the weights context KV cache 1k 0.12 GB · 3% of the weights 8k 1.0 GB · 20% 32k 4.0 GB · 82% — now rivals the weights 128k 16 GB · 3.3× the weights Bars are linear in gigabytes. Nothing here is quadratic — the cache grows in straight proportion to tokens, and that alone is enough to take over the card. 8B model, GQA, FP16
For an 8B model using grouped-query attention, each token needs 32 layers × 8 key-value heads × 128 numbers per head × 2 (one for K, one for V) × 2 bytes, which comes to 128 KB. At 128k tokens that's 16 GB, more than three times the 4.9 GB that the model's quantised weights take up. The cache grows in proportion to the number of tokens, not with its square, and that alone is enough to make the length of the conversation, more than the size of the model, decide what fits on the GPU.

That example already includes one way of shrinking the cache. In grouped-query attention (GQA), several query heads share one set of key and value heads, so there are fewer keys and values to store; the model above keeps 8 key-value heads per layer. Multi-query attention takes the same idea to the limit with a single shared key-value head. Both give up a little quality to save a lot of memory, and almost every model built for serving makes that trade.

Where attention doesn't do what you'd expect

Being able to attend anywhere doesn't mean a model attends usefully everywhere. Trained models reliably put a lot of weight on the first few tokens of the text, whether or not they're relevant, and these tokens are called attention sinks. In needle-in-a-haystack tests, where one fact is hidden somewhere in a very long text and the model is asked about it, accuracy drops for facts placed in the middle of the context.

It's also tempting to read attention weights as an explanation. If "it" puts most of its weight on "animal", surely that's why the model decided "it" means the animal? That claim is contested, and it's often wrong. Weights show where information was gathered from, but not how the feed-forward networks and later blocks used it afterwards. An attention map is a useful hint when you're debugging, not proof of how the model reasoned, and if interpretability comes up in an interview, this distinction is usually what the question is checking.

As of 2026, full quadratic attention is still the standard in the great majority of production language models. Engineering has made it affordable, through FlashAttention-style kernels, paged and grouped-query KV caches, and hybrids that mix sliding-window attention with occasional full attention, and nothing has replaced it outright. Linear-attention and state-space models (Mamba and its relatives) are a promising research direction for very long texts, but they haven't displaced attention in the largest models, so a flat claim that attention is finished is likely an overstatement.

07Summary

  1. Attention is a lookup that blends. A query is scored against every key with a dot product, a softmax turns the scores into weights, and the output is the weighted average of the values.
  2. The blend is what makes it learnable. A weighted average changes smoothly as the scores change, so training can adjust where a word looks. Picking a single winner wouldn't give it a gradient to follow.
  3. Each token gets a query, a key and a value, made by three learned matrices, because searching, being found and passing information on are different jobs.
  4. For a whole sentence it's one equation, , and it gives back one vector per token, the same number that went in.
  5. A causal mask stops tokens from looking ahead by setting future scores to minus infinity. Decoders like GPT use it, and encoders like BERT don't.
  6. Dividing by √d_k keeps the softmax trainable. Without it, scores spread out as the vectors get wider and the softmax puts all its weight on one key.
  7. Multiple heads give several kinds of relevance for the same cost, by splitting each vector into narrower pieces.
  8. Attention doesn't know word order until positions are added. RoPE adds them so that scores depend on the distance between tokens.
  9. A Transformer is a stack of blocks, each with attention, a feed-forward network, residual connections and normalisation.
  10. Any two tokens are one step apart. That's why attention replaced recurrent networks, and the price is work that grows with the square of the length.
  11. When generating, the KV cache is the main memory cost, and at long context lengths it can be larger than the model's weights.

08Build this

You can read the attention equation twenty times and still not believe it works. Building the smallest thing that uses it fixes that in an afternoon.

Project Make attention visibly learn to copy ~3 hours · PyTorch

Train a single attention layer on the copy task: given a random sequence, output the same sequence. The task is deliberately trivial so that the attention matrix has exactly one correct shape, so you can look at it and immediately tell whether the mechanism is doing what the equation says.

  1. Generate random integer sequences, length 10, vocabulary of 20. Input is the sequence, target is the same sequence.
  2. Build one attention layer by hand from the equation. Three linear layers for Q, K, V, then softmax(QKᵀ/√d_k)V. No library attention module, no multi-head, no feed-forward block.
  3. Add sinusoidal position embeddings. Train to convergence, which takes a couple of minutes on CPU.
  4. Plot the attention matrix as a heatmap with matplotlib.imshow.
  5. Now break it deliberately by removing the position embeddings and retraining, then restoring them and removing the scaling, using a large like 256.
You'll know it worked when the heatmap shows a clean bright diagonal: position attending almost entirely to position . That diagonal is the model discovering the copy rule on its own. Nobody coded it.
What the two breakages teach. Without positions, the diagonal never forms: attention is permutation-invariant, so the model literally cannot tell position 3 from position 7. Without the scaling at large , the heatmap goes hard one-hot early and training stalls, which is the vanishing-gradient argument from section 3 showing up as a picture instead of an equation.

Where this runs in production

Every long-running chat assistant relies on this directly. Causal self-attention lets today's question attend straight back to something you said 50 turns ago, in one hop, with a weight the model learned to assign based on relevance. It is not filtered through a shrinking, decaying RNN memory state.

Cross-attention does the other half of the work: query from one sequence, key and value from another. It is the mechanism a retrieval-augmented system or a translation decoder uses to let generated output consult retrieved documents or the source sentence, at every single generation step. See 11 for how this composes with a retrieval pipeline.

09Interview questions

BeginnerWalk me through scaled dot-product attention, step by step.

Project the input into Q, K, V via three learned linear layers. Compute to get raw similarity scores between every pair of tokens. Divide by to keep the variance stable. Apply softmax row-wise so each token's scores become a probability distribution. Multiply that distribution by V to get a weighted blend of every token's value — that blend is the output for this token.

BeginnerWhy divide by ?

Dot products of two random vectors grow in expected magnitude with dimension. Large-magnitude scores push softmax toward a near one-hot output, which has near-zero gradient almost everywhere — training stalls. Scaling by keeps score variance roughly constant regardless of head dimension, keeping softmax in a well-behaved gradient regime.

IntermediateWhy multiple heads instead of one larger attention operation?

A single attention function learns one similarity function and produces one blend per token. Splitting the same total dimensionality into heads lets each head specialize — one might track syntax, another coreference, another positional locality — and the concatenation lets the model combine those specialized views, rather than being forced to average everything into a single compromise representation.

IntermediateWhat's the KV cache, and why does it exist?

During autoregressive generation, each new token's query needs to attend over all previous tokens' keys and values. Recomputing K/V for the whole prefix at every new token would be wasteful, so they're cached after being computed once. The cache grows linearly with generated length × layers × heads × head_dim, and is frequently the memory bottleneck in serving long conversations — which is exactly why GQA/MQA and paged attention exist.

IntermediateSelf-attention vs. cross-attention — what's the actual difference?

Mechanically identical formula. The difference is only where Q comes from versus K/V. In self-attention, Q, K, and V all come from the same sequence. In cross-attention, Q comes from one sequence (e.g. the decoder's current state) while K and V come from a different sequence (e.g. the encoder output, or retrieved documents) — it's how one sequence "reads" another.

DeepYou need to serve a model at 128k context length cheaply. What attention-level levers do you pull, and why?

FlashAttention-class fused kernels to avoid materializing the full matrix in HBM. Grouped-query attention to shrink the KV cache size per token. Paged attention to manage that cache in fixed-size blocks instead of contiguous per-request allocations, cutting fragmentation. Possibly a sliding-window + periodic global-attention hybrid if the task tolerates it. None of these change the FLOPs of full attention — they attack memory bandwidth and cache layout, which is almost always the actual bottleneck at inference time, not raw compute.

DeepWhy doesn't a longer context window alone solve long-context reasoning?

"Can attend to" and "can effectively use" are different claims. A model can technically compute a nonzero attention weight to any token in a 1M-token context, but training data rarely rewards reliably using information buried in the middle of very long contexts, and softmax attention empirically develops sinks and dilution effects over long sequences. Needle-in-a-haystack evals expose this directly: retrieval accuracy is high near the start/end of context and dips in the middle. Extending context length is a necessary but not sufficient condition — it needs to be paired with training data and objectives that actually require long-range retrieval to reward the behavior.

10Go deeper

●Now write it yourself

Reading the derivation and being able to produce it are different skills. These are Deep-ML problems that exercise what this page covers — each one is checked against real test cases, not multiple choice.

Matched to this page from Deep-ML's catalogue of 1,380 problems. More at deep-ml.com, and Where to practise covers the other platforms and what each one trains.