Module contents
Lesson 28 of 33Core 120 min

Speech recognition: from CTC to Whisper

Study speech recognition alignment and WER, compare CTC, RNN-T and attention, and examine Conformer, self-supervised speech, Whisper and language-model decoding.

After this lesson you can

  • Calculate WER with edit distance and text normalization and understand its limits.
  • Compare CTC, RNN-T and encoder–decoder models by independence, streaming and alignment.
  • Derive RNN-T transducer loss over its alignment lattice.
  • Explain wav2vec 2.0 contrastive quantization and HuBERT pretraining.
  • Use Whisper locally, tune wav2vec 2.0 with CTC, and evaluate both using WER.

Before you start

A command without word boundaries

A microphone supplies a sequence of samples, not words with boundaries. In “turn on the light,” syllable duration varies between speakers and sounds can blend together. Automatic speech recognition estimates a transcript yy from signal xx. The decision can be formulated as arg max⁡yp(y∣x)\argmax_y p(y\mid x), but alignments between acoustic frames and symbols are latent. A good clean-speech transcript does not guarantee recognition in a noisy kitchen or that the system knows when speech is absent.

InteractiveEdit words and measure WER
enciende
enciende
match
la
∅
deletion
luz
luz
match
de
de
match
la
la
match
cocina
cocina
match
∅
ya
insertion

Top: reference. Bottom: hypothesis. Scroll horizontally if the alignment does not fit. Normalization lowercases, separates punctuation and converts digits 0 to 10 to Spanish words.

Distance matrix
ref / hyp∅enciendeluzdelacocinaya
∅0123456
enciende1012345
la2112234
luz3212334
de4321234
la5432123
cocina6543212
WER33.3 %
S / B / I0 / 1 / 1
Reference words6
Edit the reference and hypothesis. Explore the matrix and an optimal path. Normalization changes the measured question; the implementation shows its convention explicitly.

Word error rate (WER) is (S+D+I)/N(S+D+I)/N, where NN is reference word count and SS, DD, and II count substitutions, deletions, and insertions in a minimum-edit-distance alignment. If N=0N=0 there is no denominator: report insertions in silence separately. Since insertions are not bounded by NN, WER can exceed 100%. When aggregating a corpus, sum errors and words before dividing; averaging sentence WERs weights short sentences differently.

The edit table is built by prefixes. If d(i,j)d(i,j) is the cost of aligning the first ii reference words with the first jj hypothesis words, boundaries are d(i,0)=id(i,0)=i and d(0,j)=jd(0,j)=j. Each cell takes the minimum of deleting, inserting, or substituting: d(i−1,j)+1d(i-1,j)+1, d(i,j−1)+1d(i,j-1)+1 and d(i−1,j−1)+[ri≠hj]d(i-1,j-1)+[r_i\ne h_j]. Backtracking recovers a path; ties mean it is not always unique. The cell below checks that the path’s operation count matches distance, not that there is a unique error decomposition.

Normalization is part of the metric: capitalization, punctuation, accents, numbers, and spelling variants can change the result. The figure converts only numerals from 0 to 10 to Spanish words and separates punctuation; it does not convert arbitrary numeric expressions. Comparable measurement requires the same rule for all systems and a report of that rule. WER does not distinguish a wrong negation from a filler word, and a distance tie can have multiple alignments with different error-type breakdowns.

Blank, labels and time

In CTC, each frame produces a distribution over symbols and blank. A path collapses consecutive repeats and then removes blanks; for example, l blanco l represents two letters, whereas l l represents one. Sequence probability sums probabilities of all paths collapsing to it. Conditioned on acoustic representation, CTC factorizes emissions per frame; the encoder may use broad context, but outputs do not directly receive prior symbols. A prefix beam aggregates paths producing the same output; decoding frames individually and collapsing afterward need not find the most probable sequence.

The temporal constraint is concrete: to emit UU symbols with RR identical consecutive pairs, CTC needs at least U+RU+R frames, because each repeated pair requires a separating blank. Subsampling to fewer frames gives that label zero probability even if original audio was long. A transducer can emit more than one label before advancing a frame, but that freedom requires search control: implementations usually limit consecutive emissions to bound latency. This limit is a decoding decision, not part of exact marginal probability.

The RNN-T transducer adds a prediction network summarizing already emitted labels. Its joint network combines that state with the current frame’s acoustic representation. In lattice (t,u)(t,u), a blank transition advances the frame and retains uu; a label transition emits yu+1y_{u+1} and increases uu without advancing tt. With a causal or block encoder it can stream; the lattice alone does not make an encoder that sees all audio causal.

For TT frames and UU labels define α(t,u)\alpha(t,u) as probability of reaching the node, with α(0,0)=1\alpha(0,0)=1. At each node with t<Tt<T, propagate α(t,u)p(∅∣t,u)\alpha(t,u)p(\varnothing\mid t,u) to (t+1,u)(t+1,u) and, if u<Uu<U, α(t,u)p(yu+1∣t,u)\alpha(t,u)p(y_{u+1}\mid t,u) to (t,u+1)(t,u+1). The path must end with a blank after the last label to reach (T,U)(T,U). Loss is −log⁡α(T,U)-\log\alpha(T,U). The implementation below sums in logarithms and checks the recursion against exhaustive enumeration in a small example.

InteractiveThree ways to align

Frame: a → a → b. The five valid paths for these three frames and two symbols are shown.

Family
0
3
Target outputab
Partial path weight14.40 %
Sum of complete paths43.20 %
Traverse CTC and RNN-T paths for output ab and compare an educational attention map. Path weights are calculated from the widget's explicit model; attention is not a probabilistic transition alignment.

Summing paths also explains learning: a compatible transition receives contribution from every path using it. With backward recursion β\beta from (T,U)(T,U), posterior mass of transition v→wv\to w is α(v)p(v→w)β(w)/α(T,U)\alpha(v)p(v\to w)\beta(w)/\alpha(T,U), provided total probability is positive. In log space, log-sum-exp prevents products of many probabilities rounding to zero. The posterior distributes credit among alignments: there is no need to choose a single word boundary before training.

An attention encoder–decoder computes p(y∣x)=∏up(yu∣y<u,x)p(y\mid x)=\prod_u p(y_u\mid y_{<u},x); the decoder uses the prefix and attends to acoustic representations. Global attention can see the future, so streaming requires monotonic, blockwise, or other constrained attention. CTC plus attention shares an encoder and combines objectives or decoding scores; it does not eliminate the need to define latency and context window.

During training with known transcript, autoregressive loss uses the true prefix. At inference it uses its own predictions and an error can change subsequent ones. A beam retains several hypotheses but does not turn model scores into calibrated certainty. For a robotic command, measure errors by intent as well as WER, especially negations, object names, and numbers; a low average rate can hide an unacceptable action error. An interface can request repetition when recognition is uncertain, but should also be evaluated on rejected correct commands.

The Conformer combines attention and convolution: the former permits content-dependent interactions and the latter incorporates local structure. Subsampling reduces temporal length before the block, easing quadratic attention cost, but losing too much resolution can harm brief sounds. Gulati and colleagues reported 2.1% and 4.3% WER on clean and difficult LibriSpeech sets without a language model under their protocol; these are not this lab’s measurements.

Learning from sound without transcribing everything

Self-supervised speech pretraining uses audio without human labels to learn representations. wav2vec 2.0 masks segments of latent representations and distinguishes the quantized target from negatives using contrastive loss, with a jointly learned quantizer. It then adds a head and fine-tunes with transcripts. HuBERT obtains discrete labels through offline clustering and predicts labels of masked regions; these labels are training targets, not guaranteed phonemes.

Whisper’s weak supervision trains an encoder–decoder on Internet audio–text pairs with noisy, variable labels. The work describes 680000 multilingual, multitask hours, not an amount of perfectly transcribed speech. Special tokens express language, task, and timestamps; transcription is a conditioned output, not a direct reading from a speech detector. In silence or music the model can produce text without acoustic support: Barański and colleagues studied hallucinations induced by nonspeech sounds. Measure insertions in nonspeech segments, use speech detection and calibrated thresholds, and listen to problematic samples. These measures may reduce failures without proving hallucinations absent.

Pretraining and fine-tuning address different problems. The contrastive task teaches the encoder to distinguish acoustic targets within a batch; a later CTC head learns to assign characters and blank using labeled examples. English pretraining and very small bilingual tuning do not guarantee coverage of accents or proper names. HuBERT uses another signal: cluster quality and bias can also affect which patterns it retains.

InteractiveWhere Whisper looks

Synthetic speech: ‘Please place the blue block on the table.’

Whisper output with timestamps: <|0.00|> Please play as the blue bloke on the table.<|2.00|>

Input log-mel, 20 grouped bands (low frequency below)

0 s2.67 s

Token cross-attention, mean of last-layer heads

A peak position alone does not demonstrate alignment or causality. Weights were calculated over 30 padded seconds; the original-audio portion is shown without renormalization.

Control with eight seconds of digital silence: <|0.00|> you<|2.06|>. With context ‘Thank you for watching.’: <|0.00|> Thank you for watching.<|2.00|>. Context is preceding text, not speech present in the audio.

In an independent study, Whisper produced ‘thank you’ on nonspeech audio; the authors also found hallucinations when adding silence to speech. These are published results under another protocol, not output attributed to this control. See the study and tables III and V.

1
Token␠Please
Peak in audio0.46 s
Mass on audio34.9 %
Synthetic speech and cross-attention measured with Whisper small. Traverse tokens and compare their per-frame weights with log-mel and predicted timestamps; the silence control contains no speech.

The figure’s phrase is the previous lesson’s SAPI voice, resampled to 16 kHz; its reference is “Please place the blue block on the table.” In our run Whisper small produced “Please play as the blue bloke on the table.” with timestamps from 0.00 to 2.00 s. Each row corresponds to a generated token with reconstructed language and task prefix, in a second pass with the prefix already generated: last cross-attention-layer heads are averaged. Whisper’s window is padded to 30 s, and the plot crops to actual duration without renormalizing, so displayed mass may be below one. A peak describes a weight, not proof that the segment caused the word or a precise timestamp.

The control contains eight seconds of zeros. With this model and configuration, “you” was emitted without speech; adding explicit context “Thank you for watching.” reproduced that phrase in silence. These are two specific runs, not a rate or an inevitable property of every configuration. The control and extraction can be reproduced using capture_attention.py and the synthetic audio, together with Whisper small. Context is supplied as text to the decoder, not as an acoustic signal.

Language-model fusion adds a term such as λlog⁡pLM(y)\lambda\log p_{LM}(y) to the acoustic score, plus a possible length bonus. In prefix CTC the language-model state is updated only when adding a symbol to the prefix, not when repeating it in a path that will collapse. Weight is chosen on validation; a strong language model may correct spelling or impose a frequent wrong phrase. Compare the same normalization, language, data, and search budget.

For example, if an ambiguous signal admits Spanish “cierra” and “tierra,” linguistic preference can favor the word usual in context. But if the unusual command was correct, the same bias can hide weak acoustic evidence. Acoustic and language weights live on different scales and length affects summed log probabilities: measure sensitivity to beam and weight on a separate validation set. For proper names and new vocabulary, report errors by category rather than only the overall mean.

Lab: the three sums

Edit distance is dynamic programming over prefixes. This cell calculates a deterministic path despite possible ties. It checks that the example reference has six words: deleting “la” and inserting “ya” produces two errors.

[ ]WER and alignmentBrowser
import numpy as np
def wer(reference,hypothesis):
    r=reference.split();h=hypothesis.split();n=len(r);m=len(h)
    d=np.zeros((n+1,m+1),dtype=int);d[:,0]=np.arange(n+1);d[0,:]=np.arange(m+1)
    for i in range(1,n+1):
        for j in range(1,m+1):d[i,j]=min(d[i-1,j]+1,d[i,j-1]+1,d[i-1,j-1]+(r[i-1]!=h[j-1]))
    return None if n==0 else d[n,m]/n,d
def alignment(reference,hypothesis):
    r,h=reference.split(),hypothesis.split();_,d=wer(reference,hypothesis);i,j=len(r),len(h);out=[]
    while i or j:
        if i and j and r[i-1]==h[j-1] and d[i,j]==d[i-1,j-1]:
            out.append((r[i-1],h[j-1],'igual'));i-=1;j-=1
        elif i and j and d[i,j]==d[i-1,j-1]+1:
            out.append((r[i-1],h[j-1],'sustitución'));i-=1;j-=1
        elif i and d[i,j]==d[i-1,j]+1:
            out.append((r[i-1],'∅','borrado'));i-=1
        else:
            out.append(('∅',h[j-1],'inserción'));j-=1
    return out[::-1]
ref='enciende la luz de la cocina';hyp='enciende luz de la cocina ya'
rate,table=wer(ref,hyp);path=alignment(ref,hyp)
print('errores:',table[-1,-1],'referencia:',table.shape[0]-1,'WER:',round(rate,6))
print('alineamiento:',path)
assert sum(kind!='igual' for _,_,kind in path)==table[-1,-1]
[ ]RNN-T forward recursion and enumerationBrowser
import numpy as np
from scipy.special import logsumexp
T=2;labels=[1];U=len(labels);blank=0
prob=np.array([[[.4,.6],[.7,.3]],[[.8,.2],[.5,.5]]])
lp=np.log(prob)
def rnnt_logprob(lp,labels,blank=0):
    T,U1,V=lp.shape;U=len(labels)
    if U1!=U+1 or not 0<=blank<V or any(c==blank or not 0<=c<V for c in labels):raise ValueError('forma o etiquetas incompatibles')
    a=np.full((T+1,U+1),-np.inf);a[0,0]=0.
    for t in range(T):
        for u in range(U+1):
            a[t+1,u]=np.logaddexp(a[t+1,u],a[t,u]+lp[t,u,blank])
            if u<U:a[t,u+1]=np.logaddexp(a[t,u+1],a[t,u]+lp[t,u,labels[u]])
    return a[T,U]
def enumerate_paths(t,u,p):
    if t==T:return [p] if u==U else []
    out=enumerate_paths(t+1,u,p*prob[t,u,blank])
    if u<U:out+=enumerate_paths(t,u+1,p*prob[t,u,labels[u]])
    return out
paths=enumerate_paths(0,0,1.)
print('probabilidades de caminos:',paths,'suma:',sum(paths),'DP:',np.exp(rnnt_logprob(lp,labels)))
assert np.isclose(sum(paths),np.exp(rnnt_logprob(lp,labels)))

CTC beam search retains two masses per prefix: paths ending in blank and paths ending in a symbol. A repetition without blank preserves the prefix; the same letter after a blank extends it. This distinction avoids losing ll in the example. Search prunes to beam prefixes after every frame, so its result can vary with width; the exhaustive check uses a sufficiently wide beam.

[ ]Prefix CTC and exhaustive checkBrowser
import itertools
from collections import defaultdict
import numpy as np
def ctc_prefix_beam_search(log_probs,beam,lm=None):
    lp=np.asarray(log_probs,dtype=float)
    if lp.ndim!=2 or beam<1:raise ValueError('forma o haz inválidos')
    minus=-np.inf; states={(): (0.,minus)}
    def add(target,prefix,index,value):
        if np.isneginf(value):return
        old=list(target.get(prefix,(minus,minus)));old[index]=np.logaddexp(old[index],value);target[prefix]=tuple(old)
    for frame in lp:
        nxt={}
        for pre,(pb,pnb) in states.items():
            total=np.logaddexp(pb,pnb);add(nxt,pre,0,total+frame[0])
            for c in range(1,len(frame)):
                score=0. if lm is None else float(lm(pre,c))
                if pre and c==pre[-1]:
                    add(nxt,pre,1,pnb+frame[c])
                    add(nxt,pre+(c,),1,pb+frame[c]+score)
                else:add(nxt,pre+(c,),1,total+frame[c]+score)
        states=dict(sorted(nxt.items(),key=lambda kv:np.logaddexp(*kv[1]),reverse=True)[:beam])
    return sorted(((p,float(np.logaddexp(*v))) for p,v in states.items()),key=lambda x:x[1],reverse=True)
def collapse(path):
    out=[];previous=None
    for c in path:
        if c!=previous and c!=0:out.append(c)
        previous=c
    return tuple(out)
prob=np.array([[.2,.6,.2],[.5,.4,.1],[.2,.6,.2]])
exact=defaultdict(float)
for path in itertools.product(range(3),repeat=3):
    exact[collapse(path)]+=np.prod([prob[t,c] for t,c in enumerate(path)])
beam=dict(ctc_prefix_beam_search(np.log(prob),beam=100))
assert all(np.isclose(np.exp(beam[k]),v) for k,v in exact.items())
greedy=collapse(np.argmax(prob,axis=1))
print('voraz:',greedy,'mejor prefijo:',max(exact,key=exact.get),'P(ll):',round(exact[(1,1)],4))
# LM de juguete: favorece añadir b con un peso logarítmico; no premia repeticiones colapsadas.
lm=lambda prefix,c: 3. if c==2 else 0.
with_lm=ctc_prefix_beam_search(np.log(prob),beam=100,lm=lm)
print('mejor prefijo con LM ilustrativo:',with_lm[0][0])

Local lab: transcription and comparison

Download run_asr.py to your working directory and install PyTorch, Transformers, SciPy, NumPy and huggingface_hub. The first run downloads pinned FLEURS revisions and the three models if absent from asr-fleurs-data and asr-models; they need several gigabytes. If complete copies already exist, point ASR_ROOT and ASR_MODELS at their folders to avoid downloading again. The program does not need a reports path from this page.

The protocol takes the first 20 training and first 10 test audios under 15 seconds in US English and Latin American Spanish from their original splits. In this selection, the ten test recordings repeat phrases: there are five distinct English transcripts and four Spanish. None exactly matches the 20 selected training transcripts in the same language. Recordings provide audio variation but are not ten independent sentences. Fine-tune wav2vec 2.0 base with a new CTC head for two epochs on 40 training audios; freeze the convolutional extractor and tune the rest. Character vocabulary is built from training only. Whisper small and medium are used without tuning, with language and task specified. This is not an equal-budget comparison or a precise measure of general model performance.

Evaluation transcribes the same 20 test audios, clean and with independent Gaussian noise at 10 dB SNR, using fixed seeds. Reference and all hypotheses use the same rule: lowercase, Unicode NFC normalization, and punctuation as separators; numbers are not expanded and accents are not removed. Aggregate WER sums errors and reference words before division. Timing measures Whisper autoregressive generation and CTC forward pass after moving input to device and synchronizing CUDA; loading, preprocessing, CTC argmax, and token-to-text conversion are excluded. The first Whisper transcription is warmup and excluded. These runs were under shared-machine load, not a universal latency reference.

To run all stages from Python, place the downloaded file in the current directory and run the cell. You can also run python run_asr.py directly. ASR_STAGE accepts whisper-small, whisper-medium or wav2vec2-ctc to repeat one stage; without it all three run. JSON files retain hypotheses, references, duration and time per sample, and fine-tuning saves the CTC model and tokenizer.

[ ]Recognition, CTC tuning and bilingual evaluationLocal GPU
import os, runpy
from pathlib import Path
script=Path(os.environ.get('ASR_SCRIPT','run_asr.py'))
if not script.is_file():
    raise FileNotFoundError('Descarga run_asr.py y sitúalo en el directorio actual, o indica ASR_SCRIPT')
runpy.run_path(str(script),run_name='__main__')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The in-house RTX 3060 run with Whisper in float16 produced the following results. Each WER cell has 184 reference words; RTF is measured model seconds per audio second.

SystemClean EnglishEnglish 10 dBClean SpanishSpanish 10 dBRTF for the four conditions
Whisper small13/184 = 7.07 %22/184 = 11.96 %4/184 = 2.17 %12/184 = 6.52 %0.093, 0.074, 0.091, 0.095
Whisper medium12/184 = 6.52 %21/184 = 11.41 %1/184 = 0.54 %6/184 = 3.26 %0.160, 0.163, 0.210, 0.215
wav2vec 2.0 + CTC184/184 = 100 %184/184 = 100 %184/184 = 100 %184/184 = 100 %0.009, 0.007, 0.008, 0.008

In this CTC fine-tuning, mean loss fell from 5.679 to 3.257, but all 40 decoded hypotheses were empty: decreasing loss did not produce a useful recognizer in two epochs with 40 examples. A check with the reloaded checkpoint on the first English recording observed blank as the maximum on all 631 frames and mean blank probability 0.750; the CTC tokenizer removes blanks, so the empty string corresponds to that greedy output. This isolated diagnosis does not prove why it happened or predict another fine-tuning run. CTC RTF measures only forward pass, not Whisper autoregressive generation, and empty output does not make the tasks comparable. The selection includes repeated sentences and does not justify claiming medium always improves on small, noise always worsens every system, or fine-tuning converged. Timing also depends on shared load; treat it as an observation and repeat measurement for your application.

Low WER does not guarantee a command is free of critical errors. High WER after so little tuning can reflect insufficient data, language differences, character coverage, or domain mismatch; comparing affected sentences and words helps form hypotheses but does not identify one cause. Output is retained by language and condition and per sample to inspect differences and avoid hiding negative results.

Exercises

Numeric
For reference «enciende la luz de la cocina» and hypothesis «enciende luz de la cocina ya», what is WER as a fraction?
Quiz
What configuration is reasonable for streaming recognition with bounded latency?
Quiz
A system transcribes words in silent segments. What protocol is more informative?
Proof
Prove: The forward recursion sums probabilities of all valid paths ending at (T,U).
0
Each blank transition increases t and each label increases u; path weight is the product of its probabilities.

Step 1 of 3. Why does the lattice permit induction?

Code
Implement collapse(path): receive a list of integers where 0 is blank. First collapse identical consecutive symbols and then remove blanks; return a tuple. Check the difference between [1,1] and [1,0,1].
def collapse(path):
  pass
Shift+Enter to run
Code
Implement ctc_prefix_beam_search(log_probs, beam, lm=None). Each row gives log probabilities of integer symbols; 0 is blank. Return a list of (tuple, log mass), ordered highest first. lm(prefix, c) adds a score when extending a prefix, not when repeating an emission that collapses. Prune to beam after each frame.
def ctc_prefix_beam_search(log_probs,beam,lm=None):
  pass
Shift+Enter to run
Key idea
Speech recognition sums over uncertain alignments; architecture, decoder, and evaluation normalization determine what a WER means.