AI Logic

Architectures

MelGAN

Updated:

Architecture of MelGAN. The left side shows the generator (mel spectrogram → 7×1 convolution → transposed convolutions upsampling by 8, 8, 2, and 2, each followed by a residual stack → 7×1 convolution and tanh → waveform). The center shows the inside of the residual stack (three residual blocks, each with a convolution of dilation 1, 3, or 9 and a convolution of dilation 1). The right side shows the discriminator (three discriminators look at the waveform and at versions downsampled to 1/2 and 1/4 by average pooling, and the hinge loss and feature matching loss are computed from the feature maps and per-window decisions).

Background and Overview

MelGAN is a vocoder whose generator, which produces speech waveforms from mel spectrograms, is trained in the GAN (generative adversarial network) framework. Kumar et al. at Lyrebird AI and Mila introduced it in 2019 (NeurIPS 2019). It is entirely convolutional, generates all samples in parallel, and has only 4.26 M parameters, far fewer than other high-quality vocoders.

Until then, generating coherent raw waveforms with GANs was considered difficult. Prior work applying GANs to audio either generated the magnitude and phase of spectrograms or combined them with a KL divergence loss for distillation; adversarial losses alone had not produced high-quality waveforms. Other families of vocoders each had their own weaknesses.

  • Autoregressive models such as WaveNet: They generate one sample at a time, so inference is slow and unsuitable for real-time use.
  • Parallel WaveNet and ClariNet: They require distillation from a teacher model to a student model.
  • WaveGlow: It generates in parallel, but has many parameters and is unsuitable for memory-constrained applications. The paper also notes the WaveGlow authors' statement that obtaining good quality for a single-speaker model required a week of training on 8 GPUs.

By combining generator and discriminator architectures with simple training techniques, MelGAN showed that a GAN alone, without distillation or perceptual losses, can produce high-quality waveforms. The paper describes this as the first such result to the authors' knowledge. It generates speech more than 100 times faster than real time on a GTX 1080 Ti GPU and more than 2 times faster than real time even on a CPU.

Architecture

MelGAN consists of a generator that produces a waveform G(s)G(s) from a mel spectrogram ss, and three discriminators that tell whether a waveform is real or generated. In the figure at the top of the article, the left side shows the generator, the center shows the inside of the generator's residual stack, and the right side shows the discriminators.

The generator upsamples the mel spectrogram by a factor of 256 in temporal resolution to produce the waveform (there is one mel spectrogram frame per 256 waveform samples).

  1. Input convolution: Apply a 7×1 convolution to the mel spectrogram to get 512 channels.
  2. Upsampling: Increase temporal resolution with transposed convolutions after Leaky ReLU. Four stages upsample by 8, 8, 2, and 2 (256 in total) while halving the channels to 256, 128, 64, and 32.
  3. Residual stack: After each upsampling stage, place a residual stack of three residual blocks with dilated convolutions.
  4. Output: Apply Leaky ReLU and a 7×1 convolution to get 1 channel, then tanh to produce a waveform in −1-1 to 11.

Unlike typical GANs, the generator does not take a noise vector. A mel spectrogram is a compressed representation of a waveform, so many waveforms should correspond to a single mel spectrogram; yet in the paper's experiments, adding noise made little perceptual difference. The paper notes this is consistent with findings in image research that noise is unimportant when the conditioning information is strong.

Each block of the residual stack is Leaky ReLU → 3×1 convolution (dilation 1, 3, or 9) → Leaky ReLU → 3×1 convolution (dilation 1), with the input added. With the three layers of dilation 1, 3, and 9, the receptive field is 27 samples.

The discriminator consists of three discriminators D1,D2,D3D_1, D_2, D_3 with the same architecture that differ only in the scale of waveform they see. D1D_1 sees the original waveform, while D2D_2 and D3D_3 see waveforms downsampled to 1/2 and 1/4 by average pooling with a width of 4. Each discriminator is a 7-layer convolutional network including grouped convolutions (four layers with stride 4), and it decides real or generated not for the whole waveform but for each window the size of its receptive field. Weight Normalization is applied to every layer of the generator and discriminators.

The losses are the GAN hinge loss and feature matching. With xx as a real waveform, each discriminator DkD_k is trained to output values of 1 or more for real waveforms and −1-1 or less for generated ones (k=1,2,3k = 1, 2, 3).

min⁡Dk  Ex[max⁡(0, 1−Dk(x))]+Es[max⁡(0, 1+Dk(G(s)))]\min_{D_k}\; \mathbb{E}_{x}\left[\max(0,\, 1 - D_k(x))\right] + \mathbb{E}_{s}\left[\max(0,\, 1 + D_k(G(s)))\right]

The generator minimizes the adversarial loss, which pushes up the discriminators' outputs, plus a feature matching loss LFM\mathcal{L}_{\mathrm{FM}} weighted by λ=10\lambda = 10.

min⁡G  Es[∑k=13−Dk(G(s))]+λ∑k=13LFM(G,Dk)\min_{G}\; \mathbb{E}_{s}\left[\sum_{k=1}^{3} -D_k(G(s))\right] + \lambda \sum_{k=1}^{3} \mathcal{L}_{\mathrm{FM}}(G, D_k)

Feature matching is the L1 distance between the feature maps Dk(i)D_k^{(i)} of each discriminator layer for real and generated waveforms (NiN_i is the number of units in layer ii, and TT is the number of layers).

LFM(G,Dk)=Ex,s[∑i=1T1Ni∥Dk(i)(x)−Dk(i)(G(s))∥1]\mathcal{L}_{\mathrm{FM}}(G, D_k) = \mathbb{E}_{x, s}\left[\sum_{i=1}^{T} \frac{1}{N_i} \left\| D_k^{(i)}(x) - D_k^{(i)}(G(s)) \right\|_1\right]

Feature matching is a loss that brings generated waveforms closer to real ones in the space of features the discriminator has learned to be "useful for telling real from fake." The paper regards it as a learned similarity metric. Unlike the L1 distance on raw waveforms, it does not heavily penalize waveforms that differ only by a small phase shift.

Why a GAN Can Generate Waveforms

The key to MelGAN is that it stabilizes GAN training through architectural choices tailored to the nature of audio. The paper's main techniques and the reasons they work are as follows.

TechniqueWhat it doesWhy it works
Residual stacks of dilated convolutionsPlaced after each upsampling stageReceptive fields of outputs at distant time steps overlap heavily, making long-range correlations easier to produce
Transposed convolution kernel size twice the strideChooses the shape of the upsampling layersPrevents high-frequency noise from repeating (checkerboard) patterns
Dilation as powers of the kernel size1, 3, 9 for the 3×1 convolutionsThe receptive field becomes a balanced tree that sees the input uniformly, preventing repeating patterns
Weight NormalizationApplied to every layer of the generator and discriminatorsDoes not limit discriminator capacity and does not normalize activations
Discriminators at three scalesLook at the original and downsampled waveformsDownsampled waveforms lack high frequencies, so each discriminator learns features in a different frequency band
Per-window decisionsDecide real or fake for each window the size of the receptive fieldCaptures high-frequency structure more easily, uses fewer parameters, and works on audio of different lengths
Feature matchingMatches the discriminator's intermediate features to those of real audioGives the generator a stable training signal

The choice of normalization had a large effect on quality. Instance Normalization, common in image conditional GANs, wiped out pitch information that is important in audio, producing a metallic sound. Applying Spectral Normalization to the generator also gave poor results; the paper attributes this to the strong Lipschitz constraint on the discriminator affecting the feature matching loss.

Another characteristic is that no loss in waveform space is used. Image conditional GANs sometimes add the L1 distance between the generated image and the ground truth to maintain global consistency, but in MelGAN, adding a waveform L1 distance increased audible noise and lowered quality.

The discriminators are split into three scales because audio has structure at many time scales, from fine waveform shapes to long segments such as syllables. It is like dividing art judges into "those who examine the brushwork up close" and "those who step back to see the overall composition"; each can notice different flaws.

Experimental Results

The paper mainly experiments on LJ Speech, converting mel spectrograms computed from the original audio back into waveforms. MOS was collected on Amazon Mechanical Turk from 200 English speakers wearing headphones, each rating 15 randomly selected samples on a scale of 1 to 5.

Comparison with other vocoders (LJ Speech, with 95% confidence intervals. MelGAN trained until convergence, about 2.5 million updates)

ModelMOS
Griffin-Lim1.57 ± 0.04
WaveGlow4.11 ± 0.05
WaveNet4.05 ± 0.05
MelGAN3.61 ± 0.06
Original recordings4.52 ± 0.04

Parameter count and inference speed (measured on the same hardware. GPU: GTX 1080 Ti; CPU: one core of a Core i9-7920X)

ModelParametersCPU speedGPU speed
WaveNet24.7 M0.0627 kHz0.0787 kHz
ClariNet10.0 M1.96 kHz221 kHz
WaveGlow87.9 M1.58 kHz223 kHz
MelGAN4.26 M51.9 kHz2,500 kHz

MelGAN's quality fell slightly short of WaveNet and WaveGlow, but it was more than 10 times faster than WaveGlow on GPU and more than 25 times faster on CPU.

MOS when removing each technique (LJ Speech, 500 epochs each)

ModelMOS
MelGAN (all techniques)3.09 ± 0.11
Without Weight Normalization3.03 ± 0.10
Without multi-scale discriminators (only one)2.93 ± 0.11
Without dilated convolutions2.60 ± 0.10
With waveform L1 loss added2.59 ± 0.11
Without per-window decisions2.29 ± 0.10
With Spectral Normalization1.33 ± 0.07

According to the paper, removing dilated convolutions or Weight Normalization produced high-frequency noise, and using a single discriminator produced a metallic sound, especially at breaths. With Spectral Normalization or without per-window decisions, the model struggled to learn sharp high-frequency patterns, resulting in noisy audio.

Results of other experiments are as follows.

  • Generalization to unseen speakers: Trained on internal data from 6 speakers (3 male and 3 female, about 10 hours each), it could also vocode voices of speakers not seen during training. On the public VCTK data, MelGAN scored 3.49 ± 0.09, Griffin-Lim 1.72 ± 0.07, and the original recordings 4.19 ± 0.08.
  • Text-to-speech: Combined with Text2mel (an improved version of char2wav), which produces mel spectrograms, the MOS was 3.72 ± 0.04 for Text2mel + MelGAN, 4.10 ± 0.03 for Text2mel + WaveGlow, 3.52 ± 0.04 for Tacotron 2 + WaveGlow, and 4.46 ± 0.04 for the original recordings.
  • Beyond speech: In music translation (Universal Music Translation Network), replacing the WaveNet-style autoregressive decoder with the MelGAN generator made translating 1 second of music take about 160 ms, about 2,500 times faster than the original model. The paper also tried replacing the autoregressive decoder of VQ-VAE (a model with discrete VAE latent variables).

Practical Considerations

Keep the following points in mind when using MelGAN.

  • Quality is not the best: In the paper's own comparison, MelGAN (3.61) has a lower MOS than WaveNet (4.05) and WaveGlow (4.11). The paper itself frames it as gaining speed at the cost of a slight drop in quality.
  • The choice of normalization greatly affects quality: Instance Normalization wipes out pitch information, and Spectral Normalization lowered MOS to 1.33. Use Weight Normalization, as in the paper's configuration.
  • Do not add a waveform L1 loss: Adding a waveform L1 loss out of habit from image GANs increases metallic sounds and high-frequency noise (MOS 3.09 → 2.59).
  • Not trained on predicted mel spectrograms: In the paper's text-to-speech experiments, the vocoder is trained only on mel spectrograms of real audio and applied as is to generated mel spectrograms. Retraining on predicted mel spectrograms, as in the Tacotron 2 paper, may change the results.
  • Training setup: The paper trains with a batch size of 16 using Adam with a learning rate of 10−410^{-4} for both the generator and discriminators, β1=0.5\beta_1 = 0.5, and β2=0.9\beta_2 = 0.9. It can be trained on a single GPU (RTX 2080 Ti), and the paper notes that it starts producing intelligible speech early in training.

Eq. (1) of the paper is printed in the form min⁡(0,⋅)\min(0, \cdot), but the form that makes sense as a discriminator hinge loss is max⁡(0,⋅)\max(0, \cdot). The authors' official implementation (descriptinc/melgan-neurips) also computes ReLU(1−D(x))+ReLU(1+D(G(s)))\mathrm{ReLU}(1 - D(x)) + \mathrm{ReLU}(1 + D(G(s))) with ReLU (equivalent to max⁡(0,⋅)\max(0, \cdot)). Follow the official implementation's form when implementing it.

Comparison with Other Vocoders

Comparing MelGAN with other vocoders from the same perspectives gives the following. MOS and speed are values measured under the same conditions on LJ Speech in the HiFi-GAN paper (original recordings: 4.45).

ModelGenerationTraining objectiveDiscriminatorMOSGPU generation speed (× real time)Parameters
WaveNet (MoL version)AutoregressiveMaximum likelihoodNone4.02 ± 0.08About 0.003×24.73 M
WaveGlowNormalizing flow (parallel)Maximum likelihoodNone3.81 ± 0.08About 22.75×87.73 M
MelGANGAN generator (parallel)Hinge loss + feature matchingLooks at waveforms at three scales3.79 ± 0.09About 645.73×4.26 M
HiFi-GAN V1GAN generator (parallel)Least-squares GAN loss + feature matching + mel spectrogram L1Multi-period discriminator + multi-scale discriminator4.36 ± 0.07About 167.86×13.92 M

Rough guidelines for choosing are as follows.

  • When the smallest, fastest vocoder is the priority: MelGAN is a good fit. It has the fewest parameters in the comparison above and runs faster than real time even on a CPU.
  • To improve quality: HiFi-GAN, which inherits MelGAN's ideas (a generator with upsampling and dilated convolutions, multi-scale discriminators, and feature matching) and adds a multi-period discriminator and more, is a better fit.
  • To train with likelihood: WaveNet and WaveGlow are options.

MelGAN's multi-scale discriminator and feature matching are used as is in the later HiFi-GAN.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.parametrizations import weight_norm

"""
A small implementation of the MelGAN generator, multi-scale discriminator (3 scales), and losses, following Table 6 and Eqs. (1)–(4) of the paper.
PyTorch has no built-in MelGAN (the authors' official implementation is descriptinc/melgan-neurips on GitHub).
Note: in the official implementation, the second convolution of the residual block is 1×1 and the shortcut also has a 1×1 convolution. Here we follow Figure 4 of the paper.
"""

def WNConv(*args, **kw):
    return weight_norm(nn.Conv1d(*args, **kw))


class ResidualBlock(nn.Module):
    def __init__(self, ch, dilation):
        super().__init__()
        self.block = nn.Sequential(
            nn.LeakyReLU(0.2), WNConv(ch, ch, 3, dilation=dilation, padding=dilation),
            nn.LeakyReLU(0.2), WNConv(ch, ch, 3, padding=1),
        )

    def forward(self, x):
        return x + self.block(x)


class Generator(nn.Module):
    def __init__(self, n_mels=80, ratios=(8, 8, 2, 2), ch=512):
        super().__init__()
        layers = [WNConv(n_mels, ch, 7, padding=3)]
        for r in ratios:
            layers += [
                nn.LeakyReLU(0.2),
                # kernel size = 2 × stride to prevent checkerboard artifacts
                weight_norm(nn.ConvTranspose1d(ch, ch // 2, 2 * r, stride=r, padding=r // 2)),
            ]
            ch //= 2
            layers += [ResidualBlock(ch, d) for d in (1, 3, 9)]   # residual stack (receptive field 27)
        layers += [nn.LeakyReLU(0.2), WNConv(ch, 1, 7, padding=3), nn.Tanh()]
        self.net = nn.Sequential(*layers)

    def forward(self, mel):              # [B, n_mels, frames] → [B, 1, frames × 256]
        return self.net(mel)             # no noise input


class DiscriminatorBlock(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.ModuleList([
            nn.Sequential(WNConv(1, 16, 15, padding=7), nn.LeakyReLU(0.2)),
            nn.Sequential(WNConv(16, 64, 41, stride=4, padding=20, groups=4), nn.LeakyReLU(0.2)),
            nn.Sequential(WNConv(64, 256, 41, stride=4, padding=20, groups=16), nn.LeakyReLU(0.2)),
            nn.Sequential(WNConv(256, 1024, 41, stride=4, padding=20, groups=64), nn.LeakyReLU(0.2)),
            nn.Sequential(WNConv(1024, 1024, 41, stride=4, padding=20, groups=256), nn.LeakyReLU(0.2)),
            nn.Sequential(WNConv(1024, 1024, 5, padding=2), nn.LeakyReLU(0.2)),
            WNConv(1024, 1, 3, padding=1),        # per-window decision
        ])

    def forward(self, x):
        feats = []
        for layer in self.layers:
            x = layer(x)
            feats.append(x)
        return feats                              # last element is the decision, the rest are feature maps


class MultiScaleDiscriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.blocks = nn.ModuleList(DiscriminatorBlock() for _ in range(3))
        self.pool = nn.AvgPool1d(4, stride=2, padding=1, count_include_pad=False)

    def forward(self, x):
        outs = []
        for block in self.blocks:                 # D1: original waveform, D2: 1/2, D3: 1/4
            outs.append(block(x))
            x = self.pool(x)
        return outs


G, D = Generator(), MultiScaleDiscriminator()
opt_g = torch.optim.Adam(G.parameters(), lr=1e-4, betas=(0.5, 0.9))
opt_d = torch.optim.Adam(D.parameters(), lr=1e-4, betas=(0.5, 0.9))

mel = torch.randn(4, 80, 32)                     # [batch, 80, frames]
real = torch.rand(4, 1, 32 * 256) * 2 - 1        # corresponding real waveform

# discriminator update: hinge loss (Eq. 1, written with ReLU as in the official implementation)
fake = G(mel)
loss_d = sum(F.relu(1 - r[-1]).mean() + F.relu(1 + f[-1]).mean()
             for r, f in zip(D(real), D(fake.detach())))
opt_d.zero_grad(); loss_d.backward(); opt_d.step()

# generator update: adversarial loss + 10 × feature matching (Eq. 4)
d_real, d_fake = D(real), D(fake)
loss_adv = sum(-f[-1].mean() for f in d_fake)
loss_fm = sum(F.l1_loss(ff, rf.detach())       # the mean in l1_loss corresponds to 1/N_i
              for r, f in zip(d_real, d_fake) for rf, ff in zip(r[:-1], f[:-1]))
loss_g = loss_adv + 10 * loss_fm
opt_g.zero_grad(); loss_g.backward(); opt_g.step()

FAQ

Q. Why doesn't the MelGAN generator take noise as input?
A.

Because in the paper's experiments, adding noise made almost no perceptible difference to the generated waveforms. Since a mel spectrogram is a compressed representation of a waveform, many waveforms should correspond to one mel spectrogram, but the paper says this is consistent with findings in image research that noise is unimportant when the conditioning information is strong.

Q. Why are the discriminators split into three scales?
A.

Because audio has structure at various time scales. Waveforms downsampled to 1/2 and 1/4 lack high-frequency components, so their discriminators learn to discriminate using low-frequency features. In the paper's experiments, using a single discriminator lowered MOS from 3.09 to 2.93 and produced a metallic sound, especially at breaths.

Q. How do MelGAN and HiFi-GAN differ?
A.

HiFi-GAN inherits MelGAN's multi-scale discriminator and feature matching, and adds a discriminator that looks at the periodic structure of waveforms, a mel spectrogram L1 loss, and a generator with parallel residual blocks of different receptive fields. In the HiFi-GAN paper's comparison, MOS is 3.79 for MelGAN and 4.36 for HiFi-GAN V1, a large improvement in quality.

References

  1. Kumar, K., Kumar, R., de Boissiere, T., Gestin, L., Teoh, W. Z., Sotelo, J., de Brébisson, A., Bengio, Y., & Courville, A. (2019). MelGAN: Generative Adversarial Networks for Conditional Waveform Synthesis. NeurIPS 2019. arXiv:1910.06711.
  2. descriptinc. Official MelGAN implementation (melgan-neurips).
  3. 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)
  4. PyTorch. torch.nn.utils.parametrizations.weight_norm.