Equations · Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (2021); used in LLaMA and most recent LLMs
Rotary position embedding (RoPE), explained term by term
RoPE encodes position by rotating each query and key vector, in pairs of coordinates, by an angle proportional to the token's position. Because rotations compose, the attention score between positions and depends only on their offset , not on where they sit.
Term by term
The embedding of the token at position .
The ordinary query and key projections, before any position information is added.
A rotation matrix for position . It is block-diagonal: separate rotations, the -th turning coordinates by the angle , using and . The superscript is its size, a label, and is the set of all .
Bold uppercase (matrix) · Subscript (index or label) · Superscript (power or label)
The rotation speed of pair , for . The first pair turns by 1 radian per position; later pairs turn ever more slowly, down to about . Here the superscript really is a power.
Theta · Superscript (power or label) · Subscript (index or label)
Shapes
- with even (per head). , but code never builds it: it multiplies by and elementwise.
A small worked example
Take , so , and . A query at position rotates to ; a key at rotates to . Their dot product is . Move both tokens 10 places along and the score is still .
In code
import numpy as np
def rope(x, pos, base=10000.0):
# x: (n, d) queries or keys, pos: (n, 1) positions; pairs are (0,1), (2,3), ...
d = x.shape[-1]
theta = base ** (-np.arange(0, d, 2) / d) # (d/2,)
ang = pos * theta # (n, d/2)
x1, x2 = x[..., 0::2], x[..., 1::2]
out = np.empty_like(x)
out[..., 0::2] = x1 * np.cos(ang) - x2 * np.sin(ang)
out[..., 1::2] = x1 * np.sin(ang) + x2 * np.cos(ang)
return outEvery 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
- 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)