Alignment-Free Training: CTC & Transducers
Summing over every alignment with dynamic programming.
A speech recognizer hears 100 frames of audio per second and writes perhaps a dozen characters per second, and no one has marked which frame produced which character. CTC and transducers treat that alignment as a hidden variable and sum over all alignments exactly, although there are astronomically many. This lesson counts them, derives the dynamic programs over the alignment lattice, shows that their gradients come free from backpropagation, and decodes from them.
What you’ll learn
- Define CTC's path model and collapse map, and prove that a label of length with adjacent repeats has alignments to frames.
- Derive the forward recursion over the states of the blank-extended label, and prove that its gradient with respect to the log-emissions is the posterior occupancy, so that forward–backward is reverse-mode differentiation.
- Decode CTC by best path and by prefix beam search, and construct an input on which the most probable path does not give the most probable labeling.
- Derive the transducer's lattice recursion, explain the independence assumption it removes and the memory its joint network costs, and compare CTC, transducers and attention decoders for streaming.
Alignments as hidden variables
In speech recognition, handwriting recognition (Graves et al., 2009) and reading text in images, a long input of frames must be mapped to a shorter label sequence of length , and the training data give only , not which frames produced which label. An attention decoder could learn the alignment implicitly (Encoder–Decoder Models & Attention), but here something is known about it: it is monotonic, since the labels occur in the same order as the frames that produce them. Connectionist temporal classification (Graves, Fernández, Gomez & Schmidhuber, 2006) builds this into a hidden-variable model whose sum over alignments can be computed exactly.
Proposition. If has labels, of which repeat the label just before them, exactly paths of length collapse to , and none when . Proof. A path that collapses to is a run of blanks, a run of , a run of blanks, and so on, ending with a run of and a run of blanks: runs whose lengths sum to .
Label runs must be non-empty, and so must the blank run between two equal labels, or the two would merge into one. The run lengths determine the path, and the path determines them.
Remove the compulsory frames. The remaining frames are distributed freely over the runs, which "stars and bars" counts:
The count explodes. Two seconds of speech at 100 frames per second, , spelling characters with no repeats, has about alignments. The sum defining needs a dynamic program.
How many paths of length collapse to the label ?
Show the answer
35
and , so : the spare frames are spread over the five runs . For the label the blank between the two 's is compulsory, and the count drops to .
The forward recursion, and a gradient for free
Interleave blanks with the label to get the blank-extended label , with states. A valid path walks through these states from left to right, one per frame. Let be the total probability of the path prefixes that are consistent with and occupy state at frame .
A valid path starts in the leading blank or on the first label:
At each frame a path stays in its state, moves one state right, or skips a blank. The skip from to is allowed only into a label that differs from the label two states back: a blank state is entered only from its left neighbor, and skipping the blank between two equal labels would merge them.
A valid path ends on the last label or on the trailing blank. With at most three terms per state and frame, the cost is instead of the exponential count of paths:
The mirror-image backward variables sum the suffixes that complete the label from state , excluding frame 's own factor. Then is the total probability of the valid paths that sit in state at frame , and every valid path sits in exactly one state at each frame:
Write the likelihood as a sum of exponentials of path scores. It is a partition function over the valid paths:
Differentiating picks out the paths that use at frame . Divided by the total, this is a posterior probability: the derivative of a log-partition function is the expected count of the feature it multiplies.
The paths through state at frame have total probability , and several states can carry the same symbol (all the blanks, or repeated labels), which gives the sum over . Finally has , and :
So nobody needs to code the backward recursion: run the forward recursion in log space and let automatic differentiation produce the adjoints. Reverse-mode differentiation of the forward algorithm is the forward–backward algorithm (Eisner, 2016), and the same holds for every algorithm of this family. Swap the semiring and the lattice answers other questions: with in place of the recursion finds the single most probable path that collapses to , the Viterbi or forced alignment, which gives each label a time stamp.
import torch
import torch.nn.functional as F
def ctc_nll(logits, label, blank=0):
"""-log p(label | x) for one utterance; logits: (T, C), label: list of U >= 1 ids."""
lp = F.log_softmax(logits, dim=-1)
ext = [blank]
for c in label:
ext += [c, blank] # blank-extended label: 2U + 1 states
S, NEG = len(ext), -1e30 # NEG stands in for log 0
can_skip = torch.tensor([s >= 2 and ext[s] != blank and ext[s] != ext[s - 2] for s in range(S)])
emit = lp[:, ext] # (T, S) log-emission of each state
alpha = torch.where(torch.arange(S) < 2, emit[0], torch.full((S,), NEG))
for t in range(1, emit.size(0)):
step = F.pad(alpha[:-1], (1, 0), value=NEG) # from state s - 1
skip = torch.where(can_skip, F.pad(alpha[:-2], (2, 0), value=NEG), torch.full((S,), NEG))
alpha = torch.logsumexp(torch.stack([alpha, step, skip]), dim=0) + emit[t]
return -torch.logsumexp(alpha[-2:], dim=0) # end on the last label or last blank
# With logits.requires_grad_(), ctc_nll(logits, label).backward() leaves softmax(logits) - gamma in logits.grad.
# Same value: F.ctc_loss(F.log_softmax(logits, -1)[:, None], torch.tensor([label]),
# torch.tensor([T]), torch.tensor([U]), reduction='sum')The forward recursion in log space, where products become sums and sums become logsumexp. A large negative number stands in for so that unreachable states never produce in the backward pass. Production code batches utterances and uses F.ctc_loss, which implements the same recursion with a hand-written backward pass.
Decoding: best path versus best labeling
Best-path decoding takes the most probable symbol at every frame and collapses the result, with . Since frames are independent given the input, really is the most probable path. But a labeling's probability sums over all of its paths, and a labeling with many moderately likely paths can beat the one that owns the single best path.
Prefix beam search searches over labelings instead. For every candidate prefix it keeps two numbers: , the probability of the paths so far that collapse to and end in a blank, and , those that end in 's last label. The split matters because the next symbol acts differently on the two: after a blank, repeating the last label appends a new copy, but right after that label it merges into it (Hannun, Maas, Jurafsky & Ng, 2014).
CTC-PREFIX-BEAM-SEARCH(frame distributions y¹ … y^T, beam width k)
P_b(ε) ← 1; P_nb(ε) ← 0 // ε is the empty prefix
for t = 1 … T:
P_b′, P_nb′ ← new tables, all 0
for each kept prefix ℓ, with last label e:
P_b′(ℓ) += y^t(∅) · (P_b(ℓ) + P_nb(ℓ)) // a blank keeps the prefix
P_nb′(ℓ) += y^t(e) · P_nb(ℓ) // e right after e merges (skip if ℓ = ε)
for each label c:
if c = e: P_nb′(ℓc) += y^t(c) · P_b(ℓ) // a repeat needs a blank in between
else: P_nb′(ℓc) += y^t(c) · (P_b(ℓ) + P_nb(ℓ))
keep the k prefixes with the largest P_b′ + P_nb′
return the kept prefix with the largest P_b + P_nbWith an unlimited beam, at the last frame is exactly for every labeling : every path is counted once, under the prefix it collapses to. A language model enters as a factor on each extension, with a length bonus against its bias toward short outputs ("shallow fusion"; Hannun et al. scored whole words). That is how CTC systems recover the dependence between labels that the model itself leaves out.
Three frames each give and . Which statement is true?
- Best-path decoding outputs , which is also the most probable labeling
- The most probable labeling is , since there are three frames to fill
- Best-path decoding outputs the empty labeling (probability ), but is more probable (probability )
- The empty labeling, and are equally likely
Show the answer
C. Best-path decoding outputs the empty labeling (probability ), but is more probable (probability )
The best path has probability and is the only path of the empty labeling. The six paths of (, , , , , ) sum to , and has only , with . The three add up to one.
Transducers: emissions that depend on the past
CTC's independence assumption is strong. Given the input, the symbol at one frame says nothing about the symbol at another, so nothing in the model can make one word's spelling depend on how another was spelled, except through the encoder's view of the audio. CTC systems lean on an external language model for that. The transducer (RNN-T; Graves, 2012) keeps the monotonic lattice and removes the assumption.
Write and . Let be the probability of having emitted while reading frame , with . A path arrives by a blank from the previous frame or by a label from the same frame:
Every alignment ends with a blank at the last lattice point. Alignments are strings of blanks and labels that end in a blank, of them, summed in steps:
The topology differs from CTC's: a frame can emit several labels, and there are no label repeats to merge. More importantly, every move's probability depends on the labels already emitted, through :
The recursion is cheap, but the joint network must be evaluated at every lattice point: logits. For utterances, encoder frames, tokens and a character vocabulary of (as for Chinese), in 4-byte floats, how many gigabytes do the logits alone take?
Show the answer
25.9 GB
bytes GB, before gradients. Pruned RNN-T (Kuang et al., 2022) first runs a cheap joiner that is linear in and to find, for each frame, a band of label positions where the alignment can plausibly be, and evaluates the full joiner only there: with , about GB.
| Property | CTC | Transducer | Attention encoder–decoder |
|---|---|---|---|
| Output dependence | none, given the input | each emission depends on earlier labels | fully autoregressive, |
| Alignment | monotonic, one symbol per frame | monotonic, any number of labels per frame | soft attention, not constrained to be monotonic |
| Streaming | yes, with a causal or limited-look-ahead encoder | yes; widely used in deployed streaming recognizers | not natively: attends over the whole input |
| Typical role | fine-tuning self-supervised encoders; auxiliary loss | streaming speech recognition | offline recognition and translation |
Key takeaways
- CTC adds a blank, scores frame-wise paths independently given the input, and sums over the paths that collapse to the label; the forward recursion over the states of the blank-extended label does it in .
- The gradient of with respect to the log-emissions is the posterior occupancy , so reverse-mode differentiation of the forward recursion is the forward–backward algorithm; the max-product version gives forced alignments.
- Best-path decoding finds the most probable path, not labeling; prefix beam search sums each prefix's paths, keeping blank-ending and label-ending mass apart, and can fuse a language model.
- Transducers add a prediction network, so emissions depend on earlier labels; their lattice recursion is still , but the joint network's logits dominate memory, which pruned training cuts.
- CTC and transducers stream naturally; attention encoder–decoders need the whole input but are not tied to monotonic alignments.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For the label , how many states does the blank-extended label have, and what is the smallest number of frames for which can be positive?
- 10 states;
- 11 states;
- 11 states;
- 6 states;
Show the answer
C. 11 states;
. The double needs a blank between its two letters, so , for instance , which is then the only alignment: .
What is ?
- , the network's own output
- if is the label aligned to frame by a forced alignment, and otherwise
- The posterior probability, given the input and the correct label, that the path emits at frame
Show the answer
D. The posterior probability, given the input and the correct label, that the path emits at frame
is a log-partition function over the valid paths, and its derivative with respect to a log-emission is the expected count of that emission: . Through the softmax this becomes the familiar for the loss.
Why can best-path decoding miss the most probable labeling of a CTC model?
- Because CTC's frames are not independent given the input, so the per-frame argmax is not the best path
- Because a labeling's probability sums over all paths that collapse to it, and the single best path may belong to a labeling with less total mass
- Because best-path decoding ignores blanks
- It cannot: the most probable path always collapses to the most probable labeling
Show the answer
B. Because a labeling's probability sums over all paths that collapse to it, and the single best path may belong to a labeling with less total mass
The per-frame argmax is the most probable path, because CTC's path probability factorizes over frames. But labelings aggregate paths: in the two-frame example the empty labeling owns the best path () while collects from three paths.
What does a transducer's prediction network give it that CTC lacks?
- A monotonic alignment between frames and labels
- A blank symbol that lets frames emit nothing
- Emission probabilities that depend on the labels already emitted
- The ability to emit labels while the input is still arriving
Show the answer
C. Emission probabilities that depend on the labels already emitted
The prediction network turns into , which enters every emission probability through the joint network. CTC's path probabilities factorize over frames given the input, so they cannot depend on earlier outputs.
Further reading
- A. Graves, S. Fernández, F. Gomez & J. Schmidhuber, "Connectionist temporal classification: Labelling unsegmented sequence data with recurrent neural networks," ICML (2006).
- A. Graves, "Sequence transduction with recurrent neural networks," ICML Workshop on Representation Learning, arXiv:1211.3711 (2012).
- A. Y. Hannun, A. L. Maas, D. Jurafsky & A. Y. Ng, "First-pass large vocabulary continuous speech recognition using bi-directional recurrent DNNs," arXiv:1408.2873 (2014).
- J. Eisner, "Inside-outside and forward-backward algorithms are just backprop (tutorial paper)," Workshop on Structured Prediction for NLP (2016).
- F. Kuang, L. Guo, W. Kang, L. Lin, M. Luo, Z. Yao & D. Povey, "Pruned RNN-T for fast, memory-efficient ASR training," Interspeech (2022).
- A. Hannun, "Sequence modeling with CTC," Distill (2017), distill.pub/2017/ctc.