Level 3 In-Depth AI · Transformers and Language Models
Decoding: Temperature, Top-k and Top-p
A language model only gives probabilities for the next token. Decoding is how you turn those probabilities into text, and the choice (greedy, beam search, sampling with temperature, top-k or top-p) changes output from dull and repetitive to creative to nonsense.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 45 minutes to read, an hour to experiment
- Builds on
- 32 concepts →
- Quiz
- 5 questions ↓
Read first
GPT and Decoder-Only ModelsThis leads to
—The full path from zero — 32 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Decoding: Temperature, Top-k and Top-p
Read them roughly in this order. See it on the concept map →
Why it matters
A GPT-style model never outputs text directly. At each step it outputs a probability for every token in its vocabulary, 50,000 to 200,000 numbers. Something has to choose one token, append it and ask again. That something is the decoding strategy, and it lives outside the network: the same trained model can be made boringly predictable, pleasantly varied or completely incoherent just by changing it.
Most LLM tools expose these knobs. temperature, top_p and top_k appear in Hugging Face's generate, in Ollama and llama.cpp, and in many hosted APIs such as Google's (Using LLM APIs, Running Models Locally). As of late 2026, though, providers increasingly fix them for their reasoning models: OpenAI's reasoning models don't accept a custom temperature, and Anthropic's current API rejects all three, steering with an effort setting instead. Knowing what they do lets you pick sensible values: low temperature for extracting data or writing code, higher for brainstorming. Decoding also matters for speed. Speculative decoding, covered at the end, makes generation several times faster with exactly the same output distribution.
The intuition
You're writing a story with a friend who, at every word, hands you a list of suggestions with their confidence: "mat 47%, floor 29%, sofa 17%, roof 6%, moon 1%". How do you choose?
- Always take the top suggestion (greedy). Safe, but the story becomes bland and starts going round in circles.
- Plan a few words ahead (beam search). Keep several promising partial sentences going and pick the best complete one. Great when there is one right answer, as in translation; stiff and repetitive for stories.
- Roll a die weighted by the confidences (sampling). Varied and natural, but every so often the die lands on "moon" and the story derails.
- Roll the die, but first cross out the silly options (top-k, top-p). Most of the variety, far fewer derailments.
- Turn the confidence up or down (temperature). Make your friend more decisive or more open-minded before you roll.
Key idea Decoding turns next-token probabilities into text. Greedy and beam search pick the most likely continuations. Sampling picks randomly in proportion to probability. Temperature sharpens or flattens the distribution, and top-k or top-p cut off its unreliable tail.
How it works
The network's final layer produces one raw score per token, called a logit. Softmax turns logits into probabilities . Throughout this chapter we use one example: after "The cat sat on the", suppose the logits for five candidates are mat 3.0, floor 2.5, sofa 2.0, roof 1.0, moon −1.0 (a real vocabulary has thousands more, with tiny probabilities). Their softmax is 0.47, 0.29, 0.17, 0.06 and 0.01.
Greedy decoding
Greedy decoding takes the most likely token every time: , here "mat". It is deterministic: same prompt, same output. It's a good choice for short factual answers, classification-style outputs and code, where the most likely continuation is usually right.
Its weakness is long, open-ended text. Greedy decoding tends to fall into loops ("the capital of the French Republic, and the capital of the…", as GPT-2 does in the GPT and Decoder-Only Models chapter), because once a phrase becomes likely, repeating it makes it more likely still. It is also short-sighted: the best first word doesn't always lead to the best sentence.
Beam search
Beam search keeps the most probable partial sequences (the beam) instead of just one. At each step it extends each of them by every possible next token, scores each extension by the product of its probabilities (in practice the sum of log-probabilities), and keeps the best overall.
In the toy example, greedy takes "nice" (0.5) then "woman" (0.4), total . Beam search also keeps "dog" (0.4) alive, and "dog has" scores , which wins.
Beam search was the standard for machine translation and speech recognition, where you want the single most likely output. Because longer sequences multiply more probabilities and so score lower, implementations divide by a power of the length (length normalisation). For open-ended writing, beam search is a poor choice: the most probable text is often generic and repetitive, not what people actually write.
Sampling
Human text is not the most probable text. Holtzman and colleagues showed in 2019 that real writing regularly uses words a model ranks as fairly unlikely. To sound natural, we should sample: pick token at random with probability . With our numbers, "mat" comes out 47% of the time, "floor" 29%, and "moon" about 1 time in 100.
That 1% is the problem. Over a 500-token answer, unlikely tokens get chosen dozens of times, and the vocabulary's long tail contains plenty of genuinely bad choices. One bad token can derail everything after it, because the model must continue from it.
Temperature
Temperature divides the logits before the softmax:
- leaves the distribution unchanged.
- makes it sharper: differences between logits are magnified. At our probabilities become 0.66, 0.24, 0.09, 0.01, 0.00.
- makes it flatter. At : 0.35, 0.27, 0.21, 0.13, 0.05. "Moon" is now five times more likely than at .
- As , all probability goes to the top token: greedy decoding. APIs treat
temperature=0as greedy.
Worked example for : the logits become , , , , . Exponentiate: , , , , . Their sum is 614.0, so "mat" gets .
The name comes from physics, where the same formula, the Boltzmann distribution, describes how hot particles spread over energy states.
Top-k sampling
Top-k sampling keeps only the most likely tokens, sets the rest to zero, renormalises (divides by the remaining total so the probabilities sum to 1 again) and samples. With : mat and floor survive with of the mass, renormalised to and .
The weakness: is fixed. After "The capital of France is", the model may be 95% sure of "Paris", and still lets 39 poor options in. After "My favourite food is", hundreds of tokens are reasonable, and cuts off good ones.
Top-p (nucleus) sampling
Top-p sampling, or nucleus sampling (Holtzman et al., 2019), fixes this by cutting at a probability mass instead of a count. Sort tokens from most to least likely and keep the smallest set whose probabilities add up to at least (the "nucleus"), then renormalise and sample.
With : mat (0.47), plus floor (running total 0.76), plus sofa (0.93, which reaches 0.9). Roof and moon are dropped. The survivors become , and .
When the model is confident, the nucleus is one or two tokens; when it's unsure, it widens automatically. Temperature and top-p are often used together, temperature applied first. A common general-purpose setting is temperature 0.7 with top-p 0.9 to 0.95. A newer variant, min-p, keeps every token whose probability is at least a fraction (say 0.1) of the top token's.
Repetition penalties and other controls
- A repetition penalty lowers the logits of tokens that have already appeared. OpenAI's API, for example, offers a presence penalty (subtract a fixed amount once a token has appeared at all) and a frequency penalty (subtract an amount proportional to how often it has appeared). Hugging Face's
repetition_penaltydivides positive logits of seen tokens by a factor such as 1.2. Use gently: strong penalties make the model avoid words it legitimately needs, like "the". - Stop sequences and maximum length end generation.
- Logit bias adds a fixed amount to chosen tokens' logits, to ban or encourage them.
- Constrained decoding zeroes the probability of any token that would break a required format, such as valid JSON (Structured Output and JSON).
Speculative decoding: same output, faster
Generating with a big model is slow mostly because each token needs a full pass that reads all the weights from memory, and the GPU's arithmetic units sit mostly idle. Checking several tokens at once costs about the same as generating one.
Speculative decoding (Leviathan, Kalman and Matias, 2022; Chen and colleagues at DeepMind did similar work in 2023) exploits this. A small, fast draft model guesses the next few tokens, say 4. The big model then scores all 4 positions in a single pass. Each draft token is accepted with probability , where is the big model's probability and the draft model's. At the first rejection, a replacement is sampled from a corrected distribution and the rest of the draft is discarded. The maths guarantees the output has exactly the distribution the big model would have produced alone, while easy stretches of text (where the small model guesses right) go several tokens per big-model pass. Speed-ups of 2 to 3 times were reported in the original papers. Variants that draft with extra heads on the big model itself, or by looking up earlier text, are used in production serving systems (Serving LLMs at Scale).
In code
All of the sampling strategies in about 30 lines of NumPy, then 1,000 draws with each:
import numpy as np
tokens = ["mat", "floor", "sofa", "roof", "moon"]
logits = np.array([3.0, 2.5, 2.0, 1.0, -1.0]) # the model's raw scores
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def sample(logits, temperature=1.0, top_k=None, top_p=None, rng=np.random.default_rng(0)):
if temperature == 0:
return int(np.argmax(logits)) # greedy
probs = softmax(logits / temperature) # temperature reshapes the distribution
order = np.argsort(probs)[::-1] # most likely first
keep = np.ones_like(probs, dtype=bool)
if top_k is not None:
keep[order[top_k:]] = False # only the k best survive
if top_p is not None:
cum = np.cumsum(probs[order])
cutoff = np.searchsorted(cum, top_p) + 1 # smallest set with mass >= p
keep[order[cutoff:]] = False
probs = np.where(keep, probs, 0)
probs /= probs.sum() # renormalise what is left
return int(rng.choice(len(probs), p=probs))
for T in [0.5, 1.0, 2.0]:
print(f"T={T}:", softmax(logits / T).round(3))
rng = np.random.default_rng(0)
for kw in [dict(temperature=0), dict(temperature=1.0), dict(top_k=2), dict(top_p=0.9)]:
draws = [str(tokens[sample(logits, rng=rng, **kw)]) for _ in range(1000)]
print(kw, {t: draws.count(t) for t in tokens})
# T=0.5: [0.657 0.242 0.089 0.012 0. ]
# T=1.0: [0.47 0.285 0.173 0.064 0.009]
# T=2.0: [0.346 0.27 0.21 0.127 0.047]
# {'temperature': 0} {'mat': 1000, 'floor': 0, 'sofa': 0, 'roof': 0, 'moon': 0}
# {'temperature': 1.0} {'mat': 440, 'floor': 297, 'sofa': 192, 'roof': 61, 'moon': 10}
# {'top_k': 2} {'mat': 646, 'floor': 354, 'sofa': 0, 'roof': 0, 'moon': 0}
# {'top_p': 0.9} {'mat': 528, 'floor': 280, 'sofa': 192, 'roof': 0, 'moon': 0}
The counts match the theory: pure sampling picked "moon" 10 times in 1,000; top-k and top-p never did.
With a real model, Hugging Face's generate takes the same settings as arguments. Here is GPT-2 small continuing one prompt four ways (the first run downloads the model):
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
ids = tok("The old lighthouse keeper", return_tensors="pt").input_ids
settings = {
"greedy": dict(do_sample=False),
"beam search": dict(do_sample=False, num_beams=5),
"T=0.7, p=0.9": dict(do_sample=True, temperature=0.7, top_p=0.9),
"T=1.5": dict(do_sample=True, temperature=1.5, top_k=0),
}
for name, kw in settings.items():
torch.manual_seed(0)
out = model.generate(ids, max_new_tokens=25, pad_token_id=tok.eos_token_id, **kw)
print(f"{name}: {tok.decode(out[0][ids.shape[1]:])!r}")
# greedy: ', who had been a member of the family for many years, was killed in a fire in the village of Kudu'
# beam search: ', who had been on duty at the time of the attack, was shot in the head.\n\n"I don\'t'
# T=0.7, p=0.9: ', who was the first to use the "light" to the sky, had been killed by a lightning bolt in the sea'
# T=1.5: ' along Logan pilot died pretty spot... is "tree legs diffuse the spill that squat unfortunately CathP wrestler roamer regulatesPlus Chin'
Greedy and beam search give safe, newspaper-like continuations. Moderate temperature with top-p is more inventive while staying grammatical. Temperature 1.5 with no truncation (top_k=0 disables Hugging Face's default of 50) falls apart within a few words: that's the long tail at work.
Common pitfalls
- Expecting determinism at temperature 0. Greedy decoding is deterministic in principle, but batched GPU inference can produce tiny numerical differences that flip near-ties. Don't build systems that rely on byte-identical outputs from an API.
- Stacking knobs blindly. Temperature, top-k, top-p and penalties interact. Change one at a time. Many providers advise adjusting temperature or top-p, not both.
- High temperature for "creativity". Above about 1.2 most models degrade quickly unless top-p or min-p trims the tail.
- Beam search for chat or stories. It maximises probability, which favours bland, repetitive text.
- Heavy repetition penalties. They punish necessary words and can push the model into strange synonyms.
Watch out Sampling settings change what the model says, not how much it knows. Turning temperature down makes answers more consistent, not more correct: a model that is confidently wrong will be confidently wrong every time. Use evaluation (Evaluating LLM Applications) and grounding (Retrieval-Augmented Generation) for accuracy.
Where it leads
- The KV Cache and Fast Inference and Serving LLMs at Scale cover the rest of fast generation: caching, batching and serving many users.
- Structured Output and JSON uses constrained decoding to guarantee valid JSON or other formats.
- Reasoning Models and Test-Time Compute sample long chains of thought; sampling many answers and taking a majority vote ("self-consistency") is a decoding strategy in its own right.
- Hallucinations discusses calibration: whether a model's probabilities actually match how often it is right.
- Build a GPT from Scratch lets you try temperature on a model you trained yourself.
A bit of history
Beam search dates back to speech recognition research in the 1970s and was the default for neural machine translation through the 2010s. As language models began writing long text, researchers noticed that beam search and greedy output was dull and repetitive. Fan, Lewis and Dauphin (2018) used top-k sampling for story generation, and OpenAI's GPT-2 samples (2019) used it too. In 2019 Ari Holtzman and colleagues analysed "neural text degeneration" and introduced nucleus (top-p) sampling, which became the standard. Repetition penalties appeared in Salesforce's CTRL model (2019). Speculative decoding was published in late 2022 and early 2023 by teams at Google and DeepMind and was quickly adopted in production inference engines.
Try it
- By hand, compute the probabilities at from the logits 3.0, 2.5, 2.0, 1.0, −1.0 and check them against the code output.
- In the NumPy code, combine
temperature=1.5withtop_p=0.9. Which tokens survive? Compare withtemperature=1.5alone.- In the GPT-2 example, add
repetition_penalty=1.3to the greedy setting. Does the continuation change? Is it better?Hint for 1: the logits become 1.5, 1.25, 1.0, 0.5, −0.5; exponentiate each and divide by the sum (about 12.95).
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
How to generate text: using different decoding methods for language generation with Transformers
Greedy, beam search, top-k and top-p sampling compared side by side with runnable code.
The Curious Case of Neural Text Degeneration
Explains why greedy and beam search produce dull, repetitive text and introduces nucleus (top-p) sampling.
Fast Inference from Transformers via Speculative Decoding
A small draft model proposes several tokens and the big model checks them in one pass, with exactly the same output distribution.
Deep Dive into LLMs like ChatGPT
A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/decoding-strategies.md