Glow-TTS is a non-autoregressive text-to-speech (TTS) model that uses a normalizing-flow decoder to map mel spectrograms to latent variables and learns while finding, by itself, the most likely monotonic alignment with the text via dynamic programming. Kim et al. of Kakao Enterprise and Seoul National University presented it at NeurIPS 2020.
Non-autoregressive models such as FastSpeech can generate mel spectrograms quickly and in parallel. However, they needed an external aligner to learn the correspondence between phonemes and frames (how many frames each phoneme lasts). FastSpeech extracts phoneme durations from the attention of a pretrained autoregressive model, and FastSpeech 2 from an alignment tool (MFA). As a result, the aligner's quality limits the model's performance, and the training pipeline becomes complex.
Glow-TTS finds the alignment within the model itself, without an aligner.
Flow decoder: An invertible transformation maps back and forth between mel spectrograms and latent variables. Because it is invertible, the log-likelihood of a mel spectrogram can be computed exactly.
Monotonic alignment search (MAS): Following the way people read text in order without skipping, it uses dynamic programming to find, among "in-order, no-skipping" alignments, the one with the highest log-likelihood.
Quality: A MOS of 4.01 (temperature 0.333), comparable to Tacotron 2 (3.88)
Speed: Mel spectrogram generation is on average 15.7 times faster than Tacotron 2 and stays nearly constant (about 40 ms) regardless of sentence length
Robustness: The character error rate barely rises even for long sentences of over 800 characters
Diversity and control: It can produce speech with different intonation from the same sentence and can also change pitch and speaking rate
Architecture
Glow-TTS consists of three parts: a text encoder, a duration predictor, and a flow decoder. In the figure at the top of the article, the left side shows training, the center shows inference, and the right side shows the inside of monotonic alignment search.
Glow-TTS models the distribution PXโ(xโฃc) of a mel spectrogram x given text c as the distribution PZโ(zโฃc) (the prior) of a latent variable z transformed by the flow decoder fdecโ:zโx. Because the decoder is invertible, the change-of-variables formula gives the exact log-likelihood.
The prior is a Gaussian with a per-phoneme mean ฮผiโ and standard deviation ฯiโ. The alignment A is a function that maps the j-th frame of the latent variable to the i-th phoneme (A(j)=i). Tmelโ is the number of frames.
A is assumed to be monotonic (it never goes backward) and surjective (every phoneme maps to at least one frame). This rules out skipping or repeating phonemes.
The components are as follows.
Text encoder: The encoder of Transformer TTS (a pre-net and a Transformer encoder) with two changes: positional encoding is dropped in favor of relative position representations in self-attention, and residual connections are added to the pre-net. A final linear layer is designed to output ฮผiโ and ฯiโ for each phoneme. In the paper's experiments, however, the standard deviation was fixed to a constant 1 during training, so only the mean is actually learned and output.
Duration predictor: The same design as in FastSpeech (two 1D convolution layers with ReLU, layer normalization, and dropout, plus an output linear layer). It predicts each phoneme's duration in the log domain from the encoder output.
Flow decoder: A stack of 12 flow blocks, the same as in Glow. Each block consists of activation normalization (ActNorm), an invertible 1ร1 convolution, and an affine coupling layer. The affine coupling layer has the same form as in WaveGlow, but without conditioning on the mel spectrogram.
The decoder uses two tricks to reduce computation.
Grouping 2 frames at a time: The 80-channel mel spectrogram is squeezed along time, 2 frames at a time, into 160 channels before passing through the flow.
Splitting the 1ร1 convolution into groups: The channels are split into 40 groups, and a small 1ร1 convolution is applied to each group. This makes the determinant cheap to compute. Each group takes an equal number of channels from the two halves split by the coupling layer, so the two halves are mixed within each group as well.
The paper's settings (LJ Speech) are as follows.
Component
Setting
Embedding and hidden dimension
192
Pre-net
3 convolution layers (kernel size 5, dropout 0.5)
Encoder
6 blocks, 2 heads, maximum relative position 4, convolution kernel size 3 and dimension 768, dropout 0.1
Duration predictor
Convolution kernel size 3, dimension 256
Decoder
12 flow blocks, 40 groups for the 1ร1 convolution, 4 convolution layers in the coupling layer with kernel size 5 and dimension 192, dropout 0.05
Number of parameters
28.6M (FastSpeech: 30.1M)
Monotonic Alignment Search (MAS)
Monotonic alignment search is a method that uses dynamic programming to find the monotonic alignment Aโ that maximizes the log-likelihood under the current parameters.
Because optimizing the parameters ฮธ and the alignment A jointly is hard, each training step alternates between the following two. This follows the same idea as Viterbi training, which maximizes the log-likelihood of the most likely hidden alignment.
Find Aโ: With the current ฮธ, monotonic alignment search finds the most likely alignment.
Update ฮธ: Gradient descent increases the log-likelihood logPXโ(xโฃc;ฮธ,Aโ) under Aโ.
Aโ is obtained by filling table Q and then backtracking. Qi,jโ is the maximum log-likelihood when the first i phonemes are aligned to the first j frames.
Fill the first row: Set Q1,jโ=โk=1jโlogN(zkโ;ฮผ1โ,ฯ1โ).
Fill the rest in order: For j=2,โฆ,Tmelโ and i=2,โฆ,min(j,Ttextโ), compute the recurrence below.
Backtrack from the end: Start from Aโ(Tmelโ)=Ttextโ, and for j=Tmelโโ1,โฆ,1, set Aโ(j) to whichever of Aโ(j+1)โ1 and Aโ(j+1) has the larger Qi,jโ.
If frame j is aligned to phoneme i, then because the alignment is monotonic and does not skip, the previous frame jโ1 must be aligned to either phoneme iโ1 or phoneme i. The recurrence picks the better of these two cases.
From the resulting Aโ, the duration of each phoneme (the number of frames aligned to it) is counted and used as the target for the duration predictor.
The complexity is O(TtextโรTmelโ). The procedure is hard to parallelize, but on a CPU it took less than 20 ms per step, under 2% of the total training time. Inference uses the duration predictor, so monotonic alignment search is not needed.
Like CTC in speech recognition and alignment in hidden Markov models, monotonic alignment search finds an alignment with dynamic programming. The difference is that Glow-TTS is a generative model and, once aligned, can generate all frames in parallel.
Training and Inference
During training, each step computes the following in order.
The text encoder outputs ฮผiโ and ฯiโ for each phoneme.
The mel spectrogram x is passed through the flow decoder in reverse to obtain the latent variable z=fdecโ1โ(x).
Monotonic alignment search finds the most likely alignment Aโ between z and ฮผ, ฯ.
Maximize the log-likelihood: The encoder and decoder are updated to increase logPXโ(xโฃc) under Aโ.
Train the duration predictor: It learns to predict the durations d counted from Aโ, using the mean squared error in the log domain.
A stop-gradient operation sg[โ ] is applied to the duration predictor's input so that the duration loss does not affect log-likelihood training.
Ldurโ=MSE(fdurโ(sg[fencโ(c)]),d)
During inference, the following are computed in order.
The text encoder produces ฮผiโ and ฯiโ, and the duration predictor produces each phoneme's duration.
Build the alignment: ฮผiโ and ฯiโ are repeated by the predicted durations. The official implementation rounds the predicted durations up to integers.
Sample the latent variable: z is sampled from the prior.
Pass it through the flow decoder in the forward direction to generate the mel spectrogram for all frames in parallel.
In the paper's training, the prior's standard deviation ฯ is set to a constant 1. At inference, the prior's standard deviation is adjusted as a temperatureT, and z is sampled as follows (ฯต is a sample from the standard normal distribution).
z=ฮผ+ฯตโ T
Changing ฯต yields speech with different intonation and accents, and changing T changes the pitch while preserving the shape of the intonation. Multiplying the predicted durations by a positive number also changes the speaking rate (1.25, 1.0, 0.75, and 0.5 times in the paper).
The paper's training settings are as follows.
Item
Value
Data
LJ Speech randomly split into 12,500 training, 100 validation, and 500 test samples. For multi-speaker, the train-clean-100 subset of LibriTTS (247 speakers, about 54 hours)
Input
Phonemes
Optimization
Adam with the same learning rate schedule as the Transformer (decay after warmup)
Compute
Single speaker: 240k steps on 2 V100s (3 days with mixed precision). Multi-speaker: 960k steps on 4 V100s
Vocoder
Pretrained WaveGlow
For multi-speaker training, a speaker embedding is fed as a global condition to every affine coupling layer in the decoder, and the hidden dimension is increased. Because speaker information is not given to the encoder, the latent variable z becomes a speaker-independent representation. This also enables voice conversion: convert one speaker's mel spectrogram to z, then map it back conditioned on another speaker.
Experimental Results
Audio quality (50 sentences from the LJ Speech test set, MOS with 95% confidence intervals; both use WaveGlow as the vocoder)
The evaluation was run on Amazon Mechanical Turk, using MOS on a 9-point scale. A temperature of 0.333 gave the best result, and every temperature was comparable to Tacotron 2. In a 7-point side-by-side CMOS test (500 ratings), Glow-TTS (T=0.333) outperformed Tacotron 2 by 0.934.
Speed: Glow-TTS's mel spectrogram generation time stayed almost constant at about 40 ms regardless of sentence length. Tacotron 2 generates one frame at a time, so its time grows in proportion to length. On average, Glow-TTS was 15.7 times faster. Generating 1 minute of speech including WaveGlow took 1.5 seconds in total, of which Glow-TTS accounted for 55 ms (4%) and WaveGlow for the remaining 96%.
Robustness: The character error rate was measured with Google Cloud Speech-to-Text on 227 sentences, some longer than 800 characters, taken from the first two chapters of Harry Potter and the Philosopher's Stone. Tacotron 2's error rate began to rise beyond about 260 characters, while Glow-TTS's error rate barely rose, even for sentence lengths not seen in training.
The number of attention errors on the same 100 sentences used in the ParaNet paper is as follows.
Model
Repeats
Mispronunciations
Skips
Total
Tacotron 2
0
2
1
3
Glow-TTS (T=0.333)
0
3
1
4
On these 100 sentences (59.65 characters on average), Glow-TTS made slightly more errors than Tacotron 2. The paper argues that Glow-TTS maintains its robustness better on long sentences.
Multi-speaker (LibriTTS, one sentence from each of 50 speakers, MOS)
In the multi-speaker setting, the best configuration was also comparable to Tacotron 2. Unlike the single-speaker case, higher temperatures gave better results.
Practical Considerations
Keep the following points in mind when using Glow-TTS.
Choose the temperature: The inference temperature T changes quality and diversity. In the paper, 0.333 worked best for a single speaker and 0.667 for multi-speaker; the optimal value depended on the data.
Run monotonic alignment search on the CPU: It is hard to parallelize, so the paper computes it on the CPU. It takes under 20 ms per step, but grows as O(TtextโรTmelโ) for long sentences or many frames.
Non-monotonic alignments are not supported: The alignment is assumed to be monotonic, with every phoneme mapped to at least one frame.
The vocoder determines speed: Glow-TTS itself is fast; for the paper's 1 minute of speech, 96% of the total time was spent in WaveGlow. To speed up the whole pipeline, pair it with a fast vocoder such as HiFi-GAN.
The last frame is dropped for odd lengths: Because frames are grouped 2 at a time, the last frame (about 11 ms) is dropped when the number of frames is odd. The paper reports no difference in quality.
It uses dropout: The encoder (0.1), pre-net (0.5), and decoder (0.05) use dropout, so switch to model.eval() for inference. ActNorm uses data-dependent initialization.
Apply the stop-gradient operation to the duration predictor's input. Without it, the duration loss backpropagates into the encoder and pushes the encoder in a direction that conflicts with maximizing the log-likelihood. The paper includes this operation so that the duration loss does not affect the maximum likelihood objective.
Comparison with Other Models
Comparing non-autoregressive TTS models from the same angle gives the following.
Model
How phoneme durations are obtained
Training objective
Decoder
Can it produce different speech from the same sentence?
You do not want to prepare an external aligner or teacher model: Glow-TTS is a good fit. It trains on textโaudio pairs alone.
You want the same sentence read with various intonations: As a generative model, Glow-TTS can produce diverse speech by changing ฯต or the temperature.
You want even higher quality: Options include Matcha-TTS, which inherits Glow-TTS's monotonic alignment search and switches the decoder to flow matching, and VITS, which folds the vocoder into a single model as well.
PyTorch example
โถShow code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the core of Glow-TTS training (Sections 3.1 and 3.2 and Algorithm 1 of the paper)
PyTorch and torchaudio have no built-in Glow-TTS
1. Monotonic alignment search (MAS): fill table Q, then backtrack to get the alignment A* and durations d
2. Loss: negative log-likelihood under A* (prior + flow Jacobian) and the duration MSE with stop-gradient
3. Inference: predict durations, repeat ฮผ, and map z = ฮผ + ฮตยทT back through the flow decoder
(The flow decoder here is a single affine coupling layer. The real one is 12 blocks of ActNorm, 1ร1 convolution, and coupling layer)
"""
def log_normal(z, mu, logs):
"""Return log N(z_j; mu_i, sigma_i) for every pair of phoneme i and frame j. z: [C, Tmel], mu and logs: [C, Ttext] โ [Ttext, Tmel]"""
z, mu, logs = z[:, None, :], mu[:, :, None], logs[:, :, None]
return (-0.5 * math.log(2 * math.pi) - logs - 0.5 * ((z - mu) * torch.exp(-logs)) ** 2).sum(0)
@torch.no_grad()
def monotonic_alignment_search(logp):
"""logp: [Ttext, Tmel]. Follows Algorithm 1. Returns A* (the phoneme index of each frame, 0-based)"""
T_text, T_mel = logp.shape
Q = torch.full((T_text, T_mel), -float("inf"))
Q[0] = torch.cumsum(logp[0], 0) # first row
for j in range(1, T_mel):
for i in range(1, min(j + 1, T_text)):
Q[i, j] = torch.maximum(Q[i - 1, j - 1], Q[i, j - 1]) + logp[i, j]
A = torch.empty(T_mel, dtype=torch.long)
A[-1] = T_text - 1 # the last frame belongs to the last phoneme
for j in range(T_mel - 2, -1, -1):
i = A[j + 1]
A[j] = i - 1 if (i > 0 and Q[i - 1, j] > Q[i, j]) else i
return A
class AffineCoupling(nn.Module):
"""Compute scale and shift for one half of the channels from the other half (invertible)"""
def __init__(self, ch=160, hidden=192):
super().__init__()
self.net = nn.Sequential(nn.Conv1d(ch // 2, hidden, 5, padding=2), nn.ReLU(), nn.Conv1d(hidden, ch, 1))
nn.init.zeros_(self.net[-1].weight); nn.init.zeros_(self.net[-1].bias) # identity map at the start
def inverse(self, x): # training direction: x โ z
xa, xb = x.chunk(2, 0)
logs, t = self.net(xa[None])[0].chunk(2, 0)
return torch.cat([xa, (xb - t) * torch.exp(-logs)]), -logs.sum() # z and log|det|
def forward(self, z): # inference direction: z โ x
za, zb = z.chunk(2, 0)
logs, t = self.net(za[None])[0].chunk(2, 0)
return torch.cat([za, zb * torch.exp(logs) + t])
# One training step (one sentence)
T_text, T_mel, C = 6, 40, 160 # 80 mel channels grouped 2 frames at a time into 160 channels
h = torch.randn(T_text, 192, requires_grad=True) # (stand-in for) the text encoder output
proj = nn.Linear(192, C) # prior mean ฮผ (ฯ is fixed at 1 in the paper's training)
dur_pred = nn.Linear(192, 1) # (stand-in for) the duration predictor
decoder = AffineCoupling(C)
x = torch.randn(C, T_mel) # grouped mel spectrogram
mu, logs = proj(h).T, torch.zeros(C, T_text)
z, logdet = decoder.inverse(x) # 2. pass through the flow decoder in reverse
A = monotonic_alignment_search(log_normal(z, mu, logs)) # 3. monotonic alignment search (no gradient)
nll = -(log_normal(z, mu, logs)[A, torch.arange(T_mel)].sum() + logdet) / (C * T_mel) # 4. negative log-likelihood
d = torch.bincount(A, minlength=T_text).float() # Eq. (5): duration of each phoneme
loss_dur = F.mse_loss(dur_pred(h.detach()).squeeze(-1), torch.log(d)) # Eq. (6): sg[] is detach
(nll + loss_dur).backward()
# Inference: predict durations, repeat ฮผ, and map z = ฮผ + ฮตยทT back through the decoder
with torch.no_grad():
w = torch.ceil(torch.exp(dur_pred(h).squeeze(-1)) * 1.0) # changing 1.0 to 1.25 or 0.75 changes the speaking rate
mu_frames = torch.repeat_interleave(mu, w.clamp(min=1).long(), dim=1)
T = 0.333 # temperature
z = mu_frames + torch.randn_like(mu_frames) * T # Eq. (8)
mel = decoder(z) # [160, grouped frames]; ungrouping gives 80 channels and twice the frames
print(A.tolist(), d.tolist(), mel.shape)
FAQ
Q. Why can it train without an external aligner?
A.
Because the flow decoder is invertible, the mel spectrogram can be mapped to the latent variable z, and the log-likelihood can be computed exactly under any alignment. At each step, it alternates between finding, with dynamic programming (monotonic alignment search), the monotonic alignment that maximizes the log-likelihood under the current parameters, and increasing the log-likelihood under that alignment.
Q. What is the temperature $T$?
A.
It is the standard deviation of the prior used when sampling the latent variable at inference. Samples are drawn as z=ฮผ+ฯตโ T. In the paper, changing T changes the pitch while preserving the shape of the intonation, and on LJ Speech the MOS was highest at T=0.333.
Q. It uses the same duration predictor as FastSpeech, so what is different?
A.
The duration predictor has the same form as in FastSpeech, but the target durations come from a different source. FastSpeech counts durations from a teacher model's attention, while Glow-TTS counts them from the alignment found by its own monotonic alignment search. Glow-TTS also stops the gradient at the duration predictor's input so that the duration loss does not affect log-likelihood training.