Algorithm Search⌘K

Algorithmadvanced

Stack decoding

Also called A* stack decoder.

Best-first search over partial word sequences ordered by score plus an estimate of the rest, extending the top of a priority queue.

Time
O(V^2 n^2 log(V n) + V n^2 L) worst
Space
O(V^2 n^2) extra
Where
L = the largest number of phones in a word; V = the vocabulary size; n = the number of frames
Properties
deterministicexactofflineiterative
Origin
Frederick Jelinek, Lalit Bahl, Robert Mercer, Douglas B. Paul, 1969

A stack decoder recognizes speech by a best-first search over partial sentences. Each entry of its "stack", which is a priority queue, is a word sequence that explains the first tt frames, with its score. The decoder pops the entry whose score plus an estimate of the score of the remaining frames is largest, extends it by every possible next word, and pushes the results. It stops when it pops a complete sentence. If the estimate is an upper bound on the true rest, as in A* search, the first complete sentence popped is the best one. Unlike time-synchronous beam search, the search is not ordered by time: an entry that covers few frames can be extended before one that covers many.

In plain words

Keep a list of half-finished guesses at the sentence. Each guess says which words explain the speech up to some point, and how well. To compare a short guess with a long one, add to each a hopeful estimate of how well the rest of the speech could go.

Always take the guess that looks best with its estimate, and try every next word on it. When the best-looking guess is a whole sentence, stop. If the estimate is never too low, nothing you skipped could have beaten it.

The problem

The input is nn frames of acoustic scores ete_t, a lexicon, and a bigram language model. As on the page for time-synchronous beam search, each phone is one HMM state with a self loop of log probability ℓ\ell and a forward move of log probability ff, also used for the word exit. The task is the word sequence WW and segmentation that maximize

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

with the start ⟨s⟩\langle s \rangle and the end ⟨/s⟩\langle /s \rangle in plmp_{lm}. λ\lambda and ipip are tuned heuristics.

A partial hypothesis (w1⋯wk,t)(w_1 \cdots w_k, t) covers the frames 0,…,t−10, \ldots, t - 1, and its score gg is the best score of these words in these frames. The estimate h(t)h(t) of the rest must satisfy, for A*, g+h(t)≥g + h(t) \ge the score of every complete sentence that extends the hypothesis. The code uses

h(t)=∑u=tn−1max⁡phoneeu(phone)+(n−t)max⁡(0,log⁡ip),h(t) = \sum_{u = t}^{n - 1} \max_{\text{phone}} e_u(\text{phone}) + (n - t) \max(0, \log ip),

which is such a bound when the transitions and language model terms are log probabilities, so at most 0.

The algorithm

  1. STACK-DECODE(lexicon, lm, e, n, h)
  2. 1push (words = (), t = 0, g = 0) with priority h(0)
  3. 2while the stack is not empty do
  4. 3pop the entry with the largest priority
  5. 4if it is complete then return it
  6. 5if (last word, t) is closed then skip it; otherwise close it
  7. 6for each word w and each end t' > t: g' ← g + seg(w, t, t') + λ log p(w | last) + log ip
  8. 7if t' = n then push it as complete with priority g' + λ log p(⟨/s⟩ | w)
  9. 8else push (words + w, t', g') with priority g' + h(t')
  10. 9if the stack holds more than max_stack entries then drop the worst
  11. 10return failure

seg(w,t,t′)\mathrm{seg}(w, t, t') is the best score of ww in the frames t,…,t′−1t, \ldots, t' - 1, from a Viterbi pass through the phones of ww. One pass from tt gives it for every t′t', and the code keeps it in a table per (w,t)(w, t). The closed set of line L5 is a recombination: with a bigram, two hypotheses with the same last word and the same tt have the same future, so only the first one popped needs to be extended.

Example

The lexicon has x=(a)x = (a), y=(b)y = (b) and z=(c,d)z = (c, d), all language model scores are 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: e0=(a: 0,c:−1)e_0 = (a{:}\,0, c{:}{-1}) and e1=(d:−1)e_1 = (d{:}{-1}), and every other emission is −9-9. Then h(2)=0h(2) = 0, h(1)=−1h(1) = -1 and h(0)=−1h(0) = -1.

pop entry pushed (priority)
1 ()() at t=0t = 0, priority −1-1 xx at t=1t = 1 (−0.693−1=−1.693-0.693 - 1 = -1.693), zz complete (−3.386-3.386), xx complete (−10.386-10.386), yy at t=1t = 1 (−10.693-10.693), yy complete (−19.386-19.386)
2 xx at t=1t = 1, priority −1.693-1.693 x xx\,x complete (−10.386-10.386), x yx\,y complete (−10.386-10.386)
3 zz complete, −3.386-3.386 stop

The prefix xx looks best after the first expansion, because its first frame is perfect and the estimate of its second frame is optimistic. Its extensions are poor, so the complete zz, with −2+2ln⁡0.5≈−3.386-2 + 2 \ln 0.5 \approx -3.386, rises to the top and is returned. It is the best sentence.

With a stack of size 1, line L9 keeps only xx after the first pop and drops zz. The search then returns x xx\,x with −9+2ln⁡0.5≈−10.386-9 + 2 \ln 0.5 \approx -10.386. A limited stack, like a narrow beam, can lose the best path.

Correctness

The proof is in proofs/correctness.md. The estimate is admissible: each frame can add at most its best emission, transitions and language model terms add at most 0, and at most n−tn - t more words fit. It is also consistent: extending by one word never raises g+hg + h. So the priorities of the entries that are pushed never exceed the priority of the entry that was popped, and a complete entry has its true score as priority. When a complete entry is popped, every prefix of the best sentence on the stack has a priority at least as large as the best score, so the popped score is the best one.

The tests check this against exhaustive search over all sequences of at most 5 words and all their segmentations. They also check two failures: a stack of size 1 on the example, and an estimate far below the true rest, h(t)=−100(n−t)h(t) = -100 (n - t), which makes every complete sentence look better than any partial one and returns a one-word sentence that is about 3.9 worse than the best.

Proof: With an admissible, consistent heuristic, the stack decoder returns the best word sequencefull

We use the notation of the page. There are nn frames. A full path is a word sequence w1⋯wKw_1 \cdots w_K with K≥1K \ge 1 and a segmentation of the frames 0,…,n−10, \ldots, n - 1 into the phones of the words, at least one frame per phone. Its score is

S=∑k=1K(segk+λlog⁡p(wk∣wk−1)+log⁡ip)+λlog⁡p(⟨/s⟩∣wK),S = \sum_{k=1}^{K} \big(\mathrm{seg}_k + \lambda \log p(w_k \mid w_{k-1}) + \log ip\big) + \lambda \log p(\langle /s \rangle \mid w_K),

with w0=⟨s⟩w_0 = \langle s \rangle, where segk\mathrm{seg}_k is the emission and transition score of word kk in its frames, its exit move included. A partial hypothesis (w1⋯wk,t)(w_1 \cdots w_k, t) covers the frames 0,…,t−10, \ldots, t - 1, and its score gg is the sum of the first kk terms. Let S∗S^* be the best score of a full path. We assume ℓ≤0\ell \le 0, f≤0f \le 0, λ≥0\lambda \ge 0 and log probabilities ≤0\le 0, and that there is no stack limit.

Lemma 1 (the best segment). For a word ww and frames t≤ut \le u, the value seg(w,t,u+1)\mathrm{seg}(w, t, u + 1) computed by the word Viterbi pass is the best score of ww occupying exactly the frames t,…,ut, \ldots, u.

Proof. It is the Viterbi algorithm on the left-to-right chain of the phones of ww, started in the first phone at frame tt, read in the last phone at frame uu, plus the exit ff. □\square

So the best full path is found by choosing, for each word, its best segmentation inside its frames: the search over words and end frames, with Lemma 1 for the inside, covers every full path at its best segmentation.

Lemma 2 (admissible and consistent). Let h(t)=∑u≥tmax⁡phoneeu(phone)+(n−t)max⁡(0,log⁡ip)h(t) = \sum_{u \ge t} \max_{\text{phone}} e_u(\text{phone}) + (n - t) \max(0, \log ip), and h(n)=0h(n) = 0. Then

  1. for every extension of a partial hypothesis at tt by a word that covers frames t,…,t′−1t, \ldots, t' - 1, its added score Δ\Delta satisfies Δ+h(t′)≤h(t)\Delta + h(t') \le h(t);
  2. the final term λlog⁡p(⟨/s⟩∣wK)\lambda \log p(\langle /s \rangle \mid w_K) is ≤0=h(n)\le 0 = h(n);
  3. so every partial hypothesis at tt has g+h(t)≥g + h(t) \ge the score of every full path that extends it.

Proof. The added score is seg+λlog⁡p(w∣v)+log⁡ip\mathrm{seg} + \lambda \log p(w \mid v) + \log ip. The segment adds one emission per frame, each at most the maximum emission of its frame, and transitions that are ≤0\le 0. The language model term is ≤0\le 0, and log⁡ip≤(t′−t)max⁡(0,log⁡ip)\log ip \le (t' - t) \max(0, \log ip) since t′−t≥1t' - t \ge 1. Adding up gives claim 1. Claim 2 holds because log probabilities are ≤0\le 0. Claim 3 follows by adding claim 1 along the extensions up to nn and then claim 2. □\square

Lemma 3 (priorities do not grow). If an entry with priority PP is popped, every entry that its expansion pushes has priority at most PP. A complete entry has priority equal to its score.

Proof. A partial child has priority g+Δ+h(t′)≤g+h(t)=Pg + \Delta + h(t') \le g + h(t) = P by Lemma 2.1. A complete child has priority g+Δ+λlog⁡p(⟨/s⟩∣w)≤g+Δ=g+Δ+h(n)≤Pg + \Delta + \lambda \log p(\langle /s \rangle \mid w) \le g + \Delta = g + \Delta + h(n) \le P by Lemma 2.1 and 2.2. □\square

Lemma 4 (closing is safe). The future of a partial hypothesis, the set of score sums its extensions can add, depends only on its last word and tt. When the first entry with key (last word vv, tt) is popped, its gg is the best score of any partial hypothesis with that key.

Proof. The extensions depend on tt (which frames remain) and on vv (the next language model term), and on nothing else, so the first claim holds. For the second, suppose a hypothesis xx with the same key has a larger score gxg_x. Some prefix yy of xx is on the stack (or is xx itself): the root was on the stack, and the expansion of each popped prefix pushes the next one, unless its key was already closed, a case that the same argument handles by induction on the pop order. By Lemma 2.1 along the extensions from yy to xx, the priority of yy is at least gx+h(t)g_x + h(t), which is larger than the priority g+h(t)g + h(t) of the popped entry. That contradicts the choice of the popped entry as the largest. □\square

Theorem (optimality). With hh as in Lemma 2 and no stack limit, the first complete entry that is popped has the score S∗S^*.

Proof. Let π∗\pi^* be a best full path. Before the pop of a complete entry cc, some prefix of π∗\pi^*, or π∗\pi^* itself as a complete entry, is on the stack, or a prefix with the same key and a score at least as good (Lemma 4), which extends to a full path of score at least S∗S^*. By Lemma 2.3 its priority is at least S∗S^*. The popped entry has the largest priority, so the score of cc, which is its priority, is at least S∗S^*. It is the score of a full path, so it is at most S∗S^*. □\square

Termination. Each key (word, tt) is expanded at most once, there are at most V(n+1)+1V (n + 1) + 1 keys, and each expansion pushes at most VnV n entries, so the loop ends.

Remark (when it fails). The proof uses two assumptions, and the tests show what happens without them.

  • Stack limit. Dropping entries can drop every prefix of π∗\pi^*. In the example of the page, a stack of size 1 keeps the prefix xx, whose priority is the largest after the first expansion, and drops the complete zz; every extension of xx scores −9+2ln⁡0.5-9 + 2 \ln 0.5, worse than S∗=−2+2ln⁡0.5S^* = -2 + 2 \ln 0.5.
  • A heuristic below the true rest. Lemma 2.3 fails, and a complete entry can be popped while a prefix of a better path waits with a lower priority. With h(t)=−100(n−t)h(t) = -100 (n - t), the test returns a one-word sentence about 3.9 worse than the best two-word sentence.

Complexity

Let nn be the number of frames, VV the vocabulary size and LL the largest number of phones in a word. With the closed set there are at most V(n+1)+1V (n + 1) + 1 expansions, each pushes at most VnV n entries, and each push or pop costs O(log⁡(Vn))O(\log (V n)) on a heap of at most V2n2V^2 n^2 entries. The segment scores take O(nL)O(n L) per (w,t)(w, t), for VnV n pairs. This gives the worst case O(V2n2log⁡(Vn)+Vn2L)O(V^2 n^2 \log (V n) + V n^2 L) time and O(V2n2)O(V^2 n^2) space, with back pointers in the entries. The code copies the word sequence into each entry for clarity, which adds a factor of nn to the space.

In practice the search pops far fewer entries, and how many depends on how tight hh is. A loose hh makes the search close to breadth-first; a tight one goes almost straight to the answer. Without recombination, the stack decoder searches a tree of word sequences, which is exponential in the number of words, as Paul 1990 points out.

Properties

  • Exact with an admissible estimate and no stack limit. It then returns the best sentence. With a limit, or an estimate that can be too low, it is not exact.
  • Not time-synchronous. Entries cover different numbers of frames. This makes long-span language models easy, since each entry holds its full word history, but makes it hard to compare entries without a good estimate.
  • Not online. The estimate h(t)h(t) uses the frames after tt, so the decoder needs the whole utterance, or a bound on its future frames.
  • Whole words at a time. Each step adds a whole word with its best segmentation, so the acoustic match of a word runs once per start frame.

Variants and improvements

  • Fast match. Real stack decoders do not try every word. A cheap acoustic and language model match gives a short list of candidates for each entry, as in Paul 1990.
  • Normalizing by time. Instead of an estimate of the rest, compare entries by score minus the best score up to their end frame, or by score per frame. These are not admissible, but they work in practice.
  • A stack per end frame. Keep one stack for each tt and extend the best entries of each in order of tt. This becomes a time-ordered search, close to beam stack search.
  • N-best output. Do not stop at the first complete entry, and do not close keys. The next complete entries popped are then the next best sentences, in order, when the estimate is admissible and consistent. The closed set of line L5 would drop the second-best history of each key.
  • Machine translation. The same idea, with one stack per number of source words covered, is phrase-based stack decoding.

When to use it

Use it when the language model has a long history that a time-synchronous search would have to copy into many tree copies, or when you want the exact best sentence for a small task with an admissible estimate. Use it also to produce N-best lists. For large vocabularies with real-time limits, time-synchronous beam search or a WFST decoder is the usual choice, because its cost per frame is easy to control.

Pitfalls

  • A loose estimate. If hh is a poor bound, the decoder extends many short entries before any long one, and the stack grows fast.
  • An estimate that is too low. Short entries then look worse than long ones, and the decoder returns the first complete sentence it reaches, as in the test.
  • Stack limits. A size limit is needed in practice, and it makes the search inexact, as in the example.
  • Scores of different lengths. Without an estimate of the rest, a short entry has a better log score than a long one only because it covers fewer frames. Comparing raw scores is wrong.
  • Positive scores. The bound assumes that transitions and language model terms are at most 0. A positive insertion bonus or scaled scores must enter hh, as max⁡(0,log⁡ip)\max(0, \log ip) does in the code.

Implementations

The Python code runs A* over (words, end frame) with a heap, a closed set on (last word, end frame), a table of word segment scores per (word, start frame), an optional stack limit, and an optional custom estimate. The tests compare it with exhaustive search over all sequences of at most 5 words and their segmentations on random tasks, check the word segment scores and the bound, check that a stack of size 1 returns x xx\,x on the example, and check that an estimate below the true rest returns a worse one-word sentence.

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
stack_decoding.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stack-decoding/. The authors are listed in prov/A0NEW4.jsonl.

"""Stack decoding: best-first (A*) search over partial word sequences.

The model is the one of the time-synchronous beam search page: a lexicon
word -> tuple of phones, one emitting state per phone with a self loop (log
probability loop) and a forward move (log probability fwd, also used for the
word exit), emission scores emit[t][phone], and a bigram lm[(v, w)] in log
probability. Scores are log probabilities, higher is better. The score of a
word sequence with a segmentation is

    sum of emissions + transitions + sum over words of (lm_weight * lm + ip)
  + lm_weight * lm(last word, </s>).

A partial hypothesis is (words, t): the words cover frames 0..t-1 exactly. Its
score g is the best score of that prefix. The search pops the hypothesis with
the largest g + h(t), where h(t) is an upper bound on the score of frames
t..T-1:

    h(t) = sum over u >= t of max_phone emit[u][phone] + (T - t) * max(0, ip).

This bound is valid (admissible) when loop <= 0, fwd <= 0, lm <= 0 and
lm_weight >= 0, since then every transition and language model term is at
most 0 and at most T - t more words fit. It is also consistent: extending by
one word never raises g + h. So the first complete hypothesis that is popped
is the best one, and a hypothesis (last word, t) can be closed after its first
pop, because its future depends only on the last word and t.

The search is not limited to a fixed number of words. A stack limit max_stack
drops the worst entries and makes the search inexact; so does a heuristic that
is not an upper bound.
"""

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

from nlslog import NEG_INF

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


def word_scores(phones: Sequence[str], emit: Sequence[Dict[str, float]], t: int, loop: float, fwd: float) -> Dict[int, float]:
    """Return {t1: best log score of the word occupying frames t..t1-1, exit included}."""
    T = len(emit)
    k = len(phones)
    alpha = [NEG_INF] * k
    alpha[0] = emit[t][phones[0]]
    out: Dict[int, float] = {}
    for u in range(t, T):
        if u > t:
            new = [NEG_INF] * k
            for j in range(k):
                best = alpha[j] + loop
                if j > 0:
                    best = max(best, alpha[j - 1] + fwd)
                new[j] = best + emit[u][phones[j]]
            alpha = new
        if alpha[k - 1] > NEG_INF:
            out[u + 1] = alpha[k - 1] + fwd
    return out


def default_heuristic(emit: Sequence[Dict[str, float]], ip: float) -> List[float]:
    """Return h[t] for t = 0..T: the admissible bound of the module docstring."""
    T = len(emit)
    h = [0.0] * (T + 1)
    for t in range(T - 1, -1, -1):
        h[t] = h[t + 1] + max(emit[t].values()) + max(0.0, ip)
    return h


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),
    heuristic: Optional[Callable[[int], float]] = None,
    max_stack: Optional[int] = None,
):
    """Return (words, ends, score, pops): the best hypothesis found and the number of pops.

    ends[i] is the last frame of words[i]. Return ([], [], -inf, pops) if no
    complete hypothesis is found.
    """
    T = len(emit)
    if heuristic is None:
        table = default_heuristic(emit, ip)
        heuristic = table.__getitem__
    memo: Dict[Tuple[str, int], Dict[int, float]] = {}

    def seg(w: str, t: int) -> Dict[int, float]:
        if (w, t) not in memo:
            memo[(w, t)] = word_scores(lexicon[w], emit, t, loop, fwd)
        return memo[(w, t)]

    counter = itertools.count()
    # Entries: (-priority, order, complete, g, words, ends)
    stack: List = [(-heuristic(0), next(counter), False, 0.0, (), ())]  # @line L1
    closed = set()
    pops = 0
    while stack:  # @line L2
        _, _, complete, g, words, ends = heapq.heappop(stack)  # @line L3
        pops += 1
        if complete:  # @line L4
            return list(words), list(ends), g, pops
        t = ends[-1] + 1 if ends else 0
        last = words[-1] if words else BOS
        if (last, t) in closed:  # @line L5
            continue
        closed.add((last, t))
        for w in sorted(lexicon):  # @line L6
            lm_w = lm.get((last, w), NEG_INF)
            if lm_w == NEG_INF:
                continue
            for t1, s in seg(w, t).items():
                g1 = g + s + lm_weight * lm_w + ip
                if t1 == T:  # @line L7
                    end = lm.get((w, EOS), NEG_INF)
                    if end > NEG_INF:
                        total = g1 + lm_weight * end
                        heapq.heappush(stack, (-total, next(counter), True, total, words + (w,), ends + (t1 - 1,)))
                elif (w, t1) not in closed:  # @line L8
                    heapq.heappush(stack, (-(g1 + heuristic(t1)), next(counter), False, g1, words + (w,), ends + (t1 - 1,)))
        if max_stack is not None and len(stack) > max_stack:  # @line L9
            stack = heapq.nsmallest(max_stack, stack)
            heapq.heapify(stack)
    return [], [], NEG_INF, pops  # @line L10
test_stack_decoding.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stack-decoding/. The authors are listed in prov/A0NEW4.jsonl.

import itertools
import math
import random

from nlslog import NEG_INF
from stack_decoding import BOS, EOS, decode, default_heuristic, word_scores

PHONES = ["p", "q", "r"]
LOG_HALF = math.log(0.5)


def brute_force(lexicon, lm, emit, lm_weight=1.0, ip=0.0, max_words=5):
    """Best score over all word sequences of at most max_words words and all segmentations."""
    T = len(emit)
    best = NEG_INF
    for k in range(1, max_words + 1):
        for words in itertools.product(sorted(lexicon), repeat=k):
            phones = [ph for w in words for ph in lexicon[w]]
            if len(phones) > T:
                continue
            lm_part, prev = 0.0, BOS
            for w in list(words) + [EOS]:
                lm_part += lm_weight * lm.get((prev, w), NEG_INF)
                prev = w
            if lm_part == NEG_INF:
                continue
            for cuts in itertools.combinations(range(1, T), len(phones) - 1):
                bounds = (0,) + cuts + (T,)
                s = lm_part + k * ip
                for j, ph in enumerate(phones):
                    d = bounds[j + 1] - bounds[j]
                    s += sum(emit[u][ph] for u in range(bounds[j], bounds[j + 1])) + (d - 1) * LOG_HALF + LOG_HALF
                best = max(best, s)
    return best


def random_task(rng: random.Random, T: int):
    lexicon = {w: tuple(rng.choice(PHONES) for _ in range(rng.randint(1, 2))) for w in ["A", "B", "C"]}
    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_word_scores():
    emit = [{"a": -1.0, "b": -2.0}, {"a": -3.0, "b": -0.5}, {"a": -1.0, "b": -1.0}]
    out = word_scores(("a", "b"), emit, 0, LOG_HALF, LOG_HALF)
    assert set(out) == {2, 3}
    assert abs(out[2] - (-1.0 - 0.5 + 2 * LOG_HALF)) < 1e-12
    assert abs(out[3] - (-1.0 - 0.5 - 1.0 + 3 * LOG_HALF)) < 1e-12


def test_heuristic_is_an_upper_bound():
    rng = random.Random(30)
    for _ in range(30):
        lexicon, lm, emit = random_task(rng, 4)
        h = default_heuristic(emit, 0.0)
        for t in range(5):
            rest = emit[t:]
            if rest:
                # The best score of any single word that covers the rest is at most h[t].
                for w in lexicon:
                    s = word_scores(lexicon[w], emit, t, LOG_HALF, LOG_HALF).get(4, NEG_INF)
                    assert s <= h[t] + 1e-12


def test_matches_brute_force():
    rng = random.Random(31)
    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:]))


def test_wide_stack_changes_nothing():
    rng = random.Random(32)
    for _ in range(30):
        lexicon, lm, emit = random_task(rng, 5)
        a = decode(lexicon, lm, emit)
        b = decode(lexicon, lm, emit, max_stack=10 ** 6)
        assert a[:3] == b[:3]


def narrow_task():
    lexicon = {"x": ("a",), "y": ("b",), "z": ("c", "d")}
    lm = {(v, w): 0.0 for v in [BOS, "x", "y", "z"] for w in ["x", "y", "z", EOS]}
    emit = [{"a": 0.0, "b": -9.0, "c": -1.0, "d": -9.0}, {"a": -9.0, "b": -9.0, "c": -9.0, "d": -1.0}]
    return lexicon, lm, emit


def test_narrow_stack_misses_the_best_path():
    lexicon, lm, emit = narrow_task()
    words, ends, score, _ = decode(lexicon, lm, emit)
    assert (words, ends) == (["z"], [1]) and abs(score - (-2.0 + 2 * LOG_HALF)) < 1e-12
    words, ends, score, _ = decode(lexicon, lm, emit, max_stack=1)
    assert words[0] == "x"
    assert abs(score - (-9.0 + 2 * LOG_HALF)) < 1e-12


def test_inadmissible_heuristic_can_fail():
    lexicon = {"x": ("a",), "y": ("b",)}
    lm = {(BOS, "x"): LOG_HALF, (BOS, "y"): LOG_HALF}
    for v in ["x", "y"]:
        for w in ["x", "y", EOS]:
            lm[(v, w)] = math.log(1 / 3)
    emit = [{"a": 0.0, "b": -5.0}, {"a": -5.0, "b": 0.0}]
    best = decode(lexicon, lm, emit)
    assert best[0] == ["x", "y"]
    assert abs(best[2] - (2 * LOG_HALF + LOG_HALF + 2 * math.log(1 / 3))) < 1e-12
    # A heuristic far below the true rest makes any complete hypothesis look better than a partial one.
    worse = decode(lexicon, lm, emit, heuristic=lambda t: -100.0 * (2 - t))
    assert len(worse[0]) == 1
    assert worse[2] < best[2] - 3.0


def test_closed_set_limits_pops():
    rng = random.Random(33)
    lexicon, lm, emit = random_task(rng, 5)
    _, _, _, pops = decode(lexicon, lm, emit)
    # At most one expansion per (last word, start frame), plus duplicate and complete pops.
    pushes_bound = 1 + (len(lexicon) + 1) * 6 * len(lexicon) * 6
    assert pops <= pushes_bound

History

Jelinek 1969 gave the stack algorithm for the sequential decoding of convolutional codes. The IBM speech group applied it to continuous speech recognition, and Bahl, Jelinek and Mercer 1983 describe stack decoding as part of their statistical approach. Paul 1990 described a version that is an optimal A* search, which is guaranteed to find the most likely sentence, and a second algorithm that linearizes the search at the cost of approximating some path likelihoods. Time-synchronous beam search later became the more common decoder for large vocabularies, but the stack decoder idea lives on in phrase-based machine translation and in N-best search.

References

  1. Frederick Jelinek, Fast sequential decoding algorithm using a stack, IBM Journal of Research and Development 13(6), 1969, pages 675 to 685, the stack algorithm for sequential decoding
  2. Lalit R. Bahl, Frederick Jelinek and Robert L. Mercer, A maximum likelihood approach to continuous speech recognition, IEEE Transactions on Pattern Analysis and Machine Intelligence 5(2), 1983, pages 179 to 190, the discussion of decoding by stack search
  3. Douglas B. Paul, Algorithms for an optimal A* search and linearizing the search in the stack decoder, Speech and Natural Language Workshop, Hidden Valley, 1990, the abstract and the stack decoder loop (pop the best theory, stop at the end of the sentence, extend by a short list of candidate words)

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