Return the chosen token's log-prob and the top alternatives

Why it matters Token log-probs power confidence estimates, LLM-based classifiers and calibration checks in production apps.

Many LLM APIs can return, for each generated token, its log-probability and the most likely alternatives. That output is used for confidence scores, classification and debugging.

Write top_logprobs(logits, chosen, n). logits is a length-V array, chosen is the id that was sampled and n >= 1. Compute log-probabilities with a stable log-softmax. Return a dict {"token": chosen, "logprob": float, "top": list of (id, logprob) tuples} where "top" holds the n most likely ids from high to low, with ties going to the lower id. n larger than V returns all V.

Signaturedef top_logprobs(logits, chosen, n)

Example

top_logprobs([2, 1, 0], 1, 2) is {"token": 1, "logprob": -1.4076, "top": [(0, -0.4076), (1, -1.4076)]}.

Understand the idea

A logit is a raw score; a log-probability is the log of a real probability, so values from different steps can be compared and exp(logprob) gives a percentage. APIs that return "top logprobs" show the model's runner-up choices at each step, like a quiz show revealing how the audience voted.

Example: logits [2, 1, 0]. Softmax gives probabilities 0.665, 0.245, 0.090, whose logs are -0.408, -1.408, -2.408. If token 1 was sampled, its logprob is -1.408 (a 24.5% chance). The top 2 alternatives are token 0 at -0.408 and token 1 at -1.408.

Rule: logprob = x - logsumexp(x); top = the n ids with the largest logprob, ties to the lower id.

Apps use these numbers to turn a model into a classifier (compare the logprobs of "yes" and "no"), to flag low-confidence answers, and to check whether a fine-tune changed what the model considers likely.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletop_logprobs([2.0, 1.0, 0.0], 1, 2)
  • Sample 2: tiestop_logprobs([1.0, 3.0, 3.0, 0.0], 3, 3)
  • Test 3: n too bigtop_logprobs([0.0, 0.0], 0, 5)
  • Test 4: huge logitstop_logprobs([1000.0, 999.0, 0.0], 0, 1)