Skip to content
BIASED

Audio generation: speech and music

The course's models applied to sound: mel spectrograms and vocoders, Glow-TTS as a flow whose prior is set by the text, residual vector quantization in a neural codec, and MusicGen, one transformer over several streams of codes.

Sound as a signal

Autoregressive transformers left a recipe: a learned autoencoder turns an image into a short sequence of codes, and a transformer continues that sequence one code at a time. This extension takes that recipe, and the flows of The change of variables, to sound.

Sound is long. A microphone records air pressure, and a sound file stores it fsf_s times per second as a waveform, a sequence of numbers in [−1,1][-1, 1]. Speech corpora such as LJ Speech, about 24 hours of one speaker, use fs=22,050f_s = 22{,}050 Hz. WaveNet, the audio model of Autoregressive models, generates those samples one by one: 22,050 network passes for one second of speech. A three-minute song at 32 kHz is almost six million numbers.

Two answers make sound shorter. Speech systems keep a continuous summary, the mel spectrogram. Music systems compress the waveform into a few streams of discrete codes. This topic follows one model of each kind.

The spectrogram shows which frequencies sound when. The short-time Fourier transform cuts the waveform into overlapping windows and takes the Fourier transform of each; the magnitudes form a time–frequency image. With windows of 1024 samples and a hop of 256 samples, one second at 22,050 Hz gives 22,050/256≈86.1322{,}050 / 256 \approx 86.13 frames.

The mel spectrogram also compresses the frequency axis the way hearing does. We tell pitches apart finely at low frequencies and coarsely at high ones, and the mel scale follows that. A frequency ν\nu in hertz becomes, in mel,

m(ν)=2595log⁡10(1+ν700),m(\nu) = 2595 \log_{10}\Big(1 + \frac{\nu}{700}\Big),

so 1000 Hz maps to 1000 mel and 11,025 Hz, the highest frequency a 22,050 Hz recording can hold, to about 3176 mel. A bank of F=80F = 80 triangular filters, equally spaced in mel, sums the magnitudes into bands, and the result goes on a log scale. One second of speech becomes 80⋅86.13≈689180 \cdot 86.13 \approx 6891 numbers instead of 22,050, about 3.2 times fewer. It is a small image: 80 rows, 86 columns per second.

The price is the phase. Magnitudes say how much of each frequency is present, not how the waves line up, so many waveforms share one mel spectrogram. A vocoder must invent a plausible waveform for it.

The text-to-speech pipeline

A text-to-speech (TTS) system works in stages. Text normalization writes out numbers and symbols: "£5" becomes "five pounds". Grapheme-to-phoneme conversion turns letters into phonemes, the sounds of the language. An acoustic model maps the phonemes to a mel spectrogram, and a vocoder maps that to a waveform.

The acoustic model meets the central difficulty of TTS, alignment. Tens of phonemes go in, hundreds of frames come out, and the data does not say how many frames each phoneme lasts. Tacotron 2 (Shen et al., 2018) generates frames one at a time, and an attention layer decides which phoneme is being spoken; when the attention slips, the model skips or repeats words. FastSpeech (Ren et al., 2019) generates all frames in parallel but borrows its durations from the attention of an autoregressive teacher.

The vocoder is a conditional generative model of a waveform given a mel spectrogram, and every family of the course has built one:

vocoder family in short
WaveNet autoregressive one sample at a time, the mel as an extra input
WaveGlow (Prenger, Valle and Catanzaro, 2019) normalizing flow noise to waveform, the couplings see the mel
HiFi-GAN (Kong, Kim and Bae, 2020) GAN each sub-discriminator sees every pp-th sample, p∈{2,3,5,7,11}p \in \{2, 3, 5, 7, 11\}, to catch the periodicity of voiced speech
DiffWave (Kong et al., 2021) DDPM the noise predictor gets the mel, stretched to the sample rate

The stages can also merge: VITS (Kim, Kong and Son, 2021) is one conditional VAE with a flow prior and a GAN decoder that outputs the waveform directly. A speaker is one more condition, an embedding per speaker or one computed from a short recording.

The next three blocks follow one acoustic model, Glow-TTS, because it solves alignment with tools from this course: a flow and an exact likelihood.

Glow-TTS: a flow with a text-conditioned prior

Glow-TTS (Kim et al., 2020) generates a whole mel spectrogram in one parallel pass and finds its own alignment. Its generator is a normalizing flow. As in The change of variables, an invertible map ff takes a mel spectrogram xx of TmelT_{\text{mel}} frames to a latent z=f(x)z = f(x) of the same shape, F=80F = 80 numbers per frame. The flow never sees the text. The text enters through the prior.

An encoder reads the TtextT_{\text{text}} phonemes cc and outputs a mean μi\mu_i and standard deviations σi\sigma_i for each phoneme ii. An alignment A:{1,…,Tmel}→{1,…,Ttext}A: \{1, \dots, T_{\text{mel}}\} \to \{1, \dots, T_{\text{text}}\} says which phoneme each latent frame belongs to. A reader goes through a text in order and skips nothing, so AA must be monotonic, never going back, and surjective, giving every phoneme at least one frame.

Given AA, each latent frame is a Gaussian around the mean of its phoneme, and the change of variables gives the likelihood of the spectrogram:

log⁡pθ(x∣c;A)=∑j=1Tmellog⁡N(zj; μA(j), diag⁡σA(j)2)+log⁡∣det⁡Jf(x)∣,z=f(x).\log p_\theta(x \mid c; A) = \sum_{j=1}^{T_{\text{mel}}} \log \mathcal N\big(z_j;\ \mu_{A(j)},\ \operatorname{diag}\sigma_{A(j)}^2\big) + \log\big\lvert\det J_f(x)\big\rvert, \qquad z = f(x).

This is the flow likelihood of the course with one change. The base distribution is not N(0,I)\mathcal N(0, I) but one Gaussian per phoneme, stretched over that phoneme's frames by AA.

The alignment is unknown, so training alternates two steps. Given the parameters θ\theta, find the best alignment A∗=arg⁡max⁡Alog⁡pθ(x∣c;A)A^* = \arg\max_A \log p_\theta(x \mid c; A). Given A∗A^*, take a gradient step on θ\theta. Neither z=f(x)z = f(x) nor the log-determinant depends on AA, so the first step maximizes the prior term alone. The objective is the likelihood under the single best alignment, an approach known as Viterbi training.

The flow itself is a Glow stack of ActNorm layers, invertible 1×11 \times 1 convolutions and affine couplings (the extension Flow architectures builds them).

Durations and synthesis

At synthesis there is no spectrogram to align, so the durations are predicted. MAS supplies the targets: the duration did_i of phoneme ii is the number of frames aligned to it, (2,2,2)(2, 2, 2) in the example. A small convolutional duration predictor fdurf_{\text{dur}} reads the encoder output hh and is trained with a squared error on log durations:

Ldur=1Ttext∑i=1Ttext(fdur(sg[h])i−log⁡di)2.\mathcal L_{\text{dur}} = \frac{1}{T_{\text{text}}} \sum_{i=1}^{T_{\text{text}}} \Big( f_{\text{dur}}\big(\mathrm{sg}[h]\big)_i - \log d_i \Big)^2 .

The stop-gradient sg\mathrm{sg} is the identity in the forward pass and has zero derivative in the backward pass. It keeps this loss from changing the encoder, which the likelihood trains.

Synthesis is then one parallel pass:

  1. the encoder gives μi\mu_i, σi\sigma_i and a predicted log duration for every phoneme; each duration is its exponential, rounded up;
  2. every phoneme's statistics are repeated for as many frames as it lasts, which defines AA;
  3. the latent is sampled frame by frame, zj=μA(j)+τ σA(j)⊙εjz_j = \mu_{A(j)} + \tau\, \sigma_{A(j)} \odot \varepsilon_j with εj∼N(0,I)\varepsilon_j \sim \mathcal N(0, I);
  4. the flow runs backwards, x=f−1(z)x = f^{-1}(z), and a vocoder turns xx into a waveform.

The temperature τ\tau is the standard deviation used at sampling, a cousin of the temperature of Autoregressive transformers. New noise gives a new intonation, and multiplying all durations by one number changes the speaking rate.

How good is it? The usual measure is the mean opinion score (MOS): listeners rate each clip from 1 to 5 and the ratings are averaged (the topic Human evaluation at the end of the course discusses such studies). On LJ Speech, with WaveGlow as the vocoder and τ=0.333\tau = 0.333, Glow-TTS scored 4.01 against 3.88 for Tacotron 2, and it synthesized an order of magnitude faster.

Audio codecs: residual quantization

Music needs the whole frequency range and long clips, and a transformer wants discrete tokens. The image answer carries over: train an autoencoder with a discrete bottleneck on the waveform, a neural audio codec, and model its codes.

EnCodec (Défossez et al., 2023), which follows SoundStream (Zeghidour et al., 2022), has a one-dimensional convolutional encoder with strides 2, 4, 5 and 8. The total stride is 2⋅4⋅5⋅8=3202 \cdot 4 \cdot 5 \cdot 8 = 320, so 24 kHz audio gives 75 latent frames per second. The decoder mirrors it with transposed convolutions. The losses are VQGAN's, adapted to sound: distances between waveforms and between mel spectrograms, an adversarial loss and a commitment loss.

Between encoder and decoder sits the quantizer. A VQ-VAE replaces each latent vector by the nearest entry of one codebook. Residual vector quantization (RVQ) then quantizes what is left, again and again, with codebooks C1,…,CNq\mathcal C_1, \dots, \mathcal C_{N_q} of KK entries each. For a latent frame zz:

r(0)=z,e(m)=arg⁡min⁡e∈Cm∥r(m−1)−e∥2,r(m)=r(m−1)−e(m).r^{(0)} = z, \qquad e^{(m)} = \arg\min_{e \in \mathcal C_m} \big\lVert r^{(m-1)} - e \big\rVert^2, \qquad r^{(m)} = r^{(m-1)} - e^{(m)} .

The decoder receives the sum of the chosen vectors, and the sum telescopes:

z^=∑m=1Nqe(m)=∑m=1Nq(r(m−1)−r(m))=z−r(Nq).\hat z = \sum_{m=1}^{N_q} e^{(m)} = \sum_{m=1}^{N_q} \big(r^{(m-1)} - r^{(m)}\big) = z - r^{(N_q)} .

The quantization error is exactly the last residual. The code of a frame is its list of NqN_q indices, and stage mm describes only what the earlier stages missed, so the codes go from coarse to fine. With Nq=1N_q = 1 this is the VQ-VAE, and training is the same: a straight-through gradient across each argmin and a commitment term per stage.

A worked example in one dimension: z=2.7z = 2.7 and three codebooks of four entries.

stage codebook input chosen residual squared error
1 {−2,0,2,4}\{-2, 0, 2, 4\} 2.72.7 22 0.70.7 0.490.49
2 {−1,−0.5,0.5,1}\{-1, -0.5, 0.5, 1\} 0.70.7 0.50.5 0.20.2 0.040.04
3 {−0.25,−0.125,0.125,0.25}\{-0.25, -0.125, 0.125, 0.25\} 0.20.2 0.250.25 −0.05-0.05 0.00250.0025

The reconstruction is z^=2+0.5+0.25=2.75=z−r(3)\hat z = 2 + 0.5 + 0.25 = 2.75 = z - r^{(3)}, and the code takes three indices of 2 bits, 6 bits in all.

Why not one large codebook? At 6 kbps and 75 frames per second a frame gets 80 bits. One codebook would need 280≈1.2⋅10242^{80} \approx 1.2 \cdot 10^{24} entries. Eight stages of 2102^{10} entries spend the same 80 bits with 8192 stored vectors. RVQ stores a number of vectors that grows linearly with the bits, not exponentially. Its coarse-to-fine order has a bonus: training with a random number of stages per example, quantizer dropout, lets one model serve many bitrates.

A codec with NqN_q codebooks of KK entries at frf_r frames per second spends, in bits per second,

R=Nq⋅log⁡2K⋅frR = N_q \cdot \log_2 K \cdot f_r

The codec of MusicGen runs at 32 kHz with stride 640, so fr=50f_r = 50, and has four codebooks of 2048 entries: R=4⋅11⋅50=2200R = 4 \cdot 11 \cdot 50 = 2200 bits per second, 233 times less than the 512,000 of 16-bit samples. One second becomes 200 codes in four streams.

MusicGen: the delay pattern

MusicGen (Copet et al., 2023) generates those four streams with one transformer. Write qt,mq_{t,m} for the code of codebook mm at frame tt. How does one model predict NqN_q parallel streams?

The exact answer is to flatten them into one sequence, frame by frame and codebook by codebook within a frame. The chain rule of Autoregressive models then holds exactly, but the sequence has NqTN_q T steps: 6000 for 30 seconds. The cheap answer predicts a whole frame in one step, which assumes

p(qt,1,…,qt,Nq∣q<t)≈∏m=1Nqp(qt,m∣q<t).p\big(q_{t,1}, \dots, q_{t,N_q} \mid q_{<t}\big) \approx \prod_{m=1}^{N_q} p\big(q_{t,m} \mid q_{<t}\big).

That is exact only if the codes of a frame are independent given the past. In RVQ they are not: stage mm encodes what the stages before it missed.

A toy shows the cost. Take two codebooks of two entries, and a frame whose codes, given the past, are (1,1)(1, 1) or (2,2)(2, 2) with probability 0.5 each: stage 2 corrects in the direction stage 1 chose. Each code alone is (0.5,0.5)(0.5, 0.5). A one-step prediction samples from the product of these, which puts 0.25 on each of the four pairs, so half the frames get a combination the codec never produced. In cross-entropy, the product pays 1+1=21 + 1 = 2 bits per frame and the true joint pays 1 bit. The gap of 1 bit is the total correlation of the codes, and no training removes it: the factorized model cannot represent the dependence.

The delay pattern shifts codebook mm by m−1m - 1 steps, so code (t,m)(t, m) is predicted at step t+m−1t + m - 1. Each cell below holds the step that predicts that code, for four frames and four codebooks:

t=1t = 1 t=2t = 2 t=3t = 3 t=4t = 4
codebook 1 1 2 3 4
codebook 2 2 3 4 5
codebook 3 3 4 5 6
codebook 4 4 5 6 7

Each code now comes after the coarser codes of its own frame, which removes the within-frame gap, and a clip of TT frames takes T+Nq−1T + N_q - 1 steps. Codes predicted at the same step, such as (t,1)(t, 1) and (t−1,2)(t - 1, 2), are still treated as independent given the past, so a smaller gap remains.

Its cost was measured, not derived, with the Fréchet audio distance (FAD; Kilgour et al., 2018), the audio twin of FID, a score the evaluation topics cover; lower is better. On 30-second clips, flattening scored 0.86 with 6000 steps, delay 0.96 with about 1500, and the parallel pattern 2.58 with 1500. MusicGen uses the delay pattern.

The transformer and guidance on logits

At each step the transformer's input is the sum of NqN_q embeddings, one from each codebook's own table, with a special empty token where a codebook has no code at that step. Every layer has causal self-attention and cross-attention to the condition yy, a text description such as "90s rock song with a guitar riff" encoded by a frozen T5 text encoder. There are NqN_q output heads, one per codebook, each giving KK logits, and training minimizes the cross-entropy of every code.

Classifier-free guidance works on logits exactly as for Parti in Autoregressive transformers. The condition is dropped with probability 0.2 during training, so one network gives both ℓ(⋅∣y)\ell(\cdot \mid y) and ℓ(⋅∣∅)\ell(\cdot \mid \varnothing). At sampling, for every code,

ℓ~=(1+w) ℓ(⋅∣y)−w ℓ(⋅∣∅).\tilde\ell = (1 + w)\, \ell(\cdot \mid y) - w\, \ell(\cdot \mid \varnothing).

Logits are log-probabilities up to a constant, and the softmax removes constants, so the code is drawn from

p~(q)∝p(q∣y)1+w p(q∣∅)−w∝p(q∣∅) p(y∣q)1+w,\tilde p(q) \propto p(q \mid y)^{1 + w}\, p(q \mid \varnothing)^{-w} \propto p(q \mid \varnothing)\, p(y \mid q)^{1 + w},

where the second form uses Bayes' rule, p(q∣y)∝p(y∣q) p(q∣∅)p(q \mid y) \propto p(y \mid q)\, p(q \mid \varnothing). The unconditional distribution is reweighted by an implicit classifier raised to the power 1+w1 + w. The tilt holds for each code given the codes before it; each step is normalized on its own, so over a whole clip the result is not exactly the tilted distribution of sequences. MusicGen uses a guidance scale of 3, which is w=2w = 2 in the convention of Latent diffusion, and samples from the 250 likeliest codes.

A worked example. Three codes with p(⋅∣∅)=(0.5,0.3,0.2)p(\cdot \mid \varnothing) = (0.5, 0.3, 0.2), p(⋅∣y)=(0.2,0.3,0.5)p(\cdot \mid y) = (0.2, 0.3, 0.5) and w=2w = 2. The weights p(⋅∣y)3 p(⋅∣∅)−2p(\cdot \mid y)^3\, p(\cdot \mid \varnothing)^{-2} are (0.032, 0.300, 3.125)(0.032,\ 0.300,\ 3.125), which normalize to (0.009, 0.087, 0.904)(0.009,\ 0.087,\ 0.904). The code the condition favours takes almost all the mass, and the entropy falls from 1.49 bits to 0.50: samples follow the text more closely and vary less. Each step costs two forward passes, run as one batch. A melody can be a condition too, as the strongest pitch class of a reference recording per frame, and a recording's opening seconds can be encoded and continued.

Both systems inherit a ceiling from stages they do not control. WaveGlow resynthesizing the true mel spectrograms of the Glow-TTS test set scored a MOS of 4.19 against 4.54 for the recordings, and MusicGen can sound no better than its 2.2 kbps codec. And to compare the patterns above, we needed scores computed from samples: listener ratings and FAD. That question is where the main line goes next. Inception Score builds the first such score for images, and the FID behind FAD follows it.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.