FastSpeech 2 is a non-autoregressive text-to-speech (TTS) model that predicts phoneme duration, pitch, and energy, adds them to the encoder output, and generates all mel-spectrogram frames in parallel. It was introduced in 2020 by Ren et al. of Zhejiang University and Microsoft, and accepted at ICLR 2021.
Speech synthesis is a one-to-many problem: a single text has many possible spoken renditions. Even the same sentence can be read in many ways that differ in pitch, duration, volume, and intonation. A non-autoregressive model that takes only text as input cannot settle on which rendition to produce, and tends to overfit the variation in the training data.
Its predecessor, FastSpeech, eased this problem with an autoregressive teacher model (Transformer TTS). But it had three weaknesses.
Complex two-stage training: the teacher is trained first, and FastSpeech is then trained on its outputs.
Information loss in the target speech: because the target is the mel spectrogram generated by the teacher, intonation is flatter than in real recordings, lowering the ceiling on quality.
Inaccurate phoneme durations: durations extracted from the teacher's attention tend to misplace phoneme boundaries.
FastSpeech 2 solves these in two ways.
Train directly on real mel spectrograms: the teacher and knowledge distillation are eliminated.
Add information about speech variation to the input: phoneme duration (obtained with an external alignment tool), pitch, and energy are extracted from recordings and used as inputs during training, and predicted values are used during inference.
Quality: a MOS of 3.83, above FastSpeech (3.68), Transformer TTS (3.72), and Tacotron 2 (3.70)
Training time: from 53.12 hours for FastSpeech (including teacher training) to 17.02 hours, about 3.12 times shorter
Inference speed: about 47.8 times faster than Transformer TTS, including waveform synthesis
The paper also proposes FastSpeech 2s, which generates the waveform directly from text without going through a mel spectrogram.
Architecture
FastSpeech 2 consists of three parts: encoder → variance adaptor → mel-spectrogram decoder. In the figure at the top of the article, the left side shows the overall flow and the right side shows the inside of the variance adaptor.
From phonemes to the mel spectrogram, processing proceeds in the following order.
Phoneme embedding: each phoneme (76 types including punctuation) is turned into a 256-dimensional vector, and positional encoding is added.
Encoder: four FFT blocks, the same as in FastSpeech (multi-head attention and two 1D convolution layers), are stacked to produce a hidden state for each phoneme.
Variance adaptor: the hidden states are expanded to the number of frames using phoneme durations, and per-frame pitch and energy information is added.
Mel-spectrogram decoder: positional encoding is added, and four FFT blocks process the sequence.
Linear layer: the hidden states are converted to an 80-dimensional mel spectrogram, and all frames are output at once.
Vocoder: in the paper, a pre-trained Parallel WaveGAN turns the mel spectrogram into a waveform.
The variance adaptor is the part that adds information about speech variation to the hidden states. As shown on the right of the figure, it proceeds in the following order.
Duration predictor → length regulator: predicts the duration of each phoneme (how many frames), and the same length regulator as in FastSpeech repeats each phoneme's hidden state that many times.
Pitch predictor → pitch embedding: predicts the pitch (fundamental frequency F0) of each frame. The value is quantized into 256 levels on a log scale, turned into an embedding vector, and added to the hidden state.
Energy predictor → energy embedding: predicts the energy of each frame. The value is quantized uniformly into 256 levels, turned into an embedding vector, and added to the hidden state.
The three predictors share the same shape (with separate parameters): two 1D convolution layers (ReLU, each followed by layer normalization and dropout) and a linear output layer.
Each quantity is defined as follows.
Quantity
Unit
How the target is extracted
Predictor output
Phoneme duration
Per phoneme
Align text and speech with the Montreal Forced Aligner (MFA)
Duration in the log domain
Pitch
Per frame
Extract the pitch contour with PyWorld
A pitch spectrogram split into 10 components by continuous wavelet transform, plus the per-utterance mean and variance
Energy
Per frame
L2 norm of the amplitude of each short-time Fourier transform (STFT) frame
The value before quantization
Pitch is predicted in the frequency domain. The pitch contour fluctuates strongly over time, so predicting it directly makes the predicted distribution much flatter than the real one. Instead, the pitch contour is decomposed by continuous wavelet transform (CWT) into components Wi(t) at 10 scales, which become the prediction targets. At inference, the predicted components are turned back into a pitch contour with the following formula (the inverse transform), and the predicted mean and variance restore the original scale.
F^0(t)=i=1∑10W^i(t)(i+2.5)−5/2
Before applying the CWT, the pitch contour is prepared as follows, because the CWT handles discontinuous signals poorly.
Fill unvoiced frames (where there is no pitch) by linear interpolation
Convert to a log scale
Normalize each utterance to mean 0 and variance 1 (the original mean and variance are saved for restoration)
The settings in the paper are as follows.
Component
Setting
FFT blocks
4 in the encoder, 4 in the decoder
Hidden dimension
256 (embedding, attention)
Attention heads
2
FFT block convolutions
Kernel sizes 9 and 1, 256 → 1,024 → 256
Predictor convolutions
Kernel size 3, 2 layers of 256 → 256, dropout 0.5
Parameters
27M (FastSpeech has 23M, FastSpeech 2s has 28M)
The variance adaptor is the component that adds cues about "how to read the text" to the input. During training, the ground-truth duration, pitch, and energy extracted from the recording are fed in, so the decoder only needs to produce a mel spectrogram under the condition "read it at this pitch and volume," which reduces one-to-many ambiguity. At inference, the predictors produce cues of the same form.
FastSpeech 2s: generating waveforms directly from text
FastSpeech 2s is a variant that generates the waveform directly from the output of the variance adaptor, without going through a mel spectrogram. It drops the two-stage setup of a mel-spectrogram model plus a vocoder, and completes inference with a single model.
Generating waveforms directly from text poses two difficulties.
Waveforms carry a lot of information: the model must also generate phase information, which the mel spectrogram does not contain.
Long waveforms do not fit in memory: training cannot use the waveform of a whole sentence and must use short clipped segments, which makes it harder to capture relationships between distant phonemes.
The waveform decoder is therefore built as follows.
Structure: based on WaveNet, it uses non-causal dilated convolutions and gated activations. The clipped hidden states are upsampled to waveform length with one transposed convolution layer and processed by 30 residual blocks.
Adversarial training: since phase is hard to predict with a predictor, a GAN discriminator (the same shape as Parallel WaveGAN's) is used so that the waveform decoder generates phase implicitly. The losses are a multi-resolution STFT loss and the LSGAN discriminator loss.
Keep the mel-spectrogram decoder during training: a mel-spectrogram decoder trained on whole sentences is trained jointly to help the encoder capture sentence-level features. It is discarded at inference.
During training, hidden states corresponding to 20,480 waveform samples are clipped and fed into the waveform decoder.
Training procedure
FastSpeech 2 uses no teacher model and trains in a single stage with real mel spectrograms as the target.
Training proceeds as follows.
Extract the ground-truth duration, pitch, and energy: from the recordings and text, phoneme durations are obtained with MFA, pitch contours with PyWorld, and energy with the STFT. MFA is trained only on the paper's training data.
Use the ground-truth values as inputs: in the variance adaptor, the hidden states are expanded and the embeddings added using the ground-truth duration, pitch, and energy rather than predicted values.
Minimize the overall loss: the model is trained on the mean absolute error (MAE) of the mel spectrogram plus the mean squared error of the three predictors. Duration is compared in the log domain, pitch via the pitch spectrogram and mean/variance, and energy via the value before quantization.
At inference, the values produced by the three predictors are used.
The training settings in the paper are as follows.
Item
Value
Data
LJ Speech (13,100 English audio clips, about 24 hours), split into 12,228 for training, 349 for validation, and 523 for testing
Input
Text converted to phoneme sequences with an open-source grapheme-to-phoneme tool
Mel spectrogram
Sampling rate 22,050 Hz, frame size 1,024, hop 256
Optimizer
Adam (β1=0.9, β2=0.98, ϵ=10−9), with the same learning-rate schedule as the Transformer (warmup followed by decay)
Compute
One V100, batch of 48 sentences, 160K steps (FastSpeech 2s: two V100s, 6 sentences per GPU, 600K steps)
Although "no teacher model is needed," preprocessing for training requires an external alignment tool (MFA) and a pitch extraction tool. The paper's conclusion also lists training without an external alignment model as future work. Glow-TTS is a model that finds the alignment on its own during training.
Why quality improves
The improvements of FastSpeech 2 can be explained as narrowing the information gap between input and output.
The target becomes real speech: the teacher's output is flatter than real recordings. Using real mel spectrograms as the target raises the ceiling on quality.
Durations become accurate: on 50 sentences aligned by hand, the mean phoneme-boundary error was 19.68 ms for durations extracted from the teacher's attention and 12.47 ms for MFA. Simply replacing FastSpeech's durations with those from MFA raised CMOS by +0.195.
The input carries cues about variation: adding pitch and energy to the input means the decoder does not have to guess intonation that the text alone cannot determine.
Comparing pitch distributions shows the effect. The standard deviation, skewness, and kurtosis of the pitch of the generated speech, and the DTW distance to the real pitch (a distance that tolerates time misalignment), are as follows.
System
Std. dev.
Skewness
Kurtosis
DTW distance
Real recordings
54.4
0.836
0.977
−
Tacotron 2
44.1
1.28
1.311
26.32
Transformer TTS
40.8
0.703
1.419
24.40
FastSpeech
50.8
0.724
−0.041
24.89
FastSpeech 2
54.1
0.881
0.996
24.39
FastSpeech 2 (without CWT)
42.3
0.771
1.115
25.13
FastSpeech 2s
53.9
0.872
0.998
24.37
The pitch distribution of FastSpeech 2 was the closest to that of real recordings. Predicting the pitch contour directly without the CWT lowers the standard deviation to 42.3 and flattens the intonation.
Experimental results
Audio quality (100 sentences from the LJ Speech test set, MOS with 95% confidence intervals; Parallel WaveGAN as the vocoder for all systems)
System
MOS
Human recordings
4.30 ± 0.07
Human recordings → mel spectrogram → Parallel WaveGAN
3.92 ± 0.08
Tacotron 2
3.70 ± 0.08
Transformer TTS
3.72 ± 0.07
FastSpeech
3.68 ± 0.09
FastSpeech 2
3.83 ± 0.08
FastSpeech 2s
3.71 ± 0.09
Twenty native English speakers rated the samples. In CMOS with FastSpeech 2 as 0, FastSpeech scored −0.885 and Transformer TTS −0.235.
Training and inference speed (one V100; batch 48 for training, batch 1 for inference; RTF is the number of seconds needed to generate one second of waveform)
System
Training time
Inference RTF
Speedup over Transformer TTS
Transformer TTS
38.64 hours
9.32×10−1
−
FastSpeech (including teacher training)
53.12 hours
1.92×10−2
48.5×
FastSpeech 2
17.02 hours
1.95×10−2
47.8×
FastSpeech 2s
92.18 hours
1.80×10−2
51.8×
Training time covers only the mel-spectrogram model and does not include vocoder training. Because FastSpeech 2s trains everything up to waveform generation in a single model, the paper does not compare its training time with the other models.
Effect of each component (CMOS; each model is 0, compared with the version with a component removed)
Component removed
FastSpeech 2
FastSpeech 2s
Energy
−0.040
−0.160
Pitch
−0.245
−1.130
Pitch and energy
−0.370
−1.355
CWT (predict the pitch contour directly)
−0.185
−0.201
The effect of pitch was especially large, and even larger in FastSpeech 2s, which generates waveforms directly. Removing the mel-spectrogram decoder from FastSpeech 2s lowered CMOS by −0.285.
Energy accuracy: the mean absolute error of per-frame energy between generated and real speech was 0.142 for FastSpeech, 0.131 for FastSpeech 2, and 0.133 for FastSpeech 2s.
Control: high-quality mel spectrograms could still be generated when the pitch input was scaled by 0.75 to 1.50. Since duration, pitch, and energy are inputs, pitch and volume can also be changed afterward.
Practical considerations
Keep the following points in mind when using FastSpeech 2.
Preprocessing tools are required: phoneme durations require an alignment tool (MFA), and pitch requires a pitch extraction tool. The quality of the alignment sets the ceiling for the duration predictor and for audio quality.
Pitch preprocessing is intricate: it requires interpolation of unvoiced frames, log conversion, per-utterance normalization, the CWT, and even prediction of the mean and variance needed to restore the original scale.
Values come from different sources in training and inference: training uses ground-truth duration, pitch, and energy, while inference uses predicted values. If the predictions are off, the model receives inputs it never saw during training.
A separate vocoder is needed: FastSpeech 2 outputs a mel spectrogram. To get a waveform, use a pre-trained vocoder such as Parallel WaveGAN or HiFi-GAN.
There is dropout: the FFT blocks (0.1) and predictors (0.5) use dropout, so switch to model.eval() for inference.
FastSpeech 2's MOS (3.83) exceeded the autoregressive models in the paper's evaluation on single-speaker English LJ Speech with Parallel WaveGAN as the common vocoder. The conditions differ from those in the FastSpeech paper (which used WaveGlow, with Transformer TTS at 3.88 and FastSpeech at 3.84), so the MOS values of the two papers cannot be compared directly.
Comparison with other models
The table below compares non-autoregressive models in the FastSpeech family from the same perspectives.
Real waveform (mel-spectrogram decoder trained jointly)
Aligned with MFA
Duration, pitch, energy
Waveform
92.18 hours (not directly comparable, since it also covers the vocoder's role)
Rough guidelines for choosing:
To train quickly without preparing a teacher model: FastSpeech 2 is a good fit. Training is single-stage and took about one third of FastSpeech's time.
To change pitch or volume afterward: FastSpeech 2, which takes pitch and energy as inputs, is convenient.
To complete inference with a single model: FastSpeech 2s generates waveforms from text without a vocoder. In the paper, however, its quality was lower than FastSpeech 2 combined with a vocoder (MOS 3.71 vs. 3.83).
To avoid external alignment tools: there are models such as Glow-TTS that find the alignment during training.
To run with little compute: LightSpeech automatically searches for a lighter network architecture based on FastSpeech 2.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of FastSpeech 2's variance adaptor (Section 2.3, Appendix A, and Appendix C of the paper)
PyTorch and torchaudio have no built-in FastSpeech 2
1. The three predictors share the same shape: two 1D conv layers (ReLU → layer norm → dropout) → linear layer
2. Duration predictor → length regulator → add pitch embedding → add energy embedding (the order in Figure 1b)
3. Training uses the ground-truth duration, pitch, and energy as inputs; inference uses predicted values
(The pitch CWT is omitted; only the inverse transform, Eq. (2), is shown)
"""
class VariancePredictor(nn.Module):
def __init__(self, d=256, kernel=3, p=0.5, out_dim=1):
super().__init__()
self.conv1 = nn.Conv1d(d, d, kernel, padding=kernel // 2)
self.conv2 = nn.Conv1d(d, d, kernel, padding=kernel // 2)
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.drop = nn.Dropout(p)
self.out = nn.Linear(d, out_dim)
def forward(self, h): # h: [B, T, d]
x = self.drop(self.norm1(F.relu(self.conv1(h.transpose(1, 2))).transpose(1, 2)))
x = self.drop(self.norm2(F.relu(self.conv2(x.transpose(1, 2))).transpose(1, 2)))
return self.out(x) # [B, T, out_dim]
def length_regulator(h, dur):
"""h: [N, d] (one sentence), dur: [N] integers. Repeat each phoneme by its duration"""
return torch.repeat_interleave(h, dur, dim=0)
def icwt(W):
"""Eq. (2): restore the pitch contour (normalized log F0) from the 10 components W_i(t). W: [T, 10]"""
i = torch.arange(1, 11, dtype=W.dtype)
return (W * (i + 2.5) ** (-2.5)).sum(-1)
class VarianceAdaptor(nn.Module):
def __init__(self, d=256, n_bins=256, f0_min=71.0, f0_max=795.8, e_min=0.0, e_max=300.0):
super().__init__()
self.duration = VariancePredictor(d)
self.pitch = VariancePredictor(d, out_dim=10) # pitch spectrogram (10 scales)
self.pitch_stats = nn.Linear(d, 2) # per-utterance mean and standard deviation
self.energy = VariancePredictor(d)
# Quantize pitch on a log scale and energy uniformly into 256 levels (the boundary values are examples)
self.register_buffer("f0_bins", torch.exp(torch.linspace(torch.log(torch.tensor(f0_min)), torch.log(torch.tensor(f0_max)), n_bins - 1)))
self.register_buffer("e_bins", torch.linspace(e_min, e_max, n_bins - 1))
self.pitch_emb = nn.Embedding(n_bins, d)
self.energy_emb = nn.Embedding(n_bins, d)
def forward(self, h, dur=None, f0=None, energy=None):
"""h: [N, d] (one sentence). Passing dur, f0, energy means training; None means inference"""
log_dur_pred = self.duration(h[None])[0, :, 0] # [N]
if dur is None: # inference: round and use the predicted durations
dur = torch.clamp(torch.round(torch.exp(log_dur_pred)), min=1).long()
x = length_regulator(h, dur) # [T, d]
W_pred = self.pitch(x[None])[0] # [T, 10]
mean_std = self.pitch_stats(x.mean(0)) # average over time, then project
if f0 is None: # inference: inverse transform and restore the original scale
f0 = torch.exp(icwt(W_pred) * mean_std[1] + mean_std[0])
x = x + self.pitch_emb(torch.bucketize(f0, self.f0_bins))
e_pred = self.energy(x[None])[0, :, 0] # predict the value before quantization
if energy is None:
energy = e_pred
x = x + self.energy_emb(torch.bucketize(energy, self.e_bins))
return x, (log_dur_pred, W_pred, mean_std, e_pred)
adaptor = VarianceAdaptor()
h = torch.randn(12, 256) # encoder output (12 phonemes)
# Training: use the ground truth extracted from recordings (MFA durations, PyWorld pitch, STFT energy) as inputs
dur = torch.randint(1, 8, (12,))
T = int(dur.sum())
f0 = torch.rand(T) * 200 + 100 # Hz
energy = torch.rand(T) * 100
x, (log_d, W, ms, e) = adaptor(h, dur, f0, energy)
loss_var = (F.mse_loss(log_d, torch.log(dur.float())) # compare durations in the log domain
+ F.mse_loss(e, energy)) # pitch W, mean, and variance are also compared to the ground-truth CWT with MSE
mel_pred = nn.Linear(256, 80)(x) # in practice, pass through the decoder's FFT blocks × 4
loss_mel = F.l1_loss(mel_pred, torch.randn(T, 80)) # mean absolute error (MAE) for the mel spectrogram
(loss_mel + loss_var).backward()
# Inference: use the predictors' outputs (disable dropout)
adaptor.eval()
with torch.no_grad():
x, _ = adaptor(h)
print(x.shape) # [predicted number of frames, 256]
FAQ
Q. What is the biggest difference between FastSpeech and FastSpeech 2?
A.
Whether a teacher model is used. FastSpeech used the outputs of an autoregressive teacher model as its target and extracted phoneme durations from the teacher's attention. FastSpeech 2 targets real mel spectrograms, obtains durations with an alignment tool (MFA), and also adds pitch and energy to the input. In the paper, training time dropped to about one third, and MOS rose from 3.68 to 3.83.
Q. Why is pitch wavelet-transformed instead of predicted directly?
A.
Because the pitch contour fluctuates strongly over time, so fitting it directly with mean squared error pulls predictions toward the mean and flattens the intonation. In the paper, dropping the CWT lowered the standard deviation of the generated speech's pitch from 54.1 to 42.3, and CMOS also fell by −0.185.
Q. Can pitch or speaking rate be changed at inference time?
A.
Yes. Duration, pitch, and energy are inputs to the variance adaptor, so multiplying the predicted values by a factor before converting them to embeddings changes speed, pitch, and volume. In the paper, high-quality mel spectrograms could still be generated with pitch scaled by 0.75 to 1.50.