All courses

Top-k and nucleus (top-p) sampling

Truncate the distribution to the k most likely tokens, or to the smallest set covering probability p, then renormalize. Explain how cutting the unreliable low-probability tail avoids derailing tokens.

Builds on: Temperature

▶ Watch this lesson Start the whole course

What the animation says

The tail adds up

At every step, softmax gives all fifty thousand tokens some probability, never exactly zero. Say twenty sensible tokens hold ninety-five percent. The other fifty thousand share the last five. Each junk token is tiny. Together, they give every step a five percent chance of landing in the tail. And one junk token poisons the rest, because every later token is conditioned on it. So over a hundred tokens, what are the odds of at least one junk token?

Keep the head, cut the tail

Ninety-nine percent. A clean hundred-token run is under one percent likely. The head, the few tokens the model clearly favors, is where its estimates are trustworthy. The tail is a thin smear, there partly because softmax can't output zero. So keep the head, zero the rest, rescale the survivors to sum to one, then sample. Top-k keeps a fixed count. With k of two, A and B survive, summing to point seven. Divide by point seven: about point seven one and point two nine.

Top-p: cover the mass

Top-p, or nucleus sampling, doesn't fix a count. It fixes how much probability to cover. Sort tokens from most to least likely, and add them up as you go. Stop at the first token where the running sum reaches p. That's the kept set. Same five tokens. Running sums: point five, point seven, point eight five, point nine five, one. With p of point eight, tap the last token that top-p keeps.

Size adapts to confidence

C is the cutoff. Keep A, B and C; they sum to point eight five. Divide each by point eight five: about point five nine, point two four, point one eight. Now a confident step: one token at point nine two, a three percent runner-up, then crumbs. Top-p point eight stops at the first token. Only one survives, so it's greedy here. Top-k with k of two always keeps two. Does the three percent token get in?

Both rules in numpy

That three percent is the catch: a fixed k can't tell confident from unsure. Top-p adapts. In numpy, both rules fit in one function. This line sorts, most likely first. Top-k sets how many to keep. For top-p, this line finds where the running sum first reaches p. If both are given, the smaller kept set wins. Then zero the rest and divide by the sum. That's the same as setting cut logits to minus infinity and redoing softmax. Temperature usually comes first, then truncation, then sampling.

Why does plain sampling go off the rails?

At each step softmax gives every one of $V \approx 50{,}000$ tokens a nonzero probability. Suppose the 20 sensible tokens hold 95% and the other ~49,980 share the last 5%. Each junk token is negligible, but together they give each step a 5% chance of landing in that tail. Over 100 tokens that is $1-0.95^{100}\approx 99\%$ odds of at least one junk token, and every later token is conditioned on it. How do we keep variety but drop the junk?

Keep the head, cut the tail, rescale

The **head** is the few tokens the model clearly favors, and that is where its estimates are trustworthy. The **tail** is a thin smear over tens of thousands of tokens that rarely fit, and it exists partly because softmax cannot output exactly 0. Truncation keeps the head, zeroes the rest, rescales the survivors to sum to 1, then samples. **Top-k** keeps a fixed count. **Top-p (nucleus)** keeps as many as needed to cover mass $p$: few when the model is confident, many when it is unsure.

The truncation rule

Sort the next-token probabilities so that $s_1\ge s_2\ge\dots\ge s_V$. Choose a kept set $S$: - **top-k:** the $k$ largest. - **top-p:** the smallest $n$ with $\sum_{i=1}^{n}s_i\ge p$. $$q(v)=\frac{p_\theta(v\mid x_{\le t})}{\sum_{u\in S}p_\theta(u\mid x_{\le t})}\ (v\in S),\quad q(v)=0\ \text{otherwise}$$ This equals setting logits outside $S$ to $-\infty$ and taking softmax again. Temperature $\tau$ is usually applied to $z_t$ first, and top-k and top-p can be combined.

Five tokens, two rules

Probabilities for tokens A–E: $[0.50, 0.20, 0.15, 0.10, 0.05]$. **Top-k, k=2:** keep A and B, sum 0.70 → $0.714,\ 0.286$. **Top-p, p=0.8:** running sums are 0.50, 0.70, 0.85, so stop at C (the first sum ≥ 0.8). Divide by 0.85 → $0.588,\ 0.235,\ 0.176$. **Confident step** $[0.92, 0.03,\dots]$: top-p 0.8 keeps only the 0.92 token (greedy here). k=2 still admits the 0.03 token, at $0.03/0.95\approx 3\%$.

Top-k and top-p in numpy

Both rules fit in one function: sort, choose how many to keep, zero the rest, renormalize. When both are given, the smaller kept set wins. Then sample from the result with `np.random.default_rng().choice(len(q), p=q)`.
import numpy as np
def truncate(probs, k=None, top_p=None):
    idx = np.argsort(probs)[::-1]      # most likely first
    keep = len(probs) if k is None else k
    if top_p is not None:
        cum = np.cumsum(probs[idx])
        keep = min(keep, np.searchsorted(cum, top_p) + 1)
    q = np.zeros_like(probs); q[idx[:keep]] = probs[idx[:keep]]
    return q / q.sum()
probs = np.array([0.05, 0.50, 0.10, 0.20, 0.15])
print(truncate(probs, k=2))        # [0 .714 0 .286 0]
print(truncate(probs, top_p=0.8))  # [0 .588 0 .235 .176]

Remember this

Truncate, then renormalize. Top-k keeps the $k$ most likely tokens. Top-p keeps the smallest most-likely set whose probability reaches $p$, so its size adapts to the model's confidence. Every token outside the kept set gets probability exactly 0, so the long tail beyond the cutoff can never be sampled. Left in, a tail holding 5% of the mass is hit about once every 20 tokens, and each hit can derail the text. A poorly chosen cutoff can still let some junk in, as k=2 did with the 0.03 token.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.