Algorithm Search⌘K

Algorithmcore

Forced alignment

Also called Viterbi forced alignment.

Find the time span of each word, phone and HMM state of a known transcript by a Viterbi search through the left-to-right HMM built from that transcript.

Time
Θ(T S) worst
Space
Θ(T S) extra
Where
S = the number of HMM states in the chain of the transcript; T = the number of frames
Properties
deterministicexactofflineiterative
Origin
Taras K. Vintsyuk, 1968

Forced alignment finds where each word, phone and HMM state of a known transcript starts and ends in an utterance. It builds one left-to-right hidden Markov model from the transcript and the pronunciation lexicon, and runs the Viterbi algorithm through it. Because each state has only a self loop and one forward arc, the search takes Θ(TS)\Theta(T S) time for TT frames and SS states, not the Θ(TS2)\Theta(T S^2) of a general HMM. It works in log space, because the product of the probabilities of a few hundred frames underflows in double precision.

In plain words

You have a recording and the exact words that were said. You want to know when each word and each sound starts. Write the sounds of the sentence in order, as a chain. Each sound must take at least one short slice of the recording, and the sounds must come in the order of the chain. Many ways to split the recording fit these rules.

The acoustic model gives a score for each sound on each slice. Forced alignment finds the split with the best total score. It walks through the slices one by one. For each sound in the chain, it keeps the best score of any split that ends with that sound at this slice. At the end it follows the stored choices back, and reads off the start and the end of each sound.

The problem

The input is a sequence of feature frames O=o1…oTO = o_1 \ldots o_T (for example the MFCC vectors of 10 ms frames), a transcript W=w1…wUW = w_1 \ldots w_U, a lexicon that gives each word a phone sequence, and an acoustic model with a left-to-right HMM of 3 emitting states for each phone. Concatenate the phone HMMs of the transcript into one chain of SS states. The code numbers the frames 0,…,T−10, \ldots, T-1 and the states 0,…,S−10, \ldots, S-1.

A path Q=q0…qT−1Q = q_0 \ldots q_{T-1} starts in state 0, ends in state S−1S - 1, and at each frame stays in its state or moves to the next one. There are no skips, so each state takes at least one frame, and a path exists only if T≥ST \ge S. The task is

Q∗=arg⁡max⁡Qlog⁡P(O,Q∣λW)=arg⁡max⁡Q(e0(q0)+∑t=1T−1(w(qt−1,qt)+et(qt))),Q^* = \arg\max_{Q} \log P(O, Q \mid \lambda_W) = \arg\max_Q \Big( e_0(q_0) + \sum_{t=1}^{T-1} \big( w(q_{t-1}, q_t) + e_t(q_t) \big) \Big),

where et(j)=log⁡bj(ot)e_t(j) = \log b_j(o_t) is the log emission score, w(j,j)=log⁡ajjw(j, j) = \log a_{jj} is the log self loop and w(j,j+1)=log⁡aj,j+1w(j, j+1) = \log a_{j, j+1} is the log move. All logs are natural logs. The output is Q∗Q^*, its score, and the spans of the states, phones and words that Q∗Q^* implies.

This page joins the phone models directly, without the non-emitting entry and exit states of the HTK convention. The exit transition of the last state is the same factor for every path, so it does not change Q∗Q^*. A path is a segmentation of the TT frames into SS non-empty runs in order, so there are (T−1S−1)\binom{T-1}{S-1} paths.

The algorithm

The arrays hold et(j)e_t(j), aj=log⁡ajja_j = \log a_{jj} and mj=log⁡aj,j+1m_j = \log a_{j, j+1}. Only the cells with lot≤j≤hitlo_t \le j \le hi_t, where lot=max⁡(0,S−T+t)lo_t = \max(0, S - T + t) and hit=min⁡(S−1,t)hi_t = \min(S - 1, t), are computed: a state above hithi_t cannot be reached by frame tt, and a state below lotlo_t cannot reach state S−1S-1 by the last frame.

  1. FORCED-ALIGN(e, a, m) ▷ e[t][j] = log b_j(o_t), a[j] = log self loop, m[j] = log move j → j + 1
  2. 1δ[0] ← e[0][0], δ[j] ← -∞ for j = 1 .. S - 1
  3. 2for t ← 1 to T - 1 do ▷ fill δ' from δ, start with δ' = -∞, then set δ ← δ'
  4. 3for j ← lo_t to hi_t do
  5. 4stay ← δ[j] + a[j], move ← δ[j - 1] + m[j - 1] (move ← -∞ if j = 0)
  6. 5if move > stay then δ'[j] ← move + e[t][j], ψ_t[j] ← j - 1 ▷ a tie keeps the self loop
  7. 6else δ'[j] ← stay + e[t][j], ψ_t[j] ← j
  8. 7if δ[S - 1] = -∞ then error "every path has probability 0"
  9. 8q_{T-1} ← S - 1; for t ← T - 1 down to 1 do q_{t-1} ← ψ_t[q_t]
  10. 9return q_0 .. q_{T-1} and δ[S - 1]

The value δ[j]\delta[j] after the pass for frame tt is the best log score of a path prefix that ends in state jj at frame tt. The back pointer ψt[j]\psi_t[j] records whether that prefix stayed or moved at the last step. The phone and word spans follow from the states: a phone spans the frames of its 3 states, and a word spans the frames of its phones.

Example

Align the word "cat", with the phones k, ae and t, to T=6T = 6 frames. To keep the table small, each phone has one state here, so S=3S = 3. Every self loop and every move has probability 0.5. The emission probabilities bj(ot)b_j(o_t) are:

frame tt 0 1 2 3 4 5
k 0.8 0.6 0.2 0.1 0.1 0.1
ae 0.1 0.3 0.7 0.6 0.2 0.1
t 0.1 0.1 0.1 0.3 0.7 0.8

The table below gives exp⁡(δ)\exp(\delta) after each frame, so the numbers are probabilities. The code stores their logs. A dot marks a cell outside lot…hitlo_t \ldots hi_t.

frame tt 0 1 2 3 4 5
k 0.8 0.24 0.024 0.0012 · ·
ae · 0.12 0.084 0.0252 0.00252 ·
t · · 0.006 0.0126 0.00882 0.003528

For example, at frame 2 the state ae can stay (0.12⋅0.5=0.060.12 \cdot 0.5 = 0.06) or come from k (0.24⋅0.5=0.120.24 \cdot 0.5 = 0.12). The move is better, so δ=0.12⋅0.7=0.084\delta = 0.12 \cdot 0.7 = 0.084 and the back pointer is k. At frame 4 the state k is skipped: from k, two frames are not enough to pass through ae and reach t.

The final score is 0.0035280.003528, or log⁡0.003528=−5.647024\log 0.003528 = -5.647024. The back pointers from (frame 5, t) give the path k k ae ae t t, so k spans frames 0 to 1, ae frames 2 to 3 and t frames 4 to 5. There are (52)=10\binom{5}{2} = 10 paths. The next best ones, k ae ae ae t t and k k ae t t t, both have the probability 0.0017640.001764.

Correctness

The proof is in proofs/correctness.md. It is an induction on tt with the invariant that δ[j]\delta[j] is the best score of a path prefix that ends in state jj at frame tt, for every jj in lot…hitlo_t \ldots hi_t, and −∞-\infty elsewhere. The last step of a prefix that ends in jj comes from jj or from j−1j - 1, and the score is a sum along the path, so lines L4 to L6 compute the best prefix from the two best shorter prefixes. At the last frame, loT−1=hiT−1=S−1lo_{T-1} = hi_{T-1} = S - 1, so δ[S−1]\delta[S-1] is the best full score, and the back pointers give a path with that score.

The tie rule of line L5 picks one path among the optimal ones: the path whose reversed state sequence is the largest in lexicographic order. Read from the end, each state keeps as many frames as an optimal path allows. The proof also shows that in floating point the code returns the exact maximum of the rounded path scores, because rounding to nearest is monotone.

Proof: Forced alignment returns a best path of the transcript chainfull

We use the notation of the page. The chain has the states 0,1,…,S−10, 1, \ldots, S-1 and there are T≥ST \ge S frames, numbered 00 to T−1T-1 as in the code. Write et(j)e_t(j) for the log emission score of state jj at frame tt, aja_j for the log self loop of state jj and mjm_j for the log move j→j+1j \to j+1. All logs are natural logs.

A chain path to (t,j)(t, j) is a sequence q0,…,qtq_0, \ldots, q_t with q0=0q_0 = 0, qt=jq_t = j and qu−qu−1∈{0,1}q_u - q_{u-1} \in \{0, 1\} for u=1,…,tu = 1, \ldots, t. Its score is

score(q)=e0(0)+∑u=1t(w(qu−1,qu)+eu(qu)),w(i,i)=ai,w(i,i+1)=mi.\mathrm{score}(q) = e_0(0) + \sum_{u=1}^{t} \big( w(q_{u-1}, q_u) + e_u(q_u) \big), \qquad w(i, i) = a_i, \quad w(i, i+1) = m_i.

A full path is a chain path to (T−1,S−1)(T-1, S-1). Its score is log⁡P(O,Q∣λ)\log P(O, Q \mid \lambda) of the chain HMM, up to the exit transition of the last state, which is the same constant for every full path. Let V(t,j)V(t, j) be the largest score of a chain path to (t,j)(t, j), with V(t,j)=−∞V(t, j) = -\infty if there is none.

Lemma 1 (which cells matter). A chain path to (t,j)(t, j) exists if and only if 0≤j≤t0 \le j \le t. It can be extended to a full path if and only if, in addition, j≥S−T+tj \ge S - T + t.

Proof. Each step raises the state by at most 1, so qt≤tq_t \le t, and any j≤min⁡(t,S−1)j \le \min(t, S-1) is reached by moving jj times and staying the rest. From (t,j)(t, j), the T−1−tT - 1 - t remaining steps raise the state by at most T−1−tT - 1 - t, so S−1≤j+T−1−tS - 1 \le j + T - 1 - t is needed, and it is enough. □\square

Write lot=max⁡(0,S−T+t)lo_t = \max(0, S - T + t) and hit=min⁡(S−1,t)hi_t = \min(S-1, t), as in the code. Since T≥ST \ge S, lot≤hitlo_t \le hi_t for every tt.

Lemma 2 (invariant). After line L1 (for t=0t = 0) and after the pass of line L2 for frame t≥1t \ge 1, δ[j]=V(t,j)\delta[j] = V(t, j) for lot≤j≤hitlo_t \le j \le hi_t, and δ[j]=−∞\delta[j] = -\infty for every other jj. For lot≤j≤hitlo_t \le j \le hi_t and t≥1t \ge 1, the back pointer ψt(j)\psi_t(j) is a state ii with V(t,j)=V(t−1,i)+w(i,j)+et(j)V(t, j) = V(t-1, i) + w(i, j) + e_t(j).

Proof. By induction on tt. For t=0t = 0, the only chain path is q0=0q_0 = 0, with score e0(0)e_0(0). Line L1 sets δ[0]=e0(0)\delta[0] = e_0(0) and the other entries to −∞-\infty, and lo0=hi0=0lo_0 = hi_0 = 0.

For t≥1t \ge 1, take jj with lot≤j≤hitlo_t \le j \le hi_t. The last step of a chain path to (t,j)(t, j) comes from (t−1,j)(t-1, j) or from (t−1,j−1)(t-1, j-1). The score is additive along the path, so

V(t,j)=max⁡(V(t−1,j)+aj, V(t−1,j−1)+mj−1)+et(j),V(t, j) = \max\big( V(t-1, j) + a_j,\ V(t-1, j-1) + m_{j-1} \big) + e_t(j),

with the second term absent for j=0j = 0. We check that δ\delta holds the correct values of these two predecessors. First, j≥lot≥lot−1j \ge lo_t \ge lo_{t-1} and, if j≥1j \ge 1, j−1≥lot−1≥lot−1j - 1 \ge lo_t - 1 \ge lo_{t-1} when lot−1>0lo_{t-1} > 0, and j−1≥0=lot−1j - 1 \ge 0 = lo_{t-1} otherwise. Second, j−1≤hit−1j - 1 \le hi_{t-1} because j−1≤t−1j - 1 \le t - 1 and j−1≤S−1j - 1 \le S - 1. Third, j≤hit−1j \le hi_{t-1} unless j=tj = t; in that case Lemma 1 gives V(t−1,j)=−∞V(t-1, j) = -\infty, and the induction hypothesis gives δ[j]=−∞\delta[j] = -\infty. So line L4 computes the two terms with the correct values, lines L5 and L6 take the larger one, add et(j)e_t(j) and store the state that gives it. The entries outside lot…hitlo_t \ldots hi_t stay −∞-\infty, because the new array starts at −∞-\infty. □\square

Theorem. If some full path has a finite score, FORCED-ALIGN returns a full path QQ with the largest score, and this score. Otherwise it raises an error at line L7.

Proof. At t=T−1t = T - 1, loT−1=hiT−1=S−1lo_{T-1} = hi_{T-1} = S - 1, so by Lemma 2, δ[S−1]=V(T−1,S−1)\delta[S-1] = V(T-1, S-1) at line L7. This is the largest score of a full path, and it is −∞-\infty exactly when every full path has probability 0. The loop of line L8 follows the back pointers from (T−1,S−1)(T-1, S-1). By Lemma 2, each pointer goes to a state ii with V(t,j)=V(t−1,i)+w(i,j)+et(j)V(t, j) = V(t-1, i) + w(i, j) + e_t(j), and i∈{j−1,j}i \in \{j-1, j\} is a cell in the range of frame t−1t-1. By induction from t=T−1t = T-1 down to t=1t = 1, the suffix qt,…,qT−1q_t, \ldots, q_{T-1} found so far has the property that the best chain path to (t,qt)(t, q_t) followed by this suffix has the score V(T−1,S−1)V(T-1, S-1). At t=0t = 0 the only chain path is q0=0q_0 = 0, so the whole path has the score V(T−1,S−1)V(T-1, S-1). □\square

Proposition (tie rule). Among all full paths with the largest score, FORCED-ALIGN returns the one whose reversed sequence (qT−1,qT−2,…,q0)(q_{T-1}, q_{T-2}, \ldots, q_0) is the largest in lexicographic order. So, scanned from the end, each state keeps as many frames as an optimal path allows.

Proof. Let Q∗Q^* be that path and QQ the returned path. Both end in S−1S-1. Assume that they agree on the frames t,…,T−1t, \ldots, T-1, with t≥1t \ge 1, and let j=qtj = q_t. A full path with this suffix is optimal if and only if its prefix is a best chain path to (t,j)(t, j), because the score is additive. So qt−1∗q^*_{t-1} is the largest state i∈{j−1,j}i \in \{j-1, j\} with V(t−1,i)+w(i,j)=V(t,j)−et(j)V(t-1, i) + w(i, j) = V(t, j) - e_t(j). Line L5 picks the move only if the move is strictly better than the stay. So the pointer is jj whenever jj attains the maximum, and j−1j - 1 only when jj does not. That is the same choice, so qt−1=qt−1∗q_{t-1} = q^*_{t-1}. □\square

Remark (rounding). In floating point, each addition is rounded, and rounding to nearest is monotone: x≤yx \le y implies fl(x+c)≤fl(y+c)\mathrm{fl}(x + c) \le \mathrm{fl}(y + c). The code adds the terms of a path in the same order as the left fold in the definition of the score. Lemma 2 and the theorem then hold word for word with the score replaced by its rounded left fold, so the code returns the exact maximum of the rounded path scores. The values are sums of logs, not products of probabilities, so they do not underflow: a path of TT frames whose terms are at least −c-c has a score of at least −cT-cT, which is far inside the range of a double.

Complexity

In the floating-point model, each cell of lines L4 to L6 costs a constant number of additions and comparisons. The band lot…hitlo_t \ldots hi_t of a frame has at most min⁡(S,T−S+1)\min(S, T - S + 1) cells, so the recursion makes O(Tmin⁡(S,T−S+1))O(T \min(S, T - S + 1)) steps. This is Θ(TS)\Theta(T S) when T≥2ST \ge 2S, the usual case, and only Θ(T)\Theta(T) when T=ST = S. The emission scores are a separate cost: TST S evaluations of log⁡bj(ot)\log b_j(o_t), each O(Md)O(M d) for a Gaussian mixture with MM components of dimension dd. In practice this term is larger than the recursion.

The array δ\delta needs Θ(S)\Theta(S) numbers. The back pointers need Θ(TS)\Theta(T S) entries, one per cell, which is the Θ(TS)\Theta(T S) space in the front matter. Each pointer is one of two values, so one bit per cell is enough. To use less memory, store δ\delta at every T\sqrt{T}-th frame only, and recompute the pointers of one block of frames at a time during the traceback. This needs O(ST)O(S \sqrt{T}) memory and about twice the time.

Compare the general Viterbi algorithm, which takes Θ(TN2)\Theta(T N^2) time for NN states with a full transition matrix. The chain of the transcript has two arcs per state, so each cell looks at two predecessors, not NN.

Properties

  • Exact for the model. The path has the highest P(O,Q∣λW)P(O, Q \mid \lambda_W) among all paths of the chain. It is not the most accurate segmentation in any other sense; its boundaries are only as good as the acoustic model.
  • Log space. The test aligns 200 frames whose plain product of probabilities is 0.0 in double precision, and the log version recovers the planted boundaries. Scaling (Rabiner 1989, Section V.A) also works for the forward sum, but log space is the simple choice for a maximum.
  • A minimum duration. Without skips, each state takes at least one frame, so a phone with 3 states takes at least 3 frames, which is 30 ms at a 10 ms frame step.
  • A fixed tie rule. Ties keep the self loop, so later states get as many frames as an optimal path allows.

Variants and improvements

  • Optional silence and alternative pronunciations. Add an optional silence model between words, and parallel branches for words with more than one pronunciation. The chain becomes a directed acyclic graph of states per frame, and the same recursion runs over the predecessors of each state, in topological order of the graph. This is what recognizers do in practice.
  • Beam pruning. Keep only the cells within a fixed log score of the best cell at each frame. This saves time on long utterances, but it is no longer exact.
  • Neural acoustic scores. A hybrid DNN-HMM gives state posteriors. Dividing by the state priors gives scaled likelihoods, and the alignment is unchanged.
  • CTC alignment. A CTC model aligns with the same kind of chain, with a blank between the labels.
  • Soft alignment. The forward-backward algorithm on the same chain gives the posterior of each state at each frame, in place of one best path. Baum-Welch training uses these posteriors; Viterbi training uses the forced alignment.
  • Explicit durations. A hidden semi-Markov model replaces the geometric durations of the self loops by explicit duration distributions, at a higher cost.

When to use it

Use forced alignment when the words are known and you need their times. It segments the training data of HMM recognizers, which is the alignment step of Viterbi training. It also gives phone labels for corpus phonetics, durations for speech synthesis, and word times for subtitles. If the words are not known, use a decoder with a language model instead.

Pitfalls

  • A wrong transcript. A missing word, a repeated word or a hesitation that is not in the transcript forces the frames onto the wrong phones, and the error spreads to the neighbors. Add optional silence and filler models, and check alignments with a very low score per frame.
  • Too few frames. If T<ST < S, no path exists. Fast speech and short words with many states can cause this.
  • Products of probabilities. A product over a few hundred frames underflows to 0 in double precision, and then every path looks the same. Add logs.
  • A large negative number for log 0. Use −∞-\infty. A finite stand-in can make an impossible path look possible after many additions.
  • Missing words in the lexicon. A word with no pronunciation stops the alignment. Use grapheme-to-phoneme conversion for such words.

Implementations

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.

forced_alignment.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/forced-alignment/. The authors are listed in prov/4HHCES.jsonl.

"""Forced alignment: Viterbi through the left-to-right HMM of a known transcript.

The transcript w_1 ... w_U is expanded with a pronunciation lexicon into phones,
and each phone into its emitting HMM states (3 by default, no skips). The result
is one chain of S states, numbered 0..S-1 in the code. A path must start in
state 0 at frame 0, end in state S-1 at frame T-1, and at each frame either stay
in its state (self loop) or move to the next state.

The acoustic model is outside this file: the caller gives log_emit[t][j], the
log emission score log b_j(o_t) of chain state j at frame t (a Gaussian mixture
log density, or a scaled network output). The code works in log space, so a
long utterance does not underflow. Non-emitting entry and exit states (the HTK
convention) are left out: the exit transition of the last state is the same
for every path and does not change the best path.

Tie rule: when staying and moving give the same score, the path stays (line L5).
"""

from typing import Dict, List, Sequence, Tuple

from nlslog import NEG_INF, safe_log


def expand_transcript(words: Sequence[str], lexicon: Dict[str, Sequence[Sequence[str]]], states_per_phone: int = 3):
    """Return one label per chain state: (word index, word, phone index, phone, state index).

    The first pronunciation of each word in the lexicon is used. Raise KeyError
    for a word that is not in the lexicon.
    """
    labels = []
    for u, w in enumerate(words):
        phones = lexicon[w][0]
        for p, ph in enumerate(phones):
            for s in range(states_per_phone):
                labels.append((u, w, p, ph, s))
    return labels


def forced_align(log_emit: Sequence[Sequence[float]], log_self: Sequence[float], log_next: Sequence[float]):
    """Return (path, score): the best state path of the chain and its log score.

    log_emit is T x S. log_self[j] is the log self-loop probability of state j,
    log_next[j] the log probability of the move j -> j + 1 (log_next[S-1] is
    not used). Raise ValueError if T < S (no path) or every path scores -inf.
    Cost: O(T S) time and O(T S) memory for the back pointers.
    """
    T = len(log_emit)
    S = len(log_self)
    if S == 0 or T < S:
        raise ValueError("need at least one frame per state")
    delta = [NEG_INF] * S
    delta[0] = log_emit[0][0]  # @line L1
    back: List[List[int]] = [[0] * S]
    for t in range(1, T):  # @line L2
        new = [NEG_INF] * S
        ptr = [0] * S
        lo = max(0, S - (T - t))  # states that can still reach S-1 by the end
        hi = min(S - 1, t)  # states that can be reached by frame t
        for j in range(lo, hi + 1):  # @line L3
            stay = delta[j] + log_self[j]  # @line L4
            move = delta[j - 1] + log_next[j - 1] if j > 0 else NEG_INF
            if move > stay:  # @line L5: a tie keeps the self loop
                new[j], ptr[j] = move + log_emit[t][j], j - 1  # @line L6
            else:
                new[j], ptr[j] = stay + log_emit[t][j], j
        delta = new
        back.append(ptr)
    score = delta[S - 1]  # @line L7
    if score == NEG_INF:
        raise ValueError("every path has probability 0")
    path = [S - 1]
    for t in range(T - 1, 0, -1):  # @line L8
        path.append(back[t][path[-1]])
    path.reverse()
    return path, score  # @line L9


def segments(path: Sequence[int], labels: Sequence[Tuple], level: str = "phone"):
    """Turn a state path into spans (label, start, end) with frames start <= t < end.

    level is "state", "phone" or "word". A phone span is keyed by (word index,
    phone index), so two equal phones in a row stay two spans.
    """
    if level == "state":
        key = lambda j: (j,)
        name = lambda j: labels[j]
    elif level == "phone":
        key = lambda j: labels[j][:3]
        name = lambda j: labels[j][3]
    elif level == "word":
        key = lambda j: labels[j][:1]
        name = lambda j: labels[j][1]
    else:
        raise ValueError("level must be state, phone or word")
    out = []
    start = 0
    for t in range(1, len(path) + 1):
        if t == len(path) or key(path[t]) != key(path[start]):
            out.append((name(path[start]), start, t))
            start = t
    return out


def align_transcript(words, lexicon, log_b, T, self_loop=0.5, states_per_phone=3, level="phone"):
    """Align a transcript to T frames.

    log_b(t, phone, state) is the log emission score of the given phone state at
    frame t. Every state has the same self-loop probability. Return (spans, score).
    """
    labels = expand_transcript(words, lexicon, states_per_phone)
    S = len(labels)
    log_emit = [[log_b(t, labels[j][3], labels[j][4]) for j in range(S)] for t in range(T)]
    ls = [safe_log(self_loop)] * S
    ln = [safe_log(1 - self_loop)] * S
    path, score = forced_align(log_emit, ls, ln)
    return segments(path, labels, level), score
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_forced_alignment.py 319 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/forced-alignment/. The authors are listed in prov/4HHCES.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

import nlslog
from forced_alignment import align_transcript, expand_transcript, forced_align, segments
from nlslog import (
    BOOLEAN,
    COUNTING,
    LOG,
    LOG_COST,
    NEG_INF,
    POS_INF,
    PROB,
    TROPICAL,
    VITERBI,
    argmax,
    log_add,
    log_normalize,
    log_softmax,
    log_sum,
    safe_log,
    softmax,
    sr_prod,
    sr_sum,
)

# ---------------------------------------------------------------- the shared helper nlslog.py


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_safe_log():
    assert safe_log(0) == NEG_INF
    assert safe_log(1) == 0.0
    assert safe_log(F(1, 2)) == pytest.approx(math.log(0.5), abs=1e-15)
    with pytest.raises(ValueError):
        safe_log(-0.1)


def test_log_add_check_value():
    v = log_add(math.log(0.5), math.log(0.25))
    assert v == pytest.approx(math.log(0.75), abs=1e-12)
    assert round(v, 6) == -0.287682


def test_log_add_edges():
    assert log_add(NEG_INF, NEG_INF) == NEG_INF
    assert log_add(NEG_INF, -3.0) == -3.0
    assert log_add(-3.0, NEG_INF) == -3.0
    assert log_add(-1000.0, -1000.0) == pytest.approx(-1000.0 + math.log(2), abs=1e-12)
    assert log_add(1000.0, 999.0) == pytest.approx(1000.0 + math.log1p(math.exp(-1.0)), abs=1e-9)
    assert log_add(POS_INF, 0.0) == POS_INF


def test_log_sum():
    assert log_sum([]) == NEG_INF
    assert log_sum([NEG_INF, NEG_INF]) == NEG_INF
    assert log_sum([-1000.0] * 1000) == pytest.approx(-1000.0 + math.log(1000), abs=1e-9)
    rng = random.Random(1)
    xs = [rng.uniform(-5, 5) for _ in range(20)]
    assert log_sum(xs) == pytest.approx(math.log(sum(math.exp(x) for x in xs)), abs=1e-12)
    acc = NEG_INF
    for x in xs:
        acc = log_add(acc, x)
    assert acc == pytest.approx(log_sum(xs), abs=1e-12)


def test_log_normalize_and_log_softmax():
    xs = [math.log(3.0), math.log(1.0), NEG_INF]
    ys = log_normalize(xs)
    assert [math.exp(y) for y in ys] == pytest.approx([0.75, 0.25, 0.0], abs=1e-15)
    assert sum(math.exp(y) for y in log_softmax([2.0, 1.0, 0.0])) == pytest.approx(1.0, abs=1e-15)
    assert log_softmax([-2000.0, -2001.0]) == pytest.approx(log_normalize([0.0, -1.0]), abs=1e-12)
    with pytest.raises(ValueError):
        log_normalize([NEG_INF, NEG_INF])


def test_softmax_temperature_check_values():
    assert softmax([2, 1, 0]) == pytest.approx([0.66524, 0.24473, 0.09003], abs=5e-6)
    assert softmax([2, 1, 0], temperature=0.5) == pytest.approx([0.86681, 0.11731, 0.01588], abs=5e-6)
    assert softmax([2, 1, 0], temperature=2) == pytest.approx([0.50648, 0.30720, 0.18632], abs=5e-6)
    assert softmax([1000.0, 999.0, NEG_INF]) == pytest.approx(softmax([1.0, 0.0])[:2] + [0.0], abs=1e-15)
    with pytest.raises(ValueError):
        softmax([1.0], temperature=0)


def test_argmax_first_on_ties():
    assert argmax([1, 3, 3, 2]) == 1
    assert argmax([NEG_INF, NEG_INF]) == 0
    assert argmax([F(1, 3), F(2, 3), F(2, 3)]) == 1
    with pytest.raises(ValueError):
        argmax([])


SAMPLES = {
    "probability": [0, 1, F(1, 2), F(1, 3), F(5, 4)],
    "log": [NEG_INF, 0.0, -0.5, -2.0, 1.25],
    "viterbi": [NEG_INF, 0.0, -0.5, -2.0, 1.25],
    "tropical": [POS_INF, 0.0, 0.5, 2.0, -1.25],
    "log-cost": [POS_INF, 0.0, 0.5, 2.0, -1.25],
    "boolean": [False, True],
    "counting": [0, 1, 2, 3, 7],
}


def same(a, b):
    if isinstance(a, float) and isinstance(b, float):
        if math.isinf(a) or math.isinf(b):
            return a == b
        return abs(a - b) <= 1e-12 * max(1.0, abs(a), abs(b))
    return a == b


@pytest.mark.parametrize("sr", [PROB, LOG, VITERBI, TROPICAL, LOG_COST, BOOLEAN, COUNTING], ids=lambda s: s.name)
def test_semiring_axioms(sr):
    xs = SAMPLES[sr.name]
    for a in xs:
        assert same(sr.plus(a, sr.zero), a)
        assert same(sr.plus(sr.zero, a), a)
        assert same(sr.times(a, sr.one), a)
        assert same(sr.times(sr.one, a), a)
        assert same(sr.times(a, sr.zero), sr.zero)
        assert same(sr.times(sr.zero, a), sr.zero)
        if sr.idempotent:
            assert same(sr.plus(a, a), a)
        for b in xs:
            assert same(sr.plus(a, b), sr.plus(b, a))
            for c in xs:
                assert same(sr.plus(sr.plus(a, b), c), sr.plus(a, sr.plus(b, c)))
                assert same(sr.times(sr.times(a, b), c), sr.times(a, sr.times(b, c)))
                assert same(sr.times(a, sr.plus(b, c)), sr.plus(sr.times(a, b), sr.times(a, c)))
                assert same(sr.times(sr.plus(a, b), c), sr.plus(sr.times(a, c), sr.times(b, c)))
    if not sr.idempotent:
        assert any(not same(sr.plus(a, a), a) for a in xs)


def test_semirings_agree_on_one_sum():
    ps = [F(1, 2), F(1, 4), F(1, 8)]
    assert sr_sum(PROB, ps) == F(7, 8)
    assert sr_prod(PROB, ps) == F(1, 64)
    assert sr_sum(LOG, [math.log(p) for p in ps]) == pytest.approx(math.log(7 / 8), abs=1e-12)
    assert sr_sum(VITERBI, [math.log(p) for p in ps]) == pytest.approx(math.log(0.5), abs=1e-15)
    assert sr_sum(TROPICAL, [-math.log(p) for p in ps]) == pytest.approx(-math.log(0.5), abs=1e-15)
    assert sr_sum(LOG_COST, [-math.log(p) for p in ps]) == pytest.approx(-math.log(7 / 8), abs=1e-12)
    assert sr_prod(LOG, [math.log(p) for p in ps]) == pytest.approx(math.log(1 / 64), abs=1e-12)
    assert sr_sum(BOOLEAN, [False, True]) is True
    assert sr_prod(BOOLEAN, [True, False]) is False
    assert sr_sum(COUNTING, [2, 3]) == 5
    assert sr_sum(LOG, []) == NEG_INF
    assert sr_prod(TROPICAL, []) == 0.0


# ---------------------------------------------------------------- forced alignment


def compositions(T, S):
    """All ways to give S states durations >= 1 that sum to T."""
    if S == 1:
        yield (T,)
        return
    for d in range(1, T - S + 2):
        for rest in compositions(T - d, S - 1):
            yield (d,) + rest


def path_of(durs):
    return [j for j, d in enumerate(durs) for _ in range(d)]


def path_score(path, log_emit, log_self, log_next):
    s = log_emit[0][path[0]]
    for t in range(1, len(path)):
        i, j = path[t - 1], path[t]
        s += (log_self[i] if i == j else log_next[i]) + log_emit[t][j]
    return s


def random_chain(rng, T, S):
    log_emit = [[math.log(rng.uniform(0.01, 1.0)) for _ in range(S)] for _ in range(T)]
    ps = [rng.uniform(0.1, 0.9) for _ in range(S)]
    return log_emit, [math.log(p) for p in ps], [math.log(1 - p) for p in ps]


def test_number_of_segmentations():
    from math import comb

    for T in range(1, 9):
        for S in range(1, T + 1):
            assert sum(1 for _ in compositions(T, S)) == comb(T - 1, S - 1)


def test_against_brute_force():
    rng = random.Random(7)
    for _ in range(150):
        S = rng.randint(1, 4)
        T = rng.randint(S, 8)
        le, ls, ln = random_chain(rng, T, S)
        path, score = forced_align(le, ls, ln)
        best = max(compositions(T, S), key=lambda d: path_score(path_of(d), le, ls, ln))
        assert score == pytest.approx(path_score(path_of(best), le, ls, ln), abs=1e-9)
        assert path_score(path, le, ls, ln) == pytest.approx(score, abs=1e-9)
        assert path == path_of(best)
        assert path[0] == 0 and path[-1] == S - 1
        assert all(path[t] - path[t - 1] in (0, 1) for t in range(1, T))


def test_tie_keeps_the_self_loop():
    le = [[0.0, 0.0]] * 3
    ls = [math.log(0.5)] * 2
    path, score = forced_align(le, ls, ls)
    # Both paths score 2 log 0.5; the traceback stays, so the last state keeps more frames.
    assert path == [0, 1, 1]
    assert score == pytest.approx(2 * math.log(0.5), abs=1e-12)
    # Exact ties in integers: the rule gives the optimum whose reversed path is largest.
    rng = random.Random(2)
    for _ in range(100):
        S = rng.randint(1, 3)
        T = rng.randint(S, 7)
        le = [[float(rng.randint(-2, 0)) for _ in range(S)] for _ in range(T)]
        ls = [-1.0] * S
        ln = [-1.0] * S
        path, score = forced_align(le, ls, ln)
        best = max(compositions(T, S), key=lambda d: (path_score(path_of(d), le, ls, ln), path_of(d)[::-1]))
        assert path == path_of(best)


def test_errors():
    with pytest.raises(ValueError):
        forced_align([[0.0, 0.0]], [0.0, 0.0], [0.0, 0.0])
    with pytest.raises(ValueError):
        forced_align([[0.0, NEG_INF], [0.0, NEG_INF]], [0.0, 0.0], [0.0, 0.0])


LEX = {"a": [["ah"], ["ey"]], "cat": [["k", "ae", "t"]], "sat": [["s", "ae", "t"]]}


def test_expand_and_segments():
    labels = expand_transcript(["a", "cat"], LEX, states_per_phone=2)
    assert [l[3] for l in labels] == ["ah", "ah", "k", "k", "ae", "ae", "t", "t"]
    path = [0, 1, 1, 2, 3, 4, 4, 5, 6, 7]
    assert segments(path, labels, "word") == [("a", 0, 3), ("cat", 3, 10)]
    assert segments(path, labels, "phone") == [("ah", 0, 3), ("k", 3, 5), ("ae", 5, 8), ("t", 8, 10)]
    assert len(segments(path, labels, "state")) == 8
    with pytest.raises(KeyError):
        expand_transcript(["dog"], LEX)


def planted(rng, phones, durs, sd=0.3):
    """Frames from a 1-D Gaussian per phone, with the phone durations given."""
    means = {ph: float(i) for i, ph in enumerate(sorted(set(phones)))}
    xs = []
    for ph, d in zip(phones, durs):
        xs += [rng.gauss(means[ph], sd) for _ in range(d)]
    return xs, means


def gauss_log(x, m, sd):
    return -0.5 * math.log(2 * math.pi * sd * sd) - (x - m) ** 2 / (2 * sd * sd)


def test_recovers_planted_boundaries():
    rng = random.Random(3)
    words = ["a", "cat", "sat"]
    phones = ["ah", "k", "ae", "t", "s", "ae", "t"]
    durs = [9, 6, 12, 5, 8, 10, 7]
    xs, means = planted(rng, phones, durs, sd=0.1)
    spans, _ = align_transcript(words, LEX, lambda t, ph, s: gauss_log(xs[t], means[ph], 0.1), len(xs), states_per_phone=1)
    ends = [e for _, _, e in spans]
    assert [p for p, _, _ in spans] == phones
    assert ends == [sum(durs[: i + 1]) for i in range(len(durs))]
    wspans, _ = align_transcript(words, LEX, lambda t, ph, s: gauss_log(xs[t], means[ph], 0.1), len(xs), states_per_phone=1, level="word")
    assert wspans == [("a", 0, 9), ("cat", 9, 32), ("sat", 32, 57)]


def naive_product_align(log_emit, log_self, log_next):
    """The same recursion with plain products of probabilities (no logs)."""
    T, S = len(log_emit), len(log_self)
    d = [math.exp(log_emit[0][0])] + [0.0] * (S - 1)
    for t in range(1, T):
        d = [max(d[j] * math.exp(log_self[j]), d[j - 1] * math.exp(log_next[j - 1]) if j else 0.0) * math.exp(log_emit[t][j]) for j in range(S)]
    return d[S - 1]


def test_long_utterance_underflows_without_logs():
    rng = random.Random(11)
    words = ["cat", "sat"]
    phones = ["k", "ae", "t", "s", "ae", "t"]
    durs = [30, 40, 25, 35, 40, 30]  # 200 frames
    xs, means = planted(rng, phones, durs, sd=0.2)
    # A discrete-like score: each frame gets probability at most 0.02.
    def log_b(t, ph, s):
        return math.log(0.02) + gauss_log(xs[t], means[ph], 0.2) - gauss_log(means[ph], means[ph], 0.2)

    labels = expand_transcript(words, LEX, 1)
    le = [[log_b(t, l[3], l[4]) for l in labels] for t in range(len(xs))]
    ls = [math.log(0.9)] * len(labels)
    ln = [math.log(0.1)] * len(labels)
    assert naive_product_align(le, ls, ln) == 0.0
    path, score = forced_align(le, ls, ln)
    assert score > -1500 and math.isfinite(score)
    spans = segments(path, labels, "phone")
    assert [e for _, _, e in spans] == [sum(durs[: i + 1]) for i in range(len(durs))]


def test_one_state_per_frame_is_forced():
    rng = random.Random(5)
    le, ls, ln = random_chain(rng, 4, 4)
    path, _ = forced_align(le, ls, ln)
    assert path == [0, 1, 2, 3]

History

Vintsyuk 1968 matched speech against word templates by dynamic programming, the same recursion that Viterbi published in 1967 for convolutional codes. When HMMs became the standard acoustic model, the Viterbi search through the HMM of a known transcript became the usual way to segment training data and to label speech corpora (Rabiner 1989; Gales and Young 2008).

References

  1. Lawrence R. Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition, Proceedings of the IEEE 77(2), 1989, pages 257 to 286, Section III.B (the Viterbi algorithm) and Section V.A (scaling)
  2. Mark Gales and Steve Young, The application of hidden Markov models in speech recognition, Foundations and Trends in Signal Processing 1(3), 2008, pages 195 to 304, the chapters on the architecture of an HMM-based recognizer and on parameter estimation
  3. Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall PTR, 2001, Chapter 8 (hidden Markov models)
  4. T. K. Vintsyuk, Speech discrimination by dynamic programming, Cybernetics 4(1), 1968, pages 52 to 57 (Kibernetika 4(1), pages 81 to 88, in Russian), the dynamic programming alignment of an utterance with word templates

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