Skip to content

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.

Advanced ~18 min9 steps

What runs in CodeSplash

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

Read first

01

From listing to a table

Read

Listing paths costs KTK^T products for KK symbols and TT 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 ∅ a ∅ b ∅\varnothing\,a\,\varnothing\,b\,\varnothing. Then αt(u)\alpha_t(u) is the total probability of all paths that, after tt frames, sit at position uu 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.

02

The recursion

Read
αt(u)=pt(lu) [αt−1(u)+αt−1(u−1)+1[lu≠∅, lu≠lu−2] αt−1(u−2)]\alpha_t(u) = p_t(l_u)\,\bigl[\alpha_{t-1}(u) + \alpha_{t-1}(u-1) + \mathbb{1}[l_u \ne \varnothing,\ l_u \ne l_{u-2}]\,\alpha_{t-1}(u-2)\bigr]

A valid path ends on the last letter or the final blank, so p(y∣x)=αT(L)+αT(L−1)p(y \mid x) = \alpha_T(L) + \alpha_T(L-1), with LL the padded length. The table has T×LT \times L 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.

03

Check it against brute force

Read

Four frames over blank, a and b, from the reference's lab:

Python
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 reading
R
ctc_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 reading

Run 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.

  1. 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) in p_ab.

    Show a solution
    Python
    def 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])
    R
    collapse <- 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))
  2. 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
    Python
    p_aa = sum(path_prob(p) for p in paths if collapse(p) == [1, 1])
    R
    p_aa <- sum(sapply(paths, function(p) if (identical(collapse(p), c(1, 1))) path_prob(p) else 0))
  3. 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 with p_ab.

    Show a solution
    Python
    greedy = "".join("_ab"[k] for k in collapse(list(np.argmax(P, axis=1))))
    R
    greedy <- 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.

04

A doubled letter needs room

Predict

Predict 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?

The same as for abZeroHigher, because a is likely in frame 1
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.

05

Too many blanks, too few

Predict

Predict 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"?

The loss keeps fallingThe loss grows without limitThe loss doesn't change
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?

6
How sure?

Transcript

The text the frames must spell. Doubled letters (aa, bb, oo) need a blank between them.

8

How many frames the audio gives. CTC emits one symbol (a letter or the blank) per frame.

0.80

Probability the toy acoustic model gives the symbol it favors in each frame.

0.5

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.

.13.63.82.90.13.86.10.90.81.16.10.03.77.05.09.05.05.20.08.07.10.08.80.06p(∅)p(a)p(b)1. ∅2. a3. ∅4. a5. ∅6. b7. ∅

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 first; the figure appears when you commit.

Make your prediction to see the result.

06

The greedy reading

Read

The 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.

07

Where it stands in CodeSplash

Read
EntryIn 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.

08

Check: the recursion

Checkpoint

Check 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: 2×3+1=72 \times 3 + 1 = 7.

Check yourself

How many frame paths does brute force list for 4 frames and 3 symbols (blank, a, b)?

Show the answer

Answer: 81

34=813^4 = 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 u−2u-2 straight to uu?

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.

09

Recap

Recap
  • The forward recursion sums every CTC path in a T×LT \times L table instead of KTK^T 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