413. 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).
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def top_k_filter(probs, k)Top-k keeps only the k most likely tokens
Outlines are the full softmax; filled bars are after top-k and renormalising. Example logits for 8 tokens.
- entropy (nats)
- 0.975
- top class
- the
- tokens kept
- 3 of 8
Example 1
Input: top_k_filter([0.5, 0.2, 0.2, 0.1], 2)
Output: [0.714..., 0.285..., 0, 0]
Example 2
Input: probs = [0.1, 0.6, 0.3], k = 1
Output: [0.0, 1.0, 0.0]
Example 3
Input: probs = [0.25, 0.25, 0.5], k = 10
Output: [0.25, 0.25, 0.5]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
np.argsort(-p, kind='stable')[:k] gives the indices to keep.
Hint 2
Copy those into a zero array and renormalise.
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.
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.
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.
Topics
Companies4
- Anthropic a candidate reported this question Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
- Cohere a candidate reported this question Cohere Machine Learning Engineer Interview Questions | Screna AI
- DeepMind the topic appears in interview reports AI Engineering Interview Questions Company Wise (Outcome School)
- OpenAI the topic appears in interview reports Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
From public interview reports and guides. Not affiliated with or endorsed by these companies.