Equations · Vaswani et al., “Attention Is All You Need” (2017)
The attention formula, explained term by term
The core of every Transformer layer. Each token builds a weighted average of the other tokens' values, with the weights set by how well its query matches their keys.
Term by term
The queries, keys and values: matrices with one row per token, made from the input by learned projections ( and so on). The paper writes them unbolded.
Every query dotted with every key: entry is , how well token 's query matches token 's key. The transpose makes the shapes line up.
is the length of each key (and query) vector; the subscript is a label, not an index. Dividing by its square root keeps the scores' variance near 1, so the softmax does not saturate.
The scaled scores, one row per query.
Applied to each row separately, it turns that query's scores into weights that are positive and sum to 1.
Multiplying the weights by makes each output row a weighted average of the value rows.
Shapes
- , , ( queries, keys).
- : one score per query-key pair.
- Output : one row per query.
A small worked example
One query , two keys and , . Scores: . Softmax: . The output is : mostly the first value, because the query matched the first key.
In code
import numpy as np
def attention(Q, K, V):
d_k = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d_k) # (n, m)
w = np.exp(scores - scores.max(-1, keepdims=True))
w = w / w.sum(-1, keepdims=True) # softmax over each row
return w @ V # (n, d_v)Every symbol in it
Other equations
- 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)
- Multi-head attention
- 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)