Scaled Dot-Product Attention
Attention lets every position of a sequence gather information from every other position in a single step, with weights computed from the data. It is a soft, differentiable dictionary lookup: each query is compared with all keys, the similarities become a probability distribution by a softmax, and the output is the correspondingly weighted average of the values. The linear-algebra view is in Attention as Linear Algebra.
The formula
For positions with queries , keys and values :
The softmax is taken along each row, so row of the weight matrix is a distribution over the keys, and output is . In self-attention, , , all come from the same sequence .
import numpy as np
rng = np.random.default_rng(0)
n, d_model, d_k = 4, 8, 4
X = rng.normal(size=(n, d_model))
WQ, WK, WV = (rng.normal(0, d_model**-0.5, (d_model, d_k)) for _ in range(3))
Q, K, V = X @ WQ, X @ WK, X @ WV
S = Q @ K.T / np.sqrt(d_k)
A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
out = A @ V
print("attention weights (rows sum to 1):\n", np.round(A, 3))
print("output shape:", out.shape)
print("output row 0 = weighted average of value rows:", np.allclose(out[0], sum(A[0, j] * V[j] for j in range(n))))attention weights (rows sum to 1):
[[0.276 0.242 0.283 0.2 ]
[0.212 0.137 0.287 0.364]
[0.398 0.133 0.296 0.173]
[0.19 0.27 0.236 0.305]]
output shape: (4, 4)
output row 0 = weighted average of value rows: True
Why divide by the square root of the key dimension
If the entries of and are independent with mean 0 and variance 1, then has variance . For the scores have standard deviation about 11, the softmax becomes nearly one-hot, and its gradient vanishes (the Jacobian is almost zero for a one-hot , see Softmax Gradient). Dividing by restores unit variance.
import numpy as np
rng = np.random.default_rng(1)
for d_k in (4, 64, 512):
q = rng.normal(size=(2000, d_k)); k = rng.normal(size=(2000, d_k))
raw = np.sum(q * k, axis=1)
scores = rng.normal(size=(1000, 16)) * np.sqrt(d_k) # 16 keys, unscaled score spread
p = np.exp(scores - scores.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
print(f"d_k={d_k:3d}: std of q.k = {raw.std():6.2f} (sqrt d_k = {np.sqrt(d_k):5.2f}); "
f"unscaled softmax max weight {p.max(1).mean():.3f}, scaled std {np.std(raw / np.sqrt(d_k)):.2f}")d_k= 4: std of q.k = 2.01 (sqrt d_k = 2.00); unscaled softmax max weight 0.467, scaled std 1.01
d_k= 64: std of q.k = 8.02 (sqrt d_k = 8.00); unscaled softmax max weight 0.845, scaled std 1.00
d_k=512: std of q.k = 22.33 (sqrt d_k = 22.63); unscaled softmax max weight 0.947, scaled std 0.99
Properties
- Permutation equivariance: permuting the rows of permutes the output rows the same way. Attention alone has no notion of order, hence positional encodings.
- Cost: the score matrix is , so time and memory grow as and in the sequence length. FlashAttention avoids storing it by computing the softmax in blocks with a running maximum (Overflow and a Stable Softmax).
- Content-based routing: the weights depend on the input, unlike a convolution's fixed kernel. One layer can connect any two positions.
The gradient
With , and , backprop gives , , then through each row's softmax , and finally , .
In software
torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)dispatches to FlashAttention or memory-efficient kernels.- Tensors are shaped
(batch, heads, seq, head_dim);einsum("bhqd,bhkd->bhqk", q, k)computes all score matrices at once (Einsum and Broadcasting). - Cross-attention (decoder queries over encoder keys and values) uses .
Go further: Attention from Scratch adds batches with padding masks and checks the result against PyTorch.
Exercises
Exercise 1: Attention by hand
One query , keys , , values , , . Compute the output.
Answer
About .
Solution
Scores and . Weights and . Output .
Exercise 2: Memory of the score matrix
For a sequence of 32,768 tokens, 32 heads and fp16 scores, how much memory would materialized score matrices need for one layer and one sequence?
Answer
About 68.7 GB.
Solution
bytes. This is why long-context attention never materializes them.
Exercise 3: Permutation equivariance (code)
Check numerically that permuting the input rows of self-attention permutes the output rows in the same way.
Answer
The outputs match after permutation.
Solution
import numpy as np
rng = np.random.default_rng(2)
X = rng.normal(size=(5, 4)); W = [rng.normal(size=(4, 4)) for _ in range(3)]
def attn(X):
Q, K, V = (X @ w for w in W); S = Q @ K.T / 2
A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True); return A @ V
perm = np.array([3, 0, 4, 1, 2])
print(np.allclose(attn(X[perm]), attn(X)[perm]))True
Test yourself
Each row of the attention weight matrix is…
- a one-hot vector
- a probability distribution over the keys
- a value vector
- a key vector
Why are the scores divided by ?
- To save memory
- So that dot products have roughly unit variance and the softmax does not saturate
- To make the weights sum to 1
- To add position information
Self-attention's time cost grows with sequence length as…