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.

PPL⁡(X)=exp⁡(−1t∑i=1tlog⁡pθ(xi∣x<i))\operatorname{PPL}(X) = \exp\left(-\frac{1}{t}\sum_{i=1}^{t} \log p_\theta(x_i \mid x_{<i})\right)

Open in the decoder →

Term by term

  1. X=(x1,…,xt)X = (x_1, \ldots, x_t)

    The evaluation text, as a sequence of tt tokens.

  2. pθ(xi∣x<i)p_\theta(x_i \mid x_{<i})

    The probability the model with parameters θ\theta gave to the actual token xix_i, given all the tokens before it. x<ix_{<i} means x1,…,xi−1x_1, \ldots, x_{i-1}.

  3. −1t∑i=1tlog⁡(…)-\frac{1}{t}\sum_{i=1}^{t} \log(\ldots)

    The average negative log-likelihood per token: the cross-entropy loss the model was trained on, in nats.

  4. exp⁡(…)\exp(\ldots)

    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 2(…)2^{(\ldots)} instead; the result is the same.

A small worked example

Four tokens given probabilities 0.5,0.25,0.5,0.1250.5, 0.25, 0.5, 0.125. Their product is 2−72^{-7}, the geometric mean is 2−7/42^{-7/4}, so the perplexity is 27/4≈3.362^{7/4} \approx 3.36. 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

xi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)x1,…,xnx_1, \ldots, x_nDots (ellipsis)p(x),  q(z)p(\mathbf{x}), \; q(\mathbf{z})Probability p(x)p(y∣x)p(y \mid x)Given (conditional bar)pθ(x)p_\theta(x)Thetalog⁡p(x)≥LELBO\log p(x) \geq \mathcal{L}_{\text{ELBO}}Inequalitieslog⁡pθ(x)\log p_\theta(x)Logarithm∑i=1Nxi\sum_{i=1}^{N} x_iSummationab\frac{a}{b}Fractionex=exp⁡(x)e^{x} = \exp(x)ExponentialH(p)=−∑xp(x)log⁡p(x)H(p) = -\sum_x p(x) \log p(x)Entropy and cross-entropy

Other equations