◆ AI All-in-One

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
↗ Plan a path here

Read first

AttentionMatrices and Matrix Multiplication

This leads to

The KV Cache and Fast InferenceLong Context and Efficient AttentionPositional EncodingsThe Transformer
The full path from zero — 23 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. LSTMs and GRUs
  22. Sequence-to-Sequence Models
  23. Attention
  24. 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: softmax(QK⊤/d) V\text{softmax}(\mathbf{Q}\mathbf{K}^\top / \sqrt{d})\,\mathbf{V}.

How it works

The formula

Put the vectors of the nn tokens as the rows of a matrix X\mathbf{X}, of shape n×dmodeln \times d_{\text{model}}. Three learned weight matrices turn it into queries, keys and values:

Q=XWQ,K=XWK,V=XWV\mathbf{Q} = \mathbf{X}\mathbf{W}_Q, \qquad \mathbf{K} = \mathbf{X}\mathbf{W}_K, \qquad \mathbf{V} = \mathbf{X}\mathbf{W}_V

Row ii of Q\mathbf{Q} is token ii's query, and so on. Then scaled dot-product attention is

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}

In words:

  1. QK⊤\mathbf{Q}\mathbf{K}^\top is an n×nn \times n table of dot products: entry (i,j)(i, j) says how well token ii's query matches token jj's key. K⊤\mathbf{K}^\top is K\mathbf{K} transposed (rows become columns), which is what makes the multiplication compare every query with every key.
  2. Divide by dk\sqrt{d_k}, where dkd_k is the length of each key vector (explained below).
  3. Apply softmax to each row separately, so each token's weights are positive and sum to 1. This n×nn \times n table of weights is the attention matrix.
  4. Multiply by V\mathbf{V}: row ii of the result is token ii's weighted average of all value vectors.

The output has the same shape as the input, n×dn \times d: 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:

X=(100111)←the←cat←sat\mathbf{X} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{pmatrix} \begin{matrix} \leftarrow \text{the} \\ \leftarrow \text{cat} \\ \leftarrow \text{sat} \end{matrix}

and these weight matrices (in a real model they are learned; here we pick small integers so the arithmetic stays easy):

WQ=(1012),WK=(1101),WV=(1002)\mathbf{W}_Q = \begin{pmatrix} 1 & 0 \\ 1 & 2 \end{pmatrix}, \qquad \mathbf{W}_K = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}, \qquad \mathbf{W}_V = \begin{pmatrix} 1 & 0 \\ 0 & 2 \end{pmatrix}

Step 1: queries, keys and values. Multiply each row of X\mathbf{X} by each weight matrix (matrix multiplication: row times column, summed). For "cat", (0,1) WQ=(0⋅1+1⋅1,  0⋅0+1⋅2)=(1,2)(0, 1)\,\mathbf{W}_Q = (0 \cdot 1 + 1 \cdot 1,\; 0 \cdot 0 + 1 \cdot 2) = (1, 2). Doing all of them:

Q=(101222),K=(110112),V=(100212)\mathbf{Q} = \begin{pmatrix} 1 & 0 \\ 1 & 2 \\ 2 & 2 \end{pmatrix}, \qquad \mathbf{K} = \begin{pmatrix} 1 & 1 \\ 0 & 1 \\ 1 & 2 \end{pmatrix}, \qquad \mathbf{V} = \begin{pmatrix} 1 & 0 \\ 0 & 2 \\ 1 & 2 \end{pmatrix}

Step 2: scores. Every query against every key. Row 2 ("cat" asking), with qcat=(1,2)\mathbf{q}_{\text{cat}} = (1, 2):

  • vs the, k=(1,1)\mathbf{k} = (1, 1): 1⋅1+2⋅1=31 \cdot 1 + 2 \cdot 1 = 3
  • vs cat, k=(0,1)\mathbf{k} = (0, 1): 1⋅0+2⋅1=21 \cdot 0 + 2 \cdot 1 = 2
  • vs sat, k=(1,2)\mathbf{k} = (1, 2): 1⋅1+2⋅2=51 \cdot 1 + 2 \cdot 2 = 5

The full table is

QK⊤=(101325426)\mathbf{Q}\mathbf{K}^\top = \begin{pmatrix} 1 & 0 & 1 \\ 3 & 2 & 5 \\ 4 & 2 & 6 \end{pmatrix}

Step 3: scale. Here dk=2d_k = 2, so divide everything by 2≈1.414\sqrt{2} \approx 1.414:

QK⊤2=(0.7070.0000.7072.1211.4143.5362.8281.4144.243)\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{2}} = \begin{pmatrix} 0.707 & 0.000 & 0.707 \\ 2.121 & 1.414 & 3.536 \\ 2.828 & 1.414 & 4.243 \end{pmatrix}

Step 4: softmax each row. Row 2: e2.121=8.342e^{2.121} = 8.342, e1.414=4.113e^{1.414} = 4.113, e3.536=34.313e^{3.536} = 34.313. Their sum is 46.76846.768, so the weights are 8.342/46.768=0.1788.342/46.768 = 0.178, 4.113/46.768=0.0884.113/46.768 = 0.088 and 34.313/46.768=0.73434.313/46.768 = 0.734. All three rows:

A=(0.4010.1980.4010.1780.0880.7340.1870.0450.768)\mathbf{A} = \begin{pmatrix} 0.401 & 0.198 & 0.401 \\ 0.178 & 0.088 & 0.734 \\ 0.187 & 0.045 & 0.768 \end{pmatrix}

Each row sums to 1. "Cat" puts 73% of its attention on "sat".

Step 5: weighted sum of values. Row 2:

0.178 (1,0)+0.088 (0,2)+0.734 (1,2)=(0.178+0.734,    0.176+1.468)=(0.912, 1.643)0.178\,(1, 0) + 0.088\,(0, 2) + 0.734\,(1, 2) = (0.178 + 0.734,\;\; 0.176 + 1.468) = (0.912,\, 1.643)

(The second number is 1.643 rather than 1.644 because the weights were rounded for display.) The full output:

output=(0.8021.1980.9121.6430.9551.627)\text{output} = \begin{pmatrix} 0.802 & 1.198 \\ 0.912 & 1.643 \\ 0.955 & 1.627 \end{pmatrix}
Self-attention on 3 tokens with 2-number vectors (every value from the worked example) X (input) 3 tokens × 2 1 0 the 0 1 cat 1 1 sat Q = X·W_Q 1 0 1 2 2 2 K = X·W_K 1 1 0 1 1 2 V = X·W_V 1 0 0 2 1 2 three learned projections scores Q·Kᵀ / √2 0.707 0.000 0.707 the 2.121 1.414 3.536 cat 2.828 1.414 4.243 sat row = query, column = key the cat sat weights A = softmax(row) each row sums to 1 0.401 0.198 0.401 the 0.178 0.088 0.734 cat 0.187 0.045 0.768 sat softmax each row output = A·V 3 tokens × 2, now context-aware 0.802 1.198 the 0.912 1.643 cat 0.955 1.627 sat Row 2 (“cat”): 0.178·(1,0) + 0.088·(0,2) + 0.734·(1,2) = (0.912, 1.643)
Fig. 1 The whole computation for "the cat sat". Three learned matrices turn the inputs into queries, keys and values; queries are compared with keys, each row is softmaxed into weights, and the weights mix the values into new, context-aware vectors.

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 dkd_k such products, and its spread (standard deviation) grows like dk\sqrt{d_k}. With dk=128d_k = 128 the scores would typically be about 11 times bigger than with dk=1d_k = 1. 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 dk\sqrt{d_k} 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 −∞-\infty to every score where the key comes after the query (column jj > row ii) before the softmax. Since e−∞=0e^{-\infty} = 0, those positions get exactly zero weight, and the remaining weights in each row still sum to 1:

softmax ⁣(QK⊤dk+M)V,M=(0−∞−∞00−∞000)\text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}} + \mathbf{M}\right)\mathbf{V}, \qquad \mathbf{M} = \begin{pmatrix} 0 & -\infty & -\infty \\ 0 & 0 & -\infty \\ 0 & 0 & 0 \end{pmatrix}

In our example, row 1 ("the") can only see itself, so its weights become (1,0,0)(1, 0, 0) and its output is just its own value, (1,0)(1, 0). Row 2 ("cat") now has only two scores, 2.121 and 1.414, giving weights 8.342/12.455=0.6708.342/12.455 = 0.670 and 4.113/12.455=0.3304.113/12.455 = 0.330, and output 0.670 (1,0)+0.330 (0,2)=(0.670,0.660)0.670\,(1, 0) + 0.330\,(0, 2) = (0.670, 0.660). Row 3 is unchanged, because "sat" was already last.

Attention weights as heatmaps (rows: the token asking; columns: the token looked at) Full (encoder style) every token sees every token the cat sat the 0.401 0.198 0.401 cat 0.178 0.088 0.734 sat 0.187 0.045 0.768 Causal (decoder style) future cells set to −∞, so weight 0 the cat sat the 1.000 0 0 cat 0.670 0.330 0 sat 0.187 0.045 0.768 The mask added to the scores 0 −∞ −∞ 0 0 −∞ 0 0 0 Reading row 2 of the causal map: when processing “cat”, the model may only use “the” and “cat” itself. The removed weight is shared out again by the softmax: 0.670 + 0.330 = 1. The last row is unchanged, because “sat” could already see everything before it.
Fig. 2 The attention weights of the worked example as heatmaps. Left: full attention, as in BERT-style encoders. Middle: causal attention, as in GPT-style decoders; each token sees only itself and earlier tokens. Right: the mask that is added to the scores to achieve this.

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 WQ\mathbf{W}_Q, WK\mathbf{W}_K, WV\mathbf{W}_V:

headi=Attention(XWQ(i), XWK(i), XWV(i))\text{head}_i = \text{Attention}(\mathbf{X}\mathbf{W}_Q^{(i)},\, \mathbf{X}\mathbf{W}_K^{(i)},\, \mathbf{X}\mathbf{W}_V^{(i)})
MultiHead(X)=Concat(head1,…,headh) WO\text{MultiHead}(\mathbf{X}) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,\mathbf{W}_O

The original Transformer had dmodel=512d_{\text{model}} = 512 and h=8h = 8 heads of size dk=512/8=64d_k = 512/8 = 64. The heads' outputs are concatenated side by side back to width 512 and mixed by one more learned matrix WO\mathbf{W}_O. 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.

Multi-head attention (sizes from the original Transformer: d_model = 512, 8 heads of 64) input X n × 512 head 1 own W_Q, W_K, W_V: 512 → 64 e.g. looks at the previous token n×64 head 2 own W_Q, W_K, W_V: 512 → 64 e.g. verb looks at its object n×64 head 8 own W_Q, W_K, W_V: 512 → 64 e.g. copies a repeated pattern n×64 ⋮ heads 3 to 7 concatenate n × (8·64 = 512) × W_O n × 512 mixes the heads back together Each head runs the same scaled dot-product attention on its own 64-number slice, so it can learn its own notion of relevance. Total cost is about that of one 512-wide head. Head roles shown are examples of patterns researchers have found in trained models; nobody assigns them.
Fig. 3 Multi-head attention. The input is projected into several smaller query, key and value spaces, attention runs separately in each head, and the results are concatenated and mixed by W_O.

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 X\mathbf{X} 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 n×nn \times n 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 n2n^2. 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 4×64×644 \times 64 \times 64 weights for WQ\mathbf{W}_Q, WK\mathbf{W}_K, WV\mathbf{W}_V and WO\mathbf{W}_O, plus 4×644 \times 64 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_attention a boolean attn_mask uses True for positions that may be attended to; in nn.MultiheadAttention a boolean attn_mask uses True for 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 1/dk1/\sqrt{d_k}, 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 n×nn \times n 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

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

  1. By hand, compute row 1 ("the") of the unmasked example: scores (1,0,1)/2(1, 0, 1)/\sqrt{2}, softmax, then the weighted sum of values. Check you get (0.802,1.198)(0.802, 1.198).
  2. 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?
  3. Remove the / np.sqrt(...) and multiply all three weight matrices by 10. Look at A. What happened to the weights, and why would that hurt learning?

Hint for 1: e0.707=2.028e^{0.707} = 2.028, so the weights are 2.028/5.0562.028/5.056, 1/5.0561/5.056 and 2.028/5.0562.028/5.056.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. What is the difference between attention in the original translation setting and self-attention?

  2. Why are attention scores divided by √d_k?

  3. A GPT-style model's training loss drops suspiciously fast, but its generated text is garbage. What should you check first?

  4. A self-attention layer has d_model = 512 and 8 heads. What is the size of each head's query and key vectors, and how does total cost compare with one full-width head?

  5. You shuffle the order of the input tokens to a self-attention layer with no positional information. What happens to the outputs?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Article

The Illustrated Transformer

Jay Alammar · Beginner · Free

The famous picture-by-picture walk through the Transformer architecture.

Interactive

Transformer Explainer

Georgia Tech Polo Club · Beginner · Free

An interactive visualisation of GPT-2 running in your browser. Type text and watch every step.

Tutorial

The Annotated Transformer

Harvard NLP · Advanced · Free

The original Transformer paper, line by line, with working PyTorch code beside each paragraph.

Paper

Attention Is All You Need

Vaswani et al. · 2017 · Advanced · Free

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