AI Logic

Architectures

WaveNet

Updated:

Architecture of WaveNet. Left: the overall flow (past samples → causal convolution → a stack of k residual blocks; each residual block adds an optional condition to a dilated convolution, passes it through the product of tanh and σ and a 1×1 convolution, adds the result to its input for the next block, and also sends it to the output side via a skip connection; sum of skip connections → ReLU and 1×1 convolution twice → softmax → distribution of the next sample; during generation, the drawn sample is fed back as input). Right: the 16-sample range seen by the final output when causal convolutions with dilations 1, 2, 4, and 8 are stacked.

Background and Overview

WaveNet is an autoregressive generative model that predicts an audio waveform one sample at a time, conditioned on all previous samples. It was published by van den Oord et al. at DeepMind in 2016. Its defining feature is a stack of dilated causal convolutions that lets it handle long contexts reaching back thousands of samples without using recurrence.

Until then, speech synthesis was dominated by concatenative methods, which stitch together fragments of recordings, and parametric methods, which generate waveforms from acoustic features with a signal-processing vocoder. Both had weaknesses: concatenative methods tend to leave distortion at the joins, and parametric methods tend to sound muffled because of signal processing. WaveNet overcame this barrier by learning the probability distribution of the waveform itself without signal-processing assumptions.

Speech is an extremely fine-grained time series with 16,000 or more samples per second. WaveNet carried over the idea of PixelCNN, which generates images one pixel at a time, to audio, and handled this length with the following three techniques.

  • Dilated causal convolutions: convolutions that never look at the future, with the spacing doubled at each layer, so that a few layers cover a wide range
  • Softmax output: sample values quantized to 256 levels with μ-law are predicted as a 256-class classification
  • Gated activations with residual and skip connections: train a deep network stably

In text-to-speech (TTS) experiments, it achieved greater naturalness than the best parametric and concatenative systems of the time for both US English and Mandarin Chinese. The MOS gap to human recordings shrank from 0.69 to 0.34 in English and from 0.42 to 0.13 in Mandarin. The later Tacotron 2 uses WaveNet as a vocoder that produces waveforms from mel spectrograms.

Architecture

WaveNet factorizes the joint probability of a waveform x={x1,…,xT}\mathbf{x} = \{x_1, \dots, x_T\} into a product of conditional probabilities of each sample.

p(x)=∏t=1Tp(xt∣x1,…,xt−1)p(\mathbf{x}) = \prod_{t=1}^{T} p(x_t \mid x_1, \dots, x_{t-1})

These conditional probabilities are modeled by a network of stacked convolutional layers. There is no pooling, and the output has the same length as the input. The left side of the figure at the top of the article shows the overall flow, and the right side shows the stack of dilated causal convolutions.

  1. Quantization: handling 16-bit values directly would require probabilities over 65,536 classes per sample. Instead, a μ-law transformation is applied to samples normalized to −1<xt<1-1 < x_t < 1, which are then quantized to 256 levels (μ=255\mu = 255).
  2. Causal convolution: the first layer is a convolution whose output at time tt depends only on x1,…,xtx_1, \dots, x_t. For 1D data, it can be made simply by shifting the output of an ordinary convolution by a few samples.
  3. Stack residual blocks: each block consists of a dilated convolution, a gated activation, and a 1×1 convolution. The dilation doubles at each layer and repeats once it reaches its limit (1, 2, 4, …, 512, 1, 2, 4, …, 512, …).
  4. Residual and skip connections: the output of the 1×1 convolution is added to the block's input and passed to the next block (residual connection), and is also sent to the output side as a skip connection.
  5. Output layers: the skip connections of all blocks are summed and passed through ReLU → 1×1 convolution → ReLU → 1×1 convolution → softmax to produce a 256-class distribution over the next sample.
  6. Generation: during training the whole ground-truth waveform is known, so predictions for all time steps can be computed in parallel. During generation, one sample is drawn from the distribution and fed back as input to predict the next sample, and this is repeated.

The μ-law transformation is given by the following equation.

f(xt)=sign⁡(xt) ln⁡(1+μ∣xt∣)ln⁡(1+μ)f(x_t) = \operatorname{sign}(x_t)\,\frac{\ln\left(1 + \mu |x_t|\right)}{\ln(1 + \mu)}

Because it divides small amplitudes finely and large amplitudes coarsely, the same 256 levels reconstruct the original sound more faithfully than uniform quantization. The paper notes that, especially for speech, the quantized-and-reconstructed signal sounded very similar to the original.

The gated activation has the same form as in gated PixelCNN. With Wf,kW_{f,k} and Wg,kW_{g,k} as the filter and gate convolution weights of layer kk, it is computed as follows (∗* is convolution, ⊙\odot is element-wise product, and σ\sigma is the sigmoid).

z=tanh⁡(Wf,k∗x)⊙σ(Wg,k∗x)\mathbf{z} = \tanh\left(W_{f,k} * \mathbf{x}\right) \odot \sigma\left(W_{g,k} * \mathbf{x}\right)

The tanh side decides "what to pass" and the σ\sigma side decides "how much to pass". The paper reports that in initial experiments this form worked significantly better than ReLU for modeling audio.

The conditional WaveNet models p(x∣h)=∏tp(xt∣x1,…,xt−1,h)p(\mathbf{x} \mid \mathbf{h}) = \prod_t p(x_t \mid x_1, \dots, x_{t-1}, \mathbf{h}) conditioned on an additional input h\mathbf{h}. There are two ways to inject the condition.

  • Global conditioning: a single vector h\mathbf{h} shared across all time steps, such as a speaker embedding, is turned into a linear projection V⋅,k⊤hV_{\cdot,k}^\top \mathbf{h} and added inside the tanh and σ\sigma.
  • Local conditioning: a time series h\mathbf{h} with a coarser time resolution than the audio, such as linguistic features, is upsampled with a transposed convolution to y\mathbf{y} at the audio's resolution, turned into a 1×1 convolution V⋅,k∗yV_{\cdot,k} * \mathbf{y}, and added.

With local conditioning, the gate becomes the following.

z=tanh⁡(Wf,k∗x+Vf,k∗y)⊙σ(Wg,k∗x+Vg,k∗y)\mathbf{z} = \tanh\left(W_{f,k} * \mathbf{x} + V_{f,k} * \mathbf{y}\right) \odot \sigma\left(W_{g,k} * \mathbf{x} + V_{g,k} * \mathbf{y}\right)

The paper also tried repeating the values of h\mathbf{h} along time instead of using a transposed convolution, and found it slightly worse.

The large speed difference between training and generation is a property shared by all autoregressive models. In training, the "true past" can be used as input, so convolutions compute all time steps at once. In generation, the "model's own past" is needed, so the whole network has to run each time one sample is produced.

Why It Can Handle Long Contexts

The key point of WaveNet is that dilated causal convolutions widen the receptive field (the range of input that one output sees) with almost no increase in computation.

With ordinary causal convolutions, the receptive field is only "number of layers + filter length − 1". In the example in the paper's figure (4 layers with filters of width 2), the receptive field is 5 samples. Seeing 0.1 seconds of 16 kHz audio requires 1,600 samples, so this approach would need a very large number of layers.

A dilated convolution applies its filter while skipping input values at a fixed interval. As on the right side of the figure at the top of the article, doubling the dilation as 1, 2, 4, 8 lets 4 layers see 16 samples. In the paper's configuration, 10 layers with dilations 1, 2, 4, …, 512 see 1,024 samples, and the paper regards this as a more efficient, nonlinear counterpart of a 1×1,024 convolution. Stacking this block several times further increases both model capacity and the receptive field.

The roles of the other design choices are as follows.

Design choiceWhat it doesWhat it helps with
Causal convolutionDoes not use future samples for the output at time ttPreserves the prediction order even when all time steps are computed in parallel during training
Dilated convolutionDoubles the spacing at each layerThe receptive field grows exponentially with the number of layers
Softmax outputPredicts as a 256-class classificationMakes no assumption about the shape of the distribution, so it can represent any shape
Gated activationProduct of tanh and σ\sigmaModeled audio better than ReLU in the paper's experiments
Residual and skip connectionsAdds the block's input to its output, and connects each block directly to the outputSpeeds up convergence and allows training deep networks

The reason for classifying with a softmax, even for inherently continuous quantities such as audio values, is that it worked better than mixture models in the PixelCNN work. The paper explains that a categorical distribution makes no assumptions about shape and can therefore represent arbitrary distributions more easily. Training maximizes the log-likelihood of the true samples, that is, minimizes the 256-class cross-entropy.

As another way to widen the receptive field, the paper also presents a configuration in which a small context stack that looks at a long span provides local conditioning to a larger WaveNet that looks at a short span.

The idea of dilated convolution is like reviewing records at widening intervals: "every day, every week, every month". You can survey a long period in few steps without going through every single day.

Experimental Results

The paper evaluates WaveNet on four tasks: speaker-conditioned speech generation, text-to-speech (TTS), music, and speech recognition.

Naturalness of speech synthesis (5-point MOS with 95% confidence intervals)

SpeechUS EnglishMandarin Chinese
LSTM-RNN parametric3.67 ± 0.0983.79 ± 0.084
HMM-driven concatenative3.86 ± 0.1373.47 ± 0.108
WaveNet (linguistic features + log F0)4.21 ± 0.0814.08 ± 0.085
Natural speech (8-bit μ-law)4.46 ± 0.0674.25 ± 0.082
Natural speech (16-bit linear PCM)4.55 ± 0.0754.21 ± 0.071

The data are the single-speaker datasets used for Google's TTS (24.6 hours of US English and 34.8 hours of Mandarin, both by professional female speakers). All compared systems were built with the same data and linguistic features. 100 sentences not included in the training data were rated by 8 listeners per stimulus, and ratings made without headphones (about 40%) were excluded.

Results of the other evaluations are as follows.

  • Paired comparison: WaveNet conditioned only on linguistic features sounded natural in quality but sometimes had unnatural prosody, such as stressing the wrong word in a sentence. The paper attributes this to the receptive field (240 ms) being too short to capture long-range changes in the fundamental frequency (F0). Conditioning additionally on log F0 predicted by another model eliminated the problem.
  • Multiple speakers: on VCTK (109 speakers, 44 hours), the model was trained conditioned only on speaker ID, not on text. A single model could produce the voice of every speaker, and adding speakers gave better validation performance than training on a single speaker. With a receptive field of about 300 ms, it remembers only the last 2–3 phonemes, so it produces speech that sounds like non-existent words.
  • Music: trained on MagnaTagATune (about 200 hours) and YouTube piano (about 60 hours). Enlarging the receptive field was crucial for sounding musical, but even with a receptive field of several seconds, a lack of long-range consistency remained, with genre and volume changing from second to second.
  • Speech recognition: on TIMIT, mean pooling (to 10 ms frames) and non-causal convolutions were added after the dilated convolutions, and the model was trained with two losses: next-sample prediction and frame classification. The test phoneme error rate was 18.8, which the paper describes as the best to its knowledge for a model trained directly on raw waveforms.

Practical Considerations

Keep the following points in mind when using WaveNet.

  • Generation is very slow: generation runs the whole network once per sample, so one second of 16 kHz audio requires 16,000 passes. In measurements in the later HiFi-GAN paper, WaveNet (the version that outputs a mixture of logistics) generated at 0.07 kHz on a GPU, about 0.003 times real time.
  • The receptive field length sets a limit: information older than the receptive field cannot be used. In the paper's TTS, a 240 ms receptive field sometimes produced unnatural prosody, which was compensated for by adding F0 predicted by an external model as a condition.
  • Quantization sets an upper bound: the MOS of human recordings quantized with 8-bit μ-law was 4.46 in English, lower than the 16-bit recordings (4.55). Generated audio cannot exceed the quality of this quantization either.
  • Conditioning features are needed separately: the paper's TTS WaveNet uses linguistic features derived from text, plus phoneme durations and log F0 predicted by another model. A separate text-analysis component is required.
  • The input differs between training and generation: training uses the ground-truth waveform as input, while generation uses the model's own samples. Implementations often write the parallel computation for training and the sample-by-sample computation for generation separately.

A naively implemented WaveNet recomputes the whole receptive field for every sample during generation, making it even slower. As is, it is not suited to producing audio in real time. As vocoders that produce waveforms from mel spectrograms, models that generate in parallel, such as WaveGlow, MelGAN, and HiFi-GAN, later came into wide use.

Comparison with Other Vocoders

Comparing WaveNet with later vocoders from the same viewpoints gives the following. MOS and speed are values measured under the same conditions on LJ Speech in the HiFi-GAN paper (an evaluation reconstructing waveforms from mel spectrograms of the original recordings; ground truth: 4.45).

ModelGenerationTraining objectiveMOSGPU generation speed (× real time)Parameters
WaveNet (MoL version)Autoregressive (one sample at a time)Likelihood maximization4.02 ± 0.08about 0.003×24.73 M
WaveGlowNormalizing flow (all samples in parallel)Likelihood maximization3.81 ± 0.08about 22.75×87.73 M
MelGANGAN generator (parallel)Adversarial training + feature matching3.79 ± 0.09about 645.73×4.26 M
HiFi-GAN V1GAN generator (parallel)Adversarial training + mel-spectrogram loss, etc.4.36 ± 0.07about 167.86×13.92 M

Rough guidelines for choosing are as follows.

  • Generation speed is not an issue and a model evaluable by likelihood is wanted: WaveNet is the baseline. Because it can compute the log-likelihood, it is also easy to check overfitting on validation data.
  • Real-time audio generation: a GAN vocoder such as HiFi-GAN is a good fit. In the comparison above, it is faster than WaveNet and has a higher MOS.
  • Training by likelihood while generating in parallel: WaveGlow is an option. Note its large number of parameters.

Stacks of dilated causal convolutions have spread beyond audio. TCN for action segmentation carries the WaveNet-style architecture over to time-series classification.

PyTorch example

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

"""
A small implementation of WaveNet's key ideas (dilated causal convolutions, gated activations,
residual and skip connections, 256-class softmax), following the paper's equations.
PyTorch has no built-in WaveNet. The μ-law transform is also available as torchaudio.functional.mu_law_encoding.
"""

def mu_law_encode(x, mu=255):
    """Map a [-1, 1] waveform to integers 0..mu (256 levels) with μ-law"""
    y = torch.sign(x) * torch.log1p(mu * x.abs()) / torch.log1p(torch.tensor(float(mu)))
    return ((y + 1) / 2 * mu + 0.5).long().clamp(0, mu)

def mu_law_decode(q, mu=255):
    y = 2 * q.float() / mu - 1
    return torch.sign(y) * ((1 + mu) ** y.abs() - 1) / mu


class CausalConv1d(nn.Conv1d):
    """Pad only on the left so that the output at time t depends only on inputs up to t"""
    def __init__(self, in_ch, out_ch, kernel_size=2, dilation=1):
        super().__init__(in_ch, out_ch, kernel_size, dilation=dilation)
        self.left = (kernel_size - 1) * dilation

    def forward(self, x):
        return super().forward(F.pad(x, (self.left, 0)))


class ResidualBlock(nn.Module):
    def __init__(self, res_ch, skip_ch, dilation, cond_ch=None):
        super().__init__()
        # compute filter and gate (W_f, W_g) together with twice the channels
        self.dilated = CausalConv1d(res_ch, 2 * res_ch, kernel_size=2, dilation=dilation)
        # add local condition y (upsampled to the audio length) via a 1×1 conv (V_f, V_g)
        self.cond = nn.Conv1d(cond_ch, 2 * res_ch, 1) if cond_ch else None
        self.res_out = nn.Conv1d(res_ch, res_ch, 1)    # to the residual connection
        self.skip_out = nn.Conv1d(res_ch, skip_ch, 1)  # to the skip connection

    def forward(self, x, y=None):
        h = self.dilated(x)
        if self.cond is not None and y is not None:
            h = h + self.cond(y)
        f, g = h.chunk(2, dim=1)
        z = torch.tanh(f) * torch.sigmoid(g)          # Eq. (2)
        return x + self.res_out(z), self.skip_out(z)


class WaveNet(nn.Module):
    def __init__(self, n_classes=256, res_ch=64, skip_ch=128, n_layers=10, n_stacks=3, cond_ch=None):
        super().__init__()
        self.embed = nn.Embedding(n_classes, res_ch)    # quantized values to vectors
        self.causal = CausalConv1d(res_ch, res_ch, kernel_size=2)
        self.blocks = nn.ModuleList(
            ResidualBlock(res_ch, skip_ch, 2 ** i, cond_ch)   # repeat dilations 1, 2, 4, …, 512
            for _ in range(n_stacks) for i in range(n_layers)
        )
        self.head = nn.Sequential(
            nn.ReLU(), nn.Conv1d(skip_ch, skip_ch, 1),
            nn.ReLU(), nn.Conv1d(skip_ch, n_classes, 1),   # logits before the softmax
        )
        self.receptive_field = 2 + n_stacks * (2 ** n_layers - 1)

    def forward(self, q, y=None):
        """q: quantized waveform [batch, time]. Returns logits for the "next sample" at each step"""
        x = self.causal(self.embed(q).transpose(1, 2))
        skip = 0
        for block in self.blocks:
            x, s = block(x, y)
            skip = skip + s
        return self.head(skip)                          # [batch, 256, time]


model = WaveNet()
wave = torch.rand(2, 16000) * 2 - 1                    # 1 second at 16 kHz (example)
q = mu_law_encode(wave)

# training: predict the next sample from the true past (all steps in parallel)
model.train()
logits = model(q[:, :-1])
loss = F.cross_entropy(logits, q[:, 1:])               # 256-class cross-entropy
loss.backward()

# generation: draw one sample at a time and feed it back (slow; naive implementation for illustration)
model.eval()
with torch.no_grad():
    gen = torch.full((1, 1), 128, dtype=torch.long)    # start from a near-silent value
    for _ in range(100):
        ctx = gen[:, -model.receptive_field:]
        probs = F.softmax(model(ctx)[:, :, -1], dim=-1)
        nxt = torch.multinomial(probs, 1)
        gen = torch.cat([gen, nxt], dim=1)
    audio = mu_law_decode(gen)

FAQ

Q. Why is WaveNet slow at generation?
A.

Because it is an autoregressive model that needs the samples it has produced so far to predict the next one. The whole network runs each time one sample is produced, so one second of 16 kHz audio requires 16,000 passes. In training, the true past can be used, so all time steps can be computed in parallel and training is fast.

Q. Why classify into 256 classes instead of regressing the waveform value?
A.

The paper explains that a categorical distribution makes no assumptions about shape and can therefore represent distributions of any shape more easily. It also notes that in the PixelCNN work on images, a softmax worked better than mixture models over continuous values. Keeping 16 bits would mean 65,536 classes, so the μ-law transformation f(x)=sign⁡(x)ln⁡(1+μ∣x∣)/ln⁡(1+μ)f(x) = \operatorname{sign}(x)\ln(1 + \mu|x|)/\ln(1+\mu) is applied and the values are quantized to 256 levels.

Q. How much does dilated convolution widen the receptive field?
A.

With 10 layers whose dilations double as 1, 2, 4, …, 512, the receptive field becomes 1,024 samples. Without dilation, width-2 convolutions give a receptive field of only "number of layers + 1", or 11 samples for 10 layers. The paper stacks this 10-layer block repeatedly, and in the TTS experiments sets the receptive field to 240 ms. See the dilated convolution article for details.

References

  1. van den Oord, A., Dieleman, S., Zen, H., Simonyan, K., Vinyals, O., Graves, A., Kalchbrenner, N., Senior, A., & Kavukcuoglu, K. (2016). WaveNet: A Generative Model for Raw Audio. arXiv:1609.03499.
  2. van den Oord, A., Kalchbrenner, N., Vinyals, O., Espeholt, L., Graves, A., & Kavukcuoglu, K. (2016). Conditional Image Generation with PixelCNN Decoders. NeurIPS 2016. arXiv:1606.05328.
  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. torchaudio.functional.mu_law_encoding.