CTC: sum alignments without frame-level labels
CTC 损失
Derive blank/repetition collapse, forward–backward loss and gradients, with exact path checks and greedy counterexamples.
ctcYou know the words, but not their frame boundaries
Audio contains many frames, while its transcript may contain only a few labels. Without known label boundaries, each frame cannot simply receive a supplied text label during training. Connectionist temporal classification (CTC) treats boundaries as hidden alignments: specify the final label string and sum every frame-level path producing it. Paths and label strings
CTC adds a blank symbol meaning that a frame produces no new output label. It is not a text space, a true silence annotation or an end token. Repetition lets one label occupy several frames; two consecutive occurrences of the same label need a separating blank. We use synthetic labels a and b, first counting paths and then checking dynamic programming and gradients.
Merge repetitions before removing blanks
For input frames, each frame supplies class probabilities including blank. Given the complete input , CTC factorizes a path across frames, then sums paths for target string :
Mapping first merges adjacent repeated symbols, then removes blank: aa becomes a, but a blank a becomes aa. Removing blank first would incorrectly turn the latter into a. This conditional factorization does not imply independent raw acoustic frames; the network producing may use the whole input, including future frames. Output distribution and collapse
Target length is only part of feasibility. If it contains adjacent repeated pairs, each pair requires an extra blank frame:
The target aa needs at least three frames. With two equiprobable classes and three frames, only a blank a produces it, with probability 1/8. Target length no greater than input length is not sufficient. PyTorch’s CTCLoss documentation explains infinite loss for insufficient input and an optional zero_infinity policy. We explicitly report infeasibility rather than treating it as successful zero-loss training. Input length and infeasible loss
Expand the target as , of length . A state may stay or advance one position; it may skip two positions only if the destination is nonblank and differs from the symbol two positions earlier:
Out-of-range terms are zero; the third term is considered only for , with blank index 0. Initialization permits only the first blank and first label. For a nonempty target, termination sums its final label and final blank:
An empty target has only one blank state, so there is no penultimate term. Zero frames with an empty target have mass 1; zero frames with a nonempty target are infeasible. These are recurrence conditions, not cases that adding a tiny constant can meaningfully replace.
Our backward value contains probabilities only after the current frame. Its final row is one at accepting states and zero elsewhere. For legal successor set :
Here is the posterior probability of frame symbol conditioned on the final target. The original paper includes the current emission in its backward variable, requiring an additional division by the current probability in its posterior formula. Either convention works; mixing them does not. Forward–backward conventions
For pre-softmax logit , the loss derivative is:
This is the network’s current allocation minus the allocation conditioned on the target. Both distributions sum to one per frame, so the gradient sums to zero across classes. Training an acoustic network requires continuing backpropagation through the network producing these logits. We optimize only the free logits here.
Enumerate for checking; use dynamic programming for loss
The complete Python/NumPy implementation accepts 0–8 frames, 2–4 classes and at most six nonblank target labels, with finite logits within ±50. It uses stable log-softmax and log-space recursion. There is no batching, length padding or loss reduction. PyTorch’s default mean additionally normalizes by target length, so it is not directly this single-sequence negative log probability. Interface shape and reduction
"""Log-space CTC over supplied finite logits, with exact small-path enumeration.
Blank index zero; collapse adjacent repetitions before removing blank. This is a
loss/gradient demonstration, not a trained acoustic encoder or beam recognizer.
"""
import itertools,json
import numpy as np
def logsum(values):
a=np.asarray(values,float);maximum=float(np.max(a))
return maximum+float(np.log(np.exp(a-maximum).sum())) if np.isfinite(maximum) else -np.inf
def inputs(logits,target):
x=np.asarray(logits)
if np.iscomplexobj(x):raise ValueError('Real logits required')
x=np.asarray(x,float)
if x.ndim!=2 or not 0<=x.shape[0]<=8 or not 2<=x.shape[1]<=4 or not np.isfinite(x).all() or (abs(x)>50).any():raise ValueError('Use 0–8 frames, 2–4 classes and logits within ±50')
if not isinstance(target,(list,tuple)) or len(target)>6 or any(type(t) is not int or not 1<=t<x.shape[1] for t in target):raise ValueError('Targets are nonblank integer labels, length at most six')
z=x-x.max(axis=1,keepdims=True);lp=z-np.log(np.exp(z).sum(axis=1,keepdims=True))
return lp,list(target)
def collapse(path):
result=[];previous=None
for token in path:
if token!=previous and token!=0:result.append(token)
previous=token
return tuple(result)
def infer(logits,target):
lp,target=inputs(logits,target);T,V=lp.shape;labels=[0]
for token in target:labels.extend([token,0])
S=len(labels);a=np.full((T,S),-np.inf);b=a.copy();minimum=len(target)+sum(x==y for x,y in zip(target,target[1:]))
if not T:return dict(possible=not target,minimum_frames=minimum,log_probability=0. if not target else None,loss=0. if not target else None,gradient=np.zeros_like(lp).tolist() if not target else None,posterior=np.zeros_like(lp).tolist() if not target else None,states=labels)
a[0,0]=lp[0,0]
if S>1:a[0,1]=lp[0,labels[1]]
def predecessors(s):return [s]+([s-1] if s else [])+([s-2] if s>1 and labels[s]!=0 and labels[s]!=labels[s-2] else [])
for t in range(1,T):
for s in range(S):a[t,s]=lp[t,labels[s]]+logsum([a[t-1,k] for k in predecessors(s)])
ends=[S-1]+([S-2] if S>1 else []);z=logsum(a[-1,ends])
if not np.isfinite(z):return dict(possible=False,minimum_frames=minimum,log_probability=None,loss=None,gradient=None,posterior=None,states=labels)
b[-1,ends]=0
for t in range(T-2,-1,-1):
for s in range(S):
next_states=[k for k in range(s,min(S,s+3)) if s in predecessors(k)]
b[t,s]=logsum([lp[t+1,labels[k]]+b[t+1,k] for k in next_states])
occupancy=np.exp(a+b-z);posterior=np.zeros((T,V))
for s,label in enumerate(labels):posterior[:,label]+=occupancy[:,s]
gradient=np.exp(lp)-posterior
return dict(possible=True,minimum_frames=minimum,log_probability=float(z),loss=float(-z),gradient=gradient.tolist(),posterior=posterior.tolist(),states=labels,state_posterior=occupancy.tolist())
def enumerate_outputs(logits):
lp,_=inputs(logits,[]);T,V=lp.shape;mass={};best=None
for path in itertools.product(range(V),repeat=T):
value=float(np.exp(sum(lp[t,k] for t,k in enumerate(path))));key=collapse(path);mass[key]=mass.get(key,0.)+value
if best is None or value>best[0]:best=(value,path)
rows=[dict(labels=list(k),probability=v) for k,v in sorted(mass.items(),key=lambda p:(-p[1],p[0]))]
return dict(distribution=rows,total=sum(mass.values()),best_path=list(best[1]),best_path_probability=best[0],best_path_labels=list(collapse(best[1])),mode=rows[0])
def demo():
logits=np.log([[.4,.35,.25],[.4,.35,.25]]);result=infer(logits,[1]);training=[];x=logits.copy()
for _ in range(6):
r=infer(x,[1]);training.append(r['loss']);x-=.3*np.array(r['gradient'])
training.append(infer(x,[1])['loss'])
return dict(probabilities=np.exp(logits).tolist(),target=[1],inference=result,enumeration=enumerate_outputs(logits),
repeated=dict(without_blank=list(collapse([1,1])),with_blank=list(collapse([1,0,1])),too_short=infer(np.zeros((2,2)),[1,1]),minimal=infer(np.zeros((3,2)),[1,1])),
empty=infer(np.zeros((2,2)),[]),zero_frames=infer(np.zeros((0,2)),[]),training_losses=training)
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Both frames use probabilities [blank:0.4, a:0.35, b:0.25]. Framewise argmax gives blank blank, probability 0.16, collapsing to empty. But aa, a blank and blank a jointly give label a probability 0.4025, exceeding empty. The original paper states that best-path decoding need not find the most probable label sequence; here each contribution is inspectable. Limits of greedy paths
Six direct-logit updates at step size 0.3 reduce target-a loss from approximately 0.910060 to 0.511869. Central differences check every analytic gradient entry, while enumeration checks probabilities for all short outputs. An extreme bounded-logit case has target loss above 745 while retaining a finite log-space result; ordinary probability products may already underflow.
Recursion, posteriors and softmax take time and storage. Enumerating paths takes time; retaining distinct outputs takes space. Sorting adds a conservative bound. Enumeration is not a production decoder; larger settings need suitable prefix search, pruning and model constraints.
The loss does not choose an encoder or decoder for you
CTC requires monotonic alignment and bounds output length by frame count. Aggressive temporal downsampling can make repeated-label targets infeasible. Adding blank does not provide free alignment for arbitrary reordering tasks, nor automatically supply a pronunciation lexicon or explicit language model.
Frame-level conditional factorization limits how output-label dependencies are expressed. Language-model fusion and other structures can alter decoding, adding configuration choices. CTC with a bidirectional encoder is not thereby streaming. We neither train an acoustic network nor implement full prefix search or reproduce the paper’s speech benchmark. Decreasing loss verifies this small computation, not recognition performance.
Repeated labels expose the boundary cases
-
Understanding. What do a a and a blank a produce, and why not remove blank first?
Answer: They produce a and aa respectively. Removing blank first would incorrectly merge the latter into a and erase the distinction between repeated labels.
-
Calculation. Each of two frames assigns blank 0.4 and a0.6. What is the probability of output a?
Answer: Paths aa, a blank and blank a have probabilities 0.36, 0.24 and 0.24, totaling 0.84. Keeping only the best path omits other alignment mass.
-
Boundary. Should target aa with two frames have zero loss? What is its mass with three frames and two equiprobable classes?
Answer: Two frames are infeasible; the true negative log probability is infinite. We represent that with None and possible=False rather than fake zero loss. Three frames admit only a blank a, mass 1/8.
-
Transfer. Does a framewise maximum path collapsing to empty prove that empty is the most likely output?
Answer: No. Our best path has mass 0.16, while multiple paths for a sum to 0.4025. Label selection compares summed probabilities; greedy decoding approximates using one path.
Check paper equations and library defaults separately
Sections 3–4 of the original CTC paper support collapse, loss, forward–backward inference and greedy limitations. The inspected backward-variable convention is distinguished explicitly. PyTorch 2.6 documentation supports interface, target-length and reduction details; the code does not call PyTorch or CuDNN. All probabilities, gradients and training trajectories use synthetic logits, without reproducing TIMIT results.
Make a prediction, then check
What does the CTC path a, blank, a produce?
Learning objectives
- Apply repetition collapse before removing blank.
- Derive feasibility for adjacent repeated labels.
- Compute posterior symbol mass and logit gradients.
- Distinguish the best path from the highest-mass label string.
Prerequisites & connections
Explore related knowledge →References
- Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks
Alex Graves, Santiago Fernández, Faustino Gomez, Jürgen Schmidhuber · 2006 - PyTorch 2.6: torch.nn.CTCLoss
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked repetition-before-blank collapse, minimum frames for repeated labels, log-space forward/backward, a backward convention excluding current emission, target-conditioned posterior and finite-difference logit gradients against scoped CTC2006 equations and PyTorch2.6 interface notes. Six paired equations and four explained exercises. Exact short-path enumeration, greedy counterexample and free-logit optimization; no acoustic encoder, library reduction or TIMIT replication.
- Checked blank/repeat order, impossible two-frame aa, mass1/8 with three frames, greedy empty0.16 versus target-a0.4025, posterior normalization and central-difference gradients.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
- After rendered review, inserted missing spaces before English reference citations. Verified an exact whitespace-only transformation, unchanged formulas/program and preserved frozen article/test payloads; see editorial/corrections/011h-citation-spacing.
Source locations checked:
- Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks · Read section3 output distribution/collapse and greedy limitation; visually inspected physical pages4–5 recurrence/termination/backward equations. Our beta excludes the current emission, unlike the paper convention. No TIMIT results reproduced.
- PyTorch 2.6: torch.nn.CTCLoss · Read parameters and shapes: log probabilities, nonblank targets, lengths, reduction and zero_infinity. Original program accepts single-sequence logits without batch reduction; PyTorch/CuDNN not executed.
Related topics