Algorithm Search⌘K

Algorithmcore

Token passing

Also called token passing model.

Young's view of Viterbi decoding over a network of HMMs, where tokens holding scores and word histories move along arcs each frame.

Time
O(n (s + a)) worst
Space
O(s + n a) extra
Where
a = the number of word arcs; n = the number of frames; s = the number of HMM states in all word arcs
Properties
deterministicexactonlineiterative
Origin
Steve J. Young, N. H. Russell, J. H. S. Thornton, 1989

Token passing is a way to describe and build the Viterbi search of a connected speech recognizer, due to Young, Russell and Thornton 1989. The recognizer is a network: grammar nodes joined by word arcs, and each word arc is a copy of the HMM of the word. A token is a score with a link to the word history. At each frame every HMM state takes the best token offered by its predecessors and adds its emission score. When a token leaves a word, the decoder writes a word link record, and the token moves to the next grammar node. With no pruning it finds the best path, the same one as time-synchronous Viterbi beam search: the two are the same search, written as messages on a network or as a list of active hypotheses.

In plain words

Think of the recognizer as a map of rooms. Each word is a row of rooms, one for each sound, and the grammar says which word rows follow which. Each frame, every room holds at most one token, a slip that says how good the best way into this room is and which words that way went through.

At the next frame, each token is copied to the rooms it can reach, and each copy adds the cost of the move and how well the new room fits the sound. A room that gets several copies keeps the best. When a token leaves the last room of a word, you write down the word, and the token carries a pointer to that note. At the end, the best token at an end room points back to all its words.

The problem

The input is a word network, a lexicon, and nn frames of acoustic scores. The network has grammar nodes, which do not emit, a start node, final nodes with a log score, and word arcs (src,dst,w,g)(src, dst, w, g), where gg is a log grammar or language model score. A word arc is a left-to-right HMM for the phones of ww. The task is the path through the network and through the HMM states that maximizes

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

where log⁡pac\log p_{ac} is the sum of the emission and transition log scores, log⁡plm\log p_{lm} the sum of the gg of the arcs and the final score, λ\lambda the language model weight and ipip the word insertion penalty. λ\lambda and ipip are tuned heuristics.

In the code each phone is one state with a self loop of log probability ℓ\ell and a forward move of log probability ff, and the exit from a word is a forward move too. A bigram is the network with one node per previous word.

The algorithm

  1. TOKEN-PASSING(N, e, n)
  2. 1node(start) ← (0, no link); all other tokens are empty
  3. 2for t ← 0 to n - 1 do
  4. 3for each word arc a and state j: tok(a, j) ← best of tok(a, j) + ℓ, tok(a, j - 1) + f, and, for j = 0, node(src(a)) + λ g(a) + log ip; then add e_t(j)
  5. 4PRUNE: drop the tokens with a score below best - beam
  6. 5clear the node tokens
  7. 6for each arc a with a token in its last state: s ← tok + f; write a link (w(a), t, s, link of tok); node(dst(a)) ← the better of node(dst(a)) and (s, new link)
  8. 7return the best node(q) + λ final(q) over final q, and follow its links back

Line L3 is the step inside the HMMs, line L6 the step between words. A grammar node keeps only the best token that reaches it at each frame. This is the Viterbi recombination, and it is right because everything after the node depends only on the node.

Example

The network has a start node and a final node, joined by two word arcs: AB=(a,b)AB = (a, b) and CD=(c,d)CD = (c, d), with g=0g = 0 and a final score of 0. Take λ=1\lambda = 1, log⁡ip=0\log ip = 0 and ℓ=f=ln⁡0.5≈−0.693\ell = f = \ln 0.5 \approx -0.693. The emission scores are e0=(a:−1,c:−2)e_0 = (a{:}{-1}, c{:}{-2}) and e1=(b:−5,d:−1)e_1 = (b{:}{-5}, d{:}{-1}), and −9-9 for every other phone.

frame aa bb cc dd word links
0 −1-1 none −2-2 none none
1 −10.693-10.693 −6.693-6.693 −11.693-11.693 −3.693-3.693 ABAB at −7.386-7.386, CDCD at −4.386-4.386

At frame 1 the final node gets two offers and keeps CDCD at −4.386-4.386. This is the same table of scores as in the example of time-synchronous beam search, entry by entry: the two searches differ only in how they are written down.

With a beam of 0.5, line L4 drops the token in cc at frame 0, and the search returns ABAB at −7.386-7.386, which is worse than the best path by 3. A beam of 1.0 keeps it and finds CDCD.

Correctness

The proof is in proofs/correctness.md. By induction on tt, the token of state jj of arc aa at frame tt holds the best score of any partial path that is in that state at that frame, and the token of a node holds the best score of any partial path that has just left a word into it. A partial path in a state came from the same state, from the state before it, or from the source node of the arc, and the score it adds depends only on where it came from, so the best partial path extends one of the three best tokens. At the last frame, the best final node token, plus its final score, is the best full path.

For a bigram network, every path is a word sequence with a segmentation, and its score is the one that time-synchronous beam search gives it: token passing adds the language model score when a word starts and beam search adds it when the word ends, but the sum is the same. With no pruning both return the maximum of the same function, so they find the same best path. With a beam, both can miss it, and they need not miss in the same way, since the language model score enters the beam at different times.

Proof: Without pruning, token passing finds the best path through the networkfull

We use the notation of the page. A full path for nn frames is a sequence of word arcs a1,…,aKa_1, \ldots, a_K with K≥1K \ge 1 that starts at the start node, in which each arc starts where the previous one ends and the last one ends at a final node, together with a segmentation that gives each phone of the words of a1,…,aKa_1, \ldots, a_K in order at least one frame, nn frames in all. Its score SS is the sum of the emission scores of the frames, (d−1)ℓ+f(d - 1)\ell + f for each phone that occupies dd frames, λg(ak)+log⁡ip\lambda g(a_k) + \log ip for each arc, and λ⋅final(q)\lambda \cdot \text{final}(q) for the last node qq.

For frame tt, write tokt(a,j)\mathrm{tok}_t(a, j) for the token of state jj of arc aa after lines L3 and L4, and nodet(q)\mathrm{node}_t(q) for the token of node qq after line L6. Before frame 0, node−1\mathrm{node}_{-1} holds only the start node with score 0 (line L1).

Lemma 1 (tokens are best partial scores). With no pruning, for every tt:

  1. tokt(a,j)\mathrm{tok}_t(a, j) is the best partial score of a prefix of a full path that is in state jj of arc aa at frame tt;
  2. nodet(q)\mathrm{node}_t(q) is the best partial score of a prefix that has left a word into node qq at the end of frame tt, exit ff included.

A partial score counts the emissions of frames 0,…,t0, \ldots, t, the transitions between them, and λg+log⁡ip\lambda g + \log ip of every arc entered so far. A token is absent when no prefix exists.

Proof. Induction on tt. A prefix in state jj of arc aa at frame tt came from one of three places: state jj of aa at frame t−1t - 1 (self loop ℓ\ell), state j−1j - 1 of aa at frame t−1t - 1 (forward move ff), or, when j=0j = 0, the source node of aa at the end of frame t−1t - 1, entering aa with λg(a)+log⁡ip\lambda g(a) + \log ip. In each case the added score, the transition plus et(j)e_t(j), depends only on where the prefix was at t−1t - 1. So the best prefix extends the best prefix of one of these places, which by induction (or by line L1 at t=0t = 0) are tokt−1(a,j)\mathrm{tok}_{t-1}(a, j), tokt−1(a,j−1)\mathrm{tok}_{t-1}(a, j - 1) and nodet−1(src(a))\mathrm{node}_{t-1}(\mathrm{src}(a)). Line L3 takes the best of the three and adds et(j)e_t(j), which proves claim 1.

A prefix that leaves a word into qq at the end of frame tt is in the last state of some arc aa into qq at frame tt and adds ff. Line L6 takes the best of tokt(a,last)+f\mathrm{tok}_t(a, \text{last}) + f over these arcs, which proves claim 2. □\square

Theorem (exact without pruning). With an infinite beam, token passing returns a full path with the best score S∗S^*.

Proof. A full path leaves its last word into a final node qq at the end of frame n−1n - 1, and its score is its partial score there plus λ⋅final(q)\lambda \cdot \text{final}(q). By Lemma 1, line L7 computes max⁡qnoden−1(q)+λ⋅final(q)=S∗\max_q \mathrm{node}_{n-1}(q) + \lambda \cdot \text{final}(q) = S^*. Each token carries the index of the word link record of the word it left last, and line L6 writes a new record with the previous index, so the traceback reads the words and end frames of a path with this score. □\square

Corollary (same best path as time-synchronous beam search). Build the network of a bigram: one node per word history (⟨s⟩\langle s \rangle and each word), an arc v→wv \to w for word ww with g=log⁡p(w∣v)g = \log p(w \mid v), and final scores log⁡p(⟨/s⟩∣w)\log p(\langle /s \rangle \mid w). Then a full path of the network is a word sequence with a segmentation, and its score SS equals the score that time-synchronous beam search gives the same sequence and segmentation: the two add the same terms, token passing adds λg+log⁡ip\lambda g + \log ip when a word starts and beam search when it ends. Both searches return the maximum of the same function over the same set, so with no pruning they return the same best score, and the same path when it is unique.

Proposition (pruning). With a finite beam, line L4 removes tokens and never changes the score of a kept one, so the returned score is the score of a real full path and at most S∗S^*. The two-word example of the page, with a beam of 0.5, returns a path that is 3 worse than the best.

Complexity

Let nn be the number of frames, ss the number of HMM states in all word arcs and aa the number of word arcs. At each frame, line L3 looks at each state once, with at most three offers, and line L6 looks at each arc once. That is O(s+a)O(s + a) per frame and O(n(s+a))O(n (s + a)) in all, without pruning. With pruning, only the states that hold a token cost time.

The extra space is O(s)O(s) for the tokens of one frame and O(na)O(n a) for the word link records, since each frame writes at most one record per arc that ends a word.

Properties

  • Exact without pruning. It computes the Viterbi path of the whole network.
  • Same search as beam search. With the same network and no pruning, it returns the same best path as time-synchronous Viterbi beam search.
  • Online. Each frame is read once, in order.
  • Local. Each state needs only its own token and the tokens of its predecessors, so the network can be any graph: a fixed grammar, a loop of words, or a bigram.
  • History in the token. The word link records hold the word history, so the HMM states do not need back pointers per frame.

Variants and improvements

  • N-best tokens. Keep the best few tokens per state, with different word histories, to output several hypotheses or a word lattice. This was one of the extensions in Young, Russell and Thornton 1989.
  • Pruning. A global beam, a narrower beam at word ends, and a limit on the number of active models.
  • Context-dependent models. Make the word arcs from triphone models, with cross-word context on the arcs between words.
  • Precompiled networks. A WFST decoder runs the same token passing over an HCLG decoding graph, where the arcs carry HMM states instead of whole words.
  • Forced alignment. With a network that is one chain of words, token passing becomes forced alignment.

When to use it

Use it to build a decoder for any network of HMMs, from a small command grammar to a bigram over a large vocabulary, especially when the network is fixed and you want simple code. It is the model behind the HTK recognizer. For large vocabularies with long language model histories, a prefix tree with tree copies or a precompiled graph keeps the network smaller.

Pitfalls

  • Wrong network for the language model. Recombination at a node is right only if the future depends only on the node. A single node for all word ends with a bigram applied later would merge tokens with different futures.
  • Lost alternatives. Keeping one token per state gives only the best path. A lattice needs several tokens per state.
  • Tokens in loops of null nodes. If the network has arcs between grammar nodes with no HMM, tokens must be passed through them in an order with no cycle in one frame.
  • Search errors from pruning. As in the example, a narrow beam can drop the right word at the first frame.

Implementations

The Python code runs token passing over a network of word arcs with one-state phones, a beam and word link records, and builds the network of a bigram. The tests compare the best score with exhaustive search over all arc paths of at most 5 words and all their segmentations on random networks with cycles, check the bigram network, check that the example fails with a beam of 0.5 and works with 1.0, check that pruning never gives a better score, and check that the links hold a history with a repeated word.

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
token_passing.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/token-passing/. The authors are listed in prov/CTEH7D.jsonl.

"""Token passing (Young, Russell and Thornton 1989) over a word network.

The network has grammar nodes, which do not emit, and word arcs between them.
A word arc (src, dst, word, g) is one copy of the HMM of the word, entered from
src with the log grammar score g and left into dst. A node can be final with a
log score. A bigram is the network with one node per previous word.

To keep the code short, each phone is one emitting HMM state with a self loop
(log probability loop) and a forward move (log probability fwd); the exit from
the last phone of a word is a forward move too. Scores are log probabilities,
higher is better. The score of a path is

    sum of the emission scores e_t(phone at frame t)
  + sum over phones of ((d - 1) * loop + fwd)          (d frames in the phone)
  + sum over the word arcs taken of (lm_weight * g + ip)
  + lm_weight * final(last node).

A token is (score, link). The link points to a word-link record (word, end
frame, score, previous link), so a token carries its word history. Each frame
every state keeps the best token that reaches it: this is the Viterbi max.
Each grammar node keeps the best token that leaves a word into it. With no
pruning the result is the best path; a beam can lose it.
"""

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

from nlslog import NEG_INF

Token = Tuple[float, int]


class Network:
    """A word network: grammar nodes 0..n-1, a start node, final nodes and word arcs."""

    def __init__(self) -> None:
        self.num_nodes = 0
        self.start = 0
        self.final: Dict[int, float] = {}
        self.arcs: List[Tuple[int, int, str, float]] = []

    def add_node(self) -> int:
        self.num_nodes += 1
        return self.num_nodes - 1

    def add_word(self, src: int, dst: int, word: str, g: float = 0.0) -> None:
        self.arcs.append((src, dst, word, g))

    def set_final(self, q: int, score: float = 0.0) -> None:
        self.final[q] = score


def _better(a: Token, b: Token) -> bool:
    return a[0] > b[0]


def decode(
    net: Network,
    lexicon: Dict[str, Sequence[str]],
    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,
):
    """Return (words, ends, score) for the best path through the network, or ([], [], -inf)."""
    n = len(emit)
    links: List[Tuple[str, int, float, int]] = []  # (word, end frame, score, previous link)
    node: Dict[int, Token] = {net.start: (0.0, -1)}  # @line L1
    toks: Dict[Tuple[int, int], Token] = {}
    for t in range(n):  # @line L2
        e = emit[t]
        new: Dict[Tuple[int, int], Token] = {}

        def offer(key: Tuple[int, int], tok: Token) -> None:
            if tok[0] > NEG_INF and (key not in new or _better(tok, new[key])):
                new[key] = tok

        for (a, j), (s, link) in toks.items():  # @line L3
            offer((a, j), (s + loop, link))
            if j + 1 < len(lexicon[net.arcs[a][2]]):
                offer((a, j + 1), (s + fwd, link))
        for a, (src, _, _, g) in enumerate(net.arcs):
            if src in node:
                s, link = node[src]
                offer((a, 0), (s + lm_weight * g + ip, link))
        toks = {}
        for (a, j), (s, link) in new.items():
            toks[(a, j)] = (s + e[lexicon[net.arcs[a][2]][j]], link)
        if toks:  # @line L4
            best = max(s for s, _ in toks.values())
            toks = {k: v for k, v in toks.items() if v[0] >= best - beam and v[0] > NEG_INF}
        node = {}  # @line L5
        for (a, j), (s, link) in sorted(toks.items()):  # @line L6
            src, dst, word, _ = net.arcs[a]
            if j == len(lexicon[word]) - 1:
                out = s + fwd
                if dst not in node or out > node[dst][0]:
                    links.append((word, t, out, link))
                    node[dst] = (out, len(links) - 1)
    best_link, best = -1, NEG_INF
    for q in sorted(node):  # @line L7
        if q in net.final:
            s = node[q][0] + lm_weight * net.final[q]
            if s > best:
                best_link, best = node[q][1], s
    if best_link < 0:
        return [], [], NEG_INF
    words: List[str] = []
    ends: List[int] = []
    r = best_link
    while r >= 0:
        w, t, _, r = links[r]
        words.append(w)
        ends.append(t)
    return words[::-1], ends[::-1], best


def bigram_network(vocab: Sequence[str], lm: Dict[Tuple[str, str], float]) -> Network:
    """Build the network of a bigram: node 0 is <s>, node i + 1 is vocab[i]; missing pairs get no arc."""
    net = Network()
    net.add_node()
    for _ in vocab:
        net.add_node()
    index = {"<s>": 0}
    index.update({w: i + 1 for i, w in enumerate(vocab)})
    for v in ["<s>"] + list(vocab):
        for w in vocab:
            if (v, w) in lm:
                net.add_word(index[v], index[w], w, lm[(v, w)])
    for w in vocab:
        if (w, "</s>") in lm:
            net.set_final(index[w], lm[(w, "</s>")])
    return net
test_token_passing.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/token-passing/. The authors are listed in prov/CTEH7D.jsonl.

import itertools
import math
import random

from nlslog import NEG_INF
from token_passing import Network, bigram_network, decode

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


def compositions(total: int, parts: int):
    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 path_score(net, lexicon, emit, arcs, durations, lm_weight, ip):
    phones = [ph for a in arcs for ph in lexicon[net.arcs[a][2]]]
    score, t = 0.0, 0
    for ph, d in zip(phones, durations):
        score += sum(emit[t + i][ph] for i in range(d)) + (d - 1) * LOG_HALF + LOG_HALF
        t += d
    for a in arcs:
        score += lm_weight * net.arcs[a][3] + ip
    return score + lm_weight * net.final[net.arcs[arcs[-1]][1]]


def brute_force(net, lexicon, emit, lm_weight=1.0, ip=0.0):
    """Best score over all arc paths from the start to a final node with at most 5 words."""
    T = len(emit)
    best = NEG_INF
    paths = [[a] for a, arc in enumerate(net.arcs) if arc[0] == net.start]
    while paths:
        longer = []
        for path in paths:
            phones = sum(len(lexicon[net.arcs[a][2]]) for a in path)
            if phones > T:
                continue
            if net.arcs[path[-1]][1] in net.final:
                for d in compositions(T, phones):
                    best = max(best, path_score(net, lexicon, emit, path, d, lm_weight, ip))
            if len(path) < 5:
                longer += [path + [a] for a, arc in enumerate(net.arcs) if arc[0] == net.arcs[path[-1]][1]]
        paths = longer
    return best


def random_lexicon(rng: random.Random):
    return {w: tuple(rng.choice(PHONES) for _ in range(rng.randint(1, 2))) for w in ["A", "B", "C"]}


def random_network(rng: random.Random, lexicon) -> Network:
    net = Network()
    for _ in range(3):
        net.add_node()
    for _ in range(rng.randint(2, 7)):
        net.add_word(rng.randrange(3), rng.randrange(3), rng.choice(sorted(lexicon)), math.log(rng.uniform(0.1, 1.0)))
    for q in rng.sample(range(3), rng.randint(1, 3)):
        net.set_final(q, math.log(rng.uniform(0.1, 1.0)))
    return net


def random_emit(rng: random.Random, T: int):
    return [{ph: -rng.uniform(0.0, 4.0) for ph in PHONES} for _ in range(T)]


def test_random_networks_match_brute_force():
    rng = random.Random(21)
    for _ in range(80):
        lexicon = random_lexicon(rng)
        net = random_network(rng, lexicon)
        T = rng.randint(1, 5)
        emit = random_emit(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(net, lexicon, emit, **kw)
        expected = brute_force(net, lexicon, 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_bigram_network():
    rng = random.Random(22)
    for _ in range(30):
        lexicon = random_lexicon(rng)
        vocab = sorted(lexicon)
        lm = {}
        for v in ["<s>"] + vocab:
            probs = [rng.random() + 0.1 for _ in range(len(vocab) + 1)]
            z = sum(probs)
            for w, p in zip(vocab + ["</s>"], probs):
                lm[(v, w)] = math.log(p / z)
        net = bigram_network(vocab, lm)
        assert len(net.arcs) == len(vocab) * (len(vocab) + 1)
        emit = random_emit(rng, 5)
        words, _, score = decode(net, lexicon, emit)
        assert abs(score - brute_force(net, lexicon, emit)) < 1e-9
        # The words returned score the same under the bigram written out by hand.
        prev, lm_part = "<s>", 0.0
        for w in words + ["</s>"]:
            lm_part += lm[(prev, w)]
            prev = w
        n = sum(len(lexicon[w]) for w in words)
        assert n <= 5 and lm_part > NEG_INF


def test_pruning_never_improves():
    rng = random.Random(23)
    for _ in range(40):
        lexicon = random_lexicon(rng)
        net = random_network(rng, lexicon)
        emit = random_emit(rng, 5)
        full = decode(net, lexicon, emit)[2]
        for beam in [0.0, 0.5, 2.0, 1e9]:
            score = decode(net, lexicon, emit, beam=beam)[2]
            assert score <= full + 1e-12
        assert decode(net, lexicon, emit, beam=1e9) == decode(net, lexicon, emit)


def test_narrow_beam_misses_the_best_path():
    lexicon = {"AB": ("a", "b"), "CD": ("c", "d")}
    net = Network()
    s, f = net.add_node(), net.add_node()
    net.add_word(s, f, "AB", 0.0)
    net.add_word(s, f, "CD", 0.0)
    net.set_final(f, 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}]
    assert decode(net, lexicon, emit) == (["CD"], [1], -3.0 + 2 * LOG_HALF)
    assert decode(net, lexicon, emit, beam=0.5) == (["AB"], [1], -6.0 + 2 * LOG_HALF)
    assert decode(net, lexicon, emit, beam=1.0) == (["CD"], [1], -3.0 + 2 * LOG_HALF)


def test_tokens_carry_word_history():
    lexicon = {"one": ("p",), "two": ("q", "r")}
    net = Network()
    a, b, c = net.add_node(), net.add_node(), net.add_node()
    net.add_word(a, b, "one", 0.0)
    net.add_word(b, b, "two", math.log(0.5))
    net.add_word(b, c, "one", 0.0)
    net.set_final(c, 0.0)
    emit = [{x: (0.0 if x == ph else -5.0) for x in "pqr"} for ph in "pqrqrp"]
    words, ends, score = decode(net, lexicon, emit)
    assert words == ["one", "two", "two", "one"] and ends == [0, 2, 4, 5]
    assert abs(score - (2 * math.log(0.5) + 6 * LOG_HALF)) < 1e-12

History

Vintsyuk, then Bridle, Brown and Chamberlain, and Ney, had described one-pass dynamic programming for connected words before 1989. Young, Russell and Thornton wrote it in 1989 as a simple model: tokens passed around a transition network. The model made it easy to add several alternatives per state and syntax networks, and it became the decoder design of the HTK toolkit. Later WFST decoders, such as the one in Kaldi, still describe their Viterbi beam search as passing tokens over a graph.

References

  1. Steve J. Young, N. H. Russell and J. H. S. Thornton, Token passing, a simple conceptual model for connected speech recognition systems, technical report CUED/F-INFENG/TR38, Cambridge University Engineering Department, 1989, the abstract (connected word recognition as passing tokens around a transition network, and its extension to several alternatives and syntax constraints)
  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 section on time-synchronous beam search, which computes the same scores

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
  • at least three sources
  • a scene preset for the example