AI Logic

Architectures

WaveGlow

Updated:

Architecture of WaveGlow. Left: the overall flow in the training direction (waveform x → group 8 samples at a time → 3 sets of 4 invertible 1×1 convolutions and affine coupling layers; 2 channels are output early between sets, and everything is finally concatenated into z ~ 𝒩(0, σ²I); the mel spectrogram is upsampled and fed to every coupling layer). Right: the inside of an affine coupling layer (the channels are split into x_a and x_b, WN computes log s and t from x_a and the mel spectrogram, and x_b′ = s ⊙ x_b + t is concatenated with x_a).

Background and Overview

WaveGlow is a normalizing-flow vocoder that turns noise drawn from a Gaussian distribution into a speech waveform through invertible transformations, conditioned on a mel spectrogram. It was published by Prenger et al. at NVIDIA in 2018 (ICASSP 2019). Its name comes from combining the architecture of the image generative model Glow with the dilated convolutions of WaveNet.

Speech synthesis is usually done in two stages. The first stage produces time-aligned features such as a mel spectrogram from text, and the second stage, the vocoder, converts them into a waveform. WaveGlow handles this second stage.

The high-quality vocoders of the time each had weaknesses.

  • Autoregressive models such as WaveNet: they generate one sample at a time, so they cannot exploit GPU parallelism, and generating faster than real time at 16 kHz is difficult.
  • Parallel WaveNet and ClariNet: they can generate in parallel, but require two-stage training, in which a student network is learned from a previously trained teacher network, plus a combination of several losses, making them hard to reproduce and deploy.

WaveGlow trains a single network with a single loss that maximizes the likelihood of the data. Even so, it generates all samples in parallel, and the paper's PyTorch implementation produced audio at more than 500 kHz on an NVIDIA V100 GPU. Its MOS on LJ Speech was 3.961, comparable in quality to a publicly available WaveNet implementation (3.885).

Architecture

WaveGlow is a model that turns samples from a simple distribution into the distribution of speech by passing them through many invertible transformations. A Gaussian sample z\mathbf{z} is mapped to a waveform x\mathbf{x} by the composition of transformations f0,…,fkf_0, \dots, f_k.

z∼N(z; 0,I),x=f0∘f1∘⋯∘fk(z)\mathbf{z} \sim \mathcal{N}(\mathbf{z};\, \mathbf{0}, \mathbf{I}), \qquad \mathbf{x} = f_0 \circ f_1 \circ \cdots \circ f_k(\mathbf{z})

Because every layer is invertible, training computes the inverse direction z=fk−1∘⋯∘f0−1(x)\mathbf{z} = f_k^{-1} \circ \cdots \circ f_0^{-1}(\mathbf{x}), and the log-likelihood can be obtained directly from the change-of-variables formula (JJ is the Jacobian).

log⁡pθ(x)=log⁡pθ(z)+∑i=1klog⁡∣det⁡J ⁣(fi−1(x))∣\log p_\theta(\mathbf{x}) = \log p_\theta(\mathbf{z}) + \sum_{i=1}^{k} \log \left| \det J\!\left(f_i^{-1}(\mathbf{x})\right) \right|

The left side of the figure at the top of the article shows the overall flow in the training direction (waveform → z\mathbf{z}), and the right side shows the inside of an affine coupling layer. In the training direction, processing proceeds as follows.

  1. Group 8 samples at a time: the waveform is grouped into sets of 8 samples, forming a sequence of 8-channel vectors (Glow's squeeze).
  2. Invertible 1×1 convolution: mixes the channels.
  3. Affine coupling layer: computes, from half of the channels, the amounts by which to scale and shift the other half. The mel spectrogram enters here as the condition.
  4. Repeat 2 and 3 twelve times: the paper's configuration has 12 coupling layers and 12 invertible 1×1 convolutions.
  5. Early outputs: after every 4 coupling layers, 2 channels are output early to the loss. The concatenation of the channels that pass through to the end and those output early is z\mathbf{z}.

The affine coupling layer splits the input in half and, from one half xa\mathbf{x}_a, computes a scale s\mathbf{s} and a shift t\mathbf{t} that transform the other half xb\mathbf{x}_b.

xa,xb=split⁡(x)(log⁡s,t)=WN(xa,mel-spectrogram)xb′=s⊙xb+tfcoupling−1(x)=concat⁡(xa,xb′)\begin{aligned} \mathbf{x}_a, \mathbf{x}_b &= \operatorname{split}(\mathbf{x}) \\ (\log \mathbf{s}, \mathbf{t}) &= WN(\mathbf{x}_a, \text{mel-spectrogram}) \\ \mathbf{x}_b' &= \mathbf{s} \odot \mathbf{x}_b + \mathbf{t} \\ f_{\mathrm{coupling}}^{-1}(\mathbf{x}) &= \operatorname{concat}(\mathbf{x}_a, \mathbf{x}_b') \end{aligned}

WNWN is a WaveNet-like network. It consists of dilated convolution layers, gated tanh units, and residual and skip connections, but its convolutions have width 3 and are not causal (they look at both past and future samples). The upsampled mel spectrogram is added before the gate in each layer, as in WaveNet.

The invertible 1×1 convolution is a channel-wise linear transformation whose weight WW is initialized as an orthogonal matrix. In a coupling layer, channels within the same half do not directly affect each other, so the channels are remixed before each coupling layer.

The log-determinant of the Jacobian is log⁡∣s∣\log|\mathbf{s}| for a coupling layer and log⁡∣det⁡W∣\log|\det W| for a 1×1 convolution. Putting everything together, the log-likelihood maximized during training is as follows (σ2\sigma^2 is the variance assumed for the Gaussian).

log⁡pθ(x)=−z(x)⊤z(x)2σ2+∑jlog⁡sj(x,mel-spectrogram)+∑klog⁡det⁡∣Wk∣\log p_\theta(\mathbf{x}) = -\frac{\mathbf{z}(\mathbf{x})^\top \mathbf{z}(\mathbf{x})}{2\sigma^2} + \sum_{j} \log \mathbf{s}_j(\mathbf{x}, \text{mel-spectrogram}) + \sum_{k} \log \det |W_k|

The first term pushes z\mathbf{z} to be small, and the second and third terms prevent the transformation from collapsing the space. The paper notes that these terms also serve to keep the coupling layers and 1×1 convolutions invertible.

At inference, z\mathbf{z} is drawn from the Gaussian and the same network is computed in reverse. The 1×1 convolutions apply the inverse of their weights, and the coupling layers are inverted by the following equation.

xb=xb′−ts\mathbf{x}_b = \frac{\mathbf{x}_b' - \mathbf{t}}{\mathbf{s}}

Why It Can Generate in Parallel

WaveGlow is fast because every transformation can be computed for all samples at once, and the inverse can be computed the same way.

WaveNet needs its own previously generated samples to predict the next sample. WaveGlow produces every sample of the waveform from z\mathbf{z} at once, so there is no need to wait in sequence. No autoregressive procedure appears in the inverse computation either.

The affine coupling layer is invertible even though the WNWN inside it need not be, because xa\mathbf{x}_a is passed through to the output unchanged. When computing in reverse, recomputing s\mathbf{s} and t\mathbf{t} from the output xa\mathbf{x}_a with the same WNWN recovers xb\mathbf{x}_b. As a result, a highly expressive network such as WaveNet can be used freely as WNWN.

The roles of the other design choices are as follows.

Design choiceWhat it doesWhat it helps with
Grouping 8 samplesTurns samples along time into channelsCreates channels to split in half in the coupling layers and shortens the sequence
Invertible 1×1 convolutionMixes channels before each coupling layerEvery channel eventually ends up on the transformed side
Early outputsOutputs 2 channels to the loss after every 4 coupling layersMakes it easier to add information at multiple time scales and helps gradients reach earlier layers
Training with only the likelihood lossTrains one network with one lossTraining is simple and stable, with no teacher network or extra losses

Earlier models that generate in parallel (Parallel WaveNet and ClariNet) use inverse autoregressive flows (IAF). An IAF can generate in parallel, but because the flow itself is autoregressive, the likelihood cannot be computed efficiently. This is why they needed two-stage training in which a teacher network trains a student network. WaveGlow showed that autoregressive flows are unnecessary for speech synthesis.

A normalizing flow is like "reshaping clay only by stretching and shifting it, without tearing pieces off or sticking pieces on". Because every step of the deformation is remembered, you can go from the finished shape back to the original ball, or make a new shape from a ball. And if you keep track of how much you stretched it (the change in volume), probabilities can be computed exactly.

Experimental Results

The paper trains on LJ Speech (a single speaker, 13,100 clips, about 24 hours) and compares waveforms reconstructed from mel spectrograms computed from the original audio. The sampling rate is 22,050 Hz, and the mel spectrogram has 80 channels (FFT size 1,024, hop 256, window 1,024).

Audio quality (MOS with 95% confidence intervals)

ModelMOS
Griffin-Lim (60 iterations)3.823 ± 0.1349
WaveNet (publicly available implementation)3.885 ± 0.1238
WaveGlow3.961 ± 0.1343
Ground truth4.274 ± 0.1340

Ratings were collected on Amazon Mechanical Turk: listeners who passed a hearing test scored 40 utterances not used in training on a 5-point scale. WaveGlow scored highest, but the paper itself notes that even with about 1,000 ratings, the differences between methods are only weakly significant, and none of them reaches the ground truth. The paper argues that WaveGlow's advantage lies rather in the simplicity of training and the speed of inference.

Inference speed

ModelSpeed (samples generated per second)
WaveNet (implementation compared)0.11 kHz (far slower than real time)
Griffin-Lim (60 iterations)507 kHz
WaveGlow (unoptimized PyTorch implementation, V100)about 520 kHz (10-second utterance)

WaveGlow's speed is more than 20 times real time at 22,050 Hz. The paper estimates from the amount of computation that a fully optimized implementation could reach an upper bound of about 2,000 kHz on a GV100.

The WaveNet compared has 24 layers (4 cycles of doubling dilation) with 512, 512, and 256 residual, gate, and skip channels. In WaveGlow, the WNWN of each coupling layer has 8 dilated convolution layers, 512 residual channels, and 256 skip channels. It was trained on 8 GPUs with randomly cropped 16,000-sample segments, a batch size of 24, Adam with a learning rate of 1×10−41 \times 10^{-4}, and Weight Normalization, for 580k updates (the learning rate was lowered to 5×10−55 \times 10^{-5} when progress plateaued).

Practical Considerations

Keep the following points in mind when using WaveGlow.

  • Many parameters: in the comparison in the HiFi-GAN paper, WaveGlow has 87.73M parameters, more than WaveNet (24.73M) or MelGAN (4.26M). It is rather heavy for devices with little memory or for running on a CPU.
  • Noise scale at inference: the paper assumes σ=0.5\sigma = \sqrt{0.5} during training and draws z\mathbf{z} from a Gaussian with standard deviation 0.6 at inference. It reports that sampling with a smaller standard deviation than in training slightly improved audio quality.
  • Lower efficiency on short utterances: the number of processing stages is the same regardless of utterance length, so the per-sample speed drops for short utterances.
  • Limited by the recording quality of the training data: the paper mentions that LJ Speech was recorded at home with the built-in microphone of a MacBook Pro. The MOS of the original recordings is also only 4.274.
  • Fine-tuning on predictions of the first-stage model gives little gain: in the HiFi-GAN paper, fine-tuning on mel spectrograms predicted by Tacotron 2 did not raise WaveGlow's MOS (3.69 → 3.66; the same fine-tuning took HiFi-GAN V1 from 3.91 → 4.18).
  • Differences between the released configuration and the paper: the paper gives 512 residual channels for WNWN, but the configuration file of NVIDIA's official implementation sets the WNWN channels to 256. When using an implementation, check the values in its configuration file.

In the paper's MOS comparison, the differences between WaveGlow, WaveNet, and Griffin-Lim are small and only weakly significant. It cannot be claimed outright that "WaveGlow sounds better than WaveNet". The main reason to choose WaveGlow is that it achieves comparable quality much faster and with simpler training.

Comparison with Other Vocoders

Comparing WaveGlow with other vocoders from the same viewpoints gives the following. MOS and speed are values measured under the same conditions on LJ Speech in the HiFi-GAN paper (ground truth: 4.45).

ModelGenerationTraining objectiveNetworks trainedMOSGPU generation speed (× real time)Parameters
WaveNet (MoL version)AutoregressiveLikelihood maximizationOne4.02 ± 0.08about 0.003×24.73 M
WaveGlowNormalizing flow (parallel)Likelihood maximizationOne3.81 ± 0.08about 22.75×87.73 M
MelGANGAN generator (parallel)Adversarial training + feature matchingGenerator and discriminators3.79 ± 0.09about 645.73×4.26 M
HiFi-GAN V1GAN generator (parallel)Adversarial training + mel-spectrogram loss, etc.Generator and discriminators4.36 ± 0.07about 167.86×13.92 M

Rough guidelines for choosing are as follows.

  • A vocoder trained by likelihood that generates in parallel: WaveGlow is a good fit. It lacks the instability of adversarial training, and training progress can be monitored through the loss value.
  • High quality, fast, with few parameters: a GAN vocoder such as HiFi-GAN is a good fit. In the comparison above, HiFi-GAN V1 has fewer parameters than WaveGlow, is faster, and has a higher MOS.
  • Preferring the ease of handling of an autoregressive model over generation speed: WaveNet is an option.

WaveGlow was widely used as the second stage of speech synthesis. It also served as the vocoder in the FastSpeech paper and in experiments comparing Transformer TTS on LJ Speech.

PyTorch example

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

"""
A small implementation of WaveGlow's flow steps (invertible 1x1 convolution + affine coupling layer)
and loss, following the paper's equations (Eqs. 5-13). PyTorch has no built-in WaveGlow
(NVIDIA's official implementation is NVIDIA/waveglow on GitHub). Early outputs are omitted.
"""

class Invertible1x1Conv(nn.Module):
    def __init__(self, c):
        super().__init__()
        W = torch.linalg.qr(torch.randn(c, c))[0]       # initialize as an orthogonal matrix (invertible)
        if torch.det(W) < 0:
            W[:, 0] = -W[:, 0]
        self.W = nn.Parameter(W)

    def forward(self, x):                                  # training direction (x → z)
        log_det = x.size(0) * x.size(2) * torch.logdet(self.W)   # log|det W| per batch item and time step (Eq. 11)
        return torch.einsum("ij,bjt->bit", self.W, x), log_det

    def reverse(self, z):                                  # inference direction: apply the inverse
        return torch.einsum("ij,bjt->bit", torch.inverse(self.W), z)


class WN(nn.Module):
    """WaveNet-like network: non-causal width-3 dilated convs, gated tanh, residual and skip"""
    def __init__(self, in_ch, mel_ch, ch=64, n_layers=4):
        super().__init__()
        self.start = nn.Conv1d(in_ch, ch, 1)
        self.convs = nn.ModuleList(nn.Conv1d(ch, 2 * ch, 3, dilation=2 ** i, padding=2 ** i) for i in range(n_layers))
        self.conds = nn.ModuleList(nn.Conv1d(mel_ch, 2 * ch, 1) for _ in range(n_layers))
        self.res = nn.ModuleList(nn.Conv1d(ch, ch, 1) for _ in range(n_layers))
        self.skip = nn.ModuleList(nn.Conv1d(ch, ch, 1) for _ in range(n_layers))
        self.end = nn.Conv1d(ch, 2 * in_ch, 1)
        nn.init.zeros_(self.end.weight); nn.init.zeros_(self.end.bias)   # start close to the identity

    def forward(self, xa, mel):
        h, out = self.start(xa), 0
        for conv, cond, res, skip in zip(self.convs, self.conds, self.res, self.skip):
            a, b = (conv(h) + cond(mel)).chunk(2, dim=1)  # add the mel spectrogram before the gate
            z = torch.tanh(a) * torch.sigmoid(b)
            h, out = h + res(z), out + skip(z)
        return self.end(out).chunk(2, dim=1)               # (log s, t)


class AffineCoupling(nn.Module):
    def __init__(self, c, mel_ch):
        super().__init__()
        self.wn = WN(c // 2, mel_ch)

    def forward(self, x, mel):
        xa, xb = x.chunk(2, dim=1)                         # Eq. 5
        log_s, t = self.wn(xa, mel)                        # Eq. 6
        xb = torch.exp(log_s) * xb + t                     # Eq. 7
        return torch.cat([xa, xb], dim=1), log_s.sum()     # Eq. 8, log|s| (Eq. 9)

    def reverse(self, y, mel):
        xa, xb = y.chunk(2, dim=1)
        log_s, t = self.wn(xa, mel)                        # x_a is unchanged, so the same s, t can be recomputed
        return torch.cat([xa, (xb - t) * torch.exp(-log_s)], dim=1)   # Eq. 13


class TinyWaveGlow(nn.Module):
    def __init__(self, mel_ch=80, group=8, n_flows=12, hop=256):
        super().__init__()
        self.group = group
        self.up = nn.ConvTranspose1d(mel_ch, mel_ch, hop * 2, stride=hop)   # upsample mel to the audio length
        self.convs = nn.ModuleList(Invertible1x1Conv(group) for _ in range(n_flows))
        self.coups = nn.ModuleList(AffineCoupling(group, mel_ch * group) for _ in range(n_flows))

    def cond(self, mel, n):
        m = self.up(mel)[:, :, :n]                         # [B, mel_ch, T]
        B, C, T = m.shape                                  # group 8 samples at a time (mel likewise)
        return m.view(B, C, T // self.group, self.group).permute(0, 1, 3, 2).reshape(B, C * self.group, -1)

    def forward(self, audio, mel):                         # training: x → z and log-determinant
        B, T = audio.shape
        x = audio.view(B, T // self.group, self.group).transpose(1, 2)   # squeeze: [B, 8, T/8]
        c = self.cond(mel, T)
        log_det = 0
        for conv, coup in zip(self.convs, self.coups):
            x, ld1 = conv(x)
            x, ld2 = coup(x, c)
            log_det = log_det + ld1 + ld2
        return x, log_det

    @torch.no_grad()
    def infer(self, mel, n_samples, sigma=0.6):            # inference: z → x (all samples in parallel)
        c = self.cond(mel, n_samples)
        z = sigma * torch.randn(mel.size(0), self.group, n_samples // self.group)
        for conv, coup in zip(reversed(self.convs), reversed(self.coups)):
            z = conv.reverse(coup.reverse(z, c))
        return z.transpose(1, 2).reshape(mel.size(0), -1)


def waveglow_loss(z, log_det, sigma=0.5 ** 0.5):
    """Negative log-likelihood (Eq. 12 with sign flipped), averaged over elements"""
    return (z.pow(2).sum() / (2 * sigma ** 2) - log_det) / z.numel()


model = TinyWaveGlow()
mel = torch.randn(2, 80, 63)                               # [batch, 80, frames]
audio = torch.rand(2, 16000) * 2 - 1                       # 16,000-sample segment (same length as in the paper's training)
z, log_det = model(audio, mel)
loss = waveglow_loss(z, log_det)
loss.backward()
wave = model.infer(mel, 16000)                             # inference uses std 0.6

FAQ

Q. Why can WaveGlow compute the likelihood directly?
A.

Because every layer is invertible. For an invertible transformation, the change-of-variables formula gives log⁡p(x)=log⁡p(z)+∑log⁡∣det⁡J∣\log p(\mathbf{x}) = \log p(\mathbf{z}) + \sum \log|\det J|. WaveGlow is built only from layers whose log-determinant is easy to compute (log⁡∣s∣\log|\mathbf{s}| for an affine coupling layer, log⁡∣det⁡W∣\log|\det W| for a 1×1 convolution), so this formula can be used directly as the training loss.

Q. How do WaveGlow and Parallel WaveNet differ?
A.

Both are flow models that generate speech in parallel, but they are trained differently. Parallel WaveNet uses an inverse autoregressive flow (IAF), which cannot compute the likelihood efficiently, so a student network is trained from a previously trained WaveNet (the teacher) with a combination of several losses. WaveGlow uses a flow with no autoregression and trains a single network with only the likelihood loss.

Q. Why is the noise standard deviation at inference smaller than in training?
A.

Following prior work such as Glow, the paper tried drawing z\mathbf{z} with 0.6, smaller than the σ=0.5≈0.71\sigma = \sqrt{0.5} \approx 0.71 assumed during training, and found a slight improvement in audio quality. How much smaller to make it is a value chosen by actually listening.

References

  1. Prenger, R., Valle, R., & Catanzaro, B. (2019). WaveGlow: A Flow-based Generative Network for Speech Synthesis. ICASSP 2019. arXiv:1811.00002.
  2. NVIDIA. Official WaveGlow implementation (PyTorch).
  3. Kingma, D. P., & Dhariwal, P. (2018). Glow: Generative Flow with Invertible 1x1 Convolutions. NeurIPS 2018. arXiv:1807.03039.
  4. Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. ICLR 2017. arXiv:1605.08803.
  5. Kong, J., Kim, J., & Bae, J. (2020). HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis. NeurIPS 2020. arXiv:2010.05646. (figures for the vocoder comparison)