AI Logic

Architectures

HiFi-GAN

Updated:

Architecture of HiFi-GAN. The left shows generator V1 (mel spectrogram → convolution → upsampling by 8, 8, 2, and 2 with transposed convolutions, each followed by an MRF → convolution and tanh → waveform). The center shows the inside of the MRF (residual blocks of width 3, 7, and 11 in parallel, summed; each block stacks three residual connections of a convolution with dilation 1, 3, or 5 followed by a convolution with dilation 1). The right shows the discriminators (multi-period discriminators that reshape the waveform into 2D by period p, and multi-scale discriminators that look at 3 scales via average pooling; the least-squares loss, feature matching, and mel spectrogram loss are computed from the feature maps and outputs)

Background and overview

HiFi-GAN is a GAN vocoder that produces speech waveforms from mel spectrograms and, by adding a discriminator that looks at periodic patterns in the waveform, achieves both near-human audio quality and high speed. It was presented by Kong et al. at Kakao Enterprise in 2020 (NeurIPS 2020).

Vocoder research faced a trade-off between audio quality and speed.

  • WaveNet: high quality, but very slow because it generates one sample at a time.
  • WaveGlow: generates in parallel, but has a deep architecture of more than 90 layers and many parameters.
  • GAN vocoders such as MelGAN (GAN): small and fast, but a quality gap remained compared with autoregressive and flow models.

The key insight of HiFi-GAN is that speech consists of sinusoids with various periods, so capturing these periodic patterns is the key to audio quality. The authors therefore designed a discriminator that looks at the waveform at fixed intervals (MPD), and also put into the generator a module that captures patterns of different lengths in parallel (MRF).

On LJ Speech, the largest version, V1, reached an MOS of 4.36, only 0.09 below the original recordings (4.45). In the same evaluation, WaveNet scored 4.02, WaveGlow 3.81, and MelGAN 3.79. V1 generates 22.05 kHz speech 167.9 times faster than real time on a single V100 GPU, and the smallest version has only 0.92 M parameters.

Architecture

HiFi-GAN consists of one generator and two kinds of discriminators: the multi-period discriminator (MPD) and the multi-scale discriminator (MSD). In the figure at the top of the article, the left is the generator, the center is the inside of the generator's MRF, and the right is the discriminators.

The generator is a fully convolutional network.

  1. Input: an 80-band mel spectrogram is taken in by a convolution. As in MelGAN, no noise is input.
  2. Upsampling: transposed convolutions upsample the sequence until its length matches the temporal resolution of the waveform. V1 has 4 stages with kernel sizes 16, 16, 4, and 4.
  3. MRF: an MRF module is placed after each transposed convolution.
  4. Output: a final convolution and tanh produce the waveform.

The MRF (multi-receptive field fusion) is a module that places residual blocks with different kernel sizes and dilation rates in parallel and returns the sum of their outputs. V1 places 3 residual blocks with kernel sizes 3, 7, and 11 in parallel. Each residual block stacks, three times with d=1,3,5d = 1, 3, 5, the sequence Leaky ReLU → convolution with dilation dd → Leaky ReLU → convolution with dilation 1, with the input added back. Because blocks with different receptive fields run in parallel, patterns of various lengths can be captured at the same time.

The paper compares three versions of the generator with different sizes. The discriminators are the same for all three.

VersionHidden dimension huh_uTransposed conv kernels kuk_uMRF kernels krk_rDilation rates DrD_r
V151216, 16, 4, 43, 7, 11[[1, 1], [3, 1], [5, 1]] in each block
V212816, 16, 4, 43, 7, 11Same as V1
V325616, 16, 83, 5, 7[[1], [2]], [[2], [6]], [[3], [12]]

V2 keeps the same receptive field as V1 and only shrinks the hidden dimension. V3 reselects the kernel sizes and dilation rates to reduce the number of layers while keeping a wide receptive field.

The multi-period discriminator (MPD) is a collection of 5 small discriminators, each looking at the input waveform at a fixed interval pp. To avoid overlap as much as possible, the periods are the primes p=2,3,5,7,11p = 2, 3, 5, 7, 11.

  1. Reshape the 1D waveform of length TT into 2D with height T/pT/p and width pp. Each column contains samples spaced pp samples apart.
  2. Apply 2D convolutions with a kernel size of 1 along the width, processing each column (the sequence of samples for each phase of the period) separately.
  3. Stack strided convolutions and Leaky ReLU, and apply Weight Normalization.

Because the samples are reshaped rather than subsampled, the gradient from the discriminator reaches every time step of the input waveform.

The multi-scale discriminator (MSD) follows the same idea as MelGAN's discriminator: 3 discriminators that look at the raw waveform and the waveform average-pooled by 2 and by 4. Whereas the MPD looks at disjoint samples, the MSD looks at the smoothed, contiguous waveform, capturing continuous patterns and long-range dependencies. Compared with MelGAN, it uses smaller strides and more layers, making it larger. Only the discriminator on the raw waveform uses Spectral Normalization instead of Weight Normalization to stabilize training.

There are three losses. Let xx be the ground-truth waveform and ss its mel spectrogram.

  • Adversarial loss: the least-squares GAN (LSGAN) loss is used. The discriminator learns to output 1 for real and 0 for generated waveforms, and the generator learns to make the discriminator output 1.
LAdv(D;G)=E(x,s)[(D(x)−1)2+(D(G(s)))2],LAdv(G;D)=Es[(D(G(s))−1)2]\mathcal{L}_{\mathrm{Adv}}(D; G) = \mathbb{E}_{(x, s)}\left[(D(x) - 1)^2 + (D(G(s)))^2\right], \qquad \mathcal{L}_{\mathrm{Adv}}(G; D) = \mathbb{E}_{s}\left[(D(G(s)) - 1)^2\right]
  • Mel spectrogram loss: the L1 distance between the mel spectrograms of the generated and ground-truth waveforms (ϕ\phi is the function that turns a waveform into a mel spectrogram).
LMel(G)=E(x,s)[∥ϕ(x)−ϕ(G(s))∥1]\mathcal{L}_{\mathrm{Mel}}(G) = \mathbb{E}_{(x, s)}\left[\left\| \phi(x) - \phi(G(s)) \right\|_1\right]
  • Feature matching loss: as in MelGAN, the L1 distance between the features at each discriminator layer (TT is the number of layers, and DiD_i and NiN_i are the features of the ii-th layer and their number).
LFM(G;D)=E(x,s)[∑i=1T1Ni∥Di(x)−Di(G(s))∥1]\mathcal{L}_{\mathrm{FM}}(G; D) = \mathbb{E}_{(x, s)}\left[\sum_{i=1}^{T} \frac{1}{N_i} \left\| D_i(x) - D_i(G(s)) \right\|_1\right]

Writing the MPD and MSD discriminators together as D1,…,DKD_1, \dots, D_K, the generator and discriminator losses are as follows (λfm=2\lambda_{fm} = 2, λmel=45\lambda_{mel} = 45).

LG=∑k=1K[LAdv(G;Dk)+λfm LFM(G;Dk)]+λmel LMel(G),LD=∑k=1KLAdv(Dk;G)\mathcal{L}_G = \sum_{k=1}^{K}\left[\mathcal{L}_{\mathrm{Adv}}(G; D_k) + \lambda_{fm}\, \mathcal{L}_{\mathrm{FM}}(G; D_k)\right] + \lambda_{mel}\, \mathcal{L}_{\mathrm{Mel}}(G), \qquad \mathcal{L}_D = \sum_{k=1}^{K} \mathcal{L}_{\mathrm{Adv}}(D_k; G)

Why looking at periods improves quality

The essence of HiFi-GAN is that it lets the discriminator capture the periodic structure of speech.

Voiced sounds in human speech, such as vowels, consist of a fundamental frequency produced by vocal-fold vibration plus sinusoids at its harmonics. A phoneme can last longer than 100 ms, so in a 22 kHz waveform more than 2,200 samples are strongly correlated. Earlier work tackled this long-range dependency by enlarging the receptive fields of the generator and discriminator, but the HiFi-GAN paper argued that distinguishing patterns of various periods remained an unsolved problem.

The MPD reshapes the waveform every pp samples and looks only at the structure related to period pp. The periods are prime because periods that are multiples of each other, such as 2 and 4, would look at the same parts twice. In an experiment in the paper's appendix, on a task of spotting a tiny fraction of "fake frequencies" among sinusoids of random frequencies, MPD was far more accurate than MSD (with 0.1% fake frequencies, accuracy was 85.33% for MPD and 50.42% for MSD).

The roles of the other components are as follows.

ComponentWhat it doesWhat it helps with
MPDReshapes the waveform by period pp and judges each separatelyCatches errors in periodic patterns. Removing it drops MOS sharply
MSDJudges the raw waveform and smoothed versions of itLooks at continuous patterns and long-range dependencies
MRFPlaces residual blocks with different receptive fields in parallel and sums themLets the generator produce patterns of different lengths at the same time
Mel spectrogram lossMatches the mel spectrogram of the generated waveform to the ground truthMakes the waveform fit the input condition and stabilizes adversarial training from the start. It can also be expected to improve quality in line with human auditory perception
Feature matching lossMatches the discriminator's intermediate features to the ground truthGuides the generator as a learned similarity metric

As an analogy, the MPD's reshaping is like rewriting a long row of numbers as a table with pp columns and reading each column top to bottom. If there is a pattern that repeats with period pp, it lines up in the columns, making it easier to find. Comparing 5 tables with different periods lets the model check patterns of many periods.

Experimental results

The paper trains on LJ Speech (a single speaker, 13,100 clips, about 24 hours, 22 kHz, 16-bit) and compares models by resynthesizing waveforms from mel spectrograms of the original audio. The compared models were the publicly available MoL WaveNet and the official implementations of WaveGlow and MelGAN, all using their provided pretrained weights. MOS was collected on Amazon Mechanical Turk, and all evaluations were conducted anew within the paper.

Quality and speed (LJ Speech, 50 utterances not used for training. Speed measured on a V100 GPU and a MacBook Pro CPU, in 32-bit without optimization)

ModelMOSSpeed on CPU (× real time)Speed on GPU (× real time)Parameters
Ground truth4.45 ± 0.06−−−
WaveNet (MoL)4.02 ± 0.08−0.07 kHz (×0.003)24.73 M
WaveGlow3.81 ± 0.084.72 kHz (×0.21)501 kHz (×22.75)87.73 M
MelGAN3.79 ± 0.09145.52 kHz (×6.59)14,238 kHz (×645.73)4.26 M
HiFi-GAN V14.36 ± 0.0731.74 kHz (×1.43)3,701 kHz (×167.86)13.92 M
HiFi-GAN V24.23 ± 0.07214.97 kHz (×9.74)16,863 kHz (×764.80)0.92 M
HiFi-GAN V34.05 ± 0.08296.38 kHz (×13.44)26,169 kHz (×1,186.80)1.46 M

All three versions of HiFi-GAN achieved higher MOS than the other models. V2 reached 4.23 with 0.92 M parameters, and V3 matched the quality of MoL WaveNet while running 13.44 times faster than real time on a CPU.

MOS with each component removed (V3, each trained for 500k steps)

ModelMOS
Ground truth4.57 ± 0.04
HiFi-GAN V3 (all components)4.10 ± 0.05
Without MPD2.28 ± 0.09
Without MSD3.74 ± 0.05
Without MRF (keeping only the block with the widest receptive field in each MRF)3.92 ± 0.05
Without mel spectrogram loss3.25 ± 0.05
MPD periods set to 2, 4, 8, 16, 323.90 ± 0.05
MelGAN2.88 ± 0.08
MelGAN + MPD3.35 ± 0.07

Removing MPD dropped MOS sharply from 4.10 to 2.28, while removing MSD caused a relatively small drop (3.74). Simply adding MPD to MelGAN raised MOS by 0.47, and using powers of 2 as periods lowered it by 0.20 compared with primes.

Results of the other experiments are as follows.

  • Unseen speakers: 9 speakers from VCTK (109 speakers, about 44 hours) were held out from training and used for evaluation. MOS was 3.79 for the ground truth, 3.77 for V1, 3.69 for V2, and 3.61 for V3, higher than WaveNet (MoL) at 3.52, WaveGlow at 3.52, and MelGAN at 3.50.
  • Text-to-speech: waveforms were generated from mel spectrograms predicted by Tacotron 2. As is, V1 scored 3.91 and WaveGlow 3.69. After fine-tuning for 100k steps on mel spectrograms predicted by Tacotron 2 run with teacher forcing, V1 rose to 4.18, while WaveGlow did not improve, at 3.66 (ground truth: 4.23).

Caveats in practice

When using HiFi-GAN, keep the following points in mind.

  • Choose the version by use case: V1 suits top-priority audio quality, V2 (0.92 M) suits limited memory, and V3 suits fast execution on a CPU. Because the discriminators and training method are shared, the paper notes that the generator configuration can be chosen to fit the purpose without re-searching the discriminator hyperparameters.
  • Fine-tune when generating speech from text: mel spectrograms predicted by an upstream model are noisier than the ground truth. In the paper, fine-tuning on Tacotron 2's predictions raised MOS from 3.91 to 4.18. After fine-tuning, the error on the mel spectrogram actually increased, but the perceived audio quality improved.
  • Match preprocessing with the upstream model: the paper excluded MelGAN and WaveNet from this comparison because differences in preprocessing, such as frequency clipping, lead to low quality when combined with Tacotron 2. Match the way mel spectrograms are computed (80 bands, FFT and window length 1,024, hop 256 in the paper) with the upstream model.
  • Training settings: the paper uses AdamW with β1=0.8\beta_1 = 0.8, β2=0.99\beta_2 = 0.99, and weight decay 0.01, with an initial learning rate of 2×10−42 \times 10^{-4} decayed by a factor of 0.999 every epoch.

The MPD has the largest effect on HiFi-GAN's audio quality. In the paper's experiments, removing the MPD dropped MOS from 4.10 to 2.28. When cutting discriminators to make training lighter, do not remove the MPD before the MSD. The discriminators are used only during training and only the generator runs at inference, so making the discriminators larger does not change inference speed.

Comparison with other vocoders

Comparing HiFi-GAN with other vocoders from the same angles gives the following. MOS, speed, and parameter counts are from the LJ Speech comparison in the HiFi-GAN paper (ground truth: 4.45).

ModelGenerationTraining objectiveDiscriminatorsMOSGeneration speed on GPU (× real time)Parameters
WaveNet (MoL)AutoregressiveMaximum likelihoodNone4.02 ± 0.08About ×0.00324.73 M
WaveGlowNormalizing flow (parallel)Maximum likelihoodNone3.81 ± 0.08About ×22.7587.73 M
MelGANGAN generator (parallel)Hinge loss + feature matchingMulti-scale (MSD)3.79 ± 0.09About ×645.734.26 M
HiFi-GAN V1GAN generator (parallel)Least-squares GAN loss + feature matching + mel spectrogram L1Multi-period (MPD) + multi-scale (MSD)4.36 ± 0.07About ×167.8613.92 M
HiFi-GAN V3GAN generator (parallel)Same as V1Same as V14.05 ± 0.08About ×1,186.801.46 M

Rough guidelines for choosing are as follows.

  • To get both high quality and faster-than-real-time generation: HiFi-GAN is a good fit. It has the highest MOS in the comparison above and runs more than 100 times faster than real time on a GPU.
  • To run on a CPU or smartphone: HiFi-GAN V2 and V3, or small GAN vocoders like MelGAN, are suitable.
  • To train with likelihood and avoid adversarial training: WaveGlow and WaveNet are options.

When combining it with a text-to-speech model, the paper's approach is to fine-tune on mel spectrograms predicted by the upstream model. The later VITS paper also uses Tacotron 2 and Glow-TTS combined with HiFi-GAN as baselines (see the LJ Speech article).

PyTorch example

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

"""
A small implementation of HiFi-GAN's generator (MRF), multi-period discriminator (MPD), and losses, following Section 2 and Equations (1)-(8) of the paper.
PyTorch has no built-in HiFi-GAN (the authors' official implementation is jik876/hifi-gan on GitHub).
The multi-scale discriminator (MSD) has the same form as MelGAN's, so it is omitted and the loss computation is shown with MPD only.
"""

LRELU = 0.1

class ResBlock(nn.Module):
    """[lReLU -> conv with dilation d -> lReLU -> conv with dilation 1 -> add input] three times with d = 1, 3, 5"""
    def __init__(self, ch, k, dilations=(1, 3, 5)):
        super().__init__()
        pad = lambda d: (k * d - d) // 2
        self.c1 = nn.ModuleList(weight_norm(nn.Conv1d(ch, ch, k, dilation=d, padding=pad(d))) for d in dilations)
        self.c2 = nn.ModuleList(weight_norm(nn.Conv1d(ch, ch, k, padding=pad(1))) for _ in dilations)

    def forward(self, x):
        for c1, c2 in zip(self.c1, self.c2):
            x = x + c2(F.leaky_relu(c1(F.leaky_relu(x, LRELU)), LRELU))
        return x


class MRF(nn.Module):
    def __init__(self, ch, kernels=(3, 7, 11)):
        super().__init__()
        self.blocks = nn.ModuleList(ResBlock(ch, k) for k in kernels)

    def forward(self, x):
        return sum(b(x) for b in self.blocks)    # the paper uses a "sum"; the official implementation divides by the number of blocks to average


class Generator(nn.Module):                      # V1 configuration
    def __init__(self, n_mels=80, h=512, ks=(16, 16, 4, 4)):
        super().__init__()
        self.pre = weight_norm(nn.Conv1d(n_mels, h, 7, padding=3))
        self.ups, self.mrfs = nn.ModuleList(), nn.ModuleList()
        for i, k in enumerate(ks):
            stride = k // 2                      # x8, x8, x2, x2 (x256 in total)
            self.ups.append(weight_norm(nn.ConvTranspose1d(h // 2 ** i, h // 2 ** (i + 1), k, stride, padding=(k - stride) // 2)))
            self.mrfs.append(MRF(h // 2 ** (i + 1)))
        self.post = weight_norm(nn.Conv1d(h // 2 ** len(ks), 1, 7, padding=3))

    def forward(self, mel):                      # no noise input
        x = self.pre(mel)
        for up, mrf in zip(self.ups, self.mrfs):
            x = mrf(up(F.leaky_relu(x, LRELU)))
        return torch.tanh(self.post(F.leaky_relu(x)))


class PeriodDiscriminator(nn.Module):
    """Discriminator for period p: reshape the waveform into 2D [T/p, p] and look at each column with convs of width 1"""
    def __init__(self, p):
        super().__init__()
        self.p = p
        chs = [1, 32, 128, 512, 1024]
        self.convs = nn.ModuleList(
            weight_norm(nn.Conv2d(chs[i], chs[i + 1], (5, 1), (3, 1), padding=(2, 0))) for i in range(4)
        )
        self.convs.append(weight_norm(nn.Conv2d(1024, 1024, (5, 1), padding=(2, 0))))
        self.post = weight_norm(nn.Conv2d(1024, 1, (3, 1), padding=(1, 0)))

    def forward(self, x):                        # x: [B, 1, T]
        B, C, T = x.shape
        if T % self.p:
            x = F.pad(x, (0, self.p - T % self.p), mode="reflect")
        x = x.view(B, C, -1, self.p)             # reshaped rather than subsampled, so gradients reach every time step
        feats = []
        for conv in self.convs:
            x = F.leaky_relu(conv(x), LRELU)
            feats.append(x)
        x = self.post(x)
        feats.append(x)
        return x.flatten(1), feats


mpd = nn.ModuleList(PeriodDiscriminator(p) for p in (2, 3, 5, 7, 11))   # prime periods
G = Generator()
to_mel = torchaudio.transforms.MelSpectrogram(sample_rate=22050, n_fft=1024, win_length=1024, hop_length=256, n_mels=80)
opt_g = torch.optim.AdamW(G.parameters(), lr=2e-4, betas=(0.8, 0.99), weight_decay=0.01)
opt_d = torch.optim.AdamW(mpd.parameters(), lr=2e-4, betas=(0.8, 0.99), weight_decay=0.01)

real = torch.rand(2, 1, 8192) * 2 - 1           # a segment of the ground-truth waveform
mel = torch.log(to_mel(real.squeeze(1)).clamp(min=1e-5))[:, :, :32]   # conditioning mel spectrogram (32 frames)
fake = G(mel)                                    # [2, 1, 8192]

# Discriminator: least-squares loss (Equations 1 and 8)
loss_d = sum(((1 - d(real)[0]) ** 2).mean() + (d(fake.detach())[0] ** 2).mean() for d in mpd)
opt_d.zero_grad(); loss_d.backward(); opt_d.step()

# Generator: adversarial loss + 2 x feature matching + 45 x mel spectrogram L1 (Equation 7)
loss_adv, loss_fm = 0, 0
for d in mpd:
    out_f, feat_f = d(fake)
    _, feat_r = d(real)
    loss_adv = loss_adv + ((out_f - 1) ** 2).mean()
    loss_fm = loss_fm + sum(F.l1_loss(f, r.detach()) for f, r in zip(feat_f, feat_r))
mel_fake = torch.log(to_mel(fake.squeeze(1)).clamp(min=1e-5))[:, :, :32]
loss_mel = F.l1_loss(mel_fake, mel)
loss_g = loss_adv + 2 * loss_fm + 45 * loss_mel
opt_g.zero_grad(); loss_g.backward(); opt_g.step()

# At inference only the generator is used (the discriminators are for training only)
G.eval()
with torch.no_grad():
    wave = G(mel)

FAQ

Q. Why does HiFi-GAN's MPD use prime periods?
A.

To avoid overlap between periods as much as possible and distinguish as many periods as possible. For example, with 2 and 4, the samples lined up with period 4 are also contained in the columns for period 2. In the paper's experiments, changing the periods from 2, 3, 5, 7, 11 to 2, 4, 8, 16, 32 lowered MOS from 4.10 to 3.90.

Q. What is the difference between HiFi-GAN and MelGAN?
A.

There are three main differences.

  • Discriminators: adds the multi-period discriminator (MPD) to MelGAN's multi-scale discriminator (MSD)
  • Generator: uses the MRF, with parallel residual blocks of different receptive fields, instead of residual stacks
  • Losses: uses the least-squares GAN loss instead of the hinge loss, and adds the mel spectrogram L1 loss

In the HiFi-GAN paper's comparison, MOS was 3.79 for MelGAN and 4.36 for HiFi-GAN V1. Simply adding the MPD to MelGAN raised MOS by 0.47.

Q. How do I choose between V1, V2, and V3?
A.

Choose V1 (MOS 4.36, 13.92 M) if audio quality comes first, V2 (4.23, 0.92 M) if you want high quality with low memory, and V3 (4.05, 13.44 times faster than real time on a CPU) if you want fast execution on a CPU. The three differ only in the generator; the discriminators and training method are the same, so they can be trained with the same procedure.

References

  1. Kong, J., Kim, J., & Bae, J. (2020). HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis. NeurIPS 2020. arXiv:2010.05646.
  2. jik876. Official implementation of HiFi-GAN.
  3. HiFi-GAN audio samples (by the paper's authors)
  4. Kumar, K., et al. (2019). MelGAN: Generative Adversarial Networks for Conditional Waveform Synthesis. NeurIPS 2019. arXiv:1910.06711.
  5. Mao, X., Li, Q., Xie, H., Lau, R. Y. K., Wang, Z., & Smolley, S. P. (2017). Least Squares Generative Adversarial Networks. ICCV 2017. arXiv:1611.04076.