Updating every word by looking at the others: the problem self-attention solves
In the sentence "the bank approved the mortgage", the vector of the word "bank" on its own does not say whether it is an institution or the side of a river: the context decides. A model must therefore be able to rewrite the vector of each word as a combination of the vectors of the others, with weights that depend on how relevant the others are. Self-attention does exactly this, with three ingredients already met in this series: dot products to measure relevance, a softmax to turn it into weights that sum to one, and a matrix product to mix the vectors. The formula from the 2017 paper by Vaswani et al. is \text{softmax}(\mathbf{Q}\mathbf{K}^T/\sqrt{d_k})\,\mathbf{V}, and here we read it term by term, with a three-word example worked by hand.
Notation: n is the length of the sequence (the number of tokens), \mathbf{X} \in \mathbb{R}^{n \times d_{\text{model}}} the matrix with one token per row, as in the article on linear algebra. The rest of the background comes from the dot product and the softmax (same article), from the cross-entropy that trains these models (information theory) and from the gradients that update them (differential calculus).
Query, key and value: three projections of the same input
The attention layer multiplies the input by three different learned weight matrices: \mathbf{Q} = \mathbf{X}\mathbf{W}^Q, \mathbf{K} = \mathbf{X}\mathbf{W}^K, \mathbf{V} = \mathbf{X}\mathbf{W}^V, with \mathbf{W}^Q, \mathbf{W}^K \in \mathbb{R}^{d_{\text{model}} \times d_k} and \mathbf{W}^V \in \mathbb{R}^{d_{\text{model}} \times d_v}. The name comes from the analogy with a search: the query of a token is what it is looking for, the key of another is what it presents itself as, the value is the content it transmits if it is chosen. It is an analogy, not a proven property: what the three projections learn is whatever minimises the loss, and nobody imposed it.
The complete formula has four steps, in the order in which they are carried out:
- \mathbf{Q}\mathbf{K}^T \in \mathbb{R}^{n \times n}: element (i, j) is the dot product between the query of token i and the key of token j, that is how much i "looks at" j
- division by \sqrt{d_k}: brings the scores back to a scale that does not depend on the dimension
- softmax on each row: turns the scores into positive weights that sum to 1
- product by \mathbf{V}: each token becomes the weighted average of the values of all the tokens
The order is not interchangeable: the softmax must be applied after the division, because it is the scale of the scores that decides how sharp it is, and the product by \mathbf{V} comes last because the weights must already be normalised. The output is a convex combination of the values (non-negative weights summing to 1), so it lies inside the convex hull of their vectors.
A worked example on three tokens
To see the numbers, set \mathbf{Q} = \mathbf{K} = \mathbf{V} = \mathbf{X} (no learned projection) with three tokens of two components: x_1 = (1, 0), x_2 = (0, 1), x_3 = (1, 1) and d_k = 2. The scores \mathbf{X}\mathbf{X}^T are the dot products: x_1 \cdot x_1 = 1, x_1 \cdot x_2 = 0, x_1 \cdot x_3 = 1, and so on; the first row is (1, 0, 1). Divided by \sqrt{2} \approx 1.414 it becomes (0.7071;\ 0;\ 0.7071). The softmax gives e^{0.7071} = 2.0281 and e^0 = 1, sum 5.0562, hence weights (0.4011;\ 0.1978;\ 0.4011). The output of the first token is 0.4011\,(1, 0) + 0.1978\,(0, 1) + 0.4011\,(1, 1) = (0.8022;\ 0.5989): a mixture in which the tokens most similar to x_1 (itself and x_3) weigh more, but x_2, orthogonal, keeps a residual weight.
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 attention(Q, K, V):
d_k = Q.shape[-1]
weights = softmax(Q @ K.T / np.sqrt(d_k)) # (n, n): one row of weights for each token
return weights @ V, weights
# three tokens with two components; to see the calculations we use Q = K = V = X (no learned projection)
X = np.array([[1.0, 0.0],
[0.0, 1.0],
[1.0, 1.0]])
scores = X @ X.T
print("Q K^T =\n", scores)
print("divided by sqrt(2) =\n", np.round(scores / np.sqrt(2), 4))
out, w = attention(X, X, X)
print("weights (each row sums to 1) =\n", np.round(w, 4))
print("row sums:", w.sum(axis=1))
print("output of the first token =", np.round(out[0], 4), " = 0.4011*(1,0) + 0.1978*(0,1) + 0.4011*(1,1)")
# Output:
# Q K^T =
# [[1. 0. 1.]
# [0. 1. 1.]
# [1. 1. 2.]]
# divided by sqrt(2) =
# [[0.7071 0. 0.7071]
# [0. 0.7071 0.7071]
# [0.7071 0.7071 1.4142]]
# weights (each row sums to 1) =
# [[0.4011 0.1978 0.4011]
# [0.1978 0.4011 0.4011]
# [0.2483 0.2483 0.5035]]
# row sums: [1. 1. 1.]
# output of the first token = [0.8022 0.5989] = 0.4011*(1,0) + 0.1978*(0,1) + 0.4011*(1,1)
The listing defines attention with the four lines of the formula (scores, scale, softmax, weighted average) and applies it to this input. The values coincide with the hand calculation: the first row of weights is (0.4011; 0.1978; 0.4011) and the output of the first token (0.8022; 0.5989). The third row (0.2483; 0.2483; 0.5035) shows that the token x_3 = (1,1), the "largest", attends mostly to itself, because its dot product with itself is 2. The check w.sum(axis=1) verifies that each row is a distribution, and it is the first test to write when you implement attention from scratch.
Why we divide by the square root of the key dimension
If the components of \mathbf{q} and \mathbf{k} are independent variables with mean 0 and variance 1, their dot product \sum_{i=1}^{d_k} q_i k_i has mean 0 and variance d_k (footnote 4 of the paper by Vaswani et al.): it is the sum of d_k independent terms of variance 1. With d_k = 64 the scores have standard deviation 8, and the softmax, which exponentiates, amplifies the differences to almost a "winner takes all", with gradients close to zero for the other weights. Dividing by \sqrt{d_k} brings the variance back to 1, as an experiment shows that measures, for each d_k, the variance of the dot products and how sharp the softmax is.
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)
rng = np.random.default_rng(0)
print("d_k | var(q.k) | var(q.k/sqrt(d_k)) | mean max weight without/with scale | sum p(1-p) without/with scale")
for d_k in (4, 64, 512):
q = rng.normal(size=(20_000, d_k))
k = rng.normal(size=(20_000, d_k))
dots = (q * k).sum(axis=1) # 20000 dot products of independent vectors
# one query against 10 keys: how "sharp" is the softmax?
Q = rng.normal(size=(2000, 1, d_k))
K = rng.normal(size=(2000, 10, d_k))
s = (Q * K).sum(axis=2)
p_raw, p_scaled = softmax(s), softmax(s / np.sqrt(d_k))
sat = lambda p: (p * (1 - p)).sum(axis=1).mean() # close to 0 = saturated softmax (almost one-hot)
print(f"{d_k:5d} {dots.var():8.1f} {(dots / np.sqrt(d_k)).var():18.2f} {p_raw.max(axis=1).mean():.3f} / {p_scaled.max(axis=1).mean():.3f} {sat(p_raw):.3f} / {sat(p_scaled):.3f}")
# Output:
# d_k | var(q.k) | var(q.k/sqrt(d_k)) | mean max weight without/with scale | sum p(1-p) without/with scale
# 4 4.0 1.00 0.499 / 0.308 0.635 / 0.807
# 64 64.3 1.00 0.869 / 0.320 0.186 / 0.806
# 512 502.6 0.98 0.951 / 0.317 0.069 / 0.807
The variance of the dot products is about d_k (4.0; 64.3; 502.6) and after the scaling about 1. The effect on the softmax can be read in the last columns: with d_k = 512 and no scaling the mean maximum weight over ten keys is 0.951, almost a one-hot distribution, while with the scaling it stays at 0.317. The sum \sum p(1-p), which appears in the derivative of the softmax, falls from 0.635 to 0.069 without scaling (saturation, hence a small gradient) and stays at 0.807 with the scaling. The factor is not a detail of numerical stability, as is often read: it is what keeps the softmax in a region where the gradient is usable, whatever the dimension.
More heads: the same parameter budget, more subspaces
Multi-head attention projects \mathbf{Q}, \mathbf{K}, \mathbf{V} into h smaller subspaces, runs attention in each and concatenates the results: \text{MultiHead} = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\mathbf{W}^O, with d_k = d_{\text{model}}/h. In the original Transformer h = 8 and d_{\text{model}} = 512, so d_k = 64. The authors write that multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions, whereas with a single head averaging prevents this. The cost is the same: thanks to the reduced dimension of each head, the total cost is similar to that of a single full-dimension head.
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 multi_head(X, Wq, Wk, Wv, Wo, h):
n, d_model = X.shape
d_k = d_model // h
split = lambda M: (X @ M).reshape(n, h, d_k).transpose(1, 0, 2) # (h, n, d_k)
Q, K, V = split(Wq), split(Wk), split(Wv)
w = softmax(Q @ K.transpose(0, 2, 1) / np.sqrt(d_k)) # (h, n, n)
heads = w @ V # (h, n, d_k)
return heads.transpose(1, 0, 2).reshape(n, d_model) @ Wo, w
rng = np.random.default_rng(0)
n, d_model, h = 6, 16, 4
X = rng.normal(size=(n, d_model))
Wq, Wk, Wv, Wo = (rng.normal(0, 0.3, (d_model, d_model)) for _ in range(4))
out, w = multi_head(X, Wq, Wk, Wv, Wo, h)
print("output", out.shape, " weights", w.shape, " row sums:", np.allclose(w.sum(axis=-1), 1))
# check: one head at a time, with its own columns of W^Q, W^K, W^V
d_k = d_model // h
heads = []
for i in range(h):
c = slice(i * d_k, (i + 1) * d_k)
Q, K, V = X @ Wq[:, c], X @ Wk[:, c], X @ Wv[:, c]
heads.append(softmax(Q @ K.T / np.sqrt(d_k)) @ V)
print("equal to the loop over the heads:", np.allclose(out, np.concatenate(heads, axis=1) @ Wo))
for dm, hh in ((512, 8), (512, 1)):
print(f"d_model = {dm}, h = {hh}: d_k = {dm // hh}, parameters of W^Q, W^K, W^V, W^O = {4 * dm * dm}")
n_tok = 4096
print(f"score matrix with n = {n_tok}: {n_tok ** 2} elements per head, {n_tok ** 2 * 4 / 1e6:.1f} MB in float32")
# Output:
# output (6, 16) weights (4, 6, 6) row sums: True
# equal to the loop over the heads: True
# d_model = 512, h = 8: d_k = 64, parameters of W^Q, W^K, W^V, W^O = 1048576
# d_model = 512, h = 1: d_k = 512, parameters of W^Q, W^K, W^V, W^O = 1048576
# score matrix with n = 4096: 16777216 elements per head, 67.1 MB in float32
The listing implements the heads in vectorised form: you multiply by the full matrices, do a reshape into (n, h, d_k) and bring the head index to the first position, so that a single batched matrix product computes all the heads. The check is a loop that computes one head at a time with the corresponding columns of \mathbf{W}^Q, \mathbf{W}^K, \mathbf{W}^V: the two results coincide. The parameter count confirms the claim: 4 \cdot 512^2 = 1\,048\,576 both with 8 heads of 64 and with one head of 512; the heads cost no additional parameters. What grows with the length is the score matrix: for n = 4096 it has 16 777 216 elements per head (67.1 MB in float32), and it is the reason for the O(n^2 \cdot d) complexity per layer reported in table 1 of the original paper. That one head specialises on syntax and another on coreference is an observation made on specific models, not a consequence of the formula.
Attention does not know the order: positional encoding
Permuting the input tokens permutes the rows of the output in the same way: self-attention is equivariant to permutations. It is not "invariant", as is sometimes read: the output changes, but only by reordering. The consequence is that, on its own, "the dog bites the man" and "the man bites the dog" contain the same words and the model cannot tell them apart by order. The solution in the original paper is to add a position vector to the embeddings:
Each (sine, cosine) pair oscillates with a different frequency, from the fast one at i = 0 up to a very long one. By hand with d_{\text{model}} = 4: position 0 gives (\sin 0, \cos 0, \sin 0, \cos 0) = (0, 1, 0, 1); position 1 gives (\sin 1, \cos 1, \sin 0.01, \cos 0.01) \approx (0.8415;\ 0.5403;\ 0.0100;\ 1.0000), because for i = 1 the denominator is 10000^{2/4} = 100.
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)
rng = np.random.default_rng(1)
n, d = 5, 8
X = rng.normal(size=(n, d))
Wq, Wk, Wv = (rng.normal(0, 0.4, (d, d)) for _ in range(3))
def self_attention(X):
Q, K, V = X @ Wq, X @ Wk, X @ Wv
return softmax(Q @ K.T / np.sqrt(d)) @ V
perm = rng.permutation(n)
print("token permutation:", perm)
print("attention(X[perm]) == attention(X)[perm]:", np.allclose(self_attention(X[perm]), self_attention(X)[perm]))
def positional_encoding(max_len, d_model):
pos = np.arange(max_len)[:, None]
div = np.exp(np.arange(0, d_model, 2) * -(np.log(10000.0) / d_model)) # 1 / 10000^(2i/d_model)
PE = np.zeros((max_len, d_model))
PE[:, 0::2], PE[:, 1::2] = np.sin(pos * div), np.cos(pos * div)
return PE
PE = positional_encoding(50, 4)
print("PE[0] =", np.round(PE[0], 4))
print("PE[1] =", np.round(PE[1], 4), " (by hand: sin 1, cos 1, sin 0.01, cos 0.01)")
# PE(pos + k) as a linear transformation of PE(pos): a rotation for each (sin, cos) pair
pos, k, i = 7, 5, 0
om = 1 / 10000 ** (2 * i / 4)
R = np.array([[np.cos(om * k), np.sin(om * k)], [-np.sin(om * k), np.cos(om * k)]])
print("rotation:", np.round(R @ PE[pos, 0:2], 6), " PE[pos + k]:", np.round(PE[pos + k, 0:2], 6))
# same words in a different order: with fixed positions the output is no longer the same permuted
PE_n = positional_encoding(n, d)
con_pos = self_attention(X[perm] + PE_n)
print("with PE: attention(X[perm] + PE) == attention(X + PE)[perm]:", np.allclose(con_pos, self_attention(X + PE_n)[perm]))
# Output:
# token permutation: [1 0 3 2 4]
# attention(X[perm]) == attention(X)[perm]: True
# PE[0] = [0. 1. 0. 1.]
# PE[1] = [0.8415 0.5403 0.01 1. ] (by hand: sin 1, cos 1, sin 0.01, cos 0.01)
# rotation: [-0.536573 0.843854] PE[pos + k]: [-0.536573 0.843854]
# with PE: attention(X[perm] + PE) == attention(X + PE)[perm]: False
The listing makes four checks. The first confirms the equivariance: attention(X[perm]) equals attention(X)[perm]. The two prints of PE reproduce the hand values. The third explains why sine and cosine: for a frequency \omega, (\sin\omega(p+k), \cos\omega(p+k)) is a rotation by angle \omega k applied to (\sin\omega p, \cos\omega p), so for every fixed distance k the position p+k is a linear function of p (the authors give this as the reason for the choice), and the listing verifies it with a rotation matrix. The last line closes the circle: adding the fixed positions to the reordered tokens, the output is no longer the reordered version of the original (False), that is the model distinguishes the orders. The authors also tried learned positional embeddings and report nearly identical results; they chose the sinusoidal version because it may extrapolate to sequences longer than those seen in training.
Residual connections and layer normalisation
Each sub-layer is wrapped in a residual connection and a normalisation: \text{LayerNorm}(\mathbf{x} + \text{SubLayer}(\mathbf{x})). The residual connection adds the input to the output, so a block that has not yet learned anything lets the signal (and the gradient) pass unchanged. Layer normalisation (Ba, Kiros and Hinton, 2016) normalises each vector along its features, independently of the other samples in the batch, unlike batch normalisation: \text{LayerNorm}(\mathbf{x}) = \dfrac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}}\odot\boldsymbol{\gamma} + \boldsymbol{\beta}, with \mu and \sigma^2 the mean and variance of the single vector and \boldsymbol{\gamma}, \boldsymbol{\beta} learned parameters. The \epsilon goes under the root together with the variance. For \mathbf{x} = (1, 2, 3, 4): mean 2.5, variance 1.25, deviation 1.118, result (-1.5, -0.5, 0.5, 1.5)/1.118 = (-1.3416;\ -0.4472;\ 0.4472;\ 1.3416).
import numpy as np
def layer_norm(x, gamma=1.0, beta=0.0, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True) # population variance, as in the paper by Ba et al.
return (x - mu) / np.sqrt(var + eps) * gamma + beta
x = np.array([1.0, 2.0, 3.0, 4.0])
print("mean", x.mean(), " variance", x.var(), " deviation", round(x.std(), 4))
print("layer norm:", np.round(layer_norm(x), 4), "(by hand: -1.5/1.118, -0.5/1.118, 0.5/1.118, 1.5/1.118)")
y = layer_norm(np.random.default_rng(0).normal(5, 3, size=(3, 16)))
print("for each row: mean", np.round(y.mean(axis=1), 6) + 0.0, " deviation", np.round(y.std(axis=1), 4))
# Output:
# mean 2.5 variance 1.25 deviation 1.118
# layer norm: [-1.3416 -0.4472 0.4472 1.3416] (by hand: -1.5/1.118, -0.5/1.118, 0.5/1.118, 1.5/1.118)
# for each row: mean [0. 0. 0.] deviation [1. 1. 1.]
The listing compares the hand calculation with the function and verifies that, on a random batch, each row comes out with mean zero and deviation 1 (with \boldsymbol{\gamma} = 1 and \boldsymbol{\beta} = 0). The variance is the population one (x.var() without the n-1 correction), as in the definition: a vector of features is not a sample from a larger population, it is the whole set that gets normalised.
What you can do now
You can write scaled attention in about ten lines and verify it by hand on three tokens, justify the factor 1/\sqrt{d_k} with a measurement, implement the heads with a reshape and check them against a loop, and explain why positional encoding is needed and why the sinusoidal form allows relative positions. You also know where the cost grows, the n \times n matrix of scores, and can tell what the formula implies (equivariance, parameter budget) from what is an empirical observation (specialised heads). A model built this way is trained on large amounts of data; the last article of the series is about how to increase it when it is scarce: data augmentation.
Sources
- Vaswani et al., Attention Is All You Need (arXiv 1706.03762) - the scaled attention formula and footnote 4 on the variance of d_k, multi-head with h = 8 and d_k = 64, sinusoidal positional encoding and comparison with the learned one, table 1 on complexity; PDF read, consulted on 2026-11-12
- Ba, Kiros, Hinton, Layer Normalization (arXiv 1607.06450) - normalisation along the features of a single sample, independent of the batch; abstract read, consulted on 2026-11-12
- Deisenroth, Faisal, Ong, Mathematics for Machine Learning (2020), chapters 2 and 3 - the dot product and matrix products on which the calculations rest; PDF read, consulted on 2026-11-12
- NumPy: Broadcasting - the shape rules used in operations between arrays of different shapes, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment