Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Mehryar Mohri, Fernando Pereira, Michael Riley, 1996

Weighted transducer composition takes a weighted transducer T1T_1 that maps strings xx to strings yy and a weighted transducer T2T_2 that maps yy to zz, and builds one transducer T1∘T2T_1 \circ T_2 that maps xx to zz directly. Its states are pairs of states of the two machines, an arc exists where an output label of T1T_1 meets the same input label of T2T_2, and the weights combine with the ⊗\otimes 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 (K,⊕,⊗,0ˉ,1ˉ)(K, \oplus, \otimes, \bar 0, \bar 1) has a finite set of states, a start state ii, final weights ρ(q)\rho(q), and arcs (q,a,b,w,n)(q, a, b, w, n) from qq to nn with input label aa, output label bb and weight ww (weighted automaton, finite-state transducer). A label can be ε\varepsilon, the empty string. The weight of a successful path is the ⊗\otimes-product of its arc weights and the final weight, and T(x,y)T(x, y) is the ⊕\oplus-sum of the weights of all successful paths that read xx and write yy. The composition is

(T1∘T2)(x,z)=⨁yT1(x,y)⊗T2(y,z).(T_1 \circ T_2)(x, z) = \bigoplus_{y} T_1(x, y) \otimes T_2(y, z).

The task is to build a transducer TT with T(x,z)=(T1∘T2)(x,z)T(x, z) = (T_1 \circ T_2)(x, z) for all xx and zz. The semiring must be commutative.

The weights here are costs c=−log⁡pc = -\log p, as in Mohri, Pereira and Riley 2002. A probability pp becomes the cost −log⁡p-\log p, and a probability of 0 becomes +∞+\infty. Two semirings are used on costs: the tropical semiring (R∪{+∞},min⁡,+,+∞,0)(\mathbb{R} \cup \{+\infty\}, \min, +, +\infty, 0), which keeps the best path, and the log semiring with a⊕b=−log⁡(e−a+e−b)a \oplus b = -\log(e^{-a} + e^{-b}), which adds probabilities. The page writes s1,s2s_1, s_2 for the numbers of states and e1,e2e_1, e_2 for the numbers of arcs of T1T_1 and T2T_2.

The algorithm

The states of TT are triples (q1,q2,f)(q_1, q_2, f). The filter state ff records the last kind of move: 0 after a matched move or a move where both machines take an ε\varepsilon arc, 1 after a move of T1T_1 alone, 2 after a move of T2T_2 alone. The algorithm builds only the triples that are reachable from the start, with a stack.

  1. COMPOSE(T1, T2) ▷ output labels of T1 meet input labels of T2
  2. 1i ← (i1, i2, 0); Q ← {i}; S ← [i]
  3. 2while S is not empty do
  4. 3(q1, q2, f) ← POP(S)
  5. 4if q1 ∈ F1 and q2 ∈ F2 then ρ(q1, q2, f) ← ρ1(q1) ⊗ ρ2(q2)
  6. 5for 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))
  7. 6if 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))
  8. 7if f ≠ 2 then for each arc (q1, a, ε, w1, n1) do ADD(a, ε, w1, (n1, q2, 1)) ▷ T1 moves, T2 waits
  9. 8if f ≠ 1 then for each arc (q2, ε, c, w2, n2) do ADD(ε, c, w2, (q1, n2, 2)) ▷ T2 moves, T1 waits
  10. 9return the transducer with states Q, start i, the arcs and ρ
  11. ADD(a, c, w, n) ▷ an arc out of the current triple (q1, q2, f)
  12. 10if n ∉ Q then add n to Q and push n on S
  13. 11add 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 ε\varepsilon labels. In the notation of Mohri 2009, Section 5.1, they are the composition T~1∘F∘T~2\tilde T_1 \circ F \circ \tilde T_2 with a three-state filter transducer FF: from filter state 1 only T1T_1 may move alone, and from filter state 2 only T2T_2.

Example

Take T1T_1 with the arcs 0→a:x/110 \xrightarrow{a:x/1} 1 and 0→a:y/210 \xrightarrow{a:y/2} 1, and T2T_2 with the arcs 0→x:u/0.510 \xrightarrow{x:u/0.5} 1 and 0→y:u/0.2510 \xrightarrow{y:u/0.25} 1. State 1 is final with weight 0 in both. There are no ε\varepsilon labels, so only line L5 runs. From (0,0,0)(0, 0, 0) it makes two arcs to (1,1,0)(1, 1, 0): a:ua{:}u with cost 1+0.5=1.51 + 0.5 = 1.5 through xx, and a:ua{:}u with cost 2+0.25=2.252 + 0.25 = 2.25 through yy. The result has 2 states and 2 arcs, within the bounds s1s2=4s_1 s_2 = 4 and e1e2=4e_1 e_2 = 4.

The weight of the pair (a,u)(a, u) depends on the semiring. In the tropical semiring it is min⁡(1.5,2.25)=1.5\min(1.5, 2.25) = 1.5, the cost of the best path. In the log semiring it is −log⁡(e−1.5+e−2.25)=−log⁡(0.223130+0.105399)=1.113129-\log(e^{-1.5} + e^{-2.25}) = -\log(0.223130 + 0.105399) = 1.113129, the cost of the total probability 0.3285290.328529.

Now the filter. Let T1T_1 be the single arc 0→a:ε/010 \xrightarrow{a:\varepsilon/0} 1 and T2T_2 the single arc 0→ε:c/010 \xrightarrow{\varepsilon:c/0} 1. The only result is T1∘T2(a,c)=0+0=0T_1 \circ T_2(a, c) = 0 + 0 = 0, from one pair of paths. The trace from (0,0,0)(0, 0, 0):

line move new triple
L6 both take their ε\varepsilon arc (1,1,0)(1, 1, 0), final
L7 T1T_1 alone (1,0,1)(1, 0, 1)
L8 T2T_2 alone (0,1,2)(0, 1, 2)

From (1,0,1)(1, 0, 1), T2T_2 may not move alone, because f=1f = 1; from (0,1,2)(0, 1, 2), T1T_1 may not move alone, because f=2f = 2. 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 (1,1)(1, 1), and there are three successful paths. In the tropical semiring the result is still min⁡(0,0,0)=0\min(0, 0, 0) = 0. In the log semiring it is −log⁡3=−1.098612-\log 3 = -1.098612, 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 J∗A∗J^* A^* or J∗B∗J^* B^*, where JJ is a joint ε\varepsilon move, AA a move of T1T_1 alone and BB a move of T2T_2 alone, and exactly one of these words fits each pair of ε\varepsilon runs. This gives a bijection between the successful paths of TT and the pairs of successful paths of T1T_1 and T2T_2 that agree on the middle string, with w(π)=w(π1)⊗w(π2)w(\pi) = w(\pi_1) \otimes w(\pi_2) by commutativity. Distributivity then gives T(x,z)=⨁yT1(x,y)⊗T2(y,z)T(x, z) = \bigoplus_y T_1(x, y) \otimes T_2(y, z).

Proof: Composition with the epsilon filter computes the composed relationfull

We use the notation of the page. The semiring (K,⊕,⊗,0ˉ,1ˉ)(K, \oplus, \otimes, \bar 0, \bar 1) is commutative: a⊗b=b⊗aa \otimes b = b \otimes a. The tropical semiring (R∪{+∞},min⁡,+,+∞,0)(\mathbb{R} \cup \{+\infty\}, \min, +, +\infty, 0) and the log semiring on costs are commutative.

A path π\pi of a transducer is a sequence of arcs, each arc starting where the previous one ends. Its input string i(π)i(\pi) and output string o(π)o(\pi) are the labels read along it with the ε\varepsilon labels dropped. A successful path starts in the start state and ends in a final state. Its weight is w(π)=w(e1)⊗⋯⊗w(ek)⊗ρ(last state)w(\pi) = w(e_1) \otimes \cdots \otimes w(e_k) \otimes \rho(\text{last state}). The weight of a pair of strings is

T(x,y)=⨁π successful, i(π)=x, o(π)=yw(π),T(x, y) = \bigoplus_{\pi \text{ successful},\ i(\pi) = x,\ o(\pi) = y} w(\pi),

and T(x,y)=0ˉT(x, y) = \bar 0 when there is no such path. The composition is defined by (T1∘T2)(x,z)=⨁yT1(x,y)⊗T2(y,z)(T_1 \circ T_2)(x, z) = \bigoplus_y T_1(x, y) \otimes T_2(y, z). If the machines have cycles, we assume that these sums are defined, as in a kk-closed semiring; for machines without cycles and for ε\varepsilon-free machines and a fixed (x,z)(x, z) all the sums are finite.

Lemma 1 (the search builds the reachable part). Call a triple (q1,q2,f)(q_1, q_2, f) reachable if a sequence of the moves of lines L5 to L8 leads to it from (i1,i2,0)(i_1, i_2, 0). 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 QQ, so each triple is pushed and popped at most once. There are at most 3s1s23 s_1 s_2 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. □\square

Lemma 2 (one interleaving). In the moves of lines L6 to L8, write JJ for a joint move (both machines take an ε\varepsilon arc, line L6), AA for a move of T1T_1 alone (line L7) and BB for a move of T2T_2 alone (line L8). From filter state 0, the sequences of such moves that the filter allows are exactly the words of J∗(A∗∪B∗)J^* (A^* \cup B^*). For any p,r≥0p, r \ge 0 exactly one of these words has pp moves of T1T_1 (counting JJ and AA) and rr moves of T2T_2 (counting JJ and BB).

Proof. Line L6 needs f=0f = 0 and keeps f=0f = 0. Line L7 needs f∈{0,1}f \in \{0, 1\} and sets f=1f = 1. Line L8 needs f∈{0,2}f \in \{0, 2\} and sets f=2f = 2. So from state 1 only AA is allowed, from state 2 only BB, and from state 0 all three. A word that starts in state 0 is therefore a run of JJ, then either a run of AA or a run of BB, and every such word is allowed. A word JjAaJ^j A^a or JjBbJ^j B^b with pp and rr moves of the two machines has j+a=pj + a = p, j+b=rj + b = r, and a=0a = 0 or b=0b = 0. So j=min⁡(p,r)j = \min(p, r), and aa and bb are fixed. □\square

Lemma 3 (paths and pairs of paths). Let T=T1∘T2T = T_1 \circ T_2 be the output of COMPOSE. There is a bijection between the successful paths π\pi of TT and the pairs (π1,π2)(\pi_1, \pi_2) of successful paths of T1T_1 and T2T_2 with o(π1)=i(π2)o(\pi_1) = i(\pi_2). Under it, i(π)=i(π1)i(\pi) = i(\pi_1), o(π)=o(π2)o(\pi) = o(\pi_2) and w(π)=w(π1)⊗w(π2)w(\pi) = w(\pi_1) \otimes w(\pi_2).

Proof. Projection. Each arc of TT was made from one arc of T1T_1, one arc of T2T_2, or one of each. Keeping the T1T_1 arcs of π\pi in order gives a path π1\pi_1 of T1T_1 from i1i_1, and keeping the T2T_2 arcs gives a path π2\pi_2 of T2T_2 from i2i_2. The last state of π\pi is final only if both components are final (line L4), so π1\pi_1 and π2\pi_2 are successful. A matched move (line L5) reads the same symbol b≠εb \ne \varepsilon on the output of T1T_1 and the input of T2T_2, and the other moves read ε\varepsilon on both of these sides, so o(π1)=i(π2)o(\pi_1) = i(\pi_2). The input labels of π\pi are those of π1\pi_1 and the output labels those of π2\pi_2. The weights of the arcs of π\pi are the weights of the arcs of π1\pi_1 and π2\pi_2, each used once, and the final weight is ρ1⊗ρ2\rho_1 \otimes \rho_2. Since ⊗\otimes is commutative and associative, w(π)=w(π1)⊗w(π2)w(\pi) = w(\pi_1) \otimes w(\pi_2).

Construction. Let o(π1)=i(π2)=y1⋯ymo(\pi_1) = i(\pi_2) = y_1 \cdots y_m. Cut π1\pi_1 into A0e1A1⋯emAmA_0 e_1 A_1 \cdots e_m A_m, where eke_k is the arc that writes yky_k and each AkA_k is a run of arcs that write ε\varepsilon. Cut π2\pi_2 in the same way into B0f1B1⋯fmBmB_0 f_1 B_1 \cdots f_m B_m, where fkf_k reads yky_k. Build π\pi segment by segment. The filter state is 0 at the start and after each matched move. For segment kk, Lemma 2 gives exactly one allowed word of moves that takes the ∣Ak∣|A_k| arcs of AkA_k and the ∣Bk∣|B_k| arcs of BkB_k; then the matched move takes ek+1e_{k+1} and fk+1f_{k+1} (line L5 allows it in every filter state). Every triple on the way is reachable, so by Lemma 1 all these arcs are in TT, and the last triple is final by line L4.

The two maps are inverse to each other. Projection of the constructed path gives back (π1,π2)(\pi_1, \pi_2). In the other direction, a path π\pi of TT is determined by its projections: the matched moves of π\pi are fixed by the arcs ek,fke_k, f_k, and by Lemma 2 the moves between two matched moves are fixed by the lengths ∣Ak∣|A_k| and ∣Bk∣|B_k|, since the filter state is 0 after each matched move. □\square

Theorem. For all strings xx and zz, T(x,z)=(T1∘T2)(x,z)T(x, z) = (T_1 \circ T_2)(x, z).

Proof. By Lemma 3, and grouping the pairs by the middle string yy,

T(x,z)=⨁πw(π)=⨁y ⨁i(π1)=x, o(π1)=yi(π2)=y, o(π2)=zw(π1)⊗w(π2)=⨁yT1(x,y)⊗T2(y,z),T(x, z) = \bigoplus_{\pi} w(\pi) = \bigoplus_y \ \bigoplus_{\substack{i(\pi_1) = x,\ o(\pi_1) = y \\ i(\pi_2) = y,\ o(\pi_2) = z}} w(\pi_1) \otimes w(\pi_2) = \bigoplus_y T_1(x, y) \otimes T_2(y, z),

where the last step is distributivity of ⊗\otimes over ⊕\oplus. □\square

Corollary (size without epsilons). If neither machine has an ε\varepsilon on the shared side, lines L6 to L8 never run, every triple has f=0f = 0, and TT has at most s1s2s_1 s_2 states. Every arc of TT comes from line L5, from one pair (e1,e2)(e_1, e_2) of an arc of T1T_1 and an arc of T2T_2. The source of that arc is the triple of the sources of e1e_1 and e2e_2, which is popped once (Lemma 1), so each pair gives at most one arc and TT has at most e1e2e_1 e_2 arcs.

Remark (no filter). Without the filter, every word over {J,A,B}\{J, A, B\} is allowed, so the map of Lemma 3 is still onto but no longer one to one. Then T(x,z)T(x, z) is a sum in which each term w(π1)⊗w(π2)w(\pi_1) \otimes w(\pi_2) appears one or more times. In an idempotent semiring such as the tropical one, a⊕a=aa \oplus a = a, so the result is still right. In the log semiring it is not. With T1T_1 the single arc a:ε/0a{:}\varepsilon/0 and T2T_2 the single arc ε:c/0\varepsilon{:}c/0, there are three paths (A then B, B then A, and J), and the cost of (a,c)(a, c) becomes −log⁡3-\log 3 instead of 00.

Complexity

In the word-RAM model, with the states of TT kept in an array indexed by the triple, or in a hash table in expected time, and the arcs of T2T_2 grouped by input label, a popped triple (q1,q2,f)(q_1, q_2, f) costs O(1+d1(q1)d2(q2))O(1 + d_1(q_1) d_2(q_2)), where d1d_1 and d2d_2 are the out-degrees. Each triple is popped once and there are at most 3s1s23 s_1 s_2 triples, so the time is O(s1s2+e1e2)O(s_1 s_2 + e_1 e_2). The output has O(s1s2)O(s_1 s_2) states and O(e1e2)O(e_1 e_2) arcs, which is also the space.

Without ε\varepsilon labels on the shared side, the proof shows that TT has at most s1s2s_1 s_2 states and at most e1e2e_1 e_2 arcs. The bound is reached: if both machines have one state and kk self loops that all carry the same middle label, the result has k2k^2 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 O(∣T1∣∣T2∣)O(|T_1| |T_2|) bound, where ∣T∣|T| 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 TT 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. (T1∘T2)∘T3(T_1 \circ T_2) \circ T_3 and T1∘(T2∘T3)T_1 \circ (T_2 \circ T_3) 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 ε\varepsilon paths that lead nowhere, and push labels and weights forward along ε\varepsilon 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 ε\varepsilon paths twice. Without a filter, a pair of ε\varepsilon 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 T1T_1 must meet the input side of T2T_2. 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 e1e2e_1 e_2 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 TT 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 T2T_2 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 ε\varepsilon 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.

nlslog.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
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

  1. 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
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example