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
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
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)andadd_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 of the best path.
The combined log score of an arc and of a path is
which is the decoder score . The language model weight and the insertion penalty are tuned heuristics.
Representation
The nodes are numbered , 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 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: for the best path, for totals and posteriors, with weight 1 for the path count.
LATTICE-FORWARD(Λ, ⊕, ⊗, w)- 1
order ← TOPOLOGICAL-SORT(Λ) - 2
α(start) ← 1̄; α(v) ← 0̄ for every other node v - 3
for each node u in order do - 4
for each arc a from u to v: α(v) ← α(v) ⊕ (α(u) ⊗ w(a)) LATTICE-BACKWARD(Λ, ⊕, ⊗, w)- 5
β(q) ← 1̄ for each final q; β(v) ← 0̄ for every other node v - 6
for each node u in reverse order do - 7
for each arc a from u to v: β(u) ← β(u) ⊕ (w(a) ⊗ β(v)) ARC-POSTERIOR(a from u to v) ▷ α, β in the log semiring with w(a) = κ s(a); log Z = logadd of α(q) over final q- 8
γ(a) ← exp(α(u) + κ s(a) + β(v) - log Z) PRUNE(Λ, b) ▷ α, β in the (max, +) semiring with w(a) = s(a); B = the best path score- 9
keep the arcs a from u to v with α(u) + s(a) + β(v) ≥ B - b - 10
keep the start, the final nodes and the ends of the kept arcs
The acoustic scale 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 , often , 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 | ||
|---|---|---|---|
| a | 0.6 | ||
| x | 0.4 | ||
| b | 0.5 | ||
| c | 0.5 | ||
| b | 0.9 |
There are 3 paths: "a b", "a c" and "x b". With and , "a c" is best with , ahead of "x b" with . With , the language model counts more, and "x b" is best with , ahead of "a c" with and "a b" with .
With and , 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" (). Choosing word by word gives "a b", which is not the best path. A confusion network makes this idea precise. With instead, the posterior of "x" rises to 0.6674, which shows how the scale sharpens the distribution.
Pruning with 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, is the semiring sum over all paths from the start to : each path to has exactly one last arc, and its source was finished before . The same holds for in reverse. A path through an arc from to splits uniquely into a path to , the arc and a path from , so by distributivity is the sum over the paths through . In the log semiring that gives the posterior, and in it gives the best score through , 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 and a set of final nodes. A path is a sequence of arcs from to a node of . For an arc weight in a commutative semiring , the weight of a path is the -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 ,
the sum over all arc sequences from to , with 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 , already has its final value. A path to is empty (only for , which gives the of line L2) or ends with an arc from some that comes before in the order. When was processed, was final by induction, and line L4 added to . By distributivity, is the sum over the paths to whose last arc is . Each path to has exactly one last arc, so the sum over all arcs into is the sum over all paths to . No later step changes , since line L4 changes only the targets of arcs out of the node being processed, and they come after it.
Lemma 2 (backward). After LATTICE-BACKWARD, , the sum over the arc sequences from to any final node, with the empty sequence counting when .
Proof. The same induction in reverse order, with line L5 for the empty paths and line L7 for the first arc.
Corollary 1 (the three totals). The sum is
- the number of paths, in the counting semiring with all weights 1;
- the best combined score , in the Viterbi semiring ;
- , in the log semiring with weights , where .
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 with . Then, for every arc from to , line L8 gives
Proof. A path that uses uses it once, since the graph is acyclic, and it splits uniquely into a path from to , the arc , and a path from to . Every such triple is a path through . So
by Lemmas 1 and 2 in the log semiring, and dividing by gives the claim.
Corollary 2 (posteriors at a time). If every path covers each frame with exactly one arc, that is, the node times increase from at to the last time at every final node, then for every the arcs with have posteriors that add up to 1.
Proof. Each path contains exactly one such arc, so the sum of over them is .
Lemma 4 (beam pruning). Let be the best path score. With and in the Viterbi semiring, an arc from to is kept by line L9 if and only if some path through has a score of at least , where is the beam. The pruned lattice keeps every path with a score of at least , and its best path has the score .
Proof. By the same split as in Lemma 3, is the best score of a path through , which gives the first claim. A path with score at least has, for each of its arcs, a path through that arc (itself) with score at least , 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.
The pruned lattice can also hold paths with a score below , made of kept arcs from different good paths. Lemma 4 says only that no good path is lost.
Remark (floating point). The code compares with with a tolerance of , 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 be the number of nodes and 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 time and extra space, with a semiring operation in . The number of paths can be exponential in : a chain of time slots with two arcs each has paths in words of storage. The path count itself can then need bits.
Variants
- N-best lists. A list of the 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 5BPGS0 Edit this page History Report an error Markdown