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.
- Solves
- HMM decoding
- 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
- Evidence
- Proof sketchCode in 1 languages
- 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 time for frames and states, not the 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 (for example the MFCC vectors of 10 ms frames), a transcript , 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 states. The code numbers the frames and the states .
A path starts in state 0, ends in state , 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 . The task is
where is the log emission score, is the log self loop and is the log move. All logs are natural logs. The output is , its score, and the spans of the states, phones and words that 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 . A path is a segmentation of the frames into non-empty runs in order, so there are paths.
The algorithm
The arrays hold , and . Only the cells with , where and , are computed: a state above cannot be reached by frame , and a state below cannot reach state by the last frame.
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- 1
δ[0] ← e[0][0], δ[j] ← -∞ for j = 1 .. S - 1 - 2
for t ← 1 to T - 1 do ▷ fill δ' from δ, start with δ' = -∞, then set δ ← δ' - 3
for j ← lo_t to hi_t do - 4
stay ← δ[j] + a[j], move ← δ[j - 1] + m[j - 1] (move ← -∞ if j = 0) - 5
if move > stay then δ'[j] ← move + e[t][j], ψ_t[j] ← j - 1 ▷ a tie keeps the self loop - 6
else δ'[j] ← stay + e[t][j], ψ_t[j] ← j - 7
if δ[S - 1] = -∞ then error "every path has probability 0" - 8
q_{T-1} ← S - 1; for t ← T - 1 down to 1 do q_{t-1} ← ψ_t[q_t] - 9
return q_0 .. q_{T-1} and δ[S - 1]
The value after the pass for frame is the best log score of a path prefix that ends in state at frame . The back pointer 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 frames. To keep the table small, each phone has one state here, so . Every self loop and every move has probability 0.5. The emission probabilities are:
| frame | 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 after each frame, so the numbers are probabilities. The code stores their logs. A dot marks a cell outside .
| frame | 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 () or come from k (). The move is better, so 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 , or . 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 paths. The next best ones, k ae ae ae t t and k k ae t t t, both have the probability .
Correctness
The proof is in proofs/correctness.md. It is an induction on with the invariant that is the best score of a path prefix that ends in state at frame , for every in , and elsewhere. The last step of a prefix that ends in comes from or from , 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, , so 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 and there are frames, numbered to as in the code. Write for the log emission score of state at frame , for the log self loop of state and for the log move . All logs are natural logs.
A chain path to is a sequence with , and for . Its score is
A full path is a chain path to . Its score is of the chain HMM, up to the exit transition of the last state, which is the same constant for every full path. Let be the largest score of a chain path to , with if there is none.
Lemma 1 (which cells matter). A chain path to exists if and only if . It can be extended to a full path if and only if, in addition, .
Proof. Each step raises the state by at most 1, so , and any is reached by moving times and staying the rest. From , the remaining steps raise the state by at most , so is needed, and it is enough.
Write and , as in the code. Since , for every .
Lemma 2 (invariant). After line L1 (for ) and after the pass of line L2 for frame , for , and for every other . For and , the back pointer is a state with .
Proof. By induction on . For , the only chain path is , with score . Line L1 sets and the other entries to , and .
For , take with . The last step of a chain path to comes from or from . The score is additive along the path, so
with the second term absent for . We check that holds the correct values of these two predecessors. First, and, if , when , and otherwise. Second, because and . Third, unless ; in that case Lemma 1 gives , and the induction hypothesis gives . So line L4 computes the two terms with the correct values, lines L5 and L6 take the larger one, add and store the state that gives it. The entries outside stay , because the new array starts at .
Theorem. If some full path has a finite score, FORCED-ALIGN returns a full path with the largest score, and this score. Otherwise it raises an error at line L7.
Proof. At , , so by Lemma 2, at line L7. This is the largest score of a full path, and it is exactly when every full path has probability 0. The loop of line L8 follows the back pointers from . By Lemma 2, each pointer goes to a state with , and is a cell in the range of frame . By induction from down to , the suffix found so far has the property that the best chain path to followed by this suffix has the score . At the only chain path is , so the whole path has the score .
Proposition (tie rule). Among all full paths with the largest score, FORCED-ALIGN returns the one whose reversed sequence is the largest in lexicographic order. So, scanned from the end, each state keeps as many frames as an optimal path allows.
Proof. Let be that path and the returned path. Both end in . Assume that they agree on the frames , with , and let . A full path with this suffix is optimal if and only if its prefix is a best chain path to , because the score is additive. So is the largest state with . Line L5 picks the move only if the move is strictly better than the stay. So the pointer is whenever attains the maximum, and only when does not. That is the same choice, so .
Remark (rounding). In floating point, each addition is rounded, and rounding to nearest is monotone: implies . 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 frames whose terms are at least has a score of at least , 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 of a frame has at most cells, so the recursion makes steps. This is when , the usual case, and only when . The emission scores are a separate cost: evaluations of , each for a Gaussian mixture with components of dimension . In practice this term is larger than the recursion.
The array needs numbers. The back pointers need entries, one per cell, which is the space in the front matter. Each pointer is one of two values, so one bit per cell is enough. To use less memory, store at every -th frame only, and recompute the pointers of one block of frames at a time during the traceback. This needs memory and about twice the time.
Compare the general Viterbi algorithm, which takes time for states with a full transition matrix. The chain of the transcript has two arcs per state, so each cell looks at two predecessors, not .
Properties
- Exact for the model. The path has the highest 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 , 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 . 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.
# 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
- 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)
- 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
- Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall PTR, 2001, Chapter 8 (hidden Markov models)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 4HHCES Edit this page History Report an error Markdown