Skip to content

← Metrics & Evaluation step 6 of 7

Easy Primitives

Perplexity from Logits

Perplexity summarizes how much probability a model assigns to the supplied target tokens. Compute the average negative log-probability of those targets, then exponentiate. Lower perplexity means the model assigned greater geometric mean probability to those same targets.

Your task

Implement perplexity(logits, targets).

  • logits is a finite floating-point tensor with shape (N, T, V).
  • targets has shape (N, T) and contains integer-valued IDs in [0, V). The runtime delivers them as floats; cast them to integers for indexing.
  • N, T and V are positive. Test results are representable in the input dtype.
  • Return one Python float, leaving both inputs unchanged.

Targets are already aligned: targets[n, t] is the correct token for logits[n, t, :]. Do not shift either tensor, discard the last position or insert a start token. Every one of the N*T positions counts equally; there is no padding mask or ignored target ID in this exercise.

Calculation

  1. Compute log-softmax over the final vocabulary axis for each position.
  2. Select the log-probability at that position's target ID.
  3. Negate the mean of the selected values across all N*T positions.
  4. Return the natural exponential of that mean loss.
mean_nll = -sum(target_log_probabilities) / (N * T)
perplexity = exp(mean_nll)

Use a stable log-softmax. One formula is shifted - log(sum(exp(shifted))), where shifted is a vocabulary row minus its maximum. Computing softmax and then taking its logarithm can lose very small target probabilities to underflow. Do not average per-token perplexities or exponentiate the total loss.

Example and interpretation

If two target probabilities are 1/2 and 1/8, the mean loss is (log(2) + log(8)) / 2, giving perplexity 4. It is the geometric mean of inverse target probabilities, not their arithmetic mean of 5.

Uniform predictions over V tokens give perplexity V. Perplexity approaches 1 as every target probability approaches 1, but it can exceed V when the model assigns targets very low probability. It is not a literal count of options considered at every position.

Compare perplexities using the same evaluation data, tokenization and scoring rules. A lower value under a different tokenization is not directly comparable.