AI Logic

Decoding

Locally Typical Sampling

Updated:

An example of Locally Typical Sampling with τ = 0.5. Top: the flat distribution after "Today is" (entropy 1.95). In order of the smallest gap between information content and entropy, Sunday, rainy, hot, and cold are kept, while the most probable word, "sunny," is discarded because its gap is large. Right: the probabilities of the four kept words renormalized by their total of 0.53. Bottom: the peaked distribution after "Thank you very" (entropy 0.45), where only the single word "much" is kept

What is Locally Typical Sampling?

Locally Typical Sampling is a decoding method that keeps only those next-word candidates whose information content (how surprising the word is) is close to the average information content of the context (the entropy), and samples randomly from them. It was proposed by Meister et al. (2023). Unlike Top-k sampling and Nucleus sampling, it removes not only words with very low probability but sometimes also words that are too predictable.

The method starts from a linguistic observation about how people choose the words they use.

  • People try to convey information as efficiently as possible while avoiding misunderstanding.
  • As a result, they tend to avoid both very surprising words (too much information, hard to convey) and obvious words (too little information, wasteful), and speak so that the information per word stays roughly constant.

The paper explains that methods that always pick high-probability words (such as beam search) tend to produce dull or repetitive text because they string together words that carry little information. Locally Typical Sampling prevents this by restricting the candidates at each step to words with a "human-like" amount of information.

Procedure

First, two quantities are defined. The information content of a word yy is the negative log of its probability, −log⁡p(y∣y<t)-\log p(y \mid y_{<t}). It grows as the word becomes less probable (more surprising). The conditional entropy of the context is the expected value (mean) of the information content.

H(Yt∣Y<t=y<t)=−∑y∈Vp(y∣y<t)log⁡p(y∣y<t)H(Y_t \mid Y_{<t} = y_{<t}) = -\sum_{y \in \mathcal{V}} p(y \mid y_{<t}) \log p(y \mid y_{<t})

At each step, one word is chosen by the following procedure (the procedure in the computational-complexity paragraph of Section 5.2 of the paper).

  1. Use the model to compute the next-word probability p(y∣y<t)p(y \mid y_{<t}) for every word in the vocabulary.
  2. Compute the conditional entropy HH.
  3. For each word, compute the absolute difference between its information content and the entropy, ∣−log⁡p(y∣y<t)−H∣\left| -\log p(y \mid y_{<t}) - H \right|, and sort the words in ascending order of this value.
  4. Take words in that order and stop once the cumulative probability exceeds τ\tau. Call the set of taken words C(y<t)C(y_{<t}).
  5. Set the probabilities of words outside C(y<t)C(y_{<t}) to 0, renormalize by the total Z(y<t)Z(y_{<t}) (the formula below), and sample one word according to the resulting probabilities.
π(y∣y<t)=p(y∣y<t) 1{y∈C(y<t)}Z(y<t),Z(y<t)=∑y∈C(y<t)p(y∣y<t)\pi(y \mid y_{<t}) = \frac{p(y \mid y_{<t}) \, \mathbb{1}\{ y \in C(y_{<t}) \}}{Z(y_{<t})}, \qquad Z(y_{<t}) = \sum_{y \in C(y_{<t})} p(y \mid y_{<t})

τ\tau is a parameter that determines how much of the original probability mass to keep, and it plays the same role as pp in Nucleus sampling. The only difference is the order in which words are taken: not "highest probability first" but "information content closest to the entropy first."

The arXiv version of the paper (v6) carries a correction note: the formula that writes the candidate set as an optimization problem (Eq. 12) also admits solutions in which the word closest to the entropy is excluded from the set. What implementations actually use is the procedure shown here: take words in order of closeness to the entropy until the total exceeds τ\tau.

Example: the word after "Today is"

The figure at the top of the article shows an example of choosing the next word in two contexts with τ=0.5\tau = 0.5 (the probabilities are illustrative values and are the same example used in articles such as Top-k sampling; logarithms are natural logarithms).

Flat distribution (after "Today is"): the entropy is H≈1.95H \approx 1.95. The information content of each word and its gap from HH are as follows.

Rank by gapWordProbabilityInformation content −log⁡p-\log pGap ∣−log⁡p−H∣\lvert -\log p - H \rvertCumulative probabilityResult
1Sunday0.151.900.050.15Keep
2rainy0.201.610.340.35Keep
3hot0.102.300.350.45Keep
4cold0.082.530.580.53Keep (exceeds 0.5 here)
5sunny0.301.200.74−Discard
6–10Monday, nice, the, cat, of0.06–0.012.81–4.610.87–2.66−Discard

The most probable word, "sunny" (0.30), is excluded from the candidates because its information content of 1.20 is too far below the entropy (it is too predictable). Dividing the four remaining words by their total of 0.53 gives rainy 0.38, Sunday 0.28, hot 0.19, and cold 0.15.

Peaked distribution (after "Thank you very"): the entropy is small, H≈0.45H \approx 0.45, and "much" (information content 0.11, gap 0.34) is the closest word. Since "much" alone has probability 0.90, the candidate set is just the single word "much."

Thus, in contexts where the answer is nearly determined, the high-probability word is chosen as is. The paper also notes that in low-entropy contexts the candidates are the same as in Nucleus sampling. High-probability words are excluded only in contexts with many plausible candidates.

Why it works

The paper showed, using data from three language-generation tasks, that when human-written text is measured with a language model, the difference between each word's information content and the entropy of its context is concentrated near 0 (Figure 1). In other words, the words in human text are usually words with "average surprise for that context."

Text produced by probability-maximizing decoding, on the other hand, strings together words whose probability is too high, that is, whose information content is too low. The paper argues that this causes dull text, and that the phenomenon in which repeating a phrase makes that phrase more and more probable (Holtzman et al., 2020) can also be explained by the phrase's information content decreasing with each repetition.

By keeping the information content at each step within the range typical of human text, Locally Typical Sampling avoids both of these failure modes.

  • Removes overly predictable words → prevents dull text and repetition
  • Removes overly surprising words → prevents text from breaking down due to low-probability words

As an analogy, in conversation it is hard to follow both someone who only says the obvious and someone who says something completely out of the blue. The idea is that natural text consists of words that carry just the right amount of new information.

Experimental results

The paper compared the method with other decoding methods on story generation (GPT-2 Large fine-tuned on WritingPrompts) and summarization (BART fine-tuned on CNN/DailyMail). For human evaluation, five raters scored 200 generations per method on a 1–5 scale for each criterion (median of the five raters), and the scores were averaged over criteria.

Story generation (excerpt from Table 1)

MethodMAUVE (higher is better)REP (lower is better)Human evaluation
Human text−0.284.12
Nucleus (p=0.9p = 0.9)0.950.354.09
Nucleus (p=0.95p = 0.95)0.950.304.13
Top-k (k=30k = 30)0.880.354.13
Top-k (k=40k = 40)0.920.354.09
Typical (τ=0.2\tau = 0.2)0.780.304.15
Typical (τ=0.95\tau = 0.95)0.960.314.13

Summarization (excerpt from Table 2)

MethodMAUVE (higher is better)REP (lower is better)Human evaluation
Human summaries−0.134.31
Beam search (width 5)0.900.144.35
Nucleus (p=0.95p = 0.95)0.990.154.26
Top-k (k=30k = 30)0.980.164.31
Typical (τ=0.95\tau = 0.95)0.960.154.32

MAUVE measures how close the distribution of generated text is to that of human text, and REP measures the amount of repetition.

  • Human evaluation: Typical with τ=0.2\tau = 0.2 for stories and τ=0.95\tau = 0.95 for summaries scored highest among the sampling methods. However, every method scored close to human text and the differences are small; for summarization, beam search scored slightly higher.
  • Repetition: in Figure 2 of the paper, repetition rises sharply for some values of Top-k's kk and Nucleus's pp, whereas Typical's REP stays at about the level of human text for most values of τ\tau. The paper presents this as an advantage: the method is robust to the choice of parameter.

Practical considerations

A good τ\tau varies greatly by task. In the paper's preliminary experiments, τ=0.2\tau = 0.2 worked best for story generation and τ=0.95\tau = 0.95 for summarization. On the other hand, MAUVE for stories with τ=0.2\tau = 0.2 is 0.78, lower than for the other settings. Since the best value depends on the metric, choose it per task on validation data.

  • One extra entropy computation: the method requires computing the entropy over the whole vocabulary and sorting, but the paper states that its complexity is O(∣V∣log⁡∣V∣)O(|\mathcal{V}| \log |\mathcal{V}|), the same as Nucleus and Top-k.
  • Be careful with models trained with Label Smoothing: the paper warns that models trained with Label Smoothing have distributions closer to uniform, so their entropy is overestimated; the models in the experiments were fine-tuned without Label Smoothing.
  • Using it in libraries: in Hugging Face's generate, specify it as do_sample=True, typical_p=0.95 (typical_p corresponds to τ\tau). Because Top-k's default value of 50 also applies, specify top_k=0 as well when using Typical alone.

Comparison with other decoding methods

Locally Typical Sampling is one of the methods that "narrow the candidates, renormalize, then sample," like Top-k sampling and Nucleus sampling; what differs is the order in which candidates are taken.

MethodOrder of taking candidatesWhere to stopMost probable wordOutput
Top-k samplingHighest probability firstkk wordsAlways keptVaries each time
Nucleus samplingHighest probability firstTotal reaches ppAlways keptVaries each time
Locally Typical Sampling (this article)Information content closest to the entropy firstTotal exceeds τ\tauCan be excluded in flat distributionsVaries each time
Contrastive SearchAmong the top kk by probability, scored by probability and by not being too similar to the preceding contextPick oneCan be excludedSame every time
Beam searchProbability of the whole sentenceTop BB partial sentencesUsually keptSame every time

Rough guidelines for choosing:

  • Want something easy to try first: Nucleus sampling. It is widely used and is a default option in many libraries.
  • Do not want to spend time tuning parameters, or want less repetition: Locally Typical Sampling. Changing τ\tau has been reported to rarely increase repetition.
  • Want the same output every time: beam search or Contrastive Search.

PyTorch example

Show code
python
import torch


def typical_sample(logits, tau=0.95):
    """logits: [batch, vocab_size]. Keep words in order of information content closest to the entropy until the total exceeds tau, then sample"""
    log_p = torch.log_softmax(logits, dim=-1)
    p = log_p.exp()
    entropy = -(p * log_p).sum(dim=-1, keepdim=True)        # conditional entropy H
    deviation = (-log_p - entropy).abs()                    # |information content − H|
    order = deviation.argsort(dim=-1)                       # smallest gap first
    sorted_p = p.gather(-1, order)
    cum = sorted_p.cumsum(dim=-1)
    # Discard a word if the words before it already exceed tau (the first is always kept)
    remove = (cum - sorted_p) > tau
    sorted_p = sorted_p.masked_fill(remove, 0.0)
    sorted_p = sorted_p / sorted_p.sum(dim=-1, keepdim=True)  # renormalize by the total Z
    choice = torch.multinomial(sorted_p, num_samples=1)
    return order.gather(-1, choice).squeeze(-1)             # map back to vocabulary indices


# Same probabilities as the figure at the top of the article (after "Today is")
words = ["sunny", "rainy", "Sunday", "hot", "cold", "Monday", "nice", "the", "cat", "of"]
p = torch.tensor([[0.30, 0.20, 0.15, 0.10, 0.08, 0.06, 0.05, 0.03, 0.02, 0.01]])
log_p = p.log()
H = -(p * log_p).sum()
print("H =", round(H.item(), 2))  # H = 1.95
torch.manual_seed(0)
picked = {words[typical_sample(log_p, tau=0.5).item()] for _ in range(5000)}
print(sorted(picked))  # ['Sunday', 'cold', 'hot', 'rainy'] (sunny is never chosen)


# Form used with a real model (autoregressively extend one word at a time)
@torch.no_grad()
def generate(model, input_ids, max_new_tokens=50, tau=0.95, eos_id=None):
    """Assumes model(input_ids) returns logits of shape [batch, length, vocab_size]"""
    model.eval()  # disable dropout
    for _ in range(max_new_tokens):
        next_id = typical_sample(model(input_ids)[:, -1, :], tau)
        input_ids = torch.cat([input_ids, next_id[:, None]], dim=-1)
        if eos_id is not None and (next_id == eos_id).all():
            break
    return input_ids

# With Hugging Face Transformers (typical_p is tau; top_k=0 turns off Top-k)
# model.generate(input_ids, do_sample=True, typical_p=0.95, top_k=0)

FAQ

Q. Doesn't excluding the most probable word make the text strange?
A.

It is excluded only in contexts with many candidates and high entropy. In contexts where the answer is nearly determined, the entropy is small and the information content of the high-probability word is close to it, so that word stays in the candidate set. In the paper's human evaluation (the average of criteria such as fluency and coherence), the method also scored on par with or above Nucleus and Top-k.

Q. What value of τ should I use?
A.

In the paper's preliminary experiments, τ=0.2\tau = 0.2 worked best for story generation and τ=0.95\tau = 0.95 for summarization. Since it varies greatly by task, choose it on validation data. The paper reports that changing τ\tau hardly changes the amount of repetition, making the method more robust to the choice of value than Top-k's kk or Nucleus's pp.

Q. When does it give the same result as Nucleus sampling?
A.

When the distribution is peaked and the entropy is small. In that case, higher-probability words tend to have information content closer to the entropy, so "closest to the entropy first" and "highest probability first" become nearly the same order. The paper also states that when entropy is low, the two methods yield the same candidates.

References

  1. C. Meister, T. Pimentel, G. Wiher, and R. Cotterell, "Locally Typical Sampling," Transactions of the Association for Computational Linguistics (TACL), vol. 11, 2023.
  2. A. Holtzman, J. Buys, L. Du, M. Forbes, and Y. Choi, "The Curious Case of Neural Text Degeneration," ICLR, 2020.