Algorithmcore
Top-k sampling
Also called truncated sampling.
Keep only the k most probable next tokens, renormalize their probabilities and sample from them.
- Solves
- Autoregressive decoding
- Time
- O(V + k log k) worst
- Space
- O(V) extra
- Where
- V = the vocabulary size |V|; k = the number of kept tokens
- Model
- Real RAM
- Properties
- randomizednot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Angela Fan, Mike Lewis, Yann Dauphin, 2018
Top-k sampling generates text from an autoregressive language model one token at a time. At each step it keeps the most probable next tokens, sets the probability of every other token to 0, divides the kept probabilities by their sum, and draws the next token from that distribution. With it is greedy decoding; with it is plain ancestral sampling from the model. It is a heuristic method for autoregressive decoding: it does not look for the most probable text, and it does not sample from the model either. It cuts off the long tail of unlikely tokens, where a single bad draw can derail the text, and keeps the variety of sampling among the likely tokens. The value of is a setting that people tune by hand.
In plain words
The model gives a chance to every word that can come next. Most of these words are bad choices, but together they can hold a real share of the chance, so a plain random draw picks one of them now and then. Top-k sampling keeps only the best k words, for example the best 40. It forgets the others and draws at random among the kept ones, in proportion to their chances. Then it adds the word and repeats. A small k gives safe, plain text. A large k gives more varied text with more risk.
The problem
The model gives a distribution over the vocabulary for the prefix . Number the tokens . The task of one step is to choose at random. Top-k sampling draws from the truncated distribution
where is a set of tokens of largest probability. On ties at the boundary, the tokens with smaller indices are kept. The whole output is built by repeating the step until the end token </s> or a length limit, as in greedy decoding. The output distribution is not the model distribution , and no single sequence is the target; the method is defined by the rule itself.
The algorithm
The step takes and a number drawn uniformly from . In practice comes from the logits by a softmax, often with a temperature (temperature sampling); since dividing by keeps the order of the logits, is the same for every .
TOP-K-SAMPLE(p, k, u) ▷ p = next-token distribution, u uniform in [0, 1)- 1
order ← the tokens sorted by p, from high to low ▷ ties: the smaller index first - 2
K ← the first min(k, |V|) tokens of order - 3
Z ← sum of p[i] over i in K - 4
r ← u · Z - 5
c ← 0 - 6
for each i in K, in the order of L1 do - 7
c ← c + p[i] - 8
if r < c then return i - 9
return the last i in K with p[i] > 0 ▷ only if u · Z rounded up to Z
Lines L4 to L8 are inverse transform sampling on the kept tokens. The bound multiplies , so the renormalized distribution is never written down and nothing is divided. A token of probability 0 has an empty interval and is never returned.
Example
Take six next tokens with = (the 0.40, a 0.25, cat 0.15, dog 0.10, sat 0.06, ran 0.04). They are already sorted.
| kept | renormalized | ||
|---|---|---|---|
| 1 | the | 0.40 | the 1 |
| 2 | the, a | 0.65 | the 8/13 = 0.6154, a 5/13 = 0.3846 |
| 3 | the, a, cat | 0.80 | the 1/2, a 5/16 = 0.3125, cat 3/16 = 0.1875 |
| 6 | all | 1 | itself |
With and , line L4 gives . The running sum is 0.40 after "the", which is not above 0.48, and 0.65 after "a", which is. So the step returns "a". In terms of , the token "the" wins for , "a" for , and "cat" for .
The weak point shows with on two other steps. On a peaked step, = (0.90, 0.05, 0.03, 0.02), top-3 still keeps a token of probability 0.03 and gives it . On a flat step with ten tokens of 0.1 each, top-3 drops 70% of the mass and keeps three tokens that are no better than the other seven. A fixed is too large for the first step and too small for the second; nucleus sampling adapts the size of the set to the shape of .
Correctness
The proof is in proofs/correctness.md. It shows that the kept set has the largest total probability of all sets of tokens, by an exchange argument, and that the step returns each kept token with probability exactly and never returns a dropped token or a token of probability 0. The special cases follow: returns the first most probable token, and samples from . The tests check the maximum mass against all subsets on random distributions, and check the draw exactly with Fraction probabilities and on a fine grid.
Proof: Top-k sampling keeps a set of maximum mass and draws from the renormalized distributionfull
We use the notation of the page. The input is a distribution over the vocabulary , an integer , and a number drawn uniformly from . Let . We assume exact arithmetic, as with the Fractions of the tests; the last remark treats rounding.
Lemma 1 (the kept set). Line L1 sorts the indices by the key , and line L2 keeps the first of them. The kept set has elements, every kept token has a probability at least as large as every dropped token, and among the tokens with the same probability as the least probable kept token, the kept ones have the smaller indices.
Proof. The key is distinct for distinct , so the sorted order is unique, whatever sort algorithm runs. A token comes before a token exactly when , or and . The first positions therefore hold tokens whose probabilities are at least the probability of every later token, and on a tie at the boundary the smaller indices come first.
Theorem 2 (maximum mass). Among all sets with , the kept set has the largest mass .
Proof. Let be any set of size with . Then there are and , and by Lemma 1. The set has size , its mass is at least the mass of , and it has one more element in common with . Repeat until the set is . The mass never goes down, so the mass of is at least the mass of .
So top-k keeps the tokens of largest mass. Theorem 2 only says that the set is best for its size; whether tokens is a good size is a separate question, which nucleus sampling answers with a mass threshold.
Theorem 3 (the draw). Let . TOP-K-SAMPLE returns each with probability , and returns no token outside and no token with .
Proof. Write the kept tokens in sorted order as , and let and , so . Line L4 sets , which is uniform on . The loop of lines L6 to L8 returns for the first with . Since the do not decrease and , such a exists, and it is the unique with . The interval has length , so the probability of returning is . If , the interval is empty and is never returned. Line L9 is not reached.
This is inverse transform sampling on the renormalized distribution for and otherwise, but with the bound moved to the random number: comparing with is the same as comparing with , and no division is needed. The tests check Theorem 3 exactly: with on the grid and Fraction probabilities, the share of grid points that return each token equals .
Corollary 4 (special cases). With the kept set is the first index of a largest probability, and the draw returns it with probability 1, which is greedy decoding of one step. With , the kept set is all of , , and the draw is a sample from itself.
Proof. Both follow from Lemma 1 and Theorem 3.
Remark (rounding). With floats, the sum of line L3 and the running sum of line L7 can differ in the last bits, because two ways of adding the same numbers can round differently, and the product of line L4 can round up to when is very close to 1. Then can be at least , and no has . Line L9 returns the last kept token of positive probability in that case. The event has probability of the order of the rounding error, and it does not change which tokens can be drawn.
Complexity
One step reads probabilities. A full sort costs . Only the largest are needed, in order: a selection in linear time followed by a sort of the kept values costs , and a min-heap of size costs . The draw itself is . The extra space is for the scores, or beyond them with the heap. On a GPU, frameworks use a parallel top-k kernel. For a large model the call of the network costs far more than any of this.
Properties
- Randomized. The same prefix can give different tokens. Fix the seed of the random source to reproduce an output.
- Not the model distribution. For the output distribution differs from . Tokens outside the top at some step can never appear there.
- Maximum mass for its size. The kept set holds the most probability of any set of tokens.
- Order only. The kept set depends only on the order of the probabilities, so it is the same for every temperature and for the logits or the probabilities.
- Limits. is greedy decoding, and is ancestral sampling.
- Online. Each token is final when it is drawn.
Variants and improvements
- Top-k with temperature. Apply the temperature to the logits, then truncate. Holtzman et al. 2020 report top-k = 40 with as one of their baselines.
- Nucleus sampling. Keep the smallest set whose mass reaches in place of a fixed count (nucleus sampling). Libraries often apply both: first top-k, then top-p.
- Typical sampling. Keep the tokens whose surprisal is closest to the entropy of the step (typical sampling).
- Contrastive search. Take the top candidates, but choose among them by a score with a penalty for similarity to the context, without randomness (contrastive search).
- Gumbel top-k. Adding Gumbel noise to the log probabilities and taking the largest draws tokens without replacement (Gumbel-max trick, stochastic beam search). This draws several tokens at once; it is not the same as top-k sampling.
When to use it
Use top-k sampling for open-ended text, such as stories and dialogue, where varied output is wanted and the most probable text tends to be dull and repetitive. A value of between 10 and 100 is common. Prefer nucleus sampling when the shape of the distribution changes a lot from step to step, which is the usual case. Use greedy decoding or beam search when a single correct answer is wanted, as in translation or short factual answers.
Pitfalls
- One for all steps. The same keeps bad tokens on peaked steps and drops good ones on flat steps (the example above).
- Ties at the boundary. With equal probabilities at position , the kept set depends on the tie rule. Fix it if outputs must be reproducible.
- Order of the filters. Top-k then top-p is not the same as top-p then top-k with renormalization in between, and libraries differ. State the order.
- Temperature does not change the set. People sometimes expect a high temperature to let more tokens in; with top-k it only changes the weights inside the fixed set.
- Repetition is not fixed. Truncation lowers the chance of bad tokens but does not stop loops; a repetition penalty is a separate tool.
Implementations
The code takes the next-token probabilities (or logits) as given and implements the truncation and the draw; it does not run or train a network.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
top_k_sampling.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-k-sampling/. The authors are listed in prov/CNGCHZ.jsonl.
"""Top-k sampling of the next token.
A next-token distribution is a list p of probabilities, one per token of the
vocabulary, in the order of the vocabulary. The values can be floats or
Fractions; with Fractions the distribution functions are exact. The random
source is any object with a random() method that returns u in [0, 1), such
as random.Random(seed). The code takes the probabilities of the model as
given; it does not run or train a network.
"""
from typing import List, Sequence
from nlslog import softmax
def top_k_set(probs: Sequence, k: int) -> List[int]:
"""Return the indices of the min(k, |V|) most probable tokens.
The list is sorted by probability from high to low. On ties the smaller
index comes first, so the result does not depend on the sort algorithm.
"""
if k < 1:
raise ValueError("k must be at least 1")
order = sorted(range(len(probs)), key=lambda i: (-probs[i], i)) # @line L1
return order[: min(k, len(probs))] # @line L2
def top_k_distribution(probs: Sequence, k: int) -> list:
"""Return the truncated and renormalized distribution q of top-k sampling.
q[i] = p[i] / Z for the kept tokens, where Z is their total mass, and 0
for the others. Raise ValueError if the kept mass is 0.
"""
kept = top_k_set(probs, k)
z = sum(probs[i] for i in kept)
if not z > 0:
raise ValueError("the kept tokens have no mass")
q = [probs[i] * 0 for i in range(len(probs))]
for i in kept:
q[i] = probs[i] / z
return q
def top_k_sample(probs: Sequence, k: int, rng) -> int:
"""Draw one token index from the top-k distribution of probs.
The draw is inverse transform sampling over the kept tokens in sorted
order: r = u Z, and the first index whose running sum exceeds r wins.
Nothing is divided, and a token of probability 0 is never returned.
"""
kept = top_k_set(probs, k) # @line L1
z = sum(probs[i] for i in kept) # @line L3
if not z > 0:
raise ValueError("the kept tokens have no mass")
r = rng.random() * z # @line L4
c = probs[kept[0]] * 0 # @line L5
for i in kept: # @line L6
c = c + probs[i] # @line L7
if r < c: # @line L8
return i
return [i for i in kept if probs[i] > 0][-1] # @line L9
def top_k_sample_logits(logits: Sequence[float], k: int, rng, temperature: float = 1.0) -> int:
"""Top-k sampling from logits: softmax with the temperature, then top_k_sample.
The kept set is the same for every temperature, because dividing by a
positive T keeps the order of the logits.
"""
return top_k_sample(softmax(logits, temperature), k, rng)
test_top_k_sampling.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/top-k-sampling/. The authors are listed in prov/CNGCHZ.jsonl.
import itertools
import random
from fractions import Fraction as F
from nlslog import argmax, softmax
from top_k_sampling import top_k_distribution, top_k_sample, top_k_sample_logits, top_k_set
# the, a, cat, dog, sat, ran
P = [F(2, 5), F(1, 4), F(3, 20), F(1, 10), F(3, 50), F(1, 25)]
class GridU:
"""A fake random source that returns the points j / n, j = 0 ... n - 1, in turn."""
def __init__(self, n):
self.n = n
self.j = 0
def random(self):
u = F(self.j, self.n)
self.j += 1
return u
def random_fractions(rng, n):
w = [rng.randint(0, 9) for _ in range(n)]
if sum(w) == 0:
w[0] = 1
return [F(x, sum(w)) for x in w]
def test_example_values() -> None:
assert top_k_set(P, 1) == [0]
assert top_k_distribution(P, 2) == [F(8, 13), F(5, 13), 0, 0, 0, 0]
assert top_k_distribution(P, 3) == [F(1, 2), F(5, 16), F(3, 16), 0, 0, 0]
assert top_k_distribution(P, 6) == P
assert top_k_distribution(P, 100) == P
def test_kept_set_has_maximum_mass_brute_force() -> None:
rng = random.Random(1)
for _ in range(300):
n = rng.randint(1, 7)
p = random_fractions(rng, n)
for k in range(1, n + 2):
kept = top_k_set(p, k)
m = min(k, n)
assert len(kept) == m and len(set(kept)) == m
best = max(sum(p[i] for i in c) for c in itertools.combinations(range(n), m))
assert sum(p[i] for i in kept) == best
# every kept token is at least as probable as every dropped one
dropped = [i for i in range(n) if i not in kept]
if dropped:
assert min(p[i] for i in kept) >= max(p[i] for i in dropped)
def test_tie_rule_smaller_index_first() -> None:
p = [F(1, 10), F(3, 10), F(3, 10), F(3, 10)]
assert top_k_set(p, 2) == [1, 2]
assert top_k_set(p, 3) == [1, 2, 3]
def test_inverse_transform_is_exact_on_a_grid() -> None:
n = 1600
for k, q in ((2, top_k_distribution(P, 2)), (3, top_k_distribution(P, 3))):
src = GridU(n * 13)
counts = [0] * len(P)
for _ in range(n * 13):
counts[top_k_sample(P, k, src)] += 1
assert [F(c, n * 13) for c in counts] == q
def test_k_equal_one_is_greedy() -> None:
rng = random.Random(2)
for _ in range(200):
p = [rng.random() for _ in range(5)]
assert top_k_sample(p, 1, rng) == argmax(p)
def test_sampling_frequencies() -> None:
rng = random.Random(3)
probs = [float(x) for x in P]
draws = 20000
counts = [0] * len(P)
for _ in range(draws):
counts[top_k_sample(probs, 3, rng)] += 1
expected = [0.5, 0.3125, 0.1875, 0.0, 0.0, 0.0]
for c, e in zip(counts, expected):
assert abs(c / draws - e) < 0.01
assert counts[3:] == [0, 0, 0]
def test_zero_mass_token_is_never_drawn() -> None:
rng = random.Random(4)
p = [0.5, 0.0, 0.5, 0.0]
assert top_k_set(p, 3) == [0, 2, 1]
seen = {top_k_sample(p, 3, rng) for _ in range(2000)}
assert seen == {0, 2}
def test_kept_set_does_not_depend_on_temperature() -> None:
rng = random.Random(5)
for _ in range(100):
z = [rng.uniform(-5, 5) for _ in range(8)]
sets = [top_k_set(softmax(z, t), 3) for t in (0.5, 1.0, 2.0)]
assert sets[0] == sets[1] == sets[2]
assert top_k_sample_logits([2.0, 1.0, 0.0], 1, rng, temperature=3.0) == 0
def test_bad_arguments() -> None:
for bad in (lambda: top_k_set(P, 0), lambda: top_k_distribution([0, 0], 1)):
try:
bad()
except ValueError:
pass
else:
raise AssertionError("no ValueError")
History
Fan, Lewis and Dauphin 2018 used top-k random sampling with to generate stories on their WritingPrompts dataset, because beam search tended to produce common phrases and repetitive text. Top-k sampling then became a standard way to generate text with large language models. Holtzman et al. 2020 measured its weak point, the fixed size of the set, and proposed nucleus sampling, which adapts the size to the distribution.
References
- Angela Fan, Mike Lewis and Yann Dauphin, Hierarchical neural story generation, ACL 2018, pages 889 to 898, Section 5.4 (Generation), top-k random sampling from the k = 10 most likely candidates, and the note that beam search gives common phrases and repetitive text
- Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes and Yejin Choi, The curious case of neural text degeneration, ICLR 2020, Section 3.2 (top-k sampling as the size-k set of largest mass) and Table 1 (top-k = 40 and top-k = 640 against nucleus sampling on GPT-2 Large)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CNGCHZ Edit this page History Report an error Markdown