Level 3 In-Depth AI · Transformers and Language Models
Self-Attention and Multi-Head Attention
In self-attention every token of a sequence looks at every other token of the same sequence and pulls in what it needs. Worked by hand with three tokens, then in NumPy and PyTorch, with causal masking and multiple heads.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 23 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 23 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
Read them roughly in this order. See it on the concept map →
Why it matters
Read the sentence "The animal didn't cross the street because it was too tired." What does "it" refer to? The animal. Change "tired" to "wide" and "it" now means the street. To understand one word, you have to look at other words in the same sentence, sometimes far away, and which ones matter depends on the content.
Self-attention is the mechanism that lets a network do exactly that. Every token in a sequence builds a new version of itself by looking at all the other tokens and mixing in information from the relevant ones. After one self-attention layer, the vector for "it" can contain information about "animal". After a few dozen layers, each vector carries a rich, context-aware meaning.
Self-attention is the heart of the The Transformer, and so of GPT, BERT, Claude, Llama, the Vision Transformers and much more. Its two big advantages over recurrent networks (Recurrent Neural Networks, LSTMs and GRUs) are that any token can reach any other in a single step, however far apart, and that all positions are computed in parallel, which suits GPUs perfectly. Its big cost is that the work grows with the square of the sequence length.
The intuition
In the Attention chapter, a decoder looked back at an encoder: one sequence asking questions of another. In self-attention, a sequence asks questions of itself.
Picture a meeting where everyone wears three badges:
- A query badge: "here's what I'm looking for". The word "it" might effectively ask "which noun am I referring to?"
- A key badge: "here's what I have to offer". "Animal" might advertise "I'm an animate noun, a possible subject".
- A value badge: "here's what I'll tell you if you listen to me".
Each person compares their query with everyone's key, decides how much to listen to each, and walks away with a weighted blend of everyone's values. Everyone does this at the same time. Nobody hands out the badges by hand: each token's query, key and value are computed from its own vector by three learned Matrices and Matrix Multiplication, and training discovers which questions and answers are useful.
Key idea Self-attention: each token makes a query, a key and a value. Each token's output is the average of all values, weighted by how well its query matches each key. In matrix form: .
How it works
The formula
Put the vectors of the tokens as the rows of a matrix , of shape . Three learned weight matrices turn it into queries, keys and values:
Row of is token 's query, and so on. Then scaled dot-product attention is
In words:
- is an table of dot products: entry says how well token 's query matches token 's key. is transposed (rows become columns), which is what makes the multiplication compare every query with every key.
- Divide by , where is the length of each key vector (explained below).
- Apply softmax to each row separately, so each token's weights are positive and sum to 1. This table of weights is the attention matrix.
- Multiply by : row of the result is token 's weighted average of all value vectors.
The output has the same shape as the input, : one new, context-aware vector per token.
A worked example by hand: 3 tokens, 2 dimensions
Take three tokens, "the cat sat", each represented by a 2-number vector:
and these weight matrices (in a real model they are learned; here we pick small integers so the arithmetic stays easy):
Step 1: queries, keys and values. Multiply each row of by each weight matrix (matrix multiplication: row times column, summed). For "cat", . Doing all of them:
Step 2: scores. Every query against every key. Row 2 ("cat" asking), with :
- vs the, :
- vs cat, :
- vs sat, :
The full table is
Step 3: scale. Here , so divide everything by :
Step 4: softmax each row. Row 2: , , . Their sum is , so the weights are , and . All three rows:
Each row sums to 1. "Cat" puts 73% of its attention on "sat".
Step 5: weighted sum of values. Row 2:
(The second number is 1.643 rather than 1.644 because the weights were rounded for display.) The full output:
That's it. Every self-attention layer in every Transformer is this calculation, with vectors of length 64 or 128 per head instead of 2, and thousands of tokens instead of 3.
Why divide by √d?
If the entries of a query and a key are random numbers with average 0 and spread 1, their dot product is a sum of such products, and its spread (standard deviation) grows like . With the scores would typically be about 11 times bigger than with . Large scores make softmax saturate: one weight close to 1, the rest close to 0. Gradients through a saturated softmax are almost zero, so learning stalls. Dividing by brings the spread of scores back to about 1, whatever the head size. That's the "scaled" in scaled dot-product attention.
Causal masking: no peeking at the future
A model like GPT is trained to predict each next token (Language Modeling and Next-Token Prediction). During training it processes a whole sentence at once, predicting token 2 from token 1, token 3 from tokens 1–2, and so on, all in parallel. If token 2 could attend to token 3, it could simply copy the answer. So we forbid it.
The causal mask adds to every score where the key comes after the query (column > row ) before the softmax. Since , those positions get exactly zero weight, and the remaining weights in each row still sum to 1:
In our example, row 1 ("the") can only see itself, so its weights become and its output is just its own value, . Row 2 ("cat") now has only two scores, 2.121 and 1.414, giving weights and , and output . Row 3 is unchanged, because "sat" was already last.
Encoders like BERT use no mask, so every token sees both directions. Decoders like GPT use the causal mask, which is what lets them generate text one token at a time.
Multi-head attention
One attention pattern per layer is limiting. A token may need to look at the previous word for grammar, at a far-away noun to resolve "it", and at a matching opening bracket, all at once. Multi-head attention runs several attention operations, called attention heads, in parallel, each with its own smaller , , :
The original Transformer had and heads of size . The heads' outputs are concatenated side by side back to width 512 and mixed by one more learned matrix . Because each head is narrower, the total cost is about the same as one full-width head. GPT-3's largest model used 96 heads of size 128 in each of its 96 layers.
Interpretability researchers have found heads with recognisable jobs in trained models: heads that attend to the previous token, heads that link a verb to its object, and "induction heads" that find an earlier occurrence of the current token and copy what came after it (the Transformer Circuits thread has the details). Many heads, though, do nothing a human can name.
Self-attention ignores order
Shuffle the rows of and the outputs are shuffled the same way, with identical values. Self-attention treats its input as a set. "Dog bites man" and "man bites dog" would look the same. Transformers fix this by adding position information to each token vector; see Positional Encodings.
The cost: quadratic in length
The score table has entries per head per layer. For 1,000 tokens that is a million; for 8,192 tokens about 67 million; for 128,000 tokens over 16 billion. Time and (in a naive implementation) memory grow with . This is the main obstacle to long context windows. Tricks such as FlashAttention, which never stores the full table, sliding windows and sparse patterns are covered in Long Context and Efficient Attention. During generation, the keys and values of past tokens are saved and reused rather than recomputed: that's the The KV Cache and Fast Inference.
Cross-attention
When queries come from one sequence and keys and values from another, it's called cross-attention. That's the encoder-decoder attention of the original Attention chapter, still used in translation models, in Speech Recognition models like Whisper, and in Text-to-Image in Practice models where image features attend to the text prompt.
In code
Self-attention in NumPy, with optional causal masking, reproducing every number above:
import numpy as np
def softmax(x):
e = np.exp(x - x.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def self_attention(X, WQ, WK, WV, causal=False):
Q, K, V = X @ WQ, X @ WK, X @ WV # (n, d) each
scores = Q @ K.T / np.sqrt(K.shape[-1]) # (n, n): every token vs every token
if causal: # hide the future: j > i gets -inf
n = len(X)
scores = np.where(np.triu(np.ones((n, n)), k=1) == 1, -np.inf, scores)
A = softmax(scores) # each row sums to 1
return A @ V, A
X = np.array([[1., 0.], [0., 1.], [1., 1.]]) # "the", "cat", "sat"
WQ = np.array([[1., 0.], [1., 2.]])
WK = np.array([[1., 1.], [0., 1.]])
WV = np.array([[1., 0.], [0., 2.]])
out, A = self_attention(X, WQ, WK, WV)
print(A.round(3)); print(out.round(3))
out, A = self_attention(X, WQ, WK, WV, causal=True)
print(A.round(3)); print(out.round(3))
# [[0.401 0.198 0.401]
# [0.178 0.088 0.734]
# [0.187 0.045 0.768]]
# [[0.802 1.198]
# [0.912 1.643]
# [0.955 1.627]]
# [[1. 0. 0. ]
# [0.67 0.33 0. ]
# [0.187 0.045 0.768]]
# [[1. 0. ]
# [0.67 0.66 ]
# [0.955 1.627]]
PyTorch has a fused, fast version of the formula, and a ready-made multi-head layer:
import torch
import torch.nn.functional as F
X = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
WQ = torch.tensor([[1., 0.], [1., 2.]])
WK = torch.tensor([[1., 1.], [0., 1.]])
WV = torch.tensor([[1., 0.], [0., 2.]])
out = F.scaled_dot_product_attention(X @ WQ, X @ WK, X @ WV, is_causal=True)
print(out) # same numbers as the NumPy version
# Multi-head attention with learned weights: batch 4, 10 tokens, d_model 64, 8 heads
mha = torch.nn.MultiheadAttention(embed_dim=64, num_heads=8, batch_first=True)
x = torch.randn(4, 10, 64)
mask = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1) # True = not allowed
y, weights = mha(x, x, x, attn_mask=mask)
print(y.shape, weights.shape) # weights are averaged over the 8 heads
print(sum(p.numel() for p in mha.parameters()))
# tensor([[1.0000, 0.0000],
# [0.6698, 0.6605],
# [0.9546, 1.6266]])
# torch.Size([4, 10, 64]) torch.Size([4, 10, 10])
# 16640
The parameter count is weights for , , and , plus biases: 16,640. Notice it does not depend on the number of heads or on the sequence length. Build a GPT from Scratch writes a multi-head causal attention layer from scratch in about 20 lines.
Common pitfalls
- Mask conventions differ. In
F.scaled_dot_product_attentiona booleanattn_maskusesTruefor positions that may be attended to; innn.MultiheadAttentiona booleanattn_maskusesTruefor positions that are blocked. Getting this backwards silently lets the model see the future: training loss looks wonderful and generation is garbage. - Forgetting the scale. Without , training is slower and less stable, especially with large heads.
- Softmax over the wrong axis. Weights must sum to 1 over the keys (the last axis), one distribution per query.
- Fully masked rows. If every key in a row is masked (for example, a padding query), the softmax divides 0 by 0 and returns
NaN, which then spreads through the whole network. - Running out of memory on long inputs. The table per head per layer adds up fast. Use the fused PyTorch function, which uses memory-efficient kernels when it can.
Watch out A model that trains suspiciously well but generates nonsense almost always has a broken causal mask. Test it: change the last input token and check that the outputs at all earlier positions don't change.
Where it leads
- Positional Encodings gives self-attention a sense of order.
- The Transformer wraps multi-head self-attention with a feed-forward network, residual connections and layer normalisation into the block that is stacked to make every LLM.
- BERT and Encoder Models (bidirectional, no mask) and GPT and Decoder-Only Models (causal mask) are the two big families.
- The KV Cache and Fast Inference, Long Context and Efficient Attention and Mixture of Experts are about making this computation cheaper at scale.
- Vision Transformers applies exactly the same layer to patches of an image.
A bit of history
Attention began as a bridge between two recurrent networks (Attention). In 2016 several groups used intra-attention or "self-attention" within a single sequence, for example Cheng, Dong and Lapata for machine reading and Parikh and colleagues for natural language inference. The decisive step came in June 2017, when Ashish Vaswani and seven co-authors at Google published Attention Is All You Need. It introduced scaled dot-product attention, multi-head attention and the The Transformer, which dropped recurrence entirely, trained much faster in parallel, and set new records in English–German and English–French translation. Within two years it underpinned BERT and GPT-2, and today it is the most widely used neural network layer in AI.
Try it
- By hand, compute row 1 ("the") of the unmasked example: scores , softmax, then the weighted sum of values. Check you get .
- In the NumPy code, shuffle the rows of
X(e.g.X[[2, 0, 1]]) without a mask. Confirm the outputs are the same rows, shuffled. What does that tell you about word order?- Remove the
/ np.sqrt(...)and multiply all three weight matrices by 10. Look atA. What happened to the weights, and why would that hurt learning?Hint for 1: , so the weights are , and .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
The Illustrated Transformer
The famous picture-by-picture walk through the Transformer architecture.
Transformer Explainer
An interactive visualisation of GPT-2 running in your browser. Type text and watch every step.
Let's build GPT: from scratch, in code, spelled out
Two hours of live-coding a Transformer language model, explaining every line.
The Annotated Transformer
The original Transformer paper, line by line, with working PyTorch code beside each paragraph.
Attention Is All You Need
Introduced the Transformer, the architecture behind every modern LLM.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/self-attention.md