RNN-Transducer (RNN-T) is a model that converts a sequence of acoustic features into a sequence of characters or phonemes whose length and boundaries are unknown. It combines a network that reads the audio with a network that predicts the next output from the outputs emitted so far, and uses information from both to decide what to emit next (or to emit nothing). It was proposed by Graves at the University of Toronto in 2012.
In speech recognition, the input (features every 10 ms) and the output (characters or phonemes) differ in length, and it is not known which character should be emitted at which time step. The earlier CTC solved this problem by adding a blank that means "emit nothing" and summing the probabilities of all possible alignments. CTC, however, has two limitations.
It cannot model dependencies between outputs: CTC treats the output at each time step as independent of the others, so it cannot learn relationships in the output sequence such as "E tends to follow TH".
The output cannot be longer than the input: only one symbol can be emitted per time step.
RNN-T inherits the idea of CTC (add a blank and sum over all alignments) while adding a prediction network that reads the outputs emitted so far, so a single model jointly learns the relationship between input and output and the dependencies among the outputs. Any number of labels can be emitted at a single time step.
In the paper's TIMIT experiments (English phoneme recognition), the phoneme error rate was 23.2%, compared with 25.5% for CTC. RNN-T has since become one of the standard forms of speech recognition, combined with encoders such as Conformer.
Architecture
RNN-T consists of the following three parts. In the figure at the top of the article, the left side shows the overall flow and the right side shows the output lattice.
Let there be K label types, and consider the K+1 symbols obtained by adding the blank ∅ ("emit nothing").
Transcription network: reads the input sequence forward and backward, and outputs a vector ft of size K+1 at each time step t. It plays almost the same role as the CTC network and represents the acoustic information. It also reads backward so that the output at each time step can see the entire input sequence.
Prediction network: reads the output sequence with a blank prepended, (∅,y1,…,yU), one element at a time, and outputs a vector gu of size K+1. Labels are fed as one-hot vectors, and the leading blank is represented by an all-zero vector. Because it "predicts the next label from the previous outputs", its role is close to that of a language model.
Output distribution: for every pair of time step t and output position u, the two vectors are added and passed through a softmax to give the probability of symbol k (equations (12)(13) of the paper).
Pr(k∣t,u)=∑k′exp(ftk′+guk′)exp(ftk+guk)
The paper by Graves et al. the following year (2013) changed this so that, instead of adding the two vectors, they are combined by an output network with one tanh hidden layer (equations (15)–(18)). lt is the top hidden state of the transcription network passed through a linear layer, and pu is the hidden state of the prediction network.
The paper reports that this form combines acoustic and linguistic information more richly, and in particular reduces deletion errors (failing to emit a phoneme that should be emitted). This part is what is now called the "joint network".
It helps to think of the transcription network as handling "the sound being heard now" and the prediction network as handling "the flow of the sentence so far", with the output distribution combining the two opinions to decide the next character. Figure 3 of the paper shows that at the vowel position in "SHOULD", the transcription network proposes O, U, and L simultaneously, the prediction network strongly predicts O, and O is the highest in the combined distribution.
Training: summing all alignments over the lattice
RNN-T is trained by minimizing the negative log probability of the target sequence y∗, L=−lnPr(y∗∣x). The probability is computed as follows.
Represent an alignment as a sequence that includes blanks: let B be the mapping that removes blanks from a sequence a containing blanks. For example, (y1,∅,∅,y2,∅,y3) becomes (y1,y2,y3). The positions of the blanks determine the alignment between input and output.
Sum the probabilities of all alignments that collapse to the target (equation (1)): Pr(y∣x)=∑a∈B−1(y)Pr(a∣x).
Count alignments as paths on a lattice: consider a lattice whose horizontal axis is the input time step t (1…T) and whose vertical axis is the number of labels emitted so far u (0…U). From a point (t,u), the path either emits a blank and moves to the next time step (horizontal arrow, probability ∅(t,u)), or emits the next label yu+1 and stays at the same time step (vertical arrow, probability y(t,u)). The set of all paths that start at the bottom-left (1,0) and end by emitting a final blank at (T,U) corresponds to all alignments.
Sum with forward variables: let α(t,u) be "the probability of emitting the first u labels by time step t", computed in order by the following equation (equations (16)(17), α(1,0)=1).
Combine with backward variables to obtain the gradient: using β(t,u), computed from the end in the same way, gives the gradient of the loss with respect to the probability at each point, and both networks can be trained with backpropagation through time.
α(t,u)β(t,u) is "the total probability of the paths passing through point (t,u)", and summing it along the diagonal t+u=n from the top-left to the bottom-right of the lattice gives Pr(y∗∣x) for every n (equation (19)).
The right side of the figure at the top of the article shows the lattice when the target is C, A, T and the input has 5 time steps. The thick path emits C at time 1, a blank at time 2, A and T in succession at time 3, and ends with blanks at times 4 and 5. Consecutive vertical arrows show that multiple labels can be emitted at a single time step.
The CTC lattice "always emits exactly one symbol per time step", so the path moves one step to the right every time. In the RNN-T lattice, the path chooses between moving right (blank) and moving up (label), so its length is T+U, and outputs longer than the input can also be handled.
Inference: beam search
Finding the most probable output sequence for an input with a trained RNN-T is harder than training. This is because the output gu of the prediction network depends on all the labels emitted so far.
The paper searches the tree of output sequences with a beam search of width W (Algorithm 1).
At each time step t, take the most probable candidate from the set of candidates and expand it into the case of emitting a blank and moving to the next time step and the cases of appending one label k.
Candidates with an appended label can be expanded further within the same time step, so paths that emit multiple labels at one time step are also searched.
Once W candidates have advanced to the next time step and they are more probable than the remaining candidates, the search for that time step ends.
Finally, select the sequence with the largest log probability divided by its length, logPr(y)/∣y∣.
The prediction network can compute the next output from only the previous hidden state and the new label. By storing the hidden state of each candidate and advancing the computation by just one step, the search can be made much faster (at the cost of more memory).
The 2012 paper considered length normalization important, because without dividing by length, short outputs are selected too often. The 2013 paper, on the other hand, dropped the normalization and ranks candidates by the raw probability, stating that normalization helps only when deletion errors are far more frequent than insertions. Check which works better on the data at hand.
Why it works
RNN-T outperforms CTC because it learns acoustic information and the dependencies between outputs (linguistic information) jointly, with the same loss.
It can use the dependencies between outputs: the prediction network predicts the next label from the previous outputs. When the sound alone is hard to distinguish, knowledge such as "this label tends to follow this sequence" can fill the gap.
It also learns how to combine the two sources of information: the output distribution is built from two vectors, one acoustic and one linguistic, so how much to trust each source is also learned from data. This differs from conventional speech recognition, where separately built acoustic and language models were combined afterward.
The input and output lengths are unconstrained: in principle it can also be applied to problems where the output is longer than the input.
In the paper's analysis (Figure 3), for character-level speech recognition the prediction network became less sensitive at the spaces between words, and the transcription network became more sensitive to high-energy regions. Both networks were influenced by distant parts of the input and output.
On the other hand, in the paper's TIMIT experiments the gap with CTC was rather small. The paper suggests this is probably because the TIMIT transcriptions (about 150,000 labels) are too few to train the prediction network. In fact, the prediction network alone missed nearly three quarters of the next phonemes. The paper proposes training on larger data, or pretraining the prediction network on large output-only data.
Experimental results
The 2012 paper (TIMIT phoneme recognition; 39 phonemes, core test set of 192 utterances)
The input is 26-dimensional: 12 MFCC coefficients computed from a 26-channel mel filter bank plus energy, together with their deltas. The prediction network is one LSTM layer with 128 units, the transcription network is two LSTM layers with 128 units, and the whole RNN-T has 261,328 weights. The log loss is in bits per target phoneme.
Network
Training epochs
Log loss (bits)
Error rate
Prediction network only
58
4.0
72.9%
CTC
96
1.3
25.5%
RNN-T
76
1.0
23.2%
(The error rate for the prediction network alone is the error rate of predicting the next phoneme from the previous ones. For CTC and RNN-T it is the phoneme error rate.)
RNN-T achieved lower log loss and lower phoneme error rate than CTC. Training used SGD with learning rate 10−4 and momentum 0.9 (updating after each utterance), and Gaussian weight noise with standard deviation 0.075 was added to reduce overfitting. The beam width of the RNN-T beam search is 4,000.
The 2013 paper (also TIMIT; deep bidirectional LSTM and an output network with a tanh hidden layer)
Network
Weights
Phoneme error rate
CTC (3 layers, 250 units each)
3.8M
18.6%
CTC (5 layers, 250 units each)
6.8M
18.4%
RNN-T (3 layers, 250 units each)
4.3M
18.3%
RNN-T (3 layers, 250 units each, pretrained)
4.3M
17.7%
The pretrained RNN-T starts from the weights of a trained CTC network and a network that predicts phonemes, with only the output network trained from random initialization. The paper states that the advantage of RNN-T is slight when trained from random initialization, but the gap widens with pretraining. The paper reports 17.7% as the best result on TIMIT at the time.
Practical notes
Keep the following points in mind when using RNN-T.
Match the blank index: the loss functions in libraries take an argument that determines which index is treated as the blank (rnnt_loss in PyTorch's torchaudio uses the last index if not specified). If it does not match the model's output, training will not work correctly.
Streaming requires a forward-only encoder: the transcription network in the paper is bidirectional, so it produces output only after hearing the end of the utterance. To recognize incrementally while someone is still speaking, changes such as making the transcription network forward-only are needed.
Only transcribed data can be used to train the prediction network: since the prediction network is trained only on transcriptions paired with audio, knowledge from large text-only data is not included as is. The paper proposes pretraining the prediction network.
Search is slow: because the output of the prediction network depends on past outputs, the prediction network must be run for each output candidate.
During training, the output distribution is computed for all (t,u) pairs at once, producing a tensor of size "batch × number of time steps T × (output length U + 1) × (number of labels + 1)". With thousands of subword types and long utterances, memory runs out easily. Adjust by downsampling time steps in the encoder, reducing the number of label types, or using smaller batches.
Comparison with other models
Comparing the main designs that transcribe speech into text without known alignments, from the same viewpoints, gives the following.
Difficult as is, since it looks at the whole input
All of them can be trained without human-provided alignments between input and output. They differ in how they model the dependencies between outputs and in which part of the input they look at to produce each output.
Rough guidelines for choosing:
To keep computation light and implementation simple: CTC is a good fit. Dependencies between outputs are usually supplied by an external language model.
To recognize incrementally while someone is still speaking: RNN-T is a good fit. Because it decides "emit or advance" in time order, it is easy to adapt to streaming recognition by making the encoder forward-only. The Conformer paper also trains its encoder output with an RNN-T that has a one-layer LSTM decoder.
To transcribe accurately after seeing the whole utterance: an attention-based encoder-decoder is a good fit. Whisper also takes this form. Comparisons are usually made with the word error rate (WER).
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torchaudio
"""
A small implementation of the three parts of RNN-T (transcription network, prediction network, output network),
trained with torchaudio's rnnt_loss. The output network uses the tanh hidden layer form of Graves et al. (2013).
Note: the logits for rnnt_loss have size "batch x time steps T x (output length U + 1) x (number of labels + 1)".
If blank is not specified, the last index is the blank. Here, 0 is the blank.
With fused_log_softmax=True (the default), pass the values before softmax as is.
"""
BLANK = 0
class Transcription(nn.Module): # Transcription network F: bidirectional LSTM
def __init__(self, n_in, hidden, n_layers=2):
super().__init__()
self.rnn = nn.LSTM(n_in, hidden, n_layers, batch_first=True, bidirectional=True)
self.proj = nn.Linear(2 * hidden, hidden) # l_t (merges forward and backward)
def forward(self, x): # x: [B, T, n_in]
h, _ = self.rnn(x)
return self.proj(h) # [B, T, H]
class Prediction(nn.Module): # Prediction network G: one LSTM layer
def __init__(self, n_labels, hidden):
super().__init__()
# Make the embedding of index 0 (blank) a zero vector (the paper feeds the leading blank as a zero vector)
self.embed = nn.Embedding(n_labels + 1, hidden, padding_idx=BLANK)
self.rnn = nn.LSTM(hidden, hidden, batch_first=True)
def forward(self, y, state=None): # y: [B, U] (labels are 1..K)
y = nn.functional.pad(y, (1, 0), value=BLANK) # prepend a blank -> [B, U+1]
p, state = self.rnn(self.embed(y), state)
return p, state # p: [B, U+1, H]
class Joint(nn.Module): # Output network (equations (16)(17) of the 2013 paper)
def __init__(self, hidden, n_labels):
super().__init__()
self.w_l = nn.Linear(hidden, hidden)
self.w_p = nn.Linear(hidden, hidden, bias=False)
self.out = nn.Linear(hidden, n_labels + 1) # K labels + blank
def forward(self, l, p): # l: [B, T, H], p: [B, U+1, H]
h = torch.tanh(self.w_l(l).unsqueeze(2) + self.w_p(p).unsqueeze(1)) # [B, T, U+1, H]
return self.out(h) # [B, T, U+1, K+1] (before softmax)
class RNNT(nn.Module):
def __init__(self, n_in=80, n_labels=29, hidden=256):
super().__init__()
self.f = Transcription(n_in, hidden)
self.g = Prediction(n_labels, hidden)
self.joint = Joint(hidden, n_labels)
def forward(self, x, y):
p, _ = self.g(y)
return self.joint(self.f(x), p)
@torch.no_grad()
def greedy_decode(self, x, max_symbols=5):
"""Decode one utterance greedily for simplicity (the paper uses beam search). x: [1, T, n_in]"""
l = self.f(x)[0] # [T, H]
out, state = [], None
p, state = self.g.rnn(self.g.embed(torch.tensor([[BLANK]])), state)
for t in range(l.size(0)):
for _ in range(max_symbols): # multiple labels can be emitted at one time step
logits = self.joint(l[t].view(1, 1, -1), p)[0, 0, 0]
k = int(logits.argmax())
if k == BLANK: # blank: move to the next time step
break
out.append(k) # emit the label and advance the prediction network one step
p, state = self.g.rnn(self.g.embed(torch.tensor([[k]])), state)
return out
model = RNNT()
x = torch.randn(2, 120, 80) # [batch, time, features]
x_len = torch.tensor([120, 100], dtype=torch.int32)
y = torch.randint(1, 30, (2, 15), dtype=torch.int32) # targets (1..29, 0 is blank)
y_len = torch.tensor([15, 11], dtype=torch.int32)
model.train()
logits = model(x, y.long()) # [2, 120, 16, 30]
loss = torchaudio.functional.rnnt_loss(
logits, y, x_len, y_len, blank=BLANK, reduction="mean") # mean of -ln Pr(y* | x)
loss.backward()
model.eval() # no dropout in this example, so behavior is the same
print(model.greedy_decode(x[:1]))
FAQ
Q. What is the difference between RNN-T and CTC?
A.
Both add a blank that means "emit nothing" and are trained by summing the probabilities of all paths corresponding to the target. The difference is that RNN-T has a prediction network that reads the outputs emitted so far. CTC treats the output at each time step as independent of the others, whereas RNN-T also learns the dependencies between outputs. In addition, CTC can emit only one symbol per time step, while RNN-T can emit any number of labels at a single time step. In the paper's TIMIT experiments, the phoneme error rate was 23.2% for RNN-T versus 25.5% for CTC.
Q. What is the joint network of a "Transducer"?
A.
It is the part that combines the output of the transcription network with the output of the prediction network and produces the probabilities of the labels and the blank. In the original 2012 paper, the two vectors were simply added and passed through a softmax. The 2013 paper replaced this with a network that has one tanh hidden layer, which reduced deletion errors. Most current implementations use this form.
Q. Does the RNN-T encoder have to be an RNN?
A.
No. Despite the name, the training method (summing all alignments over the lattice) does not depend on the type of encoder. The Conformer paper trains an RNN-T whose transcription network is a Conformer encoder and whose prediction network is a one-layer LSTM.