Keep only the k most likely tokens before sampling

Top-k sampling throws away every token except the k most likely ones, then rescales what is left so it sums to 1 again. It stops the model from picking a weird token from the long tail.

Write top_k_filter(probs, k) that takes a 1D array of probabilities and returns a new array of the same length where everything outside the top k is 0 and the top k are renormalised.

If two tokens tie at the cut-off, keep the one with the lower index. If k is at least the vocabulary size, return the probabilities unchanged (renormalised).

Signaturedef top_k_filter(probs, k)

Example

top_k_filter([0.5, 0.2, 0.2, 0.1], 2) returns [0.714..., 0.285..., 0, 0].

Understand the idea

Top-k filtering is like a shortlist: before choosing, you keep only the k strongest candidates and forget the rest. After throwing away the long tail, the kept probabilities no longer add up to 1, so you divide them by their own sum. Ties at the cut-off are broken by keeping the lower index, which a stable sort on negated probabilities gives you for free. Worked example: probs [0.1, 0.4, 0.3, 0.2], k = 2. The top two are index 1 (0.4) and index 2 (0.3). Their sum is 0.7, so the output is [0, 0.4/0.7, 0.3/0.7, 0] = [0, 0.571, 0.429, 0]. If k is at least the vocabulary size, nothing is removed and you only renormalise. Rule: pick the k largest entries (lower index wins ties), set all others to 0, then divide by the sum of what remains. LLM text generation uses top-k to stop rare, odd tokens from being sampled.

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

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

  • Sample 1: exampletop_k_filter([0.5, 0.2, 0.2, 0.1], 2)
  • Sample 2: k = 1 is greedytop_k_filter([0.1, 0.6, 0.3], 1)
  • Test 3: k larger than vocabtop_k_filter([0.25, 0.25, 0.5], 10)
  • Test 4: tie keeps lower indextop_k_filter([0.3, 0.3, 0.3, 0.1], 2)