AI Logic

Architectures

Tacotron

Updated:

Tacotron architecture. Left: the overall flow (the encoder goes character sequence β†’ character embedding β†’ pre-net β†’ CBHG; the decoder goes output of the previous step β†’ pre-net β†’ attention RNN β†’ attention β†’ decoder RNN β†’ linear layer emitting r frames at a time β†’ mel spectrogram β†’ post-net (CBHG) β†’ linear spectrogram β†’ Griffin-Lim β†’ speech waveform; the last of the r frames is fed back as the next step's input). Right: inside CBHG (bank of 1D convolutions β†’ max pooling along time β†’ 1D convolution projections Γ— 2 β†’ residual connection with the input β†’ highway layers Γ— 4 β†’ bidirectional GRU)

Background and Overview

Tacotron is an attention-based sequence-to-sequence text-to-speech (TTS) model that predicts speech spectrograms directly from character sequences. It was proposed in 2017 by Wang et al. at Google. It can be trained as a single model from random initialization using only (text, audio) pairs.

Earlier statistical parametric speech synthesis chained together components such as the following.

  • Text frontend: extracts linguistic features from text
  • Duration model: decides the length of each sound
  • Acoustic feature model: predicts acoustic features
  • Vocoder: converts acoustic features into a waveform with signal processing

Each component requires domain expertise and is trained separately, so errors compound. Tacotron replaces these with a single neural network and also learns the per-phoneme timing alignment automatically with attention.

However, a vanilla seq2seq model does not learn character-to-speech synthesis well. The output is continuous-valued and much longer than the input, so prediction errors accumulate quickly. Tacotron solved this with the following ideas.

  • CBHG: a module that extracts features from sequences by combining a convolution bank, highway layers, and a bidirectional GRU
  • Pre-net: fully connected layers with dropout placed at the entrance of the encoder and decoder
  • Emitting rr frames per step: reduces the number of decoder steps to 1/r1/r
  • Post-net: reviews the entire decoder output and turns it into a spectrogram that is easier to convert into a waveform

On an internal North American English dataset, it achieved a 5-point MOS (mean opinion score) of 3.82, outperforming a production parametric system (3.69).

Architecture

Tacotron consists of three parts: an encoder, an attention-based decoder, and a post-net. The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of CBHG.

From text to speech waveform, processing proceeds as follows.

  1. Character embedding: Each character is mapped to a 256-dimensional vector.
  2. Encoder pre-net: Fully connected (256) β†’ ReLU β†’ dropout (0.5) β†’ fully connected (128) β†’ ReLU β†’ dropout (0.5). It acts as a bottleneck, which the paper says helps convergence and improves generalization.
  3. Encoder CBHG: Produces per-character representations. The paper reports less overfitting and fewer mispronunciations than a multi-layer RNN encoder.
  4. Attention RNN: A 1-layer GRU (256) produces the attention query at each decoder step.
  5. Attention: Content-based tanh attention (the same form as additive attention) decides which characters to attend to and produces a context vector.
  6. Decoder RNN: The attention RNN output and the context vector are concatenated and fed into a 2-layer GRU (256) with vertical residual connections.
  7. Output layer: A fully connected layer emits an 80-band mel-scale spectrogram, rr frames per step.
  8. Post-net (CBHG): Predicts a linear-frequency spectrogram from the entire sequence of decoder outputs.
  9. Griffin-Lim: Estimates the phase from the spectrogram and synthesizes a waveform.

The first decoder step receives an all-zero frame (the <GO> frame). At inference, the last frame of the rr frames emitted at step tt is used as the input at step t+1t+1. During training, the last ground-truth frame of every group of rr frames is fed in.

CBHG (1-D Convolution Bank + Highway network + bidirectional GRU) is a module based on machine translation research (Lee et al. 2016) and processes inputs in the following order.

  1. Convolution bank: KK sets of 1D convolutions with widths k=1,2,…,Kk = 1, 2, \dots, K are applied to the input in parallel and their outputs are concatenated. They capture patterns of 1, 2, …, KK consecutive characters (nn-grams).
  2. Max pooling: Applied along time with stride 1. It adds robustness to small shifts without changing the sequence length.
  3. Convolution projections: Two 1D convolutions of width 3 are stacked, and the result is added to the input sequence (residual connection).
  4. Highway layers: Four layers extract higher-level features.
  5. Bidirectional GRU: Extracts sequential features from both forward and backward context.

Batch normalization is applied to every convolution.

The paper's settings (Table 1) are as follows.

ComponentSetting
Character embedding256 dimensions
Encoder CBHGConv bank K=16K = 16 (128 channels each, ReLU), max pooling (width 2, stride 1), projections width 3, 128 β†’ width 3, 128, 4 highway layers (128), bidirectional GRU (128)
Pre-net (encoder and decoder)FC 256 β†’ dropout 0.5 β†’ FC 128 β†’ dropout 0.5
Attention RNN1-layer GRU (256)
Decoder RNN2-layer residual GRU (256)
Post-net CBHGConv bank K=8K = 8 (128 channels each), projections width 3, 256 β†’ width 3, 80, 4 highway layers (128), bidirectional GRU (128)
Frames per step rr2

Training

The loss is the L1 loss (absolute error) on both the decoder output (mel spectrogram) and the post-net output (linear spectrogram), summed with equal weights.

L=βˆ₯Y^melβˆ’Ymelβˆ₯1+βˆ₯Y^linearβˆ’Ylinearβˆ₯1\mathcal{L} = \lVert \hat{Y}_{\mathrm{mel}} - Y_{\mathrm{mel}} \rVert_1 + \lVert \hat{Y}_{\mathrm{linear}} - Y_{\mathrm{linear}} \rVert_1

The paper's training settings are as follows.

ItemValue
DataInternal North American English dataset (one professional female speaker, about 24.6 hours). Numbers and the like are spelled out, e.g., "16" β†’ "sixteen"
Audio analysis24 kHz, Hann window, 50 ms frame length, 12.5 ms hop, 2,048-point Fourier transform, pre-emphasis 0.97, log-magnitude spectrogram
OptimizationAdam. The learning rate starts at 0.001 and is reduced to 0.0005, 0.0003, and 0.0001 at 500K, 1M, and 2M steps (step decay)
Batch size32 (all sequences zero-padded to the maximum length)

During training, the decoder is fed ground-truth frames (teacher forcing). The paper did not use scheduled sampling, which feeds outputs back as inputs, because it degraded audio quality; instead, it says dropout in the decoder pre-net is essential for generalization. Dropout acts as a noise source that helps deal with the multiple modes of the output distribution (the same sentence can be spoken in many ways).

In sequence models it is common not to compute the loss on zero-padded frames (masking). In the paper, however, doing so meant the model did not learn when to stop emitting output, and it repeated the same sound at the end. Tacotron avoids this by also reconstructing the zero-padded frames.

Why It Learns Well

The paper verifies the effect of each component by comparing the attention alignments (which character is attended to at each step) and the predicted spectrograms of models with components removed. Because objective metrics for generative models often do not match perceived quality, the comparison is mainly visual.

Model comparedResult
Vanilla seq2seq (2-layer residual GRU encoder and decoder, no pre-net or post-net, predicting linear spectrograms directly)Cannot learn without scheduled sampling (0.5). Attention gets stuck on the same input for many frames, speech is hard to understand, and durations break down
Replace the CBHG encoder with a 2-layer residual GRUAlignment is noisier, and mispronunciations increase
TacotronLearns a clean, smooth alignment
Remove the post-net (decoder predicts linear spectrograms)Harmonics (such as high harmonics in frequency bins 100–400) and the shapes of high-frequency formants become coarse, increasing synthesis artifacts

The paper explains why emitting rr frames at a time helps as follows.

  • Neighboring frames are similar, and one character spans many frames: Emitting one frame at a time forces attention to stay on the same character for many steps. Emitting multiple frames makes it easier for attention to move forward from early in training.
  • The number of steps drops to 1/r1/r: Model size and training and inference time decrease. In the paper, this made attention alignment learn much faster and more stably.

Another design choice is making the decoder's prediction target the 80-band mel spectrogram rather than the redundant linear spectrogram. The seq2seq part's job is to learn the alignment between characters and speech, so a representation compressed just enough to capture pronunciation and prosody suffices. The post-net fills in the fine details needed for waveform synthesis by looking at the whole sequence.

Experimental Results

MOS comparison (5-point scale; higher is more natural)

SystemMOS
Tacotron3.82 Β± 0.085
Parametric (LSTM-based, in production)3.69 Β± 0.109
Concatenative (in production)4.09 Β± 0.119

The evaluation used 100 sentences not seen in training, each rated by 8 crowdsourced native English-speaking raters, and only ratings made with headphones were counted.

Tacotron outperformed the production parametric system but did not reach the concatenative system. The paper considers this a promising result, given the strong baselines and the artifacts introduced by Griffin-Lim. It also notes that, because it generates at the frame level, it is substantially faster than methods that generate waveform samples one at a time autoregressively (such as WaveNet).

Practical Considerations

Keep the following points in mind when using Tacotron.

  • Griffin-Lim caps audio quality: The paper describes Griffin-Lim as "a choice for simplicity" and acknowledges audible artifacts remain. It reports that raising the predicted magnitudes to the power 1.2 before Griffin-Lim reduces artifacts, and that 50 iterations suffice for convergence (around 30 is also enough).
  • Inference is step by step: The decoder is autoregressive, so time grows in proportion to output length.
  • Attention failures cause skipping and repetition: Since the alignment between characters and speech is learned by attention alone, it can break down on long sentences or unusual spellings.
  • Text normalization is needed: In the paper's data, numbers and the like are spelled out as they are read. The model does not assume raw text as input.
  • Batch normalization and dropout are present: CBHG convolutions use batch normalization, so switch to model.eval() for inference.

The paper's results come from training on an internal 24.6-hour single-speaker dataset. When experimenting with public data, the English single-speaker LJ Speech (about 24 hours) is commonly used, and the dataset's official page also lists implementations that train Tacotron on it. However, the data and evaluation conditions differ, so results cannot be compared directly with the paper's MOS.

Comparison with Other Models

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

ModelEncoderCharacter–frame alignmentHow the decoder generatesWaveform generation (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 to understand the basic form of seq2seq speech synthesis: Tacotron is the starting point. It contains the ideas inherited by later models: the pre-net, emitting rr frames at a time, and the post-net.
  • Naturalness matters most: Tacotron 2, which simplifies Tacotron's design and pairs it with a neural vocoder, scores much higher in its paper's MOS.
  • Inference speed and robustness to skipping and repetition matter: Non-autoregressive models such as FastSpeech, which predict durations instead of relying on attention, are suitable.

PyTorch example

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

"""
A small implementation of Tacotron's components (Section 3 and Table 1 of the paper)
PyTorch and torchaudio have no built-in Tacotron (1) (torchaudio only has Tacotron 2)
1. Pre-net: fully connected β†’ ReLU β†’ dropout, twice
2. CBHG: conv bank β†’ max pooling β†’ conv projections β†’ residual β†’ highway layers β†’ bidirectional GRU
"""


class Prenet(nn.Module):
    def __init__(self, in_dim, sizes=(256, 128), p=0.5):
        super().__init__()
        dims = [in_dim, *sizes]
        self.layers = nn.ModuleList(nn.Linear(a, b) for a, b in zip(dims[:-1], dims[1:]))
        self.p = p

    def forward(self, x):
        for layer in self.layers:
            # follows self.training (model.eval() disables dropout)
            x = F.dropout(F.relu(layer(x)), self.p, self.training)
        return x


class BatchNormConv1d(nn.Module):
    def __init__(self, in_ch, out_ch, k, act):
        super().__init__()
        self.conv = nn.Conv1d(in_ch, out_ch, k, padding=k // 2, bias=False)
        self.bn = nn.BatchNorm1d(out_ch)   # paper: batch normalization on every convolution
        self.act = act

    def forward(self, x):                  # x: [batch, channels, time]
        T = x.size(-1)
        y = self.conv(x)[..., :T]          # keep the length equal when the width is even
        y = self.bn(y)
        return self.act(y) if self.act is not None else y


class Highway(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.H = nn.Linear(dim, dim)
        self.T = nn.Linear(dim, dim)

    def forward(self, x):
        t = torch.sigmoid(self.T(x))       # transform gate
        return t * F.relu(self.H(x)) + (1 - t) * x


class CBHG(nn.Module):
    def __init__(self, in_dim, K=16, bank_ch=128, proj=(128, 128), n_highway=4, gru=128):
        super().__init__()
        self.bank = nn.ModuleList(
            BatchNormConv1d(in_dim, bank_ch, k, nn.ReLU()) for k in range(1, K + 1))
        self.pool = nn.MaxPool1d(kernel_size=2, stride=1, padding=1)
        self.proj1 = BatchNormConv1d(K * bank_ch, proj[0], 3, nn.ReLU())
        self.proj2 = BatchNormConv1d(proj[0], proj[1], 3, None)   # last one is linear (no activation)
        # to add the residual, the projection output has the same dimension as the input
        self.pre_highway = nn.Linear(proj[1], gru) if proj[1] != gru else nn.Identity()
        self.highways = nn.ModuleList(Highway(gru) for _ in range(n_highway))
        self.gru = nn.GRU(gru, gru, batch_first=True, bidirectional=True)

    def forward(self, x):                  # x: [batch, time, in_dim]
        T = x.size(1)
        h = x.transpose(1, 2)
        h = torch.cat([conv(h) for conv in self.bank], dim=1)    # widths 1 to K side by side, concatenated
        h = self.pool(h)[..., :T]          # stride 1: sequence length unchanged
        h = self.proj2(self.proj1(h))
        h = h.transpose(1, 2) + x          # residual connection (add to the input sequence)
        h = self.pre_highway(h)
        for hw in self.highways:
            h = hw(h)
        out, _ = self.gru(h)               # [batch, time, 2 Γ— gru]
        return out


# Encoder: character embedding (256) β†’ pre-net β†’ CBHG (K = 16)
embed = nn.Embedding(num_embeddings=70, embedding_dim=256)
prenet = Prenet(256)
cbhg = CBHG(in_dim=128, K=16, proj=(128, 128))

chars = torch.randint(0, 70, (2, 40))     # 2 sentences, 40 characters
memory = cbhg(prenet(embed(chars)))
print(memory.shape)                        # torch.Size([2, 40, 256])

# Switch batch normalization and dropout to inference mode for inference
cbhg.eval()
prenet.eval()

FAQ

Q. Does Tacotron take characters rather than phonemes as input?
A.

Yes. Tacotron in the paper takes character sequences as input and does not prepare phoneme conversion or per-phoneme timing alignments in advance. The alignment between characters and speech is learned by attention. It does, however, apply simple normalization such as spelling out numbers as they are read. Later models such as Transformer TTS and FastSpeech take phonemes as input to reduce mispronunciations.

Q. What happens if $r$ is increased?
A.

The number of decoder steps becomes 1/r1/r, training and inference become faster, and the attention alignment becomes easier to learn. The paper uses r=2r = 2 for the MOS evaluation and notes that values as large as r=5r = 5 also work well. The attention alignment comparison in Figure 3 is drawn with an r=5r = 5 model.

Q. What is the biggest difference between Tacotron and Tacotron 2?
A.

How the waveform is generated. Tacotron predicts a linear spectrogram and converts it to a waveform with Griffin-Lim, while Tacotron 2 predicts a mel spectrogram and generates the waveform with a WaveNet conditioned on it. In the Tacotron 2 paper's comparison under the same conditions, Tacotron (Griffin-Lim) scored a MOS of 4.001 and Tacotron 2 scored 4.526. Tacotron 2 also replaces CBHG and GRUs with simpler building blocks: convolutions and LSTMs.

References

  1. Wang, Y., Skerry-Ryan, R. J., Stanton, D., Wu, Y., Weiss, R. J., Jaitly, N., Yang, Z., Xiao, Y., Chen, Z., Bengio, S., Le, Q., Agiomyrgiannakis, Y., Clark, R., & Saurous, R. A. (2017). Tacotron: Towards End-to-End Speech Synthesis. arXiv:1703.10135.
  2. Tacotron audio samples (by the paper's authors)
  3. Shen, J., et al. (2018). Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions (Tacotron 2). ICASSP 2018. arXiv:1712.05884.
  4. Ito, K. (2017). The LJ Speech Dataset.