Automatic Speech Recognition (ASR) Decoding
“Turning acoustic probabilities into coherent text.”
TL;DR
ASR decoding is the final stage that converts acoustic model output probabilities into human-readable text. The main strategies are greedy decoding (fast but suboptimal), beam search (better quality at higher cost), and CTC decoding (handles alignment automatically with blank tokens). Language model integration through shallow fusion, deep fusion, or rescoring dramatically improves accuracy by incorporating linguistic knowledge. Streaming production systems typically use RNN-Transducer models with beam search, contextual biasing for names and jargon, and sometimes a second-pass rescorer, while offline systems such as Whisper use attention encoder-decoders with beam search and temperature fallback. For a line-by-line implementation of CTC prefix beam search, see ASR beam search implementation. For the full speech pipeline architecture, decoding is where acoustic signals become actionable text.

1. Introduction
Automatic Speech Recognition (ASR) converts speech audio into text. The decoding stage is where we take the acoustic model’s output (probabilities over characters/tokens) and produce the final transcription.
Pipeline:
Audio → Feature Extraction (MFCC) → Acoustic Model → Decoder → Text
The decoder’s job is to find the most likely text sequence given the acoustic observations.
2. The Decoding Problem
Mathematically:
\[\hat{W} = \arg\max_W P(W \mid O)\]Where:
O= Acoustic observations (audio features).W= Word sequence (transcription).
Using Bayes’ theorem:
\[P(W \mid O) = \frac{P(O \mid W)\, P(W)}{P(O)}\]Since P(O) is constant, we maximize:
\[\hat{W} = \arg\max_W P(O \mid W) \cdot P(W)\]P(O | W)= Acoustic Model (AM): How likely is this audio given these words?P(W)= Language Model (LM): How likely is this word sequence?
3. Decoding Strategies
3.1. Greedy Decoding
Algorithm:
- At each time step, pick the most likely token.
- Concatenate to form the output.
def greedy_decode(probs):
# probs: (T, vocab_size)
tokens = []
for t in range(len(probs)):
token = np.argmax(probs[t])
tokens.append(token)
return tokens
Pros: Fast, simple. Cons: Doesn’t consider context. Often produces suboptimal results.
3.2. Beam Search
Algorithm:
- Maintain top-k hypotheses (beams).
- At each step, extend each hypothesis with all possible tokens.
- Keep only the top-k scoring hypotheses.
- Repeat until end-of-sequence.
def beam_search(probs, beam_width=5):
# probs: (T, vocab_size)
sequences = [[[], 0.0]] # (tokens, score)
for t in range(len(probs)):
all_candidates = []
for seq, score in sequences:
for token in range(len(probs[t])):
new_seq = seq + [token]
new_score = score + np.log(probs[t][token])
all_candidates.append((new_seq, new_score))
# Keep top-k
sequences = sorted(all_candidates, key=lambda x: x[1], reverse=True)[:beam_width]
return sequences[0][0] # Return best sequence
Pros: Considers multiple hypotheses. Usually better than greedy. Cons: Computationally expensive. Still not globally optimal.
3.3. CTC Decoding
Connectionist Temporal Classification (CTC) is a loss function for sequence-to-sequence tasks where alignment is unknown.
Key Idea:
- Add a “blank” token (ε) to handle alignment.
- Multiple CTC paths map to the same output (e.g., “aa-ab” and “a-aab” both → “ab”).
CTC Decoding:
- Apply greedy or beam search to CTC output.
- Collapse consecutive duplicate tokens.
- Remove blank tokens.
def ctc_decode(probs, blank_token=0):
tokens = []
prev = -1
for t in range(len(probs)):
token = np.argmax(probs[t])
if token != prev and token != blank_token:
tokens.append(token)
prev = token
return tokens
3.4. Attention-Based Decoding
In encoder-decoder models (like Whisper, Seq2Seq), the decoder uses attention to focus on relevant parts of the encoder output.
Algorithm:
- Encoder processes audio → hidden states.
- Decoder autoregressively generates tokens.
- At each step, attention weights determine which encoder states to focus on.
def attention_decode(encoder_output, decoder, max_length=100):
tokens = [BOS_TOKEN] # Begin of sequence
for _ in range(max_length):
output = decoder(tokens, encoder_output)
next_token = np.argmax(output[-1])
tokens.append(next_token)
if next_token == EOS_TOKEN:
break
return tokens[1:-1] # Remove BOS and EOS
4. Language Model Integration
Problem: Acoustic model output may be noisy. Language models can correct grammatical errors.
Approaches:
4.1. Shallow Fusion
Idea: Combine AM and LM scores during beam search.
\[\text{score} = \log P_{AM}(y \mid x) + \lambda \log P_{LM}(y)\]Where λ is a tunable weight. Many systems also add a length bonus per word or token, because the LM term penalizes longer hypotheses.
def beam_search_with_lm(am_probs, lm, beam_width=5, lm_weight=0.5):
sequences = [[[], 0.0, 0.0]] # (tokens, am_score, lm_score)
for t in range(len(am_probs)):
all_candidates = []
for seq, am_score, lm_score in sequences:
for token in range(len(am_probs[t])):
new_seq = seq + [token]
new_am_score = am_score + np.log(am_probs[t][token])
new_lm_score = lm_score + lm.score(new_seq)
combined = new_am_score + lm_weight * new_lm_score
all_candidates.append((new_seq, new_am_score, new_lm_score, combined))
# Keep top-k by combined score
sequences = sorted(all_candidates, key=lambda x: x[3], reverse=True)[:beam_width]
return sequences[0][0]
4.2. Deep Fusion
Idea: Feed the hidden states of a separately trained LM into the ASR decoder through a learned gate, then fine-tune the fusion layers (Gulcehre et al., 2015). Cold fusion goes further and trains the decoder with the LM attached from the start.
Benefits: Tighter integration than shallow fusion. Drawbacks: Requires retraining when the LM changes. Less flexible.
4.3. Rescoring (N-Best Rescoring)
Idea:
- Generate N-best hypotheses with AM only.
- Rescore each hypothesis with a powerful LM (e.g., GPT).
- Return the highest-scoring hypothesis.
Benefits: Can use large, pretrained LMs. Drawbacks: Two-pass (slower).
5. CTC Beam Search with Language Model
Prefix Beam Search: Handles CTC’s blank tokens and collapsed outputs properly. The sketch below works in linear probability space for readability; real decoders use log space (see the step-by-step implementation).
Algorithm:
- Track two scores for each prefix:
- Pb (blank): Probability of prefix ending with blank.
- Pnb (non-blank): Probability of prefix not ending with blank.
- At each step, extend prefixes by:
- Adding a blank (only affects Pb).
- Repeating the last character (affects Pb/Pnb transition).
- Adding a new character (affects Pnb).
def ctc_beam_search_with_lm(probs, lm, beam_width=10, blank=0, lm_weight=0.5):
# probs: (T, vocab_size)
# Initialize
beams = {(): (1.0, 0.0)} # prefix: (pb, pnb)
for t in range(len(probs)):
new_beams = defaultdict(lambda: (0.0, 0.0))
for prefix, (pb, pnb) in beams.items():
for c in range(len(probs[t])):
p = probs[t][c]
if c == blank:
# Extend with blank
key = prefix
new_beams[key] = (new_beams[key][0] + (pb + pnb) * p, new_beams[key][1])
elif prefix and c == prefix[-1]:
# Repeat without a blank in between merges into the same prefix
new_beams[prefix] = (new_beams[prefix][0], new_beams[prefix][1] + pnb * p)
# Repeat after a blank starts a new copy of the character
new_key = prefix + (c,)
lm_factor = lm.score(new_key) ** lm_weight
new_beams[new_key] = (new_beams[new_key][0], new_beams[new_key][1] + pb * p * lm_factor)
else:
# New character
new_key = prefix + (c,)
lm_factor = lm.score(new_key) ** lm_weight
new_beams[new_key] = (new_beams[new_key][0], new_beams[new_key][1] + (pb + pnb) * p * lm_factor)
# Prune to beam_width
beams = dict(sorted(new_beams.items(), key=lambda x: sum(x[1]), reverse=True)[:beam_width])
# Return best prefix
best_prefix = max(beams, key=lambda x: sum(beams[x]))
return list(best_prefix)
6. System Design: Production ASR Decoder
Scenario: Build a real-time ASR system for voice assistants.
Requirements:
- Latency: < 200ms from end of utterance to transcription.
- Accuracy: WER < 10%.
- Streaming: Start transcribing before the user finishes speaking.
Architecture:
Step 1: Streaming Audio Input
- Audio arrives in 20ms chunks.
- Feature extraction (MFCC/Mel) in real-time.
Step 2: Streaming Acoustic Model
- Use a streaming-compatible architecture (e.g., Conformer with limited lookahead).
- Output probabilities every few frames (for example every 40ms after 4x subsampling of 10ms frames).
Step 3: Online Decoding
- Run CTC beam search incrementally.
- Emit partial results as hypotheses stabilize.
Step 4: Endpointing
- Detect when the user stops speaking.
- Finalize the transcription.
Step 5: Rescoring (Optional)
- Rescore final hypothesis with a larger LM.
7. Deep Dive: Weighted Finite State Transducers (WFST)
WFST is a mathematical framework for composing AM, LM, and lexicon.
Components:
- H (HMM): Maps senones to context-dependent phones.
- C (Context): Maps context-dependent phones to context-independent phones.
- L (Lexicon): Maps phones to words.
- G (Grammar): Language model (n-gram).
Composition:
\[\text{HCLG} = H \circ C \circ L \circ G\]Benefits:
- Efficient decoding using Viterbi algorithm on the composed graph.
- Caching: Precompute and store the composed graph.
Tools:
- Kaldi: Open-source ASR toolkit using WFST.
- OpenFst: Library for finite-state transducers.
8. Deep Dive: Streaming vs Non-Streaming
Non-Streaming (Offline):
- Process entire audio at once.
- Can use bidirectional models (look at future).
- Higher accuracy.
Streaming (Online):
- Process audio chunk by chunk.
- Cannot look at future (causality constraint).
- Lower latency, slightly lower accuracy.
Hybrid (Look-Ahead):
- Allow small lookahead (e.g., 200ms).
- Balance between latency and accuracy.
9. Word Error Rate (WER)
Definition:
\[\text{WER} = \frac{S + D + I}{N}\]Where:
- S = Substitutions (wrong word).
- D = Deletions (missing word).
- I = Insertions (extra word).
- N = Total words in reference.
Example:
- Reference: “the cat sat on the mat”
- Hypothesis: “the cat hat on a mat”
- Errors: S=1 (sat→hat), S=1 (the→a)
- WER = 2 / 6 = 33.3%
10. Decoding Optimizations
10.1. Pruning
Beam Pruning: Keep only top-k hypotheses. Threshold Pruning: Discard hypotheses with score < best_score - threshold. Histogram Pruning: Limit hypotheses per frame.
10.2. Lattice Generation
Instead of outputting a single transcription, output a lattice, a compact representation of all hypotheses.
Benefits:
- Rescoring: Apply different LMs later.
- Confidence Estimation: Compute confidence scores.
- N-Best Lists: Extract top-N transcriptions.
10.3. GPU Acceleration
- Batched Beam Search: Process multiple utterances in parallel.
- CUDA Implementations: Use GPU for matrix operations.
- TensorRT: Optimize inference.
11. Production Case Study: Whisper
Whisper (OpenAI):
- Architecture: Encoder-Decoder Transformer.
- Decoding: Greedy or beam search, with temperature fallback.
- Language Model: Implicit in the decoder.
- Multilingual: 99 languages.
Decoding Features:
- Timestamps: The decoder predicts segment-level timestamp tokens. Word-level timestamps in the open-source package come from aligning cross-attention weights with dynamic time warping.
- Temperature Fallback: If a segment’s decode looks like a failure (average log probability below a threshold, or a repetition loop), retry at a higher temperature.
- Compression Ratio Threshold: If the decoded text compresses too well with gzip (ratio above 2.4 by default), treat it as a repetition loop and retry.
- No-Speech Detection: If the no-speech probability is high and the log probability is low, emit nothing for that segment, which suppresses many hallucinations on silence.
12. Interview Questions
- Greedy vs Beam Search: When would you use each?
- CTC Decoding: Explain how blank tokens work.
- Language Model Integration: What is shallow fusion?
- Streaming ASR: How do you handle causality constraints?
- WFST: What is the role of the lexicon (L)?
- Calculate WER: Given reference and hypothesis, compute WER.
13. Common Mistakes
- Ignoring Blanks in CTC: Not collapsing consecutive tokens.
- Beam Width Too Small: Missing the correct hypothesis.
- LM Weight Too High: Over-relying on LM, ignoring AM.
- Not Handling OOV Words: Out-of-vocabulary words cause errors.
- Ignoring Latency: Production systems have strict latency requirements.
14. Deep Dive: Confidence Estimation
Problem: Not all transcriptions are equally reliable. How do we estimate confidence?
Approaches:
1. Posterior Probability:
- Use the probability of the best hypothesis.
-
confidence = P(W O), normalized over the N-best list or lattice.
2. Entropy:
- High entropy = low confidence (many competing hypotheses).
3. Word-Level Confidence:
- Compute confidence for each word using lattice posteriors.
4. Model-Based:
- Train a separate model to predict confidence from ASR features.
15. Deep Dive: Hot Words (Contextual Biasing)
Problem: ASR fails on domain-specific terms (e.g., product names, jargon).
Solution: Bias decoding towards expected words.
Approaches:
- N-Gram Boosting: Increase LM probability for hot words.
- Contextual LM: Condition LM on context (e.g., user’s recent queries).
- Shallow Fusion with Boosted LM: Add bonus score for hot words.
Example:
hot_words = ["Alexa", "Siri", "Cortana"]
hot_word_boost = 2.0 # Log-scale boost
def score_with_hotwords(seq, am_score, lm_score):
bonus = sum(hot_word_boost for word in seq if word in hot_words)
return am_score + lm_weight * lm_score + bonus
16. Future Trends
1. End-to-End LM Integration:
- Train AM and LM jointly (e.g., Hybrid Transducers).
2. LLM for Error Correction:
- Use GPT/LLaMA to post-process ASR output.
3. Multimodal Decoding:
- Use video (lip reading) to improve decoding.
4. On-Device Decoding:
- Run decoding on mobile devices (requires efficient implementations).
17. Deep Dive: RNN-Transducer (RNN-T) Decoding
RNN-T is a popular architecture for streaming ASR (used by Google, Meta).
Architecture:
- Encoder: Processes audio, outputs acoustic features.
- Prediction Network: RNN that processes output history.
- Joint Network: Combines encoder + prediction network outputs.
- Output: Probability over vocabulary + blank.
Decoding Algorithm:
def rnnt_greedy_decode(encoder_output, predictor, joint, max_symbols_per_step=10):
outputs = []
pred_state = predictor.initial_state()
# Prediction network output for the start-of-sequence token
pred_output, pred_state = predictor([BOS], pred_state)
for t in range(len(encoder_output)):
enc_t = encoder_output[t]
# Emit tokens at this frame until the joint network predicts blank
for _ in range(max_symbols_per_step):
logits = joint(enc_t, pred_output)
token = np.argmax(logits)
if token == BLANK:
break # Advance to the next frame
outputs.append(token)
# Only a non-blank emission updates the prediction network
pred_output, pred_state = predictor([token], pred_state)
return outputs
Key Difference from CTC:
- CTC: One output per time step.
- RNN-T: Can emit multiple tokens per time step (or none).
18. Production Case Study: Google’s On-Device Streaming Recognizer
Google described its first on-device streaming end-to-end recognizer in He et al., 2019:
- Model: RNN-Transducer, chosen because it streams naturally and needs no separate pronunciation model or decoding graph.
- Requirements named in the paper: streaming in real time, robustness to the long tail of queries, and use of user context such as contact lists.
- Result reported: the RNN-T model outperformed a conventional CTC-based model on both latency and accuracy in a number of evaluation categories.
Later Google work moved the encoder to Conformer blocks and added a second-pass or cascaded non-causal encoder to recover accuracy lost to streaming. Contextual biasing of contact and app names, quantization for mobile, and fast endpointing are standard parts of such systems.
19. Design Pattern: Two-Pass Decoding for Voice Assistants
Many assistant pipelines use a fast streaming first pass and a more accurate second pass:
- First pass: streaming CTC or RNN-T decoding with a small LM or none, producing partial results.
- Second pass: rescoring the N-best list or lattice with a larger LM (or a non-causal encoder) once the endpoint is detected.
- Downstream: NLU or an LLM consumes the final hypothesis.
Example latency budget (illustrative, not measured):
- Endpoint detection after the user stops: 50ms.
- Finalizing the first pass: 100ms.
- Second-pass rescoring: 50ms.
- Total: ~200ms from end of speech to final text.
Optimization:
- Endpointing: Detect speech end quickly.
- Prefetch: Start downstream processing on stable partial results during endpointing.
20. Benchmarking ASR Decoders
Metrics:
- WER: Word Error Rate.
- Latency: Time from audio end to transcription.
- RTF (Real-Time Factor): Processing time / Audio duration. RTF < 1 means faster than real-time.
Reference points (LibriSpeech test-clean / test-other WER):
- Conformer-L transducer: 2.1% / 4.3% without an LM, 1.9% / 3.9% with an external LM (Gulati et al., 2020).
- wav2vec 2.0 fine-tuned on all 960 labeled hours: 1.8% / 3.3% with an LM (Baevski et al., 2020).
RTF depends heavily on hardware, batch size, beam width and LM size, so measure it on your own stack rather than copying numbers. LibriSpeech is read audiobook speech; expect much higher WER on conversational or noisy audio (see the benchmark gap for voice agents).
21. Decoding for Low-Resource Languages
Challenge: Language models may not exist for low-resource languages.
Solutions:
- Multilingual Models: Use models trained on 100+ languages.
- Cross-Lingual Transfer: Fine-tune on target language with limited data.
- Character-Level LM: Train a small character LM.
- Phoneme-Based LM: Use phoneme sequences instead of words.
22. Advanced: Minimum Bayes Risk (MBR) Decoding
Problem: Beam search finds the most likely sequence, but not necessarily the one with the lowest WER.
MBR Approach:
- Generate N-best hypotheses.
- For each hypothesis, compute expected WER against all other hypotheses.
- Return the hypothesis with lowest expected WER.
Algorithm:
def mbr_decode(n_best_list):
# n_best_list: [(hypothesis, probability), ...]
best_hyp = None
best_risk = float('inf')
for hyp, prob in n_best_list:
risk = 0
for other_hyp, other_prob in n_best_list:
risk += other_prob * word_error_rate(hyp, other_hyp)
if risk < best_risk:
best_risk = risk
best_hyp = hyp
return best_hyp
Use Case: When WER is more important than likelihood.
23. Deep Dive: Subword Units
Problem: Character-level models have long sequences. Word-level models have OOV issues.
Solution: Subword units (BPE, SentencePiece).
Algorithm (BPE):
- Start with characters.
- Iteratively merge the most frequent adjacent pair.
- Stop when vocabulary size reached.
Example:
- “lower” → “l o w e r” → “lo w e r” → “low e r” → “low er” → “lower” (one merge per step)
Benefits:
- Handles rare words.
- Shorter sequences than characters.
- No OOV (can spell any word).
24. Decoding with Word Timestamps
Problem: Beyond transcription, we need to know when each word was spoken.
Approaches:
1. CTC Alignment:
- After decoding, use forced alignment to find timestamps.
2. Attention Weights:
- Use encoder-decoder attention to infer timestamps.
3. Whisper-Style:
- The decoder predicts timestamp tokens (such as
<|0.00|>and<|2.40|>) at segment boundaries; word-level times come from aligning cross-attention with dynamic time warping.
25. Decoding for Dictation vs Conversation
Dictation:
- User speaks clearly, slowly.
- Expects exact transcription.
- Punctuation and formatting expected.
Conversation:
- Multiple speakers, overlapping speech.
- Disfluencies (uh, um, repetitions).
- Informal language.
Decoding Differences:
- Dictation: Use strong LM, inverse text normalization (numbers, dates).
- Conversation: Use disfluency model, speaker diarization.
26. Implementation: PyTorch CTC Beam Search
import torch
from torchaudio.models.decoder import ctc_decoder
# Load lexicon and LM
decoder = ctc_decoder(
lexicon="lexicon.txt",
tokens="tokens.txt",
lm="language_model.arpa",
beam_size=50,
lm_weight=0.5,
word_score=-0.2
)
# Decode
emissions = model(audio) # (batch, T, vocab_size) float32 tensor on CPU
hypotheses = decoder(emissions)
# Get best hypothesis
best = hypotheses[0][0]
text = " ".join(best.words)
27. Interview Strategy: ASR Decoding
Step-by-Step:
- Explain the Problem: AM gives probabilities, need to find best text.
- Greedy: Simple but suboptimal.
- Beam Search: Better, introduce beam width.
- CTC Specifics: Blank token, collapsing.
- LM Integration: Shallow fusion, rescoring.
- Streaming: Discuss latency constraints.
- Trade-offs: Accuracy vs latency vs compute.
28. Testing ASR Decoders
Unit Tests:
- Test CTC collapsing: “aa-a-bb” → “ab”.
- Test beam search ranking.
- Test LM weight behavior.
Integration Tests:
- End-to-end: audio → transcription.
- Compare with baseline (e.g., Whisper).
Regression Tests:
- Test on standard benchmarks (LibriSpeech, Common Voice).
- Alert if WER increases.
29. Conclusion & Mastery Checklist
ASR decoding is the bridge between acoustic probabilities and human-readable text. The key is balancing:
- Accuracy: Use beam search and language models.
- Latency: Use streaming architectures and pruning.
- Flexibility: Use lattices and rescoring for adaptability.
Mastery Checklist:
- Implement greedy decoding
- Implement beam search
- Implement CTC decoding (with blank collapsing)
- Integrate language model (shallow fusion)
- Understand RNN-T decoding
- Implement N-best list generation
- Calculate WER correctly
- Handle streaming ASR
- Implement hot word boosting
- Benchmark RTF and WER
ASR decoding is where the magic happens, turning probabilities into words. The techniques you’ve learned here are the foundation for building voice assistants, transcription services, and real-time translation systems. As LLMs become more integrated with speech, the importance of efficient, accurate decoding will only grow.
Related reading:
- Custom Language Modeling: domain-specific LM integration for production ASR.
- Speech Pipeline Dependencies: orchestrating VAD, diarization, and ASR in a full pipeline.
- Speech Model Export: deploying streaming decoders to edge devices.
- Cross-Lingual Speech Transfer: adapting decoders for low-resource languages.
FAQ
What is the difference between greedy decoding and beam search in ASR?
Greedy decoding picks the most likely token at each time step, making it fast but suboptimal because it never reconsiders past decisions. Beam search maintains the top-k hypotheses at each step, exploring multiple paths simultaneously. While computationally more expensive, beam search typically produces significantly better transcriptions because it can recover from locally suboptimal choices.
How does CTC decoding handle alignment in speech recognition?
Connectionist Temporal Classification adds a special blank token to handle unknown alignment between audio frames and text output. During decoding, the model may output blanks or repeated characters at each time step. Post-processing collapses consecutive duplicate tokens and removes blanks, allowing multiple CTC paths to map to the same output sequence without requiring explicit alignment labels during training.
What is shallow fusion in ASR language model integration?
| Shallow fusion combines acoustic model and language model scores during beam search using a weighted sum: score = log P_AM(y | x) + lambda * log P_LM(y). The acoustic model judges how well the audio matches candidate text, while the language model judges how linguistically plausible that text is. The lambda weight is tuned to balance these two signals, and the approach requires no joint retraining. |
How does RNN-Transducer decoding differ from CTC decoding?
CTC emits exactly one output per time step and uses a simple blank/collapse mechanism. RNN-T uses a prediction network conditioned on output history and a joint network that combines encoder and predictor outputs. Crucially, RNN-T can emit multiple tokens per time step or none at all, giving it more flexibility to model variable-rate speech and token dependencies.