AI Logic

Architectures

Tacotron 2

Updated:

Tacotron 2 architecture. Left: the overall flow (the encoder goes character sequence β†’ character embedding β†’ 3 convolutional layers β†’ bidirectional LSTM; the decoder goes previous frame β†’ pre-net β†’ 2 LSTM layers (connected both ways with location-sensitive attention) β†’ linear projection β†’ mel spectrogram β†’ post-net β†’ add residual β†’ WaveNet β†’ speech waveform. A separate linear projection and sigmoid on the LSTM output produce the stop token, and the predicted frame is fed back as input to the next step). Right: inside location-sensitive attention (scores are computed from the decoder state, the per-character representations, and location features obtained by convolving the cumulative attention weights so far; a softmax turns them into weights that form the context vector)

Background and Overview

Tacotron 2 is a text-to-speech (TTS) model that generates speech from text in two stages: an attention-based seq2seq network that predicts a mel spectrogram from a character sequence, and a WaveNet that generates the waveform from that mel spectrogram. It was published in 2018 by Shen et al. at Google (ICASSP 2018).

Earlier approaches each had weaknesses.

  • Tacotron: It learns everything from characters to spectrogram in one network, but Griffin-Lim, used to produce the waveform, introduces characteristic artifacts that cap audio quality.
  • WaveNet: It produces waveforms with quality approaching human speech, but its inputs require linguistic features, fundamental frequency, and phoneme durations, which in turn require elaborate text analysis and a pronunciation dictionary.

Tacotron 2 combines the strengths of both by predicting a mel spectrogram with a Tacotron-style network and converting it to a waveform with a WaveNet conditioned on it. Because mel spectrograms are easy to compute from waveforms, the two components can be trained separately.

On an internal US English dataset, it achieved a MOS (mean opinion score) of 4.526, close to the 4.582 of human recordings. Under the same conditions, Tacotron (Griffin-Lim) scored 4.001 and WaveNet conditioned on linguistic features scored 4.341.

Architecture

Tacotron 2 consists of two parts: a spectrogram prediction network and a WaveNet vocoder. The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of location-sensitive attention.

The intermediate representation is an 80-channel mel spectrogram. A short-time Fourier transform with 50 ms frames, a 12.5 ms hop, and a Hann window is applied, the result is passed through an 80-channel mel-scale filterbank spanning 125 Hz to 7.6 kHz, values below 0.01 are clipped up, and the logarithm is taken. The mel scale represents the low frequencies important for intelligibility in fine detail and the noisier high frequencies coarsely, so it captures the essentials of speech in few dimensions.

The spectrogram prediction network processes inputs in the following order.

  1. Character embedding: Characters are mapped to 512-dimensional vectors.
  2. 3 convolutional layers: Convolutions with 512 filters of width 5 (spanning 5 characters), each followed by batch normalization and ReLU, are applied three times. They capture longer-range context in the character sequence.
  3. Bidirectional LSTM: One layer with 512 units (256 per direction) produces the encoder output.
  4. Location-sensitive attention: At each decoder step, the entire sequence of encoder outputs is summarized into a single context vector.
  5. Pre-net: The frame predicted at the previous step passes through 2 fully connected layers of 256 units (ReLU). The paper reports that this information bottleneck was essential for learning attention.
  6. Decoder LSTM: The pre-net output and the context vector are concatenated and fed into 2 unidirectional LSTM layers (1,024 units).
  7. Linear projection: The LSTM output and the context vector are concatenated, and a linear projection predicts the mel spectrogram one frame at a time.
  8. Stop token: A separate linear projection maps the same concatenation to a scalar, and a sigmoid predicts the probability that the output has finished. At inference, generation stops at the first frame where this probability exceeds 0.5.
  9. Post-net: 5 convolutional layers (512 filters of width 5, batch normalization, and tanh on all but the last layer) predict a residual that is added to the prediction from step 7 to refine details.

Location-sensitive attention (Chorowski et al. 2015) extends additive attention by adding the cumulative attention weights from previous steps as a feature. With decoder state sis_i, the jj-th encoder output hjh_j, and location features fi,jf_{i,j} obtained by applying a 1D convolution FF to the cumulative weights βˆ‘k<iΞ±k\sum_{k<i} \alpha_k, it is computed as follows.

fi=Fβˆ—βˆ‘k<iΞ±kei,j=w⊀tanh⁑(Wsi+Vhj+Ufi,j+b)Ξ±i,j=exp⁑(ei,j)βˆ‘jβ€²exp⁑(ei,jβ€²),ci=βˆ‘jΞ±i,j hj\begin{aligned} f_i &= F * \textstyle\sum_{k<i} \alpha_k \\ e_{i,j} &= w^\top \tanh\left(W s_i + V h_j + U f_{i,j} + b\right) \\ \alpha_{i,j} &= \frac{\exp(e_{i,j})}{\sum_{j'} \exp(e_{i,j'})}, \qquad c_i = \sum_j \alpha_{i,j}\, h_j \end{aligned}

In the paper's setup, inputs and location features are projected to 128 dimensions, and location features are computed with 32 1D convolution filters of length 31. Knowing "where it has looked so far" makes it easier to move forward through the input characters consistently, reducing failures where parts are repeated or skipped.

The WaveNet vocoder modifies the original WaveNet as follows.

  • 30 dilated convolution layers: Grouped into 3 cycles of 10 layers, with the dilation rate of layer kk (k=0,…,29k = 0, \dots, 29) being 2kβ€Šmodβ€Š102^{k \bmod 10} (dilated convolution).
  • Conditioning upsampling: To match the 12.5 ms frame hop, the conditioning stack uses 2 upsampling layers instead of 3.
  • Output distribution: Instead of selecting a value bin with a softmax, it generates 16-bit samples at 24 kHz using a mixture of 10 logistic distributions (MoL).

Compared with Tacotron, it replaces CBHG and GRUs with plain LSTMs and convolutions, and drops the trick of emitting multiple frames per step (reduction factor), emitting one frame per step.

Training

The two components are trained separately, in the order spectrogram prediction network β†’ WaveNet.

The loss for the spectrogram prediction network is the sum of the mean squared errors before and after the post-net. The decoder is trained by feeding it the ground-truth frames (teacher forcing).

ItemSpectrogram prediction networkWaveNet
Training inputCharacter sequence and ground-truth mel spectrogramMel spectrogram predicted by running the spectrogram prediction network in teacher-forcing mode
Batch size64 (1 GPU)128 (synchronous updates across 32 GPUs)
OptimizationAdam (Ξ²1=0.9\beta_1 = 0.9, Ξ²2=0.999\beta_2 = 0.999, Ο΅=10βˆ’6\epsilon = 10^{-6})Adam (Ξ²1=0.9\beta_1 = 0.9, Ξ²2=0.999\beta_2 = 0.999, Ο΅=10βˆ’8\epsilon = 10^{-8})
Learning rate10βˆ’310^{-3}, decayed exponentially to 10βˆ’510^{-5} starting after 50,000 stepsFixed at 10βˆ’410^{-4}
RegularizationL2 regularization with weight 10βˆ’610^{-6}; dropout 0.5 on convolutions and Zoneout 0.1 on LSTMsExponential moving average of parameters (decay 0.9999) used for inference
LossSum of mean squared errors before and after the post-netNegative log-likelihood of the ground-truth samples

WaveNet is trained not on mel spectrograms computed from ground-truth audio but on predicted mel spectrograms. Because they are produced in teacher-forcing mode, the predicted frames are exactly time-aligned with the ground-truth waveform.

Dropout (0.5) in the decoder's pre-net is also applied at inference. The paper says this is to introduce output variation at inference.

The data is an internal US English dataset (one professional female speaker, 24.6 hours), the same as in the Tacotron paper. Numbers and the like are spelled out, e.g., "16" β†’ "sixteen".

Because the spectrogram prediction network is trained with mean squared error, its predictions tend to be smoother and less detailed than the ground truth. Training WaveNet on those predictions lets it produce high-quality waveforms even from smooth inputs.

Effect of Each Component

The paper compares MOS while swapping components.

Combinations of features for training and synthesizing with WaveNet (MOS)

Features used to train WaveNet \ features used for synthesisPredictedGround truth
Predicted4.526 Β± 0.0664.449 Β± 0.060
Ground truth4.362 Β± 0.0664.522 Β± 0.055

Using the same kind of features for training and synthesis worked best, and training on ground truth but synthesizing from predictions was worse. This is because predicted spectrograms are oversmoothed.

Predicted representation and vocoder (MOS)

SystemMOS
Linear spectrogram + Griffin-Lim3.944 Β± 0.091
Linear spectrogram (1,025 dimensions) + WaveNet4.510 Β± 0.054
Mel spectrogram (80 dimensions) + WaveNet4.526 Β± 0.066

Switching to WaveNet gave a large improvement over Griffin-Lim, and the difference between linear and mel was small. The paper concludes that the more compact mel spectrogram is the better choice.

Post-net: Removing it lowered MOS from 4.526 to 4.429. Because the decoder predicts one frame at a time from left to right, it cannot use future frames it has not yet produced. The post-net corrects the prediction by looking at surrounding frames. Although WaveNet also contains convolutions, the post-net was still needed.

WaveNet size (receptive field and number of layers)

LayersCyclesLayers per cycleReceptive field (samples / ms)MOS
303106,139 / 255.84.526 Β± 0.066
2446505 / 21.04.547 Β± 0.056
1226253 / 10.54.481 Β± 0.059
3030161 / 2.53.930 Β± 0.076

Even 12 layers with a 10.5 ms receptive field produced high audio quality. The paper reasons that the mel spectrogram already captures long-range dependencies across frames, allowing a smaller WaveNet. However, removing dilation so that the receptive field becomes extremely narrow (last row) greatly lowered quality even with the same number of layers.

A WaveNet conditioned on linguistic features has to turn pronunciation and duration information into a waveform by itself. A mel spectrogram is a representation much closer to the waveform, so WaveNet's job reduces to converting a spectrogram into a waveform (a vocoder), which a small network can handle.

Experimental Results

MOS comparison (with 95% confidence intervals)

SystemMOS
Parametric3.492 Β± 0.096
Tacotron (Griffin-Lim)4.001 Β± 0.087
Concatenative4.166 Β± 0.091
WaveNet (linguistic features)4.341 Β± 0.051
Ground-truth recording4.582 Β± 0.053
Tacotron 24.526 Β± 0.066

The evaluation used 100 sentences selected from the internal dataset's test set, each rated by at least 8 raters on a 1–5 scale in increments of 0.5. The parametric and concatenative systems were production systems at Google.

Other evaluation results are as follows.

  • Side-by-side comparison with human recordings: The mean score on a βˆ’3 to 3 scale was βˆ’0.270Β±0.155-0.270 \pm 0.155, a small but statistically significant preference for the human recordings. Rater comments indicated the main reason was occasional mispronunciation.
  • 100 difficult sentences from Deep Voice 3: MOS 4.354. Counting errors, there were 0 sentences with repeated words, 6 with mispronunciations, 1 with skipped words, and 23 with unnatural prosody; the end-of-utterance prediction failed only on the single longest sentence.
  • 37 news headlines (sentences from a different domain than training): Tacotron 2 scored 4.148 Β± 0.124 and WaveNet with linguistic features 4.137 Β± 0.128, nearly the same. Pronunciation sometimes failed on names and similar words.

The paper concludes that while attention reliably traverses the entire input, there is room to improve prosody modeling.

Practical Considerations

Keep the following points in mind when using Tacotron 2.

  • Mind the evaluation conditions: The paper's test sentences share phrases and words with the training data. The paper itself notes that MOS may be higher than for sentences made of random words. Still, since all compared systems were trained on the same data, it argues that relative comparisons are meaningful.
  • Inference is slow: Spectrogram prediction is autoregressive one frame at a time, and WaveNet generates samples one at a time. Real-time use requires measures such as replacing the vocoder with one that generates in parallel.
  • Data covering the intended use is needed: Names and other words absent from the training data are prone to mispronunciation. The paper notes that end-to-end approaches need training data that covers the intended usage.
  • Behavior differs between training and inference: Pre-net dropout is also applied at inference, so the same sentence sounds slightly different each time it is synthesized. Other dropout, Zoneout, and batch normalization are switched to inference mode with model.eval().
  • Trained on single-speaker data: The paper uses 24.6 hours from one speaker. Public datasets include the English single-speaker LJ Speech and the Japanese single-speaker JSUT.

Training WaveNet only on mel spectrograms computed from ground-truth audio lowers quality when synthesizing from predicted mel spectrograms (4.526 β†’ 4.362 in the paper's comparison). When training in two stages, the paper's method is to train the vocoder on predictions from the spectrogram prediction network run in teacher-forcing mode.

Comparison with Other Models

Representative models that generate mel spectrograms from text compare as follows.

ModelEncoderCharacter–frame alignmentHow the decoder generatesWaveform generation in the paper
TacotronCBHGContent-based attentionAutoregressive (GRU, rr frames at a time)Griffin-Lim
Tacotron 23 conv layers + bidirectional LSTMLocation-sensitive attentionAutoregressive (LSTM, one frame at a time)WaveNet
Transformer TTSTransformer encoderMulti-head attentionAutoregressive (Transformer decoder)WaveNet
FastSpeechFFT blocksPredicts per-phoneme durations and expandsNon-autoregressive (all frames in parallel)WaveGlow

Rough guidelines for choosing:

  • You want the standard autoregressive TTS setup: Tacotron 2 is the baseline. The pre-net, stop token, post-net, and two-stage design of mel spectrogram plus vocoder were carried over into models such as Transformer TTS.
  • You want faster training or to capture long-range dependencies in long sentences: Transformer TTS replaces the RNNs with a Transformer. In its paper, each training step was about 4.25x faster.
  • You want faster inference or to prevent skipping and repetition: Non-autoregressive models such as FastSpeech are suitable. In the FastSpeech paper's evaluation on 50 difficult sentences, Tacotron 2 had repetitions or skips in 24% of sentences, while FastSpeech had 0%.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio

"""
1. Generate speech from text with torchaudio's pretrained Tacotron 2 (trained on LJ Speech)
   Note: torchaudio's vocoder is WaveRNN, not the paper's WaveNet (a Griffin-Lim version is also available).
   The features torchaudio provides vary by version, so check the documentation for the version you use
2. A small implementation of the paper's location-sensitive attention (convolving the cumulative weights into features)
"""

# --- 1. torchaudio's Tacotron 2 ---
bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_CHAR_LJSPEECH   # character-input version
processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().eval()   # inference mode (Zoneout, batch normalization, etc.)
vocoder = bundle.get_vocoder().eval()

with torch.inference_mode():
    tokens, lengths = processor("Hello world! Text to speech.")
    spec, spec_lengths, _ = tacotron2.infer(tokens, lengths)   # [batch, 80, frames]
    waveforms, _ = vocoder(spec, spec_lengths)
torchaudio.save("output.wav", waveforms[0:1].cpu(), sample_rate=vocoder.sample_rate)


# --- 2. Location-sensitive attention ---
class LocationSensitiveAttention(nn.Module):
    def __init__(self, query_dim=1024, memory_dim=512, attn_dim=128, n_filters=32, kernel=31):
        super().__init__()
        self.W = nn.Linear(query_dim, attn_dim, bias=False)    # decoder state s
        self.V = nn.Linear(memory_dim, attn_dim, bias=False)   # encoder output h_j
        self.F = nn.Conv1d(1, n_filters, kernel, padding=kernel // 2, bias=False)
        self.U = nn.Linear(n_filters, attn_dim, bias=True)     # location feature f_j (bias b is included here)
        self.w = nn.Linear(attn_dim, 1, bias=False)

    def forward(self, s, memory, cum_weights, mask=None):
        # s: [B, query_dim], memory: [B, T, memory_dim], cum_weights: [B, T] (cumulative weights so far)
        f = self.F(cum_weights.unsqueeze(1)).transpose(1, 2)    # [B, T, n_filters]
        e = self.w(torch.tanh(self.W(s).unsqueeze(1) + self.V(memory) + self.U(f))).squeeze(-1)
        if mask is not None:
            e = e.masked_fill(~mask, float("-inf"))              # ignore zero-padded characters
        alpha = F.softmax(e, dim=-1)                            # [B, T]
        context = torch.bmm(alpha.unsqueeze(1), memory).squeeze(1)   # Ξ£ Ξ±_j h_j
        return context, alpha


attn = LocationSensitiveAttention()
memory = torch.randn(2, 40, 512)        # encoder outputs for 2 sentences of 40 characters
cum = torch.zeros(2, 40)
for step in range(3):                    # 3 decoder steps
    s = torch.randn(2, 1024)             # in practice, the LSTM output
    context, alpha = attn(s, memory, cum)
    cum = cum + alpha                    # add the weights to the cumulative sum for the next step
print(context.shape, alpha.shape)        # torch.Size([2, 512]) torch.Size([2, 40])

FAQ

Q. How does Tacotron 2 differ from Tacotron?
A.

There are three main differences.

  • Waveform generation: Griffin-Lim is replaced by a WaveNet conditioned on mel spectrograms
  • Components: CBHG and GRUs are replaced by simpler building blocks: convolutions and LSTMs
  • Attention and output: It uses location-sensitive attention, emits one frame per step, and decides when to finish with a stop token

In the paper's comparison under the same conditions, Tacotron (Griffin-Lim) scored a MOS of 4.001, while Tacotron 2 scored 4.526.

Q. Why predict a mel spectrogram instead of a linear spectrogram?
A.

Because with WaveNet as the vocoder, audio quality was almost the same for a 1,025-dimensional linear spectrogram (MOS 4.510) and an 80-dimensional mel spectrogram (4.526). The lower-dimensional mel spectrogram is more compact and easier to predict, and the paper considers it the better choice.

Q. What is the stop token for?
A.

It lets the model itself decide when to stop generating. At each decoder step it predicts the probability that the output has finished, and at inference generation stops at the first frame where this exceeds 0.5. Without it, the model would keep generating up to a fixed length. In the paper's evaluation on 100 difficult sentences, the end-of-utterance prediction failed only on the single longest sentence.

References

  1. Shen, J., Pang, R., Weiss, R. J., Schuster, M., Jaitly, N., Yang, Z., Chen, Z., Zhang, Y., Wang, Y., Skerry-Ryan, R. J., Saurous, R. A., Agiomyrgiannakis, Y., & Wu, Y. (2018). Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions. ICASSP 2018. arXiv:1712.05884.
  2. Tacotron 2 audio samples (by the paper's authors)
  3. Chorowski, J., Bahdanau, D., Serdyuk, D., Cho, K., & Bengio, Y. (2015). Attention-Based Models for Speech Recognition. NeurIPS 2015. arXiv:1506.07503.
  4. Wang, Y., et al. (2017). Tacotron: Towards End-to-End Speech Synthesis. arXiv:1703.10135.
  5. PyTorch. torchaudio.pipelines (Tacotron2TTSBundle).