BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Sampling and decoding2 of 17 in topic

413. Keep only the k most likely tokens before sampling

EasySampling and decoding
Asked atAnthropicCohereDeepMindOpenAI

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.

Functiondef top_k_filter(probs, k)
Play with it

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.

0%25%50%75%100%probability, before (outline) and after the filterthe54.9%a30.1%my15%this0%one0%our0%that0%his0%
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.

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.

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
Sampling and decoding
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.

Similar questions
  • LLM sampling: turn logits into probabilities without overflowingEasy
  • Filter the next-token distribution with min-pEasy
  • Greedy decode until end of sequenceEasy
  • Ban tokens and repeated n-grams before samplingEasy
All Sampling and decoding problems
Report
413 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def top_k_filter(probs, k):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS