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
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , the shortest distance from to the final states. Then it adds to each arc from to , adds of the start state to the initial weight, and subtracts 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 has states , a start state with an initial weight , final weights , and arcs from to with input label , output label and weight (weighted automaton). The labels play no part here. The distance to the final states is
The task: build an equivalent machine in which, at every state, over the arcs that leave .
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 .
The algorithm
The first part is Mohri's generic single-source shortest-distance algorithm, run backward from the final states. Each state keeps the distance found so far and the residual , the part of that it has not yet passed to its predecessors. The second part is the reweighting.
WEIGHT-PUSH(T)- 1
for each final q: d(q) ← r(q) ← ρ(q); enqueue q ▷ all other d, r are 0̄ - 2
while the queue S is not empty do - 3
q ← DEQUEUE(S) - 4
R ← r(q); r(q) ← 0̄ - 5
for each arc (p, a, b, w, q) into q do - 6
if d(p) ⊕ (w ⊗ R) differs from d(p) then d(p) ← d(p) ⊕ (w ⊗ R); r(p) ← r(p) ⊕ (w ⊗ R) - 7
if p ∉ S then ENQUEUE(S, p) - 8
if d(i) = 0̄ then fail: no successful path - 9
drop the states q with d(q) = 0̄ and their arcs - 10
λ ← λ ⊗ d(i) - 11
for each arc e from p to n: w(e) ← d(p)⁻¹ ⊗ w(e) ⊗ d(n) ▷ on costs: w + d(n) - d(p) - 12
for 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 ". 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 of the probabilities, which stops at tolerance .
Example
The machine has the arcs , , , and , with state 3 final with weight 0 and . Its strings are with cost 3, with cost 2 and with cost 5.
In the tropical semiring the distances are . The pushed machine:
| arc | old weight | |
|---|---|---|
| 0 | ||
| 1 | ||
| 3 | ||
| 1 | ||
| 4 |
The initial weight becomes . The string costs , costs and costs , 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, costs 0 and costs 1, so it keeps , whose best ending gives 3. After pushing, costs 1 and costs 0, so it keeps , which leads to the best string with cost 2.
In the log semiring, , and . The pushed arcs from state 0 have the probabilities for and for , and those from state 2 have for and for . Each set adds up to 1, and 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 , the added terms telescope, and in and in cancel the rest. So every path keeps its weight for any finite , even an approximate one.
- The normal form. The distances satisfy . Subtracting on both sides gives . 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 exactly in the tropical semiring when no cycle has a negative cost. The proof shows that each is always the weight of some path, so , and that at the end for every arc, so .
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 or the log semiring on costs, with . In both, is . The machine has states , a start state with initial weight , final weights (with when is not final) and arcs with finite . The labels play no part, so everything below holds for acceptors and transducers alike.
For a path from to , write . The distance to the final states is
the -sum over all paths from 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 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 be any function from the trim states (those with ) to . Give the machine the new weights , for an arc from to , and , and drop the states with with their arcs. Then every successful path keeps its weight, and so every string or string pair keeps its weight.
Proof. A successful path visits only trim states, since each of them reaches the final state . So the dropped states lie on no successful path and their removal changes no weight. On the path, the new weight telescopes:
which is , the old weight. The weight of a string is the -sum of the weights of its successful paths, which are the same paths with the same weights.
So the correctness of the weights does not depend on the values of . The distances matter only for the second claim, the normal form.
Lemma 2 (the distance equation). satisfies, for every state ,
Proof. A path from is either empty, which gives the term , or starts with an arc to and goes on with a path from . Group the paths by their first arc and use distributivity of over the (possibly infinite, convergent) sum.
Lemma 3 (the shortest distance, tropical). In the tropical semiring with no cycle of negative cost, lines L1 to L7 stop and return .
Proof. We show three facts.
- Every value is a path weight. At line L1, is the weight of the empty path at . At line L6, the new value of is for an arc from to , and we show below that , so it is the weight of that arc followed by a path from . Hence at all times.
- At a pop, . starts at . After a pop it is reset to , and each later change of sets to a value below the old one and sets to , since the values decrease. A state is queued only after such a change, so at its next pop .
- At the end, the distance equation holds as an inequality. Consider any arc from to . After the last change of , the state is in the queue (line L7), and it is popped later, at which point line L6 makes . Values only decrease, so this stays true. Also from line L1.
By fact 3 and induction on the length of a path, is at most the weight of every path from to a final state, plus its final weight. So , and with fact 1, .
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 pops the states queued during round . By induction, after round every is at most the best weight of a path from with at most arcs, plus its final weight. With no negative cycle, a best path is simple and has at most arcs, so after round 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 .
In the log semiring the values grow toward from below in probability, and the loop stops when no value changes by more than . Mohri 2002 shows that the generic algorithm computes in a -closed semiring. The log semiring is not -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 be the result of lines L8 to L12 with .
- gives every string, or string pair, the same weight as .
- Tropical semiring: at every state of , the minimum of and the weights of the arcs that leave is , and every arc weight and final weight is . The initial weight is the cost of the best successful path of .
- Log semiring: at every state of , , so is stochastic. The initial weight is of the total probability of .
Proof. Claim 1 is Lemma 1. For claims 2 and 3, subtract from both sides of the distance equation of Lemma 2. Since is and commutes with adding a constant to all its arguments,
Arcs into dropped states have and contribute to the sum, so dropping them changes nothing. In the tropical semiring this says the minimum is , so each term is . In the log semiring it says that the probabilities and add up to . Finally is the -sum of the weights of all successful paths, by the definition of .
Remark (why this helps pruning). In the tropical case, let a path prefix go from to . In its cost, including , is 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 be the number of states and the number of arcs, in the word-RAM model.
- Tropical semiring, FIFO queue. 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 time (Mohri 2009, Section 6.3).
- Acyclic machines. In reverse topological order each state is handled once, so the time is in any semiring (DAG shortest paths).
- Log semiring, with cycles. The number of rounds depends on and on how fast the probabilities of long paths fall. There is no bound in and alone.
Lines L8 to L12 take time. The extra space is for the distances, the residuals, the queue and the reversed arcs.
Properties
- Exact. Every string, or string pair, keeps its weight, whatever values 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 , 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, and there is nothing to push. The code raises an error.
- Dead states. A state that reaches no final state has , and would give . Drop those states first.
- Negative cycles. In the tropical semiring a cycle of negative cost makes equal , and the FIFO loop never stops.
- Divergent sums. In the log semiring a cycle whose probabilities add up to 1 or more makes infinite or undefined. The weights must form a convergent system.
- Tolerance. In the log semiring the loop stops at , so the result is stochastic only up to about 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.
# 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
- 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
- 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
- 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)
- 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.
| 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 GPP9K3 Edit this page History Report an error Markdown