Algorithm Search⌘K

Algorithmcore

Time-synchronous Viterbi beam search

Also called Viterbi beam search, one-pass decoding.

Decode speech frame by frame, keeping only states whose score is within a beam of the best, with word ends feeding word starts.

Time
O(n k V log k) worst
Space
O(s + n k) extra
Where
V = the vocabulary size; k = the limit on active hypotheses per frame (at least V); n = the number of frames; s = the number of nodes of the prefix tree
Properties
deterministicnot exactonlineiterative
Origin
Hermann Ney, Dieter Mergel, Andreas Noll, Horst Paeseler, 1992

Time-synchronous Viterbi beam search is the standard first-pass decoder of HMM-based speech recognition. It runs the Viterbi algorithm over the HMM states of all words at once, one frame at a time. When a word ends, its score, plus the language model score of the word, starts the first states of the next words. After each frame it drops every hypothesis whose score is more than a fixed beam below the best one, and often keeps only the best kk. The pruning makes large vocabularies possible, and it also means the search can miss the best word sequence. With no pruning it finds the best path exactly, and token passing finds the same path, since it is the same search described as messages on a network.

In plain words

You hear the speech one short frame at a time. For each frame you keep a list of guesses: where in which word you are now, and how good the guess is so far. To go to the next frame, each guess can stay in its sound, move to the next sound, or finish its word and start a new one.

Two guesses that reach the same place keep only the better one. Then you throw away every guess that is far worse than the best. At the end you take the best guess that has just finished a word and follow its links back to read the words.

The problem

The input is a sequence of nn frames, an acoustic model that gives the log score et(j)e_t(j) of HMM state jj at frame tt, a pronunciation lexicon that turns each word into states, and a bigram language model log⁡p(w∣v)\log p(w \mid v). The task is the word sequence W=w1⋯wKW = w_1 \cdots w_K and state path that maximize

log⁡pac+λlog⁡plm(W)+∣W∣log⁡ip,\log p_{ac} + \lambda \log p_{lm}(W) + |W| \log ip,

where log⁡pac\log p_{ac} is the sum of the emission and transition log scores of the path, plm(W)p_{lm}(W) includes the start ⟨s⟩\langle s \rangle and the end ⟨/s⟩\langle /s \rangle, λ\lambda is the language model weight and ipip is the word insertion penalty. λ\lambda and ipip are heuristics tuned on held-out data, not parts of a probability model. The code writes log⁡ip\log ip as one additive number per word.

In the code each phone is one HMM state with a self loop of log probability ℓ\ell and a forward move of log probability ff, and the exit from the last phone of a word is a forward move too. A real system uses three states per phone, but the search is the same.

The algorithm

The phones of the words form a prefix tree (trie), so that words that begin with the same phones share their first states. A hypothesis is a pair (previous word vv, tree node qq) with a score and a back pointer. Keeping vv in the key gives one copy of the tree per previous word, so the bigram score log⁡p(w∣v)\log p(w \mid v), added when ww ends, is the right one. A word-end record (word, end frame, score, back pointer) remembers each word end for the traceback.

  1. TIME-SYNCHRONOUS-BEAM-SEARCH(tree, lm, e, n)
  2. 1H ← {(⟨s⟩, c) ↦ e_0(c) for each child c of the root}
  3. 2for t ← 0 to n - 1 do
  4. 3PRUNE(H): drop h with score(h) < best - beam; keep at most k best
  5. 4E ← {} ▷ word ends at frame t
  6. 5for each (v, q) ∈ H and each word w that ends at q: E[w] ← max(E[w], score + f + λ log p(w | v) + log ip)
  7. 6if t = n - 1 then exit the loop
  8. 7for each (v, q) ∈ H: relax (v, q) with score + ℓ + e_{t+1}(q), and (v, c) with score + f + e_{t+1}(c) for each child c
  9. 8for each w ∈ E and each child c of the root: relax (w, c) with E[w] + e_{t+1}(c)
  10. 9H ← the relaxed hypotheses of frame t + 1
  11. 10return the w ∈ E with the best E[w] + λ log p(⟨/s⟩ | w), and trace back its records

"Relax" keeps the larger score for a key, with its back pointer: this is the Viterbi recombination. Line L5 recombines the word ends per word and frame, which is enough for a bigram, because the future depends only on the last word.

Example

The lexicon has the two words AB=(a,b)AB = (a, b) and CD=(c,d)CD = (c, d), with equal bigram scores (all 0), λ=1\lambda = 1, log⁡ip=0\log ip = 0, and ℓ=f=ln⁡0.5≈−0.693\ell = f = \ln 0.5 \approx -0.693. There are two frames:

frame aa bb cc dd
0 −1-1 −9-9 −2-2 −9-9
1 −9-9 −5-5 −9-9 −1-1

With no pruning, frame 0 has the hypotheses aa at −1-1 and cc at −2-2. At frame 1, a→ba \to b gives −1−0.693−5=−6.693-1 - 0.693 - 5 = -6.693 and c→dc \to d gives −2−0.693−1=−3.693-2 - 0.693 - 1 = -3.693. The word ends add the exit ff: ABAB ends at −7.386-7.386 and CDCD at −4.386-4.386. The search returns CDCD, which is the best path.

With a beam of 0.5, line L3 at frame 0 drops cc, since −2<−1−0.5-2 < -1 - 0.5. Only ABAB can end, and the search returns ABAB at −7.386-7.386, which is 3 worse than the best path. A histogram limit of k=1k = 1 fails in the same way. A beam of 1.0 keeps cc and finds CDCD. The first frame favors the wrong word, and a narrow beam cannot recover from that.

Correctness

With no pruning, the search is the Viterbi algorithm on one large HMM: the tree copies with the word-end transitions between them. A hypothesis key (previous word, node) holds everything the future score depends on with a bigram, so keeping only the best score per key loses no optimal path. The best word-end record at the last frame, plus the end score, is then the best path. The tests check this against exhaustive search over all word sequences of at most 5 words and all their segmentations into frames.

With pruning, there is no guarantee. Line L3 can drop the prefix of the best path when that prefix is worse than other prefixes at some frame, as in the example. The returned score is always the score of a real path, so it is never better than the best one.

Proof: Without pruning, time-synchronous beam search finds the best pathfull

We use the notation of the page. A full path for nn frames is a word sequence W=w1⋯wKW = w_1 \cdots w_K with K≥1K \ge 1 and a segmentation that gives each phone of w1,…,wKw_1, \ldots, w_K in order at least one frame, nn frames in all. Its score SS is the sum of

  • the emission score et(phone at t)e_t(\text{phone at } t) of every frame tt;
  • (d−1)ℓ+f(d - 1)\ell + f for each phone that occupies dd frames (the last phone of a word pays ff for the word exit);
  • λlog⁡p(wk∣wk−1)+log⁡ip\lambda \log p(w_k \mid w_{k-1}) + \log ip for each word, with w0=⟨s⟩w_0 = \langle s \rangle;
  • λlog⁡p(⟨/s⟩∣wK)\lambda \log p(\langle /s \rangle \mid w_K).

The search returns the best full path, or nothing if no full path has a finite score. The tree lexicon gives each prefix of a pronunciation one node, so "phone jj of word ww" is a node qq of the tree, and ww ends at qq when jj is its last phone.

Lemma 1 (what a hypothesis means). With no pruning, after line L1 (for t=0t = 0) or line L9 (for t≥1t \ge 1), the hypothesis (v,q)(v, q) at frame tt has the score

Ht(v,q)=max⁡ of the partial score of a prefix of a full path that has finished the words up to v and is in node q at frame t,H_t(v, q) = \max \text{ of the partial score of a prefix of a full path that has finished the words up to } v \text{ and is in node } q \text{ at frame } t,

where the partial score counts everything above that is fixed by frames 0,…,t0, \ldots, t: the emissions of these frames, the transitions between them, and the language model and penalty terms of the finished words. A key that no such prefix reaches is absent. Also, after line L5 at frame tt,

Et(w)=max⁡ of the partial score of a prefix that ends word w at frame t, including its exit f and its terms λlog⁡p(w∣⋅)+log⁡ip.E_t(w) = \max \text{ of the partial score of a prefix that ends word } w \text{ at frame } t, \text{ including its exit } f \text{ and its terms } \lambda \log p(w \mid \cdot) + \log ip.

Proof. Induction on tt. At t=0t = 0 the prefix has read one frame, has finished no word, and sits in a first phone cc of some word, a child of the root. Its score is e0(c)e_0(c), which is line L1.

Line L5 at frame tt: a prefix that ends ww at tt is in the last node qq of ww at tt, after some previous word vv, and adds f+λlog⁡p(w∣v)+log⁡ipf + \lambda \log p(w \mid v) + \log ip. These additions depend only on (v,q)(v, q) and ww, so the best such prefix extends the best prefix for (v,q)(v, q), which is Ht(v,q)H_t(v, q). Line L5 takes the maximum over all (v,q)(v, q).

Lines L7 and L8 for frame t+1t + 1: a prefix in node q′q' at t+1t + 1 after vv got there in one of three ways. It stayed in q′q' (self loop ℓ\ell), it moved from the parent of q′q' in the same word (ff), or q′q' is a first phone, and the prefix ended vv at frame tt. In each case the added score, the transition plus et+1(q′)e_{t+1}(q'), depends only on the key at frame tt (or the ended word vv) and on q′q'. So the best prefix for (v,q′)(v, q') extends the best prefix of one of these three kinds, which are Ht(v,q′)H_t(v, q'), Ht(v,parent)H_t(v, \text{parent}) and Et(v)E_t(v). Line L7 covers the first two and line L8 the third, and "relax" keeps the maximum. □\square

Theorem (exact without pruning). With an infinite beam and no histogram limit, the search returns a full path with the best score S∗S^*.

Proof. A full path ends its last word wKw_K at frame n−1n - 1. Its score is its partial score at the word end plus λlog⁡p(⟨/s⟩∣wK)\lambda \log p(\langle /s \rangle \mid w_K). By Lemma 1, the best partial score of a prefix that ends ww at frame n−1n - 1 is En−1(w)E_{n-1}(w), so line L10 computes max⁡wEn−1(w)+λlog⁡p(⟨/s⟩∣w)=S∗\max_w E_{n-1}(w) + \lambda \log p(\langle /s \rangle \mid w) = S^*. The back pointers store, for each hypothesis and word end, the record of the word end it came from, so the traceback reads the words of a path that has this score. □\square

Why the key is enough. The proof uses that the future of a prefix, all terms added after frame tt, depends only on the key (v,q)(v, q). This holds for a bigram because the next language model term depends only on vv. With a trigram the key would need two words, and keeping only (v,q)(v, q) would merge prefixes with different futures.

Proposition (pruning). With any beam or histogram limit, the returned score is the score of a full path, so it is at most S∗S^*. It can be smaller.

Proof. Pruning removes entries from HH and never changes the score of a kept entry, so every score that the search computes is still the partial score of a real prefix, and the returned one is the score of a real full path. For the second claim, take the example of the page: words AB=(a,b)AB = (a, b) and CD=(c,d)CD = (c, d), all language model terms 0, ℓ=f=ln⁡0.5\ell = f = \ln 0.5, and the emissions e0=(a:−1,c:−2)e_0 = (a{:}{-1}, c{:}{-2}), e1=(b:−5,d:−1)e_1 = (b{:}{-5}, d{:}{-1}), with all other emissions −9-9. The best full path is CDCD with −3+2ln⁡0.5-3 + 2 \ln 0.5. A beam of 0.5 removes (⟨s⟩,c)(\langle s \rangle, c) at frame 0, since −2<−1−0.5-2 < -1 - 0.5, and no other hypothesis can reach the end of CDCD in two frames. The search returns ABAB with −6+2ln⁡0.5-6 + 2 \ln 0.5. □\square

Complexity

Let nn be the number of frames, VV the vocabulary size, ss the number of nodes of the tree and k≥Vk \ge V the histogram limit. At each frame, each of the at most kk hypotheses has its self loop and at most VV children (line L7), and at most VV word ends each start at most VV first phones (line L8). That gives O(kV)O(k V) new hypotheses per frame, and O(nkV)O(n k V) for the whole utterance, plus the top-kk selection at line L3. With a heap, the selection costs O(kVlog⁡k)O(k V \log k) per frame, which gives O(nkVlog⁡k)O(n k V \log k). With linear-time top-k selection, it is O(nkV)O(n k V). Without a histogram limit, kk grows to sVs V, the size of all the tree copies.

The extra space is O(s)O(s) for the tree and O(nk)O(n k) for the word-end records that the traceback needs. A system that keeps only the records on surviving paths, or a lattice, uses less.

Properties

  • Not exact. The beam and the histogram limit can drop the best path. With no pruning it is exact.
  • Online. It reads each frame once, in order, so it can run while the speaker talks. The traceback at the end is short, and partial results can be read from the best hypothesis.
  • Deterministic. Ties are broken in a fixed order.
  • Same as token passing. Token passing computes the same scores and finds the same best path when nothing is pruned.

Variants and improvements

  • Language model look-ahead. In a tree, the word is known only at the leaf. Look-ahead adds the best language model score of the words below each node early, so pruning sees it sooner (Ney and Ortmanns 1999).
  • A static graph. Compile the HMMs, lexicon and language model into one HCLG decoding graph, so that the search only follows arcs and does not build tree copies.
  • Word-end and phone-start pruning. Use a separate, narrower beam at word ends, where many hypotheses start at once.
  • Lattice output. Keep several word-end records per frame, not only the best per word, to output a word lattice.
  • Longer histories. With a trigram, the key must hold two previous words, which multiplies the tree copies. Rescoring a lattice with the long model is often cheaper (lattice rescoring).

When to use it

Use it as the first pass of an HMM-based recognizer with a large vocabulary, when it must run as fast as or faster than the speech. Tune the beam on held-out data: a wider beam makes fewer search errors and runs slower. Use stack decoding only when a good estimate of the rest of the utterance is cheap, and a static graph when memory allows.

Pitfalls

  • Search errors. A narrow beam can drop the right words early, as in the example. Measure the search errors by comparing with a wider beam.
  • Late language model scores. With a tree lexicon and no look-ahead, the language model score arrives only at the word end, so the beam prunes on acoustics alone inside words.
  • Wrong recombination. If the key does not hold the language model history, recombination merges hypotheses with different futures, and the result is no longer the Viterbi path even without pruning.
  • Scale of the scores. The beam is in log units of the total score, so changing λ\lambda or the acoustic scale changes what a given beam means.
  • Insertion penalty sign. A positive log⁡ip\log ip favors many short words, and a negative one favors few long words.

Implementations

The Python code searches a prefix tree of one-state phones with tree copies per previous word, a bigram, a beam and a histogram limit, and traces back the words and their end frames. The tests compare the score with exhaustive search over all word sequences of at most 5 words and all segmentations, on random lexicons and bigrams with homophones and words that are prefixes of other words. They check that a narrow beam and k=1k = 1 return ABAB in the example, that pruning never gives a better score than no pruning, and that the bigram after each word stays separate.

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.

nlslog.pyI0RawGitHub
# 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
time_synchronous_beam_search.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/time-synchronous-beam-search/. The authors are listed in prov/6JVTAP.jsonl.

"""Time-synchronous Viterbi beam search with a lexical prefix tree and a bigram.

The words are given by a lexicon word -> tuple of phones (one pronunciation per
word). To keep the code short, each phone is one emitting HMM state with a self
loop; a real system has three states per phone and context-dependent models,
and only the tree gets bigger. The phones of all words share one prefix tree,
so words that start alike share their first states.

Scores are log probabilities, higher is better. For a word sequence
w_1 ... w_K and a segmentation in which phone j of the whole sequence occupies
d_j >= 1 frames, the score is

    sum over frames of the emission log score of the phone at that frame
  + sum over phones of ((d_j - 1) * loop + fwd)        (fwd is also the word exit)
  + sum over k of (lm_weight * lm(w_{k-1}, w_k) + ip)  with w_0 = <s>
  + lm_weight * lm(w_K, </s>).

The search finds the best (word sequence, segmentation) pair when nothing is
pruned. A hypothesis is a pair (previous word, tree node): the tree is copied
per previous word, so the bigram score added at the word end is the right one,
and Viterbi recombination of hypotheses with the same key is exact. Word ends
are recombined per word and frame.

Pruning: a beam (drop hypotheses more than beam below the best of the frame)
and a histogram limit (keep at most max_active hypotheses). With pruning the
search can miss the best path.
"""

import heapq
import math
from typing import Dict, List, Optional, Sequence, Tuple

from nlslog import NEG_INF

BOS = "<s>"
EOS = "</s>"


class PrefixTree:
    """A prefix tree of pronunciations. Node 0 is the root; each other node is one phone."""

    def __init__(self, lexicon: Dict[str, Sequence[str]]) -> None:
        self.phone: List[Optional[str]] = [None]
        self.children: List[List[int]] = [[]]
        self.words: List[List[str]] = [[]]
        for w in sorted(lexicon):
            phones = lexicon[w]
            if not phones:
                raise ValueError("a word needs at least one phone")
            node = 0
            for ph in phones:
                nxt = next((c for c in self.children[node] if self.phone[c] == ph), None)
                if nxt is None:
                    nxt = len(self.phone)
                    self.phone.append(ph)
                    self.children.append([])
                    self.words.append([])
                    self.children[node].append(nxt)
                node = nxt
            self.words[node].append(w)

    def num_nodes(self) -> int:
        return len(self.phone)


def _relax(table: Dict, key, score: float, back: int) -> None:
    old = table.get(key)
    if old is None or score > old[0]:
        table[key] = (score, back)


def _prune(hyps: Dict, beam: float, max_active: Optional[int]) -> Dict:
    if not hyps:
        return hyps
    best = max(s for s, _ in hyps.values())
    kept = {k: v for k, v in hyps.items() if v[0] >= best - beam}
    if max_active is not None and len(kept) > max_active:
        top = heapq.nlargest(max_active, kept.items(), key=lambda kv: (kv[1][0], repr(kv[0])))
        kept = dict(top)
    return kept


def decode(
    lexicon: Dict[str, Sequence[str]],
    lm: Dict[Tuple[str, str], float],
    emit: Sequence[Dict[str, float]],
    lm_weight: float = 1.0,
    ip: float = 0.0,
    loop: float = math.log(0.5),
    fwd: float = math.log(0.5),
    beam: float = math.inf,
    max_active: Optional[int] = None,
):
    """Return (words, ends, score): the best word sequence, the last frame of each word, and its score.

    lm[(v, w)] is the log bigram probability of w after v; missing pairs are
    -inf. emit[t][ph] is the log emission score of phone ph at frame t.
    Return ([], [], -inf) if no hypothesis survives to the end.
    """
    tree = PrefixTree(lexicon)
    T = len(emit)
    if T == 0:
        return [], [], NEG_INF
    records: List[Tuple[str, int, float, int]] = []  # (word, end frame, score, previous record)

    def lm_score(v: str, w: str) -> float:
        return lm.get((v, w), NEG_INF)

    hyps: Dict[Tuple[str, int], Tuple[float, int]] = {}
    for c in tree.children[0]:  # @line L1
        _relax(hyps, (BOS, c), emit[0][tree.phone[c]], -1)
    ends: Dict[str, int] = {}
    for t in range(T):  # @line L2
        hyps = _prune(hyps, beam, max_active)  # @line L3
        ends = {}  # @line L4
        for (v, n), (s, back) in hyps.items():  # @line L5
            for w in tree.words[n]:
                score = s + fwd + lm_weight * lm_score(v, w) + ip
                if score == NEG_INF:
                    continue
                if w not in ends or score > records[ends[w]][2]:
                    records.append((w, t, score, back))
                    ends[w] = len(records) - 1
        if t == T - 1:  # @line L6
            break
        e = emit[t + 1]
        new: Dict[Tuple[str, int], Tuple[float, int]] = {}
        for (v, n), (s, back) in hyps.items():  # @line L7
            _relax(new, (v, n), s + loop + e[tree.phone[n]], back)
            for c in tree.children[n]:
                _relax(new, (v, c), s + fwd + e[tree.phone[c]], back)
        for w, r in ends.items():  # @line L8
            for c in tree.children[0]:
                _relax(new, (w, c), records[r][2] + e[tree.phone[c]], r)
        hyps = new  # @line L9
    best_r, best = -1, NEG_INF
    for w, r in sorted(ends.items()):  # @line L10
        score = records[r][2] + lm_weight * lm_score(w, EOS)
        if score > best:
            best_r, best = r, score
    if best_r < 0:
        return [], [], NEG_INF
    words: List[str] = []
    frames: List[int] = []
    r = best_r
    while r >= 0:
        w, t, _, r = records[r]
        words.append(w)
        frames.append(t)
    return words[::-1], frames[::-1], best


def path_score(
    lexicon: Dict[str, Sequence[str]],
    lm: Dict[Tuple[str, str], float],
    emit: Sequence[Dict[str, float]],
    words: Sequence[str],
    durations: Sequence[int],
    lm_weight: float = 1.0,
    ip: float = 0.0,
    loop: float = math.log(0.5),
    fwd: float = math.log(0.5),
) -> float:
    """Return the score of one word sequence with one duration per phone (the formula above)."""
    phones = [ph for w in words for ph in lexicon[w]]
    if len(phones) != len(durations) or sum(durations) != len(emit) or min(durations, default=1) < 1:
        raise ValueError("durations do not fit")
    score = 0.0
    t = 0
    for ph, d in zip(phones, durations):
        for _ in range(d):
            score += emit[t][ph]
            t += 1
        score += (d - 1) * loop + fwd
    prev = BOS
    for w in list(words) + [EOS]:
        score += lm_weight * lm.get((prev, w), NEG_INF)
        if w != EOS:
            score += ip
        prev = w
    return score
test_time_synchronous_beam_search.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/time-synchronous-beam-search/. The authors are listed in prov/6JVTAP.jsonl.

import itertools
import math
import random

from nlslog import NEG_INF
from time_synchronous_beam_search import BOS, EOS, PrefixTree, decode, path_score

PHONES = ["p", "q", "r"]


def compositions(total: int, parts: int):
    """Yield every tuple of `parts` positive integers that add up to `total`."""
    for cuts in itertools.combinations(range(1, total), parts - 1):
        bounds = (0,) + cuts + (total,)
        yield tuple(bounds[i + 1] - bounds[i] for i in range(parts))


def brute_force(lexicon, lm, emit, **kw):
    T = len(emit)
    best = NEG_INF
    for k in range(1, min(T, 5) + 1):
        for words in itertools.product(sorted(lexicon), repeat=k):
            n = sum(len(lexicon[w]) for w in words)
            if n > T:
                continue
            for dur in compositions(T, n):
                best = max(best, path_score(lexicon, lm, emit, words, dur, **kw))
    return best


def random_task(rng: random.Random, T: int):
    lexicon = {}
    for w in ["A", "B", "C"]:
        lexicon[w] = tuple(rng.choice(PHONES) for _ in range(rng.randint(1, 2)))
    vocab = sorted(lexicon)
    lm = {}
    for v in [BOS] + vocab:
        probs = [rng.random() + 0.1 for _ in range(len(vocab) + 1)]
        z = sum(probs)
        for w, p in zip(vocab + [EOS], probs):
            lm[(v, w)] = math.log(p / z)
    emit = [{ph: -rng.uniform(0.0, 4.0) for ph in PHONES} for _ in range(T)]
    return lexicon, lm, emit


def test_prefix_tree_shares_prefixes():
    tree = PrefixTree({"cat": ("k", "a", "t"), "cap": ("k", "a", "p"), "a": ("a",), "kay": ("k", "a")})
    assert tree.num_nodes() == 6
    assert len(tree.children[0]) == 2
    assert sorted(w for ws in tree.words for w in ws) == ["a", "cap", "cat", "kay"]


def test_wide_beam_matches_brute_force():
    rng = random.Random(11)
    for _ in range(60):
        T = rng.randint(1, 5)
        lexicon, lm, emit = random_task(rng, T)
        kw = {"lm_weight": rng.choice([0.5, 1.0, 2.0]), "ip": rng.choice([-1.0, 0.0, 0.5])}
        words, ends, score = decode(lexicon, lm, emit, **kw)
        expected = brute_force(lexicon, lm, emit, **kw)
        if expected == NEG_INF:
            assert (words, ends, score) == ([], [], NEG_INF)
            continue
        assert abs(score - expected) < 1e-9
        assert ends[-1] == T - 1
        assert all(a < b for a, b in zip(ends, ends[1:]))
        n = sum(len(lexicon[w]) for w in words)
        rescored = max(path_score(lexicon, lm, emit, words, d, **kw) for d in compositions(T, n))
        assert abs(rescored - score) < 1e-9


def test_large_histogram_limit_changes_nothing():
    rng = random.Random(12)
    for _ in range(30):
        lexicon, lm, emit = random_task(rng, 5)
        assert decode(lexicon, lm, emit) == decode(lexicon, lm, emit, beam=1e9, max_active=10 ** 6)


def test_pruned_score_is_never_better():
    rng = random.Random(13)
    for _ in range(40):
        lexicon, lm, emit = random_task(rng, 5)
        full = decode(lexicon, lm, emit)[2]
        for beam in [0.0, 0.5, 2.0]:
            for max_active in [1, 2, None]:
                words, _, score = decode(lexicon, lm, emit, beam=beam, max_active=max_active)
                assert score <= full + 1e-12
                if words:
                    assert score > NEG_INF


def test_narrow_beam_misses_the_best_path():
    lexicon = {"AB": ("a", "b"), "CD": ("c", "d")}
    lm = {(BOS, "AB"): 0.0, (BOS, "CD"): 0.0, ("AB", EOS): 0.0, ("CD", EOS): 0.0}
    emit = [{"a": -1.0, "b": -9.0, "c": -2.0, "d": -9.0}, {"a": -9.0, "b": -5.0, "c": -9.0, "d": -1.0}]
    fwd = math.log(0.5)
    assert decode(lexicon, lm, emit) == (["CD"], [1], -3.0 + 2 * fwd)
    assert decode(lexicon, lm, emit, beam=0.5) == (["AB"], [1], -6.0 + 2 * fwd)
    assert decode(lexicon, lm, emit, max_active=1) == (["AB"], [1], -6.0 + 2 * fwd)
    assert decode(lexicon, lm, emit, beam=1.0) == (["CD"], [1], -3.0 + 2 * fwd)


def test_bigram_context_is_kept_per_tree_copy():
    # After "x" the word "y" is cheap, after "z" it is expensive. Both "x" and "z" are one frame of
    # the same phone, so only a search that keeps one tree copy per previous word finds x y.
    lexicon = {"x": ("p",), "z": ("p",), "y": ("q",)}
    lm = {(BOS, "x"): math.log(0.4), (BOS, "z"): math.log(0.6), ("x", "y"): 0.0, ("z", "y"): math.log(0.01),
          ("y", EOS): 0.0}
    emit = [{"p": 0.0, "q": -9.0}, {"p": -9.0, "q": 0.0}]
    words, ends, score = decode(lexicon, lm, emit)
    assert words == ["x", "y"] and ends == [0, 1]
    assert abs(score - (math.log(0.4) + 2 * math.log(0.5))) < 1e-12


def test_no_complete_path():
    lexicon = {"AB": ("a", "b")}
    lm = {(BOS, "AB"): 0.0, ("AB", EOS): 0.0}
    emit = [{"a": 0.0, "b": 0.0}]
    assert decode(lexicon, lm, emit) == ([], [], NEG_INF)

History

Lowerre's Harpy system in 1976 introduced beam search for speech. One-pass dynamic programming for connected words, which handles word ends and word starts in the same frame loop, came from Bridle, Brown and Chamberlain in 1982 and from Ney in 1984. Ney, Mergel, Noll and Paeseler 1992 organized the search around a list of active hypotheses built frame by frame. The tree lexicon with one copy per predecessor word and language model look-ahead followed in the 1990s, and Ney and Ortmanns 1999 review them. WFST decoders later replaced the dynamic tree copies with one precompiled graph (Mohri, Pereira and Riley 2002), and kept the same frame-by-frame beam search.

References

  1. Hermann Ney, Dieter Mergel, Andreas Noll and Horst Paeseler, Data driven search organization for continuous speech recognition, IEEE Transactions on Signal Processing 40(2), 1992, pages 272 to 281, the time-synchronous dynamic programming beam search over a list of active hypotheses
  2. Hermann Ney and Stefan Ortmanns, Dynamic programming search for continuous speech recognition, IEEE Signal Processing Magazine 16(5), 1999, pages 64 to 83, the sections on time-synchronous beam search, the tree lexicon with copies per predecessor word, and language model look-ahead
  3. Mehryar Mohri, Fernando Pereira and Michael Riley, Weighted finite-state transducers in speech recognition, Computer Speech and Language 16(1), 2002, pages 69 to 88, the use of one precompiled network for the same search

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