Equations · Vaswani et al., “Attention Is All You Need” (2017)
The multi-head attention formula, explained term by term
Instead of one attention over the full vectors, a Transformer runs smaller attentions in parallel, each with its own learned projections, so different heads can attend to different things. Their outputs are concatenated and mixed by one more matrix.
Term by term
The queries, keys and values. In self-attention all three are the same input , one row per token.
Head 's projection matrices. The subscript is the head number; the superscripts , , are labels, not powers.
Subscript (index or label) · Superscript (power or label) · Bold uppercase (matrix)
Scaled dot-product attention, , run on head 's projected inputs.
The head outputs placed side by side, along the feature axis.
The output projection: mixes the heads' results back into one vector per token. stands for output.
Shapes
- Input . , , usually .
- Each ; the concatenation is ; brings it back to .
A small worked example
The original Transformer: , , so . Each head attends in a 64-dimensional space; eight heads concatenated give 512 again, and is . The total cost is about that of one full-width attention.
In code
import torch
def multi_head(X, Wq, Wk, Wv, Wo, h):
# X: (n, d). Wq, Wk, Wv, Wo: (d, d); Wq holds all h of the W_i^Q side by side
n, d = X.shape
split = lambda M: M.view(n, h, d // h).transpose(0, 1) # (h, n, d/h)
Q, K, V = split(X @ Wq), split(X @ Wk), split(X @ Wv)
w = torch.softmax(Q @ K.transpose(-2, -1) / (d // h) ** 0.5, dim=-1)
heads = w @ V # (h, n, d/h)
return heads.transpose(0, 1).reshape(n, d) @ Wo # concat, then W^OEvery symbol in it
Other equations
- Scaled dot-product attention
- Softmax
- Cross-entropy loss
- Adam update
- Layer normalization
- RMSNorm
- The ELBO
- KL divergence
- Backpropagation through one layer
- LoRA
- GELU
- Dropout
- Batch normalization
- Rotary position embedding (RoPE)
- PPO clipped objective
- DPO loss
- Policy gradient (REINFORCE)
- Bellman equation
- Q-learning update
- InfoNCE contrastive loss
- Diffusion forward process
- DDPM simplified loss
- VAE reparameterization trick
- GAN minimax objective
- AdamW
- Cosine learning-rate schedule
- Perplexity
- Logistic regression
- Normal equation (linear regression)
- Singular value decomposition (SVD)
- Principal component analysis (PCA)