AI Logic

Architectures

VALL-E

Updated:

The VALL-E architecture. The left side shows the overall flow (text is converted to phonemes and a 3-second recording to codes with EnCodec; an autoregressive model generates the first-stage tokens, a non-autoregressive model generates stages 2 to 8, and the EnCodec decoder converts them back to a waveform). The center shows the first-stage autoregressive model (phonemes and first-stage tokens are concatenated, and a causal Transformer samples the next token one at a time). The right side shows the non-autoregressive model for stages 2 to 8 (taking the phonemes, the recording's codes, and the previous stages as input, injecting the stage j through AdaLN, and predicting all frames of stage j at once)

Background and overview

VALL-E is a model that treats speech synthesis as "language modeling of acoustic tokens". Conditioned on the phonemes of a text and a 3-second recording of an unseen speaker, it generates the acoustic tokens of speech that reads the text in that speaker's voice. Wang and colleagues at Microsoft published it in 2023.

Until then, speech synthesis mainly predicted a mel spectrogram from text and turned it into a waveform with a vocoder. This approach had the following problems.

  • It needs clean data: models had to be trained on high-quality, studio-like recordings, and training data amounted to a few hundred hours at most.
  • It is weak on unseen speakers: for speakers not heard during training (zero-shot), speaker similarity and naturalness drop sharply. Dedicated techniques such as speaker adaptation (fine-tuning) or speaker encoders were needed.

Following the example of text models such as GPT-3, which greatly improved by scaling up data, VALL-E took the approach of training a language model directly on large amounts of diverse speech. To do so, it converts speech into sequences of indices (acoustic tokens) with the pretrained neural audio codec EnCodec. Because the intermediate representation changes from continuous mel spectrograms to discrete tokens, speech synthesis can be trained as "conditional language modeling".

AspectEarlier speech synthesisVALL-E
Intermediate representationMel spectrogramAudio codec tokens
Training objectiveContinuous regressionLanguage modeling (next-token prediction)
Training data600 hours or less60,000 hours
In-context learningNot possiblePossible (a 3-second recording serves as the prompt)

It was trained on 60,000 hours of English speech from about 7,000 speakers and evaluated on speakers of LibriSpeech and VCTK not included in training. Compared with YourTTS, the state-of-the-art zero-shot speech synthesis system, it scored 0.93 higher on speaker similarity (SMOS) and 0.12 higher on naturalness (CMOS) on LibriSpeech. It is also reported to carry over the emotion of the recording and even the acoustic environment, such as reverberation.

Architecture

VALL-E consists of EnCodec, which produces the acoustic tokens, and two language models that predict the tokens (an autoregressive model and a non-autoregressive model). In the figure at the top of the article, the left side shows the overall flow, the center shows the autoregressive model, and the right side shows the non-autoregressive model.

The acoustic tokens come from a pretrained EnCodec (24 kHz, 6 kbps). The EnCodec encoder downsamples a 24 kHz waveform by a factor of 320, producing 75 embeddings per second. Each embedding is turned into 8 indices by residual vector quantization with 8 stacked codebooks of 1,024 entries each. A 10-second clip becomes a 750×8750 \times 8 matrix of indices. The token matrix of speech yy is written C=Encodec(y)C = \mathrm{Encodec}(y) (T×8T \times 8), with ct,:c_{t,:} the 8 indices of frame tt and c:,jc_{:,j} the sequence of indices of stage jj.

Problem formulation: given a phoneme sequence xx and the tokens C~\tilde{C} (T′×8T' \times 8) of a recording (the acoustic prompt), the model is trained to maximize the probability p(C∣x,C~)p(C \mid x, \tilde{C}) of the token matrix CC. At inference, the predicted CC is converted back into a waveform with the EnCodec decoder.

In residual vector quantization, earlier stages represent coarse properties such as speaker identity, and later stages represent finer acoustic differences. Exploiting this hierarchy, the first stage and stages 2 to 8 are predicted by separate models.

p(C∣x,C~;θ)=p(c:,1∣C~:,1,x;θAR)∏j=28p(c:,j∣c:,<j,x,C~;θNAR)p(C \mid x, \tilde{C}; \theta) = p(c_{:,1} \mid \tilde{C}_{:,1}, x; \theta_{\mathrm{AR}}) \prod_{j=2}^{8} p(c_{:,j} \mid c_{:,<j}, x, \tilde{C}; \theta_{\mathrm{NAR}})

The autoregressive (AR) model is a decoder-only Transformer that predicts the first-stage tokens one at a time.

p(c:,1∣x,C~:,1;θAR)=∏t=0Tp(ct,1∣c<t,1,c~:,1,x;θAR)p(c_{:,1} \mid x, \tilde{C}_{:,1}; \theta_{\mathrm{AR}}) = \prod_{t=0}^{T} p(c_{t,1} \mid c_{<t,1}, \tilde{c}_{:,1}, x; \theta_{\mathrm{AR}})
  1. Input: concatenate the phoneme sequence xx and the first-stage token sequence, appending an end-of-sequence marker <EOS> after each.
  2. Embedding: map phonemes to vectors with the phoneme embedding WxW_x and tokens with the acoustic embedding WaW_a, and add sinusoidal positional embeddings separately for phonemes and tokens.
  3. Transformer decoder: with a causal mask, each token ct,1c_{t,1} sees only xx and c≤t,1c_{\le t,1}.
  4. Prediction layer: outputs the probabilities of the next token. Its weights are shared with the acoustic embedding WaW_a.

During training, the recording part is not treated specially; the model simply predicts the next token as an ordinary language model. This way, any initial portion acts as a prompt for predicting the rest.

The non-autoregressive (NAR) model is a Transformer with almost the same shape as the AR model, and it predicts stages 2 to 8, one stage at a time, with all frames of a stage predicted at once.

p(C:,2:8∣x,C~;θNAR)=∏j=28p(c:,j∣C:,<j,x,C~;θNAR)p(C_{:,2:8} \mid x, \tilde{C}; \theta_{\mathrm{NAR}}) = \prod_{j=2}^{8} p(c_{:,j} \mid C_{:,<j}, x, \tilde{C}; \theta_{\mathrm{NAR}})
  1. Input: concatenate the phoneme sequence, the acoustic prompt (the sum of the recording's embeddings over all 8 stages), and the sum of the token embeddings of stages 1 to j−1j-1. Each stage has its own acoustic embedding WajW^j_a.
  2. Stage conditioning: which stage is being predicted (jj) is injected through Adaptive Layer Normalization (AdaLN(h,j)=ajLayerNorm(h)+bj\mathrm{AdaLN}(h, j) = a_j \mathrm{LayerNorm}(h) + b_j, where aja_j and bjb_j are obtained from a stage embedding by a linear projection).
  3. Attention scope: unlike the AR model, it attends to all tokens.
  4. Prediction layer: the weights of the stage-jj prediction layer are shared with the acoustic embedding of stage j+1j+1.

In each training step, the stage jj to predict is chosen at random from 2 to 8.

ect,j=Waj⊙ct,j,ect=∑j=1i−1ect,je_{c_{t,j}} = W^j_a \odot c_{t,j}, \qquad e_{c_t} = \sum_{j=1}^{i-1} e_{c_{t,j}}

(⊙\odot denotes selecting a row of the embedding by index, and ii is the stage being predicted.)

The AR and NAR models are both Transformers with 12 layers, 16 heads, 1,024-dimensional embeddings, 4,096-dimensional feed-forward layers, and dropout of 0.1.

At inference, the model reads a sentence in an unseen speaker's voice as follows.

  1. Convert the target sentence into phonemes, and turn the 3-second recording into the token matrix C~\tilde{C} with EnCodec.
  2. Prepend the phonemes of the recording's transcript to the phonemes of the target sentence to form the phoneme prompt.
  3. With the AR model, starting from the recording's first-stage tokens c~:,1\tilde{c}_{:,1}, generate the continuing first-stage tokens one at a time by sampling.
  4. With the NAR model, generate stages 2 to 8 by choosing the most probable token at each stage (greedily).
  5. Convert the 8 stages of tokens back into a waveform with the EnCodec decoder.

The AR model does not use beam search because the language model can fall into an infinite loop repeating the same part. Sampling also greatly increases the diversity of the output.

Why a 3-second recording is enough to imitate a voice

The key point of VALL-E is that it treats voice characteristics as the "continuation" of tokens and leaves the rest to the in-context learning of a language model trained on large amounts of data.

A text language model can pick up the style and format written in a prompt and continue in the same manner (in-context learning). In VALL-E, the acoustic tokens of the recording play the role of the prompt. Because the model has learned to "predict the second half of a speaker's speech from the first half" on 60,000 hours of speech from about 7,000 speakers, it can read features such as pitch, voice quality, speaking style, and recording environment even from a 3-second recording of an unseen speaker and continue in the same manner. No dedicated speaker encoder or per-speaker fine-tuning is needed.

As an analogy, VALL-E listens to 3 seconds of someone's recorded speech and writes the continuation: "if this person read this sentence, it should sound like this". Instead of summarizing the voice into numerical features and passing them along, it passes the recording's tokens themselves as context, so not only the voice quality but also the emotion and the room's acoustics carry over.

There is a reason for splitting the work into an autoregressive first stage and non-autoregressive stages 2 to 8.

StageModelReason
Stage 1AutoregressiveSpeaking rate varies widely between speakers, making a dedicated length-prediction model hard to build. An autoregressive model continues until it outputs <EOS>, so it can decide the length flexibly
Stages 2 to 8Non-autoregressiveThe length is already fixed by stage 1, so each stage can be produced in a single pass. The number of generation steps drops from O(T)O(T), proportional to the number of frames TT, to O(1)O(1), equal to the number of stages

Since the first stage of residual vector quantization carries most of the sound (such as speaker identity) and later stages are finer corrections, the division spends time carefully generating the most important first stage autoregressively and produces the rest quickly.

Experimental results

The paper trained on 60,000 hours of English audiobook speech from about 7,000 speakers (LibriLight). Since the data has no transcripts, phoneme alignments were produced by a speech recognition model (DNN-HMM) trained on 960 hours of LibriSpeech. Training ran for 800,000 steps on 16 V100 GPUs with batches of 6,000 tokens per GPU, using AdamW with a warmup that raises the learning rate to 5×10−45 \times 10^{-4} over the first 32,000 updates, followed by linear decay. The baseline was the publicly available YourTTS (trained on VCTK, LibriTTS, and TTS-Portuguese).

The evaluation metrics are as follows.

  • WER: the word error rate when the generated speech is transcribed by a HuBERT-Large speech recognizer fine-tuned on LibriSpeech. It measures whether the text is read correctly (robustness).
  • SPK: the speaker similarity between the recording and the generated speech, measured with the speaker verification model WavLM-TDNN (−1 to 1; higher means more similar).
  • SMOS: speaker similarity rated by people (1 to 5).
  • CMOS: naturalness rated by people comparing two samples side by side (−3 to 3).

Automatic evaluation on LibriSpeech test-clean (utterances of 4 to 10 seconds, 2.2 hours in total. VALL-E uses as its prompt 3 seconds cut from a different utterance of the same speaker. VALL-E-continual uses the first 3 seconds of the same utterance and generates the continuation)

ModelInputWERSPK
Ground truth−2.20.754
GSLMSpeech (HuBERT codes)12.40.126
AudioLMSpeech6.0−
YourTTSPhonemes7.70.337
VALL-EPhonemes5.90.580
VALL-E-continualPhonemes3.80.508

(The WER of AudioLM is the value from the AudioLM paper, measured with a different speech recognition model.)

Human evaluation on LibriSpeech test-clean (40 speakers, a 3-second recording each. CMOS is relative to VALL-E)

ModelSMOSCMOS
YourTTS3.45 ± 0.09−0.12
VALL-E4.38 ± 0.100.00
Ground truth4.5 ± 0.10+0.17

Effect of the prompts (the NAR model is evaluated with the ground-truth first stage as input)

SettingWERSPK
NAR: no prompt19.60.518
NAR: phoneme prompt only3.00.541
NAR: phoneme and acoustic prompts2.80.732
AR: with acoustic prompt (VALL-E)5.90.585
AR: without acoustic prompt5.90.236

The phoneme prompt helps with the content being read, and the acoustic prompt helps with speaker similarity. Removing the acoustic prompt from the AR model dropped SPK from 0.585 to 0.236, even though the NAR model still had its prompt.

Evaluation on VCTK (108 speakers. VALL-E heard none of these speakers in training, while YourTTS heard 97 of them)

ModelSPK (3 s)SPK (5 s)SPK (10 s)
YourTTS (108 speakers)0.3570.3770.394
VALL-E (108 speakers)0.3820.4230.484
YourTTS (11 speakers unseen in training)0.3310.3370.344
VALL-E (same 11 speakers)0.3890.3800.414

In the human evaluation (60 speakers, a 3-second recording each), SMOS was 3.70 for YourTTS, 3.81 for VALL-E, and 4.29 for the ground truth. On CMOS, VALL-E was 0.23 higher than YourTTS and showed no statistically significant difference from the ground truth (the ground truth's CMOS relative to VALL-E was −0.04).

Practical considerations

Keep the following points in mind when using VALL-E.

  • Skipped and repeated words occur: the paper reports that words can become unclear, be dropped, or be repeated. Because the first stage is generated autoregressively, there is no mechanism to correct a breakdown in the attention alignment.
  • Speaking styles absent from the data are hard: the training data consists of audiobook readings, so the variety of speaking styles is limited. On speakers with various accents, as in VCTK, speaker similarity was lower than on LibriSpeech.
  • The quality of the prompt recording carries straight through: reverberation and emotion are inherited too, so a prompt with much noise or reverberation leaves them in the generated speech. For clean speech, use a clean recording.
  • Results change with every generation: because the first stage is sampled, the same sentence and recording yield speech with different speaking rates and emphasis. This is an advantage for producing pseudo-data to train speech recognition, but fix the random seed when the same result must be reproduced.
  • Generation is relatively slow: the first stage repeats the autoregressive computation once per frame, so it takes longer than models that generate in parallel, such as VITS.

Because VALL-E can imitate a specific person's voice from a 3-second recording, it carries risks of misuse such as spoofing voice-based identity verification or impersonating a specific person. The paper also points out this risk and proposes building a detection model that can tell whether speech was synthesized by VALL-E as a countermeasure. Do not use anyone's voice without their consent.

Comparison with other speech synthesis models

Comparing VALL-E with other speech synthesis models from the same viewpoints gives the following.

ModelIntermediate representationGenerationHandling unseen speakersTraining data scale (per paper)
Tacotron 2 + vocoderMel spectrogramAutoregressive + vocoderRequires speaker embeddings or fine-tuning24.6 hours from a single speaker
VITSLearned latent variablesParallel (VAE + flow + GAN)Switches between embeddings of speakers seen in trainingLJ Speech (about 24 hours), VCTK (about 44 hours)
YourTTS−−Speaker encoderVCTK, LibriTTS, TTS-Portuguese (according to the VALL-E paper)
VALL-EEnCodec tokens (8 stages)Autoregressive for stage 1, non-autoregressive for stages 2 to 8Uses a 3-second recording as the prompt (in-context learning)60,000 hours, about 7,000 speakers

Rough guidelines for choosing are as follows.

  • Producing many different people's voices from just a few seconds of recording: a language model over acoustic tokens, like VALL-E, is a good fit. No per-speaker training is needed.
  • Producing a fixed speaker's voice stably and quickly: a parallel model trained on that speaker's data, like VITS, is a good fit. Skipped and repeated words are less likely, and generation is faster.
  • Choosing how to produce the acoustic tokens: VALL-E uses EnCodec, but the same idea works with any residual vector quantization codec, such as SoundStream. More stages improve audio quality but also increase the number of tokens to predict.

PyTorch example

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

"""
A small implementation of VALL-E's two language models (autoregressive for stage 1, non-autoregressive for stages 2-8), following Section 4.2 and Eqs. (1)-(5) of the paper.
PyTorch has no built-in VALL-E. The acoustic tokens are assumed to come from a pretrained EnCodec (24 kHz, 6 kbps, 8 stages x 1,024 entries).
"""

N_PHONE, N_CODE, N_Q, D = 100, 1024, 8, 256        # the paper uses 1,024-dim embeddings, 12 layers, 16 heads
EOS = N_CODE                                       # add one <EOS> to the stage-1 vocabulary


def sinusoid(n, d):
    pos = torch.arange(n)[:, None]
    div = torch.exp(torch.arange(0, d, 2) * (-math.log(10000.0) / d))
    pe = torch.zeros(n, d)
    pe[:, 0::2], pe[:, 1::2] = torch.sin(pos * div), torch.cos(pos * div)
    return pe


class ARModel(nn.Module):
    """Predicts stage-1 tokens one at a time from the phonemes and previous tokens (decoder-only Transformer)"""
    def __init__(self, layers=2, heads=4):
        super().__init__()
        self.W_x = nn.Embedding(N_PHONE + 1, D)    # phoneme embedding (last entry is <EOS>)
        self.W_a = nn.Embedding(N_CODE + 1, D)     # acoustic embedding (last entry is <EOS>)
        layer = nn.TransformerEncoderLayer(D, heads, 4 * D, dropout=0.1, batch_first=True, norm_first=True)
        self.tf = nn.TransformerEncoder(layer, layers)

    def forward(self, phones, codes):              # phones: [B, Lx] (with <EOS>), codes: [B, T]
        ex = self.W_x(phones) + sinusoid(phones.shape[1], D)    # positional embeddings are separate for phonemes and tokens
        ea = self.W_a(codes) + sinusoid(codes.shape[1], D)
        h = torch.cat([ex, ea], 1)
        L = h.shape[1]
        mask = torch.triu(torch.ones(L, L, dtype=torch.bool), 1)   # causal: attend only to the left
        h = self.tf(h, mask=mask)
        return h[:, phones.shape[1]:] @ self.W_a.weight.t()        # prediction layer shares weights with W_a


class AdaLNBlock(nn.Module):
    """Transformer layer that injects stage j via Adaptive Layer Normalization: AdaLN(h, j) = a_j LayerNorm(h) + b_j"""
    def __init__(self, heads=4):
        super().__init__()
        self.attn = nn.MultiheadAttention(D, heads, dropout=0.1, batch_first=True)
        self.ff = nn.Sequential(nn.Linear(D, 4 * D), nn.GELU(), nn.Linear(4 * D, D))
        self.norm1, self.norm2 = nn.LayerNorm(D, elementwise_affine=False), nn.LayerNorm(D, elementwise_affine=False)
        self.ada = nn.Linear(D, 4 * D)             # stage embedding -> (a1, b1, a2, b2)

    def forward(self, h, stage_emb):
        a1, b1, a2, b2 = self.ada(stage_emb)[:, None].chunk(4, -1)
        x = a1 * self.norm1(h) + b1
        h = h + self.attn(x, x, x, need_weights=False)[0]         # no mask: attend to all tokens
        return h + self.ff(a2 * self.norm2(h) + b2)


class NARModel(nn.Module):
    """Predicts the tokens of stage j (2-8) for all frames at once"""
    def __init__(self, layers=2):
        super().__init__()
        self.W_x = nn.Embedding(N_PHONE + 1, D)
        self.W_a = nn.ModuleList(nn.Embedding(N_CODE, D) for _ in range(N_Q))   # per-stage acoustic embeddings
        self.stage = nn.Embedding(N_Q, D)
        self.blocks = nn.ModuleList(AdaLNBlock() for _ in range(layers))

    def forward(self, phones, prompt, codes, j):   # prompt: [B, T', 8], codes: [B, T, 8], j is the 1-based stage (2-8)
        ex = self.W_x(phones) + sinusoid(phones.shape[1], D)
        ep = sum(self.W_a[k](prompt[..., k]) for k in range(N_Q)) + sinusoid(prompt.shape[1], D)   # the prompt is the sum of all 8 stages
        ec = sum(self.W_a[k](codes[..., k]) for k in range(j - 1)) + sinusoid(codes.shape[1], D)   # sum of stages 1 to j-1 (Eqs. 4, 5)
        h = torch.cat([ex, ep, ec], 1)
        s = self.stage(torch.full((h.shape[0],), j - 1))
        for blk in self.blocks:
            h = blk(h, s)
        # the stage-j prediction layer shares weights with the stage-(j+1) acoustic embedding (j = 8 has no partner, so the stage-8 embedding stands in)
        W_out = self.W_a[min(j, N_Q - 1)].weight
        return h[:, -codes.shape[1]:] @ W_out.t()


ar, nar = ARModel(), NARModel()

# --- one training step (predict the next token as an ordinary language model) ---
phones = torch.randint(0, N_PHONE, (2, 20))
codes = torch.randint(0, N_CODE, (2, 150, N_Q))                    # EnCodec tokens (2 s x 75 Hz)
eos_x = torch.full((2, 1), N_PHONE)
inp = torch.cat([torch.full((2, 1), EOS), codes[..., 0]], 1)       # place a separator at the start and shift by one (implementation detail)
tgt = torch.cat([codes[..., 0], torch.full((2, 1), EOS)], 1)
loss_ar = F.cross_entropy(ar(torch.cat([phones, eos_x], 1), inp).transpose(1, 2), tgt)

j = int(torch.randint(2, N_Q + 1, ()))                             # choose the stage to predict at random
prompt, target = codes[:, :75], codes[:, 75:]                       # the paper uses 3 s of the same utterance as the prompt (1 s here)
loss_nar = F.cross_entropy(nar(torch.cat([phones, eos_x], 1), prompt, target, j).transpose(1, 2), target[..., j - 1])
(loss_ar + loss_nar).backward()

# --- inference: recording phonemes + sentence phonemes, continue from the recording's stage-1 tokens ---
ar.eval(); nar.eval()
with torch.no_grad():
    phones_all = torch.cat([phones[:1], eos_x[:1]], 1)
    prompt_codes = codes[:1, :75]                                   # tokens of the recording (the paper uses 3 s = 225 frames)
    seq = prompt_codes[..., 0]
    for _ in range(200):                                            # stage 1: one token at a time by sampling (no beam search)
        logits = ar(phones_all, torch.cat([torch.full((1, 1), EOS), seq], 1))[:, -1]
        nxt = torch.multinomial(F.softmax(logits, -1), 1)
        if nxt.item() == EOS:
            break
        seq = torch.cat([seq, nxt.clamp(max=N_CODE - 1)], 1)
    gen = torch.zeros(1, seq.shape[1] - prompt_codes.shape[1], N_Q, dtype=torch.long)
    gen[..., 0] = seq[:, prompt_codes.shape[1]:]
    for j in range(2, N_Q + 1):                                     # stages 2-8: all frames of each stage, greedily
        gen[..., j - 1] = nar(phones_all, prompt_codes, gen, j).argmax(-1)
    print(gen.shape)                                                # [1, T, 8] -> convert back to a waveform with the EnCodec decoder

FAQ

Q. Why does VALL-E use EnCodec tokens?
A.

Turning speech into discrete tokens lets a language model handle it just like text. The paper lists the advantages of codec tokens: they retain much of the speaker and recording-environment information (HuBERT codes lose speaker information), the pretrained decoder converts them straight back into a waveform so no vocoder needs to be trained, and the sequence is much shorter than raw waveform samples. At 6 kbps, EnCodec turns one second of 24 kHz audio into 75 frames × 8 stages of tokens.

Q. Why is only the first stage generated autoregressively?
A.

To decide the length. Speaking rate varies widely between speakers, making a dedicated length-prediction model hard to build, whereas an autoregressive model can decide the length flexibly by continuing until it outputs the end marker (<EOS>). For stages 2 to 8, the length is already fixed by the first stage, so the non-autoregressive model generates all frames of each stage at once, reducing the number of computation steps.

Q. When should VALL-E be used, and when VITS?
A.

VALL-E suits creating an unseen speaker's voice from a few seconds of recording, and VITS suits producing a fixed speaker's voice stably and quickly. VALL-E is trained on 60,000 hours of diverse speech, so it can imitate voices without per-speaker training, but because it is autoregressive, it sometimes skips or repeats words, and generation takes time.

References

  1. Wang, C., Chen, S., Wu, Y., Zhang, Z., Zhou, L., Liu, S., Chen, Z., Liu, Y., Wang, H., Li, J., He, L., Zhao, S., & Wei, F. (2023). Neural Codec Language Models are Zero-Shot Text to Speech Synthesizers. arXiv:2301.02111.
  2. VALL-E audio samples (by the paper's authors)
  3. Défossez, A., Copet, J., Synnaeve, G., & Adi, Y. (2022). High Fidelity Neural Audio Compression. arXiv:2210.13438.
  4. Borsos, Z., et al. (2022). AudioLM: a Language Modeling Approach to Audio Generation. arXiv:2209.03143.