Deep Speech 2 (DS2) is an end-to-end speech recognition model that passes a spectrogram through convolutions and a deep bidirectional RNN and is trained with the CTC loss to output characters directly. It was published in 2015 by Baidu Research's Silicon Valley AI Lab (Amodei et al.). It showed that two very different languages, English and Mandarin, can be recognized with nearly the same model architecture.
Conventional speech recognition combined many hand-designed components: feature extraction, acoustic models, pronunciation dictionaries, language models, speaker adaptation, and more. Each component needed tuning, so moving to a new language or environment was hard. Like its predecessor Deep Speech (DS1), DS2 replaces most of these with a single neural network, and it improved accuracy by focusing on three things:
Model architecture: going deeper, with up to 3 convolutional layers and up to 7 bidirectional RNN layers, and stabilizing training with batch normalization and SortaGrad, which starts training from short utterances.
Large amounts of training data: 11,940 hours of transcribed English speech and 9,400 hours of Mandarin, plus data augmentation by adding noise.
Computational scale: optimizing a training system that runs synchronous SGD on 8 to 16 GPUs, making it 7 times faster than DS1.
The best English model reduced the word error rate by 43.4% relative to DS1 on a diverse internal test set and achieved 5.33% on LibriSpeech test-clean (human transcription: 5.83%). On 3 of 4 read-speech test sets, it outperformed human transcriptions collected via crowdsourcing.
Architecture
As shown on the left of the figure at the top of the article, DS2 processes its input in the following order:
Input: a power-normalized spectrogram of the audio.
Convolutions (1 to 3 layers): either 1D convolutions over time only, or 2D convolutions over frequency and time. The first layer uses a stride in time to reduce the number of time steps handled by the RNNs above.
Bidirectional RNNs (1 to 7 layers): the outputs of the forward and backward RNNs are summed to form the layer output. They can also be replaced with GRUs.
Fully connected layers (one or more).
Output layer: a softmax gives, at each time step, the probabilities of characters and the CTC blank. For English these are a to z, space, and apostrophe; for Mandarin, about 6,000 characters (including Roman letters).
Loss: trained with the CTC loss.
The activation function is a ReLU clipped at 20 (clipped ReLU):
σ(x)=min{max{x,0},20}
Bidirectional RNN layer l is computed as follows (Eqs. (2)(3)). The input-to-hidden weights Wl are shared between the forward and backward directions.
htl=f(Wlhtl−1+Ulht−1l+bl),hl=hl+hl
The best English model has 11 layers: 3 2D convolutional layers, 7 bidirectional RNN layers, and a fully connected output layer, with about 100 million parameters. The time stride of the first layer is 3, and the outputs are bigrams (described below). By contrast, DS1 was a 5-layer model with only one bidirectional RNN layer.
DS2's architecture has three stages: "capture the local shape of sounds with convolutions → connect the surrounding context with RNNs → output characters at each time step." CTC determines during training which character is output at which time step, so data segmented into individual phonemes is not needed.
Techniques for stable training: batch normalization and SortaGrad
To train deep RNNs on large amounts of data, DS2 introduced two techniques.
Sequence-wise batch normalization: in RNN layers, only the input term Wlhtl−1 is normalized, and no normalization is applied to the recurrent term (Eq. (8)). The mean and variance are computed per hidden unit over all utterances in the minibatch and all time steps of each sequence.
htl=f(B(Wlhtl−1)+Ulht−1l)
B denotes batch normalization. The paper also tried normalizing at each time step including the recurrent term, but it did not improve optimization. At inference, running averages of the mean and variance collected during training are used, so utterances can be recognized one at a time.
SortaGrad: in the first epoch only, training proceeds from short to long, ordered by the length of the longest utterance in each minibatch. From the second epoch on, it returns to the usual random order. Because the CTC loss is the log of a product of per-time-step probabilities (each less than 1), longer utterances tend to have larger losses, which makes large gradients and divergence of the RNN's internal state more likely early in training. It is a form of curriculum learning that uses utterance length as a proxy for difficulty.
The paper's comparison (word error rate on the English dev set, %; all models have 38 million parameters, with narrower layers as depth increases):
Configuration
Train: no BN
Train: BN
Dev: no BN
Dev: BN
1 RNN layer, 5 layers total
10.55
11.99
13.55
14.40
3 RNN layers, 5 layers total
9.55
8.29
11.61
10.56
5 RNN layers, 7 layers total
8.59
7.61
10.77
9.78
7 RNN layers, 9 layers total
8.76
7.68
10.83
9.52
The benefit of batch normalization grows with depth, reaching a 12% difference for the deepest model. On the other hand, for the shallowest model, batch normalization actually made things worse.
9-layer model (7 RNN layers)
Train: no BN
Train: BN
Dev: no BN
Dev: BN
Not sorted by length
10.71
8.04
11.96
9.78
SortaGrad
8.76
7.68
10.83
9.52
The effect of SortaGrad is especially large for the numerically unstable model without batch normalization, and using both gives even better results.
Comparing configurations: convolution, stride, and RNN type
Convolution along frequency (word error rate on the English dev sets, %; all models have 7 RNN layers and 1 fully connected layer, about 35 million parameters)
Convolution
Regular dev
Noisy dev
1D, 1 layer
9.52
19.36
1D, 3 layers
9.20
20.22
2D, 1 layer
8.94
16.22
2D, 3 layers
8.61
14.74
Convolving along frequency as well helps especially on noisy data: going from 1D with 1 layer to 2D with 3 layers reduced errors on the noisy dev set by 23.9%. The paper attributes this to frequency convolutions capturing speaker-dependent variability in spectral features more compactly than large fully connected layers.
Stride and bigram outputs: a larger stride in the first layer reduces the number of time steps the RNNs handle, lowering computation and memory, but hurts accuracy in English. This is because CTC requires at least one time step per output character, and English has many characters per second (an average of 14.1 characters per second in the training data, versus 3.3 for Mandarin). For English, therefore, the output unit was changed to bigrams, splitting words into non-overlapping pairs of characters. For example, "the cat sat" becomes [th, e, space, ca, t, space, sa, t].
First-layer stride
Unigram (no LM)
Bigram (no LM)
Unigram (with LM)
Bigram (with LM)
2
14.93
14.56
9.52
9.66
3
15.01
15.60
9.65
10.06
4
18.86
14.84
11.92
9.93
With bigrams, errors barely increased even with a stride of 4.
Simple RNN vs. GRU: with parameters matched at about 38 million, GRUs gave better results at every depth (for example, 9.78% vs. 7.79% with 7 layers total and 5 RNN layers). However, when the model was scaled up to 100 million parameters, the simple RNN became slightly better (regular / noisy dev: RNN 7.73 / 13.06%, GRU 7.78 / 14.17%). For this reason, most of the paper's experiments use simple RNNs.
Combining with a language model
Because DS2 is trained on large amounts of data, an implicit language model forms inside the network, and it can spell fairly accurately without external knowledge. Even so, far more text is available than transcribed speech, so combining an n-gram language model at inference improves results further.
At inference, beam search looks for the transcription y that maximizes the following score Q(y) (Eq. (12)):
Q(y)=logpctc(y∣x)+αlogplm(y)+βword_count(y)
α is the weight of the language model, and β is a bonus that favors more words; both are tuned on a dev set. The English language model is a 5-gram built from Common Crawl text (400,000-word vocabulary, about 850 million n-grams), and the Mandarin one is a character-level 5-gram. The beam width is 500 for English and 200 for Mandarin.
Language
Configuration
Without LM
With LM
English (WER)
5 layers total, 1 RNN layer
27.79
14.39
English (WER)
9 layers total, 7 RNN layers
14.93
9.52
Mandarin (CER)
5 layers total, 1 RNN layer
9.80
7.13
Mandarin (CER)
9 layers total, 7 RNN layers
7.55
5.81
The relative improvement from the language model became smaller with more RNN layers (from 48% to 36% in English). The paper attributes this to the implicit language model inside the network becoming stronger as the RNN gets deeper.
Experimental results
Amount of data (English, word error rate on the regular / noisy dev sets, %; 2 2D convolutional layers and 7 RNN layers, 68 million parameters)
Training data
Regular
Noisy
120 hours (1%)
29.23
50.97
1,200 hours (10%)
13.80
22.99
6,000 hours (50%)
9.51
15.90
12,000 hours (100%)
8.46
13.59
Each 10× increase in data reduced errors by about 40%, continuing to fall along a power law.
Read speech (word error rate, %; "Human" is the better transcription of two Amazon Mechanical Turk workers)
On 100 short voice-search-like utterances, DS2 achieved 3.7% against an error rate of 4.0% for a committee of 5 people transcribing together.
Streaming recognition: row convolution
A bidirectional RNN cannot transcribe the beginning of an utterance until it has heard the end, which makes it hard to use for services that return results while the user is speaking. DS2 solved this by placing a row convolution on top of forward-only RNNs.
A row convolution is a layer that uses only a small amount of future information, τ time steps ahead, for the prediction at the current time t. From the d×(τ+1) matrix formed by ht,…,ht+τ and a weight W of the same size, the output is computed as follows (Eq. (11)):
rt,i=j=1∑τ+1Wi,jht+j−1,i,1≤i≤d
It is called a "row convolution" because the future values are summed with separate weights for each dimension i (each row). The right of the figure at the top of the article shows an example with τ=2.
The Mandarin model used for deployment consists of 5 forward-only RNN layers (2,560 units), 1 row convolution layer (τ=19), and 1 fully connected layer (2,560 units). In an evaluation on 2,000 utterances, it reached a character error rate of 6.10% versus 5.81% for the bidirectional research model, a relative degradation of only 5%.
Deployment combines the following additional techniques:
Inference with 16-bit floating point: recognition accuracy did not change noticeably.
Batch Dispatch: audio from multiple users is batched and processed on the GPU together. With 10 concurrent audio streams, the median latency was 44 ms and the 98th percentile was 70 ms.
Beam search pruning: only characters whose cumulative probability reaches 0.99 (up to 40 characters) are considered as candidates. Mandarin language model lookups became 150 times faster, with a relative effect of 0.1 to 0.3% on the character error rate.
Practical notes
When using DS2, keep the following points in mind:
It assumes large amounts of data and compute: the paper's accuracy comes from about 10,000 hours of transcribed speech and several days of training on 8 to 16 GPUs. Reducing the data to 1% (120 hours) raised the error rate on the regular dev set from 8.46% to 29.23%.
Match the output unit and the stride: CTC requires at least one time step per output, so subsampling time too aggressively hurts accuracy for languages with many characters (such as English). Reduce the number of outputs with bigrams or similar, or use a smaller stride.
Handling batch normalization at inference: at inference, use the mean and variance collected during training (model.eval() in PyTorch). In shallow models, batch normalization can actually make things worse.
It cannot be used for streaming as a bidirectional model: to recognize speech while it is being spoken, switch to a configuration such as forward-only RNNs with row convolution. Input power normalization must also use statistics from the training data rather than the whole utterance.
Tuning the language model weights: tune α and β on a dev set.
CTC treats the outputs at each time step as independent of one another, so the network alone tends to leave spelling and word-order errors; in the paper as well, combining an external language model greatly reduced the word error rate (14.93% → 9.52% for the 9-layer model). When comparing, note that the numbers in the DS2 paper are mostly results with a language model.
Comparison with other models
Comparing representative end-to-end speech recognition models from the same angles gives the following:
Decoder learns from large amounts of transcriptions
Rough guidelines for choosing:
Learning the basic structure of CTC speech recognition or keeping the implementation simple: DS2's "convolution → RNN → CTC" structure is an easy-to-understand starting point. Because CTC outputs are independent, inference is fast and combining with an external language model is straightforward.
Little transcribed data is available: fine-tuning a self-supervised pre-trained model such as wav2vec 2.0 with CTC is a better fit.
Accuracy matters and a modern architecture is wanted: Transformer-based encoders such as Conformer are now mainstream. Models are commonly compared by word error rate (WER).
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
"""
A small implementation of the Deep Speech 2 shape (2D convolution -> bidirectional RNN with sequence-wise batch norm -> fully connected -> CTC).
Eq. (8) of the paper: h_t = f(B(W x_t) + U h_{t-1}). Batch norm is applied only to the input term, and W is shared by the forward and backward directions.
PyTorch's nn.CTCLoss takes log_softmax values of shape (time, batch, class). The default blank is 0.
"""
def clipped_relu(x):
return torch.clamp(x, min=0.0, max=20.0) # min(max(x, 0), 20)
class BNBiRNN(nn.Module):
def __init__(self, n_in, hidden):
super().__init__()
self.W = nn.Linear(n_in, hidden, bias=False) # shared by forward and backward. No bias, since normalization cancels it
self.bn = nn.BatchNorm1d(hidden) # sequence-wise: mean and variance over the batch and all time steps
self.U_f = nn.Linear(hidden, hidden, bias=False)
self.U_b = nn.Linear(hidden, hidden, bias=False)
def forward(self, x): # x: [B, T, n_in]
wx = self.bn(self.W(x).transpose(1, 2)).transpose(1, 2) # B(W x_t)
B, T, H = wx.shape
h_f, h_b = wx.new_zeros(B, H), wx.new_zeros(B, H)
out_f, out_b = [], []
for t in range(T): # forward
h_f = clipped_relu(wx[:, t] + self.U_f(h_f))
out_f.append(h_f)
for t in reversed(range(T)): # backward
h_b = clipped_relu(wx[:, t] + self.U_b(h_b))
out_b.append(h_b)
return torch.stack(out_f, 1) + torch.stack(out_b[::-1], 1) # sum the two directions
class DeepSpeech2(nn.Module):
def __init__(self, n_freq=161, n_classes=29, hidden=512, n_rnn=3):
super().__init__()
# 2D convolution (frequency × time). The first layer halves the time steps
self.conv = nn.Sequential(
nn.Conv2d(1, 32, (41, 11), stride=(2, 2), padding=(20, 5)), nn.BatchNorm2d(32), nn.Hardtanh(0, 20),
nn.Conv2d(32, 32, (21, 11), stride=(2, 1), padding=(10, 5)), nn.BatchNorm2d(32), nn.Hardtanh(0, 20))
f = (n_freq + 1) // 2
f = (f + 1) // 2
self.rnns = nn.ModuleList([BNBiRNN(32 * f if i == 0 else hidden, hidden) for i in range(n_rnn)])
self.fc = nn.Linear(hidden, n_classes) # characters + blank (index 0)
def forward(self, spec): # spec: [B, freq, time]
h = self.conv(spec.unsqueeze(1)) # [B, 32, F', T']
h = h.permute(0, 3, 1, 2).flatten(2) # [B, T', 32*F']
for rnn in self.rnns:
h = rnn(h)
return self.fc(h).log_softmax(-1) # [B, T', classes]
model = DeepSpeech2()
spec = torch.randn(4, 161, 300) # 3 seconds of spectrogram
targets = torch.randint(1, 29, (4, 40)) # target characters (0 is blank)
target_lengths = torch.tensor([40, 35, 30, 25])
model.train() # batch norm uses minibatch statistics
log_probs = model(spec)
input_lengths = torch.full((4,), log_probs.size(1), dtype=torch.long)
ctc = nn.CTCLoss(blank=0, zero_infinity=True)
loss = ctc(log_probs.transpose(0, 1), targets, input_lengths, target_lengths) # pass as (T, B, C)
loss.backward()
model.eval() # inference uses the mean and variance collected during training
class RowConv(nn.Module):
"""Row convolution (Eq. (11)): r_{t,i} = Σ_{j=1}^{τ+1} W_{i,j} h_{t+j-1,i}. Placed on top of forward-only RNNs"""
def __init__(self, d, tau=19):
super().__init__()
self.tau = tau
self.conv = nn.Conv1d(d, d, tau + 1, groups=d, bias=False) # separate weights per dimension
def forward(self, h): # h: [B, T, d]
h = nn.functional.pad(h.transpose(1, 2), (0, self.tau)) # look only τ steps ahead (pad the end with 0)
return self.conv(h).transpose(1, 2) # [B, T, d]
FAQ
Q. What is the difference between Deep Speech 2 and Deep Speech (DS1)?
A.
Both are end-to-end speech recognition systems that train RNNs with CTC, but DS2 made the model larger and deeper. DS1 was a 5-layer model with one bidirectional RNN layer, a first-layer stride of 2, and one character per output. DS2's best English model has 11 layers (about 100 million parameters) with 3 2D convolutional layers and 7 bidirectional RNN layers, a stride of 3, and bigram outputs. To train the deep model, sequence-wise batch normalization and SortaGrad were introduced. On a diverse internal test set, the word error rate fell from 24.01% to 13.59%.
Q. What is SortaGrad?
A.
It is a method that trains on utterances sorted from short to long in the first epoch only, then returns to random order from the second epoch. Because the CTC loss tends to be larger for longer utterances, feeding long utterances early in training makes large gradients and divergence of the RNN state more likely. For the paper's 9-layer model, the dev-set word error rate fell from 11.96% to 10.83% without batch normalization and from 9.78% to 9.52% with it.
Q. Can Deep Speech 2 be used for streaming (incremental recognition)?
A.
The bidirectional research model cannot be used as is, but the paper presents a unidirectional model with a "row convolution" placed on top of forward-only RNNs. The row convolution uses only the next 19 time steps (τ=19) for the prediction at the current time, so it can output incrementally with a small delay. In Mandarin, its character error rate was 6.10% versus 5.81% for the bidirectional model.