Katkat

Decoding: Greedy, Temperature, Top-k and Top-p

By the Katkat team · Updated · 9 min read

Quick overview

Learn how LLMs pick the next token: logits, softmax, greedy, temperature, top-k, top-p, repetition penalties, and why temperature 0 is not not deterministic.

Lesson 5 of 88 · AI Engineering Interview Course

After this lesson you will be able to explain how a language model turns a vector of scores into one chosen token, and what each sampling knob does to that choice. You will be able to compute a temperature-scaled distribution and a top-p cutoff by hand. You will also be able to say why "temperature 0" does not guarantee identical outputs, and when repetition penalties help or hurt.

From logits to a token

A decoder-only model (see The Transformer, Explained for Engineers) generates text one token at a time. At each step, the final layer produces one logit per vocabulary entry for the last position. With a vocabulary of roughly 100,000 tokens, that is a vector of about 100,000 raw scores.

The pipeline for one step is:

  1. Take the logits for the last position.
  2. Optionally adjust them (repetition penalties, banned tokens, grammar masks).
  3. Divide by the temperature.
  4. Convert to probabilities with softmax.
  5. Optionally filter the candidate set (top-k, top-p).
  6. Pick a token: the argmax, or a random draw from what remains.
  7. Append the token and repeat.

Libraries differ in the exact order of these steps, so treat the order as something to check in the one you use. The key point is that the model only produces a distribution. Decoding is the separate policy that turns the distribution into text. Changing it needs no retraining, which is why it is the cheapest quality and style lever you have. The softmax itself is covered in Implement Numerically Stable Softmax and Cross-Entropy.

Greedy decoding and its relatives

Greedy decoding always takes the highest-probability token. It is fast, needs no randomness, and is the natural choice for extraction, classification and short factual answers.

Its weaknesses show up in long open-ended text. Greedy tends to get stuck in loops ("I think that I think that I think...") because once a repetitive pattern is likely, it reinforces itself. It also commits to a locally best token even when a slightly worse first token would lead to a better sentence.

Beam search keeps the best several partial sequences at each step instead of one. It helps in tasks with a fairly constrained correct output, such as translation, but for open-ended chat it tends to produce bland, repetitive text. Most chat APIs expose sampling rather than beams. See Implement Beam Search for the mechanics.

Sampling draws the next token at random in proportion to its probability. Everything else in this lesson is about shaping the distribution you sample from.

Temperature

Temperature T divides the logits before softmax: p_i = exp(z_i / T) / sum_j exp(z_j / T).

  • T = 1 leaves the model's distribution unchanged.
  • T < 1 sharpens it: the top token gains probability and the tail shrinks.
  • T > 1 flattens it: unlikely tokens become more likely.
  • T → 0 approaches greedy. Implementations special-case T = 0 as argmax, since dividing by zero is undefined.

Temperature never changes the ranking of tokens, only the gaps between them. That is why greedy output is unaffected by it.

Worked example

Take five candidate tokens with logits [4, 3, 2, 1, 0] for A to E.

At T = 1, the exponentials are about 54.60, 20.09, 7.39, 2.72 and 1.00. They sum to about 85.79, so the probabilities are:

TokenT = 0.5T = 1T = 2
A0.8650.6360.429
B0.1170.2340.260
C0.0160.0860.158
D0.0020.0320.096
E0.00030.0120.058

For T = 0.5, the scaled logits are [8, 6, 4, 2, 0], whose exponentials are about 2981, 403.4, 54.6, 7.39 and 1. They sum to about 3447, so A gets 2981/3447 ≈ 0.865. For T = 2, the scaled logits are [2, 1.5, 1, 0.5, 0], with exponentials 7.39, 4.48, 2.72, 1.65 and 1.00, summing to about 17.24. So A gets 7.39/17.24 ≈ 0.429.

The same ranking appears in every column, but at T = 2 the bottom two tokens together carry about 15% of the mass, versus 1.5% at T = 1. Over a 200-token answer, those small tail probabilities add up to a high chance of at least one odd token.

Top-k and top-p

Temperature reshapes the whole distribution but keeps every token possible. Truncation methods cut the unlikely tail off entirely.

Top-k keeps the k most probable tokens, renormalises and samples. With the example above and k = 3, we keep A, B and C. Their raw masses sum to 0.9566, so the renormalised probabilities are about 0.665, 0.245 and 0.090.

Top-p (nucleus sampling) keeps the smallest set of top tokens whose cumulative probability reaches p. At T = 1 the cumulative sums are A 0.636, A+B 0.871, A+B+C 0.957.

  • With p = 0.8, we need A and B (0.871 ≥ 0.8). Renormalised: A = 54.60/74.68 ≈ 0.731, B ≈ 0.269.
  • With p = 0.9, we need A, B and C.

The practical difference is that top-p adapts to the model's confidence. When the model is sure (one token at 0.95), top-p keeps one or two tokens. When it is unsure (a flat distribution), it keeps many. A fixed k = 50 keeps 50 candidates even when 49 of them are junk, and cuts valid options when many continuations are reasonable. Top-p was proposed in the paper "The Curious Case of Neural Text Degeneration", which also argues that pure sampling and pure maximisation both produce degenerate text. For code, see Implement Top-k and Top-p Sampling.

Interactions matter. Temperature applied before top-p changes which tokens fall inside the nucleus: raising T flattens the distribution, so more tokens are needed to reach p. Most guidance is to tune one of temperature or top-p, not both at once, so you can tell which change caused a behaviour shift.

Repetition, frequency and presence penalties

Penalties modify logits based on what has already been generated, before softmax. The names and exact formulas vary by API and library, so check the one you use. Common forms are:

  • Presence penalty: subtract a constant from the logit of any token that has appeared at least once. This nudges the model toward new topics.
  • Frequency penalty: subtract count × coefficient. A token that has appeared 3 times with a coefficient of 0.5 loses 1.5 from its logit.
  • Multiplicative repetition penalty (seen in some open-source libraries): divide positive logits of seen tokens by a factor r > 1 and multiply negative ones by r, so the token always becomes less likely.
  • N-gram blocking: forbid any token that would complete an n-gram already seen.

Using the example, suppose A appeared twice and the frequency penalty is 0.5. Its logit drops from 4 to 3, tying with B at 3. The distribution becomes [3, 3, 2, 1, 0], with A and B each around 0.42 at T = 1.

The trade-off is that penalties cannot tell harmful repetition from necessary repetition. JSON keys, variable names, quoted source text and the digits of a number all legitimately repeat. Strong penalties can corrupt structured output; see Getting Reliable JSON and Structured Output. Use small values, and prefer fixing the cause (prompt, temperature, a loop in the application) before cranking a penalty.

Determinism

Greedy decoding is deterministic in theory: the same logits give the same argmax. In practice, a hosted model at temperature 0 can still return different outputs for the same prompt. Typical causes:

  • Floating-point non-associativity: summing numbers in a different order gives slightly different results, and GPU kernels may choose different reduction orders.
  • Batching: your request is batched with others, and batch size can change which kernels run and how values are accumulated.
  • Near-ties: when two top logits differ by a tiny amount, a tiny numerical difference flips the argmax, and the text diverges from there.
  • Hardware or software changes: a different GPU type, driver or model version changes the numerics.
  • Mixture-of-experts routing can add its own sensitivity, depending on the model.

With sampling, a fixed random seed makes the draw reproducible only if the logits are identical, so it inherits the same problem. Some APIs offer a seed parameter, but treat it as best effort unless the documentation promises more. For tests, avoid asserting exact strings. Use structured output, tolerant checks, or evaluations over many samples (see LLM Evaluation and LLM-as-a-Judge).

Choosing settings

These are starting points, not rules. Always validate on your own evaluation set.

TaskTypical starting pointReason
Classification, extraction, routingGreedy or T near 0One right answer; variance is a cost
Code generationLow T (about 0.0 to 0.3)Syntax errors from tail tokens are costly
Question answering over retrieved textLow TFaithfulness over variety
Chat, summarisationModerate T (about 0.5 to 0.8), optionally top-p about 0.9Natural wording without much drift
Brainstorming, fictionHigher T (about 0.8 to 1.2), top-p about 0.9 to 0.95Diversity is the goal
Best-of-n with a verifierModerate to high TNeed diverse candidates to select from

Decoding also affects cost indirectly. Sampling costs almost nothing compared with the forward pass (see Prefill, Decode and the KV Cache), but loops and rambling at high temperature increase output tokens, which you pay for and wait for.

How does this come up in interviews?

1. What does temperature do, and does temperature 0 make the output deterministic? Temperature divides logits before softmax, sharpening (T < 1) or flattening (T > 1) the distribution without changing token ranking. At 0 it becomes argmax, which is deterministic on paper. In practice, floating-point differences, batching and near-ties can still change outputs between runs, so do not build tests that rely on exact text.

2. Compare top-k and top-p. Why might you prefer top-p? Top-k keeps a fixed number of tokens; top-p keeps the smallest set whose cumulative probability reaches p. Top-p adapts to the model's confidence: few candidates when it is sure, many when it is uncertain. A fixed k is too loose in the first case and too tight in the second.

3. A chat feature sometimes produces strange words in the middle of otherwise fine answers. What do you check? Look at temperature and top-p first, since a high temperature with no truncation lets tail tokens through. Then check whether penalties are set too high, which pushes the model away from the obvious token. Reproduce with logged parameters and compare outputs at several settings on a fixed prompt set.

4. The model repeats the same sentence over and over. How do you fix it? Confirm whether it is greedy decoding, where loops are common, and try a small amount of sampling. A modest frequency or presence penalty or n-gram blocking can help. Also check the prompt and any application loop that feeds output back in, since the cause is often not decoding at all.

5. How would you get diverse outputs and still pick a good one? Sample several candidates at moderate to high temperature, then choose with a verifier, a test suite, a reward model or majority voting. This trades extra output tokens for quality, so quantify the cost per request before shipping.

Common mistakes

  • Saying temperature 0 "guarantees" identical outputs.
  • Claiming temperature changes which token is most likely. It changes the gaps, not the ranking.
  • Tuning temperature and top-p together, then not knowing which one fixed the problem.
  • Using a large k and believing it protects against junk tokens when the distribution is flat or peaked.
  • Applying strong repetition penalties to code, JSON or text that must quote the source.
  • Treating decoding settings as a substitute for a good prompt or retrieval step.
  • Forgetting that the order of temperature, penalties and truncation differs between libraries.
  • Asserting exact string matches in tests of sampled output.