Next-Token Prediction & Sampling
At every step an LLM produces a logit for each token in its vocabulary. How we turn those scores into one chosen token is called decoding or sampling, and it has a big effect on the output: the same model can be precise and repetitive or creative and erratic depending on a few settings. API parameters such as temperature, top_k and top_p control exactly the steps in this lesson.
From logits to probabilities
Softmax converts logits into probabilities: exponentiate each score and divide by the total. The highest logit gets the highest probability, but every token keeps some chance.
import numpy as np
tokens = np.array(["blue", "clear", "grey", "dark", "falling"])
logits = np.array([3.0, 2.2, 1.6, 0.8, -1.0])
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
probs = softmax(logits)
for t, p in zip(tokens, probs):
print(f"{t:<8} {p:.3f}")
print("greedy choice:", tokens[np.argmax(probs)])blue 0.548
clear 0.246
grey 0.135
dark 0.061
falling 0.010
greedy choice: blue
Temperature
Temperature divides the logits before softmax: softmax(logits / T).
| Temperature | Effect |
|---|---|
T < 1 |
sharper distribution — the top token dominates; more focused, more repetitive |
T = 1 |
the model's own distribution |
T > 1 |
flatter distribution — rare tokens get more chances; more varied, more errors |
T → 0 |
equivalent to greedy decoding (always the top token) |
import numpy as np
import matplotlib.pyplot as plt
tokens = ["blue", "clear", "grey", "dark", "falling"]
logits = np.array([3.0, 2.2, 1.6, 0.8, -1.0])
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
fig, ax = plt.subplots(figsize=(6, 3.5))
width = 0.25
for i, T in enumerate([0.5, 1.0, 2.0]):
p = softmax(logits / T)
ax.bar(np.arange(5) + (i - 1) * width, p, width, label=f"T = {T}")
print(f"T={T}: " + " ".join(f"{t}={x:.2f}" for t, x in zip(tokens, p)))
ax.set_xticks(range(5), tokens); ax.set_ylabel("probability")
ax.set_title("Same logits, different temperatures"); ax.legend()
plt.show()
print("plotted 3 temperature settings")T=0.5: blue=0.78 clear=0.16 grey=0.05 dark=0.01 falling=0.00
T=1.0: blue=0.55 clear=0.25 grey=0.14 dark=0.06 falling=0.01
T=2.0: blue=0.38 clear=0.25 grey=0.19 dark=0.13 falling=0.05
plotted 3 temperature settings
Sampling with a seeded generator
Sampling means drawing a token at random according to the probabilities. Real APIs use fresh randomness each call, which is why the same prompt can give different answers. Here we seed the generator so the run is reproducible:
import numpy as np
tokens = np.array(["blue", "clear", "grey", "dark", "falling"])
logits = np.array([3.0, 2.2, 1.6, 0.8, -1.0])
def sample(logits, temperature, rng, n=20):
z = logits / temperature
p = np.exp(z - z.max()); p /= p.sum()
return rng.choice(tokens, size=n, p=p)
rng = np.random.default_rng(42)
for T in [0.2, 1.0, 2.0]:
draws = sample(logits, T, rng)
values, counts = np.unique(draws, return_counts=True)
summary = ", ".join(f"{v}:{c}" for v, c in zip(values, counts))
print(f"T={T}: {summary}")T=0.2: blue:20
T=1.0: blue:12, clear:5, dark:2, grey:1
T=2.0: blue:7, clear:4, dark:2, grey:7
At T=0.2 all 20 draws are blue; at T=1.0 other tokens appear; at T=2.0 grey is drawn as often as blue. Run it with a different seed and the counts change, but the trend stays.
Top-k and top-p (nucleus) sampling
Even at a moderate temperature, the long tail of thousands of unlikely tokens adds up to a real chance of picking nonsense. Two filters cut the tail before sampling:
- Top-k: keep only the
kmost likely tokens. - Top-p (nucleus): keep the smallest set of top tokens whose probabilities add up to at least
p(e.g. 0.9). The set grows when the model is unsure and shrinks when it is confident.
After filtering, the remaining probabilities are renormalised to sum to 1.
import numpy as np
tokens = np.array(["blue", "clear", "grey", "dark", "falling"])
probs = np.array([0.50, 0.22, 0.15, 0.09, 0.04])
def top_k(probs, k):
keep = np.argsort(-probs)[:k]
out = np.zeros_like(probs); out[keep] = probs[keep]
return out / out.sum()
def top_p(probs, p):
order = np.argsort(-probs)
cumulative = np.cumsum(probs[order])
cutoff = np.searchsorted(cumulative, p) + 1 # smallest prefix reaching p
keep = order[:cutoff]
out = np.zeros_like(probs); out[keep] = probs[keep]
return out / out.sum()
np.set_printoptions(precision=3, suppress=True)
print("original: ", probs)
print("top-k (k=2):", top_k(probs, 2))
print("top-p (0.8):", top_p(probs, 0.8))
print("kept by top-p:", tokens[top_p(probs, 0.8) > 0].tolist())original: [0.5 0.22 0.15 0.09 0.04]
top-k (k=2): [0.694 0.306 0. 0. 0. ]
top-p (0.8): [0.575 0.253 0.172 0. 0. ]
kept by top-p: ['blue', 'clear', 'grey']
Putting it together: a tiny generator
The program below combines a bigram model, temperature and top-k, with a seeded generator. Try changing TEMPERATURE and TOP_K:
import numpy as np
text = ("the cat sat on the mat . the dog sat on the rug . the cat saw the dog . "
"the dog saw a bird . a bird sat on the cat .").split()
vocab = sorted(set(text))
idx = {w: i for i, w in enumerate(vocab)}
counts = np.ones((len(vocab), len(vocab))) * 0.01 # tiny smoothing
for a, b in zip(text, text[1:]):
counts[idx[a], idx[b]] += 1
logits = np.log(counts) # log-counts act as logits
TEMPERATURE, TOP_K = 0.8, 3
rng = np.random.default_rng(5)
word, out = "the", ["the"]
for _ in range(12):
z = logits[idx[word]] / TEMPERATURE
keep = np.argsort(-z)[:TOP_K]
p = np.exp(z[keep] - z[keep].max()); p /= p.sum()
word = vocab[rng.choice(keep, p=p)]
out.append(word)
print(" ".join(out))the dog saw the cat . the cat . the mat . the
Choosing settings
| Task | Typical setting |
|---|---|
| Extraction, classification, code, facts | low temperature (0–0.3) |
| General chat, explanations | default settings |
| Brainstorming, fiction, varied phrasings | higher temperature (around 1) |
Note: A temperature of 0 makes output more repeatable but not guaranteed identical: some providers still show small variations due to how computations are batched on hardware. Also, some newer models restrict which sampling parameters can be changed; check the documentation of the model you use. Usually you adjust temperature or top-p, not both.
Go further: Inside a Decoder-Only LM shows where the logits come from in a real model and how the KV cache speeds up generation.
Test yourself
What happens when you raise the temperature above 1?
- The distribution gets sharper
- The distribution gets flatter, so less likely tokens are chosen more often
- The model becomes larger
- Only the top token can be chosen
With top-p = 0.9, which tokens are kept?
- Exactly 9 tokens
- The smallest set of most likely tokens whose probabilities sum to at least 0.9
- Tokens with probability above 0.9
- All tokens except the top one
Why can the same prompt give different answers on repeated API calls?
- The model is retrained between calls
- Tokens are sampled randomly from the predicted distribution
- The tokenizer changes
- Network errors