Algorithmadvanced
Connectionist temporal classification
Also called CTC, CTC loss.
A loss for unaligned sequences that sums over all frame labelings with blanks and repeats collapsing to the target, by forward-backward.
- Time
- Θ(T (U + K)) worst
- Space
- Θ(T U) extra
- Where
- K = the number of output symbols with the blank; T = the number of frames; U = the length of the label sequence
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alex Graves, Santiago Fernández, Faustino Gomez, Jürgen Schmidhuber, 2006
Connectionist temporal classification (CTC) trains a network that reads frames and must output a shorter label sequence , when nobody has marked which frame belongs to which label. The network outputs, at each frame, a distribution over the labels and one extra symbol, the blank. The probability of is the sum over all frame-level paths that become after merging repeats and deleting blanks. A forward-backward recursion on the sequence with blanks inserted computes this sum in steps and its gradient with respect to the outputs in , although the number of paths grows exponentially in . The loss is in nats.
In plain words
A speech network looks at many short slices of sound, but the word "cat" has only three letters. CTC lets the network say one thing for each slice: a letter, or a special "nothing here" symbol called the blank. To read the result, you merge letters that repeat next to each other and then delete the blanks. So "cc_aaa_t" and "c_a__tt" both read as "cat".
Many slice-by-slice outputs read as "cat". The training goal is to make the total probability of all of them large. Listing them is impossible, but a table with one row per slice and one column per position in "c_a_t" adds them up quickly, like counting paths through a grid. The same table, run from both ends, tells each slice how to change its output.
The problem
The input is a matrix of network outputs for frames and symbols of the alphabet , with symbols in all. The blank is written in formulas, "_" in examples and index 0 in the code. The output distribution of frame is . The model assumes that the outputs of different frames are independent given the input . This is an assumption of the model, not a property of speech.
A path is a sequence , with . The map first merges each run of equal symbols into one and then deletes the blanks, so . The order matters: blanks first would turn "a_a" into "a", but . For a label sequence over ,
The task is to compute and its gradient with respect to every . Two copies of the same label need a blank between them, so a path exists only if , where is the number of adjacent repeats in . Otherwise the loss is .
The algorithm
Insert a blank before, between and after the labels: , with states. A path moves through from left to right. At each frame it stays, moves one state, or skips one blank, and it may skip a blank only if the two labels on its sides differ. The forward variable sums the path prefixes that are in state at frame and includes . The backward variable sums the suffixes after frame and does not include . The arrays store natural logs; is log_add, so .
CTC-LOSS(u, l) ▷ u: T × K logits, l = l_1 .. l_U, ∅ = index 0, ln is the natural log- 1
ln y_t ← log-softmax(u_t) for every t; l' ← ∅ l_1 ∅ l_2 .. ∅ l_U ∅, S ← 2U + 1 - 2
α_1(1) ← ln y_1(∅), α_1(2) ← ln y_1(l_1), α_1(s) ← -∞ for s ≥ 3 - 3
for t ← 2 to T do for s ← 1 to S do - 4
a ← α_{t-1}(s) ⊕ α_{t-1}(s - 1); if l'_s ≠ ∅ and l'_s ≠ l'_{s-2} then a ← a ⊕ α_{t-1}(s - 2) - 5
α_t(s) ← a + ln y_t(l'_s) - 6
ln p ← α_T(S) ⊕ α_T(S - 1) - 7
β_T(S) ← β_T(S - 1) ← 0, else -∞; β_t(s) ← ⊕ over s' ∈ {s, s + 1, s + 2 if allowed} of (β_{t+1}(s') + ln y_{t+1}(l'_{s'})) - 8
g_t(k) ← y_t(k) - exp( ⊕_{s : l'_s = k} (α_t(s) + β_t(s)) - ln p ) for every t and k - 9
return -ln p and g
Line L4 is the whole structure of CTC. A path in state at frame was in (a repeat of the same symbol), in (one step), or in (a skip over a blank). The skip is not allowed into a blank, and it is not allowed between two equal labels, because "aa" without a blank between would merge into one "a". A path must start in the first blank or the first label (line L2) and end in the last label or the last blank (line L6).
Line L8 is the gradient of the loss with respect to the logits, . This form holds with defined without frame , as here. Graves et al. (2006) put inside their , so their eq. (16) has an extra factor in the sum; the two forms are equal.
Example
Take the alphabet {_, a, b}, the target "ab" and frames with these outputs:
| frame | _ | a | b |
|---|---|---|---|
| 1 | 0.5 | 0.4 | 0.1 |
| 2 | 0.4 | 0.3 | 0.3 |
| 3 | 0.3 | 0.1 | 0.6 |
The extended sequence is $l' = $ _ a _ b _. Exactly 5 paths of length 3 collapse to "ab": ab (0.09), a_b (0.096), aab (0.072), ab (0.036) and abb (0.072), so . The forward table, in probabilities (the code stores the logs), gets the same number without listing the paths:
| _ | a | _ | b | _ | |
|---|---|---|---|---|---|
| 0.5 | 0.4 | 0 | 0 | 0 | |
| 0.2 | 0.27 | 0.16 | 0.12 | 0 | |
| 0.06 | 0.047 | 0.129 | 0.33 | 0.036 |
For example, : the path may skip the blank from a to b because a and b differ. The answer is , and the loss is nats. The gradient for frame 1 is for (_, a, b): the loss falls if the network raises "a" at frame 1.
The example also shows that greedy decoding is not the same as finding the most probable labeling. The best symbol of each frame is _, _ and b, which reads "b", with . But "ab" has . Every single path of "ab" is less likely than the greedy path _ _ b (0.12), yet their sum is larger.
Correctness
The proof is in proofs/correctness.md. It first shows that the paths with are in one-to-one correspondence with the state sequences through that obey the start, step, skip and end rules of lines L2, L4 and L6. Then an induction on shows that sums the valid prefixes that end in , and a downward induction does the same for and the suffixes. So is the total probability of the paths in state at frame , and for every . The gradient follows from the chain rule through the softmax, with for .
Proof: The CTC forward-backward pass computes p(l | x) and the gradient of the lossfull
We use the notation of the page, with frames and states (the code counts both from 0). The blank is . The label sequence is with no blank in it, and the extended sequence is , so , for odd and . The output of frame is . The proofs work with probabilities; the code stores their natural logs, and (log_add) in log space is on probabilities, so the same statements hold for the stored values.
A path is a sequence of symbols, with probability . The map merges each run of equal symbols into one symbol and then deletes the blanks. By definition .
Paths and state sequences
Call a state skippable to if , and . An admissible state sequence is with , (only at both ends when ), and each step equal to 0 or 1, or equal to 2 when is skippable to.
Lemma 1. The map with is a bijection from the admissible state sequences onto the paths with .
Proof. Take an admissible and set . A step of 2 always lands on an even state and skips the odd state , so no even state is skipped. Since starts at 1 or 2 and ends at or , it visits each even state , each on a block of consecutive frames, in this order. The path is a run of , a run of , and so on, with blank runs between some of them. Two label runs with no blank run between them come from a step of 2, so their symbols differ, and the runs do not merge. So maps each label run to one symbol, deletes the blank runs, and gives .
Conversely, take with and cut it into maximal runs of equal symbols. Merging gives one symbol per run, and deleting the blank runs leaves , so the non-blank runs are, in order, runs of . Map the frames of the -th label run to state , the frames of a blank run between label runs and to state , a leading blank run to state 1 and a trailing blank run to state . The result is admissible: the steps inside a run are 0, a step into or out of a blank run is 1, and two adjacent label runs and give a step of 2, where because two adjacent maximal runs hold different symbols. This construction is the inverse of the first map, because the state of each frame is fixed by the run that holds the frame.
So , summed over the admissible state sequences. In particular, a path exists if and only if an admissible exists, which needs one frame for each label and one more frame for each blank state between two equal labels, that is , where is the number of indices with .
The forward and backward variables
Lemma 2 (forward). After lines L2 to L5, equals the sum, over the prefixes that satisfy the start rule and the step rule and end with , of .
Proof. By induction on . For the prefixes are and , which line L2 sets, and every other state gets 0. For , the last step of a prefix that ends in comes from , from , or from when is skippable to. These sets of prefixes are disjoint, and every prefix of each set is the extension of a prefix that ends at frame . The weight is a product, so the sum factors as (\alpha_{t-1}(s) + \alpha_{t-1}(s-1) + [\text{s$ skippable to}],\alpha_{t-1}(s-2)), y_t(l'_s)$, which is lines L4 and L5.
Lemma 3 (backward). After line L7 and its loop, equals the sum, over the suffixes such that followed by the suffix satisfies the step rule and ends in , of . The factor is not included.
Proof. By induction on downward. For the suffix is empty, its product is 1, and it is valid exactly when , which line L7 sets. For , split by , where is allowed only when it is skippable to. This gives over the allowed , which is the code.
Theorem 1. (only when ), so line L6 gives . Moreover, for every frame and state , is the total probability of the paths of that are in state at frame , and .
Proof. The first claim is Lemma 2 at with the end rule, and Lemma 1. For the second, an admissible with is a valid prefix ending in followed by a valid suffix from , and every such pair gives an admissible . The product over frames splits into the prefix part, which includes , and the suffix part, which does not, so the sum is . Each admissible is in exactly one state at frame , so summing over gives .
The gradient
Theorem 2. Let . Then
which is line L8. The log is the natural log.
Proof. By Theorem 1 and Lemma 1, is the sum of over the paths of with . Each such product holds the factor exactly once, and the products of the other paths of do not depend on . Treating the as free variables, . The softmax gives , and affects no other frame. By the chain rule,
because by Theorem 1. Change the sign.
Remark (the convention of Graves et al. 2006). Their backward variable includes the factor , so . Their eq. (16) therefore reads with . It is the same quantity as Theorem 2.
Corollary. For each frame, . The tests check this, and they check Theorem 2 against central finite differences of the loss.
Log space and rounding
The code stores and and adds probabilities with log_add, which computes . No exponential of a large number is formed, and every stored value is a log of a sum of path probabilities, which is at least the log of one path probability. If each output satisfies , a stored value is at least , so for any realistic it is far inside the range of a double, while the product of the probabilities itself would underflow. We do not give a bound on the rounding error of the log-space sums. The tests compare the code with exact enumeration and with exact path counts.
Complexity
The softmax and the gradient cost per frame. The forward and backward passes cost a constant number of log_add operations per cell, and there are cells. The total is operations. Only the cells that lie on some complete path matter. They form a band whose width grows with the slack , so a banded implementation saves time when is close to .
The and tables take numbers; the gradient output itself takes . To compute only the loss, keep one column of , which takes memory. In practice a batch of utterances runs on a GPU, and the sequential steps of the recursion, not the arithmetic, limit the speed.
A product of a few hundred probabilities underflows in double precision. The test with , 30 equally likely symbols and the target "ab" has . The forward pass in probabilities returns 0.0, and the log-space pass returns , the exact value to 9 digits. Graves et al. (2006) rescale and at each frame instead, which also works. This is why the page uses the floating-point model.
Properties
- Exact sum. The forward pass gives exactly in exact arithmetic (a theorem; see Correctness). It is the forward algorithm of a left-to-right HMM with states whose emissions are the network outputs.
- Conditional independence. The model treats the frames as independent given the input. A label can depend on the acoustic context through the network, but not on the other output labels. This is why CTC needs an external language model for good word accuracy, and why the RNN transducer adds a prediction network.
- Monotone alignment. Every path reads the labels in order, so CTC cannot model reordering. For speech this is right.
- Peaky outputs. A trained CTC network outputs the blank on most frames and each label on one or a few frames. This is an observation about trained models, not a theorem.
- Gradient sums to zero per frame. Because softmax ignores a shift of its inputs, for every frame.
- Best path is not best labeling. Greedy decoding takes the best symbol of each frame and applies . It finds the labeling of the most probable path, which is not in general the most probable labeling (Graves et al. 2006, Section 3.2); see the Example. CTC prefix beam search sums over the paths of each prefix.
Variants and improvements
- Decoding. Greedy (best path) decoding, prefix search (Graves et al. 2006), and prefix beam search with a language model (Hannun et al. 2014). A WFST decoder can also compose a CTC "token" transducer with a lexicon and a grammar, in the style of the HCLG graph.
- Viterbi alignment. Replace by in lines L4 and L6 (the Viterbi semiring of nlslog). With traceback this gives the best path, a forced alignment of the labels to the frames.
- Joint CTC-attention. Add the CTC loss to an attention encoder-decoder as an auxiliary loss, and combine the scores in decoding (joint CTC-attention).
- Fine-tuning pretrained encoders. wav2vec 2.0 fine-tunes its pretrained encoder with a CTC loss on characters.
- RNN transducer. The RNN transducer removes the independence assumption with a prediction network over the previous labels, at the cost of a lattice per joint output.
When to use it
Use CTC when the input is much longer than the output, the order is monotone, and no alignment is given: speech recognition, handwriting recognition, and keyword spotting. It is simple, it trains fast, and greedy decoding is cheap and can run frame by frame. If the output labels depend strongly on each other, or if the outputs are words or long subwords, an attention model or a transducer usually gives a lower error rate without a language model. In many systems CTC is an auxiliary loss on the encoder of such a model.
Pitfalls
- Too few frames. If , no path exists and the loss is infinite. Subsampling the frames by 4 or 8 can cause this for fast speech or for character targets. Check the lengths, or drop such utterances.
- The blank index. The code here uses 0. Some toolkits use the last index. A mismatch trains a model that cannot output one of the labels.
- The order of the collapse. Merge repeats first, then delete blanks. The other order maps "a_a" to "a" and is wrong.
- Products of probabilities. Without log space or rescaling the forward pass underflows after a few hundred frames.
- The two forms of the gradient. Mixing the of Graves et al. (with ) and the of this page (without ) gives a gradient that is off by a factor . Test against finite differences.
- Gradient with respect to what. The formula of line L8 is the gradient with respect to the logits . With respect to it is . Do not apply a second softmax derivative on top of line L8.
Implementations
The code takes the per-frame output logits of the network as given and implements the CTC loss, its gradient and greedy decoding; it does not train a network. A generic forward pass takes any semiring of nlslog, so the same code computes (probability), (log), the best path (Viterbi) and the number of paths (counting).
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/connectionist-temporal-classification/. The authors are listed in prov/7KBK03.jsonl.
"""Connectionist temporal classification (CTC): the loss, its gradient and greedy decoding.
A network gives, at each of T frames, logits u[t][k] over K symbols. Symbol 0
is the blank, written ∅ in the formulas of the page and "_" in its examples.
The symbols 1..K-1 are the labels. A path is one symbol per frame. The collapse
map B removes repeated symbols first and blanks second, so B("aa_ab_") = "aab".
The probability of a label sequence l is the sum, over all paths pi with
B(pi) = l, of the product of y_t(pi_t), where y_t = softmax(u_t).
The code follows Graves et al. (2006), Section 4, in log space. alpha_t(s)
includes the output of frame t. beta_t(s) here does NOT include the output of
frame t, so alpha_t(s) + beta_t(s) is the log of the total probability of the
paths that are in state s at frame t, and the gradient of -log p with respect
to u_t(k) is y_t(k) - (1/p) sum over s with l'_s = k of alpha_t(s) beta_t(s).
Graves defines beta with y_t inside, which puts an extra 1/y_t(k) in his
eq. (16).
Frames and states are numbered from 0 in the code and from 1 on the page.
The code takes the network outputs as given. It does not train a network.
All logs are natural logs.
"""
import itertools
import math
from typing import List, Sequence, Tuple
from nlslog import NEG_INF, POS_INF, Semiring, argmax, log_add, log_softmax, log_sum
BLANK = 0
def collapse(path: Sequence[int], blank: int = BLANK) -> Tuple[int, ...]:
"""The map B: merge runs of equal symbols, then drop blanks."""
out = []
prev = None
for k in path:
if k != prev and k != blank:
out.append(k)
prev = k
return tuple(out)
def extend_labels(labels: Sequence[int], blank: int = BLANK) -> List[int]:
"""Return l' = blank, l_1, blank, l_2, ..., l_U, blank, of length 2U + 1."""
ext = [blank]
for k in labels:
if k == blank:
raise ValueError("a label sequence may not hold the blank")
ext += [k, blank]
return ext
def min_frames(labels: Sequence[int]) -> int:
"""The fewest frames that can produce l: |l| plus the number of adjacent repeats."""
return len(labels) + sum(1 for i in range(1, len(labels)) if labels[i] == labels[i - 1])
def _can_skip(ext: Sequence[int], s: int, blank: int) -> bool:
"""True if a path may jump from state s - 2 to state s (skip the blank between)."""
return s >= 2 and ext[s] != blank and ext[s] != ext[s - 2]
def ctc_forward(sr: Semiring, weights: Sequence[Sequence], labels: Sequence[int], blank: int = BLANK):
"""The forward sum in any semiring: the semiring sum, over paths with B(path) = l,
of the semiring product of weights[t][path_t].
With PROB and probabilities it gives p(l | x), with LOG and log probabilities
it gives log p(l | x), with VITERBI it gives the log probability of the best
path, and with COUNTING and weights of 1 it counts the paths.
"""
ext = extend_labels(labels, blank)
S = len(ext)
T = len(weights)
if T == 0:
return sr.one if S == 1 else sr.zero
a = [sr.zero] * S
a[0] = weights[0][ext[0]]
if S > 1:
a[1] = weights[0][ext[1]]
for t in range(1, T):
new = [sr.zero] * S
for s in range(S):
acc = a[s]
if s >= 1:
acc = sr.plus(acc, a[s - 1])
if _can_skip(ext, s, blank):
acc = sr.plus(acc, a[s - 2])
new[s] = sr.times(acc, weights[t][ext[s]])
a = new
return a[S - 1] if S == 1 else sr.plus(a[S - 1], a[S - 2])
def log_alpha(log_y: Sequence[Sequence[float]], ext: Sequence[int], blank: int = BLANK) -> List[List[float]]:
"""alpha[t][s]: log of the summed probability of the path prefixes 0..t that
are in state s of l' at frame t and can be read as the start of l. Includes y_t."""
T, S = len(log_y), len(ext)
alpha = [[NEG_INF] * S for _ in range(T)]
alpha[0][0] = log_y[0][ext[0]] # @line L2
if S > 1:
alpha[0][1] = log_y[0][ext[1]]
for t in range(1, T): # @line L3
prev = alpha[t - 1]
for s in range(S):
acc = prev[s] # @line L4
if s >= 1:
acc = log_add(acc, prev[s - 1])
if _can_skip(ext, s, blank):
acc = log_add(acc, prev[s - 2])
alpha[t][s] = acc + log_y[t][ext[s]] # @line L5
return alpha
def log_beta(log_y: Sequence[Sequence[float]], ext: Sequence[int], blank: int = BLANK) -> List[List[float]]:
"""beta[t][s]: log of the summed probability of the frames t+1..T-1 for paths
that are in state s at frame t and end in one of the two last states. Does
NOT include y_t."""
T, S = len(log_y), len(ext)
beta = [[NEG_INF] * S for _ in range(T)]
beta[T - 1][S - 1] = 0.0 # @line L7
if S > 1:
beta[T - 1][S - 2] = 0.0
for t in range(T - 2, -1, -1):
nxt = beta[t + 1]
for s in range(S):
acc = nxt[s] + log_y[t + 1][ext[s]]
if s + 1 < S:
acc = log_add(acc, nxt[s + 1] + log_y[t + 1][ext[s + 1]])
if s + 2 < S and _can_skip(ext, s + 2, blank):
acc = log_add(acc, nxt[s + 2] + log_y[t + 1][ext[s + 2]])
beta[t][s] = acc
return beta
def ctc_loss_and_grad(logits: Sequence[Sequence[float]], labels: Sequence[int], blank: int = BLANK):
"""Return (loss, grad): loss = -log p(l | x) in nats, grad[t][k] = d loss / d u_t(k).
Raise ValueError if no path produces l (T < min_frames(l)), since then the
loss is infinite and has no gradient.
"""
T = len(logits)
if T == 0:
raise ValueError("need at least one frame")
log_y = [log_softmax(u) for u in logits] # @line L1
ext = extend_labels(labels, blank)
S = len(ext)
if T < min_frames(labels):
raise ValueError("too few frames for this label sequence")
alpha = log_alpha(log_y, ext, blank)
log_p = alpha[T - 1][S - 1] if S == 1 else log_add(alpha[T - 1][S - 1], alpha[T - 1][S - 2]) # @line L6
beta = log_beta(log_y, ext, blank)
K = len(logits[0])
grad = []
for t in range(T): # @line L8
occ = [[] for _ in range(K)]
for s in range(S):
occ[ext[s]].append(alpha[t][s] + beta[t][s])
grad.append([math.exp(log_y[t][k]) - math.exp(log_sum(occ[k]) - log_p) for k in range(K)])
return -log_p, grad # @line L9
def ctc_loss(logits: Sequence[Sequence[float]], labels: Sequence[int], blank: int = BLANK) -> float:
"""Return -log p(l | x) in nats, and POS_INF if no path produces l."""
if len(logits) == 0:
raise ValueError("need at least one frame")
if len(logits) < min_frames(labels):
return POS_INF
log_y = [log_softmax(u) for u in logits]
ext = extend_labels(labels, blank)
alpha = log_alpha(log_y, ext, blank)
last = alpha[-1]
return -(last[-1] if len(ext) == 1 else log_add(last[-1], last[-2]))
def greedy_decode(log_y: Sequence[Sequence[float]], blank: int = BLANK) -> Tuple[int, ...]:
"""Best path decoding: the most probable symbol of each frame, then B.
This is the labeling of the most probable path. It is NOT always the most
probable labeling.
"""
return collapse([argmax(row) for row in log_y], blank)
def brute_force_log_prob(log_y: Sequence[Sequence[float]], labels: Sequence[int], blank: int = BLANK) -> float:
"""log p(l | x) by summing over all K^T paths. Only for small T and K."""
T, K = len(log_y), len(log_y[0])
target = tuple(labels)
terms = [
sum(log_y[t][k] for t, k in enumerate(path))
for path in itertools.product(range(K), repeat=T)
if collapse(path, blank) == target
]
return log_sum(terms)
def labeling_posteriors(log_y: Sequence[Sequence[float]], blank: int = BLANK) -> dict:
"""Map every labeling with nonzero probability to its log probability, by
summing over all K^T paths. Only for small T and K."""
T, K = len(log_y), len(log_y[0])
acc: dict = {}
for path in itertools.product(range(K), repeat=T):
lab = collapse(path, blank)
acc.setdefault(lab, []).append(sum(log_y[t][k] for t, k in enumerate(path)))
return {lab: log_sum(v) for lab, v in acc.items()}
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_connectionist_temporal_classification.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/connectionist-temporal-classification/. The authors are listed in prov/7KBK03.jsonl.
import math
import random
import pytest
import nlslog
from connectionist_temporal_classification import (
brute_force_log_prob,
collapse,
ctc_forward,
ctc_loss,
ctc_loss_and_grad,
extend_labels,
greedy_decode,
labeling_posteriors,
log_alpha,
log_beta,
min_frames,
)
from nlslog import COUNTING, LOG, NEG_INF, POS_INF, PROB, VITERBI, log_add, log_softmax, log_sum
# The worked example of the page: symbols _ (blank, index 0), a (1), b (2), T = 3.
Y = [[0.5, 0.4, 0.1], [0.4, 0.3, 0.3], [0.3, 0.1, 0.6]]
LY = [[math.log(p) for p in row] for row in Y]
def random_logits(rng, T, K, scale=2.0):
return [[rng.uniform(-scale, scale) for _ in range(K)] 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_collapse_removes_repeats_then_blanks():
a, b = 1, 2
assert collapse([a, 0, a, b, 0]) == (a, a, b)
assert collapse([0, a, a, 0, 0, a, b, b]) == (a, a, b)
assert collapse([a, a, b]) == (a, b)
assert collapse([0, 0, 0]) == ()
# Blanks first, then repeats, would give a different map: "a_a" -> "aa" -> "a".
assert collapse([a, 0, a]) == (a, a)
def test_extended_labels():
assert extend_labels([1, 2]) == [0, 1, 0, 2, 0]
for U in range(6):
assert len(extend_labels([1] * U)) == 2 * U + 1
with pytest.raises(ValueError):
extend_labels([1, 0])
def test_path_count_check_values():
def count(T, labels, K=4):
return ctc_forward(COUNTING, [[1] * K] * T, labels)
assert count(3, [1, 2]) == 5 # _ab, a_b, aab, ab_, abb
assert count(3, [1, 1]) == 1 # a_a
assert count(4, [1, 1]) == 5
assert count(4, [1, 2]) == 15
assert count(5, [3, 1, 2]) == 28 # "cat"
assert count(2, [1, 1]) == 0
assert min_frames([1, 1]) == 3 and min_frames([1, 2, 2, 2]) == 6 and min_frames([]) == 0
def test_path_count_against_enumeration():
import itertools
for T in range(1, 6):
for labels in [(), (1,), (1, 2), (1, 1), (2, 1, 2), (1, 1, 1)]:
n = sum(1 for p in itertools.product(range(3), repeat=T) if collapse(p) == labels)
assert ctc_forward(COUNTING, [[1] * 3] * T, list(labels)) == n
assert (n > 0) == (T >= min_frames(labels))
def test_page_example():
ext = extend_labels([1, 2])
alpha = log_alpha(LY, ext)
beta = log_beta(LY, ext)
want_alpha = [[0.5, 0.4, 0, 0, 0], [0.2, 0.27, 0.16, 0.12, 0], [0.06, 0.047, 0.129, 0.33, 0.036]]
want_beta = [[0.18, 0.69, 0.51, 0.39, 0.12], [0, 0.6, 0.6, 0.9, 0.3], [0, 0, 0, 1, 1]]
for t in range(3):
assert [math.exp(x) for x in alpha[t]] == pytest.approx(want_alpha[t], abs=1e-12)
assert [math.exp(x) for x in beta[t]] == pytest.approx(want_beta[t], abs=1e-12)
assert ctc_forward(PROB, Y, [1, 2]) == pytest.approx(0.366, abs=1e-12)
assert ctc_loss(LY, [1, 2]) == pytest.approx(-math.log(0.366), abs=1e-12)
# The best single path is a_b, with probability 0.4 * 0.4 * 0.6.
assert math.exp(ctc_forward(VITERBI, LY, [1, 2])) == pytest.approx(0.096, abs=1e-12)
def test_alpha_beta_give_p_at_every_frame():
rng = random.Random(7)
for _ in range(20):
T, K = rng.randint(3, 8), rng.randint(2, 5)
U = rng.randint(0, 3)
labels = [rng.randint(1, K - 1) for _ in range(U)]
if T < min_frames(labels):
continue
ly = [log_softmax(u) for u in random_logits(rng, T, K)]
ext = extend_labels(labels)
alpha, beta = log_alpha(ly, ext), log_beta(ly, ext)
log_p = -ctc_loss(ly, labels)
for t in range(T):
assert log_sum([alpha[t][s] + beta[t][s] for s in range(len(ext))]) == pytest.approx(log_p, abs=1e-10)
def test_forward_against_brute_force():
rng = random.Random(11)
for _ in range(30):
T, K = rng.randint(1, 5), rng.randint(2, 4)
U = rng.randint(0, 3)
labels = [rng.randint(1, K - 1) for _ in range(U)]
logits = random_logits(rng, T, K)
ly = [log_softmax(u) for u in logits]
want = brute_force_log_prob(ly, labels)
if want == NEG_INF:
assert ctc_loss(logits, labels) == POS_INF
with pytest.raises(ValueError):
ctc_loss_and_grad(logits, labels)
continue
assert -ctc_loss(logits, labels) == pytest.approx(want, abs=1e-10)
assert ctc_forward(LOG, ly, labels) == pytest.approx(want, abs=1e-10)
assert ctc_forward(PROB, [[math.exp(x) for x in r] for r in ly], labels) == pytest.approx(math.exp(want), rel=1e-10)
def test_labeling_probabilities_sum_to_one():
rng = random.Random(3)
ly = [log_softmax(u) for u in random_logits(rng, 5, 3)]
post = labeling_posteriors(ly)
assert log_sum(list(post.values())) == pytest.approx(0.0, abs=1e-12)
for lab, v in post.items():
assert ctc_forward(LOG, ly, list(lab)) == pytest.approx(v, abs=1e-10)
def test_gradient_against_finite_differences():
rng = random.Random(5)
h = 1e-6
for labels, T, K in [([1, 2], 4, 3), ([1, 1], 5, 3), ([2, 1, 3], 6, 4), ([], 3, 2), ([1], 1, 2)]:
logits = random_logits(rng, T, K)
_, grad = ctc_loss_and_grad(logits, labels)
for t in range(T):
for k in range(K):
up = [row[:] for row in logits]
dn = [row[:] for row in logits]
up[t][k] += h
dn[t][k] -= h
num = (ctc_loss(up, labels) - ctc_loss(dn, labels)) / (2 * h)
assert grad[t][k] == pytest.approx(num, abs=1e-5)
# The gradient of a frame sums to 0, because softmax ignores a shift of the logits.
assert sum(grad[t]) == pytest.approx(0.0, abs=1e-12)
def test_gradient_check_values_of_the_example():
_, grad = ctc_loss_and_grad(LY, [1, 2])
want = [[0.254098, -0.354098, 0.1], [0.137705, -0.142623, 0.004918], [0.201639, 0.1, -0.301639]]
for t in range(3):
assert grad[t] == pytest.approx(want[t], abs=1e-6)
def test_greedy_is_not_the_most_probable_labeling():
# Page example: the best path __b gives "b" (0.294), but "ab" has 0.366.
post = labeling_posteriors(LY)
best = max(post, key=post.get)
assert best == (1, 2)
assert greedy_decode(LY) == (2,)
assert math.exp(post[(2,)]) == pytest.approx(0.294, abs=1e-12)
# A smaller case: two frames with blank 0.6, a 0.4. Greedy gives "" (0.36), "a" has 0.64.
ly = [[math.log(0.6), math.log(0.4)]] * 2
assert greedy_decode(ly) == ()
assert math.exp(ctc_forward(LOG, ly, [1])) == pytest.approx(0.64, abs=1e-12)
def test_product_of_probabilities_underflows_and_log_space_does_not():
T, K = 300, 30
probs = [[1.0 / K] * K for _ in range(T)]
assert ctc_forward(PROB, probs, [1, 2]) == 0.0
n = ctc_forward(COUNTING, [[1] * K] * T, [1, 2])
assert n == 339746225
want = math.log(n) - T * math.log(K)
assert want < -1000
lp = [[math.log(1.0 / K)] * K for _ in range(T)]
assert ctc_forward(LOG, lp, [1, 2]) == pytest.approx(want, abs=1e-9)
assert ctc_loss(lp, [1, 2]) == pytest.approx(-want, abs=1e-9)
def test_long_random_utterance_gradient_is_finite():
rng = random.Random(13)
T, K = 200, 6
labels = [rng.randint(1, K - 1) for _ in range(40)]
logits = random_logits(rng, T, K, scale=5.0)
loss, grad = ctc_loss_and_grad(logits, labels)
assert 0 < loss < POS_INF
for row in grad:
assert all(math.isfinite(g) for g in row)
assert sum(row) == pytest.approx(0.0, abs=1e-9)
def test_errors():
with pytest.raises(ValueError):
ctc_loss([], [1])
with pytest.raises(ValueError):
ctc_loss_and_grad([[0.0, 0.0]] * 2, [1, 1])
assert ctc_loss([[0.0, 0.0]] * 2, [1, 1]) == POS_INF
History
Graves, Fernández, Gomez and Schmidhuber (2006) introduced CTC to train bidirectional LSTM networks on unsegmented speech. On TIMIT phone recognition they measured a label error rate of 31.47% with best path decoding and 30.51% with prefix search, against 33.84% for a hybrid BLSTM/HMM system (their Table 1). Hannun, Maas, Jurafsky and Ng (2014) combined a CTC network with an n-gram language model through prefix beam search for large vocabulary recognition. CTC later became the fine-tuning loss of self-supervised speech encoders such as wav2vec 2.0 (Baevski et al. 2020) and an auxiliary loss of attention models.
References
- Alex Graves, Santiago Fernández, Faustino Gomez and Jürgen Schmidhuber, Connectionist temporal classification: labelling unsegmented sequence data with recurrent neural networks, Proceedings of the 23rd International Conference on Machine Learning (ICML 2006), pages 369 to 376, Section 3 (the map B and eqs. 2 to 4), Section 4.1 (forward and backward, eqs. 5 to 11), Section 4.2 (the gradient, eqs. 12 to 16) and Table 1
- Prefix beam search for CTC with a language model, Section 3 (decoding) and Algorithm 1
- Fine-tuning of a pretrained speech encoder with the CTC loss, the section on fine-tuning
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 7KBK03 Edit this page History Report an error Markdown