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 numbers for a three-minute stereo track.
| Property | Symbolic (MIDI-like events) | Audio (waveform or codec tokens) |
|---|---|---|
| Sequence length | tens of events per second | 44,100 samples per second per channel, or tens to hundreds of codec tokens per second |
| Captures | pitch, timing, dynamics, structure | timbre, voice, performance nuance, production |
| Control and editing | direct: change a note | indirect: prompts, conditioning, inpainting |
| Data | scarce, mostly piano and scores | abundant 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.
Relative attention adds a term that depends on the offset , with learned embeddings for (causal). Gathering for every query–key pair builds an tensor per head (Shaw, Uszkoreit & Vaswani, 2018):
Instead compute , an matrix whose column (0-based) holds offset . The wanted entry needs a row-dependent shift:
Pad one column on the left (), reshape row-major to , and drop the first row. Entry of the padded array and entry of the result occupy the same flat position when , that is , padded column being 's column . That is exactly for ; 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, -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 codebooks per frame, how should the tokens be ordered for generation?
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:
The delay pattern emits at step . A coarser code of the same frame, with , is emitted at step , so it is always in context. The last token, , is emitted at step :
Tokens sharing a step are for different : different frames and different codebooks, never two codes of one frame. Residual quantization makes the coarse-to-fine dependence within a frame strong, since codebook encodes what codebooks missed, so delay keeps the dependence that parallel discards. What delay gives up instead: sees the finest code of the previous frame only when .
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 .)
Show the answer
6000
frames and , so flattening takes steps, four times as many as delay's , 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.
MusicLM is trained without text captions, yet it accepts text prompts at inference. What makes this possible?
- A speech recognizer transcribes the lyrics of every training clip, and these serve as captions
- The prompt is converted into MIDI notes, which the model was trained on
- 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
- 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 extra memory instead of , 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 steps; parallel takes steps but assumes within-frame independence; delay takes 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.
Which codebook interleaving pattern assumes that the codebook tokens of the same frame are conditionally independent given the past?
- Flattening
- Delay
- Parallel
- Semantic tokens first, then acoustic tokens
Show the answer
C. Parallel
The parallel pattern predicts 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.
For sequence length and head dimension , what does the skewing trick do to the extra memory of relative attention?
- It reduces it from to
- It reduces it from to
- It reduces it from to
- It leaves the memory unchanged but halves the computation
Show the answer
A. It reduces it from to
The naive method gathers a -dimensional embedding for each of the query–key pairs. Skewing computes , an matrix, and realigns it with a pad, a reshape and a slice, so only () and logits the size attention already needs are stored.
In the delay pattern, which tokens are always in the context when is generated?
- All codes of the previous frame,
- The finer codes of its own frame,
- The coarse code of the next frame,
- The coarser codes of its own frame,
Show the answer
D. The coarser codes of its own frame,
is emitted at step , earlier than 's step whenever . This keeps the strong coarse-to-fine dependence of residual codes within each frame.
Two music generators are compared by FAD on VGGish embeddings. Which is a valid limitation of that comparison?
- FAD requires a human-written reference recording for every generated clip
- FAD measures how well each output follows its text prompt
- FAD is unbiased at any sample size
- 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).