AI Logic

Architectures

Listen, Attend and Spell

Updated:

Structure of Listen, Attend and Spell. Left: the Listener (input filterbanks → BLSTM → pBLSTM × 3; each layer merges two adjacent time steps, producing h at 1/8 of the original length). Right: the Speller's computation for one character (previous character and previous context → 2-layer LSTM giving state s_i → attention over all of h giving context c_i → MLP and softmax giving the next-character probabilities)

Background and Overview

Listen, Attend and Spell (LAS) is an encoder-decoder model that transcribes speech directly into a character sequence by combining a "Listener" that turns audio into features with a "Speller" that attends to those features while emitting characters one at a time. It was proposed in 2015 by Chan et al. at Google Brain and Carnegie Mellon University.

Conventional speech recognition trained an acoustic model, a pronunciation dictionary, and a language model separately, each with its own objective, and then combined them. At the time, end-to-end approaches that trained a single network fell into two lines of work.

  • CTC: Assumes the output characters are conditionally independent given the input. As a result, it cannot decide the next character based on the characters it has already emitted.
  • Attention-based Sequence to Sequence: Successful in tasks such as machine translation, but in speech it had been limited to outputting phoneme sequences.

LAS extended the latter to end-to-end speech recognition that outputs characters directly from audio. It expresses the output probability as a product of probabilities, each conditioned on all previous characters, so it makes no independence assumption between characters. It also relies on neither hidden Markov models (HMMs) nor a pronunciation dictionary.

In experiments on a subset of Google voice search (about 3 million utterances, 2,000 hours), it achieved a word error rate of 14.1% without a dictionary or language model, and 10.3% when candidates were rescored with a language model. The best system on the same data at the time, a CLDNN-HMM, scored 8.0%.

Architecture: Listener and Speller

LAS maps input filterbank features x=(x1,…,xT)\mathbf{x} = (x_1, \dots, x_T) to a character sequence y=(⟨sos⟩,y1,…,yS,⟨eos⟩)\mathbf{y} = (\langle\mathrm{sos}\rangle, y_1, \dots, y_S, \langle\mathrm{eos}\rangle). The characters are a–z, 0–9, space, comma, period, apostrophe, and an unknown symbol. The output probability is factorized by the chain rule into a product of probabilities conditioned on the previous characters (Eq. (1)).

P(y∣x)=∏iP(yi∣x,y<i)P(\mathbf{y} \mid \mathbf{x}) = \prod_i P(y_i \mid \mathbf{x}, y_{<i})

The model consists of the following two parts. In the figure at the top of the article, the left side is the Listener and the right side is the Speller's computation for one character.

h=Listen(x),P(y∣x)=AttendAndSpell(h,y)\mathbf{h} = \mathrm{Listen}(\mathbf{x}), \qquad P(\mathbf{y} \mid \mathbf{x}) = \mathrm{AttendAndSpell}(\mathbf{h}, \mathbf{y})

The Listener is an encoder that stacks bidirectional LSTMs (BLSTMs) in a pyramid.

  1. Bottom BLSTM: Reads every time step of the input.
  2. Three pyramidal BLSTM (pBLSTM) layers: Each layer concatenates the outputs of two adjacent time steps from the layer below into one time step and feeds it to a BLSTM (Eq. (5)). Each layer halves the length in time.
  3. Output: A feature sequence h=(h1,…,hU)\mathbf{h} = (h_1, \dots, h_U) whose length is reduced by a factor of 23=82^3 = 8.
hij=pBLSTM(hi−1j,[h2ij−1,h2i+1j−1])h^j_i = \mathrm{pBLSTM}\left(h^j_{i-1}, \left[h^{j-1}_{2i}, h^{j-1}_{2i+1}\right]\right)

The Speller is a two-layer attention-based LSTM decoder. Each time it emits a character yiy_i, it performs the following computation (Eqs. (6)–(8)).

  1. Update the state: An LSTM computes a new state sis_i from the previous state si−1s_{i-1}, the previous character yi−1y_{i-1}, and the previous context ci−1c_{i-1}.
  2. Build the context with attention: A context vector cic_i is computed from sis_i and the Listener output h\mathbf{h}.
  3. Output the character distribution: sis_i and cic_i are fed to an MLP with a softmax output, which gives the probabilities of the next character.
ci=AttentionContext(si,h),si=RNN(si−1,yi−1,ci−1),P(yi∣x,y<i)=CharacterDistribution(si,ci)c_i = \mathrm{AttentionContext}(s_i, \mathbf{h}), \qquad s_i = \mathrm{RNN}(s_{i-1}, y_{i-1}, c_{i-1}), \qquad P(y_i \mid \mathbf{x}, y_{<i}) = \mathrm{CharacterDistribution}(s_i, c_i)

The attention is content-based. The decoder state sis_i and each Listener time step huh_u are passed through MLPs ϕ\phi and ψ\psi, respectively; their inner product is turned into weights αi,u\alpha_{i,u} by a softmax, and the weighted sum of huh_u becomes the context (Eqs. (9)–(11)).

ei,u=⟨ϕ(si),ψ(hu)⟩,αi,u=exp⁡(ei,u)∑u′exp⁡(ei,u′),ci=∑uαi,u hue_{i,u} = \left\langle \phi(s_i), \psi(h_u) \right\rangle, \qquad \alpha_{i,u} = \frac{\exp(e_{i,u})}{\sum_{u'} \exp(e_{i,u'})}, \qquad c_i = \sum_u \alpha_{i,u}\, h_u

In the paper's configuration, the Listener has three pBLSTM layers (512 units each, 256 per direction) on top of one input BLSTM layer, and the Speller has two LSTM layers of 512 units.

As the name suggests, the model mirrors how a person takes dictation: listen → attend to the relevant part → spell. Each time the Speller writes a character, it uses attention to choose again which part of the recording to listen to.

Training

The Listener and Speller are trained jointly as a single network. The basic objective feeds the ground-truth previous characters y<i∗y^*_{<i} to the Speller and maximizes the sum of the log probabilities of the next characters (Eq. (12)).

max⁡θ∑ilog⁡P(yi∣x,y<i∗;θ)\max_\theta \sum_i \log P(y_i \mid \mathbf{x}, y^*_{<i}; \theta)

At inference time, however, there is no ground truth, so the model feeds its own predictions back as the next input. Because it always saw the correct previous characters during training, a single mistake can easily derail the later predictions. The paper therefore feeds, at a fixed rate during training, a character sampled from the model's distribution instead of the ground truth as the next input (Eqs. (13)(14)).

y~i∼CharacterDistribution(si,ci),max⁡θ∑ilog⁡P(yi∣x,y~<i;θ)\tilde{y}_i \sim \mathrm{CharacterDistribution}(s_i, c_i), \qquad \max_\theta \sum_i \log P(y_i \mid \mathbf{x}, \tilde{y}_{<i}; \theta)

y~i−1\tilde{y}_{i-1} is either the ground-truth character or a character sampled from the model. The original proposal (Scheduled Sampling) changes the rate as training progresses, but LAS uses a constant 10% from the start of training.

The other training settings are as follows.

ItemValue
DataAbout 3 million Google voice search utterances (2,000 hours). Augmented 20× by simulating room reverberation and adding noise
Input40-dimensional log-mel filterbanks (every 10 ms)
InitializationUniform distribution U(−0.1,0.1)U(-0.1, 0.1)
OptimizationAsynchronous SGD (32 replicas, 32 utterances per minibatch)
Learning rateStarts at 0.2, multiplied by 0.98 every 3 million utterances (1/20 of an epoch)
Training timeAbout 2 weeks for the model trained with ground truth only

The paper also tried pretraining the Listener with phonemes produced by a conventional GMM-HMM system and using phonemes as an auxiliary training target, but reports that neither helped.

Inference: Beam Search and Language Models

At inference, a left-to-right beam search looks for the most probable character sequence y^=arg⁡max⁡ylog⁡P(y∣x)\hat{\mathbf{y}} = \arg\max_{\mathbf{y}} \log P(\mathbf{y} \mid \mathbf{x}).

  1. Start from 〈sos〉 and keep β\beta partial hypotheses (the beam width).
  2. At each step, extend every hypothesis by every possible character and keep only the β\beta most probable.
  3. A hypothesis that emits 〈eos〉 is removed from the beam and added to the set of complete hypotheses.

The search can be restricted to real words with a dictionary, but in the paper this did not affect the word error rate, because the model learns to spell real words in almost all cases.

To exploit text, which is far more plentiful than transcribed audio, the paper reranked the top 32 hypotheses with an n-gram language model (rescoring). Because LAS has a slight bias toward short outputs, the log probability is divided by the number of characters ∣y∣c|\mathbf{y}|_c before the language-model probability is added with weight λ\lambda (Eq. (16)).

s(y∣x)=log⁡P(y∣x)∣y∣c+λlog⁡PLM(y)s(\mathbf{y} \mid \mathbf{x}) = \frac{\log P(\mathbf{y} \mid \mathbf{x})}{|\mathbf{y}|_c} + \lambda \log P_{\mathrm{LM}}(\mathbf{y})

λ\lambda is tuned on validation data and was 0.008 in the paper. The language model is used only to rerank the final 32 hypotheses, not during the search.

Why It Works

The paper states that both the pyramidal Listener and attention were necessary for LAS to work well.

  • The pyramid shortens the sequence: Speech runs to hundreds or thousands of frames. With a plain BLSTM as the Listener, training converged slowly even after a month and the results were worse. The paper attributes this to attention having difficulty extracting the relevant information from so many time steps. Reducing the length by a factor of 8 also lowers the attention cost O(US)O(US) (UU is the length of the Listener output and SS is the length of the output).
  • Attention keeps the model listening: Without attention, the model overfit heavily even with 3 million training utterances, memorizing the training transcripts instead of listening to the audio.
  • Characters are not treated as independent: Because the Speller conditions each character on all previous ones, it can produce several spellings for the same sound. For an utterance pronounced "triple a", both "aaa" and "triple a" appeared among the top hypotheses. The paper argues that CTC, whose outputs are mutually independent, would struggle to produce such different transcriptions.
  • Rare and out-of-vocabulary words can be handled: Since it emits one character at a time, it can spell words that are not in any vocabulary.

Inspecting the attention weights shows that even purely content-based attention, with no positional cues, aligned characters and audio roughly monotonically from left to right. It also correctly located the start and end of each utterance.

Even without an external language model, the Speller acquires linguistic knowledge from the training transcripts. In the paper's example, the fourth hypothesis for "triple a" was "xxx", which sounds completely different. Because "xxx" appears often in the training data, the implicit language model inside the Speller is thought to have associated "triple" with "xxx".

Experimental Results

Word error rates (%) on Google voice search (22,000 test utterances, about 16 hours) are shown below. The noisy test set adds noise and reverberation in the same way as the training data. LAS searches with a beam width of 32.

ModelCleanNoisy
CLDNN-HMM (best at the time)8.08.9
LAS16.219.0
LAS + LM rescoring12.614.7
LAS + sampling14.116.5
LAS + sampling + LM rescoring10.312.0
  • Effect of sampling: Feeding the model's outputs at a 10% rate during training lowered the clean error rate from 16.2% to 14.1%.
  • Effect of the language model: Rescoring the top 32 hypotheses brought it further down to 10.3%.
  • Gap to the best system: Within 2.5 points on clean speech and less than 3.0 points on noisy speech. The paper notes that adding the convolutions used by the CLDNN-HMM could improve results.

Widening the beam up to 16 reduced errors; beyond that, there was almost no change. If the hypothesis closest to the ground truth could be chosen from the top 32 (an oracle), the error rate would be 4.3% clean and 5.5% noisy, showing that the correct transcription is often among the candidates.

By utterance length, long utterances had higher error rates, dominated by deletions. This is thought to be because the training data contained few long utterances, and a model trained on short utterances did not generalize well to long ones. On the other hand, very short utterances of two words or fewer also had high error rates, mainly from substitutions and insertions.

Practical Considerations

Keep the following points in mind when using LAS.

  • Weak on long utterances: On utterances longer than those in the training data, errors from skipping words (deletions) increase. The paper suggests that location-based attention cues might help.
  • Not suited to streaming recognition: The Listener is a bidirectional LSTM and the attention looks at the entire Listener output every step, so the model transcribes only after hearing the whole utterance.
  • Mismatch between training and inference: Training only on ground-truth previous characters makes the model fragile once it errs at inference. As in the paper, feeding the model's own output as the next input at a fixed rate helps.
  • How to combine with a language model: LAS slightly favors short outputs, so when reranking with a language model, normalize by the number of characters before adding the LM score.
  • Training cost: Recurrent networks are computed step by step in time, which makes training hard to parallelize; in the paper it took about two weeks.

The pyramidal Listener was added because the paper found that training did not progress well without shortening the sequence. When implementing it yourself, check that two adjacent time steps are concatenated before being fed to the next layer (not summed, and not with one discarded), and that the input is padded or trimmed so its length is a multiple of 2number of layers2^{\text{number of layers}}.

Comparison with Other Models

Representative end-to-end speech recognition models compare as follows.

ModelEncoderHow outputs are producedDependence between outputsStreaming
CTC (e.g., Deep Speech 2)Convolution + RNNEmits a character or blank at each time stepAssumed independentPossible if the encoder is unidirectional
RNN-TransducerBidirectional LSTM, etc.Chooses blank or a character at each time step; a prediction network also sees previous outputsModeled by the prediction networkPossible if the encoder is unidirectional
Listen, Attend and SpellPyramidal bidirectional LSTMAttends to the whole input and emits one character at a timeModeled by the decoderDifficult
Speech-TransformerConvolution + TransformerAttends to the whole input and emits one character at a timeModeled by the decoderDifficult
WhisperConvolution + TransformerAttends to the whole input and emits one token at a timeModeled by the decoderDifficult (per 30-second segment)

Like additive attention (Bahdanau) in machine translation, LAS attention uses the decoder state to weight every encoder time step, but it computes the weights with an inner product after MLPs.

Rough guidelines for choosing:

  • To learn dependencies between outputs within one model and transcribe while seeing the whole utterance: An attention-based encoder-decoder like LAS fits. Today, Speech-Transformer and Whisper, which use Transformers for the encoder and decoder, are the mainstream form.
  • To recognize incrementally while the speaker is still talking: RNN-Transducer fits.
  • To keep computation light and combine easily with an external language model: CTC fits.

PyTorch example

Show code
python
import random
import torch
import torch.nn as nn

"""
A small implementation of Listen, Attend and Spell.
Listener: 1 BLSTM layer → 3 pBLSTM layers (concatenate two adjacent time steps to halve the length)
Speller: 2 LSTM layers + content-based attention e = <phi(s), psi(h)> + MLP character distribution
During training, 10% of the time the next input is a character sampled from the model's distribution instead of the ground truth (Section 3.3 of the paper).
"""

SOS, EOS = 1, 2


class PyramidalBLSTM(nn.Module):
    def __init__(self, n_in, hidden):
        super().__init__()
        self.rnn = nn.LSTM(2 * n_in, hidden, batch_first=True, bidirectional=True)

    def forward(self, x):                                  # x: [B, T, D]
        B, T, D = x.shape
        x = x[:, : T - T % 2].reshape(B, T // 2, 2 * D)    # concatenate two adjacent time steps → half the length
        out, _ = self.rnn(x)
        return out                                         # [B, T/2, 2*hidden]


class Listener(nn.Module):
    def __init__(self, n_mels=40, hidden=256):
        super().__init__()
        self.blstm = nn.LSTM(n_mels, hidden, batch_first=True, bidirectional=True)
        self.pyramid = nn.Sequential(*[PyramidalBLSTM(2 * hidden, hidden) for _ in range(3)])

    def forward(self, x):
        h, _ = self.blstm(x)
        return self.pyramid(h)                             # length is 1/8, [B, U, 2*hidden]


class Speller(nn.Module):
    def __init__(self, n_chars=33, d_h=512, hidden=512, d_att=128):
        super().__init__()
        self.embed = nn.Embedding(n_chars, hidden)
        self.rnn = nn.LSTM(hidden + d_h, hidden, num_layers=2, batch_first=True)   # s_i = RNN(s_{i-1}, y_{i-1}, c_{i-1})
        self.phi = nn.Sequential(nn.Linear(hidden, d_att), nn.ReLU(), nn.Linear(d_att, d_att))
        self.psi = nn.Sequential(nn.Linear(d_h, d_att), nn.ReLU(), nn.Linear(d_att, d_att))
        self.char_dist = nn.Sequential(nn.Linear(hidden + d_h, hidden), nn.ReLU(), nn.Linear(hidden, n_chars))

    def step(self, y_prev, c_prev, state, h, psi_h):
        inp = torch.cat([self.embed(y_prev), c_prev], -1).unsqueeze(1)
        s, state = self.rnn(inp, state)
        s = s.squeeze(1)                                                # s_i
        e = (psi_h @ self.phi(s).unsqueeze(-1)).squeeze(-1)            # e_{i,u} = <phi(s_i), psi(h_u)>
        alpha = torch.softmax(e, dim=-1)                                # α_{i,u}
        c = (alpha.unsqueeze(-1) * h).sum(1)                            # c_i = Σ α_{i,u} h_u
        logits = self.char_dist(torch.cat([s, c], -1))                  # P(y_i | x, y_<i)
        return logits, c, state, alpha

    def forward(self, h, targets, sample_rate=0.1):
        B = h.size(0)
        psi_h = self.psi(h)
        y_prev = torch.full((B,), SOS, dtype=torch.long)
        c = h.new_zeros(B, h.size(-1))
        state, outs = None, []
        for i in range(targets.size(1)):
            logits, c, state, _ = self.step(y_prev, c, state, h, psi_h)
            outs.append(logits)
            if self.training and random.random() < sample_rate:        # 10%: sample from the model
                y_prev = torch.distributions.Categorical(logits=logits).sample()
            else:                                                       # otherwise: ground-truth character
                y_prev = targets[:, i]
        return torch.stack(outs, 1)                                     # [B, S, n_chars]


listener, speller = Listener(), Speller()
feats = torch.randn(2, 800, 40)                     # 8 seconds of 40-dim log-mel filterbanks (every 10 ms)
targets = torch.randint(3, 33, (2, 30))             # ground-truth characters (EOS assumed at the end)

listener.train(); speller.train()
h = listener(feats)                                 # [2, 100, 512] (length is 1/8)
logits = speller(h, targets)
loss = nn.functional.cross_entropy(logits.reshape(-1, 33), targets.reshape(-1))
loss.backward()

listener.eval(); speller.eval()                     # at inference, no sampling; search with beam search

FAQ

Q. What is the difference between LAS and CTC?
A.

CTC assumes that, given the input, the outputs at each time step are mutually independent, and emits a character or blank at each time step. LAS conditions each character on all previously emitted characters, so it makes no independence assumption. This lets LAS propose different spellings for the same sound, such as "aaa" and "triple a". On the other hand, because LAS attends to the whole input, it transcribes only after hearing the entire utterance.

Q. Why is the Listener pyramidal?
A.

Speech is long—hundreds to thousands of frames—and at that length attention has trouble extracting the information it needs. In the paper, a plain BLSTM converged slowly even after a month of training and gave worse results. Each pBLSTM layer concatenates two adjacent time steps to halve the length, reaching 1/8 after three layers. This also reduces the attention cost O(US)O(US), speeding up training and inference.

Q. Why feed sampled model outputs during training?
A.

If only ground-truth previous characters are fed during training, the model easily breaks down at inference when it receives its own mistaken outputs. The paper fed characters sampled from the model's distribution at a constant 10% rate from the start of training, which lowered the word error rate without a language model from 16.2% to 14.1%.

References

  1. Chan, W., Jaitly, N., Le, Q. V., & Vinyals, O. (2015). Listen, Attend and Spell. arXiv:1508.01211.
  2. Bengio, S., Vinyals, O., Jaitly, N., & Shazeer, N. (2015). Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks. arXiv:1506.03099.