v9.1.1
Menu

Perplexity Calculator

easyFREEEvaluation MetricsLLM 3: Applications & Evaluation

Compute the perplexity of a language model on a sequence.

Perplexity is defined as: PPL=exp⁡(−1N∑i=1Nlog⁡P(wi∣w<i))\text{PPL} = \exp\left(-\frac{1}{N} \sum_{i=1}^{N} \log P(w_i | w_{<i})\right)

Given the log-probabilities of each token in a sequence, compute the perplexity.

Input: A list of log-probabilities (natural log), one per token

Output: Perplexity as a float (checked to 4 decimal places).

Example

Input
-1.0 -2.0 -1.5
Output
4.4817
Reasoning
  • Input: log_probs holds one natural-log probability per token, here log⁡P(w1)=−1.0\log P(w_1)=-1.0, log⁡P(w2)=−2.0\log P(w_2)=-2.0, log⁡P(w3)=−1.5\log P(w_3)=-1.5, so N=3N=3. Undoing the logs, the model gave the tokens probabilities of about 0.36790.3679, 0.13530.1353 and 0.22310.2231.
  • Sum and average: ∑ilog⁡P(wi)=−1.0−2.0−1.5=−4.5\sum_i \log P(w_i) = -1.0 - 2.0 - 1.5 = -4.5, and dividing by N=3N=3 gives an average log-probability of −1.5-1.5.
  • Negate: the minus sign in the formula turns this into an average negative log-likelihood of +1.5+1.5 (always ≥0\ge 0, since every log-probability is ≤0\le 0).
  • Exponentiate: PPL=e1.5≈4.48169\text{PPL} = e^{1.5} \approx 4.48169, which is 4.4817 to 4 decimal places.
  • Notice: e−1.5≈0.2231e^{-1.5} \approx 0.2231 is the geometric average of the three token probabilities, and perplexity is its reciprocal: the model was, on average, about as unsure as if it were choosing uniformly among 4.484.48 tokens. A perfect model (all log-probabilities 00) scores exactly 11.

Constraints

  • Log-probabilities are negative (or zero)
  • Use natural log
  • Round to 4 decimal places

Learn this in

More from LLM 3: Applications & Evaluation

solution.py

Test results

Sign in to run your code against the test cases.