Algorithm Search⌘K

Algorithmresearch

Lattice-free MMI

Also called LF-MMI, chain model training.

MMI training of neural acoustic models in which the denominator is a phone n-gram graph run on the GPU, so no lattices are needed.

Time
Θ(T (N + E + P)) worst
Space
Θ(T (N + P)) extra
Where
E = the number of its arcs; N = the number of states of the denominator graph; P = the number of pdfs; T = the number of frames of a chunk
Properties
deterministicexactofflineiterative
Origin
Daniel Povey, Vijayaditya Peddinti, Daniel Galvez, Pegah Ghahremani, Vimal Manohar, Xingyu Na, Yiming Wang, Sanjeev Khudanpur, 2016

Lattice-free MMI (LF-MMI) trains the neural network of an HMM-based recognizer directly with the MMI criterion, from a random start, with no cross-entropy training first. Classic MMI needs a word lattice of competing hypotheses for every utterance, generated by an earlier model. LF-MMI replaces all those lattices by one small graph: a phone n-gram language model composed with the HMM topology. The sum over all its paths is the denominator, for every utterance alike. The forward-backward pass over this graph runs on the GPU on short chunks of audio, in probability space with a scale per frame. Together with a topology that can be traversed in one frame and a frame rate reduced 3-fold, this makes sequence training about as cheap as frame-level training.

In plain words

To train a recognizer with MMI, you compare the score of the right phone sequence with the total score of all phone sequences. The old way listed the likely wrong sentences for each recording, which was slow and needed an older recognizer.

LF-MMI does not list them. It builds one small network of phones, where each phone can follow another with a probability learned from the training transcripts. Every phone sequence is a path through this network. For each short piece of audio, a fast pass over the network adds up the scores of all its paths. The training then pushes up the phone units of the right sequence and pushes down the units that the network as a whole prefers. Because the network is small and the same for every recording, the work runs well on a GPU.

The problem

The network reads the acoustic features and outputs, for each output frame t=1,…,Tt = 1, \ldots, T and each pdf pp (a tied HMM state), a number yt(p)y_t(p). LF-MMI uses yt(p)y_t(p) directly as a log likelihood: there is no division by the pdf priors and no acoustic scale. A training example is a chunk of audio with its phone sequence. The objective of one chunk is

F=ln⁡Znum−ln⁡Zden−c2∑t,pyt(p)2,F = \ln Z_{\mathrm{num}} - \ln Z_{\mathrm{den}} - \frac{c}{2} \sum_{t,p} y_t(p)^2,

where ZGZ_G sums, over the state paths of the graph GG, the product of the graph weights and eyt(pdf(qt))e^{y_t(\mathrm{pdf}(q_t))}. The numerator graph holds the paths of the reference phone sequence, and the denominator graph the paths of all phone sequences. The last term is an l2 penalty on the outputs. The task is to compute FF and ∂F/∂yt(p)\partial F / \partial y_t(p), which the network then backpropagates.

The topology. Each phone has a first state, entered once, and a loop state with a different pdf that may repeat. A phone can therefore take a single frame. The output frame rate is one third of the usual 100 frames per second.

The denominator graph. A phone language model, estimated from the phone alignments of the training data, is composed with the topology; every transition of the topology has probability 0.5. The initial probabilities come from running the graph for 100 steps from its start state and averaging the state distributions, so that a chunk may begin anywhere in an utterance. Every final probability is 1. The leaky HMM adds, at every frame, a small probability η\eta of jumping from any state to any state jj in proportion to init(j)\mathrm{init}(j), which lets a chunk recover from a bad start.

The numerator graph. It is the topology of the reference phone sequence, with each phone allowed to move up to 50 ms from its position in a reference alignment. In the code its weights are those of the same states and arcs of the denominator, so every numerator path is a denominator path and F≤0F \le 0.

The algorithm

⊕\oplus is log_add. All logs are natural logs. The numerator is small and uses log space. The denominator uses probabilities, divided at each frame by their sum ctc_t, as on a GPU.

  1. LF-MMI-GRADIENT(y, G_num, G_den, η, c) ▷ y: T × P network outputs
  2. 1(ln Z_num, γ^num) ← log-space forward-backward on G_num, with y = -∞ outside each phone's window
  3. 2m_t ← max over p of y_t(p); e_t(j) ← exp(y_t(pdf j) - m_t) for each state j of G_den
  4. 3a(j) ← init(j) e_1(j) at t = 1; a(j) ← (Σ over arcs i→j of α̂_{t-1}(i) w(i,j) + η init(j) Σ_i α̂_{t-1}(i)) e_t(j) for t ≥ 2
  5. 4c_t ← Σ_j a(j); α̂_t ← a / c_t
  6. 5ln Z_den ← Σ_t (ln c_t + m_t) + ln Σ_j α̂_T(j) final(j)
  7. 6β̂_T(j) ← final(j); β̂_t(i) ← (Σ over arcs i→j of w(i,j) e_{t+1}(j) β̂_{t+1}(j) + η Σ_j init(j) e_{t+1}(j) β̂_{t+1}(j)) / c_{t+1}
  8. 7γ^den_t(p) ← Σ over states j with pdf j = p of α̂_t(j) β̂_t(j) / Σ_j α̂_T(j) final(j)
  9. 8F ← ln Z_num - ln Z_den - (c/2) Σ y²; g_t(p) ← γ^num_t(p) - γ^den_t(p) - c y_t(p)
  10. 9return F and g

The leaky term in lines L3 and L6 costs O(N)O(N) per frame, the same as an arc from every state to every state would cost with a single shared target distribution. Povey et al. (2016) also add a second output layer trained with cross-entropy against the numerator posteriors, with weight 0.1, which this page does not treat further.

Example

Take two phones a and b, with pdfs a1, a2 (first and loop state of a) and b1, b2. The phone bigram is uniform: each phone follows each phone with probability 0.5, and a chunk starts with a or b with probability 0.5 each. From either state of a phone, the graph stays in its loop state with probability 0.5, or moves to the first state of a phone xx with 0.5⋅0.5=0.250.5 \cdot 0.5 = 0.25.

Initial probabilities. At step 0, the first states have 0.5 each. From step 1 on, each first state gets 0.250.25 (a quarter of the total mass) and each loop state gets 0.5⋅0.5=0.250.5 \cdot 0.5 = 0.25. Averaged over 100 steps, init=(0.2525,0.2475,0.2525,0.2475)\mathrm{init} = (0.2525, 0.2475, 0.2525, 0.2475) for (a1, a2, b1, b2).

One chunk. Let T=3T = 3, the reference "a b", and eyte^{y_t} as in this table:

frame a1 a2 b1 b2
1 0.6 0.1 0.2 0.1
2 0.2 0.3 0.4 0.1
3 0.1 0.1 0.3 0.5

The numerator has two paths in 3 frames: a1 b1 b2 and a1 a2 b1. Both have the graph weight 0.2525⋅0.25⋅0.50.2525 \cdot 0.25 \cdot 0.5, and the outputs give 0.6⋅0.4⋅0.5=0.120.6 \cdot 0.4 \cdot 0.5 = 0.12 and 0.6⋅0.3⋅0.3=0.0540.6 \cdot 0.3 \cdot 0.3 = 0.054. So Znum=0.2525⋅0.125⋅0.174=0.005491875Z_{\mathrm{num}} = 0.2525 \cdot 0.125 \cdot 0.174 = 0.005491875, and at frame 2 the numerator posterior is 0.690 for b1 and 0.310 for a2. The denominator sums over all paths: Zden=0.01597125Z_{\mathrm{den}} = 0.01597125 with η=0\eta = 0, so F=ln⁡(0.005491875/0.01597125)=−1.067521F = \ln(0.005491875 / 0.01597125) = -1.067521. With η=0.1\eta = 0.1, Zden=0.019400699Z_{\mathrm{den}} = 0.019400699 and F=−1.262039F = -1.262039. At frame 1, with η=0\eta = 0, the gradient is (+0.3834,−0.1007,−0.1897,−0.0930)(+0.3834, -0.1007, -0.1897, -0.0930): the numerator is surely in a1, while the denominator puts 0.6166 there. The tests check these numbers.

Correctness

The proof is in proofs/correctness.md. By induction on tt, the scaled forward values α^t\hat\alpha_t equal the true forward sums divided by ∏s≤tcsems\prod_{s \le t} c_s e^{m_s}, and the scaled backward values equal the true ones divided by ∏s>tcsems\prod_{s > t} c_s e^{m_s}. So line L5 is ln⁡Zden\ln Z_{\mathrm{den}}, and in line L7 the scale factors cancel and give the exact posteriors. The leaky jumps are arcs whose weights do not depend on yy, so they change ZZ but not the form of the gradient. The derivative of ln⁡Z\ln Z with respect to yt(p)y_t(p) is the posterior of pdf pp at frame tt, which gives line L8 (a theorem). When the numerator paths are denominator paths, F≤0F \le 0.

Proof: The scaled denominator recursion and the log-space numerator recursion give the LF-MMI objective and its exact gradientfull

We use the notation of the page. A graph has emitting states jj with pdf ids pdf(j)\mathrm{pdf}(j), arcs i→ji \to j with probabilities w(i,j)w(i, j), initial probabilities init(j)\mathrm{init}(j) and final probabilities final(j)\mathrm{final}(j). The frames are t=1,…,Tt = 1, \ldots, T, the network outputs are yt(p)y_t(p), and η≥0\eta \ge 0 is the leaky coefficient. Write et(j)=eyt(pdf(j))−mte_t(j) = e^{y_t(\mathrm{pdf}(j)) - m_t} with mt=max⁡pyt(p)m_t = \max_p y_t(p).

The leaky graph. Let wη(i,j)=w(i,j)+η init(j)w_\eta(i, j) = w(i, j) + \eta\, \mathrm{init}(j), the weight of the denominator graph with an extra arc from every state ii to every state jj of probability η init(j)\eta\, \mathrm{init}(j). For a graph with weights wηw_\eta, a path q1…qTq_1 \ldots q_T has the weight

init(q1)∏t=2Twη(qt−1,qt) final(qT)∏t=1Teyt(pdf(qt)),\mathrm{init}(q_1) \prod_{t=2}^{T} w_\eta(q_{t-1}, q_t)\, \mathrm{final}(q_T) \prod_{t=1}^{T} e^{y_t(\mathrm{pdf}(q_t))},

and ZZ is the sum of these weights. This is the ZZ of the page; for η=0\eta = 0 it is the plain graph.

Lemma 1 (the scaled forward pass). Let αt(j)\alpha_t(j) be the sum of the weights of the partial paths q1…qtq_1 \ldots q_t with qt=jq_t = j, without the final factor. Lines L3 and L4 give ct>0c_t > 0 and α^t\hat\alpha_t with

αt(j)=α^t(j)∏s=1tcsems,∑jα^t(j)=1.\alpha_t(j) = \hat\alpha_t(j) \prod_{s=1}^{t} c_s e^{m_s}, \qquad \sum_j \hat\alpha_t(j) = 1.

Proof. By induction on tt. At t=1t = 1, line L3 computes a(j)=init(j)e1(j)=α1(j)e−m1a(j) = \mathrm{init}(j) e_1(j) = \alpha_1(j) e^{-m_1}, and line L4 divides by c1=∑ja(j)c_1 = \sum_j a(j). For t≥2t \ge 2, a partial path that ends in jj is a partial path that ends in some ii followed by an arc i→ji \to j, so by distributivity

αt(j)=(∑i→jαt−1(i)w(i,j)+η init(j)∑iαt−1(i))et(j)emt.\alpha_t(j) = \Big( \sum_{i \to j} \alpha_{t-1}(i) w(i, j) + \eta\, \mathrm{init}(j) \sum_i \alpha_{t-1}(i) \Big) e_t(j) e^{m_t}.

Put in the induction hypothesis: the factor ∏s<tcsems\prod_{s < t} c_s e^{m_s} comes out of the bracket, and what is left is the value a(j)a(j) of line L3, computed from α^t−1\hat\alpha_{t-1}. Line L4 divides by ct=∑ja(j)c_t = \sum_j a(j). If ct=0c_t = 0, no partial path has positive weight, and the code raises an error. □\square

Corollary 1. ln⁡Z=∑t(ln⁡ct+mt)+ln⁡∑jα^T(j) final(j)\ln Z = \sum_t (\ln c_t + m_t) + \ln \sum_j \hat\alpha_T(j)\, \mathrm{final}(j), which is line L5. This follows from Lemma 1 at t=Tt = T and the definition of ZZ. The code never forms a product of TT probabilities, so the value does not underflow for long chunks: each ctc_t is a sum of ∑jα^t−1(j)=1\sum_j \hat\alpha_{t-1}(j) = 1 times weights and outputs of one frame only.

Lemma 2 (the scaled backward pass). Let βt(i)\beta_t(i) be the sum, over the suffixes qt+1…qTq_{t+1} \ldots q_T after qt=iq_t = i, of ∏τ>twη(qτ−1,qτ)eyτ(pdf(qτ))\prod_{\tau > t} w_\eta(q_{\tau-1}, q_\tau) e^{y_\tau(\mathrm{pdf}(q_\tau))} times final(qT)\mathrm{final}(q_T). Line L6 gives β^t\hat\beta_t with βt(i)=β^t(i)∏s>tcsems\beta_t(i) = \hat\beta_t(i) \prod_{s > t} c_s e^{m_s}.

Proof. By induction downwards. At t=Tt = T, β^T=final=βT\hat\beta_T = \mathrm{final} = \beta_T and the product is empty. For t<Tt < T, βt(i)=∑jwη(i,j)et+1(j)emt+1βt+1(j)\beta_t(i) = \sum_j w_\eta(i, j) e_{t+1}(j) e^{m_{t+1}} \beta_{t+1}(j), and ∑jη init(j)et+1(j)β^t+1(j)\sum_j \eta\, \mathrm{init}(j) e_{t+1}(j) \hat\beta_{t+1}(j) is the same for every ii, which is the term leak of the code. Dividing by ct+1c_{t+1} as in line L6 keeps the stated relation. □\square

Lemma 3 (posteriors). γtden(p)\gamma^{\mathrm{den}}_t(p) of line L7 is the posterior probability, under the distribution on the paths in proportion to their weights, that the path is in a state of pdf pp at frame tt.

Proof. The weight of the paths with qt=jq_t = j is αt(j)βt(j)\alpha_t(j) \beta_t(j). By Lemmas 1 and 2 this is α^t(j)β^t(j)∏s=1Tcsems\hat\alpha_t(j) \hat\beta_t(j) \prod_{s=1}^{T} c_s e^{m_s}, and by Corollary 1, Z=∏scsems∑jα^T(j)final(j)Z = \prod_s c_s e^{m_s} \sum_j \hat\alpha_T(j) \mathrm{final}(j). The common product cancels. □\square

The numerator. Line L1 runs the log-space forward-backward on the numerator graph, with yt(pdf(j))y_t(\mathrm{pdf}(j)) replaced by −∞-\infty at the frames outside the window of state jj. The same argument as in Lemmas 1 to 3, with log_add for ++ (see the proof on the MMI page), gives ln⁡Znum\ln Z_{\mathrm{num}} as the log of the weight of the paths that respect the windows, and γnum\gamma^{\mathrm{num}} as their posteriors.

Theorem. Line L8 returns

F=ln⁡Znum−ln⁡Zden−c2∑t,pyt(p)2,∂F∂yt(p)=γtnum(p)−γtden(p)−c yt(p).F = \ln Z_{\mathrm{num}} - \ln Z_{\mathrm{den}} - \frac{c}{2} \sum_{t,p} y_t(p)^2, \qquad \frac{\partial F}{\partial y_t(p)} = \gamma^{\mathrm{num}}_t(p) - \gamma^{\mathrm{den}}_t(p) - c\, y_t(p).

Proof. The value follows from the numerator paragraph and Corollary 1. In both graphs, the log weight of a path depends on yt(p)y_t(p) only by the term yt(pdf(qt))y_t(\mathrm{pdf}(q_t)), with coefficient 1 if pdf(qt)=p\mathrm{pdf}(q_t) = p and 0 otherwise; the arc weights, including the leaky arcs, do not depend on yy. So ∂ln⁡Z/∂yt(p)\partial \ln Z / \partial y_t(p) is the expected value of that coefficient, which is the posterior of Lemma 3 (or of the numerator paragraph). The derivative of the penalty is c yt(p)c\, y_t(p). □\square

Corollary 2. If the numerator weights are the weights of the same states and arcs of the denominator (as in the code), every numerator path that respects the windows is a denominator path with the same weight, and a positive η\eta only adds paths to the denominator. So Znum≤ZdenZ_{\mathrm{num}} \le Z_{\mathrm{den}}, and with c=0c = 0, F≤0F \le 0. For each frame, ∑p∂F/∂yt(p)=−c∑pyt(p)\sum_p \partial F / \partial y_t(p) = -c \sum_p y_t(p), since both posteriors sum to 1.

Complexity

Each frame visits every state and arc of the denominator graph once, forward and backward, and line L7 adds O(N+P)O(N + P), so a chunk costs Θ(T(N+E+P))\Theta(T (N + E + P)) operations; the numerator graph is much smaller. Space is Θ(TN)\Theta(T N) for the scaled tables and Θ(TP)\Theta(T P) for the posteriors. On Switchboard, Povey et al. (2016) report a denominator graph of about 24 thousand states and 220 thousand arcs. Its size is the same for every chunk, and the work for many chunks of 1.5 s runs in parallel on a GPU without log arithmetic.

Properties

  • Exact for the given graphs. The objective and gradient are exact; the approximations are in the choice of the graphs (a phone language model instead of words, chunks instead of utterances).
  • No lattices. The denominator does not depend on an earlier model, so there is no lattice generation and no stale lattice.
  • No prior division and no acoustic scale. The outputs are trained to be used as they are in decoding.
  • Sequence training from scratch. No cross-entropy model is needed first, although the cross-entropy output layer is kept as a regularizer.
  • Low frame rate. With one output every 30 ms and a topology that can be traversed in one frame, the network output layer and the decoder handle a third of the frames that a 10 ms rate needs.

Variants and improvements

  • Phone language model order. Povey et al. (2016) use a 4-gram, with no smoothing or pruning at and below the trigram level, keep 2000 4-gram states, and allow no backoff to lower orders. The code uses a bigram.
  • Regularization. Their recipe combines the cross-entropy output layer (weight 0.1), the l2 penalty on the outputs (c=0.0005c = 0.0005) and the leaky HMM (η=0.1\eta = 0.1).
  • LF-MMI followed by sMBR. A pass of lattice-based state-level minimum Bayes risk training after LF-MMI gave a further small gain on Switchboard.
  • End-to-end LF-MMI. Later work removed the alignments and the decision tree and trained with a full numerator graph, closer to CTC.

When to use it

Use it to train the acoustic model of a hybrid HMM recognizer with a decoding graph such as HCLG. On the Switchboard Hub5'00 set, Povey et al. (2016) report word error rates of 18.2% (cross-entropy), 16.9% (cross-entropy then sMBR), 15.5% (LF-MMI) and 15.1% (LF-MMI then sMBR), with 12.5%, 11.4%, 10.2% and 10.0% on its Switchboard part. That is about 15% relative better than cross-entropy and 8% better than cross-entropy followed by sMBR. Their Table 4 gives 4.28% on LibriSpeech and 11.2% on TED-LIUM.

Pitfalls

  • Underflow. The denominator recursion must be scaled at every frame (or run in log space). A product of hundreds of output probabilities underflows.
  • Chunk boundaries. A chunk starts in the middle of an utterance. Without the averaged initial probabilities and the final probabilities of 1, the first and last frames are forced into wrong states.
  • Over-fitting. Without the regularizers the outputs grow and the model over-fits; the l2 penalty and the cross-entropy output keep them in range.
  • Mismatched frame rates. The numerator windows, the topology and the decoding graph must all use the reduced frame rate.
  • Using the cross-entropy output in decoding. Decode with the chain output, not the regularizing one.

Implementations

The code takes the network outputs as given and computes the LF-MMI objective and gradient for small graphs, with a phone bigram, the averaged initial probabilities, the leaky HMM and the scaled denominator recursion; it does not train a network. The tests compare both recursions with a sum over all paths, the gradient with finite differences, and the scaled pass with the log-space pass on long chunks.

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.

lattice_free_mmi.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-free-mmi/. The authors are listed in prov/JBKG30.jsonl.

"""Lattice-free MMI (LF-MMI): the objective and gradient of the chain model.

The network gives y[t][p], one output per pdf and frame (at the reduced frame
rate). LF-MMI uses y directly as a log likelihood: there is no division by the
pdf priors and no acoustic scale. The objective of one chunk is

    F = ln Z_num - ln Z_den - (c / 2) * sum of y[t][p]^2,

where Z_num sums over the paths of the reference phone sequence (each phone
inside a window of frames around its position in a reference alignment) and
Z_den sums over the paths of a phone n-gram graph that is the same for every
chunk. The gradient is dF/dy[t][p] = gamma_num[t][p] - gamma_den[t][p] - c y[t][p].

Each phone has two pdfs: the pdf of its first frame and the pdf of its self
loop. The topology can be traversed in one frame. Here the phone language
model is a bigram; Povey et al. (2016) use a 4-gram. The numerator takes its
weights from the denominator graph, so that F <= 0.

The denominator forward-backward runs on probabilities with a scale per frame,
as on a GPU; the numerator runs in log space. All logs are natural logs.
"""

import math
from dataclasses import dataclass, field
from typing import Dict, List, Optional, 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. If window is
    given, state j may be occupied only at frames window[j][0]..window[j][1]."""

    pdf: List[int]
    arcs: List[Tuple[int, int, float]]
    init: Dict[int, float]
    final: Dict[int, float]
    window: Optional[List[Tuple[int, int]]] = None
    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 allowed(self, t: int, j: int) -> bool:
        return self.window is None or self.window[j][0] <= t <= self.window[j][1]


def first_pdf(phone: int) -> int:
    return 2 * phone


def loop_pdf(phone: int) -> int:
    return 2 * phone + 1


def numerator_graph(phones: Sequence[int], den: Graph, windows: Optional[Sequence[Tuple[int, int]]] = None) -> Graph:
    """The chain topology for a phone sequence. Phone k has a first state (pdf
    first_pdf) and a loop state (pdf loop_pdf); either may end the graph after the
    last phone. The weights are those of the same states and arcs of the
    denominator graph den (from denominator_graph), so every numerator path is a
    denominator path with the same score and F <= 0. windows[k] = (lo, hi) limits
    the frames of phone k."""
    den_arc = {(i, j): w for i, j, w in den.arcs}
    pdf: List[int] = []
    arcs: List[Tuple[int, int, float]] = []
    win: List[Tuple[int, int]] = []
    n = len(phones)
    for k, ph in enumerate(phones):
        f, s = 2 * k, 2 * k + 1
        pdf += [first_pdf(ph), loop_pdf(ph)]
        arcs += [(f, s, den_arc[(2 * ph, 2 * ph + 1)]), (s, s, den_arc[(2 * ph + 1, 2 * ph + 1)])]
        if k + 1 < n:
            nx = 2 * phones[k + 1]
            if (2 * ph, nx) not in den_arc:
                raise ValueError("the phone bigram does not allow this phone sequence")
            arcs += [(f, f + 2, den_arc[(2 * ph, nx)]), (s, f + 2, den_arc[(2 * ph + 1, nx)])]
        if windows is not None:
            win += [windows[k], windows[k]]
    if 2 * phones[0] not in den.init:
        raise ValueError("the first phone has no initial probability")
    final = {2 * n - 2: den.final[2 * phones[-1]], 2 * n - 1: den.final[2 * phones[-1] + 1]}
    return Graph(pdf, arcs, {0: den.init[2 * phones[0]]}, final, win if windows is not None else None)


def estimate_phone_bigram(sequences: Sequence[Sequence[int]], n_phones: int):
    """Unsmoothed bigram from phone sequences: (start[a], bigram[a][b]) as
    probabilities. A phone that is never followed by another gets a uniform row."""
    start = [0.0] * n_phones
    count = [[0.0] * n_phones for _ in range(n_phones)]
    for seq in sequences:
        start[seq[0]] += 1
        for a, b in zip(seq, seq[1:]):
            count[a][b] += 1
    start = [x / len(sequences) for x in start]
    bigram = []
    for row in count:
        s = sum(row)
        bigram.append([x / s for x in row] if s > 0 else [1.0 / n_phones] * n_phones)
    return start, bigram


def denominator_graph(start: Sequence[float], bigram: Sequence[Sequence[float]], steps: int = 100) -> Graph:
    """The phone bigram composed with the chain topology. State 2a is the first state
    of phone a and 2a+1 its loop state, so the state of a phone also remembers it as
    the history of the bigram. From either state of a, stay in the loop state with
    0.5, or go to the first state of b with 0.5 * bigram[a][b]. The initial
    probabilities are the average of the state distributions over the first `steps`
    frames, starting from start[]. Every final weight is 1."""
    P = len(bigram)
    pdf = [first_pdf(a) if j % 2 == 0 else loop_pdf(a) for a in range(P) for j in (0, 1)]
    prob_arcs: List[Tuple[int, int, float]] = []
    for a in range(P):
        for i in (2 * a, 2 * a + 1):
            prob_arcs.append((i, 2 * a + 1, 0.5))
            for b in range(P):
                if bigram[a][b] > 0:
                    prob_arcs.append((i, 2 * b, 0.5 * bigram[a][b]))
    dist = [0.0] * (2 * P)
    for a in range(P):
        dist[2 * a] = start[a]
    avg = [0.0] * (2 * P)
    for _ in range(steps):
        avg = [x + d / steps for x, d in zip(avg, dist)]
        nxt = [0.0] * (2 * P)
        for i, j, w in prob_arcs:
            nxt[j] += dist[i] * w
        dist = nxt
    arcs = [(i, j, math.log(w)) for i, j, w in prob_arcs]
    init = {j: math.log(x) for j, x in enumerate(avg) if x > 0}
    final = {j: 0.0 for j in range(2 * P)}
    return Graph(pdf, arcs, init, final)


def leaky_init(g: Graph) -> List[float]:
    """The initial probabilities of g as a list (0 for the states without one)."""
    return [math.exp(g.init[j]) if j in g.init else 0.0 for j in range(len(g.pdf))]


def forward_backward_log(g: Graph, y: Sequence[Sequence[float]]):
    """Log-space forward-backward (used for the numerator). Return (ln Z, gamma)."""
    T, n, P = len(y), len(g.pdf), len(y[0])
    emit = [[y[t][g.pdf[j]] if g.allowed(t, j) else NEG_INF 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]
    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()])
    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
    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)
    return log_z, gamma


def forward_backward_scaled(g: Graph, y: Sequence[Sequence[float]], leaky: float = 0.0):
    """Probability-space forward-backward with a scale per frame (used for the
    denominator). With leaky = eta > 0, each frame may also jump from any state to
    any state j with probability eta * init(j) (the leaky HMM). Return (ln Z, gamma)."""
    T, n, P = len(y), len(g.pdf), len(y[0])
    init = leaky_init(g)
    shift = [max(row) for row in y]
    e = [[math.exp(y[t][g.pdf[j]] - shift[t]) for j in range(n)] for t in range(T)]  # @line L2
    w_in = [[(i, math.exp(w)) for i, w in g.incoming[j]] for j in range(n)]
    w_out = [[(j, math.exp(w)) for j, w in g.outgoing[i]] for i in range(n)]
    final = [math.exp(g.final[j]) if j in g.final else 0.0 for j in range(n)]
    alpha = [[0.0] * n for _ in range(T)]
    c = [0.0] * T
    a = [init[j] * e[0][j] for j in range(n)]
    for t in range(T):
        if t > 0:
            total = math.fsum(alpha[t - 1])
            a = [(math.fsum(alpha[t - 1][i] * w for i, w in w_in[j]) + leaky * init[j] * total) * e[t][j] for j in range(n)]  # @line L3
        c[t] = math.fsum(a)
        if c[t] == 0.0:
            raise ValueError("the graph has no path of this length")
        alpha[t] = [x / c[t] for x in a]  # @line L4
    end = math.fsum(alpha[T - 1][j] * final[j] for j in range(n))
    if end == 0.0:
        raise ValueError("the graph has no path of this length")
    log_z = math.fsum(math.log(c[t]) + shift[t] for t in range(T)) + math.log(end)  # @line L5
    beta = [[0.0] * n for _ in range(T)]
    beta[T - 1] = final[:]
    for t in range(T - 2, -1, -1):
        nb = [e[t + 1][j] * beta[t + 1][j] for j in range(n)]
        leak = leaky * math.fsum(init[j] * nb[j] for j in range(n))
        beta[t] = [(math.fsum(w * nb[j] for j, w in w_out[i]) + leak) / c[t + 1] for i in range(n)]  # @line L6
    gamma = [[0.0] * P for _ in range(T)]
    for t in range(T):
        for j in range(n):
            gamma[t][g.pdf[j]] += alpha[t][j] * beta[t][j] / end  # @line L7
    return log_z, gamma


def lfmmi_objective_and_grad(y: Sequence[Sequence[float]], num: Graph, den: Graph, leaky: float = 0.1, l2: float = 0.0):
    """Return (F, grad, gamma_num, gamma_den) for one chunk."""
    lz_num, g_num = forward_backward_log(num, y)  # @line L1
    lz_den, g_den = forward_backward_scaled(den, y, leaky)
    T, P = len(y), len(y[0])
    F = lz_num - lz_den - 0.5 * l2 * math.fsum(v * v for row in y for v in row)  # @line L8
    grad = [[g_num[t][p] - g_den[t][p] - l2 * y[t][p] for p in range(P)] for t in range(T)]
    return F, grad, g_num, g_den  # @line L9


def lfmmi_objective(y, num, den, leaky: float = 0.1, l2: float = 0.0) -> float:
    return lfmmi_objective_and_grad(y, num, den, leaky, l2)[0]


# ---------------------------------------------------------------- reference versions for the tests


def with_leaky_arcs(g: Graph, leaky: float) -> Graph:
    """The same graph with an explicit arc i -> j of weight leaky * init(j) for every
    pair of states. It has the same Z as the leaky HMM."""
    if leaky <= 0:
        return g
    arcs = list(g.arcs)
    for i in range(len(g.pdf)):
        for j, w in g.init.items():
            arcs.append((i, j, math.log(leaky) + w))
    return Graph(list(g.pdf), arcs, dict(g.init), dict(g.final), g.window)


def brute_force_log_z(g: Graph, y: Sequence[Sequence[float]]) -> float:
    """ln Z by listing every path of T states. Only for small graphs."""
    T = len(y)
    terms: List[float] = []

    def walk(j: int, t: int, s: float) -> None:
        if not g.allowed(t, j):
            return
        s += y[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)
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_lattice_free_mmi.py 195 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-free-mmi/. The authors are listed in prov/JBKG30.jsonl.

import math
import random

import pytest

import nlslog
from lattice_free_mmi import (
    brute_force_log_z,
    denominator_graph,
    estimate_phone_bigram,
    forward_backward_log,
    forward_backward_scaled,
    leaky_init,
    lfmmi_objective,
    lfmmi_objective_and_grad,
    numerator_graph,
    with_leaky_arcs,
)
from nlslog import log_add

Q = [[0.6, 0.1, 0.2, 0.1], [0.2, 0.3, 0.4, 0.1], [0.1, 0.1, 0.3, 0.5]]


def example():
    den = denominator_graph([0.5, 0.5], [[0.5, 0.5], [0.5, 0.5]])
    num = numerator_graph([0, 1], den)
    y = [[math.log(v) for v in row] for row in Q]
    return y, num, den


def random_bigram(rng, P):
    start = [rng.random() + 0.1 for _ in range(P)]
    start = [x / sum(start) for x in start]
    bigram = []
    for _ in range(P):
        row = [rng.random() + 0.1 for _ in range(P)]
        bigram.append([x / sum(row) for x in row])
    return start, bigram


def random_outputs(rng, T, P, scale=2.0):
    return [[rng.uniform(-scale, scale) for _ in range(2 * P)] for _ in range(T)]


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_initial_probabilities_by_averaging():
    den = denominator_graph([0.5, 0.5], [[0.5, 0.5], [0.5, 0.5]])
    assert leaky_init(den) == pytest.approx([0.2525, 0.2475, 0.2525, 0.2475], abs=1e-12)
    rng = random.Random(1)
    start, bigram = random_bigram(rng, 4)
    init = leaky_init(denominator_graph(start, bigram))
    assert sum(init) == pytest.approx(1.0, abs=1e-12)
    # The graph is stochastic: the weights out of each state sum to 1.
    g = denominator_graph(start, bigram)
    for i in range(len(g.pdf)):
        assert math.fsum(math.exp(w) for _, w in g.outgoing[i]) == pytest.approx(1.0, abs=1e-12)


def test_page_example():
    y, num, den = example()
    lz_num, g_num = forward_backward_log(num, y)
    assert math.exp(lz_num) == pytest.approx(0.2525 * 0.125 * (0.12 + 0.054), abs=1e-15)
    assert g_num[1] == pytest.approx([0.0, 0.054 / 0.174, 0.12 / 0.174, 0.0], abs=1e-12)
    F, grad, _, g_den = lfmmi_objective_and_grad(y, num, den, leaky=0.0)
    assert math.exp(lz_num - F) == pytest.approx(0.01597125, abs=1e-12)
    assert F == pytest.approx(-1.067521, abs=1e-6)
    assert grad[0] == pytest.approx([0.3834, -0.1007, -0.1897, -0.0930], abs=1e-4)
    F, _, _, _ = lfmmi_objective_and_grad(y, num, den, leaky=0.1)
    assert math.exp(lz_num - F) == pytest.approx(0.019400699, abs=1e-9)
    assert F == pytest.approx(-1.262039, abs=1e-6)


def test_denominator_against_brute_force():
    rng = random.Random(2)
    for _ in range(12):
        P = rng.randint(1, 2)
        T = rng.randint(1, 4)
        start, bigram = random_bigram(rng, P)
        den = denominator_graph(start, bigram)
        y = random_outputs(rng, T, P)
        for leaky in (0.0, 0.1, 0.5):
            lz, gamma = forward_backward_scaled(den, y, leaky)
            assert lz == pytest.approx(brute_force_log_z(with_leaky_arcs(den, leaky), y), abs=1e-10)
            for t in range(T):
                assert sum(gamma[t]) == pytest.approx(1.0, abs=1e-12)


def test_scaled_and_log_forward_backward_agree():
    rng = random.Random(3)
    start, bigram = random_bigram(rng, 3)
    den = denominator_graph(start, bigram)
    for leaky in (0.0, 0.1):
        y = random_outputs(rng, 30, 3, scale=40.0)
        lz_s, g_s = forward_backward_scaled(den, y, leaky)
        lz_l, g_l = forward_backward_log(with_leaky_arcs(den, leaky), y)
        assert lz_s == pytest.approx(lz_l, rel=1e-12)
        for t in range(30):
            assert g_s[t] == pytest.approx(g_l[t], abs=1e-10)


def test_long_chunk_does_not_underflow():
    # 300 frames with outputs near -40: exp(-40 * 300) underflows, the scaled pass does not.
    rng = random.Random(4)
    start, bigram = random_bigram(rng, 2)
    den = denominator_graph(start, bigram)
    y = [[-40.0 + rng.uniform(-1, 1) for _ in range(4)] for _ in range(300)]
    lz_s, _ = forward_backward_scaled(den, y, 0.1)
    lz_l, _ = forward_backward_log(with_leaky_arcs(den, 0.1), y)
    assert math.isfinite(lz_s)
    assert lz_s == pytest.approx(lz_l, rel=1e-12)
    assert lz_s < -11000


def test_numerator_windows_against_brute_force():
    rng = random.Random(5)
    start, bigram = random_bigram(rng, 3)
    den = denominator_graph(start, bigram)
    for _ in range(20):
        T = rng.randint(2, 6)
        phones = [rng.randrange(3) for _ in range(rng.randint(1, min(3, T)))]
        windows = None
        if rng.random() < 0.6:
            windows = []
            for k in range(len(phones)):
                c = round((k + 0.5) * T / len(phones))
                windows.append((max(0, c - 2), min(T - 1, c + 1)))
        num = numerator_graph(phones, den, windows)
        y = random_outputs(rng, T, 3)
        bf = brute_force_log_z(num, y)
        if bf == -math.inf:
            with pytest.raises(ValueError):
                forward_backward_log(num, y)
            continue
        lz, gamma = forward_backward_log(num, y)
        assert lz == pytest.approx(bf, abs=1e-10)
        # Every numerator path is a denominator path with the same score.
        assert lz <= forward_backward_scaled(den, y, 0.0)[0] + 1e-12


def test_gradient_against_finite_differences():
    rng = random.Random(6)
    start, bigram = random_bigram(rng, 2)
    den = denominator_graph(start, bigram)
    h = 1e-6
    for leaky, l2 in ((0.0, 0.0), (0.1, 0.0005), (0.3, 0.1)):
        T = 5
        num = numerator_graph([0, 1, 1], den, [(0, 2), (1, 3), (2, 4)])
        y = random_outputs(rng, T, 2)
        F, grad, _, _ = lfmmi_objective_and_grad(y, num, den, leaky, l2)
        assert F <= 0
        for t in range(T):
            for p in range(4):
                up = [r[:] for r in y]
                dn = [r[:] for r in y]
                up[t][p] += h
                dn[t][p] -= h
                fd = (lfmmi_objective(up, num, den, leaky, l2) - lfmmi_objective(dn, num, den, leaky, l2)) / (2 * h)
                assert grad[t][p] == pytest.approx(fd, abs=1e-5)
            # Both posteriors sum to 1, so only the l2 term is left in the sum.
            assert sum(grad[t]) == pytest.approx(-l2 * sum(y[t]), abs=1e-12)


def test_estimate_phone_bigram():
    start, bigram = estimate_phone_bigram([[0, 1, 1], [1, 0], [0, 1]], 3)
    assert start == pytest.approx([2 / 3, 1 / 3, 0.0])
    assert bigram[0] == pytest.approx([0.0, 1.0, 0.0])
    assert bigram[1] == pytest.approx([0.5, 0.5, 0.0])
    assert bigram[2] == pytest.approx([1 / 3, 1 / 3, 1 / 3])
    den = denominator_graph(start, bigram)
    with pytest.raises(ValueError):
        numerator_graph([0, 0], den)  # the bigram gives 0 to a -> a
    with pytest.raises(ValueError):
        numerator_graph([2], den)  # phone 2 never starts a sequence and is never reached


def test_no_path_raises():
    y, num, den = example()
    short = numerator_graph([0, 1, 0, 1], den)
    with pytest.raises(ValueError):
        forward_backward_log(short, y)  # 4 phones need 4 frames
    windowed = numerator_graph([0, 1], den, [(0, 0), (0, 0)])
    with pytest.raises(ValueError):
        forward_backward_log(windowed, y)

History

MMI training with lattices became practical for large vocabulary recognition with Woodland and Povey (2002), and was later used to train the networks of hybrid models after cross-entropy training. Povey, Peddinti, Galvez, Ghahremani, Manohar, Na, Wang and Khudanpur (2016) removed the lattices by using a phone language model graph as the denominator, computed it on the GPU, and trained from scratch. The method is in the Kaldi toolkit under the name chain models.

References

  1. Daniel Povey, Vijayaditya Peddinti, Daniel Galvez, Pegah Ghahremani, Vimal Manohar, Xingyu Na, Yiming Wang and Sanjeev Khudanpur, Purely sequence-trained neural networks for ASR based on lattice-free MMI, Interspeech 2016, pages 2751 to 2755, the sections on the HMM topology and frame rate, the phone language model and denominator graph, the numerator, the denominator computation on the GPU, regularization, and the result tables (Switchboard Hub5'00 and Table 4)
  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 and lattice-based training (the method that LF-MMI replaces)

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
  • at least three sources
  • a scene preset for the example