Filter the next-token distribution with min-p

Top-p keeps a fixed amount of probability mass, which can let in junk tokens when the model is confident. Min-p sampling instead scales the cutoff with the top token: a token survives only if its probability is at least min_p times the largest probability.

Write min_p_filter(probs, min_p). probs is a 1-D array that sums to 1, and 0 < min_p <= 1. Zero out every token with probs < min_p * max(probs), then renormalize the survivors to sum to 1. Return the new array (same length).

Signaturedef min_p_filter(probs, min_p)

Example

probs = [0.5, 0.3, 0.15, 0.05], min_p = 0.2. The cutoff is 0.1, so the last token is removed and the result is [0.526316, 0.315789, 0.157895, 0.0] (rounded).

Understand the idea

Min-p sampling sets a cutoff that moves with the model's confidence. A token survives only if its probability is at least min_p times the top token's probability. When the model is sure, the cutoff is high and junk is removed; when the model is unsure, many options stay. Worked example: probs = [0.6, 0.25, 0.1, 0.05], min_p = 0.25. Cutoff = 0.25 * 0.6 = 0.15. Tokens with 0.1 and 0.05 are removed. Survivors sum to 0.85, so the result is [0.6 / 0.85, 0.25 / 0.85, 0, 0] = [0.7059, 0.2941, 0, 0]. Rule: zero out every entry with p < min_p * max(p), then divide the survivors by their sum so they add to 1; the array keeps its length. Comparing against min_p alone is a fixed floor and can remove every token. The top token always survives because min_p is at most 1. Min-p is offered by many open-source inference servers as an alternative to top-p.

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

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

  • Sample 1: examplemin_p_filter([0.5, 0.3, 0.15, 0.05], 0.2)
  • Sample 2: flat distribution keeps allmin_p_filter([0.26, 0.25, 0.25, 0.24], 0.5)
  • Test 3: confident modelmin_p_filter([0.9, 0.05, 0.03, 0.02], 0.05)
  • Test 4: min_p 1 keeps the maxmin_p_filter([0.1, 0.6, 0.3], 1.0)