AI Logic

Architectures

VITS

Updated:

The VITS architecture. The left side shows training (linear spectrogram → posterior encoder → latent variable z → a slice is cut out and turned into a waveform by the decoder, then evaluated by the discriminators and the mel L1 loss; z is passed through the normalizing flow, aligned with the distribution produced by the text encoder via monotonic alignment search, and the KL is computed; the stochastic duration predictor is trained on durations obtained from the alignment). The right side shows inference (phonemes → text encoder → the duration predictor decides lengths and the distribution is expanded → sampling → inverse flow → decoder → waveform)

Background and overview

VITS is a text-to-speech (TTS) model that learns everything from text (a phoneme sequence) to the speech waveform in a single model and generates in parallel. Kim and colleagues at Kakao Enterprise published it in 2021 (ICML 2021). The name is an acronym of Variational Inference with adversarial learning for end-to-end Text-to-Speech.

Until then, high-quality speech synthesis was split into two stages.

  1. First stage: predict a mel spectrogram from text (Tacotron 2, FastSpeech, Glow-TTS, and others).
  2. Second stage: a vocoder generates the waveform from the mel spectrogram (WaveNet, HiFi-GAN, and others).

The two-stage approach had problems: the second stage has to be retrained (fine-tuned) on the outputs of the first stage, and the system is tied to a predefined intermediate feature (the mel spectrogram). Meanwhile, existing approaches that learn from text to waveform in one go (FastSpeech 2s, EATS) had lower audio quality than two-stage systems.

VITS connects the two stages through the latent variables of a VAE and trains them jointly. To increase expressiveness, it adds normalizing flows to the prior and adversarial training on the waveform. It also proposes a stochastic duration predictor to model the "one-to-many" relationship in which the same sentence is spoken at different speeds and pitches by different people and from one reading to the next.

Its MOS on LJ Speech was 4.43, nearly the same as the original recordings (4.46). It surpassed Glow-TTS (4.32) and Tacotron 2 (4.25) combined with a fine-tuned HiFi-GAN, and its generation was about 2.4 times faster than Glow-TTS + HiFi-GAN.

Architecture

VITS consists of five parts: a posterior encoder, a prior encoder, a decoder, discriminators, and a stochastic duration predictor. The posterior encoder and the discriminators are used only during training. In the figure at the top of the article, the left side shows the flow during training and the right side the flow during inference.

First, consider the objective as a conditional VAE. The probability pθ(x∣c)p_\theta(x \mid c) of generating speech xx given a condition cc (the text) cannot be computed directly, so its lower bound (ELBO) is maximized.

log⁡pθ(x∣c)≥Eqϕ(z∣x)[log⁡pθ(x∣z)−log⁡qϕ(z∣x)pθ(z∣c)]\log p_\theta(x \mid c) \ge \mathbb{E}_{q_\phi(z \mid x)}\left[\log p_\theta(x \mid z) - \log \frac{q_\phi(z \mid x)}{p_\theta(z \mid c)}\right]

zz is the latent variable, qϕ(z∣x)q_\phi(z \mid x) is the posterior that estimates zz from speech, and pθ(z∣c)p_\theta(z \mid c) is the prior determined by the text. The loss is this lower bound with the sign flipped, and it is the sum of a reconstruction loss and a KL divergence.

The reconstruction loss is measured not on the waveform but as the L1 distance between 80-band mel spectrograms. The waveform y^\hat{y} produced by the decoder from zz is converted into a mel spectrogram x^mel\hat{x}_{\mathrm{mel}} and compared with the ground truth xmelx_{\mathrm{mel}}. Measuring on a scale close to human hearing improves perceived audio quality.

Lrecon=∥xmel−x^mel∥1L_{\mathrm{recon}} = \left\| x_{\mathrm{mel}} - \hat{x}_{\mathrm{mel}} \right\|_1

The KL divergence is the difference between the posterior and the prior. The posterior encoder takes the linear spectrogram xlinx_{\mathrm{lin}}, which has higher resolution than a mel spectrogram. The prior is conditioned on the phonemes ctextc_{\mathrm{text}} and the correspondence (alignment) AA between phonemes and latent variables.

Lkl=log⁡qϕ(z∣xlin)−log⁡pθ(z∣ctext,A),z∼qϕ(z∣xlin)=N(z;μϕ(xlin),σϕ(xlin))L_{\mathrm{kl}} = \log q_\phi(z \mid x_{\mathrm{lin}}) - \log p_\theta(z \mid c_{\mathrm{text}}, A), \qquad z \sim q_\phi(z \mid x_{\mathrm{lin}}) = N(z; \mu_\phi(x_{\mathrm{lin}}), \sigma_\phi(x_{\mathrm{lin}}))

To make the prior more expressive, a normalizing flow fθf_\theta (an invertible transformation) is stacked on a simple normal distribution.

pθ(z∣c)=N(fθ(z);μθ(c),σθ(c))∣det⁡∂fθ(z)∂z∣,c=[ctext,A]p_\theta(z \mid c) = N(f_\theta(z); \mu_\theta(c), \sigma_\theta(c)) \left| \det \frac{\partial f_\theta(z)}{\partial z} \right|, \qquad c = [c_{\mathrm{text}}, A]

To estimate the alignment, VITS uses the monotonic alignment search (MAS) of Glow-TTS. Since people read text in order without skipping, the alignment is restricted to ones that are "monotonic and non-skipping". Among these, dynamic programming finds the alignment that maximizes the log-likelihood of fθ(z)f_\theta(z) under the prior.

A=arg⁡max⁡A^log⁡N(fθ(z);μθ(ctext,A^),σθ(ctext,A^))A = \arg\max_{\hat{A}} \log N(f_\theta(z); \mu_\theta(c_{\mathrm{text}}, \hat{A}), \sigma_\theta(c_{\mathrm{text}}, \hat{A}))

The stochastic duration predictor is a flow-based generative model that learns the distribution of how many frames each phoneme lasts (its duration), di=∑jAi,jd_i = \sum_j A_{i,j}. Durations are integers and one-dimensional, so a flow cannot handle them as is. It therefore uses variational dequantization (drawing a value uu in [0,1)[0, 1) to make them continuous) and variational data augmentation (concatenating another variable ν\nu to add dimensions), and maximizes a lower bound on the log-likelihood of the durations.

log⁡pθ(d∣ctext)≥Eqϕ(u,ν∣d,ctext)[log⁡pθ(d−u,ν∣ctext)qϕ(u,ν∣d,ctext)]\log p_\theta(d \mid c_{\mathrm{text}}) \ge \mathbb{E}_{q_\phi(u, \nu \mid d, c_{\mathrm{text}})}\left[\log \frac{p_\theta(d - u, \nu \mid c_{\mathrm{text}})}{q_\phi(u, \nu \mid d, c_{\mathrm{text}})}\right]

This lower bound with the sign flipped is LdurL_{\mathrm{dur}}. So that training the duration predictor does not affect the other parts, a stop-gradient operation is applied to its input. At inference, durations are produced by inverting noise through the flow and rounded to integers.

In adversarial training, discriminators DD learn to distinguish the output of the decoder GG from the ground-truth waveform yy. The losses are the least-squares GAN loss and a feature matching loss (TT is the number of discriminator layers, and NlN_l is the number of features in layer ll).

Ladv(D)=E(y,z)[(D(y)−1)2+(D(G(z)))2],Ladv(G)=Ez[(D(G(z))−1)2]L_{\mathrm{adv}}(D) = \mathbb{E}_{(y, z)}\left[(D(y) - 1)^2 + (D(G(z)))^2\right], \qquad L_{\mathrm{adv}}(G) = \mathbb{E}_z\left[(D(G(z)) - 1)^2\right] Lfm(G)=E(y,z)[∑l=1T1Nl∥Dl(y)−Dl(G(z))∥1]L_{\mathrm{fm}}(G) = \mathbb{E}_{(y, z)}\left[\sum_{l=1}^{T} \frac{1}{N_l} \left\| D^l(y) - D^l(G(z)) \right\|_1\right]

The total loss is the sum of these.

Lvae=Lrecon+Lkl+Ldur+Ladv(G)+Lfm(G)L_{\mathrm{vae}} = L_{\mathrm{recon}} + L_{\mathrm{kl}} + L_{\mathrm{dur}} + L_{\mathrm{adv}}(G) + L_{\mathrm{fm}}(G)

The components are as follows.

ComponentContentsWhen used
Posterior encoder16 WaveNet residual blocks, as in WaveGlow and Glow-TTS, + a linear projection. Outputs 192-channel latent variablesTraining only
Text encoderA Transformer encoder with relative position representations + a linear projection (mean and variance)Training and inference
Normalizing flow4 affine coupling layers (each with 4 WaveNet residual blocks). A volume-preserving transformation (Jacobian determinant of 1)Training and inference (inverted at inference)
DecoderThe HiFi-GAN V1 generator (transposed convolutions and MRF)Training and inference
DiscriminatorsHiFi-GAN's multi-period discriminators plus one discriminator that looks at the raw waveform (periods 1, 2, 3, 5, 7, 11)Training only
Stochastic duration predictorResidual blocks of dilated and depthwise separable convolutions + neural spline flowsTraining and inference

To speed up training, the decoder receives not all the latent variables but only a randomly selected 32-frame segment, and the same segment is cut out of the ground-truth waveform for comparison.

Why it sounds more natural than two-stage systems

The key point of VITS is that it drops the predefined intermediate representation of the mel spectrogram and connects the two stages with learned latent variables.

In two-stage systems, the mel spectrogram predicted by the first stage is slightly blurrier than the ground-truth mel spectrogram. Since the vocoder is trained on ground truth, this mismatch degrades audio quality and requires fine-tuning. In VITS, the decoder receives latent variables produced by the posterior encoder and also pulled toward the prior. Since the decoder receives the same kind of input during training as during inference, mismatches between the stages are less likely.

The latent variables can also carry information that the text does not determine (such as fine fluctuations in pitch). At inference, that part is filled in by sampling from the prior, so the same sentence yields slightly different, natural-sounding speech each time.

As an analogy, the stochastic duration predictor is a mechanism for imitating a person whose reading changes every time they read the same script: "a bit slower here, faster there". Approaches that predict a single fixed duration (such as Glow-TTS) produce exactly the same rhythm every time. Because VITS learns durations as a probability distribution, each sample has a slightly different rhythm.

The roles of the other techniques are as follows.

TechniqueWhat it doesWhat it helps with
Conditional VAEConnects text and speech through latent variables and trains them jointlyRemoves mismatches between stages and makes fine-tuning unnecessary
Normalizing flow in the priorTurns a simple normal distribution into a complex one with an invertible transformationHas the largest effect on audio quality. Removing it lowers the MOS from 4.50 to 2.98
Linear spectrogram inputFeeds the posterior encoder a high-resolution spectrogramMOS 0.19 higher than with a mel spectrogram input
Monotonic alignment searchFinds the alignment between phonemes and latent variables that maximizes the likelihoodLearns the alignment without an external aligner or teacher model
Stochastic duration predictorLearns the distribution of durations and samples from itAdds variation to speaking rate and rhythm, making speech more natural
Adversarial trainingDiscriminators judge how real the waveform looksProduces fine waveform detail with high audio quality

Experimental results

The paper experimented on single-speaker LJ Speech (13,100 clips, about 24 hours, 22 kHz) and the 109-speaker VCTK (about 44,000 clips, about 44 hours, downsampled to 22 kHz). The input phonemes were obtained by converting the text into the International Phonetic Alphabet (IPA) and interspersing blank tokens, following the Glow-TTS implementation. Training used AdamW (β1=0.8\beta_1 = 0.8, β2=0.99\beta_2 = 0.99, weight decay 0.01, an initial learning rate of 2×10−42 \times 10^{-4} multiplied by 0.9991/80.999^{1/8} every epoch) on 4 V100 GPUs with a batch of 64 per GPU, for up to 800,000 steps. The baselines were Tacotron 2 and Glow-TTS combined with HiFi-GAN, using public implementations and pretrained weights. HiFi-GAN fine-tuned for 100,000 steps on the first-stage outputs was also compared.

MOS on LJ Speech (5-point scale, 95% confidence intervals)

ModelMOS
Ground truth4.46 ± 0.06
Tacotron 2 + HiFi-GAN3.77 ± 0.08
Tacotron 2 + HiFi-GAN (fine-tuned)4.25 ± 0.07
Glow-TTS + HiFi-GAN4.14 ± 0.07
Glow-TTS + HiFi-GAN (fine-tuned)4.32 ± 0.07
VITS (deterministic duration predictor)4.39 ± 0.06
VITS4.43 ± 0.06

Even the version that predicts deterministic durations (the same predictor as Glow-TTS) outperformed the two-stage systems. Using the stochastic duration predictor raised the score further.

MOS with components removed (LJ Speech, each trained for 300,000 steps)

ModelMOS
Ground truth4.50 ± 0.06
VITS (baseline)4.50 ± 0.06
Without normalizing flow2.98 ± 0.08
Mel spectrogram fed to the posterior encoder4.31 ± 0.08

MOS with multiple speakers (VCTK)

ModelMOS
Ground truth4.38 ± 0.07
Tacotron 2 + HiFi-GAN3.14 ± 0.09
Tacotron 2 + HiFi-GAN (fine-tuned)3.19 ± 0.09
Glow-TTS + HiFi-GAN3.76 ± 0.07
Glow-TTS + HiFi-GAN (fine-tuned)3.82 ± 0.07
VITS4.38 ± 0.06

For multiple speakers, a speaker embedding is added to the posterior encoder, the flow, the decoder, and the duration predictor. VITS's MOS was 4.38, the same as the ground truth.

Generation speed (100 sentences from LJ Speech, one V100 GPU, batch size 1, end to end from phonemes to waveform)

ModelSpeed (samples per second)Multiple of real time
Glow-TTS + HiFi-GAN606.05 kHz27.48×
VITS1,480.15 kHz67.12×
VITS (deterministic duration predictor)2,005.03 kHz90.93×

Diversity of speech: generating the sentence "How much variation is there?" 100 times, Glow-TTS produced the same length every time, while VITS's lengths varied about as much as Tacotron 2's. The pitch contour (F0) also differed from one generation to the next.

Practical considerations

Keep the following points in mind when using VITS.

  • Set the sampling strength: in the paper's evaluation, the noise fed to the duration predictor has a standard deviation of 0.8, and the standard deviation of the prior is multiplied by 0.667. Larger values increase variation in the speaking style; smaller values give steadier readings.
  • Phoneme conversion is required: the input is phonemes (IPA in the paper), not characters. Prepare a text-to-phoneme converter for each language. For Japanese, train on Japanese phonemes with a corpus such as JSUT.
  • Training is heavy: the paper trained for 800,000 steps on 4 V100 GPUs. Feeding only a segment to the decoder and mixed-precision training reduce time and memory. To prevent unstable gradients under mixed precision, the paper removes the bias of the decoder's last convolution.
  • Components unused at inference: the posterior encoder and the discriminators are used only during training. Inference runs only the text encoder, the duration predictor, the flow (inverted), and the decoder.

The normalizing flow in the prior has the largest effect on VITS's audio quality. In the paper's experiments, removing the flow dropped the MOS from 4.50 to 2.98. When making the model lighter, avoid removing the flow or shrinking it too much.

Comparison with other speech synthesis models

Comparing VITS with other speech synthesis models from the same viewpoints gives the following. MOS values are from the VITS paper's evaluation on LJ Speech (ground truth: 4.46).

ModelStagesGenerationDuration and alignmentWaveform generationMOS
Tacotron 2 + HiFi-GAN (fine-tuned)2AutoregressiveAttentionHiFi-GAN4.25 ± 0.07
Glow-TTS + HiFi-GAN (fine-tuned)2Parallel (flow)MAS + deterministic duration predictionHiFi-GAN4.32 ± 0.07
VITS1Parallel (VAE + flow + GAN)MAS + stochastic duration predictionHiFi-GAN generator trained jointly4.43 ± 0.06
VALL-E2 (language model + EnCodec decoding)Autoregressive + non-autoregressiveImplicitly decided by the language modelEnCodec decoder(not evaluated on LJ Speech)

Rough guidelines for choosing are as follows.

  • Producing a fixed speaker's voice quickly with high audio quality: VITS is a good fit. It trains as a single model and runs at about 67 times real time on a GPU.
  • Swapping the front end and the vocoder independently: a two-stage system combining Tacotron 2 or FastSpeech with a vocoder such as HiFi-GAN is a good fit.
  • Imitating an unseen speaker's voice from just a few seconds of recording: a language model over speech tokens trained on large amounts of data, such as VALL-E, is a good fit.

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 parts of VITS (volume-preserving normalizing flow, monotonic alignment search, KL loss, inference flow),
following Eqs. (3)-(6) and the pseudocode in Appendix A of the paper.
PyTorch has no built-in VITS (the authors' official implementation is jaywalnut310/vits on GitHub).
The decoder and discriminators are assumed to come from the implementation in the HiFi-GAN article and are omitted here.
"""


def log_normal(x, mean, logs):
    """Compute log N(x; mean, exp(logs)) element-wise"""
    return -0.5 * math.log(2 * math.pi) - logs - 0.5 * ((x - mean) * torch.exp(-logs)) ** 2


class MeanOnlyCoupling(nn.Module):
    """Volume-preserving affine coupling layer: computes only a shift from half the channels (Jacobian determinant is 1)"""
    def __init__(self, ch=192, hidden=192):
        super().__init__()
        self.net = nn.Sequential(nn.Conv1d(ch // 2, hidden, 5, padding=2), nn.ReLU(), nn.Conv1d(hidden, ch // 2, 1))
        nn.init.zeros_(self.net[-1].weight); nn.init.zeros_(self.net[-1].bias)

    def forward(self, z, reverse=False):
        a, b = z.chunk(2, 1)
        shift = self.net(a)
        b = b - shift if reverse else b + shift
        return torch.cat([b, a], 1)                       # swap so that the next layer transforms the other half


class Flow(nn.Module):
    def __init__(self, n_layers=4, ch=192):
        super().__init__()
        self.layers = nn.ModuleList(MeanOnlyCoupling(ch) for _ in range(n_layers))

    def forward(self, z, reverse=False):
        layers = reversed(self.layers) if reverse else self.layers
        for layer in layers:
            if reverse:                                  # undo the swap, then invert
                a, b = z.chunk(2, 1)
                z = layer(torch.cat([b, a], 1), reverse=True)
            else:
                z = layer(z)
        return z


@torch.no_grad()
def monotonic_alignment_search(value):
    """MAS from Appendix A. value[i, j] = log N(f(z)_j; μ_i, σ_i). Returns the monotonic, non-skipping alignment with the maximum log-likelihood"""
    t_x, t_y = value.shape
    Q = torch.full((t_x, t_y), -float("inf"))
    for y in range(t_y):
        for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
            if y == 0:
                Q[x, 0] = value[x, 0]
            else:
                v_prev = Q[x - 1, y - 1] if x > 0 else -float("inf")
                Q[x, y] = value[x, y] + max(v_prev, Q[x, y - 1])
    path = torch.zeros(t_x, t_y)
    index = t_x - 1
    for y in range(t_y - 1, -1, -1):                     # backtrack from the end
        path[index, y] = 1
        if index != 0 and (index == y or Q[index, y - 1] < Q[index - 1, y - 1]):
            index -= 1
    return path                                          # [num_phonemes, num_frames]


# --- KL loss during training (Eqs. 3, 4, 6) ---
C, T_text, T_frame = 192, 12, 60
flow = Flow()
m_q, logs_q = torch.randn(1, C, T_frame), torch.randn(1, C, T_frame) * 0.1   # posterior encoder output (from the linear spectrogram)
m_p, logs_p = torch.randn(1, C, T_text), torch.randn(1, C, T_text) * 0.1     # text encoder + linear projection output (per phoneme)

z = m_q + torch.randn_like(m_q) * torch.exp(logs_q)      # z ~ q(z | x_lin) (reparameterization)
z_p = flow(z)                                            # f_θ(z)

# log-likelihood of each frame's f_θ(z) under each phoneme's distribution [phoneme, frame] -> find alignment A with MAS
ll = log_normal(z_p[0, :, None, :], m_p[0, :, :, None], logs_p[0, :, :, None]).sum(0)
A = monotonic_alignment_search(ll)
durations = A.sum(1)                                     # duration d_i = Σ_j A_ij (training target of the stochastic duration predictor)

m_p_exp = m_p[0] @ A                                     # expand per-phoneme distributions to the number of frames according to the alignment
logs_p_exp = logs_p[0] @ A
# L_kl = log q(z | x_lin) − log p(z | c_text, A). The flow preserves volume, so the determinant term is 0
loss_kl = (log_normal(z[0], m_q[0], logs_q[0]) - log_normal(z_p[0], m_p_exp, logs_p_exp)).sum() / T_frame
print("durations", durations.tolist(), "L_kl", float(loss_kl))

# --- inference flow (Figure 1b) ---
with torch.no_grad():
    d = torch.clamp(torch.ceil(durations), min=1).long()          # in practice, the stochastic duration predictor produces these from noise (std 0.8)
    A_inf = torch.zeros(T_text, int(d.sum()))
    A_inf[torch.repeat_interleave(torch.arange(T_text), d), torch.arange(int(d.sum()))] = 1
    m, logs = m_p[0] @ A_inf, logs_p[0] @ A_inf
    z_p = m + torch.randn_like(m) * torch.exp(logs) * 0.667       # sample with the prior's std multiplied by 0.667
    z = flow(z_p[None], reverse=True)                             # map back to z with the inverse flow
    # wave = decoder(z)  # turn into a waveform with the HiFi-GAN V1 generator
    print(z.shape)

FAQ

Q. Why can VITS be trained in a single stage?
A.

Because it connects the prior determined by the text and the posterior estimated from speech through the latent variables of a VAE. The decoder generates the waveform directly from the latent variables, so no predefined intermediate feature such as a mel spectrogram is needed. The alignment between text and speech is computed by monotonic alignment search at every training step, so no external aligner is needed either.

Q. What is the difference between VITS and Glow-TTS + HiFi-GAN?
A.

Glow-TTS + HiFi-GAN is a two-stage system in which Glow-TTS generates a mel spectrogram from text and HiFi-GAN separately turns it into a waveform. VITS adopts Glow-TTS's monotonic alignment search and flow and HiFi-GAN's generator and discriminators, and trains them jointly as a single model. It also predicts durations stochastically. In the paper's evaluation on LJ Speech, the MOS was 4.32 (Glow-TTS combined with a fine-tuned HiFi-GAN) versus 4.43.

Q. If the same sentence is synthesized repeatedly, does the speech differ each time?
A.

Yes. The noise fed to the duration predictor and the sampling from the prior make the speaking rate and pitch vary slightly. The paper's evaluation uses a noise standard deviation of 0.8 and multiplies the standard deviation of the prior by 0.667. Making these smaller reduces the differences between runs.

References

  1. Kim, J., Kong, J., & Son, J. (2021). Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech. ICML 2021 (PMLR 139). arXiv:2106.06103.
  2. jaywalnut310. Official implementation of VITS.
  3. VITS audio samples (by the paper's authors)
  4. Kim, J., Kim, S., Kong, J., & Yoon, S. (2020). Glow-TTS: A Generative Flow for Text-to-Speech via Monotonic Alignment Search. arXiv:2005.11129.
  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.