Algorithmadvanced
Weighted determinization
Also called WFST determinization, Mohri determinization.
Turn a weighted automaton with the twins property into an equivalent one with at most one transition per label from each state, by subsets with residual weights.
- Time
- O(N e + M s log s) worst
- Space
- O(N s + M) extra
- Where
- M = the number of arcs of the result; N = the number of states of the result; e = the number of arcs of the input; s = the number of states of the input
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mehryar Mohri, 1997
Weighted determinization turns a weighted automaton into an equivalent one in which each state has at most one outgoing arc per label. It is the subset construction with a weight attached to each state of a subset. That weight, the residual, is the part of the path weight that the new machine has not yet emitted. The result gives every string the same weight as the input, and a decoder that walks it never has two arcs to follow for one label. Unlike the unweighted subset construction, it does not always stop: Mohri 1997 shows that it stops when the input has the twins property over the tropical semiring, and some weighted automata have no deterministic equivalent at all.
In plain words
A machine reads a string and can follow several paths at once, each with its own cost. You want a machine that follows only one path. Run all the old paths together. A new state is the set of old states you could be in, and for each of them the extra cost it has collected beyond the cheapest one.
On each symbol, the new arc carries the smallest cost among the old paths. Each old state keeps only its extra cost. If the extra costs keep growing forever, you get new sets without end, and the method never stops. A simple condition on the cycles of the machine rules this out.
The problem
A weighted acceptor over a semiring has a set of states , a start state with an initial weight , final weights and arcs (weighted automaton). It gives each string the weight , the -sum over the paths that read of , the arc weights and the final weight, multiplied with . The acceptor is deterministic if no state has two arcs with the same label. The task: given an -free , build a deterministic with for every string .
The weights here are costs , as in Mohri, Pereira and Riley 2002. A probability becomes the cost , and a probability of 0 becomes . The tropical semiring keeps the best path, and the log semiring with adds probabilities. In both, is , and dividing by a finite weight is subtracting . A transducer is handled by reading each pair (input, output) as one label, or with residual output strings as in Mohri 1997.
The algorithm
A state of is a weighted subset . The pair means: the input can be in state , and its best (or total) weight up to here is the weight already emitted by times .
WEIGHTED-DETERMINIZE(A)- 1
λ' ← λ; i' ← {(i, 1̄)}; Q' ← {i'}; S ← [i'] - 2
while S is not empty do - 3
p' ← DEQUEUE(S) - 4
if p' holds a final state then ρ'(p') ← ⊕ of r ⊗ ρ(q) over the pairs (q, r) ∈ p' with q final - 5
for each label a on an arc that leaves a state of p' do - 6
w' ← ⊕ of r ⊗ w over (q, r) ∈ p' and arcs (q, a, w, n) - 7
v(n) ← ⊕ of r ⊗ w over (q, r) ∈ p' and arcs (q, a, w, n), for each target n - 8
n' ← {(n, w'^{-1} ⊗ v(n))} ▷ on costs, the residual is v(n) - w' - 9
add the arc (p', a, w', n') - 10
if n' ∉ Q' then add n' to Q' and enqueue n' on S
Line L6 is the weight that emits on the arc: the minimum in the tropical semiring, the total in the log semiring. Line L8 keeps, for each target, only what remains. In the tropical semiring, at least one residual of every new subset is 0.
Example
The acceptor has the arcs , , , and , the final state 3 with weight 0, and the tropical semiring. State 0 has two arcs labelled , so is not deterministic.
| subset | label | (L6) | target subset (L8) |
|---|---|---|---|
The result has 3 states and 3 arcs, and it is deterministic. The string costs , which is in . The string costs , as in . The residual 1 of state 2 in the middle subset records that the path through state 2 is 1 worse than the best path so far; on it catches up, since .
Now an input that has no deterministic equivalent. Take the arcs , , the loops and , then and , with state 3 final. After the subset is . The residual grows by one on each , so every gives a new state and the loop never stops. A deterministic machine would have to know, after , whether to charge 3 or 4 per , and it cannot know that until it sees or . Mohri 2009, Figure 11(c), shows an acceptor of the same kind, with cycle weights 3 and 4.
Correctness
The proof is in proofs/correctness.md. Let be the weight of the paths from to that read . The invariant, by induction on , is that the subset reached by holds exactly the states with , and that , where is the weight has emitted on . Line L4 then gives .
Termination is a separate question. Two states and are siblings if one string reaches both from and one string labels a cycle at and a cycle at . They are twins if, for all such and , : the cycles cost the same at both. The input has the twins property if all its siblings are twins. Over the tropical semiring:
- Theorem (Mohri 1997; Mohri 2009, Theorem 5). If has the twins property, is determinizable, and the algorithm stops.
- Theorem (Mohri 2009, Theorem 6). If is trim and unambiguous, is determinizable if and only if it has the twins property.
- Acyclic inputs. Every acyclic acceptor over a semiring with no zero sums, such as the tropical and the log semiring, is determinizable, because it reads only finitely many strings.
In the second example, states 1 and 2 are siblings (, ) with cycle costs 3 and 4, so they are not twins.
Proof: Weighted determinization gives an equivalent deterministic acceptorfull
We use the notation of the page. Weights are costs, the semiring is the tropical semiring or the log semiring on costs, with . In both, is , and for a finite the division is . The input is an -free acceptor with finite arc weights, start state , initial weight and final weights . We assume exact arithmetic, and that two weighted subsets are the same state of the result only when they are equal. The code rounds the residuals to a multiple of before it compares subsets; the remark at the end discusses this.
For a string and a state , let be the -sum of the weights of all paths of from to that read , with if there is none. The weight of in is
with for a state that is not final.
Lemma 1 (determinism). The result is deterministic.
Proof. Line L5 handles each label once per state of , and line L9 adds one arc for it. The start state is unique (line L1).
So every string has at most one path in from the start. If it exists, write for its last state and for the product of and the weights of its arcs.
Lemma 2 (the invariant). For every string , the path of in exists if and only if some path of reads . If it exists, the weighted subset holds exactly the states with , and for each pair in it,
Proof. Induction on the length of . For the empty string, the path of is empty, and for , and starts in with (line L1), so the claim holds.
Now let satisfy the claim and let be a label. Some path of reads if and only if some state with has an arc labelled , that is, if and only if line L5 handles at . Then line L9 adds an arc with label , so the path of in exists, and otherwise it does not. Assume it exists. Lines L6 and L7 compute
where the second sum runs only over the arcs into . A path of that reads and ends in is a path that reads and ends in some , followed by an arc . By distributivity and the induction hypothesis,
The new subset holds the states with an arc into them, which are exactly those with , since all weights are finite. Line L8 sets , so .
Theorem (equivalence). If the algorithm stops, for every string .
Proof. If no path of reads , then , and by Lemma 2 no path of reads , so . Otherwise, by line L4 and Lemma 2,
Termination. Each state of is a weighted subset for some string that can read, and line L10 creates a state only once.
- If is acyclic, it reads only finitely many strings, so has finitely many states and the loop stops. The number of states can still be exponential in the number of states of , as for , where has states.
- If has the twins property over the tropical semiring, Mohri 1997 proves that only finitely many weighted subsets occur, so the loop stops (Mohri 2009, Theorem 5, states the same result). For trim unambiguous acceptors over the tropical semiring, the twins property is also necessary (Mohri 2009, Theorem 6).
- Without the twins property the loop can run forever. In the acceptor with the arcs , , , , , and final state 3, Lemma 2 and the tropical semiring give for every : the best path to 1 costs and the best path to 2 costs , and . These subsets are all different, so would need infinitely many states.
Remark (rounding). The code identifies two subsets when their residuals round to the same multiple of , and it keeps the residuals of the first one. Each such merge can change the weight of a later path by less than per merged state on the path. The opposite error, two equal subsets whose residuals round apart, only adds a state and does not change any weight. In the tropical tests all weights are multiples of , so the residuals are exact and the proof above applies as stated.
Complexity
The size of the result can be exponential. The unweighted automaton for has states, and every deterministic equivalent has at least states (determinization blow-up lower bound); weights do not help. So the cost is stated in the size of the output.
In the word-RAM model, with states and arcs in the result and states and arcs in the input, a state of holds at most pairs, and lines L5 to L7 look at most arcs of the input for it. Building and hashing the target subsets costs per arc of , for the sort that gives each subset a canonical order. The total is time, with hashing in expected time. The space is for the subsets and the arcs.
The twins property can be tested in time over the tropical semiring (Allauzen and Mohri 2003, as cited in Mohri 2009, Section 6.2).
Properties
- Exact when it stops. for every string, in the tropical and in the log semiring.
- Not always possible. Some weighted automata have no deterministic equivalent, unlike unweighted ones.
- Output-sensitive. The cost depends on the size of the result, which can be exponential in the size of the input.
- Weights move forward. emits on each arc the best (or total) weight so far, so weights tend to come earlier than in . Weight pushing moves them as far forward as possible.
- A canonical form with minimization. Determinization, then weight pushing, then unweighted minimization with (label, weight) pairs as labels, gives the minimal deterministic machine (Mohri 2009, Theorem 8; see DFA minimization).
Variants and improvements
- Transducers. Mohri 1997 also determinizes sequential transducers: a subset then holds residual output strings as well as residual weights. A transducer with ambiguous outputs, such as a lexicon with homophones, needs extra symbols first (see HCLG decoding graph).
- The log semiring. The same loop works in any weakly divisible semiring with a suitable division (Mohri 2009). The code accepts the log semiring on costs, and the tests use it on acyclic inputs.
- On-the-fly determinization. Build a state of only when a search reaches it, as for lazy composition.
- Disambiguation. Some machines that cannot be determinized can still be made unambiguous, so that each string has at most one path.
When to use it
Use it on the search graph of a speech recognizer, after composition, so that each state has at most one arc per label. This removes redundant paths, makes the graph smaller in practice, and makes the search faster, because the decoder no longer evaluates the same HMM state on several parallel arcs. Use it also to compute the best weight of each string of a lattice, by determinizing the lattice in the tropical semiring. Do not use it on an input that may lack the twins property without a size limit.
Pitfalls
- No termination. An input without the twins property makes the loop run until memory runs out. Use a state limit, as the code does, or make the input determinizable first.
- Homophones in a lexicon. Two words with the same pronunciation make the lexicon transducer not determinizable as a transducer. Add disambiguation symbols.
- Floating-point residuals. Two subsets that should be equal can have residuals that differ in the last bits. Compare residuals after rounding to a small quantum , as OpenFst does with its delta parameter. Too large a merges subsets that should differ and changes the weights a little.
- Epsilons. The algorithm needs an -free input. Remove the arcs first, or treat as an ordinary label.
- Blow-up. Even when it stops, the result can be exponential. In speech graphs it is usually smaller than the input, but that is a measurement on those graphs, not a guarantee.
Implementations
The Python code determinizes -free weighted acceptors in the tropical and the log semiring on costs, with a queue of weighted subsets and a state limit. The tests compare the weight of every string of length at most 4 before and after, on random acyclic acceptors and on random cyclic acceptors with the twins property, check that the result is deterministic, check that the example without the twins property hits the state limit with the residuals , and check the states for .
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_determinization.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-determinization/. The authors are listed in prov/40YQAC.jsonl.
"""Weighted determinization of an epsilon-free weighted acceptor (Mohri 1997).
Weights are costs -log p. The semiring is TROPICAL (min, +) or LOG_COST
(-log(exp(-a) + exp(-b)), +) from nlslog. In both, the division needed for
the residual weights is a subtraction of costs.
An acceptor has states 0..n-1, a start state with an initial weight, a final
cost per final state, and arcs (label, weight, next). A state of the result is
a weighted subset: a set of pairs (q, r), where r is the residual weight of
state q, the part of the weight that the result has not yet emitted.
The algorithm terminates when the input has the twins property over the
tropical semiring (Mohri 1997), and on every acyclic input. On other inputs
it can run forever, so max_states stops it with an error.
Residuals are floats. Two subsets are the same state when their residuals
agree after rounding to a multiple of delta; the first residuals seen are kept.
"""
from typing import Dict, FrozenSet, List, Tuple
from nlslog import TROPICAL, Semiring
class Acceptor:
"""A weighted acceptor with integer states and costs."""
def __init__(self) -> None:
self.start = 0
self.initial = 0.0
self.arcs: List[List[Tuple[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, label: str, weight: float, nxt: int) -> None:
self.arcs[q].append((label, 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 is_deterministic(self) -> bool:
return all(len({a[0] for a in arcs}) == len(arcs) for arcs in self.arcs)
class NotDeterminizable(Exception):
"""Raised when the result grows past max_states. The attribute subsets holds the subsets built so far."""
def determinize(a: Acceptor, sr: Semiring = TROPICAL, max_states: int = 10000, delta: float = 1e-9):
"""Return (d, subsets): a deterministic acceptor equivalent to a, and the weighted subset of each state.
Raise NotDeterminizable if d would have more than max_states states.
"""
d = Acceptor()
index: Dict[FrozenSet[Tuple[int, int]], int] = {}
subsets: List[List[Tuple[int, float]]] = []
queue: List[int] = []
def key(subset):
return frozenset((q, round(r / delta)) for q, r in subset)
def state_of(subset):
k = key(subset)
if k not in index: # @line L10
if len(subsets) >= max_states:
err = NotDeterminizable("more than %d states" % max_states)
err.subsets = subsets
raise err
index[k] = d.add_state()
subsets.append(subset)
queue.append(index[k])
return index[k]
d.initial = a.initial # @line L1
d.start = state_of([(a.start, sr.one)])
head = 0
while head < len(queue): # @line L2
p = queue[head] # @line L3
head += 1
subset = subsets[p]
rho = sr.zero
for q, r in subset: # @line L4
if q in a.final:
rho = sr.plus(rho, sr.times(r, a.final[q]))
if rho != sr.zero:
d.set_final(p, rho)
# Group the arcs that leave the subset by label, in first-seen order.
by_label: Dict[str, List[Tuple[float, int]]] = {}
for q, r in subset:
for label, w, n in a.arcs[q]:
by_label.setdefault(label, []).append((sr.times(r, w), n))
for label, moves in by_label.items(): # @line L5
w_new = sr.zero
for v, _ in moves: # @line L6
w_new = sr.plus(w_new, v)
residual: Dict[int, float] = {}
for v, n in moves: # @line L7
residual[n] = sr.plus(residual.get(n, sr.zero), v)
nxt = sorted((n, v - w_new) for n, v in residual.items()) # @line L8
d.add_arc(p, label, w_new, state_of(nxt)) # @line L9
return d, subsets
def string_weight(a: Acceptor, x, sr: Semiring = TROPICAL) -> float:
"""Return the weight of the string x in a: the semiring sum over the paths that read x."""
cur = {a.start: a.initial}
for c in x:
nxt: Dict[int, float] = {}
for q, w in cur.items():
for label, wa, n in a.arcs[q]:
if label == c:
nxt[n] = sr.plus(nxt.get(n, sr.zero), sr.times(w, wa))
cur = nxt
total = sr.zero
for q, w in cur.items():
if q in a.final:
total = sr.plus(total, sr.times(w, a.final[q]))
return total
test_weighted_determinization.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-determinization/. The authors are listed in prov/40YQAC.jsonl.
import itertools
import math
import random
import pytest
from nlslog import LOG_COST, TROPICAL, Semiring
from weighted_determinization import Acceptor, NotDeterminizable, determinize, string_weight
LABELS = ["a", "b"]
def all_strings(max_len: int):
for k in range(max_len + 1):
for x in itertools.product(LABELS, repeat=k):
yield x
def close(u: float, v: float, tol: float = 1e-9) -> bool:
if math.isinf(u) or math.isinf(v):
return u == v
return abs(u - v) <= tol
def equivalent(a: Acceptor, d: Acceptor, sr: Semiring, max_len: int = 4) -> bool:
return all(close(string_weight(a, x, sr), string_weight(d, x, sr)) for x in all_strings(max_len))
def random_acyclic(rng: random.Random, n: int) -> Acceptor:
a = Acceptor()
for _ in range(n):
a.add_state()
for i in range(n):
for j in range(i + 1, n):
for c in LABELS:
if rng.random() < 0.45:
a.add_arc(i, c, rng.randint(0, 8) * 0.25, j)
a.set_final(n - 1, rng.randint(0, 2) * 0.5)
if rng.random() < 0.5:
a.set_final(rng.randrange(1, n), rng.randint(0, 2) * 0.5)
a.initial = rng.randint(0, 2) * 0.5
return a
def random_twins(rng: random.Random, n: int) -> Acceptor:
"""A cyclic acceptor with the twins property: every arc out of a state other than 0 costs c[label].
No arc enters state 0, so any cycle reading v costs the sum of c over v, at
every state; two cycles that read the same string have the same weight.
"""
cost = {c: rng.randint(0, 6) * 0.5 for c in LABELS}
a = Acceptor()
for _ in range(n):
a.add_state()
for i in range(n):
for c in LABELS:
for _ in range(2):
if rng.random() < 0.5:
w = rng.randint(0, 8) * 0.25 if i == 0 else cost[c]
a.add_arc(i, c, w, rng.randrange(1, n))
for q in range(1, n):
if rng.random() < 0.5:
a.set_final(q, rng.randint(0, 4) * 0.5)
return a
def two_cycles(u: float = 3.0, v: float = 4.0) -> Acceptor:
"""States 1 and 2 are both reached by a; their a-loops cost u and v."""
a = Acceptor()
for _ in range(4):
a.add_state()
a.add_arc(0, "a", 0.0, 1)
a.add_arc(0, "a", 0.0, 2)
a.add_arc(1, "a", u, 1)
a.add_arc(2, "a", v, 2)
a.add_arc(1, "b", 0.0, 3)
a.add_arc(2, "c", 0.0, 3)
a.set_final(3)
return a
def test_page_example():
a = Acceptor()
for _ in range(4):
a.add_state()
a.add_arc(0, "a", 1.0, 1)
a.add_arc(0, "a", 2.0, 2)
a.add_arc(1, "b", 3.0, 3)
a.add_arc(2, "b", 1.0, 3)
a.add_arc(1, "c", 5.0, 3)
a.set_final(3)
d, subsets = determinize(a)
assert subsets == [[(0, 0.0)], [(1, 0.0), (2, 1.0)], [(3, 0.0)]]
assert d.arcs[0] == [("a", 1.0, 1)]
assert sorted(d.arcs[1]) == [("b", 2.0, 2), ("c", 5.0, 2)]
assert d.final == {2: 0.0}
assert string_weight(d, "ab") == 3.0 and string_weight(d, "ac") == 6.0
assert d.is_deterministic() and not a.is_deterministic()
def test_random_acyclic_tropical_and_log():
rng = random.Random(1)
for case in range(80):
sr = LOG_COST if case % 2 else TROPICAL
a = random_acyclic(rng, rng.randint(2, 5))
d, _ = determinize(a, sr)
assert d.is_deterministic()
assert equivalent(a, d, sr)
def test_cyclic_with_twins_property():
rng = random.Random(2)
for _ in range(60):
a = random_twins(rng, rng.randint(2, 5))
d, _ = determinize(a, TROPICAL, max_states=500)
assert d.is_deterministic()
assert equivalent(a, d, TROPICAL)
def test_no_twins_does_not_stop():
with pytest.raises(NotDeterminizable):
determinize(two_cycles(3.0, 4.0), TROPICAL, max_states=50)
# With equal loop costs the two states are twins and the result is small.
d, subsets = determinize(two_cycles(3.0, 3.0), TROPICAL)
assert subsets == [[(0, 0.0)], [(1, 0.0), (2, 0.0)], [(3, 0.0)]]
assert equivalent(two_cycles(3.0, 3.0), d, TROPICAL)
def test_residuals_grow_without_twins():
with pytest.raises(NotDeterminizable) as info:
determinize(two_cycles(3.0, 4.0), TROPICAL, max_states=12)
# After a^k the subset is {(1, 0), (2, k - 1)}: the residual of state 2 grows by 1 per a.
loops = [s for s in info.value.subsets if s[0][0] == 1]
assert len(loops) >= 5
assert loops == [[(1, 0.0), (2, float(k))] for k in range(len(loops))]
def test_exponential_blowup():
# (a|b)* a (a|b)^(n-1): the n-th symbol from the end is a. Weights 0.
for n in range(1, 6):
a = Acceptor()
for _ in range(n + 1):
a.add_state()
for c in LABELS:
a.add_arc(0, c, 0.0, 0)
a.add_arc(0, "a", 0.0, 1)
for i in range(1, n):
for c in LABELS:
a.add_arc(i, c, 0.0, i + 1)
a.set_final(n)
d, _ = determinize(a)
assert d.num_states() == 2 ** n
assert equivalent(a, d, TROPICAL)
def test_log_semiring_adds_probabilities():
a = Acceptor()
for _ in range(3):
a.add_state()
a.add_arc(0, "a", -math.log(0.5), 1)
a.add_arc(0, "a", -math.log(0.25), 2)
a.set_final(1)
a.set_final(2)
d, _ = determinize(a, LOG_COST)
assert d.num_states() == 2
assert close(string_weight(d, "a", LOG_COST), -math.log(0.75))
d, _ = determinize(a, TROPICAL)
assert close(string_weight(d, "a", TROPICAL), -math.log(0.5))
History
The subset construction for unweighted automata is from Rabin and Scott 1959. Mohri 1997 extended it to weighted automata and to transducers over the tropical semiring, introduced the twins property, and proved that it makes the algorithm stop. Mohri, Pereira and Riley used it, with composition and weight pushing, to build the compact networks of large vocabulary speech recognizers, and Mohri 2009 gives the algorithm for weakly divisible semirings.
References
- Mehryar Mohri, Finite-state transducers in language and speech processing, Computational Linguistics 23(2), 1997, pages 269 to 311, the sections on the determinization of weighted automata and transducers over the tropical semiring and the twins property
- Mehryar Mohri, Weighted automata algorithms, in Manfred Droste, Werner Kuich and Heiko Vogler (editors), Handbook of Weighted Automata, Springer, 2009, Section 6.2 (determinization: the algorithm for weakly divisible semirings, siblings and twins, Theorems 5 and 6, and the example that cannot be determinized)
- 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 determinization and its effect on the size and speed of the recognition network
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 40YQAC Edit this page History Report an error Markdown