2.5Self-attention step by step
The mechanism at the heart of every Transformer, computed by hand. Queries, keys, values, scaling, masking and softmax, with every number visible.
What does “it” refer to?
Read this sentence: The cat sat on the mat because it was tired. You know instantly that it is the cat, not the mat. Mats don’t get tired. Now change one word: The cat sat on the mat because it was warm. Suddenly it is probably the mat.
A language model faces this problem at every token. The embedding of it is the same in both sentences, but to predict what comes next, the model needs a version of it that knows what it refers to. The previous lesson showed why squeezing the past through an RNN’s hidden state makes this hard. Self-attentionSelf-attentionAttention in which the queries, keys and values all come from the same sequence. solves it directly: each token gets to look at the other tokens, decide which ones are relevant, and pull information from them into its own vector.
This lesson computes one attention layer completely by hand, on that exact sentence, with vectors small enough that you can read every number.
You walk into a library with a question scribbled on a card: “something about an animal”. That card is your query. Every book has a label on its spine summarizing what it’s about: those are the keys. Inside each book is its actual content: the value.
A normal library returns the one book whose label matches exactly. This fuzzy library compares your card with every label, gives each book a relevance score, and hands you a blended summary: 60% from the best-matching book, 10% from the next, and a sliver from everything else. The relevance scores are the attention weights, and the blended summary is the output. In self-attention, every word in the sentence is simultaneously a reader with a question and a book on the shelf.
Three roles for every token
Each token starts as an embedding vector . Self-attention multiplies it by three learned matrices to get three new vectors. Together they’re called queries, keys and valuesQuery, key, value (Q/K/V)Three learned projections of each token. A query is compared with keys to get attention weights, which then mix the values.:
- Query : what this token is looking for. For a pronoun, roughly “an earlier noun that could be my referent”.
- Key : what this token advertises about itself, so that queries can find it. For cat, roughly “I’m an animate noun”.
- Value : the information this token hands over if someone attends to it.
Why three separate vectors instead of just comparing embeddings directly? Because “what I’m looking for” and “what I am” are different things. A pronoun is not similar to a noun; it’s looking for one. Separate query and key projections let the model learn asymmetric relationships like that. And separating the value lets a token be found for one reason but pass on something else.
Then the recipe:
- Score. For each pair of tokens, take the dot productDot productMultiply two vectors element by element and add up the results. It is large when the vectors point in similar directions. . A large score means token matches what token is looking for.
- Scale. Divide by , where is the length of the key vectors (explained below).
- Mask. In a language model, set the scores for future tokens to so nothing can peek ahead.
- Softmax. Turn each row of scores into positive weights that sum to 1, using the softmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total.. These are the attention weightsAttention weightsThe softmax-normalized scores saying how much each token draws from every other token. Each row sums to 1..
- Mix. Each token’s output is the weighted average of all the value vectors, using its row of weights.
That’s the whole thing. Step through it below. The embeddings and the three weight matrices were designed by hand, with 4 dimensions each that have readable meanings (animate, thing, pronoun, action), so you can check every number. In a trained model, nobody chooses them: they are learned by gradient descent, and the dimensions don’t come with labels.
Each token arrives as a vector. In this toy, the 4 dimensions have readable meanings (animate, thing, pronoun, action); in a real model there are thousands and they are not human-labeled. “it” = (0.2, 0.2, 1, 0).
| animate | thing | pronoun | action | |
|---|---|---|---|---|
| The | 0.1 | 0.1 | 0.0 | 0.0 |
| cat | 1.0 | 0.2 | 0.0 | 0.0 |
| sat | 0.1 | 0.0 | 0.0 | 1.0 |
| on | 0.0 | 0.3 | 0.0 | 0.1 |
| the | 0.1 | 0.1 | 0.0 | 0.0 |
| mat | 0.0 | 1.0 | 0.0 | 0.0 |
| because | 0.0 | 0.0 | 0.1 | 0.3 |
| it | 0.2 | 0.2 | 1.0 | 0.0 |
| was | 0.0 | 0.0 | 0.2 | 0.8 |
| tired | 0.3 | 0.0 | 0.0 | 0.9 |
Things to notice as you step through:
- Stage 2. The query for it has a big first component (5.00), because maps the pronoun feature to “looking for animate”. Only cat (and, weakly, tired and it itself) has a large key in that slot.
- Stage 3. The scores row for it has its peak at cat (5.22). mat scores 1.10: a thing, but not animate.
- Stage 6. After the softmax, it sends 58% of its attention to cat. Every row sums to 1.
- Stage 7. The output for it has absorbed cat’s value vector. Its “animate” component jumps from 0.20 to about 0.61. The next layer receives an it that carries cat-information.
Why divide by √d?
The dot product of two random vectors grows with their length. If each component of and has mean 0 and variance 1, then is a sum of such products and has variance . With , a typical head size, scores routinely land in the ±20 range. Fed into a softmax, scores that spread out produce a nearly one-hot distribution: one weight close to 1 and the rest close to 0. The softmax is then saturated, its gradients are tiny, and learning stalls.
Dividing by brings the variance back to 1, whatever the head size. It is a small fix, but the original Transformer paper called it out explicitly, and it’s why the formula is called scaled dot-product attentionScaled dot-product attentionAttention(Q, K, V) = softmax(QKᵀ/√d_k)·V: compare queries with keys, normalize, and take a weighted average of values..
The causal mask: no peeking
GPT-style models are trained to predict each next token. During training, the model processes a whole passage at once, making a prediction at every position in parallel (see next-token prediction). If token 5 could attend to token 6, predicting token 6 would be trivial: just copy it. So we apply a causal maskCausal maskA mask that stops each token from attending to later tokens, so the model can't peek at the future during training.: before the softmax, every score where the key comes after the query is set to . Since , those weights become exactly zero. The result is a lower-triangular attention matrix: row 1 can only see token 1, row 10 can see everything.
Encoder models like BERT, which are not trained to generate left to right, skip the mask and let every token see the whole input. That’s the toggle in both demos.
The attention pattern as a picture
The matrix of attention weights is easiest to read as a heatmap: one row per token doing the looking (the query), one column per token being looked at (the key). Each row is a probability distribution.
Low τ sharpens each row toward a single key (low entropy); high τ flattens it toward a uniform average (entropy near the maximum). Turn the mask off and early tokens can suddenly see later ones: “The” now looks ahead.
Things to try:
- Row it, τ = 1. One dominant column, cat. The entropy readout is well below its maximum.
- τ → 0.25. Every row sharpens. it now puts almost everything on cat. This is what unscaled attention with large dimensions does all the time, and it’s too decisive to learn well.
- τ → 4. Rows approach uniform averages, and the entropy approaches its maximum. Attention that looks everywhere equally carries almost no information about which token matters.
- Mask off. The upper triangle fills in. The at position 1, which could previously only see itself, now spreads its attention across the whole sentence, including words that come after it. A left-to-right language model must never have that information.
Where this sits inside a Transformer
Our demo has one head with . Real models are the same computation at a larger size. GPT-2 small, for instance, has 12 layers, each with 12 attention heads, and each head works with 64-dimensional queries, keys and values carved out of the 768-dimensional token vectors. The heads run side by side, their outputs are concatenated and projected back to 768 dimensions, and the result is added to the token’s vector rather than replacing it. That addition (a residual connectionResidual connectionAdding a layer's input to its output (x + f(x)). This creates a 'residual stream' and makes very deep networks trainable.) means attention contributes information to each token instead of overwriting it, so it keeps knowing that it is a pronoun while also gaining cat-information.
After attention comes a small feed-forward network (an MLPMLP (feed-forward network)A multi-layer perceptron: linear layers with nonlinear activations between them. Each Transformer block contains one.) applied to each token separately. A useful slogan: attention moves information between tokens; the MLP processes information within a token. Stack dozens of these layers and the vector at each position becomes an increasingly rich, context-aware description of that token, until the final layer turns the last position’s vector into next-token logits. The Transformer walkthrough follows one token through the whole stack.
Two more properties worth knowing. First, attention by itself has no sense of order: shuffle the tokens and each one gets the same output, just shuffled, because a weighted sum doesn’t care where things are. Position must be injected separately, which the positional encoding lesson covers. Second, the score matrix is for tokens. Double the context, and you quadruple the work and memory for this step. That quadratic cost shapes everything from context-window limits to the KV cache.
MATH CORNER · optionalAttention(Q, K, V) = softmax(QKᵀ/√dₖ)V, fully worked
Stack the token vectors as rows: . With learned and ,
where the softmax is applied to each row and is the mask ( if , else 0). Row of the output is with .
Why : if the components of and are independent with mean 0 and variance 1, then , so has variance 1.
A 3-token example with (so ). Tokens cat, sat, it, with queries, keys and values given directly:
| token | |||
|---|---|---|---|
| cat | (0, 2) | (2, 0) | (1, 0) |
| sat | (2, 0) | (0, 1) | (0, 1) |
| it | (2, 0) | (1, 1) | (0.5, 0.5) |
Scores (row = query, column = key): cat row ; sat row ; it row . For example, .
Scale by , then mask the future:
| query | key: cat | key: sat | key: it |
|---|---|---|---|
| cat | 0.000 | −∞ | −∞ |
| sat | 2.828 | 0.000 | −∞ |
| it | 2.828 | 0.000 | 1.414 |
Softmax each row. For it: , , , which sum to , giving weights . The sat row gives , and cat can only see itself: .
Mix the values. For it:
The output for it is now mostly cat’s value. Notice also that sat attends 94% to cat: a verb finding its subject.
In code
Single-head causal self-attention from scratch, in about fifteen lines of PyTorch:
import math
import torch
def self_attention(x, W_q, W_k, W_v, causal=True):
# x: (n, d) token vectors; W_*: (d, d_k) learned projections
Q, K, V = x @ W_q, x @ W_k, x @ W_v
scores = Q @ K.T / math.sqrt(K.shape[-1]) # (n, n)
if causal:
n = x.shape[0]
future = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(future, float("-inf"))
weights = scores.softmax(dim=-1) # each row sums to 1
return weights @ V, weights # (n, d_v), (n, n)
n, d, d_k = 10, 16, 8
x = torch.randn(n, d)
W_q, W_k, W_v = (torch.randn(d, d_k) / math.sqrt(d) for _ in range(3))
out, A = self_attention(x, W_q, W_k, W_v)
print(out.shape, A.sum(dim=-1)) # (10, 8), all ones
# The same thing, fused and memory-efficient:
out2 = torch.nn.functional.scaled_dot_product_attention(
(x @ W_q)[None], (x @ W_k)[None], (x @ W_v)[None], is_causal=True)
- “Attention weights tell you exactly why the model made a decision.” They show where one head in one layer read from, which is a useful clue. But outputs depend on values, many heads, many layers and the MLPs between them. High attention is not the same as high influence.
- “Queries, keys and values are different kinds of input.” All three come from the same token vectors, through three different learned matrices. In self-attention, every token plays all three roles at once.
- “The √d scaling is a minor detail.” Without it, scores grow with head size and the softmax saturates, so gradients vanish and training becomes unstable.
- “The causal mask makes the model only look at the previous token.” It allows looking at all earlier tokens, and at itself. It only forbids looking at later ones.
- “Attention knows word order.” On its own it is order-blind: a weighted sum doesn’t care about positions. Order comes from positional encodings.
Check your understanding
Q1.In self-attention, what does the dot product q_i · k_j measure?
Q2.Why are attention scores divided by √d_k?
Q3.With a causal mask, which tokens can token 4 attend to?
Q4.A row of attention weights is (0.7, 0.2, 0.1) and the value vectors are (1, 0), (0, 1), (1, 1). What is the output?
Q5.You double the context length from 4,000 to 8,000 tokens. Roughly how does the size of the attention score matrix change?
Further reading
- paperAttention Is All You Need — Vaswani et al. (2017). Section 3.2 defines scaled dot-product attention, including the √d_k footnote.
- blogThe Illustrated Transformer — Jay Alammar's widely used visual walkthrough of Q, K, V and multi-head attention.
- videoAttention in transformers, step-by-step — 3Blue1Brown's animated explanation of queries, keys and values.
- videoLet's build GPT: from scratch, in code, spelled out — Andrej Karpathy implements causal self-attention line by line.
- paperA Mathematical Framework for Transformer Circuits — Anthropic's interpretability analysis of attention heads, including induction heads.