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).
def 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.