# Top-k sampling

> Canonical: https://skillalmanac.com/glossary/top-k-sampling | Last verified: 2026-11-25 | Index status: index-eligible

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](/glossary/top-p) for the cumulative-probability alternative. Holtzman and colleagues proposed nucleus sampling in a 2019 paper.

## 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](/glossary/temperature-sampling) and with [top-p](/glossary/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](/glossary/hallucination) 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](/skills/skill-almanac/llm-eval-test-sets) 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](/glossary/top-p).
- **Top-k versus temperature.** Temperature reshapes how sharp the probabilities are. Top-k removes candidates. See [Temperature sampling](/glossary/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](/glossary/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.

## Worked examples in this catalogue

### [What Is an LLM? The Facts Agent Users Need](https://skillalmanac.com/learn/what-is-an-llm-for-agent-users)

Status: illustrative example from the item's own documentation, not executed for this page.

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.

### [llm-eval-test-sets](https://skillalmanac.com/skills/skill-almanac/llm-eval-test-sets)

Status: illustrative example from the item's own documentation, not executed for this page.

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.

### [prompt-writing](https://skillalmanac.com/skills/skill-almanac/prompt-writing)

Status: illustrative example from the item's own documentation, not executed for this page.

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.

## Related terms

- [Top-p sampling](https://skillalmanac.com/glossary/top-p.md)
- [Temperature (LLM sampling)](https://skillalmanac.com/glossary/temperature-sampling.md)
- [Beam search](https://skillalmanac.com/glossary/beam-search.md)
- [Token](https://skillalmanac.com/glossary/token.md)
- [Inference](https://skillalmanac.com/glossary/inference.md)
- [Softmax](https://skillalmanac.com/glossary/softmax.md)

## Sources

- [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate), Hugging Face (accessed 2026-11-24)
- [Generation (GenerationConfig)](https://huggingface.co/docs/transformers/main_classes/text_generation), Hugging Face (accessed 2026-11-24)
- [The Curious Case of Neural Text Degeneration](https://arxiv.org/abs/1904.09751), arXiv (accessed 2026-11-24)

Definitions are written by Skill Almanac from the sources above and checked against them on 2026-11-25. [Glossary index](https://skillalmanac.com/glossary.md).
