A speech model hears T frames of audio and has to write a few letters. Nobody marked which frame belongs to which letter, and the output is far shorter than the input, so an ordinary per-frame cross-entropy has nothing to compare against. Connectionist temporal classification (CTC) removes the need for that labelling. This lesson pairs with Lectures 15 and 16 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the CTC loss with the forward algorithm, plus the collapse rule and a greedy decoder, and check them against brute force and PyTorch.
The model emits one distribution per frame over the C symbols: the real labels plus one extra symbol, the blank. An alignment is one symbol for every frame, so T symbols in all. The collapse rule turns an alignment into an output in two steps, in this order: merge every run of equal neighbours into one symbol, then delete the blanks.
The blank does two jobs. It lets a label repeat, because a, blank, a collapses to two a's while a, a collapses to one. It also lets a frame say that nothing new is happening, so most frames can be blank.
The probability of a target is not the probability of one alignment. It is the sum over every alignment that collapses to it, each alignment scored as the product of its frame probabilities. Count them for a tiny case.
from itertools import groupby, product
def collapse(path):
return [label for label, _ in groupby(path) if label != 0]
print(collapse([0, 1, 1, 0, 1, 2, 2, 0]))
paths = [p for p in product(range(3), repeat=4) if collapse(p) == [1, 2]]
print(len(paths), "of", 3 ** 4)With 3 symbols and 4 frames, 15 of the 81 possible alignments spell a, b. Enumeration grows as C^T, which is hopeless at real sizes; the forward algorithm gets the same sum in O(T · S) steps.
Build the extended target first: a blank before every label, between neighbours and after the last one. For a target of length L it has S = 2L + 1 states, so a, b becomes blank, a, blank, b, blank. Let alpha[t][s] be the total probability of all partial alignments that end in state s at frame t, counting the symbol that state s emits at frame t. State s can be entered three ways from frame t - 1:
- stay in s, repeating the symbol
- advance from s - 1
- skip from s - 2, which jumps over the blank between two labels; allowed only when s is a label and differs from the label at s - 2
The skip must be refused between equal labels. For a, a the blank between the copies is the only thing that keeps them apart, so jumping over it would merge them. An alignment starts in state 0 or 1, and it is complete when it ends in state S - 1 or S - 2, since the last label does not need a trailing blank.
Probabilities of a long input underflow, so the real recurrence runs in log space. Where the table above adds the predecessors and multiplies by a probability, the code uses np.logaddexp over the predecessors and adds a log-probability. The final answer is the loss: minus the log of that last sum. A target that cannot fit gives alpha = minus infinity everywhere in the last frame and the loss is infinity. The shortest input that can spell a target is its length plus the number of neighbouring equal labels, so a, a needs 3 frames. The next snippet shows why log space matters: 400 frames of probability 0.1 multiply to exactly 0.0 in float64, while their logs add to about -921. It also prints how many alignments 100 frames and 30 symbols allow, which is why enumeration is out.
import math
print(0.1 ** 400, round(400 * math.log(0.1), 1))
print(f"{30 ** 100:.2e}")Greedy decoding takes the best symbol in each frame and collapses the result. It finds the best single alignment, which is not the same as the most probable output, because an output's probability is spread over many alignments. The table above came from this matrix:
from itertools import groupby, product
import numpy as np
P = np.array([[0.5, 0.3, 0.2], [0.3, 0.4, 0.3], [0.41, 0.19, 0.4], [0.6, 0.1, 0.3]])
totals = {}
for path in product(range(3), repeat=4):
out = tuple(label for label, _ in groupby(path) if label != 0)
totals[out] = totals.get(out, 0.0) + float(np.prod(P[range(4), path]))
greedy = tuple(label for label, _ in groupby(P.argmax(axis=1).tolist()) if label != 0)
best = max(totals, key=totals.get)
print(greedy, round(totals[greedy], 4))
print(best, round(totals[best], 4))Greedy reads blank, a, blank, blank and returns a, with total probability 0.1695, while a, b has 0.2794. Searching over output prefixes and adding up their alignments does better. The next lesson builds beam search for the simpler case of a model that predicts one token at a time.
Four mistakes recur. Allowing the s - 2 skip between equal labels counts alignments that merge a repeat. Summing only the last state at the end drops every alignment that finishes on the final label. Deleting blanks before merging turns a, blank, a into a single a. And a blank index written as 0 in one place breaks any model that puts the blank elsewhere.
The hidden tests compare the loss with an enumeration of all alignments for small cases and with PyTorch's ctc_loss on a longer input, including repeats, an empty target, impossible targets and a nonzero blank. Agreement shows that your sum is the CTC probability of the target. It does not show that the model is good, and it says nothing about decoding quality: the greedy decoder can agree with its own definition and still return a worse output than the best one. You also build no backward pass here. Training would use autograd, or a backward table of the same shape.