Simple Algorithm
Deep Learning · Emergence · 28 min

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 UU with rr adjacent repeats has (T+U−r2U)\binom{T+U-r}{2U} alignments to TT frames.
  • Derive the forward recursion over the 2U+12U+1 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 TT frames must be mapped to a shorter label sequence l\mathbf l of length U≤TU\le T, and the training data give only l\mathbf l, 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.

DerivationCounting alignments
  1. b0+n1+b1+n2+⋯+nU+bU=T,ni≥1,bi≥0b_0+n_1+b_1+n_2+\dots+n_U+b_U=T,\qquad n_i\ge1,\quad b_i\ge0

    Proposition. If l\mathbf l has UU labels, rr of which repeat the label just before them, exactly (T+U−r2U)\binom{T+U-r}{2U} paths of length TT collapse to l\mathbf l, and none when T<U+rT<U+r. Proof. A path that collapses to l\mathbf l is a run of blanks, a run of l1l_1, a run of blanks, and so on, ending with a run of lUl_U and a run of blanks: 2U+12U+1 runs whose lengths sum to TT.

  2. bi≥1whenever li+1=li(r such i)b_i\ge1\quad\text{whenever }l_{i+1}=l_i\qquad(r\text{ such }i)

    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.

  3. ∣B−1(l)∩(L∪{∅})T∣=((T−U−r)+2U2U)=(T+U−r2U)■\big|\mathcal B^{-1}(\mathbf l)\cap(L\cup\{\varnothing\})^T\big|=\binom{(T-U-r)+2U}{2U}=\binom{T+U-r}{2U}\qquad\blacksquare

    Remove the U+rU+r compulsory frames. The remaining T−U−rT-U-r frames are distributed freely over the 2U+12U+1 runs, which "stars and bars" counts:

  4. (23060)≈1.3×1056\binom{230}{60}\approx1.3\times10^{56}

    The count explodes. Two seconds of speech at 100 frames per second, T=200T=200, spelling U=30U=30 characters with no repeats, has about 105610^{56} alignments. The sum defining p(l∣x)p(\mathbf l\mid\mathbf x) needs a dynamic program.

Predict before you look

How many paths of length T=5T=5 collapse to the label abab?

Show the answer

35

U=2U=2 and r=0r=0, so (5+24)=(74)=35\binom{5+2}{4}=\binom74=35: the T−U=3T-U=3 spare frames are spread over the five runs ∅∗a+∅∗b+∅∗\varnothing^*a^+\varnothing^*b^+\varnothing^*. For the label aaaa the blank between the two aa's is compulsory, and the count drops to (64)=15\binom{6}{4}=15.

The forward recursion, and a gradient for free

Interleave blanks with the label to get the blank-extended label l′=(∅,l1,∅,l2,…,lU,∅)\mathbf l'=(\varnothing,l_1,\varnothing,l_2,\dots,l_U,\varnothing), with ∣l′∣=2U+1|\mathbf l'|=2U+1 states. A valid path walks through these states from left to right, one per frame. Let αt(s)\alpha_t(s) be the total probability of the path prefixes π1:t\pi_{1:t} that are consistent with l\mathbf l and occupy state ss at frame tt.

DerivationThe forward recursion
  1. α1(1)=y∅1,α1(2)=yl11,α1(s)=0  (s>2)\alpha_1(1)=y^1_{\varnothing},\qquad\alpha_1(2)=y^1_{l_1},\qquad\alpha_1(s)=0\ \ (s>2)

    A valid path starts in the leading blank or on the first label:

  2. αt(s)=yls′t(αt−1(s)+αt−1(s−1)+1[ls′≠∅, ls′≠ls−2′] αt−1(s−2))\alpha_t(s)=y^t_{l'_s}\Big(\alpha_{t-1}(s)+\alpha_{t-1}(s-1)+\mathbb 1\big[l'_s\ne\varnothing,\ l'_s\ne l'_{s-2}\big]\,\alpha_{t-1}(s-2)\Big)

    At each frame a path stays in its state, moves one state right, or skips a blank. The skip from s−2s-2 to ss 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.

  3. p(l∣x)=αT(2U+1)+αT(2U),about 3(2U+1)T operationsp(\mathbf l\mid\mathbf x)=\alpha_T(2U+1)+\alpha_T(2U),\qquad\text{about }3(2U+1)T\text{ operations}

    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 O(TU)\order{TU} instead of the exponential count of paths:

  4. ∑s=12U+1αt(s) βt(s)=p(l∣x)for every t\sum_{s=1}^{2U+1}\alpha_t(s)\,\beta_t(s)=p(\mathbf l\mid\mathbf x)\qquad\text{for every }t

    The mirror-image backward variables βt(s)\beta_t(s) sum the suffixes πt+1:T\pi_{t+1:T} that complete the label from state ss, excluding frame tt's own factor. Then αt(s)βt(s)\alpha_t(s)\beta_t(s) is the total probability of the valid paths that sit in state ss at frame tt, and every valid path sits in exactly one state at each frame:

DerivationProof
  1. p(l∣x)=∑π∈B−1(l)exp⁡(∑t′aπt′t′)p(\mathbf l\mid\mathbf x)=\sum_{\boldsymbol\pi\in\mathcal B^{-1}(\mathbf l)}\exp\Big(\sum_{t'}a^{t'}_{\pi_{t'}}\Big)

    Write the likelihood as a sum of exponentials of path scores. It is a partition function over the valid paths:

  2. ∂log⁡p∂akt=∑π1[πt=k] ∏t′yπt′t′∑π∏t′yπt′t′=P(πt=k∣π∈B−1(l),x)\frac{\partial\log p}{\partial a^t_k}=\frac{\sum_{\boldsymbol\pi}\mathbb 1[\pi_t=k]\,\prod_{t'}y^{t'}_{\pi_{t'}}}{\sum_{\boldsymbol\pi}\prod_{t'}y^{t'}_{\pi_{t'}}}=P\big(\pi_t=k\mid\boldsymbol\pi\in\mathcal B^{-1}(\mathbf l),\mathbf x\big)

    Differentiating picks out the paths that use kk at frame tt. 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.

  3. ∂log⁡p∂ukt=∑k′γt(k′)(δkk′−ykt)=γt(k)−ykt■\frac{\partial\log p}{\partial u^t_k}=\sum_{k'}\gamma_t(k')\big(\delta_{kk'}-y^t_k\big)=\gamma_t(k)-y^t_k\qquad\blacksquare

    The paths through state ss at frame tt have total probability αt(s)βt(s)\alpha_t(s)\beta_t(s), and several states can carry the same symbol (all the blanks, or repeated labels), which gives the sum over ss. Finally ak′t=uk′t−log⁡∑jeujta^t_{k'}=u^t_{k'}-\log\sum_je^{u^t_j} has ∂ak′t/∂ukt=δkk′−ykt\partial a^t_{k'}/\partial u^t_k=\delta_{kk'}-y^t_k, and ∑k′γt(k′)=1\sum_{k'}\gamma_t(k')=1:

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 (max⁡,×)(\max,\times) in place of (+,×)(+,\times) the recursion finds the single most probable path that collapses to l\mathbf l, the Viterbi or forced alignment, which gives each label a time stamp.

python
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 log⁡0\log0 so that unreachable states never produce 0⋅∞0\cdot\infty 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, l^=B(π∗)\hat{\mathbf l}=\mathcal B(\boldsymbol\pi^*) with πt∗=arg max⁡kykt\pi^*_t=\argmax_ky^t_k. Since frames are independent given the input, π∗\boldsymbol\pi^* 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 ℓ\ell it keeps two numbers: Pb(ℓ)P_b(\ell), the probability of the paths so far that collapse to ℓ\ell and end in a blank, and Pnb(ℓ)P_{nb}(\ell), those that end in ℓ\ell'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).

text
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_nb

With an unlimited beam, Pb(ℓ)+Pnb(ℓ)P_b(\ell)+P_{nb}(\ell) at the last frame is exactly p(ℓ∣x)p(\ell\mid\mathbf x) for every labeling ℓ\ell: every path is counted once, under the prefix it collapses to. A language model enters as a factor pLM(c∣ℓ)αp_{\text{LM}}(c\mid\ell)^{\alpha} on each extension, with a length bonus ∣ℓ∣β|\ell|^\beta 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.

Check your understanding

Three frames each give ya=0.4y_a=0.4 and y∅=0.6y_\varnothing=0.6. Which statement is true?

  1. Best-path decoding outputs aa, which is also the most probable labeling
  2. The most probable labeling is aaaa, since there are three frames to fill
  3. Best-path decoding outputs the empty labeling (probability 0.2160.216), but aa is more probable (probability 0.6880.688)
  4. The empty labeling, aa and aaaa are equally likely
Show the answer

C. Best-path decoding outputs the empty labeling (probability 0.2160.216), but aa is more probable (probability 0.6880.688)

The best path ∅∅∅\varnothing\varnothing\varnothing has probability 0.63=0.2160.6^3=0.216 and is the only path of the empty labeling. The six paths of aa (a∅∅a\varnothing\varnothing, ∅a∅\varnothing a\varnothing, ∅∅a\varnothing\varnothing a, aa∅aa\varnothing, ∅aa\varnothing aa, aaaaaa) sum to 3(0.4)(0.36)+2(0.16)(0.6)+0.064=0.6883(0.4)(0.36)+2(0.16)(0.6)+0.064=0.688, and aaaa has only a∅aa\varnothing a, with 0.0960.096. 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.

DerivationThe lattice recursion
  1. α(t,u)=α(t−1,u) ∅(t−1,u)+α(t,u−1) e(t,u−1)\alpha(t,u)=\alpha(t-1,u)\,\varnothing(t-1,u)+\alpha(t,u-1)\,e(t,u-1)

    Write ∅(t,u)=P(∅∣t,u)\varnothing(t,u)=P(\varnothing\mid t,u) and e(t,u)=P(yu+1∣t,u)e(t,u)=P(y_{u+1}\mid t,u). Let α(t,u)\alpha(t,u) be the probability of having emitted y1:uy_{1:u} while reading frame tt, with α(1,0)=1\alpha(1,0)=1. A path arrives by a blank from the previous frame or by a label from the same frame:

  2. p(y∣x)=α(T,U) ∅(T,U)p(\mathbf y\mid\mathbf x)=\alpha(T,U)\,\varnothing(T,U)

    Every alignment ends with a blank at the last lattice point. Alignments are strings of TT blanks and UU labels that end in a blank, (T+U−1U)\binom{T+U-1}{U} of them, summed in O(TU)\order{TU} steps:

  3. P(alignment∣x)=∏movesP(move∣ft, g(y1:u))P(\text{alignment}\mid\mathbf x)=\prod_{\text{moves}}P\big(\text{move}\mid\mathbf f_t,\ \mathbf g(y_{1:u})\big)

    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 gu\mathbf g_u:

Predict before you look

The recursion is cheap, but the joint network must be evaluated at every lattice point: N×T×(U+1)×∣V∣N\times T\times(U+1)\times|\mathcal V| logits. For N=32N=32 utterances, T=400T=400 encoder frames, U=100U=100 tokens and a character vocabulary of ∣V∣=5,000|\mathcal V|=5{,}000 (as for Chinese), in 4-byte floats, how many gigabytes do the logits alone take?

Show the answer

25.9 GB

32×400×101×5,000×432\times400\times101\times5{,}000\times4 bytes ≈25.9\approx25.9 GB, before gradients. Pruned RNN-T (Kuang et al., 2022) first runs a cheap joiner that is linear in ft\mathbf f_t and gu\mathbf g_u to find, for each frame, a band of S≪US\ll U label positions where the alignment can plausibly be, and evaluates the full joiner only there: with S=4S=4, about 1.01.0 GB.

PropertyCTCTransducerAttention encoder–decoder
Output dependencenone, given the inputeach emission depends on earlier labelsfully autoregressive, p(yu∣y<u,x)p(y_u\mid y_{<u},\mathbf x)
Alignmentmonotonic, one symbol per framemonotonic, any number of labels per framesoft attention, not constrained to be monotonic
Streamingyes, with a causal or limited-look-ahead encoderyes; widely used in deployed streaming recognizersnot natively: attends over the whole input
Typical rolefine-tuning self-supervised encoders; auxiliary lossstreaming speech recognitionoffline recognition and translation
Attention decoders such as Listen, Attend and Spell (Chan et al., 2016) are flexible and accurate, but they cannot start before the input ends, and on long or noisy inputs attention can skip or repeat. Joint CTC–attention training (Kim, Hori & Watanabe, 2017) adds a CTC loss on the encoder to keep attention monotonic. Self-supervised speech encoders such as wav2vec 2.0 (Baevski, Zhou, Mohamed & Auli, 2020) are fine-tuned with a CTC head, while Whisper (Radford et al., 2023) is an attention encoder–decoder.

Key takeaways

  • CTC adds a blank, scores frame-wise paths independently given the input, and sums over the (T+U−r2U)\binom{T+U-r}{2U} paths that collapse to the label; the forward recursion over the 2U+12U+1 states of the blank-extended label does it in O(TU)\order{TU}.
  • The gradient of log⁡p\log p with respect to the log-emissions is the posterior occupancy γt(k)\gamma_t(k), 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 O(TU)\order{TU}, but the joint network's N×T×(U+1)×∣V∣N\times T\times(U+1)\times|\mathcal V| 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.

Question 1

For the label hello\mathtt{hello}, how many states does the blank-extended label l′\mathbf l' have, and what is the smallest number of frames TT for which p(l∣x)p(\mathbf l\mid\mathbf x) can be positive?

  1. 10 states; T≥5T\ge5
  2. 11 states; T≥5T\ge5
  3. 11 states; T≥6T\ge6
  4. 6 states; T≥11T\ge11
Show the answer

C. 11 states; T≥6T\ge6

∣l′∣=2U+1=11|\mathbf l'|=2U+1=11. The double l\mathtt l needs a blank between its two letters, so T≥U+r=5+1=6T\ge U+r=5+1=6, for instance hel∅lo\mathtt{hel}\varnothing\mathtt{lo}, which is then the only alignment: (6+5−110)=1\binom{6+5-1}{10}=1.

Question 2

What is ∂log⁡p(l∣x)/∂log⁡ykt\partial\log p(\mathbf l\mid\mathbf x)/\partial\log y^t_k?

  1. ykty^t_k, the network's own output
  2. 11 if kk is the label aligned to frame tt by a forced alignment, and 00 otherwise
  3. αt(k) βt(k)\alpha_t(k)\,\beta_t(k)
  4. The posterior probability, given the input and the correct label, that the path emits kk at frame tt
Show the answer

D. The posterior probability, given the input and the correct label, that the path emits kk at frame tt

log⁡p\log p 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: γt(k)=1p∑s:ls′=kαt(s)βt(s)\gamma_t(k)=\frac1p\sum_{s:l'_s=k}\alpha_t(s)\beta_t(s). Through the softmax this becomes the familiar ykt−γt(k)y^t_k-\gamma_t(k) for the loss.

Question 3

Why can best-path decoding miss the most probable labeling of a CTC model?

  1. Because CTC's frames are not independent given the input, so the per-frame argmax is not the best path
  2. 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
  3. Because best-path decoding ignores blanks
  4. 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 (0.360.36) while aa collects 0.640.64 from three paths.

Question 4

What does a transducer's prediction network give it that CTC lacks?

  1. A monotonic alignment between frames and labels
  2. A blank symbol that lets frames emit nothing
  3. Emission probabilities that depend on the labels already emitted
  4. 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 y1:uy_{1:u} into gu\mathbf g_u, 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.