AI Logic

Loss Functions

CTC Loss

Updated:

The CTC path lattice and the collapsing rule. On the left is a lattice whose rows are the target with blanks inserted (blank, C, blank, A, blank, T, blank) and whose columns are the input time steps t = 1 to 8; allowed transitions are thin lines, the path C C blank A A blank T T is a bold line, paths start in the top two rows and end in the bottom two rows. On the right is a table that collapses paths to strings: merging repeated consecutive symbols and then removing blanks turns two paths into CAT, and the paper's examples aβˆ’abβˆ’ and βˆ’aaβˆ’βˆ’abb into aab. Below, p(CAT | x) is the sum of the probabilities of all paths that collapse to CAT, and CTC Loss is its negative log

Background and overview

CTC Loss (Connectionist Temporal Classification) is a loss function for training a network that outputs sequences without knowing the alignment between the outputs at each input time step and the target string (which time step corresponds to which character). Graves et al. proposed it in 2006 for transcribing phoneme sequences from speech.

At each input time step, the network outputs probabilities for "each character" and for a blank, which means "output nothing." Picking one output per time step gives a sequence (a path), and collapsing it with the rule B\mathcal{B}, "merge repeated consecutive symbols and remove blanks," gives a string. CTC Loss sums the probabilities of all paths that collapse to the target string z\mathbf{z} and takes the negative of its logarithm.

LCTC=βˆ’ln⁑p(z∣x),p(z∣x)=βˆ‘Ο€βˆˆBβˆ’1(z)∏t=1TyΟ€ttL_{\mathrm{CTC}} = -\ln p(\mathbf{z} \mid \mathbf{x}), \qquad p(\mathbf{z} \mid \mathbf{x}) = \sum_{\pi \in \mathcal{B}^{-1}(\mathbf{z})} \prod_{t=1}^{T} y^t_{\pi_t}

x\mathbf{x} is the input sequence of length TT, ykty^t_k is the probability of outputting symbol kk (a character or the blank) at time tt, and Ο€\pi is a path of length TT.

The motivation was that, for sequence labeling, networks could not be trained on their own.

  • Per-time-step targets were required: Ordinary losses are defined per input time step. For speech, training was impossible without data in which someone had manually marked (segmented) which interval corresponds to which phoneme. The boundaries are inherently ambiguous, and segmenting is laborious.
  • Post-processing was needed to turn outputs into strings: Combining per-time-step predictions into a string required a system combined with hidden Markov models (HMMs) or similar.

CTC made it possible to train networks such as bidirectional RNNs directly from unsegmented pairs of "input sequence and target string" alone. The left side of the figure at the top is a lattice of paths that collapse to the target "CAT," and the right side shows examples of the rule that collapses paths into strings.

As an analogy, it is like watching a speaker's mouth frame by frame, writing down for each frame either "some sound" or "silence or a transition," and at the end tidying up repeated sounds and silences into a sentence.

Theory (how the loss is computed)

CTC Loss is computed in the following steps.

  1. Add one blank to the output layer: Use a softmax layer with ∣L∣+1|L| + 1 outputs, the set of characters (labels) LL plus the blank. ykty^t_k is the probability of outputting symbol kk at time tt.
  2. Take a path's probability as the product of per-time-step probabilities: The probability of a path Ο€\pi of length TT is the product of the outputs, treating each time step as independent (Eq. (2) of the paper). p(Ο€βˆ£x)=∏t=1TyΟ€ttp(\pi \mid \mathbf{x}) = \prod_{t=1}^{T} y^t_{\pi_t}
  3. Collapse paths into strings: The mapping B\mathcal{B} processes a path by first "merging repeated consecutive symbols into one" and then "removing blanks." In the paper's example, B(aβˆ’abβˆ’)=B(βˆ’aaβˆ’βˆ’abb)=aab\mathcal{B}(a{-}ab{-}) = \mathcal{B}({-}aa{-}{-}abb) = aab (βˆ’- is the blank).
  4. Sum the probabilities of all paths that collapse to the target (Eq. (3)). p(l∣x)=βˆ‘Ο€βˆˆBβˆ’1(l)p(Ο€βˆ£x)p(\mathbf{l} \mid \mathbf{x}) = \sum_{\pi \in \mathcal{B}^{-1}(\mathbf{l})} p(\pi \mid \mathbf{x})
  5. Do the summation by dynamic programming on a lattice: The number of paths grows exponentially with TT, so build a lattice with the sequence lβ€²\mathbf{l}' (length 2∣l∣+12|\mathbf{l}| + 1), the target l\mathbf{l} with blanks inserted at both ends and between characters, on one axis and time on the other. The forward variable Ξ±t(s)\alpha_t(s) (the total probability of paths that have reached position ss of lβ€²\mathbf{l}' by time tt) is computed in time order with the following formula (Eqs. (6) and (7)). Ξ±t(s)={(Ξ±tβˆ’1(s)+Ξ±tβˆ’1(sβˆ’1))ylsβ€²t(lsβ€²Β isΒ blankΒ orΒ lsβˆ’2β€²=lsβ€²)(Ξ±tβˆ’1(s)+Ξ±tβˆ’1(sβˆ’1)+Ξ±tβˆ’1(sβˆ’2))ylsβ€²t(otherwise)\alpha_t(s) = \begin{cases} \left(\alpha_{t-1}(s) + \alpha_{t-1}(s-1)\right) y^t_{l'_s} & (l'_s \text{ is blank or } l'_{s-2} = l'_s) \\ \left(\alpha_{t-1}(s) + \alpha_{t-1}(s-1) + \alpha_{t-1}(s-2)\right) y^t_{l'_s} & (\text{otherwise}) \end{cases} Paths start at the blank or the first character (Ξ±1(1)=yb1\alpha_1(1) = y^1_b, Ξ±1(2)=yl11\alpha_1(2) = y^1_{l_1}) and end at the last character or the last blank. p(l∣x)=Ξ±T(∣lβ€²βˆ£)+Ξ±T(∣lβ€²βˆ£βˆ’1)p(\mathbf{l} \mid \mathbf{x}) = \alpha_T(|\mathbf{l}'|) + \alpha_T(|\mathbf{l}'| - 1)
  6. Use the negative log-likelihood as the loss: To maximize the log probability of the targets in the training data, minimize βˆ’ln⁑p(z∣x)-\ln p(\mathbf{z} \mid \mathbf{x}) (Eq. (12)). Combining it with the backward variable Ξ²t(s)\beta_t(s), computed the same way from the end, gives the gradient with respect to the output at each time step, so the network can be trained with ordinary backpropagation through time.

In the lattice of the figure at the top, the bold line is an example path (C,C,βˆ’,A,A,βˆ’,T,T)(C, C, -, A, A, -, T, T). From each node there are three moves: stay in the same row, move down one row, or move down two rows (skipping a blank). However, a blank cannot move down two rows, and for targets with repeated characters (for example, the aaaa in aabaab), the blank between them cannot be skipped, because B\mathcal{B} would otherwise merge them into a single character.

In practice, the product of probabilities quickly becomes too small and rounds to 0 (underflow). The paper shows how to keep the values in range by dividing by the sum of αt\alpha_t at each time step, and to obtain ln⁑p(l∣x)\ln p(\mathbf{l} \mid \mathbf{x}) by adding up the logarithms of those sums. PyTorch's nn.CTCLoss also takes log probabilities rather than probabilities.

Why it can learn without segmentation

CTC can learn without segmentation because, instead of deciding "which character to output at which time step," it sums the probabilities of every possible alignment.

  • The alignment is left to the network: The loss depends only on the target string, not on character durations or boundary positions. The network itself decides during training where to output characters.
  • The blank absorbs time steps that output nothing: There are usually far more input time steps than characters. Thanks to the blank, the gaps between characters and the long stretches during which a single character is pronounced can be filled with blanks or repetitions of the same character. The blank also distinguishes the two aas in words with repeated characters (for example, aabaab).
  • The outputs become "spiky": In Figure 1 of the paper, the trained CTC network emitted a short, high-probability output (a spike) for each character, with blanks occupying the time in between. Reading the spikes in order gives the string directly.

To obtain a string from a trained network (decoding), the paper uses two approximations.

  • Best path decoding: Pick the most probable symbol at each time step, line them up, and collapse with B\mathcal{B}. It is simple to compute, but there is no guarantee of obtaining the most probable string.
  • Prefix search decoding: A modification of the forward-backward computation that searches by extending candidates from the start of the string. Given enough time it finds the most probable string, but the number of candidates grows exponentially with the input length, so the paper splits the sequence at time steps where the blank probability is high before searching.

Experimental results

The paper transcribed phoneme sequences on the TIMIT English speech data (4,620 training utterances, 1,680 test utterances, 61 phonemes) and compared systems by label error rate (LER). LER is the edit distance between the prediction and the target (the minimum number of insertions, substitutions, and deletions) divided by the total number of target labels; lower is better. The metric that measures the same thing at the word level is WER.

The CTC network is a bidirectional LSTM (BLSTM) with 100 LSTM blocks in each of the forward and backward directions, and the output layer has 62 units: 61 phonemes plus the blank. The HMM-RNN hybrid it was compared with (BLSTM/HMM) also uses a BLSTM with the same structure.

SystemLER
HMM (context-independent)38.85%
HMM (context-dependent)35.21%
BLSTM/HMM33.84 Β± 0.06%
BLSTM/HMM (errors weighted by phoneme duration)31.57 Β± 0.06%
CTC (best path decoding)31.47 Β± 0.21%
CTC (prefix search decoding)30.51 Β± 0.19%

The CTC and BLSTM/HMM values are averages over 5 training runs.

  • CTC outperformed the HMM and the HMM-RNN hybrid: CTC with prefix search decoding had an error rate about 1 point lower than the best BLSTM/HMM.
  • No duration adjustment is needed: BLSTM/HMM reached its best result with a trick that weights errors on short and long phonemes equally, but the CTC loss depends only on the order of characters, not on durations or boundaries, so no such trick was needed.
  • Prefix search was slightly better: Its error rate was about 1 point lower than best path decoding.

Practical considerations

PyTorch's nn.CTCLoss makes it easy to get the blank index, the input shape, and the lengths wrong. The main points are as follows.

  • The default for blank is 0: Output index 0 is treated as the blank. To use the last output as the blank, as in the paper, specify blank=C-1. Do not put the blank index in the target strings targets.
  • log_probs has shape (T, N, C) and holds log probabilities: The order is time T, batch N, class C (the batch does not come first). Pass the output of log_softmax, not softmax probabilities or logits.
  • Always pass input_lengths and target_lengths: These give the true lengths of the padded sequences. Each value of input_lengths must be at most T.
  • If the input is too short, the loss becomes infinite: If no path exists, p=0p = 0 and the loss is infinite, which also breaks the gradients. Each place where the same character repeats needs one blank, so the input length must be at least "target length + number of places where the same character repeats." Setting zero_infinity=True zeroes out infinite losses and their gradients.

Keep the following points in mind as well.

  • reduction="mean" divides by the target length and then averages over the batch: With PyTorch's default, each sample's loss is divided by its target length. For a plain sum like Eq. (12) of the paper, use reduction="sum".
  • targets can be passed in two forms: Padded and stacked as (N, S), or unpadded and concatenated into 1-D. In the 1-D form, the sum of target_lengths must equal the length of the tensor.
  • Results on GPU may differ from run to run: CUDA and cuDNN may choose nondeterministic algorithms. torch.backends.cudnn.deterministic = True avoids this but can be slower.
  • Outputs at different time steps are assumed independent: Because a path's probability is the product of per-time-step probabilities, dependencies between outputs (the continuity of the character sequence) are not modeled explicitly. The paper's discussion also lists not explicitly modeling inter-label dependencies as a characteristic of CTC.
  • Not suited to tasks that need boundary positions: CTC does not explicitly segment the input, so the paper notes it is hard to use for tasks where the segmentation itself is required (while noting it may work for tasks such as keyword spotting, where approximate positions suffice).
  • Prone to overfitting: The paper reports that generalization was especially difficult with CTC and that regularization by adding Gaussian noise to the inputs (standard deviation 0.6) helped.

Comparison with other methods

The table compares sequence labeling methods from the viewpoints used in the paper.

MethodTargets needed for trainingHow outputs become stringsAlignment between time steps and characters
Per-time-step classification (cross-entropy)Per-time-step labels (segmented data)Needs post-processingGiven as targets
HMMStrings (boundaries estimated during training)Decode with the HMMRepresented by HMM states
HMM-RNN hybridStrings (the HMM forces a segmentation used to train the RNN)Decode with the HMMThe HMM segments, the RNN classifies each time step
CTCStrings onlyRead the spikes (best path, prefix search)Sum the probabilities of all alignments

Rules of thumb for choosing:

  • If the input sequence is longer than the output string and no segmentation targets exist, use CTC: It suits tasks such as speech recognition and handwriting recognition, where input and output lengths differ and boundaries are ambiguous. It assumes the input length TT is at least the target length UU.
  • If per-time-step targets exist and the segmentation itself is to be predicted, use per-time-step classification: CTC does not output boundaries explicitly.

PyTorch example

Show code
python
import itertools
import math

import torch
import torch.nn as nn
import torch.nn.functional as F

# ── Basic usage of nn.CTCLoss ──
T, N, C = 50, 2, 20                        # input time steps, batch, number of classes (index 0 is the blank)
S = 10                                      # maximum length of the padded targets

logits = torch.randn(T, N, C, requires_grad=True)   # network output (shape (T, N, C))
log_probs = logits.log_softmax(dim=2)               # pass log probabilities (not probabilities or logits)

targets = torch.randint(1, C, (N, S), dtype=torch.long)     # 1 to Cβˆ’1: never include the blank 0
input_lengths = torch.tensor([50, 42], dtype=torch.long)    # true length of each sequence (at most T)
target_lengths = torch.tensor([10, 7], dtype=torch.long)    # true length of each target (at most S)

ctc = nn.CTCLoss(blank=0, reduction="mean", zero_infinity=True)
loss = ctc(log_probs, targets, input_lengths, target_lengths)  # divide by target length, then average over the batch
loss.backward()


# ── Checking the definition: sum the probabilities of all paths that collapse to the target (brute force on a small example) ──
def collapse(path, blank=0):
    """Mapping B: merge repeated consecutive symbols, then remove blanks"""
    merged = [k for i, k in enumerate(path) if i == 0 or k != path[i - 1]]
    return [k for k in merged if k != blank]


T2, C2 = 4, 3                               # 0 = blank, 1 = a, 2 = b
lp = torch.randn(T2, 1, C2).log_softmax(dim=2)
target = [1, 2]                             # target "ab"
total = 0.0
for path in itertools.product(range(C2), repeat=T2):
    if collapse(list(path)) == target:
        total += math.exp(sum(lp[t, 0, k].item() for t, k in enumerate(path)))
loss_ref = -math.log(total)
loss_ctc = F.ctc_loss(lp, torch.tensor([target]), torch.tensor([T2]), torch.tensor([2]),
                      blank=0, reduction="sum")          # match the sum (Eq. (12) of the paper)
print(loss_ref, loss_ctc.item())            # the two values match


# ── Best path decoding: pick the most probable symbol at each time step and collapse with B ──
def best_path_decode(log_probs, input_lengths, blank=0):
    best = log_probs.argmax(dim=2)          # (T, N)
    return [collapse(best[: input_lengths[n], n].tolist(), blank) for n in range(best.size(1))]


print(best_path_decode(log_probs.detach(), input_lengths))

FAQ

Q. What is the blank for?
A.

It has two roles. One is to fill time steps that output no character: there are more input time steps than characters, so the gaps between and around characters are filled with blanks. The other is to separate repeated characters: the mapping B\mathcal{B} merges repeated consecutive symbols into one, so outputting aaaa requires a blank in between, as in aβˆ’aa{-}a.

Q. The loss becomes inf or nan. What should I do?
A.

In most cases, the input is too short for the target, so not a single path collapses to the target. The input length must be at least "target length + number of places where the same character repeats." Check that input_lengths and target_lengths are correct and that the targets do not contain the blank index (0 by default); if the problem remains, use zero_infinity=True to zero out infinite losses and gradients.

Q. How do I get strings out of a trained model?
A.

The simplest way is best path decoding: pick the most probable symbol at each time step, merge repeated symbols, and then remove blanks. The paper also presents the more accurate prefix search decoding, which lowered the label error rate on TIMIT by about 1 point.

References

  1. A. Graves, S. FernΓ‘ndez, F. Gomez, and J. Schmidhuber, "Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks," ICML, 2006.
  2. PyTorch Documentation, "torch.nn.CTCLoss."