Algorithm Search⌘K

Algorithmadvanced

Weight pushing

Also called WFST weight pushing.

Move the weights of a weighted automaton toward the initial state using shortest distances to the final states, which aids pruning.

Time
O(n m) worst
Space
O(n + m) extra
Where
m = the number of arcs; n = the number of states
Properties
deterministicexactofflineiterative
Origin
Mehryar Mohri, 1997

Weight pushing moves the weights of a weighted automaton or transducer as far as possible toward the start state, and keeps the weight of every string the same. It first computes, for each state qq, the shortest distance d(q)d(q) from qq to the final states. Then it adds d(n)−d(p)d(n) - d(p) to each arc from pp to nn, adds dd of the start state to the initial weight, and subtracts d(q)d(q) from each final weight. In the tropical semiring, the cheapest way out of each state then costs exactly 0. In the log semiring, the result is stochastic: the weights that leave a state are probabilities that add up to 1. A speech decoder prunes better on a pushed graph, because the cost of a partial path then shows the cost of its best ending.

In plain words

Each path through a weighted graph has a total cost. Where the cost sits along the path does not change the total, but it changes what a search sees early. If a path starts cheap and ends expensive, a search that drops costly partial paths keeps the wrong ones.

So for each state, find the cheapest way from it to the end. Charge that amount as early as you can. Each arc then costs only how much worse it is than the best choice at its state. The totals stay the same, and the best choice at each state costs 0.

The problem

A weighted transducer over a semiring (K,⊕,⊗,0ˉ,1ˉ)(K, \oplus, \otimes, \bar 0, \bar 1) has states QQ, a start state ii with an initial weight λ\lambda, final weights ρ(q)\rho(q), and arcs (p,a,b,w,n)(p, a, b, w, n) from pp to nn with input label aa, output label bb and weight ww (weighted automaton). The labels play no part here. The distance to the final states is

D(p)=⨁π from p to a final qw(π)⊗ρ(q).D(p) = \bigoplus_{\pi \text{ from } p \text{ to a final } q} w(\pi) \otimes \rho(q).

The task: build an equivalent machine in which, at every state, ρ(p)⊕⨁ew(e)=1ˉ\rho(p) \oplus \bigoplus_e w(e) = \bar 1 over the arcs ee that leave pp.

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.

The algorithm

The first part is Mohri's generic single-source shortest-distance algorithm, run backward from the final states. Each state qq keeps the distance d(q)d(q) found so far and the residual r(q)r(q), the part of d(q)d(q) that it has not yet passed to its predecessors. The second part is the reweighting.

  1. WEIGHT-PUSH(T)
  2. 1for each final q: d(q) ← r(q) ← ρ(q); enqueue q ▷ all other d, r are 0̄
  3. 2while the queue S is not empty do
  4. 3q ← DEQUEUE(S)
  5. 4R ← r(q); r(q) ← 0̄
  6. 5for each arc (p, a, b, w, q) into q do
  7. 6if d(p) ⊕ (w ⊗ R) differs from d(p) then d(p) ← d(p) ⊕ (w ⊗ R); r(p) ← r(p) ⊕ (w ⊗ R)
  8. 7if p ∉ S then ENQUEUE(S, p)
  9. 8if d(i) = 0̄ then fail: no successful path
  10. 9drop the states q with d(q) = 0̄ and their arcs
  11. 10λ ← λ ⊗ d(i)
  12. 11for each arc e from p to n: w(e) ← d(p)⁻¹ ⊗ w(e) ⊗ d(n) ▷ on costs: w + d(n) - d(p)
  13. 12for each final q: ρ(q) ← d(q)⁻¹ ⊗ ρ(q) ▷ on costs: ρ(q) - d(q)

In the tropical semiring "differs" at line L6 means "is smaller". In the log semiring it means "changes by more than δ\delta". With a FIFO queue in the tropical semiring, lines L1 to L7 are the queue form of Bellman-Ford on the reversed graph. In the log semiring they are a fixed-point iteration for the linear system x=Px+fx = P x + f of the probabilities, which stops at tolerance δ\delta.

Example

The machine has the arcs 0→a/010 \xrightarrow{a/0} 1, 0→b/120 \xrightarrow{b/1} 2, 1→c/331 \xrightarrow{c/3} 3, 2→c/132 \xrightarrow{c/1} 3 and 2→d/432 \xrightarrow{d/4} 3, with state 3 final with weight 0 and λ=0\lambda = 0. Its strings are acac with cost 3, bcbc with cost 2 and bdbd with cost 5.

In the tropical semiring the distances are d=(2,3,1,0)d = (2, 3, 1, 0). The pushed machine:

arc old weight w+d(n)−d(p)w + d(n) - d(p)
0→a10 \xrightarrow{a} 1 0 0+3−2=10 + 3 - 2 = 1
0→b20 \xrightarrow{b} 2 1 1+1−2=01 + 1 - 2 = 0
1→c31 \xrightarrow{c} 3 3 3+0−3=03 + 0 - 3 = 0
2→c32 \xrightarrow{c} 3 1 1+0−1=01 + 0 - 1 = 0
2→d32 \xrightarrow{d} 3 4 4+0−1=34 + 0 - 1 = 3

The initial weight becomes λ=2\lambda = 2. The string acac costs 2+1+0=32 + 1 + 0 = 3, bcbc costs 2+0+0=22 + 0 + 0 = 2 and bdbd costs 2+0+3=52 + 0 + 3 = 5, as before. At each of the states 0, 1 and 2, the cheapest arc out costs 0.

Now consider a beam search that reads one symbol and keeps the cheaper partial path. Before pushing, aa costs 0 and bb costs 1, so it keeps aa, whose best ending gives 3. After pushing, aa costs 1 and bb costs 0, so it keeps bb, which leads to the best string bcbc with cost 2.

In the log semiring, d(2)=−log⁡(e−1+e−4)≈0.9514d(2) = -\log(e^{-1} + e^{-4}) \approx 0.9514, d(1)=3d(1) = 3 and d(0)=−log⁡(e−3+e−2+e−5)≈1.651d(0) = -\log(e^{-3} + e^{-2} + e^{-5}) \approx 1.651. The pushed arcs from state 0 have the probabilities 0.25950.2595 for aa and 0.74050.7405 for bb, and those from state 2 have 0.95260.9526 for cc and 0.04740.0474 for dd. Each set adds up to 1, and e−1.651≈0.1919e^{-1.651} \approx 0.1919 is the total probability of the machine.

Correctness

The proof is in proofs/correctness.md. It has two parts.

  • Equivalence for any potential. Along a successful path i=q0,…,qki = q_0, \ldots, q_k, the added terms d(qj)−d(qj−1)d(q_j) - d(q_{j-1}) telescope, and +d(i)+d(i) in λ\lambda and −d(qk)-d(q_k) in ρ\rho cancel the rest. So every path keeps its weight for any finite dd, even an approximate one.
  • The normal form. The distances satisfy D(p)=ρ(p)⊕⨁ew(e)⊗D(n)D(p) = \rho(p) \oplus \bigoplus_e w(e) \otimes D(n). Subtracting D(p)D(p) on both sides gives ρ′(p)⊕⨁ew′(e)=0=1ˉ\rho'(p) \oplus \bigoplus_e w'(e) = 0 = \bar 1. In the tropical semiring this means the minimum is 0. In the log semiring it means the probabilities add up to 1.

Lines L1 to L7 compute DD exactly in the tropical semiring when no cycle has a negative cost. The proof shows that each d(p)d(p) is always the weight of some path, so d≥Dd \ge D, and that at the end d(p)≤w+d(q)d(p) \le w + d(q) for every arc, so d≤Dd \le D.

Proof: Weight pushing keeps every weight and makes each state stochasticfull

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 ++. The machine TT has states QQ, a start state ii with initial weight λ\lambda, final weights ρ(q)\rho(q) (with ρ(q)=+∞\rho(q) = +\infty when qq is not final) and arcs e=(p,a,b,w,n)e = (p, a, b, w, n) with finite ww. The labels play no part, so everything below holds for acceptors and transducers alike.

For a path π=e1⋯ek\pi = e_1 \cdots e_k from pp to qq, write w(π)=w(e1)+⋯+w(ek)w(\pi) = w(e_1) + \cdots + w(e_k). The distance to the final states is

D(p)=⨁π from p to qw(π)⊗ρ(q),D(p) = \bigoplus_{\pi \text{ from } p \text{ to } q} w(\pi) \otimes \rho(q),

the ⊕\oplus-sum over all paths from pp and all their end states. In the tropical semiring it is the cost of the best path to a final state. In the log semiring it is −log⁡-\log of the total probability of the paths to a final state, and we assume it is finite where a final state can be reached, which holds when the sum converges.

Lemma 1 (any potential keeps the weights). Let dd be any function from the trim states (those with D(q)≠+∞D(q) \ne +\infty) to R\mathbb{R}. Give the machine the new weights λ′=λ+d(i)\lambda' = \lambda + d(i), w′(e)=w(e)+d(n)−d(p)w'(e) = w(e) + d(n) - d(p) for an arc ee from pp to nn, and ρ′(q)=ρ(q)−d(q)\rho'(q) = \rho(q) - d(q), and drop the states with D(q)=+∞D(q) = +\infty with their arcs. Then every successful path keeps its weight, and so every string or string pair keeps its weight.

Proof. A successful path i=q0,q1,…,qki = q_0, q_1, \ldots, q_k visits only trim states, since each of them reaches the final state qkq_k. So the dropped states lie on no successful path and their removal changes no weight. On the path, the new weight telescopes:

λ′+∑j=1k(w(ej)+d(qj)−d(qj−1))+ρ′(qk)=λ+d(q0)+∑jw(ej)+d(qk)−d(q0)+ρ(qk)−d(qk),\lambda' + \sum_{j=1}^{k} \big(w(e_j) + d(q_j) - d(q_{j-1})\big) + \rho'(q_k) = \lambda + d(q_0) + \sum_j w(e_j) + d(q_k) - d(q_0) + \rho(q_k) - d(q_k),

which is λ+∑jw(ej)+ρ(qk)\lambda + \sum_j w(e_j) + \rho(q_k), the old weight. The weight of a string is the ⊕\oplus-sum of the weights of its successful paths, which are the same paths with the same weights. □\square

So the correctness of the weights does not depend on the values of dd. The distances matter only for the second claim, the normal form.

Lemma 2 (the distance equation). DD satisfies, for every state pp,

D(p)=ρ(p)⊕⨁e=(p,⋅,⋅,w,n)w⊗D(n).D(p) = \rho(p) \oplus \bigoplus_{e = (p, \cdot, \cdot, w, n)} w \otimes D(n).

Proof. A path from pp is either empty, which gives the term ρ(p)\rho(p), or starts with an arc ee to nn and goes on with a path from nn. Group the paths by their first arc and use distributivity of ⊗\otimes over the (possibly infinite, convergent) sum. □\square

Lemma 3 (the shortest distance, tropical). In the tropical semiring with no cycle of negative cost, lines L1 to L7 stop and return d=Dd = D.

Proof. We show three facts.

  1. Every value is a path weight. At line L1, d(q)=ρ(q)d(q) = \rho(q) is the weight of the empty path at qq. At line L6, the new value of d(p)d(p) is w+rqw + r_q for an arc from pp to qq, and we show below that rq=d(q)r_q = d(q), so it is the weight of that arc followed by a path from qq. Hence d(p)≥D(p)d(p) \ge D(p) at all times.
  2. At a pop, rq=d(q)r_q = d(q). rqr_q starts at ρ(q)=d(q)\rho(q) = d(q). After a pop it is reset to +∞+\infty, and each later change of d(q)d(q) sets d(q)d(q) to a value xx below the old one and sets rqr_q to min⁡(rq,x)=x\min(r_q, x) = x, since the values xx decrease. A state is queued only after such a change, so at its next pop rq=d(q)r_q = d(q).
  3. At the end, the distance equation holds as an inequality. Consider any arc from pp to qq. After the last change of d(q)d(q), the state qq is in the queue (line L7), and it is popped later, at which point line L6 makes d(p)≤w+d(q)d(p) \le w + d(q). Values only decrease, so this stays true. Also d(q)≤ρ(q)d(q) \le \rho(q) from line L1.

By fact 3 and induction on the length of a path, d(p)d(p) is at most the weight of every path from pp to a final state, plus its final weight. So d(p)≤D(p)d(p) \le D(p), and with fact 1, d=Dd = D.

Termination is the argument for the queue form of Bellman-Ford. Split the run into rounds: round 0 pops the final states queued at line L1, and round k+1k + 1 pops the states queued during round kk. By induction, after round kk every d(p)d(p) is at most the best weight of a path from pp with at most kk arcs, plus its final weight. With no negative cycle, a best path is simple and has at most ∣Q∣−1|Q| - 1 arcs, so after round ∣Q∣−1|Q| - 1 every value is final, no value changes in the next round, and the queue becomes empty. Each round pops each state at most once and looks at each arc at most once, so the time is O(∣Q∣⋅∣E∣)O(|Q| \cdot |E|). □\square

In the log semiring the values d(p)d(p) grow toward D(p)D(p) from below in probability, and the loop stops when no value changes by more than δ\delta. Mohri 2002 shows that the generic algorithm computes DD in a kk-closed semiring. The log semiring is not kk-closed, and in it the result is an approximation; the tests compare it with the exact solution of the linear system for the probabilities.

Theorem (pushing). Let T′T' be the result of lines L8 to L12 with d=Dd = D.

  1. T′T' gives every string, or string pair, the same weight as TT.
  2. Tropical semiring: at every state pp of T′T', the minimum of ρ′(p)\rho'(p) and the weights of the arcs that leave pp is 00, and every arc weight and final weight is ≥0\ge 0. The initial weight λ′\lambda' is the cost of the best successful path of TT.
  3. Log semiring: at every state pp of T′T', e−ρ′(p)+∑e leaves pe−w′(e)=1e^{-\rho'(p)} + \sum_{e \text{ leaves } p} e^{-w'(e)} = 1, so T′T' is stochastic. The initial weight λ′\lambda' is −log⁡-\log of the total probability of TT.

Proof. Claim 1 is Lemma 1. For claims 2 and 3, subtract D(p)D(p) from both sides of the distance equation of Lemma 2. Since ⊗\otimes is ++ and ⊕\oplus commutes with adding a constant to all its arguments,

1ˉ=0=(ρ(p)−D(p))⊕⨁e(w(e)+D(n)−D(p))=ρ′(p)⊕⨁ew′(e).\bar 1 = 0 = \big(\rho(p) - D(p)\big) \oplus \bigoplus_{e} \big(w(e) + D(n) - D(p)\big) = \rho'(p) \oplus \bigoplus_e w'(e).

Arcs into dropped states have D(n)=+∞D(n) = +\infty and contribute +∞=0ˉ+\infty = \bar 0 to the sum, so dropping them changes nothing. In the tropical semiring this says the minimum is 00, so each term is ≥0\ge 0. In the log semiring it says that the probabilities e−ρ′(p)e^{-\rho'(p)} and e−w′(e)e^{-w'(e)} add up to e0=1e^{0} = 1. Finally λ′=λ+D(i)\lambda' = \lambda + D(i) is the ⊕\oplus-sum of the weights of all successful paths, by the definition of DD. □\square

Remark (why this helps pruning). In the tropical case, let a path prefix go from ii to qq. In T′T' its cost, including λ′\lambda', is λ+w(prefix)+D(q)\lambda + w(\text{prefix}) + D(q) by the telescoping sum of Lemma 1, which is the cost of the best complete path that starts with this prefix. Before pushing, the cost of a prefix says nothing about its endings, and a prefix can look cheap and lead only to costly endings.

Complexity

Let nn be the number of states and mm the number of arcs, in the word-RAM model.

  • Tropical semiring, FIFO queue. O(nm)O(n m) time, as for Bellman-Ford, with no cycle of negative cost.
  • Tropical semiring, non-negative weights. With a priority queue instead of the FIFO queue, it is Dijkstra's algorithm, with O(m+nlog⁡n)O(m + n \log n) time (Mohri 2009, Section 6.3).
  • Acyclic machines. In reverse topological order each state is handled once, so the time is O(n+m)O(n + m) in any semiring (DAG shortest paths).
  • Log semiring, with cycles. The number of rounds depends on δ\delta and on how fast the probabilities of long paths fall. There is no bound in nn and mm alone.

Lines L8 to L12 take O(n+m)O(n + m) time. The extra space is O(n+m)O(n + m) for the distances, the residuals, the queue and the reversed arcs.

Properties

  • Exact. Every string, or string pair, keeps its weight, whatever values dd has.
  • The machine shape does not change. Pushing changes only weights and drops states that reach no final state. It never adds a state or an arc.
  • Stochastic in the log semiring. At each state, the outgoing probabilities and the final probability add up to 1, so the pushed machine reads as a Markov chain over its arcs.
  • Non-negative in the tropical semiring. All pushed weights are at least 0, and the best arc out of each state has weight 0.
  • A canonical form. Two equivalent deterministic machines that differ only in where their weights sit become equal after pushing and unweighted minimization (Mohri 2009, Theorem 8).

Variants and improvements

  • Pushing toward the final states. Run the same steps on the reversed machine, with distances from the start state.
  • Pushing labels. The same idea moves output labels toward the start state in a transducer.
  • Approximate distances. Any potential keeps the weights, so a decoder can push with distances from a smaller model or with a cut-off δ\delta, and lose only the normal form.
  • The log semiring for the tropical search. Speech toolkits often push a graph in the log semiring and then search it in the tropical semiring. The result is stochastic, which keeps language model probabilities comparable across states.

When to use it

Use it on a recognition graph after composition and determinization (see HCLG decoding graph), so that a beam search sees the language model cost of a word as early as possible. Use it as the first step of the minimization of a weighted automaton. Use it when you want a stochastic machine from one that has arbitrary non-negative weights. Do not expect it to help a search that does not prune, because an exact search finds the same best path either way.

Pitfalls

  • No successful path. If no final state can be reached from the start, d(i)=0ˉd(i) = \bar 0 and there is nothing to push. The code raises an error.
  • Dead states. A state that reaches no final state has d=+∞d = +\infty, and w+d(n)−d(p)w + d(n) - d(p) would give ∞−∞\infty - \infty. Drop those states first.
  • Negative cycles. In the tropical semiring a cycle of negative cost makes DD equal −∞-\infty, and the FIFO loop never stops.
  • Divergent sums. In the log semiring a cycle whose probabilities add up to 1 or more makes DD infinite or undefined. The weights must form a convergent system.
  • Tolerance. In the log semiring the loop stops at δ\delta, so the result is stochastic only up to about δ\delta per state.
  • Pushing changes intermediate scores. A decoder that reports partial scores, or a lattice that keeps arc scores, shows different numbers after pushing, even though the totals agree.

Implementations

The Python code pushes weighted transducers with costs in the tropical and the log semiring, with the generic shortest-distance algorithm on a FIFO queue. The tests check the tropical distances against Bellman-Ford and the log distances against Gaussian elimination on random machines with cycles, check that every string of length at most 4 keeps its weight, check the normal form at every state (minimum 0, or probabilities that add up to 1), check the example, check that two equivalent machines with differently placed weights become equal, and check the error when no final state can be reached.

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
weight_pushing.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weight-pushing/. The authors are listed in prov/GPP9K3.jsonl.

"""Weight pushing of a weighted automaton or transducer (Mohri 1997, 2002).

Weights are costs -log p. The semiring is TROPICAL (min, +) or LOG_COST
(-log(exp(-a) + exp(-b)), +) from nlslog. Dividing by a finite cost is
subtracting it.

A machine has states 0..n-1, a start state with an initial weight, a final
cost per final state, and arcs (ilabel, olabel, weight, next). Labels play no
part in pushing.

shortest_distance_to_final computes d[q], the semiring sum over all paths from
q to a final state of the path weight times the final weight. It is the
generic single-source shortest-distance algorithm of Mohri 2002, run on the
reversed machine from the final states, with a FIFO queue. It is exact in the
tropical semiring when no cycle has a negative cost. In the log semiring it
stops when no distance changes by more than delta.

push(m) then sets, for every state q with d[q] finite,
    w(e)    <- d[p]^-1 (x) w(e) (x) d[n]   = w(e) + d[n] - d[p]  on costs
    lambda  <- lambda (x) d[i]             = lambda + d[i]
    rho(q)  <- d[q]^-1 (x) rho(q)          = rho(q) - d[q]
States that reach no final state (d = +inf) are dropped first.
"""

from collections import deque
from typing import Dict, List, Tuple

from nlslog import TROPICAL, Semiring


class Machine:
    """A weighted transducer with integer states and costs. An acceptor has ilabel == olabel."""

    def __init__(self) -> None:
        self.start = 0
        self.initial = 0.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 _changed(sr: Semiring, old: float, new: float, delta: float) -> bool:
    if sr.idempotent:
        return new != old
    if old == sr.zero:
        return new != old
    return abs(new - old) > delta


def shortest_distance_to_final(m: Machine, sr: Semiring = TROPICAL, delta: float = 1e-12, max_pops: int = 10 ** 6) -> List[float]:
    """Return d[q] for every state q: the semiring sum over the paths from q to a final state."""
    n = m.num_states()
    incoming: List[List[Tuple[int, float]]] = [[] for _ in range(n)]
    for p in range(n):
        for _, _, w, q in m.arcs[p]:
            incoming[q].append((p, w))
    d = [sr.zero] * n
    r = [sr.zero] * n
    queue: deque = deque()
    queued = [False] * n
    for q, rho in m.final.items():  # @line L1
        d[q] = sr.plus(d[q], rho)
        r[q] = sr.plus(r[q], rho)
        queue.append(q)
        queued[q] = True
    pops = 0
    while queue:  # @line L2
        q = queue.popleft()  # @line L3
        queued[q] = False
        pops += 1
        if pops > max_pops:
            raise RuntimeError("the shortest distance does not converge")
        rq, r[q] = r[q], sr.zero  # @line L4
        for p, w in incoming[q]:  # @line L5
            extra = sr.times(w, rq)
            new = sr.plus(d[p], extra)
            if _changed(sr, d[p], new, delta):  # @line L6
                d[p] = new
                r[p] = sr.plus(r[p], extra)
                if not queued[p]:  # @line L7
                    queue.append(p)
                    queued[p] = True
    return d


def push(m: Machine, sr: Semiring = TROPICAL, delta: float = 1e-12) -> Machine:
    """Return a new machine with the weights pushed toward the start state.

    Every string pair keeps its weight. Raise ValueError if no final state can
    be reached from the start.
    """
    d = shortest_distance_to_final(m, sr, delta)
    if d[m.start] == sr.zero:  # @line L8
        raise ValueError("no successful path")
    out = Machine()
    keep = [q for q in range(m.num_states()) if d[q] != sr.zero]  # @line L9
    new_id = {q: k for k, q in enumerate(keep)}
    for _ in keep:
        out.add_state()
    out.start = new_id[m.start]
    out.initial = sr.times(m.initial, d[m.start])  # @line L10
    for p in keep:
        for a, b, w, n in m.arcs[p]:  # @line L11
            if n in new_id:
                out.add_arc(new_id[p], a, b, sr.times(w, d[n]) - d[p], new_id[n])
        if p in m.final:  # @line L12
            out.set_final(new_id[p], m.final[p] - d[p])
    return out


def string_weight(m: Machine, x, sr: Semiring = TROPICAL) -> float:
    """Return the weight of the input string x in an epsilon-free acceptor m."""
    cur = {m.start: m.initial}
    for c in x:
        nxt: Dict[int, float] = {}
        for q, w in cur.items():
            for a, _, wa, n in m.arcs[q]:
                if a == 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 m.final:
            total = sr.plus(total, sr.times(w, m.final[q]))
    return total
test_weight_pushing.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weight-pushing/. The authors are listed in prov/GPP9K3.jsonl.

import itertools
import math
import random

import pytest

from nlslog import LOG_COST, TROPICAL, Semiring, log_sum
from weight_pushing import Machine, push, shortest_distance_to_final, string_weight

LABELS = ["a", "b"]


def all_strings(max_len: int):
    for k in range(max_len + 1):
        yield from itertools.product(LABELS, repeat=k)


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 random_tropical(rng: random.Random, n: int, m: int) -> Machine:
    t = Machine()
    for _ in range(n):
        t.add_state()
    for _ in range(m):
        c = rng.choice(LABELS)
        t.add_arc(rng.randrange(n), c, c, rng.randint(0, 8) * 0.5, rng.randrange(n))
    for q in rng.sample(range(n), rng.randint(1, n)):
        t.set_final(q, rng.randint(0, 4) * 0.5)
    t.initial = rng.randint(0, 2) * 0.5
    return t


def random_probabilistic(rng: random.Random, n: int, k: int) -> Machine:
    """Each state gives total probability 0.9 to its k arcs and its final weight, so all sums converge."""
    t = Machine()
    for _ in range(n):
        t.add_state()
    for q in range(n):
        parts = [rng.random() + 0.05 for _ in range(k + 1)]
        s = sum(parts)
        for j in range(k):
            c = rng.choice(LABELS)
            t.add_arc(q, c, c, -math.log(0.9 * parts[j] / s), rng.randrange(n))
        if rng.random() < 0.6 or q == n - 1:
            t.set_final(q, -math.log(0.9 * parts[k] / s))
    return t


def bellman_ford_to_final(t: Machine) -> list:
    n = t.num_states()
    d = [math.inf] * n
    for q, rho in t.final.items():
        d[q] = min(d[q], rho)
    for _ in range(n):
        for p in range(n):
            for _, _, w, q in t.arcs[p]:
                d[p] = min(d[p], w + d[q])
    return d


def linear_solve_to_final(t: Machine) -> list:
    """Solve x = P x + f in probabilities by Gaussian elimination, and return the costs -log x."""
    n = t.num_states()
    a = [[0.0] * (n + 1) for _ in range(n)]
    for p in range(n):
        a[p][p] += 1.0
        for _, _, w, q in t.arcs[p]:
            a[p][q] -= math.exp(-w)
        a[p][n] = math.exp(-t.final[p]) if p in t.final else 0.0
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(a[r][col]))
        a[col], a[piv] = a[piv], a[col]
        for r in range(n):
            if r != col and a[r][col] != 0.0:
                f = a[r][col] / a[col][col]
                a[r] = [x - f * y for x, y in zip(a[r], a[col])]
    return [-math.log(a[i][n] / a[i][i]) if a[i][n] / a[i][i] > 0 else math.inf for i in range(n)]


def out_sum(t: Machine, q: int, sr: Semiring) -> float:
    total = t.final.get(q, sr.zero)
    for _, _, w, _ in t.arcs[q]:
        total = sr.plus(total, w)
    return total


def test_page_example():
    t = Machine()
    for _ in range(4):
        t.add_state()
    t.add_arc(0, "a", "a", 0.0, 1)
    t.add_arc(0, "b", "b", 1.0, 2)
    t.add_arc(1, "c", "c", 3.0, 3)
    t.add_arc(2, "c", "c", 1.0, 3)
    t.add_arc(2, "d", "d", 4.0, 3)
    t.set_final(3, 0.0)
    assert shortest_distance_to_final(t, TROPICAL) == [2.0, 3.0, 1.0, 0.0]
    p = push(t, TROPICAL)
    assert p.initial == 2.0
    assert p.arcs == [[("a", "a", 1.0, 1), ("b", "b", 0.0, 2)], [("c", "c", 0.0, 3)], [("c", "c", 0.0, 3), ("d", "d", 3.0, 3)], []]
    d = shortest_distance_to_final(t, LOG_COST)
    assert close(d[2], -math.log(math.exp(-1) + math.exp(-4)))
    p = push(t, LOG_COST)
    for q in range(3):
        assert close(out_sum(p, q, LOG_COST), 0.0)
    assert close(math.exp(-p.arcs[0][0][2]), math.exp(-3) / (math.exp(-3) + math.exp(-2) + math.exp(-5)))


def test_tropical_distances_and_push():
    rng = random.Random(4)
    for _ in range(60):
        t = random_tropical(rng, rng.randint(1, 5), rng.randint(1, 9))
        d = shortest_distance_to_final(t, TROPICAL)
        assert d == bellman_ford_to_final(t)
        if math.isinf(d[t.start]):
            with pytest.raises(ValueError):
                push(t, TROPICAL)
            continue
        p = push(t, TROPICAL)
        assert p.initial == t.initial + d[t.start]
        for q in range(p.num_states()):
            assert close(out_sum(p, q, TROPICAL), 0.0)
            assert all(w >= -1e-12 for _, _, w, _ in p.arcs[q])
        for x in all_strings(4):
            assert close(string_weight(t, x, TROPICAL), string_weight(p, x, TROPICAL))


def test_log_distances_and_stochastic():
    rng = random.Random(5)
    for _ in range(40):
        t = random_probabilistic(rng, rng.randint(1, 5), rng.randint(1, 3))
        d = shortest_distance_to_final(t, LOG_COST)
        ref = linear_solve_to_final(t)
        assert all(close(u, v, 1e-8) for u, v in zip(d, ref))
        if math.isinf(d[t.start]):
            with pytest.raises(ValueError):
                push(t, LOG_COST)
            continue
        p = push(t, LOG_COST)
        for q in range(p.num_states()):
            probs = [math.exp(-w) for _, _, w, _ in p.arcs[q]]
            if q in p.final:
                probs.append(math.exp(-p.final[q]))
            assert abs(sum(probs) - 1.0) < 1e-8
        for x in all_strings(4):
            assert close(string_weight(t, x, LOG_COST), string_weight(p, x, LOG_COST), 1e-8)


def test_pushing_makes_equivalent_machines_equal():
    def chain(w1: float, w2: float, w3: float) -> Machine:
        t = Machine()
        for _ in range(3):
            t.add_state()
        t.add_arc(0, "a", "a", w1, 1)
        t.add_arc(1, "b", "b", w2, 2)
        t.add_arc(1, "c", "c", w3, 2)
        t.set_final(2, 0.0)
        return t

    one = push(chain(1.0, 2.0, 5.0), TROPICAL)
    two = push(chain(3.0, 0.0, 3.0), TROPICAL)
    assert one.arcs == two.arcs and one.initial == two.initial and one.final == two.final


def test_dead_states_are_removed():
    t = Machine()
    for _ in range(3):
        t.add_state()
    t.add_arc(0, "a", "a", 1.0, 1)
    t.add_arc(0, "b", "b", 1.0, 2)
    t.set_final(1, 0.5)
    p = push(t, TROPICAL)
    assert p.num_states() == 2
    assert p.initial == 1.5


def test_no_path_raises():
    t = Machine()
    t.add_state()
    t.add_state()
    t.add_arc(0, "a", "a", 1.0, 0)
    t.set_final(1, 0.0)
    with pytest.raises(ValueError):
        push(t, TROPICAL)


def test_log_sum_of_pushed_start_is_total_weight():
    rng = random.Random(6)
    t = random_probabilistic(rng, 4, 2)
    p = push(t, LOG_COST)
    # In a stochastic machine the total of all strings is 1, so the start weight carries the total.
    total = -log_sum([-string_weight(t, x, LOG_COST) for x in all_strings(8)])
    assert p.initial <= total + 1e-12
    assert abs(p.initial - total) < 0.05

History

Mohri 1997 introduced weight pushing as the first step of the minimization of weighted automata over the tropical semiring: push the weights, then minimize with each (label, weight) pair as one symbol. Mohri 2002 gave the generic shortest-distance algorithm over semirings that pushing uses. Mohri, Pereira and Riley 2002 described its use in speech recognition, where pushing the language model weights forward in the recognition network makes beam pruning more accurate, and Mohri 2009 gives the general algorithm and its running times.

References

  1. Mehryar Mohri, Finite-state transducers in language and speech processing, Computational Linguistics 23(2), 1997, pages 269 to 311, the section on the minimization of weighted automata, which first pushes the weights toward the initial state
  2. Mehryar Mohri, Semiring frameworks and algorithms for shortest-distance problems, Journal of Automata, Languages and Combinatorics 7(3), 2002, pages 321 to 350, the generic single-source shortest-distance algorithm
  3. Mehryar Mohri, Weighted automata algorithms, in Manfred Droste, Werner Kuich and Heiko Vogler (editors), Handbook of Weighted Automata, Springer, 2009, Section 6.3 (weight pushing, Proposition 7 and its running times) and Theorem 8 (minimization by pushing and unweighted minimization)
  4. 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 weight pushing and its effect on pruning in 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