advanced30 min studyLesson 62 in Engineering

Autoregressive decoding and sampling

Derive temperature, top-k, and nucleus sampling while separating likelihood, diversity, correctness, and reproducibility.

On this page

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.

P(y∣x)=∏t=1TP(yt∣x,y<t),log⁡P(y∣x)=∑t=1Tlog⁡P(yt∣x,y<t)P(y\mid x)=\prod_{t=1}^{T}P(y_t\mid x,y_{<t}),\qquad \log P(y\mid x)=\sum_{t=1}^{T}\log P(y_t\mid x,y_{<t})
The factorization is the probability chain rule for the chosen token sequence, including a declared stopping convention. It does not assert that greedy next-token decisions optimize the product.↔ Scroll wide equations horizontally.

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.

pi(T)=ezi/T∑jezj/T,qi=pi(T)1{i∈S}∑j∈Spj(T)p_i^{(T)}=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}},\qquad q_i=\frac{p_i^{(T)}\mathbf{1}\{i\in S\}}{\sum_{j\in S}p_j^{(T)}}
T must be positive. S is the retained token set after the declared truncation procedure; the denominator restores a distribution that sums to one.↔ Scroll wide equations horizontally.

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.

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.

  1. 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.

  2. Divide retained probabilities by 0.90. The sampling probabilities become approximately 0.5556, 0.2778, and 0.1667, with the fourth token assigned zero.

  3. 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.

The result

A threshold controls cumulative retained mass, while k controls retained count. After truncation, sampling must use the normalized retained distribution.

Explore the model

Interactive lab

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.

Separate randomness from a deterministic choiceThese are exact binomial probabilities for independent trials with one fixed success probability. Playback tours the distribution; it does not resample outcomes. Current readings: Mean · np: 5; Variance · np(1−p): 2.5; Total probability: 1. All parameters are adjustable with the labeled controls below.03581000.070.150.220.3Successes kP(X = k)k = 0 · P = 9.77e-4
Exact probabilityHighlighted outcomeMean np
Mean · np
5
Variance · np(1−p)
2.5
Total probability
1
t = 0 s

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.

Check your understanding

A top-p threshold is 0.7 and sorted token probabilities are 0.6, 0.25, and 0.15. Which set is retained under the smallest-prefix definition?

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.

p1(T)p2(T)=exp⁡ ⁣(z1−z2T)\frac{p_1^{(T)}}{p_2^{(T)}}=\exp\!\left(\frac{z_1-z_2}{T}\right)
The shared softmax denominator cancels. These odds concern the model's next-token distribution, not the truth of a statement.↔ Scroll wide equations horizontally.

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.