What Is CTC? Learn Alignment-Free Sequence Training and Decoding
Connectionist Temporal Classification (CTC) trains sequence models without pre-aligning input frames to target labels. Learn the blank-and-repeat collapse rule, how CTC loss differs from decoding, and how to check sequence lengths in PyTorch.
What Is CTC? Alignment-Free Sequence Training and Decoding
Connectionist Temporal Classification (CTC) lets a model learn a target label sequence from an input sequence without assigning each target label to a specific input frame in advance. The model predicts label probabilities over time; the CTC loss sums the probabilities of possible alignment paths that collapse to the target. CTC is a sequence-labeling method, not the name of one neural-network architecture.
How blank and repeated labels collapse
CTC adds a blank symbol to the label set. Blank means “no new label at this time”; it is not the same as a space between words. To turn a frame-by-frame path into a label sequence, first merge consecutive copies of the same symbol, then remove blanks.
For labels a, b, and _ (blank):
a a b b → ab
a _ a → aa
_ a a _ b _ → ab
The order matters: repeated symbols are merged before blanks are removed, so two identical labels separated by blank both remain. To emit the two consecutive o characters in “book,” a valid path needs a blank between them: b o _ o k collapses to “book,” while b o o k collapses to “bok.” This is an illustrative example of the CTC rule.
The loss sums over possible alignments
For an input of T frames and a target of U labels, CTC considers paths containing a label or blank at each time step. Many paths can collapse to the same target. CTC sums their probabilities and optimizes the model to raise the target sequence probability. This removes the need for frame-level boundary labels during training.
A target cannot be longer than the input in frames. In addition, adjacent repeated target labels may require an extra blank time step to separate them. Therefore, checking only that target length is no greater than input length is insufficient; verify that each target has a valid alignment after accounting for repeats.
The loss and decoding are separate stages. The loss scores paths corresponding to the known target during training. A decoder chooses an output sequence from the model’s frame-level scores.
Greedy decoding and its limitation
The simplest decoder selects the highest-probability symbol at each frame, then applies the collapse rule. This is fast, but the most probable individual path is not guaranteed to produce the most probable label sequence: the probabilities of several paths for another sequence may add up to more. Beam search keeps multiple candidate prefixes and combines path probabilities. A decoder may also add a language-model score; evaluate that result separately from an acoustic-model-only output.
CTC path probabilities factor across time steps given the model’s output distributions. This does not prevent the encoder from using input context to produce each frame’s distribution. However, CTC does not directly model label-to-label language dependencies in the path score; a decoder or language model can supply additional context.
Using PyTorch CTCLoss
In PyTorch 2.15, torch.nn.CTCLoss accepts log probabilities shaped (T, N, C), targets, input lengths, and target lengths. T is the number of frames, N the batch size, and C the number of classes including blank. Log probabilities are typically produced with log_softmax. The default blank index is 0, and targets must not contain the blank label.
import torch.nn.functional as F
# logits: (time, batch, classes), blank class index = 0
log_probs = F.log_softmax(logits, dim=2)
loss_fn = torch.nn.CTCLoss(blank=0, zero_infinity=False)
loss = loss_fn(log_probs, targets, input_lengths, target_lengths)input_lengths must contain each example’s real frame count, excluding padding; target_lengths contains target-label counts, also excluding padding. Passing the padded maximum length for every example can make padding appear to be valid input. zero_infinity=True can zero infinite losses and gradients for unalignable inputs, but it does not fix incorrect lengths, labels, or model output lengths. Inspect the affected examples first.
When loss is infinite or results look wrong
Check that log_probs is ordered (time, batch, classes) and was passed through log_softmax.
Confirm that input_lengths and target_lengths are true lengths paired with the right examples.
Make sure the blank index matches the model output and is absent from targets.
Find examples with too few frames or repeats that leave no valid alignment. Check data and frame counts after model downsampling before hiding infinite losses.
Check reduction. PyTorch’s default mean divides each example’s loss by its target length, then averages the batch. Its values will differ from sum or per-example loss.
CTC is useful when the input is ordered, as in speech or handwriting recognition, but exact label timing is difficult and the output sequence matters. It does not directly train frame boundaries. For meaningful comparisons, record the collapse rule, decoder and language-model use, input-length calculation, and target-label units.
References
Alex Graves et al., [Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks](https://www.cs.toronto.edu/~graves/icml_2006.pdf), ICML 2006.
PyTorch 2.15, [torch.nn.CTCLoss](https://docs.pytorch.org/docs/2.15/generated/torch.nn.CTCLoss.html)
Thomas Zenkel et al., [Comparison of Decoding Strategies for CTC Acoustic Models](https://arxiv.org/abs/1708.04469), 2017.