The earlier lessons of this course built an LSTM, the CTC loss and a greedy decoder, each for one sequence at a time. A working recognizer also needs a way to train on batches of sequences with different lengths, and an error measure for outputs whose length can be wrong. This capstone pairs with Lecture 15 and Lab 9 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the whole loop in PyTorch: pad and pack a batch, run a bidirectional LSTM, train it with CTC, decode and score by edit distance.
pad_batch travel with the batch. The encoder, the loss and the decoder each read them, so none of them ever treats padding as data.A batch is a tensor of shape (T_max, N, D): the longest sequence sets T_max, shorter ones are filled with zeros, and a vector of N true lengths records where each one ends. The tensor alone misdescribes the data, so the LSTM, the loss and the decoder all need the lengths.
The LSTM is where this goes wrong quietly. A bidirectional layer also runs from the last row of the tensor towards the first. For a short sequence that row is padding, so the backward pass reads zeros before the real frames and the outputs depend on the neighbours' lengths. The forward pass is safe, because its padding comes after the real frames. A 4-frame sequence padded to 9 frames, against the same sequence alone:
import torch
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
torch.manual_seed(0)
lstm = torch.nn.LSTM(3, 8, bidirectional=True)
short = torch.randn(4, 1, 3) # 4 real frames
padded = torch.cat([short, torch.zeros(5, 1, 3)]) # padded to 9
with torch.no_grad():
alone, _ = lstm(short)
plain, _ = lstm(padded)
packed, _ = lstm(pack_padded_sequence(padded, torch.tensor([4]), enforce_sorted=False))
packed, _ = pad_packed_sequence(packed, total_length=9)
def gap(out, half): # half 0: forward, 1: backward
h = slice(8 * half, 8 * half + 8)
return round((out[:4, :, h] - alone[:, :, h]).abs().max().item(), 4)
print(gap(plain, 0), gap(plain, 1), gap(packed, 1))The forward half is identical and the backward half is off by 0.1216. Packing with the true lengths removes the gap. Remember the property: a sequence gets the same outputs whatever batch it is in. The hidden test enforces it to 1e-5; a model without packing misses by about 0.02.
torch.nn.functional.ctc_loss takes log-probabilities of shape (T, N, C), all targets concatenated into one 1-D tensor, and two length vectors: valid frames per input and labels per target. Its default reduction divides each sequence's loss by its target length and then averages. This build uses reduction="sum" and divides by N, the mean negative log-likelihood per sequence. The two differ by a target-dependent factor, so check which one you are comparing.
import torch
F = torch.nn.functional
torch.manual_seed(0)
lp = torch.randn(6, 2, 4).log_softmax(-1) # (T, N, C), class 0 is the blank
labels = torch.tensor([1, 2, 3, 2, 2]) # targets [1, 2, 3] and [2, 2], concatenated
frames, sizes = torch.tensor([6, 6]), torch.tensor([3, 2])
each = F.ctc_loss(lp, labels, frames, sizes, reduction="none")
print([round(v, 3) for v in each.tolist()])
print(round(F.ctc_loss(lp, labels, frames, sizes).item(), 3), round(each.sum().item() / 2, 3))
short = torch.tensor([6, 2]) # two frames cannot spell [2, 2]
print(F.ctc_loss(lp, labels, short, sizes, reduction="none").tolist()[1])
print(F.ctc_loss(lp, labels, short, sizes, reduction="none", zero_infinity=True).tolist()[1])The default gives 2.304, the mean of 4.624 / 3 and 6.135 / 2; the per-sequence mean used here is 5.38. The last two lines show a target with no alignment. A target needs one frame per label plus one for every pair of equal neighbours, which a blank must separate. The target [2, 2] needs three frames, so with two the loss is infinite. zero_infinity=True turns that into 0 with zero gradient, so the sequence silently stops contributing.
Decode each sequence by taking the best class of each of its first lengths[n] frames (ties go to the lowest index, so blank wins a tie), merging runs of equal neighbours, and only then removing blanks. Frames 1 0 1 decode to [1, 1], because the blank keeps the labels apart, while frames 1 1 decode to [1]. Frames past the length hold model outputs for padding, possibly confident labels, so cut them off.
Per-position accuracy fails when the length is wrong: one early deletion shifts every later label. The edit distance is the fewest insertions, deletions and substitutions that turn one sequence into the other. Cell (i, j) of its table is the distance between the first i labels of one sequence and the first j of the other. The first row and column cost the prefix length. Every other cell is the smallest of the cell above plus 1 (a deletion), the cell to the left plus 1 (an insertion), and the diagonal cell plus 0 or 1 (a match or a substitution).
The label error rate adds the edit distances over the whole set and divides once by the total number of reference labels. It is not the mean of per-sequence ratios, which lets a one-label utterance count as much as a nine-label one.
edits = [1, 1] # one wrong label in each utterance
labels = [9, 1] # reference lengths
print(round(sum(edits) / sum(labels), 3), round(sum(e / n for e, n in zip(edits, labels)) / 2, 3))The first number, 0.2, is the label error rate; 0.556 is the mean of ratios. The rate can also exceed 1: five output labels against a one-label reference cost at least four edits, a rate of 4.0 or more.
Training ties the pieces together: each step draws a random batch, pads it, runs the model, takes the CTC loss and makes one Adam step. On the hidden tests' synthetic data (4 labels, 6 features, 2 to 4 noisy prototype frames per label with 0 to 2 silent frames between; 120 training and 60 held-out sequences; 80 steps of 16) the loss per sequence falls from 3.6, averaged over the first 20 steps, to 0.03 over the last 20. The held-out label error rate falls from 0.78 for the untrained model to 0.01.
Four mistakes recur: a decoder that reads every frame, so padding adds labels; one that removes blanks before merging, so repeats collapse; an error rate that averages ratios; and a loss compared across reductions. Forgetting to pack shows up only in the invariance test.
The tests check each piece independently: invariance on a seeded model, the loss against PyTorch and against a sum over every alignment, the edit distance against a slow recursive version on every pair of short sequences. A low held-out error rate shows the pipeline is wired correctly, not that this model would recognize speech or handwriting: the data is synthetic and both sets come from one recipe. Real recognizers add learned or spectral features, deeper encoders and beam search with a language model.