AI Wiki中文/EN

Beam search: pruning a sequence frontier

束搜索

Trace sequence probabilities, EOS and pruning; execute a case where a wider beam returns a worse answer.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Keep several unfinished sentences

A decoder assigns probability 0.6 to starting with A and 0.4 to starting with B. Greedy decoding chooses A. Suppose A then has two equally likely continuations, while B ends with certainty. The best complete B sequence has probability 0.4; either complete A sequence has probability 0.3. The most likely first choice has hidden the most likely whole answer.

Beam search delays that commitment. It keeps up to BB candidates, extends the unfinished ones by one token, ranks the combined pool, and discards the rest. The width BB limits how many alternatives survive a round. A discarded prefix loses all its future continuations, even if one would eventually win.

The word beam names a family of procedures. This article implements sequence decoding with a bounded frontier. Local beam search instead pools neighboring complete configurations, such as several arrangements of queens, and keeps the best configurations for the next iteration. It shares candidates across the population, unlike independent hill-climbing runs. Berkeley presents that variant separately. CS188, section 1.5.3

Greedy best-first graph search makes another choice: it expands the most promising item in a priority queue whose entries can have different depths. Our decoder advances every live prefix by one token per round and then applies a width limit. These distinctions matter when comparing guarantees, memory, and stopping rules.

Define the score and the meaning of finished

Fix the input xx, a finite vocabulary including the end token EOS, and a maximum generated length LL. Length includes EOS. An empty visible answer can therefore be represented by the one-token sequence (EOS,). The initial empty prefix has probability 1. A full sequence ends at its first EOS and never expands afterward. Its autoregressive score uses the entire preceding prefix:

P(y∣x)=∏t=1∣y∣p(yt∣x,y<t),s(y)=∑t=1∣y∣log⁡p(yt∣x,y<t).P(y\mid x)=\prod_{t=1}^{|y|}p(y_t\mid x,y_{<t}),\qquad s(y)=\sum_{t=1}^{|y|}\log p(y_t\mid x,y_{<t}).

The desired answer maximizes s(y)s(y) among complete sequences of at most LL tokens. Zero-probability transitions are excluded. Using logarithms replaces repeated multiplication with addition and avoids the ordinary underflow caused by multiplying many small probabilities. Logarithms do not correct a poorly estimated model.

Because each conditional probability is at most 1, a prefix bounds its descendants:

s(y∘z)=s(y)+∑jlog⁡p(zj∣x,y,z<j)≤s(y).s(y\circ z)=s(y)+\sum_j\log p(z_j\mid x,y,z_{<j})\le s(y).

Here ∘\circ means concatenation. A completed hypothesis scoring at least as well as every live prefix cannot be beaten by extensions of those live prefixes. This certificate says nothing about branches already discarded. Huang, Zhao and Ma formulate a stopping guarantee with precisely a beam-size qualification; they also explain why length rewards require a different bound. Huang et al., sections 2–4

Our teaching variant reserves no separate quota of live candidates. A previously retained completion can occupy a beam slot. We also archive the best retained completion and let it compete again in each round. The rules are:

  1. Start with the empty prefix, score 0.
  2. Expand every live prefix using every positive-probability token. Add the archived completion, if any, to the same candidate pool.
  3. Retain the top BB items. Update the archive using completions that survived this selection. Exact floating-point score ties use the lexicographic order of token tuples.
  4. Stop when all retained items have EOS or after LL rounds. Return the archive if one exists; otherwise return the best retained prefix with status truncated.

Only the best archived completion is needed: under this raw score, another complete sequence with a worse score cannot become preferable later. In exact arithmetic, recording only completions that survive selection makes B=1B=1 follow greedy decoding, including greedy’s decision to emit EOS. Recording every generated EOS before pruning would define a different algorithm. In the floating-point implementation, adding a common prefix score can round slightly different log probabilities to the same value. The lexicographic tie rule may then differ from choosing the largest local probability, even at width 1. The mathematical score guarantees do not remove this numerical limit.

In exact arithmetic, with enough width that no generated candidate, including a newly completed EOS hypothesis, is pruned by the width selection, this finite enumeration finds the highest-scoring complete sequence within the length cap. Protecting only live prefixes is insufficient: a model assigning 0.6 to x and 0.4 to EOS at every prefix has just one live continuation, yet width 1 discards every generated EOS. With a length cap of 2 it returns a truncated prefix, despite the immediate EOS being a valid completion of probability 0.4. A fixed small beam gives no such guarantee. Model-score optimality is itself narrower than factual correctness, good translation, or usefulness to a reader.

A decoder whose choices can be checked by hand

The complete program below uses Python’s standard library. model(prefix) must deterministically return a nonempty dictionary of token strings to finite numeric probabilities in [0,1][0,1]. Only queried rows are validated. The row sum may differ from 1 by at most 10−1210^{-12} for rounding; the program divides by that sum before taking logarithms. It rejects larger errors and skips zeros. The toy tables provide EOS with probability 1 at every unlisted prefix.

max_length=0 permits no generation: the result is the empty, truncated prefix. A missing EOS does not silently turn the length cap into an end token. hit_limit records whether any live candidates remained when the loop ended; a returned complete sequence can coexist with such unfinished alternatives. The function implements the stated rules, including the completion archive, rather than a production library’s undocumented defaults.

from math import exp, fsum, isclose, isfinite, log

EOS = '<eos>'

def beam_search(model, width=2, max_length=8):
    # model(prefix) is a deterministic dict: token string -> int/float probability.
    if type(width) is not int or width < 1:
        raise ValueError('width must be a positive integer')
    if type(max_length) is not int or max_length < 0:
        raise ValueError('max_length must be a nonnegative integer')
    def rank(item):
        tokens, score = item
        return -score, tokens  # Higher score first; exact float ties lexicographic.
    def completed(item):
        return bool(item[0]) and item[0][-1] == EOS
    beam, best_done = [((), 0.0)], None
    for _ in range(max_length):
        # One archived completion competes for a slot, even if pruned earlier.
        candidates = [] if best_done is None else [best_done]
        for prefix, score in beam:
            if prefix and prefix[-1] == EOS:
                continue
            row = model(prefix)
            if not isinstance(row, dict) or not row:
                raise ValueError('model must return a nonempty probability dict')
            for token, probability in row.items():
                if not isinstance(token, str) or not token:
                    raise ValueError('tokens must be nonempty strings')
                if (type(probability) not in (int, float)
                        or not 0 <= probability <= 1 or not isfinite(probability)):
                    raise ValueError('probabilities must be finite numbers in [0, 1]')
            total = fsum(row.values())
            if not isclose(total, 1.0, rel_tol=0.0, abs_tol=1e-12):
                raise ValueError('probabilities must sum to one')
            for token, probability in row.items():
                if probability > 0:
                    candidates.append((prefix+(token,), score+log(probability/total)))
        beam = sorted(candidates, key=rank)[:width]
        for item in beam:
            if completed(item) and (best_done is None or rank(item) < rank(best_done)):
                best_done = item
        if all(completed(item) for item in beam):
            break
    answer = best_done if best_done is not None else beam[0]
    return {'tokens': answer[0], 'log_probability': answer[1],
            'status': 'complete' if completed(answer) else 'truncated',
            'hit_limit': any(not completed(item) for item in beam)}

# Unlisted prefixes end immediately. These are toy models, not trained networks.
def table_model(table):
    return lambda prefix: table.get(prefix, {EOS: 1.0})

greedy_trap = table_model({(): {'A': .6, 'B': .4},
                           ('A',): {EOS: .5, 'x': .5}})
assert beam_search(greedy_trap, 1)['tokens'] == ('A', EOS)
assert beam_search(greedy_trap, 2)['tokens'] == ('B', EOS)

width_trap = table_model({
    (): {'A': .55, 'B': .45},
    ('A',): {'a': .3, 'b': .25, 'c': .25, 'd': .2},
    ('B',): {'a': .5, 'b': .5},
    ('B', 'a'): {'x': .5, 'y': .5},
    ('B', 'b'): {'x': .5, 'y': .5},
})
assert isclose(exp(beam_search(width_trap, 1)['log_probability']), .165)
assert isclose(exp(beam_search(width_trap, 2)['log_probability']), .1125)
assert isclose(exp(beam_search(width_trap, 3)['log_probability']), .165)
assert beam_search(lambda _: {'x': 1.0}, 2, 3)['status'] == 'truncated'
for width in (1, 2, 3):
    result = beam_search(width_trap, width)
    print(width, result['tokens'], round(exp(result['log_probability']), 4))

The first table is the opening example. Width 1 returns (A, EOS) with probability 0.3. Width 2 preserves B long enough to return (B, EOS) with probability 0.4. The tie between (A, EOS) and (A, x) favors EOS because the literal string '<eos>' sorts before 'x'.

The second table demonstrates a less comfortable result: increasing beam width can lower the returned probability. Every unlisted prefix ends immediately, so this is a fully specified, finite example, not an appeal to an unknown language model.

RoundWidth 1Width 2
1A: 0.55A: 0.55; B: 0.45
2A a: 0.165B a: 0.225; B b: 0.225
3A a EOS: 0.165B a x: 0.1125; B a y: 0.1125
4Already completeB a x EOS: 0.1125 wins the tie

At width 2, descendants of the newly admitted B prefix eject the A prefix that width 1 would keep. Their next probabilities then shrink. Width 3 retains A a and recovers 0.165, the exhaustive optimum for this table. The beams at different widths are not nested across rounds. This example disproves a universal monotonicity guarantee for the stated procedure; it does not predict typical quality on a corpus.

For complexity, let VV bound the number of tokens in a queried row, and exclude the model’s own computation and storage. A round materializes at most BV+1BV+1 candidates before pruning. If scores and sequence handles were constant-size and comparisons constant-time, sorting would cost O(BVlog⁡(BV+1))O(BV\log(BV+1)) per round. This implementation copies token tuples of length up to LL, and exact score ties can compare those tuples. Its conservative worst-case time bound is O(L2BVlog⁡(BV+1))O(L^2BV\log(BV+1)), with O(BVL)O(BVL) temporary token storage and O(BL)O(BL) retained beam storage. It makes at most LBLB model calls. Calling it an O(B)O(B)-memory implementation would omit its candidate pool and copied histories. Backpointers and a streaming top-BB selection can reduce those costs, but are not used here.

Width, length and stopping are separate decisions

The raw log score falls or stays equal whenever a particular prefix grows. This does not imply that every shorter sentence outranks every longer sentence: different branches begin with different probabilities. It does mean that EOS, length and scoring deserve explicit treatment when output length varies.

For example, define a normalized score for nonempty sequences by

sα(y)=s(y)∣y∣α,α≥0.s_\alpha(y)=\frac{s(y)}{|y|^\alpha},\qquad \alpha\ge0.

This is a different objective. A length-1 prefix with score −1-1 can extend by a token of log probability −0.1-0.1; its length-2 average score becomes −0.55-0.55, which is higher. The raw-prefix stopping bound no longer applies unchanged. GNMT uses its own length factor, ((5+∣Y∣)/6)α((5+|Y|)/6)^\alpha, together with a coverage term. Its formula, tuning and extra pruning rules should not be confused with the simpler example above. GNMT v2, section 7, equation 14

The code deliberately uses raw scores only. Adding normalization requires defining how to rank unfinished prefixes, how to compare completed answers, which length counts EOS, and which upper bound permits early termination. Changing just the final sort leaves pruning under the old objective.

Two practical checks prevent misleading results. First, report EOS termination separately from exhaustion of the length budget. A prefix probability is the probability that generation begins with those tokens. It can include continuations beyond the length cap or continuations that never emit EOS, so it is not the probability of a completed sentence. Second, report the actual variant: whether finished hypotheses consume slots, whether they are archived, and whether candidates are deduplicated. Different conventions can return different answers at the same width.

A decoder for a neural network also stores model state, such as recurrent states or attention caches, and spends time computing token probabilities. The table program measures none of that. For natural-language generation, higher model probability can still prefer repetitive, short, or incorrect text. Evaluation must examine the application’s outputs as well as the search score.

Trace, break and audit the decoder

  1. In greedy_trap, enumerate every complete answer with at most 3 tokens. Which one does width 1 lose?
  2. Explain the second row of the width counterexample. Would keeping the top two children of each parent implement width 2?
  3. Let the root assign EOS probability 0.1 and A probability 0.9. A splits equally into x and y; each of those splits equally into five tokens a through e, which then end with certainty. Use width 2. Why must the previously retained EOS be remembered?
  4. Run a model that always returns {'x': 1.0} with max_length=3, and then with 0. Give both results’ status and log probability. Does either contain a completed answer?
Worked answers
  1. The complete answers are A EOS with probability 0.6×0.5=0.30.6\times0.5=0.3, A x EOS with probability 0.3, and B EOS with probability 0.4. Width 1 discards B in its first round.
  2. B a and B b each score 0.45×0.5=0.2250.45\times0.5=0.225, exceeding A a at 0.55×0.3=0.1650.55\times0.3=0.165. Two children per parent would keep up to four live children here and impose a different total budget. The code pools all children before selecting.
  3. EOS survives round 1, then two 0.45 prefixes eject it in round 2. Each of their children has probability 0.09. The archive reinserts the 0.1 completion, so it ultimately wins. Forgetting it would lose the best complete answer already retained. There are ten length-4 alternatives at 0.09 each, plus the immediate EOS at 0.1; their probabilities sum to 1.
  4. The first result has tokens (x,x,x), status truncated, log probability 0 and hit_limit=True. The second has (), the same status and score, and hit_limit=True. Neither has EOS. A probability-1 continuation can remain unfinished indefinitely.

Read the contract before comparing decoders

The cited sources answer different questions. Berkeley’s local-search section describes population selection over neighboring configurations. The 2017 stopping paper studies completed sequence hypotheses and certificates conditional on beam pruning. GNMT v2 documents a particular translation decoder and modified objective. This article’s small tables, width counterexample and archive exercise are original teaching cases; its program is not a reproduction of those systems’ experiments.

The repository tests enumerate complete toy sequences with exact rational arithmetic, independently of the decoder’s ranking implementation. They check a sufficiently wide beam against that oracle, confirm the narrower counterexamples, and exercise EOS, ties, zero probabilities and length limits. Before adding a new scoring rule, reproduce those checks under the new objective. A search algorithm can faithfully optimize a score that is wrong for the application.

Make a prediction, then check

Does increasing this decoder’s beam width from 1 to 2 guarantee that the returned complete answer has no lower probability?

Choose one answer

Learning objectives

  • Distinguish local beam search, sequence beams and greedy best-first search; specify EOS, ties and length limits.
  • Audit pruning errors, nonmonotone beam-width behavior and completed-answer archives with finite probability tables and exact enumeration.

Prerequisites & connections

Explore related knowledge →

References

  1. When to Finish? Optimal Beam Search for Neural Text Generation (modulo beam size)
    Liang Huang; Kai Zhao; Mingbo Ma · 2017
  2. Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation — v2
    Yonghui Wu; Mike Schuster; Zhifeng Chen; et al. · 2016
  3. CS188 Textbook: 1.5 Local Search
    UC Berkeley CS188 course staff

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check:primary-source locations,original executable examples,independent finite-state oracles,bilingual review and a second Codex agent cross-check;not independent human peer review.

  • Reread both articles paragraph by paragraph; checked the same 3 display equations, complete Python program, 4 worked exercises, EOS slots/archive definition, probability normalization, complexity and raw-score scope. Independent rational enumeration covered 1000 small models and 50 random models at 6 length caps; the initial 7 tests passed. This is not independent human peer review.
  • Cross-review found that preserving live prefixes alone does not ensure complete-answer optimality. Tightened the exact-arithmetic premise to include newly generated EOS candidates and added the x:0.6/EOS:0.4 counterexample.
  • Cross-review reproduced accumulated-log near ties making width1 differ from local-probability greedy. Kept the declared float/lexicographic rule,qualified both languages and added the8-step regression. Final9beam tests passed.
  • Paired code,display formulas and main anchors match. All48search checks and101article Python programs passed. Reviews are AI technical checks,not independent human peer review.
  • After mobile screenshots, shortened Chinese headers and clarified run-count/total-edge-visit columns in both local-search articles. Algorithms,equations,values and conditions are unchanged; targeted rereading completed.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.