AI GLOSSARY · AI CONCEPTS
Top-k sampling
Definition
Top-k sampling is a text-generation setting that limits a language model to choosing its next token, a small piece of text, from the k most likely candidates, then picking among them at random by probability.
Also called: top-k, top k, top k sampling, top k llm, top_k.
In plain language
When a language model writes, it scores every possible next piece of text, called a token, then picks one. Top-k sampling shortlists the k highest-scoring candidates and throws away the rest before picking. If k is small, the wording stays close to the most likely choices. If k is larger, there is more variety. It works like a restaurant that shows only the top few dishes on the menu. The limit is that k is a fixed number: Hugging Face notes it does not adapt to how confident the model is at each step, so a sharp distribution can still let odd words in and a flat one can cut plausible ones.
Technical definition
At each step the model produces a probability for every token in its vocabulary. Top-k sampling keeps the k most likely tokens, redistributes the probability mass among only those k tokens, and samples one. The Hugging Face Transformers GenerationConfig describes top_k as the number of highest probability vocabulary tokens to keep for top-k filtering, with a default of 50 if the model's generation configuration does not set one, and sampling is switched on with do_sample=True. A Hugging Face explainer notes that the method does not dynamically adapt the number of words filtered, which motivated top-p, or nucleus, sampling: see Top-p for the cumulative-probability alternative. Holtzman and colleagues proposed nucleus sampling in a 2019 paper.
Worked examples in this catalogue
Catalogue examples point at a skill, guide or coding tool listed on this site, with what to run and what you see. An example marked illustrative describes the item from its own documentation; it was not executed for this page. Platform Scores are our assessment under a published method, not a safety guarantee.
Guide · Illustrative, not executed
What Is an LLM? The Facts Agent Users Need
- What you see
- The guide contrasts an autoregressive Transformer decoder with BERT's masked objective, and separates runtime context from learned parameters.
- Why it exercises the concept
- Top-k can adjust the next-token selection in the guide's autoregressive generation example; it is not a control for every model objective. Illustrative reading, not an executed decoding comparison.
Skill by Skill Almanac · Illustrative, not executed
llm-eval-test-sets 57/100 · Provisional, not yet measuredScored · Method v0.2 · How we score
- What you see
- Builds and validates an eval dataset for any LLM feature, with a checker for duplicates and missing grades.
- Why it exercises the concept
- Sampling settings change how much outputs vary between runs. A fixed eval set is how you compare two settings on the same inputs. The skill does not set top-k itself.
Skill by Skill Almanac · Illustrative, not executed
prompt-writing 57/100 · Provisional, not yet measuredScored · Method v0.2 · How we score
- What you see
- Writes and lints LLM prompts with a fixed structure, injection rules and a numeric test plan.
- Why it exercises the concept
- A contrast case: prompt wording and sampling settings both shape output, and this skill covers the wording side. Sampling is set in an API or runtime, not in the prompt.
How it shows up when you use agents
Top-k is one of the knobs that decide how varied a model's wording is. You meet it when you run an open model yourself, for example through Hugging Face Transformers or a local runtime, or when an API exposes it as a parameter. Hosted coding tools such as Claude Code, Codex and Cursor may not expose it to you at all. Where they do not, you steer with your prompt and your choice of model, for example with Claude Code's /model command.
The practical idea is simple. A small k keeps output close to the likeliest tokens, and a larger k allows more variety. The setting acts together with temperature and with top-p, and the combined effect depends on the implementation, so check the documentation of your runtime. In Transformers' generic mode table, num_beams=1 with do_sample=False gives greedy decoding; num_beams>1 with do_sample=False gives beam search. Sampling uses do_sample=True. Inspect the actual model configuration and other decoding controls rather than assuming the fallback applies.
What breaks when top-k is misunderstood: people expect a fixed k to fit every step. Hugging Face notes that it does not adapt to the shape of the distribution, which is why top-p exists. Another mistake is to assume a sampling setting guarantees accuracy. Changing the shortlist can change the selected answer and its factual claims, but does not verify them. Evaluate decoding settings on your task and check hallucinations against evidence; context or model changes may also help. A next step is to compare two settings on the same fixed test set, as the eval test set skill helps you build.
Common confusions
- Top-k versus top-p. Top-k keeps a fixed number of candidates. Top-p keeps the smallest set whose probabilities add up past p, so the number of candidates changes from step to step. See Top-p sampling.
- Top-k versus temperature. Temperature reshapes how sharp the probabilities are. Top-k removes candidates. See Temperature sampling.
- Sampling versus greedy or beam search. Greedy search takes the likeliest token each time, and beam search tracks several sequences. Top-k picks at random among a shortlist. See Beam search.
- Myth: a lower k makes the model more accurate. It narrows the token shortlist and can change the answer, but does not guarantee more correct content.
Related terms
Terms that mention Top-k sampling
1 terms mention this one
More in AI concepts
Sources
- How to generate text: using different decoding methods for language generation with Transformers, Hugging Face (accessed 2026-11-24)
- Generation (GenerationConfig), Hugging Face (accessed 2026-11-24)
- The Curious Case of Neural Text Degeneration, arXiv (accessed 2026-11-24)
Definitions are written by Skill Almanac from these sources and were checked against them on 2026-11-25. Wikipedia is never the only source.
Review record
Last verified
Drafted by Claude (original draft); OpenAI Codex (bounded factual repairs); sources and example targets checked by Independent automated source review (OpenAI Codex); not human peer review on 2026-11-25. Last verified .
Change log (5)
- : Independent automated factual/example review completed. Cached US query estimate aligned to receipt; no traffic promise. Final technical gate recorded separately; publication disabled.
- : First version.
- : Verifier pass: applied verifier corrections to unsupported or inferred claims.
- : Bounded source repairs: Specified greedy versus beam mode conditions; corrected guide scope and replaced accuracy invariance with no-guarantee task evaluation. Pending independent re-review.
- : Automated review completed; approved for the staged public release. Search indexing is controlled by the release configuration.