Algorithmintro
Greedy decoding
Also called argmax decoding.
At each step emit the single most probable next token, until an end token. Fast, but its output can be far less probable than the most probable sequence.
- Solves
- Autoregressive decoding
- Time
- O(n (C + V)) worst
- Space
- O(n + V) extra
- Where
- C = the cost of one call of the model; V = the vocabulary size |V|; n = the number of output tokens
- Model
- Word RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
Greedy decoding turns an autoregressive language model into a generator: at each step it appends the single most probable next token, and it stops when it emits the end token </s>. It makes one call of the model per output token, so it is the cheapest search for a likely output. It is a heuristic for the autoregressive decoding problem: the product of locally best choices can be much less probable than the most probable whole sequence, and the page gives a model where the ratio is as small as you like.
In plain words
The model reads the words so far and gives a score to every word that can come next. Greedy decoding takes the word with the best score, adds it to the text, and asks again. It stops when the model chooses the end mark. It never goes back. So a first word that looks good can lead into a text that is bad as a whole, and the decoder cannot fix that.
The problem
A model gives, for every prefix , a distribution over a vocabulary that contains </s>. For a conditional model the input is fixed and is left out of the notation. An output is a sequence that ends with </s> and has no </s> before it. Its probability is the product of the conditionals,
All logs are natural logs. The decoding problem asks for among the outputs of at most tokens. Greedy decoding does not solve that problem exactly. It returns the output that the greedy rule defines: at every step, with a fixed tie rule.
The algorithm
The model is a function that takes a prefix and returns for every . The limit stops a model that never chooses </s>.
GREEDY-DECODE(model, N) ▷ model(y) = log p(· | y), N = the most tokens to emity ← empty sequence- 1
s ← 0 - 2
for t ← 1 to N do - 3
ℓ ← model(y) ▷ one call, |V| log probabilities - 4
w ← argmax over v of ℓ[v] ▷ ties: the first token in the order of V - 5
append w to y, s ← s + ℓ[w] - 6
if w = "</s>" then return (y, s) - 7
return (y, s) ▷ no "</s>" within N tokens: an unfinished output
The score is a sum of logs. A product of a few hundred probabilities underflows to 0 in double precision, and the sum does not.
Example
Take the model M1 over :
| prefix | |||
|---|---|---|---|
| empty | 0.5 | 0.4 | 0.1 |
| a | 0.4 | 0.3 | 0.3 |
| b | 0.05 | 0.05 | 0.9 |
| any longer prefix | 0 | 0 | 1 |
It has seven outputs: </s> (0.1), a</s> (0.15), aa</s> (0.2), ab</s> (0.15), b</s> (0.36), ba</s> (0.02) and bb</s> (0.02). They sum to 1.
Greedy decoding chooses a (0.5 against 0.4), then a again (0.4), then </s> (1). It returns aa</s> with probability , or . The most probable output is b</s>, with . The first step chose a because a has more mass in total, but that mass is spread over three continuations, while the mass of b is nearly all on one. A beam search of width 2 keeps a and b after step 1. At step 2 the two best of the six extensions are b</s> (, finished) and aa (), so it finds b</s>.
Correctness
The proof is in proofs/correctness.md. It shows three things. The decoder stops after at most calls. The output satisfies the greedy rule at every step and its score is its exact log probability. And no constant bounds the ratio between the probability of the mode and the probability of the greedy output (a theorem): with and at the first step, an output b</s> of probability , and uniform steps over 4 tokens after a, the greedy output has probability . The test checks and , where the ratio is below 0.001.
So greedy decoding is a heuristic for the mode. The tests compare it with exhaustive search over all outputs of up to 5 tokens on 200 random models with 4 tokens: the greedy output never scores more than the best, and it is worse than the best on some models.
Proof: Greedy decoding follows the greedy rule and has no constant approximation ratiofull
We use the notation of the page. The model gives for every prefix and every token , where contains </s>. All logs are natural logs. An output is a sequence that ends with </s> and has no </s> before it. The decoder gets a limit .
Lemma 1 (termination). GREEDY-DECODE makes at most calls of the model and returns a sequence of at most tokens.
Proof. The loop of line L2 runs at most times, and each pass makes one call (line L3) and appends one token (line L5).
Lemma 2 (the greedy rule and the score). Let be the result, with . Then for every , is the first token in the order of among those with the largest value of . Only can be </s>. If = </s>, then is an output; otherwise . In both cases .
Proof. By induction on the passes of the loop, the invariant at the start of pass is: holds no </s>, each with satisfies the greedy rule, and . It holds before the first pass, with the empty prefix and (line L1). In pass , line L3 gets , and the argmax of line L4 returns the first index of a largest value (the helper scans in order and replaces the best only on a strictly larger value), so satisfies the rule. Line L5 adds to . If = </s>, line L6 returns, and ends with its first </s>, so it is an output. Otherwise the invariant holds for pass . If the loop ends without a return, and no token is </s>.
So the returned score is the exact log probability of the returned sequence under the model, apart from rounding of the additions.
Theorem 3 (no constant ratio). For every there is a model on 5 tokens whose greedy output and whose most probable output satisfy .
Proof. Take , a number and an integer . At the empty prefix, , and the other tokens have probability 0. After the prefix b, </s> has probability 1. After a prefix that starts with a and has at most tokens, each of a, b, c and d has probability and </s> has probability 0. After a longer prefix, </s> has probability 1.
At the first step the largest probability is , so . After that, every prefix of length at most that starts with a has four tied tokens of probability , so the greedy output takes more tokens and then </s>, and . Every output that starts with a has this same probability, and the output b</s> has probability . So and
Choose and with .
With and , the bound is ; the test checks that the ratio is below 0.001. The construction uses the fact that the greedy rule compares the next-token probabilities only. The mass of the prefix a is spread over continuations, while the mass of b is on one continuation.
Corollary 4. Greedy decoding is not an exact algorithm for the decoding problem and has no constant approximation ratio for it. This follows from Theorem 3. Lemma 2 only says that the output is the one that the greedy rule defines, and the tests compare it with exhaustive search for that reason.
Complexity
Each step makes one call of the model, of cost , and one pass over scores for the argmax. For an output of tokens the time is in the word RAM, with each score as one word. For a transformer the call is the main cost. Without a cache, step runs the network on all tokens; with a key-value cache it runs it on the new token only. The extra space is the output and one row of scores, , plus the cache if there is one.
Exhaustive search over outputs of at most tokens makes calls, which grows exponentially in .
Properties
- Deterministic. The same model and the same tie rule give the same output.
- Not exact. The output can be far less probable than the mode (the theorem above).
- Online. It emits each token when it chooses it, so a streaming interface can show the text as it grows.
- Beam search of width 1. Greedy decoding is the special case of beam search, and the limit of temperature sampling as the temperature goes to 0.
- Repetition. With trained models, greedy output often falls into loops that repeat a phrase. This is a measured behavior of trained models, not a property of the algorithm; repetition penalty and sampling are common fixes.
Variants and improvements
- Beam search. Keep the best prefixes in place of one (beam search). It costs about times as much and finds more probable outputs, but it is still not exact.
- Sampling. Draw the next token from or from a truncated (temperature sampling, top-k sampling, nucleus sampling) to get varied text.
- Contrastive search. Score the top candidates by probability minus a similarity penalty against the context (contrastive search).
- Speculative decoding. A small model proposes several tokens and the large model checks them in one call. With greedy acceptance the output is the same as greedy decoding of the large model, in fewer large calls (speculative decoding).
- Constrained greedy decoding. Mask the tokens that a grammar does not allow before the argmax (grammar-constrained decoding).
When to use it
Use greedy decoding when a single short answer is needed and latency matters, for example a classification label, a short extraction, or a first baseline. It is also the usual choice for code and math answers where the model is confident at most steps. Use beam search for translation and speech recognition, where a more probable output is usually a better one, and sampling for open-ended text, where the most probable text is often dull or repetitive.
Pitfalls
- No end token. A model can loop without choosing
</s>. Always pass a limit , and treat an output without</s>as unfinished. - Ties. Two tokens with the same score give different outputs under different tie rules. Fix the rule (here, the first token in the order of ) if outputs must be reproducible. On a GPU, small differences in the order of floating-point sums can change which token is the largest.
- Products of probabilities. Multiplying probabilities underflows on long outputs. Add log probabilities.
- A greedy output is not the mode. Do not call the greedy output "the most likely output" of the model; the example above shows the difference.
Implementations
The code takes the log probabilities of the model as given, as a function of the prefix, and implements the decoder around them; 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
# Part of https://algorithm.tamnd.com/greedy-decoding/. The authors are listed in prov/61Q9XF.jsonl.
"""Greedy decoding of an autoregressive model.
A model is a function that takes the prefix y_1 ... y_t (a tuple of strings)
and returns a dict from each token of the vocabulary to log p(w | prefix),
in natural log. The end token is the string "</s>". The input x of a
conditional model is fixed inside the function. The code takes these log
probabilities as given; it does not run or train a network.
"""
from typing import Callable, Dict, List, Tuple
from nlslog import argmax
EOS = "</s>"
Model = Callable[[Tuple[str, ...]], Dict[str, float]]
def greedy_decode(model: Model, max_len: int) -> Tuple[List[str], float]:
"""Return (tokens, log probability) of the greedy output.
At each step the decoder appends the most probable next token (the first
one in the order of the dict, on ties) and stops after "</s>". If no
"</s>" comes within max_len tokens, the unfinished prefix of max_len
tokens is returned with its log probability.
"""
if max_len < 1:
raise ValueError("max_len must be at least 1")
y: List[str] = []
score = 0.0 # @line L1
for _ in range(max_len): # @line L2
logp = model(tuple(y)) # @line L3
tokens = list(logp)
w = tokens[argmax([logp[t] for t in tokens])] # @line L4
y.append(w)
score += logp[w] # @line L5
if w == EOS: # @line L6
return y, score
return y, score # @line L7
nlslog.py 152 lines
# 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
test_greedy_decoding.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-decoding/. The authors are listed in prov/61Q9XF.jsonl.
import math
import random
from greedy_decoding import EOS, greedy_decode
from nlslog import NEG_INF, log_normalize, safe_log
M1 = {
(): {"a": 0.5, "b": 0.4, EOS: 0.1},
("a",): {"a": 0.4, "b": 0.3, EOS: 0.3},
("b",): {"a": 0.05, "b": 0.05, EOS: 0.9},
}
def m1(prefix):
probs = M1.get(tuple(prefix), {"a": 0.0, "b": 0.0, EOS: 1.0})
return {w: safe_log(p) for w, p in probs.items()}
def random_model(seed, vocab, n):
"""A model whose outputs have at most n tokens: "</s>" is forced at position n."""
def model(prefix):
if len(prefix) >= n - 1:
return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
rng = random.Random(f"{seed}|{' '.join(prefix)}")
raw = [math.log(rng.random() ** 2 + 1e-3) for _ in vocab]
return dict(zip(vocab, log_normalize(raw)))
return model
def exhaustive(model, n):
"""Every output of at most n tokens that ends with "</s>", with its log probability."""
out = []
def rec(prefix, s):
for w, lp in model(tuple(prefix)).items():
if lp == NEG_INF:
continue
if w == EOS:
out.append((prefix + [w], s + lp))
elif len(prefix) + 1 < n:
rec(prefix + [w], s + lp)
rec([], 0.0)
return out
def test_example_greedy_misses_the_mode() -> None:
y, s = greedy_decode(m1, 3)
assert y == ["a", "a", EOS]
assert math.isclose(math.exp(s), 0.2)
best = max(exhaustive(m1, 3), key=lambda t: t[1])
assert best[0] == ["b", EOS]
assert math.isclose(math.exp(best[1]), 0.36)
total = math.fsum(math.exp(s) for _, s in exhaustive(m1, 3))
assert math.isclose(total, 1.0)
def test_follows_the_greedy_rule() -> None:
vocab = ["a", "b", "c", EOS]
for seed in range(200):
model = random_model(seed, vocab, 5)
y, s = greedy_decode(model, 5)
assert y[-1] == EOS and EOS not in y[:-1]
total = 0.0
for t, w in enumerate(y):
logp = model(tuple(y[:t]))
assert logp[w] == max(logp.values())
total += logp[w]
assert math.isclose(s, total)
def test_against_exhaustive_search() -> None:
vocab = ["a", "b", "c", EOS]
misses = 0
for seed in range(200):
model = random_model(seed, vocab, 5)
y, s = greedy_decode(model, 5)
outputs = exhaustive(model, 5)
best = max(sc for _, sc in outputs)
assert s <= best + 1e-12
assert any(o == y and math.isclose(sc, s) for o, sc in outputs)
if s < best - 1e-12:
misses += 1
assert 0 < misses < 200
def test_ratio_can_be_tiny() -> None:
# p(a) = 1/2 + delta, p(b) = 1/2 - delta; after b the output ends, after a
# it runs on through L uniform steps over 4 tokens.
delta, length = 0.01, 6
vocab = ["a", "b", "c", "d", EOS]
def model(prefix):
if not prefix:
return {"a": math.log(0.5 + delta), "b": math.log(0.5 - delta), "c": NEG_INF, "d": NEG_INF, EOS: NEG_INF}
if prefix == ("b",) or len(prefix) > length:
return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
return {w: (NEG_INF if w == EOS else math.log(0.25)) for w in vocab}
y, s = greedy_decode(model, length + 2)
assert y[0] == "a"
assert math.isclose(math.exp(s), (0.5 + delta) * 0.25 ** length)
assert math.exp(s) / (0.5 - delta) < 0.001
def test_no_end_token_within_the_limit() -> None:
def model(prefix):
return {"a": math.log(0.9), EOS: math.log(0.1)}
y, s = greedy_decode(model, 4)
assert y == ["a", "a", "a", "a"]
assert math.isclose(s, 4 * math.log(0.9))
def test_ties_take_the_first_token() -> None:
def model(prefix):
if prefix:
return {"x": NEG_INF, "y": NEG_INF, EOS: 0.0}
return {"x": math.log(0.5), "y": math.log(0.5), EOS: NEG_INF}
assert greedy_decode(model, 3)[0] == ["x", EOS]
def test_log_space_does_not_underflow() -> None:
vocab = ["a", "b", "c", "d", "e", EOS]
probs = [0.25, 0.175, 0.175, 0.175, 0.175, 0.05]
steps = 600
def model(prefix):
if len(prefix) >= steps:
return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
return {w: math.log(p) for w, p in zip(vocab, probs)}
y, s = greedy_decode(model, steps + 1)
assert y == ["a"] * steps + [EOS]
assert math.prod([0.25] * steps) == 0.0
assert math.isclose(s, steps * math.log(0.25))
History
Greedy search is the oldest and simplest way to decode a sequence model and has no single inventor. In neural translation it became the baseline against which beam search is measured. Stahlberg and Byrne 2019 ran exact search on a trained translation model and measured how far greedy and beam search are from the mode (see inadequacy of the mode).
References
- Felix Stahlberg and Bill Byrne, On NMT search errors and model errors, cat got your tongue?, EMNLP-IJCNLP 2019, pages 3356 to 3362, the comparison of greedy search and beam search with exact search on a trained translation model
- Clara Meister, Ryan Cotterell and Tim Vieira, If beam search is the answer, what was the question?, EMNLP 2020, pages 2173 to 2185, the definition of decoding as the search for the most probable output, and beam search with width 1 as greedy search
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 61Q9XF Edit this page History Report an error Markdown