Skip to content
AI.info

Generative AI

Decoding, Search, and Sampling

Compare greedy decoding, temperature, top-k, nucleus sampling, beam search, and stopping rules for different generation contracts.

By the end you can

Fixed weights can produce different products

The checkpoint defines token scores. The decoding policy decides how those scores become an output trajectory. Change temperature, candidate filtering, search, or stopping, and quality and risk change with no weight touched. The best policy depends on the contract. A creative ideation tool is there to vary. Structured extraction has to stay faithful to the source, stop where it is told, and give the same answer twice.

Three published measurements set the scale of what that policy controls, and the rest of this lesson is built on them. On GPT-2 Large, greedy decoding repeated itself in 73.66% of its output. Human text repeated in 0.28%. Under exact inference over the WMT15 English-German test set, a Transformer base model gave its single global best score to the empty translation for more than 50% of sentences. And 1,000 completions drawn at temperature 0 from one fixed prompt came back as 80 distinct strings. Not one of those three numbers is a property of the weights.

Visual

Every generated token passes through a selection pipeline

Six stages run for every token. The model produces logits, scoring vocabulary candidates from the current context. Constraints come next: masks, schemas, bans, or grammar rules remove invalid candidates. Score transforms follow, where temperature and penalties modify relative preferences. Candidate filtering by top-k or nucleus sampling limits the available set. Selection or search then extends the sequence by greedy choice, sampling, beam search, or another policy. Finally the stopping check runs, where stop tokens, length limits, schema completion, or application logic end generation.

Providers may implement the details differently, so the deployed settings must be tested directly. Two of these six stages are the ones most products expose as parameters. The measured failures in this lesson land mostly in the other four. One of them lands below all six, in the batch-dependent kernels that compute the logits in the first place.

FigureProcess · 6 steps
  1. 1

    Produce logits

    The model scores vocabulary candidates from the current context.

  2. 2

    Apply constraints

    Masks, schemas, bans, or grammar rules remove invalid candidates.

  3. 3

    Transform scores

    Temperature and penalties modify relative preferences.

  4. 4

    Filter candidates

    Top-k or nucleus sampling limits the available set.

  5. 5

    Select or search

    Greedy choice, sampling, beam search, or another policy extends the sequence.

  6. 6

    Evaluate stopping

    Stop tokens, length limits, schema completion, or application logic end generation.

Comparison

Decoding methods optimize different notions of a good path

Greedy or near-greedy decoding chooses the locally highest-scoring continuation. It is simple and often repeatable, it can lock into a weak early path, it may produce repetitive continuations, and it still depends on infrastructure and model version. Stochastic sampling draws from a filtered probability distribution: diverse candidates, useful for ideation and ensembles, more run-to-run variation, candidate evaluation required. Beam-style search keeps several high-scoring partial sequences: useful in constrained sequence tasks, optimizing model score under a search approximation, able to favor generic or length-biased outputs, and adding compute and memory.

No method converts the model distribution into verified truth. The third family has an extreme case documented end to end. In 2019, Stahlberg and Byrne ran exact inference — beam search combined with depth-first search — over the entire WMT15 English-German test set under a Transformer base model. Exact inference returns the genuinely highest-scoring output. That let them separate two things that are normally tangled: what the search finds, and what the model actually prefers. Beam search failed to find the global best model score in most cases, even at beam size 100. And what it was failing to find turned out to be nothing at all. Their abstract: "For more than 50% of the sentences, the model in fact assigns its global best score to the empty translation, revealing a massive failure of neural models in properly accounting for adequacy." The search approximation was covering for the model. Search harder in that system and the output moves toward the empty string.

FigureComparison · 3 columns

Greedy or near-greedy

Choose the locally highest-scoring continuation.

  • Simple and often repeatable
  • Can lock into a weak early path
  • May produce repetitive continuations
  • Still depends on infrastructure and model version

Stochastic sampling

Draw from a filtered probability distribution.

  • Supports diverse candidates
  • Useful for ideation and ensembles
  • Increases run-to-run variation
  • Requires candidate evaluation

Beam-style search

Keep several high-scoring partial sequences.

  • Useful in constrained sequence tasks
  • Optimizes model score under a search approximation
  • Can favor generic or length-biased outputs
  • Adds compute and memory

Example

Decoding failures have recognizable signatures

Use output traces and distributions rather than adjusting settings blindly. The signatures are measurable, and they have been measured. The Curious Case of Neural Text Degeneration, published in 2020, put decoding strategies and human text side by side on GPT-2 Large. Its abstract states the mechanism in one line: "maximization-based decoding methods such as beam search lead to degeneration — output text that is bland, incoherent, or gets stuck in repetitive loops." Its Table 1 attaches numbers to each signature below.

  • Repetition loop: A phrase receives high local probability and reinforces itself in later context. In Table 1 that is 73.66% repetition under greedy decoding against 0.28% for human text. One model, one benchmark, and a two-hundred-fold gap opened by the selection rule alone.
  • Generic collapse: Search favors safe high-probability language over specific useful content. Beam search at b=16 repeats at 28.94%. Its perplexity in the same table is 1.48, against 1.50 for greedy and 12.38 for human text. Output far more predictable than the writing it imitates is what blandness looks like as a number.
  • Rare-token instability: High temperature promotes candidates unsupported by the task evidence, and the filter you use to hold the tail back shows up in human evaluation. Nucleus sampling at p=0.95 scores 0.97 on HUSE against 0.19 for top-k=40, while keeping repetition to 0.36% — close to the 0.28% of human text.
  • Premature stop: A stop sequence appears inside valid content and truncates the artifact. No published table catches this one for you. It is a property of your own delimiters and schema, and it surfaces only in traces of complete artifacts.
  • Runaway output: Missing termination logic consumes latency and cost after the task is complete. Stopping is the last stage of the pipeline and the one most often left at a default, because it belongs to the application rather than to the model.

Analogy

A route planner can choose the safest road or explore alternatives

A route planner selects one path from many scored possibilities. It can always choose the currently fastest turn, keep several routes open, or deliberately explore alternatives.

Decoding makes a related choice over token paths. Roads do not move when a driver turns. Each selected token changes the future probability landscape and can alter meaning discontinuously. And unlike a road network, the scores being searched may rank an empty route above every real one.

Choose a decoding policy for the artifact contract, then validate complete outputs rather than individual token scores.

Key idea

Low temperature is not a truth or determinism guarantee

A low-temperature policy concentrates probability on high-scoring tokens. It does not verify claims, eliminate ties, or guarantee identical output across changing models, kernels, batching, and provider implementations. That last clause is not a hedge. It has been measured. In September 2025, Horace He and Thinking Machines Lab sampled 1,000 completions of 1,000 tokens at temperature 0 from Qwen3-235B-A22B-Instruct-2507, all from one fixed prompt. "Surprisingly, we generate 80 unique completions, with the most common of these occuring 78 times." All 1,000 were identical for the first 102 tokens. They first diverged at the 103rd, where 992 continued "Queens, New York" and 8 continued "New York City". The sampler was not the cause. With the authors' batch-invariant kernels enabled, all 1,000 completions were identical. The nondeterminism lived in batch-dependent kernels, below the decoding policy entirely.

Decoding has its own literature, and its findings are specific results rather than defaults. In 2020, Meister and colleagues reframed beam search as the exact solution to a different objective: "We find that beam search enforces uniform information density in text, a property motivated by cognitive science." In their neural machine translation experiments, how closely a decoding strategy adheres to that property correlates strongly with BLEU. Meister and colleagues then defined locally typical sampling in 2023 — the set of strings whose every word carries information content close to the model's conditional entropy. They reported: "Automatic and human evaluations show that, in comparison to nucleus and top-k sampling, locally typical sampling offers competitive performance (in both abstractive summarization and story generation) in terms of quality while consistently reducing degenerate repetitions." Competitive quality, fewer repetitions, on two named tasks.

Even the most-copied configuration in the field is a tuned local result. The original Transformer paper says in §6.1, in 2017: "We used beam search with a beam size of 4 and length penalty α = 0.6". Those values were chosen after experimentation on the development set, together with a maximum output length of input length + 50 and early termination when possible. It is a translation setting, tuned on one development set, for one task. It is copied as though it were a default.

If repeatability matters, version every relevant component and evaluate observed variance. Exact business invariants should still be enforced outside the model.

Deterministic intent requires system-level versioning and validation, not a single decoding parameter.

Steps

Tune decoding with a task-shaped experiment

The matrix should measure how good the whole artifact is and what it costs to run. Define output quality first, specifying fidelity, diversity, structure, support, and allowed variation. Choose candidate policies, including a simple baseline and a small set of justified alternatives. Evaluate repeated runs, measuring variance, tail failures, and candidate diversity. Inspect stopping behavior, tracking truncation, invalid completion, and excess generation. Price the policy, including latency, tokens, retries, and downstream validation. Then lock the release settings, versioning the complete decoding configuration with the model.

Steps three and six are the ones teams skip. The cost of skipping them has been quantified. Ten authors measured it in 2025, in Understanding and Mitigating Numerical Sources of Nondeterminism in LLM Inference: "For instance, under bfloat16 precision with greedy decoding, a reasoning model like DeepSeek-R1-Distill-Qwen-7B can exhibit up to 9% variation in accuracy and 9,000 tokens difference in response length due to differences in GPU count, type, and evaluation batch size." The decoding policy never changes in that comparison. It is greedy throughout. Only the GPU count, the GPU type and the evaluation batch size move, and the authors trace the cause to the non-associativity of floating-point arithmetic. An accuracy number reported without the serving configuration beside it is worth up to nine points less than it looks.

Step two has its own published evidence. A 2024 survey, A Thorough Examination of Decoding Methods in the Era of LLMs, compared deterministic and stochastic decoding across tasks, models and deployment settings — on performance, on robustness to hyperparameter changes, and on decoding speed. No method won generally: "Our findings reveal that decoding method performance is notably task-dependent and influenced by factors such as alignment, model size, and quantization." Some methods only came out ahead after extensive hyperparameter tuning. That is the published reason this experiment cannot be replaced by a recommended setting from someone else's task.

FigureProcess · 6 steps
  1. 1. Define output quality

    Specify fidelity, diversity, structure, support, and allowed variation.

  2. 2. Choose candidate policies

    Include a simple baseline and a small set of justified alternatives.

  3. 3. Evaluate repeated runs

    Measure variance, tail failures, and candidate diversity.

  4. 4. Inspect stopping behavior

    Track truncation, invalid completion, and excess generation.

  5. 5. Price the policy

    Include latency, tokens, retries, and downstream validation.

  6. 6. Lock the release settings

    Version the complete decoding configuration with the model.

Decoding is a product policy over a learned distribution

Changing the selection policy can improve one output property while weakening another. The right choice follows how much the task can let the output vary, how long it can wait, and how much validation it needs. Greedy decoding is the cheapest policy, and the one that repeated at 73.66% on GPT-2 Large. Beam search is the most thorough, and the one that ranked the empty translation first for more than 50% of the WMT15 English-German test set. Temperature 0 is the most constrained, and still returned 80 distinct completions from 1,000 draws on one fixed prompt. Each of those is a reasonable policy for some contract and a defect for another. None of them is safe by default.

Prompting comes next. Prompts alter the distribution by changing context. Decoding decides how the resulting distribution is traversed.

Key takeaways