Lesson 5 of 11 · Generation
Sampling: Temperature and Top-p
How an LLM picks each token: logits and softmax, greedy decoding, temperature, top-k, top-p, min-p, seeds and penalties, with an interactive picture and Python.
- 6 min read
- Intermediate
- Reviewed
- How logits become probabilities with softmax
- What temperature does to the probabilities, mathematically
- How top-k, top-p and min-p cut off unlikely tokens
- Which settings to use for which job, and what seeds and penalties do
From scores to a choice
At each step, the model's output layer produces a raw score, called a logit, for every token in its vocabulary. Turning those scores into one chosen token is called sampling or decoding, and you can control it.
Temperature
Temperature divides every logit by T before softmax. Dividing by a small number spreads the scores apart (sharper probabilities); dividing by a large number squeezes them together (flatter probabilities).
import math
# Raw scores (logits) from the model's last layer for a few candidate tokens
logits = {"mat": 3.0, "floor": 2.2, "sofa": 1.9, "bed": 1.5, "roof": 0.4, "moon": -0.6}
def softmax(scores, temperature=1.0):
exps = {}
for token in scores:
exps[token] = math.exp(scores[token] / temperature)
total = sum(exps.values())
probabilities = {}
for token in exps:
probabilities[token] = exps[token] / total
return probabilities
for temperature in [0.5, 1.0, 1.5]:
probabilities = softmax(logits, temperature)
parts = []
for token in probabilities:
parts.append(f"{token} {probabilities[token]:.0%}")
print(f"T={temperature}: " + ", ".join(parts))At T=0.5 the top token takes almost three quarters of the probability. At T=1.5 even "moon" gets 3%. T=0 is treated as a special case: always take the highest-scoring token, called greedy decoding.
Cutting off the tail
Even with sensible temperature, there are thousands of very unlikely tokens, and together they add up. Sampled often enough, one of them will eventually be picked and derail the text. Three common filters prevent this:
| Filter | Rule | Example |
|---|---|---|
| Top-k | Keep only the k most likely tokens | k = 40 |
| Top-p (nucleus) | Keep the most likely tokens until their total probability reaches p | p = 0.9 |
| Min-p | Keep tokens whose probability is at least a fraction of the top token's | 0.05 × top probability |
Top-p adapts to the situation: when the model is confident, a couple of tokens reach 0.9 and only they are kept; when it is unsure, many tokens are kept.
import math
import random
probabilities = {"mat": 0.42, "floor": 0.19, "sofa": 0.14, "bed": 0.09,
"roof": 0.03, "moon": 0.01, "chair": 0.12}
def top_p(probabilities, p):
# Keep the most likely tokens until their total reaches p, then rescale
kept = {}
running = 0.0
for token in sorted(probabilities, key=probabilities.get, reverse=True):
if running >= p:
break
kept[token] = probabilities[token]
running += probabilities[token]
total = sum(kept.values())
for token in kept:
kept[token] = kept[token] / total
return kept
filtered = top_p(probabilities, 0.8)
print("Kept by top-p 0.8:", ", ".join(filtered))
random.seed(7)
tokens = list(filtered)
weights = list(filtered.values())
picks = random.choices(tokens, weights=weights, k=10)
print("10 samples:", " ".join(picks))After the filter, sampling happens only among the sensible options. Setting a seed (here random.seed(7)) makes the random choices repeatable, which is useful for testing. Some APIs offer a seed setting, though results may still vary slightly between runs because of how computations are spread across hardware.
Try the settings yourself. Each click picks the next word 20 times.
She opened the door and saw a ___
Bars: chance of being picked now. Dashed line: the model's original probability.
Penalties against repetition
Some APIs also offer:
- Frequency penalty: lowers a token's score the more often it has already appeared, discouraging repeated words.
- Presence penalty: lowers the score of any token that has appeared at all, nudging the model toward new topics.
Use them gently: strong penalties can make text strange, because sometimes repetition is correct ("the", names, code).
Which settings for which job
| Job | Suggested settings |
|---|---|
| Extracting data, classification, code | Temperature 0 to 0.2 |
| Factual Q&A, summaries | Temperature around 0.3 to 0.7, top-p 0.9 |
| Conversation, general writing | Temperature around 0.7 to 1, top-p 0.9 to 0.95 |
| Brainstorming, fiction, varied ideas | Temperature 1 to 1.2, top-p 0.95 |
Change one of temperature or top-p at a time; adjusting both makes the effect hard to judge. Some newer models, especially reasoning models, fix these settings themselves and ignore or reject changes.
Common mistakes
Implement top-k sampling's filtering step.
probabilities = {"yes": 0.6, "no": 0.25, "maybe": 0.1, "never": 0.05}
k = 2
# Top-k: keep only the k most likely tokens, rescale them so they add up to 1,
# and print each one with 2 decimals, most likely first, like:
# yes 0.71
# no 0.29
What does top-p = 0.9 do?
Summary
- The model produces logits; softmax turns them into probabilities.
- Temperature divides the logits: low sharpens, high flattens, 0 means greedy.
- Top-k, top-p and min-p cut off the unlikely tail before sampling.
- Seeds make sampling repeatable; penalties discourage repetition.
- Low temperature for accuracy and extraction, higher for variety; change one setting at a time.
Next: working with context windows in real applications.
Finished reading? Tick it off to track your progress.