Sampling

Sampling is the step where a generative model picks its next output, such as a token, from a probability distribution rather than always taking the top choice.

Roadmap step 3 of 4: From probabilities to text. Try it: Transformer Explainer: try temperature, top-k and top-p ↗

What it is

A language model produces a probability distribution over possible next tokens at each step. Sampling is the rule used to choose one token from that distribution. Common approaches include greedy decoding, temperature scaling, top-k, top-p (nucleus) sampling, and beam search. The term is also used for diffusion models, where it means the iterative process of generating an image or audio from noise.

Why it matters

Sampling settings strongly affect output quality, variety and reliability. Low randomness suits code, extraction and tool calling, where consistent answers matter. Higher randomness suits creative writing and brainstorming but raises the risk of errors and drift. Settings can also change benchmark results, so comparisons need to state them.

How it works

The model outputs scores for every candidate token, which are converted to probabilities with a softmax. Temperature rescales the scores before this step: lower values sharpen the distribution, higher values flatten it. Top-k keeps only the k most likely tokens, and top-p keeps the smallest set whose combined probability passes a threshold. A token is then drawn at random from the remaining set and appended to the context, and the process repeats. In diffusion models, a sampler instead runs a series of denoising steps, with the choice of sampler and step count trading speed for quality.

RelatedReasoning