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 times per second as a waveform, a sequence of numbers in . Speech corpora such as LJ Speech, about 24 hours of one speaker, use 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 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 in hertz becomes, in mel,
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 triangular filters, equally spaced in mel, sums the magnitudes into bands, and the result goes on a log scale. One second of speech becomes 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 -th sample, , 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 takes a mel spectrogram of frames to a latent of the same shape, numbers per frame. The flow never sees the text. The text enters through the prior.
An encoder reads the phonemes and outputs a mean and standard deviations for each phoneme . An alignment says which phoneme each latent frame belongs to. A reader goes through a text in order and skips nothing, so must be monotonic, never going back, and surjective, giving every phoneme at least one frame.
Given , each latent frame is a Gaussian around the mean of its phoneme, and the change of variables gives the likelihood of the spectrogram:
This is the flow likelihood of the course with one change. The base distribution is not but one Gaussian per phoneme, stretched over that phoneme's frames by .
The alignment is unknown, so training alternates two steps. Given the parameters , find the best alignment . Given , take a gradient step on . Neither nor the log-determinant depends on , 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 convolutions and affine couplings (the extension Flow architectures builds them).
Monotonic alignment search
How many alignments are there? An alignment is fixed by the frames where a new phoneme starts, so we choose of the boundaries between neighbouring frames. That gives alignments: about for 50 phonemes and 430 frames, five seconds of speech. Trying them all is out of the question.
Monotonic alignment search (MAS) finds the best one by dynamic programming. Let be the largest log-likelihood of the first frames, aligned to the first phonemes with frame on phoneme . Monotonicity and surjectivity leave frame two options, phoneme or phoneme , so
The first row simply accumulates the log-densities of phoneme 1. The table has cells, each filled in constant time. The alignment is read backwards: the last frame goes to the last phoneme, and each earlier frame goes to the predecessor with the larger .
A worked example. Take three phonemes with one-dimensional means and , the value Glow-TTS fixes, and six frames . With every log-density is a constant minus half a squared distance, so the best alignment minimizes the summed squared distance , which follows the same recursion:
| phoneme 1, | 0.04 | 0.13 | 5.89 | 6.70 | 20.39 | 37.20 |
| phoneme 2, | — | 2.93 | 0.29 | 1.50 | 4.39 | 8.80 |
| phoneme 3, | — | — | 5.49 | 9.90 | 1.59 | 1.60 |
Backtracking from the corner picks the bold cells: with cost . Frame is nearer than , yet MAS keeps it on phoneme 2.
Durations and synthesis
At synthesis there is no spectrogram to align, so the durations are predicted. MAS supplies the targets: the duration of phoneme is the number of frames aligned to it, in the example. A small convolutional duration predictor reads the encoder output and is trained with a squared error on log durations:
The stop-gradient 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:
- the encoder gives , and a predicted log duration for every phoneme; each duration is its exponential, rounded up;
- every phoneme's statistics are repeated for as many frames as it lasts, which defines ;
- the latent is sampled frame by frame, with ;
- the flow runs backwards, , and a vocoder turns into a waveform.
The temperature 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 , 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 , 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 of entries each. For a latent frame :
The decoder receives the sum of the chosen vectors, and the sum telescopes:
The quantization error is exactly the last residual. The code of a frame is its list of indices, and stage describes only what the earlier stages missed, so the codes go from coarse to fine. With 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: and three codebooks of four entries.
| stage | codebook | input | chosen | residual | squared error |
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 |
The reconstruction is , 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 entries. Eight stages of 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 codebooks of entries at frames per second spends, in bits per second,
The codec of MusicGen runs at 32 kHz with stride 640, so , and has four codebooks of 2048 entries: 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 for the code of codebook at frame . How does one model predict 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 steps: 6000 for 30 seconds. The cheap answer predicts a whole frame in one step, which assumes
That is exact only if the codes of a frame are independent given the past. In RVQ they are not: stage 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 or with probability 0.5 each: stage 2 corrects in the direction stage 1 chose. Each code alone is . 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 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 by steps, so code is predicted at step . Each cell below holds the step that predicts that code, for four frames and four codebooks:
| 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 frames takes steps. Codes predicted at the same step, such as and , 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 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 , a text description such as "90s rock song with a guitar riff" encoded by a frozen T5 text encoder. There are output heads, one per codebook, each giving 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 and . At sampling, for every code,
Logits are log-probabilities up to a constant, and the softmax removes constants, so the code is drawn from
where the second form uses Bayes' rule, . The unconditional distribution is reweighted by an implicit classifier raised to the power . 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 in the convention of Latent diffusion, and samples from the 250 likeliest codes.
A worked example. Three codes with , and . The weights are , which normalize to . 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.
Answers are saved on the server and tied to this browser until you sign in.