Algorithm Search⌘K

Data structurecore

Word lattice

Also called speech lattice.

A directed acyclic graph of word hypotheses with times and scores that compactly holds many alternative transcriptions.

Time
O(N + E) worst
Space
O(N + E) extra
Where
E = the number of arcs; N = the number of nodes
Properties
not concurrentnot externalnot persistent

A word lattice, or word graph, is the output of a speech decoder that keeps more than one answer. It is a directed acyclic graph. Each node is a point in time, and each arc is a word hypothesis that starts at the time of its source node and ends at the time of its target node, with an acoustic score and a language model score. Each path from the start node to a final node is one transcription. Because paths share arcs, a lattice of a few hundred arcs can hold millions of transcriptions. The standard queries are one pass over the nodes in topological order: the best path, the number of paths, the total score, and the posterior probability of each arc by forward-backward. Later passes rescore lattices with stronger models (lattice rescoring) or turn them into confusion networks.

In plain words

A recognizer is often unsure. At one point it might have heard "recognize speech" or "wreck a nice beach". Instead of writing down one answer, it draws a map. Each dot is a moment in time, and each arrow is a word that could fill the gap between two moments, with a score for how well it fits the sound and how likely it is as language.

Any route from the first dot to the last one is a possible sentence. Routes share arrows, so the map stays small even when it holds very many sentences. To find the best route, or how likely each arrow is, you walk through the dots once from left to right, and once back.

The abstract type

A lattice stores a set of weighted word sequences and answers queries about them.

  • add_node(time) and add_arc(u, v, word, ac, lm) build the graph. An arc may not go back in time, and the graph must stay acyclic.
  • best_path(λ, ip) returns the path with the best combined score.
  • num_paths() returns the number of paths.
  • total(semiring, weight) returns the semiring sum over all paths, for example the log of the total probability.
  • arc_posteriors(λ, ip, κ) returns, for each arc, the posterior probability that the transcription uses it.
  • prune(b, λ, ip) returns a smaller lattice with the arcs that lie on a path within bb of the best path.

The combined log score of an arc aa and of a path WW is

s(a)=log⁡pac(a)+λlog⁡plm(a)+log⁡ip,S(W)=∑a∈Ws(a),s(a) = \log p_{ac}(a) + \lambda \log p_{lm}(a) + \log ip, \qquad S(W) = \sum_{a \in W} s(a),

which is the decoder score log⁡pac+λlog⁡plm+∣W∣log⁡ip\log p_{ac} + \lambda \log p_{lm} + |W| \log ip. The language model weight λ\lambda and the insertion penalty ipip are tuned heuristics.

Representation

The nodes are numbered 0,…,N−10, \ldots, N - 1, with a time each. The arcs are in one array of tuples (source, target, word, acoustic score, language model score), and each node has a list of its outgoing and of its incoming arc numbers. There is one start node and a set of final nodes. A lattice looks like the trellis of a Viterbi decoder, but its nodes are word boundaries, not states at every frame.

Invariant.

  • (L1) Acyclic. There is no directed cycle. The code checks it in the topological sort.
  • (L2) Time. For every arc, the time of its source is at most the time of its target.
  • (L3) Adjacency. Arc kk is in the outgoing list of its source and in the incoming list of its target, once each.

The language model score on an arc is only valid for the word history that the lattice structure fixes. A trigram score on an arc needs all paths into its source node to end in the same two words. Lattices from a bigram decoder keep one node per (time, last word), and rescoring with a longer history splits nodes (see lattice rescoring).

Operations

Every query is a pass over the nodes in topological order in some semiring: (max⁡,+)(\max, +) for the best path, (logadd,+)(\mathrm{logadd}, +) for totals and posteriors, (+,×)(+, \times) with weight 1 for the path count.

  1. LATTICE-FORWARD(Λ, ⊕, ⊗, w)
  2. 1order ← TOPOLOGICAL-SORT(Λ)
  3. 2α(start) ← 1̄; α(v) ← 0̄ for every other node v
  4. 3for each node u in order do
  5. 4for each arc a from u to v: α(v) ← α(v) ⊕ (α(u) ⊗ w(a))
  6. LATTICE-BACKWARD(Λ, ⊕, ⊗, w)
  7. 5β(q) ← 1̄ for each final q; β(v) ← 0̄ for every other node v
  8. 6for each node u in reverse order do
  9. 7for each arc a from u to v: β(u) ← β(u) ⊕ (w(a) ⊗ β(v))
  10. ARC-POSTERIOR(a from u to v) ▷ α, β in the log semiring with w(a) = κ s(a); log Z = logadd of α(q) over final q
  11. 8γ(a) ← exp(α(u) + κ s(a) + β(v) - log Z)
  12. PRUNE(Λ, b) ▷ α, β in the (max, +) semiring with w(a) = s(a); B = the best path score
  13. 9keep the arcs a from u to v with α(u) + s(a) + β(v) ≥ B - b
  14. 10keep the start, the final nodes and the ends of the kept arcs

The acoustic scale κ\kappa in line L8 matters. The acoustic log scores of one frame are not independent, so raw path scores are far too peaked, and the best path would get a posterior near 1. Scaling the combined score by κ\kappa, often 1/λ1 / \lambda, keeps the language model on its own scale and flattens the acoustic part. Mangu, Brill and Stolcke 2000 and Wessel et al. 2001 compute posteriors this way.

Example

The lattice has the nodes 0 (time 0), 1 and 2 (time 30) and 3 (time 60, final), and five arcs:

arc words log⁡pac\log p_{ac} plmp_{lm}
0→10 \to 1 a −10-10 0.6
0→20 \to 2 x −9-9 0.4
1→31 \to 3 b −12-12 0.5
1→31 \to 3 c −10-10 0.5
2→32 \to 3 b −12-12 0.9

There are 3 paths: "a b", "a c" and "x b". With λ=1\lambda = 1 and log⁡ip=0\log ip = 0, "a c" is best with −20+ln⁡0.3≈−21.204-20 + \ln 0.3 \approx -21.204, ahead of "x b" with −21+ln⁡0.36≈−22.022-21 + \ln 0.36 \approx -22.022. With λ=10\lambda = 10, the language model counts more, and "x b" is best with −21+10ln⁡0.36≈−31.217-21 + 10 \ln 0.36 \approx -31.217, ahead of "a c" with −32.040-32.040 and "a b" with −34.040-34.040.

With λ=10\lambda = 10 and κ=1/10\kappa = 1 / 10, the posteriors are 0.6262 for "a", 0.3738 for "x", 0.2819 and 0.3738 for the two "b" arcs, and 0.3443 for "c". The two arcs out of node 0 add up to 1, and so do the three arcs into node 3 (Corollary 2 of the proof). So the best path is "x b", but the most likely first word is "a" (0.6262) and the most likely second word is "b" (0.2819+0.3738=0.65570.2819 + 0.3738 = 0.6557). Choosing word by word gives "a b", which is not the best path. A confusion network makes this idea precise. With κ=1\kappa = 1 instead, the posterior of "x" rises to 0.6674, which shows how the scale sharpens the distribution.

Pruning with λ=10\lambda = 10 and a beam of 1 keeps "x b" and "a c" (within 0.823 of the best) and drops the arc "b" from node 1, since its best path "a b" is 2.823 below the best. The result has 4 arcs and 2 paths.

Correctness

The proof is in proofs/correctness.md. By induction along the topological order, α(v)\alpha(v) is the semiring sum over all paths from the start to vv: each path to vv has exactly one last arc, and its source was finished before vv. The same holds for β\beta in reverse. A path through an arc aa from uu to vv splits uniquely into a path to uu, the arc aa and a path from vv, so by distributivity α(u)⊗w(a)⊗β(v)\alpha(u) \otimes w(a) \otimes \beta(v) is the sum over the paths through aa. In the log semiring that gives the posterior, and in (max⁡,+)(\max, +) it gives the best score through aa, which is what pruning compares with the beam. When every path covers every frame once, the arcs that span a frame have posteriors that add up to 1.

Proof: The lattice queries compute path sums, posteriors and beam pruning exactlyfull

We use the notation of the page. A lattice is a finite directed acyclic graph with a start node ss and a set FF of final nodes. A path is a sequence of arcs from ss to a node of FF. For an arc weight ww in a commutative semiring (K,⊕,⊗,0ˉ,1ˉ)(K, \oplus, \otimes, \bar 0, \bar 1), the weight of a path is the ⊗\otimes-product of its arc weights. Since the graph is acyclic, there are finitely many paths, and all sums below are finite.

Lemma 1 (forward). After LATTICE-FORWARD, for every node vv,

α(v)=⨁π:s⇝vw(π),\alpha(v) = \bigoplus_{\pi : s \leadsto v} w(\pi),

the sum over all arc sequences from ss to vv, with α(s)=1ˉ\alpha(s) = \bar 1 for the empty sequence.

Proof. Line L1 gives an order in which every arc goes from an earlier node to a later one. We show by induction along this order that when line L3 reaches uu, α(u)\alpha(u) already has its final value. A path to uu is empty (only for u=su = s, which gives the 1ˉ\bar 1 of line L2) or ends with an arc aa from some u′u' that comes before uu in the order. When u′u' was processed, α(u′)\alpha(u') was final by induction, and line L4 added α(u′)⊗w(a)\alpha(u') \otimes w(a) to α(u)\alpha(u). By distributivity, α(u′)⊗w(a)\alpha(u') \otimes w(a) is the sum over the paths to uu whose last arc is aa. Each path to uu has exactly one last arc, so the sum over all arcs into uu is the sum over all paths to uu. No later step changes α(u)\alpha(u), since line L4 changes only the targets of arcs out of the node being processed, and they come after it. □\square

Lemma 2 (backward). After LATTICE-BACKWARD, β(v)=⨁π:v⇝Fw(π)\beta(v) = \bigoplus_{\pi : v \leadsto F} w(\pi), the sum over the arc sequences from vv to any final node, with the empty sequence counting 1ˉ\bar 1 when v∈Fv \in F.

Proof. The same induction in reverse order, with line L5 for the empty paths and line L7 for the first arc. □\square

Corollary 1 (the three totals). The sum ⨁q∈Fα(q)\bigoplus_{q \in F} \alpha(q) is

  • the number of paths, in the counting semiring with all weights 1;
  • the best combined score max⁡π∑a∈πs(a)\max_\pi \sum_{a \in \pi} s(a), in the Viterbi semiring (max⁡,+)(\max, +);
  • log⁡∑πeκS(π)\log \sum_\pi e^{\kappa S(\pi)}, in the log semiring (logadd,+)(\mathrm{logadd}, +) with weights κ s(a)\kappa\, s(a), where S(π)=∑a∈πs(a)S(\pi) = \sum_{a \in \pi} s(a).

The best path is read back from the arcs that gave each maximum, and by the same induction it is a path with the best score.

Lemma 3 (arc posteriors). Define the posterior of a path as P(π)=eκS(π)/ZP(\pi) = e^{\kappa S(\pi)} / Z with Z=∑πeκS(π)Z = \sum_\pi e^{\kappa S(\pi)}. Then, for every arc aa from uu to vv, line L8 gives

γ(a)=exp⁡(α(u)+κs(a)+β(v)−log⁡Z)=∑π∋aP(π).\gamma(a) = \exp\big(\alpha(u) + \kappa s(a) + \beta(v) - \log Z\big) = \sum_{\pi \ni a} P(\pi).

Proof. A path that uses aa uses it once, since the graph is acyclic, and it splits uniquely into a path from ss to uu, the arc aa, and a path from vv to FF. Every such triple is a path through aa. So

∑π∋aeκS(π)=(∑s⇝ueκS)eκs(a)(∑v⇝FeκS)=eα(u)eκs(a)eβ(v)\sum_{\pi \ni a} e^{\kappa S(\pi)} = \Big(\sum_{s \leadsto u} e^{\kappa S}\Big) e^{\kappa s(a)} \Big(\sum_{v \leadsto F} e^{\kappa S}\Big) = e^{\alpha(u)} e^{\kappa s(a)} e^{\beta(v)}

by Lemmas 1 and 2 in the log semiring, and dividing by Z=elog⁡ZZ = e^{\log Z} gives the claim. □\square

Corollary 2 (posteriors at a time). If every path covers each frame tt with exactly one arc, that is, the node times increase from 00 at ss to the last time TT at every final node, then for every t<Tt < T the arcs aa with time(u)≤t<time(v)\mathrm{time}(u) \le t < \mathrm{time}(v) have posteriors that add up to 1.

Proof. Each path contains exactly one such arc, so the sum of γ(a)\gamma(a) over them is ∑πP(π)=1\sum_\pi P(\pi) = 1. □\square

Lemma 4 (beam pruning). Let BB be the best path score. With α\alpha and β\beta in the Viterbi semiring, an arc aa from uu to vv is kept by line L9 if and only if some path through aa has a score of at least B−bB - b, where bb is the beam. The pruned lattice keeps every path with a score of at least B−bB - b, and its best path has the score BB.

Proof. By the same split as in Lemma 3, α(u)+s(a)+β(v)\alpha(u) + s(a) + \beta(v) is the best score of a path through aa, which gives the first claim. A path with score at least B−bB - b has, for each of its arcs, a path through that arc (itself) with score at least B−bB - b, so all its arcs are kept, and its nodes and final node are kept by line L10. The best path is such a path, and the pruned lattice has no new paths with a better score, since its paths are paths of the original lattice. □\square

The pruned lattice can also hold paths with a score below B−bB - b, made of kept arcs from different good paths. Lemma 4 says only that no good path is lost.

Remark (floating point). The code compares α(u)+s(a)+β(v)\alpha(u) + s(a) + \beta(v) with B−bB - b with a tolerance of 10−9(1+∣B∣)10^{-9}(1 + |B|), because the two sides add the same numbers in different orders. Without it, a beam of 0 can drop an arc of the best path by rounding.

Complexity

Let NN be the number of nodes and EE the number of arcs. The topological sort, the forward pass and the backward pass each look at every node and arc once, so the best path, the path count, the total, all arc posteriors, and pruning take O(N+E)O(N + E) time and O(N+E)O(N + E) extra space, with a semiring operation in O(1)O(1). The number of paths can be exponential in NN: a chain of mm time slots with two arcs each has 2m2^m paths in 3m3m words of storage. The path count itself can then need O(N)O(N) bits.

Variants

  • N-best lists. A list of the nn best paths is a simple lattice with no shared arcs. It is easy to rescore with any model but holds far fewer alternatives for its size. k shortest paths extracts it from a lattice.
  • Word graphs with merged nodes. Ortmanns, Ney and Aubert 1997 build the graph from the word ends of the beam search and merge the nodes with the same time and word history.
  • Lattices as weighted automata. A lattice is an acyclic weighted automaton. WFST tools can then determinize it, keep the best path per word sequence, or compose it with a new language model.
  • Phone or state lattices. Arcs can also hold phones or HMM states, with word labels on some arcs, as in Kaldi.

When to use it

Use a lattice when a later step needs more than the best transcription: rescoring with a long-span or neural language model, confidence scores from posteriors, minimum word error decoding with a confusion network, discriminative training, or keyword search. Use the best path alone when nothing downstream needs alternatives.

Pitfalls

  • Unscaled posteriors. Without an acoustic scale, nearly all the mass goes to the best path, and the posteriors are useless as confidences.
  • Language model scores tied to a history. Replacing the language model on the arcs is only valid if every path into a node has the history the new model needs.
  • Pruned lattices hold new paths. Pruning keeps the arcs of good paths, and their combinations can form paths outside the beam. This is harmless but surprising.
  • Silence and filler arcs. Real lattices have arcs for silence and noise, and they must not count as words when you score word errors.
  • Very large path counts. Do not enumerate the paths. Every query here is a single pass.

Implementations

The Python code stores a lattice with node times, an arc array and in and out lists, and gives a topological sort with a cycle check, generic forward and backward passes over the semirings of the helper module, the best path, the path count, arc posteriors with an acoustic scale, and beam pruning. The tests compare the path count, the total log score, the best path and every arc posterior with enumeration of all paths on random lattices, check that the arcs that span each frame have posteriors that add up to 1, check that pruning keeps every path within the beam and the best score, and check the example.

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
word_lattice.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-lattice/. The authors are listed in prov/5BPGS0.jsonl.

"""A word lattice: a directed acyclic graph of word hypotheses with times and scores.

Nodes carry a time (a frame index). An arc (src, dst, word, ac, lm) says that
word spans the frames time[src] .. time[dst] - 1, with the log acoustic score
ac and the log language model score lm. There is one start node and a set of
final nodes. A path from the start to a final node is one transcription.

The combined log score of an arc, as in the decoder, is

    s(a) = ac + lm_weight * lm + ip,

where lm_weight and the log insertion penalty ip are tuned heuristics. All
the queries are one pass over the nodes in topological order with a semiring
(nlslog): VITERBI (max, +) for the best path, LOG (log-add, +) for total
scores and posteriors, COUNTING for the number of paths.

Arc posteriors use an acoustic scale kappa on the combined score,
exp(kappa * s(a)); kappa = 1 / lm_weight is the usual choice, so that the
language model keeps its own scale and the acoustic scores are flattened.
"""

import math
from typing import Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple

from nlslog import COUNTING, LOG, NEG_INF, VITERBI, Semiring

Arc = Tuple[int, int, str, float, float]


class Lattice:
    def __init__(self) -> None:
        self.times: List[int] = []
        self.arcs: List[Arc] = []
        self.out_arcs: List[List[int]] = []
        self.in_arcs: List[List[int]] = []
        self.start = 0
        self.final: Set[int] = set()

    def add_node(self, time: int) -> int:
        self.times.append(time)
        self.out_arcs.append([])
        self.in_arcs.append([])
        return len(self.times) - 1

    def add_arc(self, src: int, dst: int, word: str, ac: float, lm: float) -> int:
        if self.times[dst] < self.times[src]:
            raise ValueError("an arc must not go back in time")
        self.arcs.append((src, dst, word, ac, lm))
        k = len(self.arcs) - 1
        self.out_arcs[src].append(k)
        self.in_arcs[dst].append(k)
        return k

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

    def topo_order(self) -> List[int]:
        """Return the nodes in an order where every arc goes forward. Raise ValueError on a cycle."""
        indeg = [len(a) for a in self.in_arcs]
        ready = [v for v in range(self.num_nodes()) if indeg[v] == 0]
        order: List[int] = []
        while ready:
            u = ready.pop()
            order.append(u)
            for k in self.out_arcs[u]:
                v = self.arcs[k][1]
                indeg[v] -= 1
                if indeg[v] == 0:
                    ready.append(v)
        if len(order) != self.num_nodes():
            raise ValueError("the lattice has a cycle")
        return order

    def score(self, k: int, lm_weight: float = 1.0, ip: float = 0.0) -> float:
        _, _, _, ac, lm = self.arcs[k]
        return ac + lm_weight * lm + ip

    def forward(self, sr: Semiring, weight: Callable[[int], object]) -> list:
        """Return alpha[v]: the semiring sum over the paths from the start to v of their weights."""
        order = self.topo_order()  # @line L1
        alpha = [sr.zero] * self.num_nodes()
        alpha[self.start] = sr.one  # @line L2
        for u in order:  # @line L3
            for k in self.out_arcs[u]:
                v = self.arcs[k][1]
                alpha[v] = sr.plus(alpha[v], sr.times(alpha[u], weight(k)))  # @line L4
        return alpha

    def backward(self, sr: Semiring, weight: Callable[[int], object]) -> list:
        """Return beta[v]: the semiring sum over the paths from v to a final node of their weights."""
        order = self.topo_order()
        beta = [sr.zero] * self.num_nodes()
        for q in self.final:  # @line L5
            beta[q] = sr.one
        for u in reversed(order):  # @line L6
            for k in self.out_arcs[u]:
                v = self.arcs[k][1]
                beta[u] = sr.plus(beta[u], sr.times(weight(k), beta[v]))  # @line L7
        return beta

    def total(self, sr: Semiring, weight: Callable[[int], object]):
        alpha = self.forward(sr, weight)
        out = sr.zero
        for q in self.final:
            out = sr.plus(out, alpha[q])
        return out

    def num_paths(self) -> int:
        return self.total(COUNTING, lambda k: 1)

    def best_path(self, lm_weight: float = 1.0, ip: float = 0.0):
        """Return (words, score) of the path with the best combined score, or ([], -inf)."""
        order = self.topo_order()
        best = [NEG_INF] * self.num_nodes()
        back: List[Optional[int]] = [None] * self.num_nodes()
        best[self.start] = 0.0
        for u in order:
            if best[u] == NEG_INF:
                continue
            for k in self.out_arcs[u]:
                v = self.arcs[k][1]
                s = best[u] + self.score(k, lm_weight, ip)
                if s > best[v]:
                    best[v], back[v] = s, k
        end = max(sorted(self.final), key=lambda q: best[q], default=None)
        if end is None or best[end] == NEG_INF:
            return [], NEG_INF
        words: List[str] = []
        v = end
        while back[v] is not None:
            k = back[v]
            words.append(self.arcs[k][2])
            v = self.arcs[k][0]
        return words[::-1], best[end]

    def arc_posteriors(self, lm_weight: float = 1.0, ip: float = 0.0, kappa: Optional[float] = None) -> List[float]:
        """Return gamma[k]: the posterior probability that a path uses arc k, with acoustic scale kappa."""
        if kappa is None:
            kappa = 1.0 / lm_weight
        w = lambda k: kappa * self.score(k, lm_weight, ip)
        alpha = self.forward(LOG, w)
        beta = self.backward(LOG, w)
        z = NEG_INF
        for q in self.final:
            z = LOG.plus(z, alpha[q])
        if z == NEG_INF:
            raise ValueError("no path from the start to a final node")
        gamma = []
        for k, (u, v, _, _, _) in enumerate(self.arcs):
            g = alpha[u] + w(k) + beta[v] - z  # @line L8
            gamma.append(math.exp(g) if g > NEG_INF else 0.0)
        return gamma

    def prune(self, beam: float, lm_weight: float = 1.0, ip: float = 0.0) -> "Lattice":
        """Return a lattice with the arcs whose best path through them is within beam of the best path."""
        w = lambda k: self.score(k, lm_weight, ip)
        alpha = self.forward(VITERBI, w)
        beta = self.backward(VITERBI, w)
        best = max((alpha[q] for q in self.final), default=NEG_INF)
        tol = 1e-9 * (1.0 + abs(best)) if best > NEG_INF else 0.0  # sums in another order round apart
        keep = [k for k, (u, v, _, _, _) in enumerate(self.arcs)
                if best > NEG_INF and alpha[u] + w(k) + beta[v] >= best - beam - tol]  # @line L9
        used = {self.start} | {q for q in self.final}
        for k in keep:
            used.add(self.arcs[k][0])
            used.add(self.arcs[k][1])
        out = Lattice()
        new_id: Dict[int, int] = {}
        for v in sorted(used):  # @line L10
            new_id[v] = out.add_node(self.times[v])
        out.start = new_id[self.start]
        out.final = {new_id[q] for q in self.final if alpha[q] >= best - beam - tol}
        for k in keep:
            u, v, word, ac, lm = self.arcs[k]
            out.add_arc(new_id[u], new_id[v], word, ac, lm)
        return out

    def paths(self) -> Iterator[List[int]]:
        """Yield every path from the start to a final node as a list of arc ids (exponential; for tests)."""
        stack: List[Tuple[int, List[int]]] = [(self.start, [])]
        while stack:
            u, path = stack.pop()
            if u in self.final:
                yield path
            for k in self.out_arcs[u]:
                stack.append((self.arcs[k][1], path + [k]))

    def words(self, path: Sequence[int]) -> List[str]:
        return [self.arcs[k][2] for k in path]
test_word_lattice.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-lattice/. The authors are listed in prov/5BPGS0.jsonl.

import math
import random

import pytest

from nlslog import LOG, NEG_INF, log_sum
from word_lattice import Lattice

WORDS = ["a", "b", "c", "d"]


def random_lattice(rng: random.Random, n: int, extra: int) -> Lattice:
    """Nodes at times 0, 1, ..., n - 1 in a chain plus random forward arcs; node 0 starts, node n - 1 ends."""
    lat = Lattice()
    for t in range(n):
        lat.add_node(t)
    for t in range(n - 1):
        lat.add_arc(t, t + 1, rng.choice(WORDS), -rng.uniform(0, 5), -rng.uniform(0, 3))
    for _ in range(extra):
        u = rng.randrange(n - 1)
        v = rng.randrange(u + 1, n)
        lat.add_arc(u, v, rng.choice(WORDS), -rng.uniform(0, 5) * (v - u), -rng.uniform(0, 3))
    lat.final = {n - 1}
    return lat


def page_example() -> Lattice:
    lat = Lattice()
    for t in [0, 30, 30, 60]:
        lat.add_node(t)
    lat.add_arc(0, 1, "a", -10.0, math.log(0.6))
    lat.add_arc(0, 2, "x", -9.0, math.log(0.4))
    lat.add_arc(1, 3, "b", -12.0, math.log(0.5))
    lat.add_arc(1, 3, "c", -10.0, math.log(0.5))
    lat.add_arc(2, 3, "b", -12.0, math.log(0.9))
    lat.final = {3}
    return lat


def test_page_example():
    lat = page_example()
    assert lat.num_paths() == 3
    words, score = lat.best_path(lm_weight=10.0)
    assert words == ["x", "b"]
    assert abs(score - (-21.0 + 10 * math.log(0.36))) < 1e-12
    assert lat.best_path(lm_weight=1.0)[0] == ["a", "c"]
    gamma = lat.arc_posteriors(lm_weight=10.0)
    assert abs(gamma[0] + gamma[1] - 1.0) < 1e-12
    assert abs(gamma[2] + gamma[3] + gamma[4] - 1.0) < 1e-12
    assert gamma[1] == pytest.approx(gamma[4])
    # The best path is "x b", but "a" is the more likely first word and "b" the more likely second word.
    assert gamma[0] == pytest.approx(0.6262, abs=1e-4)
    assert gamma[2] + gamma[4] == pytest.approx(0.6557, abs=1e-4)
    small = lat.prune(1.0, 10.0)
    assert sorted(small.words(p) for p in small.paths()) == [["a", "c"], ["x", "b"]]
    assert len(small.arcs) == 4


def test_path_count_and_totals_match_enumeration():
    rng = random.Random(41)
    for _ in range(40):
        lat = random_lattice(rng, rng.randint(2, 7), rng.randint(0, 8))
        paths = list(lat.paths())
        assert lat.num_paths() == len(paths)
        lw, ip = rng.choice([0.5, 1.0, 8.0]), rng.choice([-1.0, 0.0, 0.5])
        scores = [sum(lat.score(k, lw, ip) for k in p) for p in paths]
        total = lat.total(LOG, lambda k: lat.score(k, lw, ip))
        assert abs(total - log_sum(scores)) < 1e-9
        words, best = lat.best_path(lw, ip)
        assert abs(best - max(scores)) < 1e-9
        assert any(lat.words(p) == words and abs(s - best) < 1e-9 for p, s in zip(paths, scores))


def test_arc_posteriors_match_enumeration():
    rng = random.Random(42)
    for _ in range(40):
        lat = random_lattice(rng, rng.randint(2, 7), rng.randint(0, 8))
        lw = rng.choice([1.0, 4.0, 12.0])
        kappa = 1.0 / lw
        gamma = lat.arc_posteriors(lw)
        paths = list(lat.paths())
        logp = [kappa * sum(lat.score(k, lw) for k in p) for p in paths]
        z = log_sum(logp)
        expect = [0.0] * len(lat.arcs)
        for p, lp in zip(paths, logp):
            for k in p:
                expect[k] += math.exp(lp - z)
        assert all(abs(g - e) < 1e-9 for g, e in zip(gamma, expect))
        # Every path covers every frame once, so the arcs that span a frame have posteriors adding up to 1.
        T = max(lat.times)
        for t in range(T):
            span = sum(g for (u, v, _, _, _), g in zip(lat.arcs, gamma) if lat.times[u] <= t < lat.times[v])
            assert abs(span - 1.0) < 1e-9


def test_acoustic_scale_flattens_posteriors():
    lat = page_example()
    sharp = lat.arc_posteriors(lm_weight=10.0, kappa=1.0)
    flat = lat.arc_posteriors(lm_weight=10.0, kappa=0.1)
    assert max(sharp[0], sharp[1]) > max(flat[0], flat[1])
    assert sharp[1] == pytest.approx(0.6674, abs=1e-4)
    assert flat[0] == pytest.approx(0.6262, abs=1e-4)


def test_prune_keeps_exactly_the_paths_within_the_beam():
    rng = random.Random(43)
    for _ in range(40):
        lat = random_lattice(rng, rng.randint(2, 7), rng.randint(0, 8))
        beam = rng.choice([0.0, 1.0, 3.0, 100.0])
        small = lat.prune(beam)
        best = lat.best_path()[1]
        assert abs(small.best_path()[1] - best) < 1e-9
        within = {(tuple(lat.words(p)), round(sum(lat.score(k) for k in p), 6)) for p in lat.paths()
                  if sum(lat.score(k) for k in p) >= best - beam - 1e-9}
        got = {(tuple(small.words(p)), round(sum(small.score(k) for k in p), 6)) for p in small.paths()}
        assert within <= got
        # Every arc that is kept lies on some path within the beam.
        g = small.arc_posteriors()
        assert all(x > 0.0 for x in g)
        assert len(small.arcs) <= len(lat.arcs)


def test_cycle_and_backward_time_are_rejected():
    lat = Lattice()
    lat.add_node(0)
    lat.add_node(0)
    lat.add_arc(0, 1, "a", 0.0, 0.0)
    lat.add_arc(1, 0, "b", 0.0, 0.0)
    with pytest.raises(ValueError):
        lat.topo_order()
    lat2 = Lattice()
    lat2.add_node(5)
    lat2.add_node(3)
    with pytest.raises(ValueError):
        lat2.add_arc(0, 1, "a", 0.0, 0.0)


def test_no_path():
    lat = Lattice()
    lat.add_node(0)
    lat.add_node(1)
    lat.final = {1}
    assert lat.num_paths() == 0
    assert lat.best_path() == ([], NEG_INF)
    with pytest.raises(ValueError):
        lat.arc_posteriors()

History

Lattices came out of the work on multi-pass speech recognition around 1990, when decoders started to keep several alternatives for later passes with stronger models. Ortmanns, Ney and Aubert 1997 gave a word graph algorithm for large vocabularies and showed that about 10 word hypotheses per spoken word were enough to lose almost no accuracy. Posterior probabilities on lattices, computed by forward-backward with a scaled score, became the standard confidence measure (Wessel et al. 2001) and the basis of consensus decoding (Mangu, Brill and Stolcke 2000). Today WFST toolkits such as Kaldi store lattices as acyclic weighted automata.

References

  1. Stefan Ortmanns, Hermann Ney and Xavier Aubert, A word graph algorithm for large vocabulary continuous speech recognition, Computer Speech and Language 11(1), 1997, pages 43 to 72, the construction of word graphs during the beam search and the measurement of their density
  2. Frank Wessel, Ralf Schlüter, Klaus Macherey and Hermann Ney, Confidence measures for large vocabulary continuous speech recognition, IEEE Transactions on Speech and Audio Processing 9(3), 2001, pages 288 to 298, word posterior probabilities computed on word graphs by forward-backward, used as confidence measures
  3. Lidia Mangu, Eric Brill and Andreas Stolcke, Finding consensus in speech recognition, word error minimization and other applications of confusion networks, Computer Speech and Language 14(4), 2000, pages 373 to 400, the lattice definitions and the computation of link posteriors with a scaled combined score

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/5BPGS0/text.yaml