Algorithmadvanced
Weighted transducer composition
Also called WFST composition.
Build the transducer of the relation of T1 followed by T2, pairing states and matching labels, with weights combined in the semiring and an epsilon filter.
- Time
- O(p q + m n) worst
- Space
- O(p q + m n) extra
- Where
- m = the number of arcs of T1; n = the number of arcs of T2; p = the number of states of T1; q = the number of states of T2
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mehryar Mohri, Fernando Pereira, Michael Riley, 1996
Weighted transducer composition takes a weighted transducer that maps strings to strings and a weighted transducer that maps to , and builds one transducer that maps to directly. Its states are pairs of states of the two machines, an arc exists where an output label of meets the same input label of , and the weights combine with the of the semiring. Speech recognizers use it to join the HMM, the context dependency, the pronunciation lexicon and the language model into one search graph (see HCLG decoding graph). Empty labels need care: without an epsilon filter, the same pair of paths can appear more than once in the result, and in a non-idempotent semiring the weights come out wrong.
In plain words
The first machine rewrites a string into another string, and gives the rewrite a cost. The second machine rewrites that result again, with its own cost. Composition builds one machine that does both rewrites in one step. A state of the new machine remembers where each of the two machines is. The new machine moves when the first machine writes a symbol and the second machine reads that same symbol. The cost of the move is the sum of the two costs.
Some moves write or read nothing. Then one machine moves and the other waits, or both move. There are several orders for such moves, and they all lead to the same place. A small extra counter allows only one order, so that each way through the two machines is counted once.
The problem
A weighted transducer over a semiring has a finite set of states, a start state , final weights , and arcs from to with input label , output label and weight (weighted automaton, finite-state transducer). A label can be , the empty string. The weight of a successful path is the -product of its arc weights and the final weight, and is the -sum of the weights of all successful paths that read and write . The composition is
The task is to build a transducer with for all and . The semiring must be commutative.
The weights here are costs , as in Mohri, Pereira and Riley 2002. A probability becomes the cost , and a probability of 0 becomes . Two semirings are used on costs: the tropical semiring , which keeps the best path, and the log semiring with , which adds probabilities. The page writes for the numbers of states and for the numbers of arcs of and .
The algorithm
The states of are triples . The filter state records the last kind of move: 0 after a matched move or a move where both machines take an arc, 1 after a move of alone, 2 after a move of alone. The algorithm builds only the triples that are reachable from the start, with a stack.
COMPOSE(T1, T2) ▷ output labels of T1 meet input labels of T2- 1
i ← (i1, i2, 0); Q ← {i}; S ← [i] - 2
while S is not empty do - 3
(q1, q2, f) ← POP(S) - 4
if q1 ∈ F1 and q2 ∈ F2 then ρ(q1, q2, f) ← ρ1(q1) ⊗ ρ2(q2) - 5
for each arc (q1, a, b, w1, n1) with b ≠ ε and each arc (q2, b, c, w2, n2) do ADD(a, c, w1 ⊗ w2, (n1, n2, 0)) - 6
if f = 0 then for each arc (q1, a, ε, w1, n1) and each arc (q2, ε, c, w2, n2) do ADD(a, c, w1 ⊗ w2, (n1, n2, 0)) - 7
if f ≠ 2 then for each arc (q1, a, ε, w1, n1) do ADD(a, ε, w1, (n1, q2, 1)) ▷ T1 moves, T2 waits - 8
if f ≠ 1 then for each arc (q2, ε, c, w2, n2) do ADD(ε, c, w2, (q1, n2, 2)) ▷ T2 moves, T1 waits - 9
return the transducer with states Q, start i, the arcs and ρ ADD(a, c, w, n) ▷ an arc out of the current triple (q1, q2, f)- 10
if n ∉ Q then add n to Q and push n on S - 11
add the arc ((q1, q2, f), a, c, w, n)
Line L5 is the plain product construction (product construction for automata). Lines L6 to L8 handle the labels. In the notation of Mohri 2009, Section 5.1, they are the composition with a three-state filter transducer : from filter state 1 only may move alone, and from filter state 2 only .
Example
Take with the arcs and , and with the arcs and . State 1 is final with weight 0 in both. There are no labels, so only line L5 runs. From it makes two arcs to : with cost through , and with cost through . The result has 2 states and 2 arcs, within the bounds and .
The weight of the pair depends on the semiring. In the tropical semiring it is , the cost of the best path. In the log semiring it is , the cost of the total probability .
Now the filter. Let be the single arc and the single arc . The only result is , from one pair of paths. The trace from :
| line | move | new triple |
|---|---|---|
| L6 | both take their arc | , final |
| L7 | alone | |
| L8 | alone |
From , may not move alone, because ; from , may not move alone, because . So the result has 4 states, 3 arcs and one successful path, of cost 0. Two of its states are dead ends, which a trim step removes. Without the filter, both dead ends lead on to , and there are three successful paths. In the tropical semiring the result is still . In the log semiring it is , which is wrong.
Correctness
The proof is in proofs/correctness.md. The search of lines L2 to L8 visits each reachable triple once and adds every move out of it once. The filter allows, between two matched moves, only the move sequences of the form or , where is a joint move, a move of alone and a move of alone, and exactly one of these words fits each pair of runs. This gives a bijection between the successful paths of and the pairs of successful paths of and that agree on the middle string, with by commutativity. Distributivity then gives .
Proof: Composition with the epsilon filter computes the composed relationfull
We use the notation of the page. The semiring is commutative: . The tropical semiring and the log semiring on costs are commutative.
A path of a transducer is a sequence of arcs, each arc starting where the previous one ends. Its input string and output string are the labels read along it with the labels dropped. A successful path starts in the start state and ends in a final state. Its weight is . The weight of a pair of strings is
and when there is no such path. The composition is defined by . If the machines have cycles, we assume that these sums are defined, as in a -closed semiring; for machines without cycles and for -free machines and a fixed all the sums are finite.
Lemma 1 (the search builds the reachable part). Call a triple reachable if a sequence of the moves of lines L5 to L8 leads to it from . The loop of lines L2 to L8 creates exactly the reachable triples, pops each of them once, and adds every move out of each of them exactly once.
Proof. Line L10 pushes a triple only when it is not yet in , so each triple is pushed and popped at most once. There are at most triples, so the loop stops. Every created triple is the target of a move from a created triple, or the start, so it is reachable. Conversely, take a reachable triple and a shortest sequence of moves to it. By induction on the length of that sequence, the triple before the last move was created and popped, and when it was popped, lines L5 to L8 made the last move, so line L10 created the triple. The arcs out of a triple are added only when that triple is popped, which happens once.
Lemma 2 (one interleaving). In the moves of lines L6 to L8, write for a joint move (both machines take an arc, line L6), for a move of alone (line L7) and for a move of alone (line L8). From filter state 0, the sequences of such moves that the filter allows are exactly the words of . For any exactly one of these words has moves of (counting and ) and moves of (counting and ).
Proof. Line L6 needs and keeps . Line L7 needs and sets . Line L8 needs and sets . So from state 1 only is allowed, from state 2 only , and from state 0 all three. A word that starts in state 0 is therefore a run of , then either a run of or a run of , and every such word is allowed. A word or with and moves of the two machines has , , and or . So , and and are fixed.
Lemma 3 (paths and pairs of paths). Let be the output of COMPOSE. There is a bijection between the successful paths of and the pairs of successful paths of and with . Under it, , and .
Proof. Projection. Each arc of was made from one arc of , one arc of , or one of each. Keeping the arcs of in order gives a path of from , and keeping the arcs gives a path of from . The last state of is final only if both components are final (line L4), so and are successful. A matched move (line L5) reads the same symbol on the output of and the input of , and the other moves read on both of these sides, so . The input labels of are those of and the output labels those of . The weights of the arcs of are the weights of the arcs of and , each used once, and the final weight is . Since is commutative and associative, .
Construction. Let . Cut into , where is the arc that writes and each is a run of arcs that write . Cut in the same way into , where reads . Build segment by segment. The filter state is 0 at the start and after each matched move. For segment , Lemma 2 gives exactly one allowed word of moves that takes the arcs of and the arcs of ; then the matched move takes and (line L5 allows it in every filter state). Every triple on the way is reachable, so by Lemma 1 all these arcs are in , and the last triple is final by line L4.
The two maps are inverse to each other. Projection of the constructed path gives back . In the other direction, a path of is determined by its projections: the matched moves of are fixed by the arcs , and by Lemma 2 the moves between two matched moves are fixed by the lengths and , since the filter state is 0 after each matched move.
Theorem. For all strings and , .
Proof. By Lemma 3, and grouping the pairs by the middle string ,
where the last step is distributivity of over .
Corollary (size without epsilons). If neither machine has an on the shared side, lines L6 to L8 never run, every triple has , and has at most states. Every arc of comes from line L5, from one pair of an arc of and an arc of . The source of that arc is the triple of the sources of and , which is popped once (Lemma 1), so each pair gives at most one arc and has at most arcs.
Remark (no filter). Without the filter, every word over is allowed, so the map of Lemma 3 is still onto but no longer one to one. Then is a sum in which each term appears one or more times. In an idempotent semiring such as the tropical one, , so the result is still right. In the log semiring it is not. With the single arc and the single arc , there are three paths (A then B, B then A, and J), and the cost of becomes instead of .
Complexity
In the word-RAM model, with the states of kept in an array indexed by the triple, or in a hash table in expected time, and the arcs of grouped by input label, a popped triple costs , where and are the out-degrees. Each triple is popped once and there are at most triples, so the time is . The output has states and arcs, which is also the space.
Without labels on the shared side, the proof shows that has at most states and at most arcs. The bound is reached: if both machines have one state and self loops that all carry the same middle label, the result has arcs. With labels from a large alphabet, most pairs of arcs do not match, and the result is much smaller than the bound. This is why recognizers compose large machines in practice. Mohri 2009 gives the same bound, where counts states and arcs.
Properties
- Exact in any commutative semiring. With the filter, every pair of paths is counted once, so the result is right in the log semiring as well as in the tropical one.
- Lazy. A triple is expanded only when the search reaches it, so the same loop can run on demand during decoding, and the parts of that are never reached are never built.
- Not trim. The result can have states that reach no final state, such as the dead ends of the example. A trim pass removes them in linear time.
- Associative. and give the same relation, so a cascade can be composed in any grouping. The sizes of the intermediate machines can differ a lot.
- Acceptors. For two weighted automata (input label equal to output label), composition is the weighted intersection.
Variants and improvements
- Without the filter. In an idempotent semiring such as the tropical one, the redundant paths do not change the weights, and some implementations skip the filter there. The result has more arcs and more paths.
- Generalized filters. Allauzen, Riley and Schalkwyk 2009 make the filter a parameter of the algorithm. Their filters also remove paths that lead nowhere, and push labels and weights forward along paths. OpenFst uses this design.
- Dynamic composition. Decoders can compose the lexicon with the language model on the fly, which avoids building the full static graph.
- Three-way and multi-tape composition. Composing three machines at once can avoid a large intermediate result.
When to use it
Use composition whenever a system is a chain of rewrites, each with its own model: phones to context dependent units, phones to words, words to a weighted language model. Compose the chain once, offline, and then optimize the result with weighted determinization, weight pushing and minimization. When the composed machine is too large to store, compose lazily at search time.
Pitfalls
- Counting paths twice. Without a filter, a pair of moves can be taken in several orders. The log semiring then adds the same probability several times, as in the example.
- The order of the machines. The output side of must meet the input side of . Swapping the machines gives a different relation, and usually an empty one.
- Sorting the arcs. Without an index by label, line L5 tests every pair of arcs, which is slow for states with many arcs. Sort or hash the arcs of one machine by label.
- Blow-up. The bound can be reached. An unpruned trigram model composed with a large lexicon can be too large for memory, so recognizers prune the language model or compose lazily.
- A non-commutative semiring. The string semiring and some product semirings are not commutative, and then the weight of a path of is not the product of the weights of the two paths. The proof needs commutativity.
Implementations
The Python code builds the reachable triples with a stack and keeps the arcs of in a dictionary by input label. It works in the tropical and in the log semiring on costs, with the filter on or off. The tests compare the weight of every string pair of the composed machine with a brute force sum over all pairs of paths of the two machines, on random machines with labels, and check that the unfiltered version is right in the tropical semiring but wrong in the log semiring.
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
weighted_transducer_composition.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-transducer-composition/. The authors are listed in prov/BWQJKE.jsonl.
"""Composition of weighted finite-state transducers, with the epsilon filter.
Weights are costs -log p, as in Mohri, Pereira and Riley 2002. The semiring is
TROPICAL (min, +) or LOG_COST (-log(exp(-a) + exp(-b)), +) from nlslog. A
transducer has states 0..n-1, one start state, a final cost per final state,
and arcs (ilabel, olabel, weight, next). EPS is the empty label.
compose(t1, t2) builds only the states (q1, q2, f) that are reachable from the
start. The filter state f in {0, 1, 2} picks one way to interleave the epsilon
moves of the two machines, so that no path is counted twice:
f = 0 after a matched move, or a move where both machines read epsilon
f = 1 after a move of t1 alone (t1 writes epsilon, t2 waits)
f = 2 after a move of t2 alone (t2 reads epsilon, t1 waits)
A move of t1 alone is allowed in f = 0 or 1, a move of t2 alone in f = 0 or 2,
and a move where both read epsilon only in f = 0.
With filter=False the three epsilon moves are always allowed. That counts some
paths more than once: harmless in TROPICAL (min is idempotent) but wrong in
LOG_COST.
"""
from typing import Dict, List, Tuple
from nlslog import TROPICAL, Semiring
EPS = "<eps>"
class Wfst:
"""A weighted transducer with integer states, weights as costs."""
def __init__(self) -> None:
self.start = 0
self.arcs: List[List[Tuple[str, str, float, int]]] = []
self.final: Dict[int, float] = {}
def add_state(self) -> int:
self.arcs.append([])
return len(self.arcs) - 1
def add_arc(self, q: int, ilabel: str, olabel: str, weight: float, nxt: int) -> None:
self.arcs[q].append((ilabel, olabel, weight, nxt))
def set_final(self, q: int, weight: float = 0.0) -> None:
self.final[q] = weight
def num_states(self) -> int:
return len(self.arcs)
def num_arcs(self) -> int:
return sum(len(a) for a in self.arcs)
def compose(t1: Wfst, t2: Wfst, sr: Semiring = TROPICAL, filter: bool = True):
"""Return (t, pairs): the composition t1 o t2 and the triple (q1, q2, f) of each state of t.
The output labels of t1 meet the input labels of t2. Without epsilons the
result has at most s1 s2 states and at most e1 e2 arcs.
Cost: O(s1 s2 d1 d2) for out-degrees d1 and d2, which is O(e1 e2).
"""
t = Wfst()
index: Dict[Tuple[int, int, int], int] = {}
pairs: List[Tuple[int, int, int]] = []
stack: List[Tuple[int, int, int]] = []
def state_of(key):
if key not in index: # @line L10
index[key] = t.add_state()
pairs.append(key)
stack.append(key)
return index[key]
# Arcs of t2 by input label, built once.
by_in: List[Dict[str, List[Tuple[str, str, float, int]]]] = []
for q in range(t2.num_states()):
d: Dict[str, List[Tuple[str, str, float, int]]] = {}
for arc in t2.arcs[q]:
d.setdefault(arc[0], []).append(arc)
by_in.append(d)
t.start = state_of((t1.start, t2.start, 0)) # @line L1
while stack: # @line L2
q1, q2, f = stack.pop() # @line L3
p = index[(q1, q2, f)]
if q1 in t1.final and q2 in t2.final: # @line L4
t.set_final(p, sr.times(t1.final[q1], t2.final[q2]))
for a, b, w1, n1 in t1.arcs[q1]:
if b != EPS: # @line L5
for _, c, w2, n2 in by_in[q2].get(b, ()):
t.add_arc(p, a, c, sr.times(w1, w2), state_of((n1, n2, 0))) # @line L11
eps1 = [arc for arc in t1.arcs[q1] if arc[1] == EPS]
eps2 = by_in[q2].get(EPS, [])
if f == 0 or not filter: # @line L6
for a, _, w1, n1 in eps1:
for _, c, w2, n2 in eps2:
t.add_arc(p, a, c, sr.times(w1, w2), state_of((n1, n2, 0)))
if f != 2 or not filter: # @line L7
for a, _, w1, n1 in eps1:
t.add_arc(p, a, EPS, w1, state_of((n1, q2, 1 if filter else 0)))
if f != 1 or not filter: # @line L8
for _, c, w2, n2 in eps2:
t.add_arc(p, EPS, c, w2, state_of((q1, n2, 2 if filter else 0)))
return t, pairs # @line L9
def relation(t: Wfst, sr: Semiring = TROPICAL, max_arcs: int = 12) -> Dict[Tuple[Tuple[str, ...], Tuple[str, ...]], float]:
"""Return the weight of each (input, output) string pair, summed over all paths of at most max_arcs arcs.
Epsilons are dropped from the strings. For an acyclic machine with fewer
than max_arcs arcs on every path this is the exact weighted relation.
The number of paths can be exponential, so use it only on small machines.
"""
out: Dict[Tuple[Tuple[str, ...], Tuple[str, ...]], float] = {}
stack = [(t.start, (), (), sr.one, 0)]
while stack:
q, x, y, w, k = stack.pop()
if q in t.final:
key = (x, y)
out[key] = sr.plus(out.get(key, sr.zero), sr.times(w, t.final[q]))
if k == max_arcs:
continue
for a, b, wa, n in t.arcs[q]:
stack.append((n, x + ((a,) if a != EPS else ()), y + ((b,) if b != EPS else ()), sr.times(w, wa), k + 1))
return out
test_weighted_transducer_composition.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-transducer-composition/. The authors are listed in prov/BWQJKE.jsonl.
import math
import random
from nlslog import LOG_COST, TROPICAL, Semiring
from weighted_transducer_composition import EPS, Wfst, compose, relation
def random_acyclic(rng: random.Random, n: int, labels_in, labels_out, p_arc: float = 0.5) -> Wfst:
t = Wfst()
for _ in range(n):
t.add_state()
for i in range(n):
for j in range(i + 1, n):
for _ in range(2):
if rng.random() < p_arc:
t.add_arc(i, rng.choice(labels_in), rng.choice(labels_out), rng.randint(0, 6) * 0.5, j)
t.set_final(n - 1, rng.randint(0, 3) * 0.5)
if rng.random() < 0.5:
t.set_final(rng.randrange(n - 1), rng.randint(0, 3) * 0.5)
return t
def random_cyclic(rng: random.Random, n: int, labels_in, labels_out, m: int) -> Wfst:
t = Wfst()
for _ in range(n):
t.add_state()
for _ in range(m):
t.add_arc(rng.randrange(n), rng.choice(labels_in), rng.choice(labels_out), rng.randint(0, 6) * 0.5, rng.randrange(n))
t.set_final(rng.randrange(n), rng.randint(0, 3) * 0.5)
return t
def brute_compose(r1, r2, sr: Semiring):
out = {}
for (x, y), w1 in r1.items():
for (y2, z), w2 in r2.items():
if y == y2:
out[(x, z)] = sr.plus(out.get((x, z), sr.zero), sr.times(w1, w2))
return out
def same(r1, r2, sr: Semiring, tol: float = 1e-9) -> bool:
keys = set(r1) | set(r2)
for k in keys:
a, b = r1.get(k, sr.zero), r2.get(k, sr.zero)
if a == b:
continue
if math.isinf(a) or math.isinf(b) or abs(a - b) > tol:
return False
return True
def one_arc(i, o, w=0.0) -> Wfst:
t = Wfst()
t.add_state()
t.add_state()
t.add_arc(0, i, o, w, 1)
t.set_final(1)
return t
def test_filter_counts_one_path():
t1 = one_arc("a", EPS)
t2 = one_arc(EPS, "c")
key = (("a",), ("c",))
for sr in (TROPICAL, LOG_COST):
t, pairs = compose(t1, t2, sr)
assert relation(t, sr)[key] == 0.0
assert sorted(pairs) == [(0, 0, 0), (0, 1, 2), (1, 0, 1), (1, 1, 0)]
assert t.num_arcs() == 3
# Without the filter there are three paths: t1 first, t2 first, or both at once.
t, _ = compose(t1, t2, LOG_COST, filter=False)
assert abs(relation(t, LOG_COST)[key] - (-math.log(3))) < 1e-12
t, _ = compose(t1, t2, TROPICAL, filter=False)
assert relation(t, TROPICAL)[key] == 0.0
def test_random_acyclic_with_epsilons_matches_brute_force():
rng = random.Random(7)
for case in range(60):
sr = LOG_COST if case % 2 else TROPICAL
t1 = random_acyclic(rng, rng.randint(2, 5), ["a", "b", EPS], ["x", "y", EPS])
t2 = random_acyclic(rng, rng.randint(2, 5), ["x", "y", EPS], ["u", "v", EPS])
t, _ = compose(t1, t2, sr)
assert same(relation(t, sr), brute_compose(relation(t1, sr), relation(t2, sr), sr), sr)
def test_no_filter_is_wrong_in_log_but_right_in_tropical():
rng = random.Random(11)
wrong = 0
for _ in range(40):
t1 = random_acyclic(rng, 4, ["a", "b"], ["x", EPS])
t2 = random_acyclic(rng, 4, ["x", EPS], ["u", "v"])
ref_t = brute_compose(relation(t1, TROPICAL), relation(t2, TROPICAL), TROPICAL)
t, _ = compose(t1, t2, TROPICAL, filter=False)
assert same(relation(t, TROPICAL), ref_t, TROPICAL)
ref_l = brute_compose(relation(t1, LOG_COST), relation(t2, LOG_COST), LOG_COST)
t, _ = compose(t1, t2, LOG_COST, filter=False)
wrong += not same(relation(t, LOG_COST), ref_l, LOG_COST)
assert wrong > 0
def test_epsilon_free_size_bound_and_cyclic_strings():
rng = random.Random(3)
for case in range(40):
sr = LOG_COST if case % 2 else TROPICAL
t1 = random_cyclic(rng, rng.randint(1, 4), ["a", "b"], ["x", "y"], rng.randint(1, 7))
t2 = random_cyclic(rng, rng.randint(1, 4), ["x", "y"], ["u", "v"], rng.randint(1, 7))
t, pairs = compose(t1, t2, sr)
assert t.num_states() <= t1.num_states() * t2.num_states()
assert t.num_arcs() <= t1.num_arcs() * t2.num_arcs()
assert all(f == 0 for _, _, f in pairs)
# Without epsilons a pair of strings of length k uses paths of exactly k arcs.
got = relation(t, sr, max_arcs=4)
ref = brute_compose(relation(t1, sr, max_arcs=4), relation(t2, sr, max_arcs=4), sr)
assert same(got, ref, sr)
def test_associative():
rng = random.Random(5)
for _ in range(20):
t1 = random_acyclic(rng, 3, ["a", "b"], ["x", EPS])
t2 = random_acyclic(rng, 3, ["x", EPS], ["u", EPS])
t3 = random_acyclic(rng, 3, ["u", EPS], ["z"])
left, _ = compose(compose(t1, t2, LOG_COST)[0], t3, LOG_COST)
right, _ = compose(t1, compose(t2, t3, LOG_COST)[0], LOG_COST)
assert same(relation(left, LOG_COST), relation(right, LOG_COST), LOG_COST)
def test_no_match_gives_empty_relation():
t, _ = compose(one_arc("a", "x", 1.0), one_arc("y", "b", 2.0))
assert relation(t) == {}
assert t.num_states() == 1 and t.num_arcs() == 0
def test_weights_add_on_a_match():
t, _ = compose(one_arc("a", "x", 1.5), one_arc("x", "b", 2.0))
assert relation(t) == {(("a",), ("b",)): 3.5}
History
Composition of unweighted transducers is a classical construction of automata theory. Mohri, Pereira and Riley 1996 gave the weighted version for language and speech, with the epsilon filter that makes it correct in any commutative semiring, and their 2002 paper in Computer Speech and Language describes recognizers built as a cascade of compositions. Mohri 2009 gives the algorithm and the filter in the general setting of weighted automata. Allauzen, Riley and Schalkwyk 2009 turned the filter into a parameter, which allows faster dynamic composition in recognizers.
References
- Mehryar Mohri, Fernando Pereira and Michael Riley, Weighted finite-state transducers in speech recognition, Computer Speech and Language 16(1), 2002, pages 69 to 88, the section on composition and its use to combine the models of a recognizer
- Mehryar Mohri, Weighted automata algorithms, in Manfred Droste, Werner Kuich and Heiko Vogler (editors), Handbook of Weighted Automata, Springer, 2009, Section 5.1 (composition: the epsilon-free algorithm, its O(|T1| |T2|) cost, the redundant epsilon paths and the filter transducer)
- Mehryar Mohri, Fernando Pereira and Michael Riley, Weighted automata in text and speech processing, ECAI 96 Workshop on Extended Finite State Models of Language, Budapest, 1996, the composition of weighted transducers and the epsilon filter
- Cyril Allauzen, Michael Riley and Johan Schalkwyk, A generalized composition algorithm for weighted finite-state transducers, Proceedings of Interspeech 2009, pages 1203 to 1206, the composition filter as a parameter of the algorithm, and the filters that remove useless epsilon paths
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 | W2 basic |
|
Tag BWQJKE Edit this page History Report an error Markdown