KatInterview

Target Token Loss and Exponential Uncertainty Score

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashingmachine-learningmathnlp

Last updated

Compute the mean negative log-likelihood across target tokens and convert it into perplexity for a given logarithm base.

In autoregressive language modeling, model performance is commonly measured by evaluating how well the model predicts each upcoming token in a sequence.

Given a sequence of token-level negative log-likelihood values token_nlls, a boolean mask target_mask indicating which tokens are valid target predictions (e.g., ignoring prompt tokens or padding), and the logarithm base log_base used when calculating the NLLs, compute:

  1. average_nll: The mean negative log-likelihood over all tokens where target_mask is True.
  2. perplexity: The perplexity calculated as $\text{log_base}^{\text{average_nll}}$.

Return a dictionary with keys "average_nll" and "perplexity".

Constraints

  • token_nlls and target_mask have equal length $N$, where $0 \le N \le 10^5$.
  • log_base > 1.0.
  • Each element in token_nlls is a non-negative floating-point number representing the negative log-likelihood of that token.
  • If there are no target tokens (i.e., target_mask contains no True values or the input lists are empty), return {"average_nll": None, "perplexity": None}.

Examples

Example 1

Input: compute_perplexity([0, 0, 0], [True, True, True], 2)

Output: {'average_nll': 0, 'perplexity': 1}

Example 2

Input: compute_perplexity([1, 2, 3], [True, True, True], 2)

Output: {'average_nll': 2, 'perplexity': 4}

Example 3

Input: compute_perplexity([0, 1, 100, 2], [True, False, True, False], 2)

Output: {'average_nll': 50, 'perplexity': 1125899906842624}

Example 4

Input: compute_perplexity([0.5, 1.5, 2.5], [False, True, True], 2.718281828459045)

Output: {'average_nll': 2, 'perplexity': 7.3890560989306495}

Hints

Hint 1

Filter out tokens where target_mask is False.

Hint 2

Compute the sum of token_nlls for the remaining target tokens and divide by the count of target tokens to get average_nll.

Hint 3

Raise log_base to the power of average_nll to compute perplexity.