Modelresearch
VITS
Also called variational inference text-to-speech.
End-to-end TTS that joins a conditional VAE, a normalizing flow and adversarial training, and finds durations by monotonic alignment search.
VITS is a text-to-speech model that goes from a phoneme sequence straight to a waveform in one network, trained end to end. It is a variational autoencoder whose latent variable is a sequence of frames. A posterior encoder reads the linear spectrogram of the training audio and gives . A decoder, the HiFi-GAN generator, turns back into a waveform and is trained with a discriminator. A prior encoder reads the text and gives a normal distribution for each phoneme; a normalizing flow makes the prior more flexible. The link between phonemes and frames is not known, so during training the model finds it with monotonic alignment search, a Viterbi style dynamic program from Glow-TTS. A separate duration predictor learns the frame counts that this search finds, and at synthesis time it replaces the search.
The machine
Sizes: phonemes, latent frames, latent channels (192 in the paper), linear spectrogram bins, hop samples per frame, and a waveform of samples. Shapes are written for one utterance.
Posterior encoder. The linear spectrogram of shape (FFT size 1024, hop 256) goes through 16 non-causal WaveNet style residual blocks and gives a mean and a log standard deviation of shape . A sample is , with standard normal of shape , so is a diagonal normal.
Decoder. The HiFi-GAN V1 generator maps of shape to a waveform of samples. To save memory it is trained on random windows of 32 frames of and the matching stretch of audio, not on the whole utterance.
Prior encoder. A transformer encoder with relative positions reads the phonemes , with a blank token between each pair of phonemes, and gives and of shape . An invertible flow of affine coupling layers, of shape to with Jacobian determinant 1, maps to . With an alignment that sends frame to phoneme , the prior density is
where repeats row for frame .
Monotonic alignment search. An alignment is monotonic and onto: , and . With , a matrix of shape , the search picks the alignment of largest . It is a dynamic program in the Viterbi semiring (max, +):
MONOTONIC-ALIGNMENT-SEARCH(v) // v has n rows (phonemes) and T columns (frames), T >= n- 1
Q[i, j] <- -inf for all i, j - 2
Q[0, 0] <- v[0, 0] - 3
for j <- 1 to T - 1 do - 4
for i <- 0 to min(j, n - 1) do - 5
Q[i, j] <- v[i, j] + max(Q[i, j - 1], Q[i - 1, j - 1]) // Q[-1, .] = -inf - 6
i <- n - 1 - 7
for j <- T - 1 down to 0 do - 8
a(j) <- i - 9
if j > 0 and i > 0 and Q[i - 1, j - 1] > Q[i, j - 1] then - 10
i <- i - 1 - 11
return a, Q[n - 1, T - 1]
The search runs with no gradient. The network is trained for the alignment it returns, and the alignment changes as the prior improves.
Duration predictor. The durations are the targets of a stochastic duration predictor, itself a small flow trained by a variational bound. At synthesis time it samples durations, the rows of and are repeated by them, a sample from that normal goes through , and the decoder makes the waveform.
Training loss. The loss is the negative evidence lower bound plus adversarial terms:
is the L1 distance between the mel spectrograms of the target and of the generated waveform. at the sampled . is the bound of the duration predictor. The adversarial and feature matching terms use the multi-period discriminator of HiFi-GAN with the least squares loss, plus the first sub-discriminator of its multi-scale discriminator, the one on the raw waveform.
Standing assumptions. A fixed phoneme set and a single speaker, or a speaker embedding for many speakers; a monotonic alignment in which every phoneme gets at least one frame; and training pairs of text and audio with no hand-made alignment.
What it counts
The model defines a distribution over waveforms given the text. Training maximizes a lower bound on for the mel target, with the alignment fixed to the result of the search at each step, plus the adversarial terms.
- Alignment search. Lines L3 to L5 fill cells, each in constant time, and the traceback takes steps. The search runs once for each training utterance at each step.
- Count of alignments. There are monotonic alignments, one for each choice of the frames where a new phoneme starts. With and there are 10. The search finds the best of them without listing them.
- Synthesis. All steps run in parallel over frames and samples: one pass of the text encoder, the duration predictor, the inverse flow and the generator. There is no step-by-step loop over frames as in Tacotron, so the cost grows linearly with the length of the audio.
Example. Take and with
| 1 | 2 | 3 | 4 | 5 | ||
|---|---|---|---|---|---|---|
The table is, row by row: ; ; . For example . The traceback from stays on phoneme 2 at frame 4, because is larger than , and moves down at frames 3 and 1. The alignment is with score , and the durations are . The test file checks this example and compares the search with all alignments.
The code with this page takes the score matrix as given and implements monotonic alignment search, its tie rule and the Gaussian scores; it does not train a network.
Relation to other models
- Glow-TTS (Kim, Kim, Kong and Yoon 2020) is the parent: a flow from mel frames to a text-conditioned normal prior, trained by exact likelihood with monotonic alignment search. VITS keeps the prior and the search, makes the latent variable a VAE latent, and adds the waveform decoder.
- HiFi-GAN gives the decoder and the discriminator. In a two-stage system the vocoder is trained on mel spectrograms; in VITS it is trained jointly on the latent .
- FastSpeech also expands phoneme states by durations, but takes the durations from a teacher model or an external aligner. VITS finds them during training with its own search.
- Tacotron learns a soft attention alignment and generates frames one by one; it can skip or repeat words when the attention fails. The monotonic alignment of VITS cannot skip a phoneme by construction.
- Forced alignment and dynamic time warping solve the same kind of monotonic alignment problem with an HMM or a frame distance in place of the flow prior.
Known results in the model
- Exactness of the search (theorem). Monotonic alignment search returns an alignment of largest total log-likelihood among all monotonic alignments, in time. The proof is the usual principle of optimality for a path in a grid; it is in the proofs folder of this page, with the tie rule.
- Training is a bound (theorem). For a fixed alignment, is, up to constants and the weight of the reconstruction term, the evidence lower bound , estimated with one sample. Maximizing the bound over the alignment is what the search does for the prior term.
- Quality on LJ Speech (measurement). The paper reports a mean opinion score of 4.43 ± 0.06 for VITS on the LJ Speech data set, on a 1 to 5 scale with crowd-sourced raters, against 4.46 ± 0.06 for the recordings. In the same test, Tacotron 2 with a fine-tuned HiFi-GAN vocoder has 4.25 ± 0.07 and Glow-TTS with a fine-tuned HiFi-GAN has 4.32 ± 0.07.
- Speed (measurement). On one V100 GPU with a batch of 1, VITS generates about 67 times faster than real time, against about 27 times for Glow-TTS with HiFi-GAN.
- Variety (measurement). Because the duration predictor is stochastic, the same text gives different lengths on different samples. Over 100 samples of one sentence, the spread of lengths of VITS is close to that of Tacotron 2, while Glow-TTS always gives the same length.
Proof: Monotonic alignment search returns a monotonic alignment of largest total score, chosen by the tie rulefull
Fix tokens, frames and real scores for and . An alignment is a map from frames to tokens with , and . Its score is . The work is in the Viterbi semiring .
Count
An alignment is fixed by the frames where . Any of the frames give one, and different sets give different alignments. So there are alignments.
The table
A partial alignment ending at is a map on the frames with , steps in and .
Lemma 1. After lines L1 to L5, is the largest score of a partial alignment ending at , and if there is none.
Proof. By induction on . For the only partial alignment is , and lines L1 and L2 set and for . For , a partial alignment ending at is a partial alignment ending at or at followed by the frame on token , and each such extension is allowed. Its score is the score of the prefix plus . Adding a constant keeps the order, so the best one is plus the larger of the two best prefix scores, which line L5 computes from the induction hypothesis. For there is no partial alignment, because the token index grows by at most one per frame; line L4 skips these cells and they stay .
Lemma 2. If is finite and , the predecessor chosen by line L9 has a finite value with .
Proof. Line L9 moves to only when , and otherwise stays on . In both cases it takes a maximum of the two values of line L5. That maximum is finite because is finite. When only the stay predecessor exists, and when the stay value is , so the strict test moves down.
Theorem 1. Lines L6 to L11 return an alignment with , and that score.
Proof. A full alignment is a partial alignment ending at , so by Lemma 1 the maximum is , which is finite because . The traceback starts there. By Lemma 2 each step goes to a finite cell whose value is the current value minus the current score, so after steps it reaches a finite cell of frame 0, which is , and the scores of the visited cells sum to . The steps are or in the token index, so is an alignment.
Theorem 2 (tie rule). Among the alignments of largest score, the returned one is the largest in the lexicographic order of .
Proof. All optimal alignments have . Assume the returned agrees with the largest optimal sequence on the frames , with . The optimal alignments with this suffix are exactly those whose prefix is an optimal partial alignment ending at . By Lemma 1 such a prefix can take exactly when , that is when . Line L9 stays on exactly in that case, so it picks the larger of the possible values of . Induction down to gives the claim.
The tests compare the result, ties included, with the best of all alignments under this order, for and .
Cost
Line L5 runs once for each cell with and , which is cells for , each in constant time. The table takes space, and the traceback takes steps.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vits/. The authors are listed in prov/HW04HE.jsonl.
"""Monotonic alignment search (MAS), the alignment step of Glow-TTS and VITS.
The network is not here. The code takes as given the n x T matrix v, where
v[i][j] is the log-likelihood of latent frame j under the prior of text
token i, and finds the monotonic alignment of the largest total score.
An alignment gives each frame j a token a(j) with a(0) = 0, a(T - 1) = n - 1
and a(j + 1) - a(j) in {0, 1}. So every token gets at least one frame and the
tokens are read in order. There are C(T - 1, n - 1) such alignments.
The dynamic program works in the Viterbi semiring (max, +):
Q[i][j] = v[i][j] + max(Q[i][j - 1], Q[i - 1][j - 1])
Tie rule in the traceback: the path stays on the same token when the two
predecessors have equal scores, so an earlier token ends as early as possible.
"""
import math
from typing import List, Sequence, Tuple
NEG_INF = float("-inf")
def monotonic_alignment_search(v: Sequence[Sequence[float]]) -> Tuple[List[int], float]:
"""Return (a, score): a[j] is the token of frame j, score is the sum of v[a[j]][j].
Raise ValueError if v is empty, ragged, or has fewer frames than tokens.
"""
n = len(v)
if n == 0:
raise ValueError("there must be at least one token")
T = len(v[0])
if any(len(row) != T for row in v):
raise ValueError("every row must have T entries")
if T < n:
raise ValueError("there must be at least as many frames as tokens")
Q = [[NEG_INF] * T for _ in range(n)] # @line L1
Q[0][0] = v[0][0] # @line L2
for j in range(1, T): # @line L3
for i in range(0, min(j, n - 1) + 1): # @line L4
stay = Q[i][j - 1]
move = Q[i - 1][j - 1] if i > 0 else NEG_INF
Q[i][j] = v[i][j] + max(stay, move) # @line L5
a = [0] * T
i = n - 1 # @line L6
for j in range(T - 1, -1, -1): # @line L7
a[j] = i # @line L8
if j > 0 and i > 0 and Q[i - 1][j - 1] > Q[i][j - 1]: # @line L9
i -= 1 # @line L10
return a, Q[n - 1][T - 1] # @line L11
def durations(a: Sequence[int], n: int) -> List[int]:
"""The number of frames of each token under the alignment a."""
d = [0] * n
for i in a:
d[i] += 1
return d
def gaussian_log_likelihoods(mu: Sequence[Sequence[float]], sigma: Sequence[Sequence[float]],
z: Sequence[Sequence[float]]) -> List[List[float]]:
"""v[i][j] = log N(z_j; mu_i, diag(sigma_i^2)) for n tokens and T frames of width d."""
v = []
for m, s in zip(mu, sigma):
row = []
for frame in z:
ll = 0.0
for x, mk, sk in zip(frame, m, s):
ll += -0.5 * math.log(2.0 * math.pi * sk * sk) - (x - mk) ** 2 / (2.0 * sk * sk)
row.append(ll)
v.append(row)
return v
test_vits.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vits/. The authors are listed in prov/HW04HE.jsonl.
import itertools
import math
import random
import pytest
from vits import durations, gaussian_log_likelihoods, monotonic_alignment_search
def all_alignments(n, T):
"""Every monotonic alignment of T frames to n tokens, from the cut points."""
for cuts in itertools.combinations(range(1, T), n - 1):
bounds = (0,) + cuts + (T,)
a = []
for i in range(n):
a.extend([i] * (bounds[i + 1] - bounds[i]))
yield a
def brute_force(v):
"""The best alignment by (score, reversed alignment), the tie rule of the code."""
n, T = len(v), len(v[0])
best = None
for a in all_alignments(n, T):
s = sum(v[a[j]][j] for j in range(T))
key = (s, tuple(reversed(a)))
if best is None or key > best[0]:
best = (key, a)
return best[1], best[0][0]
def test_count_is_binomial():
for n in range(1, 6):
for T in range(n, 9):
assert sum(1 for _ in all_alignments(n, T)) == math.comb(T - 1, n - 1)
assert sum(1 for _ in all_alignments(3, 6)) == 10
def test_matches_brute_force_float():
rng = random.Random(7)
for _ in range(200):
n = rng.randint(1, 5)
T = rng.randint(n, 9)
v = [[rng.gauss(0.0, 1.0) for _ in range(T)] for _ in range(n)]
a, s = monotonic_alignment_search(v)
b, t = brute_force(v)
assert a == b
assert math.isclose(s, t, rel_tol=1e-12, abs_tol=1e-12)
def test_matches_brute_force_with_ties():
# Small integer scores make many ties; the sums are exact in floating point.
rng = random.Random(11)
for _ in range(300):
n = rng.randint(1, 4)
T = rng.randint(n, 8)
v = [[float(rng.randint(-2, 1)) for _ in range(T)] for _ in range(n)]
a, s = monotonic_alignment_search(v)
b, t = brute_force(v)
assert s == t
assert a == b
def test_alignment_is_monotonic_and_onto():
rng = random.Random(3)
for _ in range(50):
n = rng.randint(1, 6)
T = rng.randint(n, 30)
v = [[rng.uniform(-5, 0) for _ in range(T)] for _ in range(n)]
a, s = monotonic_alignment_search(v)
assert a[0] == 0 and a[-1] == n - 1
assert all(a[j + 1] - a[j] in (0, 1) for j in range(T - 1))
assert sum(durations(a, n)) == T and min(durations(a, n)) >= 1
assert math.isclose(s, sum(v[a[j]][j] for j in range(T)))
def test_page_example():
v = [
[-1.0, -1.0, -4.0, -6.0, -6.0, -9.0],
[-5.0, -2.0, -1.0, -1.0, -5.0, -5.0],
[-9.0, -7.0, -5.0, -2.0, -1.0, -1.0],
]
a, s = monotonic_alignment_search(v)
assert a == [0, 0, 1, 1, 2, 2]
assert s == -6.0
assert durations(a, 3) == [2, 2, 2]
def test_gaussian_scores_recover_segments():
# Three tokens with well separated means; the frames come in runs of 2, 3 and 4.
mu = [[0.0, 0.0], [3.0, 0.0], [0.0, 3.0]]
sigma = [[0.5, 0.5]] * 3
rng = random.Random(5)
z = []
for i, length in enumerate([2, 3, 4]):
for _ in range(length):
z.append([mu[i][0] + rng.gauss(0, 0.1), mu[i][1] + rng.gauss(0, 0.1)])
v = gaussian_log_likelihoods(mu, sigma, z)
a, _ = monotonic_alignment_search(v)
assert durations(a, 3) == [2, 3, 4]
expected = -math.log(2 * math.pi * 0.25) - (0.0 ** 2 + 0.0 ** 2) / 0.5
assert math.isclose(gaussian_log_likelihoods([[0.0, 0.0]], [[0.5, 0.5]], [[0.0, 0.0]])[0][0], expected)
def test_large_input_runs():
rng = random.Random(9)
n, T = 40, 400
v = [[rng.uniform(-3, 0) for _ in range(T)] for _ in range(n)]
a, _ = monotonic_alignment_search(v)
assert len(a) == T and a[-1] == n - 1
def test_errors():
with pytest.raises(ValueError):
monotonic_alignment_search([])
with pytest.raises(ValueError):
monotonic_alignment_search([[0.0], [0.0]])
with pytest.raises(ValueError):
monotonic_alignment_search([[0.0, 1.0], [0.0]])
a, s = monotonic_alignment_search([[2.0, 3.0]])
assert a == [0, 0] and s == 5.0
References
- Kim, Kong and Son 2021, Section 2 (the variational inference, the alignment estimation, the adversarial training and the final loss), the MOS table on LJ Speech, the synthesis speed table, and Figure 2 (the lengths of sampled utterances)
- Kim, Kim, Kong and Yoon 2020, Section 3 (the monotonic alignment search and its recursion)
- Kong, Kim and Bae 2020, the generator and the multi-period discriminator, which VITS reuses
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag HW04HE Edit this page History Report an error Markdown