Autoregressive decoding and sampling
Derive temperature, top-k, and nucleus sampling while separating likelihood, diversity, correctness, and reproducibility.
On this page
The question for today
What you’ll understand
- Factor sequence probability into conditional next-token probabilities.
- Calculate the distributions produced by temperature and truncation.
- Design decoding comparisons with explicit stopping and reproducibility settings.
A next-token model supplies a conditional distribution. A decoding policy chooses how to turn that distribution into an actual continuation. The same weights can therefore produce different text under greedy selection, random sampling, or a truncated distribution. Decoding changes the behavior of the system without changing its learned parameters, and higher probability under the model is not the same property as factual correctness or usefulness for a particular user.
Local choices build a sequence
Autoregressive generation conditions each new token on the input and all previously selected output tokens. Greedy decoding takes the highest-probability token at each step, which is a local decision. It does not generally maximize the probability of the complete sequence because an initially less probable token can lead to a much more probable continuation. Beam search retains several candidate prefixes, but its sequence scoring and stopping policy still encode choices about length and preferred outputs.
For an open-ended writing task, maximizing likelihood can produce repetitive or uninteresting continuations. For structured extraction, sampling diversity may be unnecessary. Choose a decoding policy for the task and compare complete outputs under a fixed evaluation protocol. The log probability of a sequence is easy to add across tokens, but comparisons across different tokenizations or lengths need care. A model can assign high probability to a common misconception; decoding alone cannot make its learned distribution factually reliable.
Temperature rescales and truncation removes
For positive temperature, divide logits before softmax. Temperatures below one sharpen relative preferences; above one flatten them. Temperature approaching zero concentrates mass on maximal logits, with ties requiring a convention. A serving interface may implement a special greedy mode at zero, but division by zero is not the mathematical definition. Raising temperature is not an independent source of knowledge: it changes which available continuations are sampled and can increase error as well as variety.
Top-k retains the k highest-scoring tokens and renormalizes. Nucleus, or top-p, sampling retains a smallest high-probability prefix whose cumulative mass reaches the chosen threshold, then renormalizes. Unlike a fixed k, its retained set can vary with distribution shape. State the order if combining temperature and truncation because it can change the selected set and resulting probabilities. Tie handling and minimum-token rules are implementation details that belong in a reproducible decoding configuration.
Stopping rules are part of the result
An end token, stop string, length cap, or cancelled request can each terminate a continuation. Hitting a cap is truncation rather than successful completion and should be recorded separately. Stop strings can cross token boundaries, so process decoded text carefully. Also distinguish time to first output from time to a complete useful answer. A policy that produces much longer answers can raise total cost despite unchanged per-token throughput, and an empty answer can look fast without completing the task.
Record model and tokenizer revisions, prompts, sampling parameters, seeds, output limits, and relevant runtime versions. A seed makes a random process repeatable under controlled conditions but does not promise identical distributed GPU results across every kernel or scheduler. Compare stochastic policies with repeated samples and task-level uncertainty. Inspect failure classes as well as aggregate scores, including repetition, premature termination, invalid formats, and unsupported assertions. Good decoding settings are evidence-backed choices for a workload, not universal constants.
Work it through
Renormalize a nucleus
At one generation step four tokens have probabilities 0.50, 0.25, 0.15, and 0.10. Apply nucleus sampling with threshold 0.80 at temperature one, then compare top-k with k=2.
Sort probabilities, which are already descending. The first two total 0.75, below 0.80; include the third to reach 0.90. The retained nucleus therefore has three tokens.
Divide retained probabilities by 0.90. The sampling probabilities become approximately 0.5556, 0.2778, and 0.1667, with the fourth token assigned zero.
Top-k with k=2 instead retains total mass 0.75 and produces probabilities 2/3 and 1/3. These policies differ even though neither changes the underlying model weights.
A threshold controls cumulative retained mass, while k controls retained count. After truncation, sampling must use the normalized retained distribution.
The living notebook
Explore the model
Interactive lab · probability
Separate randomness from a deterministic choice
Adjust p and n to inspect an exact binomial count distribution for independent identical Bernoulli trials. It illustrates how random outcomes spread, but it is not a categorical token sampler and does not implement temperature, top-k, or nucleus selection.
- Mean · np
- 5
- Variance · np(1−p)
- 2.5
- Total probability
- 1
These are exact binomial probabilities for independent trials with one fixed success probability. Playback tours the distribution; it does not resample outcomes. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forA sampling policy defines a distribution over outcomes; a single realized output cannot summarize that distribution.
Pause & reason
Check your understanding
Your turn
Try it yourself
Two logits differ by ln(4). What are their probability odds at temperature one and temperature two, assuming these are the only two choices?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Softmax probability ratios equal the exponential of the logit difference divided by temperature.
Compare with the solution
At temperature one, odds are exp(ln 4)=4, so probabilities are 0.8 and 0.2. At temperature two, odds are exp(ln 4/2)=2, giving probabilities 2/3 and 1/3. Temperature has flattened the distribution without reversing its ranking or introducing a new candidate.
Keep the idea
Take it with you
- Sequence likelihood factors locally, but greedy selection need not optimize the full sequence.
- Temperature rescales probabilities; truncation removes candidates and renormalizes.
- Evaluate decoding with stopping, cost, repeated samples, and task-specific correctness.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.