Simple Algorithm
Artificial Intelligence · Deep Layer · 24 min

Audio & Music Generation

Tokenizing sound and generating it.

A three-minute stereo song at CD quality is about 16 million numbers, with structure at every scale, from the shape of a single waveform cycle to a chorus that returns two minutes later. Music generators cope by choosing a representation (notes or sound), compressing sound into token hierarchies, and generating with transformers or diffusion. This lesson works through the sequence-length arithmetic behind those choices, the exactness and cost of codebook interleaving, how such systems are evaluated, and the unresolved questions about rights and creative work.

What you’ll learn

  • Contrast symbolic and audio music generation by representation, sequence length, and what each can and cannot control.
  • Derive the memory saving of relative attention's skewing trick, and prove the exactness and step counts of codebook interleaving patterns.
  • Explain semantic-then-acoustic token hierarchies, latent diffusion for audio, and conditioning on text, melody and timing.
  • Evaluate audio generators critically, and present the main positions on training data and creative work.

Notes or sound?

Symbolic generation produces notes. A performance can be written as a sequence of events: in the vocabulary of Oore et al. (2018), 128 note-on and 128 note-off events (one per MIDI pitch), 100 time shifts from 10 ms to 1 s, and 32 velocity levels, 388 tokens in all. A model generates the event stream, and a synthesizer or a human performer renders it. Audio generation produces the sound itself, timbre, voice, production and room included, but at a cost: 44,100 samples per second per channel, so 44,100×2×180≈1.6×10744{,}100\times2\times180\approx1.6\times10^7 numbers for a three-minute stereo track.

PropertySymbolic (MIDI-like events)Audio (waveform or codec tokens)
Sequence lengthtens of events per second44,100 samples per second per channel, or tens to hundreds of codec tokens per second
Capturespitch, timing, dynamics, structuretimbre, voice, performance nuance, production
Control and editingdirect: change a noteindirect: prompts, conditioning, inpainting
Datascarce, mostly piano and scoresabundant recordings, with rights questions

The Music Transformer (Huang et al., 2019) generated minute-long piano performances with coherent motifs by giving attention a sense of relative position, since in music a repeat a bar later matters more than an absolute time stamp. The obstacle was memory.

DerivationRelative attention in O(LD) memory: the skewing trick
  1. logitij=qi⋅kj+qi⋅ej−iD,naive memory O(L2D)\text{logit}_{ij}=\frac{\mathbf q_i\cdot\mathbf k_j+\mathbf q_i\cdot\mathbf e_{j-i}}{\sqrt D},\qquad \text{naive memory }\order{L^2D}

    Relative attention adds a term that depends on the offset j−ij-i, with learned embeddings er\mathbf e_r for r=−(L−1),…,0r=-(L-1),\dots,0 (causal). Gathering ej−i\mathbf e_{j-i} for every query–key pair builds an L×L×DL\times L\times D tensor per head (Shaw, Uszkoreit & Vaswani, 2018):

  2. Sijrel=qi⋅ej−i=Mi,  j−i+L−1S^{\text{rel}}_{ij}=\mathbf q_i\cdot\mathbf e_{j-i}=M_{i,\;j-i+L-1}

    Instead compute M=QE⊤M=QE^\top, an L×LL\times L matrix whose column mm (0-based) holds offset m−(L−1)m-(L-1). The wanted entry needs a row-dependent shift:

  3. extra memory: E (L×D)  plus the L×L logits attention already stores=O(LD)\text{extra memory: }E\ (L\times D)\ \text{ plus the }L\times L\text{ logits attention already stores}=\order{LD}

    Pad one column on the left (L×(L+1)L\times(L+1)), reshape row-major to (L+1)×L(L+1)\times L, and drop the first row. Entry (i,c)(i,c) of the padded array and entry (i,j)(i,j) of the result occupy the same flat position when i(L+1)+c=(i+1)L+ji(L+1)+c=(i+1)L+j, that is c=L+j−ic=L+j-i, padded column cc being MM's column c−1=j−i+L−1c-1=j-i+L-1. That is exactly SijrelS^{\text{rel}}_{ij} for j≤ij\le i; the entries above the diagonal are garbage, removed by the causal mask anyway.

Audio models face sequences thousands of times longer. Jukebox (Dhariwal et al., 2020) compressed 44.1 kHz audio with a three-level VQ-VAE (temporal downsampling by 8, 32 and 128; Variational Autoencoders & the ELBO), modeled the coarsest tokens with a transformer conditioned on artist, genre and lyrics, and upsampled level by level. It produced songs with singing, but sampling was very slow and long-range structure was weak. The systems that followed kept the idea of generating compressed tokens and changed how the tokens are made and ordered.

Token hierarchies and interleaving

AudioLM (Borsos et al., 2023) separates two kinds of tokens. Semantic tokens, kk-means clusters of a self-supervised speech model's activations at 25 per second, capture content and long-term structure; acoustic tokens, the residual-vector-quantized codes of a SoundStream codec (Speech Synthesis), capture timbre and recording detail. Three transformer stages generate semantic tokens, then coarse acoustic tokens (the first quantizers), then fine ones. MusicLM (Agostinelli et al., 2023) added text conditioning through MuLan, a joint music–text embedding.

MusicGen (Copet et al., 2023) uses one transformer over the tokens of a 32 kHz EnCodec with 4 codebooks at 50 frames per second, with a T5 text encoder for prompts and optional melody conditioning. With KK codebooks per frame, how should the T×KT\times K tokens be ordered for generation?

DerivationProof
  1. p(ca,cb∣past) ⟶ p(ca∣past) p(cb∣past)p\big(c_a,c_b\mid\text{past}\big)\ \longrightarrow\ p\big(c_a\mid\text{past}\big)\,p\big(c_b\mid\text{past}\big)

    With one token per step, the chain rule gives the joint distribution exactly in that order. If a step holds several tokens, predicting them in parallel from the same context replaces their joint conditional by the product of marginals, which is exact only under conditional independence:

  2. step(ct,j)=t+j−1<t+k−1=step(ct,k)(j<k),#steps=T+K−1\text{step}(c_{t,j})=t+j-1<t+k-1=\text{step}(c_{t,k})\quad(j<k),\qquad\#\text{steps}=T+K-1

    The delay pattern emits ct,kc_{t,k} at step s=t+k−1s=t+k-1. A coarser code of the same frame, ct,jc_{t,j} with j<kj<k, is emitted at step t+j−1<t+k−1t+j-1<t+k-1, so it is always in context. The last token, cT,Kc_{T,K}, is emitted at step T+K−1T+K-1:

  3. ct−1,K∈context(ct,k)  ⟺  t+K−2<t+k−1  ⟺  k=Kc_{t-1,K}\in\text{context}(c_{t,k})\iff t+K-2<t+k-1\iff k=K

    Tokens sharing a step are cs−k+1,kc_{s-k+1,k} for different kk: different frames and different codebooks, never two codes of one frame. ■\blacksquare Residual quantization makes the coarse-to-fine dependence within a frame strong, since codebook kk encodes what codebooks 1,…,k−11,\dots,k-1 missed, so delay keeps the dependence that parallel discards. What delay gives up instead: ct,kc_{t,k} sees the finest code of the previous frame only when k=Kk=K.

Predict before you look

A MusicGen-style model generates a 30-second clip with 4 codebooks at 50 frames per second. How many sequential steps does the exact flattened pattern need? (The delay pattern needs 1500+3=15031500+3=1503.)

Show the answer

6000

T=30×50=1500T=30\times50=1500 frames and K=4K=4, so flattening takes TK=6000TK=6000 steps, four times as many as delay's T+K−1=1503T+K-1=1503, with attention over sequences four times longer as well. Copet et al. found that delay came close to flattening's quality at a fraction of its cost.

Diffusion and conditioning

Latent diffusion carries over to audio. AudioLDM (Liu et al., 2023) runs diffusion in the latent space of a VAE trained on mel spectrograms and recovers the waveform with a vocoder. Stable Audio (Evans et al., 2024) diffuses in the latent space of a waveform autoencoder and conditions on text and on timing, the clip's start time and total duration, so one model can produce outputs of different lengths. Classifier-free guidance (Diffusion Models) trades diversity for prompt adherence here as it does for images, and diffusion also serves as a vocoder (DiffWave, WaveGrad).

Text conditioning needs music paired with descriptions, which is scarce. Joint embeddings get around that. CLAP models (contrastive language–audio pretraining; Elizalde et al., 2023; Wu et al., 2023) train audio and text encoders contrastively, as CLIP does for images (Contrastive Vision–Language Models). MusicLM trains on audio alone, conditioned on the MuLan embedding of each training clip itself, and at inference substitutes the MuLan embedding of the text prompt, which lives in the same space; AudioLDM does the same with CLAP.

Check your understanding

MusicLM is trained without text captions, yet it accepts text prompts at inference. What makes this possible?

  1. A speech recognizer transcribes the lyrics of every training clip, and these serve as captions
  2. The prompt is converted into MIDI notes, which the model was trained on
  3. Training conditions on each clip's embedding in a joint music–text space, and at inference the prompt's text embedding, which lies in the same space, takes its place
  4. The model is fine-tuned on each prompt at inference time
Show the answer

C. Training conditions on each clip's embedding in a joint music–text space, and at inference the prompt's text embedding, which lies in the same space, takes its place

MuLan maps music and text into one embedding space, trained contrastively on music paired with text. The generator learns to follow music embeddings, which need no captions; because matching text lands nearby, a text embedding can stand in for a music embedding at inference. The approximation is only as good as the joint space's alignment.

Other controls target what musicians care about. Conditioning on a chromagram, the energy in each of the 12 pitch classes per frame, which discards octave and timbre, lets a hummed or whistled tune steer MusicGen's melody. Continuation and inpainting extend or repair existing audio.

As of the mid-2020s, commercial services such as Suno and Udio generate complete songs with vocals and lyrics from text prompts. Their architectures and training data are largely undisclosed, so claims about how they work are hard to verify. In June 2024, major record labels sued both companies for copyright infringement over the recordings used in training.

Evaluation, rights and open problems

The Fréchet Audio Distance (FAD; Kilgour et al., 2019) applies FID's formula to audio embeddings, originally from the VGGish audio classifier. It inherits FID's caveats (Generative Models): bias at small sample sizes, a Gaussian summary, and dependence on the embedding model, which can change the ranking of systems. It also summarizes windows of a few seconds, so it barely sees long-range form.

Other automatic measures cover other aspects: a CLAP score (cosine similarity between the text prompt's embedding and the generated audio's) for prompt adherence, and the KL divergence between a pretrained audio tagger's label distributions on reference and generated clips. Listening tests, with MUSHRA-style ratings or pairwise preferences, remain the reference, but they are expensive and depend on the listeners' backgrounds and musical culture. Memorization needs its own checks: the MusicLM paper, for example, reported how often generated token sequences matched training data.

Key takeaways

  • Symbolic generation (event vocabularies such as the 388-token performance encoding) controls notes but not sound. Audio generation captures timbre and performance but faces about 16 million samples per stereo song, hence compressed tokens.
  • Relative attention with the skewing trick needs O(LD)\order{LD} extra memory instead of O(L2D)\order{L^2D}, which made minute-long symbolic music feasible for the Music Transformer.
  • Audio is generated as token hierarchies: semantic, then acoustic tokens, or residual codebooks. Flattening is exact in TKTK steps; parallel takes TT steps but assumes within-frame independence; delay takes T+K−1T+K-1 steps and keeps each frame's coarse-to-fine dependence.
  • Latent diffusion over audio autoencoders and joint text–audio embeddings (MuLan, CLAP) enable text-conditioned generation even from audio-only training; melody (chroma) and timing conditioning add control.
  • Evaluation is unsolved: FAD inherits FID's caveats and misses form, while CLAP scores, classifier KL and listening tests each measure only part. Training on copyrighted music is legally and ethically contested, and lawsuits, licensed datasets and transparency rules are shaping practice as of the mid-2020s.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which codebook interleaving pattern assumes that the KK codebook tokens of the same frame are conditionally independent given the past?

  1. Flattening
  2. Delay
  3. Parallel
  4. Semantic tokens first, then acoustic tokens
Show the answer

C. Parallel

The parallel pattern predicts ct,1,…,ct,Kc_{t,1},\dots,c_{t,K} in one step from the same context, replacing their joint conditional by a product. Residual codebooks depend strongly on one another (each encodes what the coarser ones missed), so this assumption costs quality.

Question 2

For sequence length LL and head dimension DD, what does the skewing trick do to the extra memory of relative attention?

  1. It reduces it from O(L2D)\order{L^2D} to O(LD)\order{LD}
  2. It reduces it from O(L2)\order{L^2} to O(L)\order{L}
  3. It reduces it from O(LD)\order{LD} to O(D)\order{D}
  4. It leaves the memory unchanged but halves the computation
Show the answer

A. It reduces it from O(L2D)\order{L^2D} to O(LD)\order{LD}

The naive method gathers a DD-dimensional embedding for each of the L2L^2 query–key pairs. Skewing computes QE⊤QE^\top, an L×LL\times L matrix, and realigns it with a pad, a reshape and a slice, so only EE (L×DL\times D) and logits the size attention already needs are stored.

Question 3

In the delay pattern, which tokens are always in the context when ct,kc_{t,k} is generated?

  1. All KK codes of the previous frame, ct−1,1,…,ct−1,Kc_{t-1,1},\dots,c_{t-1,K}
  2. The finer codes of its own frame, ct,k+1,…,ct,Kc_{t,k+1},\dots,c_{t,K}
  3. The coarse code of the next frame, ct+1,1c_{t+1,1}
  4. The coarser codes of its own frame, ct,1,…,ct,k−1c_{t,1},\dots,c_{t,k-1}
Show the answer

D. The coarser codes of its own frame, ct,1,…,ct,k−1c_{t,1},\dots,c_{t,k-1}

ct,jc_{t,j} is emitted at step t+j−1t+j-1, earlier than ct,kc_{t,k}'s step t+k−1t+k-1 whenever j<kj<k. This keeps the strong coarse-to-fine dependence of residual codes within each frame.

Question 4

Two music generators are compared by FAD on VGGish embeddings. Which is a valid limitation of that comparison?

  1. FAD requires a human-written reference recording for every generated clip
  2. FAD measures how well each output follows its text prompt
  3. FAD is unbiased at any sample size
  4. The scores, and even the ranking, can change with the embedding model, and windowed embeddings say little about long-range form
Show the answer

D. The scores, and even the ranking, can change with the embedding model, and windowed embeddings say little about long-range form

FAD compares Gaussian summaries of two embedding distributions, so the embedding defines what counts as similar, and features of a few seconds of audio cannot reflect structure over minutes. Prompt adherence needs a separate measure, such as a CLAP score.

Further reading

  • C.-Z. A. Huang, A. Vaswani, J. Uszkoreit, N. Shazeer, I. Simon, C. Hawthorne, A. M. Dai, M. D. Hoffman, M. Dinculescu & D. Eck, "Music Transformer: Generating music with long-term structure," ICLR (2019).
  • P. Dhariwal, H. Jun, C. Payne, J. W. Kim, A. Radford & I. Sutskever, "Jukebox: A generative model for music," arXiv:2005.00341 (2020).
  • Z. Borsos, R. Marinier, D. Vincent, E. Kharitonov, O. Pietquin, M. Sharifi, D. Roblek, O. Teboul, D. Grangier, M. Tagliasacchi & N. Zeghidour, "AudioLM: A language modeling approach to audio generation," IEEE/ACM Transactions on Audio, Speech, and Language Processing (2023).
  • J. Copet, F. Kreuk, I. Gat, T. Remez, D. Kant, G. Synnaeve, Y. Adi & A. Défossez, "Simple and controllable music generation," NeurIPS (2023).
  • J.-P. Briot, G. Hadjeres & F.-D. Pachet, Deep Learning Techniques for Music Generation (Springer, 2020).