Transformer TTS is a text-to-speech (TTS) model that replaces the RNNs in the encoder and decoder of Tacotron 2, and the attention between them, with the multi-head attention of the Transformer. It predicts a mel spectrogram from a phoneme sequence and converts it into a waveform with WaveNet. Li et al. presented it at AAAI 2019 (joint research with Microsoft).
RNN-based models such as Tacotron 2 had two problems:
Slow training and inference: An RNN computes each step from the previous hidden state, so it cannot be parallelized along the time axis.
Difficulty capturing long-range dependencies: Information from many steps back fades as it passes through the RNN repeatedly. Speech prosody depends not only on the few nearby words but also on the meaning of the whole sentence.
Transformer self-attention connects any two positions directly, mitigating both problems. During training, all frames of the decoder input (the ground-truth mel spectrogram) can be fed in parallel.
On an internal US English dataset (25 hours), its MOS (mean opinion score) was 4.39, the same as Tacotron 2, approaching the 4.44 of human recordings. In CMOS, which compares the two directly, it beat Tacotron 2 by 0.048, and each training step became about 4.25 times faster.
Architecture
Transformer TTS is a Transformer encoder-decoder with added components for speech synthesis. The left of the figure at the top of the article shows the overall flow, and the right shows the inside of a decoder block.
Text is processed into a mel spectrogram in the following order:
Grapheme-to-phoneme conversion: A rule-based system that incorporates English pronunciation rules (e.g., the reading of "a" changes between open and closed syllables) converts text into a phoneme sequence. This is because, with limited training data, it is hard for a network to learn pronunciation rules including their exceptions. Word and syllable boundaries and punctuation are also included as special symbols.
Encoder pre-net: A learned 512-dimensional embedding for each phoneme is passed through the same 3 convolutional layers as Tacotron 2 (512 channels, batch normalization, ReLU, dropout), followed by a linear projection at the end.
Positional encoding with a learned scale: A sinusoidal positional encoding multiplied by a learned scale α is added to the pre-net output.
Decoder pre-net: The mel spectrogram up to the previous frame is passed through 2 fully connected layers (256 each, ReLU), followed by a linear projection at the end.
Decoder: A positional encoding is added to the pre-net output, and Transformer decoder blocks (masked self-attention, attention over the encoder output, and feed-forward) are stacked.
Output: As in Tacotron 2, two linear projections predict the mel spectrogram and the stop token, and a 5-layer convolutional post-net predicts a residual that refines the details of the mel spectrogram.
The positional encoding is added as follows, where pos is the frame (phoneme) position, i is the channel index, and dmodel is the dimension:
Learning the positional encoding scale α: In machine translation, both inputs and outputs are word embeddings, so their magnitudes match. In speech synthesis, the input is phonemes and the output is mel spectrograms, which differ in magnitude. Adding a positional encoding of fixed magnitude would place a strong constraint on the pre-net, so separate scales are learned for the encoder and the decoder. After training, the decoder's scale was smaller than the encoder's.
Adding a linear projection at the end of the pre-net: ReLU outputs are non-negative, while the positional encoding lies in −1 to 1, centered at 0. Adding zero-centered values to non-negative ones shifts the center and degrades performance, so a linear projection aligns the centers.
The decoder pre-net is essential: Phoneme embeddings are adjusted during training, but the mel spectrogram space is fixed. The paper argues that the pre-net maps mel spectrograms into the same space as the phoneme embeddings, making it possible to measure the similarity of ⟨phoneme, frame⟩ pairs, which lets attention work. With 2 fully connected layers without activation functions, no meaningful attention alignment emerged.
Weighting the positive class of the stop token: The only positive example indicating "stop" is the last frame of the sequence, while the remaining hundreds of frames are negative. This imbalance sometimes caused inference not to stop, so a weight of 5.0–8.0 was applied to the positive class in binary cross-entropy.
Tacotron 2's location-sensitive attention uses the previous attention weights as cues to move steadily forward through the input. The paper also tried making dot-product multi-head attention location-sensitive, but it doubled training time and tended to run out of memory, so it was not used.
Training
The paper's training settings are as follows:
Item
Value
Data
Internal US English female speaker data, about 25 hours (17,584 ⟨text, waveform⟩ pairs; overly long waveforms excluded). 50 ms of silence is kept at the start of each waveform and 100 ms at the end
Input
Normalized phoneme sequences (including symbols for word and syllable boundaries and punctuation)
GPUs
4 × NVIDIA Tesla P100
Batch
Dynamic batches with a fixed total number of mel spectrogram frames (16 samples per GPU on average)
Vocoder
A WaveNet conditioned on mel spectrograms, trained on the same data (2 QRNN layers + 20 dilated convolution layers, 256 channels; 16 kHz audio, mel spectrograms at 80 frames per second)
In the paper, training on a single GPU was unstable and sometimes failed. Even when it did not fail, problems such as poor audio quality, odd prosody, and dropped phonemes appeared. These were resolved by adding GPUs and increasing the batch size. The paper concludes that batch size is crucial for training stability.
Training speed is as follows:
Model
Time per step (batch of 16 samples)
Days to converge
Tacotron 2
About 1.7 s
About 4.5 days
Transformer TTS
About 0.4 s (about 4.25× faster)
About 3 days
Transformer TTS has about twice as many parameters as Tacotron 2, so the time to convergence does not shrink as much as the per-step speedup would suggest.
Effect of each component
The paper compares MOS while varying components and sizes (every table also evaluates human recordings in the same test).
Comparison
Setting
MOS
Human recordings
Centering the pre-net output
No
4.32 ± 0.05
4.43 ± 0.05
Yes
4.36 ± 0.05
Positional encoding
Original
4.37 ± 0.05
4.41 ± 0.04
Learned scale
4.40 ± 0.05
Number of layers
3 layers
4.33 ± 0.06
4.44 ± 0.05
6 layers
4.41 ± 0.05
Number of heads
4 heads
4.39 ± 0.05
4.47 ± 0.05
8 heads
4.44 ± 0.05
The model "without centering" omits the linear projection from the encoder pre-net and adds a fully connected layer with ReLU to the decoder pre-net.
Training time per step (seconds) was 0.29 with 3 layers and 8 heads, 0.44 with 6 layers and 4 heads, and 0.50 with 6 layers and 8 heads. Reducing either layers or heads speeds up training but lowers audio quality.
Other observations from the paper:
Diagonal alignment only in the first 2 layers: In the encoder-decoder attention, only some heads in the first 2 layers formed the diagonal line that represents the input-output alignment; the higher layers were scattered. Even so, adding layers lowered the loss and reproduced details, especially at high frequencies, better. The paper explains that layers connected by residual connections approximate the function like a Taylor expansion, roughly in the first layers and more finely in later ones.
Learned absolute position embeddings struggle with long sentences: The paper also tried learning an embedding for each position (learned positional embeddings), but phonemes were dropped in long sentences. Because the training data had few long samples, embeddings for later positions were not learned sufficiently.
Experimental results
Comparison of MOS and CMOS
System
MOS
CMOS
Tacotron 2
4.39 ± 0.05
0
Transformer TTS
4.39 ± 0.05
0.048
Human recordings
4.44 ± 0.05
-
The evaluation used 38 sentences of various lengths that do not overlap with the training data, and each audio sample was rated by at least 20 native English speakers (each rater heard fewer than 30 samples). Tacotron 2 was also trained on the same internal data with phonemes as input.
Since the MOS was identical, the two were also compared with CMOS (Comparison MOS), which plays them side by side. Raters heard the same sentence synthesized by Tacotron 2 and Transformer TTS, in shuffled order so they could not tell which was which, and rated the second sample relative to the first on a scale from −3 to 3 in steps of 1. Transformer TTS came out ahead by 0.048.
Comparing mel spectrograms generated from the same sentence, Transformer TTS (6 layers) reproduced details well, while the patterns of Tacotron 2 and the 3-layer model were blurry, especially at high frequencies.
The FastSpeech paper retrained Transformer TTS on LJ Speech for comparison (with a WaveGlow vocoder). The MOS was 3.86 for Tacotron 2 and 3.88 for Transformer TTS. On 50 difficult sentences prone to skipping and repetition, Transformer TTS made errors on 34% of the sentences (Tacotron 2: 24%), showing a weakness of its autoregressive attention.
Practical considerations
Keep the following in mind when using Transformer TTS:
Inference does not get faster: Training can compute frames in parallel, but inference uses the previous frame's prediction, so it remains autoregressive, one frame at a time. The paper also lists slow inference and error accumulation from autoregression (exposure bias) as remaining issues, and names non-autoregressive models as future work.
Attention alignment can break down: The encoder-decoder connection is dot-product attention only, with no location-sensitive mechanism. On difficult sentences, skipping and repetition occur (see the FastSpeech paper's evaluation above).
Large batches are required: Training with small batches on a single GPU was unstable.
Memory and compute grow with the square of sequence length: Mel spectrograms have hundreds to thousands of frames, so the decoder's self-attention requires substantial compute and memory.
Many parameters: The paper's model has about twice as many parameters as Tacotron 2.
Behavior differs between training and inference: The pre-nets use batch normalization and dropout, so call model.eval() for inference.
Comparison with other models
Comparing representative models that generate mel spectrograms from text from the same perspectives gives the following:
Predicts each phoneme's duration and expands accordingly
Frames computed in parallel
Non-autoregressive (all frames in parallel)
Rough guidelines for choosing:
Faster training of an autoregressive model and better prosody for long sentences: Transformer TTS is a good fit. However, it needs large batches and plenty of memory.
Stable attention alignment: Tacotron 2, with location-sensitive attention, made fewer errors on difficult sentences (24% vs. 34% in the FastSpeech paper's evaluation).
Faster inference and no skipping or repetition: Move on to the non-autoregressive FastSpeech, which uses Transformer TTS as a teacher to extract phoneme durations.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small example building Transformer TTS (Section 3 of the paper) with PyTorch's nn.TransformerEncoder / Decoder
- nn.TransformerEncoderLayer defaults to norm_first=False (add the sublayer output, then layer-normalize), the same form as the original Transformer
- Separate positional encoding scales α are learned for the encoder and the decoder (Eq. (8))
- A linear projection at the end of each pre-net aligns its center with the zero-centered positional encoding
"""
def sinusoid(T, d):
pos = torch.arange(T).unsqueeze(1)
div = torch.exp(torch.arange(0, d, 2) * (-math.log(10000.0) / d))
pe = torch.zeros(T, d)
pe[:, 0::2] = torch.sin(pos * div)
pe[:, 1::2] = torch.cos(pos * div)
return pe
class TransformerTTS(nn.Module):
def __init__(self, n_phonemes=80, n_mels=80, d=512, heads=8, layers=6, ff=2048):
super().__init__()
# Encoder pre-net: embedding → 3 conv layers (BN, ReLU, dropout) → linear projection
self.embed = nn.Embedding(n_phonemes, d)
self.enc_convs = nn.ModuleList(
nn.Sequential(nn.Conv1d(d, d, 5, padding=2), nn.BatchNorm1d(d), nn.ReLU(), nn.Dropout(0.5))
for _ in range(3))
self.enc_proj = nn.Linear(d, d)
# Decoder pre-net: 2 FC layers (256, ReLU) → linear projection
self.dec_prenet = nn.Sequential(
nn.Linear(n_mels, 256), nn.ReLU(), nn.Dropout(0.5),
nn.Linear(256, 256), nn.ReLU(), nn.Dropout(0.5),
nn.Linear(256, d))
self.alpha_enc = nn.Parameter(torch.ones(1)) # Positional encoding scale (learned)
self.alpha_dec = nn.Parameter(torch.ones(1))
self.encoder = nn.TransformerEncoder(
nn.TransformerEncoderLayer(d, heads, ff, dropout=0.1, batch_first=True), layers)
self.decoder = nn.TransformerDecoder(
nn.TransformerDecoderLayer(d, heads, ff, dropout=0.1, batch_first=True), layers)
self.mel_linear = nn.Linear(d, n_mels)
self.stop_linear = nn.Linear(d, 1)
# Post-net: predict the residual with 5 conv layers
post = []
for i in range(5):
cin = n_mels if i == 0 else d
cout = n_mels if i == 4 else d
post += [nn.Conv1d(cin, cout, 5, padding=2), nn.BatchNorm1d(cout)]
if i < 4:
post += [nn.Tanh(), nn.Dropout(0.5)]
self.postnet = nn.Sequential(*post)
def forward(self, phonemes, mel_in):
# phonemes: [B, N], mel_in: [B, T, n_mels] (ground truth shifted by one frame, i.e., frames up to the previous one)
x = self.embed(phonemes).transpose(1, 2)
for conv in self.enc_convs:
x = conv(x)
x = self.enc_proj(x.transpose(1, 2))
x = x + self.alpha_enc * sinusoid(x.size(1), x.size(2)).to(x)
memory = self.encoder(x)
y = self.dec_prenet(mel_in)
y = y + self.alpha_dec * sinusoid(y.size(1), y.size(2)).to(y)
causal = nn.Transformer.generate_square_subsequent_mask(y.size(1)).to(y) # Do not look at future frames
h = self.decoder(y, memory, tgt_mask=causal)
mel = self.mel_linear(h)
mel_post = mel + self.postnet(mel.transpose(1, 2)).transpose(1, 2) # Add as a residual
stop_logit = self.stop_linear(h).squeeze(-1)
return mel, mel_post, stop_logit
model = TransformerTTS()
phonemes = torch.randint(0, 80, (2, 30))
mel = torch.randn(2, 100, 80)
mel_in = F.pad(mel[:, :-1], (0, 0, 1, 0)) # Prepend a zero frame to shift by one
mel_out, mel_post, stop_logit = model(phonemes, mel_in)
stop_target = torch.zeros(2, 100)
stop_target[:, -1] = 1.0 # Only the last frame is positive
loss = (F.mse_loss(mel_out, mel) + F.mse_loss(mel_post, mel)
# Paper: compensate for having only one positive with a positive weight of 5.0–8.0
+ F.binary_cross_entropy_with_logits(stop_logit, stop_target, pos_weight=torch.tensor(5.0)))
loss.backward()
model.eval() # At inference, put batch norm and dropout in eval mode and generate one frame at a time
FAQ
Q. Is Transformer TTS also faster at inference?
A.
No. What gets faster is training. During training, all frames of the ground-truth mel spectrogram can be fed in parallel, but at inference the previously predicted frame is used as the next input, so generation remains autoregressive, one frame at a time. Parallel inference requires a non-autoregressive model such as FastSpeech. In the FastSpeech paper, mel spectrogram generation was about 270 times faster than with Transformer TTS.
Q. Why use phonemes instead of characters as input?
A.
To reduce mispronunciations. The mapping between English spelling and pronunciation has rules and many exceptions, and with limited training data it is hard for a network to learn them all. The paper reports that converting text to phonemes with a rule-based system beforehand greatly reduced mispronunciations of pronunciations that are rare in the training data.
Q. How many layers and heads were used in the paper?
A.
Following the original Transformer, the paper uses 6 layers and 8 heads as the baseline and compares it with fewer layers and heads. Six layers were better than 3 (MOS 4.33 → 4.41), and 8 heads were better than 4 (4.39 → 4.44); reducing them speeds up training but lowers audio quality.