Algorithmadvanced
Maximum mutual information training
Also called MMI training, MMIE.
Train acoustic models to maximize the posterior of the correct transcript against competitors from a lattice, a discriminative criterion.
- Time
- Θ(T (N + E + P)) worst
- Space
- Θ(T (N + P)) extra
- Where
- E = the number of arcs of both graphs; N = the number of states of the numerator and denominator graphs; P = the number of pdfs; T = the number of frames
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lalit R. Bahl, Peter F. Brown, Peter V. de Souza, Robert L. Mercer, 1986
Maximum mutual information (MMI) training is a way to estimate the parameters of an HMM acoustic model. Maximum likelihood training makes the audio likely under the model of the correct transcript and ignores the other transcripts. MMI makes the correct transcript likely compared with all the others: it maximizes the log posterior probability of the reference words given the audio. The objective is a difference of two log sums over paths, one over the paths of the reference (the numerator) and one over the paths of all competing transcripts (the denominator, in practice a word lattice). A forward-backward pass over each graph gives the objective and its exact gradient: the acoustic scale times the difference of the two state posteriors. The parameters then move by gradient steps or by the extended Baum-Welch update.
In plain words
A recognizer makes errors when a wrong sentence scores almost as high as the right one. Ordinary training only pushes the right sentence up. It never looks at the wrong sentences, so it does not learn what to tell apart.
MMI training looks at both. For each training recording it builds two networks of sound units: one for the right sentence, and one for every sentence the recognizer considers likely. It then asks what share of the total score goes to the right sentence, and it changes the model to make that share larger. A sound unit that the right sentence uses gets pushed up. A unit that the wrong sentences use gets pushed down. When the right sentence already takes almost all of the score, the push is close to zero. So the training spends its effort on the confusable parts.
The problem
Training data are utterances with audio (frames ) and reference word sequences . The acoustic model gives, for each pdf (a tied HMM state) and frame , a log likelihood , from a Gaussian mixture, a discrete distribution or a scaled network output. The language model is fixed. The MMI objective with acoustic scale is
where is the HMM of the word sequence and sums over its state paths. With and a fixed language model, maximizing is the same as maximizing an estimate of the mutual information between words and audio, which gives the name. The task is to compute and , and then to improve .
Both sums are sums over the paths of a graph. Write the numerator graph for the paths of and the denominator graph for the paths of all (it must hold the numerator). A path of states has the score , where the arc weights hold the transition, pronunciation and language model log probabilities. Then with the sum of over the paths of . In the code the graph weights hold the frame-level form ; Woodland and Povey (2002) scale the acoustic likelihoods, which is the same, and also keep the language model unscaled.
The algorithm
is log_add, . All logs are natural logs.
MMI-GRADIENT(ℓ, G_num, G_den, κ) ▷ ℓ: T × P log likelihoods; returns F and dF/dℓ- 1
for G in {G_num, G_den} do - 2
α_1(j) ← init(j) + κ ℓ_1(pdf j); α_t(j) ← ⊕ over arcs i→j of (α_{t-1}(i) + w(i,j)), plus κ ℓ_t(pdf j) - 3
ln Z_G ← ⊕ over j of (α_T(j) + final(j)) - 4
β_T(j) ← final(j); β_t(i) ← ⊕ over arcs i→j of (w(i,j) + κ ℓ_{t+1}(pdf j) + β_{t+1}(j)) - 5
γ^G_t(p) ← Σ over states j with pdf j = p of exp(α_t(j) + β_t(j) - ln Z_G) - 6
F ← ln Z_num - ln Z_den - 7
g_t(p) ← κ (γ^num_t(p) - γ^den_t(p)) - 8
return F and g
The gradient with respect to the model parameters follows by the chain rule. For a network, is the error signal at the output layer (after the division by the priors of a hybrid model). For discrete output distributions and , the derivative with respect to is , where sums over the frames with symbol . The extended Baum-Welch (EBW) update is
must keep every value positive. Gopalakrishnan et al. (1991) proved that a large enough never decreases the objective. Normandin (1996) gave the form for Gaussian means and variances, where each Gaussian gets its own .
Example
Take two words A and B, each one HMM state with its own pdf (0 and 1) and a self loop of weight 1, a language model with , and frames with these likelihoods:
| frame | pdf 0 (A) | pdf 1 (B) |
|---|---|---|
| 1 | 0.6 | 0.3 |
| 2 | 0.5 | 0.4 |
The reference is A. With , the numerator graph has one path with weight . The denominator holds A and B, with weights 0.15 and , so . The posterior of A is and .
At each frame, and , so the gradient is : raise the score of A and lower B, by the posterior mass that B takes. With , the weights become and , the posterior of A falls to 0.612574, and the gradient is . A small makes the competitors stronger, so more of the data gets a non-zero gradient. The tests check these numbers.
Correctness
The proof is in proofs/correctness.md. The forward and backward recursions sum over all partial paths, by induction on and distributivity, so line L3 gives and line L5 gives the posterior of each pdf at each frame under the distribution of over its paths. The score of a path depends on only by times the indicator that the path is in pdf at frame , so , and line L7 is the exact gradient (a theorem). The gradient of each frame sums to 0. If the denominator holds the numerator paths, and is the posterior of the reference.
Proof: The forward-backward recursions give the MMI objective and its exact gradientfull
We use the notation of the page. A graph has emitting states with pdf ids , arcs with log weights , initial log weights and final log weights ; a missing weight is . The frames are and is the log likelihood of pdf at frame . A path is a state sequence (parallel arcs count as different paths), and its score is
Let over the paths of . The proofs use probabilities; in log space is on probabilities, and the code stores logs.
Lemma 1 (forward). After lines L2 and L3, is the sum of over the partial paths with , and the value of line L3 is .
Proof. By induction on . For the only partial path is , and line L2 sets . For , a partial path that ends in is a partial path of length that ends in some , followed by an arc . Its weight is the weight of the shorter path times times . Summing over and the arcs gives the recursion of line L2 by distributivity. A full path is a partial path of length times its final weight, so line L3 sums over all paths.
Lemma 2 (backward). After line L4, is the sum of over the suffixes that follow .
Proof. By induction downwards from , where the only suffix is empty and . A suffix after at frame is an arc , the emission of at frame , and a suffix after at frame , which is the recursion of line L4.
Lemma 3 (posteriors). is the posterior probability, under the distribution on the paths, that . So of line L5 is , and for each .
Proof. Every path with splits in one way into a partial path that ends in at frame and a suffix after , and is the sum of the two parts. So is the sum of over the paths with (Lemmas 1 and 2). Dividing by gives the posterior. Each path has exactly one state at frame , so the posteriors sum to 1.
Theorem. If and , line L6 returns , and line L7 returns
Proof. The value of follows from Lemma 1 for both graphs. For the gradient, depends on only through the term , so . Then
by Lemma 3. Subtract the result for the denominator from the result for the numerator.
Corollary 1. For each frame, . So adding the same constant to all of a frame does not change , and the gradient carries no information about the scale of the frame.
Corollary 2 (a log posterior). If every path of the numerator graph is also a path of the denominator graph with the same score, then and . Then is the posterior probability of the reference under the model in which the denominator graph holds all transcripts. when the two graphs have the same paths, and then the gradient is 0.
Proof. The sum over the numerator paths is part of the sum over the denominator paths, and all terms are positive. With equal path sets the two posteriors of Lemma 3 are equal.
Remark (the extended Baum-Welch update). For discrete output distributions and , the derivative of with respect to is , the difference of the counts of symbol under pdf ; this follows from the theorem by the chain rule, because . The update
keeps a distribution when makes every numerator positive. Gopalakrishnan, Kanevsky, Nádas and Nahamoo (1991) proved that for a large enough this update does not decrease a rational function such as . The proof here does not cover that result; the tests check it on small cases and check the counts against finite differences.
Complexity
Each forward or backward step visits every state and every arc once per frame, so one graph costs log_add operations, and line L5 and line L7 add . Space is for and plus for the posteriors. In large vocabulary training the denominator is a lattice of the competing hypotheses, generated once by a recognizer with a weak language model, and its size dominates the cost. Lattice-free MMI replaces it by a phone graph that is the same for every utterance.
Properties
- Exact objective and gradient. For given graphs, the two forward-backward passes compute and its gradient exactly (a theorem).
- A log posterior. If the denominator holds the numerator, , and only when no competitor has weight. Then the gradient is 0 (a corollary).
- The gradient is a difference of counts. Statistics of the numerator push up, statistics of the denominator push down, and well-recognized utterances contribute almost nothing.
- Not concave. is a difference of two log sums and has local optima, so training starts from a maximum likelihood model.
- Matches maximum likelihood only in the limit. If the model family contains the true distribution and there is unlimited data, both criteria give it. With a wrong model, MMI usually gives a lower error rate.
Variants and improvements
- Lattice-based MMI. The denominator is a word lattice from a first decoding pass, with the time boundaries of the words fixed (Woodland and Povey 2002).
- Lattice-free MMI. The denominator is a phone n-gram graph, run on all frames of short chunks (see lattice-free MMI).
- Boosted MMI adds a term to the competing paths in proportion to their errors, so close competitors weigh more.
- Minimum phone error (MPE) and state-level minimum Bayes risk (sMBR) maximize the expected accuracy over the lattice paths instead of the posterior of the reference. They share the lattice and the forward-backward machinery.
- Sequence training of neural networks. The same gradient trains the network of a hybrid DNN-HMM model, usually after cross-entropy training.
When to use it
Use it after maximum likelihood or cross-entropy training of an HMM-based recognizer, to lower the word error rate. It needs a good starting model, the lattices (or a phone graph), and a held-out set to choose , and the number of iterations. It does not fit end-to-end models such as CTC, which already have a normalized sequence-level loss.
Pitfalls
- Acoustic scale. With the acoustic scores dwarf the language model, the posterior of the best path is close to 1, and few frames get a gradient. Use the same small scale as in decoding (for example the inverse of the language model weight).
- The numerator must be in the denominator. Otherwise can be positive and is no longer a log posterior; add the reference to each lattice.
- Too small . The EBW update can give negative probabilities or variances, or decrease . Set per pdf from the denominator counts, with a safe lower bound.
- Over-training. The objective keeps improving on the training set while the test error rises. Smooth towards the maximum likelihood statistics and stop early.
- Stale lattices. The lattices come from an older model. Regenerate them, or use a lattice-free denominator.
Implementations
The code takes the per-frame log likelihoods and the two graphs as given and computes the objective, its gradient and the extended Baum-Welch update of discrete distributions; it does not train a network. The tests compare the forward pass with a sum over all paths, the gradient with finite differences, and check that the update does not decrease the objective.
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
# Part of https://algorithm.tamnd.com/maximum-mutual-information-training/. The authors are listed in prov/BW4ZT9.jsonl.
"""Maximum mutual information (MMI) training: the objective, its gradient and
the extended Baum-Welch update of discrete output distributions.
The acoustic model is an HMM whose emitting states carry pdf ids. The caller
gives loglik[t][p] = ln p(o_t | pdf p) for frames t = 0..T-1 (a Gaussian
mixture log density, a discrete output probability, or a scaled network output).
A graph is a set of emitting states with pdf ids, arcs (i, j, ln w), initial
log weights and final log weights. The graph weights hold the transition
probabilities, the pronunciation probabilities and the language model
probabilities. The numerator graph holds the paths of the reference
transcript, the denominator graph the paths of all competing transcripts (in
practice a lattice; here any small graph, for example the union of a list of
word sequences). With an acoustic scale kappa, the score of a state path
q_0..q_{T-1} is
kappa * sum_t loglik[t][pdf(q_t)] + init(q_0) + sum_t ln w(q_{t-1}, q_t) + final(q_{T-1}),
Z_G is the sum of exp(score) over the paths of G, and the MMI objective of one
utterance is F = ln Z_num - ln Z_den. Its gradient with respect to
loglik[t][p] is kappa * (gamma_num[t][p] - gamma_den[t][p]), where gamma is the
posterior probability of pdf p at frame t in each graph.
All logs are natural logs. The code takes the per-frame scores as given.
"""
import math
from dataclasses import dataclass, field
from typing import Dict, List, Sequence, Tuple
from nlslog import NEG_INF, log_sum
@dataclass
class Graph:
"""An HMM graph of emitting states. pdf[j] is the pdf id of state j."""
pdf: List[int]
arcs: List[Tuple[int, int, float]]
init: Dict[int, float]
final: Dict[int, float]
incoming: List[List[Tuple[int, float]]] = field(init=False)
outgoing: List[List[Tuple[int, float]]] = field(init=False)
def __post_init__(self):
n = len(self.pdf)
self.incoming = [[] for _ in range(n)]
self.outgoing = [[] for _ in range(n)]
for i, j, w in self.arcs:
self.incoming[j].append((i, w))
self.outgoing[i].append((j, w))
def word_sequence_graph(words: Sequence[str], models: Dict[str, Sequence[int]], log_self: float, log_next: float, log_lm: float = 0.0) -> Graph:
"""A left-to-right chain for one word sequence. Each word is a list of pdf ids,
one emitting state each, with a self loop (ln weight log_self) and a move to the
next state (log_next). log_lm is added at the start (the LM log probability of
the whole sequence)."""
pdf: List[int] = []
for w in words:
pdf.extend(models[w])
n = len(pdf)
arcs = [(j, j, log_self) for j in range(n)] + [(j, j + 1, log_next) for j in range(n - 1)]
return Graph(pdf, arcs, {0: log_lm}, {n - 1: 0.0})
def union(graphs: Sequence[Graph]) -> Graph:
"""The union of graphs with disjoint state sets: a path of the union is a path of one of them."""
pdf: List[int] = []
arcs: List[Tuple[int, int, float]] = []
init: Dict[int, float] = {}
final: Dict[int, float] = {}
for g in graphs:
off = len(pdf)
pdf.extend(g.pdf)
arcs.extend((i + off, j + off, w) for i, j, w in g.arcs)
init.update({j + off: w for j, w in g.init.items()})
final.update({j + off: w for j, w in g.final.items()})
return Graph(pdf, arcs, init, final)
def forward_backward(g: Graph, loglik: Sequence[Sequence[float]], kappa: float):
"""Return (ln Z, gamma) for the graph g, where gamma[t][p] is the posterior of pdf p
at frame t. Raise ValueError if Z = 0 (no path of g has T frames)."""
T, n = len(loglik), len(g.pdf)
P = len(loglik[0])
emit = [[kappa * loglik[t][g.pdf[j]] for j in range(n)] for t in range(T)]
alpha = [[NEG_INF] * n for _ in range(T)]
for j, w in g.init.items():
alpha[0][j] = w + emit[0][j] # @line L2
for t in range(1, T):
for j in range(n):
alpha[t][j] = log_sum([alpha[t - 1][i] + w for i, w in g.incoming[j]]) + emit[t][j]
log_z = log_sum([alpha[T - 1][j] + w for j, w in g.final.items()]) # @line L3
if log_z == NEG_INF:
raise ValueError("the graph has no path of this length")
beta = [[NEG_INF] * n for _ in range(T)]
for j, w in g.final.items():
beta[T - 1][j] = w # @line L4
for t in range(T - 2, -1, -1):
for i in range(n):
beta[t][i] = log_sum([w + emit[t + 1][j] + beta[t + 1][j] for j, w in g.outgoing[i]])
gamma = [[0.0] * P for _ in range(T)]
for t in range(T):
for j in range(n):
if alpha[t][j] > NEG_INF and beta[t][j] > NEG_INF:
gamma[t][g.pdf[j]] += math.exp(alpha[t][j] + beta[t][j] - log_z) # @line L5
return log_z, gamma
def mmi_objective_and_grad(loglik: Sequence[Sequence[float]], num: Graph, den: Graph, kappa: float = 1.0):
"""Return (F, grad, gamma_num, gamma_den) for one utterance. F = ln Z_num - ln Z_den,
grad[t][p] = dF / d loglik[t][p] = kappa (gamma_num[t][p] - gamma_den[t][p])."""
results = [forward_backward(g, loglik, kappa) for g in (num, den)] # @line L1
(lz_num, g_num), (lz_den, g_den) = results
F = lz_num - lz_den # @line L6
P = len(loglik[0])
grad = [[kappa * (g_num[t][p] - g_den[t][p]) for p in range(P)] for t in range(len(loglik))] # @line L7
return F, grad, g_num, g_den # @line L8
def mmi_objective(loglik: Sequence[Sequence[float]], num: Graph, den: Graph, kappa: float = 1.0) -> float:
return forward_backward(num, loglik, kappa)[0] - forward_backward(den, loglik, kappa)[0]
def brute_force_log_z(g: Graph, loglik: Sequence[Sequence[float]], kappa: float) -> float:
"""ln Z by listing every path of T states, one by one. Only for small graphs."""
T = len(loglik)
terms: List[float] = []
def walk(j: int, t: int, s: float) -> None:
s += kappa * loglik[t][g.pdf[j]]
if t == T - 1:
if j in g.final:
terms.append(s + g.final[j])
return
for k, w in g.outgoing[j]:
walk(k, t + 1, s + w)
for j, w in g.init.items():
walk(j, 0, w)
return log_sum(terms)
# ---------------------------------------------------------------- discrete output distributions and extended Baum-Welch
def discrete_loglik(b: Sequence[Sequence[float]], obs: Sequence[int]) -> List[List[float]]:
"""loglik[t][p] = ln b[p][obs[t]] for discrete output distributions b[p][v]."""
return [[math.log(b[p][v]) for p in range(len(b))] for v in obs]
def ebw_counts(data, b, kappa: float = 1.0):
"""Sum over the utterances (obs, num, den) of the numerator and denominator
counts c[p][v] = sum of gamma[t][p] over the frames t with obs[t] = v, and the
total objective."""
P, V = len(b), len(b[0])
c_num = [[0.0] * V for _ in range(P)]
c_den = [[0.0] * V for _ in range(P)]
total = 0.0
for obs, num, den in data:
F, _, g_num, g_den = mmi_objective_and_grad(discrete_loglik(b, obs), num, den, kappa)
total += F
for t, v in enumerate(obs):
for p in range(P):
c_num[p][v] += kappa * g_num[t][p]
c_den[p][v] += kappa * g_den[t][p]
return total, c_num, c_den
def ebw_update(b, c_num, c_den, D: float):
"""The extended Baum-Welch update of discrete distributions:
b'[p][v] = (c_num[p][v] - c_den[p][v] + D b[p][v]) / (sum over v of the same).
Raise ValueError if D is too small to keep every value positive."""
out = []
for p in range(len(b)):
row = [c_num[p][v] - c_den[p][v] + D * b[p][v] for v in range(len(b[p]))]
if min(row) <= 0:
raise ValueError("D is too small: a probability would not be positive")
s = math.fsum(row)
out.append([x / s for x in row])
return out
def smallest_safe_d(b, c_num, c_den) -> float:
"""The smallest D that keeps every updated value positive (each row separately
would need less; this is one D for all)."""
need = 0.0
for p in range(len(b)):
for v in range(len(b[p])):
need = max(need, (c_den[p][v] - c_num[p][v]) / b[p][v])
return need
nlslog.py 152 lines
# 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
test_maximum_mutual_information_training.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-mutual-information-training/. The authors are listed in prov/BW4ZT9.jsonl.
import math
import random
import pytest
import nlslog
from maximum_mutual_information_training import (
Graph,
brute_force_log_z,
discrete_loglik,
ebw_counts,
ebw_update,
forward_backward,
mmi_objective,
mmi_objective_and_grad,
smallest_safe_d,
union,
word_sequence_graph,
)
from nlslog import NEG_INF, log_add
LS, LN = math.log(0.6), math.log(0.4)
def one_state_words():
models = {"A": [0], "B": [1]}
ll = [[math.log(0.6), math.log(0.3)], [math.log(0.5), math.log(0.4)]]
a = word_sequence_graph(["A"], models, 0.0, NEG_INF, math.log(0.5))
b = word_sequence_graph(["B"], models, 0.0, NEG_INF, math.log(0.5))
return ll, a, union([a, b])
def random_task(rng, T, P=3):
models = {"A": [0, 1], "B": [1, 2], "C": [2, 0, 1]}
words = ["A", "B", "C"]
ref = [rng.choice(words) for _ in range(rng.randint(1, 2))]
lm = math.log(1 / 3) * len(ref)
num = word_sequence_graph(ref, models, LS, LN, lm)
comps = [[w] for w in words] + [[u, v] for u in words for v in words]
comps = [c for c in comps if sum(len(models[w]) for w in c) <= T]
if ref not in comps:
comps.append(ref)
den = union([word_sequence_graph(c, models, LS, LN, math.log(1 / 3) * len(c)) for c in comps])
loglik = [[rng.uniform(-3.0, 0.0) for _ in range(P)] for _ in range(T)]
return loglik, num, den
def test_helper_header():
with open(nlslog.__file__, encoding="utf-8") as f:
lines = f.read().splitlines()
assert lines[1] == "# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/."
def test_log_add_check_value():
assert log_add(math.log(0.5), math.log(0.25)) == pytest.approx(-0.287682, abs=1e-6)
def test_page_example():
ll, num, den = one_state_words()
F, grad, g_num, g_den = mmi_objective_and_grad(ll, num, den, 1.0)
assert math.exp(F) == pytest.approx(0.15 / 0.21, abs=1e-12)
assert F == pytest.approx(-0.336472, abs=1e-6)
for t in range(2):
assert grad[t] == pytest.approx([2 / 7, -2 / 7], abs=1e-12)
F, grad, _, _ = mmi_objective_and_grad(ll, num, den, 0.5)
post = 0.5 * math.sqrt(0.30) / (0.5 * math.sqrt(0.30) + 0.5 * math.sqrt(0.12))
assert math.exp(F) == pytest.approx(post, abs=1e-12)
assert math.exp(F) == pytest.approx(0.612574, abs=1e-6)
assert grad[0] == pytest.approx([0.5 * (1 - post), -0.5 * (1 - post)], abs=1e-12)
def test_forward_against_brute_force():
rng = random.Random(1)
for _ in range(15):
T = rng.randint(2, 5)
loglik, num, den = random_task(rng, T)
kappa = rng.choice([1.0, 0.5, 0.1])
for g in (num, den):
try:
lz, gamma = forward_backward(g, loglik, kappa)
except ValueError:
assert brute_force_log_z(g, loglik, kappa) == NEG_INF
continue
assert lz == pytest.approx(brute_force_log_z(g, loglik, kappa), abs=1e-10)
for t in range(T):
assert sum(gamma[t]) == pytest.approx(1.0, abs=1e-12)
def test_objective_is_a_log_posterior():
# When the denominator holds the numerator paths, F = ln P(reference | O) <= 0.
rng = random.Random(2)
for _ in range(10):
loglik, num, den = random_task(rng, rng.randint(3, 6))
try:
F = mmi_objective(loglik, num, den, 0.3)
except ValueError:
continue
assert F <= 1e-12
def test_gradient_against_finite_differences():
rng = random.Random(3)
h = 1e-6
done = 0
while done < 4:
T = rng.randint(3, 5)
loglik, num, den = random_task(rng, T)
kappa = rng.choice([1.0, 0.25])
try:
_, grad, _, _ = mmi_objective_and_grad(loglik, num, den, kappa)
except ValueError:
continue
done += 1
for t in range(T):
for p in range(len(loglik[0])):
up = [r[:] for r in loglik]
dn = [r[:] for r in loglik]
up[t][p] += h
dn[t][p] -= h
fd = (mmi_objective(up, num, den, kappa) - mmi_objective(dn, num, den, kappa)) / (2 * h)
assert grad[t][p] == pytest.approx(fd, abs=1e-5)
# Both posteriors sum to 1 at each frame, so the gradient of a frame sums to 0.
assert sum(grad[t]) == pytest.approx(0.0, abs=1e-12)
def test_gradient_is_zero_when_there_is_no_competitor():
ll, num, _ = one_state_words()
F, grad, _, _ = mmi_objective_and_grad(ll, num, num, 1.0)
assert F == 0.0
assert all(abs(x) < 1e-15 for row in grad for x in row)
def test_extended_baum_welch_never_decreases_the_objective():
rng = random.Random(4)
models = {"A": [0, 1], "B": [1, 2], "C": [2, 0]}
P, V = 3, 3
b = [[rng.random() + 0.2 for _ in range(V)] for _ in range(P)]
b = [[x / sum(r) for x in r] for r in b]
data = []
for _ in range(4):
obs = [rng.randrange(V) for _ in range(rng.randint(4, 6))]
ref = rng.choice("ABC")
num = word_sequence_graph([ref], models, LS, LN, math.log(1 / 3))
den = union([word_sequence_graph([w], models, LS, LN, math.log(1 / 3)) for w in "ABC"])
data.append((obs, num, den))
values = []
for _ in range(8):
F, c_num, c_den = ebw_counts(data, b)
values.append(F)
D = 2 * smallest_safe_d(b, c_num, c_den) + 1.0
b = ebw_update(b, c_num, c_den, D)
for row in b:
assert min(row) > 0 and sum(row) == pytest.approx(1.0, abs=1e-12)
assert all(values[i + 1] >= values[i] - 1e-12 for i in range(len(values) - 1))
assert values[-1] > values[0] + 1.0
def test_ebw_counts_are_the_gradient_in_log_b():
# d F / d ln b[p][v] = c_num[p][v] - c_den[p][v] (kappa = 1).
rng = random.Random(5)
models = {"A": [0, 1], "B": [1, 0]}
b = [[0.3, 0.7], [0.6, 0.4]]
obs = [rng.randrange(2) for _ in range(5)]
num = word_sequence_graph(["A"], models, LS, LN, math.log(0.5))
den = union([word_sequence_graph([w], models, LS, LN, math.log(0.5)) for w in "AB"])
_, c_num, c_den = ebw_counts([(obs, num, den)], b)
h = 1e-6
for p in range(2):
for v in range(2):
def f(delta):
bb = [r[:] for r in b]
bb[p][v] = b[p][v] * math.exp(delta)
return mmi_objective(discrete_loglik(bb, obs), num, den, 1.0)
fd = (f(h) - f(-h)) / (2 * h)
assert c_num[p][v] - c_den[p][v] == pytest.approx(fd, abs=1e-5)
def test_errors():
models = {"A": [0, 1, 0]}
g = word_sequence_graph(["A"], models, LS, LN)
with pytest.raises(ValueError):
forward_backward(g, [[0.0, 0.0]] * 2, 1.0) # 3 states, 2 frames
with pytest.raises(ValueError):
ebw_update([[0.5, 0.5]], [[0.0, 0.0]], [[1.0, 0.0]], 1.0)
assert isinstance(g, Graph)
History
Bahl, Brown, de Souza and Mercer (1986) proposed estimating the parameters of a speech HMM by maximum mutual information. Gopalakrishnan, Kanevsky, Nádas and Nahamoo (1991) extended the Baum-Eagon inequality to rational functions, which gave the extended Baum-Welch update for discrete distributions, and Normandin (1996) gave the update for Gaussian densities. Woodland and Povey (2002) made MMI work on large vocabulary tasks with lattices for the denominator, acoustic scaling and a weak language model. Povey et al. (2016) removed the lattices with lattice-free MMI.
References
- Lalit R. Bahl, Peter F. Brown, Peter V. de Souza and Robert L. Mercer, Maximum mutual information estimation of hidden Markov model parameters for speech recognition, ICASSP 1986, pages 49 to 52, the whole paper (the MMI criterion for HMM parameters)
- Phil C. Woodland and Daniel Povey, Large scale discriminative training of hidden Markov models for speech recognition, Computer Speech and Language 16(1), 2002, pages 25 to 47, the sections on the MMIE objective, lattice-based training, acoustic scaling and the extended Baum-Welch update
- The extended Baum-Welch growth transform for rational objectives, the main theorem and its application to discrete HMM parameters
- Yves Normandin, Maximum mutual information estimation of hidden Markov models, in Automatic Speech and Speaker Recognition: Advanced Topics, Kluwer, 1996, pages 57 to 81, the chapter (the extended Baum-Welch update for Gaussian densities)
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 BW4ZT9 Edit this page History Report an error Markdown