Sampling and Decoding Controls
About 38 min
Goal
By the end of this lesson, you can trace autoregressive generation and explain how seeds, greedy decoding, temperature, top-k, and top-p change token selection without retraining the model.
A trained language model does not write a whole answer in one jump. It produces scores for the next token, a decoding rule selects one token, and that token is appended to the context.
Then the model runs again.
prompt
↓ model
next-token logits
↓ decoding rule
one selected token
↓ append
longer prompt
↺
That repeated loop is autoregressive generation.
First separate prediction from selection
Suppose the current context is:
"the moon"
The model might produce a next-token distribution like:
"is" 0.60
"looks" 0.25
"was" 0.10
"," 0.05
The model produced those preferences. A decoding policy decides how to select from them.
That distinction matters because decoding changes can make the output look different even when the checkpoint, tokenizer, prompt, and learned weights stay exactly the same.
Predict
Greedy decoding and sampling answer different questions
Greedy decoding chooses the highest-scoring token at every step.
A=.60 B=.30 C=.10
greedy → A
For fixed logits, greedy selection is deterministic.
Sampling draws from a probability distribution.
A=.60 B=.30 C=.10
sample → usually A, sometimes B, occasionally C
Sampling does not make the model more knowledgeable. It changes which continuation is selected from the distribution the model already produced.
A seed makes a randomized experiment repeatable
A pseudo-random generator uses a seed as a reproducible starting state.
If the distribution, runtime behavior, and seed stay fixed, the same program can repeat the same sequence of draws. Changing only the seed gives a controlled way to observe another possible sample.
A seed does not change the learned probabilities. It only controls the random draw sequence used by the experiment.
This is useful when comparing decoding settings. Keep the checkpoint, prompt, seed policy, and generation length fixed, then change one decoding control at a time.
Temperature changes how sharp the distribution is
The model first produces logits, which are raw scores. Temperature rescales those logits before softmax:
softmax(logits / temperature)
Consider two logits:
[2, 1]
The probabilities make the effect visible:
temperature 1.0 → [0.73, 0.27]
temperature 0.5 → [0.88, 0.12]
temperature 2.0 → [0.62, 0.38]
A temperature below 1 makes the gap effectively larger, so the distribution becomes sharper. A temperature above 1 makes the gap effectively smaller, so the distribution becomes flatter.
Temperature must be positive in the usual formula. If you want purely greedy decoding, use an explicit greedy rule instead of pretending temperature zero is an ordinary sampling temperature.
Temperature does not reorder the logits when the same positive value is applied to all of them. It changes their relative concentration after softmax.
Top-k keeps a fixed number of candidates
Suppose the current probabilities are:
A=.55 B=.25 C=.12 D=.06 E=.02
With top-k=2, keep only A and B, then renormalize:
A = .55 / .80 = .6875
B = .25 / .80 = .3125
Top-k asks:
How many of the highest-scoring candidates may remain?
top-k=1 leaves one candidate, so that step behaves greedily.
Top-p keeps enough probability mass
Top-p, often called nucleus sampling, asks a different question:
What is the smallest high-probability candidate set whose cumulative mass reaches at least p?
Using the same distribution:
A=.55 cumulative=.55
B=.25 cumulative=.80
C=.12 cumulative=.92
For top-p=.80, keep A and B.
For top-p=.85, A+B reaches only .80, so C must also be kept. The threshold-crossing token matters.
Top-k therefore fixes the candidate count. Top-p lets the candidate count adapt to the shape of the current distribution.
Run one merged decoding experiment
The Lab keeps the concepts visible in one place:
- a fixed weighted distribution plus a fixed seed demonstrates reproducible sampling;
- one fixed logit vector demonstrates greedy selection and temperature;
- top-k keeps the highest
kcandidates; - you complete top-p so it keeps the smallest prefix that reaches the requested probability mass.
Loading lab…
Use this sequence:
- Click Run before editing. The seeded sample should repeat exactly on another unchanged run.
- Read the greedy token and compare it with the stochastic draws.
- Compare the baseline softmax with low and high temperature. Identify which is sharper.
- Inspect
top-k=2and confirm only two candidates remain non-zero. - Complete the
top_pTODO: sort by probability, keep candidates until cumulative mass reachesp, and renormalize. - Run again until the Lab checks pass.
- Change only
seed = 7to another integer such as8and observe a different draw sequence while the probabilities remain fixed. - Reset. Then change one decoding control at a time—for example
low_temperature_value = 0.8,top_k_value = 3, ortop_p_value = 0.9. After each run, explain what changed and keep the other settings fixed.
The trained model is not updated anywhere in this Lab.
Do not confuse a decoding improvement with a training improvement
Suppose temperature 0.7 gives a sample you prefer to temperature 1.0.
That is evidence about this decoding comparison under these conditions. It does not show that:
- validation loss improved;
- the checkpoint learned new facts;
- the model weights changed;
- the same setting will be best for every prompt.
A fair decoding comparison keeps non-target conditions fixed and evaluates more than one lucky output.
Common mistakes
- Changing several controls together. You cannot tell which change caused the observed difference.
- Applying temperature to already normalized probabilities. The standard operation rescales logits before softmax.
- Forgetting renormalization. After top-k or top-p removes candidates, the remaining probabilities must sum to 1 before sampling.
- Treating a seed as a guarantee across every implementation. A seed helps reproduce one defined experiment; different libraries or kernels may use different random algorithms.
- Calling decoding “training.” No gradient update occurs when you choose a token from fixed model outputs.
Quick Check
Explain it back
In your own words, trace:
prefix → model logits → decoding controls → selected token → longer prefix
Then explain where greedy decoding, a sampling seed, temperature, top-k, and top-p act—and state what stays unchanged about the trained checkpoint.
Check your explanation
A strong answer mentions:
- Generation repeats prefix → next-token logits → decoding controls → token choice → longer prefix.
- Greedy takes the top choice; sampling uses a random draw whose seed makes that run reproducible.
- Temperature changes sharpness, top-k limits candidate count, and top-p limits cumulative probability mass; none changes the trained checkpoint weights.
Key Takeaways
- Autoregressive generation repeats next-token prediction, selection, append, and prediction again.
- Greedy decoding chooses the highest-scoring token; sampling draws from a distribution.
- A seed makes a defined stochastic experiment repeatable without changing learned probabilities.
- Temperature changes distribution sharpness; top-k fixes candidate count; top-p adapts candidate count to probability mass.
- Decoding changes output selection, not model training.
Next Lesson
Next, L6.10 — Diffusion Models: Learning to Denoise steps away from next-token generation for one Lesson and studies a second major modern generative pattern: start from noise and repeatedly remove it.
References
- Python,
random.choices. - PyTorch,
torch.multinomial. - Holtzman et al., The Curious Case of Neural Text Degeneration.
- PyTorch,
torch.topk.
Completion is stored locally on this device.