Intermediate about 3 h
The picture
01
Logits
raw scores
02
Temperature
sharpen or flatten
03
Top-k / top-p
truncate the tail
04
Sample
draw a token
05
Append
repeat
From scores to a token
At each step the model outputs logits over the vocabulary. Decoding is the rule that turns those into one token. The rule changes behaviour dramatically, even with identical weights.
import torch
def sample(logits, temperature=1.0, top_k=None, top_p=None):
logits = logits / max(temperature, 1e-6)
if top_k:
kth = torch.topk(logits, top_k).values[..., -1, None]
logits = logits.masked_fill(logits < kth, float("-inf"))
probs = torch.softmax(logits, dim=-1)
if top_p:
sp, si = torch.sort(probs, descending=True)
cum = sp.cumsum(-1)
drop = cum - sp > top_p # keep the smallest set with mass ≥ p
sp = sp.masked_fill(drop, 0.0)
probs = torch.zeros_like(probs).scatter(-1, si, sp)
probs = probs / probs.sum(-1, keepdim=True)
return torch.multinomial(probs, 1)
What each knob does
- Temperature rescales logits before softmax. is greedy; flattens the distribution and increases randomness.
- Top-k keeps the most likely tokens.
- Top-p (nucleus) keeps the smallest set whose probability adds up to . It adapts: few candidates when the model is confident, many when it is not.
- Beam search keeps several partial sequences. It suits translation and short outputs but tends to produce repetitive text in open-ended generation.
Choosing settings
- Extraction, classification, tool calls: temperature 0 (or very low). You want determinism.
- Code: low temperature, but sample several candidates and verify with tests.
- Brainstorming, creative writing: temperature around 0.8 to 1.0 with top-p near 0.9 to 0.95.
Note that even temperature 0 is not perfectly deterministic on hosted APIs (batching and floating-point effects), so never build correctness on bit-exact repeats.
Log-probabilities as a signal
Many APIs and all open-model libraries expose the log-probability of each generated token. A low value flags uncertainty: useful for routing a hard case to a stronger model or to a human.
import torch.nn.functional as F
logp = F.log_softmax(logits, dim=-1)
chosen = logp.gather(-1, next_token) # log-prob of what was sampled
confidence = chosen.exp()
Common mistakes
- Setting both a high temperature and a loose top-p and then blaming the model for nonsense.
- Using sampling for tasks that need the single best answer.
- Treating a probability as calibrated truth. Models are often over-confident.
Exercises
- Generate 20 completions of one prompt at temperatures 0.2, 0.7 and 1.2 and measure distinct n-grams.
- Use per-token log-probabilities to highlight the least certain words in an answer.
You are done when you can…
- Implement temperature, top-k and top-p sampling from logits
- Choose decoding settings for extraction, code and creative writing
- Use token log-probabilities to detect uncertainty