AI Logic

Architectures

FastSpeech

Updated:

FastSpeech architecture. Left: the overall flow (phoneme sequence β†’ phoneme embedding β†’ positional encoding β†’ FFT blocks Γ— N β†’ length regulator β†’ positional encoding β†’ FFT blocks Γ— N β†’ linear layer β†’ mel-spectrogram β†’ WaveGlow β†’ speech waveform). From the output of the phoneme-side FFT blocks, the duration predictor predicts durations D and passes them to the length regulator. During training only, durations are extracted from the attention of the teacher model (autoregressive Transformer TTS) and the predictor is trained with mean squared error against them. Right: the inside of the length regulator (the hidden states of 4 phonemes are repeated according to durations D = [2, 2, 3, 1] and a speed ratio Ξ±, giving 5 frames at Ξ± = 0.5, 8 frames at Ξ± = 1.0, and 11 frames at Ξ± = 1.3)

Background and Overview

FastSpeech is a text-to-speech (TTS) model that predicts the duration of each phoneme (how many frames it lasts) and lays out the phoneme representations repeated for that duration, generating all mel-spectrogram frames at once (non-autoregressively). It was presented by Ren et al. from Zhejiang University and Microsoft at NeurIPS 2019.

Autoregressive models such as Tacotron 2 and Transformer TTS had three problems.

  • Slow inference: A mel-spectrogram has hundreds to thousands of frames, generated one frame at a time from the previous frames.
  • Word skipping and repetition: Accumulated errors and failures of the attention alignment between text and speech cause words to be skipped or repeated.
  • Hard to control: Without an explicit alignment between text and speech, speaking rate and prosody cannot be changed directly.

FastSpeech removes the encoder–decoder attention and instead aligns phonemes with frames using two components.

  • Duration predictor: Predicts the duration of each phoneme.
  • Length regulator: Repeats each phoneme's hidden state for its duration, stretching the sequence to the same length as the mel-spectrogram.

The results on LJ Speech are as follows.

  • Quality: MOS of 3.84, nearly the same as autoregressive Transformer TTS (3.88)
  • Speed: Compared with Transformer TTS, mel-spectrogram generation is about 270Γ— faster, and synthesis all the way to the waveform is about 38Γ— faster
  • Robustness: Zero word-skipping or repetition errors on 50 difficult sentences
  • Control: Speaking rate can be adjusted smoothly from 0.5Γ— to 1.5Γ—

Architecture

FastSpeech is built from a feed-forward structure called the Feed-Forward Transformer (FFT). The left side of the figure at the top of the article shows the overall flow, and the right side shows the inside of the length regulator.

From phonemes to mel-spectrogram, processing goes in the following order.

  1. Phoneme embedding: Phonemes (51 types including punctuation) are turned into 384-dimensional vectors, and positional encodings are added.
  2. Phoneme-side FFT blocks Γ— NN: Produce a hidden state for each phoneme, Hpho=[h1,h2,…,hn]\mathcal{H}_{pho} = [h_1, h_2, \dots, h_n].
  3. Length regulator: Stretches the hidden states according to the phoneme durations D=[d1,…,dn]\mathcal{D} = [d_1, \dots, d_n] into a sequence Hmel\mathcal{H}_{mel} of the same length as the mel-spectrogram, m=βˆ‘idim = \sum_i d_i.
  4. Mel-side FFT blocks Γ— NN: Add positional encodings to the stretched sequence and process it.
  5. Linear layer: Converts the 384-dimensional hidden states into an 80-dimensional mel-spectrogram, outputting all frames at once.
  6. WaveGlow: A pre-trained vocoder turns the mel-spectrogram into a waveform.

An FFT block is a Transformer block whose feed-forward network (two fully connected layers) is replaced with two 1D convolutional layers (with ReLU). After multi-head attention and after the convolutions, residual connections, layer normalization, and dropout are added as in the Transformer. The idea is that in both phoneme sequences and mel-spectrogram sequences, adjacent hidden states are closely related, so convolutions fit better.

The length regulator is expressed as follows, where Ξ±\alpha sets the speaking rate.

Hmel=LR(Hpho,D,Ξ±)\mathcal{H}_{mel} = \mathcal{LR}(\mathcal{H}_{pho}, \mathcal{D}, \alpha)

For example, with Hpho=[h1,h2,h3,h4]\mathcal{H}_{pho} = [h_1, h_2, h_3, h_4] and D=[2,2,3,1]\mathcal{D} = [2, 2, 3, 1], normal speed (Ξ±=1\alpha = 1) gives [h1,h1,h2,h2,h3,h3,h3,h4][h_1, h_1, h_2, h_2, h_3, h_3, h_3, h_4]. At Ξ±=1.3\alpha = 1.3 (slow) the durations become [2.6,2.6,3.9,1.3]β‰ˆ[3,3,4,1][2.6, 2.6, 3.9, 1.3] \approx [3, 3, 4, 1], and at Ξ±=0.5\alpha = 0.5 (fast) they become [1,1,1.5,0.5]β‰ˆ[1,1,2,1][1, 1, 1.5, 0.5] \approx [1, 1, 2, 1], changing the sequence length. Changing the duration of spaces in the sentence (word boundaries) also adjusts the pauses between words.

The duration predictor is a small network placed on top of the phoneme-side FFT blocks. It consists of two 1D convolutional layers (ReLU, each followed by layer normalization and dropout) and a linear layer that outputs a scalar. Durations are predicted in the logarithmic domain, which brings them closer to a Gaussian distribution and makes them easier to learn.

The settings in the paper are as follows.

ComponentSetting
FFT blocks6 on the phoneme side, 6 on the mel-spectrogram side
Hidden size384 (embedding, attention, convolution)
Attention heads2
FFT block convolutionsKernel width 3, 384 β†’ 1,536 β†’ 384
Duration predictor convolutionsKernel width 3, two layers of 384 β†’ 384
Output80-dimensional mel-spectrogram

Autoregressive models use attention to decide "which phoneme is being read now" automatically at every step, so when the alignment drifts, words get skipped or repeated. FastSpeech decides in advance how many frames each phoneme lasts (a hard alignment), so every phoneme is read exactly once, in order.

Training

Training FastSpeech uses a pre-trained autoregressive Transformer TTS (the teacher). The teacher has two roles.

  • Producing ground-truth phoneme durations: It provides the per-phoneme durations used to train the duration predictor.
  • Producing target mel-spectrograms: Through sequence-level knowledge distillation, mel-spectrograms generated by the teacher become FastSpeech's training targets.

Phoneme durations are extracted from the teacher's encoder–decoder attention as follows.

  1. Train the teacher: Train an encoder–decoder Transformer TTS (6 layers each, but with 1D convolutions in place of the position-wise feed-forward networks).
  2. Pick the most diagonal head: Feed the training pairs back into the teacher and extract the attention weights. With multi-head attention there are several, but only some heads show the monotonic (diagonal) alignment between phonemes and frames. So the head with the largest focus rate FF, defined below, is chosen.
  3. Count durations: Using the chosen head, count the frames that attend most strongly to each phoneme; this count is the phoneme duration did_i.

SS is the length of the mel-spectrogram, TT is the length of the phoneme sequence, and as,ta_{s,t} is the attention weight at row ss, column tt of the attention matrix.

F=1Sβˆ‘s=1Smax⁑1≀t≀Tas,t,di=βˆ‘s=1S[arg⁑max⁑tas,t=i]F = \frac{1}{S} \sum_{s=1}^{S} \max_{1 \le t \le T} a_{s,t}, \qquad d_i = \sum_{s=1}^{S} \left[ \arg\max_t a_{s,t} = i \right]

FastSpeech is trained jointly with the duration predictor. The duration predictor's loss is the mean squared error against the extracted durations. During training, the length regulator uses the durations extracted from the teacher; the durations predicted by the duration predictor are used only at inference.

The training settings in the paper are as follows.

ItemValue
DataLJ Speech (13,100 English audio clips, about 24 hours), randomly split into 12,500 training, 300 validation, and 300 test
InputText is converted into a phoneme sequence with an internal grapheme-to-phoneme tool
Mel-spectrogramComputed following Tacotron 2; frame size 1,024, hop 256
OptimizationAdam (Ξ²1=0.9\beta_1 = 0.9, Ξ²2=0.98\beta_2 = 0.98, Ο΅=10βˆ’9\epsilon = 10^{-9}), the same learning rate schedule as the Transformer (decay after warmup)
ComputeBoth the teacher and FastSpeech on 4 NVIDIA V100s (16 sentences per GPU), about 80k steps each

Experimental Results

Quality (LJ Speech test set, MOS with 95% confidence intervals)

SystemMOS
Ground-truth recordings4.41 Β± 0.08
Ground-truth recordings β†’ mel-spectrogram β†’ WaveGlow4.00 Β± 0.09
Tacotron 2 (Mel + WaveGlow)3.86 Β± 0.09
Merlin (WORLD)2.40 Β± 0.13
Transformer TTS (Mel + WaveGlow)3.88 Β± 0.09
FastSpeech (Mel + WaveGlow)3.84 Β± 0.08

Each audio sample was rated by at least 20 native English speakers. FastSpeech is nearly on par with autoregressive Transformer TTS and Tacotron 2.

Inference speed (one V100, batch size 1; generated mel-spectrograms average about 560 frames for both)

SystemLatency (s)Speedup
Transformer TTS (Mel)6.735 ± 3.969-
FastSpeech (Mel)0.025 Β± 0.005269.40Γ—
Transformer TTS (Mel + WaveGlow)6.895 ± 3.969-
FastSpeech (Mel + WaveGlow)0.180 Β± 0.07838.30Γ—

Transformer TTS's latency grows sharply as the generated mel-spectrogram gets longer, but FastSpeech's latency barely changes with length, because it generates all frames in parallel.

Robustness (50 sentences that are hard for speech synthesis; each type of error is counted at most once per sentence)

SystemRepeatsSkipsSentences with errorsError rate
Tacotron 24111224%
Transformer TTS7151734%
FastSpeech0000%

The difficult sentences include single-letter words, spelled-out words, repeated numbers, and long sentences.

Duration control: Stretching or shrinking phoneme durations smoothly changed the speaking rate from 0.5Γ— to 1.5Γ— with almost no change in pitch. Lengthening the spaces also inserted pauses between words.

Effect of each component (CMOS; FastSpeech is 0, compared by listening to pairs side by side)

SystemCMOS
FastSpeech0
Replace the 1D convolutions in the FFT blocks with fully connected layers (similar parameter count)βˆ’0.113-0.113
Remove sequence-level knowledge distillationβˆ’0.325-0.325

Both components contribute to quality, and knowledge distillation has the larger effect.

Practical Considerations

Keep the following points in mind when using FastSpeech.

  • A teacher model is required: An autoregressive Transformer TTS must be trained first to produce ground-truth phoneme durations and target mel-spectrograms. Training becomes a two-stage process, and the teacher's quality caps FastSpeech's.
  • Duration extraction depends on attention quality: For sentences where the teacher's attention is not diagonal, the extracted durations are also inaccurate.
  • Quality rarely exceeds the teacher's: The paper's MOS falls just short of the teacher Transformer TTS (3.84 vs. 3.88). The paper notes that in additional experiments on internal data, distilling with large amounts of untranscribed text brought quality on par with the teacher across multiple languages and speakers.
  • Assumes conversion to phonemes: To reduce mispronunciations, the paper converts text to phonemes with an internal tool before input.
  • Durations come from different sources in training and inference: Training uses durations extracted from the teacher, and inference uses predicted durations. Predicted durations are rounded to integers.
  • Dropout is present: The FFT blocks and duration predictor contain dropout, so switch to model.eval() for inference.

The speedups (about 270Γ— and about 38Γ—) are measured against autoregressive Transformer TTS on one V100 with batch size 1. When the vocoder (WaveGlow) is included, the vocoder takes most of the synthesis time, so the overall speedup is much smaller than the mel-spectrogram-only speedup.

Comparison with Other Models

Comparing representative models that generate mel-spectrograms from text from the same perspective gives the following.

ModelText–frame alignmentGenerationHow length is determinedSpeaking rate control
TacotronContent-based attentionAutoregressive (rr frames at a time)Keeps generating and reconstructs through zero-padded framesNot possible
Tacotron 2Location-sensitive attentionAutoregressive (1 frame at a time)Stop tokenNot possible
Transformer TTSMulti-head attentionAutoregressive (1 frame at a time)Stop tokenNot possible
FastSpeechPredict per-phoneme durations and stretchNon-autoregressive (all frames in parallel)Sum from the duration predictorMultiply durations by Ξ±\alpha

Guidelines for choosing:

  • Prioritizing inference speed and freedom from skipping and repetition: FastSpeech is a good fit. Generation time hardly depends on the mel-spectrogram length, and errors are unlikely even on difficult sentences.
  • Training without preparing a teacher model: Autoregressive Tacotron 2 and Transformer TTS can be trained on text–speech pairs alone. A model that carries on the FastSpeech name, FastSpeech 2, also exists.
  • Adjusting speaking rate or pauses afterward: FastSpeech is convenient because the length regulator can change durations directly.

PyTorch example

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

"""
A small implementation of FastSpeech's components (Chapter 3 and Section 4.2 of the paper)
Neither PyTorch nor torchaudio has a built-in FastSpeech
1. FFT block: multi-head self-attention β†’ residual + layer norm β†’ two 1D conv layers β†’ residual + layer norm
2. Duration predictor: two 1D conv layers (ReLU β†’ layer norm β†’ dropout) β†’ linear layer (outputs log durations)
3. Length regulator: repeat each phoneme hidden state round(duration Γ— Ξ±) times
"""


class FFTBlock(nn.Module):
    def __init__(self, d=384, heads=2, d_conv=1536, kernel=3, p=0.1):
        super().__init__()
        self.attn = nn.MultiheadAttention(d, heads, dropout=p, batch_first=True)
        self.norm1 = nn.LayerNorm(d)
        self.conv = nn.Sequential(
            nn.Conv1d(d, d_conv, kernel, padding=kernel // 2), nn.ReLU(),
            nn.Conv1d(d_conv, d, kernel, padding=kernel // 2))
        self.norm2 = nn.LayerNorm(d)
        self.drop = nn.Dropout(p)

    def forward(self, x, pad_mask=None):            # x: [B, T, d]
        a, _ = self.attn(x, x, x, key_padding_mask=pad_mask)
        x = self.norm1(x + self.drop(a))
        c = self.conv(x.transpose(1, 2)).transpose(1, 2)
        return self.norm2(x + self.drop(c))


class DurationPredictor(nn.Module):
    def __init__(self, d=384, kernel=3, p=0.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, 1)

    def forward(self, h):                            # h: output of the phoneme-side FFT blocks [B, N, 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).squeeze(-1)              # Durations in the log domain [B, N]


def length_regulator(h, durations, alpha=1.0):
    """h: [N, d] (one sentence), durations: [N]. Repeat each phoneme round(duration Γ— Ξ±) times"""
    reps = torch.floor(durations.float() * alpha + 0.5).long().clamp(min=0)   # 0.5 rounds up (as in the paper's example)
    return torch.repeat_interleave(h, reps, dim=0)  # [Ξ£ reps, d]


# The paper's example: D = [2, 2, 3, 1]
h = torch.eye(4)                                     # Make h1–h4 easy-to-distinguish 4-dimensional vectors
D = torch.tensor([2, 2, 3, 1])
print(length_regulator(h, D, 1.0).argmax(-1))       # tensor([0, 0, 1, 1, 2, 2, 2, 3])  β†’ 8 frames
print(length_regulator(h, D, 0.5).argmax(-1))       # tensor([0, 1, 2, 2, 3])  β†’ durations [1, 1, 2, 1], 5 frames
print(length_regulator(h, D, 1.3).argmax(-1).numel())   # 11 frames (durations [3, 3, 4, 1])

# Training: the duration predictor is trained with MSE against durations (log) extracted from the teacher
blocks = nn.ModuleList(FFTBlock() for _ in range(6))
predictor = DurationPredictor()
x = torch.randn(2, 12, 384)                          # Phoneme embeddings + positional encodings
for blk in blocks:
    x = blk(x)
target_dur = torch.randint(1, 10, (2, 12)).float()  # Durations counted from the teacher's attention
loss_dur = F.mse_loss(predictor(x), torch.log(target_dur))
loss_dur.backward()

# Inference: map predicted durations back to the original domain and round them
predictor.eval()
with torch.no_grad():
    dur = torch.clamp(torch.floor(torch.exp(predictor(x[0:1])) + 0.5), min=1)[0]
    h_mel = length_regulator(x[0], dur, alpha=1.0)   # Into the mel-side FFT blocks
print(h_mel.shape)

FAQ

Q. Why are phoneme durations predicted in the log domain?
A.

According to the paper, taking the logarithm brings the duration distribution closer to a Gaussian, which makes it easier to learn. At inference, the predicted value is mapped back with exp⁑\exp, rounded to an integer, and passed to the length regulator.

Q. How is the speaking rate changed?
A.

In the length regulator, each phoneme's duration is multiplied by Ξ±\alpha and rounded. With Ξ±=1.3\alpha = 1.3 the durations grow by about 1.3Γ— and speech slows down; with Ξ±=0.5\alpha = 0.5 they roughly halve and speech speeds up. In the paper, the rate could be changed smoothly from 0.5Γ— to 1.5Γ— with almost no change in pitch.

Q. Why train on the teacher's mel-spectrograms (knowledge distillation)?
A.

Because it improved quality in the paper's comparison. Removing sequence-level knowledge distillation lowered CMOS by βˆ’0.325-0.325. The paper adopted it because it had worked well in non-autoregressive machine translation. The drop was larger than when the FFT block convolutions were replaced with fully connected layers (βˆ’0.113-0.113).

References

  1. Ren, Y., Ruan, Y., Tan, X., Qin, T., Zhao, S., Zhao, Z., & Liu, T.-Y. (2019). FastSpeech: Fast, Robust and Controllable Text to Speech. NeurIPS 2019. arXiv:1905.09263.
  2. FastSpeech audio samples (by the paper's authors)
  3. Li, N., et al. (2019). Neural Speech Synthesis with Transformer Network (Transformer TTS). AAAI 2019. arXiv:1809.08895.
  4. Ito, K. (2017). The LJ Speech Dataset.