Compute the CTC loss with the forward algorithm in log space
CTC trains speech and handwriting models without frame-level alignments by summing the probability of every frame path that collapses to the target. That sum has exponentially many terms, so it is computed with dynamic programming, in log space to avoid underflow.
Write ctc_loss(log_probs, target, blank=0). log_probs is (T, C), each row already log-softmaxed. target is a list of label ids (no blanks, possibly empty). Return the negative log-likelihood as a float.
Build the extended sequence l' = [blank, t1, blank, t2, ..., blank] of length S = 2L + 1. With alpha[t, s] the log-probability of being at l'[s] after frame t:
- alpha[0, 0] = lp[0, blank], alpha[0, 1] = lp[0, t1] if L > 0, all else -inf.
- alpha[t, s] = logsumexp(alpha[t-1, s], alpha[t-1, s-1], and alpha[t-1, s-2] only if l'[s] is not blank and l'[s] != l'[s-2]) + lp[t, l'[s]].
- loss = -logsumexp(alpha[T-1, S-1], alpha[T-1, S-2]) (just alpha[T-1, 0] when L = 0).
Assume T is long enough for the target.
def ctc_loss(log_probs, target, blank=0)Example
T = 1, target [2], lp[0] = log([0.1, 0.2, 0.7]) gives -log(0.7) = 0.35667.
Understand the idea
CTC loss asks: over every frame-by-frame path that collapses to the target, what is the total probability? There are too many paths to list, so dynamic programming adds them up, and working in log space avoids underflow on long audio. Worked example: T = 2 frames, target [1], blank 0, each frame has probabilities [0.4, 0.6]. Paths that collapse to [1]: (1, 1) = 0.36, (0, 1) = 0.24, (1, 0) = 0.24. Total = 0.84, loss = -ln 0.84 = 0.1744. Rule: extend the target with blanks, l' = [blank, t1, blank, t2, ..., blank], length 2L + 1. alpha[t, s] is the log probability of being at l'[s] after frame t. At each step you may stay, move one step, or skip two steps, but the skip is allowed only when l'[s] is not blank and differs from l'[s - 2]. Combine with logsumexp and add lp[t, l'[s]]. Start at the first blank or first label; finish at the last label or the final blank. The answer is minus that final logsumexp. CTC trains speech recognisers and OCR without frame alignments.