Data structureadvanced
Confusion network
Also called sausage.
A lattice reduced to a linear sequence of slots of competing words with posteriors, whose best path approximately minimizes expected word errors.
- Time
- O(N^2 + E^3) worst
- Space
- O(N^2 + E^2) extra
- Where
- E = the number of lattice arcs; N = the number of lattice nodes
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A confusion network, also called a sausage, is a word lattice squeezed into a straight line. It is a sequence of slots. Each slot holds the words that compete for one position, with their posterior probabilities, and an empty word for the paths that put no word there. Any choice of one entry per slot is a hypothesis. Mangu, Brill and Stolcke 2000 build it by aligning all the lattice paths with each other: the lattice arcs are clustered into slots by time overlap and word similarity, in a way that keeps the order of the lattice. Taking the most likely entry in each slot gives the consensus hypothesis. It minimizes the expected number of errors counted slot by slot, and that count is an upper bound on the word error, so the consensus approximately minimizes the expected word error, often better than the most likely path does.
In plain words
A lattice holds many possible sentences, and they share parts. The best whole sentence is not always the one with the fewest expected word mistakes. Word error counts words, so it is better to ask, position by position, which word is most likely.
To do that, you must first decide which words of different sentences stand at the same position. A confusion network lines all the sentences up. Words that cover the same stretch of time and sound alike go into the same slot, and every slot gets a "no word" choice for the sentences that skip it. Then you pick the strongest word in each slot.
The abstract type
A confusion network is built once from a lattice and then queried.
build(lattice, λ, ip, κ, θ)computes arc posteriors with the language model weight , the insertion penalty and the acoustic scale , drops the arcs with a posterior of at most , and aligns the rest into slots.slots[i]maps each word of slot to its posterior , andeps[i]is .consensus()returns the word of largest posterior in each slot, without .expected_errors(c)returns for one choice per slot.slot_of[e]is the slot of lattice arc .
Representation
The network is a list of slots, each a map from words to posteriors, plus one number for . As a graph it has nodes in a line and one arc per entry between neighbors. The code also keeps the slot of every lattice arc.
Invariant.
- (C1) Probabilities. In every slot, the word posteriors and are at least 0 and add up to 1.
- (C2) Order. If a lattice arc can come before an arc on a path, the slot of is before the slot of .
- (C3) Exclusion. No lattice path uses two arcs of the same slot.
Operations
BUILD-CONFUSION-NETWORK(Λ, λ, ip, κ, θ)- 1
γ ← ARC-POSTERIORS(Λ, λ, ip, κ); keep the arcs with γ(e) > θ - 2
e ≺ f ⟺ a path of kept arcs leads from the end of e to the start of f - 3
classes ← the kept arcs grouped by (word, start time, end time); < ← the transitive closure of ≺ on classes - 4
while two unordered classes with the same word have SIM₁ > 0 do - 5
MERGE the pair with the largest SIM₁ - 6
while two classes are unordered do - 7
MERGE the pair with the largest SIM₂ - 8
sort the classes by <; slot i gets p_i(w) ← the sum of γ(e) over e in C_i with the word w - 9
p_i(ε) ← 1 - the sum of p_i(w) over the words w CONSENSUS(network)- 10
for each slot i: choose the word or ε with the largest p_i, and output the words
The similarities are those of Mangu, Brill and Stolcke 2000. For the intra-word step, is the largest over and , where the overlap is the common time of the two arcs divided by the sum of their lengths. For the inter-word step, is the average of over the words of and of , where is 1 minus the edit distance of the pronunciations divided by the sum of their lengths. The code has no pronunciations and uses the letters of the words instead. You can pass another similarity.
MERGE joins two unordered classes and . The new class comes after every class that came before or and before every class that came after or , and every class before now also comes before every class after , and the other way round. This keeps the order transitive and consistent with the lattice, and it never orders a class before itself, because and were unordered. Each merge removes a class, and the loop of line L6 runs until every pair is ordered, so the result is a total order.
The acoustic scale of line L1 matters as much as on the lattice. Mangu, Brill and Stolcke 2000 found that the best scale was 1 for the language model log probabilities and for the acoustic ones. With a peaked posterior, the consensus moves to the most likely path.
Example
Take the lattice of the word lattice page with and . The arcs a and x span the frames 0 to 30, and the arcs b (twice), c span 30 to 60. Their posteriors are a 0.6262, x 0.3738, b 0.2819 (after a), c 0.3443 and b 0.3738 (after x).
- Line L3 gives four classes: , , (same word and same times) and . The lattice orders before and , and before .
- No two classes have the same word, so the intra-word step does nothing.
- Three pairs are unordered: ; ; and , since no path goes from x to c. Every pair of distinct one-letter words has the similarity , so is , and . The first pair is merged. The new class comes before both and , so only is left, and it is merged next.
The network has two slots with no :
| slot | entries |
|---|---|
| 1 | a 0.6262, x 0.3738 |
| 2 | b 0.6557, c 0.3443 |
The consensus is "a b", with expected errors. The most likely path "x b" has 0.9705, and "a c" has 1.0295. Here "a b" is the path with the lowest score in the lattice, yet it has the fewest expected errors. The network has paths, one more than the lattice: "x c" was not a lattice path.
With instead, the slots become a 0.3326, x 0.6674 and b 0.7070, c 0.2930, and the consensus is "x b", the most likely path. This is the effect of a peaked posterior.
Correctness
The proof is in proofs/correctness.md. Line L3 starts with a consistent order, since start times strictly increase along the lattice order. MERGE keeps the order irreflexive, transitive and consistent with the lattice whenever the two classes are unordered, so two arcs in one class are never on one path. Hence each lattice path picks at most one entry per slot, which gives three facts. Every lattice path is a network path, with in the slots it skips. The posterior is the probability that a path has the word in slot , and is the probability that it has nothing there. The expected number of slots in which a choice differs from a random path is . The consensus minimizes each term. Finally, the slots align any two hypotheses, so the slot errors are at least the word edit distance, and the consensus minimizes an upper bound on the expected word error, not the word error itself.
The tests check these facts on random lattices against enumeration of all paths, and check that the consensus is the best of all network paths by the slot error.
Proof: Lattice alignment gives a totally ordered network whose consensus minimizes the expected slot errorsfull
We use the notation of the page. The lattice has node times, and every arc goes from a node to a node with . We write and for these two times. A path is a sequence of arcs from the start to a final node, and is its posterior. The posterior of an arc is . Line L1 computes it exactly by forward-backward, as proved on the page word lattice. We take the threshold until the last remark, so the kept arcs are the arcs with , that is, the arcs on at least one path.
For two kept arcs, means that a path of kept arcs leads from the end node of to the start node of (line L2). If , then , so .
Lemma 0. For kept arcs , if and only if some path of the lattice holds both, with first.
Proof. If a path holds and later , its arcs between them lead from the end of to the start of , and they are kept because they lie on a path. Conversely, let through kept arcs. Take a path through and cut it after , take the connecting arcs, and take a path through from the start node of on. Since every arc moves forward in time, this is a path, and it holds and then .
A class order is a relation on the classes that is irreflexive and transitive. It is consistent if implies , where is the class of . The code stores as the sets .
Lemma 1 (initial order). After line L3, the sets are a consistent class order.
Proof. Every class has one start time, and gets as a successor only if starts later. Line L3 adds if some arc of precedes some arc of , together with all successors of , which were computed earlier because starts later. By induction on the start time from the last, is the transitive closure of this direct relation, and it is irreflexive since start times strictly increase along it. If , then , so , the class of starts later, and line L3 puts in .
Lemma 2 (merging). Let be a consistent class order and let be unordered: neither nor . After the sets are again a consistent class order on the new classes.
Proof. Let and . The code sets for the merged class and adds to for each . Other classes keep their sets, and none of them held , since all classes before are in . So the new relation is: if for old classes, for , for , and for and .
and are disjoint, and neither contains or . If , then one of , , or holds. The first two break irreflexivity by transitivity, and the last two order and . If , then or , which is excluded, and the other cases are alike.
Irreflexive: would need , and for an old class would need or .
Transitive: let . If both steps are old pairs, . If , then and , so . If is a pair or , then , and is either an old pair, which gives by transitivity, or a pair or a step into , and both need , which is impossible. So . The case where is a pair or is symmetric, with .
Consistent: if , the old order has . If neither class is or , the pair is kept. If , then , so , and if , then . Both cannot be in , because and are unordered and is irreflexive.
Corollary 1 (classes hold no ordered arcs). At every step, two arcs in one class satisfy neither nor . So by Lemma 0, no path holds two arcs of one class.
Proof. Consistency gives from , and is irreflexive.
Lemma 3 (termination and a total order). The two loops stop after at most merges, and at the end every two classes are ordered.
Proof. Each merge removes one class. The loop of line L6 merges whenever some pair is unordered, with any similarity, so it stops only when every pair is ordered.
With a total strict order on classes, the -th class from the left has exactly successors, so sorting by the number of successors gives the order. These classes are the slots.
Theorem 1 (every path is a network path). For every path of the lattice, the slots of its arcs strictly increase. So is a path of the network that takes the word of in the slot of and in every other slot.
Proof. All arcs of are kept, and , so consistency gives that the slot of is before the slot of .
Theorem 2 (slot posteriors). For a slot and a word , line L8 computes
the slot mass is at most 1, and from line L9 is the posterior of the paths with no arc in .
Proof. Expand and swap the sums. By Corollary 1, a path has at most one arc in , so is 0 or 1, and it is 1 exactly when has an arc with the word in . For the same reason the events for different words are disjoint, so the mass is the probability that has an arc in , which is at most 1, and minus it is the probability of no arc.
Theorem 3 (consensus). Map each path to its slot sequence , with a word or in each slot, as in Theorem 1. For a choice of a word or per slot, let the slot error be . Then
which is what expected_errors returns, and the choice of line L10, the largest in each slot, minimizes it. Moreover, , the word edit distance between the two word sequences after the are dropped.
Proof. By linearity of expectation, the expected slot error is , and by Theorem 2, for words and for . The terms depend on different , so the sum is smallest when each maximizes . For the bound, the slots align the two sequences: a slot with in both is skipped, equal words are matches, and the other slots are substitutions, insertions or deletions. This is one alignment, its cost is , and the edit distance is the smallest cost of any alignment.
So the consensus minimizes the expected slot error exactly, and the expected slot error is an upper bound on the expected word error of the same hypothesis. The consensus therefore only approximately minimizes the expected word error. The bound is tight when the alignment by slots is optimal for the pairs that carry most of the posterior mass, which the clustering tries to achieve but does not guarantee: the problem of the best multiple alignment has no known efficient solution, and the clustering is a heuristic.
Remark (a threshold ). The order of line L2 then uses only the kept arcs, which is the purpose of pruning: unlikely paths no longer force likely words into different slots. Lemma 0 fails, two arcs in a class can lie on one lattice path through pruned arcs, and the slot mass can exceed 1 by at most the posterior of such paths. Lemmas 1 to 3 and the minimization in Theorem 3 over the computed slot posteriors still hold. The code sets to 0 when the mass is above , which also absorbs rounding. Theorem 1 holds for the paths that use only kept arcs.
Complexity
Let be the number of lattice nodes and the number of arcs. The posteriors take time. The reachability of line L2 takes time and bits. The initial order compares arcs of all pairs of classes, in total. Each round of a clustering loop looks at all pairs of classes, at a cost of for the similarities and order tests, and a merge updates successor sets of size . There are at most merges, so the clustering takes time, which matches the of Mangu, Brill and Stolcke for links. In total this is time and space, with a word similarity in . That is why the lattice is pruned first: Mangu, Brill and Stolcke report that about 95 percent of the links can be removed without hurting the consensus.
The consensus, the expected errors and the path count take time linear in the size of the network.
Variants
- Pruning threshold. With , unlikely paths no longer force likely words into different slots. This helped accuracy in the original experiments. The slot mass can then exceed 1 a little, since two arcs of one slot can share a pruned path.
- Without times. If the lattice has no times, the overlap can use path lengths as approximate times, or the intra-word step can use the posteriors alone, as tested by Mangu, Brill and Stolcke.
- Other similarities. Phone edit distance with features such as voicing, or plain letter distance as in the code.
- Minimum Bayes risk decoding. The consensus is a cheap form of minimum Bayes risk decoding with an alignment fixed in advance. Exact search for the minimum expected word error over a lattice is much harder.
- System combination. Networks from several recognizers can be aligned with each other and voted on, slot by slot.
When to use it
Use a confusion network when the goal is a low word error rate and you have lattices with good posteriors. It also gives a word confidence (the slot posterior), compact storage of the alternatives, and a simple index for keyword spotting. Do not use it when a later step needs the exact sentence set of the lattice: the network adds paths that the lattice did not have, and it loses the language model scores between words.
Pitfalls
- Unscaled posteriors. With , almost all the mass goes to the best path, and the consensus is just the most likely path.
- Low-probability arcs. One unlikely path that puts a word before a similar word can force them into different slots. Prune first.
- Not exact. The consensus minimizes the expected slot error, not the expected word error. The clustering is a heuristic, and the best multiple alignment has no known efficient algorithm.
- New sentences. The consensus may not be a path of the lattice at all, and it may not be grammatical.
- Silence and filler words. They should be mapped to before the consensus, or they compete with real words.
- Cubic time. Without pruning, the clustering is slow on large lattices.
Implementations
The Python code computes arc posteriors by forward-backward on a lattice whose arcs move forward in time, the reachability of nodes as bit masks, the initial classes and their order, the two clustering loops with the similarities of the paper (letters in place of phones), and the slots with . The tests compare slot posteriors and with enumeration of all lattice paths, check that every lattice path maps to increasing slots, check that the consensus has the smallest expected slot error of all network paths and that the slot error is at least the word edit distance, check pruning, 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
# Part of https://algorithm.tamnd.com/confusion-network/. The authors are listed in prov/Q6R3VD.jsonl.
"""Confusion networks built from word lattices by lattice alignment.
This follows the clustering of Mangu, Brill and Stolcke (2000):
1. compute the posterior of every lattice arc by forward-backward, with an
acoustic scale kappa (1 / lm_weight by default), and drop the arcs whose
posterior is at most a threshold theta;
2. group the arcs with the same word, start time and end time into classes,
ordered by the lattice: class A comes before class B if a path leads from
the end of an arc of A to the start of an arc of B (transitive closure);
3. intra-word clustering: merge unordered classes of the same word, the pair
with the largest max over arc pairs of overlap * p(e) * p(f) first, while
that value is positive;
4. inter-word clustering: merge unordered classes, the pair with the largest
average over word pairs of sim(w1, w2) * p(w1) * p(w2) first, until every
pair is ordered;
5. the classes, in order, are the slots. The missing mass of a slot is the
posterior of the empty word EPS.
The paper uses a phonetic similarity: 1 minus the edit distance of the phone
strings normalized by the sum of their lengths. This module has no
pronunciations, so word_similarity applies the same formula to letters. Pass
another function to build() to change it.
The consensus hypothesis takes the word of largest posterior in each slot. It
minimizes the expected number of errors counted along the slots, which is an
upper bound on the word error, so it approximately minimizes the expected word
error of the lattice.
"""
import math
from typing import Callable, Dict, Iterator, List, Optional, Set, Tuple
from nlslog import LOG, NEG_INF
EPS = "-"
Arc = Tuple[int, int, str, float, float]
class Lattice:
"""A word lattice whose arcs all move forward in time: time[src] < time[dst]."""
def __init__(self) -> None:
self.times: List[int] = []
self.arcs: List[Arc] = []
self.out_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([])
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 move forward in time")
self.arcs.append((src, dst, word, ac, lm))
self.out_arcs[src].append(len(self.arcs) - 1)
return len(self.arcs) - 1
def topo_order(self) -> List[int]:
# Every arc moves forward in time, so sorting by time is a topological order.
return sorted(range(len(self.times)), key=lambda v: (self.times[v], v))
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 log_posteriors(self, lm_weight: float = 1.0, ip: float = 0.0, kappa: Optional[float] = None) -> List[float]:
"""Return the log posterior of each arc (NEG_INF if no complete path uses it)."""
if kappa is None:
kappa = 1.0 / lm_weight
w = [kappa * self.score(k, lm_weight, ip) for k in range(len(self.arcs))]
order = self.topo_order()
alpha = [NEG_INF] * len(self.times)
alpha[self.start] = 0.0
for u in order:
for k in self.out_arcs[u]:
v = self.arcs[k][1]
alpha[v] = LOG.plus(alpha[v], alpha[u] + w[k])
beta = [NEG_INF] * len(self.times)
for q in self.final:
beta[q] = 0.0
for u in reversed(order):
for k in self.out_arcs[u]:
beta[u] = LOG.plus(beta[u], w[k] + beta[self.arcs[k][1]])
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")
out = []
for k, (u, v, _, _, _) in enumerate(self.arcs):
g = alpha[u] + w[k] + beta[v]
out.append(g - z if g > NEG_INF else NEG_INF)
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 edit_distance(a, b) -> int:
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] != b[j - 1]))
prev = cur
return prev[-1]
def word_similarity(w1: str, w2: str) -> float:
"""1 minus the letter edit distance normalized by the sum of the lengths (a stand-in for phones)."""
if not w1 and not w2:
return 1.0
return 1.0 - edit_distance(w1, w2) / (len(w1) + len(w2))
class ConfusionNetwork:
def __init__(self, slots: List[Dict[str, float]], eps: List[float], slot_of: Dict[int, int]) -> None:
self.slots = slots # slots[i][w] = posterior of word w in slot i
self.eps = eps # eps[i] = posterior of the empty word in slot i
self.slot_of = slot_of # lattice arc id -> slot index, for the arcs that were kept
def consensus_slots(self) -> List[str]:
"""The word of largest posterior in each slot, EPS included (ties go to the smaller word)."""
out = []
for words, e in zip(self.slots, self.eps):
w, p = max(sorted(words.items()), key=lambda item: item[1])
out.append(w if p >= e else EPS) # @line L10
return out
def consensus(self) -> List[str]:
return [w for w in self.consensus_slots() if w != EPS]
def expected_errors(self, choice: List[str]) -> float:
"""Expected number of errors, counted slot by slot, of one choice per slot (EPS allowed)."""
total = 0.0
for words, e, w in zip(self.slots, self.eps, choice):
total += 1.0 - (e if w == EPS else words.get(w, 0.0))
return total
def num_paths(self) -> int:
n = 1
for words, e in zip(self.slots, self.eps):
n *= len(words) + (1 if e > 0.0 else 0)
return n
def build(lat: Lattice, lm_weight: float = 1.0, ip: float = 0.0, kappa: Optional[float] = None,
theta: float = 0.0, similarity: Callable[[str, str], float] = word_similarity) -> ConfusionNetwork:
times, arcs = lat.times, lat.arcs
logp = lat.log_posteriors(lm_weight, ip, kappa) # @line L1
post: Dict[int, float] = {}
for k, g in enumerate(logp):
if g > NEG_INF and (theta <= 0.0 or math.exp(g) > theta):
post[k] = math.exp(g)
# Reachability over the kept arcs, as bit masks, in reverse topological order.
kept_out: List[List[int]] = [[] for _ in times]
for k in post:
kept_out[arcs[k][0]].append(k)
reach = [0] * len(times)
for v in reversed(lat.topo_order()):
r = 1 << v
for k in kept_out[v]:
r |= reach[arcs[k][1]]
reach[v] = r
def before(e: int, f: int) -> bool: # @line L2
return (reach[arcs[e][1]] >> arcs[f][0]) & 1 == 1
# Initial classes: the kept arcs with the same word, start time and end time.
groups: Dict[Tuple[int, int, str], List[int]] = {}
for k in sorted(post):
u, v, word, _, _ = arcs[k]
groups.setdefault((times[u], times[v], word), []).append(k)
keys = sorted(groups)
classes: Dict[int, List[int]] = {c: groups[key] for c, key in enumerate(keys)}
start_of = {c: key[0] for c, key in enumerate(keys)}
succ: Dict[int, Set[int]] = {}
for c in sorted(classes, key=lambda c: -start_of[c]): # @line L3
s: Set[int] = set()
for d in classes:
if start_of[d] > start_of[c] and d not in s:
if any(before(e, f) for e in classes[c] for f in classes[d]):
s.add(d)
s |= succ[d]
succ[c] = s
def ordered(a: int, b: int) -> bool:
return b in succ[a] or a in succ[b]
def merge(a: int, b: int) -> None:
"""Merge class b into class a and keep the order transitively closed."""
preds = [p for p in classes if a in succ[p] or b in succ[p]]
after = succ[a] | succ[b]
for p in preds:
succ[p] |= after
succ[p].add(a)
succ[p].discard(b)
succ[a] = after
classes[a] = classes[a] + classes[b]
del classes[b]
del succ[b]
def overlap(e: int, f: int) -> float:
s1, e1 = times[arcs[e][0]], times[arcs[e][1]]
s2, e2 = times[arcs[f][0]], times[arcs[f][1]]
return max(0, min(e1, e2) - max(s1, s2)) / ((e1 - s1) + (e2 - s2))
def word_post(c: int) -> Dict[str, float]:
out: Dict[str, float] = {}
for k in classes[c]:
out[arcs[k][2]] = out.get(arcs[k][2], 0.0) + post[k]
return out
def sim_intra(a: int, b: int) -> float:
return max(overlap(e, f) * post[e] * post[f] for e in classes[a] for f in classes[b])
def sim_inter(a: int, b: int) -> float:
pa, pb = word_post(a), word_post(b)
total = sum(similarity(w1, w2) * p1 * p2 for w1, p1 in pa.items() for w2, p2 in pb.items())
return total / (len(pa) * len(pb))
# Intra-word clustering. Every class still holds one word here.
while True: # @line L4
best = None
ids = sorted(classes)
for i, a in enumerate(ids):
for b in ids[i + 1:]:
if arcs[classes[a][0]][2] == arcs[classes[b][0]][2] and not ordered(a, b):
s = sim_intra(a, b)
if s > 0.0 and (best is None or s > best[0]):
best = (s, a, b)
if best is None:
break
merge(best[1], best[2]) # @line L5
# Inter-word clustering, until the order is total.
while True: # @line L6
best = None
ids = sorted(classes)
for i, a in enumerate(ids):
for b in ids[i + 1:]:
if not ordered(a, b):
s = sim_inter(a, b)
if best is None or s > best[0]:
best = (s, a, b)
if best is None:
break
merge(best[1], best[2]) # @line L7
# In a total order, the first class has the most successors.
order = sorted(classes, key=lambda c: -len(succ[c]))
slots: List[Dict[str, float]] = []
eps: List[float] = []
slot_of: Dict[int, int] = {}
for i, c in enumerate(order):
words = word_post(c) # @line L8
slots.append(words)
e = 1.0 - sum(words.values()) # @line L9
eps.append(e if e > 1e-12 else 0.0) # rounding, or pruned arcs, can push the mass past 1
for k in classes[c]:
slot_of[k] = i
return ConfusionNetwork(slots, eps, slot_of)
nlslog.py 152 lines
# 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
test_confusion_network.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/confusion-network/. The authors are listed in prov/Q6R3VD.jsonl.
import itertools
import math
import random
import pytest
from confusion_network import EPS, Lattice, build, edit_distance, word_similarity
WORDS = ["a", "an", "and", "the", "then", "in"]
def random_lattice(rng: random.Random) -> Lattice:
"""A start node at time 0, a final node at time T, and middle nodes at random times."""
T = rng.randint(3, 7)
lat = Lattice()
lat.add_node(0)
end = lat.add_node(T)
mids = [lat.add_node(rng.randint(1, T - 1)) for _ in range(rng.randint(1, 5))]
lat.final = {end}
def arc(u: int, v: int) -> None:
span = lat.times[v] - lat.times[u]
lat.add_arc(u, v, rng.choice(WORDS), -rng.uniform(0, 3) * span, -rng.uniform(0, 3))
m = rng.choice(mids)
arc(0, m)
arc(m, end)
nodes = list(range(len(lat.times)))
for _ in range(rng.randint(2, 9)):
u, v = rng.choice(nodes), rng.choice(nodes)
if lat.times[u] < lat.times[v]:
arc(u, v)
return lat
def path_posteriors(lat: Lattice, lw: float):
paths = list(lat.paths())
logp = [sum(lat.score(k, lw) for k in p) / lw for p in paths]
m = max(logp)
z = m + math.log(sum(math.exp(x - m) for x in logp))
return paths, [math.exp(x - z) for x in logp]
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():
cn = build(page_example(), lm_weight=10.0)
assert len(cn.slots) == 2
assert sorted(cn.slots[0]) == ["a", "x"] and sorted(cn.slots[1]) == ["b", "c"]
assert cn.slots[0]["a"] == pytest.approx(0.6262, abs=1e-4)
assert cn.slots[1]["b"] == pytest.approx(0.6557, abs=1e-4)
assert all(e < 1e-12 for e in cn.eps)
# The consensus "a b" differs from the best path "x b" and has fewer expected errors.
assert cn.consensus() == ["a", "b"]
assert cn.expected_errors(["a", "b"]) == pytest.approx(0.7181, abs=1e-4)
assert cn.expected_errors(["x", "b"]) == pytest.approx(0.9705, abs=1e-4)
assert cn.num_paths() == 4
def test_every_lattice_path_is_a_network_path_and_the_order_is_kept():
rng = random.Random(51)
for _ in range(60):
lat = random_lattice(rng)
cn = build(lat, lm_weight=rng.choice([1.0, 3.0]))
for p in lat.paths():
slots = [cn.slot_of[k] for k in p]
assert slots == sorted(slots) and len(set(slots)) == len(slots)
assert all(lat.arcs[k][2] in cn.slots[cn.slot_of[k]] for k in p)
kept = sorted(cn.slot_of)
for e in kept:
for f in kept:
if e != f and lat.arcs[e][1] == lat.arcs[f][0]:
assert cn.slot_of[e] < cn.slot_of[f]
def test_slot_posteriors_match_enumeration():
rng = random.Random(52)
for _ in range(60):
lat = random_lattice(rng)
lw = rng.choice([1.0, 3.0])
cn = build(lat, lm_weight=lw)
paths, prob = path_posteriors(lat, lw)
n = len(cn.slots)
expect = [dict() for _ in range(n)]
missing = [0.0] * n
for p, pr in zip(paths, prob):
hit = set()
for k in p:
i = cn.slot_of[k]
w = lat.arcs[k][2]
expect[i][w] = expect[i].get(w, 0.0) + pr
hit.add(i)
for i in range(n):
if i not in hit:
missing[i] += pr
for i in range(n):
assert set(expect[i]) == set(cn.slots[i])
assert all(abs(expect[i][w] - cn.slots[i][w]) < 1e-9 for w in expect[i])
assert sum(cn.slots[i].values()) <= 1.0 + 1e-9
assert abs(cn.eps[i] - missing[i]) < 1e-9
def test_consensus_minimizes_slot_errors_which_bound_word_errors():
rng = random.Random(53)
for _ in range(40):
lat = random_lattice(rng)
cn = build(lat, lm_weight=2.0)
best = cn.consensus_slots()
choices = [sorted(s) + ([EPS] if e > 0.0 else []) for s, e in zip(cn.slots, cn.eps)]
if cn.num_paths() <= 5000:
low = min(cn.expected_errors(list(c)) for c in itertools.product(*choices))
assert cn.expected_errors(best) <= low + 1e-12
hyp = cn.consensus()
for p in lat.paths():
ref = [EPS] * len(cn.slots)
for k in p:
ref[cn.slot_of[k]] = lat.arcs[k][2]
slot_errors = sum(1 for x, y in zip(best, ref) if x != y)
assert slot_errors >= edit_distance(hyp, [w for w in ref if w != EPS])
def test_pruning_drops_unlikely_arcs():
rng = random.Random(54)
for _ in range(30):
lat = random_lattice(rng)
gamma = [math.exp(g) if g > float("-inf") else 0.0 for g in lat.log_posteriors(2.0)]
cn = build(lat, lm_weight=2.0, theta=0.1)
assert set(cn.slot_of) == {k for k, g in enumerate(gamma) if g > 0.1}
assert all(e >= 0.0 for e in cn.eps)
def test_similarity_and_errors():
assert word_similarity("then", "then") == 1.0
assert word_similarity("the", "then") == pytest.approx(1 - 1 / 7)
assert edit_distance(["a", "b"], ["b"]) == 1
lat = Lattice()
lat.add_node(0)
lat.add_node(0)
with pytest.raises(ValueError):
lat.add_arc(0, 1, "a", 0.0, 0.0)
lat2 = Lattice()
lat2.add_node(0)
lat2.add_node(1)
lat2.final = {1}
with pytest.raises(ValueError):
build(lat2)
History
Stolcke, Konig and Weintraub 1997 minimized word error over N-best lists, which is limited by the size of the list. Mangu, Brill and Stolcke 2000 moved word error minimization to lattices by aligning all the lattice paths into one confusion network, and they showed that it lowered the word error in their experiments, which included Switchboard. The same paper used the networks for lattice compression, word spotting and confidence annotation.
References
- 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 alignment algorithm (initial classes, intra-word and inter-word clustering, pruning), confusion networks with the empty word, and the consensus hypothesis
- The same paper as submitted, arXiv cs/0010012, 2000, Section 3 (the algorithm, with the similarity measures in equations 5 and 6 and the score scaling in Section 3.7), Appendix B (pseudo-code and the O(T^3) cost) and Appendix C (proof that merging keeps a consistent partial order)
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 | W2 basic |
|
Tag Q6R3VD Edit this page History Report an error Markdown