Ran Wei/ Maths for AI and LLMs
中文
Maths for AI and LLMs · Information theory

Module 4Next-token loss, perplexity and sampling

Compute an autoregressive training score and separate it from choices about how to generate text.

70 minYou need Modules 1 and 3

In this module you will

  • Calculate mean next-token negative log-likelihood and perplexity
  • Explain what must match for a perplexity comparison
  • Compute the effect of temperature on sampling odds
1

Score observed tokens

For a sequence with N>0N>0 scored positions, add the negative log probabilities of the observed tokens and divide by N:N\mathclose{\text{:}}

ℓ=−1N∑i=1Nln⁡q(ti∣t<i),PPL⁡=eℓ.\ell=-\frac{1}{N}\sum_{i=1}^N \ln q(t_i\mid t_{<i}), \qquad \operatorname{PPL}=e^\ell.

Training can feed the actual preceding tokens at every position. This is called teacher forcing. Prompts, padding and other masked positions can be excluded from the loss by omitting them from both numerator and denominator. A corpus-level mean divides the total loss by the total number of scored tokens. An unweighted average of per-document means answers a different question when document lengths differ.

Example 4.1Two tokens✓ Checked

If the assigned probabilities were 1/21/2 and 1/8,1/8\mathclose{\text{,}} the total negative log-likelihood is ln⁡16,\ln16\mathclose{\text{,}} the mean is ln⁡4,\ln4\mathclose{\text{,}} and perplexity is 4.4\mathclose{\text{.}}

Compare perplexities on the same data, tokenization and scored positions. Using different tokenizations changes the unit being averaged. A model that assigns all observed tokens probability 1/K1/K has perplexity K,K\mathclose{\text{,}} which motivates the name. Perplexity is a probability score and offers no direct guarantee about the factual accuracy of generated text.

2

Generate a continuation

Each generated token becomes part of the next prefix. With logits ziz_i and temperature T>0,T>0\mathclose{\text{,}} the sampling probabilities are proportional to ezi/T.e^{z_i/T}\mathclose{\text{.}} The odds of token ii against token jj are e(zi−zj)/T.e^{(z_i-z_j)/T}\mathclose{\text{.}} A lower temperature increases the odds in favour of the higher logit. Greedy decoding selects a largest logit at each step. Top-kk sampling retains kk candidates selected by the largest scores, with a tie rule if needed, then renormalises the selected probabilities. Changing the sampling rule changes the generation distribution. Evaluate the original model’s perplexity with the original probabilities.

Compute itCompare two temperatures

For two logits separated by ln⁡3,\ln3\mathclose{\text{,}} halve the temperature and compare the resulting odds.

Python
from math import exp, log

gap = log(3)
for temperature in (1.0, 0.5):
    print(f"{exp(gap / temperature):.0f}")
Output
3
9
3

Exercises

Exercise 4.1★Equal confidence

Find perplexity if the model assigns probability 1/51/5 to each of the three observed tokens at their respective prefixes.

Show solution✓ Checked

The mean loss is ln⁡5,\ln5\mathclose{\text{,}} so perplexity is 5.5\mathclose{\text{.}}

Exercise 4.2★★Weight each token

One document has mean loss 22 over three tokens. Another has mean loss 11 over one token. Find the corpus-level mean.

Show solution✓ Checked

The sum is 3⋅2+1=7.3\cdot2+1=7\mathclose{\text{.}} Divide by four to obtain 7/4.7/4\mathclose{\text{.}}

Exercise 4.3★★★Change the odds

At temperature 1,1\mathclose{\text{,}} the odds of AA against BB are 16:1.16:1\mathclose{\text{.}} Find the odds at temperature 22 with the same logits.

Show solution✓ Checked

Doubling the temperature halves the log odds. The new odds are 16:1=4:1.\sqrt{16}:1=4:1\mathclose{\text{.}}

4

Check yourself

1
What is one scoring position in an autoregressive evaluation?
2
How is corpus perplexity calculated from the sum of token losses?
3
Does raising a positive temperature change which logit is largest?
Finished this module?