Autoregressive language models generate text sequentially by estimating a conditional probability distribution over a vocabulary at each decoding step. While model training optimizes cross-entropy loss over large corpora, the quality, diversity, and coherence of generated sequences depend directly on the decoding strategy used to select tokens from the output logits.
Deterministic algorithms such as greedy search and beam search systematically fail in open-ended generation tasks, collapsing into repetitive loops and dull phrasing. Conversely, unconstrained stochastic sampling from the raw distribution samples improbable tokens from the long tail of the vocabulary, causing severe semantic drift.
Modern inference engines rely on stochastic decoding algorithms that dynamically reshape, truncate, and normalize probability distributions before drawing samples. Understanding the mathematical mechanics of temperature scaling, top-k, nucleus (top-p), locally typical sampling, and min-p is essential for tuning inference pipelines across deterministic code generation, structured extraction, and open-ended reasoning.
The Autoregressive Decoding Formulation
At timestep , given a context sequence , a transformer language model computes an unnormalized logit vector over a vocabulary containing discrete tokens:
Here, represents the final hidden state of the transformer stack, and denotes the output projection matrix (un-embedding layer).
The categorical distribution over candidate tokens is obtained via the standard softmax function:
In deterministic greedy decoding, the model selects the mode of the distribution at every step:
As demonstrated by Holtzman et al. (2020), greedy search and beam search suffer from neural text degeneration. Because language models assign high probabilities to generic phrases and repetitive n-grams, maximizing token likelihood leads to degenerate loops and unnatural text statistics that deviate sharply from human writing. Human text exhibits localized dips in conditional probability where surprising or context-shifting words occur.

Temperature Scaling
Temperature scaling rescales logits by a strictly positive scalar parameter before computing the softmax distribution. Originally adapted from statistical mechanics and simulated annealing (Ackley et al., 1985), temperature controls the entropy of the resulting categorical distribution.
The temperature-adjusted probability distribution is defined as:
Limiting Behaviors
- As , the distribution concentrates all probability mass onto the maximum logit value:
This recovers deterministic greedy argmax selection.
- At , the sampling distribution matches the raw model output probabilities.
- As , the logits become negligible relative to , causing the distribution to converge to a discrete uniform distribution:
Entropy Dynamics
The Shannon entropy of the distribution is given by:
Differentiating with respect to yields , establishing that entropy increases monotonically with temperature.
While temperature scales the spread of probabilities, it operates uniformly across all tokens. Increasing flattens the distribution and inflates the probability of low-confidence tail tokens, often generating incoherent tokens unless combined with truncation filters.
Fixed-Rank Truncation: Top-k Sampling
Top-k sampling, introduced for language models by Fan et al. (2018), restricts candidate tokens to the most probable items in vocabulary .
Let the vocabulary tokens be sorted by descending probability at timestep :
The top-k candidate set is defined as:
The truncated distribution sets all probabilities outside to zero and renormalizes the remaining mass:
Structural Failure Modes
Top-k sampling enforces a static rank threshold regardless of the underlying distribution geometry:
- High-Confidence (Peaked) Contexts: When the model predicts a specific grammatical continuation (for example, a closing parenthesis or common idiom where ), top-k with still admits 49 highly improbable tokens into the candidate set.
- Low-Confidence (Flat) Contexts: When the model evaluates dozens of equally plausible synonyms (for example, in creative descriptions where 200 candidates each carry ), top-k with arbitrarily cuts off 150 valid options.
Cumulative Probability Truncation: Nucleus (Top-p) Sampling
To address the rigidity of fixed rank thresholds, Holtzman et al. (2020) introduced nucleus sampling (top-p sampling). Nucleus sampling defines the truncation boundary dynamically by accumulating probability mass until reaching a predefined threshold .
The nucleus candidate set is the smallest subset of top-ranked tokens whose cumulative probability exceeds :
where is the minimal index satisfying:
The truncated and renormalized distribution is:
Dynamic Candidate Pool Sizing
The size of the candidate pool adjusts automatically based on the conditional entropy of the distribution:
- When the model is confident (), the nucleus collapses to a single token (), acting deterministically.
- When uncertainty is high, the nucleus expands across hundreds or thousands of tokens, preserving lexical diversity.
Tail Inflation Under High Temperature
When high temperatures () are applied prior to top-p truncation, individual token probabilities flatten. If the top token's probability drops to 0.02, accumulating requires including hundreds of low-probability tail tokens, permitting unvetted low-quality generations.

Information-Theoretic Truncation: Locally Typical Sampling
Locally typical sampling, formulated by Meister et al. (2022), approaches token selection through an information-theoretic framework known as the Expected Information Hypothesis.
In human communication, speakers balance information transfer across utterances, maintaining a relatively uniform rate of information rather than selecting either overly obvious or overly obscure words.
The information content (surprisal) of a candidate token is:
The expected information of the next token corresponds to the conditional Shannon entropy :
Locally typical sampling constructs a candidate set by selecting tokens whose surprisal is closest to the conditional entropy:
Tokens are sorted by their absolute deviation from the expected information:
Tokens with minimal are accumulated until their cumulative probability mass reaches threshold :
By favoring tokens whose information density matches the local context entropy, typical sampling suppresses both repetitive boilerplate tokens (which have near-zero surprisal) and nonsensical tail tokens (which have extreme surprisal).
Relative Probability Truncation: Min-p Sampling
Min-p sampling, proposed by Menet et al. (2024), introduces an adaptive truncation threshold scaled directly against the highest-probability token in the distribution.
Rather than defining an absolute cumulative mass or rank , min-p defines a base scaling factor . The minimum probability threshold at step is calculated as:
Let denote the top candidate. The candidate set retains only tokens whose probability is at least times that of :
The truncated distribution is renormalized:
Behavioral Advantages
Min-p adapts dynamically across confidence regimes:
- Confident Contexts: If and , the threshold is . All tokens below 8% probability are immediately pruned, preventing low-likelihood noise.
- Uncertain Contexts: If and , the threshold becomes . Any token with at least 1% probability remains eligible.
Because the cutoff scales proportionally with the top candidate, min-p maintains stability even at high temperatures ( to ). It allows creative exploration among competing top candidates while rigorously excluding tail tokens.
Perplexity-Controlled Decoding: Mirostat
Mirostat, developed by Basu et al. (2021), treats text generation as a closed-loop control problem. Standard samplers often drift over long generations into either:
- The Boredom Trap: Perplexity collapses, and the model enters repetitive loops.
- The Confusion Trap: Perplexity escalates, and the model produces incoherent outputs.
Mirostat regulates the generation rate of surprise to match a target surprisal .
At each step , the algorithm observes the surprise of the sampled token :
The control error is:
A feedback parameter is updated via gradient descent:
where is the learning rate.
The truncation parameter (such as dynamic top-k or top-p threshold) is then derived as a function of using estimated Zipfian power-law parameters of the vocabulary distribution. By dynamically widening or narrowing candidate pools in response to observed surprisal, Mirostat enforces stable cross-entropy across thousands of generated tokens.
Decoding Strategies in Production
Each decoding strategy optimizes for distinct trade-offs between computational overhead, vocabulary coverage, and sample coherence:
- Greedy Search (): Deterministic mode selection. Ideal for code compilation, mathematical reasoning, and schema-constrained JSON extraction where reproducibility is paramount.
- Temperature + Top-p: General standard for conversational assistants. Standard settings () provide balance, though prone to degradation if temperature is pushed past .
- Min-p Sampling: Recommended for creative writing, narrative generation, and high-temperature exploration (). Prunes low-confidence tail tokens without restricting multi-candidate exploration.
- Locally Typical Sampling: Well-suited for stylized narrative and essay generation where uniform information density improves prose cadence.
- Mirostat: Preferred for long-form synthetic book generation, long-horizon narrative planning, and autonomous agents prone to degradation over extended context horizons.
Sources
- Fan, A., Lewis, M., & Dauphin, Y. (2018). Hierarchical Neural Story Generation. Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL).
- Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2020). The Curious Case of Neural Text Degeneration. International Conference on Learning Representations (ICLR).
- Meister, C., Pimentel, T., Wiher, G., & Cotterell, R. (2022). Locally Typical Sampling. Transactions of the Association for Computational Linguistics (TACL).
- Basu, S., Ramachandran, G. S., Keskar, N. S., & Varshney, L. R. (2021). Mirostat: A Neural Text Decoding Algorithm that Directly Controls Perplexity. International Conference on Learning Representations (ICLR).
- Menet, M. et al. (2024). Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs. arXiv preprint arXiv:2407.01082.
- Ackley, D. H., Hinton, G. E., & Sejnowski, T. J. (1985). A Learning Algorithm for Boltzmann Machines80012-4). Cognitive Science, 9(1), 147-169.
