Course contents 34 / 34

34 / 34 · Audio Generation

Audio generation: text-to-speech and music

The course's models applied to sound: mel spectrograms and vocoders, Glow-TTS as a flow with a text-conditioned prior, neural codecs that turn a waveform into a few token streams, and MusicGen.

On this page 9

One second of mono audio sampled at 22,050 Hz contains 22,050 sample values. Under standard ancestral sampling, a model that generates it one number at a time, as WaveNet does, runs its network 22,050 times for that second; a three-minute song at 32 kHz is almost six million numbers.

How do we make sound short enough for the models of the course? Speech systems keep a continuous summary, the mel spectrogram, and Glow-TTS generates it with a normalizing flow whose prior is set by the text. Music systems compress the waveform into a few streams of discrete codes, as VQGAN compressed images in the previous note, and MusicGen generates the codes with one transformer.

Sound as a signal#

A microphone converts pressure variations into an electrical signal. Sampling it fsf_s times per second gives a waveform; normalized digital audio commonly represents its samples in [−1,1][-1,1]. By the Nyquist–Shannon sampling theorem, a signal with no frequency at or above fs/2f_s / 2 is determined by its complete infinite grid of exact samples; finite clips and quantized values introduce further limits. Higher frequencies fold onto lower ones, as the StyleGAN3 section derives. LJ Speech, the single-speaker corpus used in the cited TTS experiments, has about 24 hours of 16-bit audio at 22,050 Hz (Ito and Johnson, 2017).

The spectrogram says which frequencies are present 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 a window of 1024 samples (46.4 ms) and a hop of 256 samples (11.6 ms), the frame rate is 22,050/256≈86.1322{,}050 / 256 \approx 86.13 per second. A finite clip has an integer number of windows: with no padding, 22,050 samples give 1+⌊(22,050−1024)/256⌋=831+\lfloor(22{,}050-1024)/256\rfloor=83 windows. Padding changes this count.

The mel spectrogram compresses the frequency axis the way hearing does. Our pitch resolution is fine at low frequencies and coarse at high ones, and the mel scale follows it:

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

which maps 1000 Hz to approximately 1000 mel and the Nyquist frequency of 11,025 Hz to 3176 mel. A bank of FF triangular filters, equally spaced in mel, aggregates spectral magnitudes or powers into bands, depending on the preprocessing convention; a floor precedes the logarithm. With F=80F=80 bands, the long-run rate is 80×86.13≈689180 \times 86.13 \approx 6891 values per second, about 3.2 times fewer than waveform samples. This counts values, not compressed bits, and is specific to this configuration.

The price is the phase. Magnitudes say how much of each frequency is present and nothing about how the waves line up, so a mel spectrogram does not determine its waveform, and a vocoder must invent a plausible one. The classical Griffin–Lim algorithm estimates STFT phase iteratively and can introduce audible artifacts; neural vocoders learn the inversion from data.

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”), and grapheme-to-phoneme conversion maps letters to phonemes. An acoustic model maps the phonemes to a mel spectrogram, and a vocoder maps that to a waveform.

The acoustic model faces 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 decodes frames one at a time with attention that selects the input text token (Shen et al., 2018); when the attention slips, it skips or repeats words (Kim et al., 2020). FastSpeech generates all frames in parallel, but takes its durations from an autoregressive teacher’s attention (Ren et al., 2019).

Vocoders cover the families of the course. WaveNet is autoregressive over samples. WaveGlow is a normalizing flow from noise to the waveform, conditioned on the mel spectrogram (Prenger, Valle and Catanzaro, 2019). HiFi-GAN groups the waveform into pp phase columns for each p∈{2,3,5,7,11}p \in \{2,3,5,7,11\}; convolutions within each column inspect samples separated by that period, while retaining all sample positions (Kong, Kim and Bae, 2020). DiffWave is the DDPM of the course on the waveform, its noise predictor conditioned on the upsampled mel spectrogram (Kong et al., 2021).

The pipeline can also be one model: VITS is a conditional VAE with a phoneme-conditioned flow prior and a GAN decoder that outputs the waveform (Kim, Kong and Son, 2021). A speaker is one more condition, an embedding per speaker ID or one computed from a recording; YourTTS, built on VITS, clones an unseen voice from a short clip (Casanova et al., 2022).

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

Glow-TTS (Kim et al., 2020) is a parallel acoustic model that finds its own alignment, joining a normalizing flow with a dynamic-programming search.

The likelihood#

The decoder fdec:z↦xf_{\text{dec}}: z \mapsto x is an invertible flow from a latent sequence z=(z1,…,zTmel)z = (z_1, \dots, z_{T_{\text{mel}}}) to the mel spectrogram xx, both with TmelT_{\text{mel}} frames of F=80F = 80 numbers. The decoder 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. Glow-TTS imposes a monotonic, non-skipping reading model: AA is monotonic (never goes back) and surjective (every phoneme gets a frame). This is a modeling constraint, not a statement about every real utterance. Given AA, the prior is a product of Gaussians, and the change of variables gives the likelihood:

log⁡pZ(z∣c;A)=∑j=1Tmellog⁡N(zj; μA(j), diag⁡σA(j)2),log⁡pθ(x∣c;A)=log⁡pZ(fdec−1(x)∣c;A)+log⁡∣det⁡∂fdec−1(x)∂x∣.\begin{aligned} \log p_Z(z \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 p_\theta(x \mid c; A) &= \log p_Z\big(f_{\text{dec}}^{-1}(x) \mid c; A\big) \\ &\quad + \log \left\lvert \det \frac{\partial f_{\text{dec}}^{-1}(x)}{\partial x} \right\rvert . \end{aligned}

Training alternates two steps. Given the parameters θ\theta, find the best alignment A∗A^*; given A∗A^*, take a gradient step on θ\theta. The latent and the log-determinant do not depend on AA, so the first step only maximizes the prior term. The objective is the likelihood under the single best alignment, max⁡Alog⁡pθ(x∣c;A)\max_A \log p_\theta(x \mid c; A) (Viterbi training).

There are many alignments. Choosing one means choosing, among the Tmel−1T_{\text{mel}} - 1 boundaries between consecutive frames, the Ttext−1T_{\text{text}} - 1 boundaries at which a new phoneme starts, so there are (Tmel−1Ttext−1)\binom{T_{\text{mel}} - 1}{T_{\text{text}} - 1} of them: 9.3⋅10649.3 \cdot 10^{64} for 50 phonemes and 430 frames, five seconds of speech.

Monotonic alignment search (MAS) finds the best one by dynamic programming. Let Qi,jQ_{i,j} be the largest log-likelihood of the first jj frames, aligned to the first ii phonemes with frame jj on phoneme ii. Monotonicity and surjectivity leave frame j−1j - 1 two options, phoneme ii or phoneme i−1i - 1, so

Qi,j=max⁡(Qi−1, j−1, Qi, j−1)+ℓi,j,ℓi,j=log⁡N(zj; μi, diag⁡σi2),\begin{aligned} Q_{i,j} &= \max\big(Q_{i-1,\, j-1},\ Q_{i,\, j-1}\big) + \ell_{i,j}, \\ \ell_{i,j} &= \log \mathcal N\big(z_j;\ \mu_i,\ \operatorname{diag} \sigma_i^2\big), \end{aligned}

with Q1,j=ℓ1,1+⋯+ℓ1,jQ_{1,j}=\ell_{1,1}+\dots+\ell_{1,j} and impossible states j<ij<i set to −∞-\infty. This requires Tmel≥TtextT_{\text{mel}}\ge T_{\text{text}}. The table has Ttext×TmelT_{\text{text}} \times T_{\text{mel}} cells. The alignment is read backwards from A∗(Tmel)=TtextA^*(T_{\text{mel}}) = T_{\text{text}}, at each earlier frame moving to the predecessor with the larger QQ.

Worked example. Take three phonemes with one-dimensional means μ=(0,2,4)\mu = (0, 2, 4) and σ=1\sigma = 1, the value the paper fixes in training, and six frames z=(−0.2, 0.3, 2.4, 0.9, 3.7, 4.1)z = (-0.2,\ 0.3,\ 2.4,\ 0.9,\ 3.7,\ 4.1). With σ=1\sigma = 1, ℓi,j=−12log⁡2π−12(zj−μi)2\ell_{i,j} = -\tfrac12 \log 2\pi - \tfrac12 (z_j - \mu_i)^2. Summing ℓ\ell over the first jj frames gives Qi,j=−j2log⁡2π−12Ci,jQ_{i,j} = -\tfrac j2 \log 2\pi - \tfrac12 C_{i,j}, where Ci,jC_{i,j} is the summed squared distance. Every alignment of jj frames has the same constant, so maximizing QQ means minimizing CC, which follows the same recursion:

Ci,j=min⁡(Ci−1,j−1, Ci,j−1)+(zj−μi)2.C_{i,j} = \min(C_{i-1,j-1},\ C_{i,j-1}) + (z_j - \mu_i)^2 .
z1=−0.2z_1 = -0.2z2=0.3z_2 = 0.3z3=2.4z_3 = 2.4z4=0.9z_4 = 0.9z5=3.7z_5 = 3.7z6=4.1z_6 = 4.1
phoneme 1, μ1=0\mu_1 = 00.040.135.896.7020.3937.20
phoneme 2, μ2=2\mu_2 = 2—2.930.291.504.398.80
phoneme 3, μ3=4\mu_3 = 4——5.499.901.591.60

Backtracking from the corner picks the bold cells: A∗=(1,1,2,2,3,3)A^* = (1, 1, 2, 2, 3, 3), cost 1.60, prior log-likelihood −3log⁡2π−0.80=−6.31-3 \log 2\pi - 0.80 = -6.31. Frame z4=0.9z_4 = 0.9 is nearer μ1\mu_1 than μ2\mu_2, and nearest-mean assignment, (1,1,2,1,3,3)(1, 1, 2, 1, 3, 3), costs only 1.20, but it returns from phoneme 2 to phoneme 1, which violates the chosen alignment constraint. The means and six frames are locally specified scalar teaching inputs, not speech measurements or the paper’s experiment.

Durations and sampling#

At inference there is no spectrogram to align, so the alignment is predicted. MAS supplies the targets: the duration of phoneme ii is the number of frames aligned to it, di=∣{j:A∗(j)=i}∣d_i = \lvert \{ j : A^*(j) = i \} \rvert, (2,2,2)(2, 2, 2) in the example. A small convolutional duration predictor on the encoder output hh 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 ,

where the stop-gradient sg\mathrm{sg} keeps this loss from changing the encoder, which the likelihood trains.

Synthesis is then one parallel pass. Exponentiating the predicted log durations and rounding up gives positive integer durations. These durations repeat each phoneme’s mean for as many frames as it lasts; the latent is 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), which is μA(j)+τ εj\mu_{A(j)} + \tau\, \varepsilon_j with the paper’s fixed σ=1\sigma = 1, and x=fdec(z)x = f_{\text{dec}}(z). The temperature τ\tau is the standard deviation used at sampling. New noise gives a new intonation, and scaling all durations changes the speaking rate.

The decoder is a Glow stack of ActNorm, invertible 1×11 \times 1 convolutions and affine couplings (flow architectures). On LJ Speech, with WaveGlow as the vocoder and τ=0.333\tau = 0.333, listeners gave Glow-TTS a mean opinion score of 4.01 against 3.88 for Tacotron 2 (how such scores are collected).

Neural audio codecs: sound as tokens#

Music needs the whole bandwidth, and a transformer wants discrete tokens. The image answer carries over: train an autoencoder with a discrete bottleneck on the waveform, then model its codes.

EnCodec#

EnCodec (Défossez et al., 2023) follows SoundStream (Zeghidour et al., 2022). Its encoder is a one-dimensional convolutional network with strides 2, 4, 5 and 8 followed by an LSTM. 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, and between them a residual vector quantizer turns each frame into KK codes.

The losses are VQGAN’s, adapted to sound: an L1L_1 distance on the waveform and distances between mel spectrograms at several resolutions, adversarial and feature-matching losses, and a commitment loss. A loss balancer rescales each loss’s gradient by its running norm, to target specified relative gradient norms at the waveform output. Moving averages and interactions between gradient directions mean this is not an exact fixed share of the final parameter update; the commitment loss is outside this balancer.

Residual vector quantization#

A VQ-VAE replaces each encoder vector by the nearest entry of one codebook. Residual vector quantization (RVQ) then quantizes what that leaves, again and again, with codebooks C1,…,CK\mathcal C_1, \dots, \mathcal C_K of MM entries each. For a frame zz,

r(0)=z,e(k)=arg⁡min⁡e∈Ck∥r(k−1)−e∥2,r(k)=r(k−1)−e(k),\begin{aligned} r^{(0)} &= z, \\ e^{(k)} &= \arg\min_{e \in \mathcal C_k} \big\lVert r^{(k-1)} - e \big\rVert^2, \\ r^{(k)} &= r^{(k-1)} - e^{(k)} , \end{aligned}

for k=1,…,Kk = 1, \dots, K. The decoder receives the sum of the chosen vectors, and the sum telescopes:

z^=∑k=1Ke(k)=∑k=1K(r(k−1)−r(k))=z−r(K).\begin{aligned} \hat z &= \sum_{k=1}^{K} e^{(k)} \\ &= \sum_{k=1}^{K} \big(r^{(k-1)} - r^{(k)}\big) \\ &= z - r^{(K)} . \end{aligned}

The quantization error is exactly the last residual. The code of the frame is its list of KK indices, and stage kk describes only what the earlier stages missed. With K=1K=1 the bottleneck has one VQ codebook. EnCodec uses a straight-through gradient for the encoder, exponential-moving-average codebook updates and a commitment penalty; this does not make every neural-codec training procedure identical to VQ-VAE.

Figure

Residual quantization: three codebooks of four vectors

Residual quantization: three codebooks of four vectorsThree panels. The first shows a cloud of 160 points and the four vectors of codebook 1; an arrow from the codebook vector nearest to z to z itself is the residual. The second and third show the residual clouds, magnified, with codebooks 2 and 3. Below, the sum of the chosen vectors (2.39, 0.76) against z = (2.67, 0.93), and error bars 1.40, 0.39, 0.14, 0.05 after 0, 1, 2 and 3 codebooks.±3.5stage 1: codebook 111234z = (2.67, 0.93) → code 2e⁽¹⁾ = (1.42, 1.25)‖r⁽¹⁾‖² = 1.66±2stage 2: codebook 221234r⁽¹⁾ = (1.25, −0.32) → code 1e⁽²⁾ = (0.56, −0.52)‖r⁽²⁾‖² = 0.51±1.5stage 3: codebook 331234r⁽²⁾ = (0.69, 0.21) → code 4e⁽³⁾ = (0.40, 0.03)‖r⁽³⁾‖² = 0.11ẑ = e⁽¹⁾ + e⁽²⁾ + e⁽³⁾ = (2.39, 0.76)z = (2.67, 0.93)3 codes × 2 bits = 6 bits4error per coordinate over the 160 points0 books1.401 book0.392 books0.143 books0.05Residual quantization: three codebooks of four vectorsThree panels. The first shows a cloud of 160 points and the four vectors of codebook 1; an arrow from the codebook vector nearest to z to z itself is the residual. The second and third show the residual clouds, magnified, with codebooks 2 and 3. Below, the sum of the chosen vectors (2.39, 0.76) against z = (2.67, 0.93), and error bars 1.40, 0.39, 0.14, 0.05 after 0, 1, 2 and 3 codebooks.±3.5codebook 111234→ code 2e⁽¹⁾ = (1.42, 1.25)‖r⁽¹⁾‖² = 1.66±2codebook 221234→ code 1e⁽²⁾ = (0.56, −0.52)‖r⁽²⁾‖² = 0.51±1.5codebook 331234→ code 4e⁽³⁾ = (0.40, 0.03)‖r⁽³⁾‖² = 0.114error01.4010.3920.1430.05ẑ = (2.39, 0.76)z = (2.67, 0.93)3 × 2 = 6 bits
Three four-entry codebooks fit residuals of 160 specified points. Green marks inputs, amber codebooks, blue residuals and red reconstruction. For z = (2.67, 0.93), codes (2, 1, 4) give ẑ = (2.39, 0.76). Panel scales differ; their exact limits are shown inside.

Worked example. The figure follows one vector of a toy cloud through three codebooks of four entries, each fitted by k-means to the residuals of the previous stages:

StageInputChosen entrySquared residual
1z=(2.67,0.93)z = (2.67, 0.93)entry 2, (1.42,1.25)(1.42, 1.25)1.66
2r(1)=(1.25,−0.32)r^{(1)} = (1.25, -0.32)entry 1, (0.56,−0.52)(0.56, -0.52)0.51
3r(2)=(0.69,0.21)r^{(2)} = (0.69, 0.21)entry 4, (0.40,0.03)(0.40, 0.03)0.11

The squared norm falls from 8.01 to 0.11, the code is (2,1,4)(2, 1, 4), six bits, and z^=(2.39,0.76)=z−r(3)\hat z = (2.39, 0.76) = z - r^{(3)}.

Why not one large codebook? Specify a separate fictional codec with 60 frames per second and five codebooks of 16 entries. It uses 5⋅4=205\cdot4=20 bits per frame, or 1200 bits per second. One unconstrained codebook for all 20-bit indices would contain 220=1,048,5762^{20}=1{,}048{,}576 vectors; the five residual books store 5⋅16=805\cdot16=80. The possible RVQ sums form at most MKM^K distinct vectors. Searching all those sums jointly cannot be worse on a given point than the greedy RVQ choice; a globally optimized unconstrained book is at least as expressive. Finite k-means training and unseen test data do not inherit a universal ordering. On a toy cloud, fitted on 2000 points and tested on 2000 others with variance 1.589 per coordinate:

Bits per pointRVQ: stages × entriesTest errorOne codebook: entriesTest error
21 × 40.46440.463
42 × 40.166160.143
63 × 40.067640.042

In this constructed run, RVQ has higher test error at the same bit count. For fixed entries per stage, its stored codebook size grows linearly with the number of stages rather than exponentially. These are newly executed local synthetic-data calculations, not measured audio quality. Its codes also go from coarse to fine, so with quantizer dropout, a random number of stages kept per training example, one model serves many bitrates.

How many bits#

With fixed-length indices, MM a power of two, KK codebooks and frf_r frames per second, the nominal code payload rate is

R=K⋅log⁡2M⋅fr bits per second.R = K \cdot \log_2 M \cdot f_r \ \text{bits per second}.
CodecFrames per secondKKMMBitrate
SoundStream, 24 kHz75810246 kbps
EnCodec, 24 kHz752 to 3210241.5 to 24 kbps
EnCodec in MusicGen, 32 kHz, stride 64050420482.2 kbps

Headers, framing and side information add overhead; entropy coding can reduce the average rate. These numbers do not by themselves measure perceptual fidelity.

For MusicGen’s codec R=4⋅11⋅50=2200R = 4 \cdot 11 \cdot 50 = 2200 bits per second, 233 times less than the 512,000512{,}000 of 16-bit samples at 32 kHz (Copet et al., 2023). One second becomes 200 codes, or 50 frames of four codes each.

MusicGen: one transformer over parallel streams#

MusicGen (Copet et al., 2023) generates the four code streams of that codec with one transformer decoder, conditioned on a text and optionally a melody. How can one model predict KK parallel streams?

Interleaving the codebooks#

Write qt,kq_{t,k} for the code of codebook kk at frame tt. The exact answer is to flatten the codes into one sequence, frame by frame and codebook by codebook within a frame: q1,1,…,q1,K,q2,1,…q_{1,1}, \dots, q_{1,K}, q_{2,1}, \dots. The chain rule then factorizes the joint distribution exactly, but the sequence has KTKT steps, 6000 for 30 seconds.

The cheap answer predicts several codes in one step from the same past. Predicting all KK codes of frame tt together models

p(qt,1,…,qt,K∣q<t)≈∏k=1Kp(qt,k∣q<t),p(q_{t,1}, \dots, q_{t,K} \mid q_{<t}) \approx \prod_{k=1}^{K} p(q_{t,k} \mid q_{<t}) ,

which is exact only if the codes of a frame are independent given the past. RVQ generally introduces dependence because stage kk encodes the previous residual; it does not establish conditional independence of these codes.

The paper calls each layout a pattern: sets P1,…,PSP_1, \dots, P_S partitioning the cells (t,k)(t, k), where step nn predicts all cells of PnP_n at once from those of earlier sets. Flattening has S=KTS = KT; the parallel pattern, a whole frame per step, S=TS = T; coarse first, all of codebook 1 and then the rest frame by frame, S=2TS = 2T for K≥2K\ge2. The delay pattern shifts codebook kk by k−1k - 1 steps,

Pn={(n−k+1, k): 1≤k≤K,1≤n−k+1≤T},\begin{aligned} P_n = \{(n - k + 1,\ k) :\ & 1 \le k \le K, \\ & 1 \le n - k + 1 \le T\}, \end{aligned}

where the second condition keeps the frame index inside the clip. The first cell, (1,1)(1, 1), is in P1P_1 and the last, (T,K)(T, K), in PT+K−1P_{T + K - 1}, so S=T+K−1S = T + K - 1.

For a separately specified five-frame, three-codebook fixture, let qt,k=(3(t−1)+2(k−1)) mod 7q_{t,k}=(3(t-1)+2(k-1))\bmod7. The four step counts are 15, 5, 10 and 7. The figure executes the delay schedule and shows the actual integer codes; it is not a reproduction of a paper figure or an audio-model output.

Figure

Reading a delayed schedule

Fifteen specified codes in seven generation stepsRows are generation steps 1 to 7; columns are three codebooks. Frame 3 codes, 6, 1 and 3, appear in different rows. Removing codebook-index-minus-one delays recovers every original code.stepbook 1book 2book 31t1: 0——2t2: 3t1: 2—3t3: 6t2: 5t1: 44t4: 2t3: 1t2: 05t5: 5t4: 4t3: 36—t5: 0t4: 67——t5: 2frame 3: first 6, then 1, then 3specified code values; no model was trained
Five frames of three codes take seven steps. Each cell gives its source frame and a code value computed by the stated formula. Highlighted codes of frame 3 occur at steps 3, 4 and 5: each later prediction can see the earlier ones. An empty position contains no audio frame.

In the delay pattern the code (t,k)(t, k) is predicted at step t+k−1t + k - 1, after the coarser codes of its own frame at steps t,…,t+k−2t, \dots, t + k - 2: the dependency RVQ creates, at almost the cost of the parallel pattern.

The trade-off is measured by the Fréchet audio distance (FAD), the FID of audio on embeddings of the VGGish classifier (Kilgour et al., 2018). On 30-second excerpts (Table 4), flattening scores 0.86 with 6000 steps, delay 0.96 with 1500 and parallel 2.58 with 1500; the reported mean overall-quality scores were close (79.69 and 79.71), while text-relevance means favored flattening. These are the authors’ benchmark results, not our run. The table reports 1500 steps; explicitly counting all boundary positions in the finite schedule defined here instead gives 1503 for T=1500,K=4T=1500,K=4. MusicGen uses delay.

The transformer and its objective#

To predict PnP_n, the shifted input contains the codes of Pn−1P_{n-1}, summed over the KK codebook embedding tables; missing codebooks contribute a special empty token. Set P0=∅P_0=\varnothing to start the sequence. During teacher forcing these are the known previous codes, never the current target codes. For text-only conditioning, each layer has causal self-attention, cross-attention to the conditioning CC, and a feed-forward block. KK linear heads, one per codebook, each give MM logits. Training minimizes the cross-entropy of every code given the steps before it:

L(θ)=−∑n=1S∑(t,k)∈Pnlog⁡pθ(qt,k∣qP<n, C),\mathcal L(\theta) = -\sum_{n=1}^{S} \sum_{(t,k) \in P_n} \log p_\theta\big(q_{t,k} \mid q_{P_{<n}},\ C\big) ,

where qP<nq_{P_{<n}} collects the codes of earlier sets. A locally chosen description such as “quiet marimba over a slow pulse” becomes CC through a frozen T5 text encoder (Raffel et al., 2020; MusicGen implementation documentation), one vector per token.

Classifier-free guidance on logits#

As in latent diffusion, the condition is dropped in training, here with probability 0.2, so one network learns both pθ(q∣C)p_\theta(q \mid C) and pθ(q∣∅)p_\theta(q \mid \varnothing). At sampling, for every code, the two sets of logits are extrapolated with a guidance scale ss:

ℓ~=ℓ∅+s (ℓC−ℓ∅).\tilde\ell = \ell_\varnothing + s\,(\ell_C - \ell_\varnothing) .

What distribution does this sample? Logits are log-probabilities up to a constant per distribution: ℓC(q)=log⁡pθ(q∣C)+a\ell_C(q) = \log p_\theta(q \mid C) + a and ℓ∅(q)=log⁡pθ(q∣∅)+b\ell_\varnothing(q) = \log p_\theta(q \mid \varnothing) + b. Substituting and collecting terms,

ℓ~(q)=(1−s)log⁡pθ(q∣∅)+slog⁡pθ(q∣C)+const,p~(q)∝pθ(q∣∅)1−s pθ(q∣C)s,\begin{aligned} \tilde\ell(q) &= (1 - s) \log p_\theta(q \mid \varnothing) \\ &\quad + s \log p_\theta(q \mid C) + \text{const}, \\ \tilde p(q) &\propto p_\theta(q \mid \varnothing)^{1-s}\, p_\theta(q \mid C)^{s} , \end{aligned}

since the softmax removes the constant. If the conditional and unconditional probabilities come from a compatible joint distribution, Bayes’ rule, pθ(q∣C)∝p(C∣q) pθ(q∣∅)p_\theta(q \mid C) \propto p(C \mid q)\, p_\theta(q \mid \varnothing), turns this into p~(q)∝pθ(q∣∅) p(C∣q)s\tilde p(q) \propto p_\theta(q \mid \varnothing)\, p(C \mid q)^{s}: the unconditional distribution reweighted by an implicit classifier raised to the power ss. Separately learned conditional and empty-condition predictions need not be Bayes-consistent; the probability-ratio formula above remains the algebraic identity.

The tilt holds for each code given the codes before it. Over a sequence each step is normalized on its own, by a sum that depends on the prefix, and in general the result differs from tilting the whole sequence.

Derivation: per-step tilts against the tilted sequence

Write the codes q1,…,qSq_1, \dots, q_S in sampling order. Step nn samples from wn/Znw_n / Z_n:

wn(q)=pθ(q∣∅,q<n)1−s⋅pθ(q∣C,q<n)s,p~(q1:S)=∏n=1Swn(qn)Zn(q<n).\begin{aligned} w_n(q) &= p_\theta(q \mid \varnothing, q_{<n})^{1-s} \\ &\quad \cdot p_\theta(q \mid C, q_{<n})^{s}, \\ \tilde p(q_{1:S}) &= \prod_{n=1}^{S} \frac{w_n(q_n)}{Z_n(q_{<n})} . \end{aligned}

Here Zn(q<n)=∑qwn(q)Z_n(q_{<n}) = \sum_q w_n(q). By the chain rule, ∏nwn(qn)\prod_n w_n(q_n) is the tilt of the whole sequence, pθ(q1:S∣∅)1−spθ(q1:S∣C)sp_\theta(q_{1:S} \mid \varnothing)^{1-s} p_\theta(q_{1:S} \mid C)^{s}. The sampled distribution is proportional to that tilt only when ∏nZn\prod_n Z_n is the same for every sequence, which in general it is not.

MusicGen uses s=3s = 3, then samples from the 250 most likely codes (top-kk).

Worked example. Take three codes with p(⋅∣∅)=(0.5,0.3,0.2)p(\cdot \mid \varnothing) = (0.5, 0.3, 0.2) and p(⋅∣C)=(0.2,0.3,0.5)p(\cdot \mid C) = (0.2, 0.3, 0.5), and s=3s = 3:

Codep(⋅∣∅)−2 p(⋅∣C)3p(\cdot \mid \varnothing)^{-2}\, p(\cdot \mid C)^{3}p~\tilde p
10.5−2⋅0.23=0.0320.5^{-2} \cdot 0.2^{3} = 0.0320.009
20.3−2⋅0.33=0.3000.3^{-2} \cdot 0.3^{3} = 0.3000.087
30.2−2⋅0.53=3.1250.2^{-2} \cdot 0.5^{3} = 3.1250.904

In this chosen three-code example, the largest conditional-to-unconditional ratio receives most mass and entropy falls from 1.49 bits to 0.50. Neither decreasing entropy for every pair of distributions nor improved semantic text matching follows from the formula alone. Each step costs two forward passes, run as one batch.

Melody and continuation#

Text gives a style, and a melody can come from a reference recording through its chromagram, the energy in each of the 12 pitch classes over time. With drums and bass removed, only the strongest pitch class per frame is kept: with the full chromagram the model learned to copy the reference instead of composing. The result is a prefix of the decoder input.

A recording can be a prefix too: its first seconds are encoded, laid out by the delay pattern and continued, as ImageGPT completes images, within the 30-second training crops (1500 frames).

Where it breaks#

The parallel pattern fails in a way we can compute by hand. 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 that stage 1 chose. Each marginal is (0.5,0.5)(0.5, 0.5). Predicting both codes in one step samples from the product of the marginals, which puts 0.25 on each of the four pairs, so half of the frames get a combination the codec never produced.

The loss of the factorization has a name. In the following calculation, logarithms are base 2 and the preceding context is held fixed. The expected cross-entropy of the product of marginals pkp_k on data from the joint splits into one term per codebook, each depending only on its own code, whose distribution is pkp_k:

Eq[−log⁡∏kpk(qk)]=∑kEqk∼pk[−log⁡pk(qk)]=∑kH(qt,k).\begin{aligned} &\mathbb E_{q}\Big[-\log \prod_{k} p_k(q_k)\Big] \\ &\quad = \sum_{k} \mathbb E_{q_k \sim p_k}\big[-\log p_k(q_k)\big] \\ &\quad = \sum_{k} H(q_{t,k}) . \end{aligned}

The best model of the joint pays its entropy, and the difference is

Δ=∑k=1KH(qt,k)−H(qt,1,…,qt,K)=1+1−1=1 bit per frame\begin{aligned} \Delta &= \sum_{k=1}^{K} H(q_{t,k}) - H(q_{t,1}, \dots, q_{t,K}) \\ &= 1 + 1 - 1 = 1 \ \text{bit per frame} \end{aligned}

in the toy, the total correlation of the codes. No amount of training removes it, because the factorized model cannot represent the dependence. The delay pattern predicts each code after the coarser codes of its own frame, which removes this within-frame term in the constructed example. Codes predicted at one step, such as (t,1)(t, 1) and (t−1,2)(t - 1, 2), are still treated as independent given the past, so other dependencies can still be lost. There is no general theorem that their gap is smaller for every data distribution. The reported FAD difference, 0.96 against 0.86, is an empirical comparison, not a measurement of that KL/entropy gap.

The other failures come from stages the generator does not control. WaveGlow resynthesizing the true mel spectrograms of the Glow-TTS test scored 4.19 against 4.54 for the recordings, an empirical reference for what the vocoder alone loses, not a proven cap. MusicGen’s 2.2 kbps codec plays the same role.

What you should remember#

  • With the stated 80-band configuration, a mel spectrogram gives about 6900 numbers per second; a vocoder supplies a plausible waveform and phase, not a unique inverse.
  • Glow-TTS: a flow to a Gaussian prior set by the text; MAS finds the best monotonic alignment in O(TtextTmel)O(T_{\text{text}} T_{\text{mel}}).
  • RVQ: each stage quantizes the residual; the error is the last residual; R=Klog⁡2MfrR = K \log_2 M f_r.
  • The delay pattern predicts code (t,k)(t, k) at step t+k−1t + k - 1: T+K−1T + K - 1 steps, coarse codes of a frame seen first.
  • Guidance on logits samples each code from p(⋅∣∅)1−sp(⋅∣C)sp(\cdot \mid \varnothing)^{1-s} p(\cdot \mid C)^s.

Notebook#

Run python3 scripts/notes/generative-practice.py audio-generation. The standalone script synthesizes 0.25 seconds at 8,192 samples per second from two sinusoids at 227 and 463 Hz with amplitudes 0.53 and 0.19. It uses no recordings, speech corpus, pretrained voice or music weights.

  • Quantize each sample with four fixed coarse values. Quantize the remaining residual with four smaller values and add the two reconstructions. The saved mean squared error decreases from 0.020684 to 0.001261. This illustrates residual refinement with scalar codebooks; it is not a learned neural audio codec or a perceptual-quality test.
  • Separately construct five frames of three integer codebook tokens. With zero-based codebook index k=0,1,2k=0,1,2, delay codebook kk by kk steps (equivalently, by k−1k-1 with the body’s one-based indexing). The schedule takes 7 steps, and undoing the offsets recovers all five frames exactly. Empty schedule positions carry no token; counting them as complete audio frames would overstate duration.
  • Inspect the generated schedule and compare the two quantization errors. These calculations exercise signal representation and delayed token layout. They do not generate speech or music and do not validate a text-conditioned audio model.

The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.

Code#

The worked examples: alignment search, RVQ against one codebook, the codec bitrate, guidance on one code, and two dependent codes predicted in parallel. NumPy only; the k-means errors can differ slightly across platforms.

import numpy as np

# 1. Monotonic alignment search on the worked example (sigma = 1, so costs are squared distances)
mu = np.array([0.0, 2.0, 4.0])
z = np.array([-0.2, 0.3, 2.4, 0.9, 3.7, 4.1])
I, J = len(mu), len(z)
C = np.full((I, J), np.inf)
C[0, 0] = (z[0] - mu[0]) ** 2
for j in range(1, J):
    for i in range(min(j + 1, I)):
        prev = C[i, j - 1] if i == 0 else min(C[i - 1, j - 1], C[i, j - 1])
        C[i, j] = prev + (z[j] - mu[i]) ** 2
A, i = [], I - 1                                  # backtrack from the last phoneme at the last frame
for j in range(J - 1, -1, -1):
    A.append(i + 1)
    if j > 0 and i > 0 and C[i - 1, j - 1] <= C[i, j - 1]:
        i -= 1
A = A[::-1]
print(np.round(C, 2))
print(A, round(C[-1, -1], 2), round(-J / 2 * np.log(2 * np.pi) - C[-1, -1] / 2, 2))
nearest = np.abs(z[:, None] - mu).argmin(1) + 1
print(nearest, round(((z - mu[nearest - 1]) ** 2).sum(), 2))
# [[ 0.04  0.13  5.89  6.7  20.39 37.2 ]
#  [  inf  2.93  0.29  1.5   4.39  8.8 ]
#  [  inf   inf  5.49  9.9   1.59  1.6 ]]
# [1, 1, 2, 2, 3, 3] 1.6 -6.31
# [1 1 2 1 3 3] 1.2

# 2. Residual VQ against one codebook with the same number of bits (toy 2-D cloud)
rng = np.random.default_rng(0)
def cloud(n):
    u, v = 1.6 * rng.standard_normal(n), 0.8 * rng.standard_normal(n)
    return np.stack([0.8 * u - 0.6 * v, 0.6 * u + 0.8 * v], 1)
train, test = cloud(2000), cloud(2000)
def kmeans(X, m, iters=200, restarts=5):
    best = None
    for r in range(restarts):
        cb = X[rng.choice(len(X), m, replace=False)]
        for _ in range(iters):
            a = ((X[:, None] - cb) ** 2).sum(-1).argmin(1)
            cb = np.array([X[a == k].mean(0) if (a == k).any() else cb[k] for k in range(m)])
        a = ((X[:, None] - cb) ** 2).sum(-1).argmin(1)
        err = ((X - cb[a]) ** 2).sum()
        if best is None or err < best[0]: best = (err, cb)
    return best[1]
quant = lambda X, cb: cb[((X[:, None] - cb) ** 2).sum(-1).argmin(1)]
mse = lambda X: (X ** 2).mean()                   # mean squared error per coordinate
print('test variance per coordinate', round(test.var(0).mean(), 3))
r_tr, r_te = train.copy(), test.copy()
for stages in (1, 2, 3):                          # 4 entries per stage: 2 bits each
    cb = kmeans(r_tr, 4)
    r_tr, r_te = r_tr - quant(r_tr, cb), r_te - quant(r_te, cb)
    one = kmeans(train, 4 ** stages)
    print(2 * stages, 'bits: RVQ', round(mse(r_te), 3), ' one codebook', round(mse(test - quant(test, one)), 3))
# test variance per coordinate 1.589
# 2 bits: RVQ 0.464  one codebook 0.463
# 4 bits: RVQ 0.166  one codebook 0.143
# 6 bits: RVQ 0.067  one codebook 0.042

# 3. Bitrate of MusicGen's codec
K, M, fr = 4, 2048, 50
R = K * np.log2(M) * fr
print(R, round(32000 * 16 / R))                   # 2200.0 233

# 4. Classifier-free guidance on one code
p0, pc, s = np.array([0.5, 0.3, 0.2]), np.array([0.2, 0.3, 0.5]), 3.0
w = p0 ** (1 - s) * pc ** s
pt = w / w.sum()
H = lambda p: -(p * np.log2(p)).sum()
print(np.round(w, 3), np.round(pt, 3), round(H(pc), 2), round(H(pt), 2))
# [0.032 0.3   3.125] [0.009 0.087 0.904] 1.49 0.5

# 5. Parallel prediction of two dependent codes: the joint against the product of its marginals
joint = np.array([[0.5, 0.0], [0.0, 0.5]])        # rows: code of codebook 1, columns: codebook 2
prod = np.outer(joint.sum(1), joint.sum(0))
Hj = -(joint[joint > 0] * np.log2(joint[joint > 0])).sum()
print(prod, round(prod[joint == 0].sum(), 2), round(H(joint.sum(1)) + H(joint.sum(0)) - Hj, 2))
# [[0.25 0.25]
#  [0.25 0.25]] 0.5 1.0

The course in one paragraph#

Every model of the course answers one question: how to fit pθ≈pdatap_\theta \approx p_{\text{data}} and sample from it when pdatap_{\text{data}} is known only through examples. The Foundations turn that into maximum likelihood, a KL divergence to minimize, and the six families differ in what part of the likelihood they can compute and what they pay for it:

FamilyWhat it computesWhat it pays
VAEa lower bound, through an encoderan inference gap; sample fidelity depends on the observation model and capacity
GANno likelihood, a discriminator insteada minimax optimization problem and possible coverage failures
Normalizing flowthe exact likelihoodinvertible layers of fixed width
Energy-based modelthe density up to its normalizing constantoften approximate normalization and iterative sampling
Diffusiona bound with a fixed encoder, a regression on noise or scoreusually many network evaluations, with faster approximate or distilled variants
Autoregressivethe exact likelihood, a product of conditionalssequential conditional draws in standard ancestral sampling

Evaluation comes before the GANs, because a model without a likelihood is judged by its samples: FID, precision and recall, human judgement.

The families then meet. Under the appropriate score and regularity assumptions, diffusion in continuous time has a probability-flow ODE with matching marginals. The largest systems stack two models: an autoencoder compresses the image or the sound into a short code, and diffusion or an autoregressive transformer generates the code. The audio models above follow that recipe.

References#