## Abstract

Decoding for many NLP tasks requires an effective heuristic algorithm for approximating exact search because the problem of searching the full output space is often intractable, or impractical in many settings. The default algorithm for this job is beam search—a pruned version of breadth-first search. Quite surprisingly, beam search often returns *better* results than exact inference due to *beneficial* search bias for NLP tasks. In this work, we show that the standard implementation of beam search can be made up to 10x faster in practice. Our method assumes that the scoring function is monotonic in the sequence length, which allows us to safely prune hypotheses that cannot be in the final set of hypotheses early on. We devise effective monotonic approximations to popular nonmonontic scoring functions, including length normalization and mutual information decoding. Lastly, we propose a memory-reduced variant of best-first beam search, which has a similar beneficial search bias in terms of downstream performance, but runs in a fraction of the time.

## 1 Introduction

Beam search is a common heuristic algorithm for decoding structured predictors (e.g., neural machine translation models and transition-based parsers). Because of the widespread adoption of recurrent neural networks and other non-Markov models, traditional dynamic programming solutions, such as the Viterbi algorithm (Viterbi, 1967), are prohibitively inefficient; this makes beam search a common component of many state- of-the-art NLP systems. Despite offering no formal guarantee of finding the highest-scoring hypothesis under the model, beam search yields impressive performance on a variety of tasks— unexpectedly providing a beneficial search bias over *exact* search for many tasks (Stahlberg and Byrne, 2019).

Within NLP, most research on beam search has focused on altering the log-probability scoring function to return improved results, for example, higher bleu scores (Wu et al., 2016; Murray and Chiang, 2018; Shu and Nakayama, 2018; Yang et al., 2018) or a more diverse set of outputs (Vijayakumar et al., 2016). However, little work has been done to speed up beam search itself. Filling this gap, this paper focuses on reformulating beam search in order to make it *faster*. We propose best-first beam search, a prioritized version of traditional beam search that is up to an order of magnitude faster in practice while still returning the same set of results. We additionally discuss an even faster heuristic version of our algorithm that further limits the number of candidate solutions, leading to a smaller memory footprint while still finding good solutions.

Concretely, we offer a novel interpretation of beam search as an agenda-based algorithm where traditional beam search is recovered by utilizing a length-based prioritization scheme. We prove that a specific best-first prioritization scheme, as in classic A^{*} search (Hart et al., 1968), allows for the elimination of paths that will necessarily fall off the beam; for many scoring functions, including standard log-probability scoring, we can still guarantee the same *k* hypotheses as traditional beam search are returned. Indeed, our algorithm returns beam search’s top hypothesis the first time it encounters a complete hypothesis, allowing the program to stop early. Further, we discuss the application of best-first beam search to several popular scoring functions in the literature (He et al., 2016; Li et al., 2016); this demonstrates that we have a general framework for adapting a variety of rescoring methods and alternate objectives to work with our algorithm.

Empirically, we compare best-first beam search to ordinary beam search on two NLP sequence-to-sequence tasks: neural machine translation (NMT) and abstractive summarization (AS). On NMT, we find that our algorithm achieves roughly a 30% speed-up over traditional beam search with increased gains for larger beams (e.g., ≈ 10x for a beam of 500). We find similar results hold for AS. Finally, we show that our memory-reduced version, which limits the number of active hypotheses, leads to additional speed-ups over best-first beam search across beam sizes while maintaining similar bleu scores.

## 2 Sequence Transduction

**x**is an input and $Y(x)$ is a set of well-formed outputs for the input. An important example of (1) is maximum a posteriori (MAP),

Our work focuses on sequence-to-sequence transduction: predicting an output sequence given an input sequence. One such task is machine translation, wherein a source-language sentence is mapped (“transduced”) to a target-language sentence. While our exposition focuses on sequence-to-sequence prediction, our algorithms are directly applicable to any sequential structured prediction model, such as transition-based parsers (Nivre et al., 2008) and sequence taggers (McCallum et al., 2000; Lafferty et al., 2001).

### Notation.

*N*

_{x}and, likewise, let

**y**=$\u2329y1,\u2026,yNy\u232a$ be an output sequence of length

*N*

_{y}. Each

*y*

_{t}is an element of $V$, the set of output tokens. Finally, let $Y(x)$ be the set of all valid output sequences (i.e., complete hypotheses). For the task of language generation, which we focus on experimentally, this set is defined as

*n*

_{max}(

**x**). In words, every valid sequence begins and ends with distinguished tokens (bos and eos, respectively).

^{1}Furthermore, each sequence has

*at most*length

*n*

_{max}(

**x**)—which is typically dependent on

**x**—a restriction we impose to ensure termination. Some applications may require a stronger coupling between $Y(x)$ and

**x**(e.g., |

**x**| = |

**y**|). We drop the dependence of $Y$ and

*n*

_{max}on

**x**when it is clear from context.

### Scoring.

^{2}

### Beam search.

The worst-case running time of exactly computing (1) is exponential in *n*_{max}; namely, $O(|V|nmax)$.^{3} Beam search is a commonly used approximation to (1) in NMT and language generation tasks. It is used in many (if not most) state-of-the-art NLP systems (Wu et al., 2016; Serban et al., 2017; Edunov et al., 2018; Yang et al., 2019). Beam search may be understood as a pruned version of the classic path-search algorithm, breadth-first search (BFS), where the breadth is narrowed to the beam size *k*. Pseudocode is given in (1).

Although, beam search does not solve (1) exactly, it is a surprisingly useful approximation for NLP models. In many settings, beam search *outperforms* exact methods in terms of downstream evaluation (Koehn and Knowles, 2017; Stahlberg and Byrne, 2019). For the remainder of this paper, we will pivot our attention away from exact solutions to (1) to exact solutions to the *beam search* output.

* k-optimal hypothesis.* We say that a hypothesis is

*k*-optimal if it is the top hypothesis returned by beam search with beam size

*k*.

## 3 A^{*} Beam Search

We develop a meta-algorithm that is parameterized by several choice points. Our general search algorithm for decoding (Alg. 2) takes an arbitrary prioritization function, stopping criterion, and search heuristic. With certain values of these attributes, we recover many common search algorithms: greedy search, beam search, best-first search (Dijkstra, 1959), and A^{*} search (Hart et al., 1968). We propose an alternate prioritization function for beam search that allows for faster decoding while still returning the same *k*-optimal set of hypotheses.

### 3.1 Choice Points of 2

Here we review the components of our meta algorithm (the highlighted sections in Alg. 2) that can be varied to recover different search strategies:

⧁ :

**y**×**y**→{True, False}. A priority queue $Q$ maintains the set of active hypotheses. Elements in this set are ordered according to a generic comparator ⧁. When its peek() (or pop()) methods are called, the first element ordered by ⧁ is returned (or returned and removed).stop(⋅) : Collection〈

**y**〉→{True, False}. The algorithm terminates according to configurable stopping criterion based on the current set of elements in $Q$.*k*∈ℕ_{>0}. Only*k*paths of a given length are considered. If the algorithm has already encountered*k*paths of a given length, subsequent paths of that length are not evaluated. If we take $k=\u221e$, we recover unpruned search algorithms.*h*(⋅,⋅) :**x**×**y**→ℝ. A heuristic function*h*(**x**,**y**) can be used during search to change the priority in which paths are evaluated. We note that with pruning, a heuristic may change the value of the*k*-optimal hypothesis (see § 4.1).

#### Recovering Beam Search.

To recover beam search from Algorithm 2, we use the choice points from Table 1. Explicitly, the comparator prioritizes hypotheses from earlier time steps first, but breaks ties with the hypotheses’ scores under the model. We note that while the standard algorithm for beam search does not prioritize by score within a time step, variations of the algorithm use this strategy so they can use early-stopping strategies (Klein et al., 2017; Huang et al., 2017). Beam search terminates once either *all* hypotheses end in eos or the queue is empty (i.e., when the *k* beams have been extended *n*_{max} time steps but none end in eos). In the second case, no complete hypothesis is found. Finally, choosing the heuristic *h*(**x**,**y**) = 0 makes the algorithm a case of standard best-first search.

. | Beam Search
. | Best-First Beam Search
. | A
. ^{*} Beam Search |
---|---|---|---|

① | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ |y| < |y|′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ |

$or|y|=|y|\u2032andsh\u2265sh\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | |

② | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ |

$y.last()=eos\u2200y\u2208Q$ | $Q.peek().last()=eos$ | $Q.peek().last()=eos$ | |

③ | k = beam size | k = beam size | k = beam size |

④ | 0 | 0 | any admissible heuristic |

Breadth-First Search | Best-First Search | A ^{*} Search | |

① | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ |y| < |y|′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ |

$or|y|=|y|\u2032andsh\u2265sh\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | |

② | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ |

$y.last()=eos\u2200y\u2208Q$ | $Q.peek().last()=eos$ | $Q.peek().last()=eos$ | |

③ | $k=\u221e$ | $k=\u221e$ | $k=\u221e$ |

④ | 0 | 0 | any admissible heuristic |

. | Beam Search
. | Best-First Beam Search
. | A
. ^{*} Beam Search |
---|---|---|---|

① | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ |y| < |y|′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ |

$or|y|=|y|\u2032andsh\u2265sh\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | |

② | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ |

$y.last()=eos\u2200y\u2208Q$ | $Q.peek().last()=eos$ | $Q.peek().last()=eos$ | |

③ | k = beam size | k = beam size | k = beam size |

④ | 0 | 0 | any admissible heuristic |

Breadth-First Search | Best-First Search | A ^{*} Search | |

① | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ |y| < |y|′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ | 〈s_{h},y〉⧁〈s_{h}′,y′〉 ⇔ s_{h} > s_{h}′ |

$or|y|=|y|\u2032andsh\u2265sh\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | $orsh=sh\u2032and|y|<|y|\u2032$ | |

② | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ | $stop(Q)\u21d4$ |

$y.last()=eos\u2200y\u2208Q$ | $Q.peek().last()=eos$ | $Q.peek().last()=eos$ | |

③ | $k=\u221e$ | $k=\u221e$ | $k=\u221e$ |

④ | 0 | 0 | any admissible heuristic |

Note that, while standard beam search returns a set, Alg 2 only returns the *k*-optimal hypothesis. This behavior is sufficient for the majority of use cases for beam search. However, if the full set of *k* hypotheses is desired, the stopping criterion can be changed to evaluate true only when *k* hypotheses are complete. Under the other beam search settings, this would probably return the same set as beam search (see § 4.1).

#### Recovering A^{*}.

To recover the traditional A^{*} search algorithm, we use the comparator that prioritizes hypotheses with a higher score first; ties are broken by hypothesis length. The algorithm terminates when the first item of $Q$ contains an eos. If we take $k=\u221e$, best-first beam search recovers A^{*}. Any admissible heuristic may be used for *h*(**x**,**y**).

*Admissible Heuristic.* A heuristic *h* is admissible if it never overestimates the future cost—or underestimates the future reward—of continuing down a path.

## 3.2 Best-First Beam Search

In its original form, A^{*} search may traverse the entire $O(|V|nmax)$ graph, which as discussed earlier, is intractable for many decoding problems. While standard beam search addresses this problem by limiting the search space, it still has computational inefficiencies—namely, we *must* analyze *k* hypotheses of a given length (i.e., time step), regardless of how poor their scores may already be, before considering longer hypotheses. However, prioritization by length is not strictly necessary for finding a *k*-optimal hypothesis. As is done in A^{*}, we can use score as the prioritization scheme and still guarantee optimality–or *k*-optimality–of the paths returned by the algorithm.

We define A^{*} beam search as the A^{*} algorithm where breadth is limited to size *k*. Further, we define best-first beam search as the case of A^{*} beam search when no heuristic is used (see Table 1 for algorithm settings). This formulation has two large advantages over standard beam search: (1) we gain the ability to remove paths from the queue that are guaranteed to fall off the beam and (2) we can terminate the algorithm the first time a complete hypothesis is encountered. We can therefore reduce the computation required for decoding while still returning the same set of results.

The mathematical property that makes this short-circuiting of computation possible is the monotonicity of the scoring function. Note that not all scoring functions are monotonic, but many important ones are, including log-probability (5). We discuss effective approximations for popular non-monotonic scoring functions in § 5.

*Monotonicity.*A scoring function score(⋅,⋅) is monotonic in

*t*if for all

**x**,

**y**

_{<t}= 〈

*y*

_{1}…

*y*

_{t−1}〉, $yt\u2208V,1\u2264t\u2264nmax$

Clearly, (5) is a monotonic scoring function in *t* because score_{s2s} ≤ 0, that is, the score of a partial hypothesis **y**_{<t} can only decrease if we extend it by another symbol *y*_{t}. This implies we can order our search according to score(**x**,**y**_{<t}) without fear of overlooking a hypothesis whose score would increase over time. Furthermore, once *k* hypotheses of a given length *t* have been evaluated, we no longer need to consider any hypothesis where |**y**| < *t* because such hypotheses would necessarily fall off the beam. We can therefore remove such hypotheses from the queue and avoid wasting computational power on their evaluation. We prove this formally in § 4.1.

Another implication of the monotonicity property of score is that we may terminate best-first beam search once a hypothesis containing eos is encountered (i.e., the end state is found). If the full set of *k* complete hypotheses is desired, then we simply continue until *k* hypotheses have reached eos. We prove the *k*-optimality of these hypotheses under best-first beam search in § 4.1.

## 3.3 Implementation Details

Standard beam search forms a separate set of active hypotheses for each time step, that is, each *B*_{t} is its own set. Once *B*_{t} has been narrowed down to the top *k*, the previous *B*_{<t} can be forgotten. However in best-first beam search, because hypotheses are not evaluated in order of time step, we may need to keep *B*_{t} from several time steps at any given point.

A naive implementation of best-first beam search is to keep a single priority queue with all the active hypotheses ordered by current score. However, each push to the queue would then require $O(log(nmaxk|V|))$ time. We can reduce this runtime by instead keeping a priority queue of beams, where the priority queue is ordered by the highest-scoring hypothesis from each beam. Further, each beam can be represented by a min-max queue (Atkinson et al., 1986); this allows us to limit the size of *B*_{t} to *k*: we can check in $O(1)$ time if a hypothesis is in the top-*k* before adding it to *B*_{t}.

A potential inefficiency, which we avoid, comes from updating *B*_{t+1}, which we must do when evaluating a hypothesis from *B*_{t}. Because all beams are stored in a queue, there is no guarantee of the location in the queue of *B*_{t+1}. To avoid $O(nmax)$ lookup, we can keep a pointer to each beam, indexed by *t* making the lookup $O(1)$. However, we acquire a $O(lognmax)$ term to update the queue of beams as *B*_{t+1} may change priority.

### Memory-Reduced Best-First Beam Search.

A major drawback of the A^{*} algorithm is its memory usage, which in the worst-case is $O(bd)$ for breadth width *b* and maximum depth *d*. In the A^{*} formulation of beam search, where the breadth width is limited to the beam size, this amounts to worst-case $O(k\u22c5nmax)$ memory usage, where standard beam search has $O(k)$ memory usage. Whereas in many settings the multiplicative factor may be insignificant, for neural sequence models it can be prohibitive; this is due to the large amount of memory required to store each hypothesis (e.g., prior hidden states needed to compute subsequent scores for scoring functions parameterized by neural networks).

We propose a variant of best-first beam search that limits memory usage, that is, the queue capacity. Specifically, if we reach the chosen queue capacity, we remove the worst scoring active hypothesis from the earliest active time step. This can easily be done in $O(1)$ time given our pointer to each beam.

## 4 Algorithm Analysis

### 4.1 Correctness

We show the equivalence of the top hypothesis^{6} returned by beam search and best-first beam search when score(⋅,⋅) is monotonically decreasing in *t*, length-based prioritization is used, and the beam size *k* is the same for both algorithms. Without loss of generality, we hold **x** constant in all the following proofs.

Note that we take the terms *pop* and *push* from queue terminology. Specifically, “popping a hypothesis” refers to making it past line 7 of Alg. 2, where a hypothesis **y** is expanded by $yt\u2208V$. In path search terminology, this would be equivalent to visiting a node and adding the edges from that node as potential paths to explore. Lastly, we refer to the priority queue used by beam search and best-first beam search as $QBS$ and $QA*$, respectively.

*Best-first beam search evaluates all hypotheses of a given length t in order of their score.*

*Proof.*

We prove the lemma by induction. The lemma holds trivially for the base case of hypotheses of length 0 because the only hypothesis of length 0 is 〈bos〉.

Now, by the inductive hypothesis, suppose Lemma 4.1 holds for all hypotheses of length < *t*. We will show it must also hold for hypotheses of length *t*. Consider two competing hypotheses: **y** =**y**_{<t} ∘ *y*_{t} and $y\u2032=y<t\u2032\u2218yt\u2032$. Note that |**y**_{<t}| = |**y**_{<t}*′*| = *t* − 1. Suppose score(**x**,**y***′*) < score(**x**,**y**).

*Case 1*: $score(x,y<t\u2032)<score(x,y<t)$. Then by induction, **y**_{<t} popped first and **y** is pushed to $Q$ before **y***′*. Because score(**x**,**y***′*) < score(**x**,**y**), **y** will be popped before **y***′*.

*Case 2*: $score(x,y<t)<score(x,y<t\u2032)$. Then by induction, $y<t\u2032$ is popped first and **y***′* is added to $Q$ before **y**. But, because score(**x**,**y***′*) < score(**x**,**y**) ≤score(**x**,**y**_{<t}) by monotonicity, then **y**_{<t} will be popped before **y***′*. Consequently, **y** will be pushed to $Q$ before **y***′* is evaluated. By the rules of the priority queue **y** will be evaluated before **y***′*.

*Case 3*: score(**x**,**y***′*) = score(**x**,**y**). The lemma holds if either **y** or **y***′* is popped first.

By the principle of induction, Lemmma 4.1 holds for all *t* ∈ℕ_{>0}.

*The first hypothesis that best-first beam search pops that ends in eos is k-optimal.*

*Proof.*

Let **y** be the first hypothesis popped by best-first beam search ending in eos. By rules of the priority queue, no other active hypothesis has a higher score than **y**. Additionally, by monotonicity of the scoring function, no other hypothesis can subsequently have score greater than **y**. Therefore **y** must be *k*-optimal.

*If best-first beam search pops a hypothesis, then beam search necessarily pops that same hypothesis.*

*Proof.*

We prove the lemma by induction on hypothesis length. The base case holds trivially: For hypotheses of length 0, both best-first beam search and beam search must pop the 〈bos〉 as it is the only item in the queue after initialization.

By the inductive hypothesis, suppose Lemma 4.1 holds for hypotheses of length < *t*. Suppose best-first beam search pops a hypothesis **y** =**y**_{<t} ∘ *y*_{t} of length *t*.

*Case 1:* Best-first beam search pops *k* hypotheses of length *t* − 1 before popping **y**, which is of length *t*. The sets of hypotheses of length *t* − 1 that each algorithm pops are necessarily the same by the inductive hypothesis and the fact that they have the same cardinality. If best-first beam search pops **y**, which is of length *t*, then it must be in the top-*k* highest-scoring hypotheses of length *t* in $QA*$ by the rules of the priority queue. Consequently, it must be in the top-*k* in $QBS$.

*Case 2:* Best-first beam search has popped fewer than *k* hypotheses of length *t* − 1 before popping **y**. Then, all remaining hypotheses of length *t* − 1 in $QA*$ must have $score(x,y<t\u2032)<score(x,y)$ by the rules of the priority queue. By the monotonicity of the score function, all extensions of those $y<t\u2032$ will also have $score(x,y<t\u2032\u2218yt\u2032)<score(x,y)$. Because none of $y<t\u2032\u2218yt\u2032$ has greater score than **y**, **y** must be in *B*_{t}.

*Best-first beam search will never pop more hypotheses than beam search.*

*Once best-first beam search has popped k hypotheses of length t, hypotheses from time steps < t do not need to be popped.*

*Proof.*

This follows from Lemma 4.1. If *k* hypotheses of length *t* have been popped, then these must be the top-*k* hypotheses from time step *t*. Therefore no hypothesis from time step < *t* that is still in $QA*$ would be in the top-*k* at time step *t*.

*Let* ℋ_{bs}*and* ℋ_{A}*be the set of khypotheses returned by beam search and best-first beam search, respectively.* ℋ_{bs} =ℋ_{A}.

*Proof.*

Because |ℋ_{bs}| = |ℋ_{A}| = *k*, we only need to show **y** ∈ℋ_{bs}⇒**y** ∈ℋ_{A}.

Suppose, by way of contradiction, there exists a hypothesis **y** ∈ℋ_{bs} such that **y**∉ℋ_{A}. If **y**∉ℋ_{A} then we must not pop the prefix **y**_{<t} (where **y** =**y**_{<t} ∘**y**_{t:|y|}) for some time step *t* < |**y**|.

*Case 1*: At some time step *t* + *j* (*j* ≥ 0), we pop *k* partial hypotheses ${y\u2264t+j(1),\u2026,y\u2264t+j(k)}$ where $y\u2264t+j\u2209{y\u2264t+j(1),\u2026,y\u2264t+j(k)}$. By Lemma 4.1, it must be that $score(x,y\u2264t+j(i))>score(x,y\u2264t+j$) ∀*i* ∈ 1,…,*k*. This implies that for beam search, **y**_{≤t+j} would not be in the top-*k* paths at time step *t* + *j* since by Lemma 4.3, paths ${y\u2264t+j(1),\u2026,y\u2264t+j(k)}$ would also be evaluated by beam search. Therefore **y** cannot be in ℋ_{bs}, which is a contradiction.

*Case 2*: For no time step *t* + *j* (*j* ≥ 0) do we pop *k* paths. This can only happen if the algorithm stops early, namely, we have found *k* complete hypotheses **y**^{(1)},…,**y**^{(k)}. If this is the case, then by rules of the priority queue, each **y**^{(1)},…,**y**^{(k)} must have score greater than score(**x**,**y**_{<t}). By monotonicity of the score function, score(**x**,**y**^{(i)})> score(**x**,**y**). This implies **y** cannot be in ℋ_{bs}, which is a contradiction.

#### Non-monotonic Scoring Functions.

Non-monotonic scoring functions (Definition 3.2) break the assumptions of § 4.1, in which case best-first beam search is not guaranteed to return a *k*-optimal hypothesis. However, when the scoring function is boundable from above, we can alter the original stopping criterion (② in Alg. 2) such that *k*-optimality is again guaranteed.

**y**

*′*can increase as

**y**

*′*is expanded further.

^{7}In this situation, best-first beam search only terminates once no other hypothesis in $Q$ can have a score greater than the best finished hypothesis. We note that Huang et al. (2017) use a similar scheme for optimal stopping with bounded length normalization. We discuss examples of non-monotonic scoring functions in § 5.

#### A Note on Heuristics.

Our analysis shows the equivalence of beam search and best-first beam search, that is, when *h*(**x**,**y**) = 0. The analysis does *not* hold for arbitrary admissible heuristics. A poor heuristic (e.g., one that grossly overestimates the future score of continuing down one path) may cause other items to be pruned from best-first beam search that otherwise would have remained on the beam in standard beam search.

### 4.2 Runtime

*The runtime of best-first beam search is*$O(nmaxk(|V|log(k)+log(nmax)))$

*Proof.*

We pop at most *n*_{max} ⋅ *k* items. Each pop requires us to push $|V|$ items. Each push requires $log(k)$ time when the priority queue is implemented with a min–max heap (Atkinson et al., 1986) and incrementally pruned so that it has no more than *k* items. After pushing those $|V|$ items, we have to perform a percolation in the priority queue of priority queues, which requires $log(nmax)$ time. This yields $O(nmaxk(|V|log(k)+log(nmax)))$ time.

*The runtime of standard beam search is*$O(nmaxk|V|log(k))$.

*Proof.*

The proof is the same as Theorem 4.6, but we can forgo the percolation step in the queue of queues because standard beam search proceeds in order of hypothesis length. This yields $O(nmaxk|V|log(k))$.

Although the theoretical bound of best-first beam search has an additional log factor compared with standard beam search, we find this to be negligible in practice. Rather, we find number of calls to score, the scoring function under our model (e.g., a neural network), is often the bottleneck operation when decoding neural networks (see § 6 for empirical evidence). In terms of this metric, the beam search algorithm makes $O(knmax)$ calls to score, as score is called once for each active hypothesis in *B* and *B* may evolve for *n*_{max} rounds. The worst-case number of calls to score will be the same as for beam search, which follows from Lemma 4.3.

## 5 Scoring Functions

Even before the findings of Stahlberg and Byrne (2019), it was well known that the best-scoring hypothesis with respect to the traditional likelihood objective can be far from ideal in practice (Wu et al., 2016; Murray and Chiang, 2018; Yang et al., 2018). For language generation tasks specifically, the results returned by neural models using the standard scoring function are often short and default to high-frequency words (Vinyals and Le, 2015; Shen et al., 2016).

To alleviate such problems, methods that revise hypothesis scores to incorporate preferences for longer, less repetitive, or more diverse options have been introduced and are often used in practice. While most such techniques change the scoring function such that it is no longer monotonic, we can still guarantee the *k*-optimality of the returned hypothesis for (upper) bounded scoring functions using the methods discussed in § 4.1. In the remainder of this section, we present alternate scoring schemes adapted to work with best-first beam search. Additionally, we present several heuristics which, while breaking the *k*-optimality guarantee, provide another set of decoding strategies worth exploring.

### Length Normalization.

Length normalization is a widely used hypothesis scoring method that aims to counteract the propensity for shorter sequences to have higher scores under neural models; this is done by normalizing scores by hypothesis length (see Murray and Chiang [2018] for more detail).

*r*and the final sequence length

*N*

_{y}:

*β*is the scaling parameter for the reward. We note, however, that the same can be done with the maximum sequence length

*n*

_{max}such that the traditional length reward used by He et al. (2016) is recovered:

*b*can be

*r*|

**x**| or

*n*

_{max};

^{8}or (2) stopping criterion as in (6) albeit with scoring function score

_{ln}and upper-bound function:

*k*-optimal hypotheses as beam search, using a heuristic during pruned search means we can no longer guarantee the

*k*-optimality of the results with respect to the scoring function as the heuristic may push hypotheses off of the beam. We present experimental results for both methods in § 6.

### Mutual Information.

**y**to maximize conditional probability with respect to the input

**x**, we instead choose

**y**to maximize pointwise mutual information (PMI):

*p*(

**y**) term, as Li et al. (2016) point out, acts as an “anti-language model.” One unfortunate side effect of this objective is that ungrammatical and nonsensical outputs, which have probabilities close to 0 under a language model like

*p*(

**y**), end up with high scores because of the second term in the score function. To address this problem, and to upper-bound the scoring function, we propose lower-bounding the language model term by a hyperparameter 1 ≥

*ε*> 0. We additionally use the strength hyperparameter

*λ*employed by Li et al. (2016):

_{pmi}and upper-bound function:

_{pmi}by the above function. However, as with our length normalization strategy, we lose the

*k*-optimality guarantee with the heuristic method for mutual information decoding. We present experimental results for both methods in § 6.

## 6 Experiments

We run our algorithm on several language-related tasks that typically use beam search for decoding: NMT and AS. Specifically, experiments are performed on IWSLT’14 De-En (Cettolo et al., 2012), WMT’17 De-En (Bojar et al., 2017), MTTT Fr-En (Duh, 2018), and CNN-DailyMail (Hermann et al., 2015) using both Transformers (Vaswani et al., 2017) and Convolutional sequence-to-sequence models (Gehring et al., 2017).

For reproducibility, we use the data pre-processing scripts provided by fairseq (Ott et al., 2019) and follow their methods for training sequence transduction models. Hyperparameters are set in accordance with previous works. Specifically, on IWSLT’14 and MTTT tasks, we follow the recommended Transformer settings for IWSLT’14 in fairseq,^{9} which are based on Vaswani et al. (2017) and Gehring et al. (2017). Hyperparameters for models trained on the WMT task are set following version 3 of the Tensor2Tensor toolkit (Vaswani et al., 2018). We use byte-pair encoding (BPE; Sennrich et al. 2016) for all languages. Vocabulary sizes for WMT and IWSLT’14 are set from recommendations for the respective tasks in fairseq; for the MTTT tasks, vocabulary sizes are tuned on models trained with standard label-smoothing regularization. Similarly, the CNN/DailyMail dataset is pre-processed and uses BPE following the same steps as (Lewis et al., 2019); model hyperparameters are likewise copied. Details are available on fairseq’s Web site.^{10}

### 6.1 Running Time

In Table 2, we report values as the average number of calls to the scoring function per input; we do not use wall-clock time as this is heavily dependent on hardware. See Fig. 1 for empirical justification of the correlation between calls to the scoring function and runtime on the hardware our experiments were run on. For reference, in our experiments, the scoring function took on average > 99*%* of the total computation time, even with larger beam sizes, when overhead of the search algorithm is most significant.

. | IWSLT’14 De-En
. | MTTT Fr-En
. | CNN-DailyMail
. | |||||||
---|---|---|---|---|---|---|---|---|---|---|

. | k = 5 (35.6)
. | k = 10 (35.4)
. | k = 100 (34.7)
. | k = 500 (7.9)
. | k = 10 (33.0)
. | k = 100 (9.9)
. | k = 500 (1.2)
. | k = 5 (31.5)
. | k = 10 (30.9)
. | k = 100 (29.1)
. |

BF beam search | 93_{(24%)} | 169_{(36%)} | 1275_{(79%)} | 1168_{(736%)} | 184_{(16%)} | 867_{(138%)} | 885_{(836%)} | 200_{(33%)} | 305_{(43%)} | 2960_{(92%)} |

Beam search (ES) | 10_{(7%)} | 210_{(9%)} | 2047_{(12%)} | 7685_{(27%)} | 196_{(9%)} | 1310_{(58%)} | 4182_{(98%)} | 224_{(19%)} | 357_{(22%)} | 3942_{(59%)} |

Beam search | 115 | 229 | 2286 | 9770 | 214 | 2066 | 8281 | 266 | 435 | 5673 |

. | IWSLT’14 De-En
. | MTTT Fr-En
. | CNN-DailyMail
. | |||||||
---|---|---|---|---|---|---|---|---|---|---|

. | k = 5 (35.6)
. | k = 10 (35.4)
. | k = 100 (34.7)
. | k = 500 (7.9)
. | k = 10 (33.0)
. | k = 100 (9.9)
. | k = 500 (1.2)
. | k = 5 (31.5)
. | k = 10 (30.9)
. | k = 100 (29.1)
. |

BF beam search | 93_{(24%)} | 169_{(36%)} | 1275_{(79%)} | 1168_{(736%)} | 184_{(16%)} | 867_{(138%)} | 885_{(836%)} | 200_{(33%)} | 305_{(43%)} | 2960_{(92%)} |

Beam search (ES) | 10_{(7%)} | 210_{(9%)} | 2047_{(12%)} | 7685_{(27%)} | 196_{(9%)} | 1310_{(58%)} | 4182_{(98%)} | 224_{(19%)} | 357_{(22%)} | 3942_{(59%)} |

Beam search | 115 | 229 | 2286 | 9770 | 214 | 2066 | 8281 | 266 | 435 | 5673 |

We find that best-first (BF) beam search leads to significant speed-ups over both traditional beam search and beam search with early stopping, with a performance increase^{12} of ≈ 8*x* for a beam size of 500. We likewise find that best-first beam search offers speed-ups over early stopping methods that are *not* guaranteed to return the same results as standard beam search (see Table 3).

IWSLT’14 De-En
. | ||||
---|---|---|---|---|

k
. | method . | search error . | bleu . | # calls . |

10 | shrinking | 0% | 35.4 | 229(0%) |

early | 0% | 35.4 | 225(2%) | |

BF BS | − | 35.4 | 169(36%) | |

100 | shrinking | 31.7% | 13.2 | 2278(0%) |

early | 31.7% | 13.2 | 1738(31%) | |

BF BS | − | 34.7 | 1275(79%) | |

WMT’17 De-En | ||||

10 | shrinking | 0% | 28.6 | 260(0%) |

early | 0% | 28.6 | 252(3%) | |

BF BS | − | 28.6 | 230(12%) | |

100 | shrinking | 1.7% | 26.4 | 2587(0%) |

early | 1.7% | 26.4 | 2402(8%) | |

BF BS | − | 26.9 | 2046(26%) |

IWSLT’14 De-En
. | ||||
---|---|---|---|---|

k
. | method . | search error . | bleu . | # calls . |

10 | shrinking | 0% | 35.4 | 229(0%) |

early | 0% | 35.4 | 225(2%) | |

BF BS | − | 35.4 | 169(36%) | |

100 | shrinking | 31.7% | 13.2 | 2278(0%) |

early | 31.7% | 13.2 | 1738(31%) | |

BF BS | − | 34.7 | 1275(79%) | |

WMT’17 De-En | ||||

10 | shrinking | 0% | 28.6 | 260(0%) |

early | 0% | 28.6 | 252(3%) | |

BF BS | − | 28.6 | 230(12%) | |

100 | shrinking | 1.7% | 26.4 | 2587(0%) |

early | 1.7% | 26.4 | 2402(8%) | |

BF BS | − | 26.9 | 2046(26%) |

### 6.2 Length Normalization

We experiment with both forms of length normalization presented in § 5 and provide results in Table 4. We find that both methods, that is, changing the stopping criterion and using a heuristic during search, provide improvements over baseline bleu scores albeit with different hyperparameter settings; increases are similar to improvements reported by Murray and Chiang (2018). Notably, using a heuristic causes a large percentage of search errors with respect to standard beam search using the same scoring function. However, the difference in results appears to be *beneficial* in terms of bleu.

IWSLT’14 De-En
. | ||||||
---|---|---|---|---|---|---|

. |
. k |
. β |
. b | # calls . | search error . | bleu . |

Heuristic | 5 | 0.8 | |x| | 115_{(0%)} | 40.6% | 33.9_{+0.3} |

10 | 1.2 | |x| | 229_{(0%)} | 54.7% | 33.8_{+0.5} | |

Stopping Criterion | 5 | 0.5 | n_{max} | 73_{(58%)} | − | 33.7_{+0.1} |

10 | 0.5 | n_{max} | 130_{(76%)} | − | 33.7_{+0.4} | |

MTTT Fr-En | ||||||

Heuristic | 5 | 0.8 | .7|x| | 100_{(8%)} | 16.2% | 33.5_{+0.2} |

10 | 1.0 | .7|x| | 196_{(9%)} | 25.2% | 33.6_{+0.6} | |

Stopping Criterion | 5 | 1.0 | n_{max} | 65_{(66%)} | − | 34.1_{+0.8} |

10 | 1.2 | n_{max} | 88_{(143%)} | − | 34.1_{+1.1} |

IWSLT’14 De-En
. | ||||||
---|---|---|---|---|---|---|

. |
. k |
. β |
. b | # calls . | search error . | bleu . |

Heuristic | 5 | 0.8 | |x| | 115_{(0%)} | 40.6% | 33.9_{+0.3} |

10 | 1.2 | |x| | 229_{(0%)} | 54.7% | 33.8_{+0.5} | |

Stopping Criterion | 5 | 0.5 | n_{max} | 73_{(58%)} | − | 33.7_{+0.1} |

10 | 0.5 | n_{max} | 130_{(76%)} | − | 33.7_{+0.4} | |

MTTT Fr-En | ||||||

Heuristic | 5 | 0.8 | .7|x| | 100_{(8%)} | 16.2% | 33.5_{+0.2} |

10 | 1.0 | .7|x| | 196_{(9%)} | 25.2% | 33.6_{+0.6} | |

Stopping Criterion | 5 | 1.0 | n_{max} | 65_{(66%)} | − | 34.1_{+0.8} |

10 | 1.2 | n_{max} | 88_{(143%)} | − | 34.1_{+1.1} |

### 6.3 Mutual Information

We train a language model on the IWSLT dataset and use it to calculate *p*(**y**) from (12) as marginalizing over **y** is intractable (see Li et al. [2016] for further justification). We run experiments using both of the methods discussed in § 5 and present results in Table 5. We find that both methods provide results of equivalent bleu score compared with the baseline output, namely, results obtained with the unbounded PMI objective and beam search. Again, despite the high search error rate demonstrated by the heuristic method, evaluation metrics are still comparable.

. |
. k |
. ε |
. β | # calls . | search error . | bleu . |
---|---|---|---|---|---|---|

Baseline | 5 | − | .05 | 115 | − | 33.2 |

10 | − | .05 | 229 | − | 33.0 | |

Heuristic | 5 | .02 | .05 | 129_{(0%)} | 42.7% | 33.2 |

10 | .02 | .05 | 256_{(0%)} | 42.7% | 33.0 | |

Stopping Criterion | 5 | 3e–4 | .05 | 114_{(1%)} | 29.2% | 33.2 |

10 | 5e–5 | .05 | 224_{(2%)} | 26.6% | 33.0 |

. |
. k |
. ε |
. β | # calls . | search error . | bleu . |
---|---|---|---|---|---|---|

Baseline | 5 | − | .05 | 115 | − | 33.2 |

10 | − | .05 | 229 | − | 33.0 | |

Heuristic | 5 | .02 | .05 | 129_{(0%)} | 42.7% | 33.2 |

10 | .02 | .05 | 256_{(0%)} | 42.7% | 33.0 | |

Stopping Criterion | 5 | 3e–4 | .05 | 114_{(1%)} | 29.2% | 33.2 |

10 | 5e–5 | .05 | 224_{(2%)} | 26.6% | 33.0 |

### 6.4 Memory Usage

We conduct a set of experiments where we limit total queue capacity to *k* ⋅ *γ* for *γ* ∈{1,…,*n*_{max}}, as described in § 3.3, and report the bleu score of the resulting set of hypotheses.

As shown in Table 6, we find that restricting the queue capacity does not harm output quality and, additionally, leads to even greater runtime performance increase. For example, runtime for decoding of IWSLT’14 with a beam size of 10 can be improved by > 3*x* while returning results with better evaluation metrics. We find that improvements are even more pronounced for larger beam sizes. Across beam widths and tasks, we find that search error (with respect to standard beam search) is quite low for *γ* = 5. Additionally, for smaller *γ*, the change in bleu score demonstrates that search error in this context does not necessarily hurt the quality of results.

IWSLT’14 De-En
. | ||||
---|---|---|---|---|

. k |
. γ | search error . | bleu . | # calls . |

5 | 2 | 22.7% | 35.7_{+0.1} | 43.8(163%) |

5 | 4.4% | 35.8_{+0.2} | 79.8(44%) | |

n_{max} | − | 35.6 | 93.0(24%) | |

10 | 2 | 22.6% | 35.7_{+0.3} | 48.4(374%) |

5 | 4.5% | 35.6_{+0.2} | 126.9(81%) | |

n_{max} | − | 35.4 | 169.0(36%) | |

WMT’17 De-En | ||||

5 | 2 | 29.0% | 29.7_{+0.2} | 77.5(75%) |

5 | 1.2% | 29.5_{+0.0} | 115.8(12%) | |

n_{max} | − | 29.5 | 118.8(10%) | |

10 | 2 | 36.6% | 29.5_{+0.2} | 97.3(165%) |

5 | 2.6% | 29.3_{+0.0} | 230.0(12%) | |

n_{max} | − | 29.3 | 230.2(12%) |

IWSLT’14 De-En
. | ||||
---|---|---|---|---|

. k |
. γ | search error . | bleu . | # calls . |

5 | 2 | 22.7% | 35.7_{+0.1} | 43.8(163%) |

5 | 4.4% | 35.8_{+0.2} | 79.8(44%) | |

n_{max} | − | 35.6 | 93.0(24%) | |

10 | 2 | 22.6% | 35.7_{+0.3} | 48.4(374%) |

5 | 4.5% | 35.6_{+0.2} | 126.9(81%) | |

n_{max} | − | 35.4 | 169.0(36%) | |

WMT’17 De-En | ||||

5 | 2 | 29.0% | 29.7_{+0.2} | 77.5(75%) |

5 | 1.2% | 29.5_{+0.0} | 115.8(12%) | |

n_{max} | − | 29.5 | 118.8(10%) | |

10 | 2 | 36.6% | 29.5_{+0.2} | 97.3(165%) |

5 | 2.6% | 29.3_{+0.0} | 230.0(12%) | |

n_{max} | − | 29.3 | 230.2(12%) |

## 7 Related Work

Our work is most similar to that of Zhou and Hansen (2005), who propose beam stack search. However, they are focused on exact inference and still evaluate hypotheses in breadth-first order. Additionally, their algorithm requires $O(nmaxk)$ memory; although best-first beam search has the same requirements, we introduce effective methods for reducing them, namely, memory-reduced best-first beam search.

Huang et al. (2017) propose and prove the optimality of an early-stopping criterion for beam search. The authors find in practice though that reduction in computation from their algorithm was generally not significant. We build on this work and introduce additional methods for avoiding unnecessary computation. Our method leads to better performance, as shown in Table 2.

Klein and Manning (2003) use A^{*} for PCFG parsing; however, they use the un-pruned version for exact search, which is not applicable for NMT or AS as the memory requirements of the algorithm are far too large for these tasks. Subsequently, Pauls and Klein (2009) provide a method for pruning this search algorithm, albeit using a threshold rather than explicitly limiting the state space. Huang et al. (2012) also adapt A^{*} for a *k*-best decoding algorithm. Although their methods differ notably from ours, they likewise use pruning techniques that allow for substantial speedups.

Stahlberg and Byrne (2019) create an exact inference algorithm for decoding and use it to analyze the output of neural NMT models. Whereas they likewise utilize the monotonicity of the scoring function to make their method tractable, they do not focus on speed or mimicking the results of standard beam search.

## 8 Conclusion

We propose best-first beam search, an algorithm that allows for faster decoding while still guaranteeing *k*-optimality. We provide results on several sequence-to-sequence transduction tasks that show the speed-ups that our algorithm provides over standard beam search for decoding neural models. We adapt several popular alternate scoring functions to best-first beam search and provide a framework that can be used to adapt other scoring methods such as coverage normalization (Wu et al., 2016) or diverse beam search (Vijayakumar et al., 2016). We also provide a memory-reduced version of our algorithm, which returns competitive results in a fraction of the time needed for standard beam search.

## Notes

^{1}

bos and eos are typically members of $V$. Often, eos counts towards the *n*_{max} length limit while bos does not. This is reflected in (3).

^{2}

To see why, apply $exp$ (an order-preserving transformation): $exp(scores2s(x,y))=exp\u2211t=1Nylogp(yt\u2223y<t,x)=$$\u220ft=1Nyp(yt\u2223y<t,x)=p(y\u2223x)$.

^{4}

Often, the score function is additively decomposable in *t*, such as (5). Implementations can exploit this fact to make each score evaluation (line 9) $O(1)$ rather than $O(t)$. We did not make this implementation detail explicit in Alg. 1 or Alg. 2 for generality and simplicity.

^{5}

If the last token of **y***′* is the end symbol (e.g., eos), then **y***′* is not expanded any further. One can either regard **y***′* as any other hypothesis albeit with **y***′*∘ *y*_{t} =**y***′* or keep appending eos (i.e., **y***′*∘ *y*_{t} =**y***′*∘eos ) so that time step and length can be regarded as synonymous. We adopt the latter standard for comparability with subsequent algorithms.

^{6}

Best-first beam search is guaranteed to return the same set of *k* hypotheses as beam search. We include the proof for only the top hypothesis for simplicity. The proof for set equality follows naturally.

^{7}

For monotonic scoring functions, we have $U(x,y\u2032)=0$.

^{8}

We enforce *r*|**x**| < *n*_{max}.

^{12}

Performance increase is defined as (old −new)/new.

## References

**DOI:**https://doi.org/10.1145/6617.6621

**DOI:**https://doi.org/10.18653/v1/W17-4717

^{3}: Web inventory of transcribed and translated talks

**DOI:**https://doi.org/10.1007/BF01386390

**DOI:**https://doi.org/10.18653/v1/D18-1045

**DOI:**https://doi.org/10.18653/v1/P17-1012,

**PMID:**28964987,

**PMCID:**PMC6754825

**DOI:**https://doi.org/10.1109/TSSC.1968.300136

**DOI:**https://doi.org/10.18653/v1/D17-1227,

**PMID:**28564569

**DOI:**https://doi.org/10.3115/1073445.1073461

**DOI:**https://doi.org/10.18653/v1/P17-4012

**DOI:**https://doi.org/10.18653/v1/W17-3204

**DOI:**https://doi.org/10.18653/v1/2020.acl-main.703

**DOI:**https://doi.org/10.18653/v1/W18-6322

**DOI:**https://doi.org/10.3115/1599081.1599162

**DOI:**https://doi.org/10.18653/v1/N19-4009

**DOI:**https://doi.org/10.3115/1073083.1073135

**DOI:**https://doi.org/10.3115/1620754.1620835

**DOI:**https://doi.org/10.18653/v1/W18-6319

**DOI:**https://doi.org/10.18653/v1/P16-1162

**DOI:**https://doi.org/10.18653/v1/P16-1159,

**PMID:**27069146

**DOI:**https://doi.org/10.18653/v1/D19-1331

**DOI:**https://doi.org/10.18653/v1/D16-1206

**DOI:**https://doi.org/10.1109/TIT.1967.1054010

**DOI:**https://doi.org/10.18653/v1/D18-1342