Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 (K,⊕,⊗,0ˉ,1ˉ)(K, \oplus, \otimes, \bar 0, \bar 1) has a set of states QQ, a start state ii with an initial weight λ\lambda, final weights ρ(q)\rho(q) and arcs (q,a,w,n)(q, a, w, n) (weighted automaton). It gives each string uu the weight A(u)A(u), the ⊕\oplus-sum over the paths that read uu of λ\lambda, the arc weights and the final weight, multiplied with ⊗\otimes. The acceptor is deterministic if no state has two arcs with the same label. The task: given an ε\varepsilon-free AA, build a deterministic DD with D(u)=A(u)D(u) = A(u) for every string uu.

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. The tropical semiring (R∪{+∞},min⁡,+,+∞,0)(\mathbb{R} \cup \{+\infty\}, \min, +, +\infty, 0) keeps the best path, and the log semiring with a⊕b=−log⁡(e−a+e−b)a \oplus b = -\log(e^{-a} + e^{-b}) adds probabilities. In both, ⊗\otimes is ++, and dividing by a finite weight ww is subtracting ww. 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 DD is a weighted subset {(q1,r1),…,(qk,rk)}\{(q_1, r_1), \ldots, (q_k, r_k)\}. The pair (q,r)(q, r) means: the input can be in state qq, and its best (or total) weight up to here is the weight already emitted by DD times rr.

  1. WEIGHTED-DETERMINIZE(A)
  2. 1λ' ← λ; i' ← {(i, 1̄)}; Q' ← {i'}; S ← [i']
  3. 2while S is not empty do
  4. 3p' ← DEQUEUE(S)
  5. 4if p' holds a final state then ρ'(p') ← ⊕ of r ⊗ ρ(q) over the pairs (q, r) ∈ p' with q final
  6. 5for each label a on an arc that leaves a state of p' do
  7. 6w' ← ⊕ of r ⊗ w over (q, r) ∈ p' and arcs (q, a, w, n)
  8. 7v(n) ← ⊕ of r ⊗ w over (q, r) ∈ p' and arcs (q, a, w, n), for each target n
  9. 8n' ← {(n, w'^{-1} ⊗ v(n))} ▷ on costs, the residual is v(n) - w'
  10. 9add the arc (p', a, w', n')
  11. 10if n' ∉ Q' then add n' to Q' and enqueue n' on S

Line L6 is the weight that DD 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 AA has the arcs 0→a/110 \xrightarrow{a/1} 1, 0→a/220 \xrightarrow{a/2} 2, 1→b/331 \xrightarrow{b/3} 3, 2→b/132 \xrightarrow{b/1} 3 and 1→c/531 \xrightarrow{c/5} 3, the final state 3 with weight 0, and the tropical semiring. State 0 has two arcs labelled aa, so AA is not deterministic.

subset label w′w' (L6) target subset (L8)
{(0,0)}\{(0, 0)\} aa min⁡(0+1,0+2)=1\min(0 + 1, 0 + 2) = 1 {(1,0),(2,1)}\{(1, 0), (2, 1)\}
{(1,0),(2,1)}\{(1, 0), (2, 1)\} bb min⁡(0+3,1+1)=2\min(0 + 3, 1 + 1) = 2 {(3,0)}\{(3, 0)\}
{(1,0),(2,1)}\{(1, 0), (2, 1)\} cc 0+5=50 + 5 = 5 {(3,0)}\{(3, 0)\}

The result has 3 states and 3 arcs, and it is deterministic. The string abab costs 1+2=31 + 2 = 3, which is min⁡(1+3,2+1)\min(1 + 3, 2 + 1) in AA. The string acac costs 1+5=61 + 5 = 6, as in AA. 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 bb it catches up, since 1+1<0+31 + 1 < 0 + 3.

Now an input that has no deterministic equivalent. Take the arcs 0→a/010 \xrightarrow{a/0} 1, 0→a/020 \xrightarrow{a/0} 2, the loops 1→a/311 \xrightarrow{a/3} 1 and 2→a/422 \xrightarrow{a/4} 2, then 1→b/031 \xrightarrow{b/0} 3 and 2→c/032 \xrightarrow{c/0} 3, with state 3 final. After aka^k the subset is {(1,0),(2,k−1)}\{(1, 0), (2, k - 1)\}. The residual grows by one on each aa, so every kk gives a new state and the loop never stops. A deterministic machine would have to know, after aka^k, whether to charge 3 or 4 per aa, and it cannot know that until it sees bb or cc. 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 δ(u,q)\delta(u, q) be the weight of the paths from ii to qq that read uu. The invariant, by induction on ∣u∣|u|, is that the subset reached by uu holds exactly the states qq with δ(u,q)≠0ˉ\delta(u, q) \ne \bar 0, and that λ⊗δ(u,q)=W(u)⊗rq\lambda \otimes \delta(u, q) = W(u) \otimes r_q, where W(u)W(u) is the weight DD has emitted on uu. Line L4 then gives D(u)=A(u)D(u) = A(u).

Termination is a separate question. Two states qq and q′q' are siblings if one string xx reaches both from ii and one string yy labels a cycle at qq and a cycle at q′q'. They are twins if, for all such xx and yy, δ(xy,q)−δ(x,q)=δ(xy,q′)−δ(x,q′)\delta(xy, q) - \delta(x, q) = \delta(xy, q') - \delta(x, q'): 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 AA has the twins property, AA is determinizable, and the algorithm stops.
  • Theorem (Mohri 2009, Theorem 6). If AA is trim and unambiguous, AA 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 (x=ax = a, y=ay = a) 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 (R∪{+∞},min⁡,+,+∞,0)(\mathbb{R} \cup \{+\infty\}, \min, +, +\infty, 0) or the log semiring on costs, with a⊕b=−log⁡(e−a+e−b)a \oplus b = -\log(e^{-a} + e^{-b}). In both, ⊗\otimes is ++, and for a finite ww the division w−1⊗vw^{-1} \otimes v is v−wv - w. The input AA is an ε\varepsilon-free acceptor with finite arc weights, start state ii, initial weight λ\lambda and final weights ρ\rho. 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 δ\delta before it compares subsets; the remark at the end discusses this.

For a string uu and a state qq, let δ(u,q)\delta(u, q) be the ⊕\oplus-sum of the weights of all paths of AA from ii to qq that read uu, with δ(u,q)=0ˉ=+∞\delta(u, q) = \bar 0 = +\infty if there is none. The weight of uu in AA is

A(u)=⨁qλ⊗δ(u,q)⊗ρ(q),A(u) = \bigoplus_q \lambda \otimes \delta(u, q) \otimes \rho(q),

with ρ(q)=0ˉ\rho(q) = \bar 0 for a state that is not final.

Lemma 1 (determinism). The result DD is deterministic.

Proof. Line L5 handles each label once per state of DD, and line L9 adds one arc for it. The start state is unique (line L1). □\square

So every string uu has at most one path in DD from the start. If it exists, write p′(u)p'(u) for its last state and W(u)=λ′⊗w1′⊗⋯⊗wk′W(u) = \lambda' \otimes w'_1 \otimes \cdots \otimes w'_k for the product of λ′=λ\lambda' = \lambda and the weights of its arcs.

Lemma 2 (the invariant). For every string uu, the path of uu in DD exists if and only if some path of AA reads uu. If it exists, the weighted subset p′(u)p'(u) holds exactly the states qq with δ(u,q)≠0ˉ\delta(u, q) \ne \bar 0, and for each pair (q,rq)(q, r_q) in it,

λ⊗δ(u,q)=W(u)⊗rq.\lambda \otimes \delta(u, q) = W(u) \otimes r_q .

Proof. Induction on the length of uu. For the empty string, the path of AA is empty, δ(ϵ,i)=1ˉ\delta(\epsilon, i) = \bar 1 and δ(ϵ,q)=0ˉ\delta(\epsilon, q) = \bar 0 for q≠iq \ne i, and DD starts in {(i,1ˉ)}\{(i, \bar 1)\} with W=λW = \lambda (line L1), so the claim holds.

Now let uu satisfy the claim and let aa be a label. Some path of AA reads uaua if and only if some state qq with δ(u,q)≠0ˉ\delta(u, q) \ne \bar 0 has an arc labelled aa, that is, if and only if line L5 handles aa at p′(u)p'(u). Then line L9 adds an arc with label aa, so the path of uaua in DD exists, and otherwise it does not. Assume it exists. Lines L6 and L7 compute

w′=⨁(q,rq)∈p′(u) ⨁(q,a,w,n)rq⊗w,v(n)=⨁(q,rq)∈p′(u) ⨁(q,a,w,n)rq⊗w,w' = \bigoplus_{(q, r_q) \in p'(u)} \ \bigoplus_{(q, a, w, n)} r_q \otimes w, \qquad v(n) = \bigoplus_{(q, r_q) \in p'(u)} \ \bigoplus_{(q, a, w, n)} r_q \otimes w,

where the second sum runs only over the arcs into nn. A path of AA that reads uaua and ends in nn is a path that reads uu and ends in some qq, followed by an arc (q,a,w,n)(q, a, w, n). By distributivity and the induction hypothesis,

λ⊗δ(ua,n)=⨁q⨁(q,a,w,n)λ⊗δ(u,q)⊗w=⨁q⨁(q,a,w,n)W(u)⊗rq⊗w=W(u)⊗v(n).\lambda \otimes \delta(ua, n) = \bigoplus_q \bigoplus_{(q, a, w, n)} \lambda \otimes \delta(u, q) \otimes w = \bigoplus_q \bigoplus_{(q, a, w, n)} W(u) \otimes r_q \otimes w = W(u) \otimes v(n).

The new subset holds the states nn with an arc into them, which are exactly those with δ(ua,n)≠0ˉ\delta(ua, n) \ne \bar 0, since all weights are finite. Line L8 sets rn=v(n)−w′r_n = v(n) - w', so W(ua)⊗rn=W(u)+w′+v(n)−w′=W(u)⊗v(n)=λ⊗δ(ua,n)W(ua) \otimes r_n = W(u) + w' + v(n) - w' = W(u) \otimes v(n) = \lambda \otimes \delta(ua, n). □\square

Theorem (equivalence). If the algorithm stops, D(u)=A(u)D(u) = A(u) for every string uu.

Proof. If no path of AA reads uu, then A(u)=0ˉA(u) = \bar 0, and by Lemma 2 no path of DD reads uu, so D(u)=0ˉD(u) = \bar 0. Otherwise, by line L4 and Lemma 2,

D(u)=W(u)⊗ρ′(p′(u))=⨁(q,rq)W(u)⊗rq⊗ρ(q)=⨁qλ⊗δ(u,q)⊗ρ(q)=A(u).□D(u) = W(u) \otimes \rho'(p'(u)) = \bigoplus_{(q, r_q)} W(u) \otimes r_q \otimes \rho(q) = \bigoplus_q \lambda \otimes \delta(u, q) \otimes \rho(q) = A(u). \qquad \square

Termination. Each state of DD is a weighted subset p′(u)p'(u) for some string uu that AA can read, and line L10 creates a state only once.

  • If AA is acyclic, it reads only finitely many strings, so DD has finitely many states and the loop stops. The number of states can still be exponential in the number of states of AA, as for (a∣b)∗a(a∣b)n−1(a \mid b)^* a (a \mid b)^{n-1}, where DD has 2n2^n states.
  • If AA 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 0→a/010 \xrightarrow{a/0} 1, 0→a/020 \xrightarrow{a/0} 2, 1→a/311 \xrightarrow{a/3} 1, 2→a/422 \xrightarrow{a/4} 2, 1→b/031 \xrightarrow{b/0} 3, 2→c/032 \xrightarrow{c/0} 3 and final state 3, Lemma 2 and the tropical semiring give p′(ak)={(1,0),(2,k−1)}p'(a^k) = \{(1, 0), (2, k - 1)\} for every k≥1k \ge 1: the best path to 1 costs 3(k−1)3(k-1) and the best path to 2 costs 4(k−1)4(k-1), and W(ak)=3(k−1)W(a^k) = 3(k-1). These subsets are all different, so DD would need infinitely many states.

Remark (rounding). The code identifies two subsets when their residuals round to the same multiple of δ\delta, and it keeps the residuals of the first one. Each such merge can change the weight of a later path by less than δ\delta 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 0.250.25, 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 (a∣b)∗a(a∣b)n−1(a \mid b)^* a (a \mid b)^{n-1} has n+1n + 1 states, and every deterministic equivalent has at least 2n2^n 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 NN states and MM arcs in the result and ss states and ee arcs in the input, a state of DD holds at most ss pairs, and lines L5 to L7 look at most ee arcs of the input for it. Building and hashing the target subsets costs O(slog⁡s)O(s \log s) per arc of DD, for the sort that gives each subset a canonical order. The total is O(Ne+Mslog⁡s)O(N e + M s \log s) time, with hashing in expected time. The space is O(Ns+M)O(N s + M) for the subsets and the arcs.

The twins property can be tested in O(s2+e2)O(s^2 + e^2) time over the tropical semiring (Allauzen and Mohri 2003, as cited in Mohri 2009, Section 6.2).

Properties

  • Exact when it stops. D(u)=A(u)D(u) = A(u) 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. DD emits on each arc the best (or total) weight so far, so weights tend to come earlier than in AA. 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 DD 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 δ\delta, as OpenFst does with its delta parameter. Too large a δ\delta merges subsets that should differ and changes the weights a little.
  • Epsilons. The algorithm needs an ε\varepsilon-free input. Remove the ε\varepsilon arcs first, or treat ε\varepsilon 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 ε\varepsilon-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 0,1,2,…0, 1, 2, \ldots, and check the 2n2^n states for (a∣b)∗a(a∣b)n−1(a \mid b)^* a (a \mid b)^{n-1}.

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_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

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

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