Target Token Loss and Exponential Uncertainty Score
Arrays & HashingAuto-graded · 22 test casesLast 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:
average_nll: The mean negative log-likelihood over all tokens wheretarget_maskisTrue.perplexity: The perplexity calculated as $\text{log_base}^{\text{average_nll}}$.
Return a dictionary with keys "average_nll" and "perplexity".
Constraints
token_nllsandtarget_maskhave equal length $N$, where $0 \le N \le 10^5$.log_base > 1.0.- Each element in
token_nllsis a non-negative floating-point number representing the negative log-likelihood of that token. - If there are no target tokens (i.e.,
target_maskcontains noTruevalues 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To evaluate language model perplexity over valid target tokens:
- Iterate through
token_nllsalongsidetarget_mask. - Sum the negative log-likelihood values (
token_nlls) for positions wheretarget_maskisTrue, and keep track of the count of valid target tokens. - If the count of target tokens is zero, return
Nonefor both fields in the dictionary. - Otherwise, compute
average_nllas the total sum divided by the valid count. - Compute
perplexityby exponentiatinglog_baseto the power ofaverage_nll($b^{\text{average_nll}}$).
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of tokens, as we iterate through the list once.
- Space Complexity: $\mathcal{O}(1)$, requiring only scalar variables for aggregation.
from typing import Dict, List, Optional
def compute_perplexity(token_nlls: List[float], target_mask: List[bool], log_base: float) -> Dict[str, Optional[float]]:
total_nll = 0.0
valid_count = 0
for nll, is_target in zip(token_nlls, target_mask):
if is_target:
total_nll += float(nll)
valid_count += 1
if valid_count == 0:
return {"average_nll": None, "perplexity": None}
avg_nll = total_nll / valid_count
ppl = log_base ** avg_nll
return {
"average_nll": avg_nll,
"perplexity": ppl
}