Algorithm Search⌘K

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
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 r=1,…,Rr = 1, \ldots, R with audio OrO_r (frames o1,…,oTo_1, \ldots, o_T) and reference word sequences WrW_r. The acoustic model gives, for each pdf pp (a tied HMM state) and frame tt, a log likelihood ℓt(p)=ln⁡pθ(ot∣p)\ell_t(p) = \ln p_\theta(o_t \mid p), from a Gaussian mixture, a discrete distribution or a scaled network output. The language model P(W)P(W) is fixed. The MMI objective with acoustic scale κ\kappa is

F(θ)=∑r=1Rln⁡pθ(Or∣MWr)κP(Wr)∑Wpθ(Or∣MW)κP(W),F(\theta) = \sum_{r=1}^{R} \ln \frac{p_\theta(O_r \mid M_{W_r})^{\kappa} P(W_r)}{\sum_{W} p_\theta(O_r \mid M_W)^{\kappa} P(W)},

where MWM_W is the HMM of the word sequence WW and pθ(O∣MW)p_\theta(O \mid M_W) sums over its state paths. With κ=1\kappa = 1 and a fixed language model, maximizing FF is the same as maximizing an estimate of the mutual information between words and audio, which gives the name. The task is to compute FF and ∂F/∂ℓt(p)\partial F / \partial \ell_t(p), and then to improve θ\theta.

Both sums are sums over the paths of a graph. Write the numerator graph GnumG_{\mathrm{num}} for the paths of WrW_r and the denominator graph GdenG_{\mathrm{den}} for the paths of all WW (it must hold the numerator). A path q1…qTq_1 \ldots q_T of states has the score init(q1)+∑tw(qt−1,qt)+final(qT)+κ∑tℓt(pdf(qt))\mathrm{init}(q_1) + \sum_t w(q_{t-1}, q_t) + \mathrm{final}(q_T) + \kappa \sum_t \ell_t(\mathrm{pdf}(q_t)), where the arc weights hold the transition, pronunciation and language model log probabilities. Then F=ln⁡Znum−ln⁡ZdenF = \ln Z_{\mathrm{num}} - \ln Z_{\mathrm{den}} with ZGZ_G the sum of escoree^{\mathrm{score}} over the paths of GG. In the code the graph weights hold the frame-level form κℓt\kappa \ell_t; Woodland and Povey (2002) scale the acoustic likelihoods, which is the same, and also keep the language model unscaled.

The algorithm

⊕\oplus is log_add, a⊕b=ln⁡(ea+eb)a \oplus b = \ln(e^a + e^b). All logs are natural logs.

  1. MMI-GRADIENT(ℓ, G_num, G_den, κ) ▷ ℓ: T × P log likelihoods; returns F and dF/dℓ
  2. 1for G in {G_num, G_den} do
  3. 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)
  4. 3ln Z_G ← ⊕ over j of (α_T(j) + final(j))
  5. 4β_T(j) ← final(j); β_t(i) ← ⊕ over arcs i→j of (w(i,j) + κ ℓ_{t+1}(pdf j) + β_{t+1}(j))
  6. 5γ^G_t(p) ← Σ over states j with pdf j = p of exp(α_t(j) + β_t(j) - ln Z_G)
  7. 6F ← ln Z_num - ln Z_den
  8. 7g_t(p) ← κ (γ^num_t(p) - γ^den_t(p))
  9. 8return F and g

The gradient with respect to the model parameters follows by the chain rule. For a network, gg is the error signal at the output layer (after the division by the priors of a hybrid model). For discrete output distributions bp(v)b_p(v) and κ=1\kappa = 1, the derivative with respect to ln⁡bp(v)\ln b_p(v) is cpnum(v)−cpden(v)c^{\mathrm{num}}_p(v) - c^{\mathrm{den}}_p(v), where cp(v)c_p(v) sums γt(p)\gamma_t(p) over the frames with symbol vv. The extended Baum-Welch (EBW) update is

bp′(v)=cpnum(v)−cpden(v)+D bp(v)∑v′(cpnum(v′)−cpden(v′)+D bp(v′)).b'_p(v) = \frac{c^{\mathrm{num}}_p(v) - c^{\mathrm{den}}_p(v) + D\, b_p(v)}{\sum_{v'} \left( c^{\mathrm{num}}_p(v') - c^{\mathrm{den}}_p(v') + D\, b_p(v') \right)}.

DD must keep every value positive. Gopalakrishnan et al. (1991) proved that a large enough DD never decreases the objective. Normandin (1996) gave the form for Gaussian means and variances, where each Gaussian gets its own DD.

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 P(A)=P(B)=0.5P(\mathrm{A}) = P(\mathrm{B}) = 0.5, and T=2T = 2 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 κ=1\kappa = 1, the numerator graph has one path with weight 0.5⋅0.6⋅0.5=0.150.5 \cdot 0.6 \cdot 0.5 = 0.15. The denominator holds A and B, with weights 0.15 and 0.5⋅0.3⋅0.4=0.060.5 \cdot 0.3 \cdot 0.4 = 0.06, so Zden=0.21Z_{\mathrm{den}} = 0.21. The posterior of A is 0.15/0.21=0.7142860.15 / 0.21 = 0.714286 and F=ln⁡0.714286=−0.336472F = \ln 0.714286 = -0.336472.

At each frame, γnum=(1,0)\gamma^{\mathrm{num}} = (1, 0) and γden=(5/7,2/7)\gamma^{\mathrm{den}} = (5/7, 2/7), so the gradient is (+0.285714,−0.285714)(+0.285714, -0.285714): raise the score of A and lower B, by the posterior mass that B takes. With κ=0.5\kappa = 0.5, the weights become 0.50.300.5\sqrt{0.30} and 0.50.120.5\sqrt{0.12}, the posterior of A falls to 0.612574, and the gradient is ±0.5⋅0.387426=±0.193713\pm 0.5 \cdot 0.387426 = \pm 0.193713. A small κ\kappa 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 escoree^{\mathrm{score}} over all partial paths, by induction on tt and distributivity, so line L3 gives ln⁡ZG\ln Z_G and line L5 gives the posterior of each pdf at each frame under the distribution of GG over its paths. The score of a path depends on ℓt(p)\ell_t(p) only by κ\kappa times the indicator that the path is in pdf pp at frame tt, so ∂ln⁡ZG/∂ℓt(p)=κγtG(p)\partial \ln Z_G / \partial \ell_t(p) = \kappa \gamma^G_t(p), and line L7 is the exact gradient (a theorem). The gradient of each frame sums to 0. If the denominator holds the numerator paths, F≤0F \le 0 and eFe^F 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 GG has emitting states jj with pdf ids pdf(j)\mathrm{pdf}(j), arcs i→ji \to j with log weights w(i,j)w(i, j), initial log weights init(j)\mathrm{init}(j) and final log weights final(j)\mathrm{final}(j); a missing weight is −∞-\infty. The frames are t=1,…,Tt = 1, \ldots, T and ℓt(p)\ell_t(p) is the log likelihood of pdf pp at frame tt. A path is a state sequence q=q1…qTq = q_1 \ldots q_T (parallel arcs count as different paths), and its score is

s(q)=init(q1)+∑t=2Tw(qt−1,qt)+final(qT)+κ∑t=1Tℓt(pdf(qt)).s(q) = \mathrm{init}(q_1) + \sum_{t=2}^{T} w(q_{t-1}, q_t) + \mathrm{final}(q_T) + \kappa \sum_{t=1}^{T} \ell_t(\mathrm{pdf}(q_t)).

Let ZG=∑qes(q)Z_G = \sum_q e^{s(q)} over the paths of GG. The proofs use probabilities; ⊕\oplus in log space is ++ on probabilities, and the code stores logs.

Lemma 1 (forward). After lines L2 and L3, eαt(j)e^{\alpha_t(j)} is the sum of einit(q1)+∑τ=2tw(qτ−1,qτ)+κ∑τ=1tℓτ(pdf(qτ))e^{\mathrm{init}(q_1) + \sum_{\tau=2}^{t} w(q_{\tau-1}, q_\tau) + \kappa \sum_{\tau=1}^{t} \ell_\tau(\mathrm{pdf}(q_\tau))} over the partial paths q1…qtq_1 \ldots q_t with qt=jq_t = j, and the value of line L3 is ln⁡ZG\ln Z_G.

Proof. By induction on tt. For t=1t = 1 the only partial path is jj, and line L2 sets α1(j)=init(j)+κℓ1(pdf(j))\alpha_1(j) = \mathrm{init}(j) + \kappa \ell_1(\mathrm{pdf}(j)). For t≥2t \ge 2, a partial path that ends in jj is a partial path of length t−1t - 1 that ends in some ii, followed by an arc i→ji \to j. Its weight is the weight of the shorter path times ew(i,j)e^{w(i, j)} times eκℓt(pdf(j))e^{\kappa \ell_t(\mathrm{pdf}(j))}. Summing over ii and the arcs gives the recursion of line L2 by distributivity. A full path is a partial path of length TT times its final weight, so line L3 sums es(q)e^{s(q)} over all paths. □\square

Lemma 2 (backward). After line L4, eβt(i)e^{\beta_t(i)} is the sum of e∑τ=t+1T(w(qτ−1,qτ)+κℓτ(pdf(qτ)))+final(qT)e^{\sum_{\tau=t+1}^{T} (w(q_{\tau-1}, q_\tau) + \kappa \ell_\tau(\mathrm{pdf}(q_\tau))) + \mathrm{final}(q_T)} over the suffixes qt+1…qTq_{t+1} \ldots q_T that follow qt=iq_t = i.

Proof. By induction downwards from t=Tt = T, where the only suffix is empty and βT(i)=final(i)\beta_T(i) = \mathrm{final}(i). A suffix after ii at frame tt is an arc i→ji \to j, the emission of jj at frame t+1t + 1, and a suffix after jj at frame t+1t + 1, which is the recursion of line L4. □\square

Lemma 3 (posteriors). eαt(j)+βt(j)−ln⁡ZGe^{\alpha_t(j) + \beta_t(j) - \ln Z_G} is the posterior probability, under the distribution PG(q)=es(q)/ZGP_G(q) = e^{s(q)} / Z_G on the paths, that qt=jq_t = j. So γtG(p)\gamma^G_t(p) of line L5 is PG(pdf(qt)=p)P_G(\mathrm{pdf}(q_t) = p), and ∑pγtG(p)=1\sum_p \gamma^G_t(p) = 1 for each tt.

Proof. Every path with qt=jq_t = j splits in one way into a partial path that ends in jj at frame tt and a suffix after jj, and s(q)s(q) is the sum of the two parts. So eαt(j)+βt(j)e^{\alpha_t(j) + \beta_t(j)} is the sum of es(q)e^{s(q)} over the paths with qt=jq_t = j (Lemmas 1 and 2). Dividing by ZGZ_G gives the posterior. Each path has exactly one state at frame tt, so the posteriors sum to 1. □\square

Theorem. If Znum>0Z_{\mathrm{num}} > 0 and Zden>0Z_{\mathrm{den}} > 0, line L6 returns F=ln⁡Znum−ln⁡ZdenF = \ln Z_{\mathrm{num}} - \ln Z_{\mathrm{den}}, and line L7 returns

∂F∂ℓt(p)=κ(γtnum(p)−γtden(p)).\frac{\partial F}{\partial \ell_t(p)} = \kappa \left( \gamma^{\mathrm{num}}_t(p) - \gamma^{\mathrm{den}}_t(p) \right).

Proof. The value of FF follows from Lemma 1 for both graphs. For the gradient, s(q)s(q) depends on ℓt(p)\ell_t(p) only through the term κℓt(pdf(qt))\kappa \ell_t(\mathrm{pdf}(q_t)), so ∂s(q)/∂ℓt(p)=κ[pdf(qt)=p]\partial s(q) / \partial \ell_t(p) = \kappa [\mathrm{pdf}(q_t) = p]. Then

∂ln⁡ZG∂ℓt(p)=1ZG∑qes(q)κ[pdf(qt)=p]=κPG(pdf(qt)=p)=κγtG(p)\frac{\partial \ln Z_G}{\partial \ell_t(p)} = \frac{1}{Z_G} \sum_q e^{s(q)} \kappa [\mathrm{pdf}(q_t) = p] = \kappa P_G(\mathrm{pdf}(q_t) = p) = \kappa \gamma^G_t(p)

by Lemma 3. Subtract the result for the denominator from the result for the numerator. □\square

Corollary 1. For each frame, ∑p∂F/∂ℓt(p)=κ(1−1)=0\sum_p \partial F / \partial \ell_t(p) = \kappa (1 - 1) = 0. So adding the same constant to all ℓt(p)\ell_t(p) of a frame does not change FF, 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 Znum≤ZdenZ_{\mathrm{num}} \le Z_{\mathrm{den}} and F≤0F \le 0. Then eFe^F is the posterior probability of the reference under the model in which the denominator graph holds all transcripts. F=0F = 0 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. □\square

Remark (the extended Baum-Welch update). For discrete output distributions bp(v)b_p(v) and κ=1\kappa = 1, the derivative of FF with respect to ln⁡bp(v)\ln b_p(v) is cpnum(v)−cpden(v)c^{\mathrm{num}}_p(v) - c^{\mathrm{den}}_p(v), the difference of the counts of symbol vv under pdf pp; this follows from the theorem by the chain rule, because ℓt(p)=ln⁡bp(obst)\ell_t(p) = \ln b_p(\mathrm{obs}_t). The update

bp′(v)=cpnum(v)−cpden(v)+Dbp(v)∑v′(cpnum(v′)−cpden(v′)+Dbp(v′))b'_p(v) = \frac{c^{\mathrm{num}}_p(v) - c^{\mathrm{den}}_p(v) + D b_p(v)}{\sum_{v'} \left( c^{\mathrm{num}}_p(v') - c^{\mathrm{den}}_p(v') + D b_p(v') \right)}

keeps b′b' a distribution when DD makes every numerator positive. Gopalakrishnan, Kanevsky, Nádas and Nahamoo (1991) proved that for a large enough DD this update does not decrease a rational function such as eFe^F. 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 Θ(T(N+E))\Theta(T (N + E)) log_add operations, and line L5 and line L7 add Θ(T(N+P))\Theta(T (N + P)). Space is Θ(TN)\Theta(T N) for α\alpha and β\beta plus Θ(TP)\Theta(T P) 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 FF and its gradient exactly (a theorem).
  • A log posterior. If the denominator holds the numerator, F≤0F \le 0, and F=0F = 0 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. FF 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 gg 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 κ\kappa, DD 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 κ=1\kappa = 1 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 FF can be positive and is no longer a log posterior; add the reference to each lattice.
  • Too small DD. The EBW update can give negative probabilities or variances, or decrease FF. Set DD 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.

maximum_mutual_information_training.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. The extended Baum-Welch growth transform for rational objectives, the main theorem and its application to discrete HMM parameters
  4. 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.

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