◆ AI All-in-One

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
↗ Plan a path here

Read first

GPT and Decoder-Only Models

This leads to

—
The full path from zero — 32 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. Logistic Regression
  19. Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. LSTMs and GRUs
  26. Residual Connections
  27. Sequence-to-Sequence Models
  28. Attention
  29. Self-Attention and Multi-Head Attention
  30. Positional Encodings
  31. The Transformer
  32. GPT and Decoder-Only Models
  33. 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.
Temperature reshapes the same scores: “The cat sat on the …” logits: mat 3.0, floor 2.5, sofa 2.0, roof 1.0, moon −1.0; probabilities = softmax(logits / T) T = 0.5: sharper, safer 0.66 mat 0.24 floor 0.09 sofa 0.01 roof 0.00 moon T = 1: unchanged 0.47 mat 0.29 floor 0.17 sofa 0.06 roof 0.01 moon T = 2: flatter, more random 0.35 mat 0.27 floor 0.21 sofa 0.13 roof 0.05 moon T → 0 approaches greedy decoding (always “mat”). Large T approaches a uniform choice, so rare and odd tokens like “moon” get picked more often. The order of the tokens never changes.
Fig. 1 The same five scores turned into probabilities at three temperatures. Low temperature concentrates probability on the top token; high temperature spreads it out. The ranking never changes.

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 ziz_i into probabilities pi=ezi/∑jezjp_i = e^{z_i} / \sum_j e^{z_j}. 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: arg⁡max⁡ipi\arg\max_i p_i, 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 keeps the BB 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 BB overall.

Greedy versus beam search (beam width 2) on a toy example The 0.5 nice 0.4 dog 0.1 car 0.4 woman 0.3 house 0.9 has 0.05 runs 0.3 is 0.5 × 0.4 = 0.20 0.5 × 0.3 = 0.15 0.4 × 0.9 = 0.36 0.4 × 0.05 = 0.02 0.1 × 0.3 = 0.03 greedy: always take the single best next token → “The nice woman”, probability 0.20 beam search keeps the 2 best partial sequences at each step → finds “The dog has”, probability 0.36
Fig. 2 A toy example where greedy decoding misses the best sequence. Greedy commits to "nice" (0.5) and ends with probability 0.20. Beam search with width 2 also keeps "dog" (0.4), whose continuation "has" (0.9) gives 0.36.

In the toy example, greedy takes "nice" (0.5) then "woman" (0.4), total 0.5×0.4=0.200.5 \times 0.4 = 0.20. Beam search also keeps "dog" (0.4) alive, and "dog has" scores 0.4×0.9=0.360.4 \times 0.9 = 0.36, 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 ii at random with probability pip_i. 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 TT divides the logits before the softmax:

pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}
  • T=1T = 1 leaves the distribution unchanged.
  • T<1T < 1 makes it sharper: differences between logits are magnified. At T=0.5T = 0.5 our probabilities become 0.66, 0.24, 0.09, 0.01, 0.00.
  • T>1T > 1 makes it flatter. At T=2T = 2: 0.35, 0.27, 0.21, 0.13, 0.05. "Moon" is now five times more likely than at T=1T = 1.
  • As T→0T \to 0, all probability goes to the top token: greedy decoding. APIs treat temperature=0 as greedy.

Worked example for T=0.5T = 0.5: the logits become 3.0/0.5=63.0/0.5 = 6, 55, 44, 22, −2-2. Exponentiate: e6=403.4e^6 = 403.4, e5=148.4e^5 = 148.4, e4=54.6e^4 = 54.6, e2=7.4e^2 = 7.4, e−2=0.14e^{-2} = 0.14. Their sum is 614.0, so "mat" gets 403.4/614.0=0.657403.4 / 614.0 = 0.657.

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 kk most likely tokens, sets the rest to zero, renormalises (divides by the remaining total so the probabilities sum to 1 again) and samples. With k=2k = 2: mat and floor survive with 0.47+0.29=0.760.47 + 0.29 = 0.76 of the mass, renormalised to 0.47/0.76=0.620.47/0.76 = 0.62 and 0.380.38.

The weakness: kk is fixed. After "The capital of France is", the model may be 95% sure of "Paris", and k=40k = 40 still lets 39 poor options in. After "My favourite food is", hundreds of tokens are reasonable, and k=40k = 40 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 pp (the "nucleus"), then renormalise and sample.

With p=0.9p = 0.9: 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 0.47/0.93=0.510.47/0.93 = 0.51, 0.310.31 and 0.190.19.

Truncation: throw away the unlikely tail, then renormalise and sample top-k with k = 2 keep the 2 most likely tokens 0.47→0.62 mat 0.29→0.38 floor 0.17 sofa 0.06 roof 0.01 moon top-p (nucleus) with p = 0.9 keep the smallest set whose total ≥ 0.9 0.47→0.51 mat 0.29→0.31 floor 0.17→0.19 sofa 0.06 roof 0.01 moon 0.47 + 0.29 + 0.17 = 0.93 ≥ 0.9 Solid: original probability (T = 1). Dashed: probability after renormalising the survivors. Grey: removed. Top-p adapts: when the model is confident the nucleus is small; when it is unsure, more tokens survive.
Fig. 3 Top-k keeps a fixed number of tokens; top-p keeps however many it takes to cover a fixed share of the probability. The survivors are renormalised so they sum to 1.

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_penalty divides 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 min⁡(1,p(x)/q(x))\min(1, p(x)/q(x)), where pp is the big model's probability and qq 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

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

  1. By hand, compute the probabilities at T=2T = 2 from the logits 3.0, 2.5, 2.0, 1.0, −1.0 and check them against the code output.
  2. In the NumPy code, combine temperature=1.5 with top_p=0.9. Which tokens survive? Compare with temperature=1.5 alone.
  3. In the GPT-2 example, add repetition_penalty=1.3 to 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).

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your manager wants the model to extract invoice fields into the same format every time. Which setting fits best?

  2. Logits are mat 3.0, floor 2.5, sofa 2.0, roof 1.0, moon −1.0 (probabilities 0.47, 0.29, 0.17, 0.06, 0.01). With top-p = 0.9, which tokens survive?

  3. Why can top-p sampling be better than a fixed top-k?

  4. A colleague sets temperature to 0 and says the answers are now correct. What is wrong with that claim?

  5. What does speculative decoding change about the output?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

The Curious Case of Neural Text Degeneration

Holtzman, Buys, Du, Forbes & Choi · 2019 · Advanced · Free

Explains why greedy and beam search produce dull, repetitive text and introduces nucleus (top-p) sampling.

Video

Deep Dive into LLMs like ChatGPT

Andrej Karpathy · 2025 · Beginner · Free

A 3.5-hour walk through the full stack of how chat models are built: pretraining, tokenization, post-training, RL and reasoning.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

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