Keep the nucleus: top-p filtering

Top-p sampling keeps the smallest set of tokens whose probabilities add up to at least p, and drops the long tail. Unlike top-k, the set grows when the model is unsure and shrinks when it is confident.

Write top_p_filter(probs, p) for a 1D probability vector. Sort tokens by probability (ties: lower index first), keep tokens until the running total reaches at least p (always keep at least one), zero the rest, renormalise, and return the new vector in the original order.

Signaturedef top_p_filter(probs, p)

Understand the idea

Top-p (nucleus) sampling keeps the smallest group of most likely tokens whose probabilities add up to at least p, then renormalises. When the model is confident, that group is small; when unsure, it grows. Like ordering from the dishes that together cover most of what customers usually order. Sort by probability (lower index first on ties), add up until the running total reaches p, and include the token that crosses p. Worked example: probs [0.1, 0.5, 0.25, 0.15], p = 0.7. Sorted: index 1 (0.5), index 2 (0.25), index 3, index 0. After index 1 the total is 0.5, below 0.7. After index 2 it is 0.75, which reaches 0.7, so stop. Kept sum 0.75, output [0, 0.667, 0.333, 0] in original order. With p = 0.4, the top token alone is 0.5, so only it is kept. Rule: keep the shortest prefix of the sorted list whose sum >= p (at least one token), zero the rest, divide by the kept sum. Most LLM APIs expose top_p as a setting.

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

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

  • Sample 1: p = 0.8top_p_filter([0.1, 0.5, 0.25, 0.15], 0.8)
  • Sample 2: confident model keeps onetop_p_filter([0.05, 0.9, 0.05], 0.5)
  • Test 3: p = 1 keeps alltop_p_filter([0.2, 0.3, 0.5], 1.0)