Equations · Jelinek et al. (1977), for speech recognition; the standard metric for language models since
The perplexity formula for language models, explained
The usual way to score a language model on held-out text: the exponential of the average cross-entropy per token. It reads as an effective branching factor: a perplexity of 20 means the model is, on average, as unsure as if it were choosing uniformly among 20 tokens. Lower is better.
Term by term
The evaluation text, as a sequence of tokens.
The probability the model with parameters gave to the actual token , given all the tokens before it. means .
Probability p(x) · Given (conditional bar) · Theta · Subscript (index or label) · Inequalities
Undoes the log, turning an average loss into a number of choices. It equals the inverse of the geometric mean of the token probabilities. If the loss is in bits, use instead; the result is the same.
A small worked example
Four tokens given probabilities . Their product is , the geometric mean is , so the perplexity is . A model that spreads probability evenly over a 50,000-token vocabulary has perplexity 50,000. Perplexities are only comparable between models with the same tokenizer.
In code
import torch
import torch.nn.functional as F
def perplexity(logits, targets):
# logits: (t, V) next-token scores; targets: (t,) the actual next tokens
nll = F.cross_entropy(logits, targets) # mean of -log p(x_i | x_<i)
return torch.exp(nll)Every 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)
- 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
- Logistic regression
- Normal equation (linear regression)
- Singular value decomposition (SVD)
- Principal component analysis (PCA)