Skip to main content

Advanced decoding strategies

Temperature, truncated sampling, search, and quality-diversity trade-offs

The text generation lesson introduces the essential mechanism: produce a conditional distribution, select a token, append it to the context, and repeat. This optional page studies finer choices that transform that distribution or search over sequences. They do not update the model’s parameters, but they change the effective output distribution and the trade-offs among diversity, coherence, and instruction fidelity.

By the end of this page, you will be able to: - distinguish token-level distribution shaping from sequence search; - explain temperature, top-k, and nucleus sampling; - understand why maximizing likelihood does not by itself optimize open-ended text quality; - compare method families without assuming one strategy is universally better; - document the parameters needed for a reproducible decoding experiment.

TipKey ideas in one minute
  • Local processing: logits can be transformed, filtered, and renormalized before selecting the next token.
  • Temperature: it controls distribution concentration; it changes neither model parameters nor intrinsic model quality.
  • Top-k / top-p: they restrict candidates by a fixed count or a target cumulative mass; they change the effective distribution.
  • Search: greedy decoding optimizes a local decision; beam search keeps several hypotheses; contrastive decoding compares an expert and an amateur model.
  • Evaluation: quality and diversity depend on the task, metrics, and protocol; documenting settings is necessary for reproducibility. No strategy guarantees truth or global coherence.

Comprehension question on decoding.

At the first step of the Romans example, the illustrative distribution assigns 0.6 to “They” and 0.2 to “Aqueducts”. Greedy selection takes “They”. Unfiltered sampling can also draw “Aqueducts”. The selected token is appended to the prefix, which conditions the next step.

1. Where decoding happens

At a given step, the model produces logits \(z\) for the next token. A processing chain may then:

  1. transform logits or probabilities (for example, with temperature);
  2. restrict the candidate set (for example, top-k or top-p);
  3. renormalize the retained probabilities;
  4. select the next token, using argmax or sampling.

This is a conceptual representation. Libraries can apply several logits processors and warpers in an implementation-defined order. The order matters: applying temperature before or after truncation does not necessarily produce the same result.

Distinguish two operations:

  • Transforming a local distribution: changing candidate probabilities at one position.
  • Searching over sequences: comparing several continuations across multiple steps while accumulating their scores.

2. Temperature: controlling concentration

For a temperature \(T>0\), probabilities are computed from logits divided by \(T\):

\[ p_i(T)=\operatorname{softmax}\left(\frac{z}{T}\right)_i. \]

  • \(T=1\) preserves the distribution obtained from the logits.
  • \(0<T<1\) amplifies differences: the distribution becomes more concentrated.
  • \(T>1\) reduces differences: the distribution becomes flatter.
  • As \(T\) approaches zero, selection approaches argmax (apart from ties and numerical effects).

Temperature controls the spread of choices, not the model’s intrinsic quality. A low temperature does not guarantee a truthful answer; a high temperature does not guarantee creativity. It can also affect probability calibration and sequence diversity.

We reuse the base distribution from the output probabilities lesson to isolate the effect of temperature without changing the logits.

Candidate token Logit Exponential Probability
“They” \(\ln 6\) 6 0.6
“Aqueducts” \(\ln 2\) 2 0.2
“Nothing” \(0\) 1 0.1
“Well” \(0\) 1 0.1

Explore the effect of temperature

At temperature 1, “They” receives 60% in the course’s illustrative example. Before moving to \(\tau=0.5\), predict what will change: the probability distribution, the leading token, or both?

Check your prediction

At \(\tau=0.5\), dividing logits by the temperature doubles them. Their exponentials go from \((6,2,1,1)\) to \((36,4,1,1)\). Softmax then divides each value by \(42\). “They” rises from 60% to about 85.7% and remains first.

With finite logits, the distribution approaches uniformity as temperature increases: as \(\tau\to\infty\), each probability tends to \(1/V\). At low temperature, unfiltered sampling can still select a candidate with positive probability. For temperature \(T\), probability ratios satisfy \(p_i(T)/p_j(T)=\exp((z_i-z_j)/T)\): temperature changes probability ratios, but not the ranking of logits.

Numerical workbench and worked example

Logits optionally pass through temperature scaling, then softmax. Optional top-k or top-p filters may then be applied with renormalization, before selection by argmax or sampling. For z equal to (0, ln 3), probabilities change from 25/75 percent at temperature 1 to 36.6/63.4 percent at temperature 2; the ranking stays unchanged.

Pipeline from logits to a selected token, including the effect of temperature on a numerical example.

To reduce numerical overflow, implementations usually subtract the maximum before exponentiation: \(e^{z_i-m}/\sum_j e^{z_j-m}\), where \(m=\max_j z_j\). A tested implementation of temperature-scaled softmax is available in src/llm_lab/foundations/attention.py (softmax_with_temperature) and covered by tests/unit/test_attention.py.

NUMERICAL WORKBENCH · TEMPERATURE-SCALED SOFTMAX Python 3.12+ / NumPy

import numpy as np

logits = np.log([6, 2, 1, 1])

def stable_softmax(z, temperature=1.0):
    scaled = z / temperature
    exp_z = np.exp(scaled - np.max(scaled))
    return exp_z / np.sum(exp_z)

# Temperatures offered in the explorer
p_cold, p_standard, p_hot = (stable_softmax(logits, t) for t in (0.5, 1, 2))

for temperature, probabilities in zip((0.5, 1, 2), (p_cold, p_standard, p_hot)):
    print(f"Leading token probability (τ={temperature}) = {probabilities[0]:.2%}")

assert p_cold[0] > p_standard[0] > p_hot[0]
assert np.argmax(p_cold) == np.argmax(p_standard) == np.argmax(p_hot)

Compare a different set of four logits

With \(z=(3.0,1.5,1.0,0.2)\), the rounded percentages are as follows.

Temperature A B C D
0.2 99.9401 0.0553 0.0045 0.0001
1 70.4585 15.7214 9.5355 4.2846
5 33.5306 24.8401 22.4763 19.1530

At \(\tau=5\), all four probabilities are within 10 percentage points of the uniform value of 25%. To reproduce the table, reuse the workbench’s stable_softmax function with these four logits and three temperatures.

3. Truncated sampling: top-k and nucleus (top-p)

Pure ancestral sampling can select very low-probability tokens. Truncation methods reduce the candidate set before sampling.

Top-k: a fixed number of candidates

Top-k retains the \(k\) tokens with the highest probabilities, sets all other probabilities to zero, and renormalizes the retained probabilities.

The support size is fixed, but the retained probability mass varies with the distribution’s shape. The same \(k\) can therefore be highly restrictive at one step and much less restrictive at another.

Nucleus sampling: a target probability mass

Top-p (or nucleus sampling) retains the smallest set of most probable tokens whose cumulative probability reaches or exceeds threshold \(p\). The number of candidates therefore varies with the distribution:

  • highly concentrated distribution: the nucleus can be small;
  • flatter distribution: the nucleus can be larger.

The method was proposed to avoid sampling from the unreliable long tail while retaining diversity adapted to local uncertainty. It does not, however, guarantee global coherence.

What these filters change

Top-k and top-p redistribute conditional probability over a subset. They can reduce some undesirable tokens, but they also exclude possible continuations. This is a precision-recall trade-off over continuations: a filtered distribution is no longer the model’s original distribution.

Repetition penalties: a different family of controls

A repetition penalty does not select a fixed number of candidates or a nucleus with a target cumulative mass. Instead, it modifies logits associated with tokens already present in a history window, according to an inference engine’s convention, before selection. It can reduce some repetition loops, but an excessive penalty may distort an answer, penalize necessary terms, or suppress legitimate repetition. Record its value, the history window it applies to, and the implementation used. This penalty is not implemented in this project’s reference NumPy filters, which cover top-k and top-p only.

The reference NumPy implementation and its unit tests cover the two filters of this section: top_k_filter (a fixed support of \(k\) candidates) and top_p_filter (the smallest set whose cumulative mass reaches or exceeds \(p\), including the token that crosses the threshold). Both renormalize the retained distribution; ties are broken by the lowest original index (stable sort), so the result is deterministic.

This reference filters an already-computed probability distribution at one position (for example the output of a temperature softmax). Since the optional wiring into the generation loop, generate(..., greedy=False, top_k=..., top_p=...) applies temperature then truncation (top-k then top-p) before the draw; in greedy mode the filters are validated but ignored. There is no configurable logits processors chain, no beam search, no contrastive decoding, and no penalties. The “temperature then truncation” order applied here is a teaching convention, not an implementation standard.

The tests check renormalization, top-k(1) equivalence with greedy selection, inclusion of the crossing token, nucleus size adapting to the distribution’s shape, the effect of the temperature → filter order, determinism, absence of input mutation, and rejection of invalid distributions. They validate the announced scope, not the optimality of any setting for a given task.

4. Greedy selection, beam search, and open-ended generation

Greedy decoding selects the most likely token at each step. It is simple and deterministic, but a local choice does not necessarily maximize the probability of the best complete sequence. A myopic choice can steer the entire continuation.

Deterministic example: the best first token does not give the best sequence

Consider a two-token generation tree with no early stopping. The values below are conditional probabilities produced by the model (they could be obtained by applying softmax to logits):

Prefix Candidate token Conditional probability
start A 0.60
start B 0.40
A x 0.51
A y 0.49
B z 0.99
B w 0.01

Greedy decoding first selects A, because \(0.60>0.40\), and then x. The sequence probability is \(0.60\times0.51=0.306\). However, sequence B z has probability \(0.40\times0.99=0.396\): it is more likely over the two-token horizon.

This does not contradict greedy selection: it optimizes each local decision, not the product of conditional probabilities over the complete sequence.

import numpy as np

def softmax(logits):
    shifted = logits - np.max(logits)
    exp = np.exp(shifted)
    return exp / exp.sum()

# Log-probabilities used as logits: softmax(log(p)) = p.
p_first = softmax(np.log([0.60, 0.40]))       # A, B
p_after_a = softmax(np.log([0.51, 0.49]))     # x, y
p_after_b = softmax(np.log([0.99, 0.01]))     # z, w

sequence_scores = {
    ("A", "x"): p_first[0] * p_after_a[0],
    ("A", "y"): p_first[0] * p_after_a[1],
    ("B", "z"): p_first[1] * p_after_b[0],
    ("B", "w"): p_first[1] * p_after_b[1],
}
greedy = (
    ("A", "B")[int(np.argmax(p_first))],
    ("x", "y")[int(np.argmax(p_after_a))]
    if np.argmax(p_first) == 0
    else ("z", "w")[int(np.argmax(p_after_b))],
)
best_sequence = max(sequence_scores, key=sequence_scores.get)

print("greedy:", greedy, sequence_scores[greedy])  # ('A', 'x'), 0.306
print("best:  ", best_sequence, sequence_scores[best_sequence])  # ('B', 'z'), 0.396

This example is exhaustive because the tree contains only four sequences of fixed length two. For a longer horizon or a large vocabulary, exhaustive enumeration quickly becomes expensive; beam search then explores a subset of prefixes and remains an approximate search method. With variable-length sequences, stopping rules and any length normalization also affect the score being compared.

Beam search retains several candidate prefixes and expands the best-scoring continuations according to an accumulated score. It performs approximate search in sequence space; it is not merely an independent argmax at each position. It is useful in some constrained problems (translation, transcription, structured outputs), but likelihood maximization can produce short, generic, or repetitive open-ended text.

In the standard probabilistic formulation, the accumulated score is the sum of token log-probabilities (equivalent to multiplying probabilities for a fixed-length sequence). Practical implementations may, however, normalize this score by length and apply early-stopping rules. These choices change hypothesis ranking and termination; they are not merely optimization details. For example, Transformers documents a length_penalty that divides the score by a power of the length, along with several early_stopping policies. The A/B counterexample above deliberately compares fixed-length sequences without normalization; it illustrates the difference between a local and a sequence optimum, not every setting of production beam search (current Transformers documentation).

Holtzman et al. show that maximization methods, including beam search in their open-ended generation experiments, can degenerate despite high local likelihood. This does not mean beam search is always poor: task, score, constraints, and evaluation protocol determine its relevance.

5. Contrastive decoding: comparing an expert and an amateur model

Contrastive decoding proposes comparing the scores of a larger expert model and a smaller amateur model. The idea is to favor continuations better supported by the expert than by the amateur, while imposing a plausibility constraint to avoid tokens that are too unlikely under the expert.

This method illustrates a change in scoring function rather than a simple transformation of one model’s distribution. It does not necessarily require additional training, but it does require multiple models and increases inference cost. Published results depend on the models, tasks, and evaluation protocols; they do not demonstrate universal superiority.

6. Evaluating the quality-diversity trade-off

There is no optimal setting independent of the task. A strategy suited to creative completion may be unsuitable for factual extraction, translation, or constrained generation.

Separate several dimensions during evaluation:

  • Quality / relevance: does the output answer the prompt and satisfy constraints?
  • Coherence: are local and global dependencies preserved?
  • Diversity: are outputs excessively similar to one another?
  • Repetition: does the text loop or repeat segments?
  • Probabilistic fidelity: what probability does the model assign to observed tokens or sequences?

Perplexity does not summarize these dimensions. Likelihood (or mean NLL, and the perplexity derived from it under the chosen logarithm convention) measures the probability assigned to observed tokens on a given corpus; it does not directly measure factuality, instruction following, or user utility. Conversely, a task metric measures only the properties defined by that task and its protocol. For example, the Average Precision in the evaluation exercise measures ranking quality, not probability calibration; the likelihood lesson clarifies what the probabilistic score measures.

Example: same ranking, different calibration

Consider four binary observations, two positive and two negative, in the following ranking order:

Observation Target Score A Score B
1 1 0.65 0.99
2 0 0.55 0.89
3 1 0.45 0.11
4 0 0.35 0.01

Scores B are a strictly increasing transformation of scores A, so the ranking is unchanged. Average Precision is therefore \(5/6 \approx 0.833\) in both cases. However, with two fixed calibration bins \([0,0.5)\) and \([0.5,1]\), the observed positive frequency is \(0.5\) in each bin. The mean predicted score is respectively \(0.40\) and \(0.60\) for A, versus \(0.06\) and \(0.94\) for B. The size-weighted expected calibration error (ECE) is thus \(0.10\) for A and \(0.44\) for B.

labels = [1, 0, 1, 0]
scores_a = [0.65, 0.55, 0.45, 0.35]
scores_b = [0.99, 0.89, 0.11, 0.01]

def average_precision(y_true, scores):
    order = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
    positives = sum(y_true)
    return sum(
        sum(y_true[j] for j in order[:rank + 1]) / (rank + 1)
        for rank, i in enumerate(order)
        if y_true[i]
    ) / positives

def two_bin_ece(y_true, probabilities):
    groups = [
        [i for i, p in enumerate(probabilities) if p < 0.5],
        [i for i, p in enumerate(probabilities) if p >= 0.5],
    ]
    return sum(
        len(group) / len(y_true)
        * abs(
            sum(y_true[i] for i in group) / len(group)
            - sum(probabilities[i] for i in group) / len(group)
        )
        for group in groups
    )

ap_a, ap_b = average_precision(labels, scores_a), average_precision(labels, scores_b)
ece_a = two_bin_ece(labels, scores_a)
ece_b = two_bin_ece(labels, scores_b)

assert abs(ap_a - 5 / 6) < 1e-12 and abs(ap_a - ap_b) < 1e-12
assert abs(ece_a - 0.10) < 1e-12 and abs(ece_b - 0.44) < 1e-12
print(f"AP: {ap_a:.3f} / {ap_b:.3f}; ECE: {ece_a:.2f} / {ece_b:.2f}")

This counterexample shows that a rank-based metric cannot distinguish two calibrations when ordering is preserved. ECE depends on the number and placement of bins; on a small sample, these values illustrate a property rather than provide a reliable calibration estimate. This binary example explains the metric distinction; it is not an empirical evaluation of an LLM.

A strategy can improve some human judgments or sequence-level metrics while degrading other properties. Work on sampling adapters analyzes, in particular, the precision-recall trade-offs induced by local distribution transformations.

WarningInterpretation caveat

Holtzman et al.’s results primarily concern open-ended generation and the models/protocols studied. Their conclusions do not automatically transfer to translation, code, structured generation, or modern LLMs with complex post-processing. Comparing strategies requires holding the model, prompt, corpus, constraints, and evaluation protocol constant.

7. Making comparisons reproducible

For each comparison, record at least:

  • model identifier and version, tokenizer, and inference library;
  • exact prompt, available context, and truncation rules;
  • temperature, top-k, top-p, and processing order;
  • random seed, if the implementation allows it to be controlled;
  • maximum token count, stopping criteria, and any penalties;
  • number of generations per prompt and evaluation protocol;
  • automatic metrics and, where possible, human evaluation instructions.

Parameter labels alone (such as “temperature 0.7” or “top-p 0.9”) are insufficient if other processors, their order, or software versions differ.

Practice

To check the distinction between local transformations and sequence search, start with the dedicated decoding-strategies comprehension question. To calculate temperature effects and compare top-k with top-p on a concrete distribution, also use the Generation exercises on temperature and top-k/top-p. These activities are optional and include worked solutions; they do not replace evaluating output quality on real tasks.

Research references

Language: Français · English