Algorithm Search⌘K

Algorithmadvanced

CTC prefix beam search

Also called prefix beam search, CTC beam search decoding.

Beam search over output prefixes of a CTC model that merges paths giving the same prefix, tracking blank and non-blank endings.

Time
O(T W K) worst
Space
O(W K + T W) extra
Where
K = the number of output symbols with the blank; T = the number of frames; W = the beam width
Properties
deterministicnot exactonlineiterative
Origin
Awni Y. Hannun, Andrew L. Maas, Daniel Jurafsky, Andrew Y. Ng, 2014

CTC prefix beam search finds a likely label sequence from the per-frame outputs of a CTC network. Many frame-level paths collapse to the same labels, so the probability of a labeling is a sum over paths, and the best single path does not give the best labeling. The search therefore keeps label prefixes, not paths. For each prefix it stores two numbers: the probability of the paths that end in a blank, and of the paths that end in the last label. These two numbers are enough to extend the prefix by one frame exactly. A beam keeps the WW best prefixes after each frame, and a language model can be added when a label is appended.

In plain words

A CTC network gives, for every short slice of sound, how likely each letter is and how likely "nothing" (the blank) is. Many slice-by-slice outputs spell the same text: "c_aa_t" and "cc_a_tt" both spell "cat". The text you want is the one whose outputs add up to the most.

The search reads the slices one by one and keeps a short list of the best partial texts. For each partial text it remembers two totals: the outputs that end in a blank, and those that end in the last letter. The split matters for doubled letters: after "a", another "a" continues the same letter, but after "a_", another "a" starts a new one. At the end, the best text on the list is the answer. A longer list costs more time but loses less.

The problem

The input is a T×KT \times K matrix of output probabilities yt(k)y_t(k) of a CTC network, for frames t=1,…,Tt = 1, \ldots, T and symbols kk in L∪{∅}L \cup \{\varnothing\}. The blank is written ∅\varnothing in formulas, "_" in examples and index 0 in the code. The map B\mathcal{B} merges runs of equal symbols and then deletes the blanks, and

p(ℓ∣x)=∑π:B(π)=ℓ∏t=1Tyt(πt).p(\ell \mid x) = \sum_{\pi : \mathcal{B}(\pi) = \ell} \prod_{t=1}^{T} y_t(\pi_t).

The task is to find ℓ∗=arg⁡max⁡ℓ p(ℓ∣x) Λ(ℓ)\ell^* = \arg\max_\ell \, p(\ell \mid x)\, \Lambda(\ell), where Λ(ℓ)\Lambda(\ell) is an optional language model weight. Hannun et al. (2014) use Λ(W)=pLM(W)α∣W∣β\Lambda(W) = p_{\mathrm{LM}}(W)^{\alpha} |W|^{\beta} for a word sequence WW, with a weight α\alpha and an insertion bonus β\beta set on held-out data. The code here takes a hook lm(ℓ,c)\mathrm{lm}(\ell, c) that returns the log weight of appending label cc to the prefix ℓ\ell, and ln⁡Λ(ℓ)\ln \Lambda(\ell) is the sum of the hook along ℓ\ell. Without a language model, Λ=1\Lambda = 1.

The number of labelings grows exponentially in TT. With a beam that keeps every prefix the search is exact, and it then costs exponential time. With a fixed beam it is a heuristic.

The algorithm

For a prefix ℓ\ell after frame tt, b(ℓ)b(\ell) is the log probability of the paths of frames 1..t1..t that collapse to ℓ\ell and end in ∅\varnothing, and nb(ℓ)nb(\ell) the same for the paths that end in a label, which must be ℓend\ell_{\mathrm{end}}, the last label of ℓ\ell. ⊕\oplus is log_add, a⊕b=ln⁡(ea+eb)a \oplus b = \ln(e^a + e^b), and x⊕=vx \mathrel{\oplus}= v means x←x⊕vx \leftarrow x \oplus v. A missing entry of the map NN is (−∞,−∞)(-\infty, -\infty).

  1. PREFIX-BEAM-SEARCH(ln y, W, lm) ▷ ln y: T × K log outputs, ∅ = index 0, lm(ℓ, c) = 0 if no LM; ln is the natural log
  2. 1A ← { ε : (b = 0, nb = -∞) }
  3. 2for t ← 1 to T do
  4. 3N ← empty map
  5. 4for each prefix ℓ in A, with (b, nb) = A[ℓ] do
  6. 5N[ℓ].b ⊕= ln y_t(∅) + (b ⊕ nb) ▷ a blank keeps the prefix
  7. 6if ℓ ≠ ε then N[ℓ].nb ⊕= ln y_t(ℓ_end) + nb ▷ the run of the last label goes on
  8. 7for each label c do
  9. 8if c = ℓ_end then s ← b else s ← b ⊕ nb ▷ a repeated label needs a blank between
  10. 9N[ℓ c].nb ⊕= ln y_t(c) + s + lm(ℓ, c)
  11. 10A ← the W prefixes of N with the largest b ⊕ nb
  12. 11return the prefix in A with the largest b ⊕ nb, and that score

Line L8 is the reason for the two numbers. If the new label equals the last label of ℓ\ell, only the paths that end in a blank start a new copy of it; the paths that end in the label merge with it and stay in ℓ\ell (line L6). Every update accumulates with ⊕\oplus. Algorithm 1 of Hannun et al. (2014) writes some of these updates as assignments, but two different prefixes, or the same prefix by two routes, can add to the same entry, so an assignment loses probability. This is a known source of bugs.

Hannun et al. also handle a prefix ℓ+=ℓc\ell^+ = \ell c that was scored at the previous frame but pruned: when ℓ\ell makes ℓ+\ell^+ again, they add the blank and repeat continuations of the old scores of ℓ+\ell^+. The code has this as the option recover. It does not change the result of a full beam, and it can only add probability.

Example

Use the outputs of the example on the CTC page, with the alphabet {_, a, b} and T=3T = 3:

frame _ a b
1 0.5 0.4 0.1
2 0.4 0.3 0.3
3 0.3 0.1 0.6

The scores below are probabilities eb+enbe^{b} + e^{nb}; the code stores logs. With a beam of W=3W = 3:

after frame kept prefixes pruned
1 ε 0.5, a 0.4, b 0.1 none
2 a 0.43, b 0.22, ε 0.2 ab 0.12, ba 0.03
3 b 0.294, ab 0.258, a 0.176

After frame 2, the prefix "a" has b=0.16b = 0.16 (the path a_) and nb=0.27nb = 0.27 (the paths _a and aa). At frame 3, "b" collects 0.22⋅0.3=0.0660.22 \cdot 0.3 = 0.066 by a blank, 0.18⋅0.6=0.1080.18 \cdot 0.6 = 0.108 by repeating b, and 0.2⋅0.6=0.120.2 \cdot 0.6 = 0.12 from the empty prefix, so 0.294. The prefix "ab" gets only 0.43⋅0.6=0.2580.43 \cdot 0.6 = 0.258 from "a", because its own 0.12 from frame 2 was pruned. The search returns "b", which is wrong.

The exact answer is "ab" with p=0.366p = 0.366; "b" has 0.294. A full beam finds it, and so does W=4W = 4. W=2W = 2 also returns "ab", but with the score 0.258, because it pruned "b" and "ab" at frame 2. So a wider beam is not always better. With the recover option, W=2W = 2 and W=3W = 3 both return "ab" with the exact 0.366. Greedy decoding reads _ _ b and returns "b". The tests check all these numbers.

Correctness

The proof is in proofs/correctness.md. A path of tt frames that collapses to ℓ\ell comes from a path of t−1t - 1 frames in exactly one of four ways: a blank after a path of ℓ\ell; the last label again after a path of ℓ\ell that ends in that label; the last label after a path of ℓ−\ell^- that ends in a blank; or the last label after a path of ℓ−\ell^- that ends in a different label. Lines L5, L6 and L9 add exactly these four terms, so by induction on tt, with a beam that prunes nothing, bb and nbnb are exact and line L11 returns a maximizer of p(ℓ∣x)Λ(ℓ)p(\ell \mid x)\Lambda(\ell) (a theorem). With pruning, every stored value is a sum over a subset of the paths, so the returned score is a lower bound on the true score of the returned prefix. There is no guarantee about which prefix is returned (see the example).

Proof: With a beam that keeps every prefix, CTC prefix beam search returns the most probable labelingfull

We use the notation of the page. The frames are t=1,…,Tt = 1, \ldots, T, the blank is ∅\varnothing, and yt(k)y_t(k) is the output of frame tt. The map B\mathcal{B} merges runs of equal symbols and then deletes blanks. The proofs work with probabilities; the code stores natural logs, and log_add in log space is ++ on probabilities. For a prefix ℓ=ℓ1…ℓn\ell = \ell_1 \ldots \ell_n write ℓend=ℓn\ell_{\mathrm{end}} = \ell_n, write ℓ−\ell^- for ℓ\ell without its last label, and let

Λ(ℓ)=∏i=1nλ(ℓ1…ℓi−1,ℓi)\Lambda(\ell) = \prod_{i=1}^{n} \lambda(\ell_1 \ldots \ell_{i-1}, \ell_i)

be the product of the language model weights λ=elm\lambda = e^{\mathrm{lm}} along ℓ\ell, with Λ(ε)=1\Lambda(\varepsilon) = 1 for the empty prefix ε\varepsilon. Without a language model, λ=1\lambda = 1 and Λ=1\Lambda = 1.

For t≥1t \ge 1, let Pt(ℓ)P_t(\ell) be the set of paths π1…πt\pi_1 \ldots \pi_t with B(π1…πt)=ℓ\mathcal{B}(\pi_1 \ldots \pi_t) = \ell. Split it into Ptb(ℓ)P^{b}_t(\ell), the paths with πt=∅\pi_t = \varnothing, and Ptnb(ℓ)P^{nb}_t(\ell), the paths with πt≠∅\pi_t \neq \varnothing. A path in Ptnb(ℓ)P^{nb}_t(\ell) has ℓ≠ε\ell \neq \varepsilon and πt=ℓend\pi_t = \ell_{\mathrm{end}}, because the last symbol of a path that is not a blank is the last label of its collapse. Define

bt∗(ℓ)=Λ(ℓ)∑π∈Ptb(ℓ)∏τ=1tyτ(πτ),nbt∗(ℓ)=Λ(ℓ)∑π∈Ptnb(ℓ)∏τ=1tyτ(πτ).b_t^*(\ell) = \Lambda(\ell) \sum_{\pi \in P^b_t(\ell)} \prod_{\tau=1}^{t} y_\tau(\pi_\tau), \qquad nb_t^*(\ell) = \Lambda(\ell) \sum_{\pi \in P^{nb}_t(\ell)} \prod_{\tau=1}^{t} y_\tau(\pi_\tau).

At t=Tt = T, bT∗(ℓ)+nbT∗(ℓ)=Λ(ℓ) p(ℓ∣x)b_T^*(\ell) + nb_T^*(\ell) = \Lambda(\ell)\, p(\ell \mid x).

Lemma 1 (one frame). For t≥2t \ge 2, every path in Pt(ℓ)P_t(\ell) is a path π1…πt−1\pi_1 \ldots \pi_{t-1} followed by one symbol, in exactly one of these four ways:

  1. πt=∅\pi_t = \varnothing and π1…πt−1∈Pt−1(ℓ)\pi_1 \ldots \pi_{t-1} \in P_{t-1}(\ell);
  2. πt=ℓend\pi_t = \ell_{\mathrm{end}} and π1…πt−1∈Pt−1nb(ℓ)\pi_1 \ldots \pi_{t-1} \in P^{nb}_{t-1}(\ell) (the run of the last label goes on);
  3. πt=ℓend\pi_t = \ell_{\mathrm{end}} and π1…πt−1∈Pt−1b(ℓ−)\pi_1 \ldots \pi_{t-1} \in P^{b}_{t-1}(\ell^-) (a new run after a blank);
  4. πt=ℓend\pi_t = \ell_{\mathrm{end}}, ℓ−≠ε\ell^- \neq \varepsilon, ℓend≠ℓend−\ell_{\mathrm{end}} \neq \ell^-_{\mathrm{end}} and π1…πt−1∈Pt−1nb(ℓ−)\pi_1 \ldots \pi_{t-1} \in P^{nb}_{t-1}(\ell^-) (a new run right after a different label).

For t=1t = 1 the same holds with P0(ε)=P0b(ε)P_0(\varepsilon) = P_0^b(\varepsilon) holding only the empty path, and P0P_0 empty for every other prefix.

Proof. If πt=∅\pi_t = \varnothing, deleting it does not change the collapse, which gives case 1. Otherwise πt=ℓend\pi_t = \ell_{\mathrm{end}}. If πt−1=πt\pi_{t-1} = \pi_t, the last symbol joins the run before it, so the shorter path also collapses to ℓ\ell and ends in a label: case 2. If πt−1=∅\pi_{t-1} = \varnothing, the last symbol starts a new run, and the shorter path collapses to ℓ−\ell^- and ends in a blank: case 3. If πt−1\pi_{t-1} is a label different from πt\pi_t, the last symbol starts a new run after a label run, the shorter path collapses to ℓ−\ell^-, ends in a label, and that label is ℓend−=πt−1≠ℓend\ell^-_{\mathrm{end}} = \pi_{t-1} \neq \ell_{\mathrm{end}}: case 4. The cases are disjoint because they differ in πt\pi_t or in πt−1\pi_{t-1}. Conversely, each construction gives a path in Pt(ℓ)P_t(\ell), by the same reading of the runs. □\square

Theorem. If the beam width WW is at least the number of prefixes scored at every frame (for example W≥∑n=0T(K−1)nW \ge \sum_{n=0}^{T} (K-1)^n), then after frame tt, for every prefix ℓ\ell that has a path, the code holds b(ℓ)=bt∗(ℓ)b(\ell) = b_t^*(\ell) and nb(ℓ)=nbt∗(ℓ)nb(\ell) = nb_t^*(\ell). So line L11 returns a labeling ℓ\ell that maximizes Λ(ℓ) p(ℓ∣x)\Lambda(\ell)\, p(\ell \mid x), and the returned score is its exact value.

Proof. By induction on tt. Before the first frame, line L1 sets b(ε)=1b(\varepsilon) = 1 and nb(ε)=0nb(\varepsilon) = 0, which matches P0P_0. Assume the claim after frame t−1t - 1. No prefix is pruned, so the map AA holds every prefix that has a path of length t−1t-1, and every other prefix has b∗=nb∗=0b^* = nb^* = 0 at t−1t - 1. Lines L4 to L9 add, for every ℓ\ell in AA:

  • to b(ℓ)b(\ell) the term yt(∅)(b(ℓ)+nb(ℓ))y_t(\varnothing)(b(\ell) + nb(\ell)), which is case 1 (line L5);
  • to nb(ℓ)nb(\ell) the term yt(ℓend) nb(ℓ)y_t(\ell_{\mathrm{end}})\, nb(\ell), which is case 2 (line L6);
  • to nb(ℓc)nb(\ell c) for every label cc the term yt(c) s λ(ℓ,c)y_t(c)\, s\, \lambda(\ell, c), with s=b(ℓ)s = b(\ell) if c=ℓendc = \ell_{\mathrm{end}} and s=b(ℓ)+nb(ℓ)s = b(\ell) + nb(\ell) otherwise (lines L8 and L9). For the prefix ℓc\ell c, whose ℓc−\ell c^- is ℓ\ell, this is case 3 plus, when c≠ℓendc \neq \ell_{\mathrm{end}}, case 4.

Each case of Lemma 1 for each prefix of frame tt is added exactly once, from the unique prefix it names. Cases 1 and 2 keep the prefix, so the factor Λ(ℓ)\Lambda(\ell) carries over. Cases 3 and 4 extend ℓ−\ell^- by ℓend\ell_{\mathrm{end}} and multiply by λ(ℓ−,ℓend)\lambda(\ell^-, \ell_{\mathrm{end}}), and Λ(ℓ−)λ(ℓ−,ℓend)=Λ(ℓ)\Lambda(\ell^-)\lambda(\ell^-, \ell_{\mathrm{end}}) = \Lambda(\ell). By Lemma 1 and the induction hypothesis the sums are bt∗(ℓ)b_t^*(\ell) and nbt∗(ℓ)nb_t^*(\ell). The step of the option recover adds nothing here, because it acts only on prefixes that were pruned. At t=Tt = T, line L11 picks the largest b+nb=Λ(ℓ) p(ℓ∣x)b + nb = \Lambda(\ell)\, p(\ell \mid x). □\square

Proposition (a narrow beam gives a lower bound). For any beam width, every value b(ℓ)b(\ell) and nb(ℓ)nb(\ell) that the code holds after frame tt is at most bt∗(ℓ)b_t^*(\ell) and nbt∗(ℓ)nb_t^*(\ell). In particular, the returned score is at most Λ(ℓ) p(ℓ∣x)\Lambda(\ell)\, p(\ell \mid x) of the returned ℓ\ell, which is at most the optimum.

Proof. By induction on tt, the stored values are sums over subsets of the four cases of Lemma 1: pruning removes whole prefixes from AA, which removes the terms that come from them, and adds nothing. The recover step adds, for a pruned prefix ℓ+\ell^+ that is made again from its parent, the terms of cases 1 and 2 of ℓ+\ell^+ computed from its values at frame t−1t - 1, which by induction are at most the true values. These cases are not added anywhere else in that frame, because ℓ+\ell^+ is not in AA. All terms are non-negative, so a subset gives a smaller or equal sum. □\square

The proposition says nothing about which labeling a narrow beam returns, and no such guarantee holds: the page and the tests give an example where a beam of 3 returns the wrong labeling while beams of 2 and 4 return the right one.

Complexity

Each frame touches at most WW prefixes and does O(K)O(K) log_add operations for each one, so it scores at most WKW K entries. Selecting the best WW of them takes O(WK)O(W K) time with a linear time top-k selection, or O(WKlog⁡(WK))O(W K \log(W K)) with a sort, as in the code. The total is O(TWK)O(T W K) log_add operations in the word-RAM model, plus the selection, plus the language model calls. Storing prefixes as nodes of a trie makes each extension O(1)O(1); the code uses tuples, which costs O(n)O(n) for a prefix of length nn. The map of a frame has at most WKW K entries, and the trie of the kept prefixes has at most TWT W nodes, which gives the space bound.

In practice the beam is large: Hannun et al. used W=200W = 200 over a character alphabet. Frames where the blank has almost all the probability can be skipped, and symbols with a very small yt(c)y_t(c) can be left out of line L7.

Properties

  • Exact with a full beam. It returns the most probable labeling (a theorem). The number of prefixes is then exponential in TT.
  • Not exact with a finite beam. It may return a wrong labeling, and the error is not monotone in WW (the example).
  • Better than greedy decoding in practice. Greedy decoding returns the labeling of the most probable path, which is not in general the most probable labeling (Graves et al. 2006, Section 3.2). A beam of 1 is not the same as greedy decoding, because it ranks by the summed probability of the prefix.
  • Online. It reads one frame at a time and can output the common part of the prefixes in the beam while the audio arrives.
  • Language model at word ends. With a word language model, Hannun et al. apply pLMp_{\mathrm{LM}} when a space is appended, so the weight of a word is known only when the word ends.

Variants and improvements

  • Prefix search decoding (Graves et al. 2006) expands the most probable prefix first and stops when no prefix can beat the best complete one. It is exact but can take exponential time; they also split the output at frames where the blank is very likely.
  • Shallow fusion. Adding the language model inside the search, as here, is shallow fusion. Rescoring an n-best list or a word lattice with a larger model is the other option.
  • WFST decoding. Compose a CTC token transducer with a lexicon and a grammar and run a time-synchronous beam search over the graph.
  • CTC prefix scores in attention decoding. Joint CTC-attention decoding scores each output prefix of an attention decoder with the CTC prefix probability (Watanabe et al. 2017).
  • Transducer beam search. The RNN transducer has its own beam search with a similar merge of prefixes, but its label probabilities depend on the prefix.

When to use it

Use it to decode a CTC model when a language model is available or when greedy decoding is not accurate enough. On the Wall Street Journal eval92 test set, Hannun et al. measured a word error rate of 35.8% without a language model, 24.4% with a dictionary constraint and 14.1% with a bigram language model, at a beam of 200 (their Table 1). If no language model is used and the outputs are peaky, greedy decoding is much cheaper and often nearly as good.

Pitfalls

  • Assignment instead of accumulation. Every update of bb and nbnb must add. Several prefixes and several routes add to the same entry.
  • The repeated label. Extending ℓ\ell by ℓend\ell_{\mathrm{end}} uses only b(ℓ)b(\ell). Using b⊕nbb \oplus nb makes "a a" read as "aa" and counts the same paths twice.
  • Pruning prefixes of probability 0. A prefix with more repeats than the frames allow has score −∞-\infty. Keep it out of the beam, or a small beam fills up with dead prefixes.
  • Unnormalized language model weights. With α\alpha and β\beta, the score is no longer a probability, and the best labeling depends on both. Tune them on held-out data.
  • Comparing prefixes of different lengths. Long prefixes collect more language model penalties; without the insertion bonus β\beta the search prefers short outputs. See length normalization.

Implementations

The code takes the per-frame output distributions of the network as given and implements the prefix beam search with an optional language model hook and the recover step; it does not train a network. The tests compare a full beam with exhaustive search over all labelings for T≤6T \le 6 and K≤3K \le 3, with and without a bigram language model.

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.

ctc_prefix_beam_search.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ctc-prefix-beam-search/. The authors are listed in prov/NXHD7B.jsonl.

"""CTC prefix beam search, in log space.

The input is a T x K matrix of log outputs ln y_t(k) of a CTC network. Symbol 0
is the blank, written ∅ on the page and "_" in its examples. A prefix is a
tuple of labels (symbols 1..K-1). For each prefix l the search keeps two log
probabilities:

    b(l)   the total probability of the frame paths so far that collapse to l
           and end in a blank,
    nb(l)  the same for the paths that end in a label (the last label of l).

Their log_add is the probability of l given the frames read so far. A
repeated label needs a blank between its two copies, so extending l by its own
last label uses only b(l), while the paths of nb(l) that read the same label
again stay in l.

An optional language model hook lm(prefix, c) returns the log weight added when
label c is appended to prefix (for example alpha * ln p_LM(c | prefix) + beta).
The search ranks the prefixes by b + nb (log_add) with the weights included.
Every probability is accumulated with log_add. Hannun et al. (2014), Algorithm 1,
write some of these updates as plain assignments, which loses probability.

The code takes the network outputs as given. All logs are natural logs.
"""

import itertools
from typing import Callable, Dict, List, Optional, Sequence, Tuple

from nlslog import NEG_INF, log_add, log_sum

BLANK = 0
Prefix = Tuple[int, ...]


def _no_lm(prefix: Prefix, c: int) -> float:
    return 0.0


def prefix_beam_search(
    log_y: Sequence[Sequence[float]],
    beam: int,
    lm: Optional[Callable[[Prefix, int], float]] = None,
    blank: int = BLANK,
    recover: bool = False,
) -> Tuple[Prefix, float, List[Tuple[Prefix, float]]]:
    """Return (best prefix, its log score, the final beam as (prefix, log score) pairs).

    beam is the number of prefixes kept after each frame. Ties are broken by the
    smaller prefix tuple, so the result does not depend on the order of a dict.

    With recover=True, a prefix l+ that was scored at the previous frame but
    pruned, and is now made again from its parent l, also gets the paths that
    continue its old b and nb (a blank, or its own last label again). This is
    the "l+ not in A_prev" step of Hannun et al. (2014), Algorithm 1. With a
    beam that keeps everything it changes nothing.
    """
    if beam < 1:
        raise ValueError("the beam must keep at least one prefix")
    if len(log_y) == 0:
        raise ValueError("need at least one frame")
    lm = lm or _no_lm
    K = len(log_y[0])
    labels = [c for c in range(K) if c != blank]
    A: Dict[Prefix, Tuple[float, float]] = {(): (0.0, NEG_INF)}  # @line L1
    scored: Dict[Prefix, List[float]] = {}  # every prefix of the previous frame, before pruning
    for row in log_y:  # @line L2
        N: Dict[Prefix, List[float]] = {}  # @line L3

        def acc(p: Prefix, which: int, v: float) -> None:
            cell = N.setdefault(p, [NEG_INF, NEG_INF])
            cell[which] = log_add(cell[which], v)

        for l, (b, nb) in A.items():  # @line L4
            acc(l, 0, row[blank] + log_add(b, nb))  # @line L5
            if l:
                acc(l, 1, row[l[-1]] + nb)  # @line L6
            for c in labels:  # @line L7
                s = b if (l and c == l[-1]) else log_add(b, nb)  # @line L8
                acc(l + (c,), 1, row[c] + s + lm(l, c))  # @line L9
                lp = l + (c,)
                if recover and lp not in A and lp in scored:
                    ob, onb = scored[lp]
                    acc(lp, 0, row[blank] + log_add(ob, onb))
                    acc(lp, 1, row[c] + onb)
        scored = N
        ranked = sorted(N.items(), key=lambda kv: (-log_add(kv[1][0], kv[1][1]), kv[0]))
        A = {p: (v[0], v[1]) for p, v in ranked[:beam]}  # @line L10
    final = sorted(((p, log_add(b, nb)) for p, (b, nb) in A.items()), key=lambda x: (-x[1], x[0]))
    best, score = final[0]  # @line L11
    return best, score, final


def collapse(path: Sequence[int], blank: int = BLANK) -> Prefix:
    """The CTC map B: merge runs of equal symbols, then drop blanks."""
    out = []
    prev = None
    for k in path:
        if k != prev and k != blank:
            out.append(k)
        prev = k
    return tuple(out)


def greedy_decode(log_y: Sequence[Sequence[float]], blank: int = BLANK) -> Prefix:
    """Best path decoding: the best symbol per frame (first on ties), then B."""
    return collapse([max(range(len(r)), key=lambda k: (r[k], -k)) for r in log_y], blank)


def lm_log_weight(prefix: Prefix, lm: Optional[Callable[[Prefix, int], float]] = None) -> float:
    """The sum of the hook weights for building prefix label by label."""
    if lm is None:
        return 0.0
    return sum(lm(prefix[:i], prefix[i]) for i in range(len(prefix)))


def exhaustive_scores(
    log_y: Sequence[Sequence[float]],
    lm: Optional[Callable[[Prefix, int], float]] = None,
    blank: int = BLANK,
) -> Dict[Prefix, float]:
    """Every labeling with nonzero probability and its log score
    ln p(l | x) + lm_log_weight(l), by summing over all K^T frame paths.
    Only for small T and K."""
    T, K = len(log_y), len(log_y[0])
    terms: Dict[Prefix, List[float]] = {}
    for path in itertools.product(range(K), repeat=T):
        terms.setdefault(collapse(path, blank), []).append(sum(log_y[t][k] for t, k in enumerate(path)))
    return {l: log_sum(v) + lm_log_weight(l, lm) for l, v in terms.items()}


def exhaustive_best(
    log_y: Sequence[Sequence[float]],
    lm: Optional[Callable[[Prefix, int], float]] = None,
    blank: int = BLANK,
) -> Tuple[Prefix, float]:
    """The labeling with the largest score, by exhaustive search (ties: smaller tuple)."""
    scores = exhaustive_scores(log_y, lm, blank)
    best = min(scores, key=lambda l: (-scores[l], l))
    return best, scores[best]
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_ctc_prefix_beam_search.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ctc-prefix-beam-search/. The authors are listed in prov/NXHD7B.jsonl.

import math
import random

import pytest

import nlslog
from ctc_prefix_beam_search import (
    collapse,
    exhaustive_best,
    exhaustive_scores,
    greedy_decode,
    lm_log_weight,
    prefix_beam_search,
)
from nlslog import log_add, log_sum

# The example of the page: symbols _ (blank, 0), a (1), b (2), T = 3 frames.
Y = [[0.5, 0.4, 0.1], [0.4, 0.3, 0.3], [0.3, 0.1, 0.6]]
LY = [[math.log(p) for p in row] for row in Y]
A, B = 1, 2
WIDE = 10 ** 6


def random_log_y(rng, T, K):
    rows = [[rng.random() + 0.05 for _ in range(K)] for _ in range(T)]
    return [[math.log(x / sum(r)) for x in r] for r in rows]


def bigram_lm(table):
    """A label bigram hook: lm(prefix, c) = ln table[last label or 0][c]."""

    def lm(prefix, c):
        return math.log(table[prefix[-1] if prefix else 0][c])

    return lm


def test_helper_header():
    with open(nlslog.__file__, encoding="utf-8") as f:
        lines = f.read().splitlines()
    assert lines[1] == "# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/."


def test_log_add_check_value():
    assert log_add(math.log(0.5), math.log(0.25)) == pytest.approx(-0.287682, abs=1e-6)


def test_collapse():
    assert collapse([A, A, 0, A, B, 0]) == (A, A, B)
    assert collapse([0, 0]) == ()


def test_page_example_full_beam_is_exact():
    best, score, final = prefix_beam_search(LY, WIDE)
    assert best == (A, B)
    assert math.exp(score) == pytest.approx(0.366, abs=1e-12)
    want = {(A, B): 0.366, (B,): 0.294, (A,): 0.176, (): 0.06, (B, A): 0.034, (B, B): 0.024}
    got = dict(final)
    for prefix, p in want.items():
        assert math.exp(got[prefix]) == pytest.approx(p, abs=1e-12)
    # The final scores of a full beam are the exact labeling probabilities, which sum to 1.
    assert log_sum([s for _, s in final]) == pytest.approx(0.0, abs=1e-12)


def test_page_example_beam_trace():
    _, _, beam1 = prefix_beam_search(LY[:1], 3)
    _, _, beam2 = prefix_beam_search(LY[:2], 3)
    assert [(p, round(math.exp(s), 12)) for p, s in beam1] == [((), 0.5), ((A,), 0.4), ((B,), 0.1)]
    assert [(p, round(math.exp(s), 12)) for p, s in beam2] == [((A,), 0.43), ((B,), 0.22), ((), 0.2)]


def test_greedy_differs_from_the_most_probable_labeling():
    assert greedy_decode(LY) == (B,)
    assert exhaustive_best(LY)[0] == (A, B)


def test_narrow_beams_can_be_wrong():
    # Beam 3 prunes "ab" (0.12) after frame 2 and returns "b" (0.294) instead of "ab" (0.366).
    best, score, _ = prefix_beam_search(LY, 3)
    assert best == (B,)
    assert math.exp(score) == pytest.approx(0.294, abs=1e-12)
    # Beam 2 returns the right labeling, but with a score that misses the pruned paths.
    best, score, _ = prefix_beam_search(LY, 2)
    assert best == (A, B)
    assert math.exp(score) == pytest.approx(0.258, abs=1e-12)
    # Beam 1 returns "b" with the probability of one path only.
    best, score, _ = prefix_beam_search(LY, 1)
    assert best == (B,) and math.exp(score) == pytest.approx(0.12, abs=1e-12)
    # A wider beam is not always better: 2 is right here, 3 is wrong, 4 is exact.
    assert prefix_beam_search(LY, 4)[0] == (A, B)


def test_recovery_of_pruned_prefixes():
    # The "l+ not in A_prev" step of Hannun et al. gets back the 0.108 that beam 3 lost.
    best, score, _ = prefix_beam_search(LY, 3, recover=True)
    assert best == (A, B) and math.exp(score) == pytest.approx(0.366, abs=1e-12)
    best, score, _ = prefix_beam_search(LY, 2, recover=True)
    assert best == (A, B) and math.exp(score) == pytest.approx(0.366, abs=1e-12)


def test_full_beam_against_exhaustive_search():
    rng = random.Random(2)
    for _ in range(80):
        T, K = rng.randint(1, 6), rng.randint(2, 3)
        ly = random_log_y(rng, T, K)
        scores = exhaustive_scores(ly)
        ranked = sorted(scores.values(), reverse=True)
        if len(ranked) > 1 and ranked[0] - ranked[1] < 1e-9:
            continue  # a tie; either answer is right
        best, score, final = prefix_beam_search(ly, WIDE, recover=rng.random() < 0.5)
        assert best == exhaustive_best(ly)[0]
        assert score == pytest.approx(scores[best], abs=1e-10)
        for prefix, s in final:
            if s == float("-inf"):
                assert prefix not in scores  # a prefix with too many repeats for T frames
            else:
                assert s == pytest.approx(scores[prefix], abs=1e-10)


def test_full_beam_with_a_language_model_against_exhaustive_search():
    rng = random.Random(4)
    for _ in range(60):
        T, K = rng.randint(1, 5), 3
        ly = random_log_y(rng, T, K)
        table = [[rng.random() + 0.05 for _ in range(K)] for _ in range(K)]
        lm = bigram_lm(table)
        scores = exhaustive_scores(ly, lm)
        ranked = sorted(scores.values(), reverse=True)
        if len(ranked) > 1 and ranked[0] - ranked[1] < 1e-9:
            continue
        best, score, _ = prefix_beam_search(ly, WIDE, lm=lm)
        assert best == exhaustive_best(ly, lm)[0]
        assert score == pytest.approx(scores[best], abs=1e-10)
        assert lm_log_weight(best, lm) == pytest.approx(sum(lm(best[:i], best[i]) for i in range(len(best))), abs=1e-12)


def test_language_model_changes_the_answer():
    # An LM that makes "b" after "a" very likely and "b" at the start unlikely.
    table = [[1.0, 0.5, 0.01], [1.0, 0.1, 0.9], [1.0, 0.5, 0.5]]
    lm = bigram_lm(table)
    assert prefix_beam_search(LY, WIDE, lm=lm)[0] == (A, B)
    table = [[1.0, 0.9, 0.9], [1.0, 0.05, 0.05], [1.0, 0.5, 0.5]]
    lm = bigram_lm(table)
    best, _, _ = prefix_beam_search(LY, WIDE, lm=lm)
    assert best == exhaustive_best(LY, lm)[0] == (B,)


def test_narrow_beam_is_never_better_than_the_optimum():
    rng = random.Random(9)
    wrong = 0
    for _ in range(60):
        T, K = rng.randint(2, 6), 3
        ly = random_log_y(rng, T, K)
        _, opt = exhaustive_best(ly)
        best, score, _ = prefix_beam_search(ly, 2)
        # A pruned search only drops paths, so its score is at most the true probability.
        assert score <= exhaustive_scores(ly)[best] + 1e-12 <= opt + 1e-12
        wrong += best != exhaustive_best(ly)[0]
    assert wrong > 0


def test_errors():
    with pytest.raises(ValueError):
        prefix_beam_search(LY, 0)
    with pytest.raises(ValueError):
        prefix_beam_search([], 4)

History

Graves et al. (2006) defined best path decoding and prefix search decoding for CTC and showed that the first is not exact. Hannun, Maas, Jurafsky and Ng (2014) gave the prefix beam search with an n-gram language model, which made a CTC network without an HMM competitive for large vocabulary recognition. The CTC prefix probability later became a score inside attention decoders (Watanabe et al. 2017).

References

  1. The prefix beam search with a language model and an insertion bonus, Section 3 (decoding, eqs. 7 to 9), Algorithm 1 and Table 1
  2. Alex Graves, Santiago Fernández, Faustino Gomez and Jürgen Schmidhuber, Connectionist temporal classification: labelling unsegmented sequence data with recurrent neural networks, ICML 2006, pages 369 to 376, Section 3.2 (best path decoding and prefix search decoding)
  3. Shinji Watanabe, Takaaki Hori, Suyoun Kim, John R. Hershey and Tomoki Hayashi, Hybrid CTC/attention architecture for end-to-end speech recognition, IEEE Journal of Selected Topics in Signal Processing 11(8), 2017, pages 1240 to 1253, the section on joint decoding with the CTC prefix score

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example