Lab: the CTC forward recursion, blanks and repeats
Audio lab A. Replace path listing with the forward recursion, check that both give the same probability, see why a doubled letter needs a spare frame, and watch what the blank probability does to the loss.
What runs in CodeSplash
- AUD001Connectionist temporal classification (CTC) Explained here
You will be able to
- Build the blank-padded label sequence and the forward table for a transcript
- Check the recursion against brute-force path listing in Python and R
- Explain why repeated labels need a separating blank and enough frames
- Predict how the blank probability moves the CTC loss
From listing to a table
ReadListing paths costs products for symbols and frames: hopeless for a second of speech. The forward recursionCTC forward recursionA dynamic program that adds up every CTC path for a transcript in time proportional to frames × labels, instead of listing paths. shares the work. Pad the transcript with blanks, so "ab" becomes . Then is the total probability of all paths that, after frames, sit at position of that padded sequence.
From one frame to the next a path may stay on its symbol, move one step, or skip a blank, but only between two different letters. Skipping the blank between two equal letters would merge them.
The recursion
ReadA valid path ends on the last letter or the final blank, so , with the padded length. The table has cells, each a sum of at most three terms: linear in the audio length instead of exponential. Real code works with log probabilities so long products don't underflow.
Check it against brute force
ReadFour frames over blank, a and b, from the reference's lab:
import itertools
import numpy as np
def ctc_forward(p, target):
labels = [0]
for tok in target:
labels += [tok, 0] # blank, a, blank, b, blank
alpha = np.zeros((len(p), len(labels)))
alpha[0, 0] = p[0, 0]
if target:
alpha[0, 1] = p[0, target[0]]
for t in range(1, len(p)):
for u, lab in enumerate(labels):
total = alpha[t - 1, u] # stay
if u > 0:
total += alpha[t - 1, u - 1] # move one step
if u > 1 and lab != 0 and lab != labels[u - 2]:
total += alpha[t - 1, u - 2] # skip a blank between different labels
alpha[t, u] = total * p[t, lab]
return alpha[-1, -1] + (alpha[-1, -2] if target else 0.0)
def collapse(path):
merged = [v for i, v in enumerate(path) if i == 0 or v != path[i - 1]]
return tuple(v for v in merged if v != 0)
def ctc_enumerate(p, target):
return sum(np.prod(p[np.arange(len(p)), path])
for path in itertools.product(range(p.shape[1]), repeat=len(p))
if collapse(path) == tuple(target))
p = np.array([[.25, .65, .10], [.55, .35, .10], [.15, .20, .65], [.55, .10, .35]])
print(ctc_forward(p, (1, 2)), ctc_enumerate(p, (1, 2))) # "ab": the same number twice
print(ctc_forward(p, (1, 1)), ctc_forward(p[:2], (1, 1))) # "aa" in 4 frames, then in 2
print([int(v) for v in collapse(tuple(p.argmax(1)))]) # greedy readingctc_forward <- function(p, target) { # blank is 1; labels are 2, 3, ...
labels <- c(1, as.vector(rbind(target, 1))) # blank, a, blank, b, blank
alpha <- matrix(0, nrow(p), length(labels))
alpha[1, 1] <- p[1, 1]
if (length(target)) alpha[1, 2] <- p[1, target[1]]
for (t in 2:nrow(p)) for (u in seq_along(labels)) {
total <- alpha[t - 1, u] # stay
if (u > 1) total <- total + alpha[t - 1, u - 1] # move one step
if (u > 2 && labels[u] != 1 && labels[u] != labels[u - 2])
total <- total + alpha[t - 1, u - 2] # skip a blank
alpha[t, u] <- total * p[t, labels[u]]
}
L <- length(labels)
alpha[nrow(p), L] + if (length(target)) alpha[nrow(p), L - 1] else 0
}
collapse <- function(path) {
merged <- path[c(TRUE, diff(path) != 0)]
merged[merged != 1]
}
ctc_enumerate <- function(p, target) {
paths <- as.matrix(expand.grid(rep(list(seq_len(ncol(p))), nrow(p))))
keep <- apply(paths, 1, function(q) identical(as.numeric(collapse(q)), as.numeric(target)))
sum(apply(paths[keep, , drop = FALSE], 1, function(q) prod(p[cbind(seq_len(nrow(p)), q)])))
}
p <- matrix(c(.25, .65, .10, .55, .35, .10, .15, .20, .65, .55, .10, .35), nrow = 4, byrow = TRUE)
print(c(ctc_forward(p, c(2, 3)), ctc_enumerate(p, c(2, 3)))) # "ab": the same twice
print(c(ctc_forward(p, c(2, 2)), ctc_forward(p[1:2, ], c(2, 2)))) # "aa" in 4 frames, then 2
print(collapse(apply(p, 1, which.max))) # greedy readingRun it: the first line prints one probability twice, from the table and from all 81 paths. R labels are one higher (blank is 1), with the same probabilities.
Notebook exercise · ~15 min
CTC by brute force, blanks and repeats
Add up every frame path that collapses to a transcript, check it against the CTC forward recursion, and see why a doubled letter needs a blank.
- Every path to "ab"
Write
collapse(p): merge repeated symbols, then drop blanks. Store the total probability of the paths that collapse to "ab" (the labels 1, 2) inp_ab.Show a solution
Pythondef collapse(p): merged = [k for i, k in enumerate(p) if i == 0 or k != p[i - 1]] return [k for k in merged if k != 0] p_ab = sum(path_prob(p) for p in paths if collapse(p) == [1, 2])Rcollapse <- function(p) { merged <- p[c(TRUE, diff(p) != 0)] merged[merged != 0] } p_ab <- sum(sapply(paths, function(p) if (identical(collapse(p), c(1, 2))) path_prob(p) else 0)) - A doubled letter
Store the total probability of the paths that collapse to "aa" (labels 1, 1) in
p_aa. Which paths can produce it?Show a solution
Pythonp_aa = sum(path_prob(p) for p in paths if collapse(p) == [1, 1])Rp_aa <- sum(sapply(paths, function(p) if (identical(collapse(p), c(1, 1))) path_prob(p) else 0)) - The greedy transcript
Greedy decoding takes the most likely symbol at every frame and collapses that one path. Store the transcript it gives as text, using "a" and "b" (for example "ab"), in
greedy. Compare its probability withp_ab.Show a solution
Pythongreedy = "".join("_ab"[k] for k in collapse(list(np.argmax(P, axis=1))))Rgreedy <- paste(c("_", "a", "b")[collapse(max.col(P, ties.method = "first") - 1) + 1], collapse = "")
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
A doubled letter needs room
PredictPredict first
The second line asks for "aa". With all four frames it gets a positive probability. What does it get with only the first two frames?
Reveal
Zero. "aa" needs a blank between the two letters, a ∅ a, so at least three frames. In two frames every path reads "a", "b", "ab", "ba" or nothing. In general a transcript needs as many frames as it has letters, plus one for each doubled pair.
Too many blanks, too few
PredictPredict first
Keep each frame's ratio of a to b, and raise the blank's share in every frame toward 1. What happens to the loss for "ab"?
Reveal
It grows without limit: every path that reads "ab" must spend at least two frames on letters, and those frames get rarer. At the other extreme there are no blanks to separate repeats or fill pauses. Training finds a balance, and trained CTC models end up predicting blank in most frames, with short spikes for letters.
DExplorable · CTC: blanks, repeats and the forward table
How does CTC score a transcript without knowing which frame holds which letter?
What is the fewest number of frames that can spell this transcript?
Transcript
The text the frames must spell. Doubled letters (aa, bb, oo) need a blank between them.
How many frames the audio gives. CTC emits one symbol (a letter or the blank) per frame.
Probability the toy acoustic model gives the symbol it favors in each frame.
Random jitter added to the model's scores before the softmax.
Skip rule
CTC may skip a blank only between two different letters. The wrong rule also skips it between equal letters.
Likeliest single path: a ∅ ∅ ∅ a ∅ b ∅. Greedy reading (top symbol per frame, collapsed): “aab”. Probabilities in each column of the lower table add up to 1.
Commit your prediction above to see the result
Make your prediction to see the result.
The greedy reading
ReadThe third line is the greedy readingGreedy CTC decodingTake the likeliest symbol in each frame, merge repeats, drop blanks. Fast, but not always the likeliest transcript.: the likeliest symbol per frame, collapsed. Here it gives "ab", but greedy decoding scores one path, while the transcript's probability is the whole table's total. On real audio two transcripts can swap order between the two views. Beam search over prefixes, often with a language model, closes the gap.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| CTC (AUD001) | Explained here. The lab's code runs in a Python or R notebook |
No CodeSplash method trains a CTC model; the forward recursion here is for learning, checked against brute force.
Check: the recursion
CheckpointCheck yourself
How long is the blank-padded label sequence for the transcript "cat"?
Show the answer
Answer: 7
One blank before each letter plus one at the end: .
Check yourself
How many frame paths does brute force list for 4 frames and 3 symbols (blank, a, b)?
Show the answer
Answer: 81
. Each extra frame triples the count; the forward table only grows by one row.
Check yourself
In the forward recursion, when may a path skip from position straight to ?
Show the answer
Answer: c
Skipping the blank between two different letters is allowed. Between equal letters the blank is what keeps them apart, so the skip is forbidden.
Check yourself
What is the smallest number of frames in which CTC can output "aab"?
Show the answer
Answer: 4
a ∅ a b: three letters plus one blank to separate the doubled a, so 4 frames.
Recap
Recap- The forward recursion sums every CTC path in a table instead of products.
- Paths stay, move, or skip a blank between different letters.
- Doubled letters need a separating blank and enough frames.
- Greedy decoding reads one path; beam search reads the transcript's total better.
Concepts in this lesson