What is the difference between top-k and top-p sampling?
Top-k keeps a fixed number of the most likely tokens. Top-p (nucleus sampling) keeps the smallest highest-probability set that reaches a cumulative probability threshold. Then the remaining probabilities are renormalized before sampling.
LLM Basics in One Minute
One minute. One concept. Understand LLMs.
Episode 05: Top-k and Top-p Sampling
Worked example: a complete four-token toy vocabulary has probabilities mat 50%, floor 25%, sofa 15%, bed 10%. Top-k=2 keeps mat and floor, which become 2/3 and 1/3 after renormalization. Top-p=0.8 keeps mat, floor and sofa: 75% is below the threshold; 90% reaches it. Their renormalized probabilities are approximately 55.6%, 27.8% and 16.7%. Rounded values may not sum to exactly 100%.
In a second toy context, probabilities are 85%, 7%, 5%, 3%. The same top-p=0.8 keeps only the first token. The candidate set is recomputed from the current distribution at each generation step.
These are illustrative probabilities, not measurements from a model. The filters are shown independently, on probabilities after any temperature scaling, with no ties, penalties or minimum-token overrides. Combined filters, tie handling and filter order depend on the implementation. Word labels simplify tokens and omit leading spaces. Neither method guarantees factual accuracy.
Previous episode — Greedy Decoding, Sampling & Temperature:
Sources:
Hugging Face — Generation parameters
Holtzman et al. — The Curious Case of Neural Text Degeneration (ICLR 2020)
Original procedural visuals and sound effects. Synthetic narration with Kokoro. DM Sans and Space Grotesk fonts under the SIL Open Font License. No third-party footage, logos or music.
#LLM #NucleusSampling #AIExplained
source
