Algorithm Search⌘K

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
Origin
Alex Graves, Santiago Fernández, Faustino Gomez, Jürgen Schmidhuber, 2006

Connectionist temporal classification (CTC) trains a network that reads TT frames and must output a shorter label sequence ll, 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 ll is the sum over all frame-level paths that become ll after merging repeats and deleting blanks. A forward-backward recursion on the sequence ll with blanks inserted computes this sum in Θ(TU)\Theta(T U) steps and its gradient with respect to the outputs in Θ(T(U+K))\Theta(T (U + K)), although the number of paths grows exponentially in TT. The loss is −ln⁡p(l∣x)-\ln p(l \mid x) 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 ut(k)u_t(k) for frames t=1,…,Tt = 1, \ldots, T and symbols kk of the alphabet L∪{∅}L \cup \{\varnothing\}, with K=∣L∣+1K = |L| + 1 symbols in all. The blank is written ∅\varnothing in formulas, "_" in examples and index 0 in the code. The output distribution of frame tt is yt=softmax(ut)y_t = \mathrm{softmax}(u_t). The model assumes that the outputs of different frames are independent given the input xx. This is an assumption of the model, not a property of speech.

A path is a sequence π∈(L∪{∅})T\pi \in (L \cup \{\varnothing\})^T, with p(π∣x)=∏tyt(πt)p(\pi \mid x) = \prod_t y_t(\pi_t). The map B\mathcal{B} first merges each run of equal symbols into one and then deletes the blanks, so B(aa_ab_)=aab\mathcal{B}(\mathrm{aa\_ab\_}) = \mathrm{aab}. The order matters: blanks first would turn "a_a" into "a", but B(a_a)=aa\mathcal{B}(\mathrm{a\_a}) = \mathrm{aa}. For a label sequence l=l1…lUl = l_1 \ldots l_U over LL,

p(l∣x)=∑π:B(π)=l ∏t=1Tyt(πt),LCTC=−ln⁡p(l∣x).p(l \mid x) = \sum_{\pi : \mathcal{B}(\pi) = l} \ \prod_{t=1}^{T} y_t(\pi_t), \qquad \mathcal{L}_{\mathrm{CTC}} = -\ln p(l \mid x).

The task is to compute LCTC\mathcal{L}_{\mathrm{CTC}} and its gradient with respect to every ut(k)u_t(k). Two copies of the same label need a blank between them, so a path exists only if T≥U+rT \ge U + r, where rr is the number of adjacent repeats in ll. Otherwise the loss is +∞+\infty.

The algorithm

Insert a blank before, between and after the labels: l′=∅ l1 ∅ l2…∅ lU ∅l' = \varnothing\, l_1\, \varnothing\, l_2 \ldots \varnothing\, l_U\, \varnothing, with S=2U+1S = 2U + 1 states. A path moves through l′l' 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 αt(s)\alpha_t(s) sums the path prefixes that are in state ss at frame tt and includes yty_t. The backward variable βt(s)\beta_t(s) sums the suffixes after frame tt and does not include yty_t. The arrays store natural logs; ⊕\oplus is log_add, so a⊕b=ln⁡(ea+eb)a \oplus b = \ln(e^a + e^b).

  1. CTC-LOSS(u, l) ▷ u: T × K logits, l = l_1 .. l_U, ∅ = index 0, ln is the natural log
  2. 1ln y_t ← log-softmax(u_t) for every t; l' ← ∅ l_1 ∅ l_2 .. ∅ l_U ∅, S ← 2U + 1
  3. 2α_1(1) ← ln y_1(∅), α_1(2) ← ln y_1(l_1), α_1(s) ← -∞ for s ≥ 3
  4. 3for t ← 2 to T do for s ← 1 to S do
  5. 4a ← α_{t-1}(s) ⊕ α_{t-1}(s - 1); if l'_s ≠ ∅ and l'_s ≠ l'_{s-2} then a ← a ⊕ α_{t-1}(s - 2)
  6. 5α_t(s) ← a + ln y_t(l'_s)
  7. 6ln p ← α_T(S) ⊕ α_T(S - 1)
  8. 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'}))
  9. 8g_t(k) ← y_t(k) - exp( ⊕_{s : l'_s = k} (α_t(s) + β_t(s)) - ln p ) for every t and k
  10. 9return -ln p and g

Line L4 is the whole structure of CTC. A path in state ss at frame tt was in ss (a repeat of the same symbol), in s−1s - 1 (one step), or in s−2s - 2 (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, ∂L/∂ut(k)=yt(k)−1p∑s:ls′=kαt(s)βt(s)\partial \mathcal{L} / \partial u_t(k) = y_t(k) - \frac{1}{p} \sum_{s : l'_s = k} \alpha_t(s) \beta_t(s). This form holds with β\beta defined without frame tt, as here. Graves et al. (2006) put yty_t inside their β\beta, so their eq. (16) has an extra factor 1/yt(k)1 / y_t(k) in the sum; the two forms are equal.

Example

Take the alphabet {_, a, b}, the target "ab" and T=3T = 3 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 p(ab∣x)=0.366p(\mathrm{ab} \mid x) = 0.366. The forward table, in probabilities (the code stores the logs), gets the same number without listing the paths:

αt(s)\alpha_t(s) _ a _ b _
t=1t = 1 0.5 0.4 0 0 0
t=2t = 2 0.2 0.27 0.16 0.12 0
t=3t = 3 0.06 0.047 0.129 0.33 0.036

For example, α2(b)=(α1(b)+α1(_)+α1(a))⋅0.3=0.4⋅0.3=0.12\alpha_2(\mathrm{b}) = (\alpha_1(\mathrm{b}) + \alpha_1(\_) + \alpha_1(\mathrm{a})) \cdot 0.3 = 0.4 \cdot 0.3 = 0.12: the path may skip the blank from a to b because a and b differ. The answer is α3(b)+α3(_)=0.33+0.036=0.366\alpha_3(\mathrm{b}) + \alpha_3(\_) = 0.33 + 0.036 = 0.366, and the loss is −ln⁡0.366=1.005122-\ln 0.366 = 1.005122 nats. The gradient for frame 1 is (0.254098,−0.354098,0.1)(0.254098, -0.354098, 0.1) 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 p(b∣x)=0.294p(\mathrm{b} \mid x) = 0.294. But "ab" has p=0.366p = 0.366. 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 π\pi with B(π)=l\mathcal{B}(\pi) = l are in one-to-one correspondence with the state sequences through l′l' that obey the start, step, skip and end rules of lines L2, L4 and L6. Then an induction on tt shows that αt(s)\alpha_t(s) sums the valid prefixes that end in ss, and a downward induction does the same for βt(s)\beta_t(s) and the suffixes. So αt(s)βt(s)\alpha_t(s)\beta_t(s) is the total probability of the paths in state ss at frame tt, and ∑sαt(s)βt(s)=p(l∣x)\sum_s \alpha_t(s)\beta_t(s) = p(l \mid x) for every tt. The gradient follows from the chain rule through the softmax, with ∑kγt(k)=p\sum_k \gamma_t(k) = p for γt(k)=∑s:ls′=kαt(s)βt(s)\gamma_t(k) = \sum_{s : l'_s = k} \alpha_t(s)\beta_t(s).

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 t=1,…,Tt = 1, \ldots, T and states s=1,…,Ss = 1, \ldots, S (the code counts both from 0). The blank is ∅\varnothing. The label sequence is l=l1…lUl = l_1 \ldots l_U with no blank in it, and the extended sequence is l′=∅ l1 ∅ l2…lU ∅l' = \varnothing\, l_1\, \varnothing\, l_2 \ldots l_U\, \varnothing, so S=2U+1S = 2U + 1, ls′=∅l'_s = \varnothing for odd ss and l2j′=ljl'_{2j} = l_j. The output of frame tt is yt=softmax(ut)y_t = \mathrm{softmax}(u_t). The proofs work with probabilities; the code stores their natural logs, and ⊕\oplus (log_add) in log space is ++ on probabilities, so the same statements hold for the stored values.

A path is a sequence π=π1…πT\pi = \pi_1 \ldots \pi_T of symbols, with probability ∏tyt(πt)\prod_t y_t(\pi_t). The map B\mathcal{B} merges each run of equal symbols into one symbol and then deletes the blanks. By definition p(l∣x)=∑π:B(π)=l∏tyt(πt)p(l \mid x) = \sum_{\pi : \mathcal{B}(\pi) = l} \prod_t y_t(\pi_t).

Paths and state sequences

Call a state ss skippable to if s≥3s \ge 3, ls′≠∅l'_s \neq \varnothing and ls′≠ls−2′l'_s \neq l'_{s-2}. An admissible state sequence is σ=σ1…σT\sigma = \sigma_1 \ldots \sigma_T with σ1∈{1,2}\sigma_1 \in \{1, 2\}, σT∈{S−1,S}\sigma_T \in \{S-1, S\} (only {1}\{1\} at both ends when S=1S = 1), and each step σt−σt−1\sigma_t - \sigma_{t-1} equal to 0 or 1, or equal to 2 when σt\sigma_t is skippable to.

Lemma 1. The map σ↦π\sigma \mapsto \pi with πt=lσt′\pi_t = l'_{\sigma_t} is a bijection from the admissible state sequences onto the paths π\pi with B(π)=l\mathcal{B}(\pi) = l.

Proof. Take an admissible σ\sigma and set πt=lσt′\pi_t = l'_{\sigma_t}. A step of 2 always lands on an even state ss and skips the odd state s−1s - 1, so no even state is skipped. Since σ\sigma starts at 1 or 2 and ends at S−1S - 1 or SS, it visits each even state 2,4,…,2U2, 4, \ldots, 2U, each on a block of consecutive frames, in this order. The path π\pi is a run of l1l_1, a run of l2l_2, 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 B\mathcal{B} maps each label run to one symbol, deletes the blank runs, and gives ll.

Conversely, take π\pi with B(π)=l\mathcal{B}(\pi) = l and cut it into maximal runs of equal symbols. Merging gives one symbol per run, and deleting the blank runs leaves ll, so the non-blank runs are, in order, runs of l1,…,lUl_1, \ldots, l_U. Map the frames of the jj-th label run to state 2j2j, the frames of a blank run between label runs jj and j+1j+1 to state 2j+12j + 1, a leading blank run to state 1 and a trailing blank run to state 2U+12U + 1. 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 jj and j+1j + 1 give a step of 2, where lj+1≠ljl_{j+1} \neq l_j 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. □\square

So p(l∣x)=∑σ∏tyt(lσt′)p(l \mid x) = \sum_\sigma \prod_t y_t(l'_{\sigma_t}), summed over the admissible state sequences. In particular, a path exists if and only if an admissible σ\sigma exists, which needs one frame for each label and one more frame for each blank state between two equal labels, that is T≥U+rT \ge U + r, where rr is the number of indices jj with lj=lj+1l_j = l_{j+1}.

The forward and backward variables

Lemma 2 (forward). After lines L2 to L5, αt(s)\alpha_t(s) equals the sum, over the prefixes σ1…σt\sigma_1 \ldots \sigma_t that satisfy the start rule and the step rule and end with σt=s\sigma_t = s, of ∏τ=1tyτ(lστ′)\prod_{\tau = 1}^{t} y_\tau(l'_{\sigma_\tau}).

Proof. By induction on tt. For t=1t = 1 the prefixes are σ1=1\sigma_1 = 1 and σ1=2\sigma_1 = 2, which line L2 sets, and every other state gets 0. For t>1t > 1, the last step of a prefix that ends in ss comes from ss, from s−1s - 1, or from s−2s - 2 when ss 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 t−1t - 1. 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. □\square

Lemma 3 (backward). After line L7 and its loop, βt(s)\beta_t(s) equals the sum, over the suffixes σt+1…σT\sigma_{t+1} \ldots \sigma_T such that σt=s\sigma_t = s followed by the suffix satisfies the step rule and ends in {S−1,S}\{S-1, S\}, of ∏τ=t+1Tyτ(lστ′)\prod_{\tau = t+1}^{T} y_\tau(l'_{\sigma_\tau}). The factor yty_t is not included.

Proof. By induction on tt downward. For t=Tt = T the suffix is empty, its product is 1, and it is valid exactly when s∈{S−1,S}s \in \{S - 1, S\}, which line L7 sets. For t<Tt < T, split by σt+1∈{s,s+1,s+2}\sigma_{t+1} \in \{s, s+1, s+2\}, where s+2s + 2 is allowed only when it is skippable to. This gives βt(s)=∑s′yt+1(ls′′) βt+1(s′)\beta_t(s) = \sum_{s'} y_{t+1}(l'_{s'})\, \beta_{t+1}(s') over the allowed s′s', which is the code. □\square

Theorem 1. p(l∣x)=αT(S)+αT(S−1)p(l \mid x) = \alpha_T(S) + \alpha_T(S-1) (only αT(1)\alpha_T(1) when S=1S = 1), so line L6 gives log⁡p(l∣x)\log p(l \mid x). Moreover, for every frame tt and state ss, αt(s)βt(s)\alpha_t(s)\beta_t(s) is the total probability of the paths of ll that are in state ss at frame tt, and ∑sαt(s)βt(s)=p(l∣x)\sum_s \alpha_t(s) \beta_t(s) = p(l \mid x).

Proof. The first claim is Lemma 2 at t=Tt = T with the end rule, and Lemma 1. For the second, an admissible σ\sigma with σt=s\sigma_t = s is a valid prefix ending in ss followed by a valid suffix from ss, and every such pair gives an admissible σ\sigma. The product over frames splits into the prefix part, which includes yty_t, and the suffix part, which does not, so the sum is αt(s)βt(s)\alpha_t(s)\beta_t(s). Each admissible σ\sigma is in exactly one state at frame tt, so summing over ss gives pp. □\square

The gradient

Theorem 2. Let γt(k)=∑s:ls′=kαt(s)βt(s)\gamma_t(k) = \sum_{s : l'_s = k} \alpha_t(s)\beta_t(s). Then

∂(−ln⁡p(l∣x))∂ut(k)=yt(k)−γt(k)p(l∣x),\frac{\partial(-\ln p(l \mid x))}{\partial u_t(k)} = y_t(k) - \frac{\gamma_t(k)}{p(l \mid x)},

which is line L8. The log is the natural log.

Proof. By Theorem 1 and Lemma 1, γt(k)\gamma_t(k) is the sum of ∏τyτ(πτ)\prod_\tau y_\tau(\pi_\tau) over the paths of ll with πt=k\pi_t = k. Each such product holds the factor yt(k)y_t(k) exactly once, and the products of the other paths of ll do not depend on yt(k)y_t(k). Treating the yt(j)y_t(j) as free variables, ∂p/∂yt(j)=γt(j)/yt(j)\partial p / \partial y_t(j) = \gamma_t(j) / y_t(j). The softmax gives ∂yt(j)/∂ut(k)=yt(j)(δjk−yt(k))\partial y_t(j) / \partial u_t(k) = y_t(j)(\delta_{jk} - y_t(k)), and utu_t affects no other frame. By the chain rule,

∂ln⁡p∂ut(k)=∑jγt(j)p yt(j) yt(j)(δjk−yt(k))=γt(k)p−yt(k)∑jγt(j)p=γt(k)p−yt(k),\frac{\partial \ln p}{\partial u_t(k)} = \sum_j \frac{\gamma_t(j)}{p\, y_t(j)}\, y_t(j)\big(\delta_{jk} - y_t(k)\big) = \frac{\gamma_t(k)}{p} - y_t(k) \frac{\sum_j \gamma_t(j)}{p} = \frac{\gamma_t(k)}{p} - y_t(k),

because ∑jγt(j)=∑sαt(s)βt(s)=p\sum_j \gamma_t(j) = \sum_s \alpha_t(s)\beta_t(s) = p by Theorem 1. Change the sign. □\square

Remark (the convention of Graves et al. 2006). Their backward variable β^t(s)\hat\beta_t(s) includes the factor yt(ls′)y_t(l'_s), so α^t(s)β^t(s)=αt(s)βt(s) yt(ls′)\hat\alpha_t(s)\hat\beta_t(s) = \alpha_t(s)\beta_t(s)\, y_t(l'_s). Their eq. (16) therefore reads yt(k)−1yt(k)Zt∑s:ls′=kα^t(s)β^t(s)y_t(k) - \frac{1}{y_t(k) Z_t} \sum_{s : l'_s = k} \hat\alpha_t(s)\hat\beta_t(s) with Zt=∑sα^t(s)β^t(s)/yt(ls′)=pZ_t = \sum_s \hat\alpha_t(s)\hat\beta_t(s) / y_t(l'_s) = p. It is the same quantity as Theorem 2.

Corollary. For each frame, ∑k∂(−ln⁡p)/∂ut(k)=1−∑kγt(k)/p=0\sum_k \partial(-\ln p)/\partial u_t(k) = 1 - \sum_k \gamma_t(k)/p = 0. The tests check this, and they check Theorem 2 against central finite differences of the loss.

Log space and rounding

The code stores ln⁡α\ln \alpha and ln⁡β\ln \beta and adds probabilities with log_add, which computes max⁡(a,b)+ln⁡(1+e−∣a−b∣)\max(a, b) + \ln(1 + e^{-|a - b|}). 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 yt(k)≥e−cy_t(k) \ge e^{-c}, a stored value is at least −cT-cT, so for any realistic TT 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 Θ(K)\Theta(K) per frame. The forward and backward passes cost a constant number of log_add operations per cell, and there are TS=T(2U+1)T S = T(2U + 1) cells. The total is Θ(T(U+K))\Theta(T(U + K)) operations. Only the cells that lie on some complete path matter. They form a band whose width grows with the slack T−U−rT - U - r, so a banded implementation saves time when TT is close to U+rU + r.

The α\alpha and β\beta tables take Θ(TU)\Theta(T U) numbers; the gradient output itself takes TKT K. To compute only the loss, keep one column of α\alpha, which takes Θ(U)\Theta(U) memory. In practice a batch of utterances runs on a GPU, and the Θ(T)\Theta(T) 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 T=300T = 300, 30 equally likely symbols and the target "ab" has p=339746225⋅30−300≈e−1000.7p = 339746225 \cdot 30^{-300} \approx e^{-1000.7}. The forward pass in probabilities returns 0.0, and the log-space pass returns −1000.7155-1000.7155, the exact value to 9 digits. Graves et al. (2006) rescale α\alpha and β\beta at each frame instead, which also works. This is why the page uses the floating-point model.

Properties

  • Exact sum. The forward pass gives p(l∣x)p(l \mid x) exactly in exact arithmetic (a theorem; see Correctness). It is the forward algorithm of a left-to-right HMM with SS 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, ∑k∂L/∂ut(k)=0\sum_k \partial \mathcal{L} / \partial u_t(k) = 0 for every frame.
  • Best path is not best labeling. Greedy decoding takes the best symbol of each frame and applies B\mathcal{B}. 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 ⊕\oplus by max⁡\max 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 T×UT \times U 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 T<U+rT < U + r, 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 β\beta of Graves et al. (with yty_t) and the β\beta of this page (without yty_t) gives a gradient that is off by a factor yt(k)y_t(k). Test against finite differences.
  • Gradient with respect to what. The formula of line L8 is the gradient with respect to the logits ut(k)u_t(k). With respect to yt(k)y_t(k) it is −γt(k)/(p yt(k))-\gamma_t(k) / (p\, y_t(k)). 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 p(l∣x)p(l \mid x) (probability), ln⁡p(l∣x)\ln p(l \mid x) (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.

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

  1. 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
  2. Prefix beam search for CTC with a language model, Section 3 (decoding) and Algorithm 1
  3. 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.

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