7 Inference and Serving 2 / 8
  1. In this chapter
  2. Your first inference service
  3. Decoding and Sampling
  4. KV Cache and Inference Performance
  5. Prefix Caching and PD Disaggregation
  6. Model Quantization
  7. LLM Inference Serving
  8. Continuous Batching and PagedAttention
  9. Speculative Decoding
All chapters →

Chapter 7 · Inference and Serving 7.2

Decoding and Sampling: Temperature, Top-k, Top-p and Beam Search

Decoding turns the model's output distribution into tokens: greedy picks the most likely one, temperature sharpens or flattens the distribution, top-k and top-p cut off the unlikely tail, and beam search keeps several candidates. Together they set how deterministic and diverse the output is.

Beginner 14 min read Updated Companion code ↓

After this page you will be able to

  • Say that a model outputs scores and a probability distribution, not an answer.
  • Explain how greedy decoding, temperature, top-k and top-p each change the choice, and implement them in a few lines.
  • Describe how beam search keeps several candidates at once.
  • Choose temperature, top-p and repetition penalties for a task.
On this page
  1. The model outputs scores, not answers
  2. Greedy decoding: always take the largest
  3. Temperature: make the distribution steeper or flatter
  4. Top-k: choose only among the top k
  5. Top-p (nucleus sampling): truncate by cumulative probability
  6. Try it yourself
  7. A complete implementation
  8. Beam search: keep several candidates
  9. Repetition penalties and related parameters
  10. How to choose the parameters
  11. How decoding relates to inference optimization
  12. Summary and exercises
  13. Quick self-check
  14. FAQ

The model outputs scores, not answers

If you are new to this topic, start with Your first inference service.

At each step a language model outputs a score vector z∈R∣V∣z \in \mathbb{R}^{|\mathcal{V}|} (the logits) over the vocabulary, and softmax turns it into probabilities:

pi=exp⁡(zi)∑jexp⁡(zj)p_i = \frac{\exp(z_i)}{\sum_{j} \exp(z_j)}

Decoding answers the question: given this probability distribution, which token is actually chosen next? Different choices make the same model behave completely differently: some are stable but dull, others lively but prone to drifting off.

We use one example throughout this page. Suppose the model scores four candidate tokens as z=[4,3,1,0]z = [4, 3, 1, 0], which by default gives probabilities of about [0.696, 0.256, 0.035, 0.013][0.696,\ 0.256,\ 0.035,\ 0.013].

Greedy decoding: always take the largest

The simplest approach is to pick the most likely token at every step:

xt=arg⁡max⁡i pix_t = \arg\max_i\, p_i

The advantages are that it is deterministic and fast, which suits tasks with a standard answer. The drawbacks are:

  • No diversity: the same input always gives the same output.
  • Prone to repetition: locally optimal choices can keep leading the model back to the same phrase, producing loops such as “of the of the of the”.
  • Not necessarily globally optimal: the best choice at each step does not make the whole sentence the most probable.

Temperature: make the distribution steeper or flatter

Temperature TT rescales the scores before softmax:

pi(T)=exp⁡(zi/T)∑jexp⁡(zj/T)p_i(T) = \frac{\exp(z_i / T)}{\sum_{j} \exp(z_j / T)}
  • T<1T < 1: gaps between scores are amplified, the distribution is steeper, high-probability tokens dominate more, and the output is more conservative.
  • T=1T = 1: the original distribution.
  • T>1T > 1: gaps between scores are compressed, the distribution is flatter, low-probability tokens get more chance, and the output is more divergent.
  • T→0T \to 0: approaches greedy decoding.

With the example z=[4,3,1,0]z = [4, 3, 1, 0]:

Temperaturetoken 1token 2token 3token 4
T=0.5T = 0.50.8790.1190.0020.000
T=1T = 10.6960.2560.0350.013
T=2T = 20.5090.3090.1140.069

Note that temperature does not change the ranking, only the gaps between probabilities. It adjusts “how random”, not “which one”.

A higher temperature is not more creative

Raising the temperature amplifies both “interesting low-probability options” and “low-probability options that make no sense at all”. The higher the temperature, the more likely grammatical errors, drifting off topic and factual mistakes become. Creative tasks usually combine it with a truncation method (top-p) instead of raising the temperature alone.

Top-k: choose only among the top k

The long tail holds thousands of tokens with tiny probabilities; each is irrelevant on its own, but together their probability mass is not negligible. When sampling by probability, drawing one of them now and then makes a strange word suddenly appear in the output.

Top-k keeps only the kk most likely tokens, sets the rest to zero, renormalizes, and then samples.

In the example, take k=2k = 2: keep token 1 and token 2, and after renormalizing we get [0.731, 0.269, 0, 0][0.731,\ 0.269,\ 0,\ 0].

The problem with top-k is that kk is fixed: when the model is very sure (a sharp distribution), k=50k = 50 still lets in many unnecessary candidates; when the model is very unsure (a flat distribution), k=50k = 50 may cut off reasonable options.

Top-p (nucleus sampling): truncate by cumulative probability

Top-p, also called nucleus sampling, was proposed by Holtzman et al. in the 2019 paper The Curious Case of Neural Text Degeneration. It sorts tokens by probability from high to low, keeps the smallest set whose cumulative probability just reaches pp, discards the rest, and renormalizes:

Vp=the smallest set such that ∑i∈Vppi≥p\mathcal{V}_p = \text{the smallest set such that } \sum_{i \in \mathcal{V}_p} p_i \ge p

The size of this set is adaptive: when the model is very sure, one or two tokens already reach pp, so there are few candidates; when the model is very unsure, more tokens are needed to reach pp, so there are naturally more candidates.

In the example, take p=0.9p = 0.9: token 1 accumulates 0.696, and adding token 2 brings it to 0.953, which already exceeds 0.9, so the first two are kept, and the result is again [0.731, 0.269, 0, 0][0.731,\ 0.269,\ 0,\ 0].

Some inference frameworks also support min-p: keep the tokens whose probability is at least some fraction of the highest probability. It is adaptive like top-p, but its threshold is relative to the maximum probability instead of the cumulative probability.

Try it yourself

The demo below uses a fixed set of candidate tokens (the next word after “The weather today is”, with hand-set illustrative probabilities). Drag the sliders to see how the three parameters change the distribution, then click the sampling buttons to see the frequencies after many draws.

A complete implementation

Below is a common sampling function in PyTorch that combines temperature, top-k and top-p:

import torch


def sample_next_token(
    logits: torch.Tensor,
    temperature: float = 1.0,
    top_k: int | None = None,
    top_p: float | None = None,
) -> int:
    """logits: [vocab]. Returns the sampled token id."""
    if temperature == 0:  # degenerates to greedy decoding
        return int(logits.argmax())

    probs = torch.softmax(logits / temperature, dim=-1)
    sorted_probs, sorted_ids = probs.sort(descending=True)

    keep = torch.ones_like(sorted_probs, dtype=torch.bool)
    if top_k is not None:
        keep[top_k:] = False
    if top_p is not None:
        cumulative = sorted_probs.cumsum(dim=-1)
        # Drop every token whose cumulative probability before adding it already reached top_p
        # (the most likely token is always kept)
        keep &= (cumulative - sorted_probs) < top_p

    filtered = torch.where(keep, sorted_probs, torch.zeros_like(sorted_probs))
    filtered = filtered / filtered.sum()  # renormalize
    choice = torch.multinomial(filtered, num_samples=1)
    return int(sorted_ids[choice])

For logits = [4, 3, 1, 0] from the example, with top_p=0.9 or top_k=2, the candidate distribution is [0.731, 0.269, 0, 0]; with temperature=0.5, top_p=0.9 it is [0.881, 0.119, 0, 0].

A few implementation details to watch:

  • Apply temperature scaling first, then top-k / top-p. A different order gives different results.
  • The truncation condition of top-p is that “the cumulative probability before adding the current token is still less than pp”; this guarantees “the smallest set whose cumulative probability just reaches pp” and means the most likely token is never dropped.
  • You must renormalize after truncation, otherwise it is not a valid probability distribution.

Beam search: keep several candidates

Greedy decoding keeps a single choice per step. Beam search keeps the BB best partial sequences at the same time, extends each by one token at every step, and then picks the BB with the highest total log-probability among all extensions:

score(x1:t)=∑s=1tlog⁡p(xs∣x<s)\text{score}(x_{1:t}) = \sum_{s=1}^{t} \log p(x_s \mid x_{<s})

Beam search works well in tasks such as translation and summarization, where the output space is constrained and there is a fairly clear reference answer, because it is closer to “maximize the probability of the whole sentence”. Since the score is a sum of log-probabilities, longer sequences score lower, so length normalization is often needed.

In open-ended generation (dialogue, writing), however, beam search often produces bland, repetitive text. Holtzman et al. point out that the per-step probability of human writing is actually not always high, and pursuing the highest whole-sentence probability departs from the distribution of human text. This is why chat LLMs mainly use sampling rather than beam search.

Some services also provide penalty parameters on the generation history to suppress repetition:

ParameterHow it works
Repetition penaltyRescales the scores of tokens that have already appeared, lowering the chance of seeing them again
Frequency penaltySubtracts linearly with the number of times a token has appeared; the more it appeared, the more is subtracted
Presence penaltySubtracts a fixed amount once a token has appeared at all, encouraging new topics
Maximum generation lengthLimits the number of generated tokens to avoid endless generation
Stop sequencesStop immediately when a given string is generated

Penalties that are too strong hurt correctness: code, JSON and proper nouns naturally need the same token to recur.

How to choose the parameters

Below are common starting points, not final answers; adjust them with evaluations on your own task:

TaskSuggested starting pointReason
Information extraction, classification, structured outputTemperature 0–0.2Aim for stability; the answer is essentially unique
Code generationTemperature 0–0.3Strict syntax, small errors get amplified
Question answering, summarizationTemperature 0.2–0.7Balance accuracy and naturalness
Dialogue, writingTemperature 0.7–1.0, top-p 0.9–0.95Need naturalness and diversity
Brainstorming, creative workTemperature above 0.9, with top-pNeed divergence, but cut the long tail

Another rule of thumb: adjust one parameter at a time, and judge by the average performance of multiple samples on a fixed evaluation set instead of the quality of a single output.

Temperature 0 does not guarantee byte-for-byte identical output

The order of summation in parallel floating-point operations, how requests are batched together, and similar factors can cause small inconsistencies even in services that use greedy decoding. When strict reproducibility is needed, pin the model version, random seed and inference configuration, and tolerate tiny differences at the business level.

How decoding relates to inference optimization

Decoding is the last step of inference, but it is closely tied to the whole inference system:

  • Generating each token requires another forward pass, so the KV cache is essential for lowering decoding cost.
  • Speculative decoding drafts several tokens with a small model and verifies them with the large model in one pass; it uses rejection sampling to guarantee that the final distribution matches sampling directly from the large model (for a reading of the paper see Speculative Decoding).
  • To force the output into JSON or some grammar, mask the illegal tokens at every step before sampling; this is constrained decoding, covered in Structured Outputs and Function Calling.
  • At the serving layer, temperature, top-p, maximum length and stop conditions are usually per-request parameters.

Summary and exercises

Key points of this page:

  1. Decoding turns a probability distribution into concrete tokens; greedy is deterministic but prone to repetition, while sampling is diverse but may drift off.
  2. Temperature rescales the gaps between scores without changing the ranking; top-k keeps a fixed kk tokens, and top-p truncates adaptively by cumulative probability.
  3. Temperature first, then truncation, then renormalization; beam search suits tasks with a clear reference answer and does not suit open-ended generation.
  4. Parameters should be tuned with evaluations on your task, one at a time.

Quick self-check

1. You lower the temperature from 1 to 0.5 and change nothing else. What happens?

  • The most probable token changes, because the ranking is altered
  • The distribution gets sharper and the top token’s share rises, while the ranking stays the same
  • The distribution gets flatter and low-probability tokens get more chances
  • The probability of every token drops

The temperature scales the scores before softmax, so the gaps between scores are enlarged and high-probability tokens gain an advantage, but the ranking does not change. In the example on this page the top probability rises from 0.696 to 0.879.

2. The model is very sure: the top token holds 98% of the probability. How many candidates do Top-p 0.9 and Top-k 50 keep?

  • Both keep 50
  • Top-p keeps 50 and Top-k keeps 1
  • Top-p keeps just 1 and Top-k still keeps 50
  • Both keep just 1

Top-p keeps the smallest set whose cumulative probability reaches p; the first token already exceeds 0.9, so the set has 1 token, which means the number of candidates adapts. Top-k has a fixed k and still lets 49 unnecessary candidates in.

3. At some step the scores are [4, 3, 1, 0], giving probabilities of about [0.696, 0.256, 0.035, 0.013]. With Top-p = 0.9, how many tokens are kept?

  • 1
  • 2
  • 3
  • 4

The first token accumulates 0.696, still short of 0.9; adding the second gives 0.953, which exceeds 0.9, so the first two are kept and renormalizing gives [0.731, 0.269, 0, 0].

4. When temperature and Top-p are used together, what is the correct order?

  • Truncate with Top-p first, then scale by temperature, then normalize
  • Scale by temperature first, then truncate, renormalize after truncation, and finally sample
  • Sample first, then adjust the sampled token with the temperature
  • The order does not affect the result

Truncation is based on the probabilities after scaling, so a different order gives a different result. Without renormalizing after truncation you do not have a valid probability distribution.

5. Why do chat LLMs mainly use sampling instead of beam search?

  • Because beam search cannot be parallelized
  • Because beam search works only for English
  • Because in open-ended generation, maximizing the probability of the whole sequence tends to produce bland, repetitive text that departs from the distribution of human text
  • Because beam search needs no temperature parameter

Beam search works well for tasks such as translation and summarization, where the output space is constrained and there is a fairly clear reference answer. Holtzman et al. pointed out that the per-step probability of human writing is not always high.

6. Does setting the temperature to 0 (greedy decoding) guarantee byte-identical output?

  • Yes, because greedy decoding is a deterministic algorithm
  • Not necessarily; the summation order of parallel floating-point operations, how requests are batched and similar factors cause tiny numerical differences
  • No, because the model contains random numbers internally
  • Yes, as long as you change the random seed

Two nearly equal logits can swap rank under a tiny numerical difference, and one different token sends the rest of the generation in another direction. For strict reproducibility, pin the model version, the random seed and the inference configuration, and tolerate tiny differences in the application.

Exercises:

  1. By hand: for z=[2,1,0]z = [2, 1, 0], find the probability distributions at T=1T = 1 and T=0.5T = 0.5.
  2. Turn the function above into a batched version (logits of shape [batch, vocab]) and write a unit test to verify the truncation result of top_p.
  3. On a model API you know, sample the same prompt 5 times each at temperature 0, 0.7 and 1.2, record the differences in the outputs and explain why they happen.
Reference answers
  1. At T=1T = 1, exp⁡(2),exp⁡(1),exp⁡(0)\exp(2),\exp(1),\exp(0) are about 7.389, 2.718, 17.389,\ 2.718,\ 1 with sum 11.10711.107, so the probabilities are [0.665, 0.245, 0.090][0.665,\ 0.245,\ 0.090]. At T=0.5T = 0.5 the scores become [4, 2, 0][4,\ 2,\ 0], the exponentials are about 54.598, 7.389, 154.598,\ 7.389,\ 1 with sum 62.98762.987, and the probabilities are [0.867, 0.117, 0.016][0.867,\ 0.117,\ 0.016]. Lowering the temperature raises the top probability from 0.665 to 0.867 and leaves the ranking unchanged.

  2. The key to the batched version is to do every operation along the last dimension (dim=-1) and to put the probabilities back into the original vocabulary order with scatter after truncation:

    import torch
    
    
    def filter_probs(logits, temperature=1.0, top_k=None, top_p=None):
        """logits: [batch, vocab]. Returns truncated, renormalized probs."""
        probs = torch.softmax(logits / temperature, dim=-1)
        sorted_probs, sorted_ids = probs.sort(dim=-1, descending=True)
        keep = torch.ones_like(sorted_probs, dtype=torch.bool)
        if top_k is not None:
            keep[:, top_k:] = False
        if top_p is not None:
            cumulative = sorted_probs.cumsum(dim=-1)
            keep &= (cumulative - sorted_probs) < top_p
        filtered = torch.where(keep, sorted_probs, torch.zeros_like(sorted_probs))
        filtered = filtered / filtered.sum(dim=-1, keepdim=True)
        # Put the probabilities back in the original vocabulary order
        return torch.zeros_like(filtered).scatter(-1, sorted_ids, filtered)
    
    
    def test_top_p():
        logits = torch.tensor([[4.0, 3.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0]])
        out = filter_probs(logits, top_p=0.9)
        # Row 0: keep the first two and renormalize
        expected = torch.tensor([0.7311, 0.2689, 0.0, 0.0])
        assert torch.allclose(out[0], expected, atol=1e-4)
        # Row 1: a perfectly flat distribution needs all 4 to pass 0.9
        assert torch.allclose(out[1], torch.full((4,), 0.25))
        # Every row sums to 1
        assert torch.allclose(out.sum(dim=-1), torch.ones(2))
        # With a tiny p the most probable token is still kept
        tiny = filter_probs(logits[:1], top_p=1e-6)
        assert torch.equal(tiny, torch.tensor([[1.0, 0.0, 0.0, 0.0]]))
    
    
    test_top_p()
    print("all tests passed")  # Output: all tests passed

    To sample, call torch.multinomial(probs, num_samples=1) on the result of filter_probs; it already supports batches.

  3. What to expect (the exact text depends on the model and prompt, so rely on your own records): at temperature 0 the 5 outputs are essentially identical, with an occasional tiny difference on hosted services; at 0.7 the wording starts to differ while the key points stay the same; at 1.2 the differences are largest and off-topic, incoherent or factually wrong text can appear. The reason is that a higher temperature gives low-probability tokens a better chance of being drawn, and generation conditions every token on the prefix, so one different choice sends everything after it in a different direction and the differences grow. When recording, count how many distinct answers appear among the 5 outputs; the trend is easier to see than by comparing the text line by line.

FAQ

Is setting temperature to 0 the same as top_k=1?
In principle both are equivalent to greedy decoding, that is, always picking the most likely token. Services implement temperature=0 differently: some convert it directly to argmax, others treat it as a tiny positive number. For reproducible results you usually also need to fix the random seed and avoid floating-point differences introduced by batching.
Can top-p and top-k be used together?
Yes. A common approach is to keep the k most likely tokens with top-k first, then truncate within them by top-p, and finally renormalize and sample. But adjusting too many parameters at once makes behaviour hard to predict; fix the temperature first, adjust only one truncation parameter, and verify with an evaluation set.
Why does the same prompt give different results across runs?
Because the default decoding samples randomly according to the probabilities, each step may pick a different token, and the differences grow as generation goes on. Lowering the temperature, using greedy decoding or fixing the random seed reduces the differences, but in most online services byte-for-byte identical output is still not guaranteed.
What temperature should I use for code generation or information extraction?
These tasks have a clear correct answer, so a low temperature (0 to 0.3) or even greedy decoding is usually used for stability. For tasks that need diversity, such as brainstorming or creative writing, a temperature of 0.7 or higher combined with top-p works. The exact values should follow the evaluation results on your own task.