
An LLM does not choose the next word directly. It gives every possible token a score, turns the scores into probabilities, then samples. Temperature and top-p control that last step.
A worked example
Suppose three candidate tokens have scores (logits) 2.0, 1.0 and 0.1. Divide by the temperature, then apply softmax:
| Temperature | Token A | Token B | Token C |
|---|---|---|---|
| 0.5 (focused) | 86% | 12% | 2% |
| 1.0 (default) | 66% | 24% | 10% |
| 2.0 (wild) | 50% | 31% | 19% |
Low temperature sharpens the distribution toward the top choice; high temperature flattens it so unlikely tokens appear more often. Temperature 0 means “always take the top token” (nearly deterministic).
“`python
import numpy as np
def softmax_t(logits, t):
z = np.array(logits) / t
e = np.exp(z – z.max())
return (e / e.sum()).round(2)
print(softmax_t([2.0, 1.0, 0.1], 0.5), softmax_t([2.0, 1.0, 0.1], 2.0))
“`
Top-p (nucleus sampling)
Top-p keeps only the smallest set of tokens whose probabilities add up to p, then samples among them. With top_p = 0.9 in the default row above, A + B = 90%, so C is never chosen. It cuts off the long tail of weird tokens while still allowing variety.
Which settings to use
| Task | Temperature |
|---|---|
| Formulas, SQL, code, data extraction | 0β0.3 |
| Emails, summaries, explanations | 0.5β0.8 |
| Brainstorming names, stories, slogans | 0.9β1.2 |
We implement sampling ourselves in Lesson 8 of the free Build Your Own LLM course.